]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/registry/helm_registry.ml
- added "has" method
[helm.git] / helm / ocaml / registry / helm_registry.ml
1 (* Copyright (C) 2004, 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
28 let debug = false
29 let debug_print s =
30   if debug then prerr_endline ("Helm_registry debugging: " ^ s)
31
32   (** <helpers> *)
33
34 let list_uniq l =
35   let rec aux last_element = function
36     | [] -> []
37     | hd :: tl ->
38         (match last_element with
39         | Some elt when elt = hd -> aux last_element tl
40         | _ -> hd :: aux (Some hd) tl)
41   in
42   aux None l
43
44 let starts_with prefix =
45 (*
46   let rex = Str.regexp (Str.quote prefix) in
47   fun s -> Str.string_match rex s 0
48 *)
49   let prefix_len = String.length prefix in
50   fun s ->
51     try
52       String.sub s 0 prefix_len = prefix
53     with Invalid_argument _ -> false
54
55 let hashtbl_keys tbl = Hashtbl.fold (fun k _ acc -> k :: acc) tbl []
56 let hashtbl_pairs tbl = Hashtbl.fold (fun k v acc -> (k,v) :: acc) tbl []
57
58   (** </helpers> *)
59
60 exception Malformed_key of string
61 exception Key_not_found of string
62 exception Cyclic_definition of string
63 exception Type_error of string * string * string (* expected type, value, msg *)
64 exception Parse_error of string * int * int * string  (* file, line, col, msg *)
65 exception Invalid_value of (string * string) * string (* key, value, descr *)
66
67 type validator_id = int
68
69   (* root XML tag: used by save_to, ignored by load_from *)
70 let root_tag = "helm_registry"
71
72 let get_next_validator_id =
73   let next_id = ref 0 in
74   fun () ->
75     incr next_id;
76     !next_id
77
78 let magic_size = 127
79 let validators = Hashtbl.create magic_size
80 let registry = Hashtbl.create magic_size
81
82 let backup_registry () = Hashtbl.copy registry
83 let restore_registry backup =
84   Hashtbl.clear registry;
85   Hashtbl.iter (fun key value -> Hashtbl.replace registry key value) backup
86
87   (* as \\w but:
88    * - no sequences of '_' longer than 1 are permitted
89    * - no uppercase letter are permitted
90    *)
91 let valid_step_rex_raw = "[a-z0-9]+\\(_[a-z0-9]+\\)*"
92 let valid_key_rex_raw =
93   sprintf "%s\(\\.%s\)*" valid_step_rex_raw valid_step_rex_raw
94 let valid_key_rex = Str.regexp ("^" ^ valid_key_rex_raw ^ "$")
95 let interpolated_key_rex = Str.regexp ("\\$(" ^ valid_key_rex_raw ^ ")")
96 let dot_rex = Str.regexp "\\."
97 let spaces_rex = Str.regexp "[ \t\n\r]+"
98 let heading_spaces_rex = Str.regexp "^[ \t\n\r]+"
99
100 let split s =
101   (* trailing blanks are removed per default by split *)
102   Str.split spaces_rex (Str.global_replace heading_spaces_rex "" s)
103 let merge l = String.concat " " l
104
105   (* escapes for xml configuration file *)
106 let (escape, unescape) =
107   let (in_enc, out_enc) = (`Enc_utf8, `Enc_utf8) in
108   (Netencoding.Html.encode ~in_enc ~out_enc (),
109    Netencoding.Html.decode ~in_enc ~out_enc ~entity_base:`Xml ())
110
111 let key_is_valid key =
112   if not (Str.string_match valid_key_rex key 0) then
113     raise (Malformed_key key)
114
115 let value_is_valid ~key ~value =
116   List.iter
117     (fun (validator, descr) ->
118       if not (validator value) then
119         raise (Invalid_value ((key, value), descr)))
120     (Hashtbl.find_all validators key)
121
122 let set' registry ~key ~value =
123   debug_print (sprintf "Setting %s = %s" key value);
124   key_is_valid key;
125   value_is_valid ~key ~value;
126   Hashtbl.replace registry key value
127
128 let unset = Hashtbl.remove registry
129
130 let env_var_of_key key =
131   Str.global_replace dot_rex "__" (String.uppercase key)
132
133 let get key =
134   let rec aux stack key =
135     key_is_valid key;
136     if List.mem key stack then begin
137       let msg = (String.concat " -> " (List.rev stack)) ^ " -> " ^ key in
138       raise (Cyclic_definition msg)
139     end;
140     let registry_value =  (* internal value *)
141       try
142         Some (Hashtbl.find registry key)
143       with Not_found -> None
144     in
145     let env_value = (* environment value *)
146       try
147         Some (Sys.getenv (env_var_of_key key))
148       with Not_found -> None
149     in
150     let value = (* resulting value *)
151       match (registry_value, env_value) with
152       | Some reg, Some env  -> env
153       | Some reg, None      -> reg
154       | None,     Some env  -> env
155       | None,     None      -> raise (Key_not_found key)
156     in
157     interpolate (key :: stack) value
158   and interpolate stack value =
159     Str.global_substitute interpolated_key_rex
160       (fun s ->
161         let matched = Str.matched_string s in
162           (* "$(var)" -> "var" *)
163         let key = String.sub matched 2 (String.length matched - 3) in
164         aux stack key)
165       value
166   in
167   aux [] key
168
169 let set = set' registry
170
171 let has key = Hashtbl.mem registry key
172
173 let mk_get_set type_name (from_string: string -> 'a) (to_string: 'a -> string) =
174   let getter key =
175     let value = get key in
176     try
177       from_string value
178     with exn ->
179       raise (Type_error (type_name, value, Printexc.to_string exn))
180   in
181   let setter ~key ~value = set ~key ~value:(to_string value) in
182   (getter, setter)
183
184 let (get_string, set_string) = (get, set)
185 let (get_int, set_int) = mk_get_set "int" int_of_string string_of_int
186 let (get_float, set_float) = mk_get_set "float" float_of_string string_of_float
187 let (get_bool, set_bool) = mk_get_set "bool" bool_of_string string_of_bool
188 let (get_string_list, set_string_list) = mk_get_set "string list" split merge
189
190 let get_opt getter key =
191   try
192     Some (getter key)
193   with Key_not_found _ -> None
194 let set_opt setter ~key ~value =
195   match value with
196   | None -> unset key
197   | Some value -> setter ~key ~value
198 let get_opt_default getter default key =
199   match get_opt getter key with
200   | None -> default
201   | Some v -> v
202
203 let add_validator ~key ~validator ~descr =
204   let id = get_next_validator_id () in
205   Hashtbl.add validators key (validator, descr);
206   id
207
208 open Pxp_dtd
209 open Pxp_document
210 open Pxp_types
211 open Pxp_yacc
212
213 let save_to =
214   let dtd = new dtd PxpHelmConf.pxp_config.warner `Enc_utf8 in
215   let dot_RE = Str.regexp "\\." in
216   let create_key_node key value = (* create a <key name="foo">value</key> *)
217     let element =
218       create_element_node ~valcheck:false PxpHelmConf.pxp_spec dtd
219         "key" ["name", key]
220     in
221     let data = create_data_node PxpHelmConf.pxp_spec dtd value in
222     element#append_node data;
223     element
224   in
225   let is_section name =
226     fun node ->
227       match node#node_type with
228       | T_element "section" ->
229           (try node#attribute "name" = Value name with Not_found -> false)
230       | _ -> false
231   in
232   let add_key_node root sections key value =
233     let rec aux node = function
234       | [] ->
235           let key_node = create_key_node key value in
236           node#append_node key_node
237       | section :: tl ->
238           let next_node =
239             try
240               find ~deeply:false (is_section section) node
241             with Not_found ->
242               let section_node =
243                 create_element_node ~valcheck:false PxpHelmConf.pxp_spec dtd
244                   "section" ["name", section]
245               in
246               node#append_node section_node;
247               section_node
248           in
249           aux next_node tl
250     in
251     aux root sections
252   in
253   fun fname ->
254     let xml_root =
255       create_element_node ~valcheck:false PxpHelmConf.pxp_spec dtd "helm_registry" []
256     in
257     Hashtbl.iter
258       (fun key value ->
259         let sections, key =
260           let hd, tl =
261             match List.rev (Str.split dot_RE key) with
262             | hd :: tl -> hd, tl
263             | _ -> assert false
264           in
265           List.rev tl, hd
266         in
267         add_key_node xml_root sections key value)
268       registry;
269       let outchan = (* let's write xml output to fname *)
270         if Unix.system "xmllint --version &> /dev/null" = Unix.WEXITED 0 then
271           (* xmllint available, use it! *)
272           Unix.open_process_out (sprintf
273             "xmllint --format --encode utf8 -o '%s' -" fname)
274         else
275           (* xmllint not available, write pxp ugly output directly to fname *)
276           open_out fname
277       in
278       xml_root#write (`Out_channel outchan) `Enc_utf8;
279       close_out outchan
280
281 let load_from_absolute =
282   let config = PxpHelmConf.pxp_config in
283   let entry = `Entry_document [ `Extend_dtd_fully; `Parse_xml_decl ] in
284   let fold_key key_stack key =
285     match key_stack with
286     | [] -> key
287     | _ -> String.concat "." key_stack ^ "." ^ key
288   in
289   fun fname ->
290     debug_print ("Loading configuration from " ^ fname);
291     let document =
292       parse_wfdocument_entity config (from_file fname) PxpHelmConf.pxp_spec
293     in
294     let rec aux key_stack node =
295       node#iter_nodes (fun n ->
296         try
297           (match n#node_type with
298           | T_element "section" ->
299               let section = n#required_string_attribute "name" in
300               aux (key_stack @ [section]) n
301           | T_element "key" ->
302               let key = n#required_string_attribute "name" in
303               let value = n#data in
304               set ~key:(fold_key key_stack key) ~value
305           | _ -> ())
306         with exn ->
307           let (fname, line, pos) = n#position in
308           raise (Parse_error (fname, line, pos,
309             "Uncaught exception: " ^ Printexc.to_string exn)))
310     in
311     let backup = backup_registry () in
312     Hashtbl.clear registry;
313     try
314       aux [] document#root
315     with exn ->
316       restore_registry backup;
317       raise exn
318
319 let load_from ?path fname =
320   if Filename.is_relative fname then begin
321     let no_file_found = ref true in
322     let path =
323       match path with
324       | Some path -> path (* path given as argument *)
325       | None -> [ Sys.getcwd () ] (* no path given, try with cwd *)
326     in
327     List.iter
328       (fun dir ->
329         let conffile = dir ^ "/" ^ fname in
330         if Sys.file_exists conffile then begin
331           no_file_found := false;
332           load_from_absolute conffile
333         end)
334        path;
335     if !no_file_found then
336       failwith (sprintf
337         "Helm_registry.init: no configuration file named %s in [ %s ]"
338         fname (String.concat "; " path))
339   end else
340     load_from_absolute fname
341
342 let fold ?prefix f init =
343   match prefix with
344   | None -> Hashtbl.fold (fun k v acc -> f acc k v) registry init
345   | Some s ->
346       let key_matches = starts_with (s ^ ".") in
347       let rec fold_filter acc = function
348         | [] -> acc
349         | (k,v) :: tl when key_matches k -> fold_filter (f acc k v) tl
350         | _ :: tl -> fold_filter acc tl
351       in
352       fold_filter init (hashtbl_pairs registry)
353
354 let iter ?prefix f = fold ?prefix (fun _ k v -> f k v) ()
355 let to_list ?prefix () = fold ?prefix (fun acc k v -> (k, v) :: acc) []
356
357 let ls prefix =
358   let prefix = prefix ^ "." in
359   let prefix_len = String.length prefix in
360   let key_matches = starts_with prefix in
361   let matching_keys = (* collect matching keys' _postfixes_ *)
362     fold
363       (fun acc key _ ->
364         if key_matches key then
365           String.sub key prefix_len (String.length key - prefix_len) :: acc
366         else
367           acc)
368       []
369   in
370   let (sections, keys) =
371     List.fold_left
372       (fun (sections, keys) postfix ->
373         match Str.split dot_rex postfix with
374         | [key] -> (sections, key :: keys)
375         | hd_key :: _ ->  (* length > 1 => nested section found *)
376             (hd_key :: sections, keys)
377         | _ -> assert false)
378       ([], []) matching_keys
379   in
380   (list_uniq (List.sort Pervasives.compare sections), keys)
381
382   (* DEBUGGING ONLY *)
383
384 let dump () = Hashtbl.iter (fun k v -> printf "%s = %s\n" k v) registry
385