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