]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/registry/helm_registry.ml
- added support for variable interpolation
[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 exception Malformed_key of string
33 exception Key_not_found of string
34 exception Cyclic_definition of string
35 exception Type_error of string * string * string (* expected type, value, msg *)
36 exception Parse_error of string * int * int * string  (* file, line, col, msg *)
37 exception Invalid_value of (string * string) * string (* key, value, descr *)
38
39 type validator_id = int
40
41 let get_next_validator_id =
42   let next_id = ref 0 in
43   fun () ->
44     incr next_id;
45     !next_id
46
47 let magic_size = 127
48 let validators = Hashtbl.create magic_size
49 let registry = Hashtbl.create magic_size
50
51 let backup_registry () = Hashtbl.copy registry
52 let restore_registry backup =
53   Hashtbl.clear registry;
54   Hashtbl.iter (fun key value -> Hashtbl.replace registry key value) backup
55
56   (* as \\w but:
57    * - no sequences of '_' longer than 1 are permitted
58    * - no uppercase letter are permitted
59    *)
60 (*
61 let valid_step_rex_raw = "[a-z0-9]+(_[a-z0-9]+)*"
62 let valid_key_rex_raw =
63   sprintf "^%s(\\.%s)*$" valid_step_rex_raw valid_step_rex_raw
64 let valid_key_rex = Pcre.regexp valid_key_rex_raw
65 let dot_rex = Pcre.regexp "\\."
66 let spaces_rex = Pcre.regexp "\\s+"
67 let heading_spaces_rex = Pcre.regexp "^\\s+"
68 *)
69 let valid_step_rex_raw = "[a-z0-9]+\\(_[a-z0-9]+\\)*"
70 let valid_key_rex_raw =
71   sprintf "%s\(\\.%s\)*" valid_step_rex_raw valid_step_rex_raw
72 let valid_key_rex = Str.regexp ("^" ^ valid_key_rex_raw ^ "$")
73 let interpolated_key_rex = Str.regexp ("\\$(" ^ valid_key_rex_raw ^ ")")
74 let dot_rex = Str.regexp "\\."
75 let spaces_rex = Str.regexp "[ \t\n\r]+"
76 let heading_spaces_rex = Str.regexp "^[ \t\n\r]+"
77
78   (* escapes for xml configuration file *)
79 let (escape, unescape) =
80   let (in_enc, out_enc) = (`Enc_utf8, `Enc_utf8) in
81   (Netencoding.Html.encode ~in_enc ~out_enc (),
82    Netencoding.Html.decode ~in_enc ~out_enc ~entity_base:`Xml ())
83
84 let key_is_valid key =
85 (*   if not (Pcre.pmatch ~rex:valid_key_rex key) then *)
86   if not (Str.string_match valid_key_rex key 0) then
87     raise (Malformed_key key)
88
89 let value_is_valid ~key ~value =
90   List.iter
91     (fun (validator, descr) ->
92       if not (validator value) then
93         raise (Invalid_value ((key, value), descr)))
94     (Hashtbl.find_all validators key)
95
96 let set' registry ~key ~value =
97   debug_print (sprintf "Setting %s = %s" key value);
98   key_is_valid key;
99   value_is_valid ~key ~value;
100   Hashtbl.replace registry key value
101
102 let env_var_of_key key =
103 (*   Pcre.replace ~rex:dot_rex ~templ:"__" (String.uppercase key) *)
104   Str.global_replace dot_rex "__" (String.uppercase key)
105
106 let get key =
107   let rec aux stack key =
108     key_is_valid key;
109     if List.mem key stack then begin
110       let msg = (String.concat " -> " (List.rev stack)) ^ " -> " ^ key in
111       raise (Cyclic_definition msg)
112     end;
113     let registry_value =  (* internal value *)
114       try
115         Some (Hashtbl.find registry key)
116       with Not_found -> None
117     in
118     let env_value = (* environment value *)
119       try
120         Some (Sys.getenv (env_var_of_key key))
121       with Not_found -> None
122     in
123     let value = (* resulting value *)
124       match (registry_value, env_value) with
125       | Some reg, Some env  -> env
126       | Some reg, None      -> reg
127       | None,     Some env  -> env
128       | None,     None      -> raise (Key_not_found key)
129     in
130     interpolate (key :: stack) value
131   and interpolate stack value =
132     Str.global_substitute interpolated_key_rex
133       (fun s ->
134         let matched = Str.matched_string s in
135           (* "$(var)" -> "var" *)
136         let key = String.sub matched 2 (String.length matched - 3) in
137         aux stack key)
138       value
139   in
140   aux [] key
141
142 let set = set' registry
143
144 let string_list_of_string s =
145   (* trailing blanks are removed per default by split *)
146 (*   Pcre.split ~res:spaces_rex (Pcre.replace ~rex:heading_spaces_rex s) *)
147   Str.split spaces_rex (Str.global_replace heading_spaces_rex "" s)
148 let string_of_string_list l = String.concat " " l
149
150 let mk_get_set type_name (from_string: string -> 'a) (to_string: 'a -> string) =
151   let getter key =
152     let value = get key in
153     try
154       from_string value
155     with exn ->
156       raise (Type_error (type_name, value, Printexc.to_string exn))
157   in
158   let setter ~key ~value = set ~key ~value:(to_string value) in
159   (getter, setter)
160
161 let (get_string, set_string) = (get, set)
162 let (get_int, set_int) = mk_get_set "int" int_of_string string_of_int
163 let (get_float, set_float) = mk_get_set "float" float_of_string string_of_float
164 let (get_string_list, set_string_list) =
165   mk_get_set "string list" string_list_of_string string_of_string_list
166
167 let save_to fname =
168   debug_print ("Saving configuration to " ^ fname);
169   let oc = open_out fname in
170   output_string oc "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
171   output_string oc "<helm_registry>\n";
172   try
173     Hashtbl.iter
174       (fun key value ->
175         fprintf oc "  <value key=\"%s\">%s</value>\n" key (escape value))
176       registry;
177     output_string oc "</helm_registry>";
178     close_out oc
179   with e ->
180     close_out oc;
181     raise e
182
183 let add_validator ~key ~validator ~descr =
184   let id = get_next_validator_id () in
185   Hashtbl.add validators key (validator, descr);
186   id
187
188 open Pxp_document
189 open Pxp_types
190 open Pxp_yacc
191
192 let load_from =
193   let config = default_config in
194   let entry = `Entry_document [ `Extend_dtd_fully; `Parse_xml_decl ] in
195   fun fname ->
196     debug_print ("Loading configuration from " ^ fname);
197     let document =
198       parse_wfdocument_entity config (from_file fname) default_spec
199     in
200     let fill_registry () =
201       document#root#iter_nodes (fun n ->
202         try
203           (match n#node_type with
204           | T_element "value" ->
205               let key = n#required_string_attribute "key" in
206               let value = n#data in
207               set ~key ~value
208           | _ -> ())
209         with exn ->
210           let (fname, line, pos) = n#position in
211           raise (Parse_error (fname, line, pos,
212             "Uncaught exception: " ^ Printexc.to_string exn)))
213     in
214     let backup = backup_registry () in
215     Hashtbl.clear registry;
216     try
217       fill_registry ()
218     with exn ->
219       restore_registry backup;
220       raise exn
221
222   (* DEBUGGING ONLY *)
223
224 let dump () = Hashtbl.iter (fun k v -> printf "%s = %s\n" k v) registry
225