1 (* Copyright (C) 2004, 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/
30 open DisambiguateTypes
33 (* the integer is an offset to be added to each location *)
34 exception NoWellTypedInterpretation of
36 ((Token.flocation list * string * string) list *
37 (DisambiguateTypes.domain_item * DisambiguateTypes.codomain_item) list *
38 Token.flocation option * string Lazy.t) list
39 exception PathNotWellFormed
41 (** raised when an environment is not enough informative to decide *)
42 exception Try_again of string Lazy.t
44 type aliases = bool * DisambiguateTypes.environment
45 type 'a disambiguator_input = string * int * 'a
48 let debug_print s = if debug then prerr_endline (Lazy.force s) else ()
51 (** print benchmark information *)
53 let max_refinements = ref 0 (* benchmarking is not thread safe *)
54 let actual_refinements = ref 0
55 let domain_size = ref 0
56 let choices_avg = ref 0.
59 let descr_of_domain_item = function
62 | Num i -> string_of_int i
65 | Ok of 'a * Cic.metasenv
66 | Ko of Token.flocation option * string Lazy.t
67 | Uncertain of Token.flocation option * string Lazy.t
69 let refine_term metasenv context uri term ugraph ~localization_tbl =
70 (* if benchmark then incr actual_refinements; *)
72 debug_print (lazy (sprintf "TEST_INTERPRETATION: %s" (CicPp.ppterm term)));
74 let term', _, metasenv',ugraph1 =
75 CicRefine.type_of_aux' metasenv context term ugraph ~localization_tbl in
76 (Ok (term', metasenv')),ugraph1
79 let rec process_exn loc =
81 HExtlib.Localized (loc,exn) -> process_exn (Some loc) exn
82 | CicRefine.Uncertain msg ->
83 debug_print (lazy ("UNCERTAIN!!! [" ^ (Lazy.force msg) ^ "] " ^ CicPp.ppterm term)) ;
84 Uncertain (loc,msg),ugraph
85 | CicRefine.RefineFailure msg ->
86 debug_print (lazy (sprintf "PRUNED!!!\nterm%s\nmessage:%s"
87 (CicPp.ppterm term) (Lazy.force msg)));
93 let refine_obj metasenv context uri obj ugraph ~localization_tbl =
94 assert (context = []);
95 debug_print (lazy (sprintf "TEST_INTERPRETATION: %s" (CicPp.ppobj obj))) ;
97 let obj', metasenv,ugraph =
98 CicRefine.typecheck metasenv uri obj ~localization_tbl
100 (Ok (obj', metasenv)),ugraph
103 let rec process_exn loc =
105 HExtlib.Localized (loc,exn) -> process_exn (Some loc) exn
106 | CicRefine.Uncertain msg ->
107 debug_print (lazy ("UNCERTAIN!!! [" ^ (Lazy.force msg) ^ "] " ^ CicPp.ppobj obj)) ;
108 Uncertain (loc,msg),ugraph
109 | CicRefine.RefineFailure msg ->
110 debug_print (lazy (sprintf "PRUNED!!!\nterm%s\nmessage:%s"
111 (CicPp.ppobj obj) (Lazy.force msg))) ;
117 let resolve (env: codomain_item Environment.t) (item: domain_item) ?(num = "") ?(args = []) () =
119 snd (Environment.find item env) env num args
121 failwith ("Domain item not found: " ^
122 (DisambiguateTypes.string_of_domain_item item))
124 (* TODO move it to Cic *)
125 let find_in_context name context =
126 let rec aux acc = function
127 | [] -> raise Not_found
128 | Cic.Name hd :: tl when hd = name -> acc
129 | _ :: tl -> aux (acc + 1) tl
133 let interpretate_term ~(context: Cic.name list) ~env ~uri ~is_path ast
137 let rec aux ~localize loc (context: Cic.name list) = function
138 | CicNotationPt.AttributedTerm (`Loc loc, term) ->
139 let res = aux ~localize loc context term in
140 if localize then Cic.CicHash.add localization_tbl res loc;
142 | CicNotationPt.AttributedTerm (_, term) -> aux ~localize loc context term
143 | CicNotationPt.Appl (CicNotationPt.Symbol (symb, i) :: args) ->
144 let cic_args = List.map (aux ~localize loc context) args in
145 resolve env (Symbol (symb, i)) ~args:cic_args ()
146 | CicNotationPt.Appl terms ->
147 Cic.Appl (List.map (aux ~localize loc context) terms)
148 | CicNotationPt.Binder (binder_kind, (var, typ), body) ->
149 let cic_type = aux_option ~localize loc context (Some `Type) typ in
150 let cic_name = CicNotationUtil.cic_name_of_name var in
151 let cic_body = aux ~localize loc (cic_name :: context) body in
152 (match binder_kind with
153 | `Lambda -> Cic.Lambda (cic_name, cic_type, cic_body)
155 | `Forall -> Cic.Prod (cic_name, cic_type, cic_body)
157 resolve env (Symbol ("exists", 0))
158 ~args:[ cic_type; Cic.Lambda (cic_name, cic_type, cic_body) ] ())
159 | CicNotationPt.Case (term, indty_ident, outtype, branches) ->
160 let cic_term = aux ~localize loc context term in
161 let cic_outtype = aux_option ~localize loc context None outtype in
162 let do_branch ((head, _, args), term) =
163 let rec do_branch' context = function
164 | [] -> aux ~localize loc context term
165 | (name, typ) :: tl ->
166 let cic_name = CicNotationUtil.cic_name_of_name name in
167 let cic_body = do_branch' (cic_name :: context) tl in
170 | None -> Cic.Implicit (Some `Type)
171 | Some typ -> aux ~localize loc context typ
173 Cic.Lambda (cic_name, typ, cic_body)
175 do_branch' context args
177 let (indtype_uri, indtype_no) =
178 match indty_ident with
179 | Some (indty_ident, _) ->
180 (match resolve env (Id indty_ident) () with
181 | Cic.MutInd (uri, tyno, _) -> (uri, tyno)
183 raise (Try_again (lazy "The type of the term to be matched
186 raise (Invalid_choice (lazy "The type of the term to be matched is not (co)inductive!")))
188 let fst_constructor =
190 | ((head, _, _), _) :: _ -> head
191 | [] -> raise (Invalid_choice (lazy "The type of the term to be matched is an inductive type without constructors that cannot be determined"))
193 (match resolve env (Id fst_constructor) () with
194 | Cic.MutConstruct (indtype_uri, indtype_no, _, _) ->
195 (indtype_uri, indtype_no)
197 raise (Try_again (lazy "The type of the term to be matched
200 raise (Invalid_choice (lazy "The type of the term to be matched is not (co)inductive!")))
202 Cic.MutCase (indtype_uri, indtype_no, cic_outtype, cic_term,
203 (List.map do_branch branches))
204 | CicNotationPt.Cast (t1, t2) ->
205 let cic_t1 = aux ~localize loc context t1 in
206 let cic_t2 = aux ~localize loc context t2 in
207 Cic.Cast (cic_t1, cic_t2)
208 | CicNotationPt.LetIn ((name, typ), def, body) ->
209 let cic_def = aux ~localize loc context def in
210 let cic_name = CicNotationUtil.cic_name_of_name name in
214 | Some t -> Cic.Cast (cic_def, aux ~localize loc context t)
216 let cic_body = aux ~localize loc (cic_name :: context) body in
217 Cic.LetIn (cic_name, cic_def, cic_body)
218 | CicNotationPt.LetRec (kind, defs, body) ->
221 (fun acc (_, (name, _), _, _) ->
222 CicNotationUtil.cic_name_of_name name :: acc)
226 let unlocalized_body = aux ~localize:false loc context' body in
227 match unlocalized_body with
228 Cic.Rel 1 -> `AvoidLetInNoAppl
229 | Cic.Appl (Cic.Rel 1::l) ->
234 let t',subst,metasenv =
235 CicMetaSubst.delift_rels [] [] 1 t
238 assert (metasenv=[]);
241 (* We can avoid the LetIn. But maybe we need to recompute l'
242 so that it is localized *)
245 CicNotationPt.AttributedTerm (_,CicNotationPt.Appl(_::l)) ->
246 let l' = List.map (aux ~localize loc context) l in
252 CicMetaSubst.DeliftingARelWouldCaptureAFreeVariable ->
254 `AddLetIn (aux ~localize loc context' body)
256 `AddLetIn unlocalized_body)
259 `AddLetIn (aux ~localize loc context' body)
261 `AddLetIn unlocalized_body
265 (fun (params, (name, typ), body, decr_idx) ->
266 let add_binders kind t =
268 (fun var t -> CicNotationPt.Binder (kind, var, t)) params t
271 aux ~localize loc context' (add_binders `Lambda body) in
273 aux_option ~localize loc context (Some `Type)
274 (HExtlib.map_option (add_binders `Pi) typ) in
276 match CicNotationUtil.cic_name_of_name name with
278 CicNotationPt.fail loc
279 "Recursive functions cannot be anonymous"
280 | Cic.Name name -> name
282 (name, decr_idx, cic_type, cic_body))
285 let counter = ref ~-1 in
286 let build_term funs =
287 (* this is the body of the fold_right function below. Rationale: Fix
288 * and CoFix cases differs only in an additional index in the
289 * inductiveFun list, see Cic.term *)
292 (fun (var, _, _, _) cic ->
294 let fix = Cic.Fix (!counter,funs) in
296 `Recipe (`AddLetIn cic) ->
297 `Term (Cic.LetIn (Cic.Name var, fix, cic))
298 | `Recipe (`AvoidLetIn l) -> `Term (Cic.Appl (fix::l))
299 | `Recipe `AvoidLetInNoAppl -> `Term fix
300 | `Term t -> `Term (Cic.LetIn (Cic.Name var, fix, t)))
303 List.map (fun (name, _, typ, body) -> (name, typ, body)) funs
305 (fun (var, _, _, _) cic ->
307 let cofix = Cic.CoFix (!counter,funs) in
309 `Recipe (`AddLetIn cic) ->
310 `Term (Cic.LetIn (Cic.Name var, cofix, cic))
311 | `Recipe (`AvoidLetIn l) -> `Term (Cic.Appl (cofix::l))
312 | `Recipe `AvoidLetInNoAppl -> `Term cofix
313 | `Term t -> `Term (Cic.LetIn (Cic.Name var, cofix, t)))
316 List.fold_right (build_term inductiveFuns) inductiveFuns
319 `Recipe _ -> assert false
321 | CicNotationPt.Ident _
322 | CicNotationPt.Uri _ when is_path -> raise PathNotWellFormed
323 | CicNotationPt.Ident (name, subst)
324 | CicNotationPt.Uri (name, subst) as ast ->
325 let is_uri = function CicNotationPt.Uri _ -> true | _ -> false in
327 if is_uri ast then raise Not_found;(* don't search the env for URIs *)
328 let index = find_in_context name context in
329 if subst <> None then
330 CicNotationPt.fail loc "Explicit substitutions not allowed here";
334 if is_uri ast then (* we have the URI, build the term out of it *)
336 CicUtil.term_of_uri (UriManager.uri_of_string name)
337 with UriManager.IllFormedUri _ ->
338 CicNotationPt.fail loc "Ill formed URI"
340 resolve env (Id name) ()
344 List.map (fun uri -> UriManager.name_of_uri uri, uri) uris
351 List.assoc s ids_to_uris, aux ~localize loc context term
353 raise (Invalid_choice (lazy "The provided explicit named substitution is trying to instantiate a named variable the object is not abstracted on"))))
355 | None -> List.map (fun uri -> uri, Cic.Implicit None) uris)
359 | Cic.Const (uri, []) ->
360 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
361 let uris = CicUtil.params_of_obj o in
362 Cic.Const (uri, mk_subst uris)
363 | Cic.Var (uri, []) ->
364 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
365 let uris = CicUtil.params_of_obj o in
366 Cic.Var (uri, mk_subst uris)
367 | Cic.MutInd (uri, i, []) ->
369 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
370 let uris = CicUtil.params_of_obj o in
371 Cic.MutInd (uri, i, mk_subst uris)
373 CicEnvironment.Object_not_found _ ->
374 (* if we are here it is probably the case that during the
375 definition of a mutual inductive type we have met an
376 occurrence of the type in one of its constructors.
377 However, the inductive type is not yet in the environment
379 (*here the explicit_named_substituion is assumed to be of length 0 *)
380 Cic.MutInd (uri,i,[]))
381 | Cic.MutConstruct (uri, i, j, []) ->
382 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
383 let uris = CicUtil.params_of_obj o in
384 Cic.MutConstruct (uri, i, j, mk_subst uris)
385 | Cic.Meta _ | Cic.Implicit _ as t ->
387 debug_print (lazy (sprintf
388 "Warning: %s must be instantiated with _[%s] but we do not enforce it"
392 (fun (s, term) -> s ^ " := " ^ CicNotationPtPp.pp_term term)
397 raise (Invalid_choice (lazy "??? Can this happen?"))
399 CicEnvironment.CircularDependency _ ->
400 raise (Invalid_choice (lazy "Circular dependency in the environment"))))
401 | CicNotationPt.Implicit -> Cic.Implicit None
402 | CicNotationPt.UserInput -> Cic.Implicit (Some `Hole)
403 | CicNotationPt.Num (num, i) -> resolve env (Num i) ~num ()
404 | CicNotationPt.Meta (index, subst) ->
409 | Some term -> Some (aux ~localize loc context term))
412 Cic.Meta (index, cic_subst)
413 | CicNotationPt.Sort `Prop -> Cic.Sort Cic.Prop
414 | CicNotationPt.Sort `Set -> Cic.Sort Cic.Set
415 | CicNotationPt.Sort (`Type u) -> Cic.Sort (Cic.Type u)
416 | CicNotationPt.Sort `CProp -> Cic.Sort Cic.CProp
417 | CicNotationPt.Symbol (symbol, instance) ->
418 resolve env (Symbol (symbol, instance)) ()
419 | _ -> assert false (* god bless Bologna *)
420 and aux_option ~localize loc (context: Cic.name list) annotation = function
421 | None -> Cic.Implicit annotation
422 | Some term -> aux ~localize loc context term
424 aux ~localize:true HExtlib.dummy_floc context ast
426 let interpretate_path ~context path =
427 let localization_tbl = Cic.CicHash.create 23 in
428 (* here we are throwing away useful localization informations!!! *)
430 interpretate_term ~context ~env:Environment.empty ~uri:None ~is_path:true
431 path ~localization_tbl, localization_tbl)
433 let interpretate_obj ~context ~env ~uri ~is_path obj ~localization_tbl =
434 assert (context = []);
435 assert (is_path = false);
436 let interpretate_term = interpretate_term ~localization_tbl in
438 | CicNotationPt.Inductive (params,tyl) ->
439 let uri = match uri with Some uri -> uri | None -> assert false in
443 (fun (context,res) (name,t) ->
446 None -> CicNotationPt.Implicit
448 let name = CicNotationUtil.cic_name_of_name name in
449 name::context,(name, interpretate_term context env None false t)::res
452 context,List.rev res in
454 List.fold_right (fun (name,ty) t -> Cic.Prod (name,ty,t)) params in
458 (*here the explicit_named_substituion is assumed to be of length 0 *)
459 (fun (i,res) (name,_,_,_) ->
460 i + 1,(name,name,Cic.MutInd (uri,i,[]))::res
462 let con_env = DisambiguateTypes.env_of_list name_to_uris env in
465 (fun (name,b,ty,cl) ->
466 let ty' = add_params (interpretate_term context env None false ty) in
471 add_params (interpretate_term context con_env None false ty)
479 Cic.InductiveDefinition (tyl,[],List.length params,[])
480 | CicNotationPt.Record (params,name,ty,fields) ->
481 let uri = match uri with Some uri -> uri | None -> assert false in
485 (fun (context,res) (name,t) ->
488 None -> CicNotationPt.Implicit
490 let name = CicNotationUtil.cic_name_of_name name in
491 name::context,(name, interpretate_term context env None false t)::res
494 context,List.rev res in
497 (fun (name,ty) t -> Cic.Prod (name,ty,t)) params in
498 let ty' = add_params (interpretate_term context env None false ty) in
502 (fun (context,res) (name,ty,_coercion,arity) ->
503 let context' = Cic.Name name :: context in
504 context',(name,interpretate_term context env None false ty)::res
505 ) (context,[]) fields) in
507 (*here the explicit_named_substituion is assumed to be of length 0 *)
508 let mutind = Cic.MutInd (uri,0,[]) in
509 if params = [] then mutind
512 (mutind::CicUtil.mk_rels (List.length params) (List.length fields)) in
515 (fun t (name,ty) -> Cic.Prod (Cic.Name name,ty,t))
517 let con' = add_params con in
518 let tyl = [name,true,ty',["mk_" ^ name,con']] in
519 let field_names = List.map (fun (x,_,y,z) -> x,y,z) fields in
520 Cic.InductiveDefinition
521 (tyl,[],List.length params,[`Class (`Record field_names)])
522 | CicNotationPt.Theorem (flavour, name, ty, bo) ->
523 let attrs = [`Flavour flavour] in
524 let ty' = interpretate_term [] env None false ty in
525 (match bo,flavour with
527 Cic.Constant (name,None,ty',[],attrs)
528 | Some bo,`Axiom -> assert false
530 Cic.CurrentProof (name,[],Cic.Implicit None,ty',[],attrs)
532 let bo' = Some (interpretate_term [] env None false bo) in
533 Cic.Constant (name,bo',ty',[],attrs))
536 (* e.g. [5;1;1;1;2;3;4;1;2] -> [2;1;4;3;5] *)
538 let module SortedItem =
540 type t = DisambiguateTypes.domain_item
541 let compare = Pervasives.compare
544 let module Map = Map.Make (SortedItem) in
546 let rev_l = List.rev l in
547 let (members, uniq_rev_l) =
549 (fun (members, rev_l) (loc,elt) ->
551 let locs = Map.find elt members in
552 if List.mem loc locs then
555 Map.add elt (loc::locs) members, rev_l
557 | Not_found -> Map.add elt [loc] members, elt :: rev_l)
558 (Map.empty, []) rev_l
561 (fun e -> try Map.find e members,e with Not_found -> assert false)
564 (* "aux" keeps domain in reverse order and doesn't care about duplicates.
565 * Domain item more in deep in the list will be processed first.
567 let rec domain_rev_of_term ?(loc = HExtlib.dummy_floc) context = function
568 | CicNotationPt.AttributedTerm (`Loc loc, term) ->
569 domain_rev_of_term ~loc context term
570 | CicNotationPt.AttributedTerm (_, term) ->
571 domain_rev_of_term ~loc context term
572 | CicNotationPt.Appl terms ->
574 (fun dom term -> domain_rev_of_term ~loc context term @ dom) [] terms
575 | CicNotationPt.Binder (kind, (var, typ), body) ->
578 | `Exists -> [ loc, Symbol ("exists", 0) ]
581 let type_dom = domain_rev_of_term_option ~loc context typ in
583 domain_rev_of_term ~loc
584 (CicNotationUtil.cic_name_of_name var :: context) body
586 body_dom @ type_dom @ kind_dom
587 | CicNotationPt.Case (term, indty_ident, outtype, branches) ->
588 let term_dom = domain_rev_of_term ~loc context term in
589 let outtype_dom = domain_rev_of_term_option loc context outtype in
590 let get_first_constructor = function
592 | ((head, _, _), _) :: _ -> [ loc, Id head ]
594 let do_branch ((head, _, args), term) =
595 let (term_context, args_domain) =
597 (fun (cont, dom) (name, typ) ->
598 (CicNotationUtil.cic_name_of_name name :: cont,
601 | Some typ -> domain_rev_of_term ~loc cont typ @ dom)))
604 args_domain @ domain_rev_of_term ~loc term_context term
607 List.fold_left (fun dom branch -> do_branch branch @ dom) [] branches
609 branches_dom @ outtype_dom @ term_dom @
610 (match indty_ident with
611 | None -> get_first_constructor branches
612 | Some (ident, _) -> [ loc, Id ident ])
613 | CicNotationPt.Cast (term, ty) ->
614 let term_dom = domain_rev_of_term ~loc context term in
615 let ty_dom = domain_rev_of_term ~loc context ty in
617 | CicNotationPt.LetIn ((var, typ), body, where) ->
618 let body_dom = domain_rev_of_term ~loc context body in
619 let type_dom = domain_rev_of_term_option loc context typ in
621 domain_rev_of_term ~loc
622 (CicNotationUtil.cic_name_of_name var :: context) where
624 where_dom @ type_dom @ body_dom
625 | CicNotationPt.LetRec (kind, defs, where) ->
626 let add_defs context =
628 (fun acc (_, (var, _), _, _) ->
629 CicNotationUtil.cic_name_of_name var :: acc
631 let where_dom = domain_rev_of_term ~loc (add_defs context) where in
634 (fun dom (params, (_, typ), body, _) ->
638 (fun acc (var,_) -> CicNotationUtil.cic_name_of_name var :: acc)
641 domain_rev_of_term ~loc context' body @
642 domain_rev_of_term_option ~loc context typ @
646 (fun (context,res) (var,ty) ->
647 CicNotationUtil.cic_name_of_name var :: context,
648 res @ domain_rev_of_term_option ~loc context ty)
649 (add_defs context,[]) params))
653 | CicNotationPt.Ident (name, subst) ->
655 (* the next line can raise Not_found *)
656 ignore(find_in_context name context);
657 if subst <> None then
658 CicNotationPt.fail loc "Explicit substitutions not allowed here"
663 | None -> [loc, Id name]
666 (fun dom (_, term) ->
667 let dom' = domain_rev_of_term ~loc context term in
669 [loc, Id name] subst))
670 | CicNotationPt.Uri _ -> []
671 | CicNotationPt.Implicit -> []
672 | CicNotationPt.Num (num, i) -> [loc, Num i ]
673 | CicNotationPt.Meta (index, local_context) ->
675 (fun dom term -> domain_rev_of_term_option loc context term @ dom) []
677 | CicNotationPt.Sort _ -> []
678 | CicNotationPt.Symbol (symbol, instance) -> [loc, Symbol (symbol, instance) ]
679 | CicNotationPt.UserInput
680 | CicNotationPt.Literal _
681 | CicNotationPt.Layout _
682 | CicNotationPt.Magic _
683 | CicNotationPt.Variable _ -> assert false
685 and domain_rev_of_term_option ~loc context = function
687 | Some t -> domain_rev_of_term ~loc context t
689 let domain_of_term ~context ast = rev_uniq (domain_rev_of_term context ast)
691 let domain_of_obj ~context ast =
692 assert (context = []);
695 | CicNotationPt.Theorem (_,_,ty,bo) ->
698 | Some bo -> domain_rev_of_term [] bo) @
699 domain_rev_of_term [] ty
700 | CicNotationPt.Inductive (params,tyl) ->
707 (fun (_,ty) -> domain_rev_of_term [] ty) cl) @
708 domain_rev_of_term [] ty) tyl) in
714 | Some ty -> domain_rev_of_term [] ty @ dom
719 not ( List.exists (fun (name',_) ->
720 match CicNotationUtil.cic_name_of_name name' with
721 Cic.Anonymous -> false
722 | Cic.Name name' -> name = Id name') params
723 || List.exists (fun (name',_,_,_) -> name = Id name') tyl)
725 | CicNotationPt.Record (params,_,ty,fields) ->
728 (List.rev_map (fun (_,ty,_,_) -> domain_rev_of_term [] ty) fields) in
734 | Some ty -> domain_rev_of_term [] ty @ dom
735 ) (dom @ domain_rev_of_term [] ty) params
739 not ( List.exists (fun (name',_) ->
740 match CicNotationUtil.cic_name_of_name name' with
741 Cic.Anonymous -> false
742 | Cic.Name name' -> name = Id name') params
743 || List.exists (fun (name',_,_,_) -> name = Id name') fields)
749 let domain_diff dom1 dom2 =
750 (* let domain_diff = Domain.diff *)
754 | Symbol (symb, 0) ->
756 Symbol (symb',_) when symb = symb' -> true
765 List.filter (fun (_,elt) -> not (is_in_dom2 elt)) dom1
767 module type Disambiguator =
769 val disambiguate_term :
770 ?fresh_instances:bool ->
772 context:Cic.context ->
773 metasenv:Cic.metasenv ->
774 ?initial_ugraph:CicUniv.universe_graph ->
775 aliases:DisambiguateTypes.environment ->(* previous interpretation status *)
776 universe:DisambiguateTypes.multiple_environment option ->
777 CicNotationPt.term disambiguator_input ->
778 ((DisambiguateTypes.domain_item * DisambiguateTypes.codomain_item) list *
779 Cic.metasenv * (* new metasenv *)
781 CicUniv.universe_graph) list * (* disambiguated term *)
784 val disambiguate_obj :
785 ?fresh_instances:bool ->
787 aliases:DisambiguateTypes.environment ->(* previous interpretation status *)
788 universe:DisambiguateTypes.multiple_environment option ->
789 uri:UriManager.uri option -> (* required only for inductive types *)
790 CicNotationPt.obj disambiguator_input ->
791 ((DisambiguateTypes.domain_item * DisambiguateTypes.codomain_item) list *
792 Cic.metasenv * (* new metasenv *)
794 CicUniv.universe_graph) list * (* disambiguated obj *)
798 module Make (C: Callbacks) =
800 let choices_of_id dbd id =
801 let uris = Whelp.locate ~dbd id in
806 (C.input_or_locate_uri
807 ~title:("URI matching \"" ^ id ^ "\" unknown.") ~id ())
813 C.interactive_user_uri_choice ~selection_mode:`MULTIPLE
814 ~ok:"Try selected." ~enable_button_for_non_vars:true
815 ~title:"Ambiguous input." ~id
816 ~msg: ("Ambiguous input \"" ^ id ^
817 "\". Please, choose one or more interpretations:")
822 (UriManager.string_of_uri uri,
825 CicUtil.term_of_uri uri
827 debug_print (lazy (UriManager.string_of_uri uri));
828 debug_print (lazy (Printexc.to_string exn));
834 let refine_profiler = HExtlib.profile "disambiguate_thing.refine_thing"
836 let disambiguate_thing ~dbd ~context ~metasenv
837 ?(initial_ugraph = CicUniv.empty_ugraph) ~aliases ~universe
838 ~uri ~pp_thing ~domain_of_thing ~interpretate_thing ~refine_thing
839 (thing_txt,thing_txt_prefix_len,thing)
841 debug_print (lazy "DISAMBIGUATE INPUT");
842 let disambiguate_context = (* cic context -> disambiguate context *)
844 (function None -> Cic.Anonymous | Some (name, _) -> name)
847 debug_print (lazy ("TERM IS: " ^ (pp_thing thing)));
848 let thing_dom = domain_of_thing ~context:disambiguate_context thing in
849 debug_print (lazy (sprintf "DISAMBIGUATION DOMAIN: %s"
850 (string_of_domain (List.map snd thing_dom))));
852 debug_print (lazy (sprintf "DISAMBIGUATION ENVIRONMENT: %s"
853 (DisambiguatePp.pp_environment aliases)));
854 debug_print (lazy (sprintf "DISAMBIGUATION UNIVERSE: %s"
855 (match universe with None -> "None" | Some _ -> "Some _")));
858 Environment.fold (fun item _ dom -> item :: dom) aliases []
860 let todo_dom = domain_diff thing_dom current_dom in
861 (* (2) lookup function for any item (Id/Symbol/Num) *)
865 let lookup_in_library () =
867 | Id id -> choices_of_id dbd id
868 | Symbol (symb, _) ->
869 List.map DisambiguateChoices.mk_choice
870 (TermAcicContent.lookup_interpretations symb)
872 DisambiguateChoices.lookup_num_choices ()
875 | None -> lookup_in_library ()
880 | Symbol (symb, _) -> Symbol (symb, 0)
883 Environment.find item e
884 with Not_found -> lookup_in_library ())
891 if benchmark then begin
892 let per_item_choices =
896 let len = List.length (lookup_choices dom_item) in
897 debug_print (lazy (sprintf "BENCHMARK %s: %d"
898 (string_of_domain_item dom_item) len));
900 with No_choices _ -> 0)
903 max_refinements := List.fold_left ( * ) 1 per_item_choices;
904 actual_refinements := 0;
905 domain_size := List.length thing_dom;
907 (float_of_int !max_refinements) ** (1. /. float_of_int !domain_size)
913 (* (3) test an interpretation filling with meta uninterpreted identifiers
915 let test_env aliases todo_dom ugraph =
922 | Id _ | Num _ -> (fun _ _ _ -> Cic.Implicit (Some `Closed))
923 | Symbol _ -> (fun _ _ _ -> Cic.Implicit None))) env)
927 let localization_tbl = Cic.CicHash.create 503 in
929 interpretate_thing ~context:disambiguate_context ~env:filled_env
930 ~uri ~is_path:false thing ~localization_tbl
934 refine_thing metasenv context uri cic_thing ugraph ~localization_tbl
937 in refine_profiler.HExtlib.profile foo ()
939 | Try_again msg -> Uncertain (None,msg), ugraph
940 | Invalid_choice msg -> Ko (None,msg), ugraph
942 (* (4) build all possible interpretations *)
943 let (@@) (l1,l2) (l1',l2') = l1@l1', l2@l2' in
944 let rec aux aliases diff lookup_in_todo_dom todo_dom base_univ =
947 assert (lookup_in_todo_dom = None);
948 (match test_env aliases [] base_univ with
949 | Ok (thing, metasenv),new_univ ->
950 [ aliases, diff, metasenv, thing, new_univ ], []
952 | Uncertain (loc,msg),_ -> [],[aliases,diff,loc,msg])
953 | (locs,item) :: remaining_dom ->
954 debug_print (lazy (sprintf "CHOOSED ITEM: %s"
955 (string_of_domain_item item)));
957 match lookup_in_todo_dom with
958 None -> lookup_choices item
959 | Some choices -> choices in
964 lazy ("No choices for " ^ string_of_domain_item item)]
966 (* just one choice. We perform a one-step look-up and
967 if the next set of choices is also a singleton we
968 skip this refinement step *)
969 debug_print(lazy (sprintf "%s CHOSEN" (fst codomain_item)));
970 let new_env = Environment.add item codomain_item aliases in
971 let new_diff = (item,codomain_item)::diff in
972 let lookup_in_todo_dom,next_choice_is_single =
973 match remaining_dom with
976 let choices = lookup_choices he in
977 Some choices,List.length choices = 1
979 if next_choice_is_single then
980 aux new_env new_diff lookup_in_todo_dom remaining_dom
983 (match test_env new_env remaining_dom base_univ with
984 | Ok (thing, metasenv),new_univ ->
985 (match remaining_dom with
987 [ new_env, new_diff, metasenv, thing, new_univ ], []
989 aux new_env new_diff lookup_in_todo_dom
990 remaining_dom new_univ)
991 | Uncertain (loc,msg),new_univ ->
992 (match remaining_dom with
993 | [] -> [], [new_env,new_diff,loc,msg]
995 aux new_env new_diff lookup_in_todo_dom
996 remaining_dom new_univ)
997 | Ko (loc,msg),_ -> [], [new_env,new_diff,loc,msg])
999 let rec filter univ = function
1001 | codomain_item :: tl ->
1002 debug_print(lazy (sprintf "%s CHOSEN" (fst codomain_item)));
1003 let new_env = Environment.add item codomain_item aliases in
1004 let new_diff = (item,codomain_item)::diff in
1005 (match test_env new_env remaining_dom univ with
1006 | Ok (thing, metasenv),new_univ ->
1007 (match remaining_dom with
1008 | [] -> [new_env,new_diff,metasenv,thing,new_univ], []
1009 | _ -> aux new_env new_diff None remaining_dom new_univ
1012 | Uncertain (loc,msg),new_univ ->
1013 (match remaining_dom with
1014 | [] -> [],[new_env,new_diff,loc,msg]
1015 | _ -> aux new_env new_diff None remaining_dom new_univ
1018 | Ko (loc,msg),_ -> ([],[new_env,new_diff,loc,msg]) @@ filter univ tl)
1020 filter base_univ choices
1022 let aux' aliases diff lookup_in_todo_dom todo_dom base_univ =
1023 match test_env aliases todo_dom base_univ with
1026 aux aliases diff lookup_in_todo_dom todo_dom base_univ
1027 | Ko (loc,msg),_ -> ([],[aliases,diff,loc,msg]) in
1028 let base_univ = initial_ugraph in
1031 match aux' aliases [] None todo_dom base_univ with
1035 (fun (env,diff,loc,msg) ->
1038 (fun (locs,domain_item) ->
1041 fst (Environment.find domain_item env)
1043 Some (locs,descr_of_domain_item domain_item,description)
1051 raise (NoWellTypedInterpretation (0,errors))
1052 | [_,diff,metasenv,t,ugraph],_ ->
1053 debug_print (lazy "SINGLE INTERPRETATION");
1054 [diff,metasenv,t,ugraph], false
1057 (lazy (sprintf "MANY INTERPRETATIONS (%d)" (List.length l)));
1060 (fun (env, _, _, _, _) ->
1062 (fun (locs,domain_item) ->
1064 fst (Environment.find domain_item env)
1066 locs,descr_of_domain_item domain_item, description)
1071 C.interactive_interpretation_choice
1072 thing_txt thing_txt_prefix_len choices
1074 (List.map (fun n->let _,d,m,t,u= List.nth l n in d,m,t,u) choosed),
1079 CicEnvironment.CircularDependency s ->
1080 failwith "Disambiguate: circular dependency"
1082 let disambiguate_term ?(fresh_instances=false) ~dbd ~context ~metasenv
1083 ?(initial_ugraph = CicUniv.empty_ugraph) ~aliases ~universe
1084 (text,prefix_len,term)
1087 if fresh_instances then CicNotationUtil.freshen_term term else term
1089 disambiguate_thing ~dbd ~context ~metasenv ~initial_ugraph ~aliases
1090 ~universe ~uri:None ~pp_thing:CicNotationPp.pp_term
1091 ~domain_of_thing:domain_of_term ~interpretate_thing:interpretate_term
1092 ~refine_thing:refine_term (text,prefix_len,term)
1094 let disambiguate_obj ?(fresh_instances=false) ~dbd ~aliases ~universe ~uri
1095 (text,prefix_len,obj)
1098 if fresh_instances then CicNotationUtil.freshen_obj obj else obj
1100 disambiguate_thing ~dbd ~context:[] ~metasenv:[] ~aliases ~universe ~uri
1101 ~pp_thing:CicNotationPp.pp_obj ~domain_of_thing:domain_of_obj
1102 ~interpretate_thing:interpretate_obj ~refine_thing:refine_obj
1103 (text,prefix_len,obj)