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