| 22 | // /(x)(x)?/ but both parentheses capture as $1. The returned regexp |
| 23 | // may share structure with or be the original. |
| 24 | static Regexp simplify(Regexp re) { |
| 25 | if (re == null) { |
| 26 | return null; |
| 27 | } |
| 28 | switch (re.op) { |
| 29 | case CAPTURE: |
| 30 | case CONCAT: |
| 31 | case ALTERNATE: |
| 32 | { |
| 33 | // Simplify children, building new Regexp if children change. |
| 34 | Regexp nre = re; |
| 35 | for (int i = 0; i < re.subs.length; ++i) { |
| 36 | Regexp sub = re.subs[i]; |
| 37 | Regexp nsub = simplify(sub); |
| 38 | if (nre == re && nsub != sub) { |
| 39 | // Start a copy. |
| 40 | nre = new Regexp(re); // shallow copy |
| 41 | nre.runes = null; |
| 42 | nre.subs = Parser.subarray(re.subs, 0, re.subs.length); // clone |
| 43 | } |
| 44 | if (nre != re) { |
| 45 | nre.subs[i] = nsub; |
| 46 | } |
| 47 | } |
| 48 | return nre; |
| 49 | } |
| 50 | case STAR: |
| 51 | case PLUS: |
| 52 | case QUEST: |
| 53 | { |
| 54 | Regexp sub = simplify(re.subs[0]); |
| 55 | return simplify1(re.op, re.flags, sub, re); |
| 56 | } |
| 57 | case REPEAT: |
| 58 | { |
| 59 | // Special special case: x{0} matches the empty string |
| 60 | // and doesn't even need to consider x. |
| 61 | if (re.min == 0 && re.max == 0) { |
| 62 | return new Regexp(Regexp.Op.EMPTY_MATCH); |
| 63 | } |
| 64 | |
| 65 | // The fun begins. |
| 66 | Regexp sub = simplify(re.subs[0]); |
| 67 | |
| 68 | // x{n,} means at least n matches of x. |
| 69 | if (re.max == -1) { |
| 70 | // Special case: x{0,} is x*. |
| 71 | if (re.min == 0) { |
| 72 | return simplify1(Regexp.Op.STAR, re.flags, sub, null); |
| 73 | } |
| 74 | |
| 75 | // Special case: x{1,} is x+. |
| 76 | if (re.min == 1) { |
| 77 | return simplify1(Regexp.Op.PLUS, re.flags, sub, null); |
| 78 | } |
| 79 | |
| 80 | // General case: x{4,} is xxxx+. |
| 81 | Regexp nre = new Regexp(Regexp.Op.CONCAT); |