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