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