rev 57941 : [mq]: 8235812-Unicode-linebreak-with-quantifier-does-not-match-valid-input

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