]> matita.cs.unibo.it Git - helm.git/blob - helm/software/matita/matitacLib.ml
c14e5e3a60f4bd7b9b1ed8896bf6af1a7c840c30
[helm.git] / helm / software / 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 = 
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 extra = try Sys.getenv "BENCH_EXTRA_TEXT" with Not_found -> "" in
72     let rc,rcascii = 
73       if rc then "\e[0;32mOK\e[0m","Ok" else "\e[0;31mFAIL\e[0m","Fail" in
74     let times = 
75       let fmt t = 
76         let seconds = int_of_float t in
77         let cents = int_of_float ((t -. floor t) *. 100.0) in
78         let minutes = seconds / 60 in
79         let seconds = seconds mod 60 in
80         Printf.sprintf "%dm%02d.%02ds" minutes seconds cents
81       in
82       Printf.sprintf "%s %s %s" (fmt r) (fmt u) (fmt s)
83     in
84     let s = Printf.sprintf "%-4s %s %s" rc times extra in
85     print_endline s;
86     flush stdout;
87     HLog.message ("Compilation of "^Filename.basename fname^": "^rc)
88 ;;
89
90 let cut prefix s = 
91   let lenp = String.length prefix in
92   let lens = String.length s in
93   assert (lens > lenp);
94   assert (String.sub s 0 lenp = prefix);
95   String.sub s lenp (lens-lenp)
96 ;;
97
98 let get_include_paths options =
99   let include_paths = 
100     try List.assoc "include_paths" options with Not_found -> "" 
101   in
102   let include_paths = Str.split (Str.regexp " ") include_paths in
103   let include_paths = 
104     include_paths @ 
105     Helm_registry.get_list Helm_registry.string "matita.includes" 
106   in
107     include_paths
108 ;;
109
110 let compile options fname =
111   let matita_debug = Helm_registry.get_bool "matita.debug" in
112   let include_paths = get_include_paths options in
113   let root,baseuri,fname,_tgt = 
114     Librarian.baseuri_of_script ~include_paths fname in
115   let grafite_status = GrafiteSync.init baseuri in
116   let lexicon_status = 
117     CicNotation2.load_notation ~include_paths:[]
118       BuildTimeConf.core_notation_script 
119   in
120   let initial_lexicon_status = lexicon_status in
121   let big_bang = Unix.gettimeofday () in
122   let time = Unix.time () in
123   try
124     (* sanity checks *)
125     let moo_fname = 
126      LibraryMisc.obj_file_of_baseuri ~must_exist:false ~baseuri ~writable:true
127     in
128     let lexicon_fname= 
129      LibraryMisc.lexicon_file_of_baseuri 
130        ~must_exist:false ~baseuri ~writable:true
131     in
132     if Http_getter_storage.is_read_only baseuri then 
133       HLog.error 
134         (Printf.sprintf "uri %s belongs to a read-only repository" baseuri);
135     (* cleanup of previously compiled objects *)
136     if (not (Http_getter_storage.is_empty ~local:true baseuri) ||
137         LibraryClean.db_uris_of_baseuri baseuri <> []) 
138       then begin
139       HLog.message ("baseuri " ^ baseuri ^ " is not empty");
140       HLog.message ("cleaning baseuri " ^ baseuri);
141       LibraryClean.clean_baseuris [baseuri];
142     end;
143     HLog.message ("compiling " ^ Filename.basename fname ^ " in " ^ baseuri);
144     if not (Helm_registry.get_bool "matita.verbose") then
145       (let cc = 
146         let rex = Str.regexp ".*opt$" in
147         if Str.string_match rex Sys.argv.(0) 0 then "matitac.opt"
148         else "matitac" 
149       in
150       let s = Printf.sprintf "%s %-35s " cc (cut (root^"/") fname) in
151       print_string s; flush stdout);
152     (* we dalay this error check until we print 'matitac file ' *)
153     if (not (Http_getter_storage.is_empty ~local:true baseuri)) then begin
154       HLog.error ("Baseuri "^baseuri^" not cleaned! (probably readonly)");
155       (* Ugly hack *)
156       raise Sys.Break
157     end;
158     (* create dir for XML files *)
159     if not (Helm_registry.get_opt_default Helm_registry.bool "matita.nodisk"
160               ~default:false) 
161     then
162       HExtlib.mkdir 
163         (Filename.dirname 
164           (Http_getter.filename ~local:true ~writable:true (baseuri ^
165           "foo.con")));
166     let buf = Ulexing.from_utf8_channel (open_in fname) in
167     let print_cb =
168       if not (Helm_registry.get_bool "matita.verbose") then (fun _ _ -> ())
169       else pp_ast_statement
170     in
171     let grafite_status, lexicon_status =
172      let rec aux_for_dump x =
173      try
174       match
175        MatitaEngine.eval_from_stream ~first_statement_only:false ~include_paths
176         lexicon_status grafite_status buf x
177       with
178       | [] -> grafite_status, lexicon_status 
179       | ((grafite,lexicon),None)::_ -> grafite, lexicon
180       | ((_,l),Some _)::_ -> raise (AttemptToInsertAnAlias l)
181
182      with MatitaEngine.EnrichedWithLexiconStatus 
183             (GrafiteEngine.Macro (floc, f), lex_status) as exn ->
184             match f (get_macro_context (Some grafite_status)) with 
185             | _, GrafiteAst.Inline (_, style, suri, prefix) ->
186               let str =
187                ApplyTransformation.txt_of_inline_macro style suri prefix
188                 ~map_unicode_to_tex:(Helm_registry.get_bool
189                   "matita.paste_unicode_as_tex") in
190               !out str;
191               aux_for_dump x
192             |_-> raise exn
193      in
194        aux_for_dump print_cb
195     in
196     let elapsed = Unix.time () -. time in
197     let proof_status,moo_content_rev,lexicon_content_rev = 
198       grafite_status.proof_status, grafite_status.moo_content_rev, 
199        lexicon_status.LexiconEngine.lexicon_content_rev
200     in
201     if proof_status <> GrafiteTypes.No_proof then
202      (HLog.error
203       "there are still incomplete proofs at the end of the script"; 
204      pp_times fname false big_bang;
205      LexiconSync.time_travel 
206        ~present:lexicon_status ~past:initial_lexicon_status;
207      clean_exit baseuri false)
208     else
209      (if not (Helm_registry.get_bool "matita.moo" && 
210               Filename.check_suffix fname ".mma") then begin
211         (* FG: we do not generate .moo when dumping .mma files *)
212         GrafiteMarshal.save_moo moo_fname moo_content_rev;
213         LexiconMarshal.save_lexicon lexicon_fname lexicon_content_rev;
214      end;
215      let tm = Unix.gmtime elapsed in
216      let sec = string_of_int tm.Unix.tm_sec ^ "''" in
217      let min = 
218        if tm.Unix.tm_min > 0 then (string_of_int tm.Unix.tm_min^"' ") else "" 
219      in
220      let hou = 
221        if tm.Unix.tm_hour > 0 then (string_of_int tm.Unix.tm_hour^"h ") else ""
222      in
223      HLog.message 
224        (sprintf "execution of %s completed in %s." fname (hou^min^sec));
225      pp_times fname true big_bang;
226      LexiconSync.time_travel 
227        ~present:lexicon_status ~past:initial_lexicon_status;
228      true)
229   with 
230   (* all exceptions should be wrapped to allow lexicon-undo (LS.time_travel) *)
231   | AttemptToInsertAnAlias lexicon_status -> 
232      pp_times fname false big_bang;
233      LexiconSync.time_travel 
234        ~present:lexicon_status ~past:initial_lexicon_status;
235      clean_exit baseuri false
236   | MatitaEngine.EnrichedWithLexiconStatus (exn, lex_stat) ->
237       (match exn with
238       | Sys.Break -> HLog.error "user break!"
239       | HExtlib.Localized (floc,CicNotationParser.Parse_error err) ->
240           let (x, y) = HExtlib.loc_of_floc floc in
241           HLog.error (sprintf "Parse error at %d-%d: %s" x y err)
242       | exn -> HLog.error (snd (MatitaExcPp.to_string exn)));
243       LexiconSync.time_travel ~present:lex_stat ~past:initial_lexicon_status;
244       pp_times fname false big_bang;
245       clean_exit baseuri false
246   | Sys.Break as exn ->
247      if matita_debug then raise exn; 
248      HLog.error "user break!";
249      pp_times fname false big_bang;
250      clean_exit baseuri false
251   | exn ->
252        if matita_debug then raise exn; 
253        HLog.error 
254          ("Unwrapped exception, please fix: "^ snd (MatitaExcPp.to_string exn));
255        pp_times fname false big_bang;
256        clean_exit baseuri false
257 ;;
258
259 module F = 
260   struct 
261     type source_object = string
262     type target_object = string
263     let string_of_source_object s = s;;
264     let string_of_target_object s = s;;
265
266     let root_and_target_of opts mafile = 
267       try
268         let include_paths = get_include_paths opts in
269         let root,baseuri,_,_ =
270           Librarian.baseuri_of_script ~include_paths mafile 
271         in
272         Some root, LibraryMisc.obj_file_of_baseuri 
273           ~must_exist:false ~baseuri ~writable:true 
274       with Librarian.NoRootFor x -> None, ""
275     ;;
276
277     let mtime_of_source_object s =
278       try Some (Unix.stat s).Unix.st_mtime
279       with Unix.Unix_error (Unix.ENOENT, "stat", f) when f = s -> None
280     ;;
281
282     let mtime_of_target_object s =
283       try Some (Unix.stat s).Unix.st_mtime
284       with Unix.Unix_error (Unix.ENOENT, "stat", f) when f = s -> None
285     ;;
286
287     let build = compile;;
288
289     let load_deps_file = Librarian.load_deps_file;;
290
291   end 
292
293 module Make = Librarian.Make(F) 
294