]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/cic_notation/cicNotationMatcher.ml
* added backtracking in matching code (hairy code!)
[helm.git] / helm / ocaml / cic_notation / cicNotationMatcher.ml
1 (* Copyright (C) 2004-2005, 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://helm.cs.unibo.it/
24  *)
25
26 open Printf
27
28 module Pp = CicNotationPp
29 module Pt = CicNotationPt
30 module Env = CicNotationEnv
31 module Util = CicNotationUtil
32
33 type pattern_id = int
34
35 exception No_match
36
37 module OrderedInt =
38 struct
39   type t = int
40   let compare (x1:t) (x2:t) = Pervasives.compare x2 x1  (* reverse order *)
41 end
42
43 module IntSet = Set.Make (OrderedInt)
44
45 let int_set_of_int_list l =
46   List.fold_left (fun acc i -> IntSet.add i acc) IntSet.empty l
47
48 type pattern_kind = Variable | Constructor
49 type tag_t = int
50
51 module type PATTERN =
52 sig
53   type pattern_t
54   type term_t
55   val classify : pattern_t -> pattern_kind
56   val tag_of_pattern : pattern_t -> tag_t * pattern_t list
57   val tag_of_term : term_t -> tag_t * term_t list
58 end
59
60 module Matcher (P: PATTERN) =
61 struct
62   type row_t = P.pattern_t list * P.pattern_t list * pattern_id
63   type t = row_t list
64
65   let compatible p1 p2 = P.classify p1 = P.classify p2
66
67   let matched = List.map (fun (matched, _, pid) -> matched, pid)
68
69   let partition t pidl =
70     let partitions = Hashtbl.create 11 in
71     let add pid row = Hashtbl.add partitions pid row in
72     (try
73       List.iter2 add pidl t
74     with Invalid_argument _ -> assert false);
75     let pidset = int_set_of_int_list pidl in
76     IntSet.fold
77       (fun pid acc ->
78         match Hashtbl.find_all partitions pid with
79         | [] -> acc
80         | patterns -> (pid, List.rev patterns) :: acc)
81       pidset []
82
83   let are_empty t =
84     match t with
85     | (_, [], _) :: _ -> true
86       (* if first row has an empty list of patterns, then others have as well *)
87     | _ -> false
88
89     (* return 2 lists of rows, first one containing homogeneous rows according
90      * to "compatible" below *)
91   let horizontal_split t =
92     let ap, first_row, t', first_row_class =
93       match t with
94       | [] -> assert false
95       | (_, [], _) :: _ ->
96           assert false  (* are_empty should have been invoked in advance *)
97       | ((_, hd :: _ , _) as row) :: tl -> hd, row, tl, P.classify hd
98     in
99     let rec aux prev_t = function
100       | [] -> List.rev prev_t, []
101       | (_, [], _) :: _ -> assert false
102       | ((_, hd :: _, _) as row) :: tl when compatible ap hd ->
103           aux (row :: prev_t) tl
104       | t -> List.rev prev_t, t
105     in
106     let rows1, rows2 = aux [first_row] t' in
107     first_row_class, rows1, rows2
108
109     (* return 2 lists, first one representing first column, second one
110      * representing a new pattern matrix where matched patterns have been moved
111      * to decl *)
112   let vertical_split t =
113     List.map
114       (function
115         | decls, hd :: tl, pid -> hd :: decls, tl, pid
116         | _ -> assert false)
117       t
118
119   let variable_closure k =
120     (fun matched_terms terms ->
121       match terms with
122       | hd :: tl -> k (hd :: matched_terms) tl
123       | _ -> assert false)
124
125   let constructor_closure ks k =
126     (fun matched_terms terms ->
127       match terms with
128       | t :: tl ->
129           (try
130             let tag, subterms = P.tag_of_term t in
131             let k' = List.assoc tag ks in
132             k' matched_terms (subterms @ tl)
133           with Not_found -> k matched_terms terms)
134       | [] -> assert false)
135
136   let compiler rows match_cb fail_k =
137     let rec aux t k =
138       if t = [] then
139         k
140       else if are_empty t then
141         let res = match_cb (matched t) in
142         (fun matched_terms terms ->
143            match res matched_terms with
144                None ->
145                  begin
146                    (* the match has failed, we rollback the last matched term
147                     * into the unmatched ones and call the failure continuation
148                     *)
149                    match matched_terms with
150                        hd :: tl -> k tl (hd :: terms)
151                      | _ -> assert false
152                  end
153              | Some v -> Some v)
154       else
155         match horizontal_split t with
156         | _, [], _ -> assert false
157         | Variable, t', [] -> variable_closure (aux (vertical_split t') k)
158         | Constructor, t', [] ->
159             let tagl =
160               List.map
161                 (function
162                   | _, p :: _, _ -> fst (P.tag_of_pattern p)
163                   | _ -> assert false)
164                 t'
165             in
166             let clusters = partition t' tagl in
167             let ks =
168               List.map
169                 (fun (tag, cluster) ->
170                   let cluster' =
171                     List.map  (* add args as patterns heads *)
172                       (function
173                         | matched_p, p :: tl, pid ->
174                             let _, subpatterns = P.tag_of_pattern p in
175                             matched_p, subpatterns @ tl, pid
176                         | _ -> assert false)
177                       cluster
178                   in
179                   tag, aux cluster' k)
180                 clusters
181             in
182             constructor_closure ks k
183         | _, t', t'' -> aux t' (aux t'' k)
184     in
185     let t = List.map (fun (p, pid) -> [], [p], pid) rows in
186     let matcher = aux t (fun _ _ -> fail_k ()) in
187     (fun term -> matcher [] [term])
188 end
189
190 module Matcher21 =
191 struct
192   module Pattern21 =
193   struct
194     type pattern_t = Pt.term
195     type term_t = Pt.term
196     let classify = function
197       | Pt.Variable _ -> Variable
198       | Pt.Magic _
199       | Pt.Layout _
200       | Pt.Literal _ as t -> assert false
201       | _ -> Constructor
202     let tag_of_pattern = CicNotationTag.get_tag
203     let tag_of_term = CicNotationTag.get_tag
204   end
205
206   module M = Matcher (Pattern21)
207
208   let extract_magic term =
209     let magic_map = ref [] in
210     let add_magic m =
211       let name = Util.fresh_name () in
212       magic_map := (name, m) :: !magic_map;
213       Pt.Variable (Pt.TermVar name)
214     in
215     let rec aux = function
216       | Pt.AttributedTerm (_, t) -> assert false
217       | Pt.Literal _
218       | Pt.Layout _ -> assert false
219       | Pt.Variable v -> Pt.Variable v
220       | Pt.Magic m -> add_magic m
221       | t -> Util.visit_ast aux t
222     in
223     let term' = aux term in
224     term', !magic_map
225
226   let env_of_matched pl tl =
227     List.map2
228       (fun p t ->
229         match p, t with
230           Pt.Variable (Pt.TermVar name), _ ->
231             name, (Env.TermType, Env.TermValue t)
232         | Pt.Variable (Pt.NumVar name), (Pt.Num (s, _)) ->
233             name, (Env.NumType, Env.NumValue s)
234         | Pt.Variable (Pt.IdentVar name), (Pt.Ident (s, None)) ->
235             name, (Env.StringType, Env.StringValue s)
236         | _ -> assert false)
237       pl tl
238
239   let rec compiler rows =
240     let rows', magic_maps =
241       List.split
242         (List.map
243           (fun (p, pid) ->
244             let p', map = extract_magic p in
245             (p', pid), (pid, map))
246           rows)
247     in
248     let magichecker map =
249       List.fold_left
250         (fun f (name, m) ->
251            prerr_endline ("compiling magichecker for " ^ name) ;
252           let m_checker = compile_magic m in
253           (fun env ->
254             match m_checker (Env.lookup_term env name) env with
255             | None -> None
256             | Some env' ->
257                 f env'))
258         (fun env ->
259              prerr_endline ("all magics processed ENV = " ^ Pp.pp_env env) ;       
260            Some env)
261         map
262     in
263     let magichooser candidates =
264       List.fold_left
265         (fun f (pid, pl, checker) ->
266            List.iter (fun p -> prerr_endline ("P = " ^ Pp.pp_term p)) pl ;
267           (fun matched_terms ->
268             let env = env_of_matched pl matched_terms in
269             match checker env with
270             | None -> f matched_terms
271             | Some env ->
272                 prerr_endline (String.concat " / " (List.map Pp.pp_term pl)) ;
273                 prerr_endline ("magichoose found a match for " ^ Pp.pp_env env ^ " " ^ string_of_int pid) ;
274                 let magic_map =
275                   try List.assoc pid magic_maps with Not_found -> assert false
276                 in
277                 let env' = Env.remove_names env (List.map fst magic_map) in
278                 Some (env', pid)))
279         (fun _ -> None)
280         candidates
281     in
282     let match_cb rows =
283       let candidates =
284         List.map
285           (fun (pl, pid) ->
286             let magic_map =
287               try List.assoc pid magic_maps with Not_found -> assert false
288             in
289             pid, pl, magichecker magic_map)
290           rows
291       in
292         magichooser candidates
293     in
294     M.compiler rows' match_cb (fun _ -> None)
295
296   and compile_magic = function
297     | Pt.Fold (kind, p_base, names, p_rec) ->
298         let p_rec_decls = Env.declarations_of_term p_rec in
299           (* LUCA: p_rec_decls should not contain "names" *)
300         let acc_name = try List.hd names with Failure _ -> assert false in
301         let compiled_base = compiler [p_base, 0]
302         and compiled_rec = compiler [p_rec, 0] in
303           (fun term env ->
304              let aux_base term =
305                match compiled_base term with
306                  | None -> None
307                  | Some (env', _) -> Some (env', [])
308              in
309              let rec aux term =
310                match compiled_rec term with
311                  | None -> aux_base term
312                  | Some (env', _) ->
313                      begin
314                        let acc = Env.lookup_term env' acc_name in
315                        let env'' = Env.remove_name env' acc_name in
316                          match aux acc with
317                            | None -> aux_base term
318                            | Some (base_env, rec_envl) -> 
319                                Some (base_env, env'' :: rec_envl)
320                      end
321              in
322                match aux term with
323                  | None -> None
324                  | Some (base_env, rec_envl) ->
325                      Some (base_env @ Env.coalesce_env p_rec_decls rec_envl @ env)) (* @ env LUCA!!! *)
326
327     | Pt.Default (p_some, p_none) ->  (* p_none can't bound names *)
328         let p_some_decls = Env.declarations_of_term p_some in
329         let none_env = List.map Env.opt_binding_of_name p_some_decls in
330         let compiled = compiler [p_some, 0] in
331         (fun term env ->
332           match compiled term with
333           | None -> Some none_env (* LUCA: @ env ??? *)
334           | Some (env', 0) -> Some (List.map Env.opt_binding_some env' @ env)
335           | _ -> assert false)
336
337     | Pt.If (guard, p) ->
338         prerr_endline ("guard = " ^ CicNotationPp.pp_term guard) ;
339         prerr_endline ("p = " ^ CicNotationPp.pp_term p) ;
340         let compiled_guard = compiler [guard, 0]
341         and compiled_p = compiler [p, 0] in
342           (fun term env ->
343              prerr_endline "GUARDIA?" ;
344              match compiled_guard term with
345                | None -> None
346                | Some _ ->
347                    begin
348                      match compiled_p term with
349                        | None -> None
350                        | Some (env', _) ->
351                            prerr_endline "guardia ok" ;
352                            Some (env' @ env)
353                    end)
354
355     | _ -> assert false
356 end
357
358 module Matcher32 =
359 struct
360   module Pattern32 =
361   struct
362     type cic_mask_t =
363       Blob
364     | Uri of UriManager.uri
365     | Appl of cic_mask_t list
366
367     let uri_of_term t = CicUtil.uri_of_term (Deannotate.deannotate_term t)
368
369     let mask_of_cic = function
370       | Cic.AAppl (_, tl) -> Appl (List.map (fun _ -> Blob) tl), tl
371       | Cic.AConst (_, _, [])
372       | Cic.AVar (_, _, [])
373       | Cic.AMutInd (_, _, _, [])
374       | Cic.AMutConstruct (_, _, _, _, []) as t -> Uri (uri_of_term t), []
375       | _ -> Blob, []
376
377     let tag_of_term t =
378       let mask, tl = mask_of_cic t in
379       Hashtbl.hash mask, tl
380
381     let mask_of_appl_pattern = function
382       | Pt.UriPattern uri -> Uri uri, []
383       | Pt.VarPattern _ -> Blob, []
384       | Pt.ApplPattern pl -> Appl (List.map (fun _ -> Blob) pl), pl
385
386     let tag_of_pattern p =
387       let mask, pl = mask_of_appl_pattern p in
388       Hashtbl.hash mask, pl
389
390     type pattern_t = Pt.cic_appl_pattern
391     type term_t = Cic.annterm
392
393     let classify = function
394       | Pt.VarPattern _ -> Variable
395       | _ -> Constructor
396   end
397
398   module M = Matcher (Pattern32)
399
400   let compiler rows =
401     let match_cb rows =
402       let pl, pid = try List.hd rows with Not_found -> assert false in
403       (fun matched_terms ->
404         let env =
405           List.map2
406             (fun p t ->
407               match p with
408               | Pt.VarPattern name -> name, t
409               | _ -> assert false)
410             pl matched_terms
411         in
412         Some (env, pid))
413     in
414     M.compiler rows match_cb (fun () -> None)
415 end
416