]> matita.cs.unibo.it Git - helm.git/blob - matita/matita/matitaEngine.ml
Change Sort.merge (deprecated) with List.merge
[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 first_line = ref true ;;
50
51 let cases_or_induction_context stack =
52     match stack with
53      [] -> false
54     | (g,t,k,tag,p)::tl -> try
55                             let s = List.assoc "context" p in
56                             s = "cases" || s = "induction"
57                            with
58                             Not_found -> false
59 ;;
60
61 let has_focused_goal stack =
62     match stack with
63      [] -> false
64     | (g,t,k,tag,p)::tl -> (List.length g) > 0
65 ;;
66
67 let get_indentation status statement =
68   let base_ind =
69     match status#stack with
70       [] -> 0
71     | s -> List.length(s) * 2
72   in
73     if cases_or_induction_context status#stack then
74       (
75         if has_focused_goal status#stack then
76             base_ind + 2
77         else
78             base_ind
79       )
80     else
81       base_ind
82 ;;
83
84 let pp_ind s n =
85   let rec aux s n =
86     match n with
87       0 -> s
88     | n -> " " ^ (aux s (n-1))
89   in
90     aux s n
91
92 let write_ast_to_file status fname statement =
93   let indentation = get_indentation status statement in
94   let str = match statement with
95       G.Comment _ -> GrafiteAstPp.pp_statement status statement
96                        ~map_unicode_to_tex:(Helm_registry.get_bool "matita.paste_unicode_as_tex")
97     | G.Executable (_,code) ->
98       (
99         match code with
100           G.NTactic _ -> GrafiteAstPp.pp_statement status statement
101                            ~map_unicode_to_tex:(Helm_registry.get_bool "matita.paste_unicode_as_tex")
102         | G.NCommand (_,cmd) ->
103           (
104               match cmd with
105                 | G.NObj (_,obj,_) ->
106                         (
107                         match obj with
108                             Theorem _ -> "\n" ^ GrafiteAstPp.pp_statement status statement
109                                    ~map_unicode_to_tex:(Helm_registry.get_bool "matita.paste_unicode_as_tex")
110                         |   _ -> ""
111                         )
112                 | G.NQed _ -> GrafiteAstPp.pp_statement status statement
113                                    ~map_unicode_to_tex:(Helm_registry.get_bool "matita.paste_unicode_as_tex")
114                 | _ -> ""
115           )
116         | _ -> ""
117       )
118   in
119     if str <> "" then
120       (
121         let s = pp_ind str indentation in
122         let flaglist = if !first_line = false then [Open_wronly; Open_append; Open_creat]
123           else (first_line := false; [Open_wronly; Open_trunc; Open_creat])
124         in
125         let out_channel =
126           Stdlib.open_out_gen flaglist 0o0644 fname in
127         let _ = Stdlib.output_string out_channel ((if str.[0] <> '\n' then s else str) ^ "\n") in
128         let _ = Stdlib.close_out out_channel in
129         str
130       )
131     else
132       str
133 ;;
134
135 let pp_ast_statement status stm ~fname =
136   let stm = write_ast_to_file status (fname ^ ".parsed.ma") stm in
137   if stm <> "" then
138   (
139     let stm = Pcre.replace ~rex:slash_n_RE stm in
140     let stm =
141       if String.length stm > 50 then String.sub stm 0 50 ^ " ..."
142       else stm
143     in
144     HLog.debug ("Executing: ``" ^ stm ^ "''")
145   )
146   else
147     HLog.debug ("Executing: `` Unprintable statement ''")
148 ;;
149
150 let clean_exit baseuri exn =
151   LibraryClean.clean_baseuris ~verbose:false [baseuri];
152   raise (FailureCompiling (baseuri,exn))
153 ;;
154
155 let cut prefix s =
156   let lenp = String.length prefix in
157   let lens = String.length s in
158   assert (lens > lenp);
159   assert (String.sub s 0 lenp = prefix);
160   String.sub s lenp (lens-lenp)
161 ;;
162
163 let print_string =
164   let indent = ref 0 in
165   let print_string ~right_justify s =
166     let ss =
167       match right_justify with
168         None -> ""
169       | Some (ss,len_ss) ->
170         let i = 80 - !indent - len_ss - String.length s in
171         if i > 0 then String.make i ' ' ^ ss else ss
172     in
173     assert (!indent >=0);
174     print_string (String.make !indent ' ' ^ s ^ ss) in
175   fun enter ?right_justify s ->
176     if enter then (print_string ~right_justify s; incr indent) else (decr indent; print_string ~right_justify s)
177 ;;
178
179 let pp_times ss fname rc big_bang big_bang_u big_bang_s =
180   if not (Helm_registry.get_bool "matita.verbose") then
181     let { Unix.tms_utime = u ; Unix.tms_stime = s} = Unix.times () in
182     let r = Unix.gettimeofday () -. big_bang in
183     let u = u -. big_bang_u in
184     let s = s -. big_bang_s in
185     let extra = try Sys.getenv "BENCH_EXTRA_TEXT" with Not_found -> "" in
186     let rc =
187       if rc then "\e[0;32mOK\e[0m" else "\e[0;31mFAIL\e[0m" in
188     let times =
189       let fmt t =
190         let seconds = int_of_float t in
191         let cents = int_of_float ((t -. floor t) *. 100.0) in
192         let minutes = seconds / 60 in
193         let seconds = seconds mod 60 in
194         Printf.sprintf "%dm%02d.%02ds" minutes seconds cents
195       in
196       Printf.sprintf "%s %s %s" (fmt r) (fmt u) (fmt s)
197     in
198     let s = Printf.sprintf "%-14s %s %s\n" rc times extra in
199     print_string false ~right_justify:(s,31) ss;
200     flush stdout;
201     HLog.message ("Compilation of "^Filename.basename fname^": "^rc)
202 ;;
203
204 let eval_ast ~include_paths ?do_heavy_checks status (text,prefix_len,ast) =
205   let baseuri = status#baseuri in
206   let new_aliases,new_status =
207     GrafiteDisambiguate.eval_with_new_aliases status
208       (fun status ->
209          let time0 = Unix.gettimeofday () in
210          let status =
211            GrafiteEngine.eval_ast ~include_paths ?do_heavy_checks status
212              (text,prefix_len,ast) in
213          let time1 = Unix.gettimeofday () in
214          HLog.debug ("... grafite_engine done in " ^ string_of_float (time1 -. time0) ^ "s");
215          status
216       ) in
217   let _,intermediate_states =
218     List.fold_left
219       (fun (status,acc) (k,value) ->
220          let v = GrafiteAst.description_of_alias value in
221          let b =
222            try
223              let NReference.Ref (uri,_) = NReference.reference_of_string v in
224              NUri.baseuri_of_uri uri = baseuri
225            with
226              NReference.IllFormedReference _ ->
227              false (* v is a description, not a URI *)
228          in
229          if b then
230            status,acc
231          else
232            let status =
233              GrafiteDisambiguate.set_proof_aliases status ~implicit_aliases:false
234                GrafiteAst.WithPreferences [k,value]
235            in
236            status, (status ,Some (k,value))::acc
237       ) (status,[]) new_aliases (* WARNING: this must be the old status! *)
238   in
239   (new_status,None)::intermediate_states
240 ;;
241
242 let baseuri_of_script ~include_paths fname =
243   try Librarian.baseuri_of_script ~include_paths fname
244   with
245     Librarian.NoRootFor _ ->
246     HLog.error ("The included file '"^fname^"' has no root file,");
247     HLog.error "please create it.";
248     raise (Failure ("No root file for "^fname))
249   | Librarian.FileNotFound _ ->
250     raise (Failure ("File not found: "^fname))
251 ;;
252
253 (* given a path to a ma file inside the include_paths, returns the
254    new include_paths associated to that file *)
255 let read_include_paths ~include_paths file =
256   try
257     let root, _buri, _fname, _tgt =
258       Librarian.baseuri_of_script ~include_paths:[] file in
259     let includes =
260       try
261         Str.split (Str.regexp " ")
262           (List.assoc "include_paths" (Librarian.load_root_file (root^"/root")))
263       with Not_found -> []
264     in
265     let rc = root :: includes in
266     List.iter (HLog.debug) rc; rc
267   with Librarian.NoRootFor _ | Librarian.FileNotFound _ ->
268     []
269 ;;
270
271 let rec get_ast status ~compiling ~asserted ~include_paths strm =
272   match GrafiteParser.parse_statement status strm with
273     (GrafiteAst.Executable
274        (_,GrafiteAst.NCommand (_,GrafiteAst.Include (_,_,mafilename)))) as cmd
275     ->
276     let already_included = NCicLibrary.get_transitively_included status in
277     let asserted,_ =
278       assert_ng ~already_included ~compiling ~asserted ~include_paths
279         mafilename
280     in
281     asserted,cmd
282   | cmd -> asserted,cmd
283
284 and eval_from_stream ~compiling ~asserted ~include_paths ?do_heavy_checks status str cb =
285   let matita_debug = Helm_registry.get_bool "matita.debug" in
286   let rec loop asserted status str =
287     let asserted,stop,status,str =
288       try
289         let cont =
290           try Some (get_ast status ~compiling ~asserted ~include_paths str)
291           with End_of_file -> None in
292         match cont with
293         | None -> asserted, true, status, str
294         | Some (asserted,ast) ->
295           cb status ast;
296           let new_statuses =
297             eval_ast ~include_paths ?do_heavy_checks status ("",0,ast) in
298           let status =
299             match new_statuses with
300               [s,None] -> s
301             | _::(_,Some (_,value))::_ ->
302               raise (TryingToAdd (lazy (GrafiteAstPp.pp_alias value)))
303             | _ -> assert false in
304           (* CSC: complex patch to re-build the lexer since the tokens may
305              have changed. Note: this way we loose look-ahead tokens.
306              Hence the "include" command must be terminated (no look-ahead) *)
307           let str =
308             match ast with
309               (GrafiteAst.Executable
310                  (_,GrafiteAst.NCommand
311                     (_,(GrafiteAst.Include _ | GrafiteAst.Notation _)))) ->
312               GrafiteParser.parsable_statement status
313                 (GrafiteParser.strm_of_parsable str)
314             | _ -> str
315           in
316           asserted, false, status, str
317       with exn when not matita_debug ->
318         raise (EnrichedWithStatus (exn, status))
319     in
320     if stop then asserted,status else loop asserted status str
321   in
322   loop asserted status str
323
324 and compile ~compiling ~asserted ~include_paths fname =
325   if List.mem fname compiling then raise (CircularDependency fname);
326   let compiling = fname::compiling in
327   let matita_debug = Helm_registry.get_bool "matita.debug" in
328   let root,baseuri,fname,_tgt =
329     Librarian.baseuri_of_script ~include_paths fname in
330   if Http_getter_storage.is_read_only baseuri then assert false;
331   (* MATITA 1.0: debbo fare time_travel sulla ng_library? *)
332   let status = new status baseuri in
333   (*CSC: bad, one imperative bit is still there!
334          to be moved into functional status *)
335   NCicMetaSubst.pushmaxmeta ();
336   let ocamldirname = Filename.dirname fname in
337   let ocamlfname = Filename.chop_extension (Filename.basename fname) in
338   let status,ocamlfname =
339     Common.modname_of_filename status false ocamlfname in
340   let ocamlfname = ocamldirname ^ "/" ^ ocamlfname ^ ".ml" in
341   let status = OcamlExtraction.open_file status ~baseuri ocamlfname in
342   let big_bang = Unix.gettimeofday () in
343   let { Unix.tms_utime = big_bang_u ; Unix.tms_stime = big_bang_s} =
344     Unix.times ()
345   in
346   let time = Unix.time () in
347   let cc =
348     let rex = Str.regexp ".*opt$" in
349     if Str.string_match rex Sys.argv.(0) 0 then "matitac.opt"
350     else "matitac" in
351   let s = Printf.sprintf "%s %s" cc (cut (root^"/") fname) in
352   try
353     (* cleanup of previously compiled objects *)
354     if (not (Http_getter_storage.is_empty ~local:true baseuri))
355     then begin
356       HLog.message ("baseuri " ^ baseuri ^ " is not empty");
357       HLog.message ("cleaning baseuri " ^ baseuri);
358       LibraryClean.clean_baseuris [baseuri];
359     end;
360     HLog.message ("compiling " ^ Filename.basename fname ^ " in " ^ baseuri);
361     if not (Helm_registry.get_bool "matita.verbose") then
362       (print_string true (s ^ "\n"); flush stdout);
363     (* we dalay this error check until we print 'matitac file ' *)
364     assert (Http_getter_storage.is_empty ~local:true baseuri);
365     (* create dir for XML files *)
366     if not (Helm_registry.get_opt_default Helm_registry.bool "matita.nodisk"
367               ~default:false)
368     then
369       HExtlib.mkdir
370         (Filename.dirname
371            (Http_getter.filename ~local:true ~writable:true (baseuri ^
372                                                              "foo.con")));
373     let buf =
374       GrafiteParser.parsable_statement status
375         (Ulexing.from_utf8_channel (open_in fname))
376     in
377     let print_cb =
378       if not (Helm_registry.get_bool "matita.verbose") then fun _ _ -> ()
379       else pp_ast_statement ~fname
380     in
381     let asserted, status =
382       eval_from_stream ~compiling ~asserted ~include_paths status buf print_cb in
383     let status = OcamlExtraction.close_file status in
384     let elapsed = Unix.time () -. time in
385     (if Helm_registry.get_bool "matita.moo" then begin
386         GrafiteTypes.Serializer.serialize ~baseuri:(NUri.uri_of_string baseuri)
387           status
388       end;
389      let tm = Unix.gmtime elapsed in
390      let sec = string_of_int tm.Unix.tm_sec ^ "''" in
391      let min =
392        if tm.Unix.tm_min > 0 then (string_of_int tm.Unix.tm_min^"' ") else ""
393      in
394      let hou =
395        if tm.Unix.tm_hour > 0 then (string_of_int tm.Unix.tm_hour^"h ") else ""
396      in
397      HLog.message
398        (sprintf "execution of %s completed in %s." fname (hou^min^sec));
399      pp_times s fname true big_bang big_bang_u big_bang_s;
400      (*CSC: bad, one imperative bit is still there!
401             to be moved into functional status *)
402      NCicMetaSubst.pushmaxmeta ();
403      (* MATITA 1.0: debbo fare time_travel sulla ng_library?
404           LexiconSync.time_travel
405             ~present:lexicon_status ~past:initial_lexicon_status;
406      *)
407      asserted)
408   with
409   (* all exceptions should be wrapped to allow lexicon-undo (LS.time_travel) *)
410   | exn when not matita_debug ->
411     (* MATITA 1.0: debbo fare time_travel sulla ng_library?
412            LexiconSync.time_travel ~present:lexicon ~past:initial_lexicon_status;
413      *       *)
414     (*CSC: bad, one imperative bit is still there!
415            to be moved into functional status *)
416     NCicMetaSubst.pushmaxmeta ();
417     pp_times s fname false big_bang big_bang_u big_bang_s;
418     clean_exit baseuri exn
419
420 and assert_ng ~already_included ~compiling ~asserted ~include_paths mapath =
421   let root,baseuri,fullmapath,_ =
422     Librarian.baseuri_of_script ~include_paths mapath in
423   if List.mem fullmapath asserted then asserted,false
424   else
425     begin
426       let include_paths =
427         let includes =
428           try
429             Str.split (Str.regexp " ")
430               (List.assoc "include_paths" (Librarian.load_root_file (root^"/root")))
431           with Not_found -> []
432         in
433         root::includes @
434         Helm_registry.get_list Helm_registry.string "matita.includes" in
435       let baseuri = NUri.uri_of_string baseuri in
436       let ngtime_of baseuri =
437         let ngpath = NCicLibrary.ng_path_of_baseuri baseuri in
438         try
439           Some (Unix.stat ngpath).Unix.st_mtime
440         with Unix.Unix_error (Unix.ENOENT, "stat", f) when f = ngpath -> None in
441       let matime =
442         try (Unix.stat fullmapath).Unix.st_mtime
443         with Unix.Unix_error (Unix.ENOENT, "stat", f) when f = fullmapath -> assert false
444       in
445       let ngtime = ngtime_of baseuri in
446       let asserted,to_be_compiled =
447         match ngtime with
448           Some ngtime ->
449           let preamble = GrafiteTypes.Serializer.dependencies_of baseuri in
450           let asserted,children_bad =
451             List.fold_left
452               (fun (asserted,b) mapath ->
453                  let asserted,b1 =
454                    try
455                      assert_ng ~already_included ~compiling ~asserted ~include_paths
456                        mapath
457                    with Librarian.NoRootFor _ | Librarian.FileNotFound _ ->
458                      asserted, true
459                  in
460                  asserted, b || b1
461                            || let _,baseuri,_,_ =
462                                 (*CSC: bug here? include_paths should be empty and
463                                        mapath should be absolute *)
464                                 Librarian.baseuri_of_script ~include_paths mapath in
465                            let baseuri = NUri.uri_of_string baseuri in
466                            (match ngtime_of baseuri with
467                               Some child_ngtime -> child_ngtime > ngtime
468                             | None -> assert false)
469               ) (asserted,false) preamble
470           in
471           asserted, children_bad || matime > ngtime
472         | None -> asserted,true
473       in
474       if not to_be_compiled then fullmapath::asserted,false
475       else
476       if List.mem baseuri already_included then
477         (* maybe recompiling it I would get the same... *)
478         raise (AlreadyLoaded (lazy mapath))
479       else
480         let asserted = compile ~compiling ~asserted ~include_paths fullmapath in
481         fullmapath::asserted,true
482     end
483 ;;
484
485 let assert_ng ~include_paths mapath =
486   snd (assert_ng ~include_paths ~already_included:[] ~compiling:[] ~asserted:[]
487          mapath)
488 let get_ast status ~include_paths strm =
489   snd (get_ast status ~compiling:[] ~asserted:[] ~include_paths strm)