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