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
40 let descr_of_domain_item = function
43 | Num i -> string_of_int i
46 | Ok of Cic.term * Cic.metasenv
50 let refine metasenv context term =
51 let metasenv, term = CicMkImplicit.expand_implicits metasenv context term in
52 debug_print (sprintf "TEST_INTERPRETATION: %s" (CicPp.ppterm term));
54 let term', _, metasenv' = CicRefine.type_of_aux' metasenv context term in
57 | CicRefine.Uncertain _ ->
58 debug_print ("%%% UNCERTAIN!!! " ^ CicPp.ppterm term) ;
61 (* TODO we should catch only the RefineFailure excecption *)
62 debug_print ("%%% PRUNED!!! " ^ CicPp.ppterm term) ;
65 let resolve (env: environment) (item: domain_item) ?(num = "") ?(args = []) () =
67 snd (Environment.find item env) env num args
68 with Not_found -> assert false
70 (* TODO move it to Cic *)
71 let find_in_environment name context =
72 let rec aux acc = function
73 | [] -> raise Not_found
74 | Cic.Name hd :: tl when hd = name -> acc
75 | _ :: tl -> aux (acc + 1) tl
79 let interpretate ~context ~env ast =
80 let rec aux loc context = function
81 | CicAst.AttributedTerm (`Loc loc, term) ->
83 | CicAst.AttributedTerm (_, term) -> aux loc context term
84 | CicAst.Appl (CicAst.Symbol (symb, i) :: args) ->
85 let cic_args = List.map (aux loc context) args in
86 resolve env (Symbol (symb, i)) ~args:cic_args ()
87 | CicAst.Appl terms -> Cic.Appl (List.map (aux loc context) terms)
88 | CicAst.Binder (binder_kind, (var, typ), body) ->
89 let cic_type = aux_option loc context typ in
90 let cic_body = aux loc (var :: context) body in
91 (match binder_kind with
92 | `Lambda -> Cic.Lambda (var, cic_type, cic_body)
93 | `Pi | `Forall -> Cic.Prod (var, cic_type, cic_body)
95 resolve env (Symbol ("exists", 0))
96 ~args:[ cic_type; Cic.Lambda (var, cic_type, cic_body) ] ())
97 | CicAst.Case (term, indty_ident, outtype, branches) ->
98 let cic_term = aux loc context term in
99 let cic_outtype = aux_option loc context outtype in
100 let do_branch ((head, args), term) =
101 let rec do_branch' context = function
102 | [] -> aux loc context term
103 | (name, typ) :: tl ->
104 let cic_body = do_branch' (name :: context) tl in
107 | None -> Cic.Implicit (Some `Type)
108 | Some typ -> aux loc context typ
110 Cic.Lambda (name, typ, cic_body)
112 do_branch' context args
114 let (indtype_uri, indtype_no) =
115 match indty_ident with
116 | Some indty_ident ->
117 (match resolve env (Id indty_ident) () with
118 | Cic.MutInd (uri, tyno, _) -> (uri, tyno)
119 | Cic.Implicit _ -> raise Try_again
120 | _ -> raise DisambiguateChoices.Invalid_choice)
122 let fst_constructor =
124 | ((head, _), _) :: _ -> head
125 | [] -> raise DisambiguateChoices.Invalid_choice
127 (match resolve env (Id fst_constructor) () with
128 | Cic.MutConstruct (indtype_uri, indtype_no, _, _) ->
129 (indtype_uri, indtype_no)
130 | Cic.Implicit _ -> raise Try_again
131 | _ -> raise DisambiguateChoices.Invalid_choice)
133 Cic.MutCase (indtype_uri, indtype_no, cic_outtype, cic_term,
134 (List.map do_branch branches))
135 | CicAst.LetIn ((name, typ), def, body) ->
136 let cic_def = aux loc context def in
140 | Some t -> Cic.Cast (cic_def, aux loc context t)
142 let cic_body = aux loc (name :: context) body in
143 Cic.LetIn (name, cic_def, cic_body)
144 | CicAst.LetRec (kind, defs, body) ->
146 List.fold_left (fun acc ((name, _), _, _) -> name :: acc)
149 let cic_body = aux loc context' body in
152 (fun ((name, typ), body, decr_idx) ->
153 let cic_body = aux loc context' body in
154 let cic_type = aux_option loc context typ in
158 CicTextualParser2.fail loc
159 "Recursive functions cannot be anonymous"
160 | Cic.Name name -> name
162 (name, decr_idx, cic_type, cic_body))
165 let counter = ref ~-1 in
166 let build_term funs =
167 (* this is the body of the fold_right function below. Rationale: Fix
168 * and CoFix cases differs only in an additional index in the
169 * inductiveFun list, see Cic.term *)
172 (fun (var, _, _, _) cic ->
174 Cic.LetIn (Cic.Name var, Cic.Fix (!counter, funs), cic))
177 List.map (fun (name, _, typ, body) -> (name, typ, body)) funs
179 (fun (var, _, _, _) cic ->
181 Cic.LetIn (Cic.Name var, Cic.CoFix (!counter, funs), cic))
183 List.fold_right (build_term inductiveFuns) inductiveFuns cic_body
184 | CicAst.Ident (name, subst) ->
186 let index = find_in_environment name context in
187 if subst <> None then
188 CicTextualParser2.fail loc
189 "Explicit substitutions not allowed here";
192 let cic = resolve env (Id name) () in
195 List.map (fun uri -> UriManager.name_of_uri uri, uri) uris
202 List.assoc s ids_to_uris, aux loc context term
204 raise DisambiguateChoices.Invalid_choice))
206 | None -> List.map (fun uri -> uri, Cic.Implicit None) uris)
209 | Cic.Const (uri, []) ->
211 match CicEnvironment.get_obj uri with
212 | Cic.Constant (_, _, _, uris) -> uris
215 Cic.Const (uri, mk_subst uris)
216 | Cic.Var (uri, []) ->
218 match CicEnvironment.get_obj uri with
219 | Cic.Variable (_, _, _, uris) -> uris
222 Cic.Var (uri, mk_subst uris)
223 | Cic.MutInd (uri, i, []) ->
225 match CicEnvironment.get_obj uri with
226 | Cic.InductiveDefinition (_, uris, _) -> uris
229 Cic.MutInd (uri, i, mk_subst uris)
230 | Cic.MutConstruct (uri, i, j, []) ->
232 match CicEnvironment.get_obj uri with
233 | Cic.InductiveDefinition (_, uris, _) -> uris
236 Cic.MutConstruct (uri, i, j, mk_subst uris)
237 | Cic.Meta _ | Cic.Implicit _ as t ->
239 prerr_endline (sprintf
240 "Warning: %s must be instantiated with _[%s] but we do not enforce it"
244 (fun (s, term) -> s ^ " := " ^ CicAstPp.pp_term term)
249 raise DisambiguateChoices.Invalid_choice))
250 | CicAst.Implicit -> Cic.Implicit None
251 | CicAst.Num (num, i) -> resolve env (Num i) ~num ()
252 | CicAst.Meta (index, subst) ->
255 (function None -> None | Some term -> Some (aux loc context term))
258 Cic.Meta (index, cic_subst)
259 | CicAst.Sort `Prop -> Cic.Sort Cic.Prop
260 | CicAst.Sort `Set -> Cic.Sort Cic.Set
261 | CicAst.Sort `Type -> Cic.Sort Cic.Type
262 | CicAst.Sort `CProp -> Cic.Sort Cic.CProp
263 | CicAst.Symbol (symbol, instance) ->
264 resolve env (Symbol (symbol, instance)) ()
265 and aux_option loc context = function
266 | None -> Cic.Implicit (Some `Type)
267 | Some term -> aux loc context term
270 | CicAst.AttributedTerm (`Loc loc, term) -> aux loc context term
271 | term -> aux (-1, -1) context term
273 let domain_of_term ~context ast =
274 (* "aux" keeps domain in reverse order and doesn't care about duplicates.
275 * Domain item more in deep in the list will be processed first.
277 let rec aux loc context = function
278 | CicAst.AttributedTerm (`Loc loc, term) -> aux loc context term
279 | CicAst.AttributedTerm (_, term) -> aux loc context term
280 | CicAst.Appl terms ->
281 List.fold_left (fun dom term -> aux loc context term @ dom) [] terms
282 | CicAst.Binder (kind, (var, typ), body) ->
285 | `Exists -> [ Symbol ("exists", 0) ]
288 let type_dom = aux_option loc context typ in
289 let body_dom = aux loc (var :: context) body in
290 body_dom @ type_dom @ kind_dom
291 | CicAst.Case (term, indty_ident, outtype, branches) ->
292 let term_dom = aux loc context term in
293 let outtype_dom = aux_option loc context outtype in
294 let do_branch ((head, args), term) =
295 let (term_context, args_domain) =
297 (fun (cont, dom) (name, typ) ->
301 | Some typ -> aux loc cont typ @ dom)))
304 args_domain @ aux loc term_context term
307 List.fold_left (fun dom branch -> do_branch branch @ dom) [] branches
309 branches_dom @ outtype_dom @ term_dom @
310 (match indty_ident with None -> [] | Some ident -> [ Id ident ])
311 | CicAst.LetIn ((var, typ), body, where) ->
312 let body_dom = aux loc context body in
313 let type_dom = aux_option loc context typ in
314 let where_dom = aux loc (var :: context) where in
315 where_dom @ type_dom @ body_dom
316 | CicAst.LetRec (kind, defs, where) ->
318 List.fold_left (fun acc ((var, typ), _, _) -> var :: acc)
321 let where_dom = aux loc context' where in
324 (fun dom ((_, typ), body, _) ->
325 aux loc context' body @ aux_option loc context typ)
329 | CicAst.Ident (name, subst) ->
331 let index = find_in_environment name context in
332 if subst <> None then
333 CicTextualParser2.fail loc
334 "Explicit substitutions not allowed here"
342 (fun dom (_, term) ->
343 let dom' = aux loc context term in
346 | CicAst.Implicit -> []
347 | CicAst.Num (num, i) -> [ Num i ]
348 | CicAst.Meta (index, local_context) ->
349 List.fold_left (fun dom term -> aux_option loc context term @ dom) []
351 | CicAst.Sort _ -> []
352 | CicAst.Symbol (symbol, instance) -> [ Symbol (symbol, instance) ]
354 and aux_option loc context = function
356 | Some t -> aux loc context t
359 (* e.g. [5;1;1;1;2;3;4;1;2] -> [2;1;4;3;5] *)
361 let module SortedItem =
363 type t = DisambiguateTypes.domain_item
364 let compare = Pervasives.compare
367 let module Set = Set.Make (SortedItem) in
369 let rev_l = List.rev l in
370 let (_, uniq_rev_l) =
372 (fun (members, rev_l) elt ->
373 if Set.mem elt members then
376 Set.add elt members, elt :: rev_l)
377 (Set.empty, []) rev_l
384 | CicAst.AttributedTerm (`Loc loc, term) -> aux loc context term
385 | term -> aux (-1, -1) context term)
389 let domain_diff dom1 dom2 =
390 (* let domain_diff = Domain.diff *)
392 List.fold_left (fun pred elt -> (fun elt' -> elt' = elt || pred elt'))
393 (fun _ -> false) dom2
395 List.filter (fun elt -> not (is_in_dom2 elt)) dom1
397 module Make (C: Callbacks) =
399 let choices_of_id mqi_handle id =
400 let query = MQueryGenerator.locate id in
401 let result = MQueryInterpreter.execute mqi_handle query in
405 MQueryMisc.wrong_xpointer_format_from_wrong_xpointer_format' uri
407 HelmLogger.log (`Msg (`T "Locate query:"));
408 MQueryUtil.text_of_query
409 (fun s -> HelmLogger.log ~append_NL:false (`Msg (`T s)))
411 HelmLogger.log (`Msg (`T "Result:"));
412 MQueryUtil.text_of_result
413 (fun s -> HelmLogger.log (`Msg (`T s))) "" result;
417 [UriManager.string_of_uri (C.input_or_locate_uri
418 ~title:("URI matching \"" ^ id ^ "\" unknown."))]
421 C.interactive_user_uri_choice ~selection_mode:`MULTIPLE
422 ~ok:"Try selected." ~enable_button_for_non_vars:true
423 ~title:"Ambiguous input." ~id
424 ~msg: ("Ambiguous input \"" ^ id ^
425 "\". Please, choose one or more interpretations:")
433 HelmLibraryObjects.term_of_uri (UriManager.uri_of_string uri)
434 with _ -> assert false
439 let disambiguate_term mqi_handle context metasenv term ~aliases:current_env
441 debug_print "NEW DISAMBIGUATE INPUT";
442 let disambiguate_context = (* cic context -> disambiguate context *)
444 (function None -> Cic.Anonymous | Some (name, _) -> name)
447 let term_dom = domain_of_term ~context:disambiguate_context term in
448 debug_print (sprintf "DISAMBIGUATION DOMAIN: %s"
449 (string_of_domain term_dom));
451 Environment.fold (fun item _ dom -> item :: dom) current_env []
453 let todo_dom = domain_diff term_dom current_dom in
454 (* (2) lookup function for any item (Id/Symbol/Num) *)
456 let id_choices = Hashtbl.create 1023 in
462 Hashtbl.find id_choices id
464 let choices = choices_of_id mqi_handle id in
465 Hashtbl.add id_choices id choices;
467 | Symbol (symb, _) -> DisambiguateChoices.lookup_symbol_choices symb
468 | Num instance -> DisambiguateChoices.lookup_num_choices ()
470 if choices = [] then raise (No_choices item);
473 (* (3) test an interpretation filling with meta uninterpreted identifiers
475 let test_env current_env todo_dom =
482 | Id _ | Num _ -> (fun _ _ _ -> Cic.Implicit (Some `Closed))
483 | Symbol _ -> (fun _ _ _ -> Cic.Implicit None))) env)
488 interpretate ~context:disambiguate_context ~env:filled_env term
490 refine metasenv context cic_term
492 | Try_again -> Uncertain
493 | DisambiguateChoices.Invalid_choice -> Ko
495 (* (4) build all possible interpretations *)
496 let rec aux current_env todo_dom =
499 (match test_env current_env [] with
500 | Ok (term, metasenv) -> [ current_env, metasenv, term ]
501 | Ko | Uncertain -> [])
502 | item :: remaining_dom ->
503 debug_print (sprintf "CHOOSED ITEM: %s"
504 (string_of_domain_item item));
505 let choices = lookup_choices item in
506 let rec filter = function
508 | codomain_item :: tl ->
509 debug_print (sprintf "%s CHOSEN" (fst codomain_item)) ;
511 Environment.add item codomain_item current_env
513 (match test_env new_env remaining_dom with
514 | Ok (term, metasenv) ->
515 (match remaining_dom with
516 | [] -> [ new_env, metasenv, term ]
517 | _ -> aux new_env remaining_dom) @ filter tl
519 (match remaining_dom with
521 | _ -> aux new_env remaining_dom) @ filter tl
526 match aux current_env todo_dom with
527 | [] -> raise NoWellTypedInterpretation
529 debug_print "UNA SOLA SCELTA";
532 debug_print (sprintf "PIU' SCELTE (%d)" (List.length l));
539 fst (Environment.find domain_item env)
541 (descr_of_domain_item domain_item, description))
545 let choosed = C.interactive_interpretation_choice choices in
546 List.map (List.nth l) choosed