Debian Codegraph @

net/sf/saxon/query/XQueryFunctionLibrary.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.query;
9
10 import com.saxonica.functions.hof.UnresolvedXQueryFunctionItem;
11 import com.saxonica.functions.hof.UserFunctionReference;
12 import net.sf.saxon.Configuration;
13 import net.sf.saxon.expr.*;
14 import net.sf.saxon.expr.instruct.UserFunction;
15 import net.sf.saxon.expr.parser.ExpressionVisitor;
16 import net.sf.saxon.functions.FunctionLibrary;
17 import net.sf.saxon.om.*;
18 import net.sf.saxon.trace.ExpressionPresenter;
19 import net.sf.saxon.trans.SymbolicName;
20 import net.sf.saxon.trans.XPathException;
21 import net.sf.saxon.type.FunctionItemType;
22 import net.sf.saxon.type.SpecificFunctionType;
23
24 import java.util.HashMap;
25 import java.util.Iterator;
26 import java.util.List;
27
28 /**
29 * An XQueryFunctionLibrary is a function library containing all the user-defined functions available for use within a
30 * particular XQuery module: that is, the functions declared in that module, and the functions imported from other
31 * modules. It also contains (transiently during compilation) a list of function calls within the module that have not
32 * yet been bound to a specific function declaration.
33 */
34
35 public class XQueryFunctionLibrary implements FunctionLibrary, XQueryFunctionBinder {
36
37 private Configuration config;
38
39 // The functions in this library are represented using a HashMap
40 // The key of the hashmap is an object that encodes the QName of the function and its arity
41 // The value in the hashmap is an XQueryFunction
42 /*@NotNull*/ private HashMap<SymbolicName, XQueryFunction> functions =
43 new HashMap<>(20);
44
45 /**
46 * Create an XQueryFunctionLibrary
47 *
48 * @param config the Saxon configuration
49 */
50
51 public XQueryFunctionLibrary(Configuration config) {
52 this.config = config;
53 }
54
55 /**
56 * Set the Configuration options
57 *
58 * @param config the Saxon configuration
59 */
60
61 public void setConfiguration(Configuration config) {
62 this.config = config;
63 }
64
65 /**
66 * Get the Configuration options
67 *
68 * @return the Saxon configuration
69 */
70
71 public Configuration getConfiguration() {
72 return config;
73 }
74
75 /**
76 * Register a user-defined XQuery function
77 *
78 * @param function the function to be registered
79 * @throws XPathException if there is an existing function with the same name and arity
80 */
81
82 public void declareFunction(/*@NotNull*/ XQueryFunction function) throws XPathException {
83 SymbolicName keyObj = function.getIdentificationKey();
84 XQueryFunction existing = functions.get(keyObj);
85 if (existing == function) {
86 return;
87 }
88 if (existing != null) {
89 XPathException err = new XPathException("Duplicate definition of function " +
90 function.getDisplayName() +
91 " (see line " + existing.getLineNumber() + " in " + existing.getSystemId() + ')');
92 err.setErrorCode("XQST0034");
93 err.setIsStaticError(true);
94 err.setLocator(function);
95 throw err;
96 }
97 functions.put(keyObj, function);
98 }
99
100 //#ifdefined HOF
101
102 /**
103 * Test whether a function with a given name and arity is available; if so, return a function
104 * item that can be dynamically called.
105 * <p>This supports the function-lookup() function in XPath 3.0.</p>
106 *
107 * @param functionName the qualified name of the function being called
108 * @param staticContext the static context to be used by the function, in the event that
109 * it is a system function with dependencies on the static context
110 * @return if a function of this name and arity is available for calling, then a corresponding
111 * function item; or null if the function does not exist
112 */
113 public Function getFunctionItem(SymbolicName.F functionName, StaticContext staticContext)
114 throws XPathException {
115 XQueryFunction fd = functions.get(functionName);
116 if (fd != null) {
117 if (fd.isPrivate() && !fd.getSystemId().equals(staticContext.getStaticBaseURI())) {
118 throw new XPathException("Cannot call the private function " +
119 functionName.getComponentName().getDisplayName() + " from outside its module", "XPST0017");
120 }
121 final UserFunction fn = fd.getUserFunction();
122 FunctionItemType type = new SpecificFunctionType(
123 fd.getArgumentTypes(), fd.getResultType(), fd.getAnnotations());
124 if (fn == null) {
125 // not yet compiled: create a dummy
126 UserFunction uf = new UserFunction();
127 uf.setFunctionName(functionName.getComponentName());
128 uf.setResultType(fd.getResultType());
129 uf.setParameterDefinitions(fd.getParameterDefinitions());
130 final UserFunctionReference ref = new UserFunctionReference(uf);
131 fd.registerReference(ref);
132 return new UnresolvedXQueryFunctionItem(fd, functionName, ref);
133
134 } else {
135 return fn;
136 }
137 } else {
138 return null;
139 }
140 }
141 //#endif
142
143
144 /**
145 * Test whether a function with a given name and arity is available
146 * <p>This supports the function-available() function in XSLT.</p>
147 *
148 * @param functionName the qualified name of the function being called
149 * @return true if a function of this name and arity is available for calling
150 */
151 public boolean isAvailable(SymbolicName.F functionName) {
152 return functions.get(functionName) != null;
153 }
154
155 /**
156 * Inner class containing information about a reference to a function whose declaration
157 * has not yet been encountered. The references gets fixed up later, once information
158 * about all user-declared functions is available.
159 */
160
161 public static class UnresolvedCallable implements UserFunctionResolvable, Callable {
162 SymbolicName.F symbolicName;
163 UserFunction function;
164
165 public UnresolvedCallable(SymbolicName.F symbolicName) {
166 this.symbolicName = symbolicName;
167 }
168
169 public StructuredQName getFunctionName() {
170 return symbolicName.getComponentName();
171 }
172
173 public int getArity() {
174 return symbolicName.getArity();
175 }
176
177 //public void setFunctionItem(CallableFunctionItem fi) {
178 // this.functionItem = fi;
179 //}
180
181 /**
182 * Evaluate the expression
183 *
184 * @param context the dynamic evaluation context
185 * @param arguments the values of the arguments, supplied as Sequences
186 * @return the result of the evaluation, in the form of a Sequence
187 * @throws net.sf.saxon.trans.XPathException
188 * if a dynamic error occurs during the evaluation of the expression
189 */
190 public Sequence<?> call(XPathContext context, Sequence<?>[] arguments) throws XPathException {
191 if (function == null) {
192 throw new XPathException("Forwards reference to XQuery function has not been resolved");
193 }
194 Sequence[] args = new Sequence[arguments.length];
195 for (int i = 0; i < arguments.length; i++) {
196 args[i] = ((SequenceIterator<?>) arguments[i].iterate()).materialize();
197 }
198 return function.call(context.newCleanContext(), args);
199 }
200
201 public void setFunction(UserFunction function) {
202 this.function = function;
203 }
204
205 public UserFunction getFunction() {
206 return function;
207 }
208 }
209
210 /**
211 * Identify a (namespace-prefixed) function appearing in the expression. This
212 * method is called by the XQuery parser to resolve function calls found within
213 * the query.
214 * <p>Note that a function call may appear earlier in the query than the definition
215 * of the function to which it is bound. Unlike XSLT, we cannot search forwards to
216 * find the function definition. Binding of function calls is therefore a two-stage
217 * process; at the time the function call is parsed, we simply register it as
218 * pending; subsequently at the end of query parsing all the pending function
219 * calls are resolved. Another consequence of this is that we cannot tell at the time
220 * a function call is parsed whether it is a call to an internal (XSLT or XQuery)
221 * function or to an extension function written in Java.
222 *
223 * @return an Expression representing the function call. This will normally be
224 * a FunctionCall, but it may be rewritten as some other expression.
225 */
226
227 /*@Nullable*/
228 public Expression bind(/*@NotNull*/ SymbolicName.F functionName, /*@NotNull*/ Expression[] arguments, StaticContext env, List<String> reasons) {
229 XQueryFunction fd = functions.get(functionName);
230 if (fd != null) {
231 if (fd.isPrivate() && fd.getStaticContext() != env) {
232 reasons.add("Cannot call the private XQuery function " +
233 functionName.getComponentName().getDisplayName() + " from outside its module");
234 return null;
235 }
236 UserFunctionCall ufc = new UserFunctionCall();
237 ufc.setFunctionName(fd.getFunctionName());
238 ufc.setArguments(arguments);
239 ufc.setStaticType(fd.getResultType());
240 UserFunction fn = fd.getUserFunction();
241 if (fn == null) {
242 // not yet compiled
243 fd.registerReference(ufc);
244 } else {
245 ufc.setFunction(fn);
246 }
247 return ufc;
248 } else {
249 return null;
250 }
251 }
252
253 /**
254 * Get the function declaration corresponding to a given function name and arity
255 *
256 * @return the XQueryFunction if there is one, or null if not.
257 */
258
259 public XQueryFunction getDeclaration(StructuredQName functionName, int staticArgs) {
260 SymbolicName functionKey = XQueryFunction.getIdentificationKey(
261 functionName, staticArgs);
262 return functions.get(functionKey);
263 }
264
265 /**
266 * Get the function declaration corresponding to a given function name and arity, supplied
267 * in the form "{uri}local/arity"
268 *
269 * @param functionKey a string in the form "{uri}local/arity" identifying the required function
270 * @return the XQueryFunction if there is one, or null if not.
271 */
272
273 public XQueryFunction getDeclarationByKey(SymbolicName functionKey) {
274 return functions.get(functionKey);
275 }
276
277 /**
278 * Get an iterator over the Functions defined in this module
279 *
280 * @return an Iterator, whose items are {@link XQueryFunction} objects. It returns
281 * all function known to this module including those imported from elsewhere; they
282 * can be distinguished by their namespace.
283 */
284
285 public Iterator<XQueryFunction> getFunctionDefinitions() {
286 return functions.values().iterator();
287 }
288
289 /**
290 * Fixup all references to global functions. This method is called
291 * on completion of query parsing. Each XQueryFunction is required to
292 * bind all references to that function to the object representing the run-time
293 * executable code of the function.
294 * <p>This method is for internal use.</p>
295 *
296 * @param env the static context for the main query body.
297 * @throws net.sf.saxon.trans.XPathException
298 * if an error occurs
299 */
300
301 protected void fixupGlobalFunctions(/*@NotNull*/ QueryModule env) throws XPathException {
302 ExpressionVisitor visitor = ExpressionVisitor.make(env);
303 for (XQueryFunction fn : functions.values()) {
304 fn.compile();
305 }
306 for (XQueryFunction fn : functions.values()) {
307 fn.checkReferences(visitor);
308 }
309 }
310
311 /**
312 * Optimize the body of all global functions. This may involve inlining functions calls
313 *
314 * @throws net.sf.saxon.trans.XPathException
315 * if an error occurs
316 * @param topModule the top level module of the compilation unit whose functions are
317 * to be optimized; functions in separately-compiled imported libraries
318 * are unaffected.
319 */
320
321 protected void optimizeGlobalFunctions(QueryModule topModule) throws XPathException {
322 for (XQueryFunction fn : functions.values()) {
323 if (((QueryModule)fn.getStaticContext()).getTopLevelModule() == topModule) {
324 fn.optimize();
325 }
326 }
327 }
328
329
330 /**
331 * Output "explain" information about each declared function
332 *
333 * @param out the ExpressionPresenter that renders the output
334 */
335
336 public void explainGlobalFunctions(/*@NotNull*/ ExpressionPresenter out) throws XPathException {
337 for (XQueryFunction fn : functions.values()) {
338 fn.explain(out);
339 }
340 }
341
342 /**
343 * Get the function with a given name and arity. This method is provided so that XQuery functions
344 * can be called directly from a Java application. Note that there is no type checking or conversion
345 * of arguments when this is done: the arguments must be provided in exactly the form that the function
346 * signature declares them.
347 *
348 * @param uri the uri of the function name
349 * @param localName the local part of the function name
350 * @param arity the number of arguments.
351 * @return the function identified by the URI, local name, and arity; or null if there is no such function
352 */
353
354 /*@Nullable*/
355 public UserFunction getUserDefinedFunction(/*@NotNull*/ String uri, /*@NotNull*/ String localName, int arity) {
356 SymbolicName functionKey = new SymbolicName.F(new StructuredQName("", uri, localName), arity);
357 XQueryFunction fd = functions.get(functionKey);
358 if (fd == null) {
359 return null;
360 }
361 return fd.getUserFunction();
362 }
363
364 /**
365 * This method creates a copy of a FunctionLibrary: if the original FunctionLibrary allows
366 * new functions to be added, then additions to this copy will not affect the original, or
367 * vice versa.
368 *
369 * @return a copy of this function library. This must be an instance of the original class.
370 */
371
372 /*@NotNull*/
373 public FunctionLibrary copy() {
374 XQueryFunctionLibrary qfl = new XQueryFunctionLibrary(config);
375 qfl.functions = new HashMap<>(functions);
376 return qfl;
377 }
378
379
380 }