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 (head, href, vars) =
155 hbox true false (ident_w_href href head :: List.map aux_var vars)
163 mk_case_pattern lhs; builtin_symbol "\\Rightarrow" ];
164 break; top_pos (k rhs) ]))
168 let rec aux_patterns = function
174 last; builtin_symbol "]" ] ]
176 [ break; hbox false false [ builtin_symbol "|"; hd ] ]
181 [ hbox false false [ builtin_symbol "["; builtin_symbol "]" ] ]
184 builtin_symbol "["; one; builtin_symbol "]" ] ]
186 hbox false false [ builtin_symbol "["; hd ]
189 add_level_info Ast.simple_prec Ast.simple_assoc
191 hvbox false false ([match_box]); break;
192 hbox false false [ hvbox false false patterns'' ] ])
193 | Ast.Cast (bo, ty) ->
194 add_level_info Ast.simple_prec Ast.simple_assoc
196 builtin_symbol "("; top_pos (k bo); break; builtin_symbol ":";
197 top_pos (k ty); builtin_symbol ")"])
198 | Ast.LetIn (var, s, t) ->
199 add_level_info Ast.let_in_prec Ast.let_in_assoc
204 aux_var var; builtin_symbol "\\def"; break; top_pos (k s) ];
205 break; keyword "in" ];
208 | Ast.LetRec (rec_kind, funs, where) ->
210 match rec_kind with `Inductive -> "rec" | `CoInductive -> "corec"
212 let mk_fun (args, (name,ty), body, _) =
213 List.map aux_var args ,k name, HExtlib.map_option k ty, k body in
214 let mk_funs = List.map mk_fun in
215 let fst_fun, tl_funs =
216 match mk_funs funs with hd :: tl -> hd, tl | [] -> assert false
219 let (params, name, ty, body) = fst_fun in
227 (match ty with None -> [] | Some ty -> [builtin_symbol ":"; ty]) @
228 [ builtin_symbol "\\def";
234 (fun (params, name, ty, body) ->
242 | Some ty -> [builtin_symbol ":"; ty]) @
243 [ builtin_symbol "\\def"; break; body ])])
246 add_level_info Ast.let_in_prec Ast.let_in_assoc
248 (fst_row :: List.flatten tl_rows
249 @ [ break; keyword "in"; break; k where ])))
250 | Ast.Implicit -> builtin_symbol "?"
252 let local_context l =
253 List.map (function None -> None | Some t -> Some (k t)) l
255 Ast.Meta(n, local_context l)
256 | Ast.Sort sort -> aux_sort sort
259 | Ast.Ident (_, None) | Ast.Ident (_, Some [])
260 | Ast.Uri (_, None) | Ast.Uri (_, Some [])
262 | Ast.UserInput as leaf -> leaf
263 | t -> CicNotationUtil.visit_ast ~special_k k t
264 and aux_sort sort_kind =
265 add_xml_attrs (RenderingAttrs.keyword_attributes `MathML)
266 (Ast.Ident (string_of_sort_kind sort_kind, None))
267 and aux_ty = function
268 | None -> builtin_symbol "?"
270 and aux_var = function
273 builtin_symbol "("; name; builtin_symbol ":"; break; k ty;
276 and special_k = function
277 | Ast.AttributedTerm (attrs, t) -> Ast.AttributedTerm (attrs, k t)
279 prerr_endline ("unexpected special: " ^ CicNotationPp.pp_term t);
284 (* persistent state *)
286 let level1_patterns21 = Hashtbl.create 211
288 let compiled21 = ref None
290 let pattern21_matrix = ref []
292 let get_compiled21 () =
293 match !compiled21 with
294 | None -> assert false
295 | Some f -> Lazy.force f
297 let set_compiled21 f = compiled21 := Some f
300 List.fold_right (fun idref t -> Ast.AttributedTerm (`IdRef idref, t))
302 let instantiate21 idrefs env l1 =
303 let rec subst_singleton pos env =
305 Ast.AttributedTerm (attr, t) ->
306 Ast.AttributedTerm (attr, subst_singleton pos env t)
307 | t -> CicNotationUtil.group (subst pos env t)
308 and subst pos env = function
309 | Ast.AttributedTerm (attr, t) ->
310 (* prerr_endline ("loosing attribute " ^ CicNotationPp.pp_attribute attr); *)
312 | Ast.Variable var ->
313 let name, expected_ty = CicNotationEnv.declaration_of_var var in
318 prerr_endline ("name " ^ name ^ " not found in environment");
321 assert (CicNotationEnv.well_typed ty value); (* INVARIANT *)
322 (* following assertion should be a conditional that makes this
323 * instantiation fail *)
324 assert (CicNotationEnv.well_typed expected_ty value);
325 [ add_pos_info pos (CicNotationEnv.term_of_value value) ]
326 | Ast.Magic m -> subst_magic pos env m
327 | Ast.Literal l as t ->
328 let t = add_idrefs idrefs t in
330 | `Keyword k -> [ add_keyword_attrs t ]
332 | Ast.Layout l -> [ Ast.Layout (subst_layout pos env l) ]
333 | t -> [ CicNotationUtil.visit_ast (subst_singleton pos env) t ]
334 and subst_magic pos env = function
335 | Ast.List0 (p, sep_opt)
336 | Ast.List1 (p, sep_opt) ->
337 let rec_decls = CicNotationEnv.declarations_of_term p in
339 List.map (fun (n, _) -> CicNotationEnv.lookup_list env n) rec_decls
341 let values = CicNotationUtil.ncombine rec_values in
345 | Some l -> [ Ast.Literal l ]
347 let rec instantiate_list acc = function
350 let env = CicNotationEnv.combine rec_decls value_set in
351 instantiate_list (CicNotationUtil.group (subst pos env p) :: acc)
354 let env = CicNotationEnv.combine rec_decls value_set in
355 let terms = subst pos env p in
356 instantiate_list (CicNotationUtil.group (terms @ sep) :: acc) tl
358 instantiate_list [] values
360 let opt_decls = CicNotationEnv.declarations_of_term p in
362 let rec build_env = function
364 | (name, ty) :: tl ->
365 (* assumption: if one of the value is None then all are *)
366 (match CicNotationEnv.lookup_opt env name with
368 | Some v -> (name, (ty, v)) :: build_env tl)
370 try build_env opt_decls with Exit -> []
375 | _ -> subst pos env p
377 | _ -> assert false (* impossible *)
378 and subst_layout pos env = function
379 | Ast.Box (kind, tl) ->
380 let tl' = subst_children pos env tl in
381 Ast.Box (kind, List.concat tl')
382 | l -> CicNotationUtil.visit_layout (subst_singleton pos env) l
383 and subst_children pos env =
391 (* | `None -> assert false *)
394 [ subst pos' env child ]
400 (* | `None -> assert false *)
403 (subst pos env hd) :: subst_children pos' env tl
405 subst_singleton `Left env l1
407 let rec pp_ast1 term =
408 let rec pp_value = function
409 | CicNotationEnv.NumValue _ as v -> v
410 | CicNotationEnv.StringValue _ as v -> v
411 (* | CicNotationEnv.TermValue t when t == term -> CicNotationEnv.TermValue (pp_ast0 t pp_ast1) *)
412 | CicNotationEnv.TermValue t -> CicNotationEnv.TermValue (pp_ast1 t)
413 | CicNotationEnv.OptValue None as v -> v
414 | CicNotationEnv.OptValue (Some v) ->
415 CicNotationEnv.OptValue (Some (pp_value v))
416 | CicNotationEnv.ListValue vl ->
417 CicNotationEnv.ListValue (List.map pp_value vl)
419 let ast_env_of_env env =
420 List.map (fun (var, (ty, value)) -> (var, (ty, pp_value value))) env
422 (* prerr_endline ("pattern matching from 2 to 1 on term " ^ CicNotationPp.pp_term term); *)
424 | Ast.AttributedTerm (attrs, term') ->
425 Ast.AttributedTerm (attrs, pp_ast1 term')
427 (match (get_compiled21 ()) term with
428 | None -> pp_ast0 term pp_ast1
429 | Some (env, ctors, pid) ->
431 List.flatten (List.map CicNotationUtil.get_idrefs ctors)
435 Hashtbl.find level1_patterns21 pid
436 with Not_found -> assert false
438 instantiate21 idrefs (ast_env_of_env env) l1)
440 let load_patterns21 t =
441 set_compiled21 (lazy (Content2presMatcher.Matcher21.compiler t))
444 debug_print (lazy "pp_ast <-");
445 let ast' = pp_ast1 ast in
446 debug_print (lazy ("pp_ast -> " ^ CicNotationPp.pp_term ast'));
449 exception Pretty_printer_not_found
451 let fill_pos_info l1_pattern = l1_pattern
452 (* let rec aux toplevel pos =
459 | Ast.Variable _ as t -> add_pos_info pos t
462 aux true l1_pattern *)
465 let counter = ref ~-1 in
470 let add_pretty_printer ~precedence ~associativity l2 l1 =
471 let id = fresh_id () in
472 let l1' = add_level_info precedence associativity (fill_pos_info l1) in
473 let l2' = CicNotationUtil.strip_attributes l2 in
474 Hashtbl.add level1_patterns21 id l1';
475 pattern21_matrix := (l2', id) :: !pattern21_matrix;
476 load_patterns21 !pattern21_matrix;
479 let remove_pretty_printer id =
481 Hashtbl.remove level1_patterns21 id;
482 with Not_found -> raise Pretty_printer_not_found);
483 pattern21_matrix := List.filter (fun (_, id') -> id <> id') !pattern21_matrix;
484 load_patterns21 !pattern21_matrix
486 (* presentation -> content *)
488 let unopt_names names env =
489 let rec aux acc = function
490 | (name, (ty, v)) :: tl when List.mem name names ->
492 | Env.OptType ty, Env.OptValue (Some v) ->
493 aux ((name, (ty, v)) :: acc) tl
495 | hd :: tl -> aux (hd :: acc) tl
500 let head_names names env =
501 let rec aux acc = function
502 | (name, (ty, v)) :: tl when List.mem name names ->
504 | Env.ListType ty, Env.ListValue (v :: _) ->
505 aux ((name, (ty, v)) :: acc) tl
507 | _ :: tl -> aux acc tl
508 (* base pattern may contain only meta names, thus we trash all others *)
513 let tail_names names env =
514 let rec aux acc = function
515 | (name, (ty, v)) :: tl when List.mem name names ->
517 | Env.ListType ty, Env.ListValue (_ :: vtl) ->
518 aux ((name, (Env.ListType ty, Env.ListValue vtl)) :: acc) tl
520 | binding :: tl -> aux (binding :: acc) tl
525 let instantiate_level2 env term =
526 let fresh_env = ref [] in
527 let lookup_fresh_name n =
529 List.assoc n !fresh_env
531 let new_name = CicNotationUtil.fresh_name () in
532 fresh_env := (n, new_name) :: !fresh_env;
535 let rec aux env term =
536 (* prerr_endline ("ENV " ^ CicNotationPp.pp_env env); *)
538 | Ast.AttributedTerm (_, term) -> aux env term
539 | Ast.Appl terms -> Ast.Appl (List.map (aux env) terms)
540 | Ast.Binder (binder, var, body) ->
541 Ast.Binder (binder, aux_capture_var env var, aux env body)
542 | Ast.Case (term, indty, outty_opt, patterns) ->
543 Ast.Case (aux env term, indty, aux_opt env outty_opt,
544 List.map (aux_branch env) patterns)
545 | Ast.LetIn (var, t1, t2) ->
546 Ast.LetIn (aux_capture_var env var, aux env t1, aux env t2)
547 | Ast.LetRec (kind, definitions, body) ->
548 Ast.LetRec (kind, List.map (aux_definition env) definitions,
550 | Ast.Uri (name, None) -> Ast.Uri (name, None)
551 | Ast.Uri (name, Some substs) ->
552 Ast.Uri (name, Some (aux_substs env substs))
553 | Ast.Ident (name, Some substs) ->
554 Ast.Ident (name, Some (aux_substs env substs))
555 | Ast.Meta (index, substs) -> Ast.Meta (index, aux_meta_substs env substs)
562 | Ast.UserInput -> term
564 | Ast.Magic magic -> aux_magic env magic
565 | Ast.Variable var -> aux_variable env var
568 and aux_opt env = function
569 | Some term -> Some (aux env term)
571 and aux_capture_var env (name, ty_opt) = (aux env name, aux_opt env ty_opt)
572 and aux_branch env (pattern, term) =
573 (aux_pattern env pattern, aux env term)
574 and aux_pattern env (head, hrefs, vars) =
575 (head, hrefs, List.map (aux_capture_var env) vars)
576 and aux_definition env (params, var, term, i) =
577 (List.map (aux_capture_var env) params, aux_capture_var env var, aux env term, i)
578 and aux_substs env substs =
579 List.map (fun (name, term) -> (name, aux env term)) substs
580 and aux_meta_substs env meta_substs = List.map (aux_opt env) meta_substs
581 and aux_variable env = function
582 | Ast.NumVar name -> Ast.Num (Env.lookup_num env name, 0)
583 | Ast.IdentVar name -> Ast.Ident (Env.lookup_string env name, None)
584 | Ast.TermVar name -> Env.lookup_term env name
585 | Ast.FreshVar name -> Ast.Ident (lookup_fresh_name name, None)
586 | Ast.Ascription (term, name) -> assert false
587 and aux_magic env = function
588 | Ast.Default (some_pattern, none_pattern) ->
589 let some_pattern_names = CicNotationUtil.names_of_term some_pattern in
590 let none_pattern_names = CicNotationUtil.names_of_term none_pattern in
593 (fun name -> not (List.mem name none_pattern_names))
596 (match opt_names with
597 | [] -> assert false (* some pattern must contain at least 1 name *)
598 | (name :: _) as names ->
599 (match Env.lookup_value env name with
600 | Env.OptValue (Some _) ->
601 (* assumption: if "name" above is bound to Some _, then all
602 * names returned by "meta_names_of" are bound to Some _ as well
604 aux (unopt_names names env) some_pattern
605 | Env.OptValue None -> aux env none_pattern
607 prerr_endline (sprintf
608 "lookup of %s in env %s did not return an optional value"
609 name (CicNotationPp.pp_env env));
611 | Ast.Fold (`Left, base_pattern, names, rec_pattern) ->
612 let acc_name = List.hd names in (* names can't be empty, cfr. parser *)
614 List.filter ((<>) acc_name)
615 (CicNotationUtil.names_of_term rec_pattern)
617 (match meta_names with
618 | [] -> assert false (* as above *)
619 | (name :: _) as names ->
620 let rec instantiate_fold_left acc env' =
621 match Env.lookup_value env' name with
622 | Env.ListValue (_ :: _) ->
623 instantiate_fold_left
625 acc_name, (Env.TermType, Env.TermValue acc)
627 aux (acc_binding :: head_names names env') rec_pattern)
628 (tail_names names env')
629 | Env.ListValue [] -> acc
632 instantiate_fold_left (aux env base_pattern) env)
633 | Ast.Fold (`Right, base_pattern, names, rec_pattern) ->
634 let acc_name = List.hd names in (* names can't be empty, cfr. parser *)
636 List.filter ((<>) acc_name)
637 (CicNotationUtil.names_of_term rec_pattern)
639 (match meta_names with
640 | [] -> assert false (* as above *)
641 | (name :: _) as names ->
642 let rec instantiate_fold_right env' =
643 match Env.lookup_value env' name with
644 | Env.ListValue (_ :: _) ->
645 let acc = instantiate_fold_right (tail_names names env') in
647 acc_name, (Env.TermType, Env.TermValue acc)
649 aux (acc_binding :: head_names names env') rec_pattern
650 | Env.ListValue [] -> aux env base_pattern
653 instantiate_fold_right env)
654 | Ast.If (_, p_true, p_false) as t ->
655 aux env (CicNotationUtil.find_branch (Ast.Magic t))
656 | Ast.Fail -> assert false
663 let _ = load_patterns21 []