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 type interpretation_id = pattern_id
32 type pretty_printer_id = pattern_id
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) *)
92 let builtin_symbol s = reset_href (Ast.Literal (`Symbol s))
93 let keyword k = reset_href (add_keyword_attrs (Ast.Literal (`Keyword k)))
96 (add_xml_attrs (RenderingAttrs.number_attributes `MathML)
97 (Ast.Literal (`Number s)))
99 add_xml_attrs (RenderingAttrs.ident_attributes `MathML) (Ast.Ident (i, None))
100 let binder_symbol s =
101 add_xml_attrs (RenderingAttrs.builtin_symbol_attributes `MathML)
104 let string_of_sort_kind = function
111 let rec aux = function
113 add_level_info Ast.apply_prec Ast.apply_assoc
114 (hovbox true true (CicNotationUtil.dress break (List.map k ts)))
115 | Ast.Binder (binder_kind, (id, ty), body) ->
116 add_level_info Ast.binder_prec Ast.binder_assoc
118 [ binder_symbol (resolve_binder binder_kind);
119 k id; builtin_symbol ":"; aux_ty ty; break;
120 builtin_symbol "."; k body ])
121 | Ast.Case (what, indty_opt, outty_opt, patterns) ->
126 [ builtin_symbol "["; remove_level_info (k outty);
127 builtin_symbol "]"; break ]
132 | Some indty -> [ keyword "in"; ident indty ]
136 keyword "match"; break;
137 hvbox false false ([ k what ] @ indty_box); break;
140 let mk_case_pattern (head, vars) =
141 hbox true false (ident head :: List.map aux_var vars)
149 mk_case_pattern lhs; builtin_symbol "\\Rightarrow" ];
154 let rec aux_patterns = function
160 last; builtin_symbol "]" ] ]
162 [ break; hbox false false [ builtin_symbol "|"; hd ] ]
167 [ hbox false false [ builtin_symbol "["; builtin_symbol "]" ] ]
170 builtin_symbol "["; one; builtin_symbol "]" ] ]
172 hbox false false [ builtin_symbol "["; hd ]
175 add_level_info Ast.simple_prec Ast.simple_assoc
177 hvbox false false (outty_box @ [ match_box ]); break;
178 hbox false false [ hvbox false false patterns'' ] ])
179 | Ast.Cast (bo, ty) ->
180 add_level_info Ast.simple_prec Ast.simple_assoc
182 builtin_symbol "("; k bo; break; builtin_symbol ":"; k ty;
184 | Ast.LetIn (var, s, t) ->
185 add_level_info Ast.let_in_prec Ast.let_in_assoc
190 aux_var var; builtin_symbol "\\def"; break; k s ];
191 break; keyword "in" ];
193 | Ast.LetRec (rec_kind, funs, where) ->
195 match rec_kind with `Inductive -> "rec" | `CoInductive -> "corec"
197 let mk_fun (var, body, _) = aux_var var, k body in
198 let mk_funs = List.map mk_fun in
199 let fst_fun, tl_funs =
200 match mk_funs funs with hd :: tl -> hd, tl | [] -> assert false
203 let (name, body) = fst_fun in
205 keyword "let"; keyword rec_op; name; builtin_symbol "\\def"; break;
213 keyword "and"; name; builtin_symbol "\\def"; break; body ] ])
216 add_level_info Ast.let_in_prec Ast.let_in_assoc
218 (fst_row :: List.flatten tl_rows
219 @ [ break; keyword "in"; break; k where ])))
220 | Ast.Implicit -> builtin_symbol "?"
222 let local_context l =
223 CicNotationUtil.dress (builtin_symbol ";")
224 (List.map (function None -> builtin_symbol "_" | Some t -> k t) l)
227 ([ builtin_symbol "?"; number (string_of_int n) ]
228 @ (if l <> [] then local_context l else []))
229 | Ast.Sort sort -> aux_sort sort
232 | Ast.Ident (_, None) | Ast.Ident (_, Some [])
233 | Ast.Uri (_, None) | Ast.Uri (_, Some [])
235 | Ast.UserInput as leaf -> leaf
236 | t -> CicNotationUtil.visit_ast ~special_k k t
237 and aux_sort sort_kind =
238 add_xml_attrs (RenderingAttrs.keyword_attributes `MathML)
239 (Ast.Ident (string_of_sort_kind sort_kind, None))
240 and aux_ty = function
241 | None -> builtin_symbol "?"
243 and aux_var = function
246 builtin_symbol "("; name; builtin_symbol ":"; break; k ty;
249 and special_k = function
250 | Ast.AttributedTerm (attrs, t) -> Ast.AttributedTerm (attrs, k t)
252 prerr_endline ("unexpected special: " ^ CicNotationPp.pp_term t);
257 let ast_of_acic0 term_info acic k =
258 let k = k term_info in
259 let register_uri id uri = Hashtbl.add term_info.uri id uri in
262 Hashtbl.find term_info.sort id
264 prerr_endline (sprintf "warning: sort of id %s not found, using Type" id);
267 let aux_substs substs =
270 (fun (uri, annterm) -> (UriManager.name_of_uri uri, k annterm))
273 let aux_context context =
277 | Some annterm -> Some (k annterm))
281 | Cic.ARel (id,_,_,b) -> idref id (Ast.Ident (b, None))
282 | Cic.AVar (id,uri,substs) ->
283 register_uri id (UriManager.string_of_uri uri);
284 idref id (Ast.Ident (UriManager.name_of_uri uri, aux_substs substs))
285 | Cic.AMeta (id,n,l) -> idref id (Ast.Meta (n, aux_context l))
286 | Cic.ASort (id,Cic.Prop) -> idref id (Ast.Sort `Prop)
287 | Cic.ASort (id,Cic.Set) -> idref id (Ast.Sort `Set)
288 | Cic.ASort (id,Cic.Type _) -> idref id (Ast.Sort `Type)
289 | Cic.ASort (id,Cic.CProp) -> idref id (Ast.Sort `CProp)
290 | Cic.AImplicit _ -> assert false
291 | Cic.AProd (id,n,s,t) ->
293 match sort_of_id id with
294 | `Set | `Type -> `Pi
295 | `Prop | `CProp -> `Forall
297 idref id (Ast.Binder (binder_kind,
298 (CicNotationUtil.name_of_cic_name n, Some (k s)), k t))
299 | Cic.ACast (id,v,t) -> idref id (Ast.Cast (k v, k t))
300 | Cic.ALambda (id,n,s,t) ->
301 idref id (Ast.Binder (`Lambda,
302 (CicNotationUtil.name_of_cic_name n, Some (k s)), k t))
303 | Cic.ALetIn (id,n,s,t) ->
304 idref id (Ast.LetIn ((CicNotationUtil.name_of_cic_name n, None),
306 | Cic.AAppl (aid,args) -> idref aid (Ast.Appl (List.map k args))
307 | Cic.AConst (id,uri,substs) ->
308 register_uri id (UriManager.string_of_uri uri);
309 idref id (Ast.Ident (UriManager.name_of_uri uri, aux_substs substs))
310 | Cic.AMutInd (id,uri,i,substs) as t ->
311 let name = name_of_inductive_type uri i in
312 let uri_str = UriManager.string_of_uri uri in
314 uri_str ^ "#xpointer(1/" ^ (string_of_int (i + 1)) ^ ")"
316 register_uri id puri_str;
317 idref id (Ast.Ident (name, aux_substs substs))
318 | Cic.AMutConstruct (id,uri,i,j,substs) ->
319 let name = constructor_of_inductive_type uri i j in
320 let uri_str = UriManager.string_of_uri uri in
321 let puri_str = sprintf "%s#xpointer(1/%d/%d)" uri_str (i + 1) j in
322 register_uri id puri_str;
323 idref id (Ast.Ident (name, aux_substs substs))
324 | Cic.AMutCase (id,uri,typeno,ty,te,patterns) ->
325 let name = name_of_inductive_type uri typeno in
326 let constructors = constructors_of_inductive_type uri typeno in
327 let rec eat_branch ty pat =
329 | Cic.Prod (_, _, t), Cic.ALambda (_, name, s, t') ->
330 let (cv, rhs) = eat_branch t t' in
331 (CicNotationUtil.name_of_cic_name name, Some (k s)) :: cv, rhs
336 (fun (name, ty) pat ->
337 let (capture_variables, rhs) = eat_branch ty pat in
338 ((name, capture_variables), rhs))
339 constructors patterns
341 idref id (Ast.Case (k te, Some name, Some (k ty), patterns))
342 | Cic.AFix (id, no, funs) ->
345 (fun (_, n, decr_idx, ty, bo) ->
346 ((Ast.Ident (n, None), Some (k ty)), k bo, decr_idx))
351 (match List.nth defs no with
352 | (Ast.Ident (n, _), _), _, _ when n <> "_" -> n
354 with Not_found -> assert false
356 idref id (Ast.LetRec (`Inductive, defs, Ast.Ident (name, None)))
357 | Cic.ACoFix (id, no, funs) ->
360 (fun (_, n, ty, bo) ->
361 ((Ast.Ident (n, None), Some (k ty)), k bo, 0))
366 (match List.nth defs no with
367 | (Ast.Ident (n, _), _), _, _ when n <> "_" -> n
369 with Not_found -> assert false
371 idref id (Ast.LetRec (`CoInductive, defs, Ast.Ident (name, None)))
375 (* persistent state *)
377 let level1_patterns21 = Hashtbl.create 211
378 let level2_patterns32 = Hashtbl.create 211
379 let interpretations = Hashtbl.create 211 (* symb -> id list ref *)
381 let compiled21 = ref None
382 let compiled32 = ref None
384 let pattern21_matrix = ref []
385 let pattern32_matrix = ref []
387 let get_compiled21 () =
388 match !compiled21 with
389 | None -> assert false
390 | Some f -> Lazy.force f
391 let get_compiled32 () =
392 match !compiled32 with
393 | None -> assert false
394 | Some f -> Lazy.force f
396 let set_compiled21 f = compiled21 := Some f
397 let set_compiled32 f = compiled32 := Some f
399 let instantiate21 env (* precedence associativity *) l1 =
400 let rec subst_singleton env t =
401 CicNotationUtil.group (subst env t)
402 and subst env = function
403 | Ast.AttributedTerm (_, t) -> subst env t
404 | Ast.Variable var ->
405 let name, expected_ty = CicNotationEnv.declaration_of_var var in
409 with Not_found -> assert false
411 assert (CicNotationEnv.well_typed ty value); (* INVARIANT *)
412 (* following assertion should be a conditional that makes this
413 * instantiation fail *)
414 assert (CicNotationEnv.well_typed expected_ty value);
415 [ CicNotationEnv.term_of_value value ]
416 | Ast.Magic m -> subst_magic env m
417 | Ast.Literal (`Keyword k) as t -> [ (*reset_href*) (add_keyword_attrs t) ]
418 | Ast.Literal _ as t -> [ (*reset_href*) t ]
419 | Ast.Layout l -> [ Ast.Layout (subst_layout env l) ]
420 | t -> [ CicNotationUtil.visit_ast (subst_singleton env) t ]
421 and subst_magic env = function
422 | Ast.List0 (p, sep_opt)
423 | Ast.List1 (p, sep_opt) ->
424 let rec_decls = CicNotationEnv.declarations_of_term p in
426 List.map (fun (n, _) -> CicNotationEnv.lookup_list env n) rec_decls
428 let values = CicNotationUtil.ncombine rec_values in
432 | Some l -> [ Ast.Literal l ]
434 let rec instantiate_list acc = function
437 let env = CicNotationEnv.combine rec_decls value_set in
438 instantiate_list (CicNotationUtil.group (subst env p) :: acc) []
440 let env = CicNotationEnv.combine rec_decls value_set in
442 (CicNotationUtil.group ((subst env p) @ sep) :: acc) tl
444 instantiate_list [] values
446 let opt_decls = CicNotationEnv.declarations_of_term p in
448 let rec build_env = function
450 | (name, ty) :: tl ->
451 (* assumption: if one of the value is None then all are *)
452 (match CicNotationEnv.lookup_opt env name with
454 | Some v -> (name, (ty, v)) :: build_env tl)
456 try build_env opt_decls with Exit -> []
463 | _ -> assert false (* impossible *)
464 and subst_layout env = function
465 | Ast.Box (kind, tl) ->
466 Ast.Box (kind, List.concat (List.map (subst env) tl))
467 | l -> CicNotationUtil.visit_layout (subst_singleton env) l
469 subst_singleton env l1
471 let rec pp_ast1 term =
472 let rec pp_value = function
473 | CicNotationEnv.NumValue _ as v -> v
474 | CicNotationEnv.StringValue _ as v -> v
475 (* | CicNotationEnv.TermValue t when t == term -> CicNotationEnv.TermValue (pp_ast0 t pp_ast1) *)
476 | CicNotationEnv.TermValue t -> CicNotationEnv.TermValue (pp_ast1 t)
477 | CicNotationEnv.OptValue None as v -> v
478 | CicNotationEnv.OptValue (Some v) ->
479 CicNotationEnv.OptValue (Some (pp_value v))
480 | CicNotationEnv.ListValue vl ->
481 CicNotationEnv.ListValue (List.map pp_value vl)
483 let ast_env_of_env env =
484 List.map (fun (var, (ty, value)) -> (var, (ty, pp_value value))) env
487 | Ast.AttributedTerm (attrs, t) -> Ast.AttributedTerm (attrs, pp_ast1 t)
489 (match (get_compiled21 ()) term with
490 | None -> pp_ast0 term pp_ast1
492 let prec, assoc, l1 =
494 Hashtbl.find level1_patterns21 pid
495 with Not_found -> assert false
497 add_level_info prec assoc (instantiate21 (ast_env_of_env env) l1))
499 let instantiate32 term_info env symbol args =
500 let rec instantiate_arg = function
501 | Ast.IdentArg (n, name) ->
502 let t = (try List.assoc name env with Not_found -> assert false) in
503 let rec count_lambda = function
504 | Ast.Binder (`Lambda, _, body) -> 1 + count_lambda body
507 let rec add_lambda t n =
509 let name = CicNotationUtil.fresh_name () in
510 Ast.Binder (`Lambda, (Ast.Ident (name, None), None),
511 Ast.Appl [add_lambda t (n - 1); Ast.Ident (name, None)])
515 add_lambda t (n - count_lambda t)
517 let head = Ast.Symbol (symbol, 0) in
520 | _ -> Ast.Appl (head :: List.map instantiate_arg args)
522 let rec ast_of_acic1 term_info annterm =
523 match (get_compiled32 ()) annterm with
524 | None -> ast_of_acic0 term_info annterm ast_of_acic1
527 List.map (fun (name, term) -> (name, ast_of_acic1 term_info term)) env
529 let _, symbol, args, _, uris =
531 Hashtbl.find level2_patterns32 pid
532 with Not_found -> assert false
534 let ast = instantiate32 term_info env' symbol args in
535 Ast.AttributedTerm (`IdRef (CicUtil.id_of_annterm annterm),
538 | _ -> Ast.AttributedTerm (`Href uris, ast)))
540 let load_patterns32 t =
541 set_compiled32 (lazy (CicNotationMatcher.Matcher32.compiler t))
543 let load_patterns21 t =
544 set_compiled21 (lazy (CicNotationMatcher.Matcher21.compiler t))
546 let ast_of_acic id_to_sort annterm =
547 let term_info = { sort = id_to_sort; uri = Hashtbl.create 211 } in
548 let ast = ast_of_acic1 term_info annterm in
552 (* prerr_endline ("pp_ast <- : " ^ CicNotationPp.pp_term term); *)
556 let counter = ref ~-1 in
561 let add_interpretation dsc (symbol, args) appl_pattern =
562 let id = fresh_id () in
563 let uris = CicNotationUtil.find_appl_pattern_uris appl_pattern in
564 Hashtbl.add level2_patterns32 id (dsc, symbol, args, appl_pattern, uris);
565 pattern32_matrix := (appl_pattern, id) :: !pattern32_matrix;
566 load_patterns32 !pattern32_matrix;
568 let ids = Hashtbl.find interpretations symbol in
570 with Not_found -> Hashtbl.add interpretations symbol (ref [id]));
573 exception Interpretation_not_found
574 exception Pretty_printer_not_found
576 let rec list_uniq = function
579 | h1::h2::tl when h1 = h2 -> list_uniq (h2 :: tl)
580 | h1::tl (* when h1 <> h2 *) -> h1 :: list_uniq tl
582 let lookup_interpretations symbol =
585 (List.sort Pervasives.compare
588 let (dsc, _, args, appl_pattern, _) =
590 Hashtbl.find level2_patterns32 id
591 with Not_found -> assert false
593 dsc, args, appl_pattern)
594 !(Hashtbl.find interpretations symbol)))
595 with Not_found -> raise Interpretation_not_found
597 let add_pretty_printer ~precedence ~associativity l2 l1 =
598 let id = fresh_id () in
599 let l2' = CicNotationUtil.strip_attributes l2 in
600 Hashtbl.add level1_patterns21 id (precedence, associativity, l1);
601 pattern21_matrix := (l2', id) :: !pattern21_matrix;
602 load_patterns21 !pattern21_matrix;
605 let remove_interpretation id =
607 let _, symbol, _, _, _ = Hashtbl.find level2_patterns32 id in
608 let ids = Hashtbl.find interpretations symbol in
609 ids := List.filter ((<>) id) !ids;
610 Hashtbl.remove level2_patterns32 id;
611 with Not_found -> raise Interpretation_not_found);
612 pattern32_matrix := List.filter (fun (_, id') -> id <> id') !pattern32_matrix;
613 load_patterns32 !pattern32_matrix
615 let remove_pretty_printer id =
617 Hashtbl.remove level1_patterns21 id;
618 with Not_found -> raise Pretty_printer_not_found);
619 pattern21_matrix := List.filter (fun (_, id') -> id <> id') !pattern21_matrix;
620 load_patterns21 !pattern21_matrix