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 string Lazy.t list
32 exception PathNotWellFormed
34 (** raised when an environment is not enough informative to decide *)
35 exception Try_again of string Lazy.t
37 type aliases = bool * DisambiguateTypes.environment
40 let debug_print s = if debug then prerr_endline (Lazy.force s) else ()
43 (** print benchmark information *)
45 let max_refinements = ref 0 (* benchmarking is not thread safe *)
46 let actual_refinements = ref 0
47 let domain_size = ref 0
48 let choices_avg = ref 0.
51 let descr_of_domain_item = function
54 | Num i -> string_of_int i
57 | Ok of 'a * Cic.metasenv
59 | Uncertain of string Lazy.t
61 let refine_term metasenv context uri term ugraph =
62 (* if benchmark then incr actual_refinements; *)
64 debug_print (lazy (sprintf "TEST_INTERPRETATION: %s" (CicPp.ppterm term)));
66 let term', _, metasenv',ugraph1 =
67 CicRefine.type_of_aux' metasenv context term ugraph in
68 (Ok (term', metasenv')),ugraph1
70 | CicRefine.Uncertain msg ->
71 debug_print (lazy ("UNCERTAIN!!! [" ^ (Lazy.force msg) ^ "] " ^ CicPp.ppterm term)) ;
72 Uncertain (msg (*lazy ("Uncertain trying to refine: " ^ CicMetaSubst.ppterm_in_context [] term context ^ "\n" ^ Lazy.force msg)*)),ugraph
73 | CicRefine.RefineFailure msg ->
74 debug_print (lazy (sprintf "PRUNED!!!\nterm%s\nmessage:%s"
75 (CicPp.ppterm term) (Lazy.force msg)));
76 Ko (msg (*lazy ("Error trying to refine: " ^ CicMetaSubst.ppterm_in_context [] term context ^ "\n" ^ Lazy.force msg)*)),ugraph
78 let refine_obj metasenv context uri obj ugraph =
79 assert (context = []);
80 debug_print (lazy (sprintf "TEST_INTERPRETATION: %s" (CicPp.ppobj obj))) ;
82 let obj', metasenv,ugraph = CicRefine.typecheck metasenv uri obj in
83 (Ok (obj', metasenv)),ugraph
85 | CicRefine.Uncertain msg ->
86 debug_print (lazy ("UNCERTAIN!!! [" ^ (Lazy.force msg) ^ "] " ^ CicPp.ppobj obj)) ;
87 Uncertain (msg (*lazy ("Uncertain trying to refine: " ^ CicPp.ppobj obj ^ "\n" ^ Lazy.force msg)*)),ugraph
88 | CicRefine.RefineFailure msg ->
89 debug_print (lazy (sprintf "PRUNED!!!\nterm%s\nmessage:%s"
90 (CicPp.ppobj obj) (Lazy.force msg))) ;
91 Ko (msg (*lazy ("Error trying to refine: " ^ CicPp.ppobj obj ^ "\n" ^ Lazy.force msg)*)),ugraph
93 let resolve (env: codomain_item Environment.t) (item: domain_item) ?(num = "") ?(args = []) () =
95 snd (Environment.find item env) env num args
97 failwith ("Domain item not found: " ^
98 (DisambiguateTypes.string_of_domain_item item))
100 (* TODO move it to Cic *)
101 let find_in_context name (context: Cic.name list) =
102 let rec aux acc = function
103 | [] -> raise Not_found
104 | Cic.Name hd :: tl when hd = name -> acc
105 | _ :: tl -> aux (acc + 1) tl
109 let interpretate_term ~(context: Cic.name list) ~env ~uri ~is_path ast =
111 let rec aux loc (context: Cic.name list) = function
112 | CicNotationPt.AttributedTerm (`Loc loc, term) ->
114 | CicNotationPt.AttributedTerm (_, term) -> aux loc context term
115 | CicNotationPt.Appl (CicNotationPt.Symbol (symb, i) :: args) ->
116 let cic_args = List.map (aux loc context) args in
117 resolve env (Symbol (symb, i)) ~args:cic_args ()
118 | CicNotationPt.Appl terms -> Cic.Appl (List.map (aux loc context) terms)
119 | CicNotationPt.Binder (binder_kind, (var, typ), body) ->
120 let cic_type = aux_option loc context (Some `Type) typ in
121 let cic_name = CicNotationUtil.cic_name_of_name var in
122 let cic_body = aux loc (cic_name :: context) body in
123 (match binder_kind with
124 | `Lambda -> Cic.Lambda (cic_name, cic_type, cic_body)
126 | `Forall -> Cic.Prod (cic_name, cic_type, cic_body)
128 resolve env (Symbol ("exists", 0))
129 ~args:[ cic_type; Cic.Lambda (cic_name, cic_type, cic_body) ] ())
130 | CicNotationPt.Case (term, indty_ident, outtype, branches) ->
131 let cic_term = aux loc context term in
132 let cic_outtype = aux_option loc context None outtype in
133 let do_branch ((head, _, args), term) =
134 let rec do_branch' context = function
135 | [] -> aux loc context term
136 | (name, typ) :: tl ->
137 let cic_name = CicNotationUtil.cic_name_of_name name in
138 let cic_body = do_branch' (cic_name :: context) tl in
141 | None -> Cic.Implicit (Some `Type)
142 | Some typ -> aux loc context typ
144 Cic.Lambda (cic_name, typ, cic_body)
146 do_branch' context args
148 let (indtype_uri, indtype_no) =
149 match indty_ident with
150 | Some (indty_ident, _) ->
151 (match resolve env (Id indty_ident) () with
152 | Cic.MutInd (uri, tyno, _) -> (uri, tyno)
154 raise (Try_again (lazy "The type of the term to be matched
157 raise (Invalid_choice (lazy "The type of the term to be matched is not (co)inductive!")))
159 let fst_constructor =
161 | ((head, _, _), _) :: _ -> head
162 | [] -> raise (Invalid_choice (lazy "The type of the term to be matched is an inductive type without constructors that cannot be determined"))
164 (match resolve env (Id fst_constructor) () with
165 | Cic.MutConstruct (indtype_uri, indtype_no, _, _) ->
166 (indtype_uri, indtype_no)
168 raise (Try_again (lazy "The type of the term to be matched
171 raise (Invalid_choice (lazy "The type of the term to be matched is not (co)inductive!")))
173 Cic.MutCase (indtype_uri, indtype_no, cic_outtype, cic_term,
174 (List.map do_branch branches))
175 | CicNotationPt.Cast (t1, t2) ->
176 let cic_t1 = aux loc context t1 in
177 let cic_t2 = aux loc context t2 in
178 Cic.Cast (cic_t1, cic_t2)
179 | CicNotationPt.LetIn ((name, typ), def, body) ->
180 let cic_def = aux loc context def in
181 let cic_name = CicNotationUtil.cic_name_of_name name in
185 | Some t -> Cic.Cast (cic_def, aux loc context t)
187 let cic_body = aux loc (cic_name :: context) body in
188 Cic.LetIn (cic_name, cic_def, cic_body)
189 | CicNotationPt.LetRec (kind, defs, body) ->
192 (fun acc ((name, _), _, _) ->
193 CicNotationUtil.cic_name_of_name name :: acc)
196 let cic_body = aux loc context' body in
199 (fun ((name, typ), body, decr_idx) ->
200 let cic_body = aux loc context' body in
201 let cic_type = aux_option loc context (Some `Type) typ in
203 match CicNotationUtil.cic_name_of_name name with
205 CicNotationPt.fail loc
206 "Recursive functions cannot be anonymous"
207 | Cic.Name name -> name
209 (name, decr_idx, cic_type, cic_body))
212 let counter = ref ~-1 in
213 let build_term funs =
214 (* this is the body of the fold_right function below. Rationale: Fix
215 * and CoFix cases differs only in an additional index in the
216 * inductiveFun list, see Cic.term *)
219 (fun (var, _, _, _) cic ->
221 let fix = Cic.Fix (!counter,funs) in
224 | (Cic.Appl (Cic.Rel 1::l)) ->
229 let t',subst,metasenv =
230 CicMetaSubst.delift_rels [] [] 1 t
233 assert (metasenv=[]);
238 CicMetaSubst.DeliftingARelWouldCaptureAFreeVariable ->
239 Cic.LetIn (Cic.Name var, fix, cic))
240 | _ -> Cic.LetIn (Cic.Name var, fix, cic))
243 List.map (fun (name, _, typ, body) -> (name, typ, body)) funs
245 (fun (var, _, _, _) cic ->
247 let cofix = Cic.CoFix (!counter,funs) in
250 | (Cic.Appl (Cic.Rel 1::l)) -> Cic.Appl (cofix::l)
251 | _ -> Cic.LetIn (Cic.Name var, cofix, cic))
253 List.fold_right (build_term inductiveFuns) inductiveFuns cic_body
254 | CicNotationPt.Ident _
255 | CicNotationPt.Uri _ when is_path -> raise PathNotWellFormed
256 | CicNotationPt.Ident (name, subst)
257 | CicNotationPt.Uri (name, subst) as ast ->
258 let is_uri = function CicNotationPt.Uri _ -> true | _ -> false in
260 if is_uri ast then raise Not_found;(* don't search the env for URIs *)
261 let index = find_in_context name context in
262 if subst <> None then
263 CicNotationPt.fail loc "Explicit substitutions not allowed here";
267 if is_uri ast then (* we have the URI, build the term out of it *)
269 CicUtil.term_of_uri (UriManager.uri_of_string name)
270 with UriManager.IllFormedUri _ ->
271 CicNotationPt.fail loc "Ill formed URI"
273 resolve env (Id name) ()
277 List.map (fun uri -> UriManager.name_of_uri uri, uri) uris
284 List.assoc s ids_to_uris, aux loc context term
286 raise (Invalid_choice (lazy "The provided explicit named substitution is trying to instantiate a named variable the object is not abstracted on"))))
288 | None -> List.map (fun uri -> uri, Cic.Implicit None) uris)
292 | Cic.Const (uri, []) ->
293 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
294 let uris = CicUtil.params_of_obj o in
295 Cic.Const (uri, mk_subst uris)
296 | Cic.Var (uri, []) ->
297 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
298 let uris = CicUtil.params_of_obj o in
299 Cic.Var (uri, mk_subst uris)
300 | Cic.MutInd (uri, i, []) ->
302 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
303 let uris = CicUtil.params_of_obj o in
304 Cic.MutInd (uri, i, mk_subst uris)
306 CicEnvironment.Object_not_found _ ->
307 (* if we are here it is probably the case that during the
308 definition of a mutual inductive type we have met an
309 occurrence of the type in one of its constructors.
310 However, the inductive type is not yet in the environment
312 (*here the explicit_named_substituion is assumed to be of length 0 *)
313 Cic.MutInd (uri,i,[]))
314 | Cic.MutConstruct (uri, i, j, []) ->
315 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
316 let uris = CicUtil.params_of_obj o in
317 Cic.MutConstruct (uri, i, j, mk_subst uris)
318 | Cic.Meta _ | Cic.Implicit _ as t ->
320 debug_print (lazy (sprintf
321 "Warning: %s must be instantiated with _[%s] but we do not enforce it"
325 (fun (s, term) -> s ^ " := " ^ CicNotationPtPp.pp_term term)
330 raise (Invalid_choice (lazy "??? Can this happen?"))
332 CicEnvironment.CircularDependency _ ->
333 raise (Invalid_choice (lazy "Circular dependency in the environment"))))
334 | CicNotationPt.Implicit -> Cic.Implicit None
335 | CicNotationPt.UserInput -> Cic.Implicit (Some `Hole)
336 | CicNotationPt.Num (num, i) -> resolve env (Num i) ~num ()
337 | CicNotationPt.Meta (index, subst) ->
340 (function None -> None | Some term -> Some (aux loc context term))
343 Cic.Meta (index, cic_subst)
344 | CicNotationPt.Sort `Prop -> Cic.Sort Cic.Prop
345 | CicNotationPt.Sort `Set -> Cic.Sort Cic.Set
346 | CicNotationPt.Sort (`Type u) -> Cic.Sort (Cic.Type u)
347 | CicNotationPt.Sort `CProp -> Cic.Sort Cic.CProp
348 | CicNotationPt.Symbol (symbol, instance) ->
349 resolve env (Symbol (symbol, instance)) ()
350 | _ -> assert false (* god bless Bologna *)
351 and aux_option loc (context: Cic.name list) annotation = function
352 | None -> Cic.Implicit annotation
353 | Some term -> aux loc context term
356 | CicNotationPt.AttributedTerm (`Loc loc, term) -> aux loc context term
357 | term -> aux dummy_floc context term
359 let interpretate_path ~context path =
360 interpretate_term ~context ~env:Environment.empty ~uri:None ~is_path:true path
362 let interpretate_obj ~context ~env ~uri ~is_path obj =
363 assert (context = []);
364 assert (is_path = false);
366 | CicNotationPt.Inductive (params,tyl) ->
367 let uri = match uri with Some uri -> uri | None -> assert false in
371 (fun (context,res) (name,t) ->
372 Cic.Name name :: context,
373 (name, interpretate_term context env None false t)::res
376 context,List.rev res in
379 (fun (name,ty) t -> Cic.Prod (Cic.Name name,ty,t)) params in
383 (*here the explicit_named_substituion is assumed to be of length 0 *)
384 (fun (i,res) (name,_,_,_) ->
385 i + 1,(name,name,Cic.MutInd (uri,i,[]))::res
387 let con_env = DisambiguateTypes.env_of_list name_to_uris env in
391 (fun (name,_,_,_) (i,t) ->
392 (*here the explicit_named_substituion is assumed to be of length 0 *)
393 let t' = Cic.MutInd (uri,i,[]) in
394 let t = CicSubstitution.subst t' t in
396 ) tyl (List.length tyl - 1,t)) in
399 (fun (name,b,ty,cl) ->
400 let ty' = add_params (interpretate_term context env None false ty) in
405 add_params (interpretate_term context con_env None false ty)
413 Cic.InductiveDefinition (tyl,[],List.length params,[])
414 | CicNotationPt.Record (params,name,ty,fields) ->
415 let uri = match uri with Some uri -> uri | None -> assert false in
419 (fun (context,res) (name,t) ->
420 (Cic.Name name :: context),
421 (name, interpretate_term context env None false t)::res
424 context,List.rev res in
427 (fun (name,ty) t -> Cic.Prod (Cic.Name name,ty,t)) params in
428 let ty' = add_params (interpretate_term context env None false ty) in
432 (fun (context,res) (name,ty) ->
433 let context' = Cic.Name name :: context in
434 context',(name,interpretate_term context env None false ty)::res
435 ) (context,[]) fields) in
437 (*here the explicit_named_substituion is assumed to be of length 0 *)
438 let mutind = Cic.MutInd (uri,0,[]) in
439 if params = [] then mutind
442 (mutind::CicUtil.mk_rels (List.length params) (List.length fields)) in
445 (fun t (name,ty) -> Cic.Prod (Cic.Name name,ty,t))
447 let con' = add_params con in
448 let tyl = [name,true,ty',["mk_" ^ name,con']] in
449 let field_names = List.map fst fields in
450 Cic.InductiveDefinition
451 (tyl,[],List.length params,[`Class (`Record field_names)])
452 | CicNotationPt.Theorem (flavour, name, ty, bo) ->
453 let attrs = [`Flavour flavour] in
454 let ty' = interpretate_term [] env None false ty in
457 Cic.CurrentProof (name,[],Cic.Implicit None,ty',[],attrs)
459 let bo' = Some (interpretate_term [] env None false bo) in
460 Cic.Constant (name,bo',ty',[],attrs))
463 (* e.g. [5;1;1;1;2;3;4;1;2] -> [2;1;4;3;5] *)
465 let module SortedItem =
467 type t = DisambiguateTypes.domain_item
468 let compare = Pervasives.compare
471 let module Set = Set.Make (SortedItem) in
473 let rev_l = List.rev l in
474 let (_, uniq_rev_l) =
476 (fun (members, rev_l) elt ->
477 if Set.mem elt members then
480 Set.add elt members, elt :: rev_l)
481 (Set.empty, []) rev_l
485 (* "aux" keeps domain in reverse order and doesn't care about duplicates.
486 * Domain item more in deep in the list will be processed first.
488 let rec domain_rev_of_term ?(loc = dummy_floc) context = function
489 | CicNotationPt.AttributedTerm (`Loc loc, term) ->
490 domain_rev_of_term ~loc context term
491 | CicNotationPt.AttributedTerm (_, term) ->
492 domain_rev_of_term ~loc context term
493 | CicNotationPt.Appl terms ->
495 (fun dom term -> domain_rev_of_term ~loc context term @ dom) [] terms
496 | CicNotationPt.Binder (kind, (var, typ), body) ->
499 | `Exists -> [ Symbol ("exists", 0) ]
502 let type_dom = domain_rev_of_term_option loc context typ in
504 domain_rev_of_term ~loc
505 (CicNotationUtil.cic_name_of_name var :: context) body
507 body_dom @ type_dom @ kind_dom
508 | CicNotationPt.Case (term, indty_ident, outtype, branches) ->
509 let term_dom = domain_rev_of_term ~loc context term in
510 let outtype_dom = domain_rev_of_term_option loc context outtype in
511 let get_first_constructor = function
513 | ((head, _, _), _) :: _ -> [ Id head ]
515 let do_branch ((head, _, args), term) =
516 let (term_context, args_domain) =
518 (fun (cont, dom) (name, typ) ->
519 (CicNotationUtil.cic_name_of_name name :: cont,
522 | Some typ -> domain_rev_of_term ~loc cont typ @ dom)))
525 args_domain @ domain_rev_of_term ~loc term_context term
528 List.fold_left (fun dom branch -> do_branch branch @ dom) [] branches
530 branches_dom @ outtype_dom @ term_dom @
531 (match indty_ident with
532 | None -> get_first_constructor branches
533 | Some (ident, _) -> [ Id ident ])
534 | CicNotationPt.Cast (term, ty) ->
535 let term_dom = domain_rev_of_term ~loc context term in
536 let ty_dom = domain_rev_of_term ~loc context ty in
538 | CicNotationPt.LetIn ((var, typ), body, where) ->
539 let body_dom = domain_rev_of_term ~loc context body in
540 let type_dom = domain_rev_of_term_option loc context typ in
542 domain_rev_of_term ~loc
543 (CicNotationUtil.cic_name_of_name var :: context) where
545 where_dom @ type_dom @ body_dom
546 | CicNotationPt.LetRec (kind, defs, where) ->
549 (fun acc ((var, typ), _, _) ->
550 CicNotationUtil.cic_name_of_name var :: acc)
553 let where_dom = domain_rev_of_term ~loc context' where in
556 (fun dom ((_, typ), body, _) ->
557 domain_rev_of_term ~loc context' body @
558 domain_rev_of_term_option loc context typ)
562 | CicNotationPt.Ident (name, subst) ->
564 let index = find_in_context name context in
565 if subst <> None then
566 CicNotationPt.fail loc "Explicit substitutions not allowed here"
574 (fun dom (_, term) ->
575 let dom' = domain_rev_of_term ~loc context term in
578 | CicNotationPt.Uri _ -> []
579 | CicNotationPt.Implicit -> []
580 | CicNotationPt.Num (num, i) -> [ Num i ]
581 | CicNotationPt.Meta (index, local_context) ->
583 (fun dom term -> domain_rev_of_term_option loc context term @ dom) []
585 | CicNotationPt.Sort _ -> []
586 | CicNotationPt.Symbol (symbol, instance) -> [ Symbol (symbol, instance) ]
587 | CicNotationPt.UserInput
588 | CicNotationPt.Literal _
589 | CicNotationPt.Layout _
590 | CicNotationPt.Magic _
591 | CicNotationPt.Variable _ -> assert false
593 and domain_rev_of_term_option loc context = function
595 | Some t -> domain_rev_of_term ~loc context t
597 let domain_of_term ~context ast = rev_uniq (domain_rev_of_term context ast)
599 let domain_of_obj ~context ast =
600 assert (context = []);
603 | CicNotationPt.Theorem (_,_,ty,bo) ->
606 | Some bo -> domain_rev_of_term [] bo) @
608 | CicNotationPt.Inductive (params,tyl) ->
615 (fun (_,ty) -> domain_rev_of_term [] ty) cl) @
616 domain_rev_of_term [] ty) tyl) in
620 domain_rev_of_term [] ty @ dom
625 not ( List.exists (fun (name',_) -> name = Id name') params
626 || List.exists (fun (name',_,_,_) -> name = Id name') tyl)
628 | CicNotationPt.Record (params,_,ty,fields) ->
631 (List.rev_map (fun (_,ty) -> domain_rev_of_term [] ty) fields) in
635 not ( List.exists (fun (name',_) -> name = Id name') params
636 || List.exists (fun (name',_) -> name = Id name') fields)
641 domain_rev_of_term [] ty @ dom
642 ) (dom @ domain_rev_of_term [] ty) params
647 let domain_diff dom1 dom2 =
648 (* let domain_diff = Domain.diff *)
650 List.fold_left (fun pred elt -> (fun elt' -> elt' = elt || pred elt'))
651 (fun _ -> false) dom2
653 List.filter (fun elt -> not (is_in_dom2 elt)) dom1
655 module type Disambiguator =
657 val disambiguate_term :
658 ?fresh_instances:bool ->
660 context:Cic.context ->
661 metasenv:Cic.metasenv ->
662 ?initial_ugraph:CicUniv.universe_graph ->
663 aliases:DisambiguateTypes.environment ->(* previous interpretation status *)
664 universe:DisambiguateTypes.multiple_environment option ->
665 CicNotationPt.term ->
666 ((DisambiguateTypes.domain_item * DisambiguateTypes.codomain_item) list *
667 Cic.metasenv * (* new metasenv *)
669 CicUniv.universe_graph) list * (* disambiguated term *)
672 val disambiguate_obj :
673 ?fresh_instances:bool ->
675 aliases:DisambiguateTypes.environment ->(* previous interpretation status *)
676 universe:DisambiguateTypes.multiple_environment option ->
677 uri:UriManager.uri option -> (* required only for inductive types *)
679 ((DisambiguateTypes.domain_item * DisambiguateTypes.codomain_item) list *
680 Cic.metasenv * (* new metasenv *)
682 CicUniv.universe_graph) list * (* disambiguated obj *)
686 module Make (C: Callbacks) =
688 let choices_of_id dbd id =
689 let uris = Whelp.locate ~dbd id in
693 [(C.input_or_locate_uri
694 ~title:("URI matching \"" ^ id ^ "\" unknown.") ~id ())]
697 C.interactive_user_uri_choice ~selection_mode:`MULTIPLE
698 ~ok:"Try selected." ~enable_button_for_non_vars:true
699 ~title:"Ambiguous input." ~id
700 ~msg: ("Ambiguous input \"" ^ id ^
701 "\". Please, choose one or more interpretations:")
706 (UriManager.string_of_uri uri,
709 CicUtil.term_of_uri uri
711 debug_print (lazy (UriManager.string_of_uri uri));
712 debug_print (lazy (Printexc.to_string exn));
718 let refine_profiler = HExtlib.profile "disambiguate_thing.refine_thing"
720 let disambiguate_thing ~dbd ~context ~metasenv
721 ?(initial_ugraph = CicUniv.empty_ugraph) ~aliases ~universe
722 ~uri ~pp_thing ~domain_of_thing ~interpretate_thing ~refine_thing thing
724 debug_print (lazy "DISAMBIGUATE INPUT");
725 let disambiguate_context = (* cic context -> disambiguate context *)
727 (function None -> Cic.Anonymous | Some (name, _) -> name)
730 debug_print (lazy ("TERM IS: " ^ (pp_thing thing)));
731 let thing_dom = domain_of_thing ~context:disambiguate_context thing in
732 debug_print (lazy (sprintf "DISAMBIGUATION DOMAIN: %s"
733 (string_of_domain thing_dom)));
735 debug_print (lazy (sprintf "DISAMBIGUATION ENVIRONMENT: %s"
736 (DisambiguatePp.pp_environment aliases)));
737 debug_print (lazy (sprintf "DISAMBIGUATION UNIVERSE: %s"
738 (match universe with None -> "None" | Some _ -> "Some _")));
741 Environment.fold (fun item _ dom -> item :: dom) aliases []
743 let todo_dom = domain_diff thing_dom current_dom in
744 (* (2) lookup function for any item (Id/Symbol/Num) *)
746 let id_choices = Hashtbl.create 1023 in
749 let lookup_in_library () =
751 | Id id -> choices_of_id dbd id
752 | Symbol (symb, _) ->
753 List.map DisambiguateChoices.mk_choice
754 (TermAcicContent.lookup_interpretations symb)
756 DisambiguateChoices.lookup_num_choices ()
759 | None -> lookup_in_library ()
764 | Symbol (symb, _) -> Symbol (symb, 0)
767 Environment.find item e
768 with Not_found -> [])
775 if benchmark then begin
776 let per_item_choices =
780 let len = List.length (lookup_choices dom_item) in
781 debug_print (lazy (sprintf "BENCHMARK %s: %d"
782 (string_of_domain_item dom_item) len));
784 with No_choices _ -> 0)
787 max_refinements := List.fold_left ( * ) 1 per_item_choices;
788 actual_refinements := 0;
789 domain_size := List.length thing_dom;
791 (float_of_int !max_refinements) ** (1. /. float_of_int !domain_size)
797 (* (3) test an interpretation filling with meta uninterpreted identifiers
799 let test_env aliases todo_dom ugraph =
806 | Id _ | Num _ -> (fun _ _ _ -> Cic.Implicit (Some `Closed))
807 | Symbol _ -> (fun _ _ _ -> Cic.Implicit None))) env)
812 interpretate_thing ~context:disambiguate_context ~env:filled_env
813 ~uri ~is_path:false thing
816 let k,ugraph1 = refine_thing metasenv context uri cic_thing ugraph in
818 in refine_profiler.HExtlib.profile foo ()
820 | Try_again msg -> Uncertain msg, ugraph
821 | Invalid_choice msg -> Ko msg, ugraph
823 (* (4) build all possible interpretations *)
824 let (@@) (l1,l2) (l1',l2') = l1@l1', l2@l2' in
825 let rec aux aliases diff lookup_in_todo_dom todo_dom base_univ =
828 assert (lookup_in_todo_dom = None);
829 (match test_env aliases [] base_univ with
830 | Ok (thing, metasenv),new_univ ->
831 [ aliases, diff, metasenv, thing, new_univ ], []
832 | Ko msg,_ | Uncertain msg,_ -> [],[msg])
833 | item :: remaining_dom ->
834 debug_print (lazy (sprintf "CHOOSED ITEM: %s"
835 (string_of_domain_item item)));
837 match lookup_in_todo_dom with
838 None -> lookup_choices item
839 | Some choices -> choices in
841 [] -> [], [lazy ("No choices for " ^ string_of_domain_item item)]
843 (* just one choice. We perform a one-step look-up and
844 if the next set of choices is also a singleton we
845 skip this refinement step *)
846 debug_print(lazy (sprintf "%s CHOSEN" (fst codomain_item)));
847 let new_env = Environment.add item codomain_item aliases in
848 let new_diff = (item,codomain_item)::diff in
849 let lookup_in_todo_dom,next_choice_is_single =
850 match remaining_dom with
853 let choices = lookup_choices he in
854 Some choices,List.length choices = 1
856 if next_choice_is_single then
857 aux new_env new_diff lookup_in_todo_dom remaining_dom
860 (match test_env new_env remaining_dom base_univ with
861 | Ok (thing, metasenv),new_univ ->
862 (match remaining_dom with
864 [ new_env, new_diff, metasenv, thing, new_univ ], []
866 aux new_env new_diff lookup_in_todo_dom
867 remaining_dom new_univ)
868 | Uncertain msg,new_univ ->
869 (match remaining_dom with
872 aux new_env new_diff lookup_in_todo_dom
873 remaining_dom new_univ)
874 | Ko msg,_ -> [], [msg])
876 let rec filter univ = function
878 | codomain_item :: tl ->
879 debug_print(lazy (sprintf "%s CHOSEN" (fst codomain_item)));
880 let new_env = Environment.add item codomain_item aliases in
881 let new_diff = (item,codomain_item)::diff in
882 (match test_env new_env remaining_dom univ with
883 | Ok (thing, metasenv),new_univ ->
884 (match remaining_dom with
885 | [] -> [ new_env, new_diff, metasenv, thing, new_univ ], []
886 | _ -> aux new_env new_diff None remaining_dom new_univ
889 | Uncertain msg,new_univ ->
890 (match remaining_dom with
892 | _ -> aux new_env new_diff None remaining_dom new_univ
895 | Ko msg,_ -> ([],[msg]) @@ filter univ tl)
897 filter base_univ choices
899 let base_univ = initial_ugraph in
902 match aux aliases [] None todo_dom base_univ with
903 | [],errors -> raise (NoWellTypedInterpretation errors)
904 | [_,diff,metasenv,t,ugraph],_ ->
905 debug_print (lazy "SINGLE INTERPRETATION");
906 [diff,metasenv,t,ugraph], false
908 debug_print (lazy (sprintf "MANY INTERPRETATIONS (%d)" (List.length l)));
911 (fun (env, _, _, _, _) ->
915 fst (Environment.find domain_item env)
917 (descr_of_domain_item domain_item, description))
921 let choosed = C.interactive_interpretation_choice choices in
922 (List.map (fun n->let _,d,m,t,u= List.nth l n in d,m,t,u) choosed),
927 CicEnvironment.CircularDependency s ->
928 failwith "Disambiguate: circular dependency"
930 let disambiguate_term ?(fresh_instances=false) ~dbd ~context ~metasenv
931 ?(initial_ugraph = CicUniv.empty_ugraph) ~aliases ~universe term
934 if fresh_instances then CicNotationUtil.freshen_term term else term
936 disambiguate_thing ~dbd ~context ~metasenv ~initial_ugraph ~aliases
937 ~universe ~uri:None ~pp_thing:CicNotationPp.pp_term
938 ~domain_of_thing:domain_of_term ~interpretate_thing:interpretate_term
939 ~refine_thing:refine_term term
941 let disambiguate_obj ?(fresh_instances=false) ~dbd ~aliases ~universe ~uri
945 if fresh_instances then CicNotationUtil.freshen_obj obj else obj
947 disambiguate_thing ~dbd ~context:[] ~metasenv:[] ~aliases ~universe ~uri
948 ~pp_thing:CicNotationPp.pp_obj ~domain_of_thing:domain_of_obj
949 ~interpretate_thing:interpretate_obj ~refine_thing:refine_obj