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