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