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,arity) ->
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,z) -> x,y,z) 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
509 (match bo,flavour with
511 Cic.Constant (name,None,ty',[],attrs)
512 | Some bo,`Axiom -> assert false
514 Cic.CurrentProof (name,[],Cic.Implicit None,ty',[],attrs)
516 let bo' = Some (interpretate_term [] env None false bo) in
517 Cic.Constant (name,bo',ty',[],attrs))
520 (* e.g. [5;1;1;1;2;3;4;1;2] -> [2;1;4;3;5] *)
522 let module SortedItem =
524 type t = DisambiguateTypes.domain_item
525 let compare = Pervasives.compare
528 let module Map = Map.Make (SortedItem) in
530 let rev_l = List.rev l in
531 let (members, uniq_rev_l) =
533 (fun (members, rev_l) (loc,elt) ->
535 let locs = Map.find elt members in
536 if List.mem loc locs then
539 Map.add elt (loc::locs) members, rev_l
541 | Not_found -> Map.add elt [loc] members, elt :: rev_l)
542 (Map.empty, []) rev_l
545 (fun e -> try Map.find e members,e with Not_found -> assert false)
548 (* "aux" keeps domain in reverse order and doesn't care about duplicates.
549 * Domain item more in deep in the list will be processed first.
551 let rec domain_rev_of_term ?(loc = HExtlib.dummy_floc) context = function
552 | CicNotationPt.AttributedTerm (`Loc loc, term) ->
553 domain_rev_of_term ~loc context term
554 | CicNotationPt.AttributedTerm (_, term) ->
555 domain_rev_of_term ~loc context term
556 | CicNotationPt.Appl terms ->
558 (fun dom term -> domain_rev_of_term ~loc context term @ dom) [] terms
559 | CicNotationPt.Binder (kind, (var, typ), body) ->
562 | `Exists -> [ loc, Symbol ("exists", 0) ]
565 let type_dom = domain_rev_of_term_option loc context typ in
567 domain_rev_of_term ~loc
568 (CicNotationUtil.cic_name_of_name var :: context) body
570 body_dom @ type_dom @ kind_dom
571 | CicNotationPt.Case (term, indty_ident, outtype, branches) ->
572 let term_dom = domain_rev_of_term ~loc context term in
573 let outtype_dom = domain_rev_of_term_option loc context outtype in
574 let get_first_constructor = function
576 | ((head, _, _), _) :: _ -> [ loc, Id head ]
578 let do_branch ((head, _, args), term) =
579 let (term_context, args_domain) =
581 (fun (cont, dom) (name, typ) ->
582 (CicNotationUtil.cic_name_of_name name :: cont,
585 | Some typ -> domain_rev_of_term ~loc cont typ @ dom)))
588 args_domain @ domain_rev_of_term ~loc term_context term
591 List.fold_left (fun dom branch -> do_branch branch @ dom) [] branches
593 branches_dom @ outtype_dom @ term_dom @
594 (match indty_ident with
595 | None -> get_first_constructor branches
596 | Some (ident, _) -> [ loc, Id ident ])
597 | CicNotationPt.Cast (term, ty) ->
598 let term_dom = domain_rev_of_term ~loc context term in
599 let ty_dom = domain_rev_of_term ~loc context ty in
601 | CicNotationPt.LetIn ((var, typ), body, where) ->
602 let body_dom = domain_rev_of_term ~loc context body in
603 let type_dom = domain_rev_of_term_option loc context typ in
605 domain_rev_of_term ~loc
606 (CicNotationUtil.cic_name_of_name var :: context) where
608 where_dom @ type_dom @ body_dom
609 | CicNotationPt.LetRec (kind, defs, where) ->
612 (fun acc ((var, typ), _, _) ->
613 CicNotationUtil.cic_name_of_name var :: acc)
616 let where_dom = domain_rev_of_term ~loc context' where in
619 (fun dom ((_, typ), body, _) ->
620 domain_rev_of_term ~loc context' body @
621 domain_rev_of_term_option loc context typ)
625 | CicNotationPt.Ident (name, subst) ->
627 (* the next line can raise Not_found *)
628 ignore(find_in_context name context);
629 if subst <> None then
630 CicNotationPt.fail loc "Explicit substitutions not allowed here"
635 | None -> [loc, Id name]
638 (fun dom (_, term) ->
639 let dom' = domain_rev_of_term ~loc context term in
641 [loc, Id name] subst))
642 | CicNotationPt.Uri _ -> []
643 | CicNotationPt.Implicit -> []
644 | CicNotationPt.Num (num, i) -> [loc, Num i ]
645 | CicNotationPt.Meta (index, local_context) ->
647 (fun dom term -> domain_rev_of_term_option loc context term @ dom) []
649 | CicNotationPt.Sort _ -> []
650 | CicNotationPt.Symbol (symbol, instance) -> [loc, Symbol (symbol, instance) ]
651 | CicNotationPt.UserInput
652 | CicNotationPt.Literal _
653 | CicNotationPt.Layout _
654 | CicNotationPt.Magic _
655 | CicNotationPt.Variable _ -> assert false
657 and domain_rev_of_term_option loc context = function
659 | Some t -> domain_rev_of_term ~loc context t
661 let domain_of_term ~context ast = rev_uniq (domain_rev_of_term context ast)
663 let domain_of_obj ~context ast =
664 assert (context = []);
667 | CicNotationPt.Theorem (_,_,ty,bo) ->
670 | Some bo -> domain_rev_of_term [] bo) @
671 domain_rev_of_term [] ty
672 | CicNotationPt.Inductive (params,tyl) ->
679 (fun (_,ty) -> domain_rev_of_term [] ty) cl) @
680 domain_rev_of_term [] ty) tyl) in
684 domain_rev_of_term [] ty @ dom
689 not ( List.exists (fun (name',_) -> name = Id name') params
690 || List.exists (fun (name',_,_,_) -> name = Id name') tyl)
692 | CicNotationPt.Record (params,_,ty,fields) ->
695 (List.rev_map (fun (_,ty,_,_) -> domain_rev_of_term [] ty) fields) in
699 domain_rev_of_term [] ty @ dom
700 ) (dom @ domain_rev_of_term [] ty) params
704 not ( List.exists (fun (name',_) -> name = Id name') params
705 || List.exists (fun (name',_,_,_) -> name = Id name') fields)
711 let domain_diff dom1 dom2 =
712 (* let domain_diff = Domain.diff *)
716 | Symbol (symb, 0) ->
718 Symbol (symb',_) when symb = symb' -> true
727 List.filter (fun (_,elt) -> not (is_in_dom2 elt)) dom1
729 module type Disambiguator =
731 val disambiguate_term :
732 ?fresh_instances:bool ->
734 context:Cic.context ->
735 metasenv:Cic.metasenv ->
736 ?initial_ugraph:CicUniv.universe_graph ->
737 aliases:DisambiguateTypes.environment ->(* previous interpretation status *)
738 universe:DisambiguateTypes.multiple_environment option ->
739 CicNotationPt.term disambiguator_input ->
740 ((DisambiguateTypes.domain_item * DisambiguateTypes.codomain_item) list *
741 Cic.metasenv * (* new metasenv *)
743 CicUniv.universe_graph) list * (* disambiguated term *)
746 val disambiguate_obj :
747 ?fresh_instances:bool ->
749 aliases:DisambiguateTypes.environment ->(* previous interpretation status *)
750 universe:DisambiguateTypes.multiple_environment option ->
751 uri:UriManager.uri option -> (* required only for inductive types *)
752 CicNotationPt.obj disambiguator_input ->
753 ((DisambiguateTypes.domain_item * DisambiguateTypes.codomain_item) list *
754 Cic.metasenv * (* new metasenv *)
756 CicUniv.universe_graph) list * (* disambiguated obj *)
760 module Make (C: Callbacks) =
762 let choices_of_id dbd id =
763 let uris = Whelp.locate ~dbd id in
768 (C.input_or_locate_uri
769 ~title:("URI matching \"" ^ id ^ "\" unknown.") ~id ())
775 C.interactive_user_uri_choice ~selection_mode:`MULTIPLE
776 ~ok:"Try selected." ~enable_button_for_non_vars:true
777 ~title:"Ambiguous input." ~id
778 ~msg: ("Ambiguous input \"" ^ id ^
779 "\". Please, choose one or more interpretations:")
784 (UriManager.string_of_uri uri,
787 CicUtil.term_of_uri uri
789 debug_print (lazy (UriManager.string_of_uri uri));
790 debug_print (lazy (Printexc.to_string exn));
796 let refine_profiler = HExtlib.profile "disambiguate_thing.refine_thing"
798 let disambiguate_thing ~dbd ~context ~metasenv
799 ?(initial_ugraph = CicUniv.empty_ugraph) ~aliases ~universe
800 ~uri ~pp_thing ~domain_of_thing ~interpretate_thing ~refine_thing
801 (thing_txt,thing_txt_prefix_len,thing)
803 debug_print (lazy "DISAMBIGUATE INPUT");
804 let disambiguate_context = (* cic context -> disambiguate context *)
806 (function None -> Cic.Anonymous | Some (name, _) -> name)
809 debug_print (lazy ("TERM IS: " ^ (pp_thing thing)));
810 let thing_dom = domain_of_thing ~context:disambiguate_context thing in
811 debug_print (lazy (sprintf "DISAMBIGUATION DOMAIN: %s"
812 (string_of_domain (List.map snd thing_dom))));
814 debug_print (lazy (sprintf "DISAMBIGUATION ENVIRONMENT: %s"
815 (DisambiguatePp.pp_environment aliases)));
816 debug_print (lazy (sprintf "DISAMBIGUATION UNIVERSE: %s"
817 (match universe with None -> "None" | Some _ -> "Some _")));
820 Environment.fold (fun item _ dom -> item :: dom) aliases []
822 let todo_dom = domain_diff thing_dom current_dom in
823 (* (2) lookup function for any item (Id/Symbol/Num) *)
827 let lookup_in_library () =
829 | Id id -> choices_of_id dbd id
830 | Symbol (symb, _) ->
831 List.map DisambiguateChoices.mk_choice
832 (TermAcicContent.lookup_interpretations symb)
834 DisambiguateChoices.lookup_num_choices ()
837 | None -> lookup_in_library ()
842 | Symbol (symb, _) -> Symbol (symb, 0)
845 Environment.find item e
846 with Not_found -> lookup_in_library ())
853 if benchmark then begin
854 let per_item_choices =
858 let len = List.length (lookup_choices dom_item) in
859 debug_print (lazy (sprintf "BENCHMARK %s: %d"
860 (string_of_domain_item dom_item) len));
862 with No_choices _ -> 0)
865 max_refinements := List.fold_left ( * ) 1 per_item_choices;
866 actual_refinements := 0;
867 domain_size := List.length thing_dom;
869 (float_of_int !max_refinements) ** (1. /. float_of_int !domain_size)
875 (* (3) test an interpretation filling with meta uninterpreted identifiers
877 let test_env aliases todo_dom ugraph =
884 | Id _ | Num _ -> (fun _ _ _ -> Cic.Implicit (Some `Closed))
885 | Symbol _ -> (fun _ _ _ -> Cic.Implicit None))) env)
889 let localization_tbl = Cic.CicHash.create 503 in
891 interpretate_thing ~context:disambiguate_context ~env:filled_env
892 ~uri ~is_path:false thing ~localization_tbl
896 refine_thing metasenv context uri cic_thing ugraph ~localization_tbl
899 in refine_profiler.HExtlib.profile foo ()
901 | Try_again msg -> Uncertain (None,msg), ugraph
902 | Invalid_choice msg -> Ko (None,msg), ugraph
904 (* (4) build all possible interpretations *)
905 let (@@) (l1,l2) (l1',l2') = l1@l1', l2@l2' in
906 let rec aux aliases diff lookup_in_todo_dom todo_dom base_univ =
909 assert (lookup_in_todo_dom = None);
910 (match test_env aliases [] base_univ with
911 | Ok (thing, metasenv),new_univ ->
912 [ aliases, diff, metasenv, thing, new_univ ], []
913 | Ko (loc,msg),_ | Uncertain (loc,msg),_ -> [],[loc,msg])
914 | (locs,item) :: remaining_dom ->
915 debug_print (lazy (sprintf "CHOOSED ITEM: %s"
916 (string_of_domain_item item)));
918 match lookup_in_todo_dom with
919 None -> lookup_choices item
920 | Some choices -> choices in
923 [], [Some (List.hd locs),
924 lazy ("No choices for " ^ string_of_domain_item item)]
926 (* just one choice. We perform a one-step look-up and
927 if the next set of choices is also a singleton we
928 skip this refinement step *)
929 debug_print(lazy (sprintf "%s CHOSEN" (fst codomain_item)));
930 let new_env = Environment.add item codomain_item aliases in
931 let new_diff = (item,codomain_item)::diff in
932 let lookup_in_todo_dom,next_choice_is_single =
933 match remaining_dom with
936 let choices = lookup_choices he in
937 Some choices,List.length choices = 1
939 if next_choice_is_single then
940 aux new_env new_diff lookup_in_todo_dom remaining_dom
943 (match test_env new_env remaining_dom base_univ with
944 | Ok (thing, metasenv),new_univ ->
945 (match remaining_dom with
947 [ new_env, new_diff, metasenv, thing, new_univ ], []
949 aux new_env new_diff lookup_in_todo_dom
950 remaining_dom new_univ)
951 | Uncertain (loc,msg),new_univ ->
952 (match remaining_dom with
953 | [] -> [], [loc,msg]
955 aux new_env new_diff lookup_in_todo_dom
956 remaining_dom new_univ)
957 | Ko (loc,msg),_ -> [], [loc,msg])
959 let rec filter univ = function
961 | codomain_item :: tl ->
962 debug_print(lazy (sprintf "%s CHOSEN" (fst codomain_item)));
963 let new_env = Environment.add item codomain_item aliases in
964 let new_diff = (item,codomain_item)::diff in
965 (match test_env new_env remaining_dom univ with
966 | Ok (thing, metasenv),new_univ ->
967 (match remaining_dom with
968 | [] -> [ new_env, new_diff, metasenv, thing, new_univ ], []
969 | _ -> aux new_env new_diff None remaining_dom new_univ
972 | Uncertain (loc,msg),new_univ ->
973 (match remaining_dom with
975 | _ -> aux new_env new_diff None remaining_dom new_univ
978 | Ko (loc,msg),_ -> ([],[loc,msg]) @@ filter univ tl)
980 filter base_univ choices
982 let base_univ = initial_ugraph in
985 match aux aliases [] None todo_dom base_univ with
986 | [],errors -> raise (NoWellTypedInterpretation (0,errors))
987 | [_,diff,metasenv,t,ugraph],_ ->
988 debug_print (lazy "SINGLE INTERPRETATION");
989 [diff,metasenv,t,ugraph], false
992 (lazy (sprintf "MANY INTERPRETATIONS (%d)" (List.length l)));
995 (fun (env, _, _, _, _) ->
997 (fun (locs,domain_item) ->
999 fst (Environment.find domain_item env)
1001 locs,descr_of_domain_item domain_item, description)
1006 C.interactive_interpretation_choice
1007 thing_txt thing_txt_prefix_len choices
1009 (List.map (fun n->let _,d,m,t,u= List.nth l n in d,m,t,u) choosed),
1014 CicEnvironment.CircularDependency s ->
1015 failwith "Disambiguate: circular dependency"
1017 let disambiguate_term ?(fresh_instances=false) ~dbd ~context ~metasenv
1018 ?(initial_ugraph = CicUniv.empty_ugraph) ~aliases ~universe
1019 (text,prefix_len,term)
1022 if fresh_instances then CicNotationUtil.freshen_term term else term
1024 disambiguate_thing ~dbd ~context ~metasenv ~initial_ugraph ~aliases
1025 ~universe ~uri:None ~pp_thing:CicNotationPp.pp_term
1026 ~domain_of_thing:domain_of_term ~interpretate_thing:interpretate_term
1027 ~refine_thing:refine_term (text,prefix_len,term)
1029 let disambiguate_obj ?(fresh_instances=false) ~dbd ~aliases ~universe ~uri
1030 (text,prefix_len,obj)
1033 if fresh_instances then CicNotationUtil.freshen_obj obj else obj
1035 disambiguate_thing ~dbd ~context:[] ~metasenv:[] ~aliases ~universe ~uri
1036 ~pp_thing:CicNotationPp.pp_obj ~domain_of_thing:domain_of_obj
1037 ~interpretate_thing:interpretate_obj ~refine_thing:refine_obj
1038 (text,prefix_len,obj)