]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/cic_disambiguation/disambiguate.ml
Added a TODO (to catch only the right exceptions instead of everything).
[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         (* TODO we should catch only the RefineFailure excecption *)
62         debug_print ("%%% PRUNED!!! " ^ CicPp.ppterm term) ;
63         Ko
64
65 let resolve (env: environment) (item: domain_item) ?(num = "") ?(args = []) () =
66   snd (Environment.find item env) env num args
67
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
74   in
75   aux 1 context
76
77 let interpretate ~context ~env ast =
78   let rec aux loc context = function
79     | CicAst.AttributedTerm (`Loc loc, term) ->
80         aux loc context 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)
92         | `Exists ->
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
103                 let typ =
104                   match typ with
105                   | None -> Cic.Implicit
106                   | Some typ -> aux loc context typ
107                 in
108                 Cic.Lambda (name, typ, cic_body)
109           in
110           do_branch' context args
111         in
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
117         in
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
122         let cic_def =
123           match typ with
124           | None -> cic_def
125           | Some t -> Cic.Cast (cic_def, aux loc context t)
126         in
127         let cic_body = aux loc (name :: context) body in
128         Cic.LetIn (name, cic_def, cic_body)
129     | CicAst.LetRec (kind, defs, body) ->
130         let context' =
131           List.fold_left (fun acc ((name, _), _, _) -> name :: acc)
132             context defs
133         in
134         let cic_body = aux loc context' body in
135         let inductiveFuns =
136           List.map
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
140               let name =
141                 match name with
142                 | Cic.Anonymous ->
143                     CicTextualParser2.fail loc
144                       "Recursive functions cannot be anonymous"
145                 | Cic.Name name -> name
146               in
147               (name, decr_idx, cic_type, cic_body))
148             defs
149         in
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 *)
155           match kind with
156           | `Inductive ->
157               (fun (var, _, _, _) cic ->
158                 incr counter;
159                 Cic.LetIn (Cic.Name var, Cic.Fix (!counter, funs), cic))
160           | `CoInductive ->
161               let funs =
162                 List.map (fun (name, _, typ, body) -> (name, typ, body)) funs
163               in
164               (fun (var, _, _, _) cic ->
165                 incr counter;
166                 Cic.LetIn (Cic.Name var, Cic.CoFix (!counter, funs), cic))
167         in
168         List.fold_right (build_term inductiveFuns) inductiveFuns cic_body
169     | CicAst.Ident (name, subst) ->
170         (* TODO hanlde explicit substitutions *)
171         (try
172           let index = find_in_environment name context in
173           if subst <> [] then
174             CicTextualParser2.fail loc
175               "Explicit substitutions not allowed here";
176           Cic.Rel index
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) ->
181         let cic_subst =
182           List.map
183             (function None -> None | Some term -> Some (aux loc context term))
184             subst
185         in
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
196   in
197   match ast with
198   | CicAst.AttributedTerm (`Loc loc, term) -> aux loc context term
199   | _ -> assert false
200
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.
204      *)
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
213         body_dom @ type_dom
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) =
219             List.fold_left
220               (fun (cont, dom) (name, typ) ->
221                 (name :: cont,
222                  (match typ with
223                  | None -> dom
224                  | Some typ -> aux loc cont typ @ dom)))
225               (context, []) args
226           in
227           args_domain @ aux loc term_context term
228         in
229         let branches_dom =
230           List.fold_left (fun dom branch -> do_branch branch @ dom) [] branches
231         in
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) ->
239         let context' =
240           List.fold_left (fun acc ((var, typ), _, _) -> var :: acc)
241             context defs
242         in
243         let where_dom = aux loc context' where in
244         let defs_dom =
245           List.fold_left
246             (fun dom ((_, typ), body, _) ->
247               aux loc context' body @ aux_option loc context typ)
248             [] defs
249         in
250         where_dom @ defs_dom
251     | CicAst.Ident (name, subst) ->
252         (* TODO hanlde explicit substitutions *)
253         (try
254           let index = find_in_environment name context in
255           if subst <> [] then
256             CicTextualParser2.fail loc
257               "Explicit substitutions not allowed here";
258           []
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) []
264           local_context
265     | CicAst.Sort _ -> []
266     | CicAst.Symbol (symbol, instance) -> [ Symbol (symbol, instance) ]
267
268   and aux_option loc context = function
269     | None -> []
270     | Some t -> aux loc context t
271   in
272
273     (* e.g. [5;1;1;1;2;3;4;1;2] -> [2;1;4;3;5] *)
274   let rev_uniq =
275     let module SortedItem =
276       struct
277         type t = DisambiguateTypes.domain_item
278         let compare = Pervasives.compare
279       end
280     in
281     let module Set = Set.Make (SortedItem) in
282     fun l ->
283       let rev_l = List.rev l in
284       let (_, uniq_rev_l) =
285         List.fold_left
286           (fun (members, rev_l) elt ->
287             if Set.mem elt members then
288               (members, rev_l)
289             else
290               Set.add elt members, elt :: rev_l)
291           (Set.empty, []) rev_l
292       in
293       List.rev uniq_rev_l
294   in
295             
296   match ast with
297   | CicAst.AttributedTerm (`Loc loc, term) -> rev_uniq (aux loc context term)
298   | _ -> assert false
299
300
301   (* dom1 \ dom2 *)
302 let domain_diff dom1 dom2 =
303 (* let domain_diff = Domain.diff *)
304   let is_in_dom2 =
305     List.fold_left (fun pred elt -> (fun elt' -> elt' = elt || pred elt'))
306       (fun _ -> false) dom2
307   in
308   List.filter (fun elt -> not (is_in_dom2 elt)) dom1
309
310 module Make (C: Callbacks) =
311   struct
312     let choices_of_id mqi_handle id =
313      let query  =  MQueryGenerator.locate id in
314      let result = MQueryInterpreter.execute mqi_handle query in
315      let uris =
316       List.map
317        (function uri,_ ->
318          MQueryMisc.wrong_xpointer_format_from_wrong_xpointer_format' uri
319        ) result in
320       C.output_html (`Msg (`T "Locate query:"));
321       MQueryUtil.text_of_query
322        (fun s -> C.output_html ~append_NL:false (`Msg (`T s)))
323        "" query; 
324       C.output_html (`Msg (`T "Result:"));
325       MQueryUtil.text_of_result
326         (fun s -> C.output_html (`Msg (`T s))) "" result;
327       let uris' =
328        match uris with
329         | [] ->
330            [UriManager.string_of_uri (C.input_or_locate_uri
331             ~title:("URI matching \"" ^ id ^ "\" unknown."))]
332         | [uri] -> [uri]
333         | _ ->
334             C.interactive_user_uri_choice ~selection_mode:`MULTIPLE
335              ~ok:"Try selected." ~enable_button_for_non_vars:true
336              ~title:"Ambiguous input." ~id
337              ~msg: ("Ambiguous input \"" ^ id ^
338                 "\". Please, choose one or more interpretations:")
339              uris
340       in
341       List.map
342         (fun uri ->
343           (uri,
344            let term =
345              try
346                HelmLibraryObjects.term_of_uri (UriManager.uri_of_string uri)
347              with _ -> assert false
348             in
349            fun _ _ _ -> term))
350         uris'
351
352     let disambiguate_term mqi_handle context metasenv term ~aliases:current_env
353     =
354       debug_print "NEW DISAMBIGUATE INPUT";
355       let disambiguate_context =  (* cic context -> disambiguate context *)
356         List.map
357           (function None -> Cic.Anonymous | Some (name, _) -> name)
358           context
359       in
360       let term_dom = domain_of_term ~context:disambiguate_context term in
361       debug_print (sprintf "DISAMBIGUATION DOMAIN: %s"
362         (string_of_domain term_dom));
363       let current_dom =
364         Environment.fold (fun item _ dom -> item :: dom) current_env []
365       in
366       let todo_dom = domain_diff term_dom current_dom in
367       (* (2) lookup function for any item (Id/Symbol/Num) *)
368       let lookup_choices =
369         let id_choices = Hashtbl.create 1023 in
370         fun item ->
371         let choices =
372           match item with
373           | Id id ->
374               (try
375                 Hashtbl.find id_choices id
376               with Not_found ->
377                 let choices = choices_of_id mqi_handle id in
378                 Hashtbl.add id_choices id choices;
379                 choices)
380           | Symbol (symb, _) -> DisambiguateChoices.lookup_symbol_choices symb
381           | Num instance -> DisambiguateChoices.lookup_num_choices ()
382         in
383         if choices = [] then raise (No_choices item);
384         choices
385       in
386       (* (3) test an interpretation filling with meta uninterpreted identifiers
387        *)
388       let test_env current_env todo_dom =
389         let filled_env =
390           List.fold_left
391             (fun env item ->
392               Environment.add item ("Implicit", fun _ _ _ -> Cic.Implicit) env)
393             current_env todo_dom 
394         in
395         try
396           let cic_term =
397             interpretate ~context:disambiguate_context ~env:filled_env term
398           in
399           refine metasenv context cic_term
400         with
401         | Try_again -> Uncertain
402         | DisambiguateChoices.Invalid_choice -> Ko
403       in
404       (* (4) build all possible interpretations *)
405       let rec aux current_env todo_dom =
406         match todo_dom with
407         | [] ->
408             (match test_env current_env [] with
409             | Ok (term, metasenv) -> [ current_env, term, metasenv ]
410             | Ko | Uncertain -> [])
411         | item :: remaining_dom ->
412             debug_print (sprintf "CHOOSED ITEM: %s"
413               (string_of_domain_item item));
414             let choices = lookup_choices item in
415             let rec filter = function
416               | [] -> []
417               | codomain_item :: tl ->
418                   debug_print (sprintf "%s CHOSEN" (fst codomain_item)) ;
419                   let new_env =
420                     Environment.add item codomain_item current_env
421                   in
422                   (match test_env new_env remaining_dom with
423                   | Ok (term, metasenv) ->
424                       (match remaining_dom with
425                       | [] -> [ new_env, term, metasenv ]
426                       | _ -> aux new_env remaining_dom) @ filter tl
427                   | Uncertain ->
428                       (match remaining_dom with
429                       | [] -> []
430                       | _ -> aux new_env remaining_dom) @ filter tl
431                   | Ko -> filter tl)
432             in
433             filter choices
434       in
435       let (choosed_env, choosed_term, choosed_metasenv) =
436         match aux current_env todo_dom with
437         | [] -> raise NoWellTypedInterpretation
438         | [ x ] ->
439             debug_print "UNA SOLA SCELTA";
440             x
441         | l ->
442             debug_print (sprintf "PIU' SCELTE (%d)" (List.length l));
443             let choices =
444               List.map
445                 (fun (env, _, _) ->
446                   List.map
447                     (fun domain_item ->
448                       let description =
449                         fst (Environment.find domain_item env)
450                       in
451                       (descr_of_domain_item domain_item, description))
452                     term_dom)
453                 l
454             in
455             let choosed = C.interactive_interpretation_choice choices in
456             List.nth l choosed
457       in
458       (choosed_env, choosed_metasenv, choosed_term)
459
460   end
461