]> matita.cs.unibo.it Git - helm.git/blob - matita/matita/matitaEngine.ml
- matitacLib merged into matitaEngine
[helm.git] / matita / matita / matitaEngine.ml
1 (* Copyright (C) 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 module G = GrafiteAst
29
30 let debug = false ;;
31 let debug_print = if debug then prerr_endline else ignore ;;
32
33 let eval_macro_screenshot (status : GrafiteTypes.status) name =
34   assert false (* MATITA 1.0
35   let _,_,metasenv,subst,_ = status#obj in
36   let sequent = List.hd metasenv in
37   let mathml = 
38     ApplyTransformation.nmml_of_cic_sequent 
39       status metasenv subst sequent 
40   in
41   let domImpl = Gdome.domImplementation () in
42   ignore(domImpl#saveDocumentToFile 
43     ~name:(name^".xml") ~doc:mathml ());
44   ignore(Sys.command ("mathmlsvg --verbose=1 --font-size=20 --cut-filename=no " ^ 
45     Filename.quote (name^".xml")));
46   ignore(Sys.command ("convert " ^ 
47     Filename.quote (name^".svg") ^ " " ^ 
48     Filename.quote (name^".png")));
49   HLog.debug ("generated " ^ name ^ ".png");
50   status, `New []
51   *)
52 ;;
53
54 let eval_ast ~include_paths ?do_heavy_checks status (text,prefix_len,ast) =
55  let baseuri = status#baseuri in
56  let new_aliases,new_status =
57   GrafiteDisambiguate.eval_with_new_aliases status
58    (fun status ->
59      GrafiteEngine.eval_ast ~include_paths ?do_heavy_checks status
60       (text,prefix_len,ast)) in
61  let _,intermediate_states = 
62   List.fold_left
63    (fun (status,acc) (k,value) -> 
64      let v = GrafiteAst.description_of_alias value in
65      let b =
66       try
67        let NReference.Ref (uri,_) = NReference.reference_of_string v in
68         NUri.baseuri_of_uri uri = baseuri
69       with
70        NReference.IllFormedReference _ ->
71         false (* v is a description, not a URI *)
72      in
73       if b then 
74        status,acc
75       else
76        let status =
77         GrafiteDisambiguate.set_proof_aliases status ~implicit_aliases:false
78          GrafiteAst.WithPreferences [k,value]
79        in
80         status, (status ,Some (k,value))::acc
81    ) (status,[]) new_aliases (* WARNING: this must be the old status! *)
82  in
83   (new_status,None)::intermediate_states
84 ;;
85
86 exception TryingToAdd of string
87 exception EnrichedWithStatus of exn * GrafiteTypes.status
88
89 let eval_from_stream ~include_paths ?do_heavy_checks status str cb =
90  let matita_debug = Helm_registry.get_bool "matita.debug" in
91  let rec loop status =
92   let stop,status = 
93    try
94      let cont =
95        try Some (GrafiteParser.parse_statement status str)
96        with End_of_file -> None in
97      match cont with
98      | None -> true, status
99      | Some ast ->
100         cb status ast;
101         let new_statuses =
102           eval_ast ~include_paths ?do_heavy_checks status ("",0,ast) in
103         let status =
104          match new_statuses with
105             [s,None] -> s
106           | _::(_,Some (_,value))::_ ->
107                 raise (TryingToAdd (GrafiteAstPp.pp_alias value))
108           | _ -> assert false
109         in
110          false, status
111    with exn when not matita_debug ->
112      raise (EnrichedWithStatus (exn, status))
113   in
114   if stop then status else loop status
115  in
116   loop status
117 ;;
118
119 (* EX MATITACLIB *)
120 open Printf
121
122 open GrafiteTypes
123
124 let slash_n_RE = Pcre.regexp "\\n" ;;
125
126 let pp_ast_statement grafite_status stm =
127   let stm = GrafiteAstPp.pp_statement stm
128     ~map_unicode_to_tex:(Helm_registry.get_bool "matita.paste_unicode_as_tex")
129   in
130   let stm = Pcre.replace ~rex:slash_n_RE stm in
131   let stm =
132       if String.length stm > 50 then String.sub stm 0 50 ^ " ..."
133       else stm
134   in
135     HLog.debug ("Executing: ``" ^ stm ^ "''")
136 ;;
137
138 let clean_exit baseuri rc =
139   LibraryClean.clean_baseuris ~verbose:false [baseuri]; rc
140 ;;
141
142 let pp_times fname rc big_bang big_bang_u big_bang_s = 
143   if not (Helm_registry.get_bool "matita.verbose") then
144     let { Unix.tms_utime = u ; Unix.tms_stime = s} = Unix.times () in
145     let r = Unix.gettimeofday () -. big_bang in
146     let u = u -. big_bang_u in
147     let s = s -. big_bang_s in
148     let extra = try Sys.getenv "BENCH_EXTRA_TEXT" with Not_found -> "" in
149     let rc,rcascii = 
150       if rc then "\e[0;32mOK\e[0m","Ok" else "\e[0;31mFAIL\e[0m","Fail" in
151     let times = 
152       let fmt t = 
153         let seconds = int_of_float t in
154         let cents = int_of_float ((t -. floor t) *. 100.0) in
155         let minutes = seconds / 60 in
156         let seconds = seconds mod 60 in
157         Printf.sprintf "%dm%02d.%02ds" minutes seconds cents
158       in
159       Printf.sprintf "%s %s %s" (fmt r) (fmt u) (fmt s)
160     in
161     let s = Printf.sprintf "%-4s %s %s" rc times extra in
162     print_endline s;
163     flush stdout;
164     HLog.message ("Compilation of "^Filename.basename fname^": "^rc)
165 ;;
166
167 let cut prefix s = 
168   let lenp = String.length prefix in
169   let lens = String.length s in
170   assert (lens > lenp);
171   assert (String.sub s 0 lenp = prefix);
172   String.sub s lenp (lens-lenp)
173 ;;
174
175 let get_include_paths options =
176   let include_paths = 
177     try List.assoc "include_paths" options with Not_found -> "" 
178   in
179   let include_paths = Str.split (Str.regexp " ") include_paths in
180   let include_paths = 
181     include_paths @ 
182     Helm_registry.get_list Helm_registry.string "matita.includes" 
183   in
184     include_paths
185 ;;
186
187 let activate_extraction baseuri fname =
188   ()
189   (* MATITA 1.0
190  if Helm_registry.get_bool "matita.extract" then
191   let mangled_baseuri =
192    let baseuri = String.sub baseuri 5 (String.length baseuri - 5) in
193      let baseuri = Pcre.replace ~pat:"/" ~templ:"_" baseuri in
194       String.uncapitalize baseuri in
195   let f =
196     open_out
197      (Filename.dirname fname ^ "/" ^ mangled_baseuri ^ ".ml") in
198    LibrarySync.add_object_declaration_hook
199     (fun ~add_obj ~add_coercion _ obj ->
200       output_string f (CicExportation.ppobj baseuri obj);
201       flush f; []);
202       *)
203 ;;
204
205 let compile options fname =
206   let matita_debug = Helm_registry.get_bool "matita.debug" in
207   let include_paths = get_include_paths options in
208   let root,baseuri,fname,_tgt = 
209     Librarian.baseuri_of_script ~include_paths fname in
210   if Http_getter_storage.is_read_only baseuri then assert false;
211   activate_extraction baseuri fname ;
212   let grafite_status = new GrafiteTypes.status baseuri in
213   let big_bang = Unix.gettimeofday () in
214   let { Unix.tms_utime = big_bang_u ; Unix.tms_stime = big_bang_s} = 
215     Unix.times () 
216   in
217   let time = Unix.time () in
218   try
219     (* cleanup of previously compiled objects *)
220     if (not (Http_getter_storage.is_empty ~local:true baseuri))
221       then begin
222       HLog.message ("baseuri " ^ baseuri ^ " is not empty");
223       HLog.message ("cleaning baseuri " ^ baseuri);
224       LibraryClean.clean_baseuris [baseuri];
225     end;
226     HLog.message ("compiling " ^ Filename.basename fname ^ " in " ^ baseuri);
227     if not (Helm_registry.get_bool "matita.verbose") then
228       (let cc = 
229         let rex = Str.regexp ".*opt$" in
230         if Str.string_match rex Sys.argv.(0) 0 then "matitac.opt"
231         else "matitac" 
232       in
233       let s = Printf.sprintf "%s %-35s " cc (cut (root^"/") fname) in
234       print_string s; flush stdout);
235     (* we dalay this error check until we print 'matitac file ' *)
236     assert (Http_getter_storage.is_empty ~local:true baseuri);
237     (* create dir for XML files *)
238     if not (Helm_registry.get_opt_default Helm_registry.bool "matita.nodisk"
239               ~default:false) 
240     then
241       HExtlib.mkdir 
242         (Filename.dirname 
243           (Http_getter.filename ~local:true ~writable:true (baseuri ^
244           "foo.con")));
245     let buf = Ulexing.from_utf8_channel (open_in fname) in
246     let print_cb =
247       if not (Helm_registry.get_bool "matita.verbose") then (fun _ _ -> ())
248       else pp_ast_statement
249     in
250     let grafite_status =
251      eval_from_stream ~include_paths grafite_status buf print_cb
252     in
253     let elapsed = Unix.time () -. time in
254      (if Helm_registry.get_bool "matita.moo" then begin
255        GrafiteTypes.Serializer.serialize ~baseuri:(NUri.uri_of_string baseuri)
256         grafite_status#dump
257      end;
258      let tm = Unix.gmtime elapsed in
259      let sec = string_of_int tm.Unix.tm_sec ^ "''" in
260      let min = 
261        if tm.Unix.tm_min > 0 then (string_of_int tm.Unix.tm_min^"' ") else "" 
262      in
263      let hou = 
264        if tm.Unix.tm_hour > 0 then (string_of_int tm.Unix.tm_hour^"h ") else ""
265      in
266      HLog.message 
267        (sprintf "execution of %s completed in %s." fname (hou^min^sec));
268      pp_times fname true big_bang big_bang_u big_bang_s;
269 (*
270      LexiconSync.time_travel 
271        ~present:lexicon_status ~past:initial_lexicon_status;
272 *)
273      true)
274   with 
275   (* all exceptions should be wrapped to allow lexicon-undo (LS.time_travel) *)
276   | EnrichedWithStatus (exn, _grafite) as exn' ->
277       (match exn with
278       | Sys.Break -> HLog.error "user break!"
279       | HExtlib.Localized (floc,CicNotationParser.Parse_error err) ->
280           let (x, y) = HExtlib.loc_of_floc floc in
281           HLog.error (sprintf "Parse error at %d-%d: %s" x y err)
282       | exn when matita_debug -> raise exn'
283       | exn -> HLog.error (snd (MatitaExcPp.to_string exn))
284       );
285 (*       LexiconSync.time_travel ~present:lexicon ~past:initial_lexicon_status;
286  *       *)
287       pp_times fname false big_bang big_bang_u big_bang_s;
288       clean_exit baseuri false
289   | Sys.Break when not matita_debug ->
290      HLog.error "user break!";
291      pp_times fname false big_bang big_bang_u big_bang_s;
292      clean_exit baseuri false
293   | exn when not matita_debug ->
294        HLog.error 
295          ("Unwrapped exception, please fix: "^ snd (MatitaExcPp.to_string exn));
296        pp_times fname false big_bang big_bang_u big_bang_s;
297        clean_exit baseuri false
298
299 module F = 
300   struct 
301     type source_object = string
302     type target_object = string
303     let string_of_source_object s = s;;
304     let string_of_target_object s = s;;
305
306     let is_readonly_buri_of opts file = 
307      let buri = List.assoc "baseuri" opts in
308      Http_getter_storage.is_read_only (Librarian.mk_baseuri buri file)
309     ;;
310
311     let root_and_target_of opts mafile = 
312       try
313         let include_paths = get_include_paths opts in
314         let root,baseuri,_,relpath =
315           Librarian.baseuri_of_script ~include_paths mafile 
316         in
317         let obj_writeable, obj_read_only =
318            if Filename.check_suffix mafile ".mma" then 
319               Filename.chop_suffix mafile ".mma" ^ ".ma",
320               Filename.chop_suffix mafile ".mma" ^ ".ma"
321            else
322               LibraryMisc.obj_file_of_baseuri 
323                         ~must_exist:false ~baseuri ~writable:true,
324               LibraryMisc.obj_file_of_baseuri 
325                         ~must_exist:false ~baseuri ~writable:false
326         in
327         Some root, relpath, obj_writeable, obj_read_only
328       with Librarian.NoRootFor x -> None, "", "", ""
329     ;;
330
331     let mtime_of_source_object s =
332       try Some (Unix.stat s).Unix.st_mtime
333       with Unix.Unix_error (Unix.ENOENT, "stat", f) when f = s -> None
334     ;;
335
336     let mtime_of_target_object s =
337       try Some (Unix.stat s).Unix.st_mtime
338       with Unix.Unix_error (Unix.ENOENT, "stat", f) when f = s -> None
339     ;;
340
341 (* FG: a problem was noticed in relising memory between subsequent *)
342 (*     invocations of the compiler. The following might help       *)
343     let compact r = Gc.compact (); r
344
345     let build options fname =
346       let matita_debug = Helm_registry.get_bool "matita.debug" in
347       let compile opts fname =
348         try
349         (* MATITA 1.0: c'erano le push/pop per il parser; ma per
350          * l'environment nuovo? *)
351          compile opts fname
352         with 
353         | Sys.Break -> false
354         | exn when not matita_debug ->
355             HLog.error ("Unexpected " ^ snd(MatitaExcPp.to_string exn));
356             assert false
357       in
358        compact (compile options fname)
359     ;;
360
361     let load_deps_file = Librarian.load_deps_file;;
362
363   end 
364
365 module Make = Librarian.Make(F) 
366
367 (* FINE EX MATITACLIB *)
368
369
370
371 (* this function calls the parser in a way that it does not perform inclusions,
372  * so that we can ensure the inclusion is performed after the included file 
373  * is compiled (if needed). matitac does not need that, since it compiles files
374  * in the good order, here files may be compiled on demand. *)
375 let wrap_with_make include_paths f x = 
376   match f x with
377      (GrafiteAst.Executable
378        (_,GrafiteAst.NCommand (_,GrafiteAst.Include (_,_,mafilename)))) as cmd
379      ->
380       let root, buri, _, tgt = 
381         try Librarian.baseuri_of_script ~include_paths mafilename
382         with Librarian.NoRootFor _ -> 
383           HLog.error ("The included file '"^mafilename^"' has no root file,");
384           HLog.error "please create it.";
385           raise (Failure ("No root file for "^mafilename))
386       in
387       if Make.make root [tgt] then
388        cmd
389       else raise (Failure ("Compiling: " ^ tgt))
390    | cmd -> cmd
391 ;;
392
393 let toplevel status ~include_paths text =
394  wrap_with_make include_paths
395   (GrafiteParser.parse_statement status)
396     (Ulexing.from_utf8_string text)
397 ;;