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