Debian Codegraph @

net/sf/saxon/expr/FunctionCall.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.expr.oper.OperandArray;
11 import net.sf.saxon.expr.parser.*;
12 import net.sf.saxon.lib.NamespaceConstant;
13 import net.sf.saxon.om.*;
14 import net.sf.saxon.trace.ExpressionPresenter;
15 import net.sf.saxon.trans.NoDynamicContextException;
16 import net.sf.saxon.trans.XPathException;
17 import net.sf.saxon.tree.util.FastStringBuffer;
18 import net.sf.saxon.type.JavaExternalObjectType;
19 import net.sf.saxon.value.SequenceType;
20
21 import java.util.Collections;
22
23 /**
24 * Abstract superclass for calls to system-defined and user-defined functions
25 */
26
27 public abstract class FunctionCall extends Expression {
28
29 private OperandArray operanda;
30
31 /**
32 * Set the data structure for the operands of this expression. This must be created during initialisation of the
33 * expression and must not be subsequently changed
34 *
35 * @param operanda the data structure for expression operands
36 */
37
38 protected void setOperanda(OperandArray operanda) {
39 this.operanda = operanda;
40 }
41
42 /**
43 * Get the data structure holding the operands of this expression.
44 *
45 * @return the data structure holding expression operands
46 */
47
48 public OperandArray getOperanda() {
49 return operanda;
50 }
51
52 @Override
53 public Iterable<Operand> operands() {
54 if (operanda != null) {
55 return operanda.operands();
56 } else {
57 // happens during expression tree construction
58 return Collections.emptyList();
59 }
60 }
61
62 /**
63 * Get the target function to be called
64 * @param context the dynamic evaluation context
65 * @return the target function
66 * @throws XPathException if the target function cannot be determined
67 */
68
69 public abstract Function getTargetFunction(XPathContext context) throws XPathException;
70
71 /**
72 * Get the qualified of the function being called
73 *
74 * @return the qualified name. May be null if the function is anonymous.
75 */
76
77 public abstract StructuredQName getFunctionName();
78
79 /**
80 * Determine the number of actual arguments supplied in the function call
81 *
82 * @return the arity (the number of arguments)
83 */
84
85 public final int getArity() {
86 return getOperanda().getNumberOfOperands();
87 }
88
89 /**
90 * Method called by the expression parser when all arguments have been supplied
91 *
92 * @param args the expressions contained in the argument list of the function call
93 */
94
95 public void setArguments(Expression[] args) {
96 setOperanda(new OperandArray(this, args));
97 }
98
99 protected void setOperanda(Expression[] args, OperandRole roles[]) {
100 setOperanda(new OperandArray(this, args, roles));
101 }
102
103 /**
104 * Get the expressions supplied as actual arguments to the function
105 *
106 * @return the array of expressions supplied in the argument list of the function call. The array
107 * is newly constructed to ensure that modifications to the array have no effect.
108 */
109
110 public Expression[] getArguments() {
111 Expression[] result = new Expression[getArity()];
112 int i=0;
113 for (Operand o : operands()) {
114 result[i++] = o.getChildExpression();
115 }
116 return result;
117 }
118
119 /**
120 * Get the expression supplied as the Nth argument
121 * @param n the required argument, zero-based
122 * @return the expression supplied in the relevant position
123 * @throws java.lang.IllegalArgumentException if the value of n is out of range
124 */
125
126 public Expression getArg(int n) {
127 return getOperanda().getOperandExpression(n);
128 }
129
130 /**
131 * Set the expression to be used as the Nth argument
132 * @param n the required argument, zero-based
133 * @param child the expression to be used in the relevant position
134 * @throws java.lang.IllegalArgumentException if the value of n is out of range
135 */
136
137 public void setArg(int n, Expression child) {
138 getOperanda().setOperand(n, child);
139 adoptChildExpression(child);
140 }
141 /**
142 * Simplify the arguments of the function.
143 * Called from the simplify() method of each function.
144 *
145 * @param env the static context
146 * @return the result of simplifying the arguments of the expression
147 * @throws net.sf.saxon.trans.XPathException if an error occurs
148 */
149
150 protected final Expression simplifyArguments(StaticContext env) throws XPathException {
151 for (int i = 0; i < getArguments().length; i++) {
152 Expression exp = getArg(i).simplify();
153 if (exp != getArg(i)) {
154 adoptChildExpression(exp);
155 setArg(i, exp);
156 }
157 }
158 return this;
159 }
160
161 /**
162 * Type-check the expression. This also calls preEvaluate() to evaluate the function
163 * if all the arguments are constant; functions that do not require this behavior
164 * can override the preEvaluate method.
165 */
166
167 /*@NotNull*/
168 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
169 typeCheckChildren(visitor, contextInfo);
170 checkArguments(visitor);
171 return preEvaluateIfConstant(visitor);
172 }
173
174 protected Expression preEvaluateIfConstant(ExpressionVisitor visitor) throws XPathException {
175 boolean fixed = true;
176 for (Operand o : operands()) {
177 if (!(o.getChildExpression() instanceof Literal)) {
178 fixed = false;
179 }
180 }
181 if (fixed) {
182 try {
183 return preEvaluate(visitor);
184 } catch (NoDynamicContextException err) {
185 // Early evaluation failed, typically because the implicit timezone is not yet known.
186 // Try again later at run-time.
187 return this;
188 }
189 } else {
190 return this;
191 }
192 }
193
194 /**
195 * Check the function call against the declared function signature, applying the
196 * function conversion rules to each argument as necessary
197 *
198 * @param target the function being called
199 * @param visitor an expression visitor
200 * @throws XPathException if there is a type error
201 */
202
203 public void checkFunctionCall(Function target,
204 ExpressionVisitor visitor) throws XPathException {
205 TypeChecker tc = visitor.getConfiguration().getTypeChecker(visitor.getStaticContext().isInBackwardsCompatibleMode());
206 SequenceType[] argTypes = target.getFunctionItemType().getArgumentTypes();
207 int n = target.getArity();
208 for (int i = 0; i < n; i++) {
209 String name = getFunctionName() == null ? "" : getFunctionName().getDisplayName();
210 RoleDiagnostic role = new RoleDiagnostic(RoleDiagnostic.FUNCTION, name, i);
211 setArg(i, tc.staticTypeCheck(
212 getArg(i),
213 argTypes[i],
214 role, visitor));
215 }
216 }
217
218
219 /**
220 * Perform optimisation of an expression and its subexpressions.
221 * <p>This method is called after all references to functions and variables have been resolved
222 * to the declaration of the function or variable, and after all type checking has been done.</p>
223 *
224 * @param visitor an expression visitor
225 * @param contextItemType the static type of "." at the point where this expression is invoked.
226 * The parameter is set to null if it is known statically that the context item will be undefined.
227 * If the type of the context item is not known statically, the argument is set to
228 * {@link net.sf.saxon.type.Type#ITEM_TYPE}
229 * @return the original expression, rewritten if appropriate to optimize execution
230 * @throws XPathException if an error is discovered during this phase
231 * (typically a type error)
232 */
233
234 /*@NotNull*/
235 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType) throws XPathException {
236 optimizeChildren(visitor, contextItemType);
237
238 boolean fixed = true;
239 for (Operand o : operands()) {
240 if (!(o.getChildExpression() instanceof Literal)) {
241 fixed = false;
242 break;
243 }
244 }
245
246 return fixed ? preEvaluate(visitor) : this;
247 }
248
249 /**
250 * Return the estimated cost of evaluating an expression. This is a very crude measure based
251 * on the syntactic form of the expression (we have no knowledge of data values). We take
252 * the cost of evaluating a simple scalar comparison or arithmetic expression as 1 (one),
253 * and we assume that a sequence has length 5. The resulting estimates may be used, for
254 * example, to reorder the predicates in a filter expression so cheaper predicates are
255 * evaluated first.
256 */
257 @Override
258 public int getNetCost() {
259 return 5;
260 }
261
262 /**
263 * Pre-evaluate a function at compile time. Functions that do not allow
264 * pre-evaluation, or that need access to context information, can override this method.
265 *
266 * @param visitor an expression visitor
267 * @return the result of the early evaluation, or the original expression, or potentially
268 * a simplified expression
269 * @throws net.sf.saxon.trans.XPathException if evaluation fails
270 */
271
272 public Expression preEvaluate(ExpressionVisitor visitor) throws XPathException {
273 if ((getIntrinsicDependencies() & ~StaticProperty.DEPENDS_ON_STATIC_CONTEXT) != 0) {
274 return this;
275 }
276 try {
277 Literal lit = Literal.makeLiteral(iterate(visitor.getStaticContext().makeEarlyEvaluationContext()).materialize(), this);
278 Optimizer.trace(visitor.getConfiguration(), "Pre-evaluated function call " + toShortString(), lit);
279 return lit;
280 } catch (NoDynamicContextException e) {
281 // early evaluation failed, usually because implicit timezone required
282 return this;
283 } catch (UnsupportedOperationException e) {
284 //e.printStackTrace();
285 if (e.getCause() instanceof NoDynamicContextException) {
286 return this;
287 } else {
288 throw e;
289 }
290 }
291 }
292
293 /**
294 * Method supplied by each class of function to check arguments during parsing, when all
295 * the argument expressions have been read
296 *
297 * @param visitor the expression visitor
298 * @throws net.sf.saxon.trans.XPathException if the arguments are incorrect
299 */
300
301 protected void checkArguments(ExpressionVisitor visitor) throws XPathException {
302 // default: do nothing
303 }
304
305 /**
306 * Check number of arguments. <BR>
307 * A convenience routine for use in subclasses.
308 *
309 * @param min the minimum number of arguments allowed
310 * @param max the maximum number of arguments allowed
311 * @return the actual number of arguments
312 * @throws net.sf.saxon.trans.XPathException if the number of arguments is out of range
313 */
314
315 protected int checkArgumentCount(int min, int max) throws XPathException {
316 int numArgs = getArity();
317 String msg = null;
318 if (min == max && numArgs != min) {
319 msg = "Function " + getDisplayName() + " must have " + pluralArguments(min);
320 } else if (numArgs < min) {
321 msg = "Function " + getDisplayName() + " must have at least " + pluralArguments(min);
322 } else if (numArgs > max) {
323 msg = "Function " + getDisplayName() + " must have no more than " + pluralArguments(max);
324 }
325 if (msg != null) {
326 XPathException err = new XPathException(msg, "XPST0017");
327 err.setIsStaticError(true);
328 err.setLocation(getLocation());
329 throw err;
330 }
331 return numArgs;
332 }
333
334 /**
335 * An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process().
336 * This method indicates which of these methods is provided directly. The other methods will always be available
337 * indirectly, using an implementation that relies on one of the other methods.
338 *
339 * @return the implementation method, for example {@link #ITERATE_METHOD} or {@link #EVALUATE_METHOD} or
340 * {@link #PROCESS_METHOD}
341 */
342 @Override
343 public int getImplementationMethod() {
344 return ITERATE_METHOD;
345 }
346
347 /**
348 * Utility routine used in constructing error messages: get the word "argument" or "arguments"
349 *
350 * @param num the number of arguments
351 * @return the singular or plural word
352 */
353
354 public static String pluralArguments(int num) {
355 return num == 1 ? "one argument" : (num + " arguments");
356 }
357
358
359 /**
360 * Add a representation of this expression to a PathMap. The PathMap captures a map of the nodes visited
361 * by an expression in a source tree.
362 * <p>The default implementation of this method assumes that an expression does no navigation other than
363 * the navigation done by evaluating its subexpressions, and that the subexpressions are evaluated in the
364 * same context as the containing expression. The method must be overridden for any expression
365 * where these assumptions do not hold. For example, implementations exist for AxisExpression, ParentExpression,
366 * and RootExpression (because they perform navigation), and for the doc(), document(), and collection()
367 * functions because they create a new navigation root. Implementations also exist for PathExpression and
368 * FilterExpression because they have subexpressions that are evaluated in a different context from the
369 * calling expression.</p>
370 *
371 * @param pathMap the PathMap to which the expression should be added
372 * @param pathMapNodes the node in the PathMap representing the focus at the point where this expression
373 * is called. Set to null if this expression appears at the top level, in which case the expression, if it
374 * is registered in the path map at all, must create a new path map root.
375 * @return the pathMapNode representing the focus established by this expression, in the case where this
376 * expression is the first operand of a path expression or filter expression. For an expression that does
377 * navigation, it represents the end of the arc in the path map that describes the navigation route. For other
378 * expressions, it is the same as the input pathMapNode.
379 */
380
381 public PathMap.PathMapNodeSet addExternalFunctionCallToPathMap(PathMap pathMap, PathMap.PathMapNodeSet pathMapNodes) {
382 // Except in the case of system functions, we have no idea where a function call might
383 // navigate, so we assume the worst, and register that the path has unknown dependencies
384 PathMap.PathMapNodeSet result = new PathMap.PathMapNodeSet();
385 for (Operand o : operands()) {
386 result.addNodeSet(o.getChildExpression().addToPathMap(pathMap, pathMapNodes));
387 }
388 result.setHasUnknownDependencies();
389 return result;
390 }
391
392 /**
393 * Get a name identifying the kind of expression, in terms meaningful to a user.
394 *
395 * @return a name identifying the kind of expression, in terms meaningful to a user.
396 * The name will always be in the form of a lexical XML QName, and should match the name used
397 * in explain() output displaying the expression.
398 */
399
400 public String getExpressionName() {
401 return "functionCall";
402 }
403
404 /**
405 * Get the name of the function for display in messages
406 *
407 * @return the name of the function as a lexical QName
408 */
409
410 public final String getDisplayName() {
411 StructuredQName fName = getFunctionName();
412 return fName == null ? "(anonymous)" : fName.getDisplayName();
413 }
414
415 /**
416 * The toString() method for an expression attempts to give a representation of the expression
417 * in an XPath-like form, but there is no guarantee that the syntax will actually be true XPath.
418 * In the case of XSLT instructions, the toString() method gives an abstracted view of the syntax
419 */
420
421 public String toString() {
422 FastStringBuffer buff = new FastStringBuffer(FastStringBuffer.C64);
423 StructuredQName fName = getFunctionName();
424 String f;
425 if (fName == null) {
426 f = "$anonymousFunction";
427 } else if (fName.hasURI(NamespaceConstant.FN)) {
428 f = fName.getLocalPart();
429 } else {
430 f = fName.getEQName();
431 }
432 buff.append(f);
433 boolean first = true;
434 for (Operand o : operands()) {
435 buff.append(first ? "(" : ", ");
436 buff.append(o.getChildExpression().toString());
437 first = false;
438 }
439 buff.append(first ? "()" : ")");
440 return buff.toString();
441 }
442
443 /**
444 * Produce a short string identifying the expression for use in error messages
445 *
446 * @return a short string, sufficient to identify the expression
447 */
448 @Override
449 public String toShortString() {
450 StructuredQName fName = getFunctionName();
451 return (fName == null ? "$anonFn" : fName.getDisplayName()) +
452 "(" + (getArity() == 0 ? "" : "...") + ")";
453 }
454
455 /**
456 * Diagnostic print of expression structure. The abstract expression tree
457 * is written to the supplied output destination.
458 */
459
460 public void export(ExpressionPresenter out) throws XPathException {
461 out.startElement("functionCall", this);
462 if (getFunctionName() == null) {
463 throw new AssertionError("Exporting call to anonymous function");
464 } else {
465 out.emitAttribute("name", getFunctionName().getDisplayName());
466 }
467 for (Operand o : operands()) {
468 o.getChildExpression().export(out);
469 }
470 out.endElement();
471 }
472
473 /**
474 * Determine whether two expressions are equivalent
475 */
476
477 public boolean equals(Object o) {
478 if (!(o instanceof FunctionCall)) {
479 return false;
480 }
481 if (getFunctionName() == null) {
482 return this == o;
483 }
484 FunctionCall f = (FunctionCall) o;
485 if (!getFunctionName().equals(f.getFunctionName())) {
486 return false;
487 }
488 if (getArity() != f.getArity()) {
489 return false;
490 }
491 for (int i = 0; i < getArity(); i++) {
492 if (!getArg(i).isEqual(f.getArg(i))) {
493 return false;
494 }
495 }
496 return true;
497 }
498
499 /**
500 * Get hashCode in support of equals() method
501 */
502
503 public int computeHashCode() {
504 if (getFunctionName() == null) {
505 return super.computeHashCode();
506 }
507 int h = getFunctionName().hashCode();
508 for (int i = 0; i < getArity(); i++) {
509 h ^= getArg(i).hashCode();
510 }
511 return h;
512 }
513
514 /**
515 * Return an Iterator to iterate over the values of a sequence. The value of every
516 * expression can be regarded as a sequence, so this method is supported for all
517 * expressions. This default implementation handles iteration for expressions that
518 * return singleton values: for non-singleton expressions, the subclass must
519 * provide its own implementation.
520 *
521 * @param context supplies the context for evaluation
522 * @return a SequenceIterator that can be used to iterate over the result
523 * of the expression
524 * @throws net.sf.saxon.trans.XPathException if any dynamic error occurs evaluating the
525 * expression
526 */
527 @Override
528 public SequenceIterator<?> iterate(XPathContext context) throws XPathException {
529 Function target = getTargetFunction(context);
530 Sequence[] actualArgs = evaluateArguments(context);
531 try {
532 return target.call(context, actualArgs).iterate();
533 } catch (XPathException e) {
534 e.maybeSetLocation(getLocation());
535 e.maybeSetContext(context);
536 e.maybeSetFailingExpression(this);
537 throw e;
538 }
539 }
540
541 public Sequence[] evaluateArguments(XPathContext context) throws XPathException {
542 int numArgs = getArity();
543 Sequence[] actualArgs = new Sequence[numArgs];
544 for (int i = 0; i < numArgs; i++) {
545 actualArgs[i] = ExpressionTool.lazyEvaluate(getArg(i), context, false);
546 }
547 return actualArgs;
548 }
549
550 /**
551 * When a call to a Java extension function appears in a context where there the required type
552 * is a Java external object (typically an xsl:variable with a declared type, or as an argument
553 * to another Java extension function), notify this required type so that the process of converting
554 * the result to an XDM value can be short-circuited.
555 * @param requiredType the required type of the result of the function, determined by the context
556 * in which the function call appears
557 * @throws XPathException if the required return type is incompatible with the type actually returned
558 * by the Java method
559 * @return Ok if the type has been successfully adjusted
560 */
561
562 public boolean adjustRequiredType(JavaExternalObjectType requiredType) throws XPathException {
563 return false;
564 }
565
566 }
567