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