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