Debian Codegraph @

net/sf/saxon/expr/AxisExpression.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.expr;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.expr.parser.*;
12 import net.sf.saxon.om.*;
13 import net.sf.saxon.pattern.*;
14 import net.sf.saxon.trace.ExpressionPresenter;
15 import net.sf.saxon.trans.XPathException;
16 import net.sf.saxon.tree.iter.AxisIterator;
17 import net.sf.saxon.tree.util.FastStringBuffer;
18 import net.sf.saxon.type.*;
19 import net.sf.saxon.value.Cardinality;
20 import net.sf.saxon.z.IntHashSet;
21 import net.sf.saxon.z.IntIterator;
22 import net.sf.saxon.z.IntSet;
23
24 import java.util.*;
25
26
27 /**
28 * An AxisExpression is always obtained by simplifying a PathExpression.
29 * It represents a PathExpression that starts at the context node, and uses
30 * a simple node-test with no filters. For example "*", "title", "./item",
31 * "@*", or "ancestor::chapter*".
32 * <p>An AxisExpression delivers nodes in axis order (not in document order).
33 * To get nodes in document order, in the case of a reverse axis, the expression
34 * should be wrapped in a call on reverse().</p>
35 */
36
37 public final class AxisExpression extends Expression {
38
39 private byte axis;
40 /*@Nullable*/
41 private NodeTest test;
42 /*@Nullable*/
43 private ItemType itemType = null;
44 private ContextItemStaticInfo staticInfo = ContextItemStaticInfo.DEFAULT;
45 private int computedCardinality = -1;
46 private boolean doneTypeCheck = false;
47 private boolean doneOptimize = false;
48
49 /**
50 * Constructor for an AxisExpression whose origin is the context item
51 *
52 * @param axis The axis to be used in this AxisExpression: relevant constants are defined
53 * in class {@link net.sf.saxon.om.AxisInfo}.
54 * @param nodeTest The conditions to be satisfied by selected nodes. May be null,
55 * indicating that any node on the axis is acceptable
56 * @see net.sf.saxon.om.AxisInfo
57 */
58
59 public AxisExpression(byte axis, /*@Nullable*/ NodeTest nodeTest) {
60 this.axis = axis;
61 this.test = nodeTest;
62 }
63
64 /**
65 * Set the axis
66 *
67 * @param axis the new axis
68 */
69
70 public void setAxis(byte axis) {
71 this.axis = axis;
72 }
73
74 /**
75 * Get a name identifying the kind of expression, in terms meaningful to a user.
76 *
77 * @return a name identifying the kind of expression, in terms meaningful to a user.
78 * The name will always be in the form of a lexical XML QName, and should match the name used
79 * in explain() output displaying the expression.
80 */
81
82 public String getExpressionName() {
83 return "axisStep";
84 }
85
86 /**
87 * Simplify an expression
88 */
89
90 /*@NotNull*/
91 public Expression simplify() throws XPathException {
92 Expression e2 = super.simplify();
93 if (e2 != this) {
94 return e2;
95 }
96 if ((test == null || test == AnyNodeTest.getInstance()) &&
97 (axis == AxisInfo.PARENT || axis == AxisInfo.ANCESTOR)) {
98 // get more precise type information for parent/ancestor nodes
99 test = MultipleNodeKindTest.PARENT_NODE;
100 }
101 return this;
102 }
103
104 /**
105 * Type-check the expression
106 */
107
108 /*@NotNull*/
109 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
110 ItemType contextItemType = contextInfo.getItemType();
111 boolean noWarnings = doneOptimize || (doneTypeCheck && this.staticInfo.getItemType().equals(contextItemType));
112 doneTypeCheck = true;
113 if (contextItemType == ErrorType.getInstance()) {
114 // There is no context item. In principle we could raise XPTY0020 ("Context item is not a node"),
115 // which is a type error and therefore can be thrown statically. But many test cases expect
116 // XPDY0002 ("Context item absent") which for inexplicable reasons is a dynamic error rather than
117 // a type error, and therefore cannot be raised until execution time.
118 XPathException err = new XPathException("Axis step " + this +
119 " cannot be used here: the context item is absent");
120 //err.setIsTypeError(true);
121 err.setErrorCode("XPDY0002");
122 err.setLocation(getLocation());
123 throw err;
124 } else {
125 staticInfo = contextInfo;
126 }
127 Configuration config = visitor.getConfiguration();
128
129 if (contextItemType.getGenre() != Genre.NODE) {
130 TypeHierarchy th = config.getTypeHierarchy();
131 int relation = th.relationship(contextItemType, AnyNodeTest.getInstance());
132 if (relation == TypeHierarchy.DISJOINT) {
133 XPathException err = new XPathException("Axis step " + this +
134 " cannot be used here: the context item is not a node");
135 err.setIsTypeError(true);
136 err.setErrorCode("XPTY0020");
137 err.setLocation(getLocation());
138 throw err;
139 } else if (relation == TypeHierarchy.OVERLAPS || relation == TypeHierarchy.SUBSUMES) {
140 // need to insert a dynamic check of the context item type
141 Expression thisExp = checkPlausibility(visitor, contextInfo, !noWarnings);
142 if (Literal.isEmptySequence(thisExp)) {
143 return thisExp;
144 }
145 ContextItemExpression exp = new ContextItemExpression();
146 ExpressionTool.copyLocationInfo(this, exp);
147 RoleDiagnostic role = new RoleDiagnostic(RoleDiagnostic.AXIS_STEP, "", axis);
148 role.setErrorCode("XPTY0020");
149 ItemChecker checker = new ItemChecker(exp, AnyNodeTest.getInstance(), role);
150 ExpressionTool.copyLocationInfo(this, checker);
151 SimpleStepExpression step = new SimpleStepExpression(checker, thisExp);
152 ExpressionTool.copyLocationInfo(this, step);
153 return step;
154 }
155 }
156
157 if (visitor.getStaticContext().getOptimizerOptions().isSet(OptimizerOptions.VOID_EXPRESSIONS)) {
158 return checkPlausibility(visitor, contextInfo, !noWarnings);
159 } else {
160 return this;
161 }
162 }
163
164 private Expression checkPlausibility(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo, boolean warnings)
165 throws XPathException {
166 StaticContext env = visitor.getStaticContext();
167 Configuration config = env.getConfiguration();
168 ItemType contextType = contextInfo.getItemType();
169
170 if (!(contextType instanceof NodeTest)) {
171 contextType = AnyNodeTest.getInstance();
172 }
173
174 // New code in terms of UTypes
175
176 // Test whether the requested nodetest is consistent with the requested axis
177 if (test != null && !AxisInfo.getTargetUType(UType.ANY_NODE, axis).overlaps(test.getUType())) {
178 if (warnings) {
179 visitor.issueWarning("The " + AxisInfo.axisName[axis] + " axis will never select " +
180 test.getUType().toStringWithIndefiniteArticle(),
181 getLocation());
182 }
183 return Literal.makeEmptySequence();
184 }
185
186 if (test instanceof NameTest && axis == AxisInfo.NAMESPACE && !((NameTest) test).getNamespaceURI().isEmpty()) {
187 if (warnings) {
188 visitor.issueWarning("The names of namespace nodes are never prefixed, so this axis step will never select anything",
189 getLocation());
190 }
191 return Literal.makeEmptySequence();
192 }
193
194 // Test whether the axis ever selects anything, when starting at this context node
195 UType originUType = contextType.getUType();
196 UType targetUType = AxisInfo.getTargetUType(originUType, axis);
197 UType testUType = test == null ? UType.ANY_NODE : test.getUType();
198 if (targetUType.equals(UType.VOID)) {
199 if (warnings) {
200 visitor.issueWarning("The " + AxisInfo.axisName[axis] + " axis starting at " +
201 originUType.toStringWithIndefiniteArticle() + " will never select anything",
202 getLocation());
203 }
204 return Literal.makeEmptySequence();
205 }
206
207 // Test whether the axis ever selects a node of the right kind, when starting at this context node
208 if (!targetUType.overlaps(testUType)) {
209 if (warnings) {
210 visitor.issueWarning("The " + AxisInfo.axisName[axis] + " axis starting at " +
211 originUType.toStringWithIndefiniteArticle() + " will never select " +
212 test.getUType().toStringWithIndefiniteArticle(),
213 getLocation());
214 }
215 return Literal.makeEmptySequence();
216 }
217
218 // For an X-or-self axis, if X never selects anything, then substitute the self axis.
219 byte nonSelf = AxisInfo.excludeSelfAxis[axis];
220 UType kind = test == null ? UType.ANY_NODE : test.getUType();
221 if (axis != nonSelf) {
222 UType nonSelfTarget = AxisInfo.getTargetUType(originUType, nonSelf);
223 if (!nonSelfTarget.overlaps(testUType)) {
224 axis = AxisInfo.SELF;
225 targetUType = AxisInfo.getTargetUType(originUType, axis);
226 }
227 }
228
229 ItemType target = targetUType.toItemType();
230 if (test == null || test instanceof AnyNodeTest) {
231 itemType = target;
232 } else if (target instanceof AnyNodeTest || targetUType.subsumes(test.getUType())) {
233 itemType = test;
234 } else {
235 itemType = new CombinedNodeTest((NodeTest) target, Token.INTERSECT, test);
236 }
237
238 int origin = contextType.getPrimitiveType();
239
240 if (test != null) {
241
242 // If the content type of the context item is known, see whether the node test can select anything
243
244 if (contextType instanceof DocumentNodeTest && kind.equals(UType.ELEMENT)) {
245 NodeTest elementTest = ((DocumentNodeTest) contextType).getElementTest();
246 Optional<IntSet> outermostElementNames = elementTest.getRequiredNodeNames();
247 if (outermostElementNames.isPresent()) {
248 Optional<IntSet> selectedElementNames = test.getRequiredNodeNames();
249 if (selectedElementNames.isPresent()) {
250 if (axis == AxisInfo.CHILD) {
251 // check that the name appearing in the step is one of the names allowed by the nodetest
252
253 if (selectedElementNames.get().intersect(outermostElementNames.get()).isEmpty()) {
254 if (warnings) {
255 visitor.issueWarning(
256 "Starting at a document node, the step is selecting an element whose name " +
257 "is not among the names of child elements permitted for this document node type", getLocation());
258 }
259
260 return Literal.makeEmptySequence();
261 }
262
263 if (env.getPackageData().isSchemaAware() &&
264 elementTest instanceof SchemaNodeTest &&
265 outermostElementNames.get().size() == 1) {
266 IntIterator oeni = outermostElementNames.get().iterator();
267 int outermostElementName = oeni.hasNext() ? oeni.next() : -1;
268 SchemaDeclaration decl = config.getElementDeclaration(outermostElementName);
269 if (decl == null) {
270 if (warnings) {
271 visitor.issueWarning("Element " + config.getNamePool().getEQName(outermostElementName) +
272 " is not declared in the schema", getLocation());
273 }
274 itemType = elementTest;
275 } else {
276 SchemaType contentType = decl.getType();
277 itemType = new CombinedNodeTest(
278 elementTest, Token.INTERSECT,
279 new ContentTypeTest(Type.ELEMENT, contentType, config, true));
280 }
281 } else {
282 itemType = elementTest;
283 }
284 return this;
285
286 } else if (axis == AxisInfo.DESCENDANT) {
287 // check that the name appearing in the step is one of the names allowed by the nodetest
288 boolean canMatchOutermost = !selectedElementNames.get().intersect(outermostElementNames.get()).isEmpty();
289 if (!canMatchOutermost) {
290 // The expression /descendant::x starting at the document node doesn't match the outermost
291 // element, so replace it by child::*/descendant::x, and check that
292 Expression path = ExpressionTool.makePathExpression(new AxisExpression(AxisInfo.CHILD, elementTest), new AxisExpression(AxisInfo.DESCENDANT, test));
293 ExpressionTool.copyLocationInfo(this, path);
294 return path.typeCheck(visitor, contextInfo);
295 }
296 }
297 }
298 }
299 }
300
301 SchemaType contentType = ((NodeTest) contextType).getContentType();
302 if (contentType == AnyType.getInstance()) {
303 // fast exit in non-schema-aware case
304 return this;
305 }
306
307 if (!env.getPackageData().isSchemaAware()) {
308 SchemaType ct = test.getContentType();
309 if (!(ct == AnyType.getInstance() || ct == Untyped.getInstance() || ct == AnySimpleType.getInstance() ||
310 ct == BuiltInAtomicType.ANY_ATOMIC || ct == BuiltInAtomicType.UNTYPED_ATOMIC ||
311 ct == BuiltInAtomicType.STRING)) {
312 if (warnings) {
313 visitor.issueWarning(
314 "The " + AxisInfo.axisName[axis] + " axis will never select any typed nodes, " +
315 "because the expression is being compiled in an environment that is not schema-aware",
316 getLocation());
317 }
318 return Literal.makeEmptySequence();
319 }
320 }
321
322 int targetfp = test.getFingerprint();
323 StructuredQName targetName = test.getMatchingNodeName();
324
325 if (contentType.isSimpleType()) {
326 if (warnings) {
327 if ((axis == AxisInfo.CHILD || axis == AxisInfo.DESCENDANT || axis == AxisInfo.DESCENDANT_OR_SELF) &&
328 UType.PARENT_NODE_KINDS.union(UType.ATTRIBUTE).subsumes(kind)) {
329 visitor.issueWarning(
330 "The " + AxisInfo.axisName[axis] + " axis will never select any " +
331 kind + " nodes when starting at " +
332 (origin == Type.ATTRIBUTE ? "an attribute node" : getStartingNodeDescription(contentType)),
333 getLocation());
334 } else if (axis == AxisInfo.CHILD && kind.equals(UType.TEXT) &&
335 (getParentExpression() instanceof Atomizer)) {
336 visitor.issueWarning(
337 "Selecting the text nodes of an element with simple content may give the " +
338 "wrong answer in the presence of comments or processing instructions. It is usually " +
339 "better to omit the '/text()' step",
340 getLocation());
341 } else if (axis == AxisInfo.ATTRIBUTE) {
342 Iterator extensions = config.getExtensionsOfType(contentType);
343 boolean found = false;
344 if (targetfp == -1) {
345 while (extensions.hasNext()) {
346 ComplexType extension = (ComplexType) extensions.next();
347 if (extension.allowsAttributes()) {
348 found = true;
349 break;
350 }
351 }
352 } else {
353 while (extensions.hasNext()) {
354 ComplexType extension = (ComplexType) extensions.next();
355 try {
356 if (extension.getAttributeUseType(targetName) != null) {
357 found = true;
358 break;
359 }
360 } catch (SchemaException e) {
361 // ignore the error
362 }
363 }
364 }
365 if (!found) {
366 visitor.issueWarning(
367 "The " + AxisInfo.axisName[axis] + " axis will never select " +
368 (targetName == null ?
369 "any attribute nodes" :
370 "an attribute node named " + getDiagnosticName(targetName, env)) +
371 " when starting at " + getStartingNodeDescription(contentType), getLocation());
372 // Despite the warning, leave the expression unchanged. This is because
373 // we don't necessarily know about all extended types at compile time:
374 // in particular, we don't seal the XML Schema namespace to block extensions
375 // of built-in types
376 }
377 }
378 }
379 } else if (((ComplexType) contentType).isSimpleContent() &&
380 (axis == AxisInfo.CHILD || axis == AxisInfo.DESCENDANT || axis == AxisInfo.DESCENDANT_OR_SELF) &&
381 UType.PARENT_NODE_KINDS.subsumes(kind)) {
382 // We don't need to consider extended types here, because a type with complex content
383 // can never be defined as an extension of a type with simple content
384 if (warnings) {
385 visitor.issueWarning("The " + AxisInfo.axisName[axis] + " axis will never select any " +
386 kind +
387 " nodes when starting at " +
388 getStartingNodeDescription(contentType) +
389 ", as this type requires simple content", getLocation());
390 }
391 return Literal.makeEmptySequence();
392 } else if (((ComplexType) contentType).isEmptyContent() &&
393 (axis == AxisInfo.CHILD || axis == AxisInfo.DESCENDANT || axis == AxisInfo.DESCENDANT_OR_SELF)) {
394 for (Iterator iter = config.getExtensionsOfType(contentType); iter.hasNext(); ) {
395 ComplexType extension = (ComplexType) iter.next();
396 if (!extension.isEmptyContent()) {
397 return this;
398 }
399 }
400 if (warnings) {
401 visitor.issueWarning("The " + AxisInfo.axisName[axis] + " axis will never select any" +
402 " nodes when starting at " +
403 getStartingNodeDescription(contentType) +
404 ", as this type requires empty content", getLocation());
405 }
406 return Literal.makeEmptySequence();
407 } else if (axis == AxisInfo.ATTRIBUTE) {
408 if (targetfp == -1) {
409 if (warnings) {
410 if (!((ComplexType) contentType).allowsAttributes()) {
411 visitor.issueWarning(
412 "The complex type " + contentType.getDescription() +
413 " allows no attributes other than the standard attributes in the xsi namespace",
414 getLocation());
415 }
416 }
417 } else {
418 try {
419 SchemaType schemaType;
420 if (targetfp == StandardNames.XSI_TYPE) {
421 schemaType = BuiltInAtomicType.QNAME;
422 } else if (targetfp == StandardNames.XSI_SCHEMA_LOCATION) {
423 schemaType = BuiltInListType.ANY_URIS;
424 } else if (targetfp == StandardNames.XSI_NO_NAMESPACE_SCHEMA_LOCATION) {
425 schemaType = BuiltInAtomicType.ANY_URI;
426 } else if (targetfp == StandardNames.XSI_NIL) {
427 schemaType = BuiltInAtomicType.BOOLEAN;
428 } else {
429 schemaType = ((ComplexType) contentType).getAttributeUseType(targetName);
430 }
431 if (schemaType == null) {
432 if (warnings) {
433 visitor.issueWarning(
434 "The complex type " + contentType.getDescription() +
435 " does not allow an attribute named " + getDiagnosticName(targetName, env),
436 getLocation());
437 return Literal.makeEmptySequence();
438 }
439 } else {
440 itemType = new CombinedNodeTest(
441 test,
442 Token.INTERSECT,
443 new ContentTypeTest(Type.ATTRIBUTE, schemaType, config, false));
444 }
445 } catch (SchemaException e) {
446 // ignore the exception
447 }
448 }
449 } else if (axis == AxisInfo.CHILD && kind.equals(UType.ELEMENT)) {
450 try {
451 int childfp = targetfp;
452 if (targetName == null) {
453 // select="child::*"
454 if (((ComplexType) contentType).containsElementWildcard()) {
455 return this;
456 }
457 IntHashSet children = new IntHashSet();
458 ((ComplexType) contentType).gatherAllPermittedChildren(children, false);
459 if (children.isEmpty()) {
460 if (warnings) {
461 visitor.issueWarning(
462 "The complex type " + contentType.getDescription() +
463 " does not allow children",
464 getLocation());
465 }
466 return Literal.makeEmptySequence();
467 }
468 // if (children.contains(-1)) {
469 // return this;
470 // }
471 if (children.size() == 1) {
472 IntIterator iter = children.iterator();
473 if (iter.hasNext()) {
474 childfp = iter.next();
475 }
476 } else {
477 return this;
478 }
479 }
480 SchemaType schemaType = ((ComplexType) contentType).getElementParticleType(childfp, true);
481 if (schemaType == null) {
482 if (warnings) {
483 StructuredQName childElement = getConfiguration().getNamePool().getStructuredQName(childfp);
484 String message = "The complex type " + contentType.getDescription() +
485 " does not allow a child element named " + getDiagnosticName(childElement, env);
486 IntHashSet permitted = new IntHashSet();
487 ((ComplexType) contentType).gatherAllPermittedChildren(permitted, false);
488 if (!permitted.contains(-1)) {
489 IntIterator kids = permitted.iterator();
490 while (kids.hasNext()) {
491 int kid = kids.next();
492 StructuredQName sq = getConfiguration().getNamePool().getStructuredQName(kid);
493 if (sq.getLocalPart().equals(childElement.getLocalPart()) && kid != childfp) {
494 message += ". Perhaps the namespace is " +
495 (childElement.hasURI("") ? "missing" : "wrong") +
496 ", and " + sq.getEQName() + " was intended?";
497 break;
498 }
499 }
500 visitor.issueWarning(message, getLocation());
501 }
502 }
503 return Literal.makeEmptySequence();
504 } else {
505 itemType = new CombinedNodeTest(
506 test,
507 Token.INTERSECT,
508 new ContentTypeTest(Type.ELEMENT, schemaType, config, true));
509 computedCardinality = ((ComplexType) contentType).getElementParticleCardinality(childfp, true);
510 ExpressionTool.resetStaticProperties(this);
511 if (computedCardinality == StaticProperty.ALLOWS_ZERO) {
512 // this shouldn't happen, because we've already checked for this a different way.
513 // but it's worth being safe (there was a bug involving an incorrect inference here)
514 StructuredQName childElement = getConfiguration().getNamePool().getStructuredQName(childfp);
515 visitor.issueWarning(
516 "The complex type " + contentType.getDescription() +
517 " appears not to allow a child element named " +
518 getDiagnosticName(childElement, env),
519 getLocation());
520 return Literal.makeEmptySequence();
521 }
522 if (!Cardinality.allowsMany(computedCardinality) &&
523 !(getParentExpression() instanceof FirstItemExpression) &&
524 !visitor.isOptimizeForPatternMatching()) {
525 // if there can be at most one child of this name, create a FirstItemExpression
526 // to stop the search after the first one is found
527 return FirstItemExpression.makeFirstItemExpression(this);
528 }
529 }
530 } catch (SchemaException e) {
531 // ignore the exception
532 }
533 } else if (axis == AxisInfo.DESCENDANT && kind.equals(UType.ELEMENT) && targetfp != -1) {
534 // when searching for a specific element on the descendant axis, try to produce a more
535 // specific path that avoids searching branches of the tree where the element cannot occur
536 try {
537 IntHashSet descendants = new IntHashSet();
538 ((ComplexType) contentType).gatherAllPermittedDescendants(descendants);
539 if (descendants.contains(-1)) {
540 return this;
541 }
542 if (descendants.contains(targetfp)) {
543 IntHashSet children = new IntHashSet();
544 ((ComplexType) contentType).gatherAllPermittedChildren(children, false);
545 IntHashSet usefulChildren = new IntHashSet();
546 boolean considerSelf = false;
547 boolean considerDescendants = false;
548 IntIterator kids = children.iterator();
549 while (kids.hasNext()) {
550 int c = kids.next();
551 if (c == targetfp) {
552 usefulChildren.add(c);
553 considerSelf = true;
554 }
555 SchemaType st = ((ComplexType) contentType).getElementParticleType(c, true);
556 if (st == null) {
557 throw new AssertionError("Can't find type for child element " + c);
558 }
559 if (st instanceof ComplexType) {
560 IntHashSet subDescendants = new IntHashSet();
561 ((ComplexType) st).gatherAllPermittedDescendants(subDescendants);
562 if (subDescendants.contains(targetfp)) {
563 usefulChildren.add(c);
564 considerDescendants = true;
565 }
566 }
567 }
568 itemType = test;
569 if (considerDescendants) {
570 SchemaType st = ((ComplexType) contentType).getDescendantElementType(targetfp);
571 if (st != AnyType.getInstance()) {
572 itemType = new CombinedNodeTest(
573 test, Token.INTERSECT,
574 new ContentTypeTest(Type.ELEMENT, st, config, true));
575 }
576 //return this;
577 }
578 if (usefulChildren.size() < children.size()) {
579 NodeTest childTest = makeUnionNodeTest(usefulChildren, config.getNamePool());
580 AxisExpression first = new AxisExpression(AxisInfo.CHILD, childTest);
581 ExpressionTool.copyLocationInfo(this, first);
582 byte nextAxis;
583 if (considerSelf) {
584 nextAxis = considerDescendants ? AxisInfo.DESCENDANT_OR_SELF : AxisInfo.SELF;
585 } else {
586 nextAxis = AxisInfo.DESCENDANT;
587 }
588 AxisExpression next = new AxisExpression(nextAxis, (NodeTest) itemType);
589 ExpressionTool.copyLocationInfo(this, next);
590 Expression path = ExpressionTool.makePathExpression(first, next);
591 ExpressionTool.copyLocationInfo(this, path);
592 return path.typeCheck(visitor, contextInfo);
593 }
594 } else {
595 if (warnings) {
596 visitor.issueWarning(
597 "The complex type " + contentType.getDescription() +
598 " does not allow a descendant element named " +
599 getDiagnosticName(targetName, env),
600 getLocation());
601 }
602 }
603 } catch (SchemaException e) {
604 throw new AssertionError(e);
605 }
606
607
608 }
609 }
610
611 return this;
612 }
613
614 /*
615 * Get a string representation of a name to use in diagnostics
616 */
617
618 private static String getDiagnosticName(StructuredQName name, StaticContext env) {
619 String uri = name.getURI();
620 if (uri.equals("")) {
621 return name.getLocalPart();
622 } else {
623 NamespaceResolver resolver = env.getNamespaceResolver();
624 for (Iterator<String> it = resolver.iteratePrefixes(); it.hasNext(); ) {
625 String prefix = it.next();
626 if (uri.equals(resolver.getURIForPrefix(prefix, true))) {
627 if (prefix.isEmpty()) {
628 return "Q{" + uri + "}" + name.getLocalPart();
629 } else {
630 return prefix + ":" + name.getLocalPart();
631 }
632 }
633 }
634 }
635 return "Q{" + uri + "}" + name.getLocalPart();
636 }
637
638 private static String getStartingNodeDescription(SchemaType type) {
639 String s = type.getDescription();
640 if (s.startsWith("of element")) {
641 return "a valid element named" + s.substring("of element".length());
642 } else if (s.startsWith("of attribute")) {
643 return "a valid attribute named" + s.substring("of attribute".length());
644 } else {
645 return "a node with " + (type.isSimpleType() ? "simple" : "complex") + " type " + s;
646 }
647 }
648
649 /**
650 * Make a union node test for a set of supplied element fingerprints
651 *
652 * @param elements the set of integer element fingerprints to be tested for. Must not
653 * be empty.
654 * @param pool the name pool
655 * @return a NodeTest that returns true if the node is an element whose name is one of the names
656 * in this set
657 */
658
659 private NodeTest makeUnionNodeTest(IntHashSet elements, NamePool pool) {
660 NodeTest test = null;
661 IntIterator iter = elements.iterator();
662 while (iter.hasNext()) {
663 int fp = iter.next();
664 NodeTest nextTest = new NameTest(Type.ELEMENT, fp, pool);
665 if (test == null) {
666 test = nextTest;
667 } else {
668 test = new CombinedNodeTest(test, Token.UNION, nextTest);
669 }
670 }
671 return test;
672 }
673
674 /**
675 * Get the static type of the context item for this AxisExpression. May be null if not known.
676 *
677 * @return the statically-inferred type, or null if not known
678 */
679
680 public ItemType getContextItemType() {
681 return staticInfo.getItemType();
682 }
683
684
685 /**
686 * Perform optimisation of an expression and its subexpressions.
687 * <p>This method is called after all references to functions and variables have been resolved
688 * to the declaration of the function or variable, and after all type checking has been done.</p>
689 *
690 * @param visitor an expression visitor
691 * @param contextInfo the static type of "." at the point where this expression is invoked.
692 * The parameter is set to null if it is known statically that the context item will be undefined.
693 * If the type of the context item is not known statically, the argument is set to
694 * {@link net.sf.saxon.type.Type#ITEM_TYPE}
695 * @return the original expression, rewritten if appropriate to optimize execution
696 */
697
698 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) {
699 doneOptimize = true; // This ensures no more warnings about empty axes, because (a) we've probably output the
700 // warning already, and (b) we're now looking at a different expression from what the user
701 // wrote. In particular, prevent spurious warnings after function inlining.
702 staticInfo = contextInfo;
703 return this;
704 }
705
706 /**
707 * Return the estimated cost of evaluating an expression. This is a very crude measure based
708 * on the syntactic form of the expression (we have no knowledge of data values). We take
709 * the cost of evaluating a simple scalar comparison or arithmetic expression as 1 (one),
710 * and we assume that a sequence has length 5. The resulting estimates may be used, for
711 * example, to reorder the predicates in a filter expression so cheaper predicates are
712 * evaluated first.
713 */
714 @Override
715 public int getCost() {
716 switch (axis) {
717 case AxisInfo.SELF:
718 case AxisInfo.PARENT:
719 case AxisInfo.ATTRIBUTE:
720 return 1;
721 case AxisInfo.CHILD:
722 case AxisInfo.FOLLOWING_SIBLING:
723 case AxisInfo.PRECEDING_SIBLING:
724 case AxisInfo.ANCESTOR:
725 case AxisInfo.ANCESTOR_OR_SELF:
726 return 5;
727 default:
728 return 20;
729 }
730 }
731
732 /**
733 * Is this expression the same as another expression?
734 */
735
736 public boolean equals(Object other) {
737 return other instanceof AxisExpression &&
738 axis == ((AxisExpression) other).axis &&
739 Objects.equals(test, ((AxisExpression) other).test);
740 }
741
742 /**
743 * get HashCode for comparing two expressions
744 */
745
746 public int computeHashCode() {
747 // generate an arbitrary hash code that depends on the axis and the node test
748 int h = 9375162 + axis << 20;
749 if (test != null) {
750 h ^= test.getPrimitiveType() << 16;
751 h ^= test.getFingerprint();
752 }
753 return h;
754 }
755
756 /**
757 * Copy an expression. This makes a deep copy.
758 *
759 * @param rebindings a mutable list of (old binding, new binding) pairs
760 * that is used to update the bindings held in any
761 * local variable references that are copied.
762 * @return the copy of the original expression
763 */
764
765 /*@NotNull*/
766 public Expression copy(RebindingMap rebindings) {
767 AxisExpression a2 = new AxisExpression(axis, test);
768 a2.itemType = itemType;
769 a2.staticInfo = staticInfo;
770 a2.computedCardinality = computedCardinality;
771 a2.doneTypeCheck = doneTypeCheck;
772 a2.doneOptimize = doneOptimize;
773 ExpressionTool.copyLocationInfo(this, a2);
774 return a2;
775 }
776
777 /**
778 * Get the static properties of this expression (other than its type). The result is
779 * bit-signficant. These properties are used for optimizations. In general, if
780 * property bit is set, it is true, but if it is unset, the value is unknown.
781 */
782
783 public int computeSpecialProperties() {
784 return StaticProperty.CONTEXT_DOCUMENT_NODESET |
785 StaticProperty.SINGLE_DOCUMENT_NODESET |
786 StaticProperty.NO_NODES_NEWLY_CREATED |
787 (AxisInfo.isForwards[axis] ? StaticProperty.ORDERED_NODESET : StaticProperty.REVERSE_DOCUMENT_ORDER) |
788 (AxisInfo.isPeerAxis[axis] || isPeerNodeTest(test) ? StaticProperty.PEER_NODESET : 0) |
789 (AxisInfo.isSubtreeAxis[axis] ? StaticProperty.SUBTREE_NODESET : 0) |
790 (axis == AxisInfo.ATTRIBUTE || axis == AxisInfo.NAMESPACE ? StaticProperty.ATTRIBUTE_NS_NODESET : 0);
791 }
792
793 /**
794 * Determine whether a node test is a peer node test. A peer node test is one that, if it
795 * matches a node, cannot match any of its descendants. For example, text() is a peer node-test.
796 *
797 * @param test the node test
798 * @return true if nodes selected by this node-test will never contain each other as descendants
799 */
800
801 private static boolean isPeerNodeTest(NodeTest test) {
802 if (test == null) {
803 return false;
804 }
805 UType uType = test.getUType();
806 if (uType.overlaps(UType.ELEMENT)) {
807 // can match elements; for the moment, assume these can contain each other
808 return false;
809 } else if (uType.overlaps(UType.DOCUMENT)) {
810 // can match documents; return false if we can also match non-documents
811 return uType.equals(UType.DOCUMENT);
812 } else {
813 return true;
814 }
815 }
816
817 /**
818 * Determine the data type of the items returned by this expression
819 *
820 * @return Type.NODE or a subtype, based on the NodeTest in the axis step, plus
821 * information about the content type if this is known from schema analysis
822 */
823
824 /*@NotNull*/
825 public final ItemType getItemType() {
826 if (itemType != null) {
827 return itemType;
828 }
829 int p = AxisInfo.principalNodeType[axis];
830 switch (p) {
831 case Type.ATTRIBUTE:
832 case Type.NAMESPACE:
833 return NodeKindTest.makeNodeKindTest(p);
834 default:
835 if (test == null) {
836 return AnyNodeTest.getInstance();
837 } else {
838 return test;
839 }
840 }
841 }
842
843
844 /**
845 * Get the static type of the expression as a UType, following precisely the type
846 * inference rules defined in the XSLT 3.0 specification.
847 *
848 * @param contextItemType the static type of the context item for the expression evaluation
849 * @return the static item type of the expression according to the XSLT 3.0 defined rules
850 */
851 @Override
852 public UType getStaticUType(UType contextItemType) {
853 // See W3C bug 30032
854 UType reachable = AxisInfo.getTargetUType(contextItemType, axis);
855 if (test == null) {
856 return reachable;
857 } else {
858 return reachable.intersection(test.getUType());
859 }
860 }
861
862
863 /**
864 * Determine the intrinsic dependencies of an expression, that is, those which are not derived
865 * from the dependencies of its subexpressions. For example, position() has an intrinsic dependency
866 * on the context position, while (position()+1) does not. The default implementation
867 * of the method returns 0, indicating "no dependencies".
868 *
869 * @return a set of bit-significant flags identifying the "intrinsic"
870 * dependencies. The flags are documented in class net.sf.saxon.value.StaticProperty
871 */
872 @Override
873 public int getIntrinsicDependencies() {
874 return StaticProperty.DEPENDS_ON_CONTEXT_ITEM;
875 }
876
877 /**
878 * Determine the cardinality of the result of this expression
879 */
880
881 public final int computeCardinality() {
882 if (computedCardinality != -1) {
883 // This takes care of the case where cardinality was computed during type checking of the child axis
884 return computedCardinality;
885 }
886 NodeTest originNodeType;
887 NodeTest nodeTest = test;
888 ItemType contextItemType = staticInfo.getItemType();
889 if (contextItemType instanceof NodeTest) {
890 originNodeType = (NodeTest) contextItemType;
891 } else if (contextItemType instanceof AnyItemType) {
892 originNodeType = AnyNodeTest.getInstance();
893 } else {
894 // context item not a node - we'll report a type error somewhere along the line
895 return StaticProperty.ALLOWS_ZERO_OR_MORE;
896 }
897 if (axis == AxisInfo.ATTRIBUTE && nodeTest instanceof NameTest) {
898 SchemaType contentType = originNodeType.getContentType();
899 if (contentType instanceof ComplexType) {
900 try {
901 return ((ComplexType) contentType).getAttributeUseCardinality(nodeTest.getMatchingNodeName());
902 } catch (SchemaException err) {
903 // shouldn't happen; play safe
904 return StaticProperty.ALLOWS_ZERO_OR_ONE;
905 }
906 } else if (contentType instanceof SimpleType) {
907 return StaticProperty.EMPTY;
908 }
909 return StaticProperty.ALLOWS_ZERO_OR_ONE;
910 } else if (axis == AxisInfo.DESCENDANT && nodeTest instanceof NameTest && nodeTest.getPrimitiveType() == Type.ELEMENT) {
911 SchemaType contentType = originNodeType.getContentType();
912 if (contentType instanceof ComplexType) {
913 try {
914 return ((ComplexType) contentType).getDescendantElementCardinality(nodeTest.getFingerprint());
915 } catch (SchemaException err) {
916 // shouldn't happen; play safe
917 return StaticProperty.ALLOWS_ZERO_OR_MORE;
918 }
919 } else {
920 return StaticProperty.EMPTY;
921 }
922
923 } else if (axis == AxisInfo.SELF) {
924 return StaticProperty.ALLOWS_ZERO_OR_ONE;
925 } else {
926 return StaticProperty.ALLOWS_ZERO_OR_MORE;
927 }
928 // the parent axis isn't handled by this class
929 }
930
931 /**
932 * Determine whether the expression can be evaluated without reference to the part of the context
933 * document outside the subtree rooted at the context node.
934 *
935 * @return true if the expression has no dependencies on the context node, or if the only dependencies
936 * on the context node are downward selections using the self, child, descendant, attribute, and namespace
937 * axes.
938 */
939
940 public boolean isSubtreeExpression() {
941 return AxisInfo.isSubtreeAxis[axis];
942 }
943
944 /**
945 * Get the axis
946 *
947 * @return the axis number, for example {@link net.sf.saxon.om.AxisInfo#CHILD}
948 */
949
950 public byte getAxis() {
951 return axis;
952 }
953
954 /**
955 * Get the NodeTest. Returns null if the AxisExpression can return any node.
956 *
957 * @return the node test, or null if all nodes are returned
958 */
959
960 public NodeTest getNodeTest() {
961 return test;
962 }
963
964
965 /**
966 * Add a representation of this expression to a PathMap. The PathMap captures a map of the nodes visited
967 * by an expression in a source tree.
968 *
969 * @param pathMap the PathMap to which the expression should be added
970 * @param pathMapNodeSet the PathMapNodeSet to which the paths embodied in this expression should be added
971 * @return the pathMapNode representing the focus established by this expression, in the case where this
972 * expression is the first operand of a path expression or filter expression
973 */
974
975 public PathMap.PathMapNodeSet addToPathMap(PathMap pathMap, PathMap.PathMapNodeSet pathMapNodeSet) {
976 if (pathMapNodeSet == null) {
977 ContextItemExpression cie = new ContextItemExpression();
978 //cie.setContainer(getContainer());
979 pathMapNodeSet = new PathMap.PathMapNodeSet(pathMap.makeNewRoot(cie));
980 }
981 return pathMapNodeSet.createArc(axis, test == null ? AnyNodeTest.getInstance() : test);
982 }
983
984 /**
985 * Ask whether there is a possibility that the context item will be undefined
986 *
987 * @return true if this is a possibility
988 */
989
990 public boolean isContextPossiblyUndefined() {
991 return staticInfo.isPossiblyAbsent();
992 }
993
994 public ContextItemStaticInfo getContextItemStaticInfo() {
995 return staticInfo;
996 }
997
998 /**
999 * Convert this expression to an equivalent XSLT pattern
1000 *
1001 * @param config the Saxon configuration
1002 * @return the equivalent pattern
1003 * @throws net.sf.saxon.trans.XPathException if conversion is not possible
1004 */
1005 @Override
1006 public Pattern toPattern(Configuration config) throws XPathException {
1007
1008 NodeTest test = getNodeTest();
1009 Pattern pat;
1010
1011 if (test == null) {
1012 test = AnyNodeTest.getInstance();
1013 }
1014 if (test instanceof AnyNodeTest && (axis == AxisInfo.CHILD || axis == AxisInfo.DESCENDANT || axis == AxisInfo.SELF)) {
1015 test = AnyChildNodeTest.getInstance();
1016 }
1017 int kind = test.getPrimitiveType();
1018 if (axis == AxisInfo.SELF) {
1019 pat = new NodeTestPattern(test);
1020 } else if (axis == AxisInfo.ATTRIBUTE) {
1021 if (kind == Type.NODE) {
1022 // attribute::node() matches any attribute, and only an attribute
1023 pat = new NodeTestPattern(NodeKindTest.ATTRIBUTE);
1024 } else if (!AxisInfo.containsNodeKind(axis, kind)) {
1025 // for example, attribute::comment()
1026 pat = new NodeTestPattern(ErrorType.getInstance());
1027 } else {
1028 pat = new NodeTestPattern(test);
1029 }
1030 } else if (axis == AxisInfo.CHILD || axis == AxisInfo.DESCENDANT || axis == AxisInfo.DESCENDANT_OR_SELF) {
1031 if (kind != Type.NODE && !AxisInfo.containsNodeKind(axis, kind)) {
1032 pat = new NodeTestPattern(ErrorType.getInstance());
1033 } else {
1034 pat = new NodeTestPattern(test);
1035 }
1036 } else if (axis == AxisInfo.NAMESPACE) {
1037 if (kind == Type.NODE) {
1038 // namespace::node() matches any attribute, and only an attribute
1039 pat = new NodeTestPattern(NodeKindTest.NAMESPACE);
1040 } else if (!AxisInfo.containsNodeKind(axis, kind)) {
1041 // for example, namespace::comment()
1042 pat = new NodeTestPattern(ErrorType.getInstance());
1043 } else {
1044 pat = new NodeTestPattern(test);
1045 }
1046 } else {
1047 throw new XPathException("Only downwards axes are allowed in a pattern", "XTSE0340");
1048 }
1049 ExpressionTool.copyLocationInfo(this, pat);
1050 return pat;
1051 }
1052
1053 @Override
1054 public int getImplementationMethod() {
1055 return ITERATE_METHOD;
1056 }
1057
1058 /**
1059 * Evaluate the path-expression in a given context to return a NodeSet
1060 *
1061 * @param context the evaluation context
1062 */
1063
1064 /*@NotNull*/
1065 public SequenceIterator<?> iterate(XPathContext context) throws XPathException {
1066 Item item = context.getContextItem();
1067 if (item == null) {
1068 // Might as well do the test anyway, whether or not contextMaybeUndefined is set
1069 XPathException err = new XPathException("The context item for axis step " +
1070 this + " is absent");
1071 err.setErrorCode("XPDY0002");
1072 err.setXPathContext(context);
1073 err.setLocation(getLocation());
1074 err.setIsTypeError(true);
1075 throw err;
1076 }
1077 try {
1078 if (test == null) {
1079 return ((NodeInfo) item).iterateAxis(axis);
1080 } else {
1081 return ((NodeInfo) item).iterateAxis(axis, test);
1082 }
1083 } catch (ClassCastException cce) {
1084 XPathException err = new XPathException("The context item for axis step " +
1085 this + " is not a node");
1086 err.setErrorCode("XPTY0020");
1087 err.setXPathContext(context);
1088 err.setLocation(getLocation());
1089 err.setIsTypeError(true);
1090 throw err;
1091 } catch (UnsupportedOperationException err) {
1092 if (err.getCause() instanceof XPathException) {
1093 XPathException ec = (XPathException) err.getCause();
1094 ec.maybeSetLocation(getLocation());
1095 ec.maybeSetContext(context);
1096 throw ec;
1097 } else {
1098 // the namespace axis is not supported for all tree implementations
1099 dynamicError(err.getMessage(), "XPST0010", context);
1100 return null;
1101 }
1102 }
1103 }
1104
1105 /**
1106 * Iterate the axis from a given starting node, without regard to context
1107 *
1108 * @param origin the starting node
1109 * @return the iterator over the axis
1110 */
1111
1112 public AxisIterator iterate(NodeInfo origin) {
1113 if (test == null) {
1114 return origin.iterateAxis(axis);
1115 } else {
1116 return origin.iterateAxis(axis, test);
1117 }
1118 }
1119
1120 /**
1121 * Diagnostic print of expression structure. The abstract expression tree
1122 * is written to the supplied output destination.
1123 */
1124
1125 public void export(ExpressionPresenter destination) throws XPathException {
1126 destination.startElement("axis", this);
1127 destination.emitAttribute("name", AxisInfo.axisName[axis]);
1128 destination.emitAttribute("nodeTest", test == null ? "node()" : test.toString());
1129 if ("JS".equals(((ExpressionPresenter.ExportOptions) destination.getOptions()).target)) {
1130 NodeTest known = AnyNodeTest.getInstance();
1131 if (axis == AxisInfo.ATTRIBUTE) {
1132 known = NodeKindTest.makeNodeKindTest(Type.ATTRIBUTE);
1133 } else if (axis == AxisInfo.NAMESPACE) {
1134 known = NodeKindTest.makeNodeKindTest(Type.NAMESPACE);
1135 }
1136 int targetVersion = ((ExpressionPresenter.ExportOptions) destination.getOptions()).targetVersion;
1137 try {
1138 destination.emitAttribute("jsTest", test == null ? "return true;" : test.generateJavaScriptItemTypeTest(known, targetVersion));
1139 } catch (XPathException e) {
1140 e.maybeSetLocation(getLocation());
1141 throw e;
1142 }
1143 }
1144 destination.endElement();
1145 }
1146
1147 /**
1148 * Represent the expression as a string. The resulting string will be a valid XPath 3.0 expression
1149 * with no dependencies on namespace bindings other than the binding of the prefix "xs" to the XML Schema
1150 * namespace.
1151 *
1152 * @return the expression as a string in XPath 3.0 syntax
1153 */
1154
1155 public String toString() {
1156 FastStringBuffer fsb = new FastStringBuffer(FastStringBuffer.C16);
1157 fsb.append(AxisInfo.axisName[axis]);
1158 fsb.append("::");
1159 fsb.append(test == null ? "node()" : test.toString());
1160 return fsb.toString();
1161 }
1162
1163 @Override
1164 public String toShortString() {
1165 FastStringBuffer fsb = new FastStringBuffer(FastStringBuffer.C16);
1166 if (axis == AxisInfo.CHILD) {
1167 // no action
1168 } else if (axis == AxisInfo.ATTRIBUTE) {
1169 fsb.append("@");
1170 } else {
1171 fsb.append(AxisInfo.axisName[axis]);
1172 fsb.append("::");
1173 }
1174 if (test == null) {
1175 fsb.append("node()");
1176 } else if (test instanceof NameTest) {
1177 if (((NameTest) test).getNodeKind() != AxisInfo.principalNodeType[axis]) {
1178 fsb.append(test.toString());
1179 } else {
1180 fsb.append(test.getMatchingNodeName().getDisplayName());
1181 }
1182 } else {
1183 fsb.append(test.toString());
1184 }
1185 return fsb.toString();
1186 }
1187
1188 @Override
1189 public String getStreamerName() {
1190 return "AxisExpression";
1191 }
1192
1193 /**
1194 * Find any necessary preconditions for the satisfaction of this expression
1195 * as a set of boolean expressions to be evaluated on the context node
1196 *
1197 * @return A set of conditions, or null if none have been computed
1198 */
1199 public Set<Expression> getPreconditions() {
1200 HashSet<Expression> pre = new HashSet<>(1);
1201 /*Expression args[] = new Expression[1];
1202 args[0] = this.copy();
1203 pre.add(SystemFunctionCall.makeSystemFunction(
1204 "exists", args));*/
1205 Expression a = this.copy(new RebindingMap());
1206 a.setRetainedStaticContext(getRetainedStaticContext());
1207 pre.add(a);
1208 return pre;
1209 }
1210 }
1211