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