Debian Codegraph @

net/sf/saxon/pattern/GeneralPositionalPattern.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.pattern;
9
10 import com.saxonica.ee.stream.Streamability;
11 import com.saxonica.ee.stream.Sweep;
12 import com.saxonica.ee.trans.ContextItemStaticInfoEE;
13 import net.sf.saxon.Configuration;
14 import net.sf.saxon.expr.*;
15 import net.sf.saxon.expr.instruct.SlotManager;
16 import net.sf.saxon.expr.parser.ContextItemStaticInfo;
17 import net.sf.saxon.expr.parser.ExpressionTool;
18 import net.sf.saxon.expr.parser.ExpressionVisitor;
19 import net.sf.saxon.expr.parser.RebindingMap;
20 import net.sf.saxon.om.*;
21 import net.sf.saxon.trace.ExpressionPresenter;
22 import net.sf.saxon.trans.XPathException;
23 import net.sf.saxon.tree.iter.ManualIterator;
24 import net.sf.saxon.tree.util.Navigator;
25 import net.sf.saxon.type.AnyItemType;
26 import net.sf.saxon.type.ErrorType;
27 import net.sf.saxon.type.ItemType;
28 import net.sf.saxon.type.Type;
29 import net.sf.saxon.type.UType;
30 import net.sf.saxon.value.NumericValue;
31
32 /**
33 * A GeneralPositionalPattern is a pattern of the form A[P] where A is an axis expression using the child axis
34 * and P is an expression that depends on the position.
35 * <p>This class handles cases where the predicate P is arbitrarily complex. Simple comparisons of position() against
36 * an integer value are handled by the class SimplePositionalPattern.</p>
37 */
38 public class GeneralPositionalPattern extends Pattern {
39
40 private NodeTest nodeTest;
41 private Expression positionExpr;
42 private boolean usesPosition = true;
43
44 /**
45 * Create a GeneralPositionalPattern
46 *
47 * @param base the base expression (to be matched independently of position)
48 * @param positionExpr the positional filter which matches only if the position of the node is correct
49 */
50
51 public GeneralPositionalPattern(NodeTest base, Expression positionExpr) {
52 this.nodeTest = base;
53 this.positionExpr = positionExpr;
54 }
55
56 /**
57 * Get the immediate sub-expressions of this expression, with information about the relationship
58 * of each expression to its parent expression. Default implementation
59 * works off the results of iterateSubExpressions()
60 * <p>If the expression is a Callable, then it is required that the order of the operands
61 * returned by this function is the same as the order of arguments supplied to the corresponding
62 * call() method.</p>
63 *
64 * @return an iterator containing the sub-expressions of this expression
65 */
66 @Override
67 public Iterable<Operand> operands() {
68 return new Operand(this, positionExpr, OperandRole.FOCUS_CONTROLLED_ACTION);
69 }
70
71 /**
72 * Get the filter assocated with the pattern
73 *
74 * @return the filter predicate
75 */
76
77 public Expression getPositionExpr() {
78 return positionExpr;
79 }
80
81 /**
82 * Get the base pattern
83 *
84 * @return the base pattern before filtering
85 */
86
87 public NodeTest getNodeTest() {
88 return nodeTest;
89 }
90
91 public void setUsesPosition(boolean usesPosition) {
92 this.usesPosition = usesPosition;
93 }
94
95 /**
96 * Simplify the pattern: perform any context-independent optimisations
97 *
98 */
99
100 public Pattern simplify() throws XPathException {
101 positionExpr = positionExpr.simplify();
102 return this;
103 }
104
105 /**
106 * Type-check the pattern, performing any type-dependent optimizations.
107 *
108 * @param visitor an expression visitor
109 * @param contextItemType the type of the context item at the point where the pattern appears
110 * @return the optimised Pattern
111 */
112
113 public Pattern typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType) throws XPathException {
114
115 // analyze each component of the pattern
116 ContextItemStaticInfo cit = visitor.getConfiguration().makeContextItemStaticInfo(getItemType(), false);
117
118 positionExpr = positionExpr.typeCheck(visitor, cit);
119 positionExpr = ExpressionTool.unsortedIfHomogeneous(positionExpr, false);
120
121
122 return this;
123
124 }
125
126 /**
127 * Perform optimisation of an expression and its subexpressions. This is the third and final
128 * phase of static optimization.
129 * <p>This method is called after all references to functions and variables have been resolved
130 * to the declaration of the function or variable, and after all type checking has been done.</p>
131 *
132 * @param visitor an expression visitor
133 * @param contextInfo the static type of "." at the point where this expression is invoked.
134 * The parameter is set to null if it is known statically that the context item will be undefined.
135 * If the type of the context item is not known statically, the argument is set to
136 * {@link Type#ITEM_TYPE}
137 * @return the original expression, rewritten if appropriate to optimize execution
138 * @throws XPathException if an error is discovered during this phase
139 * (typically a type error)
140 */
141 @Override
142 public Pattern optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
143 Configuration config = visitor.getConfiguration();
144 ContextItemStaticInfo cit = config.makeContextItemStaticInfo(getItemType(), false);
145 positionExpr = positionExpr.optimize(visitor, cit);
146
147 if (Literal.isConstantBoolean(positionExpr, true)) {
148 return new NodeTestPattern(nodeTest);
149 } else if (Literal.isConstantBoolean(positionExpr, false)) {
150 // if a filter is constant false, the pattern doesn't match anything
151 return new NodeTestPattern(ErrorType.getInstance());
152 }
153
154 if ((positionExpr.getDependencies() & StaticProperty.DEPENDS_ON_POSITION) == 0) {
155 usesPosition = false;
156 }
157
158 // See if the expression is now known to be non-positional (see bugs 1908, 1992, test mode-0011)
159 if (!FilterExpression.isPositionalFilter(positionExpr, config.getTypeHierarchy())) {
160 byte axis = AxisInfo.CHILD;
161 if (nodeTest.getPrimitiveType() == Type.ATTRIBUTE) {
162 axis = AxisInfo.ATTRIBUTE;
163 } else if (nodeTest.getPrimitiveType() == Type.NAMESPACE) {
164 axis = AxisInfo.NAMESPACE;
165 }
166 AxisExpression ae = new AxisExpression(axis, nodeTest);
167 FilterExpression fe = new FilterExpression(ae, positionExpr);
168 return PatternMaker.fromExpression(fe, config, true)
169 .typeCheck(visitor, contextInfo);
170 }
171 return this;
172 }
173
174 /**
175 * Get the dependencies of the pattern. The only interesting dependencies for a pattern are
176 * dependencies on local variables or on user-defined functions. These are analyzed in those
177 * patterns containing predicates.
178 *
179 * @return the dependencies, as a bit-significant mask
180 */
181
182 public int getDependencies() {
183 // the only dependency that's interesting is a dependency on local variables
184 return positionExpr.getDependencies() &
185 (StaticProperty.DEPENDS_ON_LOCAL_VARIABLES | StaticProperty.DEPENDS_ON_USER_FUNCTIONS);
186 }
187
188 /**
189 * Allocate slots to any variables used within the pattern
190 *
191 * @param slotManager manages allocation of slots in a stack frame
192 * @param nextFree the next slot that is free to be allocated @return the next slot that is free to be allocated
193 */
194
195 public int allocateSlots(SlotManager slotManager, int nextFree) {
196 return ExpressionTool.allocateSlots(positionExpr, nextFree, slotManager);
197 }
198
199 /**
200 * Determine whether the pattern matches a given item.
201 *
202 * @param item the item to be tested
203 * @return true if the pattern matches, else false
204 */
205
206 public boolean matches(Item<?> item, XPathContext context) throws XPathException {
207 return item instanceof NodeInfo && matchesBeneathAnchor((NodeInfo) item, null, context);
208 }
209
210 /**
211 * Determine whether this pattern matches a given Node within the subtree rooted at a given
212 * anchor node. This method is used when the pattern is used for streaming.
213 *
214 * @param node The NodeInfo representing the Element or other node to be tested against the Pattern
215 * @param anchor The anchor node, which must match any AnchorPattern subpattern
216 * @param context The dynamic context. Only relevant if the pattern
217 * uses variables, or contains calls on functions such as document() or key().
218 * @return true if the node matches the Pattern, false otherwise
219 */
220
221 public boolean matchesBeneathAnchor(NodeInfo node, NodeInfo anchor, XPathContext context) throws XPathException {
222 return internalMatches(node, anchor, context);
223 }
224
225 /**
226 * Test whether the pattern matches, but without changing the current() node
227 */
228
229 private boolean internalMatches(NodeInfo node, NodeInfo anchor, XPathContext context) throws XPathException {
230 if (!nodeTest.matchesNode(node)) {
231 return false;
232 }
233
234 XPathContext c2 = context.newMinorContext();
235 ManualIterator<NodeInfo> iter = new ManualIterator<>(node);
236 c2.setCurrentIterator(iter);
237
238 try {
239 XPathContext c = c2;
240 int actualPosition = -1;
241 if (usesPosition) {
242 actualPosition = getActualPosition(node, Integer.MAX_VALUE, context.getCurrentIterator());
243 ManualIterator<NodeInfo> man = new ManualIterator<>(node, actualPosition);
244 XPathContext c3 = c2.newMinorContext();
245 c3.setCurrentIterator(man);
246 c = c3;
247 }
248 Item predicate = positionExpr.evaluateItem(c);
249 if (predicate instanceof NumericValue) {
250 NumericValue position = (NumericValue) positionExpr.evaluateItem(context);
251 int requiredPos = position.asSubscript();
252 if (actualPosition < 0 && requiredPos != -1) {
253 actualPosition = getActualPosition(node, requiredPos, context.getCurrentIterator());
254 }
255 return requiredPos != -1 && actualPosition == requiredPos;
256 } else {
257 return ExpressionTool.effectiveBooleanValue(predicate);
258 }
259
260 } catch (XPathException.Circularity e) {
261 throw e;
262 } catch (XPathException e) {
263 handleDynamicError(e, c2);
264 return false;
265 }
266 }
267
268 private int getActualPosition(NodeInfo node, int max, FocusIterator iterator) {
269 if (iterator instanceof FocusTrackingIterator) {
270 // This path makes use of cached information
271 return ((FocusTrackingIterator)iterator).getSiblingPosition(node, nodeTest, max);
272 }
273 return Navigator.getSiblingPosition(node, nodeTest, max);
274 }
275
276
277 /**
278 * Get a UType indicating which kinds of items this Pattern can match.
279 *
280 * @return a UType indicating all the primitive types of item that the pattern can match.
281 */
282 @Override
283 public UType getUType() {
284 return nodeTest.getUType();
285 }
286
287 /**
288 * Determine the fingerprint of nodes to which this pattern applies.
289 * Used for optimisation.
290 *
291 * @return the fingerprint of nodes matched by this pattern.
292 */
293
294 public int getFingerprint() {
295 return nodeTest.getFingerprint();
296 }
297
298 /**
299 * Get an ItemType that all the nodes matching this pattern must satisfy
300 */
301
302 public ItemType getItemType() {
303 return nodeTest;
304 }
305
306 /**
307 * Determine whether this pattern is the same as another pattern
308 *
309 * @param other the other object
310 */
311
312 public boolean equals(Object other) {
313 if (other instanceof GeneralPositionalPattern) {
314 GeneralPositionalPattern fp = (GeneralPositionalPattern) other;
315 return nodeTest.equals(fp.nodeTest) && positionExpr.isEqual(fp.positionExpr);
316 } else {
317 return false;
318 }
319 }
320
321 /**
322 * hashcode supporting equals()
323 */
324
325 public int computeHashCode() {
326 return nodeTest.hashCode() ^ positionExpr.hashCode();
327 }
328
329 //#ifdefined STREAM
330
331 /**
332 * Test whether a pattern is motionless, that is, whether it can be evaluated against a node
333 * without repositioning the input stream. This is a necessary condition for patterns used
334 * as the match pattern of a streamed template rule.
335 *
336 * @return true if the pattern is motionless, that is, if it can be evaluated against a streamed
337 * node without changing the position in the streamed input file
338 */
339
340 public boolean isMotionless() {
341 ContextItemStaticInfoEE csi = (ContextItemStaticInfoEE)getConfiguration().makeContextItemStaticInfo(getItemType(), false);
342 csi.setContextPostureStriding();
343 Streamability.getStreamability(positionExpr, csi, null);
344 return Streamability.getSweep(positionExpr) == Sweep.MOTIONLESS;
345 }
346 //#endif
347
348 /**
349 * Copy a pattern. This makes a deep copy.
350 *
351 * @return the copy of the original pattern
352 * @param rebindings variables that need to be re-bound
353 */
354
355 /*@NotNull*/
356 public Pattern copy(RebindingMap rebindings) {
357 GeneralPositionalPattern n = new GeneralPositionalPattern(nodeTest.copy(), positionExpr.copy(rebindings));
358 ExpressionTool.copyLocationInfo(this, n);
359 return n;
360 }
361
362 /**
363 * Get a string representation of the pattern. This will be in a form similar to the
364 * original pattern text, but not necessarily identical. It is not guaranteed to be
365 * in legal pattern syntax.
366 */
367 @Override
368 public String toString() {
369 return nodeTest + "[" + positionExpr + "]";
370 }
371
372 public void export(ExpressionPresenter presenter) throws XPathException {
373 presenter.startElement("p.genPos");
374 presenter.emitAttribute("type", nodeTest.toString());
375 if (!usesPosition) {
376 // flag is this way around for backwards compatibility with 9.8
377 presenter.emitAttribute("flags", "P");
378 }
379 if ("JS".equals(((ExpressionPresenter.ExportOptions) presenter.getOptions()).target)) {
380 try {
381 int targetVersion = ((ExpressionPresenter.ExportOptions) presenter.getOptions()).targetVersion;
382 presenter.emitAttribute("jsTest", nodeTest.generateJavaScriptItemTypeTest(AnyItemType.getInstance(), targetVersion));
383 } catch (XPathException e) {
384 e.maybeSetLocation(getLocation());
385 throw e;
386 }
387 }
388 positionExpr.export(presenter);
389 presenter.endElement();
390 }
391
392 /*
393 * Optimization
394 * Note that any replacement by a BooleanExpressionPattern based on the positionExpr
395 * REQUIRES that the position has been set appropriately in the context for its evaluation.
396 * This is NOT the case in generalized {@link net.sf.saxon.trans.Mode.getRule()},
397 * but is under {@link com.saxonica.ee.optim.ModeEE.getRule()}
398 * This should be checked.
399 *//*
400 public Pattern optimizeForName(int i) {
401 Object o = nodeTest.optimizeForName(i);
402 if (o == null) {
403 return null;
404 } else {
405 return optimizePosition();
406 }
407 }
408
409 public Pattern optimizeForType(int i) {
410 Object o = nodeTest.optimizeForType(i);
411 if (o == null) {
412 return null;
413 } else {
414 return optimizePosition();
415 }
416 }
417
418 private Pattern optimizePosition() {
419 Expression pe = makePosition(positionExpr, nodeTest);
420 BooleanExpressionPattern p = new BooleanExpressionPattern(pe);
421 ExpressionTool.copyLocationInfo(this, p);
422 //p.setPackageData(getPackageData());
423 return p;
424 }
425
426 public Pattern applyAxis(byte axis) {
427 Expression pe = makePosition(positionExpr, nodeTest);
428 FilterExpression filter = new FilterExpression(new AxisExpression(axis, nodeTest), pe);
429 BooleanExpressionPattern p = new BooleanExpressionPattern(filter);
430 ExpressionTool.copyLocationInfo(this, p);
431 //p.setPackageData(getPackageData());
432 return p;
433 }
434
435 public static Expression makePosition(Expression expr, NodeTest nodeTest) {
436 Expression n = expr;
437 RetainedStaticContext rsc = expr.getRetainedStaticContext();
438 if (expr instanceof Literal) {
439 GroundedValue value = ((Literal) expr).getValue();
440 try {
441 if (value instanceof IntegerValue) {
442 Expression operands[] = new Expression[1];
443 operands[0] = new AxisExpression(AxisInfo.PRECEDING_SIBLING, nodeTest);
444 Expression position = SystemFunction.makeCall("count", rsc, operands);
445 n = new CompareToIntegerConstant(position, Token.FEQ,
446 ((IntegerValue)value).longValue() - 1);
447 return n;
448 }
449
450 Expression position = SystemFunction.makeCall("position", rsc);
451 n = new CompareToIntegerConstant(position, Token.FEQ,
452 ((IntegerValue) ((Literal) expr).getValue()).longValue());
453 } catch (XPathException e) {
454 e.printStackTrace();
455 }
456 } else if (expr instanceof CompareToIntegerConstant) {
457 CompareToIntegerConstant c = (CompareToIntegerConstant)expr;
458 Operand op1 = expr.operands().iterator().next();
459 Expression e1 = op1.getChildExpression();
460 if (e1.isCallOn(PositionAndLast.class)) {
461 Expression position = SystemFunction.makeCall("count",
462 rsc, new AxisExpression(AxisInfo.PRECEDING_SIBLING, nodeTest));
463 n = new CompareToIntegerConstant(position, c.getComparisonOperator(),
464 c.getComparand() - 1);
465 return n;
466 }
467 }
468 return n;
469 }*/
470
471 }
472 // Copyright (c) 2012 Saxonica Limited