]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/cic_disambiguation/disambiguate.ml
- removed ancient refine exception
[helm.git] / helm / ocaml / cic_disambiguation / disambiguate.ml
1 (* Copyright (C) 2004, HELM Team.
2  * 
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.
6  * 
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.
11  * 
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.
16  *
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,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://helm.cs.unibo.it/
24  *)
25
26 open Printf
27
28 open DisambiguateTypes
29 open UriManager
30
31 exception No_choices of domain_item
32 exception NoWellTypedInterpretation
33
34   (** raised when an environment is not enough informative to decide *)
35 exception Try_again
36
37 let debug = true
38 let debug_print = if debug then prerr_endline else ignore
39
40 let descr_of_domain_item = function
41  | Id s -> s
42  | Symbol (s, _) -> s
43  | Num i -> string_of_int i
44
45 type test_result =
46   | Ok of Cic.term * Cic.metasenv
47   | Ko
48   | Uncertain
49
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));
53   try
54     let term', _, _, metasenv' = CicRefine.type_of_aux' metasenv context term in
55     Ok (term', metasenv')
56   with
57     | CicRefine.Uncertain _ ->
58         debug_print ("%%% UNCERTAIN!!! " ^ CicPp.ppterm term) ;
59         Uncertain
60     | _ ->
61         debug_print ("%%% PRUNED!!! " ^ CicPp.ppterm term) ;
62         Ko
63
64 let resolve (env: environment) (item: domain_item) ?(num = "") ?(args = []) () =
65   snd (Environment.find item env) env num args
66
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
73   in
74   aux 1 context
75
76 let interpretate ~context ~env ast =
77   let rec aux loc context = function
78     | CicTextualParser2Ast.LocatedTerm (loc, term) -> aux loc context term
79     | CicTextualParser2Ast.Appl terms -> Cic.Appl (List.map (aux loc context) terms)
80     | CicTextualParser2Ast.Appl_symbol (symb, i, args) ->
81         let cic_args = List.map (aux loc context) args in
82         resolve env (Symbol (symb, i)) ~args:cic_args ()
83     | CicTextualParser2Ast.Binder (binder_kind, var, typ, body) ->
84         let cic_type = aux_option loc context typ in
85         let cic_body = aux loc (var :: context) body in
86         (match binder_kind with
87         | `Lambda -> Cic.Lambda (var, cic_type, cic_body)
88         | `Pi | `Forall -> Cic.Prod (var, cic_type, cic_body)
89         | `Exists ->
90             resolve env (Symbol ("exists", 0))
91               ~args:[ cic_type; Cic.Lambda (var, cic_type, cic_body) ] ())
92     | CicTextualParser2Ast.Case (term, indty_ident, outtype, branches) ->
93         let cic_term = aux loc context term in
94         let cic_outtype = aux_option loc context outtype in
95         let do_branch (pat, term) =
96           let rec do_branch' context = function
97             | [] -> aux loc context term
98             | hd :: tl ->
99                 let cic_body = do_branch' (Cic.Name hd :: context) tl in
100                 Cic.Lambda (Cic.Name hd, Cic.Implicit, cic_body)
101           in
102           match pat with
103           | _ :: tl -> (* ignoring constructor *) do_branch' context tl
104           | [] -> assert false
105         in
106         let (indtype_uri, indtype_no) =
107           match resolve env (Id indty_ident) () with
108           | Cic.MutInd (uri, tyno, _) -> uri, tyno
109           | Cic.Implicit -> raise Try_again
110           | _ -> raise DisambiguateChoices.Invalid_choice
111         in
112         Cic.MutCase (indtype_uri, indtype_no, cic_outtype, cic_term,
113           (List.map do_branch branches))
114     | CicTextualParser2Ast.LetIn (var, def, body) ->
115         let cic_def = aux loc context def in
116         let name = Cic.Name var in
117         let cic_body = aux loc (name :: context) body in
118         Cic.LetIn (name, cic_def, cic_body)
119     | CicTextualParser2Ast.LetRec (kind, defs, body) ->
120         let context' =
121           List.fold_left (fun acc (var, _, _, _) -> Cic.Name var :: acc)
122             context defs
123         in
124         let cic_body = aux loc context' body in
125         let inductiveFuns =
126           List.map
127             (fun (var, body, typ, decr_idx) ->
128               let cic_body = aux loc context' body in
129               let cic_type = aux_option loc context typ in
130               (var, decr_idx, cic_type, cic_body))
131             defs
132         in
133         let counter = ref 0 in
134         let build_term funs =
135           (* this is the body of the fold_right function below. Rationale: Fix
136            * and CoFix cases differs only in an additional index in the
137            * indcutiveFun list, see Cic.term *)
138           match kind with
139           | `Inductive ->
140               (fun (var, _, _, _) cic ->
141                 incr counter;
142                 Cic.LetIn (Cic.Name var, Cic.Fix (!counter, funs), cic))
143           | `CoInductive ->
144               let funs =
145                 List.map (fun (name, _, typ, body) -> (name, typ, body)) funs
146               in
147               (fun (var, _, _, _) cic ->
148                 Cic.LetIn (Cic.Name var, Cic.CoFix (!counter, funs), cic))
149         in
150         List.fold_right (build_term inductiveFuns) inductiveFuns cic_body
151     | CicTextualParser2Ast.Ident (name, subst) ->
152         (* TODO hanlde explicit substitutions *)
153         (try
154           let index = find_in_environment name context in
155           if subst <> [] then
156             CicTextualParser2.fail loc "Explicit substitutions not allowed here";
157           Cic.Rel index
158         with Not_found -> resolve env (Id name) ())
159     | CicTextualParser2Ast.Num (num, i) -> resolve env (Num i) ~num ()
160     | CicTextualParser2Ast.Meta (index, subst) ->
161         let cic_subst =
162           List.map
163             (function None -> None | Some term -> Some (aux loc context term))
164             subst
165         in
166         Cic.Meta (index, cic_subst)
167     | CicTextualParser2Ast.Sort `Prop -> Cic.Sort Cic.Prop
168     | CicTextualParser2Ast.Sort `Set -> Cic.Sort Cic.Set
169     | CicTextualParser2Ast.Sort `Type -> Cic.Sort Cic.Type
170     | CicTextualParser2Ast.Sort `CProp -> Cic.Sort Cic.CProp
171   and aux_option loc context = function
172     | None -> Cic.Implicit
173     | Some term -> aux loc context term
174   in
175   match ast with
176   | CicTextualParser2Ast.LocatedTerm (loc, term) -> aux loc context term
177   | _ -> assert false
178
179 let domain_of_term ~context ast =
180   let rec aux loc context = function
181     | CicTextualParser2Ast.LocatedTerm (_, term) -> aux loc context term
182     | CicTextualParser2Ast.Appl terms ->
183         List.fold_left (fun dom term -> Domain.union dom (aux loc context term))
184           Domain.empty terms
185     | CicTextualParser2Ast.Appl_symbol (symb, i, args) ->
186         List.fold_left (fun dom term -> Domain.union dom (aux loc context term))
187           (Domain.singleton (Symbol (symb, i))) args
188     | CicTextualParser2Ast.Binder (_, var, typ, body) ->
189         let type_dom = aux_option loc context typ in
190         let body_dom = aux loc (var :: context) body in
191         Domain.union type_dom body_dom
192     | CicTextualParser2Ast.Case (term, indty_ident, outtype, branches) ->
193         let term_dom = aux loc context term in
194         let outtype_dom = aux_option loc context outtype in
195         let do_branch (pat, term) =
196           match pat with
197           | _ :: tl ->
198               aux loc
199                 (List.fold_left (fun acc var -> (Cic.Name var) :: acc)
200                   context tl)
201                 term
202           | [] -> assert false
203         in
204         let branches_dom =
205           List.fold_left (fun dom branch -> Domain.union dom (do_branch branch))
206             Domain.empty branches
207         in
208         Domain.add (Id indty_ident)
209           (Domain.union outtype_dom (Domain.union term_dom branches_dom))
210     | CicTextualParser2Ast.LetIn (var, body, where) ->
211         let body_dom = aux loc context body in
212         let where_dom = aux loc (Cic.Name var :: context) where in
213         Domain.union body_dom where_dom
214     | CicTextualParser2Ast.LetRec (kind, defs, where) ->
215         let context' =
216           List.fold_left (fun acc (var, _, _, _) -> Cic.Name var :: acc)
217             context defs
218         in
219         let where_dom = aux loc context' where in
220         let defs_dom =
221           List.fold_left
222             (fun dom (_, body, typ, _) ->
223               Domain.union (aux loc context' body) (aux_option loc context typ))
224             Domain.empty defs
225         in
226         Domain.union where_dom defs_dom
227     | CicTextualParser2Ast.Ident (name, subst) ->
228         (* TODO hanlde explicit substitutions *)
229         (try
230           let index = find_in_environment name context in
231           if subst <> [] then
232             CicTextualParser2.fail loc "Explicit substitutions not allowed here";
233           Domain.empty
234         with Not_found -> Domain.singleton (Id name))
235     | CicTextualParser2Ast.Num (num, i) -> Domain.singleton (Num i)
236     | CicTextualParser2Ast.Meta (index, local_context) ->
237         List.fold_left
238           (fun dom term -> Domain.union dom (aux_option loc context term))
239             Domain.empty local_context
240     | CicTextualParser2Ast.Sort _ -> Domain.empty
241   and aux_option loc context = function
242     | None -> Domain.empty
243     | Some t -> aux loc context t
244   in
245   match ast with
246   | CicTextualParser2Ast.LocatedTerm (loc, term) -> aux loc context term
247   | _ -> assert false
248
249 module Make (C: Callbacks) =
250   struct
251     let choices_of_id mqi_handle id =
252      let query  =  MQueryGenerator.locate id in
253      let result = MQueryInterpreter.execute mqi_handle query in
254      let uris =
255       List.map
256        (function uri,_ ->
257          MQueryMisc.wrong_xpointer_format_from_wrong_xpointer_format' uri
258        ) result in
259       C.output_html (`Msg (`T "Locate query:"));
260       MQueryUtil.text_of_query
261        (fun s -> C.output_html ~append_NL:false (`Msg (`T s)))
262        "" query; 
263       C.output_html (`Msg (`T "Result:"));
264       MQueryUtil.text_of_result
265         (fun s -> C.output_html (`Msg (`T s))) "" result;
266       let uris' =
267        match uris with
268         | [] ->
269            [UriManager.string_of_uri (C.input_or_locate_uri
270             ~title:("URI matching \"" ^ id ^ "\" unknown."))]
271         | [uri] -> [uri]
272         | _ ->
273             C.interactive_user_uri_choice ~selection_mode:`MULTIPLE
274              ~ok:"Try selected." ~enable_button_for_non_vars:true
275              ~title:"Ambiguous input." ~id
276              ~msg: ("Ambiguous input \"" ^ id ^
277                 "\". Please, choose one or more interpretations:")
278              uris
279       in
280       List.map
281         (fun uri ->
282           (uri,
283            let term =
284              try
285                HelmLibraryObjects.term_of_uri (UriManager.uri_of_string uri)
286              with _ -> assert false
287             in
288            fun _ _ _ -> term))
289         uris'
290
291     let disambiguate_term mqi_handle context metasenv term ~aliases:current_env
292     =
293       let current_dom = (* TODO temporary, remove ASAP *)
294         Environment.fold (fun item _ dom -> Domain.add item dom)
295           current_env Domain.empty
296       in
297       debug_print "NEW DISAMBIGUATE INPUT";
298       let disambiguate_context =  (* cic context -> disambiguate context *)
299         List.map
300           (function None -> Cic.Anonymous | Some (name, _) -> name)
301           context
302       in
303       let term_dom = domain_of_term ~context:disambiguate_context term in
304       debug_print (sprintf "DISAMBIGUATION DOMAIN: %s"
305         (string_of_domain term_dom));
306       let todo_dom = Domain.diff term_dom current_dom in
307       (* (2) lookup function for any item (Id/Symbol/Num) *)
308       let lookup_choices =
309         let id_choices = Hashtbl.create 1023 in
310         fun item ->
311         let choices =
312           match item with
313           | Id id ->
314               (try
315                 Hashtbl.find id_choices id
316               with Not_found ->
317                 let choices = choices_of_id mqi_handle id in
318                 Hashtbl.add id_choices id choices;
319                 choices)
320           | Symbol (symb, _) -> DisambiguateChoices.lookup_symbol_choices symb
321           | Num instance -> DisambiguateChoices.lookup_num_choices ()
322         in
323         if choices = [] then raise (No_choices item);
324         choices
325       in
326       (* (3) test an interpretation filling with meta uninterpreted identifiers
327        *)
328       let test_env current_env todo_dom =
329         let filled_env =
330           Domain.fold
331             (fun item env ->
332               Environment.add item ("Implicit", fun _ _ _ -> Cic.Implicit) env)
333             todo_dom current_env
334         in
335         try
336           let cic_term =
337             interpretate ~context:disambiguate_context ~env:filled_env term
338           in
339           refine metasenv context cic_term
340         with
341         | Try_again -> Uncertain
342         | DisambiguateChoices.Invalid_choice -> Ko
343       in
344       (* (4) build all possible interpretations *)
345       let rec aux current_env todo_dom =
346         if Domain.is_empty todo_dom then
347           match test_env current_env Domain.empty with
348           | Ok (term, metasenv) -> [ current_env, term, metasenv ]
349           | Ko | Uncertain -> []
350         else
351           let item = Domain.choose todo_dom in
352           let remaining_dom = Domain.remove item todo_dom in
353           debug_print (sprintf "CHOOSED ITEM: %s" (string_of_domain_item item));
354           let choices = lookup_choices item in
355           let rec filter = function
356             | [] -> []
357             | codomain_item :: tl ->
358                 let new_env = Environment.add item codomain_item current_env in
359                 (match test_env new_env remaining_dom with
360                 | Ok (term, metasenv) ->
361                     (if Domain.is_empty remaining_dom then
362                       [ new_env, term, metasenv ]
363                     else
364                       aux new_env remaining_dom)
365                     @ filter tl
366                 | Uncertain ->
367                     (if Domain.is_empty remaining_dom then
368                       []
369                     else
370                       aux new_env remaining_dom)
371                     @ filter tl
372                 | Ko -> filter tl)
373           in
374           filter choices
375       in
376       let (choosed_env, choosed_term, choosed_metasenv) =
377         match aux current_env todo_dom with
378         | [] -> raise NoWellTypedInterpretation
379         | [ x ] ->
380             debug_print "UNA SOLA SCELTA";
381             x
382         | l ->
383             debug_print (sprintf "PIU' SCELTE (%d)" (List.length l));
384             let choices =
385               List.map
386                 (fun (env, _, _) ->
387                   List.map
388                     (fun domain_item ->
389                       let description =
390                         fst (Environment.find domain_item env)
391                       in
392                       (descr_of_domain_item domain_item, description))
393                     (Domain.elements term_dom))
394                 l
395             in
396             let choosed = C.interactive_interpretation_choice choices in
397             List.nth l choosed
398       in
399       (choosed_env, choosed_metasenv, choosed_term)
400
401   end
402