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