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