1 (* Copyright (C) 2004, HELM Team.
3 * This file is part of HELM, an Hypertextual, Electronic
4 * Library of Mathematics, developed at the Computer Science
5 * Department, University of Bologna, Italy.
7 * HELM is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
12 * HELM is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with HELM; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
22 * For details, see the HELM World-Wide-Web page,
23 * http://helm.cs.unibo.it/
30 open DisambiguateTypes
33 (* the integer is an offset to be added to each location *)
34 exception NoWellTypedInterpretation of
35 int * (Token.flocation option * string Lazy.t) list
36 exception PathNotWellFormed
38 (** raised when an environment is not enough informative to decide *)
39 exception Try_again of string Lazy.t
41 type aliases = bool * DisambiguateTypes.environment
42 type 'a disambiguator_input = string * int * 'a
45 let debug_print s = if debug then prerr_endline (Lazy.force s) else ()
48 (** print benchmark information *)
50 let max_refinements = ref 0 (* benchmarking is not thread safe *)
51 let actual_refinements = ref 0
52 let domain_size = ref 0
53 let choices_avg = ref 0.
56 let descr_of_domain_item = function
59 | Num i -> string_of_int i
62 | Ok of 'a * Cic.metasenv
63 | Ko of Token.flocation option * string Lazy.t
64 | Uncertain of Token.flocation option * string Lazy.t
66 let refine_term metasenv context uri term ugraph ~localization_tbl =
67 (* if benchmark then incr actual_refinements; *)
69 debug_print (lazy (sprintf "TEST_INTERPRETATION: %s" (CicPp.ppterm term)));
71 let term', _, metasenv',ugraph1 =
72 CicRefine.type_of_aux' metasenv context term ugraph ~localization_tbl in
73 (Ok (term', metasenv')),ugraph1
76 let rec process_exn loc =
78 HExtlib.Localized (loc,exn) -> process_exn (Some loc) exn
79 | CicRefine.Uncertain msg ->
80 debug_print (lazy ("UNCERTAIN!!! [" ^ (Lazy.force msg) ^ "] " ^ CicPp.ppterm term)) ;
81 Uncertain (loc,msg),ugraph
82 | CicRefine.RefineFailure msg ->
83 debug_print (lazy (sprintf "PRUNED!!!\nterm%s\nmessage:%s"
84 (CicPp.ppterm term) (Lazy.force msg)));
90 let refine_obj metasenv context uri obj ugraph ~localization_tbl =
91 assert (context = []);
92 debug_print (lazy (sprintf "TEST_INTERPRETATION: %s" (CicPp.ppobj obj))) ;
94 let obj', metasenv,ugraph =
95 CicRefine.typecheck metasenv uri obj ~localization_tbl
97 (Ok (obj', metasenv)),ugraph
100 let rec process_exn loc =
102 HExtlib.Localized (loc,exn) -> process_exn (Some loc) exn
103 | CicRefine.Uncertain msg ->
104 debug_print (lazy ("UNCERTAIN!!! [" ^ (Lazy.force msg) ^ "] " ^ CicPp.ppobj obj)) ;
105 Uncertain (loc,msg),ugraph
106 | CicRefine.RefineFailure msg ->
107 debug_print (lazy (sprintf "PRUNED!!!\nterm%s\nmessage:%s"
108 (CicPp.ppobj obj) (Lazy.force msg))) ;
114 let resolve (env: codomain_item Environment.t) (item: domain_item) ?(num = "") ?(args = []) () =
116 snd (Environment.find item env) env num args
118 failwith ("Domain item not found: " ^
119 (DisambiguateTypes.string_of_domain_item item))
121 (* TODO move it to Cic *)
122 let find_in_context name context =
123 let rec aux acc = function
124 | [] -> raise Not_found
125 | Cic.Name hd :: tl when hd = name -> acc
126 | _ :: tl -> aux (acc + 1) tl
130 let interpretate_term ~(context: Cic.name list) ~env ~uri ~is_path ast
134 let rec aux ~localize loc (context: Cic.name list) = function
135 | CicNotationPt.AttributedTerm (`Loc loc, term) ->
136 let res = aux ~localize loc context term in
137 if localize then Cic.CicHash.add localization_tbl res loc;
139 | CicNotationPt.AttributedTerm (_, term) -> aux ~localize loc context term
140 | CicNotationPt.Appl (CicNotationPt.Symbol (symb, i) :: args) ->
141 let cic_args = List.map (aux ~localize loc context) args in
142 resolve env (Symbol (symb, i)) ~args:cic_args ()
143 | CicNotationPt.Appl terms ->
144 Cic.Appl (List.map (aux ~localize loc context) terms)
145 | CicNotationPt.Binder (binder_kind, (var, typ), body) ->
146 let cic_type = aux_option ~localize loc context (Some `Type) typ in
147 let cic_name = CicNotationUtil.cic_name_of_name var in
148 let cic_body = aux ~localize loc (cic_name :: context) body in
149 (match binder_kind with
150 | `Lambda -> Cic.Lambda (cic_name, cic_type, cic_body)
152 | `Forall -> Cic.Prod (cic_name, cic_type, cic_body)
154 resolve env (Symbol ("exists", 0))
155 ~args:[ cic_type; Cic.Lambda (cic_name, cic_type, cic_body) ] ())
156 | CicNotationPt.Case (term, indty_ident, outtype, branches) ->
157 let cic_term = aux ~localize loc context term in
158 let cic_outtype = aux_option ~localize loc context None outtype in
159 let do_branch ((head, _, args), term) =
160 let rec do_branch' context = function
161 | [] -> aux ~localize loc context term
162 | (name, typ) :: tl ->
163 let cic_name = CicNotationUtil.cic_name_of_name name in
164 let cic_body = do_branch' (cic_name :: context) tl in
167 | None -> Cic.Implicit (Some `Type)
168 | Some typ -> aux ~localize loc context typ
170 Cic.Lambda (cic_name, typ, cic_body)
172 do_branch' context args
174 let (indtype_uri, indtype_no) =
175 match indty_ident with
176 | Some (indty_ident, _) ->
177 (match resolve env (Id indty_ident) () with
178 | Cic.MutInd (uri, tyno, _) -> (uri, tyno)
180 raise (Try_again (lazy "The type of the term to be matched
183 raise (Invalid_choice (lazy "The type of the term to be matched is not (co)inductive!")))
185 let fst_constructor =
187 | ((head, _, _), _) :: _ -> head
188 | [] -> raise (Invalid_choice (lazy "The type of the term to be matched is an inductive type without constructors that cannot be determined"))
190 (match resolve env (Id fst_constructor) () with
191 | Cic.MutConstruct (indtype_uri, indtype_no, _, _) ->
192 (indtype_uri, indtype_no)
194 raise (Try_again (lazy "The type of the term to be matched
197 raise (Invalid_choice (lazy "The type of the term to be matched is not (co)inductive!")))
199 Cic.MutCase (indtype_uri, indtype_no, cic_outtype, cic_term,
200 (List.map do_branch branches))
201 | CicNotationPt.Cast (t1, t2) ->
202 let cic_t1 = aux ~localize loc context t1 in
203 let cic_t2 = aux ~localize loc context t2 in
204 Cic.Cast (cic_t1, cic_t2)
205 | CicNotationPt.LetIn ((name, typ), def, body) ->
206 let cic_def = aux ~localize loc context def in
207 let cic_name = CicNotationUtil.cic_name_of_name name in
211 | Some t -> Cic.Cast (cic_def, aux ~localize loc context t)
213 let cic_body = aux ~localize loc (cic_name :: context) body in
214 Cic.LetIn (cic_name, cic_def, cic_body)
215 | CicNotationPt.LetRec (kind, defs, body) ->
218 (fun acc ((name, _), _, _) ->
219 CicNotationUtil.cic_name_of_name name :: acc)
223 let unlocalized_body = aux ~localize:false loc context' body in
224 match unlocalized_body with
225 Cic.Rel 1 -> `AvoidLetInNoAppl
226 | Cic.Appl (Cic.Rel 1::l) ->
231 let t',subst,metasenv =
232 CicMetaSubst.delift_rels [] [] 1 t
235 assert (metasenv=[]);
238 (* We can avoid the LetIn. But maybe we need to recompute l'
239 so that it is localized *)
242 CicNotationPt.AttributedTerm (_,CicNotationPt.Appl(_::l)) ->
243 let l' = List.map (aux ~localize loc context) l in
249 CicMetaSubst.DeliftingARelWouldCaptureAFreeVariable ->
251 `AddLetIn (aux ~localize loc context' body)
253 `AddLetIn unlocalized_body)
256 `AddLetIn (aux ~localize loc context' body)
258 `AddLetIn unlocalized_body
262 (fun ((name, typ), body, decr_idx) ->
263 let cic_body = aux ~localize loc context' body in
265 aux_option ~localize loc context (Some `Type) typ in
267 match CicNotationUtil.cic_name_of_name name with
269 CicNotationPt.fail loc
270 "Recursive functions cannot be anonymous"
271 | Cic.Name name -> name
273 (name, decr_idx, cic_type, cic_body))
276 let counter = ref ~-1 in
277 let build_term funs =
278 (* this is the body of the fold_right function below. Rationale: Fix
279 * and CoFix cases differs only in an additional index in the
280 * inductiveFun list, see Cic.term *)
283 (fun (var, _, _, _) cic ->
285 let fix = Cic.Fix (!counter,funs) in
287 `Recipe (`AddLetIn cic) ->
288 `Term (Cic.LetIn (Cic.Name var, fix, cic))
289 | `Recipe (`AvoidLetIn l) -> `Term (Cic.Appl (fix::l))
290 | `Recipe `AvoidLetInNoAppl -> `Term fix
291 | `Term t -> `Term (Cic.LetIn (Cic.Name var, fix, t)))
294 List.map (fun (name, _, typ, body) -> (name, typ, body)) funs
296 (fun (var, _, _, _) cic ->
298 let cofix = Cic.CoFix (!counter,funs) in
300 `Recipe (`AddLetIn cic) ->
301 `Term (Cic.LetIn (Cic.Name var, cofix, cic))
302 | `Recipe (`AvoidLetIn l) -> `Term (Cic.Appl (cofix::l))
303 | `Recipe `AvoidLetInNoAppl -> `Term cofix
304 | `Term t -> `Term (Cic.LetIn (Cic.Name var, cofix, t)))
307 List.fold_right (build_term inductiveFuns) inductiveFuns
310 `Recipe _ -> assert false
312 | CicNotationPt.Ident _
313 | CicNotationPt.Uri _ when is_path -> raise PathNotWellFormed
314 | CicNotationPt.Ident (name, subst)
315 | CicNotationPt.Uri (name, subst) as ast ->
316 let is_uri = function CicNotationPt.Uri _ -> true | _ -> false in
318 if is_uri ast then raise Not_found;(* don't search the env for URIs *)
319 let index = find_in_context name context in
320 if subst <> None then
321 CicNotationPt.fail loc "Explicit substitutions not allowed here";
325 if is_uri ast then (* we have the URI, build the term out of it *)
327 CicUtil.term_of_uri (UriManager.uri_of_string name)
328 with UriManager.IllFormedUri _ ->
329 CicNotationPt.fail loc "Ill formed URI"
331 resolve env (Id name) ()
335 List.map (fun uri -> UriManager.name_of_uri uri, uri) uris
342 List.assoc s ids_to_uris, aux ~localize loc context term
344 raise (Invalid_choice (lazy "The provided explicit named substitution is trying to instantiate a named variable the object is not abstracted on"))))
346 | None -> List.map (fun uri -> uri, Cic.Implicit None) uris)
350 | Cic.Const (uri, []) ->
351 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
352 let uris = CicUtil.params_of_obj o in
353 Cic.Const (uri, mk_subst uris)
354 | Cic.Var (uri, []) ->
355 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
356 let uris = CicUtil.params_of_obj o in
357 Cic.Var (uri, mk_subst uris)
358 | Cic.MutInd (uri, i, []) ->
360 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
361 let uris = CicUtil.params_of_obj o in
362 Cic.MutInd (uri, i, mk_subst uris)
364 CicEnvironment.Object_not_found _ ->
365 (* if we are here it is probably the case that during the
366 definition of a mutual inductive type we have met an
367 occurrence of the type in one of its constructors.
368 However, the inductive type is not yet in the environment
370 (*here the explicit_named_substituion is assumed to be of length 0 *)
371 Cic.MutInd (uri,i,[]))
372 | Cic.MutConstruct (uri, i, j, []) ->
373 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
374 let uris = CicUtil.params_of_obj o in
375 Cic.MutConstruct (uri, i, j, mk_subst uris)
376 | Cic.Meta _ | Cic.Implicit _ as t ->
378 debug_print (lazy (sprintf
379 "Warning: %s must be instantiated with _[%s] but we do not enforce it"
383 (fun (s, term) -> s ^ " := " ^ CicNotationPtPp.pp_term term)
388 raise (Invalid_choice (lazy "??? Can this happen?"))
390 CicEnvironment.CircularDependency _ ->
391 raise (Invalid_choice (lazy "Circular dependency in the environment"))))
392 | CicNotationPt.Implicit -> Cic.Implicit None
393 | CicNotationPt.UserInput -> Cic.Implicit (Some `Hole)
394 | CicNotationPt.Num (num, i) -> resolve env (Num i) ~num ()
395 | CicNotationPt.Meta (index, subst) ->
400 | Some term -> Some (aux ~localize loc context term))
403 Cic.Meta (index, cic_subst)
404 | CicNotationPt.Sort `Prop -> Cic.Sort Cic.Prop
405 | CicNotationPt.Sort `Set -> Cic.Sort Cic.Set
406 | CicNotationPt.Sort (`Type u) -> Cic.Sort (Cic.Type u)
407 | CicNotationPt.Sort `CProp -> Cic.Sort Cic.CProp
408 | CicNotationPt.Symbol (symbol, instance) ->
409 resolve env (Symbol (symbol, instance)) ()
410 | _ -> assert false (* god bless Bologna *)
411 and aux_option ~localize loc (context: Cic.name list) annotation = function
412 | None -> Cic.Implicit annotation
413 | Some term -> aux ~localize loc context term
415 aux ~localize:true HExtlib.dummy_floc context ast
417 let interpretate_path ~context path =
418 let localization_tbl = Cic.CicHash.create 23 in
419 (* here we are throwing away useful localization informations!!! *)
421 interpretate_term ~context ~env:Environment.empty ~uri:None ~is_path:true
422 path ~localization_tbl, localization_tbl)
424 let interpretate_obj ~context ~env ~uri ~is_path obj ~localization_tbl =
425 assert (context = []);
426 assert (is_path = false);
427 let interpretate_term = interpretate_term ~localization_tbl in
429 | CicNotationPt.Inductive (params,tyl) ->
430 let uri = match uri with Some uri -> uri | None -> assert false in
434 (fun (context,res) (name,t) ->
435 Cic.Name name :: context,
436 (name, interpretate_term context env None false t)::res
439 context,List.rev res in
442 (fun (name,ty) t -> Cic.Prod (Cic.Name name,ty,t)) params in
446 (*here the explicit_named_substituion is assumed to be of length 0 *)
447 (fun (i,res) (name,_,_,_) ->
448 i + 1,(name,name,Cic.MutInd (uri,i,[]))::res
450 let con_env = DisambiguateTypes.env_of_list name_to_uris env in
453 (fun (name,b,ty,cl) ->
454 let ty' = add_params (interpretate_term context env None false ty) in
459 add_params (interpretate_term context con_env None false ty)
467 Cic.InductiveDefinition (tyl,[],List.length params,[])
468 | CicNotationPt.Record (params,name,ty,fields) ->
469 let uri = match uri with Some uri -> uri | None -> assert false in
473 (fun (context,res) (name,t) ->
474 (Cic.Name name :: context),
475 (name, interpretate_term context env None false t)::res
478 context,List.rev res in
481 (fun (name,ty) t -> Cic.Prod (Cic.Name name,ty,t)) params in
482 let ty' = add_params (interpretate_term context env None false ty) in
486 (fun (context,res) (name,ty,_coercion) ->
487 let context' = Cic.Name name :: context in
488 context',(name,interpretate_term context env None false ty)::res
489 ) (context,[]) fields) in
491 (*here the explicit_named_substituion is assumed to be of length 0 *)
492 let mutind = Cic.MutInd (uri,0,[]) in
493 if params = [] then mutind
496 (mutind::CicUtil.mk_rels (List.length params) (List.length fields)) in
499 (fun t (name,ty) -> Cic.Prod (Cic.Name name,ty,t))
501 let con' = add_params con in
502 let tyl = [name,true,ty',["mk_" ^ name,con']] in
503 let field_names = List.map (fun (x,_,y) -> x,y) fields in
504 Cic.InductiveDefinition
505 (tyl,[],List.length params,[`Class (`Record field_names)])
506 | CicNotationPt.Theorem (flavour, name, ty, bo) ->
507 let attrs = [`Flavour flavour] in
508 let ty' = interpretate_term [] env None false ty in
511 Cic.CurrentProof (name,[],Cic.Implicit None,ty',[],attrs)
513 let bo' = Some (interpretate_term [] env None false bo) in
514 Cic.Constant (name,bo',ty',[],attrs))
517 (* e.g. [5;1;1;1;2;3;4;1;2] -> [2;1;4;3;5] *)
519 let module SortedItem =
521 type t = DisambiguateTypes.domain_item
522 let compare = Pervasives.compare
525 let module Map = Map.Make (SortedItem) in
527 let rev_l = List.rev l in
528 let (members, uniq_rev_l) =
530 (fun (members, rev_l) (loc,elt) ->
532 let locs = Map.find elt members in
533 if List.mem loc locs then
536 Map.add elt (loc::locs) members, rev_l
538 | Not_found -> Map.add elt [loc] members, elt :: rev_l)
539 (Map.empty, []) rev_l
542 (fun e -> try Map.find e members,e with Not_found -> assert false)
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 = HExtlib.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 -> [ loc, 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, _, _), _) :: _ -> [ loc, 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, _) -> [ loc, 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 (* the next line can raise Not_found *)
625 ignore(find_in_context name context);
626 if subst <> None then
627 CicNotationPt.fail loc "Explicit substitutions not allowed here"
632 | None -> [loc, Id name]
635 (fun dom (_, term) ->
636 let dom' = domain_rev_of_term ~loc context term in
638 [loc, Id name] subst))
639 | CicNotationPt.Uri _ -> []
640 | CicNotationPt.Implicit -> []
641 | CicNotationPt.Num (num, i) -> [loc, Num i ]
642 | CicNotationPt.Meta (index, local_context) ->
644 (fun dom term -> domain_rev_of_term_option loc context term @ dom) []
646 | CicNotationPt.Sort _ -> []
647 | CicNotationPt.Symbol (symbol, instance) -> [loc, Symbol (symbol, instance) ]
648 | CicNotationPt.UserInput
649 | CicNotationPt.Literal _
650 | CicNotationPt.Layout _
651 | CicNotationPt.Magic _
652 | CicNotationPt.Variable _ -> assert false
654 and domain_rev_of_term_option loc context = function
656 | Some t -> domain_rev_of_term ~loc context t
658 let domain_of_term ~context ast = rev_uniq (domain_rev_of_term context ast)
660 let domain_of_obj ~context ast =
661 assert (context = []);
664 | CicNotationPt.Theorem (_,_,ty,bo) ->
667 | Some bo -> domain_rev_of_term [] bo) @
668 domain_rev_of_term [] ty
669 | CicNotationPt.Inductive (params,tyl) ->
676 (fun (_,ty) -> domain_rev_of_term [] ty) cl) @
677 domain_rev_of_term [] ty) tyl) in
681 domain_rev_of_term [] ty @ dom
686 not ( List.exists (fun (name',_) -> name = Id name') params
687 || List.exists (fun (name',_,_,_) -> name = Id name') tyl)
689 | CicNotationPt.Record (params,_,ty,fields) ->
692 (List.rev_map (fun (_,ty,_) -> domain_rev_of_term [] ty) fields) in
696 domain_rev_of_term [] ty @ dom
697 ) (dom @ domain_rev_of_term [] ty) params
701 not ( List.exists (fun (name',_) -> name = Id name') params
702 || List.exists (fun (name',_,_) -> name = Id name') fields)
708 let domain_diff dom1 dom2 =
709 (* let domain_diff = Domain.diff *)
711 List.fold_left (fun pred elt -> (fun elt' -> elt' = elt || pred elt'))
712 (fun _ -> false) dom2
714 List.filter (fun (_,elt) -> not (is_in_dom2 elt)) dom1
716 module type Disambiguator =
718 val disambiguate_term :
719 ?fresh_instances:bool ->
721 context:Cic.context ->
722 metasenv:Cic.metasenv ->
723 ?initial_ugraph:CicUniv.universe_graph ->
724 aliases:DisambiguateTypes.environment ->(* previous interpretation status *)
725 universe:DisambiguateTypes.multiple_environment option ->
726 CicNotationPt.term disambiguator_input ->
727 ((DisambiguateTypes.domain_item * DisambiguateTypes.codomain_item) list *
728 Cic.metasenv * (* new metasenv *)
730 CicUniv.universe_graph) list * (* disambiguated term *)
733 val disambiguate_obj :
734 ?fresh_instances:bool ->
736 aliases:DisambiguateTypes.environment ->(* previous interpretation status *)
737 universe:DisambiguateTypes.multiple_environment option ->
738 uri:UriManager.uri option -> (* required only for inductive types *)
739 CicNotationPt.obj disambiguator_input ->
740 ((DisambiguateTypes.domain_item * DisambiguateTypes.codomain_item) list *
741 Cic.metasenv * (* new metasenv *)
743 CicUniv.universe_graph) list * (* disambiguated obj *)
747 module Make (C: Callbacks) =
749 let choices_of_id dbd id =
750 let uris = Whelp.locate ~dbd id in
755 (C.input_or_locate_uri
756 ~title:("URI matching \"" ^ id ^ "\" unknown.") ~id ())
762 C.interactive_user_uri_choice ~selection_mode:`MULTIPLE
763 ~ok:"Try selected." ~enable_button_for_non_vars:true
764 ~title:"Ambiguous input." ~id
765 ~msg: ("Ambiguous input \"" ^ id ^
766 "\". Please, choose one or more interpretations:")
771 (UriManager.string_of_uri uri,
774 CicUtil.term_of_uri uri
776 debug_print (lazy (UriManager.string_of_uri uri));
777 debug_print (lazy (Printexc.to_string exn));
783 let refine_profiler = HExtlib.profile "disambiguate_thing.refine_thing"
785 let disambiguate_thing ~dbd ~context ~metasenv
786 ?(initial_ugraph = CicUniv.empty_ugraph) ~aliases ~universe
787 ~uri ~pp_thing ~domain_of_thing ~interpretate_thing ~refine_thing
788 (thing_txt,thing_txt_prefix_len,thing)
790 debug_print (lazy "DISAMBIGUATE INPUT");
791 let disambiguate_context = (* cic context -> disambiguate context *)
793 (function None -> Cic.Anonymous | Some (name, _) -> name)
796 debug_print (lazy ("TERM IS: " ^ (pp_thing thing)));
797 let thing_dom = domain_of_thing ~context:disambiguate_context thing in
798 debug_print (lazy (sprintf "DISAMBIGUATION DOMAIN: %s"
799 (string_of_domain (List.map snd thing_dom))));
801 debug_print (lazy (sprintf "DISAMBIGUATION ENVIRONMENT: %s"
802 (DisambiguatePp.pp_environment aliases)));
803 debug_print (lazy (sprintf "DISAMBIGUATION UNIVERSE: %s"
804 (match universe with None -> "None" | Some _ -> "Some _")));
807 Environment.fold (fun item _ dom -> item :: dom) aliases []
809 let todo_dom = domain_diff thing_dom current_dom in
810 (* (2) lookup function for any item (Id/Symbol/Num) *)
814 let lookup_in_library () =
816 | Id id -> choices_of_id dbd id
817 | Symbol (symb, _) ->
818 List.map DisambiguateChoices.mk_choice
819 (TermAcicContent.lookup_interpretations symb)
821 DisambiguateChoices.lookup_num_choices ()
824 | None -> lookup_in_library ()
829 | Symbol (symb, _) -> Symbol (symb, 0)
832 Environment.find item e
833 with Not_found -> [])
840 if benchmark then begin
841 let per_item_choices =
845 let len = List.length (lookup_choices dom_item) in
846 debug_print (lazy (sprintf "BENCHMARK %s: %d"
847 (string_of_domain_item dom_item) len));
849 with No_choices _ -> 0)
852 max_refinements := List.fold_left ( * ) 1 per_item_choices;
853 actual_refinements := 0;
854 domain_size := List.length thing_dom;
856 (float_of_int !max_refinements) ** (1. /. float_of_int !domain_size)
862 (* (3) test an interpretation filling with meta uninterpreted identifiers
864 let test_env aliases todo_dom ugraph =
871 | Id _ | Num _ -> (fun _ _ _ -> Cic.Implicit (Some `Closed))
872 | Symbol _ -> (fun _ _ _ -> Cic.Implicit None))) env)
876 let localization_tbl = Cic.CicHash.create 503 in
878 interpretate_thing ~context:disambiguate_context ~env:filled_env
879 ~uri ~is_path:false thing ~localization_tbl
883 refine_thing metasenv context uri cic_thing ugraph ~localization_tbl
886 in refine_profiler.HExtlib.profile foo ()
888 | Try_again msg -> Uncertain (None,msg), ugraph
889 | Invalid_choice msg -> Ko (None,msg), ugraph
891 (* (4) build all possible interpretations *)
892 let (@@) (l1,l2) (l1',l2') = l1@l1', l2@l2' in
893 let rec aux aliases diff lookup_in_todo_dom todo_dom base_univ =
896 assert (lookup_in_todo_dom = None);
897 (match test_env aliases [] base_univ with
898 | Ok (thing, metasenv),new_univ ->
899 [ aliases, diff, metasenv, thing, new_univ ], []
900 | Ko (loc,msg),_ | Uncertain (loc,msg),_ -> [],[loc,msg])
901 | (locs,item) :: remaining_dom ->
902 debug_print (lazy (sprintf "CHOOSED ITEM: %s"
903 (string_of_domain_item item)));
905 match lookup_in_todo_dom with
906 None -> lookup_choices item
907 | Some choices -> choices in
910 [], [Some (List.hd locs),
911 lazy ("No choices for " ^ string_of_domain_item item)]
913 (* just one choice. We perform a one-step look-up and
914 if the next set of choices is also a singleton we
915 skip this refinement step *)
916 debug_print(lazy (sprintf "%s CHOSEN" (fst codomain_item)));
917 let new_env = Environment.add item codomain_item aliases in
918 let new_diff = (item,codomain_item)::diff in
919 let lookup_in_todo_dom,next_choice_is_single =
920 match remaining_dom with
923 let choices = lookup_choices he in
924 Some choices,List.length choices = 1
926 if next_choice_is_single then
927 aux new_env new_diff lookup_in_todo_dom remaining_dom
930 (match test_env new_env remaining_dom base_univ with
931 | Ok (thing, metasenv),new_univ ->
932 (match remaining_dom with
934 [ new_env, new_diff, metasenv, thing, new_univ ], []
936 aux new_env new_diff lookup_in_todo_dom
937 remaining_dom new_univ)
938 | Uncertain (loc,msg),new_univ ->
939 (match remaining_dom with
940 | [] -> [], [loc,msg]
942 aux new_env new_diff lookup_in_todo_dom
943 remaining_dom new_univ)
944 | Ko (loc,msg),_ -> [], [loc,msg])
946 let rec filter univ = function
948 | codomain_item :: tl ->
949 debug_print(lazy (sprintf "%s CHOSEN" (fst codomain_item)));
950 let new_env = Environment.add item codomain_item aliases in
951 let new_diff = (item,codomain_item)::diff in
952 (match test_env new_env remaining_dom univ with
953 | Ok (thing, metasenv),new_univ ->
954 (match remaining_dom with
955 | [] -> [ new_env, new_diff, metasenv, thing, new_univ ], []
956 | _ -> aux new_env new_diff None remaining_dom new_univ
959 | Uncertain (loc,msg),new_univ ->
960 (match remaining_dom with
962 | _ -> aux new_env new_diff None remaining_dom new_univ
965 | Ko (loc,msg),_ -> ([],[loc,msg]) @@ filter univ tl)
967 filter base_univ choices
969 let base_univ = initial_ugraph in
972 match aux aliases [] None todo_dom base_univ with
973 | [],errors -> raise (NoWellTypedInterpretation (0,errors))
974 | [_,diff,metasenv,t,ugraph],_ ->
975 debug_print (lazy "SINGLE INTERPRETATION");
976 [diff,metasenv,t,ugraph], false
979 (lazy (sprintf "MANY INTERPRETATIONS (%d)" (List.length l)));
982 (fun (env, _, _, _, _) ->
984 (fun (locs,domain_item) ->
986 fst (Environment.find domain_item env)
988 locs,descr_of_domain_item domain_item, description)
993 C.interactive_interpretation_choice
994 thing_txt thing_txt_prefix_len choices
996 (List.map (fun n->let _,d,m,t,u= List.nth l n in d,m,t,u) choosed),
1001 CicEnvironment.CircularDependency s ->
1002 failwith "Disambiguate: circular dependency"
1004 let disambiguate_term ?(fresh_instances=false) ~dbd ~context ~metasenv
1005 ?(initial_ugraph = CicUniv.empty_ugraph) ~aliases ~universe
1006 (text,prefix_len,term)
1009 if fresh_instances then CicNotationUtil.freshen_term term else term
1011 disambiguate_thing ~dbd ~context ~metasenv ~initial_ugraph ~aliases
1012 ~universe ~uri:None ~pp_thing:CicNotationPp.pp_term
1013 ~domain_of_thing:domain_of_term ~interpretate_thing:interpretate_term
1014 ~refine_thing:refine_term (text,prefix_len,term)
1016 let disambiguate_obj ?(fresh_instances=false) ~dbd ~aliases ~universe ~uri
1017 (text,prefix_len,obj)
1020 if fresh_instances then CicNotationUtil.freshen_obj obj else obj
1022 disambiguate_thing ~dbd ~context:[] ~metasenv:[] ~aliases ~universe ~uri
1023 ~pp_thing:CicNotationPp.pp_obj ~domain_of_thing:domain_of_obj
1024 ~interpretate_thing:interpretate_obj ~refine_thing:refine_obj
1025 (text,prefix_len,obj)