Debian Codegraph @

net/sf/saxon/expr/instruct/UserFunction.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.instruct;
9
10 //import com.saxonica.expr.MemoFunction;
11
12 import net.sf.saxon.Configuration;
13 import net.sf.saxon.Controller;
14 import net.sf.saxon.expr.*;
15 import net.sf.saxon.expr.parser.*;
16 import net.sf.saxon.expr.sort.AtomicComparer;
17 import net.sf.saxon.om.*;
18 import net.sf.saxon.pattern.NodeTest;
19 import net.sf.saxon.query.AnnotationList;
20 import net.sf.saxon.style.StylesheetPackage;
21 import net.sf.saxon.trace.ExpressionPresenter;
22 import net.sf.saxon.trace.LocationKind;
23 import net.sf.saxon.trans.FunctionStreamability;
24 import net.sf.saxon.trans.SymbolicName;
25 import net.sf.saxon.trans.Visibility;
26 import net.sf.saxon.trans.XPathException;
27 import net.sf.saxon.tree.iter.SingletonIterator;
28 import net.sf.saxon.tree.iter.UnfailingIterator;
29 import net.sf.saxon.type.*;
30 import net.sf.saxon.value.EmptySequence;
31 import net.sf.saxon.value.SequenceType;
32
33 import java.util.Objects;
34
35 /**
36 * This object represents the compiled form of a user-written function
37 * (the source can be either an XSLT stylesheet function or an XQuery function).
38 * <p>It is assumed that type-checking, of both the arguments and the results,
39 * has been handled at compile time. That is, the expression supplied as the body
40 * of the function must be wrapped in code to check or convert the result to the
41 * required type, and calls on the function must be wrapped at compile time to check or
42 * convert the supplied arguments.</p>
43 */
44
45 public class UserFunction extends Actor implements Function, ContextOriginator {
46
47 public enum Determinism {DETERMINISTIC, PROACTIVE, ELIDABLE}
48 private final static int MAX_INLININGS = 100;
49
50 private StructuredQName functionName; // null for an anonymous function
51 private boolean tailCalls = false;
52 // indicates that the function contains tail calls, not necessarily recursive ones.
53 private boolean tailRecursive = false;
54 // indicates that the function contains tail calls on itself
55 private UserFunctionParameter[] parameterDefinitions;
56 private SequenceType resultType;
57 private SequenceType declaredResultType;
58 protected Evaluator evaluator = null;
59 private boolean isUpdating = false;
60 private int inlineable = -1; // 0:no 1:yes -1:don't know
61 private int inliningCount = 0;
62 private boolean overrideExtensionFunction = true;
63 private AnnotationList annotations = AnnotationList.EMPTY;
64 private FunctionStreamability declaredStreamability = FunctionStreamability.UNCLASSIFIED;
65 private Determinism determinism = Determinism.PROACTIVE;
66 private int refCount = 0;
67
68
69 /**
70 * Create a user-defined function (the body must be added later)
71 */
72
73 public UserFunction() {
74 }
75
76
77 public int getComponentKind() {
78 return StandardNames.XSL_FUNCTION;
79 }
80
81 /**
82 * Set the function name
83 *
84 * @param name the function name
85 */
86
87 public void setFunctionName(StructuredQName name) {
88 functionName = name;
89 }
90
91 /**
92 * Get the function name
93 *
94 * @return the function name, as a StructuredQName. Returns null for an anonymous function
95 */
96
97 public StructuredQName getFunctionName() {
98 return functionName;
99 }
100
101 /**
102 * Get a description of this function for use in error messages. For named functions, the description
103 * is the function name (as a lexical QName). For others, it might be, for example, "inline function",
104 * or "partially-applied ends-with function".
105 *
106 * @return a description of the function for use in error messages
107 */
108 public String getDescription() {
109 return getFunctionName().getDisplayName();
110 }
111
112 /**
113 * Get a name identifying the object of the expression, for example a function name, template name,
114 * variable name, key name, element name, etc. This is used only where the name is known statically.
115 */
116
117 public StructuredQName getObjectName() {
118 return functionName;
119 }
120
121 public SymbolicName.F getSymbolicName() {
122 return new SymbolicName.F(functionName, getArity());
123 }
124
125
126 /**
127 * Get the type of the function
128 *
129 * @return the function type
130 */
131
132 public FunctionItemType getFunctionItemType() {
133 SequenceType[] argTypes = new SequenceType[parameterDefinitions.length];
134 for (int i = 0; i < parameterDefinitions.length; i++) {
135 UserFunctionParameter ufp = parameterDefinitions[i];
136 argTypes[i] = ufp.getRequiredType();
137 }
138 return new SpecificFunctionType(argTypes, resultType, annotations);
139 }
140
141 /**
142 * Get the roles of the arguments, for the purposes of streaming
143 *
144 * @return an array of OperandRole objects, one for each argument
145 */
146 public OperandRole[] getOperandRoles() {
147 OperandRole[] roles = new OperandRole[getArity()];
148 OperandUsage first = null;
149 switch (declaredStreamability) {
150 case UNCLASSIFIED:
151 SequenceType required = getArgumentType(0);
152 first = OperandRole.getTypeDeterminedUsage(required.getPrimaryType());
153 break;
154 case ABSORBING:
155 first = OperandUsage.ABSORPTION;
156 break;
157 case INSPECTION:
158 first = OperandUsage.INSPECTION;
159 break;
160 case FILTER:
161 first = OperandUsage.TRANSMISSION;
162 break;
163 case SHALLOW_DESCENT:
164 first = OperandUsage.TRANSMISSION;
165 break;
166 case DEEP_DESCENT:
167 first = OperandUsage.TRANSMISSION;
168 break;
169 case ASCENT:
170 first = OperandUsage.TRANSMISSION;
171 break;
172 }
173 roles[0] = new OperandRole(0, first, getArgumentType(0));
174 for (int i = 1; i < roles.length; i++) {
175 SequenceType required = getArgumentType(i);
176 roles[i] = new OperandRole(0, OperandRole.getTypeDeterminedUsage(required.getPrimaryType()), required);
177 }
178 return roles;
179 }
180
181 /**
182 * Ask whether any of the declared arguments accept nodes without atomizing them
183 *
184 * @return true if this is the case
185 */
186
187 public boolean acceptsNodesWithoutAtomization() {
188 for (int i = 0; i < getArity(); i++) {
189 ItemType type = getArgumentType(i).getPrimaryType();
190 if (type instanceof NodeTest || type == AnyItemType.getInstance()) {
191 return true;
192 }
193 }
194 return false;
195 }
196
197 public boolean isOverrideExtensionFunction() {
198 return overrideExtensionFunction;
199 }
200
201 public void setOverrideExtensionFunction(boolean overrideExtensionFunction) {
202 this.overrideExtensionFunction = overrideExtensionFunction;
203 }
204
205 /**
206 * Supply a set of annotations
207 *
208 * @param list the new set of annotations, which will replace any previous annotations on the function
209 */
210
211 public void setAnnotations(AnnotationList list) {
212 this.annotations = Objects.requireNonNull(list);
213 }
214
215 /**
216 * Get the annotations defined on this function
217 * @return the list of annotations defined on this function
218 */
219
220 public AnnotationList getAnnotations() {
221 return annotations;
222 }
223
224 /**
225 * Set the determinism of the function. Corresponds to the XSLT 3.0 values new-each-time=yes|no|maybe
226 *
227 * @param determinism the determinism value for the function
228 */
229
230 public void setDeterminism(Determinism determinism) {
231 this.determinism = determinism;
232 }
233
234 /**
235 * Get the determinism of the function. Corresponds to the XSLT 3.0 values new-each-time=yes|no|maybe
236 *
237 * @return the determinism value for the function
238 */
239
240 public Determinism getDeterminism() {
241 return determinism;
242 }
243
244 /**
245 * Determine the preferred evaluation mode for this function
246 */
247
248 public void computeEvaluationMode() {
249 if (tailRecursive) {
250 // If this function contains tail calls, we evaluate it eagerly, because
251 // the caller needs to know whether a tail call was returned or not: if we
252 // return a Closure, the tail call escapes into the wild and can reappear anywhere...
253 evaluator = ExpressionTool.eagerEvaluator(getBody());
254 // } else if ((getBody().getSpecialProperties() & StaticProperty.ALL_NODES_NEWLY_CREATED) != 0) {
255 // evaluationMode = ExpressionTool.PROCESS;
256 // } else if (getFunctionName().getLocalPart().equals("check-syntax-primary")) { // KILROY
257 // evaluator = ExpressionTool.eagerEvaluator(getBody());
258 } else {
259 evaluator = ExpressionTool.lazyEvaluator(getBody(), true);
260 //evaluator = ExpressionTool.eagerEvaluator(getBody());
261 }
262 }
263
264 /**
265 * Ask whether the function can be inlined
266 *
267 * @return true (yes), false (no), or null (don't know)
268 */
269
270 /*@Nullable*/
271 public Boolean isInlineable() {
272 if (inlineable != -1) {
273 return inlineable > 0 && inliningCount < MAX_INLININGS;
274 }
275 if (body == null) {
276 // bug 2226
277 return null;
278 }
279 if (body.hasSpecialProperty(StaticProperty.HAS_SIDE_EFFECTS) || tailCalls) {
280 // This is mainly to handle current-output-uri()
281 return false;
282 }
283 Component component = getDeclaringComponent();
284 if (component != null) {
285 Visibility visibility = getDeclaringComponent().getVisibility();
286 if (visibility == Visibility.PRIVATE || visibility == Visibility.FINAL) {
287 if (inlineable < 0) {
288 return null;
289 } else {
290 return inlineable > 0;
291 }
292 } else {
293 return false;
294 }
295 } else {
296 return null;
297 }
298 }
299
300
301 /**
302 * Say whether this function can be inlined
303 *
304 * @param inlineable true or false
305 */
306
307 public void setInlineable(boolean inlineable) {
308 this.inlineable = inlineable ? 1 : 0;
309 }
310
311 /**
312 * Indicate that the function is being inlined, incrementing a count of how
313 * many times it has been inlined
314 */
315
316 public void markAsInlined() {
317 inliningCount++;
318 }
319
320 /**
321 * Set the definitions of the declared parameters for this function
322 *
323 * @param params an array of parameter definitions
324 */
325
326 public void setParameterDefinitions(UserFunctionParameter[] params) {
327 parameterDefinitions = params;
328 }
329
330 /**
331 * Get the definitions of the declared parameters for this function
332 *
333 * @return an array of parameter definitions
334 */
335
336 public UserFunctionParameter[] getParameterDefinitions() {
337 return parameterDefinitions;
338 }
339
340 /**
341 * Set the declared result type of the function
342 *
343 * @param resultType the declared return type
344 */
345
346 public void setResultType(SequenceType resultType) {
347 this.declaredResultType = resultType;
348 this.resultType = resultType;
349 }
350
351 /**
352 * Indicate whether the function contains a tail call
353 *
354 * @param tailCalls true if the function contains a tail call (on any function)
355 * @param recursiveTailCalls true if the function contains a tail call (on itself)
356 */
357
358 public void setTailRecursive(boolean tailCalls, boolean recursiveTailCalls) {
359 this.tailCalls = tailCalls;
360 tailRecursive = recursiveTailCalls;
361 }
362
363 /**
364 * Determine whether the function contains tail calls (on this or other functions)
365 *
366 * @return true if the function contains tail calls
367 */
368
369 public boolean containsTailCalls() {
370 return tailCalls;
371 }
372
373 /**
374 * Determine whether the function contains a tail call, calling itself
375 *
376 * @return true if the function contains a directly-recursive tail call
377 */
378
379 public boolean isTailRecursive() {
380 return tailRecursive;
381 }
382
383 /**
384 * Set whether this is an updating function (as defined in XQuery Update)
385 *
386 * @param isUpdating true if this is an updating function
387 */
388
389 public void setUpdating(boolean isUpdating) {
390 this.isUpdating = isUpdating;
391 }
392
393 /**
394 * Ask whether this is an updating function (as defined in XQuery Update)
395 *
396 * @return true if this is an updating function
397 */
398
399 public boolean isUpdating() {
400 return isUpdating;
401 }
402
403 /**
404 * Set the declared streamability (XSLT 3.0 attribute)
405 *
406 * @param streamability the declared streamability (defaults to "unclassified")
407 */
408
409 public void setDeclaredStreamability(FunctionStreamability streamability) {
410 this.declaredStreamability = streamability == null ? FunctionStreamability.UNCLASSIFIED : streamability;
411 }
412
413 /**
414 * Get the declared streamability (XSLT 3.0 attribute)
415 *
416 * @return the declared streamability (defaults to "unclassified")
417 */
418
419 public FunctionStreamability getDeclaredStreamability() {
420 return this.declaredStreamability;
421 }
422
423 /**
424 * Get the type of value returned by this function
425 *
426 * @return the declared result type, or the inferred result type
427 * if this is more precise
428 */
429
430 public SequenceType getResultType() {
431 if (resultType == SequenceType.ANY_SEQUENCE && getBody() != null) {
432 // see if we can infer a more precise result type. We don't do this if the function contains
433 // calls on further functions, to prevent infinite regress.
434 if (!containsUserFunctionCalls(getBody())) {
435 resultType = SequenceType.makeSequenceType(
436 getBody().getItemType(), getBody().getCardinality());
437 }
438 }
439 return resultType;
440 }
441
442 /**
443 * Get the declared result type
444 *
445 * @return the declared result type
446 */
447
448 public SequenceType getDeclaredResultType() {
449 return declaredResultType;
450 }
451
452 /**
453 * Determine whether a given expression contains calls on user-defined functions
454 *
455 * @param exp the expression to be tested
456 * @return true if the expression contains calls to user functions.
457 */
458
459 private static boolean containsUserFunctionCalls(Expression exp) {
460 if (exp instanceof UserFunctionCall) {
461 return true;
462 }
463 for (Operand o : exp.operands()) {
464 if (containsUserFunctionCalls(o.getChildExpression())) {
465 return true;
466 }
467 }
468 return false;
469 }
470
471 /**
472 * Get the required types of an argument to this function
473 *
474 * @param n identifies the argument in question, starting at 0
475 * @return a SequenceType object, indicating the required type of the argument
476 */
477
478 public SequenceType getArgumentType(int n) {
479 return parameterDefinitions[n].getRequiredType();
480 }
481
482 /**
483 * Get the evaluation mode. The evaluation mode will be computed if this has not already been done
484 *
485 * @return the computed evaluation mode
486 */
487
488 public Evaluator getEvaluator() {
489 if (evaluator == null) {
490 computeEvaluationMode();
491 }
492 return evaluator;
493 }
494
495 /**
496 * Set the evaluation mode. (Used when reloading a saved package)
497 *
498 * @param mode the evaluation mode
499 */
500
501 public void setEvaluationMode(int mode) {
502 evaluator = Evaluator.evaluatorForCode(mode);
503 }
504
505 /**
506 * Get the arity of this function
507 *
508 * @return the number of arguments
509 */
510
511 public int getArity() {
512 return parameterDefinitions.length;
513 }
514
515 /**
516 * Ask whether this function is a memo function
517 *
518 * @return false (overridden in a subclass)
519 */
520
521 public boolean isMemoFunction() {
522 return false;
523 }
524
525 public void typeCheck(ExpressionVisitor visitor) throws XPathException {
526 Expression exp = getBody();
527 if (exp instanceof ValueOf
528 && ((ValueOf)exp).getSelect().getItemType().isAtomicType()
529 && declaredResultType.getPrimaryType().isAtomicType()
530 && declaredResultType.getPrimaryType() != BuiltInAtomicType.STRING) {
531 visitor.getStaticContext().issueWarning(
532 "A function that computes atomic values should use xsl:sequence rather than xsl:value-of",
533 getLocation());
534 }
535 ExpressionTool.resetPropertiesWithinSubtree(exp);
536 Expression exp2 = exp;
537 try {
538 // We've already done the typecheck of each XPath expression, but it's worth doing again at this
539 // level because we have more information now.
540 ContextItemStaticInfo info = ContextItemStaticInfo.ABSENT;
541 exp2 = exp.typeCheck(visitor, info);
542 if (resultType != null) {
543 RoleDiagnostic role =
544 new RoleDiagnostic(RoleDiagnostic.FUNCTION_RESULT,
545 functionName == null ? "" : functionName.getDisplayName() + "#" + getArity(), 0);
546 role.setErrorCode(getPackageData().getHostLanguage() == Configuration.XSLT && getFunctionName() != null ? "XTTE0780" : "XPTY0004");
547 exp2 = visitor.getConfiguration().getTypeChecker(false).staticTypeCheck(exp2, resultType, role, visitor);
548 }
549 } catch (XPathException err) {
550 err.maybeSetLocation(getLocation());
551 throw err;
552 }
553 if (exp2 != exp) {
554 setBody(exp2);
555 }
556 }
557
558 /**
559 * Create a context for evaluating this function
560 *
561 * @param oldContext the existing context of the caller
562 * @param originator
563 * @return a new context which should be supplied to the call() method.
564 */
565
566 public XPathContextMajor makeNewContext(XPathContext oldContext, ContextOriginator originator) {
567 XPathContextMajor c2 = oldContext.newCleanContext();
568 c2.setReceiver(oldContext.getReceiver());
569 c2.setTemporaryOutputState(StandardNames.XSL_FUNCTION);
570 c2.setCurrentOutputUri(null);
571 c2.setCurrentComponent(getDeclaringComponent()); // default value for the caller to override if necessary
572 c2.setOrigin(originator);
573 return c2;
574 }
575
576
577 /**
578 * Call this function to return a value.
579 *
580 * @param context This provides the run-time context for evaluating the function. This should be created
581 * using {@link Function#makeNewContext(XPathContext, ContextOriginator)}. It must be an instance of XPathContextMajor.
582 * @param actualArgs the arguments supplied to the function. These must have the correct
583 * types required by the function signature (it is the caller's responsibility to check this).
584 * It is acceptable to supply a {@link net.sf.saxon.value.Closure} to represent a value whose
585 * evaluation will be delayed until it is needed. The array must be the correct size to match
586 * the number of arguments: again, it is the caller's responsibility to check this.
587 * @return a Value representing the result of the function.
588 * @throws net.sf.saxon.trans.XPathException if a dynamic error occurs while evaluating the function
589 */
590
591 public Sequence<?> call(XPathContext context, Sequence[] actualArgs)
592 throws XPathException {
593 if (evaluator == null) {
594 // should have been done at compile time
595 computeEvaluationMode();
596 }
597
598 XPathContextMajor c2 = (XPathContextMajor) context;
599 c2.setStackFrame(getStackFrameMap(), actualArgs);
600 Sequence<?> result;
601 try {
602 result = evaluator.evaluate(getBody(), c2);
603 } catch (XPathException err) {
604 err.maybeSetLocation(getLocation());
605 err.maybeSetContext(c2);
606 throw err;
607 } catch (Exception err2) {
608 String message = "Internal error evaluating function "
609 + (functionName == null ? "(unnamed)" : functionName.getDisplayName())
610 + (getLineNumber() > 0 ? " at line " + getLineNumber() : "")
611 + (getSystemId() != null ? " in module " + getSystemId() : "");
612 throw new RuntimeException(message, err2);
613 }
614 return result;
615 }
616
617 /**
618 * Call this function in "push" mode, writing the results to the current output destination.
619 *
620 * @param actualArgs the arguments supplied to the function. These must have the correct
621 * types required by the function signature (it is the caller's responsibility to check this).
622 * It is acceptable to supply a {@link net.sf.saxon.value.Closure} to represent a value whose
623 * evaluation will be delayed until it is needed. The array must be the correct size to match
624 * the number of arguments: again, it is the caller's responsibility to check this.
625 * @param context This provides the run-time context for evaluating the function. It is the caller's
626 * responsibility to allocate a "clean" context for the function to use; the context that is provided
627 * will be overwritten by the function.
628 * @throws net.sf.saxon.trans.XPathException if a dynamic error occurs while evaluating the function
629 */
630
631 public void process(Sequence[] actualArgs, XPathContextMajor context)
632 throws XPathException {
633 context.setStackFrame(getStackFrameMap(), actualArgs);
634 getBody().process(context);
635 }
636
637 /**
638 * Call this function. This method allows an XQuery function to be called directly from a Java
639 * application. It creates the environment needed to achieve this
640 *
641 * @param actualArgs the arguments supplied to the function. These must have the correct
642 * types required by the function signature (it is the caller's responsibility to check this).
643 * It is acceptable to supply a {@link net.sf.saxon.value.Closure} to represent a value whose
644 * evaluation will be delayed until it is needed. The array must be the correct size to match
645 * the number of arguments: again, it is the caller's responsibility to check this.
646 * @param controller This provides the run-time context for evaluating the function. A Controller
647 * may be obtained by calling {@link net.sf.saxon.query.XQueryExpression#newController}. This may
648 * be used for a series of calls on functions defined in the same module as the XQueryExpression.
649 * @return a Value representing the result of the function.
650 * @throws net.sf.saxon.trans.XPathException if a dynamic error occurs while evaluating the function.
651 */
652
653 public Sequence<?> call(Sequence[] actualArgs, Controller controller) throws XPathException {
654 return call(controller.newXPathContext(), actualArgs);
655 }
656
657 /**
658 * Call an updating function.
659 *
660 * @param actualArgs the arguments supplied to the function. These must have the correct
661 * types required by the function signature (it is the caller's responsibility to check this).
662 * It is acceptable to supply a {@link net.sf.saxon.value.Closure} to represent a value whose
663 * evaluation will be delayed until it is needed. The array must be the correct size to match
664 * the number of arguments: again, it is the caller's responsibility to check this.
665 * @param context the dynamic evaluation context
666 * @param pul the pending updates list, to which the function's update actions are to be added.
667 * @throws net.sf.saxon.trans.XPathException if a dynamic error occurs while evaluating the function.
668 */
669
670 public void callUpdating(Sequence[] actualArgs, XPathContextMajor context, PendingUpdateList pul)
671 throws XPathException {
672 context.setStackFrame(getStackFrameMap(), actualArgs);
673 try {
674 getBody().evaluatePendingUpdates(context, pul);
675 } catch (XPathException err) {
676 err.maybeSetLocation(getLocation());
677 throw err;
678 }
679 }
680
681 /**
682 * Diagnostic print of expression structure. The abstract expression tree
683 * is written to the supplied outputstream.
684 *
685 * @param presenter the expression presenter used to display the structure
686 */
687 @Override
688 public void export(ExpressionPresenter presenter) throws XPathException {
689 presenter.startElement("function");
690 if (getFunctionName() != null) {
691 presenter.emitAttribute("name", getFunctionName());
692 presenter.emitAttribute("line", getLineNumber() + "");
693 presenter.emitAttribute("module", getSystemId());
694 presenter.emitAttribute("eval", getEvaluator().getCode() + "");
695 }
696 String flags = "";
697 if (determinism == Determinism.PROACTIVE) {
698 flags += "p";
699 } else if (determinism == Determinism.ELIDABLE) {
700 flags += "e";
701 } else {
702 flags += "d";
703 }
704 if (isMemoFunction()) {
705 flags += "m";
706 }
707 switch (declaredStreamability) {
708 case UNCLASSIFIED:
709 flags += "U";
710 break;
711 case ABSORBING:
712 flags += "A";
713 break;
714 case INSPECTION:
715 flags += "I";
716 break;
717 case FILTER:
718 flags += "F";
719 break;
720 case SHALLOW_DESCENT:
721 flags += "S";
722 break;
723 case DEEP_DESCENT:
724 flags += "D";
725 break;
726 case ASCENT:
727 flags += "C";
728 break;
729 }
730 presenter.emitAttribute("flags", flags);
731 presenter.emitAttribute("as", getDeclaredResultType().toExportString());
732 presenter.emitAttribute("slots", getStackFrameMap().getNumberOfVariables() + "");
733 for (UserFunctionParameter p : parameterDefinitions) {
734 presenter.startElement("arg");
735 presenter.emitAttribute("name", p.getVariableQName());
736 presenter.emitAttribute("as", p.getRequiredType().toExportString());
737 presenter.endElement();
738 }
739 presenter.setChildRole("body");
740 getBody().export(presenter);
741 presenter.endElement();
742 }
743
744 @Override
745 public boolean isExportable() {
746 return refCount > 0 ||
747 (getDeclaredVisibility() != null && getDeclaredVisibility() != Visibility.PRIVATE) ||
748 ((StylesheetPackage) getPackageData()).isRetainUnusedFunctions();
749 }
750
751 public boolean isTrustedResultType() {
752 return false;
753 }
754
755 /**
756 * Get the type of construct. This will either be the fingerprint of a standard XSLT instruction name
757 * (values in {@link net.sf.saxon.om.StandardNames}: all less than 1024)
758 * or it will be a constant in class {@link LocationKind}.
759 */
760
761 public int getConstructType() {
762 return LocationKind.FUNCTION;
763 }
764
765 /**
766 * Get an iterator over all the items in the sequence (that is, the singleton sequence
767 * consisting of this function item)
768 *
769 * @return an iterator over all the items
770 */
771 public UnfailingIterator<Function> iterate() {
772 return SingletonIterator.makeIterator(this);
773 }
774
775 /**
776 * Ask whether this function item is a map
777 *
778 * @return true if this function item is a map, otherwise false
779 */
780 public boolean isMap() {
781 return false;
782 }
783
784 /**
785 * Ask whether this function item is an array
786 *
787 * @return true if this function item is an array, otherwise false
788 */
789 public boolean isArray() {
790 return false;
791 }
792
793 /**
794 * Test whether this FunctionItem is deep-equal to another function item,
795 * under the rules of the deep-equal function
796 *
797 * @param other the other function item
798 * @param context the dynamic evaluation context
799 * @param comparer the object to perform the comparison
800 * @param flags options for how the comparison is performed
801 * @return true if the two function items are deep-equal
802 * @throws net.sf.saxon.trans.XPathException if the comparison cannot be performed
803 */
804 public boolean deepEquals(Function other, XPathContext context, AtomicComparer comparer, int flags) throws XPathException {
805 XPathException err = new XPathException("Cannot compare functions using deep-equal", "FOTY0015");
806 err.setIsTypeError(true);
807 err.setXPathContext(context);
808 throw err;
809 }
810
811 /**
812 * Get the n'th item in the value, counting from 0
813 *
814 * @param n the index of the required item, with 0 representing the first item in the sequence
815 * @return the n'th item if it exists, or null otherwise
816 */
817 public Function itemAt(int n) {
818 return n == 0 ? this : null;
819 }
820
821 /**
822 * Get a subsequence of the value
823 *
824 * @param start the index of the first item to be included in the result, counting from zero.
825 * A negative value is taken as zero. If the value is beyond the end of the sequence, an empty
826 * sequence is returned
827 * @param length the number of items to be included in the result. Specify Integer.MAX_VALUE to
828 * get the subsequence up to the end of the base sequence. If the value is negative, an empty sequence
829 * is returned. If the value goes off the end of the sequence, the result returns items up to the end
830 * of the sequence
831 * @return the required subsequence.
832 */
833 public GroundedValue<Function> subsequence(int start, int length) {
834 return start <= 0 && (start + length) > 0 ? this : EmptySequence.getInstance();
835 }
836
837 /**
838 * Get the size of the value (the number of items)
839 *
840 * @return the number of items in the sequence
841 */
842 public int getLength() {
843 return 1;
844 }
845
846 /**
847 * Get the effective boolean value of this sequence
848 *
849 * @return the effective boolean value
850 * @throws net.sf.saxon.trans.XPathException if the sequence has no effective boolean value (for example a sequence of two integers)
851 */
852 public boolean effectiveBooleanValue() throws XPathException {
853 return ExpressionTool.effectiveBooleanValue(this);
854 }
855
856 /**
857 * Reduce the sequence to its simplest form. If the value is an empty sequence, the result will be
858 * EmptySequence.getInstance(). If the value is a single atomic value, the result will be an instance
859 * of AtomicValue. If the value is a single item of any other kind, the result will be an instance
860 * of One. Otherwise, the result will typically be unchanged.
861 *
862 * @return the simplified sequence
863 */
864 public UserFunction reduce() {
865 return this;
866 }
867
868 /**
869 * Get the first item in the sequence. Differs from the superclass {@link net.sf.saxon.om.Sequence} in that
870 * no exception is thrown.
871 *
872 * @return the first item in the sequence if there is one, or null if the sequence
873 * is empty
874 */
875 public UserFunction head() {
876 return this;
877 }
878
879 /**
880 * Get the value of the item as a string. For nodes, this is the string value of the
881 * node as defined in the XPath 2.0 data model, except that all nodes are treated as being
882 * untyped: it is not an error to get the string value of a node with a complex type.
883 * For atomic values, the method returns the result of casting the atomic value to a string.
884 * <p>If the calling code can handle any CharSequence, the method {@link #getStringValueCS} should
885 * be used. If the caller requires a string, this method is preferred.</p>
886 *
887 * @return the string value of the item
888 * @throws UnsupportedOperationException if the item is a function item (an unchecked exception
889 * is used here to avoid introducing exception handling to a large number of paths where it is not
890 * needed)
891 * @see #getStringValueCS
892 * @since 8.4
893 */
894 public String getStringValue() {
895 throw new UnsupportedOperationException("A function has no string value");
896 }
897
898 /**
899 * Get the string value of the item as a CharSequence. This is in some cases more efficient than
900 * the version of the method that returns a String. The method satisfies the rule that
901 * <code>X.getStringValueCS().toString()</code> returns a string that is equal to
902 * <code>X.getStringValue()</code>.
903 * <p>Note that two CharSequence values of different types should not be compared using equals(), and
904 * for the same reason they should not be used as a key in a hash table.</p>
905 * <p>If the calling code can handle any CharSequence, this method should
906 * be used. If the caller requires a string, the {@link #getStringValue} method is preferred.</p>
907 *
908 * @return the string value of the item
909 * @throws UnsupportedOperationException if the item is a function item (an unchecked exception
910 * is used here to avoid introducing exception handling to a large number of paths where it is not
911 * needed)
912 * @see #getStringValue
913 * @since 8.4
914 */
915 public CharSequence getStringValueCS() {
916 return getStringValue();
917 }
918
919 /**
920 * Atomize the item.
921 *
922 * @return the result of atomization
923 * @throws net.sf.saxon.trans.XPathException if atomization is not allowed
924 * for this kind of item
925 */
926 public AtomicSequence atomize() throws XPathException {
927 throw new XPathException("Functions cannot be atomized", "FOTY0013");
928 }
929
930 public void incrementReferenceCount() {
931 refCount++;
932 }
933
934 public int getReferenceCount() {
935 return refCount;
936 }
937
938 public void prepareForStreaming() throws XPathException {
939 // method is defined in streamable subclass
940 }
941
942 }
943
944