Debian Codegraph @

net/sf/saxon/functions/registry/BuiltInFunctionSet.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.registry;
9
10 import net.sf.saxon.expr.Expression;
11 import net.sf.saxon.expr.OperandUsage;
12 import net.sf.saxon.expr.StaticContext;
13 import net.sf.saxon.expr.StaticProperty;
14 import net.sf.saxon.expr.parser.RetainedStaticContext;
15 import net.sf.saxon.functions.FunctionLibrary;
16 import net.sf.saxon.functions.OptionsParameter;
17 import net.sf.saxon.functions.SystemFunction;
18 import net.sf.saxon.lib.NamespaceConstant;
19 import net.sf.saxon.om.Function;
20 import net.sf.saxon.om.Item;
21 import net.sf.saxon.om.Sequence;
22 import net.sf.saxon.om.StructuredQName;
23 import net.sf.saxon.trans.SymbolicName;
24 import net.sf.saxon.trans.XPathException;
25 import net.sf.saxon.type.ItemType;
26 import net.sf.saxon.type.PlainType;
27 import net.sf.saxon.value.AtomicValue;
28 import net.sf.saxon.value.EmptySequence;
29 import net.sf.saxon.value.SequenceType;
30
31 import java.util.HashMap;
32 import java.util.List;
33
34 /**
35 * This class is used to contain information about a set of built-in functions.
36 */
37 public abstract class BuiltInFunctionSet implements FunctionLibrary {
38
39 public static Sequence<?> EMPTY = EmptySequence.getInstance();
40
41 /**
42 * Categories of functions, bit significant
43 */
44
45 public static final int CORE = 1;
46 public static final int XSLT = 2;
47 public static final int USE_WHEN = 4;
48 public static final int XQUPDATE = 8;
49 public static final int XPATH30 = 16;
50 public static final int INTERNAL = 32;
51 public static final int XSLT30 = 64;
52 public static final int XPATH31 = 128;
53 public static final int HOF = 256;
54
55 /**
56 * Local names used for cardinality values
57 */
58
59 public static final int ONE = StaticProperty.ALLOWS_ONE;
60 public static final int OPT = StaticProperty.ALLOWS_ZERO_OR_ONE;
61 public static final int STAR = StaticProperty.ALLOWS_ZERO_OR_MORE;
62 public static final int PLUS = StaticProperty.ALLOWS_ONE_OR_MORE;
63
64 /**
65 * Function properties
66 */
67
68 public static final int AS_ARG0 = 1; // Result has same type as first argument
69 public static final int AS_PRIM_ARG0 = 2; // Result has same primitive type as first argument
70 public static final int CITEM = 4; // Depends on context item
71 public static final int BASE = 8; // Depends on base URI
72 public static final int NS = 16; // Depends on namespace context
73 public static final int DCOLL = 32; // Depends on default collation
74 public static final int DLANG = 64; // Depends on default language
75 public static final int FILTER = 256; // Result is a subset of the value of the first arg
76 public static final int LATE = 512; // Disallow compile-time evaluation
77 public static final int UO = 1024; // Ordering in first argument is irrelevant
78 public static final int POSN = 1024*2; // Depends on position
79 public static final int LAST = 1024*4; // Depends on last
80 public static final int SIDE = 1024*8; // Has side-effects
81 public static final int CDOC = 1024*16; // Depends on context document
82 public static final int CARD0 = 1024*32; // Result is empty only if first arg is empty
83 public static final int NEW = 1024*64; // All nodes in the result are newly created
84
85 public static final int DEPENDS_ON_STATIC_CONTEXT = BASE | NS | DCOLL;
86 public static final int FOCUS = CITEM | POSN | LAST | CDOC;
87
88
89 /**
90 * Classification of function arguments for serialization purposes; note that values must not conflict
91 * with bit settings used for cardinalities
92 */
93
94 public static final int INS = 1 << 24; // = usage INSPECTION
95 public static final int ABS = 1 << 25; // = usage ABSORPTION (implicit when type is atomic)
96 public static final int TRA = 1 << 26; // = usage TRANSMISSION (node is included in function result)
97 public static final int NAV = 1 << 27; // = usage NAVIGATION (function navigates from this node)
98
99
100 private HashMap<String, Entry> functionTable = new HashMap<>(200);
101 //private List<BuiltInFunctionSet> importedFunctions = new ArrayList<BuiltInFunctionSet>();
102
103 /**
104 * Import another function set (which must be in the same namespace)
105 * @param importee the function set to be imported. (No cycles allowed!)
106 */
107
108 public final void importFunctionSet(BuiltInFunctionSet importee) {
109 if (!importee.getNamespace().equals(getNamespace())) {
110 throw new IllegalArgumentException(importee.getNamespace());
111 }
112 functionTable.putAll(importee.functionTable);
113 //importedFunctions.add(importee);
114 }
115
116 /**
117 * Locate the entry for a function with a given name and arity, if it exists
118 * @param name the local part of the function name
119 * @param arity the arity of the function. -1 considers all possibly arities and returns an arbitrary function
120 * if one exists with the right name.
121 * @return the entry for the required function, or null if not found
122 */
123
124 public Entry getFunctionDetails(String name, int arity) {
125 if (arity == -1) {
126 for (int i=0; i<20; i++) {
127 Entry found = getFunctionDetails(name, i);
128 if (found != null) {
129 return found;
130 }
131 }
132 return null;
133 }
134 String key = name + "#" + arity;
135 Entry entry = functionTable.get(key);
136 if (entry != null) {
137 return entry;
138 }
139 // Try for a variable-arity function (concat only)
140 if (name.equals("concat") && arity >= 2 && getNamespace().equals(NamespaceConstant.FN)) {
141 key = "concat#-1";
142 entry = functionTable.get(key);
143 if (entry != null) {
144 return entry;
145 }
146 }
147 // for (BuiltInFunctionSet lib : importedFunctions) {
148 // entry = lib.getFunctionDetails(name, arity);
149 // if (entry != null) {
150 // return entry;
151 // }
152 // }
153 return null;
154 }
155
156 /**
157 * Bind a function, given the URI and local parts of the function name,
158 * and the list of expressions supplied as arguments. This method is called at compile
159 * time.
160 *
161 * @param symbolicName the symbolic name of the function being called
162 * @param staticArgs May be null; if present, the length of the array must match the
163 * value of arity. Contains the expressions supplied statically in arguments to the function call.
164 * The intention is
165 * that the static type of the arguments (obtainable via getItemType() and getCardinality()) may
166 * be used as part of the binding algorithm. In some cases it may be possible for the function
167 * to be pre-evaluated at compile time, for example if these expressions are all constant values.
168 * <p>The conventions of the XPath language demand that the results of a function depend only on the
169 * values of the expressions supplied as arguments, and not on the form of those expressions. For
170 * example, the result of f(4) is expected to be the same as f(2+2). The actual expression is supplied
171 * here to enable the binding mechanism to select the most efficient possible implementation (including
172 * compile-time pre-evaluation where appropriate).</p>
173 * @param env The static context of the function call
174 * @param reasons If no matching function is found by the function library, it may add
175 * a diagnostic explanation to this list explaining why none of the available
176 * functions could be used.
177 * @return An expression equivalent to a call on the specified function, if one is found;
178 * null if no function was found matching the required name and arity.
179 */
180 @Override
181 public Expression bind(SymbolicName.F symbolicName, Expression[] staticArgs, StaticContext env, List<String> reasons) {
182 StructuredQName functionName = symbolicName.getComponentName();
183 int arity = symbolicName.getArity();
184 String localName = functionName.getLocalPart();
185 if (functionName.hasURI(getNamespace()) && getFunctionDetails(localName, arity) != null) {
186 RetainedStaticContext rsc = new RetainedStaticContext(env);
187 try {
188 SystemFunction fn = makeFunction(localName, arity);
189 fn.setRetainedStaticContext(rsc);
190 Expression f = fn.makeFunctionCall(staticArgs);
191 f.setRetainedStaticContext(rsc);
192 return f;
193 } catch (XPathException e) {
194 reasons.add(e.getMessage());
195 return null;
196 }
197 } else {
198 return null;
199 }
200 }
201
202 public SystemFunction makeFunction(String name, int arity) throws XPathException {
203 Entry entry = getFunctionDetails(name, arity);
204 if (entry == null) {
205 String diagName = getNamespace().equals(NamespaceConstant.FN) ?
206 "System function " + name :
207 "Function Q{" + getNamespace() + "}" + name;
208 if (getFunctionDetails(name, -1) == null) {
209 XPathException err = new XPathException(diagName + "() does not exist or is not available in this environment");
210 err.setErrorCode("XPST0017");
211 err.setIsStaticError(true);
212 throw err;
213 } else {
214 XPathException err = new XPathException(diagName + "() cannot be called with "
215 + pluralArguments(arity));
216 err.setErrorCode("XPST0017");
217 err.setIsStaticError(true);
218 throw err;
219 }
220 }
221
222 Class functionClass = entry.implementationClass;
223 SystemFunction f;
224 try {
225 f = (SystemFunction) functionClass.newInstance();
226 } catch (Exception err) {
227 err.printStackTrace();
228 throw new AssertionError("Failed to instantiate system function " + name + " - " + err.getMessage());
229 }
230 f.setDetails(entry);
231 f.setArity(arity);
232 return f;
233 }
234
235 /**
236 * Utility routine used in constructing error messages
237 *
238 * @param num the number of arguments
239 * @return the string " argument" or "arguments" depending whether num is plural
240 */
241
242 private static String pluralArguments(int num) {
243 if (num == 0) {
244 return "zero arguments";
245 }
246 if (num == 1) {
247 return "one argument";
248 }
249 return num + " arguments";
250 }
251
252 /**
253 * Test whether a function with a given name and arity is available
254 * <p>This supports the function-available() function in XSLT.</p>
255 *
256 * @param symbolicName the qualified name of the function being called, together with its arity.
257 * For legacy reasons, the arity may be set to -1 to mean any arity will do
258 * @return true if a function of this name and arity is available for calling
259 */
260 @Override
261 public boolean isAvailable(SymbolicName.F symbolicName) {
262 StructuredQName qn = symbolicName.getComponentName();
263 return qn.hasURI(getNamespace()) && getFunctionDetails(qn.getLocalPart(), symbolicName.getArity()) != null;
264 }
265
266 /**
267 * This method creates a copy of a FunctionLibrary: if the original FunctionLibrary allows
268 * new functions to be added, then additions to this copy will not affect the original, or
269 * vice versa.
270 *
271 * @return a copy of this function library. This must be an instance of the original class.
272 */
273 @Override
274 public FunctionLibrary copy() {
275 return this;
276 }
277
278 //#ifdefined HOF
279 /**
280 * Test whether a function with a given name and arity is available; if so, return a function
281 * item that can be dynamically called.
282 * <p>This supports the function-lookup() function in XPath 3.0.</p>
283 *
284 * @param symbolicName the qualified name of the function being called
285 * @param staticContext the static context to be used by the function, in the event that
286 * it is a system function with dependencies on the static context
287 * @return if a function of this name and arity is available for calling, then a corresponding
288 * function item; or null if the function does not exist
289 * @throws XPathException in the event of certain errors, for example attempting to get a function
290 * that is private
291 */
292 @Override
293 public Function getFunctionItem(SymbolicName.F symbolicName, StaticContext staticContext) throws XPathException {
294 StructuredQName functionName = symbolicName.getComponentName();
295 int arity = symbolicName.getArity();
296 if (functionName.hasURI(getNamespace()) && getFunctionDetails(functionName.getLocalPart(), arity) != null) {
297 RetainedStaticContext rsc = staticContext.makeRetainedStaticContext();
298 SystemFunction fn = makeFunction(functionName.getLocalPart(), arity);
299 fn.setRetainedStaticContext(rsc);
300 return fn;
301 } else {
302 return null;
303 }
304 }
305 //#endif
306
307 /**
308 * Register a system function in the table of function details.
309 *
310 * @param name the function name
311 * @param implementationClass the class used to implement the function
312 * @param itemType the item type of the result of the function
313 * @param cardinality the cardinality of the result of the function
314 * @param applicability the host languages (and versions thereof) in which this function is available
315 * @param properties bitwise properties of the function
316 * @return the entry describing the function. The entry is incomplete, it does not yet contain information
317 * about the function arguments.
318 */
319
320 /*@NotNull*/
321 protected Entry register(String name,
322 int arity,
323 Class<? extends SystemFunction> implementationClass,
324 ItemType itemType,
325 int cardinality,
326 int applicability,
327 int properties) {
328 Entry e = new Entry();
329 e.name = new StructuredQName(getConventionalPrefix(), getNamespace(), name);
330 e.arity = arity;
331 e.implementationClass = implementationClass;
332 e.itemType = itemType;
333 e.cardinality = cardinality;
334 e.applicability = applicability;
335 e.properties = properties;
336 if (e.arity == -1) {
337 // special case for concat()
338 e.argumentTypes = new SequenceType[1];
339 e.resultIfEmpty = new AtomicValue[1];
340 e.usage = new OperandUsage[1];
341 } else {
342 e.argumentTypes = new SequenceType[arity];
343 e.resultIfEmpty = (Sequence<?>[])new Sequence[arity];
344 e.usage = new OperandUsage[arity];
345 }
346 functionTable.put(name + "#" + arity, e);
347 return e;
348 }
349
350 /**
351 * Register reduced-arity versions of a function, with arities in a specified range,
352 * using common argument and return types
353 */
354
355 protected void registerReducedArityVariants(String key, int min, int max) {
356 Entry master = functionTable.get(key);
357 for (int arity = min; arity <= max; arity++) {
358 Entry e = new Entry();
359 e.name = master.name;
360 e.arity = arity;
361 e.implementationClass = master.implementationClass;
362 e.itemType = master.itemType;
363 e.cardinality = master.cardinality;
364 e.applicability = master.applicability;
365 e.properties = master.properties;
366 e.argumentTypes = new SequenceType[arity];
367 e.resultIfEmpty = (Sequence<?>[])new Sequence[arity];
368 e.usage = new OperandUsage[arity];
369 for (int i=0; i<arity; i++) {
370 e.argumentTypes[i] = master.argumentTypes[i];
371 e.resultIfEmpty[i] = master.resultIfEmpty[i];
372 e.usage[i] = master.usage[i];
373 }
374 functionTable.put(e.name.getLocalPart() + "#" + arity, e);
375 }
376 }
377
378 /**
379 * Return the namespace URI for the functions local to this function set.
380 * @return the namespace URI of the functions local to this function set.
381 * Note that functions imported from another function set may have a different
382 * namespace URI.
383 */
384
385 public String getNamespace() {
386 return NamespaceConstant.FN;
387 }
388
389 /**
390 * Return a conventional prefix for use with this namespace, typically
391 * the prefix used in the documentation of these functions.
392 */
393
394 public String getConventionalPrefix() {
395 return "fn";
396 }
397
398 /**
399 * An entry in the table describing the properties of a function
400 */
401 public static class Entry implements java.io.Serializable {
402 /**
403 * The name of the function as a QName
404 */
405 public StructuredQName name;
406 /**
407 * The class containing the implementation of this function (always a subclass of SystemFunction)
408 */
409 public Class implementationClass;
410 /**
411 * The arity of the function
412 */
413 public int arity;
414 /**
415 * The item type of the result of the function
416 */
417 public ItemType itemType;
418 /**
419 * The cardinality of the result of the function
420 */
421 public int cardinality;
422 /**
423 * Flags indicating which host languages the function is applicable to
424 */
425 public int applicability;
426 /**
427 * The syntactic context of each argument for the purposes of streamability analysis
428 */
429 public OperandUsage[] usage;
430 /**
431 * An array holding the types of the arguments to the function
432 */
433 public SequenceType[] argumentTypes;
434 /**
435 * An array holding, for each declared argument, the value that is to be returned if an empty sequence
436 * as the value of this argument allows the result to be determined irrespective of the values of the
437 * other arguments; null if there is no such calculation possible
438 */
439 public Sequence<?>[] resultIfEmpty;
440 /**
441 * Any additional properties. Various bit settings are defined: for example SAME_AS_FIRST_ARGUMENT indicates that
442 * the result type is the same as the type of the first argument
443 */
444 public int properties;
445 /**
446 * For options parameters, details of the accepted options, their defaults, and required type
447 */
448 public OptionsParameter optionDetails;
449 /**
450 * Class used to provide a streaming implementation of the function
451 */
452 public Class streamingAdjunct;
453
454 /**
455 * Add information to a function entry about the argument types of the function
456 *
457 * @param a the position of the argument, counting from zero
458 * @param type the item type of the argument
459 * @param options the cardinality and usage of the argument
460 * @param resultIfEmpty the value returned by the function if an empty sequence appears as the value
461 * of this argument, in the case when this result is unaffected by any other arguments. Supply null
462 * if this does not apply.
463 * @return this entry (to allow chaining)
464 */
465
466 public Entry arg(int a, ItemType type, int options, Sequence<?> resultIfEmpty) {
467 int cardinality = options & StaticProperty.CARDINALITY_MASK;
468 OperandUsage usage = OperandUsage.NAVIGATION;
469 if ((options & ABS) != 0) {
470 usage = OperandUsage.ABSORPTION;
471 } else if ((options & TRA) != 0) {
472 usage = OperandUsage.TRANSMISSION;
473 } else if ((options & INS) != 0) {
474 usage = OperandUsage.INSPECTION;
475 } else if (type instanceof PlainType) {
476 usage = OperandUsage.ABSORPTION;
477 }
478 try {
479 this.argumentTypes[a] = SequenceType.makeSequenceType(type, cardinality);
480 this.resultIfEmpty[a] = resultIfEmpty;
481 this.usage[a] = usage;
482 } catch (ArrayIndexOutOfBoundsException err) {
483 System.err.println("Internal Saxon error: Can't set argument " + a + " of " + name);
484 }
485 return this;
486 }
487
488 /**
489 * Add details for options parameters (only applies to one argument, the function is expected to know which)
490 */
491
492 public Entry optionDetails(OptionsParameter details) {
493 this.optionDetails = details;
494 return this;
495 }
496
497 /**
498 * Define the class to be used to provide a streaming implementation of the function
499 */
500
501 public void setStreamingAdjunctClass(Class streamer) {
502 this.streamingAdjunct = streamer;
503 }
504
505 }
506
507
508 }
509