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