]> matita.cs.unibo.it Git - helm.git/blob - helm/gTopLevel/oldDisambiguate.ml
ported to new type_of prototype
[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.Uncertain _ ->
170 prerr_endline ("%%% UNCERTAIN!!! " ^ CicPp.ppterm expr) ;
171              Uncertain
172           | _ ->
173 prerr_endline ("%%% PRUNED!!! " ^ CicPp.ppterm expr) ;
174             Ko
175       in
176       let rec aux resolve_id ids list_of_uris =
177        match ids,list_of_uris with
178           [],[] ->
179            (match test resolve_id [] with
180                Ok (term,metasenv) -> [resolve_id,term,metasenv]
181              | Ko | Uncertain -> [])
182         | id::idtl,uris::uristl ->
183            let rec filter =
184             function
185                [] -> []
186              | (uri : CicTextualParser0.interpretation_codomain_item)::uritl ->
187                 let resolve_id' =
188                  function id' -> if id = id' then Some uri else resolve_id id'
189                 in
190                  (match test resolve_id' idtl with
191                      Ok (term,metasenv) ->
192                       (* the next three ``if''s are used to avoid the base   *)
193                       (* case where the term would be refined a second time. *)
194                       (if uristl = [] then
195                         [resolve_id',term,metasenv]
196                        else
197                         (aux resolve_id' idtl uristl)
198                       ) @ (filter uritl)
199                    | Uncertain ->
200                       (if uristl = [] then []
201                        else
202                         (aux resolve_id' idtl uristl)
203                       ) @ (filter uritl)
204                    | Ko ->
205                       filter uritl
206                  )
207            in
208             (match uris with
209                 Uris uris ->
210                  filter
211                   (List.map (function uri -> CicTextualParser0.Uri uri) uris)
212               | Symbols symbols ->
213                  filter
214                   (List.map
215                     (function sym -> CicTextualParser0.Term sym) symbols))
216         | _,_ -> assert false
217       in
218        aux resolve_id dom' list_of_uris
219      in
220       List.iter
221        (function (resolve,term,newmetasenv) ->
222          (* If metasen <> newmetasenv is a normal condition, we should *)
223          (* be prepared to apply the returned substitution to the      *)
224          (* whole current proof.                                       *)
225          if metasenv <> newmetasenv then
226           begin
227            prerr_endline
228             (Printf.sprintf
229               "+++++ ASSERTION FAILED: a refine operation should not modify the metasenv. Old metasenv:\n %s\n New metasenv:\n %s\n"
230               (CicMetaSubst.ppmetasenv metasenv [])
231               (CicMetaSubst.ppmetasenv newmetasenv [])) ;
232            (* an assert would raise an exception that could be caught *)
233            exit 1
234           end
235        ) resolve_ids ;
236       let resolve_id',term,metasenv' =
237        match resolve_ids with
238           [] -> raise ThereDoesNotExistAnyWellTypedInterpretationOfTheInput
239         | [resolve_id] -> resolve_id
240         | _ ->
241           let choices =
242            List.map
243             (function (resolve,_,_) ->
244               List.map
245                (function id ->
246                  (match id with
247                      CicTextualParser0.Id id -> id
248                    | CicTextualParser0.Symbol (descr,_) -> descr
249                  ),
250                   match resolve id with
251                      None -> assert false
252                    | Some (CicTextualParser0.Uri uri) ->
253                       (match uri with
254                           CicTextualParser0.ConUri uri
255                         | CicTextualParser0.VarUri uri ->
256                            UriManager.string_of_uri uri
257                         | CicTextualParser0.IndTyUri (uri,tyno) ->
258                            UriManager.string_of_uri uri ^ "#xpointer(1/" ^
259                             string_of_int (tyno+1) ^ ")"
260                         | CicTextualParser0.IndConUri (uri,tyno,consno) ->
261                            UriManager.string_of_uri uri ^ "#xpointer(1/" ^
262                             string_of_int (tyno+1) ^ "/" ^ string_of_int consno ^                           ")")
263                    | Some (CicTextualParser0.Term term) ->
264                       (* CSC: Implementare resa delle scelte *)
265                       "To be implemented XXX01"
266                    | Some CicTextualParser0.Implicit -> assert false
267                ) dom
268             ) resolve_ids
269           in
270            let index = C.interactive_interpretation_choice choices in
271             List.nth resolve_ids index
272       in
273        (known_ids @ dom', resolve_id'), metasenv',term
274 end
275 ;;
276
277 module EnvironmentP3 =
278  struct
279   type t = domain_and_interpretation
280
281   let empty = ""
282
283   let to_string (dom,resolve_id) =
284    let string_of_cic_textual_parser_uri uri =
285     let module C = Cic in
286     let module CTP = CicTextualParser0 in
287      let uri' =
288       match uri with
289          CTP.ConUri uri -> UriManager.string_of_uri uri
290        | CTP.VarUri uri -> UriManager.string_of_uri uri
291        | CTP.IndTyUri (uri,tyno) ->
292           UriManager.string_of_uri uri ^ "#1/" ^ string_of_int (tyno + 1)
293        | CTP.IndConUri (uri,tyno,consno) ->
294           UriManager.string_of_uri uri ^ "#1/" ^ string_of_int (tyno + 1) ^ "/" ^
295            string_of_int consno
296      in
297       (* 4 = String.length "cic:" *)
298       String.sub uri' 4 (String.length uri' - 4)
299    in
300    String.concat "\n"
301     (List.map
302       (function v ->
303         let uri =
304          match resolve_id v with
305             None -> assert false
306           | Some (CicTextualParser0.Uri uri) -> uri
307           | Some (CicTextualParser0.Term _)
308           | Some CicTextualParser0.Implicit -> assert false
309         in
310          "alias " ^
311           (match v with
312               CicTextualParser0.Id id -> id
313             | CicTextualParser0.Symbol (descr,_) ->
314                (* CSC: To be implemented *)
315                assert false
316           )^ " " ^ (string_of_cic_textual_parser_uri uri)
317       ) dom)
318
319   let of_string inputtext =
320     let regexpr =
321      let alfa = "[a-zA-Z_-]" in
322      let digit = "[0-9]" in
323      let ident = alfa ^ "\(" ^ alfa ^ "\|" ^ digit ^ "\)*" in
324      let blanks = "\( \|\t\|\n\)+" in
325      let nonblanks = "[^ \t\n]+" in
326      let uri = "/\(" ^ ident ^ "/\)*" ^ nonblanks in (* not very strict check *)
327       Str.regexp
328        ("alias" ^ blanks ^ "\(" ^ ident ^ "\)" ^ blanks ^ "\(" ^ uri ^ "\)")
329     in
330      let rec aux n =
331       try
332        let n' = Str.search_forward regexpr inputtext n in
333         let id = CicTextualParser0.Id (Str.matched_group 2 inputtext) in
334         let uri =
335          MQueryMisc.cic_textual_parser_uri_of_string
336           ("cic:" ^ (Str.matched_group 5 inputtext))
337         in
338          let dom,resolve_id = aux (n' + 1) in
339           if List.mem id dom then
340            dom,resolve_id
341           else
342            id::dom,
343             (function id' ->
344               if id = id' then
345                Some (CicTextualParser0.Uri uri)
346               else resolve_id id')
347       with
348        Not_found -> ([],function _ -> None)
349      in
350       aux 0
351  end