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/
29 type interpretation_id = pattern_id
30 type pretty_printer_id = pattern_id
32 module Ast = CicNotationPt
35 { sort: (Cic.id, Ast.sort_kind) Hashtbl.t;
36 uri: (Cic.id, string) Hashtbl.t;
40 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
42 | Cic.InductiveDefinition (l,_,_,_) -> l
45 let name_of_inductive_type uri i =
46 let types = get_types uri in
47 let (name, _, _, _) = try List.nth types i with Not_found -> assert false in
50 (* returns <name, type> pairs *)
51 let constructors_of_inductive_type uri i =
52 let types = get_types uri in
53 let (_, _, _, constructors) =
54 try List.nth types i with Not_found -> assert false
58 (* returns name only *)
59 let constructor_of_inductive_type uri i j =
61 fst (List.nth (constructors_of_inductive_type uri i) (j-1))
62 with Not_found -> assert false)
64 let idref id t = Ast.AttributedTerm (`IdRef id, t)
66 let resolve_binder = function
67 | `Lambda -> "\\lambda"
69 | `Forall -> "\\forall"
70 | `Exists -> "\\exists"
72 let add_level_info prec assoc t = Ast.AttributedTerm (`Level (prec, assoc), t)
74 let rec remove_level_info =
76 | Ast.AttributedTerm (`Level _, t) -> remove_level_info t
77 | Ast.AttributedTerm (a, t) -> Ast.AttributedTerm (a, remove_level_info t)
80 let add_xml_attrs attrs t = Ast.AttributedTerm (`XmlAttrs attrs, t)
81 let add_keyword_attrs =
82 add_xml_attrs (RenderingAttrs.keyword_attributes `MathML)
83 let box kind spacing indent content =
84 Ast.Layout (Ast.Box ((kind, spacing, indent), content))
87 let hvbox = box Ast.HV
88 let hovbox = box Ast.HOV
89 let break = Ast.Layout Ast.Break
90 let reset_href t = Ast.AttributedTerm (`Href [], t)
91 let builtin_symbol s = reset_href (Ast.Literal (`Symbol s))
92 let keyword k = reset_href (add_keyword_attrs (Ast.Literal (`Keyword k)))
95 (add_xml_attrs (RenderingAttrs.number_attributes `MathML)
96 (Ast.Literal (`Number s)))
98 add_xml_attrs (RenderingAttrs.ident_attributes `MathML) (Ast.Ident (i, None))
100 add_xml_attrs (RenderingAttrs.builtin_symbol_attributes `MathML)
103 let string_of_sort_kind = function
110 let rec aux = function
112 add_level_info Ast.apply_prec Ast.apply_assoc
113 (hovbox true true (CicNotationUtil.dress break (List.map k ts)))
114 | Ast.Binder (binder_kind, (id, ty), body) ->
115 add_level_info Ast.binder_prec Ast.binder_assoc
117 [ binder_symbol (resolve_binder binder_kind);
118 k id; builtin_symbol ":"; aux_ty ty; break;
119 builtin_symbol "."; k body ])
120 | Ast.Case (what, indty_opt, outty_opt, patterns) ->
125 [ builtin_symbol "["; remove_level_info (k outty);
126 builtin_symbol "]"; break ]
131 | Some indty -> [ keyword "in"; ident indty ]
135 keyword "match"; break;
136 hvbox false false ([ k what ] @ indty_box); break;
139 let mk_case_pattern (head, vars) =
140 hbox true false (ident head :: List.map aux_var vars)
148 mk_case_pattern lhs; builtin_symbol "\\Rightarrow" ];
153 let rec aux_patterns = function
159 last; builtin_symbol "]" ] ]
161 [ break; hbox false false [ builtin_symbol "|"; hd ] ]
166 [ hbox false false [ builtin_symbol "["; builtin_symbol "]" ] ]
169 builtin_symbol "["; one; builtin_symbol "]" ] ]
171 hbox false false [ builtin_symbol "["; hd ]
174 add_level_info Ast.simple_prec Ast.simple_assoc
176 hvbox false false (outty_box @ [ match_box ]); break;
177 hbox false false [ hvbox false false patterns'' ] ])
178 | Ast.Cast (bo, ty) ->
179 add_level_info Ast.simple_prec Ast.simple_assoc
181 builtin_symbol "("; k bo; break; builtin_symbol ":"; k ty;
183 | Ast.LetIn (var, s, t) ->
184 add_level_info Ast.let_in_prec Ast.let_in_assoc
189 aux_var var; builtin_symbol "\\def"; break; k s ];
190 break; keyword "in" ];
192 | Ast.LetRec (rec_kind, funs, where) ->
194 match rec_kind with `Inductive -> "rec" | `CoInductive -> "corec"
196 let mk_fun (var, body, _) = aux_var var, k body in
197 let mk_funs = List.map mk_fun in
198 let fst_fun, tl_funs =
199 match mk_funs funs with hd :: tl -> hd, tl | [] -> assert false
202 let (name, body) = fst_fun in
204 keyword "let"; keyword rec_op; name; builtin_symbol "\\def"; break;
212 keyword "and"; name; builtin_symbol "\\def"; break; body ] ])
215 add_level_info Ast.let_in_prec Ast.let_in_assoc
217 (fst_row :: List.flatten tl_rows
218 @ [ break; keyword "in"; break; k where ])))
219 | Ast.Implicit -> builtin_symbol "?"
221 let local_context l =
222 CicNotationUtil.dress (builtin_symbol ";")
223 (List.map (function None -> builtin_symbol "_" | Some t -> k t) l)
226 ([ builtin_symbol "?"; number (string_of_int n) ]
227 @ (if l <> [] then local_context l else []))
228 | Ast.Sort sort -> aux_sort sort
231 | Ast.Ident (_, None) | Ast.Ident (_, Some [])
232 | Ast.Uri (_, None) | Ast.Uri (_, Some [])
234 | Ast.UserInput as leaf -> leaf
235 | t -> CicNotationUtil.visit_ast ~special_k k t
236 and aux_sort sort_kind =
237 add_xml_attrs (RenderingAttrs.keyword_attributes `MathML)
238 (Ast.Ident (string_of_sort_kind sort_kind, None))
239 and aux_ty = function
240 | None -> builtin_symbol "?"
242 and aux_var = function
245 builtin_symbol "("; name; builtin_symbol ":"; break; k ty;
248 and special_k = function
249 | Ast.AttributedTerm (attrs, t) -> Ast.AttributedTerm (attrs, k t)
251 prerr_endline ("unexpected special: " ^ CicNotationPp.pp_term t);
256 let ast_of_acic0 term_info acic k =
257 let k = k term_info in
258 let register_uri id uri = Hashtbl.add term_info.uri id uri in
261 Hashtbl.find term_info.sort id
263 prerr_endline (sprintf "warning: sort of id %s not found, using Type" id);
266 let aux_substs substs =
269 (fun (uri, annterm) -> (UriManager.name_of_uri uri, k annterm))
272 let aux_context context =
276 | Some annterm -> Some (k annterm))
280 | Cic.ARel (id,_,_,b) -> idref id (Ast.Ident (b, None))
281 | Cic.AVar (id,uri,substs) ->
282 register_uri id (UriManager.string_of_uri uri);
283 idref id (Ast.Ident (UriManager.name_of_uri uri, aux_substs substs))
284 | Cic.AMeta (id,n,l) -> idref id (Ast.Meta (n, aux_context l))
285 | Cic.ASort (id,Cic.Prop) -> idref id (Ast.Sort `Prop)
286 | Cic.ASort (id,Cic.Set) -> idref id (Ast.Sort `Set)
287 | Cic.ASort (id,Cic.Type _) -> idref id (Ast.Sort `Type)
288 | Cic.ASort (id,Cic.CProp) -> idref id (Ast.Sort `CProp)
289 | Cic.AImplicit _ -> assert false
290 | Cic.AProd (id,n,s,t) ->
292 match sort_of_id id with
293 | `Set | `Type -> `Pi
294 | `Prop | `CProp -> `Forall
296 idref id (Ast.Binder (binder_kind,
297 (CicNotationUtil.name_of_cic_name n, Some (k s)), k t))
298 | Cic.ACast (id,v,t) -> idref id (Ast.Cast (k v, k t))
299 | Cic.ALambda (id,n,s,t) ->
300 idref id (Ast.Binder (`Lambda,
301 (CicNotationUtil.name_of_cic_name n, Some (k s)), k t))
302 | Cic.ALetIn (id,n,s,t) ->
303 idref id (Ast.LetIn ((CicNotationUtil.name_of_cic_name n, None),
305 | Cic.AAppl (aid,args) -> idref aid (Ast.Appl (List.map k args))
306 | Cic.AConst (id,uri,substs) ->
307 register_uri id (UriManager.string_of_uri uri);
308 idref id (Ast.Ident (UriManager.name_of_uri uri, aux_substs substs))
309 | Cic.AMutInd (id,uri,i,substs) as t ->
310 let name = name_of_inductive_type uri i in
311 let uri_str = UriManager.string_of_uri uri in
313 uri_str ^ "#xpointer(1/" ^ (string_of_int (i + 1)) ^ ")"
315 register_uri id puri_str;
316 idref id (Ast.Ident (name, aux_substs substs))
317 | Cic.AMutConstruct (id,uri,i,j,substs) ->
318 let name = constructor_of_inductive_type uri i j in
319 let uri_str = UriManager.string_of_uri uri in
320 let puri_str = sprintf "%s#xpointer(1/%d/%d)" uri_str (i + 1) j in
321 register_uri id puri_str;
322 idref id (Ast.Ident (name, aux_substs substs))
323 | Cic.AMutCase (id,uri,typeno,ty,te,patterns) ->
324 let name = name_of_inductive_type uri typeno in
325 let constructors = constructors_of_inductive_type uri typeno in
326 let rec eat_branch ty pat =
328 | Cic.Prod (_, _, t), Cic.ALambda (_, name, s, t') ->
329 let (cv, rhs) = eat_branch t t' in
330 (CicNotationUtil.name_of_cic_name name, Some (k s)) :: cv, rhs
335 (fun (name, ty) pat ->
336 let (capture_variables, rhs) = eat_branch ty pat in
337 ((name, capture_variables), rhs))
338 constructors patterns
340 idref id (Ast.Case (k te, Some name, Some (k ty), patterns))
341 | Cic.AFix (id, no, funs) ->
344 (fun (_, n, decr_idx, ty, bo) ->
345 ((Ast.Ident (n, None), Some (k ty)), k bo, decr_idx))
350 (match List.nth defs no with
351 | (Ast.Ident (n, _), _), _, _ when n <> "_" -> n
353 with Not_found -> assert false
355 idref id (Ast.LetRec (`Inductive, defs, Ast.Ident (name, None)))
356 | Cic.ACoFix (id, no, funs) ->
359 (fun (_, n, ty, bo) ->
360 ((Ast.Ident (n, None), Some (k ty)), k bo, 0))
365 (match List.nth defs no with
366 | (Ast.Ident (n, _), _), _, _ when n <> "_" -> n
368 with Not_found -> assert false
370 idref id (Ast.LetRec (`CoInductive, defs, Ast.Ident (name, None)))
374 (* persistent state *)
376 let level1_patterns21 = Hashtbl.create 211
377 let level2_patterns32 = Hashtbl.create 211
378 let interpretations = Hashtbl.create 211 (* symb -> id list ref *)
380 let compiled21 = ref None
381 let compiled32 = ref None
383 let pattern21_matrix = ref []
384 let pattern32_matrix = ref []
386 let get_compiled21 () =
387 match !compiled21 with
388 | None -> assert false
389 | Some f -> Lazy.force f
390 let get_compiled32 () =
391 match !compiled32 with
392 | None -> assert false
393 | Some f -> Lazy.force f
395 let set_compiled21 f = compiled21 := Some f
396 let set_compiled32 f = compiled32 := Some f
398 let instantiate21 env (* precedence associativity *) l1 =
399 let rec subst_singleton env t =
400 CicNotationUtil.group (subst env t)
401 and subst env = function
402 | Ast.AttributedTerm (_, t) -> subst env t
403 | Ast.Variable var ->
404 let name, expected_ty = CicNotationEnv.declaration_of_var var in
408 with Not_found -> assert false
410 assert (CicNotationEnv.well_typed ty value); (* INVARIANT *)
411 (* following assertion should be a conditional that makes this
412 * instantiation fail *)
413 assert (CicNotationEnv.well_typed expected_ty value);
414 [ CicNotationEnv.term_of_value value ]
415 | Ast.Magic m -> subst_magic env m
416 | Ast.Literal (`Keyword k) as t -> [ (*reset_href*) (add_keyword_attrs t) ]
417 | Ast.Literal _ as t -> [ (*reset_href*) t ]
418 | Ast.Layout l -> [ Ast.Layout (subst_layout env l) ]
419 | t -> [ CicNotationUtil.visit_ast (subst_singleton env) t ]
420 and subst_magic env = function
421 | Ast.List0 (p, sep_opt)
422 | Ast.List1 (p, sep_opt) ->
423 let rec_decls = CicNotationEnv.declarations_of_term p in
425 List.map (fun (n, _) -> CicNotationEnv.lookup_list env n) rec_decls
427 let values = CicNotationUtil.ncombine rec_values in
431 | Some l -> [ Ast.Literal l ]
433 let rec instantiate_list acc = function
436 let env = CicNotationEnv.combine rec_decls value_set in
437 instantiate_list (CicNotationUtil.group (subst env p) :: acc) []
439 let env = CicNotationEnv.combine rec_decls value_set in
441 (CicNotationUtil.group ((subst env p) @ sep) :: acc) tl
443 instantiate_list [] values
445 let opt_decls = CicNotationEnv.declarations_of_term p in
447 let rec build_env = function
449 | (name, ty) :: tl ->
450 (* assumption: if one of the value is None then all are *)
451 (match CicNotationEnv.lookup_opt env name with
453 | Some v -> (name, (ty, v)) :: build_env tl)
455 try build_env opt_decls with Exit -> []
462 | _ -> assert false (* impossible *)
463 and subst_layout env = function
464 | Ast.Box (kind, tl) ->
465 Ast.Box (kind, List.concat (List.map (subst env) tl))
466 | l -> CicNotationUtil.visit_layout (subst_singleton env) l
468 subst_singleton env l1
470 let rec pp_ast1 term =
471 let rec pp_value = function
472 | CicNotationEnv.NumValue _ as v -> v
473 | CicNotationEnv.StringValue _ as v -> v
474 (* | CicNotationEnv.TermValue t when t == term -> CicNotationEnv.TermValue (pp_ast0 t pp_ast1) *)
475 | CicNotationEnv.TermValue t -> CicNotationEnv.TermValue (pp_ast1 t)
476 | CicNotationEnv.OptValue None as v -> v
477 | CicNotationEnv.OptValue (Some v) ->
478 CicNotationEnv.OptValue (Some (pp_value v))
479 | CicNotationEnv.ListValue vl ->
480 CicNotationEnv.ListValue (List.map pp_value vl)
482 let ast_env_of_env env =
483 List.map (fun (var, (ty, value)) -> (var, (ty, pp_value value))) env
486 | Ast.AttributedTerm (attrs, t) -> Ast.AttributedTerm (attrs, pp_ast1 t)
488 (match (get_compiled21 ()) term with
489 | None -> pp_ast0 term pp_ast1
491 let prec, assoc, l1 =
493 Hashtbl.find level1_patterns21 pid
494 with Not_found -> assert false
496 add_level_info prec assoc (instantiate21 (ast_env_of_env env) l1))
498 let instantiate32 term_info env symbol args =
499 let rec instantiate_arg = function
500 | Ast.IdentArg (n, name) ->
501 let t = (try List.assoc name env with Not_found -> assert false) in
502 let rec count_lambda = function
503 | Ast.Binder (`Lambda, _, body) -> 1 + count_lambda body
506 let rec add_lambda t n =
508 let name = CicNotationUtil.fresh_name () in
509 Ast.Binder (`Lambda, (Ast.Ident (name, None), None),
510 Ast.Appl [add_lambda t (n - 1); Ast.Ident (name, None)])
514 add_lambda t (n - count_lambda t)
516 let head = Ast.Symbol (symbol, 0) in
519 | _ -> Ast.Appl (head :: List.map instantiate_arg args)
521 let rec ast_of_acic1 term_info annterm =
522 match (get_compiled32 ()) annterm with
523 | None -> ast_of_acic0 term_info annterm ast_of_acic1
526 List.map (fun (name, term) -> (name, ast_of_acic1 term_info term)) env
528 let _, symbol, args, _, uris =
530 Hashtbl.find level2_patterns32 pid
531 with Not_found -> assert false
533 let ast = instantiate32 term_info env' symbol args in
534 Ast.AttributedTerm (`IdRef (CicUtil.id_of_annterm annterm),
537 | _ -> Ast.AttributedTerm (`Href uris, ast)))
539 let load_patterns32 t =
540 set_compiled32 (lazy (CicNotationMatcher.Matcher32.compiler t))
542 let load_patterns21 t =
543 set_compiled21 (lazy (CicNotationMatcher.Matcher21.compiler t))
545 let ast_of_acic id_to_sort annterm =
546 let term_info = { sort = id_to_sort; uri = Hashtbl.create 211 } in
547 let ast = ast_of_acic1 term_info annterm in
551 (* prerr_endline ("pp_ast <- : " ^ CicNotationPp.pp_term term); *)
555 let counter = ref ~-1 in
560 let add_interpretation dsc (symbol, args) appl_pattern =
561 let id = fresh_id () in
562 let uris = CicNotationUtil.find_appl_pattern_uris appl_pattern in
563 Hashtbl.add level2_patterns32 id (dsc, symbol, args, appl_pattern, uris);
564 pattern32_matrix := (appl_pattern, id) :: !pattern32_matrix;
565 load_patterns32 !pattern32_matrix;
567 let ids = Hashtbl.find interpretations symbol in
569 with Not_found -> Hashtbl.add interpretations symbol (ref [id]));
572 exception Interpretation_not_found
573 exception Pretty_printer_not_found
575 let rec list_uniq = function
578 | h1::h2::tl when h1 = h2 -> list_uniq (h2 :: tl)
579 | h1::tl (* when h1 <> h2 *) -> h1 :: list_uniq tl
581 let lookup_interpretations symbol =
584 (List.sort Pervasives.compare
587 let (dsc, _, args, appl_pattern, _) =
589 Hashtbl.find level2_patterns32 id
590 with Not_found -> assert false
592 dsc, args, appl_pattern)
593 !(Hashtbl.find interpretations symbol)))
594 with Not_found -> raise Interpretation_not_found
596 let add_pretty_printer ~precedence ~associativity l2 l1 =
597 let id = fresh_id () in
598 let l2' = CicNotationUtil.strip_attributes l2 in
599 Hashtbl.add level1_patterns21 id (precedence, associativity, l1);
600 pattern21_matrix := (l2', id) :: !pattern21_matrix;
601 load_patterns21 !pattern21_matrix;
604 let remove_interpretation id =
606 let _, symbol, _, _, _ = Hashtbl.find level2_patterns32 id in
607 let ids = Hashtbl.find interpretations symbol in
608 ids := List.filter ((<>) id) !ids;
609 Hashtbl.remove level2_patterns32 id;
610 with Not_found -> raise Interpretation_not_found);
611 pattern32_matrix := List.filter (fun (_, id') -> id <> id') !pattern32_matrix;
612 load_patterns32 !pattern32_matrix
614 let remove_pretty_printer id =
616 Hashtbl.remove level1_patterns21 id;
617 with Not_found -> raise Pretty_printer_not_found);
618 pattern21_matrix := List.filter (fun (_, id') -> id <> id') !pattern21_matrix;
619 load_patterns21 !pattern21_matrix