]> matita.cs.unibo.it Git - helm.git/blob - matita/matitacLib.ml
maxipatch for support of multiple DBs.
[helm.git] / matita / matitacLib.ml
1 (* Copyright (C) 2004-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 open GrafiteTypes
31
32 exception AttemptToInsertAnAlias
33
34 let out = ref ignore 
35
36 let set_callback f = out := f
37
38 let pp_ast_statement =
39   GrafiteAstPp.pp_statement ~term_pp:CicNotationPp.pp_term
40     ~lazy_term_pp:CicNotationPp.pp_term ~obj_pp:(CicNotationPp.pp_obj CicNotationPp.pp_term)
41
42 (** {2 Initialization} *)
43
44 let grafite_status = (ref None : GrafiteTypes.status option ref)
45 let lexicon_status = (ref None : LexiconEngine.status option ref)
46
47 let run_script is eval_function  =
48   let lexicon_status',grafite_status' = 
49     match !lexicon_status,!grafite_status with
50     | Some ss, Some s -> ss,s
51     | _,_ -> assert false
52   in
53   let slash_n_RE = Pcre.regexp "\\n" in
54   let cb = 
55     if Helm_registry.get_int "matita.verbosity" < 1 then 
56       (fun _ _ -> ())
57     else 
58       (fun grafite_status stm ->
59         (* dump_status grafite_status; *)
60         let stm = pp_ast_statement stm in
61         let stm = Pcre.replace ~rex:slash_n_RE stm in
62         let stm =
63           if String.length stm > 50 then
64             String.sub stm 0 50 ^ " ..."
65           else
66             stm
67         in
68         HLog.debug ("Executing: ``" ^ stm ^ "''"))
69   in
70   let matita_debug = Helm_registry.get_bool "matita.debug" in
71   try
72    match eval_function lexicon_status' grafite_status' is cb with
73       [] -> raise End_of_file
74     | ((grafite_status'',lexicon_status''),None)::_ ->
75        lexicon_status := Some lexicon_status'';
76        grafite_status := Some grafite_status''
77     | (s,Some _)::_ -> raise AttemptToInsertAnAlias
78   with
79   | GrafiteEngine.Drop  
80   | End_of_file
81   | CicNotationParser.Parse_error _ 
82   | GrafiteEngine.Macro _ as exn -> raise exn
83   | exn -> 
84       if not matita_debug then
85        HLog.error (snd (MatitaExcPp.to_string exn)) ;
86       raise exn
87
88 let fname () =
89   let rec aux = function
90   | ""::tl -> aux tl
91   | [x] -> x
92   | [] -> MatitaInit.die_usage ()
93   | l -> 
94       prerr_endline 
95         ("Wrong commands: " ^ 
96           String.concat " " (List.map (fun x -> "'" ^ x ^ "'") l));
97       MatitaInit.die_usage ()
98   in
99   aux (Helm_registry.get_list Helm_registry.string "matita.args")
100
101 let pp_ocaml_mode () = 
102   HLog.message "";
103   HLog.message "                      ** Entering Ocaml mode ** ";
104   HLog.message "";
105   HLog.message "Type 'go ();;' to enter an interactive matitac";
106   HLog.message ""
107   
108 let clean_exit n =
109  let opt_exit =
110   function
111      None -> ()
112    | Some n -> exit n
113  in
114   match !grafite_status with
115      None -> opt_exit n
116    | Some grafite_status ->
117       try
118        let baseuri = GrafiteTypes.get_string_option grafite_status "baseuri" in
119        LibraryClean.clean_baseuris ~verbose:false [baseuri];
120        opt_exit n
121       with GrafiteTypes.Option_error("baseuri", "not found") ->
122        (* no baseuri ==> nothing to clean yet *)
123        opt_exit n
124
125 let get_macro_context = function
126    | Some {GrafiteTypes.proof_status = GrafiteTypes.No_proof} -> []
127    | Some status                ->
128       let stack = GrafiteTypes.get_stack status in
129       let goal = Continuationals.Stack.find_goal stack in
130       GrafiteTypes.get_proof_context status goal
131    | None                       -> assert false
132    
133 let rec interactive_loop () = 
134   let str = Ulexing.from_utf8_channel stdin in
135   try
136     run_script str 
137       (MatitaEngine.eval_from_stream ~first_statement_only:false ~prompt:true
138       ~include_paths:(Helm_registry.get_list Helm_registry.string
139         "matita.includes"))
140   with 
141   | GrafiteEngine.Drop -> pp_ocaml_mode ()
142   | GrafiteEngine.Macro (floc, f) ->
143       begin match f (get_macro_context !grafite_status) with 
144        | _, GrafiteAst.Inline (_, style, suri, prefix) ->
145          let str = ApplyTransformation.txt_of_inline_macro style suri prefix in
146          !out str;
147          interactive_loop ()
148        | _ ->
149          let x, y = HExtlib.loc_of_floc floc in
150          HLog.error (sprintf "A macro has been found in a script at %d-%d" x y);
151          interactive_loop ()
152       end
153   | Sys.Break -> HLog.error "user break!"; interactive_loop ()
154   | GrafiteTypes.Command_error _ -> interactive_loop ()
155   | End_of_file ->
156      print_newline ();
157      clean_exit (Some 0)
158   | HExtlib.Localized (floc,CicNotationParser.Parse_error err) ->
159      let x, y = HExtlib.loc_of_floc floc in
160       HLog.error (sprintf "Parse error at %d-%d: %s" x y err);
161       interactive_loop ()
162   | exn -> HLog.error (Printexc.to_string exn); interactive_loop ()
163
164 let go () =
165   Helm_registry.load_from BuildTimeConf.matita_conf;
166   Http_getter.init ();
167   MetadataTypes.ownerize_tables (Helm_registry.get "matita.owner");
168   LibraryDb.create_owner_environment ();
169   CicEnvironment.set_trust (* environment trust *)
170     (let trust =
171       Helm_registry.get_opt_default Helm_registry.get_bool
172         ~default:true "matita.environment_trust" in
173      fun _ -> trust);
174   let include_paths =
175    Helm_registry.get_list Helm_registry.string "matita.includes" in
176   grafite_status := Some (GrafiteSync.init ());
177   lexicon_status :=
178    Some (CicNotation2.load_notation ~include_paths
179     BuildTimeConf.core_notation_script);
180   Sys.catch_break true;
181   interactive_loop ()
182
183 let pp_times fname bench_mode rc big_bang = 
184   if bench_mode then
185     begin
186       let { Unix.tms_utime = u ; Unix.tms_stime = s} = Unix.times () in
187       let r = Unix.gettimeofday () -. big_bang in
188       let extra = try Sys.getenv "BENCH_EXTRA_TEXT" with Not_found -> "" in
189       let cc = 
190         if Str.string_match (Str.regexp ".*opt$") Sys.argv.(0) 0 then 
191           "matitac.opt" 
192         else 
193           "matitac" 
194       in
195       let rc = if rc then "\e[0;32mOK\e[0m" else "\e[0;31mFAIL\e[0m" in
196       let times = 
197         let fmt t = 
198           let seconds = int_of_float t in
199           let cents = int_of_float ((t -. floor t) *. 100.0) in
200           let minutes = seconds / 60 in
201           let seconds = seconds mod 60 in
202           Printf.sprintf "%dm%02d.%02ds" minutes seconds cents
203         in
204         Printf.sprintf "%s %s %s" (fmt r) (fmt u) (fmt s)
205       in
206       let fname = 
207         match MatitamakeLib.development_for_dir (Filename.dirname fname) with
208         | None -> fname
209         | Some d -> 
210             let rootlen = String.length(MatitamakeLib.root_for_development d)in
211             let fnamelen = String.length fname in
212             assert (fnamelen > rootlen); 
213             String.sub fname rootlen (fnamelen - rootlen)           
214       in
215       let fname = 
216         if fname.[0] = '/' then
217           String.sub fname 1 (String.length fname - 1)
218         else
219           fname
220       in
221       let s = Printf.sprintf "%s %-35s %-4s %s %s" cc fname rc times extra in
222       print_endline s;
223       flush stdout
224     end
225 ;;
226
227 let rec compiler_loop fname big_bang mode buf =
228  let include_paths =
229   Helm_registry.get_list Helm_registry.string "matita.includes" in
230  let clean_baseuri = not (Helm_registry.get_bool "matita.preserve") in    
231  let matita_debug = Helm_registry.get_bool "matita.debug" in
232  let bench_mode =  Helm_registry.get_bool "matita.bench" in
233  try
234   run_script buf 
235    (MatitaEngine.eval_from_stream ~first_statement_only:false ~include_paths
236     ~clean_baseuri)
237  with 
238   | End_of_file -> ()
239   | Sys.Break as exn ->
240      if matita_debug then raise exn;
241       HLog.error "user break!";
242       pp_times fname bench_mode false big_bang;
243       if mode = `COMPILER then
244         clean_exit (Some ~-1)
245       else
246         pp_ocaml_mode ()
247   | GrafiteEngine.Drop ->
248       if mode = `COMPILER then 
249         begin
250           pp_times fname bench_mode false big_bang;
251           clean_exit (Some 1)
252         end
253       else 
254         pp_ocaml_mode ()
255   | GrafiteEngine.Macro (floc, f) ->
256       begin match f (get_macro_context !grafite_status) with 
257        | _, GrafiteAst.Inline (_, style, suri, prefix) ->
258          let str = ApplyTransformation.txt_of_inline_macro style suri prefix in
259          !out str;
260          compiler_loop fname big_bang mode buf
261        | _ ->
262          let x, y = HExtlib.loc_of_floc floc in
263          HLog.error (sprintf "A macro has been found in a script at %d-%d" x y);
264          if mode = `COMPILER then
265             begin 
266                pp_times fname bench_mode false big_bang;
267                clean_exit (Some 1)
268             end 
269          else 
270             pp_ocaml_mode ()
271       end
272   | HExtlib.Localized (floc,CicNotationParser.Parse_error err) ->
273      let (x, y) = HExtlib.loc_of_floc floc in
274      HLog.error (sprintf "Parse error at %d-%d: %s" x y err);
275      if mode = `COMPILER then
276        begin
277          pp_times fname bench_mode false big_bang;
278          clean_exit (Some 1)
279        end
280      else
281        pp_ocaml_mode ()
282   | exn ->
283       if matita_debug then raise exn;
284       if mode = `COMPILER then 
285         begin
286           pp_times fname bench_mode false big_bang;
287           clean_exit (Some 3)
288         end
289       else 
290         pp_ocaml_mode ()
291
292 let main ~mode = 
293   let big_bang = Unix.gettimeofday () in
294   MatitaInit.initialize_all ();
295   (* must be called after init since args are set by cmdline parsing *)
296   let fname = fname () in
297   let system_mode =  Helm_registry.get_bool "matita.system" in
298   let bench_mode =  Helm_registry.get_bool "matita.bench" in
299   if bench_mode then
300     Helm_registry.set_int "matita.verbosity" 0;
301   let include_paths =
302    Helm_registry.get_list Helm_registry.string "matita.includes" in
303   grafite_status := Some (GrafiteSync.init ());
304   lexicon_status :=
305    Some (CicNotation2.load_notation ~include_paths
306     BuildTimeConf.core_notation_script);
307   Sys.catch_break true;
308   let origcb = HLog.get_log_callback () in
309   let origcb t s = origcb t ((if system_mode then "[S] " else "") ^ s) in
310   let newcb tag s =
311     match tag with
312     | `Debug | `Message -> ()
313     | `Warning | `Error -> origcb tag s
314   in
315   if Helm_registry.get_int "matita.verbosity" < 1 then
316     HLog.set_log_callback newcb;
317   if bench_mode then MatitaMisc.shutup ();
318     let time = Unix.time () in
319     if Helm_registry.get_int "matita.verbosity" < 1 && not bench_mode then
320       origcb `Message ("compiling " ^ Filename.basename fname ^ "...")
321     else
322       HLog.message (sprintf "execution of %s started:" fname);
323     let ich = match fname with
324      | "stdin" -> stdin
325      | fname -> open_in fname
326     in
327     let buf = Ulexing.from_utf8_channel ich in
328     compiler_loop fname big_bang mode buf;
329     let elapsed = Unix.time () -. time in
330     let tm = Unix.gmtime elapsed in
331     let sec = string_of_int tm.Unix.tm_sec ^ "''" in
332     let min = 
333       if tm.Unix.tm_min > 0 then (string_of_int tm.Unix.tm_min ^ "' ") else "" 
334     in
335     let hou = 
336       if tm.Unix.tm_hour > 0 then (string_of_int tm.Unix.tm_hour ^ "h ") else ""
337     in
338     let proof_status,moo_content_rev,lexicon_content_rev = 
339       match !lexicon_status,!grafite_status with
340       | Some ss, Some s ->
341          s.proof_status, s.moo_content_rev, 
342           ss.LexiconEngine.lexicon_content_rev
343       | _,_ -> assert false
344     in
345     if proof_status <> GrafiteTypes.No_proof then
346      begin
347       HLog.error
348        "there are still incomplete proofs at the end of the script";
349       pp_times fname bench_mode true big_bang;
350       clean_exit (Some 2)
351      end
352     else
353      begin
354        let baseuri, _fullpathforfname =
355         DependenciesParser.baseuri_of_script ~include_paths fname in
356        let moo_fname = 
357          LibraryMisc.obj_file_of_baseuri 
358            ~must_exist:false ~baseuri ~writable:true 
359        in
360        let lexicon_fname= 
361          LibraryMisc.lexicon_file_of_baseuri 
362           ~must_exist:false ~baseuri ~writable:true 
363        in
364        GrafiteMarshal.save_moo moo_fname moo_content_rev;
365        LexiconMarshal.save_lexicon lexicon_fname lexicon_content_rev;
366        HLog.message 
367          (sprintf "execution of %s completed in %s." fname (hou^min^sec));
368        pp_times fname bench_mode true big_bang;
369        exit 0
370      end