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