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/
28 open DisambiguateTypes
31 exception NoWellTypedInterpretation of
32 (Token.flocation option * string Lazy.t) list
33 exception PathNotWellFormed
35 (** raised when an environment is not enough informative to decide *)
36 exception Try_again of string Lazy.t
38 type aliases = bool * DisambiguateTypes.environment
41 let debug_print s = if debug then prerr_endline (Lazy.force s) else ()
44 (** print benchmark information *)
46 let max_refinements = ref 0 (* benchmarking is not thread safe *)
47 let actual_refinements = ref 0
48 let domain_size = ref 0
49 let choices_avg = ref 0.
52 let descr_of_domain_item = function
55 | Num i -> string_of_int i
58 | Ok of 'a * Cic.metasenv
59 | Ko of Token.flocation option * string Lazy.t
60 | Uncertain of Token.flocation option * string Lazy.t
62 let refine_term metasenv context uri term ugraph ~localization_tbl =
63 (* if benchmark then incr actual_refinements; *)
65 debug_print (lazy (sprintf "TEST_INTERPRETATION: %s" (CicPp.ppterm term)));
67 let term', _, metasenv',ugraph1 =
68 CicRefine.type_of_aux' metasenv context term ugraph ~localization_tbl in
69 (Ok (term', metasenv')),ugraph1
72 let rec process_exn loc =
74 HExtlib.Localized (loc,exn) -> process_exn (Some loc) exn
75 | CicRefine.Uncertain msg ->
76 debug_print (lazy ("UNCERTAIN!!! [" ^ (Lazy.force msg) ^ "] " ^ CicPp.ppterm term)) ;
77 Uncertain (loc,msg),ugraph
78 | CicRefine.RefineFailure msg ->
79 debug_print (lazy (sprintf "PRUNED!!!\nterm%s\nmessage:%s"
80 (CicPp.ppterm term) (Lazy.force msg)));
86 let refine_obj metasenv context uri obj ugraph ~localization_tbl =
87 assert (context = []);
88 debug_print (lazy (sprintf "TEST_INTERPRETATION: %s" (CicPp.ppobj obj))) ;
90 let obj', metasenv,ugraph =
91 CicRefine.typecheck metasenv uri obj ~localization_tbl
93 (Ok (obj', metasenv)),ugraph
96 let rec process_exn loc =
98 HExtlib.Localized (loc,exn) -> process_exn (Some loc) exn
99 | CicRefine.Uncertain msg ->
100 debug_print (lazy ("UNCERTAIN!!! [" ^ (Lazy.force msg) ^ "] " ^ CicPp.ppobj obj)) ;
101 Uncertain (loc,msg),ugraph
102 | CicRefine.RefineFailure msg ->
103 debug_print (lazy (sprintf "PRUNED!!!\nterm%s\nmessage:%s"
104 (CicPp.ppobj obj) (Lazy.force msg))) ;
110 let resolve (env: codomain_item Environment.t) (item: domain_item) ?(num = "") ?(args = []) () =
112 snd (Environment.find item env) env num args
114 failwith ("Domain item not found: " ^
115 (DisambiguateTypes.string_of_domain_item item))
117 (* TODO move it to Cic *)
118 let find_in_context name (context: Cic.name list) =
119 let rec aux acc = function
120 | [] -> raise Not_found
121 | Cic.Name hd :: tl when hd = name -> acc
122 | _ :: tl -> aux (acc + 1) tl
126 let interpretate_term ~(context: Cic.name list) ~env ~uri ~is_path ast
130 let rec aux loc (context: Cic.name list) = function
131 | CicNotationPt.AttributedTerm (`Loc loc, term) ->
132 let res = aux loc context term in
133 Cic.CicHash.add localization_tbl res loc;
135 | CicNotationPt.AttributedTerm (_, term) -> aux loc context term
136 | CicNotationPt.Appl (CicNotationPt.Symbol (symb, i) :: args) ->
137 let cic_args = List.map (aux loc context) args in
138 resolve env (Symbol (symb, i)) ~args:cic_args ()
139 | CicNotationPt.Appl terms -> Cic.Appl (List.map (aux loc context) terms)
140 | CicNotationPt.Binder (binder_kind, (var, typ), body) ->
141 let cic_type = aux_option loc context (Some `Type) typ in
142 let cic_name = CicNotationUtil.cic_name_of_name var in
143 let cic_body = aux loc (cic_name :: context) body in
144 (match binder_kind with
145 | `Lambda -> Cic.Lambda (cic_name, cic_type, cic_body)
147 | `Forall -> Cic.Prod (cic_name, cic_type, cic_body)
149 resolve env (Symbol ("exists", 0))
150 ~args:[ cic_type; Cic.Lambda (cic_name, cic_type, cic_body) ] ())
151 | CicNotationPt.Case (term, indty_ident, outtype, branches) ->
152 let cic_term = aux loc context term in
153 let cic_outtype = aux_option loc context None outtype in
154 let do_branch ((head, _, args), term) =
155 let rec do_branch' context = function
156 | [] -> aux loc context term
157 | (name, typ) :: tl ->
158 let cic_name = CicNotationUtil.cic_name_of_name name in
159 let cic_body = do_branch' (cic_name :: context) tl in
162 | None -> Cic.Implicit (Some `Type)
163 | Some typ -> aux loc context typ
165 Cic.Lambda (cic_name, typ, cic_body)
167 do_branch' context args
169 let (indtype_uri, indtype_no) =
170 match indty_ident with
171 | Some (indty_ident, _) ->
172 (match resolve env (Id indty_ident) () with
173 | Cic.MutInd (uri, tyno, _) -> (uri, tyno)
175 raise (Try_again (lazy "The type of the term to be matched
178 raise (Invalid_choice (lazy "The type of the term to be matched is not (co)inductive!")))
180 let fst_constructor =
182 | ((head, _, _), _) :: _ -> head
183 | [] -> raise (Invalid_choice (lazy "The type of the term to be matched is an inductive type without constructors that cannot be determined"))
185 (match resolve env (Id fst_constructor) () with
186 | Cic.MutConstruct (indtype_uri, indtype_no, _, _) ->
187 (indtype_uri, indtype_no)
189 raise (Try_again (lazy "The type of the term to be matched
192 raise (Invalid_choice (lazy "The type of the term to be matched is not (co)inductive!")))
194 Cic.MutCase (indtype_uri, indtype_no, cic_outtype, cic_term,
195 (List.map do_branch branches))
196 | CicNotationPt.Cast (t1, t2) ->
197 let cic_t1 = aux loc context t1 in
198 let cic_t2 = aux loc context t2 in
199 Cic.Cast (cic_t1, cic_t2)
200 | CicNotationPt.LetIn ((name, typ), def, body) ->
201 let cic_def = aux loc context def in
202 let cic_name = CicNotationUtil.cic_name_of_name name in
206 | Some t -> Cic.Cast (cic_def, aux loc context t)
208 let cic_body = aux loc (cic_name :: context) body in
209 Cic.LetIn (cic_name, cic_def, cic_body)
210 | CicNotationPt.LetRec (kind, defs, body) ->
213 (fun acc ((name, _), _, _) ->
214 CicNotationUtil.cic_name_of_name name :: acc)
217 let cic_body = aux loc context' body in
220 (fun ((name, typ), body, decr_idx) ->
221 let cic_body = aux loc context' body in
222 let cic_type = aux_option loc context (Some `Type) typ in
224 match CicNotationUtil.cic_name_of_name name with
226 CicNotationPt.fail loc
227 "Recursive functions cannot be anonymous"
228 | Cic.Name name -> name
230 (name, decr_idx, cic_type, cic_body))
233 let counter = ref ~-1 in
234 let build_term funs =
235 (* this is the body of the fold_right function below. Rationale: Fix
236 * and CoFix cases differs only in an additional index in the
237 * inductiveFun list, see Cic.term *)
240 (fun (var, _, _, _) cic ->
242 let fix = Cic.Fix (!counter,funs) in
245 | (Cic.Appl (Cic.Rel 1::l)) ->
250 let t',subst,metasenv =
251 CicMetaSubst.delift_rels [] [] 1 t
254 assert (metasenv=[]);
259 CicMetaSubst.DeliftingARelWouldCaptureAFreeVariable ->
260 Cic.LetIn (Cic.Name var, fix, cic))
261 | _ -> Cic.LetIn (Cic.Name var, fix, cic))
264 List.map (fun (name, _, typ, body) -> (name, typ, body)) funs
266 (fun (var, _, _, _) cic ->
268 let cofix = Cic.CoFix (!counter,funs) in
271 | (Cic.Appl (Cic.Rel 1::l)) -> Cic.Appl (cofix::l)
272 | _ -> Cic.LetIn (Cic.Name var, cofix, cic))
274 List.fold_right (build_term inductiveFuns) inductiveFuns cic_body
275 | CicNotationPt.Ident _
276 | CicNotationPt.Uri _ when is_path -> raise PathNotWellFormed
277 | CicNotationPt.Ident (name, subst)
278 | CicNotationPt.Uri (name, subst) as ast ->
279 let is_uri = function CicNotationPt.Uri _ -> true | _ -> false in
281 if is_uri ast then raise Not_found;(* don't search the env for URIs *)
282 let index = find_in_context name context in
283 if subst <> None then
284 CicNotationPt.fail loc "Explicit substitutions not allowed here";
288 if is_uri ast then (* we have the URI, build the term out of it *)
290 CicUtil.term_of_uri (UriManager.uri_of_string name)
291 with UriManager.IllFormedUri _ ->
292 CicNotationPt.fail loc "Ill formed URI"
294 resolve env (Id name) ()
298 List.map (fun uri -> UriManager.name_of_uri uri, uri) uris
305 List.assoc s ids_to_uris, aux loc context term
307 raise (Invalid_choice (lazy "The provided explicit named substitution is trying to instantiate a named variable the object is not abstracted on"))))
309 | None -> List.map (fun uri -> uri, Cic.Implicit None) uris)
313 | Cic.Const (uri, []) ->
314 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
315 let uris = CicUtil.params_of_obj o in
316 Cic.Const (uri, mk_subst uris)
317 | Cic.Var (uri, []) ->
318 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
319 let uris = CicUtil.params_of_obj o in
320 Cic.Var (uri, mk_subst uris)
321 | Cic.MutInd (uri, i, []) ->
323 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
324 let uris = CicUtil.params_of_obj o in
325 Cic.MutInd (uri, i, mk_subst uris)
327 CicEnvironment.Object_not_found _ ->
328 (* if we are here it is probably the case that during the
329 definition of a mutual inductive type we have met an
330 occurrence of the type in one of its constructors.
331 However, the inductive type is not yet in the environment
333 (*here the explicit_named_substituion is assumed to be of length 0 *)
334 Cic.MutInd (uri,i,[]))
335 | Cic.MutConstruct (uri, i, j, []) ->
336 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
337 let uris = CicUtil.params_of_obj o in
338 Cic.MutConstruct (uri, i, j, mk_subst uris)
339 | Cic.Meta _ | Cic.Implicit _ as t ->
341 debug_print (lazy (sprintf
342 "Warning: %s must be instantiated with _[%s] but we do not enforce it"
346 (fun (s, term) -> s ^ " := " ^ CicNotationPtPp.pp_term term)
351 raise (Invalid_choice (lazy "??? Can this happen?"))
353 CicEnvironment.CircularDependency _ ->
354 raise (Invalid_choice (lazy "Circular dependency in the environment"))))
355 | CicNotationPt.Implicit -> Cic.Implicit None
356 | CicNotationPt.UserInput -> Cic.Implicit (Some `Hole)
357 | CicNotationPt.Num (num, i) -> resolve env (Num i) ~num ()
358 | CicNotationPt.Meta (index, subst) ->
361 (function None -> None | Some term -> Some (aux loc context term))
364 Cic.Meta (index, cic_subst)
365 | CicNotationPt.Sort `Prop -> Cic.Sort Cic.Prop
366 | CicNotationPt.Sort `Set -> Cic.Sort Cic.Set
367 | CicNotationPt.Sort (`Type u) -> Cic.Sort (Cic.Type u)
368 | CicNotationPt.Sort `CProp -> Cic.Sort Cic.CProp
369 | CicNotationPt.Symbol (symbol, instance) ->
370 resolve env (Symbol (symbol, instance)) ()
371 | _ -> assert false (* god bless Bologna *)
372 and aux_option loc (context: Cic.name list) annotation = function
373 | None -> Cic.Implicit annotation
374 | Some term -> aux loc context term
376 aux dummy_floc context ast
378 let interpretate_path ~context path =
379 let localization_tbl = Cic.CicHash.create 23 in
380 (* here we are throwing away useful localization informations!!! *)
382 interpretate_term ~context ~env:Environment.empty ~uri:None ~is_path:true
383 path ~localization_tbl, localization_tbl)
385 let interpretate_obj ~context ~env ~uri ~is_path obj ~localization_tbl =
386 assert (context = []);
387 assert (is_path = false);
388 let interpretate_term = interpretate_term ~localization_tbl in
390 | CicNotationPt.Inductive (params,tyl) ->
391 let uri = match uri with Some uri -> uri | None -> assert false in
395 (fun (context,res) (name,t) ->
396 Cic.Name name :: context,
397 (name, interpretate_term context env None false t)::res
400 context,List.rev res in
403 (fun (name,ty) t -> Cic.Prod (Cic.Name name,ty,t)) params in
407 (*here the explicit_named_substituion is assumed to be of length 0 *)
408 (fun (i,res) (name,_,_,_) ->
409 i + 1,(name,name,Cic.MutInd (uri,i,[]))::res
411 let con_env = DisambiguateTypes.env_of_list name_to_uris env in
415 (fun (name,_,_,_) (i,t) ->
416 (*here the explicit_named_substituion is assumed to be of length 0 *)
417 let t' = Cic.MutInd (uri,i,[]) in
418 let t = CicSubstitution.subst t' t in
420 ) tyl (List.length tyl - 1,t)) in
423 (fun (name,b,ty,cl) ->
424 let ty' = add_params (interpretate_term context env None false ty) in
429 add_params (interpretate_term context con_env None false ty)
437 Cic.InductiveDefinition (tyl,[],List.length params,[])
438 | CicNotationPt.Record (params,name,ty,fields) ->
439 let uri = match uri with Some uri -> uri | None -> assert false in
443 (fun (context,res) (name,t) ->
444 (Cic.Name name :: context),
445 (name, interpretate_term context env None false t)::res
448 context,List.rev res in
451 (fun (name,ty) t -> Cic.Prod (Cic.Name name,ty,t)) params in
452 let ty' = add_params (interpretate_term context env None false ty) in
456 (fun (context,res) (name,ty) ->
457 let context' = Cic.Name name :: context in
458 context',(name,interpretate_term context env None false ty)::res
459 ) (context,[]) fields) in
461 (*here the explicit_named_substituion is assumed to be of length 0 *)
462 let mutind = Cic.MutInd (uri,0,[]) in
463 if params = [] then mutind
466 (mutind::CicUtil.mk_rels (List.length params) (List.length fields)) in
469 (fun t (name,ty) -> Cic.Prod (Cic.Name name,ty,t))
471 let con' = add_params con in
472 let tyl = [name,true,ty',["mk_" ^ name,con']] in
473 let field_names = List.map fst fields in
474 Cic.InductiveDefinition
475 (tyl,[],List.length params,[`Class (`Record field_names)])
476 | CicNotationPt.Theorem (flavour, name, ty, bo) ->
477 let attrs = [`Flavour flavour] in
478 let ty' = interpretate_term [] env None false ty in
481 Cic.CurrentProof (name,[],Cic.Implicit None,ty',[],attrs)
483 let bo' = Some (interpretate_term [] env None false bo) in
484 Cic.Constant (name,bo',ty',[],attrs))
487 (* e.g. [5;1;1;1;2;3;4;1;2] -> [2;1;4;3;5] *)
489 let module SortedItem =
491 type t = DisambiguateTypes.domain_item
492 let compare = Pervasives.compare
495 let module Set = Set.Make (SortedItem) in
497 let rev_l = List.rev l in
498 let (_, uniq_rev_l) =
500 (fun (members, rev_l) elt ->
501 if Set.mem elt members then
504 Set.add elt members, elt :: rev_l)
505 (Set.empty, []) rev_l
509 (* "aux" keeps domain in reverse order and doesn't care about duplicates.
510 * Domain item more in deep in the list will be processed first.
512 let rec domain_rev_of_term ?(loc = dummy_floc) context = function
513 | CicNotationPt.AttributedTerm (`Loc loc, term) ->
514 domain_rev_of_term ~loc context term
515 | CicNotationPt.AttributedTerm (_, term) ->
516 domain_rev_of_term ~loc context term
517 | CicNotationPt.Appl terms ->
519 (fun dom term -> domain_rev_of_term ~loc context term @ dom) [] terms
520 | CicNotationPt.Binder (kind, (var, typ), body) ->
523 | `Exists -> [ Symbol ("exists", 0) ]
526 let type_dom = domain_rev_of_term_option loc context typ in
528 domain_rev_of_term ~loc
529 (CicNotationUtil.cic_name_of_name var :: context) body
531 body_dom @ type_dom @ kind_dom
532 | CicNotationPt.Case (term, indty_ident, outtype, branches) ->
533 let term_dom = domain_rev_of_term ~loc context term in
534 let outtype_dom = domain_rev_of_term_option loc context outtype in
535 let get_first_constructor = function
537 | ((head, _, _), _) :: _ -> [ Id head ]
539 let do_branch ((head, _, args), term) =
540 let (term_context, args_domain) =
542 (fun (cont, dom) (name, typ) ->
543 (CicNotationUtil.cic_name_of_name name :: cont,
546 | Some typ -> domain_rev_of_term ~loc cont typ @ dom)))
549 args_domain @ domain_rev_of_term ~loc term_context term
552 List.fold_left (fun dom branch -> do_branch branch @ dom) [] branches
554 branches_dom @ outtype_dom @ term_dom @
555 (match indty_ident with
556 | None -> get_first_constructor branches
557 | Some (ident, _) -> [ Id ident ])
558 | CicNotationPt.Cast (term, ty) ->
559 let term_dom = domain_rev_of_term ~loc context term in
560 let ty_dom = domain_rev_of_term ~loc context ty in
562 | CicNotationPt.LetIn ((var, typ), body, where) ->
563 let body_dom = domain_rev_of_term ~loc context body in
564 let type_dom = domain_rev_of_term_option loc context typ in
566 domain_rev_of_term ~loc
567 (CicNotationUtil.cic_name_of_name var :: context) where
569 where_dom @ type_dom @ body_dom
570 | CicNotationPt.LetRec (kind, defs, where) ->
573 (fun acc ((var, typ), _, _) ->
574 CicNotationUtil.cic_name_of_name var :: acc)
577 let where_dom = domain_rev_of_term ~loc context' where in
580 (fun dom ((_, typ), body, _) ->
581 domain_rev_of_term ~loc context' body @
582 domain_rev_of_term_option loc context typ)
586 | CicNotationPt.Ident (name, subst) ->
588 let index = find_in_context name context in
589 if subst <> None then
590 CicNotationPt.fail loc "Explicit substitutions not allowed here"
598 (fun dom (_, term) ->
599 let dom' = domain_rev_of_term ~loc context term in
602 | CicNotationPt.Uri _ -> []
603 | CicNotationPt.Implicit -> []
604 | CicNotationPt.Num (num, i) -> [ Num i ]
605 | CicNotationPt.Meta (index, local_context) ->
607 (fun dom term -> domain_rev_of_term_option loc context term @ dom) []
609 | CicNotationPt.Sort _ -> []
610 | CicNotationPt.Symbol (symbol, instance) -> [ Symbol (symbol, instance) ]
611 | CicNotationPt.UserInput
612 | CicNotationPt.Literal _
613 | CicNotationPt.Layout _
614 | CicNotationPt.Magic _
615 | CicNotationPt.Variable _ -> assert false
617 and domain_rev_of_term_option loc context = function
619 | Some t -> domain_rev_of_term ~loc context t
621 let domain_of_term ~context ast = rev_uniq (domain_rev_of_term context ast)
623 let domain_of_obj ~context ast =
624 assert (context = []);
627 | CicNotationPt.Theorem (_,_,ty,bo) ->
630 | Some bo -> domain_rev_of_term [] bo) @
632 | CicNotationPt.Inductive (params,tyl) ->
639 (fun (_,ty) -> domain_rev_of_term [] ty) cl) @
640 domain_rev_of_term [] ty) tyl) in
644 domain_rev_of_term [] ty @ dom
649 not ( List.exists (fun (name',_) -> name = Id name') params
650 || List.exists (fun (name',_,_,_) -> name = Id name') tyl)
652 | CicNotationPt.Record (params,_,ty,fields) ->
655 (List.rev_map (fun (_,ty) -> domain_rev_of_term [] ty) fields) in
659 not ( List.exists (fun (name',_) -> name = Id name') params
660 || List.exists (fun (name',_) -> name = Id name') fields)
665 domain_rev_of_term [] ty @ dom
666 ) (dom @ domain_rev_of_term [] ty) params
671 let domain_diff dom1 dom2 =
672 (* let domain_diff = Domain.diff *)
674 List.fold_left (fun pred elt -> (fun elt' -> elt' = elt || pred elt'))
675 (fun _ -> false) dom2
677 List.filter (fun elt -> not (is_in_dom2 elt)) dom1
679 module type Disambiguator =
681 val disambiguate_term :
682 ?fresh_instances:bool ->
684 context:Cic.context ->
685 metasenv:Cic.metasenv ->
686 ?initial_ugraph:CicUniv.universe_graph ->
687 aliases:DisambiguateTypes.environment ->(* previous interpretation status *)
688 universe:DisambiguateTypes.multiple_environment option ->
689 CicNotationPt.term ->
690 ((DisambiguateTypes.domain_item * DisambiguateTypes.codomain_item) list *
691 Cic.metasenv * (* new metasenv *)
693 CicUniv.universe_graph) list * (* disambiguated term *)
696 val disambiguate_obj :
697 ?fresh_instances:bool ->
699 aliases:DisambiguateTypes.environment ->(* previous interpretation status *)
700 universe:DisambiguateTypes.multiple_environment option ->
701 uri:UriManager.uri option -> (* required only for inductive types *)
703 ((DisambiguateTypes.domain_item * DisambiguateTypes.codomain_item) list *
704 Cic.metasenv * (* new metasenv *)
706 CicUniv.universe_graph) list * (* disambiguated obj *)
710 module Make (C: Callbacks) =
712 let choices_of_id dbd id =
713 let uris = Whelp.locate ~dbd id in
717 [(C.input_or_locate_uri
718 ~title:("URI matching \"" ^ id ^ "\" unknown.") ~id ())]
721 C.interactive_user_uri_choice ~selection_mode:`MULTIPLE
722 ~ok:"Try selected." ~enable_button_for_non_vars:true
723 ~title:"Ambiguous input." ~id
724 ~msg: ("Ambiguous input \"" ^ id ^
725 "\". Please, choose one or more interpretations:")
730 (UriManager.string_of_uri uri,
733 CicUtil.term_of_uri uri
735 debug_print (lazy (UriManager.string_of_uri uri));
736 debug_print (lazy (Printexc.to_string exn));
742 let refine_profiler = HExtlib.profile "disambiguate_thing.refine_thing"
744 let disambiguate_thing ~dbd ~context ~metasenv
745 ?(initial_ugraph = CicUniv.empty_ugraph) ~aliases ~universe
746 ~uri ~pp_thing ~domain_of_thing ~interpretate_thing ~refine_thing thing
748 debug_print (lazy "DISAMBIGUATE INPUT");
749 let disambiguate_context = (* cic context -> disambiguate context *)
751 (function None -> Cic.Anonymous | Some (name, _) -> name)
754 debug_print (lazy ("TERM IS: " ^ (pp_thing thing)));
755 let thing_dom = domain_of_thing ~context:disambiguate_context thing in
756 debug_print (lazy (sprintf "DISAMBIGUATION DOMAIN: %s"
757 (string_of_domain thing_dom)));
759 debug_print (lazy (sprintf "DISAMBIGUATION ENVIRONMENT: %s"
760 (DisambiguatePp.pp_environment aliases)));
761 debug_print (lazy (sprintf "DISAMBIGUATION UNIVERSE: %s"
762 (match universe with None -> "None" | Some _ -> "Some _")));
765 Environment.fold (fun item _ dom -> item :: dom) aliases []
767 let todo_dom = domain_diff thing_dom current_dom in
768 (* (2) lookup function for any item (Id/Symbol/Num) *)
770 let id_choices = Hashtbl.create 1023 in
773 let lookup_in_library () =
775 | Id id -> choices_of_id dbd id
776 | Symbol (symb, _) ->
777 List.map DisambiguateChoices.mk_choice
778 (TermAcicContent.lookup_interpretations symb)
780 DisambiguateChoices.lookup_num_choices ()
783 | None -> lookup_in_library ()
788 | Symbol (symb, _) -> Symbol (symb, 0)
791 Environment.find item e
792 with Not_found -> [])
799 if benchmark then begin
800 let per_item_choices =
804 let len = List.length (lookup_choices dom_item) in
805 debug_print (lazy (sprintf "BENCHMARK %s: %d"
806 (string_of_domain_item dom_item) len));
808 with No_choices _ -> 0)
811 max_refinements := List.fold_left ( * ) 1 per_item_choices;
812 actual_refinements := 0;
813 domain_size := List.length thing_dom;
815 (float_of_int !max_refinements) ** (1. /. float_of_int !domain_size)
821 (* (3) test an interpretation filling with meta uninterpreted identifiers
823 let test_env aliases todo_dom ugraph =
830 | Id _ | Num _ -> (fun _ _ _ -> Cic.Implicit (Some `Closed))
831 | Symbol _ -> (fun _ _ _ -> Cic.Implicit None))) env)
835 let localization_tbl = Cic.CicHash.create 503 in
837 interpretate_thing ~context:disambiguate_context ~env:filled_env
838 ~uri ~is_path:false thing ~localization_tbl
842 refine_thing metasenv context uri cic_thing ugraph ~localization_tbl
845 in refine_profiler.HExtlib.profile foo ()
847 | Try_again msg -> Uncertain (None,msg), ugraph
848 | Invalid_choice msg -> Ko (None,msg), ugraph
850 (* (4) build all possible interpretations *)
851 let (@@) (l1,l2) (l1',l2') = l1@l1', l2@l2' in
852 let rec aux aliases diff lookup_in_todo_dom todo_dom base_univ =
855 assert (lookup_in_todo_dom = None);
856 (match test_env aliases [] base_univ with
857 | Ok (thing, metasenv),new_univ ->
858 [ aliases, diff, metasenv, thing, new_univ ], []
859 | Ko (loc,msg),_ | Uncertain (loc,msg),_ -> [],[loc,msg])
860 | item :: remaining_dom ->
861 debug_print (lazy (sprintf "CHOOSED ITEM: %s"
862 (string_of_domain_item item)));
864 match lookup_in_todo_dom with
865 None -> lookup_choices item
866 | Some choices -> choices in
869 [], [None,lazy ("No choices for " ^ string_of_domain_item item)]
871 (* just one choice. We perform a one-step look-up and
872 if the next set of choices is also a singleton we
873 skip this refinement step *)
874 debug_print(lazy (sprintf "%s CHOSEN" (fst codomain_item)));
875 let new_env = Environment.add item codomain_item aliases in
876 let new_diff = (item,codomain_item)::diff in
877 let lookup_in_todo_dom,next_choice_is_single =
878 match remaining_dom with
881 let choices = lookup_choices he in
882 Some choices,List.length choices = 1
884 if next_choice_is_single then
885 aux new_env new_diff lookup_in_todo_dom remaining_dom
888 (match test_env new_env remaining_dom base_univ with
889 | Ok (thing, metasenv),new_univ ->
890 (match remaining_dom with
892 [ new_env, new_diff, metasenv, thing, new_univ ], []
894 aux new_env new_diff lookup_in_todo_dom
895 remaining_dom new_univ)
896 | Uncertain (loc,msg),new_univ ->
897 (match remaining_dom with
898 | [] -> [], [loc,msg]
900 aux new_env new_diff lookup_in_todo_dom
901 remaining_dom new_univ)
902 | Ko (loc,msg),_ -> [], [loc,msg])
904 let rec filter univ = function
906 | codomain_item :: tl ->
907 debug_print(lazy (sprintf "%s CHOSEN" (fst codomain_item)));
908 let new_env = Environment.add item codomain_item aliases in
909 let new_diff = (item,codomain_item)::diff in
910 (match test_env new_env remaining_dom univ with
911 | Ok (thing, metasenv),new_univ ->
912 (match remaining_dom with
913 | [] -> [ new_env, new_diff, metasenv, thing, new_univ ], []
914 | _ -> aux new_env new_diff None remaining_dom new_univ
917 | Uncertain (loc,msg),new_univ ->
918 (match remaining_dom with
920 | _ -> aux new_env new_diff None remaining_dom new_univ
923 | Ko (loc,msg),_ -> ([],[loc,msg]) @@ filter univ tl)
925 filter base_univ choices
927 let base_univ = initial_ugraph in
930 match aux aliases [] None todo_dom base_univ with
931 | [],errors -> raise (NoWellTypedInterpretation errors)
932 | [_,diff,metasenv,t,ugraph],_ ->
933 debug_print (lazy "SINGLE INTERPRETATION");
934 [diff,metasenv,t,ugraph], false
936 debug_print (lazy (sprintf "MANY INTERPRETATIONS (%d)" (List.length l)));
939 (fun (env, _, _, _, _) ->
943 fst (Environment.find domain_item env)
945 (descr_of_domain_item domain_item, description))
949 let choosed = C.interactive_interpretation_choice choices in
950 (List.map (fun n->let _,d,m,t,u= List.nth l n in d,m,t,u) choosed),
955 CicEnvironment.CircularDependency s ->
956 failwith "Disambiguate: circular dependency"
958 let disambiguate_term ?(fresh_instances=false) ~dbd ~context ~metasenv
959 ?(initial_ugraph = CicUniv.empty_ugraph) ~aliases ~universe term
962 if fresh_instances then CicNotationUtil.freshen_term term else term
964 disambiguate_thing ~dbd ~context ~metasenv ~initial_ugraph ~aliases
965 ~universe ~uri:None ~pp_thing:CicNotationPp.pp_term
966 ~domain_of_thing:domain_of_term ~interpretate_thing:interpretate_term
967 ~refine_thing:refine_term term
969 let disambiguate_obj ?(fresh_instances=false) ~dbd ~aliases ~universe ~uri
973 if fresh_instances then CicNotationUtil.freshen_obj obj else obj
975 disambiguate_thing ~dbd ~context:[] ~metasenv:[] ~aliases ~universe ~uri
976 ~pp_thing:CicNotationPp.pp_obj ~domain_of_thing:domain_of_obj
977 ~interpretate_thing:interpretate_obj ~refine_thing:refine_obj