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 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 = UriManager.string_of_uri href in
85 add_xml_attrs [Some "xlink", "href", href] (ident i)
88 add_xml_attrs (RenderingAttrs.builtin_symbol_attributes `MathML)
91 let string_of_sort_kind = function
101 let rec aux_args level =
105 [ Ast.AttributedTerm (`Level level,k last) ]
107 (Ast.AttributedTerm (`Level level, k hd)) :: aux_args 71 tl
109 add_level_info Ast.apply_prec
110 (hovbox true true (CicNotationUtil.dress break (aux_args 70 ts)))
111 | Ast.Binder (binder_kind, (id, ty), body) ->
112 add_level_info Ast.binder_prec
114 [ binder_symbol (resolve_binder binder_kind);
115 k id; builtin_symbol ":"; aux_ty ty; break;
116 builtin_symbol "."; k body ])
117 | Ast.Case (what, indty_opt, outty_opt, patterns) ->
122 [ space; keyword "return"; space; break; remove_level_info (k outty)]
127 | Some (indty, href) -> [ space; keyword "in"; space; break; ident_w_href href indty ]
132 hvbox false true [keyword "match"; space; break; top_pos (k what)];
134 hvbox false true indty_box;
136 hvbox false true outty_box
144 let mk_case_pattern =
146 Ast.Pattern (head, href, vars) ->
147 hbox true false (ident_w_href href head :: List.map aux_var vars)
148 | Ast.Wildcard -> builtin_symbol "_"
156 mk_case_pattern lhs; builtin_symbol "\\Rightarrow" ];
157 break; top_pos (k rhs) ]))
161 let rec aux_patterns = function
167 last; builtin_symbol "]" ] ]
169 [ break; hbox false false [ builtin_symbol "|"; hd ] ]
174 [ hbox false false [ builtin_symbol "["; builtin_symbol "]" ] ]
177 builtin_symbol "["; one; builtin_symbol "]" ] ]
179 hbox false false [ builtin_symbol "["; hd ]
182 add_level_info Ast.simple_prec
184 hvbox false false ([match_box]); break;
185 hbox false false [ hvbox false false patterns'' ] ])
186 | Ast.Cast (bo, ty) ->
187 add_level_info Ast.simple_prec
189 builtin_symbol "("; top_pos (k bo); break; builtin_symbol ":";
190 top_pos (k ty); builtin_symbol ")"])
191 | Ast.LetIn (var, s, t) ->
192 add_level_info Ast.let_in_prec
195 keyword "let"; space;
198 builtin_symbol "\\def"; break; top_pos (k s) ];
199 break; space; keyword "in" ];
202 | Ast.LetRec (rec_kind, funs, where) ->
204 match rec_kind with `Inductive -> "rec" | `CoInductive -> "corec"
206 let mk_fun (args, (name,ty), body, rec_param) =
207 List.map aux_var args ,k name, HExtlib.map_option k ty, k body,
208 fst (List.nth args rec_param)
210 let mk_funs = List.map mk_fun in
211 let fst_fun, tl_funs =
212 match mk_funs funs with hd :: tl -> hd, tl | [] -> assert false
215 let (params, name, ty, body, rec_param) = fst_fun in
223 [space; keyword "on" ; space ; rec_param ;space ] @
224 (match ty with None -> [] | Some ty -> [builtin_symbol ":"; ty]) @
225 [ builtin_symbol "\\def";
231 (fun (params, name, ty, body, rec_param) ->
237 [space; keyword "on" ; space; rec_param ;space ] @
240 | Some ty -> [builtin_symbol ":"; ty]) @
241 [ builtin_symbol "\\def"; break; body ])])
244 add_level_info Ast.let_in_prec
246 (fst_row :: List.flatten tl_rows
247 @ [ break; keyword "in"; break; k where ])))
248 | Ast.Implicit -> builtin_symbol "?"
250 let local_context l =
251 List.map (function None -> None | Some t -> Some (k t)) l
253 Ast.Meta(n, local_context l)
254 | Ast.Sort sort -> aux_sort sort
257 | Ast.Ident (_, None) | Ast.Ident (_, Some [])
258 | Ast.Uri (_, None) | Ast.Uri (_, Some [])
260 | Ast.UserInput as leaf -> leaf
261 | t -> CicNotationUtil.visit_ast ~special_k k t
262 and aux_sort sort_kind =
263 add_xml_attrs (RenderingAttrs.keyword_attributes `MathML)
264 (Ast.Ident (string_of_sort_kind sort_kind, None))
265 and aux_ty = function
266 | None -> builtin_symbol "?"
268 and aux_var = function
271 builtin_symbol "("; name; builtin_symbol ":"; break; k ty;
274 and special_k = function
275 | Ast.AttributedTerm (attrs, t) -> Ast.AttributedTerm (attrs, k t)
277 prerr_endline ("unexpected special: " ^ CicNotationPp.pp_term t);
282 (* persistent state *)
284 let level1_patterns21 = Hashtbl.create 211
286 let compiled21 = ref None
288 let pattern21_matrix = ref []
290 let get_compiled21 () =
291 match !compiled21 with
292 | None -> assert false
293 | Some f -> Lazy.force f
295 let set_compiled21 f = compiled21 := Some f
298 List.fold_right (fun idref t -> Ast.AttributedTerm (`IdRef idref, t))
300 let instantiate21 idrefs env l1 =
301 let rec subst_singleton pos env =
303 Ast.AttributedTerm (attr, t) ->
304 Ast.AttributedTerm (attr, subst_singleton pos env t)
305 | t -> CicNotationUtil.group (subst pos env t)
306 and subst pos env = function
307 | Ast.AttributedTerm (attr, t) ->
308 (* prerr_endline ("loosing attribute " ^ CicNotationPp.pp_attribute attr); *)
310 | Ast.Variable var ->
311 let name, expected_ty = CicNotationEnv.declaration_of_var var in
316 prerr_endline ("name " ^ name ^ " not found in environment");
319 assert (CicNotationEnv.well_typed ty value); (* INVARIANT *)
320 (* following assertion should be a conditional that makes this
321 * instantiation fail *)
322 assert (CicNotationEnv.well_typed expected_ty value);
323 let value = CicNotationEnv.term_of_value value in
325 match expected_ty with
326 | Env.TermType (Some l) ->
327 Ast.AttributedTerm (`Level l,value)
331 | Ast.Magic m -> subst_magic pos env m
332 | Ast.Literal l as t ->
333 let t = add_idrefs idrefs t in
335 | `Keyword k -> [ add_keyword_attrs t ]
337 | Ast.Layout l -> [ Ast.Layout (subst_layout pos env l) ]
338 | t -> [ CicNotationUtil.visit_ast (subst_singleton pos env) t ]
339 and subst_magic pos env = function
340 | Ast.List0 (p, sep_opt)
341 | Ast.List1 (p, sep_opt) ->
342 let rec_decls = CicNotationEnv.declarations_of_term p in
344 List.map (fun (n, _) -> CicNotationEnv.lookup_list env n) rec_decls
346 let values = CicNotationUtil.ncombine rec_values in
350 | Some l -> [ Ast.Literal l ]
352 let rec instantiate_list acc = function
355 let env = CicNotationEnv.combine rec_decls value_set in
356 instantiate_list (CicNotationUtil.group (subst pos env p) :: acc)
359 let env = CicNotationEnv.combine rec_decls value_set in
360 let terms = subst pos env p in
361 instantiate_list (CicNotationUtil.group (terms @ sep) :: acc) tl
363 instantiate_list [] values
365 let opt_decls = CicNotationEnv.declarations_of_term p in
367 let rec build_env = function
369 | (name, ty) :: tl ->
370 (* assumption: if one of the value is None then all are *)
371 (match CicNotationEnv.lookup_opt env name with
373 | Some v -> (name, (ty, v)) :: build_env tl)
375 try build_env opt_decls with Exit -> []
380 | _ -> subst pos env p
382 | _ -> assert false (* impossible *)
383 and subst_layout pos env = function
384 | Ast.Box (kind, tl) ->
385 let tl' = subst_children pos env tl in
386 Ast.Box (kind, List.concat tl')
387 | l -> CicNotationUtil.visit_layout (subst_singleton pos env) l
388 and subst_children pos env =
396 (* | `None -> assert false *)
399 [ subst pos' env child ]
405 (* | `None -> assert false *)
408 (subst pos env hd) :: subst_children pos' env tl
410 subst_singleton `Left env l1
412 let rec pp_ast1 term =
413 let rec pp_value = function
414 | CicNotationEnv.NumValue _ as v -> v
415 | CicNotationEnv.StringValue _ as v -> v
416 (* | CicNotationEnv.TermValue t when t == term -> CicNotationEnv.TermValue (pp_ast0 t pp_ast1) *)
417 | CicNotationEnv.TermValue t -> CicNotationEnv.TermValue (pp_ast1 t)
418 | CicNotationEnv.OptValue None as v -> v
419 | CicNotationEnv.OptValue (Some v) ->
420 CicNotationEnv.OptValue (Some (pp_value v))
421 | CicNotationEnv.ListValue vl ->
422 CicNotationEnv.ListValue (List.map pp_value vl)
424 let ast_env_of_env env =
425 List.map (fun (var, (ty, value)) -> (var, (ty, pp_value value))) env
427 (* prerr_endline ("pattern matching from 2 to 1 on term " ^ CicNotationPp.pp_term term); *)
429 | Ast.AttributedTerm (attrs, term') ->
430 Ast.AttributedTerm (attrs, pp_ast1 term')
432 (match (get_compiled21 ()) term with
433 | None -> pp_ast0 term pp_ast1
434 | Some (env, ctors, pid) ->
436 List.flatten (List.map CicNotationUtil.get_idrefs ctors)
440 Hashtbl.find level1_patterns21 pid
441 with Not_found -> assert false
443 instantiate21 idrefs (ast_env_of_env env) l1)
445 let load_patterns21 t =
446 set_compiled21 (lazy (Content2presMatcher.Matcher21.compiler t))
449 debug_print (lazy "pp_ast <-");
450 let ast' = pp_ast1 ast in
451 debug_print (lazy ("pp_ast -> " ^ CicNotationPp.pp_term ast'));
454 exception Pretty_printer_not_found
456 let fill_pos_info l1_pattern = l1_pattern
457 (* let rec aux toplevel pos =
464 | Ast.Variable _ as t -> add_pos_info pos t
467 aux true l1_pattern *)
469 let counter = ref ~-1
472 Hashtbl.clear level1_patterns21
479 let add_pretty_printer l2 (CicNotationParser.CL1P (l1,precedence)) =
480 let id = fresh_id () in
481 let l1' = add_level_info precedence (fill_pos_info l1) in
482 let l2' = CicNotationUtil.strip_attributes l2 in
483 Hashtbl.add level1_patterns21 id l1';
484 pattern21_matrix := (l2', id) :: !pattern21_matrix;
485 load_patterns21 !pattern21_matrix;
488 let remove_pretty_printer id =
490 Hashtbl.remove level1_patterns21 id;
491 with Not_found -> raise Pretty_printer_not_found);
492 pattern21_matrix := List.filter (fun (_, id') -> id <> id') !pattern21_matrix;
493 load_patterns21 !pattern21_matrix
495 (* presentation -> content *)
497 let unopt_names names env =
498 let rec aux acc = function
499 | (name, (ty, v)) :: tl when List.mem name names ->
501 | Env.OptType ty, Env.OptValue (Some v) ->
502 aux ((name, (ty, v)) :: acc) tl
504 | hd :: tl -> aux (hd :: acc) tl
509 let head_names names env =
510 let rec aux acc = function
511 | (name, (ty, v)) :: tl when List.mem name names ->
513 | Env.ListType ty, Env.ListValue (v :: _) ->
514 aux ((name, (ty, v)) :: acc) tl
516 | _ :: tl -> aux acc tl
517 (* base pattern may contain only meta names, thus we trash all others *)
522 let tail_names names env =
523 let rec aux acc = function
524 | (name, (ty, v)) :: tl when List.mem name names ->
526 | Env.ListType ty, Env.ListValue (_ :: vtl) ->
527 aux ((name, (Env.ListType ty, Env.ListValue vtl)) :: acc) tl
529 | binding :: tl -> aux (binding :: acc) tl
534 let instantiate_level2 env term =
535 let fresh_env = ref [] in
536 let lookup_fresh_name n =
538 List.assoc n !fresh_env
540 let new_name = CicNotationUtil.fresh_name () in
541 fresh_env := (n, new_name) :: !fresh_env;
544 let rec aux env term =
545 (* prerr_endline ("ENV " ^ CicNotationPp.pp_env env); *)
547 | Ast.AttributedTerm (_, term) -> aux env term
548 | Ast.Appl terms -> Ast.Appl (List.map (aux env) terms)
549 | Ast.Binder (binder, var, body) ->
550 Ast.Binder (binder, aux_capture_var env var, aux env body)
551 | Ast.Case (term, indty, outty_opt, patterns) ->
552 Ast.Case (aux env term, indty, aux_opt env outty_opt,
553 List.map (aux_branch env) patterns)
554 | Ast.LetIn (var, t1, t3) ->
555 Ast.LetIn (aux_capture_var env var, aux env t1, aux env t3)
556 | Ast.LetRec (kind, definitions, body) ->
557 Ast.LetRec (kind, List.map (aux_definition env) definitions,
559 | Ast.Uri (name, None) -> Ast.Uri (name, None)
560 | Ast.Uri (name, Some substs) ->
561 Ast.Uri (name, Some (aux_substs env substs))
562 | Ast.Ident (name, Some substs) ->
563 Ast.Ident (name, Some (aux_substs env substs))
564 | Ast.Meta (index, substs) -> Ast.Meta (index, aux_meta_substs env substs)
571 | Ast.UserInput -> term
573 | Ast.Magic magic -> aux_magic env magic
574 | Ast.Variable var -> aux_variable env var
577 and aux_opt env = function
578 | Some term -> Some (aux env term)
580 and aux_capture_var env (name, ty_opt) = (aux env name, aux_opt env ty_opt)
581 and aux_branch env (pattern, term) =
582 (aux_pattern env pattern, aux env term)
583 and aux_pattern env =
585 Ast.Pattern (head, hrefs, vars) ->
586 Ast.Pattern (head, hrefs, List.map (aux_capture_var env) vars)
587 | Ast.Wildcard -> Ast.Wildcard
588 and aux_definition env (params, var, term, i) =
589 (List.map (aux_capture_var env) params, aux_capture_var env var, aux env term, i)
590 and aux_substs env substs =
591 List.map (fun (name, term) -> (name, aux env term)) substs
592 and aux_meta_substs env meta_substs = List.map (aux_opt env) meta_substs
593 and aux_variable env = function
594 | Ast.NumVar name -> Ast.Num (Env.lookup_num env name, 0)
595 | Ast.IdentVar name -> Ast.Ident (Env.lookup_string env name, None)
596 | Ast.TermVar (name,None) ->
597 Env.lookup_term env name
598 | Ast.TermVar (name,Some l) ->
599 Ast.AttributedTerm (`Level l,Env.lookup_term env name)
600 | Ast.FreshVar name -> Ast.Ident (lookup_fresh_name name, None)
601 | Ast.Ascription (term, name) -> assert false
602 and aux_magic env = function
603 | Ast.Default (some_pattern, none_pattern) ->
604 let some_pattern_names = CicNotationUtil.names_of_term some_pattern in
605 let none_pattern_names = CicNotationUtil.names_of_term none_pattern in
608 (fun name -> not (List.mem name none_pattern_names))
611 (match opt_names with
612 | [] -> assert false (* some pattern must contain at least 1 name *)
613 | (name :: _) as names ->
614 (match Env.lookup_value env name with
615 | Env.OptValue (Some _) ->
616 (* assumption: if "name" above is bound to Some _, then all
617 * names returned by "meta_names_of" are bound to Some _ as well
619 aux (unopt_names names env) some_pattern
620 | Env.OptValue None -> aux env none_pattern
622 prerr_endline (sprintf
623 "lookup of %s in env %s did not return an optional value"
624 name (CicNotationPp.pp_env env));
626 | Ast.Fold (`Left, base_pattern, names, rec_pattern) ->
627 let acc_name = List.hd names in (* names can't be empty, cfr. parser *)
629 List.filter ((<>) acc_name)
630 (CicNotationUtil.names_of_term rec_pattern)
632 (match meta_names with
633 | [] -> assert false (* as above *)
634 | (name :: _) as names ->
635 let rec instantiate_fold_left acc env' =
636 match Env.lookup_value env' name with
637 | Env.ListValue (_ :: _) ->
638 instantiate_fold_left
640 acc_name, (Env.TermType None, Env.TermValue acc)
642 aux (acc_binding :: head_names names env') rec_pattern)
643 (tail_names names env')
644 | Env.ListValue [] -> acc
647 instantiate_fold_left (aux env base_pattern) env)
648 | Ast.Fold (`Right, base_pattern, names, rec_pattern) ->
649 let acc_name = List.hd names in (* names can't be empty, cfr. parser *)
651 List.filter ((<>) acc_name)
652 (CicNotationUtil.names_of_term rec_pattern)
654 (match meta_names with
655 | [] -> assert false (* as above *)
656 | (name :: _) as names ->
657 let rec instantiate_fold_right env' =
658 match Env.lookup_value env' name with
659 | Env.ListValue (_ :: _) ->
660 let acc = instantiate_fold_right (tail_names names env') in
662 acc_name, (Env.TermType None, Env.TermValue acc)
664 aux (acc_binding :: head_names names env') rec_pattern
665 | Env.ListValue [] -> aux env base_pattern
668 instantiate_fold_right env)
669 | Ast.If (_, p_true, p_false) as t ->
670 aux env (CicNotationUtil.find_branch (Ast.Magic t))
671 | Ast.Fail -> assert false
678 let _ = load_patterns21 []