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