]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/cic_notation/cicNotationRew.ml
changed precedence/associativeness handling: relative position of children wrt its...
[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 module Ast = CicNotationPt
29
30 let debug = false
31 let debug_print s = if debug then prerr_endline (Lazy.force s) else ()
32
33 type pattern_id = int
34 type interpretation_id = pattern_id
35 type pretty_printer_id = pattern_id
36
37 type term_info =
38   { sort: (Cic.id, Ast.sort_kind) Hashtbl.t;
39     uri: (Cic.id, UriManager.uri) 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 add_level_info prec assoc t = Ast.AttributedTerm (`Level (prec, assoc), t)
76 let add_pos_info pos t = Ast.AttributedTerm (`ChildPos pos, t)
77
78 let rec remove_level_info =
79   function
80   | Ast.AttributedTerm (`Level _, t) -> remove_level_info t
81   | Ast.AttributedTerm (a, t) -> Ast.AttributedTerm (a, remove_level_info t)
82   | t -> t
83
84 let add_xml_attrs attrs t =
85   if attrs = [] then t else Ast.AttributedTerm (`XmlAttrs attrs, t)
86
87 let add_keyword_attrs =
88   add_xml_attrs (RenderingAttrs.keyword_attributes `MathML)
89
90 let box kind spacing indent content =
91   Ast.Layout (Ast.Box ((kind, spacing, indent), content))
92
93 let hbox = box Ast.H
94 let vbox = box Ast.V
95 let hvbox = box Ast.HV
96 let hovbox = box Ast.HOV
97 let break = Ast.Layout Ast.Break
98 let builtin_symbol s = Ast.Literal (`Symbol s)
99 let keyword k = add_keyword_attrs (Ast.Literal (`Keyword k))
100
101 let number s =
102   add_xml_attrs (RenderingAttrs.number_attributes `MathML)
103     (Ast.Literal (`Number s))
104
105 let ident i =
106   add_xml_attrs (RenderingAttrs.ident_attributes `MathML) (Ast.Ident (i, None))
107
108 let ident_w_href href i =
109   match href with
110   | None -> ident i
111   | Some href ->
112       let href = UriManager.string_of_uri href in
113       add_xml_attrs [Some "xlink", "href", href] (ident i)
114
115 let binder_symbol s =
116   add_xml_attrs (RenderingAttrs.builtin_symbol_attributes `MathML)
117     (builtin_symbol s)
118
119 let string_of_sort_kind = function
120   | `Prop -> "Prop"
121   | `Set -> "Set"
122   | `CProp -> "CProp"
123   | `Type _ -> "Type"
124
125 let pp_ast0 t k =
126   let rec aux =
127     function
128     | Ast.Appl ts ->
129         add_level_info Ast.apply_prec Ast.apply_assoc
130           (hovbox true true (CicNotationUtil.dress break (List.map k ts)))
131     | Ast.Binder (binder_kind, (id, ty), body) ->
132         add_level_info Ast.binder_prec Ast.binder_assoc
133           (hvbox false true
134             [ binder_symbol (resolve_binder binder_kind);
135               k id; builtin_symbol ":"; aux_ty ty; break;
136               builtin_symbol "."; k body ])
137     | Ast.Case (what, indty_opt, outty_opt, patterns) ->
138         let outty_box =
139           match outty_opt with
140           | None -> []
141           | Some outty ->
142               [ builtin_symbol "["; remove_level_info (k outty);
143                 builtin_symbol "]"; break ]
144         in
145         let indty_box =
146           match indty_opt with
147           | None -> []
148           | Some (indty, href) -> [ keyword "in"; ident_w_href href indty ]
149         in
150         let match_box =
151           hvbox false true [
152             keyword "match"; break;
153             hvbox false false ([ k what ] @ indty_box); break;
154             keyword "with" ]
155         in
156         let mk_case_pattern (head, href, vars) =
157           hbox true false (ident_w_href href head :: List.map aux_var vars)
158         in
159         let patterns' =
160           List.map
161             (fun (lhs, rhs) ->
162               remove_level_info
163                 (hvbox false true [
164                   hbox false true [
165                     mk_case_pattern lhs; builtin_symbol "\\Rightarrow" ];
166                   break; k rhs ]))
167             patterns
168         in
169         let patterns'' =
170           let rec aux_patterns = function
171             | [] -> assert false
172             | [ last ] ->
173                 [ break; 
174                   hbox false false [
175                     builtin_symbol "|";
176                     last; builtin_symbol "]" ] ]
177             | hd :: tl ->
178                 [ break; hbox false false [ builtin_symbol "|"; hd ] ]
179                 @ aux_patterns tl
180           in
181           match patterns' with
182           | [] ->
183               [ hbox false false [ builtin_symbol "["; builtin_symbol "]" ] ]
184           | [ one ] ->
185               [ hbox false false [
186                 builtin_symbol "["; one; builtin_symbol "]" ] ]
187           | hd :: tl ->
188               hbox false false [ builtin_symbol "["; hd ]
189               :: aux_patterns tl
190         in
191         add_level_info Ast.simple_prec Ast.simple_assoc
192           (hvbox false false [
193             hvbox false false (outty_box @ [ match_box ]); break;
194             hbox false false [ hvbox false false patterns'' ] ])
195     | Ast.Cast (bo, ty) ->
196         add_level_info Ast.simple_prec Ast.simple_assoc
197           (hvbox false true [
198             builtin_symbol "("; k bo; break; builtin_symbol ":"; k ty;
199             builtin_symbol ")"])
200     | Ast.LetIn (var, s, t) ->
201         add_level_info Ast.let_in_prec Ast.let_in_assoc
202           (hvbox false true [
203             hvbox false true [
204               keyword "let";
205               hvbox false true [
206                 aux_var var; builtin_symbol "\\def"; break; k s ];
207               break; keyword "in" ];
208             break;
209             k t ])
210     | Ast.LetRec (rec_kind, funs, where) ->
211         let rec_op =
212           match rec_kind with `Inductive -> "rec" | `CoInductive -> "corec"
213         in
214         let mk_fun (var, body, _) = aux_var var, k body in
215         let mk_funs = List.map mk_fun in
216         let fst_fun, tl_funs =
217           match mk_funs funs with hd :: tl -> hd, tl | [] -> assert false
218         in
219         let fst_row =
220           let (name, body) = fst_fun in
221           hvbox false true [
222             keyword "let"; keyword rec_op; name; builtin_symbol "\\def"; break;
223             body ]
224         in
225         let tl_rows =
226           List.map
227             (fun (name, body) ->
228               [ break;
229                 hvbox false true [
230                   keyword "and"; name; builtin_symbol "\\def"; break; body ] ])
231             tl_funs
232         in
233         add_level_info Ast.let_in_prec Ast.let_in_assoc
234           ((hvbox false false
235             (fst_row :: List.flatten tl_rows
236              @ [ break; keyword "in"; break; k where ])))
237     | Ast.Implicit -> builtin_symbol "?"
238     | Ast.Meta (n, l) ->
239         let local_context l =
240           CicNotationUtil.dress (builtin_symbol ";")
241             (List.map (function None -> builtin_symbol "_" | Some t -> k t) l)
242         in
243         hbox false false
244           ([ builtin_symbol "?"; number (string_of_int n) ]
245             @ (if l <> [] then local_context l else []))
246     | Ast.Sort sort -> aux_sort sort
247     | Ast.Num _
248     | Ast.Symbol _
249     | Ast.Ident (_, None) | Ast.Ident (_, Some [])
250     | Ast.Uri (_, None) | Ast.Uri (_, Some [])
251     | Ast.Literal _
252     | Ast.UserInput as leaf -> leaf
253     | t -> CicNotationUtil.visit_ast ~special_k k t
254   and aux_sort sort_kind =
255     add_xml_attrs (RenderingAttrs.keyword_attributes `MathML)
256       (Ast.Ident (string_of_sort_kind sort_kind, None))
257   and aux_ty = function
258     | None -> builtin_symbol "?"
259     | Some ty -> k ty
260   and aux_var = function
261     | name, Some ty ->
262         hvbox false true [
263           builtin_symbol "("; name; builtin_symbol ":"; break; k ty;
264           builtin_symbol ")" ]
265     | name, None -> name
266   and special_k = function
267     | Ast.AttributedTerm (attrs, t) -> Ast.AttributedTerm (attrs, k t)
268     | t ->
269         prerr_endline ("unexpected special: " ^ CicNotationPp.pp_term t);
270         assert false
271   in
272   aux t
273
274 let ast_of_acic0 term_info acic k =
275   let k = k term_info in
276   let id_to_uris = term_info.uri in
277   let register_uri id uri = Hashtbl.add id_to_uris id uri in
278   let sort_of_id id =
279     try
280       Hashtbl.find term_info.sort id
281     with Not_found ->
282       prerr_endline (sprintf "warning: sort of id %s not found, using Type" id);
283       `Type (CicUniv.fresh ())
284   in
285   let aux_substs substs =
286     Some
287       (List.map
288         (fun (uri, annterm) -> (UriManager.name_of_uri uri, k annterm))
289         substs)
290   in
291   let aux_context context =
292     List.map
293       (function
294         | None -> None
295         | Some annterm -> Some (k annterm))
296       context
297   in
298   let aux = function
299     | Cic.ARel (id,_,_,b) -> idref id (Ast.Ident (b, None))
300     | Cic.AVar (id,uri,substs) ->
301         register_uri id uri;
302         idref id (Ast.Ident (UriManager.name_of_uri uri, aux_substs substs))
303     | Cic.AMeta (id,n,l) -> idref id (Ast.Meta (n, aux_context l))
304     | Cic.ASort (id,Cic.Prop) -> idref id (Ast.Sort `Prop)
305     | Cic.ASort (id,Cic.Set) -> idref id (Ast.Sort `Set)
306     | Cic.ASort (id,Cic.Type u) -> idref id (Ast.Sort (`Type u))
307     | Cic.ASort (id,Cic.CProp) -> idref id (Ast.Sort `CProp)
308     | Cic.AImplicit _ -> assert false
309     | Cic.AProd (id,n,s,t) ->
310         let binder_kind =
311           match sort_of_id id with
312           | `Set | `Type _ -> `Pi
313           | `Prop | `CProp -> `Forall
314         in
315         idref id (Ast.Binder (binder_kind,
316           (CicNotationUtil.name_of_cic_name n, Some (k s)), k t))
317     | Cic.ACast (id,v,t) -> idref id (Ast.Cast (k v, k t))
318     | Cic.ALambda (id,n,s,t) ->
319         idref id (Ast.Binder (`Lambda,
320           (CicNotationUtil.name_of_cic_name n, Some (k s)), k t))
321     | Cic.ALetIn (id,n,s,t) ->
322         idref id (Ast.LetIn ((CicNotationUtil.name_of_cic_name n, None),
323           k s, k t))
324     | Cic.AAppl (aid,args) -> idref aid (Ast.Appl (List.map k args))
325     | Cic.AConst (id,uri,substs) ->
326         register_uri id uri;
327         idref id (Ast.Ident (UriManager.name_of_uri uri, aux_substs substs))
328     | Cic.AMutInd (id,uri,i,substs) as t ->
329         let name = name_of_inductive_type uri i in
330         let uri_str = UriManager.string_of_uri uri in
331         let puri_str = sprintf "%s#xpointer(1/%d)" uri_str (i+1) in
332         register_uri id (UriManager.uri_of_string puri_str);
333         idref id (Ast.Ident (name, aux_substs substs))
334     | Cic.AMutConstruct (id,uri,i,j,substs) ->
335         let name = constructor_of_inductive_type uri i j in
336         let uri_str = UriManager.string_of_uri uri in
337         let puri_str = sprintf "%s#xpointer(1/%d/%d)" uri_str (i + 1) j in
338         register_uri id (UriManager.uri_of_string puri_str);
339         idref id (Ast.Ident (name, aux_substs substs))
340     | Cic.AMutCase (id,uri,typeno,ty,te,patterns) ->
341         let name = name_of_inductive_type uri typeno in
342         let uri_str = UriManager.string_of_uri uri in
343         let puri_str = sprintf "%s#xpointer(1/%d)" uri_str (typeno+1) in
344         let ctor_puri j =
345           UriManager.uri_of_string
346             (sprintf "%s#xpointer(1/%d/%d)" uri_str (typeno+1) j)
347         in
348         let case_indty = name, Some (UriManager.uri_of_string puri_str) in
349         let constructors = constructors_of_inductive_type uri typeno in
350         let rec eat_branch ty pat =
351           match (ty, pat) with
352           | Cic.Prod (_, _, t), Cic.ALambda (_, name, s, t') ->
353               let (cv, rhs) = eat_branch t t' in
354               (CicNotationUtil.name_of_cic_name name, Some (k s)) :: cv, rhs
355           | _, _ -> [], k pat
356         in
357         let j = ref 0 in
358         let patterns =
359           try
360             List.map2
361               (fun (name, ty) pat ->
362                 incr j;
363                 let (capture_variables, rhs) = eat_branch ty pat in
364                 ((name, Some (ctor_puri !j), capture_variables), rhs))
365               constructors patterns
366           with Invalid_argument _ -> assert false
367         in
368         idref id (Ast.Case (k te, Some case_indty, Some (k ty), patterns))
369     | Cic.AFix (id, no, funs) -> 
370         let defs = 
371           List.map
372             (fun (_, n, decr_idx, ty, bo) ->
373               ((Ast.Ident (n, None), Some (k ty)), k bo, decr_idx))
374             funs
375         in
376         let name =
377           try
378             (match List.nth defs no with
379             | (Ast.Ident (n, _), _), _, _ when n <> "_" -> n
380             | _ -> assert false)
381           with Not_found -> assert false
382         in
383         idref id (Ast.LetRec (`Inductive, defs, Ast.Ident (name, None)))
384     | Cic.ACoFix (id, no, funs) -> 
385         let defs = 
386           List.map
387             (fun (_, n, ty, bo) ->
388               ((Ast.Ident (n, None), Some (k ty)), k bo, 0))
389             funs
390         in
391         let name =
392           try
393             (match List.nth defs no with
394             | (Ast.Ident (n, _), _), _, _ when n <> "_" -> n
395             | _ -> assert false)
396           with Not_found -> assert false
397         in
398         idref id (Ast.LetRec (`CoInductive, defs, Ast.Ident (name, None)))
399   in
400   aux acic
401
402   (* persistent state *)
403
404 let level1_patterns21 = Hashtbl.create 211
405 let level2_patterns32 = Hashtbl.create 211
406 let interpretations = Hashtbl.create 211  (* symb -> id list ref *)
407
408 let compiled21 = ref None
409 let compiled32 = ref None
410
411 let pattern21_matrix = ref []
412 let pattern32_matrix = ref []
413
414 let get_compiled21 () =
415   match !compiled21 with
416   | None -> assert false
417   | Some f -> Lazy.force f
418 let get_compiled32 () =
419   match !compiled32 with
420   | None -> assert false
421   | Some f -> Lazy.force f
422
423 let set_compiled21 f = compiled21 := Some f
424 let set_compiled32 f = compiled32 := Some f
425
426 let add_idrefs =
427   List.fold_right (fun idref t -> Ast.AttributedTerm (`IdRef idref, t))
428
429 let instantiate21 idrefs env l1 =
430   let rec subst_singleton pos env =
431     function
432       Ast.AttributedTerm (attr, t) ->
433         Ast.AttributedTerm (attr, subst_singleton pos env t)
434     | t -> CicNotationUtil.group (subst pos env t)
435   and subst pos env = function
436     | Ast.AttributedTerm (attr, t) as term ->
437         prerr_endline ("loosing attribute " ^ CicNotationPp.pp_attribute attr);
438         subst pos env t
439     | Ast.Variable var ->
440         let name, expected_ty = CicNotationEnv.declaration_of_var var in
441         let ty, value =
442           try
443             List.assoc name env
444           with Not_found ->
445             prerr_endline ("name " ^ name ^ " not found in environment");
446             assert false
447         in
448         assert (CicNotationEnv.well_typed ty value); (* INVARIANT *)
449         (* following assertion should be a conditional that makes this
450          * instantiation fail *)
451         assert (CicNotationEnv.well_typed expected_ty value);
452         [ add_pos_info pos (CicNotationEnv.term_of_value value) ]
453     | Ast.Magic m -> subst_magic pos env m
454     | Ast.Literal l as t ->
455         let t = add_idrefs idrefs t in
456         (match l with
457         | `Keyword k -> [ add_keyword_attrs t ]
458         | _ -> [ t ])
459     | Ast.Layout l -> [ Ast.Layout (subst_layout pos env l) ]
460     | t -> [ CicNotationUtil.visit_ast (subst_singleton pos env) t ]
461   and subst_magic pos env = function
462     | Ast.List0 (p, sep_opt)
463     | Ast.List1 (p, sep_opt) ->
464         let rec_decls = CicNotationEnv.declarations_of_term p in
465         let rec_values =
466           List.map (fun (n, _) -> CicNotationEnv.lookup_list env n) rec_decls
467         in
468         let values = CicNotationUtil.ncombine rec_values in
469         let sep =
470           match sep_opt with
471             | None -> []
472             | Some l -> [ Ast.Literal l ]
473         in
474         let rec instantiate_list acc = function
475           | [] -> List.rev acc
476           | value_set :: [] ->
477               let env = CicNotationEnv.combine rec_decls value_set in
478               instantiate_list (CicNotationUtil.group (subst pos env p) :: acc)
479                 []
480           | value_set :: tl ->
481               let env = CicNotationEnv.combine rec_decls value_set in
482               let terms = subst pos env p in
483               instantiate_list (CicNotationUtil.group (terms @ sep) :: acc) tl
484         in
485         instantiate_list [] values
486     | Ast.Opt p ->
487         let opt_decls = CicNotationEnv.declarations_of_term p in
488         let env =
489           let rec build_env = function
490             | [] -> []
491             | (name, ty) :: tl ->
492                   (* assumption: if one of the value is None then all are *)
493                 (match CicNotationEnv.lookup_opt env name with
494                 | None -> raise Exit
495                 | Some v -> (name, (ty, v)) :: build_env tl)
496           in
497           try build_env opt_decls with Exit -> []
498         in
499           begin
500             match env with
501               | [] -> []
502               | _ -> subst pos env p
503           end
504     | _ -> assert false (* impossible *)
505   and subst_layout pos env = function
506     | Ast.Box (kind, tl) ->
507         let tl' = subst_children pos env tl in
508         Ast.Box (kind, List.concat tl')
509     | l -> CicNotationUtil.visit_layout (subst_singleton pos env) l
510   and subst_children pos env =
511     function
512     | [] -> []
513     | [ child ] ->
514         let pos' =
515           match pos with
516           | `Inner -> `Right
517           | `Left -> `Left
518           | `None -> assert false
519           | `Right -> `Right
520         in
521         [ subst pos' env child ]
522     | hd :: tl ->
523         let pos' =
524           match pos with
525           | `Inner -> `Inner
526           | `Left -> `Inner
527           | `None -> assert false
528           | `Right -> `Right
529         in
530         (subst pos env hd) :: subst_children pos' env tl
531   in
532     subst_singleton `Left env l1
533
534 let rec pp_ast1 term = 
535   let rec pp_value = function
536     | CicNotationEnv.NumValue _ as v -> v
537     | CicNotationEnv.StringValue _ as v -> v
538 (*     | CicNotationEnv.TermValue t when t == term -> CicNotationEnv.TermValue (pp_ast0 t pp_ast1) *)
539     | CicNotationEnv.TermValue t -> CicNotationEnv.TermValue (pp_ast1 t)
540     | CicNotationEnv.OptValue None as v -> v
541     | CicNotationEnv.OptValue (Some v) -> 
542         CicNotationEnv.OptValue (Some (pp_value v))
543     | CicNotationEnv.ListValue vl ->
544         CicNotationEnv.ListValue (List.map pp_value vl)
545   in
546   let ast_env_of_env env =
547     List.map (fun (var, (ty, value)) -> (var, (ty, pp_value value))) env
548   in
549 (* prerr_endline ("pattern matching from 2 to 1 on term " ^ CicNotationPp.pp_term term); *)
550   match term with
551   | Ast.AttributedTerm (attrs, term') ->
552       Ast.AttributedTerm (attrs, pp_ast1 term')
553   | _ ->
554       (match (get_compiled21 ()) term with
555       | None -> pp_ast0 term pp_ast1
556       | Some (env, ctors, pid) ->
557           let idrefs =
558             List.flatten (List.map CicNotationUtil.get_idrefs ctors)
559           in
560           let prec, assoc, l1 =
561             try
562               Hashtbl.find level1_patterns21 pid
563             with Not_found -> assert false
564           in
565           add_level_info prec assoc
566             (instantiate21 idrefs (ast_env_of_env env) l1))
567
568 let instantiate32 term_info idrefs env symbol args =
569   let rec instantiate_arg = function
570     | Ast.IdentArg (n, name) ->
571         let t = (try List.assoc name env with Not_found -> assert false) in
572         let rec count_lambda = function
573           | Ast.AttributedTerm (_, t) -> count_lambda t
574           | Ast.Binder (`Lambda, _, body) -> 1 + count_lambda body
575           | _ -> 0
576         in
577         let rec add_lambda t n =
578           if n > 0 then
579             let name = CicNotationUtil.fresh_name () in
580             Ast.Binder (`Lambda, (Ast.Ident (name, None), None),
581               Ast.Appl [add_lambda t (n - 1); Ast.Ident (name, None)])
582           else
583             t
584         in
585         add_lambda t (n - count_lambda t)
586   in
587   let head =
588     let symbol = Ast.Symbol (symbol, 0) in
589     add_idrefs idrefs symbol
590   in
591   if args = [] then head
592   else Ast.Appl (head :: List.map instantiate_arg args)
593
594 let rec ast_of_acic1 term_info annterm = 
595   let id_to_uris = term_info.uri in
596   let register_uri id uri = Hashtbl.add id_to_uris id uri in
597   match (get_compiled32 ()) annterm with
598   | None -> ast_of_acic0 term_info annterm ast_of_acic1
599   | Some (env, ctors, pid) -> 
600       let idrefs =
601         List.map
602           (fun annterm ->
603             let idref = CicUtil.id_of_annterm annterm in
604             (try
605               register_uri idref
606                 (CicUtil.uri_of_term (Deannotate.deannotate_term annterm))
607             with Invalid_argument _ -> ());
608             idref)
609           ctors
610       in
611       let env' =
612         List.map (fun (name, term) -> (name, ast_of_acic1 term_info term)) env
613       in
614       let _, symbol, args, _ =
615         try
616           Hashtbl.find level2_patterns32 pid
617         with Not_found -> assert false
618       in
619       let ast = instantiate32 term_info idrefs env' symbol args in
620       Ast.AttributedTerm (`IdRef (CicUtil.id_of_annterm annterm), ast)
621
622 let load_patterns32 t =
623   set_compiled32 (lazy (CicNotationMatcher.Matcher32.compiler t))
624
625 let load_patterns21 t =
626   set_compiled21 (lazy (CicNotationMatcher.Matcher21.compiler t))
627
628 let ast_of_acic id_to_sort annterm =
629   debug_print (lazy ("ast_of_acic <- "
630     ^ CicPp.ppterm (Deannotate.deannotate_term annterm)));
631   let term_info = { sort = id_to_sort; uri = Hashtbl.create 211 } in
632   let ast = ast_of_acic1 term_info annterm in
633   debug_print (lazy ("ast_of_acic -> " ^ CicNotationPp.pp_term ast));
634   ast, term_info.uri
635
636 let pp_ast ast =
637   debug_print (lazy "pp_ast <-");
638   let ast' = pp_ast1 ast in
639   debug_print (lazy ("pp_ast -> " ^ CicNotationPp.pp_term ast'));
640   ast'
641
642 let fresh_id =
643   let counter = ref ~-1 in
644   fun () ->
645     incr counter;
646     !counter
647
648 let add_interpretation dsc (symbol, args) appl_pattern =
649   let id = fresh_id () in
650   Hashtbl.add level2_patterns32 id (dsc, symbol, args, appl_pattern);
651   pattern32_matrix := (appl_pattern, id) :: !pattern32_matrix;
652   load_patterns32 !pattern32_matrix;
653   (try
654     let ids = Hashtbl.find interpretations symbol in
655     ids := id :: !ids
656   with Not_found -> Hashtbl.add interpretations symbol (ref [id]));
657   id
658
659 exception Interpretation_not_found
660 exception Pretty_printer_not_found
661
662 let rec list_uniq = function 
663   | [] -> []
664   | h::[] -> [h]
665   | h1::h2::tl when h1 = h2 -> list_uniq (h2 :: tl) 
666   | h1::tl (* when h1 <> h2 *) -> h1 :: list_uniq tl
667
668 let lookup_interpretations symbol =
669   try
670    list_uniq
671     (List.sort Pervasives.compare
672      (List.map
673       (fun id ->
674         let (dsc, _, args, appl_pattern) =
675           try
676             Hashtbl.find level2_patterns32 id
677           with Not_found -> assert false 
678         in
679         dsc, args, appl_pattern)
680       !(Hashtbl.find interpretations symbol)))
681   with Not_found -> raise Interpretation_not_found
682
683 let add_pretty_printer ~precedence ~associativity l2 l1 =
684   let id = fresh_id () in
685   let l2' = CicNotationUtil.strip_attributes l2 in
686   Hashtbl.add level1_patterns21 id (precedence, associativity, l1);
687   pattern21_matrix := (l2', id) :: !pattern21_matrix;
688   load_patterns21 !pattern21_matrix;
689   id
690
691 let remove_interpretation id =
692   (try
693     let _, symbol, _, _ = Hashtbl.find level2_patterns32 id in
694     let ids = Hashtbl.find interpretations symbol in
695     ids := List.filter ((<>) id) !ids;
696     Hashtbl.remove level2_patterns32 id;
697   with Not_found -> raise Interpretation_not_found);
698   pattern32_matrix := List.filter (fun (_, id') -> id <> id') !pattern32_matrix;
699   load_patterns32 !pattern32_matrix
700
701 let remove_pretty_printer id =
702   (try
703     Hashtbl.remove level1_patterns21 id;
704   with Not_found -> raise Pretty_printer_not_found);
705   pattern21_matrix := List.filter (fun (_, id') -> id <> id') !pattern21_matrix;
706   load_patterns21 !pattern21_matrix
707
708 let _ =
709   load_patterns21 [];
710   load_patterns32 []
711