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)
78 let rec remove_level_info =
80 | Ast.AttributedTerm (`Level _, t) -> remove_level_info t
81 | Ast.AttributedTerm (a, t) -> Ast.AttributedTerm (a, remove_level_info t)
84 let add_xml_attrs attrs t =
85 if attrs = [] then t else Ast.AttributedTerm (`XmlAttrs attrs, t)
87 let add_keyword_attrs =
88 add_xml_attrs (RenderingAttrs.keyword_attributes `MathML)
90 let box kind spacing indent content =
91 Ast.Layout (Ast.Box ((kind, spacing, indent), content))
95 let hvbox = box Ast.HV
96 let hovbox = box Ast.HOV
97 let break = Ast.Layout Ast.Break
98 let builtin_symbol s = Ast.Literal (`Symbol s)
99 let keyword k = add_keyword_attrs (Ast.Literal (`Keyword k))
102 add_xml_attrs (RenderingAttrs.number_attributes `MathML)
103 (Ast.Literal (`Number s))
106 add_xml_attrs (RenderingAttrs.ident_attributes `MathML) (Ast.Ident (i, None))
108 let ident_w_href href i =
112 let href = UriManager.string_of_uri href in
113 add_xml_attrs [Some "xlink", "href", href] (ident i)
115 let binder_symbol s =
116 add_xml_attrs (RenderingAttrs.builtin_symbol_attributes `MathML)
119 let string_of_sort_kind = function
129 add_level_info Ast.apply_prec Ast.apply_assoc
130 (hovbox true true (CicNotationUtil.dress break (List.map k ts)))
131 | Ast.Binder (binder_kind, (id, ty), body) ->
132 add_level_info Ast.binder_prec Ast.binder_assoc
134 [ binder_symbol (resolve_binder binder_kind);
135 k id; builtin_symbol ":"; aux_ty ty; break;
136 builtin_symbol "."; k body ])
137 | Ast.Case (what, indty_opt, outty_opt, patterns) ->
142 [ builtin_symbol "["; remove_level_info (k outty);
143 builtin_symbol "]"; break ]
148 | Some (indty, href) -> [ keyword "in"; ident_w_href href indty ]
152 keyword "match"; break;
153 hvbox false false ([ k what ] @ indty_box); break;
156 let mk_case_pattern (head, href, vars) =
157 hbox true false (ident_w_href href head :: List.map aux_var vars)
165 mk_case_pattern lhs; builtin_symbol "\\Rightarrow" ];
170 let rec aux_patterns = function
176 last; builtin_symbol "]" ] ]
178 [ break; hbox false false [ builtin_symbol "|"; hd ] ]
183 [ hbox false false [ builtin_symbol "["; builtin_symbol "]" ] ]
186 builtin_symbol "["; one; builtin_symbol "]" ] ]
188 hbox false false [ builtin_symbol "["; hd ]
191 add_level_info Ast.simple_prec Ast.simple_assoc
193 hvbox false false (outty_box @ [ match_box ]); break;
194 hbox false false [ hvbox false false patterns'' ] ])
195 | Ast.Cast (bo, ty) ->
196 add_level_info Ast.simple_prec Ast.simple_assoc
198 builtin_symbol "("; k bo; break; builtin_symbol ":"; k ty;
200 | Ast.LetIn (var, s, t) ->
201 add_level_info Ast.let_in_prec Ast.let_in_assoc
206 aux_var var; builtin_symbol "\\def"; break; k s ];
207 break; keyword "in" ];
210 | Ast.LetRec (rec_kind, funs, where) ->
212 match rec_kind with `Inductive -> "rec" | `CoInductive -> "corec"
214 let mk_fun (var, body, _) = aux_var var, k body in
215 let mk_funs = List.map mk_fun in
216 let fst_fun, tl_funs =
217 match mk_funs funs with hd :: tl -> hd, tl | [] -> assert false
220 let (name, body) = fst_fun in
222 keyword "let"; keyword rec_op; name; builtin_symbol "\\def"; break;
230 keyword "and"; name; builtin_symbol "\\def"; break; body ] ])
233 add_level_info Ast.let_in_prec Ast.let_in_assoc
235 (fst_row :: List.flatten tl_rows
236 @ [ break; keyword "in"; break; k where ])))
237 | Ast.Implicit -> builtin_symbol "?"
239 let local_context l =
240 CicNotationUtil.dress (builtin_symbol ";")
241 (List.map (function None -> builtin_symbol "_" | Some t -> k t) l)
244 ([ builtin_symbol "?"; number (string_of_int n) ]
245 @ (if l <> [] then local_context l else []))
246 | Ast.Sort sort -> aux_sort sort
249 | Ast.Ident (_, None) | Ast.Ident (_, Some [])
250 | Ast.Uri (_, None) | Ast.Uri (_, Some [])
252 | Ast.UserInput as leaf -> leaf
253 | t -> CicNotationUtil.visit_ast ~special_k k t
254 and aux_sort sort_kind =
255 add_xml_attrs (RenderingAttrs.keyword_attributes `MathML)
256 (Ast.Ident (string_of_sort_kind sort_kind, None))
257 and aux_ty = function
258 | None -> builtin_symbol "?"
260 and aux_var = function
263 builtin_symbol "("; name; builtin_symbol ":"; break; k ty;
266 and special_k = function
267 | Ast.AttributedTerm (attrs, t) -> Ast.AttributedTerm (attrs, k t)
269 prerr_endline ("unexpected special: " ^ CicNotationPp.pp_term t);
274 let ast_of_acic0 term_info acic k =
275 let k = k term_info in
276 let id_to_uris = term_info.uri in
277 let register_uri id uri = Hashtbl.add id_to_uris id uri in
280 Hashtbl.find term_info.sort id
282 prerr_endline (sprintf "warning: sort of id %s not found, using Type" id);
283 `Type (CicUniv.fresh ())
285 let aux_substs substs =
288 (fun (uri, annterm) -> (UriManager.name_of_uri uri, k annterm))
291 let aux_context context =
295 | Some annterm -> Some (k annterm))
299 | Cic.ARel (id,_,_,b) -> idref id (Ast.Ident (b, None))
300 | Cic.AVar (id,uri,substs) ->
302 idref id (Ast.Ident (UriManager.name_of_uri uri, aux_substs substs))
303 | Cic.AMeta (id,n,l) -> idref id (Ast.Meta (n, aux_context l))
304 | Cic.ASort (id,Cic.Prop) -> idref id (Ast.Sort `Prop)
305 | Cic.ASort (id,Cic.Set) -> idref id (Ast.Sort `Set)
306 | Cic.ASort (id,Cic.Type u) -> idref id (Ast.Sort (`Type u))
307 | Cic.ASort (id,Cic.CProp) -> idref id (Ast.Sort `CProp)
308 | Cic.AImplicit _ -> assert false
309 | Cic.AProd (id,n,s,t) ->
311 match sort_of_id id with
312 | `Set | `Type _ -> `Pi
313 | `Prop | `CProp -> `Forall
315 idref id (Ast.Binder (binder_kind,
316 (CicNotationUtil.name_of_cic_name n, Some (k s)), k t))
317 | Cic.ACast (id,v,t) -> idref id (Ast.Cast (k v, k t))
318 | Cic.ALambda (id,n,s,t) ->
319 idref id (Ast.Binder (`Lambda,
320 (CicNotationUtil.name_of_cic_name n, Some (k s)), k t))
321 | Cic.ALetIn (id,n,s,t) ->
322 idref id (Ast.LetIn ((CicNotationUtil.name_of_cic_name n, None),
324 | Cic.AAppl (aid,args) -> idref aid (Ast.Appl (List.map k args))
325 | Cic.AConst (id,uri,substs) ->
327 idref id (Ast.Ident (UriManager.name_of_uri uri, aux_substs substs))
328 | Cic.AMutInd (id,uri,i,substs) as t ->
329 let name = name_of_inductive_type uri i in
330 let uri_str = UriManager.string_of_uri uri in
331 let puri_str = sprintf "%s#xpointer(1/%d)" uri_str (i+1) in
332 register_uri id (UriManager.uri_of_string puri_str);
333 idref id (Ast.Ident (name, aux_substs substs))
334 | Cic.AMutConstruct (id,uri,i,j,substs) ->
335 let name = constructor_of_inductive_type uri i j in
336 let uri_str = UriManager.string_of_uri uri in
337 let puri_str = sprintf "%s#xpointer(1/%d/%d)" uri_str (i + 1) j in
338 register_uri id (UriManager.uri_of_string puri_str);
339 idref id (Ast.Ident (name, aux_substs substs))
340 | Cic.AMutCase (id,uri,typeno,ty,te,patterns) ->
341 let name = name_of_inductive_type uri typeno in
342 let uri_str = UriManager.string_of_uri uri in
343 let puri_str = sprintf "%s#xpointer(1/%d)" uri_str (typeno+1) in
345 UriManager.uri_of_string
346 (sprintf "%s#xpointer(1/%d/%d)" uri_str (typeno+1) j)
348 let case_indty = name, Some (UriManager.uri_of_string puri_str) in
349 let constructors = constructors_of_inductive_type uri typeno in
350 let rec eat_branch ty pat =
352 | Cic.Prod (_, _, t), Cic.ALambda (_, name, s, t') ->
353 let (cv, rhs) = eat_branch t t' in
354 (CicNotationUtil.name_of_cic_name name, Some (k s)) :: cv, rhs
361 (fun (name, ty) pat ->
363 let (capture_variables, rhs) = eat_branch ty pat in
364 ((name, Some (ctor_puri !j), capture_variables), rhs))
365 constructors patterns
366 with Invalid_argument _ -> assert false
368 idref id (Ast.Case (k te, Some case_indty, Some (k ty), patterns))
369 | Cic.AFix (id, no, funs) ->
372 (fun (_, n, decr_idx, ty, bo) ->
373 ((Ast.Ident (n, None), Some (k ty)), k bo, decr_idx))
378 (match List.nth defs no with
379 | (Ast.Ident (n, _), _), _, _ when n <> "_" -> n
381 with Not_found -> assert false
383 idref id (Ast.LetRec (`Inductive, defs, Ast.Ident (name, None)))
384 | Cic.ACoFix (id, no, funs) ->
387 (fun (_, n, ty, bo) ->
388 ((Ast.Ident (n, None), Some (k ty)), k bo, 0))
393 (match List.nth defs no with
394 | (Ast.Ident (n, _), _), _, _ when n <> "_" -> n
396 with Not_found -> assert false
398 idref id (Ast.LetRec (`CoInductive, defs, Ast.Ident (name, None)))
402 (* persistent state *)
404 let level1_patterns21 = Hashtbl.create 211
405 let level2_patterns32 = Hashtbl.create 211
406 let interpretations = Hashtbl.create 211 (* symb -> id list ref *)
408 let compiled21 = ref None
409 let compiled32 = ref None
411 let pattern21_matrix = ref []
412 let pattern32_matrix = ref []
414 let get_compiled21 () =
415 match !compiled21 with
416 | None -> assert false
417 | Some f -> Lazy.force f
418 let get_compiled32 () =
419 match !compiled32 with
420 | None -> assert false
421 | Some f -> Lazy.force f
423 let set_compiled21 f = compiled21 := Some f
424 let set_compiled32 f = compiled32 := Some f
427 List.fold_right (fun idref t -> Ast.AttributedTerm (`IdRef idref, t))
429 let instantiate21 idrefs env l1 =
430 let rec subst_singleton pos env =
432 Ast.AttributedTerm (attr, t) ->
433 Ast.AttributedTerm (attr, subst_singleton pos env t)
434 | t -> CicNotationUtil.group (subst pos env t)
435 and subst pos env = function
436 | Ast.AttributedTerm (attr, t) as term ->
437 prerr_endline ("loosing attribute " ^ CicNotationPp.pp_attribute attr);
439 | Ast.Variable var ->
440 let name, expected_ty = CicNotationEnv.declaration_of_var var in
445 prerr_endline ("name " ^ name ^ " not found in environment");
448 assert (CicNotationEnv.well_typed ty value); (* INVARIANT *)
449 (* following assertion should be a conditional that makes this
450 * instantiation fail *)
451 assert (CicNotationEnv.well_typed expected_ty value);
452 [ add_pos_info pos (CicNotationEnv.term_of_value value) ]
453 | Ast.Magic m -> subst_magic pos env m
454 | Ast.Literal l as t ->
455 let t = add_idrefs idrefs t in
457 | `Keyword k -> [ add_keyword_attrs t ]
459 | Ast.Layout l -> [ Ast.Layout (subst_layout pos env l) ]
460 | t -> [ CicNotationUtil.visit_ast (subst_singleton pos env) t ]
461 and subst_magic pos env = function
462 | Ast.List0 (p, sep_opt)
463 | Ast.List1 (p, sep_opt) ->
464 let rec_decls = CicNotationEnv.declarations_of_term p in
466 List.map (fun (n, _) -> CicNotationEnv.lookup_list env n) rec_decls
468 let values = CicNotationUtil.ncombine rec_values in
472 | Some l -> [ Ast.Literal l ]
474 let rec instantiate_list acc = function
477 let env = CicNotationEnv.combine rec_decls value_set in
478 instantiate_list (CicNotationUtil.group (subst pos env p) :: acc)
481 let env = CicNotationEnv.combine rec_decls value_set in
482 let terms = subst pos env p in
483 instantiate_list (CicNotationUtil.group (terms @ sep) :: acc) tl
485 instantiate_list [] values
487 let opt_decls = CicNotationEnv.declarations_of_term p in
489 let rec build_env = function
491 | (name, ty) :: tl ->
492 (* assumption: if one of the value is None then all are *)
493 (match CicNotationEnv.lookup_opt env name with
495 | Some v -> (name, (ty, v)) :: build_env tl)
497 try build_env opt_decls with Exit -> []
502 | _ -> subst pos env p
504 | _ -> assert false (* impossible *)
505 and subst_layout pos env = function
506 | Ast.Box (kind, tl) ->
507 let tl' = subst_children pos env tl in
508 Ast.Box (kind, List.concat tl')
509 | l -> CicNotationUtil.visit_layout (subst_singleton pos env) l
510 and subst_children pos env =
518 | `None -> assert false
521 [ subst pos' env child ]
527 | `None -> assert false
530 (subst pos env hd) :: subst_children pos' env tl
532 subst_singleton `Left env l1
534 let rec pp_ast1 term =
535 let rec pp_value = function
536 | CicNotationEnv.NumValue _ as v -> v
537 | CicNotationEnv.StringValue _ as v -> v
538 (* | CicNotationEnv.TermValue t when t == term -> CicNotationEnv.TermValue (pp_ast0 t pp_ast1) *)
539 | CicNotationEnv.TermValue t -> CicNotationEnv.TermValue (pp_ast1 t)
540 | CicNotationEnv.OptValue None as v -> v
541 | CicNotationEnv.OptValue (Some v) ->
542 CicNotationEnv.OptValue (Some (pp_value v))
543 | CicNotationEnv.ListValue vl ->
544 CicNotationEnv.ListValue (List.map pp_value vl)
546 let ast_env_of_env env =
547 List.map (fun (var, (ty, value)) -> (var, (ty, pp_value value))) env
549 (* prerr_endline ("pattern matching from 2 to 1 on term " ^ CicNotationPp.pp_term term); *)
551 | Ast.AttributedTerm (attrs, term') ->
552 Ast.AttributedTerm (attrs, pp_ast1 term')
554 (match (get_compiled21 ()) term with
555 | None -> pp_ast0 term pp_ast1
556 | Some (env, ctors, pid) ->
558 List.flatten (List.map CicNotationUtil.get_idrefs ctors)
560 let prec, assoc, l1 =
562 Hashtbl.find level1_patterns21 pid
563 with Not_found -> assert false
565 add_level_info prec assoc
566 (instantiate21 idrefs (ast_env_of_env env) l1))
568 let instantiate32 term_info idrefs env symbol args =
569 let rec instantiate_arg = function
570 | Ast.IdentArg (n, name) ->
571 let t = (try List.assoc name env with Not_found -> assert false) in
572 let rec count_lambda = function
573 | Ast.AttributedTerm (_, t) -> count_lambda t
574 | Ast.Binder (`Lambda, _, body) -> 1 + count_lambda body
577 let rec add_lambda t n =
579 let name = CicNotationUtil.fresh_name () in
580 Ast.Binder (`Lambda, (Ast.Ident (name, None), None),
581 Ast.Appl [add_lambda t (n - 1); Ast.Ident (name, None)])
585 add_lambda t (n - count_lambda t)
588 let symbol = Ast.Symbol (symbol, 0) in
589 add_idrefs idrefs symbol
591 if args = [] then head
592 else Ast.Appl (head :: List.map instantiate_arg args)
594 let rec ast_of_acic1 term_info annterm =
595 let id_to_uris = term_info.uri in
596 let register_uri id uri = Hashtbl.add id_to_uris id uri in
597 match (get_compiled32 ()) annterm with
598 | None -> ast_of_acic0 term_info annterm ast_of_acic1
599 | Some (env, ctors, pid) ->
603 let idref = CicUtil.id_of_annterm annterm in
606 (CicUtil.uri_of_term (Deannotate.deannotate_term annterm))
607 with Invalid_argument _ -> ());
612 List.map (fun (name, term) -> (name, ast_of_acic1 term_info term)) env
614 let _, symbol, args, _ =
616 Hashtbl.find level2_patterns32 pid
617 with Not_found -> assert false
619 let ast = instantiate32 term_info idrefs env' symbol args in
620 Ast.AttributedTerm (`IdRef (CicUtil.id_of_annterm annterm), ast)
622 let load_patterns32 t =
623 set_compiled32 (lazy (CicNotationMatcher.Matcher32.compiler t))
625 let load_patterns21 t =
626 set_compiled21 (lazy (CicNotationMatcher.Matcher21.compiler t))
628 let ast_of_acic id_to_sort annterm =
629 debug_print (lazy ("ast_of_acic <- "
630 ^ CicPp.ppterm (Deannotate.deannotate_term annterm)));
631 let term_info = { sort = id_to_sort; uri = Hashtbl.create 211 } in
632 let ast = ast_of_acic1 term_info annterm in
633 debug_print (lazy ("ast_of_acic -> " ^ CicNotationPp.pp_term ast));
637 debug_print (lazy "pp_ast <-");
638 let ast' = pp_ast1 ast in
639 debug_print (lazy ("pp_ast -> " ^ CicNotationPp.pp_term ast'));
643 let counter = ref ~-1 in
648 let add_interpretation dsc (symbol, args) appl_pattern =
649 let id = fresh_id () in
650 Hashtbl.add level2_patterns32 id (dsc, symbol, args, appl_pattern);
651 pattern32_matrix := (appl_pattern, id) :: !pattern32_matrix;
652 load_patterns32 !pattern32_matrix;
654 let ids = Hashtbl.find interpretations symbol in
656 with Not_found -> Hashtbl.add interpretations symbol (ref [id]));
659 exception Interpretation_not_found
660 exception Pretty_printer_not_found
662 let rec list_uniq = function
665 | h1::h2::tl when h1 = h2 -> list_uniq (h2 :: tl)
666 | h1::tl (* when h1 <> h2 *) -> h1 :: list_uniq tl
668 let lookup_interpretations symbol =
671 (List.sort Pervasives.compare
674 let (dsc, _, args, appl_pattern) =
676 Hashtbl.find level2_patterns32 id
677 with Not_found -> assert false
679 dsc, args, appl_pattern)
680 !(Hashtbl.find interpretations symbol)))
681 with Not_found -> raise Interpretation_not_found
683 let add_pretty_printer ~precedence ~associativity l2 l1 =
684 let id = fresh_id () in
685 let l2' = CicNotationUtil.strip_attributes l2 in
686 Hashtbl.add level1_patterns21 id (precedence, associativity, l1);
687 pattern21_matrix := (l2', id) :: !pattern21_matrix;
688 load_patterns21 !pattern21_matrix;
691 let remove_interpretation id =
693 let _, symbol, _, _ = Hashtbl.find level2_patterns32 id in
694 let ids = Hashtbl.find interpretations symbol in
695 ids := List.filter ((<>) id) !ids;
696 Hashtbl.remove level2_patterns32 id;
697 with Not_found -> raise Interpretation_not_found);
698 pattern32_matrix := List.filter (fun (_, id') -> id <> id') !pattern32_matrix;
699 load_patterns32 !pattern32_matrix
701 let remove_pretty_printer id =
703 Hashtbl.remove level1_patterns21 id;
704 with Not_found -> raise Pretty_printer_not_found);
705 pattern21_matrix := List.filter (fun (_, id') -> id <> id') !pattern21_matrix;
706 load_patterns21 !pattern21_matrix