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 exception No_choices of domain_item
32 exception NoWellTypedInterpretation
34 (** raised when an environment is not enough informative to decide *)
38 let debug_print = if debug then prerr_endline else ignore
41 (** print benchmark information *)
43 let max_refinements = ref 0 (* benchmarking is not thread safe *)
44 let actual_refinements = ref 0
45 let domain_size = ref 0
46 let choices_avg = ref 0.
49 let descr_of_domain_item = function
52 | Num i -> string_of_int i
55 | Ok of Cic.term * Cic.metasenv
59 let refine metasenv context term =
60 (* if benchmark then incr actual_refinements; *)
61 let metasenv, term = CicMkImplicit.expand_implicits metasenv [] context term in
62 debug_print (sprintf "TEST_INTERPRETATION: %s" (CicPp.ppterm term));
64 let term', _, metasenv' = CicRefine.type_of_aux' metasenv context term in
67 | CicRefine.Uncertain _ ->
68 debug_print ("%%% UNCERTAIN!!! " ^ CicPp.ppterm term) ;
70 | CicRefine.RefineFailure _ ->
71 debug_print ("%%% PRUNED!!! " ^ CicPp.ppterm term) ;
74 let resolve (env: environment) (item: domain_item) ?(num = "") ?(args = []) () =
76 snd (Environment.find item env) env num args
77 with Not_found -> assert false
79 (* TODO move it to Cic *)
80 let find_in_environment name context =
81 let rec aux acc = function
82 | [] -> raise Not_found
83 | Cic.Name hd :: tl when hd = name -> acc
84 | _ :: tl -> aux (acc + 1) tl
88 let interpretate ~context ~env ast =
89 let rec aux loc context = function
90 | CicAst.AttributedTerm (`Loc loc, term) ->
92 | CicAst.AttributedTerm (_, term) -> aux loc context term
93 | CicAst.Appl (CicAst.Symbol (symb, i) :: args) ->
94 let cic_args = List.map (aux loc context) args in
95 resolve env (Symbol (symb, i)) ~args:cic_args ()
96 | CicAst.Appl terms -> Cic.Appl (List.map (aux loc context) terms)
97 | CicAst.Binder (binder_kind, (var, typ), body) ->
98 let cic_type = aux_option loc context typ in
99 let cic_body = aux loc (var :: context) body in
100 (match binder_kind with
101 | `Lambda -> Cic.Lambda (var, cic_type, cic_body)
102 | `Pi | `Forall -> Cic.Prod (var, cic_type, cic_body)
104 resolve env (Symbol ("exists", 0))
105 ~args:[ cic_type; Cic.Lambda (var, cic_type, cic_body) ] ())
106 | CicAst.Case (term, indty_ident, outtype, branches) ->
107 let cic_term = aux loc context term in
108 let cic_outtype = aux_option loc context outtype in
109 let do_branch ((head, args), term) =
110 let rec do_branch' context = function
111 | [] -> aux loc context term
112 | (name, typ) :: tl ->
113 let cic_body = do_branch' (name :: context) tl in
116 | None -> Cic.Implicit (Some `Type)
117 | Some typ -> aux loc context typ
119 Cic.Lambda (name, typ, cic_body)
121 do_branch' context args
123 let (indtype_uri, indtype_no) =
124 match indty_ident with
125 | Some indty_ident ->
126 (match resolve env (Id indty_ident) () with
127 | Cic.MutInd (uri, tyno, _) -> (uri, tyno)
128 | Cic.Implicit _ -> raise Try_again
129 | _ -> raise DisambiguateChoices.Invalid_choice)
131 let fst_constructor =
133 | ((head, _), _) :: _ -> head
134 | [] -> raise DisambiguateChoices.Invalid_choice
136 (match resolve env (Id fst_constructor) () with
137 | Cic.MutConstruct (indtype_uri, indtype_no, _, _) ->
138 (indtype_uri, indtype_no)
139 | Cic.Implicit _ -> raise Try_again
140 | _ -> raise DisambiguateChoices.Invalid_choice)
142 Cic.MutCase (indtype_uri, indtype_no, cic_outtype, cic_term,
143 (List.map do_branch branches))
144 | CicAst.LetIn ((name, typ), def, body) ->
145 let cic_def = aux loc context def in
149 | Some t -> Cic.Cast (cic_def, aux loc context t)
151 let cic_body = aux loc (name :: context) body in
152 Cic.LetIn (name, cic_def, cic_body)
153 | CicAst.LetRec (kind, defs, body) ->
155 List.fold_left (fun acc ((name, _), _, _) -> name :: acc)
158 let cic_body = aux loc context' body in
161 (fun ((name, typ), body, decr_idx) ->
162 let cic_body = aux loc context' body in
163 let cic_type = aux_option loc context typ in
167 CicTextualParser2.fail loc
168 "Recursive functions cannot be anonymous"
169 | Cic.Name name -> name
171 (name, decr_idx, cic_type, cic_body))
174 let counter = ref ~-1 in
175 let build_term funs =
176 (* this is the body of the fold_right function below. Rationale: Fix
177 * and CoFix cases differs only in an additional index in the
178 * inductiveFun list, see Cic.term *)
181 (fun (var, _, _, _) cic ->
183 Cic.LetIn (Cic.Name var, Cic.Fix (!counter, funs), cic))
186 List.map (fun (name, _, typ, body) -> (name, typ, body)) funs
188 (fun (var, _, _, _) cic ->
190 Cic.LetIn (Cic.Name var, Cic.CoFix (!counter, funs), cic))
192 List.fold_right (build_term inductiveFuns) inductiveFuns cic_body
193 | CicAst.Ident (name, subst) ->
195 let index = find_in_environment name context in
196 if subst <> None then
197 CicTextualParser2.fail loc
198 "Explicit substitutions not allowed here";
201 let cic = resolve env (Id name) () in
204 List.map (fun uri -> UriManager.name_of_uri uri, uri) uris
211 List.assoc s ids_to_uris, aux loc context term
213 raise DisambiguateChoices.Invalid_choice))
215 | None -> List.map (fun uri -> uri, Cic.Implicit None) uris)
217 (* the try is for CicTypeChecker.typecheck *)
220 | Cic.Const (uri, []) ->
222 match CicEnvironment.get_obj uri with
223 (*match CicTypeChecker.typecheck uri with*)
224 | Cic.Constant (_, _, _, uris) -> uris
227 Cic.Const (uri, mk_subst uris)
228 | Cic.Var (uri, []) ->
230 match CicEnvironment.get_obj uri with
231 (*match CicTypeChecker.typecheck uri with*)
232 | Cic.Variable (_, _, _, uris) -> uris
235 Cic.Var (uri, mk_subst uris)
236 | Cic.MutInd (uri, i, []) ->
238 match CicEnvironment.get_obj uri with
239 (*match CicTypeChecker.typecheck uri with*)
240 | Cic.InductiveDefinition (_, uris, _) -> uris
243 Cic.MutInd (uri, i, mk_subst uris)
244 | Cic.MutConstruct (uri, i, j, []) ->
246 match CicEnvironment.get_obj uri with
247 (*match CicTypeChecker.typecheck uri with*)
248 | Cic.InductiveDefinition (_, uris, _) -> uris
251 Cic.MutConstruct (uri, i, j, mk_subst uris)
252 | Cic.Meta _ | Cic.Implicit _ as t ->
254 prerr_endline (sprintf
255 "Warning: %s must be instantiated with _[%s] but we do not enforce it"
259 (fun (s, term) -> s ^ " := " ^ CicAstPp.pp_term term)
264 raise DisambiguateChoices.Invalid_choice
266 CicEnvironment.CircularDependency _ ->
267 raise DisambiguateChoices.Invalid_choice))
268 | CicAst.Implicit -> Cic.Implicit None
269 | CicAst.Num (num, i) -> resolve env (Num i) ~num ()
270 | CicAst.Meta (index, subst) ->
273 (function None -> None | Some term -> Some (aux loc context term))
276 Cic.Meta (index, cic_subst)
277 | CicAst.Sort `Prop -> Cic.Sort Cic.Prop
278 | CicAst.Sort `Set -> Cic.Sort Cic.Set
279 | CicAst.Sort `Type -> Cic.Sort (Cic.Type (CicUniv.fresh())) (* TASSI *)
280 | CicAst.Sort `CProp -> Cic.Sort Cic.CProp
281 | CicAst.Symbol (symbol, instance) ->
282 resolve env (Symbol (symbol, instance)) ()
283 and aux_option loc context = function
284 | None -> Cic.Implicit (Some `Type)
285 | Some term -> aux loc context term
288 | CicAst.AttributedTerm (`Loc loc, term) -> aux loc context term
289 | term -> aux (-1, -1) context term
291 let domain_of_term ~context ast =
292 (* "aux" keeps domain in reverse order and doesn't care about duplicates.
293 * Domain item more in deep in the list will be processed first.
295 let rec aux loc context = function
296 | CicAst.AttributedTerm (`Loc loc, term) -> aux loc context term
297 | CicAst.AttributedTerm (_, term) -> aux loc context term
298 | CicAst.Appl terms ->
299 List.fold_left (fun dom term -> aux loc context term @ dom) [] terms
300 | CicAst.Binder (kind, (var, typ), body) ->
303 | `Exists -> [ Symbol ("exists", 0) ]
306 let type_dom = aux_option loc context typ in
307 let body_dom = aux loc (var :: context) body in
308 body_dom @ type_dom @ kind_dom
309 | CicAst.Case (term, indty_ident, outtype, branches) ->
310 let term_dom = aux loc context term in
311 let outtype_dom = aux_option loc context outtype in
312 let do_branch ((head, args), term) =
313 let (term_context, args_domain) =
315 (fun (cont, dom) (name, typ) ->
319 | Some typ -> aux loc cont typ @ dom)))
322 args_domain @ aux loc term_context term
325 List.fold_left (fun dom branch -> do_branch branch @ dom) [] branches
327 branches_dom @ outtype_dom @ term_dom @
328 (match indty_ident with None -> [] | Some ident -> [ Id ident ])
329 | CicAst.LetIn ((var, typ), body, where) ->
330 let body_dom = aux loc context body in
331 let type_dom = aux_option loc context typ in
332 let where_dom = aux loc (var :: context) where in
333 where_dom @ type_dom @ body_dom
334 | CicAst.LetRec (kind, defs, where) ->
336 List.fold_left (fun acc ((var, typ), _, _) -> var :: acc)
339 let where_dom = aux loc context' where in
342 (fun dom ((_, typ), body, _) ->
343 aux loc context' body @ aux_option loc context typ)
347 | CicAst.Ident (name, subst) ->
349 let index = find_in_environment name context in
350 if subst <> None then
351 CicTextualParser2.fail loc
352 "Explicit substitutions not allowed here"
360 (fun dom (_, term) ->
361 let dom' = aux loc context term in
364 | CicAst.Implicit -> []
365 | CicAst.Num (num, i) -> [ Num i ]
366 | CicAst.Meta (index, local_context) ->
367 List.fold_left (fun dom term -> aux_option loc context term @ dom) []
369 | CicAst.Sort _ -> []
370 | CicAst.Symbol (symbol, instance) -> [ Symbol (symbol, instance) ]
372 and aux_option loc context = function
374 | Some t -> aux loc context t
377 (* e.g. [5;1;1;1;2;3;4;1;2] -> [2;1;4;3;5] *)
379 let module SortedItem =
381 type t = DisambiguateTypes.domain_item
382 let compare = Pervasives.compare
385 let module Set = Set.Make (SortedItem) in
387 let rev_l = List.rev l in
388 let (_, uniq_rev_l) =
390 (fun (members, rev_l) elt ->
391 if Set.mem elt members then
394 Set.add elt members, elt :: rev_l)
395 (Set.empty, []) rev_l
402 | CicAst.AttributedTerm (`Loc loc, term) -> aux loc context term
403 | term -> aux (-1, -1) context term)
407 let domain_diff dom1 dom2 =
408 (* let domain_diff = Domain.diff *)
410 List.fold_left (fun pred elt -> (fun elt' -> elt' = elt || pred elt'))
411 (fun _ -> false) dom2
413 List.filter (fun elt -> not (is_in_dom2 elt)) dom1
415 module Make (C: Callbacks) =
417 let choices_of_id mqi_handle id =
418 let query = MQueryGenerator.locate id in
419 let result = MQueryInterpreter.execute mqi_handle query in
423 MQueryMisc.wrong_xpointer_format_from_wrong_xpointer_format' uri
428 [UriManager.string_of_uri (C.input_or_locate_uri
429 ~title:("URI matching \"" ^ id ^ "\" unknown.") ~id ())]
432 C.interactive_user_uri_choice ~selection_mode:`MULTIPLE
433 ~ok:"Try selected." ~enable_button_for_non_vars:true
434 ~title:"Ambiguous input." ~id
435 ~msg: ("Ambiguous input \"" ^ id ^
436 "\". Please, choose one or more interpretations:")
444 HelmLibraryObjects.term_of_uri (UriManager.uri_of_string uri)
445 with _ -> assert false
450 let disambiguate_term mqi_handle context metasenv term ~aliases:current_env
452 debug_print "NEW DISAMBIGUATE INPUT";
453 let disambiguate_context = (* cic context -> disambiguate context *)
455 (function None -> Cic.Anonymous | Some (name, _) -> name)
458 let term_dom = domain_of_term ~context:disambiguate_context term in
459 debug_print (sprintf "DISAMBIGUATION DOMAIN: %s"
460 (string_of_domain term_dom));
462 Environment.fold (fun item _ dom -> item :: dom) current_env []
464 let todo_dom = domain_diff term_dom current_dom in
465 (* (2) lookup function for any item (Id/Symbol/Num) *)
467 let id_choices = Hashtbl.create 1023 in
473 Hashtbl.find id_choices id
475 let choices = choices_of_id mqi_handle id in
476 Hashtbl.add id_choices id choices;
478 | Symbol (symb, _) -> DisambiguateChoices.lookup_symbol_choices symb
479 | Num instance -> DisambiguateChoices.lookup_num_choices ()
481 if choices = [] then raise (No_choices item);
488 if benchmark then begin
489 let per_item_choices =
493 let len = List.length (lookup_choices dom_item) in
494 prerr_endline (sprintf "BENCHMARK %s: %d"
495 (string_of_domain_item dom_item) len);
497 with No_choices _ -> 0)
500 max_refinements := List.fold_left ( * ) 1 per_item_choices;
501 actual_refinements := 0;
502 domain_size := List.length term_dom;
504 (float_of_int !max_refinements) ** (1. /. float_of_int !domain_size)
510 (* (3) test an interpretation filling with meta uninterpreted identifiers
512 let test_env current_env todo_dom univ =
519 | Id _ | Num _ -> (fun _ _ _ -> Cic.Implicit (Some `Closed))
520 | Symbol _ -> (fun _ _ _ -> Cic.Implicit None))) env)
524 CicUniv.set_working univ;
526 interpretate ~context:disambiguate_context ~env:filled_env term
528 let k = refine metasenv context cic_term in
529 let new_univ = CicUniv.get_working () in
532 | Try_again -> Uncertain,univ
533 | DisambiguateChoices.Invalid_choice -> Ko,univ
535 (* (4) build all possible interpretations *)
536 let rec aux current_env todo_dom base_univ =
539 (match test_env current_env [] base_univ with
540 | Ok (term, metasenv),new_univ ->
541 [ current_env, metasenv, term, new_univ ]
542 | Ko,_ | Uncertain,_ -> [])
543 | item :: remaining_dom ->
544 debug_print (sprintf "CHOOSED ITEM: %s"
545 (string_of_domain_item item));
546 let choices = lookup_choices item in
547 let rec filter univ = function
549 | codomain_item :: tl ->
550 debug_print (sprintf "%s CHOSEN" (fst codomain_item)) ;
552 Environment.add item codomain_item current_env
554 (match test_env new_env remaining_dom univ with
555 | Ok (term, metasenv),new_univ ->
556 (match remaining_dom with
557 | [] -> [ new_env, metasenv, term, new_univ ]
558 | _ -> aux new_env remaining_dom new_univ )@
560 | Uncertain,new_univ ->
561 (match remaining_dom with
563 | _ -> aux new_env remaining_dom new_univ )@
565 | Ko,_ -> filter univ tl)
567 filter base_univ choices
569 let base_univ = CicUniv.get_working () in
572 match aux current_env todo_dom base_univ with
573 | [] -> raise NoWellTypedInterpretation
574 | [ e,me,t,u ] as l ->
575 debug_print "UNA SOLA SCELTA";
576 CicUniv.set_working u;
579 debug_print (sprintf "PIU' SCELTE (%d)" (List.length l));
582 (fun (env, _, _, _) ->
586 fst (Environment.find domain_item env)
588 (descr_of_domain_item domain_item, description))
592 let choosed = C.interactive_interpretation_choice choices in
593 let l' = List.map (List.nth l) choosed in
597 CicUniv.set_working u;
598 (*CicUniv.print_working_graph ();*)
600 | hd::tl -> (* ok, testlibrary... cosi' stampa MANY... bah *)
601 List.map (fun (e,me,t,u) -> (e,me,t)) l'
605 let res_size = List.length res in
606 prerr_endline (sprintf
607 ("BENCHMARK: %d/%d refinements performed, domain size %d, interps %d, k %.2f\n" ^^
608 "BENCHMARK: estimated %.2f")
609 !actual_refinements !max_refinements !domain_size res_size
611 (float_of_int (!domain_size - 1) *. !choices_avg *. (float_of_int res_size) +. !choices_avg)));
615 CicEnvironment.CircularDependency s ->
616 raise (Failure "e chi la becca sta CircularDependency?");