Debian Codegraph @

net/sf/saxon/query/XQueryFunction.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 net.sf.saxon.Configuration;
11 import net.sf.saxon.expr.*;
12 import net.sf.saxon.expr.instruct.*;
13 import net.sf.saxon.expr.parser.*;
14 import net.sf.saxon.om.NamespaceResolver;
15 import net.sf.saxon.om.StandardNames;
16 import net.sf.saxon.om.StructuredQName;
17 import net.sf.saxon.trace.ExpressionPresenter;
18 import net.sf.saxon.trace.InstructionInfo;
19 import net.sf.saxon.trace.LocationKind;
20 import net.sf.saxon.trans.FunctionStreamability;
21 import net.sf.saxon.trans.GlobalVariableManager;
22 import net.sf.saxon.trans.SymbolicName;
23 import net.sf.saxon.trans.XPathException;
24 import net.sf.saxon.tree.jiter.PairIterator;
25 import net.sf.saxon.value.SequenceType;
26
27 import java.util.ArrayList;
28 import java.util.Iterator;
29 import java.util.List;
30
31 /**
32 * A user-defined function in an XQuery module
33 */
34
35 public class XQueryFunction implements InstructionInfo, Declaration {
36 private StructuredQName functionName;
37 private List<UserFunctionParameter> arguments;
38 private SequenceType resultType;
39 private Expression body = null;
40 private List<UserFunctionResolvable> references = new ArrayList<>(10);
41 private Location location;
42 /*@Nullable*/ private UserFunction compiledFunction = null;
43 private boolean memoFunction;
44 private NamespaceResolver namespaceResolver;
45 private QueryModule staticContext;
46 private boolean isUpdating = false;
47 private AnnotationList annotations = AnnotationList.EMPTY;
48
49 /**
50 * Create an XQuery function
51 */
52
53 public XQueryFunction() {
54 arguments = new ArrayList<>(8);
55 }
56
57 /**
58 * Get data about the unit of compilation (XQuery module, XSLT package) to which this
59 * container belongs
60 */
61 public PackageData getPackageData() {
62 return staticContext.getPackageData();
63 }
64
65 /**
66 * Set the name of the function
67 *
68 * @param name the name of the function as a StructuredQName object
69 */
70
71 public void setFunctionName(StructuredQName name) {
72 functionName = name;
73 }
74
75 /**
76 * Add an argument to the list of arguments
77 *
78 * @param argument the formal declaration of the argument to be added
79 */
80
81 public void addArgument(UserFunctionParameter argument) {
82 arguments.add(argument);
83 }
84
85 /**
86 * Set the required result type of the function
87 *
88 * @param resultType the declared result type of the function
89 */
90
91 public void setResultType(SequenceType resultType) {
92 this.resultType = resultType;
93 }
94
95 /**
96 * Set the body of the function
97 *
98 * @param body the expression forming the body of the function
99 */
100
101 public void setBody(/*@Nullable*/ Expression body) {
102 this.body = body;
103 // if (body != null) {
104 // body.setContainer(this);
105 // }
106 }
107
108 /**
109 * Get the body of the function
110 *
111 * @return the expression making up the body of the function
112 */
113
114 /*@Nullable*/
115 public Expression getBody() {
116 return body;
117 }
118
119 /**
120 * Set the location of the source declaration of the function
121 *
122 * @param location the source location
123 */
124
125 public void setLocation(Location location) {
126 this.location = location;
127 }
128
129 /**
130 * Get the name of the function as a structured QName
131 *
132 * @return the name of the function as a structured QName
133 */
134
135 public StructuredQName getFunctionName() {
136 return functionName;
137 }
138
139 /**
140 * Get the name of the function for display in error messages
141 *
142 * @return the name of the function as a lexical QName
143 */
144
145 public String getDisplayName() {
146 return functionName.getDisplayName();
147 }
148
149 /**
150 * Get an identifying key for this function, which incorporates the URI and local part of the
151 * function name plus the arity
152 *
153 * @return an identifying key
154 */
155
156 /*@NotNull*/
157 public SymbolicName getIdentificationKey() {
158 return new SymbolicName.F(functionName, arguments.size());
159 }
160
161 /**
162 * Construct what the identification key would be for a function with given URI, local name, and arity
163 *
164 * @param qName the name of the function
165 * @param arity the number of arguments
166 * @return an identifying key
167 */
168
169 public static SymbolicName getIdentificationKey(StructuredQName qName, int arity) {
170 return new SymbolicName.F(qName, arity);
171 }
172
173 /**
174 * Get the result type of the function
175 *
176 * @return the declared result type
177 */
178
179 public SequenceType getResultType() {
180 return resultType;
181 }
182
183 /**
184 * Set the static context for this function
185 *
186 * @param env the static context for the module in which the function is declared
187 */
188
189 public void setStaticContext(QueryModule env) {
190 staticContext = env;
191 }
192
193 /**
194 * Get the static context for this function
195 *
196 * @return the static context for the module in which the function is declared
197 */
198
199 public StaticContext getStaticContext() {
200 return staticContext;
201 }
202
203 /**
204 * Get the declared types of the arguments of this function
205 *
206 * @return an array, holding the types of the arguments in order
207 */
208
209 /*@NotNull*/
210 public SequenceType[] getArgumentTypes() {
211 SequenceType[] types = new SequenceType[arguments.size()];
212 for (int i = 0; i < arguments.size(); i++) {
213 types[i] = arguments.get(i).getRequiredType();
214 }
215 return types;
216 }
217
218 /**
219 * Get the definitions of the arguments to this function
220 *
221 * @return an array of UserFunctionParameter objects, one for each argument
222 */
223
224 public UserFunctionParameter[] getParameterDefinitions() {
225 UserFunctionParameter[] params = new UserFunctionParameter[arguments.size()];
226 return arguments.toArray(params);
227 }
228
229 /**
230 * Get the arity of the function
231 *
232 * @return the arity (the number of arguments)
233 */
234
235 public int getNumberOfArguments() {
236 return arguments.size();
237 }
238
239 /**
240 * Register a call on this function
241 *
242 * @param ufc a user function call that references this function.
243 */
244
245 public void registerReference(UserFunctionResolvable ufc) {
246 references.add(ufc);
247 }
248
249 /**
250 * Set that this is, or is not, a memo function. A memo function remembers the results of calls
251 * on the function so that the a subsequent call with the same arguments simply look up the result
252 *
253 * @param isMemoFunction true if this is a memo function.
254 */
255
256 public void setMemoFunction(boolean isMemoFunction) {
257 memoFunction = isMemoFunction;
258 }
259
260 /**
261 * Find out whether this is a memo function
262 *
263 * @return true if this is a memo function
264 */
265
266 public boolean isMemoFunction() {
267 return memoFunction;
268 }
269
270 /**
271 * Set whether this is an updating function (as defined in XQuery Update)
272 *
273 * @param isUpdating true if this is an updating function
274 */
275
276 public void setUpdating(boolean isUpdating) {
277 this.isUpdating = isUpdating;
278 }
279
280 /**
281 * Ask whether this is an updating function (as defined in XQuery Update)
282 *
283 * @return true if this is an updating function
284 */
285
286 public boolean isUpdating() {
287 return isUpdating;
288 }
289
290 /**
291 * Set the annotations on this function
292 *
293 * @param annotations the annotations, indexed by annotation name
294 */
295
296 public void setAnnotations(AnnotationList annotations) {
297 this.annotations = annotations;
298 if (compiledFunction != null) {
299 compiledFunction.setAnnotations(annotations);
300 }
301 if (annotations.includes(Annotation.UPDATING)) {
302 setUpdating(true);
303 }
304 }
305
306 /**
307 * Get the annotations defined on this function
308 *
309 * @return the list of annotations defined on this function
310 */
311
312 public AnnotationList getAnnotations() {
313 return annotations;
314 }
315
316 /**
317 * Ask whether the function has an annotation with a particular name
318 * @param name the name of the required annotation
319 */
320
321 public boolean hasAnnotation(StructuredQName name) {
322 return annotations.includes(name);
323 }
324
325
326 /**
327 * Ask whether this is a private function (as defined in XQuery 3.0)
328 *
329 * @return true if this is a private function
330 */
331
332 public boolean isPrivate() {
333 return hasAnnotation(Annotation.PRIVATE);
334 }
335
336 /**
337 * Compile this function to create a run-time definition that can be interpreted (note, this
338 * has nothing to do with Java code generation)
339 *
340 * @throws XPathException if errors are found
341 */
342
343 public void compile() throws XPathException {
344 Configuration config = staticContext.getConfiguration();
345 try {
346 // If a query function is imported into several modules, then the compile()
347 // method will be called once for each importing module. If the compiled
348 // function already exists, then this is a repeat call, and the only thing
349 // needed is to fix up references to the function from within the importing
350 // module.
351
352 if (compiledFunction == null) {
353 SlotManager map = config.makeSlotManager();
354 UserFunctionParameter[] params = getParameterDefinitions();
355 for (int i = 0; i < params.length; i++) {
356 params[i].setSlotNumber(i);
357 map.allocateSlotNumber(params[i].getVariableQName());
358 }
359
360 // type-check the body of the function
361
362 RetainedStaticContext rsc = null;
363 try {
364 rsc = getStaticContext().makeRetainedStaticContext();
365 body.setRetainedStaticContext(rsc);
366
367 ExpressionVisitor visitor = ExpressionVisitor.make(staticContext);
368 body = body.simplify().typeCheck(visitor, ContextItemStaticInfo.ABSENT);
369
370 // Try to extract new global variables from the body of the function
371 //body = config.getOptimizer().promoteExpressionsToGlobal(body, visitor);
372
373 //body.setContainer(this);
374 RoleDiagnostic role =
375 new RoleDiagnostic(RoleDiagnostic.FUNCTION_RESULT, functionName.getDisplayName(), 0);
376 //role.setSourceLocator(this);
377 body = config.getTypeChecker(false).staticTypeCheck(body, resultType, role, visitor);
378 if (staticContext.getUserQueryContext().isCompileWithTracing()) {
379 namespaceResolver = staticContext.getNamespaceResolver();
380 TraceExpression trace = new TraceExpression(body);
381 trace.setConstructType(StandardNames.XSL_FUNCTION);
382 trace.setObjectName(functionName);
383 trace.setNamespaceResolver(staticContext.getNamespaceResolver());
384 trace.setLocation(location);
385 body = trace;
386 }
387 } catch (XPathException e) {
388 e.maybeSetLocation(this);
389 if (e.isReportableStatically()) {
390 throw e;
391 } else {
392 Expression newBody = new ErrorExpression(e);
393 ExpressionTool.copyLocationInfo(body, newBody);
394 body = newBody;
395 }
396 }
397
398 compiledFunction = config.newUserFunction(memoFunction, FunctionStreamability.UNCLASSIFIED);
399 compiledFunction.setRetainedStaticContext(rsc);
400 compiledFunction.setPackageData(staticContext.getPackageData());
401 compiledFunction.setBody(body);
402 compiledFunction.setFunctionName(functionName);
403 compiledFunction.setParameterDefinitions(params);
404 compiledFunction.setResultType(getResultType());
405 compiledFunction.setLineNumber(location.getLineNumber());
406 compiledFunction.setSystemId(location.getSystemId());
407 compiledFunction.setStackFrameMap(map);
408 compiledFunction.setUpdating(isUpdating);
409 compiledFunction.setAnnotations(annotations);
410
411 }
412 // bind all references to this function to the UserFunction object
413
414 fixupReferences();
415
416 } catch (XPathException e) {
417 e.maybeSetLocation(this);
418 throw e;
419 }
420 }
421
422 /**
423 * Optimize the body of this function
424 *
425 * @throws net.sf.saxon.trans.XPathException
426 * if execution fails, for example because the function is updating
427 * and contains constructs not allowed in an updating function, or vice-versa.
428 */
429
430 public void optimize() throws XPathException {
431 body.checkForUpdatingSubexpressions();
432 if (isUpdating) {
433 if (ExpressionTool.isNotAllowedInUpdatingContext(body)) {
434 XPathException err = new XPathException(
435 "The body of an updating function must be an updating expression", "XUST0002");
436 err.setLocator(body.getLocation());
437 throw err;
438 }
439 } else {
440 //body.checkForUpdatingSubexpressions();
441 if (body.isUpdatingExpression()) {
442 XPathException err = new XPathException(
443 "The body of a non-updating function must be a non-updating expression", "XUST0001");
444 err.setLocator(body.getLocation());
445 throw err;
446 }
447 }
448 ExpressionVisitor visitor = ExpressionVisitor.make(staticContext);
449 Configuration config = staticContext.getConfiguration();
450 Optimizer opt = visitor.obtainOptimizer();
451 int arity = arguments.size();
452 if (opt.isOptionSet(OptimizerOptions.MISCELLANEOUS)) {
453 body = body.optimize(visitor, ContextItemStaticInfo.ABSENT);
454 }
455 body.setParentExpression(null);
456 if (opt.isOptionSet(OptimizerOptions.LOOP_LIFTING)) {
457 body = LoopLifter.process(body, visitor, ContextItemStaticInfo.ABSENT);
458 }
459 if (opt.isOptionSet(OptimizerOptions.EXTRACT_GLOBALS)) {
460 final Executable exec = ((QueryModule)getStaticContext()).getExecutable();
461 GlobalVariableManager manager = new GlobalVariableManager() {
462 public void addGlobalVariable(GlobalVariable variable) throws XPathException {
463 PackageData pd = staticContext.getPackageData();
464 variable.setPackageData(pd);
465 //exec.registerGlobalVariable(variable);
466 SlotManager sm = pd.getGlobalSlotManager();
467 int slot = sm.allocateSlotNumber(variable.getVariableQName());
468 variable.compile(exec, slot);
469 pd.addGlobalVariable(variable);
470 }
471
472 @Override
473 public GlobalVariable getEquivalentVariable(Expression select) {
474 return null;
475 }
476 };
477
478 // Try to extract new global variables from the body of the function
479 Expression b2 = opt.promoteExpressionsToGlobal(body, manager, visitor);
480 if (b2 != null) {
481 body = body.optimize(visitor, ContextItemStaticInfo.ABSENT);
482 }
483 }
484
485 // mark tail calls within the function body
486 if (opt.getOptimizerOptions().isSet(OptimizerOptions.TAIL_CALLS) && !isUpdating) {
487 int tailCalls = ExpressionTool.markTailFunctionCalls(body, functionName, arity);
488 if (tailCalls != 0) {
489 compiledFunction.setBody(body);
490 compiledFunction.setTailRecursive(tailCalls > 0, tailCalls > 1);
491 body = new TailCallLoop(compiledFunction, body);
492 }
493 }
494 compiledFunction.setBody(body);
495
496 compiledFunction.computeEvaluationMode();
497 ExpressionTool.allocateSlots(body, arity, compiledFunction.getStackFrameMap());
498 if (config.isGenerateByteCode(Configuration.XQUERY)) {
499 if (config.getCountDown() == 0) {
500 ICompilerService compilerService = config.makeCompilerService(Configuration.XQUERY);
501 Expression cbody = opt.compileToByteCode(compilerService, body, getFunctionName().getDisplayName(),
502 Expression.PROCESS_METHOD | Expression.ITERATE_METHOD);
503 if (cbody != null) {
504 body = cbody;
505 }
506 } else {
507 opt.injectByteCodeCandidates(body);
508 body = opt.makeByteCodeCandidate(compiledFunction, body, getDisplayName(),
509 Expression.PROCESS_METHOD | Expression.ITERATE_METHOD);
510 }
511 compiledFunction.setBody(body);
512 compiledFunction.computeEvaluationMode();
513 }
514 }
515
516 /**
517 * Fix up references to this function
518 */
519
520 public void fixupReferences() {
521 for (UserFunctionResolvable ufc : references) {
522 ufc.setFunction(compiledFunction);
523 }
524 }
525
526 /**
527 * Type-check references to this function
528 *
529 * @param visitor the expression visitor
530 */
531
532 public void checkReferences(ExpressionVisitor visitor) throws XPathException {
533 for (UserFunctionResolvable ufr : references) {
534 if (ufr instanceof UserFunctionCall) {
535 UserFunctionCall ufc = (UserFunctionCall) ufr;
536 ufc.checkFunctionCall(compiledFunction, visitor);
537 //ufc.computeArgumentEvaluationModes();
538 }
539 }
540
541 // clear the list of references, so that more can be added in another module
542 references = new ArrayList<>(0);
543
544 }
545
546 /**
547 * Produce diagnostic output showing the compiled and optimized expression tree for a function
548 *
549 * @param out the destination to be used
550 */
551 public void explain(/*@NotNull*/ ExpressionPresenter out) throws XPathException {
552 out.startElement("declareFunction");
553 out.emitAttribute("name", functionName.getDisplayName());
554 out.emitAttribute("arity", "" + getNumberOfArguments());
555 if (compiledFunction == null) {
556 out.emitAttribute("unreferenced", "true");
557 } else {
558 if (compiledFunction.isMemoFunction()) {
559 out.emitAttribute("memo", "true");
560 }
561 out.emitAttribute("tailRecursive", compiledFunction.isTailRecursive() ? "true" : "false");
562 body.export(out);
563 }
564 out.endElement();
565 }
566
567 /**
568 * Get the callable compiled function contained within this XQueryFunction definition.
569 *
570 * @return the compiled function object
571 */
572
573 /*@Nullable*/
574 public UserFunction getUserFunction() {
575 return compiledFunction;
576 }
577
578 /**
579 * Get the type of construct. This will be a constant in
580 * class {@link LocationKind}.
581 */
582
583 public int getConstructType() {
584 return StandardNames.XSL_FUNCTION;
585 }
586
587 /**
588 * Get a name identifying the object of the expression, for example a function name, template name,
589 * variable name, key name, element name, etc. This is used only where the name is known statically.
590 */
591
592 public StructuredQName getObjectName() {
593 return functionName;
594 }
595
596 /**
597 * Get the system identifier (URI) of the source module containing
598 * the instruction. This will generally be an absolute URI. If the system
599 * identifier is not known, the method may return null. In some cases, for example
600 * where XML external entities are used, the correct system identifier is not
601 * always retained.
602 */
603
604 public String getSystemId() {
605 return location.getSystemId();
606 }
607
608 /**
609 * Get the line number of the instruction in the source stylesheet module.
610 * If this is not known, or if the instruction is an artificial one that does
611 * not relate to anything in the source code, the value returned may be -1.
612 */
613
614 public int getLineNumber() {
615 return location.getLineNumber();
616 }
617
618 /**
619 * Return the public identifier for the current document event.
620 *
621 * @return A string containing the public identifier, or
622 * null if none is available.
623 * @see #getSystemId
624 */
625 /*@Nullable*/
626 public String getPublicId() {
627 return null;
628 }
629
630 /**
631 * Return the column number
632 *
633 * @return The column number, or -1 if none is available.
634 * @see #getLineNumber
635 */
636
637 public int getColumnNumber() {
638 return -1;
639 }
640
641 /**
642 * Get an immutable copy of this Location object. By default Location objects may be mutable, so they
643 * should not be saved for later use. The result of this operation holds the same location information,
644 * but in an immutable form.
645 */
646 public Location saveLocation() {
647 return this;
648 }
649
650 /**
651 * Get the namespace context of the instruction. This will not always be available, in which
652 * case the method returns null.
653 */
654
655 public NamespaceResolver getNamespaceResolver() {
656 return namespaceResolver;
657 }
658
659 /**
660 * Get the value of a particular property of the instruction. Properties
661 * of XSLT instructions are generally known by the name of the stylesheet attribute
662 * that defines them.
663 *
664 * @param name The name of the required property
665 * @return The value of the requested property, or null if the property is not available
666 */
667
668 /*@Nullable*/
669 public Object getProperty(String name) {
670 if ("name".equals(name)) {
671 return functionName.getDisplayName();
672 } else if ("as".equals(name)) {
673 return resultType.toString();
674 } else {
675 return null;
676 }
677 }
678
679 /**
680 * Get an iterator over all the properties available. The values returned by the iterator
681 * will be of type String, and each string can be supplied as input to the getProperty()
682 * method to retrieve the value of the property.
683 */
684
685 /*@NotNull*/
686 public Iterator<String> getProperties() {
687 return new PairIterator<>("name", "as");
688 }
689
690 /**
691 * Get the host language (XSLT, XQuery, XPath) used to implement the code in this container
692 *
693 * @return typically {@link net.sf.saxon.Configuration#XSLT} or {@link net.sf.saxon.Configuration#XQUERY}
694 */
695
696 public int getHostLanguage() {
697 return Configuration.XQUERY;
698 }
699
700 }
701