Debian Codegraph @

net/sf/saxon/expr/UserFunctionCall.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.instruct.Block;
11 import net.sf.saxon.expr.instruct.UserFunction;
12 import net.sf.saxon.expr.parser.*;
13 import net.sf.saxon.om.*;
14 import net.sf.saxon.trace.ExpressionPresenter;
15 import net.sf.saxon.trace.LocationKind;
16 import net.sf.saxon.trans.*;
17 import net.sf.saxon.tree.util.FastStringBuffer;
18 import net.sf.saxon.type.AnyItemType;
19 import net.sf.saxon.type.ItemType;
20 import net.sf.saxon.type.UType;
21 import net.sf.saxon.value.Cardinality;
22 import net.sf.saxon.value.EmptySequence;
23 import net.sf.saxon.value.SequenceType;
24 import net.sf.saxon.value.Whitespace;
25
26 import java.util.ArrayList;
27 import java.util.List;
28
29
30 /**
31 * This class represents a call to a user-defined function in the stylesheet or query.
32 */
33
34 public class UserFunctionCall extends FunctionCall implements UserFunctionResolvable, ComponentInvocation, ContextOriginator {
35
36 private SequenceType staticType;
37 private UserFunction function;
38 private int bindingSlot = -1;
39 private int tailCall = NOT_TAIL_CALL;
40 private StructuredQName name;
41
42 public boolean isBeingInlined() {
43 return beingInlined;
44 }
45
46 public void setBeingInlined(boolean beingInlined) {
47 this.beingInlined = beingInlined;
48 }
49
50 private boolean beingInlined = false;
51
52
53 /*@Nullable*/ private Evaluator[] argumentEvaluators = null;
54
55 public static final int NOT_TAIL_CALL = 0;
56 public static final int FOREIGN_TAIL_CALL = 1;
57 public static final int SELF_TAIL_CALL = 2;
58
59 /**
60 * Create a function call to a user-written function in a query or stylesheet
61 */
62
63 public UserFunctionCall() {
64 }
65
66
67 /**
68 * Set the name of the function being called
69 *
70 * @param name the name of the function
71 */
72
73 public final void setFunctionName(StructuredQName name) {
74 this.name = name;
75 }
76
77
78 /**
79 * Set the static type
80 *
81 * @param type the static type of the result of the function call
82 */
83
84 public void setStaticType(SequenceType type) {
85 staticType = type;
86 }
87
88 /**
89 * Create the reference to the function to be called
90 *
91 * @param compiledFunction the function being called
92 */
93
94 public void setFunction(UserFunction compiledFunction) {
95 function = compiledFunction;
96 }
97
98 /**
99 * Set the binding slot to be used. This is the offset within the binding vector of the containing
100 * component where the actual target template is to be found. The target function is not held directly
101 * in the UserFunctionCall expression itself because it can be overridden in a using package.
102 *
103 * @param slot the offset in the binding vector of the containing package where the target template
104 * can be found.
105 */
106
107
108 public void setBindingSlot(int slot) {
109 this.bindingSlot = slot;
110 }
111
112 /**
113 * Get the binding slot to be used. This is the offset within the binding vector of the containing
114 * component where the actual target template is to be found.
115 *
116 * @return the offset in the binding vector of the containing package where the target template
117 * can be found.
118 */
119
120 public int getBindingSlot() {
121 return bindingSlot;
122 }
123
124
125 /**
126 * Get the function that is being called by this function call. This is the provisional
127 * binding: the actual function might be an override of this one.
128 *
129 * @return the function being called
130 */
131
132 public UserFunction getFunction() {
133 return function;
134 }
135
136 public Component getFixedTarget() {
137 Visibility v = function.getDeclaringComponent().getVisibility();
138 if (v == Visibility.PRIVATE || v == Visibility.FINAL) {
139 return function.getDeclaringComponent();
140 } else {
141 return null;
142 }
143 }
144
145 /**
146 * Determine whether this is a tail call (not necessarily a recursive tail call)
147 *
148 * @return true if this function call is a tail call
149 */
150
151 public boolean isTailCall() {
152 return tailCall != NOT_TAIL_CALL;
153 }
154
155 public boolean isRecursiveTailCall() {
156 return tailCall == SELF_TAIL_CALL;
157 }
158
159 /**
160 * Get the qualified of the function being called
161 *
162 * @return the qualified name
163 */
164
165 public final StructuredQName getFunctionName() {
166 if (name == null) {
167 return function.getFunctionName();
168 } else {
169 return name;
170 }
171 }
172
173 public SymbolicName getSymbolicName() {
174 return new SymbolicName.F(getFunctionName(), getArity());
175 }
176
177 public Component getTarget() {
178 return function.getDeclaringComponent();
179 }
180
181 /**
182 * Set the argument evaluation modes
183 *
184 * @param evalModes the argument evaluation modes to be used
185 */
186
187 public void setArgumentEvaluationModes(int[] evalModes) {
188 argumentEvaluators = new Evaluator[evalModes.length];
189 for (int i=0; i<evalModes.length; i++) {
190 argumentEvaluators[i] = Evaluator.evaluatorForCode(evalModes[i]);
191 }
192 }
193
194
195 private static final int UNHANDLED_DEPENDENCIES =
196 StaticProperty.DEPENDS_ON_POSITION | StaticProperty.DEPENDS_ON_LAST |
197 StaticProperty.DEPENDS_ON_XSLT_CONTEXT | StaticProperty.DEPENDS_ON_USER_FUNCTIONS;
198
199 public void allocateArgumentEvaluators() {
200 argumentEvaluators = new Evaluator[getArity()];
201 int i=0;
202 for (Operand o : operands()) {
203 Expression arg = o.getChildExpression();
204 SequenceType required = function.getArgumentType(i);
205 int cardinality = required.getCardinality();
206
207 if (i == 0 && function.getDeclaredStreamability().isConsuming()) {
208 argumentEvaluators[i] = Evaluator.STREAMING_ARGUMENT;
209 } else if (function.getParameterDefinitions()[i].isIndexedVariable()) {
210 argumentEvaluators[i] = Evaluator.MAKE_INDEXED_VARIABLE;
211 } else {
212 if (arg instanceof Literal) {
213 argumentEvaluators[i] = Evaluator.LITERAL;
214 } else if (arg instanceof VariableReference) {
215 argumentEvaluators[i] = Evaluator.VARIABLE;
216 } else if (cardinality == StaticProperty.EXACTLY_ONE) {
217 argumentEvaluators[i] = Evaluator.SINGLE_ITEM;
218 } else if ((arg.getDependencies() & UNHANDLED_DEPENDENCIES) != 0) {
219 // If the argument contains a call to a user-defined function, then it might be a recursive call.
220 // It's better to evaluate it now, rather than waiting until we are on a new stack frame, as
221 // that can blow the stack if done repeatedly. (See test func42)
222 // If the argument contains calls to position(), last(), regex-group(), current-group(),
223 // current-merge-group(), etc, then in general we can't save the values in a Closure
224 // so we need to evaluate the argument eagerly. (Tests position-0103, merge-096).
225 argumentEvaluators[i] = Evaluator.EAGER_SEQUENCE;
226 } else if (!Cardinality.allowsMany(arg.getCardinality()) && arg.getCost() < 20) {
227 // the argument is cheap to evaluate and doesn't use much memory...
228 argumentEvaluators[i] = Evaluator.EAGER_SEQUENCE;
229 } else if (cardinality == StaticProperty.ALLOWS_ZERO_OR_ONE) {
230 argumentEvaluators[i] = Evaluator.OPTIONAL_ITEM;
231 } else if (arg instanceof Block && ((Block) arg).isCandidateForSharedAppend()) {
232 // If the expression is a Block, that is, it is appending a value to a sequence,
233 // then we have the opportunity to use a shared list underpinning the old value and
234 // the new. This takes precedence over lazy evaluation (it would be possible to do this
235 // lazily, but more difficult). We currently do this for any Block that has a variable
236 // reference as one of its subexpressions. The most common case is that the first argument is a reference
237 // to an argument of recursive function, where the recursive function returns the result of
238 // appending to the sequence.
239 argumentEvaluators[i] = Evaluator.SHARED_APPEND;
240 } else {
241 argumentEvaluators[i] = Evaluator.MEMO_CLOSURE;
242 }
243 }
244 i++;
245 }
246 }
247
248 public Evaluator[] getArgumentEvaluators() {
249 return argumentEvaluators;
250 }
251
252
253 /**
254 * Pre-evaluate a function at compile time. This version of the method suppresses
255 * early evaluation by doing nothing.
256 *
257 * @param visitor an expression visitor
258 */
259
260 public Expression preEvaluate(ExpressionVisitor visitor) {
261 return this;
262 }
263
264 /**
265 * Determine the data type of the expression, if possible
266 *
267 * @return Type.ITEM (meaning not known in advance)
268 */
269
270 /*@NotNull*/
271 public ItemType getItemType() {
272 if (staticType == null) {
273 // the actual type is not known yet, so we return an approximation
274 return AnyItemType.getInstance();
275 } else {
276 return staticType.getPrimaryType();
277 }
278 }
279
280 /**
281 * Get the static type of the expression as a UType, following precisely the type
282 * inference rules defined in the XSLT 3.0 specification.
283 *
284 * @param contextItemType the static type of the context item
285 * @return the static item type of the expression according to the XSLT 3.0 defined rules
286 */
287 @Override
288 public UType getStaticUType(UType contextItemType) {
289 UserFunction f = getFunction();
290 if (f == null) {
291 // Happens when called during parsing
292 return UType.ANY;
293 }
294 return f.getResultType().getPrimaryType().getUType();
295 }
296
297 public int getIntrinsicDependencies() {
298 return StaticProperty.DEPENDS_ON_USER_FUNCTIONS;
299 }
300
301 /**
302 * Determine whether this is an updating expression as defined in the XQuery update specification
303 *
304 * @return true if this is an updating expression
305 */
306
307 public boolean isUpdatingExpression() {
308 return function.isUpdating();
309 }
310
311 /**
312 * Compute the special properties of this expression. These properties are denoted by a bit-significant
313 * integer, possible values are in class {@link net.sf.saxon.expr.StaticProperty}. The "special" properties are properties
314 * other than cardinality and dependencies, and most of them relate to properties of node sequences, for
315 * example whether the nodes are in document order.
316 *
317 * @return the special properties, as a bit-significant integer
318 */
319
320 protected int computeSpecialProperties() {
321 // Inherit the properties of the function being called if possible. But we have to prevent
322 // looping when the function is recursive. For safety, we only consider the properties of the
323 // function body if it contains no further function calls. Also, we can only do this safely if
324 // the function is private or final
325 if (function == null) {
326 return super.computeSpecialProperties();
327 } else if (function.getBody() != null &&
328 (function.getDeclaredVisibility() == Visibility.PRIVATE || function.getDeclaredVisibility() == Visibility.FINAL)) {
329 int props;
330 List<UserFunction> calledFunctions = new ArrayList<>();
331 ExpressionTool.gatherCalledFunctions(function.getBody(), calledFunctions);
332 if (calledFunctions.isEmpty()) {
333 props = function.getBody().getSpecialProperties();
334 } else {
335 props = super.computeSpecialProperties();
336 }
337 if (function.getDeterminism() != UserFunction.Determinism.PROACTIVE) {
338 props |= StaticProperty.NO_NODES_NEWLY_CREATED;
339 }
340 return props;
341 } else {
342 return super.computeSpecialProperties();
343 }
344 }
345
346 /**
347 * Copy an expression. This makes a deep copy.
348 *
349 * @param rebindings variable bindings that need to be changed
350 * @return the copy of the original expression
351 */
352
353 /*@NotNull*/
354 public Expression copy(RebindingMap rebindings) {
355 if (function == null) {
356 // not bound yet, we have no way to register the new copy with the XSLFunction
357 throw new UnsupportedOperationException("UserFunctionCall.copy()");
358 }
359 UserFunctionCall ufc = new UserFunctionCall();
360 ufc.setFunction(function);
361 ufc.setStaticType(staticType);
362 int numArgs = getArity();
363 Expression[] a2 = new Expression[numArgs];
364 for (int i = 0; i < numArgs; i++) {
365 a2[i] = getArg(i).copy(rebindings);
366 }
367 ufc.setArguments(a2);
368 ExpressionTool.copyLocationInfo(this, ufc);
369 return ufc;
370 }
371
372 /**
373 * Determine the cardinality of the result
374 */
375
376 public int computeCardinality() {
377 if (staticType == null) {
378 // the actual type is not known yet, so we return an approximation
379 return StaticProperty.ALLOWS_ZERO_OR_MORE;
380 } else {
381 return staticType.getCardinality();
382 }
383 }
384
385 /*@NotNull*/
386 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
387 Expression e = super.typeCheck(visitor, contextInfo);
388 if (e != this) {
389 return e;
390 }
391 if (function != null) {
392 checkFunctionCall(function, visitor);
393 if (staticType == null || staticType == SequenceType.ANY_SEQUENCE) {
394 // try to get a better type
395 staticType = function.getResultType();
396 }
397 }
398 return this;
399 }
400
401 /*@NotNull*/
402 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType) throws XPathException {
403 //function.setOnFirstCall(new DeferredAction(visitor, contextItemType));
404 Expression e = super.optimize(visitor, contextItemType);
405 if (e == this && function != null) {
406 Expression e2 = visitor.obtainOptimizer().tryInlineFunctionCall(
407 this, visitor, contextItemType);
408 // if (e2 != this) {
409 // return e2.optimize(visitor, contextItemType);
410 // }
411 return e2;
412 }
413 return e;
414 }
415
416 /**
417 * Reset the static properties of the expression to -1, so that they have to be recomputed
418 * next time they are used.
419 */
420 @Override
421 public void resetLocalStaticProperties() {
422 super.resetLocalStaticProperties();
423 argumentEvaluators = null;
424 }
425
426 /**
427 * Add a representation of this expression to a PathMap. The PathMap captures a map of the nodes visited
428 * by an expression in a source tree.
429 * <p>The default implementation of this method assumes that an expression does no navigation other than
430 * the navigation done by evaluating its subexpressions, and that the subexpressions are evaluated in the
431 * same context as the containing expression. The method must be overridden for any expression
432 * where these assumptions do not hold. For example, implementations exist for AxisExpression, ParentExpression,
433 * and RootExpression (because they perform navigation), and for the doc(), document(), and collection()
434 * functions because they create a new navigation root. Implementations also exist for PathExpression and
435 * FilterExpression because they have subexpressions that are evaluated in a different context from the
436 * calling expression.</p>
437 *
438 * @param pathMap the PathMap to which the expression should be added
439 * @param pathMapNodeSet the PathMapNodeSet to which the paths embodied in this expression should be added
440 * @return the pathMapNode representing the focus established by this expression, in the case where this
441 * expression is the first operand of a path expression or filter expression. For an expression that does
442 * navigation, it represents the end of the arc in the path map that describes the navigation route. For other
443 * expressions, it is the same as the input pathMapNode.
444 */
445
446 public PathMap.PathMapNodeSet addToPathMap(PathMap pathMap, PathMap.PathMapNodeSet pathMapNodeSet) {
447 return addExternalFunctionCallToPathMap(pathMap, pathMapNodeSet);
448 }
449
450 /**
451 * Mark tail-recursive calls on stylesheet functions. This marks the function call as tailRecursive if
452 * if is a call to the containing function, and in this case it also returns "true" to the caller to indicate
453 * that a tail call was found.
454 */
455
456 public int markTailFunctionCalls(StructuredQName qName, int arity) {
457 tailCall = getFunctionName().equals(qName) &&
458 arity == getArity() ? SELF_TAIL_CALL : FOREIGN_TAIL_CALL;
459 return tailCall;
460 }
461
462 public int getImplementationMethod() {
463 if (Cardinality.allowsMany(getCardinality())) {
464 return ITERATE_METHOD | PROCESS_METHOD;
465 } else {
466 return EVALUATE_METHOD;
467 }
468 }
469
470 /**
471 * Call the function, returning the value as an item. This method will be used
472 * only when the cardinality is zero or one. If the function is tail recursive,
473 * it returns an Object representing the arguments to the next (recursive) call
474 */
475
476 public Item evaluateItem(XPathContext c) throws XPathException {
477 return callFunction(c).head();
478 }
479
480 /**
481 * Call the function, returning an iterator over the results. (But if the function is
482 * tail recursive, it returns an iterator over the arguments of the recursive call)
483 */
484
485 /*@NotNull*/
486 public SequenceIterator<?> iterate(XPathContext c) throws XPathException {
487 return callFunction(c).iterate();
488 }
489
490
491 /**
492 * Evaluate an updating expression, adding the results to a Pending Update List.
493 * The default implementation of this method, which is used for non-updating expressions,
494 * throws an UnsupportedOperationException
495 *
496 * @param context the XPath dynamic evaluation context
497 * @param pul the pending update list to which the results should be written
498 */
499
500 public void evaluatePendingUpdates(XPathContext context, PendingUpdateList pul) throws XPathException {
501 Sequence[] actualArgs = evaluateArguments(context);
502 XPathContextMajor c2 = context.newCleanContext();
503 c2.setOrigin(this);
504 function.callUpdating(actualArgs, c2, pul);
505 }
506
507 /**
508 * This is the method that actually does the function call (in pull mode)
509 *
510 * @param context the dynamic context
511 * @return the result of the function
512 * @throws XPathException if dynamic errors occur
513 */
514 private Sequence<?> callFunction(XPathContext context) throws XPathException {
515 UserFunction targetFunction;
516 Sequence<?>[] actualArgs = evaluateArguments(context);
517 XPathContextMajor c2;
518 if (isTailCall()) {
519 requestTailCall(context, actualArgs);
520 return EmptySequence.getInstance();
521 }
522
523 if (bindingSlot >= 0) {
524 Component target = getTargetComponent(context);
525 if (target.isHiddenAbstractComponent()) {
526 throw new XPathException("Cannot call an abstract function (" +
527 name.getDisplayName() +
528 ") with no implementation", "XTDE3052");
529 }
530 targetFunction = (UserFunction) target.getActor();
531 c2 = targetFunction.makeNewContext(context, this);
532 c2.setCurrentComponent(target);
533 c2.setOrigin(this);
534 } else {
535 targetFunction = function;
536 c2 = targetFunction.makeNewContext(context, this);
537 c2.setOrigin(this);
538 }
539
540 try {
541 return targetFunction.call(c2, actualArgs);
542 } catch (UncheckedXPathException e) {
543 XPathException xe = e.getXPathException();
544 xe.maybeSetLocation(getLocation());
545 throw xe;
546 } catch (StackOverflowError err) {
547 err.printStackTrace();
548 throw new XPathException("Too many nested function calls. May be due to infinite recursion",
549 SaxonErrorCode.SXLM0001, getLocation());
550 }
551 }
552
553 private void requestTailCall(XPathContext context, Sequence<?>[] actualArgs) throws XPathException {
554 if (bindingSlot >= 0) {
555 TailCallLoop.TailCallComponent info = new TailCallLoop.TailCallComponent();
556 Component target = getTargetComponent(context);
557 info.component = target;
558 info.function = (UserFunction) target.getActor();
559 if (target.isHiddenAbstractComponent()) {
560 throw new XPathException("Cannot call an abstract function (" +
561 name.getDisplayName() +
562 ") with no implementation", "XTDE3052");
563 }
564 ((XPathContextMajor) context).requestTailCall(info, actualArgs);
565
566 } else {
567 TailCallLoop.TailCallFunction info = new TailCallLoop.TailCallFunction();
568 info.function = function;
569 ((XPathContextMajor) context).requestTailCall(info, actualArgs);
570 }
571
572 }
573
574 /**
575 * Process the function call in push mode
576 *
577 * @param context the XPath dynamic context
578 * @throws XPathException if a dynamic error occurs
579 */
580
581 public void process(XPathContext context) throws XPathException {
582
583 Sequence<?>[] actualArgs = evaluateArguments(context);
584
585 if (isTailCall()) {
586 requestTailCall(context, actualArgs);
587 return;
588 }
589
590 if (bindingSlot >= 0) {
591 Component target = getTargetComponent(context);
592 UserFunction targetFunction = (UserFunction) target.getActor();
593 if (target.getVisibility() == Visibility.ABSTRACT) {
594 throw new XPathException("Cannot call a function defined with visibility=abstract", "XTDE3052");
595 }
596 XPathContextMajor c2 = targetFunction.makeNewContext(context, this);
597 c2.setCurrentComponent(target);
598 c2.setOrigin(this);
599 targetFunction.process(actualArgs, c2);
600 } else {
601 XPathContextMajor c2 = function.makeNewContext(context, this);
602 c2.setOrigin(this);
603 function.process(actualArgs, c2);
604 }
605 }
606
607 public Component getTargetComponent(XPathContext context) {
608 if (bindingSlot == -1) {
609 // fallback for non-package code
610 return function.getDeclaringComponent();
611 } else {
612 return context.getTargetComponent(bindingSlot);
613 }
614 }
615
616 public UserFunction getTargetFunction(XPathContext context) {
617 return (UserFunction) getTargetComponent(context).getActor();
618 }
619
620 public Sequence<?>[] evaluateArguments(XPathContext c) throws XPathException {
621 return evaluateArguments(c, false);
622 }
623
624
625 public Sequence<?>[] evaluateArguments(XPathContext c, boolean streamed) throws XPathException {
626 int numArgs = getArity();
627 Sequence<?>[] actualArgs = SequenceTool.makeSequenceArray(numArgs);
628 synchronized(this) {
629 if (argumentEvaluators == null) {
630 // should have been done at compile time
631 allocateArgumentEvaluators();
632 }
633 }
634 for (int i = 0; i < numArgs; i++) {
635 Evaluator eval = argumentEvaluators[i];
636 if (eval == Evaluator.STREAMING_ARGUMENT && !streamed) {
637 eval = Evaluator.EAGER_SEQUENCE;
638 }
639 actualArgs[i] = eval.evaluate(getArg(i), c);
640
641 if (actualArgs[i] == null) {
642 actualArgs[i] = EmptySequence.getInstance();
643 }
644 }
645 return actualArgs;
646 }
647
648 /**
649 * Diagnostic print of expression structure. The abstract expression tree
650 * is written to the supplied output destination.
651 */
652
653 public void export(ExpressionPresenter out) throws XPathException {
654 out.startElement("ufCall", this);
655 if (getFunctionName() != null) {
656 out.emitAttribute("name", getFunctionName());
657 out.emitAttribute("tailCall",
658 tailCall == NOT_TAIL_CALL ? "false" : tailCall == SELF_TAIL_CALL ? "self" : "foreign");
659 }
660 out.emitAttribute("bSlot", "" + getBindingSlot());
661 if (argumentEvaluators != null && getArity() > 0) {
662 FastStringBuffer fsb = new FastStringBuffer(FastStringBuffer.C64);
663 for (Evaluator e : argumentEvaluators) {
664 fsb.append(e.getCode() + " ");
665 }
666 out.emitAttribute("eval", Whitespace.trim(fsb));
667 }
668 for (Operand o : operands()) {
669 o.getChildExpression().export(out);
670 }
671 if (getFunctionName() == null) {
672 out.setChildRole("inline");
673 function.getBody().export(out);
674 out.endElement();
675 }
676 out.endElement();
677 }
678
679 public int getConstructType() {
680 return LocationKind.FUNCTION_CALL;
681 }
682
683 /**
684 * Get a name identifying the kind of expression, in terms meaningful to a user.
685 *
686 * @return a name identifying the kind of expression, in terms meaningful to a user.
687 * The name will always be in the form of a lexical XML QName, and should match the name used
688 * in explain() output displaying the expression.
689 */
690 @Override
691 public String getExpressionName() {
692 return "userFunctionCall";
693 }
694
695 public Object getProperty(String name) {
696 if (name.equals("target")) {
697 return function;
698 }
699 return super.getProperty(name);
700 }
701
702 public StructuredQName getObjectName() {
703 return getFunctionName();
704 }
705
706
707 }