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