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