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/
28 module Ast = CicNotationPt
29 module Env = CicNotationEnv
32 let debug_print s = if debug then prerr_endline (Lazy.force s) else ()
35 type pretty_printer_id = pattern_id
37 let resolve_binder = function
38 | `Lambda -> "\\lambda"
40 | `Forall -> "\\forall"
41 | `Exists -> "\\exists"
43 let add_level_info prec assoc t = Ast.AttributedTerm (`Level (prec, assoc), t)
44 let add_pos_info pos t = Ast.AttributedTerm (`ChildPos pos, t)
45 let left_pos = add_pos_info `Left
46 let right_pos = add_pos_info `Right
47 let inner_pos = add_pos_info `Inner
49 let rec top_pos t = add_level_info ~-1 Gramext.NonA (inner_pos t)
51 | Ast.AttributedTerm (`Level _, t) ->
52 add_level_info ~-1 Gramext.NonA (inner_pos t)
53 | Ast.AttributedTerm (attr, t) -> Ast.AttributedTerm (attr, top_pos t)
54 | t -> add_level_info ~-1 Gramext.NonA (inner_pos t) *)
56 let rec remove_level_info =
58 | Ast.AttributedTerm (`Level _, t) -> remove_level_info t
59 | Ast.AttributedTerm (a, t) -> Ast.AttributedTerm (a, remove_level_info t)
62 let add_xml_attrs attrs t =
63 if attrs = [] then t else Ast.AttributedTerm (`XmlAttrs attrs, t)
65 let add_keyword_attrs =
66 add_xml_attrs (RenderingAttrs.keyword_attributes `MathML)
68 let box kind spacing indent content =
69 Ast.Layout (Ast.Box ((kind, spacing, indent), content))
73 let hvbox = box Ast.HV
74 let hovbox = box Ast.HOV
75 let break = Ast.Layout Ast.Break
76 let builtin_symbol s = Ast.Literal (`Symbol s)
77 let keyword k = add_keyword_attrs (Ast.Literal (`Keyword k))
80 add_xml_attrs (RenderingAttrs.number_attributes `MathML)
81 (Ast.Literal (`Number s))
84 add_xml_attrs (RenderingAttrs.ident_attributes `MathML) (Ast.Ident (i, None))
86 let ident_w_href href i =
90 let href = UriManager.string_of_uri href in
91 add_xml_attrs [Some "xlink", "href", href] (ident i)
94 add_xml_attrs (RenderingAttrs.builtin_symbol_attributes `MathML)
97 let string_of_sort_kind = function
107 let rec aux_args pos =
112 if pos = `Left then [ left_pos last ] else [ right_pos last ]
114 (add_pos_info pos (k hd)) :: aux_args `Inner tl
116 add_level_info Ast.apply_prec Ast.apply_assoc
117 (hovbox true true (CicNotationUtil.dress break (aux_args `Left ts)))
118 | Ast.Binder (binder_kind, (id, ty), body) ->
119 add_level_info Ast.binder_prec Ast.binder_assoc
121 [ binder_symbol (resolve_binder binder_kind);
122 k id; builtin_symbol ":"; aux_ty ty; break;
123 builtin_symbol "."; right_pos (k body) ])
124 | Ast.Case (what, indty_opt, outty_opt, patterns) ->
129 [ keyword "return"; break; remove_level_info (k outty)]
134 | Some (indty, href) -> [ keyword "in"; break; ident_w_href href indty ]
139 hvbox false true [ keyword "match"; break; top_pos (k what) ];
141 hvbox false true indty_box;
143 hvbox false true outty_box
149 let mk_case_pattern (head, href, vars) =
150 hbox true false (ident_w_href href head :: List.map aux_var vars)
158 mk_case_pattern lhs; builtin_symbol "\\Rightarrow" ];
159 break; top_pos (k rhs) ]))
163 let rec aux_patterns = function
169 last; builtin_symbol "]" ] ]
171 [ break; hbox false false [ builtin_symbol "|"; hd ] ]
176 [ hbox false false [ builtin_symbol "["; builtin_symbol "]" ] ]
179 builtin_symbol "["; one; builtin_symbol "]" ] ]
181 hbox false false [ builtin_symbol "["; hd ]
184 add_level_info Ast.simple_prec Ast.simple_assoc
186 hvbox false false ([match_box]); break;
187 hbox false false [ hvbox false false patterns'' ] ])
188 | Ast.Cast (bo, ty) ->
189 add_level_info Ast.simple_prec Ast.simple_assoc
191 builtin_symbol "("; top_pos (k bo); break; builtin_symbol ":";
192 top_pos (k ty); builtin_symbol ")"])
193 | Ast.LetIn (var, s, t) ->
194 add_level_info Ast.let_in_prec Ast.let_in_assoc
199 aux_var var; builtin_symbol "\\def"; break; top_pos (k s) ];
200 break; keyword "in" ];
203 | Ast.LetRec (rec_kind, funs, where) ->
205 match rec_kind with `Inductive -> "rec" | `CoInductive -> "corec"
207 let mk_fun (var, body, _) = aux_var var, k body in
208 let mk_funs = List.map mk_fun in
209 let fst_fun, tl_funs =
210 match mk_funs funs with hd :: tl -> hd, tl | [] -> assert false
213 let (name, body) = fst_fun in
215 keyword "let"; keyword rec_op; name; builtin_symbol "\\def"; break;
223 keyword "and"; name; builtin_symbol "\\def"; break; body ] ])
226 add_level_info Ast.let_in_prec Ast.let_in_assoc
228 (fst_row :: List.flatten tl_rows
229 @ [ break; keyword "in"; break; k where ])))
230 | Ast.Implicit -> builtin_symbol "?"
232 let local_context l =
233 CicNotationUtil.dress (builtin_symbol ";")
234 (List.map (function None -> builtin_symbol "_" | Some t -> k t) l)
237 ([ builtin_symbol "?"; number (string_of_int n) ]
238 @ (if l <> [] then local_context l else []))
239 | Ast.Sort sort -> aux_sort sort
242 | Ast.Ident (_, None) | Ast.Ident (_, Some [])
243 | Ast.Uri (_, None) | Ast.Uri (_, Some [])
245 | Ast.UserInput as leaf -> leaf
246 | t -> CicNotationUtil.visit_ast ~special_k k t
247 and aux_sort sort_kind =
248 add_xml_attrs (RenderingAttrs.keyword_attributes `MathML)
249 (Ast.Ident (string_of_sort_kind sort_kind, None))
250 and aux_ty = function
251 | None -> builtin_symbol "?"
253 and aux_var = function
256 builtin_symbol "("; name; builtin_symbol ":"; break; k ty;
259 and special_k = function
260 | Ast.AttributedTerm (attrs, t) -> Ast.AttributedTerm (attrs, k t)
262 prerr_endline ("unexpected special: " ^ CicNotationPp.pp_term t);
267 (* persistent state *)
269 let level1_patterns21 = Hashtbl.create 211
271 let compiled21 = ref None
273 let pattern21_matrix = ref []
275 let get_compiled21 () =
276 match !compiled21 with
277 | None -> assert false
278 | Some f -> Lazy.force f
280 let set_compiled21 f = compiled21 := Some f
283 List.fold_right (fun idref t -> Ast.AttributedTerm (`IdRef idref, t))
285 let instantiate21 idrefs env l1 =
286 let rec subst_singleton pos env =
288 Ast.AttributedTerm (attr, t) ->
289 Ast.AttributedTerm (attr, subst_singleton pos env t)
290 | t -> CicNotationUtil.group (subst pos env t)
291 and subst pos env = function
292 | Ast.AttributedTerm (attr, t) ->
293 (* prerr_endline ("loosing attribute " ^ CicNotationPp.pp_attribute attr); *)
295 | Ast.Variable var ->
296 let name, expected_ty = CicNotationEnv.declaration_of_var var in
301 prerr_endline ("name " ^ name ^ " not found in environment");
304 assert (CicNotationEnv.well_typed ty value); (* INVARIANT *)
305 (* following assertion should be a conditional that makes this
306 * instantiation fail *)
307 assert (CicNotationEnv.well_typed expected_ty value);
308 [ add_pos_info pos (CicNotationEnv.term_of_value value) ]
309 | Ast.Magic m -> subst_magic pos env m
310 | Ast.Literal l as t ->
311 let t = add_idrefs idrefs t in
313 | `Keyword k -> [ add_keyword_attrs t ]
315 | Ast.Layout l -> [ Ast.Layout (subst_layout pos env l) ]
316 | t -> [ CicNotationUtil.visit_ast (subst_singleton pos env) t ]
317 and subst_magic pos env = function
318 | Ast.List0 (p, sep_opt)
319 | Ast.List1 (p, sep_opt) ->
320 let rec_decls = CicNotationEnv.declarations_of_term p in
322 List.map (fun (n, _) -> CicNotationEnv.lookup_list env n) rec_decls
324 let values = CicNotationUtil.ncombine rec_values in
328 | Some l -> [ Ast.Literal l ]
330 let rec instantiate_list acc = function
333 let env = CicNotationEnv.combine rec_decls value_set in
334 instantiate_list (CicNotationUtil.group (subst pos env p) :: acc)
337 let env = CicNotationEnv.combine rec_decls value_set in
338 let terms = subst pos env p in
339 instantiate_list (CicNotationUtil.group (terms @ sep) :: acc) tl
341 instantiate_list [] values
343 let opt_decls = CicNotationEnv.declarations_of_term p in
345 let rec build_env = function
347 | (name, ty) :: tl ->
348 (* assumption: if one of the value is None then all are *)
349 (match CicNotationEnv.lookup_opt env name with
351 | Some v -> (name, (ty, v)) :: build_env tl)
353 try build_env opt_decls with Exit -> []
358 | _ -> subst pos env p
360 | _ -> assert false (* impossible *)
361 and subst_layout pos env = function
362 | Ast.Box (kind, tl) ->
363 let tl' = subst_children pos env tl in
364 Ast.Box (kind, List.concat tl')
365 | l -> CicNotationUtil.visit_layout (subst_singleton pos env) l
366 and subst_children pos env =
374 (* | `None -> assert false *)
377 [ subst pos' env child ]
383 (* | `None -> assert false *)
386 (subst pos env hd) :: subst_children pos' env tl
388 subst_singleton `Left env l1
390 let rec pp_ast1 term =
391 let rec pp_value = function
392 | CicNotationEnv.NumValue _ as v -> v
393 | CicNotationEnv.StringValue _ as v -> v
394 (* | CicNotationEnv.TermValue t when t == term -> CicNotationEnv.TermValue (pp_ast0 t pp_ast1) *)
395 | CicNotationEnv.TermValue t -> CicNotationEnv.TermValue (pp_ast1 t)
396 | CicNotationEnv.OptValue None as v -> v
397 | CicNotationEnv.OptValue (Some v) ->
398 CicNotationEnv.OptValue (Some (pp_value v))
399 | CicNotationEnv.ListValue vl ->
400 CicNotationEnv.ListValue (List.map pp_value vl)
402 let ast_env_of_env env =
403 List.map (fun (var, (ty, value)) -> (var, (ty, pp_value value))) env
405 (* prerr_endline ("pattern matching from 2 to 1 on term " ^ CicNotationPp.pp_term term); *)
407 | Ast.AttributedTerm (attrs, term') ->
408 Ast.AttributedTerm (attrs, pp_ast1 term')
410 (match (get_compiled21 ()) term with
411 | None -> pp_ast0 term pp_ast1
412 | Some (env, ctors, pid) ->
414 List.flatten (List.map CicNotationUtil.get_idrefs ctors)
418 Hashtbl.find level1_patterns21 pid
419 with Not_found -> assert false
421 instantiate21 idrefs (ast_env_of_env env) l1)
423 let load_patterns21 t =
424 set_compiled21 (lazy (Content2presMatcher.Matcher21.compiler t))
427 debug_print (lazy "pp_ast <-");
428 let ast' = pp_ast1 ast in
429 debug_print (lazy ("pp_ast -> " ^ CicNotationPp.pp_term ast'));
432 exception Pretty_printer_not_found
434 let fill_pos_info l1_pattern = l1_pattern
435 (* let rec aux toplevel pos =
442 | Ast.Variable _ as t -> add_pos_info pos t
445 aux true l1_pattern *)
448 let counter = ref ~-1 in
453 let add_pretty_printer ~precedence ~associativity l2 l1 =
454 let id = fresh_id () in
455 let l1' = add_level_info precedence associativity (fill_pos_info l1) in
456 let l2' = CicNotationUtil.strip_attributes l2 in
457 Hashtbl.add level1_patterns21 id l1';
458 pattern21_matrix := (l2', id) :: !pattern21_matrix;
459 load_patterns21 !pattern21_matrix;
462 let remove_pretty_printer id =
464 Hashtbl.remove level1_patterns21 id;
465 with Not_found -> raise Pretty_printer_not_found);
466 pattern21_matrix := List.filter (fun (_, id') -> id <> id') !pattern21_matrix;
467 load_patterns21 !pattern21_matrix
469 (* presentation -> content *)
471 let unopt_names names env =
472 let rec aux acc = function
473 | (name, (ty, v)) :: tl when List.mem name names ->
475 | Env.OptType ty, Env.OptValue (Some v) ->
476 aux ((name, (ty, v)) :: acc) tl
478 | hd :: tl -> aux (hd :: acc) tl
483 let head_names names env =
484 let rec aux acc = function
485 | (name, (ty, v)) :: tl when List.mem name names ->
487 | Env.ListType ty, Env.ListValue (v :: _) ->
488 aux ((name, (ty, v)) :: acc) tl
490 | _ :: tl -> aux acc tl
491 (* base pattern may contain only meta names, thus we trash all others *)
496 let tail_names names env =
497 let rec aux acc = function
498 | (name, (ty, v)) :: tl when List.mem name names ->
500 | Env.ListType ty, Env.ListValue (_ :: vtl) ->
501 aux ((name, (Env.ListType ty, Env.ListValue vtl)) :: acc) tl
503 | binding :: tl -> aux (binding :: acc) tl
508 let instantiate_level2 env term =
509 let fresh_env = ref [] in
510 let lookup_fresh_name n =
512 List.assoc n !fresh_env
514 let new_name = CicNotationUtil.fresh_name () in
515 fresh_env := (n, new_name) :: !fresh_env;
518 let rec aux env term =
519 (* prerr_endline ("ENV " ^ CicNotationPp.pp_env env); *)
521 | Ast.AttributedTerm (_, term) -> aux env term
522 | Ast.Appl terms -> Ast.Appl (List.map (aux env) terms)
523 | Ast.Binder (binder, var, body) ->
524 Ast.Binder (binder, aux_capture_var env var, aux env body)
525 | Ast.Case (term, indty, outty_opt, patterns) ->
526 Ast.Case (aux env term, indty, aux_opt env outty_opt,
527 List.map (aux_branch env) patterns)
528 | Ast.LetIn (var, t1, t2) ->
529 Ast.LetIn (aux_capture_var env var, aux env t1, aux env t2)
530 | Ast.LetRec (kind, definitions, body) ->
531 Ast.LetRec (kind, List.map (aux_definition env) definitions,
533 | Ast.Uri (name, None) -> Ast.Uri (name, None)
534 | Ast.Uri (name, Some substs) ->
535 Ast.Uri (name, Some (aux_substs env substs))
536 | Ast.Ident (name, Some substs) ->
537 Ast.Ident (name, Some (aux_substs env substs))
538 | Ast.Meta (index, substs) -> Ast.Meta (index, aux_meta_substs env substs)
545 | Ast.UserInput -> term
547 | Ast.Magic magic -> aux_magic env magic
548 | Ast.Variable var -> aux_variable env var
551 and aux_opt env = function
552 | Some term -> Some (aux env term)
554 and aux_capture_var env (name, ty_opt) = (aux env name, aux_opt env ty_opt)
555 and aux_branch env (pattern, term) =
556 (aux_pattern env pattern, aux env term)
557 and aux_pattern env (head, hrefs, vars) =
558 (head, hrefs, List.map (aux_capture_var env) vars)
559 and aux_definition env (var, term, i) =
560 (aux_capture_var env var, aux env term, i)
561 and aux_substs env substs =
562 List.map (fun (name, term) -> (name, aux env term)) substs
563 and aux_meta_substs env meta_substs = List.map (aux_opt env) meta_substs
564 and aux_variable env = function
565 | Ast.NumVar name -> Ast.Num (Env.lookup_num env name, 0)
566 | Ast.IdentVar name -> Ast.Ident (Env.lookup_string env name, None)
567 | Ast.TermVar name -> Env.lookup_term env name
568 | Ast.FreshVar name -> Ast.Ident (lookup_fresh_name name, None)
569 | Ast.Ascription (term, name) -> assert false
570 and aux_magic env = function
571 | Ast.Default (some_pattern, none_pattern) ->
572 let some_pattern_names = CicNotationUtil.names_of_term some_pattern in
573 let none_pattern_names = CicNotationUtil.names_of_term none_pattern in
576 (fun name -> not (List.mem name none_pattern_names))
579 (match opt_names with
580 | [] -> assert false (* some pattern must contain at least 1 name *)
581 | (name :: _) as names ->
582 (match Env.lookup_value env name with
583 | Env.OptValue (Some _) ->
584 (* assumption: if "name" above is bound to Some _, then all
585 * names returned by "meta_names_of" are bound to Some _ as well
587 aux (unopt_names names env) some_pattern
588 | Env.OptValue None -> aux env none_pattern
590 prerr_endline (sprintf
591 "lookup of %s in env %s did not return an optional value"
592 name (CicNotationPp.pp_env env));
594 | Ast.Fold (`Left, base_pattern, names, rec_pattern) ->
595 let acc_name = List.hd names in (* names can't be empty, cfr. parser *)
597 List.filter ((<>) acc_name)
598 (CicNotationUtil.names_of_term rec_pattern)
600 (match meta_names with
601 | [] -> assert false (* as above *)
602 | (name :: _) as names ->
603 let rec instantiate_fold_left acc env' =
604 match Env.lookup_value env' name with
605 | Env.ListValue (_ :: _) ->
606 instantiate_fold_left
608 acc_name, (Env.TermType, Env.TermValue acc)
610 aux (acc_binding :: head_names names env') rec_pattern)
611 (tail_names names env')
612 | Env.ListValue [] -> acc
615 instantiate_fold_left (aux env base_pattern) env)
616 | Ast.Fold (`Right, base_pattern, names, rec_pattern) ->
617 let acc_name = List.hd names in (* names can't be empty, cfr. parser *)
619 List.filter ((<>) acc_name)
620 (CicNotationUtil.names_of_term rec_pattern)
622 (match meta_names with
623 | [] -> assert false (* as above *)
624 | (name :: _) as names ->
625 let rec instantiate_fold_right env' =
626 match Env.lookup_value env' name with
627 | Env.ListValue (_ :: _) ->
628 let acc = instantiate_fold_right (tail_names names env') in
630 acc_name, (Env.TermType, Env.TermValue acc)
632 aux (acc_binding :: head_names names env') rec_pattern
633 | Env.ListValue [] -> aux env base_pattern
636 instantiate_fold_right env)
637 | Ast.If (_, p_true, p_false) as t ->
638 aux env (CicNotationUtil.find_branch (Ast.Magic t))
639 | Ast.Fail -> assert false
646 let _ = load_patterns21 []