]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/cic_disambiguation/disambiguate.ml
ported to new logger
[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 (Some `Type)
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 ->
178           let cic = resolve env (Id name) () in
179           let mk_subst uris =
180             let ids_to_uris =
181               List.map (fun uri -> UriManager.name_of_uri uri, uri) uris
182             in
183             List.map
184               (fun (s, term) ->
185                 (try
186                   List.assoc s ids_to_uris, aux loc context term
187                  with Not_found -> raise DisambiguateChoices.Invalid_choice))
188               subst
189          in
190           (match cic with
191           | Cic.Const (uri, []) ->
192               let uris =
193                 match CicEnvironment.get_obj uri with
194                 | Cic.Constant (_, _, _, uris) -> uris
195                 | _ -> assert false
196               in
197               Cic.Const (uri, mk_subst uris)
198           | Cic.Var (uri, []) ->
199               let uris =
200                 match CicEnvironment.get_obj uri with
201                 | Cic.Variable (_, _, _, uris) -> uris
202                 | _ -> assert false
203               in
204               Cic.Var (uri, mk_subst uris)
205           | Cic.MutInd (uri, i, []) ->
206               let uris =
207                 match CicEnvironment.get_obj uri with
208                 | Cic.InductiveDefinition (_, uris, _) -> uris
209                 | _ -> assert false
210               in
211               Cic.MutInd (uri, i, mk_subst uris)
212           | Cic.MutConstruct (uri, i, j, []) ->
213               let uris =
214                 match CicEnvironment.get_obj uri with
215                 | Cic.InductiveDefinition (_, uris, _) -> uris
216                 | _ -> assert false
217               in
218               Cic.MutConstruct (uri, i, j, mk_subst uris)
219           | Cic.Meta _ | Cic.Implicit _ as t ->
220 (*
221               prerr_endline (sprintf
222                 "Warning: %s must be instantiated with _[%s] but we do not enforce it"
223                 (CicPp.ppterm t)
224                 (String.concat "; "
225                   (List.map
226                     (fun (s, term) -> s ^ " := " ^ CicAstPp.pp_term term)
227                     subst)));
228 *)
229               t
230           | _ ->
231               raise DisambiguateChoices.Invalid_choice))
232     | CicAst.Implicit -> Cic.Implicit None
233     | CicAst.Num (num, i) -> resolve env (Num i) ~num ()
234     | CicAst.Meta (index, subst) ->
235         let cic_subst =
236           List.map
237             (function None -> None | Some term -> Some (aux loc context term))
238             subst
239         in
240         Cic.Meta (index, cic_subst)
241     | CicAst.Sort `Prop -> Cic.Sort Cic.Prop
242     | CicAst.Sort `Set -> Cic.Sort Cic.Set
243     | CicAst.Sort `Type -> Cic.Sort Cic.Type
244     | CicAst.Sort `CProp -> Cic.Sort Cic.CProp
245     | CicAst.Symbol (symbol, instance) ->
246         resolve env (Symbol (symbol, instance)) ()
247   and aux_option loc context = function
248     | None -> Cic.Implicit (Some `Type)
249     | Some term -> aux loc context term
250   in
251   match ast with
252   | CicAst.AttributedTerm (`Loc loc, term) -> aux loc context term
253   | term -> aux (-1, -1) context term
254
255 let domain_of_term ~context ast =
256     (* "aux" keeps domain in reverse order and doesn't care about duplicates.
257      * Domain item more in deep in the list will be processed first.
258      *)
259   let rec aux loc context = function
260     | CicAst.AttributedTerm (`Loc loc, term) -> aux loc context term
261     | CicAst.AttributedTerm (_, term) -> aux loc context term
262     | CicAst.Appl terms ->
263         List.fold_left (fun dom term -> aux loc context term @ dom) [] terms
264     | CicAst.Binder (_, (var, typ), body) ->
265         let type_dom = aux_option loc context typ in
266         let body_dom = aux loc (var :: context) body in
267         body_dom @ type_dom
268     | CicAst.Case (term, indty_ident, outtype, branches) ->
269         let term_dom = aux loc context term in
270         let outtype_dom = aux_option loc context outtype in
271         let do_branch ((head, args), term) =
272           let (term_context, args_domain) =
273             List.fold_left
274               (fun (cont, dom) (name, typ) ->
275                 (name :: cont,
276                  (match typ with
277                  | None -> dom
278                  | Some typ -> aux loc cont typ @ dom)))
279               (context, []) args
280           in
281           args_domain @ aux loc term_context term
282         in
283         let branches_dom =
284           List.fold_left (fun dom branch -> do_branch branch @ dom) [] branches
285         in
286         branches_dom @ outtype_dom @ term_dom @ [ Id indty_ident ]
287     | CicAst.LetIn ((var, typ), body, where) ->
288         let body_dom = aux loc context body in
289         let type_dom = aux_option loc context typ in
290         let where_dom = aux loc (var :: context) where in
291         where_dom @ type_dom @ body_dom
292     | CicAst.LetRec (kind, defs, where) ->
293         let context' =
294           List.fold_left (fun acc ((var, typ), _, _) -> var :: acc)
295             context defs
296         in
297         let where_dom = aux loc context' where in
298         let defs_dom =
299           List.fold_left
300             (fun dom ((_, typ), body, _) ->
301               aux loc context' body @ aux_option loc context typ)
302             [] defs
303         in
304         where_dom @ defs_dom
305     | CicAst.Ident (name, subst) ->
306         (* TODO hanlde explicit substitutions *)
307         (try
308           let index = find_in_environment name context in
309           if subst <> [] then
310             CicTextualParser2.fail loc
311               "Explicit substitutions not allowed here";
312           []
313         with Not_found ->
314           List.fold_left
315             (fun dom (_, term) ->
316               let dom' = aux loc context term in
317               dom' @ dom)
318             [ Id name ] subst)
319     | CicAst.Implicit -> []
320     | CicAst.Num (num, i) -> [ Num i ]
321     | CicAst.Meta (index, local_context) ->
322         List.fold_left (fun dom term -> aux_option loc context term @ dom) []
323           local_context
324     | CicAst.Sort _ -> []
325     | CicAst.Symbol (symbol, instance) -> [ Symbol (symbol, instance) ]
326
327   and aux_option loc context = function
328     | None -> []
329     | Some t -> aux loc context t
330   in
331
332     (* e.g. [5;1;1;1;2;3;4;1;2] -> [2;1;4;3;5] *)
333   let rev_uniq =
334     let module SortedItem =
335       struct
336         type t = DisambiguateTypes.domain_item
337         let compare = Pervasives.compare
338       end
339     in
340     let module Set = Set.Make (SortedItem) in
341     fun l ->
342       let rev_l = List.rev l in
343       let (_, uniq_rev_l) =
344         List.fold_left
345           (fun (members, rev_l) elt ->
346             if Set.mem elt members then
347               (members, rev_l)
348             else
349               Set.add elt members, elt :: rev_l)
350           (Set.empty, []) rev_l
351       in
352       List.rev uniq_rev_l
353   in
354             
355   rev_uniq
356     (match ast with
357     | CicAst.AttributedTerm (`Loc loc, term) -> aux loc context term
358     | term -> aux (-1, -1) context term)
359
360
361   (* dom1 \ dom2 *)
362 let domain_diff dom1 dom2 =
363 (* let domain_diff = Domain.diff *)
364   let is_in_dom2 =
365     List.fold_left (fun pred elt -> (fun elt' -> elt' = elt || pred elt'))
366       (fun _ -> false) dom2
367   in
368   List.filter (fun elt -> not (is_in_dom2 elt)) dom1
369
370 module Make (C: Callbacks) =
371   struct
372     let choices_of_id mqi_handle id =
373      let query  =  MQueryGenerator.locate id in
374      let result = MQueryInterpreter.execute mqi_handle query in
375      let uris =
376       List.map
377        (function uri,_ ->
378          MQueryMisc.wrong_xpointer_format_from_wrong_xpointer_format' uri
379        ) result in
380       HelmLogger.log (`Msg (`T "Locate query:"));
381       MQueryUtil.text_of_query
382        (fun s -> HelmLogger.log ~append_NL:false (`Msg (`T s)))
383        "" query; 
384       HelmLogger.log (`Msg (`T "Result:"));
385       MQueryUtil.text_of_result
386         (fun s -> HelmLogger.log (`Msg (`T s))) "" result;
387       let uris' =
388        match uris with
389         | [] ->
390            [UriManager.string_of_uri (C.input_or_locate_uri
391             ~title:("URI matching \"" ^ id ^ "\" unknown."))]
392         | [uri] -> [uri]
393         | _ ->
394             C.interactive_user_uri_choice ~selection_mode:`MULTIPLE
395              ~ok:"Try selected." ~enable_button_for_non_vars:true
396              ~title:"Ambiguous input." ~id
397              ~msg: ("Ambiguous input \"" ^ id ^
398                 "\". Please, choose one or more interpretations:")
399              uris
400       in
401       List.map
402         (fun uri ->
403           (uri,
404            let term =
405              try
406                HelmLibraryObjects.term_of_uri (UriManager.uri_of_string uri)
407              with _ -> assert false
408             in
409            fun _ _ _ -> term))
410         uris'
411
412     let disambiguate_term mqi_handle context metasenv term ~aliases:current_env
413     =
414       debug_print "NEW DISAMBIGUATE INPUT";
415       let disambiguate_context =  (* cic context -> disambiguate context *)
416         List.map
417           (function None -> Cic.Anonymous | Some (name, _) -> name)
418           context
419       in
420       let term_dom = domain_of_term ~context:disambiguate_context term in
421       debug_print (sprintf "DISAMBIGUATION DOMAIN: %s"
422         (string_of_domain term_dom));
423       let current_dom =
424         Environment.fold (fun item _ dom -> item :: dom) current_env []
425       in
426       let todo_dom = domain_diff term_dom current_dom in
427       (* (2) lookup function for any item (Id/Symbol/Num) *)
428       let lookup_choices =
429         let id_choices = Hashtbl.create 1023 in
430         fun item ->
431         let choices =
432           match item with
433           | Id id ->
434               (try
435                 Hashtbl.find id_choices id
436               with Not_found ->
437                 let choices = choices_of_id mqi_handle id in
438                 Hashtbl.add id_choices id choices;
439                 choices)
440           | Symbol (symb, _) -> DisambiguateChoices.lookup_symbol_choices symb
441           | Num instance -> DisambiguateChoices.lookup_num_choices ()
442         in
443         if choices = [] then raise (No_choices item);
444         choices
445       in
446       (* (3) test an interpretation filling with meta uninterpreted identifiers
447        *)
448       let test_env current_env todo_dom =
449         let filled_env =
450           List.fold_left
451             (fun env item ->
452               Environment.add item
453                 ("Implicit",
454                  (match item with
455                  | Id _ | Num _ -> (fun _ _ _ -> Cic.Implicit (Some `Closed))
456                  | Symbol _ -> (fun _ _ _ -> Cic.Implicit None))) env)
457             current_env todo_dom 
458         in
459         try
460           let cic_term =
461             interpretate ~context:disambiguate_context ~env:filled_env term
462           in
463           refine metasenv context cic_term
464         with
465         | Try_again -> Uncertain
466         | DisambiguateChoices.Invalid_choice -> Ko
467       in
468       (* (4) build all possible interpretations *)
469       let rec aux current_env todo_dom =
470         match todo_dom with
471         | [] ->
472             (match test_env current_env [] with
473             | Ok (term, metasenv) -> [ current_env, term, metasenv ]
474             | Ko | Uncertain -> [])
475         | item :: remaining_dom ->
476             debug_print (sprintf "CHOOSED ITEM: %s"
477               (string_of_domain_item item));
478             let choices = lookup_choices item in
479             let rec filter = function
480               | [] -> []
481               | codomain_item :: tl ->
482                   debug_print (sprintf "%s CHOSEN" (fst codomain_item)) ;
483                   let new_env =
484                     Environment.add item codomain_item current_env
485                   in
486                   (match test_env new_env remaining_dom with
487                   | Ok (term, metasenv) ->
488                       (match remaining_dom with
489                       | [] -> [ new_env, term, metasenv ]
490                       | _ -> aux new_env remaining_dom) @ filter tl
491                   | Uncertain ->
492                       (match remaining_dom with
493                       | [] -> []
494                       | _ -> aux new_env remaining_dom) @ filter tl
495                   | Ko -> filter tl)
496             in
497             filter choices
498       in
499       let (choosed_env, choosed_term, choosed_metasenv) =
500         match aux current_env todo_dom with
501         | [] -> raise NoWellTypedInterpretation
502         | [ x ] ->
503             debug_print "UNA SOLA SCELTA";
504             x
505         | l ->
506             debug_print (sprintf "PIU' SCELTE (%d)" (List.length l));
507             let choices =
508               List.map
509                 (fun (env, _, _) ->
510                   List.map
511                     (fun domain_item ->
512                       let description =
513                         fst (Environment.find domain_item env)
514                       in
515                       (descr_of_domain_item domain_item, description))
516                     term_dom)
517                 l
518             in
519             let choosed = C.interactive_interpretation_choice choices in
520             List.nth l choosed
521       in
522       (choosed_env, choosed_metasenv, choosed_term)
523
524   end
525