]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/cic_notation/cicNotationRew.ml
handled difference associativity for the same level of the extensible grammar
[helm.git] / helm / ocaml / cic_notation / cicNotationRew.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
28 type pattern_id = int
29 type interpretation_id = pattern_id
30 type pretty_printer_id = pattern_id
31
32 module Ast = CicNotationPt
33
34 type term_info =
35   { sort: (Cic.id, Ast.sort_kind) Hashtbl.t;
36     uri: (Cic.id, string) Hashtbl.t;
37   }
38
39 let get_types uri =
40   let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
41     match o with
42       | Cic.InductiveDefinition (l,_,_,_) -> l 
43       | _ -> assert false
44
45 let name_of_inductive_type uri i = 
46   let types = get_types uri in
47   let (name, _, _, _) = try List.nth types i with Not_found -> assert false in
48   name
49
50   (* returns <name, type> pairs *)
51 let constructors_of_inductive_type uri i =
52   let types = get_types uri in
53   let (_, _, _, constructors) = 
54     try List.nth types i with Not_found -> assert false
55   in
56   constructors
57
58   (* returns name only *)
59 let constructor_of_inductive_type uri i j =
60   (try
61     fst (List.nth (constructors_of_inductive_type uri i) (j-1))
62   with Not_found -> assert false)
63
64 let idref id t = Ast.AttributedTerm (`IdRef id, t)
65
66 let resolve_binder = function
67   | `Lambda -> "\\lambda"
68   | `Pi -> "\\Pi"
69   | `Forall -> "\\forall"
70   | `Exists -> "\\exists"
71
72 let binder_attributes = [None, "mathcolor", "blue"]
73 let atop_attributes = [None, "linethickness", "0pt"]
74 let indent_attributes = [None, "indent", "1em"]
75 let keyword_attributes = [None, "mathcolor", "blue"]
76
77 let pp_ast0 t k =
78   let reset_href t = Ast.AttributedTerm (`Href [], t) in
79   let builtin_symbol s = reset_href (Ast.Literal (`Symbol s)) in
80   let binder_symbol s =
81     Ast.AttributedTerm (`XmlAttrs binder_attributes, builtin_symbol s)
82   in
83   let rec aux = function
84     | Ast.Appl ts ->
85         Ast.AttributedTerm (`Level (Ast.apply_prec, Ast.apply_assoc),
86           Ast.Layout
87             (Ast.Box ((Ast.HOV, true, true),
88                       (CicNotationUtil.dress
89                          (Ast.Layout Ast.Break)
90                          (List.map k ts)))))
91     | Ast.Binder (`Forall, (Ast.Ident ("_", _), ty), body)
92     | Ast.Binder (`Pi, (Ast.Ident ("_", _), ty), body) ->
93         Ast.AttributedTerm (`Level (Ast.binder_prec, Ast.binder_assoc),
94           Ast.Layout (Ast.Box ((Ast.HV, false, true), [
95             aux_ty ty;
96             Ast.Layout Ast.Break;                        
97             binder_symbol "\\to";
98             k body])))
99     | Ast.Binder (binder_kind, (id, ty), body) ->
100         Ast.AttributedTerm (`Level (Ast.binder_prec, Ast.binder_assoc),
101           Ast.Layout (Ast.Box ((Ast.HV, false, true), [
102             binder_symbol (resolve_binder binder_kind);
103             k id;
104             builtin_symbol ":";
105             aux_ty ty;
106             Ast.Layout Ast.Break;
107             builtin_symbol ".";
108             k body ])))
109     | t -> CicNotationUtil.visit_ast ~special_k k t
110   and aux_ty = function
111     | None -> builtin_symbol "?"
112     | Some ty -> k ty
113   and special_k = function
114     | Ast.AttributedTerm (attrs, t) -> Ast.AttributedTerm (attrs, k t)
115     | _ -> assert false
116   in
117   aux t
118
119 let ast_of_acic0 term_info acic k =
120   let k = k term_info in
121   let register_uri id uri = Hashtbl.add term_info.uri id uri in
122   let sort_of_id id =
123     try
124       Hashtbl.find term_info.sort id
125     with Not_found -> assert false
126   in
127   let aux_substs substs =
128     Some
129       (List.map
130         (fun (uri, annterm) -> (UriManager.name_of_uri uri, k annterm))
131         substs)
132   in
133   let aux_context context =
134     List.map
135       (function
136         | None -> None
137         | Some annterm -> Some (k annterm))
138       context
139   in
140   let aux = function
141     | Cic.ARel (id,_,_,b) -> idref id (Ast.Ident (b, None))
142     | Cic.AVar (id,uri,substs) ->
143         register_uri id (UriManager.string_of_uri uri);
144         idref id (Ast.Ident (UriManager.name_of_uri uri, aux_substs substs))
145     | Cic.AMeta (id,n,l) -> idref id (Ast.Meta (n, aux_context l))
146     | Cic.ASort (id,Cic.Prop) -> idref id (Ast.Sort `Prop)
147     | Cic.ASort (id,Cic.Set) -> idref id (Ast.Sort `Set)
148     | Cic.ASort (id,Cic.Type _) -> idref id (Ast.Sort `Type)
149     | Cic.ASort (id,Cic.CProp) -> idref id (Ast.Sort `CProp)
150     | Cic.AImplicit _ -> assert false
151     | Cic.AProd (id,n,s,t) ->
152         let binder_kind =
153           match sort_of_id id with
154           | `Set | `Type -> `Pi
155           | `Prop | `CProp -> `Forall
156         in
157         idref id (Ast.Binder (binder_kind,
158           (CicNotationUtil.name_of_cic_name n, Some (k s)), k t))
159     | Cic.ACast (id,v,t) -> idref id (Ast.Cast (k v, k t))
160     | Cic.ALambda (id,n,s,t) ->
161         idref id (Ast.Binder (`Lambda,
162           (CicNotationUtil.name_of_cic_name n, Some (k s)), k t))
163     | Cic.ALetIn (id,n,s,t) ->
164         idref id (Ast.LetIn ((CicNotationUtil.name_of_cic_name n, None),
165           k s, k t))
166     | Cic.AAppl (aid,args) -> idref aid (Ast.Appl (List.map k args))
167     | Cic.AConst (id,uri,substs) ->
168         register_uri id (UriManager.string_of_uri uri);
169         idref id (Ast.Ident (UriManager.name_of_uri uri, aux_substs substs))
170     | Cic.AMutInd (id,uri,i,substs) as t ->
171         let name = name_of_inductive_type uri i in
172         let uri_str = UriManager.string_of_uri uri in
173         let puri_str =
174           uri_str ^ "#xpointer(1/" ^ (string_of_int (i + 1)) ^ ")"
175         in
176         register_uri id puri_str;
177         idref id (Ast.Ident (name, aux_substs substs))
178     | Cic.AMutConstruct (id,uri,i,j,substs) ->
179         let name = constructor_of_inductive_type uri i j in
180         let uri_str = UriManager.string_of_uri uri in
181         let puri_str = sprintf "%s#xpointer(1/%d/%d)" uri_str (i + 1) j in
182         register_uri id puri_str;
183         idref id (Ast.Ident (name, aux_substs substs))
184     | Cic.AMutCase (id,uri,typeno,ty,te,patterns) ->
185         let name = name_of_inductive_type uri typeno in
186         let constructors = constructors_of_inductive_type uri typeno in
187         let rec eat_branch ty pat =
188           match (ty, pat) with
189           | Cic.Prod (_, _, t), Cic.ALambda (_, name, s, t') ->
190               let (cv, rhs) = eat_branch t t' in
191               (CicNotationUtil.name_of_cic_name name, Some (k s)) :: cv, rhs
192           | _, _ -> [], k pat
193         in
194         let patterns =
195           List.map2
196             (fun (name, ty) pat ->
197               let (capture_variables, rhs) = eat_branch ty pat in
198               ((name, capture_variables), rhs))
199             constructors patterns
200         in
201         idref id (Ast.Case (k te, Some name, Some (k ty), patterns))
202     | Cic.AFix (id, no, funs) -> 
203         let defs = 
204           List.map
205             (fun (_, n, decr_idx, ty, bo) ->
206               ((Ast.Ident (n, None), Some (k ty)), k bo, decr_idx))
207             funs
208         in
209         let name =
210           try
211             (match List.nth defs no with
212             | (Ast.Ident (n, _), _), _, _ when n <> "_" -> n
213             | _ -> assert false)
214           with Not_found -> assert false
215         in
216         idref id (Ast.LetRec (`Inductive, defs, Ast.Ident (name, None)))
217     | Cic.ACoFix (id, no, funs) -> 
218         let defs = 
219           List.map
220             (fun (_, n, ty, bo) -> ((Ast.Ident (n, None), Some (k ty)), k bo, 0))
221             funs
222         in
223         let name =
224           try
225             (match List.nth defs no with
226             | (Ast.Ident (n, _), _), _, _ when n <> "_" -> n
227             | _ -> assert false)
228           with Not_found -> assert false
229         in
230         idref id (Ast.LetRec (`CoInductive, defs, Ast.Ident (name, None)))
231   in
232   aux acic
233
234   (* persistent state *)
235
236 let level1_patterns21 = Hashtbl.create 211
237 let level2_patterns32 = Hashtbl.create 211
238 let interpretations = Hashtbl.create 211  (* symb -> id list ref *)
239
240 let compiled21 = ref None
241 let compiled32 = ref None
242
243 let pattern21_matrix = ref []
244 let pattern32_matrix = ref []
245
246 let get_compiled21 () =
247   match !compiled21 with
248   | None -> assert false
249   | Some f -> Lazy.force f
250 let get_compiled32 () =
251   match !compiled32 with
252   | None -> assert false
253   | Some f -> Lazy.force f
254
255 let set_compiled21 f = compiled21 := Some f
256 let set_compiled32 f = compiled32 := Some f
257
258 let instantiate21 env (* precedence associativity *) l1 =
259   let rec subst_singleton env t =
260     CicNotationUtil.group (subst env t)
261   and subst env = function
262     | Ast.AttributedTerm (_, t) -> subst env t
263     | Ast.Variable var ->
264         let name, expected_ty = CicNotationEnv.declaration_of_var var in
265         let ty, value =
266           try
267             List.assoc name env
268           with Not_found -> assert false
269         in
270         assert (CicNotationEnv.well_typed ty value); (* INVARIANT *)
271         (* following assertion should be a conditional that makes this
272          * instantiation fail *)
273         assert (CicNotationEnv.well_typed expected_ty value);
274         [ CicNotationEnv.term_of_value value ]
275     | Ast.Magic m -> subst_magic env m
276     | Ast.Literal (`Keyword k) as t ->
277         [ Ast.AttributedTerm (`XmlAttrs keyword_attributes, t) ]
278     | Ast.Literal _ as t -> [ t ]
279     | Ast.Layout l -> [ Ast.Layout (subst_layout env l) ]
280     | t -> [ CicNotationUtil.visit_ast (subst_singleton env) t ]
281   and subst_magic env = function
282     | Ast.List0 (p, sep_opt)
283     | Ast.List1 (p, sep_opt) ->
284         let rec_decls = CicNotationEnv.declarations_of_term p in
285         let rec_values =
286           List.map (fun (n, _) -> CicNotationEnv.lookup_list env n) rec_decls
287         in
288         let values = CicNotationUtil.ncombine rec_values in
289         let sep =
290           match sep_opt with
291             | None -> []
292             | Some l -> [ Ast.Literal l ]
293         in
294         let rec instantiate_list acc = function
295           | [] -> List.rev acc
296           | value_set :: [] ->
297               let env = CicNotationEnv.combine rec_decls value_set in
298                 instantiate_list (CicNotationUtil.group (subst env p) :: acc) []
299           | value_set :: tl ->
300               let env = CicNotationEnv.combine rec_decls value_set in
301                 instantiate_list (CicNotationUtil.group ((subst env p) @ sep) :: acc) tl
302         in
303         instantiate_list [] values
304     | Ast.Opt p ->
305         let opt_decls = CicNotationEnv.declarations_of_term p in
306         let env =
307           let rec build_env = function
308             | [] -> []
309             | (name, ty) :: tl ->
310                   (* assumption: if one of the value is None then all are *)
311                 (match CicNotationEnv.lookup_opt env name with
312                 | None -> raise Exit
313                 | Some v -> (name, (ty, v)) :: build_env tl)
314           in
315           try build_env opt_decls with Exit -> []
316         in
317           begin
318             match env with
319               | [] -> []
320               | _ -> subst env p
321           end
322     | _ -> assert false (* impossible *)
323   and subst_layout env = function
324     | Ast.Box (kind, tl) ->
325         Ast.Box (kind, List.concat (List.map (subst env) tl))
326     | l -> CicNotationUtil.visit_layout (subst_singleton env) l
327   in
328     subst_singleton env l1
329
330 let rec pp_ast1 term = 
331   let rec pp_value = function
332     | CicNotationEnv.NumValue _ as v -> v
333     | CicNotationEnv.StringValue _ as v -> v
334 (*     | CicNotationEnv.TermValue t when t == term -> CicNotationEnv.TermValue (pp_ast0 t pp_ast1) *)
335     | CicNotationEnv.TermValue t -> CicNotationEnv.TermValue (pp_ast1 t)
336     | CicNotationEnv.OptValue None as v -> v
337     | CicNotationEnv.OptValue (Some v) -> 
338         CicNotationEnv.OptValue (Some (pp_value v))
339     | CicNotationEnv.ListValue vl ->
340         CicNotationEnv.ListValue (List.map pp_value vl)
341   in
342   let ast_env_of_env env =
343     List.map (fun (var, (ty, value)) -> (var, (ty, pp_value value))) env
344   in
345   match term with
346   | Ast.AttributedTerm (attrs, t) -> Ast.AttributedTerm (attrs, pp_ast1 t)
347   | _ ->
348       begin
349         match (get_compiled21 ()) term with
350           | None -> pp_ast0 term pp_ast1
351           | Some (env, pid) ->
352               let precedence, associativity, l1 =
353                 try
354                   Hashtbl.find level1_patterns21 pid
355                 with Not_found -> assert false
356               in
357                 Ast.AttributedTerm (`Level (precedence, associativity),
358                                 (instantiate21 (ast_env_of_env env) l1))
359       end
360
361 let instantiate32 term_info env symbol args =
362   let rec instantiate_arg = function
363     | Ast.IdentArg (n, name) ->
364         let t = (try List.assoc name env with Not_found -> assert false) in
365         let rec count_lambda = function
366           | Ast.Binder (`Lambda, _, body) -> 1 + count_lambda body
367           | _ -> 0
368         in
369         let rec add_lambda t n =
370           if n > 0 then
371             let name = CicNotationUtil.fresh_name () in
372             Ast.Binder (`Lambda, (Ast.Ident (name, None), None),
373               Ast.Appl [add_lambda t (n - 1); Ast.Ident (name, None)])
374           else
375             t
376         in
377         add_lambda t (n - count_lambda t)
378   in
379   let args' = List.map instantiate_arg args in
380   Ast.Appl (Ast.Symbol (symbol, 0) :: args')
381
382 let rec ast_of_acic1 term_info annterm = 
383   match (get_compiled32 ()) annterm with
384   | None -> ast_of_acic0 term_info annterm ast_of_acic1
385   | Some (env, pid) -> 
386       let env' =
387         List.map (fun (name, term) -> (name, ast_of_acic1 term_info term)) env
388       in
389       let _, symbol, args, _, uris =
390         try
391           Hashtbl.find level2_patterns32 pid
392         with Not_found -> assert false
393       in
394       let ast = instantiate32 term_info env' symbol args in
395       match uris with
396       | [] -> ast
397       | _ -> Ast.AttributedTerm (`Href uris, ast)
398
399 let load_patterns32 t =
400   set_compiled32 (lazy (CicNotationMatcher.Matcher32.compiler t))
401
402 let load_patterns21 t =
403   set_compiled21 (lazy (CicNotationMatcher.Matcher21.compiler t))
404
405 let ast_of_acic id_to_sort annterm =
406   let term_info = { sort = id_to_sort; uri = Hashtbl.create 211 } in
407   let ast = ast_of_acic1 term_info annterm in
408   ast, term_info.uri
409
410 let pp_ast term = pp_ast1 term
411
412 let fresh_id =
413   let counter = ref ~-1 in
414   fun () ->
415     incr counter;
416     !counter
417
418 let add_interpretation dsc (symbol, args) appl_pattern =
419   let id = fresh_id () in
420   let uris = CicNotationUtil.find_appl_pattern_uris appl_pattern in
421   Hashtbl.add level2_patterns32 id (dsc, symbol, args, appl_pattern, uris);
422   pattern32_matrix := (appl_pattern, id) :: !pattern32_matrix;
423   load_patterns32 !pattern32_matrix;
424   (try
425     let ids = Hashtbl.find interpretations symbol in
426     ids := id :: !ids
427   with Not_found -> Hashtbl.add interpretations symbol (ref [id]));
428   id
429
430 exception Interpretation_not_found
431 exception Pretty_printer_not_found
432
433 let lookup_interpretations symbol =
434   try
435     List.map
436       (fun id ->
437         let (dsc, _, args, appl_pattern, _) =
438           try
439             Hashtbl.find level2_patterns32 id
440           with Not_found -> assert false 
441         in
442         dsc, args, appl_pattern)
443       !(Hashtbl.find interpretations symbol)
444   with Not_found -> raise Interpretation_not_found
445
446 let add_pretty_printer ~precedence ~associativity l2 l1 =
447   let id = fresh_id () in
448   let l2' = CicNotationUtil.strip_attributes l2 in
449   Hashtbl.add level1_patterns21 id (precedence, associativity, l1);
450   pattern21_matrix := (l2', id) :: !pattern21_matrix;
451   load_patterns21 !pattern21_matrix;
452   id
453
454 let remove_interpretation id =
455   (try
456     let _, symbol, _, _, _ = Hashtbl.find level2_patterns32 id in
457     let ids = Hashtbl.find interpretations symbol in
458     ids := List.filter ((<>) id) !ids;
459     Hashtbl.remove level2_patterns32 id;
460   with Not_found -> raise Interpretation_not_found);
461   pattern32_matrix := List.filter (fun (_, id') -> id <> id') !pattern32_matrix;
462   load_patterns32 !pattern32_matrix
463
464 let remove_pretty_printer id =
465   (try
466     Hashtbl.remove level1_patterns21 id;
467   with Not_found -> raise Pretty_printer_not_found);
468   pattern21_matrix := List.filter (fun (_, id') -> id <> id') !pattern21_matrix;
469   load_patterns21 !pattern21_matrix
470
471 let _ =
472   load_patterns21 [];
473   load_patterns32 []
474