]> matita.cs.unibo.it Git - helm.git/blob - helm/gTopLevel/disambiguate.ml
MQueryInterpreter: interface updated
[helm.git] / helm / gTopLevel / disambiguate.ml
1 (* Copyright (C) 2000-2002, 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://cs.unibo.it/helm/.
24  *)
25
26 (******************************************************************************)
27 (*                                                                            *)
28 (*                               PROJECT HELM                                 *)
29 (*                                                                            *)
30 (*                Claudio Sacerdoti Coen <sacerdot@cs.unibo.it>               *)
31 (*                                 06/01/2002                                 *)
32 (*                                                                            *)
33 (*                                                                            *)
34 (******************************************************************************)
35
36 (* CSC: IMPERATIVE AND NOT VERY CLEAN, TO GET THE LAST ISSUED QUERY *)
37 (* FG : THIS FUNCTION IS BECOMING A REAL NONSENSE                   *)
38 let get_last_query = 
39  let query = ref "" in
40   let out s = query := ! query ^ s in
41   MQueryGenerator.set_confirm_query
42    (function q -> 
43     query := ""; MQueryUtil.text_of_query out q ""; true);
44   function result ->
45    out (!query ^ " <h1>Result:</h1> "); MQueryUtil.text_of_result out result "<br>";
46    !query
47 ;;
48
49 (** This module provides a functor to disambiguate the input **)
50 (** given a set of user-interface call-backs                 **)
51
52 module type Callbacks =
53   sig
54     (* The following two functions are used to save/restore the metasenv *)
55     (* before/after the parsing.                                         *)
56     (*CSC: This should be made functional sooner or later! *)
57     val get_metasenv : unit -> Cic.metasenv
58     val set_metasenv : Cic.metasenv -> unit
59
60     val output_html : string -> unit
61     val interactive_user_uri_choice :
62       selection_mode:[`SINGLE | `EXTENDED] ->
63       ?ok:string ->
64       ?enable_button_for_non_vars:bool ->
65       title:string -> msg:string -> id:string -> string list -> string list
66     val interactive_interpretation_choice :
67       (string * string) list list -> int
68     val input_or_locate_uri : title:string -> UriManager.uri
69   end
70 ;;
71
72 type domain_and_interpretation =
73  CicTextualParser0.interpretation_domain_item list *
74   CicTextualParser0.interpretation
75 ;;
76
77 module Make(C:Callbacks) =
78   struct
79
80    let locate_one_id mqi_handle id =
81     let result = MQueryGenerator.locate mqi_handle id in
82     let uris =
83      List.map
84       (function uri,_ ->
85         MQueryMisc.wrong_xpointer_format_from_wrong_xpointer_format' uri
86       ) result in
87     let html=
88      " <h1>Locate Query: </h1><pre>" ^ get_last_query result ^ "</pre>"
89     in
90      C.output_html html ;
91      let uris' =
92       match uris with
93          [] ->
94           [UriManager.string_of_uri
95            (C.input_or_locate_uri
96              ~title:("URI matching \"" ^ id ^ "\" unknown."))]
97        | [uri] -> [uri]
98        | _ ->
99          C.interactive_user_uri_choice
100           ~selection_mode:`EXTENDED
101           ~ok:"Try every selection."
102           ~enable_button_for_non_vars:true
103           ~title:"Ambiguous input."
104           ~msg:
105             ("Ambiguous input \"" ^ id ^
106              "\". Please, choose one or more interpretations:")
107           ~id
108           uris
109      in
110       List.map MQueryMisc.cic_textual_parser_uri_of_string uris'
111
112
113    exception ThereDoesNotExistAnyWellTypedInterpretationOfTheInput
114
115    type test_result =
116       Ok of Cic.term * Cic.metasenv
117     | Ko
118     | Uncertain
119
120    type ambiguous_choices =
121       Uris of CicTextualParser0.uri list
122     | Symbols of (CicTextualParser0.interpretation -> Cic.term) list
123
124    let disambiguate_input mqi_handle context metasenv dom mk_metasenv_and_expr ~id_to_uris=
125     let known_ids,resolve_id = id_to_uris in
126     let dom' =
127      let rec filter =
128       function
129          [] -> []
130        | he::tl ->
131           if List.mem he known_ids then filter tl else he::(filter tl)
132      in
133       filter dom
134     in
135      (* for each id in dom' we get the list of uris associated to it *)
136      let list_of_uris =
137       List.map
138        (function
139            CicTextualParser0.Id id -> Uris (locate_one_id mqi_handle id)
140          | CicTextualParser0.Symbol (descr,choices) ->
141             (* CSC: Implementare la funzione di filtraggio manuale *)
142             (* CSC: corrispondente alla locate_one_id              *)
143             Symbols (List.map snd choices)
144        ) dom' in
145      let tests_no =
146       List.fold_left
147        (fun i uris ->
148          let len =
149           match uris with
150              Uris l -> List.length l
151            | Symbols l -> List.length l
152          in
153           i * len
154        ) 1 list_of_uris
155      in
156       if tests_no > 1 then
157        C.output_html
158         ("<h1>Disambiguation phase started: up to " ^
159           string_of_int tests_no ^ " cases will be tried.") ;
160      (* and now we compute the list of all possible assignments from *)
161      (* id to uris that generate well-typed terms                    *)
162      let resolve_ids =
163       (* function to test if a partial interpretation is so far correct *)
164       let test resolve_id residual_dom =
165        (* We put implicits in place of every identifier that is not *)
166        (* resolved by resolve_id                                    *)
167        let resolve_id' =
168         List.fold_left
169          (fun f id ->
170            function id' ->
171             if id = id' then Some (CicTextualParser0.Implicit) else f id'
172          ) resolve_id residual_dom
173        in
174         (* and we try to refine the term *)
175         let saved_status = C.get_metasenv () in
176         let metasenv',expr = mk_metasenv_and_expr resolve_id' in
177 (*CSC: Bug here: we do not try to typecheck also the metasenv' *)
178         (* The parser is imperative ==> we must restore the old status ;-(( *)
179         C.set_metasenv saved_status ;
180          try
181           let term,_,_,metasenv'' =
182            CicRefine.type_of_aux' metasenv' context expr
183           in
184            Ok (term,metasenv'')
185          with
186             CicRefine.MutCaseFixAndCofixRefineNotImplemented ->
187              (try
188                let term = CicTypeChecker.type_of_aux' metasenv' context expr in
189                 Ok (term,metasenv')
190               with _ -> Ko
191              )
192           | CicRefine.Uncertain _ ->
193 prerr_endline ("%%% UNCERTAIN!!! " ^ CicPp.ppterm expr) ;
194              Uncertain
195           | _ ->
196 prerr_endline ("%%% PRUNED!!! " ^ CicPp.ppterm expr) ;
197             Ko
198       in
199       let rec aux resolve_id ids list_of_uris =
200        match ids,list_of_uris with
201           [],[] ->
202            (match test resolve_id [] with
203                Ok (term,metasenv) -> [resolve_id,term,metasenv]
204              | Ko | Uncertain -> [])
205         | id::idtl,uris::uristl ->
206            let rec filter =
207             function
208                [] -> []
209              | (uri : CicTextualParser0.interpretation_codomain_item)::uritl ->
210                 let resolve_id' =
211                  function id' -> if id = id' then Some uri else resolve_id id'
212                 in
213                  (match test resolve_id' idtl with
214                      Ok (term,metasenv) ->
215                       (* the next three ``if''s are used to avoid the base   *)
216                       (* case where the term would be refined a second time. *)
217                       (if uristl = [] then
218                         [resolve_id',term,metasenv]
219                        else
220                         (aux resolve_id' idtl uristl)
221                       ) @ (filter uritl)
222                    | Uncertain ->
223                       (if uristl = [] then []
224                        else
225                         (aux resolve_id' idtl uristl)
226                       ) @ (filter uritl)
227                    | Ko ->
228                       filter uritl
229                  )
230            in
231             (match uris with
232                 Uris uris ->
233                  filter
234                   (List.map (function uri -> CicTextualParser0.Uri uri) uris)
235               | Symbols symbols ->
236                  filter
237                   (List.map
238                     (function sym -> CicTextualParser0.Term sym) symbols))
239         | _,_ -> assert false
240       in
241        aux resolve_id dom' list_of_uris
242      in
243       List.iter
244        (function (resolve,term,newmetasenv) ->
245          (* If metasen <> newmetasenv is a normal condition, we should *)
246          (* be prepared to apply the returned substitution to the      *)
247          (* whole current proof.                                       *)
248          if metasenv <> newmetasenv then
249           begin
250            prerr_endline
251             ("+++++ ASSERTION FAILED: " ^
252              "a refine operation should not modify the metasenv") ;
253            (* an assert would raise an exception that could be caught *)
254            exit 1
255           end
256        ) resolve_ids ;
257       let resolve_id',term,metasenv' =
258        match resolve_ids with
259           [] -> raise ThereDoesNotExistAnyWellTypedInterpretationOfTheInput
260         | [resolve_id] -> resolve_id
261         | _ ->
262           let choices =
263            List.map
264             (function (resolve,_,_) ->
265               List.map
266                (function id ->
267                  (match id with
268                      CicTextualParser0.Id id -> id
269                    | CicTextualParser0.Symbol (descr,_) -> descr
270                  ),
271                   match resolve id with
272                      None -> assert false
273                    | Some (CicTextualParser0.Uri uri) ->
274                       (match uri with
275                           CicTextualParser0.ConUri uri
276                         | CicTextualParser0.VarUri uri ->
277                            UriManager.string_of_uri uri
278                         | CicTextualParser0.IndTyUri (uri,tyno) ->
279                            UriManager.string_of_uri uri ^ "#xpointer(1/" ^
280                             string_of_int (tyno+1) ^ ")"
281                         | CicTextualParser0.IndConUri (uri,tyno,consno) ->
282                            UriManager.string_of_uri uri ^ "#xpointer(1/" ^
283                             string_of_int (tyno+1) ^ "/" ^ string_of_int consno ^                           ")")
284                    | Some (CicTextualParser0.Term term) ->
285                       (* CSC: Implementare resa delle scelte *)
286                       "To be implemented XXX01"
287                    | Some CicTextualParser0.Implicit -> assert false
288                ) dom
289             ) resolve_ids
290           in
291            let index = C.interactive_interpretation_choice choices in
292             List.nth resolve_ids index
293       in
294        (known_ids @ dom', resolve_id'), metasenv',term
295 end
296 ;;