]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/content_pres/termContentPres.ml
Preparing for 0.5.9 release.
[helm.git] / helm / software / components / content_pres / termContentPres.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 (* $Id$ *)
27
28 open Printf
29
30 module Ast = CicNotationPt
31 module Env = CicNotationEnv
32
33 let debug = false
34 let debug_print s = if debug then prerr_endline (Lazy.force s) else ()
35
36 type pattern_id = int
37 type pretty_printer_id = pattern_id
38
39 let resolve_binder = function
40   | `Lambda -> "\\lambda"
41   | `Pi -> "\\Pi"
42   | `Forall -> "\\forall"
43   | `Exists -> "\\exists"
44
45 let add_level_info prec t = Ast.AttributedTerm (`Level prec, t)
46
47 let rec top_pos t = add_level_info ~-1 t
48
49 let rec remove_level_info =
50   function
51   | Ast.AttributedTerm (`Level _, t) -> remove_level_info t
52   | Ast.AttributedTerm (a, t) -> Ast.AttributedTerm (a, remove_level_info t)
53   | t -> t
54
55 let add_xml_attrs attrs t =
56   if attrs = [] then t else Ast.AttributedTerm (`XmlAttrs attrs, t)
57
58 let add_keyword_attrs =
59   add_xml_attrs (RenderingAttrs.keyword_attributes `MathML)
60
61 let box kind spacing indent content =
62   Ast.Layout (Ast.Box ((kind, spacing, indent), content))
63
64 let hbox = box Ast.H
65 let vbox = box Ast.V
66 let hvbox = box Ast.HV
67 let hovbox = box Ast.HOV
68 let break = Ast.Layout Ast.Break
69 let space = Ast.Literal (`Symbol " ")
70 let builtin_symbol s = Ast.Literal (`Symbol s)
71 let keyword k = add_keyword_attrs (Ast.Literal (`Keyword k))
72
73 let number s =
74   add_xml_attrs (RenderingAttrs.number_attributes `MathML)
75     (Ast.Literal (`Number s))
76
77 let ident i =
78   add_xml_attrs (RenderingAttrs.ident_attributes `MathML) (Ast.Ident (i, None))
79
80 let ident_w_href href i =
81   match href with
82   | None -> ident i
83   | Some href ->
84       let href = UriManager.string_of_uri href in
85       add_xml_attrs [Some "xlink", "href", href] (ident i)
86
87 let binder_symbol s =
88   add_xml_attrs (RenderingAttrs.builtin_symbol_attributes `MathML)
89     (builtin_symbol s)
90
91 let xml_of_sort x = 
92   let to_string x = Ast.Ident (x, None) in
93   let identify x = 
94     add_xml_attrs (RenderingAttrs.keyword_attributes `MathML) (to_string x)
95   in
96   let lvl t = Ast.AttributedTerm (`Level 90,t) in
97   match x with
98   | `Prop -> identify "Prop"
99   | `Set -> identify "Set"
100   | `CProp _ -> identify "CProp"
101   | `Type _ -> identify "Type"
102   | `NType s -> lvl(Ast.Layout (Ast.Sub (identify "Type",to_string s)))
103   | `NCProp s -> lvl(Ast.Layout (Ast.Sub (identify "CProp",to_string s)))
104 ;;
105
106
107 let map_space f l =
108  HExtlib.list_concat
109   ~sep:[space] (List.map (fun x -> [f x]) l)
110 ;;
111
112 let pp_ast0 t k =
113   let rec aux =
114     function
115     | Ast.Appl ts ->
116         let rec aux_args level =
117           function
118           | [] -> []
119           | [ last ] ->
120               [ Ast.AttributedTerm (`Level level,k last) ]
121           | hd :: tl ->
122               (Ast.AttributedTerm (`Level level, k hd)) :: aux_args 71 tl
123         in
124         add_level_info Ast.apply_prec 
125           (hovbox true true (CicNotationUtil.dress break (aux_args 70 ts)))
126     | Ast.Binder (binder_kind, (id, ty), body) ->
127         add_level_info Ast.binder_prec
128           (hvbox false true
129             [ binder_symbol (resolve_binder binder_kind);
130               k id; builtin_symbol ":"; aux_ty ty; break;
131               builtin_symbol "."; k body ])
132     | Ast.Case (what, indty_opt, outty_opt, patterns) ->
133         let outty_box =
134           match outty_opt with
135           | None -> []
136           | Some outty ->
137               [ space; keyword "return"; space; break; remove_level_info (k outty)]
138         in
139         let indty_box =
140           match indty_opt with
141           | None -> []
142           | Some (indty, href) -> [ space; keyword "in"; space; break; ident_w_href href indty ]
143         in
144         let match_box =
145           hvbox false false [
146            hvbox false true [
147             hvbox false true [keyword "match"; space; break; top_pos (k what)];
148             break;
149             hvbox false true indty_box;
150             break;
151             hvbox false true outty_box
152            ];
153            break;
154            space;
155            keyword "with";
156            space
157          ]
158         in
159         let mk_case_pattern =
160          function
161             Ast.Pattern (head, href, vars) ->
162              hvbox true true (ident_w_href href head :: 
163                List.flatten (List.map (fun x -> [break;x]) (map_space aux_var vars)))
164           | Ast.Wildcard -> builtin_symbol "_"
165         in
166         let patterns' =
167           List.map
168             (fun (lhs, rhs) ->
169               remove_level_info
170                 (hovbox false true [ 
171                   mk_case_pattern lhs; break; builtin_symbol "\\Rightarrow"; 
172                   break; top_pos (k rhs) ]))
173             patterns
174         in
175         let patterns'' =
176           let rec aux_patterns = function
177             | [] -> assert false
178             | [ last ] ->
179                 [ break; 
180                   hbox false false [
181                     builtin_symbol "|";
182                     last; builtin_symbol "]" ] ]
183             | hd :: tl ->
184                 [ break; hbox false false [ builtin_symbol "|"; hd ] ]
185                 @ aux_patterns tl
186           in
187           match patterns' with
188           | [] ->
189               [ hbox false false [ builtin_symbol "["; builtin_symbol "]" ] ]
190           | [ one ] ->
191               [ hbox false false [
192                 builtin_symbol "["; one; builtin_symbol "]" ] ]
193           | hd :: tl ->
194               hbox false false [ builtin_symbol "["; hd ]
195               :: aux_patterns tl
196         in
197         add_level_info Ast.simple_prec
198           (hvbox false false [
199             hvbox false false ([match_box]); break;
200             hbox false false [ hvbox false false patterns'' ] ])
201     | Ast.Cast (bo, ty) ->
202         add_level_info Ast.simple_prec
203           (hvbox false true [
204             builtin_symbol "("; top_pos (k bo); break; builtin_symbol ":";
205             top_pos (k ty); builtin_symbol ")"])
206     | Ast.LetIn (var, s, t) ->
207         add_level_info Ast.let_in_prec 
208           (hvbox false true [
209             hvbox false true [
210               keyword "let"; space;
211               hvbox false true [
212                 aux_var var; space;
213                 builtin_symbol "\\def"; break; top_pos (k s) ];
214               break; space; keyword "in"; space ];
215             break;
216             k t ])
217     | Ast.LetRec (rec_kind, funs, where) ->
218         let rec_op =
219           match rec_kind with `Inductive -> "rec" | `CoInductive -> "corec"
220         in
221         let mk_fun (args, (name,ty), body, rec_param) =
222          List.flatten (List.map (fun x -> [aux_var x; space]) args),
223           k name, HExtlib.map_option k ty, k body, fst (List.nth args rec_param)
224         in
225         let mk_funs = List.map mk_fun in
226         let fst_fun, tl_funs =
227           match mk_funs funs with hd :: tl -> hd, tl | [] -> assert false
228         in
229         let fst_row =
230           let (params, name, ty, body, rec_param) = fst_fun in
231           hvbox false true ([
232             keyword "let";
233             space;
234             keyword rec_op;
235             space;
236             name;
237             space] @
238             params @
239             [keyword "on" ; space ; rec_param ;space ] @
240             (match ty with None -> [] | Some ty -> [builtin_symbol ":"; ty]) @
241             [ builtin_symbol "\\def";
242             break;
243             top_pos body ])
244         in
245         let tl_rows =
246           List.map
247             (fun (params, name, ty, body, rec_param) ->
248               [ break;
249                 hvbox false true ([
250                   keyword "and"; space;
251                   name] @
252                   params @
253                   [space; keyword "on" ; space; rec_param ;space ] @
254                   (match ty with
255                       None -> []
256                     | Some ty -> [builtin_symbol ":"; ty]) @
257                   [ builtin_symbol "\\def"; break; body ])])
258             tl_funs
259         in
260         add_level_info Ast.let_in_prec
261           ((hvbox false false
262             (fst_row :: List.flatten tl_rows
263              @ [ break; keyword "in"; break; k where ])))
264     | Ast.Implicit `JustOne -> builtin_symbol "?"
265     | Ast.Implicit `Vector -> builtin_symbol "…"
266     | Ast.Meta (n, l) ->
267         let local_context l =
268             List.map (function None -> None | Some t -> Some (k t)) l
269         in
270         Ast.Meta(n, local_context l)
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 = xml_of_sort sort_kind
280   and aux_ty = function
281     | None -> builtin_symbol "?"
282     | Some ty -> k ty
283   and aux_var = function
284     | name, Some ty ->
285         hvbox false true [
286           builtin_symbol "("; name; builtin_symbol ":"; break; k ty;
287           builtin_symbol ")" ]
288     | name, None -> name
289   and special_k = function
290     | Ast.AttributedTerm (attrs, t) -> Ast.AttributedTerm (attrs, k t)
291     | t ->
292         prerr_endline ("unexpected special: " ^ CicNotationPp.pp_term t);
293         assert false
294   in
295   aux t
296
297   (* persistent state *)
298
299 let initial_level1_patterns21 () = Hashtbl.create 211
300 let level1_patterns21 = ref (initial_level1_patterns21 ())
301 let compiled21 = ref None
302 let pattern21_matrix = ref []
303 let counter = ref ~-1 
304
305 let stack = ref [];;
306
307 let push () =
308   stack := (!counter,!level1_patterns21,!compiled21,!pattern21_matrix)::!stack;
309   counter := ~-1;
310   level1_patterns21 := initial_level1_patterns21 ();
311   compiled21 := None;
312   pattern21_matrix := []
313 ;;
314
315 let pop () =
316  match !stack with
317     [] -> assert false
318   | (ocounter,olevel1_patterns21,ocompiled21,opatterns21_matrix)::old ->
319      stack := old;
320      counter := ocounter;
321      level1_patterns21 := olevel1_patterns21;
322      compiled21 := ocompiled21;
323      pattern21_matrix := opatterns21_matrix
324 ;;
325
326 let get_compiled21 () =
327   match !compiled21 with
328   | None -> assert false
329   | Some f -> Lazy.force f
330
331 let set_compiled21 f = compiled21 := Some f
332
333 let add_idrefs =
334   List.fold_right (fun idref t -> Ast.AttributedTerm (`IdRef idref, t))
335
336 let instantiate21 idrefs env l1 =
337   let rec subst_singleton pos env =
338     function
339       Ast.AttributedTerm (attr, t) ->
340         Ast.AttributedTerm (attr, subst_singleton pos env t)
341     | t -> CicNotationUtil.group (subst pos env t)
342   and subst pos env = function
343     | Ast.AttributedTerm (attr, t) ->
344 (*         prerr_endline ("loosing attribute " ^ CicNotationPp.pp_attribute attr); *)
345         subst pos env t
346     | Ast.Variable var ->
347         let name, expected_ty = CicNotationEnv.declaration_of_var var in
348         let ty, value =
349           try
350             List.assoc name env
351           with Not_found ->
352             prerr_endline ("name " ^ name ^ " not found in environment");
353             assert false
354         in
355         assert (CicNotationEnv.well_typed ty value); (* INVARIANT *)
356         (* following assertion should be a conditional that makes this
357          * instantiation fail *)
358         if not (CicNotationEnv.well_typed expected_ty value) then
359          begin
360           prerr_endline ("The variable " ^ name ^ " is used with the wrong type in the notation declaration");
361           assert false
362          end;
363         let value = CicNotationEnv.term_of_value value in
364         let value = 
365           match expected_ty with
366           | Env.TermType l -> Ast.AttributedTerm (`Level l,value) 
367           | _ -> value
368         in
369         [ value ]
370     | Ast.Magic m -> subst_magic pos env m
371     | Ast.Literal l as t ->
372         let t = add_idrefs idrefs t in
373         (match l with
374         | `Keyword k -> [ add_keyword_attrs t ]
375         | _ -> [ t ])
376     | Ast.Layout l -> [ Ast.Layout (subst_layout pos env l) ]
377     | t -> [ CicNotationUtil.visit_ast (subst_singleton pos env) t ]
378   and subst_magic pos env = function
379     | Ast.List0 (p, sep_opt)
380     | Ast.List1 (p, sep_opt) ->
381         let rec_decls = CicNotationEnv.declarations_of_term p in
382         let rec_values =
383           List.map (fun (n, _) -> CicNotationEnv.lookup_list env n) rec_decls
384         in
385         let values = CicNotationUtil.ncombine rec_values in
386         let sep =
387           match sep_opt with
388             | None -> []
389             | Some l -> [ Ast.Literal l; break; space ]
390         in
391         let rec instantiate_list acc = function
392           | [] -> List.rev acc
393           | value_set :: [] ->
394               let env = CicNotationEnv.combine rec_decls value_set in
395               instantiate_list (CicNotationUtil.group (subst pos env p) :: acc)
396                 []
397           | value_set :: tl ->
398               let env = CicNotationEnv.combine rec_decls value_set in
399               let terms = subst pos env p in
400               instantiate_list (CicNotationUtil.group (terms @ sep) :: acc) tl
401         in
402         if values = [] then []
403         else [hovbox false false (instantiate_list [] values)]
404     | Ast.Opt p ->
405         let opt_decls = CicNotationEnv.declarations_of_term p in
406         let env =
407           let rec build_env = function
408             | [] -> []
409             | (name, ty) :: tl ->
410                   (* assumption: if one of the value is None then all are *)
411                 (match CicNotationEnv.lookup_opt env name with
412                 | None -> raise Exit
413                 | Some v -> (name, (ty, v)) :: build_env tl)
414           in
415           try build_env opt_decls with Exit -> []
416         in
417           begin
418             match env with
419               | [] -> []
420               | _ -> subst pos env p
421           end
422     | _ -> assert false (* impossible *)
423   and subst_layout pos env = function
424     | Ast.Box (kind, tl) ->
425         let tl' = subst_children pos env tl in
426         Ast.Box (kind, List.concat tl')
427     | l -> CicNotationUtil.visit_layout (subst_singleton pos env) l
428   and subst_children pos env =
429     function
430     | [] -> []
431     | [ child ] ->
432         let pos' =
433           match pos with
434           | `Inner -> `Right
435           | `Left -> `Left
436 (*           | `None -> assert false *)
437           | `Right -> `Right
438         in
439         [ subst pos' env child ]
440     | hd :: tl ->
441         let pos' =
442           match pos with
443           | `Inner -> `Inner
444           | `Left -> `Inner
445 (*           | `None -> assert false *)
446           | `Right -> `Right
447         in
448         (subst pos env hd) :: subst_children pos' env tl
449   in
450     subst_singleton `Left env l1
451
452 let rec pp_ast1 term = 
453   let rec pp_value = function
454     | CicNotationEnv.NumValue _ as v -> v
455     | CicNotationEnv.StringValue _ as v -> v
456 (*     | CicNotationEnv.TermValue t when t == term -> CicNotationEnv.TermValue (pp_ast0 t pp_ast1) *)
457     | CicNotationEnv.TermValue t -> CicNotationEnv.TermValue (pp_ast1 t)
458     | CicNotationEnv.OptValue None as v -> v
459     | CicNotationEnv.OptValue (Some v) -> 
460         CicNotationEnv.OptValue (Some (pp_value v))
461     | CicNotationEnv.ListValue vl ->
462         CicNotationEnv.ListValue (List.map pp_value vl)
463   in
464   let ast_env_of_env env =
465     List.map (fun (var, (ty, value)) -> (var, (ty, pp_value value))) env
466   in
467 (* prerr_endline ("pattern matching from 2 to 1 on term " ^ CicNotationPp.pp_term term); *)
468   match term with
469   | Ast.AttributedTerm (attrs, term') ->
470       Ast.AttributedTerm (attrs, pp_ast1 term')
471   | _ ->
472       (match (get_compiled21 ()) term with
473       | None -> pp_ast0 term pp_ast1
474       | Some (env, ctors, pid) ->
475           let idrefs =
476             List.flatten (List.map CicNotationUtil.get_idrefs ctors)
477           in
478           let l1 =
479             try
480               Hashtbl.find !level1_patterns21 pid
481             with Not_found -> assert false
482           in
483           instantiate21 idrefs (ast_env_of_env env) l1)
484
485 let load_patterns21 t =
486   set_compiled21 (lazy (Content2presMatcher.Matcher21.compiler t))
487
488 let pp_ast ast =
489   debug_print (lazy "pp_ast <-");
490   let ast' = pp_ast1 ast in
491   debug_print (lazy ("pp_ast -> " ^ CicNotationPp.pp_term ast'));
492   ast'
493
494 exception Pretty_printer_not_found
495
496 let fill_pos_info l1_pattern = l1_pattern
497 (*   let rec aux toplevel pos =
498     function
499     | Ast.Layout l ->
500         (match l 
501
502     | Ast.Magic m ->
503         Ast.Box (
504     | Ast.Variable _ as t -> add_pos_info pos t
505     | t -> t
506   in
507   aux true l1_pattern *)
508
509 let fresh_id =
510   fun () ->
511     incr counter;
512     !counter
513
514 let add_pretty_printer l2 (CicNotationParser.CL1P (l1,precedence)) =
515   let id = fresh_id () in
516   let l1' = add_level_info precedence (fill_pos_info l1) in
517   let l2' = CicNotationUtil.strip_attributes l2 in
518   Hashtbl.add !level1_patterns21 id l1';
519   pattern21_matrix := (l2', id) :: !pattern21_matrix;
520   load_patterns21 !pattern21_matrix;
521   id
522
523 let remove_pretty_printer id =
524   (try
525     Hashtbl.remove !level1_patterns21 id;
526   with Not_found -> raise Pretty_printer_not_found);
527   pattern21_matrix := List.filter (fun (_, id') -> id <> id') !pattern21_matrix;
528   load_patterns21 !pattern21_matrix
529
530   (* presentation -> content *)
531
532 let unopt_names names env =
533   let rec aux acc = function
534     | (name, (ty, v)) :: tl when List.mem name names ->
535         (match ty, v with
536         | Env.OptType ty, Env.OptValue (Some v) ->
537             aux ((name, (ty, v)) :: acc) tl
538         | _ -> assert false)
539     | hd :: tl -> aux (hd :: acc) tl
540     | [] -> acc
541   in
542   aux [] env
543
544 let head_names names env =
545   let rec aux acc = function
546     | (name, (ty, v)) :: tl when List.mem name names ->
547         (match ty, v with
548         | Env.ListType ty, Env.ListValue (v :: _) ->
549             aux ((name, (ty, v)) :: acc) tl
550         | Env.TermType _, Env.TermValue _  ->
551             aux ((name, (ty, v)) :: acc) tl
552         | Env.OptType _, Env.OptValue _ ->
553             aux ((name, (ty, v)) :: acc) tl
554         | _ -> assert false)
555     | _ :: tl -> aux acc tl
556       (* base pattern may contain only meta names, thus we trash all others *)
557     | [] -> acc
558   in
559   aux [] env
560
561 let tail_names names env =
562   let rec aux acc = function
563     | (name, (ty, v)) :: tl when List.mem name names ->
564         (match ty, v with
565         | Env.ListType ty, Env.ListValue (_ :: vtl) ->
566             aux ((name, (Env.ListType ty, Env.ListValue vtl)) :: acc) tl
567         | Env.TermType _, Env.TermValue _  ->
568             aux ((name, (ty, v)) :: acc) tl
569         | Env.OptType _, Env.OptValue _ ->
570             aux ((name, (ty, v)) :: acc) tl
571         | _ -> assert false)
572     | binding :: tl -> aux (binding :: acc) tl
573     | [] -> acc
574   in
575   aux [] env
576
577 let instantiate_level2 env term =
578 (*   prerr_endline ("istanzio: " ^ CicNotationPp.pp_term term); *)
579   let fresh_env = ref [] in
580   let lookup_fresh_name n =
581     try
582       List.assoc n !fresh_env
583     with Not_found ->
584       let new_name = CicNotationUtil.fresh_name () in
585       fresh_env := (n, new_name) :: !fresh_env;
586       new_name
587   in
588   let rec aux env term =
589 (*    prerr_endline ("ENV " ^ CicNotationPp.pp_env env); *)
590     match term with
591     | Ast.AttributedTerm (a, term) -> (*Ast.AttributedTerm (a, *)aux env term
592     | Ast.Appl terms -> Ast.Appl (List.map (aux env) terms)
593     | Ast.Binder (binder, var, body) ->
594         Ast.Binder (binder, aux_capture_var env var, aux env body)
595     | Ast.Case (term, indty, outty_opt, patterns) ->
596         Ast.Case (aux env term, indty, aux_opt env outty_opt,
597           List.map (aux_branch env) patterns)
598     | Ast.LetIn (var, t1, t3) ->
599         Ast.LetIn (aux_capture_var env var, aux env t1, aux env t3)
600     | Ast.LetRec (kind, definitions, body) ->
601         Ast.LetRec (kind, List.map (aux_definition env) definitions,
602           aux env body)
603     | Ast.Uri (name, None) -> Ast.Uri (name, None)
604     | Ast.Uri (name, Some substs) ->
605         Ast.Uri (name, Some (aux_substs env substs))
606     | Ast.Ident (name, Some substs) ->
607         Ast.Ident (name, Some (aux_substs env substs))
608     | Ast.Meta (index, substs) -> Ast.Meta (index, aux_meta_substs env substs)
609
610     | Ast.Implicit _
611     | Ast.Ident _
612     | Ast.Num _
613     | Ast.Sort _
614     | Ast.Symbol _
615     | Ast.UserInput -> term
616
617     | Ast.Magic magic -> aux_magic env magic
618     | Ast.Variable var -> aux_variable env var
619
620     | Ast.Cast (t, ty) -> Ast.Cast (aux env t, aux env ty)
621
622     | _ -> assert false
623   and aux_opt env = function
624     | Some term -> Some (aux env term)
625     | None -> None
626   and aux_capture_var env (name, ty_opt) = (aux env name, aux_opt env ty_opt)
627   and aux_branch env (pattern, term) =
628     (aux_pattern env pattern, aux env term)
629   and aux_pattern env =
630    function
631       Ast.Pattern (head, hrefs, vars) ->
632        Ast.Pattern (head, hrefs, List.map (aux_capture_var env) vars)
633     | Ast.Wildcard -> Ast.Wildcard
634   and aux_definition env (params, var, term, i) =
635     (List.map (aux_capture_var env) params, aux_capture_var env var, aux env term, i)
636   and aux_substs env substs =
637     List.map (fun (name, term) -> (name, aux env term)) substs
638   and aux_meta_substs env meta_substs = List.map (aux_opt env) meta_substs
639   and aux_variable env = function
640     | Ast.NumVar name -> Ast.Num (Env.lookup_num env name, 0)
641     | Ast.IdentVar name -> Ast.Ident (Env.lookup_string env name, None)
642     | Ast.TermVar (name,(Ast.Level l|Ast.Self l)) -> 
643         Ast.AttributedTerm (`Level l,Env.lookup_term env name)
644     | Ast.FreshVar name -> Ast.Ident (lookup_fresh_name name, None)
645     | Ast.Ascription (term, name) -> assert false
646   and aux_magic env = function
647     | Ast.Default (some_pattern, none_pattern) ->
648         let some_pattern_names = CicNotationUtil.names_of_term some_pattern in
649         let none_pattern_names = CicNotationUtil.names_of_term none_pattern in
650         let opt_names =
651           List.filter
652             (fun name -> not (List.mem name none_pattern_names))
653             some_pattern_names
654         in
655         (match opt_names with
656         | [] -> assert false (* some pattern must contain at least 1 name *)
657         | (name :: _) as names ->
658             (match Env.lookup_value env name with
659             | Env.OptValue (Some _) ->
660                 (* assumption: if "name" above is bound to Some _, then all
661                  * names returned by "meta_names_of" are bound to Some _ as well
662                  *)
663                 aux (unopt_names names env) some_pattern
664             | Env.OptValue None -> aux env none_pattern
665             | _ ->
666                 prerr_endline (sprintf
667                   "lookup of %s in env %s did not return an optional value"
668                   name (CicNotationPp.pp_env env));
669                 assert false))
670     | Ast.Fold (`Left, base_pattern, names, rec_pattern) ->
671         let acc_name = List.hd names in (* names can't be empty, cfr. parser *)
672         let meta_names =
673           List.filter ((<>) acc_name)
674             (CicNotationUtil.names_of_term rec_pattern)
675         in
676         (match meta_names with
677         | [] -> assert false (* as above *)
678         | (name :: _) as names ->
679             let rec instantiate_fold_left acc env' =
680               match Env.lookup_value env' name with
681               | Env.ListValue (_ :: _) ->
682                   instantiate_fold_left 
683                     (let acc_binding =
684                       acc_name, (Env.TermType 0, Env.TermValue acc)
685                      in
686                      aux (acc_binding :: head_names names env') rec_pattern)
687                     (tail_names names env')
688               | Env.ListValue [] -> acc
689               | _ -> assert false
690             in
691             instantiate_fold_left (aux env base_pattern) env)
692     | Ast.Fold (`Right, base_pattern, names, rec_pattern) ->
693         let acc_name = List.hd names in (* names can't be empty, cfr. parser *)
694         let meta_names =
695           List.filter ((<>) acc_name)
696             (CicNotationUtil.names_of_term rec_pattern)
697         in
698         (match meta_names with
699         | [] -> assert false (* as above *)
700         | (name :: _) as names ->
701             let rec instantiate_fold_right env' =
702               match Env.lookup_value env' name with
703               | Env.ListValue (_ :: _) ->
704                   let acc = instantiate_fold_right (tail_names names env') in
705                   let acc_binding =
706                     acc_name, (Env.TermType 0, Env.TermValue acc)
707                   in
708                   aux (acc_binding :: head_names names env') rec_pattern
709               | Env.ListValue [] -> aux env base_pattern
710               | _ -> assert false
711             in
712             instantiate_fold_right env)
713     | Ast.If (_, p_true, p_false) as t ->
714         aux env (CicNotationUtil.find_branch (Ast.Magic t))
715     | Ast.Fail -> assert false
716     | _ -> assert false
717   in
718   aux env term
719
720   (* initialization *)
721
722 let _ = load_patterns21 []
723
724
725