Debian Codegraph @

net/sf/saxon/expr/parser/XPathParser.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.Configuration;
11 import net.sf.saxon.Version;
12 import net.sf.saxon.expr.*;
13 import net.sf.saxon.expr.flwor.Clause;
14 import net.sf.saxon.expr.instruct.Block;
15 import net.sf.saxon.expr.instruct.Choose;
16 import net.sf.saxon.expr.instruct.ForEach;
17 import net.sf.saxon.functions.*;
18 import net.sf.saxon.functions.registry.VendorFunctionSetHE;
19 import net.sf.saxon.lib.Feature;
20 import net.sf.saxon.lib.NamespaceConstant;
21 import net.sf.saxon.ma.arrays.ArrayFunctionSet;
22 import net.sf.saxon.ma.arrays.ArrayItemType;
23 import net.sf.saxon.ma.arrays.SimpleArrayItem;
24 import net.sf.saxon.ma.arrays.SquareArrayConstructor;
25 import net.sf.saxon.ma.map.*;
26 import net.sf.saxon.om.*;
27 import net.sf.saxon.pattern.*;
28 import net.sf.saxon.query.AnnotationList;
29 import net.sf.saxon.trace.LocationKind;
30 import net.sf.saxon.trans.Err;
31 import net.sf.saxon.trans.LicenseException;
32 import net.sf.saxon.trans.SymbolicName;
33 import net.sf.saxon.trans.XPathException;
34 import net.sf.saxon.type.*;
35 import net.sf.saxon.value.*;
36 import net.sf.saxon.z.IntArraySet;
37 import net.sf.saxon.z.IntSet;
38
39 import java.util.ArrayList;
40 import java.util.Arrays;
41 import java.util.List;
42 import java.util.Stack;
43 import java.util.function.IntPredicate;
44
45 import static net.sf.saxon.type.BuiltInAtomicType.*;
46
47 /**
48 * Parser for XPath expressions and XSLT patterns.
49 * <p>This code was originally inspired by James Clark's xt but has been totally rewritten (several times)</p>
50 * <p>The base class handles parsing of XPath 2.0, XPath 3.0 and XPath 3.1 syntax (switched by a languageVersion variable).
51 * Subclasses refine this to handle XQuery syntax (1.0, 3.0 and 3.1) and XQuery Update syntax.</p>
52 *
53 * @author Michael Kay
54 */
55
56
57 public class XPathParser {
58
59 protected Tokenizer t;
60 protected StaticContext env;
61 protected Stack<LocalBinding> rangeVariables = new Stack<>();
62 // The stack holds a list of range variables that are in scope.
63 // Each entry on the stack is a Binding object containing details
64 // of the variable.
65
66 protected QNameParser qNameParser;
67 protected ParserExtension parserExtension = new ParserExtension();
68
69 protected IntPredicate charChecker;
70
71 protected boolean allowXPath30Syntax = false;
72 protected boolean allowXPath30XSLTExtensions = false;
73 protected boolean allowXPath31Syntax = false;
74 protected boolean allowSaxonExtensions = false;
75
76 protected boolean scanOnly = false;
77 // scanOnly is set to true while attributes in direct element constructors
78 // are being processed. We need to parse enclosed expressions in the attribute
79 // in order to find the end of the attribute value, but we don't yet know the
80 // full namespace context at this stage.
81
82 private boolean allowAbsentExpression = false;
83 // allowAbsentExpression is a flag that indicates that it is acceptable
84 // for the expression to be empty (that is, to consist solely of whitespace and
85 // comments). The result of parsing such an expression is equivalent to the
86 // result of parsing an empty sequence literal, "()"
87
88 /*@Nullable*/
89 protected CodeInjector codeInjector = null;
90 private Accelerator accelerator = null;
91
92 protected int language = XPATH; // know which language we are parsing, for diagnostics
93 public static final int XPATH = 0;
94 public static final int XSLT_PATTERN = 1;
95 public static final int SEQUENCE_TYPE = 2;
96 public static final int XQUERY = 3;
97 public static final int EXTENDED_ITEM_TYPE = 4;
98
99 protected int languageVersion = 20;
100 protected int catchDepth = 0;
101
102 public interface Accelerator {
103
104 /**
105 * Attempt fast parsing of an expression, provided it is sufficiently simple.
106 *
107 * @param t the tokenizer
108 * @param env the static context
109 * @param expression the string containing expression to be parsed
110 * @param start start position within the input string
111 * @param terminator either EOF or RCURLY, indicating how parsing should end
112 * @return either the parsed expression, or null if it is erroneous or too
113 * complex to parse.
114 */
115
116 Expression parse(Tokenizer t, StaticContext env, String expression, int start, int terminator);
117 }
118
119 /**
120 * Create an expression parser
121 */
122
123 public XPathParser() {
124 }
125
126 /**
127 * Set a CodeInjector which can be used to modify or wrap expressions on the tree
128 * as the expression is parsed and the tree is constructed. This is typically used
129 * to add tracing code.
130 *
131 * @param injector the code injector to be used
132 */
133
134 public void setCodeInjector(/*@Nullable*/ CodeInjector injector) {
135 this.codeInjector = injector;
136 }
137
138 /**
139 * Set a CodeInjector which can be used to modify or wrap expressions on the tree
140 * as the expression is parsed and the tree is constructed. This is typically used
141 * to add tracing code.
142 *
143 * @return the code injector in use, if any; or null otherwise
144 */
145
146 /*@Nullable*/
147 public CodeInjector getCodeInjector() {
148 return codeInjector;
149 }
150
151 /**
152 * Set an accelerator which can be used for fast parsing of special cases
153 * @param accelerator a parsing accelerator
154 */
155
156 public void setAccelerator(Accelerator accelerator) {
157 this.accelerator = accelerator;
158 }
159
160 /**
161 * Get the tokenizer (the lexical analyzer)
162 *
163 * @return the tokenizer (the lexical analyzer)
164 */
165
166 public Tokenizer getTokenizer() {
167 return t;
168 }
169
170 /**
171 * Get the static context used by this expression parser
172 *
173 * @return the static context
174 */
175
176 public StaticContext getStaticContext() {
177 return env;
178 }
179
180 // /**
181 // * Set the default container for newly constructed expressions
182 // *
183 // * @param container the default container
184 // */
185 //
186 // public void setDefaultContainer(Container container) {
187 // this.defaultContainer = container;
188 // }
189 //
190 // /**
191 // * Get the default container for newly constructed expressions
192 // *
193 // * @return the default container
194 // */
195 //
196 // public Container getDefaultContainer() {
197 // return defaultContainer;
198 // }
199
200 /**
201 * Set a parser extension which can handle extensions to the XPath syntax, e.g. for
202 * XQuery update extensions
203 * @param extension a parser extension
204 */
205
206 public void setParserExtension(ParserExtension extension) {
207 this.parserExtension = extension;
208 }
209
210 /**
211 * Set the depth of nesting within try/catch
212 *
213 * @param depth the depth of nesting
214 */
215
216 public void setCatchDepth(int depth) {
217 catchDepth = depth;
218 }
219
220 /**
221 * Read the next token, catching any exception thrown by the tokenizer
222 *
223 * @throws XPathException if an invalid token is found
224 */
225
226 public void nextToken() throws XPathException {
227 try {
228 t.next();
229 } catch (XPathException e) {
230 grumble(e.getMessage());
231 }
232 }
233
234 /**
235 * Expect a given token; fail if the current token is different. Note that this method
236 * does not read any tokens.
237 *
238 * @param token the expected token
239 * @throws XPathException if the current token is not the expected
240 * token
241 */
242
243 public void expect(int token) throws XPathException {
244 if (t.currentToken != token) {
245 grumble("expected \"" + Token.tokens[token] +
246 "\", found " + currentTokenDisplay());
247 }
248 }
249
250 /**
251 * Report a syntax error (a static error with error code XPST0003)
252 *
253 * @param message the error message
254 * @throws XPathException always thrown: an exception containing the
255 * supplied message
256 */
257
258 public void grumble(String message) throws XPathException {
259 grumble(message, language == XSLT_PATTERN ? "XTSE0340" : "XPST0003");
260 }
261
262 /**
263 * Report a static error
264 *
265 * @param message the error message
266 * @param errorCode the error code
267 * @throws XPathException always thrown: an exception containing the
268 * supplied message
269 */
270
271 public void grumble(String message, String errorCode) throws XPathException {
272 grumble(message, new StructuredQName("", NamespaceConstant.ERR, errorCode), -1);
273 }
274
275 /**
276 * Report a static error, with location information
277 *
278 * @param message the error message
279 * @param errorCode the error code
280 * @param offset the coded location of the error, or -1 if the location of the current token should be used
281 * @throws XPathException always thrown: an exception containing the
282 * supplied message
283 */
284
285 public void grumble(String message, String errorCode, int offset) throws XPathException {
286 grumble(message, new StructuredQName("", NamespaceConstant.ERR, errorCode), offset);
287 }
288
289 /**
290 * Report a static error
291 *
292 * @param message the error message
293 * @param errorCode the error code
294 * @param offset the coded location of the error, or -1 if the location of the current token should be used
295 * @throws XPathException always thrown: an exception containing the
296 * supplied message
297 */
298
299 protected void grumble(String message, StructuredQName errorCode, int offset) throws XPathException {
300 if (errorCode == null) {
301 errorCode = new StructuredQName("err", NamespaceConstant.ERR, "XPST0003");
302 }
303 String nearbyText = t.recentText(-1);
304 int line;
305 int column;
306 if (offset == -1) {
307 line = t.getLineNumber();
308 column = t.getColumnNumber();
309 } else {
310 line = t.getLineNumber(offset);
311 column = t.getColumnNumber(offset);
312 }
313 Location loc = makeNestedLocation(env.getContainingLocation(), line, column, nearbyText);
314
315 XPathException err = new XPathException(message);
316 err.setLocation(loc);
317 err.setIsSyntaxError("XPST0003".equals(errorCode.getLocalPart()));
318 err.setIsStaticError(true);
319 err.setHostLanguage(getLanguage());
320 // err.setAdditionalLocationText(prefix);
321 err.setErrorCodeQName(errorCode);
322 throw err;
323 }
324
325
326 /**
327 * Output a warning message
328 *
329 * @param message the text of the message
330 */
331
332 protected void warning(String message) {
333 if (!env.getConfiguration().getBooleanProperty(Feature.SUPPRESS_XPATH_WARNINGS)) {
334 String s = t.recentText(-1);
335 String prefix =
336 (message.startsWith("...") ? "near" : "in") +
337 ' ' + Err.wrap(s) + ":\n ";
338 env.issueWarning(prefix + message, makeLocation());
339 }
340 }
341
342 /**
343 * Set the current language (XPath or XQuery, XSLT Pattern, or SequenceType)
344 *
345 * @param language one of the constants {@link #XPATH}, {@link #XQUERY}, {@link #XSLT_PATTERN}, {@link #SEQUENCE_TYPE}
346 * @param version The XPath or XQuery language version. For XQuery the value must be
347 * 10 (for "1.0"), 30 (for "3.0") or 31 (for "3.1"); for XPath it must be 20 (="2.0"),
348 * 30 (="3.0") or 31 (="3.1"). The value 305 is also recognized to mean XPath 3.0 plus
349 * the extensions defined in XSLT 3.0
350 */
351
352 public void setLanguage(int language, int version) {
353 if (version == 0) {
354 version = 30; // default
355 }
356 if (version == 305) {
357 version = 30;
358 allowXPath30XSLTExtensions = true;
359 }
360 switch (language) {
361 case XPATH:
362 if (!(version == 20 || version == 30 || version == 31)) {
363 throw new IllegalArgumentException("Unsupported language version " + version);
364 }
365 break;
366 case XSLT_PATTERN:
367 case SEQUENCE_TYPE:
368 if (!(version == 20 || version == 30 || version == 31)) {
369 throw new IllegalArgumentException("Unsupported language version " + version);
370 }
371 break;
372 case XQUERY:
373 if (!(version == 10 || version == 30 || version == 31)) {
374 throw new IllegalArgumentException("Unsupported language version " + version);
375 }
376 break;
377 default:
378 throw new IllegalArgumentException("Unknown language " + language);
379 }
380 this.language = language;
381 this.languageVersion = version;
382 this.allowXPath30Syntax = languageVersion >= 30;
383 this.allowXPath31Syntax = languageVersion >= 31;
384
385 }
386
387 /**
388 * Get the current language (XPath or XQuery)
389 *
390 * @return a string representation of the language being parsed, for use in error messages
391 */
392
393 protected String getLanguage() {
394 switch (language) {
395 case XPATH:
396 return "XPath";
397 case XSLT_PATTERN:
398 return "XSLT Pattern";
399 case SEQUENCE_TYPE:
400 return "SequenceType";
401 case XQUERY:
402 return "XQuery";
403 case EXTENDED_ITEM_TYPE:
404 return "Extended ItemType";
405 default:
406 return "XPath";
407 }
408 }
409
410 /**
411 * Ask if XPath 3.1 is in use
412 *
413 * @return true if XPath 3.1 syntax (and therefore XQuery 3.1 syntax) is permitted
414 */
415
416 public boolean isAllowXPath31Syntax() {
417 return allowXPath31Syntax;
418 }
419
420 /**
421 * Set the QNameParser to be used while parsing
422 *
423 * @param qp the QNameParser
424 */
425
426 public void setQNameParser(QNameParser qp) {
427 this.qNameParser = qp;
428 }
429
430 /**
431 * Get the QNameParser to be used while parsing
432 *
433 * @return the QNameParser
434 */
435
436 public QNameParser getQNameParser() {
437 return qNameParser;
438 }
439
440 /**
441 * Display the current token in an error message
442 *
443 * @return the display representation of the token
444 */
445 /*@NotNull*/
446 protected String currentTokenDisplay() {
447 if (t.currentToken == Token.NAME) {
448 return "name \"" + t.currentTokenValue + '\"';
449 } else if (t.currentToken == Token.UNKNOWN) {
450 return "(unknown token)";
451 } else {
452 return '\"' + Token.tokens[t.currentToken] + '\"';
453 }
454 }
455
456 /**
457 * Parse a string representing an expression. This will accept an XPath expression if called on an
458 * ExpressionParser, or an XQuery expression if called on a QueryParser.
459 *
460 * @param expression the expression expressed as a String
461 * @param start offset within the string where parsing is to start
462 * @param terminator character to treat as terminating the expression
463 * @param env the static context for the expression
464 * @return an Expression object representing the result of parsing
465 * @throws XPathException if the expression contains a syntax error
466 */
467
468 /*@NotNull*/
469 public Expression parse(String expression, int start, int terminator, StaticContext env)
470 throws XPathException {
471 // System.err.println("Parse expression: " + expression);
472 this.env = env;
473 int languageVersion = env.getXPathVersion();
474 if (languageVersion == 20 && language == XQUERY) {
475 languageVersion = 10;
476 }
477 setLanguage(language, languageVersion);
478
479 Expression exp = null;
480 int offset = start;
481 if (accelerator != null) {
482 if (expression.length() - start < 30 || terminator == Token.RCURLY) {
483 // We need the tokenizer to be visible so that the caller can ask
484 // about where the expression ended within the input string
485 t = new Tokenizer();
486 t.languageLevel = env.getXPathVersion();
487 exp = accelerator.parse(t, env, expression, start, terminator);
488 }
489 }
490
491 if (exp == null) {
492
493 qNameParser = new QNameParser(env.getNamespaceResolver());
494 qNameParser.setAcceptEQName(allowXPath30Syntax);
495 qNameParser.setDefaultNamespace("");
496 qNameParser.setErrorOnBadSyntax(language == XSLT_PATTERN ? "XTSE0340" : "XPST0003");
497 qNameParser.setErrorOnUnresolvedPrefix("XPST0081");
498
499 charChecker = env.getConfiguration().getValidCharacterChecker();
500 t = new Tokenizer();
501 t.languageLevel = env.getXPathVersion();
502 allowSaxonExtensions =
503 t.allowSaxonExtensions =
504 env.getConfiguration().getBooleanProperty(Feature.ALLOW_SYNTAX_EXTENSIONS);
505 offset = t.currentTokenStartOffset;
506 customizeTokenizer(t);
507 try {
508 t.tokenize(expression, start, -1);
509 } catch (XPathException err) {
510 grumble(err.getMessage());
511 }
512 if (t.currentToken == terminator) {
513 if (allowAbsentExpression) {
514 Expression result = Literal.makeEmptySequence();
515 result.setRetainedStaticContext(env.makeRetainedStaticContext());
516 setLocation(result);
517 return result;
518 } else {
519 grumble("The expression is empty");
520 }
521 }
522 exp = parseExpression();
523 if (t.currentToken != terminator) {
524 if (t.currentToken == Token.EOF && terminator == Token.RCURLY) {
525 grumble("Missing curly brace after expression in value template", "XTSE0350");
526 } else {
527 grumble("Unexpected token " + currentTokenDisplay() + " beyond end of expression");
528 }
529 }
530 setLocation(exp, offset);
531 }
532 exp.setRetainedStaticContextThoroughly(env.makeRetainedStaticContext());
533 //exp.verifyParentPointers();
534 return exp;
535 }
536
537 /**
538 * Callback to tailor the tokenizer
539 *
540 * @param t the Tokenizer to be customized
541 */
542
543 protected void customizeTokenizer(Tokenizer t) {
544 // do nothing
545 }
546
547
548 /**
549 * Parse a string representing a sequence type
550 *
551 * @param input the string, which should conform to the XPath SequenceType
552 * production
553 * @param env the static context
554 * @return a SequenceType object representing the type
555 * @throws XPathException if any error is encountered
556 */
557
558 public SequenceType parseSequenceType(String input, /*@NotNull*/ StaticContext env) throws XPathException {
559 this.env = env;
560 if (qNameParser == null) {
561 qNameParser = new QNameParser(env.getNamespaceResolver());
562 if (languageVersion >= 30) {
563 qNameParser.setAcceptEQName(true);
564 }
565 }
566 language = SEQUENCE_TYPE;
567 t = new Tokenizer();
568 t.languageLevel = env.getXPathVersion();
569 allowSaxonExtensions =
570 t.allowSaxonExtensions =
571 env.getConfiguration().getBooleanProperty(Feature.ALLOW_SYNTAX_EXTENSIONS);
572 try {
573 t.tokenize(input, 0, -1);
574 } catch (XPathException err) {
575 grumble(err.getMessage());
576 }
577 SequenceType req = parseSequenceType();
578 if (t.currentToken != Token.EOF) {
579 grumble("Unexpected token " + currentTokenDisplay() + " beyond end of SequenceType");
580 }
581 return req;
582 }
583
584 /**
585 * Parse a string representing an extended item type: specifically, the content of itemType
586 * or nodeTest attributes in an exported package. As well as regular itemType syntax, these
587 * allow combined node tests separated with "|", "except", or "intersect" operators. Expressions
588 * using these operators will always be parenthesized.
589 *
590 * @param input the string, which should conform to the XPath SequenceType
591 * production
592 * @param env the static context
593 * @return a SequenceType object representing the type
594 * @throws XPathException if any error is encountered
595 */
596
597 public ItemType parseExtendedItemType(String input, StaticContext env) throws XPathException {
598 this.env = env;
599 language = EXTENDED_ITEM_TYPE;
600 t = new Tokenizer();
601 t.languageLevel = env.getXPathVersion();
602 allowSaxonExtensions = t.allowSaxonExtensions = true;
603 try {
604 t.tokenize(input, 0, -1);
605 } catch (XPathException err) {
606 grumble(err.getMessage());
607 }
608 ItemType req = parseItemType();
609 if (t.currentToken != Token.EOF) {
610 grumble("Unexpected token " + currentTokenDisplay() + " beyond end of ItemType");
611 }
612 return req;
613 }
614
615 /**
616 * Parse a string representing a sequence type with syntax extensions used in exported stylesheets.
617 * Also allows the extensions permitted in saxon:as, e.g. tuple types, type aliases
618 *
619 * @param input the string, which should conform to the XPath SequenceType
620 * production
621 * @param env the static context
622 * @return a SequenceType object representing the type
623 * @throws XPathException if any error is encountered
624 */
625
626 public SequenceType parseExtendedSequenceType(String input, /*@NotNull*/ StaticContext env) throws XPathException {
627 this.env = env;
628 language = EXTENDED_ITEM_TYPE;
629 t = new Tokenizer();
630 t.languageLevel = env.getXPathVersion();
631 allowSaxonExtensions = t.allowSaxonExtensions = true;
632 try {
633 t.tokenize(input, 0, -1);
634 } catch (XPathException err) {
635 grumble(err.getMessage());
636 }
637 SequenceType req = parseSequenceType();
638 if (t.currentToken != Token.EOF) {
639 grumble("Unexpected token " + currentTokenDisplay() + " beyond end of SequenceType");
640 }
641 return req;
642 }
643
644
645 //////////////////////////////////////////////////////////////////////////////////
646 // EXPRESSIONS //
647 //////////////////////////////////////////////////////////////////////////////////
648
649 /**
650 * Parse a top-level Expression:
651 * ExprSingle ( ',' ExprSingle )*
652 *
653 * @return the Expression object that results from parsing
654 * @throws XPathException if the expression contains a syntax error
655 */
656
657 /*@NotNull*/
658 public Expression parseExpression() throws XPathException {
659 int offset = t.currentTokenStartOffset;
660 Expression exp = parseExprSingle();
661 ArrayList<Expression> list = null;
662 while (t.currentToken == Token.COMMA) {
663 // An expression containing a comma often contains many, so we accumulate all the
664 // subexpressions into a list before creating the Block expression which reduces it to an array
665 if (list == null) {
666 list = new ArrayList<>(10);
667 list.add(exp);
668 }
669 nextToken();
670 Expression next = parseExprSingle();
671 setLocation(next);
672 list.add(next);
673 }
674 if (list != null) {
675 exp = Block.makeBlock(list);
676 setLocation(exp, offset);
677 }
678 return exp;
679 }
680
681 /**
682 * Parse an ExprSingle
683 *
684 * @return the resulting subexpression
685 * @throws XPathException if any error is encountered
686 */
687
688 /*@NotNull*/
689 public Expression parseExprSingle() throws XPathException {
690 Expression e = parserExtension.parseExtendedExprSingle(this);
691 if (e != null) {
692 return e;
693 }
694 // Short-circuit for a single-token expression
695 int peek = t.peekAhead();
696 if (peek == Token.EOF || peek == Token.COMMA || peek == Token.RPAR || peek == Token.RSQB) {
697 switch (t.currentToken) {
698 case Token.STRING_LITERAL:
699 return parseStringLiteral(true);
700 case Token.NUMBER:
701 return parseNumericLiteral(true);
702 case Token.NAME:
703 case Token.PREFIX:
704 case Token.SUFFIX:
705 case Token.STAR:
706 return parseBasicStep(true);
707 case Token.DOT:
708 nextToken();
709 Expression cie = new ContextItemExpression();
710 setLocation(cie);
711 return cie;
712 case Token.DOTDOT:
713 nextToken();
714 Expression pne = new AxisExpression(AxisInfo.PARENT, null);
715 setLocation(pne);
716 return pne;
717 case Token.EOF:
718 // fall through
719 default:
720 }
721 }
722 switch (t.currentToken) {
723 case Token.EOF:
724 grumble("Expected an expression, but reached the end of the input");
725 case Token.FOR:
726 case Token.LET:
727 case Token.FOR_SLIDING:
728 case Token.FOR_TUMBLING:
729 return parseFLWORExpression();
730 case Token.SOME:
731 case Token.EVERY:
732 return parseQuantifiedExpression();
733 case Token.IF:
734 return parseIfExpression();
735 case Token.SWITCH:
736 return parseSwitchExpression();
737 case Token.TYPESWITCH:
738 return parseTypeswitchExpression();
739 case Token.VALIDATE:
740 case Token.VALIDATE_STRICT:
741 case Token.VALIDATE_LAX:
742 case Token.VALIDATE_TYPE:
743 return parseValidateExpression();
744 case Token.PRAGMA:
745 return parseExtensionExpression(); // XQuery only
746 case Token.KEYWORD_CURLY:
747 if (t.currentTokenValue.equals("try")) {
748 return parseTryCatchExpression();
749 }
750 // else drop through
751
752 default:
753 return parseBinaryExpression(parseUnaryExpression(), 4);
754 }
755 }
756
757 /**
758 * Parse a binary expression, using operator precedence parsing. This is used
759 * to parse the part of the grammar consisting largely of binary operators
760 * distinguished by precedence: from "or expressions" down to "unary expressions".
761 * Algorithm for the mainstream binary operators is from Wikipedia article
762 * on precedence parsing; operator precedences are from the XQuery specification
763 * appendix B.
764 *
765 * @param lhs Left-hand side "basic expression"
766 * @param minPrecedence the minimum precedence of an operator that is to be treated as not terminating the
767 * current expression
768 * @return the parsed expression
769 * @throws XPathException if a static error is found
770 */
771
772 /*@NotNull*/
773 public Expression parseBinaryExpression(Expression lhs, int minPrecedence) throws XPathException {
774 while (getCurrentOperatorPrecedence() >= minPrecedence) {
775 int offset = t.currentTokenStartOffset;
776 int operator = t.currentToken;
777 int prec = getCurrentOperatorPrecedence();
778 switch (operator) {
779 case Token.INSTANCE_OF:
780 case Token.TREAT_AS:
781 nextToken();
782 SequenceType seq = parseSequenceType();
783 lhs = makeSequenceTypeExpression(lhs, operator, seq);
784 setLocation(lhs, offset);
785 if (getCurrentOperatorPrecedence() >= prec) {
786 grumble("Left operand of '" + Token.tokens[t.currentToken] + "' needs parentheses");
787 }
788 break;
789 case Token.CAST_AS:
790 case Token.CASTABLE_AS:
791 nextToken();
792 SimpleType at;
793 if (allowSaxonExtensions && t.currentToken == Token.NODEKIND && t.currentTokenValue.equals("union")) {
794 // Saxon 9.8 extension
795 at = (SimpleType)parseItemType();
796 } else {
797 expect(Token.NAME);
798 at = getSimpleType(t.currentTokenValue);
799 if (at == ANY_ATOMIC) {
800 grumble("No value is castable to xs:anyAtomicType", "XPST0080");
801 }
802 if (at == NOTATION) {
803 grumble("No value is castable to xs:NOTATION", "XPST0080");
804 }
805 nextToken();
806 }
807
808 boolean allowEmpty = t.currentToken == Token.QMARK;
809 if (allowEmpty) {
810 nextToken();
811 }
812 lhs = makeSingleTypeExpression(lhs, operator, at, allowEmpty);
813 setLocation(lhs, offset);
814 if (getCurrentOperatorPrecedence() >= prec) {
815 grumble("Left operand of '" + Token.tokens[t.currentToken] + "' needs parentheses");
816 }
817 break;
818 case Token.ARROW:
819 lhs = parseArrowPostfix(lhs);
820 break;
821 default:
822 nextToken();
823 Expression rhs = parseUnaryExpression();
824 while (getCurrentOperatorPrecedence() > prec) {
825 rhs = parseBinaryExpression(rhs, getCurrentOperatorPrecedence());
826 }
827 if (getCurrentOperatorPrecedence() == prec && !allowMultipleOperators()) {
828 String tok = Token.tokens[t.currentToken];
829 String message = "Left operand of '" + Token.tokens[t.currentToken] + "' needs parentheses";
830 if (tok.equals("<") || tok.equals(">")) {
831 // Example input: return <a>3</a><b>4</b> - bug 2659
832 message += ". Or perhaps an XQuery element constructor appears where it is not allowed";
833 }
834 grumble(message);
835 }
836 lhs = makeBinaryExpression(lhs, operator, rhs);
837 setLocation(lhs, offset);
838 }
839 }
840 return lhs;
841 }
842
843 private boolean allowMultipleOperators() {
844 switch (t.currentToken) {
845 case Token.FEQ:
846 case Token.FNE:
847 case Token.FLE:
848 case Token.FLT:
849 case Token.FGE:
850 case Token.FGT:
851 case Token.EQUALS:
852 case Token.NE:
853 case Token.LE:
854 case Token.LT:
855 case Token.GE:
856 case Token.GT:
857 case Token.IS:
858 case Token.PRECEDES:
859 case Token.FOLLOWS:
860 case Token.TO:
861 return false;
862 default:
863 return true;
864 }
865 }
866
867 private int getCurrentOperatorPrecedence() {
868 return operatorPrecedence(t.currentToken);
869 }
870
871 /**
872 * Get the precedence associated with a given operator
873 * @param operator the operator in question
874 * @return a higher number for higher precedence (closer binding)
875 */
876
877 public static int operatorPrecedence(int operator) {
878 switch (operator) {
879 case Token.OR:
880 case Token.OR_ELSE:
881 return 4;
882 case Token.AND:
883 case Token.AND_ALSO:
884 return 5;
885 case Token.FEQ:
886 case Token.FNE:
887 case Token.FLE:
888 case Token.FLT:
889 case Token.FGE:
890 case Token.FGT:
891 case Token.EQUALS:
892 case Token.NE:
893 case Token.LE:
894 case Token.LT:
895 case Token.GE:
896 case Token.GT:
897 case Token.IS:
898 case Token.PRECEDES:
899 case Token.FOLLOWS:
900 return 6;
901 case Token.CONCAT:
902 return 7;
903 case Token.TO:
904 return 8;
905 case Token.PLUS:
906 case Token.MINUS:
907 return 9;
908 case Token.MULT:
909 case Token.DIV:
910 case Token.IDIV:
911 case Token.MOD:
912 return 10;
913 case Token.UNION:
914 return 11;
915 case Token.INTERSECT:
916 case Token.EXCEPT:
917 return 12;
918 case Token.INSTANCE_OF:
919 return 13;
920 case Token.TREAT_AS:
921 return 14;
922 case Token.CASTABLE_AS:
923 return 15;
924 case Token.CAST_AS:
925 return 16;
926 case Token.ARROW:
927 return 17;
928 // remainder commented out because not used in precedence parsing (but perhaps they could be)
929 // case Token.BANG:
930 // return 20;
931 // case Token.SLASH:
932 // return 21;
933 // case Token.SLASH_SLASH:
934 // return 22;
935 // case Token.QMARK:
936 // return 23;
937 default:
938 return -1;
939 }
940 }
941
942 /*@NotNull*/
943 private Expression makeBinaryExpression(Expression lhs, int operator, Expression rhs) throws XPathException {
944 switch (operator) {
945 case Token.OR:
946 return new OrExpression(lhs, rhs);
947 case Token.AND:
948 return new AndExpression(lhs, rhs);
949 case Token.FEQ:
950 case Token.FNE:
951 case Token.FLE:
952 case Token.FLT:
953 case Token.FGE:
954 case Token.FGT:
955 return new ValueComparison(lhs, operator, rhs);
956 case Token.EQUALS:
957 case Token.NE:
958 case Token.LE:
959 case Token.LT:
960 case Token.GE:
961 case Token.GT:
962 return env.getConfiguration().getTypeChecker(env.isInBackwardsCompatibleMode()).makeGeneralComparison(lhs, operator, rhs);
963 case Token.IS:
964 case Token.PRECEDES:
965 case Token.FOLLOWS:
966 return new IdentityComparison(lhs, operator, rhs);
967 case Token.TO:
968 return new RangeExpression(lhs, rhs);
969 case Token.CONCAT: {
970 if (!allowXPath30Syntax) {
971 grumble("Concatenation operator ('||') requires XPath 3.0 to be enabled");
972 }
973 RetainedStaticContext rsc = new RetainedStaticContext(env);
974 if (lhs.isCallOn(Concat.class)) {
975 Expression[] args = ((SystemFunctionCall) lhs).getArguments();
976 Expression[] newArgs = new Expression[args.length + 1];
977 System.arraycopy(args, 0, newArgs, 0, args.length);
978 newArgs[args.length] = rhs;
979 return SystemFunction.makeCall("concat", rsc, newArgs);
980 } else {
981 return SystemFunction.makeCall("concat", rsc, lhs, rhs);
982 }
983 }
984 case Token.PLUS:
985 case Token.MINUS:
986 case Token.MULT:
987 case Token.DIV:
988 case Token.IDIV:
989 case Token.MOD:
990 return env.getConfiguration().getTypeChecker(env.isInBackwardsCompatibleMode()).makeArithmeticExpression(lhs, operator, rhs);
991 case Token.UNION:
992 case Token.INTERSECT:
993 case Token.EXCEPT:
994 return new VennExpression(lhs, operator, rhs);
995 case Token.OR_ELSE: {
996 RetainedStaticContext rsc = new RetainedStaticContext(env);
997 rhs = SystemFunction.makeCall("boolean", rsc, rhs);
998 return Choose.makeConditional(lhs, Literal.makeLiteral(BooleanValue.TRUE), rhs);
999 }
1000 case Token.AND_ALSO: {
1001 RetainedStaticContext rsc = new RetainedStaticContext(env);
1002 rhs = SystemFunction.makeCall("boolean", rsc, rhs);
1003 return Choose.makeConditional(lhs, rhs, Literal.makeLiteral(BooleanValue.FALSE));
1004 }
1005 default:
1006 throw new IllegalArgumentException(Token.tokens[operator]);
1007 }
1008 }
1009
1010 private Expression makeSequenceTypeExpression(Expression lhs, int operator, /*@NotNull*/ SequenceType type) {
1011 switch (operator) {
1012 case Token.INSTANCE_OF:
1013 return new InstanceOfExpression(lhs, type);
1014 case Token.TREAT_AS:
1015 return TreatExpression.make(lhs, type);
1016 default:
1017 throw new IllegalArgumentException();
1018 }
1019
1020 }
1021
1022 private Expression makeSingleTypeExpression(Expression lhs, int operator, /*@NotNull*/ SimpleType type, boolean allowEmpty)
1023 throws XPathException {
1024 if (type instanceof AtomicType && !(type == ErrorType.getInstance())) {
1025 switch (operator) {
1026 case Token.CASTABLE_AS:
1027 CastableExpression castable = new CastableExpression(lhs, (AtomicType) type, allowEmpty);
1028 if (lhs instanceof StringLiteral) {
1029 castable.setOperandIsStringLiteral(true);
1030 }
1031 return castable;
1032
1033 case Token.CAST_AS:
1034 CastExpression cast = new CastExpression(lhs, (AtomicType) type, allowEmpty);
1035 if (lhs instanceof StringLiteral) {
1036 cast.setOperandIsStringLiteral(true);
1037 }
1038 return cast;
1039
1040 default:
1041 throw new IllegalArgumentException();
1042 }
1043 } else if (allowXPath30Syntax) {
1044 switch (operator) {
1045 case Token.CASTABLE_AS:
1046 if (type.isUnionType()) {
1047 NamespaceResolver resolver = env.getNamespaceResolver();
1048 UnionCastableFunction ucf = new UnionCastableFunction((UnionType) type, resolver, allowEmpty);
1049 return new StaticFunctionCall(ucf, new Expression[]{lhs});
1050 } else if (type.isListType()) {
1051 NamespaceResolver resolver = env.getNamespaceResolver();
1052 ListCastableFunction lcf = new ListCastableFunction((ListType) type, resolver, allowEmpty);
1053 return new StaticFunctionCall(lcf, new Expression[]{lhs});
1054 }
1055 break;
1056 case Token.CAST_AS:
1057 if (type.isUnionType()) {
1058 NamespaceResolver resolver = env.getNamespaceResolver();
1059 UnionConstructorFunction ucf = new UnionConstructorFunction((UnionType) type, resolver, allowEmpty);
1060 return new StaticFunctionCall(ucf, new Expression[]{lhs});
1061 } else if (type.isListType()) {
1062 NamespaceResolver resolver = env.getNamespaceResolver();
1063 ListConstructorFunction lcf = new ListConstructorFunction((ListType) type, resolver, allowEmpty);
1064 return new StaticFunctionCall(lcf, new Expression[]{lhs});
1065 }
1066 break;
1067 default:
1068 throw new IllegalArgumentException();
1069 }
1070 if (type == AnySimpleType.getInstance()) {
1071 throw new XPathException("Cannot cast to xs:anySimpleType", "XPST0080");
1072 } else {
1073 throw new XPathException("Cannot cast to " + type.getDescription(), "XPST0051");
1074 }
1075 } else {
1076 throw new XPathException("Casting to list or union types requires XPath 3.0 to be enabled", "XPST0051");
1077 }
1078
1079 }
1080
1081 /**
1082 * Parse a Typeswitch Expression.
1083 * This construct is XQuery-only, so the XPath version of this
1084 * method throws an error unconditionally
1085 *
1086 * @return the expression that results from the parsing
1087 * @throws XPathException if a static error is found
1088 */
1089
1090 /*@NotNull*/
1091 protected Expression parseTypeswitchExpression() throws XPathException {
1092 grumble("typeswitch is not allowed in XPath");
1093 return new ErrorExpression();
1094 }
1095
1096
1097 /**
1098 * Parse a Switch Expression.
1099 * This construct is XQuery-only.
1100 * SwitchExpr ::= "switch" "(" Expr ")" SwitchCaseClause+ "default" "return" ExprSingle
1101 * SwitchCaseClause ::= ("case" ExprSingle)+ "return" ExprSingle
1102 *
1103 * @return the parsed expression
1104 * @throws XPathException in the event of a syntax error
1105 */
1106
1107 /*@NotNull*/
1108 protected Expression parseSwitchExpression() throws XPathException {
1109 grumble("switch is not allowed in XPath");
1110 return new ErrorExpression();
1111 }
1112
1113 /**
1114 * Parse a Validate Expression.
1115 * This construct is XQuery-only, so the XPath version of this
1116 * method throws an error unconditionally
1117 *
1118 * @return the parsed expression; except that this version of the method always
1119 * throws an exception
1120 * @throws XPathException if a static error is found
1121 */
1122
1123 /*@NotNull*/
1124 protected Expression parseValidateExpression() throws XPathException {
1125 grumble("validate{} expressions are not allowed in XPath");
1126 return new ErrorExpression();
1127 }
1128
1129 /**
1130 * Parse an Extension Expression
1131 * This construct is XQuery-only, so the XPath version of this
1132 * method throws an error unconditionally
1133 *
1134 * @return the parsed expression; except that this version of the method
1135 * always throws an exception
1136 * @throws XPathException if a static error is found
1137 */
1138
1139 /*@NotNull*/
1140 protected Expression parseExtensionExpression() throws XPathException {
1141 grumble("extension expressions (#...#) are not allowed in XPath");
1142 return new ErrorExpression();
1143 }
1144
1145
1146 /**
1147 * Parse a try/catch Expression
1148 * This construct is XQuery-3.0 only, so the XPath version of this
1149 * method throws an error unconditionally
1150 *
1151 * @return the parsed expression; except that this version of the method
1152 * always throws an exception
1153 * @throws XPathException if a static error is found
1154 */
1155
1156 /*@NotNull*/
1157 protected Expression parseTryCatchExpression() throws XPathException {
1158 grumble("try/catch expressions are not allowed in XPath");
1159 return new ErrorExpression();
1160 }
1161
1162 /**
1163 * Parse a FOR or LET expression:
1164 * for $x in expr (',' $y in expr)* 'return' expr
1165 * let $x := expr (', $y := expr)* 'return' expr
1166 * This version of the method handles the subset of the FLWOR syntax allowed in XPath
1167 *
1168 * @return the resulting subexpression
1169 * @throws XPathException if any error is encountered
1170 */
1171
1172 protected Expression parseFLWORExpression() throws XPathException {
1173 if (t.currentToken == Token.LET && !allowXPath30Syntax) {
1174 grumble("'let' is not permitted in XPath 2.0");
1175 }
1176 if (t.currentToken == Token.FOR_SLIDING || t.currentToken == Token.FOR_TUMBLING) {
1177 grumble("sliding/tumbling windows can only be used in XQuery");
1178 }
1179 int clauses = 0;
1180 int offset;
1181 int operator = t.currentToken;
1182 Assignation first = null;
1183 Assignation previous = null;
1184 do {
1185 offset = t.currentTokenStartOffset;
1186 nextToken();
1187 expect(Token.DOLLAR);
1188 nextToken();
1189 expect(Token.NAME);
1190 String var = t.currentTokenValue;
1191
1192 // declare the range variable
1193 Assignation v;
1194 if (operator == Token.FOR) {
1195 v = new ForExpression();
1196 v.setRequiredType(SequenceType.SINGLE_ITEM);
1197 } else /*if (operator == Token.LET)*/ {
1198 v = new LetExpression();
1199 v.setRequiredType(SequenceType.ANY_SEQUENCE);
1200 }
1201
1202 clauses++;
1203 setLocation(v, offset);
1204 v.setVariableQName(makeStructuredQName(var, ""));
1205 nextToken();
1206
1207 // process the "in" or ":=" clause
1208 expect(operator == Token.LET ? Token.ASSIGN : Token.IN);
1209 nextToken();
1210 v.setSequence(parseExprSingle());
1211 declareRangeVariable(v);
1212 if (previous == null) {
1213 first = v;
1214 } else {
1215 previous.setAction(v);
1216 }
1217 previous = v;
1218
1219 } while (t.currentToken == Token.COMMA);
1220
1221 // process the "return" expression (called the "action")
1222 expect(Token.RETURN);
1223 nextToken();
1224 previous.setAction(parseExprSingle());
1225
1226 // undeclare all the range variables
1227
1228 for (int i = 0; i < clauses; i++) {
1229 undeclareRangeVariable();
1230 }
1231 return makeTracer(offset, first, LocationKind.FOR_EXPRESSION, first.getVariableQName());
1232 }
1233
1234 /**
1235 * Parse a quantified expression:
1236 * (some|every) $x in expr 'satisfies' expr
1237 *
1238 * @return the resulting subexpression
1239 * @throws XPathException if any error is encountered
1240 */
1241
1242 private Expression parseQuantifiedExpression() throws XPathException {
1243 int clauses = 0;
1244 int operator = t.currentToken;
1245 QuantifiedExpression first = null;
1246 QuantifiedExpression previous = null;
1247 int initialOffset = t.currentTokenStartOffset;
1248 do {
1249 int offset = t.currentTokenStartOffset;
1250 nextToken();
1251 expect(Token.DOLLAR);
1252 nextToken();
1253 expect(Token.NAME);
1254 String var = t.currentTokenValue;
1255 clauses++;
1256
1257 // declare the range variable
1258 QuantifiedExpression v = new QuantifiedExpression();
1259 v.setRequiredType(SequenceType.SINGLE_ITEM);
1260 v.setOperator(operator);
1261 setLocation(v, offset);
1262
1263 v.setVariableQName(makeStructuredQName(var, ""));
1264 nextToken();
1265
1266 if (t.currentToken == Token.AS && language == XQUERY) {
1267 // We use this path for quantified expressions in XQuery, which permit an "as" clause
1268 nextToken();
1269 SequenceType type = parseSequenceType();
1270 if (type.getCardinality() != StaticProperty.EXACTLY_ONE) {
1271 warning("Occurrence indicator on singleton range variable has no effect");
1272 type = SequenceType.makeSequenceType(type.getPrimaryType(), StaticProperty.EXACTLY_ONE);
1273 }
1274 v.setRequiredType(type);
1275 }
1276
1277 // process the "in" clause
1278 expect(Token.IN);
1279 nextToken();
1280 v.setSequence(parseExprSingle());
1281 declareRangeVariable(v);
1282 if (previous != null) {
1283 previous.setAction(v);
1284 } else {
1285 first = v;
1286 }
1287 previous = v;
1288
1289 } while (t.currentToken == Token.COMMA);
1290
1291 // process the "return/satisfies" expression (called the "action")
1292 expect(Token.SATISFIES);
1293 nextToken();
1294 previous.setAction(parseExprSingle());
1295
1296
1297 // undeclare all the range variables
1298
1299 for (int i = 0; i < clauses; i++) {
1300 undeclareRangeVariable();
1301 }
1302 return makeTracer(initialOffset, first, LocationKind.FOR_EXPRESSION, first.getVariableQName());
1303
1304 }
1305
1306
1307 /**
1308 * Parse an IF expression:
1309 * if '(' expr ')' 'then' expr 'else' expr
1310 *
1311 * @return the resulting subexpression
1312 * @throws XPathException if any error is encountered
1313 */
1314
1315 private Expression parseIfExpression() throws XPathException {
1316 // left paren already read
1317 int ifoffset = t.currentTokenStartOffset;
1318 nextToken();
1319 Expression condition = parseExpression();
1320 expect(Token.RPAR);
1321 nextToken();
1322 int thenoffset = t.currentTokenStartOffset;
1323 expect(Token.THEN);
1324 nextToken();
1325 Expression thenExp = makeTracer(thenoffset, parseExprSingle(), LocationKind.THEN_EXPRESSION, null);
1326 int elseoffset = t.currentTokenStartOffset;
1327 expect(Token.ELSE);
1328 nextToken();
1329 Expression elseExp = makeTracer(elseoffset, parseExprSingle(), LocationKind.ELSE_EXPRESSION, null);
1330 Expression ifExp = Choose.makeConditional(condition, thenExp, elseExp);
1331 setLocation(ifExp, ifoffset);
1332 return makeTracer(ifoffset, ifExp, LocationKind.IF_EXPRESSION, null);
1333 }
1334
1335 /**
1336 * Analyze a token whose expected value is the name of an atomic type,
1337 * or in XPath 3.0 a "plain" union type and return the object representing the atomic or union type.
1338 *
1339 * @param qname The lexical QName of the atomic type; alternatively, a Clark name
1340 * @return The atomic type
1341 * @throws XPathException if the QName is invalid or if no atomic type of that
1342 * name exists as a built-in type or a type in an imported schema
1343 */
1344 /*@NotNull*/
1345 private ItemType getPlainType(String qname) throws XPathException {
1346 if (scanOnly) {
1347 return STRING;
1348 }
1349 qNameParser.setDefaultNamespace(env.getDefaultElementNamespace());
1350 StructuredQName sq = null;
1351 try {
1352 sq = qNameParser.parse(qname);
1353 } catch (XPathException e) {
1354 grumble(e.getMessage(), e.getErrorCodeLocalPart());
1355 }
1356 return getPlainType(sq);
1357 }
1358
1359 public ItemType getPlainType(StructuredQName sq) throws XPathException {
1360 Configuration config = env.getConfiguration();
1361 String uri = sq.getURI();
1362 if (uri.isEmpty()) {
1363 uri = env.getDefaultElementNamespace();
1364 }
1365 String local = sq.getLocalPart();
1366 String qname = sq.getDisplayName();
1367
1368 boolean builtInNamespace = uri.equals(NamespaceConstant.SCHEMA);
1369
1370 if (builtInNamespace) {
1371 ItemType t = Type.getBuiltInItemType(uri, local);
1372 if (t == null) {
1373 grumble("Unknown atomic type " + qname, "XPST0051");
1374 assert false;
1375 }
1376 if (t instanceof BuiltInAtomicType) {
1377 checkAllowedType(env, (BuiltInAtomicType) t);
1378 return t;
1379 } else if (t.isPlainType()) {
1380 return t;
1381 } else {
1382 grumble("The type " + qname + " is not atomic", "XPST0051");
1383 assert false;
1384 }
1385 } else if (uri.equals(NamespaceConstant.JAVA_TYPE)) {
1386 Class theClass;
1387 try {
1388 String className = JavaExternalObjectType.localNameToClassName(local);
1389 theClass = config.getClass(className, false, null);
1390 } catch (XPathException err) {
1391 grumble("Unknown Java class " + local, "XPST0051");
1392 return AnyItemType.getInstance();
1393 }
1394 return config.getJavaExternalObjectType(theClass);
1395 } else if (uri.equals(NamespaceConstant.DOT_NET_TYPE)) {
1396 return Version.platform.getExternalObjectType(config, uri, local);
1397 } else {
1398 SchemaType st = config.getSchemaType(sq);
1399 if (st == null) {
1400 grumble("Unknown simple type " + qname, "XPST0051");
1401 } else if (st.isAtomicType()) {
1402 if (!env.isImportedSchema(uri)) {
1403 grumble("Atomic type " + qname + " exists, but its schema definition has not been imported", "XPST0051");
1404 }
1405 return (AtomicType) st;
1406 } else if (st instanceof ItemType && ((ItemType) st).isPlainType() && allowXPath30Syntax) {
1407 if (!env.isImportedSchema(uri)) {
1408 grumble("Type " + qname + " exists, but its schema definition has not been imported", "XPST0051");
1409 }
1410 return (ItemType) st;
1411 } else if (st.isComplexType()) {
1412 grumble("Type (" + qname + ") is a complex type", "XPST0051");
1413 return ANY_ATOMIC;
1414 } else if (((SimpleType) st).isListType()) {
1415 grumble("Type (" + qname + ") is a list type", "XPST0051");
1416 return ANY_ATOMIC;
1417 } else if (allowXPath30Syntax) {
1418 grumble("Type (" + qname + ") is a union type that cannot be used as an item type", "XPST0051");
1419 return ANY_ATOMIC;
1420 } else {
1421 grumble("The union type (" + qname + ") cannot be used as an item type unless XPath 3.0 is enabled", "XPST0051");
1422 return ANY_ATOMIC;
1423 }
1424 }
1425 grumble("Unknown atomic type " + qname, "XPST0051");
1426 return ANY_ATOMIC;
1427 }
1428
1429 private void checkAllowedType(StaticContext env, BuiltInAtomicType type) throws XPathException {
1430 String s = whyDisallowedType(env.getPackageData(), type);
1431 if (s != null) {
1432 grumble(s, "XPST0080");
1433 }
1434 }
1435
1436 /**
1437 * Determine whether a given built-in type is disallowed in a given environment, and in the
1438 * case where it is disallowed, return a string explaining why
1439 *
1440 * @param pack the containing package
1441 * @param type the built-in type to be tested
1442 * @return null if the type is OK to be used; or a string explaining why not.
1443 */
1444
1445 public static String whyDisallowedType(PackageData pack, BuiltInAtomicType type) {
1446 if (!type.isAllowedInXSD10() && pack.getConfiguration().getXsdVersion() == Configuration.XSD10) {
1447 return "The built-in atomic type " + type.getDisplayName() + " is not recognized unless XSD 1.1 is enabled";
1448 }
1449 return null;
1450 }
1451
1452
1453 /**
1454 * Analyze a token whose expected value is the name of a simple type: any type name
1455 * allowed as the operand of "cast" or "castable".
1456 *
1457 * @param qname The lexical QName of the atomic type; alternatively, a Clark name
1458 * @return The atomic type
1459 * @throws XPathException if the QName is invalid or if no atomic type of that
1460 * name exists as a built-in type or a type in an imported schema
1461 */
1462 /*@NotNull*/
1463 private SimpleType getSimpleType(/*@NotNull*/ String qname) throws XPathException {
1464 if (scanOnly) {
1465 return STRING;
1466 }
1467 qNameParser.setDefaultNamespace(env.getDefaultElementNamespace());
1468 StructuredQName sq = null;
1469 try {
1470 sq = qNameParser.parse(qname);
1471 } catch (XPathException e) {
1472 grumble(e.getMessage(), e.getErrorCodeLocalPart());
1473 assert false;
1474 }
1475 String uri = sq.getURI();
1476 String local = sq.getLocalPart();
1477
1478 boolean builtInNamespace = uri.equals(NamespaceConstant.SCHEMA);
1479 if (builtInNamespace) {
1480 SimpleType t = Type.getBuiltInSimpleType(uri, local);
1481 if (t == null) {
1482 if (allowXPath30Syntax) {
1483 grumble("Unknown simple type " + qname, "XQST0052");
1484 } else {
1485 grumble("Unknown simple type " + qname, "XPST0051");
1486 }
1487 }
1488 if (t instanceof BuiltInAtomicType) {
1489 checkAllowedType(env, (BuiltInAtomicType) t);
1490 }
1491 return t;
1492 } else if (uri.equals(NamespaceConstant.DOT_NET_TYPE)) {
1493 return (AtomicType) Version.platform.getExternalObjectType(env.getConfiguration(), uri, local);
1494
1495 } else {
1496
1497 SchemaType st = env.getConfiguration().getSchemaType(new StructuredQName("", uri, local));
1498 if (st == null) {
1499 if (allowXPath30Syntax) {
1500 grumble("Unknown simple type " + qname, "XQST0052");
1501 } else {
1502 grumble("Unknown simple type " + qname, "XPST0051");
1503 }
1504 return ANY_ATOMIC;
1505 }
1506 if (allowXPath30Syntax) {
1507 // XPath 3.0
1508 if (!env.isImportedSchema(uri)) {
1509 grumble("Simple type " + qname + " exists, but its target namespace has not been imported in the static context");
1510 }
1511 return (SimpleType) st;
1512
1513 } else {
1514 // XPath 2.0
1515 if (st.isAtomicType()) {
1516 if (!env.isImportedSchema(uri)) {
1517 grumble("Atomic type " + qname + " exists, but its target namespace has not been imported in the static context");
1518 }
1519 return (AtomicType) st;
1520 } else if (st.isComplexType()) {
1521 grumble("Cannot cast to a complex type (" + qname + ")", "XPST0051");
1522 return ANY_ATOMIC;
1523 } else if (((SimpleType) st).isListType()) {
1524 grumble("Casting to a list type (" + qname + ") requires XPath 3.0", "XPST0051");
1525 return ANY_ATOMIC;
1526 } else {
1527 grumble("casting to a union type (" + qname + ") requires XPath 3.0", "XPST0051");
1528 return ANY_ATOMIC;
1529 }
1530 }
1531 }
1532 }
1533
1534 /**
1535 * Parse the sequence type production.
1536 * The QName must be the name of a built-in schema-defined data type.
1537 *
1538 * @return the resulting subexpression
1539 * @throws XPathException if any error is encountered
1540 */
1541
1542 public SequenceType parseSequenceType() throws XPathException {
1543 boolean disallowIndicator = t.currentTokenValue.equals("empty-sequence");
1544 ItemType primaryType = parseItemType();
1545 if (disallowIndicator) {
1546 // No occurrence indicator allowed
1547 return SequenceType.makeSequenceType(primaryType, StaticProperty.EMPTY);
1548 }
1549 int occurrenceFlag;
1550 switch (t.currentToken) {
1551 case Token.STAR:
1552 case Token.MULT:
1553 // "*" will be tokenized different ways depending on what precedes it
1554 occurrenceFlag = StaticProperty.ALLOWS_ZERO_OR_MORE;
1555 // Make the tokenizer ignore the occurrence indicator when classifying the next token
1556 t.currentToken = Token.RPAR;
1557 nextToken();
1558 break;
1559 case Token.PLUS:
1560 occurrenceFlag = StaticProperty.ALLOWS_ONE_OR_MORE;
1561 // Make the tokenizer ignore the occurrence indicator when classifying the next token
1562 t.currentToken = Token.RPAR;
1563 nextToken();
1564 break;
1565 case Token.QMARK:
1566 occurrenceFlag = StaticProperty.ALLOWS_ZERO_OR_ONE;
1567 // Make the tokenizer ignore the occurrence indicator when classifying the next token
1568 t.currentToken = Token.RPAR;
1569 nextToken();
1570 break;
1571 default:
1572 occurrenceFlag = StaticProperty.EXACTLY_ONE;
1573 }
1574 return SequenceType.makeSequenceType(primaryType, occurrenceFlag);
1575 }
1576
1577 /**
1578 * Parse an ItemType within a SequenceType
1579 *
1580 * @return the ItemType after parsing
1581 * @throws XPathException if a static error is found
1582 */
1583
1584 /*@NotNull*/
1585 public ItemType parseItemType() throws XPathException {
1586 ItemType extended = parserExtension.parseExtendedItemType(this);
1587 return extended == null ? parseSimpleItemType() : extended;
1588 }
1589
1590 private ItemType parseSimpleItemType() throws XPathException {
1591 ItemType primaryType;
1592 if (t.currentToken == Token.LPAR) {
1593 primaryType = parseParenthesizedItemType();
1594 //nextToken();
1595 } else if (t.currentToken == Token.NAME) {
1596 primaryType = getPlainType(t.currentTokenValue);
1597 nextToken();
1598 } else if (t.currentToken == Token.NODEKIND) {
1599 // Which includes things such as "map" and "array"...
1600 switch (t.currentTokenValue) {
1601 case "item":
1602 nextToken();
1603 expect(Token.RPAR);
1604 nextToken();
1605 primaryType = AnyItemType.getInstance();
1606 break;
1607 case "function":
1608 checkLanguageVersion30();
1609 AnnotationList annotations = AnnotationList.EMPTY;
1610 primaryType = parseFunctionItemType(annotations);
1611 break;
1612 case "map":
1613 primaryType = parseMapItemType();
1614 break;
1615 case "array":
1616 primaryType = parseArrayItemType();
1617 break;
1618 case "empty-sequence":
1619 nextToken();
1620 expect(Token.RPAR);
1621 nextToken();
1622 primaryType = ErrorType.getInstance();
1623 break;
1624 default:
1625 primaryType = parseKindTest();
1626 break;
1627 }
1628 } else if (t.currentToken == Token.PERCENT) {
1629 AnnotationList annotations = parseAnnotationsList();
1630 if (t.currentTokenValue.equals("function")) {
1631 primaryType = parseFunctionItemType(annotations);
1632 } else {
1633 grumble("Expected 'function' to follow annotation assertions, found " + Token.tokens[t.currentToken]);
1634 return null;
1635 }
1636 } else if (language == EXTENDED_ITEM_TYPE && t.currentToken == Token.PREFIX) {
1637 String tokv = t.currentTokenValue;
1638 nextToken();
1639 return makeNamespaceTest(Type.ELEMENT, tokv);
1640 } else if (language == EXTENDED_ITEM_TYPE && t.currentToken == Token.SUFFIX) {
1641 nextToken();
1642 expect(Token.NAME);
1643 String tokv = t.currentTokenValue;
1644 nextToken();
1645 return makeLocalNameTest(Type.ELEMENT, tokv);
1646 } else if (language == EXTENDED_ITEM_TYPE && t.currentToken == Token.AT) {
1647 nextToken();
1648 if (t.currentToken == Token.PREFIX) {
1649 String tokv = t.currentTokenValue;
1650 nextToken();
1651 return makeNamespaceTest(Type.ATTRIBUTE, tokv);
1652 } else if (t.currentToken == Token.SUFFIX) {
1653 nextToken();
1654 expect(Token.NAME);
1655 String tokv = t.currentTokenValue;
1656 nextToken();
1657 return makeLocalNameTest(Type.ATTRIBUTE, tokv);
1658 } else {
1659 grumble("Expected NodeTest after '@'");
1660 return ANY_ATOMIC;
1661 }
1662 } else {
1663 grumble("Expected type name in SequenceType, found " + Token.tokens[t.currentToken]);
1664 return ANY_ATOMIC;
1665 }
1666 return primaryType;
1667 }
1668
1669 /**
1670 * Get the item type used for function items (XPath 3.0 higher order functions)
1671 *
1672 * @return the item type representing a function item
1673 * @throws net.sf.saxon.trans.XPathException if a static error occurs (including the case
1674 * where XPath 3.0 syntax is not enabled)
1675 * @param annotations the list of annotation assertions for this function item type
1676 */
1677
1678 /*@NotNull*/
1679 protected ItemType parseFunctionItemType(AnnotationList annotations) throws XPathException {
1680 return parserExtension.parseFunctionItemType(this, annotations);
1681 }
1682
1683 /**
1684 * Parse the item type used for maps (XSLT extension to XPath 3.0)
1685 * Syntax:
1686 * map '(' '*' ') |
1687 * map '(' ItemType ',' SeqType ')' 'as' SeqType
1688 * The "map(" has already been read
1689 * @return the item type of the map
1690 * @throws XPathException if a parsing error occurs or if the map syntax
1691 * is not available
1692 */
1693
1694 /*@NotNull*/
1695 protected ItemType parseMapItemType() throws XPathException {
1696 checkMapExtensions();
1697 Tokenizer t = getTokenizer();
1698 nextToken();
1699 if (t.currentToken == Token.STAR || t.currentToken == Token.MULT) {
1700 // Allow both to be safe
1701 nextToken();
1702 expect(Token.RPAR);
1703 nextToken();
1704 return MapType.ANY_MAP_TYPE;
1705 } else {
1706 ItemType keyType = parseItemType();
1707 expect(Token.COMMA);
1708 nextToken();
1709 SequenceType valueType = parseSequenceType();
1710 expect(Token.RPAR);
1711 nextToken();
1712 if (!(keyType instanceof AtomicType)) {
1713 grumble("Key type of a map must be atomic");
1714 return null;
1715 }
1716 return new MapType((AtomicType) keyType, valueType);
1717 }
1718 }
1719
1720 /**
1721 * Get the item type used for array items (XPath 3.1)
1722 * Syntax:
1723 * array '(' '*' ') |
1724 * array '(' SeqType ')'
1725 * The "array(" has already been read
1726 * @return the item type of the array
1727 * @throws XPathException if a parsing error occurs or if the array syntax
1728 * is not available
1729 */
1730
1731 /*@NotNull*/
1732 protected ItemType parseArrayItemType() throws XPathException {
1733 checkLanguageVersion31();
1734 Tokenizer t = getTokenizer();
1735 nextToken();
1736 if (t.currentToken == Token.STAR || t.currentToken == Token.MULT) {
1737 // Allow both to be safe
1738 nextToken();
1739 expect(Token.RPAR);
1740 nextToken();
1741 return ArrayItemType.ANY_ARRAY_TYPE;
1742 } else {
1743 SequenceType memberType = parseSequenceType();
1744 expect(Token.RPAR);
1745 nextToken();
1746 return new ArrayItemType(memberType);
1747 }
1748 }
1749
1750 /**
1751 * Parse a parenthesized item type (allowed in XQuery 3.0 and XPath 3.0 only)
1752 *
1753 * @return the item type
1754 * @throws XPathException in the event of a syntax error (or if 3.0 is not enabled)
1755 */
1756
1757 /*@NotNull*/
1758 private ItemType parseParenthesizedItemType() throws XPathException {
1759 if (!allowXPath30Syntax) {
1760 grumble("Parenthesized item types require 3.0 to be enabled");
1761 }
1762 nextToken();
1763 ItemType primaryType = parseItemType();
1764 while (primaryType instanceof NodeTest && language == EXTENDED_ITEM_TYPE && t.currentToken != Token.RPAR) {
1765 switch (t.currentToken) {
1766 case Token.UNION:
1767 case Token.EXCEPT:
1768 case Token.INTERSECT:
1769 int op = t.currentToken;
1770 nextToken();
1771 primaryType = new CombinedNodeTest((NodeTest) primaryType, op, (NodeTest) parseItemType());
1772 }
1773 }
1774 expect(Token.RPAR);
1775 nextToken();
1776 return primaryType;
1777 }
1778
1779
1780 /**
1781 * Parse a UnaryExpr:<br>
1782 * ('+'|'-')* ValueExpr
1783 * parsed as ('+'|'-')? UnaryExpr
1784 *
1785 * @return the resulting subexpression
1786 * @throws XPathException if any error is encountered
1787 */
1788
1789 /*@NotNull*/
1790 private Expression parseUnaryExpression() throws XPathException {
1791 Expression exp;
1792 switch (t.currentToken) {
1793 case Token.MINUS: {
1794 nextToken();
1795 Expression operand = parseUnaryExpression();
1796 exp = makeUnaryExpression(Token.NEGATE, operand);
1797 break;
1798 }
1799 case Token.PLUS: {
1800 nextToken();
1801 // Unary plus: can't ignore it completely, it might be a type error, or it might
1802 // force conversion to a number which would affect operations such as "=".
1803 Expression operand = parseUnaryExpression();
1804 exp = makeUnaryExpression(Token.PLUS, operand);
1805 break;
1806 }
1807 case Token.VALIDATE:
1808 case Token.VALIDATE_STRICT:
1809 case Token.VALIDATE_LAX:
1810 case Token.VALIDATE_TYPE:
1811 exp = parseValidateExpression();
1812 break;
1813 case Token.PRAGMA:
1814 exp = parseExtensionExpression();
1815 break;
1816
1817 case Token.KEYWORD_CURLY:
1818 if (t.currentTokenValue.equals("validate")) {
1819 exp = parseValidateExpression();
1820 break;
1821 }
1822 // else fall through
1823 default:
1824 exp = parseSimpleMappingExpression();
1825 }
1826 setLocation(exp);
1827 return exp;
1828 }
1829
1830 private Expression makeUnaryExpression(int operator, Expression operand) {
1831 if (Literal.isAtomic(operand)) {
1832 // very early evaluation of expressions like "-1", so they are treated as numeric literals
1833 AtomicValue val = (AtomicValue) ((Literal) operand).getValue();
1834 if (val instanceof NumericValue) {
1835 if (env.isInBackwardsCompatibleMode()) {
1836 val = new DoubleValue(((NumericValue) val).getDoubleValue());
1837 }
1838 AtomicValue value = operator == Token.NEGATE ? ((NumericValue) val).negate() : (NumericValue) val;
1839 return Literal.makeLiteral(value);
1840 }
1841 }
1842 return env.getConfiguration().getTypeChecker(env.isInBackwardsCompatibleMode()).makeArithmeticExpression(
1843 Literal.makeLiteral(Int64Value.ZERO), operator, operand);
1844 }
1845
1846 /**
1847 * Test whether the current token is one that can start a RelativePathExpression
1848 *
1849 * @return the resulting subexpression
1850 */
1851
1852 protected boolean atStartOfRelativePath() {
1853 switch (t.currentToken) {
1854 case Token.AXIS:
1855 case Token.AT:
1856 case Token.NAME:
1857 case Token.PREFIX:
1858 case Token.SUFFIX:
1859 case Token.STAR:
1860 case Token.NODEKIND:
1861 case Token.DOT:
1862 case Token.DOTDOT:
1863 case Token.FUNCTION:
1864 case Token.STRING_LITERAL:
1865 case Token.NUMBER:
1866 case Token.LPAR:
1867 case Token.DOLLAR:
1868 case Token.PRAGMA:
1869 case Token.ELEMENT_QNAME:
1870 case Token.ATTRIBUTE_QNAME:
1871 case Token.PI_QNAME:
1872 case Token.NAMESPACE_QNAME:
1873 case Token.NAMED_FUNCTION_REF:
1874 return true;
1875 case Token.KEYWORD_CURLY:
1876 return t.currentTokenValue.equals("ordered") || t.currentTokenValue.equals("unordered");
1877 default:
1878 return false;
1879 }
1880 }
1881
1882 /**
1883 * Test whether the current token is one that is disallowed after a "leading lone slash".
1884 * These composite tokens have been parsed as operators, but are not allowed after "/" under the
1885 * rules of erratum E24
1886 *
1887 * @return the resulting subexpression
1888 */
1889
1890 protected boolean disallowedAtStartOfRelativePath() {
1891 switch (t.currentToken) {
1892 // Although these "double keyword" operators can readily be recognized as operators,
1893 // they are not permitted after leading "/" under the rules of erratum XQ.E24
1894 case Token.CAST_AS:
1895 case Token.CASTABLE_AS:
1896 case Token.INSTANCE_OF:
1897 case Token.TREAT_AS:
1898 return true;
1899 default:
1900 return false;
1901 }
1902 }
1903
1904 /**
1905 * Parse a PathExpresssion. This includes "true" path expressions such as A/B/C, and also
1906 * constructs that may start a path expression such as a variable reference $name or a
1907 * parenthesed expression (A|B). Numeric and string literals also come under this heading.
1908 *
1909 * @return the resulting subexpression
1910 * @throws XPathException if any error is encountered
1911 */
1912
1913 /*@NotNull*/
1914 protected Expression parsePathExpression() throws XPathException {
1915 int offset = t.currentTokenStartOffset;
1916 switch (t.currentToken) {
1917 case Token.SLASH:
1918 nextToken();
1919 final RootExpression start = new RootExpression();
1920 setLocation(start);
1921 if (disallowedAtStartOfRelativePath()) {
1922 grumble("Operator '" + Token.tokens[t.currentToken] + "' is not allowed after '/'");
1923 }
1924 if (atStartOfRelativePath()) {
1925 final Expression path = parseRemainingPath(start);
1926 setLocation(path, offset);
1927 return path;
1928 } else {
1929 return start;
1930 }
1931
1932 case Token.SLASH_SLASH:
1933 nextToken();
1934 final RootExpression start2 = new RootExpression();
1935 setLocation(start2, offset);
1936 final AxisExpression axisExp = new AxisExpression(AxisInfo.DESCENDANT_OR_SELF, null);
1937 setLocation(axisExp, offset);
1938 final Expression slashExp = ExpressionTool.makePathExpression(start2, axisExp);
1939 setLocation(slashExp, offset);
1940 final Expression exp = parseRemainingPath(slashExp);
1941 setLocation(exp, offset);
1942 return exp;
1943
1944 default:
1945 if (t.currentToken == Token.NAME &&
1946 (t.currentTokenValue.equals("true") || t.currentTokenValue.equals("false"))) {
1947 warning("The expression is looking for a child element named '" + t.currentTokenValue +
1948 "' - perhaps " + t.currentTokenValue + "() was intended? To avoid this warning, use child::" +
1949 t.currentTokenValue + " or ./" + t.currentTokenValue + ".");
1950 }
1951 if (t.currentToken == Token.NAME && t.getBinaryOp(t.currentTokenValue) != Token.UNKNOWN &&
1952 language != XSLT_PATTERN && (offset > 0 || t.peekAhead() != Token.EOF)) {
1953 String s = t.currentTokenValue;
1954 warning("The keyword '" + s + "' in this context means 'child::" + s +
1955 "'. If this was intended, use 'child::" + s + "' or './" + s + "' to avoid this warning.");
1956 }
1957 return parseRelativePath();
1958 }
1959
1960 }
1961
1962 /**
1963 * Parse an XPath 3.0 simple mapping expression ("!" operator)
1964 *
1965 * @return the parsed expression
1966 * @throws XPathException in the event of a syntax error
1967 */
1968
1969 protected Expression parseSimpleMappingExpression() throws XPathException {
1970 int offset = t.currentTokenStartOffset;
1971 Expression exp = parsePathExpression();
1972 while (t.currentToken == Token.BANG) {
1973 if (!allowXPath30Syntax) {
1974 grumble("XPath '!' operator requires XPath 3.0 to be enabled");
1975 }
1976 nextToken();
1977 Expression next = parsePathExpression();
1978 exp = new ForEach(exp, next);
1979 setLocation(exp, offset);
1980 }
1981 return exp;
1982 }
1983
1984 /**
1985 * Parse a relative path (a sequence of steps). Called when the current token immediately
1986 * follows a separator (/ or //), or an implicit separator (XYZ is equivalent to ./XYZ)
1987 *
1988 * @return the resulting subexpression
1989 * @throws XPathException if any error is encountered
1990 */
1991
1992 /*@NotNull*/
1993 protected Expression parseRelativePath() throws XPathException {
1994 int offset = t.currentTokenStartOffset;
1995 Expression exp = parseStepExpression(language == XSLT_PATTERN);
1996 while (t.currentToken == Token.SLASH ||
1997 t.currentToken == Token.SLASH_SLASH) {
1998 int op = t.currentToken;
1999 nextToken();
2000 Expression next = parseStepExpression(false);
2001 if (op == Token.SLASH) {
2002
2003 //return new RawSlashExpression(start, step);
2004 exp = new HomogeneityChecker(new SlashExpression(exp, next));
2005 } else /* (op == Token.SLASH_SLASH)*/ {
2006 // add implicit descendant-or-self::node() step
2007 AxisExpression ae = new AxisExpression(AxisInfo.DESCENDANT_OR_SELF, null);
2008 setLocation(ae, offset);
2009 Expression one = ExpressionTool.makePathExpression(exp, ae);
2010 setLocation(one, offset);
2011 exp = ExpressionTool.makePathExpression(one, next);
2012 exp = new HomogeneityChecker(exp);
2013 }
2014 setLocation(exp, offset);
2015 }
2016 return exp;
2017 }
2018
2019 /**
2020 * Parse the remaining steps of an absolute path expression (one starting in "/" or "//"). Note that the
2021 * token immediately after the "/" or "//" has already been read, and in the case of "/", it has been confirmed
2022 * that we have a path expression starting with "/" rather than a standalone "/" expression.
2023 *
2024 * @param start the initial implicit expression: root() in the case of "/", root()/descendant-or-self::node in
2025 * the case of "//"
2026 * @return the completed path expression
2027 * @throws XPathException if a static error is found
2028 */
2029 /*@NotNull*/
2030 protected Expression parseRemainingPath(Expression start) throws XPathException {
2031 int offset = t.currentTokenStartOffset;
2032 Expression exp = start;
2033 int op = Token.SLASH;
2034 while (true) {
2035 Expression next = parseStepExpression(false);
2036 if (op == Token.SLASH) {
2037
2038 //return new RawSlashExpression(start, step);
2039 exp = new HomogeneityChecker(new SlashExpression(exp, next));
2040 } else if (op == Token.SLASH_SLASH) {
2041 // add implicit descendant-or-self::node() step
2042 AxisExpression descOrSelf = new AxisExpression(AxisInfo.DESCENDANT_OR_SELF, null);
2043 setLocation(descOrSelf);
2044 Expression step = ExpressionTool.makePathExpression(descOrSelf, next);
2045 setLocation(step);
2046 exp = ExpressionTool.makePathExpression(exp, step);
2047 exp = new HomogeneityChecker(exp);
2048 } else /*if (op == Token.BANG)*/ {
2049 if (!allowXPath30Syntax) {
2050 grumble("XPath '!' operator requires XPath 3.0 to be enabled");
2051 }
2052 exp = new ForEach(exp, next);
2053 }
2054 setLocation(exp, offset);
2055 op = t.currentToken;
2056 if (op != Token.SLASH && op != Token.SLASH_SLASH && op != Token.BANG) {
2057 break;
2058 }
2059 nextToken();
2060 }
2061 return exp;
2062 }
2063
2064
2065 /**
2066 * Parse a step (including an optional sequence of predicates)
2067 *
2068 * @param firstInPattern true only if we are parsing the first step in a
2069 * RelativePathPattern in the XSLT Pattern syntax
2070 * @return the resulting subexpression
2071 * @throws XPathException if any error is encountered
2072 */
2073
2074 /*@NotNull*/
2075 protected Expression parseStepExpression(boolean firstInPattern) throws XPathException {
2076 Expression step = parseBasicStep(firstInPattern);
2077
2078 // When the filter is applied to an Axis step, the nodes are considered in
2079 // axis order. In all other cases they are considered in document order
2080 boolean reverse = (step instanceof AxisExpression) &&
2081 !AxisInfo.isForwards[((AxisExpression) step).getAxis()];
2082
2083 while (true) {
2084 if (t.currentToken == Token.LSQB) {
2085 step = parsePredicate(step);
2086 } else if (t.currentToken == Token.LPAR) {
2087 // dynamic function call (XQuery 3.0/XPath 3.0 syntax)
2088 step = parseDynamicFunctionCall(step, null);
2089 setLocation(step);
2090 } else if (t.currentToken == Token.QMARK) {
2091 step = parseLookup(step);
2092 setLocation(step);
2093 } else {
2094 break;
2095 }
2096 }
2097 if (reverse) {
2098 // An AxisExpression such as preceding-sibling::x delivers nodes in axis
2099 // order, so that positional predicate like preceding-sibling::x[1] work
2100 // correctly. To satisfy the XPath semantics we turn preceding-sibling::x
2101 // into reverse(preceding-sibling::x), and preceding-sibling::x[3] into
2102 // reverse(preceding-sibling::x[3]). The call on reverse() will be eliminated
2103 // later in the case where the predicate selects a singleton.
2104 RetainedStaticContext rsc = env.makeRetainedStaticContext();
2105 step = SystemFunction.makeCall("reverse", rsc, step);
2106 assert step != null;
2107 return step;
2108 } else {
2109 return step;
2110 }
2111 }
2112
2113 protected Expression parsePredicate(Expression step) throws XPathException {
2114 nextToken();
2115 Expression predicate = parsePredicate();
2116 expect(Token.RSQB);
2117 nextToken();
2118 step = new FilterExpression(step, predicate);
2119 setLocation(step);
2120 return step;
2121 }
2122
2123 /**
2124 * Parse an XPath 3.1 arrow operator ("=&gt;")
2125 *
2126 * @return the expression that results from the parsing
2127 */
2128
2129 /*@NotNull*/
2130 protected Expression parseArrowPostfix(Expression lhs) throws XPathException {
2131 checkLanguageVersion31();
2132 nextToken();
2133 int token = getTokenizer().currentToken;
2134 if (token == Token.NAME || token == Token.FUNCTION) {
2135 return parseFunctionCall(lhs);
2136 } else if (token == Token.DOLLAR) {
2137 Expression var = parseVariableReference();
2138 expect(Token.LPAR);
2139 return parseDynamicFunctionCall(var, lhs);
2140 } else if (token == Token.LPAR) {
2141 Expression var = parseParenthesizedExpression();
2142 expect(Token.LPAR);
2143 return parseDynamicFunctionCall(var, lhs);
2144 } else {
2145 grumble("Unexpected " + Token.tokens[token] + " after '=>'");
2146 return null;
2147 }
2148 }
2149
2150 /**
2151 * Parse the expression within a predicate. A separate method so it can be overridden
2152 *
2153 * @return the expression within the predicate
2154 * @throws XPathException if a static error is found
2155 */
2156
2157 /*@NotNull*/
2158 protected Expression parsePredicate() throws XPathException {
2159 return parseExpression();
2160 }
2161
2162 protected boolean isReservedInQuery(String uri) {
2163 if (allowXPath31Syntax) {
2164 return NamespaceConstant.isReservedInQuery31(uri);
2165 } else if (allowXPath30Syntax) {
2166 return NamespaceConstant.isReservedInQuery30(uri);
2167 } else {
2168 return NamespaceConstant.isReservedInQuery(uri);
2169 }
2170 }
2171
2172 /**
2173 * Parse a basic step expression (without the predicates)
2174 *
2175 * @param firstInPattern true only if we are parsing the first step in a
2176 * RelativePathPattern in the XSLT Pattern syntax
2177 * @return the resulting subexpression
2178 * @throws XPathException if any error is encountered
2179 */
2180
2181 /*@NotNull*/
2182 protected Expression parseBasicStep(boolean firstInPattern) throws XPathException {
2183 switch (t.currentToken) {
2184 case Token.DOLLAR:
2185 return parseVariableReference();
2186
2187 case Token.LPAR:
2188 return parseParenthesizedExpression();
2189
2190 case Token.LSQB:
2191 return parseArraySquareConstructor();
2192
2193 case Token.STRING_LITERAL:
2194 return parseStringLiteral(true);
2195
2196 case Token.STRING_TEMPLATE_COMPLETE:
2197 return parseStringTemplate(true);
2198
2199 case Token.STRING_TEMPLATE_INITIAL:
2200 return parseStringTemplate(false);
2201
2202 case Token.NUMBER:
2203 return parseNumericLiteral(true);
2204
2205 case Token.FUNCTION:
2206 return parseFunctionCall(null);
2207
2208 case Token.QMARK:
2209 return parseLookup(new ContextItemExpression());
2210
2211 case Token.DOT:
2212 nextToken();
2213 Expression cie = new ContextItemExpression();
2214 setLocation(cie);
2215 return cie;
2216
2217 case Token.DOTDOT:
2218 nextToken();
2219 Expression pne = new AxisExpression(AxisInfo.PARENT, null);
2220 setLocation(pne);
2221 return pne;
2222
2223 case Token.PERCENT: {
2224 AnnotationList annotations = parseAnnotationsList();
2225 if (!t.currentTokenValue.equals("function")) {
2226 grumble("Expected 'function' to follow the annotation assertion");
2227 }
2228 annotations.check(env.getConfiguration(), "IF");
2229 return parseInlineFunction(annotations);
2230 }
2231 case Token.NODEKIND:
2232 if (t.currentTokenValue.equals("function")) {
2233 AnnotationList annotations = AnnotationList.EMPTY;
2234 return parseInlineFunction(annotations);
2235 // } else if (t.currentTokenValue.equals("map")) {
2236 // return parseFunctionCall(null);
2237 }
2238 // fall through!
2239 case Token.NAME:
2240 case Token.PREFIX:
2241 case Token.SUFFIX:
2242 case Token.STAR:
2243 byte defaultAxis = AxisInfo.CHILD;
2244 if (t.currentToken == Token.NODEKIND &&
2245 (t.currentTokenValue.equals("attribute") || t.currentTokenValue.equals("schema-attribute"))) {
2246 defaultAxis = AxisInfo.ATTRIBUTE;
2247 } else if (t.currentToken == Token.NODEKIND && t.currentTokenValue.equals("namespace-node")) {
2248 defaultAxis = AxisInfo.NAMESPACE;
2249 testPermittedAxis(AxisInfo.NAMESPACE, "XQST0134");
2250 } else if (firstInPattern && t.currentToken == Token.NODEKIND && t.currentTokenValue.equals("document-node")) {
2251 defaultAxis = AxisInfo.SELF;
2252 }
2253 NodeTest test = parseNodeTest(Type.ELEMENT);
2254 if (test instanceof AnyNodeTest) {
2255 // handles patterns of the form match="node()"
2256 test = defaultAxis == AxisInfo.CHILD ? AnyChildNodeTest.getInstance() : NodeKindTest.ATTRIBUTE;
2257 }
2258 AxisExpression ae = new AxisExpression(defaultAxis, test);
2259 setLocation(ae);
2260 return ae;
2261
2262 case Token.AT:
2263 nextToken();
2264 switch (t.currentToken) {
2265
2266 case Token.NAME:
2267 case Token.PREFIX:
2268 case Token.SUFFIX:
2269 case Token.STAR:
2270 case Token.NODEKIND:
2271 AxisExpression ae2 = new AxisExpression(AxisInfo.ATTRIBUTE, parseNodeTest(Type.ATTRIBUTE));
2272 setLocation(ae2);
2273 return ae2;
2274
2275 default:
2276 grumble("@ must be followed by a NodeTest");
2277 }
2278 break;
2279
2280 case Token.AXIS:
2281 byte axis;
2282 try {
2283 axis = AxisInfo.getAxisNumber(t.currentTokenValue);
2284 } catch (XPathException err) {
2285 grumble(err.getMessage());
2286 axis = AxisInfo.CHILD; // error recovery
2287 }
2288 testPermittedAxis(axis, "XPST0003");
2289 short principalNodeType = AxisInfo.principalNodeType[axis];
2290 nextToken();
2291 switch (t.currentToken) {
2292
2293 case Token.NAME:
2294 case Token.PREFIX:
2295 case Token.SUFFIX:
2296 case Token.STAR:
2297 case Token.NODEKIND:
2298 Expression ax = new AxisExpression(axis, parseNodeTest(principalNodeType));
2299 setLocation(ax);
2300 return ax;
2301
2302 default:
2303 grumble("Unexpected token " + currentTokenDisplay() + " after axis name");
2304 }
2305 break;
2306
2307 case Token.KEYWORD_CURLY:
2308 switch (t.currentTokenValue) {
2309 case "map":
2310 return parseMapExpression();
2311 case "array":
2312 return parseArrayCurlyConstructor();
2313 case "fn":
2314 return parserExtension.parseSimpleInlineFunction(this);
2315 }
2316 // else fall through
2317 case Token.ELEMENT_QNAME:
2318 case Token.ATTRIBUTE_QNAME:
2319 case Token.NAMESPACE_QNAME:
2320 case Token.PI_QNAME:
2321 case Token.TAG:
2322 return parseConstructor();
2323
2324 case Token.NAMED_FUNCTION_REF:
2325 return parseNamedFunctionReference();
2326
2327 default:
2328 grumble("Unexpected token " + currentTokenDisplay() + " at start of expression");
2329 //break;
2330 }
2331 return new ErrorExpression();
2332 }
2333
2334 public Expression parseParenthesizedExpression() throws XPathException {
2335 nextToken();
2336 if (t.currentToken == Token.RPAR) {
2337 nextToken();
2338 return Literal.makeEmptySequence();
2339 }
2340 Expression seq = parseExpression();
2341 expect(Token.RPAR);
2342 nextToken();
2343 return seq;
2344 }
2345
2346 protected void testPermittedAxis(byte axis, String errorCode) throws XPathException {
2347 // no action by default - all axes are permitted
2348 }
2349
2350
2351 public Expression parseNumericLiteral(boolean traceable) throws XPathException {
2352 int offset = t.currentTokenStartOffset;
2353 NumericValue number = NumericValue.parseNumber(t.currentTokenValue);
2354 if (number.isNaN()) {
2355 grumble("Invalid numeric literal " + Err.wrap(t.currentTokenValue, Err.VALUE));
2356 }
2357 nextToken();
2358 Literal lit = Literal.makeLiteral(number);
2359 setLocation(lit, offset);
2360 //lit.setRetainedStaticContext(env.makeRetainedStaticContext());
2361 return traceable ? makeTracer(offset, lit, 0, null) : lit;
2362 }
2363
2364 protected Expression parseStringLiteral(boolean traceable) throws XPathException {
2365 int offset = t.currentTokenStartOffset;
2366 Literal literal = makeStringLiteral(t.currentTokenValue);
2367 //literal.setRetainedStaticContext(env.makeRetainedStaticContext());
2368 nextToken();
2369 return traceable ? makeTracer(offset, literal, 0, null) : literal;
2370 }
2371
2372 protected Expression parseStringTemplate(boolean complete) throws XPathException {
2373 grumble("String constructor expressions are allowed only in XQuery");
2374 return null;
2375 }
2376
2377 /*@NotNull*/
2378 public Expression parseVariableReference() throws XPathException {
2379 int offset = t.currentTokenStartOffset;
2380 nextToken();
2381 expect(Token.NAME);
2382 String var = t.currentTokenValue;
2383 nextToken();
2384
2385 if (scanOnly) {
2386 return new ContextItemExpression();
2387 // don't do any semantic checks during a prescan
2388 }
2389
2390 //int vtest = makeNameCode(var, false) & 0xfffff;
2391 StructuredQName vtest = makeStructuredQName(var, "");
2392 assert vtest != null;
2393
2394 // See if it's a range variable or a variable in the context
2395 LocalBinding b = findRangeVariable(vtest);
2396 Expression ref;
2397 if (b != null) {
2398 ref = new LocalVariableReference(b);
2399 } else {
2400 if (catchDepth > 0) {
2401 for (StructuredQName errorVariable : StandardNames.errorVariables) {
2402 if (errorVariable.getLocalPart().equals(vtest.getLocalPart())) {
2403 StructuredQName functionName =
2404 new StructuredQName("saxon", NamespaceConstant.SAXON, "dynamic-error-info");
2405 SymbolicName.F sn = new SymbolicName.F(functionName, 1);
2406 Expression[] args = new Expression[]{new StringLiteral(vtest.getLocalPart())};
2407 return VendorFunctionSetHE.getInstance().bind(sn, args, env, new ArrayList<>());
2408 }
2409 }
2410 }
2411 try {
2412 ref = env.bindVariable(vtest);
2413 } catch (XPathException err) {
2414 err.maybeSetLocation(makeLocation());
2415 throw err;
2416 }
2417 }
2418 setLocation(ref, offset);
2419 return ref;
2420 }
2421
2422 /**
2423 * Method to make a string literal from a token identified as a string
2424 * literal. This is trivial in XPath, but in XQuery the method is overridden
2425 * to identify pseudo-XML character and entity references. Note that the job of handling
2426 * doubled string delimiters is done by the tokenizer.
2427 *
2428 * @param currentTokenValue the token as read (excluding quotation marks)
2429 * @return The string value of the string literal
2430 * @throws net.sf.saxon.trans.XPathException if a static error is found
2431 */
2432
2433 /*@NotNull*/
2434 protected Literal makeStringLiteral(String currentTokenValue) throws XPathException {
2435 StringLiteral literal = new StringLiteral(currentTokenValue);
2436 setLocation(literal);
2437 return literal;
2438 }
2439
2440 /**
2441 * Unescape character references and built-in entity references in a string. Does nothing
2442 * in XPath, because XPath does not recognize entity references in string literals
2443 *
2444 * @param token the input string, which may include XML-style character references or built-in
2445 * entity references
2446 * @return the string with character references and built-in entity references replaced by their expansion
2447 * @throws XPathException if a malformed character or entity reference is found
2448 */
2449
2450 /*@NotNull*/
2451 protected CharSequence unescape(String token) throws XPathException {
2452 return token;
2453 }
2454
2455
2456 /**
2457 * Parse a node constructor. This is allowed only in XQuery, so the method throws
2458 * an error for XPath.
2459 *
2460 * @return the expression that results from the parsing
2461 * @throws net.sf.saxon.trans.XPathException if a static error occurs
2462 */
2463
2464 /*@NotNull*/
2465 protected Expression parseConstructor() throws XPathException {
2466 grumble("Node constructor expressions are allowed only in XQuery, not in XPath");
2467 return new ErrorExpression();
2468 }
2469
2470 /**
2471 * Parse a dynamic function call
2472 *
2473 * @param functionItem the expression that determines the function to be called
2474 * @param prefixArgument the LHS of an arrow operator, or null if this is not part of an arrow expression
2475 * @return the expression that results from the parsing
2476 * @throws net.sf.saxon.trans.XPathException if a static error is found
2477 */
2478
2479 /*@NotNull*/
2480 public Expression parseDynamicFunctionCall(Expression functionItem, Expression prefixArgument) throws XPathException {
2481 checkLanguageVersion30();
2482
2483 ArrayList<Expression> args = new ArrayList<>(10);
2484 if (prefixArgument != null) {
2485 args.add(prefixArgument);
2486 }
2487 IntSet placeMarkers = null;
2488
2489 // the "(" has already been read by the Tokenizer: now parse the arguments
2490 nextToken();
2491 if (t.currentToken != Token.RPAR) {
2492 while (true) {
2493 Expression arg = parseFunctionArgument();
2494 if (arg == null) {
2495 // this is a "?" placemarker
2496 if (placeMarkers == null) {
2497 placeMarkers = new IntArraySet();
2498 }
2499 placeMarkers.add(args.size());
2500 arg = Literal.makeEmptySequence(); // a convenient fiction
2501 checkHofFeature();
2502 }
2503 args.add(arg);
2504 if (t.currentToken == Token.COMMA) {
2505 nextToken();
2506 } else {
2507 break;
2508 }
2509 }
2510 expect(Token.RPAR);
2511 }
2512 nextToken();
2513
2514 if (placeMarkers == null) {
2515 return generateApplyCall(functionItem, args);
2516 } else {
2517 return parserExtension.createDynamicCurriedFunction(this, functionItem, args, placeMarkers);
2518 }
2519 }
2520
2521
2522
2523 protected Expression generateApplyCall(Expression functionItem, ArrayList<Expression> args) throws XPathException {
2524 SquareArrayConstructor block = new SquareArrayConstructor(args);
2525 RetainedStaticContext rsc = new RetainedStaticContext(getStaticContext());
2526 SystemFunction fn = VendorFunctionSetHE.getInstance().makeFunction("apply", 2);
2527 fn.setRetainedStaticContext(rsc);
2528 Expression call = fn.makeFunctionCall(functionItem, block);
2529 ((ApplyFn) fn).setDynamicFunctionCall(functionItem.toShortString());
2530 setLocation(call, t.currentTokenStartOffset);
2531 return call;
2532 }
2533
2534 /**
2535 * Parse a lookup operator ("?")
2536 *
2537 * @param lhs the expression that the function to be called
2538 * @return the expression that results from the parsing
2539 * @throws net.sf.saxon.trans.XPathException if a static error is found
2540 */
2541
2542 /*@NotNull*/
2543 protected Expression parseLookup(Expression lhs) throws XPathException {
2544 checkLanguageVersion31();
2545 Tokenizer t = getTokenizer();
2546 int offset = t.currentTokenStartOffset;
2547 t.setState(Tokenizer.BARE_NAME_STATE); // Prevent mis-recognition of x?f(2)
2548 t.currentToken = Token.LPAR; // Hack to force following symbol to be recognised in post-operator mode
2549 nextToken();
2550 int token = t.currentToken;
2551 t.setState(Tokenizer.OPERATOR_STATE);
2552
2553 Expression result;
2554 if (token == Token.NAME) {
2555 String name = t.currentTokenValue;
2556 if (!NameChecker.isValidNCName(name)) {
2557 grumble("The name following '?' must be a valid NCName");
2558 }
2559 nextToken();
2560 result = lookupName(lhs, name);
2561 } else if (token == Token.NUMBER) {
2562 NumericValue number = NumericValue.parseNumber(t.currentTokenValue);
2563 if (!(number instanceof IntegerValue)) {
2564 grumble("Number following '?' must be an integer");
2565 }
2566 nextToken();
2567 result = lookup(this, lhs, Literal.makeLiteral(number));
2568 } else if (token == Token.MULT || token == Token.STAR) {
2569 nextToken();
2570 result = lookupStar(lhs);
2571 } else if (token == Token.LPAR) {
2572 result = lookup(this, lhs, parseParenthesizedExpression());
2573 } else {
2574 grumble("Unexpected " + Token.tokens[token] + " after '?'");
2575 return null;
2576 }
2577 setLocation(result, offset);
2578 return result;
2579 }
2580
2581 /**
2582 * Supporting code for lookup expressions (A?B)
2583 *
2584 * @param parser the XPath parser
2585 * @param lhs the LHS operand of the lookup expression
2586 * @param rhs the RHS operand of the lookup expression
2587 * @return the result of parsing the expression
2588 */
2589
2590 private static Expression lookup(XPathParser parser, Expression lhs, Expression rhs) {
2591 return new LookupExpression(lhs, rhs);
2592 // ForExpression lhsVar = new ForExpression();
2593 // lhsVar.setVariableQName(new StructuredQName("vv", NamespaceConstant.SAXON_GENERATED_VARIABLE, "LHS" + lhsVar.hashCode()));
2594 // lhsVar.setSequence(lhs);
2595 // lhsVar.setRequiredType(SequenceType.SINGLE_FUNCTION);
2596 //
2597 // ForExpression rhsVar = new ForExpression();
2598 // rhsVar.setVariableQName(new StructuredQName("vv", NamespaceConstant.SAXON_GENERATED_VARIABLE, "RHS" + rhsVar.hashCode()));
2599 // rhsVar.setSequence(new Atomizer(rhs));
2600 // rhsVar.setRequiredType(SequenceType.SINGLE_ATOMIC);
2601 //
2602 // Expression condition1 = new InstanceOfExpression(new LocalVariableReference(lhsVar), HashTrieMap.SINGLE_MAP_TYPE);
2603 // Expression condition2 = new InstanceOfExpression(new LocalVariableReference(lhsVar), ArrayItem.SINGLE_ARRAY_TYPE);
2604 // Expression condition3 = Literal.makeLiteral(BooleanValue.TRUE);
2605 // Expression action1 = makeMapGetFunction().makeFunctionCall(
2606 // new LocalVariableReference(lhsVar),
2607 // new LocalVariableReference(rhsVar)
2608 // );
2609 // Expression action2branch1 = makeArrayGetFunction().makeFunctionCall(
2610 // new LocalVariableReference(lhsVar),
2611 // new LocalVariableReference(rhsVar)
2612 // );
2613 // Expression action2branch2 = makeArrayGetFunction().makeFunctionCall(
2614 // new LocalVariableReference(lhsVar),
2615 // new LocalVariableReference(rhsVar)
2616 // );
2617 // Expression action2branch3 = new ErrorExpression(
2618 // "When the first argument of '?' is an array, the second argument must be an integer", "XPTY0004", true);
2619 // Expression action2 = new Choose(
2620 // new Expression[]{new InstanceOfExpression(new LocalVariableReference(rhsVar), SequenceType.SINGLE_INTEGER),
2621 // new InstanceOfExpression(new LocalVariableReference(rhsVar), SequenceType.SINGLE_UNTYPED_ATOMIC),
2622 // Literal.makeLiteral(BooleanValue.TRUE)},
2623 // new Expression[]{action2branch1, action2branch2, action2branch3});
2624 // Expression action3 = new ErrorExpression(
2625 // "First argument of '?' must be a sequence of arrays and/or maps", "XPTY0004", true);
2626 // Expression choice = new Choose(
2627 // new Expression[]{condition1, condition2, condition3},
2628 // new Expression[]{action1, action2, action3});
2629 // lhsVar.setAction(rhsVar);
2630 // rhsVar.setAction(choice);
2631 // return lhsVar;
2632 }
2633
2634 private static SystemFunction makeMapGetFunction() {
2635 try {
2636 return MapFunctionSet.getInstance().makeFunction("get", 2);
2637 } catch (XPathException e) {
2638 throw new AssertionError(e);
2639 }
2640 }
2641
2642 private static SystemFunction makeArrayGetFunction() {
2643 try {
2644 return ArrayFunctionSet.getInstance().makeFunction("get", 2);
2645 } catch (XPathException e) {
2646 throw new AssertionError(e);
2647 }
2648 }
2649
2650 private static SystemFunction makeMapKeysFunction() {
2651 try {
2652 return MapFunctionSet.getInstance().makeFunction("keys", 1);
2653 } catch (XPathException e) {
2654 throw new AssertionError(e);
2655 }
2656 }
2657
2658 private static SystemFunction makeArrayToSequenceFunction() {
2659 try {
2660 return ArrayFunctionSet.getInstance().makeFunction("_to-sequence", 1);
2661 } catch (XPathException e) {
2662 throw new AssertionError(e);
2663 }
2664 }
2665
2666 /**
2667 * Supporting code for lookup expressions (A?B) where B is an NCName
2668 *
2669 * @param lhs the LHS operand of the lookup expression
2670 * @param rhs the RHS operand of the lookup expression
2671 * @return the result of parsing the expression
2672 */
2673
2674 private Expression lookupName(Expression lhs, String rhs) {
2675 return new LookupExpression(lhs, new StringLiteral(rhs));
2676 // ForExpression lhsVar = new ForExpression();
2677 // lhsVar.setVariableQName(new StructuredQName("vv", NamespaceConstant.SAXON_GENERATED_VARIABLE, "LHS" + lhsVar.hashCode()));
2678 // lhsVar.setSequence(lhs);
2679 // lhsVar.setRequiredType(SequenceType.SINGLE_FUNCTION);
2680 // setLocation(lhs);
2681 //
2682 // Expression condition1 = new InstanceOfExpression(new LocalVariableReference(lhsVar), HashTrieMap.SINGLE_MAP_TYPE);
2683 // setLocation(condition1);
2684 // Expression condition3 = Literal.makeLiteral(BooleanValue.TRUE);
2685 // setLocation(condition3);
2686 // Expression action1 = makeMapGetFunction().makeFunctionCall(
2687 // new LocalVariableReference(lhsVar), new StringLiteral(rhs));
2688 // setLocation(condition3);
2689 // Expression action3 = new ErrorExpression("First argument of '?' must be a sequence of maps", "XPTY0004", true);
2690 // setLocation(action3);
2691 // Expression choice = new Choose(new Expression[]{condition1, condition3}, new Expression[]{action1, action3});
2692 // setLocation(choice);
2693 // lhsVar.setAction(choice);
2694 // return lhsVar;
2695 }
2696
2697 /**
2698 * Supporting code for lookup expressions (A?B) where B is the wildcard "*"
2699 *
2700 * @param lhs the LHS operand of the lookup expression
2701 * @return the result of parsing the expression
2702 */
2703
2704 private static Expression lookupStar(Expression lhs) {
2705 return new LookupAllExpression(lhs);
2706 // ForExpression lhsVar = new ForExpression();
2707 // lhsVar.setVariableQName(new StructuredQName("vv", NamespaceConstant.SAXON_GENERATED_VARIABLE, "LHS" + lhsVar.hashCode()));
2708 // lhsVar.setSequence(lhs);
2709 // lhsVar.setRequiredType(SequenceType.SINGLE_FUNCTION);
2710 //
2711 // Expression condition1 = new InstanceOfExpression(new LocalVariableReference(lhsVar), HashTrieMap.SINGLE_MAP_TYPE);
2712 // Expression condition2 = new InstanceOfExpression(new LocalVariableReference(lhsVar), ArrayItem.SINGLE_ARRAY_TYPE);
2713 // Expression condition3 = Literal.makeLiteral(BooleanValue.TRUE);
2714 //
2715 // ExpressionTool.copyLocationInfo(lhs, condition1);
2716 // ExpressionTool.copyLocationInfo(lhs, condition2);
2717 // ExpressionTool.copyLocationInfo(lhs, condition3);
2718 //
2719 // // for $k in map:keys($M) return map:get($M, $k)
2720 // ForExpression getMapValues = new ForExpression();
2721 // getMapValues.setVariableQName(new StructuredQName("vv", NamespaceConstant.SAXON_GENERATED_VARIABLE, "STAR" + getMapValues.hashCode()));
2722 // Expression mapKeys = makeMapKeysFunction().makeFunctionCall(new LocalVariableReference(lhsVar));
2723 // getMapValues.setSequence(mapKeys);
2724 // getMapValues.setRequiredType(SequenceType.SINGLE_ATOMIC);
2725 // Expression mapGet = makeMapGetFunction().makeFunctionCall(
2726 // new LocalVariableReference(lhsVar), new LocalVariableReference(getMapValues));
2727 // getMapValues.setAction(mapGet);
2728 //
2729 // Expression action2 = makeArrayToSequenceFunction().makeFunctionCall(
2730 // new LocalVariableReference(lhsVar));
2731 // Expression action3 = new ErrorExpression(
2732 // "First argument of '?' must be a sequence of arrays and/or maps", "XPTY0004", true);
2733 // Expression choice = new Choose(
2734 // new Expression[]{condition1, condition2, condition3}, new Expression[]{getMapValues, action2, action3});
2735 // lhsVar.setAction(choice);
2736 // return lhsVar;
2737 }
2738
2739
2740 /**
2741 * Parse a NodeTest.
2742 * One of QName, prefix:*, *:suffix, *, text(), node(), comment(), or
2743 * processing-instruction(literal?), or element(~,~), attribute(~,~), etc.
2744 *
2745 * @param nodeType the node type being sought if one is specified
2746 * @return the resulting NodeTest object
2747 * @throws XPathException if any error is encountered
2748 */
2749
2750 /*@NotNull*/
2751 protected NodeTest parseNodeTest(short nodeType) throws XPathException {
2752 int tok = t.currentToken;
2753 String tokv = t.currentTokenValue;
2754 switch (tok) {
2755 case Token.NAME:
2756 nextToken();
2757 return makeNameTest(nodeType, tokv, nodeType == Type.ELEMENT);
2758
2759 case Token.PREFIX:
2760 nextToken();
2761 return makeNamespaceTest(nodeType, tokv);
2762
2763 case Token.SUFFIX:
2764 nextToken();
2765 tokv = t.currentTokenValue;
2766 expect(Token.NAME);
2767 nextToken();
2768 return makeLocalNameTest(nodeType, tokv);
2769
2770 case Token.STAR:
2771 nextToken();
2772 return NodeKindTest.makeNodeKindTest(nodeType);
2773
2774 case Token.NODEKIND:
2775 return parseKindTest();
2776
2777 default:
2778 grumble("Unrecognized node test");
2779 throw new XPathException(""); // unreachable instruction
2780 }
2781 }
2782
2783 /**
2784 * Parse a KindTest
2785 *
2786 * @return the KindTest, expressed as a NodeTest object
2787 * @throws net.sf.saxon.trans.XPathException if a static error is found
2788 */
2789
2790 /*@NotNull*/
2791 private NodeTest parseKindTest() throws XPathException {
2792 NamePool pool = env.getConfiguration().getNamePool();
2793 String typeName = t.currentTokenValue;
2794 boolean schemaDeclaration = typeName.startsWith("schema-");
2795 int primaryType = getSystemType(typeName);
2796 int fp = -1;
2797 boolean empty = false;
2798 nextToken();
2799 if (t.currentToken == Token.RPAR) {
2800 if (schemaDeclaration) {
2801 grumble("schema-element() and schema-attribute() require a name to be supplied");
2802 return null;
2803 }
2804 empty = true;
2805 nextToken();
2806 }
2807 switch (primaryType) {
2808 case Type.ITEM:
2809 grumble("item() is not allowed in a path expression");
2810 return null;
2811 case Type.NODE:
2812 if (empty) {
2813 return AnyNodeTest.getInstance();
2814 } else {
2815 grumble("Expected ')': no arguments are allowed in node()");
2816 return null;
2817 }
2818 case Type.TEXT:
2819 if (empty) {
2820 return NodeKindTest.TEXT;
2821 } else {
2822 grumble("Expected ')': no arguments are allowed in text()");
2823 return null;
2824 }
2825 case Type.COMMENT:
2826 if (empty) {
2827 return NodeKindTest.COMMENT;
2828 } else {
2829 grumble("Expected ')': no arguments are allowed in comment()");
2830 return null;
2831 }
2832 case Type.NAMESPACE:
2833 if (empty) {
2834 if (!isNamespaceTestAllowed()) {
2835 grumble("namespace-node() test is not allowed in XPath 2.0/XQuery 1.0");
2836 }
2837 return NodeKindTest.NAMESPACE;
2838 } else {
2839 if (language == EXTENDED_ITEM_TYPE && t.currentToken == Token.NAME) {
2840 String nsName = t.currentTokenValue;
2841 nextToken();
2842 expect(Token.RPAR);
2843 nextToken();
2844 return new NameTest(Type.NAMESPACE, "", nsName, pool);
2845 } else {
2846 grumble("No arguments are allowed in namespace-node()");
2847 return null;
2848 }
2849 }
2850 case Type.DOCUMENT:
2851 if (empty) {
2852 return NodeKindTest.DOCUMENT;
2853 } else {
2854 int innerType;
2855 try {
2856 innerType = getSystemType(t.currentTokenValue);
2857 } catch (XPathException err) {
2858 innerType = Type.ITEM;
2859 }
2860 if (innerType != Type.ELEMENT) {
2861 grumble("Argument to document-node() must be an element type descriptor");
2862 return null;
2863 }
2864 NodeTest inner = parseKindTest();
2865 expect(Token.RPAR);
2866 nextToken();
2867 return new DocumentNodeTest(inner);
2868 }
2869 case Type.PROCESSING_INSTRUCTION:
2870 if (empty) {
2871 return NodeKindTest.PROCESSING_INSTRUCTION;
2872 } else if (t.currentToken == Token.STRING_LITERAL) {
2873 String piName = Whitespace.trim(unescape(t.currentTokenValue));
2874 if (!NameChecker.isValidNCName(piName)) {
2875 // Became an error as a result of XPath erratum XP.E7
2876 grumble("Processing instruction name must be a valid NCName", "XPTY0004");
2877 } else {
2878 fp = pool.allocateFingerprint("", piName);
2879 }
2880 } else if (t.currentToken == Token.NAME) {
2881 try {
2882 String[] parts = NameChecker.getQNameParts(t.currentTokenValue);
2883 if (parts[0].isEmpty()) {
2884 fp = pool.allocateFingerprint("", parts[1]);
2885 } else {
2886 grumble("Processing instruction name must not contain a colon");
2887 }
2888 } catch (QNameException e) {
2889 grumble("Invalid processing instruction name. " + e.getMessage());
2890 }
2891 } else {
2892 grumble("Processing instruction name must be a QName or a string literal");
2893 }
2894 nextToken();
2895 expect(Token.RPAR);
2896 nextToken();
2897 return new NameTest(Type.PROCESSING_INSTRUCTION, fp, pool);
2898
2899 case Type.ATTRIBUTE:
2900 // drop through
2901
2902 case Type.ELEMENT:
2903 String nodeName = "";
2904 if (empty) {
2905 return NodeKindTest.makeNodeKindTest(primaryType);
2906 } else if (t.currentToken == Token.STAR || t.currentToken == Token.MULT) {
2907 // allow for both representations of "*" to be safe
2908 if (schemaDeclaration) {
2909 grumble("schema-element() and schema-attribute() must specify an actual name, not '*'");
2910 return null;
2911 }
2912 fp = -1;
2913 } else if (t.currentToken == Token.NAME) {
2914 nodeName = t.currentTokenValue;
2915 fp = makeFingerprint(t.currentTokenValue, primaryType == Type.ELEMENT);
2916 } else {
2917 grumble("Unexpected " + Token.tokens[t.currentToken] + " after '(' in SequenceType");
2918 }
2919 String suri = null;
2920 if (fp != -1) {
2921 suri = pool.getURI(fp);
2922 }
2923 nextToken();
2924 if (t.currentToken == Token.RPAR) {
2925 nextToken();
2926 if (fp == -1) {
2927 // element(*) or attribute(*)
2928 return NodeKindTest.makeNodeKindTest(primaryType);
2929 } else {
2930 NodeTest nameTest;
2931 if (primaryType == Type.ATTRIBUTE) {
2932 // attribute(N) or schema-attribute(N)
2933 if (schemaDeclaration) {
2934 // schema-attribute(N)
2935 SchemaDeclaration attributeDecl =
2936 env.getConfiguration().getAttributeDeclaration(fp & 0xfffff);
2937 if (!env.isImportedSchema(suri)) {
2938 grumble("No schema has been imported for namespace '" + suri + '\'', "XPST0008");
2939 }
2940 if (attributeDecl == null) {
2941 grumble("There is no declaration for attribute @" + nodeName + " in an imported schema", "XPST0008");
2942 return null;
2943 } else {
2944 return attributeDecl.makeSchemaNodeTest();
2945 }
2946 } else {
2947 nameTest = new NameTest(Type.ATTRIBUTE, fp, pool);
2948 return nameTest;
2949 }
2950 } else {
2951 // element(N) or schema-element(N)
2952 if (schemaDeclaration) {
2953 // schema-element(N)
2954 if (!env.isImportedSchema(suri)) {
2955 grumble("No schema has been imported for namespace '" + suri + '\'', "XPST0008");
2956 }
2957 SchemaDeclaration elementDecl =
2958 env.getConfiguration().getElementDeclaration(fp & 0xfffff);
2959 if (elementDecl == null) {
2960 grumble("There is no declaration for element <" + nodeName + "> in an imported schema", "XPST0008");
2961 return null;
2962 } else {
2963 return elementDecl.makeSchemaNodeTest();
2964 }
2965 } else {
2966 nameTest = new NameTest(Type.ELEMENT, fp, pool);
2967 return nameTest;
2968 }
2969 }
2970 }
2971 } else if (t.currentToken == Token.COMMA) {
2972 if (schemaDeclaration) {
2973 grumble("schema-element() and schema-attribute() must have one argument only");
2974 return null;
2975 }
2976 nextToken();
2977 NodeTest result;
2978 if (t.currentToken == Token.STAR) {
2979 grumble("'*' is no longer permitted as the second argument of element() and attribute()");
2980 return null;
2981 } else if (t.currentToken == Token.NAME) {
2982 SchemaType schemaType;
2983 StructuredQName contentType = makeStructuredQName(t.currentTokenValue, env.getDefaultElementNamespace());
2984 assert contentType != null;
2985 String uri = contentType.getURI();
2986 String lname = contentType.getLocalPart();
2987
2988 if (uri.equals(NamespaceConstant.SCHEMA)) {
2989 schemaType = env.getConfiguration().getSchemaType(contentType);
2990 } else {
2991 if (!env.isImportedSchema(uri)) {
2992 grumble("No schema has been imported for namespace '" + uri + '\'', "XPST0008");
2993 }
2994 schemaType = env.getConfiguration().getSchemaType(contentType);
2995 }
2996 if (schemaType == null) {
2997 grumble("Unknown type name " + contentType.getEQName(), "XPST0008");
2998 return null;
2999 }
3000 if (primaryType == Type.ATTRIBUTE && schemaType.isComplexType()) {
3001 warning("An attribute cannot have a complex type");
3002 }
3003 ContentTypeTest typeTest = new ContentTypeTest(primaryType, schemaType, env.getConfiguration(), false);
3004 if (fp == -1) {
3005 // this represents element(*,T) or attribute(*,T)
3006 result = typeTest;
3007 if (primaryType == Type.ATTRIBUTE) {
3008 nextToken();
3009 } else {
3010 // assert (primaryType == Type.ELEMENT);
3011 nextToken();
3012 if (t.currentToken == Token.QMARK) {
3013 typeTest.setNillable(true);
3014 nextToken();
3015 }
3016 }
3017 } else {
3018 if (primaryType == Type.ATTRIBUTE) {
3019 NodeTest nameTest = new NameTest(Type.ATTRIBUTE, fp, pool);
3020 if (schemaType == AnyType.getInstance() || schemaType == AnySimpleType.getInstance()) {
3021 result = nameTest;
3022 } else {
3023 result = new CombinedNodeTest(nameTest, Token.INTERSECT, typeTest);
3024 }
3025 nextToken();
3026 } else {
3027 // assert (primaryType == Type.ELEMENT);
3028 NodeTest nameTest = new NameTest(Type.ELEMENT, fp, pool);
3029 // if (schemaType == AnyType.getInstance()) {
3030 // result = nameTest;
3031 // } else {
3032 result = new CombinedNodeTest(nameTest, Token.INTERSECT, typeTest);
3033 // }
3034 nextToken();
3035 if (t.currentToken == Token.QMARK) {
3036 typeTest.setNillable(true);
3037 nextToken();
3038 }
3039 }
3040 }
3041 } else {
3042 grumble("Unexpected " + Token.tokens[t.currentToken] + " after ',' in SequenceType");
3043 return null;
3044 }
3045
3046 expect(Token.RPAR);
3047 nextToken();
3048 return result;
3049 } else {
3050 grumble("Expected ')' or ',' in SequenceType");
3051 }
3052 return null;
3053 default:
3054 // can't happen!
3055 grumble("Unknown node kind");
3056 return null;
3057 }
3058 }
3059
3060 /**
3061 * Ask whether the syntax namespace-node() is allowed in a node kind test.
3062 *
3063 * @return true unless XPath 2.0 / XQuery 1.0 syntax is required
3064 */
3065
3066 protected boolean isNamespaceTestAllowed() {
3067 return allowXPath30Syntax;
3068 }
3069
3070 /**
3071 * Get a system type - that is, one whose name is a keyword rather than a QName. This includes the node
3072 * kinds such as element and attribute, and the generic types node() and item()
3073 *
3074 * @param name the name of the system type, for example "element" or "comment"
3075 * @return the integer constant denoting the type, for example {@link Type#ITEM} or {@link Type#ELEMENT}
3076 * @throws XPathException if the name is not recognized
3077 */
3078 private int getSystemType(String name) throws XPathException {
3079 if ("item".equals(name)) {
3080 return Type.ITEM;
3081 } else if ("document-node".equals(name)) {
3082 return Type.DOCUMENT;
3083 } else if ("element".equals(name)) {
3084 return Type.ELEMENT;
3085 } else if ("schema-element".equals(name)) {
3086 return Type.ELEMENT;
3087 } else if ("attribute".equals(name)) {
3088 return Type.ATTRIBUTE;
3089 } else if ("schema-attribute".equals(name)) {
3090 return Type.ATTRIBUTE;
3091 } else if ("text".equals(name)) {
3092 return Type.TEXT;
3093 } else if ("comment".equals(name)) {
3094 return Type.COMMENT;
3095 } else if ("processing-instruction".equals(name)) {
3096 return Type.PROCESSING_INSTRUCTION;
3097 } else if ("namespace-node".equals(name)) {
3098 return Type.NAMESPACE;
3099 } else if ("node".equals(name)) {
3100 return Type.NODE;
3101 } else {
3102 grumble("Unknown type " + name);
3103 return -1;
3104 }
3105 }
3106
3107 /**
3108 * Check that XPath 3.0 is in use
3109 *
3110 * @throws net.sf.saxon.trans.XPathException if XPath 3.0 support was not requested
3111 */
3112
3113 protected void checkLanguageVersion30() throws XPathException {
3114 if (!allowXPath30Syntax) {
3115 grumble("To use XPath 3.0 syntax, you must configure the XPath parser to handle it");
3116 }
3117 }
3118
3119 /**
3120 * Check that XPath 3.1 is in use
3121 *
3122 * @throws net.sf.saxon.trans.XPathException if XPath 3.1 support was not requested
3123 */
3124
3125 protected void checkLanguageVersion31() throws XPathException {
3126 if (!allowXPath31Syntax) {
3127 grumble("The XPath parser is not configured to allow use of XPath 3.1 syntax");
3128 }
3129 }
3130
3131 /**
3132 * Check that the map syntax is enabled: this covers the extensions to XPath 3.0
3133 * syntax defined in XSLT 3.0 (and also, of course, in XPath 3.1)
3134 *
3135 * @throws net.sf.saxon.trans.XPathException if XPath 3.1 support was not requested
3136 */
3137
3138 protected void checkMapExtensions() throws XPathException {
3139 if (!(allowXPath31Syntax || allowXPath30XSLTExtensions)) {
3140 grumble("The XPath parser is not configured to allow use of the map syntax from XSLT 3.0 or XPath 3.1");
3141 }
3142 }
3143
3144 /**
3145 * Check that Saxon syntax extensions are permitted
3146 * @throws XPathException if Saxon syntax extensions have not been enabled
3147 */
3148
3149 public void checkSyntaxExtensions(String construct) throws XPathException {
3150 if (!allowSaxonExtensions) {
3151 grumble("Saxon XPath syntax extensions have not been enabled: " + construct + " is not allowed");
3152 }
3153 }
3154
3155 /**
3156 * Parse a map expression. Requires XPath/XQuery 3.0
3157 * Provisional syntax
3158 * map { expr : expr (, expr : expr )*} }
3159 *
3160 * @return the map expression
3161 * @throws XPathException if parsing fails
3162 */
3163
3164 /*@NotNull*/
3165 protected Expression parseMapExpression() throws XPathException {
3166 checkMapExtensions();
3167
3168 // have read the "map {"
3169 Tokenizer t = getTokenizer();
3170 int offset = t.currentTokenStartOffset;
3171 List<Expression> entries = new ArrayList<>();
3172 nextToken();
3173 if (t.currentToken != Token.RCURLY) {
3174 while (true) {
3175 Expression key = parseExprSingle();
3176 if (t.currentToken == Token.ASSIGN) {
3177 grumble("The ':=' notation is no longer accepted in map expressions: use ':' instead");
3178 }
3179 expect(Token.COLON);
3180 nextToken();
3181 Expression value = parseExprSingle();
3182 Expression entry;
3183 if (key instanceof Literal && ((Literal)key).getValue() instanceof AtomicValue
3184 && value instanceof Literal) {
3185 entry = Literal.makeLiteral(
3186 new SingleEntryMap((AtomicValue) ((Literal)key).getValue(),
3187 ((Literal)value).getValue()));
3188 } else {
3189 entry = MapFunctionSet.getInstance().makeFunction("entry", 2).makeFunctionCall(key, value);
3190 }
3191 entries.add(entry);
3192 if (t.currentToken == Token.RCURLY) {
3193 break;
3194 } else {
3195 expect(Token.COMMA);
3196 nextToken();
3197 }
3198 }
3199 }
3200 t.lookAhead(); //manual lookahead after an RCURLY
3201 nextToken();
3202
3203 Expression result;
3204 switch (entries.size()) {
3205 case 0:
3206 result = Literal.makeLiteral(new HashTrieMap());
3207 break;
3208 case 1:
3209 result = entries.get(0);
3210 break;
3211 default:
3212 Expression[] entriesArray = new Expression[entries.size()];
3213 Block block = new Block(entries.toArray(entriesArray));
3214 DictionaryMap options = new DictionaryMap();
3215 options.initialPut("duplicates", new StringValue("reject"));
3216 options.initialPut("duplicates-error-code", new StringValue("XQDY0137"));
3217 result = MapFunctionSet.getInstance().makeFunction("merge", 2).makeFunctionCall(block, Literal.makeLiteral(options));
3218 break;
3219 }
3220 setLocation(result, offset);
3221 return result;
3222
3223 }
3224
3225 /**
3226 * Parse a "square" array constructor
3227 * "[" (exprSingle ("," exprSingle)* )? "]"
3228 * Applies to XPath/XQuery 3.1 only
3229 */
3230 protected Expression parseArraySquareConstructor() throws XPathException {
3231 checkLanguageVersion31();
3232 Tokenizer t = getTokenizer();
3233 int offset = t.currentTokenStartOffset;
3234 List<Expression> members = new ArrayList<>();
3235 nextToken();
3236 if (t.currentToken == Token.RSQB) {
3237 nextToken();
3238 SquareArrayConstructor block = new SquareArrayConstructor(members);
3239 setLocation(block, offset);
3240 return block;
3241 }
3242 while (true) {
3243 Expression member = parseExprSingle();
3244 members.add(member);
3245 if (t.currentToken == Token.COMMA) {
3246 nextToken();
3247 continue;
3248 } else if (t.currentToken == Token.RSQB) {
3249 nextToken();
3250 break;
3251 }
3252 grumble("Expected ',' or ']', " +
3253 "found " + Token.tokens[t.currentToken]);
3254 return new ErrorExpression();
3255 }
3256 SquareArrayConstructor block = new SquareArrayConstructor(members);
3257 setLocation(block, offset);
3258 return block;
3259 }
3260
3261 /**
3262 * Parse a "curly" array constructor
3263 * array "{" expr "}"
3264 * Applies to XPath/XQuery 3.1 only
3265 *
3266 * @return the parsed expression
3267 * @throws XPathException if the syntax is invalid or the construct is not permitted
3268 */
3269
3270 protected Expression parseArrayCurlyConstructor() throws XPathException {
3271 checkLanguageVersion31();
3272 Tokenizer t = getTokenizer();
3273 int offset = t.currentTokenStartOffset;
3274 nextToken();
3275 if (t.currentToken == Token.RCURLY) {
3276 t.lookAhead(); //manual lookahead after an RCURLY
3277 nextToken();
3278 return Literal.makeLiteral(SimpleArrayItem.EMPTY_ARRAY);
3279 }
3280 Expression body = parseExpression();
3281 expect(Token.RCURLY);
3282 t.lookAhead(); //manual lookahead after an RCURLY
3283 nextToken();
3284
3285 SystemFunction sf = ArrayFunctionSet.getInstance().makeFunction("_from-sequence", 1);
3286 Expression result = sf.makeFunctionCall(body);
3287 //
3288 // ArrayFromSequence defn = new ArrArrayFromSequence();
3289 // Expression result = IntegratedFunctionLibrary.makeFunctionCall(defn, new Expression[]{body});
3290 setLocation(result, offset);
3291 return result;
3292 }
3293
3294 /**
3295 * Parse a function call.
3296 * function-name '(' ( Expression (',' Expression )* )? ')'
3297 *
3298 * @param prefixArgument left hand operand of arrow operator,
3299 * or null in the case of a conventional function call
3300 * @return the resulting subexpression
3301 * @throws XPathException if any error is encountered
3302 */
3303
3304 /*@NotNull*/
3305 public Expression parseFunctionCall(Expression prefixArgument) throws XPathException {
3306
3307 String fname = t.currentTokenValue;
3308 int offset = t.currentTokenStartOffset;
3309 ArrayList<Expression> args = new ArrayList<>(10);
3310 if (prefixArgument != null) {
3311 args.add(prefixArgument);
3312 }
3313
3314 StructuredQName functionName = resolveFunctionName(fname);
3315 IntSet placeMarkers = null;
3316
3317 // the "(" has already been read by the Tokenizer: now parse the arguments
3318
3319 nextToken();
3320 if (t.currentToken != Token.RPAR) {
3321 while (true) {
3322 Expression arg = parseFunctionArgument();
3323 if (arg == null) {
3324 // this is a "?" placemarker
3325 if (placeMarkers == null) {
3326 placeMarkers = new IntArraySet();
3327 }
3328 placeMarkers.add(args.size());
3329 arg = Literal.makeEmptySequence(); // a convenient fiction
3330 }
3331 args.add(arg);
3332 if (t.currentToken == Token.COMMA) {
3333 nextToken();
3334 } else {
3335 break;
3336 }
3337 }
3338 expect(Token.RPAR);
3339 }
3340 nextToken();
3341
3342 if (scanOnly) {
3343 return new StringLiteral(StringValue.EMPTY_STRING);
3344 }
3345
3346 Expression[] arguments = new Expression[args.size()];
3347 args.toArray(arguments);
3348
3349 if (placeMarkers != null) {
3350 return parserExtension.makeCurriedFunction(this, offset, functionName, arguments, placeMarkers);
3351 }
3352
3353 Expression fcall;
3354 SymbolicName.F sn = new SymbolicName.F(functionName, args.size());
3355 List<String> reasons = new ArrayList<>();
3356 fcall = env.getFunctionLibrary().bind(sn, arguments, env, reasons);
3357 if (fcall == null) {
3358 return reportMissingFunction(offset, functionName, arguments, reasons);
3359 }
3360 // A QName or NOTATION constructor function must be given the namespace context now
3361 // if (fcall instanceof CastExpression &&
3362 // ((AtomicType) fcall.getItemType()).isNamespaceSensitive()) {
3363 // ((CastExpression) fcall).bindStaticContext(env);
3364 // }
3365 // There are special rules for certain functions appearing in a pattern
3366 if (language == XSLT_PATTERN) {
3367 if (fcall.isCallOn(RegexGroup.class)) {
3368 return Literal.makeEmptySequence();
3369 } else if (fcall instanceof CurrentGroupCall) {
3370 grumble("The current-group() function cannot be used in a pattern",
3371 "XTSE1060", offset);
3372 return new ErrorExpression();
3373 } else if (fcall instanceof CurrentGroupingKeyCall) {
3374 grumble("The current-grouping-key() function cannot be used in a pattern",
3375 "XTSE1070", offset);
3376 return new ErrorExpression();
3377 } else if (fcall.isCallOn(CurrentMergeGroup.class)) {
3378 grumble("The current-merge-group() function cannot be used in a pattern",
3379 "XTSE3470", offset);
3380 return new ErrorExpression();
3381 } else if (fcall.isCallOn(CurrentMergeKey.class)) {
3382 grumble("The current-merge-key() function cannot be used in a pattern",
3383 "XTSE3500", offset);
3384 return new ErrorExpression();
3385 }
3386 }
3387 setLocation(fcall, offset);
3388 for (Expression argument : arguments) {
3389 if (fcall != argument && !functionName.hasURI(NamespaceConstant.GLOBAL_JS)) {
3390 // avoid doing this when the function has already been optimized away, e.g. unordered()
3391 // Also avoid doing this when a js: function is parsed into an ixsl:call()
3392 // TODO move the adoptChildExpression into individual function libraries
3393 fcall.adoptChildExpression(argument);
3394 }
3395 }
3396
3397 return makeTracer(offset, fcall, LocationKind.FUNCTION_CALL, functionName);
3398
3399 }
3400
3401 /*@NotNull*/
3402 public Expression reportMissingFunction(int offset, StructuredQName functionName, Expression[] arguments, List<String> reasons) throws XPathException {
3403 StringBuilder sb = new StringBuilder();
3404 sb.append("Cannot find a ").append(arguments.length).append(
3405 "-argument function named ").append(functionName.getEQName()).append("()");
3406 Configuration config = env.getConfiguration();
3407 for (String reason : reasons) {
3408 sb.append(". ").append(reason);
3409 }
3410 if (config.getBooleanProperty(Feature.ALLOW_EXTERNAL_FUNCTIONS)) {
3411 boolean existsWithDifferentArity = false;
3412 for (int i = 0; i < arguments.length + 5; i++) {
3413 if (i != arguments.length) {
3414 SymbolicName.F sn = new SymbolicName.F(functionName, i);
3415 if (env.getFunctionLibrary().isAvailable(sn)) {
3416 existsWithDifferentArity = true;
3417 break;
3418 }
3419 }
3420 }
3421 if (existsWithDifferentArity) {
3422 sb.append(". The namespace URI and local name are recognized, but the number of arguments is wrong");
3423 } else {
3424 String supplementary = getMissingFunctionExplanation(functionName, config);
3425 if (supplementary != null) {
3426 sb.append(". ").append(supplementary);
3427 }
3428 }
3429 } else {
3430 sb.append(". External function calls have been disabled");
3431 }
3432 if (env.isInBackwardsCompatibleMode()) {
3433 // treat this as a dynamic error to be reported only if the function call is executed
3434 return new ErrorExpression(sb.toString(), "XTDE1425", false);
3435 } else {
3436 grumble(sb.toString(), "XPST0017", offset);
3437 return null;
3438 }
3439 }
3440
3441 /**
3442 * Get a message containing suggestions as to why a requested function might not be available
3443 * @param functionName the name of the required function
3444 * @param config the Saxon configuration
3445 * @return a suggestion as to why the function was not found; or null if no suggestions can be offered.
3446 */
3447
3448 public static String getMissingFunctionExplanation(StructuredQName functionName, Configuration config) {
3449 String actualURI = functionName.getURI();
3450 String similarNamespace = NamespaceConstant.findSimilarNamespace(actualURI);
3451 if (similarNamespace != null) {
3452 if (similarNamespace.equals(actualURI)) {
3453 switch (similarNamespace) {
3454 case NamespaceConstant.FN:
3455 String[] hof = new String[]{"apply", "filter", "fold-left", "fold-right",
3456 "for-each", "for-each-pair", "function-arity", "function-lookup", "function-name",
3457 "load-xquery-module", "random-number-generator"};
3458 if (Arrays.binarySearch(hof, functionName.getLocalPart()) >= 0) {
3459 return "Higher-order functions are not available in this Configuration";
3460 }
3461 return null;
3462 case NamespaceConstant.SAXON:
3463 if (config.getEditionCode().equals("HE")) {
3464 return "Saxon extension functions are not available under Saxon-HE";
3465 } else if (!config.isLicensedFeature(Configuration.LicenseFeature.PROFESSIONAL_EDITION)) {
3466 return "Saxon extension functions require a Saxon-PE or Saxon-EE license";
3467 }
3468 break;
3469 case NamespaceConstant.XSLT:
3470 if (functionName.getLocalPart().equals("original")) {
3471 return "Function name xsl:original is only available within an overriding function";
3472 } else {
3473 return "There are no functions defined in the XSLT namespace";
3474 }
3475 }
3476 } else {
3477 return "Perhaps the intended namespace was '" + similarNamespace + "'";
3478 }
3479 } else if (actualURI.contains("java")) {
3480 if (config.getEditionCode().equals("HE")) {
3481 return "Reflexive calls to Java methods are not available under Saxon-HE";
3482 } else if (!config.isLicensedFeature(Configuration.LicenseFeature.PROFESSIONAL_EDITION)) {
3483 return "Reflexive calls to Java methods require a Saxon-PE or Saxon-EE license, and none was found";
3484 } else {
3485 return "For diagnostics on calls to Java methods, use the -TJ command line option " +
3486 "or set the Configuration property FeatureKeys.TRACE_EXTERNAL_FUNCTIONS";
3487 }
3488 } else if (actualURI.startsWith("clitype:")) {
3489 if (config.getEditionCode().equals("HE")) {
3490 return "Reflexive calls to external .NET methods are not available under Saxon-HE";
3491 } else if (!config.isLicensedFeature(Configuration.LicenseFeature.PROFESSIONAL_EDITION)) {
3492 return "Reflexive calls to external .NET methods require a Saxon-PE or Saxon-EE license, and none was found";
3493 } else {
3494 return "For diagnostics on calls to .NET methods, use the -TJ command line option " +
3495 "or call processor.SetProperty(\"http://saxon.sf.net/feature/trace-external-functions\", \"true\")";
3496 }
3497 }
3498 return null;
3499 }
3500
3501 /**
3502 * Interpret a function name, returning it as a resolved QName
3503 *
3504 * @param fname the lexical QName used as the function name; or an EQName presented
3505 * by the tokenizer as a name in Clark notation
3506 * @return the Structured QName obtained by resolving any prefix in the function name
3507 * @throws XPathException if the supplied name is not a valid QName or if its prefix
3508 * is not in scope
3509 */
3510
3511 /*@NotNull*/
3512 protected StructuredQName resolveFunctionName(String fname) throws XPathException {
3513 if (scanOnly) {
3514 return new StructuredQName("", NamespaceConstant.SAXON, "dummy");
3515 }
3516 StructuredQName functionName = null;
3517 qNameParser.setDefaultNamespace(env.getDefaultFunctionNamespace());
3518 try {
3519 functionName = qNameParser.parse(fname);
3520 } catch (XPathException e) {
3521 grumble(e.getMessage(), e.getErrorCodeLocalPart());
3522 assert false;
3523 }
3524
3525 if (functionName.hasURI(NamespaceConstant.SCHEMA)) {
3526 ItemType t = Type.getBuiltInItemType(functionName.getURI(), functionName.getLocalPart());
3527 if (t instanceof BuiltInAtomicType) {
3528 checkAllowedType(env, (BuiltInAtomicType) t);
3529 }
3530 }
3531 return functionName;
3532 }
3533
3534 /**
3535 * Parse an argument to a function call. Separate method so it can
3536 * be overridden. With higher-order-function syntax in XPath 3.0/XQuery 3.0,
3537 * this returns null if the pseudo-argument "?" is found.
3538 *
3539 * @return the Expression used as the argument, or null if the argument is the place-holder "?"
3540 * @throws XPathException if the argument expression does not parse correctly
3541 */
3542
3543 /*@Nullable*/
3544 public Expression parseFunctionArgument() throws XPathException {
3545 if (t.currentToken == Token.QMARK) {
3546 int next = t.peekAhead();
3547 if (next == Token.COMMA || next == Token.RPAR) {
3548 nextToken();
3549 return parserExtension.makeArgumentPlaceMarker(this);
3550 }
3551 }
3552 return parseExprSingle();
3553 }
3554
3555 /**
3556 * Parse a literal function item (introduced in XQuery 1.1)
3557 * Syntax: QName # integer
3558 * The QName and # have already been read
3559 *
3560 * @return an ExternalObject representing the function item
3561 * @throws net.sf.saxon.trans.XPathException if a static error is encountered
3562 */
3563
3564 /*@NotNull*/
3565 protected Expression parseNamedFunctionReference() throws XPathException {
3566 return parserExtension.parseNamedFunctionReference(this);
3567 }
3568
3569 /**
3570 * Parse the annotations that can appear in a variable or function declaration
3571 *
3572 * @return the annotations as a list
3573 * @throws XPathException in the event of a syntax error
3574 */
3575
3576 protected AnnotationList parseAnnotationsList() throws XPathException {
3577 grumble("Inline functions are not allowed in Saxon-HE");
3578 return null;
3579 }
3580
3581 /**
3582 * Parse an inline function
3583 * "function" "(" ParamList? ")" ("as" SequenceType)? EnclosedExpr
3584 * On entry, "function (" has already been read
3585 *
3586 * @param annotations the function annotations, which have already been read, or null if there are none
3587 * @return the parsed inline function
3588 * @throws XPathException if a syntax error is found
3589 */
3590
3591 /*@NotNull*/
3592 protected Expression parseInlineFunction(AnnotationList annotations) throws XPathException {
3593 return parserExtension.parseInlineFunction(this, annotations);
3594 }
3595
3596 /**
3597 * Process a function call in which one or more of the argument positions are
3598 * represented as "?" placemarkers (indicating partial application or currying)
3599 *
3600 * @param offset the position of the expression in the source text
3601 * @param name the function name (as if there were no currying)
3602 * @param args the arguments (with EmptySequence in the placemarker positions)
3603 * @param placeMarkers the positions of the placemarkers @return the curried function
3604 * @return the curried function
3605 * @throws XPathException if a static error is found
3606 */
3607
3608 /*@NotNull*/
3609 protected Expression makeCurriedFunction(
3610 int offset, StructuredQName name, Expression[] args, IntSet placeMarkers)
3611 throws XPathException {
3612 grumble("Partial function application is not allowed in Saxon-HE");
3613 return new ErrorExpression();
3614 }
3615
3616 /* Must be in alphabetical order, since a binary search is used */
3617
3618 private final static String[] reservedFunctionNames30 = new String[]{
3619 "attribute", "comment", "document-node", "element", "empty-sequence", "function", "if", "item",
3620 "namespace-node", "node", "processing-instruction", "schema-attribute", "schema-element", "switch", "text", "typeswitch"
3621 };
3622
3623 /**
3624 * Check whether a function name is reserved in XPath 3.0 (when unprefixed)
3625 *
3626 * @param name the function name (the local-name as a string)
3627 * @return true if the function name is reserved
3628 */
3629
3630 protected static boolean isReservedFunctionName30(String name) {
3631 int x = Arrays.binarySearch(reservedFunctionNames30, name);
3632 return x >= 0;
3633 }
3634
3635 /* Must be in alphabetical order, since a binary search is used */
3636
3637 private final static String[] reservedFunctionNames31 = new String[]{
3638 "array", "attribute", "comment", "document-node", "element", "empty-sequence", "function", "if", "item", "map",
3639 "namespace-node", "node", "processing-instruction", "schema-attribute", "schema-element", "switch", "text", "typeswitch"
3640 };
3641
3642 /**
3643 * Check whether a function name is reserved in XPath 3.1 (when unprefixed)
3644 *
3645 * @param name the function name (the local-name as a string)
3646 * @return true if the function name is reserved
3647 */
3648
3649 public static boolean isReservedFunctionName31(String name) {
3650 int x = Arrays.binarySearch(reservedFunctionNames31, name);
3651 return x >= 0;
3652 }
3653
3654
3655 //////////////////////////////////////////////////////////////////////////////////
3656 // Routines for handling range variables
3657 //////////////////////////////////////////////////////////////////////////////////
3658
3659 /**
3660 * Get the stack of in-scope range variables
3661 *
3662 * @return the stack of variables
3663 */
3664
3665 public Stack<LocalBinding> getRangeVariables() {
3666 return rangeVariables;
3667 }
3668
3669 /**
3670 * Set a new stack of in-scope range variables
3671 *
3672 * @param variables the stack of variables
3673 */
3674
3675 public void setRangeVariables(Stack<LocalBinding> variables) {
3676 this.rangeVariables = variables;
3677 }
3678
3679 /**
3680 * Declare a range variable (record its existence within the parser).
3681 * A range variable is a variable declared within an expression, as distinct
3682 * from a variable declared in the context.
3683 *
3684 * @param declaration the variable declaration to be added to the stack
3685 */
3686
3687 public void declareRangeVariable(LocalBinding declaration) {
3688 rangeVariables.push(declaration);
3689 }
3690
3691 /**
3692 * Note when the most recently declared range variable has gone out of scope
3693 */
3694
3695 public void undeclareRangeVariable() {
3696 rangeVariables.pop();
3697 }
3698
3699 /**
3700 * Locate a range variable with a given name. (By "range variable", we mean a
3701 * variable declared within the expression where it is used.)
3702 *
3703 * @param qName identifies the name of the range variable
3704 * @return null if not found (this means the variable is probably a
3705 * context variable); otherwise the relevant RangeVariable
3706 */
3707
3708 /*@Nullable*/
3709 protected LocalBinding findRangeVariable(StructuredQName qName) {
3710 for (int v = rangeVariables.size() - 1; v >= 0; v--) {
3711 LocalBinding b = rangeVariables.elementAt(v);
3712 if (b.getVariableQName().equals(qName)) {
3713 return b;
3714 }
3715 }
3716 return parserExtension.findOuterRangeVariable(this, qName);
3717 }
3718
3719 /**
3720 * Set the range variable stack. Used when parsing a nested subexpression
3721 * inside an attribute constructor.
3722 *
3723 * @param stack the stack to be used for local variables declared within the expression
3724 */
3725
3726 public void setRangeVariableStack(Stack<LocalBinding> stack) {
3727 rangeVariables = stack;
3728 }
3729
3730 /**
3731 * Make a NameCode, using the static context for namespace resolution
3732 *
3733 * @param qname The name as written, in the form "[prefix:]localname"; alternatively,
3734 * a QName in Clark notation ({uri}local)
3735 * @param useDefault Defines the action when there is no prefix. If
3736 * true, use the default namespace URI for element names. If false,
3737 * use no namespace URI (as for attribute names).
3738 * @return the fingerprint, which can be used to identify this name in the
3739 * name pool
3740 * @throws XPathException if the name is invalid, or the prefix
3741 * undeclared
3742 */
3743
3744 public final int makeFingerprint(/*@NotNull*/ String qname, boolean useDefault) throws XPathException {
3745 if (scanOnly) {
3746 return StandardNames.XML_SPACE;
3747 }
3748 try {
3749 qNameParser.setDefaultNamespace(useDefault ? env.getDefaultElementNamespace() : "");
3750 StructuredQName sq = qNameParser.parse(qname);
3751 return env.getConfiguration().getNamePool().allocateFingerprint(sq.getURI(), sq.getLocalPart());
3752 } catch (XPathException e) {
3753 grumble(e.getMessage(), e.getErrorCodeLocalPart());
3754 return -1;
3755 }
3756 }
3757
3758 /**
3759 * Make a NameCode, using the static context for namespace resolution.
3760 * This variant of the method does not call "grumble" to report any errors
3761 * to the ErrorListener, it only reports errors by throwing exceptions. This
3762 * allows the caller to control the message output.
3763 *
3764 * @param qname The name as written, in the form "[prefix:]localname"
3765 * @param defaultUri Defines the URI to be returned if there is no prefix.
3766 * @return the structured QName
3767 * @throws XPathException if the name is invalid, or the prefix
3768 * undeclared or if the name is not a lexically valid QName
3769 */
3770
3771 public final StructuredQName makeStructuredQNameSilently(/*@NotNull*/ String qname, String defaultUri)
3772 throws XPathException {
3773 if (scanOnly) {
3774 return new StructuredQName("", NamespaceConstant.SAXON, "dummy");
3775 }
3776 qNameParser.setDefaultNamespace(defaultUri);
3777 return qNameParser.parse(qname);
3778 }
3779
3780 /**
3781 * Make a Structured QName, using the static context for namespace resolution
3782 *
3783 * @param qname The name as written, in the form "[prefix:]localname"; alternatively, a QName in
3784 * Clark format ({uri}local)
3785 * @param defaultUri The URI to be used if the name is written as a localname with no prefix
3786 * @return the QName as an instance of StructuredQName
3787 * @throws XPathException if the name is invalid, or the prefix
3788 * undeclared
3789 */
3790
3791 /*@NotNull*/
3792 public final StructuredQName makeStructuredQName(/*@NotNull*/ String qname, String defaultUri) throws XPathException {
3793 try {
3794 return makeStructuredQNameSilently(qname, defaultUri);
3795 } catch (XPathException err) {
3796 grumble(err.getMessage(), err.getErrorCodeLocalPart());
3797 return new StructuredQName("", "", "error"); // Not executed; here to keep the compiler happy
3798 }
3799 }
3800
3801 /**
3802 * Make a FingerprintedQName, using the static context for namespace resolution
3803 *
3804 * @param qname The name as written, in the form "[prefix:]localname"; alternatively, a QName in
3805 * Clark format ({uri}local)
3806 * @param useDefault Defines the action when there is no prefix. If
3807 * true, use the default namespace URI for element names. If false,
3808 * use no namespace URI (as for attribute names).
3809 * @return the fingerprinted QName
3810 * @throws XPathException if the name is invalid, or the prefix
3811 * undeclared
3812 */
3813
3814 /*@NotNull*/
3815 public final NodeName makeNodeName(String qname, boolean useDefault) throws XPathException {
3816 StructuredQName sq = makeStructuredQNameSilently(qname, useDefault ? env.getDefaultElementNamespace() : "");
3817 String prefix = sq.getPrefix();
3818 String uri = sq.getURI();
3819 String local = sq.getLocalPart();
3820 if (uri.isEmpty()) {
3821 int fp = env.getConfiguration().getNamePool().allocateFingerprint("", qname);
3822 return new NoNamespaceName(qname, fp);
3823 } else {
3824 int fp = env.getConfiguration().getNamePool().allocateFingerprint(uri, local);
3825 return new FingerprintedQName(prefix, uri, local, fp);
3826 }
3827 }
3828
3829
3830 /**
3831 * Make a NameTest, using the static context for namespace resolution
3832 *
3833 * @param nodeType the type of node required (identified by a constant in
3834 * class Type)
3835 * @param qname the lexical QName of the required node; alternatively,
3836 * a QName in Clark notation ({uri}local)
3837 * @param useDefault true if the default namespace should be used when
3838 * the QName is unprefixed
3839 * @return a NameTest, representing a pattern that tests for a node of a
3840 * given node kind and a given name
3841 * @throws XPathException if the QName is invalid
3842 */
3843
3844 /*@NotNull*/
3845 public NameTest makeNameTest(short nodeType, /*@NotNull*/ String qname, boolean useDefault)
3846 throws XPathException {
3847 NamePool pool = env.getConfiguration().getNamePool();
3848 StructuredQName q = makeStructuredQName(qname, useDefault ? env.getDefaultElementNamespace() : "");
3849 assert q != null;
3850 int fp = pool.allocateFingerprint(q.getURI(), q.getLocalPart());
3851 return new NameTest(nodeType, fp, pool);
3852 }
3853
3854 /**
3855 * Make a NamespaceTest (name:*)
3856 *
3857 * @param nodeType integer code identifying the type of node required
3858 * @param prefix the namespace prefix
3859 * @return the NamespaceTest, a pattern that matches all nodes in this
3860 * namespace
3861 * @throws XPathException if the namespace prefix is not declared
3862 */
3863
3864 /*@NotNull*/
3865 public NamespaceTest makeNamespaceTest(short nodeType, String prefix)
3866 throws XPathException {
3867 NamePool pool = env.getConfiguration().getNamePool();
3868 if (scanOnly) {
3869 // return an arbitrary namespace if we're only doing a syntax check
3870 return new NamespaceTest(pool, nodeType, NamespaceConstant.SAXON);
3871 }
3872 if (prefix.startsWith("Q{")) {
3873 String uri = prefix.substring(2, prefix.length() - 2);
3874 return new NamespaceTest(pool, nodeType, uri);
3875 }
3876 try {
3877 StructuredQName sq = qNameParser.parse(prefix + ":dummy");
3878 return new NamespaceTest(pool, nodeType, sq.getURI());
3879 } catch (XPathException err) {
3880 grumble(err.getMessage(), err.getErrorCodeLocalPart());
3881 return null;
3882 }
3883 }
3884
3885 /**
3886 * Make a LocalNameTest (*:name)
3887 *
3888 * @param nodeType the kind of node to be matched
3889 * @param localName the requred local name
3890 * @return a LocalNameTest, a pattern which matches all nodes of a given
3891 * local name, regardless of namespace
3892 * @throws XPathException if the local name is invalid
3893 */
3894
3895 /*@NotNull*/
3896 public LocalNameTest makeLocalNameTest(short nodeType, String localName)
3897 throws XPathException {
3898 if (!NameChecker.isValidNCName(localName)) {
3899 grumble("Local name [" + localName + "] contains invalid characters");
3900 }
3901 return new LocalNameTest(env.getConfiguration().getNamePool(), nodeType, localName);
3902 }
3903
3904 /**
3905 * Set location information on an expression. At present this consists of a simple
3906 * line number. Needed mainly for XQuery.
3907 *
3908 * @param exp the expression whose location information is to be set
3909 */
3910
3911 protected void setLocation(/*@NotNull*/ Expression exp) {
3912 setLocation(exp, t.currentTokenStartOffset);
3913 }
3914
3915 /**
3916 * Set location information on an expression. At present only the line number
3917 * is retained. Needed mainly for XQuery. This version of the method supplies an
3918 * explicit offset (character position within the expression or query), which the tokenizer
3919 * can convert to a line number and column number.
3920 *
3921 * @param exp the expression whose location information is to be set
3922 * @param offset the character position within the expression (ignoring newlines)
3923 */
3924
3925 public void setLocation(Expression exp, int offset) {
3926 if (exp != null) {
3927 int line = t.getLineNumber(offset);
3928 int column = t.getColumnNumber(offset);
3929 if (exp.getLocation() == null || exp.getLocation() == ExplicitLocation.UNKNOWN_LOCATION) {
3930 Location loc = makeNestedLocation(env.getContainingLocation(), line, column, null);
3931 exp.setLocation(loc);
3932 }
3933 }
3934 }
3935
3936 /**
3937 * Set location information on a clause of a FLWOR expression. This version of the method supplies an
3938 * explicit offset (character position within the expression or query), which the tokenizer
3939 * can convert to a line number and column number.
3940 *
3941 * @param clause the clause whose location information is to be set
3942 * @param offset the character position within the expression (ignoring newlines)
3943 */
3944
3945 public void setLocation(Clause clause, int offset) {
3946 int line = t.getLineNumber(offset);
3947 int column = t.getColumnNumber(offset);
3948 Location loc = makeNestedLocation(env.getContainingLocation(), line, column, null);
3949 clause.setLocation(loc);
3950 clause.setPackageData(env.getPackageData());
3951 }
3952
3953 private Location mostRecentLocation = ExplicitLocation.UNKNOWN_LOCATION;
3954
3955 public Location makeLocation() {
3956 if (t.getLineNumber() == mostRecentLocation.getLineNumber() &&
3957 t.getColumnNumber() == mostRecentLocation.getColumnNumber() &&
3958 ((env.getSystemId() == null && mostRecentLocation.getSystemId() == null) ||
3959 env.getSystemId().equals(mostRecentLocation.getSystemId()))) {
3960 return mostRecentLocation;
3961 } else {
3962 int line = t.getLineNumber();
3963 int column = t.getColumnNumber();
3964 mostRecentLocation = makeNestedLocation(env.getContainingLocation(), line, column, null);
3965 return mostRecentLocation;
3966 }
3967 }
3968
3969 /**
3970 * Make a Location object relative to an existing location
3971 * @param containingLoc the containing location
3972 * @param line the line number relative to the containing location (zero-based)
3973 * @param column the column number relative to the containing location (zero-based)
3974 * @param nearbyText (maybe null) expression text around the point of the error
3975 * @return a suitable Location object
3976 */
3977
3978 public Location makeNestedLocation(Location containingLoc, int line, int column, String nearbyText) {
3979 if (containingLoc instanceof ExplicitLocation &&
3980 containingLoc.getLineNumber() <= 1 && containingLoc.getColumnNumber() == -1 &&
3981 nearbyText == null) {
3982 // No extra information available about the container
3983 return new ExplicitLocation(env.getSystemId(), line + 1, column + 1);
3984 } else {
3985 return new NestedLocation(containingLoc, line, column, nearbyText);
3986 }
3987 }
3988
3989
3990 /**
3991 * If tracing, wrap an expression in a trace instruction
3992 *
3993 * @param startOffset the position of the expression in the soruce
3994 * @param exp the expression to be wrapped
3995 * @param construct integer constant identifying the kind of construct
3996 * @param qName the name of the construct (if applicable)
3997 * @return the expression that does the tracing
3998 */
3999
4000 public Expression makeTracer(int startOffset, Expression exp, int construct, /*@Nullable*/ StructuredQName qName) {
4001 exp.setRetainedStaticContextLocally(env.makeRetainedStaticContext());
4002 if (codeInjector != null) {
4003 return codeInjector.inject(exp, env, construct, qName);
4004 } else {
4005 return exp;
4006 }
4007 }
4008
4009 /**
4010 * Test whether the current token is a given keyword.
4011 *
4012 * @param s The string to be compared with the current token
4013 * @return true if they are the same
4014 */
4015
4016 protected boolean isKeyword(String s) {
4017 return t.currentToken == Token.NAME && t.currentTokenValue.equals(s);
4018 }
4019
4020 /**
4021 * Set that we are parsing in "scan only"
4022 *
4023 * @param scanOnly true if parsing is to proceed in scan-only mode. In this mode
4024 * namespace bindings are not yet known, so no attempt is made to look up namespace
4025 * prefixes.
4026 */
4027
4028 public void setScanOnly(boolean scanOnly) {
4029 this.scanOnly = scanOnly;
4030 }
4031
4032 /**
4033 * Say whether an absent expression is permitted
4034 *
4035 * @param allowEmpty true if it is permitted for the expression to consist
4036 * only of whitespace and comments, in which case the result
4037 * of parsing will be an EmptySequence literal
4038 */
4039
4040 public void setAllowAbsentExpression(boolean allowEmpty) {
4041 this.allowAbsentExpression = allowEmpty;
4042 }
4043
4044 /**
4045 * Ask whether an absent expression is permitted
4046 *
4047 * @return true if it is permitted for the expression to consist
4048 * only of whitespace and comments, in which case the result
4049 * of parsing will be an EmptySequence literal
4050 */
4051
4052 public boolean isAllowAbsentExpression(boolean allowEmpty) {
4053 return this.allowAbsentExpression;
4054 }
4055
4056 /**
4057 * Check that the higher-order-function feature is licensed
4058 *
4059 * @throws LicenseException if the feature is not licensed
4060 */
4061
4062 public void checkHofFeature() {
4063 env.getConfiguration().checkLicensedFeature(Configuration.LicenseFeature.PROFESSIONAL_EDITION, "higher-order functions", -1);
4064 }
4065
4066 /**
4067 * A nested location: for use with XPath expressions and queries nested within some
4068 * larger document. The location information comes in two parts: the location of the query
4069 * or expression within the containing document, and the location of an error within the
4070 * query or XPath expression.
4071 */
4072
4073 public static class NestedLocation implements Location {
4074
4075 private final Location containingLocation;
4076 private final int localLineNumber;
4077 private final int localColumnNumber;
4078 private String nearbyText;
4079
4080 /**
4081 * Create a NestedLocation
4082 *
4083 * @param containingLocation the location of the containing construct, typically an attribute or
4084 * text node in an XML document
4085 * @param localLineNumber the line number within the containing construct, starting at zero
4086 * @param localColumnNumber the column number within the containing construct, starting at zero
4087 */
4088 public NestedLocation(Location containingLocation, int localLineNumber, int localColumnNumber) {
4089 this.containingLocation = containingLocation.saveLocation();
4090 this.localLineNumber = localLineNumber;
4091 this.localColumnNumber = localColumnNumber;
4092 }
4093
4094 /**
4095 * Create a NestedLocation
4096 *
4097 * @param containingLocation the location of the containing construct, typically an attribute or
4098 * text node in an XML document
4099 * @param localLineNumber the line number within the containing construct, starting at zero
4100 * @param localColumnNumber the column number within the containing construct, starting at zero
4101 * @param nearbyText text appearing in the vicinity of the error location
4102 */
4103
4104 public NestedLocation(Location containingLocation, int localLineNumber, int localColumnNumber, String nearbyText) {
4105 this.containingLocation = containingLocation.saveLocation();
4106 this.localLineNumber = localLineNumber;
4107 this.localColumnNumber = localColumnNumber;
4108 this.nearbyText = nearbyText;
4109 }
4110
4111 /**
4112 * Get the location of the container. This is normally used for expressions nested within
4113 * an XML document, where the container location gives the location of the attribute or text
4114 * node holding the XPath expression as a whole
4115 *
4116 * @return the location of the containing expression or query
4117 */
4118
4119 public Location getContainingLocation() {
4120 return containingLocation;
4121 }
4122
4123 /**
4124 * Get the column number of the error within the expression or query
4125 *
4126 * @return the column number. This is generally maintained only during parsing,
4127 * so it will be returned as -1 (meaning not available) in the case of dynamic
4128 * errors. Column numbers start at 0. For expressions held within XML attributes,
4129 * the position is within the attribute after XML attribute-value normalization,
4130 * which replaces newlines by spaces and expands entity references.
4131 */
4132
4133 public int getColumnNumber() {
4134 return localColumnNumber;
4135 }
4136
4137 /**
4138 * Get the system identifier of the expression's container. This will normally
4139 * be the URI of the document (or external entity) in which the expression appears.
4140 *
4141 * @return the system identifier of the expression's container, or null if not known
4142 */
4143
4144 public String getSystemId() {
4145 return containingLocation.getSystemId();
4146 }
4147
4148 /**
4149 * Get the public identifier. This will normally be null, but is provided for
4150 * compatibility with SAX and JAXP interfaces
4151 *
4152 * @return the public identifier - usually null
4153 */
4154
4155 public String getPublicId() {
4156 return containingLocation.getPublicId();
4157 }
4158
4159 /**
4160 * Get the local line number, that is the line number relative to the start of the
4161 * expression or query. For expressions held within XML attributes,
4162 * the position is within the attribute after XML attribute-value normalization,
4163 * which replaces newlines by spaces and expands entity references; the value
4164 * will therefore in many cases not be usable. Local line numbers start at 0.
4165 *
4166 * @return the local line number within the expression or query. Set to -1
4167 * if not known.
4168 */
4169
4170 public int getLocalLineNumber() {
4171 return localLineNumber;
4172 }
4173
4174 /**
4175 * Get the line number within the containing entity. This is the sum of the containing
4176 * location's line number, plus the local line number. Returns -1 if unknown.
4177 *
4178 * @return the line number within the containing entity, or -1 if unknown.
4179 */
4180
4181 public int getLineNumber() {
4182 return containingLocation.getLineNumber() + localLineNumber;
4183 }
4184
4185 /**
4186 * Get text appearing near to the error (typically a syntax error) within the source
4187 * text of the expression or query.
4188 *
4189 * @return nearby text to the error. May be null.
4190 */
4191
4192 public String getNearbyText() {
4193 return nearbyText;
4194 }
4195
4196 /**
4197 * Save an immutable copy of the location information. This implementation does
4198 * nothing, because the object is already immutable
4199 *
4200 * @return immutable location information.
4201 */
4202
4203 public Location saveLocation() {
4204 return this;
4205 }
4206 }
4207
4208 }
4209
4210 /*
4211
4212 The following copyright notice is copied from the licence for xt, from which the
4213 original version of this module was derived:
4214 --------------------------------------------------------------------------------
4215 Copyright (c) 1998, 1999 James Clark
4216
4217 Permission is hereby granted, free of charge, to any person obtaining
4218 a copy of this software and associated documentation files (the
4219 "Software"), to deal in the Software without restriction, including
4220 without limitation the rights to use, copy, modify, merge, publish,
4221 distribute, sublicense, and/or sell copies of the Software, and to
4222 permit persons to whom the Software is furnished to do so, subject to
4223 the following conditions:
4224
4225 The above copyright notice and this permission notice shall be included
4226 in all copies or substantial portions of the Software.
4227
4228 THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS
4229 OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4230 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
4231 IN NO EVENT SHALL JAMES CLARK BE LIABLE FOR ANY CLAIM, DAMAGES OR
4232 OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
4233 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
4234 OTHER DEALINGS IN THE SOFTWARE.
4235
4236 Except as contained in this notice, the name of James Clark shall
4237 not be used in advertising or otherwise to promote the sale, use or
4238 other dealings in this Software without prior written authorization
4239 from James Clark.
4240 ---------------------------------------------------------------------------
4241 */