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
31 let debug_print s = if debug then prerr_endline (Lazy.force s) else ()
34 type interpretation_id = pattern_id
35 type pretty_printer_id = pattern_id
38 { sort: (Cic.id, Ast.sort_kind) Hashtbl.t;
39 uri: (Cic.id, UriManager.uri) Hashtbl.t;
43 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
45 | Cic.InductiveDefinition (l,_,_,_) -> l
48 let name_of_inductive_type uri i =
49 let types = get_types uri in
50 let (name, _, _, _) = try List.nth types i with Not_found -> assert false in
53 (* returns <name, type> pairs *)
54 let constructors_of_inductive_type uri i =
55 let types = get_types uri in
56 let (_, _, _, constructors) =
57 try List.nth types i with Not_found -> assert false
61 (* returns name only *)
62 let constructor_of_inductive_type uri i j =
64 fst (List.nth (constructors_of_inductive_type uri i) (j-1))
65 with Not_found -> assert false)
67 let idref id t = Ast.AttributedTerm (`IdRef id, t)
69 let resolve_binder = function
70 | `Lambda -> "\\lambda"
72 | `Forall -> "\\forall"
73 | `Exists -> "\\exists"
75 let add_level_info prec assoc t = Ast.AttributedTerm (`Level (prec, assoc), t)
76 let add_pos_info pos t = Ast.AttributedTerm (`ChildPos pos, t)
77 let left_pos = add_pos_info `Left
78 let right_pos = add_pos_info `Right
79 let inner_pos = add_pos_info `Inner
81 let rec top_pos t = add_level_info ~-1 Gramext.NonA (inner_pos t)
83 | Ast.AttributedTerm (`Level _, t) ->
84 add_level_info ~-1 Gramext.NonA (inner_pos t)
85 | Ast.AttributedTerm (attr, t) -> Ast.AttributedTerm (attr, top_pos t)
86 | t -> add_level_info ~-1 Gramext.NonA (inner_pos t) *)
88 let rec remove_level_info =
90 | Ast.AttributedTerm (`Level _, t) -> remove_level_info t
91 | Ast.AttributedTerm (a, t) -> Ast.AttributedTerm (a, remove_level_info t)
94 let add_xml_attrs attrs t =
95 if attrs = [] then t else Ast.AttributedTerm (`XmlAttrs attrs, t)
97 let add_keyword_attrs =
98 add_xml_attrs (RenderingAttrs.keyword_attributes `MathML)
100 let box kind spacing indent content =
101 Ast.Layout (Ast.Box ((kind, spacing, indent), content))
105 let hvbox = box Ast.HV
106 let hovbox = box Ast.HOV
107 let break = Ast.Layout Ast.Break
108 let builtin_symbol s = Ast.Literal (`Symbol s)
109 let keyword k = add_keyword_attrs (Ast.Literal (`Keyword k))
112 add_xml_attrs (RenderingAttrs.number_attributes `MathML)
113 (Ast.Literal (`Number s))
116 add_xml_attrs (RenderingAttrs.ident_attributes `MathML) (Ast.Ident (i, None))
118 let ident_w_href href i =
122 let href = UriManager.string_of_uri href in
123 add_xml_attrs [Some "xlink", "href", href] (ident i)
125 let binder_symbol s =
126 add_xml_attrs (RenderingAttrs.builtin_symbol_attributes `MathML)
129 let string_of_sort_kind = function
139 let rec aux_args pos =
144 if pos = `Left then [ left_pos last ] else [ right_pos last ]
146 (add_pos_info pos (k hd)) :: aux_args `Inner tl
148 add_level_info Ast.apply_prec Ast.apply_assoc
149 (hovbox true true (CicNotationUtil.dress break (aux_args `Left ts)))
150 | Ast.Binder (binder_kind, (id, ty), body) ->
151 add_level_info Ast.binder_prec Ast.binder_assoc
153 [ binder_symbol (resolve_binder binder_kind);
154 k id; builtin_symbol ":"; aux_ty ty; break;
155 builtin_symbol "."; right_pos (k body) ])
156 | Ast.Case (what, indty_opt, outty_opt, patterns) ->
161 [ keyword "return"; break; remove_level_info (k outty)]
166 | Some (indty, href) -> [ keyword "in"; break; ident_w_href href indty ]
171 hvbox false true [ keyword "match"; break; top_pos (k what) ];
173 hvbox false true indty_box;
175 hvbox false true outty_box
181 let mk_case_pattern (head, href, vars) =
182 hbox true false (ident_w_href href head :: List.map aux_var vars)
190 mk_case_pattern lhs; builtin_symbol "\\Rightarrow" ];
191 break; top_pos (k rhs) ]))
195 let rec aux_patterns = function
201 last; builtin_symbol "]" ] ]
203 [ break; hbox false false [ builtin_symbol "|"; hd ] ]
208 [ hbox false false [ builtin_symbol "["; builtin_symbol "]" ] ]
211 builtin_symbol "["; one; builtin_symbol "]" ] ]
213 hbox false false [ builtin_symbol "["; hd ]
216 add_level_info Ast.simple_prec Ast.simple_assoc
218 hvbox false false ([match_box]); break;
219 hbox false false [ hvbox false false patterns'' ] ])
220 | Ast.Cast (bo, ty) ->
221 add_level_info Ast.simple_prec Ast.simple_assoc
223 builtin_symbol "("; top_pos (k bo); break; builtin_symbol ":";
224 top_pos (k ty); builtin_symbol ")"])
225 | Ast.LetIn (var, s, t) ->
226 add_level_info Ast.let_in_prec Ast.let_in_assoc
231 aux_var var; builtin_symbol "\\def"; break; top_pos (k s) ];
232 break; keyword "in" ];
235 | Ast.LetRec (rec_kind, funs, where) ->
237 match rec_kind with `Inductive -> "rec" | `CoInductive -> "corec"
239 let mk_fun (var, body, _) = aux_var var, k body in
240 let mk_funs = List.map mk_fun in
241 let fst_fun, tl_funs =
242 match mk_funs funs with hd :: tl -> hd, tl | [] -> assert false
245 let (name, body) = fst_fun in
247 keyword "let"; keyword rec_op; name; builtin_symbol "\\def"; break;
255 keyword "and"; name; builtin_symbol "\\def"; break; body ] ])
258 add_level_info Ast.let_in_prec Ast.let_in_assoc
260 (fst_row :: List.flatten tl_rows
261 @ [ break; keyword "in"; break; k where ])))
262 | Ast.Implicit -> builtin_symbol "?"
264 let local_context l =
265 CicNotationUtil.dress (builtin_symbol ";")
266 (List.map (function None -> builtin_symbol "_" | Some t -> k t) l)
269 ([ builtin_symbol "?"; number (string_of_int n) ]
270 @ (if l <> [] then local_context l else []))
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 -> CicNotationUtil.visit_ast ~special_k k t
279 and aux_sort sort_kind =
280 add_xml_attrs (RenderingAttrs.keyword_attributes `MathML)
281 (Ast.Ident (string_of_sort_kind sort_kind, None))
282 and aux_ty = function
283 | None -> builtin_symbol "?"
285 and aux_var = function
288 builtin_symbol "("; name; builtin_symbol ":"; break; k ty;
291 and special_k = function
292 | Ast.AttributedTerm (attrs, t) -> Ast.AttributedTerm (attrs, k t)
294 prerr_endline ("unexpected special: " ^ CicNotationPp.pp_term t);
299 let ast_of_acic0 term_info acic k =
300 let k = k term_info in
301 let id_to_uris = term_info.uri in
302 let register_uri id uri = Hashtbl.add id_to_uris id uri in
305 Hashtbl.find term_info.sort id
307 prerr_endline (sprintf "warning: sort of id %s not found, using Type" id);
308 `Type (CicUniv.fresh ())
310 let aux_substs substs =
313 (fun (uri, annterm) -> (UriManager.name_of_uri uri, k annterm))
316 let aux_context context =
320 | Some annterm -> Some (k annterm))
324 | Cic.ARel (id,_,_,b) -> idref id (Ast.Ident (b, None))
325 | Cic.AVar (id,uri,substs) ->
327 idref id (Ast.Ident (UriManager.name_of_uri uri, aux_substs substs))
328 | Cic.AMeta (id,n,l) -> idref id (Ast.Meta (n, aux_context l))
329 | Cic.ASort (id,Cic.Prop) -> idref id (Ast.Sort `Prop)
330 | Cic.ASort (id,Cic.Set) -> idref id (Ast.Sort `Set)
331 | Cic.ASort (id,Cic.Type u) -> idref id (Ast.Sort (`Type u))
332 | Cic.ASort (id,Cic.CProp) -> idref id (Ast.Sort `CProp)
333 | Cic.AImplicit (id, Some `Hole) -> idref id Ast.UserInput
334 | Cic.AImplicit (id, _) -> idref id Ast.Implicit
335 | Cic.AProd (id,n,s,t) ->
337 match sort_of_id id with
338 | `Set | `Type _ -> `Pi
339 | `Prop | `CProp -> `Forall
341 idref id (Ast.Binder (binder_kind,
342 (CicNotationUtil.name_of_cic_name n, Some (k s)), k t))
343 | Cic.ACast (id,v,t) -> idref id (Ast.Cast (k v, k t))
344 | Cic.ALambda (id,n,s,t) ->
345 idref id (Ast.Binder (`Lambda,
346 (CicNotationUtil.name_of_cic_name n, Some (k s)), k t))
347 | Cic.ALetIn (id,n,s,t) ->
348 idref id (Ast.LetIn ((CicNotationUtil.name_of_cic_name n, None),
350 | Cic.AAppl (aid,args) -> idref aid (Ast.Appl (List.map k args))
351 | Cic.AConst (id,uri,substs) ->
353 idref id (Ast.Ident (UriManager.name_of_uri uri, aux_substs substs))
354 | Cic.AMutInd (id,uri,i,substs) as t ->
355 let name = name_of_inductive_type uri i in
356 let uri_str = UriManager.string_of_uri uri in
357 let puri_str = sprintf "%s#xpointer(1/%d)" uri_str (i+1) in
358 register_uri id (UriManager.uri_of_string puri_str);
359 idref id (Ast.Ident (name, aux_substs substs))
360 | Cic.AMutConstruct (id,uri,i,j,substs) ->
361 let name = constructor_of_inductive_type uri i j in
362 let uri_str = UriManager.string_of_uri uri in
363 let puri_str = sprintf "%s#xpointer(1/%d/%d)" uri_str (i + 1) j in
364 register_uri id (UriManager.uri_of_string puri_str);
365 idref id (Ast.Ident (name, aux_substs substs))
366 | Cic.AMutCase (id,uri,typeno,ty,te,patterns) ->
367 let name = name_of_inductive_type uri typeno in
368 let uri_str = UriManager.string_of_uri uri in
369 let puri_str = sprintf "%s#xpointer(1/%d)" uri_str (typeno+1) in
371 UriManager.uri_of_string
372 (sprintf "%s#xpointer(1/%d/%d)" uri_str (typeno+1) j)
374 let case_indty = name, Some (UriManager.uri_of_string puri_str) in
375 let constructors = constructors_of_inductive_type uri typeno in
376 let rec eat_branch ty pat =
378 | Cic.Prod (_, _, t), Cic.ALambda (_, name, s, t') ->
379 let (cv, rhs) = eat_branch t t' in
380 (CicNotationUtil.name_of_cic_name name, Some (k s)) :: cv, rhs
387 (fun (name, ty) pat ->
389 let (capture_variables, rhs) = eat_branch ty pat in
390 ((name, Some (ctor_puri !j), capture_variables), rhs))
391 constructors patterns
392 with Invalid_argument _ -> assert false
394 idref id (Ast.Case (k te, Some case_indty, Some (k ty), patterns))
395 | Cic.AFix (id, no, funs) ->
398 (fun (_, n, decr_idx, ty, bo) ->
399 ((Ast.Ident (n, None), Some (k ty)), k bo, decr_idx))
404 (match List.nth defs no with
405 | (Ast.Ident (n, _), _), _, _ when n <> "_" -> n
407 with Not_found -> assert false
409 idref id (Ast.LetRec (`Inductive, defs, Ast.Ident (name, None)))
410 | Cic.ACoFix (id, no, funs) ->
413 (fun (_, n, ty, bo) ->
414 ((Ast.Ident (n, None), Some (k ty)), k bo, 0))
419 (match List.nth defs no with
420 | (Ast.Ident (n, _), _), _, _ when n <> "_" -> n
422 with Not_found -> assert false
424 idref id (Ast.LetRec (`CoInductive, defs, Ast.Ident (name, None)))
428 (* persistent state *)
430 let level1_patterns21 = Hashtbl.create 211
431 let level2_patterns32 = Hashtbl.create 211
432 let interpretations = Hashtbl.create 211 (* symb -> id list ref *)
434 let compiled21 = ref None
435 let compiled32 = ref None
437 let pattern21_matrix = ref []
438 let pattern32_matrix = ref []
440 let get_compiled21 () =
441 match !compiled21 with
442 | None -> assert false
443 | Some f -> Lazy.force f
444 let get_compiled32 () =
445 match !compiled32 with
446 | None -> assert false
447 | Some f -> Lazy.force f
449 let set_compiled21 f = compiled21 := Some f
450 let set_compiled32 f = compiled32 := Some f
453 List.fold_right (fun idref t -> Ast.AttributedTerm (`IdRef idref, t))
455 let instantiate21 idrefs env l1 =
456 let rec subst_singleton pos env =
458 Ast.AttributedTerm (attr, t) ->
459 Ast.AttributedTerm (attr, subst_singleton pos env t)
460 | t -> CicNotationUtil.group (subst pos env t)
461 and subst pos env = function
462 | Ast.AttributedTerm (attr, t) as term ->
463 (* prerr_endline ("loosing attribute " ^ CicNotationPp.pp_attribute attr); *)
465 | Ast.Variable var ->
466 let name, expected_ty = CicNotationEnv.declaration_of_var var in
471 prerr_endline ("name " ^ name ^ " not found in environment");
474 assert (CicNotationEnv.well_typed ty value); (* INVARIANT *)
475 (* following assertion should be a conditional that makes this
476 * instantiation fail *)
477 assert (CicNotationEnv.well_typed expected_ty value);
478 [ add_pos_info pos (CicNotationEnv.term_of_value value) ]
479 | Ast.Magic m -> subst_magic pos env m
480 | Ast.Literal l as t ->
481 let t = add_idrefs idrefs t in
483 | `Keyword k -> [ add_keyword_attrs t ]
485 | Ast.Layout l -> [ Ast.Layout (subst_layout pos env l) ]
486 | t -> [ CicNotationUtil.visit_ast (subst_singleton pos env) t ]
487 and subst_magic pos env = function
488 | Ast.List0 (p, sep_opt)
489 | Ast.List1 (p, sep_opt) ->
490 let rec_decls = CicNotationEnv.declarations_of_term p in
492 List.map (fun (n, _) -> CicNotationEnv.lookup_list env n) rec_decls
494 let values = CicNotationUtil.ncombine rec_values in
498 | Some l -> [ Ast.Literal l ]
500 let rec instantiate_list acc = function
503 let env = CicNotationEnv.combine rec_decls value_set in
504 instantiate_list (CicNotationUtil.group (subst pos env p) :: acc)
507 let env = CicNotationEnv.combine rec_decls value_set in
508 let terms = subst pos env p in
509 instantiate_list (CicNotationUtil.group (terms @ sep) :: acc) tl
511 instantiate_list [] values
513 let opt_decls = CicNotationEnv.declarations_of_term p in
515 let rec build_env = function
517 | (name, ty) :: tl ->
518 (* assumption: if one of the value is None then all are *)
519 (match CicNotationEnv.lookup_opt env name with
521 | Some v -> (name, (ty, v)) :: build_env tl)
523 try build_env opt_decls with Exit -> []
528 | _ -> subst pos env p
530 | _ -> assert false (* impossible *)
531 and subst_layout pos env = function
532 | Ast.Box (kind, tl) ->
533 let tl' = subst_children pos env tl in
534 Ast.Box (kind, List.concat tl')
535 | l -> CicNotationUtil.visit_layout (subst_singleton pos env) l
536 and subst_children pos env =
544 (* | `None -> assert false *)
547 [ subst pos' env child ]
553 (* | `None -> assert false *)
556 (subst pos env hd) :: subst_children pos' env tl
558 subst_singleton `Left env l1
560 let rec pp_ast1 term =
561 let rec pp_value = function
562 | CicNotationEnv.NumValue _ as v -> v
563 | CicNotationEnv.StringValue _ as v -> v
564 (* | CicNotationEnv.TermValue t when t == term -> CicNotationEnv.TermValue (pp_ast0 t pp_ast1) *)
565 | CicNotationEnv.TermValue t -> CicNotationEnv.TermValue (pp_ast1 t)
566 | CicNotationEnv.OptValue None as v -> v
567 | CicNotationEnv.OptValue (Some v) ->
568 CicNotationEnv.OptValue (Some (pp_value v))
569 | CicNotationEnv.ListValue vl ->
570 CicNotationEnv.ListValue (List.map pp_value vl)
572 let ast_env_of_env env =
573 List.map (fun (var, (ty, value)) -> (var, (ty, pp_value value))) env
575 (* prerr_endline ("pattern matching from 2 to 1 on term " ^ CicNotationPp.pp_term term); *)
577 | Ast.AttributedTerm (attrs, term') ->
578 Ast.AttributedTerm (attrs, pp_ast1 term')
580 (match (get_compiled21 ()) term with
581 | None -> pp_ast0 term pp_ast1
582 | Some (env, ctors, pid) ->
584 List.flatten (List.map CicNotationUtil.get_idrefs ctors)
588 Hashtbl.find level1_patterns21 pid
589 with Not_found -> assert false
591 instantiate21 idrefs (ast_env_of_env env) l1)
593 let instantiate32 term_info idrefs env symbol args =
594 let rec instantiate_arg = function
595 | Ast.IdentArg (n, name) ->
596 let t = (try List.assoc name env with Not_found -> assert false) in
597 let rec count_lambda = function
598 | Ast.AttributedTerm (_, t) -> count_lambda t
599 | Ast.Binder (`Lambda, _, body) -> 1 + count_lambda body
602 let rec add_lambda t n =
604 let name = CicNotationUtil.fresh_name () in
605 Ast.Binder (`Lambda, (Ast.Ident (name, None), None),
606 Ast.Appl [add_lambda t (n - 1); Ast.Ident (name, None)])
610 add_lambda t (n - count_lambda t)
613 let symbol = Ast.Symbol (symbol, 0) in
614 add_idrefs idrefs symbol
616 if args = [] then head
617 else Ast.Appl (head :: List.map instantiate_arg args)
619 let rec ast_of_acic1 term_info annterm =
620 let id_to_uris = term_info.uri in
621 let register_uri id uri = Hashtbl.add id_to_uris id uri in
622 match (get_compiled32 ()) annterm with
623 | None -> ast_of_acic0 term_info annterm ast_of_acic1
624 | Some (env, ctors, pid) ->
628 let idref = CicUtil.id_of_annterm annterm in
631 (CicUtil.uri_of_term (Deannotate.deannotate_term annterm))
632 with Invalid_argument _ -> ());
637 List.map (fun (name, term) -> (name, ast_of_acic1 term_info term)) env
639 let _, symbol, args, _ =
641 Hashtbl.find level2_patterns32 pid
642 with Not_found -> assert false
644 let ast = instantiate32 term_info idrefs env' symbol args in
645 Ast.AttributedTerm (`IdRef (CicUtil.id_of_annterm annterm), ast)
647 let load_patterns32 t =
649 HExtlib.filter_map (function (true, ap, id) -> Some (ap, id) | _ -> None) t
651 set_compiled32 (lazy (CicNotationMatcher.Matcher32.compiler t))
653 let load_patterns21 t =
654 set_compiled21 (lazy (CicNotationMatcher.Matcher21.compiler t))
656 let ast_of_acic id_to_sort annterm =
657 debug_print (lazy ("ast_of_acic <- "
658 ^ CicPp.ppterm (Deannotate.deannotate_term annterm)));
659 let term_info = { sort = id_to_sort; uri = Hashtbl.create 211 } in
660 let ast = ast_of_acic1 term_info annterm in
661 debug_print (lazy ("ast_of_acic -> " ^ CicNotationPp.pp_term ast));
665 debug_print (lazy "pp_ast <-");
666 let ast' = pp_ast1 ast in
667 debug_print (lazy ("pp_ast -> " ^ CicNotationPp.pp_term ast'));
671 let counter = ref ~-1 in
676 let add_interpretation dsc (symbol, args) appl_pattern =
677 let id = fresh_id () in
678 Hashtbl.add level2_patterns32 id (dsc, symbol, args, appl_pattern);
679 pattern32_matrix := (true, appl_pattern, id) :: !pattern32_matrix;
680 load_patterns32 !pattern32_matrix;
682 let ids = Hashtbl.find interpretations symbol in
684 with Not_found -> Hashtbl.add interpretations symbol (ref [id]));
687 let get_all_interpretations () =
689 (function (_, _, id) ->
692 Hashtbl.find level2_patterns32 id
693 with Not_found -> assert false
698 let get_active_interpretations () =
699 HExtlib.filter_map (function (true, _, id) -> Some id | _ -> None)
702 let set_active_interpretations ids =
703 let pattern32_matrix' =
706 | (_, ap, id) when List.mem id ids -> (true, ap, id)
707 | (_, ap, id) -> (false, ap, id))
710 pattern32_matrix := pattern32_matrix';
711 load_patterns32 !pattern32_matrix
713 exception Interpretation_not_found
714 exception Pretty_printer_not_found
716 let rec list_uniq = function
719 | h1::h2::tl when h1 = h2 -> list_uniq (h2 :: tl)
720 | h1::tl (* when h1 <> h2 *) -> h1 :: list_uniq tl
722 let lookup_interpretations symbol =
725 (List.sort Pervasives.compare
728 let (dsc, _, args, appl_pattern) =
730 Hashtbl.find level2_patterns32 id
731 with Not_found -> assert false
733 dsc, args, appl_pattern)
734 !(Hashtbl.find interpretations symbol)))
735 with Not_found -> raise Interpretation_not_found
737 let fill_pos_info l1_pattern = l1_pattern
738 (* let rec aux toplevel pos =
745 | Ast.Variable _ as t -> add_pos_info pos t
748 aux true l1_pattern *)
750 let add_pretty_printer ~precedence ~associativity l2 l1 =
751 let id = fresh_id () in
752 let l1' = add_level_info precedence associativity (fill_pos_info l1) in
753 let l2' = CicNotationUtil.strip_attributes l2 in
754 Hashtbl.add level1_patterns21 id l1';
755 pattern21_matrix := (l2', id) :: !pattern21_matrix;
756 load_patterns21 !pattern21_matrix;
759 let remove_interpretation id =
761 let _, symbol, _, _ = Hashtbl.find level2_patterns32 id in
762 let ids = Hashtbl.find interpretations symbol in
763 ids := List.filter ((<>) id) !ids;
764 Hashtbl.remove level2_patterns32 id;
765 with Not_found -> raise Interpretation_not_found);
767 List.filter (fun (_, _, id') -> id <> id') !pattern32_matrix;
768 load_patterns32 !pattern32_matrix
770 let remove_pretty_printer id =
772 Hashtbl.remove level1_patterns21 id;
773 with Not_found -> raise Pretty_printer_not_found);
774 pattern21_matrix := List.filter (fun (_, id') -> id <> id') !pattern21_matrix;
775 load_patterns21 !pattern21_matrix