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) ;
60 | CicRefine.RefineFailure _ ->
61 debug_print ("%%% PRUNED!!! " ^ CicPp.ppterm term) ;
64 let resolve (env: environment) (item: domain_item) ?(num = "") ?(args = []) () =
66 snd (Environment.find item env) env num args
67 with Not_found -> assert false
69 (* TODO move it to Cic *)
70 let find_in_environment name context =
71 let rec aux acc = function
72 | [] -> raise Not_found
73 | Cic.Name hd :: tl when hd = name -> acc
74 | _ :: tl -> aux (acc + 1) tl
78 let interpretate ~context ~env ast =
79 let rec aux loc context = function
80 | CicAst.AttributedTerm (`Loc loc, term) ->
82 | CicAst.AttributedTerm (_, term) -> aux loc context term
83 | CicAst.Appl (CicAst.Symbol (symb, i) :: args) ->
84 let cic_args = List.map (aux loc context) args in
85 resolve env (Symbol (symb, i)) ~args:cic_args ()
86 | CicAst.Appl terms -> Cic.Appl (List.map (aux loc context) terms)
87 | CicAst.Binder (binder_kind, (var, typ), body) ->
88 let cic_type = aux_option loc context typ in
89 let cic_body = aux loc (var :: context) body in
90 (match binder_kind with
91 | `Lambda -> Cic.Lambda (var, cic_type, cic_body)
92 | `Pi | `Forall -> Cic.Prod (var, cic_type, cic_body)
94 resolve env (Symbol ("exists", 0))
95 ~args:[ cic_type; Cic.Lambda (var, cic_type, cic_body) ] ())
96 | CicAst.Case (term, indty_ident, outtype, branches) ->
97 let cic_term = aux loc context term in
98 let cic_outtype = aux_option loc context outtype in
99 let do_branch ((head, args), term) =
100 let rec do_branch' context = function
101 | [] -> aux loc context term
102 | (name, typ) :: tl ->
103 let cic_body = do_branch' (name :: context) tl in
106 | None -> Cic.Implicit (Some `Type)
107 | Some typ -> aux loc context typ
109 Cic.Lambda (name, typ, cic_body)
111 do_branch' context args
113 let (indtype_uri, indtype_no) =
114 match indty_ident with
115 | Some indty_ident ->
116 (match resolve env (Id indty_ident) () with
117 | Cic.MutInd (uri, tyno, _) -> (uri, tyno)
118 | Cic.Implicit _ -> raise Try_again
119 | _ -> raise DisambiguateChoices.Invalid_choice)
121 let fst_constructor =
123 | ((head, _), _) :: _ -> head
124 | [] -> raise DisambiguateChoices.Invalid_choice
126 (match resolve env (Id fst_constructor) () with
127 | Cic.MutConstruct (indtype_uri, indtype_no, _, _) ->
128 (indtype_uri, indtype_no)
129 | Cic.Implicit _ -> raise Try_again
130 | _ -> raise DisambiguateChoices.Invalid_choice)
132 Cic.MutCase (indtype_uri, indtype_no, cic_outtype, cic_term,
133 (List.map do_branch branches))
134 | CicAst.LetIn ((name, typ), def, body) ->
135 let cic_def = aux loc context def in
139 | Some t -> Cic.Cast (cic_def, aux loc context t)
141 let cic_body = aux loc (name :: context) body in
142 Cic.LetIn (name, cic_def, cic_body)
143 | CicAst.LetRec (kind, defs, body) ->
145 List.fold_left (fun acc ((name, _), _, _) -> name :: acc)
148 let cic_body = aux loc context' body in
151 (fun ((name, typ), body, decr_idx) ->
152 let cic_body = aux loc context' body in
153 let cic_type = aux_option loc context typ in
157 CicTextualParser2.fail loc
158 "Recursive functions cannot be anonymous"
159 | Cic.Name name -> name
161 (name, decr_idx, cic_type, cic_body))
164 let counter = ref ~-1 in
165 let build_term funs =
166 (* this is the body of the fold_right function below. Rationale: Fix
167 * and CoFix cases differs only in an additional index in the
168 * inductiveFun list, see Cic.term *)
171 (fun (var, _, _, _) cic ->
173 Cic.LetIn (Cic.Name var, Cic.Fix (!counter, funs), cic))
176 List.map (fun (name, _, typ, body) -> (name, typ, body)) funs
178 (fun (var, _, _, _) cic ->
180 Cic.LetIn (Cic.Name var, Cic.CoFix (!counter, funs), cic))
182 List.fold_right (build_term inductiveFuns) inductiveFuns cic_body
183 | CicAst.Ident (name, subst) ->
185 let index = find_in_environment name context in
186 if subst <> None then
187 CicTextualParser2.fail loc
188 "Explicit substitutions not allowed here";
191 let cic = resolve env (Id name) () in
194 List.map (fun uri -> UriManager.name_of_uri uri, uri) uris
201 List.assoc s ids_to_uris, aux loc context term
203 raise DisambiguateChoices.Invalid_choice))
205 | None -> List.map (fun uri -> uri, Cic.Implicit None) uris)
208 | Cic.Const (uri, []) ->
210 match CicEnvironment.get_obj uri with
211 | Cic.Constant (_, _, _, uris) -> uris
214 Cic.Const (uri, mk_subst uris)
215 | Cic.Var (uri, []) ->
217 match CicEnvironment.get_obj uri with
218 | Cic.Variable (_, _, _, uris) -> uris
221 Cic.Var (uri, mk_subst uris)
222 | Cic.MutInd (uri, i, []) ->
224 match CicEnvironment.get_obj uri with
225 | Cic.InductiveDefinition (_, uris, _) -> uris
228 Cic.MutInd (uri, i, mk_subst uris)
229 | Cic.MutConstruct (uri, i, j, []) ->
231 match CicEnvironment.get_obj uri with
232 | Cic.InductiveDefinition (_, uris, _) -> uris
235 Cic.MutConstruct (uri, i, j, mk_subst uris)
236 | Cic.Meta _ | Cic.Implicit _ as t ->
238 prerr_endline (sprintf
239 "Warning: %s must be instantiated with _[%s] but we do not enforce it"
243 (fun (s, term) -> s ^ " := " ^ CicAstPp.pp_term term)
248 raise DisambiguateChoices.Invalid_choice))
249 | CicAst.Implicit -> Cic.Implicit None
250 | CicAst.Num (num, i) -> resolve env (Num i) ~num ()
251 | CicAst.Meta (index, subst) ->
254 (function None -> None | Some term -> Some (aux loc context term))
257 Cic.Meta (index, cic_subst)
258 | CicAst.Sort `Prop -> Cic.Sort Cic.Prop
259 | CicAst.Sort `Set -> Cic.Sort Cic.Set
260 | CicAst.Sort `Type -> Cic.Sort (Cic.Type (CicUniv.fresh())) (* TASSI *)
261 | CicAst.Sort `CProp -> Cic.Sort Cic.CProp
262 | CicAst.Symbol (symbol, instance) ->
263 resolve env (Symbol (symbol, instance)) ()
264 and aux_option loc context = function
265 | None -> Cic.Implicit (Some `Type)
266 | Some term -> aux loc context term
269 | CicAst.AttributedTerm (`Loc loc, term) -> aux loc context term
270 | term -> aux (-1, -1) context term
272 let domain_of_term ~context ast =
273 (* "aux" keeps domain in reverse order and doesn't care about duplicates.
274 * Domain item more in deep in the list will be processed first.
276 let rec aux loc context = function
277 | CicAst.AttributedTerm (`Loc loc, term) -> aux loc context term
278 | CicAst.AttributedTerm (_, term) -> aux loc context term
279 | CicAst.Appl terms ->
280 List.fold_left (fun dom term -> aux loc context term @ dom) [] terms
281 | CicAst.Binder (kind, (var, typ), body) ->
284 | `Exists -> [ Symbol ("exists", 0) ]
287 let type_dom = aux_option loc context typ in
288 let body_dom = aux loc (var :: context) body in
289 body_dom @ type_dom @ kind_dom
290 | CicAst.Case (term, indty_ident, outtype, branches) ->
291 let term_dom = aux loc context term in
292 let outtype_dom = aux_option loc context outtype in
293 let do_branch ((head, args), term) =
294 let (term_context, args_domain) =
296 (fun (cont, dom) (name, typ) ->
300 | Some typ -> aux loc cont typ @ dom)))
303 args_domain @ aux loc term_context term
306 List.fold_left (fun dom branch -> do_branch branch @ dom) [] branches
308 branches_dom @ outtype_dom @ term_dom @
309 (match indty_ident with None -> [] | Some ident -> [ Id ident ])
310 | CicAst.LetIn ((var, typ), body, where) ->
311 let body_dom = aux loc context body in
312 let type_dom = aux_option loc context typ in
313 let where_dom = aux loc (var :: context) where in
314 where_dom @ type_dom @ body_dom
315 | CicAst.LetRec (kind, defs, where) ->
317 List.fold_left (fun acc ((var, typ), _, _) -> var :: acc)
320 let where_dom = aux loc context' where in
323 (fun dom ((_, typ), body, _) ->
324 aux loc context' body @ aux_option loc context typ)
328 | CicAst.Ident (name, subst) ->
330 let index = find_in_environment name context in
331 if subst <> None then
332 CicTextualParser2.fail loc
333 "Explicit substitutions not allowed here"
341 (fun dom (_, term) ->
342 let dom' = aux loc context term in
345 | CicAst.Implicit -> []
346 | CicAst.Num (num, i) -> [ Num i ]
347 | CicAst.Meta (index, local_context) ->
348 List.fold_left (fun dom term -> aux_option loc context term @ dom) []
350 | CicAst.Sort _ -> []
351 | CicAst.Symbol (symbol, instance) -> [ Symbol (symbol, instance) ]
353 and aux_option loc context = function
355 | Some t -> aux loc context t
358 (* e.g. [5;1;1;1;2;3;4;1;2] -> [2;1;4;3;5] *)
360 let module SortedItem =
362 type t = DisambiguateTypes.domain_item
363 let compare = Pervasives.compare
366 let module Set = Set.Make (SortedItem) in
368 let rev_l = List.rev l in
369 let (_, uniq_rev_l) =
371 (fun (members, rev_l) elt ->
372 if Set.mem elt members then
375 Set.add elt members, elt :: rev_l)
376 (Set.empty, []) rev_l
383 | CicAst.AttributedTerm (`Loc loc, term) -> aux loc context term
384 | term -> aux (-1, -1) context term)
388 let domain_diff dom1 dom2 =
389 (* let domain_diff = Domain.diff *)
391 List.fold_left (fun pred elt -> (fun elt' -> elt' = elt || pred elt'))
392 (fun _ -> false) dom2
394 List.filter (fun elt -> not (is_in_dom2 elt)) dom1
396 module Make (C: Callbacks) =
398 let choices_of_id mqi_handle id =
399 let query = MQueryGenerator.locate id in
400 let result = MQueryInterpreter.execute mqi_handle query in
404 MQueryMisc.wrong_xpointer_format_from_wrong_xpointer_format' uri
409 [UriManager.string_of_uri (C.input_or_locate_uri
410 ~title:("URI matching \"" ^ id ^ "\" unknown.") ~id ())]
413 C.interactive_user_uri_choice ~selection_mode:`MULTIPLE
414 ~ok:"Try selected." ~enable_button_for_non_vars:true
415 ~title:"Ambiguous input." ~id
416 ~msg: ("Ambiguous input \"" ^ id ^
417 "\". Please, choose one or more interpretations:")
425 HelmLibraryObjects.term_of_uri (UriManager.uri_of_string uri)
426 with _ -> assert false
431 let disambiguate_term mqi_handle context metasenv term ~aliases:current_env
433 debug_print "NEW DISAMBIGUATE INPUT";
434 let disambiguate_context = (* cic context -> disambiguate context *)
436 (function None -> Cic.Anonymous | Some (name, _) -> name)
439 let term_dom = domain_of_term ~context:disambiguate_context term in
440 debug_print (sprintf "DISAMBIGUATION DOMAIN: %s"
441 (string_of_domain term_dom));
443 Environment.fold (fun item _ dom -> item :: dom) current_env []
445 let todo_dom = domain_diff term_dom current_dom in
446 (* (2) lookup function for any item (Id/Symbol/Num) *)
448 let id_choices = Hashtbl.create 1023 in
454 Hashtbl.find id_choices id
456 let choices = choices_of_id mqi_handle id in
457 Hashtbl.add id_choices id choices;
459 | Symbol (symb, _) -> DisambiguateChoices.lookup_symbol_choices symb
460 | Num instance -> DisambiguateChoices.lookup_num_choices ()
462 if choices = [] then raise (No_choices item);
465 (* (3) test an interpretation filling with meta uninterpreted identifiers
467 let test_env current_env todo_dom =
474 | Id _ | Num _ -> (fun _ _ _ -> Cic.Implicit (Some `Closed))
475 | Symbol _ -> (fun _ _ _ -> Cic.Implicit None))) env)
480 interpretate ~context:disambiguate_context ~env:filled_env term
482 refine metasenv context cic_term
484 | Try_again -> Uncertain
485 | DisambiguateChoices.Invalid_choice -> Ko
487 (* (4) build all possible interpretations *)
488 let rec aux current_env todo_dom =
491 (match test_env current_env [] with
492 | Ok (term, metasenv) -> [ current_env, metasenv, term ]
493 | Ko | Uncertain -> [])
494 | item :: remaining_dom ->
495 debug_print (sprintf "CHOOSED ITEM: %s"
496 (string_of_domain_item item));
497 let choices = lookup_choices item in
498 let rec filter = function
500 | codomain_item :: tl ->
501 debug_print (sprintf "%s CHOSEN" (fst codomain_item)) ;
503 Environment.add item codomain_item current_env
505 (match test_env new_env remaining_dom with
506 | Ok (term, metasenv) ->
507 (match remaining_dom with
508 | [] -> [ new_env, metasenv, term ]
509 | _ -> aux new_env remaining_dom) @ filter tl
511 (match remaining_dom with
513 | _ -> aux new_env remaining_dom) @ filter tl
518 match aux current_env todo_dom with
519 | [] -> raise NoWellTypedInterpretation
521 debug_print "UNA SOLA SCELTA";
524 debug_print (sprintf "PIU' SCELTE (%d)" (List.length l));
531 fst (Environment.find domain_item env)
533 (descr_of_domain_item domain_item, description))
537 let choosed = C.interactive_interpretation_choice choices in
538 List.map (List.nth l) choosed