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