]> matita.cs.unibo.it Git - helm.git/blob - matita/matita/matitaEngine.ml
porting to recent ocaml
[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 open Printf
29
30 class status baseuri =
31  object
32   inherit GrafiteTypes.status baseuri
33   inherit ApplyTransformation.status
34  end
35
36 exception TryingToAdd of string Lazy.t
37 exception EnrichedWithStatus of exn * status
38 exception AlreadyLoaded of string Lazy.t
39 exception FailureCompiling of string * exn
40 exception CircularDependency of string
41
42 let debug = false ;;
43 let debug_print = if debug then prerr_endline else ignore ;;
44
45 let slash_n_RE = Pcre.regexp "\\n" ;;
46
47 let pp_ast_statement status stm =
48   let stm = GrafiteAstPp.pp_statement status stm
49     ~map_unicode_to_tex:(Helm_registry.get_bool "matita.paste_unicode_as_tex")
50   in
51   let stm = Pcre.replace ~rex:slash_n_RE stm in
52   let stm =
53       if String.length stm > 50 then String.sub stm 0 50 ^ " ..."
54       else stm
55   in
56     HLog.debug ("Executing: ``" ^ stm ^ "''")
57 ;;
58
59 let clean_exit baseuri exn =
60   LibraryClean.clean_baseuris ~verbose:false [baseuri];
61   raise (FailureCompiling (baseuri,exn))
62 ;;
63
64 let cut prefix s = 
65   let lenp = String.length prefix in
66   let lens = String.length s in
67   assert (lens > lenp);
68   assert (String.sub s 0 lenp = prefix);
69   String.sub s lenp (lens-lenp)
70 ;;
71
72 let print_string = 
73  let indent = ref 0 in
74  let print_string ~right_justify s =
75   let ss =
76    match right_justify with
77       None -> ""
78     | Some (ss,len_ss) ->
79        let i = 80 - !indent - len_ss - String.length s in
80        if i > 0 then String.make i ' ' ^ ss else ss
81   in
82    assert (!indent >=0);
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 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    let time0 = Unix.gettimeofday () in
119    let status =
120      GrafiteEngine.eval_ast ~include_paths ?do_heavy_checks status
121       (text,prefix_len,ast) in
122    let time1 = Unix.gettimeofday () in
123    HLog.debug ("... grafite_engine done in " ^ string_of_float (time1 -. time0) ^ "s");
124    status
125    ) 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
220                 (_,(GrafiteAst.Include _ | GrafiteAst.Notation _)))) ->
221               GrafiteParser.parsable_statement status
222                (GrafiteParser.strm_of_parsable str)
223           | _ -> str
224         in
225          asserted, false, status, str
226    with exn when not matita_debug ->
227      raise (EnrichedWithStatus (exn, status))
228   in
229   if stop then asserted,status else loop asserted status str
230  in
231   loop asserted status str
232
233 and compile ~compiling ~asserted ~include_paths fname =
234   if List.mem fname compiling then raise (CircularDependency fname);
235   let compiling = fname::compiling in
236   let matita_debug = Helm_registry.get_bool "matita.debug" in
237   let root,baseuri,fname,_tgt = 
238     Librarian.baseuri_of_script ~include_paths fname in
239   if Http_getter_storage.is_read_only baseuri then assert false;
240   (* MATITA 1.0: debbo fare time_travel sulla ng_library? *)
241   let status = new status baseuri in
242   (*CSC: bad, one imperative bit is still there!
243          to be moved into functional status *)
244   NCicMetaSubst.pushmaxmeta ();
245   let ocamldirname = Filename.dirname fname in
246   let ocamlfname = Filename.chop_extension (Filename.basename fname) in
247   let status,ocamlfname =
248    Common.modname_of_filename status false ocamlfname in
249   let ocamlfname = ocamldirname ^ "/" ^ ocamlfname ^ ".ml" in
250   let status = OcamlExtraction.open_file status ~baseuri ocamlfname in
251   let big_bang = Unix.gettimeofday () in
252   let { Unix.tms_utime = big_bang_u ; Unix.tms_stime = big_bang_s} = 
253     Unix.times () 
254   in
255   let time = Unix.time () in
256   let cc = 
257    let rex = Str.regexp ".*opt$" in
258    if Str.string_match rex Sys.argv.(0) 0 then "matitac.opt"
259    else "matitac" in
260   let s = Printf.sprintf "%s %s" cc (cut (root^"/") fname) in
261   try
262     (* cleanup of previously compiled objects *)
263     if (not (Http_getter_storage.is_empty ~local:true baseuri))
264       then begin
265       HLog.message ("baseuri " ^ baseuri ^ " is not empty");
266       HLog.message ("cleaning baseuri " ^ baseuri);
267       LibraryClean.clean_baseuris [baseuri];
268     end;
269     HLog.message ("compiling " ^ Filename.basename fname ^ " in " ^ baseuri);
270     if not (Helm_registry.get_bool "matita.verbose") then
271      (print_string true (s ^ "\n"); flush stdout);
272     (* we dalay this error check until we print 'matitac file ' *)
273     assert (Http_getter_storage.is_empty ~local:true baseuri);
274     (* create dir for XML files *)
275     if not (Helm_registry.get_opt_default Helm_registry.bool "matita.nodisk"
276               ~default:false) 
277     then
278       HExtlib.mkdir 
279         (Filename.dirname 
280           (Http_getter.filename ~local:true ~writable:true (baseuri ^
281           "foo.con")));
282     let buf =
283      GrafiteParser.parsable_statement status
284       (Ulexing.from_utf8_channel (open_in fname))
285     in
286     let print_cb =
287       if not (Helm_registry.get_bool "matita.verbose") then (fun _ _ -> ())
288       else pp_ast_statement
289     in
290     let asserted, status =
291      eval_from_stream ~compiling ~asserted ~include_paths status buf print_cb in
292     let status = OcamlExtraction.close_file status in
293     let elapsed = Unix.time () -. time in
294      (if Helm_registry.get_bool "matita.moo" then begin
295        GrafiteTypes.Serializer.serialize ~baseuri:(NUri.uri_of_string baseuri)
296         status
297      end;
298      let tm = Unix.gmtime elapsed in
299      let sec = string_of_int tm.Unix.tm_sec ^ "''" in
300      let min = 
301        if tm.Unix.tm_min > 0 then (string_of_int tm.Unix.tm_min^"' ") else "" 
302      in
303      let hou = 
304        if tm.Unix.tm_hour > 0 then (string_of_int tm.Unix.tm_hour^"h ") else ""
305      in
306      HLog.message 
307        (sprintf "execution of %s completed in %s." fname (hou^min^sec));
308      pp_times s fname true big_bang big_bang_u big_bang_s;
309      (*CSC: bad, one imperative bit is still there!
310             to be moved into functional status *)
311      NCicMetaSubst.pushmaxmeta ();
312 (* MATITA 1.0: debbo fare time_travel sulla ng_library?
313      LexiconSync.time_travel 
314        ~present:lexicon_status ~past:initial_lexicon_status;
315 *)
316      asserted)
317   with 
318   (* all exceptions should be wrapped to allow lexicon-undo (LS.time_travel) *)
319   | exn when not matita_debug ->
320 (* MATITA 1.0: debbo fare time_travel sulla ng_library?
321        LexiconSync.time_travel ~present:lexicon ~past:initial_lexicon_status;
322  *       *)
323       (*CSC: bad, one imperative bit is still there!
324              to be moved into functional status *)
325       NCicMetaSubst.pushmaxmeta ();
326       pp_times s fname false big_bang big_bang_u big_bang_s;
327       clean_exit baseuri exn
328
329 and assert_ng ~already_included ~compiling ~asserted ~include_paths mapath =
330  let root,baseuri,fullmapath,_ =
331   Librarian.baseuri_of_script ~include_paths mapath in
332  if List.mem fullmapath asserted then asserted,false
333  else
334   begin
335    let include_paths =
336     let includes =
337      try
338       Str.split (Str.regexp " ") 
339        (List.assoc "include_paths" (Librarian.load_root_file (root^"/root")))
340      with Not_found -> []
341     in
342      root::includes @
343       Helm_registry.get_list Helm_registry.string "matita.includes" in
344    let baseuri = NUri.uri_of_string baseuri in
345    let ngtime_of baseuri =
346     let ngpath = NCicLibrary.ng_path_of_baseuri baseuri in
347     try
348      Some (Unix.stat ngpath).Unix.st_mtime
349     with Unix.Unix_error (Unix.ENOENT, "stat", f) when f = ngpath -> None in
350    let matime =
351     try (Unix.stat fullmapath).Unix.st_mtime
352     with Unix.Unix_error (Unix.ENOENT, "stat", f) when f = fullmapath -> assert false
353    in
354    let ngtime = ngtime_of baseuri in
355    let asserted,to_be_compiled =
356     match ngtime with
357        Some ngtime ->
358         let preamble = GrafiteTypes.Serializer.dependencies_of baseuri in
359         let asserted,children_bad =
360          List.fold_left
361           (fun (asserted,b) mapath -> 
362             let asserted,b1 =
363               try 
364                assert_ng ~already_included ~compiling ~asserted ~include_paths
365                 mapath
366               with Librarian.NoRootFor _ | Librarian.FileNotFound _ ->
367                 asserted, true 
368             in
369              asserted, b || b1
370               || let _,baseuri,_,_ =
371                    (*CSC: bug here? include_paths should be empty and
372                           mapath should be absolute *)
373                    Librarian.baseuri_of_script ~include_paths mapath in
374                  let baseuri = NUri.uri_of_string baseuri in
375                   (match ngtime_of baseuri with
376                       Some child_ngtime -> child_ngtime > ngtime
377                     | None -> assert false)
378           ) (asserted,false) preamble
379         in
380          asserted, children_bad || matime > ngtime
381      | None -> asserted,true
382    in
383     if not to_be_compiled then fullmapath::asserted,false
384     else
385      if List.mem baseuri already_included then
386        (* maybe recompiling it I would get the same... *)
387        raise (AlreadyLoaded (lazy mapath))
388      else
389       let asserted = compile ~compiling ~asserted ~include_paths fullmapath in
390        fullmapath::asserted,true
391   end
392 ;;
393
394 let assert_ng ~include_paths mapath =
395  snd (assert_ng ~include_paths ~already_included:[] ~compiling:[] ~asserted:[]
396   mapath)
397 let get_ast status ~include_paths strm =
398  snd (get_ast status ~compiling:[] ~asserted:[] ~include_paths strm)