]> matita.cs.unibo.it Git - helm.git/blob - matita/matita/matitacLib.ml
84606564547305589be35f4a2b9121c0d2dd7eb1
[helm.git] / matita / 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 let slash_n_RE = Pcre.regexp "\\n" ;;
33
34 let pp_ast_statement grafite_status stm =
35   let stm = GrafiteAstPp.pp_statement stm
36     ~map_unicode_to_tex:(Helm_registry.get_bool "matita.paste_unicode_as_tex")
37   in
38   let stm = Pcre.replace ~rex:slash_n_RE stm in
39   let stm =
40       if String.length stm > 50 then String.sub stm 0 50 ^ " ..."
41       else stm
42   in
43     HLog.debug ("Executing: ``" ^ stm ^ "''")
44 ;;
45
46 let clean_exit baseuri rc =
47   LibraryClean.clean_baseuris ~verbose:false [baseuri]; rc
48 ;;
49
50 let get_macro_context = function _ -> []
51 ;;
52    
53 let pp_times fname rc big_bang big_bang_u big_bang_s = 
54   if not (Helm_registry.get_bool "matita.verbose") then
55     let { Unix.tms_utime = u ; Unix.tms_stime = s} = Unix.times () in
56     let r = Unix.gettimeofday () -. big_bang in
57     let u = u -. big_bang_u in
58     let s = s -. big_bang_s in
59     let extra = try Sys.getenv "BENCH_EXTRA_TEXT" with Not_found -> "" in
60     let rc,rcascii = 
61       if rc then "\e[0;32mOK\e[0m","Ok" else "\e[0;31mFAIL\e[0m","Fail" in
62     let times = 
63       let fmt t = 
64         let seconds = int_of_float t in
65         let cents = int_of_float ((t -. floor t) *. 100.0) in
66         let minutes = seconds / 60 in
67         let seconds = seconds mod 60 in
68         Printf.sprintf "%dm%02d.%02ds" minutes seconds cents
69       in
70       Printf.sprintf "%s %s %s" (fmt r) (fmt u) (fmt s)
71     in
72     let s = Printf.sprintf "%-4s %s %s" rc times extra in
73     print_endline s;
74     flush stdout;
75     HLog.message ("Compilation of "^Filename.basename fname^": "^rc)
76 ;;
77
78 let cut prefix s = 
79   let lenp = String.length prefix in
80   let lens = String.length s in
81   assert (lens > lenp);
82   assert (String.sub s 0 lenp = prefix);
83   String.sub s lenp (lens-lenp)
84 ;;
85
86 let get_include_paths options =
87   let include_paths = 
88     try List.assoc "include_paths" options with Not_found -> "" 
89   in
90   let include_paths = Str.split (Str.regexp " ") include_paths in
91   let include_paths = 
92     include_paths @ 
93     Helm_registry.get_list Helm_registry.string "matita.includes" 
94   in
95     include_paths
96 ;;
97
98 let activate_extraction baseuri fname =
99   ()
100   (* MATITA 1.0
101  if Helm_registry.get_bool "matita.extract" then
102   let mangled_baseuri =
103    let baseuri = String.sub baseuri 5 (String.length baseuri - 5) in
104      let baseuri = Pcre.replace ~pat:"/" ~templ:"_" baseuri in
105       String.uncapitalize baseuri in
106   let f =
107     open_out
108      (Filename.dirname fname ^ "/" ^ mangled_baseuri ^ ".ml") in
109    LibrarySync.add_object_declaration_hook
110     (fun ~add_obj ~add_coercion _ obj ->
111       output_string f (CicExportation.ppobj baseuri obj);
112       flush f; []);
113       *)
114 ;;
115
116 let compile options fname =
117   let matita_debug = Helm_registry.get_bool "matita.debug" in
118   let include_paths = get_include_paths options in
119   let root,baseuri,fname,_tgt = 
120     Librarian.baseuri_of_script ~include_paths fname in
121   if Http_getter_storage.is_read_only baseuri then assert false;
122   activate_extraction baseuri fname ;
123   let grafite_status = new GrafiteTypes.status baseuri in
124   let big_bang = Unix.gettimeofday () in
125   let { Unix.tms_utime = big_bang_u ; Unix.tms_stime = big_bang_s} = 
126     Unix.times () 
127   in
128   let time = Unix.time () in
129   try
130     (* cleanup of previously compiled objects *)
131     if (not (Http_getter_storage.is_empty ~local:true baseuri))
132       then begin
133       HLog.message ("baseuri " ^ baseuri ^ " is not empty");
134       HLog.message ("cleaning baseuri " ^ baseuri);
135       LibraryClean.clean_baseuris [baseuri];
136     end;
137     HLog.message ("compiling " ^ Filename.basename fname ^ " in " ^ baseuri);
138     if not (Helm_registry.get_bool "matita.verbose") then
139       (let cc = 
140         let rex = Str.regexp ".*opt$" in
141         if Str.string_match rex Sys.argv.(0) 0 then "matitac.opt"
142         else "matitac" 
143       in
144       let s = Printf.sprintf "%s %-35s " cc (cut (root^"/") fname) in
145       print_string s; flush stdout);
146     (* we dalay this error check until we print 'matitac file ' *)
147     assert (Http_getter_storage.is_empty ~local:true baseuri);
148     (* create dir for XML files *)
149     if not (Helm_registry.get_opt_default Helm_registry.bool "matita.nodisk"
150               ~default:false) 
151     then
152       HExtlib.mkdir 
153         (Filename.dirname 
154           (Http_getter.filename ~local:true ~writable:true (baseuri ^
155           "foo.con")));
156     let buf = Ulexing.from_utf8_channel (open_in fname) in
157     let print_cb =
158       if not (Helm_registry.get_bool "matita.verbose") then (fun _ _ -> ())
159       else pp_ast_statement
160     in
161     let grafite_status =
162      MatitaEngine.eval_from_stream ~include_paths grafite_status buf print_cb
163     in
164     let elapsed = Unix.time () -. time in
165      (if Helm_registry.get_bool "matita.moo" then begin
166        GrafiteTypes.Serializer.serialize ~baseuri:(NUri.uri_of_string baseuri)
167         grafite_status#dump
168      end;
169      let tm = Unix.gmtime elapsed in
170      let sec = string_of_int tm.Unix.tm_sec ^ "''" in
171      let min = 
172        if tm.Unix.tm_min > 0 then (string_of_int tm.Unix.tm_min^"' ") else "" 
173      in
174      let hou = 
175        if tm.Unix.tm_hour > 0 then (string_of_int tm.Unix.tm_hour^"h ") else ""
176      in
177      HLog.message 
178        (sprintf "execution of %s completed in %s." fname (hou^min^sec));
179      pp_times fname true big_bang big_bang_u big_bang_s;
180 (*
181      LexiconSync.time_travel 
182        ~present:lexicon_status ~past:initial_lexicon_status;
183 *)
184      true)
185   with 
186   (* all exceptions should be wrapped to allow lexicon-undo (LS.time_travel) *)
187   | MatitaEngine.EnrichedWithStatus (exn, _grafite) as exn' ->
188       (match exn with
189       | Sys.Break -> HLog.error "user break!"
190       | HExtlib.Localized (floc,CicNotationParser.Parse_error err) ->
191           let (x, y) = HExtlib.loc_of_floc floc in
192           HLog.error (sprintf "Parse error at %d-%d: %s" x y err)
193       | exn when matita_debug -> raise exn'
194       | exn -> HLog.error (snd (MatitaExcPp.to_string exn))
195       );
196 (*       LexiconSync.time_travel ~present:lexicon ~past:initial_lexicon_status;
197  *       *)
198       pp_times fname false big_bang big_bang_u big_bang_s;
199       clean_exit baseuri false
200   | Sys.Break when not matita_debug ->
201      HLog.error "user break!";
202      pp_times fname false big_bang big_bang_u big_bang_s;
203      clean_exit baseuri false
204   | exn when not matita_debug ->
205        HLog.error 
206          ("Unwrapped exception, please fix: "^ snd (MatitaExcPp.to_string exn));
207        pp_times fname false big_bang big_bang_u big_bang_s;
208        clean_exit baseuri false
209
210 module F = 
211   struct 
212     type source_object = string
213     type target_object = string
214     let string_of_source_object s = s;;
215     let string_of_target_object s = s;;
216
217     let is_readonly_buri_of opts file = 
218      let buri = List.assoc "baseuri" opts in
219      Http_getter_storage.is_read_only (Librarian.mk_baseuri buri file)
220     ;;
221
222     let root_and_target_of opts mafile = 
223       try
224         let include_paths = get_include_paths opts in
225         let root,baseuri,_,relpath =
226           Librarian.baseuri_of_script ~include_paths mafile 
227         in
228         let obj_writeable, obj_read_only =
229            if Filename.check_suffix mafile ".mma" then 
230               Filename.chop_suffix mafile ".mma" ^ ".ma",
231               Filename.chop_suffix mafile ".mma" ^ ".ma"
232            else
233               LibraryMisc.obj_file_of_baseuri 
234                         ~must_exist:false ~baseuri ~writable:true,
235               LibraryMisc.obj_file_of_baseuri 
236                         ~must_exist:false ~baseuri ~writable:false
237         in
238         Some root, relpath, obj_writeable, obj_read_only
239       with Librarian.NoRootFor x -> None, "", "", ""
240     ;;
241
242     let mtime_of_source_object s =
243       try Some (Unix.stat s).Unix.st_mtime
244       with Unix.Unix_error (Unix.ENOENT, "stat", f) when f = s -> None
245     ;;
246
247     let mtime_of_target_object s =
248       try Some (Unix.stat s).Unix.st_mtime
249       with Unix.Unix_error (Unix.ENOENT, "stat", f) when f = s -> None
250     ;;
251
252 (* FG: a problem was noticed in relising memory between subsequent *)
253 (*     invocations of the compiler. The following might help       *)
254     let compact r = Gc.compact (); r
255
256     let build options fname =
257       let matita_debug = Helm_registry.get_bool "matita.debug" in
258       let compile opts fname =
259         try
260         (* MATITA 1.0: c'erano le push/pop per il parser; ma per
261          * l'environment nuovo? *)
262          compile opts fname
263         with 
264         | Sys.Break -> false
265         | exn when not matita_debug ->
266             HLog.error ("Unexpected " ^ snd(MatitaExcPp.to_string exn));
267             assert false
268       in
269        compact (compile options fname)
270     ;;
271
272     let load_deps_file = Librarian.load_deps_file;;
273
274   end 
275
276 module Make = Librarian.Make(F) 
277