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