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