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