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 (* the integer is an offset to be added to each location *)
32 exception NoWellTypedInterpretation of
33 int * (Token.flocation option * string Lazy.t) list
34 exception PathNotWellFormed
36 (** raised when an environment is not enough informative to decide *)
37 exception Try_again of string Lazy.t
39 type aliases = bool * DisambiguateTypes.environment
42 let debug_print s = if debug then prerr_endline (Lazy.force s) else ()
45 (** print benchmark information *)
47 let max_refinements = ref 0 (* benchmarking is not thread safe *)
48 let actual_refinements = ref 0
49 let domain_size = ref 0
50 let choices_avg = ref 0.
53 let descr_of_domain_item = function
56 | Num i -> string_of_int i
59 | Ok of 'a * Cic.metasenv
60 | Ko of Token.flocation option * string Lazy.t
61 | Uncertain of Token.flocation option * string Lazy.t
63 let refine_term metasenv context uri term ugraph ~localization_tbl =
64 (* if benchmark then incr actual_refinements; *)
66 debug_print (lazy (sprintf "TEST_INTERPRETATION: %s" (CicPp.ppterm term)));
68 let term', _, metasenv',ugraph1 =
69 CicRefine.type_of_aux' metasenv context term ugraph ~localization_tbl in
70 (Ok (term', metasenv')),ugraph1
73 let rec process_exn loc =
75 HExtlib.Localized (loc,exn) -> process_exn (Some loc) exn
76 | CicRefine.Uncertain msg ->
77 debug_print (lazy ("UNCERTAIN!!! [" ^ (Lazy.force msg) ^ "] " ^ CicPp.ppterm term)) ;
78 Uncertain (loc,msg),ugraph
79 | CicRefine.RefineFailure msg ->
80 debug_print (lazy (sprintf "PRUNED!!!\nterm%s\nmessage:%s"
81 (CicPp.ppterm term) (Lazy.force msg)));
87 let refine_obj metasenv context uri obj ugraph ~localization_tbl =
88 assert (context = []);
89 debug_print (lazy (sprintf "TEST_INTERPRETATION: %s" (CicPp.ppobj obj))) ;
91 let obj', metasenv,ugraph =
92 CicRefine.typecheck metasenv uri obj ~localization_tbl
94 (Ok (obj', metasenv)),ugraph
97 let rec process_exn loc =
99 HExtlib.Localized (loc,exn) -> process_exn (Some loc) exn
100 | CicRefine.Uncertain msg ->
101 debug_print (lazy ("UNCERTAIN!!! [" ^ (Lazy.force msg) ^ "] " ^ CicPp.ppobj obj)) ;
102 Uncertain (loc,msg),ugraph
103 | CicRefine.RefineFailure msg ->
104 debug_print (lazy (sprintf "PRUNED!!!\nterm%s\nmessage:%s"
105 (CicPp.ppobj obj) (Lazy.force msg))) ;
111 let resolve (env: codomain_item Environment.t) (item: domain_item) ?(num = "") ?(args = []) () =
113 snd (Environment.find item env) env num args
115 failwith ("Domain item not found: " ^
116 (DisambiguateTypes.string_of_domain_item item))
118 (* TODO move it to Cic *)
119 let find_in_context name (context: Cic.name list) =
120 let rec aux acc = function
121 | [] -> raise Not_found
122 | Cic.Name hd :: tl when hd = name -> acc
123 | _ :: tl -> aux (acc + 1) tl
127 let interpretate_term ~(context: Cic.name list) ~env ~uri ~is_path ast
131 let rec aux ~localize loc (context: Cic.name list) = function
132 | CicNotationPt.AttributedTerm (`Loc loc, term) ->
133 let res = aux ~localize loc context term in
134 if localize then Cic.CicHash.add localization_tbl res loc;
136 | CicNotationPt.AttributedTerm (_, term) -> aux ~localize loc context term
137 | CicNotationPt.Appl (CicNotationPt.Symbol (symb, i) :: args) ->
138 let cic_args = List.map (aux ~localize loc context) args in
139 resolve env (Symbol (symb, i)) ~args:cic_args ()
140 | CicNotationPt.Appl terms ->
141 Cic.Appl (List.map (aux ~localize loc context) terms)
142 | CicNotationPt.Binder (binder_kind, (var, typ), body) ->
143 let cic_type = aux_option ~localize loc context (Some `Type) typ in
144 let cic_name = CicNotationUtil.cic_name_of_name var in
145 let cic_body = aux ~localize loc (cic_name :: context) body in
146 (match binder_kind with
147 | `Lambda -> Cic.Lambda (cic_name, cic_type, cic_body)
149 | `Forall -> Cic.Prod (cic_name, cic_type, cic_body)
151 resolve env (Symbol ("exists", 0))
152 ~args:[ cic_type; Cic.Lambda (cic_name, cic_type, cic_body) ] ())
153 | CicNotationPt.Case (term, indty_ident, outtype, branches) ->
154 let cic_term = aux ~localize loc context term in
155 let cic_outtype = aux_option ~localize loc context None outtype in
156 let do_branch ((head, _, args), term) =
157 let rec do_branch' context = function
158 | [] -> aux ~localize loc context term
159 | (name, typ) :: tl ->
160 let cic_name = CicNotationUtil.cic_name_of_name name in
161 let cic_body = do_branch' (cic_name :: context) tl in
164 | None -> Cic.Implicit (Some `Type)
165 | Some typ -> aux ~localize loc context typ
167 Cic.Lambda (cic_name, typ, cic_body)
169 do_branch' context args
171 let (indtype_uri, indtype_no) =
172 match indty_ident with
173 | Some (indty_ident, _) ->
174 (match resolve env (Id indty_ident) () with
175 | Cic.MutInd (uri, tyno, _) -> (uri, tyno)
177 raise (Try_again (lazy "The type of the term to be matched
180 raise (Invalid_choice (lazy "The type of the term to be matched is not (co)inductive!")))
182 let fst_constructor =
184 | ((head, _, _), _) :: _ -> head
185 | [] -> raise (Invalid_choice (lazy "The type of the term to be matched is an inductive type without constructors that cannot be determined"))
187 (match resolve env (Id fst_constructor) () with
188 | Cic.MutConstruct (indtype_uri, indtype_no, _, _) ->
189 (indtype_uri, indtype_no)
191 raise (Try_again (lazy "The type of the term to be matched
194 raise (Invalid_choice (lazy "The type of the term to be matched is not (co)inductive!")))
196 Cic.MutCase (indtype_uri, indtype_no, cic_outtype, cic_term,
197 (List.map do_branch branches))
198 | CicNotationPt.Cast (t1, t2) ->
199 let cic_t1 = aux ~localize loc context t1 in
200 let cic_t2 = aux ~localize loc context t2 in
201 Cic.Cast (cic_t1, cic_t2)
202 | CicNotationPt.LetIn ((name, typ), def, body) ->
203 let cic_def = aux ~localize loc context def in
204 let cic_name = CicNotationUtil.cic_name_of_name name in
208 | Some t -> Cic.Cast (cic_def, aux ~localize loc context t)
210 let cic_body = aux ~localize loc (cic_name :: context) body in
211 Cic.LetIn (cic_name, cic_def, cic_body)
212 | CicNotationPt.LetRec (kind, defs, body) ->
215 (fun acc ((name, _), _, _) ->
216 CicNotationUtil.cic_name_of_name name :: acc)
220 let unlocalized_body = aux ~localize:false loc context' body in
221 match unlocalized_body with
222 Cic.Rel 1 -> `AvoidLetInNoAppl
223 | Cic.Appl (Cic.Rel 1::l) ->
228 let t',subst,metasenv =
229 CicMetaSubst.delift_rels [] [] 1 t
232 assert (metasenv=[]);
235 (* We can avoid the LetIn. But maybe we need to recompute l'
236 so that it is localized *)
239 CicNotationPt.AttributedTerm (_,CicNotationPt.Appl(_::l)) ->
240 let l' = List.map (aux ~localize loc context) l in
246 CicMetaSubst.DeliftingARelWouldCaptureAFreeVariable ->
248 `AddLetIn (aux ~localize loc context' body)
250 `AddLetIn unlocalized_body)
253 `AddLetIn (aux ~localize loc context' body)
255 `AddLetIn unlocalized_body
259 (fun ((name, typ), body, decr_idx) ->
260 let cic_body = aux ~localize loc context' body in
262 aux_option ~localize loc context (Some `Type) typ in
264 match CicNotationUtil.cic_name_of_name name with
266 CicNotationPt.fail loc
267 "Recursive functions cannot be anonymous"
268 | Cic.Name name -> name
270 (name, decr_idx, cic_type, cic_body))
273 let counter = ref ~-1 in
274 let build_term funs =
275 (* this is the body of the fold_right function below. Rationale: Fix
276 * and CoFix cases differs only in an additional index in the
277 * inductiveFun list, see Cic.term *)
280 (fun (var, _, _, _) cic ->
282 let fix = Cic.Fix (!counter,funs) in
284 `Recipe (`AddLetIn cic) ->
285 `Term (Cic.LetIn (Cic.Name var, fix, cic))
286 | `Recipe (`AvoidLetIn l) -> `Term (Cic.Appl (fix::l))
287 | `Recipe `AvoidLetInNoAppl -> `Term fix
288 | `Term t -> `Term (Cic.LetIn (Cic.Name var, fix, t)))
291 List.map (fun (name, _, typ, body) -> (name, typ, body)) funs
293 (fun (var, _, _, _) cic ->
295 let cofix = Cic.CoFix (!counter,funs) in
297 `Recipe (`AddLetIn cic) ->
298 `Term (Cic.LetIn (Cic.Name var, cofix, cic))
299 | `Recipe (`AvoidLetIn l) -> `Term (Cic.Appl (cofix::l))
300 | `Recipe `AvoidLetInNoAppl -> `Term cofix
301 | `Term t -> `Term (Cic.LetIn (Cic.Name var, cofix, t)))
304 List.fold_right (build_term inductiveFuns) inductiveFuns
307 `Recipe _ -> assert false
309 | CicNotationPt.Ident _
310 | CicNotationPt.Uri _ when is_path -> raise PathNotWellFormed
311 | CicNotationPt.Ident (name, subst)
312 | CicNotationPt.Uri (name, subst) as ast ->
313 let is_uri = function CicNotationPt.Uri _ -> true | _ -> false in
315 if is_uri ast then raise Not_found;(* don't search the env for URIs *)
316 let index = find_in_context name context in
317 if subst <> None then
318 CicNotationPt.fail loc "Explicit substitutions not allowed here";
322 if is_uri ast then (* we have the URI, build the term out of it *)
324 CicUtil.term_of_uri (UriManager.uri_of_string name)
325 with UriManager.IllFormedUri _ ->
326 CicNotationPt.fail loc "Ill formed URI"
328 resolve env (Id name) ()
332 List.map (fun uri -> UriManager.name_of_uri uri, uri) uris
339 List.assoc s ids_to_uris, aux ~localize loc context term
341 raise (Invalid_choice (lazy "The provided explicit named substitution is trying to instantiate a named variable the object is not abstracted on"))))
343 | None -> List.map (fun uri -> uri, Cic.Implicit None) uris)
347 | Cic.Const (uri, []) ->
348 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
349 let uris = CicUtil.params_of_obj o in
350 Cic.Const (uri, mk_subst uris)
351 | Cic.Var (uri, []) ->
352 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
353 let uris = CicUtil.params_of_obj o in
354 Cic.Var (uri, mk_subst uris)
355 | Cic.MutInd (uri, i, []) ->
357 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
358 let uris = CicUtil.params_of_obj o in
359 Cic.MutInd (uri, i, mk_subst uris)
361 CicEnvironment.Object_not_found _ ->
362 (* if we are here it is probably the case that during the
363 definition of a mutual inductive type we have met an
364 occurrence of the type in one of its constructors.
365 However, the inductive type is not yet in the environment
367 (*here the explicit_named_substituion is assumed to be of length 0 *)
368 Cic.MutInd (uri,i,[]))
369 | Cic.MutConstruct (uri, i, j, []) ->
370 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
371 let uris = CicUtil.params_of_obj o in
372 Cic.MutConstruct (uri, i, j, mk_subst uris)
373 | Cic.Meta _ | Cic.Implicit _ as t ->
375 debug_print (lazy (sprintf
376 "Warning: %s must be instantiated with _[%s] but we do not enforce it"
380 (fun (s, term) -> s ^ " := " ^ CicNotationPtPp.pp_term term)
385 raise (Invalid_choice (lazy "??? Can this happen?"))
387 CicEnvironment.CircularDependency _ ->
388 raise (Invalid_choice (lazy "Circular dependency in the environment"))))
389 | CicNotationPt.Implicit -> Cic.Implicit None
390 | CicNotationPt.UserInput -> Cic.Implicit (Some `Hole)
391 | CicNotationPt.Num (num, i) -> resolve env (Num i) ~num ()
392 | CicNotationPt.Meta (index, subst) ->
397 | Some term -> Some (aux ~localize loc context term))
400 Cic.Meta (index, cic_subst)
401 | CicNotationPt.Sort `Prop -> Cic.Sort Cic.Prop
402 | CicNotationPt.Sort `Set -> Cic.Sort Cic.Set
403 | CicNotationPt.Sort (`Type u) -> Cic.Sort (Cic.Type u)
404 | CicNotationPt.Sort `CProp -> Cic.Sort Cic.CProp
405 | CicNotationPt.Symbol (symbol, instance) ->
406 resolve env (Symbol (symbol, instance)) ()
407 | _ -> assert false (* god bless Bologna *)
408 and aux_option ~localize loc (context: Cic.name list) annotation = function
409 | None -> Cic.Implicit annotation
410 | Some term -> aux ~localize loc context term
412 aux ~localize:true dummy_floc context ast
414 let interpretate_path ~context path =
415 let localization_tbl = Cic.CicHash.create 23 in
416 (* here we are throwing away useful localization informations!!! *)
418 interpretate_term ~context ~env:Environment.empty ~uri:None ~is_path:true
419 path ~localization_tbl, localization_tbl)
421 let interpretate_obj ~context ~env ~uri ~is_path obj ~localization_tbl =
422 assert (context = []);
423 assert (is_path = false);
424 let interpretate_term = interpretate_term ~localization_tbl in
426 | CicNotationPt.Inductive (params,tyl) ->
427 let uri = match uri with Some uri -> uri | None -> assert false in
431 (fun (context,res) (name,t) ->
432 Cic.Name name :: context,
433 (name, interpretate_term context env None false t)::res
436 context,List.rev res in
439 (fun (name,ty) t -> Cic.Prod (Cic.Name name,ty,t)) params in
443 (*here the explicit_named_substituion is assumed to be of length 0 *)
444 (fun (i,res) (name,_,_,_) ->
445 i + 1,(name,name,Cic.MutInd (uri,i,[]))::res
447 let con_env = DisambiguateTypes.env_of_list name_to_uris env in
450 (fun (name,b,ty,cl) ->
451 let ty' = add_params (interpretate_term context env None false ty) in
456 add_params (interpretate_term context con_env None false ty)
464 Cic.InductiveDefinition (tyl,[],List.length params,[])
465 | CicNotationPt.Record (params,name,ty,fields) ->
466 let uri = match uri with Some uri -> uri | None -> assert false in
470 (fun (context,res) (name,t) ->
471 (Cic.Name name :: context),
472 (name, interpretate_term context env None false t)::res
475 context,List.rev res in
478 (fun (name,ty) t -> Cic.Prod (Cic.Name name,ty,t)) params in
479 let ty' = add_params (interpretate_term context env None false ty) in
483 (fun (context,res) (name,ty,_coercion) ->
484 let context' = Cic.Name name :: context in
485 context',(name,interpretate_term context env None false ty)::res
486 ) (context,[]) fields) in
488 (*here the explicit_named_substituion is assumed to be of length 0 *)
489 let mutind = Cic.MutInd (uri,0,[]) in
490 if params = [] then mutind
493 (mutind::CicUtil.mk_rels (List.length params) (List.length fields)) in
496 (fun t (name,ty) -> Cic.Prod (Cic.Name name,ty,t))
498 let con' = add_params con in
499 let tyl = [name,true,ty',["mk_" ^ name,con']] in
500 let field_names = List.map (fun (x,_,y) -> x,y) fields in
501 Cic.InductiveDefinition
502 (tyl,[],List.length params,[`Class (`Record field_names)])
503 | CicNotationPt.Theorem (flavour, name, ty, bo) ->
504 let attrs = [`Flavour flavour] in
505 let ty' = interpretate_term [] env None false ty in
508 Cic.CurrentProof (name,[],Cic.Implicit None,ty',[],attrs)
510 let bo' = Some (interpretate_term [] env None false bo) in
511 Cic.Constant (name,bo',ty',[],attrs))
514 (* e.g. [5;1;1;1;2;3;4;1;2] -> [2;1;4;3;5] *)
516 let module SortedItem =
518 type t = DisambiguateTypes.domain_item
519 let compare = Pervasives.compare
522 let module Set = Set.Make (SortedItem) in
524 let rev_l = List.rev l in
525 let (_, uniq_rev_l) =
527 (fun (members, rev_l) elt ->
528 if Set.mem elt members then
531 Set.add elt members, elt :: rev_l)
532 (Set.empty, []) rev_l
536 (* "aux" keeps domain in reverse order and doesn't care about duplicates.
537 * Domain item more in deep in the list will be processed first.
539 let rec domain_rev_of_term ?(loc = dummy_floc) context = function
540 | CicNotationPt.AttributedTerm (`Loc loc, term) ->
541 domain_rev_of_term ~loc context term
542 | CicNotationPt.AttributedTerm (_, term) ->
543 domain_rev_of_term ~loc context term
544 | CicNotationPt.Appl terms ->
546 (fun dom term -> domain_rev_of_term ~loc context term @ dom) [] terms
547 | CicNotationPt.Binder (kind, (var, typ), body) ->
550 | `Exists -> [ Symbol ("exists", 0) ]
553 let type_dom = domain_rev_of_term_option loc context typ in
555 domain_rev_of_term ~loc
556 (CicNotationUtil.cic_name_of_name var :: context) body
558 body_dom @ type_dom @ kind_dom
559 | CicNotationPt.Case (term, indty_ident, outtype, branches) ->
560 let term_dom = domain_rev_of_term ~loc context term in
561 let outtype_dom = domain_rev_of_term_option loc context outtype in
562 let get_first_constructor = function
564 | ((head, _, _), _) :: _ -> [ Id head ]
566 let do_branch ((head, _, args), term) =
567 let (term_context, args_domain) =
569 (fun (cont, dom) (name, typ) ->
570 (CicNotationUtil.cic_name_of_name name :: cont,
573 | Some typ -> domain_rev_of_term ~loc cont typ @ dom)))
576 args_domain @ domain_rev_of_term ~loc term_context term
579 List.fold_left (fun dom branch -> do_branch branch @ dom) [] branches
581 branches_dom @ outtype_dom @ term_dom @
582 (match indty_ident with
583 | None -> get_first_constructor branches
584 | Some (ident, _) -> [ Id ident ])
585 | CicNotationPt.Cast (term, ty) ->
586 let term_dom = domain_rev_of_term ~loc context term in
587 let ty_dom = domain_rev_of_term ~loc context ty in
589 | CicNotationPt.LetIn ((var, typ), body, where) ->
590 let body_dom = domain_rev_of_term ~loc context body in
591 let type_dom = domain_rev_of_term_option loc context typ in
593 domain_rev_of_term ~loc
594 (CicNotationUtil.cic_name_of_name var :: context) where
596 where_dom @ type_dom @ body_dom
597 | CicNotationPt.LetRec (kind, defs, where) ->
600 (fun acc ((var, typ), _, _) ->
601 CicNotationUtil.cic_name_of_name var :: acc)
604 let where_dom = domain_rev_of_term ~loc context' where in
607 (fun dom ((_, typ), body, _) ->
608 domain_rev_of_term ~loc context' body @
609 domain_rev_of_term_option loc context typ)
613 | CicNotationPt.Ident (name, subst) ->
615 let index = find_in_context name context in
616 if subst <> None then
617 CicNotationPt.fail loc "Explicit substitutions not allowed here"
625 (fun dom (_, term) ->
626 let dom' = domain_rev_of_term ~loc context term in
629 | CicNotationPt.Uri _ -> []
630 | CicNotationPt.Implicit -> []
631 | CicNotationPt.Num (num, i) -> [ Num i ]
632 | CicNotationPt.Meta (index, local_context) ->
634 (fun dom term -> domain_rev_of_term_option loc context term @ dom) []
636 | CicNotationPt.Sort _ -> []
637 | CicNotationPt.Symbol (symbol, instance) -> [ Symbol (symbol, instance) ]
638 | CicNotationPt.UserInput
639 | CicNotationPt.Literal _
640 | CicNotationPt.Layout _
641 | CicNotationPt.Magic _
642 | CicNotationPt.Variable _ -> assert false
644 and domain_rev_of_term_option loc context = function
646 | Some t -> domain_rev_of_term ~loc context t
648 let domain_of_term ~context ast = rev_uniq (domain_rev_of_term context ast)
650 let domain_of_obj ~context ast =
651 assert (context = []);
654 | CicNotationPt.Theorem (_,_,ty,bo) ->
657 | Some bo -> domain_rev_of_term [] bo) @
659 | CicNotationPt.Inductive (params,tyl) ->
666 (fun (_,ty) -> domain_rev_of_term [] ty) cl) @
667 domain_rev_of_term [] ty) tyl) in
671 domain_rev_of_term [] ty @ dom
676 not ( List.exists (fun (name',_) -> name = Id name') params
677 || List.exists (fun (name',_,_,_) -> name = Id name') tyl)
679 | CicNotationPt.Record (params,_,ty,fields) ->
682 (List.rev_map (fun (_,ty,_) -> domain_rev_of_term [] ty) fields) in
686 not ( List.exists (fun (name',_) -> name = Id name') params
687 || List.exists (fun (name',_,_) -> name = Id name') fields)
692 domain_rev_of_term [] ty @ dom
693 ) (dom @ domain_rev_of_term [] ty) params
698 let domain_diff dom1 dom2 =
699 (* let domain_diff = Domain.diff *)
701 List.fold_left (fun pred elt -> (fun elt' -> elt' = elt || pred elt'))
702 (fun _ -> false) dom2
704 List.filter (fun elt -> not (is_in_dom2 elt)) dom1
706 module type Disambiguator =
708 val disambiguate_term :
709 ?fresh_instances:bool ->
711 context:Cic.context ->
712 metasenv:Cic.metasenv ->
713 ?initial_ugraph:CicUniv.universe_graph ->
714 aliases:DisambiguateTypes.environment ->(* previous interpretation status *)
715 universe:DisambiguateTypes.multiple_environment option ->
716 CicNotationPt.term ->
717 ((DisambiguateTypes.domain_item * DisambiguateTypes.codomain_item) list *
718 Cic.metasenv * (* new metasenv *)
720 CicUniv.universe_graph) list * (* disambiguated term *)
723 val disambiguate_obj :
724 ?fresh_instances:bool ->
726 aliases:DisambiguateTypes.environment ->(* previous interpretation status *)
727 universe:DisambiguateTypes.multiple_environment option ->
728 uri:UriManager.uri option -> (* required only for inductive types *)
730 ((DisambiguateTypes.domain_item * DisambiguateTypes.codomain_item) list *
731 Cic.metasenv * (* new metasenv *)
733 CicUniv.universe_graph) list * (* disambiguated obj *)
737 module Make (C: Callbacks) =
739 let choices_of_id dbd id =
740 let uris = Whelp.locate ~dbd id in
744 [(C.input_or_locate_uri
745 ~title:("URI matching \"" ^ id ^ "\" unknown.") ~id ())]
748 C.interactive_user_uri_choice ~selection_mode:`MULTIPLE
749 ~ok:"Try selected." ~enable_button_for_non_vars:true
750 ~title:"Ambiguous input." ~id
751 ~msg: ("Ambiguous input \"" ^ id ^
752 "\". Please, choose one or more interpretations:")
757 (UriManager.string_of_uri uri,
760 CicUtil.term_of_uri uri
762 debug_print (lazy (UriManager.string_of_uri uri));
763 debug_print (lazy (Printexc.to_string exn));
769 let refine_profiler = HExtlib.profile "disambiguate_thing.refine_thing"
771 let disambiguate_thing ~dbd ~context ~metasenv
772 ?(initial_ugraph = CicUniv.empty_ugraph) ~aliases ~universe
773 ~uri ~pp_thing ~domain_of_thing ~interpretate_thing ~refine_thing thing
775 debug_print (lazy "DISAMBIGUATE INPUT");
776 let disambiguate_context = (* cic context -> disambiguate context *)
778 (function None -> Cic.Anonymous | Some (name, _) -> name)
781 debug_print (lazy ("TERM IS: " ^ (pp_thing thing)));
782 let thing_dom = domain_of_thing ~context:disambiguate_context thing in
783 debug_print (lazy (sprintf "DISAMBIGUATION DOMAIN: %s"
784 (string_of_domain thing_dom)));
786 debug_print (lazy (sprintf "DISAMBIGUATION ENVIRONMENT: %s"
787 (DisambiguatePp.pp_environment aliases)));
788 debug_print (lazy (sprintf "DISAMBIGUATION UNIVERSE: %s"
789 (match universe with None -> "None" | Some _ -> "Some _")));
792 Environment.fold (fun item _ dom -> item :: dom) aliases []
794 let todo_dom = domain_diff thing_dom current_dom in
795 (* (2) lookup function for any item (Id/Symbol/Num) *)
799 let lookup_in_library () =
801 | Id id -> choices_of_id dbd id
802 | Symbol (symb, _) ->
803 List.map DisambiguateChoices.mk_choice
804 (TermAcicContent.lookup_interpretations symb)
806 DisambiguateChoices.lookup_num_choices ()
809 | None -> lookup_in_library ()
814 | Symbol (symb, _) -> Symbol (symb, 0)
817 Environment.find item e
818 with Not_found -> [])
825 if benchmark then begin
826 let per_item_choices =
830 let len = List.length (lookup_choices dom_item) in
831 debug_print (lazy (sprintf "BENCHMARK %s: %d"
832 (string_of_domain_item dom_item) len));
834 with No_choices _ -> 0)
837 max_refinements := List.fold_left ( * ) 1 per_item_choices;
838 actual_refinements := 0;
839 domain_size := List.length thing_dom;
841 (float_of_int !max_refinements) ** (1. /. float_of_int !domain_size)
847 (* (3) test an interpretation filling with meta uninterpreted identifiers
849 let test_env aliases todo_dom ugraph =
856 | Id _ | Num _ -> (fun _ _ _ -> Cic.Implicit (Some `Closed))
857 | Symbol _ -> (fun _ _ _ -> Cic.Implicit None))) env)
861 let localization_tbl = Cic.CicHash.create 503 in
863 interpretate_thing ~context:disambiguate_context ~env:filled_env
864 ~uri ~is_path:false thing ~localization_tbl
868 refine_thing metasenv context uri cic_thing ugraph ~localization_tbl
871 in refine_profiler.HExtlib.profile foo ()
873 | Try_again msg -> Uncertain (None,msg), ugraph
874 | Invalid_choice msg -> Ko (None,msg), ugraph
876 (* (4) build all possible interpretations *)
877 let (@@) (l1,l2) (l1',l2') = l1@l1', l2@l2' in
878 let rec aux aliases diff lookup_in_todo_dom todo_dom base_univ =
881 assert (lookup_in_todo_dom = None);
882 (match test_env aliases [] base_univ with
883 | Ok (thing, metasenv),new_univ ->
884 [ aliases, diff, metasenv, thing, new_univ ], []
885 | Ko (loc,msg),_ | Uncertain (loc,msg),_ -> [],[loc,msg])
886 | item :: remaining_dom ->
887 debug_print (lazy (sprintf "CHOOSED ITEM: %s"
888 (string_of_domain_item item)));
890 match lookup_in_todo_dom with
891 None -> lookup_choices item
892 | Some choices -> choices in
895 [], [None,lazy ("No choices for " ^ string_of_domain_item item)]
897 (* just one choice. We perform a one-step look-up and
898 if the next set of choices is also a singleton we
899 skip this refinement step *)
900 debug_print(lazy (sprintf "%s CHOSEN" (fst codomain_item)));
901 let new_env = Environment.add item codomain_item aliases in
902 let new_diff = (item,codomain_item)::diff in
903 let lookup_in_todo_dom,next_choice_is_single =
904 match remaining_dom with
907 let choices = lookup_choices he in
908 Some choices,List.length choices = 1
910 if next_choice_is_single then
911 aux new_env new_diff lookup_in_todo_dom remaining_dom
914 (match test_env new_env remaining_dom base_univ with
915 | Ok (thing, metasenv),new_univ ->
916 (match remaining_dom with
918 [ new_env, new_diff, metasenv, thing, new_univ ], []
920 aux new_env new_diff lookup_in_todo_dom
921 remaining_dom new_univ)
922 | Uncertain (loc,msg),new_univ ->
923 (match remaining_dom with
924 | [] -> [], [loc,msg]
926 aux new_env new_diff lookup_in_todo_dom
927 remaining_dom new_univ)
928 | Ko (loc,msg),_ -> [], [loc,msg])
930 let rec filter univ = function
932 | codomain_item :: tl ->
933 debug_print(lazy (sprintf "%s CHOSEN" (fst codomain_item)));
934 let new_env = Environment.add item codomain_item aliases in
935 let new_diff = (item,codomain_item)::diff in
936 (match test_env new_env remaining_dom univ with
937 | Ok (thing, metasenv),new_univ ->
938 (match remaining_dom with
939 | [] -> [ new_env, new_diff, metasenv, thing, new_univ ], []
940 | _ -> aux new_env new_diff None remaining_dom new_univ
943 | Uncertain (loc,msg),new_univ ->
944 (match remaining_dom with
946 | _ -> aux new_env new_diff None remaining_dom new_univ
949 | Ko (loc,msg),_ -> ([],[loc,msg]) @@ filter univ tl)
951 filter base_univ choices
953 let base_univ = initial_ugraph in
956 match aux aliases [] None todo_dom base_univ with
957 | [],errors -> raise (NoWellTypedInterpretation (0,errors))
958 | [_,diff,metasenv,t,ugraph],_ ->
959 debug_print (lazy "SINGLE INTERPRETATION");
960 [diff,metasenv,t,ugraph], false
962 debug_print (lazy (sprintf "MANY INTERPRETATIONS (%d)" (List.length l)));
965 (fun (env, _, _, _, _) ->
969 fst (Environment.find domain_item env)
971 (descr_of_domain_item domain_item, description))
975 let choosed = C.interactive_interpretation_choice choices in
976 (List.map (fun n->let _,d,m,t,u= List.nth l n in d,m,t,u) choosed),
981 CicEnvironment.CircularDependency s ->
982 failwith "Disambiguate: circular dependency"
984 let disambiguate_term ?(fresh_instances=false) ~dbd ~context ~metasenv
985 ?(initial_ugraph = CicUniv.empty_ugraph) ~aliases ~universe term
988 if fresh_instances then CicNotationUtil.freshen_term term else term
990 disambiguate_thing ~dbd ~context ~metasenv ~initial_ugraph ~aliases
991 ~universe ~uri:None ~pp_thing:CicNotationPp.pp_term
992 ~domain_of_thing:domain_of_term ~interpretate_thing:interpretate_term
993 ~refine_thing:refine_term term
995 let disambiguate_obj ?(fresh_instances=false) ~dbd ~aliases ~universe ~uri
999 if fresh_instances then CicNotationUtil.freshen_obj obj else obj
1001 disambiguate_thing ~dbd ~context:[] ~metasenv:[] ~aliases ~universe ~uri
1002 ~pp_thing:CicNotationPp.pp_obj ~domain_of_thing:domain_of_obj
1003 ~interpretate_thing:interpretate_obj ~refine_thing:refine_obj