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