]> matita.cs.unibo.it Git - helm.git/blob - matita/matita/matitaEngine.ml
long file names caused indentation underflow (String.make) when times
[helm.git] / matita / matita / matitaEngine.ml
1 (* Copyright (C) 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 module G = GrafiteAst
29 open GrafiteTypes
30 open Printf
31
32 class status baseuri =
33  object
34   inherit GrafiteTypes.status baseuri
35   inherit ApplyTransformation.status
36  end
37
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
43
44 let debug = false ;;
45 let debug_print = if debug then prerr_endline else ignore ;;
46
47 let slash_n_RE = Pcre.regexp "\\n" ;;
48
49 let pp_ast_statement status stm =
50   let stm = GrafiteAstPp.pp_statement status stm
51     ~map_unicode_to_tex:(Helm_registry.get_bool "matita.paste_unicode_as_tex")
52   in
53   let stm = Pcre.replace ~rex:slash_n_RE stm in
54   let stm =
55       if String.length stm > 50 then String.sub stm 0 50 ^ " ..."
56       else stm
57   in
58     HLog.debug ("Executing: ``" ^ stm ^ "''")
59 ;;
60
61 let clean_exit baseuri exn =
62   LibraryClean.clean_baseuris ~verbose:false [baseuri];
63   raise (FailureCompiling (baseuri,exn))
64 ;;
65
66 let cut prefix s = 
67   let lenp = String.length prefix in
68   let lens = String.length s in
69   assert (lens > lenp);
70   assert (String.sub s 0 lenp = prefix);
71   String.sub s lenp (lens-lenp)
72 ;;
73
74 let print_string = 
75  let indent = ref 0 in
76  let print_string ~right_justify s =
77   let ss =
78    match right_justify with
79       None -> ""
80     | Some (ss,len_ss) ->
81        let i = 80 - !indent - len_ss - String.length s in
82        if i > 0 then String.make i ' ' ^ ss else ss
83   in
84    assert (!indent >=0);
85    print_string (String.make !indent ' ' ^ s ^ ss) in
86  fun enter ?right_justify s ->
87   if enter then (print_string ~right_justify s; incr indent) else (decr indent; print_string ~right_justify s)
88 ;;
89
90 let pp_times ss fname rc big_bang big_bang_u big_bang_s = 
91   if not (Helm_registry.get_bool "matita.verbose") then
92     let { Unix.tms_utime = u ; Unix.tms_stime = s} = Unix.times () in
93     let r = Unix.gettimeofday () -. big_bang in
94     let u = u -. big_bang_u in
95     let s = s -. big_bang_s in
96     let extra = try Sys.getenv "BENCH_EXTRA_TEXT" with Not_found -> "" in
97     let rc = 
98       if rc then "\e[0;32mOK\e[0m" else "\e[0;31mFAIL\e[0m" in
99     let times = 
100       let fmt t = 
101         let seconds = int_of_float t in
102         let cents = int_of_float ((t -. floor t) *. 100.0) in
103         let minutes = seconds / 60 in
104         let seconds = seconds mod 60 in
105         Printf.sprintf "%dm%02d.%02ds" minutes seconds cents
106       in
107       Printf.sprintf "%s %s %s" (fmt r) (fmt u) (fmt s)
108     in
109     let s = Printf.sprintf "%-14s %s %s\n" rc times extra in
110     print_string false ~right_justify:(s,31) ss;
111     flush stdout;
112     HLog.message ("Compilation of "^Filename.basename fname^": "^rc)
113 ;;
114
115 let activate_extraction baseuri fname =
116   ()
117   (* MATITA 1.0
118  if Helm_registry.get_bool "matita.extract" then
119   let mangled_baseuri =
120    let baseuri = String.sub baseuri 5 (String.length baseuri - 5) in
121      let baseuri = Pcre.replace ~pat:"/" ~templ:"_" baseuri in
122       String.uncapitalize baseuri in
123   let f =
124     open_out
125      (Filename.dirname fname ^ "/" ^ mangled_baseuri ^ ".ml") in
126    LibrarySync.add_object_declaration_hook
127     (fun ~add_obj ~add_coercion _ obj ->
128       output_string f (CicExportation.ppobj baseuri obj);
129       flush f; []);
130       *)
131 ;;
132
133
134 let eval_ast ~include_paths ?do_heavy_checks status (text,prefix_len,ast) =
135  let baseuri = status#baseuri in
136  let new_aliases,new_status =
137   GrafiteDisambiguate.eval_with_new_aliases status
138    (fun status ->
139      GrafiteEngine.eval_ast ~include_paths ?do_heavy_checks status
140       (text,prefix_len,ast)) in
141  let _,intermediate_states = 
142   List.fold_left
143    (fun (status,acc) (k,value) -> 
144      let v = GrafiteAst.description_of_alias value in
145      let b =
146       try
147        let NReference.Ref (uri,_) = NReference.reference_of_string v in
148         NUri.baseuri_of_uri uri = baseuri
149       with
150        NReference.IllFormedReference _ ->
151         false (* v is a description, not a URI *)
152      in
153       if b then 
154        status,acc
155       else
156        let status =
157         GrafiteDisambiguate.set_proof_aliases status ~implicit_aliases:false
158          GrafiteAst.WithPreferences [k,value]
159        in
160         status, (status ,Some (k,value))::acc
161    ) (status,[]) new_aliases (* WARNING: this must be the old status! *)
162  in
163   (new_status,None)::intermediate_states
164 ;;
165
166 let baseuri_of_script ~include_paths fname =
167  try Librarian.baseuri_of_script ~include_paths fname
168  with
169    Librarian.NoRootFor _ -> 
170     HLog.error ("The included file '"^fname^"' has no root file,");
171     HLog.error "please create it.";
172     raise (Failure ("No root file for "^fname))
173   | Librarian.FileNotFound _ -> 
174     raise (Failure ("File not found: "^fname))
175 ;;
176
177 (* given a path to a ma file inside the include_paths, returns the
178    new include_paths associated to that file *)
179 let read_include_paths ~include_paths file =
180  try 
181    let root, _buri, _fname, _tgt = 
182      Librarian.baseuri_of_script ~include_paths:[] file in 
183    let includes =
184     try
185      Str.split (Str.regexp " ") 
186       (List.assoc "include_paths" (Librarian.load_root_file (root^"/root")))
187     with Not_found -> []
188    in
189    let rc = root :: includes in
190     List.iter (HLog.debug) rc; rc
191  with Librarian.NoRootFor _ | Librarian.FileNotFound _ ->
192   []
193 ;;
194
195 let rec get_ast status ~compiling ~asserted ~include_paths strm = 
196   match GrafiteParser.parse_statement status strm with
197      (GrafiteAst.Executable
198        (_,GrafiteAst.NCommand (_,GrafiteAst.Include (_,_,mafilename)))) as cmd
199      ->
200        let already_included = NCicLibrary.get_transitively_included status in
201        let asserted,_ =
202         assert_ng ~already_included ~compiling ~asserted ~include_paths
203          mafilename
204        in
205         asserted,cmd
206    | cmd -> asserted,cmd
207
208 and eval_from_stream ~compiling ~asserted ~include_paths ?do_heavy_checks status str cb =
209  let matita_debug = Helm_registry.get_bool "matita.debug" in
210  let rec loop asserted status str =
211   let asserted,stop,status,str = 
212    try
213      let cont =
214        try Some (get_ast status ~compiling ~asserted ~include_paths str)
215        with End_of_file -> None in
216      match cont with
217      | None -> asserted, true, status, str
218      | Some (asserted,ast) ->
219         cb status ast;
220         let new_statuses =
221           eval_ast ~include_paths ?do_heavy_checks status ("",0,ast) in
222         let status =
223          match new_statuses with
224             [s,None] -> s
225           | _::(_,Some (_,value))::_ ->
226                 raise (TryingToAdd (lazy (GrafiteAstPp.pp_alias value)))
227           | _ -> assert false in
228         (* CSC: complex patch to re-build the lexer since the tokens may
229            have changed. Note: this way we loose look-ahead tokens.
230            Hence the "include" command must be terminated (no look-ahead) *)
231         let str =
232          match ast with
233             (GrafiteAst.Executable
234               (_,GrafiteAst.NCommand
235                 (_,(GrafiteAst.Include _ | GrafiteAst.Notation _)))) ->
236               GrafiteParser.parsable_statement status
237                (GrafiteParser.strm_of_parsable str)
238           | _ -> str
239         in
240          asserted, false, status, str
241    with exn when not matita_debug ->
242      raise (EnrichedWithStatus (exn, status))
243   in
244   if stop then asserted,status else loop asserted status str
245  in
246   loop asserted status str
247
248 and compile ~compiling ~asserted ~include_paths fname =
249   if List.mem fname compiling then raise (CircularDependency fname);
250   let compiling = fname::compiling in
251   let matita_debug = Helm_registry.get_bool "matita.debug" in
252   let root,baseuri,fname,_tgt = 
253     Librarian.baseuri_of_script ~include_paths fname in
254   if Http_getter_storage.is_read_only baseuri then assert false;
255   activate_extraction baseuri fname ;
256   (* MATITA 1.0: debbo fare time_travel sulla ng_library? *)
257   let status = new status baseuri in
258   let big_bang = Unix.gettimeofday () in
259   let { Unix.tms_utime = big_bang_u ; Unix.tms_stime = big_bang_s} = 
260     Unix.times () 
261   in
262   let time = Unix.time () in
263   let cc = 
264    let rex = Str.regexp ".*opt$" in
265    if Str.string_match rex Sys.argv.(0) 0 then "matitac.opt"
266    else "matitac" in
267   let s = Printf.sprintf "%s %s" cc (cut (root^"/") fname) in
268   try
269     (* cleanup of previously compiled objects *)
270     if (not (Http_getter_storage.is_empty ~local:true baseuri))
271       then begin
272       HLog.message ("baseuri " ^ baseuri ^ " is not empty");
273       HLog.message ("cleaning baseuri " ^ baseuri);
274       LibraryClean.clean_baseuris [baseuri];
275     end;
276     HLog.message ("compiling " ^ Filename.basename fname ^ " in " ^ baseuri);
277     if not (Helm_registry.get_bool "matita.verbose") then
278      (print_string true (s ^ "\n"); flush stdout);
279     (* we dalay this error check until we print 'matitac file ' *)
280     assert (Http_getter_storage.is_empty ~local:true baseuri);
281     (* create dir for XML files *)
282     if not (Helm_registry.get_opt_default Helm_registry.bool "matita.nodisk"
283               ~default:false) 
284     then
285       HExtlib.mkdir 
286         (Filename.dirname 
287           (Http_getter.filename ~local:true ~writable:true (baseuri ^
288           "foo.con")));
289     let buf =
290      GrafiteParser.parsable_statement status
291       (Ulexing.from_utf8_channel (open_in fname))
292     in
293     let print_cb =
294       if not (Helm_registry.get_bool "matita.verbose") then (fun _ _ -> ())
295       else pp_ast_statement
296     in
297     let asserted, status =
298      eval_from_stream ~compiling ~asserted ~include_paths status buf print_cb in
299     let elapsed = Unix.time () -. time in
300      (if Helm_registry.get_bool "matita.moo" then begin
301        GrafiteTypes.Serializer.serialize ~baseuri:(NUri.uri_of_string baseuri)
302         status
303      end;
304      let tm = Unix.gmtime elapsed in
305      let sec = string_of_int tm.Unix.tm_sec ^ "''" in
306      let min = 
307        if tm.Unix.tm_min > 0 then (string_of_int tm.Unix.tm_min^"' ") else "" 
308      in
309      let hou = 
310        if tm.Unix.tm_hour > 0 then (string_of_int tm.Unix.tm_hour^"h ") else ""
311      in
312      HLog.message 
313        (sprintf "execution of %s completed in %s." fname (hou^min^sec));
314      pp_times s fname true big_bang big_bang_u big_bang_s;
315      asserted
316 (* MATITA 1.0: debbo fare time_travel sulla ng_library?
317      LexiconSync.time_travel 
318        ~present:lexicon_status ~past:initial_lexicon_status;
319 *))
320   with 
321   (* all exceptions should be wrapped to allow lexicon-undo (LS.time_travel) *)
322   | exn when not matita_debug ->
323 (* MATITA 1.0: debbo fare time_travel sulla ng_library?
324        LexiconSync.time_travel ~present:lexicon ~past:initial_lexicon_status;
325  *       *)
326       pp_times s fname false big_bang big_bang_u big_bang_s;
327       clean_exit baseuri exn
328
329 and assert_ng ~already_included ~compiling ~asserted ~include_paths mapath =
330  let root,baseuri,fullmapath,_ =
331   Librarian.baseuri_of_script ~include_paths mapath in
332  if List.mem fullmapath asserted then asserted,false
333  else
334   begin
335    let include_paths =
336     let includes =
337      try
338       Str.split (Str.regexp " ") 
339        (List.assoc "include_paths" (Librarian.load_root_file (root^"/root")))
340      with Not_found -> []
341     in
342      root::includes @
343       Helm_registry.get_list Helm_registry.string "matita.includes" in
344    let baseuri = NUri.uri_of_string baseuri in
345    let ngtime_of baseuri =
346     let ngpath = NCicLibrary.ng_path_of_baseuri baseuri in
347     try
348      Some (Unix.stat ngpath).Unix.st_mtime
349     with Unix.Unix_error (Unix.ENOENT, "stat", f) when f = ngpath -> None in
350    let matime =
351     try (Unix.stat fullmapath).Unix.st_mtime
352     with Unix.Unix_error (Unix.ENOENT, "stat", f) when f = fullmapath -> assert false
353    in
354    let ngtime = ngtime_of baseuri in
355    let asserted,to_be_compiled =
356     match ngtime with
357        Some ngtime ->
358         let preamble = GrafiteTypes.Serializer.dependencies_of baseuri in
359         let asserted,children_bad =
360          List.fold_left
361           (fun (asserted,b) mapath ->
362             let asserted,b1 =
363               assert_ng ~already_included ~compiling ~asserted ~include_paths
364                mapath
365             in
366              asserted, b || b1
367               || let _,baseuri,_,_ =
368                    (*CSC: bug here? include_paths should be empty and
369                           mapath should be absolute *)
370                    Librarian.baseuri_of_script ~include_paths mapath in
371                  let baseuri = NUri.uri_of_string baseuri in
372                   (match ngtime_of baseuri with
373                       Some child_ngtime -> child_ngtime > ngtime
374                     | None -> assert false)
375           ) (asserted,false) preamble
376         in
377          asserted, children_bad || matime > ngtime
378      | None -> asserted,true
379    in
380     if not to_be_compiled then fullmapath::asserted,false
381     else
382      if List.mem baseuri already_included then
383        (* maybe recompiling it I would get the same... *)
384        raise (AlreadyLoaded (lazy mapath))
385      else
386       let asserted = compile ~compiling ~asserted ~include_paths fullmapath in
387        fullmapath::asserted,true
388   end
389 ;;
390
391 let assert_ng ~include_paths mapath =
392  snd (assert_ng ~include_paths ~already_included:[] ~compiling:[] ~asserted:[]
393   mapath)
394 let get_ast status ~include_paths strm =
395  snd (get_ast status ~compiling:[] ~asserted:[] ~include_paths strm)