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
33 { sort: (Cic.id, CicNotationPt.sort_kind) Hashtbl.t;
34 uri: (Cic.id, string) Hashtbl.t;
42 let compare (x1:t) (x2:t) = Pervasives.compare x2 x1 (* reverse order *)
45 module IntSet = Set.Make (OrderedInt)
47 let int_set_of_int_list l =
48 List.fold_left (fun acc i -> IntSet.add i acc) IntSet.empty l
50 let warning s = prerr_endline ("CicNotation WARNING: " ^ s)
55 val compatible : pattern_t -> pattern_t -> bool
58 module Patterns (P: PATTERN) =
60 type row_t = P.pattern_t list * pattern_id
65 let first_column t = List.map (fun (patterns, _) -> List.hd patterns) t
66 let pattern_ids t = List.map snd t
68 let partition t pidl =
69 let partitions = Hashtbl.create 11 in
70 let add pid row = Hashtbl.add partitions pid row in
73 with Invalid_argument _ -> assert false);
74 let pidset = int_set_of_int_list pidl in
77 match Hashtbl.find_all partitions pid with
79 | patterns -> (pid, List.rev patterns) :: acc)
82 let are_empty t = fst (List.hd t) = []
83 (* if first row has an empty list of patterns, then others will as well *)
85 (* return 2 lists of rows, first one containing homogeneous rows according
86 * to "compatible" below *)
87 let horizontal_split t =
92 assert false (* are_empty should have been invoked in advance *)
93 | (hd :: _ , _) :: _ -> hd
95 let rec aux prev_t = function
96 | [] -> List.rev prev_t, []
97 | ([], _) :: _ -> assert false
98 | (((hd :: _), _) as row) :: tl when P.compatible ap hd ->
99 aux (row :: prev_t) tl
100 | t -> List.rev prev_t, t
104 (* return 2 lists, first one representing first column, second one
105 * representing rows stripped of the first element *)
106 let vertical_split t =
110 | (hd :: tl, pid) -> hd, (tl, pid)
117 module Patterns21 = Patterns (CicNotationTag)
121 type row_t = CicNotationPt.cic_appl_pattern list * pattern_id
126 let first_column t = List.map (fun (patterns, _) -> List.hd patterns) t
127 let pattern_ids t = List.map snd t
129 let partition t pidl =
130 let partitions = Hashtbl.create 11 in
131 let add pid row = Hashtbl.add partitions pid row in
133 List.iter2 add pidl t
134 with Invalid_argument _ -> assert false);
135 let pidset = int_set_of_int_list pidl in
138 match Hashtbl.find_all partitions pid with
140 | patterns -> (pid, List.rev patterns) :: acc)
143 let are_empty t = fst (List.hd t) = []
144 (* if first row has an empty list of patterns, then others will as well *)
146 (* return 2 lists of rows, first one containing homogeneous rows according
147 * to "compatible" below *)
148 let horizontal_split t =
149 let compatible ap1 ap2 =
151 | CicNotationPt.UriPattern _, CicNotationPt.UriPattern _
152 | CicNotationPt.ArgPattern _, CicNotationPt.ArgPattern _
153 | CicNotationPt.ApplPattern _, CicNotationPt.ApplPattern _ -> true
160 assert false (* are_empty should have been invoked in advance *)
161 | (hd :: _ , _) :: _ -> hd
163 let rec aux prev_t = function
164 | [] -> List.rev prev_t, []
165 | ([], _) :: _ -> assert false
166 | (((hd :: _), _) as row) :: tl when compatible ap hd ->
167 aux (row :: prev_t) tl
168 | t -> List.rev prev_t, t
172 (* return 2 lists, first one representing first column, second one
173 * representing rows stripped of the first element *)
174 let vertical_split t =
178 | (hd :: tl, pid) -> hd, (tl, pid)
185 (* acic -> ast auxiliary function s *)
188 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
190 | Cic.InductiveDefinition (l,_,_,_) -> l
193 let name_of_inductive_type uri i =
194 let types = get_types uri in
195 let (name, _, _, _) = try List.nth types i with Not_found -> assert false in
198 (* returns <name, type> pairs *)
199 let constructors_of_inductive_type uri i =
200 let types = get_types uri in
201 let (_, _, _, constructors) =
202 try List.nth types i with Not_found -> assert false
206 (* returns name only *)
207 let constructor_of_inductive_type uri i j =
209 fst (List.nth (constructors_of_inductive_type uri i) (j-1))
210 with Not_found -> assert false)
212 module Ast = CicNotationPt
214 let string_of_name = function
216 | Cic.Anonymous -> "_"
218 let ident_of_name n = Ast.Ident (string_of_name n, None)
220 let idref id t = Ast.AttributedTerm (`IdRef id, t)
223 prerr_endline "pp_ast0";
224 let rec aux t = CicNotationUtil.visit_ast ~special_k k t
225 and special_k = function
226 | Ast.AttributedTerm (attrs, t) -> Ast.AttributedTerm (attrs, aux t)
231 let ast_of_acic0 term_info acic k =
232 (* prerr_endline "ast_of_acic0"; *)
233 let k = k term_info in
234 let register_uri id uri = Hashtbl.add term_info.uri id uri in
237 Hashtbl.find term_info.sort id
238 with Not_found -> assert false
240 let aux_substs substs =
243 (fun (uri, annterm) -> (UriManager.name_of_uri uri, k annterm))
246 let aux_context context =
250 | Some annterm -> Some (k annterm))
254 | Cic.ARel (id,_,_,b) -> idref id (Ast.Ident (b, None))
255 | Cic.AVar (id,uri,substs) ->
256 register_uri id (UriManager.string_of_uri uri);
257 idref id (Ast.Ident (UriManager.name_of_uri uri, aux_substs substs))
258 | Cic.AMeta (id,n,l) -> idref id (Ast.Meta (n, aux_context l))
259 | Cic.ASort (id,Cic.Prop) -> idref id (Ast.Sort `Prop)
260 | Cic.ASort (id,Cic.Set) -> idref id (Ast.Sort `Set)
261 | Cic.ASort (id,Cic.Type _) -> idref id (Ast.Sort `Type)
262 | Cic.ASort (id,Cic.CProp) -> idref id (Ast.Sort `CProp)
263 | Cic.AImplicit _ -> assert false
264 | Cic.AProd (id,n,s,t) ->
266 match sort_of_id id with
267 | `Set | `Type -> `Pi
268 | `Prop | `CProp -> `Forall
270 idref id (Ast.Binder (binder_kind, (ident_of_name n, Some (k s)), k t))
271 | Cic.ACast (id,v,t) ->
272 idref id (Ast.Appl [idref id (Ast.Symbol ("cast", 0)); k v; k t])
273 | Cic.ALambda (id,n,s,t) ->
274 idref id (Ast.Binder (`Lambda, (ident_of_name n, Some (k s)), k t))
275 | Cic.ALetIn (id,n,s,t) ->
276 idref id (Ast.LetIn ((ident_of_name n, None), k s, k t))
277 | Cic.AAppl (aid,args) -> idref aid (Ast.Appl (List.map k args))
278 | Cic.AConst (id,uri,substs) ->
279 register_uri id (UriManager.string_of_uri uri);
280 idref id (Ast.Ident (UriManager.name_of_uri uri, aux_substs substs))
281 | Cic.AMutInd (id,uri,i,substs) as t ->
282 let name = name_of_inductive_type uri i in
283 let uri_str = UriManager.string_of_uri uri in
285 uri_str ^ "#xpointer(1/" ^ (string_of_int (i + 1)) ^ ")"
287 register_uri id puri_str;
288 idref id (Ast.Ident (name, aux_substs substs))
289 | Cic.AMutConstruct (id,uri,i,j,substs) ->
290 let name = constructor_of_inductive_type uri i j in
291 let uri_str = UriManager.string_of_uri uri in
292 let puri_str = sprintf "%s#xpointer(1/%d/%d)" uri_str (i + 1) j in
293 register_uri id puri_str;
294 idref id (Ast.Ident (name, aux_substs substs))
295 | Cic.AMutCase (id,uri,typeno,ty,te,patterns) ->
296 let name = name_of_inductive_type uri typeno in
297 let constructors = constructors_of_inductive_type uri typeno in
298 let rec eat_branch ty pat =
300 | Cic.Prod (_, _, t), Cic.ALambda (_, name, s, t') ->
301 let (cv, rhs) = eat_branch t t' in
302 (ident_of_name name, Some (k s)) :: cv, rhs
307 (fun (name, ty) pat ->
308 let (capture_variables, rhs) = eat_branch ty pat in
309 ((name, capture_variables), rhs))
310 constructors patterns
312 idref id (Ast.Case (k te, Some name, Some (k ty), patterns))
313 | Cic.AFix (id, no, funs) ->
316 (fun (_, n, decr_idx, ty, bo) ->
317 ((Ast.Ident (n, None), Some (k ty)), k bo, decr_idx))
322 (match List.nth defs no with
323 | (Ast.Ident (n, _), _), _, _ when n <> "_" -> n
325 with Not_found -> assert false
327 idref id (Ast.LetRec (`Inductive, defs, Ast.Ident (name, None)))
328 | Cic.ACoFix (id, no, funs) ->
331 (fun (_, n, ty, bo) -> ((Ast.Ident (n, None), Some (k ty)), k bo, 0))
336 (match List.nth defs no with
337 | (Ast.Ident (n, _), _), _, _ when n <> "_" -> n
339 with Not_found -> assert false
341 idref id (Ast.LetRec (`CoInductive, defs, Ast.Ident (name, None)))
345 (* persistent state *)
347 let level1_patterns21 = Hashtbl.create 211
348 let level2_patterns32 = Hashtbl.create 211
350 let (compiled21: (CicNotationPt.term -> CicNotationPt.term) option ref) =
352 let (compiled32: (term_info -> Cic.annterm -> CicNotationPt.term) option ref) =
355 let pattern21_matrix = ref Patterns21.empty
356 let pattern32_matrix = ref Patterns32.empty
358 let get_compiled21 () =
359 match !compiled21 with
360 | None -> assert false
362 let get_compiled32 () =
363 match !compiled32 with
364 | None -> assert false
367 let set_compiled21 f = compiled21 := Some f
368 let set_compiled32 f = compiled32 := Some f
370 (* "envl" is a list of triples:
371 * <name environment, term environment, pattern id>, where
372 * name environment: (string * string) list
373 * term environment: (string * Cic.annterm) list *)
374 let return_closure success_k =
375 (fun term_info terms envl ->
376 (* prerr_endline "return_closure"; *)
380 success_k term_info (List.hd envl)
381 with Failure _ -> assert false)
384 let variable_closure names k =
385 (fun term_info terms envl ->
386 (* prerr_endline "variable_closure"; *)
391 (fun arg (name_env, term_env, pid) ->
392 let rec aux name_env term_env pid arg term =
394 Ast.IdentArg name, _ ->
395 (name_env, (name, term) :: term_env, pid)
396 | Ast.EtaArg (Some name, arg'),
397 Cic.ALambda (id, name', ty, body) ->
399 ((name, (string_of_name name', Some (ty, id))) :: name_env)
400 term_env pid arg' body
401 | Ast.EtaArg (Some name, arg'), _ ->
402 let name' = CicNotationUtil.fresh_name () in
403 aux ((name, (name', None)) :: name_env)
404 term_env pid arg' term
405 | Ast.EtaArg (None, arg'), Cic.ALambda (id, name, ty, body) ->
407 | Ast.EtaArg (None, arg'), _ ->
410 aux name_env term_env pid arg hd)
416 let appl_closure ks k =
417 (fun term_info terms envl ->
418 (* prerr_endline "appl_closure"; *)
420 | Cic.AAppl (_, args) :: tl ->
422 let k' = List.assoc (List.length args) ks in
423 k' term_info (args @ tl) envl
424 with Not_found -> k term_info terms envl)
426 | _ -> k term_info terms envl))
428 let uri_of_term t = CicUtil.uri_of_term (Deannotate.deannotate_term t)
430 let uri_closure ks k =
431 (fun term_info terms envl ->
432 (* prerr_endline "uri_closure"; *)
436 (* prerr_endline (sprintf "uri_of_term = %s" (uri_of_term hd)); *)
439 let k' = List.assoc (uri_of_term hd) ks in
442 | Invalid_argument _ (* raised by uri_of_term *)
443 | Not_found -> k term_info terms envl
446 (* compiler from level 3 to level 2 *)
447 let compiler32 (t: Patterns32.t) success_k fail_k =
448 let rec aux t k = (* k is a continuation *)
451 else if Patterns32.are_empty t then begin
454 (* XXX optimization possible here: throw away all except one of the
455 * rules which lead to ambiguity *)
456 warning "ambiguous interpretation"
458 return_closure success_k
460 match Patterns32.horizontal_split t with
464 | ([], _) :: _ -> assert false
465 | (Ast.ArgPattern (Ast.IdentArg _) :: _, _) :: _
466 | (Ast.ArgPattern (Ast.EtaArg _) :: _, _) :: _ ->
467 let first_column, t'' = Patterns32.vertical_split t' in
471 | Ast.ArgPattern arg -> arg
475 variable_closure names (aux t'' k)
476 | (Ast.ApplPattern _ :: _, _) :: _ ->
480 | (Ast.ApplPattern args) :: _, _ -> List.length args
484 (* arity partitioning *)
485 let clusters = Patterns32.partition t' pidl in
486 let ks = (* k continuation list *)
488 (fun (len, cluster) ->
490 List.map (* add args as patterns heads *)
492 | (Ast.ApplPattern args) :: tl, pid ->
493 (* let's throw away "teste di cluster" *)
502 | (Ast.UriPattern _ :: _, _) :: _ ->
504 let urimap = ref [] in
505 let uidmap = ref [] in
508 List.assoc uri !urimap
511 let uid = List.length !urimap in
512 urimap := (uri, uid) :: !urimap ;
513 uidmap := (uid, uri) :: !uidmap ;
519 | (Ast.UriPattern uri) :: _, _ -> get_uri_id uri
525 let clusters = Patterns32.partition t' pidl in
528 (fun (uid, cluster) ->
532 | (Ast.UriPattern uri) :: tl, pid -> tl, pid
536 List.assoc uid uidmap, aux cluster' k)
540 | t', tl -> aux t' (aux tl k)
542 let matcher = aux t (fun _ _ -> raise No_match) in
543 (fun term_info annterm ->
545 matcher term_info [annterm] (List.map (fun (_, pid) -> [], [], pid) t)
546 with No_match -> fail_k term_info annterm)
548 let return_closure21 success_k =
550 prerr_endline "return_closure21";
554 success_k (List.hd envl)
555 with Failure _ -> assert false)
558 let variable_closure21 vars k =
560 prerr_endline "variable_closure21";
564 List.map2 (fun var (env, pid) -> (var, hd) :: env, pid) vars envl
569 let constructor_closure21 ks k =
571 prerr_endline "constructor_closure21";
574 prerr_endline (sprintf "on term %s" (CicNotationPp.pp_term p));
576 let tag, subterms = CicNotationTag.get_tag p in
577 let k' = List.assoc tag ks in
578 k' (subterms @ tl) envl
579 with Not_found -> k terms envl)
580 | [] -> assert false))
582 let compiler21 (t: Patterns21.t) success_k fail_k =
586 else if Patterns21.are_empty t then begin
589 (* XXX optimization possible here: throw away all except one of the
590 * rules which lead to ambiguity *)
591 warning "ambiguous notation"
593 return_closure21 success_k
595 match Patterns21.horizontal_split t with
599 | ([], _) :: _ -> assert false
600 | (Ast.Variable _ :: _, _) :: _ ->
601 let first_column, t'' = Patterns21.vertical_split t' in
605 | Ast.Variable v -> v
609 variable_closure21 vars (aux t'' k)
614 | p :: _, _ -> fst (CicNotationTag.get_tag p)
615 | [], _ -> assert false)
618 let clusters = Patterns21.partition t' pidl in
621 (fun (pid, cluster) ->
623 List.map (* add args as patterns heads *)
626 let _, subpatterns = CicNotationTag.get_tag p in
627 subpatterns @ tl, pid
634 constructor_closure21 ks k)
635 | t', tl -> aux t' (aux tl k)
637 let matcher = aux t (fun _ _ -> raise No_match) in
640 matcher [ast] (List.map (fun (_, pid) -> [], pid) t)
641 with No_match -> fail_k ast)
643 let ast_of_acic1 term_info annterm = (get_compiled32 ()) term_info annterm
645 let pp_ast1 term = (get_compiled21 ()) term
647 let instantiate21 env pid =
648 prerr_endline "instantiate21";
649 let precedence, associativity, l1 =
651 Hashtbl.find level1_patterns21 pid
652 with Not_found -> assert false
654 let rec subst = function
655 | Ast.AttributedTerm (_, t) -> subst t
656 | Ast.Variable var ->
657 (try List.assoc var env with Not_found -> assert false)
659 | Ast.Magic _) as t -> t
660 | Ast.Layout l -> Ast.Layout (subst_layout l)
661 | t -> CicNotationUtil.visit_ast subst t
662 and subst_layout l = CicNotationUtil.visit_layout subst l in
665 let instantiate32 term_info name_env term_env pid =
668 Hashtbl.find level2_patterns32 pid
669 with Not_found -> assert false
671 let rec instantiate_arg = function
672 | Ast.IdentArg name ->
673 (try List.assoc name term_env with Not_found -> assert false)
674 | Ast.EtaArg (None, _) -> assert false (* TODO *)
675 | Ast.EtaArg (Some name, arg) ->
676 let (name', ty_opt) =
677 try List.assoc name name_env with Not_found -> assert false
679 let body = instantiate_arg arg in
680 let name' = Ast.Ident (name', None) in
682 | None -> Ast.Binder (`Lambda, (name', None), body)
684 idref id (Ast.Binder (`Lambda, (name', Some ty), body))
686 let args' = List.map instantiate_arg args in
687 Ast.Appl (Ast.Symbol (symbol, 0) :: args')
689 let load_patterns32 t =
690 let ast_env_of_name_env term_info name_env =
692 (fun (name, (name', ty_opt)) ->
696 | Some (annterm, id) -> Some (ast_of_acic1 term_info annterm, id)
698 (name, (name', ast_ty_opt)))
701 let ast_env_of_term_env term_info =
702 List.map (fun (name, term) -> (name, ast_of_acic1 term_info term))
704 let fail_k term_info annterm = ast_of_acic0 term_info annterm ast_of_acic1 in
705 let success_k term_info (name_env, term_env, pid) =
708 (ast_env_of_name_env term_info name_env)
709 (ast_env_of_term_env term_info term_env)
712 let compiled32 = compiler32 t success_k fail_k in
713 set_compiled32 compiled32
715 let load_patterns21 t =
716 let ast_env_of_env env =
717 List.map (fun (var, term) -> (var, pp_ast1 term)) env
719 let fail_k term = pp_ast0 term pp_ast1 in
720 let success_k (env, pid) = instantiate21 (ast_env_of_env env) pid in
721 let compiled21 = compiler21 t success_k fail_k in
722 set_compiled21 compiled21
724 let ast_of_acic id_to_sort annterm =
725 let term_info = { sort = id_to_sort; uri = Hashtbl.create 211 } in
726 let ast = ast_of_acic1 term_info annterm in
729 let pp_ast term = pp_ast1 term
732 let counter = ref ~-1 in
737 let add_interpretation (symbol, args) appl_pattern =
738 let id = fresh_id () in
739 Hashtbl.add level2_patterns32 id (symbol, args);
740 pattern32_matrix := ([appl_pattern], id) :: !pattern32_matrix;
741 load_patterns32 !pattern32_matrix;
744 let add_pretty_printer ?precedence ?associativity l2 l1 =
745 let id = fresh_id () in
746 let l2' = CicNotationUtil.strip_attributes l2 in
747 Hashtbl.add level1_patterns21 id (precedence, associativity, l1);
748 pattern21_matrix := ([l2'], id) :: !pattern21_matrix;
749 load_patterns21 !pattern21_matrix;
752 exception Interpretation_not_found
753 exception Pretty_printer_not_found
755 let remove_interpretation id =
757 Hashtbl.remove level2_patterns32 id;
758 with Not_found -> raise Interpretation_not_found);
759 pattern32_matrix := List.filter (fun (_, id') -> id <> id') !pattern32_matrix;
760 load_patterns32 !pattern32_matrix
762 let remove_pretty_printer id =
764 Hashtbl.remove level1_patterns21 id;
765 with Not_found -> raise Pretty_printer_not_found);
766 pattern21_matrix := List.filter (fun (_, id') -> id <> id') !pattern21_matrix;
767 load_patterns21 !pattern21_matrix