]> matita.cs.unibo.it Git - helm.git/blob - matitaB/matita/matitaEngine.ml
Matitaweb:
[helm.git] / matitaB / 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 uid baseuri =
33  object
34   inherit GrafiteTypes.status uid baseuri
35   inherit ApplyTransformation.status uid
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 as ast') =
120  let baseuri = status#baseuri in
121    GrafiteEngine.eval_ast ~include_paths ?do_heavy_checks status ast'
122 ;;
123
124 let baseuri_of_script ~include_paths fname =
125  try Librarian.baseuri_of_script ~include_paths fname
126  with
127    Librarian.NoRootFor _ -> 
128     HLog.error ("The included file '"^fname^"' has no root file,");
129     HLog.error "please create it.";
130     raise (Failure ("No root file for "^fname))
131   | Librarian.FileNotFound _ -> 
132     raise (Failure ("File not found: "^fname))
133 ;;
134
135 let rec get_ast status ~compiling ~asserted ~include_paths strm = 
136   match GrafiteParser.parse_statement status strm with
137      (GrafiteAst.Executable
138        (_,GrafiteAst.NCommand (_,GrafiteAst.Include (_,_,mafilename)))) as cmd
139      ->
140        let already_included = NCicLibrary.get_transitively_included status in
141        let asserted,_ =
142         assert_ng ~already_included ~compiling ~asserted ~include_paths
143          ?uid:status#user mafilename
144        in
145         asserted,cmd
146    | cmd -> asserted,cmd
147
148 and eval_from_stream ~compiling ~asserted ~include_paths ?do_heavy_checks status str cb =
149  let matita_debug = Helm_registry.get_bool "matita.debug" in
150  let rec loop asserted status str =
151   let asserted,stop,status,str = 
152    try
153      let cont =
154        try Some (get_ast status ~compiling ~asserted ~include_paths str)
155        with End_of_file -> None in
156      match cont with
157      | None -> asserted, true, status, str
158      | Some (asserted,ast) ->
159         (* pp_ast_statement status ast; *)
160         cb status ast;
161         let status =
162           eval_ast ~include_paths ?do_heavy_checks status ("",0,ast)
163         in
164         let str =
165          match ast with
166             (GrafiteAst.Executable
167               (_,GrafiteAst.NCommand
168                 (_,(GrafiteAst.Include _ | GrafiteAst.Notation _)))) ->
169               GrafiteParser.parsable_statement status
170                (GrafiteParser.strm_of_parsable str)
171           | _ -> str
172         in
173          asserted, false, status, str
174    with exn when not matita_debug ->
175      prerr_endline ("EnrichedWithStatus: " ^ Printexc.to_string exn);
176      raise (EnrichedWithStatus (exn, status))
177   in
178   if stop then asserted,status else loop asserted status str
179  in
180   loop asserted status str
181
182 and compile ~compiling ~asserted ~include_paths ~outch ?uid fname =
183   if List.mem fname compiling then raise (CircularDependency fname);
184   let compiling = fname::compiling in
185   let matita_debug = Helm_registry.get_bool "matita.debug" in
186   let matita_debug = true in
187   let root,baseuri,fname,_tgt = 
188     Librarian.baseuri_of_script ~include_paths fname in
189   if Http_getter_storage.is_read_only baseuri then assert false;
190   activate_extraction baseuri fname ;
191   (* MATITA 1.0: debbo fare time_travel sulla ng_library? *)
192   (* FIXME: currently hardcoded to single user mode *)
193   let status = new status uid baseuri in
194   let big_bang = Unix.gettimeofday () in
195   let { Unix.tms_utime = big_bang_u ; Unix.tms_stime = big_bang_s} = 
196     Unix.times () 
197   in
198   let time = Unix.time () in
199   try
200     (* cleanup of previously compiled objects *)
201     if (not (Http_getter_storage.is_empty ~local:true baseuri))
202       then begin
203       HLog.message ("baseuri " ^ baseuri ^ " is not empty");
204       HLog.message ("cleaning baseuri " ^ baseuri);
205       LibraryClean.clean_baseuris [baseuri];
206     end;
207     HLog.message ("compiling " ^ Filename.basename fname ^ " in " ^ baseuri);
208     if not (Helm_registry.get_bool "matita.verbose") then
209       (let cc = 
210         let rex = Str.regexp ".*opt$" in
211         if Str.string_match rex Sys.argv.(0) 0 then "matitac.opt"
212         else "matitac" 
213       in
214       let s = Printf.sprintf "%s %-35s " cc (cut (root^"/") fname) in
215       print_string s; flush stdout);
216     (* we dalay this error check until we print 'matitac file ' *)
217     assert (Http_getter_storage.is_empty ~local:true baseuri);
218     (* create dir for XML files *)
219     if not (Helm_registry.get_opt_default Helm_registry.bool "matita.nodisk"
220               ~default:false) 
221     then
222       HExtlib.mkdir 
223         (Filename.dirname 
224           (Http_getter.filename ~local:true ~writable:true (baseuri ^
225           "foo.con")));
226     prerr_endline ("trying to compile " ^ fname); 
227     let buf =
228      GrafiteParser.parsable_statement status
229       (Ulexing.from_utf8_channel (open_in fname))
230     in
231     let print_cb =
232       if not (Helm_registry.get_bool "matita.verbose") then (fun _ _ -> ())
233       else pp_ast_statement
234     in
235     let asserted, status =
236      eval_from_stream ~compiling ~asserted ~include_paths status buf print_cb in
237     prerr_endline ("end compile of " ^ fname); 
238     let elapsed = Unix.time () -. time in
239      (if Helm_registry.get_bool "matita.moo" then begin
240        GrafiteTypes.Serializer.serialize ~baseuri:(NUri.uri_of_string baseuri)
241         status
242      end;
243      let tm = Unix.gmtime elapsed in
244      let sec = string_of_int tm.Unix.tm_sec ^ "''" in
245      let min = 
246        if tm.Unix.tm_min > 0 then (string_of_int tm.Unix.tm_min^"' ") else "" 
247      in
248      let hou = 
249        if tm.Unix.tm_hour > 0 then (string_of_int tm.Unix.tm_hour^"h ") else ""
250      in
251      HLog.message 
252        (sprintf "execution of %s completed in %s." fname (hou^min^sec));
253      pp_times fname true big_bang big_bang_u big_bang_s;
254      prerr_endline ("now generating disambiguated script for " ^ fname);
255      let origbuf = Ulexing.from_utf8_channel (open_in fname) in
256      let interpr = GrafiteDisambiguate.get_interpr status#disambiguate_db in
257      let outstr = ref "" in
258      ignore (SmallLexer.mk_small_printer interpr outstr origbuf);
259      Printf.fprintf outch "%s" !outstr;
260      prerr_endline ("returning after compilation of " ^ fname);
261      asserted
262 (* MATITA 1.0: debbo fare time_travel sulla ng_library?
263      LexiconSync.time_travel 
264        ~present:lexicon_status ~past:initial_lexicon_status;
265 *))
266   with 
267   (* all exceptions should be wrapped to allow lexicon-undo (LS.time_travel) *)
268   | exn when not matita_debug -> 
269 (* MATITA 1.0: debbo fare time_travel sulla ng_library?
270        LexiconSync.time_travel ~present:lexicon ~past:initial_lexicon_status;
271  *       *)
272       pp_times fname false big_bang big_bang_u big_bang_s;
273       clean_exit baseuri exn
274
275 and assert_ng ~already_included ~compiling ~asserted ~include_paths ?outch ?uid mapath =
276  let _,baseuri,fullmapath,_ = Librarian.baseuri_of_script ~include_paths mapath in
277  if List.mem fullmapath asserted then asserted,false
278  else
279   begin
280    let baseuri = NUri.uri_of_string baseuri in
281    let ngtime_of baseuri =
282     let ngpath = NCicLibrary.ng_path_of_baseuri uid baseuri in
283     let uid = match uid with Some u -> "Some " ^ u | _ -> "None" in
284     prerr_endline ("uid = " ^ uid);
285     prerr_endline ("ngpath = " ^ ngpath);
286     try
287      Some (Unix.stat ngpath).Unix.st_mtime
288     with Unix.Unix_error (Unix.ENOENT, "stat", f) when f = ngpath -> None in
289    let matime =
290     try (Unix.stat fullmapath).Unix.st_mtime
291     with Unix.Unix_error (Unix.ENOENT, "stat", f) when f = fullmapath -> assert false
292    in
293    let ngtime = ngtime_of baseuri in
294    let asserted,to_be_compiled =
295     match ngtime with
296        Some ngtime ->
297         let preamble = GrafiteTypes.Serializer.dependencies_of uid baseuri in
298         let asserted,children_bad =
299          List.fold_left
300           (fun (asserted,b) mapath ->
301             let asserted,b1 =
302               assert_ng ~already_included ~compiling ~asserted ~include_paths
303                 ?uid mapath
304             in
305              asserted, b || b1
306               || let _,baseuri,_,_ =
307                    Librarian.baseuri_of_script ~include_paths mapath in
308                  let baseuri = NUri.uri_of_string baseuri in
309                   (match ngtime_of baseuri with
310                       Some child_ngtime -> child_ngtime > ngtime
311                     | None -> assert false)
312           ) (asserted,false) preamble
313         in
314          asserted, children_bad || matime > ngtime
315      | None -> asserted,true
316    in
317     prerr_endline ("asserted = " ^ (String.concat "," asserted));
318     if not to_be_compiled then fullmapath::asserted,false
319     else
320      if List.mem baseuri already_included then
321        (* maybe recompiling it I would get the same... *)
322        raise (AlreadyLoaded (lazy mapath))
323      else
324       let outch, is_file_ch = 
325         match outch with
326         | None -> open_out (fullmapath ^ ".mad"), true
327         | Some c -> c, false
328       in
329       prerr_endline ("compiling " ^ fullmapath);
330       let asserted = compile ~compiling ~asserted ~include_paths ~outch ?uid fullmapath in
331        if is_file_ch then close_out outch;
332        fullmapath::asserted,true
333   end
334 ;;
335
336 let eos status s =
337   let only_dust_RE = Pcre.regexp "^(\\s|\n|%%[^\n]*\n)*$" in      
338   let rec is_there_only_comments status s = 
339   if Pcre.pmatch ~rex:only_dust_RE s then raise End_of_file;
340   let strm =
341     GrafiteParser.parsable_statement status
342     (Ulexing.from_utf8_string s) in
343   match GrafiteParser.parse_statement status strm with
344   | GrafiteAst.Comment (loc,_) -> 
345       let _,parsed_text_length = HExtlib.utf8_parsed_text s loc in
346       (* CSC: why +1 in the following lines ???? *)
347       let parsed_text_length = parsed_text_length + 1 in
348       let remain_len = String.length s - parsed_text_length in
349       let next = String.sub s parsed_text_length remain_len in
350       is_there_only_comments status next
351   | GrafiteAst.Executable _ -> false
352  in
353  try is_there_only_comments status s
354   with 
355   | NCicLibrary.IncludedFileNotCompiled _
356   | HExtlib.Localized _
357   | CicNotationParser.Parse_error _ -> false
358   | End_of_file -> true
359   | Invalid_argument "Array.make" -> false
360 ;;
361
362
363 let assert_ng ~include_paths ?outch mapath =
364  snd (assert_ng ~include_paths ~already_included:[] ~compiling:[] ~asserted:[]
365   ?outch mapath)
366 let get_ast status ~include_paths strm =
367  snd (get_ast status ~compiling:[] ~asserted:[] ~include_paths strm)