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