Debian Codegraph @

src/com/google/javascript/jscomp/regex/RegExpTree.java

raw symbols SCIP
1 /*
2 * Copyright 2011 The Closure Compiler Authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.javascript.jscomp.regex;
18
19 import com.google.common.base.Preconditions;
20 import com.google.common.collect.ImmutableList;
21 import com.google.common.collect.ImmutableMap;
22 import com.google.common.collect.Lists;
23 import com.google.common.collect.Sets;
24
25 import java.util.Iterator;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Set;
29
30 /**
31 * An AST for JavaScript regular expressions.
32 *
33 * @author Mike Samuel <[email protected]>
34 */
35 public abstract class RegExpTree {
36
37 /**
38 * Returns a simpler regular expression that is semantically the same assuming
39 * the given flags.
40 * @param flags Regular expression flags, e.g. {@code "igm"}.
41 */
42 public abstract RegExpTree simplify(String flags);
43
44 /**
45 * True if the presence or absence of an {@code "i"} flag would change the
46 * meaning of this regular expression.
47 */
48 public abstract boolean isCaseSensitive();
49
50 /**
51 * True if the regular expression contains an anchor : {@code ^} or {@code $}.
52 */
53 public abstract boolean containsAnchor();
54
55 /**
56 * True if the regular expression contains capturing groups.
57 */
58 public final boolean hasCapturingGroup() {
59 return numCapturingGroups() != 0;
60 }
61
62 /**
63 * The number of capturing groups.
64 */
65 public abstract int numCapturingGroups();
66
67 /**
68 * The children of this node.
69 */
70 public abstract List<? extends RegExpTree> children();
71
72 /**
73 * Appends this regular expression source to the given buffer.
74 */
75 protected abstract void appendSourceCode(StringBuilder sb);
76
77 protected abstract void appendDebugInfo(StringBuilder sb);
78
79 @Override
80 public final String toString() {
81 StringBuilder sb = new StringBuilder();
82 sb.append('/');
83 appendSourceCode(sb);
84 // Don't emit a regular expression that looks like a line comment start.
85 if (sb.length() == 1) {
86 sb.append("(?:)");
87 }
88 sb.append('/');
89 return sb.toString();
90 }
91
92 public final String toDebugString() {
93 StringBuilder sb = new StringBuilder();
94 appendDebugString(sb);
95 return sb.toString();
96 }
97
98 private void appendDebugString(StringBuilder sb) {
99 sb.append('(').append(getClass().getSimpleName());
100 int len = sb.length();
101 sb.append(' ');
102 appendDebugInfo(sb);
103 if (sb.length() == len + 1) { sb.setLength(len); }
104 for (RegExpTree child : children()) {
105 sb.append(' ');
106 child.appendDebugString(sb);
107 }
108 sb.append(')');
109 }
110
111 @Override
112 public abstract boolean equals(Object o);
113
114 @Override
115 public abstract int hashCode();
116
117
118 /**
119 * Parses a regular expression to an AST.
120 *
121 * @param pattern The {@code foo} From {@code /foo/i}.
122 * @param flags The {@code i} From {@code /foo/i}.
123 */
124 public static RegExpTree parseRegExp(
125 final String pattern, final String flags) {
126
127 /** A recursive descent parser that closes over pattern and flags above. */
128 class Parser {
129 /** The number of characters in pattern consumed. */
130 int pos;
131 /** The number of capturing groups seen so far. */
132 int numCapturingGroups = 0;
133 /** The length of pattern. */
134 final int limit = pattern.length();
135
136 RegExpTree parseTopLevel() {
137 this.pos = 0;
138 RegExpTree out = parse();
139 if (pos < limit) { // Unmatched closed paren maybe.
140 throw new IllegalArgumentException(pattern.substring(pos));
141 }
142 return out;
143 }
144
145 RegExpTree parse() {
146 // Collects ["foo", "bar", "baz"] for /foo|bar|baz/.
147 ImmutableList.Builder<RegExpTree> alternatives = null;
148 // The last item parsed within an alternation.
149 RegExpTree preceder = null;
150
151 topLoop:
152 while (pos < limit) {
153 char ch = pattern.charAt(pos);
154 RegExpTree atom;
155 switch (ch) {
156 case '[':
157 atom = parseCharset();
158 break;
159 case '(':
160 atom = parseParenthetical();
161 break;
162 case ')':
163 break topLoop;
164 case '\\':
165 atom = parseEscape();
166 break;
167 case '^':
168 case '$':
169 atom = new Anchor(ch);
170 ++pos;
171 break;
172 case '.':
173 // We represent . as a character set to make it easy to simplify
174 // things like /.|[\r\n]/.
175 atom = DOT_CHARSET;
176 ++pos;
177 break;
178 case '|':
179 // An alternative may be empty as in /foo||bar/.
180 // The '|' is consumed below.
181 atom = Empty.INSTANCE;
182 break;
183 default:
184 // Find a run of concatenated characters to avoid building a
185 // tree node per literal character.
186 int start = pos;
187 int end = pos + 1;
188 charsLoop:
189 while (end < limit) {
190 switch (pattern.charAt(end)) {
191 case '[':
192 case '(':
193 case ')':
194 case '\\':
195 case '^':
196 case '$':
197 case '|':
198 case '.':
199 case '*':
200 case '+':
201 case '?':
202 case '{':
203 break charsLoop;
204 default:
205 // Repetition binds more tightly than concatenation.
206 // Only consume up to "foo" in /foob*/ so that the suffix
207 // operator parser below has the right precedence.
208 if (end + 1 >= limit
209 || !isRepetitionStart(pattern.charAt(end + 1))) {
210 ++end;
211 } else {
212 break charsLoop;
213 }
214 }
215 }
216 atom = new Text(pattern.substring(start, end));
217 pos = end;
218 break;
219 }
220 if (pos < limit && isRepetitionStart(pattern.charAt(pos))) {
221 atom = parseRepetition(atom);
222 }
223 if (preceder == null) {
224 preceder = atom;
225 } else {
226 preceder = new Concatenation(preceder, atom);
227 }
228 // If this is an alternative in a alternation, then add it to the
229 // list of complete alternatives, and reset the parser state for the
230 // next alternative.
231 if (pos < limit && pattern.charAt(pos) == '|') {
232 if (alternatives == null) {
233 alternatives = ImmutableList.builder();
234 }
235 alternatives.add(preceder);
236 preceder = null;
237 ++pos;
238 }
239 }
240 // An alternative may have no parsed content blank as in /foo|/.
241 if (preceder == null) { preceder = Empty.INSTANCE; }
242 if (alternatives != null) {
243 alternatives.add(preceder);
244 return new Alternation(alternatives.build());
245 } else {
246 return preceder;
247 }
248 }
249
250 /**
251 * Handles capturing groups {@code (...)},
252 * non-capturing groups {@code (?:...)}, and lookahead assertions
253 * {@code (?=...)}.
254 */
255 private RegExpTree parseParenthetical() {
256 Preconditions.checkState(pattern.charAt(pos) == '(');
257 int start = pos;
258 ++pos;
259 boolean capturing = true;
260 int type = 0;
261 if (pos < limit && pattern.charAt(pos) == '?') {
262 if (pos + 1 < limit) {
263 capturing = false;
264 char ch = pattern.charAt(pos + 1);
265 switch (ch) {
266 case ':': // A (?:...) style non-capturing group.
267 pos += 2;
268 break;
269 case '!': // A lookahead assertion
270 case '=':
271 pos += 2;
272 type = ch;
273 break;
274 default:
275 throw new IllegalArgumentException(
276 "Malformed parenthetical: " + pattern.substring(start));
277 }
278 }
279 }
280 RegExpTree body = parse();
281 if (pos < limit && pattern.charAt(pos) == ')') {
282 ++pos;
283 } else {
284 throw new IllegalArgumentException(
285 "Unclosed parenthetical group: " + pattern.substring(start));
286 }
287 if (capturing) {
288 ++numCapturingGroups;
289 return new CapturingGroup(body);
290 } else if (type != 0) {
291 return new LookaheadAssertion(body, type == '=');
292 } else {
293 return body;
294 }
295 }
296
297 /**
298 * Parses a square bracketed character set.
299 * Standalone character groups (@code /\d/} are handled by
300 * {@link #parseEscape}.
301 */
302 private RegExpTree parseCharset() {
303 Preconditions.checkState(pattern.charAt(pos) == '[');
304 ++pos;
305
306 boolean isCaseInsensitive = flags.indexOf('i') >= 0;
307 boolean inverse = pos < limit && pattern.charAt(pos) == '^';
308 if (inverse) { ++pos; }
309 CharRanges ranges = CharRanges.EMPTY;
310 CharRanges ieExplicits = CharRanges.EMPTY;
311 while (pos < limit && pattern.charAt(pos) != ']') {
312 char ch = pattern.charAt(pos);
313 char start;
314 if (ch == '\\') {
315 ++pos;
316 char possibleGroupName = pattern.charAt(pos);
317 CharRanges group = NAMED_CHAR_GROUPS.get(possibleGroupName);
318 if (group != null) {
319 ++pos;
320 ranges = ranges.union(group);
321 continue;
322 }
323 start = parseEscapeChar();
324 } else {
325 start = ch;
326 ++pos;
327 }
328 char end = start;
329 if (pos + 1 < limit && pattern.charAt(pos) == '-'
330 && pattern.charAt(pos + 1) != ']') {
331 ++pos;
332 ch = pattern.charAt(pos);
333 if (ch == '\\') {
334 ++pos;
335 end = parseEscapeChar();
336 } else {
337 end = ch;
338 ++pos;
339 }
340 }
341 CharRanges range = CharRanges.inclusive(start, end);
342 ranges = ranges.union(range);
343 if (IE_SPEC_ERRORS.contains(start) && IE_SPEC_ERRORS.contains(end)) {
344 ieExplicits = ieExplicits.union(range.intersection(IE_SPEC_ERRORS));
345 }
346 if (isCaseInsensitive) {
347 // If the flags contain the 'i' flag, then it is not correct to
348 // say that [^a-z] contains the letter 'A', or that [a-z] does not
349 // contain the letter 'A'.
350 // We expand out letter groups here so that parse returns something
351 // that is valid independent of flags.
352 // Calls to simplify(flags) may later reintroduce flag assumptions.
353 // but without this step, later steps might conflate
354 // /[a-z]/i
355 // and
356 // /[^\0-`{-\uffff]/i
357 // which matches nothing because the information about whether the
358 // ^ is present has been lost during optimizations and charset
359 // unionizing as in /[...]|[^...]/.
360 ranges = CaseCanonicalize.expandToAllMatched(ranges);
361 }
362 }
363 ++pos; // Consume ']'
364
365 if (inverse) {
366 ranges = CharRanges.ALL_CODE_UNITS.difference(ranges);
367 }
368
369 return new Charset(ranges, ieExplicits);
370 }
371
372 /**
373 * Parses an escape to a code point.
374 * Some of the characters parsed here have special meanings in various
375 * contexts, so contexts must filter those instead.
376 * E.g. '\b' means a different thing inside a charset than without.
377 */
378 private char parseEscapeChar() {
379 char ch = pattern.charAt(pos++);
380 switch (ch) {
381 case 'b': return '\b';
382 case 'f': return '\f';
383 case 'n': return '\n';
384 case 'r': return '\r';
385 case 't': return '\t';
386 case 'u': return parseHex(4);
387 case 'v': return '\u000b';
388 case 'x': return parseHex(2);
389 default:
390 if ('0' <= ch && ch <= '7') {
391 char codeUnit = (char) (ch - '0');
392 // Allow octal literals in the range \0-\377.
393 // \41 might be a group, but \041 is not a group.
394 // We read, but do not emit octal literals since they
395 // are deprecated in ES5.
396 int octLimit = Math.min(
397 limit, pos + (ch <= '3' ? 2 : 1) + (ch == '0' ? 1 : 0));
398 while (pos < octLimit) {
399 ch = pattern.charAt(pos);
400 if ('0' <= ch && ch <= '7') {
401 codeUnit = (char) ((codeUnit << 3) + (ch - '0'));
402 ++pos;
403 } else {
404 break;
405 }
406 }
407 return codeUnit;
408 }
409 return ch;
410 }
411 }
412
413 /**
414 * Parses an escape that appears outside a charset.
415 */
416 private RegExpTree parseEscape() {
417 Preconditions.checkState(pattern.charAt(pos) == '\\');
418 ++pos;
419 char ch = pattern.charAt(pos);
420 if (ch == 'b' || ch == 'B') {
421 ++pos;
422 return new WordBoundary(ch);
423 } else if ('1' <= ch && ch <= '9') {
424 ++pos;
425 int possibleGroupIndex = ch - '0';
426 if (numCapturingGroups >= possibleGroupIndex) {
427 if (pos < limit) {
428 char next = pattern.charAt(pos);
429 if ('0' <= next && next <= '9') {
430 int twoDigitGroupIndex = possibleGroupIndex * 10 + (next - '0');
431 if (numCapturingGroups >= twoDigitGroupIndex) {
432 ++pos;
433 possibleGroupIndex = twoDigitGroupIndex;
434 }
435 }
436 }
437 return new BackReference(possibleGroupIndex);
438 } else {
439 // \1 - \7 are octal escapes if there is no such group.
440 // \8 and \9 are the literal characters '8' and '9' if there
441 // is no such group.
442 return new Text(Character.toString(
443 possibleGroupIndex <= 7 ? (char) possibleGroupIndex : ch));
444 }
445 } else {
446 CharRanges charGroup = NAMED_CHAR_GROUPS.get(ch);
447 if (charGroup != null) { // Handle \d, etc.
448 ++pos;
449 return new Charset(charGroup, CharRanges.EMPTY);
450 }
451 return new Text("" + parseEscapeChar());
452 }
453 }
454
455 /**
456 * Parses n hex digits to a code-unit.
457 */
458 private char parseHex(int n) {
459 if (pos + n > limit) {
460 throw new IllegalArgumentException(
461 "Abbreviated hex escape " + pattern.substring(pos));
462 }
463 int result = 0;
464 while (--n >= 0) {
465 char ch = pattern.charAt(pos);
466 int digit;
467 if ('0' <= ch && ch <= '9') {
468 digit = ch - '0';
469 } else if ('a' <= ch && ch <= 'f') {
470 digit = ch + (10 - 'a');
471 } else if ('A' <= ch && ch <= 'F') {
472 digit = ch + (10 - 'A');
473 } else {
474 throw new IllegalArgumentException(pattern.substring(pos));
475 }
476 ++pos;
477 result = (result << 4) | digit;
478 }
479 return (char) result;
480 }
481
482 private boolean isRepetitionStart(char ch) {
483 switch (ch) {
484 case '?':
485 case '*':
486 case '+':
487 case '{':
488 return true;
489 default:
490 return false;
491 }
492 }
493
494 /**
495 * Parse a repetition. {@code x?} is treated as a repetition --
496 * an optional production can be matched 0 or 1 time.
497 */
498 private RegExpTree parseRepetition(RegExpTree body) {
499 if (pos == limit) { return body; }
500 int min, max;
501 switch (pattern.charAt(pos)) {
502 case '+':
503 ++pos;
504 min = 1;
505 max = Integer.MAX_VALUE;
506 break;
507 case '*':
508 ++pos;
509 min = 0;
510 max = Integer.MAX_VALUE;
511 break;
512 case '?':
513 ++pos;
514 min = 0;
515 max = 1;
516 break;
517 case '{':
518 ++pos;
519 int start = pos;
520 int end = pattern.indexOf('}', start);
521 if (end < 0) {
522 pos = start - 1;
523 return body;
524 }
525 String counts = pattern.substring(start, end);
526 pos = end + 1;
527 int comma = counts.indexOf(',');
528 try {
529 min = Integer.parseInt(
530 comma >= 0 ? counts.substring(0, comma) : counts);
531 max = comma >= 0
532 ? comma + 1 != counts.length()
533 ? Integer.parseInt(counts.substring(comma + 1))
534 : Integer.MAX_VALUE
535 : min;
536 } catch (NumberFormatException ex) {
537 min = max = -1;
538 }
539 if (min < 0 || min > max) {
540 // Treat the open curly bracket literally.
541 pos = start - 1;
542 return body;
543 }
544 break;
545 default:
546 return body;
547 }
548 boolean greedy = true;
549 if (pos < limit && pattern.charAt(pos) == '?') {
550 greedy = false;
551 ++pos;
552 }
553 return new Repetition(body, min, max, greedy);
554 }
555 }
556
557 return new Parser().parseTopLevel();
558 }
559
560
561 /**
562 * True if, but not necessarily always when the, given regular expression
563 * must match the whole input or none of it.
564 */
565 public static boolean matchesWholeInput(RegExpTree t, String flags) {
566 if (flags.indexOf('m') >= 0) { return false; }
567
568 if (!(t instanceof Concatenation)) {
569 return false;
570 }
571
572 Concatenation c = (Concatenation) t;
573 if (c.elements.isEmpty()) { return false; }
574 RegExpTree first = c.elements.get(0),
575 last = c.elements.get(c.elements.size() - 1);
576 if (!(first instanceof Anchor && last instanceof Anchor)) { return false; }
577 return ((Anchor) first).type == '^' && ((Anchor) last).type == '$';
578 }
579
580
581 static abstract class RegExpTreeAtom extends RegExpTree {
582 @Override
583 public boolean isCaseSensitive() {
584 return false;
585 }
586
587 @Override
588 public boolean containsAnchor() {
589 return false;
590 }
591
592 @Override
593 public final int numCapturingGroups() {
594 return 0;
595 }
596
597 @Override
598 public final List<? extends RegExpTree> children() {
599 return ImmutableList.of();
600 }
601 }
602
603 static final class Empty extends RegExpTreeAtom {
604 static final Empty INSTANCE = new Empty();
605
606 @Override
607 public RegExpTree simplify(String flags) {
608 return this;
609 }
610
611 @Override
612 protected void appendSourceCode(StringBuilder sb) {
613 // No output
614 }
615
616 @Override
617 protected void appendDebugInfo(StringBuilder sb) {
618 // No output
619 }
620
621 @Override
622 public boolean equals(Object o) {
623 return o instanceof Empty;
624 }
625
626 @Override
627 public int hashCode() {
628 return 0x7ee06141;
629 }
630 }
631
632 static final class Anchor extends RegExpTreeAtom {
633 final char type;
634 Anchor(char type) { this.type = type; }
635
636 @Override
637 public RegExpTree simplify(String flags) {
638 return this;
639 }
640
641 @Override
642 public boolean containsAnchor() {
643 return true;
644 }
645
646 @Override
647 protected void appendSourceCode(StringBuilder sb) {
648 sb.append(type);
649 }
650
651 @Override
652 protected void appendDebugInfo(StringBuilder sb) {
653 sb.append(type);
654 }
655
656 @Override
657 public boolean equals(Object o) {
658 return o instanceof Anchor && type == ((Anchor) o).type;
659 }
660
661 @Override
662 public int hashCode() {
663 return type ^ 0xe85317ff;
664 }
665 }
666
667 static final class WordBoundary extends RegExpTreeAtom {
668 final char type;
669
670 WordBoundary(char type) {
671 this.type = type;
672 }
673
674 @Override
675 public RegExpTree simplify(String flags) {
676 return this;
677 }
678
679 @Override
680 protected void appendSourceCode(StringBuilder sb) {
681 sb.append('\\').append(type);
682 }
683
684 @Override
685 protected void appendDebugInfo(StringBuilder sb) {
686 sb.append(type);
687 }
688
689 @Override
690 public boolean equals(Object o) {
691 return o instanceof WordBoundary && type == ((WordBoundary) o).type;
692 }
693
694 @Override
695 public int hashCode() {
696 return 0x5673aa29 ^ type;
697 }
698 }
699
700 static final class BackReference extends RegExpTreeAtom {
701 final int groupIndex;
702
703 BackReference(int groupIndex) {
704 Preconditions.checkArgument(groupIndex >= 0 && groupIndex <= 99);
705 this.groupIndex = groupIndex;
706 }
707
708 @Override
709 public RegExpTree simplify(String flags) {
710 return this;
711 }
712
713 @Override
714 protected void appendSourceCode(StringBuilder sb) {
715 sb.append('\\').append(groupIndex);
716 }
717
718 @Override
719 protected void appendDebugInfo(StringBuilder sb) {
720 sb.append(groupIndex);
721 }
722
723 @Override
724 public boolean equals(Object o) {
725 return o instanceof BackReference
726 && groupIndex == ((BackReference) o).groupIndex;
727 }
728
729 @Override
730 public int hashCode() {
731 return 0xff072663 ^ groupIndex;
732 }
733 }
734
735 static final class Text extends RegExpTreeAtom {
736 final String text;
737
738 Text(String text) {
739 this.text = text;
740 }
741
742 /**
743 * @param ch The code-unit to escape.
744 * @param next The next code-unit or -1 if indeterminable.
745 */
746 private static void escapeRegularCharOnto(
747 char ch, int next, StringBuilder sb) {
748 switch (ch) {
749 case '$':
750 case '^':
751 case '*':
752 case '(':
753 case ')':
754 case '+':
755 case '[':
756 case '|':
757 case '.':
758 case '/':
759 case '?':
760 sb.append('\\').append(ch);
761 break;
762 case '{':
763 // If possibly part of a repetition, then escape.
764 // Concatenation is handled by the digitsMightBleed check.
765 if ('0' <= next && next <= '9') {
766 sb.append('\\');
767 }
768 sb.append(ch);
769 break;
770 default:
771 escapeCharOnto(ch, sb);
772 }
773 }
774
775 @Override
776 public RegExpTree simplify(String flags) {
777 int n = text.length();
778 if (n == 0) {
779 return Empty.INSTANCE;
780 }
781 if (flags.indexOf('i') >= 0) {
782 String canonicalized = CaseCanonicalize.caseCanonicalize(text);
783 if (text != canonicalized) {
784 return new Text(canonicalized);
785 }
786 }
787 return this;
788 }
789
790 @Override
791 public boolean isCaseSensitive() {
792 for (int i = 0, n = text.length(); i < n; ++i) {
793 if (CaseCanonicalize.CASE_SENSITIVE.contains(text.charAt(i))) {
794 return true;
795 }
796 }
797 return false;
798 }
799
800 @Override
801 protected void appendSourceCode(StringBuilder sb) {
802 for (int i = 0, n = text.length(); i < n; ++i) {
803 escapeRegularCharOnto(text.charAt(i), i + 1 < n ? text.charAt(i + 1) : -1, sb);
804 }
805 }
806
807 @Override
808 protected void appendDebugInfo(StringBuilder sb) {
809 sb.append('`').append(text).append('`');
810 }
811
812 @Override
813 public boolean equals(Object o) {
814 return o instanceof Text && text.equals(((Text) o).text);
815 }
816
817 @Override
818 public int hashCode() {
819 return text.hashCode() ^ 0x617e310;
820 }
821 }
822
823 static final class Repetition extends RegExpTree {
824 final RegExpTree body;
825 final int min, max;
826 final boolean greedy;
827
828 Repetition(RegExpTree body, int min, int max, boolean greedy) {
829 this.body = body;
830 this.min = min;
831 this.max = max;
832 this.greedy = greedy;
833 }
834
835 @Override
836 public RegExpTree simplify(String flags) {
837 RegExpTree body = this.body.simplify(flags);
838 if (max == 0 && !body.hasCapturingGroup()) { return Empty.INSTANCE; }
839 if (body instanceof Empty || NEVER_MATCHES.equals(body)) { return body; }
840 int min = this.min;
841 int max = this.max;
842 if (body instanceof Repetition) {
843 Repetition rbody = (Repetition) body;
844 if (rbody.greedy == greedy) {
845 long lmin = ((long) min) * rbody.min;
846 long lmax = ((long) max) * rbody.max;
847 if (lmin < Integer.MAX_VALUE) {
848 body = rbody.body;
849 min = (int) lmin;
850 max = lmax >= Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) lmax;
851 }
852 }
853 }
854 if (min == 1 && max == 1) { return body; }
855 boolean greedy = this.greedy || min == max;
856 return body.equals(this.body) && min == this.min && max == this.max
857 && greedy == this.greedy
858 ? this
859 : new Repetition(body, min, max, greedy).simplify(flags);
860 }
861
862 @Override
863 public boolean isCaseSensitive() {
864 return body.isCaseSensitive();
865 }
866
867 @Override
868 public boolean containsAnchor() {
869 return body.containsAnchor();
870 }
871
872 @Override
873 public int numCapturingGroups() {
874 return body.numCapturingGroups();
875 }
876
877 @Override
878 public List<? extends RegExpTree> children() {
879 return ImmutableList.of(body);
880 }
881
882 private void appendBodySourceCode(StringBuilder sb) {
883 if (body instanceof Alternation || body instanceof Concatenation
884 || body instanceof Repetition
885 || (body instanceof Text && ((Text) body).text.length() > 1)) {
886 sb.append("(?:");
887 body.appendSourceCode(sb);
888 sb.append(')');
889 } else {
890 body.appendSourceCode(sb);
891 }
892 }
893
894 private static int suffixLen(int min, int max) {
895 // This mirrors the branches that renders a suffix in appendSourceCode below.
896 if (max == Integer.MAX_VALUE) {
897 switch (min) {
898 case 0: return 1; // *
899 case 1: return 1; // +
900 default: return 3 + numDecimalDigits(min); // {3,}
901 }
902 }
903 if (min == 0 && max == 1) {
904 return 1; // ?
905 }
906 if (min == max) {
907 if (min == 1) {
908 return 0; // No suffix needed for {1}.
909 }
910 return 2 + numDecimalDigits(min); // {4}
911 }
912 return 3 + numDecimalDigits(min) + numDecimalDigits(max); // {2,7}
913 }
914
915 private static int numDecimalDigits(int n) {
916 if (n < 0) {
917 // Negative values should not be passed in.
918 throw new AssertionError();
919 // If changing this code to support negative values,
920 // Integer.MIN_VALUE is a corner-case..
921 }
922 int nDigits = 1;
923 while (n >= 10) {
924 ++nDigits;
925 n /= 10;
926 }
927 return nDigits;
928 }
929
930 @Override
931 protected void appendSourceCode(StringBuilder sb) {
932 int bodyStart = sb.length();
933 appendBodySourceCode(sb);
934 int bodyEnd = sb.length();
935 int bodyLen = bodyEnd - bodyStart;
936 int min = this.min;
937 int max = this.max;
938 if (min >= 2 && max == Integer.MAX_VALUE || max - min <= 1) {
939 int expanded =
940 // If min == max then we want to try expanding to the limit and
941 // attach the empty suffix, which is equivalent to min = max = 1,
942 // i.e. /a/ vs /a{1}/.
943 min == max
944 // Give aa+ preference over aaa*.
945 || max == Integer.MAX_VALUE
946 ? min - 1
947 : min;
948 int expandedMin = min - expanded;
949 int expandedMax = max == Integer.MAX_VALUE ? max : max - expanded;
950 int suffixLen = suffixLen(min, max);
951 int expandedSuffixLen = suffixLen(expandedMin, expandedMax);
952 if (bodyLen * expanded + expandedSuffixLen < suffixLen
953 && !body.hasCapturingGroup()) {
954 // a{2} -> aa
955 // a{2,} -> aa+
956 // a{2,3} -> aaa?
957 while (--expanded >= 0) {
958 sb.append(sb, bodyStart, bodyEnd);
959 }
960 min = expandedMin;
961 max = expandedMax;
962 }
963 }
964
965 if (max == Integer.MAX_VALUE) {
966 switch (min) {
967 case 0: sb.append('*'); break;
968 case 1: sb.append('+'); break;
969 default:
970 sb.append('{').append(min).append(",}");
971 }
972 } else if (min == 0 && max == 1) {
973 sb.append('?');
974 } else if (min == max) {
975 if (min != 1) {
976 sb.append('{').append(min).append('}');
977 }
978 } else {
979 sb.append('{').append(min).append(',').append(max).append('}');
980 }
981 if (!greedy) {
982 sb.append('?');
983 }
984 }
985
986 @Override
987 protected void appendDebugInfo(StringBuilder sb) {
988 sb.append(" min=").append(min).append(", max=").append(max);
989 if (!greedy) { sb.append(" not_greedy"); }
990 }
991
992 @Override
993 public boolean equals(Object o) {
994 if (!(o instanceof Repetition)) { return false; }
995 Repetition that = (Repetition) o;
996 return this.body.equals(that.body)
997 && this.min == that.min
998 && this.max == that.max
999 && this.greedy == that.greedy;
1000 }
1001
1002 @Override
1003 public int hashCode() {
1004 return min + 31 * (max + 31 * ((greedy ? 1 : 0) + 31 * body.hashCode()));
1005 }
1006 }
1007
1008 static final class Alternation extends RegExpTree {
1009 final ImmutableList<RegExpTree> alternatives;
1010
1011 Alternation(List<? extends RegExpTree> alternatives) {
1012 this.alternatives = ImmutableList.copyOf(alternatives);
1013 }
1014
1015 @Override
1016 public RegExpTree simplify(String flags) {
1017 List<RegExpTree> alternatives = Lists.newArrayList();
1018 for (RegExpTree alternative : this.alternatives) {
1019 alternative = alternative.simplify(flags);
1020 if (alternative instanceof Alternation) {
1021 alternatives.addAll(((Alternation) alternative).alternatives);
1022 } else {
1023 alternatives.add(alternative);
1024 }
1025 }
1026 // Remove duplicates
1027 RegExpTree last = null;
1028 for (Iterator<RegExpTree> it = alternatives.iterator(); it.hasNext();) {
1029 RegExpTree alternative = it.next();
1030 if (alternative.equals(NEVER_MATCHES)) { continue; }
1031 if (alternative.equals(last) && !alternative.hasCapturingGroup()) {
1032 it.remove();
1033 } else {
1034 last = alternative;
1035 }
1036 }
1037 // Collapse character alternatives into character sets.
1038 for (int i = 0, n = alternatives.size(); i < n; ++i) {
1039 RegExpTree alternative = alternatives.get(i);
1040 if ((alternative instanceof Text
1041 && ((Text) alternative).text.length() == 1)
1042 || alternative instanceof Charset) {
1043 int end = i;
1044 int nCharsets = 0;
1045 while (end < n) {
1046 RegExpTree follower = alternatives.get(end);
1047 if (follower instanceof Charset) {
1048 ++nCharsets;
1049 } else if (!(follower instanceof Text
1050 && ((Text) follower).text.length() == 1)) {
1051 break;
1052 }
1053 ++end;
1054 }
1055 if (end - i >= 3 || (nCharsets != 0 && end - i >= 2)) {
1056 int[] members = new int[end - i - nCharsets];
1057 int memberIdx = 0;
1058 CharRanges chars = CharRanges.EMPTY;
1059 CharRanges ieExplicits = CharRanges.EMPTY;
1060 List<RegExpTree> charAlternatives = alternatives.subList(i, end);
1061 for (RegExpTree charAlternative : charAlternatives) {
1062 if (charAlternative instanceof Text) {
1063 char ch = ((Text) charAlternative).text.charAt(0);
1064 members[memberIdx++] = ch;
1065 if (IE_SPEC_ERRORS.contains(ch)) {
1066 ieExplicits = ieExplicits.union(CharRanges.inclusive(ch, ch));
1067 }
1068 } else if (charAlternative instanceof Charset) {
1069 Charset cs = (Charset) charAlternative;
1070 chars = chars.union(cs.ranges);
1071 ieExplicits = ieExplicits.union(cs.ieExplicits);
1072 }
1073 }
1074 chars = chars.union(CharRanges.withMembers(members));
1075 charAlternatives.clear();
1076 charAlternatives.add(
1077 new Charset(chars, ieExplicits).simplify(flags));
1078 n = alternatives.size();
1079 }
1080 }
1081 }
1082 switch (alternatives.size()) {
1083 case 0: return Empty.INSTANCE;
1084 case 1: return alternatives.get(0);
1085 case 2:
1086 if (alternatives.get(1) instanceof Empty) { // (?:a|) -> a?
1087 return new Repetition(alternatives.get(0), 0, 1, true);
1088 } else if (alternatives.get(0) instanceof Empty) {
1089 return new Repetition(alternatives.get(1), 0, 1, false);
1090 }
1091 break;
1092 }
1093 // TODO: maybe pull out common prefix or suffix
1094 return alternatives.equals(this.alternatives)
1095 ? this : new Alternation(alternatives);
1096 }
1097
1098 @Override
1099 public boolean isCaseSensitive() {
1100 for (RegExpTree alternative : alternatives) {
1101 if (alternative.isCaseSensitive()) { return true; }
1102 }
1103 return false;
1104 }
1105
1106 @Override
1107 public boolean containsAnchor() {
1108 for (RegExpTree alternative : alternatives) {
1109 if (alternative.containsAnchor()) { return true; }
1110 }
1111 return false;
1112 }
1113
1114 @Override
1115 public int numCapturingGroups() {
1116 int n = 0;
1117 for (RegExpTree alternative : alternatives) {
1118 n += alternative.numCapturingGroups();
1119 }
1120 return n;
1121 }
1122
1123 @Override
1124 public List<? extends RegExpTree> children() {
1125 return alternatives;
1126 }
1127
1128 @Override
1129 protected void appendSourceCode(StringBuilder sb) {
1130 for (int i = 0, n = alternatives.size(); i < n; ++i) {
1131 if (i != 0) {
1132 sb.append('|');
1133 }
1134 alternatives.get(i).appendSourceCode(sb);
1135 }
1136 }
1137
1138 @Override
1139 protected void appendDebugInfo(StringBuilder sb) {
1140 // Nothing besides children.
1141 }
1142
1143 @Override
1144 public boolean equals(Object o) {
1145 return this == o || (
1146 (o instanceof Alternation)
1147 && alternatives.equals(((Alternation) o).alternatives));
1148 }
1149
1150 @Override
1151 public int hashCode() {
1152 return 0x51b57cd1 ^ alternatives.hashCode();
1153 }
1154 }
1155
1156 private static final RegExpTree NEVER_MATCHES = new LookaheadAssertion(
1157 Empty.INSTANCE, false);
1158
1159 static final class LookaheadAssertion extends RegExpTree {
1160 final RegExpTree body;
1161 final boolean positive;
1162
1163 LookaheadAssertion(RegExpTree body, boolean positive) {
1164 this.body = body;
1165 this.positive = positive;
1166 }
1167
1168 @Override
1169 public RegExpTree simplify(String flags) {
1170 RegExpTree simpleBody = body.simplify(flags);
1171 if (simpleBody instanceof Empty) {
1172 if (positive) { // Always true
1173 return simpleBody;
1174 }
1175 }
1176 return new LookaheadAssertion(simpleBody, positive);
1177 }
1178
1179 @Override
1180 public boolean isCaseSensitive() {
1181 return body.isCaseSensitive();
1182 }
1183
1184 @Override
1185 public boolean containsAnchor() {
1186 return body.containsAnchor();
1187 }
1188
1189 @Override
1190 public int numCapturingGroups() {
1191 return body.numCapturingGroups();
1192 }
1193
1194 @Override
1195 public List<? extends RegExpTree> children() {
1196 return ImmutableList.of(body);
1197 }
1198
1199 @Override
1200 protected void appendSourceCode(StringBuilder sb) {
1201 sb.append(positive ? "(?=" : "(?!");
1202 body.appendSourceCode(sb);
1203 sb.append(')');
1204 }
1205
1206 @Override
1207 protected void appendDebugInfo(StringBuilder sb) {
1208 sb.append(positive ? "positive" : "negative");
1209 }
1210
1211 @Override
1212 public boolean equals(Object o) {
1213 if (!(o instanceof LookaheadAssertion)) { return false; }
1214 LookaheadAssertion that = (LookaheadAssertion) o;
1215 return this.positive == that.positive && this.body.equals(that.body);
1216 }
1217
1218 @Override
1219 public int hashCode() {
1220 return 0x723aba9 ^ body.hashCode();
1221 }
1222 }
1223
1224 static final class CapturingGroup extends RegExpTree {
1225 final RegExpTree body;
1226
1227 CapturingGroup(RegExpTree body) {
1228 this.body = body;
1229 }
1230
1231 @Override
1232 public RegExpTree simplify(String flags) {
1233 return new CapturingGroup(body.simplify(flags));
1234 }
1235
1236 @Override
1237 public boolean isCaseSensitive() {
1238 return body.isCaseSensitive();
1239 }
1240
1241 @Override
1242 public boolean containsAnchor() {
1243 return body.containsAnchor();
1244 }
1245
1246 @Override
1247 public int numCapturingGroups() {
1248 return 1;
1249 }
1250
1251 @Override
1252 public List<? extends RegExpTree> children() {
1253 return ImmutableList.of(body);
1254 }
1255
1256 @Override
1257 protected void appendSourceCode(StringBuilder sb) {
1258 sb.append('(');
1259 body.appendSourceCode(sb);
1260 sb.append(')');
1261 }
1262
1263 @Override
1264 protected void appendDebugInfo(StringBuilder sb) {
1265 // Nothing besides children.
1266 }
1267
1268 @Override
1269 public boolean equals(Object o) {
1270 return o instanceof CapturingGroup
1271 && body.equals(((CapturingGroup) o).body);
1272 }
1273
1274 @Override
1275 public int hashCode() {
1276 return 0x55781738 ^ body.hashCode();
1277 }
1278 }
1279
1280 private static final CharRanges DIGITS = CharRanges.inclusive('0', '9');
1281
1282 private static final CharRanges UCASE_LETTERS
1283 = CharRanges.inclusive('A', 'Z');
1284
1285 private static final CharRanges LCASE_LETTERS
1286 = CharRanges.inclusive('a', 'z');
1287
1288 private static final CharRanges LETTERS = UCASE_LETTERS.union(LCASE_LETTERS);
1289
1290 private static final CharRanges WORD_CHARS = DIGITS
1291 .union(LETTERS).union(CharRanges.withMembers('_'));
1292
1293 private static final CharRanges INVERSE_WORD_CHARS
1294 = CharRanges.ALL_CODE_UNITS.difference(WORD_CHARS);
1295
1296 private static final CharRanges SPACE_CHARS = CharRanges.withMembers(
1297 '\t', '\n', '\u000b', '\u000c', '\r', ' ', '\u00a0',
1298 // Unicode 3.0 Zs
1299 '\u1680', '\u180e', '\u2000', '\u2001',
1300 '\u2002', '\u2003', '\u2004', '\u2005',
1301 '\u2006', '\u2007', '\u2008', '\u2009',
1302 '\u200a',
1303 // Line terminator chars
1304 '\u2028', '\u2029',
1305 // Unicode 3.0 Zs
1306 '\u202f', '\u205f', '\u3000',
1307 // Byte order marker is a space character in ES5 but not ES3.
1308 '\ufeff'
1309 );
1310
1311 /** IE is broken around \s. IE (6, 7, 8 at least), only recognize these. */
1312 private static final CharRanges IE_SPACE_CHARS = CharRanges.withMembers(
1313 '\t', '\n', '\u000b', '\u000c', '\r', ' '
1314 );
1315
1316 /** IE is broken around \s. IE (6, 7, 8 at least), only recognize these. */
1317 private static final CharRanges IE_SPEC_ERRORS = SPACE_CHARS.difference(
1318 IE_SPACE_CHARS);
1319
1320 private static final ImmutableMap<Character, CharRanges> NAMED_CHAR_GROUPS
1321 = ImmutableMap.<Character, CharRanges>builder()
1322 .put('d', DIGITS)
1323 .put('D', CharRanges.ALL_CODE_UNITS.difference(DIGITS))
1324 .put('s', SPACE_CHARS)
1325 .put('S', CharRanges.ALL_CODE_UNITS.difference(SPACE_CHARS))
1326 .put('w', WORD_CHARS)
1327 .put('W', INVERSE_WORD_CHARS)
1328 .build();
1329
1330 private static final Charset DOT_CHARSET = new Charset(
1331 CharRanges.ALL_CODE_UNITS.difference(
1332 CharRanges.withMembers('\n', '\r', '\u2028', '\u2029')),
1333 CharRanges.EMPTY);
1334
1335 static final class Charset extends RegExpTreeAtom {
1336 final CharRanges ranges;
1337 /**
1338 * Code units that were mentioned explicitly and that might be matched by
1339 * a group according to ECMAScript 5 but would not because of specification
1340 * violations in IE.
1341 */
1342 final CharRanges ieExplicits;
1343
1344 Charset(CharRanges ranges, CharRanges ieExplicits) {
1345 this.ranges = ranges;
1346 this.ieExplicits = ieExplicits;
1347 }
1348
1349 private static int complexityWordFolded(CharRanges ranges) {
1350 return Math.min(
1351 complexityWordFoldedHelper(ranges),
1352 1 + complexityWordFoldedHelper(
1353 CharRanges.ALL_CODE_UNITS.difference(ranges)));
1354 }
1355
1356 private static int complexityWordFoldedHelper(CharRanges ranges) {
1357 int complexity = DecomposedCharset.complexity(ranges);
1358 if (ranges.containsAll(WORD_CHARS)) {
1359 complexity = Math.min(
1360 complexity,
1361 1 + DecomposedCharset.complexity(ranges.difference(WORD_CHARS)));
1362 }
1363 if (ranges.containsAll(INVERSE_WORD_CHARS)) {
1364 complexity = Math.min(
1365 complexity,
1366 1 + DecomposedCharset.complexity(
1367 ranges.difference(INVERSE_WORD_CHARS)));
1368 }
1369 return complexity;
1370 }
1371
1372 @Override
1373 public RegExpTree simplify(String flags) {
1374 if (ranges.isEmpty()) {
1375 return NEVER_MATCHES;
1376 }
1377 CharRanges best = ranges;
1378 if (flags.indexOf('i') >= 0) {
1379 Set<CharRanges> options = Sets.newLinkedHashSet();
1380 options.add(CaseCanonicalize.expandToAllMatched(ranges));
1381 options.add(CaseCanonicalize.reduceToMinimum(ranges));
1382
1383 CharRanges lcaseLetters = ranges.intersection(LCASE_LETTERS);
1384 CharRanges ucaseLetters = ranges.intersection(UCASE_LETTERS);
1385
1386 CharRanges lcaseLettersToUpper = lcaseLetters.shift(-32);
1387 CharRanges ucaseLettersToLower = ucaseLetters.shift(32);
1388
1389 options.add(ranges.union(ucaseLettersToLower));
1390 options.add(ranges.union(lcaseLettersToUpper));
1391 options.add(ranges.union(lcaseLettersToUpper)
1392 .union(ucaseLettersToLower));
1393
1394 options.add(ranges.union(ucaseLettersToLower).difference(ucaseLetters));
1395 options.add(ranges.union(lcaseLettersToUpper).difference(lcaseLetters));
1396
1397 int bestComplexity = complexityWordFolded(ranges);
1398
1399 for (CharRanges option : options) {
1400 int complexity = complexityWordFolded(option);
1401 if (complexity < bestComplexity) {
1402 bestComplexity = complexity;
1403 best = option;
1404 }
1405 }
1406 }
1407
1408 if (best.getNumRanges() == 1
1409 && best.end(0) - best.start(0) == 1) {
1410 return new Text(Character.toString((char) best.start(0)));
1411 }
1412
1413 if (!best.equals(ranges)) {
1414 return new Charset(best, ieExplicits);
1415 }
1416
1417 return this;
1418 }
1419
1420 @Override
1421 public boolean isCaseSensitive() {
1422 // We could test
1423 // !ranges.equals(CaseCanonicalize.expandToAllMatched(ranges))
1424 // but we get better optimizations by leaving the 'i' flag on in most
1425 // cases.
1426
1427 // Check whether skipping all the character groups that are known
1428 // case-insensitive leaves us with something that matches the above
1429 // definition.
1430 CharRanges withoutNamedGroups = decompose().ranges;
1431 return !withoutNamedGroups.equals(
1432 CaseCanonicalize.expandToAllMatched(withoutNamedGroups));
1433 }
1434
1435 private DecomposedCharset decompose(CharRanges ranges, boolean inverted) {
1436 StringBuilder namedGroups = new StringBuilder();
1437 CharRanges rangesInterIeExplicits = ranges.intersection(ieExplicits);
1438 while (true) {
1439 char groupName = 0;
1440 CharRanges simplest = null;
1441 int minComplexity = DecomposedCharset.complexity(ranges);
1442 for (Map.Entry<Character, CharRanges> namedGroup
1443 : NAMED_CHAR_GROUPS.entrySet()) {
1444 CharRanges group = namedGroup.getValue();
1445 if (ranges.containsAll(group)) {
1446 CharRanges withoutGroup = ranges.difference(group).union(
1447 rangesInterIeExplicits);
1448 int complexity = DecomposedCharset.complexity(withoutGroup);
1449 if (complexity < minComplexity) {
1450 simplest = withoutGroup;
1451 groupName = namedGroup.getKey().charValue();
1452 minComplexity = complexity;
1453 }
1454 }
1455 }
1456 if (simplest != null) {
1457 namedGroups.append('\\').append(groupName);
1458 ranges = simplest;
1459 } else {
1460 break;
1461 }
1462 }
1463 return new DecomposedCharset(inverted, ranges, namedGroups.toString());
1464 }
1465
1466 @Override
1467 protected void appendSourceCode(StringBuilder sb) {
1468 if (DOT_CHARSET.ranges.equals(ranges)) {
1469 sb.append('.');
1470 return;
1471 }
1472 decompose().appendSourceCode(sb);
1473 }
1474
1475 DecomposedCharset decompose() {
1476 CharRanges negRanges = CharRanges.ALL_CODE_UNITS.difference(ranges);
1477 if (!ieExplicits.isEmpty()) {
1478 if (negRanges.intersection(ieExplicits).isEmpty()) {
1479 return decompose(ranges, false);
1480 } else if (ranges.intersection(ieExplicits).isEmpty()) {
1481 return decompose(negRanges, true);
1482 }
1483 }
1484 DecomposedCharset positive = decompose(ranges, false);
1485 DecomposedCharset negative = decompose(negRanges, true);
1486 return positive.complexity() <= negative.complexity()
1487 ? positive : negative;
1488 }
1489
1490 @Override
1491 protected void appendDebugInfo(StringBuilder sb) {
1492 sb.append(ranges);
1493 }
1494
1495 @Override
1496 public boolean equals(Object o) {
1497 return o instanceof Charset && ranges.equals(((Charset) o).ranges);
1498 }
1499
1500 @Override
1501 public int hashCode() {
1502 return ranges.hashCode() ^ 0xdede2246;
1503 }
1504 }
1505
1506 static final class DecomposedCharset {
1507 boolean inverted;
1508 final CharRanges ranges;
1509 final String namedGroups;
1510
1511 DecomposedCharset(
1512 boolean inverted, CharRanges ranges, String namedGroups) {
1513 this.inverted = inverted;
1514 this.ranges = ranges;
1515 this.namedGroups = namedGroups;
1516 }
1517
1518 int complexity() {
1519 return (inverted ? 1 : 0) + namedGroups.length() + complexity(ranges);
1520 }
1521
1522 void appendSourceCode(StringBuilder sb) {
1523 if (ranges.isEmpty()) {
1524 if (!inverted && namedGroups.length() == 2) {
1525 sb.append(namedGroups);
1526 return;
1527 } else if (ranges.isEmpty() && namedGroups.length() == 0) {
1528 sb.append(inverted ? "[\\S\\s]" : "(?!)");
1529 return;
1530 }
1531 }
1532 sb.append('[');
1533 if (inverted) { sb.append('^'); }
1534 sb.append(namedGroups);
1535 boolean rangesStartCharset = !inverted && namedGroups.length() == 0;
1536 boolean emitDashAtEnd = false;
1537 for (int i = 0, n = ranges.getNumRanges(); i < n; ++i) {
1538 char start = (char) ranges.start(i);
1539 char end = (char) (ranges.end(i) - 1);
1540 switch (end - start) {
1541 case 0:
1542 if (start == '-') {
1543 // Put it at the end where it doesn't need escaping.
1544 emitDashAtEnd = true;
1545 } else {
1546 escapeRangeCharOnto(
1547 start, rangesStartCharset, i == 0, i + 1 == n, sb);
1548 }
1549 break;
1550 case 1:
1551 escapeRangeCharOnto(start, rangesStartCharset, i == 0, false, sb);
1552 escapeRangeCharOnto(
1553 end, rangesStartCharset, false, i + 1 == n, sb);
1554 break;
1555 default:
1556 escapeRangeCharOnto(start, rangesStartCharset, i == 0, false, sb);
1557 sb.append('-');
1558 escapeRangeCharOnto(end, rangesStartCharset, false, true, sb);
1559 break;
1560 }
1561 }
1562 if (emitDashAtEnd) { sb.append('-'); }
1563 sb.append(']');
1564 }
1565
1566 static void escapeRangeCharOnto(
1567 char ch, boolean startIsFlush, boolean atStart, boolean atEnd,
1568 StringBuilder sb) {
1569 switch (ch) {
1570 case '\b':
1571 sb.append("\\b");
1572 break;
1573 case '^':
1574 sb.append(atStart && startIsFlush ? "\\^" : "^");
1575 break;
1576 case '-':
1577 sb.append(atStart || atEnd ? "-" : "\\-");
1578 break;
1579 case '\\':
1580 case ']':
1581 sb.append('\\').append(ch);
1582 break;
1583 default:
1584 escapeCharOnto(ch, sb);
1585 }
1586 }
1587
1588 static int complexity(CharRanges ranges) {
1589 int complexity = 0;
1590 for (int i = 0, n = ranges.getNumRanges(); i < n; ++i) {
1591 int start = ranges.start(i);
1592 int end = ranges.end(i) - 1;
1593 if (start < 0x20 || start >= 0x7f) {
1594 complexity += start >= 0x100 ? 6 : 4;
1595 } else {
1596 ++complexity;
1597 }
1598 switch (end - start) {
1599 case 0: continue;
1600 case 1: break;
1601 default: complexity += 1;
1602 }
1603 if (end < 0x20 || end >= 0x7f) {
1604 complexity += end >= 0x100 ? 6 : 4;
1605 } else {
1606 ++complexity;
1607 }
1608 }
1609 return complexity;
1610 }
1611
1612 @Override
1613 public boolean equals(Object o) {
1614 if (!(o instanceof DecomposedCharset)) {
1615 return false;
1616 }
1617 DecomposedCharset that = (DecomposedCharset) o;
1618 return this.inverted = that.inverted
1619 && this.ranges.equals(that.ranges)
1620 && this.namedGroups.equals(that.namedGroups);
1621 }
1622
1623 @Override
1624 public int hashCode() {
1625 return ranges.hashCode()
1626 + 31 * (namedGroups.hashCode() + (inverted ? 1 : 0));
1627 }
1628 }
1629
1630 static final class Concatenation extends RegExpTree {
1631 final ImmutableList<RegExpTree> elements;
1632
1633 Concatenation(RegExpTree a, RegExpTree b) {
1634 elements = ImmutableList.of(a, b);
1635 }
1636
1637 Concatenation(List<? extends RegExpTree> elements) {
1638 this.elements = ImmutableList.copyOf(elements);
1639 }
1640
1641 @Override
1642 public RegExpTree simplify(final String flags) {
1643 class Simplifier {
1644 final List<RegExpTree> simplified = Lists.newArrayList();
1645
1646 void simplify(RegExpTree t) {
1647 if (t instanceof Concatenation) {
1648 for (RegExpTree child : ((Concatenation) t).elements) {
1649 simplify(child);
1650 }
1651 } else if (t instanceof Empty) {
1652 // Do nothing
1653 } else {
1654 int lastIndex = simplified.size() - 1;
1655 if (lastIndex >= 0) {
1656 RegExpTree pairwise = simplifyPairwise(
1657 simplified.get(lastIndex), t);
1658 if (pairwise != null) {
1659 simplified.set(lastIndex, pairwise);
1660 return;
1661 }
1662 }
1663 simplified.add(t);
1664 }
1665 }
1666
1667 RegExpTree simplifyPairwise(RegExpTree before, RegExpTree after) {
1668 if (before instanceof Text && after instanceof Text) {
1669 return new Text(
1670 ((Text) before).text + ((Text) after).text).simplify(flags);
1671 }
1672 // Fold adjacent repetitions.
1673 int beforeMin = 1, beforeMax = 1;
1674 RegExpTree beforeBody = before;
1675 boolean beforeGreedy = false;
1676 if (before instanceof Repetition) {
1677 Repetition r = (Repetition) before;
1678 beforeMin = r.min;
1679 beforeMax = r.max;
1680 beforeBody = r.body;
1681 beforeGreedy = r.greedy;
1682 }
1683 int afterMin = 1, afterMax = 1;
1684 RegExpTree afterBody = after;
1685 boolean afterGreedy = false;
1686 if (after instanceof Repetition) {
1687 Repetition r = (Repetition) after;
1688 afterMin = r.min;
1689 afterMax = r.max;
1690 afterBody = r.body;
1691 afterGreedy = r.greedy;
1692 }
1693 if (beforeBody.equals(afterBody)
1694 && !beforeBody.hasCapturingGroup()) {
1695 long lmin = ((long) beforeMin) + afterMin;
1696 long lmax = ((long) beforeMax) + afterMax;
1697 if (lmin < Integer.MAX_VALUE) {
1698 int min = (int) lmin;
1699 int max = lmax >= Integer.MAX_VALUE
1700 ? Integer.MAX_VALUE : (int) lmax;
1701 return new Repetition(
1702 beforeBody, min, max,
1703 beforeGreedy || afterGreedy || min == max);
1704 }
1705 }
1706 return null;
1707 }
1708 }
1709
1710 Simplifier s = new Simplifier();
1711 for (RegExpTree element : elements) {
1712 s.simplify(element.simplify(flags));
1713 }
1714
1715 switch (s.simplified.size()) {
1716 case 0: return Empty.INSTANCE;
1717 case 1: return s.simplified.get(0);
1718 default: return new Concatenation(s.simplified);
1719 }
1720 }
1721
1722 @Override
1723 public boolean isCaseSensitive() {
1724 for (RegExpTree element : elements) {
1725 if (element.isCaseSensitive()) {
1726 return true;
1727 }
1728 }
1729 return false;
1730 }
1731
1732 @Override
1733 public boolean containsAnchor() {
1734 for (RegExpTree element : elements) {
1735 if (element.containsAnchor()) {
1736 return true;
1737 }
1738 }
1739 return false;
1740 }
1741
1742 @Override
1743 public int numCapturingGroups() {
1744 int n = 0;
1745 for (RegExpTree element : elements) {
1746 n += element.numCapturingGroups();
1747 }
1748 return n;
1749 }
1750
1751 @Override
1752 public List<? extends RegExpTree> children() {
1753 return elements;
1754 }
1755
1756 @Override
1757 protected void appendSourceCode(StringBuilder sb) {
1758 // True if the last content written might consume
1759 // decimal digits written subsequently.
1760 boolean digitsMightBleed = false;
1761 for (RegExpTree element : elements) {
1762 boolean parenthesize = false;
1763 if (element instanceof Alternation
1764 || element instanceof Concatenation) {
1765 parenthesize = true;
1766 }
1767 if (parenthesize) {
1768 sb.append("(?:");
1769 element.appendSourceCode(sb);
1770 sb.append(')');
1771 } else {
1772 int start = sb.length();
1773 element.appendSourceCode(sb);
1774 if (digitsMightBleed && sb.length() > start) {
1775 char firstChar = sb.charAt(start);
1776 if ('0' <= firstChar && firstChar <= '9') {
1777 // Bleeding happened.
1778 // If the last character would be ambiguous
1779 // with a repetition, escape it.
1780 if (sb.charAt(start - 1) == '{') {
1781 // Concatenation from optimization of
1782 // /{(?:0,}/ -> /\{0,}/
1783 sb.insert(start - 1, '\\');
1784 } else {
1785 // Or parenthesize otherwise.
1786 // Concatenation from optimization of
1787 // /(.)\1(?:0)/ -> /(.)\1(?:0)/.
1788 sb.insert(start, "(?:").append(')');
1789 }
1790 }
1791 }
1792 }
1793 digitsMightBleed = (
1794 // \1(?:0) bleeds if there are 10 or more
1795 // capturing groups preceding.
1796 (element instanceof BackReference
1797 && ((BackReference) element).groupIndex < 10)
1798 // foo{(?:10}) bleeds.
1799 || (element instanceof Text
1800 && ((Text) element).text.endsWith("{")));
1801 }
1802 }
1803
1804 @Override
1805 protected void appendDebugInfo(StringBuilder sb) {
1806 // Nothing besides children.
1807 }
1808
1809 @Override
1810 public boolean equals(Object o) {
1811 return o instanceof Concatenation
1812 && elements.equals(((Concatenation) o).elements);
1813 }
1814
1815 @Override
1816 public int hashCode() {
1817 return 0x20997e3e ^ elements.hashCode();
1818 }
1819 }
1820
1821 static void escapeCharOnto(char ch, StringBuilder sb) {
1822 switch (ch) {
1823 case '\u0000':
1824 sb.append("\\0");
1825 break;
1826 case '\f':
1827 sb.append("\\f");
1828 break;
1829 case '\t':
1830 sb.append("\\t");
1831 break;
1832 case '\n':
1833 sb.append("\\n");
1834 break;
1835 case '\r':
1836 sb.append("\\r");
1837 break;
1838 case '\\':
1839 sb.append("\\\\");
1840 break;
1841 default:
1842 if (ch < 0x20 || ch >= 0x7f) {
1843 if (ch >= 0x100) {
1844 sb.append("\\u");
1845 sb.append("0123456789abcdef".charAt((ch >> 12) & 0xf));
1846 sb.append("0123456789abcdef".charAt((ch >> 8) & 0xf));
1847 sb.append("0123456789abcdef".charAt((ch >> 4) & 0xf));
1848 sb.append("0123456789abcdef".charAt((ch) & 0xf));
1849 } else {
1850 sb.append("\\x");
1851 sb.append("0123456789abcdef".charAt((ch >> 4) & 0xf));
1852 sb.append("0123456789abcdef".charAt((ch) & 0xf));
1853 }
1854 } else {
1855 sb.append(ch);
1856 }
1857 }
1858 }
1859 }