Debian Codegraph @

net/sf/saxon/functions/IntegratedFunctionCall.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.functions;
9
10 //import com.saxonica.expr.JavaExtensionFunctionCall;
11
12 import net.sf.saxon.Configuration;
13 import net.sf.saxon.expr.*;
14 import net.sf.saxon.expr.parser.*;
15 import net.sf.saxon.lib.ExtensionFunctionCall;
16 import net.sf.saxon.lib.ExtensionFunctionDefinition;
17 import net.sf.saxon.om.*;
18 import net.sf.saxon.pattern.AnyNodeTest;
19 import net.sf.saxon.trace.ExpressionPresenter;
20 import net.sf.saxon.trans.SaxonErrorCode;
21 import net.sf.saxon.trans.XPathException;
22 import net.sf.saxon.type.AnyItemType;
23 import net.sf.saxon.type.ItemType;
24 import net.sf.saxon.type.TypeHierarchy;
25 import net.sf.saxon.value.SequenceType;
26
27 /**
28 * Expression representing a call to a user-written extension
29 * function implemented as a subtype of {@link ExtensionFunctionCall}
30 */
31 public class IntegratedFunctionCall extends FunctionCall implements Callable {
32
33 private StructuredQName name;
34 private ExtensionFunctionCall function;
35 private SequenceType resultType = SequenceType.ANY_SEQUENCE;
36 private int state = 0;
37
38 public IntegratedFunctionCall(StructuredQName name, ExtensionFunctionCall function) {
39 this.name = name;
40 this.function = function;
41 }
42
43 /**
44 * Set the result type of the function
45 * @param resultType the result type
46 */
47
48 public void setResultType(SequenceType resultType) {
49 this.resultType = resultType;
50 }
51
52 /**
53 * Get the qualified of the function being called
54 *
55 * @return the qualified name
56 */
57 @Override
58 public StructuredQName getFunctionName() {
59 return name;
60 }
61
62 /**
63 * Get the target function to be called
64 *
65 * @param context the dynamic evaluation context
66 * @return the target function, or null if unknown
67 */
68 @Override
69 public Function getTargetFunction(XPathContext context) {
70 return null;
71 }
72
73 /**
74 * Get the ExtensionFunctionCall object supplied by the application
75 *
76 * @return the ExtensionFunctionCall object
77 */
78
79 public ExtensionFunctionCall getFunction() {
80 return function;
81 }
82
83
84 /**
85 * Method supplied by each class of function to check arguments during parsing, when all
86 * the argument expressions have been read. This implementation of the method checks the arguments
87 * of the supplied function call against the argument types declared as part of the extension function
88 * definition, and generates code to do the conversion if necessary.
89 *
90 * @param visitor the expression visitor
91 * @throws net.sf.saxon.trans.XPathException
92 * if the arguments are statically determined to be incompatible
93 * with the declared argument types of the function.
94 */
95
96 public void checkArguments(/*@NotNull*/ ExpressionVisitor visitor) throws XPathException {
97 ExtensionFunctionDefinition definition = function.getDefinition();
98 checkArgumentCount(definition.getMinimumNumberOfArguments(), definition.getMaximumNumberOfArguments());
99 final int args = getArity();
100 SequenceType[] declaredArgumentTypes = definition.getArgumentTypes();
101 if (declaredArgumentTypes == null || (args != 0 && declaredArgumentTypes.length == 0)) {
102 throw new XPathException("Integrated function " + getDisplayName() +
103 " failed to declare its argument types");
104 }
105 SequenceType[] actualArgumentTypes = new SequenceType[args];
106 TypeChecker tc = visitor.getConfiguration().getTypeChecker(false);
107 for (int i = 0; i < args; i++) {
108 setArg(i, tc.staticTypeCheck(
109 getArg(i),
110 i < declaredArgumentTypes.length ?
111 declaredArgumentTypes[i] :
112 declaredArgumentTypes[declaredArgumentTypes.length - 1],
113 new RoleDiagnostic(RoleDiagnostic.FUNCTION, getFunctionName().getDisplayName(), i),
114 visitor));
115
116 actualArgumentTypes[i] = SequenceType.makeSequenceType(
117 getArg(i).getItemType(),
118 getArg(i).getCardinality());
119 }
120 resultType = definition.getResultType(actualArgumentTypes);
121 if (state == 0) {
122 function.supplyStaticContext(visitor.getStaticContext(), 0, getArguments());
123 }
124 state++;
125 }
126
127 /**
128 * Type-check the expression.
129 */
130
131 /*@NotNull*/
132 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
133 Expression exp = super.typeCheck(visitor, contextInfo);
134 if (exp instanceof IntegratedFunctionCall) {
135 Expression exp2 = ((IntegratedFunctionCall) exp).function.rewrite(visitor.getStaticContext(), getArguments());
136 if (exp2 == null) {
137 return exp;
138 } else {
139 ExpressionTool.copyLocationInfo(this, exp2);
140 return exp2.simplify().typeCheck(visitor, contextInfo).optimize(visitor, contextInfo);
141 }
142 }
143 return exp;
144 }
145
146 /**
147 * Pre-evaluate a function at compile time. This function does not allow
148 * pre-evaluation, so the method returns null.
149 *
150 * @param visitor an expression visitor
151 * @return for this class: always null
152 */
153
154 public Expression preEvaluate(ExpressionVisitor visitor) {
155 return this;
156 }
157
158 /**
159 * Determine the data type of the expression, if possible. All expression return
160 * sequences, in general; this method determines the type of the items within the
161 * sequence, assuming that (a) this is known in advance, and (b) it is the same for
162 * all items in the sequence.
163 * <p>This method should always return a result, though it may be the best approximation
164 * that is available at the time.</p>
165 *
166 * @return a value such as Type.STRING, Type.BOOLEAN, Type.NUMBER,
167 * Type.NODE, or Type.ITEM (meaning not known at compile time)
168 */
169
170 /*@NotNull*/
171 public ItemType getItemType() {
172 return resultType.getPrimaryType();
173 }
174
175 /**
176 * Compute the static cardinality of this expression
177 *
178 * @return the computed cardinality, as one of the values {@link net.sf.saxon.expr.StaticProperty#ALLOWS_ZERO_OR_ONE},
179 * {@link net.sf.saxon.expr.StaticProperty#EXACTLY_ONE}, {@link net.sf.saxon.expr.StaticProperty#ALLOWS_ONE_OR_MORE},
180 * {@link net.sf.saxon.expr.StaticProperty#ALLOWS_ZERO_OR_MORE}
181 */
182
183 protected int computeCardinality() {
184 return resultType.getCardinality();
185 }
186
187 /**
188 * Determine the intrinsic dependencies of an expression, that is, those which are not derived
189 * from the dependencies of its subexpressions. For example, position() has an intrinsic dependency
190 * on the context position, while (position()+1) does not. The default implementation
191 * of the method returns 0, indicating "no dependencies".
192 *
193 * @return a set of bit-significant flags identifying the "intrinsic"
194 * dependencies. The flags are documented in class net.sf.saxon.value.StaticProperty
195 */
196
197 public int getIntrinsicDependencies() {
198 ExtensionFunctionDefinition definition = function.getDefinition();
199 return definition.dependsOnFocus() ? StaticProperty.DEPENDS_ON_FOCUS : 0;
200 }
201
202 /**
203 * Compute the special properties of this expression. These properties are denoted by a bit-significant
204 * integer, possible values are in class {@link net.sf.saxon.expr.StaticProperty}. The "special" properties are properties
205 * other than cardinality and dependencies, and most of them relate to properties of node sequences, for
206 * example whether the nodes are in document order.
207 *
208 * @return the special properties, as a bit-significant integer
209 */
210
211 protected int computeSpecialProperties() {
212 ExtensionFunctionDefinition definition = function.getDefinition();
213 return definition.hasSideEffects() ? StaticProperty.HAS_SIDE_EFFECTS : StaticProperty.NO_NODES_NEWLY_CREATED;
214 }
215
216 /**
217 * Copy an expression. This makes a deep copy.
218 *
219 * @return the copy of the original expression
220 * @param rebindings Variables that need to be re-bound
221 */
222
223 /*@NotNull*/
224 public Expression copy(RebindingMap rebindings) {
225 ExtensionFunctionCall newCall = function.getDefinition().makeCallExpression();
226 newCall.setDefinition(function.getDefinition());
227 function.copyLocalData(newCall);
228 IntegratedFunctionCall copy = new IntegratedFunctionCall(getFunctionName(), newCall);
229 Expression[] args = new Expression[getArity()];
230 for (int i = 0; i < args.length; i++) {
231 args[i] = getArg(i).copy(rebindings);
232 }
233 copy.setArguments(args);
234 copy.resultType = resultType;
235 copy.state = state;
236 ExpressionTool.copyLocationInfo(this, copy);
237 return copy;
238 }
239
240 /**
241 * Diagnostic print of expression structure. The abstract expression tree
242 * is written to the supplied output destination.
243 */
244
245 public void export(ExpressionPresenter out) throws XPathException {
246 out.startElement("ifCall", this);
247 out.emitAttribute("name", getFunctionName());
248 out.emitAttribute("type", resultType.toExportString());
249 for (Operand o : operands()) {
250 o.getChildExpression().export(out);
251 }
252 out.endElement();
253 }
254
255
256 /**
257 * Return an Iterator to iterate over the values of a sequence. The value of every
258 * expression can be regarded as a sequence, so this method is supported for all
259 * expressions. This default implementation handles iteration for expressions that
260 * return singleton values: for non-singleton expressions, the subclass must
261 * provide its own implementation.
262 *
263 * @param context supplies the context for evaluation
264 * @return a SequenceIterator that can be used to iterate over the result
265 * of the expression
266 * @throws net.sf.saxon.trans.XPathException
267 * if any dynamic error occurs evaluating the
268 * expression
269 */
270
271 /*@NotNull*/
272 public SequenceIterator<?> iterate(final XPathContext context) throws XPathException {
273 ExtensionFunctionDefinition definition = function.getDefinition();
274 Sequence[] argValues = new Sequence[getArity()];
275 for (int i = 0; i < argValues.length; i++) {
276 argValues[i] = SequenceTool.toLazySequence(getArg(i).iterate(context));
277 }
278 final RoleDiagnostic role = new RoleDiagnostic(RoleDiagnostic.FUNCTION_RESULT, getFunctionName().getDisplayName(), 0);
279 final Configuration config = context.getConfiguration();
280 final TypeHierarchy th = config.getTypeHierarchy();
281
282 SequenceIterator<?> result;
283 try {
284 result = function.call(context, argValues).iterate();
285 } catch (XPathException e) {
286 e.maybeSetLocation(getLocation());
287 throw e;
288 }
289 if (!definition.trustResultType()) {
290 int card = resultType.getCardinality();
291 if (card != StaticProperty.ALLOWS_ZERO_OR_MORE) {
292 result = new CardinalityCheckingIterator<>(result, card, role, getLocation());
293 }
294 final ItemType type = resultType.getPrimaryType();
295 if (type != AnyItemType.getInstance()) {
296 result = new ItemMappingIterator<>(result,
297 (ItemMappingFunction<Item<?>, Item<?>>) item -> {
298 if (!type.matches(item, th)) {
299 String msg = role.composeErrorMessage(type, item, th);
300 XPathException err = new XPathException(msg, "XPTY0004");
301 err.setLocation(getLocation());
302 throw err;
303 }
304 return item;
305 }, true);
306 }
307 if (th.relationship(type, AnyNodeTest.getInstance()) != TypeHierarchy.DISJOINT) {
308 result = new ItemMappingIterator<>(
309 result,
310 new ConfigurationCheckingFunction(context.getConfiguration()), true);
311 }
312 }
313 return result;
314 }
315
316 /**
317 * Get the effective boolean value of the expression. This returns false if the value
318 * is the empty sequence, a zero-length string, a number equal to zero, or the boolean
319 * false. Otherwise it returns true.
320 *
321 * @param context The context in which the expression is to be evaluated
322 * @return the effective boolean value
323 * @throws net.sf.saxon.trans.XPathException
324 * if any dynamic error occurs evaluating the
325 * expression
326 */
327
328 public boolean effectiveBooleanValue(XPathContext context) throws XPathException {
329 Sequence[] argValues = new Sequence[getArity()];
330 for (int i = 0; i < argValues.length; i++) {
331 argValues[i] = SequenceTool.toLazySequence(getArg(i).iterate(context));
332 }
333 try {
334 return function.effectiveBooleanValue(context, argValues);
335 } catch (XPathException e) {
336 e.maybeSetLocation(getLocation());
337 throw e;
338 }
339 }
340
341 public Sequence<?> call(XPathContext context, Sequence[] arguments) throws XPathException {
342 return function.call(context, arguments);
343 }
344
345
346 /**
347 * This class checks that NodeInfo objects returned by an extension function were created
348 * under the right Configuration
349 */
350
351 public static class ConfigurationCheckingFunction implements ItemMappingFunction<Item<?>, Item<?>> {
352
353 private Configuration config;
354
355 public ConfigurationCheckingFunction(Configuration config) {
356 this.config = config;
357 }
358
359 /**
360 * Map one item to another item.
361 *
362 * @param item The input item to be mapped.
363 * @return either the output item, or null.
364 */
365
366 public Item mapItem(Item item) throws XPathException {
367 if (item instanceof NodeInfo && !config.isCompatible(((NodeInfo) item).getConfiguration())) {
368 throw new XPathException(
369 "Node returned by extension function was created with an incompatible Configuration", SaxonErrorCode.SXXP0004);
370 }
371 return item;
372 }
373 }
374 }
375