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 
  26 package java.util.regex;
  27 
  28 import java.text.Normalizer;
  29 import java.text.Normalizer.Form;
  30 import java.util.Locale;
  31 import java.util.Iterator;
  32 import java.util.Map;
  33 import java.util.ArrayList;
  34 import java.util.HashMap;
  35 import java.util.LinkedHashSet;
  36 import java.util.List;
  37 import java.util.Set;
  38 import java.util.Arrays;
  39 import java.util.NoSuchElementException;
  40 import java.util.Spliterator;
  41 import java.util.Spliterators;
  42 import java.util.function.Predicate;
  43 import java.util.stream.Stream;
  44 import 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 
 781 public 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).append('|'));
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.
1594 loop:   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         if (ch < 256 &&
2708             !(has(CASE_INSENSITIVE) && has(UNICODE_CASE) &&
2709               (ch == 0xff || ch == 0xb5 ||
2710                ch == 0x49 || ch == 0x69 ||    //I and i
2711                ch == 0x53 || ch == 0x73 ||    //S and s
2712                ch == 0x4b || ch == 0x6b ||    //K and k
2713                ch == 0xc5 || ch == 0xe5))) {  //A+ring
2714             bits.add(ch, flags());
2715             return null;
2716         }
2717         return single(ch);
2718     }
2719 
2720     /**
2721      *  Returns a suitably optimized, single character predicate
2722      */
2723     private CharPredicate single(final int ch) {
2724         if (has(CASE_INSENSITIVE)) {
2725             int lower, upper;
2726             if (has(UNICODE_CASE)) {
2727                 upper = Character.toUpperCase(ch);
2728                 lower = Character.toLowerCase(upper);
2729                 // Unicode case insensitive matches
2730                 if (upper != lower)
2731                     return SingleU(lower);
2732             } else if (ASCII.isAscii(ch)) {
2733                 lower = ASCII.toLower(ch);
2734                 upper = ASCII.toUpper(ch);
2735                 // Case insensitive matches a given BMP character
2736                 if (lower != upper)
2737                     return SingleI(lower, upper);
2738             }
2739         }
2740         if (isSupplementary(ch))
2741             return SingleS(ch);
2742         return Single(ch);  // Match a given BMP character
2743     }
2744 
2745     /**
2746      * Parse a single character or a character range in a character class
2747      * and return its representative node.
2748      */
2749     private CharPredicate range(BitClass bits) {
2750         int ch = peek();
2751         if (ch == '\\') {
2752             ch = nextEscaped();
2753             if (ch == 'p' || ch == 'P') { // A property
2754                 boolean comp = (ch == 'P');
2755                 boolean oneLetter = true;
2756                 // Consume { if present
2757                 ch = next();
2758                 if (ch != '{')
2759                     unread();
2760                 else
2761                     oneLetter = false;
2762                 return family(oneLetter, comp);
2763             } else { // ordinary escape
2764                 boolean isrange = temp[cursor+1] == '-';
2765                 unread();
2766                 ch = escape(true, true, isrange);
2767                 if (ch == -1)
2768                     return predicate;
2769             }
2770         } else {
2771             next();
2772         }
2773         if (ch >= 0) {
2774             if (peek() == '-') {
2775                 int endRange = temp[cursor+1];
2776                 if (endRange == '[') {
2777                     return bitsOrSingle(bits, ch);
2778                 }
2779                 if (endRange != ']') {
2780                     next();
2781                     int m = peek();
2782                     if (m == '\\') {
2783                         m = escape(true, false, true);
2784                     } else {
2785                         next();
2786                     }
2787                     if (m < ch) {
2788                         throw error("Illegal character range");
2789                     }
2790                     if (has(CASE_INSENSITIVE)) {
2791                         if (has(UNICODE_CASE))
2792                             return CIRangeU(ch, m);
2793                         return CIRange(ch, m);
2794                     } else {
2795                         return Range(ch, m);
2796                     }
2797                 }
2798             }
2799             return bitsOrSingle(bits, ch);
2800         }
2801         throw error("Unexpected character '"+((char)ch)+"'");
2802     }
2803 
2804     /**
2805      * Parses a Unicode character family and returns its representative node.
2806      */
2807     private CharPredicate family(boolean singleLetter, boolean isComplement) {
2808         next();
2809         String name;
2810         CharPredicate p = null;
2811 
2812         if (singleLetter) {
2813             int c = temp[cursor];
2814             if (!Character.isSupplementaryCodePoint(c)) {
2815                 name = String.valueOf((char)c);
2816             } else {
2817                 name = new String(temp, cursor, 1);
2818             }
2819             read();
2820         } else {
2821             int i = cursor;
2822             mark('}');
2823             while(read() != '}') {
2824             }
2825             mark('\000');
2826             int j = cursor;
2827             if (j > patternLength)
2828                 throw error("Unclosed character family");
2829             if (i + 1 >= j)
2830                 throw error("Empty character family");
2831             name = new String(temp, i, j-i-1);
2832         }
2833 
2834         int i = name.indexOf('=');
2835         if (i != -1) {
2836             // property construct \p{name=value}
2837             String value = name.substring(i + 1);
2838             name = name.substring(0, i).toLowerCase(Locale.ENGLISH);
2839             switch (name) {
2840                 case "sc":
2841                 case "script":
2842                     p = CharPredicates.forUnicodeScript(value);
2843                     break;
2844                 case "blk":
2845                 case "block":
2846                     p = CharPredicates.forUnicodeBlock(value);
2847                     break;
2848                 case "gc":
2849                 case "general_category":
2850                     p = CharPredicates.forProperty(value);
2851                     break;
2852                 default:
2853                     break;
2854             }
2855             if (p == null)
2856                 throw error("Unknown Unicode property {name=<" + name + ">, "
2857                              + "value=<" + value + ">}");
2858 
2859         } else {
2860             if (name.startsWith("In")) {
2861                 // \p{InBlockName}
2862                 p = CharPredicates.forUnicodeBlock(name.substring(2));
2863             } else if (name.startsWith("Is")) {
2864                 // \p{IsGeneralCategory} and \p{IsScriptName}
2865                 name = name.substring(2);
2866                 p = CharPredicates.forUnicodeProperty(name);
2867                 if (p == null)
2868                     p = CharPredicates.forProperty(name);
2869                 if (p == null)
2870                     p = CharPredicates.forUnicodeScript(name);
2871             } else {
2872                 if (has(UNICODE_CHARACTER_CLASS)) {
2873                     p = CharPredicates.forPOSIXName(name);
2874                 }
2875                 if (p == null)
2876                     p = CharPredicates.forProperty(name);
2877             }
2878             if (p == null)
2879                 throw error("Unknown character property name {In/Is" + name + "}");
2880         }
2881         if (isComplement) {
2882             // it might be too expensive to detect if a complement of
2883             // CharProperty can match "certain" supplementary. So just
2884             // go with StartS.
2885             hasSupplementary = true;
2886             p = p.negate();
2887         }
2888         return p;
2889     }
2890 
2891     private CharProperty newCharProperty(CharPredicate p) {
2892         if (p == null)
2893             return null;
2894         if (p instanceof BmpCharPredicate)
2895             return new BmpCharProperty((BmpCharPredicate)p);
2896         else
2897             return new CharProperty(p);
2898     }
2899 
2900     /**
2901      * Parses and returns the name of a "named capturing group", the trailing
2902      * ">" is consumed after parsing.
2903      */
2904     private String groupname(int ch) {
2905         StringBuilder sb = new StringBuilder();
2906         sb.append(Character.toChars(ch));
2907         while (ASCII.isLower(ch=read()) || ASCII.isUpper(ch) ||
2908                ASCII.isDigit(ch)) {
2909             sb.append(Character.toChars(ch));
2910         }
2911         if (sb.length() == 0)
2912             throw error("named capturing group has 0 length name");
2913         if (ch != '>')
2914             throw error("named capturing group is missing trailing '>'");
2915         return sb.toString();
2916     }
2917 
2918     /**
2919      * Parses a group and returns the head node of a set of nodes that process
2920      * the group. Sometimes a double return system is used where the tail is
2921      * returned in root.
2922      */
2923     private Node group0() {
2924         boolean capturingGroup = false;
2925         Node head = null;
2926         Node tail = null;
2927         int save = flags;
2928         int saveTCNCount = topClosureNodes.size();
2929         root = null;
2930         int ch = next();
2931         if (ch == '?') {
2932             ch = skip();
2933             switch (ch) {
2934             case ':':   //  (?:xxx) pure group
2935                 head = createGroup(true);
2936                 tail = root;
2937                 head.next = expr(tail);
2938                 break;
2939             case '=':   // (?=xxx) and (?!xxx) lookahead
2940             case '!':
2941                 head = createGroup(true);
2942                 tail = root;
2943                 head.next = expr(tail);
2944                 if (ch == '=') {
2945                     head = tail = new Pos(head);
2946                 } else {
2947                     head = tail = new Neg(head);
2948                 }
2949                 break;
2950             case '>':   // (?>xxx)  independent group
2951                 head = createGroup(true);
2952                 tail = root;
2953                 head.next = expr(tail);
2954                 head = tail = new Ques(head, Qtype.INDEPENDENT);
2955                 break;
2956             case '<':   // (?<xxx)  look behind
2957                 ch = read();
2958                 if (ASCII.isLower(ch) || ASCII.isUpper(ch)) {
2959                     // named captured group
2960                     String name = groupname(ch);
2961                     if (namedGroups().containsKey(name))
2962                         throw error("Named capturing group <" + name
2963                                     + "> is already defined");
2964                     capturingGroup = true;
2965                     head = createGroup(false);
2966                     tail = root;
2967                     namedGroups().put(name, capturingGroupCount-1);
2968                     head.next = expr(tail);
2969                     break;
2970                 }
2971                 int start = cursor;
2972                 head = createGroup(true);
2973                 tail = root;
2974                 head.next = expr(tail);
2975                 tail.next = lookbehindEnd;
2976                 TreeInfo info = new TreeInfo();
2977                 head.study(info);
2978                 if (info.maxValid == false) {
2979                     throw error("Look-behind group does not have "
2980                                 + "an obvious maximum length");
2981                 }
2982                 boolean hasSupplementary = findSupplementary(start, patternLength);
2983                 if (ch == '=') {
2984                     head = tail = (hasSupplementary ?
2985                                    new BehindS(head, info.maxLength,
2986                                                info.minLength) :
2987                                    new Behind(head, info.maxLength,
2988                                               info.minLength));
2989                 } else if (ch == '!') {
2990                     head = tail = (hasSupplementary ?
2991                                    new NotBehindS(head, info.maxLength,
2992                                                   info.minLength) :
2993                                    new NotBehind(head, info.maxLength,
2994                                                  info.minLength));
2995                 } else {
2996                     throw error("Unknown look-behind group");
2997                 }
2998                 // clear all top-closure-nodes inside lookbehind
2999                 if (saveTCNCount < topClosureNodes.size())
3000                     topClosureNodes.subList(saveTCNCount, topClosureNodes.size()).clear();
3001                 break;
3002             case '$':
3003             case '@':
3004                 throw error("Unknown group type");
3005             default:    // (?xxx:) inlined match flags
3006                 unread();
3007                 addFlag();
3008                 ch = read();
3009                 if (ch == ')') {
3010                     return null;    // Inline modifier only
3011                 }
3012                 if (ch != ':') {
3013                     throw error("Unknown inline modifier");
3014                 }
3015                 head = createGroup(true);
3016                 tail = root;
3017                 head.next = expr(tail);
3018                 break;
3019             }
3020         } else { // (xxx) a regular group
3021             capturingGroup = true;
3022             head = createGroup(false);
3023             tail = root;
3024             head.next = expr(tail);
3025         }
3026 
3027         accept(')', "Unclosed group");
3028         flags = save;
3029 
3030         // Check for quantifiers
3031         Node node = closure(head);
3032         if (node == head) { // No closure
3033             root = tail;
3034             return node;    // Dual return
3035         }
3036         if (head == tail) { // Zero length assertion
3037             root = node;
3038             return node;    // Dual return
3039         }
3040 
3041         // have group closure, clear all inner closure nodes from the
3042         // top list (no backtracking stopper optimization for inner
3043         if (saveTCNCount < topClosureNodes.size())
3044             topClosureNodes.subList(saveTCNCount, topClosureNodes.size()).clear();
3045 
3046         if (node instanceof Ques) {
3047             Ques ques = (Ques) node;
3048             if (ques.type == Qtype.POSSESSIVE) {
3049                 root = node;
3050                 return node;
3051             }
3052             tail.next = new BranchConn();
3053             tail = tail.next;
3054             if (ques.type == Qtype.GREEDY) {
3055                 head = new Branch(head, null, tail);
3056             } else { // Reluctant quantifier
3057                 head = new Branch(null, head, tail);
3058             }
3059             root = tail;
3060             return head;
3061         } else if (node instanceof Curly) {
3062             Curly curly = (Curly) node;
3063             if (curly.type == Qtype.POSSESSIVE) {
3064                 root = node;
3065                 return node;
3066             }
3067             // Discover if the group is deterministic
3068             TreeInfo info = new TreeInfo();
3069             if (head.study(info)) { // Deterministic
3070                 GroupTail temp = (GroupTail) tail;
3071                 head = root = new GroupCurly(head.next, curly.cmin,
3072                                    curly.cmax, curly.type,
3073                                    ((GroupTail)tail).localIndex,
3074                                    ((GroupTail)tail).groupIndex,
3075                                              capturingGroup);
3076                 return head;
3077             } else { // Non-deterministic
3078                 int temp = ((GroupHead) head).localIndex;
3079                 Loop loop;
3080                 if (curly.type == Qtype.GREEDY) {
3081                     loop = new Loop(this.localCount, temp);
3082                     // add the max_reps greedy to the top-closure-node list
3083                     if (curly.cmax == MAX_REPS)
3084                         topClosureNodes.add(loop);
3085                 } else {  // Reluctant Curly
3086                     loop = new LazyLoop(this.localCount, temp);
3087                 }
3088                 Prolog prolog = new Prolog(loop);
3089                 this.localCount += 1;
3090                 loop.cmin = curly.cmin;
3091                 loop.cmax = curly.cmax;
3092                 loop.body = head;
3093                 tail.next = loop;
3094                 root = loop;
3095                 return prolog; // Dual return
3096             }
3097         }
3098         throw error("Internal logic error");
3099     }
3100 
3101     /**
3102      * Create group head and tail nodes using double return. If the group is
3103      * created with anonymous true then it is a pure group and should not
3104      * affect group counting.
3105      */
3106     private Node createGroup(boolean anonymous) {
3107         int localIndex = localCount++;
3108         int groupIndex = 0;
3109         if (!anonymous)
3110             groupIndex = capturingGroupCount++;
3111         GroupHead head = new GroupHead(localIndex);
3112         root = new GroupTail(localIndex, groupIndex);
3113 
3114         // for debug/print only, head.match does NOT need the "tail" info
3115         head.tail = (GroupTail)root;
3116 
3117         if (!anonymous && groupIndex < 10)
3118             groupNodes[groupIndex] = head;
3119         return head;
3120     }
3121 
3122     @SuppressWarnings("fallthrough")
3123     /**
3124      * Parses inlined match flags and set them appropriately.
3125      */
3126     private void addFlag() {
3127         int ch = peek();
3128         for (;;) {
3129             switch (ch) {
3130             case 'i':
3131                 flags |= CASE_INSENSITIVE;
3132                 break;
3133             case 'm':
3134                 flags |= MULTILINE;
3135                 break;
3136             case 's':
3137                 flags |= DOTALL;
3138                 break;
3139             case 'd':
3140                 flags |= UNIX_LINES;
3141                 break;
3142             case 'u':
3143                 flags |= UNICODE_CASE;
3144                 break;
3145             case 'c':
3146                 flags |= CANON_EQ;
3147                 break;
3148             case 'x':
3149                 flags |= COMMENTS;
3150                 break;
3151             case 'U':
3152                 flags |= (UNICODE_CHARACTER_CLASS | UNICODE_CASE);
3153                 break;
3154             case '-': // subFlag then fall through
3155                 ch = next();
3156                 subFlag();
3157             default:
3158                 return;
3159             }
3160             ch = next();
3161         }
3162     }
3163 
3164     @SuppressWarnings("fallthrough")
3165     /**
3166      * Parses the second part of inlined match flags and turns off
3167      * flags appropriately.
3168      */
3169     private void subFlag() {
3170         int ch = peek();
3171         for (;;) {
3172             switch (ch) {
3173             case 'i':
3174                 flags &= ~CASE_INSENSITIVE;
3175                 break;
3176             case 'm':
3177                 flags &= ~MULTILINE;
3178                 break;
3179             case 's':
3180                 flags &= ~DOTALL;
3181                 break;
3182             case 'd':
3183                 flags &= ~UNIX_LINES;
3184                 break;
3185             case 'u':
3186                 flags &= ~UNICODE_CASE;
3187                 break;
3188             case 'c':
3189                 flags &= ~CANON_EQ;
3190                 break;
3191             case 'x':
3192                 flags &= ~COMMENTS;
3193                 break;
3194             case 'U':
3195                 flags &= ~(UNICODE_CHARACTER_CLASS | UNICODE_CASE);
3196                 break;
3197             default:
3198                 return;
3199             }
3200             ch = next();
3201         }
3202     }
3203 
3204     static final int MAX_REPS   = 0x7FFFFFFF;
3205 
3206     static enum Qtype {
3207         GREEDY, LAZY, POSSESSIVE, INDEPENDENT
3208     }
3209 
3210     private Node curly(Node prev, int cmin) {
3211         int ch = next();
3212         if (ch == '?') {
3213             next();
3214             return new Curly(prev, cmin, MAX_REPS, Qtype.LAZY);
3215         } else if (ch == '+') {
3216             next();
3217             return new Curly(prev, cmin, MAX_REPS, Qtype.POSSESSIVE);
3218         }
3219         if (prev instanceof BmpCharProperty) {
3220             return new BmpCharPropertyGreedy((BmpCharProperty)prev, cmin);
3221         } else if (prev instanceof CharProperty) {
3222             return new CharPropertyGreedy((CharProperty)prev, cmin);
3223         }
3224         return new Curly(prev, cmin, MAX_REPS, Qtype.GREEDY);
3225     }
3226 
3227     /**
3228      * Processes repetition. If the next character peeked is a quantifier
3229      * then new nodes must be appended to handle the repetition.
3230      * Prev could be a single or a group, so it could be a chain of nodes.
3231      */
3232     private Node closure(Node prev) {
3233         Node atom;
3234         int ch = peek();
3235         switch (ch) {
3236         case '?':
3237             ch = next();
3238             if (ch == '?') {
3239                 next();
3240                 return new Ques(prev, Qtype.LAZY);
3241             } else if (ch == '+') {
3242                 next();
3243                 return new Ques(prev, Qtype.POSSESSIVE);
3244             }
3245             return new Ques(prev, Qtype.GREEDY);
3246         case '*':
3247             return curly(prev, 0);
3248         case '+':
3249             return curly(prev, 1);
3250         case '{':
3251             ch = temp[cursor+1];
3252             if (ASCII.isDigit(ch)) {
3253                 skip();
3254                 int cmin = 0;
3255                 do {
3256                     cmin = cmin * 10 + (ch - '0');
3257                 } while (ASCII.isDigit(ch = read()));
3258                 int cmax = cmin;
3259                 if (ch == ',') {
3260                     ch = read();
3261                     cmax = MAX_REPS;
3262                     if (ch != '}') {
3263                         cmax = 0;
3264                         while (ASCII.isDigit(ch)) {
3265                             cmax = cmax * 10 + (ch - '0');
3266                             ch = read();
3267                         }
3268                     }
3269                 }
3270                 if (ch != '}')
3271                     throw error("Unclosed counted closure");
3272                 if (((cmin) | (cmax) | (cmax - cmin)) < 0)
3273                     throw error("Illegal repetition range");
3274                 Curly curly;
3275                 ch = peek();
3276                 if (ch == '?') {
3277                     next();
3278                     curly = new Curly(prev, cmin, cmax, Qtype.LAZY);
3279                 } else if (ch == '+') {
3280                     next();
3281                     curly = new Curly(prev, cmin, cmax, Qtype.POSSESSIVE);
3282                 } else {
3283                     curly = new Curly(prev, cmin, cmax, Qtype.GREEDY);
3284                 }
3285                 return curly;
3286             } else {
3287                 throw error("Illegal repetition");
3288             }
3289         default:
3290             return prev;
3291         }
3292     }
3293 
3294     /**
3295      *  Utility method for parsing control escape sequences.
3296      */
3297     private int c() {
3298         if (cursor < patternLength) {
3299             return read() ^ 64;
3300         }
3301         throw error("Illegal control escape sequence");
3302     }
3303 
3304     /**
3305      *  Utility method for parsing octal escape sequences.
3306      */
3307     private int o() {
3308         int n = read();
3309         if (((n-'0')|('7'-n)) >= 0) {
3310             int m = read();
3311             if (((m-'0')|('7'-m)) >= 0) {
3312                 int o = read();
3313                 if ((((o-'0')|('7'-o)) >= 0) && (((n-'0')|('3'-n)) >= 0)) {
3314                     return (n - '0') * 64 + (m - '0') * 8 + (o - '0');
3315                 }
3316                 unread();
3317                 return (n - '0') * 8 + (m - '0');
3318             }
3319             unread();
3320             return (n - '0');
3321         }
3322         throw error("Illegal octal escape sequence");
3323     }
3324 
3325     /**
3326      *  Utility method for parsing hexadecimal escape sequences.
3327      */
3328     private int x() {
3329         int n = read();
3330         if (ASCII.isHexDigit(n)) {
3331             int m = read();
3332             if (ASCII.isHexDigit(m)) {
3333                 return ASCII.toDigit(n) * 16 + ASCII.toDigit(m);
3334             }
3335         } else if (n == '{' && ASCII.isHexDigit(peek())) {
3336             int ch = 0;
3337             while (ASCII.isHexDigit(n = read())) {
3338                 ch = (ch << 4) + ASCII.toDigit(n);
3339                 if (ch > Character.MAX_CODE_POINT)
3340                     throw error("Hexadecimal codepoint is too big");
3341             }
3342             if (n != '}')
3343                 throw error("Unclosed hexadecimal escape sequence");
3344             return ch;
3345         }
3346         throw error("Illegal hexadecimal escape sequence");
3347     }
3348 
3349     /**
3350      *  Utility method for parsing unicode escape sequences.
3351      */
3352     private int cursor() {
3353         return cursor;
3354     }
3355 
3356     private void setcursor(int pos) {
3357         cursor = pos;
3358     }
3359 
3360     private int uxxxx() {
3361         int n = 0;
3362         for (int i = 0; i < 4; i++) {
3363             int ch = read();
3364             if (!ASCII.isHexDigit(ch)) {
3365                 throw error("Illegal Unicode escape sequence");
3366             }
3367             n = n * 16 + ASCII.toDigit(ch);
3368         }
3369         return n;
3370     }
3371 
3372     private int u() {
3373         int n = uxxxx();
3374         if (Character.isHighSurrogate((char)n)) {
3375             int cur = cursor();
3376             if (read() == '\\' && read() == 'u') {
3377                 int n2 = uxxxx();
3378                 if (Character.isLowSurrogate((char)n2))
3379                     return Character.toCodePoint((char)n, (char)n2);
3380             }
3381             setcursor(cur);
3382         }
3383         return n;
3384     }
3385 
3386     private int N() {
3387         if (read() == '{') {
3388             int i = cursor;
3389             while (cursor < patternLength && read() != '}') {}
3390             if (cursor > patternLength)
3391                 throw error("Unclosed character name escape sequence");
3392             String name = new String(temp, i, cursor - i - 1);
3393             try {
3394                 return Character.codePointOf(name);
3395             } catch (IllegalArgumentException x) {
3396                 throw error("Unknown character name [" + name + "]");
3397             }
3398         }
3399         throw error("Illegal character name escape sequence");
3400     }
3401 
3402     //
3403     // Utility methods for code point support
3404     //
3405     private static final int countChars(CharSequence seq, int index,
3406                                         int lengthInCodePoints) {
3407         // optimization
3408         if (lengthInCodePoints == 1 && !Character.isHighSurrogate(seq.charAt(index))) {
3409             assert (index >= 0 && index < seq.length());
3410             return 1;
3411         }
3412         int length = seq.length();
3413         int x = index;
3414         if (lengthInCodePoints >= 0) {
3415             assert (index >= 0 && index < length);
3416             for (int i = 0; x < length && i < lengthInCodePoints; i++) {
3417                 if (Character.isHighSurrogate(seq.charAt(x++))) {
3418                     if (x < length && Character.isLowSurrogate(seq.charAt(x))) {
3419                         x++;
3420                     }
3421                 }
3422             }
3423             return x - index;
3424         }
3425 
3426         assert (index >= 0 && index <= length);
3427         if (index == 0) {
3428             return 0;
3429         }
3430         int len = -lengthInCodePoints;
3431         for (int i = 0; x > 0 && i < len; i++) {
3432             if (Character.isLowSurrogate(seq.charAt(--x))) {
3433                 if (x > 0 && Character.isHighSurrogate(seq.charAt(x-1))) {
3434                     x--;
3435                 }
3436             }
3437         }
3438         return index - x;
3439     }
3440 
3441     private static final int countCodePoints(CharSequence seq) {
3442         int length = seq.length();
3443         int n = 0;
3444         for (int i = 0; i < length; ) {
3445             n++;
3446             if (Character.isHighSurrogate(seq.charAt(i++))) {
3447                 if (i < length && Character.isLowSurrogate(seq.charAt(i))) {
3448                     i++;
3449                 }
3450             }
3451         }
3452         return n;
3453     }
3454 
3455     /**
3456      *  Creates a bit vector for matching Latin-1 values. A normal BitClass
3457      *  never matches values above Latin-1, and a complemented BitClass always
3458      *  matches values above Latin-1.
3459      */
3460     static final class BitClass extends BmpCharProperty {
3461         final boolean[] bits;
3462         BitClass() {
3463             this(new boolean[256]);
3464         }
3465         private BitClass(boolean[] bits) {
3466             super( ch -> ch < 256 && bits[ch]);
3467             this.bits = bits;
3468         }
3469         BitClass add(int c, int flags) {
3470             assert c >= 0 && c <= 255;
3471             if ((flags & CASE_INSENSITIVE) != 0) {
3472                 if (ASCII.isAscii(c)) {
3473                     bits[ASCII.toUpper(c)] = true;
3474                     bits[ASCII.toLower(c)] = true;
3475                 } else if ((flags & UNICODE_CASE) != 0) {
3476                     bits[Character.toLowerCase(c)] = true;
3477                     bits[Character.toUpperCase(c)] = true;
3478                 }
3479             }
3480             bits[c] = true;
3481             return this;
3482         }
3483     }
3484 
3485     /**
3486      *  Utility method for creating a string slice matcher.
3487      */
3488     private Node newSlice(int[] buf, int count, boolean hasSupplementary) {
3489         int[] tmp = new int[count];
3490         if (has(CASE_INSENSITIVE)) {
3491             if (has(UNICODE_CASE)) {
3492                 for (int i = 0; i < count; i++) {
3493                     tmp[i] = Character.toLowerCase(
3494                                  Character.toUpperCase(buf[i]));
3495                 }
3496                 return hasSupplementary? new SliceUS(tmp) : new SliceU(tmp);
3497             }
3498             for (int i = 0; i < count; i++) {
3499                 tmp[i] = ASCII.toLower(buf[i]);
3500             }
3501             return hasSupplementary? new SliceIS(tmp) : new SliceI(tmp);
3502         }
3503         for (int i = 0; i < count; i++) {
3504             tmp[i] = buf[i];
3505         }
3506         return hasSupplementary ? new SliceS(tmp) : new Slice(tmp);
3507     }
3508 
3509     /**
3510      * The following classes are the building components of the object
3511      * tree that represents a compiled regular expression. The object tree
3512      * is made of individual elements that handle constructs in the Pattern.
3513      * Each type of object knows how to match its equivalent construct with
3514      * the match() method.
3515      */
3516 
3517     /**
3518      * Base class for all node classes. Subclasses should override the match()
3519      * method as appropriate. This class is an accepting node, so its match()
3520      * always returns true.
3521      */
3522     static class Node extends Object {
3523         Node next;
3524         Node() {
3525             next = Pattern.accept;
3526         }
3527         /**
3528          * This method implements the classic accept node.
3529          */
3530         boolean match(Matcher matcher, int i, CharSequence seq) {
3531             matcher.last = i;
3532             matcher.groups[0] = matcher.first;
3533             matcher.groups[1] = matcher.last;
3534             return true;
3535         }
3536         /**
3537          * This method is good for all zero length assertions.
3538          */
3539         boolean study(TreeInfo info) {
3540             if (next != null) {
3541                 return next.study(info);
3542             } else {
3543                 return info.deterministic;
3544             }
3545         }
3546     }
3547 
3548     static class LastNode extends Node {
3549         /**
3550          * This method implements the classic accept node with
3551          * the addition of a check to see if the match occurred
3552          * using all of the input.
3553          */
3554         boolean match(Matcher matcher, int i, CharSequence seq) {
3555             if (matcher.acceptMode == Matcher.ENDANCHOR && i != matcher.to)
3556                 return false;
3557             matcher.last = i;
3558             matcher.groups[0] = matcher.first;
3559             matcher.groups[1] = matcher.last;
3560             return true;
3561         }
3562     }
3563 
3564     /**
3565      * Used for REs that can start anywhere within the input string.
3566      * This basically tries to match repeatedly at each spot in the
3567      * input string, moving forward after each try. An anchored search
3568      * or a BnM will bypass this node completely.
3569      */
3570     static class Start extends Node {
3571         int minLength;
3572         Start(Node node) {
3573             this.next = node;
3574             TreeInfo info = new TreeInfo();
3575             next.study(info);
3576             minLength = info.minLength;
3577         }
3578         boolean match(Matcher matcher, int i, CharSequence seq) {
3579             if (i > matcher.to - minLength) {
3580                 matcher.hitEnd = true;
3581                 return false;
3582             }
3583             int guard = matcher.to - minLength;
3584             for (; i <= guard; i++) {
3585                 if (next.match(matcher, i, seq)) {
3586                     matcher.first = i;
3587                     matcher.groups[0] = matcher.first;
3588                     matcher.groups[1] = matcher.last;
3589                     return true;
3590                 }
3591             }
3592             matcher.hitEnd = true;
3593             return false;
3594         }
3595         boolean study(TreeInfo info) {
3596             next.study(info);
3597             info.maxValid = false;
3598             info.deterministic = false;
3599             return false;
3600         }
3601     }
3602 
3603     /*
3604      * StartS supports supplementary characters, including unpaired surrogates.
3605      */
3606     static final class StartS extends Start {
3607         StartS(Node node) {
3608             super(node);
3609         }
3610         boolean match(Matcher matcher, int i, CharSequence seq) {
3611             if (i > matcher.to - minLength) {
3612                 matcher.hitEnd = true;
3613                 return false;
3614             }
3615             int guard = matcher.to - minLength;
3616             while (i <= guard) {
3617                 //if ((ret = next.match(matcher, i, seq)) || i == guard)
3618                 if (next.match(matcher, i, seq)) {
3619                     matcher.first = i;
3620                     matcher.groups[0] = matcher.first;
3621                     matcher.groups[1] = matcher.last;
3622                     return true;
3623                 }
3624                 if (i == guard)
3625                     break;
3626                 // Optimization to move to the next character. This is
3627                 // faster than countChars(seq, i, 1).
3628                 if (Character.isHighSurrogate(seq.charAt(i++))) {
3629                     if (i < seq.length() &&
3630                         Character.isLowSurrogate(seq.charAt(i))) {
3631                         i++;
3632                     }
3633                 }
3634             }
3635             matcher.hitEnd = true;
3636             return false;
3637         }
3638     }
3639 
3640     /**
3641      * Node to anchor at the beginning of input. This object implements the
3642      * match for a \A sequence, and the caret anchor will use this if not in
3643      * multiline mode.
3644      */
3645     static final class Begin extends Node {
3646         boolean match(Matcher matcher, int i, CharSequence seq) {
3647             int fromIndex = (matcher.anchoringBounds) ?
3648                 matcher.from : 0;
3649             if (i == fromIndex && next.match(matcher, i, seq)) {
3650                 matcher.first = i;
3651                 matcher.groups[0] = i;
3652                 matcher.groups[1] = matcher.last;
3653                 return true;
3654             } else {
3655                 return false;
3656             }
3657         }
3658     }
3659 
3660     /**
3661      * Node to anchor at the end of input. This is the absolute end, so this
3662      * should not match at the last newline before the end as $ will.
3663      */
3664     static final class End extends Node {
3665         boolean match(Matcher matcher, int i, CharSequence seq) {
3666             int endIndex = (matcher.anchoringBounds) ?
3667                 matcher.to : matcher.getTextLength();
3668             if (i == endIndex) {
3669                 matcher.hitEnd = true;
3670                 return next.match(matcher, i, seq);
3671             }
3672             return false;
3673         }
3674     }
3675 
3676     /**
3677      * Node to anchor at the beginning of a line. This is essentially the
3678      * object to match for the multiline ^.
3679      */
3680     static final class Caret extends Node {
3681         boolean match(Matcher matcher, int i, CharSequence seq) {
3682             int startIndex = matcher.from;
3683             int endIndex = matcher.to;
3684             if (!matcher.anchoringBounds) {
3685                 startIndex = 0;
3686                 endIndex = matcher.getTextLength();
3687             }
3688             // Perl does not match ^ at end of input even after newline
3689             if (i == endIndex) {
3690                 matcher.hitEnd = true;
3691                 return false;
3692             }
3693             if (i > startIndex) {
3694                 char ch = seq.charAt(i-1);
3695                 if (ch != '\n' && ch != '\r'
3696                     && (ch|1) != '\u2029'
3697                     && ch != '\u0085' ) {
3698                     return false;
3699                 }
3700                 // Should treat /r/n as one newline
3701                 if (ch == '\r' && seq.charAt(i) == '\n')
3702                     return false;
3703             }
3704             return next.match(matcher, i, seq);
3705         }
3706     }
3707 
3708     /**
3709      * Node to anchor at the beginning of a line when in unixdot mode.
3710      */
3711     static final class UnixCaret extends Node {
3712         boolean match(Matcher matcher, int i, CharSequence seq) {
3713             int startIndex = matcher.from;
3714             int endIndex = matcher.to;
3715             if (!matcher.anchoringBounds) {
3716                 startIndex = 0;
3717                 endIndex = matcher.getTextLength();
3718             }
3719             // Perl does not match ^ at end of input even after newline
3720             if (i == endIndex) {
3721                 matcher.hitEnd = true;
3722                 return false;
3723             }
3724             if (i > startIndex) {
3725                 char ch = seq.charAt(i-1);
3726                 if (ch != '\n') {
3727                     return false;
3728                 }
3729             }
3730             return next.match(matcher, i, seq);
3731         }
3732     }
3733 
3734     /**
3735      * Node to match the location where the last match ended.
3736      * This is used for the \G construct.
3737      */
3738     static final class LastMatch extends Node {
3739         boolean match(Matcher matcher, int i, CharSequence seq) {
3740             if (i != matcher.oldLast)
3741                 return false;
3742             return next.match(matcher, i, seq);
3743         }
3744     }
3745 
3746     /**
3747      * Node to anchor at the end of a line or the end of input based on the
3748      * multiline mode.
3749      *
3750      * When not in multiline mode, the $ can only match at the very end
3751      * of the input, unless the input ends in a line terminator in which
3752      * it matches right before the last line terminator.
3753      *
3754      * Note that \r\n is considered an atomic line terminator.
3755      *
3756      * Like ^ the $ operator matches at a position, it does not match the
3757      * line terminators themselves.
3758      */
3759     static final class Dollar extends Node {
3760         boolean multiline;
3761         Dollar(boolean mul) {
3762             multiline = mul;
3763         }
3764         boolean match(Matcher matcher, int i, CharSequence seq) {
3765             int endIndex = (matcher.anchoringBounds) ?
3766                 matcher.to : matcher.getTextLength();
3767             if (!multiline) {
3768                 if (i < endIndex - 2)
3769                     return false;
3770                 if (i == endIndex - 2) {
3771                     char ch = seq.charAt(i);
3772                     if (ch != '\r')
3773                         return false;
3774                     ch = seq.charAt(i + 1);
3775                     if (ch != '\n')
3776                         return false;
3777                 }
3778             }
3779             // Matches before any line terminator; also matches at the
3780             // end of input
3781             // Before line terminator:
3782             // If multiline, we match here no matter what
3783             // If not multiline, fall through so that the end
3784             // is marked as hit; this must be a /r/n or a /n
3785             // at the very end so the end was hit; more input
3786             // could make this not match here
3787             if (i < endIndex) {
3788                 char ch = seq.charAt(i);
3789                  if (ch == '\n') {
3790                      // No match between \r\n
3791                      if (i > 0 && seq.charAt(i-1) == '\r')
3792                          return false;
3793                      if (multiline)
3794                          return next.match(matcher, i, seq);
3795                  } else if (ch == '\r' || ch == '\u0085' ||
3796                             (ch|1) == '\u2029') {
3797                      if (multiline)
3798                          return next.match(matcher, i, seq);
3799                  } else { // No line terminator, no match
3800                      return false;
3801                  }
3802             }
3803             // Matched at current end so hit end
3804             matcher.hitEnd = true;
3805             // If a $ matches because of end of input, then more input
3806             // could cause it to fail!
3807             matcher.requireEnd = true;
3808             return next.match(matcher, i, seq);
3809         }
3810         boolean study(TreeInfo info) {
3811             next.study(info);
3812             return info.deterministic;
3813         }
3814     }
3815 
3816     /**
3817      * Node to anchor at the end of a line or the end of input based on the
3818      * multiline mode when in unix lines mode.
3819      */
3820     static final class UnixDollar extends Node {
3821         boolean multiline;
3822         UnixDollar(boolean mul) {
3823             multiline = mul;
3824         }
3825         boolean match(Matcher matcher, int i, CharSequence seq) {
3826             int endIndex = (matcher.anchoringBounds) ?
3827                 matcher.to : matcher.getTextLength();
3828             if (i < endIndex) {
3829                 char ch = seq.charAt(i);
3830                 if (ch == '\n') {
3831                     // If not multiline, then only possible to
3832                     // match at very end or one before end
3833                     if (multiline == false && i != endIndex - 1)
3834                         return false;
3835                     // If multiline return next.match without setting
3836                     // matcher.hitEnd
3837                     if (multiline)
3838                         return next.match(matcher, i, seq);
3839                 } else {
3840                     return false;
3841                 }
3842             }
3843             // Matching because at the end or 1 before the end;
3844             // more input could change this so set hitEnd
3845             matcher.hitEnd = true;
3846             // If a $ matches because of end of input, then more input
3847             // could cause it to fail!
3848             matcher.requireEnd = true;
3849             return next.match(matcher, i, seq);
3850         }
3851         boolean study(TreeInfo info) {
3852             next.study(info);
3853             return info.deterministic;
3854         }
3855     }
3856 
3857     /**
3858      * Node class that matches a Unicode line ending '\R'
3859      */
3860     static final class LineEnding extends Node {
3861         boolean match(Matcher matcher, int i, CharSequence seq) {
3862             // (u+000Du+000A|[u+000Au+000Bu+000Cu+000Du+0085u+2028u+2029])
3863             if (i < matcher.to) {
3864                 int ch = seq.charAt(i);
3865                 if (ch == 0x0A || ch == 0x0B || ch == 0x0C ||
3866                     ch == 0x85 || ch == 0x2028 || ch == 0x2029)
3867                     return next.match(matcher, i + 1, seq);
3868                 if (ch == 0x0D) {
3869                     i++;
3870                     if (i < matcher.to && seq.charAt(i) == 0x0A)
3871                         i++;
3872                     return next.match(matcher, i, seq);
3873                 }
3874             } else {
3875                 matcher.hitEnd = true;
3876             }
3877             return false;
3878         }
3879         boolean study(TreeInfo info) {
3880             info.minLength++;
3881             info.maxLength += 2;
3882             return next.study(info);
3883         }
3884     }
3885 
3886     /**
3887      * Abstract node class to match one character satisfying some
3888      * boolean property.
3889      */
3890     static class CharProperty extends Node {
3891         CharPredicate predicate;
3892 
3893         CharProperty (CharPredicate predicate) {
3894             this.predicate = predicate;
3895         }
3896         boolean match(Matcher matcher, int i, CharSequence seq) {
3897             if (i < matcher.to) {
3898                 int ch = Character.codePointAt(seq, i);
3899                 return predicate.is(ch) &&
3900                        next.match(matcher, i + Character.charCount(ch), seq);
3901             } else {
3902                 matcher.hitEnd = true;
3903                 return false;
3904             }
3905         }
3906         boolean study(TreeInfo info) {
3907             info.minLength++;
3908             info.maxLength++;
3909             return next.study(info);
3910         }
3911     }
3912 
3913     /**
3914      * Optimized version of CharProperty that works only for
3915      * properties never satisfied by Supplementary characters.
3916      */
3917     private static class BmpCharProperty extends CharProperty {
3918         BmpCharProperty (BmpCharPredicate predicate) {
3919             super(predicate);
3920         }
3921         boolean match(Matcher matcher, int i, CharSequence seq) {
3922             if (i < matcher.to) {
3923                 return predicate.is(seq.charAt(i)) &&
3924                        next.match(matcher, i + 1, seq);
3925             } else {
3926                 matcher.hitEnd = true;
3927                 return false;
3928             }
3929         }
3930     }
3931 
3932     private static class NFCCharProperty extends Node {
3933         CharPredicate predicate;
3934         NFCCharProperty (CharPredicate predicate) {
3935             this.predicate = predicate;
3936         }
3937 
3938         boolean match(Matcher matcher, int i, CharSequence seq) {
3939             if (i < matcher.to) {
3940                 int ch0 = Character.codePointAt(seq, i);
3941                 int n = Character.charCount(ch0);
3942                 int j = i + n;
3943                 while (j < matcher.to) {
3944                     int ch1 = Character.codePointAt(seq, j);
3945                     if (Grapheme.isBoundary(ch0, ch1))
3946                         break;
3947                     ch0 = ch1;
3948                     j += Character.charCount(ch1);
3949                 }
3950                 if (i + n == j) {    // single, assume nfc cp
3951                     if (predicate.is(ch0))
3952                         return next.match(matcher, j, seq);
3953                 } else {
3954                     while (i + n < j) {
3955                         String nfc = Normalizer.normalize(
3956                             seq.toString().substring(i, j), Normalizer.Form.NFC);
3957                         if (nfc.codePointCount(0, nfc.length()) == 1) {
3958                             if (predicate.is(nfc.codePointAt(0)) &&
3959                                 next.match(matcher, j, seq)) {
3960                                 return true;
3961                             }
3962                         }
3963 
3964                         ch0 = Character.codePointBefore(seq, j);
3965                         j -= Character.charCount(ch0);
3966                     }
3967                 }
3968                 if (j < matcher.to)
3969                     return false;
3970             }
3971             matcher.hitEnd = true;
3972             return false;
3973         }
3974 
3975         boolean study(TreeInfo info) {
3976             info.minLength++;
3977             info.deterministic = false;
3978             return next.study(info);
3979         }
3980     }
3981 
3982     /**
3983      * Node class that matches an unicode extended grapheme cluster
3984      */
3985     static class XGrapheme extends Node {
3986         boolean match(Matcher matcher, int i, CharSequence seq) {
3987             if (i < matcher.to) {
3988                 int ch0 = Character.codePointAt(seq, i);
3989                     i += Character.charCount(ch0);
3990                 while (i < matcher.to) {
3991                     int ch1 = Character.codePointAt(seq, i);
3992                     if (Grapheme.isBoundary(ch0, ch1))
3993                         break;
3994                     ch0 = ch1;
3995                     i += Character.charCount(ch1);
3996                 }
3997                 return next.match(matcher, i, seq);
3998             }
3999             matcher.hitEnd = true;
4000             return false;
4001         }
4002 
4003         boolean study(TreeInfo info) {
4004             info.minLength++;
4005             info.deterministic = false;
4006             return next.study(info);
4007         }
4008     }
4009 
4010     /**
4011      * Node class that handles grapheme boundaries
4012      */
4013     static class GraphemeBound extends Node {
4014         boolean match(Matcher matcher, int i, CharSequence seq) {
4015             int startIndex = matcher.from;
4016             int endIndex = matcher.to;
4017             if (matcher.transparentBounds) {
4018                 startIndex = 0;
4019                 endIndex = matcher.getTextLength();
4020             }
4021             if (i == startIndex) {
4022                 return next.match(matcher, i, seq);
4023             }
4024             if (i < endIndex) {
4025                 if (Character.isSurrogatePair(seq.charAt(i-1), seq.charAt(i)) ||
4026                     !Grapheme.isBoundary(Character.codePointBefore(seq, i),
4027                                          Character.codePointAt(seq, i))) {
4028                     return false;
4029                 }
4030             } else {
4031                 matcher.hitEnd = true;
4032                 matcher.requireEnd = true;
4033             }
4034             return next.match(matcher, i, seq);
4035         }
4036     }
4037 
4038     /**
4039      * Base class for all Slice nodes
4040      */
4041     static class SliceNode extends Node {
4042         int[] buffer;
4043         SliceNode(int[] buf) {
4044             buffer = buf;
4045         }
4046         boolean study(TreeInfo info) {
4047             info.minLength += buffer.length;
4048             info.maxLength += buffer.length;
4049             return next.study(info);
4050         }
4051     }
4052 
4053     /**
4054      * Node class for a case sensitive/BMP-only sequence of literal
4055      * characters.
4056      */
4057     static class Slice extends SliceNode {
4058         Slice(int[] buf) {
4059             super(buf);
4060         }
4061         boolean match(Matcher matcher, int i, CharSequence seq) {
4062             int[] buf = buffer;
4063             int len = buf.length;
4064             for (int j=0; j<len; j++) {
4065                 if ((i+j) >= matcher.to) {
4066                     matcher.hitEnd = true;
4067                     return false;
4068                 }
4069                 if (buf[j] != seq.charAt(i+j))
4070                     return false;
4071             }
4072             return next.match(matcher, i+len, seq);
4073         }
4074     }
4075 
4076     /**
4077      * Node class for a case_insensitive/BMP-only sequence of literal
4078      * characters.
4079      */
4080     static class SliceI extends SliceNode {
4081         SliceI(int[] buf) {
4082             super(buf);
4083         }
4084         boolean match(Matcher matcher, int i, CharSequence seq) {
4085             int[] buf = buffer;
4086             int len = buf.length;
4087             for (int j=0; j<len; j++) {
4088                 if ((i+j) >= matcher.to) {
4089                     matcher.hitEnd = true;
4090                     return false;
4091                 }
4092                 int c = seq.charAt(i+j);
4093                 if (buf[j] != c &&
4094                     buf[j] != ASCII.toLower(c))
4095                     return false;
4096             }
4097             return next.match(matcher, i+len, seq);
4098         }
4099     }
4100 
4101     /**
4102      * Node class for a unicode_case_insensitive/BMP-only sequence of
4103      * literal characters. Uses unicode case folding.
4104      */
4105     static final class SliceU extends SliceNode {
4106         SliceU(int[] buf) {
4107             super(buf);
4108         }
4109         boolean match(Matcher matcher, int i, CharSequence seq) {
4110             int[] buf = buffer;
4111             int len = buf.length;
4112             for (int j=0; j<len; j++) {
4113                 if ((i+j) >= matcher.to) {
4114                     matcher.hitEnd = true;
4115                     return false;
4116                 }
4117                 int c = seq.charAt(i+j);
4118                 if (buf[j] != c &&
4119                     buf[j] != Character.toLowerCase(Character.toUpperCase(c)))
4120                     return false;
4121             }
4122             return next.match(matcher, i+len, seq);
4123         }
4124     }
4125 
4126     /**
4127      * Node class for a case sensitive sequence of literal characters
4128      * including supplementary characters.
4129      */
4130     static final class SliceS extends Slice {
4131         SliceS(int[] buf) {
4132             super(buf);
4133         }
4134         boolean match(Matcher matcher, int i, CharSequence seq) {
4135             int[] buf = buffer;
4136             int x = i;
4137             for (int j = 0; j < buf.length; j++) {
4138                 if (x >= matcher.to) {
4139                     matcher.hitEnd = true;
4140                     return false;
4141                 }
4142                 int c = Character.codePointAt(seq, x);
4143                 if (buf[j] != c)
4144                     return false;
4145                 x += Character.charCount(c);
4146                 if (x > matcher.to) {
4147                     matcher.hitEnd = true;
4148                     return false;
4149                 }
4150             }
4151             return next.match(matcher, x, seq);
4152         }
4153     }
4154 
4155     /**
4156      * Node class for a case insensitive sequence of literal characters
4157      * including supplementary characters.
4158      */
4159     static class SliceIS extends SliceNode {
4160         SliceIS(int[] buf) {
4161             super(buf);
4162         }
4163         int toLower(int c) {
4164             return ASCII.toLower(c);
4165         }
4166         boolean match(Matcher matcher, int i, CharSequence seq) {
4167             int[] buf = buffer;
4168             int x = i;
4169             for (int j = 0; j < buf.length; j++) {
4170                 if (x >= matcher.to) {
4171                     matcher.hitEnd = true;
4172                     return false;
4173                 }
4174                 int c = Character.codePointAt(seq, x);
4175                 if (buf[j] != c && buf[j] != toLower(c))
4176                     return false;
4177                 x += Character.charCount(c);
4178                 if (x > matcher.to) {
4179                     matcher.hitEnd = true;
4180                     return false;
4181                 }
4182             }
4183             return next.match(matcher, x, seq);
4184         }
4185     }
4186 
4187     /**
4188      * Node class for a case insensitive sequence of literal characters.
4189      * Uses unicode case folding.
4190      */
4191     static final class SliceUS extends SliceIS {
4192         SliceUS(int[] buf) {
4193             super(buf);
4194         }
4195         int toLower(int c) {
4196             return Character.toLowerCase(Character.toUpperCase(c));
4197         }
4198     }
4199 
4200     /**
4201      * The 0 or 1 quantifier. This one class implements all three types.
4202      */
4203     static final class Ques extends Node {
4204         Node atom;
4205         Qtype type;
4206         Ques(Node node, Qtype type) {
4207             this.atom = node;
4208             this.type = type;
4209         }
4210         boolean match(Matcher matcher, int i, CharSequence seq) {
4211             switch (type) {
4212             case GREEDY:
4213                 return (atom.match(matcher, i, seq) && next.match(matcher, matcher.last, seq))
4214                     || next.match(matcher, i, seq);
4215             case LAZY:
4216                 return next.match(matcher, i, seq)
4217                     || (atom.match(matcher, i, seq) && next.match(matcher, matcher.last, seq));
4218             case POSSESSIVE:
4219                 if (atom.match(matcher, i, seq)) i = matcher.last;
4220                 return next.match(matcher, i, seq);
4221             default:
4222                 return atom.match(matcher, i, seq) && next.match(matcher, matcher.last, seq);
4223             }
4224         }
4225         boolean study(TreeInfo info) {
4226             if (type != Qtype.INDEPENDENT) {
4227                 int minL = info.minLength;
4228                 atom.study(info);
4229                 info.minLength = minL;
4230                 info.deterministic = false;
4231                 return next.study(info);
4232             } else {
4233                 atom.study(info);
4234                 return next.study(info);
4235             }
4236         }
4237     }
4238 
4239     /**
4240      * Handles the greedy style repetition with the minimum either be
4241      * 0 or 1 and the maximum be MAX_REPS, for * and + quantifier.
4242      */
4243     static class CharPropertyGreedy extends Node {
4244         final CharPredicate predicate;
4245         final int cmin;
4246 
4247         CharPropertyGreedy(CharProperty cp, int cmin) {
4248             this.predicate = cp.predicate;
4249             this.cmin = cmin;
4250         }
4251         boolean match(Matcher matcher, int i,  CharSequence seq) {
4252             int n = 0;
4253             int to = matcher.to;
4254             // greedy, all the way down
4255             while (i < to) {
4256                 int ch = Character.codePointAt(seq, i);
4257                 if (!predicate.is(ch))
4258                    break;
4259                 i += Character.charCount(ch);
4260                 n++;
4261             }
4262             if (i >= to) {
4263                 matcher.hitEnd = true;
4264             }
4265             while (n >= cmin) {
4266                 if (next.match(matcher, i, seq))
4267                     return true;
4268                 if (n == cmin)
4269                     return false;
4270                  // backing off if match fails
4271                 int ch = Character.codePointBefore(seq, i);
4272                 i -= Character.charCount(ch);
4273                 n--;
4274             }
4275             return false;
4276         }
4277 
4278         boolean study(TreeInfo info) {
4279             info.minLength += cmin;
4280             if (info.maxValid) {
4281                 info.maxLength += MAX_REPS;
4282             }
4283             info.deterministic = false;
4284             return next.study(info);
4285         }
4286     }
4287 
4288     static final class BmpCharPropertyGreedy extends CharPropertyGreedy {
4289 
4290         BmpCharPropertyGreedy(BmpCharProperty bcp, int cmin) {
4291             super(bcp, cmin);
4292         }
4293 
4294         boolean match(Matcher matcher, int i,  CharSequence seq) {
4295             int n = 0;
4296             int to = matcher.to;
4297             while (i < to && predicate.is(seq.charAt(i))) {
4298                 i++; n++;
4299             }
4300             if (i >= to) {
4301                 matcher.hitEnd = true;
4302             }
4303             while (n >= cmin) {
4304                 if (next.match(matcher, i, seq))
4305                     return true;
4306                 i--; n--;  // backing off if match fails
4307             }
4308             return false;
4309         }
4310     }
4311 
4312     /**
4313      * Handles the curly-brace style repetition with a specified minimum and
4314      * maximum occurrences. The * quantifier is handled as a special case.
4315      * This class handles the three types.
4316      */
4317     static final class Curly extends Node {
4318         Node atom;
4319         Qtype type;
4320         int cmin;
4321         int cmax;
4322 
4323         Curly(Node node, int cmin, int cmax, Qtype type) {
4324             this.atom = node;
4325             this.type = type;
4326             this.cmin = cmin;
4327             this.cmax = cmax;
4328         }
4329         boolean match(Matcher matcher, int i, CharSequence seq) {
4330             int j;
4331             for (j = 0; j < cmin; j++) {
4332                 if (atom.match(matcher, i, seq)) {
4333                     i = matcher.last;
4334                     continue;
4335                 }
4336                 return false;
4337             }
4338             if (type == Qtype.GREEDY)
4339                 return match0(matcher, i, j, seq);
4340             else if (type == Qtype.LAZY)
4341                 return match1(matcher, i, j, seq);
4342             else
4343                 return match2(matcher, i, j, seq);
4344         }
4345         // Greedy match.
4346         // i is the index to start matching at
4347         // j is the number of atoms that have matched
4348         boolean match0(Matcher matcher, int i, int j, CharSequence seq) {
4349             if (j >= cmax) {
4350                 // We have matched the maximum... continue with the rest of
4351                 // the regular expression
4352                 return next.match(matcher, i, seq);
4353             }
4354             int backLimit = j;
4355             while (atom.match(matcher, i, seq)) {
4356                 // k is the length of this match
4357                 int k = matcher.last - i;
4358                 if (k == 0) // Zero length match
4359                     break;
4360                 // Move up index and number matched
4361                 i = matcher.last;
4362                 j++;
4363                 // We are greedy so match as many as we can
4364                 while (j < cmax) {
4365                     if (!atom.match(matcher, i, seq))
4366                         break;
4367                     if (i + k != matcher.last) {
4368                         if (match0(matcher, matcher.last, j+1, seq))
4369                             return true;
4370                         break;
4371                     }
4372                     i += k;
4373                     j++;
4374                 }
4375                 // Handle backing off if match fails
4376                 while (j >= backLimit) {
4377                    if (next.match(matcher, i, seq))
4378                         return true;
4379                     i -= k;
4380                     j--;
4381                 }
4382                 return false;
4383             }
4384             return next.match(matcher, i, seq);
4385         }
4386         // Reluctant match. At this point, the minimum has been satisfied.
4387         // i is the index to start matching at
4388         // j is the number of atoms that have matched
4389         boolean match1(Matcher matcher, int i, int j, CharSequence seq) {
4390             for (;;) {
4391                 // Try finishing match without consuming any more
4392                 if (next.match(matcher, i, seq))
4393                     return true;
4394                 // At the maximum, no match found
4395                 if (j >= cmax)
4396                     return false;
4397                 // Okay, must try one more atom
4398                 if (!atom.match(matcher, i, seq))
4399                     return false;
4400                 // If we haven't moved forward then must break out
4401                 if (i == matcher.last)
4402                     return false;
4403                 // Move up index and number matched
4404                 i = matcher.last;
4405                 j++;
4406             }
4407         }
4408         boolean match2(Matcher matcher, int i, int j, CharSequence seq) {
4409             for (; j < cmax; j++) {
4410                 if (!atom.match(matcher, i, seq))
4411                     break;
4412                 if (i == matcher.last)
4413                     break;
4414                 i = matcher.last;
4415             }
4416             return next.match(matcher, i, seq);
4417         }
4418         boolean study(TreeInfo info) {
4419             // Save original info
4420             int minL = info.minLength;
4421             int maxL = info.maxLength;
4422             boolean maxV = info.maxValid;
4423             boolean detm = info.deterministic;
4424             info.reset();
4425 
4426             atom.study(info);
4427 
4428             int temp = info.minLength * cmin + minL;
4429             if (temp < minL) {
4430                 temp = 0xFFFFFFF; // arbitrary large number
4431             }
4432             info.minLength = temp;
4433 
4434             if (maxV & info.maxValid) {
4435                 temp = info.maxLength * cmax + maxL;
4436                 info.maxLength = temp;
4437                 if (temp < maxL) {
4438                     info.maxValid = false;
4439                 }
4440             } else {
4441                 info.maxValid = false;
4442             }
4443 
4444             if (info.deterministic && cmin == cmax)
4445                 info.deterministic = detm;
4446             else
4447                 info.deterministic = false;
4448             return next.study(info);
4449         }
4450     }
4451 
4452     /**
4453      * Handles the curly-brace style repetition with a specified minimum and
4454      * maximum occurrences in deterministic cases. This is an iterative
4455      * optimization over the Prolog and Loop system which would handle this
4456      * in a recursive way. The * quantifier is handled as a special case.
4457      * If capture is true then this class saves group settings and ensures
4458      * that groups are unset when backing off of a group match.
4459      */
4460     static final class GroupCurly extends Node {
4461         Node atom;
4462         Qtype type;
4463         int cmin;
4464         int cmax;
4465         int localIndex;
4466         int groupIndex;
4467         boolean capture;
4468 
4469         GroupCurly(Node node, int cmin, int cmax, Qtype type, int local,
4470                    int group, boolean capture) {
4471             this.atom = node;
4472             this.type = type;
4473             this.cmin = cmin;
4474             this.cmax = cmax;
4475             this.localIndex = local;
4476             this.groupIndex = group;
4477             this.capture = capture;
4478         }
4479         boolean match(Matcher matcher, int i, CharSequence seq) {
4480             int[] groups = matcher.groups;
4481             int[] locals = matcher.locals;
4482             int save0 = locals[localIndex];
4483             int save1 = 0;
4484             int save2 = 0;
4485 
4486             if (capture) {
4487                 save1 = groups[groupIndex];
4488                 save2 = groups[groupIndex+1];
4489             }
4490 
4491             // Notify GroupTail there is no need to setup group info
4492             // because it will be set here
4493             locals[localIndex] = -1;
4494 
4495             boolean ret = true;
4496             for (int j = 0; j < cmin; j++) {
4497                 if (atom.match(matcher, i, seq)) {
4498                     if (capture) {
4499                         groups[groupIndex] = i;
4500                         groups[groupIndex+1] = matcher.last;
4501                     }
4502                     i = matcher.last;
4503                 } else {
4504                     ret = false;
4505                     break;
4506                 }
4507             }
4508             if (ret) {
4509                 if (type == Qtype.GREEDY) {
4510                     ret = match0(matcher, i, cmin, seq);
4511                 } else if (type == Qtype.LAZY) {
4512                     ret = match1(matcher, i, cmin, seq);
4513                 } else {
4514                     ret = match2(matcher, i, cmin, seq);
4515                 }
4516             }
4517             if (!ret) {
4518                 locals[localIndex] = save0;
4519                 if (capture) {
4520                     groups[groupIndex] = save1;
4521                     groups[groupIndex+1] = save2;
4522                 }
4523             }
4524             return ret;
4525         }
4526         // Aggressive group match
4527         boolean match0(Matcher matcher, int i, int j, CharSequence seq) {
4528             // don't back off passing the starting "j"
4529             int min = j;
4530             int[] groups = matcher.groups;
4531             int save0 = 0;
4532             int save1 = 0;
4533             if (capture) {
4534                 save0 = groups[groupIndex];
4535                 save1 = groups[groupIndex+1];
4536             }
4537             for (;;) {
4538                 if (j >= cmax)
4539                     break;
4540                 if (!atom.match(matcher, i, seq))
4541                     break;
4542                 int k = matcher.last - i;
4543                 if (k <= 0) {
4544                     if (capture) {
4545                         groups[groupIndex] = i;
4546                         groups[groupIndex+1] = i + k;
4547                     }
4548                     i = i + k;
4549                     break;
4550                 }
4551                 for (;;) {
4552                     if (capture) {
4553                         groups[groupIndex] = i;
4554                         groups[groupIndex+1] = i + k;
4555                     }
4556                     i = i + k;
4557                     if (++j >= cmax)
4558                         break;
4559                     if (!atom.match(matcher, i, seq))
4560                         break;
4561                     if (i + k != matcher.last) {
4562                         if (match0(matcher, i, j, seq))
4563                             return true;
4564                         break;
4565                     }
4566                 }
4567                 while (j > min) {
4568                     if (next.match(matcher, i, seq)) {
4569                         if (capture) {
4570                             groups[groupIndex+1] = i;
4571                             groups[groupIndex] = i - k;
4572                         }
4573                         return true;
4574                     }
4575                     // backing off
4576                     i = i - k;
4577                     if (capture) {
4578                         groups[groupIndex+1] = i;
4579                         groups[groupIndex] = i - k;
4580                     }
4581                     j--;
4582 
4583                 }
4584                 break;
4585             }
4586             if (capture) {
4587                 groups[groupIndex] = save0;
4588                 groups[groupIndex+1] = save1;
4589             }
4590             return next.match(matcher, i, seq);
4591         }
4592         // Reluctant matching
4593         boolean match1(Matcher matcher, int i, int j, CharSequence seq) {
4594             for (;;) {
4595                 if (next.match(matcher, i, seq))
4596                     return true;
4597                 if (j >= cmax)
4598                     return false;
4599                 if (!atom.match(matcher, i, seq))
4600                     return false;
4601                 if (i == matcher.last)
4602                     return false;
4603                 if (capture) {
4604                     matcher.groups[groupIndex] = i;
4605                     matcher.groups[groupIndex+1] = matcher.last;
4606                 }
4607                 i = matcher.last;
4608                 j++;
4609             }
4610         }
4611         // Possessive matching
4612         boolean match2(Matcher matcher, int i, int j, CharSequence seq) {
4613             for (; j < cmax; j++) {
4614                 if (!atom.match(matcher, i, seq)) {
4615                     break;
4616                 }
4617                 if (capture) {
4618                     matcher.groups[groupIndex] = i;
4619                     matcher.groups[groupIndex+1] = matcher.last;
4620                 }
4621                 if (i == matcher.last) {
4622                     break;
4623                 }
4624                 i = matcher.last;
4625             }
4626             return next.match(matcher, i, seq);
4627         }
4628         boolean study(TreeInfo info) {
4629             // Save original info
4630             int minL = info.minLength;
4631             int maxL = info.maxLength;
4632             boolean maxV = info.maxValid;
4633             boolean detm = info.deterministic;
4634             info.reset();
4635 
4636             atom.study(info);
4637 
4638             int temp = info.minLength * cmin + minL;
4639             if (temp < minL) {
4640                 temp = 0xFFFFFFF; // Arbitrary large number
4641             }
4642             info.minLength = temp;
4643 
4644             if (maxV & info.maxValid) {
4645                 temp = info.maxLength * cmax + maxL;
4646                 info.maxLength = temp;
4647                 if (temp < maxL) {
4648                     info.maxValid = false;
4649                 }
4650             } else {
4651                 info.maxValid = false;
4652             }
4653 
4654             if (info.deterministic && cmin == cmax) {
4655                 info.deterministic = detm;
4656             } else {
4657                 info.deterministic = false;
4658             }
4659             return next.study(info);
4660         }
4661     }
4662 
4663     /**
4664      * A Guard node at the end of each atom node in a Branch. It
4665      * serves the purpose of chaining the "match" operation to
4666      * "next" but not the "study", so we can collect the TreeInfo
4667      * of each atom node without including the TreeInfo of the
4668      * "next".
4669      */
4670     static final class BranchConn extends Node {
4671         BranchConn() {};
4672         boolean match(Matcher matcher, int i, CharSequence seq) {
4673             return next.match(matcher, i, seq);
4674         }
4675         boolean study(TreeInfo info) {
4676             return info.deterministic;
4677         }
4678     }
4679 
4680     /**
4681      * Handles the branching of alternations. Note this is also used for
4682      * the ? quantifier to branch between the case where it matches once
4683      * and where it does not occur.
4684      */
4685     static final class Branch extends Node {
4686         Node[] atoms = new Node[2];
4687         int size = 2;
4688         Node conn;
4689         Branch(Node first, Node second, Node branchConn) {
4690             conn = branchConn;
4691             atoms[0] = first;
4692             atoms[1] = second;
4693         }
4694 
4695         void add(Node node) {
4696             if (size >= atoms.length) {
4697                 Node[] tmp = new Node[atoms.length*2];
4698                 System.arraycopy(atoms, 0, tmp, 0, atoms.length);
4699                 atoms = tmp;
4700             }
4701             atoms[size++] = node;
4702         }
4703 
4704         boolean match(Matcher matcher, int i, CharSequence seq) {
4705             for (int n = 0; n < size; n++) {
4706                 if (atoms[n] == null) {
4707                     if (conn.next.match(matcher, i, seq))
4708                         return true;
4709                 } else if (atoms[n].match(matcher, i, seq)) {
4710                     return true;
4711                 }
4712             }
4713             return false;
4714         }
4715 
4716         boolean study(TreeInfo info) {
4717             int minL = info.minLength;
4718             int maxL = info.maxLength;
4719             boolean maxV = info.maxValid;
4720 
4721             int minL2 = Integer.MAX_VALUE; //arbitrary large enough num
4722             int maxL2 = -1;
4723             for (int n = 0; n < size; n++) {
4724                 info.reset();
4725                 if (atoms[n] != null)
4726                     atoms[n].study(info);
4727                 minL2 = Math.min(minL2, info.minLength);
4728                 maxL2 = Math.max(maxL2, info.maxLength);
4729                 maxV = (maxV & info.maxValid);
4730             }
4731 
4732             minL += minL2;
4733             maxL += maxL2;
4734 
4735             info.reset();
4736             conn.next.study(info);
4737 
4738             info.minLength += minL;
4739             info.maxLength += maxL;
4740             info.maxValid &= maxV;
4741             info.deterministic = false;
4742             return false;
4743         }
4744     }
4745 
4746     /**
4747      * The GroupHead saves the location where the group begins in the locals
4748      * and restores them when the match is done.
4749      *
4750      * The matchRef is used when a reference to this group is accessed later
4751      * in the expression. The locals will have a negative value in them to
4752      * indicate that we do not want to unset the group if the reference
4753      * doesn't match.
4754      */
4755     static final class GroupHead extends Node {
4756         int localIndex;
4757         GroupTail tail;    // for debug/print only, match does not need to know
4758         GroupHead(int localCount) {
4759             localIndex = localCount;
4760         }
4761         boolean match(Matcher matcher, int i, CharSequence seq) {
4762             int save = matcher.locals[localIndex];
4763             matcher.locals[localIndex] = i;
4764             boolean ret = next.match(matcher, i, seq);
4765             matcher.locals[localIndex] = save;
4766             return ret;
4767         }
4768         boolean matchRef(Matcher matcher, int i, CharSequence seq) {
4769             int save = matcher.locals[localIndex];
4770             matcher.locals[localIndex] = ~i; // HACK
4771             boolean ret = next.match(matcher, i, seq);
4772             matcher.locals[localIndex] = save;
4773             return ret;
4774         }
4775     }
4776 
4777     /**
4778      * Recursive reference to a group in the regular expression. It calls
4779      * matchRef because if the reference fails to match we would not unset
4780      * the group.
4781      */
4782     static final class GroupRef extends Node {
4783         GroupHead head;
4784         GroupRef(GroupHead head) {
4785             this.head = head;
4786         }
4787         boolean match(Matcher matcher, int i, CharSequence seq) {
4788             return head.matchRef(matcher, i, seq)
4789                 && next.match(matcher, matcher.last, seq);
4790         }
4791         boolean study(TreeInfo info) {
4792             info.maxValid = false;
4793             info.deterministic = false;
4794             return next.study(info);
4795         }
4796     }
4797 
4798     /**
4799      * The GroupTail handles the setting of group beginning and ending
4800      * locations when groups are successfully matched. It must also be able to
4801      * unset groups that have to be backed off of.
4802      *
4803      * The GroupTail node is also used when a previous group is referenced,
4804      * and in that case no group information needs to be set.
4805      */
4806     static final class GroupTail extends Node {
4807         int localIndex;
4808         int groupIndex;
4809         GroupTail(int localCount, int groupCount) {
4810             localIndex = localCount;
4811             groupIndex = groupCount + groupCount;
4812         }
4813         boolean match(Matcher matcher, int i, CharSequence seq) {
4814             int tmp = matcher.locals[localIndex];
4815             if (tmp >= 0) { // This is the normal group case.
4816                 // Save the group so we can unset it if it
4817                 // backs off of a match.
4818                 int groupStart = matcher.groups[groupIndex];
4819                 int groupEnd = matcher.groups[groupIndex+1];
4820 
4821                 matcher.groups[groupIndex] = tmp;
4822                 matcher.groups[groupIndex+1] = i;
4823                 if (next.match(matcher, i, seq)) {
4824                     return true;
4825                 }
4826                 matcher.groups[groupIndex] = groupStart;
4827                 matcher.groups[groupIndex+1] = groupEnd;
4828                 return false;
4829             } else {
4830                 // This is a group reference case. We don't need to save any
4831                 // group info because it isn't really a group.
4832                 matcher.last = i;
4833                 return true;
4834             }
4835         }
4836     }
4837 
4838     /**
4839      * This sets up a loop to handle a recursive quantifier structure.
4840      */
4841     static final class Prolog extends Node {
4842         Loop loop;
4843         Prolog(Loop loop) {
4844             this.loop = loop;
4845         }
4846         boolean match(Matcher matcher, int i, CharSequence seq) {
4847             return loop.matchInit(matcher, i, seq);
4848         }
4849         boolean study(TreeInfo info) {
4850             return loop.study(info);
4851         }
4852     }
4853 
4854     /**
4855      * Handles the repetition count for a greedy Curly. The matchInit
4856      * is called from the Prolog to save the index of where the group
4857      * beginning is stored. A zero length group check occurs in the
4858      * normal match but is skipped in the matchInit.
4859      */
4860     static class Loop extends Node {
4861         Node body;
4862         int countIndex; // local count index in matcher locals
4863         int beginIndex; // group beginning index
4864         int cmin, cmax;
4865         int posIndex;
4866         Loop(int countIndex, int beginIndex) {
4867             this.countIndex = countIndex;
4868             this.beginIndex = beginIndex;
4869             this.posIndex = -1;
4870         }
4871         boolean match(Matcher matcher, int i, CharSequence seq) {
4872             // Avoid infinite loop in zero-length case.
4873             if (i > matcher.locals[beginIndex]) {
4874                 int count = matcher.locals[countIndex];
4875 
4876                 // This block is for before we reach the minimum
4877                 // iterations required for the loop to match
4878                 if (count < cmin) {
4879                     matcher.locals[countIndex] = count + 1;
4880                     boolean b = body.match(matcher, i, seq);
4881                     // If match failed we must backtrack, so
4882                     // the loop count should NOT be incremented
4883                     if (!b)
4884                         matcher.locals[countIndex] = count;
4885                     // Return success or failure since we are under
4886                     // minimum
4887                     return b;
4888                 }
4889                 // This block is for after we have the minimum
4890                 // iterations required for the loop to match
4891                 if (count < cmax) {
4892                     // Let's check if we have already tried and failed
4893                     // at this starting position "i" in the past.
4894                     // If yes, then just return false wihtout trying
4895                     // again, to stop the exponential backtracking.
4896                     if (posIndex != -1 &&
4897                         matcher.localsPos[posIndex].contains(i)) {
4898                         return next.match(matcher, i, seq);
4899                     }
4900                     matcher.locals[countIndex] = count + 1;
4901                     boolean b = body.match(matcher, i, seq);
4902                     // If match failed we must backtrack, so
4903                     // the loop count should NOT be incremented
4904                     if (b)
4905                         return true;
4906                     matcher.locals[countIndex] = count;
4907                     // save the failed position
4908                     if (posIndex != -1) {
4909                         matcher.localsPos[posIndex].add(i);
4910                     }
4911                 }
4912             }
4913             return next.match(matcher, i, seq);
4914         }
4915         boolean matchInit(Matcher matcher, int i, CharSequence seq) {
4916             int save = matcher.locals[countIndex];
4917             boolean ret = false;
4918             if (posIndex != -1 && matcher.localsPos[posIndex] == null) {
4919                 matcher.localsPos[posIndex] = new IntHashSet();
4920             }
4921             if (0 < cmin) {
4922                 matcher.locals[countIndex] = 1;
4923                 ret = body.match(matcher, i, seq);
4924             } else if (0 < cmax) {
4925                 matcher.locals[countIndex] = 1;
4926                 ret = body.match(matcher, i, seq);
4927                 if (ret == false)
4928                     ret = next.match(matcher, i, seq);
4929             } else {
4930                 ret = next.match(matcher, i, seq);
4931             }
4932             matcher.locals[countIndex] = save;
4933             return ret;
4934         }
4935         boolean study(TreeInfo info) {
4936             info.maxValid = false;
4937             info.deterministic = false;
4938             return false;
4939         }
4940     }
4941 
4942     /**
4943      * Handles the repetition count for a reluctant Curly. The matchInit
4944      * is called from the Prolog to save the index of where the group
4945      * beginning is stored. A zero length group check occurs in the
4946      * normal match but is skipped in the matchInit.
4947      */
4948     static final class LazyLoop extends Loop {
4949         LazyLoop(int countIndex, int beginIndex) {
4950             super(countIndex, beginIndex);
4951         }
4952         boolean match(Matcher matcher, int i, CharSequence seq) {
4953             // Check for zero length group
4954             if (i > matcher.locals[beginIndex]) {
4955                 int count = matcher.locals[countIndex];
4956                 if (count < cmin) {
4957                     matcher.locals[countIndex] = count + 1;
4958                     boolean result = body.match(matcher, i, seq);
4959                     // If match failed we must backtrack, so
4960                     // the loop count should NOT be incremented
4961                     if (!result)
4962                         matcher.locals[countIndex] = count;
4963                     return result;
4964                 }
4965                 if (next.match(matcher, i, seq))
4966                     return true;
4967                 if (count < cmax) {
4968                     matcher.locals[countIndex] = count + 1;
4969                     boolean result = body.match(matcher, i, seq);
4970                     // If match failed we must backtrack, so
4971                     // the loop count should NOT be incremented
4972                     if (!result)
4973                         matcher.locals[countIndex] = count;
4974                     return result;
4975                 }
4976                 return false;
4977             }
4978             return next.match(matcher, i, seq);
4979         }
4980         boolean matchInit(Matcher matcher, int i, CharSequence seq) {
4981             int save = matcher.locals[countIndex];
4982             boolean ret = false;
4983             if (0 < cmin) {
4984                 matcher.locals[countIndex] = 1;
4985                 ret = body.match(matcher, i, seq);
4986             } else if (next.match(matcher, i, seq)) {
4987                 ret = true;
4988             } else if (0 < cmax) {
4989                 matcher.locals[countIndex] = 1;
4990                 ret = body.match(matcher, i, seq);
4991             }
4992             matcher.locals[countIndex] = save;
4993             return ret;
4994         }
4995         boolean study(TreeInfo info) {
4996             info.maxValid = false;
4997             info.deterministic = false;
4998             return false;
4999         }
5000     }
5001 
5002     /**
5003      * Refers to a group in the regular expression. Attempts to match
5004      * whatever the group referred to last matched.
5005      */
5006     static class BackRef extends Node {
5007         int groupIndex;
5008         BackRef(int groupCount) {
5009             super();
5010             groupIndex = groupCount + groupCount;
5011         }
5012         boolean match(Matcher matcher, int i, CharSequence seq) {
5013             int j = matcher.groups[groupIndex];
5014             int k = matcher.groups[groupIndex+1];
5015 
5016             int groupSize = k - j;
5017             // If the referenced group didn't match, neither can this
5018             if (j < 0)
5019                 return false;
5020 
5021             // If there isn't enough input left no match
5022             if (i + groupSize > matcher.to) {
5023                 matcher.hitEnd = true;
5024                 return false;
5025             }
5026             // Check each new char to make sure it matches what the group
5027             // referenced matched last time around
5028             for (int index=0; index<groupSize; index++)
5029                 if (seq.charAt(i+index) != seq.charAt(j+index))
5030                     return false;
5031 
5032             return next.match(matcher, i+groupSize, seq);
5033         }
5034         boolean study(TreeInfo info) {
5035             info.maxValid = false;
5036             return next.study(info);
5037         }
5038     }
5039 
5040     static class CIBackRef extends Node {
5041         int groupIndex;
5042         boolean doUnicodeCase;
5043         CIBackRef(int groupCount, boolean doUnicodeCase) {
5044             super();
5045             groupIndex = groupCount + groupCount;
5046             this.doUnicodeCase = doUnicodeCase;
5047         }
5048         boolean match(Matcher matcher, int i, CharSequence seq) {
5049             int j = matcher.groups[groupIndex];
5050             int k = matcher.groups[groupIndex+1];
5051 
5052             int groupSize = k - j;
5053 
5054             // If the referenced group didn't match, neither can this
5055             if (j < 0)
5056                 return false;
5057 
5058             // If there isn't enough input left no match
5059             if (i + groupSize > matcher.to) {
5060                 matcher.hitEnd = true;
5061                 return false;
5062             }
5063 
5064             // Check each new char to make sure it matches what the group
5065             // referenced matched last time around
5066             int x = i;
5067             for (int index=0; index<groupSize; index++) {
5068                 int c1 = Character.codePointAt(seq, x);
5069                 int c2 = Character.codePointAt(seq, j);
5070                 if (c1 != c2) {
5071                     if (doUnicodeCase) {
5072                         int cc1 = Character.toUpperCase(c1);
5073                         int cc2 = Character.toUpperCase(c2);
5074                         if (cc1 != cc2 &&
5075                             Character.toLowerCase(cc1) !=
5076                             Character.toLowerCase(cc2))
5077                             return false;
5078                     } else {
5079                         if (ASCII.toLower(c1) != ASCII.toLower(c2))
5080                             return false;
5081                     }
5082                 }
5083                 x += Character.charCount(c1);
5084                 j += Character.charCount(c2);
5085             }
5086 
5087             return next.match(matcher, i+groupSize, seq);
5088         }
5089         boolean study(TreeInfo info) {
5090             info.maxValid = false;
5091             return next.study(info);
5092         }
5093     }
5094 
5095     /**
5096      * Searches until the next instance of its atom. This is useful for
5097      * finding the atom efficiently without passing an instance of it
5098      * (greedy problem) and without a lot of wasted search time (reluctant
5099      * problem).
5100      */
5101     static final class First extends Node {
5102         Node atom;
5103         First(Node node) {
5104             this.atom = BnM.optimize(node);
5105         }
5106         boolean match(Matcher matcher, int i, CharSequence seq) {
5107             if (atom instanceof BnM) {
5108                 return atom.match(matcher, i, seq)
5109                     && next.match(matcher, matcher.last, seq);
5110             }
5111             for (;;) {
5112                 if (i > matcher.to) {
5113                     matcher.hitEnd = true;
5114                     return false;
5115                 }
5116                 if (atom.match(matcher, i, seq)) {
5117                     return next.match(matcher, matcher.last, seq);
5118                 }
5119                 i += countChars(seq, i, 1);
5120                 matcher.first++;
5121             }
5122         }
5123         boolean study(TreeInfo info) {
5124             atom.study(info);
5125             info.maxValid = false;
5126             info.deterministic = false;
5127             return next.study(info);
5128         }
5129     }
5130 
5131     static final class Conditional extends Node {
5132         Node cond, yes, not;
5133         Conditional(Node cond, Node yes, Node not) {
5134             this.cond = cond;
5135             this.yes = yes;
5136             this.not = not;
5137         }
5138         boolean match(Matcher matcher, int i, CharSequence seq) {
5139             if (cond.match(matcher, i, seq)) {
5140                 return yes.match(matcher, i, seq);
5141             } else {
5142                 return not.match(matcher, i, seq);
5143             }
5144         }
5145         boolean study(TreeInfo info) {
5146             int minL = info.minLength;
5147             int maxL = info.maxLength;
5148             boolean maxV = info.maxValid;
5149             info.reset();
5150             yes.study(info);
5151 
5152             int minL2 = info.minLength;
5153             int maxL2 = info.maxLength;
5154             boolean maxV2 = info.maxValid;
5155             info.reset();
5156             not.study(info);
5157 
5158             info.minLength = minL + Math.min(minL2, info.minLength);
5159             info.maxLength = maxL + Math.max(maxL2, info.maxLength);
5160             info.maxValid = (maxV & maxV2 & info.maxValid);
5161             info.deterministic = false;
5162             return next.study(info);
5163         }
5164     }
5165 
5166     /**
5167      * Zero width positive lookahead.
5168      */
5169     static final class Pos extends Node {
5170         Node cond;
5171         Pos(Node cond) {
5172             this.cond = cond;
5173         }
5174         boolean match(Matcher matcher, int i, CharSequence seq) {
5175             int savedTo = matcher.to;
5176             boolean conditionMatched = false;
5177 
5178             // Relax transparent region boundaries for lookahead
5179             if (matcher.transparentBounds)
5180                 matcher.to = matcher.getTextLength();
5181             try {
5182                 conditionMatched = cond.match(matcher, i, seq);
5183             } finally {
5184                 // Reinstate region boundaries
5185                 matcher.to = savedTo;
5186             }
5187             return conditionMatched && next.match(matcher, i, seq);
5188         }
5189     }
5190 
5191     /**
5192      * Zero width negative lookahead.
5193      */
5194     static final class Neg extends Node {
5195         Node cond;
5196         Neg(Node cond) {
5197             this.cond = cond;
5198         }
5199         boolean match(Matcher matcher, int i, CharSequence seq) {
5200             int savedTo = matcher.to;
5201             boolean conditionMatched = false;
5202 
5203             // Relax transparent region boundaries for lookahead
5204             if (matcher.transparentBounds)
5205                 matcher.to = matcher.getTextLength();
5206             try {
5207                 if (i < matcher.to) {
5208                     conditionMatched = !cond.match(matcher, i, seq);
5209                 } else {
5210                     // If a negative lookahead succeeds then more input
5211                     // could cause it to fail!
5212                     matcher.requireEnd = true;
5213                     conditionMatched = !cond.match(matcher, i, seq);
5214                 }
5215             } finally {
5216                 // Reinstate region boundaries
5217                 matcher.to = savedTo;
5218             }
5219             return conditionMatched && next.match(matcher, i, seq);
5220         }
5221     }
5222 
5223     /**
5224      * For use with lookbehinds; matches the position where the lookbehind
5225      * was encountered.
5226      */
5227     static Node lookbehindEnd = new Node() {
5228         boolean match(Matcher matcher, int i, CharSequence seq) {
5229             return i == matcher.lookbehindTo;
5230         }
5231     };
5232 
5233     /**
5234      * Zero width positive lookbehind.
5235      */
5236     static class Behind extends Node {
5237         Node cond;
5238         int rmax, rmin;
5239         Behind(Node cond, int rmax, int rmin) {
5240             this.cond = cond;
5241             this.rmax = rmax;
5242             this.rmin = rmin;
5243         }
5244 
5245         boolean match(Matcher matcher, int i, CharSequence seq) {
5246             int savedFrom = matcher.from;
5247             boolean conditionMatched = false;
5248             int startIndex = (!matcher.transparentBounds) ?
5249                              matcher.from : 0;
5250             int from = Math.max(i - rmax, startIndex);
5251             // Set end boundary
5252             int savedLBT = matcher.lookbehindTo;
5253             matcher.lookbehindTo = i;
5254             // Relax transparent region boundaries for lookbehind
5255             if (matcher.transparentBounds)
5256                 matcher.from = 0;
5257             for (int j = i - rmin; !conditionMatched && j >= from; j--) {
5258                 conditionMatched = cond.match(matcher, j, seq);
5259             }
5260             matcher.from = savedFrom;
5261             matcher.lookbehindTo = savedLBT;
5262             return conditionMatched && next.match(matcher, i, seq);
5263         }
5264     }
5265 
5266     /**
5267      * Zero width positive lookbehind, including supplementary
5268      * characters or unpaired surrogates.
5269      */
5270     static final class BehindS extends Behind {
5271         BehindS(Node cond, int rmax, int rmin) {
5272             super(cond, rmax, rmin);
5273         }
5274         boolean match(Matcher matcher, int i, CharSequence seq) {
5275             int rmaxChars = countChars(seq, i, -rmax);
5276             int rminChars = countChars(seq, i, -rmin);
5277             int savedFrom = matcher.from;
5278             int startIndex = (!matcher.transparentBounds) ?
5279                              matcher.from : 0;
5280             boolean conditionMatched = false;
5281             int from = Math.max(i - rmaxChars, startIndex);
5282             // Set end boundary
5283             int savedLBT = matcher.lookbehindTo;
5284             matcher.lookbehindTo = i;
5285             // Relax transparent region boundaries for lookbehind
5286             if (matcher.transparentBounds)
5287                 matcher.from = 0;
5288 
5289             for (int j = i - rminChars;
5290                  !conditionMatched && j >= from;
5291                  j -= j>from ? countChars(seq, j, -1) : 1) {
5292                 conditionMatched = cond.match(matcher, j, seq);
5293             }
5294             matcher.from = savedFrom;
5295             matcher.lookbehindTo = savedLBT;
5296             return conditionMatched && next.match(matcher, i, seq);
5297         }
5298     }
5299 
5300     /**
5301      * Zero width negative lookbehind.
5302      */
5303     static class NotBehind extends Node {
5304         Node cond;
5305         int rmax, rmin;
5306         NotBehind(Node cond, int rmax, int rmin) {
5307             this.cond = cond;
5308             this.rmax = rmax;
5309             this.rmin = rmin;
5310         }
5311 
5312         boolean match(Matcher matcher, int i, CharSequence seq) {
5313             int savedLBT = matcher.lookbehindTo;
5314             int savedFrom = matcher.from;
5315             boolean conditionMatched = false;
5316             int startIndex = (!matcher.transparentBounds) ?
5317                              matcher.from : 0;
5318             int from = Math.max(i - rmax, startIndex);
5319             matcher.lookbehindTo = i;
5320             // Relax transparent region boundaries for lookbehind
5321             if (matcher.transparentBounds)
5322                 matcher.from = 0;
5323             for (int j = i - rmin; !conditionMatched && j >= from; j--) {
5324                 conditionMatched = cond.match(matcher, j, seq);
5325             }
5326             // Reinstate region boundaries
5327             matcher.from = savedFrom;
5328             matcher.lookbehindTo = savedLBT;
5329             return !conditionMatched && next.match(matcher, i, seq);
5330         }
5331     }
5332 
5333     /**
5334      * Zero width negative lookbehind, including supplementary
5335      * characters or unpaired surrogates.
5336      */
5337     static final class NotBehindS extends NotBehind {
5338         NotBehindS(Node cond, int rmax, int rmin) {
5339             super(cond, rmax, rmin);
5340         }
5341         boolean match(Matcher matcher, int i, CharSequence seq) {
5342             int rmaxChars = countChars(seq, i, -rmax);
5343             int rminChars = countChars(seq, i, -rmin);
5344             int savedFrom = matcher.from;
5345             int savedLBT = matcher.lookbehindTo;
5346             boolean conditionMatched = false;
5347             int startIndex = (!matcher.transparentBounds) ?
5348                              matcher.from : 0;
5349             int from = Math.max(i - rmaxChars, startIndex);
5350             matcher.lookbehindTo = i;
5351             // Relax transparent region boundaries for lookbehind
5352             if (matcher.transparentBounds)
5353                 matcher.from = 0;
5354             for (int j = i - rminChars;
5355                  !conditionMatched && j >= from;
5356                  j -= j>from ? countChars(seq, j, -1) : 1) {
5357                 conditionMatched = cond.match(matcher, j, seq);
5358             }
5359             //Reinstate region boundaries
5360             matcher.from = savedFrom;
5361             matcher.lookbehindTo = savedLBT;
5362             return !conditionMatched && next.match(matcher, i, seq);
5363         }
5364     }
5365 
5366     /**
5367      * Handles word boundaries. Includes a field to allow this one class to
5368      * deal with the different types of word boundaries we can match. The word
5369      * characters include underscores, letters, and digits. Non spacing marks
5370      * can are also part of a word if they have a base character, otherwise
5371      * they are ignored for purposes of finding word boundaries.
5372      */
5373     static final class Bound extends Node {
5374         static int LEFT = 0x1;
5375         static int RIGHT= 0x2;
5376         static int BOTH = 0x3;
5377         static int NONE = 0x4;
5378         int type;
5379         boolean useUWORD;
5380         Bound(int n, boolean useUWORD) {
5381             type = n;
5382             this.useUWORD = useUWORD;
5383         }
5384 
5385         boolean isWord(int ch) {
5386             return useUWORD ? CharPredicates.WORD().is(ch)
5387                             : (ch == '_' || Character.isLetterOrDigit(ch));
5388         }
5389 
5390         int check(Matcher matcher, int i, CharSequence seq) {
5391             int ch;
5392             boolean left = false;
5393             int startIndex = matcher.from;
5394             int endIndex = matcher.to;
5395             if (matcher.transparentBounds) {
5396                 startIndex = 0;
5397                 endIndex = matcher.getTextLength();
5398             }
5399             if (i > startIndex) {
5400                 ch = Character.codePointBefore(seq, i);
5401                 left = (isWord(ch) ||
5402                     ((Character.getType(ch) == Character.NON_SPACING_MARK)
5403                      && hasBaseCharacter(matcher, i-1, seq)));
5404             }
5405             boolean right = false;
5406             if (i < endIndex) {
5407                 ch = Character.codePointAt(seq, i);
5408                 right = (isWord(ch) ||
5409                     ((Character.getType(ch) == Character.NON_SPACING_MARK)
5410                      && hasBaseCharacter(matcher, i, seq)));
5411             } else {
5412                 // Tried to access char past the end
5413                 matcher.hitEnd = true;
5414                 // The addition of another char could wreck a boundary
5415                 matcher.requireEnd = true;
5416             }
5417             return ((left ^ right) ? (right ? LEFT : RIGHT) : NONE);
5418         }
5419         boolean match(Matcher matcher, int i, CharSequence seq) {
5420             return (check(matcher, i, seq) & type) > 0
5421                 && next.match(matcher, i, seq);
5422         }
5423     }
5424 
5425     /**
5426      * Non spacing marks only count as word characters in bounds calculations
5427      * if they have a base character.
5428      */
5429     private static boolean hasBaseCharacter(Matcher matcher, int i,
5430                                             CharSequence seq)
5431     {
5432         int start = (!matcher.transparentBounds) ?
5433             matcher.from : 0;
5434         for (int x=i; x >= start; x--) {
5435             int ch = Character.codePointAt(seq, x);
5436             if (Character.isLetterOrDigit(ch))
5437                 return true;
5438             if (Character.getType(ch) == Character.NON_SPACING_MARK)
5439                 continue;
5440             return false;
5441         }
5442         return false;
5443     }
5444 
5445     /**
5446      * Attempts to match a slice in the input using the Boyer-Moore string
5447      * matching algorithm. The algorithm is based on the idea that the
5448      * pattern can be shifted farther ahead in the search text if it is
5449      * matched right to left.
5450      * <p>
5451      * The pattern is compared to the input one character at a time, from
5452      * the rightmost character in the pattern to the left. If the characters
5453      * all match the pattern has been found. If a character does not match,
5454      * the pattern is shifted right a distance that is the maximum of two
5455      * functions, the bad character shift and the good suffix shift. This
5456      * shift moves the attempted match position through the input more
5457      * quickly than a naive one position at a time check.
5458      * <p>
5459      * The bad character shift is based on the character from the text that
5460      * did not match. If the character does not appear in the pattern, the
5461      * pattern can be shifted completely beyond the bad character. If the
5462      * character does occur in the pattern, the pattern can be shifted to
5463      * line the pattern up with the next occurrence of that character.
5464      * <p>
5465      * The good suffix shift is based on the idea that some subset on the right
5466      * side of the pattern has matched. When a bad character is found, the
5467      * pattern can be shifted right by the pattern length if the subset does
5468      * not occur again in pattern, or by the amount of distance to the
5469      * next occurrence of the subset in the pattern.
5470      *
5471      * Boyer-Moore search methods adapted from code by Amy Yu.
5472      */
5473     static class BnM extends Node {
5474         int[] buffer;
5475         int[] lastOcc;
5476         int[] optoSft;
5477 
5478         /**
5479          * Pre calculates arrays needed to generate the bad character
5480          * shift and the good suffix shift. Only the last seven bits
5481          * are used to see if chars match; This keeps the tables small
5482          * and covers the heavily used ASCII range, but occasionally
5483          * results in an aliased match for the bad character shift.
5484          */
5485         static Node optimize(Node node) {
5486             if (!(node instanceof Slice)) {
5487                 return node;
5488             }
5489 
5490             int[] src = ((Slice) node).buffer;
5491             int patternLength = src.length;
5492             // The BM algorithm requires a bit of overhead;
5493             // If the pattern is short don't use it, since
5494             // a shift larger than the pattern length cannot
5495             // be used anyway.
5496             if (patternLength < 4) {
5497                 return node;
5498             }
5499             int i, j, k;
5500             int[] lastOcc = new int[128];
5501             int[] optoSft = new int[patternLength];
5502             // Precalculate part of the bad character shift
5503             // It is a table for where in the pattern each
5504             // lower 7-bit value occurs
5505             for (i = 0; i < patternLength; i++) {
5506                 lastOcc[src[i]&0x7F] = i + 1;
5507             }
5508             // Precalculate the good suffix shift
5509             // i is the shift amount being considered
5510 NEXT:       for (i = patternLength; i > 0; i--) {
5511                 // j is the beginning index of suffix being considered
5512                 for (j = patternLength - 1; j >= i; j--) {
5513                     // Testing for good suffix
5514                     if (src[j] == src[j-i]) {
5515                         // src[j..len] is a good suffix
5516                         optoSft[j-1] = i;
5517                     } else {
5518                         // No match. The array has already been
5519                         // filled up with correct values before.
5520                         continue NEXT;
5521                     }
5522                 }
5523                 // This fills up the remaining of optoSft
5524                 // any suffix can not have larger shift amount
5525                 // then its sub-suffix. Why???
5526                 while (j > 0) {
5527                     optoSft[--j] = i;
5528                 }
5529             }
5530             // Set the guard value because of unicode compression
5531             optoSft[patternLength-1] = 1;
5532             if (node instanceof SliceS)
5533                 return new BnMS(src, lastOcc, optoSft, node.next);
5534             return new BnM(src, lastOcc, optoSft, node.next);
5535         }
5536         BnM(int[] src, int[] lastOcc, int[] optoSft, Node next) {
5537             this.buffer = src;
5538             this.lastOcc = lastOcc;
5539             this.optoSft = optoSft;
5540             this.next = next;
5541         }
5542         boolean match(Matcher matcher, int i, CharSequence seq) {
5543             int[] src = buffer;
5544             int patternLength = src.length;
5545             int last = matcher.to - patternLength;
5546 
5547             // Loop over all possible match positions in text
5548 NEXT:       while (i <= last) {
5549                 // Loop over pattern from right to left
5550                 for (int j = patternLength - 1; j >= 0; j--) {
5551                     int ch = seq.charAt(i+j);
5552                     if (ch != src[j]) {
5553                         // Shift search to the right by the maximum of the
5554                         // bad character shift and the good suffix shift
5555                         i += Math.max(j + 1 - lastOcc[ch&0x7F], optoSft[j]);
5556                         continue NEXT;
5557                     }
5558                 }
5559                 // Entire pattern matched starting at i
5560                 matcher.first = i;
5561                 boolean ret = next.match(matcher, i + patternLength, seq);
5562                 if (ret) {
5563                     matcher.first = i;
5564                     matcher.groups[0] = matcher.first;
5565                     matcher.groups[1] = matcher.last;
5566                     return true;
5567                 }
5568                 i++;
5569             }
5570             // BnM is only used as the leading node in the unanchored case,
5571             // and it replaced its Start() which always searches to the end
5572             // if it doesn't find what it's looking for, so hitEnd is true.
5573             matcher.hitEnd = true;
5574             return false;
5575         }
5576         boolean study(TreeInfo info) {
5577             info.minLength += buffer.length;
5578             info.maxValid = false;
5579             return next.study(info);
5580         }
5581     }
5582 
5583     /**
5584      * Supplementary support version of BnM(). Unpaired surrogates are
5585      * also handled by this class.
5586      */
5587     static final class BnMS extends BnM {
5588         int lengthInChars;
5589 
5590         BnMS(int[] src, int[] lastOcc, int[] optoSft, Node next) {
5591             super(src, lastOcc, optoSft, next);
5592             for (int cp : buffer) {
5593                 lengthInChars += Character.charCount(cp);
5594             }
5595         }
5596         boolean match(Matcher matcher, int i, CharSequence seq) {
5597             int[] src = buffer;
5598             int patternLength = src.length;
5599             int last = matcher.to - lengthInChars;
5600 
5601             // Loop over all possible match positions in text
5602 NEXT:       while (i <= last) {
5603                 // Loop over pattern from right to left
5604                 int ch;
5605                 for (int j = countChars(seq, i, patternLength), x = patternLength - 1;
5606                      j > 0; j -= Character.charCount(ch), x--) {
5607                     ch = Character.codePointBefore(seq, i+j);
5608                     if (ch != src[x]) {
5609                         // Shift search to the right by the maximum of the
5610                         // bad character shift and the good suffix shift
5611                         int n = Math.max(x + 1 - lastOcc[ch&0x7F], optoSft[x]);
5612                         i += countChars(seq, i, n);
5613                         continue NEXT;
5614                     }
5615                 }
5616                 // Entire pattern matched starting at i
5617                 matcher.first = i;
5618                 boolean ret = next.match(matcher, i + lengthInChars, seq);
5619                 if (ret) {
5620                     matcher.first = i;
5621                     matcher.groups[0] = matcher.first;
5622                     matcher.groups[1] = matcher.last;
5623                     return true;
5624                 }
5625                 i += countChars(seq, i, 1);
5626             }
5627             matcher.hitEnd = true;
5628             return false;
5629         }
5630     }
5631 
5632     @FunctionalInterface
5633     static interface CharPredicate {
5634         boolean is(int ch);
5635 
5636         default CharPredicate and(CharPredicate p) {
5637             return ch -> is(ch) && p.is(ch);
5638         }
5639         default CharPredicate union(CharPredicate p) {
5640             return ch -> is(ch) || p.is(ch);
5641         }
5642         default CharPredicate union(CharPredicate p1,
5643                                     CharPredicate p2 ) {
5644             return ch -> is(ch) || p1.is(ch) || p2.is(ch);
5645         }
5646         default CharPredicate negate() {
5647             return ch -> !is(ch);
5648         }
5649     }
5650 
5651     static interface BmpCharPredicate extends CharPredicate {
5652 
5653         default CharPredicate and(CharPredicate p) {
5654             if(p instanceof BmpCharPredicate)
5655                 return (BmpCharPredicate)(ch -> is(ch) && p.is(ch));
5656             return ch -> is(ch) && p.is(ch);
5657         }
5658         default CharPredicate union(CharPredicate p) {
5659             if (p instanceof BmpCharPredicate)
5660                 return (BmpCharPredicate)(ch -> is(ch) || p.is(ch));
5661             return ch -> is(ch) || p.is(ch);
5662         }
5663         static CharPredicate union(CharPredicate... predicates) {
5664             CharPredicate cp = ch -> {
5665                 for (CharPredicate p : predicates) {
5666                     if (!p.is(ch))
5667                         return false;
5668                 }
5669                 return true;
5670             };
5671             for (CharPredicate p : predicates) {
5672                 if (! (p instanceof BmpCharPredicate))
5673                     return cp;
5674             }
5675             return (BmpCharPredicate)cp;
5676         }
5677     }
5678 
5679     /**
5680      * matches a Perl vertical whitespace
5681      */
5682     static BmpCharPredicate VertWS() {
5683         return cp -> (cp >= 0x0A && cp <= 0x0D) ||
5684             cp == 0x85 || cp == 0x2028 || cp == 0x2029;
5685     }
5686 
5687     /**
5688      * matches a Perl horizontal whitespace
5689      */
5690     static BmpCharPredicate HorizWS() {
5691         return cp ->
5692             cp == 0x09 || cp == 0x20 || cp == 0xa0 || cp == 0x1680 ||
5693             cp == 0x180e || cp >= 0x2000 && cp <= 0x200a ||  cp == 0x202f ||
5694             cp == 0x205f || cp == 0x3000;
5695     }
5696 
5697     /**
5698      *  for the Unicode category ALL and the dot metacharacter when
5699      *  in dotall mode.
5700      */
5701     static CharPredicate ALL() {
5702         return ch -> true;
5703     }
5704 
5705     /**
5706      * for the dot metacharacter when dotall is not enabled.
5707      */
5708     static CharPredicate DOT() {
5709         return ch ->
5710             (ch != '\n' && ch != '\r'
5711             && (ch|1) != '\u2029'
5712             && ch != '\u0085');
5713     }
5714 
5715     /**
5716      *  the dot metacharacter when dotall is not enabled but UNIX_LINES is enabled.
5717      */
5718     static CharPredicate UNIXDOT() {
5719         return ch ->  ch != '\n';
5720     }
5721 
5722     /**
5723      * Indicate that matches a Supplementary Unicode character
5724      */
5725     static CharPredicate SingleS(int c) {
5726         return ch -> ch == c;
5727     }
5728 
5729     /**
5730      * A bmp/optimized predicate of single
5731      */
5732     static BmpCharPredicate Single(int c) {
5733         return ch -> ch == c;
5734     }
5735 
5736     /**
5737      * Case insensitive matches a given BMP character
5738      */
5739     static BmpCharPredicate SingleI(int lower, int upper) {
5740         return ch -> ch == lower || ch == upper;
5741     }
5742 
5743     /**
5744      * Unicode case insensitive matches a given Unicode character
5745      */
5746     static CharPredicate SingleU(int lower) {
5747         return ch -> lower == ch ||
5748                      lower == Character.toLowerCase(Character.toUpperCase(ch));
5749     }
5750 
5751     private static boolean inRange(int lower, int ch, int upper) {
5752         return lower <= ch && ch <= upper;
5753     }
5754 
5755     /**
5756      * Charactrs within a explicit value range
5757      */
5758     static CharPredicate Range(int lower, int upper) {
5759         if (upper < Character.MIN_HIGH_SURROGATE ||
5760             lower > Character.MAX_HIGH_SURROGATE &&
5761             upper < Character.MIN_SUPPLEMENTARY_CODE_POINT)
5762             return (BmpCharPredicate)(ch -> inRange(lower, ch, upper));
5763         return ch -> inRange(lower, ch, upper);
5764     }
5765 
5766    /**
5767     * Charactrs within a explicit value range in a case insensitive manner.
5768     */
5769     static CharPredicate CIRange(int lower, int upper) {
5770         return ch -> inRange(lower, ch, upper) ||
5771                      ASCII.isAscii(ch) &&
5772                      (inRange(lower, ASCII.toUpper(ch), upper) ||
5773                       inRange(lower, ASCII.toLower(ch), upper));
5774     }
5775 
5776     static CharPredicate CIRangeU(int lower, int upper) {
5777         return ch -> {
5778             if (inRange(lower, ch, upper))
5779                 return true;
5780             int up = Character.toUpperCase(ch);
5781             return inRange(lower, up, upper) ||
5782                    inRange(lower, Character.toLowerCase(up), upper);
5783         };
5784     }
5785 
5786     /**
5787      *  This must be the very first initializer.
5788      */
5789     static final Node accept = new Node();
5790 
5791     static final Node lastAccept = new LastNode();
5792 
5793     /**
5794      * Creates a predicate which can be used to match a string.
5795      *
5796      * @return  The predicate which can be used for matching on a string
5797      * @since   1.8
5798      */
5799     public Predicate<String> asPredicate() {
5800         return s -> matcher(s).find();
5801     }
5802 
5803     /**
5804      * Creates a stream from the given input sequence around matches of this
5805      * pattern.
5806      *
5807      * <p> The stream returned by this method contains each substring of the
5808      * input sequence that is terminated by another subsequence that matches
5809      * this pattern or is terminated by the end of the input sequence.  The
5810      * substrings in the stream are in the order in which they occur in the
5811      * input. Trailing empty strings will be discarded and not encountered in
5812      * the stream.
5813      *
5814      * <p> If this pattern does not match any subsequence of the input then
5815      * the resulting stream has just one element, namely the input sequence in
5816      * string form.
5817      *
5818      * <p> When there is a positive-width match at the beginning of the input
5819      * sequence then an empty leading substring is included at the beginning
5820      * of the stream. A zero-width match at the beginning however never produces
5821      * such empty leading substring.
5822      *
5823      * <p> If the input sequence is mutable, it must remain constant during the
5824      * execution of the terminal stream operation.  Otherwise, the result of the
5825      * terminal stream operation is undefined.
5826      *
5827      * @param   input
5828      *          The character sequence to be split
5829      *
5830      * @return  The stream of strings computed by splitting the input
5831      *          around matches of this pattern
5832      * @see     #split(CharSequence)
5833      * @since   1.8
5834      */
5835     public Stream<String> splitAsStream(final CharSequence input) {
5836         class MatcherIterator implements Iterator<String> {
5837             private Matcher matcher;
5838             // The start position of the next sub-sequence of input
5839             // when current == input.length there are no more elements
5840             private int current;
5841             // null if the next element, if any, needs to obtained
5842             private String nextElement;
5843             // > 0 if there are N next empty elements
5844             private int emptyElementCount;
5845 
5846             public String next() {
5847                 if (!hasNext())
5848                     throw new NoSuchElementException();
5849 
5850                 if (emptyElementCount == 0) {
5851                     String n = nextElement;
5852                     nextElement = null;
5853                     return n;
5854                 } else {
5855                     emptyElementCount--;
5856                     return "";
5857                 }
5858             }
5859 
5860             public boolean hasNext() {
5861                 if (matcher == null) {
5862                     matcher = matcher(input);
5863                     // If the input is an empty string then the result can only be a
5864                     // stream of the input.  Induce that by setting the empty
5865                     // element count to 1
5866                     emptyElementCount = input.length() == 0 ? 1 : 0;
5867                 }
5868                 if (nextElement != null || emptyElementCount > 0)
5869                     return true;
5870 
5871                 if (current == input.length())
5872                     return false;
5873 
5874                 // Consume the next matching element
5875                 // Count sequence of matching empty elements
5876                 while (matcher.find()) {
5877                     nextElement = input.subSequence(current, matcher.start()).toString();
5878                     current = matcher.end();
5879                     if (!nextElement.isEmpty()) {
5880                         return true;
5881                     } else if (current > 0) { // no empty leading substring for zero-width
5882                                               // match at the beginning of the input
5883                         emptyElementCount++;
5884                     }
5885                 }
5886 
5887                 // Consume last matching element
5888                 nextElement = input.subSequence(current, input.length()).toString();
5889                 current = input.length();
5890                 if (!nextElement.isEmpty()) {
5891                     return true;
5892                 } else {
5893                     // Ignore a terminal sequence of matching empty elements
5894                     emptyElementCount = 0;
5895                     nextElement = null;
5896                     return false;
5897                 }
5898             }
5899         }
5900         return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
5901                 new MatcherIterator(), Spliterator.ORDERED | Spliterator.NONNULL), false);
5902     }
5903 }