Debian Codegraph @

net/sf/saxon/expr/QuantifiedExpression.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.functions.BooleanFn;
13 import net.sf.saxon.functions.SystemFunction;
14 import net.sf.saxon.om.GroundedValue;
15 import net.sf.saxon.om.Item;
16 import net.sf.saxon.om.SequenceIterator;
17 import net.sf.saxon.trace.ExpressionPresenter;
18 import net.sf.saxon.trans.XPathException;
19 import net.sf.saxon.type.BuiltInAtomicType;
20 import net.sf.saxon.type.ItemType;
21 import net.sf.saxon.type.UType;
22 import net.sf.saxon.value.BooleanValue;
23 import net.sf.saxon.value.SequenceType;
24
25 /**
26 * A QuantifiedExpression tests whether some/all items in a sequence satisfy
27 * some condition.
28 */
29
30 public class QuantifiedExpression extends Assignation {
31
32 private int operator; // Token.SOME or Token.EVERY
33
34 /**
35 * Get a name identifying the kind of expression, in terms meaningful to a user.
36 *
37 * @return a name identifying the kind of expression, in terms meaningful to a user.
38 * The name will always be in the form of a lexical XML QName, and should match the name used
39 * in explain() output displaying the expression.
40 */
41
42 public String getExpressionName() {
43 return Token.tokens[operator];
44 }
45
46 /**
47 * Set the operator, either {@link Token#SOME} or {@link Token#EVERY}
48 *
49 * @param operator the operator
50 */
51
52 public void setOperator(int operator) {
53 this.operator = operator;
54 }
55
56 /**
57 * Get the operator, either {@link Token#SOME} or {@link Token#EVERY}
58 *
59 * @return the operator
60 */
61
62 public int getOperator() {
63 return operator;
64 }
65
66 /**
67 * Determine the static cardinality
68 */
69
70 public int computeCardinality() {
71 return StaticProperty.EXACTLY_ONE;
72 }
73
74 /**
75 * Type-check the expression
76 */
77
78 /*@NotNull*/
79 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
80
81 // The order of events is critical here. First we ensure that the type of the
82 // sequence expression is established. This is used to establish the type of the variable,
83 // which in turn is required when type-checking the action part.
84
85 getSequenceOp().typeCheck(visitor, contextInfo);
86
87 if (Literal.isEmptySequence(getSequence())) {
88 return Literal.makeLiteral(BooleanValue.get(operator != Token.SOME), this);
89 }
90
91 // "some" and "every" have no ordering constraints
92
93 setSequence(getSequence().unordered(false, false));
94
95 SequenceType decl = getRequiredType();
96 if (decl.getCardinality() == StaticProperty.ALLOWS_ZERO) {
97 XPathException err = new XPathException("Range variable will never satisfy the type empty-sequence()", "XPTY0004");
98 err.setIsTypeError(true);
99 err.setLocation(getLocation());
100 throw err;
101 }
102 SequenceType sequenceType = SequenceType.makeSequenceType(decl.getPrimaryType(),
103 StaticProperty.ALLOWS_ZERO_OR_MORE);
104 RoleDiagnostic role = new RoleDiagnostic(RoleDiagnostic.VARIABLE, getVariableQName().getDisplayName(), 0);
105 //role.setSourceLocator(this);
106 setSequence(TypeChecker.strictTypeCheck(
107 getSequence(), sequenceType, role, visitor.getStaticContext()));
108 ItemType actualItemType = getSequence().getItemType();
109 refineTypeInformation(actualItemType,
110 StaticProperty.EXACTLY_ONE,
111 null,
112 getSequence().getSpecialProperties(), this);
113
114 //declaration = null; // let the garbage collector take it
115
116 getActionOp().typeCheck(visitor, contextInfo);
117 XPathException err = TypeChecker.ebvError(getAction(), visitor.getConfiguration().getTypeHierarchy());
118 if (err != null) {
119 err.setLocation(getLocation());
120 throw err;
121 }
122 return this;
123 }
124
125 /**
126 * Perform optimisation of an expression and its subexpressions.
127 * <p>This method is called after all references to functions and variables have been resolved
128 * to the declaration of the function or variable, and after all type checking has been done.</p>
129 *
130 * @param visitor an expression visitor
131 * @param contextItemType the static type of "." at the point where this expression is invoked.
132 * The parameter is set to null if it is known statically that the context item will be undefined.
133 * If the type of the context item is not known statically, the argument is set to
134 * {@link net.sf.saxon.type.Type#ITEM_TYPE}
135 * @return the original expression, rewritten if appropriate to optimize execution
136 * @throws XPathException if an error is discovered during this phase
137 * (typically a type error)
138 */
139
140 /*@NotNull*/
141 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType) throws XPathException {
142
143 Configuration config = visitor.getConfiguration();
144 Optimizer opt = visitor.obtainOptimizer();
145
146 getSequenceOp().optimize(visitor, contextItemType);
147 getActionOp().optimize(visitor, contextItemType);
148 Expression ebv = BooleanFn.rewriteEffectiveBooleanValue(getAction(), visitor, contextItemType);
149 if (ebv != null) {
150 setAction(ebv);
151 adoptChildExpression(ebv);
152 }
153 if (Literal.hasEffectiveBooleanValue(ebv, true)) {
154 // some $x satisfies true() => exists($x)
155 // every $x satisfies true() => true()
156 if (getOperator() == Token.SOME) {
157 return SystemFunction.makeCall("exists", getRetainedStaticContext(), getSequence());
158 } else {
159 Expression e2 = new Literal(BooleanValue.TRUE);
160 ExpressionTool.copyLocationInfo(this, e2);
161 return e2;
162 }
163 } else if (Literal.hasEffectiveBooleanValue(ebv, false)) {
164 // some $x satisfies false() => false()
165 // every $x satisfies false() => empty($x)
166 if (getOperator() == Token.SOME) {
167 Expression e2 = new Literal(BooleanValue.FALSE);
168 ExpressionTool.copyLocationInfo(this, e2);
169 return e2;
170 } else {
171 return SystemFunction.makeCall("empty", getRetainedStaticContext(), getSequence());
172 }
173 }
174 if (getSequence() instanceof Literal) {
175 GroundedValue seq = ((Literal)getSequence()).getValue();
176 int len = seq.getLength();
177 if (len == 0) {
178 Expression e2 = new Literal(BooleanValue.get(getOperator() == Token.EVERY));
179 ExpressionTool.copyLocationInfo(this, e2);
180 return e2;
181 } else if (len == 1) {
182 if (getAction() instanceof VariableReference && ((VariableReference) getAction()).getBinding() == this) {
183 return SystemFunction.makeCall("boolean", getRetainedStaticContext(), getSequence());
184 } else {
185 replaceVariable(getSequence());
186 return getAction();
187 }
188 }
189 }
190
191 // if streaming, convert to an expression that can be streamed
192
193 if (visitor.isOptimizeForStreaming()) {
194 Expression e3 = visitor.obtainOptimizer().optimizeQuantifiedExpressionForStreaming(this);
195 if (e3 != null && e3 != this) {
196 return e3.optimize(visitor, contextItemType);
197 }
198 }
199 return this;
200 }
201
202 /**
203 * An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process().
204 * This method indicates which of these methods is provided directly. The other methods will always be available
205 * indirectly, using an implementation that relies on one of the other methods.
206 *
207 * @return the implementation method, for example {@link #ITERATE_METHOD} or {@link #EVALUATE_METHOD} or
208 * {@link #PROCESS_METHOD}
209 */
210 @Override
211 public int getImplementationMethod() {
212 return EVALUATE_METHOD;
213 }
214
215 /**
216 * Check to ensure that this expression does not contain any updating subexpressions.
217 * This check is overridden for those expressions that permit updating subexpressions.
218 *
219 * @throws net.sf.saxon.trans.XPathException
220 * if the expression has a non-permitted updateing subexpression
221 */
222
223 public void checkForUpdatingSubexpressions() throws XPathException {
224 getSequence().checkForUpdatingSubexpressions();
225 getAction().checkForUpdatingSubexpressions();
226 }
227
228 /**
229 * Determine whether this is an updating expression as defined in the XQuery update specification
230 *
231 * @return true if this is an updating expression
232 */
233
234 public boolean isUpdatingExpression() {
235 return false;
236 }
237
238 /**
239 * Copy an expression. This makes a deep copy.
240 *
241 * @return the copy of the original expression
242 * @param rebindings variables that need to be re-bound
243 */
244
245 /*@NotNull*/
246 public Expression copy(RebindingMap rebindings) {
247 QuantifiedExpression qe = new QuantifiedExpression();
248 ExpressionTool.copyLocationInfo(this, qe);
249 qe.setOperator(operator);
250 qe.setVariableQName(variableName);
251 qe.setRequiredType(requiredType);
252 qe.setSequence(getSequence().copy(rebindings));
253 Expression newAction = getAction().copy(rebindings);
254 qe.setAction(newAction);
255 qe.variableName = variableName;
256 qe.slotNumber = slotNumber;
257 ExpressionTool.rebindVariableReferences(newAction, this, qe);
258 return qe;
259 }
260
261
262 /**
263 * Determine the special properties of this expression
264 *
265 * @return {@link StaticProperty#NO_NODES_NEWLY_CREATED}.
266 */
267
268 public int computeSpecialProperties() {
269 int p = super.computeSpecialProperties();
270 return p | StaticProperty.NO_NODES_NEWLY_CREATED;
271 }
272
273 /**
274 * Evaluate the expression to return a singleton value
275 */
276
277 public BooleanValue evaluateItem(XPathContext context) throws XPathException {
278 return BooleanValue.get(effectiveBooleanValue(context));
279 }
280
281 /**
282 * Get the result as a boolean
283 */
284
285 public boolean effectiveBooleanValue(XPathContext context) throws XPathException {
286
287 // First create an iteration of the base sequence.
288
289 SequenceIterator<?> base = getSequence().iterate(context);
290
291 // Now test to see if some or all of the tests are true. The same
292 // logic is used for the SOME and EVERY operators
293
294 final boolean some = operator == Token.SOME;
295 int slot = getLocalSlotNumber();
296 Item<?> it;
297 while ((it = base.next()) != null) {
298 context.setLocalVariable(slot, it);
299 if (some == getAction().effectiveBooleanValue(context)) {
300 base.close();
301 return some;
302 }
303 }
304 return !some;
305 }
306
307
308 /**
309 * Determine the data type of the items returned by the expression
310 *
311 * @return Type.BOOLEAN
312 */
313
314 /*@NotNull*/
315 public ItemType getItemType() {
316 return BuiltInAtomicType.BOOLEAN;
317 }
318
319 /**
320 * Get the static type of the expression as a UType, following precisely the type
321 * inference rules defined in the XSLT 3.0 specification.
322 *
323 * @return the static item type of the expression according to the XSLT 3.0 defined rules
324 * @param contextItemType the static type of the context item
325 */
326 @Override
327 public UType getStaticUType(UType contextItemType) {
328 return UType.BOOLEAN;
329 }
330
331 /**
332 * The toString() method for an expression attempts to give a representation of the expression
333 * in an XPath-like form, but there is no guarantee that the syntax will actually be true XPath.
334 * In the case of XSLT instructions, the toString() method gives an abstracted view of the syntax
335 *
336 * @return a representation of the expression as a string
337 */
338
339 public String toString() {
340 return (operator == Token.SOME ? "some" : "every") + " $" + getVariableEQName() +
341 " in " + getSequence() + " satisfies " +
342 ExpressionTool.parenthesize(getAction());
343 }
344
345 public String toShortString() {
346 return (operator == Token.SOME ? "some" : "every") + " $" + getVariableName() +
347 " in " + getSequence().toShortString() + " satisfies ...";
348 }
349
350 /**
351 * Diagnostic print of expression structure. The abstract expression tree
352 * is written to the supplied output destination.
353 */
354
355 public void export(ExpressionPresenter out) throws XPathException {
356 out.startElement(Token.tokens[operator], this);
357 out.emitAttribute("var", getVariableQName());
358 out.emitAttribute("slot", ""+slotNumber);
359 getSequence().export(out);
360 getAction().export(out);
361 out.endElement();
362 }
363
364
365
366 }
367