]> matita.cs.unibo.it Git - helm.git/blob - matita/matita/matitaEngine.ml
1. bug fixed: in the last commit on NCicLibrary we forgot that
[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_ast ~include_paths ?do_heavy_checks status (text,prefix_len,ast) =
114  let baseuri = status#baseuri in
115  let new_aliases,new_status =
116   GrafiteDisambiguate.eval_with_new_aliases status
117    (fun status ->
118      GrafiteEngine.eval_ast ~include_paths ?do_heavy_checks status
119       (text,prefix_len,ast)) in
120  let _,intermediate_states = 
121   List.fold_left
122    (fun (status,acc) (k,value) -> 
123      let v = GrafiteAst.description_of_alias value in
124      let b =
125       try
126        let NReference.Ref (uri,_) = NReference.reference_of_string v in
127         NUri.baseuri_of_uri uri = baseuri
128       with
129        NReference.IllFormedReference _ ->
130         false (* v is a description, not a URI *)
131      in
132       if b then 
133        status,acc
134       else
135        let status =
136         GrafiteDisambiguate.set_proof_aliases status ~implicit_aliases:false
137          GrafiteAst.WithPreferences [k,value]
138        in
139         status, (status ,Some (k,value))::acc
140    ) (status,[]) new_aliases (* WARNING: this must be the old status! *)
141  in
142   (new_status,None)::intermediate_states
143 ;;
144
145 let baseuri_of_script ~include_paths fname =
146  try Librarian.baseuri_of_script ~include_paths fname
147  with
148    Librarian.NoRootFor _ -> 
149     HLog.error ("The included file '"^fname^"' has no root file,");
150     HLog.error "please create it.";
151     raise (Failure ("No root file for "^fname))
152   | Librarian.FileNotFound _ -> 
153     raise (Failure ("File not found: "^fname))
154 ;;
155
156 let rec get_ast status ~compiling ~asserted ~include_paths strm = 
157   match GrafiteParser.parse_statement status strm with
158      (GrafiteAst.Executable
159        (_,GrafiteAst.NCommand (_,GrafiteAst.Include (_,_,mafilename)))) as cmd
160      ->
161        let already_included = NCicLibrary.get_transitively_included status in
162        let asserted,_ =
163         assert_ng ~already_included ~compiling ~asserted ~include_paths
164          mafilename
165        in
166         asserted,cmd
167    | cmd -> asserted,cmd
168
169 and eval_from_stream ~compiling ~asserted ~include_paths ?do_heavy_checks status str cb =
170  let matita_debug = Helm_registry.get_bool "matita.debug" in
171  let rec loop asserted status =
172   let asserted,stop,status = 
173    try
174      let cont =
175        try Some (get_ast status ~compiling ~asserted ~include_paths str)
176        with End_of_file -> None in
177      match cont with
178      | None -> asserted, true, status
179      | Some (asserted,ast) ->
180         cb status ast;
181         let new_statuses =
182           eval_ast ~include_paths ?do_heavy_checks status ("",0,ast) in
183         let status =
184          match new_statuses with
185             [s,None] -> s
186           | _::(_,Some (_,value))::_ ->
187                 raise (TryingToAdd (lazy (GrafiteAstPp.pp_alias value)))
188           | _ -> assert false
189         in
190          asserted, false, status
191    with exn when not matita_debug ->
192      raise (EnrichedWithStatus (exn, status))
193   in
194   if stop then asserted,status else loop asserted status
195  in
196   loop asserted status
197
198 and compile ~compiling ~asserted ~include_paths fname =
199   if List.mem fname compiling then raise (CircularDependency fname);
200   let compiling = fname::compiling in
201   let matita_debug = Helm_registry.get_bool "matita.debug" in
202   let root,baseuri,fname,_tgt = 
203     Librarian.baseuri_of_script ~include_paths fname in
204   if Http_getter_storage.is_read_only baseuri then assert false;
205   activate_extraction baseuri fname ;
206   (* MATITA 1.0: debbo fare time_travel sulla ng_library? *)
207   let grafite_status = new GrafiteTypes.status baseuri in
208   let big_bang = Unix.gettimeofday () in
209   let { Unix.tms_utime = big_bang_u ; Unix.tms_stime = big_bang_s} = 
210     Unix.times () 
211   in
212   let time = Unix.time () in
213   try
214     (* cleanup of previously compiled objects *)
215     if (not (Http_getter_storage.is_empty ~local:true baseuri))
216       then begin
217       HLog.message ("baseuri " ^ baseuri ^ " is not empty");
218       HLog.message ("cleaning baseuri " ^ baseuri);
219       LibraryClean.clean_baseuris [baseuri];
220     end;
221     HLog.message ("compiling " ^ Filename.basename fname ^ " in " ^ baseuri);
222     if not (Helm_registry.get_bool "matita.verbose") then
223       (let cc = 
224         let rex = Str.regexp ".*opt$" in
225         if Str.string_match rex Sys.argv.(0) 0 then "matitac.opt"
226         else "matitac" 
227       in
228       let s = Printf.sprintf "%s %-35s " cc (cut (root^"/") fname) in
229       print_string s; flush stdout);
230     (* we dalay this error check until we print 'matitac file ' *)
231     assert (Http_getter_storage.is_empty ~local:true baseuri);
232     (* create dir for XML files *)
233     if not (Helm_registry.get_opt_default Helm_registry.bool "matita.nodisk"
234               ~default:false) 
235     then
236       HExtlib.mkdir 
237         (Filename.dirname 
238           (Http_getter.filename ~local:true ~writable:true (baseuri ^
239           "foo.con")));
240     let buf =
241      GrafiteParser.parsable_statement grafite_status
242       (Ulexing.from_utf8_channel (open_in fname))
243     in
244     let print_cb =
245       if not (Helm_registry.get_bool "matita.verbose") then (fun _ _ -> ())
246       else pp_ast_statement
247     in
248     let asserted, grafite_status =
249      eval_from_stream ~compiling ~asserted ~include_paths grafite_status buf print_cb in
250     let elapsed = Unix.time () -. time in
251      (if Helm_registry.get_bool "matita.moo" then begin
252        GrafiteTypes.Serializer.serialize ~baseuri:(NUri.uri_of_string baseuri)
253         grafite_status
254      end;
255      let tm = Unix.gmtime elapsed in
256      let sec = string_of_int tm.Unix.tm_sec ^ "''" in
257      let min = 
258        if tm.Unix.tm_min > 0 then (string_of_int tm.Unix.tm_min^"' ") else "" 
259      in
260      let hou = 
261        if tm.Unix.tm_hour > 0 then (string_of_int tm.Unix.tm_hour^"h ") else ""
262      in
263      HLog.message 
264        (sprintf "execution of %s completed in %s." fname (hou^min^sec));
265      pp_times fname true big_bang big_bang_u big_bang_s;
266      asserted
267 (* MATITA 1.0: debbo fare time_travel sulla ng_library?
268      LexiconSync.time_travel 
269        ~present:lexicon_status ~past:initial_lexicon_status;
270 *))
271   with 
272   (* all exceptions should be wrapped to allow lexicon-undo (LS.time_travel) *)
273   | exn when not matita_debug ->
274 (* MATITA 1.0: debbo fare time_travel sulla ng_library?
275        LexiconSync.time_travel ~present:lexicon ~past:initial_lexicon_status;
276  *       *)
277       pp_times fname false big_bang big_bang_u big_bang_s;
278       clean_exit baseuri exn
279
280 and assert_ng ~already_included ~compiling ~asserted ~include_paths mapath =
281  let _,baseuri,fullmapath,_ = Librarian.baseuri_of_script ~include_paths mapath in
282  if List.mem fullmapath asserted then asserted,false
283  else
284   begin
285    let baseuri = NUri.uri_of_string baseuri in
286    let ngtime_of baseuri =
287     let ngpath = NCicLibrary.ng_path_of_baseuri baseuri in
288     try
289      Some (Unix.stat ngpath).Unix.st_mtime
290     with Unix.Unix_error (Unix.ENOENT, "stat", f) when f = ngpath -> None in
291    let matime =
292     try (Unix.stat fullmapath).Unix.st_mtime
293     with Unix.Unix_error (Unix.ENOENT, "stat", f) when f = fullmapath -> assert false
294    in
295    let ngtime = ngtime_of baseuri in
296    let asserted,to_be_compiled =
297     match ngtime with
298        Some ngtime ->
299         let preamble = GrafiteTypes.Serializer.dependencies_of baseuri in
300         let asserted,children_bad =
301          List.fold_left
302           (fun (asserted,b) mapath ->
303             let asserted,b1 =
304               assert_ng ~already_included ~compiling ~asserted ~include_paths
305                mapath
306             in
307              asserted, b || b1
308               || let _,baseuri,_,_ =
309                    Librarian.baseuri_of_script ~include_paths mapath in
310                  let baseuri = NUri.uri_of_string baseuri in
311                   (match ngtime_of baseuri with
312                       Some child_ngtime -> child_ngtime > ngtime
313                     | None -> assert false)
314           ) (asserted,false) preamble
315         in
316          asserted, children_bad || matime > ngtime
317      | None -> asserted,true
318    in
319     if not to_be_compiled then fullmapath::asserted,false
320     else
321      if List.mem baseuri already_included then
322        (* maybe recompiling it I would get the same... *)
323        raise (AlreadyLoaded (lazy mapath))
324      else
325       let asserted = compile ~compiling ~asserted ~include_paths fullmapath in
326        fullmapath::asserted,true
327   end
328 ;;
329
330 let assert_ng ~include_paths mapath =
331  snd (assert_ng ~include_paths ~already_included:[] ~compiling:[] ~asserted:[]
332   mapath)
333 let get_ast status ~include_paths strm =
334  snd (get_ast status ~compiling:[] ~asserted:[] ~include_paths strm)