01: package kawa.lang;
02:
03: import gnu.lists.*;
04: import gnu.text.*;
05:
06: /** Match a list whose length in in the range [min_length..max_length]. */
07:
08: public class ListPat extends Pattern {
09: /** Minimun length of list that will match. */
10: int min_length;
11: /** Maximum length of list that will match. */
12: int max_length;
13: Object default_value;
14:
15: public ListPat(int len) {
16: min_length = len;
17: max_length = len;
18: }
19:
20: public ListPat(int min, int max) {
21: min_length = min;
22: max_length = max;
23: }
24:
25: public ListPat(int min, int max, Object default_val) {
26: min_length = min;
27: max_length = max;
28: default_value = default_val;
29: }
30:
31: public static boolean match(int min, int max, Object default_val,
32: Object obj, Object[] vars, int start_vars) {
33: int i;
34: for (i = 0; i < max; i++) {
35: if (obj instanceof Pair) {
36: Pair p = (Pair) obj;
37: vars[start_vars + i] = p.car;
38: obj = p.cdr;
39: } else if (i < min)
40: return false;
41: else
42: break;
43: }
44: if (i == max && obj != LList.Empty)
45: return false;
46: for (; i < max; i++)
47: vars[start_vars + i] = default_val;
48: return true;
49: }
50:
51: /**
52: * Succeeds if obj is a list of length [min..max].
53: * @param obj the object to match against
54: * @return true iff the match succeeded
55: * On success, max_length values from the elements of the list are placed
56: * in vars (starting at start_vars); if obj is shorter, missing elements
57: * are set to default_value.
58: */
59: public static Object[] match(int min, int max, Object default_val,
60: Object obj) {
61: Object[] vars = new Object[max];
62: return match(min, max, default_val, obj, vars, 0) ? vars : null;
63: }
64:
65: /**
66: * Succeeds if obj is a list of length [min_length..max_length].
67: * @param obj the object to match against
68: * @return null on failure, or an array of bound pattern variables:
69: * max_length values from the elements of the list are placed
70: * in the result; if obj is shorter, missing elements
71: * are set to default_value.
72: */
73: public boolean match(Object obj, Object[] vars, int start_vars) {
74: return match(min_length, max_length, default_value, obj, vars,
75: start_vars);
76: }
77:
78: public int varCount() {
79: return max_length;
80: }
81:
82: public void print(Consumer out) {
83: out.write("#<list-pattern min:");
84: out.write(Integer.toString(min_length));
85: out.write(" max:");
86: out.write(Integer.toString(max_length));
87: out.write(" default:");
88: ReportFormat.print(default_value, out);
89: out.write('>');
90: }
91: }
|