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