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