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 debug_print ("%%% PRUNED!!! " ^ CicPp.ppterm term) ;
64 let resolve (env: environment) (item: domain_item) ?(num = "") ?(args = []) () =
65 snd (Environment.find item env) env num args
67 (* TODO move it to Cic *)
68 let find_in_environment name context =
69 let rec aux acc = function
70 | [] -> raise Not_found
71 | Cic.Name hd :: tl when hd = name -> acc
72 | _ :: tl -> aux (acc + 1) tl
76 let interpretate ~context ~env ast =
77 let rec aux loc context = function
78 | CicAst.AttributedTerm (`Loc loc, term) ->
80 | CicAst.AttributedTerm (_, term) -> aux loc context term
81 | CicAst.Appl (CicAst.Symbol (symb, i) :: args) ->
82 let cic_args = List.map (aux loc context) args in
83 resolve env (Symbol (symb, i)) ~args:cic_args ()
84 | CicAst.Appl terms -> Cic.Appl (List.map (aux loc context) terms)
85 | CicAst.Binder (binder_kind, (var, typ), body) ->
86 let cic_type = aux_option loc context typ in
87 let cic_body = aux loc (var :: context) body in
88 (match binder_kind with
89 | `Lambda -> Cic.Lambda (var, cic_type, cic_body)
90 | `Pi | `Forall -> Cic.Prod (var, cic_type, cic_body)
92 resolve env (Symbol ("exists", 0))
93 ~args:[ cic_type; Cic.Lambda (var, cic_type, cic_body) ] ())
94 | CicAst.Case (term, indty_ident, outtype, branches) ->
95 let cic_term = aux loc context term in
96 let cic_outtype = aux_option loc context outtype in
97 let do_branch ((head, args), term) =
98 let rec do_branch' context = function
99 | [] -> aux loc context term
100 | (name, typ) :: tl ->
101 let cic_body = do_branch' (name :: context) tl in
104 | None -> Cic.Implicit
105 | Some typ -> aux loc context typ
107 Cic.Lambda (name, typ, cic_body)
109 do_branch' context args
111 let (indtype_uri, indtype_no) =
112 match resolve env (Id indty_ident) () with
113 | Cic.MutInd (uri, tyno, _) -> uri, tyno
114 | Cic.Implicit -> raise Try_again
115 | _ -> raise DisambiguateChoices.Invalid_choice
117 Cic.MutCase (indtype_uri, indtype_no, cic_outtype, cic_term,
118 (List.map do_branch branches))
119 | CicAst.LetIn ((name, typ), def, body) ->
120 let cic_def = aux loc context def in
124 | Some t -> Cic.Cast (cic_def, aux loc context t)
126 let cic_body = aux loc (name :: context) body in
127 Cic.LetIn (name, cic_def, cic_body)
128 | CicAst.LetRec (kind, defs, body) ->
130 List.fold_left (fun acc ((name, _), _, _) -> name :: acc)
133 let cic_body = aux loc context' body in
136 (fun ((name, typ), body, decr_idx) ->
137 let cic_body = aux loc context' body in
138 let cic_type = aux_option loc context typ in
142 CicTextualParser2.fail loc
143 "Recursive functions cannot be anonymous"
144 | Cic.Name name -> name
146 (name, decr_idx, cic_type, cic_body))
149 let counter = ref ~-1 in
150 let build_term funs =
151 (* this is the body of the fold_right function below. Rationale: Fix
152 * and CoFix cases differs only in an additional index in the
153 * inductiveFun list, see Cic.term *)
156 (fun (var, _, _, _) cic ->
158 Cic.LetIn (Cic.Name var, Cic.Fix (!counter, funs), cic))
161 List.map (fun (name, _, typ, body) -> (name, typ, body)) funs
163 (fun (var, _, _, _) cic ->
165 Cic.LetIn (Cic.Name var, Cic.CoFix (!counter, funs), cic))
167 List.fold_right (build_term inductiveFuns) inductiveFuns cic_body
168 | CicAst.Ident (name, subst) ->
169 (* TODO hanlde explicit substitutions *)
171 let index = find_in_environment name context in
173 CicTextualParser2.fail loc
174 "Explicit substitutions not allowed here";
176 with Not_found -> resolve env (Id name) ())
177 | CicAst.Implicit -> Cic.Implicit
178 | CicAst.Num (num, i) -> resolve env (Num i) ~num ()
179 | CicAst.Meta (index, subst) ->
182 (function None -> None | Some term -> Some (aux loc context term))
185 Cic.Meta (index, cic_subst)
186 | CicAst.Sort `Prop -> Cic.Sort Cic.Prop
187 | CicAst.Sort `Set -> Cic.Sort Cic.Set
188 | CicAst.Sort `Type -> Cic.Sort Cic.Type
189 | CicAst.Sort `CProp -> Cic.Sort Cic.CProp
190 | CicAst.Symbol (symbol, instance) ->
191 resolve env (Symbol (symbol, instance)) ()
192 and aux_option loc context = function
193 | None -> Cic.Implicit
194 | Some term -> aux loc context term
197 | CicAst.AttributedTerm (`Loc loc, term) -> aux loc context term
200 let domain_of_term ~context ast =
201 (* "aux" keeps domain in reverse order and doesn't care about duplicates.
202 * Domain item more in deep in the list will be processed first.
204 let rec aux loc context = function
205 | CicAst.AttributedTerm (`Loc loc, term) -> aux loc context term
206 | CicAst.AttributedTerm (_, term) -> aux loc context term
207 | CicAst.Appl terms ->
208 List.fold_left (fun dom term -> aux loc context term @ dom) [] terms
209 | CicAst.Binder (_, (var, typ), body) ->
210 let type_dom = aux_option loc context typ in
211 let body_dom = aux loc (var :: context) body in
213 | CicAst.Case (term, indty_ident, outtype, branches) ->
214 let term_dom = aux loc context term in
215 let outtype_dom = aux_option loc context outtype in
216 let do_branch ((head, args), term) =
217 let (term_context, args_domain) =
219 (fun (cont, dom) (name, typ) ->
223 | Some typ -> aux loc cont typ @ dom)))
226 args_domain @ aux loc term_context term
229 List.fold_left (fun dom branch -> do_branch branch @ dom) [] branches
231 branches_dom @ outtype_dom @ term_dom @ [ Id indty_ident ]
232 | CicAst.LetIn ((var, typ), body, where) ->
233 let body_dom = aux loc context body in
234 let type_dom = aux_option loc context typ in
235 let where_dom = aux loc (var :: context) where in
236 where_dom @ type_dom @ body_dom
237 | CicAst.LetRec (kind, defs, where) ->
239 List.fold_left (fun acc ((var, typ), _, _) -> var :: acc)
242 let where_dom = aux loc context' where in
245 (fun dom ((_, typ), body, _) ->
246 aux loc context' body @ aux_option loc context typ)
250 | CicAst.Ident (name, subst) ->
251 (* TODO hanlde explicit substitutions *)
253 let index = find_in_environment name context in
255 CicTextualParser2.fail loc
256 "Explicit substitutions not allowed here";
258 with Not_found -> [ Id name ])
259 | CicAst.Implicit -> []
260 | CicAst.Num (num, i) -> [ Num i ]
261 | CicAst.Meta (index, local_context) ->
262 List.fold_left (fun dom term -> aux_option loc context term @ dom) []
264 | CicAst.Sort _ -> []
265 | CicAst.Symbol (symbol, instance) -> [ Symbol (symbol, instance) ]
267 and aux_option loc context = function
269 | Some t -> aux loc context t
272 (* e.g. [5;1;1;1;2;3;4;1;2] -> [2;1;4;3;5] *)
274 let module SortedItem =
276 type t = DisambiguateTypes.domain_item
277 let compare = Pervasives.compare
280 let module Set = Set.Make (SortedItem) in
282 let rev_l = List.rev l in
283 let (_, uniq_rev_l) =
285 (fun (members, rev_l) elt ->
286 if Set.mem elt members then
289 Set.add elt members, elt :: rev_l)
290 (Set.empty, []) rev_l
296 | CicAst.AttributedTerm (`Loc loc, term) -> rev_uniq (aux loc context term)
301 let domain_diff dom1 dom2 =
302 (* let domain_diff = Domain.diff *)
304 List.fold_left (fun pred elt -> (fun elt' -> elt' = elt || pred elt'))
305 (fun _ -> false) dom2
307 List.filter (fun elt -> not (is_in_dom2 elt)) dom1
309 module Make (C: Callbacks) =
311 let choices_of_id mqi_handle id =
312 let query = MQueryGenerator.locate id in
313 let result = MQueryInterpreter.execute mqi_handle query in
317 MQueryMisc.wrong_xpointer_format_from_wrong_xpointer_format' uri
319 C.output_html (`Msg (`T "Locate query:"));
320 MQueryUtil.text_of_query
321 (fun s -> C.output_html ~append_NL:false (`Msg (`T s)))
323 C.output_html (`Msg (`T "Result:"));
324 MQueryUtil.text_of_result
325 (fun s -> C.output_html (`Msg (`T s))) "" result;
329 [UriManager.string_of_uri (C.input_or_locate_uri
330 ~title:("URI matching \"" ^ id ^ "\" unknown."))]
333 C.interactive_user_uri_choice ~selection_mode:`MULTIPLE
334 ~ok:"Try selected." ~enable_button_for_non_vars:true
335 ~title:"Ambiguous input." ~id
336 ~msg: ("Ambiguous input \"" ^ id ^
337 "\". Please, choose one or more interpretations:")
345 HelmLibraryObjects.term_of_uri (UriManager.uri_of_string uri)
346 with _ -> assert false
351 let disambiguate_term mqi_handle context metasenv term ~aliases:current_env
353 debug_print "NEW DISAMBIGUATE INPUT";
354 let disambiguate_context = (* cic context -> disambiguate context *)
356 (function None -> Cic.Anonymous | Some (name, _) -> name)
359 let term_dom = domain_of_term ~context:disambiguate_context term in
360 debug_print (sprintf "DISAMBIGUATION DOMAIN: %s"
361 (string_of_domain term_dom));
363 Environment.fold (fun item _ dom -> item :: dom) current_env []
365 let todo_dom = domain_diff term_dom current_dom in
366 (* (2) lookup function for any item (Id/Symbol/Num) *)
368 let id_choices = Hashtbl.create 1023 in
374 Hashtbl.find id_choices id
376 let choices = choices_of_id mqi_handle id in
377 Hashtbl.add id_choices id choices;
379 | Symbol (symb, _) -> DisambiguateChoices.lookup_symbol_choices symb
380 | Num instance -> DisambiguateChoices.lookup_num_choices ()
382 if choices = [] then raise (No_choices item);
385 (* (3) test an interpretation filling with meta uninterpreted identifiers
387 let test_env current_env todo_dom =
391 Environment.add item ("Implicit", fun _ _ _ -> Cic.Implicit) env)
396 interpretate ~context:disambiguate_context ~env:filled_env term
398 refine metasenv context cic_term
400 | Try_again -> Uncertain
401 | DisambiguateChoices.Invalid_choice -> Ko
403 (* (4) build all possible interpretations *)
404 let rec aux current_env todo_dom =
407 (match test_env current_env [] with
408 | Ok (term, metasenv) -> [ current_env, term, metasenv ]
409 | Ko | Uncertain -> [])
410 | item :: remaining_dom ->
411 debug_print (sprintf "CHOOSED ITEM: %s"
412 (string_of_domain_item item));
413 let choices = lookup_choices item in
414 let rec filter = function
416 | codomain_item :: tl ->
417 debug_print (sprintf "%s CHOSEN" (fst codomain_item)) ;
419 Environment.add item codomain_item current_env
421 (match test_env new_env remaining_dom with
422 | Ok (term, metasenv) ->
423 (match remaining_dom with
424 | [] -> [ new_env, term, metasenv ]
425 | _ -> aux new_env remaining_dom) @ filter tl
427 (match remaining_dom with
429 | _ -> aux new_env remaining_dom) @ filter tl
434 let (choosed_env, choosed_term, choosed_metasenv) =
435 match aux current_env todo_dom with
436 | [] -> raise NoWellTypedInterpretation
438 debug_print "UNA SOLA SCELTA";
441 debug_print (sprintf "PIU' SCELTE (%d)" (List.length l));
448 fst (Environment.find domain_item env)
450 (descr_of_domain_item domain_item, description))
454 let choosed = C.interactive_interpretation_choice choices in
457 (choosed_env, choosed_metasenv, choosed_term)