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