]> matita.cs.unibo.it Git - helm.git/blob - helm/gTopLevel/oldDisambiguate.ml
ocaml 3.09 transition
[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 interactive_user_uri_choice :
44       selection_mode:[`SINGLE | `MULTIPLE] ->
45       ?ok:string ->
46       ?enable_button_for_non_vars:bool ->
47       title:string -> msg:string -> id:string -> string list -> string list
48     val interactive_interpretation_choice :
49       (string * string) list list -> int list
50     val input_or_locate_uri : title:string -> ?id:string -> unit -> UriManager.uri
51   end
52 ;;
53
54 type domain_and_interpretation =
55  CicTextualParser0.interpretation_domain_item list *
56   CicTextualParser0.interpretation
57 ;;
58
59 module Make(C:Callbacks) =
60   struct
61
62    let locate_one_id mqi_handle id =
63     let query  =  MQueryGenerator.locate id in
64     let result = MQueryInterpreter.execute mqi_handle query in
65     let uris =
66      List.map
67       (function uri,_ ->
68         MQueryMisc.wrong_xpointer_format_from_wrong_xpointer_format' uri
69       ) result in
70      HelmLogger.log (`Msg (`T "Locate query:"));
71      MQueryUtil.text_of_query
72       (fun s -> HelmLogger.log ~append_NL:false (`Msg (`T s)))
73       "" query; 
74      HelmLogger.log (`Msg (`T "Result:"));
75      MQueryUtil.text_of_result (fun s -> HelmLogger.log (`Msg (`T s))) "" result;
76      let uris' =
77       match uris with
78          [] ->
79           [UriManager.string_of_uri
80            (C.input_or_locate_uri
81              ~title:("URI matching \"" ^ id ^ "\" unknown.") ~id ())]
82        | [uri] -> [uri]
83        | _ ->
84          C.interactive_user_uri_choice
85           ~selection_mode:`MULTIPLE
86           ~ok:"Try every selection."
87           ~enable_button_for_non_vars:true
88           ~title:"Ambiguous input."
89           ~msg:
90             ("Ambiguous input \"" ^ id ^
91              "\". Please, choose one or more interpretations:")
92           ~id
93           uris
94      in
95       List.map MQueryMisc.cic_textual_parser_uri_of_string uris'
96
97
98    exception ThereDoesNotExistAnyWellTypedInterpretationOfTheInput
99
100    type test_result =
101       Ok of Cic.term * Cic.metasenv
102     | Ko
103     | Uncertain
104
105    type ambiguous_choices =
106       Uris of CicTextualParser0.uri list
107     | Symbols of (CicTextualParser0.interpretation -> Cic.term) list
108
109    let disambiguate_input mqi_handle context metasenv dom mk_metasenv_and_expr ~id_to_uris=
110     let known_ids,resolve_id = id_to_uris in
111     let dom' =
112      let rec filter =
113       function
114          [] -> []
115        | he::tl ->
116           if List.mem he known_ids then filter tl else he::(filter tl)
117      in
118       filter dom
119     in
120      (* for each id in dom' we get the list of uris associated to it *)
121      let list_of_uris =
122       List.map
123        (function
124            CicTextualParser0.Id id -> Uris (locate_one_id mqi_handle id)
125          | CicTextualParser0.Symbol (descr,choices) ->
126             (* CSC: Implementare la funzione di filtraggio manuale *)
127             (* CSC: corrispondente alla locate_one_id              *)
128             Symbols (List.map snd choices)
129        ) dom' in
130      let tests_no =
131       List.fold_left
132        (fun i uris ->
133          let len =
134           match uris with
135              Uris l -> List.length l
136            | Symbols l -> List.length l
137          in
138           i * len
139        ) 1 list_of_uris
140      in
141       if tests_no > 1 then
142        HelmLogger.log (`Msg (`T (sprintf
143         "Disambiguation phase started: up to %d cases will be tried"
144         tests_no)));
145      (* and now we compute the list of all possible assignments from *)
146      (* id to uris that generate well-typed terms                    *)
147      let resolve_ids =
148       (* function to test if a partial interpretation is so far correct *)
149       let test resolve_id residual_dom =
150        (* We put implicits in place of every identifier that is not *)
151        (* resolved by resolve_id                                    *)
152        let resolve_id' =
153         List.fold_left
154          (fun f id ->
155            function id' ->
156             if id = id' then Some (CicTextualParser0.Implicit) else f id'
157          ) resolve_id residual_dom
158        in
159         (* and we try to refine the term *)
160         let metasenv',expr = mk_metasenv_and_expr resolve_id' in
161 (*CSC: Bug here: we do not try to typecheck also the metasenv' *)
162          try
163           let term,_,metasenv'',_ = (* TASSI: FIXME what are we doning here?*)
164            CicRefine.type_of_aux' metasenv' context expr CicUniv.empty_ugraph
165           in
166            Ok (term,metasenv'') (* TASSI: whould we pass back the ugraph? *)
167          with
168             CicRefine.Uncertain _ ->
169 prerr_endline ("%%% UNCERTAIN!!! " ^ CicPp.ppterm expr) ;
170              Uncertain
171           | CicRefine.RefineFailure _ ->
172 prerr_endline ("%%% PRUNED!!! " ^ CicPp.ppterm expr) ;
173             Ko
174       in
175       let rec aux resolve_id ids list_of_uris =
176        match ids,list_of_uris with
177           [],[] ->
178            (match test resolve_id [] with
179                Ok (term,metasenv) -> [resolve_id,term,metasenv]
180              | Ko | Uncertain -> [])
181         | id::idtl,uris::uristl ->
182            let rec filter =
183             function
184                [] -> []
185              | (uri : CicTextualParser0.interpretation_codomain_item)::uritl ->
186                 let resolve_id' =
187                  function id' -> if id = id' then Some uri else resolve_id id'
188                 in
189                  (match test resolve_id' idtl with
190                      Ok (term,metasenv) ->
191                       (* the next three ``if''s are used to avoid the base   *)
192                       (* case where the term would be refined a second time. *)
193                       (if uristl = [] then
194                         [resolve_id',term,metasenv]
195                        else
196                         (aux resolve_id' idtl uristl)
197                       ) @ (filter uritl)
198                    | Uncertain ->
199                       (if uristl = [] then []
200                        else
201                         (aux resolve_id' idtl uristl)
202                       ) @ (filter uritl)
203                    | Ko ->
204                       filter uritl
205                  )
206            in
207             (match uris with
208                 Uris uris ->
209                  filter
210                   (List.map (function uri -> CicTextualParser0.Uri uri) uris)
211               | Symbols symbols ->
212                  filter
213                   (List.map
214                     (function sym -> CicTextualParser0.Term sym) symbols))
215         | _,_ -> assert false
216       in
217        aux resolve_id dom' list_of_uris
218      in
219       List.iter
220        (function (resolve,term,newmetasenv) ->
221          (* If metasen <> newmetasenv is a normal condition, we should *)
222          (* be prepared to apply the returned substitution to the      *)
223          (* whole current proof.                                       *)
224          if metasenv <> newmetasenv then
225           begin
226            prerr_endline
227             (Printf.sprintf
228               "+++++ ASSERTION FAILED: a refine operation should not modify the metasenv. Old metasenv:\n %s\n New metasenv:\n %s\n"
229               (CicMetaSubst.ppmetasenv metasenv [])
230               (CicMetaSubst.ppmetasenv newmetasenv [])) ;
231            (* an assert would raise an exception that could be caught *)
232            exit 1
233           end
234        ) resolve_ids ;
235       let res =
236        match resolve_ids with
237           [] -> raise ThereDoesNotExistAnyWellTypedInterpretationOfTheInput
238         | [_] -> resolve_ids
239         | _ ->
240           let choices =
241            List.map
242             (function (resolve,_,_) ->
243               List.map
244                (function id ->
245                  (match id with
246                      CicTextualParser0.Id id -> id
247                    | CicTextualParser0.Symbol (descr,_) -> descr
248                  ),
249                   match resolve id with
250                      None -> assert false
251                    | Some (CicTextualParser0.Uri uri) ->
252                       (match uri with
253                           CicTextualParser0.ConUri uri
254                         | CicTextualParser0.VarUri uri ->
255                            UriManager.string_of_uri uri
256                         | CicTextualParser0.IndTyUri (uri,tyno) ->
257                            UriManager.string_of_uri uri ^ "#xpointer(1/" ^
258                             string_of_int (tyno+1) ^ ")"
259                         | CicTextualParser0.IndConUri (uri,tyno,consno) ->
260                            UriManager.string_of_uri uri ^ "#xpointer(1/" ^
261                             string_of_int (tyno+1) ^ "/" ^ string_of_int consno ^                           ")")
262                    | Some (CicTextualParser0.Term term) ->
263                       (* CSC: Implementare resa delle scelte *)
264                       "To be implemented XXX01"
265                    | Some CicTextualParser0.Implicit -> assert false
266                ) dom
267             ) resolve_ids
268           in
269            let indexes = C.interactive_interpretation_choice choices in
270             List.map (List.nth resolve_ids) indexes
271       in
272        List.map
273         (fun (resolve_id',term,metasenv') ->
274           (known_ids @ dom', resolve_id'), metasenv',term
275         ) res
276 end
277 ;;
278
279 module EnvironmentP3 =
280  struct
281   type t = domain_and_interpretation
282
283   let empty = ""
284
285   let to_string (dom,resolve_id) =
286    let string_of_cic_textual_parser_uri uri =
287     let module C = Cic in
288     let module CTP = CicTextualParser0 in
289      let uri' =
290       match uri with
291          CTP.ConUri uri -> UriManager.string_of_uri uri
292        | CTP.VarUri uri -> UriManager.string_of_uri uri
293        | CTP.IndTyUri (uri,tyno) ->
294           UriManager.string_of_uri uri ^ "#1/" ^ string_of_int (tyno + 1)
295        | CTP.IndConUri (uri,tyno,consno) ->
296           UriManager.string_of_uri uri ^ "#1/" ^ string_of_int (tyno + 1) ^ "/" ^
297            string_of_int consno
298      in
299       (* 4 = String.length "cic:" *)
300       String.sub uri' 4 (String.length uri' - 4)
301    in
302    String.concat "\n"
303     (List.map
304       (function v ->
305         let uri =
306          match resolve_id v with
307             None -> assert false
308           | Some (CicTextualParser0.Uri uri) -> uri
309           | Some (CicTextualParser0.Term _)
310           | Some CicTextualParser0.Implicit -> assert false
311         in
312          "alias " ^
313           (match v with
314               CicTextualParser0.Id id -> id
315             | CicTextualParser0.Symbol (descr,_) ->
316                (* CSC: To be implemented *)
317                assert false
318           )^ " " ^ (string_of_cic_textual_parser_uri uri)
319       ) dom)
320
321   let of_string inputtext =
322     let regexpr =
323      let alfa = "[a-zA-Z_-]" in
324      let digit = "[0-9]" in
325      let ident = alfa ^ "\\(" ^ alfa ^ "\\|" ^ digit ^ "\\)*" in
326      let blanks = "\\( \\|\t\\|\n\\)+" in
327      let nonblanks = "[^ \t\n]+" in
328      let uri = "/\\(" ^ ident ^ "/\\)*" ^ nonblanks in
329       (* not very strict check *)
330       Str.regexp
331        ("alias" ^ blanks ^ "\\(" ^ ident ^ "\\)" ^ blanks ^ "\\(" ^ uri ^ "\\)")
332     in
333      let rec aux n =
334       try
335        let n' = Str.search_forward regexpr inputtext n in
336         let id = CicTextualParser0.Id (Str.matched_group 2 inputtext) in
337         let uri =
338          MQueryMisc.cic_textual_parser_uri_of_string
339           ("cic:" ^ (Str.matched_group 5 inputtext))
340         in
341          let dom,resolve_id = aux (n' + 1) in
342           if List.mem id dom then
343            dom,resolve_id
344           else
345            id::dom,
346             (function id' ->
347               if id = id' then
348                Some (CicTextualParser0.Uri uri)
349               else resolve_id id')
350       with
351        Not_found -> ([],function _ -> None)
352      in
353       aux 0
354  end