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