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
451 (fun (name,_,_,_) (i,t) ->
452 (*here the explicit_named_substituion is assumed to be of length 0 *)
453 let t' = Cic.MutInd (uri,i,[]) in
454 let t = CicSubstitution.subst t' t in
456 ) tyl (List.length tyl - 1,t)) in
459 (fun (name,b,ty,cl) ->
460 let ty' = add_params (interpretate_term context env None false ty) in
465 add_params (interpretate_term context con_env None false ty)
473 Cic.InductiveDefinition (tyl,[],List.length params,[])
474 | CicNotationPt.Record (params,name,ty,fields) ->
475 let uri = match uri with Some uri -> uri | None -> assert false in
479 (fun (context,res) (name,t) ->
480 (Cic.Name name :: context),
481 (name, interpretate_term context env None false t)::res
484 context,List.rev res in
487 (fun (name,ty) t -> Cic.Prod (Cic.Name name,ty,t)) params in
488 let ty' = add_params (interpretate_term context env None false ty) in
492 (fun (context,res) (name,ty) ->
493 let context' = Cic.Name name :: context in
494 context',(name,interpretate_term context env None false ty)::res
495 ) (context,[]) fields) in
497 (*here the explicit_named_substituion is assumed to be of length 0 *)
498 let mutind = Cic.MutInd (uri,0,[]) in
499 if params = [] then mutind
502 (mutind::CicUtil.mk_rels (List.length params) (List.length fields)) in
505 (fun t (name,ty) -> Cic.Prod (Cic.Name name,ty,t))
507 let con' = add_params con in
508 let tyl = [name,true,ty',["mk_" ^ name,con']] in
509 let field_names = List.map fst fields in
510 Cic.InductiveDefinition
511 (tyl,[],List.length params,[`Class (`Record field_names)])
512 | CicNotationPt.Theorem (flavour, name, ty, bo) ->
513 let attrs = [`Flavour flavour] in
514 let ty' = interpretate_term [] env None false ty in
517 Cic.CurrentProof (name,[],Cic.Implicit None,ty',[],attrs)
519 let bo' = Some (interpretate_term [] env None false bo) in
520 Cic.Constant (name,bo',ty',[],attrs))
523 (* e.g. [5;1;1;1;2;3;4;1;2] -> [2;1;4;3;5] *)
525 let module SortedItem =
527 type t = DisambiguateTypes.domain_item
528 let compare = Pervasives.compare
531 let module Set = Set.Make (SortedItem) in
533 let rev_l = List.rev l in
534 let (_, uniq_rev_l) =
536 (fun (members, rev_l) elt ->
537 if Set.mem elt members then
540 Set.add elt members, elt :: rev_l)
541 (Set.empty, []) rev_l
545 (* "aux" keeps domain in reverse order and doesn't care about duplicates.
546 * Domain item more in deep in the list will be processed first.
548 let rec domain_rev_of_term ?(loc = dummy_floc) context = function
549 | CicNotationPt.AttributedTerm (`Loc loc, term) ->
550 domain_rev_of_term ~loc context term
551 | CicNotationPt.AttributedTerm (_, term) ->
552 domain_rev_of_term ~loc context term
553 | CicNotationPt.Appl terms ->
555 (fun dom term -> domain_rev_of_term ~loc context term @ dom) [] terms
556 | CicNotationPt.Binder (kind, (var, typ), body) ->
559 | `Exists -> [ Symbol ("exists", 0) ]
562 let type_dom = domain_rev_of_term_option loc context typ in
564 domain_rev_of_term ~loc
565 (CicNotationUtil.cic_name_of_name var :: context) body
567 body_dom @ type_dom @ kind_dom
568 | CicNotationPt.Case (term, indty_ident, outtype, branches) ->
569 let term_dom = domain_rev_of_term ~loc context term in
570 let outtype_dom = domain_rev_of_term_option loc context outtype in
571 let get_first_constructor = function
573 | ((head, _, _), _) :: _ -> [ Id head ]
575 let do_branch ((head, _, args), term) =
576 let (term_context, args_domain) =
578 (fun (cont, dom) (name, typ) ->
579 (CicNotationUtil.cic_name_of_name name :: cont,
582 | Some typ -> domain_rev_of_term ~loc cont typ @ dom)))
585 args_domain @ domain_rev_of_term ~loc term_context term
588 List.fold_left (fun dom branch -> do_branch branch @ dom) [] branches
590 branches_dom @ outtype_dom @ term_dom @
591 (match indty_ident with
592 | None -> get_first_constructor branches
593 | Some (ident, _) -> [ Id ident ])
594 | CicNotationPt.Cast (term, ty) ->
595 let term_dom = domain_rev_of_term ~loc context term in
596 let ty_dom = domain_rev_of_term ~loc context ty in
598 | CicNotationPt.LetIn ((var, typ), body, where) ->
599 let body_dom = domain_rev_of_term ~loc context body in
600 let type_dom = domain_rev_of_term_option loc context typ in
602 domain_rev_of_term ~loc
603 (CicNotationUtil.cic_name_of_name var :: context) where
605 where_dom @ type_dom @ body_dom
606 | CicNotationPt.LetRec (kind, defs, where) ->
609 (fun acc ((var, typ), _, _) ->
610 CicNotationUtil.cic_name_of_name var :: acc)
613 let where_dom = domain_rev_of_term ~loc context' where in
616 (fun dom ((_, typ), body, _) ->
617 domain_rev_of_term ~loc context' body @
618 domain_rev_of_term_option loc context typ)
622 | CicNotationPt.Ident (name, subst) ->
624 let index = find_in_context name context in
625 if subst <> None then
626 CicNotationPt.fail loc "Explicit substitutions not allowed here"
634 (fun dom (_, term) ->
635 let dom' = domain_rev_of_term ~loc context term in
638 | CicNotationPt.Uri _ -> []
639 | CicNotationPt.Implicit -> []
640 | CicNotationPt.Num (num, i) -> [ Num i ]
641 | CicNotationPt.Meta (index, local_context) ->
643 (fun dom term -> domain_rev_of_term_option loc context term @ dom) []
645 | CicNotationPt.Sort _ -> []
646 | CicNotationPt.Symbol (symbol, instance) -> [ Symbol (symbol, instance) ]
647 | CicNotationPt.UserInput
648 | CicNotationPt.Literal _
649 | CicNotationPt.Layout _
650 | CicNotationPt.Magic _
651 | CicNotationPt.Variable _ -> assert false
653 and domain_rev_of_term_option loc context = function
655 | Some t -> domain_rev_of_term ~loc context t
657 let domain_of_term ~context ast = rev_uniq (domain_rev_of_term context ast)
659 let domain_of_obj ~context ast =
660 assert (context = []);
663 | CicNotationPt.Theorem (_,_,ty,bo) ->
666 | Some bo -> domain_rev_of_term [] bo) @
668 | CicNotationPt.Inductive (params,tyl) ->
675 (fun (_,ty) -> domain_rev_of_term [] ty) cl) @
676 domain_rev_of_term [] ty) tyl) in
680 domain_rev_of_term [] ty @ dom
685 not ( List.exists (fun (name',_) -> name = Id name') params
686 || List.exists (fun (name',_,_,_) -> name = Id name') tyl)
688 | CicNotationPt.Record (params,_,ty,fields) ->
691 (List.rev_map (fun (_,ty) -> domain_rev_of_term [] ty) fields) in
695 not ( List.exists (fun (name',_) -> name = Id name') params
696 || List.exists (fun (name',_) -> name = Id name') fields)
701 domain_rev_of_term [] ty @ dom
702 ) (dom @ domain_rev_of_term [] ty) params
707 let domain_diff dom1 dom2 =
708 (* let domain_diff = Domain.diff *)
710 List.fold_left (fun pred elt -> (fun elt' -> elt' = elt || pred elt'))
711 (fun _ -> false) dom2
713 List.filter (fun elt -> not (is_in_dom2 elt)) dom1
715 module type Disambiguator =
717 val disambiguate_term :
718 ?fresh_instances:bool ->
720 context:Cic.context ->
721 metasenv:Cic.metasenv ->
722 ?initial_ugraph:CicUniv.universe_graph ->
723 aliases:DisambiguateTypes.environment ->(* previous interpretation status *)
724 universe:DisambiguateTypes.multiple_environment option ->
725 CicNotationPt.term ->
726 ((DisambiguateTypes.domain_item * DisambiguateTypes.codomain_item) list *
727 Cic.metasenv * (* new metasenv *)
729 CicUniv.universe_graph) list * (* disambiguated term *)
732 val disambiguate_obj :
733 ?fresh_instances:bool ->
735 aliases:DisambiguateTypes.environment ->(* previous interpretation status *)
736 universe:DisambiguateTypes.multiple_environment option ->
737 uri:UriManager.uri option -> (* required only for inductive types *)
739 ((DisambiguateTypes.domain_item * DisambiguateTypes.codomain_item) list *
740 Cic.metasenv * (* new metasenv *)
742 CicUniv.universe_graph) list * (* disambiguated obj *)
746 module Make (C: Callbacks) =
748 let choices_of_id dbd id =
749 let uris = Whelp.locate ~dbd id in
753 [(C.input_or_locate_uri
754 ~title:("URI matching \"" ^ id ^ "\" unknown.") ~id ())]
757 C.interactive_user_uri_choice ~selection_mode:`MULTIPLE
758 ~ok:"Try selected." ~enable_button_for_non_vars:true
759 ~title:"Ambiguous input." ~id
760 ~msg: ("Ambiguous input \"" ^ id ^
761 "\". Please, choose one or more interpretations:")
766 (UriManager.string_of_uri uri,
769 CicUtil.term_of_uri uri
771 debug_print (lazy (UriManager.string_of_uri uri));
772 debug_print (lazy (Printexc.to_string exn));
778 let refine_profiler = HExtlib.profile "disambiguate_thing.refine_thing"
780 let disambiguate_thing ~dbd ~context ~metasenv
781 ?(initial_ugraph = CicUniv.empty_ugraph) ~aliases ~universe
782 ~uri ~pp_thing ~domain_of_thing ~interpretate_thing ~refine_thing thing
784 debug_print (lazy "DISAMBIGUATE INPUT");
785 let disambiguate_context = (* cic context -> disambiguate context *)
787 (function None -> Cic.Anonymous | Some (name, _) -> name)
790 debug_print (lazy ("TERM IS: " ^ (pp_thing thing)));
791 let thing_dom = domain_of_thing ~context:disambiguate_context thing in
792 debug_print (lazy (sprintf "DISAMBIGUATION DOMAIN: %s"
793 (string_of_domain thing_dom)));
795 debug_print (lazy (sprintf "DISAMBIGUATION ENVIRONMENT: %s"
796 (DisambiguatePp.pp_environment aliases)));
797 debug_print (lazy (sprintf "DISAMBIGUATION UNIVERSE: %s"
798 (match universe with None -> "None" | Some _ -> "Some _")));
801 Environment.fold (fun item _ dom -> item :: dom) aliases []
803 let todo_dom = domain_diff thing_dom current_dom in
804 (* (2) lookup function for any item (Id/Symbol/Num) *)
808 let lookup_in_library () =
810 | Id id -> choices_of_id dbd id
811 | Symbol (symb, _) ->
812 List.map DisambiguateChoices.mk_choice
813 (TermAcicContent.lookup_interpretations symb)
815 DisambiguateChoices.lookup_num_choices ()
818 | None -> lookup_in_library ()
823 | Symbol (symb, _) -> Symbol (symb, 0)
826 Environment.find item e
827 with Not_found -> [])
834 if benchmark then begin
835 let per_item_choices =
839 let len = List.length (lookup_choices dom_item) in
840 debug_print (lazy (sprintf "BENCHMARK %s: %d"
841 (string_of_domain_item dom_item) len));
843 with No_choices _ -> 0)
846 max_refinements := List.fold_left ( * ) 1 per_item_choices;
847 actual_refinements := 0;
848 domain_size := List.length thing_dom;
850 (float_of_int !max_refinements) ** (1. /. float_of_int !domain_size)
856 (* (3) test an interpretation filling with meta uninterpreted identifiers
858 let test_env aliases todo_dom ugraph =
865 | Id _ | Num _ -> (fun _ _ _ -> Cic.Implicit (Some `Closed))
866 | Symbol _ -> (fun _ _ _ -> Cic.Implicit None))) env)
870 let localization_tbl = Cic.CicHash.create 503 in
872 interpretate_thing ~context:disambiguate_context ~env:filled_env
873 ~uri ~is_path:false thing ~localization_tbl
877 refine_thing metasenv context uri cic_thing ugraph ~localization_tbl
880 in refine_profiler.HExtlib.profile foo ()
882 | Try_again msg -> Uncertain (None,msg), ugraph
883 | Invalid_choice msg -> Ko (None,msg), ugraph
885 (* (4) build all possible interpretations *)
886 let (@@) (l1,l2) (l1',l2') = l1@l1', l2@l2' in
887 let rec aux aliases diff lookup_in_todo_dom todo_dom base_univ =
890 assert (lookup_in_todo_dom = None);
891 (match test_env aliases [] base_univ with
892 | Ok (thing, metasenv),new_univ ->
893 [ aliases, diff, metasenv, thing, new_univ ], []
894 | Ko (loc,msg),_ | Uncertain (loc,msg),_ -> [],[loc,msg])
895 | item :: remaining_dom ->
896 debug_print (lazy (sprintf "CHOOSED ITEM: %s"
897 (string_of_domain_item item)));
899 match lookup_in_todo_dom with
900 None -> lookup_choices item
901 | Some choices -> choices in
904 [], [None,lazy ("No choices for " ^ string_of_domain_item item)]
906 (* just one choice. We perform a one-step look-up and
907 if the next set of choices is also a singleton we
908 skip this refinement step *)
909 debug_print(lazy (sprintf "%s CHOSEN" (fst codomain_item)));
910 let new_env = Environment.add item codomain_item aliases in
911 let new_diff = (item,codomain_item)::diff in
912 let lookup_in_todo_dom,next_choice_is_single =
913 match remaining_dom with
916 let choices = lookup_choices he in
917 Some choices,List.length choices = 1
919 if next_choice_is_single then
920 aux new_env new_diff lookup_in_todo_dom remaining_dom
923 (match test_env new_env remaining_dom base_univ with
924 | Ok (thing, metasenv),new_univ ->
925 (match remaining_dom with
927 [ new_env, new_diff, metasenv, thing, new_univ ], []
929 aux new_env new_diff lookup_in_todo_dom
930 remaining_dom new_univ)
931 | Uncertain (loc,msg),new_univ ->
932 (match remaining_dom with
933 | [] -> [], [loc,msg]
935 aux new_env new_diff lookup_in_todo_dom
936 remaining_dom new_univ)
937 | Ko (loc,msg),_ -> [], [loc,msg])
939 let rec filter univ = function
941 | codomain_item :: tl ->
942 debug_print(lazy (sprintf "%s CHOSEN" (fst codomain_item)));
943 let new_env = Environment.add item codomain_item aliases in
944 let new_diff = (item,codomain_item)::diff in
945 (match test_env new_env remaining_dom univ with
946 | Ok (thing, metasenv),new_univ ->
947 (match remaining_dom with
948 | [] -> [ new_env, new_diff, metasenv, thing, new_univ ], []
949 | _ -> aux new_env new_diff None remaining_dom new_univ
952 | Uncertain (loc,msg),new_univ ->
953 (match remaining_dom with
955 | _ -> aux new_env new_diff None remaining_dom new_univ
958 | Ko (loc,msg),_ -> ([],[loc,msg]) @@ filter univ tl)
960 filter base_univ choices
962 let base_univ = initial_ugraph in
965 match aux aliases [] None todo_dom base_univ with
966 | [],errors -> raise (NoWellTypedInterpretation (0,errors))
967 | [_,diff,metasenv,t,ugraph],_ ->
968 debug_print (lazy "SINGLE INTERPRETATION");
969 [diff,metasenv,t,ugraph], false
971 debug_print (lazy (sprintf "MANY INTERPRETATIONS (%d)" (List.length l)));
974 (fun (env, _, _, _, _) ->
978 fst (Environment.find domain_item env)
980 (descr_of_domain_item domain_item, description))
984 let choosed = C.interactive_interpretation_choice choices in
985 (List.map (fun n->let _,d,m,t,u= List.nth l n in d,m,t,u) choosed),
990 CicEnvironment.CircularDependency s ->
991 failwith "Disambiguate: circular dependency"
993 let disambiguate_term ?(fresh_instances=false) ~dbd ~context ~metasenv
994 ?(initial_ugraph = CicUniv.empty_ugraph) ~aliases ~universe term
997 if fresh_instances then CicNotationUtil.freshen_term term else term
999 disambiguate_thing ~dbd ~context ~metasenv ~initial_ugraph ~aliases
1000 ~universe ~uri:None ~pp_thing:CicNotationPp.pp_term
1001 ~domain_of_thing:domain_of_term ~interpretate_thing:interpretate_term
1002 ~refine_thing:refine_term term
1004 let disambiguate_obj ?(fresh_instances=false) ~dbd ~aliases ~universe ~uri
1008 if fresh_instances then CicNotationUtil.freshen_obj obj else obj
1010 disambiguate_thing ~dbd ~context:[] ~metasenv:[] ~aliases ~universe ~uri
1011 ~pp_thing:CicNotationPp.pp_obj ~domain_of_thing:domain_of_obj
1012 ~interpretate_thing:interpretate_obj ~refine_thing:refine_obj