]> matita.cs.unibo.it Git - helm.git/blob - matita/matita/matitaEngine.ml
Large commit:
[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 open GrafiteTypes
30 open Printf
31
32 exception TryingToAdd of string Lazy.t
33 exception EnrichedWithStatus of exn * GrafiteTypes.status
34 exception AlreadyLoaded of string Lazy.t
35 exception FailureCompiling of string * exn
36 exception CircularDependency of string
37
38 let debug = false ;;
39 let debug_print = if debug then prerr_endline else ignore ;;
40
41 let slash_n_RE = Pcre.regexp "\\n" ;;
42
43 let pp_ast_statement grafite_status stm =
44   let stm = GrafiteAstPp.pp_statement stm
45     ~map_unicode_to_tex:(Helm_registry.get_bool "matita.paste_unicode_as_tex")
46   in
47   let stm = Pcre.replace ~rex:slash_n_RE stm in
48   let stm =
49       if String.length stm > 50 then String.sub stm 0 50 ^ " ..."
50       else stm
51   in
52     HLog.debug ("Executing: ``" ^ stm ^ "''")
53 ;;
54
55 let clean_exit baseuri exn =
56   LibraryClean.clean_baseuris ~verbose:false [baseuri];
57   raise (FailureCompiling (baseuri,exn))
58 ;;
59
60
61 let pp_times fname rc big_bang big_bang_u big_bang_s = 
62   if not (Helm_registry.get_bool "matita.verbose") then
63     let { Unix.tms_utime = u ; Unix.tms_stime = s} = Unix.times () in
64     let r = Unix.gettimeofday () -. big_bang in
65     let u = u -. big_bang_u in
66     let s = s -. big_bang_s in
67     let extra = try Sys.getenv "BENCH_EXTRA_TEXT" with Not_found -> "" in
68     let rc,rcascii = 
69       if rc then "\e[0;32mOK\e[0m","Ok" else "\e[0;31mFAIL\e[0m","Fail" in
70     let times = 
71       let fmt t = 
72         let seconds = int_of_float t in
73         let cents = int_of_float ((t -. floor t) *. 100.0) in
74         let minutes = seconds / 60 in
75         let seconds = seconds mod 60 in
76         Printf.sprintf "%dm%02d.%02ds" minutes seconds cents
77       in
78       Printf.sprintf "%s %s %s" (fmt r) (fmt u) (fmt s)
79     in
80     let s = Printf.sprintf "%-4s %s %s" rc times extra in
81     print_endline s;
82     flush stdout;
83     HLog.message ("Compilation of "^Filename.basename fname^": "^rc)
84 ;;
85
86 let cut prefix s = 
87   let lenp = String.length prefix in
88   let lens = String.length s in
89   assert (lens > lenp);
90   assert (String.sub s 0 lenp = prefix);
91   String.sub s lenp (lens-lenp)
92 ;;
93
94 let activate_extraction baseuri fname =
95   ()
96   (* MATITA 1.0
97  if Helm_registry.get_bool "matita.extract" then
98   let mangled_baseuri =
99    let baseuri = String.sub baseuri 5 (String.length baseuri - 5) in
100      let baseuri = Pcre.replace ~pat:"/" ~templ:"_" baseuri in
101       String.uncapitalize baseuri in
102   let f =
103     open_out
104      (Filename.dirname fname ^ "/" ^ mangled_baseuri ^ ".ml") in
105    LibrarySync.add_object_declaration_hook
106     (fun ~add_obj ~add_coercion _ obj ->
107       output_string f (CicExportation.ppobj baseuri obj);
108       flush f; []);
109       *)
110 ;;
111
112
113 let eval_macro_screenshot (status : GrafiteTypes.status) name =
114   assert false (* MATITA 1.0
115   let _,_,metasenv,subst,_ = status#obj in
116   let sequent = List.hd metasenv in
117   let mathml = 
118     ApplyTransformation.nmml_of_cic_sequent 
119       status metasenv subst sequent 
120   in
121   let domImpl = Gdome.domImplementation () in
122   ignore(domImpl#saveDocumentToFile 
123     ~name:(name^".xml") ~doc:mathml ());
124   ignore(Sys.command ("mathmlsvg --verbose=1 --font-size=20 --cut-filename=no " ^ 
125     Filename.quote (name^".xml")));
126   ignore(Sys.command ("convert " ^ 
127     Filename.quote (name^".svg") ^ " " ^ 
128     Filename.quote (name^".png")));
129   HLog.debug ("generated " ^ name ^ ".png");
130   status, `New []
131   *)
132 ;;
133
134 let eval_ast ~include_paths ?do_heavy_checks status (text,prefix_len,ast) =
135  let baseuri = status#baseuri in
136  let new_aliases,new_status =
137   GrafiteDisambiguate.eval_with_new_aliases status
138    (fun status ->
139      GrafiteEngine.eval_ast ~include_paths ?do_heavy_checks status
140       (text,prefix_len,ast)) in
141  let _,intermediate_states = 
142   List.fold_left
143    (fun (status,acc) (k,value) -> 
144      let v = GrafiteAst.description_of_alias value in
145      let b =
146       try
147        let NReference.Ref (uri,_) = NReference.reference_of_string v in
148         NUri.baseuri_of_uri uri = baseuri
149       with
150        NReference.IllFormedReference _ ->
151         false (* v is a description, not a URI *)
152      in
153       if b then 
154        status,acc
155       else
156        let status =
157         GrafiteDisambiguate.set_proof_aliases status ~implicit_aliases:false
158          GrafiteAst.WithPreferences [k,value]
159        in
160         status, (status ,Some (k,value))::acc
161    ) (status,[]) new_aliases (* WARNING: this must be the old status! *)
162  in
163   (new_status,None)::intermediate_states
164 ;;
165
166 let baseuri_of_script ~include_paths fname =
167  try Librarian.baseuri_of_script ~include_paths fname
168  with
169    Librarian.NoRootFor _ -> 
170     HLog.error ("The included file '"^fname^"' has no root file,");
171     HLog.error "please create it.";
172     raise (Failure ("No root file for "^fname))
173   | Librarian.FileNotFound _ -> 
174     raise (Failure ("File not found: "^fname))
175 ;;
176
177 let rec get_ast status ~compiling ~include_paths strm = 
178   match GrafiteParser.parse_statement status strm with
179      (GrafiteAst.Executable
180        (_,GrafiteAst.NCommand (_,GrafiteAst.Include (_,_,mafilename)))) as cmd
181      ->
182        let already_included = NCicLibrary.get_already_included status in
183        ignore(assert_ng ~already_included ~compiling ~include_paths mafilename);
184        cmd
185    | cmd -> cmd
186
187 and eval_from_stream ~compiling ~include_paths ?do_heavy_checks status str cb =
188  let matita_debug = Helm_registry.get_bool "matita.debug" in
189  let rec loop status =
190   let stop,status = 
191    try
192      let cont =
193        try Some (get_ast status ~compiling ~include_paths str)
194        with End_of_file -> None in
195      match cont with
196      | None -> true, status
197      | Some ast ->
198         cb status ast;
199         let new_statuses =
200           eval_ast ~include_paths ?do_heavy_checks status ("",0,ast) in
201         let status =
202          match new_statuses with
203             [s,None] -> s
204           | _::(_,Some (_,value))::_ ->
205                 raise (TryingToAdd (lazy (GrafiteAstPp.pp_alias value)))
206           | _ -> assert false
207         in
208          false, status
209    with exn when not matita_debug ->
210      raise (EnrichedWithStatus (exn, status))
211   in
212   if stop then status else loop status
213  in
214   loop status
215
216 and compile ~compiling ~include_paths fname =
217   if List.mem fname compiling then raise (CircularDependency fname);
218   let compiling = fname::compiling in
219   let matita_debug = Helm_registry.get_bool "matita.debug" in
220   let root,baseuri,fname,_tgt = 
221     Librarian.baseuri_of_script ~include_paths fname in
222   if Http_getter_storage.is_read_only baseuri then assert false;
223   activate_extraction baseuri fname ;
224   (* MATITA 1.0: debbo fare time_travel sulla ng_library? *)
225   let grafite_status = new GrafiteTypes.status baseuri in
226   let big_bang = Unix.gettimeofday () in
227   let { Unix.tms_utime = big_bang_u ; Unix.tms_stime = big_bang_s} = 
228     Unix.times () 
229   in
230   let time = Unix.time () in
231   try
232     (* cleanup of previously compiled objects *)
233     if (not (Http_getter_storage.is_empty ~local:true baseuri))
234       then begin
235       HLog.message ("baseuri " ^ baseuri ^ " is not empty");
236       HLog.message ("cleaning baseuri " ^ baseuri);
237       LibraryClean.clean_baseuris [baseuri];
238     end;
239     HLog.message ("compiling " ^ Filename.basename fname ^ " in " ^ baseuri);
240     if not (Helm_registry.get_bool "matita.verbose") then
241       (let cc = 
242         let rex = Str.regexp ".*opt$" in
243         if Str.string_match rex Sys.argv.(0) 0 then "matitac.opt"
244         else "matitac" 
245       in
246       let s = Printf.sprintf "%s %-35s " cc (cut (root^"/") fname) in
247       print_string s; flush stdout);
248     (* we dalay this error check until we print 'matitac file ' *)
249     assert (Http_getter_storage.is_empty ~local:true baseuri);
250     (* create dir for XML files *)
251     if not (Helm_registry.get_opt_default Helm_registry.bool "matita.nodisk"
252               ~default:false) 
253     then
254       HExtlib.mkdir 
255         (Filename.dirname 
256           (Http_getter.filename ~local:true ~writable:true (baseuri ^
257           "foo.con")));
258     let buf =
259      GrafiteParser.parsable_statement grafite_status
260       (Ulexing.from_utf8_channel (open_in fname))
261     in
262     let print_cb =
263       if not (Helm_registry.get_bool "matita.verbose") then (fun _ _ -> ())
264       else pp_ast_statement
265     in
266     let grafite_status =
267      eval_from_stream ~compiling ~include_paths grafite_status buf print_cb in
268     let elapsed = Unix.time () -. time in
269      (if Helm_registry.get_bool "matita.moo" then begin
270        GrafiteTypes.Serializer.serialize ~baseuri:(NUri.uri_of_string baseuri)
271         grafite_status
272      end;
273      let tm = Unix.gmtime elapsed in
274      let sec = string_of_int tm.Unix.tm_sec ^ "''" in
275      let min = 
276        if tm.Unix.tm_min > 0 then (string_of_int tm.Unix.tm_min^"' ") else "" 
277      in
278      let hou = 
279        if tm.Unix.tm_hour > 0 then (string_of_int tm.Unix.tm_hour^"h ") else ""
280      in
281      HLog.message 
282        (sprintf "execution of %s completed in %s." fname (hou^min^sec));
283      pp_times fname true big_bang big_bang_u big_bang_s
284 (* MATITA 1.0: debbo fare time_travel sulla ng_library?
285      LexiconSync.time_travel 
286        ~present:lexicon_status ~past:initial_lexicon_status;
287 *))
288   with 
289   (* all exceptions should be wrapped to allow lexicon-undo (LS.time_travel) *)
290   | exn when not matita_debug ->
291 (* MATITA 1.0: debbo fare time_travel sulla ng_library?
292        LexiconSync.time_travel ~present:lexicon ~past:initial_lexicon_status;
293  *       *)
294       pp_times fname false big_bang big_bang_u big_bang_s;
295       clean_exit baseuri exn
296
297 and assert_ng ~already_included ~compiling ~include_paths mapath =
298  let _,baseuri,fullmapath,_ = Librarian.baseuri_of_script ~include_paths mapath in
299  let baseuri = NUri.uri_of_string baseuri in
300  let ngtime_of baseuri =
301   let ngpath = NCicLibrary.ng_path_of_baseuri baseuri in
302   try
303    Some (Unix.stat ngpath).Unix.st_mtime
304   with Unix.Unix_error (Unix.ENOENT, "stat", f) when f = ngpath -> None in
305  let matime =
306   try (Unix.stat fullmapath).Unix.st_mtime
307   with Unix.Unix_error (Unix.ENOENT, "stat", f) when f = fullmapath -> assert false
308  in
309  let ngtime = ngtime_of baseuri in
310  let to_be_compiled =
311   match ngtime with
312      Some ngtime ->
313       let preamble = GrafiteTypes.Serializer.dependencies_of baseuri in
314       let children_bad =
315        List.exists
316         (fun mapath ->
317              assert_ng ~already_included ~compiling ~include_paths mapath
318           || let _,baseuri,_,_ =
319                Librarian.baseuri_of_script ~include_paths mapath in
320              let baseuri = NUri.uri_of_string baseuri in
321               (match ngtime_of baseuri with
322                   Some child_ngtime -> child_ngtime > ngtime
323                 | None -> assert false)
324         ) preamble
325       in
326        children_bad || matime > ngtime
327    | None -> true
328  in
329   if not to_be_compiled then false
330   else
331    if List.mem baseuri already_included then
332      (* maybe recompiling it I would get the same... *)
333      raise (AlreadyLoaded (lazy mapath))
334    else
335     (compile ~compiling ~include_paths fullmapath; true)
336 ;;
337
338 let assert_ng = assert_ng ~already_included:[] ~compiling:[]
339 let get_ast = get_ast ~compiling:[]