Debian Codegraph @

net/sf/saxon/regex/RECompiler.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 /*
9 * Licensed to the Apache Software Foundation (ASF) under one or more
10 * contributor license agreements. See the NOTICE file distributed with
11 * this work for additional information regarding copyright ownership.
12 * The ASF licenses this file to You under the Apache License, Version 2.0
13 * (the "License"); you may not use this file except in compliance with
14 * the License. You may obtain a copy of the License at
15 *
16 * http://www.apache.org/licenses/LICENSE-2.0
17 *
18 * Unless required by applicable law or agreed to in writing, software
19 * distributed under the License is distributed on an "AS IS" BASIS,
20 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21 * See the License for the specific language governing permissions and
22 * limitations under the License.
23 */
24
25 /*
26 * Originally part of Apache's Jakarta project (downloaded January 2012),
27 * this file has been extensively modified for integration into Saxon by
28 * Michael Kay, Saxonica.
29 */
30
31 package net.sf.saxon.regex;
32
33 import net.sf.saxon.regex.charclass.*;
34 import net.sf.saxon.tree.util.FastStringBuffer;
35 import net.sf.saxon.value.Whitespace;
36 import net.sf.saxon.z.*;
37
38 import java.util.function.IntPredicate;
39
40 import java.util.ArrayList;
41 import java.util.Collections;
42 import java.util.List;
43
44 /**
45 * A regular expression compiler class. This class compiles a pattern string into a
46 * regular expression program interpretable by the RE evaluator class. The 'recompile'
47 * command line tool uses this compiler to pre-compile regular expressions for use
48 * with RE. For a description of the syntax accepted by RECompiler and what you can
49 * do with regular expressions, see the documentation for the RE matcher class.
50 *
51 * @author <a href="mailto:[email protected]">Jonathan Locke</a>
52 * @author <a href="mailto:[email protected]">Michael McCallum</a>
53 * @version $Id: RECompiler.java 518156 2007-03-14 14:31:26Z vgritsenko $
54 * @see net.sf.saxon.regex.REMatcher
55 */
56
57 /*
58 * Changes made for Saxon:
59 *
60 * - handle full Unicode repertoire (esp non-BMP characters) using UnicodeString class for
61 * both the source string and the regular expression
62 * - added support for subtraction in a character class
63 * - in a character range, changed the condition start < end to start <= end
64 * - removed support for [:POSIX:] construct
65 * - added support for \p{} and \P{} classes
66 * - removed support for unsupported escapes: f, x, u, b, octal characters; added i and c
67 * - changed the handling of hyphens within square brackets, and ^ appearing other than at the start
68 * - changed the data structure used for the executable so that terms that match a character class
69 * now reference an IntPredicate that tests for membership of the character in a set
70 * - added support for reluctant {n,m}? quantifiers
71 * - allow a quantifier on a nullable expression
72 * - allow a quantifier on '$' or '^'
73 * - some constructs (back-references, non-capturing groups, etc) are conditional on which XPath/XSD version
74 * is in use
75 * - regular expression flags are now fixed at the time the RE is compiled, this can no longer be deferred
76 * until the RE is evaluated
77 * - split() function includes a zero-length string at the end of the returned sequence if the last
78 * separator is at the end of the string
79 * - added support for the 'q' and 'x' flags; improved support for the 'i' flag
80 * - added a method to determine whether there is an anchored match (for XSD use)
81 * - tests for newline (e.g in multiline mode) now match \n only, as required by the XPath specification
82 * - reorganised the executable program to use Operation objects rather than integer opcodes
83 * - introduced optimization for non-backtracking + and * operators (with simple operands)
84 *
85 * Further changes made February 2014:
86 * - complete rewrite of the run-time engine to use an interpreter approach directly on the parsed expression
87 * tree, bypassing the generation of a finite state machine. This achieves a substantial reduction in
88 * recursive depth; the old code had one level of recursion per input character in some cases. In addition
89 * the compiled code for expressions involving large finite counters is much more compact.
90 */
91 public class RECompiler {
92
93 // Input state for compiling regular expression
94 UnicodeString pattern; // Input string
95 int len; // Length of the pattern string
96 int idx; // Current input index into ac
97 int capturingOpenParenCount; // Total number of paren pairs
98
99 // Node flags
100 static final int NODE_NORMAL = 0; // No flags (nothing special)
101 static final int NODE_TOPLEVEL = 2; // True if top level expr
102
103 // {m,n} stacks
104 int bracketMin; // Minimum number of matches
105 int bracketMax; // Maximum number of matches
106
107 boolean isXPath = true;
108 boolean isXPath30 = true;
109 boolean isXSD11 = false;
110 IntHashSet captures = new IntHashSet();
111 boolean hasBackReferences = false;
112
113 REFlags reFlags;
114
115 List<String> warnings;
116
117 private final static boolean TRACING = false;
118
119 /**
120 * Constructor. Creates (initially empty) storage for a regular expression program.
121 */
122 public RECompiler() {
123
124 }
125
126 /**
127 * Set the regular expression flags to be used
128 *
129 * @param flags the regular expression flags
130 */
131
132 public void setFlags(REFlags flags) {
133 this.reFlags = flags;
134 isXPath = flags.isAllowsXPath20Extensions();
135 isXPath30 = flags.isAllowsXPath30Extensions();
136 isXSD11 = flags.isAllowsXSD11Syntax();
137 }
138
139
140 private void warning(String s) {
141 if (warnings == null) {
142 warnings = new ArrayList<>(4);
143 }
144 warnings.add(s);
145 }
146
147 /**
148 * On completion of compilation, get any warnings that were generated
149 *
150 * @return the list of warning messages
151 */
152
153 public List<String> getWarnings() {
154 if (warnings == null) {
155 return Collections.emptyList();
156 } else {
157 return warnings;
158 }
159 }
160
161 /**
162 * Throws a new internal error exception
163 *
164 * @throws Error Thrown in the event of an internal error.
165 */
166 void internalError() throws Error {
167 throw new Error("Internal error!");
168 }
169
170 /**
171 * Throws a new syntax error exception
172 *
173 * @param s the error message
174 * @throws net.sf.saxon.regex.RESyntaxException
175 * Thrown if the regular expression has invalid syntax.
176 */
177 void syntaxError(String s) throws RESyntaxException {
178 throw new RESyntaxException(s, idx);
179 }
180
181 /**
182 * Optionally add trace code around an operation
183 * @param base the operation to which trace code is to be added
184 * @return the trace operation; this matches the same strings as the base operation,
185 * but traces its execution for diagnostic purposes, provided the TRACING switch is set.
186 */
187
188 static Operation trace(Operation base) {
189 if (TRACING && !(base instanceof Operation.OpTrace)) {
190 return new Operation.OpTrace(base);
191 } else {
192 return base;
193 }
194 }
195
196 /**
197 * Match bracket {m,n} expression, putting the results in bracket member variables
198 *
199 * @throws net.sf.saxon.regex.RESyntaxException
200 * Thrown if the regular expression has invalid syntax.
201 */
202 void bracket() throws RESyntaxException {
203 // Current character must be a '{'
204 if (idx >= len || pattern.uCharAt(idx++) != '{') {
205 internalError();
206 }
207
208 // Next char must be a digit
209 if (idx >= len || !isAsciiDigit(pattern.uCharAt(idx))) {
210 syntaxError("Expected digit");
211 }
212
213 // Get min ('m' of {m,n}) number
214 FastStringBuffer number = new FastStringBuffer(16);
215 while (idx < len && isAsciiDigit(pattern.uCharAt(idx))) {
216 number.append((char) pattern.uCharAt(idx++));
217 }
218 try {
219 bracketMin = Integer.parseInt(number.toString());
220 } catch (NumberFormatException e) {
221 syntaxError("Expected valid number");
222 }
223
224 // If out of input, fail
225 if (idx >= len) {
226 syntaxError("Expected comma or right bracket");
227 }
228
229 // If end of expr, optional limit is 0
230 if (pattern.uCharAt(idx) == '}') {
231 idx++;
232 bracketMax = bracketMin;
233 return;
234 }
235
236 // Must have at least {m,} and maybe {m,n}.
237 if (idx >= len || pattern.uCharAt(idx++) != ',') {
238 syntaxError("Expected comma");
239 }
240
241 // If out of input, fail
242 if (idx >= len) {
243 syntaxError("Expected comma or right bracket");
244 }
245
246 // If {m,} max is unlimited
247 if (pattern.uCharAt(idx) == '}') {
248 idx++;
249 bracketMax = Integer.MAX_VALUE;
250 return;
251 }
252
253 // Next char must be a digit
254 if (idx >= len || !isAsciiDigit(pattern.uCharAt(idx))) {
255 syntaxError("Expected digit");
256 }
257
258 // Get max number
259 number.setLength(0);
260 while (idx < len && isAsciiDigit(pattern.uCharAt(idx))) {
261 number.append((char) pattern.uCharAt(idx++));
262 }
263 try {
264 bracketMax = Integer.parseInt(number.toString());
265 } catch (NumberFormatException e) {
266 syntaxError("Expected valid number");
267 }
268
269 // Optional repetitions must be >= 0
270 if (bracketMax < bracketMin) {
271 syntaxError("Bad range");
272 }
273
274 // Must have close brace
275 if (idx >= len || pattern.uCharAt(idx++) != '}') {
276 syntaxError("Missing close brace");
277 }
278 }
279
280 /**
281 * Test whether a character is an ASCII decimal digit
282 *
283 * @param ch the character to be matched
284 * @return true if the character is an ASCII digit (0-9)
285 */
286
287 private static boolean isAsciiDigit(int ch) {
288 return ch >= '0' && ch <= '9';
289 }
290
291 /**
292 * Match an escape sequence. Handles quoted chars and octal escapes as well
293 * as normal escape characters. Always advances the input stream by the
294 * right amount. This code "understands" the subtle difference between an
295 * octal escape and a backref. You can access the type of ESC_CLASS or
296 * ESC_COMPLEX or ESC_BACKREF by looking at pattern[idx - 1].
297 * @param inSquareBrackets true if the escape sequence is within square brackets
298 * @return an IntPredicate that matches the character or characters represented
299 * by this escape sequence. For a single-character escape this must be an IntValuePredicate
300 * @throws net.sf.saxon.regex.RESyntaxException
301 * Thrown if the regular expression has invalid syntax.
302 */
303 CharacterClass escape(boolean inSquareBrackets) throws RESyntaxException {
304 // "Shouldn't" happen
305 if (pattern.uCharAt(idx) != '\\') {
306 internalError();
307 }
308
309 // Escape shouldn't occur as last character in string!
310 if (idx + 1 == len) {
311 syntaxError("Escape terminates string");
312 }
313
314 // Switch on character after backslash
315 idx += 2;
316 int escapeChar = pattern.uCharAt(idx - 1);
317 switch (escapeChar) {
318
319 case 'n':
320 return new SingletonCharacterClass('\n');
321 case 'r':
322 return new SingletonCharacterClass('\r');
323 case 't':
324 return new SingletonCharacterClass('\t');
325
326 case '\\':
327 case '|':
328 case '.':
329 case '-':
330 case '^':
331 case '?':
332 case '*':
333 case '+':
334 case '{':
335 case '}':
336 case '(':
337 case ')':
338 case '[':
339 case ']':
340 return new SingletonCharacterClass(escapeChar);
341
342 case '$':
343 if (isXPath) {
344 return new SingletonCharacterClass(escapeChar);
345 } else {
346 syntaxError("In XSD, '$' must not be escaped");
347 }
348
349 case 's':
350 return Categories.ESCAPE_s;
351
352 case 'S':
353 return Categories.ESCAPE_S;
354
355 case 'i':
356 return Categories.ESCAPE_i;
357
358 case 'I':
359 return Categories.ESCAPE_I;
360
361 case 'c':
362 return Categories.ESCAPE_c;
363
364 case 'C':
365 return Categories.ESCAPE_C;
366
367 case 'd':
368 return Categories.ESCAPE_d;
369
370 case 'D':
371 return Categories.ESCAPE_D;
372
373 case 'w':
374 return Categories.ESCAPE_w;
375
376 case 'W':
377 return Categories.ESCAPE_W;
378
379
380 case 'p':
381 case 'P':
382
383 if (idx == len) {
384 syntaxError("Expected '{' after \\" + escapeChar);
385 }
386 if (pattern.uCharAt(idx) != '{') {
387 syntaxError("Expected '{' after \\" + escapeChar);
388 }
389 int close = pattern.uIndexOf('}', idx++);
390 if (close == -1) {
391 syntaxError("No closing '}' after \\" + escapeChar);
392 }
393 UnicodeString block = pattern.uSubstring(idx, close);
394 if (block.uLength() == 1 || block.uLength() == 2) {
395 CharacterClass primary = Categories.getCategory(block.toString());
396 if (primary == null) {
397 syntaxError("Unknown character category " + block.toString());
398 }
399 idx = close + 1;
400 if (escapeChar == 'p') {
401 return primary;
402 } else {
403 return makeComplement(primary);
404 }
405 } else if (block.toString().startsWith("Is")) {
406 String blockName = block.toString().substring(2);
407 IntSet uniBlock = UnicodeBlocks.getBlock(blockName);
408 if (uniBlock == null) {
409 // XSD 1.1 says this is not an error, but by default we reject it
410 if (reFlags.isAllowUnknownBlockNames()) {
411 warning("Unknown Unicode block: " + blockName);
412 idx = close + 1;
413 return EmptyCharacterClass.getComplement();
414 } else {
415 syntaxError("Unknown Unicode block: " + blockName);
416 }
417 }
418 idx = close + 1;
419 IntSetCharacterClass primary = new IntSetCharacterClass(uniBlock);
420 if (escapeChar == 'p') {
421 return primary;
422 } else {
423 return makeComplement(primary);
424 }
425 } else {
426 syntaxError("Unknown character category: " + block);
427 }
428
429 case '0':
430 syntaxError("Octal escapes not allowed");
431
432 case '1':
433 case '2':
434 case '3':
435 case '4':
436 case '5':
437 case '6':
438 case '7':
439 case '8':
440 case '9':
441
442 if (inSquareBrackets) {
443 syntaxError("Backreference not allowed within character class");
444 } else if (isXPath) {
445 int backRef = escapeChar - '0';
446 while (idx < len) {
447 int c1 = "0123456789".indexOf(pattern.uCharAt(idx));
448 if (c1 < 0) {
449 break;
450 } else {
451 int backRef2 = backRef * 10 + c1;
452 if (backRef2 > (capturingOpenParenCount - 1)) {
453 break;
454 } else {
455 backRef = backRef2;
456 idx++;
457 }
458 }
459
460 }
461 if (!captures.contains(backRef)) {
462 String explanation = backRef > (capturingOpenParenCount - 1) ? "(no such group)" : "(group not yet closed)";
463 syntaxError("invalid backreference \\" + backRef + " " + explanation);
464 }
465 hasBackReferences = true;
466 return new BackReference(backRef);
467 } else {
468 syntaxError("digit not allowed after \\");
469 }
470
471 default:
472
473 // Other characters not allowed in XSD regexes
474 syntaxError("Escape character '" + (char) escapeChar + "' not allowed");
475 }
476 return null;
477 }
478
479 /**
480 * For convenience a back-reference is treated as an CharacterClass, although this a fiction
481 */
482
483 class BackReference extends SingletonCharacterClass {
484 public BackReference(int number) {
485 super(number);
486 }
487 }
488
489
490 /**
491 * Compile a character class (in square brackets)
492 *
493 * @return an IntPredicate that tests whether a character matches this character class
494 * @throws net.sf.saxon.regex.RESyntaxException
495 * Thrown if the regular expression has invalid syntax.
496 */
497 CharacterClass parseCharacterClass() throws RESyntaxException {
498 // Check for bad calling or empty class
499 if (pattern.uCharAt(idx) != '[') {
500 internalError();
501 }
502
503 // Check for unterminated or empty class
504 if ((idx + 1) >= len || pattern.uCharAt(++idx) == ']') {
505 syntaxError("Missing ']'");
506 }
507
508 // Parse class declaration
509 int simpleChar;
510 boolean positive = true;
511 boolean definingRange = false;
512 int rangeStart = -1;
513 int rangeEnd;
514 IntRangeSet range = new IntRangeSet();
515 CharacterClass addend = null;
516 CharacterClass subtrahend = null;
517 if (thereFollows("^")) {
518 if (thereFollows("^-[")) {
519 syntaxError("Nothing before subtraction operator");
520 } else if (thereFollows("^]")) {
521 syntaxError("Empty negative character group");
522 } else {
523 positive = false;
524 idx++;
525 }
526 } else if (thereFollows("-[")) {
527 syntaxError("Nothing before subtraction operator");
528 }
529 while (idx < len && pattern.uCharAt(idx) != ']') {
530 int ch = pattern.uCharAt(idx);
531 simpleChar = -1;
532 switch (ch) {
533 case '[':
534 syntaxError("Unescaped '[' within square brackets");
535 break;
536 case '\\': {
537 // Escape always advances the stream
538 CharacterClass cc = escape(true);
539 if (cc instanceof SingletonCharacterClass) {
540 simpleChar = ((SingletonCharacterClass) cc).getCodepoint();
541 break;
542 } else {
543 if (definingRange) {
544 syntaxError("Multi-character escape cannot follow '-'");
545 } else if (addend == null) {
546 addend = cc;
547 } else {
548 addend = makeUnion(addend, cc);
549 }
550 continue;
551 }
552 }
553 case '-':
554 if (thereFollows("-[")) {
555 idx++;
556 subtrahend = parseCharacterClass();
557 if (!thereFollows("]")) {
558 syntaxError("Expected closing ']' after subtraction");
559 }
560 } else if (thereFollows("-]")) {
561 simpleChar = '-';
562 idx++;
563 } else if (rangeStart >= 0) {
564 definingRange = true;
565 idx++;
566 continue;
567 } else if (definingRange) {
568 syntaxError("Bad range");
569 } else if (thereFollows("--") && !thereFollows("--[")) {
570 syntaxError("Unescaped hyphen as start of range");
571 } else if (!isXSD11 && pattern.uCharAt(idx - 1) != '[' && pattern.uCharAt(idx - 1) != '^' && !thereFollows("]") && !thereFollows("-[")) {
572 syntaxError("In XSD 1.0, hyphen is allowed only at the beginning or end of a positive character group");
573 } else {
574 simpleChar = '-';
575 idx++;
576 }
577 break;
578
579 default:
580 simpleChar = ch;
581 idx++;
582 break;
583 }
584
585 // Handle simple character simpleChar
586 if (definingRange) {
587 // if we are defining a range make it now
588 rangeEnd = simpleChar;
589
590 // Actually create a range if the range is ok
591 if (rangeStart > rangeEnd) {
592 syntaxError("Bad character range: start > end");
593 // Technically this is not an error in XSD, merely a no-op; but it is so
594 // utterly pointless that it is almost certainly a mistake; and we have no
595 // way of indicating warnings.
596 }
597 range.addRange(rangeStart, rangeEnd);
598 if (reFlags.isCaseIndependent()) {
599 // Special-case A-Z and a-z
600 if (rangeStart == 'a' && rangeEnd == 'z') {
601 range.addRange('A', 'Z');
602 for (int v = 0; v < CaseVariants.ROMAN_VARIANTS.length; v++) {
603 range.add(CaseVariants.ROMAN_VARIANTS[v]);
604 }
605 } else if (rangeStart == 'A' && rangeEnd == 'Z') {
606 range.addRange('a', 'z');
607 for (int v = 0; v < CaseVariants.ROMAN_VARIANTS.length; v++) {
608 range.add(CaseVariants.ROMAN_VARIANTS[v]);
609 }
610 } else {
611 for (int k = rangeStart; k <= rangeEnd; k++) {
612 int[] variants = CaseVariants.getCaseVariants(k);
613 for (int variant : variants) {
614 range.add(variant);
615 }
616 }
617 }
618 }
619
620 // We are done defining the range
621 definingRange = false;
622 rangeStart = -1;
623 } else {
624 // If simple character and not start of range, include it (see XSD 1.1 rules)
625 if (thereFollows("-")) {
626 if (thereFollows("-[")) {
627 range.add(simpleChar);
628 } else if (thereFollows("-]")) {
629 range.add(simpleChar);
630 } else if (thereFollows("--[")) {
631 range.add(simpleChar);
632 } else if (thereFollows("--")) {
633 syntaxError("Unescaped hyphen cannot act as end of range");
634 } else {
635 rangeStart = simpleChar;
636 }
637 } else {
638 range.add(simpleChar);
639 if (reFlags.isCaseIndependent()) {
640 int[] variants = CaseVariants.getCaseVariants(simpleChar);
641 for (int variant : variants) {
642 range.add(variant);
643 }
644 }
645 }
646 }
647 }
648
649 // Shouldn't be out of input
650 if (idx == len) {
651 syntaxError("Unterminated character class");
652 }
653
654 // Absorb the ']' end of class marker
655 idx++;
656 CharacterClass result = new IntSetCharacterClass(range);
657 if (addend != null) {
658 result = makeUnion(result, addend);
659 }
660 if (!positive) {
661 result = makeComplement(result);
662 }
663 if (subtrahend != null) {
664 result = makeDifference(result, subtrahend);
665 }
666 return result;
667 }
668
669 /**
670 * Test whether the string starting at the current position is equal to some specified string
671 *
672 * @param s the string being tested
673 * @return true if the specified string is present
674 */
675
676 private boolean thereFollows(String s) {
677 return idx + s.length() <= len &&
678 pattern.uSubstring(idx, idx + s.length()).toString().equals(s);
679 }
680
681 /**
682 * Make the union of two IntPredicates (matches if p1 matches or p2 matches)
683 *
684 * @param p1 the first
685 * @param p2 the second
686 * @return the result
687 */
688
689 public static CharacterClass makeUnion(CharacterClass p1, CharacterClass p2) {
690 if (p1 == EmptyCharacterClass.getInstance()) {
691 return p2;
692 }
693 if (p2 == EmptyCharacterClass.getInstance()) {
694 return p1;
695 }
696 IntSet is1 = p1.getIntSet();
697 IntSet is2 = p2.getIntSet();
698 if (is1 == null || is2 == null) {
699 return new PredicateCharacterClass(p1.or(p2));
700 } else {
701 return new IntSetCharacterClass(is1.union(is2));
702 }
703 }
704
705 /**
706 * Make the difference of two IntPredicates (matches if p1 matches and p2 does not match)
707 *
708 * @param p1 the first
709 * @param p2 the second
710 * @return the result
711 */
712
713 public static CharacterClass makeDifference(CharacterClass p1, CharacterClass p2) {
714 if (p1 == EmptyCharacterClass.getInstance()) {
715 return p1;
716 }
717 if (p2 == EmptyCharacterClass.getInstance()) {
718 return p1;
719 }
720 IntSet is1 = p1.getIntSet();
721 IntSet is2 = p2.getIntSet();
722 if (is1 == null || is2 == null) {
723 return new PredicateCharacterClass(new IntExceptPredicate(p1, p2));
724 } else {
725 return new IntSetCharacterClass(is1.except(is2));
726 }
727 }
728
729 /**
730 * Make the complement of an IntPredicate (matches if p1 does not match)
731 *
732 * @param p1 the operand
733 * @return the result
734 */
735
736 public static CharacterClass makeComplement(CharacterClass p1) {
737 if (p1 instanceof InverseCharacterClass) {
738 return ((InverseCharacterClass) p1).getComplement();
739 } else {
740 return new InverseCharacterClass(p1);
741 }
742 }
743
744 /**
745 * Absorb an atomic character string. This method is a little tricky because
746 * it can un-include the last character of string if a quantifier operator follows.
747 * This is correct because *+? have higher precedence than concatentation (thus
748 * ABC* means AB(C*) and NOT (ABC)*).
749 *
750 * @return Index of new atom node
751 * @throws net.sf.saxon.regex.RESyntaxException
752 * Thrown if the regular expression has invalid syntax.
753 */
754 Operation parseAtom() throws RESyntaxException {
755
756 // Length of atom
757 int lenAtom = 0;
758
759 // Loop while we've got input
760
761 FastStringBuffer fsb = new FastStringBuffer(FastStringBuffer.C64);
762
763 atomLoop:
764
765 while (idx < len) {
766 // Is there a next char?
767 if ((idx + 1) < len) {
768 int c = pattern.uCharAt(idx + 1);
769
770 // If the next 'char' is an escape, look past the whole escape
771 if (pattern.uCharAt(idx) == '\\') {
772 int idxEscape = idx;
773 escape(false);
774 if (idx < len) {
775 c = pattern.uCharAt(idx);
776 }
777 idx = idxEscape;
778 }
779
780 // Switch on next char
781 switch (c) {
782 case '{':
783 case '?':
784 case '*':
785 case '+':
786
787 // If the next character is a quantifier operator and our atom is non-empty, the
788 // current character should bind to the quantifier operator rather than the atom
789 if (lenAtom != 0) {
790 break atomLoop;
791 }
792 }
793 }
794
795 // Switch on current char
796 switch (pattern.uCharAt(idx)) {
797 case ']':
798 case '.':
799 case '[':
800 case '(':
801 case ')':
802 case '|':
803 break atomLoop;
804
805 case '{':
806 case '?':
807 case '*':
808 case '+':
809
810 // We should have an atom by now
811 if (lenAtom == 0) {
812 // No atom before quantifier
813 syntaxError("No expression before quantifier");
814 }
815 break atomLoop;
816
817 case '\\': {
818 // Get the escaped character (advances input automatically)
819 int idxBeforeEscape = idx;
820 IntPredicate charClass = escape(false);
821
822 // Check if it's a simple escape (as opposed to, say, a backreference)
823 if (charClass instanceof BackReference || !(charClass instanceof IntValuePredicate)) {
824 // Not a simple escape, so backup to where we were before the escape.
825 idx = idxBeforeEscape;
826 break atomLoop;
827 }
828
829 // Add escaped char to atom
830 fsb.appendWideChar(((IntValuePredicate) charClass).getTarget());
831 lenAtom++;
832 break;
833 }
834
835 case '^':
836 case '$':
837 if (isXPath) {
838 break atomLoop;
839 }
840 // else fall through ($ is not a metacharacter in XSD)
841
842 default:
843
844 // Add normal character to atom
845 fsb.appendWideChar(pattern.uCharAt(idx++));
846 lenAtom++;
847 break;
848 }
849 }
850
851 // This shouldn't happen
852 if (fsb.isEmpty()) {
853 internalError();
854 }
855
856 // Return the instruction
857 return trace(new Operation.OpAtom(UnicodeString.makeUnicodeString(fsb.condense())));
858 }
859
860
861 /**
862 * Match a terminal symbol.
863 *
864 * @param flags Flags
865 * @return Index of terminal node (closeable)
866 * @throws net.sf.saxon.regex.RESyntaxException
867 * Thrown if the regular expression has invalid syntax.
868 */
869 Operation parseTerminal(int[] flags) throws RESyntaxException {
870 switch (pattern.uCharAt(idx)) {
871 case '$':
872 if (isXPath) {
873 idx++;
874 return trace(new Operation.OpEOL());
875 }
876 break;
877
878 case '^':
879 if (isXPath) {
880 idx++;
881 return trace(new Operation.OpBOL());
882 }
883 break;
884
885 case '.':
886 idx++;
887 IntPredicate predicate;
888 if (reFlags.isSingleLine()) {
889 // in XPath with the 's' flag, '.' matches everything
890 predicate = IntSetPredicate.ALWAYS_TRUE;
891 } else {
892 // in XSD, "." matches everything except \n and \r. See also bug 15594.
893 predicate = value -> value != '\n' && value != '\r';
894 }
895 return trace(new Operation.OpCharClass(predicate));
896
897 case '[':
898 CharacterClass range = parseCharacterClass();
899 return trace(new Operation.OpCharClass(range));
900
901 case '(':
902 return parseExpr(flags);
903
904 case ')':
905 syntaxError("Unexpected closing ')'");
906
907 case '|':
908 internalError();
909
910 case ']':
911 syntaxError("Unexpected closing ']'");
912
913 case 0:
914 syntaxError("Unexpected end of input");
915
916 case '?':
917 case '+':
918 case '{':
919 case '*':
920 syntaxError("No expression before quantifier");
921
922 case '\\': {
923 // Don't forget, escape() advances the input stream!
924 int idxBeforeEscape = idx;
925
926 CharacterClass esc = escape(false);
927
928 if (esc instanceof BackReference) {
929 // this is a total kludge
930 int backreference = ((BackReference) esc).getCodepoint();
931 if (capturingOpenParenCount <= backreference) {
932 syntaxError("Bad backreference");
933 }
934 return trace(new Operation.OpBackReference(backreference));
935
936 } else if (esc instanceof IntSingletonSet) {
937 // We had a simple escape and we want to have it end up in
938 // an atom, so we back up and fall though to the default handling
939 idx = idxBeforeEscape;
940
941 } else {
942 return trace(new Operation.OpCharClass(esc));
943 }
944
945 }
946 }
947
948 // Everything above either fails or returns.
949 // If it wasn't one of the above, it must be the start of an atom.
950 return parseAtom();
951 }
952
953 /**
954 * Compile a piece consisting of an atom and optional quantifier
955 *
956 * @param flags Flags passed by reference
957 * @return Index of resulting instruction
958 * @throws net.sf.saxon.regex.RESyntaxException
959 * Thrown if the regular expression has invalid syntax.
960 */
961 Operation piece(int[] flags) throws RESyntaxException {
962
963 // Values to pass by reference to terminal()
964 int[] terminalFlags = {NODE_NORMAL};
965
966 // Get terminal symbol
967 Operation ret = parseTerminal(terminalFlags);
968
969 // Or in flags from terminal symbol
970 flags[0] |= terminalFlags[0];
971
972 // Advance input, set NODE_NULLABLE flag and do sanity checks
973 if (idx >= len) {
974 return ret;
975 }
976
977 boolean greedy = true;
978 int quantifierType = pattern.uCharAt(idx);
979 switch (quantifierType) {
980 case '?':
981 case '*':
982 case '+':
983
984 // Eat quantifier character
985 idx++;
986
987 // Drop through
988
989 case '{':
990
991 if (quantifierType == '{') {
992 bracket();
993 }
994
995
996 if (ret instanceof Operation.OpBOL || ret instanceof Operation.OpEOL) {
997 // Pretty meaningless, but legal. If the quantifier allows zero occurrences, ignore the instruction.
998 // Otherwise, ignore the quantifier
999 if (quantifierType == '?' || quantifierType == '*' ||
1000 (quantifierType == '{' && bracketMin == 0)) {
1001 return new Operation.OpNothing();
1002 } else {
1003 quantifierType = 0;
1004 }
1005 }
1006 if (ret.matchesEmptyString() == Operation.MATCHES_ZLS_ANYWHERE) {
1007 if (quantifierType == '?') {
1008 // can ignore the quantifier
1009 quantifierType = 0;
1010 } else if (quantifierType == '+') {
1011 // '*' and '+' are equivalent
1012 quantifierType = '*';
1013 } else if (quantifierType == '{') {
1014 // bounds are meaningless
1015 quantifierType = '*';
1016 }
1017 }
1018
1019 }
1020
1021 // If the next character is a '?', make the quantifier non-greedy (reluctant)
1022 if (idx < len && pattern.uCharAt(idx) == '?') {
1023 if (!isXPath) {
1024 syntaxError("Reluctant quantifiers are not allowed in XSD");
1025 }
1026 idx++;
1027 greedy = false;
1028 }
1029 int min = 1;
1030 int max = 1;
1031 switch (quantifierType) {
1032 case '{':
1033 min = this.bracketMin;
1034 max = this.bracketMax;
1035 break;
1036 case '?':
1037 min = 0;
1038 max = 1;
1039 break;
1040 case '+':
1041 min = 1;
1042 max = Integer.MAX_VALUE;
1043 break;
1044 case '*':
1045 min = 0;
1046 max = Integer.MAX_VALUE;
1047 break;
1048 }
1049
1050 Operation result;
1051 if (max == 0) {
1052 result = new Operation.OpNothing();
1053 } else if (min == 1 && max == 1) {
1054 return ret;
1055 } else if (greedy) {
1056 // Actually do the quantifier now
1057 if (ret.getMatchLength() == -1) {
1058 result = trace(new Operation.OpRepeat(ret, min, max, true));
1059 } else {
1060 result = new Operation.OpGreedyFixed(ret, min, max, ret.getMatchLength());
1061 }
1062 } else {
1063 if (ret.getMatchLength() == -1) {
1064 result = new Operation.OpRepeat(ret, min, max, false);
1065 } else {
1066 result = new Operation.OpReluctantFixed(ret, min, max, ret.getMatchLength());
1067 }
1068 }
1069 return trace(result);
1070
1071 }
1072
1073 /**
1074 * Compile body of one branch of an or operator (implements concatenation)
1075 *
1076 * @return Pointer to first node in the branch
1077 * @throws net.sf.saxon.regex.RESyntaxException
1078 * Thrown if the regular expression has invalid syntax.
1079 */
1080 Operation parseBranch() throws RESyntaxException {
1081 // Get each possibly qnatified piece and concat
1082 Operation current = null;
1083 int[] quantifierFlags = new int[1];
1084 while (idx < len && pattern.uCharAt(idx) != '|' && pattern.uCharAt(idx) != ')') {
1085 // Get new node
1086 quantifierFlags[0] = NODE_NORMAL;
1087 Operation op = piece(quantifierFlags);
1088 if (current == null) {
1089 current = op;
1090 } else {
1091 current = makeSequence(current, op);
1092 }
1093 }
1094
1095 // If we don't run loop, make a nothing node
1096 if (current == null) {
1097 return new Operation.OpNothing();
1098 }
1099
1100 return current;
1101 }
1102
1103 /**
1104 * Compile an expression with possible parens around it. Paren matching
1105 * is done at this level so we can tie the branch tails together.
1106 *
1107 * @param compilerFlags Flag value passed by reference
1108 * @return Node index of expression in instruction array
1109 * @throws net.sf.saxon.regex.RESyntaxException
1110 * Thrown if the regular expression has invalid syntax.
1111 */
1112 private Operation parseExpr(int[] compilerFlags) throws RESyntaxException {
1113 // Create open paren node unless we were called from the top level (which has no parens)
1114 int paren = -1;
1115 int group = 0;
1116 List<Operation> branches = new ArrayList<>();
1117 int closeParens = capturingOpenParenCount;
1118 boolean capturing = true;
1119 if ((compilerFlags[0] & NODE_TOPLEVEL) == 0 && pattern.uCharAt(idx) == '(') {
1120 // if its a cluster ( rather than a proper subexpression ie with backrefs )
1121 if (idx + 2 < len && pattern.uCharAt(idx + 1) == '?' && pattern.uCharAt(idx + 2) == ':') {
1122 if (!isXPath30) {
1123 syntaxError("Non-capturing groups allowed only in XPath3.0");
1124 }
1125 paren = 2;
1126 idx += 3;
1127 capturing = false;
1128 } else {
1129 paren = 1;
1130 idx++;
1131 group = capturingOpenParenCount++;
1132 }
1133 }
1134 compilerFlags[0] &= ~NODE_TOPLEVEL;
1135
1136 // Process contents of first branch node
1137 branches.add(parseBranch());
1138
1139 // Loop through branches
1140 while (idx < len && pattern.uCharAt(idx) == '|') {
1141 idx++;
1142 branches.add(parseBranch());
1143 }
1144
1145 Operation op;
1146 if (branches.size() == 1) {
1147 op = branches.get(0);
1148 } else {
1149 op = new Operation.OpChoice(branches);
1150 }
1151
1152 // Create an ending node (either a close paren or an OP_END)
1153 if (paren > 0) {
1154 if (idx < len && pattern.uCharAt(idx) == ')') {
1155 idx++;
1156 } else {
1157 syntaxError("Missing close paren");
1158 }
1159 if (capturing) {
1160 op = new Operation.OpCapture(op, group);
1161 captures.add(closeParens);
1162 } else {
1163 // return op unchanged
1164 }
1165 } else {
1166 op = makeSequence(op, new Operation.OpEndProgram());
1167 }
1168
1169 // Return the node list
1170 return op;
1171 }
1172
1173 private static Operation makeSequence(Operation o1, Operation o2) {
1174 if (o1 instanceof Operation.OpSequence) {
1175 if (o2 instanceof Operation.OpSequence) {
1176 List<Operation> l1 = ((Operation.OpSequence)o1).getOperations();
1177 List<Operation> l2 = ((Operation.OpSequence)o2).getOperations();
1178 l1.addAll(l2);
1179 return o1;
1180 }
1181 List<Operation> l1 = ((Operation.OpSequence)o1).getOperations();
1182 l1.add(o2);
1183 return o1;
1184 } else if (o2 instanceof Operation.OpSequence) {
1185 List<Operation> l2 = ((Operation.OpSequence)o2).getOperations();
1186 l2.add(0, o1);
1187 return o2;
1188 } else {
1189 List<Operation> list = new ArrayList<>(4);
1190 list.add(o1);
1191 list.add(o2);
1192 return trace(new Operation.OpSequence(list));
1193 }
1194 }
1195
1196 /**
1197 * Compiles a regular expression pattern into a program runnable by the pattern
1198 * matcher class 'RE'.
1199 *
1200 * @param pattern Regular expression pattern to compile (see RECompiler class
1201 * for details).
1202 * @return A compiled regular expression program.
1203 * @throws net.sf.saxon.regex.RESyntaxException
1204 * Thrown if the regular expression has invalid syntax.
1205 * @see RECompiler
1206 * @see net.sf.saxon.regex.REMatcher
1207 */
1208 public REProgram compile(UnicodeString pattern) throws RESyntaxException {
1209 // Initialize variables for compilation
1210 //System.err.println("Compiling regex " + pattern);
1211 this.pattern = pattern; // Save pattern in instance variable
1212 len = pattern.uLength(); // Precompute pattern length for speed
1213 idx = 0; // Set parsing index to the first character
1214 capturingOpenParenCount = 1; // Set paren level to 1 (the implicit outer parens)
1215
1216 if (reFlags.isLiteral()) {
1217
1218 // 'q' flag is set
1219 // Create a string node
1220 Operation ret = new Operation.OpAtom(this.pattern);
1221 Operation endNode = new Operation.OpEndProgram();
1222 Operation seq = makeSequence(ret, endNode);
1223 return new REProgram(seq, capturingOpenParenCount, reFlags);
1224
1225 } else {
1226
1227 if (reFlags.isAllowWhitespace()) {
1228 // 'x' flag is set. Preprocess the expression to strip whitespace, other than between
1229 // square brackets
1230 FastStringBuffer sb = new FastStringBuffer(pattern.uLength());
1231 int nesting = 0;
1232 boolean astral = false;
1233 boolean escaped = false;
1234 for (int i = 0; i < pattern.uLength(); i++) {
1235 int ch = pattern.uCharAt(i);
1236 if (ch > 65535) {
1237 astral = true;
1238 }
1239 if (ch == '\\' && !escaped) {
1240 escaped = true;
1241 sb.appendWideChar(ch);
1242 } else if (ch == '[' && !escaped) {
1243 nesting++;
1244 escaped = false;
1245 sb.appendWideChar(ch);
1246 } else if (ch == ']' && !escaped) {
1247 nesting--;
1248 escaped = false;
1249 sb.appendWideChar(ch);
1250 } else if (nesting == 0 && Whitespace.isWhitespace(ch)) {
1251 // no action
1252 } else {
1253 escaped = false;
1254 sb.appendWideChar(ch);
1255 }
1256 }
1257 if (astral) {
1258 pattern = new GeneralUnicodeString(sb);
1259 } else {
1260 pattern = new BMPString(sb);
1261 }
1262 this.pattern = pattern;
1263 this.len = pattern.uLength();
1264 }
1265
1266 // Initialize pass by reference flags value
1267 int[] compilerFlags = {NODE_TOPLEVEL};
1268
1269 // Parse expression
1270 Operation exp = parseExpr(compilerFlags);
1271
1272 // Should be at end of input
1273 if (idx != len) {
1274 if (pattern.uCharAt(idx) == ')') {
1275 syntaxError("Unmatched close paren");
1276 }
1277 syntaxError("Unexpected input remains");
1278 }
1279
1280 REProgram program = new REProgram(exp, capturingOpenParenCount, reFlags);
1281 if (hasBackReferences) {
1282 program.optimizationFlags |= REProgram.OPT_HASBACKREFS;
1283 }
1284 return program;
1285
1286 }
1287
1288 }
1289
1290
1291 /**
1292 * Determine that there is no ambiguity between two branches, that is, if one of them matches then the
1293 * other cannot possibly match. (This is for optimization, so it does not have to detect all cases; but
1294 * if it returns true, then the result must be dependable.)
1295 * @param op0 the first branch
1296 * @param op1 the second branch
1297 * @param caseBlind true if the "i" flag is in force
1298 * @param reluctant true if the first branch is a repeat branch with a reluctant quantifier
1299 * @return true if it can be established that there is no input sequence that will match both instructions
1300 */
1301
1302 static boolean noAmbiguity(Operation op0, Operation op1, boolean caseBlind, boolean reluctant) {
1303 if (op1 instanceof Operation.OpEndProgram) {
1304 return !reluctant;
1305 }
1306 if (op1 instanceof Operation.OpBOL || op1 instanceof Operation.OpEOL) {
1307 return true;
1308 }
1309 if (op1 instanceof Operation.OpRepeat && ((Operation.OpRepeat)op1).min == 0) {
1310 return false; //Bug 3429
1311 }
1312 CharacterClass c0 = op0.getInitialCharacterClass(caseBlind);
1313 CharacterClass c1 = op1.getInitialCharacterClass(caseBlind);
1314 return c0.isDisjoint(c1);
1315 }
1316
1317 }