1 (* Copyright (C) 2005, HELM Team.
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.
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.
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.
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,
22 * For details, see the HELM World-Wide-Web page,
23 * http://helm.cs.unibo.it/
32 class status baseuri =
34 inherit GrafiteTypes.status baseuri
35 inherit ApplyTransformation.status
38 exception TryingToAdd of string Lazy.t
39 exception EnrichedWithStatus of exn * status
40 exception AlreadyLoaded of string Lazy.t
41 exception FailureCompiling of string * exn
42 exception CircularDependency of string
45 let debug_print = if debug then prerr_endline else ignore ;;
47 let slash_n_RE = Pcre.regexp "\\n" ;;
49 let first_line = ref true ;;
51 let cases_or_induction_context stack =
54 | (g,t,k,tag,p)::tl -> try
55 let s = List.assoc "context" p in
56 s = "cases" || s = "induction"
61 let has_focused_goal stack =
64 | (g,t,k,tag,p)::tl -> (List.length g) > 0
67 let get_indentation status statement =
69 match status#stack with
71 | s -> List.length(s) * 2
73 if cases_or_induction_context status#stack then
75 if has_focused_goal status#stack then
88 | n -> " " ^ (aux s (n-1))
92 let write_ast_to_file status fname statement =
93 let indentation = get_indentation status statement in
94 let str = match statement with
95 G.Comment _ -> GrafiteAstPp.pp_statement status statement
96 ~map_unicode_to_tex:(Helm_registry.get_bool "matita.paste_unicode_as_tex")
97 | G.Executable (_,code) ->
100 G.NTactic _ -> GrafiteAstPp.pp_statement status statement
101 ~map_unicode_to_tex:(Helm_registry.get_bool "matita.paste_unicode_as_tex")
102 | G.NCommand (_,cmd) ->
105 | G.NObj (_,obj,_) ->
108 Theorem _ -> "\n" ^ GrafiteAstPp.pp_statement status statement
109 ~map_unicode_to_tex:(Helm_registry.get_bool "matita.paste_unicode_as_tex")
112 | G.NQed _ -> GrafiteAstPp.pp_statement status statement
113 ~map_unicode_to_tex:(Helm_registry.get_bool "matita.paste_unicode_as_tex")
121 let s = pp_ind str indentation in
122 let flaglist = if !first_line = false then [Open_wronly; Open_append; Open_creat]
123 else (first_line := false; [Open_wronly; Open_trunc; Open_creat])
126 Stdlib.open_out_gen flaglist 0o0644 fname in
127 let _ = Stdlib.output_string out_channel ((if str.[0] <> '\n' then s else str) ^ "\n") in
128 let _ = Stdlib.close_out out_channel in
135 let pp_ast_statement status stm ~fname =
136 let stm = write_ast_to_file status (fname ^ ".parsed.ma") stm in
139 let stm = Pcre.replace ~rex:slash_n_RE stm in
141 if String.length stm > 50 then String.sub stm 0 50 ^ " ..."
144 HLog.debug ("Executing: ``" ^ stm ^ "''")
147 HLog.debug ("Executing: `` Unprintable statement ''")
150 let clean_exit baseuri exn =
151 LibraryClean.clean_baseuris ~verbose:false [baseuri];
152 raise (FailureCompiling (baseuri,exn))
156 let lenp = String.length prefix in
157 let lens = String.length s in
158 assert (lens > lenp);
159 assert (String.sub s 0 lenp = prefix);
160 String.sub s lenp (lens-lenp)
164 let indent = ref 0 in
165 let print_string ~right_justify s =
167 match right_justify with
169 | Some (ss,len_ss) ->
170 let i = 80 - !indent - len_ss - String.length s in
171 if i > 0 then String.make i ' ' ^ ss else ss
173 assert (!indent >=0);
174 print_string (String.make !indent ' ' ^ s ^ ss) in
175 fun enter ?right_justify s ->
176 if enter then (print_string ~right_justify s; incr indent) else (decr indent; print_string ~right_justify s)
179 let pp_times ss fname rc big_bang big_bang_u big_bang_s =
180 if not (Helm_registry.get_bool "matita.verbose") then
181 let { Unix.tms_utime = u ; Unix.tms_stime = s} = Unix.times () in
182 let r = Unix.gettimeofday () -. big_bang in
183 let u = u -. big_bang_u in
184 let s = s -. big_bang_s in
185 let extra = try Sys.getenv "BENCH_EXTRA_TEXT" with Not_found -> "" in
187 if rc then "
\e[0;32mOK
\e[0m" else "
\e[0;31mFAIL
\e[0m" in
190 let seconds = int_of_float t in
191 let cents = int_of_float ((t -. floor t) *. 100.0) in
192 let minutes = seconds / 60 in
193 let seconds = seconds mod 60 in
194 Printf.sprintf "%dm%02d.%02ds" minutes seconds cents
196 Printf.sprintf "%s %s %s" (fmt r) (fmt u) (fmt s)
198 let s = Printf.sprintf "%-14s %s %s\n" rc times extra in
199 print_string false ~right_justify:(s,31) ss;
201 HLog.message ("Compilation of "^Filename.basename fname^": "^rc)
204 let eval_ast ~include_paths ?do_heavy_checks status (text,prefix_len,ast) =
205 let baseuri = status#baseuri in
206 let new_aliases,new_status =
207 GrafiteDisambiguate.eval_with_new_aliases status
209 let time0 = Unix.gettimeofday () in
211 GrafiteEngine.eval_ast ~include_paths ?do_heavy_checks status
212 (text,prefix_len,ast) in
213 let time1 = Unix.gettimeofday () in
214 HLog.debug ("... grafite_engine done in " ^ string_of_float (time1 -. time0) ^ "s");
217 let _,intermediate_states =
219 (fun (status,acc) (k,value) ->
220 let v = GrafiteAst.description_of_alias value in
223 let NReference.Ref (uri,_) = NReference.reference_of_string v in
224 NUri.baseuri_of_uri uri = baseuri
226 NReference.IllFormedReference _ ->
227 false (* v is a description, not a URI *)
233 GrafiteDisambiguate.set_proof_aliases status ~implicit_aliases:false
234 GrafiteAst.WithPreferences [k,value]
236 status, (status ,Some (k,value))::acc
237 ) (status,[]) new_aliases (* WARNING: this must be the old status! *)
239 (new_status,None)::intermediate_states
242 let baseuri_of_script ~include_paths fname =
243 try Librarian.baseuri_of_script ~include_paths fname
245 Librarian.NoRootFor _ ->
246 HLog.error ("The included file '"^fname^"' has no root file,");
247 HLog.error "please create it.";
248 raise (Failure ("No root file for "^fname))
249 | Librarian.FileNotFound _ ->
250 raise (Failure ("File not found: "^fname))
253 (* given a path to a ma file inside the include_paths, returns the
254 new include_paths associated to that file *)
255 let read_include_paths ~include_paths file =
257 let root, _buri, _fname, _tgt =
258 Librarian.baseuri_of_script ~include_paths:[] file in
261 Str.split (Str.regexp " ")
262 (List.assoc "include_paths" (Librarian.load_root_file (root^"/root")))
265 let rc = root :: includes in
266 List.iter (HLog.debug) rc; rc
267 with Librarian.NoRootFor _ | Librarian.FileNotFound _ ->
271 let rec get_ast status ~compiling ~asserted ~include_paths strm =
272 match GrafiteParser.parse_statement status strm with
273 (GrafiteAst.Executable
274 (_,GrafiteAst.NCommand (_,GrafiteAst.Include (_,_,mafilename)))) as cmd
276 let already_included = NCicLibrary.get_transitively_included status in
278 assert_ng ~already_included ~compiling ~asserted ~include_paths
282 | cmd -> asserted,cmd
284 and eval_from_stream ~compiling ~asserted ~include_paths ?do_heavy_checks status str cb =
285 let matita_debug = Helm_registry.get_bool "matita.debug" in
286 let rec loop asserted status str =
287 let asserted,stop,status,str =
290 try Some (get_ast status ~compiling ~asserted ~include_paths str)
291 with End_of_file -> None in
293 | None -> asserted, true, status, str
294 | Some (asserted,ast) ->
297 eval_ast ~include_paths ?do_heavy_checks status ("",0,ast) in
299 match new_statuses with
301 | _::(_,Some (_,value))::_ ->
302 raise (TryingToAdd (lazy (GrafiteAstPp.pp_alias value)))
303 | _ -> assert false in
304 (* CSC: complex patch to re-build the lexer since the tokens may
305 have changed. Note: this way we loose look-ahead tokens.
306 Hence the "include" command must be terminated (no look-ahead) *)
309 (GrafiteAst.Executable
310 (_,GrafiteAst.NCommand
311 (_,(GrafiteAst.Include _ | GrafiteAst.Notation _)))) ->
312 GrafiteParser.parsable_statement status
313 (GrafiteParser.strm_of_parsable str)
316 asserted, false, status, str
317 with exn when not matita_debug ->
318 raise (EnrichedWithStatus (exn, status))
320 if stop then asserted,status else loop asserted status str
322 loop asserted status str
324 and compile ~compiling ~asserted ~include_paths fname =
325 if List.mem fname compiling then raise (CircularDependency fname);
326 let compiling = fname::compiling in
327 let matita_debug = Helm_registry.get_bool "matita.debug" in
328 let root,baseuri,fname,_tgt =
329 Librarian.baseuri_of_script ~include_paths fname in
330 if Http_getter_storage.is_read_only baseuri then assert false;
331 (* MATITA 1.0: debbo fare time_travel sulla ng_library? *)
332 let status = new status baseuri in
333 (*CSC: bad, one imperative bit is still there!
334 to be moved into functional status *)
335 NCicMetaSubst.pushmaxmeta ();
336 let ocamldirname = Filename.dirname fname in
337 let ocamlfname = Filename.chop_extension (Filename.basename fname) in
338 let status,ocamlfname =
339 Common.modname_of_filename status false ocamlfname in
340 let ocamlfname = ocamldirname ^ "/" ^ ocamlfname ^ ".ml" in
341 let status = OcamlExtraction.open_file status ~baseuri ocamlfname in
342 let big_bang = Unix.gettimeofday () in
343 let { Unix.tms_utime = big_bang_u ; Unix.tms_stime = big_bang_s} =
346 let time = Unix.time () in
348 let rex = Str.regexp ".*opt$" in
349 if Str.string_match rex Sys.argv.(0) 0 then "matitac.opt"
351 let s = Printf.sprintf "%s %s" cc (cut (root^"/") fname) in
353 (* cleanup of previously compiled objects *)
354 if (not (Http_getter_storage.is_empty ~local:true baseuri))
356 HLog.message ("baseuri " ^ baseuri ^ " is not empty");
357 HLog.message ("cleaning baseuri " ^ baseuri);
358 LibraryClean.clean_baseuris [baseuri];
360 HLog.message ("compiling " ^ Filename.basename fname ^ " in " ^ baseuri);
361 if not (Helm_registry.get_bool "matita.verbose") then
362 (print_string true (s ^ "\n"); flush stdout);
363 (* we dalay this error check until we print 'matitac file ' *)
364 assert (Http_getter_storage.is_empty ~local:true baseuri);
365 (* create dir for XML files *)
366 if not (Helm_registry.get_opt_default Helm_registry.bool "matita.nodisk"
371 (Http_getter.filename ~local:true ~writable:true (baseuri ^
374 GrafiteParser.parsable_statement status
375 (Ulexing.from_utf8_channel (open_in fname))
378 if not (Helm_registry.get_bool "matita.verbose") then fun _ _ -> ()
379 else pp_ast_statement ~fname
381 let asserted, status =
382 eval_from_stream ~compiling ~asserted ~include_paths status buf print_cb in
383 let status = OcamlExtraction.close_file status in
384 let elapsed = Unix.time () -. time in
385 (if Helm_registry.get_bool "matita.moo" then begin
386 GrafiteTypes.Serializer.serialize ~baseuri:(NUri.uri_of_string baseuri)
389 let tm = Unix.gmtime elapsed in
390 let sec = string_of_int tm.Unix.tm_sec ^ "''" in
392 if tm.Unix.tm_min > 0 then (string_of_int tm.Unix.tm_min^"' ") else ""
395 if tm.Unix.tm_hour > 0 then (string_of_int tm.Unix.tm_hour^"h ") else ""
398 (sprintf "execution of %s completed in %s." fname (hou^min^sec));
399 pp_times s fname true big_bang big_bang_u big_bang_s;
400 (*CSC: bad, one imperative bit is still there!
401 to be moved into functional status *)
402 NCicMetaSubst.pushmaxmeta ();
403 (* MATITA 1.0: debbo fare time_travel sulla ng_library?
404 LexiconSync.time_travel
405 ~present:lexicon_status ~past:initial_lexicon_status;
409 (* all exceptions should be wrapped to allow lexicon-undo (LS.time_travel) *)
410 | exn when not matita_debug ->
411 (* MATITA 1.0: debbo fare time_travel sulla ng_library?
412 LexiconSync.time_travel ~present:lexicon ~past:initial_lexicon_status;
414 (*CSC: bad, one imperative bit is still there!
415 to be moved into functional status *)
416 NCicMetaSubst.pushmaxmeta ();
417 pp_times s fname false big_bang big_bang_u big_bang_s;
418 clean_exit baseuri exn
420 and assert_ng ~already_included ~compiling ~asserted ~include_paths mapath =
421 let root,baseuri,fullmapath,_ =
422 Librarian.baseuri_of_script ~include_paths mapath in
423 if List.mem fullmapath asserted then asserted,false
429 Str.split (Str.regexp " ")
430 (List.assoc "include_paths" (Librarian.load_root_file (root^"/root")))
434 Helm_registry.get_list Helm_registry.string "matita.includes" in
435 let baseuri = NUri.uri_of_string baseuri in
436 let ngtime_of baseuri =
437 let ngpath = NCicLibrary.ng_path_of_baseuri baseuri in
439 Some (Unix.stat ngpath).Unix.st_mtime
440 with Unix.Unix_error (Unix.ENOENT, "stat", f) when f = ngpath -> None in
442 try (Unix.stat fullmapath).Unix.st_mtime
443 with Unix.Unix_error (Unix.ENOENT, "stat", f) when f = fullmapath -> assert false
445 let ngtime = ngtime_of baseuri in
446 let asserted,to_be_compiled =
449 let preamble = GrafiteTypes.Serializer.dependencies_of baseuri in
450 let asserted,children_bad =
452 (fun (asserted,b) mapath ->
455 assert_ng ~already_included ~compiling ~asserted ~include_paths
457 with Librarian.NoRootFor _ | Librarian.FileNotFound _ ->
461 || let _,baseuri,_,_ =
462 (*CSC: bug here? include_paths should be empty and
463 mapath should be absolute *)
464 Librarian.baseuri_of_script ~include_paths mapath in
465 let baseuri = NUri.uri_of_string baseuri in
466 (match ngtime_of baseuri with
467 Some child_ngtime -> child_ngtime > ngtime
468 | None -> assert false)
469 ) (asserted,false) preamble
471 asserted, children_bad || matime > ngtime
472 | None -> asserted,true
474 if not to_be_compiled then fullmapath::asserted,false
476 if List.mem baseuri already_included then
477 (* maybe recompiling it I would get the same... *)
478 raise (AlreadyLoaded (lazy mapath))
480 let asserted = compile ~compiling ~asserted ~include_paths fullmapath in
481 fullmapath::asserted,true
485 let assert_ng ~include_paths mapath =
486 snd (assert_ng ~include_paths ~already_included:[] ~compiling:[] ~asserted:[]
488 let get_ast status ~include_paths strm =
489 snd (get_ast status ~compiling:[] ~asserted:[] ~include_paths strm)