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