Debian Codegraph @

net/sf/saxon/pattern/GeneralNodePattern.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 net.sf.saxon.Configuration;
11 import net.sf.saxon.expr.*;
12 import net.sf.saxon.expr.instruct.SlotManager;
13 import net.sf.saxon.expr.parser.*;
14 import net.sf.saxon.functions.Current;
15 import net.sf.saxon.om.AxisInfo;
16 import net.sf.saxon.om.Item;
17 import net.sf.saxon.om.NodeInfo;
18 import net.sf.saxon.om.SequenceIterator;
19 import net.sf.saxon.trace.ExpressionPresenter;
20 import net.sf.saxon.trans.XPathException;
21 import net.sf.saxon.tree.iter.AxisIterator;
22 import net.sf.saxon.tree.iter.ManualIterator;
23 import net.sf.saxon.type.ItemType;
24 import net.sf.saxon.type.Type;
25 import net.sf.saxon.type.TypeHierarchy;
26 import net.sf.saxon.type.UType;
27
28 /**
29 * A GeneralNodePattern represents a pattern which, because of the presence of positional
30 * predicates or otherwise, can only be evaluated "the hard way", by evaluating the equivalent
31 * expression with successive ancestors of the tested node as context item.
32 */
33
34 public final class GeneralNodePattern extends Pattern {
35
36 private Expression equivalentExpr = null;
37 private NodeTest itemType = null;
38
39 /**
40 * Create a GeneralNodePattern
41 *
42 * @param expr the "equivalent expression"
43 * @param itemType a type that all matched nodes must satisfy
44 */
45
46 public GeneralNodePattern(Expression expr, NodeTest itemType) {
47 equivalentExpr = expr;
48 this.itemType = itemType;
49 }
50
51 /**
52 * Get the immediate sub-expressions of this expression, with information about the relationship
53 * of each expression to its parent expression. Default implementation
54 * works off the results of iterateSubExpressions()
55 * <p>If the expression is a Callable, then it is required that the order of the operands
56 * returned by this function is the same as the order of arguments supplied to the corresponding
57 * call() method.</p>
58 *
59 * @return an iterator containing the sub-expressions of this expression
60 */
61 @Override
62 public Iterable<Operand> operands() {
63 return new Operand(this, equivalentExpr, OperandRole.SAME_FOCUS_ACTION);
64 }
65
66 /**
67 * Test whether a pattern is motionless, that is, whether it can be evaluated against a node
68 * without repositioning the input stream. This is a necessary condition for patterns used
69 * as the match pattern of a streamed template rule.
70 *
71 * @return true if the pattern is motionless, that is, if it can be evaluated against a streamed
72 * node without changing the position in the streamed input file
73 */
74
75 public boolean isMotionless() {
76 return false;
77 }
78
79 /**
80 * Type-check the pattern, performing any type-dependent optimizations.
81 *
82 * @param visitor an expression visitor
83 * @param contextItemType the type of the context item at the point where the pattern appears
84 * @return the optimised Pattern
85 */
86
87 public Pattern typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType) throws XPathException {
88 ContextItemStaticInfo cit = visitor.getConfiguration().getDefaultContextItemStaticInfo();
89 equivalentExpr = equivalentExpr.typeCheck(visitor, cit);
90 return this;
91 }
92
93 /**
94 * Perform optimisation of an expression and its subexpressions. This is the third and final
95 * phase of static optimization.
96 * <p>This method is called after all references to functions and variables have been resolved
97 * to the declaration of the function or variable, and after all type checking has been done.</p>
98 *
99 * @param visitor an expression visitor
100 * @param contextInfo the static type of "." at the point where this expression is invoked.
101 * The parameter is set to null if it is known statically that the context item will be undefined.
102 * If the type of the context item is not known statically, the argument is set to
103 * {@link Type#ITEM_TYPE}
104 * @return the original expression, rewritten if appropriate to optimize execution
105 * @throws XPathException if an error is discovered during this phase
106 * (typically a type error)
107 */
108 @Override
109 public Pattern optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
110 Configuration config = visitor.getConfiguration();
111 ContextItemStaticInfo defaultInfo = config.getDefaultContextItemStaticInfo();
112 equivalentExpr = equivalentExpr.optimize(visitor, defaultInfo);
113 // See if the expression is now known to be non-positional
114 if (equivalentExpr instanceof FilterExpression && !((FilterExpression) equivalentExpr).isFilterIsPositional()) {
115 try {
116 return PatternMaker.fromExpression(equivalentExpr, config, true)
117 .typeCheck(visitor, defaultInfo);
118 } catch (XPathException err) {
119 // cannot make pattern from expression - not a problem, just use the original
120 }
121 }
122 return this;
123 }
124
125 /**
126 * Get the dependencies of the pattern. The only interesting dependencies for a pattern are
127 * dependencies on local variables or on user-defined functions. These are analyzed in those
128 * patterns containing predicates.
129 *
130 * @return the dependencies, as a bit-significant mask
131 */
132
133 public int getDependencies() {
134 return equivalentExpr.getDependencies() &
135 (StaticProperty.DEPENDS_ON_LOCAL_VARIABLES | StaticProperty.DEPENDS_ON_USER_FUNCTIONS);
136 }
137
138 /**
139 * Replace any calls on current() by a variable reference bound to the supplied binding
140 */
141 @Override
142 public void bindCurrent(LocalBinding binding) {
143 if (ExpressionTool.callsFunction(equivalentExpr, Current.FN_CURRENT, false)) {
144 if (equivalentExpr.isCallOn(Current.class)) {
145 equivalentExpr = new LocalVariableReference(binding);
146 } else {
147 replaceCurrent(equivalentExpr, binding);
148 }
149 }
150 }
151
152 /**
153 * Allocate slots to any variables used within the pattern
154 *
155 * @param slotManager details of the stack frame
156 * @param nextFree the next slot that is free to be allocated @return the next slot that is free to be allocated
157 */
158
159 public int allocateSlots(SlotManager slotManager, int nextFree) {
160 return ExpressionTool.allocateSlots(equivalentExpr, nextFree, slotManager);
161 }
162
163 /**
164 * Determine whether the pattern matches a given item.
165 *
166 * @param item the item to be tested
167 * @return true if the pattern matches, else false
168 */
169
170 public boolean matches(Item<?> item, XPathContext context) throws XPathException {
171 TypeHierarchy th = context.getConfiguration().getTypeHierarchy();
172 if (!itemType.matches(item, th)) {
173 return false;
174 }
175 AxisIterator anc = ((NodeInfo) item).iterateAxis(AxisInfo.ANCESTOR_OR_SELF);
176 while (true) {
177 NodeInfo a = anc.next();
178 if (a == null) {
179 return false;
180 }
181 if (matchesBeneathAnchor((NodeInfo) item, a, context)) {
182 return true;
183 }
184 }
185 }
186
187 /**
188 * Determine whether this pattern matches a given Node within the subtree rooted at a given
189 * anchor node. This method is used when the pattern is used for streaming.
190 *
191 * @param node The NodeInfo representing the Element or other node to be tested against the Pattern
192 * @param anchor The anchor node, which if present must match any AnchorPattern subpattern; may be null
193 * @param context The dynamic context. Only relevant if the pattern
194 * uses variables, or contains calls on functions such as document() or key().
195 * @return true if the node matches the Pattern, false otherwise
196 */
197
198 public boolean matchesBeneathAnchor(NodeInfo node, NodeInfo anchor, XPathContext context) throws XPathException {
199 if (!itemType.matchesNode(node)) {
200 return false;
201 }
202
203 // for a positional pattern, we do it the hard way: test whether the
204 // node is a member of the nodeset obtained by evaluating the
205 // equivalent expression
206
207 if (anchor == null) {
208 AxisIterator ancestors = node.iterateAxis(AxisInfo.ANCESTOR_OR_SELF);
209 while (true) {
210 NodeInfo ancestor = ancestors.next();
211 if (ancestor == null) {
212 return false;
213 }
214 if (matchesBeneathAnchor(node, ancestor, context)) {
215 return true;
216 }
217 }
218 }
219
220 // System.err.println("Testing positional pattern against node " + node.generateId());
221 XPathContext c2 = context.newMinorContext();
222 ManualIterator<? extends NodeInfo> iter = new ManualIterator<>(anchor);
223 c2.setCurrentIterator(iter);
224 try {
225 SequenceIterator<? extends NodeInfo> nsv = (SequenceIterator<? extends NodeInfo>)equivalentExpr.iterate(c2);
226 while (true) {
227 NodeInfo n = nsv.next();
228 if (n == null) {
229 return false;
230 }
231 if (n.equals(node)) {
232 return true;
233 }
234 }
235 } catch (XPathException.Circularity e) {
236 throw e;
237 } catch (XPathException e) {
238 handleDynamicError(e, c2);
239 return false;
240 }
241 }
242
243 /**
244 * Get a UType indicating which kinds of items this Pattern can match.
245 *
246 * @return a UType indicating all the primitive types of item that the pattern can match.
247 */
248 @Override
249 public UType getUType() {
250 return itemType.getUType();
251 }
252
253 /**
254 * Determine the fingerprint of nodes to which this pattern applies.
255 * Used for optimisation.
256 *
257 * @return the fingerprint of nodes matched by this pattern.
258 */
259
260 public int getFingerprint() {
261 return itemType.getFingerprint();
262 }
263
264 /**
265 * Get a NodeTest that all the nodes matching this pattern must satisfy
266 */
267
268 public ItemType getItemType() {
269 return itemType;
270 }
271
272 public Expression getEquivalentExpr() {
273 return equivalentExpr;
274 }
275 /**
276 * Determine whether this pattern is the same as another pattern
277 *
278 * @param other the other object
279 */
280
281 public boolean equals(Object other) {
282 if (other instanceof GeneralNodePattern) {
283 GeneralNodePattern lpp = (GeneralNodePattern) other;
284 return equivalentExpr.isEqual(lpp.equivalentExpr);
285 } else {
286 return false;
287 }
288 }
289
290 /**
291 * hashcode supporting equals()
292 */
293
294 public int computeHashCode() {
295 return 83641 ^ equivalentExpr.hashCode();
296 }
297
298 /**
299 * Copy a pattern. This makes a deep copy.
300 *
301 * @return the copy of the original pattern
302 * @param rebindings variables that need to be re-bound
303 */
304
305 /*@NotNull*/
306 public Pattern copy(RebindingMap rebindings) {
307 GeneralNodePattern n = new GeneralNodePattern(equivalentExpr.copy(rebindings), itemType);
308 ExpressionTool.copyLocationInfo(this, n);
309 return n;
310 }
311
312 public void export(ExpressionPresenter presenter) throws XPathException {
313 presenter.startElement("p.genNode");
314 presenter.emitAttribute("type", itemType.toString());
315 equivalentExpr.export(presenter);
316 presenter.endElement();
317 }
318
319 }
320