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