]> matita.cs.unibo.it Git - helm.git/blob - matita/matita/matitaEngine.ml
Some bugs fixed (and some still open) in recursive compilation of files:
[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 exception CircularDependency of string
37
38 let debug = false ;;
39 let debug_print = if debug then prerr_endline else ignore ;;
40
41 let slash_n_RE = Pcre.regexp "\\n" ;;
42
43 let pp_ast_statement grafite_status stm =
44   let stm = GrafiteAstPp.pp_statement stm
45     ~map_unicode_to_tex:(Helm_registry.get_bool "matita.paste_unicode_as_tex")
46   in
47   let stm = Pcre.replace ~rex:slash_n_RE stm in
48   let stm =
49       if String.length stm > 50 then String.sub stm 0 50 ^ " ..."
50       else stm
51   in
52     HLog.debug ("Executing: ``" ^ stm ^ "''")
53 ;;
54
55 let clean_exit baseuri exn =
56   LibraryClean.clean_baseuris ~verbose:false [baseuri];
57   raise (FailureCompiling (baseuri,exn))
58 ;;
59
60 let pp_times fname rc big_bang big_bang_u big_bang_s = 
61   if not (Helm_registry.get_bool "matita.verbose") then
62     let { Unix.tms_utime = u ; Unix.tms_stime = s} = Unix.times () in
63     let r = Unix.gettimeofday () -. big_bang in
64     let u = u -. big_bang_u in
65     let s = s -. big_bang_s in
66     let extra = try Sys.getenv "BENCH_EXTRA_TEXT" with Not_found -> "" in
67     let rc,rcascii = 
68       if rc then "\e[0;32mOK\e[0m","Ok" else "\e[0;31mFAIL\e[0m","Fail" in
69     let times = 
70       let fmt t = 
71         let seconds = int_of_float t in
72         let cents = int_of_float ((t -. floor t) *. 100.0) in
73         let minutes = seconds / 60 in
74         let seconds = seconds mod 60 in
75         Printf.sprintf "%dm%02d.%02ds" minutes seconds cents
76       in
77       Printf.sprintf "%s %s %s" (fmt r) (fmt u) (fmt s)
78     in
79     let s = Printf.sprintf "%-4s %s %s" rc times extra in
80     print_endline s;
81     flush stdout;
82     HLog.message ("Compilation of "^Filename.basename fname^": "^rc)
83 ;;
84
85 let cut prefix s = 
86   let lenp = String.length prefix in
87   let lens = String.length s in
88   assert (lens > lenp);
89   assert (String.sub s 0 lenp = prefix);
90   String.sub s lenp (lens-lenp)
91 ;;
92
93 let activate_extraction baseuri fname =
94   ()
95   (* MATITA 1.0
96  if Helm_registry.get_bool "matita.extract" then
97   let mangled_baseuri =
98    let baseuri = String.sub baseuri 5 (String.length baseuri - 5) in
99      let baseuri = Pcre.replace ~pat:"/" ~templ:"_" baseuri in
100       String.uncapitalize baseuri in
101   let f =
102     open_out
103      (Filename.dirname fname ^ "/" ^ mangled_baseuri ^ ".ml") in
104    LibrarySync.add_object_declaration_hook
105     (fun ~add_obj ~add_coercion _ obj ->
106       output_string f (CicExportation.ppobj baseuri obj);
107       flush f; []);
108       *)
109 ;;
110
111
112 let eval_macro_screenshot (status : GrafiteTypes.status) name =
113   assert false (* MATITA 1.0
114   let _,_,metasenv,subst,_ = status#obj in
115   let sequent = List.hd metasenv in
116   let mathml = 
117     ApplyTransformation.nmml_of_cic_sequent 
118       status metasenv subst sequent 
119   in
120   let domImpl = Gdome.domImplementation () in
121   ignore(domImpl#saveDocumentToFile 
122     ~name:(name^".xml") ~doc:mathml ());
123   ignore(Sys.command ("mathmlsvg --verbose=1 --font-size=20 --cut-filename=no " ^ 
124     Filename.quote (name^".xml")));
125   ignore(Sys.command ("convert " ^ 
126     Filename.quote (name^".svg") ^ " " ^ 
127     Filename.quote (name^".png")));
128   HLog.debug ("generated " ^ name ^ ".png");
129   status, `New []
130   *)
131 ;;
132
133 let eval_ast ~include_paths ?do_heavy_checks status (text,prefix_len,ast) =
134  let baseuri = status#baseuri in
135  let new_aliases,new_status =
136   GrafiteDisambiguate.eval_with_new_aliases status
137    (fun status ->
138      GrafiteEngine.eval_ast ~include_paths ?do_heavy_checks status
139       (text,prefix_len,ast)) in
140  let _,intermediate_states = 
141   List.fold_left
142    (fun (status,acc) (k,value) -> 
143      let v = GrafiteAst.description_of_alias value in
144      let b =
145       try
146        let NReference.Ref (uri,_) = NReference.reference_of_string v in
147         NUri.baseuri_of_uri uri = baseuri
148       with
149        NReference.IllFormedReference _ ->
150         false (* v is a description, not a URI *)
151      in
152       if b then 
153        status,acc
154       else
155        let status =
156         GrafiteDisambiguate.set_proof_aliases status ~implicit_aliases:false
157          GrafiteAst.WithPreferences [k,value]
158        in
159         status, (status ,Some (k,value))::acc
160    ) (status,[]) new_aliases (* WARNING: this must be the old status! *)
161  in
162   (new_status,None)::intermediate_states
163 ;;
164
165 let baseuri_of_script ~include_paths fname =
166  try Librarian.baseuri_of_script ~include_paths fname
167  with
168    Librarian.NoRootFor _ -> 
169     HLog.error ("The included file '"^fname^"' has no root file,");
170     HLog.error "please create it.";
171     raise (Failure ("No root file for "^fname))
172   | Librarian.FileNotFound _ -> 
173     raise (Failure ("File not found: "^fname))
174 ;;
175
176 let rec get_ast status ~compiling ~include_paths strm = 
177   match GrafiteParser.parse_statement status strm with
178      (GrafiteAst.Executable
179        (_,GrafiteAst.NCommand (_,GrafiteAst.Include (_,_,mafilename)))) as cmd
180      ->
181        ignore (assert_ng ~compiling ~include_paths mafilename);
182        cmd
183    | cmd -> cmd
184
185 and eval_from_stream ~compiling ~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 ~compiling ~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 ~compiling ~include_paths fname =
215   if List.mem fname compiling then raise (CircularDependency fname);
216   let compiling = fname::compiling in
217   let matita_debug = Helm_registry.get_bool "matita.debug" in
218   let root,baseuri,fname,_tgt = 
219     Librarian.baseuri_of_script ~include_paths fname in
220   if Http_getter_storage.is_read_only baseuri then assert false;
221   activate_extraction baseuri fname ;
222   (* MATITA 1.0: debbo fare time_travel sulla ng_library? *)
223   let grafite_status = new GrafiteTypes.status baseuri in
224   let big_bang = Unix.gettimeofday () in
225   let { Unix.tms_utime = big_bang_u ; Unix.tms_stime = big_bang_s} = 
226     Unix.times () 
227   in
228   let time = Unix.time () in
229   try
230     (* cleanup of previously compiled objects *)
231     if (not (Http_getter_storage.is_empty ~local:true baseuri))
232       then begin
233       HLog.message ("baseuri " ^ baseuri ^ " is not empty");
234       HLog.message ("cleaning baseuri " ^ baseuri);
235       LibraryClean.clean_baseuris [baseuri];
236     end;
237     HLog.message ("compiling " ^ Filename.basename fname ^ " in " ^ baseuri);
238     if not (Helm_registry.get_bool "matita.verbose") then
239       (let cc = 
240         let rex = Str.regexp ".*opt$" in
241         if Str.string_match rex Sys.argv.(0) 0 then "matitac.opt"
242         else "matitac" 
243       in
244       let s = Printf.sprintf "%s %-35s " cc (cut (root^"/") fname) in
245       print_string s; flush stdout);
246     (* we dalay this error check until we print 'matitac file ' *)
247     assert (Http_getter_storage.is_empty ~local:true baseuri);
248     (* create dir for XML files *)
249     if not (Helm_registry.get_opt_default Helm_registry.bool "matita.nodisk"
250               ~default:false) 
251     then
252       HExtlib.mkdir 
253         (Filename.dirname 
254           (Http_getter.filename ~local:true ~writable:true (baseuri ^
255           "foo.con")));
256     let buf =
257      GrafiteParser.parsable_statement grafite_status
258       (Ulexing.from_utf8_channel (open_in fname))
259     in
260     let print_cb =
261       if not (Helm_registry.get_bool "matita.verbose") then (fun _ _ -> ())
262       else pp_ast_statement
263     in
264     let grafite_status =
265      eval_from_stream ~compiling ~include_paths grafite_status buf print_cb in
266     let elapsed = Unix.time () -. time in
267      (if Helm_registry.get_bool "matita.moo" then begin
268        GrafiteTypes.Serializer.serialize ~baseuri:(NUri.uri_of_string baseuri)
269         ~dependencies:grafite_status#dependencies grafite_status#dump
270      end;
271      let tm = Unix.gmtime elapsed in
272      let sec = string_of_int tm.Unix.tm_sec ^ "''" in
273      let min = 
274        if tm.Unix.tm_min > 0 then (string_of_int tm.Unix.tm_min^"' ") else "" 
275      in
276      let hou = 
277        if tm.Unix.tm_hour > 0 then (string_of_int tm.Unix.tm_hour^"h ") else ""
278      in
279      HLog.message 
280        (sprintf "execution of %s completed in %s." fname (hou^min^sec));
281      pp_times fname true big_bang big_bang_u big_bang_s
282 (* MATITA 1.0: debbo fare time_travel sulla ng_library?
283      LexiconSync.time_travel 
284        ~present:lexicon_status ~past:initial_lexicon_status;
285 *))
286   with 
287   (* all exceptions should be wrapped to allow lexicon-undo (LS.time_travel) *)
288   | exn when not matita_debug ->
289 (* MATITA 1.0: debbo fare time_travel sulla ng_library?
290        LexiconSync.time_travel ~present:lexicon ~past:initial_lexicon_status;
291  *       *)
292       pp_times fname false big_bang big_bang_u big_bang_s;
293       clean_exit baseuri exn
294
295 and assert_ng ~compiling ~include_paths mapath =
296  let _,baseuri,fullmapath,_ = Librarian.baseuri_of_script ~include_paths mapath in
297  let baseuri = NUri.uri_of_string baseuri in
298  let ngtime_of baseuri =
299   let ngpath = NCicLibrary.ng_path_of_baseuri baseuri in
300   try
301    Some (Unix.stat ngpath).Unix.st_mtime
302   with Unix.Unix_error (Unix.ENOENT, "stat", f) when f = ngpath -> None in
303  let matime =
304   try (Unix.stat fullmapath).Unix.st_mtime
305   with Unix.Unix_error (Unix.ENOENT, "stat", f) when f = fullmapath -> assert false
306  in
307  let ngtime = ngtime_of baseuri in
308  let to_be_compiled =
309   match ngtime with
310      Some ngtime ->
311       let preamble = GrafiteTypes.Serializer.dependencies_of baseuri in
312       let children_bad =
313        List.exists
314         (fun mapath ->
315              assert_ng ~compiling ~include_paths mapath
316           || let _,baseuri,_,_ =
317                Librarian.baseuri_of_script ~include_paths mapath in
318              let baseuri = NUri.uri_of_string baseuri in
319               (match ngtime_of baseuri with
320                   Some child_ngtime -> child_ngtime > ngtime
321                 | None -> assert false)
322         ) preamble
323       in
324        children_bad || matime > ngtime
325    | None -> true
326  in
327   if not to_be_compiled then false
328   else
329    (* MATITA 1.0: SHOULD TAKE THIS FROM THE STATUS *)
330    if List.mem baseuri (NCicLibrary.get_already_included ()) then
331      (* maybe recompiling it I would get the same... *)
332      raise (AlreadyLoaded (lazy mapath))
333    else
334     (compile ~compiling ~include_paths fullmapath; true)
335 ;;
336
337 let assert_ng = assert_ng ~compiling:[]
338 let get_ast = get_ast ~compiling:[]