]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/cic_notation/cicNotationRew.ml
snapshot (added typed environment in 2 -> 1 conversion)
[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 type term_info =
33   { sort: (Cic.id, CicNotationPt.sort_kind) Hashtbl.t;
34     uri: (Cic.id, string) Hashtbl.t;
35   }
36
37 exception No_match
38
39 module OrderedInt =
40   struct
41   type t = int
42   let compare (x1:t) (x2:t) = Pervasives.compare x2 x1  (* reverse order *)
43   end
44
45 module IntSet = Set.Make (OrderedInt)
46
47 let int_set_of_int_list l =
48   List.fold_left (fun acc i -> IntSet.add i acc) IntSet.empty l
49
50 let warning s = prerr_endline ("CicNotation WARNING: " ^ s)
51
52 module type PATTERN =
53   sig
54   type pattern_t
55   val compatible : pattern_t -> pattern_t -> bool
56   end
57
58 module Patterns (P: PATTERN) =
59   struct
60   type row_t = P.pattern_t list * pattern_id
61   type t = row_t list
62
63   let empty = []
64
65   let first_column t = List.map (fun (patterns, _) -> List.hd patterns) t
66   let pattern_ids t = List.map snd t
67
68   let partition t pidl =
69     let partitions = Hashtbl.create 11 in
70     let add pid row = Hashtbl.add partitions pid row in
71     (try
72       List.iter2 add pidl t
73     with Invalid_argument _ -> assert false);
74     let pidset = int_set_of_int_list pidl in
75     IntSet.fold
76       (fun pid acc ->
77         match Hashtbl.find_all partitions pid with
78         | [] -> acc
79         | patterns -> (pid, List.rev patterns) :: acc)
80       pidset []
81
82   let are_empty t = fst (List.hd t) = []
83     (* if first row has an empty list of patterns, then others will as well *)
84
85     (* return 2 lists of rows, first one containing homogeneous rows according
86      * to "compatible" below *)
87   let horizontal_split t =
88     let ap, first_row, t' =
89       match t with
90       | [] -> assert false
91       | ([], _) :: _ ->
92           assert false  (* are_empty should have been invoked in advance *)
93       | ((hd :: _ , _) as row) :: tl -> hd, row, tl
94     in
95     let rec aux prev_t = function
96       | [] -> List.rev prev_t, []
97       | ([], _) :: _ -> assert false
98       | (((hd :: _), _) as row) :: tl when P.compatible ap hd ->
99           aux (row :: prev_t) tl
100       | t -> List.rev prev_t, t
101     in
102     aux [first_row] t'
103
104     (* return 2 lists, first one representing first column, second one
105      * representing rows stripped of the first element *)
106   let vertical_split t =
107     let l =
108       List.map
109         (function
110           | (hd :: tl, pid) -> hd, (tl, pid)
111           | _ -> assert false)
112         t
113     in
114     List.split l
115   end
116
117 module Patterns21 = Patterns (CicNotationTag)
118
119 module Patterns32 =
120   struct
121   type row_t = CicNotationPt.cic_appl_pattern list * pattern_id
122   type t = row_t list
123
124   let empty = []
125
126   let first_column t = List.map (fun (patterns, _) -> List.hd patterns) t
127   let pattern_ids t = List.map snd t
128
129   let partition t pidl =
130     let partitions = Hashtbl.create 11 in
131     let add pid row = Hashtbl.add partitions pid row in
132     (try
133       List.iter2 add pidl t
134     with Invalid_argument _ -> assert false);
135     let pidset = int_set_of_int_list pidl in
136     IntSet.fold
137       (fun pid acc ->
138         match Hashtbl.find_all partitions pid with
139         | [] -> acc
140         | patterns -> (pid, List.rev patterns) :: acc)
141       pidset []
142
143   let are_empty t = fst (List.hd t) = []
144     (* if first row has an empty list of patterns, then others will as well *)
145
146     (* return 2 lists of rows, first one containing homogeneous rows according
147      * to "compatible" below *)
148   let horizontal_split t =
149     let compatible ap1 ap2 =
150       match ap1, ap2 with
151       | CicNotationPt.UriPattern _, CicNotationPt.UriPattern _
152       | CicNotationPt.ArgPattern _, CicNotationPt.ArgPattern _
153       | CicNotationPt.ApplPattern _, CicNotationPt.ApplPattern _ -> true
154       | _ -> false
155     in
156     let ap =
157       match t with
158       | [] -> assert false
159       | ([], _) :: _ ->
160           assert false  (* are_empty should have been invoked in advance *)
161       | (hd :: _ , _) :: _ -> hd
162     in
163     let rec aux prev_t = function
164       | [] -> List.rev prev_t, []
165       | ([], _) :: _ -> assert false
166       | (((hd :: _), _) as row) :: tl when compatible ap hd ->
167           aux (row :: prev_t) tl
168       | t -> List.rev prev_t, t
169     in
170     aux [] t
171
172     (* return 2 lists, first one representing first column, second one
173      * representing rows stripped of the first element *)
174   let vertical_split t =
175     let l =
176       List.map
177         (function
178           | (hd :: tl, pid) -> hd, (tl, pid)
179           | _ -> assert false)
180         t
181     in
182     List.split l
183   end
184
185   (* acic -> ast auxiliary function s *)
186
187 let get_types uri =
188   let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
189     match o with
190       | Cic.InductiveDefinition (l,_,_,_) -> l 
191       | _ -> assert false
192
193 let name_of_inductive_type uri i = 
194   let types = get_types uri in
195   let (name, _, _, _) = try List.nth types i with Not_found -> assert false in
196   name
197
198   (* returns <name, type> pairs *)
199 let constructors_of_inductive_type uri i =
200   let types = get_types uri in
201   let (_, _, _, constructors) = 
202     try List.nth types i with Not_found -> assert false
203   in
204   constructors
205
206   (* returns name only *)
207 let constructor_of_inductive_type uri i j =
208   (try
209     fst (List.nth (constructors_of_inductive_type uri i) (j-1))
210   with Not_found -> assert false)
211
212 module Ast = CicNotationPt
213
214 let string_of_name = function
215   | Cic.Name s -> s
216   | Cic.Anonymous -> "_"
217
218 let ident_of_name n = Ast.Ident (string_of_name n, None)
219
220 let idref id t = Ast.AttributedTerm (`IdRef id, t)
221
222 let pp_ast0 t k =
223   prerr_endline "pp_ast0";
224   let rec aux t = CicNotationUtil.visit_ast ~special_k k t
225   and special_k = function
226     | Ast.AttributedTerm (attrs, t) -> Ast.AttributedTerm (attrs, aux t)
227     | _ -> assert false
228   in
229   aux t
230
231 let ast_of_acic0 term_info acic k =
232 (*   prerr_endline "ast_of_acic0"; *)
233   let k = k term_info in
234   let register_uri id uri = Hashtbl.add term_info.uri id uri in
235   let sort_of_id id =
236     try
237       Hashtbl.find term_info.sort id
238     with Not_found -> assert false
239   in
240   let aux_substs substs =
241     Some
242       (List.map
243         (fun (uri, annterm) -> (UriManager.name_of_uri uri, k annterm))
244         substs)
245   in
246   let aux_context context =
247     List.map
248       (function
249         | None -> None
250         | Some annterm -> Some (k annterm))
251       context
252   in
253   let aux = function
254     | Cic.ARel (id,_,_,b) -> idref id (Ast.Ident (b, None))
255     | Cic.AVar (id,uri,substs) ->
256         register_uri id (UriManager.string_of_uri uri);
257         idref id (Ast.Ident (UriManager.name_of_uri uri, aux_substs substs))
258     | Cic.AMeta (id,n,l) -> idref id (Ast.Meta (n, aux_context l))
259     | Cic.ASort (id,Cic.Prop) -> idref id (Ast.Sort `Prop)
260     | Cic.ASort (id,Cic.Set) -> idref id (Ast.Sort `Set)
261     | Cic.ASort (id,Cic.Type _) -> idref id (Ast.Sort `Type)
262     | Cic.ASort (id,Cic.CProp) -> idref id (Ast.Sort `CProp)
263     | Cic.AImplicit _ -> assert false
264     | Cic.AProd (id,n,s,t) ->
265         let binder_kind =
266           match sort_of_id id with
267           | `Set | `Type -> `Pi
268           | `Prop | `CProp -> `Forall
269         in
270         idref id (Ast.Binder (binder_kind, (ident_of_name n, Some (k s)), k t))
271     | Cic.ACast (id,v,t) ->
272         idref id (Ast.Appl [idref id (Ast.Symbol ("cast", 0)); k v; k t])
273     | Cic.ALambda (id,n,s,t) ->
274         idref id (Ast.Binder (`Lambda, (ident_of_name n, Some (k s)), k t))
275     | Cic.ALetIn (id,n,s,t) ->
276         idref id (Ast.LetIn ((ident_of_name n, None), k s, k t))
277     | Cic.AAppl (aid,args) -> idref aid (Ast.Appl (List.map k args))
278     | Cic.AConst (id,uri,substs) ->
279         register_uri id (UriManager.string_of_uri uri);
280         idref id (Ast.Ident (UriManager.name_of_uri uri, aux_substs substs))
281     | Cic.AMutInd (id,uri,i,substs) as t ->
282         let name = name_of_inductive_type uri i in
283         let uri_str = UriManager.string_of_uri uri in
284         let puri_str =
285           uri_str ^ "#xpointer(1/" ^ (string_of_int (i + 1)) ^ ")"
286         in
287         register_uri id puri_str;
288         idref id (Ast.Ident (name, aux_substs substs))
289     | Cic.AMutConstruct (id,uri,i,j,substs) ->
290         let name = constructor_of_inductive_type uri i j in
291         let uri_str = UriManager.string_of_uri uri in
292         let puri_str = sprintf "%s#xpointer(1/%d/%d)" uri_str (i + 1) j in
293         register_uri id puri_str;
294         idref id (Ast.Ident (name, aux_substs substs))
295     | Cic.AMutCase (id,uri,typeno,ty,te,patterns) ->
296         let name = name_of_inductive_type uri typeno in
297         let constructors = constructors_of_inductive_type uri typeno in
298         let rec eat_branch ty pat =
299           match (ty, pat) with
300           | Cic.Prod (_, _, t), Cic.ALambda (_, name, s, t') ->
301               let (cv, rhs) = eat_branch t t' in
302               (ident_of_name name, Some (k s)) :: cv, rhs
303           | _, _ -> [], k pat
304         in
305         let patterns =
306           List.map2
307             (fun (name, ty) pat ->
308               let (capture_variables, rhs) = eat_branch ty pat in
309               ((name, capture_variables), rhs))
310             constructors patterns
311         in
312         idref id (Ast.Case (k te, Some name, Some (k ty), patterns))
313     | Cic.AFix (id, no, funs) -> 
314         let defs = 
315           List.map
316             (fun (_, n, decr_idx, ty, bo) ->
317               ((Ast.Ident (n, None), Some (k ty)), k bo, decr_idx))
318             funs
319         in
320         let name =
321           try
322             (match List.nth defs no with
323             | (Ast.Ident (n, _), _), _, _ when n <> "_" -> n
324             | _ -> assert false)
325           with Not_found -> assert false
326         in
327         idref id (Ast.LetRec (`Inductive, defs, Ast.Ident (name, None)))
328     | Cic.ACoFix (id, no, funs) -> 
329         let defs = 
330           List.map
331             (fun (_, n, ty, bo) -> ((Ast.Ident (n, None), Some (k ty)), k bo, 0))
332             funs
333         in
334         let name =
335           try
336             (match List.nth defs no with
337             | (Ast.Ident (n, _), _), _, _ when n <> "_" -> n
338             | _ -> assert false)
339           with Not_found -> assert false
340         in
341         idref id (Ast.LetRec (`CoInductive, defs, Ast.Ident (name, None)))
342   in
343   aux acic
344
345   (* persistent state *)
346
347 let level1_patterns21 = Hashtbl.create 211
348 let level2_patterns32 = Hashtbl.create 211
349
350 let (compiled21: (CicNotationPt.term -> CicNotationPt.term) option ref) =
351   ref None
352 let (compiled32: (term_info -> Cic.annterm -> CicNotationPt.term) option ref) =
353   ref None
354
355 let pattern21_matrix = ref Patterns21.empty
356 let pattern32_matrix = ref Patterns32.empty
357
358 let get_compiled21 () =
359   match !compiled21 with
360   | None -> assert false
361   | Some f -> f
362 let get_compiled32 () =
363   match !compiled32 with
364   | None -> assert false
365   | Some f -> f
366
367 let set_compiled21 f = compiled21 := Some f
368 let set_compiled32 f = compiled32 := Some f
369
370   (* "envl" is a list of triples:
371    *   <name environment, term environment, pattern id>, where
372    *   name environment: (string * string) list
373    *   term environment: (string * Cic.annterm) list *)
374 let return_closure success_k =
375   (fun term_info terms envl ->
376 (*     prerr_endline "return_closure"; *)
377     match terms with
378     | [] ->
379         (try
380           success_k term_info (List.hd envl)
381         with Failure _ -> assert false)
382     | _ -> assert false)
383
384 let variable_closure names k =
385   (fun term_info terms envl ->
386 (*     prerr_endline "variable_closure"; *)
387     match terms with
388     | hd :: tl ->
389         let envl' =
390           List.map2
391             (fun arg (name_env, term_env, pid) ->
392               let rec aux name_env term_env pid arg term =
393                 match arg, term with
394                   Ast.IdentArg name, _ ->
395                     (name_env, (name, term) :: term_env, pid)
396                 | Ast.EtaArg (Some name, arg'),
397                   Cic.ALambda (id, name', ty, body) ->
398                     aux
399                       ((name, (string_of_name name', Some (ty, id))) :: name_env)
400                       term_env pid arg' body
401                 | Ast.EtaArg (Some name, arg'), _ ->
402                     let name' = CicNotationUtil.fresh_name () in
403                     aux ((name, (name', None)) :: name_env)
404                       term_env pid arg' term
405                 | Ast.EtaArg (None, arg'), Cic.ALambda (id, name, ty, body) ->
406                     assert false
407                 | Ast.EtaArg (None, arg'), _ ->
408                     assert false
409               in
410                 aux name_env term_env pid arg hd)
411             names envl
412         in
413         k term_info tl envl'
414     | _ -> assert false)
415
416 let appl_closure ks k =
417   (fun term_info terms envl ->
418 (*     prerr_endline "appl_closure"; *)
419     (match terms with
420     | Cic.AAppl (_, args) :: tl ->
421         (try
422           let k' = List.assoc (List.length args) ks in
423           k' term_info (args @ tl) envl
424         with Not_found -> k term_info terms envl)
425     | [] -> assert false
426     | _ -> k term_info terms envl))
427
428 let uri_of_term t = CicUtil.uri_of_term (Deannotate.deannotate_term t)
429
430 let uri_closure ks k =
431   (fun term_info terms envl ->
432 (*     prerr_endline "uri_closure"; *)
433     (match terms with
434     | [] -> assert false
435     | hd :: tl ->
436 (*         prerr_endline (sprintf "uri_of_term = %s" (uri_of_term hd)); *)
437         begin
438           try
439             let k' = List.assoc (uri_of_term hd) ks in
440             k' term_info tl envl
441           with
442           | Invalid_argument _  (* raised by uri_of_term *)
443           | Not_found -> k term_info terms envl
444         end))
445
446   (* compiler from level 3 to level 2 *)
447 let compiler32 (t: Patterns32.t) success_k fail_k =
448   let rec aux t k = (* k is a continuation *)
449     if t = [] then
450       k
451     else if Patterns32.are_empty t then begin
452       (match t with
453       | _::_::_ ->
454           (* XXX optimization possible here: throw away all except one of the
455            * rules which lead to ambiguity *)
456           warning "ambiguous interpretation"
457       | _ -> ());
458       return_closure success_k
459     end else
460       match Patterns32.horizontal_split t with
461       | t', [] ->
462           (match t' with
463           | []
464           | ([], _) :: _ -> assert false
465           | (Ast.ArgPattern (Ast.IdentArg _) :: _, _) :: _
466           | (Ast.ArgPattern (Ast.EtaArg _) :: _, _) :: _ ->
467               let first_column, t'' = Patterns32.vertical_split t' in
468               let names =
469                 List.map
470                   (function
471                     | Ast.ArgPattern arg -> arg
472                     | _ -> assert false)
473                   first_column
474               in
475               variable_closure names (aux t'' k)
476           | (Ast.ApplPattern _ :: _, _) :: _ ->
477               let pidl =
478                 List.map
479                   (function
480                     | (Ast.ApplPattern args) :: _, _ -> List.length args
481                     | _ -> assert false)
482                   t'
483               in
484                 (* arity partitioning *)
485               let clusters = Patterns32.partition t' pidl in
486               let ks =  (* k continuation list *)
487                 List.map
488                   (fun (len, cluster) ->
489                     let cluster' =
490                       List.map  (* add args as patterns heads *)
491                         (function
492                           | (Ast.ApplPattern args) :: tl, pid ->
493                               (* let's throw away "teste di cluster" *)
494                               args @ tl, pid
495                           | _ -> assert false)
496                         cluster
497                     in
498                     len, aux cluster' k)
499                   clusters
500               in
501               appl_closure ks k
502           | (Ast.UriPattern _ :: _, _) :: _ ->
503               let uidmap, pidl =
504                 let urimap = ref [] in
505                 let uidmap = ref [] in
506                 let get_uri_id uri =
507                   try
508                     List.assoc uri !urimap
509                   with
510                     Not_found ->
511                       let uid = List.length !urimap in
512                       urimap := (uri, uid) :: !urimap ;
513                       uidmap := (uid, uri) :: !uidmap ;
514                       uid
515                 in
516                 let uidl =
517                   List.map
518                     (function
519                       | (Ast.UriPattern uri) :: _, _ -> get_uri_id uri
520                       | _ -> assert false)
521                     t'
522                 in
523                   !uidmap, uidl
524               in
525               let clusters = Patterns32.partition t' pidl in
526               let ks =
527                 List.map
528                   (fun (uid, cluster) ->
529                     let cluster' =
530                       List.map
531                         (function
532                         | (Ast.UriPattern uri) :: tl, pid -> tl, pid
533                         | _ -> assert false)
534                       cluster
535                     in
536                     List.assoc uid uidmap, aux cluster' k)
537                   clusters
538               in
539               uri_closure ks k)
540       | t', tl -> aux t' (aux tl k)
541   in
542   let matcher = aux t (fun _ _ -> raise No_match) in
543   (fun term_info annterm ->
544     try
545       matcher term_info [annterm] (List.map (fun (_, pid) -> [], [], pid) t)
546     with No_match -> fail_k term_info annterm)
547
548 let return_closure21 success_k =
549   (fun terms envl ->
550     prerr_endline "return_closure21";
551     match terms with
552     | [] ->
553         (try
554           success_k (List.hd envl)
555         with Failure _ -> assert false)
556     | _ -> assert false)
557
558 let variable_closure21 vars k =
559   (fun terms envl ->
560     prerr_endline "variable_closure21";
561     match terms with
562     | hd :: tl ->
563         let envl' =
564           List.map2
565             (fun (name, ty) (env, pid) ->
566               (name, (ty, CicNotationEnv.value_of_term hd)) :: env, pid)
567             vars envl
568         in
569         k tl envl'
570     | _ -> assert false)
571
572 let constructor_closure21 ks k =
573   (fun terms envl ->
574     prerr_endline "constructor_closure21";
575     (match terms with
576     | p :: tl ->
577         prerr_endline (sprintf "on term %s" (CicNotationPp.pp_term p));
578         (try
579           let tag, subterms = CicNotationTag.get_tag p in
580           let k' = List.assoc tag ks in
581           k' (subterms @ tl) envl
582         with Not_found -> k terms envl)
583     | [] -> assert false))
584
585 let compiler21 (t: Patterns21.t) success_k fail_k =
586   let rec aux t k =
587     if t = [] then
588       k
589     else if Patterns21.are_empty t then begin
590       (match t with
591       | _::_::_ ->
592           (* XXX optimization possible here: throw away all except one of the
593            * rules which lead to ambiguity *)
594           warning "ambiguous notation"
595       | _ -> ());
596       return_closure21 success_k
597     end else
598       match Patterns21.horizontal_split t with
599       | t', [] ->
600           (match t' with
601           | []
602           | ([], _) :: _ -> assert false
603           | (Ast.Variable _ :: _, _) :: _ ->
604               let first_column, t'' = Patterns21.vertical_split t' in
605               let vars =
606                 List.map
607                   (function
608                     | Ast.Variable v -> CicNotationEnv.declaration_of_var v
609                     | _ -> assert false)
610                   first_column
611               in
612               variable_closure21 vars (aux t'' k)
613           | _ ->
614               let pidl =
615                 List.map
616                   (function
617                     | p :: _, _ -> fst (CicNotationTag.get_tag p)
618                     | [], _ -> assert false)
619                   t'
620               in
621               let clusters = Patterns21.partition t' pidl in
622               let ks =
623                 List.map
624                   (fun (pid, cluster) ->
625                     let cluster' =
626                       List.map  (* add args as patterns heads *)
627                         (function
628                           | p :: tl, pid ->
629                               let _, subpatterns = CicNotationTag.get_tag p in
630                               subpatterns @ tl, pid
631                           | _ -> assert false)
632                         cluster
633                     in
634                     pid, aux cluster' k)
635                   clusters
636               in
637               constructor_closure21 ks k)
638       | t', tl -> aux t' (aux tl k)
639   in
640   let matcher = aux t (fun _ _ -> raise No_match) in
641   (fun ast ->
642     try
643       matcher [ast] (List.map (fun (_, pid) -> [], pid) t)
644     with No_match -> fail_k ast)
645
646 let ast_of_acic1 term_info annterm = (get_compiled32 ()) term_info annterm
647
648 let pp_ast1 term = (get_compiled21 ()) term
649
650 let instantiate21 env pid =
651   prerr_endline "instantiate21";
652   let precedence, associativity, l1 =
653     try
654       Hashtbl.find level1_patterns21 pid
655     with Not_found -> assert false
656   in
657   let rec subst = function
658     | Ast.AttributedTerm (_, t) -> subst t
659     | Ast.Variable var ->
660         let name, expected_ty = CicNotationEnv.declaration_of_var var in
661         let ty, value =
662           try
663             List.assoc name env
664           with Not_found -> assert false
665         in
666         assert (CicNotationEnv.well_typed ty value); (* INVARIANT *)
667         (* following assertion should be a conditional that makes this
668          * instantiation fail *)
669         assert (CicNotationEnv.well_typed expected_ty value);
670         CicNotationEnv.term_of_value value
671     | Ast.Magic _ -> assert false (* TO BE IMPLEMENTED *)
672     | Ast.Literal _ as t -> t
673     | Ast.Layout l -> Ast.Layout (subst_layout l)
674     | t -> CicNotationUtil.visit_ast subst t
675   and subst_layout l = CicNotationUtil.visit_layout subst l in
676   subst l1
677
678 let instantiate32 term_info name_env term_env pid =
679   let symbol, args =
680     try
681       Hashtbl.find level2_patterns32 pid
682     with Not_found -> assert false
683   in
684   let rec instantiate_arg = function
685     | Ast.IdentArg name ->
686         (try List.assoc name term_env with Not_found -> assert false)
687     | Ast.EtaArg (None, _) -> assert false  (* TODO *)
688     | Ast.EtaArg (Some name, arg) ->
689         let (name', ty_opt) =
690           try List.assoc name name_env with Not_found -> assert false
691         in
692         let body = instantiate_arg arg in
693         let name' = Ast.Ident (name', None) in
694         match ty_opt with
695         | None -> Ast.Binder (`Lambda, (name', None), body)
696         | Some (ty, id) ->
697             idref id (Ast.Binder (`Lambda, (name', Some ty), body))
698   in
699   let args' = List.map instantiate_arg args in
700   Ast.Appl (Ast.Symbol (symbol, 0) :: args')
701
702 let load_patterns32 t =
703   let ast_env_of_name_env term_info name_env =
704     List.map
705       (fun (name, (name', ty_opt)) ->
706         let ast_ty_opt =
707           match ty_opt with
708           | None -> None
709           | Some (annterm, id) -> Some (ast_of_acic1 term_info annterm, id)
710         in
711         (name, (name', ast_ty_opt)))
712       name_env
713   in
714   let ast_env_of_term_env term_info =
715     List.map (fun (name, term) -> (name, ast_of_acic1 term_info term))
716   in
717   let fail_k term_info annterm = ast_of_acic0 term_info annterm ast_of_acic1 in
718   let success_k term_info (name_env, term_env, pid) =
719     instantiate32
720       term_info
721       (ast_env_of_name_env term_info name_env)
722       (ast_env_of_term_env term_info term_env)
723       pid
724   in
725   let compiled32 = compiler32 t success_k fail_k in
726   set_compiled32 compiled32
727
728 let load_patterns21 t =
729   let rec pp_value = function
730     | CicNotationEnv.NumValue _ as v -> v
731     | CicNotationEnv.StringValue _ as v -> v
732     | CicNotationEnv.TermValue t -> CicNotationEnv.TermValue (pp_ast1 t)
733     | CicNotationEnv.OptValue None as v -> v
734     | CicNotationEnv.OptValue (Some v) -> 
735         CicNotationEnv.OptValue (Some (pp_value v))
736     | CicNotationEnv.ListValue vl ->
737         CicNotationEnv.ListValue (List.map pp_value vl)
738   in
739   let ast_env_of_env env =
740     List.map (fun (var, (ty, value)) -> (var, (ty, pp_value value))) env
741   in
742   let fail_k term = pp_ast0 term pp_ast1 in
743   let success_k (env, pid) = instantiate21 (ast_env_of_env env) pid in
744   let compiled21 = compiler21 t success_k fail_k in
745   set_compiled21 compiled21
746
747 let ast_of_acic id_to_sort annterm =
748   let term_info = { sort = id_to_sort; uri = Hashtbl.create 211 } in
749   let ast = ast_of_acic1 term_info annterm in
750   ast, term_info.uri
751
752 let pp_ast term = pp_ast1 term
753
754 let fresh_id =
755   let counter = ref ~-1 in
756   fun () ->
757     incr counter;
758     !counter
759
760 let add_interpretation (symbol, args) appl_pattern =
761   let id = fresh_id () in
762   Hashtbl.add level2_patterns32 id (symbol, args);
763   pattern32_matrix := ([appl_pattern], id) :: !pattern32_matrix;
764   load_patterns32 !pattern32_matrix;
765   id
766
767 let add_pretty_printer ?precedence ?associativity l2 l1 =
768   let id = fresh_id () in
769   let l2' = CicNotationUtil.strip_attributes l2 in
770   Hashtbl.add level1_patterns21 id (precedence, associativity, l1);
771   pattern21_matrix := ([l2'], id) :: !pattern21_matrix;
772   load_patterns21 !pattern21_matrix;
773   id
774
775 exception Interpretation_not_found
776 exception Pretty_printer_not_found
777
778 let remove_interpretation id =
779   (try
780     Hashtbl.remove level2_patterns32 id;
781   with Not_found -> raise Interpretation_not_found);
782   pattern32_matrix := List.filter (fun (_, id') -> id <> id') !pattern32_matrix;
783   load_patterns32 !pattern32_matrix
784
785 let remove_pretty_printer id =
786   (try
787     Hashtbl.remove level1_patterns21 id;
788   with Not_found -> raise Pretty_printer_not_found);
789   pattern21_matrix := List.filter (fun (_, id') -> id <> id') !pattern21_matrix;
790   load_patterns21 !pattern21_matrix
791
792 let _ =
793   load_patterns21 [];
794   load_patterns32 []
795