ListPat.java 2.5 KB

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