]> matita.cs.unibo.it Git - helm.git/blob - matita/matitacLib.ml
tagged 0.5.0-rc1
[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 of LexiconEngine.status
33
34 let out = ref ignore 
35 let set_callback f = out := f
36
37 let slash_n_RE = Pcre.regexp "\\n" ;;
38
39 let pp_ast_statement grafite_status stm =
40   let stm = GrafiteAstPp.pp_statement
41     ~map_unicode_to_tex:(Helm_registry.get_bool "matita.paste_unicode_as_tex")
42     ~term_pp:CicNotationPp.pp_term
43     ~lazy_term_pp:CicNotationPp.pp_term ~obj_pp:(CicNotationPp.pp_obj
44     CicNotationPp.pp_term) stm
45   in
46   let stm = Pcre.replace ~rex:slash_n_RE stm in
47   let stm =
48       if String.length stm > 50 then String.sub stm 0 50 ^ " ..."
49       else stm
50   in
51     HLog.debug ("Executing: ``" ^ stm ^ "''")
52 ;;
53
54 let clean_exit baseuri rc =
55   LibraryClean.clean_baseuris ~verbose:false [baseuri]; rc
56 ;;
57
58 let get_macro_context = function
59    | Some {GrafiteTypes.proof_status = GrafiteTypes.No_proof} -> []
60    | Some status                ->
61       let stack = GrafiteTypes.get_stack status in
62       let goal = Continuationals.Stack.find_goal stack in
63       GrafiteTypes.get_proof_context status goal
64    | None                       -> assert false
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 get_include_paths options =
101   let include_paths = 
102     try List.assoc "include_paths" options with Not_found -> "" 
103   in
104   let include_paths = Str.split (Str.regexp " ") include_paths in
105   let include_paths = 
106     include_paths @ 
107     Helm_registry.get_list Helm_registry.string "matita.includes" 
108   in
109     include_paths
110 ;;
111
112 let activate_extraction baseuri fname =
113  if Helm_registry.get_bool "matita.extract" then
114   let mangled_baseuri =
115    let baseuri = String.sub baseuri 5 (String.length baseuri - 5) in
116      let baseuri = Pcre.replace ~pat:"/" ~templ:"_" baseuri in
117       String.uncapitalize baseuri in
118   let f =
119     open_out
120      (Filename.dirname fname ^ "/" ^ mangled_baseuri ^ ".ml") in
121    LibrarySync.set_object_declaration_hook
122     (fun _ obj ->
123       output_string f (CicExportation.ppobj baseuri obj);
124       flush f);
125 ;;
126
127 let compile options fname =
128   let matita_debug = Helm_registry.get_bool "matita.debug" in
129   let include_paths = get_include_paths options in
130   let root,baseuri,fname,_tgt = 
131     Librarian.baseuri_of_script ~include_paths fname in
132   if Http_getter_storage.is_read_only baseuri then assert false;
133   activate_extraction baseuri fname ;
134   let grafite_status = GrafiteSync.init baseuri in
135   let lexicon_status = 
136     CicNotation2.load_notation ~include_paths:[]
137       BuildTimeConf.core_notation_script 
138   in
139   let initial_lexicon_status = lexicon_status in
140   let big_bang = Unix.gettimeofday () in
141   let { Unix.tms_utime = big_bang_u ; Unix.tms_stime = big_bang_s} = 
142     Unix.times () 
143   in
144   let time = Unix.time () in
145   try
146     (* sanity checks *)
147     let moo_fname = 
148      LibraryMisc.obj_file_of_baseuri ~must_exist:false ~baseuri ~writable:true
149     in
150     let lexicon_fname= 
151      LibraryMisc.lexicon_file_of_baseuri 
152        ~must_exist:false ~baseuri ~writable:true
153     in
154     (* cleanup of previously compiled objects *)
155     if (not (Http_getter_storage.is_empty ~local:true baseuri) ||
156         LibraryClean.db_uris_of_baseuri baseuri <> []) 
157       then begin
158       HLog.message ("baseuri " ^ baseuri ^ " is not empty");
159       HLog.message ("cleaning baseuri " ^ baseuri);
160       LibraryClean.clean_baseuris [baseuri];
161     end;
162     HLog.message ("compiling " ^ Filename.basename fname ^ " in " ^ baseuri);
163     if not (Helm_registry.get_bool "matita.verbose") then
164       (let cc = 
165         let rex = Str.regexp ".*opt$" in
166         if Str.string_match rex Sys.argv.(0) 0 then "matitac.opt"
167         else "matitac" 
168       in
169       let s = Printf.sprintf "%s %-35s " cc (cut (root^"/") fname) in
170       print_string s; flush stdout);
171     (* we dalay this error check until we print 'matitac file ' *)
172     assert (Http_getter_storage.is_empty ~local:true baseuri);
173     (* create dir for XML files *)
174     if not (Helm_registry.get_opt_default Helm_registry.bool "matita.nodisk"
175               ~default:false) 
176     then
177       HExtlib.mkdir 
178         (Filename.dirname 
179           (Http_getter.filename ~local:true ~writable:true (baseuri ^
180           "foo.con")));
181     let buf = Ulexing.from_utf8_channel (open_in fname) in
182     let print_cb =
183       if not (Helm_registry.get_bool "matita.verbose") then (fun _ _ -> ())
184       else pp_ast_statement
185     in
186     let grafite_status, lexicon_status =
187      let rec aux_for_dump x =
188      try
189       match
190        MatitaEngine.eval_from_stream ~first_statement_only:false ~include_paths
191         lexicon_status grafite_status buf x
192       with
193       | [] -> grafite_status, lexicon_status 
194       | ((grafite,lexicon),None)::_ -> grafite, lexicon
195       | ((_,l),Some _)::_ -> raise (AttemptToInsertAnAlias l)
196
197      with MatitaEngine.EnrichedWithLexiconStatus 
198             (GrafiteEngine.Macro (floc, f), lex_status) as exn ->
199             match f (get_macro_context (Some grafite_status)) with 
200             | _, GrafiteAst.Inline (_, style, suri, prefix) ->
201               let str =
202                ApplyTransformation.txt_of_inline_macro style suri prefix
203                 ~map_unicode_to_tex:(Helm_registry.get_bool
204                   "matita.paste_unicode_as_tex") in
205               !out str;
206               aux_for_dump x
207             |_-> raise exn
208      in
209        aux_for_dump print_cb
210     in
211     let elapsed = Unix.time () -. time in
212     let proof_status,moo_content_rev,lexicon_content_rev = 
213       grafite_status.proof_status, grafite_status.moo_content_rev, 
214        lexicon_status.LexiconEngine.lexicon_content_rev
215     in
216     if proof_status <> GrafiteTypes.No_proof then
217      (HLog.error
218       "there are still incomplete proofs at the end of the script"; 
219      pp_times fname false big_bang big_bang_u big_bang_s;
220      LexiconSync.time_travel 
221        ~present:lexicon_status ~past:initial_lexicon_status;
222      clean_exit baseuri false)
223     else
224      (if not (Helm_registry.get_bool "matita.moo" && 
225               Filename.check_suffix fname ".mma") then begin
226         (* FG: we do not generate .moo when dumping .mma files *)
227         GrafiteMarshal.save_moo moo_fname moo_content_rev;
228         LexiconMarshal.save_lexicon lexicon_fname lexicon_content_rev;
229      end;
230      let tm = Unix.gmtime elapsed in
231      let sec = string_of_int tm.Unix.tm_sec ^ "''" in
232      let min = 
233        if tm.Unix.tm_min > 0 then (string_of_int tm.Unix.tm_min^"' ") else "" 
234      in
235      let hou = 
236        if tm.Unix.tm_hour > 0 then (string_of_int tm.Unix.tm_hour^"h ") else ""
237      in
238      HLog.message 
239        (sprintf "execution of %s completed in %s." fname (hou^min^sec));
240      pp_times fname true big_bang big_bang_u big_bang_s;
241      LexiconSync.time_travel 
242        ~present:lexicon_status ~past:initial_lexicon_status;
243      true)
244   with 
245   (* all exceptions should be wrapped to allow lexicon-undo (LS.time_travel) *)
246   | AttemptToInsertAnAlias lexicon_status -> 
247      pp_times fname false big_bang big_bang_u big_bang_s;
248      LexiconSync.time_travel 
249        ~present:lexicon_status ~past:initial_lexicon_status;
250      clean_exit baseuri false
251   | MatitaEngine.EnrichedWithLexiconStatus (exn, lex_stat) as exn' ->
252       (match exn with
253       | Sys.Break -> HLog.error "user break!"
254       | HExtlib.Localized (floc,CicNotationParser.Parse_error err) ->
255           let (x, y) = HExtlib.loc_of_floc floc in
256           HLog.error (sprintf "Parse error at %d-%d: %s" x y err)
257       | exn when matita_debug -> raise exn'
258       | exn -> HLog.error (snd (MatitaExcPp.to_string exn)));
259       LexiconSync.time_travel ~present:lex_stat ~past:initial_lexicon_status;
260       pp_times fname false big_bang big_bang_u big_bang_s;
261       clean_exit baseuri false
262   | Sys.Break as exn ->
263      if matita_debug then raise exn; 
264      HLog.error "user break!";
265      pp_times fname false big_bang big_bang_u big_bang_s;
266      clean_exit baseuri false
267   | exn ->
268        if matita_debug then raise exn; 
269        HLog.error 
270          ("Unwrapped exception, please fix: "^ snd (MatitaExcPp.to_string exn));
271        pp_times fname false big_bang big_bang_u big_bang_s;
272        clean_exit baseuri false
273
274 module F = 
275   struct 
276     type source_object = string
277     type target_object = string
278     let string_of_source_object s = s;;
279     let string_of_target_object s = s;;
280
281     let is_readonly_buri_of opts file = 
282      let buri = List.assoc "baseuri" opts in
283      Http_getter_storage.is_read_only (Librarian.mk_baseuri buri file)
284
285     let root_and_target_of opts mafile = 
286       try
287         let include_paths = get_include_paths opts in
288         let root,baseuri,_,_ =
289           Librarian.baseuri_of_script ~include_paths mafile 
290         in
291         Some root, LibraryMisc.obj_file_of_baseuri 
292           ~must_exist:false ~baseuri ~writable:true 
293       with Librarian.NoRootFor x -> None, ""
294
295     let mtime_of_source_object s =
296       try Some (Unix.stat s).Unix.st_mtime
297       with Unix.Unix_error (Unix.ENOENT, "stat", f) when f = s -> None
298
299     let mtime_of_target_object s =
300       try Some (Unix.stat s).Unix.st_mtime
301       with Unix.Unix_error (Unix.ENOENT, "stat", f) when f = s -> None
302
303     let build = compile;;
304
305     let load_deps_file = Librarian.load_deps_file;;
306
307   end 
308
309 module Make = Librarian.Make(F) 
310