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 = []) () =
66 snd (Environment.find item env) env num args
68 (* TODO move it to Cic *)
69 let find_in_environment name context =
70 let rec aux acc = function
71 | [] -> raise Not_found
72 | Cic.Name hd :: tl when hd = name -> acc
73 | _ :: tl -> aux (acc + 1) tl
77 let interpretate ~context ~env ast =
78 let rec aux loc context = function
79 | CicAst.AttributedTerm (`Loc loc, term) ->
81 | CicAst.AttributedTerm (_, term) -> aux loc context term
82 | CicAst.Appl (CicAst.Symbol (symb, i) :: args) ->
83 let cic_args = List.map (aux loc context) args in
84 resolve env (Symbol (symb, i)) ~args:cic_args ()
85 | CicAst.Appl terms -> Cic.Appl (List.map (aux loc context) terms)
86 | CicAst.Binder (binder_kind, (var, typ), body) ->
87 let cic_type = aux_option loc context typ in
88 let cic_body = aux loc (var :: context) body in
89 (match binder_kind with
90 | `Lambda -> Cic.Lambda (var, cic_type, cic_body)
91 | `Pi | `Forall -> Cic.Prod (var, cic_type, cic_body)
93 resolve env (Symbol ("exists", 0))
94 ~args:[ cic_type; Cic.Lambda (var, cic_type, cic_body) ] ())
95 | CicAst.Case (term, indty_ident, outtype, branches) ->
96 let cic_term = aux loc context term in
97 let cic_outtype = aux_option loc context outtype in
98 let do_branch ((head, args), term) =
99 let rec do_branch' context = function
100 | [] -> aux loc context term
101 | (name, typ) :: tl ->
102 let cic_body = do_branch' (name :: context) tl in
105 | None -> Cic.Implicit
106 | Some typ -> aux loc context typ
108 Cic.Lambda (name, typ, cic_body)
110 do_branch' context args
112 let (indtype_uri, indtype_no) =
113 match resolve env (Id indty_ident) () with
114 | Cic.MutInd (uri, tyno, _) -> uri, tyno
115 | Cic.Implicit -> raise Try_again
116 | _ -> raise DisambiguateChoices.Invalid_choice
118 Cic.MutCase (indtype_uri, indtype_no, cic_outtype, cic_term,
119 (List.map do_branch branches))
120 | CicAst.LetIn ((name, typ), def, body) ->
121 let cic_def = aux loc context def in
125 | Some t -> Cic.Cast (cic_def, aux loc context t)
127 let cic_body = aux loc (name :: context) body in
128 Cic.LetIn (name, cic_def, cic_body)
129 | CicAst.LetRec (kind, defs, body) ->
131 List.fold_left (fun acc ((name, _), _, _) -> name :: acc)
134 let cic_body = aux loc context' body in
137 (fun ((name, typ), body, decr_idx) ->
138 let cic_body = aux loc context' body in
139 let cic_type = aux_option loc context typ in
143 CicTextualParser2.fail loc
144 "Recursive functions cannot be anonymous"
145 | Cic.Name name -> name
147 (name, decr_idx, cic_type, cic_body))
150 let counter = ref ~-1 in
151 let build_term funs =
152 (* this is the body of the fold_right function below. Rationale: Fix
153 * and CoFix cases differs only in an additional index in the
154 * inductiveFun list, see Cic.term *)
157 (fun (var, _, _, _) cic ->
159 Cic.LetIn (Cic.Name var, Cic.Fix (!counter, funs), cic))
162 List.map (fun (name, _, typ, body) -> (name, typ, body)) funs
164 (fun (var, _, _, _) cic ->
166 Cic.LetIn (Cic.Name var, Cic.CoFix (!counter, funs), cic))
168 List.fold_right (build_term inductiveFuns) inductiveFuns cic_body
169 | CicAst.Ident (name, subst) ->
170 (* TODO hanlde explicit substitutions *)
172 let index = find_in_environment name context in
174 CicTextualParser2.fail loc
175 "Explicit substitutions not allowed here";
177 with Not_found -> resolve env (Id name) ())
178 | CicAst.Implicit -> Cic.Implicit
179 | CicAst.Num (num, i) -> resolve env (Num i) ~num ()
180 | CicAst.Meta (index, subst) ->
183 (function None -> None | Some term -> Some (aux loc context term))
186 Cic.Meta (index, cic_subst)
187 | CicAst.Sort `Prop -> Cic.Sort Cic.Prop
188 | CicAst.Sort `Set -> Cic.Sort Cic.Set
189 | CicAst.Sort `Type -> Cic.Sort Cic.Type
190 | CicAst.Sort `CProp -> Cic.Sort Cic.CProp
191 | CicAst.Symbol (symbol, instance) ->
192 resolve env (Symbol (symbol, instance)) ()
193 and aux_option loc context = function
194 | None -> Cic.Implicit
195 | Some term -> aux loc context term
198 | CicAst.AttributedTerm (`Loc loc, term) -> aux loc context term
199 | term -> aux (-1, -1) context term
201 let domain_of_term ~context ast =
202 (* "aux" keeps domain in reverse order and doesn't care about duplicates.
203 * Domain item more in deep in the list will be processed first.
205 let rec aux loc context = function
206 | CicAst.AttributedTerm (`Loc loc, term) -> aux loc context term
207 | CicAst.AttributedTerm (_, term) -> aux loc context term
208 | CicAst.Appl terms ->
209 List.fold_left (fun dom term -> aux loc context term @ dom) [] terms
210 | CicAst.Binder (_, (var, typ), body) ->
211 let type_dom = aux_option loc context typ in
212 let body_dom = aux loc (var :: context) body in
214 | CicAst.Case (term, indty_ident, outtype, branches) ->
215 let term_dom = aux loc context term in
216 let outtype_dom = aux_option loc context outtype in
217 let do_branch ((head, args), term) =
218 let (term_context, args_domain) =
220 (fun (cont, dom) (name, typ) ->
224 | Some typ -> aux loc cont typ @ dom)))
227 args_domain @ aux loc term_context term
230 List.fold_left (fun dom branch -> do_branch branch @ dom) [] branches
232 branches_dom @ outtype_dom @ term_dom @ [ Id indty_ident ]
233 | CicAst.LetIn ((var, typ), body, where) ->
234 let body_dom = aux loc context body in
235 let type_dom = aux_option loc context typ in
236 let where_dom = aux loc (var :: context) where in
237 where_dom @ type_dom @ body_dom
238 | CicAst.LetRec (kind, defs, where) ->
240 List.fold_left (fun acc ((var, typ), _, _) -> var :: acc)
243 let where_dom = aux loc context' where in
246 (fun dom ((_, typ), body, _) ->
247 aux loc context' body @ aux_option loc context typ)
251 | CicAst.Ident (name, subst) ->
252 (* TODO hanlde explicit substitutions *)
254 let index = find_in_environment name context in
256 CicTextualParser2.fail loc
257 "Explicit substitutions not allowed here";
259 with Not_found -> [ Id name ])
260 | CicAst.Implicit -> []
261 | CicAst.Num (num, i) -> [ Num i ]
262 | CicAst.Meta (index, local_context) ->
263 List.fold_left (fun dom term -> aux_option loc context term @ dom) []
265 | CicAst.Sort _ -> []
266 | CicAst.Symbol (symbol, instance) -> [ Symbol (symbol, instance) ]
268 and aux_option loc context = function
270 | Some t -> aux loc context t
273 (* e.g. [5;1;1;1;2;3;4;1;2] -> [2;1;4;3;5] *)
275 let module SortedItem =
277 type t = DisambiguateTypes.domain_item
278 let compare = Pervasives.compare
281 let module Set = Set.Make (SortedItem) in
283 let rev_l = List.rev l in
284 let (_, uniq_rev_l) =
286 (fun (members, rev_l) elt ->
287 if Set.mem elt members then
290 Set.add elt members, elt :: rev_l)
291 (Set.empty, []) rev_l
298 | CicAst.AttributedTerm (`Loc loc, term) -> aux loc context term
299 | term -> aux (-1, -1) context term)
303 let domain_diff dom1 dom2 =
304 (* let domain_diff = Domain.diff *)
306 List.fold_left (fun pred elt -> (fun elt' -> elt' = elt || pred elt'))
307 (fun _ -> false) dom2
309 List.filter (fun elt -> not (is_in_dom2 elt)) dom1
311 module Make (C: Callbacks) =
313 let choices_of_id mqi_handle id =
314 let query = MQueryGenerator.locate id in
315 let result = MQueryInterpreter.execute mqi_handle query in
319 MQueryMisc.wrong_xpointer_format_from_wrong_xpointer_format' uri
321 C.output_html (`Msg (`T "Locate query:"));
322 MQueryUtil.text_of_query
323 (fun s -> C.output_html ~append_NL:false (`Msg (`T s)))
325 C.output_html (`Msg (`T "Result:"));
326 MQueryUtil.text_of_result
327 (fun s -> C.output_html (`Msg (`T s))) "" result;
331 [UriManager.string_of_uri (C.input_or_locate_uri
332 ~title:("URI matching \"" ^ id ^ "\" unknown."))]
335 C.interactive_user_uri_choice ~selection_mode:`MULTIPLE
336 ~ok:"Try selected." ~enable_button_for_non_vars:true
337 ~title:"Ambiguous input." ~id
338 ~msg: ("Ambiguous input \"" ^ id ^
339 "\". Please, choose one or more interpretations:")
347 HelmLibraryObjects.term_of_uri (UriManager.uri_of_string uri)
348 with _ -> assert false
353 let disambiguate_term mqi_handle context metasenv term ~aliases:current_env
355 debug_print "NEW DISAMBIGUATE INPUT";
356 let disambiguate_context = (* cic context -> disambiguate context *)
358 (function None -> Cic.Anonymous | Some (name, _) -> name)
361 let term_dom = domain_of_term ~context:disambiguate_context term in
362 debug_print (sprintf "DISAMBIGUATION DOMAIN: %s"
363 (string_of_domain term_dom));
365 Environment.fold (fun item _ dom -> item :: dom) current_env []
367 let todo_dom = domain_diff term_dom current_dom in
368 (* (2) lookup function for any item (Id/Symbol/Num) *)
370 let id_choices = Hashtbl.create 1023 in
376 Hashtbl.find id_choices id
378 let choices = choices_of_id mqi_handle id in
379 Hashtbl.add id_choices id choices;
381 | Symbol (symb, _) -> DisambiguateChoices.lookup_symbol_choices symb
382 | Num instance -> DisambiguateChoices.lookup_num_choices ()
384 if choices = [] then raise (No_choices item);
387 (* (3) test an interpretation filling with meta uninterpreted identifiers
389 let test_env current_env todo_dom =
393 Environment.add item ("Implicit", fun _ _ _ -> Cic.Implicit) env)
398 interpretate ~context:disambiguate_context ~env:filled_env term
400 refine metasenv context cic_term
402 | Try_again -> Uncertain
403 | DisambiguateChoices.Invalid_choice -> Ko
405 (* (4) build all possible interpretations *)
406 let rec aux current_env todo_dom =
409 (match test_env current_env [] with
410 | Ok (term, metasenv) -> [ current_env, term, metasenv ]
411 | Ko | Uncertain -> [])
412 | item :: remaining_dom ->
413 debug_print (sprintf "CHOOSED ITEM: %s"
414 (string_of_domain_item item));
415 let choices = lookup_choices item in
416 let rec filter = function
418 | codomain_item :: tl ->
419 debug_print (sprintf "%s CHOSEN" (fst codomain_item)) ;
421 Environment.add item codomain_item current_env
423 (match test_env new_env remaining_dom with
424 | Ok (term, metasenv) ->
425 (match remaining_dom with
426 | [] -> [ new_env, term, metasenv ]
427 | _ -> aux new_env remaining_dom) @ filter tl
429 (match remaining_dom with
431 | _ -> aux new_env remaining_dom) @ filter tl
436 let (choosed_env, choosed_term, choosed_metasenv) =
437 match aux current_env todo_dom with
438 | [] -> raise NoWellTypedInterpretation
440 debug_print "UNA SOLA SCELTA";
443 debug_print (sprintf "PIU' SCELTE (%d)" (List.length l));
450 fst (Environment.find domain_item env)
452 (descr_of_domain_item domain_item, description))
456 let choosed = C.interactive_interpretation_choice choices in
459 (choosed_env, choosed_metasenv, choosed_term)