]> matita.cs.unibo.it Git - helm.git/blob - helm/software/matita/matitacLib.ml
- matitacLib: better handling of the callbacks for the dump operation
[helm.git] / helm / software / matita / matitacLib.ml
1 (* Copyright (C) 2004-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 open Printf
29
30 open GrafiteTypes
31
32 exception AttemptToInsertAnAlias of LexiconEngine.status
33
34 let out = ref ignore 
35 let set_callback f = out := f
36
37
38 let slash_n_RE = Pcre.regexp "\\n" ;;
39
40 let pp_ast_statement grafite_status stm =
41   let stm = GrafiteAstPp.pp_statement
42     ~map_unicode_to_tex:(Helm_registry.get_bool "matita.paste_unicode_as_tex")
43     ~term_pp:CicNotationPp.pp_term
44     ~lazy_term_pp:CicNotationPp.pp_term ~obj_pp:(CicNotationPp.pp_obj
45     CicNotationPp.pp_term) stm
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 rc =
56   LibraryClean.clean_baseuris ~verbose:false [baseuri]; rc
57 ;;
58
59 let dump f =
60    let module G = GrafiteAst in
61    let module L = LexiconAst in
62    let module H = HExtlib in
63    Helm_registry.set_bool "matita.moo" false;
64    let floc = H.dummy_floc in
65    let nl_ast = G.Comment (floc, G.Note (floc, "")) in
66    let pp_statement stm =
67      GrafiteAstPp.pp_statement ~term_pp:CicNotationPp.pp_term
68        ~map_unicode_to_tex:(Helm_registry.get_bool
69          "matita.paste_unicode_as_tex")
70        ~lazy_term_pp:CicNotationPp.pp_term 
71        ~obj_pp:(CicNotationPp.pp_obj CicNotationPp.pp_term) stm
72    in
73    let pp_lexicon = LexiconAstPp.pp_command in
74    let och = open_out f in
75    let nl () =  output_string och (pp_statement nl_ast) in
76    MatitaMisc.out_preamble och;
77    let grafite_parser_cb status = function
78       | G.Executable (_, G.Macro (_, G.Inline _)) -> ()
79       | stm                                       ->
80          output_string och (pp_statement stm); nl (); nl ()
81    in
82    let lexicon_parser_cb status cmd =
83          output_string och (pp_lexicon cmd); nl (); nl ()
84    in
85 (*
86    let matita_engine_cb = function
87       | G.Executable (_, G.Macro (_, G.Inline _)) 
88       | G.Executable (_, G.Command (_, G.Include _)) -> ()
89       | ast                                          ->
90 *)
91    let matitac_lib_cb = output_string och in
92    begin fun () ->
93       GrafiteParser.set_grafite_callback grafite_parser_cb;
94       GrafiteParser.set_lexicon_callback lexicon_parser_cb;
95 (*   
96       MatitaEngine.set_callback matita_engine_cb;
97 *)   
98       set_callback matitac_lib_cb
99    end, 
100    begin fun x ->
101       close_out och;
102       GrafiteParser.set_grafite_callback (fun _ _ -> ());
103       GrafiteParser.set_lexicon_callback (fun _ _ -> ());
104       set_callback ignore; x
105    end
106 ;;
107
108 let get_macro_context = function
109    | Some {GrafiteTypes.proof_status = GrafiteTypes.No_proof} -> []
110    | Some status                ->
111       let stack = GrafiteTypes.get_stack status in
112       let goal = Continuationals.Stack.find_goal stack in
113       GrafiteTypes.get_proof_context status goal
114    | None                       -> assert false
115 ;;
116    
117 let pp_times fname rc big_bang big_bang_u big_bang_s = 
118   if not (Helm_registry.get_bool "matita.verbose") then
119     let { Unix.tms_utime = u ; Unix.tms_stime = s} = Unix.times () in
120     let r = Unix.gettimeofday () -. big_bang in
121     let u = u -. big_bang_u in
122     let s = s -. big_bang_s in
123     let extra = try Sys.getenv "BENCH_EXTRA_TEXT" with Not_found -> "" in
124     let rc,rcascii = 
125       if rc then "\e[0;32mOK\e[0m","Ok" else "\e[0;31mFAIL\e[0m","Fail" in
126     let times = 
127       let fmt t = 
128         let seconds = int_of_float t in
129         let cents = int_of_float ((t -. floor t) *. 100.0) in
130         let minutes = seconds / 60 in
131         let seconds = seconds mod 60 in
132         Printf.sprintf "%dm%02d.%02ds" minutes seconds cents
133       in
134       Printf.sprintf "%s %s %s" (fmt r) (fmt u) (fmt s)
135     in
136     let s = Printf.sprintf "%-4s %s %s" rc times extra in
137     print_endline s;
138     flush stdout;
139     HLog.message ("Compilation of "^Filename.basename fname^": "^rc)
140 ;;
141
142 let cut prefix s = 
143   let lenp = String.length prefix in
144   let lens = String.length s in
145   assert (lens > lenp);
146   assert (String.sub s 0 lenp = prefix);
147   String.sub s lenp (lens-lenp)
148 ;;
149
150 let get_include_paths options =
151   let include_paths = 
152     try List.assoc "include_paths" options with Not_found -> "" 
153   in
154   let include_paths = Str.split (Str.regexp " ") include_paths in
155   let include_paths = 
156     include_paths @ 
157     Helm_registry.get_list Helm_registry.string "matita.includes" 
158   in
159     include_paths
160 ;;
161
162 let activate_extraction baseuri fname =
163  if Helm_registry.get_bool "matita.extract" then
164   let mangled_baseuri =
165    let baseuri = String.sub baseuri 5 (String.length baseuri - 5) in
166      let baseuri = Pcre.replace ~pat:"/" ~templ:"_" baseuri in
167       String.uncapitalize baseuri in
168   let f =
169     open_out
170      (Filename.dirname fname ^ "/" ^ mangled_baseuri ^ ".ml") in
171    LibrarySync.add_object_declaration_hook
172     (fun ~add_obj ~add_coercion _ obj ->
173       output_string f (CicExportation.ppobj baseuri obj);
174       flush f; []);
175 ;;
176
177 let compile atstart options fname =
178   let matita_debug = Helm_registry.get_bool "matita.debug" in
179   let include_paths = get_include_paths options in
180   let root,baseuri,fname,_tgt = 
181     Librarian.baseuri_of_script ~include_paths fname in
182   if Http_getter_storage.is_read_only baseuri then assert false;
183   activate_extraction baseuri fname ;
184   let lexicon_status = 
185     CicNotation2.load_notation ~include_paths:[]
186       BuildTimeConf.core_notation_script 
187   in
188   atstart ();
189   let grafite_status = GrafiteSync.init lexicon_status baseuri in
190   let big_bang = Unix.gettimeofday () in
191   let { Unix.tms_utime = big_bang_u ; Unix.tms_stime = big_bang_s} = 
192     Unix.times () 
193   in
194   let time = Unix.time () in
195   try
196     (* sanity checks *)
197     let moo_fname = 
198      LibraryMisc.obj_file_of_baseuri ~must_exist:false ~baseuri ~writable:true
199     in
200     let lexicon_fname= 
201      LibraryMisc.lexicon_file_of_baseuri 
202        ~must_exist:false ~baseuri ~writable:true
203     in
204     (* cleanup of previously compiled objects *)
205     if (not (Http_getter_storage.is_empty ~local:true baseuri) ||
206         LibraryClean.db_uris_of_baseuri baseuri <> []) 
207       then begin
208       HLog.message ("baseuri " ^ baseuri ^ " is not empty");
209       HLog.message ("cleaning baseuri " ^ baseuri);
210       LibraryClean.clean_baseuris [baseuri];
211     end;
212     HLog.message ("compiling " ^ Filename.basename fname ^ " in " ^ baseuri);
213     if not (Helm_registry.get_bool "matita.verbose") then
214       (let cc = 
215         let rex = Str.regexp ".*opt$" in
216         if Str.string_match rex Sys.argv.(0) 0 then "matitac.opt"
217         else "matitac" 
218       in
219       let s = Printf.sprintf "%s %-35s " cc (cut (root^"/") fname) in
220       print_string s; flush stdout);
221     (* we dalay this error check until we print 'matitac file ' *)
222     assert (Http_getter_storage.is_empty ~local:true baseuri);
223     (* create dir for XML files *)
224     if not (Helm_registry.get_opt_default Helm_registry.bool "matita.nodisk"
225               ~default:false) 
226     then
227       HExtlib.mkdir 
228         (Filename.dirname 
229           (Http_getter.filename ~local:true ~writable:true (baseuri ^
230           "foo.con")));
231     let buf = Ulexing.from_utf8_channel (open_in fname) in
232     let print_cb =
233       if not (Helm_registry.get_bool "matita.verbose") then (fun _ _ -> ())
234       else pp_ast_statement
235     in
236     let grafite_status, lexicon_status =
237      let rec aux_for_dump x =
238      try
239       match
240        MatitaEngine.eval_from_stream ~first_statement_only:false ~include_paths
241         lexicon_status grafite_status buf x
242       with
243       | [] -> grafite_status, lexicon_status 
244       | ((grafite,lexicon),None)::_ -> grafite, lexicon
245       | ((_,l),Some _)::_ -> raise (AttemptToInsertAnAlias l)
246
247      with MatitaEngine.EnrichedWithLexiconStatus 
248             (GrafiteEngine.Macro (floc, f), lex_status) as exn ->
249             match f (get_macro_context (Some grafite_status)) with 
250             | _, GrafiteAst.Inline (_, style, suri, prefix, flavour) ->
251               let str =
252                ApplyTransformation.txt_of_inline_macro style prefix suri
253                 ?flavour
254                 ~map_unicode_to_tex:(Helm_registry.get_bool
255                   "matita.paste_unicode_as_tex")
256               in
257               !out str;
258               aux_for_dump x
259             |_-> raise exn
260      in
261        aux_for_dump print_cb
262     in
263     let elapsed = Unix.time () -. time in
264     let proof_status,moo_content_rev,lexicon_content_rev = 
265       grafite_status.proof_status, grafite_status.moo_content_rev, 
266        lexicon_status.LexiconEngine.lexicon_content_rev
267     in
268     if proof_status <> GrafiteTypes.No_proof then
269      (HLog.error
270       "there are still incomplete proofs at the end of the script"; 
271      pp_times fname false big_bang big_bang_u big_bang_s;
272 (*
273      LexiconSync.time_travel 
274        ~present:lexicon_status ~past:initial_lexicon_status;
275 *)
276      clean_exit baseuri false)
277     else
278      (if not (Helm_registry.get_bool "matita.moo" && 
279               Filename.check_suffix fname ".mma") then begin
280         (* FG: we do not generate .moo when dumping .mma files *)
281         GrafiteMarshal.save_moo moo_fname moo_content_rev;
282         LexiconMarshal.save_lexicon lexicon_fname lexicon_content_rev;
283      end;
284      let tm = Unix.gmtime elapsed in
285      let sec = string_of_int tm.Unix.tm_sec ^ "''" in
286      let min = 
287        if tm.Unix.tm_min > 0 then (string_of_int tm.Unix.tm_min^"' ") else "" 
288      in
289      let hou = 
290        if tm.Unix.tm_hour > 0 then (string_of_int tm.Unix.tm_hour^"h ") else ""
291      in
292      HLog.message 
293        (sprintf "execution of %s completed in %s." fname (hou^min^sec));
294      pp_times fname true big_bang big_bang_u big_bang_s;
295 (*
296      LexiconSync.time_travel 
297        ~present:lexicon_status ~past:initial_lexicon_status;
298 *)
299      true)
300   with 
301   (* all exceptions should be wrapped to allow lexicon-undo (LS.time_travel) *)
302   | AttemptToInsertAnAlias lexicon_status -> 
303      pp_times fname false big_bang big_bang_u big_bang_s;
304 (*
305      LexiconSync.time_travel 
306        ~present:lexicon_status ~past:initial_lexicon_status;
307 *)
308      clean_exit baseuri false
309   | MatitaEngine.EnrichedWithLexiconStatus (exn, lex_stat) as exn' ->
310       (match exn with
311       | Sys.Break -> HLog.error "user break!"
312       | HExtlib.Localized (floc,CicNotationParser.Parse_error err) ->
313           let (x, y) = HExtlib.loc_of_floc floc in
314           HLog.error (sprintf "Parse error at %d-%d: %s" x y err)
315       | exn when matita_debug -> raise exn'
316       | exn -> HLog.error (snd (MatitaExcPp.to_string exn))
317       );
318 (*       LexiconSync.time_travel ~present:lex_stat ~past:initial_lexicon_status;
319  *       *)
320       pp_times fname false big_bang big_bang_u big_bang_s;
321       clean_exit baseuri false
322   | Sys.Break when not matita_debug ->
323      HLog.error "user break!";
324      pp_times fname false big_bang big_bang_u big_bang_s;
325      clean_exit baseuri false
326   | exn when not matita_debug ->
327        HLog.error 
328          ("Unwrapped exception, please fix: "^ snd (MatitaExcPp.to_string exn));
329        pp_times fname false big_bang big_bang_u big_bang_s;
330        clean_exit baseuri false
331
332 module F = 
333   struct 
334     type source_object = string
335     type target_object = string
336     let string_of_source_object s = s;;
337     let string_of_target_object s = s;;
338
339     let is_readonly_buri_of opts file = 
340      let buri = List.assoc "baseuri" opts in
341      Http_getter_storage.is_read_only (Librarian.mk_baseuri buri file)
342     ;;
343
344     let root_and_target_of opts mafile = 
345       try
346         let include_paths = get_include_paths opts in
347         let root,baseuri,_,_ =
348           Librarian.baseuri_of_script ~include_paths mafile 
349         in
350         let obj_writeable, obj_read_only =
351            if Filename.check_suffix mafile ".mma" then 
352               Filename.chop_suffix mafile ".mma" ^ ".ma",
353               Filename.chop_suffix mafile ".mma" ^ ".ma"
354            else
355               LibraryMisc.obj_file_of_baseuri 
356                         ~must_exist:false ~baseuri ~writable:true,
357               LibraryMisc.obj_file_of_baseuri 
358                         ~must_exist:false ~baseuri ~writable:false
359         in
360         Some root, obj_writeable, obj_read_only
361       with Librarian.NoRootFor x -> None, "", ""
362     ;;
363
364     let mtime_of_source_object s =
365       try Some (Unix.stat s).Unix.st_mtime
366       with Unix.Unix_error (Unix.ENOENT, "stat", f) when f = s -> None
367     ;;
368
369     let mtime_of_target_object s =
370       try Some (Unix.stat s).Unix.st_mtime
371       with Unix.Unix_error (Unix.ENOENT, "stat", f) when f = s -> None
372     ;;
373
374 (* FG: a problem was noticed in relising memory between subsequent *)
375 (*     invocations of the compiler. The following might help       *)
376     let compact r = Gc.compact (); r
377
378     let build options fname =
379       let matita_debug = Helm_registry.get_bool "matita.debug" in
380       let compile atstart opts fname =
381         try
382           GrafiteSync.push ();
383           GrafiteParser.push ();
384           let rc = compile atstart opts fname in
385           GrafiteParser.pop ();
386           GrafiteSync.pop ();
387           rc
388         with 
389         | Sys.Break ->
390             GrafiteParser.pop ();
391             GrafiteSync.pop ();
392             false
393         | exn when not matita_debug ->
394             HLog.error ("Unexpected " ^ snd(MatitaExcPp.to_string exn));
395             assert false
396       in
397       if Filename.check_suffix fname ".mma" then 
398          let generated = Filename.chop_suffix fname ".mma" ^ ".ma" in
399          let atstart, atexit = dump generated in
400          let res = compile atstart options fname in
401          let r = compact (atexit res) in
402          if r then r else begin
403 (*            Sys.remove generated; *)
404             Printf.printf "rm %s\n" generated; flush stdout; r
405          end
406       else
407          compile ignore options fname
408     ;;
409
410     let load_deps_file = Librarian.load_deps_file;;
411
412   end 
413
414 module Make = Librarian.Make(F) 
415