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 = CicNotationPt
31 module Env = CicNotationEnv
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 assoc t = Ast.AttributedTerm (`Level (prec, assoc), t)
46 let add_pos_info pos t = Ast.AttributedTerm (`ChildPos pos, t)
47 let left_pos = add_pos_info `Left
48 let right_pos = add_pos_info `Right
49 let inner_pos = add_pos_info `Inner
51 let rec top_pos t = add_level_info ~-1 Gramext.NonA (inner_pos t)
53 | Ast.AttributedTerm (`Level _, t) ->
54 add_level_info ~-1 Gramext.NonA (inner_pos t)
55 | Ast.AttributedTerm (attr, t) -> Ast.AttributedTerm (attr, top_pos t)
56 | t -> add_level_info ~-1 Gramext.NonA (inner_pos t) *)
58 let rec remove_level_info =
60 | Ast.AttributedTerm (`Level _, t) -> remove_level_info t
61 | Ast.AttributedTerm (a, t) -> Ast.AttributedTerm (a, remove_level_info t)
64 let add_xml_attrs attrs t =
65 if attrs = [] then t else Ast.AttributedTerm (`XmlAttrs attrs, t)
67 let add_keyword_attrs =
68 add_xml_attrs (RenderingAttrs.keyword_attributes `MathML)
70 let box kind spacing indent content =
71 Ast.Layout (Ast.Box ((kind, spacing, indent), content))
75 let hvbox = box Ast.HV
76 let hovbox = box Ast.HOV
77 let break = Ast.Layout Ast.Break
78 let space = Ast.Literal (`Symbol " ")
79 let builtin_symbol s = Ast.Literal (`Symbol s)
80 let keyword k = add_keyword_attrs (Ast.Literal (`Keyword k))
83 add_xml_attrs (RenderingAttrs.number_attributes `MathML)
84 (Ast.Literal (`Number s))
87 add_xml_attrs (RenderingAttrs.ident_attributes `MathML) (Ast.Ident (i, None))
89 let ident_w_href href i =
93 let href = UriManager.string_of_uri href in
94 add_xml_attrs [Some "xlink", "href", href] (ident i)
97 add_xml_attrs (RenderingAttrs.builtin_symbol_attributes `MathML)
100 let string_of_sort_kind = function
110 let rec aux_args pos =
115 if pos = `Left then [ left_pos last ] else [ right_pos last ]
117 (add_pos_info pos (k hd)) :: aux_args `Inner tl
119 add_level_info Ast.apply_prec Ast.apply_assoc
120 (hovbox true true (CicNotationUtil.dress break (aux_args `Left ts)))
121 | Ast.Binder (binder_kind, (id, ty), body) ->
122 add_level_info Ast.binder_prec Ast.binder_assoc
124 [ binder_symbol (resolve_binder binder_kind);
125 k id; builtin_symbol ":"; aux_ty ty; break;
126 builtin_symbol "."; right_pos (k body) ])
127 | Ast.Case (what, indty_opt, outty_opt, patterns) ->
132 [ space; keyword "return"; space; break; remove_level_info (k outty)]
137 | Some (indty, href) -> [ space; keyword "in"; space; break; ident_w_href href indty ]
142 hvbox false true [keyword "match"; space; break; top_pos (k what)];
144 hvbox false true indty_box;
146 hvbox false true outty_box
154 let mk_case_pattern =
156 Ast.Pattern (head, href, vars) ->
157 hbox true false (ident_w_href href head :: List.map aux_var vars)
158 | Ast.Wildcard -> builtin_symbol "_"
166 mk_case_pattern lhs; builtin_symbol "\\Rightarrow" ];
167 break; top_pos (k rhs) ]))
171 let rec aux_patterns = function
177 last; builtin_symbol "]" ] ]
179 [ break; hbox false false [ builtin_symbol "|"; hd ] ]
184 [ hbox false false [ builtin_symbol "["; builtin_symbol "]" ] ]
187 builtin_symbol "["; one; builtin_symbol "]" ] ]
189 hbox false false [ builtin_symbol "["; hd ]
192 add_level_info Ast.simple_prec Ast.simple_assoc
194 hvbox false false ([match_box]); break;
195 hbox false false [ hvbox false false patterns'' ] ])
196 | Ast.Cast (bo, ty) ->
197 add_level_info Ast.simple_prec Ast.simple_assoc
199 builtin_symbol "("; top_pos (k bo); break; builtin_symbol ":";
200 top_pos (k ty); builtin_symbol ")"])
201 | Ast.LetIn (var, s, t) ->
202 add_level_info Ast.let_in_prec Ast.let_in_assoc
205 keyword "let"; space;
207 aux_var var; space; builtin_symbol "\\def"; break; top_pos (k s) ];
208 break; space; keyword "in" ];
211 | Ast.LetRec (rec_kind, funs, where) ->
213 match rec_kind with `Inductive -> "rec" | `CoInductive -> "corec"
215 let mk_fun (args, (name,ty), body, rec_param) =
216 List.map aux_var args ,k name, HExtlib.map_option k ty, k body,
217 fst (List.nth args rec_param)
219 let mk_funs = List.map mk_fun in
220 let fst_fun, tl_funs =
221 match mk_funs funs with hd :: tl -> hd, tl | [] -> assert false
224 let (params, name, ty, body, rec_param) = fst_fun in
232 [space; keyword "on" ; space ; rec_param ;space ] @
233 (match ty with None -> [] | Some ty -> [builtin_symbol ":"; ty]) @
234 [ builtin_symbol "\\def";
240 (fun (params, name, ty, body, rec_param) ->
246 [space; keyword "on" ; space; rec_param ;space ] @
249 | Some ty -> [builtin_symbol ":"; ty]) @
250 [ builtin_symbol "\\def"; break; body ])])
253 add_level_info Ast.let_in_prec Ast.let_in_assoc
255 (fst_row :: List.flatten tl_rows
256 @ [ break; keyword "in"; break; k where ])))
257 | Ast.Implicit -> builtin_symbol "?"
259 let local_context l =
260 List.map (function None -> None | Some t -> Some (k t)) l
262 Ast.Meta(n, local_context l)
263 | Ast.Sort sort -> aux_sort sort
266 | Ast.Ident (_, None) | Ast.Ident (_, Some [])
267 | Ast.Uri (_, None) | Ast.Uri (_, Some [])
269 | Ast.UserInput as leaf -> leaf
270 | t -> CicNotationUtil.visit_ast ~special_k k t
271 and aux_sort sort_kind =
272 add_xml_attrs (RenderingAttrs.keyword_attributes `MathML)
273 (Ast.Ident (string_of_sort_kind sort_kind, None))
274 and aux_ty = function
275 | None -> builtin_symbol "?"
277 and aux_var = function
280 builtin_symbol "("; name; builtin_symbol ":"; break; k ty;
283 and special_k = function
284 | Ast.AttributedTerm (attrs, t) -> Ast.AttributedTerm (attrs, k t)
286 prerr_endline ("unexpected special: " ^ CicNotationPp.pp_term t);
291 (* persistent state *)
293 let level1_patterns21 = Hashtbl.create 211
295 let compiled21 = ref None
297 let pattern21_matrix = ref []
299 let get_compiled21 () =
300 match !compiled21 with
301 | None -> assert false
302 | Some f -> Lazy.force f
304 let set_compiled21 f = compiled21 := Some f
307 List.fold_right (fun idref t -> Ast.AttributedTerm (`IdRef idref, t))
309 let instantiate21 idrefs env l1 =
310 let rec subst_singleton pos env =
312 Ast.AttributedTerm (attr, t) ->
313 Ast.AttributedTerm (attr, subst_singleton pos env t)
314 | t -> CicNotationUtil.group (subst pos env t)
315 and subst pos env = function
316 | Ast.AttributedTerm (attr, t) ->
317 (* prerr_endline ("loosing attribute " ^ CicNotationPp.pp_attribute attr); *)
319 | Ast.Variable var ->
320 let name, expected_ty = CicNotationEnv.declaration_of_var var in
325 prerr_endline ("name " ^ name ^ " not found in environment");
328 assert (CicNotationEnv.well_typed ty value); (* INVARIANT *)
329 (* following assertion should be a conditional that makes this
330 * instantiation fail *)
331 assert (CicNotationEnv.well_typed expected_ty value);
332 [ add_pos_info pos (CicNotationEnv.term_of_value value) ]
333 | Ast.Magic m -> subst_magic pos env m
334 | Ast.Literal l as t ->
335 let t = add_idrefs idrefs t in
337 | `Keyword k -> [ add_keyword_attrs t ]
339 | Ast.Layout l -> [ Ast.Layout (subst_layout pos env l) ]
340 | t -> [ CicNotationUtil.visit_ast (subst_singleton pos env) t ]
341 and subst_magic pos env = function
342 | Ast.List0 (p, sep_opt)
343 | Ast.List1 (p, sep_opt) ->
344 let rec_decls = CicNotationEnv.declarations_of_term p in
346 List.map (fun (n, _) -> CicNotationEnv.lookup_list env n) rec_decls
348 let values = CicNotationUtil.ncombine rec_values in
352 | Some l -> [ Ast.Literal l ]
354 let rec instantiate_list acc = function
357 let env = CicNotationEnv.combine rec_decls value_set in
358 instantiate_list (CicNotationUtil.group (subst pos env p) :: acc)
361 let env = CicNotationEnv.combine rec_decls value_set in
362 let terms = subst pos env p in
363 instantiate_list (CicNotationUtil.group (terms @ sep) :: acc) tl
365 instantiate_list [] values
367 let opt_decls = CicNotationEnv.declarations_of_term p in
369 let rec build_env = function
371 | (name, ty) :: tl ->
372 (* assumption: if one of the value is None then all are *)
373 (match CicNotationEnv.lookup_opt env name with
375 | Some v -> (name, (ty, v)) :: build_env tl)
377 try build_env opt_decls with Exit -> []
382 | _ -> subst pos env p
384 | _ -> assert false (* impossible *)
385 and subst_layout pos env = function
386 | Ast.Box (kind, tl) ->
387 let tl' = subst_children pos env tl in
388 Ast.Box (kind, List.concat tl')
389 | l -> CicNotationUtil.visit_layout (subst_singleton pos env) l
390 and subst_children pos env =
398 (* | `None -> assert false *)
401 [ subst pos' env child ]
407 (* | `None -> assert false *)
410 (subst pos env hd) :: subst_children pos' env tl
412 subst_singleton `Left env l1
414 let rec pp_ast1 term =
415 let rec pp_value = function
416 | CicNotationEnv.NumValue _ as v -> v
417 | CicNotationEnv.StringValue _ as v -> v
418 (* | CicNotationEnv.TermValue t when t == term -> CicNotationEnv.TermValue (pp_ast0 t pp_ast1) *)
419 | CicNotationEnv.TermValue t -> CicNotationEnv.TermValue (pp_ast1 t)
420 | CicNotationEnv.OptValue None as v -> v
421 | CicNotationEnv.OptValue (Some v) ->
422 CicNotationEnv.OptValue (Some (pp_value v))
423 | CicNotationEnv.ListValue vl ->
424 CicNotationEnv.ListValue (List.map pp_value vl)
426 let ast_env_of_env env =
427 List.map (fun (var, (ty, value)) -> (var, (ty, pp_value value))) env
429 (* prerr_endline ("pattern matching from 2 to 1 on term " ^ CicNotationPp.pp_term term); *)
431 | Ast.AttributedTerm (attrs, term') ->
432 Ast.AttributedTerm (attrs, pp_ast1 term')
434 (match (get_compiled21 ()) term with
435 | None -> pp_ast0 term pp_ast1
436 | Some (env, ctors, pid) ->
438 List.flatten (List.map CicNotationUtil.get_idrefs ctors)
442 Hashtbl.find level1_patterns21 pid
443 with Not_found -> assert false
445 instantiate21 idrefs (ast_env_of_env env) l1)
447 let load_patterns21 t =
448 set_compiled21 (lazy (Content2presMatcher.Matcher21.compiler t))
451 debug_print (lazy "pp_ast <-");
452 let ast' = pp_ast1 ast in
453 debug_print (lazy ("pp_ast -> " ^ CicNotationPp.pp_term ast'));
456 exception Pretty_printer_not_found
458 let fill_pos_info l1_pattern = l1_pattern
459 (* let rec aux toplevel pos =
466 | Ast.Variable _ as t -> add_pos_info pos t
469 aux true l1_pattern *)
471 let counter = ref ~-1
472 let reset () = counter := ~-1;;
478 let add_pretty_printer ~precedence ~associativity l2 l1 =
479 let id = fresh_id () in
480 let l1' = add_level_info precedence associativity (fill_pos_info l1) in
481 let l2' = CicNotationUtil.strip_attributes l2 in
482 Hashtbl.add level1_patterns21 id l1';
483 pattern21_matrix := (l2', id) :: !pattern21_matrix;
484 load_patterns21 !pattern21_matrix;
487 let remove_pretty_printer id =
489 Hashtbl.remove level1_patterns21 id;
490 with Not_found -> raise Pretty_printer_not_found);
491 pattern21_matrix := List.filter (fun (_, id') -> id <> id') !pattern21_matrix;
492 load_patterns21 !pattern21_matrix
494 (* presentation -> content *)
496 let unopt_names names env =
497 let rec aux acc = function
498 | (name, (ty, v)) :: tl when List.mem name names ->
500 | Env.OptType ty, Env.OptValue (Some v) ->
501 aux ((name, (ty, v)) :: acc) tl
503 | hd :: tl -> aux (hd :: acc) tl
508 let head_names names env =
509 let rec aux acc = function
510 | (name, (ty, v)) :: tl when List.mem name names ->
512 | Env.ListType ty, Env.ListValue (v :: _) ->
513 aux ((name, (ty, v)) :: acc) tl
515 | _ :: tl -> aux acc tl
516 (* base pattern may contain only meta names, thus we trash all others *)
521 let tail_names names env =
522 let rec aux acc = function
523 | (name, (ty, v)) :: tl when List.mem name names ->
525 | Env.ListType ty, Env.ListValue (_ :: vtl) ->
526 aux ((name, (Env.ListType ty, Env.ListValue vtl)) :: acc) tl
528 | binding :: tl -> aux (binding :: acc) tl
533 let instantiate_level2 env term =
534 let fresh_env = ref [] in
535 let lookup_fresh_name n =
537 List.assoc n !fresh_env
539 let new_name = CicNotationUtil.fresh_name () in
540 fresh_env := (n, new_name) :: !fresh_env;
543 let rec aux env term =
544 (* prerr_endline ("ENV " ^ CicNotationPp.pp_env env); *)
546 | Ast.AttributedTerm (_, term) -> aux env term
547 | Ast.Appl terms -> Ast.Appl (List.map (aux env) terms)
548 | Ast.Binder (binder, var, body) ->
549 Ast.Binder (binder, aux_capture_var env var, aux env body)
550 | Ast.Case (term, indty, outty_opt, patterns) ->
551 Ast.Case (aux env term, indty, aux_opt env outty_opt,
552 List.map (aux_branch env) patterns)
553 | Ast.LetIn (var, t1, t2) ->
554 Ast.LetIn (aux_capture_var env var, aux env t1, aux env t2)
555 | Ast.LetRec (kind, definitions, body) ->
556 Ast.LetRec (kind, List.map (aux_definition env) definitions,
558 | Ast.Uri (name, None) -> Ast.Uri (name, None)
559 | Ast.Uri (name, Some substs) ->
560 Ast.Uri (name, Some (aux_substs env substs))
561 | Ast.Ident (name, Some substs) ->
562 Ast.Ident (name, Some (aux_substs env substs))
563 | Ast.Meta (index, substs) -> Ast.Meta (index, aux_meta_substs env substs)
570 | Ast.UserInput -> term
572 | Ast.Magic magic -> aux_magic env magic
573 | Ast.Variable var -> aux_variable env var
576 and aux_opt env = function
577 | Some term -> Some (aux env term)
579 and aux_capture_var env (name, ty_opt) = (aux env name, aux_opt env ty_opt)
580 and aux_branch env (pattern, term) =
581 (aux_pattern env pattern, aux env term)
582 and aux_pattern env =
584 Ast.Pattern (head, hrefs, vars) ->
585 Ast.Pattern (head, hrefs, List.map (aux_capture_var env) vars)
586 | Ast.Wildcard -> Ast.Wildcard
587 and aux_definition env (params, var, term, i) =
588 (List.map (aux_capture_var env) params, aux_capture_var env var, aux env term, i)
589 and aux_substs env substs =
590 List.map (fun (name, term) -> (name, aux env term)) substs
591 and aux_meta_substs env meta_substs = List.map (aux_opt env) meta_substs
592 and aux_variable env = function
593 | Ast.NumVar name -> Ast.Num (Env.lookup_num env name, 0)
594 | Ast.IdentVar name -> Ast.Ident (Env.lookup_string env name, None)
595 | Ast.TermVar name -> Env.lookup_term env name
596 | Ast.FreshVar name -> Ast.Ident (lookup_fresh_name name, None)
597 | Ast.Ascription (term, name) -> assert false
598 and aux_magic env = function
599 | Ast.Default (some_pattern, none_pattern) ->
600 let some_pattern_names = CicNotationUtil.names_of_term some_pattern in
601 let none_pattern_names = CicNotationUtil.names_of_term none_pattern in
604 (fun name -> not (List.mem name none_pattern_names))
607 (match opt_names with
608 | [] -> assert false (* some pattern must contain at least 1 name *)
609 | (name :: _) as names ->
610 (match Env.lookup_value env name with
611 | Env.OptValue (Some _) ->
612 (* assumption: if "name" above is bound to Some _, then all
613 * names returned by "meta_names_of" are bound to Some _ as well
615 aux (unopt_names names env) some_pattern
616 | Env.OptValue None -> aux env none_pattern
618 prerr_endline (sprintf
619 "lookup of %s in env %s did not return an optional value"
620 name (CicNotationPp.pp_env env));
622 | Ast.Fold (`Left, base_pattern, names, rec_pattern) ->
623 let acc_name = List.hd names in (* names can't be empty, cfr. parser *)
625 List.filter ((<>) acc_name)
626 (CicNotationUtil.names_of_term rec_pattern)
628 (match meta_names with
629 | [] -> assert false (* as above *)
630 | (name :: _) as names ->
631 let rec instantiate_fold_left acc env' =
632 match Env.lookup_value env' name with
633 | Env.ListValue (_ :: _) ->
634 instantiate_fold_left
636 acc_name, (Env.TermType, Env.TermValue acc)
638 aux (acc_binding :: head_names names env') rec_pattern)
639 (tail_names names env')
640 | Env.ListValue [] -> acc
643 instantiate_fold_left (aux env base_pattern) env)
644 | Ast.Fold (`Right, base_pattern, names, rec_pattern) ->
645 let acc_name = List.hd names in (* names can't be empty, cfr. parser *)
647 List.filter ((<>) acc_name)
648 (CicNotationUtil.names_of_term rec_pattern)
650 (match meta_names with
651 | [] -> assert false (* as above *)
652 | (name :: _) as names ->
653 let rec instantiate_fold_right env' =
654 match Env.lookup_value env' name with
655 | Env.ListValue (_ :: _) ->
656 let acc = instantiate_fold_right (tail_names names env') in
658 acc_name, (Env.TermType, Env.TermValue acc)
660 aux (acc_binding :: head_names names env') rec_pattern
661 | Env.ListValue [] -> aux env base_pattern
664 instantiate_fold_right env)
665 | Ast.If (_, p_true, p_false) as t ->
666 aux env (CicNotationUtil.find_branch (Ast.Magic t))
667 | Ast.Fail -> assert false
674 let _ = load_patterns21 []