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