Debian Codegraph @

net/sf/saxon/expr/parser/Tokenizer.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 package net.sf.saxon.expr.parser;
9
10 import net.sf.saxon.om.NameChecker;
11 import net.sf.saxon.trans.XPathException;
12 import net.sf.saxon.value.Whitespace;
13
14 import java.util.ArrayList;
15 import java.util.List;
16
17 /**
18 * Tokenizer for expressions and inputs.
19 * <p>This code was originally derived from James Clark's xt, though it has been greatly modified since.
20 * See copyright notice at end of file.</p>
21 */
22
23
24 @SuppressWarnings({"StringEquality"})
25 public final class Tokenizer {
26
27
28 private int state = DEFAULT_STATE;
29 // we may need to make this a stack at some time
30
31 /**
32 * Initial default state of the Tokenizer
33 */
34 public static final int DEFAULT_STATE = 0;
35
36 /**
37 * State in which a name is NOT to be merged with what comes next, for example "("
38 */
39 public static final int BARE_NAME_STATE = 1;
40
41 /**
42 * State in which the next thing to be read is a SequenceType
43 */
44 public static final int SEQUENCE_TYPE_STATE = 2;
45 /**
46 * State in which the next thing to be read is an operator
47 */
48
49 public static final int OPERATOR_STATE = 3;
50
51 /**
52 * The number identifying the most recently read token
53 */
54 public int currentToken = Token.EOF;
55 /**
56 * The string value of the most recently read token
57 */
58 /*@Nullable*/ public String currentTokenValue = null;
59 /**
60 * The position in the input expression where the current token starts
61 */
62 public int currentTokenStartOffset = 0;
63 /**
64 * The number of the next token to be returned
65 */
66 private int nextToken = Token.EOF;
67 /**
68 * The string value of the next token to be returned
69 */
70 private String nextTokenValue = null;
71 /**
72 * The position in the expression of the start of the next token
73 */
74 private int nextTokenStartOffset = 0;
75 /**
76 * The string being parsed
77 */
78 public String input;
79 /**
80 * The current position within the input string
81 */
82 public int inputOffset = 0;
83 /**
84 * The length of the input string
85 */
86 private int inputLength;
87 /**
88 * The line number (within the expression) of the current token
89 */
90 private int lineNumber = 1;
91 /**
92 * The line number (within the expression) of the next token
93 */
94 private int nextLineNumber = 1;
95
96 /**
97 * List containing the positions (offsets in the input string) at which newline characters
98 * occur
99 */
100
101 private List<Integer> newlineOffsets = null;
102
103 /**
104 * The token number of the token that preceded the current token
105 */
106 private int precedingToken = Token.UNKNOWN;
107
108 /**
109 * The content of the preceding token
110 */
111
112 private String precedingTokenValue = "";
113
114 /**
115 * Flag to disallow "union" as a synonym for "|" when parsing XSLT 2.0 patterns
116 */
117
118 public boolean disallowUnionKeyword;
119
120 /**
121 * Flag to indicate that this is XQuery as distinct from XPath
122 */
123
124 public boolean isXQuery = false;
125
126 /**
127 * XPath language level: e.g. 2.0, 3.0, or 3.1
128 */
129
130 public int languageLevel = 20;
131
132 /**
133 * Flag to allow Saxon extensions
134 */
135
136 public boolean allowSaxonExtensions = false;
137
138 public Tokenizer() {
139 }
140
141 /**
142 * Get the current tokenizer state
143 *
144 * @return the current state
145 */
146
147 public int getState() {
148 return state;
149 }
150
151 /**
152 * Set the tokenizer into a special state
153 *
154 * @param state the new state
155 */
156
157 public void setState(int state) {
158 this.state = state;
159 if (state == DEFAULT_STATE) {
160 // force the followsOperator() test to return true
161 precedingToken = Token.UNKNOWN;
162 precedingTokenValue = "";
163 currentToken = Token.UNKNOWN;
164 } else if (state == OPERATOR_STATE) {
165 precedingToken = Token.RPAR;
166 precedingTokenValue = ")";
167 currentToken = Token.RPAR;
168 }
169 }
170
171 //
172 // Lexical analyser for expressions, queries, and XSLT patterns
173 //
174
175 /**
176 * Prepare a string for tokenization.
177 * The actual tokens are obtained by calls on next()
178 *
179 * @param input the string to be tokenized
180 * @param start start point within the string
181 * @param end end point within the string (last character not read):
182 * -1 means end of string
183 * @throws XPathException if a lexical error occurs, e.g. unmatched
184 * string quotes
185 */
186 public void tokenize(String input, int start, int end) throws XPathException {
187 nextToken = Token.EOF;
188 nextTokenValue = null;
189 nextTokenStartOffset = 0;
190 inputOffset = start;
191 this.input = input;
192 this.lineNumber = 0;
193 nextLineNumber = 0;
194 if (end == -1) {
195 inputLength = input.length();
196 } else {
197 inputLength = end;
198 }
199
200 // The tokenizer actually reads one token ahead. The raw lexical analysis performed by
201 // the lookAhead() method does not (in general) distinguish names used as QNames from names
202 // used for operators, axes, and functions. The next() routine further refines names into the
203 // correct category, by looking at the following token. In addition, it combines compound tokens
204 // such as "instance of" and "cast as".
205
206 lookAhead();
207 next();
208 }
209
210 //diagnostic version of next(): change real version to realnext()
211 //
212 //public void next() throws XPathException {
213 // realnext();
214 // System.err.println("Token: " + currentToken + "[" + tokens[currentToken] + "]");
215 //}
216
217 /**
218 * Get the next token from the input expression. The type of token is returned in the
219 * currentToken variable, the string value of the token in currentTokenValue.
220 *
221 * @throws XPathException if a lexical error is detected
222 */
223
224 public void next() throws XPathException {
225 precedingToken = currentToken;
226 precedingTokenValue = currentTokenValue;
227 currentToken = nextToken;
228 currentTokenValue = nextTokenValue;
229 if (currentTokenValue == null) {
230 currentTokenValue = "";
231 }
232 currentTokenStartOffset = nextTokenStartOffset;
233 lineNumber = nextLineNumber;
234
235 // disambiguate the current token based on the tokenizer state
236
237 switch (currentToken) {
238 case Token.NAME:
239 int optype = getBinaryOp(currentTokenValue);
240 if (optype != Token.UNKNOWN && !followsOperator(precedingToken)) {
241 currentToken = optype;
242 }
243 break;
244 case Token.LT:
245 if (isXQuery && followsOperator(precedingToken)) {
246 currentToken = Token.TAG;
247 }
248 break;
249 case Token.STAR:
250 if (!followsOperator(precedingToken)) {
251 currentToken = Token.MULT;
252 }
253 break;
254 }
255
256 if (currentToken == Token.TAG || currentToken == Token.RCURLY) {
257 // No lookahead after encountering "<" at the start of an XML-like tag.
258 // After an RCURLY, the parser must do an explicit lookahead() to continue
259 // tokenizing; otherwise it can continue with direct character reading
260 return;
261 }
262
263 int oldPrecedingToken = precedingToken;
264 lookAhead();
265
266 if (currentToken == Token.NAME) {
267 if (state == BARE_NAME_STATE) {
268 return;
269 }
270 if (oldPrecedingToken == Token.DOLLAR) {
271 return;
272 }
273 switch (nextToken) {
274 case Token.LPAR:
275 int op = getBinaryOp(currentTokenValue);
276 // the test on followsOperator() is to cater for an operator being used as a function name,
277 // e.g. is(): see XQTS test K-FunctionProlog-66
278 if (op == Token.UNKNOWN || followsOperator(oldPrecedingToken)) {
279 currentToken = getFunctionType(currentTokenValue);
280 lookAhead(); // swallow the "("
281 } else {
282 currentToken = op;
283 }
284 break;
285
286 case Token.LCURLY:
287 if (!(state == SEQUENCE_TYPE_STATE)) {
288 currentToken = Token.KEYWORD_CURLY;
289 lookAhead(); // swallow the "{"
290 }
291 break;
292
293 case Token.COLONCOLON:
294 lookAhead();
295 currentToken = Token.AXIS;
296 break;
297
298 case Token.HASH:
299 lookAhead();
300 currentToken = Token.NAMED_FUNCTION_REF;
301 break;
302
303 case Token.COLONSTAR:
304 lookAhead();
305 currentToken = Token.PREFIX;
306 break;
307
308 case Token.DOLLAR:
309 if (currentTokenValue.equals("for")) {
310 currentToken = Token.FOR;
311 } else if (currentTokenValue.equals("some")) {
312 currentToken = Token.SOME;
313 } else if (currentTokenValue.equals("every")) {
314 currentToken = Token.EVERY;
315 } else if (currentTokenValue.equals("let")) {
316 currentToken = Token.LET;
317 } else if (currentTokenValue.equals("count")) {
318 currentToken = Token.COUNT;
319 } else if (currentTokenValue.equals("copy")) {
320 currentToken = Token.COPY;
321 }
322 break;
323
324 case Token.PERCENT:
325 if (currentTokenValue.equals("declare")) {
326 currentToken = Token.DECLARE_ANNOTATED;
327 }
328 break;
329
330 case Token.NAME:
331 int candidate = -1;
332 if (currentTokenValue.equals("element")) {
333 candidate = Token.ELEMENT_QNAME;
334 } else if (currentTokenValue.equals("attribute")) {
335 candidate = Token.ATTRIBUTE_QNAME;
336 } else if (currentTokenValue.equals("processing-instruction")) {
337 candidate = Token.PI_QNAME;
338 } else if (currentTokenValue.equals("namespace")) {
339 candidate = Token.NAMESPACE_QNAME;
340 }
341 if (candidate != -1) {
342 // <'element' QName '{'> constructor
343 // <'attribute' QName '{'> constructor
344 // <'processing-instruction' QName '{'> constructor
345 // <'namespace' QName '{'> constructor
346
347 String qname = nextTokenValue;
348 String saveTokenValue = currentTokenValue;
349 int savePosition = inputOffset;
350 lookAhead();
351 if (nextToken == Token.LCURLY) {
352 currentToken = candidate;
353 currentTokenValue = qname;
354 lookAhead();
355 return;
356 } else {
357 // backtrack (we don't have 2-token lookahead; this is the
358 // only case where it's needed. So we backtrack instead.)
359 currentToken = Token.NAME;
360 currentTokenValue = saveTokenValue;
361 inputOffset = savePosition;
362 nextToken = Token.NAME;
363 nextTokenValue = qname;
364 }
365
366 }
367 String composite = currentTokenValue + ' ' + nextTokenValue;
368 Integer val = Token.doubleKeywords.get(composite);
369 if (val == null) {
370 break;
371 } else {
372 currentToken = val;
373 currentTokenValue = composite;
374 // some tokens are actually triples
375 if (currentToken == Token.REPLACE_VALUE) {
376 // this one's a quadruplet - "replace value of node"
377 lookAhead();
378 if (nextToken != Token.NAME || !nextTokenValue.equals("of")) {
379 throw new XPathException("After '" + composite + "', expected 'of'");
380 }
381 lookAhead();
382 if (nextToken != Token.NAME || !nextTokenValue.equals("node")) {
383 throw new XPathException("After 'replace value of', expected 'node'");
384 }
385 nextToken = currentToken; // to reestablish after-operator state
386 }
387 lookAhead();
388 return;
389 }
390 default:
391 // no action needed
392 }
393 }
394 }
395
396 /**
397 * Peek ahead at the next token
398 */
399
400 public int peekAhead() {
401 return nextToken;
402 }
403
404 /**
405 * Force the current token to be treated as an operator if possible
406 */
407
408 public void treatCurrentAsOperator() {
409 switch (currentToken) {
410 case Token.NAME:
411 int optype = getBinaryOp(currentTokenValue);
412 if (optype != Token.UNKNOWN) {
413 currentToken = optype;
414 }
415 break;
416 case Token.STAR:
417 currentToken = Token.MULT;
418 break;
419 }
420 }
421
422 /**
423 * Look ahead by one token. This method does the real tokenization work.
424 * The method is normally called internally, but the XQuery parser also
425 * calls it to resume normal tokenization after dealing with pseudo-XML
426 * syntax.
427 *
428 * @throws XPathException if a lexical error occurs
429 */
430 public void lookAhead() throws XPathException {
431 precedingToken = nextToken;
432 precedingTokenValue = nextTokenValue;
433 nextTokenValue = null;
434 nextTokenStartOffset = inputOffset;
435 for (; ; ) {
436 if (inputOffset >= inputLength) {
437 nextToken = Token.EOF;
438 return;
439 }
440 char c = input.charAt(inputOffset++);
441 switch (c) {
442 case '/':
443 if (inputOffset < inputLength
444 && input.charAt(inputOffset) == '/') {
445 inputOffset++;
446 nextToken = Token.SLASH_SLASH;
447 return;
448 }
449 nextToken = Token.SLASH;
450 return;
451 case ':':
452 if (inputOffset < inputLength) {
453 if (input.charAt(inputOffset) == ':') {
454 inputOffset++;
455 nextToken = Token.COLONCOLON;
456 return;
457 } else if (input.charAt(inputOffset) == '=') {
458 nextToken = Token.ASSIGN;
459 inputOffset++;
460 return;
461 } else { // if (input.charAt(inputOffset) == ' ') ??
462 nextToken = Token.COLON;
463 return;
464 }
465 }
466 throw new XPathException("Unexpected colon at start of token");
467 case '@':
468 nextToken = Token.AT;
469 return;
470 case '~':
471 nextToken = Token.TILDE;
472 return;
473 case '?':
474 nextToken = Token.QMARK;
475 return;
476 case '[':
477 nextToken = Token.LSQB;
478 return;
479 case ']':
480 nextToken = Token.RSQB;
481 return;
482 case '{':
483 nextToken = Token.LCURLY;
484 return;
485 case '}':
486 // if (inputOffset < inputLength && input.charAt(inputOffset) == '`') {
487 // inputOffset++;
488 // int j = inputOffset;
489 // int newlines = 0;
490 // while (true) {
491 // if (j >= inputLength) {
492 // throw new XPathException("Unclosed string template in expression");
493 // }
494 // if (input.charAt(j) == '\n') {
495 // newlines++;
496 // } else if (input.charAt(j) == '`' && j + 1 < inputLength && input.charAt(j + 1) == '{') {
497 // nextToken = Token.STRING_TEMPLATE_INTERMEDIATE;
498 // nextTokenValue = input.substring(inputOffset, j);
499 // inputOffset = j + 2;
500 // incrementLineNumber(newlines);
501 // return;
502 // } else if (input.charAt(j) == ']' && j + 2 < inputLength
503 // && input.charAt(j + 1) == '`' && input.charAt(j + 2) == '`') {
504 // nextToken = Token.STRING_TEMPLATE_FINAL;
505 // nextTokenValue = input.substring(inputOffset, j);
506 // inputOffset = j + 3;
507 // incrementLineNumber(newlines);
508 // return;
509 // }
510 // j++;
511 // }
512 // } else {
513 nextToken = Token.RCURLY;
514 return;
515 // }
516 case ';':
517 nextToken = Token.SEMICOLON;
518 state = DEFAULT_STATE;
519 return;
520 case '%':
521 nextToken = Token.PERCENT;
522 return;
523 case '(':
524 if (inputOffset < inputLength && input.charAt(inputOffset) == '#') {
525 inputOffset++;
526 int pragmaStart = inputOffset;
527 int nestingDepth = 1;
528 while (nestingDepth > 0 && inputOffset < (inputLength - 1)) {
529 if (input.charAt(inputOffset) == '\n') {
530 incrementLineNumber();
531 } else if (input.charAt(inputOffset) == '#' &&
532 input.charAt(inputOffset + 1) == ')') {
533 nestingDepth--;
534 inputOffset++;
535 } else if (input.charAt(inputOffset) == '(' &&
536 input.charAt(inputOffset + 1) == '#') {
537 nestingDepth++;
538 inputOffset++;
539 }
540 inputOffset++;
541 }
542 if (nestingDepth > 0) {
543 throw new XPathException("Unclosed XQuery pragma");
544 }
545 nextToken = Token.PRAGMA;
546 nextTokenValue = input.substring(pragmaStart, inputOffset - 2);
547 return;
548 }
549 if (inputOffset < inputLength && input.charAt(inputOffset) == ':') {
550 // XPath comment syntax is (: .... :)
551 // Comments may be nested, and may now be empty
552 inputOffset++;
553 int nestingDepth = 1;
554 while (nestingDepth > 0 && inputOffset < (inputLength - 1)) {
555 if (input.charAt(inputOffset) == '\n') {
556 incrementLineNumber();
557 } else if (input.charAt(inputOffset) == ':' &&
558 input.charAt(inputOffset + 1) == ')') {
559 nestingDepth--;
560 inputOffset++;
561 } else if (input.charAt(inputOffset) == '(' &&
562 input.charAt(inputOffset + 1) == ':') {
563 nestingDepth++;
564 inputOffset++;
565 }
566 inputOffset++;
567 }
568 if (nestingDepth > 0) {
569 throw new XPathException("Unclosed XPath comment");
570 }
571 lookAhead();
572 } else {
573 nextToken = Token.LPAR;
574 }
575 return;
576 case ')':
577 nextToken = Token.RPAR;
578 return;
579 case '+':
580 nextToken = Token.PLUS;
581 return;
582 case '-':
583 nextToken = Token.MINUS; // not detected if part of a name
584 return;
585 case '=':
586 if (inputOffset < inputLength
587 && input.charAt(inputOffset) == '>') {
588 inputOffset++;
589 nextToken = Token.ARROW;
590 return;
591 }
592 nextToken = Token.EQUALS;
593 return;
594 case '!':
595 if (inputOffset < inputLength
596 && input.charAt(inputOffset) == '=') {
597 inputOffset++;
598 nextToken = Token.NE;
599 return;
600 }
601 nextToken = Token.BANG;
602 return;
603 case '*':
604 // disambiguation of MULT and STAR is now done later
605 if (inputOffset < inputLength
606 && input.charAt(inputOffset) == ':'
607 && inputOffset + 1 < inputLength
608 && (input.charAt(inputOffset + 1) > 127 || NameChecker.isNCNameStartChar(input.charAt(inputOffset + 1)))) {
609 inputOffset++;
610 nextToken = Token.SUFFIX;
611 return;
612 }
613 nextToken = Token.STAR;
614 return;
615 case ',':
616 nextToken = Token.COMMA;
617 return;
618 case '$':
619 nextToken = Token.DOLLAR;
620 return;
621 case '|':
622 if (inputOffset < inputLength && input.charAt(inputOffset) == '|') {
623 inputOffset++;
624 nextToken = Token.CONCAT;
625 return;
626 }
627 nextToken = Token.UNION;
628 return;
629 case '#':
630 nextToken = Token.HASH;
631 return;
632 case '<':
633 if (inputOffset < inputLength
634 && input.charAt(inputOffset) == '=') {
635 inputOffset++;
636 nextToken = Token.LE;
637 return;
638 }
639 if (inputOffset < inputLength
640 && input.charAt(inputOffset) == '<') {
641 inputOffset++;
642 nextToken = Token.PRECEDES;
643 return;
644 }
645 nextToken = Token.LT;
646 return;
647 case '>':
648 if (inputOffset < inputLength
649 && input.charAt(inputOffset) == '=') {
650 inputOffset++;
651 nextToken = Token.GE;
652 return;
653 }
654 if (inputOffset < inputLength
655 && input.charAt(inputOffset) == '>') {
656 inputOffset++;
657 nextToken = Token.FOLLOWS;
658 return;
659 }
660 nextToken = Token.GT;
661 return;
662 case '.':
663 if (inputOffset < inputLength
664 && input.charAt(inputOffset) == '.') {
665 inputOffset++;
666 nextToken = Token.DOTDOT;
667 return;
668 }
669 if (inputOffset == inputLength
670 || input.charAt(inputOffset) < '0'
671 || input.charAt(inputOffset) > '9') {
672 nextToken = Token.DOT;
673 return;
674 }
675 // otherwise drop through: we have a number starting with a decimal point
676 case '0':
677 case '1':
678 case '2':
679 case '3':
680 case '4':
681 case '5':
682 case '6':
683 case '7':
684 case '8':
685 case '9':
686 // The logic here can return some tokens that are not legitimate numbers,
687 // for example "23e" or "1.0e+". However, this will only happen if the XPath
688 // expression as a whole is syntactically incorrect.
689 // These errors will be caught by the numeric constructor.
690 boolean allowE = true;
691 boolean allowSign = false;
692 boolean allowDot = true;
693 numloop:
694 while (true) {
695 switch (c) {
696 case '0':
697 case '1':
698 case '2':
699 case '3':
700 case '4':
701 case '5':
702 case '6':
703 case '7':
704 case '8':
705 case '9':
706 allowSign = false;
707 break;
708 case '.':
709 if (allowDot) {
710 allowDot = false;
711 allowSign = false;
712 } else {
713 inputOffset--;
714 break numloop;
715 }
716 break;
717 case 'E':
718 case 'e':
719 if (allowE) {
720 allowSign = true;
721 allowE = false;
722 } else {
723 inputOffset--;
724 break numloop;
725 }
726 break;
727 case '+':
728 case '-':
729 if (allowSign) {
730 allowSign = false;
731 } else {
732 inputOffset--;
733 break numloop;
734 }
735 break;
736 default:
737 if (('a' <= c && c <= 'z') || c > 127) {
738 // this prevents the famous "10div 3"
739 throw new XPathException("Separator needed after numeric literal");
740 }
741 inputOffset--;
742 break numloop;
743 }
744 if (inputOffset >= inputLength) {
745 break;
746 }
747 c = input.charAt(inputOffset++);
748 }
749 nextTokenValue = input.substring(nextTokenStartOffset, inputOffset);
750 nextToken = Token.NUMBER;
751 return;
752 case '"':
753 case '\'':
754 nextTokenValue = "";
755 while (true) {
756 inputOffset = input.indexOf(c, inputOffset);
757 if (inputOffset < 0) {
758 inputOffset = nextTokenStartOffset + 1;
759 throw new XPathException("Unmatched quote in expression");
760 }
761 nextTokenValue += input.substring(nextTokenStartOffset + 1, inputOffset++);
762 if (inputOffset < inputLength) {
763 char n = input.charAt(inputOffset);
764 if (n == c) {
765 // Doubled delimiters
766 nextTokenValue += c;
767 nextTokenStartOffset = inputOffset;
768 inputOffset++;
769
770 } else {
771 break;
772 }
773 } else {
774 break;
775 }
776 }
777
778 // maintain line number if there are newlines in the string
779 if (nextTokenValue.indexOf('\n') >= 0) {
780 for (int i = 0; i < nextTokenValue.length(); i++) {
781 if (nextTokenValue.charAt(i) == '\n') {
782 incrementLineNumber(nextTokenStartOffset + i + 1);
783 }
784 }
785 }
786 //nextTokenValue = nextTokenValue.intern();
787 nextToken = Token.STRING_LITERAL;
788 return;
789 case '`':
790 if (inputOffset < inputLength - 1
791 && input.charAt(inputOffset) == '`'
792 && input.charAt(inputOffset + 1) == '[') {
793 inputOffset += 2;
794 int j = inputOffset;
795 int newlines = 0;
796 while (true) {
797 if (j >= inputLength) {
798 throw new XPathException("Unclosed string template in expression");
799 }
800 if (input.charAt(j) == '\n') {
801 newlines++;
802 } else if (input.charAt(j) == '`' && j + 1 < inputLength && input.charAt(j + 1) == '{') {
803 nextToken = Token.STRING_TEMPLATE_INITIAL;
804 nextTokenValue = input.substring(inputOffset, j);
805 inputOffset = j + 2;
806 incrementLineNumber(newlines);
807 return;
808 } else if (input.charAt(j) == ']' && j + 2 < inputLength
809 && input.charAt(j + 1) == '`' && input.charAt(j + 2) == '`') {
810 nextToken = Token.STRING_TEMPLATE_COMPLETE;
811 nextTokenValue = input.substring(inputOffset, j);
812 inputOffset = j + 3;
813 incrementLineNumber(newlines);
814 return;
815 }
816 j++;
817 }
818 } else {
819 throw new XPathException("Invalid character '`' (backtick) in expression");
820 }
821 case '\n':
822 incrementLineNumber();
823 // drop through
824 case ' ':
825 case '\t':
826 case '\r':
827 nextTokenStartOffset = inputOffset;
828 break;
829 case '\u00B6':
830
831 case 'Q':
832 if (inputOffset < inputLength && input.charAt(inputOffset) == '{') {
833 // EQName, revised syntax as per bug 15399
834 int close = input.indexOf('}', inputOffset++);
835 if (close < inputOffset) {
836 throw new XPathException("Missing closing brace in EQName");
837 }
838 String uri = input.substring(inputOffset, close);
839 uri = Whitespace.collapseWhitespace(uri).toString(); // Bug 29708
840 if (uri.contains("{")) {
841 throw new XPathException("EQName must not contain opening brace");
842 }
843 inputOffset = close + 1;
844 int start = inputOffset;
845 boolean isStar = false;
846 while (inputOffset < inputLength) {
847 char c2 = input.charAt(inputOffset);
848 if (c2 > 0x80 || Character.isLetterOrDigit(c2) || c2 == '_' || c2 == '.' || c2 == '-') {
849 inputOffset++;
850 } else if (c2 == '*' && (start == inputOffset)) {
851 inputOffset++;
852 isStar = true;
853 break;
854 } else {
855 break;
856 }
857 }
858 String localName = input.substring(start, inputOffset);
859 nextTokenValue = "Q{" + uri + "}" + localName;
860 // Reuse Token.NAME because EQName is allowed anywhere that QName is allowed
861 nextToken = isStar ? Token.PREFIX : Token.NAME;
862 return;
863
864
865 }
866 /* else fall through */
867 default:
868 if (c < 0x80 && !Character.isLetter(c)) {
869 throw new XPathException("Invalid character '" + c + "' in expression");
870 }
871 /* fall through */
872 case '_':
873 boolean foundColon = false;
874 loop:
875 for (; inputOffset < inputLength; inputOffset++) {
876 c = input.charAt(inputOffset);
877 switch (c) {
878 case ':':
879 if (!foundColon) {
880 if (precedingToken == Token.QMARK || precedingToken == Token.SUFFIX) {
881 // only NCName allowed after "? in a lookup expression, or after *:
882 nextTokenValue = input.substring(nextTokenStartOffset, inputOffset);
883 nextToken = Token.NAME;
884 return;
885 }
886 if (inputOffset + 1 < inputLength) {
887 char nc = input.charAt(inputOffset + 1);
888 if (nc == ':') {
889 nextTokenValue = input.substring(nextTokenStartOffset, inputOffset);
890 nextToken = Token.AXIS;
891 inputOffset += 2;
892 return;
893 } else if (nc == '*') {
894 nextTokenValue = input.substring(nextTokenStartOffset, inputOffset);
895 nextToken = Token.PREFIX;
896 inputOffset += 2;
897 return;
898 } else if (!(nc == '_' || nc > 127 || Character.isLetter(nc))) {
899 // for example: "let $x:=2", "x:y:z", "x:2"
900 // end the token before the colon
901 nextTokenValue = input.substring(nextTokenStartOffset, inputOffset);
902 nextToken = Token.NAME;
903 return;
904 }
905 }
906 foundColon = true;
907 } else {
908 break loop;
909 }
910 break;
911 case '.':
912 case '-':
913 // If the name up to the "-" or "." is a valid operator, and if the preceding token
914 // is such that an operator is valid here and an NCName isn't, then quit here (bug 2715)
915 if (precedingToken > Token.LAST_OPERATOR &&
916 !(precedingToken == Token.QMARK || precedingToken == Token.SUFFIX) &&
917 getBinaryOp(input.substring(nextTokenStartOffset, inputOffset)) != Token.UNKNOWN &&
918 !(precedingToken == Token.NAME && getBinaryOp(precedingTokenValue) != Token.UNKNOWN)) {
919 nextToken = getBinaryOp(input.substring(nextTokenStartOffset, inputOffset));
920 return;
921 }
922 // else fall through
923 case '_':
924 break;
925
926 default:
927 if (c < 0x80 && !Character.isLetterOrDigit(c)) {
928 break loop;
929 }
930 break;
931 }
932 }
933 nextTokenValue = input.substring(nextTokenStartOffset, inputOffset);
934 //nextTokenValue = nextTokenValue.intern();
935 nextToken = Token.NAME;
936 return;
937 }
938 }
939 }
940
941
942 /**
943 * Identify a binary operator
944 *
945 * @param s String representation of the operator - must be interned
946 * @return the token number of the operator, or UNKNOWN if it is not a
947 * known operator
948 */
949
950 public int getBinaryOp(String s) {
951 switch (s.length()) {
952 case 2:
953 if (s.equals("or")) {
954 return Token.OR;
955 }
956 if (s.equals("is")) {
957 return Token.IS;
958 }
959 if (s.equals("to")) {
960 return Token.TO;
961 }
962 if (s.equals("in")) {
963 return Token.IN;
964 }
965 if (s.equals("eq")) {
966 return Token.FEQ;
967 }
968 if (s.equals("ne")) {
969 return Token.FNE;
970 }
971 if (s.equals("gt")) {
972 return Token.FGT;
973 }
974 if (s.equals("ge")) {
975 return Token.FGE;
976 }
977 if (s.equals("lt")) {
978 return Token.FLT;
979 }
980 if (s.equals("le")) {
981 return Token.FLE;
982 }
983 if (s.equals("as")) {
984 return Token.AS;
985 }
986 break;
987 case 3:
988 if (s.equals("and")) {
989 return Token.AND;
990 }
991 if (s.equals("div")) {
992 return Token.DIV;
993 }
994 if (s.equals("mod")) {
995 return Token.MOD;
996 }
997 break;
998 case 4:
999 if (s.equals("idiv")) {
1000 return Token.IDIV;
1001 }
1002 if (s.equals("then")) {
1003 return Token.THEN;
1004 }
1005 if (s.equals("else")) {
1006 return Token.ELSE;
1007 }
1008 if (s.equals("case")) {
1009 return Token.CASE;
1010 }
1011 if (s.equals("into")) {
1012 return Token.INTO;
1013 }
1014 if (s.equals("with")) {
1015 return Token.WITH;
1016 }
1017 break;
1018 case 5:
1019 if (s.equals("where")) {
1020 return Token.WHERE;
1021 }
1022 if (s.equals("union") && !disallowUnionKeyword) {
1023 return Token.UNION;
1024 }
1025 if (s.equals("after")) {
1026 return Token.AFTER;
1027 }
1028 break;
1029 case 6:
1030 if (s.equals("except")) {
1031 return Token.EXCEPT;
1032 }
1033 if (s.equals("return")) {
1034 return Token.RETURN;
1035 }
1036 if (s.equals("before")) {
1037 return Token.BEFORE;
1038 }
1039 if (s.equals("modify")) {
1040 return Token.MODIFY;
1041 }
1042 if (s.equals("orElse") && allowSaxonExtensions) {
1043 return Token.OR_ELSE;
1044 }
1045 break;
1046 case 7:
1047 if (s.equals("default")) {
1048 return Token.DEFAULT;
1049 }
1050 if (s.equals("andAlso") && allowSaxonExtensions) {
1051 return Token.AND_ALSO;
1052 }
1053 break;
1054 case 9:
1055 if (s.equals("intersect")) {
1056 return Token.INTERSECT;
1057 }
1058 if (s.equals("satisfies")) {
1059 return Token.SATISFIES;
1060 }
1061 break;
1062 }
1063 return Token.UNKNOWN;
1064 }
1065
1066 /**
1067 * Distinguish nodekind names, "if", and function names, which are all
1068 * followed by a "("
1069 *
1070 * @param s the name - must be interned
1071 * @return the token number
1072 */
1073
1074 private int getFunctionType(String s) {
1075 switch (s.length()) {
1076 case 2:
1077 if (s.equals("if")) {
1078 return Token.IF;
1079 }
1080 break;
1081 case 3:
1082 if (s.equals("map")) {
1083 return languageLevel == 20 ? Token.FUNCTION : Token.NODEKIND; // map() in XPath 3.0
1084 }
1085 break;
1086 case 4:
1087 if (s.equals("node")) {
1088 return Token.NODEKIND;
1089 }
1090 if (s.equals("item")) {
1091 return Token.NODEKIND;
1092 }
1093 if (s.equals("text")) {
1094 return Token.NODEKIND;
1095 }
1096 break;
1097 case 5:
1098 if (s.equals("array")) {
1099 return languageLevel == 20 ? Token.FUNCTION : Token.NODEKIND; // array() in XPath 3.1
1100 }
1101 if (s.equals("tuple")) {
1102 return allowSaxonExtensions ? Token.NODEKIND : Token.FUNCTION; // Saxon tuple(...) types
1103 }
1104 if (s.equals("union")) {
1105 return allowSaxonExtensions ? Token.NODEKIND : Token.FUNCTION; // Saxon union(...) types
1106 }
1107 break;
1108 case 6:
1109 if (s.equals("switch")) {
1110 // Reserved in XPath 3.0, even though only used in XQuery
1111 return languageLevel == 20 ? Token.FUNCTION : Token.SWITCH;
1112 }
1113 break;
1114 case 7:
1115 if (s.equals("element")) {
1116 return Token.NODEKIND;
1117 }
1118 if (s.equals("comment")) {
1119 return Token.NODEKIND;
1120 }
1121 break;
1122 case 8:
1123 if (s.equals("function")) {
1124 return languageLevel == 20 ? Token.FUNCTION : Token.NODEKIND;
1125 // Higher order functions in XPath 3.0
1126 }
1127 break;
1128 case 9:
1129 if (s.equals("attribute")) {
1130 return Token.NODEKIND;
1131 }
1132 break;
1133 case 10:
1134 if (s.equals("typeswitch")) {
1135 return Token.TYPESWITCH;
1136 }
1137 break;
1138 case 13:
1139 if (s.equals("document-node")) {
1140 return Token.NODEKIND;
1141 }
1142 break;
1143 case 14:
1144 if (s.equals("empty-sequence")) {
1145 return Token.NODEKIND;
1146 }
1147 if (s.equals("namespace-node")) {
1148 return languageLevel == 20 ? Token.FUNCTION : Token.NODEKIND;
1149 }
1150 if (s.equals("schema-element")) {
1151 return Token.NODEKIND;
1152 }
1153 break;
1154 default:
1155 if (s.equals("schema-attribute")) {
1156 return Token.NODEKIND;
1157 }
1158 if (s.equals("processing-instruction")) {
1159 return Token.NODEKIND;
1160 }
1161 break;
1162 }
1163 return Token.FUNCTION;
1164 }
1165
1166 /**
1167 * Test whether the previous token is an operator
1168 *
1169 * @param precedingToken the token to be tested
1170 * @return true if the previous token is an operator token
1171 */
1172
1173 private boolean followsOperator(int precedingToken) {
1174 return precedingToken <= Token.LAST_OPERATOR;
1175 }
1176
1177 /**
1178 * Read next character directly. Used by the XQuery parser when parsing pseudo-XML syntax
1179 *
1180 * @return the next character from the input
1181 * @throws StringIndexOutOfBoundsException
1182 * if an attempt is made to read beyond
1183 * the end of the string. This will only occur in the event of a syntax error in the
1184 * input.
1185 */
1186
1187 public char nextChar() throws StringIndexOutOfBoundsException {
1188 char c = input.charAt(inputOffset++);
1189 //c = normalizeLineEnding(c);
1190 if (c == '\n') {
1191 incrementLineNumber();
1192 lineNumber++;
1193 }
1194 return c;
1195 }
1196
1197 /**
1198 * Increment the line number, making a record of where in the input string the newline character occurred.
1199 */
1200
1201 private void incrementLineNumber() {
1202 nextLineNumber++;
1203 if (newlineOffsets == null) {
1204 newlineOffsets = new ArrayList<Integer>(20);
1205 }
1206 newlineOffsets.add(inputOffset - 1);
1207 }
1208
1209 /**
1210 * Increment the line number, making a record of where in the input string the newline character occurred.
1211 *
1212 * @param offset the place in the input string where the newline occurred
1213 */
1214
1215 public void incrementLineNumber(int offset) {
1216 nextLineNumber++;
1217 if (newlineOffsets == null) {
1218 newlineOffsets = new ArrayList<Integer>(20);
1219 }
1220 newlineOffsets.add(offset);
1221 }
1222
1223 /**
1224 * Step back one character. If this steps back to a previous line, adjust the line number.
1225 */
1226
1227 public void unreadChar() {
1228 if (input.charAt(--inputOffset) == '\n') {
1229 nextLineNumber--;
1230 lineNumber--;
1231 if (newlineOffsets != null) {
1232 newlineOffsets.remove(newlineOffsets.size() - 1);
1233 }
1234 }
1235 }
1236
1237 /**
1238 * Get the most recently read text (for use in an error message)
1239 *
1240 * @param offset the offset of the offending token, if known, or -1 to use the current offset
1241 * @return a chunk of text leading up to the error
1242 */
1243
1244 public String recentText(int offset) {
1245 if (offset == -1) {
1246 // if no offset was supplied, we want the text immediately before the current reading position
1247 if (inputOffset > inputLength) {
1248 inputOffset = inputLength;
1249 }
1250 if (inputOffset < 34) {
1251 return input.substring(0, inputOffset);
1252 } else {
1253 return Whitespace.collapseWhitespace(
1254 "..." + input.substring(inputOffset - 30, inputOffset)).toString();
1255 }
1256 } else {
1257 // if a specific offset was supplied, we want the text *starting* at that offset
1258 int end = offset + 30;
1259 if (end > inputLength) {
1260 end = inputLength;
1261 }
1262 return Whitespace.collapseWhitespace(
1263 (offset > 0 ? "..." : "") +
1264 input.substring(offset, end)).toString();
1265 }
1266 }
1267
1268 /**
1269 * Get the line number of the current token
1270 *
1271 * @return the line number. Line numbers reported by the tokenizer start at zero.
1272 */
1273
1274 public int getLineNumber() {
1275 return lineNumber;
1276 }
1277
1278 /**
1279 * Get the column number of the current token
1280 *
1281 * @return the column number. Column numbers reported by the tokenizer start at zero.
1282 */
1283
1284 public int getColumnNumber() {
1285 return (int) (getLineAndColumn(currentTokenStartOffset) & 0x7fffffff);
1286 }
1287
1288 /**
1289 * Get the line and column number corresponding to a given offset in the input expression,
1290 * as a long value with the line number in the top half and the column number in the lower half.
1291 * Line and column numbers reported by the tokenizer start at zero.
1292 *
1293 * @param offset the byte offset in the expression
1294 * @return the line and column number, packed together
1295 */
1296
1297 public long getLineAndColumn(int offset) {
1298 if (newlineOffsets == null) {
1299 return (long) offset;
1300 }
1301 for (int line = newlineOffsets.size() - 1; line >= 0; line--) {
1302 int nloffset = newlineOffsets.get(line);
1303 if (offset > nloffset) {
1304 return ((long) (line+1) << 32) | (long) (offset - nloffset);
1305 }
1306 }
1307 return (long) offset;
1308 }
1309
1310 /**
1311 * Return the line number corresponding to a given offset in the expression
1312 *
1313 * @param offset the byte offset in the expression
1314 * @return the line number. Line and column numbers reported by the tokenizer start at zero.
1315 */
1316
1317 public int getLineNumber(int offset) {
1318 return (int) (getLineAndColumn(offset) >> 32);
1319 }
1320
1321 /**
1322 * Return the column number corresponding to a given offset in the expression
1323 *
1324 * @param offset the byte offset in the expression
1325 * @return the column number. Line and column numbers reported by the tokenizer start at zero.
1326 */
1327
1328 public int getColumnNumber(int offset) {
1329 return (int) (getLineAndColumn(offset) & 0x7fffffff);
1330 }
1331
1332 }
1333
1334 /*
1335
1336 The following copyright notice is copied from the licence for xt, from which the
1337 original version of this module was derived:
1338 --------------------------------------------------------------------------------
1339 Copyright (c) 1998, 1999 James Clark
1340
1341 Permission is hereby granted, free of charge, to any person obtaining
1342 a copy of this software and associated documentation files (the
1343 "Software"), to deal in the Software without restriction, including
1344 without limitation the rights to use, copy, modify, merge, publish,
1345 distribute, sublicense, and/or sell copies of the Software, and to
1346 permit persons to whom the Software is furnished to do so, subject to
1347 the following conditions:
1348
1349 The above copyright notice and this permission notice shall be included
1350 in all copies or substantial portions of the Software.
1351
1352 THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS
1353 OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
1354 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
1355 IN NO EVENT SHALL JAMES CLARK BE LIABLE FOR ANY CLAIM, DAMAGES OR
1356 OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
1357 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
1358 OTHER DEALINGS IN THE SOFTWARE.
1359
1360 Except as contained in this notice, the name of James Clark shall
1361 not be used in advertising or otherwise to promote the sale, use or
1362 other dealings in this Software without prior written authorization
1363 from James Clark.
1364 ---------------------------------------------------------------------------
1365 */