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, string) 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)
77 let rec remove_level_info =
79 | Ast.AttributedTerm (`Level _, t) -> remove_level_info t
80 | Ast.AttributedTerm (a, t) -> Ast.AttributedTerm (a, remove_level_info t)
83 let add_xml_attrs attrs t = Ast.AttributedTerm (`XmlAttrs attrs, t)
85 let add_keyword_attrs =
86 add_xml_attrs (RenderingAttrs.keyword_attributes `MathML)
88 let box kind spacing indent content =
89 Ast.Layout (Ast.Box ((kind, spacing, indent), content))
93 let hvbox = box Ast.HV
94 let hovbox = box Ast.HOV
95 let break = Ast.Layout Ast.Break
96 let builtin_symbol s = Ast.Literal (`Symbol s)
97 let keyword k = add_keyword_attrs (Ast.Literal (`Keyword k))
100 add_xml_attrs (RenderingAttrs.number_attributes `MathML)
101 (Ast.Literal (`Number s))
104 add_xml_attrs (RenderingAttrs.ident_attributes `MathML) (Ast.Ident (i, None))
106 let ident_w_href href i =
109 | Some href -> Ast.AttributedTerm (`Href [href], ident i)
111 let binder_symbol s =
112 add_xml_attrs (RenderingAttrs.builtin_symbol_attributes `MathML)
115 let string_of_sort_kind = function
125 add_level_info Ast.apply_prec Ast.apply_assoc
126 (hovbox true true (CicNotationUtil.dress break (List.map k ts)))
127 | Ast.Binder (binder_kind, (id, ty), body) ->
128 add_level_info Ast.binder_prec Ast.binder_assoc
130 [ binder_symbol (resolve_binder binder_kind);
131 k id; builtin_symbol ":"; aux_ty ty; break;
132 builtin_symbol "."; k body ])
133 | Ast.Case (what, indty_opt, outty_opt, patterns) ->
138 [ builtin_symbol "["; remove_level_info (k outty);
139 builtin_symbol "]"; break ]
144 | Some (indty, href) -> [ keyword "in"; ident_w_href href indty ]
148 keyword "match"; break;
149 hvbox false false ([ k what ] @ indty_box); break;
152 let mk_case_pattern (head, href, vars) =
153 hbox true false (ident_w_href href head :: List.map aux_var vars)
161 mk_case_pattern lhs; builtin_symbol "\\Rightarrow" ];
166 let rec aux_patterns = function
172 last; builtin_symbol "]" ] ]
174 [ break; hbox false false [ builtin_symbol "|"; hd ] ]
179 [ hbox false false [ builtin_symbol "["; builtin_symbol "]" ] ]
182 builtin_symbol "["; one; builtin_symbol "]" ] ]
184 hbox false false [ builtin_symbol "["; hd ]
187 add_level_info Ast.simple_prec Ast.simple_assoc
189 hvbox false false (outty_box @ [ match_box ]); break;
190 hbox false false [ hvbox false false patterns'' ] ])
191 | Ast.Cast (bo, ty) ->
192 add_level_info Ast.simple_prec Ast.simple_assoc
194 builtin_symbol "("; k bo; break; builtin_symbol ":"; k ty;
196 | Ast.LetIn (var, s, t) ->
197 add_level_info Ast.let_in_prec Ast.let_in_assoc
202 aux_var var; builtin_symbol "\\def"; break; k s ];
203 break; keyword "in" ];
206 | Ast.LetRec (rec_kind, funs, where) ->
208 match rec_kind with `Inductive -> "rec" | `CoInductive -> "corec"
210 let mk_fun (var, body, _) = aux_var var, k body in
211 let mk_funs = List.map mk_fun in
212 let fst_fun, tl_funs =
213 match mk_funs funs with hd :: tl -> hd, tl | [] -> assert false
216 let (name, body) = fst_fun in
218 keyword "let"; keyword rec_op; name; builtin_symbol "\\def"; break;
226 keyword "and"; name; builtin_symbol "\\def"; break; body ] ])
229 add_level_info Ast.let_in_prec Ast.let_in_assoc
231 (fst_row :: List.flatten tl_rows
232 @ [ break; keyword "in"; break; k where ])))
233 | Ast.Implicit -> builtin_symbol "?"
235 let local_context l =
236 CicNotationUtil.dress (builtin_symbol ";")
237 (List.map (function None -> builtin_symbol "_" | Some t -> k t) l)
240 ([ builtin_symbol "?"; number (string_of_int n) ]
241 @ (if l <> [] then local_context l else []))
242 | Ast.Sort sort -> aux_sort sort
245 | Ast.Ident (_, None) | Ast.Ident (_, Some [])
246 | Ast.Uri (_, None) | Ast.Uri (_, Some [])
248 | Ast.UserInput as leaf -> leaf
249 | t -> CicNotationUtil.visit_ast ~special_k k t
250 and aux_sort sort_kind =
251 add_xml_attrs (RenderingAttrs.keyword_attributes `MathML)
252 (Ast.Ident (string_of_sort_kind sort_kind, None))
253 and aux_ty = function
254 | None -> builtin_symbol "?"
256 and aux_var = function
259 builtin_symbol "("; name; builtin_symbol ":"; break; k ty;
262 and special_k = function
263 | Ast.AttributedTerm (attrs, t) -> Ast.AttributedTerm (attrs, k t)
265 prerr_endline ("unexpected special: " ^ CicNotationPp.pp_term t);
270 let ast_of_acic0 term_info acic k =
271 let k = k term_info in
272 let register_uri id uri = Hashtbl.add term_info.uri id uri in
275 Hashtbl.find term_info.sort id
277 prerr_endline (sprintf "warning: sort of id %s not found, using Type" id);
278 `Type (CicUniv.fresh ())
280 let aux_substs substs =
283 (fun (uri, annterm) -> (UriManager.name_of_uri uri, k annterm))
286 let aux_context context =
290 | Some annterm -> Some (k annterm))
294 | Cic.ARel (id,_,_,b) -> idref id (Ast.Ident (b, None))
295 | Cic.AVar (id,uri,substs) ->
296 register_uri id (UriManager.string_of_uri uri);
297 idref id (Ast.Ident (UriManager.name_of_uri uri, aux_substs substs))
298 | Cic.AMeta (id,n,l) -> idref id (Ast.Meta (n, aux_context l))
299 | Cic.ASort (id,Cic.Prop) -> idref id (Ast.Sort `Prop)
300 | Cic.ASort (id,Cic.Set) -> idref id (Ast.Sort `Set)
301 | Cic.ASort (id,Cic.Type u) ->idref id (Ast.Sort (`Type u))
302 | Cic.ASort (id,Cic.CProp) -> idref id (Ast.Sort `CProp)
303 | Cic.AImplicit _ -> assert false
304 | Cic.AProd (id,n,s,t) ->
306 match sort_of_id id with
307 | `Set | `Type _ -> `Pi
308 | `Prop | `CProp -> `Forall
310 idref id (Ast.Binder (binder_kind,
311 (CicNotationUtil.name_of_cic_name n, Some (k s)), k t))
312 | Cic.ACast (id,v,t) -> idref id (Ast.Cast (k v, k t))
313 | Cic.ALambda (id,n,s,t) ->
314 idref id (Ast.Binder (`Lambda,
315 (CicNotationUtil.name_of_cic_name n, Some (k s)), k t))
316 | Cic.ALetIn (id,n,s,t) ->
317 idref id (Ast.LetIn ((CicNotationUtil.name_of_cic_name n, None),
319 | Cic.AAppl (aid,args) -> idref aid (Ast.Appl (List.map k args))
320 | Cic.AConst (id,uri,substs) ->
321 register_uri id (UriManager.string_of_uri uri);
322 idref id (Ast.Ident (UriManager.name_of_uri uri, aux_substs substs))
323 | Cic.AMutInd (id,uri,i,substs) as t ->
324 let name = name_of_inductive_type uri i in
325 let uri_str = UriManager.string_of_uri uri in
326 let puri_str = sprintf "%s#xpointer(1/%d)" uri_str (i+1) in
327 register_uri id puri_str;
328 idref id (Ast.Ident (name, aux_substs substs))
329 | Cic.AMutConstruct (id,uri,i,j,substs) ->
330 let name = constructor_of_inductive_type uri i j in
331 let uri_str = UriManager.string_of_uri uri in
332 let puri_str = sprintf "%s#xpointer(1/%d/%d)" uri_str (i + 1) j in
333 register_uri id puri_str;
334 idref id (Ast.Ident (name, aux_substs substs))
335 | Cic.AMutCase (id,uri,typeno,ty,te,patterns) ->
336 let name = name_of_inductive_type uri typeno in
337 let uri_str = UriManager.string_of_uri uri in
338 let puri_str = sprintf "%s#xpointer(1/%d)" uri_str (typeno+1) in
340 UriManager.uri_of_string
341 (sprintf "%s#xpointer(1/%d/%d)" uri_str (typeno+1) j)
343 let case_indty = name, Some (UriManager.uri_of_string puri_str) in
344 let constructors = constructors_of_inductive_type uri typeno in
345 let rec eat_branch ty pat =
347 | Cic.Prod (_, _, t), Cic.ALambda (_, name, s, t') ->
348 let (cv, rhs) = eat_branch t t' in
349 (CicNotationUtil.name_of_cic_name name, Some (k s)) :: cv, rhs
356 (fun (name, ty) pat ->
358 let (capture_variables, rhs) = eat_branch ty pat in
359 ((name, Some (ctor_puri !j), capture_variables), rhs))
360 constructors patterns
361 with Invalid_argument _ -> assert false
363 idref id (Ast.Case (k te, Some case_indty, Some (k ty), patterns))
364 | Cic.AFix (id, no, funs) ->
367 (fun (_, n, decr_idx, ty, bo) ->
368 ((Ast.Ident (n, None), Some (k ty)), k bo, decr_idx))
373 (match List.nth defs no with
374 | (Ast.Ident (n, _), _), _, _ when n <> "_" -> n
376 with Not_found -> assert false
378 idref id (Ast.LetRec (`Inductive, defs, Ast.Ident (name, None)))
379 | Cic.ACoFix (id, no, funs) ->
382 (fun (_, n, ty, bo) ->
383 ((Ast.Ident (n, None), Some (k ty)), k bo, 0))
388 (match List.nth defs no with
389 | (Ast.Ident (n, _), _), _, _ when n <> "_" -> n
391 with Not_found -> assert false
393 idref id (Ast.LetRec (`CoInductive, defs, Ast.Ident (name, None)))
397 (* persistent state *)
399 let level1_patterns21 = Hashtbl.create 211
400 let level2_patterns32 = Hashtbl.create 211
401 let interpretations = Hashtbl.create 211 (* symb -> id list ref *)
403 let compiled21 = ref None
404 let compiled32 = ref None
406 let pattern21_matrix = ref []
407 let pattern32_matrix = ref []
409 let get_compiled21 () =
410 match !compiled21 with
411 | None -> assert false
412 | Some f -> Lazy.force f
413 let get_compiled32 () =
414 match !compiled32 with
415 | None -> assert false
416 | Some f -> Lazy.force f
418 let set_compiled21 f = compiled21 := Some f
419 let set_compiled32 f = compiled32 := Some f
421 let instantiate21 env (* precedence associativity *) l1 =
422 let rec subst_singleton env t =
423 CicNotationUtil.group (subst env t)
424 and subst env = function
425 | Ast.AttributedTerm (_, t) -> subst env t
426 | Ast.Variable var ->
427 let name, expected_ty = CicNotationEnv.declaration_of_var var in
432 prerr_endline ("name " ^ name ^ " not found in environment");
435 assert (CicNotationEnv.well_typed ty value); (* INVARIANT *)
436 (* following assertion should be a conditional that makes this
437 * instantiation fail *)
438 assert (CicNotationEnv.well_typed expected_ty value);
439 [ CicNotationEnv.term_of_value value ]
440 | Ast.Magic m -> subst_magic env m
441 | Ast.Literal (`Keyword k) as t -> [ add_keyword_attrs t ]
442 | Ast.Literal _ as t -> [ t ]
443 | Ast.Layout l -> [ Ast.Layout (subst_layout env l) ]
444 | t -> [ CicNotationUtil.visit_ast (subst_singleton env) t ]
445 and subst_magic env = function
446 | Ast.List0 (p, sep_opt)
447 | Ast.List1 (p, sep_opt) ->
448 let rec_decls = CicNotationEnv.declarations_of_term p in
450 List.map (fun (n, _) -> CicNotationEnv.lookup_list env n) rec_decls
452 let values = CicNotationUtil.ncombine rec_values in
456 | Some l -> [ Ast.Literal l ]
458 let rec instantiate_list acc = function
461 let env = CicNotationEnv.combine rec_decls value_set in
462 instantiate_list (CicNotationUtil.group (subst env p) :: acc) []
464 let env = CicNotationEnv.combine rec_decls value_set in
465 let terms = subst env p in
466 instantiate_list (CicNotationUtil.group (terms @ sep) :: acc) tl
468 instantiate_list [] values
470 let opt_decls = CicNotationEnv.declarations_of_term p in
472 let rec build_env = function
474 | (name, ty) :: tl ->
475 (* assumption: if one of the value is None then all are *)
476 (match CicNotationEnv.lookup_opt env name with
478 | Some v -> (name, (ty, v)) :: build_env tl)
480 try build_env opt_decls with Exit -> []
487 | _ -> assert false (* impossible *)
488 and subst_layout env = function
489 | Ast.Box (kind, tl) ->
490 Ast.Box (kind, List.concat (List.map (subst env) tl))
491 | l -> CicNotationUtil.visit_layout (subst_singleton env) l
493 subst_singleton env l1
495 let rec pp_ast1 term =
496 let rec pp_value = function
497 | CicNotationEnv.NumValue _ as v -> v
498 | CicNotationEnv.StringValue _ as v -> v
499 (* | CicNotationEnv.TermValue t when t == term -> CicNotationEnv.TermValue (pp_ast0 t pp_ast1) *)
500 | CicNotationEnv.TermValue t -> CicNotationEnv.TermValue (pp_ast1 t)
501 | CicNotationEnv.OptValue None as v -> v
502 | CicNotationEnv.OptValue (Some v) ->
503 CicNotationEnv.OptValue (Some (pp_value v))
504 | CicNotationEnv.ListValue vl ->
505 CicNotationEnv.ListValue (List.map pp_value vl)
507 let ast_env_of_env env =
508 List.map (fun (var, (ty, value)) -> (var, (ty, pp_value value))) env
510 (* prerr_endline ("pattern matching from 2 to 1 on term " ^ CicNotationPp.pp_term term); *)
511 (match (get_compiled21 ()) term with
512 | None -> pp_ast0 term pp_ast1
514 let prec, assoc, l1 =
516 Hashtbl.find level1_patterns21 pid
517 with Not_found -> assert false
519 add_level_info prec assoc (instantiate21 (ast_env_of_env env) l1))
521 let instantiate32 term_info env symbol args =
522 let rec instantiate_arg = function
523 | Ast.IdentArg (n, name) ->
524 let t = (try List.assoc name env with Not_found -> assert false) in
525 let rec count_lambda = function
526 | Ast.AttributedTerm (_, t) -> count_lambda t
527 | Ast.Binder (`Lambda, _, body) -> 1 + count_lambda body
530 let rec add_lambda t n =
532 let name = CicNotationUtil.fresh_name () in
533 Ast.Binder (`Lambda, (Ast.Ident (name, None), None),
534 Ast.Appl [add_lambda t (n - 1); Ast.Ident (name, None)])
538 add_lambda t (n - count_lambda t)
540 let head = Ast.Symbol (symbol, 0) in
543 | _ -> Ast.Appl (head :: List.map instantiate_arg args)
545 let rec ast_of_acic1 term_info annterm =
546 match (get_compiled32 ()) annterm with
547 | None -> ast_of_acic0 term_info annterm ast_of_acic1
550 List.map (fun (name, term) -> (name, ast_of_acic1 term_info term)) env
552 let _, symbol, args, _, uris =
554 Hashtbl.find level2_patterns32 pid
555 with Not_found -> assert false
557 let ast = instantiate32 term_info env' symbol args in
558 Ast.AttributedTerm (`IdRef (CicUtil.id_of_annterm annterm),
561 | _ -> Ast.AttributedTerm (`Href uris, ast)))
563 let load_patterns32 t =
564 set_compiled32 (lazy (CicNotationMatcher.Matcher32.compiler t))
566 let load_patterns21 t =
567 set_compiled21 (lazy (CicNotationMatcher.Matcher21.compiler t))
569 let ast_of_acic id_to_sort annterm =
570 debug_print (lazy ("ast_of_acic <- "
571 ^ CicPp.ppterm (Deannotate.deannotate_term annterm)));
572 let term_info = { sort = id_to_sort; uri = Hashtbl.create 211 } in
573 let ast = ast_of_acic1 term_info annterm in
574 debug_print (lazy ("ast_of_acic -> " ^ CicNotationPp.pp_term ast));
578 debug_print (lazy "pp_ast <-");
579 let ast' = pp_ast1 ast in
580 debug_print (lazy ("pp_ast -> " ^ CicNotationPp.pp_term ast'));
584 let counter = ref ~-1 in
589 let add_interpretation dsc (symbol, args) appl_pattern =
590 let id = fresh_id () in
591 let uris = CicNotationUtil.find_appl_pattern_uris appl_pattern in
592 Hashtbl.add level2_patterns32 id (dsc, symbol, args, appl_pattern, uris);
593 pattern32_matrix := (appl_pattern, id) :: !pattern32_matrix;
594 load_patterns32 !pattern32_matrix;
596 let ids = Hashtbl.find interpretations symbol in
598 with Not_found -> Hashtbl.add interpretations symbol (ref [id]));
601 exception Interpretation_not_found
602 exception Pretty_printer_not_found
604 let rec list_uniq = function
607 | h1::h2::tl when h1 = h2 -> list_uniq (h2 :: tl)
608 | h1::tl (* when h1 <> h2 *) -> h1 :: list_uniq tl
610 let lookup_interpretations symbol =
613 (List.sort Pervasives.compare
616 let (dsc, _, args, appl_pattern, _) =
618 Hashtbl.find level2_patterns32 id
619 with Not_found -> assert false
621 dsc, args, appl_pattern)
622 !(Hashtbl.find interpretations symbol)))
623 with Not_found -> raise Interpretation_not_found
625 let add_pretty_printer ~precedence ~associativity l2 l1 =
626 let id = fresh_id () in
627 let l2' = CicNotationUtil.strip_attributes l2 in
628 Hashtbl.add level1_patterns21 id (precedence, associativity, l1);
629 pattern21_matrix := (l2', id) :: !pattern21_matrix;
630 load_patterns21 !pattern21_matrix;
633 let remove_interpretation id =
635 let _, symbol, _, _, _ = Hashtbl.find level2_patterns32 id in
636 let ids = Hashtbl.find interpretations symbol in
637 ids := List.filter ((<>) id) !ids;
638 Hashtbl.remove level2_patterns32 id;
639 with Not_found -> raise Interpretation_not_found);
640 pattern32_matrix := List.filter (fun (_, id') -> id <> id') !pattern32_matrix;
641 load_patterns32 !pattern32_matrix
643 let remove_pretty_printer id =
645 Hashtbl.remove level1_patterns21 id;
646 with Not_found -> raise Pretty_printer_not_found);
647 pattern21_matrix := List.filter (fun (_, id') -> id <> id') !pattern21_matrix;
648 load_patterns21 !pattern21_matrix