Debian Codegraph @

net/sf/saxon/pattern/BasePatternWithPredicate.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.expr.*;
14 import net.sf.saxon.expr.instruct.SlotManager;
15 import net.sf.saxon.expr.parser.ContextItemStaticInfo;
16 import net.sf.saxon.expr.parser.ExpressionTool;
17 import net.sf.saxon.expr.parser.ExpressionVisitor;
18 import net.sf.saxon.expr.parser.RebindingMap;
19 import net.sf.saxon.functions.Current;
20 import net.sf.saxon.om.Item;
21 import net.sf.saxon.om.NodeInfo;
22 import net.sf.saxon.trace.ExpressionPresenter;
23 import net.sf.saxon.trans.XPathException;
24 import net.sf.saxon.tree.iter.ManualIterator;
25 import net.sf.saxon.type.ItemType;
26 import net.sf.saxon.type.Type;
27 import net.sf.saxon.type.UType;
28
29 /**
30 * Class for handling patterns with simple non-positional boolean predicates
31 */
32 public class BasePatternWithPredicate extends Pattern implements PatternWithPredicate {
33
34 Operand basePatternOp;
35 Operand predicateOp;
36
37 public BasePatternWithPredicate(Pattern basePattern, Expression predicate) {
38 basePatternOp = new Operand(this, basePattern, OperandRole.ATOMIC_SEQUENCE);
39 predicateOp = new Operand(this, predicate, OperandRole.FOCUS_CONTROLLED_ACTION);
40 adoptChildExpression(getBasePattern());
41 adoptChildExpression(getPredicate());
42 }
43
44 public Expression getPredicate() {
45 return predicateOp.getChildExpression();
46 }
47 public Pattern getBasePattern() {
48 return (Pattern)basePatternOp.getChildExpression();
49 }
50
51 /**
52 * Replace any calls on current() by a variable reference bound to the supplied binding
53 */
54 @Override
55 public void bindCurrent(LocalBinding binding) {
56 Expression predicate = getPredicate();
57 if (predicate.isCallOn(Current.class)) {
58 predicateOp.setChildExpression(new LocalVariableReference(binding));
59 } else if (ExpressionTool.callsFunction(predicate, Current.FN_CURRENT, false)) {
60 replaceCurrent(predicate, binding);
61 }
62 getBasePattern().bindCurrent(binding);
63 }
64
65 /**
66 * Ask whether the pattern is anchored on a call on current-group()
67 *
68 * @return true if calls on matchesBeneathAnchor should test with all nodes in the
69 * current group as anchor nodes. If false, only the first node in a group is
70 * treated as the anchor node
71 */
72
73 public boolean matchesCurrentGroup() {
74 return getBasePattern().matchesCurrentGroup();
75 }
76
77 /**
78 * Get the immediate sub-expressions of this expression, with information about the relationship
79 * of each expression to its parent expression. Default implementation
80 * works off the results of iterateSubExpressions()
81 * <p>If the expression is a Callable, then it is required that the order of the operands
82 * returned by this function is the same as the order of arguments supplied to the corresponding
83 * call() method.</p>
84 *
85 * @return an iterator containing the sub-expressions of this expression
86 */
87 @Override
88 public Iterable<Operand> operands() {
89 return operandList(basePatternOp, predicateOp);
90 }
91
92 /**
93 * Allocate slots to any variables used within the pattern
94 *
95 * @param slotManager holds details of the allocated slots
96 * @param nextFree the next slot that is free to be allocated @return the next slot that is free to be allocated
97 */
98
99 public int allocateSlots(SlotManager slotManager, int nextFree) {
100 int n = ExpressionTool.allocateSlots(getPredicate(), nextFree, slotManager);
101 return getBasePattern().allocateSlots(slotManager, n);
102 }
103
104 /**
105 * Determine whether this Pattern matches the given Node.
106 *
107 * @param item The NodeInfo representing the Element or other node to be tested against the Pattern
108 * @param context The dynamic context. Only relevant if the pattern
109 * uses variables, or contains calls on functions such as document() or key().
110 * @return true if the node matches the Pattern, false otherwise
111 */
112 @Override
113 public boolean matches(Item<?> item, XPathContext context) throws XPathException {
114 if (!getBasePattern().matches(item, context)) {
115 return false;
116 }
117 return matchesPredicate(item, context);
118 }
119
120 private boolean matchesPredicate(Item<?> item, XPathContext context) throws XPathException {
121 XPathContext c2 = context.newMinorContext();
122 ManualIterator<Item<?>> si = new ManualIterator<>(item);
123 c2.setCurrentIterator(si);
124 c2.setCurrentOutputUri(null);
125 try {
126 return getPredicate().effectiveBooleanValue(c2);
127 } catch (XPathException.Circularity e) {
128 throw e;
129 } catch (XPathException ex) {
130 handleDynamicError(ex, c2);
131 return false;
132 }
133 }
134
135 @Override
136 public boolean matchesBeneathAnchor(NodeInfo node, NodeInfo anchor, XPathContext context) throws XPathException {
137 return getBasePattern().matchesBeneathAnchor(node, anchor, context) &&
138 matchesPredicate(node, context);
139 }
140
141 /**
142 * Get a UType indicating which kinds of items this Pattern can match.
143 *
144 * @return a UType indicating all the primitive types of item that the pattern can match.
145 */
146 @Override
147 public UType getUType() {
148 return getBasePattern().getUType();
149 }
150
151 /**
152 * Determine the name fingerprint of nodes to which this pattern applies. Used for
153 * optimisation.
154 *
155 * @return A fingerprint that the nodes must match, or -1 if it can match multiple fingerprints,
156 * or it if matches atomic values
157 */
158 @Override
159 public int getFingerprint() {
160 return getBasePattern().getFingerprint();
161 }
162
163 /**
164 * Get an ItemType that all the items matching this pattern must satisfy
165 *
166 * @return an ItemType, as specific as possible, which all the matching items satisfy
167 */
168 /*@Nullable*/
169 @Override
170 public ItemType getItemType() {
171 return getBasePattern().getItemType();
172 }
173
174 /**
175 * Get the dependencies of the pattern. The only possible dependency for a pattern is
176 * on local variables. This is analyzed in those patterns where local variables may appear.
177 *
178 * @return the dependencies, as a bit-significant mask
179 */
180 @Override
181 public int getDependencies() {
182 return getPredicate().getDependencies();
183 }
184
185 /**
186 * Type-check the pattern.
187 *
188 * @param visitor the expression visitor
189 * @param contextItemType the type of the context item at the point where the pattern
190 * is defined. Set to null if it is known that the context item is undefined.
191 * @return the optimised Pattern
192 */
193 @Override
194 public Pattern typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType) throws XPathException {
195 basePatternOp.setChildExpression(getBasePattern().typeCheck(visitor, contextItemType));
196 ContextItemStaticInfo cit = visitor.getConfiguration().makeContextItemStaticInfo(
197 getBasePattern().getItemType(), false);
198 predicateOp.setChildExpression(getPredicate().typeCheck(visitor, cit));
199 return this;
200 }
201
202 /**
203 * Perform optimisation of an expression and its subexpressions. This is the third and final
204 * phase of static optimization.
205 * <p>This method is called after all references to functions and variables have been resolved
206 * to the declaration of the function or variable, and after all type checking has been done.</p>
207 *
208 * @param visitor an expression visitor
209 * @param contextInfo the static type of "." at the point where this expression is invoked.
210 * The parameter is set to null if it is known statically that the context item will be undefined.
211 * If the type of the context item is not known statically, the argument is set to
212 * {@link Type#ITEM_TYPE}
213 * @return the original expression, rewritten if appropriate to optimize execution
214 * @throws XPathException if an error is discovered during this phase
215 * (typically a type error)
216 */
217 @Override
218 public Pattern optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
219 basePatternOp.setChildExpression(getBasePattern().optimize(visitor, contextInfo));
220 ContextItemStaticInfo cit = visitor.getConfiguration().makeContextItemStaticInfo(
221 getBasePattern().getItemType(), false);
222 predicateOp.setChildExpression(getPredicate().optimize(visitor, cit));
223 predicateOp.setChildExpression(visitor.obtainOptimizer().eliminateCommonSubexpressions(getPredicate()));
224 return this;
225 }
226
227 /**
228 * Convert the pattern to a typed pattern, in which an element name is treated as
229 * schema-element(N)
230 *
231 * @param val either "strict" or "lax" depending on the value of xsl:mode/@typed
232 * @return either the original pattern unchanged, or a new pattern as the result of the
233 * conversion
234 * @throws net.sf.saxon.trans.XPathException if the pattern cannot be converted
235 */
236 @Override
237 public Pattern convertToTypedPattern(String val) throws XPathException {
238 Pattern b2 = getBasePattern().convertToTypedPattern(val);
239 if (b2 == getBasePattern()) {
240 return this;
241 } else {
242 return new BasePatternWithPredicate(b2, getPredicate());
243 }
244 }
245
246 //#ifdefined STREAM
247 @Override
248 public boolean isMotionless() {
249 ContextItemStaticInfoEE cio = (ContextItemStaticInfoEE)getConfiguration().makeContextItemStaticInfo(getItemType(), false);
250 cio.setContextPostureStriding();
251 Streamability.getStreamability(getPredicate(), cio, null);
252 return getBasePattern().isMotionless() &&
253 Streamability.getSweep(getPredicate()) == Sweep.MOTIONLESS;
254 }
255
256 //#endif
257
258 /**
259 * Display the pattern for diagnostics
260 */
261
262 public String toString() {
263 return getBasePattern() + "[" + getPredicate() + "]";
264 }
265
266 @Override
267 public String toShortString() {
268 return getBasePattern().toShortString() + "[" + getPredicate().toShortString() + "]";
269 }
270
271
272 /**
273 * Copy a pattern. This makes a deep copy.
274 *
275 * @return the copy of the original pattern
276 * @param rebindings variables that need to be re-bound
277 */
278
279 /*@NotNull*/
280 public Pattern copy(RebindingMap rebindings) {
281 BasePatternWithPredicate n = new BasePatternWithPredicate(
282 getBasePattern().copy(rebindings), getPredicate().copy(rebindings));
283 ExpressionTool.copyLocationInfo(this, n);
284 return n;
285 }
286
287 @Override
288 public boolean equals(Object obj) {
289 return obj instanceof BasePatternWithPredicate &&
290 ((BasePatternWithPredicate)obj).getBasePattern().isEqual(getBasePattern()) &&
291 ((BasePatternWithPredicate) obj).getPredicate().isEqual(getPredicate());
292 }
293
294 @Override
295 public int computeHashCode() {
296 return getBasePattern().hashCode() ^ getPredicate().hashCode();
297 }
298
299 public void export(ExpressionPresenter presenter) throws XPathException {
300 presenter.startElement("p.withPredicate");
301 getBasePattern().export(presenter);
302 getPredicate().export(presenter);
303 presenter.endElement();
304 }
305
306 }
307