]> matita.cs.unibo.it Git - helm.git/blob - matita/matita/matitaEngine.ml
Huge change!!!
[helm.git] / matita / matita / matitaEngine.ml
1 (* Copyright (C) 2005, HELM Team.
2  * 
3  * This file is part of HELM, an Hypertextual, Electronic
4  * Library of Mathematics, developed at the Computer Science
5  * Department, University of Bologna, Italy.
6  * 
7  * HELM is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  * 
12  * HELM is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with HELM; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://helm.cs.unibo.it/
24  *)
25
26 (* $Id$ *)
27
28 module G = GrafiteAst
29 open GrafiteTypes
30 open Printf
31
32 exception TryingToAdd of string Lazy.t
33 exception EnrichedWithStatus of exn * GrafiteTypes.status
34 exception AlreadyLoaded of string Lazy.t
35 exception FailureCompiling of string * exn
36
37 let debug = false ;;
38 let debug_print = if debug then prerr_endline else ignore ;;
39
40 let slash_n_RE = Pcre.regexp "\\n" ;;
41
42 let pp_ast_statement grafite_status stm =
43   let stm = GrafiteAstPp.pp_statement stm
44     ~map_unicode_to_tex:(Helm_registry.get_bool "matita.paste_unicode_as_tex")
45   in
46   let stm = Pcre.replace ~rex:slash_n_RE stm in
47   let stm =
48       if String.length stm > 50 then String.sub stm 0 50 ^ " ..."
49       else stm
50   in
51     HLog.debug ("Executing: ``" ^ stm ^ "''")
52 ;;
53
54 let clean_exit baseuri exn =
55   LibraryClean.clean_baseuris ~verbose:false [baseuri];
56   raise (FailureCompiling (baseuri,exn))
57 ;;
58
59 let pp_times fname rc big_bang big_bang_u big_bang_s = 
60   if not (Helm_registry.get_bool "matita.verbose") then
61     let { Unix.tms_utime = u ; Unix.tms_stime = s} = Unix.times () in
62     let r = Unix.gettimeofday () -. big_bang in
63     let u = u -. big_bang_u in
64     let s = s -. big_bang_s in
65     let extra = try Sys.getenv "BENCH_EXTRA_TEXT" with Not_found -> "" in
66     let rc,rcascii = 
67       if rc then "\e[0;32mOK\e[0m","Ok" else "\e[0;31mFAIL\e[0m","Fail" in
68     let times = 
69       let fmt t = 
70         let seconds = int_of_float t in
71         let cents = int_of_float ((t -. floor t) *. 100.0) in
72         let minutes = seconds / 60 in
73         let seconds = seconds mod 60 in
74         Printf.sprintf "%dm%02d.%02ds" minutes seconds cents
75       in
76       Printf.sprintf "%s %s %s" (fmt r) (fmt u) (fmt s)
77     in
78     let s = Printf.sprintf "%-4s %s %s" rc times extra in
79     print_endline s;
80     flush stdout;
81     HLog.message ("Compilation of "^Filename.basename fname^": "^rc)
82 ;;
83
84 let cut prefix s = 
85   let lenp = String.length prefix in
86   let lens = String.length s in
87   assert (lens > lenp);
88   assert (String.sub s 0 lenp = prefix);
89   String.sub s lenp (lens-lenp)
90 ;;
91
92 (*MATITA 1.0 assert false;; (* chiamare enrich_include_paths *)*)
93 let enrich_include_paths ~include_paths =
94  include_paths @ Helm_registry.get_list Helm_registry.string "matita.includes" 
95 ;;
96
97 let activate_extraction baseuri fname =
98   ()
99   (* MATITA 1.0
100  if Helm_registry.get_bool "matita.extract" then
101   let mangled_baseuri =
102    let baseuri = String.sub baseuri 5 (String.length baseuri - 5) in
103      let baseuri = Pcre.replace ~pat:"/" ~templ:"_" baseuri in
104       String.uncapitalize baseuri in
105   let f =
106     open_out
107      (Filename.dirname fname ^ "/" ^ mangled_baseuri ^ ".ml") in
108    LibrarySync.add_object_declaration_hook
109     (fun ~add_obj ~add_coercion _ obj ->
110       output_string f (CicExportation.ppobj baseuri obj);
111       flush f; []);
112       *)
113 ;;
114
115
116 let eval_macro_screenshot (status : GrafiteTypes.status) name =
117   assert false (* MATITA 1.0
118   let _,_,metasenv,subst,_ = status#obj in
119   let sequent = List.hd metasenv in
120   let mathml = 
121     ApplyTransformation.nmml_of_cic_sequent 
122       status metasenv subst sequent 
123   in
124   let domImpl = Gdome.domImplementation () in
125   ignore(domImpl#saveDocumentToFile 
126     ~name:(name^".xml") ~doc:mathml ());
127   ignore(Sys.command ("mathmlsvg --verbose=1 --font-size=20 --cut-filename=no " ^ 
128     Filename.quote (name^".xml")));
129   ignore(Sys.command ("convert " ^ 
130     Filename.quote (name^".svg") ^ " " ^ 
131     Filename.quote (name^".png")));
132   HLog.debug ("generated " ^ name ^ ".png");
133   status, `New []
134   *)
135 ;;
136
137 let eval_ast ~include_paths ?do_heavy_checks status (text,prefix_len,ast) =
138  let baseuri = status#baseuri in
139  let new_aliases,new_status =
140   GrafiteDisambiguate.eval_with_new_aliases status
141    (fun status ->
142      GrafiteEngine.eval_ast ~include_paths ?do_heavy_checks status
143       (text,prefix_len,ast)) in
144  let _,intermediate_states = 
145   List.fold_left
146    (fun (status,acc) (k,value) -> 
147      let v = GrafiteAst.description_of_alias value in
148      let b =
149       try
150        let NReference.Ref (uri,_) = NReference.reference_of_string v in
151         NUri.baseuri_of_uri uri = baseuri
152       with
153        NReference.IllFormedReference _ ->
154         false (* v is a description, not a URI *)
155      in
156       if b then 
157        status,acc
158       else
159        let status =
160         GrafiteDisambiguate.set_proof_aliases status ~implicit_aliases:false
161          GrafiteAst.WithPreferences [k,value]
162        in
163         status, (status ,Some (k,value))::acc
164    ) (status,[]) new_aliases (* WARNING: this must be the old status! *)
165  in
166   (new_status,None)::intermediate_states
167 ;;
168
169 let rec get_ast status ~include_paths strm = 
170   match GrafiteParser.parse_statement status strm with
171      (GrafiteAst.Executable
172        (_,GrafiteAst.NCommand (_,GrafiteAst.Include (_,_,mafilename)))) as cmd
173      ->
174       let root, buri, _, tgt = 
175         try Librarian.baseuri_of_script ~include_paths mafilename
176         with Librarian.NoRootFor _ -> 
177           HLog.error ("The included file '"^mafilename^"' has no root file,");
178           HLog.error "please create it.";
179           raise (Failure ("No root file for "^mafilename))
180       in
181        ignore (assert_ng ~include_paths ~root tgt);
182        cmd
183    | cmd -> cmd
184
185 and eval_from_stream ~include_paths ?do_heavy_checks status str cb =
186  let matita_debug = Helm_registry.get_bool "matita.debug" in
187  let rec loop status =
188   let stop,status = 
189    try
190      let cont =
191        try Some (get_ast status ~include_paths str)
192        with End_of_file -> None in
193      match cont with
194      | None -> true, status
195      | Some ast ->
196         cb status ast;
197         let new_statuses =
198           eval_ast ~include_paths ?do_heavy_checks status ("",0,ast) in
199         let status =
200          match new_statuses with
201             [s,None] -> s
202           | _::(_,Some (_,value))::_ ->
203                 raise (TryingToAdd (lazy (GrafiteAstPp.pp_alias value)))
204           | _ -> assert false
205         in
206          false, status
207    with exn when not matita_debug ->
208      raise (EnrichedWithStatus (exn, status))
209   in
210   if stop then status else loop status
211  in
212   loop status
213
214 and compile ~include_paths fname =
215   let matita_debug = Helm_registry.get_bool "matita.debug" in
216   let root,baseuri,fname,_tgt = 
217     Librarian.baseuri_of_script ~include_paths fname in
218   if Http_getter_storage.is_read_only baseuri then assert false;
219   activate_extraction baseuri fname ;
220   (* MATITA 1.0: debbo fare time_travel sulla ng_library? *)
221   let grafite_status = new GrafiteTypes.status baseuri in
222   let big_bang = Unix.gettimeofday () in
223   let { Unix.tms_utime = big_bang_u ; Unix.tms_stime = big_bang_s} = 
224     Unix.times () 
225   in
226   let time = Unix.time () in
227   try
228     (* cleanup of previously compiled objects *)
229     if (not (Http_getter_storage.is_empty ~local:true baseuri))
230       then begin
231       HLog.message ("baseuri " ^ baseuri ^ " is not empty");
232       HLog.message ("cleaning baseuri " ^ baseuri);
233       LibraryClean.clean_baseuris [baseuri];
234     end;
235     HLog.message ("compiling " ^ Filename.basename fname ^ " in " ^ baseuri);
236     if not (Helm_registry.get_bool "matita.verbose") then
237       (let cc = 
238         let rex = Str.regexp ".*opt$" in
239         if Str.string_match rex Sys.argv.(0) 0 then "matitac.opt"
240         else "matitac" 
241       in
242       let s = Printf.sprintf "%s %-35s " cc (cut (root^"/") fname) in
243       print_string s; flush stdout);
244     (* we dalay this error check until we print 'matitac file ' *)
245     assert (Http_getter_storage.is_empty ~local:true baseuri);
246     (* create dir for XML files *)
247     if not (Helm_registry.get_opt_default Helm_registry.bool "matita.nodisk"
248               ~default:false) 
249     then
250       HExtlib.mkdir 
251         (Filename.dirname 
252           (Http_getter.filename ~local:true ~writable:true (baseuri ^
253           "foo.con")));
254     let buf = Ulexing.from_utf8_channel (open_in fname) in
255     let print_cb =
256       if not (Helm_registry.get_bool "matita.verbose") then (fun _ _ -> ())
257       else pp_ast_statement
258     in
259     let grafite_status =
260      eval_from_stream ~include_paths grafite_status buf print_cb in
261     let elapsed = Unix.time () -. time in
262      (if Helm_registry.get_bool "matita.moo" then begin
263        GrafiteTypes.Serializer.serialize ~baseuri:(NUri.uri_of_string baseuri)
264         ~dependencies:grafite_status#dependencies grafite_status#dump
265      end;
266      let tm = Unix.gmtime elapsed in
267      let sec = string_of_int tm.Unix.tm_sec ^ "''" in
268      let min = 
269        if tm.Unix.tm_min > 0 then (string_of_int tm.Unix.tm_min^"' ") else "" 
270      in
271      let hou = 
272        if tm.Unix.tm_hour > 0 then (string_of_int tm.Unix.tm_hour^"h ") else ""
273      in
274      HLog.message 
275        (sprintf "execution of %s completed in %s." fname (hou^min^sec));
276      pp_times fname true big_bang big_bang_u big_bang_s
277 (* MATITA 1.0: debbo fare time_travel sulla ng_library?
278      LexiconSync.time_travel 
279        ~present:lexicon_status ~past:initial_lexicon_status;
280 *))
281   with 
282   (* all exceptions should be wrapped to allow lexicon-undo (LS.time_travel) *)
283   | exn when not matita_debug ->
284 (* MATITA 1.0: debbo fare time_travel sulla ng_library?
285        LexiconSync.time_travel ~present:lexicon ~past:initial_lexicon_status;
286  *       *)
287       pp_times fname false big_bang big_bang_u big_bang_s;
288       clean_exit baseuri exn
289
290 (* BIG BUG: if a file recursively includes itself, anything can happen,
291  * from divergence to inclusion of an old copy of itself *)
292 and assert_ng ~include_paths ~root mapath =
293  let root',baseuri,_,_ = Librarian.baseuri_of_script ~include_paths mapath in
294  assert (root=root');
295  let baseuri = NUri.uri_of_string baseuri in
296  let ngpath = NCicLibrary.ng_path_of_baseuri baseuri in
297  let ngtime =
298   try
299    Some (Unix.stat ngpath).Unix.st_mtime
300   with Unix.Unix_error (Unix.ENOENT, "stat", f) when f = ngpath -> None in
301  let matime =
302   try (Unix.stat mapath).Unix.st_mtime
303   with Unix.Unix_error (Unix.ENOENT, "stat", f) when f = mapath -> assert false
304  in
305  let to_be_compiled =
306   match ngtime with
307      Some ngtime ->
308       let preamble = GrafiteTypes.Serializer.dependencies_of baseuri in
309       let children_bad= List.exists (assert_ng ~include_paths ~root) preamble in
310        children_bad || matime > ngtime
311    | None -> true
312  in
313   if not to_be_compiled then false
314   else
315    (* MATITA 1.0: SHOULD TAKE THIS FROM THE STATUS *)
316    if List.mem baseuri (NCicLibrary.get_already_included ()) then
317      (* maybe recompiling it I would get the same... *)
318      raise (AlreadyLoaded (lazy mapath))
319    else
320     (compile ~include_paths mapath; true)