Debian Codegraph @

net/sf/saxon/expr/SystemFunctionCall.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.instruct.AnalyzeString;
12 import net.sf.saxon.expr.oper.OperandArray;
13 import net.sf.saxon.expr.parser.*;
14 import net.sf.saxon.functions.*;
15 import net.sf.saxon.functions.Error;
16 import net.sf.saxon.functions.registry.BuiltInFunctionSet;
17 import net.sf.saxon.lib.NamespaceConstant;
18 import net.sf.saxon.ma.map.MapFunctionSet;
19 import net.sf.saxon.om.Sequence;
20 import net.sf.saxon.pattern.NodeSetPattern;
21 import net.sf.saxon.pattern.Pattern;
22 import net.sf.saxon.trace.ExpressionPresenter;
23 import net.sf.saxon.trans.XPathException;
24 import net.sf.saxon.type.BuiltInAtomicType;
25 import net.sf.saxon.type.ItemType;
26 import net.sf.saxon.type.TypeHierarchy;
27 import net.sf.saxon.value.IntegerValue;
28
29 import java.util.Arrays;
30
31 /**
32 * A call to a system-defined function (specifically, a function implemented as an instance
33 * of {@link net.sf.saxon.functions.SystemFunction})
34 */
35 public class SystemFunctionCall extends StaticFunctionCall implements Negatable {
36
37 public Evaluator[] argumentEvaluators;
38
39 public SystemFunctionCall(SystemFunction target, Expression[] arguments) {
40 super(target, arguments);
41 argumentEvaluators = new Evaluator[arguments.length];
42 Arrays.fill(argumentEvaluators, Evaluator.LAZY_SEQUENCE);
43 }
44
45 /**
46 * Set the retained static context
47 *
48 * @param rsc the static context to be retained
49 */
50 @Override
51 public void setRetainedStaticContext(RetainedStaticContext rsc) {
52 super.setRetainedStaticContext(rsc);
53 getTargetFunction().setRetainedStaticContext(rsc);
54 }
55
56 /**
57 * Pre-evaluate a function at compile time. Functions that do not allow
58 * pre-evaluation, or that need access to context information, can prevent early
59 * evaluation by setting the LATE bit in the function properties.
60 *
61 * @param visitor an expression visitor
62 * @return the result of the early evaluation, or the original expression, or potentially
63 * a simplified expression
64 * @throws net.sf.saxon.trans.XPathException if evaluation fails
65 */
66 @Override
67 public Expression preEvaluate(ExpressionVisitor visitor) throws XPathException {
68 SystemFunction target = getTargetFunction();
69 if ((target.getDetails().properties & BuiltInFunctionSet.LATE) == 0) {
70 return super.preEvaluate(visitor);
71 } else {
72 // Early evaluation of this function is suppressed
73 return this;
74 }
75 }
76
77 /**
78 * Type-check the expression. This also calls preEvaluate() to evaluate the function
79 * if all the arguments are constant; functions that do not require this behavior
80 * can override the preEvaluate method.
81 *
82 * @param visitor the expression visitor
83 * @param contextInfo information about the type of the context item
84 */
85 @Override
86 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
87 typeCheckChildren(visitor, contextInfo);
88 checkFunctionCall(getTargetFunction(), visitor);
89 // Give the function an opportunity to use the type information now available
90 getTargetFunction().supplyTypeInformation(visitor, contextInfo, getArguments());
91 if ((getTargetFunction().getDetails().properties & BuiltInFunctionSet.LATE) == 0) {
92 return preEvaluateIfConstant(visitor);
93 }
94 allocateArgumentEvaluators(getArguments());
95 return this;
96 }
97
98 private void allocateArgumentEvaluators(Expression[] arguments) {
99 for (int i = 0; i < arguments.length; i++) {
100 Expression arg = arguments[i];
101 int cardinality = isCallOn(Concat.class) ?
102 StaticProperty.ALLOWS_ZERO_OR_ONE :
103 getTargetFunction().getDetails().argumentTypes[i].getCardinality();
104 if (arg instanceof Literal) {
105 argumentEvaluators[i] = Evaluator.LITERAL;
106 } else if (arg instanceof VariableReference) {
107 argumentEvaluators[i] = Evaluator.VARIABLE;
108 } else if (cardinality == StaticProperty.EXACTLY_ONE) {
109 argumentEvaluators[i] = Evaluator.SINGLE_ITEM;
110 } else if (cardinality == StaticProperty.ALLOWS_ZERO_OR_ONE) {
111 argumentEvaluators[i] = Evaluator.OPTIONAL_ITEM;
112 } else {
113 argumentEvaluators[i] = Evaluator.LAZY_SEQUENCE;
114 }
115 }
116 }
117
118 @Override
119 public SystemFunction getTargetFunction() {
120 return (SystemFunction) super.getTargetFunction();
121 }
122
123 /**
124 * Compute the dependencies of an expression, as the union of the
125 * dependencies of its subexpressions. (This is overridden for path expressions
126 * and filter expressions, where the dependencies of a subexpression are not all
127 * propogated). This method should be called only once, to compute the dependencies;
128 * after that, getDependencies should be used.
129 *
130 * @return the depencies, as a bit-mask
131 */
132 @Override
133 public int getIntrinsicDependencies() {
134 int properties = getTargetFunction().getDetails().properties;
135 int dep = 0;
136 if ((properties & BuiltInFunctionSet.LATE) != 0) {
137 dep = StaticProperty.DEPENDS_ON_RUNTIME_ENVIRONMENT;
138 }
139 if ((properties & BuiltInFunctionSet.FOCUS) != 0) {
140 if ((properties & BuiltInFunctionSet.CDOC) != 0) {
141 dep |= StaticProperty.DEPENDS_ON_CONTEXT_DOCUMENT;
142 }
143 if ((properties & BuiltInFunctionSet.CITEM) != 0) {
144 dep |= StaticProperty.DEPENDS_ON_CONTEXT_ITEM;
145 }
146 if ((properties & BuiltInFunctionSet.POSN) != 0) {
147 dep |= StaticProperty.DEPENDS_ON_POSITION;
148 }
149 if ((properties & BuiltInFunctionSet.LAST) != 0) {
150 dep |= StaticProperty.DEPENDS_ON_LAST;
151 }
152 }
153 if ((properties & BuiltInFunctionSet.BASE) != 0) {
154 dep |= StaticProperty.DEPENDS_ON_STATIC_CONTEXT;
155 }
156 if ((properties & BuiltInFunctionSet.DCOLL) != 0) {
157 dep |= StaticProperty.DEPENDS_ON_STATIC_CONTEXT;
158 }
159 if (isCallOn(RegexGroup.class) || isCallOn(CurrentMergeGroup.class) || isCallOn(CurrentMergeKey.class)) {
160 dep |= StaticProperty.DEPENDS_ON_CURRENT_GROUP;
161 }
162 return dep;
163 }
164
165 /**
166 * Compute the static cardinality of this expression
167 *
168 * @return the computed cardinality, as one of the values {@link net.sf.saxon.expr.StaticProperty#ALLOWS_ZERO_OR_ONE},
169 * {@link net.sf.saxon.expr.StaticProperty#EXACTLY_ONE}, {@link net.sf.saxon.expr.StaticProperty#ALLOWS_ONE_OR_MORE},
170 * {@link net.sf.saxon.expr.StaticProperty#ALLOWS_ZERO_OR_MORE}
171 */
172 @Override
173 protected int computeCardinality() {
174 return getTargetFunction().getCardinality(getArguments());
175 }
176
177 /**
178 * Compute the special properties of this expression. These properties are denoted by a bit-significant
179 * integer, possible values are in class {@link net.sf.saxon.expr.StaticProperty}. The "special" properties are properties
180 * other than cardinality and dependencies, and most of them relate to properties of node sequences, for
181 * example whether the nodes are in document order.
182 *
183 * @return the special properties, as a bit-significant integer
184 */
185 @Override
186 protected int computeSpecialProperties() {
187 return getTargetFunction().getSpecialProperties(getArguments());
188 }
189
190 /**
191 * Return the estimated cost of evaluating an expression. This is a very crude measure based
192 * on the syntactic form of the expression (we have no knowledge of data values). We take
193 * the cost of evaluating a simple scalar comparison or arithmetic expression as 1 (one),
194 * and we assume that a sequence has length 5. The resulting estimates may be used, for
195 * example, to reorder the predicates in a filter expression so cheaper predicates are
196 * evaluated first.
197 */
198 @Override
199 public int getNetCost() {
200 return getTargetFunction().getNetCost();
201 }
202
203 @Override
204 public Expression getScopingExpression() {
205 if (isCallOn(RegexGroup.class)) {
206 Expression parent = getParentExpression();
207 while (parent != null) {
208 if (parent instanceof AnalyzeString) {
209 return parent;
210 }
211 parent = parent.getParentExpression();
212 }
213 return null;
214 } else {
215 return super.getScopingExpression();
216 }
217 }
218
219 /**
220 * Ask whether the expression can be lifted out of a loop, assuming it has no dependencies
221 * on the controlling variable/focus of the loop
222 *
223 * @param forStreaming true if we are optimizing for streamed evaluation
224 */
225 @Override
226 public boolean isLiftable(boolean forStreaming) {
227 // xsl:map-entry is not liftable when streaming because of the special streamability
228 // rules for xsl:map; similarly XPath map constructor expressions.
229 // The tests for current-merge-group/key were added to fix bug 3652 - it seems
230 // an inelegant solution because it's being handled differently from other context
231 // dependencies, but it works.
232 return super.isLiftable(forStreaming) &&
233 !isCallOn(CurrentMergeGroup.class) && !isCallOn(CurrentMergeKey.class) &&
234 (!forStreaming || !isCallOn(MapFunctionSet.MapEntry.class));
235 }
236
237 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
238 Expression sf = super.optimize(visitor, contextInfo);
239 if (sf == this) {
240 // Give the function an opportunity to regenerate the function call, with more information about
241 // the types of the arguments than was previously available
242 Expression sfo = getTargetFunction().makeOptimizedFunctionCall(visitor, contextInfo, getArguments());
243 if (sfo != null) {
244 sfo.setParentExpression(getParentExpression());
245 ExpressionTool.copyLocationInfo(this, sfo);
246 if (sfo instanceof SystemFunctionCall) {
247 ((SystemFunctionCall) sfo).allocateArgumentEvaluators(((SystemFunctionCall) sfo).getArguments());
248 }
249 return sfo;
250 }
251 }
252 if (sf instanceof SystemFunctionCall) {
253 // If any arguments are known to be empty, pre-evaluate the result
254 BuiltInFunctionSet.Entry details = ((SystemFunctionCall) sf).getTargetFunction().getDetails();
255 if ((details.properties & BuiltInFunctionSet.UO) != 0) {
256 // First argument does not need to be in any particular order
257 setArg(0, getArg(0).unordered(true, visitor.isOptimizeForStreaming()));
258 }
259 if (getArity() <= details.resultIfEmpty.length) {
260 // the condition eliminates concat, which is a special case.
261 for (int i = 0; i < getArity(); i++) {
262 if (Literal.isEmptySequence(getArg(i)) && details.resultIfEmpty[i] != null) {
263 return Literal.makeLiteral(details.resultIfEmpty[i].materialize(), this);
264 }
265 }
266 }
267 ((SystemFunctionCall) sf).allocateArgumentEvaluators(((SystemFunctionCall) sf).getArguments());
268 }
269 return sf;
270 }
271
272 @Override
273 public boolean isVacuousExpression() {
274 return isCallOn(Error.class);
275 }
276
277 /**
278 * Determine the data type of the expression, if possible. All expression return
279 * sequences, in general; this method determines the type of the items within the
280 * sequence, assuming that (a) this is known in advance, and (b) it is the same for
281 * all items in the sequence.
282 * <p>This method should always return a result, though it may be the best approximation
283 * that is available at the time.</p>
284 *
285 * @return a value such as Type.STRING, Type.BOOLEAN, Type.NUMBER,
286 * Type.NODE, or Type.ITEM (meaning not known at compile time)
287 */
288 @Override
289 public ItemType getItemType() {
290 return getTargetFunction().getResultItemType(getArguments());
291 }
292
293 /**
294 * Copy an expression. This makes a deep copy.
295 * @param rebindings variables that need to be re-bound
296 * @return the copy of the original expression
297 */
298 @Override
299 public Expression copy(RebindingMap rebindings) {
300 Expression[] args = new Expression[getArity()];
301 for (int i = 0; i < args.length; i++) {
302 args[i] = getArg(i).copy(rebindings);
303 }
304 SystemFunction target = getTargetFunction();
305 if (target instanceof StatefulSystemFunction) {
306 target = ((StatefulSystemFunction) target).copy();
307 }
308 return target.makeFunctionCall(args);
309 }
310 /**
311 * For an expression that returns an integer or a sequence of integers, get
312 * a lower and upper bound on the values of the integers that may be returned, from
313 * static analysis. The default implementation returns null, meaning "unknown" or
314 * "not applicable". Other implementations return an array of two IntegerValue objects,
315 * representing the lower and upper bounds respectively. The values
316 * UNBOUNDED_LOWER and UNBOUNDED_UPPER are used by convention to indicate that
317 * the value may be arbitrarily large. The values MAX_STRING_LENGTH and MAX_SEQUENCE_LENGTH
318 * are used to indicate values limited by the size of a string or the size of a sequence.
319 *
320 * @return the lower and upper bounds of integer values in the result, or null to indicate
321 * unknown or not applicable.
322 */
323 //@Override
324 public IntegerValue[] getIntegerBounds() {
325 SystemFunction fn = getTargetFunction();
326 if ((fn.getDetails().properties & BuiltInFunctionSet.FILTER) != 0) {
327 return getArg(0).getIntegerBounds();
328 }
329 return fn.getIntegerBounds();
330 }
331
332 /**
333 * Check whether this specific instance of the expression is negatable
334 *
335 * @param th the TypeHierarchy (in case it's needed)
336 * @return true if it is
337 */
338 public boolean isNegatable(TypeHierarchy th) {
339 return isCallOn(NotFn.class) || isCallOn(BooleanFn.class) || isCallOn(Empty.class) || isCallOn(Exists.class);
340 }
341
342 /**
343 * Create an expression that returns the negation of this expression
344 *
345 * @return the negated expression
346 * @throws UnsupportedOperationException if isNegatable() returns false
347 */
348 public Expression negate() {
349 SystemFunction fn = getTargetFunction();
350 if (fn instanceof NotFn) {
351 Expression arg = getArg(0);
352 if (arg.getItemType() == BuiltInAtomicType.BOOLEAN && arg.getCardinality() == StaticProperty.EXACTLY_ONE) {
353 return arg;
354 } else {
355 return SystemFunction.makeCall("boolean", getRetainedStaticContext(), arg);
356 }
357 } else if (fn instanceof BooleanFn) {
358 return SystemFunction.makeCall("not", getRetainedStaticContext(), getArg(0));
359 } else if (fn instanceof Exists) {
360 return SystemFunction.makeCall("empty", getRetainedStaticContext(), getArg(0));
361 } else if (fn instanceof Empty) {
362 return SystemFunction.makeCall("exists", getRetainedStaticContext(), getArg(0));
363 }
364 throw new UnsupportedOperationException();
365 }
366
367 /**
368 * Replace this expression by a simpler expression that delivers the results without regard
369 * to order.
370 *
371 * @param retainAllNodes set to true if the result must contain exactly the same nodes as the
372 * original; set to false if the result can eliminate (or introduce) duplicates.
373 * @param forStreaming set to true if the result is to be optimized for streaming
374 * @return an expression that delivers the same nodes in a more convenient order
375 * @throws net.sf.saxon.trans.XPathException if the rewrite fails
376 */
377 @Override
378 public Expression unordered(boolean retainAllNodes, boolean forStreaming) throws XPathException {
379 SystemFunction fn = getTargetFunction();
380 if (fn instanceof Reverse) {
381 return getArg(0);
382 }
383 if (fn instanceof TreatFn) {
384 setArg(0, getArg(0).unordered(retainAllNodes, forStreaming));
385 }
386 return this;
387 }
388
389 /**
390 * Add a representation of this expression to a PathMap. The PathMap captures a map of the nodes visited
391 * by an expression in a source tree.
392 * <p>The default implementation of this method assumes that an expression does no navigation other than
393 * the navigation done by evaluating its subexpressions, and that the subexpressions are evaluated in the
394 * same context as the containing expression. The method must be overridden for any expression
395 * where these assumptions do not hold. For example, implementations exist for AxisExpression, ParentExpression,
396 * and RootExpression (because they perform navigation), and for the doc(), document(), and collection()
397 * functions because they create a new navigation root. Implementations also exist for PathExpression and
398 * FilterExpression because they have subexpressions that are evaluated in a different context from the
399 * calling expression.</p>
400 *
401 * @param pathMap the PathMap to which the expression should be added
402 * @param pathMapNodeSet the PathMapNodeSet to which the paths embodied in this expression should be added
403 * @return the pathMapNodeSet representing the points in the source document that are both reachable by this
404 * expression, and that represent possible results of this expression. For an expression that does
405 * navigation, it represents the end of the arc in the path map that describes the navigation route. For other
406 * expressions, it is the same as the input pathMapNode.
407 */
408 @Override
409 public PathMap.PathMapNodeSet addToPathMap(PathMap pathMap, PathMap.PathMapNodeSet pathMapNodeSet) {
410 if (isCallOn(Doc.class) || isCallOn(DocumentFn.class) || isCallOn(CollectionFn.class)) {
411 getArg(0).addToPathMap(pathMap, pathMapNodeSet);
412 return new PathMap.PathMapNodeSet(pathMap.makeNewRoot(this));
413 } else if (isCallOn(KeyFn.class)) {
414 return ((KeyFn) getTargetFunction()).addToPathMap(pathMap, pathMapNodeSet);
415 } else {
416 return super.addToPathMap(pathMap, pathMapNodeSet);
417 }
418 }
419
420 /**
421 * Convert this expression to an equivalent XSLT pattern
422 *
423 * @param config the Saxon configuration
424 * @return the equivalent pattern
425 * @throws net.sf.saxon.trans.XPathException if conversion is not possible
426 */
427 @Override
428 public Pattern toPattern(Configuration config) throws XPathException {
429 SystemFunction fn = getTargetFunction();
430 if (fn instanceof Root_1) {
431 if (getArg(0) instanceof ContextItemExpression ||
432 (getArg(0) instanceof ItemChecker &&
433 ((ItemChecker) getArg(0)).getBaseExpression() instanceof ContextItemExpression)) {
434 return new NodeSetPattern(this);
435 }
436 }
437 return super.toPattern(config);
438 }
439
440 public Sequence[] evaluateArguments(XPathContext context) throws XPathException {
441 OperandArray operanda = getOperanda();
442 int numArgs = operanda.getNumberOfOperands();
443 Sequence[] actualArgs = new Sequence[numArgs];
444 for (int i = 0; i < numArgs; i++) {
445 Expression exp = operanda.getOperandExpression(i);
446 actualArgs[i] = argumentEvaluators[i].evaluate(exp, context);
447 }
448 return actualArgs;
449 }
450
451 @Override
452 public void resetLocalStaticProperties() {
453 super.resetLocalStaticProperties();
454 if (argumentEvaluators != null) {
455 allocateArgumentEvaluators(getArguments());
456 }
457 }
458
459 /**
460 * Get a name identifying the kind of expression, in terms meaningful to a user.
461 *
462 * @return a name identifying the kind of expression, in terms meaningful to a user.
463 * The name will always be in the form of a lexical XML QName, and should match the name used
464 * in explain() output displaying the expression.
465 */
466 @Override
467 public String getExpressionName() {
468 return "sysFuncCall";
469 }
470
471 /**
472 * Diagnostic print of expression structure. The abstract expression tree
473 * is written to the supplied output destination.
474 *
475 * @param out the destination of the output
476 */
477 @Override
478 public void export(ExpressionPresenter out) throws XPathException {
479 if (getFunctionName().hasURI(NamespaceConstant.FN)) {
480 out.startElement("fn", this);
481 out.emitAttribute("name", getFunctionName().getLocalPart());
482 getTargetFunction().exportAttributes(out);
483 for (Operand o : operands()) {
484 o.getChildExpression().export(out);
485 }
486 getTargetFunction().exportAdditionalArguments(this, out);
487 out.endElement();
488 } else {
489 // Function was implemented as an IntegratedFunctionCall in 9.7 and we retain the same export format
490 out.startElement("ifCall", this);
491 out.emitAttribute("name", getFunctionName());
492 out.emitAttribute("type", getTargetFunction().getFunctionItemType().getResultType().toExportString());
493 ExpressionPresenter.ExportOptions options = (ExpressionPresenter.ExportOptions) out.getOptions();
494 if (options.target != null && options.target.equals("JS") && options.targetVersion == 2) {
495 out.emitAttribute("typeJ", getTargetFunction().getFunctionItemType().getResultType().toExportString2());
496 }
497 getTargetFunction().exportAttributes(out);
498 for (Operand o : operands()) {
499 o.getChildExpression().export(out);
500 }
501 getTargetFunction().exportAdditionalArguments(this, out);
502 out.endElement();
503 }
504 }
505
506 /**
507 * Subclass representing a system function call that has been optimized; this overrides the
508 * optimize() method to do nothing, thus ensuring that optimization converges.
509 */
510
511 public abstract static class Optimized extends SystemFunctionCall {
512
513 public Optimized(SystemFunction target, Expression[] arguments) {
514 super(target, arguments);
515 }
516 @Override
517 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
518 return this; // prevent infinite optimization
519 }
520 }
521
522
523 }