Debian Codegraph @

net/sf/saxon/style/XSLFunction.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.style;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.expr.Component;
12 import net.sf.saxon.expr.Expression;
13 import net.sf.saxon.expr.Literal;
14 import net.sf.saxon.expr.TailCallLoop;
15 import net.sf.saxon.expr.instruct.SlotManager;
16 import net.sf.saxon.expr.instruct.UserFunction;
17 import net.sf.saxon.expr.instruct.UserFunctionParameter;
18 import net.sf.saxon.expr.parser.*;
19 import net.sf.saxon.lib.NamespaceConstant;
20 import net.sf.saxon.om.*;
21 import net.sf.saxon.query.Annotation;
22 import net.sf.saxon.query.AnnotationList;
23 import net.sf.saxon.trace.LocationKind;
24 import net.sf.saxon.trans.*;
25 import net.sf.saxon.tree.iter.AxisIterator;
26 import net.sf.saxon.type.TypeHierarchy;
27 import net.sf.saxon.value.SequenceType;
28 import net.sf.saxon.value.Whitespace;
29
30 import java.util.ArrayList;
31 import java.util.List;
32
33 /**
34 * Handler for xsl:function elements in stylesheet (XSLT 2.0). <BR>
35 * Attributes: <br>
36 * name gives the name of the function
37 * saxon:memo-function=yes|no indicates whether it acts as a memo function.
38 */
39
40 public class XSLFunction extends StyleElement implements StylesheetComponent {
41
42 private boolean doneAttributes = false;
43 /*@Nullable*/ private String nameAtt = null;
44 private String asAtt = null;
45 private String extraAsAtt = null;
46 private SequenceType resultType = SequenceType.ANY_SEQUENCE;
47 private SlotManager stackFrameMap;
48 private boolean memoFunction = false;
49 private String overrideExtensionFunctionAtt = null;
50 private boolean overrideExtensionFunction = true;
51 private int numberOfArguments = -1; // -1 means not yet known
52 private UserFunction compiledFunction;
53 private Visibility visibility;
54 private FunctionStreamability streamability;
55 private UserFunction.Determinism determinism = UserFunction.Determinism.PROACTIVE;
56
57 /**
58 * Get the corresponding Procedure object that results from the compilation of this
59 * StylesheetProcedure
60 */
61 public UserFunction getActor() {
62 return compiledFunction;
63 }
64
65 /**
66 * Ask whether this node is a declaration, that is, a permitted child of xsl:stylesheet
67 * (including xsl:include and xsl:import).
68 *
69 * @return true for this element
70 */
71
72 @Override
73 public boolean isDeclaration() {
74 return true;
75 }
76
77 public void prepareAttributes() throws XPathException {
78
79 if (doneAttributes) {
80 return;
81 }
82 doneAttributes = true;
83
84 AttributeCollection atts = getAttributeList();
85
86 overrideExtensionFunctionAtt = null;
87 String visibilityAtt = null;
88 String cacheAtt = null;
89 String newEachTimeAtt = null;
90 String streamabilityAtt = null;
91
92 for (int a = 0; a < atts.getLength(); a++) {
93 String uri = atts.getURI(a);
94 String local = atts.getLocalName(a);
95 if ("".equals(uri)) {
96 switch (local) {
97 case "name":
98 nameAtt = Whitespace.trim(atts.getValue(a));
99 assert nameAtt != null;
100 try {
101 StructuredQName functionName = makeQName(nameAtt);
102 if (functionName.hasURI("")) {
103 functionName = new StructuredQName("saxon", NamespaceConstant.SAXON, functionName.getLocalPart());
104 compileError("Function name must be in a namespace", "XTSE0740");
105 }
106 setObjectName(functionName);
107 } catch (XPathException err) {
108 compileError(err);
109 }
110 break;
111 case "as":
112 asAtt = atts.getValue(a);
113 break;
114 case "visibility":
115 visibilityAtt = Whitespace.trim(atts.getValue(a));
116 break;
117 case "streamability":
118 streamabilityAtt = Whitespace.trim(atts.getValue(a));
119 break;
120 case "override":
121 String overrideAtt = Whitespace.trim(atts.getValue(a));
122 boolean override = processBooleanAttribute("override", overrideAtt);
123 if (overrideExtensionFunctionAtt != null) {
124 if (override != overrideExtensionFunction) {
125 compileError("Attributes override-extension-function and override are both used, but do not match", "XTSE0020");
126 }
127 } else {
128 overrideExtensionFunctionAtt = overrideAtt;
129 overrideExtensionFunction = override;
130 }
131 compileWarning("The xsl:function/@override attribute is deprecated; use override-extension-function", SaxonErrorCode.SXWN9014);
132 break;
133 case "override-extension-function":
134 String overrideExtAtt = Whitespace.trim(atts.getValue(a));
135 boolean overrideExt = processBooleanAttribute("override-extension-function", overrideExtAtt);
136 if (overrideExtensionFunctionAtt != null) {
137 if (overrideExt != overrideExtensionFunction) {
138 compileError("Attributes override-extension-function and override are both used, but do not match", "XTSE0020");
139 }
140 } else {
141 overrideExtensionFunctionAtt = overrideExtAtt;
142 overrideExtensionFunction = overrideExt;
143 }
144 if (local.equals("override")) {
145 compileWarning("The xsl:function/@override attribute is deprecated; use override-extension-function", SaxonErrorCode.SXWN9014);
146 }
147 break;
148 case "cache":
149 cacheAtt = Whitespace.trim(atts.getValue(a));
150 break;
151 case "new-each-time":
152 newEachTimeAtt = Whitespace.trim(atts.getValue(a));
153 break;
154 default:
155 checkUnknownAttribute(atts.getNodeName(a));
156 break;
157 }
158 } else if (uri.equals(NamespaceConstant.SAXON)) {
159 if (local.equals("memo-function")) {
160 memoFunction = processBooleanAttribute("saxon:memo-function", atts.getValue(a));
161 } else if (local.equals("as")) {
162 extraAsAtt = atts.getValue(a);
163 }
164 } else {
165 checkUnknownAttribute(atts.getNodeName(a));
166 }
167 }
168
169 if (nameAtt == null) {
170 reportAbsence("name");
171 nameAtt = "xsl:unnamed-function-" + generateId();
172 }
173
174 if (asAtt != null) {
175 try {
176 resultType = makeSequenceType(asAtt);
177 } catch (XPathException e) {
178 compileErrorInAttribute(e.getMessage(), e.getErrorCodeLocalPart(), "as");
179 }
180 }
181
182 if (extraAsAtt != null) {
183 SequenceType extraResultType = null;
184 try {
185 extraResultType = makeExtendedSequenceType(extraAsAtt);
186 } catch (XPathException e) {
187 compileErrorInAttribute(e.getMessage(), e.getErrorCodeLocalPart(), "saxon:as");
188 extraResultType = resultType;
189 }
190 if (asAtt != null) {
191 int rel = getConfiguration().getTypeHierarchy().sequenceTypeRelationship(extraResultType, resultType);
192 if (rel == TypeHierarchy.SAME_TYPE || rel == TypeHierarchy.SUBSUMED_BY) {
193 resultType = extraResultType;
194 } else {
195 compileErrorInAttribute("When both are present, @saxon:as must be a subtype of @as", "SXER7TBA", "saxon:as");
196 }
197 } else {
198 resultType = extraResultType;
199 }
200 }
201
202 if (visibilityAtt == null) {
203 visibility = Visibility.PRIVATE;
204 } else {
205 visibility = interpretVisibilityValue(visibilityAtt, "");
206 }
207
208 if (streamabilityAtt == null) {
209 streamability = FunctionStreamability.UNCLASSIFIED;
210 } else {
211 streamability = getStreamabilityValue(streamabilityAtt);
212 if (streamability.isStreaming()) {
213 boolean streamable = processStreamableAtt("yes");
214 if (!streamable) {
215 streamability = FunctionStreamability.UNCLASSIFIED;
216 }
217 }
218 }
219
220 if (newEachTimeAtt != null) {
221 if ("maybe".equals(newEachTimeAtt)) {
222 determinism = UserFunction.Determinism.ELIDABLE;
223 } else {
224 boolean b = processBooleanAttribute("new-each-time", newEachTimeAtt);
225 determinism = b ? UserFunction.Determinism.PROACTIVE : UserFunction.Determinism.DETERMINISTIC;
226 }
227 }
228
229 boolean cache = false;
230 if (cacheAtt != null) {
231 cache = processBooleanAttribute("cache", cacheAtt);
232 }
233
234 if (determinism == UserFunction.Determinism.DETERMINISTIC || cache) {
235 memoFunction = true;
236 }
237 }
238
239 private FunctionStreamability getStreamabilityValue(String s) throws XPathException {
240 if (s.contains(":")) {
241 // QNames are allowed but not recognized by Saxon
242 makeQName(s);
243 return FunctionStreamability.UNCLASSIFIED;
244 }
245 for (FunctionStreamability v : FunctionStreamability.values()) {
246 if (v.streamabilityStr.equals(s)) {
247 return v;
248 }
249 }
250 invalidAttribute("visibility", "unclassified|absorbing|inspection|filter|shallow-descent|deep-descent|ascent");
251 return null;
252 }
253
254 /**
255 * Get a name identifying the object of the expression, for example a function name, template name,
256 * variable name, key name, element name, etc. This is used only where the name is known statically.
257 * If there is no name, the value will be -1.
258 */
259
260 /*@NotNull*/
261 public StructuredQName getObjectName() {
262 StructuredQName qn = super.getObjectName();
263 if (qn == null) {
264 nameAtt = Whitespace.trim(getAttributeValue("", "name"));
265 if (nameAtt == null) {
266 return new StructuredQName("saxon", NamespaceConstant.SAXON, "badly-named-function" + generateId());
267 }
268 try {
269 qn = makeQName(nameAtt);
270 setObjectName(qn);
271 } catch (XPathException err) {
272 return new StructuredQName("saxon", NamespaceConstant.SAXON, "badly-named-function" + generateId());
273 }
274 }
275 return qn;
276 }
277
278 /**
279 * Determine whether this type of element is allowed to contain a template-body.
280 *
281 * @return true: yes, it may contain a general template-body
282 */
283
284 public boolean mayContainSequenceConstructor() {
285 return true;
286 }
287
288 protected boolean mayContainParam() {
289 return true;
290 }
291
292 /**
293 * Specify that xsl:param is a permitted child
294 */
295
296 protected boolean isPermittedChild(StyleElement child) {
297 return child instanceof XSLLocalParam;
298 }
299
300 public Visibility getVisibility() {
301 if (visibility == null) {
302 String vAtt = getAttributeValue("", "visibility");
303 return vAtt == null ? Visibility.PRIVATE : interpretVisibilityValue(Whitespace.trim(vAtt), "");
304 }
305 return visibility;
306 }
307
308 public SymbolicName.F getSymbolicName() {
309 return new SymbolicName.F(getObjectName(), getNumberOfArguments());
310 }
311
312 public void checkCompatibility(Component component) {
313 if (compiledFunction == null) {
314 getCompiledFunction();
315 }
316
317 TypeHierarchy th = getConfiguration().getTypeHierarchy();
318 UserFunction other = (UserFunction) component.getActor();
319 if (!compiledFunction.getSymbolicName().equals(other.getSymbolicName())) {
320 // Can't happen
321 compileError("The overriding xsl:function " + nameAtt + " does not match the overridden function: " +
322 "the function name/arity does not match", "XTSE3070");
323 }
324 if (!compiledFunction.getDeclaredResultType().isSameType(other.getDeclaredResultType(), th)) {
325 compileError("The overriding xsl:function " + nameAtt + " does not match the overridden function: " +
326 "the return type does not match", "XTSE3070");
327 }
328 if (!compiledFunction.getDeclaredStreamability().equals(other.getDeclaredStreamability())) {
329 compileError("The overriding xsl:function " + nameAtt + " does not match the overridden function: " +
330 "the streamability category does not match", "XTSE3070");
331 }
332 if (!compiledFunction.getDeterminism().equals(other.getDeterminism())) {
333 compileError("The overriding xsl:function " + nameAtt + " does not match the overridden function: " +
334 "the new-each-time attribute does not match", "XTSE3070");
335 }
336
337 for (int i = 0; i < getNumberOfArguments(); i++) {
338 if (!compiledFunction.getArgumentType(i).isSameType(other.getArgumentType(i), th)) {
339 compileError("The overriding xsl:function " + nameAtt + " does not match the overridden function: " +
340 "the type of the " + RoleDiagnostic.ordinal(i + 1) + " argument does not match", "XTSE3070");
341 }
342 }
343 }
344
345 /**
346 * Is override-extension-function="yes"?.
347 *
348 * @return true if override-extension-function="yes" was specified, otherwise false
349 */
350
351 public boolean isOverrideExtensionFunction() {
352 if (overrideExtensionFunctionAtt == null) {
353 // this is a forwards reference
354 try {
355 prepareAttributes();
356 } catch (XPathException e) {
357 // no action: error will be caught later
358 }
359 }
360 return overrideExtensionFunction;
361 }
362
363 public void index(ComponentDeclaration decl, PrincipalStylesheetModule top) {
364 //getSkeletonCompiledFunction();
365 getCompiledFunction();
366 top.indexFunction(decl);
367 }
368
369 public void validate(ComponentDeclaration decl) throws XPathException {
370
371 stackFrameMap = getConfiguration().makeSlotManager();
372
373 // check the element is at the top level of the stylesheet
374
375 checkTopLevel("XTSE0010", true);
376 int arity = getNumberOfArguments();
377 if (arity == 0 && streamability != FunctionStreamability.UNCLASSIFIED) {
378 compileError("A function with no arguments must have streamability=unclassified", "XTSE3155");
379 }
380
381 }
382
383
384 /**
385 * Compile the function definition to create an executable representation
386 * The compileDeclaration() method has the side-effect of binding
387 * all references to the function to the executable representation
388 * (a UserFunction object)
389 *
390 * @throws XPathException if compilation fails
391 */
392
393 public void compileDeclaration(Compilation compilation, ComponentDeclaration decl) throws XPathException {
394 Expression exp = compileSequenceConstructor(compilation, decl, false);
395 if (exp == null) {
396 exp = Literal.makeEmptySequence();
397 } else if (Literal.isEmptySequence(exp)) {
398 // no action
399 } else {
400 if (visibility == Visibility.ABSTRACT) {
401 compileError("A function defined with visibility='abstract' must have no body");
402 }
403 exp = exp.simplify();
404 }
405
406 UserFunction fn = getCompiledFunction();
407 fn.setBody(exp);
408 fn.setStackFrameMap(stackFrameMap);
409 bindParameterDefinitions(fn);
410 fn.setRetainedStaticContext(makeRetainedStaticContext());
411 fn.setOverrideExtensionFunction(overrideExtensionFunction);
412
413 if (determinism == UserFunction.Determinism.DETERMINISTIC && !fn.isMemoFunction()) {
414 compileWarning("Deterministic user functions are not available in Saxon-HE: new-each-time attribute ignored",
415 SaxonErrorCode.SXWN9011);
416 } else if (memoFunction && !fn.isMemoFunction()) {
417 compileWarning("Memo functions are not available in Saxon-HE: @cache (or @saxon:memo-function) attribute ignored",
418 SaxonErrorCode.SXWN9011);
419 }
420
421 Component overridden = getOverriddenComponent();
422 if (overridden != null) {
423 checkCompatibility(overridden);
424 }
425 }
426
427 public void optimize(ComponentDeclaration declaration) throws XPathException {
428 Expression exp = compiledFunction.getBody();
429 ExpressionTool.resetPropertiesWithinSubtree(exp);
430 ExpressionVisitor visitor = makeExpressionVisitor();
431 Expression exp2 = exp.typeCheck(visitor, ContextItemStaticInfo.ABSENT);
432
433 if (streamability.isStreaming()) {
434 visitor.setOptimizeForStreaming(true);
435 }
436 exp2 = ExpressionTool.optimizeComponentBody(exp2, getCompilation(), visitor, ContextItemStaticInfo.ABSENT, true);
437
438 // Add trace wrapper code if required
439 exp2 = makeTraceInstruction(this, exp2);
440 compiledFunction.setBody(exp2);
441
442 // Assess the streamability of the function body
443 Optimizer optimizer = visitor.getConfiguration().obtainOptimizer();
444 if (streamability.isStreaming()) {
445 optimizer.assessFunctionStreamability(this, compiledFunction);
446 }
447
448 allocateLocalSlots(exp2);
449 if (exp2 != exp) {
450 compiledFunction.setBody(exp2);
451 }
452
453 OptimizerOptions options = getCompilation().getCompilerInfo().getOptimizerOptions();
454 if (options.isSet(OptimizerOptions.TAIL_CALLS) && !streamability.isStreaming()) {
455 int tailCalls = ExpressionTool.markTailFunctionCalls(exp2, getObjectName(), getNumberOfArguments());
456 if (tailCalls != 0) {
457 compiledFunction.setTailRecursive(tailCalls > 0, tailCalls > 1);
458 exp2 = compiledFunction.getBody();
459 compiledFunction.setBody(new TailCallLoop(compiledFunction, exp2));
460 }
461 }
462
463 compiledFunction.computeEvaluationMode();
464
465 if (streamability.isStreaming()) {
466 compiledFunction.prepareForStreaming();
467 } else if (visitor.getConfiguration().isDeferredByteCode(Configuration.XSLT)) {
468 int evaluationModes = Expression.ITERATE_METHOD | Expression.PROCESS_METHOD;
469 compiledFunction.setBody(getConfiguration().obtainOptimizer().makeByteCodeCandidate(
470 compiledFunction, compiledFunction.getBody(), nameAtt, evaluationModes));
471 }
472
473 if (isExplaining()) {
474 exp2.explain(getConfiguration().getLogger());
475 }
476 }
477
478 /**
479 * Generate byte code if appropriate
480 *
481 * @param opt the optimizer
482 * @throws net.sf.saxon.trans.XPathException if bytecode generation fails
483 */
484 public void generateByteCode(Optimizer opt) throws XPathException {
485 // Generate byte code if appropriate
486
487 if (getCompilation().getCompilerInfo().isGenerateByteCode() &&
488 streamability == FunctionStreamability.UNCLASSIFIED) {
489 try {
490 ICompilerService compilerService = getConfiguration().makeCompilerService(Configuration.XSLT);
491 Expression cbody = opt.compileToByteCode(compilerService, compiledFunction.getBody(), nameAtt,
492 Expression.PROCESS_METHOD | Expression.ITERATE_METHOD);
493 if (cbody != null) {
494 compiledFunction.setBody(cbody);
495 }
496 } catch (Exception e) {
497 System.err.println("Failed while compiling function " + nameAtt);
498 e.printStackTrace();
499 throw new XPathException(e);
500 }
501 }
502 }
503
504
505
506 /**
507 * Get associated stack frame details.
508 *
509 * @return the associated SlotManager object
510 */
511
512 public SlotManager getSlotManager() {
513 return stackFrameMap;
514 }
515
516 /**
517 * Get the type of value returned by this function
518 *
519 * @return the declared result type, or the inferred result type
520 * if this is more precise
521 */
522 public SequenceType getResultType() {
523 if (resultType == null) {
524 // may be handling a forwards reference - see hof-038
525 String asAtt = getAttributeValue("", "as");
526 if (asAtt != null) {
527 try {
528 resultType = makeSequenceType(asAtt);
529 } catch (XPathException err) {
530 // the error will be reported when we get round to processing the function declaration
531 }
532 }
533 }
534 return resultType == null ? SequenceType.ANY_SEQUENCE : resultType;
535 }
536
537 /**
538 * Get the number of arguments declared by this function (that is, its arity).
539 *
540 * @return the arity of the function
541 */
542
543 public int getNumberOfArguments() {
544 if (numberOfArguments == -1) {
545 numberOfArguments = 0;
546 AxisIterator kids = iterateAxis(AxisInfo.CHILD);
547 while (true) {
548 Item child = kids.next();
549 if (child instanceof XSLLocalParam) {
550 numberOfArguments++;
551 } else {
552 return numberOfArguments;
553 }
554 }
555 }
556 return numberOfArguments;
557 }
558
559 /**
560 * Set the definitions of the parameters in the compiled function, as an array.
561 *
562 * @param fn the compiled object representing the user-written function
563 */
564
565 public void setParameterDefinitions(UserFunction fn) {
566 UserFunctionParameter[] params = new UserFunctionParameter[getNumberOfArguments()];
567 fn.setParameterDefinitions(params);
568 int count = 0;
569 AxisIterator kids = iterateAxis(AxisInfo.CHILD);
570 NodeInfo node;
571 while ((node = kids.next()) != null) {
572 if (node instanceof XSLLocalParam) {
573 UserFunctionParameter param = new UserFunctionParameter();
574 params[count] = param;
575 param.setRequiredType(((XSLLocalParam) node).getRequiredType());
576 param.setVariableQName(((XSLLocalParam) node).getVariableQName());
577 param.setSlotNumber(((XSLLocalParam) node).getSlotNumber());
578 if (count == 0 && streamability != FunctionStreamability.UNCLASSIFIED) {
579 param.setFunctionStreamability(streamability);
580 }
581 count++;
582 } else {
583 break;
584 }
585 }
586 }
587
588 /**
589 * For each local parameter definition, fix up all references to the function parameter
590 * @param fn the compiled user function
591 */
592
593 private void bindParameterDefinitions(UserFunction fn) {
594 UserFunctionParameter[] params = fn.getParameterDefinitions();
595 int count = 0;
596 AxisIterator kids = iterateAxis(AxisInfo.CHILD);
597 NodeInfo node;
598 while ((node = kids.next()) != null) {
599 if (node instanceof XSLLocalParam) {
600 UserFunctionParameter param = params[count++];
601 param.setRequiredType(((XSLLocalParam) node).getRequiredType());
602 param.setVariableQName(((XSLLocalParam) node).getVariableQName());
603 param.setSlotNumber(((XSLLocalParam) node).getSlotNumber());
604 ((XSLLocalParam) node).getSourceBinding().fixupBinding(param);
605 }
606 }
607 }
608
609 /**
610 * Get the argument types
611 *
612 * @return the declared types of the arguments
613 */
614
615 public SequenceType[] getArgumentTypes() {
616 SequenceType[] types = new SequenceType[getNumberOfArguments()];
617 int count = 0;
618 AxisIterator kids = iterateAxis(AxisInfo.CHILD);
619 NodeInfo node;
620 while ((node = kids.next()) != null) {
621 if (node instanceof XSLLocalParam) {
622 types[count++] = ((XSLLocalParam) node).getRequiredType();
623 }
624 }
625 return types;
626 }
627
628 /**
629 * Get the compiled function
630 *
631 * @return the object representing the compiled user-written function
632 */
633
634 public UserFunction getCompiledFunction() {
635 if (compiledFunction == null) {
636 try {
637 prepareAttributes();
638 UserFunction fn = getConfiguration().newUserFunction(memoFunction, streamability);
639 fn.setPackageData(getCompilation().getPackageData());
640 fn.setFunctionName(getObjectName());
641 setParameterDefinitions(fn);
642 fn.setResultType(getResultType());
643 fn.setLineNumber(getLineNumber());
644 fn.setSystemId(getSystemId());
645 fn.obtainDeclaringComponent(this);
646 fn.setDeclaredVisibility(getDeclaredVisibility());
647 fn.setDeclaredStreamability(streamability);
648 fn.setDeterminism(determinism);
649 List<Annotation> annotations = new ArrayList<>();
650 if (memoFunction) {
651 annotations.add(new Annotation(new StructuredQName("saxon", NamespaceConstant.SAXON, "memo-function")));
652 }
653 fn.setAnnotations(new AnnotationList(annotations));
654 fn.setOverrideExtensionFunction(overrideExtensionFunction);
655 compiledFunction = fn;
656 } catch (XPathException err) {
657 return null;
658 }
659 }
660 return compiledFunction;
661 }
662
663
664 /**
665 * Get the type of construct. This will be a constant in
666 * class {@link LocationKind}. This method is part of the
667 * {@link net.sf.saxon.trace.InstructionInfo} interface
668 */
669
670 public int getConstructType() {
671 return StandardNames.XSL_FUNCTION;
672 }
673
674 }
675