1 (* Copyright (C) 2004-2005, HELM Team.
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.
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.
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.
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,
22 * For details, see the HELM World-Wide-Web page,
23 * http://helm.cs.unibo.it/
30 module Ast = NotationPt
31 module Env = NotationEnv
34 let debug_print s = if debug then prerr_endline (Lazy.force s) else ()
37 type pretty_printer_id = pattern_id
39 let resolve_binder = function
40 | `Lambda -> "\\lambda"
42 | `Forall -> "\\forall"
43 | `Exists -> "\\exists"
45 let add_level_info prec t = Ast.AttributedTerm (`Level prec, t)
47 let rec top_pos t = add_level_info ~-1 t
49 let rec remove_level_info =
51 | Ast.AttributedTerm (`Level _, t) -> remove_level_info t
52 | Ast.AttributedTerm (a, t) -> Ast.AttributedTerm (a, remove_level_info t)
55 let add_xml_attrs attrs t =
56 if attrs = [] then t else Ast.AttributedTerm (`XmlAttrs attrs, t)
58 let add_keyword_attrs =
59 add_xml_attrs (RenderingAttrs.keyword_attributes `MathML)
61 let box kind spacing indent content =
62 Ast.Layout (Ast.Box ((kind, spacing, indent), content))
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))
74 add_xml_attrs (RenderingAttrs.number_attributes `MathML)
75 (Ast.Literal (`Number s))
78 add_xml_attrs (RenderingAttrs.ident_attributes `MathML) (Ast.Ident (i, None))
80 let ident_w_href href i =
84 let href = NReference.string_of_reference href in
85 add_xml_attrs [Some "xlink", "href", href] (ident i)
88 add_xml_attrs (RenderingAttrs.builtin_symbol_attributes `MathML)
92 let to_string x = Ast.Ident (x, None) in
94 add_xml_attrs (RenderingAttrs.keyword_attributes `MathML) (to_string x)
96 let lvl t = Ast.AttributedTerm (`Level 90,t) in
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)))
109 ~sep:[space] (List.map (fun x -> [f x]) l)
112 let pp_ast0 status t k =
116 let rec aux_args level =
120 [ Ast.AttributedTerm (`Level level,k last) ]
122 (Ast.AttributedTerm (`Level level, k hd)) :: aux_args 71 tl
124 add_level_info Ast.apply_prec
125 (hovbox true true (NotationUtil.dress break (aux_args 70 ts)))
126 | Ast.Binder (binder_kind, (id, ty), body) ->
127 add_level_info Ast.binder_prec
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) ->
137 [ space; keyword "return"; space; break; remove_level_info (k outty)]
142 | Some (indty, href) -> [ space; keyword "in"; space; break; ident_w_href href indty ]
147 hvbox false true [keyword "match"; space; break; top_pos (k what)];
149 hvbox false true indty_box;
151 hvbox false true outty_box
159 let mk_case_pattern =
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 "_"
171 mk_case_pattern lhs; break; builtin_symbol "\\Rightarrow";
172 break; top_pos (k rhs) ]))
176 let rec aux_patterns = function
182 last; builtin_symbol "]" ] ]
184 [ break; hbox false false [ builtin_symbol "|"; hd ] ]
189 [ hbox false false [ builtin_symbol "["; builtin_symbol "]" ] ]
192 builtin_symbol "["; one; builtin_symbol "]" ] ]
194 hbox false false [ builtin_symbol "["; hd ]
197 add_level_info Ast.simple_prec
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
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
210 keyword "let"; space;
213 builtin_symbol "\\def"; break; top_pos (k s); space; keyword "in"; space ];
217 | Ast.LetRec (rec_kind, funs, where) ->
219 match rec_kind with `Inductive -> "rec" | `CoInductive -> "corec"
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)
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
230 let (params, name, ty, body, rec_param) = fst_fun in
239 [keyword "on" ; space ; rec_param ;space ] @
240 (match ty with None -> [] | Some ty -> [builtin_symbol ":"; ty]) @
241 [ builtin_symbol "\\def";
247 (fun (params, name, ty, body, rec_param) ->
250 keyword "and"; space;
253 [space; keyword "on" ; space; rec_param ;space ] @
256 | Some ty -> [builtin_symbol ":"; ty]) @
257 [ builtin_symbol "\\def"; break; body ])])
260 add_level_info Ast.let_in_prec
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 "…"
267 let local_context l =
268 List.map (function None -> None | Some t -> Some (k t)) l
270 Ast.Meta(n, local_context l)
271 | Ast.Sort sort -> aux_sort sort
274 | Ast.Ident (_, None) | Ast.Ident (_, Some [])
275 | Ast.Uri (_, None) | Ast.Uri (_, Some [])
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 "?"
283 and aux_var = function
286 builtin_symbol "("; name; builtin_symbol ":"; break; k ty;
289 and special_k = function
290 | Ast.AttributedTerm (attrs, t) -> Ast.AttributedTerm (attrs, k t)
292 prerr_endline ("unexpected special: " ^ NotationPp.pp_term status t);
297 (* persistent state *)
299 module IntMap = Map.Make(struct type t = int let compare = compare end);;
302 level1_patterns21: NotationPt.term IntMap.t;
303 compiled21: ((NotationPt.term -> (NotationEnv.t * NotationPt.term list * int) option)) Lazy.t;
304 pattern21_matrix: (NotationPt.term * pattern_id) list;
309 level1_patterns21 = IntMap.empty;
310 compiled21 = lazy (Content2presMatcher.Matcher21.compiler []);
311 pattern21_matrix = [];
315 class type g_status =
317 method content_pres_db: db
320 class virtual status =
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 >}
331 let get_compiled21 status =
332 Lazy.force status#content_pres_db.compiled21
334 let set_compiled21 status f =
335 status#set_content_pres_db
336 { status#content_pres_db with compiled21 = f }
339 List.fold_right (fun idref t -> Ast.AttributedTerm (`IdRef idref, t))
341 let instantiate21 idrefs env l1 =
342 let rec subst_singleton pos env =
344 Ast.AttributedTerm (attr, t) ->
345 Ast.AttributedTerm (attr, subst_singleton pos env t)
346 | t -> NotationUtil.group (subst pos env t)
347 and subst pos env = function
348 | Ast.AttributedTerm (attr, t) ->
349 (* prerr_endline ("loosing attribute " ^ NotationPp.pp_attribute attr); *)
351 | Ast.Variable var ->
352 let name, expected_ty = NotationEnv.declaration_of_var var in
357 prerr_endline ("name " ^ name ^ " not found in environment");
360 assert (NotationEnv.well_typed ty value); (* INVARIANT *)
361 (* following assertion should be a conditional that makes this
362 * instantiation fail *)
363 if not (NotationEnv.well_typed expected_ty value) then
365 prerr_endline ("The variable " ^ name ^ " is used with the wrong type in the notation declaration");
368 let value = NotationEnv.term_of_value value in
370 match expected_ty with
371 | Env.TermType l -> Ast.AttributedTerm (`Level l,value)
375 | Ast.Magic m -> subst_magic pos env m
376 | Ast.Literal l as t ->
377 let t = add_idrefs idrefs t in
379 | `Keyword k -> [ add_keyword_attrs t ]
381 | Ast.Layout l -> [ Ast.Layout (subst_layout pos env l) ]
382 | t -> [ NotationUtil.visit_ast (subst_singleton pos env) t ]
383 and subst_magic pos env = function
384 | Ast.List0 (p, sep_opt)
385 | Ast.List1 (p, sep_opt) ->
386 let rec_decls = NotationEnv.declarations_of_term p in
388 List.map (fun (n, _) -> NotationEnv.lookup_list env n) rec_decls
390 let values = NotationUtil.ncombine rec_values in
394 | Some l -> [ Ast.Literal l; break; space ]
396 let rec instantiate_list acc = function
399 let env = NotationEnv.combine rec_decls value_set in
400 instantiate_list (NotationUtil.group (subst pos env p) :: acc)
403 let env = NotationEnv.combine rec_decls value_set in
404 let terms = subst pos env p in
405 instantiate_list (NotationUtil.group (terms @ sep) :: acc) tl
407 if values = [] then []
408 else [hovbox false false (instantiate_list [] values)]
410 let opt_decls = NotationEnv.declarations_of_term p in
412 let rec build_env = function
414 | (name, ty) :: tl ->
415 (* assumption: if one of the value is None then all are *)
416 (match NotationEnv.lookup_opt env name with
418 | Some v -> (name, (ty, v)) :: build_env tl)
420 try build_env opt_decls with Exit -> []
425 | _ -> subst pos env p
427 | _ -> assert false (* impossible *)
428 and subst_layout pos env = function
429 | Ast.Box (kind, tl) ->
430 let tl' = subst_children pos env tl in
431 Ast.Box (kind, List.concat tl')
432 | l -> NotationUtil.visit_layout (subst_singleton pos env) l
433 and subst_children pos env =
441 (* | `None -> assert false *)
444 [ subst pos' env child ]
450 (* | `None -> assert false *)
453 (subst pos env hd) :: subst_children pos' env tl
455 subst_singleton `Left env l1
457 let rec pp_ast1 status term =
458 let rec pp_value = function
459 | NotationEnv.NumValue _ as v -> v
460 | NotationEnv.StringValue _ as v -> v
461 (* | NotationEnv.TermValue t when t == term -> NotationEnv.TermValue (pp_ast0 status t pp_ast1) *)
462 | NotationEnv.TermValue t -> NotationEnv.TermValue (pp_ast1 status t)
463 | NotationEnv.OptValue None as v -> v
464 | NotationEnv.OptValue (Some v) ->
465 NotationEnv.OptValue (Some (pp_value v))
466 | NotationEnv.ListValue vl ->
467 NotationEnv.ListValue (List.map pp_value vl)
469 let ast_env_of_env env =
470 List.map (fun (var, (ty, value)) -> (var, (ty, pp_value value))) env
472 (* prerr_endline ("pattern matching from 2 to 1 on term " ^ NotationPp.pp_term term); *)
474 | Ast.AttributedTerm (attrs, term') ->
475 Ast.AttributedTerm (attrs, pp_ast1 status term')
477 (match get_compiled21 status term with
478 | None -> pp_ast0 status term (pp_ast1 status)
479 | Some (env, ctors, pid) ->
481 List.flatten (List.map NotationUtil.get_idrefs ctors)
485 IntMap.find pid status#content_pres_db.level1_patterns21
486 with Not_found -> assert false
488 instantiate21 idrefs (ast_env_of_env env) l1)
490 let load_patterns21 status t =
491 set_compiled21 status (lazy (Content2presMatcher.Matcher21.compiler t))
493 let pp_ast status ast =
494 debug_print (lazy "pp_ast <-");
495 let ast' = pp_ast1 status ast in
496 debug_print (lazy ("pp_ast -> " ^ NotationPp.pp_term status ast'));
499 let fill_pos_info l1_pattern = l1_pattern
500 (* let rec aux toplevel pos =
507 | Ast.Variable _ as t -> add_pos_info pos t
510 aux true l1_pattern *)
512 let fresh_id status =
513 let counter = status#content_pres_db.counter+1 in
514 status#set_content_pres_db ({ status#content_pres_db with counter = counter }), counter
516 let add_pretty_printer status l2 (CicNotationParser.CL1P (l1,precedence)) =
517 let status,id = fresh_id status in
518 let l1' = add_level_info precedence (fill_pos_info l1) in
519 let l2' = NotationUtil.strip_attributes l2 in
521 status#set_content_pres_db
522 { status#content_pres_db with
524 IntMap.add id l1' status#content_pres_db.level1_patterns21;
525 pattern21_matrix = (l2',id)::status#content_pres_db.pattern21_matrix } in
526 load_patterns21 status status#content_pres_db.pattern21_matrix
528 (* presentation -> content *)
530 let unopt_names names env =
531 let rec aux acc = function
532 | (name, (ty, v)) :: tl when List.mem name names ->
534 | Env.OptType ty, Env.OptValue (Some v) ->
535 aux ((name, (ty, v)) :: acc) tl
537 | hd :: tl -> aux (hd :: acc) tl
542 let head_names names env =
543 let rec aux acc = function
544 | (name, (ty, v)) :: tl when List.mem name names ->
546 | Env.ListType ty, Env.ListValue (v :: _) ->
547 aux ((name, (ty, v)) :: acc) tl
548 | Env.TermType _, Env.TermValue _ ->
549 aux ((name, (ty, v)) :: acc) tl
550 | Env.OptType _, Env.OptValue _ ->
551 aux ((name, (ty, v)) :: acc) tl
553 | _ :: tl -> aux acc tl
554 (* base pattern may contain only meta names, thus we trash all others *)
559 let tail_names names env =
560 let rec aux acc = function
561 | (name, (ty, v)) :: tl when List.mem name names ->
563 | Env.ListType ty, Env.ListValue (_ :: vtl) ->
564 aux ((name, (Env.ListType ty, Env.ListValue vtl)) :: acc) tl
565 | Env.TermType _, Env.TermValue _ ->
566 aux ((name, (ty, v)) :: acc) tl
567 | Env.OptType _, Env.OptValue _ ->
568 aux ((name, (ty, v)) :: acc) tl
570 | binding :: tl -> aux (binding :: acc) tl
575 let instantiate_level2 status env term =
576 (* prerr_endline ("istanzio: " ^ NotationPp.pp_term term); *)
577 let fresh_env = ref [] in
578 let lookup_fresh_name n =
580 List.assoc n !fresh_env
582 let new_name = NotationUtil.fresh_name () in
583 fresh_env := (n, new_name) :: !fresh_env;
586 let rec aux env term =
588 | Ast.AttributedTerm (a, term) -> (*Ast.AttributedTerm (a, *)aux env term
589 | Ast.Appl terms -> Ast.Appl (List.map (aux env) terms)
590 | Ast.Binder (binder, var, body) ->
591 Ast.Binder (binder, aux_capture_var env var, aux env body)
592 | Ast.Case (term, indty, outty_opt, patterns) ->
593 Ast.Case (aux env term, indty, aux_opt env outty_opt,
594 List.map (aux_branch env) patterns)
595 | Ast.LetIn (var, t1, t3) ->
596 Ast.LetIn (aux_capture_var env var, aux env t1, aux env t3)
597 | Ast.LetRec (kind, definitions, body) ->
598 Ast.LetRec (kind, List.map (aux_definition env) definitions,
600 | Ast.Uri (name, None) -> Ast.Uri (name, None)
601 | Ast.Uri (name, Some substs) ->
602 Ast.Uri (name, Some (aux_substs env substs))
603 | Ast.Ident (name, Some substs) ->
604 Ast.Ident (name, Some (aux_substs env substs))
605 | Ast.Meta (index, substs) -> Ast.Meta (index, aux_meta_substs env substs)
612 | Ast.UserInput -> term
614 | Ast.Magic magic -> aux_magic env magic
615 | Ast.Variable var -> aux_variable env var
617 | Ast.Cast (t, ty) -> Ast.Cast (aux env t, aux env ty)
620 and aux_opt env = function
621 | Some term -> Some (aux env term)
623 and aux_capture_var env (name, ty_opt) = (aux env name, aux_opt env ty_opt)
624 and aux_branch env (pattern, term) =
625 (aux_pattern env pattern, aux env term)
626 and aux_pattern env =
628 Ast.Pattern (head, hrefs, vars) ->
629 Ast.Pattern (head, hrefs, List.map (aux_capture_var env) vars)
630 | Ast.Wildcard -> Ast.Wildcard
631 and aux_definition env (params, var, term, i) =
632 (List.map (aux_capture_var env) params, aux_capture_var env var, aux env term, i)
633 and aux_substs env substs =
634 List.map (fun (name, term) -> (name, aux env term)) substs
635 and aux_meta_substs env meta_substs = List.map (aux_opt env) meta_substs
636 and aux_variable env = function
637 | Ast.NumVar name -> Ast.Num (Env.lookup_num env name, 0)
638 | Ast.IdentVar name ->
639 (match Env.lookup_string env name with
640 Env.Ident x -> Ast.Ident (x, None)
641 | Env.Var x -> Ast.Variable (Ast.IdentVar x))
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 = NotationUtil.names_of_term some_pattern in
649 let none_pattern_names = NotationUtil.names_of_term none_pattern in
652 (fun name -> not (List.mem name none_pattern_names))
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
663 aux (unopt_names names env) some_pattern
664 | Env.OptValue None -> aux env none_pattern
666 prerr_endline (sprintf
667 "lookup of %s in env %s did not return an optional value"
668 name (NotationPp.pp_env status env));
670 | Ast.Fold (`Left, base_pattern, names, rec_pattern) ->
671 let acc_name = List.hd names in (* names can't be empty, cfr. parser *)
673 List.filter ((<>) acc_name)
674 (NotationUtil.names_of_term rec_pattern)
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
684 acc_name, (Env.TermType 0, Env.TermValue acc)
686 aux (acc_binding :: head_names names env') rec_pattern)
687 (tail_names names env')
688 | Env.ListValue [] -> acc
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 *)
695 List.filter ((<>) acc_name)
696 (NotationUtil.names_of_term rec_pattern)
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
706 acc_name, (Env.TermType 0, Env.TermValue acc)
708 aux (acc_binding :: head_names names env') rec_pattern
709 | Env.ListValue [] -> aux env base_pattern
712 instantiate_fold_right env)
713 | Ast.If (_, p_true, p_false) as t ->
714 aux env (NotationUtil.find_branch (Ast.Magic t))
715 | Ast.Fail -> assert false