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
262 with Not_found -> assert false
264 let aux_substs substs =
267 (fun (uri, annterm) -> (UriManager.name_of_uri uri, k annterm))
270 let aux_context context =
274 | Some annterm -> Some (k annterm))
278 | Cic.ARel (id,_,_,b) -> idref id (Ast.Ident (b, None))
279 | Cic.AVar (id,uri,substs) ->
280 register_uri id (UriManager.string_of_uri uri);
281 idref id (Ast.Ident (UriManager.name_of_uri uri, aux_substs substs))
282 | Cic.AMeta (id,n,l) -> idref id (Ast.Meta (n, aux_context l))
283 | Cic.ASort (id,Cic.Prop) -> idref id (Ast.Sort `Prop)
284 | Cic.ASort (id,Cic.Set) -> idref id (Ast.Sort `Set)
285 | Cic.ASort (id,Cic.Type _) -> idref id (Ast.Sort `Type)
286 | Cic.ASort (id,Cic.CProp) -> idref id (Ast.Sort `CProp)
287 | Cic.AImplicit _ -> assert false
288 | Cic.AProd (id,n,s,t) ->
290 match sort_of_id id with
291 | `Set | `Type -> `Pi
292 | `Prop | `CProp -> `Forall
294 idref id (Ast.Binder (binder_kind,
295 (CicNotationUtil.name_of_cic_name n, Some (k s)), k t))
296 | Cic.ACast (id,v,t) -> idref id (Ast.Cast (k v, k t))
297 | Cic.ALambda (id,n,s,t) ->
298 idref id (Ast.Binder (`Lambda,
299 (CicNotationUtil.name_of_cic_name n, Some (k s)), k t))
300 | Cic.ALetIn (id,n,s,t) ->
301 idref id (Ast.LetIn ((CicNotationUtil.name_of_cic_name n, None),
303 | Cic.AAppl (aid,args) -> idref aid (Ast.Appl (List.map k args))
304 | Cic.AConst (id,uri,substs) ->
305 register_uri id (UriManager.string_of_uri uri);
306 idref id (Ast.Ident (UriManager.name_of_uri uri, aux_substs substs))
307 | Cic.AMutInd (id,uri,i,substs) as t ->
308 let name = name_of_inductive_type uri i in
309 let uri_str = UriManager.string_of_uri uri in
311 uri_str ^ "#xpointer(1/" ^ (string_of_int (i + 1)) ^ ")"
313 register_uri id puri_str;
314 idref id (Ast.Ident (name, aux_substs substs))
315 | Cic.AMutConstruct (id,uri,i,j,substs) ->
316 let name = constructor_of_inductive_type uri i j in
317 let uri_str = UriManager.string_of_uri uri in
318 let puri_str = sprintf "%s#xpointer(1/%d/%d)" uri_str (i + 1) j in
319 register_uri id puri_str;
320 idref id (Ast.Ident (name, aux_substs substs))
321 | Cic.AMutCase (id,uri,typeno,ty,te,patterns) ->
322 let name = name_of_inductive_type uri typeno in
323 let constructors = constructors_of_inductive_type uri typeno in
324 let rec eat_branch ty pat =
326 | Cic.Prod (_, _, t), Cic.ALambda (_, name, s, t') ->
327 let (cv, rhs) = eat_branch t t' in
328 (CicNotationUtil.name_of_cic_name name, Some (k s)) :: cv, rhs
333 (fun (name, ty) pat ->
334 let (capture_variables, rhs) = eat_branch ty pat in
335 ((name, capture_variables), rhs))
336 constructors patterns
338 idref id (Ast.Case (k te, Some name, Some (k ty), patterns))
339 | Cic.AFix (id, no, funs) ->
342 (fun (_, n, decr_idx, ty, bo) ->
343 ((Ast.Ident (n, None), Some (k ty)), k bo, decr_idx))
348 (match List.nth defs no with
349 | (Ast.Ident (n, _), _), _, _ when n <> "_" -> n
351 with Not_found -> assert false
353 idref id (Ast.LetRec (`Inductive, defs, Ast.Ident (name, None)))
354 | Cic.ACoFix (id, no, funs) ->
357 (fun (_, n, ty, bo) ->
358 ((Ast.Ident (n, None), Some (k ty)), k bo, 0))
363 (match List.nth defs no with
364 | (Ast.Ident (n, _), _), _, _ when n <> "_" -> n
366 with Not_found -> assert false
368 idref id (Ast.LetRec (`CoInductive, defs, Ast.Ident (name, None)))
372 (* persistent state *)
374 let level1_patterns21 = Hashtbl.create 211
375 let level2_patterns32 = Hashtbl.create 211
376 let interpretations = Hashtbl.create 211 (* symb -> id list ref *)
378 let compiled21 = ref None
379 let compiled32 = ref None
381 let pattern21_matrix = ref []
382 let pattern32_matrix = ref []
384 let get_compiled21 () =
385 match !compiled21 with
386 | None -> assert false
387 | Some f -> Lazy.force f
388 let get_compiled32 () =
389 match !compiled32 with
390 | None -> assert false
391 | Some f -> Lazy.force f
393 let set_compiled21 f = compiled21 := Some f
394 let set_compiled32 f = compiled32 := Some f
396 let instantiate21 env (* precedence associativity *) l1 =
397 let rec subst_singleton env t =
398 CicNotationUtil.group (subst env t)
399 and subst env = function
400 | Ast.AttributedTerm (_, t) -> subst env t
401 | Ast.Variable var ->
402 let name, expected_ty = CicNotationEnv.declaration_of_var var in
406 with Not_found -> assert false
408 assert (CicNotationEnv.well_typed ty value); (* INVARIANT *)
409 (* following assertion should be a conditional that makes this
410 * instantiation fail *)
411 assert (CicNotationEnv.well_typed expected_ty value);
412 [ CicNotationEnv.term_of_value value ]
413 | Ast.Magic m -> subst_magic env m
414 | Ast.Literal (`Keyword k) as t -> [ (*reset_href*) (add_keyword_attrs t) ]
415 | Ast.Literal _ as t -> [ (*reset_href*) t ]
416 | Ast.Layout l -> [ Ast.Layout (subst_layout env l) ]
417 | t -> [ CicNotationUtil.visit_ast (subst_singleton env) t ]
418 and subst_magic env = function
419 | Ast.List0 (p, sep_opt)
420 | Ast.List1 (p, sep_opt) ->
421 let rec_decls = CicNotationEnv.declarations_of_term p in
423 List.map (fun (n, _) -> CicNotationEnv.lookup_list env n) rec_decls
425 let values = CicNotationUtil.ncombine rec_values in
429 | Some l -> [ Ast.Literal l ]
431 let rec instantiate_list acc = function
434 let env = CicNotationEnv.combine rec_decls value_set in
435 instantiate_list (CicNotationUtil.group (subst env p) :: acc) []
437 let env = CicNotationEnv.combine rec_decls value_set in
439 (CicNotationUtil.group ((subst env p) @ sep) :: acc) tl
441 instantiate_list [] values
443 let opt_decls = CicNotationEnv.declarations_of_term p in
445 let rec build_env = function
447 | (name, ty) :: tl ->
448 (* assumption: if one of the value is None then all are *)
449 (match CicNotationEnv.lookup_opt env name with
451 | Some v -> (name, (ty, v)) :: build_env tl)
453 try build_env opt_decls with Exit -> []
460 | _ -> assert false (* impossible *)
461 and subst_layout env = function
462 | Ast.Box (kind, tl) ->
463 Ast.Box (kind, List.concat (List.map (subst env) tl))
464 | l -> CicNotationUtil.visit_layout (subst_singleton env) l
466 subst_singleton env l1
468 let rec pp_ast1 term =
469 let rec pp_value = function
470 | CicNotationEnv.NumValue _ as v -> v
471 | CicNotationEnv.StringValue _ as v -> v
472 (* | CicNotationEnv.TermValue t when t == term -> CicNotationEnv.TermValue (pp_ast0 t pp_ast1) *)
473 | CicNotationEnv.TermValue t -> CicNotationEnv.TermValue (pp_ast1 t)
474 | CicNotationEnv.OptValue None as v -> v
475 | CicNotationEnv.OptValue (Some v) ->
476 CicNotationEnv.OptValue (Some (pp_value v))
477 | CicNotationEnv.ListValue vl ->
478 CicNotationEnv.ListValue (List.map pp_value vl)
480 let ast_env_of_env env =
481 List.map (fun (var, (ty, value)) -> (var, (ty, pp_value value))) env
484 | Ast.AttributedTerm (attrs, t) -> Ast.AttributedTerm (attrs, pp_ast1 t)
486 (match (get_compiled21 ()) term with
487 | None -> pp_ast0 term pp_ast1
489 let prec, assoc, l1 =
491 Hashtbl.find level1_patterns21 pid
492 with Not_found -> assert false
494 add_level_info prec assoc (instantiate21 (ast_env_of_env env) l1))
496 let instantiate32 term_info env symbol args =
497 let rec instantiate_arg = function
498 | Ast.IdentArg (n, name) ->
499 let t = (try List.assoc name env with Not_found -> assert false) in
500 let rec count_lambda = function
501 | Ast.Binder (`Lambda, _, body) -> 1 + count_lambda body
504 let rec add_lambda t n =
506 let name = CicNotationUtil.fresh_name () in
507 Ast.Binder (`Lambda, (Ast.Ident (name, None), None),
508 Ast.Appl [add_lambda t (n - 1); Ast.Ident (name, None)])
512 add_lambda t (n - count_lambda t)
514 let head = Ast.Symbol (symbol, 0) in
517 | _ -> Ast.Appl (head :: List.map instantiate_arg args)
519 let rec ast_of_acic1 term_info annterm =
520 match (get_compiled32 ()) annterm with
521 | None -> ast_of_acic0 term_info annterm ast_of_acic1
524 List.map (fun (name, term) -> (name, ast_of_acic1 term_info term)) env
526 let _, symbol, args, _, uris =
528 Hashtbl.find level2_patterns32 pid
529 with Not_found -> assert false
531 let ast = instantiate32 term_info env' symbol args in
532 Ast.AttributedTerm (`IdRef (CicUtil.id_of_annterm annterm),
535 | _ -> Ast.AttributedTerm (`Href uris, ast)))
537 let load_patterns32 t =
538 set_compiled32 (lazy (CicNotationMatcher.Matcher32.compiler t))
540 let load_patterns21 t =
541 set_compiled21 (lazy (CicNotationMatcher.Matcher21.compiler t))
543 let ast_of_acic id_to_sort annterm =
544 let term_info = { sort = id_to_sort; uri = Hashtbl.create 211 } in
545 let ast = ast_of_acic1 term_info annterm in
549 (* prerr_endline ("pp_ast <- : " ^ CicNotationPp.pp_term term); *)
553 let counter = ref ~-1 in
558 let add_interpretation dsc (symbol, args) appl_pattern =
559 let id = fresh_id () in
560 let uris = CicNotationUtil.find_appl_pattern_uris appl_pattern in
561 Hashtbl.add level2_patterns32 id (dsc, symbol, args, appl_pattern, uris);
562 pattern32_matrix := (appl_pattern, id) :: !pattern32_matrix;
563 load_patterns32 !pattern32_matrix;
565 let ids = Hashtbl.find interpretations symbol in
567 with Not_found -> Hashtbl.add interpretations symbol (ref [id]));
570 exception Interpretation_not_found
571 exception Pretty_printer_not_found
573 let rec list_uniq = function
576 | h1::h2::tl when h1 = h2 -> list_uniq (h2 :: tl)
577 | h1::tl (* when h1 <> h2 *) -> h1 :: list_uniq tl
579 let lookup_interpretations symbol =
582 (List.sort Pervasives.compare
585 let (dsc, _, args, appl_pattern, _) =
587 Hashtbl.find level2_patterns32 id
588 with Not_found -> assert false
590 dsc, args, appl_pattern)
591 !(Hashtbl.find interpretations symbol)))
592 with Not_found -> raise Interpretation_not_found
594 let add_pretty_printer ~precedence ~associativity l2 l1 =
595 let id = fresh_id () in
596 let l2' = CicNotationUtil.strip_attributes l2 in
597 Hashtbl.add level1_patterns21 id (precedence, associativity, l1);
598 pattern21_matrix := (l2', id) :: !pattern21_matrix;
599 load_patterns21 !pattern21_matrix;
602 let remove_interpretation id =
604 let _, symbol, _, _, _ = Hashtbl.find level2_patterns32 id in
605 let ids = Hashtbl.find interpretations symbol in
606 ids := List.filter ((<>) id) !ids;
607 Hashtbl.remove level2_patterns32 id;
608 with Not_found -> raise Interpretation_not_found);
609 pattern32_matrix := List.filter (fun (_, id') -> id <> id') !pattern32_matrix;
610 load_patterns32 !pattern32_matrix
612 let remove_pretty_printer id =
614 Hashtbl.remove level1_patterns21 id;
615 with Not_found -> raise Pretty_printer_not_found);
616 pattern21_matrix := List.filter (fun (_, id') -> id <> id') !pattern21_matrix;
617 load_patterns21 !pattern21_matrix