New Pattern.java
1 /*
2 * %W% %E%
3 *
4 * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6 */
7
8 package java.util.regex;
9
10 import java.security.AccessController;
11 import java.security.PrivilegedAction;
12 import java.text.CharacterIterator;
13 import java.text.Normalizer;
14 import java.util.ArrayList;
15 import java.util.HashMap;
16
17
18 /**
19 * A compiled representation of a regular expression.
20 *
21 * <p> A regular expression, specified as a string, must first be compiled into
22 * an instance of this class. The resulting pattern can then be used to create
23 * a {@link Matcher} object that can match arbitrary {@link
24 * java.lang.CharSequence </code>character sequences<code>} against the regular
25 * expression. All of the state involved in performing a match resides in the
26 * matcher, so many matchers can share the same pattern.
27 *
28 * <p> A typical invocation sequence is thus
29 *
30 * <blockquote><pre>
31 * Pattern p = Pattern.{@link #compile compile}("a*b");
32 * Matcher m = p.{@link #matcher matcher}("aaaaab");
33 * boolean b = m.{@link Matcher#matches matches}();</pre></blockquote>
34 *
35 * <p> A {@link #matches matches} method is defined by this class as a
36 * convenience for when a regular expression is used just once. This method
37 * compiles an expression and matches an input sequence against it in a single
38 * invocation. The statement
39 *
40 * <blockquote><pre>
41 * boolean b = Pattern.matches("a*b", "aaaaab");</pre></blockquote>
42 *
43 * is equivalent to the three statements above, though for repeated matches it
44 * is less efficient since it does not allow the compiled pattern to be reused.
45 *
46 * <p> Instances of this class are immutable and are safe for use by multiple
47 * concurrent threads. Instances of the {@link Matcher} class are not safe for
48 * such use.
49 *
50 *
51 * <a name="sum">
52 * <h4> Summary of regular-expression constructs </h4>
53 *
54 * <table border="0" cellpadding="1" cellspacing="0"
55 * summary="Regular expression constructs, and what they match">
56 *
57 * <tr align="left">
58 * <th bgcolor="#CCCCFF" align="left" id="construct">Construct</th>
59 * <th bgcolor="#CCCCFF" align="left" id="matches">Matches</th>
60 * </tr>
61 *
62 * <tr><th> </th></tr>
63 * <tr align="left"><th colspan="2" id="characters">Characters</th></tr>
64 *
65 * <tr><td valign="top" headers="construct characters"><i>x</i></td>
66 * <td headers="matches">The character <i>x</i></td></tr>
67 * <tr><td valign="top" headers="construct characters"><tt>\\</tt></td>
68 * <td headers="matches">The backslash character</td></tr>
69 * <tr><td valign="top" headers="construct characters"><tt>\0</tt><i>n</i></td>
70 * <td headers="matches">The character with octal value <tt>0</tt><i>n</i>
71 * (0 <tt><=</tt> <i>n</i> <tt><=</tt> 7)</td></tr>
72 * <tr><td valign="top" headers="construct characters"><tt>\0</tt><i>nn</i></td>
73 * <td headers="matches">The character with octal value <tt>0</tt><i>nn</i>
74 * (0 <tt><=</tt> <i>n</i> <tt><=</tt> 7)</td></tr>
75 * <tr><td valign="top" headers="construct characters"><tt>\0</tt><i>mnn</i></td>
76 * <td headers="matches">The character with octal value <tt>0</tt><i>mnn</i>
77 * (0 <tt><=</tt> <i>m</i> <tt><=</tt> 3,
78 * 0 <tt><=</tt> <i>n</i> <tt><=</tt> 7)</td></tr>
79 * <tr><td valign="top" headers="construct characters"><tt>\x</tt><i>hh</i></td>
80 * <td headers="matches">The character with hexadecimal value <tt>0x</tt><i>hh</i></td></tr>
81 * <tr><td valign="top" headers="construct characters"><tt>\u</tt><i>hhhh</i></td>
82 * <td headers="matches">The character with hexadecimal value <tt>0x</tt><i>hhhh</i></td></tr>
83 * <tr><td valign="top" headers="matches"><tt>\t</tt></td>
84 * <td headers="matches">The tab character (<tt>'\u0009'</tt>)</td></tr>
85 * <tr><td valign="top" headers="construct characters"><tt>\n</tt></td>
86 * <td headers="matches">The newline (line feed) character (<tt>'\u000A'</tt>)</td></tr>
87 * <tr><td valign="top" headers="construct characters"><tt>\r</tt></td>
88 * <td headers="matches">The carriage-return character (<tt>'\u000D'</tt>)</td></tr>
89 * <tr><td valign="top" headers="construct characters"><tt>\f</tt></td>
90 * <td headers="matches">The form-feed character (<tt>'\u000C'</tt>)</td></tr>
91 * <tr><td valign="top" headers="construct characters"><tt>\a</tt></td>
92 * <td headers="matches">The alert (bell) character (<tt>'\u0007'</tt>)</td></tr>
93 * <tr><td valign="top" headers="construct characters"><tt>\e</tt></td>
94 * <td headers="matches">The escape character (<tt>'\u001B'</tt>)</td></tr>
95 * <tr><td valign="top" headers="construct characters"><tt>\c</tt><i>x</i></td>
96 * <td headers="matches">The control character corresponding to <i>x</i></td></tr>
97 *
98 * <tr><th> </th></tr>
99 * <tr align="left"><th colspan="2" id="classes">Character classes</th></tr>
100 *
101 * <tr><td valign="top" headers="construct classes"><tt>[abc]</tt></td>
102 * <td headers="matches"><tt>a</tt>, <tt>b</tt>, or <tt>c</tt> (simple class)</td></tr>
103 * <tr><td valign="top" headers="construct classes"><tt>[^abc]</tt></td>
104 * <td headers="matches">Any character except <tt>a</tt>, <tt>b</tt>, or <tt>c</tt> (negation)</td></tr>
105 * <tr><td valign="top" headers="construct classes"><tt>[a-zA-Z]</tt></td>
106 * <td headers="matches"><tt>a</tt> through <tt>z</tt>
107 * or <tt>A</tt> through <tt>Z</tt>, inclusive (range)</td></tr>
108 * <tr><td valign="top" headers="construct classes"><tt>[a-d[m-p]]</tt></td>
109 * <td headers="matches"><tt>a</tt> through <tt>d</tt>,
110 * or <tt>m</tt> through <tt>p</tt>: <tt>[a-dm-p]</tt> (union)</td></tr>
111 * <tr><td valign="top" headers="construct classes"><tt>[a-z&&[def]]</tt></td>
112 * <td headers="matches"><tt>d</tt>, <tt>e</tt>, or <tt>f</tt> (intersection)</tr>
113 * <tr><td valign="top" headers="construct classes"><tt>[a-z&&[^bc]]</tt></td>
114 * <td headers="matches"><tt>a</tt> through <tt>z</tt>,
115 * except for <tt>b</tt> and <tt>c</tt>: <tt>[ad-z]</tt> (subtraction)</td></tr>
116 * <tr><td valign="top" headers="construct classes"><tt>[a-z&&[^m-p]]</tt></td>
117 * <td headers="matches"><tt>a</tt> through <tt>z</tt>,
118 * and not <tt>m</tt> through <tt>p</tt>: <tt>[a-lq-z]</tt>(subtraction)</td></tr>
119 * <tr><th> </th></tr>
120 *
121 * <tr align="left"><th colspan="2" id="predef">Predefined character classes</th></tr>
122 *
123 * <tr><td valign="top" headers="construct predef"><tt>.</tt></td>
124 * <td headers="matches">Any character (may or may not match <a href="#lt">line terminators</a>)</td></tr>
125 * <tr><td valign="top" headers="construct predef"><tt>\d</tt></td>
126 * <td headers="matches">A digit: <tt>[0-9]</tt></td></tr>
127 * <tr><td valign="top" headers="construct predef"><tt>\D</tt></td>
128 * <td headers="matches">A non-digit: <tt>[^0-9]</tt></td></tr>
129 * <tr><td valign="top" headers="construct predef"><tt>\s</tt></td>
130 * <td headers="matches">A whitespace character: <tt>[ \t\n\x0B\f\r]</tt></td></tr>
131 * <tr><td valign="top" headers="construct predef"><tt>\S</tt></td>
132 * <td headers="matches">A non-whitespace character: <tt>[^\s]</tt></td></tr>
133 * <tr><td valign="top" headers="construct predef"><tt>\w</tt></td>
134 * <td headers="matches">A word character: <tt>[a-zA-Z_0-9]</tt></td></tr>
135 * <tr><td valign="top" headers="construct predef"><tt>\W</tt></td>
136 * <td headers="matches">A non-word character: <tt>[^\w]</tt></td></tr>
137 *
138 * <tr><th> </th></tr>
139 * <tr align="left"><th colspan="2" id="posix">POSIX character classes</b> (US-ASCII only)<b></th></tr>
140 *
141 * <tr><td valign="top" headers="construct posix"><tt>\p{Lower}</tt></td>
142 * <td headers="matches">A lower-case alphabetic character: <tt>[a-z]</tt></td></tr>
143 * <tr><td valign="top" headers="construct posix"><tt>\p{Upper}</tt></td>
144 * <td headers="matches">An upper-case alphabetic character:<tt>[A-Z]</tt></td></tr>
145 * <tr><td valign="top" headers="construct posix"><tt>\p{ASCII}</tt></td>
146 * <td headers="matches">All ASCII:<tt>[\x00-\x7F]</tt></td></tr>
147 * <tr><td valign="top" headers="construct posix"><tt>\p{Alpha}</tt></td>
148 * <td headers="matches">An alphabetic character:<tt>[\p{Lower}\p{Upper}]</tt></td></tr>
149 * <tr><td valign="top" headers="construct posix"><tt>\p{Digit}</tt></td>
150 * <td headers="matches">A decimal digit: <tt>[0-9]</tt></td></tr>
151 * <tr><td valign="top" headers="construct posix"><tt>\p{Alnum}</tt></td>
152 * <td headers="matches">An alphanumeric character:<tt>[\p{Alpha}\p{Digit}]</tt></td></tr>
153 * <tr><td valign="top" headers="construct posix"><tt>\p{Punct}</tt></td>
154 * <td headers="matches">Punctuation: One of <tt>!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~</tt></td></tr>
155 * <!-- <tt>[\!"#\$%&'\(\)\*\+,\-\./:;\<=\>\?@\[\\\]\^_`\{\|\}~]</tt>
156 * <tt>[\X21-\X2F\X31-\X40\X5B-\X60\X7B-\X7E]</tt> -->
157 * <tr><td valign="top" headers="construct posix"><tt>\p{Graph}</tt></td>
158 * <td headers="matches">A visible character: <tt>[\p{Alnum}\p{Punct}]</tt></td></tr>
159 * <tr><td valign="top" headers="construct posix"><tt>\p{Print}</tt></td>
160 * <td headers="matches">A printable character: <tt>[\p{Graph}\x20]</tt></td></tr>
161 * <tr><td valign="top" headers="construct posix"><tt>\p{Blank}</tt></td>
162 * <td headers="matches">A space or a tab: <tt>[ \t]</tt></td></tr>
163 * <tr><td valign="top" headers="construct posix"><tt>\p{Cntrl}</tt></td>
164 * <td headers="matches">A control character: <tt>[\x00-\x1F\x7F]</td></tr>
165 * <tr><td valign="top" headers="construct posix"><tt>\p{XDigit}</tt></td>
166 * <td headers="matches">A hexadecimal digit: <tt>[0-9a-fA-F]</tt></td></tr>
167 * <tr><td valign="top" headers="construct posix"><tt>\p{Space}</tt></td>
168 * <td headers="matches">A whitespace character: <tt>[ \t\n\x0B\f\r]</tt></td></tr>
169 *
170 * <tr><th> </th></tr>
171 * <tr align="left"><th colspan="2">java.lang.Character classes (simple <a href="#jcc">java character type</a>)</th></tr>
172 *
173 * <tr><td valign="top"><tt>\p{javaLowerCase}</tt></td>
174 * <td>Equivalent to java.lang.Character.isLowerCase()</td></tr>
175 * <tr><td valign="top"><tt>\p{javaUpperCase}</tt></td>
176 * <td>Equivalent to java.lang.Character.isUpperCase()</td></tr>
177 * <tr><td valign="top"><tt>\p{javaWhitespace}</tt></td>
178 * <td>Equivalent to java.lang.Character.isWhitespace()</td></tr>
179 * <tr><td valign="top"><tt>\p{javaMirrored}</tt></td>
180 * <td>Equivalent to java.lang.Character.isMirrored()</td></tr>
181 *
182 * <tr><th> </th></tr>
183 * <tr align="left"><th colspan="2" id="unicode">Classes for Unicode blocks and categories</th></tr>
184 *
185 * <tr><td valign="top" headers="construct unicode"><tt>\p{InGreek}</tt></td>
186 * <td headers="matches">A character in the Greek block (simple <a href="#ubc">block</a>)</td></tr>
187 * <tr><td valign="top" headers="construct unicode"><tt>\p{Lu}</tt></td>
188 * <td headers="matches">An uppercase letter (simple <a href="#ubc">category</a>)</td></tr>
189 * <tr><td valign="top" headers="construct unicode"><tt>\p{Sc}</tt></td>
190 * <td headers="matches">A currency symbol</td></tr>
191 * <tr><td valign="top" headers="construct unicode"><tt>\P{InGreek}</tt></td>
192 * <td headers="matches">Any character except one in the Greek block (negation)</td></tr>
193 * <tr><td valign="top" headers="construct unicode"><tt>[\p{L}&&[^\p{Lu}]] </tt></td>
194 * <td headers="matches">Any letter except an uppercase letter (subtraction)</td></tr>
195 *
196 * <tr><th> </th></tr>
197 * <tr align="left"><th colspan="2" id="bounds">Boundary matchers</th></tr>
198 *
199 * <tr><td valign="top" headers="construct bounds"><tt>^</tt></td>
200 * <td headers="matches">The beginning of a line</td></tr>
201 * <tr><td valign="top" headers="construct bounds"><tt>$</tt></td>
202 * <td headers="matches">The end of a line</td></tr>
203 * <tr><td valign="top" headers="construct bounds"><tt>\b</tt></td>
204 * <td headers="matches">A word boundary</td></tr>
205 * <tr><td valign="top" headers="construct bounds"><tt>\B</tt></td>
206 * <td headers="matches">A non-word boundary</td></tr>
207 * <tr><td valign="top" headers="construct bounds"><tt>\A</tt></td>
208 * <td headers="matches">The beginning of the input</td></tr>
209 * <tr><td valign="top" headers="construct bounds"><tt>\G</tt></td>
210 * <td headers="matches">The end of the previous match</td></tr>
211 * <tr><td valign="top" headers="construct bounds"><tt>\Z</tt></td>
212 * <td headers="matches">The end of the input but for the final
213 * <a href="#lt">terminator</a>, if any</td></tr>
214 * <tr><td valign="top" headers="construct bounds"><tt>\z</tt></td>
215 * <td headers="matches">The end of the input</td></tr>
216 *
217 * <tr><th> </th></tr>
218 * <tr align="left"><th colspan="2" id="greedy">Greedy quantifiers</th></tr>
219 *
220 * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>?</tt></td>
221 * <td headers="matches"><i>X</i>, once or not at all</td></tr>
222 * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>*</tt></td>
223 * <td headers="matches"><i>X</i>, zero or more times</td></tr>
224 * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>+</tt></td>
225 * <td headers="matches"><i>X</i>, one or more times</td></tr>
226 * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>{</tt><i>n</i><tt>}</tt></td>
227 * <td headers="matches"><i>X</i>, exactly <i>n</i> times</td></tr>
228 * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>{</tt><i>n</i><tt>,}</tt></td>
229 * <td headers="matches"><i>X</i>, at least <i>n</i> times</td></tr>
230 * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>{</tt><i>n</i><tt>,</tt><i>m</i><tt>}</tt></td>
231 * <td headers="matches"><i>X</i>, at least <i>n</i> but not more than <i>m</i> times</td></tr>
232 *
233 * <tr><th> </th></tr>
234 * <tr align="left"><th colspan="2" id="reluc">Reluctant quantifiers</th></tr>
235 *
236 * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>??</tt></td>
237 * <td headers="matches"><i>X</i>, once or not at all</td></tr>
238 * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>*?</tt></td>
239 * <td headers="matches"><i>X</i>, zero or more times</td></tr>
240 * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>+?</tt></td>
241 * <td headers="matches"><i>X</i>, one or more times</td></tr>
242 * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>{</tt><i>n</i><tt>}?</tt></td>
243 * <td headers="matches"><i>X</i>, exactly <i>n</i> times</td></tr>
244 * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>{</tt><i>n</i><tt>,}?</tt></td>
245 * <td headers="matches"><i>X</i>, at least <i>n</i> times</td></tr>
246 * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>{</tt><i>n</i><tt>,</tt><i>m</i><tt>}?</tt></td>
247 * <td headers="matches"><i>X</i>, at least <i>n</i> but not more than <i>m</i> times</td></tr>
248 *
249 * <tr><th> </th></tr>
250 * <tr align="left"><th colspan="2" id="poss">Possessive quantifiers</th></tr>
251 *
252 * <tr><td valign="top" headers="construct poss"><i>X</i><tt>?+</tt></td>
253 * <td headers="matches"><i>X</i>, once or not at all</td></tr>
254 * <tr><td valign="top" headers="construct poss"><i>X</i><tt>*+</tt></td>
255 * <td headers="matches"><i>X</i>, zero or more times</td></tr>
256 * <tr><td valign="top" headers="construct poss"><i>X</i><tt>++</tt></td>
257 * <td headers="matches"><i>X</i>, one or more times</td></tr>
258 * <tr><td valign="top" headers="construct poss"><i>X</i><tt>{</tt><i>n</i><tt>}+</tt></td>
259 * <td headers="matches"><i>X</i>, exactly <i>n</i> times</td></tr>
260 * <tr><td valign="top" headers="construct poss"><i>X</i><tt>{</tt><i>n</i><tt>,}+</tt></td>
261 * <td headers="matches"><i>X</i>, at least <i>n</i> times</td></tr>
262 * <tr><td valign="top" headers="construct poss"><i>X</i><tt>{</tt><i>n</i><tt>,</tt><i>m</i><tt>}+</tt></td>
263 * <td headers="matches"><i>X</i>, at least <i>n</i> but not more than <i>m</i> times</td></tr>
264 *
265 * <tr><th> </th></tr>
266 * <tr align="left"><th colspan="2" id="logical">Logical operators</th></tr>
267 *
268 * <tr><td valign="top" headers="construct logical"><i>XY</i></td>
269 * <td headers="matches"><i>X</i> followed by <i>Y</i></td></tr>
270 * <tr><td valign="top" headers="construct logical"><i>X</i><tt>|</tt><i>Y</i></td>
271 * <td headers="matches">Either <i>X</i> or <i>Y</i></td></tr>
272 * <tr><td valign="top" headers="construct logical"><tt>(</tt><i>X</i><tt>)</tt></td>
273 * <td headers="matches">X, as a <a href="#cg">capturing group</a></td></tr>
274 *
275 * <tr><th> </th></tr>
276 * <tr align="left"><th colspan="2" id="backref">Back references</th></tr>
277 *
278 * <tr><td valign="bottom" headers="construct backref"><tt>\</tt><i>n</i></td>
279 * <td valign="bottom" headers="matches">Whatever the <i>n</i><sup>th</sup>
280 * <a href="#cg">capturing group</a> matched</td></tr>
281 *
282 * <tr><th> </th></tr>
283 * <tr align="left"><th colspan="2" id="quot">Quotation</th></tr>
284 *
285 * <tr><td valign="top" headers="construct quot"><tt>\</tt></td>
286 * <td headers="matches">Nothing, but quotes the following character</tt></td></tr>
287 * <tr><td valign="top" headers="construct quot"><tt>\Q</tt></td>
288 * <td headers="matches">Nothing, but quotes all characters until <tt>\E</tt></td></tr>
289 * <tr><td valign="top" headers="construct quot"><tt>\E</tt></td>
290 * <td headers="matches">Nothing, but ends quoting started by <tt>\Q</tt></td></tr>
291 * <!-- Metachars: !$()*+.<>?[\]^{|} -->
292 *
293 * <tr><th> </th></tr>
294 * <tr align="left"><th colspan="2" id="special">Special constructs (non-capturing)</th></tr>
295 *
296 * <tr><td valign="top" headers="construct special"><tt>(?:</tt><i>X</i><tt>)</tt></td>
297 * <td headers="matches"><i>X</i>, as a non-capturing group</td></tr>
298 * <tr><td valign="top" headers="construct special"><tt>(?idmsux-idmsux) </tt></td>
299 * <td headers="matches">Nothing, but turns match flags <a href="#CASE_INSENSITIVE">i</a>
300 * <a href="#UNIX_LINES">d</a> <a href="#MULTILINE">m</a> <a href="#DOTALL">s</a>
301 * <a href="#UNICODE_CASE">u</a> <a href="#COMMENTS">x</a> on - off</td></tr>
302 * <tr><td valign="top" headers="construct special"><tt>(?idmsux-idmsux:</tt><i>X</i><tt>)</tt> </td>
303 * <td headers="matches"><i>X</i>, as a <a href="#cg">non-capturing group</a> with the
304 * given flags <a href="#CASE_INSENSITIVE">i</a> <a href="#UNIX_LINES">d</a>
305 * <a href="#MULTILINE">m</a> <a href="#DOTALL">s</a> <a href="#UNICODE_CASE">u</a >
306 * <a href="#COMMENTS">x</a> on - off</td></tr>
307 * <tr><td valign="top" headers="construct special"><tt>(?=</tt><i>X</i><tt>)</tt></td>
308 * <td headers="matches"><i>X</i>, via zero-width positive lookahead</td></tr>
309 * <tr><td valign="top" headers="construct special"><tt>(?!</tt><i>X</i><tt>)</tt></td>
310 * <td headers="matches"><i>X</i>, via zero-width negative lookahead</td></tr>
311 * <tr><td valign="top" headers="construct special"><tt>(?<=</tt><i>X</i><tt>)</tt></td>
312 * <td headers="matches"><i>X</i>, via zero-width positive lookbehind</td></tr>
313 * <tr><td valign="top" headers="construct special"><tt>(?<!</tt><i>X</i><tt>)</tt></td>
314 * <td headers="matches"><i>X</i>, via zero-width negative lookbehind</td></tr>
315 * <tr><td valign="top" headers="construct special"><tt>(?></tt><i>X</i><tt>)</tt></td>
316 * <td headers="matches"><i>X</i>, as an independent, non-capturing group</td></tr>
317 *
318 * </table>
319 *
320 * <hr>
321 *
322 *
323 * <a name="bs">
324 * <h4> Backslashes, escapes, and quoting </h4>
325 *
326 * <p> The backslash character (<tt>'\'</tt>) serves to introduce escaped
327 * constructs, as defined in the table above, as well as to quote characters
328 * that otherwise would be interpreted as unescaped constructs. Thus the
329 * expression <tt>\\</tt> matches a single backslash and <tt>\{</tt> matches a
330 * left brace.
331 *
332 * <p> It is an error to use a backslash prior to any alphabetic character that
333 * does not denote an escaped construct; these are reserved for future
334 * extensions to the regular-expression language. A backslash may be used
335 * prior to a non-alphabetic character regardless of whether that character is
336 * part of an unescaped construct.
337 *
338 * <p> Backslashes within string literals in Java source code are interpreted
339 * as required by the <a
340 * href="http://java.sun.com/docs/books/jls/second_edition/html/">Java Language
341 * Specification</a> as either <a
342 * href="http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#100850">Unicode
343 * escapes</a> or other <a
344 * href="http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#101089">character
345 * escapes</a>. It is therefore necessary to double backslashes in string
346 * literals that represent regular expressions to protect them from
347 * interpretation by the Java bytecode compiler. The string literal
348 * <tt>"\b"</tt>, for example, matches a single backspace character when
349 * interpreted as a regular expression, while <tt>"\\b"</tt> matches a
350 * word boundary. The string literal <tt>"\(hello\)"</tt> is illegal
351 * and leads to a compile-time error; in order to match the string
352 * <tt>(hello)</tt> the string literal <tt>"\\(hello\\)"</tt>
353 * must be used.
354 *
355 * <a name="cc">
356 * <h4> Character Classes </h4>
357 *
358 * <p> Character classes may appear within other character classes, and
359 * may be composed by the union operator (implicit) and the intersection
360 * operator (<tt>&&</tt>).
361 * The union operator denotes a class that contains every character that is
362 * in at least one of its operand classes. The intersection operator
363 * denotes a class that contains every character that is in both of its
364 * operand classes.
365 *
366 * <p> The precedence of character-class operators is as follows, from
367 * highest to lowest:
368 *
369 * <blockquote><table border="0" cellpadding="1" cellspacing="0"
370 * summary="Precedence of character class operators.">
371 * <tr><th>1 </th>
372 * <td>Literal escape </td>
373 * <td><tt>\x</tt></td></tr>
374 * <tr><th>2 </th>
375 * <td>Grouping</td>
376 * <td><tt>[...]</tt></td></tr>
377 * <tr><th>3 </th>
378 * <td>Range</td>
379 * <td><tt>a-z</tt></td></tr>
380 * <tr><th>4 </th>
381 * <td>Union</td>
382 * <td><tt>[a-e][i-u]<tt></td></tr>
383 * <tr><th>5 </th>
384 * <td>Intersection</td>
385 * <td><tt>[a-z&&[aeiou]]</tt></td></tr>
386 * </table></blockquote>
387 *
388 * <p> Note that a different set of metacharacters are in effect inside
389 * a character class than outside a character class. For instance, the
390 * regular expression <tt>.</tt> loses its special meaning inside a
391 * character class, while the expression <tt>-</tt> becomes a range
392 * forming metacharacter.
393 *
394 * <a name="lt">
395 * <h4> Line terminators </h4>
396 *
397 * <p> A <i>line terminator</i> is a one- or two-character sequence that marks
398 * the end of a line of the input character sequence. The following are
399 * recognized as line terminators:
400 *
401 * <ul>
402 *
403 * <li> A newline (line feed) character (<tt>'\n'</tt>),
404 *
405 * <li> A carriage-return character followed immediately by a newline
406 * character (<tt>"\r\n"</tt>),
407 *
408 * <li> A standalone carriage-return character (<tt>'\r'</tt>),
409 *
410 * <li> A next-line character (<tt>'\u0085'</tt>),
411 *
412 * <li> A line-separator character (<tt>'\u2028'</tt>), or
413 *
414 * <li> A paragraph-separator character (<tt>'\u2029</tt>).
415 *
416 * </ul>
417 * <p>If {@link #UNIX_LINES} mode is activated, then the only line terminators
418 * recognized are newline characters.
419 *
420 * <p> The regular expression <tt>.</tt> matches any character except a line
421 * terminator unless the {@link #DOTALL} flag is specified.
422 *
423 * <p> By default, the regular expressions <tt>^</tt> and <tt>$</tt> ignore
424 * line terminators and only match at the beginning and the end, respectively,
425 * of the entire input sequence. If {@link #MULTILINE} mode is activated then
426 * <tt>^</tt> matches at the beginning of input and after any line terminator
427 * except at the end of input. When in {@link #MULTILINE} mode <tt>$</tt>
428 * matches just before a line terminator or the end of the input sequence.
429 *
430 * <a name="cg">
431 * <h4> Groups and capturing </h4>
432 *
433 * <p> Capturing groups are numbered by counting their opening parentheses from
434 * left to right. In the expression <tt>((A)(B(C)))</tt>, for example, there
435 * are four such groups: </p>
436 *
437 * <blockquote><table cellpadding=1 cellspacing=0 summary="Capturing group numberings">
438 * <tr><th>1 </th>
439 * <td><tt>((A)(B(C)))</tt></td></tr>
440 * <tr><th>2 </th>
441 * <td><tt>(A)</tt></td></tr>
442 * <tr><th>3 </th>
443 * <td><tt>(B(C))</tt></td></tr>
444 * <tr><th>4 </th>
445 * <td><tt>(C)</tt></td></tr>
446 * </table></blockquote>
447 *
448 * <p> Group zero always stands for the entire expression.
449 *
450 * <p> Capturing groups are so named because, during a match, each subsequence
451 * of the input sequence that matches such a group is saved. The captured
452 * subsequence may be used later in the expression, via a back reference, and
453 * may also be retrieved from the matcher once the match operation is complete.
454 *
455 * <p> The captured input associated with a group is always the subsequence
456 * that the group most recently matched. If a group is evaluated a second time
457 * because of quantification then its previously-captured value, if any, will
458 * be retained if the second evaluation fails. Matching the string
459 * <tt>"aba"</tt> against the expression <tt>(a(b)?)+</tt>, for example, leaves
460 * group two set to <tt>"b"</tt>. All captured input is discarded at the
461 * beginning of each match.
462 *
463 * <p> Groups beginning with <tt>(?</tt> are pure, <i>non-capturing</i> groups
464 * that do not capture text and do not count towards the group total.
465 *
466 *
467 * <h4> Unicode support </h4>
468 *
469 * <p> This class is in conformance with Level 1 of <a
470 * href="http://www.unicode.org/reports/tr18/"><i>Unicode Technical
471 * Standard #18: Unicode Regular Expression Guidelines</i></a>, plus RL2.1
472 * Canonical Equivalents.
473 *
474 * <p> Unicode escape sequences such as <tt>\u2014</tt> in Java source code
475 * are processed as described in <a
476 * href="http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#100850">\u00A73.3</a>
477 * of the Java Language Specification. Such escape sequences are also
478 * implemented directly by the regular-expression parser so that Unicode
479 * escapes can be used in expressions that are read from files or from the
480 * keyboard. Thus the strings <tt>"\u2014"</tt> and <tt>"\\u2014"</tt>,
481 * while not equal, compile into the same pattern, which matches the character
482 * with hexadecimal value <tt>0x2014</tt>.
483 *
484 * <a name="ubc"> <p>Unicode blocks and categories are written with the
485 * <tt>\p</tt> and <tt>\P</tt> constructs as in
486 * Perl. <tt>\p{</tt><i>prop</i><tt>}</tt> matches if the input has the
487 * property <i>prop</i>, while \P{</tt><i>prop</i><tt>}</tt> does not match if
488 * the input has that property. Blocks are specified with the prefix
489 * <tt>In</tt>, as in <tt>InMongolian</tt>. Categories may be specified with
490 * the optional prefix <tt>Is</tt>: Both <tt>\p{L}</tt> and <tt>\p{IsL}</tt>
491 * denote the category of Unicode letters. Blocks and categories can be used
492 * both inside and outside of a character class.
493 *
494 * <p> The supported categories are those of
495 * <a href="http://www.unicode.org/unicode/standard/standard.html">
496 * <i>The Unicode Standard</i></a> in the version specified by the
497 * {@link java.lang.Character Character} class. The category names are those
498 * defined in the Standard, both normative and informative.
499 * The block names supported by <code>Pattern</code> are the valid block names
500 * accepted and defined by
501 * {@link java.lang.Character.UnicodeBlock#forName(String) UnicodeBlock.forName}.
502 *
503 * <a name="jcc"> <p>Categories that behave like the java.lang.Character
504 * boolean is<i>methodname</i> methods (except for the deprecated ones) are
505 * available through the same <tt>\p{</tt><i>prop</i><tt>}</tt> syntax where
506 * the specified property has the name <tt>java<i>methodname</i></tt>.
507 *
508 * <h4> Comparison to Perl 5 </h4>
509 *
510 * <p>The <code>Pattern</code> engine performs traditional NFA-based matching
511 * with ordered alternation as occurs in Perl 5.
512 *
513 * <p> Perl constructs not supported by this class: </p>
514 *
515 * <ul>
516 *
517 * <li><p> The conditional constructs <tt>(?{</tt><i>X</i><tt>})</tt> and
518 * <tt>(?(</tt><i>condition</i><tt>)</tt><i>X</i><tt>|</tt><i>Y</i><tt>)</tt>,
519 * </p></li>
520 *
521 * <li><p> The embedded code constructs <tt>(?{</tt><i>code</i><tt>})</tt>
522 * and <tt>(??{</tt><i>code</i><tt>})</tt>,</p></li>
523 *
524 * <li><p> The embedded comment syntax <tt>(?#comment)</tt>, and </p></li>
525 *
526 * <li><p> The preprocessing operations <tt>\l</tt> <tt>\u</tt>,
527 * <tt>\L</tt>, and <tt>\U</tt>. </p></li>
528 *
529 * </ul>
530 *
531 * <p> Constructs supported by this class but not by Perl: </p>
532 *
533 * <ul>
534 *
535 * <li><p> Possessive quantifiers, which greedily match as much as they can
536 * and do not back off, even when doing so would allow the overall match to
537 * succeed. </p></li>
538 *
539 * <li><p> Character-class union and intersection as described
540 * <a href="#cc">above</a>.</p></li>
541 *
542 * </ul>
543 *
544 * <p> Notable differences from Perl: </p>
545 *
546 * <ul>
547 *
548 * <li><p> In Perl, <tt>\1</tt> through <tt>\9</tt> are always interpreted
549 * as back references; a backslash-escaped number greater than <tt>9</tt> is
550 * treated as a back reference if at least that many subexpressions exist,
551 * otherwise it is interpreted, if possible, as an octal escape. In this
552 * class octal escapes must always begin with a zero. In this class,
553 * <tt>\1</tt> through <tt>\9</tt> are always interpreted as back
554 * references, and a larger number is accepted as a back reference if at
555 * least that many subexpressions exist at that point in the regular
556 * expression, otherwise the parser will drop digits until the number is
557 * smaller or equal to the existing number of groups or it is one digit.
558 * </p></li>
559 *
560 * <li><p> Perl uses the <tt>g</tt> flag to request a match that resumes
561 * where the last match left off. This functionality is provided implicitly
562 * by the {@link Matcher} class: Repeated invocations of the {@link
563 * Matcher#find find} method will resume where the last match left off,
564 * unless the matcher is reset. </p></li>
565 *
566 * <li><p> In Perl, embedded flags at the top level of an expression affect
567 * the whole expression. In this class, embedded flags always take effect
568 * at the point at which they appear, whether they are at the top level or
569 * within a group; in the latter case, flags are restored at the end of the
570 * group just as in Perl. </p></li>
571 *
572 * <li><p> Perl is forgiving about malformed matching constructs, as in the
573 * expression <tt>*a</tt>, as well as dangling brackets, as in the
574 * expression <tt>abc]</tt>, and treats them as literals. This
575 * class also accepts dangling brackets but is strict about dangling
576 * metacharacters like +, ? and *, and will throw a
577 * {@link PatternSyntaxException} if it encounters them. </p></li>
578 *
579 * </ul>
580 *
581 *
582 * <p> For a more precise description of the behavior of regular expression
583 * constructs, please see <a href="http://www.oreilly.com/catalog/regex2/">
584 * <i>Mastering Regular Expressions, 2nd Edition</i>, Jeffrey E. F. Friedl,
585 * O'Reilly and Associates, 2002.</a>
586 * </p>
587 *
588 * @see java.lang.String#split(String, int)
589 * @see java.lang.String#split(String)
590 *
591 * @author Mike McCloskey
592 * @author Mark Reinhold
593 * @author JSR-51 Expert Group
594 * @version %I%, %E%
595 * @since 1.4
596 * @spec JSR-51
597 */
598
599 public final class Pattern
600 implements java.io.Serializable
601 {
602
603 /**
604 * Regular expression modifier values. Instead of being passed as
605 * arguments, they can also be passed as inline modifiers.
606 * For example, the following statements have the same effect.
607 * <pre>
608 * RegExp r1 = RegExp.compile("abc", Pattern.I|Pattern.M);
609 * RegExp r2 = RegExp.compile("(?im)abc", 0);
610 * </pre>
611 *
612 * The flags are duplicated so that the familiar Perl match flag
613 * names are available.
614 */
615
616 /**
617 * Enables Unix lines mode.
618 *
619 * <p> In this mode, only the <tt>'\n'</tt> line terminator is recognized
620 * in the behavior of <tt>.</tt>, <tt>^</tt>, and <tt>$</tt>.
621 *
622 * <p> Unix lines mode can also be enabled via the embedded flag
623 * expression <tt>(?d)</tt>.
624 */
625 public static final int UNIX_LINES = 0x01;
626
627 /**
628 * Enables case-insensitive matching.
629 *
630 * <p> By default, case-insensitive matching assumes that only characters
631 * in the US-ASCII charset are being matched. Unicode-aware
632 * case-insensitive matching can be enabled by specifying the {@link
633 * #UNICODE_CASE} flag in conjunction with this flag.
634 *
635 * <p> Case-insensitive matching can also be enabled via the embedded flag
636 * expression <tt>(?i)</tt>.
637 *
638 * <p> Specifying this flag may impose a slight performance penalty. </p>
639 */
640 public static final int CASE_INSENSITIVE = 0x02;
641
642 /**
643 * Permits whitespace and comments in pattern.
644 *
645 * <p> In this mode, whitespace is ignored, and embedded comments starting
646 * with <tt>#</tt> are ignored until the end of a line.
647 *
648 * <p> Comments mode can also be enabled via the embedded flag
649 * expression <tt>(?x)</tt>.
650 */
651 public static final int COMMENTS = 0x04;
652
653 /**
654 * Enables multiline mode.
655 *
656 * <p> In multiline mode the expressions <tt>^</tt> and <tt>$</tt> match
657 * just after or just before, respectively, a line terminator or the end of
658 * the input sequence. By default these expressions only match at the
659 * beginning and the end of the entire input sequence.
660 *
661 * <p> Multiline mode can also be enabled via the embedded flag
662 * expression <tt>(?m)</tt>. </p>
663 */
664 public static final int MULTILINE = 0x08;
665
666 /**
667 * Enables literal parsing of the pattern.
668 *
669 * <p> When this flag is specified then the input string that specifies
670 * the pattern is treated as a sequence of literal characters.
671 * Metacharacters or escape sequences in the input sequence will be
672 * given no special meaning.
673 *
674 * <p>The flags CASE_INSENSITIVE and UNICODE_CASE retain their impact on
675 * matching when used in conjunction with this flag. The other flags
676 * become superfluous.
677 *
678 * <p> There is no embedded flag character for enabling literal parsing.
679 */
680 public static final int LITERAL = 0x10;
681
682 /**
683 * Enables dotall mode.
684 *
685 * <p> In dotall mode, the expression <tt>.</tt> matches any character,
686 * including a line terminator. By default this expression does not match
687 * line terminators.
688 *
689 * <p> Dotall mode can also be enabled via the embedded flag
690 * expression <tt>(?s)</tt>. (The <tt>s</tt> is a mnemonic for
691 * "single-line" mode, which is what this is called in Perl.) </p>
692 */
693 public static final int DOTALL = 0x20;
694
695 /**
696 * Enables Unicode-aware case folding.
697 *
698 * <p> When this flag is specified then case-insensitive matching, when
699 * enabled by the {@link #CASE_INSENSITIVE} flag, is done in a manner
700 * consistent with the Unicode Standard. By default, case-insensitive
701 * matching assumes that only characters in the US-ASCII charset are being
702 * matched.
703 *
704 * <p> Unicode-aware case folding can also be enabled via the embedded flag
705 * expression <tt>(?u)</tt>.
706 *
707 * <p> Specifying this flag may impose a performance penalty. </p>
708 */
709 public static final int UNICODE_CASE = 0x40;
710
711 /**
712 * Enables canonical equivalence.
713 *
714 * <p> When this flag is specified then two characters will be considered
715 * to match if, and only if, their full canonical decompositions match.
716 * The expression <tt>"a\u030A"</tt>, for example, will match the
717 * string <tt>"\u00E5"</tt> when this flag is specified. By default,
718 * matching does not take canonical equivalence into account.
719 *
720 * <p> There is no embedded flag character for enabling canonical
721 * equivalence.
722 *
723 * <p> Specifying this flag may impose a performance penalty. </p>
724 */
725 public static final int CANON_EQ = 0x80;
726
727 /* Pattern has only two serialized components: The pattern string
728 * and the flags, which are all that is needed to recompile the pattern
729 * when it is deserialized.
730 */
731
732 /** use serialVersionUID from Merlin b59 for interoperability */
733 private static final long serialVersionUID = 5073258162644648461L;
734
735 /**
736 * The original regular-expression pattern string.
737 *
738 * @serial
739 */
740 private String pattern;
741
742 /**
743 * The original pattern flags.
744 *
745 * @serial
746 */
747 private int flags;
748
749 /**
750 * Boolean indicating this Pattern is compiled; this is necessary in order
751 * to lazily compile deserialized Patterns.
752 */
753 private transient volatile boolean compiled = false;
754
755 /**
756 * The normalized pattern string.
757 */
758 private transient String normalizedPattern;
759
760 /**
761 * The starting point of state machine for the find operation. This allows
762 * a match to start anywhere in the input.
763 */
764 transient Node root;
765
766 /**
767 * The root of object tree for a match operation. The pattern is matched
768 * at the beginning. This may include a find that uses BnM or a First
769 * node.
770 */
771 transient Node matchRoot;
772
773 /**
774 * Temporary storage used by parsing pattern slice.
775 */
776 transient int[] buffer;
777
778 /**
779 * Temporary storage used while parsing group references.
780 */
781 transient GroupHead[] groupNodes;
782
783 /**
784 * Temporary null terminated char array used by pattern compiling.
785 */
786 private transient int[] temp;
787
788 /**
789 * The number of capturing groups in this Pattern. Used by matchers to
790 * allocate storage needed to perform a match.
791 */
792 transient int capturingGroupCount;
793
794 /**
795 * The local variable count used by parsing tree. Used by matchers to
796 * allocate storage needed to perform a match.
797 */
798 transient int localCount;
799
800 /**
801 * Index into the pattern string that keeps track of how much has been
802 * parsed.
803 */
804 private transient int cursor;
805
806 /**
807 * Holds the length of the pattern string.
808 */
809 private transient int patternLength;
810
811 /**
812 * Compiles the given regular expression into a pattern. </p>
813 *
814 * @param regex
815 * The expression to be compiled
816 *
817 * @throws PatternSyntaxException
818 * If the expression's syntax is invalid
819 */
820 public static Pattern compile(String regex) {
821 return new Pattern(regex, 0);
822 }
823
824 /**
825 * Compiles the given regular expression into a pattern with the given
826 * flags. </p>
827 *
828 * @param regex
829 * The expression to be compiled
830 *
831 * @param flags
832 * Match flags, a bit mask that may include
833 * {@link #CASE_INSENSITIVE}, {@link #MULTILINE}, {@link #DOTALL},
834 * {@link #UNICODE_CASE}, {@link #CANON_EQ}, {@link #UNIX_LINES},
835 * {@link #LITERAL} and {@link #COMMENTS}
836 *
837 * @throws IllegalArgumentException
838 * If bit values other than those corresponding to the defined
839 * match flags are set in <tt>flags</tt>
840 *
841 * @throws PatternSyntaxException
842 * If the expression's syntax is invalid
843 */
844 public static Pattern compile(String regex, int flags) {
845 return new Pattern(regex, flags);
846 }
847
848 /**
849 * Returns the regular expression from which this pattern was compiled.
850 * </p>
851 *
852 * @return The source of this pattern
853 */
854 public String pattern() {
855 return pattern;
856 }
857
858 /**
859 * <p>Returns the string representation of this pattern. This
860 * is the regular expression from which this pattern was
861 * compiled.</p>
862 *
863 * @return The string representation of this pattern
864 * @since 1.5
865 */
866 public String toString() {
867 return pattern;
868 }
869
870 /**
871 * Creates a matcher that will match the given input against this pattern.
872 * </p>
873 *
874 * @param input
875 * The character sequence to be matched
876 *
877 * @return A new matcher for this pattern
878 */
879 public Matcher matcher(CharSequence input) {
880 synchronized(this) {
881 if (!compiled)
882 compile();
883 }
884 Matcher m = new Matcher(this, input);
885 return m;
886 }
887
888 /**
889 * Returns this pattern's match flags. </p>
890 *
891 * @return The match flags specified when this pattern was compiled
892 */
893 public int flags() {
894 return flags;
895 }
896
897 /**
898 * Compiles the given regular expression and attempts to match the given
899 * input against it.
900 *
901 * <p> An invocation of this convenience method of the form
902 *
903 * <blockquote><pre>
904 * Pattern.matches(regex, input);</pre></blockquote>
905 *
906 * behaves in exactly the same way as the expression
907 *
908 * <blockquote><pre>
909 * Pattern.compile(regex).matcher(input).matches()</pre></blockquote>
910 *
911 * <p> If a pattern is to be used multiple times, compiling it once and reusing
912 * it will be more efficient than invoking this method each time. </p>
913 *
914 * @param regex
915 * The expression to be compiled
916 *
917 * @param input
918 * The character sequence to be matched
919 *
920 * @throws PatternSyntaxException
921 * If the expression's syntax is invalid
922 */
923 public static boolean matches(String regex, CharSequence input) {
924 Pattern p = Pattern.compile(regex);
925 Matcher m = p.matcher(input);
926 return m.matches();
927 }
928
929 /**
930 * Splits the given input sequence around matches of this pattern.
931 *
932 * <p> The array returned by this method contains each substring of the
933 * input sequence that is terminated by another subsequence that matches
934 * this pattern or is terminated by the end of the input sequence. The
935 * substrings in the array are in the order in which they occur in the
936 * input. If this pattern does not match any subsequence of the input then
937 * the resulting array has just one element, namely the input sequence in
938 * string form.
939 *
940 * <p> The <tt>limit</tt> parameter controls the number of times the
941 * pattern is applied and therefore affects the length of the resulting
942 * array. If the limit <i>n</i> is greater than zero then the pattern
943 * will be applied at most <i>n</i> - 1 times, the array's
944 * length will be no greater than <i>n</i>, and the array's last entry
945 * will contain all input beyond the last matched delimiter. If <i>n</i>
946 * is non-positive then the pattern will be applied as many times as
947 * possible and the array can have any length. If <i>n</i> is zero then
948 * the pattern will be applied as many times as possible, the array can
949 * have any length, and trailing empty strings will be discarded.
950 *
951 * <p> The input <tt>"boo:and:foo"</tt>, for example, yields the following
952 * results with these parameters:
953 *
954 * <blockquote><table cellpadding=1 cellspacing=0
955 * summary="Split examples showing regex, limit, and result">
956 * <tr><th><P align="left"><i>Regex </i></th>
957 * <th><P align="left"><i>Limit </i></th>
958 * <th><P align="left"><i>Result </i></th></tr>
959 * <tr><td align=center>:</td>
960 * <td align=center>2</td>
961 * <td><tt>{ "boo", "and:foo" }</tt></td></tr>
962 * <tr><td align=center>:</td>
963 * <td align=center>5</td>
964 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
965 * <tr><td align=center>:</td>
966 * <td align=center>-2</td>
967 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
968 * <tr><td align=center>o</td>
969 * <td align=center>5</td>
970 * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
971 * <tr><td align=center>o</td>
972 * <td align=center>-2</td>
973 * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
974 * <tr><td align=center>o</td>
975 * <td align=center>0</td>
976 * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
977 * </table></blockquote>
978 *
979 *
980 * @param input
981 * The character sequence to be split
982 *
983 * @param limit
984 * The result threshold, as described above
985 *
986 * @return The array of strings computed by splitting the input
987 * around matches of this pattern
988 */
989 public String[] split(CharSequence input, int limit) {
990 int index = 0;
991 boolean matchLimited = limit > 0;
992 ArrayList matchList = new ArrayList();
993 Matcher m = matcher(input);
994
995 // Add segments before each match found
996 while(m.find()) {
997 if (!matchLimited || matchList.size() < limit - 1) {
998 String match = input.subSequence(index, m.start()).toString();
999 matchList.add(match);
1000 index = m.end();
1001 } else if (matchList.size() == limit - 1) { // last one
1002 String match = input.subSequence(index,
1003 input.length()).toString();
1004 matchList.add(match);
1005 index = m.end();
1006 }
1007 }
1008
1009 // If no match was found, return this
1010 if (index == 0)
1011 return new String[] {input.toString()};
1012
1013 // Add remaining segment
1014 if (!matchLimited || matchList.size() < limit)
1015 matchList.add(input.subSequence(index, input.length()).toString());
1016
1017 // Construct result
1018 int resultSize = matchList.size();
1019 if (limit == 0)
1020 while (resultSize > 0 && matchList.get(resultSize-1).equals(""))
1021 resultSize--;
1022 String[] result = new String[resultSize];
1023 return (String[])matchList.subList(0, resultSize).toArray(result);
1024 }
1025
1026 /**
1027 * Splits the given input sequence around matches of this pattern.
1028 *
1029 * <p> This method works as if by invoking the two-argument {@link
1030 * #split(java.lang.CharSequence, int) split} method with the given input
1031 * sequence and a limit argument of zero. Trailing empty strings are
1032 * therefore not included in the resulting array. </p>
1033 *
1034 * <p> The input <tt>"boo:and:foo"</tt>, for example, yields the following
1035 * results with these expressions:
1036 *
1037 * <blockquote><table cellpadding=1 cellspacing=0
1038 * summary="Split examples showing regex and result">
1039 * <tr><th><P align="left"><i>Regex </i></th>
1040 * <th><P align="left"><i>Result</i></th></tr>
1041 * <tr><td align=center>:</td>
1042 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
1043 * <tr><td align=center>o</td>
1044 * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
1045 * </table></blockquote>
1046 *
1047 *
1048 * @param input
1049 * The character sequence to be split
1050 *
1051 * @return The array of strings computed by splitting the input
1052 * around matches of this pattern
1053 */
1054 public String[] split(CharSequence input) {
1055 return split(input, 0);
1056 }
1057
1058 /**
1059 * Returns a literal pattern <code>String</code> for the specified
1060 * <code>String</code>.
1061 *
1062 * <p>This method produces a <code>String</code> that can be used to
1063 * create a <code>Pattern</code> that would match the string
1064 * <code>s</code> as if it were a literal pattern.</p> Metacharacters
1065 * or escape sequences in the input sequence will be given no special
1066 * meaning.
1067 *
1068 * @param s The string to be literalized
1069 * @return A literal string replacement
1070 * @since 1.5
1071 */
1072 public static String quote(String s) {
1073 int slashEIndex = s.indexOf("\\E");
1074 if (slashEIndex == -1)
1075 return "\\Q" + s + "\\E";
1076
1077 StringBuilder sb = new StringBuilder(s.length() * 2);
1078 sb.append("\\Q");
1079 slashEIndex = 0;
1080 int current = 0;
1081 while ((slashEIndex = s.indexOf("\\E", current)) != -1) {
1082 sb.append(s.substring(current, slashEIndex));
1083 current = slashEIndex + 2;
1084 sb.append("\\E\\\\E\\Q");
1085 }
1086 sb.append(s.substring(current, s.length()));
1087 sb.append("\\E");
1088 return sb.toString();
1089 }
1090
1091 /**
1092 * Recompile the Pattern instance from a stream. The original pattern
1093 * string is read in and the object tree is recompiled from it.
1094 */
1095 private void readObject(java.io.ObjectInputStream s)
1096 throws java.io.IOException, ClassNotFoundException {
1097
1098 // Read in all fields
1099 s.defaultReadObject();
1100
1101 // Initialize counts
1102 capturingGroupCount = 1;
1103 localCount = 0;
1104
1105 // if length > 0, the Pattern is lazily compiled
1106 compiled = false;
1107 if (pattern.length() == 0) {
1108 root = new Start(lastAccept);
1109 matchRoot = lastAccept;
1110 compiled = true;
1111 }
1112 }
1113
1114 /**
1115 * This private constructor is used to create all Patterns. The pattern
1116 * string and match flags are all that is needed to completely describe
1117 * a Pattern. An empty pattern string results in an object tree with
1118 * only a Start node and a LastNode node.
1119 */
1120 private Pattern(String p, int f) {
1121 pattern = p;
1122 flags = f;
1123
1124 // Reset group index count
1125 capturingGroupCount = 1;
1126 localCount = 0;
1127
1128 if (pattern.length() > 0) {
1129 compile();
1130 } else {
1131 root = new Start(lastAccept);
1132 matchRoot = lastAccept;
1133 }
1134 }
1135
1136 /**
1137 * The pattern is converted to normalizedD form and then a pure group
1138 * is constructed to match canonical equivalences of the characters.
1139 */
1140 private void normalize() {
1141 boolean inCharClass = false;
1142 int lastCodePoint = -1;
1143
1144 // Convert pattern into normalizedD form
1145 normalizedPattern = Normalizer.normalize(pattern, Normalizer.Form.NFD);
1146 patternLength = normalizedPattern.length();
1147
1148 // Modify pattern to match canonical equivalences
1149 StringBuilder newPattern = new StringBuilder(patternLength);
1150 for(int i=0; i<patternLength; ) {
1151 int c = normalizedPattern.codePointAt(i);
1152 StringBuilder sequenceBuffer;
1153 if ((Character.getType(c) == Character.NON_SPACING_MARK)
1154 && (lastCodePoint != -1)) {
1155 sequenceBuffer = new StringBuilder();
1156 sequenceBuffer.appendCodePoint(lastCodePoint);
1157 sequenceBuffer.appendCodePoint(c);
1158 while(Character.getType(c) == Character.NON_SPACING_MARK) {
1159 i += Character.charCount(c);
1160 if (i >= patternLength)
1161 break;
1162 c = normalizedPattern.codePointAt(i);
1163 sequenceBuffer.appendCodePoint(c);
1164 }
1165 String ea = produceEquivalentAlternation(
1166 sequenceBuffer.toString());
1167 newPattern.setLength(newPattern.length()-Character.charCount(lastCodePoint));
1168 newPattern.append("(?:").append(ea).append(")");
1169 } else if (c == '[' && lastCodePoint != '\\') {
1170 i = normalizeCharClass(newPattern, i);
1171 } else {
1172 newPattern.appendCodePoint(c);
1173 }
1174 lastCodePoint = c;
1175 i += Character.charCount(c);
1176 }
1177 normalizedPattern = newPattern.toString();
1178 }
1179
1180 /**
1181 * Complete the character class being parsed and add a set
1182 * of alternations to it that will match the canonical equivalences
1183 * of the characters within the class.
1184 */
1185 private int normalizeCharClass(StringBuilder newPattern, int i) {
1186 StringBuilder charClass = new StringBuilder();
1187 StringBuilder eq = null;
1188 int lastCodePoint = -1;
1189 String result;
1190
1191 i++;
1192 charClass.append("[");
1193 while(true) {
1194 int c = normalizedPattern.codePointAt(i);
1195 StringBuilder sequenceBuffer;
1196
1197 if (c == ']' && lastCodePoint != '\\') {
1198 charClass.append((char)c);
1199 break;
1200 } else if (Character.getType(c) == Character.NON_SPACING_MARK) {
1201 sequenceBuffer = new StringBuilder();
1202 sequenceBuffer.appendCodePoint(lastCodePoint);
1203 while(Character.getType(c) == Character.NON_SPACING_MARK) {
1204 sequenceBuffer.appendCodePoint(c);
1205 i += Character.charCount(c);
1206 if (i >= normalizedPattern.length())
1207 break;
1208 c = normalizedPattern.codePointAt(i);
1209 }
1210 String ea = produceEquivalentAlternation(
1211 sequenceBuffer.toString());
1212
1213 charClass.setLength(charClass.length()-Character.charCount(lastCodePoint));
1214 if (eq == null)
1215 eq = new StringBuilder();
1216 eq.append('|');
1217 eq.append(ea);
1218 } else {
1219 charClass.appendCodePoint(c);
1220 i++;
1221 }
1222 if (i == normalizedPattern.length())
1223 throw error("Unclosed character class");
1224 lastCodePoint = c;
1225 }
1226
1227 if (eq != null) {
1228 result = "(?:"+charClass.toString()+eq.toString()+")";
1229 } else {
1230 result = charClass.toString();
1231 }
1232
1233 newPattern.append(result);
1234 return i;
1235 }
1236
1237 /**
1238 * Given a specific sequence composed of a regular character and
1239 * combining marks that follow it, produce the alternation that will
1240 * match all canonical equivalences of that sequence.
1241 */
1242 private String produceEquivalentAlternation(String source) {
1243 int len = countChars(source, 0, 1);
1244 if (source.length() == len)
1245 // source has one character.
1246 return source;
1247
1248 String base = source.substring(0,len);
1249 String combiningMarks = source.substring(len);
1250
1251 String[] perms = producePermutations(combiningMarks);
1252 StringBuilder result = new StringBuilder(source);
1253
1254 // Add combined permutations
1255 for(int x=0; x<perms.length; x++) {
1256 String next = base + perms[x];
1257 if (x>0)
1258 result.append("|"+next);
1259 next = composeOneStep(next);
1260 if (next != null)
1261 result.append("|"+produceEquivalentAlternation(next));
1262 }
1263 return result.toString();
1264 }
1265
1266 /**
1267 * Returns an array of strings that have all the possible
1268 * permutations of the characters in the input string.
1269 * This is used to get a list of all possible orderings
1270 * of a set of combining marks. Note that some of the permutations
1271 * are invalid because of combining class collisions, and these
1272 * possibilities must be removed because they are not canonically
1273 * equivalent.
1274 */
1275 private String[] producePermutations(String input) {
1276 if (input.length() == countChars(input, 0, 1))
1277 return new String[] {input};
1278
1279 if (input.length() == countChars(input, 0, 2)) {
1280 int c0 = Character.codePointAt(input, 0);
1281 int c1 = Character.codePointAt(input, Character.charCount(c0));
1282 if (getClass(c1) == getClass(c0)) {
1283 return new String[] {input};
1284 }
1285 String[] result = new String[2];
1286 result[0] = input;
1287 StringBuilder sb = new StringBuilder(2);
1288 sb.appendCodePoint(c1);
1289 sb.appendCodePoint(c0);
1290 result[1] = sb.toString();
1291 return result;
1292 }
1293
1294 int length = 1;
1295 int nCodePoints = countCodePoints(input);
1296 for(int x=1; x<nCodePoints; x++)
1297 length = length * (x+1);
1298
1299 String[] temp = new String[length];
1300
1301 int combClass[] = new int[nCodePoints];
1302 for(int x=0, i=0; x<nCodePoints; x++) {
1303 int c = Character.codePointAt(input, i);
1304 combClass[x] = getClass(c);
1305 i += Character.charCount(c);
1306 }
1307
1308 // For each char, take it out and add the permutations
1309 // of the remaining chars
1310 int index = 0;
1311 int len;
1312 // offset maintains the index in code units.
1313 loop: for(int x=0, offset=0; x<nCodePoints; x++, offset+=len) {
1314 len = countChars(input, offset, 1);
1315 boolean skip = false;
1316 for(int y=x-1; y>=0; y--) {
1317 if (combClass[y] == combClass[x]) {
1318 continue loop;
1319 }
1320 }
1321 StringBuilder sb = new StringBuilder(input);
1322 String otherChars = sb.delete(offset, offset+len).toString();
1323 String[] subResult = producePermutations(otherChars);
1324
1325 String prefix = input.substring(offset, offset+len);
1326 for(int y=0; y<subResult.length; y++)
1327 temp[index++] = prefix + subResult[y];
1328 }
1329 String[] result = new String[index];
1330 for (int x=0; x<index; x++)
1331 result[x] = temp[x];
1332 return result;
1333 }
1334
1335 private int getClass(int c) {
1336 return sun.text.Normalizer.getCombiningClass(c);
1337 }
1338
1339 /**
1340 * Attempts to compose input by combining the first character
1341 * with the first combining mark following it. Returns a String
1342 * that is the composition of the leading character with its first
1343 * combining mark followed by the remaining combining marks. Returns
1344 * null if the first two characters cannot be further composed.
1345 */
1346 private String composeOneStep(String input) {
1347 int len = countChars(input, 0, 2);
1348 String firstTwoCharacters = input.substring(0, len);
1349 String result = Normalizer.normalize(firstTwoCharacters, Normalizer.Form.NFC);
1350
1351 if (result.equals(firstTwoCharacters))
1352 return null;
1353 else {
1354 String remainder = input.substring(len);
1355 return result + remainder;
1356 }
1357 }
1358
1359 /**
1360 * Preprocess any /Q.../E sequences in `temp', meta-quoting them.
1361 * See the description of `quotemeta' in perlfunc(1).
1362 */
1363 private void RemoveQEQuoting() {
1364 for (int i = 0; i < patternLength-1; i++)
1365 if (temp[i] == '\\' && temp[i+1] == 'Q') {
1366 int j = i;
1367 int[] newtemp = new int[j + 2*(temp.length-j) - 6];
1368 System.arraycopy(temp, 0, newtemp, 0, j);
1369 i+=2;
1370 boolean inQuote = true;
1371 while (i < patternLength) {
1372 int c = temp[i++];
1373 if (! ASCII.isAscii(c) || ASCII.isAlnum(c)) {
1374 newtemp[j++] = c;
1375 } else if (c != '\\') {
1376 if (inQuote) newtemp[j++] = '\\';
1377 newtemp[j++] = c;
1378 } else if (inQuote) {
1379 if (temp[i] == 'E') {
1380 i++;
1381 inQuote = false;
1382 } else {
1383 newtemp[j++] = '\\';
1384 newtemp[j++] = '\\';
1385 }
1386 } else {
1387 if (temp[i] == 'Q') {
1388 i++;
1389 inQuote = true;
1390 } else {
1391 newtemp[j++] = c;
1392 }
1393 }
1394 }
1395 patternLength = j;
1396 int[] newtemp2 = new int[patternLength+2];
1397 System.arraycopy(newtemp, 0, newtemp2, 0, patternLength);
1398 temp = newtemp2;
1399 return;
1400 }
1401 }
1402
1403 /**
1404 * Copies regular expression to an int array and invokes the parsing
1405 * of the expression which will create the object tree.
1406 */
1407 private void compile() {
1408 // Handle canonical equivalences
1409 if (has(CANON_EQ) && !has(LITERAL)) {
1410 normalize();
1411 } else {
1412 normalizedPattern = pattern;
1413 }
1414 patternLength = normalizedPattern.length();
1415
1416 // Copy pattern to int array for convenience
1417 // Use double zero to terminate pattern
1418 temp = new int[patternLength + 2];
1419
1420 boolean hasSupplementary = false;
1421 int c, count = 0;
1422 // Convert all chars into code points
1423 for (int x = 0; x < patternLength; x += Character.charCount(c)) {
1424 c = normalizedPattern.codePointAt(x);
1425 if (isSupplementary(c)) {
1426 hasSupplementary = true;
1427 }
1428 temp[count++] = c;
1429 }
1430
1431 patternLength = count; // patternLength now in code points
1432
1433 if (! has(LITERAL))
1434 RemoveQEQuoting();
1435
1436 // Allocate all temporary objects here.
1437 buffer = new int[32];
1438 groupNodes = new GroupHead[10];
1439
1440 if (has(LITERAL)) {
1441 // Literal pattern handling
1442 matchRoot = newSlice(temp, patternLength, hasSupplementary);
1443 matchRoot.next = lastAccept;
1444 } else {
1445 // Start recursive descent parsing
1446 matchRoot = expr(lastAccept);
1447 // Check extra pattern characters
1448 if (patternLength != cursor) {
1449 if (peek() == ')') {
1450 throw error("Unmatched closing ')'");
1451 } else {
1452 throw error("Unexpected internal error");
1453 }
1454 }
1455 }
1456
1457 // Peephole optimization
1458 if (matchRoot instanceof Slice) {
1459 root = BnM.optimize(matchRoot);
1460 if (root == matchRoot) {
1461 root = hasSupplementary ? new StartS(matchRoot) : new Start(matchRoot);
1462 }
1463 } else if (matchRoot instanceof Begin || matchRoot instanceof First) {
1464 root = matchRoot;
1465 } else {
1466 root = hasSupplementary ? new StartS(matchRoot) : new Start(matchRoot);
1467 }
1468
1469 // Release temporary storage
1470 temp = null;
1471 buffer = null;
1472 groupNodes = null;
1473 patternLength = 0;
1474 compiled = true;
1475 }
1476
1477 /**
1478 * Used to print out a subtree of the Pattern to help with debugging.
1479 */
1480 private static void printObjectTree(Node node) {
1481 while(node != null) {
1482 if (node instanceof Prolog) {
1483 System.out.println(node);
1484 printObjectTree(((Prolog)node).loop);
1485 System.out.println("**** end contents prolog loop");
1486 } else if (node instanceof Loop) {
1487 System.out.println(node);
1488 printObjectTree(((Loop)node).body);
1489 System.out.println("**** end contents Loop body");
1490 } else if (node instanceof Curly) {
1491 System.out.println(node);
1492 printObjectTree(((Curly)node).atom);
1493 System.out.println("**** end contents Curly body");
1494 } else if (node instanceof GroupCurly) {
1495 System.out.println(node);
1496 printObjectTree(((GroupCurly)node).atom);
1497 System.out.println("**** end contents GroupCurly body");
1498 } else if (node instanceof GroupTail) {
1499 System.out.println(node);
1500 System.out.println("Tail next is "+node.next);
1501 return;
1502 } else {
1503 System.out.println(node);
1504 }
1505 node = node.next;
1506 if (node != null)
1507 System.out.println("->next:");
1508 if (node == Pattern.accept) {
1509 System.out.println("Accept Node");
1510 node = null;
1511 }
1512 }
1513 }
1514
1515 /**
1516 * Used to accumulate information about a subtree of the object graph
1517 * so that optimizations can be applied to the subtree.
1518 */
1519 static final class TreeInfo {
1520 int minLength;
1521 int maxLength;
1522 boolean maxValid;
1523 boolean deterministic;
1524
1525 TreeInfo() {
1526 reset();
1527 }
1528 void reset() {
1529 minLength = 0;
1530 maxLength = 0;
1531 maxValid = true;
1532 deterministic = true;
1533 }
1534 }
1535
1536 /*
1537 * The following private methods are mainly used to improve the
1538 * readability of the code. In order to let the Java compiler easily
1539 * inline them, we should not put many assertions or error checks in them.
1540 */
1541
1542 /**
1543 * Indicates whether a particular flag is set or not.
1544 */
1545 private boolean has(int f) {
1546 return (flags & f) != 0;
1547 }
1548
1549 /**
1550 * Match next character, signal error if failed.
1551 */
1552 private void accept(int ch, String s) {
1553 int testChar = temp[cursor++];
1554 if (has(COMMENTS))
1555 testChar = parsePastWhitespace(testChar);
1556 if (ch != testChar) {
1557 throw error(s);
1558 }
1559 }
1560
1561 /**
1562 * Mark the end of pattern with a specific character.
1563 */
1564 private void mark(int c) {
1565 temp[patternLength] = c;
1566 }
1567
1568 /**
1569 * Peek the next character, and do not advance the cursor.
1570 */
1571 private int peek() {
1572 int ch = temp[cursor];
1573 if (has(COMMENTS))
1574 ch = peekPastWhitespace(ch);
1575 return ch;
1576 }
1577
1578 /**
1579 * Read the next character, and advance the cursor by one.
1580 */
1581 private int read() {
1582 int ch = temp[cursor++];
1583 if (has(COMMENTS))
1584 ch = parsePastWhitespace(ch);
1585 return ch;
1586 }
1587
1588 /**
1589 * Read the next character, and advance the cursor by one,
1590 * ignoring the COMMENTS setting
1591 */
1592 private int readEscaped() {
1593 int ch = temp[cursor++];
1594 return ch;
1595 }
1596
1597 /**
1598 * Advance the cursor by one, and peek the next character.
1599 */
1600 private int next() {
1601 int ch = temp[++cursor];
1602 if (has(COMMENTS))
1603 ch = peekPastWhitespace(ch);
1604 return ch;
1605 }
1606
1607 /**
1608 * Advance the cursor by one, and peek the next character,
1609 * ignoring the COMMENTS setting
1610 */
1611 private int nextEscaped() {
1612 int ch = temp[++cursor];
1613 return ch;
1614 }
1615
1616 /**
1617 * If in xmode peek past whitespace and comments.
1618 */
1619 private int peekPastWhitespace(int ch) {
1620 while (ASCII.isSpace(ch) || ch == '#') {
1621 while (ASCII.isSpace(ch))
1622 ch = temp[++cursor];
1623 if (ch == '#') {
1624 ch = peekPastLine();
1625 }
1626 }
1627 return ch;
1628 }
1629
1630 /**
1631 * If in xmode parse past whitespace and comments.
1632 */
1633 private int parsePastWhitespace(int ch) {
1634 while (ASCII.isSpace(ch) || ch == '#') {
1635 while (ASCII.isSpace(ch))
1636 ch = temp[cursor++];
1637 if (ch == '#')
1638 ch = parsePastLine();
1639 }
1640 return ch;
1641 }
1642
1643 /**
1644 * xmode parse past comment to end of line.
1645 */
1646 private int parsePastLine() {
1647 int ch = temp[cursor++];
1648 while (ch != 0 && !isLineSeparator(ch))
1649 ch = temp[cursor++];
1650 return ch;
1651 }
1652
1653 /**
1654 * xmode peek past comment to end of line.
1655 */
1656 private int peekPastLine() {
1657 int ch = temp[++cursor];
1658 while (ch != 0 && !isLineSeparator(ch))
1659 ch = temp[++cursor];
1660 return ch;
1661 }
1662
1663 /**
1664 * Determines if character is a line separator in the current mode
1665 */
1666 private boolean isLineSeparator(int ch) {
1667 if (has(UNIX_LINES)) {
1668 return ch == '\n';
1669 } else {
1670 return (ch == '\n' ||
1671 ch == '\r' ||
1672 (ch|1) == '\u2029' ||
1673 ch == '\u0085');
1674 }
1675 }
1676
1677 /**
1678 * Read the character after the next one, and advance the cursor by two.
1679 */
1680 private int skip() {
1681 int i = cursor;
1682 int ch = temp[i+1];
1683 cursor = i + 2;
1684 return ch;
1685 }
1686
1687 /**
1688 * Unread one next character, and retreat cursor by one.
1689 */
1690 private void unread() {
1691 cursor--;
1692 }
1693
1694 /**
1695 * Internal method used for handling all syntax errors. The pattern is
1696 * displayed with a pointer to aid in locating the syntax error.
1697 */
1698 private PatternSyntaxException error(String s) {
1699 return new PatternSyntaxException(s, normalizedPattern, cursor - 1);
1700 }
1701
1702 /**
1703 * Determines if there is any supplementary character or unpaired
1704 * surrogate in the specified range.
1705 */
1706 private boolean findSupplementary(int start, int end) {
1707 for (int i = start; i < end; i++) {
1708 if (isSupplementary(temp[i]))
1709 return true;
1710 }
1711 return false;
1712 }
1713
1714 /**
1715 * Determines if the specified code point is a supplementary
1716 * character or unpaired surrogate.
1717 */
1718 private static final boolean isSupplementary(int ch) {
1719 return ch >= Character.MIN_SUPPLEMENTARY_CODE_POINT || isSurrogate(ch);
1720 }
1721
1722 /**
1723 * The following methods handle the main parsing. They are sorted
1724 * according to their precedence order, the lowest one first.
1725 */
1726
1727 /**
1728 * The expression is parsed with branch nodes added for alternations.
1729 * This may be called recursively to parse sub expressions that may
1730 * contain alternations.
1731 */
1732 private Node expr(Node end) {
1733 Node prev = null;
1734 Node firstTail = null;
1735 Node branchConn = null;
1736
1737 for (;;) {
1738 Node node = sequence(end);
1739 Node nodeTail = root; //double return
1740 if (prev == null) {
1741 prev = node;
1742 firstTail = nodeTail;
1743 } else {
1744 // Branch
1745 if (branchConn == null) {
1746 branchConn = new BranchConn();
1747 branchConn.next = end;
1748 }
1749 if (node == end) {
1750 // if the node returned from sequence() is "end"
1751 // we have an empty expr, set a null atom into
1752 // the branch to indicate to go "next" directly.
1753 node = null;
1754 } else {
1755 // the "tail.next" of each atom goes to branchConn
1756 nodeTail.next = branchConn;
1757 }
1758 if (prev instanceof Branch) {
1759 ((Branch)prev).add(node);
1760 } else {
1761 if (prev == end) {
1762 prev = null;
1763 } else {
1764 // replace the "end" with "branchConn" at its tail.next
1765 // when put the "prev" into the branch as the first atom.
1766 firstTail.next = branchConn;
1767 }
1768 prev = new Branch(prev, node, branchConn);
1769 }
1770 }
1771 if (peek() != '|') {
1772 return prev;
1773 }
1774 next();
1775 }
1776 }
1777
1778 /**
1779 * Parsing of sequences between alternations.
1780 */
1781 private Node sequence(Node end) {
1782 Node head = null;
1783 Node tail = null;
1784 Node node = null;
1785 LOOP:
1786 for (;;) {
1787 int ch = peek();
1788 switch (ch) {
1789 case '(':
1790 // Because group handles its own closure,
1791 // we need to treat it differently
1792 node = group0();
1793 // Check for comment or flag group
1794 if (node == null)
1795 continue;
1796 if (head == null)
1797 head = node;
1798 else
1799 tail.next = node;
1800 // Double return: Tail was returned in root
1801 tail = root;
1802 continue;
1803 case '[':
1804 node = clazz(true);
1805 break;
1806 case '\\':
1807 ch = nextEscaped();
1808 if (ch == 'p' || ch == 'P') {
1809 boolean oneLetter = true;
1810 boolean comp = (ch == 'P');
1811 ch = next(); // Consume { if present
1812 if (ch != '{') {
1813 unread();
1814 } else {
1815 oneLetter = false;
1816 }
1817 node = family(oneLetter).maybeComplement(comp);
1818 } else {
1819 unread();
1820 node = atom();
1821 }
1822 break;
1823 case '^':
1824 next();
1825 if (has(MULTILINE)) {
1826 if (has(UNIX_LINES))
1827 node = new UnixCaret();
1828 else
1829 node = new Caret();
1830 } else {
1831 node = new Begin();
1832 }
1833 break;
1834 case '$':
1835 next();
1836 if (has(UNIX_LINES))
1837 node = new UnixDollar(has(MULTILINE));
1838 else
1839 node = new Dollar(has(MULTILINE));
1840 break;
1841 case '.':
1842 next();
1843 if (has(DOTALL)) {
1844 node = new All();
1845 } else {
1846 if (has(UNIX_LINES))
1847 node = new UnixDot();
1848 else {
1849 node = new Dot();
1850 }
1851 }
1852 break;
1853 case '|':
1854 case ')':
1855 break LOOP;
1856 case ']': // Now interpreting dangling ] and } as literals
1857 case '}':
1858 node = atom();
1859 break;
1860 case '?':
1861 case '*':
1862 case '+':
1863 next();
1864 throw error("Dangling meta character '" + ((char)ch) + "'");
1865 case 0:
1866 if (cursor >= patternLength) {
1867 break LOOP;
1868 }
1869 // Fall through
1870 default:
1871 node = atom();
1872 break;
1873 }
1874
1875 node = closure(node);
1876
1877 if (head == null) {
1878 head = tail = node;
1879 } else {
1880 tail.next = node;
1881 tail = node;
1882 }
1883 }
1884 if (head == null) {
1885 return end;
1886 }
1887 tail.next = end;
1888 root = tail; //double return
1889 return head;
1890 }
1891
1892 /**
1893 * Parse and add a new Single or Slice.
1894 */
1895 private Node atom() {
1896 int first = 0;
1897 int prev = -1;
1898 boolean hasSupplementary = false;
1899 int ch = peek();
1900 for (;;) {
1901 switch (ch) {
1902 case '*':
1903 case '+':
1904 case '?':
1905 case '{':
1906 if (first > 1) {
1907 cursor = prev; // Unwind one character
1908 first--;
1909 }
1910 break;
1911 case '$':
1912 case '.':
1913 case '^':
1914 case '(':
1915 case '[':
1916 case '|':
1917 case ')':
1918 break;
1919 case '\\':
1920 ch = nextEscaped();
1921 if (ch == 'p' || ch == 'P') { // Property
1922 if (first > 0) { // Slice is waiting; handle it first
1923 unread();
1924 break;
1925 } else { // No slice; just return the family node
1926 boolean comp = (ch == 'P');
1927 boolean oneLetter = true;
1928 ch = next(); // Consume { if present
1929 if (ch != '{')
1930 unread();
1931 else
1932 oneLetter = false;
1933 return family(oneLetter).maybeComplement(comp);
1934 }
1935 }
1936 unread();
1937 prev = cursor;
1938 ch = escape(false, first == 0);
1939 if (ch >= 0) {
1940 append(ch, first);
1941 first++;
1942 if (isSupplementary(ch)) {
1943 hasSupplementary = true;
1944 }
1945 ch = peek();
1946 continue;
1947 } else if (first == 0) {
1948 return root;
1949 }
1950 // Unwind meta escape sequence
1951 cursor = prev;
1952 break;
1953 case 0:
1954 if (cursor >= patternLength) {
1955 break;
1956 }
1957 // Fall through
1958 default:
1959 prev = cursor;
1960 append(ch, first);
1961 first++;
1962 if (isSupplementary(ch)) {
1963 hasSupplementary = true;
1964 }
1965 ch = next();
1966 continue;
1967 }
1968 break;
1969 }
1970 if (first == 1) {
1971 return newSingle(buffer[0]);
1972 } else {
1973 return newSlice(buffer, first, hasSupplementary);
1974 }
1975 }
1976
1977 private void append(int ch, int len) {
1978 if (len >= buffer.length) {
1979 int[] tmp = new int[len+len];
1980 System.arraycopy(buffer, 0, tmp, 0, len);
1981 buffer = tmp;
1982 }
1983 buffer[len] = ch;
1984 }
1985
1986 /**
1987 * Parses a backref greedily, taking as many numbers as it
1988 * can. The first digit is always treated as a backref, but
1989 * multi digit numbers are only treated as a backref if at
1990 * least that many backrefs exist at this point in the regex.
1991 */
1992 private Node ref(int refNum) {
1993 boolean done = false;
1994 while(!done) {
1995 int ch = peek();
1996 switch(ch) {
1997 case '0':
1998 case '1':
1999 case '2':
2000 case '3':
2001 case '4':
2002 case '5':
2003 case '6':
2004 case '7':
2005 case '8':
2006 case '9':
2007 int newRefNum = (refNum * 10) + (ch - '0');
2008 // Add another number if it doesn't make a group
2009 // that doesn't exist
2010 if (capturingGroupCount - 1 < newRefNum) {
2011 done = true;
2012 break;
2013 }
2014 refNum = newRefNum;
2015 read();
2016 break;
2017 default:
2018 done = true;
2019 break;
2020 }
2021 }
2022 if (has(CASE_INSENSITIVE) || has(UNICODE_CASE))
2023 return new CIBackRef(refNum);
2024 else
2025 return new BackRef(refNum);
2026 }
2027
2028 /**
2029 * Parses an escape sequence to determine the actual value that needs
2030 * to be matched.
2031 * If -1 is returned and create was true a new object was added to the tree
2032 * to handle the escape sequence.
2033 * If the returned value is greater than zero, it is the value that
2034 * matches the escape sequence.
2035 */
2036 private int escape(boolean inclass, boolean create) {
2037 int ch = skip();
2038 switch (ch) {
2039 case '0':
2040 return o();
2041 case '1':
2042 case '2':
2043 case '3':
2044 case '4':
2045 case '5':
2046 case '6':
2047 case '7':
2048 case '8':
2049 case '9':
2050 if (inclass) break;
2051 if (capturingGroupCount < (ch - '0'))
2052 throw error("No such group yet exists at this point in the pattern");
2053 if (create) {
2054 root = ref((ch - '0'));
2055 }
2056 return -1;
2057 case 'A':
2058 if (inclass) break;
2059 if (create) root = new Begin();
2060 return -1;
2061 case 'B':
2062 if (inclass) break;
2063 if (create) root = new Bound(Bound.NONE);
2064 return -1;
2065 case 'C':
2066 break;
2067 case 'D':
2068 if (create) root = new Ctype(ASCII.DIGIT).complement();
2069 return -1;
2070 case 'E':
2071 case 'F':
2072 break;
2073 case 'G':
2074 if (inclass) break;
2075 if (create) root = new LastMatch();
2076 return -1;
2077 case 'H':
2078 case 'I':
2079 case 'J':
2080 case 'K':
2081 case 'L':
2082 case 'M':
2083 case 'N':
2084 case 'O':
2085 case 'P':
2086 case 'Q':
2087 case 'R':
2088 break;
2089 case 'S':
2090 if (create) root = new Ctype(ASCII.SPACE).complement();
2091 return -1;
2092 case 'T':
2093 case 'U':
2094 case 'V':
2095 break;
2096 case 'W':
2097 if (create) root = new Ctype(ASCII.WORD).complement();
2098 return -1;
2099 case 'X':
2100 case 'Y':
2101 break;
2102 case 'Z':
2103 if (inclass) break;
2104 if (create) {
2105 if (has(UNIX_LINES))
2106 root = new UnixDollar(false);
2107 else
2108 root = new Dollar(false);
2109 }
2110 return -1;
2111 case 'a':
2112 return '\007';
2113 case 'b':
2114 if (inclass) break;
2115 if (create) root = new Bound(Bound.BOTH);
2116 return -1;
2117 case 'c':
2118 return c();
2119 case 'd':
2120 if (create) root = new Ctype(ASCII.DIGIT);
2121 return -1;
2122 case 'e':
2123 return '\033';
2124 case 'f':
2125 return '\f';
2126 case 'g':
2127 case 'h':
2128 case 'i':
2129 case 'j':
2130 case 'k':
2131 case 'l':
2132 case 'm':
2133 break;
2134 case 'n':
2135 return '\n';
2136 case 'o':
2137 case 'p':
2138 case 'q':
2139 break;
2140 case 'r':
2141 return '\r';
2142 case 's':
2143 if (create) root = new Ctype(ASCII.SPACE);
2144 return -1;
2145 case 't':
2146 return '\t';
2147 case 'u':
2148 return u();
2149 case 'v':
2150 return '\013';
2151 case 'w':
2152 if (create) root = new Ctype(ASCII.WORD);
2153 return -1;
2154 case 'x':
2155 return x();
2156 case 'y':
2157 break;
2158 case 'z':
2159 if (inclass) break;
2160 if (create) root = new End();
2161 return -1;
2162 default:
2163 return ch;
2164 }
2165 throw error("Illegal/unsupported escape squence");
2166 }
2167
2168 /**
2169 * Parse a character class, and return the node that matches it.
2170 *
2171 * Consumes a ] on the way out if consume is true. Usually consume
2172 * is true except for the case of [abc&&def] where def is a separate
2173 * right hand node with "understood" brackets.
2174 */
2175 private CharProperty clazz(boolean consume) {
2176 CharProperty prev = null;
2177 CharProperty node = null;
2178 BitClass bits = new BitClass();
2179 boolean include = true;
2180 boolean firstInClass = true;
2181 int ch = next();
2182 for (;;) {
2183 switch (ch) {
2184 case '^':
2185 // Negates if first char in a class, otherwise literal
2186 if (firstInClass) {
2187 if (temp[cursor-1] != '[')
2188 break;
2189 ch = next();
2190 include = !include;
2191 continue;
2192 } else {
2193 // ^ not first in class, treat as literal
2194 break;
2195 }
2196 case '[':
2197 firstInClass = false;
2198 node = clazz(true);
2199 if (prev == null)
2200 prev = node;
2201 else
2202 prev = union(prev, node);
2203 ch = peek();
2204 continue;
2205 case '&':
2206 firstInClass = false;
2207 ch = next();
2208 if (ch == '&') {
2209 ch = next();
2210 CharProperty rightNode = null;
2211 while (ch != ']' && ch != '&') {
2212 if (ch == '[') {
2213 if (rightNode == null)
2214 rightNode = clazz(true);
2215 else
2216 rightNode = union(rightNode, clazz(true));
2217 } else { // abc&&def
2218 unread();
2219 rightNode = clazz(false);
2220 }
2221 ch = peek();
2222 }
2223 if (rightNode != null)
2224 node = rightNode;
2225 if (prev == null) {
2226 if (rightNode == null)
2227 throw error("Bad class syntax");
2228 else
2229 prev = rightNode;
2230 } else {
2231 prev = intersection(prev, node);
2232 }
2233 } else {
2234 // treat as a literal &
2235 unread();
2236 break;
2237 }
2238 continue;
2239 case 0:
2240 firstInClass = false;
2241 if (cursor >= patternLength)
2242 throw error("Unclosed character class");
2243 break;
2244 case ']':
2245 firstInClass = false;
2246 if (prev != null) {
2247 if (consume)
2248 next();
2249 return prev;
2250 }
2251 break;
2252 default:
2253 firstInClass = false;
2254 break;
2255 }
2256 node = range(bits);
2257 if (include) {
2258 if (prev == null) {
2259 prev = node;
2260 } else {
2261 if (prev != node)
2262 prev = union(prev, node);
2263 }
2264 } else {
2265 if (prev == null) {
2266 prev = node.complement();
2267 } else {
2268 if (prev != node)
2269 prev = setDifference(prev, node);
2270 }
2271 }
2272 ch = peek();
2273 }
2274 }
2275
2276 /**
2277 * Parse a single character or a character range in a character class
2278 * and return its representative node.
2279 */
2280 private CharProperty range(BitClass bits) {
2281 int ch = peek();
2282 if (ch == '\\') {
2283 ch = nextEscaped();
2284 if (ch == 'p' || ch == 'P') { // A property
2285 boolean comp = (ch == 'P');
2286 boolean oneLetter = true;
2287 // Consume { if present
2288 ch = next();
2289 if (ch != '{')
2290 unread();
2291 else
2292 oneLetter = false;
2293 return family(oneLetter).maybeComplement(comp);
2294 } else { // ordinary escape
2295 unread();
2296 ch = escape(true, true);
2297 if (ch == -1)
2298 return (CharProperty) root;
2299 }
2300 } else {
2301 ch = single();
2302 }
2303 if (ch >= 0) {
2304 if (peek() == '-') {
2305 int endRange = temp[cursor+1];
2306 if (endRange == '[') {
2307 if (ch < 256)
2308 return bits.add(ch, flags());
2309 return newSingle(ch);
2310 }
2311 if (endRange != ']') {
2312 next();
2313 int m = single();
2314 if (m < ch)
2315 throw error("Illegal character range");
2316 if (has(CASE_INSENSITIVE) || has(UNICODE_CASE))
2317 return caseInsensitiveRangeFor(ch, m);
2318 else
2319 return rangeFor(ch, m);
2320 }
2321 }
2322 if (ch < 256)
2323 return bits.add(ch, flags());
2324 return newSingle(ch);
2325 }
2326 throw error("Unexpected character '"+((char)ch)+"'");
2327 }
2328
2329 private int single() {
2330 int ch = peek();
2331 switch (ch) {
2332 case '\\':
2333 return escape(true, false);
2334 default:
2335 next();
2336 return ch;
2337 }
2338 }
2339
2340 /**
2341 * Parses a Unicode character family and returns its representative node.
2342 */
2343 private CharProperty family(boolean singleLetter) {
2344 next();
2345 String name;
2346
2347 if (singleLetter) {
2348 int c = temp[cursor];
2349 if (!Character.isSupplementaryCodePoint(c)) {
2350 name = String.valueOf((char)c);
2351 } else {
2352 name = new String(temp, cursor, 1);
2353 }
2354 read();
2355 } else {
2356 int i = cursor;
2357 mark('}');
2358 while(read() != '}') {
2359 }
2360 mark('\000');
2361 int j = cursor;
2362 if (j > patternLength)
2363 throw error("Unclosed character family");
2364 if (i + 1 >= j)
2365 throw error("Empty character family");
2366 name = new String(temp, i, j-i-1);
2367 }
2368
2369 if (name.startsWith("In")) {
2370 return unicodeBlockPropertyFor(name.substring(2));
2371 } else {
2372 if (name.startsWith("Is"))
2373 name = name.substring(2);
2374 return charPropertyNodeFor(name);
2375 }
2376 }
2377
2378 /**
2379 * Returns a CharProperty matching all characters in a UnicodeBlock.
2380 */
2381 private CharProperty unicodeBlockPropertyFor(String name) {
2382 final Character.UnicodeBlock block;
2383 try {
2384 block = Character.UnicodeBlock.forName(name);
2385 } catch (IllegalArgumentException iae) {
2386 throw error("Unknown character block name {" + name + "}");
2387 }
2388 return new CharProperty() {
2389 boolean isSatisfiedBy(int ch) {
2390 return block == Character.UnicodeBlock.of(ch);}};
2391 }
2392
2393 /**
2394 * Returns a CharProperty matching all characters in a named property.
2395 */
2396 private CharProperty charPropertyNodeFor(String name) {
2397 CharProperty p = CharPropertyNames.charPropertyFor(name);
2398 if (p == null)
2399 throw error("Unknown character property name {" + name + "}");
2400 return p;
2401 }
2402
2403 /**
2404 * Parses a group and returns the head node of a set of nodes that process
2405 * the group. Sometimes a double return system is used where the tail is
2406 * returned in root.
2407 */
2408 private Node group0() {
2409 boolean capturingGroup = false;
2410 Node head = null;
2411 Node tail = null;
2412 int save = flags;
2413 root = null;
2414 int ch = next();
2415 if (ch == '?') {
2416 ch = skip();
2417 switch (ch) {
2418 case ':': // (?:xxx) pure group
2419 head = createGroup(true);
2420 tail = root;
2421 head.next = expr(tail);
2422 break;
2423 case '=': // (?=xxx) and (?!xxx) lookahead
2424 case '!':
2425 head = createGroup(true);
2426 tail = root;
2427 head.next = expr(tail);
2428 if (ch == '=') {
2429 head = tail = new Pos(head);
2430 } else {
2431 head = tail = new Neg(head);
2432 }
2433 break;
2434 case '>': // (?>xxx) independent group
2435 head = createGroup(true);
2436 tail = root;
2437 head.next = expr(tail);
2438 head = tail = new Ques(head, INDEPENDENT);
2439 break;
2440 case '<': // (?<xxx) look behind
2441 ch = read();
2442 int start = cursor;
2443 head = createGroup(true);
2444 tail = root;
2445 head.next = expr(tail);
2446 TreeInfo info = new TreeInfo();
2447 head.study(info);
2448 if (info.maxValid == false) {
2449 throw error("Look-behind group does not have "
2450 + "an obvious maximum length");
2451 }
2452 boolean hasSupplementary = findSupplementary(start, patternLength);
2453 if (ch == '=') {
2454 head = tail = (hasSupplementary ?
2455 new BehindS(head, info.maxLength,
2456 info.minLength) :
2457 new Behind(head, info.maxLength,
2458 info.minLength));
2459 } else if (ch == '!') {
2460 head = tail = (hasSupplementary ?
2461 new NotBehindS(head, info.maxLength,
2462 info.minLength) :
2463 new NotBehind(head, info.maxLength,
2464 info.minLength));
2465 } else {
2466 throw error("Unknown look-behind group");
2467 }
2468 break;
2469 case '$':
2470 case '@':
2471 throw error("Unknown group type");
2472 default: // (?xxx:) inlined match flags
2473 unread();
2474 addFlag();
2475 ch = read();
2476 if (ch == ')') {
2477 return null; // Inline modifier only
2478 }
2479 if (ch != ':') {
2480 throw error("Unknown inline modifier");
2481 }
2482 head = createGroup(true);
2483 tail = root;
2484 head.next = expr(tail);
2485 break;
2486 }
2487 } else { // (xxx) a regular group
2488 capturingGroup = true;
2489 head = createGroup(false);
2490 tail = root;
2491 head.next = expr(tail);
2492 }
2493
2494 accept(')', "Unclosed group");
2495 flags = save;
2496
2497 // Check for quantifiers
2498 Node node = closure(head);
2499 if (node == head) { // No closure
2500 root = tail;
2501 return node; // Dual return
2502 }
2503 if (head == tail) { // Zero length assertion
2504 root = node;
2505 return node; // Dual return
2506 }
2507
2508 if (node instanceof Ques) {
2509 Ques ques = (Ques) node;
2510 if (ques.type == POSSESSIVE) {
2511 root = node;
2512 return node;
2513 }
2514 tail.next = new BranchConn();
2515 tail = tail.next;
2516 if (ques.type == GREEDY) {
2517 head = new Branch(head, null, tail);
2518 } else { // Reluctant quantifier
2519 head = new Branch(null, head, tail);
2520 }
2521 root = tail;
2522 return head;
2523 } else if (node instanceof Curly) {
2524 Curly curly = (Curly) node;
2525 if (curly.type == POSSESSIVE) {
2526 root = node;
2527 return node;
2528 }
2529 // Discover if the group is deterministic
2530 TreeInfo info = new TreeInfo();
2531 if (head.study(info)) { // Deterministic
2532 GroupTail temp = (GroupTail) tail;
2533 head = root = new GroupCurly(head.next, curly.cmin,
2534 curly.cmax, curly.type,
2535 ((GroupTail)tail).localIndex,
2536 ((GroupTail)tail).groupIndex,
2537 capturingGroup);
2538 return head;
2539 } else { // Non-deterministic
2540 int temp = ((GroupHead) head).localIndex;
2541 Loop loop;
2542 if (curly.type == GREEDY)
2543 loop = new Loop(this.localCount, temp);
2544 else // Reluctant Curly
2545 loop = new LazyLoop(this.localCount, temp);
2546 Prolog prolog = new Prolog(loop);
2547 this.localCount += 1;
2548 loop.cmin = curly.cmin;
2549 loop.cmax = curly.cmax;
2550 loop.body = head;
2551 tail.next = loop;
2552 root = loop;
2553 return prolog; // Dual return
2554 }
2555 }
2556 throw error("Internal logic error");
2557 }
2558
2559 /**
2560 * Create group head and tail nodes using double return. If the group is
2561 * created with anonymous true then it is a pure group and should not
2562 * affect group counting.
2563 */
2564 private Node createGroup(boolean anonymous) {
2565 int localIndex = localCount++;
2566 int groupIndex = 0;
2567 if (!anonymous)
2568 groupIndex = capturingGroupCount++;
2569 GroupHead head = new GroupHead(localIndex);
2570 root = new GroupTail(localIndex, groupIndex);
2571 if (!anonymous && groupIndex < 10)
2572 groupNodes[groupIndex] = head;
2573 return head;
2574 }
2575
2576 /**
2577 * Parses inlined match flags and set them appropriately.
2578 */
2579 private void addFlag() {
2580 int ch = peek();
2581 for (;;) {
2582 switch (ch) {
2583 case 'i':
2584 flags |= CASE_INSENSITIVE;
2585 break;
2586 case 'm':
2587 flags |= MULTILINE;
2588 break;
2589 case 's':
2590 flags |= DOTALL;
2591 break;
2592 case 'd':
2593 flags |= UNIX_LINES;
2594 break;
2595 case 'u':
2596 flags |= UNICODE_CASE;
2597 break;
2598 case 'c':
2599 flags |= CANON_EQ;
2600 break;
2601 case 'x':
2602 flags |= COMMENTS;
2603 break;
2604 case '-': // subFlag then fall through
2605 ch = next();
2606 subFlag();
2607 default:
2608 return;
2609 }
2610 ch = next();
2611 }
2612 }
2613
2614 /**
2615 * Parses the second part of inlined match flags and turns off
2616 * flags appropriately.
2617 */
2618 private void subFlag() {
2619 int ch = peek();
2620 for (;;) {
2621 switch (ch) {
2622 case 'i':
2623 flags &= ~CASE_INSENSITIVE;
2624 break;
2625 case 'm':
2626 flags &= ~MULTILINE;
2627 break;
2628 case 's':
2629 flags &= ~DOTALL;
2630 break;
2631 case 'd':
2632 flags &= ~UNIX_LINES;
2633 break;
2634 case 'u':
2635 flags &= ~UNICODE_CASE;
2636 break;
2637 case 'c':
2638 flags &= ~CANON_EQ;
2639 break;
2640 case 'x':
2641 flags &= ~COMMENTS;
2642 break;
2643 default:
2644 return;
2645 }
2646 ch = next();
2647 }
2648 }
2649
2650 static final int MAX_REPS = 0x7FFFFFFF;
2651
2652 static final int GREEDY = 0;
2653
2654 static final int LAZY = 1;
2655
2656 static final int POSSESSIVE = 2;
2657
2658 static final int INDEPENDENT = 3;
2659
2660 /**
2661 * Processes repetition. If the next character peeked is a quantifier
2662 * then new nodes must be appended to handle the repetition.
2663 * Prev could be a single or a group, so it could be a chain of nodes.
2664 */
2665 private Node closure(Node prev) {
2666 Node atom;
2667 int ch = peek();
2668 switch (ch) {
2669 case '?':
2670 ch = next();
2671 if (ch == '?') {
2672 next();
2673 return new Ques(prev, LAZY);
2674 } else if (ch == '+') {
2675 next();
2676 return new Ques(prev, POSSESSIVE);
2677 }
2678 return new Ques(prev, GREEDY);
2679 case '*':
2680 ch = next();
2681 if (ch == '?') {
2682 next();
2683 return new Curly(prev, 0, MAX_REPS, LAZY);
2684 } else if (ch == '+') {
2685 next();
2686 return new Curly(prev, 0, MAX_REPS, POSSESSIVE);
2687 }
2688 return new Curly(prev, 0, MAX_REPS, GREEDY);
2689 case '+':
2690 ch = next();
2691 if (ch == '?') {
2692 next();
2693 return new Curly(prev, 1, MAX_REPS, LAZY);
2694 } else if (ch == '+') {
2695 next();
2696 return new Curly(prev, 1, MAX_REPS, POSSESSIVE);
2697 }
2698 return new Curly(prev, 1, MAX_REPS, GREEDY);
2699 case '{':
2700 ch = temp[cursor+1];
2701 if (ASCII.isDigit(ch)) {
2702 skip();
2703 int cmin = 0;
2704 do {
2705 cmin = cmin * 10 + (ch - '0');
2706 } while (ASCII.isDigit(ch = read()));
2707 int cmax = cmin;
2708 if (ch == ',') {
2709 ch = read();
2710 cmax = MAX_REPS;
2711 if (ch != '}') {
2712 cmax = 0;
2713 while (ASCII.isDigit(ch)) {
2714 cmax = cmax * 10 + (ch - '0');
2715 ch = read();
2716 }
2717 }
2718 }
2719 if (ch != '}')
2720 throw error("Unclosed counted closure");
2721 if (((cmin) | (cmax) | (cmax - cmin)) < 0)
2722 throw error("Illegal repetition range");
2723 Curly curly;
2724 ch = peek();
2725 if (ch == '?') {
2726 next();
2727 curly = new Curly(prev, cmin, cmax, LAZY);
2728 } else if (ch == '+') {
2729 next();
2730 curly = new Curly(prev, cmin, cmax, POSSESSIVE);
2731 } else {
2732 curly = new Curly(prev, cmin, cmax, GREEDY);
2733 }
2734 return curly;
2735 } else {
2736 throw error("Illegal repetition");
2737 }
2738 default:
2739 return prev;
2740 }
2741 }
2742
2743 /**
2744 * Utility method for parsing control escape sequences.
2745 */
2746 private int c() {
2747 if (cursor < patternLength) {
2748 return read() ^ 64;
2749 }
2750 throw error("Illegal control escape sequence");
2751 }
2752
2753 /**
2754 * Utility method for parsing octal escape sequences.
2755 */
2756 private int o() {
2757 int n = read();
2758 if (((n-'0')|('7'-n)) >= 0) {
2759 int m = read();
2760 if (((m-'0')|('7'-m)) >= 0) {
2761 int o = read();
2762 if ((((o-'0')|('7'-o)) >= 0) && (((n-'0')|('3'-n)) >= 0)) {
2763 return (n - '0') * 64 + (m - '0') * 8 + (o - '0');
2764 }
2765 unread();
2766 return (n - '0') * 8 + (m - '0');
2767 }
2768 unread();
2769 return (n - '0');
2770 }
2771 throw error("Illegal octal escape sequence");
2772 }
2773
2774 /**
2775 * Utility method for parsing hexadecimal escape sequences.
2776 */
2777 private int x() {
2778 int n = read();
2779 if (ASCII.isHexDigit(n)) {
2780 int m = read();
2781 if (ASCII.isHexDigit(m)) {
2782 return ASCII.toDigit(n) * 16 + ASCII.toDigit(m);
2783 }
2784 }
2785 throw error("Illegal hexadecimal escape sequence");
2786 }
2787
2788 /**
2789 * Utility method for parsing unicode escape sequences.
2790 */
2791 private int u() {
2792 int n = 0;
2793 for (int i = 0; i < 4; i++) {
2794 int ch = read();
2795 if (!ASCII.isHexDigit(ch)) {
2796 throw error("Illegal Unicode escape sequence");
2797 }
2798 n = n * 16 + ASCII.toDigit(ch);
2799 }
2800 return n;
2801 }
2802
2803 //
2804 // Utility methods for code point support
2805 //
2806
2807 /**
2808 * Tests a surrogate value.
2809 */
2810 private static final boolean isSurrogate(int c) {
2811 return c >= Character.MIN_HIGH_SURROGATE && c <= Character.MAX_LOW_SURROGATE;
2812 }
2813
2814 private static final int countChars(CharSequence seq, int index,
2815 int lengthInCodePoints) {
2816 // optimization
2817 if (lengthInCodePoints == 1 && !Character.isHighSurrogate(seq.charAt(index))) {
2818 assert (index >= 0 && index < seq.length());
2819 return 1;
2820 }
2821 int length = seq.length();
2822 int x = index;
2823 if (lengthInCodePoints >= 0) {
2824 assert (index >= 0 && index < length);
2825 for (int i = 0; x < length && i < lengthInCodePoints; i++) {
2826 if (Character.isHighSurrogate(seq.charAt(x++))) {
2827 if (x < length && Character.isLowSurrogate(seq.charAt(x))) {
2828 x++;
2829 }
2830 }
2831 }
2832 return x - index;
2833 }
2834
2835 assert (index >= 0 && index <= length);
2836 if (index == 0) {
2837 return 0;
2838 }
2839 int len = -lengthInCodePoints;
2840 for (int i = 0; x > 0 && i < len; i++) {
2841 if (Character.isLowSurrogate(seq.charAt(--x))) {
2842 if (x > 0 && Character.isHighSurrogate(seq.charAt(x-1))) {
2843 x--;
2844 }
2845 }
2846 }
2847 return index - x;
2848 }
2849
2850 private static final int countCodePoints(CharSequence seq) {
2851 int length = seq.length();
2852 int n = 0;
2853 for (int i = 0; i < length; ) {
2854 n++;
2855 if (Character.isHighSurrogate(seq.charAt(i++))) {
2856 if (i < length && Character.isLowSurrogate(seq.charAt(i))) {
2857 i++;
2858 }
2859 }
2860 }
2861 return n;
2862 }
2863
2864 /**
2865 * Creates a bit vector for matching Latin-1 values. A normal BitClass
2866 * never matches values above Latin-1, and a complemented BitClass always
2867 * matches values above Latin-1.
2868 */
2869 private static final class BitClass extends BmpCharProperty {
2870 final boolean[] bits;
2871 BitClass() { bits = new boolean[256]; }
2872 private BitClass(boolean[] bits) { this.bits = bits; }
2873 BitClass add(int c, int f) {
2874 assert c >= 0 && c <= 255;
2875 if ((f & CASE_INSENSITIVE) == 0) {
2876 bits[c] = true;
2877 } else if (ASCII.isAscii(c)) {
2878 bits[ASCII.toUpper(c)] = true;
2879 bits[ASCII.toLower(c)] = true;
2880 } else {
2881 bits[Character.toLowerCase((char)c)] = true;
2882 bits[Character.toUpperCase((char)c)] = true;
2883 }
2884 return this;
2885 }
2886 boolean isSatisfiedBy(int ch) {
2887 return ch > 255 ? false : bits[ch];
2888 }
2889 }
2890
2891 /**
2892 * Returns a suitably optimized, single character matcher.
2893 */
2894 private CharProperty newSingle(final int ch) {
2895 if (has(UNICODE_CASE)) {
2896 // Case independent unicode
2897 final int d = Character.toLowerCase(Character.toUpperCase(ch));
2898 return new CharProperty() {
2899 boolean isSatisfiedBy(int c) {
2900 return c == d ||
2901 Character.toLowerCase(
2902 Character.toUpperCase(c)) == d; }};
2903 } else if (has(CASE_INSENSITIVE) && ASCII.isAscii(ch)) {
2904 // Case independent ASCII characters
2905 final int d = ASCII.toLower(ch);
2906 return new BmpCharProperty() {
2907 boolean isSatisfiedBy(int c) {
2908 return c == d || ASCII.toLower(c) == d; }};
2909 } else if (isSupplementary(ch)) {
2910 // Match a given Unicode character
2911 return new CharProperty() {
2912 boolean isSatisfiedBy(int c) { return ch == c; }};
2913 } else {
2914 // Optimization -- match a given BMP character
2915 return new BmpCharProperty() {
2916 boolean isSatisfiedBy(int c) { return ch == c; }};
2917 }
2918 }
2919
2920 /**
2921 * Utility method for creating a string slice matcher.
2922 */
2923 private Node newSlice(int[] buf, int count, boolean hasSupplementary) {
2924 int[] tmp = new int[count];
2925 int i = flags;
2926 if ((i & (CASE_INSENSITIVE|UNICODE_CASE)) == 0) {
2927 for (i = 0; i < count; i++) {
2928 tmp[i] = buf[i];
2929 }
2930 return hasSupplementary ? new SliceS(tmp) : new Slice(tmp);
2931 } else if ((i & UNICODE_CASE) == 0) {
2932 for (i = 0; i < count; i++) {
2933 tmp[i] = (char)ASCII.toLower(buf[i]);
2934 }
2935 return new SliceA(tmp);
2936 } else {
2937 for (i = 0; i < count; i++) {
2938 int c = buf[i];
2939 c = Character.toUpperCase(c);
2940 c = Character.toLowerCase(c);
2941 tmp[i] = c;
2942 }
2943 return new SliceU(tmp);
2944 }
2945 }
2946
2947 /**
2948 * The following classes are the building components of the object
2949 * tree that represents a compiled regular expression. The object tree
2950 * is made of individual elements that handle constructs in the Pattern.
2951 * Each type of object knows how to match its equivalent construct with
2952 * the match() method.
2953 */
2954
2955 /**
2956 * Base class for all node classes. Subclasses should override the match()
2957 * method as appropriate. This class is an accepting node, so its match()
2958 * always returns true.
2959 */
2960 static class Node extends Object {
2961 Node next;
2962 Node() {
2963 next = Pattern.accept;
2964 }
2965 /**
2966 * This method implements the classic accept node.
2967 */
2968 boolean match(Matcher matcher, int i, CharSequence seq) {
2969 matcher.last = i;
2970 matcher.groups[0] = matcher.first;
2971 matcher.groups[1] = matcher.last;
2972 return true;
2973 }
2974 /**
2975 * This method is good for all zero length assertions.
2976 */
2977 boolean study(TreeInfo info) {
2978 if (next != null) {
2979 return next.study(info);
2980 } else {
2981 return info.deterministic;
2982 }
2983 }
2984 }
2985
2986 static class LastNode extends Node {
2987 /**
2988 * This method implements the classic accept node with
2989 * the addition of a check to see if the match occurred
2990 * using all of the input.
2991 */
2992 boolean match(Matcher matcher, int i, CharSequence seq) {
2993 if (matcher.acceptMode == Matcher.ENDANCHOR && i != matcher.to)
2994 return false;
2995 matcher.last = i;
2996 matcher.groups[0] = matcher.first;
2997 matcher.groups[1] = matcher.last;
2998 return true;
2999 }
3000 }
3001
3002 /**
3003 * Used for REs that can start anywhere within the input string.
3004 * This basically tries to match repeatedly at each spot in the
3005 * input string, moving forward after each try. An anchored search
3006 * or a BnM will bypass this node completely.
3007 */
3008 static class Start extends Node {
3009 int minLength;
3010 Start(Node node) {
3011 this.next = node;
3012 TreeInfo info = new TreeInfo();
3013 next.study(info);
3014 minLength = info.minLength;
3015 }
3016 boolean match(Matcher matcher, int i, CharSequence seq) {
3017 if (i > matcher.to - minLength) {
3018 matcher.hitEnd = true;
3019 return false;
3020 }
3021 boolean ret = false;
3022 int guard = matcher.to - minLength;
3023 for (; i <= guard; i++) {
3024 if (ret = next.match(matcher, i, seq))
3025 break;
3026 if (i == guard)
3027 matcher.hitEnd = true;
3028 }
3029 if (ret) {
3030 matcher.first = i;
3031 matcher.groups[0] = matcher.first;
3032 matcher.groups[1] = matcher.last;
3033 }
3034 return ret;
3035 }
3036 boolean study(TreeInfo info) {
3037 next.study(info);
3038 info.maxValid = false;
3039 info.deterministic = false;
3040 return false;
3041 }
3042 }
3043
3044 /*
3045 * StartS supports supplementary characters, including unpaired surrogates.
3046 */
3047 static final class StartS extends Start {
3048 StartS(Node node) {
3049 super(node);
3050 }
3051 boolean match(Matcher matcher, int i, CharSequence seq) {
3052 if (i > matcher.to - minLength) {
3053 matcher.hitEnd = true;
3054 return false;
3055 }
3056 boolean ret = false;
3057 int guard = matcher.to - minLength;
3058 while (i <= guard) {
3059 if ((ret = next.match(matcher, i, seq)) || i == guard)
3060 break;
3061 // Optimization to move to the next character. This is
3062 // faster than countChars(seq, i, 1).
3063 if (Character.isHighSurrogate(seq.charAt(i++))) {
3064 if (i < seq.length() && Character.isLowSurrogate(seq.charAt(i))) {
3065 i++;
3066 }
3067 }
3068 if (i == guard)
3069 matcher.hitEnd = true;
3070 }
3071 if (ret) {
3072 matcher.first = i;
3073 matcher.groups[0] = matcher.first;
3074 matcher.groups[1] = matcher.last;
3075 }
3076 return ret;
3077 }
3078 }
3079
3080 /**
3081 * Node to anchor at the beginning of input. This object implements the
3082 * match for a \A sequence, and the caret anchor will use this if not in
3083 * multiline mode.
3084 */
3085 static final class Begin extends Node {
3086 boolean match(Matcher matcher, int i, CharSequence seq) {
3087 int fromIndex = (matcher.anchoringBounds) ?
3088 matcher.from : 0;
3089 if (i == fromIndex && next.match(matcher, i, seq)) {
3090 matcher.first = i;
3091 matcher.groups[0] = i;
3092 matcher.groups[1] = matcher.last;
3093 return true;
3094 } else {
3095 return false;
3096 }
3097 }
3098 }
3099
3100 /**
3101 * Node to anchor at the end of input. This is the absolute end, so this
3102 * should not match at the last newline before the end as $ will.
3103 */
3104 static final class End extends Node {
3105 boolean match(Matcher matcher, int i, CharSequence seq) {
3106 int endIndex = (matcher.anchoringBounds) ?
3107 matcher.to : matcher.getTextLength();
3108 if (i == endIndex) {
3109 matcher.hitEnd = true;
3110 return next.match(matcher, i, seq);
3111 }
3112 return false;
3113 }
3114 }
3115
3116 /**
3117 * Node to anchor at the beginning of a line. This is essentially the
3118 * object to match for the multiline ^.
3119 */
3120 static final class Caret extends Node {
3121 boolean match(Matcher matcher, int i, CharSequence seq) {
3122 int startIndex = matcher.from;
3123 int endIndex = matcher.to;
3124 if (!matcher.anchoringBounds) {
3125 startIndex = 0;
3126 endIndex = matcher.getTextLength();
3127 }
3128 // Perl does not match ^ at end of input even after newline
3129 if (i == endIndex) {
3130 matcher.hitEnd = true;
3131 return false;
3132 }
3133 if (i > startIndex) {
3134 char ch = seq.charAt(i-1);
3135 if (ch != '\n' && ch != '\r'
3136 && (ch|1) != '\u2029'
3137 && ch != '\u0085' ) {
3138 return false;
3139 }
3140 // Should treat /r/n as one newline
3141 if (ch == '\r' && seq.charAt(i) == '\n')
3142 return false;
3143 }
3144 return next.match(matcher, i, seq);
3145 }
3146 }
3147
3148 /**
3149 * Node to anchor at the beginning of a line when in unixdot mode.
3150 */
3151 static final class UnixCaret extends Node {
3152 boolean match(Matcher matcher, int i, CharSequence seq) {
3153 int startIndex = matcher.from;
3154 int endIndex = matcher.to;
3155 if (!matcher.anchoringBounds) {
3156 startIndex = 0;
3157 endIndex = matcher.getTextLength();
3158 }
3159 // Perl does not match ^ at end of input even after newline
3160 if (i == endIndex) {
3161 matcher.hitEnd = true;
3162 return false;
3163 }
3164 if (i > startIndex) {
3165 char ch = seq.charAt(i-1);
3166 if (ch != '\n') {
3167 return false;
3168 }
3169 }
3170 return next.match(matcher, i, seq);
3171 }
3172 }
3173
3174 /**
3175 * Node to match the location where the last match ended.
3176 * This is used for the \G construct.
3177 */
3178 static final class LastMatch extends Node {
3179 boolean match(Matcher matcher, int i, CharSequence seq) {
3180 if (i != matcher.oldLast)
3181 return false;
3182 return next.match(matcher, i, seq);
3183 }
3184 }
3185
3186 /**
3187 * Node to anchor at the end of a line or the end of input based on the
3188 * multiline mode.
3189 *
3190 * When not in multiline mode, the $ can only match at the very end
3191 * of the input, unless the input ends in a line terminator in which
3192 * it matches right before the last line terminator.
3193 *
3194 * Note that \r\n is considered an atomic line terminator.
3195 *
3196 * Like ^ the $ operator matches at a position, it does not match the
3197 * line terminators themselves.
3198 */
3199 static final class Dollar extends Node {
3200 boolean multiline;
3201 Dollar(boolean mul) {
3202 multiline = mul;
3203 }
3204 boolean match(Matcher matcher, int i, CharSequence seq) {
3205 int endIndex = (matcher.anchoringBounds) ?
3206 matcher.to : matcher.getTextLength();
3207 if (!multiline) {
3208 if (i < endIndex - 2)
3209 return false;
3210 if (i == endIndex - 2) {
3211 char ch = seq.charAt(i);
3212 if (ch != '\r')
3213 return false;
3214 ch = seq.charAt(i + 1);
3215 if (ch != '\n')
3216 return false;
3217 }
3218 }
3219 // Matches before any line terminator; also matches at the
3220 // end of input
3221 // Before line terminator:
3222 // If multiline, we match here no matter what
3223 // If not multiline, fall through so that the end
3224 // is marked as hit; this must be a /r/n or a /n
3225 // at the very end so the end was hit; more input
3226 // could make this not match here
3227 if (i < endIndex) {
3228 char ch = seq.charAt(i);
3229 if (ch == '\n') {
3230 // No match between \r\n
3231 if (i > 0 && seq.charAt(i-1) == '\r')
3232 return false;
3233 if (multiline)
3234 return next.match(matcher, i, seq);
3235 } else if (ch == '\r' || ch == '\u0085' ||
3236 (ch|1) == '\u2029') {
3237 if (multiline)
3238 return next.match(matcher, i, seq);
3239 } else { // No line terminator, no match
3240 return false;
3241 }
3242 }
3243 // Matched at current end so hit end
3244 matcher.hitEnd = true;
3245 // If a $ matches because of end of input, then more input
3246 // could cause it to fail!
3247 matcher.requireEnd = true;
3248 return next.match(matcher, i, seq);
3249 }
3250 boolean study(TreeInfo info) {
3251 next.study(info);
3252 return info.deterministic;
3253 }
3254 }
3255
3256 /**
3257 * Node to anchor at the end of a line or the end of input based on the
3258 * multiline mode when in unix lines mode.
3259 */
3260 static final class UnixDollar extends Node {
3261 boolean multiline;
3262 UnixDollar(boolean mul) {
3263 multiline = mul;
3264 }
3265 boolean match(Matcher matcher, int i, CharSequence seq) {
3266 int endIndex = (matcher.anchoringBounds) ?
3267 matcher.to : matcher.getTextLength();
3268 if (i < endIndex) {
3269 char ch = seq.charAt(i);
3270 if (ch == '\n') {
3271 // If not multiline, then only possible to
3272 // match at very end or one before end
3273 if (multiline == false && i != endIndex - 1)
3274 return false;
3275 // If multiline return next.match without setting
3276 // matcher.hitEnd
3277 if (multiline)
3278 return next.match(matcher, i, seq);
3279 } else {
3280 return false;
3281 }
3282 }
3283 // Matching because at the end or 1 before the end;
3284 // more input could change this so set hitEnd
3285 matcher.hitEnd = true;
3286 // If a $ matches because of end of input, then more input
3287 // could cause it to fail!
3288 matcher.requireEnd = true;
3289 return next.match(matcher, i, seq);
3290 }
3291 boolean study(TreeInfo info) {
3292 next.study(info);
3293 return info.deterministic;
3294 }
3295 }
3296
3297 /**
3298 * Abstract node class to match one character satisfying some
3299 * boolean property.
3300 */
3301 private static abstract class CharProperty extends Node {
3302 abstract boolean isSatisfiedBy(int ch);
3303 CharProperty complement() {
3304 return new CharProperty() {
3305 boolean isSatisfiedBy(int ch) {
3306 return ! CharProperty.this.isSatisfiedBy(ch);}};
3307 }
3308 CharProperty maybeComplement(boolean complement) {
3309 return complement ? complement() : this;
3310 }
3311 boolean match(Matcher matcher, int i, CharSequence seq) {
3312 if (i < matcher.to) {
3313 int ch = Character.codePointAt(seq, i);
3314 return isSatisfiedBy(ch)
3315 && next.match(matcher, i+Character.charCount(ch), seq);
3316 } else {
3317 matcher.hitEnd = true;
3318 return false;
3319 }
3320 }
3321 boolean study(TreeInfo info) {
3322 info.minLength++;
3323 info.maxLength++;
3324 return next.study(info);
3325 }
3326 }
3327
3328 /**
3329 * Optimized version of CharProperty that works only for
3330 * properties never satisfied by Supplementary characters.
3331 */
3332 private static abstract class BmpCharProperty extends CharProperty {
3333 boolean match(Matcher matcher, int i, CharSequence seq) {
3334 if (i < matcher.to) {
3335 return isSatisfiedBy(seq.charAt(i))
3336 && next.match(matcher, i+1, seq);
3337 } else {
3338 matcher.hitEnd = true;
3339 return false;
3340 }
3341 }
3342 }
3343
3344 /**
3345 * Node class that matches a Unicode category.
3346 */
3347 static final class Category extends CharProperty {
3348 final int typeMask;
3349 Category(int typeMask) { this.typeMask = typeMask; }
3350 boolean isSatisfiedBy(int ch) {
3351 return (typeMask & (1 << Character.getType(ch))) != 0;
3352 }
3353 }
3354
3355 /**
3356 * Node class that matches a POSIX type.
3357 */
3358 static final class Ctype extends BmpCharProperty {
3359 final int ctype;
3360 Ctype(int ctype) { this.ctype = ctype; }
3361 boolean isSatisfiedBy(int ch) {
3362 return ch < 128 && ASCII.isType(ch, ctype);
3363 }
3364 }
3365
3366 /**
3367 * Node class for a case sensitive sequence of literal characters.
3368 */
3369 static class Slice extends Node {
3370 int[] buffer;
3371 Slice(int[] buf) {
3372 buffer = buf;
3373 }
3374 boolean match(Matcher matcher, int i, CharSequence seq) {
3375 int[] buf = buffer;
3376 int len = buf.length;
3377
3378 // Unfortunately we must now void this opto
3379 // in order to properly report hitEnd...
3380 //if (i + len > matcher.to) {
3381 // matcher.hitEnd = true;
3382 // return false;
3383 //}
3384
3385 for (int j=0; j<len; j++) {
3386 if ((i+j) >= matcher.to) {
3387 matcher.hitEnd = true;
3388 return false;
3389 }
3390 if (buf[j] != seq.charAt(i+j))
3391 return false;
3392 }
3393
3394 return next.match(matcher, i+len, seq);
3395 }
3396 boolean study(TreeInfo info) {
3397 info.minLength += buffer.length;
3398 info.maxLength += buffer.length;
3399 return next.study(info);
3400 }
3401 }
3402
3403 /**
3404 * Node class for a case insensitive sequence of literal characters.
3405 */
3406 static final class SliceA extends Node {
3407 int[] buffer;
3408 SliceA(int[] buf) {
3409 buffer = buf;
3410 }
3411 boolean match(Matcher matcher, int i, CharSequence seq) {
3412 int[] buf = buffer;
3413 int len = buf.length;
3414 for (int j=0; j<len; j++) {
3415 if ((i+j) >= matcher.to) {
3416 matcher.hitEnd = true;
3417 return false;
3418 }
3419 int c = ASCII.toLower(seq.charAt(i+j));
3420 if (buf[j] != c)
3421 return false;
3422 }
3423 return next.match(matcher, i+len, seq);
3424 }
3425 boolean study(TreeInfo info) {
3426 info.minLength += buffer.length;
3427 info.maxLength += buffer.length;
3428 return next.study(info);
3429 }
3430 }
3431
3432 /**
3433 * Node class for a case insensitive sequence of literal characters.
3434 * Uses unicode case folding.
3435 */
3436 static final class SliceU extends Node {
3437 int[] buffer;
3438 SliceU(int[] buf) {
3439 buffer = buf;
3440 }
3441 boolean match(Matcher matcher, int i, CharSequence seq) {
3442 int[] buf = buffer;
3443 int x = i;
3444 for (int j = 0; j < buf.length; j++) {
3445 if (x >= matcher.to) {
3446 matcher.hitEnd = true;
3447 return false;
3448 }
3449 int c = Character.codePointAt(seq, x);
3450 int cc = Character.toUpperCase(c);
3451 cc = Character.toLowerCase(cc);
3452 if (buf[j] != cc) {
3453 return false;
3454 }
3455 x += Character.charCount(c);
3456 if (x > matcher.to) {
3457 matcher.hitEnd = true;
3458 return false;
3459 }
3460 }
3461 return next.match(matcher, x, seq);
3462 }
3463 boolean study(TreeInfo info) {
3464 info.minLength += buffer.length;
3465 info.maxLength += buffer.length;
3466 return next.study(info);
3467 }
3468 }
3469
3470 /**
3471 * Node class for a case sensitive sequence of literal characters
3472 * including supplementary characters.
3473 */
3474 static final class SliceS extends Slice {
3475 SliceS(int[] buf) {
3476 super(buf);
3477 }
3478 boolean match(Matcher matcher, int i, CharSequence seq) {
3479 int[] buf = buffer;
3480 int x = i;
3481 for (int j = 0; j < buf.length; j++) {
3482 if (x >= matcher.to) {
3483 matcher.hitEnd = true;
3484 return false;
3485 }
3486 int c = Character.codePointAt(seq, x);
3487 if (buf[j] != c)
3488 return false;
3489 x += Character.charCount(c);
3490 if (x > matcher.to) {
3491 matcher.hitEnd = true;
3492 return false;
3493 }
3494 }
3495
3496 return next.match(matcher, x, seq);
3497 }
3498 }
3499
3500 private static boolean inRange(int lower, int ch, int upper) {
3501 return lower <= ch && ch <= upper;
3502 }
3503
3504 /**
3505 * Node class for matching characters within an explicit value range.
3506 */
3507
3508 /**
3509 * Returns node for matching characters within an explicit value range.
3510 */
3511 private static CharProperty rangeFor(final int lower,
3512 final int upper) {
3513 return new CharProperty() {
3514 boolean isSatisfiedBy(int ch) {
3515 return inRange(lower, ch, upper);}};
3516 }
3517
3518 /**
3519 * Returns node for matching characters within an explicit value
3520 * range in a case insensitive manner.
3521 */
3522 private static CharProperty caseInsensitiveRangeFor(final int lower,
3523 final int upper) {
3524 return new CharProperty() {
3525 boolean isSatisfiedBy(int ch) {
3526 return inRange(lower, ch, upper) ||
3527 inRange(lower, Character.toUpperCase(ch), upper) ||
3528 inRange(lower, Character.toLowerCase(ch), upper);}};
3529 }
3530
3531 /**
3532 * Implements the Unicode category ALL and the dot metacharacter when
3533 * in dotall mode.
3534 */
3535 static final class All extends CharProperty {
3536 boolean isSatisfiedBy(int ch) {
3537 return true;
3538 }
3539 }
3540
3541 /**
3542 * Node class for the dot metacharacter when dotall is not enabled.
3543 */
3544 static final class Dot extends CharProperty {
3545 boolean isSatisfiedBy(int ch) {
3546 return (ch != '\n' && ch != '\r'
3547 && (ch|1) != '\u2029'
3548 && ch != '\u0085');
3549 }
3550 }
3551
3552 /**
3553 * Node class for the dot metacharacter when dotall is not enabled
3554 * but UNIX_LINES is enabled.
3555 */
3556 static final class UnixDot extends CharProperty {
3557 boolean isSatisfiedBy(int ch) {
3558 return ch != '\n';
3559 }
3560 }
3561
3562 /**
3563 * The 0 or 1 quantifier. This one class implements all three types.
3564 */
3565 static final class Ques extends Node {
3566 Node atom;
3567 int type;
3568 Ques(Node node, int type) {
3569 this.atom = node;
3570 this.type = type;
3571 }
3572 boolean match(Matcher matcher, int i, CharSequence seq) {
3573 switch (type) {
3574 case GREEDY:
3575 return (atom.match(matcher, i, seq) && next.match(matcher, matcher.last, seq))
3576 || next.match(matcher, i, seq);
3577 case LAZY:
3578 return next.match(matcher, i, seq)
3579 || (atom.match(matcher, i, seq) && next.match(matcher, matcher.last, seq));
3580 case POSSESSIVE:
3581 if (atom.match(matcher, i, seq)) i = matcher.last;
3582 return next.match(matcher, i, seq);
3583 default:
3584 return atom.match(matcher, i, seq) && next.match(matcher, matcher.last, seq);
3585 }
3586 }
3587 boolean study(TreeInfo info) {
3588 if (type != INDEPENDENT) {
3589 int minL = info.minLength;
3590 atom.study(info);
3591 info.minLength = minL;
3592 info.deterministic = false;
3593 return next.study(info);
3594 } else {
3595 atom.study(info);
3596 return next.study(info);
3597 }
3598 }
3599 }
3600
3601 /**
3602 * Handles the curly-brace style repetition with a specified minimum and
3603 * maximum occurrences. The * quantifier is handled as a special case.
3604 * This class handles the three types.
3605 */
3606 static final class Curly extends Node {
3607 Node atom;
3608 int type;
3609 int cmin;
3610 int cmax;
3611
3612 Curly(Node node, int cmin, int cmax, int type) {
3613 this.atom = node;
3614 this.type = type;
3615 this.cmin = cmin;
3616 this.cmax = cmax;
3617 }
3618 boolean match(Matcher matcher, int i, CharSequence seq) {
3619 int j;
3620 for (j = 0; j < cmin; j++) {
3621 if (atom.match(matcher, i, seq)) {
3622 i = matcher.last;
3623 continue;
3624 }
3625 return false;
3626 }
3627 if (type == GREEDY)
3628 return match0(matcher, i, j, seq);
3629 else if (type == LAZY)
3630 return match1(matcher, i, j, seq);
3631 else
3632 return match2(matcher, i, j, seq);
3633 }
3634 // Greedy match.
3635 // i is the index to start matching at
3636 // j is the number of atoms that have matched
3637 boolean match0(Matcher matcher, int i, int j, CharSequence seq) {
3638 if (j >= cmax) {
3639 // We have matched the maximum... continue with the rest of
3640 // the regular expression
3641 return next.match(matcher, i, seq);
3642 }
3643 int backLimit = j;
3644 while (atom.match(matcher, i, seq)) {
3645 // k is the length of this match
3646 int k = matcher.last - i;
3647 if (k == 0) // Zero length match
3648 break;
3649 // Move up index and number matched
3650 i = matcher.last;
3651 j++;
3652 // We are greedy so match as many as we can
3653 while (j < cmax) {
3654 if (!atom.match(matcher, i, seq))
3655 break;
3656 if (i + k != matcher.last) {
3657 if (match0(matcher, matcher.last, j+1, seq))
3658 return true;
3659 break;
3660 }
3661 i += k;
3662 j++;
3663 }
3664 // Handle backing off if match fails
3665 while (j >= backLimit) {
3666 if (next.match(matcher, i, seq))
3667 return true;
3668 i -= k;
3669 j--;
3670 }
3671 return false;
3672 }
3673 return next.match(matcher, i, seq);
3674 }
3675 // Reluctant match. At this point, the minimum has been satisfied.
3676 // i is the index to start matching at
3677 // j is the number of atoms that have matched
3678 boolean match1(Matcher matcher, int i, int j, CharSequence seq) {
3679 for (;;) {
3680 // Try finishing match without consuming any more
3681 if (next.match(matcher, i, seq))
3682 return true;
3683 // At the maximum, no match found
3684 if (j >= cmax)
3685 return false;
3686 // Okay, must try one more atom
3687 if (!atom.match(matcher, i, seq))
3688 return false;
3689 // If we haven't moved forward then must break out
3690 if (i == matcher.last)
3691 return false;
3692 // Move up index and number matched
3693 i = matcher.last;
3694 j++;
3695 }
3696 }
3697 boolean match2(Matcher matcher, int i, int j, CharSequence seq) {
3698 for (; j < cmax; j++) {
3699 if (!atom.match(matcher, i, seq))
3700 break;
3701 if (i == matcher.last)
3702 break;
3703 i = matcher.last;
3704 }
3705 return next.match(matcher, i, seq);
3706 }
3707 boolean study(TreeInfo info) {
3708 // Save original info
3709 int minL = info.minLength;
3710 int maxL = info.maxLength;
3711 boolean maxV = info.maxValid;
3712 boolean detm = info.deterministic;
3713 info.reset();
3714
3715 atom.study(info);
3716
3717 int temp = info.minLength * cmin + minL;
3718 if (temp < minL) {
3719 temp = 0xFFFFFFF; // arbitrary large number
3720 }
3721 info.minLength = temp;
3722
3723 if (maxV & info.maxValid) {
3724 temp = info.maxLength * cmax + maxL;
3725 info.maxLength = temp;
3726 if (temp < maxL) {
3727 info.maxValid = false;
3728 }
3729 } else {
3730 info.maxValid = false;
3731 }
3732
3733 if (info.deterministic && cmin == cmax)
3734 info.deterministic = detm;
3735 else
3736 info.deterministic = false;
3737
3738 return next.study(info);
3739 }
3740 }
3741
3742 /**
3743 * Handles the curly-brace style repetition with a specified minimum and
3744 * maximum occurrences in deterministic cases. This is an iterative
3745 * optimization over the Prolog and Loop system which would handle this
3746 * in a recursive way. The * quantifier is handled as a special case.
3747 * If capture is true then this class saves group settings and ensures
3748 * that groups are unset when backing off of a group match.
3749 */
3750 static final class GroupCurly extends Node {
3751 Node atom;
3752 int type;
3753 int cmin;
3754 int cmax;
3755 int localIndex;
3756 int groupIndex;
3757 boolean capture;
3758
3759 GroupCurly(Node node, int cmin, int cmax, int type, int local,
3760 int group, boolean capture) {
3761 this.atom = node;
3762 this.type = type;
3763 this.cmin = cmin;
3764 this.cmax = cmax;
3765 this.localIndex = local;
3766 this.groupIndex = group;
3767 this.capture = capture;
3768 }
3769 boolean match(Matcher matcher, int i, CharSequence seq) {
3770 int[] groups = matcher.groups;
3771 int[] locals = matcher.locals;
3772 int save0 = locals[localIndex];
3773 int save1 = 0;
3774 int save2 = 0;
3775
3776 if (capture) {
3777 save1 = groups[groupIndex];
3778 save2 = groups[groupIndex+1];
3779 }
3780
3781 // Notify GroupTail there is no need to setup group info
3782 // because it will be set here
3783 locals[localIndex] = -1;
3784
3785 boolean ret = true;
3786 for (int j = 0; j < cmin; j++) {
3787 if (atom.match(matcher, i, seq)) {
3788 if (capture) {
3789 groups[groupIndex] = i;
3790 groups[groupIndex+1] = matcher.last;
3791 }
3792 i = matcher.last;
3793 } else {
3794 ret = false;
3795 break;
3796 }
3797 }
3798 if (!ret) {
3799 locals[localIndex] = save0;
3800 if (capture) {
3801 groups[groupIndex] = save1;
3802 groups[groupIndex+1] = save2;
3803 }
3804 } else if (type == GREEDY) {
3805 ret = match0(matcher, i, cmin, seq);
3806 } else if (type == LAZY) {
3807 ret = match1(matcher, i, cmin, seq);
3808 } else {
3809 ret = match2(matcher, i, cmin, seq);
3810 }
3811 return ret;
3812 }
3813 // Aggressive group match
3814 boolean match0(Matcher matcher, int i, int j, CharSequence seq) {
3815 int[] groups = matcher.groups;
3816 int save0 = 0;
3817 int save1 = 0;
3818 if (capture) {
3819 save0 = groups[groupIndex];
3820 save1 = groups[groupIndex+1];
3821 }
3822 for (;;) {
3823 if (j >= cmax)
3824 break;
3825 if (!atom.match(matcher, i, seq))
3826 break;
3827 int k = matcher.last - i;
3828 if (k <= 0) {
3829 if (capture) {
3830 groups[groupIndex] = i;
3831 groups[groupIndex+1] = i + k;
3832 }
3833 i = i + k;
3834 break;
3835 }
3836 for (;;) {
3837 if (capture) {
3838 groups[groupIndex] = i;
3839 groups[groupIndex+1] = i + k;
3840 }
3841 i = i + k;
3842 if (++j >= cmax)
3843 break;
3844 if (!atom.match(matcher, i, seq))
3845 break;
3846 if (i + k != matcher.last) {
3847 if (match0(matcher, i, j, seq))
3848 return true;
3849 break;
3850 }
3851 }
3852 while (j > cmin) {
3853 if (next.match(matcher, i, seq)) {
3854 if (capture) {
3855 groups[groupIndex+1] = i;
3856 groups[groupIndex] = i - k;
3857 }
3858 i = i - k;
3859 return true;
3860 }
3861 // backing off
3862 if (capture) {
3863 groups[groupIndex+1] = i;
3864 groups[groupIndex] = i - k;
3865 }
3866 i = i - k;
3867 j--;
3868 }
3869 break;
3870 }
3871 if (capture) {
3872 groups[groupIndex] = save0;
3873 groups[groupIndex+1] = save1;
3874 }
3875 return next.match(matcher, i, seq);
3876 }
3877 // Reluctant matching
3878 boolean match1(Matcher matcher, int i, int j, CharSequence seq) {
3879 for (;;) {
3880 if (next.match(matcher, i, seq))
3881 return true;
3882 if (j >= cmax)
3883 return false;
3884 if (!atom.match(matcher, i, seq))
3885 return false;
3886 if (i == matcher.last)
3887 return false;
3888 if (capture) {
3889 matcher.groups[groupIndex] = i;
3890 matcher.groups[groupIndex+1] = matcher.last;
3891 }
3892 i = matcher.last;
3893 j++;
3894 }
3895 }
3896 // Possessive matching
3897 boolean match2(Matcher matcher, int i, int j, CharSequence seq) {
3898 for (; j < cmax; j++) {
3899 if (!atom.match(matcher, i, seq)) {
3900 break;
3901 }
3902 if (capture) {
3903 matcher.groups[groupIndex] = i;
3904 matcher.groups[groupIndex+1] = matcher.last;
3905 }
3906 if (i == matcher.last) {
3907 break;
3908 }
3909 i = matcher.last;
3910 }
3911 return next.match(matcher, i, seq);
3912 }
3913 boolean study(TreeInfo info) {
3914 // Save original info
3915 int minL = info.minLength;
3916 int maxL = info.maxLength;
3917 boolean maxV = info.maxValid;
3918 boolean detm = info.deterministic;
3919 info.reset();
3920
3921 atom.study(info);
3922
3923 int temp = info.minLength * cmin + minL;
3924 if (temp < minL) {
3925 temp = 0xFFFFFFF; // Arbitrary large number
3926 }
3927 info.minLength = temp;
3928
3929 if (maxV & info.maxValid) {
3930 temp = info.maxLength * cmax + maxL;
3931 info.maxLength = temp;
3932 if (temp < maxL) {
3933 info.maxValid = false;
3934 }
3935 } else {
3936 info.maxValid = false;
3937 }
3938
3939 if (info.deterministic && cmin == cmax) {
3940 info.deterministic = detm;
3941 } else {
3942 info.deterministic = false;
3943 }
3944
3945 return next.study(info);
3946 }
3947 }
3948
3949 /**
3950 * A Guard node at the end of each atom node in a Branch. It
3951 * serves the purpose of chaining the "match" operation to
3952 * "next" but not the "study", so we can collect the TreeInfo
3953 * of each atom node without including the TreeInfo of the
3954 * "next".
3955 */
3956 static final class BranchConn extends Node {
3957 BranchConn() {};
3958 boolean match(Matcher matcher, int i, CharSequence seq) {
3959 return next.match(matcher, i, seq);
3960 }
3961 boolean study(TreeInfo info) {
3962 return info.deterministic;
3963 }
3964 }
3965
3966 /**
3967 * Handles the branching of alternations. Note this is also used for
3968 * the ? quantifier to branch between the case where it matches once
3969 * and where it does not occur.
3970 */
3971 static final class Branch extends Node {
3972 Node[] atoms = new Node[2];
3973 int size = 2;
3974 Node conn;
3975 Branch(Node first, Node second, Node branchConn) {
3976 conn = branchConn;
3977 atoms[0] = first;
3978 atoms[1] = second;
3979 }
3980
3981 void add(Node node) {
3982 if (size >= atoms.length) {
3983 Node[] tmp = new Node[atoms.length*2];
3984 System.arraycopy(atoms, 0, tmp, 0, atoms.length);
3985 atoms = tmp;
3986 }
3987 atoms[size++] = node;
3988 }
3989
3990 boolean match(Matcher matcher, int i, CharSequence seq) {
3991 for (int n = 0; n < size; n++) {
3992 if (atoms[n] == null) {
3993 if (conn.next.match(matcher, i, seq))
3994 return true;
3995 } else if (atoms[n].match(matcher, i, seq)) {
3996 return true;
3997 }
3998 }
3999 return false;
4000 }
4001
4002 boolean study(TreeInfo info) {
4003 int minL = info.minLength;
4004 int maxL = info.maxLength;
4005 boolean maxV = info.maxValid;
4006
4007 int minL2 = Integer.MAX_VALUE; //arbitrary large enough num
4008 int maxL2 = -1;
4009 for (int n = 0; n < size; n++) {
4010 info.reset();
4011 if (atoms[n] != null)
4012 atoms[n].study(info);
4013 minL2 = Math.min(minL2, info.minLength);
4014 maxL2 = Math.max(maxL2, info.maxLength);
4015 maxV = (maxV & info.maxValid);
4016 }
4017
4018 minL += minL2;
4019 maxL += maxL2;
4020
4021 info.reset();
4022 conn.next.study(info);
4023
4024 info.minLength += minL;
4025 info.maxLength += maxL;
4026 info.maxValid &= maxV;
4027 info.deterministic = false;
4028 return false;
4029 }
4030 }
4031
4032 /**
4033 * The GroupHead saves the location where the group begins in the locals
4034 * and restores them when the match is done.
4035 *
4036 * The matchRef is used when a reference to this group is accessed later
4037 * in the expression. The locals will have a negative value in them to
4038 * indicate that we do not want to unset the group if the reference
4039 * doesn't match.
4040 */
4041 static final class GroupHead extends Node {
4042 int localIndex;
4043 GroupHead(int localCount) {
4044 localIndex = localCount;
4045 }
4046 boolean match(Matcher matcher, int i, CharSequence seq) {
4047 int save = matcher.locals[localIndex];
4048 matcher.locals[localIndex] = i;
4049 boolean ret = next.match(matcher, i, seq);
4050 matcher.locals[localIndex] = save;
4051 return ret;
4052 }
4053 boolean matchRef(Matcher matcher, int i, CharSequence seq) {
4054 int save = matcher.locals[localIndex];
4055 matcher.locals[localIndex] = ~i; // HACK
4056 boolean ret = next.match(matcher, i, seq);
4057 matcher.locals[localIndex] = save;
4058 return ret;
4059 }
4060 }
4061
4062 /**
4063 * Recursive reference to a group in the regular expression. It calls
4064 * matchRef because if the reference fails to match we would not unset
4065 * the group.
4066 */
4067 static final class GroupRef extends Node {
4068 GroupHead head;
4069 GroupRef(GroupHead head) {
4070 this.head = head;
4071 }
4072 boolean match(Matcher matcher, int i, CharSequence seq) {
4073 return head.matchRef(matcher, i, seq)
4074 && next.match(matcher, matcher.last, seq);
4075 }
4076 boolean study(TreeInfo info) {
4077 info.maxValid = false;
4078 info.deterministic = false;
4079 return next.study(info);
4080 }
4081 }
4082
4083 /**
4084 * The GroupTail handles the setting of group beginning and ending
4085 * locations when groups are successfully matched. It must also be able to
4086 * unset groups that have to be backed off of.
4087 *
4088 * The GroupTail node is also used when a previous group is referenced,
4089 * and in that case no group information needs to be set.
4090 */
4091 static final class GroupTail extends Node {
4092 int localIndex;
4093 int groupIndex;
4094 GroupTail(int localCount, int groupCount) {
4095 localIndex = localCount;
4096 groupIndex = groupCount + groupCount;
4097 }
4098 boolean match(Matcher matcher, int i, CharSequence seq) {
4099 int tmp = matcher.locals[localIndex];
4100 if (tmp >= 0) { // This is the normal group case.
4101 // Save the group so we can unset it if it
4102 // backs off of a match.
4103 int groupStart = matcher.groups[groupIndex];
4104 int groupEnd = matcher.groups[groupIndex+1];
4105
4106 matcher.groups[groupIndex] = tmp;
4107 matcher.groups[groupIndex+1] = i;
4108 if (next.match(matcher, i, seq)) {
4109 return true;
4110 }
4111 matcher.groups[groupIndex] = groupStart;
4112 matcher.groups[groupIndex+1] = groupEnd;
4113 return false;
4114 } else {
4115 // This is a group reference case. We don't need to save any
4116 // group info because it isn't really a group.
4117 matcher.last = i;
4118 return true;
4119 }
4120 }
4121 }
4122
4123 /**
4124 * This sets up a loop to handle a recursive quantifier structure.
4125 */
4126 static final class Prolog extends Node {
4127 Loop loop;
4128 Prolog(Loop loop) {
4129 this.loop = loop;
4130 }
4131 boolean match(Matcher matcher, int i, CharSequence seq) {
4132 return loop.matchInit(matcher, i, seq);
4133 }
4134 boolean study(TreeInfo info) {
4135 return loop.study(info);
4136 }
4137 }
4138
4139 /**
4140 * Handles the repetition count for a greedy Curly. The matchInit
4141 * is called from the Prolog to save the index of where the group
4142 * beginning is stored. A zero length group check occurs in the
4143 * normal match but is skipped in the matchInit.
4144 */
4145 static class Loop extends Node {
4146 Node body;
4147 int countIndex; // local count index in matcher locals
4148 int beginIndex; // group beginning index
4149 int cmin, cmax;
4150 Loop(int countIndex, int beginIndex) {
4151 this.countIndex = countIndex;
4152 this.beginIndex = beginIndex;
4153 }
4154 boolean match(Matcher matcher, int i, CharSequence seq) {
4155 // Avoid infinite loop in zero-length case.
4156 if (i > matcher.locals[beginIndex]) {
4157 int count = matcher.locals[countIndex];
4158
4159 // This block is for before we reach the minimum
4160 // iterations required for the loop to match
4161 if (count < cmin) {
4162 matcher.locals[countIndex] = count + 1;
4163 boolean b = body.match(matcher, i, seq);
4164 // If match failed we must backtrack, so
4165 // the loop count should NOT be incremented
4166 if (!b)
4167 matcher.locals[countIndex] = count;
4168 // Return success or failure since we are under
4169 // minimum
4170 return b;
4171 }
4172 // This block is for after we have the minimum
4173 // iterations required for the loop to match
4174 if (count < cmax) {
4175 matcher.locals[countIndex] = count + 1;
4176 boolean b = body.match(matcher, i, seq);
4177 // If match failed we must backtrack, so
4178 // the loop count should NOT be incremented
4179 if (!b)
4180 matcher.locals[countIndex] = count;
4181 else
4182 return true;
4183 }
4184 }
4185 return next.match(matcher, i, seq);
4186 }
4187 boolean matchInit(Matcher matcher, int i, CharSequence seq) {
4188 int save = matcher.locals[countIndex];
4189 boolean ret = false;
4190 if (0 < cmin) {
4191 matcher.locals[countIndex] = 1;
4192 ret = body.match(matcher, i, seq);
4193 } else if (0 < cmax) {
4194 matcher.locals[countIndex] = 1;
4195 ret = body.match(matcher, i, seq);
4196 if (ret == false)
4197 ret = next.match(matcher, i, seq);
4198 } else {
4199 ret = next.match(matcher, i, seq);
4200 }
4201 matcher.locals[countIndex] = save;
4202 return ret;
4203 }
4204 boolean study(TreeInfo info) {
4205 info.maxValid = false;
4206 info.deterministic = false;
4207 return false;
4208 }
4209 }
4210
4211 /**
4212 * Handles the repetition count for a reluctant Curly. The matchInit
4213 * is called from the Prolog to save the index of where the group
4214 * beginning is stored. A zero length group check occurs in the
4215 * normal match but is skipped in the matchInit.
4216 */
4217 static final class LazyLoop extends Loop {
4218 LazyLoop(int countIndex, int beginIndex) {
4219 super(countIndex, beginIndex);
4220 }
4221 boolean match(Matcher matcher, int i, CharSequence seq) {
4222 // Check for zero length group
4223 if (i > matcher.locals[beginIndex]) {
4224 int count = matcher.locals[countIndex];
4225 if (count < cmin) {
4226 matcher.locals[countIndex] = count + 1;
4227 boolean result = body.match(matcher, i, seq);
4228 // If match failed we must backtrack, so
4229 // the loop count should NOT be incremented
4230 if (!result)
4231 matcher.locals[countIndex] = count;
4232 return result;
4233 }
4234 if (next.match(matcher, i, seq))
4235 return true;
4236 if (count < cmax) {
4237 matcher.locals[countIndex] = count + 1;
4238 boolean result = body.match(matcher, i, seq);
4239 // If match failed we must backtrack, so
4240 // the loop count should NOT be incremented
4241 if (!result)
4242 matcher.locals[countIndex] = count;
4243 return result;
4244 }
4245 return false;
4246 }
4247 return next.match(matcher, i, seq);
4248 }
4249 boolean matchInit(Matcher matcher, int i, CharSequence seq) {
4250 int save = matcher.locals[countIndex];
4251 boolean ret = false;
4252 if (0 < cmin) {
4253 matcher.locals[countIndex] = 1;
4254 ret = body.match(matcher, i, seq);
4255 } else if (next.match(matcher, i, seq)) {
4256 ret = true;
4257 } else if (0 < cmax) {
4258 matcher.locals[countIndex] = 1;
4259 ret = body.match(matcher, i, seq);
4260 }
4261 matcher.locals[countIndex] = save;
4262 return ret;
4263 }
4264 boolean study(TreeInfo info) {
4265 info.maxValid = false;
4266 info.deterministic = false;
4267 return false;
4268 }
4269 }
4270
4271 /**
4272 * Refers to a group in the regular expression. Attempts to match
4273 * whatever the group referred to last matched.
4274 */
4275 static class BackRef extends Node {
4276 int groupIndex;
4277 BackRef(int groupCount) {
4278 super();
4279 groupIndex = groupCount + groupCount;
4280 }
4281 boolean match(Matcher matcher, int i, CharSequence seq) {
4282 int j = matcher.groups[groupIndex];
4283 int k = matcher.groups[groupIndex+1];
4284
4285 int groupSize = k - j;
4286
4287 // If the referenced group didn't match, neither can this
4288 if (j < 0)
4289 return false;
4290
4291 // If there isn't enough input left no match
4292 if (i + groupSize > matcher.to) {
4293 matcher.hitEnd = true;
4294 return false;
4295 }
4296
4297 // Check each new char to make sure it matches what the group
4298 // referenced matched last time around
4299 for (int index=0; index<groupSize; index++)
4300 if (seq.charAt(i+index) != seq.charAt(j+index))
4301 return false;
4302
4303 return next.match(matcher, i+groupSize, seq);
4304 }
4305 boolean study(TreeInfo info) {
4306 info.maxValid = false;
4307 return next.study(info);
4308 }
4309 }
4310
4311 static class CIBackRef extends Node {
4312 int groupIndex;
4313 CIBackRef(int groupCount) {
4314 super();
4315 groupIndex = groupCount + groupCount;
4316 }
4317 boolean match(Matcher matcher, int i, CharSequence seq) {
4318 int j = matcher.groups[groupIndex];
4319 int k = matcher.groups[groupIndex+1];
4320
4321 int groupSize = k - j;
4322
4323 // If the referenced group didn't match, neither can this
4324 if (j < 0)
4325 return false;
4326
4327 // If there isn't enough input left no match
4328 if (i + groupSize > matcher.to) {
4329 matcher.hitEnd = true;
4330 return false;
4331 }
4332
4333 // Check each new char to make sure it matches what the group
4334 // referenced matched last time around
4335 int x = i;
4336 for (int index=0; index<groupSize; index++) {
4337 int c1 = Character.codePointAt(seq, x);
4338 int c2 = Character.codePointAt(seq, j);
4339 if (c1 != c2) {
4340 int cc1 = Character.toUpperCase(c1);
4341 int cc2 = Character.toUpperCase(c2);
4342 if (cc1 != cc2) {
4343 cc1 = Character.toLowerCase(cc1);
4344 cc2 = Character.toLowerCase(cc2);
4345 if (cc1 != cc2)
4346 return false;
4347 }
4348 }
4349 x += Character.charCount(c1);
4350 j += Character.charCount(c2);
4351 }
4352
4353 return next.match(matcher, i+groupSize, seq);
4354 }
4355 boolean study(TreeInfo info) {
4356 info.maxValid = false;
4357 return next.study(info);
4358 }
4359 }
4360
4361 /**
4362 * Searches until the next instance of its atom. This is useful for
4363 * finding the atom efficiently without passing an instance of it
4364 * (greedy problem) and without a lot of wasted search time (reluctant
4365 * problem).
4366 */
4367 static final class First extends Node {
4368 Node atom;
4369 First(Node node) {
4370 this.atom = BnM.optimize(node);
4371 }
4372 boolean match(Matcher matcher, int i, CharSequence seq) {
4373 if (atom instanceof BnM) {
4374 return atom.match(matcher, i, seq)
4375 && next.match(matcher, matcher.last, seq);
4376 }
4377 for (;;) {
4378 if (i > matcher.to) {
4379 matcher.hitEnd = true;
4380 return false;
4381 }
4382 if (atom.match(matcher, i, seq)) {
4383 return next.match(matcher, matcher.last, seq);
4384 }
4385 i += countChars(seq, i, 1);
4386 matcher.first++;
4387 }
4388 }
4389 boolean study(TreeInfo info) {
4390 atom.study(info);
4391 info.maxValid = false;
4392 info.deterministic = false;
4393 return next.study(info);
4394 }
4395 }
4396
4397 static final class Conditional extends Node {
4398 Node cond, yes, not;
4399 Conditional(Node cond, Node yes, Node not) {
4400 this.cond = cond;
4401 this.yes = yes;
4402 this.not = not;
4403 }
4404 boolean match(Matcher matcher, int i, CharSequence seq) {
4405 if (cond.match(matcher, i, seq)) {
4406 return yes.match(matcher, i, seq);
4407 } else {
4408 return not.match(matcher, i, seq);
4409 }
4410 }
4411 boolean study(TreeInfo info) {
4412 int minL = info.minLength;
4413 int maxL = info.maxLength;
4414 boolean maxV = info.maxValid;
4415 info.reset();
4416 yes.study(info);
4417
4418 int minL2 = info.minLength;
4419 int maxL2 = info.maxLength;
4420 boolean maxV2 = info.maxValid;
4421 info.reset();
4422 not.study(info);
4423
4424 info.minLength = minL + Math.min(minL2, info.minLength);
4425 info.maxLength = maxL + Math.max(maxL2, info.maxLength);
4426 info.maxValid = (maxV & maxV2 & info.maxValid);
4427 info.deterministic = false;
4428 return next.study(info);
4429 }
4430 }
4431
4432 /**
4433 * Zero width positive lookahead.
4434 */
4435 static final class Pos extends Node {
4436 Node cond;
4437 Pos(Node cond) {
4438 this.cond = cond;
4439 }
4440 boolean match(Matcher matcher, int i, CharSequence seq) {
4441 int savedTo = matcher.to;
4442 boolean conditionMatched = false;
4443
4444 // Relax transparent region boundaries for lookahead
4445 if (matcher.transparentBounds)
4446 matcher.to = matcher.getTextLength();
4447 try {
4448 conditionMatched = cond.match(matcher, i, seq);
4449 } finally {
4450 // Reinstate region boundaries
4451 matcher.to = savedTo;
4452 }
4453 return conditionMatched && next.match(matcher, i, seq);
4454 }
4455 }
4456
4457 /**
4458 * Zero width negative lookahead.
4459 */
4460 static final class Neg extends Node {
4461 Node cond;
4462 Neg(Node cond) {
4463 this.cond = cond;
4464 }
4465 boolean match(Matcher matcher, int i, CharSequence seq) {
4466 int savedTo = matcher.to;
4467 boolean conditionMatched = false;
4468
4469 // Relax transparent region boundaries for lookahead
4470 if (matcher.transparentBounds)
4471 matcher.to = matcher.getTextLength();
4472 try {
4473 if (i < matcher.to) {
4474 conditionMatched = !cond.match(matcher, i, seq);
4475 } else {
4476 // If a negative lookahead succeeds then more input
4477 // could cause it to fail!
4478 matcher.requireEnd = true;
4479 conditionMatched = !cond.match(matcher, i, seq);
4480 }
4481 } finally {
4482 // Reinstate region boundaries
4483 matcher.to = savedTo;
4484 }
4485 return conditionMatched && next.match(matcher, i, seq);
4486 }
4487 }
4488
4489 /**
4490 * Zero width positive lookbehind.
4491 */
4492 static class Behind extends Node {
4493 Node cond;
4494 int rmax, rmin;
4495 Behind(Node cond, int rmax, int rmin) {
4496 this.cond = cond;
4497 this.rmax = rmax;
4498 this.rmin = rmin;
4499 }
4500 boolean match(Matcher matcher, int i, CharSequence seq) {
4501 int savedFrom = matcher.from;
4502 boolean conditionMatched = false;
4503 int startIndex = (!matcher.transparentBounds) ?
4504 matcher.from : 0;
4505 int from = Math.max(i - rmax, startIndex);
4506 for (int j = i - rmin; j >= from; j--) {
4507
4508 // Relax transparent region boundaries for lookbehind
4509 if (matcher.transparentBounds)
4510 matcher.from = 0;
4511 try {
4512 conditionMatched =
4513 (cond.match(matcher, j, seq) && matcher.last == i);
4514 } finally { // Reinstate region boundaries
4515 matcher.from = savedFrom;
4516 }
4517
4518 if (conditionMatched)
4519 return next.match(matcher, i, seq);
4520 }
4521 return false;
4522 }
4523 }
4524
4525 /**
4526 * Zero width positive lookbehind, including supplementary
4527 * characters or unpaired surrogates.
4528 */
4529 static final class BehindS extends Behind {
4530 BehindS(Node cond, int rmax, int rmin) {
4531 super(cond, rmax, rmin);
4532 }
4533 boolean match(Matcher matcher, int i, CharSequence seq) {
4534 int rmaxChars = countChars(seq, i, -rmax);
4535 int rminChars = countChars(seq, i, -rmin);
4536 int savedFrom = matcher.from;
4537 int startIndex = (!matcher.transparentBounds) ?
4538 matcher.from : 0;
4539 boolean conditionMatched = false;
4540 int from = Math.max(i - rmaxChars, startIndex);
4541 for (int j = i - rminChars;
4542 j >= from;
4543 j -= j>from ? countChars(seq, j, -1) : 1) {
4544 // Relax transparent region boundaries for lookbehind
4545 if (matcher.transparentBounds)
4546 matcher.from = 0;
4547 try {
4548 conditionMatched =
4549 (cond.match(matcher, j, seq) && matcher.last == i);
4550 } finally { // Reinstate region boundaries
4551 matcher.from = savedFrom;
4552 }
4553 if (conditionMatched)
4554 return next.match(matcher, i, seq);
4555 }
4556 return false;
4557 }
4558 }
4559
4560 /**
4561 * Zero width negative lookbehind.
4562 */
4563 static class NotBehind extends Node {
4564 Node cond;
4565 int rmax, rmin;
4566 NotBehind(Node cond, int rmax, int rmin) {
4567 this.cond = cond;
4568 this.rmax = rmax;
4569 this.rmin = rmin;
4570 }
4571 boolean match(Matcher matcher, int i, CharSequence seq) {
4572 int savedFrom = matcher.from;
4573 boolean conditionMatched = false;
4574 int startIndex = (!matcher.transparentBounds) ?
4575 matcher.from : 0;
4576 int from = Math.max(i - rmax, startIndex);
4577 for (int j = i - rmin; j >= from; j--) {
4578
4579 // Relax transparent region boundaries for lookbehind
4580 if (matcher.transparentBounds)
4581 matcher.from = 0;
4582 try {
4583 conditionMatched =
4584 (cond.match(matcher, j, seq) && matcher.last == i);
4585 } finally { // Reinstate region boundaries
4586 matcher.from = savedFrom;
4587 }
4588 if (conditionMatched)
4589 return false;
4590 }
4591 return next.match(matcher, i, seq);
4592 }
4593 }
4594
4595 /**
4596 * Zero width negative lookbehind, including supplementary
4597 * characters or unpaired surrogates.
4598 */
4599 static final class NotBehindS extends NotBehind {
4600 NotBehindS(Node cond, int rmax, int rmin) {
4601 super(cond, rmax, rmin);
4602 }
4603 boolean match(Matcher matcher, int i, CharSequence seq) {
4604 int rmaxChars = countChars(seq, i, -rmax);
4605 int rminChars = countChars(seq, i, -rmin);
4606 int savedFrom = matcher.from;
4607 boolean conditionMatched = false;
4608 int startIndex = (!matcher.transparentBounds) ?
4609 matcher.from : 0;
4610 int from = Math.max(i - rmaxChars, startIndex);
4611 for (int j = i - rminChars;
4612 j >= from;
4613 j -= j>from ? countChars(seq, j, -1) : 1) {
4614 // Relax transparent region boundaries for lookbehind
4615 if (matcher.transparentBounds)
4616 matcher.from = 0;
4617 try {
4618 conditionMatched =
4619 (cond.match(matcher, j, seq) && matcher.last == i);
4620 } finally { // Reinstate region boundaries
4621 matcher.from = savedFrom;
4622 }
4623 if (conditionMatched)
4624 return false;
4625 }
4626 return next.match(matcher, i, seq);
4627 }
4628 }
4629
4630 /**
4631 * Returns the set union of two CharProperty nodes.
4632 */
4633 private static CharProperty union(final CharProperty lhs,
4634 final CharProperty rhs) {
4635 return new CharProperty() {
4636 boolean isSatisfiedBy(int ch) {
4637 return lhs.isSatisfiedBy(ch) || rhs.isSatisfiedBy(ch);}};
4638 }
4639
4640 /**
4641 * Returns the set intersection of two CharProperty nodes.
4642 */
4643 private static CharProperty intersection(final CharProperty lhs,
4644 final CharProperty rhs) {
4645 return new CharProperty() {
4646 boolean isSatisfiedBy(int ch) {
4647 return lhs.isSatisfiedBy(ch) && rhs.isSatisfiedBy(ch);}};
4648 }
4649
4650 /**
4651 * Returns the set difference of two CharProperty nodes.
4652 */
4653 private static CharProperty setDifference(final CharProperty lhs,
4654 final CharProperty rhs) {
4655 return new CharProperty() {
4656 boolean isSatisfiedBy(int ch) {
4657 return ! rhs.isSatisfiedBy(ch) && lhs.isSatisfiedBy(ch);}};
4658 }
4659
4660 /**
4661 * Handles word boundaries. Includes a field to allow this one class to
4662 * deal with the different types of word boundaries we can match. The word
4663 * characters include underscores, letters, and digits. Non spacing marks
4664 * can are also part of a word if they have a base character, otherwise
4665 * they are ignored for purposes of finding word boundaries.
4666 */
4667 static final class Bound extends Node {
4668 static int LEFT = 0x1;
4669 static int RIGHT= 0x2;
4670 static int BOTH = 0x3;
4671 static int NONE = 0x4;
4672 int type;
4673 Bound(int n) {
4674 type = n;
4675 }
4676 int check(Matcher matcher, int i, CharSequence seq) {
4677 int ch;
4678 boolean left = false;
4679 int startIndex = matcher.from;
4680 int endIndex = matcher.to;
4681 if (matcher.transparentBounds) {
4682 startIndex = 0;
4683 endIndex = matcher.getTextLength();
4684 }
4685 if (i > startIndex) {
4686 ch = Character.codePointBefore(seq, i);
4687 left = (ch == '_' || Character.isLetterOrDigit(ch) ||
4688 ((Character.getType(ch) == Character.NON_SPACING_MARK)
4689 && hasBaseCharacter(matcher, i-1, seq)));
4690 }
4691 boolean right = false;
4692 if (i < endIndex) {
4693 ch = Character.codePointAt(seq, i);
4694 right = (ch == '_' || Character.isLetterOrDigit(ch) ||
4695 ((Character.getType(ch) == Character.NON_SPACING_MARK)
4696 && hasBaseCharacter(matcher, i, seq)));
4697 } else {
4698 // Tried to access char past the end
4699 matcher.hitEnd = true;
4700 // The addition of another char could wreck a boundary
4701 matcher.requireEnd = true;
4702 }
4703 return ((left ^ right) ? (right ? LEFT : RIGHT) : NONE);
4704 }
4705 boolean match(Matcher matcher, int i, CharSequence seq) {
4706 return (check(matcher, i, seq) & type) > 0
4707 && next.match(matcher, i, seq);
4708 }
4709 }
4710
4711 /**
4712 * Non spacing marks only count as word characters in bounds calculations
4713 * if they have a base character.
4714 */
4715 private static boolean hasBaseCharacter(Matcher matcher, int i,
4716 CharSequence seq)
4717 {
4718 int start = (!matcher.transparentBounds) ?
4719 matcher.from : 0;
4720 for (int x=i; x >= start; x--) {
4721 int ch = Character.codePointAt(seq, x);
4722 if (Character.isLetterOrDigit(ch))
4723 return true;
4724 if (Character.getType(ch) == Character.NON_SPACING_MARK)
4725 continue;
4726 return false;
4727 }
4728 return false;
4729 }
4730
4731 /**
4732 * Attempts to match a slice in the input using the Boyer-Moore string
4733 * matching algorithm. The algorithm is based on the idea that the
4734 * pattern can be shifted farther ahead in the search text if it is
4735 * matched right to left.
4736 * <p>
4737 * The pattern is compared to the input one character at a time, from
4738 * the rightmost character in the pattern to the left. If the characters
4739 * all match the pattern has been found. If a character does not match,
4740 * the pattern is shifted right a distance that is the maximum of two
4741 * functions, the bad character shift and the good suffix shift. This
4742 * shift moves the attempted match position through the input more
4743 * quickly than a naive one position at a time check.
4744 * <p>
4745 * The bad character shift is based on the character from the text that
4746 * did not match. If the character does not appear in the pattern, the
4747 * pattern can be shifted completely beyond the bad character. If the
4748 * character does occur in the pattern, the pattern can be shifted to
4749 * line the pattern up with the next occurrence of that character.
4750 * <p>
4751 * The good suffix shift is based on the idea that some subset on the right
4752 * side of the pattern has matched. When a bad character is found, the
4753 * pattern can be shifted right by the pattern length if the subset does
4754 * not occur again in pattern, or by the amount of distance to the
4755 * next occurrence of the subset in the pattern.
4756 *
4757 * Boyer-Moore search methods adapted from code by Amy Yu.
4758 */
4759 static class BnM extends Node {
4760 int[] buffer;
4761 int[] lastOcc;
4762 int[] optoSft;
4763
4764 /**
4765 * Pre calculates arrays needed to generate the bad character
4766 * shift and the good suffix shift. Only the last seven bits
4767 * are used to see if chars match; This keeps the tables small
4768 * and covers the heavily used ASCII range, but occasionally
4769 * results in an aliased match for the bad character shift.
4770 */
4771 static Node optimize(Node node) {
4772 if (!(node instanceof Slice)) {
4773 return node;
4774 }
4775
4776 int[] src = ((Slice) node).buffer;
4777 int patternLength = src.length;
4778 // The BM algorithm requires a bit of overhead;
4779 // If the pattern is short don't use it, since
4780 // a shift larger than the pattern length cannot
4781 // be used anyway.
4782 if (patternLength < 4) {
4783 return node;
4784 }
4785 int i, j, k;
4786 int[] lastOcc = new int[128];
4787 int[] optoSft = new int[patternLength];
4788 // Precalculate part of the bad character shift
4789 // It is a table for where in the pattern each
4790 // lower 7-bit value occurs
4791 for (i = 0; i < patternLength; i++) {
4792 lastOcc[src[i]&0x7F] = i + 1;
4793 }
4794 // Precalculate the good suffix shift
4795 // i is the shift amount being considered
4796 NEXT: for (i = patternLength; i > 0; i--) {
4797 // j is the beginning index of suffix being considered
4798 for (j = patternLength - 1; j >= i; j--) {
4799 // Testing for good suffix
4800 if (src[j] == src[j-i]) {
4801 // src[j..len] is a good suffix
4802 optoSft[j-1] = i;
4803 } else {
4804 // No match. The array has already been
4805 // filled up with correct values before.
4806 continue NEXT;
4807 }
4808 }
4809 // This fills up the remaining of optoSft
4810 // any suffix can not have larger shift amount
4811 // then its sub-suffix. Why???
4812 while (j > 0) {
4813 optoSft[--j] = i;
4814 }
4815 }
4816 // Set the guard value because of unicode compression
4817 optoSft[patternLength-1] = 1;
4818 if (node instanceof SliceS)
4819 return new BnMS(src, lastOcc, optoSft, node.next);
4820 return new BnM(src, lastOcc, optoSft, node.next);
4821 }
4822 BnM(int[] src, int[] lastOcc, int[] optoSft, Node next) {
4823 this.buffer = src;
4824 this.lastOcc = lastOcc;
4825 this.optoSft = optoSft;
4826 this.next = next;
4827 }
4828 boolean match(Matcher matcher, int i, CharSequence seq) {
4829 int[] src = buffer;
4830 int patternLength = src.length;
4831 int last = matcher.to - patternLength;
4832
4833 // Loop over all possible match positions in text
4834 NEXT: while (i <= last) {
4835 // Loop over pattern from right to left
4836 for (int j = patternLength - 1; j >= 0; j--) {
4837 int ch = seq.charAt(i+j);
4838 if (ch != src[j]) {
4839 // Shift search to the right by the maximum of the
4840 // bad character shift and the good suffix shift
4841 i += Math.max(j + 1 - lastOcc[ch&0x7F], optoSft[j]);
4842 continue NEXT;
4843 }
4844 }
4845 // Entire pattern matched starting at i
4846 matcher.first = i;
4847 boolean ret = next.match(matcher, i + patternLength, seq);
4848 if (ret) {
4849 matcher.first = i;
4850 matcher.groups[0] = matcher.first;
4851 matcher.groups[1] = matcher.last;
4852 return true;
4853 }
4854 i++;
4855 }
4856 // BnM is only used as the leading node in the unanchored case,
4857 // and it replaced its Start() which always searches to the end
4858 // if it doesn't find what it's looking for, so hitEnd is true.
4859 matcher.hitEnd = true;
4860 return false;
4861 }
4862 boolean study(TreeInfo info) {
4863 info.minLength += buffer.length;
4864 info.maxValid = false;
4865 return next.study(info);
4866 }
4867 }
4868
4869 /**
4870 * Supplementary support version of BnM(). Unpaired surrogates are
4871 * also handled by this class.
4872 */
4873 static final class BnMS extends BnM {
4874 int lengthInChars;
4875
4876 BnMS(int[] src, int[] lastOcc, int[] optoSft, Node next) {
4877 super(src, lastOcc, optoSft, next);
4878 for (int x = 0; x < buffer.length; x++) {
4879 lengthInChars += Character.charCount(buffer[x]);
4880 }
4881 }
4882 boolean match(Matcher matcher, int i, CharSequence seq) {
4883 int[] src = buffer;
4884 int patternLength = src.length;
4885 int last = matcher.to - lengthInChars;
4886
4887 // Loop over all possible match positions in text
4888 NEXT: while (i <= last) {
4889 // Loop over pattern from right to left
4890 int ch;
4891 for (int j = countChars(seq, i, patternLength), x = patternLength - 1;
4892 j > 0; j -= Character.charCount(ch), x--) {
4893 ch = Character.codePointBefore(seq, i+j);
4894 if (ch != src[x]) {
4895 // Shift search to the right by the maximum of the
4896 // bad character shift and the good suffix shift
4897 int n = Math.max(x + 1 - lastOcc[ch&0x7F], optoSft[x]);
4898 i += countChars(seq, i, n);
4899 continue NEXT;
4900 }
4901 }
4902 // Entire pattern matched starting at i
4903 matcher.first = i;
4904 boolean ret = next.match(matcher, i + lengthInChars, seq);
4905 if (ret) {
4906 matcher.first = i;
4907 matcher.groups[0] = matcher.first;
4908 matcher.groups[1] = matcher.last;
4909 return true;
4910 }
4911 i += countChars(seq, i, 1);
4912 }
4913 matcher.hitEnd = true;
4914 return false;
4915 }
4916 }
4917
4918 ///////////////////////////////////////////////////////////////////////////////
4919 ///////////////////////////////////////////////////////////////////////////////
4920
4921 /**
4922 * This must be the very first initializer.
4923 */
4924 static Node accept = new Node();
4925
4926 static Node lastAccept = new LastNode();
4927
4928 private static class CharPropertyNames {
4929
4930 static CharProperty charPropertyFor(String name) {
4931 CharPropertyFactory m = map.get(name);
4932 return m == null ? null : m.make();
4933 }
4934
4935 private static abstract class CharPropertyFactory {
4936 abstract CharProperty make();
4937 }
4938
4939 private static void defCategory(String name,
4940 final int typeMask) {
4941 map.put(name, new CharPropertyFactory() {
4942 CharProperty make() { return new Category(typeMask);}});
4943 }
4944
4945 private static void defRange(String name,
4946 final int lower, final int upper) {
4947 map.put(name, new CharPropertyFactory() {
4948 CharProperty make() { return rangeFor(lower, upper);}});
4949 }
4950
4951 private static void defCtype(String name,
4952 final int ctype) {
4953 map.put(name, new CharPropertyFactory() {
4954 CharProperty make() { return new Ctype(ctype);}});
4955 }
4956
4957 private static abstract class CloneableProperty
4958 extends CharProperty implements Cloneable
4959 {
4960 public CloneableProperty clone() {
4961 try {
4962 return (CloneableProperty) super.clone();
4963 } catch (CloneNotSupportedException e) {
4964 throw new AssertionError(e);
4965 }
4966 }
4967 }
4968
4969 private static void defClone(String name,
4970 final CloneableProperty p) {
4971 map.put(name, new CharPropertyFactory() {
4972 CharProperty make() { return p.clone();}});
4973 }
4974
4975 private static final HashMap<String, CharPropertyFactory> map
4976 = new HashMap<String, CharPropertyFactory>();
4977
4978 static {
4979 // Unicode character property aliases, defined in
4980 // http://www.unicode.org/Public/UNIDATA/PropertyValueAliases.txt
4981 defCategory("Cn", 1<<Character.UNASSIGNED);
4982 defCategory("Lu", 1<<Character.UPPERCASE_LETTER);
4983 defCategory("Ll", 1<<Character.LOWERCASE_LETTER);
4984 defCategory("Lt", 1<<Character.TITLECASE_LETTER);
4985 defCategory("Lm", 1<<Character.MODIFIER_LETTER);
4986 defCategory("Lo", 1<<Character.OTHER_LETTER);
4987 defCategory("Mn", 1<<Character.NON_SPACING_MARK);
4988 defCategory("Me", 1<<Character.ENCLOSING_MARK);
4989 defCategory("Mc", 1<<Character.COMBINING_SPACING_MARK);
4990 defCategory("Nd", 1<<Character.DECIMAL_DIGIT_NUMBER);
4991 defCategory("Nl", 1<<Character.LETTER_NUMBER);
4992 defCategory("No", 1<<Character.OTHER_NUMBER);
4993 defCategory("Zs", 1<<Character.SPACE_SEPARATOR);
4994 defCategory("Zl", 1<<Character.LINE_SEPARATOR);
4995 defCategory("Zp", 1<<Character.PARAGRAPH_SEPARATOR);
4996 defCategory("Cc", 1<<Character.CONTROL);
4997 defCategory("Cf", 1<<Character.FORMAT);
4998 defCategory("Co", 1<<Character.PRIVATE_USE);
4999 defCategory("Cs", 1<<Character.SURROGATE);
5000 defCategory("Pd", 1<<Character.DASH_PUNCTUATION);
5001 defCategory("Ps", 1<<Character.START_PUNCTUATION);
5002 defCategory("Pe", 1<<Character.END_PUNCTUATION);
5003 defCategory("Pc", 1<<Character.CONNECTOR_PUNCTUATION);
5004 defCategory("Po", 1<<Character.OTHER_PUNCTUATION);
5005 defCategory("Sm", 1<<Character.MATH_SYMBOL);
5006 defCategory("Sc", 1<<Character.CURRENCY_SYMBOL);
5007 defCategory("Sk", 1<<Character.MODIFIER_SYMBOL);
5008 defCategory("So", 1<<Character.OTHER_SYMBOL);
5009 defCategory("Pi", 1<<Character.INITIAL_QUOTE_PUNCTUATION);
5010 defCategory("Pf", 1<<Character.FINAL_QUOTE_PUNCTUATION);
5011 defCategory("L", ((1<<Character.UPPERCASE_LETTER) |
5012 (1<<Character.LOWERCASE_LETTER) |
5013 (1<<Character.TITLECASE_LETTER) |
5014 (1<<Character.MODIFIER_LETTER) |
5015 (1<<Character.OTHER_LETTER)));
5016 defCategory("M", ((1<<Character.NON_SPACING_MARK) |
5017 (1<<Character.ENCLOSING_MARK) |
5018 (1<<Character.COMBINING_SPACING_MARK)));
5019 defCategory("N", ((1<<Character.DECIMAL_DIGIT_NUMBER) |
5020 (1<<Character.LETTER_NUMBER) |
5021 (1<<Character.OTHER_NUMBER)));
5022 defCategory("Z", ((1<<Character.SPACE_SEPARATOR) |
5023 (1<<Character.LINE_SEPARATOR) |
5024 (1<<Character.PARAGRAPH_SEPARATOR)));
5025 defCategory("C", ((1<<Character.CONTROL) |
5026 (1<<Character.FORMAT) |
5027 (1<<Character.PRIVATE_USE) |
5028 (1<<Character.SURROGATE))); // Other
5029 defCategory("P", ((1<<Character.DASH_PUNCTUATION) |
5030 (1<<Character.START_PUNCTUATION) |
5031 (1<<Character.END_PUNCTUATION) |
5032 (1<<Character.CONNECTOR_PUNCTUATION) |
5033 (1<<Character.OTHER_PUNCTUATION) |
5034 (1<<Character.INITIAL_QUOTE_PUNCTUATION) |
5035 (1<<Character.FINAL_QUOTE_PUNCTUATION)));
5036 defCategory("S", ((1<<Character.MATH_SYMBOL) |
5037 (1<<Character.CURRENCY_SYMBOL) |
5038 (1<<Character.MODIFIER_SYMBOL) |
5039 (1<<Character.OTHER_SYMBOL)));
5040 defCategory("LC", ((1<<Character.UPPERCASE_LETTER) |
5041 (1<<Character.LOWERCASE_LETTER) |
5042 (1<<Character.TITLECASE_LETTER)));
5043 defCategory("LD", ((1<<Character.UPPERCASE_LETTER) |
5044 (1<<Character.LOWERCASE_LETTER) |
5045 (1<<Character.TITLECASE_LETTER) |
5046 (1<<Character.MODIFIER_LETTER) |
5047 (1<<Character.OTHER_LETTER) |
5048 (1<<Character.DECIMAL_DIGIT_NUMBER)));
5049 defRange("L1", 0x00, 0xFF); // Latin-1
5050 map.put("all", new CharPropertyFactory() {
5051 CharProperty make() { return new All(); }});
5052
5053 // Posix regular expression character classes, defined in
5054 // http://www.unix.org/onlinepubs/009695399/basedefs/xbd_chap09.html
5055 defRange("ASCII", 0x00, 0x7F); // ASCII
5056 defCtype("Alnum", ASCII.ALNUM); // Alphanumeric characters
5057 defCtype("Alpha", ASCII.ALPHA); // Alphabetic characters
5058 defCtype("Blank", ASCII.BLANK); // Space and tab characters
5059 defCtype("Cntrl", ASCII.CNTRL); // Control characters
5060 defRange("Digit", '0', '9'); // Numeric characters
5061 defCtype("Graph", ASCII.GRAPH); // printable and visible
5062 defRange("Lower", 'a', 'z'); // Lower-case alphabetic
5063 defRange("Print", 0x20, 0x7E); // Printable characters
5064 defCtype("Punct", ASCII.PUNCT); // Punctuation characters
5065 defCtype("Space", ASCII.SPACE); // Space characters
5066 defRange("Upper", 'A', 'Z'); // Upper-case alphabetic
5067 defCtype("XDigit",ASCII.XDIGIT); // hexadecimal digits
5068
5069 // Java character properties, defined by methods in Character.java
5070 defClone("javaLowerCase", new CloneableProperty() {
5071 boolean isSatisfiedBy(int ch) {
5072 return Character.isLowerCase(ch);}});
5073 defClone("javaUpperCase", new CloneableProperty() {
5074 boolean isSatisfiedBy(int ch) {
5075 return Character.isUpperCase(ch);}});
5076 defClone("javaTitleCase", new CloneableProperty() {
5077 boolean isSatisfiedBy(int ch) {
5078 return Character.isTitleCase(ch);}});
5079 defClone("javaDigit", new CloneableProperty() {
5080 boolean isSatisfiedBy(int ch) {
5081 return Character.isDigit(ch);}});
5082 defClone("javaDefined", new CloneableProperty() {
5083 boolean isSatisfiedBy(int ch) {
5084 return Character.isDefined(ch);}});
5085 defClone("javaLetter", new CloneableProperty() {
5086 boolean isSatisfiedBy(int ch) {
5087 return Character.isLetter(ch);}});
5088 defClone("javaLetterOrDigit", new CloneableProperty() {
5089 boolean isSatisfiedBy(int ch) {
5090 return Character.isLetterOrDigit(ch);}});
5091 defClone("javaJavaIdentifierStart", new CloneableProperty() {
5092 boolean isSatisfiedBy(int ch) {
5093 return Character.isJavaIdentifierStart(ch);}});
5094 defClone("javaJavaIdentifierPart", new CloneableProperty() {
5095 boolean isSatisfiedBy(int ch) {
5096 return Character.isJavaIdentifierPart(ch);}});
5097 defClone("javaUnicodeIdentifierStart", new CloneableProperty() {
5098 boolean isSatisfiedBy(int ch) {
5099 return Character.isUnicodeIdentifierStart(ch);}});
5100 defClone("javaUnicodeIdentifierPart", new CloneableProperty() {
5101 boolean isSatisfiedBy(int ch) {
5102 return Character.isUnicodeIdentifierPart(ch);}});
5103 defClone("javaIdentifierIgnorable", new CloneableProperty() {
5104 boolean isSatisfiedBy(int ch) {
5105 return Character.isIdentifierIgnorable(ch);}});
5106 defClone("javaSpaceChar", new CloneableProperty() {
5107 boolean isSatisfiedBy(int ch) {
5108 return Character.isSpaceChar(ch);}});
5109 defClone("javaWhitespace", new CloneableProperty() {
5110 boolean isSatisfiedBy(int ch) {
5111 return Character.isWhitespace(ch);}});
5112 defClone("javaISOControl", new CloneableProperty() {
5113 boolean isSatisfiedBy(int ch) {
5114 return Character.isISOControl(ch);}});
5115 defClone("javaMirrored", new CloneableProperty() {
5116 boolean isSatisfiedBy(int ch) {
5117 return Character.isMirrored(ch);}});
5118 }
5119 }
5120 }