]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/cic_notation/cicNotationMatcher.ml
bugfix in default magic handling: consider as having option type only names
[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 Ast = CicNotationPt
29 module Env = CicNotationEnv
30 module Pp = CicNotationPp
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 ksucc =
120     (fun matched_terms terms ->
121 (* prerr_endline "variable_closure"; *)
122       match terms with
123       | hd :: tl -> ksucc (hd :: matched_terms) tl
124       | _ -> assert false)
125
126   let success_closure ksucc =
127     (fun matched_terms terms ->
128 (* prerr_endline "success_closure"; *)
129        ksucc matched_terms)
130
131   let constructor_closure ksuccs =
132     (fun matched_terms terms ->
133 (* prerr_endline "constructor_closure"; *)
134       match terms with
135       | t :: tl ->
136           (try
137             let tag, subterms = P.tag_of_term t in
138             let k' = List.assoc tag ksuccs in
139             k' matched_terms (subterms @ tl)
140           with Not_found -> None)
141       | [] -> assert false)
142
143   let backtrack_closure ksucc kfail =
144     (fun matched_terms terms ->
145 (* prerr_endline "backtrack_closure"; *)
146       match ksucc matched_terms terms with
147       | Some x -> Some x
148       | None -> kfail matched_terms terms)
149
150   let compiler rows match_cb fail_k =
151     let rec aux t =
152       if t = [] then
153         (fun _ _ -> fail_k ())
154       else if are_empty t then
155         success_closure (match_cb (matched t))
156       else
157         match horizontal_split t with
158         | _, [], _ -> assert false
159         | Variable, t', [] -> variable_closure (aux (vertical_split t'))
160         | Constructor, t', [] ->
161             let tagl =
162               List.map
163                 (function
164                   | _, p :: _, _ -> fst (P.tag_of_pattern p)
165                   | _ -> assert false)
166                 t'
167             in
168             let clusters = partition t' tagl in
169             let ksuccs =
170               List.map
171                 (fun (tag, cluster) ->
172                   let cluster' =
173                     List.map  (* add args as patterns heads *)
174                       (function
175                         | matched_p, p :: tl, pid ->
176                             let _, subpatterns = P.tag_of_pattern p in
177                             matched_p, subpatterns @ tl, pid
178                         | _ -> assert false)
179                       cluster
180                   in
181                   tag, aux cluster')
182                 clusters
183             in
184             constructor_closure ksuccs
185         | _, t', t'' -> backtrack_closure (aux t') (aux t'')
186     in
187     let t = List.map (fun (p, pid) -> [], [p], pid) rows in
188     let matcher = aux t in
189     (fun term -> matcher [] [term])
190 end
191
192 module Matcher21 =
193 struct
194   module Pattern21 =
195   struct
196     type pattern_t = Ast.term
197     type term_t = Ast.term
198     let rec classify = function
199       | Ast.AttributedTerm (_, t) -> classify t
200       | Ast.Variable _ -> Variable
201       | Ast.Magic _
202       | Ast.Layout _
203       | Ast.Literal _ as t -> assert false
204       | _ -> Constructor
205     let tag_of_pattern = CicNotationTag.get_tag
206     let tag_of_term t = CicNotationTag.get_tag t
207   end
208
209   module M = Matcher (Pattern21)
210
211   let extract_magic term =
212     let magic_map = ref [] in
213     let add_magic m =
214       let name = Util.fresh_name () in
215       magic_map := (name, m) :: !magic_map;
216       Ast.Variable (Ast.TermVar name)
217     in
218     let rec aux = function
219       | Ast.AttributedTerm (_, t) -> assert false
220       | Ast.Literal _
221       | Ast.Layout _ -> assert false
222       | Ast.Variable v -> Ast.Variable v
223       | Ast.Magic m -> add_magic m
224       | t -> Util.visit_ast aux t
225     in
226     let term' = aux term in
227     term', !magic_map
228
229   let env_of_matched pl tl =
230     try
231       List.map2
232         (fun p t ->
233           match p, t with
234             Ast.Variable (Ast.TermVar name), _ ->
235               name, (Env.TermType, Env.TermValue t)
236           | Ast.Variable (Ast.NumVar name), (Ast.Num (s, _)) ->
237               name, (Env.NumType, Env.NumValue s)
238           | Ast.Variable (Ast.IdentVar name), (Ast.Ident (s, None)) ->
239               name, (Env.StringType, Env.StringValue s)
240           | _ -> assert false)
241         pl tl
242     with Invalid_argument _ -> assert false
243
244   let rec compiler rows =
245     let rows', magic_maps =
246       List.split
247         (List.map
248           (fun (p, pid) ->
249             let p', map = extract_magic p in
250             (p', pid), (pid, map))
251           rows)
252     in
253     let magichecker map =
254       List.fold_left
255         (fun f (name, m) ->
256           let m_checker = compile_magic m in
257           (fun env ->
258             match m_checker (Env.lookup_term env name) env with
259             | None -> None
260             | Some env' -> f env'))
261         (fun env -> Some env)
262         map
263     in
264     let magichooser candidates =
265       List.fold_left
266         (fun f (pid, pl, checker) ->
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                 let magic_map =
273                   try List.assoc pid magic_maps with Not_found -> assert false
274                 in
275                 let env' = Env.remove_names env (List.map fst magic_map) in
276                 Some (env', pid)))
277         (fun _ -> None)
278         (List.rev candidates)
279     in
280     let match_cb rows =
281       let candidates =
282         List.map
283           (fun (pl, pid) ->
284             let magic_map =
285               try List.assoc pid magic_maps with Not_found -> assert false
286             in
287             pid, pl, magichecker magic_map)
288           rows
289       in
290       magichooser candidates
291     in
292     M.compiler rows' match_cb (fun _ -> None)
293
294   and compile_magic = function
295     | Ast.Fold (kind, p_base, names, p_rec) ->
296         let p_rec_decls = Env.declarations_of_term p_rec in
297           (* LUCA: p_rec_decls should not contain "names" *)
298         let acc_name = try List.hd names with Failure _ -> assert false in
299         let compiled_base = compiler [p_base, 0]
300         and compiled_rec = compiler [p_rec, 0] in
301           (fun term env ->
302              let aux_base term =
303                match compiled_base term with
304                  | None -> None
305                  | Some (env', _) -> Some (env', [])
306              in
307              let rec aux term =
308                match compiled_rec term with
309                  | None -> aux_base term
310                  | Some (env', _) ->
311                      begin
312                        let acc = Env.lookup_term env' acc_name in
313                        let env'' = Env.remove_name env' acc_name in
314                          match aux acc with
315                            | None -> aux_base term
316                            | Some (base_env, rec_envl) -> 
317                                Some (base_env, env'' :: rec_envl)
318                      end
319              in
320                match aux term with
321                  | None -> None
322                  | Some (base_env, rec_envl) ->
323                      Some (base_env @ Env.coalesce_env p_rec_decls rec_envl @ env)) (* @ env LUCA!!! *)
324
325     | Ast.Default (p_some, p_none) ->  (* p_none can't bound names *)
326         let p_some_decls = Env.declarations_of_term p_some in
327         let p_none_decls = Env.declarations_of_term p_none in
328         let p_opt_decls =
329           List.filter
330             (fun decl -> not (List.mem decl p_none_decls))
331             p_some_decls
332         in
333         let none_env = List.map Env.opt_binding_of_name p_opt_decls in
334         let compiled = compiler [p_some, 0] in
335         (fun term env ->
336           match compiled term with
337           | None -> Some none_env (* LUCA: @ env ??? *)
338           | Some (env', 0) ->
339               let env' =
340                 List.map
341                   (fun (name, (ty, v)) as binding ->
342                     if List.exists (fun (name', _) -> name = name') p_opt_decls
343                     then Env.opt_binding_some binding
344                     else binding)
345                   env'
346               in
347               Some (env' @ env)
348           | _ -> assert false)
349
350     | Ast.If (p_test, p_true, p_false) ->
351         let compiled_test = compiler [p_test, 0]
352         and compiled_true = compiler [p_true, 0]
353         and compiled_false = compiler [p_false, 0] in
354           (fun term env ->
355              let branch =
356                match compiled_test term with
357                  | None -> compiled_false
358                  | Some _ -> compiled_true
359              in
360                match branch term with
361                  | None -> None
362                  | Some (env', _) -> Some (env' @ env))
363
364     | Ast.Fail -> (fun _ _ -> None)
365
366     | _ -> assert false
367 end
368
369 module Matcher32 =
370 struct
371   module Pattern32 =
372   struct
373     type cic_mask_t =
374       Blob
375     | Uri of UriManager.uri
376     | Appl of cic_mask_t list
377
378     let uri_of_term t = CicUtil.uri_of_term (Deannotate.deannotate_term t)
379
380     let mask_of_cic = function
381       | Cic.AAppl (_, tl) -> Appl (List.map (fun _ -> Blob) tl), tl
382       | Cic.AConst (_, _, [])
383       | Cic.AVar (_, _, [])
384       | Cic.AMutInd (_, _, _, [])
385       | Cic.AMutConstruct (_, _, _, _, []) as t -> Uri (uri_of_term t), []
386       | _ -> Blob, []
387
388     let tag_of_term t =
389       let mask, tl = mask_of_cic t in
390       Hashtbl.hash mask, tl
391
392     let mask_of_appl_pattern = function
393       | Ast.UriPattern uri -> Uri uri, []
394       | Ast.ImplicitPattern
395       | Ast.VarPattern _ -> Blob, []
396       | Ast.ApplPattern pl -> Appl (List.map (fun _ -> Blob) pl), pl
397
398     let tag_of_pattern p =
399       let mask, pl = mask_of_appl_pattern p in
400       Hashtbl.hash mask, pl
401
402     type pattern_t = Ast.cic_appl_pattern
403     type term_t = Cic.annterm
404
405     let classify = function
406       | Ast.ImplicitPattern
407       | Ast.VarPattern _ -> Variable
408       | Ast.UriPattern _
409       | Ast.ApplPattern _ -> Constructor
410   end
411
412   module M = Matcher (Pattern32)
413
414   let compiler rows =
415     let match_cb rows =
416       let pl, pid = try List.hd rows with Not_found -> assert false in
417       (fun matched_terms ->
418         let env =
419           try
420             List.map2
421               (fun p t ->
422                 match p with
423                 | Ast.ImplicitPattern -> Util.fresh_name (), t
424                 | Ast.VarPattern name -> name, t
425                 | _ -> assert false)
426               pl matched_terms
427           with Invalid_argument _ -> assert false
428         in
429         Some (env, pid))
430     in
431     M.compiler rows match_cb (fun () -> None)
432 end
433