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 ugraph =
60 (* if benchmark then incr actual_refinements; *)
62 CicMkImplicit.expand_implicits metasenv [] context term in
63 debug_print (sprintf "TEST_INTERPRETATION: %s" (CicPp.ppterm term));
65 let term', _, metasenv',ugraph1 =
66 CicRefine.type_of_aux' metasenv context term ugraph in
67 (Ok (term', metasenv')),ugraph1
69 | CicRefine.Uncertain _ ->
70 debug_print ("%%% UNCERTAIN!!! " ^ CicPp.ppterm term) ;
72 | CicRefine.RefineFailure msg ->
74 (sprintf ("%%%%%% PRUNED!!!\n<<begin cause>>\n" ^^
75 "%s\n<<end cause>>\n<<begin term>>\n%s\n<<end term>>")
76 msg (CicPp.ppterm term)));
78 | CicUnification.UnificationFailure s ->
79 prerr_endline ("PASSADI QUI: " ^ s);
80 raise ( CicUnification.UnificationFailure s )
82 let resolve (env: environment) (item: domain_item) ?(num = "") ?(args = []) () =
84 snd (Environment.find item env) env num args
86 failwith ("Domain item not found: " ^
87 (DisambiguateTypes.string_of_domain_item item))
89 (* TODO move it to Cic *)
90 let find_in_environment name context =
91 let rec aux acc = function
92 | [] -> raise Not_found
93 | Cic.Name hd :: tl when hd = name -> acc
94 | _ :: tl -> aux (acc + 1) tl
98 let interpretate ~context ~env ast =
99 let rec aux loc context = function
100 | CicAst.AttributedTerm (`Loc loc, term) ->
102 | CicAst.AttributedTerm (_, term) -> aux loc context term
103 | CicAst.Appl (CicAst.Symbol (symb, i) :: args) ->
104 let cic_args = List.map (aux loc context) args in
105 resolve env (Symbol (symb, i)) ~args:cic_args ()
106 | CicAst.Appl terms -> Cic.Appl (List.map (aux loc context) terms)
107 | CicAst.Binder (binder_kind, (var, typ), body) ->
108 let cic_type = aux_option loc context typ in
109 let cic_body = aux loc (var :: context) body in
110 (match binder_kind with
111 | `Lambda -> Cic.Lambda (var, cic_type, cic_body)
112 | `Pi | `Forall -> Cic.Prod (var, cic_type, cic_body)
114 resolve env (Symbol ("exists", 0))
115 ~args:[ cic_type; Cic.Lambda (var, cic_type, cic_body) ] ())
116 | CicAst.Case (term, indty_ident, outtype, branches) ->
117 let cic_term = aux loc context term in
118 let cic_outtype = aux_option loc context outtype in
119 let do_branch ((head, args), term) =
120 let rec do_branch' context = function
121 | [] -> aux loc context term
122 | (name, typ) :: tl ->
123 let cic_body = do_branch' (name :: context) tl in
126 | None -> Cic.Implicit (Some `Type)
127 | Some typ -> aux loc context typ
129 Cic.Lambda (name, typ, cic_body)
131 do_branch' context args
133 let (indtype_uri, indtype_no) =
134 match indty_ident with
135 | Some indty_ident ->
136 (match resolve env (Id indty_ident) () with
137 | Cic.MutInd (uri, tyno, _) -> (uri, tyno)
138 | Cic.Implicit _ -> raise Try_again
139 | _ -> raise DisambiguateChoices.Invalid_choice)
141 let fst_constructor =
143 | ((head, _), _) :: _ -> head
144 | [] -> raise DisambiguateChoices.Invalid_choice
146 (match resolve env (Id fst_constructor) () with
147 | Cic.MutConstruct (indtype_uri, indtype_no, _, _) ->
148 (indtype_uri, indtype_no)
149 | Cic.Implicit _ -> raise Try_again
150 | _ -> raise DisambiguateChoices.Invalid_choice)
152 Cic.MutCase (indtype_uri, indtype_no, cic_outtype, cic_term,
153 (List.map do_branch branches))
154 | CicAst.LetIn ((name, typ), def, body) ->
155 let cic_def = aux loc context def in
159 | Some t -> Cic.Cast (cic_def, aux loc context t)
161 let cic_body = aux loc (name :: context) body in
162 Cic.LetIn (name, cic_def, cic_body)
163 | CicAst.LetRec (kind, defs, body) ->
165 List.fold_left (fun acc ((name, _), _, _) -> name :: acc)
168 let cic_body = aux loc context' body in
171 (fun ((name, typ), body, decr_idx) ->
172 let cic_body = aux loc context' body in
173 let cic_type = aux_option loc context typ in
177 CicTextualParser2.fail loc
178 "Recursive functions cannot be anonymous"
179 | Cic.Name name -> name
181 (name, decr_idx, cic_type, cic_body))
184 let counter = ref ~-1 in
185 let build_term funs =
186 (* this is the body of the fold_right function below. Rationale: Fix
187 * and CoFix cases differs only in an additional index in the
188 * inductiveFun list, see Cic.term *)
191 (fun (var, _, _, _) cic ->
193 Cic.LetIn (Cic.Name var, Cic.Fix (!counter, funs), cic))
196 List.map (fun (name, _, typ, body) -> (name, typ, body)) funs
198 (fun (var, _, _, _) cic ->
200 Cic.LetIn (Cic.Name var, Cic.CoFix (!counter, funs), cic))
202 List.fold_right (build_term inductiveFuns) inductiveFuns cic_body
203 | CicAst.Ident (name, subst)
204 | CicAst.Uri (name, subst) as ast ->
205 let is_uri = function CicAst.Uri _ -> true | _ -> false in
207 if is_uri ast then raise Not_found;(* don't search the env for URIs *)
208 let index = find_in_environment name context in
209 if subst <> None then
210 CicTextualParser2.fail loc
211 "Explicit substitutions not allowed here";
215 if is_uri ast then (* we have the URI, build the term out of it *)
217 CicUtil.term_of_uri name
218 with UriManager.IllFormedUri _ ->
219 CicTextualParser2.fail loc "Ill formed URI"
221 resolve env (Id name) ()
225 List.map (fun uri -> UriManager.name_of_uri uri, uri) uris
232 List.assoc s ids_to_uris, aux loc context term
234 raise DisambiguateChoices.Invalid_choice))
236 | None -> List.map (fun uri -> uri, Cic.Implicit None) uris)
240 | Cic.Const (uri, []) ->
241 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
242 let uris = CicUtil.params_of_obj o in
243 Cic.Const (uri, mk_subst uris)
244 | Cic.Var (uri, []) ->
245 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
246 let uris = CicUtil.params_of_obj o in
247 Cic.Var (uri, mk_subst uris)
248 | Cic.MutInd (uri, i, []) ->
249 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
250 let uris = CicUtil.params_of_obj o in
251 Cic.MutInd (uri, i, mk_subst uris)
252 | Cic.MutConstruct (uri, i, j, []) ->
253 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
254 let uris = CicUtil.params_of_obj o in
255 Cic.MutConstruct (uri, i, j, mk_subst uris)
256 | Cic.Meta _ | Cic.Implicit _ as t ->
258 prerr_endline (sprintf
259 "Warning: %s must be instantiated with _[%s] but we do not enforce it"
263 (fun (s, term) -> s ^ " := " ^ CicAstPp.pp_term term)
268 raise DisambiguateChoices.Invalid_choice
270 CicEnvironment.CircularDependency _ ->
271 raise DisambiguateChoices.Invalid_choice))
272 | CicAst.Implicit -> Cic.Implicit None
273 | CicAst.Num (num, i) -> resolve env (Num i) ~num ()
274 | CicAst.Meta (index, subst) ->
277 (function None -> None | Some term -> Some (aux loc context term))
280 Cic.Meta (index, cic_subst)
281 | CicAst.Sort `Prop -> Cic.Sort Cic.Prop
282 | CicAst.Sort `Set -> Cic.Sort Cic.Set
283 | CicAst.Sort `Type -> Cic.Sort (Cic.Type (CicUniv.fresh())) (* TASSI *)
284 | CicAst.Sort `CProp -> Cic.Sort Cic.CProp
285 | CicAst.Symbol (symbol, instance) ->
286 resolve env (Symbol (symbol, instance)) ()
287 | CicAst.UserInput -> assert false
288 and aux_option loc context = function
289 | None -> Cic.Implicit (Some `Type)
290 | Some term -> aux loc context term
293 | CicAst.AttributedTerm (`Loc loc, term) -> aux loc context term
294 | term -> aux CicAst.dummy_floc context term
296 let domain_of_term ~context ast =
297 (* "aux" keeps domain in reverse order and doesn't care about duplicates.
298 * Domain item more in deep in the list will be processed first.
300 let rec aux loc context = function
301 | CicAst.AttributedTerm (`Loc loc, term) -> aux loc context term
302 | CicAst.AttributedTerm (_, term) -> aux loc context term
303 | CicAst.Appl terms ->
304 List.fold_left (fun dom term -> aux loc context term @ dom) [] terms
305 | CicAst.Binder (kind, (var, typ), body) ->
308 | `Exists -> [ Symbol ("exists", 0) ]
311 let type_dom = aux_option loc context typ in
312 let body_dom = aux loc (var :: context) body in
313 body_dom @ type_dom @ kind_dom
314 | CicAst.Case (term, indty_ident, outtype, branches) ->
315 let term_dom = aux loc context term in
316 let outtype_dom = aux_option loc context outtype in
317 let do_branch ((head, args), term) =
318 let (term_context, args_domain) =
320 (fun (cont, dom) (name, typ) ->
324 | Some typ -> aux loc cont typ @ dom)))
327 args_domain @ aux loc term_context term
330 List.fold_left (fun dom branch -> do_branch branch @ dom) [] branches
332 branches_dom @ outtype_dom @ term_dom @
333 (match indty_ident with None -> [] | Some ident -> [ Id ident ])
334 | CicAst.LetIn ((var, typ), body, where) ->
335 let body_dom = aux loc context body in
336 let type_dom = aux_option loc context typ in
337 let where_dom = aux loc (var :: context) where in
338 where_dom @ type_dom @ body_dom
339 | CicAst.LetRec (kind, defs, where) ->
341 List.fold_left (fun acc ((var, typ), _, _) -> var :: acc)
344 let where_dom = aux loc context' where in
347 (fun dom ((_, typ), body, _) ->
348 aux loc context' body @ aux_option loc context typ)
352 | CicAst.Ident (name, subst) ->
354 let index = find_in_environment name context in
355 if subst <> None then
356 CicTextualParser2.fail loc
357 "Explicit substitutions not allowed here"
365 (fun dom (_, term) ->
366 let dom' = aux loc context term in
370 | CicAst.Implicit -> []
371 | CicAst.Num (num, i) -> [ Num i ]
372 | CicAst.Meta (index, local_context) ->
373 List.fold_left (fun dom term -> aux_option loc context term @ dom) []
375 | CicAst.Sort _ -> []
376 | CicAst.Symbol (symbol, instance) -> [ Symbol (symbol, instance) ]
377 | CicAst.UserInput -> assert false
379 and aux_option loc context = function
381 | Some t -> aux loc context t
384 (* e.g. [5;1;1;1;2;3;4;1;2] -> [2;1;4;3;5] *)
386 let module SortedItem =
388 type t = DisambiguateTypes.domain_item
389 let compare = Pervasives.compare
392 let module Set = Set.Make (SortedItem) in
394 let rev_l = List.rev l in
395 let (_, uniq_rev_l) =
397 (fun (members, rev_l) elt ->
398 if Set.mem elt members then
401 Set.add elt members, elt :: rev_l)
402 (Set.empty, []) rev_l
409 | CicAst.AttributedTerm (`Loc loc, term) -> aux loc context term
410 | term -> aux CicAst.dummy_floc context term)
414 let domain_diff dom1 dom2 =
415 (* let domain_diff = Domain.diff *)
417 List.fold_left (fun pred elt -> (fun elt' -> elt' = elt || pred elt'))
418 (fun _ -> false) dom2
420 List.filter (fun elt -> not (is_in_dom2 elt)) dom1
422 module Make (C: Callbacks) =
424 let choices_of_id dbd id =
425 let uris = MetadataQuery.locate ~dbd id in
429 [UriManager.string_of_uri (C.input_or_locate_uri
430 ~title:("URI matching \"" ^ id ^ "\" unknown.") ~id ())]
433 C.interactive_user_uri_choice ~selection_mode:`MULTIPLE
434 ~ok:"Try selected." ~enable_button_for_non_vars:true
435 ~title:"Ambiguous input." ~id
436 ~msg: ("Ambiguous input \"" ^ id ^
437 "\". Please, choose one or more interpretations:")
445 CicUtil.term_of_uri uri
448 prerr_endline (Printexc.to_string exn);
454 let disambiguate_term ~(dbd:Mysql.dbd) context metasenv term
455 ?(initial_ugraph = CicUniv.empty_ugraph) ~aliases:current_env
457 debug_print "NEW DISAMBIGUATE INPUT";
458 let disambiguate_context = (* cic context -> disambiguate context *)
460 (function None -> Cic.Anonymous | Some (name, _) -> name)
463 let term_dom = domain_of_term ~context:disambiguate_context term in
464 debug_print (sprintf "DISAMBIGUATION DOMAIN: %s"
465 (string_of_domain term_dom));
467 Environment.fold (fun item _ dom -> item :: dom) current_env []
469 let todo_dom = domain_diff term_dom current_dom in
470 (* (2) lookup function for any item (Id/Symbol/Num) *)
472 let id_choices = Hashtbl.create 1023 in
478 Hashtbl.find id_choices id
480 let choices = choices_of_id dbd id in
481 Hashtbl.add id_choices id choices;
483 | Symbol (symb, _) -> DisambiguateChoices.lookup_symbol_choices symb
484 | Num instance -> DisambiguateChoices.lookup_num_choices ()
486 if choices = [] then raise (No_choices item);
493 if benchmark then begin
494 let per_item_choices =
498 let len = List.length (lookup_choices dom_item) in
499 prerr_endline (sprintf "BENCHMARK %s: %d"
500 (string_of_domain_item dom_item) len);
502 with No_choices _ -> 0)
505 max_refinements := List.fold_left ( * ) 1 per_item_choices;
506 actual_refinements := 0;
507 domain_size := List.length term_dom;
509 (float_of_int !max_refinements) ** (1. /. float_of_int !domain_size)
515 (* (3) test an interpretation filling with meta uninterpreted identifiers
517 let test_env current_env todo_dom ugraph =
524 | Id _ | Num _ -> (fun _ _ _ -> Cic.Implicit (Some `Closed))
525 | Symbol _ -> (fun _ _ _ -> Cic.Implicit None))) env)
530 interpretate ~context:disambiguate_context ~env:filled_env term
532 let k,ugraph1 = refine metasenv context cic_term ugraph in
535 | Try_again -> Uncertain,ugraph
536 | DisambiguateChoices.Invalid_choice -> Ko,ugraph
538 (* (4) build all possible interpretations *)
539 let rec aux current_env todo_dom base_univ =
542 (match test_env current_env [] base_univ with
543 | Ok (term, metasenv),new_univ ->
544 [ current_env, metasenv, term, new_univ ]
545 | Ko,_ | Uncertain,_ -> [])
546 | item :: remaining_dom ->
547 debug_print (sprintf "CHOOSED ITEM: %s"
548 (string_of_domain_item item));
549 let choices = lookup_choices item in
550 let rec filter univ = function
552 | codomain_item :: tl ->
553 debug_print (sprintf "%s CHOSEN" (fst codomain_item)) ;
555 Environment.add item codomain_item current_env
557 (match test_env new_env remaining_dom univ with
558 | Ok (term, metasenv),new_univ ->
559 (match remaining_dom with
560 | [] -> [ new_env, metasenv, term, new_univ ]
561 | _ -> aux new_env remaining_dom new_univ )@
563 | Uncertain,new_univ ->
564 (match remaining_dom with
566 | _ -> aux new_env remaining_dom new_univ )@
568 | Ko,_ -> filter univ tl)
570 filter base_univ choices
572 let base_univ = initial_ugraph in
575 match aux current_env todo_dom base_univ with
576 | [] -> raise NoWellTypedInterpretation
577 | [ e,me,t,u ] as l ->
578 debug_print "UNA SOLA SCELTA";
581 debug_print (sprintf "PIU' SCELTE (%d)" (List.length l));
584 (fun (env, _, _, _) ->
588 fst (Environment.find domain_item env)
590 (descr_of_domain_item domain_item, description))
594 let choosed = C.interactive_interpretation_choice choices in
595 List.map (List.nth l) choosed
599 let res_size = List.length res in
600 prerr_endline (sprintf
601 ("BENCHMARK: %d/%d refinements performed, domain size %d, interps %d, k %.2f\n" ^^
602 "BENCHMARK: estimated %.2f")
603 !actual_refinements !max_refinements !domain_size res_size
605 (float_of_int (!domain_size - 1) *. !choices_avg *. (float_of_int res_size) +. !choices_avg)));
609 CicEnvironment.CircularDependency s ->
610 failwith "Disambiguate: circular dependency"