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