Debian Codegraph @

net/sf/saxon/query/XQueryParser.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.query;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.event.PipelineConfiguration;
12 import net.sf.saxon.expr.*;
13 import net.sf.saxon.expr.flwor.*;
14 import net.sf.saxon.expr.instruct.*;
15 import net.sf.saxon.expr.parser.*;
16 import net.sf.saxon.expr.sort.GenericAtomicComparer;
17 import net.sf.saxon.expr.sort.SortKeyDefinition;
18 import net.sf.saxon.functions.*;
19 import net.sf.saxon.functions.registry.BuiltInFunctionSet;
20 import net.sf.saxon.functions.registry.ConstructorFunctionLibrary;
21 import net.sf.saxon.lib.*;
22 import net.sf.saxon.om.*;
23 import net.sf.saxon.pattern.AnyNodeTest;
24 import net.sf.saxon.pattern.QNameTest;
25 import net.sf.saxon.pattern.UnionQNameTest;
26 import net.sf.saxon.serialize.CharacterMap;
27 import net.sf.saxon.serialize.CharacterMapIndex;
28 import net.sf.saxon.serialize.SerializationParamsHandler;
29 import net.sf.saxon.serialize.charcode.UTF16CharacterSet;
30 import net.sf.saxon.style.AttributeValueTemplate;
31 import net.sf.saxon.trace.LocationKind;
32 import net.sf.saxon.trans.DecimalFormatManager;
33 import net.sf.saxon.trans.DecimalSymbols;
34 import net.sf.saxon.trans.Err;
35 import net.sf.saxon.trans.XPathException;
36 import net.sf.saxon.tree.util.FastStringBuffer;
37 import net.sf.saxon.tree.util.NamespaceResolverWithDefault;
38 import net.sf.saxon.type.*;
39 import net.sf.saxon.value.*;
40 import net.sf.saxon.z.IntHashSet;
41
42 import javax.xml.transform.OutputKeys;
43 import javax.xml.transform.Source;
44 import javax.xml.transform.TransformerException;
45 import javax.xml.transform.stream.StreamSource;
46 import java.io.IOException;
47 import java.net.URI;
48 import java.net.URISyntaxException;
49 import java.util.*;
50 import java.util.function.IntPredicate;
51 import java.util.regex.Pattern;
52
53 /**
54 * This class defines extensions to the XPath parser to handle the additional
55 * syntax supported in XQuery
56 */
57 public class XQueryParser extends XPathParser {
58
59 public final static String XQUERY10 = "1.0";
60 public final static String XQUERY30 = "3.0";
61 public final static String XQUERY31 = "3.1";
62
63 private boolean memoFunction = false;
64 private boolean streaming = false;
65 //protected String queryVersion = null;
66 private int errorCount = 0;
67 /*@Nullable*/ private XPathException firstError = null;
68
69 /*@NotNull*/ protected Executable executable;
70
71 private boolean foundCopyNamespaces = false;
72 private boolean foundBoundarySpaceDeclaration = false;
73 private boolean foundOrderingDeclaration = false;
74 private boolean foundEmptyOrderingDeclaration = false;
75 private boolean foundDefaultCollation = false;
76 private boolean foundConstructionDeclaration = false;
77 private boolean foundDefaultFunctionNamespace = false;
78 private boolean foundDefaultElementNamespace = false;
79 private boolean foundBaseURIDeclaration = false;
80 private boolean foundContextItemDeclaration = false;
81 private boolean foundDefaultDecimalFormat = false;
82 private boolean preambleProcessed = false;
83
84 public final Set<String> importedModules = new HashSet<>(5);
85 final List<String> namespacesToBeSealed = new ArrayList<>(10);
86 final List<Import> schemaImports = new ArrayList<>(5);
87 final List<Import> moduleImports = new ArrayList<>(5);
88
89 private final Set<StructuredQName> outputPropertiesSeen = new HashSet<>(4);
90 private Properties parameterDocProperties;
91
92
93 /**
94 * Constructor for internal use: this class should be instantiated via the QueryModule
95 */
96
97 public XQueryParser() {
98 //queryVersion = XQUERY31;
99 setLanguage(XQUERY, 31);
100 }
101
102 /**
103 * Create a new parser of the same kind
104 *
105 * @return a new parser of the same kind as this one
106 */
107
108 public XQueryParser newParser() {
109 XQueryParser qp = new XQueryParser();
110 qp.setLanguage(language, 31);
111 qp.setParserExtension(parserExtension);
112 return qp;
113 }
114
115 /**
116 * Create an XQueryExpression
117 *
118 * @param query the source text of the query
119 * @param mainModule the static context of the query
120 * @param config the Saxon configuration
121 * @return the compiled XQuery expression
122 * @throws XPathException if the expression contains static errors
123 */
124
125 /*@NotNull*/
126 public XQueryExpression makeXQueryExpression(
127 /*@NotNull*/ String query,
128 /*@NotNull*/ QueryModule mainModule,
129 /*@NotNull*/ Configuration config) throws XPathException {
130 try {
131 setLanguage(XQUERY, 31);
132 if (config.getXMLVersion() == Configuration.XML10) {
133 query = normalizeLineEndings10(query);
134 } else {
135 query = normalizeLineEndings11(query);
136 }
137 Executable exec = mainModule.getExecutable();
138 if (exec == null) {
139 exec = new Executable(config);
140 exec.setHostLanguage(Configuration.XQUERY);
141 exec.setTopLevelPackage(mainModule.getPackageData());
142 setExecutable(exec);
143 //mainModule.setExecutable(exec);
144 }
145 GlobalContextRequirement requirement = exec.getGlobalContextRequirement();
146 if (requirement != null) {
147 requirement.addRequiredItemType(mainModule.getRequiredContextItemType());
148 } else if (mainModule.getRequiredContextItemType() != null
149 && mainModule.getRequiredContextItemType() != AnyItemType.getInstance()) {
150 GlobalContextRequirement req = new GlobalContextRequirement();
151 req.setExternal(true);
152 req.addRequiredItemType(mainModule.getRequiredContextItemType());
153 exec.setGlobalContextRequirement(req);
154 }
155
156 // setDefaultContainer(new SimpleContainer(mainModule.getPackageData()));
157
158 Properties outputProps = new Properties(config.getDefaultSerializationProperties());
159 if (outputProps.getProperty(OutputKeys.METHOD) == null) {
160 outputProps.setProperty(OutputKeys.METHOD, "xml");
161 }
162 parameterDocProperties = new Properties(outputProps);
163 exec.setDefaultOutputProperties(new Properties(parameterDocProperties));
164
165 //exec.setLocationMap(new LocationMap());
166 FunctionLibraryList libList = new FunctionLibraryList();
167 libList.addFunctionLibrary(new ExecutableFunctionLibrary(config));
168 exec.setFunctionLibrary(libList);
169 // this will be changed later
170 setExecutable(exec);
171
172 setCodeInjector(mainModule.getCodeInjector());
173
174 Expression exp = parseQuery(query, mainModule);
175 if (streaming) {
176 env.getConfiguration().checkLicensedFeature(Configuration.LicenseFeature.ENTERPRISE_XQUERY, "streaming", -1);
177 }
178
179 exec.fixupQueryModules(mainModule);
180
181 // Check for cyclic dependencies among the modules
182
183 // if (!disableCycleChecks) {
184 // Iterator miter = exec.getQueryLibraryModules();
185 // while (miter.hasNext()) {
186 // QueryModule module = (QueryModule)miter.next();
187 // module.lookForModuleCycles(new Stack(), 1);
188 // }
189 // }
190
191 // Make the XQueryExpression object
192
193 XQueryExpression queryExp = config.makeXQueryExpression(exp, mainModule, streaming);
194
195 // Make the function library that's available at run-time (e.g. for saxon:evaluate() and function-lookup()).
196 // This includes all user-defined functions regardless of which module they are in
197
198 FunctionLibrary userlib = exec.getFunctionLibrary();
199 FunctionLibraryList lib = new FunctionLibraryList();
200 lib.addFunctionLibrary(mainModule.getBuiltInFunctionSet());
201 lib.addFunctionLibrary(config.getBuiltInExtensionLibraryList());
202 lib.addFunctionLibrary(new ConstructorFunctionLibrary(config));
203 lib.addFunctionLibrary(config.getIntegratedFunctionLibrary());
204 lib.addFunctionLibrary(mainModule.getGlobalFunctionLibrary());
205 config.addExtensionBinders(lib);
206 lib.addFunctionLibrary(userlib);
207 exec.setFunctionLibrary(lib);
208
209 return queryExp;
210 } catch (XPathException e) {
211 if (!e.hasBeenReported()) {
212 reportError(e);
213 }
214 throw e;
215 }
216 }
217
218 /**
219 * Get the permitted set of standard functions in this environment
220 *
221 * @return a code indicating which system library functions are supported in this version of the language
222 */
223
224 public int getPermittedFunctions() {
225 return BuiltInFunctionSet.CORE | BuiltInFunctionSet.XPATH30;
226 }
227
228 /**
229 * Check that an expression is streamable
230 * @param exp the expression to be checked
231 * @param contextInfo information about the context item
232 * @throws XPathException if the expression is not streamable
233 */
234
235 public void checkStreamability(Expression exp, ContextItemStaticInfo contextInfo) throws XPathException {
236 throw new XPathException("Streaming requires Saxon-EE");
237 }
238
239 /**
240 * Normalize line endings in the source query, according to the XML 1.1 rules.
241 *
242 * @param in the input query
243 * @return the query with line endings normalized
244 */
245
246 private static String normalizeLineEndings11(/*@NotNull*/ String in) {
247 if (in.indexOf((char) 0xd) < 0 && in.indexOf((char) 0x85) < 0 && in.indexOf((char) 0x2028) < 0) {
248 return in;
249 }
250 FastStringBuffer sb = new FastStringBuffer(in.length());
251 for (int i = 0; i < in.length(); i++) {
252 char ch = in.charAt(i);
253 switch (ch) {
254 case 0x85:
255 case 0x2028:
256 sb.append((char) 0xa);
257 break;
258 case 0xd:
259 if (i < in.length() - 1 && (in.charAt(i + 1) == (char) 0xa || in.charAt(i + 1) == (char) 0x85)) {
260 sb.append((char) 0xa);
261 i++;
262 } else {
263 sb.append((char) 0xa);
264 }
265 break;
266 default:
267 sb.append(ch);
268 }
269 }
270 return sb.toString();
271 }
272
273 /**
274 * Normalize line endings in the source query, according to the XML 1.0 rules.
275 *
276 * @param in the input query
277 * @return the query text with line endings normalized
278 */
279
280 private static String normalizeLineEndings10(/*@NotNull*/ String in) {
281 if (in.indexOf((char) 0xd) < 0) {
282 return in;
283 }
284 FastStringBuffer sb = new FastStringBuffer(in.length());
285 for (int i = 0; i < in.length(); i++) {
286 char ch = in.charAt(i);
287 switch (ch) {
288 case 0xd:
289 if (i < in.length() - 1 && in.charAt(i + 1) == (char) 0xa) {
290 sb.append((char) 0xa);
291 i++;
292 } else {
293 sb.append((char) 0xa);
294 }
295 break;
296 default:
297 sb.append(ch);
298 }
299 }
300 return sb.toString();
301 }
302
303
304 /**
305 * Get the executable containing this expression.
306 *
307 * @return the executable
308 */
309
310 /*@NotNull*/
311 public Executable getExecutable() {
312 return executable;
313 }
314
315 /**
316 * Set the executable used for this query expression
317 *
318 * @param exec the executable
319 */
320
321 public void setExecutable(/*@NotNull*/ Executable exec) {
322 executable = exec;
323 }
324
325
326 /**
327 * Callback to tailor the tokenizer
328 */
329
330 protected void customizeTokenizer(Tokenizer t) {
331 t.isXQuery = true;
332 }
333
334
335 /**
336 * Say whether the query should be compiled and evaluated to use streaming.
337 * This affects subsequent calls on the parseQuery() method. This option requires
338 * Saxon-EE.
339 * @param option if true, the compiler will attempt to compile a query to be
340 * capable of executing in streaming mode. If the query cannot be streamed,
341 * a compile-time exception is reported. In streaming mode, the source
342 * document is supplied as a stream, and no tree is built in memory. The default
343 * is false.
344 * @since 9.6
345 */
346
347 public void setStreaming(boolean option) {
348 streaming = option;
349 }
350
351 /**
352 * Ask whether the streaming option has been set, that is, whether
353 * subsequent calls on parseQuery() will compile queries to be capable
354 * of executing in streaming mode.
355 * @return true if the streaming option has been set.
356 * @since 9.6
357 */
358
359 public boolean isStreaming() {
360 return streaming;
361 }
362
363
364
365 /**
366 * Parse a top-level Query.
367 * Prolog? Expression
368 *
369 * @param queryString The text of the query
370 * @param env The static context
371 * @return the Expression object that results from parsing
372 * @throws net.sf.saxon.trans.XPathException
373 * if the expression contains a syntax error
374 */
375
376 /*@NotNull*/
377 private Expression parseQuery(String queryString, QueryModule env) throws XPathException {
378 this.env = Objects.requireNonNull(env);
379 charChecker = env.getConfiguration().getValidCharacterChecker();
380 // if (defaultContainer == null) {
381 // defaultContainer = new TemporaryContainer(env.getConfiguration(), env.getLocationMap(), 1);
382 // }
383 language = XQUERY;
384 t = new Tokenizer();
385 t.languageLevel = 31;
386 t.isXQuery = true;
387 try {
388 t.tokenize(Objects.requireNonNull(queryString), 0, -1);
389 } catch (XPathException err) {
390 grumble(err.getMessage());
391 }
392 parseVersionDeclaration();
393 allowSaxonExtensions =
394 t.allowSaxonExtensions =
395 env.getConfiguration().getBooleanProperty(Feature.ALLOW_SYNTAX_EXTENSIONS);
396
397 QNameParser qp = new QNameParser(env.getLiveNamespaceResolver());
398 qp.setAcceptEQName(true);
399 qp.setUnescaper(new Unescaper(env.getConfiguration().getValidCharacterChecker()));
400 setQNameParser(qp);
401
402 parseProlog();
403 processPreamble();
404
405 Expression exp = parseExpression();
406 exp = makeTracer(0, exp, LocationKind.XQUERY_BODY, null);
407
408 // Diagnostic code - show the expression before any optimizations
409 // ExpressionPresenter ep = ExpressionPresenter.make(env.getConfiguration());
410 // exp.explain(ep);
411 // ep.close();
412 // End of diagnostic code
413
414 if (t.currentToken != Token.EOF) {
415 grumble("Unexpected token " + currentTokenDisplay() + " beyond end of query");
416 }
417 setLocation(exp);
418 ExpressionTool.setDeepRetainedStaticContext(exp, env.makeRetainedStaticContext());
419 if (errorCount == 0) {
420 return exp;
421 } else {
422 XPathException err = new XPathException("One or more static errors were reported during query analysis");
423 err.setHasBeenReported(true);
424 err.setErrorCodeQName(firstError.getErrorCodeQName()); // largely for the XQTS test driver
425 throw err;
426 }
427 }
428
429 /**
430 * Parse a library module.
431 * Prolog? Expression
432 *
433 * @param queryString The text of the library module.
434 * @param env The static context. The result of parsing
435 * a library module is that the static context is populated with a set of function
436 * declarations and variable declarations. Each library module must have its own
437 * static context objext.
438 * @throws XPathException if the expression contains a syntax error
439 */
440
441 public final void parseLibraryModule(String queryString, /*@NotNull*/ QueryModule env)
442 throws XPathException {
443 this.env = env;
444 final Configuration config = env.getConfiguration();
445 charChecker = config.getValidCharacterChecker();
446 if (config.getXMLVersion() == Configuration.XML10) {
447 queryString = normalizeLineEndings10(queryString);
448 } else {
449 queryString = normalizeLineEndings11(queryString);
450 }
451 Executable exec = env.getExecutable();
452 if (exec == null) {
453 throw new IllegalStateException("Query library module has no associated Executable");
454 }
455 executable = exec;
456 // defaultContainer = new SimpleContainer(env.getPackageData());
457 t = new Tokenizer();
458 t.languageLevel = 31;
459 t.isXQuery = true;
460 QNameParser qp = new QNameParser(env.getLiveNamespaceResolver());
461 qp.setAcceptEQName(true);
462 qp.setUnescaper(new Unescaper(config.getValidCharacterChecker()));
463 setQNameParser(qp);
464 try {
465 t.tokenize(queryString, 0, -1);
466 } catch (XPathException err) {
467 grumble(err.getMessage());
468 }
469 parseVersionDeclaration();
470 //t.setAllowExpandedQNameSyntax("3.0".equals(queryVersion));
471 parseModuleDeclaration();
472 parseProlog();
473 processPreamble();
474 if (t.currentToken != Token.EOF) {
475 grumble("Unrecognized content found after the variable and function declarations in a library module");
476 }
477 if (errorCount != 0) {
478 XPathException err = new XPathException("Static errors were reported in the imported library module");
479 err.setErrorCodeQName(firstError.getErrorCodeQName());
480 throw err;
481 }
482 }
483
484
485 private void reportError(/*@NotNull*/ XPathException exception) throws XPathException {
486 errorCount++;
487 if (firstError == null) {
488 firstError = exception;
489 }
490 ((QueryModule) env).reportStaticError(exception);
491 throw exception;
492 }
493
494 private static final Pattern encNamePattern = Pattern.compile("^[A-Za-z]([A-Za-z0-9._\\x2D])*$");
495
496 /**
497 * Parse the version declaration if present.
498 *
499 * @throws XPathException in the event of a syntax error.
500 */
501 private void parseVersionDeclaration() throws XPathException {
502 if (t.currentToken == Token.XQUERY_VERSION) {
503 nextToken();
504 expect(Token.STRING_LITERAL);
505 String queryVersion = unescape(t.currentTokenValue).toString();
506 String[] allowedVersions = new String[]{"1.0", "3.0", "3.1"};
507 if (Arrays.binarySearch(allowedVersions, queryVersion) < 0) {
508 // if (!queryVersion.trim().matches("[0-9]+\\.[0-9]+")) {
509 grumble("Invalid XQuery version " + queryVersion, "XQST0031");
510 }
511 // if (XQUERY10.equals(queryVersion)) {
512 // // no action
513 // } else if (XQUERY30.equals(queryVersion) || "1.1".equals(queryVersion)) {
514 // queryVersion = XQUERY30;
515 // if (((QueryModule) env).getLanguageVersion() != 30 && ((QueryModule) env).getLanguageVersion() != 31) {
516 // grumble("XQuery 3.0 was not enabled when invoking Saxon", "XQST0031");
517 // queryVersion = XQUERY10;
518 // }
519 // } else if(XQUERY31.equals(queryVersion)) {
520 // queryVersion = XQUERY31;
521 // if (((QueryModule) env).getLanguageVersion() != 31) {
522 // grumble("XQuery 3.1 was not enabled when invoking Saxon", "XQST0031");
523 // queryVersion = XQUERY30;
524 // }
525 // } else {
526 // grumble("Unsupported XQuery version " + queryVersion, "XQST0031");
527 // queryVersion = XQUERY10;
528 // }
529 nextToken();
530 if ("encoding".equals(t.currentTokenValue)) {
531 nextToken();
532 expect(Token.STRING_LITERAL);
533 if (!encNamePattern.matcher(unescape(t.currentTokenValue)).matches()) {
534 grumble("Encoding name contains invalid characters", "XQST0087");
535 }
536 // we ignore the encoding now: it was handled earlier, while decoding the byte stream
537 nextToken();
538 }
539 expect(Token.SEMICOLON);
540 nextToken();
541 } else {
542 // if (((QueryModule) env).getLanguageVersion()== 30) {
543 // queryVersion = XQUERY30;
544 // } else if (((QueryModule) env).getLanguageVersion() == 31) {
545 // queryVersion = XQUERY31;
546 // } else {
547 // queryVersion = XQUERY10;
548 // }
549 if (t.currentToken == Token.XQUERY_ENCODING) {
550 nextToken();
551 expect(Token.STRING_LITERAL);
552 if (!encNamePattern.matcher(t.currentTokenValue).matches()) {
553 grumble("Encoding name contains invalid characters", "XQST0087");
554 }
555 // we ignore the encoding now: it was handled earlier, while decoding the byte stream
556 nextToken();
557 expect(Token.SEMICOLON);
558 nextToken();
559 }
560 }
561 }
562
563 /**
564 * In a library module, parse the module declaration
565 * Syntax: &lt;"module" "namespace"&gt; prefix "=" uri ";"
566 *
567 * @throws XPathException in the event of a syntax error.
568 */
569
570 private void parseModuleDeclaration() throws XPathException {
571 expect(Token.MODULE_NAMESPACE);
572 nextToken();
573 expect(Token.NAME);
574 String prefix = t.currentTokenValue;
575 nextToken();
576 expect(Token.EQUALS);
577 nextToken();
578 expect(Token.STRING_LITERAL);
579 String uri = uriLiteral(t.currentTokenValue);
580 checkProhibitedPrefixes(prefix, uri);
581 if (uri.isEmpty()) {
582 grumble("Module namespace cannot be \"\"", "XQST0088");
583 uri = "http://saxon.fallback.namespace/"; // for error recovery
584 }
585 nextToken();
586 expect(Token.SEMICOLON);
587 nextToken();
588 try {
589 ((QueryModule) env).setModuleNamespace(uri);
590 ((QueryModule) env).declarePrologNamespace(prefix, uri);
591 executable.addQueryLibraryModule((QueryModule) env);
592 } catch (XPathException err) {
593 err.setLocator(makeLocation());
594 reportError(err);
595 }
596 }
597
598 /**
599 * Parse the query prolog. This method, and its subordinate methods which handle
600 * individual declarations in the prolog, cause the static context to be updated
601 * with relevant context information. On exit, t.currentToken is the first token
602 * that is not recognized as being part of the prolog.
603 *
604 * @throws XPathException in the event of a syntax error.
605 */
606
607 private void parseProlog() throws XPathException {
608 //boolean allowSetters = true;
609 boolean allowModuleDecl = true;
610 boolean allowDeclarations = true;
611
612 while (true) {
613 try {
614 if (t.currentToken == Token.MODULE_NAMESPACE) {
615 String uri = ((QueryModule) env).getModuleNamespace();
616 if (uri == null) {
617 grumble("Module declaration must not be used in a main module");
618 } else {
619 grumble("Module declaration appears more than once");
620 }
621 if (!allowModuleDecl) {
622 grumble("Module declaration must precede other declarations in the query prolog");
623 }
624 }
625 allowModuleDecl = false;
626 switch (t.currentToken) {
627 case Token.DECLARE_NAMESPACE:
628 if (!allowDeclarations) {
629 grumble("Namespace declarations cannot follow variables, functions, or options");
630 }
631 //allowSetters = false;
632 parseNamespaceDeclaration();
633 break;
634 case Token.DECLARE_ANNOTATED:
635 // we have read "declare %"
636 processPreamble();
637 if (allowDeclarations) {
638 sealNamespaces(namespacesToBeSealed, env.getConfiguration());
639 allowDeclarations = false;
640 }
641 nextToken();
642 expect(Token.PERCENT);
643 AnnotationList annotationList = parseAnnotationsList();
644 if (isKeyword("function")) {
645 annotationList.check(env.getConfiguration(), "DF");
646 parseFunctionDeclaration(annotationList);
647 } else if (isKeyword("variable")) {
648 annotationList.check(env.getConfiguration(), "DV");
649 parseVariableDeclaration(annotationList);
650 } else {
651 grumble("Annotations can appear only in 'declare variable' and 'declare function'");
652 }
653 break;
654 case Token.DECLARE_DEFAULT:
655 nextToken();
656 expect(Token.NAME);
657 switch (t.currentTokenValue) {
658 case "element":
659 if (!allowDeclarations) {
660 grumble("Namespace declarations cannot follow variables, functions, or options");
661 }
662 //allowSetters = false;
663 parseDefaultElementNamespace();
664 break;
665 case "function":
666 if (!allowDeclarations) {
667 grumble("Namespace declarations cannot follow variables, functions, or options");
668 }
669 //allowSetters = false;
670 parseDefaultFunctionNamespace();
671 break;
672 case "collation":
673 if (!allowDeclarations) {
674 grumble("Collation declarations must appear earlier in the prolog");
675 }
676 parseDefaultCollation();
677 break;
678 case "order":
679 if (!allowDeclarations) {
680 grumble("Order declarations must appear earlier in the prolog");
681 }
682 parseDefaultOrder();
683 break;
684 case "decimal-format":
685 nextToken();
686 parseDefaultDecimalFormat();
687 break;
688 default:
689 grumble("After 'declare default', expected 'element', 'function', or 'collation'");
690 break;
691 }
692 break;
693 case Token.DECLARE_BOUNDARY_SPACE:
694 if (!allowDeclarations) {
695 grumble("'declare boundary-space' must appear earlier in the query prolog");
696 }
697 parseBoundarySpaceDeclaration();
698 break;
699 case Token.DECLARE_ORDERING:
700 if (!allowDeclarations) {
701 grumble("'declare ordering' must appear earlier in the query prolog");
702 }
703 parseOrderingDeclaration();
704 break;
705 case Token.DECLARE_COPY_NAMESPACES:
706 if (!allowDeclarations) {
707 grumble("'declare copy-namespaces' must appear earlier in the query prolog");
708 }
709 parseCopyNamespacesDeclaration();
710 break;
711 case Token.DECLARE_BASEURI:
712 if (!allowDeclarations) {
713 grumble("'declare base-uri' must appear earlier in the query prolog");
714 }
715 parseBaseURIDeclaration();
716 break;
717 case Token.DECLARE_DECIMAL_FORMAT:
718 if (!allowDeclarations) {
719 grumble("'declare decimal-format' must appear earlier in the query prolog");
720 }
721 parseDecimalFormatDeclaration();
722 break;
723 case Token.IMPORT_SCHEMA:
724 //allowSetters = false;
725 if (!allowDeclarations) {
726 grumble("Import schema must appear earlier in the prolog");
727 }
728 parseSchemaImport();
729 break;
730 case Token.IMPORT_MODULE:
731 //allowSetters = false;
732 if (!allowDeclarations) {
733 grumble("Import module must appear earlier in the prolog");
734 }
735 parseModuleImport();
736 break;
737 case Token.DECLARE_VARIABLE:
738 //allowSetters = false;
739 if (allowDeclarations) {
740 sealNamespaces(namespacesToBeSealed, env.getConfiguration());
741 allowDeclarations = false;
742 }
743 processPreamble();
744 parseVariableDeclaration(AnnotationList.EMPTY);
745 break;
746 case Token.DECLARE_CONTEXT:
747 //allowSetters = false;
748 if (allowDeclarations) {
749 sealNamespaces(namespacesToBeSealed, env.getConfiguration());
750 allowDeclarations = false;
751 }
752 processPreamble();
753 parseContextItemDeclaration();
754 break;
755 case Token.DECLARE_FUNCTION:
756 if (allowDeclarations) {
757 sealNamespaces(namespacesToBeSealed, env.getConfiguration());
758 allowDeclarations = false;
759 }
760 processPreamble();
761 parseFunctionDeclaration(AnnotationList.EMPTY);
762 break;
763 case Token.DECLARE_UPDATING:
764 nextToken();
765 if (!isKeyword("function")) {
766 grumble("expected 'function' after 'declare updating");
767 }
768 if (allowDeclarations) {
769 sealNamespaces(namespacesToBeSealed, env.getConfiguration());
770 allowDeclarations = false;
771 }
772 processPreamble();
773 parserExtension.parseUpdatingFunctionDeclaration(this);
774 break;
775 case Token.DECLARE_OPTION:
776 if (allowDeclarations) {
777 sealNamespaces(namespacesToBeSealed, env.getConfiguration());
778 allowDeclarations = false;
779 }
780 parseOptionDeclaration();
781 break;
782 case Token.DECLARE_TYPE:
783 checkSyntaxExtensions("declare type");
784 if (allowDeclarations) {
785 sealNamespaces(namespacesToBeSealed, env.getConfiguration());
786 allowDeclarations = false;
787 }
788 parseTypeAliasDeclaration();
789 break;
790 case Token.DECLARE_CONSTRUCTION:
791 if (!allowDeclarations) {
792 grumble("'declare construction' must appear earlier in the query prolog");
793 }
794 parseConstructionDeclaration();
795 break;
796 case Token.DECLARE_REVALIDATION:
797 if (!allowDeclarations) {
798 grumble("'declare revalidation' must appear earlier in the query prolog");
799 }
800 parserExtension.parseRevalidationDeclaration(this);
801 break;
802 case Token.EOF:
803 String uri = ((QueryModule) env).getModuleNamespace();
804 if (uri == null) {
805 grumble("The main module must contain a query expression after any declarations in the prolog");
806 } else {
807 return;
808 }
809 break;
810 default:
811 return;
812 }
813 expect(Token.SEMICOLON);
814 nextToken();
815 } catch (XPathException err) {
816 if (err.getLocator() == null) {
817 err.setLocator(makeLocation());
818 }
819 if (!err.hasBeenReported()) {
820 errorCount++;
821 if (firstError == null) {
822 firstError = err;
823 }
824 ((QueryModule) env).reportStaticError(err);
825 }
826 // we've reported an error, attempt to recover by skipping to the
827 // next semicolon
828 while (t.currentToken != Token.SEMICOLON) {
829 nextToken();
830 if (t.currentToken == Token.EOF) {
831 return;
832 } else if (t.currentToken == Token.RCURLY) {
833 t.lookAhead();
834 } else if (t.currentToken == Token.TAG) {
835 parsePseudoXML(true);
836 }
837 }
838 nextToken();
839 }
840 }
841 }
842
843 /**
844 * Parse the annotations that can appear in a variable or function declaration
845 * @return the annotations as a list
846 * @throws XPathException in the event of a syntax error
847 */
848
849 protected AnnotationList parseAnnotationsList() throws XPathException {
850 // we have read "declare" and have seen "%" as lookahead
851 ArrayList<Annotation> annotations = new ArrayList<>();
852 int options = 0;
853 while (true) {
854 t.setState(Tokenizer.BARE_NAME_STATE);
855 nextToken();
856 expect(Token.NAME);
857 t.setState(Tokenizer.DEFAULT_STATE);
858 StructuredQName qName;
859 String uri;
860 if (t.currentTokenValue.indexOf(':') < 0) {
861 uri = NamespaceConstant.XQUERY;
862 qName = new StructuredQName("", uri, t.currentTokenValue);
863 } else {
864 qName = makeStructuredQName(t.currentTokenValue, "");
865 assert qName != null;
866 uri = qName.getURI();
867 }
868 Annotation annotation = new Annotation(qName);
869 if (uri.equals(NamespaceConstant.XQUERY)) {
870 if (qName.equals(Annotation.PRIVATE) || qName.equals(Annotation.PUBLIC) ||
871 qName.equals(Annotation.UPDATING) || qName.equals(Annotation.SIMPLE)) {
872 // OK
873 } else {
874 grumble("Unrecognized variable or function annotation " + qName.getDisplayName(), "XQST0045");
875 }
876 annotation.addAnnotationParameter(new Int64Value(options));
877 } else if (isReservedInQuery(uri)) {
878 grumble("The annotation " + t.currentTokenValue + " is in a reserved namespace", "XQST0045");
879 } else if (uri.equals("")) {
880 grumble("The annotation " + t.currentTokenValue + " is in no namespace", "XQST0045");
881 } else {
882 // no action - ignore namespaced annotations
883 }
884 nextToken();
885 if (t.currentToken == Token.LPAR) {
886 nextToken();
887 if (t.currentToken == Token.RPAR) {
888 grumble("Annotation parameter list cannot be empty");
889 }
890 while (true) {
891 // nextToken();
892 Literal arg = null;
893 switch (t.currentToken) {
894 case Token.STRING_LITERAL:
895 arg = (Literal)parseStringLiteral(false);
896 break;
897
898 case Token.NUMBER:
899 arg = (Literal)parseNumericLiteral(false);
900 break;
901
902 default:
903 grumble("Annotation parameter must be a literal");
904 return null;
905 }
906 GroundedValue val = arg.getValue();
907 if (val instanceof StringValue || val instanceof NumericValue) {
908 annotation.addAnnotationParameter((AtomicValue) val);
909 } else {
910 grumble("Annotation parameter must be a string or number");
911 }
912
913 if (t.currentToken == Token.RPAR) {
914 nextToken();
915 break;
916 }
917 expect(Token.COMMA);
918 nextToken();
919 }
920 }
921 annotations.add(annotation);
922 if (t.currentToken != Token.PERCENT) {
923 return new AnnotationList(annotations);
924 }
925 }
926 }
927
928
929 private void sealNamespaces(/*@NotNull*/ List namespacesToBeSealed, /*@NotNull*/ Configuration config) {
930 for (Object aNamespacesToBeSealed : namespacesToBeSealed) {
931 String ns = (String) aNamespacesToBeSealed;
932 config.sealNamespace(ns);
933 }
934 }
935
936 /**
937 * Method called once the setters have been read to do tidying up that can't be done until we've got
938 * to the end
939 *
940 * @throws XPathException if parsing fails
941 */
942
943 private void processPreamble() throws XPathException {
944 if (preambleProcessed) {
945 return;
946 }
947 preambleProcessed = true;
948 if (foundDefaultCollation) {
949 String collationName = env.getDefaultCollationName();
950 URI collationURI;
951 try {
952 collationURI = new URI(collationName);
953 if (!collationURI.isAbsolute()) {
954 URI base = new URI(env.getStaticBaseURI());
955 collationURI = base.resolve(collationURI);
956 collationName = collationURI.toString();
957 }
958 } catch (URISyntaxException err) {
959 grumble("Default collation name '" + collationName + "' is not a valid URI", "XQST0046");
960 collationName = NamespaceConstant.CODEPOINT_COLLATION_URI;
961 }
962 if (env.getConfiguration().getCollation(collationName) == null) {
963 grumble("Default collation name '" + collationName + "' is not a recognized collation", "XQST0038");
964 collationName = NamespaceConstant.CODEPOINT_COLLATION_URI;
965 }
966 ((QueryModule) env).setDefaultCollationName(collationName);
967 }
968 for (Import imp : schemaImports) {
969 try {
970 applySchemaImport(imp);
971 } catch (XPathException err) {
972 if (!err.hasBeenReported()) {
973 throw err;
974 }
975 }
976 }
977 for (Import imp : moduleImports) {
978 // Check that this import would not create a cycle involving a change of namespace
979 // if (!disableCycleChecks) {
980 // if (!imp.namespaceURI.equals(((QueryModule)env).getModuleNamespace())) {
981 // QueryModule parent = (QueryModule)env;
982 // if (!parent.mayImportModule(imp.namespaceURI)) {
983 // XPathException err = new XPathException(
984 // "A module cannot import itself directly or indirectly, unless all modules in the cycle are in the same namespace");
985 // err.setErrorCode("XQST0073");
986 // err.setIsStaticError(true);
987 // throw err;
988 // }
989 // }
990 // }
991 try {
992 applyModuleImport(imp);
993 } catch (XPathException err) {
994 if (!err.hasBeenReported()) {
995 throw err;
996 }
997 }
998 }
999 }
1000
1001 private void parseDefaultCollation() throws XPathException {
1002 // <"default" "collation"> StringLiteral
1003 if (foundDefaultCollation) {
1004 grumble("default collation appears more than once", "XQST0038");
1005 }
1006 foundDefaultCollation = true;
1007 nextToken();
1008 expect(Token.STRING_LITERAL);
1009 String uri = uriLiteral(t.currentTokenValue);
1010 ((QueryModule) env).setDefaultCollationName(uri);
1011 nextToken();
1012 }
1013
1014 /**
1015 * Parse "declare default order empty (least|greatest)"
1016 *
1017 * @throws XPathException if parsing fails
1018 */
1019 private void parseDefaultOrder() throws XPathException {
1020 if (foundEmptyOrderingDeclaration) {
1021 grumble("empty ordering declaration appears more than once", "XQST0069");
1022 }
1023 foundEmptyOrderingDeclaration = true;
1024 nextToken();
1025 if (!isKeyword("empty")) {
1026 grumble("After 'declare default order', expected keyword 'empty'");
1027 }
1028 nextToken();
1029 if (isKeyword("least")) {
1030 ((QueryModule) env).setEmptyLeast(true);
1031 } else if (isKeyword("greatest")) {
1032 ((QueryModule) env).setEmptyLeast(false);
1033 } else {
1034 grumble("After 'declare default order empty', expected keyword 'least' or 'greatest'");
1035 }
1036 nextToken();
1037 }
1038
1039 /**
1040 * Parse the "declare xmlspace" declaration.
1041 * Syntax: &lt;"declare" "boundary-space"&gt; ("preserve" | "strip")
1042 *
1043 * @throws XPathException if a static error is encountered
1044 */
1045
1046 private void parseBoundarySpaceDeclaration() throws XPathException {
1047 if (foundBoundarySpaceDeclaration) {
1048 grumble("'declare boundary-space' appears more than once", "XQST0068");
1049 }
1050 foundBoundarySpaceDeclaration = true;
1051 nextToken();
1052 expect(Token.NAME);
1053 if ("preserve".equals(t.currentTokenValue)) {
1054 ((QueryModule) env).setPreserveBoundarySpace(true);
1055 } else if ("strip".equals(t.currentTokenValue)) {
1056 ((QueryModule) env).setPreserveBoundarySpace(false);
1057 } else {
1058 grumble("boundary-space must be 'preserve' or 'strip'");
1059 }
1060 nextToken();
1061 }
1062
1063 /**
1064 * Parse the "declare ordering" declaration.
1065 * Syntax: &lt;"declare" "ordering"&gt; ("ordered" | "unordered")
1066 *
1067 * @throws XPathException if parsing fails
1068 */
1069
1070 private void parseOrderingDeclaration() throws XPathException {
1071 if (foundOrderingDeclaration) {
1072 grumble("ordering mode declaration appears more than once", "XQST0065");
1073 }
1074 foundOrderingDeclaration = true;
1075 nextToken();
1076 expect(Token.NAME);
1077 if ("ordered".equals(t.currentTokenValue)) {
1078 // no action
1079 } else if ("unordered".equals(t.currentTokenValue)) {
1080 // no action
1081 } else {
1082 grumble("ordering mode must be 'ordered' or 'unordered'");
1083 }
1084 nextToken();
1085 }
1086
1087 /**
1088 * Parse the "declare copy-namespaces" declaration.
1089 * Syntax: &lt;"declare" "copy-namespaces"&gt; ("preserve" | "no-preserve") "," ("inherit" | "no-inherit")
1090 *
1091 * @throws XPathException if a static error is encountered
1092 */
1093
1094 private void parseCopyNamespacesDeclaration() throws XPathException {
1095 if (foundCopyNamespaces) {
1096 grumble("declare copy-namespaces appears more than once", "XQST0055");
1097 }
1098 foundCopyNamespaces = true;
1099 nextToken();
1100 expect(Token.NAME);
1101 if ("preserve".equals(t.currentTokenValue)) {
1102 ((QueryModule) env).setPreserveNamespaces(true);
1103 } else if ("no-preserve".equals(t.currentTokenValue)) {
1104 ((QueryModule) env).setPreserveNamespaces(false);
1105 } else {
1106 grumble("copy-namespaces must be followed by 'preserve' or 'no-preserve'");
1107 }
1108 nextToken();
1109 expect(Token.COMMA);
1110 nextToken();
1111 expect(Token.NAME);
1112 if ("inherit".equals(t.currentTokenValue)) {
1113 ((QueryModule) env).setInheritNamespaces(true);
1114 } else if ("no-inherit".equals(t.currentTokenValue)) {
1115 ((QueryModule) env).setInheritNamespaces(false);
1116 } else {
1117 grumble("After the comma in the copy-namespaces declaration, expected 'inherit' or 'no-inherit'");
1118 }
1119 nextToken();
1120 }
1121
1122
1123 /**
1124 * Parse the "declare construction" declaration.
1125 * Syntax: &lt;"declare" "construction"&gt; ("preserve" | "strip")
1126 *
1127 * @throws XPathException if parsing fails
1128 */
1129
1130 private void parseConstructionDeclaration() throws XPathException {
1131 if (foundConstructionDeclaration) {
1132 grumble("declare construction appears more than once", "XQST0067");
1133 }
1134 foundConstructionDeclaration = true;
1135 nextToken();
1136 expect(Token.NAME);
1137 int val;
1138 if ("preserve".equals(t.currentTokenValue)) {
1139 val = Validation.PRESERVE;
1140 // if (!env.getExecutable().isSchemaAware()) {
1141 // grumble("construction mode preserve is allowed only with a schema-aware query");
1142 // }
1143 } else if ("strip".equals(t.currentTokenValue)) {
1144 val = Validation.STRIP;
1145 } else {
1146 grumble("construction mode must be 'preserve' or 'strip'");
1147 val = Validation.STRIP;
1148 }
1149 ((QueryModule) env).setConstructionMode(val);
1150 nextToken();
1151 }
1152
1153 /**
1154 * Parse the "declare revalidation" declaration.
1155 * Syntax: not allowed unless XQuery update is in use
1156 *
1157 * @throws XPathException if the syntax is incorrect, or is not allowed in this XQuery processor
1158 */
1159
1160 protected void parseRevalidationDeclaration() throws XPathException {
1161 grumble("declare revalidation is allowed only in XQuery Update");
1162 }
1163
1164 /**
1165 * Parse (and process) the schema import declaration.
1166 * SchemaImport ::= "import" "schema" SchemaPrefix? URILiteral ("at" URILiteral ("," URILiteral)*)?
1167 * SchemaPrefix ::= ("namespace" NCName "=") | ("default" "element" "namespace")
1168 *
1169 * @throws XPathException if parsing fails
1170 */
1171
1172 private void parseSchemaImport() throws XPathException {
1173 ensureSchemaAware("import schema");
1174 Import sImport = new Import();
1175 String prefix = null;
1176 sImport.namespaceURI = null;
1177 sImport.locationURIs = new ArrayList<>(5);
1178 nextToken();
1179 if (isKeyword("namespace")) {
1180 prefix = readNamespaceBinding();
1181 } else if (isKeyword("default")) {
1182 nextToken();
1183 if (!isKeyword("element")) {
1184 grumble("In 'import schema', expected 'element namespace'");
1185 }
1186 nextToken();
1187 if (!isKeyword("namespace")) {
1188 grumble("In 'import schema', expected keyword 'namespace'");
1189 }
1190 nextToken();
1191 prefix = "";
1192 }
1193 if (t.currentToken == Token.STRING_LITERAL) {
1194 String uri = uriLiteral(t.currentTokenValue);
1195 checkProhibitedPrefixes(prefix, uri);
1196 sImport.namespaceURI = uri;
1197 nextToken();
1198 if (isKeyword("at")) {
1199 nextToken();
1200 expect(Token.STRING_LITERAL);
1201 sImport.locationURIs.add(uriLiteral(t.currentTokenValue));
1202 nextToken();
1203 while (t.currentToken == Token.COMMA) {
1204 nextToken();
1205 expect(Token.STRING_LITERAL);
1206 sImport.locationURIs.add(uriLiteral(t.currentTokenValue));
1207 nextToken();
1208 }
1209 } else if (t.currentToken != Token.SEMICOLON) {
1210 grumble("After the target namespace URI, expected 'at' or ';'");
1211 }
1212 } else {
1213 grumble("After 'import schema', expected 'namespace', 'default', or a string-literal");
1214 }
1215 if (prefix != null) {
1216 try {
1217 if (prefix.isEmpty()) {
1218 ((QueryModule) env).setDefaultElementNamespace(sImport.namespaceURI);
1219 } else {
1220 if (sImport.namespaceURI == null || "".equals(sImport.namespaceURI)) {
1221 grumble("A prefix cannot be bound to the null namespace", "XQST0057");
1222 }
1223 ((QueryModule) env).declarePrologNamespace(prefix, sImport.namespaceURI);
1224 }
1225 } catch (XPathException err) {
1226 err.setLocator(makeLocation());
1227 reportError(err);
1228 }
1229 }
1230 for (Object schemaImport : schemaImports) {
1231 Import imp = (Import) schemaImport;
1232 if (imp.namespaceURI.equals(sImport.namespaceURI)) {
1233 grumble("Schema namespace '" + sImport.namespaceURI + "' is imported more than once", "XQST0058");
1234 break;
1235 }
1236 }
1237
1238 schemaImports.add(sImport);
1239
1240 }
1241
1242 private String readNamespaceBinding() throws XPathException {
1243 t.setState(Tokenizer.DEFAULT_STATE);
1244 nextToken();
1245 expect(Token.NAME);
1246 String prefix = t.currentTokenValue;
1247 nextToken();
1248 expect(Token.EQUALS);
1249 nextToken();
1250 return prefix;
1251 }
1252
1253 protected void ensureSchemaAware(String featureName) throws XPathException {
1254 if (!env.getConfiguration().isLicensedFeature(Configuration.LicenseFeature.ENTERPRISE_XQUERY)) {
1255 throw new XPathException("This Saxon version and license does not allow use of '" + featureName + "'", "XQST0009");
1256 }
1257 env.getConfiguration().checkLicensedFeature(Configuration.LicenseFeature.ENTERPRISE_XQUERY, featureName, -1);
1258 getExecutable().setSchemaAware(true);
1259 getStaticContext().getPackageData().setSchemaAware(true);
1260 }
1261
1262 private void applySchemaImport(/*@NotNull*/ Import sImport) throws XPathException {
1263
1264 // Do the importing
1265
1266 Configuration config = env.getConfiguration();
1267 //noinspection SynchronizationOnLocalVariableOrMethodParameter
1268 synchronized (config) {
1269 if (!config.isSchemaAvailable(sImport.namespaceURI)) {
1270 if (!sImport.locationURIs.isEmpty()) {
1271 try {
1272 PipelineConfiguration pipe = config.makePipelineConfiguration();
1273 config.readMultipleSchemas(pipe, env.getStaticBaseURI(), sImport.locationURIs, sImport.namespaceURI);
1274 namespacesToBeSealed.add(sImport.namespaceURI);
1275 } catch (SchemaException err) {
1276 grumble("Error in schema " + sImport.namespaceURI + ": " + err.getMessage(), "XQST0059");
1277 }
1278 } else if (sImport.namespaceURI.equals(NamespaceConstant.XML) ||
1279 sImport.namespaceURI.equals(NamespaceConstant.FN)||
1280 sImport.namespaceURI.equals(NamespaceConstant.SCHEMA_INSTANCE)) {
1281 config.addSchemaForBuiltInNamespace(sImport.namespaceURI);
1282 } else {
1283 grumble("Unable to locate requested schema " + sImport.namespaceURI, "XQST0059");
1284 }
1285 }
1286 ((QueryModule) env).addImportedSchema(sImport.namespaceURI, env.getStaticBaseURI(), sImport.locationURIs);
1287 }
1288 }
1289
1290 /**
1291 * Parse (and expand) the module import declaration.
1292 * Syntax: "import" "module" ("namespace" NCName "=")? uri ("at" uri ("," uri)*)? ";"
1293 *
1294 * @throws net.sf.saxon.trans.XPathException
1295 * if a static error is encountered
1296 */
1297
1298 private void parseModuleImport() throws XPathException {
1299 QueryModule thisModule = (QueryModule) env;
1300 Import mImport = new Import();
1301 String prefix = null;
1302 mImport.namespaceURI = null;
1303 mImport.locationURIs = new ArrayList<>(5);
1304 nextToken();
1305 if (t.currentToken == Token.NAME && t.currentTokenValue.equals("namespace")) {
1306 prefix = readNamespaceBinding();
1307 }
1308 if (t.currentToken == Token.STRING_LITERAL) {
1309 String uri = uriLiteral(t.currentTokenValue);
1310 checkProhibitedPrefixes(prefix, uri);
1311 mImport.namespaceURI = uri;
1312 if (mImport.namespaceURI.isEmpty()) {
1313 grumble("Imported module namespace cannot be \"\"", "XQST0088");
1314 mImport.namespaceURI = "http://saxon.fallback.namespace/line" + t.getLineNumber(); // for error recovery
1315 }
1316 if (importedModules.contains(mImport.namespaceURI)) {
1317 grumble("Two 'import module' declarations specify the same module namespace", "XQST0047");
1318 }
1319 importedModules.add(mImport.namespaceURI);
1320 ((QueryModule) env).addImportedNamespace(mImport.namespaceURI);
1321 nextToken();
1322 if (isKeyword("at")) {
1323 do {
1324 nextToken();
1325 expect(Token.STRING_LITERAL);
1326 mImport.locationURIs.add(uriLiteral(t.currentTokenValue));
1327 nextToken();
1328 } while (t.currentToken == Token.COMMA);
1329 }
1330 } else {
1331 grumble("After 'import module', expected 'namespace' or a string-literal");
1332 }
1333 if (prefix != null) {
1334 try {
1335 if (mImport.namespaceURI.equals(thisModule.getModuleNamespace()) &&
1336 mImport.namespaceURI.equals(thisModule.checkURIForPrefix(prefix))) {
1337 // then do nothing: a duplicate declaration in this situation is not an error
1338 } else {
1339 thisModule.declarePrologNamespace(prefix, mImport.namespaceURI);
1340 }
1341 } catch (XPathException err) {
1342 err.setLocator(makeLocation());
1343 reportError(err);
1344 }
1345 }
1346
1347 // // Check that this import would not create a cycle involving a change of namespace
1348 // if (!disableCycleChecks) {
1349 // if (!mImport.namespaceURI.equals(((QueryModule)env).getModuleNamespace())) {
1350 // QueryModule parent = (QueryModule)env;
1351 // if (!parent.mayImport(mImport.namespaceURI)) {
1352 // StaticError err = new StaticError("A module cannot import itself directly or indirectly, unless all modules in the cycle are in the same namespace");
1353 // err.setErrorCode("XQST0073");
1354 // throw err;
1355 // }
1356 // }
1357 // }
1358
1359 moduleImports.add(mImport);
1360 }
1361
1362 public void applyModuleImport(/*@NotNull*/ Import mImport) throws XPathException {
1363 List<QueryModule> existingModules;
1364
1365 // resolve the location URIs against the base URI
1366 for (int i = 0; i < mImport.locationURIs.size(); i++) {
1367 try {
1368 String uri = mImport.locationURIs.get(i);
1369 URI abs = ResolveURI.makeAbsolute(uri, env.getStaticBaseURI());
1370 mImport.locationURIs.set(i, abs.toString());
1371 } catch (URISyntaxException e) {
1372 grumble("Invalid URI " + mImport.locationURIs.get(i) + ": " + e.getMessage(), "XQST0046");
1373 }
1374 }
1375
1376 // See if the URI is that of a separately-compiled query library
1377 QueryLibrary lib = ((QueryModule) env).getUserQueryContext().getCompiledLibrary(mImport.namespaceURI);
1378 if (lib != null) {
1379 executable.addQueryLibraryModule(lib);
1380 existingModules = new ArrayList<>();
1381 existingModules.add(lib);
1382 lib.link((QueryModule) env);
1383
1384 } else if (!env.getConfiguration().getBooleanProperty(Feature.XQUERY_MULTIPLE_MODULE_IMPORTS)) {
1385 // Unless this configuration option is set, if we already know a module with the right module URI, then we
1386 // use it irrespective of its location URI.
1387 List<QueryModule> list = executable.getQueryLibraryModules(mImport.namespaceURI);
1388 if (list != null && !list.isEmpty()) {
1389 return;
1390 }
1391 } else {
1392
1393 for (int h = mImport.locationURIs.size() - 1; h >= 0; h--) {
1394 if (executable.isQueryLocationHintProcessed(mImport.locationURIs.get(h))) {
1395 mImport.locationURIs.remove(h);
1396 }
1397 }
1398
1399 }
1400
1401 // If there are no location URIs left, and we already know a module with the right module URI.
1402
1403 if (mImport.locationURIs.isEmpty()) {
1404 List<QueryModule> list = executable.getQueryLibraryModules(mImport.namespaceURI);
1405 if (list != null && !list.isEmpty()) {
1406 return;
1407 }
1408 }
1409
1410 // Call the module URI resolver to find the remaining modules
1411
1412 ModuleURIResolver resolver = ((QueryModule) env).getUserQueryContext().getModuleURIResolver();
1413
1414 String[] hints = new String[mImport.locationURIs.size()];
1415 for (int h = 0; h < hints.length; h++) {
1416 hints[h] = mImport.locationURIs.get(h);
1417 }
1418 StreamSource[] sources = null;
1419 if (resolver != null) {
1420 try {
1421 sources = resolver.resolve(mImport.namespaceURI, env.getStaticBaseURI(), hints);
1422 } catch (XPathException err) {
1423 grumble("Failed to resolve URI of imported module: " + err.getMessage(), "XQST0059");
1424 }
1425 }
1426 if (sources == null) {
1427 if (hints.length == 0) {
1428 grumble("Cannot locate module for namespace " + mImport.namespaceURI, "XQST0059");
1429 }
1430 resolver = env.getConfiguration().getStandardModuleURIResolver();
1431 sources = resolver.resolve(mImport.namespaceURI, env.getStaticBaseURI(), hints);
1432 }
1433
1434 for (String hint : mImport.locationURIs) {
1435 executable.addQueryLocationHintProcessed(hint);
1436 }
1437
1438 for (int m = 0; m < sources.length; m++) {
1439 StreamSource ss = sources[m];
1440 String baseURI = ss.getSystemId();
1441 if (baseURI == null) {
1442 if (m < hints.length) {
1443 baseURI = hints[m];
1444 ss.setSystemId(hints[m]);
1445 } else {
1446 grumble("No base URI available for imported module", "XQST0059");
1447 }
1448 }
1449 // Although the module hadn't been loaded when we started, it might have been loaded since, as
1450 // a result of a reference from another imported module.
1451 // TODO: use similar logic when loading schema modules
1452 existingModules = executable.getQueryLibraryModules(mImport.namespaceURI);
1453 boolean loaded = false;
1454 if (existingModules != null && m < hints.length) {
1455 for (QueryModule existingModule : existingModules) {
1456 URI uri = existingModule.getLocationURI();
1457 if (uri != null && uri.toString().equals(mImport.locationURIs.get(m))) {
1458 loaded = true;
1459 break;
1460 }
1461 }
1462 }
1463 if (loaded) {
1464 break;
1465 }
1466
1467 try {
1468 String queryText = QueryReader.readSourceQuery(ss, charChecker);
1469 try {
1470 if (ss.getInputStream() != null) {
1471 ss.getInputStream().close();
1472 } else if (ss.getReader() != null) {
1473 ss.getReader().close();
1474 }
1475 } catch (IOException e) {
1476 throw new XPathException("Failure while closing file for imported query module");
1477 }
1478 QueryModule.makeQueryModule(
1479 baseURI, executable, (QueryModule) env, queryText, mImport.namespaceURI
1480 );
1481 } catch (XPathException err) {
1482 err.maybeSetLocation(makeLocation());
1483 reportError(err);
1484 }
1485 }
1486 }
1487
1488 /**
1489 * Parse the Base URI declaration.
1490 * Syntax: &lt;"declare" "base-uri"&gt; uri-literal
1491 *
1492 * @throws XPathException if a static error is found
1493 */
1494
1495 private void parseBaseURIDeclaration() throws XPathException {
1496 if (foundBaseURIDeclaration) {
1497 grumble("Base URI Declaration may only appear once", "XQST0032");
1498 }
1499 foundBaseURIDeclaration = true;
1500 nextToken();
1501 expect(Token.STRING_LITERAL);
1502 String uri = uriLiteral(t.currentTokenValue);
1503 try {
1504 // if the supplied URI is relative, try to resolve it
1505 URI baseURI = new URI(uri);
1506 if (!baseURI.isAbsolute()) {
1507 String oldBase = env.getStaticBaseURI();
1508 uri = ResolveURI.makeAbsolute(uri, oldBase).toString();
1509 }
1510 ((QueryModule) env).setBaseURI(uri);
1511 } catch (URISyntaxException err) {
1512 // The spec says this "is not intrinsically an error", but can cause a failure later
1513 ((QueryModule) env).setBaseURI(uri);
1514 }
1515 nextToken();
1516 }
1517
1518
1519 /**
1520 * Parse a named decimal format declaration.
1521 * "declare" "decimal-format" QName (property "=" string-literal)*
1522 *
1523 * @throws XPathException if parsing fails
1524 */
1525
1526 private void parseDecimalFormatDeclaration() throws XPathException {
1527 nextToken();
1528 expect(Token.NAME);
1529 StructuredQName formatName = makeStructuredQName(t.currentTokenValue, "");
1530 if (env.getDecimalFormatManager().getNamedDecimalFormat(formatName) != null) {
1531 grumble("Duplicate declaration of decimal-format " + formatName.getDisplayName(), "XQST0111");
1532 }
1533 nextToken();
1534 parseDecimalFormatProperties(formatName);
1535 }
1536
1537 /**
1538 * Parse a default decimal format declaration
1539 * "declare" "default" "decimal-format" (property "=" string-literal)*
1540 *
1541 * @throws XPathException if parsing fails
1542 */
1543
1544 private void parseDefaultDecimalFormat() throws XPathException {
1545 if (foundDefaultDecimalFormat) {
1546 grumble("Duplicate declaration of default decimal-format", "XQST0111");
1547 }
1548 foundDefaultDecimalFormat = true;
1549 parseDecimalFormatProperties(null);
1550 }
1551
1552 private void parseDecimalFormatProperties(/*@Nullable*/ StructuredQName formatName) throws XPathException {
1553 int outerOffset = t.currentTokenStartOffset;
1554 DecimalFormatManager dfm = env.getDecimalFormatManager();
1555 DecimalSymbols dfs = formatName == null ? dfm.getDefaultDecimalFormat() : dfm.obtainNamedDecimalFormat(formatName);
1556 dfs.setHostLanguage(Configuration.XQUERY, 31);
1557 Set<String> propertyNames = new HashSet<>(10);
1558 while (t.currentToken != Token.SEMICOLON) {
1559 int offset = t.currentTokenStartOffset;
1560 String propertyName = t.currentTokenValue;
1561 if (propertyNames.contains(propertyName)) {
1562 grumble("Property name " + propertyName + " is defined more than once", "XQST0114", offset);
1563 }
1564 nextToken();
1565 expect(Token.EQUALS);
1566 nextToken();
1567 expect(Token.STRING_LITERAL);
1568 String propertyValue = unescape(t.currentTokenValue).toString();
1569 nextToken();
1570 propertyNames.add(propertyName);
1571 switch (propertyName) {
1572 case "decimal-separator":
1573 dfs.setDecimalSeparator(propertyValue);
1574 break;
1575 case "grouping-separator":
1576 dfs.setGroupingSeparator(propertyValue);
1577 break;
1578 case "infinity":
1579 dfs.setInfinity(propertyValue);
1580 break;
1581 case "minus-sign":
1582 dfs.setMinusSign(propertyValue);
1583 break;
1584 case "NaN":
1585 dfs.setNaN(propertyValue);
1586 break;
1587 case "percent":
1588 dfs.setPercent(propertyValue);
1589 break;
1590 case "per-mille":
1591 dfs.setPerMille(propertyValue);
1592 break;
1593 case "zero-digit":
1594 try {
1595 dfs.setZeroDigit(propertyValue);
1596 } catch (XPathException err) {
1597 err.setErrorCode("XQST0097");
1598 throw err;
1599 }
1600 break;
1601 case "digit":
1602 dfs.setDigit(propertyValue);
1603 break;
1604 case "pattern-separator":
1605 dfs.setPatternSeparator(propertyValue);
1606 break;
1607 case "exponent-separator":
1608 dfs.setExponentSeparator(propertyValue);
1609 break;
1610 default:
1611 grumble("Unknown decimal-format property: " + propertyName, "XPST0003", offset);
1612 break;
1613 }
1614 }
1615
1616
1617 try {
1618 dfs.checkConsistency(formatName);
1619 } catch (XPathException err) {
1620 grumble(err.getMessage(), "XQST0098", outerOffset);
1621 }
1622
1623 }
1624
1625 /**
1626 * Parse the "default function namespace" declaration.
1627 * Syntax: &lt;"declare" "default" "function" "namespace"&gt; StringLiteral
1628 *
1629 * @throws XPathException to indicate a syntax error
1630 */
1631
1632 private void parseDefaultFunctionNamespace() throws XPathException {
1633 if (foundDefaultFunctionNamespace) {
1634 grumble("default function namespace appears more than once", "XQST0066");
1635 }
1636 foundDefaultFunctionNamespace = true;
1637 nextToken();
1638 expect(Token.NAME);
1639 if (!"namespace".equals(t.currentTokenValue)) {
1640 grumble("After 'declare default function', expected 'namespace'");
1641 }
1642 nextToken();
1643 expect(Token.STRING_LITERAL);
1644 String uri = uriLiteral(t.currentTokenValue);
1645 if (uri.equals(NamespaceConstant.XML) || uri.equals(NamespaceConstant.XMLNS)) {
1646 grumble("Reserved namespace used as default element/type namespace", "XQST0070");
1647 }
1648 ((QueryModule) env).setDefaultFunctionNamespace(uri);
1649 nextToken();
1650 }
1651
1652 /**
1653 * Parse the "default element namespace" declaration.
1654 * Syntax: &lt;"declare" "default" "element" "namespace"&gt; StringLiteral
1655 *
1656 * @throws XPathException to indicate a syntax error
1657 */
1658
1659 private void parseDefaultElementNamespace() throws XPathException {
1660 if (foundDefaultElementNamespace) {
1661 grumble("default element namespace appears more than once", "XQST0066");
1662 }
1663 foundDefaultElementNamespace = true;
1664 nextToken();
1665 expect(Token.NAME);
1666 if (!"namespace".equals(t.currentTokenValue)) {
1667 grumble("After 'declare default element', expected 'namespace'");
1668 }
1669 nextToken();
1670 expect(Token.STRING_LITERAL);
1671 String uri = uriLiteral(t.currentTokenValue);
1672 if (uri.equals(NamespaceConstant.XML) || uri.equals(NamespaceConstant.XMLNS)) {
1673 grumble("Reserved namespace used as default element/type namespace", "XQST0070");
1674 }
1675 ((QueryModule) env).setDefaultElementNamespace(uri);
1676 nextToken();
1677 }
1678
1679 /**
1680 * Parse a namespace declaration in the Prolog.
1681 * Syntax: &lt;"declare" "namespace"&gt; NCName "=" StringLiteral
1682 *
1683 * @throws XPathException if parsing fails or a static error is found
1684 */
1685
1686 private void parseNamespaceDeclaration() throws XPathException {
1687 nextToken();
1688 expect(Token.NAME);
1689 String prefix = t.currentTokenValue;
1690 if (!NameChecker.isValidNCName(prefix)) {
1691 grumble("Invalid namespace prefix " + Err.wrap(prefix));
1692 }
1693 nextToken();
1694 expect(Token.EQUALS);
1695 nextToken();
1696 expect(Token.STRING_LITERAL);
1697 String uri = uriLiteral(t.currentTokenValue);
1698 checkProhibitedPrefixes(prefix, uri);
1699 if ("xml".equals(prefix)) {
1700 // disallowed here even if bound to the correct namespace - erratum XQ.E19
1701 grumble("Namespace prefix 'xml' cannot be declared", "XQST0070");
1702 }
1703 try {
1704 ((QueryModule) env).declarePrologNamespace(prefix, uri);
1705 } catch (XPathException err) {
1706 err.setLocator(makeLocation());
1707 reportError(err);
1708 }
1709 nextToken();
1710 }
1711
1712 /**
1713 * Check that a namespace declaration does not use a prohibited prefix or URI (xml or xmlns)
1714 *
1715 * @param prefix the prefix to be tested
1716 * @param uri the URI being declared
1717 * @throws XPathException if the prefix is prohibited
1718 */
1719
1720 private void checkProhibitedPrefixes(/*@Nullable*/ String prefix, /*@Nullable*/ String uri) throws XPathException {
1721 if (prefix != null && !prefix.isEmpty() && !NameChecker.isValidNCName(prefix)) {
1722 grumble("The namespace prefix " + Err.wrap(prefix) + " is not a valid NCName");
1723 }
1724 if (prefix == null) {
1725 prefix = "";
1726 }
1727 if (uri == null) {
1728 uri = "";
1729 }
1730 if ("xmlns".equals(prefix)) {
1731 grumble("The namespace prefix 'xmlns' cannot be redeclared", "XQST0070");
1732 }
1733 if (uri.equals(NamespaceConstant.XMLNS)) {
1734 grumble("The xmlns namespace URI is reserved", "XQST0070");
1735 }
1736 if (uri.equals(NamespaceConstant.XML) && !prefix.equals("xml")) {
1737 grumble("The XML namespace cannot be bound to any prefix other than 'xml'", "XQST0070");
1738 }
1739 if (prefix.equals("xml") && !uri.equals(NamespaceConstant.XML)) {
1740 grumble("The prefix 'xml' cannot be bound to any namespace other than " + NamespaceConstant.XML, "XQST0070");
1741 }
1742 }
1743
1744 /**
1745 * Parse a global variable definition.
1746 * &lt;"declare" "variable" "$"&gt; VarName TypeDeclaration?
1747 * ((":=" ExprSingle ) | "external")
1748 * XQuery 3.0 allows "external := ExprSingle"
1749 *
1750 * @param annotations derived from any %-annotations present in XQuery 3.0
1751 * @throws XPathException if a static error is found
1752 */
1753
1754 private void parseVariableDeclaration(AnnotationList annotations) throws XPathException {
1755 int offset = t.currentTokenStartOffset;
1756 GlobalVariable var = new GlobalVariable();
1757 var.setPackageData(env.getPackageData());
1758 var.setLineNumber(t.getLineNumber() + 1);
1759 var.setSystemId(env.getSystemId());
1760 if (annotations != null) {
1761 var.setPrivate(annotations.includes(Annotation.PRIVATE));
1762 }
1763 nextToken();
1764 expect(Token.DOLLAR);
1765 t.setState(Tokenizer.BARE_NAME_STATE);
1766 nextToken();
1767 expect(Token.NAME);
1768 String varName = t.currentTokenValue;
1769 StructuredQName varQName = makeStructuredQName(t.currentTokenValue, "");
1770 assert varQName != null;
1771 var.setVariableQName(varQName);
1772
1773 String uri = varQName.getURI();
1774 String moduleURI = ((QueryModule) env).getModuleNamespace();
1775 if (moduleURI != null && !moduleURI.equals(uri)) {
1776 grumble("A variable declared in a library module must be in the module namespace", "XQST0048", offset);
1777 }
1778
1779 nextToken();
1780 SequenceType requiredType = SequenceType.ANY_SEQUENCE;
1781 if (t.currentToken == Token.AS) {
1782 t.setState(Tokenizer.SEQUENCE_TYPE_STATE);
1783 nextToken();
1784 requiredType = parseSequenceType();
1785 }
1786 var.setRequiredType(requiredType);
1787
1788 if (t.currentToken == Token.ASSIGN) {
1789 t.setState(Tokenizer.DEFAULT_STATE);
1790 nextToken();
1791 Expression exp = parseExprSingle();
1792 var.setSelectExpression(makeTracer(offset, exp, StandardNames.XSL_VARIABLE, varQName));
1793 } else if (t.currentToken == Token.NAME) {
1794 if ("external".equals(t.currentTokenValue)) {
1795 GlobalParam par = new GlobalParam();
1796 par.setPackageData(env.getPackageData());
1797 //par.setExecutable(var.getExecutable());
1798 par.setLineNumber(var.getLineNumber());
1799 par.setSystemId(var.getSystemId());
1800 par.setVariableQName(var.getVariableQName());
1801 par.setRequiredType(var.getRequiredType());
1802 var = par;
1803 nextToken();
1804 if (t.currentToken == Token.ASSIGN) {
1805 t.setState(Tokenizer.DEFAULT_STATE);
1806 nextToken();
1807 Expression exp = parseExprSingle();
1808 var.setSelectExpression(makeTracer(offset, exp, StandardNames.XSL_VARIABLE, varQName));
1809 }
1810
1811 } else {
1812 grumble("Variable must either be initialized or be declared as external");
1813 }
1814 } else {
1815 grumble("Expected ':=' or 'external' in variable declaration");
1816 }
1817
1818 QueryModule qenv = (QueryModule) env;
1819 RetainedStaticContext rsc = env.makeRetainedStaticContext();
1820 var.setRetainedStaticContext(rsc);
1821 if (var.getBody() != null) {
1822 ExpressionTool.setDeepRetainedStaticContext(var.getBody(), rsc);
1823 }
1824 if (qenv.getModuleNamespace() != null &&
1825 !uri.equals(qenv.getModuleNamespace())) {
1826 grumble("Variable " + Err.wrap(varName, Err.VARIABLE) + " is not defined in the module namespace");
1827 }
1828 try {
1829 qenv.declareVariable(var);
1830 } catch (XPathException e) {
1831 grumble(e.getMessage(), e.getErrorCodeQName(), -1);
1832 }
1833 }
1834
1835
1836 /**
1837 * Parse a context item declaration.
1838 * "declare" "context" "item" TypeDeclaration?
1839 * ((":=" ExprSingle ) | ("external" (":=" ExprSingle ))
1840 *
1841 * @throws XPathException if parsing fails
1842 */
1843
1844 private void parseContextItemDeclaration() throws XPathException {
1845 int offset = t.currentTokenStartOffset;
1846 nextToken();
1847 if (!isKeyword("item")) {
1848 grumble("After 'declare context', expected 'item'");
1849 }
1850 if (foundContextItemDeclaration) {
1851 grumble("More than one context item declaration found", "XQST0099", offset);
1852 }
1853 foundContextItemDeclaration = true;
1854
1855 GlobalContextRequirement req = new GlobalContextRequirement();
1856 req.setAbsentFocus(false);
1857
1858 t.setState(Tokenizer.BARE_NAME_STATE);
1859
1860 nextToken();
1861 ItemType requiredType = AnyItemType.getInstance();
1862 if (t.currentToken == Token.AS) {
1863 t.setState(Tokenizer.SEQUENCE_TYPE_STATE);
1864 nextToken();
1865 requiredType = parseItemType();
1866 }
1867 req.addRequiredItemType(requiredType);
1868
1869 if (t.currentToken == Token.ASSIGN) {
1870 if (!((QueryModule) env).isMainModule()) {
1871 grumble("The context item must not be initialized in a library module", "XQST0113");
1872 }
1873 t.setState(Tokenizer.DEFAULT_STATE);
1874 nextToken();
1875 Expression exp = parseExprSingle();
1876 exp.setRetainedStaticContext(env.makeRetainedStaticContext());
1877 RoleDiagnostic role = new RoleDiagnostic(RoleDiagnostic.CONTEXT_ITEM, "context item declaration", 0);
1878 exp = CardinalityChecker.makeCardinalityChecker(exp, StaticProperty.EXACTLY_ONE, role);
1879 ExpressionVisitor visitor = ExpressionVisitor.make(env);
1880 exp = exp.simplify();
1881 ContextItemStaticInfo info = env.getConfiguration().makeContextItemStaticInfo(AnyItemType.getInstance(), true);
1882 exp.setRetainedStaticContext(env.makeRetainedStaticContext());
1883 exp = exp.typeCheck(visitor, info);
1884 req.setDefaultValue(exp);
1885 req.setExternal(false);
1886 } else if (t.currentToken == Token.NAME && "external".equals(t.currentTokenValue)) {
1887 req.setAbsentFocus(false);
1888 req.setExternal(true);
1889 nextToken();
1890 if (t.currentToken == Token.ASSIGN) {
1891 if (!((QueryModule) env).isMainModule()) {
1892 grumble("The context item must not be initialized in a library module", "XQST0113");
1893 }
1894 t.setState(Tokenizer.DEFAULT_STATE);
1895 nextToken();
1896 Expression exp = parseExprSingle();
1897 RoleDiagnostic role = new RoleDiagnostic(RoleDiagnostic.CONTEXT_ITEM, "context item declaration", 0);
1898 exp = CardinalityChecker.makeCardinalityChecker(exp, StaticProperty.EXACTLY_ONE, role);
1899 exp.setRetainedStaticContext(env.makeRetainedStaticContext());
1900 req.setDefaultValue(exp);
1901 }
1902 } else {
1903 grumble("Expected ':=' or 'external' in context item declaration");
1904 }
1905
1906 Executable exec = getExecutable();
1907 if (exec.getGlobalContextRequirement() != null) {
1908 // the context item is already declared in another module. Compare the required types
1909 GlobalContextRequirement gcr = exec.getGlobalContextRequirement();
1910 if (gcr.getDefaultValue() == null && req.getDefaultValue() != null) {
1911 gcr.setDefaultValue(req.getDefaultValue());
1912 }
1913 for (ItemType otherType : gcr.getRequiredItemTypes()) {
1914 if (otherType != AnyItemType.getInstance()) {
1915 TypeHierarchy th = env.getConfiguration().getTypeHierarchy();
1916 int rel = th.relationship(requiredType, otherType);
1917 if (rel == TypeHierarchy.DISJOINT) {
1918 // the two types are incompatible: fail now
1919 grumble("Different modules specify incompatible requirements for the type of the initial context item", "XPTY0004");
1920 }
1921 }
1922 }
1923 gcr.addRequiredItemType(requiredType);
1924 } else {
1925 exec.setGlobalContextRequirement(req);
1926 }
1927 }
1928
1929 /**
1930 * Parse a function declaration.
1931 * <p>Syntax: <br />
1932 * &lt;"declare" "function"&gt; QName "(" ParamList? ")" ("as" SequenceType)?
1933 * (EnclosedExpr | "external")
1934 * </p>
1935 * <p>On entry, the "declare function" has already been recognized</p>
1936 *
1937 * @param annotations the list of annotations that have been encountered for this function declaration
1938 * @throws XPathException if a syntax error is found
1939 */
1940
1941 public void parseFunctionDeclaration(AnnotationList annotations) throws XPathException {
1942
1943 if (annotations.includes(SAXON_MEMO_FUNCTION)) {
1944 if (env.getConfiguration().getEditionCode().equals("HE")) {
1945 warning("saxon:memo-function option is ignored under Saxon-HE");
1946 } else {
1947 memoFunction = true;
1948 }
1949 }
1950
1951 // the next token should be the < QNAME "("> pair
1952 int offset = t.currentTokenStartOffset;
1953 t.setState(Tokenizer.DEFAULT_STATE);
1954 nextToken();
1955 expect(Token.FUNCTION);
1956
1957 String uri;
1958 StructuredQName qName;
1959 if (t.currentTokenValue.indexOf(':') < 0) {
1960 uri = env.getDefaultFunctionNamespace();
1961 qName = new StructuredQName("", uri, t.currentTokenValue);
1962 } else {
1963 qName = makeStructuredQName(t.currentTokenValue, "");
1964 uri = qName.getURI();
1965 }
1966
1967 if (uri.isEmpty()) {
1968 grumble("The function must be in a namespace", "XQST0060");
1969 }
1970
1971 String moduleURI = ((QueryModule) env).getModuleNamespace();
1972 if (moduleURI != null && !moduleURI.equals(uri)) {
1973 grumble("A function in a library module must be in the module namespace", "XQST0048");
1974 }
1975
1976 if (isReservedInQuery(uri)) {
1977 grumble("The function name " + t.currentTokenValue + " is in a reserved namespace", "XQST0045");
1978 }
1979
1980 XQueryFunction func = new XQueryFunction();
1981 func.setFunctionName(qName);
1982 func.setResultType(SequenceType.ANY_SEQUENCE);
1983 func.setBody(null);
1984 Location loc = makeNestedLocation(env.getContainingLocation(), t.getLineNumber(offset), t.getColumnNumber(offset), null);
1985 func.setLocation(loc);
1986 func.setStaticContext((QueryModule) env);
1987 func.setMemoFunction(memoFunction);
1988 func.setUpdating(annotations.includes(Annotation.UPDATING));
1989 func.setAnnotations(annotations);
1990
1991 nextToken();
1992 HashSet<StructuredQName> paramNames = new HashSet<>(8);
1993 boolean external = false;
1994 if (t.currentToken != Token.RPAR) {
1995 while (true) {
1996 // ParamList ::= Param ("," Param)*
1997 // Param ::= "$" VarName TypeDeclaration?
1998 expect(Token.DOLLAR);
1999 nextToken();
2000 expect(Token.NAME);
2001 StructuredQName argQName = makeStructuredQName(t.currentTokenValue, "");
2002 if (paramNames.contains(argQName)) {
2003 grumble("Duplicate parameter name " + Err.wrap(t.currentTokenValue, Err.VARIABLE), "XQST0039");
2004 }
2005 paramNames.add(argQName);
2006 SequenceType paramType = SequenceType.ANY_SEQUENCE;
2007 nextToken();
2008 if (t.currentToken == Token.AS) {
2009 nextToken();
2010 paramType = parseSequenceType();
2011 }
2012
2013 UserFunctionParameter arg = new UserFunctionParameter();
2014 arg.setRequiredType(paramType);
2015 arg.setVariableQName(argQName);
2016 func.addArgument(arg);
2017 declareRangeVariable(arg);
2018 if (t.currentToken == Token.RPAR) {
2019 break;
2020 } else if (t.currentToken == Token.COMMA) {
2021 nextToken();
2022 } else {
2023 grumble("Expected ',' or ')' after function argument, found '" +
2024 Token.tokens[t.currentToken] + '\'');
2025 }
2026 }
2027 }
2028 t.setState(Tokenizer.BARE_NAME_STATE);
2029 nextToken();
2030 if (t.currentToken == Token.AS) {
2031 if (func.isUpdating()) {
2032 grumble("Cannot specify a return type for an updating function", "XUST0028");
2033 }
2034 t.setState(Tokenizer.SEQUENCE_TYPE_STATE);
2035 nextToken();
2036 func.setResultType(parseSequenceType());
2037 }
2038 if (isKeyword("external")) {
2039 external = true;
2040 } else {
2041 expect(Token.LCURLY);
2042 t.setState(Tokenizer.DEFAULT_STATE);
2043 nextToken();
2044 if (t.currentToken == Token.RCURLY) {
2045 Expression body = Literal.makeEmptySequence();
2046 body.setRetainedStaticContext(env.makeRetainedStaticContext());
2047 setLocation(body);
2048 func.setBody(body);
2049 } else {
2050 Expression body = parseExpression();
2051 func.setBody(body);
2052 ExpressionTool.setDeepRetainedStaticContext(body, env.makeRetainedStaticContext());
2053 }
2054 expect(Token.RCURLY);
2055 lookAhead(); // must be done manually after an RCURLY
2056 }
2057 UserFunctionParameter[] params = func.getParameterDefinitions();
2058 //noinspection UnusedDeclaration
2059 for (UserFunctionParameter param : params) {
2060 undeclareRangeVariable();
2061 }
2062 t.setState(Tokenizer.DEFAULT_STATE);
2063 nextToken();
2064
2065 QueryModule qenv = (QueryModule) env;
2066
2067 if (external) {
2068 parserExtension.handleExternalFunctionDeclaration(this, func);
2069 } else {
2070 try {
2071 qenv.declareFunction(func);
2072 } catch (XPathException e) {
2073 grumble(e.getMessage(), e.getErrorCodeQName(), -1);
2074 }
2075 }
2076 memoFunction = false;
2077 }
2078
2079 public static final StructuredQName SAXON_MEMO_FUNCTION = new StructuredQName("saxon", NamespaceConstant.SAXON, "memo-function");
2080
2081
2082 /**
2083 * Parse a type alias declaration. Allowed only in Saxon-PE and higher
2084 * @throws XPathException if parsing fails
2085 */
2086
2087 protected void parseTypeAliasDeclaration() throws XPathException {
2088 parserExtension.parseTypeAliasDeclaration(this);
2089 }
2090
2091 /**
2092 * Parse an option declaration.
2093 * <p>Syntax:
2094 * &lt;"declare" "option"&gt; QName "string-literal"
2095 * </p>
2096 * <p>On entry, the "declare option" has already been recognized</p>
2097 *
2098 * @throws XPathException if a syntax error is found
2099 */
2100
2101 private void parseOptionDeclaration() throws XPathException {
2102 nextToken();
2103 expect(Token.NAME);
2104 String defaultUri = NamespaceConstant.XQUERY;
2105 StructuredQName varName = makeStructuredQName(t.currentTokenValue, defaultUri);
2106 assert varName != null;
2107 String uri = varName.getURI();
2108
2109 if (uri.isEmpty()) {
2110 grumble("The QName identifying an option declaration must be prefixed", "XPST0081");
2111 return;
2112 }
2113
2114 nextToken();
2115 expect(Token.STRING_LITERAL);
2116 //String value = URILiteral(t.currentTokenValue).trim();
2117 String value = unescape(t.currentTokenValue).toString();
2118
2119 if (uri.equals(NamespaceConstant.OUTPUT)) {
2120 parseOutputDeclaration(varName, value);
2121 } else if (uri.equals(NamespaceConstant.SAXON)) {
2122 String localName = varName.getLocalPart();
2123 switch (localName) {
2124 case "output":
2125 setOutputProperty(value);
2126 break;
2127 case "memo-function":
2128 value = value.trim();
2129 switch (value) {
2130 case "true":
2131 memoFunction = true;
2132 if (env.getConfiguration().getEditionCode().equals("HE")) {
2133 warning("saxon:memo-function option is ignored under Saxon-HE");
2134 }
2135 break;
2136 case "false":
2137 memoFunction = false;
2138 break;
2139 default:
2140 warning("Value of saxon:memo-function must be 'true' or 'false'");
2141 break;
2142 }
2143 break;
2144 case "allow-cycles":
2145 warning("Value of saxon:allow-cycles is ignored");
2146 break;
2147 default:
2148 warning("Unknown Saxon option declaration: " + varName.getDisplayName());
2149 break;
2150 }
2151 }
2152 nextToken();
2153 }
2154
2155 protected void parseOutputDeclaration(StructuredQName varName, String value) throws XPathException {
2156
2157 if (!((QueryModule) env).isMainModule()) {
2158 grumble("Output declarations must not appear in a library module", "XQST0108");
2159 }
2160 String localName = varName.getLocalPart();
2161 if (outputPropertiesSeen.contains(varName)) {
2162 grumble("Duplicate output declaration (" + varName + ")", "XQST0110");
2163 }
2164 outputPropertiesSeen.add(varName);
2165 switch (localName) {
2166 case "parameter-document": {
2167 Source source;
2168 try {
2169 source = env.getConfiguration().getURIResolver().resolve(value, env.getStaticBaseURI());
2170 } catch (TransformerException e) {
2171 throw XPathException.makeXPathException(e);
2172 }
2173 ParseOptions options = new ParseOptions();
2174 options.setSchemaValidationMode(Validation.LAX);
2175 TreeInfo doc = env.getConfiguration().buildDocumentTree(source);
2176 SerializationParamsHandler ph = new SerializationParamsHandler(parameterDocProperties);
2177 ph.setSerializationParams(doc.getRootNode());
2178
2179 CharacterMap characterMap = ph.getCharacterMap();
2180 if (characterMap != null) {
2181 CharacterMapIndex index = new CharacterMapIndex();
2182 index.putCharacterMap(characterMap.getName(), characterMap);
2183 getExecutable().setCharacterMapIndex(index);
2184 parameterDocProperties.setProperty(SaxonOutputKeys.USE_CHARACTER_MAPS, characterMap.getName().getClarkName());
2185 }
2186 break;
2187 }
2188 case "use-character-maps":
2189 grumble("Output declaration use-character-maps cannot appear except in a parameter file", "XQST0109");
2190 break;
2191 default: {
2192 Properties props = getExecutable().getPrimarySerializationProperties().getProperties();
2193 ResultDocument.setSerializationProperty(props,
2194 "", localName,
2195 value,
2196 env.getNamespaceResolver(),
2197 false,
2198 env.getConfiguration());
2199 break;
2200 }
2201 }
2202 }
2203
2204 /**
2205 * Handle a saxon:output option declaration. Format:
2206 * declare option saxon:output "indent = yes"
2207 *
2208 * @param property a property name=value pair. The name is the name of a serialization
2209 * property, potentially as a prefixed QName; the value is the value of the property. A warning
2210 * is output for unrecognized properties or values
2211 */
2212
2213 private void setOutputProperty(/*@NotNull*/ String property) {
2214 int equals = property.indexOf("=");
2215 if (equals < 0) {
2216 badOutputProperty("no equals sign");
2217 } else if (equals == 0) {
2218 badOutputProperty("starts with '=");
2219 }
2220 String keyword = Whitespace.trim(property.substring(0, equals));
2221 String value = equals == property.length() - 1 ? "" : Whitespace.trim(property.substring(equals + 1));
2222
2223 Properties props = getExecutable().getPrimarySerializationProperties().getProperties();
2224 try {
2225 StructuredQName name = makeStructuredQName(keyword, "");
2226 String lname = name.getLocalPart();
2227 String uri = name.getURI();
2228 ResultDocument.setSerializationProperty(props,
2229 uri, lname,
2230 value,
2231 env.getNamespaceResolver(),
2232 false,
2233 env.getConfiguration());
2234 } catch (XPathException e) {
2235 badOutputProperty(e.getMessage());
2236 }
2237 }
2238
2239 private void badOutputProperty(String s) {
2240 warning("Invalid serialization property (" + s + ")");
2241 }
2242
2243 /**
2244 * Parse a FLWOR expression. This replaces the XPath "for" expression.
2245 * Full syntax:
2246 * <p>
2247 * [41] FLWORExpr ::= (ForClause | LetClause)+
2248 * WhereClause? OrderByClause?
2249 * "return" ExprSingle <br />
2250 * [42] ForClause ::= &lt;"for" "$"&gt; VarName TypeDeclaration? PositionalVar? "in" ExprSingle
2251 * ("," "$" VarName TypeDeclaration? PositionalVar? "in" ExprSingle)* <br />
2252 * [43] PositionalVar ::= "at" "$" VarName <br />
2253 * [44] LetClause ::= &lt;"let" "$"&gt; VarName TypeDeclaration? ":=" ExprSingle
2254 * ("," "$" VarName TypeDeclaration? ":=" ExprSingle)* <br />
2255 * [45] WhereClause ::= "where" Expr <br />
2256 * [46] OrderByClause ::= (&lt;"order" "by"&gt; | &lt;"stable" "order" "by"&gt;) OrderSpecList <br />
2257 * [47] OrderSpecList ::= OrderSpec ("," OrderSpec)* <br />
2258 * [48] OrderSpec ::= ExprSingle OrderModifier <br />
2259 * [49] OrderModifier ::= ("ascending" | "descending")?
2260 * (&lt;"empty" "greatest"&gt; | &lt;"empty" "least"&gt;)?
2261 * ("collation" StringLiteral)?
2262 * </p>
2263 *
2264 * @return the resulting subexpression
2265 * @throws XPathException if any error is encountered
2266 */
2267
2268 /*@Nullable*/
2269 protected Expression parseFLWORExpression() throws XPathException {
2270 FLWORExpression flwor = new FLWORExpression();
2271 int exprOffset = t.currentTokenStartOffset;
2272 List<Clause> clauseList = new ArrayList<>(4);
2273 boolean foundOrderBy = false;
2274 boolean foundWhere = false;
2275 while (true) {
2276 int offset = t.currentTokenStartOffset;
2277 if (t.currentToken == Token.FOR) {
2278 parseForClause(flwor, clauseList);
2279 } else if (t.currentToken == Token.LET) {
2280 parseLetClause(flwor, clauseList);
2281 } else if (t.currentToken == Token.COUNT) {
2282 parseCountClause(clauseList);
2283 } else if (t.currentToken == Token.GROUP_BY) {
2284 parseGroupByClause(flwor, clauseList);
2285 } else if (t.currentToken == Token.FOR_TUMBLING || t.currentToken == Token.FOR_SLIDING) {
2286 parseWindowClause(flwor, clauseList);
2287 } else if (t.currentToken == Token.WHERE || isKeyword("where")) {
2288 nextToken();
2289 Expression condition = parseExprSingle();
2290 WhereClause clause = new WhereClause(flwor, condition);
2291 clause.setRepeated(containsLoopingClause(clauseList));
2292 clauseList.add(clause);
2293 foundWhere = true;
2294 } else if (isKeyword("stable") || isKeyword("order")) {
2295 // we read the "stable" keyword but ignore it; Saxon ordering is always stable
2296 if (isKeyword("stable")) {
2297 nextToken();
2298 if (!isKeyword("order")) {
2299 grumble("'stable' must be followed by 'order by'");
2300 }
2301 }
2302 foundOrderBy = true;
2303 TupleExpression tupleExpression = new TupleExpression();
2304 List<LocalVariableReference> vars = new ArrayList<>();
2305 for (Clause c : clauseList) {
2306 for (LocalVariableBinding b : c.getRangeVariables()) {
2307 vars.add(new LocalVariableReference(b));
2308 }
2309 }
2310 tupleExpression.setVariables(vars);
2311 List sortSpecList;
2312 t.setState(Tokenizer.BARE_NAME_STATE);
2313 nextToken();
2314 if (!isKeyword("by")) {
2315 grumble("'order' must be followed by 'by'");
2316 }
2317 t.setState(Tokenizer.DEFAULT_STATE);
2318 nextToken();
2319 sortSpecList = parseSortDefinition();
2320 SortKeyDefinition[] keys = new SortKeyDefinition[sortSpecList.size()];
2321 for (int i = 0; i < keys.length; i++) {
2322 SortSpec spec = (SortSpec) sortSpecList.get(i);
2323 SortKeyDefinition key = new SortKeyDefinition();
2324 key.setSortKey(((SortSpec) sortSpecList.get(i)).sortKey, false);
2325 key.setOrder(new StringLiteral(spec.ascending ? "ascending" : "descending"));
2326 key.setEmptyLeast(spec.emptyLeast);
2327
2328 if (spec.collation != null) {
2329 final StringCollator comparator = env.getConfiguration().getCollation(spec.collation);
2330 if (comparator == null) {
2331 grumble("Unknown collation '" + spec.collation + '\'', "XQST0076");
2332 }
2333 key.setCollation(comparator);
2334 }
2335 keys[i] = key;
2336 }
2337 OrderByClause clause = new OrderByClause(flwor, keys, tupleExpression);
2338 clause.setRepeated(containsLoopingClause(clauseList));
2339 clauseList.add(clause);
2340 } else {
2341 break;
2342 }
2343 setLocation(clauseList.get(clauseList.size() - 1), offset);
2344 }
2345
2346 int returnOffset = t.currentTokenStartOffset;
2347 expect(Token.RETURN);
2348 t.setState(Tokenizer.DEFAULT_STATE);
2349 nextToken();
2350 Expression returnExpression = parseExprSingle();
2351 returnExpression = makeTracer(returnOffset, returnExpression, LocationKind.RETURN_EXPRESSION, null);
2352
2353 // undeclare all the range variables
2354
2355 for (int i = clauseList.size() - 1; i >= 0; i--) {
2356 Clause clause = clauseList.get(i);
2357 for (int n = 0; n < clause.getRangeVariables().length; n++) {
2358 undeclareRangeVariable();
2359 }
2360 }
2361
2362 if (codeInjector != null) {
2363 List<Clause> expandedList = new ArrayList<>(clauseList.size() * 2);
2364 expandedList.add(clauseList.get(0));
2365 for (int i = 1; i < clauseList.size(); i++) {
2366 Clause extra = codeInjector.injectClause(
2367 clauseList.get(i - 1),
2368 env
2369 );
2370 if (extra != null) {
2371 expandedList.add(extra);
2372 }
2373 expandedList.add(clauseList.get(i));
2374 }
2375 Clause extra = codeInjector.injectClause(
2376 clauseList.get(clauseList.size() - 1), env);
2377 if (extra != null) {
2378 expandedList.add(extra);
2379 }
2380 clauseList = expandedList;
2381 }
2382
2383 flwor.init(clauseList, returnExpression);
2384 setLocation(flwor, exprOffset);
2385 return flwor;
2386
2387 }
2388
2389 /**
2390 * Make a LetExpression. This returns an ordinary LetExpression if tracing is off, and an EagerLetExpression
2391 * if tracing is on. This is so that trace events occur in an order that the user can follow.
2392 *
2393 * @return the constructed "let" expression
2394 */
2395
2396 /*@NotNull*/
2397 protected LetExpression makeLetExpression() {
2398 if (((QueryModule)env).getUserQueryContext().isCompileWithTracing()) {
2399 return new EagerLetExpression();
2400 } else {
2401 return new LetExpression();
2402 }
2403 }
2404
2405 protected static boolean containsLoopingClause(List<Clause> clauseList) {
2406 for (Clause c : clauseList) {
2407 if (FLWORExpression.isLoopingClause(c)) {
2408 return true;
2409 }
2410 }
2411 return false;
2412 }
2413
2414 /**
2415 * Parse a ForClause.
2416 * <p>
2417 * [42] ForClause ::= "for" ForBinding ("," ForBinding)* <br />
2418 * [42a] ForBinding ::= "$" VarName TypeDeclaration? ("allowing" "empty")? PositionalVar? "in" ExprSingle
2419 * </p>
2420 *
2421 * @param clauseList - the components of the parsed ForClause are appended to the
2422 * supplied list
2423 * @throws XPathException if parsing fails
2424 */
2425 private void parseForClause(FLWORExpression flwor, List<Clause> clauseList) throws XPathException {
2426 boolean first = true;
2427 do {
2428 ForClause clause = new ForClause();
2429 clause.setRepeated(!first || containsLoopingClause(clauseList));
2430 setLocation(clause, t.currentTokenStartOffset);
2431 if (first) {
2432 //clause.offset = t.currentTokenStartOffset;
2433 }
2434 clauseList.add(clause);
2435 nextToken();
2436 if (first) {
2437 first = false;
2438 } else {
2439 //clause.offset = t.currentTokenStartOffset;
2440 }
2441 expect(Token.DOLLAR);
2442 nextToken();
2443 expect(Token.NAME);
2444 StructuredQName varQName = makeStructuredQName(t.currentTokenValue, "");
2445 SequenceType type = SequenceType.SINGLE_ITEM;
2446 nextToken();
2447
2448 boolean explicitType = false;
2449 if (t.currentToken == Token.AS) {
2450 explicitType = true;
2451 nextToken();
2452 type = parseSequenceType();
2453 }
2454
2455 boolean allowingEmpty = false;
2456 if (isKeyword("allowing")) {
2457 allowingEmpty = true;
2458 clause.setAllowingEmpty(true);
2459 if (!explicitType) {
2460 type = SequenceType.OPTIONAL_ITEM;
2461 }
2462 nextToken();
2463 if (!isKeyword("empty")) {
2464 grumble("After 'allowing', expected 'empty'");
2465 }
2466 nextToken();
2467 }
2468
2469 if (explicitType && !allowingEmpty && type.getCardinality() != StaticProperty.EXACTLY_ONE) {
2470 warning("Occurrence indicator on singleton range variable has no effect");
2471 type = SequenceType.makeSequenceType(type.getPrimaryType(), StaticProperty.EXACTLY_ONE);
2472 }
2473
2474 LocalVariableBinding binding = new LocalVariableBinding(varQName, type);
2475 clause.setRangeVariable(binding);
2476
2477 if (isKeyword("at")) {
2478 nextToken();
2479 expect(Token.DOLLAR);
2480 nextToken();
2481 expect(Token.NAME);
2482 StructuredQName posQName = makeStructuredQName(t.currentTokenValue, "");
2483 if (!scanOnly && posQName.equals(varQName)) {
2484 grumble("The two variables declared in a single 'for' clause must have different names", "XQST0089");
2485 }
2486 LocalVariableBinding pos = new LocalVariableBinding(posQName, SequenceType.SINGLE_INTEGER);
2487 clause.setPositionVariable(pos);
2488 nextToken();
2489 }
2490 expect(Token.IN);
2491 nextToken();
2492 clause.initSequence(flwor, parseExprSingle());
2493 declareRangeVariable(clause.getRangeVariable());
2494 if (clause.getPositionVariable() != null) {
2495 declareRangeVariable(clause.getPositionVariable());
2496 }
2497 if (allowingEmpty) {
2498 checkForClauseAllowingEmpty(flwor, clause);
2499 }
2500 } while (t.currentToken == Token.COMMA);
2501 }
2502
2503 /**
2504 * Check a ForClause for an "outer for"
2505 *
2506 * @throws net.sf.saxon.trans.XPathException
2507 * if invalid
2508 */
2509
2510 private void checkForClauseAllowingEmpty(FLWORExpression flwor, ForClause clause) throws XPathException {
2511 if (!allowXPath30Syntax) {
2512 grumble("The 'allowing empty' option requires XQuery 3.0");
2513 }
2514 SequenceType type = clause.getRangeVariable().getRequiredType();
2515 if (!Cardinality.allowsZero(type.getCardinality())) {
2516 warning("When 'allowing empty' is specified, the occurrence indicator on the range variable type should be '?'");
2517 }
2518 }
2519
2520 /**
2521 * Parse a LetClause.
2522 * <p>
2523 * [44] LetClause ::= &lt;"let" "$"&gt; VarName TypeDeclaration? ":=" ExprSingle
2524 * ("," "$" VarName TypeDeclaration? ":=" ExprSingle)*
2525 * </p>
2526 *
2527 * @param clauseList - the components of the parsed LetClause are appended to the
2528 * supplied list
2529 * @throws XPathException if a static error is found
2530 */
2531 private void parseLetClause(FLWORExpression flwor, List<Clause> clauseList) throws XPathException {
2532 boolean first = true;
2533 do {
2534 LetClause clause = new LetClause();
2535 setLocation(clause, t.currentTokenStartOffset);
2536 clause.setRepeated(containsLoopingClause(clauseList));
2537 if (first) {
2538 //clause.offset = t.currentTokenStartOffset;
2539 }
2540 clauseList.add(clause);
2541 nextToken();
2542 if (first) {
2543 first = false;
2544 } else {
2545 //clause.offset = t.currentTokenStartOffset;
2546 }
2547 expect(Token.DOLLAR);
2548 nextToken();
2549 expect(Token.NAME);
2550 String var = t.currentTokenValue;
2551
2552 StructuredQName varQName = makeStructuredQName(var, "");
2553 SequenceType type = SequenceType.ANY_SEQUENCE;
2554 nextToken();
2555 if (t.currentToken == Token.AS) {
2556 nextToken();
2557 type = parseSequenceType();
2558 }
2559 LocalVariableBinding v = new LocalVariableBinding(varQName, type);
2560
2561 expect(Token.ASSIGN);
2562 nextToken();
2563 clause.initSequence(flwor, parseExprSingle());
2564 clause.setRangeVariable(v);
2565 declareRangeVariable(v);
2566 } while (t.currentToken == Token.COMMA);
2567 }
2568
2569 /**
2570 * Parse a CountClause.
2571 * <p>
2572 * [44] CountClause ::= &lt;"count" "$"&gt; VarName
2573 * </p>
2574 *
2575 * @param clauseList - the components of the parsed CountClause are appended to the
2576 * supplied list
2577 * @throws XPathException in the event of a syntax error
2578 */
2579 private void parseCountClause(List<Clause> clauseList) throws XPathException {
2580 do {
2581 CountClause clause = new CountClause();
2582 setLocation(clause, t.currentTokenStartOffset);
2583 clause.setRepeated(containsLoopingClause(clauseList));
2584 clauseList.add(clause);
2585 nextToken();
2586 expect(Token.DOLLAR);
2587 nextToken();
2588 expect(Token.NAME);
2589 String var = t.currentTokenValue;
2590
2591 StructuredQName varQName = makeStructuredQName(var, "");
2592 SequenceType type = SequenceType.ANY_SEQUENCE;
2593 nextToken();
2594 LocalVariableBinding v = new LocalVariableBinding(varQName, type);
2595 clause.setRangeVariable(v);
2596 declareRangeVariable(v);
2597 } while (t.currentToken == Token.COMMA);
2598 }
2599
2600 /**
2601 * Parse a Group By clause.
2602 * Handles the full XQuery 3.0 syntax:
2603 * "group by" ($varname ["collation" URILiteral]) [,...]
2604 * @param clauseList the list of clauses of the FLWOR expression, to which this clause is added
2605 * @throws XPathException if there is a syntax error
2606 *
2607 */
2608 private void parseGroupByClause(FLWORExpression flwor, List<Clause> clauseList) throws XPathException {
2609 GroupByClause clause = new GroupByClause(env.getConfiguration());
2610 setLocation(clause, t.currentTokenStartOffset);
2611 clause.setRepeated(containsLoopingClause(clauseList));
2612 List<StructuredQName> variableNames = new ArrayList<>();
2613 List<String> collations = new ArrayList<>();
2614 nextToken();
2615 while (true) {
2616 StructuredQName varQName = readVariableName();
2617
2618 if (t.currentToken == Token.ASSIGN) {
2619 LetClause letClause = new LetClause();
2620
2621 clauseList.add(letClause);
2622 nextToken();
2623
2624 SequenceType type = SequenceType.ANY_SEQUENCE;
2625 if (t.currentToken == Token.AS) {
2626 nextToken();
2627 type = parseSequenceType();
2628 }
2629 LocalVariableBinding v = new LocalVariableBinding(varQName, type);
2630
2631 letClause.initSequence(flwor, parseExprSingle());
2632 letClause.setRangeVariable(v);
2633 declareRangeVariable(v);
2634 }
2635 variableNames.add(varQName);
2636 if (isKeyword("collation")) {
2637 nextToken();
2638 expect(Token.STRING_LITERAL);
2639 collations.add(t.currentTokenValue);
2640 nextToken();
2641 } else {
2642 collations.add(env.getDefaultCollationName());
2643 }
2644 if (t.currentToken == Token.COMMA) {
2645 nextToken();
2646 } else {
2647 break;
2648 }
2649 }
2650 // Each of the variable names acts both as a variable reference (for a variable in the pre-grouping stream)
2651 // and a variable declaration (for a variable in the post-grouping stream).
2652 TupleExpression groupingTupleExpr = new TupleExpression();
2653 TupleExpression retainedTupleExpr = new TupleExpression();
2654 List<LocalVariableReference> groupingRefs = new ArrayList<>();
2655 List<LocalVariableReference> retainedRefs = new ArrayList<>();
2656 List<LocalVariableBinding> groupedBindings = new ArrayList<>();
2657 for (StructuredQName q : variableNames) {
2658 boolean found = false;
2659 search:
2660 for (int i = clauseList.size() - 1; i >= 0; i--) {
2661 for (LocalVariableBinding b : clauseList.get(i).getRangeVariables()) {
2662 if (q.equals(b.getVariableQName())) {
2663 groupedBindings.add(b);
2664 groupingRefs.add(new LocalVariableReference(b));
2665 found = true;
2666 break search;
2667 }
2668 }
2669 }
2670 if (!found) {
2671 grumble("The grouping variable " + q.getDisplayName() + " must be the name of a variable bound earlier in the FLWOR expression",
2672 "XQST0094");
2673 }
2674 }
2675 groupingTupleExpr.setVariables(groupingRefs);
2676 clause.initGroupingTupleExpression(flwor, groupingTupleExpr);
2677
2678 List<LocalVariableBinding> ungroupedBindings = new ArrayList<>();
2679 for (int i = clauseList.size() - 1; i >= 0; i--) {
2680 for (LocalVariableBinding b : clauseList.get(i).getRangeVariables()) {
2681 if (!groupedBindings.contains(b)) {
2682 ungroupedBindings.add(b);
2683 retainedRefs.add(new LocalVariableReference(b));
2684 }
2685 }
2686 }
2687
2688 retainedTupleExpr.setVariables(retainedRefs);
2689 clause.initRetainedTupleExpression(flwor, retainedTupleExpr);
2690
2691 LocalVariableBinding[] bindings = new LocalVariableBinding[groupedBindings.size() + ungroupedBindings.size()];
2692 int k = 0;
2693
2694 for (LocalVariableBinding b : groupedBindings) {
2695 bindings[k] = new LocalVariableBinding(b.getVariableQName(), b.getRequiredType());
2696 //declareRangeVariable(bindings[k]);
2697 k++;
2698 }
2699
2700 for (LocalVariableBinding b : ungroupedBindings) {
2701 ItemType itemType = b.getRequiredType().getPrimaryType();
2702 bindings[k] = new LocalVariableBinding(b.getVariableQName(),
2703 SequenceType.makeSequenceType(itemType, StaticProperty.ALLOWS_ZERO_OR_MORE));
2704 //declareRangeVariable(bindings[k]);
2705 k++;
2706 }
2707
2708 for (int z = groupedBindings.size(); z < bindings.length; z++) {
2709 declareRangeVariable(bindings[z]);
2710 }
2711 for (int z = 0; z < groupedBindings.size(); z++) {
2712 declareRangeVariable(bindings[z]);
2713 }
2714
2715 clause.setVariableBindings(bindings);
2716 GenericAtomicComparer[] comparers = new GenericAtomicComparer[collations.size()];
2717 XPathContext context = env.makeEarlyEvaluationContext();
2718 for (int i = 0; i < comparers.length; i++) {
2719 StringCollator coll = env.getConfiguration().getCollation(collations.get(i));
2720 comparers[i] = (GenericAtomicComparer) GenericAtomicComparer.makeAtomicComparer(
2721 BuiltInAtomicType.ANY_ATOMIC, BuiltInAtomicType.ANY_ATOMIC, coll, context);
2722 }
2723 clause.setComparers(comparers);
2724 clauseList.add(clause);
2725 }
2726
2727 private StructuredQName readVariableName() throws XPathException {
2728 expect(Token.DOLLAR);
2729 nextToken();
2730 expect(Token.NAME);
2731 String name = t.currentTokenValue;
2732 nextToken();
2733 return makeStructuredQName(name, "");
2734 }
2735
2736 /**
2737 * Parse a tumbling or sliding window clause.
2738 * @param clauseList the list of clauses of the FLWOR expression, to which this clause is aded
2739 * @throws XPathException if there is a syntax error
2740 *
2741 */
2742 private void parseWindowClause(FLWORExpression flwor, List<Clause> clauseList) throws XPathException {
2743 WindowClause clause = new WindowClause();
2744 setLocation(clause, t.currentTokenStartOffset);
2745 clause.setRepeated(containsLoopingClause(clauseList));
2746 clause.setIsSlidingWindow(t.currentToken == Token.FOR_SLIDING);
2747 nextToken();
2748 if (!isKeyword("window")) {
2749 grumble("after 'sliding' or 'tumbling', expected 'window', but found " + currentTokenDisplay());
2750 }
2751 nextToken();
2752 StructuredQName windowVarName = readVariableName();
2753 SequenceType windowType = SequenceType.ANY_SEQUENCE;
2754 if (t.currentToken == Token.AS) {
2755 nextToken();
2756 windowType = parseSequenceType();
2757 }
2758
2759 LocalVariableBinding windowVar = new LocalVariableBinding(windowVarName, windowType);
2760 clause.setVariableBinding(WindowClause.WINDOW_VAR, windowVar);
2761
2762 // We can't assume that all the items in the input sequence belong to the item type of the windows: test case SlidingWindowExpr507
2763 SequenceType windowItemTypeMandatory = SequenceType.SINGLE_ITEM;
2764 SequenceType windowItemTypeOptional = SequenceType.OPTIONAL_ITEM;
2765
2766 expect(Token.IN);
2767 nextToken();
2768 clause.initSequence(flwor, parseExprSingle());
2769 if (!isKeyword("start")) {
2770 grumble("in window clause, expected 'start', but found " + currentTokenDisplay());
2771 }
2772 t.setState(Tokenizer.BARE_NAME_STATE);
2773 nextToken();
2774 if (t.currentToken == Token.DOLLAR) {
2775 LocalVariableBinding startItemVar = new LocalVariableBinding(readVariableName(), windowItemTypeMandatory);
2776 clause.setVariableBinding(WindowClause.START_ITEM, startItemVar);
2777 declareRangeVariable(startItemVar);
2778 }
2779 if (isKeyword("at")) {
2780 nextToken();
2781 LocalVariableBinding startPositionVar = new LocalVariableBinding(readVariableName(), SequenceType.SINGLE_INTEGER);
2782 clause.setVariableBinding(WindowClause.START_ITEM_POSITION, startPositionVar);
2783 declareRangeVariable(startPositionVar);
2784 }
2785 if (isKeyword("previous")) {
2786 nextToken();
2787 LocalVariableBinding startPreviousItemVar = new LocalVariableBinding(readVariableName(), windowItemTypeOptional);
2788 clause.setVariableBinding(WindowClause.START_PREVIOUS_ITEM, startPreviousItemVar);
2789 declareRangeVariable(startPreviousItemVar);
2790 }
2791 if (isKeyword("next")) {
2792 nextToken();
2793 LocalVariableBinding startNextItemVar = new LocalVariableBinding(readVariableName(), windowItemTypeOptional);
2794 clause.setVariableBinding(WindowClause.START_NEXT_ITEM, startNextItemVar);
2795 declareRangeVariable(startNextItemVar);
2796 }
2797 if (!isKeyword("when")) {
2798 grumble("Expected 'when' condition for window start, but found " + currentTokenDisplay());
2799 }
2800 t.setState(Tokenizer.DEFAULT_STATE);
2801 nextToken();
2802 clause.initStartCondition(flwor, parseExprSingle());
2803 if (isKeyword("only")) {
2804 clause.setIncludeUnclosedWindows(false);
2805 nextToken();
2806 }
2807 if (isKeyword("end")) {
2808 t.setState(Tokenizer.BARE_NAME_STATE);
2809 nextToken();
2810
2811 if (t.currentToken == Token.DOLLAR) {
2812 LocalVariableBinding endItemVar = new LocalVariableBinding(readVariableName(), windowItemTypeMandatory);
2813 clause.setVariableBinding(WindowClause.END_ITEM, endItemVar);
2814 declareRangeVariable(endItemVar);
2815 }
2816 if (isKeyword("at")) {
2817 nextToken();
2818 LocalVariableBinding endPositionVar = new LocalVariableBinding(readVariableName(), SequenceType.SINGLE_INTEGER);
2819 clause.setVariableBinding(WindowClause.END_ITEM_POSITION, endPositionVar);
2820 declareRangeVariable(endPositionVar);
2821 }
2822 if (isKeyword("previous")) {
2823 nextToken();
2824 LocalVariableBinding endPreviousItemVar = new LocalVariableBinding(readVariableName(), windowItemTypeOptional);
2825 clause.setVariableBinding(WindowClause.END_PREVIOUS_ITEM, endPreviousItemVar);
2826 declareRangeVariable(endPreviousItemVar);
2827 }
2828 if (isKeyword("next")) {
2829 nextToken();
2830 LocalVariableBinding endNextItemVar = new LocalVariableBinding(readVariableName(), windowItemTypeOptional);
2831 clause.setVariableBinding(WindowClause.END_NEXT_ITEM, endNextItemVar);
2832 declareRangeVariable(endNextItemVar);
2833 }
2834 if (!isKeyword("when")) {
2835 grumble("Expected 'when' condition for window end, but found " + currentTokenDisplay());
2836 }
2837 t.setState(Tokenizer.DEFAULT_STATE);
2838 nextToken();
2839 clause.initEndCondition(flwor, parseExprSingle());
2840 } else {
2841 // no "end" condition found
2842 if (clause.isSlidingWindow()) {
2843 grumble("A sliding window requires an end condition");
2844 }
2845 }
2846 declareRangeVariable(windowVar);
2847 clauseList.add(clause);
2848 }
2849
2850
2851 /**
2852 * Make a string-join expression that concatenates the string-values of items in
2853 * a sequence with intervening spaces. This may be simplified later as a result
2854 * of type-checking.
2855 *
2856 * @param exp the base expression, evaluating to a sequence
2857 * @param env the static context
2858 * @return a call on string-join to create a string containing the
2859 * representations of the items in the sequence separated by spaces.
2860 */
2861
2862 /*@Nullable*/
2863 public static Expression makeStringJoin(Expression exp, /*@NotNull*/ StaticContext env) {
2864
2865 exp = Atomizer.makeAtomizer(exp, null);
2866 ItemType t = exp.getItemType();
2867 if (!t.equals(BuiltInAtomicType.STRING) && !t.equals(BuiltInAtomicType.UNTYPED_ATOMIC)) {
2868 exp = new AtomicSequenceConverter(exp, BuiltInAtomicType.STRING);
2869 ((AtomicSequenceConverter) exp).allocateConverterStatically(env.getConfiguration(), false);
2870 }
2871
2872 if (exp.getCardinality() == StaticProperty.EXACTLY_ONE) {
2873 return exp;
2874 } else {
2875 RetainedStaticContext rsc = new RetainedStaticContext(env);
2876 Expression fn = SystemFunction.makeCall("string-join", rsc, exp, new StringLiteral(StringValue.SINGLE_SPACE));
2877 ExpressionTool.copyLocationInfo(exp, fn);
2878 return fn;
2879 }
2880 }
2881
2882 /**
2883 * Parse the "order by" clause.
2884 * <p>[46] OrderByClause ::= (&lt;"order" "by"&gt; | &lt;"stable" "order" "by"&gt;) OrderSpecList <br />
2885 * [47] OrderSpecList ::= OrderSpec ("," OrderSpec)* <br />
2886 * [48] OrderSpec ::= ExprSingle OrderModifier <br />
2887 * [49] OrderModifier ::= ("ascending" | "descending")?
2888 * (&lt;"empty" "greatest"&gt; | &lt;"empty" "least"&gt;)?
2889 * ("collation" StringLiteral)?
2890 * </p>
2891 *
2892 * @return a list of sort specifications (SortSpec), one per sort key
2893 * @throws XPathException if parsing fails
2894 */
2895 /*@NotNull*/
2896 private List parseSortDefinition() throws XPathException {
2897 List<SortSpec> sortSpecList = new ArrayList<>(5);
2898 while (true) {
2899 SortSpec sortSpec = new SortSpec();
2900 sortSpec.sortKey = parseExprSingle();
2901 sortSpec.ascending = true;
2902 sortSpec.emptyLeast = ((QueryModule) env).isEmptyLeast();
2903 sortSpec.collation = env.getDefaultCollationName();
2904 //t.setState(t.BARE_NAME_STATE);
2905 if (isKeyword("ascending")) {
2906 nextToken();
2907 } else if (isKeyword("descending")) {
2908 sortSpec.ascending = false;
2909 nextToken();
2910 }
2911 if (isKeyword("empty")) {
2912 nextToken();
2913 if (isKeyword("greatest")) {
2914 sortSpec.emptyLeast = false;
2915 nextToken();
2916 } else if (isKeyword("least")) {
2917 sortSpec.emptyLeast = true;
2918 nextToken();
2919 } else {
2920 grumble("'empty' must be followed by 'greatest' or 'least'");
2921 }
2922 }
2923 if (isKeyword("collation")) {
2924 sortSpec.collation = readCollationName();
2925 }
2926 sortSpecList.add(sortSpec);
2927 if (t.currentToken == Token.COMMA) {
2928 nextToken();
2929 } else {
2930 break;
2931 }
2932 }
2933 return sortSpecList;
2934 }
2935
2936 protected String readCollationName() throws XPathException {
2937 nextToken();
2938 expect(Token.STRING_LITERAL);
2939 String collationName = uriLiteral(t.currentTokenValue);
2940 URI collationURI;
2941 try {
2942 collationURI = new URI(collationName);
2943 if (!collationURI.isAbsolute()) {
2944 URI base = new URI(env.getStaticBaseURI());
2945 collationURI = base.resolve(collationURI);
2946 collationName = collationURI.toString();
2947 }
2948 } catch (URISyntaxException err) {
2949 grumble("Collation name '" + collationName + "' is not a valid URI", "XQST0046");
2950 collationName = NamespaceConstant.CODEPOINT_COLLATION_URI;
2951 }
2952 nextToken();
2953 return collationName;
2954 }
2955
2956 private static class SortSpec {
2957 /*@Nullable*/ public Expression sortKey;
2958 public boolean ascending;
2959 public boolean emptyLeast;
2960 public String collation;
2961 }
2962
2963 /**
2964 * Parse a Typeswitch Expression.
2965 * This construct is XQuery-only.
2966 * TypeswitchExpr ::=
2967 * "typeswitch" "(" Expr ")"
2968 * CaseClause+
2969 * "default" ("$" VarName)? "return" ExprSingle
2970 * CaseClause ::=
2971 * "case" ("$" VarName "as")? SequenceType "return" ExprSingle
2972 *
2973 * @throws XPathException if parsing fails
2974 */
2975
2976 /*@NotNull*/
2977 protected Expression parseTypeswitchExpression() throws XPathException {
2978
2979 // On entry, the "(" has already been read
2980 int offset = t.currentTokenStartOffset;
2981 nextToken();
2982 Expression operand = parseExpression();
2983 List<List<SequenceType>> types = new ArrayList<>(10);
2984 List<Expression> actions = new ArrayList<>(10);
2985 expect(Token.RPAR);
2986 nextToken();
2987
2988 // The code generated takes the form:
2989 // let $zzz := operand return
2990 // if ($zzz instance of t1) then action1
2991 // else if ($zzz instance of t2) then action2
2992 // else default-action
2993 //
2994 // If a variable is declared in a case clause or default clause,
2995 // then "action-n" takes the form
2996 // let $v as type := $zzz return action-n
2997
2998 // we were generating "let $v as type := $zzz return action-n" but this gives a compile time error if
2999 // there's a case clause that specifies an impossible type.
3000
3001 LetExpression outerLet = makeLetExpression();
3002 outerLet.setRequiredType(SequenceType.ANY_SEQUENCE);
3003 outerLet.setVariableQName(new StructuredQName("zz", NamespaceConstant.SAXON, "zz_typeswitchVar"));
3004 outerLet.setSequence(operand);
3005
3006 while (t.currentToken == Token.CASE) {
3007 int caseOffset = t.currentTokenStartOffset;
3008 List<SequenceType> typeList;
3009 Expression action;
3010 nextToken();
3011 if (t.currentToken == Token.DOLLAR) {
3012 nextToken();
3013 expect(Token.NAME);
3014 final String var = t.currentTokenValue;
3015 final StructuredQName varQName = makeStructuredQName(var, "");
3016 nextToken();
3017 expect(Token.AS);
3018 nextToken();
3019 typeList = parseSequenceTypeList();
3020 action = makeTracer(caseOffset,
3021 parseTypeswitchReturnClause(varQName, outerLet),
3022 LocationKind.CASE_EXPRESSION,
3023 varQName);
3024 if (action instanceof TraceExpression) {
3025 ((TraceExpression) action).setProperty("type", typeList.get(0).toString());
3026 }
3027
3028 } else {
3029 typeList = parseSequenceTypeList();
3030 action = makeTracer(caseOffset, parseExprSingle(), LocationKind.CASE_EXPRESSION, null);
3031 if (action instanceof TraceExpression) {
3032 ((TraceExpression) action).setProperty("type", typeList.get(0).toString());
3033 }
3034 }
3035 types.add(typeList);
3036 actions.add(action);
3037 }
3038 if (types.isEmpty()) {
3039 grumble("At least one case clause is required in a typeswitch");
3040 }
3041 expect(Token.DEFAULT);
3042 final int defaultOffset = t.currentTokenStartOffset;
3043 nextToken();
3044 Expression defaultAction;
3045 if (t.currentToken == Token.DOLLAR) {
3046 nextToken();
3047 expect(Token.NAME);
3048 final String var = t.currentTokenValue;
3049 final StructuredQName varQName = makeStructuredQName(var, "");
3050 nextToken();
3051 expect(Token.RETURN);
3052 nextToken();
3053 defaultAction = makeTracer(defaultOffset,
3054 parseTypeswitchReturnClause(varQName, outerLet),
3055 LocationKind.DEFAULT_EXPRESSION,
3056 varQName);
3057 } else {
3058 t.treatCurrentAsOperator();
3059 expect(Token.RETURN);
3060 nextToken();
3061 defaultAction = makeTracer(defaultOffset, parseExprSingle(), LocationKind.DEFAULT_EXPRESSION, null);
3062 }
3063
3064 Expression lastAction = defaultAction;
3065 // Note, the ragged "choose" later gets flattened into a single-level choose, saving stack space
3066 for (int i = types.size() - 1; i >= 0; i--) {
3067 final LocalVariableReference var = new LocalVariableReference(outerLet);
3068 setLocation(var);
3069 Expression ioe = new InstanceOfExpression(var, types.get(i).get(0));
3070 for (int j = 1; j < types.get(i).size(); j++) {
3071 ioe = new OrExpression(ioe, new InstanceOfExpression(var.copy(new RebindingMap()), types.get(i).get(j)));
3072 }
3073 setLocation(ioe);
3074 final Expression ife = Choose.makeConditional(ioe, actions.get(i), lastAction);
3075 setLocation(ife);
3076 lastAction = ife;
3077 }
3078 outerLet.setAction(lastAction);
3079 return makeTracer(offset, outerLet, LocationKind.TYPESWITCH_EXPRESSION, null);
3080 }
3081
3082 /*@NotNull*/
3083 private List<SequenceType> parseSequenceTypeList() throws XPathException {
3084 List<SequenceType> typeList = new ArrayList<>();
3085 while (true) {
3086 SequenceType type = parseSequenceType();
3087 typeList.add(type);
3088 t.treatCurrentAsOperator();
3089 if (t.currentToken == Token.UNION) {
3090 nextToken();
3091 } else {
3092 break;
3093 }
3094 }
3095 expect(Token.RETURN);
3096 nextToken();
3097 return typeList;
3098 }
3099
3100 /*@NotNull*/
3101 private Expression parseTypeswitchReturnClause(StructuredQName varQName, LetExpression outerLet)
3102 throws XPathException {
3103 Expression action;
3104 // t.treatCurrentAsOperator();
3105 // expect(Token.RETURN);
3106 // nextToken();
3107
3108 LetExpression innerLet = makeLetExpression();
3109 innerLet.setRequiredType(SequenceType.ANY_SEQUENCE);
3110 innerLet.setVariableQName(varQName);
3111 innerLet.setSequence(new LocalVariableReference(outerLet));
3112
3113 declareRangeVariable(innerLet);
3114 action = parseExprSingle();
3115 undeclareRangeVariable();
3116
3117 innerLet.setAction(action);
3118 return innerLet;
3119 // if (Literal.isEmptySequence(action)) {
3120 // // The purpose of simplifying this now is that () is allowed in a branch even in XQuery Update when
3121 // // other branches of the typeswitch are updating.
3122 // return action;
3123 // } else {
3124 // return innerLet;
3125 // }
3126 }
3127
3128
3129 /**
3130 * Parse a Switch Expression.
3131 * This construct is XQuery-3.0-only.
3132 * SwitchExpr ::= "switch" "(" Expr ")" SwitchCaseClause+ "default" "return" ExprSingle
3133 * SwitchCaseClause ::= ("case" ExprSingle)+ "return" ExprSingle
3134 */
3135
3136 /*@NotNull*/
3137 protected Expression parseSwitchExpression() throws XPathException {
3138
3139 // On entry, the "(" has already been read
3140 int offset = t.currentTokenStartOffset;
3141 nextToken();
3142 Expression operand = parseExpression();
3143 expect(Token.RPAR);
3144 nextToken();
3145
3146 List<Expression> conditions = new ArrayList<>(10);
3147 List<Expression> actions = new ArrayList<>(10);
3148
3149 // The code generated takes the form:
3150 // let $zzz := zero-or-one(atomize(operand)) return
3151 // choose
3152 // when ($zzz eq t1) then action1
3153 // when ($zzz eq t2) then action2
3154 // when (true) default-action
3155 //
3156 // We rely on the optimizer to convert this to a SwitchExpression in the case where all the case clauses
3157 // are literal constants.
3158
3159 LetExpression outerLet = makeLetExpression();
3160 outerLet.setRequiredType(SequenceType.OPTIONAL_ATOMIC);
3161 outerLet.setVariableQName(new StructuredQName("zz", NamespaceConstant.SAXON, "zz_switchVar"));
3162 outerLet.setSequence(Atomizer.makeAtomizer(operand, null));
3163
3164 do {
3165 List<Expression> caseExpressions = new ArrayList<>(4);
3166
3167 expect(Token.CASE);
3168 do {
3169 nextToken();
3170 Expression c = parseExprSingle();
3171 caseExpressions.add(c);
3172 } while (t.currentToken == Token.CASE);
3173
3174 expect(Token.RETURN);
3175 nextToken();
3176
3177 Expression action = parseExprSingle();
3178 for (int i = 0; i < caseExpressions.size(); i++) {
3179 EquivalenceComparison vc = new EquivalenceComparison(
3180 new LocalVariableReference(outerLet),
3181 Token.FEQ,
3182 caseExpressions.get(i));
3183 if (i == 0) {
3184 conditions.add(vc);
3185 actions.add(action);
3186 } else {
3187 OrExpression orExpr = new OrExpression(conditions.remove(conditions.size() - 1), vc);
3188 conditions.add(orExpr);
3189 }
3190 //actions.add((i==0 ? action : action.copy()));
3191 }
3192
3193 } while (t.currentToken == Token.CASE);
3194
3195 expect(Token.DEFAULT);
3196 nextToken();
3197 expect(Token.RETURN);
3198 nextToken();
3199 Expression defaultExpr = parseExprSingle();
3200 conditions.add(Literal.makeLiteral(BooleanValue.TRUE));
3201 actions.add(defaultExpr);
3202
3203 Choose choice = new Choose(
3204 conditions.toArray(new Expression[0]),
3205 actions.toArray(new Expression[conditions.size()]));
3206 outerLet.setAction(choice);
3207 return makeTracer(offset, outerLet, LocationKind.SWITCH_EXPRESSION, null);
3208 }
3209
3210
3211 /**
3212 * Parse a Validate Expression.
3213 * This construct is XQuery-only. The syntax allows:
3214 * validate mode? { Expr }
3215 * mode ::= "strict" | "lax"
3216 *
3217 * @throws XPathException if parsing fails
3218 */
3219
3220 /*@NotNull*/
3221 protected Expression parseValidateExpression() throws XPathException {
3222 int offset = t.currentTokenStartOffset;
3223 int mode = Validation.STRICT;
3224 boolean foundCurly = false;
3225 SchemaType requiredType = null;
3226 ensureSchemaAware("validate expression");
3227 switch (t.currentToken) {
3228 case Token.VALIDATE_STRICT:
3229 mode = Validation.STRICT;
3230 nextToken();
3231 break;
3232 case Token.VALIDATE_LAX:
3233 mode = Validation.LAX;
3234 nextToken();
3235 break;
3236 case Token.VALIDATE_TYPE:
3237 // if (XQUERY10.equals(queryVersion)) {
3238 // grumble("validate-as-type requires XQuery 3.0");
3239 // }
3240 mode = Validation.BY_TYPE;
3241 nextToken();
3242 expect(Token.KEYWORD_CURLY);
3243 if (!NameChecker.isQName(t.currentTokenValue)) {
3244 grumble("Schema type name expected after 'validate type");
3245 }
3246 requiredType = env.getConfiguration().getSchemaType(
3247 makeStructuredQName(t.currentTokenValue, env.getDefaultElementNamespace()));
3248 if (requiredType == null) {
3249 grumble("Unknown schema type " + t.currentTokenValue, "XQST0104");
3250 }
3251 foundCurly = true;
3252 break;
3253 case Token.KEYWORD_CURLY:
3254 if (t.currentTokenValue.equals("validate")) {
3255 mode = Validation.STRICT;
3256 } else {
3257 throw new AssertionError("shouldn't be parsing a validate expression");
3258 }
3259 foundCurly = true;
3260 }
3261
3262 if (!foundCurly) {
3263 expect(Token.LCURLY);
3264 }
3265 nextToken();
3266
3267 Expression exp = parseExpression();
3268 if (exp instanceof ParentNodeConstructor) {
3269 ((ParentNodeConstructor) exp).setValidationAction(mode, mode == Validation.BY_TYPE ? requiredType : null);
3270 } else {
3271 // the expression must return a single element or document node. The type-
3272 // checking machinery can't handle a union type, so we just check that it's
3273 // a node for now. Because we are reusing XSLT copy-of code, we need
3274 // an ad-hoc check that the node is of the right kind.
3275
3276 // below code moved to XQuery-specific path in CopyOf
3277 // try {
3278 // RoleLocator role = new RoleLocator(RoleLocator.TYPE_OP, "validate", 0);
3279 // role.setErrorCode("XQTY0030");
3280 // setLocation(exp);
3281 // exp = config.getTypeChecker().staticTypeCheck(exp,
3282 // SequenceType.SINGLE_NODE,
3283 // false,
3284 // role, ExpressionVisitor.make(env, getExecutable()));
3285 // } catch (XPathException err) {
3286 // grumble(err.getMessage(), err.getErrorCodeQName(), -1);
3287 // }
3288 exp = new CopyOf(exp, true, mode, requiredType, true);
3289 setLocation(exp);
3290 ((CopyOf) exp).setRequireDocumentOrElement(true);
3291 }
3292
3293 expect(Token.RCURLY);
3294 t.lookAhead(); // always done manually after an RCURLY
3295 nextToken();
3296 return makeTracer(offset, exp, LocationKind.VALIDATE_EXPRESSION, null);
3297 }
3298
3299 /**
3300 * Parse an Extension Expression.
3301 * Syntax: "(#" QName arbitrary-text "#)")+ "{" expr? "}"
3302 *
3303 * @throws XPathException if parsing fails
3304 */
3305
3306 /*@NotNull*/
3307 protected Expression parseExtensionExpression() throws XPathException {
3308 SchemaType requiredType = null;
3309 CharSequence trimmed = Whitespace.removeLeadingWhitespace(t.currentTokenValue);
3310 int c = 0;
3311 int len = trimmed.length();
3312 while (c < len && " \t\r\n".indexOf(trimmed.charAt(c)) < 0) {
3313 c++;
3314 }
3315 String qname = trimmed.subSequence(0, c).toString();
3316 String pragmaContents = "";
3317 while (c < len && " \t\r\n".indexOf(trimmed.charAt(c)) >= 0) {
3318 c++;
3319 }
3320 if (c < len) {
3321 pragmaContents = trimmed.subSequence(c, len).toString();
3322 }
3323
3324 boolean validateType = false;
3325 boolean streaming = false;
3326 StructuredQName pragmaName = makeStructuredQName(qname, "");
3327 assert pragmaName != null;
3328 String uri = pragmaName.getURI();
3329 String localName = pragmaName.getLocalPart();
3330 if (uri.equals(NamespaceConstant.SAXON)) {
3331 switch (localName) {
3332 case "validate-type":
3333 if (!env.getConfiguration().isLicensedFeature(Configuration.LicenseFeature.ENTERPRISE_XQUERY)) {
3334 warning("Ignoring saxon:validate-type. To use this feature " +
3335 "you need the Saxon-EE processor from http://www.saxonica.com/");
3336 } else {
3337 String typeName = Whitespace.trim(pragmaContents);
3338 if (!NameChecker.isQName(typeName)) {
3339 grumble("Schema type name expected in saxon:validate-type pragma: found " + Err.wrap(typeName));
3340 }
3341 requiredType = env.getConfiguration().getSchemaType(
3342 makeStructuredQName(typeName, env.getDefaultElementNamespace()));
3343 if (requiredType == null) {
3344 grumble("Unknown schema type " + typeName);
3345 }
3346 validateType = true;
3347 }
3348 break;
3349 default:
3350 warning("Ignored pragma " + qname + " (unrecognized Saxon pragma)");
3351 break;
3352 }
3353 }
3354
3355 nextToken();
3356 Expression expr;
3357 if (t.currentToken == Token.PRAGMA) {
3358 expr = parseExtensionExpression();
3359 } else {
3360 expect(Token.LCURLY);
3361 nextToken();
3362 if (t.currentToken == Token.RCURLY) {
3363 t.lookAhead(); // always done manually after an RCURLY
3364 nextToken();
3365 grumble("Unrecognized pragma, with no fallback expression", "XQST0079");
3366 }
3367 expr = parseExpression();
3368 expect(Token.RCURLY);
3369 t.lookAhead(); // always done manually after an RCURLY
3370 nextToken();
3371 }
3372 if (validateType) {
3373 if (expr instanceof ParentNodeConstructor) {
3374 ((ParentNodeConstructor) expr).setValidationAction(Validation.BY_TYPE, requiredType);
3375 return expr;
3376 } else if (expr instanceof AttributeCreator) {
3377 if (!(requiredType instanceof SimpleType)) {
3378 grumble("The type used for validating an attribute must be a simple type");
3379 }
3380
3381 //noinspection ConstantConditions
3382 ((AttributeCreator) expr).setSchemaType((SimpleType) requiredType);
3383 ((AttributeCreator) expr).setValidationAction(Validation.BY_TYPE);
3384 return expr;
3385 } else {
3386 CopyOf copy = new CopyOf(expr, true, Validation.BY_TYPE, requiredType, true);
3387 copy.setLocation(makeLocation());
3388 return copy;
3389 }
3390 } else {
3391 return expr;
3392 }
3393 }
3394
3395 /**
3396 * Parse a node constructor. This is allowed only in XQuery. This method handles
3397 * both the XML-like "direct" constructors, and the XQuery-based "computed"
3398 * constructors.
3399 *
3400 * @return an Expression for evaluating the parsed constructor
3401 * @throws XPathException in the event of a syntax error.
3402 */
3403
3404 /*@NotNull*/
3405 protected Expression parseConstructor() throws XPathException {
3406 int offset = t.currentTokenStartOffset;
3407 switch (t.currentToken) {
3408 case Token.TAG:
3409 Expression tag = parsePseudoXML(false);
3410 lookAhead();
3411 t.setState(Tokenizer.OPERATOR_STATE);
3412 nextToken();
3413 return tag;
3414 case Token.KEYWORD_CURLY:
3415 String nodeKind = t.currentTokenValue;
3416 switch (nodeKind) {
3417 case "validate":
3418 grumble("A validate expression is not allowed within a path expression");
3419
3420 //if (nodeKind.equals("validate")) {
3421 // this allows a validate{} expression to appear as an operand of '/', which the grammar does not allow
3422 // return parseValidateExpression();
3423 break;
3424 case "ordered":
3425 case "unordered":
3426 // these are currently no-ops in Saxon
3427 nextToken();
3428 Expression content;
3429 if (t.currentToken == Token.RCURLY && allowXPath31Syntax) {
3430 content = Literal.makeEmptySequence();
3431 } else {
3432 content = parseExpression();
3433 }
3434 expect(Token.RCURLY);
3435 lookAhead(); // must be done manually after an RCURLY
3436
3437 nextToken();
3438 return content;
3439 case "document":
3440 return parseDocumentConstructor(offset);
3441
3442 case "element":
3443 return parseComputedElementConstructor(offset);
3444
3445 case "attribute":
3446 return parseComputedAttributeConstructor(offset);
3447
3448 case "text":
3449 return parseTextNodeConstructor(offset);
3450
3451 case "comment":
3452 return parseCommentConstructor(offset);
3453
3454 case "processing-instruction":
3455 return parseProcessingInstructionConstructor(offset);
3456
3457 case "namespace":
3458 return parseNamespaceConstructor(offset);
3459
3460 default:
3461 grumble("Unrecognized node constructor " + t.currentTokenValue + "{}");
3462 break;
3463 }
3464 case Token.ELEMENT_QNAME:
3465 return parseNamedElementConstructor(offset);
3466
3467 case Token.ATTRIBUTE_QNAME:
3468 return parseNamedAttributeConstructor(offset);
3469
3470 case Token.NAMESPACE_QNAME:
3471 return parseNamedNamespaceConstructor(offset);
3472
3473 case Token.PI_QNAME:
3474 return parseNamedProcessingInstructionConstructor(offset);
3475 }
3476 return new ErrorExpression();
3477 }
3478
3479 /**
3480 * Parse document constructor: document {...}
3481 *
3482 * @param offset the location in the source query
3483 * @return the document constructor instruction
3484 * @throws XPathException if parsing fails
3485 */
3486
3487 /*@NotNull*/
3488 private Expression parseDocumentConstructor(int offset) throws XPathException {
3489 nextToken();
3490 Expression content;
3491 if (t.currentToken == Token.RCURLY && allowXPath31Syntax) {
3492 content = Literal.makeEmptySequence();
3493 } else {
3494 content = parseExpression();
3495 }
3496 expect(Token.RCURLY);
3497 lookAhead(); // must be done manually after an RCURLY
3498 nextToken();
3499 DocumentInstr doc = new DocumentInstr(false, null);
3500 if (!((QueryModule) env).isPreserveNamespaces()) {
3501 content = new CopyOf(content, false, Validation.PRESERVE, null, true);
3502 }
3503 doc.setValidationAction(((QueryModule) env).getConstructionMode(), null);
3504 doc.setContentExpression(content);
3505 setLocation(doc, offset);
3506 return doc;
3507 }
3508
3509 /**
3510 * Parse an element constructor of the form
3511 * element {expr} {expr}
3512 *
3513 * @param offset location of the expression in the source query
3514 * @return the compiled instruction
3515 * @throws XPathException if a static error is found
3516 */
3517
3518 /*@NotNull*/
3519 private Expression parseComputedElementConstructor(int offset) throws XPathException {
3520 nextToken();
3521 // get the expression that yields the element name
3522 Expression name = parseExpression();
3523 expect(Token.RCURLY);
3524 lookAhead(); // must be done manually after an RCURLY
3525 nextToken();
3526 expect(Token.LCURLY);
3527 t.setState(Tokenizer.DEFAULT_STATE);
3528 nextToken();
3529 Expression content = null;
3530 if (t.currentToken != Token.RCURLY) {
3531 // get the expression that yields the element content
3532 content = parseExpression();
3533 // if the child expression creates another element,
3534 // suppress validation, as the parent already takes care of it
3535 if (content instanceof ElementCreator && ((ElementCreator) content).getSchemaType() == null) {
3536 ((ElementCreator) content).setValidationAction(Validation.PRESERVE, null);
3537 }
3538 expect(Token.RCURLY);
3539 }
3540 lookAhead(); // done manually after an RCURLY
3541 nextToken();
3542
3543 Instruction inst;
3544 if (name instanceof Literal) {
3545 GroundedValue vName = ((Literal) name).getValue();
3546 // if element name is supplied as a literal, treat it like a direct element constructor
3547 NodeName elemName;
3548 if (vName instanceof StringValue && !(vName instanceof AnyURIValue)) {
3549 String lex = ((StringValue) vName).getStringValue();
3550 try {
3551 elemName = makeNodeName(lex, true);
3552 elemName.obtainFingerprint(env.getConfiguration().getNamePool());
3553 } catch (XPathException staticError) {
3554 String code = staticError.getErrorCodeLocalPart();
3555 if ("XPST0008".equals(code) || "XPST0081".equals(code)) {
3556 staticError.setErrorCode("XQDY0074");
3557 } else if ("XPST0003".equals(code)) {
3558 //staticError.setErrorCode("XQDY0074");
3559 grumble("Invalid QName in element constructor: " + lex, "XQDY0074", offset);
3560 return new ErrorExpression();
3561 }
3562 staticError.setLocator(makeLocation());
3563 staticError.setIsStaticError(false);
3564 return new ErrorExpression(staticError);
3565 }
3566 } else if (vName instanceof QualifiedNameValue) {
3567 String uri = ((QualifiedNameValue) vName).getNamespaceURI();
3568 elemName = new FingerprintedQName("", uri, ((QualifiedNameValue) vName).getLocalName());
3569 elemName.obtainFingerprint(env.getConfiguration().getNamePool());
3570 } else {
3571 grumble("Element name must be either a string or a QName", "XPTY0004", offset);
3572 return new ErrorExpression();
3573 }
3574 inst = new FixedElement(elemName,
3575 ((QueryModule) env).getActiveNamespaceCodes(),
3576 ((QueryModule) env).isInheritNamespaces(),
3577 true, null,
3578 ((QueryModule) env).getConstructionMode());
3579 if (content == null) {
3580 content = Literal.makeEmptySequence();
3581 }
3582 if (!((QueryModule) env).isPreserveNamespaces()) {
3583 content = new CopyOf(content, false, Validation.PRESERVE, null, true);
3584 }
3585 ((FixedElement) inst).setContentExpression(content);
3586 setLocation(inst, offset);
3587 //makeContentConstructor(content, (InstructionWithChildren) inst, offset);
3588 return makeTracer(offset, inst, LocationKind.LITERAL_RESULT_ELEMENT, elemName.getStructuredQName());
3589 } else {
3590 // it really is a computed element constructor: save the namespace context
3591 NamespaceResolver ns = new NamespaceResolverWithDefault(
3592 env.getNamespaceResolver(),
3593 env.getDefaultElementNamespace());
3594 inst = new ComputedElement(name, null, null,
3595 ((QueryModule) env).getConstructionMode(),
3596 ((QueryModule) env).isInheritNamespaces(),
3597 true);
3598 setLocation(inst);
3599 if (content == null) {
3600 content = Literal.makeEmptySequence();
3601 }
3602 if (!((QueryModule) env).isPreserveNamespaces()) {
3603 content = new CopyOf(content, false, Validation.PRESERVE, null, true);
3604 }
3605 ((ComputedElement) inst).setContentExpression(content);
3606 setLocation(inst, offset);
3607 //makeContentConstructor(content, (InstructionWithChildren) inst, offset);
3608 return makeTracer(offset, inst, StandardNames.XSL_ELEMENT, null);
3609 }
3610 }
3611
3612 /**
3613 * Parse an element constructor of the form
3614 * element qname { expr }
3615 *
3616 * @param offset the position in the source query
3617 * @return the compiled instruction
3618 * @throws XPathException if parsing fails
3619 */
3620
3621 private Expression parseNamedElementConstructor(int offset) throws XPathException {
3622 NodeName nodeName = makeNodeName(t.currentTokenValue, true);
3623 Expression content = null;
3624 nextToken();
3625 if (t.currentToken != Token.RCURLY) {
3626 content = parseExpression();
3627 expect(Token.RCURLY);
3628 }
3629 lookAhead(); // after an RCURLY
3630 nextToken();
3631 FixedElement el2 = new FixedElement(nodeName,
3632 ((QueryModule) env).getActiveNamespaceCodes(),
3633 ((QueryModule) env).isInheritNamespaces(),
3634 true, null,
3635 ((QueryModule) env).getConstructionMode());
3636 setLocation(el2, offset);
3637 if (content == null) {
3638 content = Literal.makeEmptySequence();
3639 }
3640 if (!((QueryModule) env).isPreserveNamespaces()) {
3641 content = new CopyOf(content, false, Validation.PRESERVE, null, true);
3642 }
3643 el2.setContentExpression(content);
3644 return makeTracer(offset, el2, LocationKind.LITERAL_RESULT_ELEMENT, nodeName.getStructuredQName());
3645 }
3646
3647 /**
3648 * Parse an attribute constructor of the form
3649 * attribute {expr} {expr}
3650 *
3651 * @param offset position of the expression in the input
3652 * @return the compiled instruction
3653 * @throws XPathException if a static error is encountered
3654 */
3655
3656 /*@NotNull*/
3657 private Expression parseComputedAttributeConstructor(int offset) throws XPathException {
3658 nextToken();
3659 Expression name = parseExpression();
3660 expect(Token.RCURLY);
3661 lookAhead(); // must be done manually after an RCURLY
3662 nextToken();
3663 expect(Token.LCURLY);
3664 t.setState(Tokenizer.DEFAULT_STATE);
3665 nextToken();
3666 Expression content = null;
3667 if (t.currentToken != Token.RCURLY) {
3668 content = parseExpression();
3669 expect(Token.RCURLY);
3670 }
3671 lookAhead(); // after an RCURLY
3672 nextToken();
3673 if (name instanceof Literal) {
3674 GroundedValue vName = ((Literal) name).getValue();
3675 if (vName instanceof StringValue && !(vName instanceof AnyURIValue)) {
3676 String lex = ((StringValue) vName).getStringValue();
3677 if (lex.equals("xmlns") || lex.startsWith("xmlns:")) {
3678 grumble("Cannot create a namespace using an attribute constructor", "XQDY0044", offset);
3679 }
3680 NodeName attributeName;
3681 try {
3682 attributeName = makeNodeName(lex, false);
3683 } catch (XPathException staticError) {
3684 String code = staticError.getErrorCodeLocalPart();
3685 staticError.setLocator(makeLocation());
3686 if ("XPST0008".equals(code) || "XPST0081".equals(code)) {
3687 staticError.setErrorCode("XQDY0074");
3688 } else if ("XPST0003".equals(code)) {
3689 grumble("Invalid QName in attribute constructor: " + lex, "XQDY0074", offset);
3690 return new ErrorExpression();
3691 }
3692 throw staticError;
3693 }
3694 FixedAttribute fatt = new FixedAttribute(attributeName,
3695 Validation.STRIP,
3696 null);
3697 fatt.setRejectDuplicates();
3698 makeSimpleContent(content, fatt, offset);
3699 return makeTracer(offset, fatt, StandardNames.XSL_ATTRIBUTE, null);
3700 } else if (vName instanceof QNameValue) {
3701 QNameValue qnv = (QNameValue) vName;
3702 NodeName attributeName = new FingerprintedQName(
3703 qnv.getPrefix(), qnv.getNamespaceURI(), qnv.getLocalName());
3704 attributeName.obtainFingerprint(env.getConfiguration().getNamePool());
3705 FixedAttribute fatt = new FixedAttribute(attributeName,
3706 Validation.STRIP,
3707 null);
3708 fatt.setRejectDuplicates();
3709 makeSimpleContent(content, fatt, offset);
3710 return makeTracer(offset, fatt, StandardNames.XSL_ATTRIBUTE, null);
3711 }
3712 }
3713 ComputedAttribute att = new ComputedAttribute(name,
3714 null,
3715 env.getNamespaceResolver(),
3716 Validation.STRIP,
3717 null,
3718 true);
3719 att.setRejectDuplicates();
3720 makeSimpleContent(content, att, offset);
3721 return makeTracer(offset, att, StandardNames.XSL_ATTRIBUTE, null);
3722 }
3723
3724 /**
3725 * Parse an attribute constructor of the form
3726 * attribute name {expr}
3727 *
3728 * @param offset position of the expression in the source
3729 * @return the parsed expression
3730 * @throws XPathException if a static error is found
3731 */
3732
3733 private Expression parseNamedAttributeConstructor(int offset) throws XPathException {
3734 String warning = null;
3735 if (t.currentTokenValue.equals("xmlns") || t.currentTokenValue.startsWith("xmlns:")) {
3736 warning = "Cannot create a namespace declaration using an attribute constructor";
3737 }
3738 NodeName attributeName = makeNodeName(t.currentTokenValue, false);
3739 if (!attributeName.getURI().equals("") && attributeName.getPrefix().equals("")) {
3740 // This must be because the name was given as Q{uri}local. Invent a prefix.
3741 attributeName = new FingerprintedQName("_", attributeName.getURI(), attributeName.getLocalPart());
3742 }
3743 Expression attContent = null;
3744 nextToken();
3745 if (t.currentToken != Token.RCURLY) {
3746 attContent = parseExpression();
3747 expect(Token.RCURLY);
3748 }
3749 lookAhead(); // after an RCURLY
3750 nextToken();
3751 if (warning == null) {
3752 FixedAttribute att2 = new FixedAttribute(attributeName,
3753 Validation.STRIP,
3754 null);
3755 att2.setRejectDuplicates();
3756 att2.setRetainedStaticContext(env.makeRetainedStaticContext());
3757 makeSimpleContent(attContent, att2, offset);
3758 return makeTracer(offset, att2, LocationKind.LITERAL_RESULT_ATTRIBUTE, attributeName.getStructuredQName());
3759 } else {
3760 warning(warning);
3761 return new ErrorExpression(warning, "XQDY0044", false);
3762 }
3763 }
3764
3765 private Expression parseTextNodeConstructor(int offset) throws XPathException {
3766 nextToken();
3767 Expression value;
3768 if (t.currentToken == Token.RCURLY && allowXPath31Syntax) {
3769 value = Literal.makeEmptySequence();
3770 } else {
3771 value = parseExpression();
3772 }
3773 expect(Token.RCURLY);
3774 lookAhead(); // after an RCURLY
3775 nextToken();
3776 Expression select = stringify(value, true, env);
3777 ValueOf vof = new ValueOf(select, false, true);
3778 setLocation(vof, offset);
3779 return makeTracer(offset, vof, StandardNames.XSL_TEXT, null);
3780 }
3781
3782 private Expression parseCommentConstructor(int offset) throws XPathException {
3783 nextToken();
3784 Expression value;
3785 if (t.currentToken == Token.RCURLY && allowXPath31Syntax) {
3786 value = Literal.makeEmptySequence();
3787 } else {
3788 value = parseExpression();
3789 }
3790 expect(Token.RCURLY);
3791 lookAhead(); // after an RCURLY
3792 nextToken();
3793 Comment com = new Comment();
3794 makeSimpleContent(value, com, offset);
3795 return makeTracer(offset, com, StandardNames.XSL_COMMENT, null);
3796 }
3797
3798 /**
3799 * Parse a processing instruction constructor of the form
3800 * processing-instruction {expr} {expr}
3801 *
3802 * @param offset the position of the expression in the source query
3803 * @return the compiled instruction
3804 * @throws XPathException if parsing fails
3805 */
3806
3807 private Expression parseProcessingInstructionConstructor(int offset) throws XPathException {
3808 nextToken();
3809 Expression name = parseExpression();
3810 expect(Token.RCURLY);
3811 lookAhead(); // must be done manually after an RCURLY
3812 nextToken();
3813 expect(Token.LCURLY);
3814 t.setState(Tokenizer.DEFAULT_STATE);
3815 nextToken();
3816 Expression content = null;
3817 if (t.currentToken != Token.RCURLY) {
3818 content = parseExpression();
3819 expect(Token.RCURLY);
3820 }
3821 lookAhead(); // after an RCURLY
3822 nextToken();
3823 ProcessingInstruction pi = new ProcessingInstruction(name);
3824 makeSimpleContent(content, pi, offset);
3825 return makeTracer(offset, pi, StandardNames.XSL_PROCESSING_INSTRUCTION, null);
3826 }
3827
3828 /**
3829 * Parse a processing instruction constructor of the form
3830 * processing-instruction name { expr }
3831 *
3832 * @param offset position of the expression in the source
3833 * @return the parsed expression
3834 * @throws XPathException if a static error is found
3835 */
3836
3837 private Expression parseNamedProcessingInstructionConstructor(int offset) throws XPathException {
3838 String target = t.currentTokenValue;
3839 String warning = null;
3840 if (target.equalsIgnoreCase("xml")) {
3841 warning = "A processing instruction must not be named 'xml' in any combination of upper and lower case";
3842 }
3843 if (!NameChecker.isValidNCName(target)) {
3844 grumble("Invalid processing instruction name " + Err.wrap(target));
3845 }
3846 Expression piName = new StringLiteral(target);
3847 Expression piContent = null;
3848 nextToken();
3849 if (t.currentToken != Token.RCURLY) {
3850 piContent = parseExpression();
3851 expect(Token.RCURLY);
3852 }
3853 lookAhead(); // after an RCURLY
3854 nextToken();
3855 if (warning == null) {
3856 ProcessingInstruction pi2 = new ProcessingInstruction(piName);
3857 makeSimpleContent(piContent, pi2, offset);
3858 return makeTracer(offset, pi2, StandardNames.XSL_PROCESSING_INSTRUCTION, null);
3859 } else {
3860 warning(warning);
3861 return new ErrorExpression(warning, "XQDY0064", false);
3862 }
3863 }
3864
3865 /**
3866 * Parse a Try/Catch Expression.
3867 * This construct is XQuery-3.0 only. The syntax allows:
3868 * try { Expr } catch NameTest ('|' NameTest)* { Expr }
3869 * We don't currently implement the CatchVars
3870 */
3871
3872 protected Expression parseTryCatchExpression() throws XPathException {
3873 if (!allowXPath30Syntax) {
3874 grumble("try/catch requires XQuery 3.0");
3875 }
3876 int offset = t.currentTokenStartOffset;
3877 nextToken();
3878 Expression tryExpr;
3879 if (t.currentToken == Token.RCURLY && allowXPath31Syntax) {
3880 tryExpr = Literal.makeEmptySequence();
3881 } else {
3882 tryExpr = parseExpression();
3883 }
3884 TryCatch tryCatch = new TryCatch(tryExpr);
3885 setLocation(tryCatch, offset);
3886 expect(Token.RCURLY);
3887 lookAhead(); // must be done manually after an RCURLY
3888 nextToken();
3889 boolean foundOneCatch = false;
3890 List<QNameTest> tests = new ArrayList<>();
3891 while (isKeyword("catch")) {
3892 tests.clear();
3893 foundOneCatch = true;
3894 boolean seenCurly = false;
3895 do {
3896 nextToken();
3897 String tokv = t.currentTokenValue;
3898 switch (t.currentToken) {
3899 case Token.NAME:
3900 nextToken();
3901 tests.add(makeNameTest(Type.ELEMENT, tokv, false));
3902 break;
3903
3904 case Token.KEYWORD_CURLY:
3905 nextToken();
3906 tests.add(makeNameTest(Type.ELEMENT, tokv, false));
3907 seenCurly = true;
3908 break;
3909
3910 case Token.PREFIX:
3911 nextToken();
3912 tests.add(makeNamespaceTest(Type.ELEMENT, tokv));
3913 break;
3914
3915 case Token.SUFFIX:
3916 nextToken();
3917 tokv = t.currentTokenValue;
3918 if (t.currentToken == Token.NAME) {
3919 // OK
3920 } else if (t.currentToken == Token.KEYWORD_CURLY) {
3921 // OK
3922 seenCurly = true;
3923 } else {
3924 grumble("Expected name after '*:'");
3925 }
3926 nextToken();
3927 tests.add(makeLocalNameTest(Type.ELEMENT, tokv));
3928 break;
3929
3930 case Token.STAR:
3931 case Token.MULT:
3932 nextToken();
3933 tests.add(AnyNodeTest.getInstance());
3934 break;
3935
3936 default:
3937 grumble("Unrecognized name test");
3938 return null;
3939 }
3940 }
3941 while (t.currentToken == Token.UNION && !t.currentTokenValue.equals("union")); // must be "|" not "union"!
3942 if (!seenCurly) {
3943 expect(Token.LCURLY);
3944 nextToken();
3945 }
3946 QNameTest test;
3947 if (tests.size() == 1) {
3948 test = tests.get(0);
3949 } else {
3950 test = new UnionQNameTest(tests);
3951 }
3952 catchDepth++;
3953 Expression catchExpr;
3954 if (t.currentToken == Token.RCURLY && allowXPath31Syntax) {
3955 catchExpr = Literal.makeEmptySequence();
3956 } else {
3957 catchExpr = parseExpression();
3958 }
3959 tryCatch.addCatchExpression(test, catchExpr);
3960 expect(Token.RCURLY);
3961 lookAhead(); // must be done manually after an RCURLY
3962 nextToken();
3963 catchDepth--;
3964 }
3965 if (!foundOneCatch) {
3966 grumble("After try{}, expected 'catch'");
3967 }
3968
3969 return tryCatch;
3970 }
3971
3972
3973 /**
3974 * Parse a computed namespace constructor of the form
3975 * namespace {expr}{expr}
3976 *
3977 * @param offset the location of the expression in the query source
3978 * @return the compiled Namespace instruction
3979 * @throws XPathException in the event of a syntax error
3980 */
3981
3982 /*@NotNull*/
3983 private Expression parseNamespaceConstructor(int offset) throws XPathException {
3984 if (!allowXPath30Syntax) {
3985 grumble("Namespace node constructors require XQuery 3.0");
3986 }
3987 nextToken();
3988 Expression nameExpr = parseExpression();
3989 expect(Token.RCURLY);
3990 lookAhead(); // must be done manually after an RCURLY
3991 nextToken();
3992 expect(Token.LCURLY);
3993 t.setState(Tokenizer.DEFAULT_STATE);
3994 nextToken();
3995 Expression content = null;
3996 if (t.currentToken != Token.RCURLY) {
3997 content = parseExpression();
3998 expect(Token.RCURLY);
3999 }
4000 lookAhead(); // after an RCURLY
4001 nextToken();
4002
4003 NamespaceConstructor instr = new NamespaceConstructor(nameExpr);
4004 setLocation(instr);
4005 makeSimpleContent(content, instr, offset);
4006 return makeTracer(offset, instr, StandardNames.XSL_NAMESPACE, null);
4007 }
4008
4009 /**
4010 * Parse a namespace node constructor of the form
4011 * namespace name { expr }
4012 *
4013 * @param offset the location of the expression in the query source
4014 * @return the compiled instruction
4015 * @throws XPathException in the event of a syntax error
4016 */
4017
4018 /*@NotNull*/
4019 private Expression parseNamedNamespaceConstructor(int offset) throws XPathException {
4020 if (!allowXPath30Syntax) {
4021 grumble("Namespace node constructors require XQuery 3.0");
4022 }
4023 String target = t.currentTokenValue;
4024 if (!NameChecker.isValidNCName(target)) {
4025 grumble("Invalid namespace prefix " + Err.wrap(target));
4026 }
4027 Expression nsName = new StringLiteral(target);
4028 Expression nsContent = null;
4029 nextToken();
4030 if (t.currentToken != Token.RCURLY) {
4031 nsContent = parseExpression();
4032 expect(Token.RCURLY);
4033 }
4034 lookAhead(); // after an RCURLY
4035 nextToken();
4036 NamespaceConstructor instr = new NamespaceConstructor(nsName);
4037 makeSimpleContent(nsContent, instr, offset);
4038 return makeTracer(offset, instr, StandardNames.XSL_NAMESPACE, null);
4039 }
4040
4041
4042 /**
4043 * Make the instructions for the children of a node with simple content (attribute, text, PI, etc)
4044 *
4045 * @param content the expression making up the simple content
4046 * @param inst the skeletal instruction for creating the node
4047 * @param offset the character position of this construct within the source query
4048 */
4049
4050 protected void makeSimpleContent(Expression content, SimpleNodeConstructor inst, int offset) {
4051 if (content == null) {
4052 inst.setSelect(new StringLiteral(StringValue.EMPTY_STRING));
4053 } else {
4054 inst.setSelect(stringify(content, false, env));
4055 }
4056 setLocation(inst, offset);
4057 }
4058
4059 /**
4060 * Parse pseudo-XML syntax in direct element constructors, comments, CDATA, etc.
4061 * This is handled by reading single characters from the Tokenizer until the
4062 * end of the tag (or an enclosed expression) is encountered.
4063 * This method is also used to read an end tag. Because an end tag is not an
4064 * expression, the method in this case returns a StringValue containing the
4065 * contents of the end tag.
4066 *
4067 * @param allowEndTag true if the context allows an End Tag to appear here
4068 * @return an Expression representing the result of parsing the constructor.
4069 * If an end tag was read, its contents will be returned as a StringValue.
4070 * @throws XPathException if parsing fails
4071 */
4072
4073 /*@NotNull*/
4074 private Expression parsePseudoXML(boolean allowEndTag) throws XPathException {
4075 try {
4076 Expression exp;
4077 int offset = t.inputOffset;
4078 // we're reading raw characters, so we don't want the currentTokenStartOffset
4079 char c = t.nextChar();
4080 switch (c) {
4081 case '!':
4082 c = t.nextChar();
4083 if (c == '-') {
4084 exp = parseCommentConstructor();
4085 } else if (c == '[') {
4086 grumble("A CDATA section is allowed only in element content");
4087 return null;
4088 // if CDATA were allowed here, we would have already read it
4089 } else {
4090 grumble("Expected '--' or '[CDATA[' after '<!'");
4091 return null;
4092 }
4093 break;
4094 case '?':
4095 exp = parsePIConstructor();
4096 break;
4097 case '/':
4098 if (allowEndTag) {
4099 FastStringBuffer sb = new FastStringBuffer(FastStringBuffer.C16);
4100 while (true) {
4101 c = t.nextChar();
4102 if (c == '>') {
4103 break;
4104 }
4105 sb.append(c);
4106 }
4107 return new StringLiteral(sb.toString());
4108 }
4109 grumble("Unmatched XML end tag");
4110 return new ErrorExpression();
4111 default:
4112 t.unreadChar();
4113 exp = parseDirectElementConstructor(allowEndTag);
4114 }
4115 setLocation(exp, offset);
4116 return exp;
4117 } catch (StringIndexOutOfBoundsException e) {
4118 grumble("End of input encountered while parsing direct constructor");
4119 return new ErrorExpression();
4120 }
4121 }
4122
4123 /**
4124 * Parse a direct element constructor
4125 *
4126 * @param isNested true if this constructor is nested directly as part of the content of another
4127 * element constructor. This has the effect that the child element is not copied, which means
4128 * that namespace inheritance (which only happens during copying) has no effect
4129 * @return the expression representing the constructor
4130 * @throws XPathException if a syntax error is found
4131 * @throws StringIndexOutOfBoundsException
4132 * if the end of input is encountered prematurely
4133 */
4134
4135 private Expression parseDirectElementConstructor(boolean isNested) throws XPathException, StringIndexOutOfBoundsException {
4136 NamePool pool = env.getConfiguration().getNamePool();
4137 boolean changesContext = false;
4138 int offset = t.inputOffset - 1;
4139 // we're reading raw characters, so we don't want the currentTokenStartOffset
4140 char c;
4141 FastStringBuffer buff = new FastStringBuffer(FastStringBuffer.C64);
4142 int namespaceCount = 0;
4143 while (true) {
4144 c = t.nextChar();
4145 if (c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == '/' || c == '>') {
4146 break;
4147 }
4148 buff.append(c);
4149 }
4150 String elname = buff.toString();
4151 if (elname.isEmpty()) {
4152 grumble("Expected element name after '<'");
4153 }
4154 //Used LinkedHashMap because it is friendly to retain the order of attributes.
4155 LinkedHashMap<String, AttributeDetails> attributes = new LinkedHashMap<>(10);
4156 while (true) {
4157 // loop through the attributes
4158 // We must process namespace declaration attributes first;
4159 // their scope applies to all preceding attribute names and values.
4160 // But finding the delimiting quote of an attribute value requires the
4161 // XPath expressions to be parsed, because they may contain nested quotes.
4162 // So we parse in "scanOnly" mode, which ignores any undeclared namespace
4163 // prefixes, use the result of this parse to determine the length of the
4164 // attribute value, save the value, and reparse it when all the namespace
4165 // declarations have been dealt with.
4166 c = skipSpaces(c);
4167 if (c == '/' || c == '>') {
4168 break;
4169 }
4170 int attOffset = t.inputOffset - 1;
4171 buff.setLength(0);
4172 // read the attribute name
4173 do {
4174 buff.append(c);
4175 c = t.nextChar();
4176 } while (c != ' ' && c != '\n' && c != '\r' && c != '\t' && c != '=');
4177 String attName = buff.toString();
4178 if (!NameChecker.isQName(attName)) {
4179 grumble("Invalid attribute name " + Err.wrap(attName, Err.ATTRIBUTE));
4180 }
4181 c = skipSpaces(c);
4182 expectChar(c, '=');
4183 c = t.nextChar();
4184 c = skipSpaces(c);
4185 char delim = c;
4186 boolean isNamespace = "xmlns".equals(attName) || attName.startsWith("xmlns:");
4187 int end;
4188 if (isNamespace) {
4189 end = makeNamespaceContent(t.input, t.inputOffset, delim);
4190 changesContext = true;
4191 } else {
4192 Expression avt;
4193 try {
4194 avt = makeAttributeContent(t.input, t.inputOffset, delim, true);
4195 } catch (XPathException err) {
4196 if (!err.hasBeenReported()) {
4197 grumble(err.getMessage());
4198 }
4199 throw err;
4200 }
4201
4202 // by convention, this returns the end position when called with scanOnly set
4203 end = (int) ((Int64Value) ((Literal) avt).getValue()).longValue();
4204
4205 }
4206 // save the value with its surrounding quotes
4207 String val = t.input.substring(t.inputOffset - 1, end + 1);
4208 // and without
4209 String rval = t.input.substring(t.inputOffset, end);
4210
4211 // account for any newlines found in the value
4212 // (note, subexpressions between curlies will have been parsed using a different tokenizer)
4213 String tail = val;
4214 int pos;
4215 while ((pos = tail.indexOf('\n')) >= 0) {
4216 t.incrementLineNumber(t.inputOffset - 1 + pos);
4217 tail = tail.substring(pos + 1);
4218 }
4219 t.inputOffset = end + 1;
4220
4221 if (isNamespace) {
4222 // Processing follows the resolution of bug 5083: doubled curly braces represent single
4223 // curly braces, single curly braces are not allowed.
4224 FastStringBuffer sb = new FastStringBuffer(rval.length());
4225 boolean prevDelim = false;
4226 boolean prevOpenCurly = false;
4227 boolean prevCloseCurly = false;
4228 for (int i = 0; i < rval.length(); i++) {
4229 char n = rval.charAt(i);
4230 if (n == delim) {
4231 prevDelim = !prevDelim;
4232 if (prevDelim) {
4233 continue;
4234 }
4235 }
4236 if (n == '{') {
4237 prevOpenCurly = !prevOpenCurly;
4238 if (prevOpenCurly) {
4239 continue;
4240 }
4241 } else if (prevOpenCurly) {
4242 grumble("Namespace must not contain an unescaped opening brace", "XQST0022");
4243 }
4244 if (n == '}') {
4245 prevCloseCurly = !prevCloseCurly;
4246 if (prevCloseCurly) {
4247 continue;
4248 }
4249 } else if (prevCloseCurly) {
4250 grumble("Namespace must not contain an unescaped closing brace", "XPST0003");
4251 }
4252 sb.append(n);
4253 }
4254 if (prevOpenCurly) {
4255 grumble("Namespace must not contain an unescaped opening brace", "XQST0022");
4256 }
4257 if (prevCloseCurly) {
4258 grumble("Namespace must not contain an unescaped closing brace", "XPST0003");
4259 }
4260 rval = sb.toString();
4261 String uri = uriLiteral(rval);
4262 if (!StandardURIChecker.getInstance().isValidURI(uri)) {
4263 grumble("Namespace must be a valid URI value", "XQST0046");
4264 }
4265 String prefix;
4266 if ("xmlns".equals(attName)) {
4267 prefix = "";
4268 if (uri.equals(NamespaceConstant.XML)) {
4269 grumble("Cannot have the XML namespace as the default namespace", "XQST0070");
4270 }
4271 } else {
4272 prefix = attName.substring(6);
4273 if (prefix.equals("xml") && !uri.equals(NamespaceConstant.XML)) {
4274 grumble("Cannot bind the prefix 'xml' to a namespace other than the XML namespace", "XQST0070");
4275 } else if (uri.equals(NamespaceConstant.XML) && !prefix.equals("xml")) {
4276 grumble("Cannot bind a prefix other than 'xml' to the XML namespace", "XQST0070");
4277 } else if (prefix.equals("xmlns")) {
4278 grumble("Cannot use xmlns as a namespace prefix", "XQST0070");
4279 }
4280
4281 if (uri.isEmpty()) {
4282 if (env.getConfiguration().getXMLVersion() == Configuration.XML10) {
4283 grumble("Namespace URI must not be empty", "XQST0085");
4284 }
4285 }
4286 }
4287 namespaceCount++;
4288 ((QueryModule) env).declareActiveNamespace(prefix, uri);
4289 }
4290 if (attributes.get(attName) != null) {
4291 if (isNamespace) {
4292 grumble("Duplicate namespace declaration " + attName, "XQST0071", attOffset);
4293 } else {
4294 grumble("Duplicate attribute name " + attName, "XQST0040", attOffset);
4295 }
4296 }
4297 // if (attName.equals("xml:id") && !NameChecker.isValidNCName(rval)) {
4298 // grumble("Value of xml:id must be a valid NCName", "XQST0082");
4299 // }
4300 AttributeDetails a = new AttributeDetails();
4301 a.value = val;
4302 a.startOffset = attOffset;
4303 attributes.put(attName, a);
4304
4305 // on return, the current character is the closing quote
4306 c = t.nextChar();
4307 if (!(c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == '/' || c == '>')) {
4308 grumble("There must be whitespace after every attribute except the last");
4309 }
4310 }
4311 StructuredQName qName = null;
4312 if (scanOnly) {
4313 qName = StandardNames.getStructuredQName(StandardNames.XSL_ELEMENT); // any name will do
4314 } else {
4315 try {
4316 String[] parts = NameChecker.getQNameParts(elname);
4317 String namespace = ((QueryModule) env).checkURIForPrefix(parts[0]);
4318 if (namespace == null) {
4319 grumble("Undeclared prefix in element name " + Err.wrap(elname, Err.ELEMENT), "XPST0081", offset);
4320 }
4321 qName = new StructuredQName(parts[0], namespace, parts[1]);
4322 } catch (QNameException e) {
4323 grumble("Invalid element name " + Err.wrap(elname, Err.ELEMENT), "XPST0003", offset);
4324 qName = StandardNames.getStructuredQName(StandardNames.XSL_ELEMENT); // any name will do
4325 }
4326 }
4327 int validationMode = ((QueryModule) env).getConstructionMode();
4328 FingerprintedQName fqn = new FingerprintedQName(
4329 qName.getPrefix(), qName.getURI(), qName.getLocalPart(), pool.allocateFingerprint(qName.getURI(), qName.getLocalPart()));
4330 FixedElement elInst = new FixedElement(fqn,
4331 ((QueryModule) env).getActiveNamespaceCodes(),
4332 ((QueryModule) env).isInheritNamespaces(),
4333 !isNested,
4334 null,
4335 validationMode);
4336
4337 setLocation(elInst, offset);
4338
4339 List<Expression> contents = new ArrayList<>(10);
4340
4341 IntHashSet attFingerprints = new IntHashSet(attributes.size());
4342 // we've checked for duplicate lexical QNames, but not for duplicate expanded-QNames
4343 for (Map.Entry<String, AttributeDetails> entry : attributes.entrySet()) {
4344 String attName = entry.getKey();
4345 AttributeDetails a = entry.getValue();
4346 String attValue = a.value;
4347 int attOffset = a.startOffset;
4348
4349 if ("xmlns".equals(attName) || attName.startsWith("xmlns:")) {
4350 // do nothing
4351 } else if (scanOnly) {
4352 // This means we are prescanning an attribute constructor, and we found a nested attribute
4353 // constructor, which we have prescanned; we now don't want to re-process the nested attribute
4354 // constructor because it might depend on things like variables declared in the containing
4355 // attribute constructor, and in any case we're going to come back to it again later.
4356 // See test qxmp180
4357 } else {
4358 NodeName attributeName = null;
4359 String attNamespace;
4360 try {
4361 String[] parts = NameChecker.getQNameParts(attName);
4362 if (parts[0].isEmpty()) {
4363 // attributes don't use the default namespace
4364 attNamespace = "";
4365 } else {
4366 attNamespace = ((QueryModule) env).checkURIForPrefix(parts[0]);
4367 }
4368 if (attNamespace == null) {
4369 grumble("Undeclared prefix in attribute name " +
4370 Err.wrap(attName, Err.ATTRIBUTE), "XPST0081", attOffset);
4371 }
4372 attributeName = new FingerprintedQName(parts[0], attNamespace, parts[1]);
4373 int key = attributeName.obtainFingerprint(pool);
4374 if (attFingerprints.contains(key)) {
4375 grumble("Duplicate expanded attribute name " + attName, "XQST0040", attOffset);
4376 }
4377 attFingerprints.add(key);
4378 } catch (QNameException e) {
4379 grumble("Invalid attribute name " + Err.wrap(attName, Err.ATTRIBUTE), "XPST0003", attOffset);
4380 }
4381
4382 assert attributeName != null;
4383 FixedAttribute attInst =
4384 new FixedAttribute(attributeName, Validation.STRIP, null);
4385
4386 setLocation(attInst);
4387 Expression select;
4388 try {
4389 select = makeAttributeContent(attValue, 1, attValue.charAt(0), false);
4390 } catch (XPathException err) {
4391 err.setIsStaticError(true);
4392 throw err;
4393 }
4394 attInst.setRetainedStaticContext(env.makeRetainedStaticContext());
4395 attInst.setSelect(select);
4396 attInst.setRejectDuplicates();
4397 setLocation(attInst);
4398 contents.add(makeTracer(attOffset, attInst, LocationKind.LITERAL_RESULT_ATTRIBUTE,
4399 attributeName.getStructuredQName()));
4400 }
4401 }
4402 if (c == '/') {
4403 // empty element tag
4404 expectChar(t.nextChar(), '>');
4405 } else {
4406 readElementContent(elname, contents);
4407 }
4408
4409 Expression[] elk = new Expression[contents.size()];
4410 for (int i = 0; i < contents.size(); i++) {
4411 // if the child expression creates another element,
4412 // suppress validation, as the parent already takes care of it
4413 if (validationMode != Validation.STRIP) {
4414 contents.get(i).suppressValidation(validationMode);
4415 }
4416 elk[i] = contents.get(i);
4417 }
4418 Block block = new Block(elk);
4419 if (changesContext) {
4420 block.setRetainedStaticContext(env.makeRetainedStaticContext());
4421 }
4422 elInst.setContentExpression(block);
4423
4424 // reset the in-scope namespaces to what they were before
4425
4426 for (int n = 0; n < namespaceCount; n++) {
4427 ((QueryModule) env).undeclareNamespace();
4428 }
4429
4430 return makeTracer(offset, elInst, LocationKind.LITERAL_RESULT_ELEMENT, qName);
4431 }
4432
4433 /**
4434 * Parse the content of an attribute in a direct element constructor. This may contain nested expressions
4435 * within curly braces. A particular problem is that the namespaces used in the expression may not yet be
4436 * known. This means we need the ability to parse in "scanOnly" mode, where undeclared namespace prefixes
4437 * are ignored.
4438 * <p>The code is based on the XSLT code in {@link AttributeValueTemplate#make}: the main difference is that
4439 * character entities and built-in entity references need to be recognized and expanded. Also, whitespace
4440 * needs to be normalized, mimicking the action of an XML parser</p>
4441 *
4442 * @param avt the content of the attribute as written, including variable portions enclosed in curly braces
4443 * @param start the character position in the attribute value where parsing should start
4444 * @param terminator a character that is to be taken as marking the end of the expression
4445 * @param scanOnly if the purpose of this parse is simply to locate the end of the attribute value, and not
4446 * to report any semantic errors.
4447 * @return the expression that will evaluate the content of the attribute
4448 * @throws XPathException if parsing fails
4449 */
4450
4451 /*@Nullable*/
4452 private Expression makeAttributeContent(/*@NotNull*/ String avt,
4453 int start,
4454 char terminator,
4455 boolean scanOnly) throws XPathException {
4456
4457 Location loc = makeLocation();
4458 List<Expression> components = new ArrayList<>(10);
4459
4460 int i0, i1, i2, i8, i9, len, last;
4461 last = start;
4462 len = avt.length();
4463 while (last < len) {
4464 i2 = avt.indexOf(terminator, last);
4465 if (i2 < 0) {
4466 XPathException e = new XPathException("Attribute constructor is not properly terminated");
4467 e.setIsStaticError(true);
4468 throw e;
4469 }
4470
4471 i0 = avt.indexOf("{", last);
4472 i1 = avt.indexOf("{{", last);
4473 i8 = avt.indexOf("}", last);
4474 i9 = avt.indexOf("}}", last);
4475
4476 if ((i0 < 0 || i2 < i0) && (i8 < 0 || i2 < i8)) { // found end of string
4477 addStringComponent(components, avt, last, i2);
4478
4479 // look for doubled quotes, and skip them (for now)
4480 if (i2 + 1 < avt.length() && avt.charAt(i2 + 1) == terminator) {
4481 components.add(new StringLiteral(terminator + ""));
4482 last = i2 + 2;
4483 //continue;
4484 } else {
4485 last = i2;
4486 break;
4487 }
4488 } else if (i8 >= 0 && (i0 < 0 || i8 < i0)) { // found a "}"
4489 if (i8 != i9) { // a "}" that isn't a "}}"
4490 XPathException e = new XPathException(
4491 "Closing curly brace in attribute value template \"" + avt + "\" must be doubled");
4492 e.setIsStaticError(true);
4493 throw e;
4494 }
4495 addStringComponent(components, avt, last, i8 + 1);
4496 last = i8 + 2;
4497 } else if (i1 >= 0 && i1 == i0) { // found a doubled "{{"
4498 addStringComponent(components, avt, last, i1 + 1);
4499 last = i1 + 2;
4500 } else if (i0 >= 0) { // found a single "{"
4501 if (i0 > last) {
4502 addStringComponent(components, avt, last, i0);
4503 }
4504 Expression exp;
4505 XPathParser parser = newParser();
4506 ((XQueryParser) parser).executable = executable;
4507 parser.setAllowAbsentExpression(allowXPath31Syntax);
4508 parser.setScanOnly(scanOnly);
4509 parser.setRangeVariableStack(rangeVariables);
4510 parser.setCatchDepth(catchDepth);
4511 exp = parser.parse(avt, i0 + 1, Token.RCURLY, env);
4512 if (!scanOnly) {
4513 exp = exp.simplify();
4514 }
4515 last = parser.getTokenizer().currentTokenStartOffset + 1;
4516 components.add(makeStringJoin(exp, env));
4517
4518 } else {
4519 throw new IllegalStateException("Internal error parsing direct attribute constructor");
4520 }
4521 }
4522
4523 // if this is simply a prescan, return the position of the end of the
4524 // AVT, so we can parse it properly later
4525
4526 if (scanOnly) {
4527 return Literal.makeLiteral(Int64Value.makeIntegerValue(last));
4528 }
4529
4530 // is it empty?
4531
4532 if (components.isEmpty()) {
4533 return new StringLiteral(StringValue.EMPTY_STRING);
4534 }
4535
4536 // is it a single component?
4537
4538 if (components.size() == 1) {
4539 return components.get(0);
4540 }
4541
4542 // otherwise, return an expression that concatenates the components
4543
4544
4545 Expression[] args = new Expression[components.size()];
4546 components.toArray(args);
4547 RetainedStaticContext rsc = new RetainedStaticContext(env);
4548 Expression fn = SystemFunction.makeCall("concat", rsc, args);
4549 assert fn != null;
4550 fn.setLocation(loc);
4551 return fn;
4552 //return visitor.simplify(fn);
4553
4554 }
4555
4556 private void addStringComponent(/*@NotNull*/ List<Expression> components, /*@NotNull*/ String avt, int start, int end)
4557 throws XPathException {
4558 // analyze fixed text within the value of a direct attribute constructor.
4559 if (start < end) {
4560 FastStringBuffer sb = new FastStringBuffer(end - start);
4561 for (int i = start; i < end; i++) {
4562 char c = avt.charAt(i);
4563 switch (c) {
4564 case '&': {
4565 int semic = avt.indexOf(';', i);
4566 if (semic < 0) {
4567 grumble("No closing ';' found for entity or character reference");
4568 } else {
4569 String entity = avt.substring(i + 1, semic);
4570 sb.append(new Unescaper(env.getConfiguration().getValidCharacterChecker()).analyzeEntityReference(entity));
4571 i = semic;
4572 }
4573 break;
4574 }
4575 case '<':
4576 grumble("The < character must not appear in attribute content");
4577 break;
4578 case '\n':
4579 case '\t':
4580 sb.append(' ');
4581 break;
4582 case '\r':
4583 sb.append(' ');
4584 if (i + 1 < end && avt.charAt(i + 1) == '\n') {
4585 i++;
4586 }
4587 break;
4588 default:
4589 sb.append(c);
4590
4591 }
4592 }
4593 components.add(new StringLiteral(sb.toString()));
4594 }
4595 }
4596
4597 /**
4598 * Parse the content of an namespace declaration attribute in a direct element constructor. This is simpler
4599 * than an ordinary attribute because it does not contain nested expressions in curly braces. (But see bug 5083).
4600 *
4601 * @param avt the content of the attribute as written, including variable portions enclosed in curly braces
4602 * @param start the character position in the attribute value where parsing should start
4603 * @param terminator a character that is to be taken as marking the end of the expression
4604 * @return the position of the end of the URI value
4605 * @throws XPathException if parsing fails
4606 */
4607
4608 private int makeNamespaceContent(/*@NotNull*/ String avt, int start, char terminator) throws XPathException {
4609
4610 int i2, len, last;
4611 last = start;
4612 len = avt.length();
4613 while (last < len) {
4614 i2 = avt.indexOf(terminator, last);
4615 if (i2 < 0) {
4616 XPathException e = new XPathException("Namespace declaration is not properly terminated");
4617 e.setIsStaticError(true);
4618 throw e;
4619 }
4620
4621 // look for doubled quotes, and skip them (for now)
4622 if (i2 + 1 < avt.length() && avt.charAt(i2 + 1) == terminator) {
4623 last = i2 + 2;
4624 //continue;
4625 } else {
4626 last = i2;
4627 break;
4628 }
4629 }
4630
4631 // return the position of the end of the literal
4632 return last;
4633
4634 }
4635
4636 /**
4637 * Read the content of a direct element constructor
4638 *
4639 * @param startTag the element start tag
4640 * @param components an empty list, to which the expressions comprising the element contents are added
4641 * @throws XPathException if any static errors are detected
4642 */
4643 private void readElementContent(String startTag, /*@NotNull*/ List<Expression> components) throws XPathException {
4644 try {
4645 boolean afterEnclosedExpr = false;
4646 while (true) {
4647 // read all the components of the element value
4648 FastStringBuffer text = new FastStringBuffer(FastStringBuffer.C64);
4649 char c;
4650 boolean containsEntities = false;
4651 while (true) {
4652 c = t.nextChar();
4653 if (c == '<') {
4654 // See if we've got a CDATA section
4655 if (t.nextChar() == '!') {
4656 if (t.nextChar() == '[') {
4657 readCDATASection(text);
4658 containsEntities = true;
4659 continue;
4660 } else {
4661 t.unreadChar();
4662 t.unreadChar();
4663 }
4664 } else {
4665 t.unreadChar();
4666 }
4667 break;
4668 } else if (c == '&') {
4669 text.append(readEntityReference());
4670 containsEntities = true;
4671 } else if (c == '}') {
4672 c = t.nextChar();
4673 if (c != '}') {
4674 grumble("'}' must be written as '}}' within element content");
4675 }
4676 text.append(c);
4677 } else if (c == '{') {
4678 c = t.nextChar();
4679 if (c != '{') {
4680 c = '{';
4681 break;
4682 }
4683 text.append(c);
4684 } else {
4685 if (!charChecker.test(c) && !UTF16CharacterSet.isSurrogate(c)) {
4686 grumble("Character code " + c + " is not a valid XML character");
4687 }
4688 text.append(c);
4689 }
4690 }
4691 if (!text.isEmpty() &&
4692 (containsEntities |
4693 ((QueryModule) env).isPreserveBoundarySpace() ||
4694 !Whitespace.isWhite(text))) {
4695 ValueOf inst = new ValueOf(new StringLiteral(new StringValue(text.condense())), false, false);
4696 setLocation(inst);
4697 components.add(inst);
4698 afterEnclosedExpr = false;
4699 }
4700 if (c == '<') {
4701 Expression exp = parsePseudoXML(true);
4702 // An end tag can appear here, and is returned as a string value
4703 if (exp instanceof StringLiteral) {
4704 String endTag = ((StringLiteral) exp).getStringValue();
4705 if (Whitespace.isWhitespace(endTag.charAt(0))) {
4706 grumble("End tag contains whitespace before the name");
4707 }
4708 endTag = Whitespace.trim(endTag);
4709 if (endTag.equals(startTag)) {
4710 return;
4711 } else {
4712 grumble("End tag </" + endTag +
4713 "> does not match start tag <" + startTag + '>', "XQST0118");
4714 // error code allocated by spec bug 11609
4715 }
4716 } else {
4717 components.add(exp);
4718 }
4719 } else {
4720 // we read an '{' indicating an enclosed expression
4721 if (afterEnclosedExpr) {
4722 Expression previousComponent = components.get(components.size() - 1);
4723 boolean previousComponentIsNodeTest = true;
4724 UType previousItemType = previousComponent.getStaticUType(UType.ANY);
4725 previousComponentIsNodeTest = UType.ANY_NODE.subsumes(previousItemType);
4726 if (!previousComponentIsNodeTest) {
4727 // Add a zero-length text node, to prevent {"a"}{"b"} generating an intervening space
4728 // See tests (qxmp132, qxmp261)
4729 ValueOf inst = new ValueOf(new StringLiteral(StringValue.EMPTY_STRING), false, false);
4730 setLocation(inst);
4731 components.add(inst);
4732 }
4733 }
4734 t.unreadChar();
4735 t.setState(Tokenizer.DEFAULT_STATE);
4736 lookAhead();
4737 nextToken();
4738 if (t.currentToken == Token.RCURLY && allowXPath31Syntax) {
4739 components.add(Literal.makeEmptySequence());
4740 } else {
4741 Expression exp = parseExpression();
4742 if (!((QueryModule) env).isPreserveNamespaces()) {
4743 exp = new CopyOf(exp, false, Validation.PRESERVE, null, true);
4744 }
4745 components.add(exp);
4746 expect(Token.RCURLY);
4747 }
4748 afterEnclosedExpr = true;
4749 }
4750 }
4751 } catch (StringIndexOutOfBoundsException err) {
4752 grumble("No closing end tag found for direct element constructor");
4753 }
4754 }
4755
4756 /*@Nullable*/
4757 private Expression parsePIConstructor() throws XPathException {
4758 try {
4759 FastStringBuffer pi = new FastStringBuffer(FastStringBuffer.C64);
4760 int firstSpace = -1;
4761 while (!pi.toString().endsWith("?>")) {
4762 char c = t.nextChar();
4763 if (firstSpace < 0 && " \t\r\n".indexOf(c) >= 0) {
4764 firstSpace = pi.length();
4765 }
4766 pi.append(c);
4767 }
4768 pi.setLength(pi.length() - 2);
4769
4770 String target;
4771 String data = "";
4772 if (firstSpace < 0) {
4773 // there is no data part
4774 target = pi.toString();
4775 } else {
4776 // trim leading space from the data part, but not trailing space
4777 target = pi.toString().substring(0, firstSpace);
4778 firstSpace++;
4779 while (firstSpace < pi.length() && " \t\r\n".indexOf(pi.charAt(firstSpace)) >= 0) {
4780 firstSpace++;
4781 }
4782 data = pi.toString().substring(firstSpace);
4783 }
4784
4785 if (!NameChecker.isValidNCName(target)) {
4786 grumble("Invalid processing instruction name " + Err.wrap(target));
4787 }
4788
4789 if (target.equalsIgnoreCase("xml")) {
4790 grumble("A processing instruction must not be named 'xml' in any combination of upper and lower case");
4791 }
4792
4793 ProcessingInstruction instruction =
4794 new ProcessingInstruction(new StringLiteral(target));
4795 instruction.setSelect(new StringLiteral(data));
4796 setLocation(instruction);
4797 return instruction;
4798 } catch (StringIndexOutOfBoundsException err) {
4799 grumble("No closing '?>' found for processing instruction");
4800 return null;
4801 }
4802 }
4803
4804 private void readCDATASection(/*@NotNull*/ FastStringBuffer cdata) throws XPathException {
4805 try {
4806 char c;
4807 // CDATA section
4808 c = t.nextChar();
4809 expectChar(c, 'C');
4810 c = t.nextChar();
4811 expectChar(c, 'D');
4812 c = t.nextChar();
4813 expectChar(c, 'A');
4814 c = t.nextChar();
4815 expectChar(c, 'T');
4816 c = t.nextChar();
4817 expectChar(c, 'A');
4818 c = t.nextChar();
4819 expectChar(c, '[');
4820 while (!cdata.toString().endsWith("]]>")) {
4821 cdata.append(t.nextChar());
4822 }
4823 cdata.setLength(cdata.length() - 3);
4824 } catch (StringIndexOutOfBoundsException err) {
4825 grumble("No closing ']]>' found for CDATA section");
4826 }
4827 }
4828
4829 /*@Nullable*/
4830 private Expression parseCommentConstructor() throws XPathException {
4831 try {
4832 char c = t.nextChar();
4833 // XML-like comment
4834 expectChar(c, '-');
4835 FastStringBuffer comment = new FastStringBuffer(FastStringBuffer.C256);
4836 while (!comment.toString().endsWith("--")) {
4837 comment.append(t.nextChar());
4838 }
4839 if (t.nextChar() != '>') {
4840 grumble("'--' is not permitted in an XML comment");
4841 }
4842 CharSequence commentText = comment.subSequence(0, comment.length() - 2);
4843 Comment instruction = new Comment();
4844 instruction.setSelect(new StringLiteral(new StringValue(commentText)));
4845 setLocation(instruction);
4846 return instruction;
4847 } catch (StringIndexOutOfBoundsException err) {
4848 grumble("No closing '-->' found for comment constructor");
4849 return null;
4850 }
4851 }
4852
4853 /**
4854 * Convert an expression so it generates a space-separated sequence of strings
4855 *
4856 * @param exp the expression that calculates the content
4857 * @param noNodeIfEmpty if true, no node is produced when the value of the content
4858 * expression is an empty sequence. If false, the effect of supplying an empty sequence
4859 * is that a node is created whose string-value is a zero-length string. Set to true for
4860 * text node constructors, false for other kinds of node.
4861 * @param env the static context
4862 * @return an expression that computes the content and converts the result to a character string
4863 */
4864
4865 public static Expression stringify(Expression exp, boolean noNodeIfEmpty, StaticContext env) {
4866 // Compare with XSLLeafNodeConstructor.makeSimpleContentConstructor
4867 // Fast path if given a string literal
4868 if (exp instanceof StringLiteral) {
4869 return exp;
4870 }
4871 if (exp.getLocalRetainedStaticContext() == null) {
4872 exp.setRetainedStaticContext(env.makeRetainedStaticContext());
4873 }
4874 // Atomize the result
4875 exp = Atomizer.makeAtomizer(exp, null);
4876 // Convert each atomic value to a string
4877 exp = new AtomicSequenceConverter(exp, BuiltInAtomicType.STRING);
4878 //((AtomicSequenceConverter) exp).allocateConverter(config, false);
4879 // Join the resulting strings with a separator
4880 exp = SystemFunction.makeCall("string-join", exp.getRetainedStaticContext(), exp, new StringLiteral(StringValue.SINGLE_SPACE));
4881 assert exp != null;
4882 if (noNodeIfEmpty) {
4883 ((StringJoin) ((SystemFunctionCall) exp).getTargetFunction()).setReturnEmptyIfEmpty(true);
4884 }
4885 // All that's left for the instruction to do is to construct the right kind of node
4886 return exp;
4887 }
4888
4889 /**
4890 * Method to make a string literal from a token identified as a string
4891 * literal. This is trivial in XPath, but in XQuery the method is overridden
4892 * to identify pseudo-XML character and entity references
4893 *
4894 * @param token the string as written (or as returned by the tokenizer)
4895 * @return The string value of the string literal, after dereferencing entity and
4896 * character references
4897 * @throws XPathException if parsing fails
4898 */
4899
4900 @Override
4901 /*@NotNull*/
4902 protected Literal makeStringLiteral(/*@NotNull*/ String token) throws XPathException {
4903 StringLiteral lit;
4904 if (token.indexOf('&') == -1) {
4905 lit = new StringLiteral(token);
4906 } else {
4907 CharSequence sb = unescape(token);
4908 lit = new StringLiteral(StringValue.makeStringValue(sb));
4909 }
4910 setLocation(lit);
4911 return lit;
4912 }
4913
4914 /**
4915 * Unescape character references and built-in entity references in a string
4916 *
4917 * @param token the input string, which may include XML-style character references or built-in
4918 * entity references
4919 * @return the string with character references and built-in entity references replaced by their expansion
4920 * @throws XPathException if a malformed character or entity reference is found
4921 */
4922
4923 /*@NotNull*/
4924 protected CharSequence unescape(/*@NotNull*/ String token) throws XPathException {
4925 return new Unescaper(env.getConfiguration().getValidCharacterChecker()).unescape(token);
4926 }
4927
4928 public static class Unescaper {
4929
4930 private final IntPredicate characterChecker;
4931
4932 public Unescaper(IntPredicate characterChecker) {
4933 this.characterChecker = characterChecker;
4934 }
4935 public CharSequence unescape(String token) throws XPathException {
4936 FastStringBuffer sb = new FastStringBuffer(token.length());
4937 for (int i = 0; i < token.length(); i++) {
4938 char c = token.charAt(i);
4939 if (c == '&') {
4940 int semic = token.indexOf(';', i);
4941 if (semic < 0) {
4942 throw new XPathException("No closing ';' found for entity or character reference", "XPST0003");
4943 } else {
4944 String entity = token.substring(i + 1, semic);
4945 sb.append(analyzeEntityReference(entity));
4946 i = semic;
4947 }
4948 } else {
4949 sb.append(c);
4950 }
4951 }
4952 return sb;
4953 }
4954
4955
4956 /*@Nullable*/
4957 private String analyzeEntityReference(/*@NotNull*/ String entity) throws XPathException {
4958 if ("lt".equals(entity)) {
4959 return "<";
4960 } else if ("gt".equals(entity)) {
4961 return ">";
4962 } else if ("amp".equals(entity)) {
4963 return "&";
4964 } else if ("quot".equals(entity)) {
4965 return "\"";
4966 } else if ("apos".equals(entity)) {
4967 return "'";
4968 } else if (entity.length() < 2 || entity.charAt(0) != '#') {
4969 throw new XPathException("invalid character reference &" + entity + ';', "XPST0003");
4970 } else {
4971 //entity = entity.toLowerCase();
4972 return parseCharacterReference(entity);
4973 }
4974 }
4975
4976 /*@Nullable*/
4977 private String parseCharacterReference(/*@NotNull*/ String entity) throws XPathException {
4978 int value = 0;
4979 if (entity.charAt(1) == 'x') {
4980 if (entity.length() < 3) {
4981 throw new XPathException("No hex digits in hexadecimal character reference", "XPST0003");
4982 }
4983 entity = entity.toLowerCase();
4984 for (int i = 2; i < entity.length(); i++) {
4985 int digit = "0123456789abcdef".indexOf(entity.charAt(i));
4986 if (digit < 0) {
4987 throw new XPathException("Invalid hex digit '" + entity.charAt(i) + "' in character reference", "XPST0003");
4988 }
4989 value = (value * 16) + digit;
4990 if (value > UTF16CharacterSet.NONBMP_MAX) {
4991 throw new XPathException("Character reference exceeds Unicode codepoint limit", "XQST0090");
4992 }
4993 }
4994 } else {
4995 for (int i = 1; i < entity.length(); i++) {
4996 int digit = "0123456789".indexOf(entity.charAt(i));
4997 if (digit < 0) {
4998 throw new XPathException("Invalid digit '" + entity.charAt(i) + "' in decimal character reference", "XPST0003");
4999 }
5000 value = (value * 10) + digit;
5001 if (value > UTF16CharacterSet.NONBMP_MAX) {
5002 throw new XPathException("Character reference exceeds Unicode codepoint limit", "XQST0090");
5003 }
5004 }
5005 }
5006
5007 if (!characterChecker.test(value)) {
5008 throw new XPathException("Invalid XML character reference x"
5009 + Integer.toHexString(value), "XQST0090");
5010 }
5011 // following code borrowed from AElfred
5012 // Check for surrogates: 00000000 0000xxxx yyyyyyyy zzzzzzzz
5013 // (1101|10xx|xxyy|yyyy + 1101|11yy|zzzz|zzzz:
5014 if (value <= 0x0000ffff) {
5015 // no surrogates needed
5016 return "" + (char) value;
5017 } else {
5018 assert value <= 0x0010ffff;
5019 value -= 0x10000;
5020 // > 16 bits, surrogate needed
5021 return "" + (char) (0xd800 | (value >> 10))
5022 + (char) (0xdc00 | (value & 0x0003ff));
5023 }
5024 }
5025
5026 }
5027
5028 /**
5029 * Read a pseudo-XML character reference or entity reference.
5030 *
5031 * @return The character represented by the character or entity reference. Note
5032 * that this is a string rather than a char because a char only accommodates characters
5033 * up to 65535.
5034 * @throws XPathException if the character or entity reference is not well-formed
5035 */
5036
5037 /*@Nullable*/
5038 private String readEntityReference() throws XPathException {
5039 try {
5040 FastStringBuffer sb = new FastStringBuffer(FastStringBuffer.C64);
5041 while (true) {
5042 char c = t.nextChar();
5043 if (c == ';') {
5044 break;
5045 }
5046 sb.append(c);
5047 }
5048 String entity = sb.toString();
5049 return new Unescaper(env.getConfiguration().getValidCharacterChecker()).analyzeEntityReference(entity);
5050 } catch (StringIndexOutOfBoundsException err) {
5051 grumble("No closing ';' found for entity or character reference");
5052 return ""; // to keep the Java compiler happy
5053 }
5054 }
5055
5056 /**
5057 * Parse a string constructor: introduced in XQuery 3.1
5058 */
5059
5060 @Override
5061 public Expression parseStringTemplate(boolean complete) throws XPathException {
5062 // For legacy reasons (see bug 4208) parsing of string constructors is split
5063 // rather arbitrarily between the parser and tokenizer.
5064 // If the tokenizer sees ``[ then it scans until it finds either `{ or ]``, and
5065 // reports either STRING_TEMPLATE_INITIAL or STRING_TEMPLATE_COMPLETE (which cause
5066 // entry to this method). In the case of `{, we then call parseExpression(), which
5067 // should leave the tokenizer positioned on the closing "}". Because of bug 4208, the
5068 // tokenizer doesn't attempt to process this as }` - instead the parser then reads
5069 // character-by-character until it encounters the next `{ or ]``.
5070 int offset = t.currentTokenStartOffset;
5071 if (!allowXPath31Syntax) {
5072 throw new XPathException("String constructor expressions require XQuery 3.1");
5073 }
5074 if (complete) {
5075 Expression result = new StringLiteral(t.currentTokenValue);
5076 setLocation(result, offset);
5077 t.next();
5078 return result;
5079 } else {
5080 List<Expression> components = new ArrayList<>();
5081 components.add(new StringLiteral(t.currentTokenValue));
5082 t.next();
5083 outer:
5084 while (true) {
5085 boolean emptyExpression = t.currentToken == Token.RCURLY;
5086 if (t.currentToken != Token.STRING_TEMPLATE_FINAL && t.currentToken != Token.STRING_TEMPLATE_INTERMEDIATE) {
5087 if (emptyExpression) {
5088 components.add(new StringLiteral(StringValue.EMPTY_STRING));
5089 } else {
5090 Expression enclosed = parseExpression();
5091 Expression stringJoin = SystemFunction.makeCall(
5092 "string-join", env.makeRetainedStaticContext(), enclosed, new StringLiteral(" "));
5093 components.add(stringJoin);
5094 }
5095 if (t.currentToken != Token.RCURLY) {
5096 grumble("Expected '}' after enclosed expression in string constructor");
5097 }
5098 FastStringBuffer sb = new FastStringBuffer(256);
5099 char c = t.nextChar();
5100 if (c != '`') {
5101 grumble("Expected '}`' after enclosed expression in string constructor");
5102 }
5103 char latest = (char)0;
5104 char penult = (char)0;
5105 try {
5106 while (true) {
5107 c = t.nextChar();
5108 if (latest == '`' && c == '{') {
5109 sb.setLength(sb.length() - 1);
5110 components.add(new StringLiteral(sb));
5111 t.lookAhead();
5112 t.next();
5113 if (t.currentToken == Token.RCURLY) {
5114 components.add(Literal.makeEmptySequence());
5115 sb.setLength(0);
5116 continue;
5117 } else {
5118 continue outer;
5119 }
5120 } else if (penult == ']' && latest == '`' && c == '`') {
5121 sb.setLength(sb.length() - 2);
5122 components.add(new StringLiteral(sb));
5123 t.lookAhead();
5124 t.next();
5125 break outer;
5126 }
5127 sb.append(c);
5128 penult = latest;
5129 latest = c;
5130 }
5131 } catch (StringIndexOutOfBoundsException e) {
5132 grumble("String constructor is missing ]`` terminator ");
5133 }
5134 }
5135 // TODO: following code no longer used?
5136 if (t.currentToken == Token.STRING_TEMPLATE_FINAL) {
5137 components.add(new StringLiteral(t.currentTokenValue));
5138 t.next();
5139 break;
5140 } else if (t.currentToken == Token.STRING_TEMPLATE_INTERMEDIATE) {
5141 components.add(new StringLiteral(t.currentTokenValue));
5142 t.next();
5143 } else {
5144 grumble("Expected '}`' after enclosed expression in string template");
5145 }
5146 }
5147 Expression[] args = components.toArray(new Expression[0]);
5148 Expression result = SystemFunction.makeCall("concat", env.makeRetainedStaticContext(), args);
5149 setLocation(result, offset);
5150 return result;
5151 }
5152
5153 }
5154
5155 /**
5156 * Handle a URI literal. This is whitespace-normalized as well as being unescaped
5157 *
5158 * @param in the string as written
5159 * @return the URI after unescaping of entity and character references
5160 * followed by whitespace normalization
5161 * @throws net.sf.saxon.trans.XPathException
5162 * if an error is found while unescaping the URI
5163 */
5164
5165 public String uriLiteral(/*@NotNull*/ String in) throws XPathException {
5166 return Whitespace.applyWhitespaceNormalization(Whitespace.COLLAPSE, unescape(in)).toString();
5167 }
5168
5169 /**
5170 * Lookahead one token, catching any exception thrown by the tokenizer. This
5171 * method is only called from the query parser when switching from character-at-a-time
5172 * mode to tokenizing mode
5173 *
5174 * @throws XPathException if parsing fails
5175 */
5176
5177 protected void lookAhead() throws XPathException {
5178 try {
5179 t.lookAhead();
5180 } catch (XPathException err) {
5181 grumble(err.getMessage());
5182 }
5183 }
5184
5185 @Override
5186 protected boolean atStartOfRelativePath() {
5187 return t.currentToken == Token.TAG || super.atStartOfRelativePath();
5188 // "<" after "/" is recognized in XQuery but not in XPath.
5189 }
5190
5191 @Override
5192 protected void testPermittedAxis(byte axis, String errorCode) throws XPathException {
5193 if (axis == AxisInfo.NAMESPACE && language == XQUERY) {
5194 grumble("The namespace axis is not available in XQuery", errorCode);
5195 }
5196 }
5197
5198 /**
5199 * Skip whitespace.
5200 *
5201 * @param c the current character
5202 * @return the first character after any whitespace
5203 * @throws StringIndexOutOfBoundsException
5204 * if the end of input is encountered
5205 */
5206
5207 private char skipSpaces(char c) throws StringIndexOutOfBoundsException {
5208 while (c == ' ' || c == '\n' || c == '\r' || c == '\t') {
5209 c = t.nextChar();
5210 }
5211 return c;
5212 }
5213
5214 /**
5215 * Test whether the current character is the expected character.
5216 *
5217 * @param actual The character that was read
5218 * @param expected The character that was expected
5219 * @throws XPathException if they are different
5220 */
5221
5222 private void expectChar(char actual, char expected) throws XPathException {
5223 if (actual != expected) {
5224 grumble("Expected '" + expected + "', found '" + actual + '\'');
5225 }
5226 }
5227
5228 /**
5229 * Get the current language (XPath or XQuery)
5230 */
5231
5232 /*@NotNull*/
5233 protected String getLanguage() {
5234 return "XQuery";
5235 }
5236
5237 private static class AttributeDetails {
5238 String value;
5239 int startOffset;
5240 }
5241
5242 private static class Import {
5243 /*@Nullable*/ String namespaceURI;
5244 List<String> locationURIs;
5245 }
5246 }
5247