]> matita.cs.unibo.it Git - helm.git/blob - helm/software/matita/matitacLib.ml
basic support for imposed flavour in procedural object rendering
[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
38 let slash_n_RE = Pcre.regexp "\\n" ;;
39
40 let pp_ast_statement grafite_status stm =
41   let stm = GrafiteAstPp.pp_statement
42     ~map_unicode_to_tex:(Helm_registry.get_bool "matita.paste_unicode_as_tex")
43     ~term_pp:CicNotationPp.pp_term
44     ~lazy_term_pp:CicNotationPp.pp_term ~obj_pp:(CicNotationPp.pp_obj
45     CicNotationPp.pp_term) stm
46   in
47   let stm = Pcre.replace ~rex:slash_n_RE stm in
48   let stm =
49       if String.length stm > 50 then String.sub stm 0 50 ^ " ..."
50       else stm
51   in
52     HLog.debug ("Executing: ``" ^ stm ^ "''")
53 ;;
54
55 let clean_exit baseuri rc =
56   LibraryClean.clean_baseuris ~verbose:false [baseuri]; rc
57 ;;
58
59 let dump f =
60    let module G = GrafiteAst in
61    let module L = LexiconAst in
62    let module H = HExtlib in
63    Helm_registry.set_bool "matita.moo" false;
64    let floc = H.dummy_floc in
65    let nl_ast = G.Comment (floc, G.Note (floc, "")) in
66    let och = open_out f in
67    let out_comment och s =
68       let s = if s <> "" && s.[0] = '*' then "#" ^ s else s in 
69       Printf.fprintf och "%s%s%s\n\n" "(*" s "*)"
70    in
71    let out_line_comment och s =
72       let l = 70 - String.length s in
73       let s = Printf.sprintf " %s %s" s (String.make l '*') in
74       out_comment och s
75    in
76    let out_preamble och (path, lines) =
77       let ich = open_in path in
78       let rec print i =
79          if i > 0 then 
80             let s = input_line ich in
81             begin Printf.fprintf och "%s\n" s; print (pred i) end
82       in 
83       print lines;
84       out_line_comment och "This file was automatically generated: do not edit"
85    in
86    let pp_ast_statement st =
87      GrafiteAstPp.pp_statement ~term_pp:CicNotationPp.pp_term
88        ~map_unicode_to_tex:(Helm_registry.get_bool
89          "matita.paste_unicode_as_tex")
90        ~lazy_term_pp:CicNotationPp.pp_term 
91        ~obj_pp:(CicNotationPp.pp_obj CicNotationPp.pp_term) st
92    in
93    let nl () =  output_string och (pp_ast_statement nl_ast) in
94    let rt_base_dir = Filename.dirname Sys.argv.(0) in
95    let path = Filename.concat rt_base_dir "matita.ma.templ" in
96    let lines = 14 in
97    out_preamble och (path, lines);
98    let grafite_parser_cb fname = 
99       let ast = G.Executable 
100         (floc, G.Command (floc, G.Include (floc, fname))) in
101       output_string och (pp_ast_statement ast); nl (); nl ()
102    in
103    let matita_engine_cb = function
104       | G.Executable (_, G.Macro (_, G.Inline _)) 
105       | G.Executable (_, G.Command (_, G.Include _)) -> ()
106       | ast                                          ->
107          output_string och (pp_ast_statement ast); nl (); nl ()
108    in
109    let matitac_lib_cb = output_string och in
110    GrafiteParser.set_callback grafite_parser_cb;
111    MatitaEngine.set_callback matita_engine_cb;
112    set_callback matitac_lib_cb;
113    fun x ->
114       close_out och;
115       GrafiteParser.set_callback ignore;
116       MatitaEngine.set_callback ignore;
117       set_callback ignore; x
118 ;;
119
120 let get_macro_context = function
121    | Some {GrafiteTypes.proof_status = GrafiteTypes.No_proof} -> []
122    | Some status                ->
123       let stack = GrafiteTypes.get_stack status in
124       let goal = Continuationals.Stack.find_goal stack in
125       GrafiteTypes.get_proof_context status goal
126    | None                       -> assert false
127 ;;
128    
129 let pp_times fname rc big_bang big_bang_u big_bang_s = 
130   if not (Helm_registry.get_bool "matita.verbose") then
131     let { Unix.tms_utime = u ; Unix.tms_stime = s} = Unix.times () in
132     let r = Unix.gettimeofday () -. big_bang in
133     let u = u -. big_bang_u in
134     let s = s -. big_bang_s in
135     let extra = try Sys.getenv "BENCH_EXTRA_TEXT" with Not_found -> "" in
136     let rc,rcascii = 
137       if rc then "\e[0;32mOK\e[0m","Ok" else "\e[0;31mFAIL\e[0m","Fail" in
138     let times = 
139       let fmt t = 
140         let seconds = int_of_float t in
141         let cents = int_of_float ((t -. floor t) *. 100.0) in
142         let minutes = seconds / 60 in
143         let seconds = seconds mod 60 in
144         Printf.sprintf "%dm%02d.%02ds" minutes seconds cents
145       in
146       Printf.sprintf "%s %s %s" (fmt r) (fmt u) (fmt s)
147     in
148     let s = Printf.sprintf "%-4s %s %s" rc times extra in
149     print_endline s;
150     flush stdout;
151     HLog.message ("Compilation of "^Filename.basename fname^": "^rc)
152 ;;
153
154 let cut prefix s = 
155   let lenp = String.length prefix in
156   let lens = String.length s in
157   assert (lens > lenp);
158   assert (String.sub s 0 lenp = prefix);
159   String.sub s lenp (lens-lenp)
160 ;;
161
162 let get_include_paths options =
163   let include_paths = 
164     try List.assoc "include_paths" options with Not_found -> "" 
165   in
166   let include_paths = Str.split (Str.regexp " ") include_paths in
167   let include_paths = 
168     include_paths @ 
169     Helm_registry.get_list Helm_registry.string "matita.includes" 
170   in
171     include_paths
172 ;;
173
174 let activate_extraction baseuri fname =
175  if Helm_registry.get_bool "matita.extract" then
176   let mangled_baseuri =
177    let baseuri = String.sub baseuri 5 (String.length baseuri - 5) in
178      let baseuri = Pcre.replace ~pat:"/" ~templ:"_" baseuri in
179       String.uncapitalize baseuri in
180   let f =
181     open_out
182      (Filename.dirname fname ^ "/" ^ mangled_baseuri ^ ".ml") in
183    LibrarySync.set_object_declaration_hook
184     (fun _ obj ->
185       output_string f (CicExportation.ppobj baseuri obj);
186       flush f);
187 ;;
188
189 let compile options fname =
190   let matita_debug = Helm_registry.get_bool "matita.debug" in
191   let include_paths = get_include_paths options in
192   let root,baseuri,fname,_tgt = 
193     Librarian.baseuri_of_script ~include_paths fname in
194   if Http_getter_storage.is_read_only baseuri then assert false;
195   activate_extraction baseuri fname ;
196   let grafite_status = GrafiteSync.init baseuri in
197   let lexicon_status = 
198     CicNotation2.load_notation ~include_paths:[]
199       BuildTimeConf.core_notation_script 
200   in
201   let initial_lexicon_status = lexicon_status in
202   let big_bang = Unix.gettimeofday () in
203   let { Unix.tms_utime = big_bang_u ; Unix.tms_stime = big_bang_s} = 
204     Unix.times () 
205   in
206   let time = Unix.time () in
207   try
208     (* sanity checks *)
209     let moo_fname = 
210      LibraryMisc.obj_file_of_baseuri ~must_exist:false ~baseuri ~writable:true
211     in
212     let lexicon_fname= 
213      LibraryMisc.lexicon_file_of_baseuri 
214        ~must_exist:false ~baseuri ~writable:true
215     in
216     (* cleanup of previously compiled objects *)
217     if (not (Http_getter_storage.is_empty ~local:true baseuri) ||
218         LibraryClean.db_uris_of_baseuri baseuri <> []) 
219       then begin
220       HLog.message ("baseuri " ^ baseuri ^ " is not empty");
221       HLog.message ("cleaning baseuri " ^ baseuri);
222       LibraryClean.clean_baseuris [baseuri];
223     end;
224     HLog.message ("compiling " ^ Filename.basename fname ^ " in " ^ baseuri);
225     if not (Helm_registry.get_bool "matita.verbose") then
226       (let cc = 
227         let rex = Str.regexp ".*opt$" in
228         if Str.string_match rex Sys.argv.(0) 0 then "matitac.opt"
229         else "matitac" 
230       in
231       let s = Printf.sprintf "%s %-35s " cc (cut (root^"/") fname) in
232       print_string s; flush stdout);
233     (* we dalay this error check until we print 'matitac file ' *)
234     assert (Http_getter_storage.is_empty ~local:true baseuri);
235     (* create dir for XML files *)
236     if not (Helm_registry.get_opt_default Helm_registry.bool "matita.nodisk"
237               ~default:false) 
238     then
239       HExtlib.mkdir 
240         (Filename.dirname 
241           (Http_getter.filename ~local:true ~writable:true (baseuri ^
242           "foo.con")));
243     let buf = Ulexing.from_utf8_channel (open_in fname) in
244     let print_cb =
245       if not (Helm_registry.get_bool "matita.verbose") then (fun _ _ -> ())
246       else pp_ast_statement
247     in
248     let grafite_status, lexicon_status =
249      let rec aux_for_dump x =
250      try
251       match
252        MatitaEngine.eval_from_stream ~first_statement_only:false ~include_paths
253         lexicon_status grafite_status buf x
254       with
255       | [] -> grafite_status, lexicon_status 
256       | ((grafite,lexicon),None)::_ -> grafite, lexicon
257       | ((_,l),Some _)::_ -> raise (AttemptToInsertAnAlias l)
258
259      with MatitaEngine.EnrichedWithLexiconStatus 
260             (GrafiteEngine.Macro (floc, f), lex_status) as exn ->
261             match f (get_macro_context (Some grafite_status)) with 
262             | _, GrafiteAst.Inline (_, style, suri, prefix, flavour) ->
263               let str =
264                ApplyTransformation.txt_of_inline_macro style prefix suri
265                 ?flavour
266                 ~map_unicode_to_tex:(Helm_registry.get_bool
267                   "matita.paste_unicode_as_tex")
268               in
269               !out str;
270               aux_for_dump x
271             |_-> raise exn
272      in
273        aux_for_dump print_cb
274     in
275     let elapsed = Unix.time () -. time in
276     let proof_status,moo_content_rev,lexicon_content_rev = 
277       grafite_status.proof_status, grafite_status.moo_content_rev, 
278        lexicon_status.LexiconEngine.lexicon_content_rev
279     in
280     if proof_status <> GrafiteTypes.No_proof then
281      (HLog.error
282       "there are still incomplete proofs at the end of the script"; 
283      pp_times fname false big_bang big_bang_u big_bang_s;
284      LexiconSync.time_travel 
285        ~present:lexicon_status ~past:initial_lexicon_status;
286      clean_exit baseuri false)
287     else
288      (if not (Helm_registry.get_bool "matita.moo" && 
289               Filename.check_suffix fname ".mma") then begin
290         (* FG: we do not generate .moo when dumping .mma files *)
291         GrafiteMarshal.save_moo moo_fname moo_content_rev;
292         LexiconMarshal.save_lexicon lexicon_fname lexicon_content_rev;
293      end;
294      let tm = Unix.gmtime elapsed in
295      let sec = string_of_int tm.Unix.tm_sec ^ "''" in
296      let min = 
297        if tm.Unix.tm_min > 0 then (string_of_int tm.Unix.tm_min^"' ") else "" 
298      in
299      let hou = 
300        if tm.Unix.tm_hour > 0 then (string_of_int tm.Unix.tm_hour^"h ") else ""
301      in
302      HLog.message 
303        (sprintf "execution of %s completed in %s." fname (hou^min^sec));
304      pp_times fname true big_bang big_bang_u big_bang_s;
305      LexiconSync.time_travel 
306        ~present:lexicon_status ~past:initial_lexicon_status;
307      true)
308   with 
309   (* all exceptions should be wrapped to allow lexicon-undo (LS.time_travel) *)
310   | AttemptToInsertAnAlias lexicon_status -> 
311      pp_times fname false big_bang big_bang_u big_bang_s;
312      LexiconSync.time_travel 
313        ~present:lexicon_status ~past:initial_lexicon_status;
314      clean_exit baseuri false
315   | MatitaEngine.EnrichedWithLexiconStatus (exn, lex_stat) as exn' ->
316       (match exn with
317       | Sys.Break -> HLog.error "user break!"
318       | HExtlib.Localized (floc,CicNotationParser.Parse_error err) ->
319           let (x, y) = HExtlib.loc_of_floc floc in
320           HLog.error (sprintf "Parse error at %d-%d: %s" x y err)
321       | exn when matita_debug -> raise exn'
322       | exn -> HLog.error (snd (MatitaExcPp.to_string exn)));
323       LexiconSync.time_travel ~present:lex_stat ~past:initial_lexicon_status;
324       pp_times fname false big_bang big_bang_u big_bang_s;
325       clean_exit baseuri false
326   | Sys.Break when not matita_debug ->
327      HLog.error "user break!";
328      pp_times fname false big_bang big_bang_u big_bang_s;
329      clean_exit baseuri false
330   | exn when not matita_debug ->
331        HLog.error 
332          ("Unwrapped exception, please fix: "^ snd (MatitaExcPp.to_string exn));
333        pp_times fname false big_bang big_bang_u big_bang_s;
334        clean_exit baseuri false
335
336 module F = 
337   struct 
338     type source_object = string
339     type target_object = string
340     let string_of_source_object s = s;;
341     let string_of_target_object s = s;;
342
343     let is_readonly_buri_of opts file = 
344      let buri = List.assoc "baseuri" opts in
345      Http_getter_storage.is_read_only (Librarian.mk_baseuri buri file)
346
347     let root_and_target_of opts mafile = 
348       try
349         let include_paths = get_include_paths opts in
350         let root,baseuri,_,_ =
351           Librarian.baseuri_of_script ~include_paths mafile 
352         in
353         let obj =
354            if Filename.check_suffix mafile ".mma" then 
355               Filename.chop_suffix mafile ".mma" ^ ".ma"
356            else
357               LibraryMisc.obj_file_of_baseuri 
358                  ~must_exist:false ~baseuri ~writable:true
359         in
360         Some root, obj 
361       with Librarian.NoRootFor x -> None, ""
362
363     let mtime_of_source_object s =
364       try Some (Unix.stat s).Unix.st_mtime
365       with Unix.Unix_error (Unix.ENOENT, "stat", f) when f = s -> None
366
367     let mtime_of_target_object s =
368       try Some (Unix.stat s).Unix.st_mtime
369       with Unix.Unix_error (Unix.ENOENT, "stat", f) when f = s -> None
370
371     let build options fname =
372        if Filename.check_suffix fname ".mma" then 
373           let generated = Filename.chop_suffix fname ".mma" ^ ".ma" in
374           let atexit = dump generated in
375           let res = compile options fname in
376           atexit res
377        else
378           compile options fname
379
380     let load_deps_file = Librarian.load_deps_file
381
382   end 
383
384 module Make = Librarian.Make(F) 
385