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 * ((DisambiguateTypes.domain_item * DisambiguateTypes.codomain_item) list * 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 (params, (name, typ), body, decr_idx) ->
263 let add_binders kind t =
265 (fun var t -> CicNotationPt.Binder (kind, var, t)) params t
268 aux ~localize loc context' (add_binders `Lambda body) in
270 aux_option ~localize loc context (Some `Type)
271 (HExtlib.map_option (add_binders `Pi) typ) in
273 match CicNotationUtil.cic_name_of_name name with
275 CicNotationPt.fail loc
276 "Recursive functions cannot be anonymous"
277 | Cic.Name name -> name
279 (name, decr_idx, cic_type, cic_body))
282 let counter = ref ~-1 in
283 let build_term funs =
284 (* this is the body of the fold_right function below. Rationale: Fix
285 * and CoFix cases differs only in an additional index in the
286 * inductiveFun list, see Cic.term *)
289 (fun (var, _, _, _) cic ->
291 let fix = Cic.Fix (!counter,funs) in
293 `Recipe (`AddLetIn cic) ->
294 `Term (Cic.LetIn (Cic.Name var, fix, cic))
295 | `Recipe (`AvoidLetIn l) -> `Term (Cic.Appl (fix::l))
296 | `Recipe `AvoidLetInNoAppl -> `Term fix
297 | `Term t -> `Term (Cic.LetIn (Cic.Name var, fix, t)))
300 List.map (fun (name, _, typ, body) -> (name, typ, body)) funs
302 (fun (var, _, _, _) cic ->
304 let cofix = Cic.CoFix (!counter,funs) in
306 `Recipe (`AddLetIn cic) ->
307 `Term (Cic.LetIn (Cic.Name var, cofix, cic))
308 | `Recipe (`AvoidLetIn l) -> `Term (Cic.Appl (cofix::l))
309 | `Recipe `AvoidLetInNoAppl -> `Term cofix
310 | `Term t -> `Term (Cic.LetIn (Cic.Name var, cofix, t)))
313 List.fold_right (build_term inductiveFuns) inductiveFuns
316 `Recipe _ -> assert false
318 | CicNotationPt.Ident _
319 | CicNotationPt.Uri _ when is_path -> raise PathNotWellFormed
320 | CicNotationPt.Ident (name, subst)
321 | CicNotationPt.Uri (name, subst) as ast ->
322 let is_uri = function CicNotationPt.Uri _ -> true | _ -> false in
324 if is_uri ast then raise Not_found;(* don't search the env for URIs *)
325 let index = find_in_context name context in
326 if subst <> None then
327 CicNotationPt.fail loc "Explicit substitutions not allowed here";
331 if is_uri ast then (* we have the URI, build the term out of it *)
333 CicUtil.term_of_uri (UriManager.uri_of_string name)
334 with UriManager.IllFormedUri _ ->
335 CicNotationPt.fail loc "Ill formed URI"
337 resolve env (Id name) ()
341 List.map (fun uri -> UriManager.name_of_uri uri, uri) uris
348 List.assoc s ids_to_uris, aux ~localize loc context term
350 raise (Invalid_choice (lazy "The provided explicit named substitution is trying to instantiate a named variable the object is not abstracted on"))))
352 | None -> List.map (fun uri -> uri, Cic.Implicit None) uris)
356 | Cic.Const (uri, []) ->
357 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
358 let uris = CicUtil.params_of_obj o in
359 Cic.Const (uri, mk_subst uris)
360 | Cic.Var (uri, []) ->
361 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
362 let uris = CicUtil.params_of_obj o in
363 Cic.Var (uri, mk_subst uris)
364 | Cic.MutInd (uri, i, []) ->
366 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
367 let uris = CicUtil.params_of_obj o in
368 Cic.MutInd (uri, i, mk_subst uris)
370 CicEnvironment.Object_not_found _ ->
371 (* if we are here it is probably the case that during the
372 definition of a mutual inductive type we have met an
373 occurrence of the type in one of its constructors.
374 However, the inductive type is not yet in the environment
376 (*here the explicit_named_substituion is assumed to be of length 0 *)
377 Cic.MutInd (uri,i,[]))
378 | Cic.MutConstruct (uri, i, j, []) ->
379 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
380 let uris = CicUtil.params_of_obj o in
381 Cic.MutConstruct (uri, i, j, mk_subst uris)
382 | Cic.Meta _ | Cic.Implicit _ as t ->
384 debug_print (lazy (sprintf
385 "Warning: %s must be instantiated with _[%s] but we do not enforce it"
389 (fun (s, term) -> s ^ " := " ^ CicNotationPtPp.pp_term term)
394 raise (Invalid_choice (lazy "??? Can this happen?"))
396 CicEnvironment.CircularDependency _ ->
397 raise (Invalid_choice (lazy "Circular dependency in the environment"))))
398 | CicNotationPt.Implicit -> Cic.Implicit None
399 | CicNotationPt.UserInput -> Cic.Implicit (Some `Hole)
400 | CicNotationPt.Num (num, i) -> resolve env (Num i) ~num ()
401 | CicNotationPt.Meta (index, subst) ->
406 | Some term -> Some (aux ~localize loc context term))
409 Cic.Meta (index, cic_subst)
410 | CicNotationPt.Sort `Prop -> Cic.Sort Cic.Prop
411 | CicNotationPt.Sort `Set -> Cic.Sort Cic.Set
412 | CicNotationPt.Sort (`Type u) -> Cic.Sort (Cic.Type u)
413 | CicNotationPt.Sort `CProp -> Cic.Sort Cic.CProp
414 | CicNotationPt.Symbol (symbol, instance) ->
415 resolve env (Symbol (symbol, instance)) ()
416 | _ -> assert false (* god bless Bologna *)
417 and aux_option ~localize loc (context: Cic.name list) annotation = function
418 | None -> Cic.Implicit annotation
419 | Some term -> aux ~localize loc context term
421 aux ~localize:true HExtlib.dummy_floc context ast
423 let interpretate_path ~context path =
424 let localization_tbl = Cic.CicHash.create 23 in
425 (* here we are throwing away useful localization informations!!! *)
427 interpretate_term ~context ~env:Environment.empty ~uri:None ~is_path:true
428 path ~localization_tbl, localization_tbl)
430 let interpretate_obj ~context ~env ~uri ~is_path obj ~localization_tbl =
431 assert (context = []);
432 assert (is_path = false);
433 let interpretate_term = interpretate_term ~localization_tbl in
435 | CicNotationPt.Inductive (params,tyl) ->
436 let uri = match uri with Some uri -> uri | None -> assert false in
440 (fun (context,res) (name,t) ->
443 None -> CicNotationPt.Implicit
445 let name = CicNotationUtil.cic_name_of_name name in
446 name::context,(name, interpretate_term context env None false t)::res
449 context,List.rev res in
451 List.fold_right (fun (name,ty) t -> Cic.Prod (name,ty,t)) params in
455 (*here the explicit_named_substituion is assumed to be of length 0 *)
456 (fun (i,res) (name,_,_,_) ->
457 i + 1,(name,name,Cic.MutInd (uri,i,[]))::res
459 let con_env = DisambiguateTypes.env_of_list name_to_uris env in
462 (fun (name,b,ty,cl) ->
463 let ty' = add_params (interpretate_term context env None false ty) in
468 add_params (interpretate_term context con_env None false ty)
476 Cic.InductiveDefinition (tyl,[],List.length params,[])
477 | CicNotationPt.Record (params,name,ty,fields) ->
478 let uri = match uri with Some uri -> uri | None -> assert false in
482 (fun (context,res) (name,t) ->
485 None -> CicNotationPt.Implicit
487 let name = CicNotationUtil.cic_name_of_name name in
488 name::context,(name, interpretate_term context env None false t)::res
491 context,List.rev res in
494 (fun (name,ty) t -> Cic.Prod (name,ty,t)) params in
495 let ty' = add_params (interpretate_term context env None false ty) in
499 (fun (context,res) (name,ty,_coercion,arity) ->
500 let context' = Cic.Name name :: context in
501 context',(name,interpretate_term context env None false ty)::res
502 ) (context,[]) fields) in
504 (*here the explicit_named_substituion is assumed to be of length 0 *)
505 let mutind = Cic.MutInd (uri,0,[]) in
506 if params = [] then mutind
509 (mutind::CicUtil.mk_rels (List.length params) (List.length fields)) in
512 (fun t (name,ty) -> Cic.Prod (Cic.Name name,ty,t))
514 let con' = add_params con in
515 let tyl = [name,true,ty',["mk_" ^ name,con']] in
516 let field_names = List.map (fun (x,_,y,z) -> x,y,z) fields in
517 Cic.InductiveDefinition
518 (tyl,[],List.length params,[`Class (`Record field_names)])
519 | CicNotationPt.Theorem (flavour, name, ty, bo) ->
520 let attrs = [`Flavour flavour] in
521 let ty' = interpretate_term [] env None false ty in
522 (match bo,flavour with
524 Cic.Constant (name,None,ty',[],attrs)
525 | Some bo,`Axiom -> assert false
527 Cic.CurrentProof (name,[],Cic.Implicit None,ty',[],attrs)
529 let bo' = Some (interpretate_term [] env None false bo) in
530 Cic.Constant (name,bo',ty',[],attrs))
533 (* e.g. [5;1;1;1;2;3;4;1;2] -> [2;1;4;3;5] *)
535 let module SortedItem =
537 type t = DisambiguateTypes.domain_item
538 let compare = Pervasives.compare
541 let module Map = Map.Make (SortedItem) in
543 let rev_l = List.rev l in
544 let (members, uniq_rev_l) =
546 (fun (members, rev_l) (loc,elt) ->
548 let locs = Map.find elt members in
549 if List.mem loc locs then
552 Map.add elt (loc::locs) members, rev_l
554 | Not_found -> Map.add elt [loc] members, elt :: rev_l)
555 (Map.empty, []) rev_l
558 (fun e -> try Map.find e members,e with Not_found -> assert false)
561 (* "aux" keeps domain in reverse order and doesn't care about duplicates.
562 * Domain item more in deep in the list will be processed first.
564 let rec domain_rev_of_term ?(loc = HExtlib.dummy_floc) context = function
565 | CicNotationPt.AttributedTerm (`Loc loc, term) ->
566 domain_rev_of_term ~loc context term
567 | CicNotationPt.AttributedTerm (_, term) ->
568 domain_rev_of_term ~loc context term
569 | CicNotationPt.Appl terms ->
571 (fun dom term -> domain_rev_of_term ~loc context term @ dom) [] terms
572 | CicNotationPt.Binder (kind, (var, typ), body) ->
575 | `Exists -> [ loc, Symbol ("exists", 0) ]
578 let type_dom = domain_rev_of_term_option ~loc context typ in
580 domain_rev_of_term ~loc
581 (CicNotationUtil.cic_name_of_name var :: context) body
583 body_dom @ type_dom @ kind_dom
584 | CicNotationPt.Case (term, indty_ident, outtype, branches) ->
585 let term_dom = domain_rev_of_term ~loc context term in
586 let outtype_dom = domain_rev_of_term_option loc context outtype in
587 let get_first_constructor = function
589 | ((head, _, _), _) :: _ -> [ loc, Id head ]
591 let do_branch ((head, _, args), term) =
592 let (term_context, args_domain) =
594 (fun (cont, dom) (name, typ) ->
595 (CicNotationUtil.cic_name_of_name name :: cont,
598 | Some typ -> domain_rev_of_term ~loc cont typ @ dom)))
601 args_domain @ domain_rev_of_term ~loc term_context term
604 List.fold_left (fun dom branch -> do_branch branch @ dom) [] branches
606 branches_dom @ outtype_dom @ term_dom @
607 (match indty_ident with
608 | None -> get_first_constructor branches
609 | Some (ident, _) -> [ loc, Id ident ])
610 | CicNotationPt.Cast (term, ty) ->
611 let term_dom = domain_rev_of_term ~loc context term in
612 let ty_dom = domain_rev_of_term ~loc context ty in
614 | CicNotationPt.LetIn ((var, typ), body, where) ->
615 let body_dom = domain_rev_of_term ~loc context body in
616 let type_dom = domain_rev_of_term_option loc context typ in
618 domain_rev_of_term ~loc
619 (CicNotationUtil.cic_name_of_name var :: context) where
621 where_dom @ type_dom @ body_dom
622 | CicNotationPt.LetRec (kind, defs, where) ->
623 let add_defs context =
625 (fun acc (_, (var, _), _, _) ->
626 CicNotationUtil.cic_name_of_name var :: acc
628 let where_dom = domain_rev_of_term ~loc (add_defs context) where in
631 (fun dom (params, (_, typ), body, _) ->
635 (fun acc (var,_) -> CicNotationUtil.cic_name_of_name var :: acc)
638 domain_rev_of_term ~loc context' body @
639 domain_rev_of_term_option ~loc context typ @
643 (fun (context,res) (var,ty) ->
644 CicNotationUtil.cic_name_of_name var :: context,
645 res @ domain_rev_of_term_option ~loc context ty)
646 (add_defs context,[]) params))
650 | CicNotationPt.Ident (name, subst) ->
652 (* the next line can raise Not_found *)
653 ignore(find_in_context name context);
654 if subst <> None then
655 CicNotationPt.fail loc "Explicit substitutions not allowed here"
660 | None -> [loc, Id name]
663 (fun dom (_, term) ->
664 let dom' = domain_rev_of_term ~loc context term in
666 [loc, Id name] subst))
667 | CicNotationPt.Uri _ -> []
668 | CicNotationPt.Implicit -> []
669 | CicNotationPt.Num (num, i) -> [loc, Num i ]
670 | CicNotationPt.Meta (index, local_context) ->
672 (fun dom term -> domain_rev_of_term_option loc context term @ dom) []
674 | CicNotationPt.Sort _ -> []
675 | CicNotationPt.Symbol (symbol, instance) -> [loc, Symbol (symbol, instance) ]
676 | CicNotationPt.UserInput
677 | CicNotationPt.Literal _
678 | CicNotationPt.Layout _
679 | CicNotationPt.Magic _
680 | CicNotationPt.Variable _ -> assert false
682 and domain_rev_of_term_option ~loc context = function
684 | Some t -> domain_rev_of_term ~loc context t
686 let domain_of_term ~context ast = rev_uniq (domain_rev_of_term context ast)
688 let domain_of_obj ~context ast =
689 assert (context = []);
692 | CicNotationPt.Theorem (_,_,ty,bo) ->
695 | Some bo -> domain_rev_of_term [] bo) @
696 domain_rev_of_term [] ty
697 | CicNotationPt.Inductive (params,tyl) ->
704 (fun (_,ty) -> domain_rev_of_term [] ty) cl) @
705 domain_rev_of_term [] ty) tyl) in
711 | Some ty -> domain_rev_of_term [] ty @ dom
716 not ( List.exists (fun (name',_) ->
717 match CicNotationUtil.cic_name_of_name name' with
718 Cic.Anonymous -> false
719 | Cic.Name name' -> name = Id name') params
720 || List.exists (fun (name',_,_,_) -> name = Id name') tyl)
722 | CicNotationPt.Record (params,_,ty,fields) ->
725 (List.rev_map (fun (_,ty,_,_) -> domain_rev_of_term [] ty) fields) in
731 | Some ty -> domain_rev_of_term [] ty @ dom
732 ) (dom @ domain_rev_of_term [] ty) params
736 not ( List.exists (fun (name',_) ->
737 match CicNotationUtil.cic_name_of_name name' with
738 Cic.Anonymous -> false
739 | Cic.Name name' -> name = Id name') params
740 || List.exists (fun (name',_,_,_) -> name = Id name') fields)
746 let domain_diff dom1 dom2 =
747 (* let domain_diff = Domain.diff *)
751 | Symbol (symb, 0) ->
753 Symbol (symb',_) when symb = symb' -> true
762 List.filter (fun (_,elt) -> not (is_in_dom2 elt)) dom1
764 module type Disambiguator =
766 val disambiguate_term :
767 ?fresh_instances:bool ->
769 context:Cic.context ->
770 metasenv:Cic.metasenv ->
771 ?initial_ugraph:CicUniv.universe_graph ->
772 aliases:DisambiguateTypes.environment ->(* previous interpretation status *)
773 universe:DisambiguateTypes.multiple_environment option ->
774 CicNotationPt.term disambiguator_input ->
775 ((DisambiguateTypes.domain_item * DisambiguateTypes.codomain_item) list *
776 Cic.metasenv * (* new metasenv *)
778 CicUniv.universe_graph) list * (* disambiguated term *)
781 val disambiguate_obj :
782 ?fresh_instances:bool ->
784 aliases:DisambiguateTypes.environment ->(* previous interpretation status *)
785 universe:DisambiguateTypes.multiple_environment option ->
786 uri:UriManager.uri option -> (* required only for inductive types *)
787 CicNotationPt.obj disambiguator_input ->
788 ((DisambiguateTypes.domain_item * DisambiguateTypes.codomain_item) list *
789 Cic.metasenv * (* new metasenv *)
791 CicUniv.universe_graph) list * (* disambiguated obj *)
795 module Make (C: Callbacks) =
797 let choices_of_id dbd id =
798 let uris = Whelp.locate ~dbd id in
803 (C.input_or_locate_uri
804 ~title:("URI matching \"" ^ id ^ "\" unknown.") ~id ())
810 C.interactive_user_uri_choice ~selection_mode:`MULTIPLE
811 ~ok:"Try selected." ~enable_button_for_non_vars:true
812 ~title:"Ambiguous input." ~id
813 ~msg: ("Ambiguous input \"" ^ id ^
814 "\". Please, choose one or more interpretations:")
819 (UriManager.string_of_uri uri,
822 CicUtil.term_of_uri uri
824 debug_print (lazy (UriManager.string_of_uri uri));
825 debug_print (lazy (Printexc.to_string exn));
831 let refine_profiler = HExtlib.profile "disambiguate_thing.refine_thing"
833 let disambiguate_thing ~dbd ~context ~metasenv
834 ?(initial_ugraph = CicUniv.empty_ugraph) ~aliases ~universe
835 ~uri ~pp_thing ~domain_of_thing ~interpretate_thing ~refine_thing
836 (thing_txt,thing_txt_prefix_len,thing)
838 debug_print (lazy "DISAMBIGUATE INPUT");
839 let disambiguate_context = (* cic context -> disambiguate context *)
841 (function None -> Cic.Anonymous | Some (name, _) -> name)
844 debug_print (lazy ("TERM IS: " ^ (pp_thing thing)));
845 let thing_dom = domain_of_thing ~context:disambiguate_context thing in
846 debug_print (lazy (sprintf "DISAMBIGUATION DOMAIN: %s"
847 (string_of_domain (List.map snd thing_dom))));
849 debug_print (lazy (sprintf "DISAMBIGUATION ENVIRONMENT: %s"
850 (DisambiguatePp.pp_environment aliases)));
851 debug_print (lazy (sprintf "DISAMBIGUATION UNIVERSE: %s"
852 (match universe with None -> "None" | Some _ -> "Some _")));
855 Environment.fold (fun item _ dom -> item :: dom) aliases []
857 let todo_dom = domain_diff thing_dom current_dom in
858 (* (2) lookup function for any item (Id/Symbol/Num) *)
862 let lookup_in_library () =
864 | Id id -> choices_of_id dbd id
865 | Symbol (symb, _) ->
866 List.map DisambiguateChoices.mk_choice
867 (TermAcicContent.lookup_interpretations symb)
869 DisambiguateChoices.lookup_num_choices ()
872 | None -> lookup_in_library ()
877 | Symbol (symb, _) -> Symbol (symb, 0)
880 Environment.find item e
881 with Not_found -> lookup_in_library ())
888 if benchmark then begin
889 let per_item_choices =
893 let len = List.length (lookup_choices dom_item) in
894 debug_print (lazy (sprintf "BENCHMARK %s: %d"
895 (string_of_domain_item dom_item) len));
897 with No_choices _ -> 0)
900 max_refinements := List.fold_left ( * ) 1 per_item_choices;
901 actual_refinements := 0;
902 domain_size := List.length thing_dom;
904 (float_of_int !max_refinements) ** (1. /. float_of_int !domain_size)
910 (* (3) test an interpretation filling with meta uninterpreted identifiers
912 let test_env aliases todo_dom ugraph =
919 | Id _ | Num _ -> (fun _ _ _ -> Cic.Implicit (Some `Closed))
920 | Symbol _ -> (fun _ _ _ -> Cic.Implicit None))) env)
924 let localization_tbl = Cic.CicHash.create 503 in
926 interpretate_thing ~context:disambiguate_context ~env:filled_env
927 ~uri ~is_path:false thing ~localization_tbl
931 refine_thing metasenv context uri cic_thing ugraph ~localization_tbl
934 in refine_profiler.HExtlib.profile foo ()
936 | Try_again msg -> Uncertain (None,msg), ugraph
937 | Invalid_choice msg -> Ko (None,msg), ugraph
939 (* (4) build all possible interpretations *)
940 let (@@) (l1,l2) (l1',l2') = l1@l1', l2@l2' in
941 let rec aux aliases diff lookup_in_todo_dom todo_dom base_univ =
944 assert (lookup_in_todo_dom = None);
945 (match test_env aliases [] base_univ with
946 | Ok (thing, metasenv),new_univ ->
947 [ aliases, diff, metasenv, thing, new_univ ], []
948 | Ko (loc,msg),_ | Uncertain (loc,msg),_ -> [],[diff,loc,msg])
949 | (locs,item) :: remaining_dom ->
950 debug_print (lazy (sprintf "CHOOSED ITEM: %s"
951 (string_of_domain_item item)));
953 match lookup_in_todo_dom with
954 None -> lookup_choices item
955 | Some choices -> choices in
960 lazy ("No choices for " ^ string_of_domain_item item)]
962 (* just one choice. We perform a one-step look-up and
963 if the next set of choices is also a singleton we
964 skip this refinement step *)
965 debug_print(lazy (sprintf "%s CHOSEN" (fst codomain_item)));
966 let new_env = Environment.add item codomain_item aliases in
967 let new_diff = (item,codomain_item)::diff in
968 let lookup_in_todo_dom,next_choice_is_single =
969 match remaining_dom with
972 let choices = lookup_choices he in
973 Some choices,List.length choices = 1
975 if next_choice_is_single then
976 aux new_env new_diff lookup_in_todo_dom remaining_dom
979 (match test_env new_env remaining_dom base_univ with
980 | Ok (thing, metasenv),new_univ ->
981 (match remaining_dom with
983 [ new_env, new_diff, metasenv, thing, new_univ ], []
985 aux new_env new_diff lookup_in_todo_dom
986 remaining_dom new_univ)
987 | Uncertain (loc,msg),new_univ ->
988 (match remaining_dom with
989 | [] -> [], [new_diff,loc,msg]
991 aux new_env new_diff lookup_in_todo_dom
992 remaining_dom new_univ)
993 | Ko (loc,msg),_ -> [], [new_diff,loc,msg])
995 let rec filter univ = function
997 | codomain_item :: tl ->
998 debug_print(lazy (sprintf "%s CHOSEN" (fst codomain_item)));
999 let new_env = Environment.add item codomain_item aliases in
1000 let new_diff = (item,codomain_item)::diff in
1001 (match test_env new_env remaining_dom univ with
1002 | Ok (thing, metasenv),new_univ ->
1003 (match remaining_dom with
1004 | [] -> [new_env,new_diff,metasenv,thing,new_univ], []
1005 | _ -> aux new_env new_diff None remaining_dom new_univ
1008 | Uncertain (loc,msg),new_univ ->
1009 (match remaining_dom with
1010 | [] -> [],[new_diff,loc,msg]
1011 | _ -> aux new_env new_diff None remaining_dom new_univ
1014 | Ko (loc,msg),_ -> ([],[new_diff,loc,msg]) @@ filter univ tl)
1016 filter base_univ choices
1018 let base_univ = initial_ugraph in
1021 match aux aliases [] None todo_dom base_univ with
1022 | [],errors -> raise (NoWellTypedInterpretation (0,errors))
1023 | [_,diff,metasenv,t,ugraph],_ ->
1024 debug_print (lazy "SINGLE INTERPRETATION");
1025 [diff,metasenv,t,ugraph], false
1028 (lazy (sprintf "MANY INTERPRETATIONS (%d)" (List.length l)));
1031 (fun (env, _, _, _, _) ->
1033 (fun (locs,domain_item) ->
1035 fst (Environment.find domain_item env)
1037 locs,descr_of_domain_item domain_item, description)
1042 C.interactive_interpretation_choice
1043 thing_txt thing_txt_prefix_len choices
1045 (List.map (fun n->let _,d,m,t,u= List.nth l n in d,m,t,u) choosed),
1050 CicEnvironment.CircularDependency s ->
1051 failwith "Disambiguate: circular dependency"
1053 let disambiguate_term ?(fresh_instances=false) ~dbd ~context ~metasenv
1054 ?(initial_ugraph = CicUniv.empty_ugraph) ~aliases ~universe
1055 (text,prefix_len,term)
1058 if fresh_instances then CicNotationUtil.freshen_term term else term
1060 disambiguate_thing ~dbd ~context ~metasenv ~initial_ugraph ~aliases
1061 ~universe ~uri:None ~pp_thing:CicNotationPp.pp_term
1062 ~domain_of_thing:domain_of_term ~interpretate_thing:interpretate_term
1063 ~refine_thing:refine_term (text,prefix_len,term)
1065 let disambiguate_obj ?(fresh_instances=false) ~dbd ~aliases ~universe ~uri
1066 (text,prefix_len,obj)
1069 if fresh_instances then CicNotationUtil.freshen_obj obj else obj
1071 disambiguate_thing ~dbd ~context:[] ~metasenv:[] ~aliases ~universe ~uri
1072 ~pp_thing:CicNotationPp.pp_obj ~domain_of_thing:domain_of_obj
1073 ~interpretate_thing:interpretate_obj ~refine_thing:refine_obj
1074 (text,prefix_len,obj)