]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaMisc.ml
universes are saved to disk
[helm.git] / helm / matita / matitaMisc.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 open Printf
27 open MatitaTypes 
28
29 (** Functions "imported" from Http_getter_misc *)
30
31 let strip_trailing_slash = Http_getter_misc.strip_trailing_slash
32 let normalize_dir = Http_getter_misc.normalize_dir
33 let strip_suffix = Http_getter_misc.strip_suffix
34
35 let baseuri_of_baseuri_decl st =
36   match st with
37   | GrafiteAst.Executable (_, GrafiteAst.Command (_, GrafiteAst.Set (_, "baseuri", buri))) ->
38       Some buri
39   | _ -> None
40
41 let baseuri_of_file file = 
42   let uri = ref None in
43   let ic = open_in file in
44   let istream = Ulexing.from_utf8_channel ic in
45   (try
46     while true do
47       try 
48         let stm = GrafiteParser.parse_statement istream in
49         match baseuri_of_baseuri_decl stm with
50         | Some buri -> 
51             let u = strip_trailing_slash buri in
52             if String.length u < 5 || String.sub u 0 5 <> "cic:/" then
53               MatitaLog.error (file ^ " sets an incorrect baseuri: " ^ buri);
54             (try 
55               ignore(Http_getter.resolve u)
56             with
57             | Http_getter_types.Unresolvable_URI _ -> 
58                 MatitaLog.error (file ^ " sets an unresolvable baseuri: "^buri)
59             | Http_getter_types.Key_not_found _ -> ());
60             uri := Some u;
61             raise End_of_file
62         | None -> ()
63       with
64         CicNotationParser.Parse_error _ as exn ->
65           prerr_endline ("Unable to parse: " ^ file);
66           prerr_endline (MatitaExcPp.to_string exn);
67           ()
68     done
69   with End_of_file -> close_in ic);
70   match !uri with
71   | Some uri -> uri
72   | None -> failwith ("No baseuri defined in " ^ file)
73
74 let is_empty buri =
75  List.for_all
76   (function
77       Http_getter_types.Ls_section _ -> true
78     | Http_getter_types.Ls_object _ -> false)
79   (Http_getter.ls (Http_getter_misc.strip_trailing_slash buri ^ "/"))
80
81 let safe_remove fname = if Sys.file_exists fname then Sys.remove fname
82
83 let is_dir fname =
84   try
85     (Unix.stat fname).Unix.st_kind = Unix.S_DIR
86   with Unix.Unix_error _ -> false
87
88 let is_regular fname =
89   try
90     (Unix.stat fname).Unix.st_kind = Unix.S_REG
91   with Unix.Unix_error _ -> false
92
93 let input_file fname =
94   let size = (Unix.stat fname).Unix.st_size in
95   let buf = Buffer.create size in
96   let ic = open_in fname in
97   Buffer.add_channel buf ic size;
98   close_in ic;
99   Buffer.contents buf
100
101 let output_file data file = 
102   let oc = open_out file in
103   output_string oc data;
104   close_out oc
105
106
107 let absolute_path file =
108   if file.[0] = '/' then file else Unix.getcwd () ^ "/" ^ file
109   
110 let is_proof_script fname = true  (** TODO Zack *)
111 let is_proof_object fname = true  (** TODO Zack *)
112
113 let append_phrase_sep s =
114   if not (Pcre.pmatch ~pat:(sprintf "%s$" BuildTimeConf.phrase_sep) s) then
115     s ^ BuildTimeConf.phrase_sep
116   else
117     s
118
119 let mkdir path =
120   let components = Str.split (Str.regexp "/") path in
121   let rec aux where = function
122     | [] -> ()
123     | piece::tl -> 
124         let path = where ^ "/" ^ piece in
125         (try
126           Unix.mkdir path 0o755
127         with 
128         | Unix.Unix_error (Unix.EEXIST,_,_) -> ()
129         | Unix.Unix_error (e,_,_) -> 
130             raise 
131               (Failure 
132                 ("Unix.mkdir " ^ path ^ " 0o755 :" ^ (Unix.error_message e))));
133         aux path tl
134   in
135   aux "" components
136
137 let trim_blanks =
138   let rex = Pcre.regexp "^\\s*(.*?)\\s*$" in
139   fun s -> (Pcre.extract ~rex s).(1)
140
141 let split ?(char = ' ') s =
142   let pieces = ref [] in
143   let rec aux idx =
144     match (try Some (String.index_from s idx char) with Not_found -> None) with
145     | Some pos ->
146         pieces := String.sub s idx (pos - idx) :: !pieces;
147         aux (pos + 1)
148     | None -> pieces := String.sub s idx (String.length s - idx) :: !pieces
149   in
150   aux 0;
151   List.rev !pieces
152
153 let empty_mathml () =
154   DomMisc.domImpl#createDocument ~namespaceURI:(Some DomMisc.mathml_ns)
155     ~qualifiedName:(Gdome.domString "math") ~doctype:None
156
157 let empty_boxml () =
158   DomMisc.domImpl#createDocument ~namespaceURI:(Some DomMisc.boxml_ns) 
159     ~qualifiedName:(Gdome.domString "box") ~doctype:None
160
161 exception History_failure
162
163 type 'a memento = 'a array * int * int * int  (* data, hd, tl, cur *)
164
165 class type ['a] history =
166   object
167     method add : 'a -> unit
168     method next : 'a
169     method previous : 'a
170     method load: 'a memento -> unit
171     method save: 'a memento
172     method is_begin: bool
173     method is_end: bool
174   end
175
176 class basic_history (head, tail, cur) =
177   object
178     val mutable hd = head  (* insertion point *)
179     val mutable tl = tail (* oldest inserted item *)
180     val mutable cur = cur  (* current item for the history *)
181     
182     method is_begin = cur <= tl
183     method is_end = cur >= hd
184   end
185   
186   
187 class shell_history size =
188   let size = size + 1 in
189   let decr x = let x' = x - 1 in if x' < 0 then size + x' else x' in
190   let incr x = (x + 1) mod size in
191   object (self)
192     val data = Array.create size ""
193
194     inherit basic_history (0, -1 , -1)
195     
196     method add s =
197       data.(hd) <- s;
198       if tl = -1 then tl <- hd;
199       hd <- incr hd;
200       if hd = tl then tl <- incr tl;
201       cur <- hd
202     method previous =
203       if cur = tl then raise History_failure;
204       cur <- decr cur;
205       data.(cur)
206     method next =
207       if cur = hd then raise History_failure;
208       cur <- incr cur;
209       if cur = hd then "" else data.(cur)
210     method load (data', hd', tl', cur') =
211       assert (Array.length data = Array.length data');
212       hd <- hd'; tl <- tl'; cur <- cur';
213       Array.blit data' 0 data 0 (Array.length data')
214     method save = (Array.copy data, hd, tl, cur)
215   end
216
217 class ['a] browser_history ?memento size init =
218   object (self)
219     initializer match memento with Some m -> self#load m | _ -> ()
220     val data = Array.create size init
221
222     inherit basic_history (0, 0, 0)
223     
224     method previous =
225       if cur = tl then raise History_failure;
226       cur <- cur - 1;
227       if cur = ~-1 then cur <- size - 1;
228       data.(cur)
229     method next =
230       if cur = hd then raise History_failure;
231       cur <- cur + 1;
232       if cur = size then cur <- 0;
233       data.(cur)
234     method add (e:'a) =
235       if e <> data.(cur) then
236         begin
237           cur <- cur + 1;
238           if cur = size then cur <- 0;
239           if cur = tl then tl <- tl + 1;
240           if tl = size then tl <- 0;
241           hd <- cur;
242           data.(cur) <- e
243         end
244     method load (data', hd', tl', cur') =
245       assert (Array.length data = Array.length data');
246       hd <- hd'; tl <- tl'; cur <- cur';
247       Array.blit data' 0 data 0 (Array.length data')
248     method save = (Array.copy data, hd, tl, cur)
249   end
250
251 let singleton f =
252   let instance = lazy (f ()) in
253   fun () -> Lazy.force instance
254
255 let get_proof_status status =
256   match status.proof_status with
257   | Incomplete_proof s -> s
258   | _ -> statement_error "no ongoing proof"
259
260 let get_proof_metasenv status =
261   match status.proof_status with
262   | No_proof -> []
263   | Incomplete_proof ((_, metasenv, _, _), _) -> metasenv
264   | Proof (_, metasenv, _, _) -> metasenv
265   | Intermediate m -> m
266
267 let get_proof_context status =
268   match status.proof_status with
269   | Incomplete_proof ((_, metasenv, _, _), goal) ->
270       let (_, context, _) = CicUtil.lookup_meta goal metasenv in
271       context
272   | _ -> []
273  
274 let get_proof_conclusion status =
275   match status.proof_status with
276   | Incomplete_proof ((_, metasenv, _, _), goal) ->
277       let (_, _, conclusion) = CicUtil.lookup_meta goal metasenv in
278       conclusion
279   | _ -> statement_error "no ongoing proof"
280  
281 let qualify status name = get_string_option status "baseuri" ^ "/" ^ name
282
283 let unopt = function None -> failwith "unopt: None" | Some v -> v
284
285 let image_path n = sprintf "%s/%s" BuildTimeConf.images_dir n
286
287 let end_ma_RE = Pcre.regexp "\\.ma$"
288
289 let obj_file_of_baseuri baseuri =
290  let path =
291   Helm_registry.get "matita.basedir" ^ "/xml" ^
292    Pcre.replace ~pat:"^cic:" ~templ:"" baseuri
293  in
294   path ^ ".moo"
295
296 let obj_file_of_script f =
297  if f = "coq.ma" then BuildTimeConf.coq_notation_script else
298   let baseuri = baseuri_of_file f in
299    obj_file_of_baseuri baseuri
300
301 let rec list_uniq = function 
302   | [] -> []
303   | h::[] -> [h]
304   | h1::h2::tl when h1 = h2 -> list_uniq (h2 :: tl) 
305   | h1::tl (* when h1 <> h2 *) -> h1 :: list_uniq tl
306
307 let list_tl_at ?(equality=(==)) e l =
308   let rec aux =
309     function
310     | [] -> raise Not_found
311     | hd :: tl as l when equality hd e -> l
312     | hd :: tl -> aux tl
313   in
314   aux l
315
316 let debug_wrap name f =
317   prerr_endline (sprintf "debug_wrap: ==>> %s" name);
318   let res = f () in
319   prerr_endline (sprintf "debug_wrap: <<== %s" name);
320   res
321