Debian Codegraph @

net/sf/saxon/expr/instruct/LocalParam.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.expr.instruct;
9
10 import net.sf.saxon.expr.*;
11 import net.sf.saxon.expr.parser.*;
12 import net.sf.saxon.om.Sequence;
13 import net.sf.saxon.om.StandardNames;
14 import net.sf.saxon.om.StructuredQName;
15 import net.sf.saxon.trace.ExpressionPresenter;
16 import net.sf.saxon.trans.XPathException;
17 import net.sf.saxon.type.ErrorType;
18 import net.sf.saxon.type.ItemType;
19 import net.sf.saxon.value.IntegerValue;
20 import net.sf.saxon.value.SequenceType;
21
22 /**
23 * The compiled form of an xsl:param element within a template in an XSLT stylesheet.
24 * <p>The xsl:param element in XSLT has mandatory attribute name and optional attribute select. It can also
25 * be specified as required="yes" or required="no".</p>
26 * <p>This is used only for parameters to XSLT templates. For function calls, the caller of the function
27 * places supplied arguments onto the callee's stackframe and the callee does not need to do anything.
28 * Global parameters (XQuery external variables) are handled using {@link GlobalParam}.</p>
29 * <p>The LocalParam class is also used to represent parameters with the saxon:iterate instruction</p>
30 *
31 * <p>Changed in Saxon 9.8 to combine the previously-separate LocalParamSetter and LocalParam classes into one</p>
32 */
33
34 public final class LocalParam extends Instruction implements LocalBinding {
35
36 private Operand conversionOp = null;
37 private Evaluator conversionEvaluator = null;
38
39 private static final int REQUIRED = 4;
40 private static final int TUNNEL = 8;
41 private static final int IMPLICITLY_REQUIRED = 16; // a parameter that is required because the fallback
42 // value is not a valid instance of the type.
43
44 private byte properties = 0;
45 private Operand selectOp = null;
46 protected StructuredQName variableQName;
47 private SequenceType requiredType;
48 protected int slotNumber = -999;
49 protected int referenceCount = 10;
50 protected Evaluator evaluator = null;
51
52
53
54 /**
55 * Set the expression to which this variable is bound
56 *
57 * @param select the initializing expression
58 */
59
60 public void setSelectExpression(Expression select) {
61 if (select != null) {
62 if (selectOp == null) {
63 selectOp = new Operand(this, select, OperandRole.NAVIGATE);
64 } else {
65 selectOp.setChildExpression(select);
66 }
67 } else {
68 selectOp = null;
69 }
70 evaluator = null;
71 }
72
73 /**
74 * Get the expression to which this variable is bound
75 *
76 * @return the initializing expression
77 */
78
79 public Expression getSelectExpression() {
80 return selectOp == null ? null : selectOp.getChildExpression();
81 }
82
83 /**
84 * Set the required type of this variable
85 *
86 * @param required the required type
87 */
88
89 public void setRequiredType(SequenceType required) {
90 requiredType = required;
91 }
92
93 /**
94 * Get the required type of this variable
95 *
96 * @return the required type
97 */
98
99 public SequenceType getRequiredType() {
100 return requiredType;
101 }
102
103 /**
104 * Indicate that this variable represents a required parameter
105 *
106 * @param requiredParam true if this is a required parameter
107 */
108
109 public void setRequiredParam(boolean requiredParam) {
110 if (requiredParam) {
111 properties |= REQUIRED;
112 } else {
113 properties &= ~REQUIRED;
114 }
115 }
116
117 /**
118 * Indicate that this variable represents a parameter that is implicitly required (because there is no
119 * usable default value)
120 *
121 * @param requiredParam true if this is an implicitly required parameter
122 */
123
124 public void setImplicitlyRequiredParam(boolean requiredParam) {
125 if (requiredParam) {
126 properties |= IMPLICITLY_REQUIRED;
127 } else {
128 properties &= ~IMPLICITLY_REQUIRED;
129 }
130 }
131
132 /**
133 * Indicate whether this variable represents a tunnel parameter
134 *
135 * @param tunnel true if this is a tunnel parameter
136 */
137
138 public void setTunnel(boolean tunnel) {
139 if (tunnel) {
140 properties |= TUNNEL;
141 } else {
142 properties &= ~TUNNEL;
143 }
144 }
145
146 /**
147 * Set the nominal number of references to this variable
148 *
149 * @param refCount the nominal number of references
150 */
151
152 public void setReferenceCount(int refCount) {
153 referenceCount = refCount;
154 }
155
156 // /**
157 // * Get the evaluation mode of the variable
158 // *
159 // * @return the evaluation mode (a constant in {@link ExpressionTool}
160 // */
161 //
162 // public int getEvaluationMode() {
163 // if (evaluationMode == ExpressionTool.UNDECIDED) {
164 // if (referenceCount == FilterExpression.FILTERED) {
165 // evaluationMode = ExpressionTool.MAKE_INDEXED_VARIABLE;
166 // } else {
167 // evaluationMode = ExpressionTool.lazyEvaluationMode(getSelectExpression());
168 // }
169 // }
170 // return evaluationMode;
171 // }
172
173 /**
174 * Get the cardinality of the result of this instruction. An xsl:variable instruction returns nothing, so the
175 * type is empty.
176 *
177 * @return the empty cardinality.
178 */
179
180 public int getCardinality() {
181 return StaticProperty.EMPTY;
182 }
183
184 public boolean isAssignable() {
185 return false;
186 }
187
188 public boolean isGlobal() {
189 return false;
190 }
191
192 /**
193 * If this is a local variable held on the local stack frame, return the corresponding slot number.
194 * In other cases, return -1.
195 */
196
197 public int getLocalSlotNumber() {
198 return slotNumber;
199 }
200
201 /**
202 * Ask whether this variable represents a required parameter
203 *
204 * @return true if this is a required parameter
205 */
206
207 public final boolean isRequiredParam() {
208 return (properties & REQUIRED) != 0;
209 }
210
211 /**
212 * Ask whether this variable represents a parameter that is implicitly required, because there is no usable
213 * default value
214 *
215 * @return true if this variable is an implicitly required parameter
216 */
217
218 public final boolean isImplicitlyRequiredParam() {
219 return (properties & IMPLICITLY_REQUIRED) != 0;
220 }
221
222 /**
223 * Ask whether this variable represents a tunnel parameter
224 *
225 * @return true if this is a tunnel parameter
226 */
227
228 public final boolean isTunnelParam() {
229 return (properties & TUNNEL) != 0;
230 }
231
232
233 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType) throws XPathException {
234 Expression e2 = super.typeCheck(visitor, contextItemType);
235 if (e2 != this) {
236 return e2;
237 }
238 checkAgainstRequiredType(visitor);
239 return this;
240 }
241
242 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType) throws XPathException {
243 Expression e2 = super.optimize(visitor, contextItemType);
244 if (e2 != this) {
245 return e2;
246 }
247 // if (selectOp != null) {
248 // computeEvaluationMode();
249 // }
250 return this;
251 }
252
253 public void computeEvaluationMode() {
254 if (getSelectExpression() != null) {
255 if (referenceCount == FilterExpression.FILTERED) {
256 evaluator = Evaluator.MAKE_INDEXED_VARIABLE;
257 } else {
258 evaluator = ExpressionTool.lazyEvaluator(getSelectExpression(), referenceCount > 1);
259 }
260 }
261 }
262
263
264 /**
265 * Copy an expression. This makes a deep copy.
266 * @param rebindings a mutable list of (old binding, new binding) pairs
267 * that is used to update the bindings held in any
268 * local variable references that are copied.
269 * @return the copy of the original expression
270 */
271
272 public LocalParam copy(RebindingMap rebindings) {
273 LocalParam p2 = new LocalParam();
274 if (conversionOp != null) {
275 assert getConversion() != null;
276 p2.setConversion(getConversion().copy(rebindings));
277 }
278 p2.conversionEvaluator = conversionEvaluator;
279 p2.properties = properties;
280 if (selectOp != null) {
281 assert getSelectExpression() != null;
282 p2.setSelectExpression(getSelectExpression().copy(rebindings));
283 }
284 p2.variableQName = variableQName;
285 p2.requiredType = requiredType;
286 p2.slotNumber = slotNumber;
287 p2.referenceCount = referenceCount;
288 p2.evaluator = evaluator;
289 return p2;
290 }
291
292 public void addReference(VariableReference ref, boolean isLoopingReference) {
293
294 }
295
296 /**
297 * Check the select expression against the required type.
298 *
299 * @param visitor an expression visitor
300 * @throws XPathException if the check fails
301 */
302
303 public void checkAgainstRequiredType(ExpressionVisitor visitor)
304 throws XPathException {
305 // Note, in some cases we are doing this twice.
306 RoleDiagnostic role = new RoleDiagnostic(RoleDiagnostic.VARIABLE, variableQName.getDisplayName(), 0);
307 //role.setSourceLocator(this);
308 SequenceType r = requiredType;
309 Expression select = getSelectExpression();
310 if (r != null && select != null) {
311 // check that the expression is consistent with the required type
312 select = visitor.getConfiguration().getTypeChecker(false).staticTypeCheck(select, requiredType, role, visitor);
313 }
314 }
315
316 /**
317 * Evaluate the variable. That is,
318 * get the value of the select expression if present or the content
319 * of the element otherwise, either as a tree or as a sequence
320 *
321 * @param context the XPath dynamic context
322 * @return the result of evaluating the variable
323 * @throws net.sf.saxon.trans.XPathException
324 * if evaluation of the select expression fails
325 * with a dynamic error
326 */
327
328 public Sequence<?> getSelectValue(XPathContext context) throws XPathException {
329 Expression select = getSelectExpression();
330 if (select == null) {
331 throw new AssertionError("Internal error: No select expression");
332 // The value of the variable is a sequence of nodes and/or atomic values
333 } else if (select instanceof Literal) {
334 // fast path for common case
335 return ((Literal)select).getValue();
336 } else {
337 // There is a select attribute: do a lazy evaluation of the expression,
338 // which will already contain any code to force conversion to the required type.
339 int savedOutputState = context.getTemporaryOutputState();
340 context.setTemporaryOutputState(StandardNames.XSL_WITH_PARAM);
341 Sequence<?> result = evaluator.evaluate(select, context);
342 context.setTemporaryOutputState(savedOutputState);
343 return result;
344 }
345 }
346
347 /**
348 * Get the slot number allocated to this variable
349 *
350 * @return the slot number, that is the position allocated to the variable on its stack frame
351 */
352
353 public int getSlotNumber() {
354 return slotNumber;
355 }
356
357 /**
358 * Set the slot number of this variable
359 *
360 * @param s the slot number, that is, the position allocated to this variable on its stack frame
361 */
362
363 public void setSlotNumber(int s) {
364 slotNumber = s;
365 }
366
367 /**
368 * Set the name of the variable
369 *
370 * @param s the name of the variable (a QName)
371 */
372
373 public void setVariableQName(StructuredQName s) {
374 variableQName = s;
375 }
376
377 /**
378 * Get the name of this variable
379 *
380 * @return the name of this variable (a QName)
381 */
382
383 public StructuredQName getVariableQName() {
384 return variableQName;
385 }
386
387 /**
388 * Define a conversion that is to be applied to the supplied parameter value.
389 *
390 * @param convertor The expression to be applied. This performs type checking,
391 * and the basic conversions implied by function calling rules, for example
392 * numeric promotion, atomization, and conversion of untyped atomic values to
393 * a required type. The conversion uses the actual parameter value as input,
394 * referencing it using a VariableReference. The argument can be null to indicate
395 * that no conversion is required.
396 */
397 public void setConversion(Expression convertor) {
398 if (convertor != null) {
399 if (conversionOp == null) {
400 conversionOp = new Operand(this, convertor, OperandRole.SINGLE_ATOMIC);
401 }
402 conversionEvaluator = ExpressionTool.eagerEvaluator(convertor);
403 } else {
404 conversionOp = null;
405 }
406 }
407
408 /**
409 * Get the conversion expression
410 *
411 * @return the expression used to convert the value to the required type,
412 * or null if there is none
413 */
414
415 /*@Nullable*/
416 public Expression getConversion() {
417 return conversionOp == null ? null : conversionOp.getChildExpression();
418 }
419
420 public int getConversionEvaluationMode() {
421 return conversionEvaluator.getCode();
422 }
423
424 /**
425 * Get the name of this instruction for diagnostic and tracing purposes
426 * @return the integer name code
427 */
428
429 public int getInstructionNameCode() {
430 return StandardNames.XSL_PARAM;
431 }
432
433
434 /**
435 * Get all the XPath expressions associated with this instruction
436 * (in XSLT terms, the expression present on attributes of the instruction,
437 * as distinct from the child instructions in a sequence construction)
438 * @return an iterator over the subexpressions
439 */
440
441 @Override
442 public Iterable<Operand> operands() {
443 return operandSparseList(selectOp, conversionOp);
444 }
445
446 /**
447 * Process the local parameter declaration
448 *
449 * @param context the dynamic context
450 * @return either null if processing is complete, or a tailcall if one is left outstanding
451 * @throws net.sf.saxon.trans.XPathException
452 * if a dynamic error occurs in the evaluation
453 */
454
455 public TailCall processLeavingTail(XPathContext context) throws XPathException {
456 int wasSupplied = context.useLocalParameter(variableQName, slotNumber, isTunnelParam());
457 switch (wasSupplied) {
458 case ParameterSet.SUPPLIED_AND_CHECKED:
459 // No action needed
460 break;
461
462 case ParameterSet.SUPPLIED:
463 // if a parameter was supplied by the caller, with no type-checking by the caller,
464 // then we may need to convert it to the type required
465 if (conversionOp != null) {
466 context.setLocalVariable(slotNumber,
467 conversionEvaluator.evaluate(getConversion(), context));
468 // We do an eager evaluation here for safety, because the result of the
469 // type conversion overwrites the slot where the actual supplied parameter
470 // is contained.
471 }
472 break;
473
474 // don't evaluate the default if a value has been supplied or if it has already been
475 // evaluated by virtue of a forwards reference
476
477 case ParameterSet.NOT_SUPPLIED:
478 if (isRequiredParam() || isImplicitlyRequiredParam()) {
479 String name = "$" + getVariableQName().getDisplayName();
480 int suppliedAsTunnel = context.useLocalParameter(variableQName, slotNumber, !isTunnelParam());
481 String message = "No value supplied for required parameter " + name;
482 if (isImplicitlyRequiredParam()) {
483 message += ". A value is required because " +
484 "the default value is not a valid instance of the required type";
485 }
486 if (suppliedAsTunnel != ParameterSet.NOT_SUPPLIED) {
487 if (isTunnelParam()) {
488 message += ". A non-tunnel parameter with this name was supplied, but a tunnel parameter is required";
489 } else {
490 message += ". A tunnel parameter with this name was supplied, but a non-tunnel parameter is required";
491 }
492 }
493 XPathException e = new XPathException(message);
494 e.setXPathContext(context);
495 e.setErrorCode("XTDE0700");
496 throw e;
497 }
498 context.setLocalVariable(slotNumber, getSelectValue(context));
499 }
500 return null;
501 }
502
503 /**
504 * If the variable is bound to an integer, get the minimum and maximum possible values.
505 * Return null if unknown or not applicable
506 */
507
508 public IntegerValue[] getIntegerBoundsForVariable() {
509 return null;
510 }
511
512 /**
513 * Evaluate the variable
514 */
515
516 public Sequence<?> evaluateVariable(XPathContext c) {
517 return c.evaluateLocalVariable(slotNumber);
518 }
519
520
521 /**
522 * Check if parameter is compatible with another
523 *
524 * @param other - the LocalParam object to compare
525 * @return result of the compatibility check
526 */
527 public boolean isCompatible(LocalParam other) {
528 return getVariableQName().equals(other.getVariableQName()) &&
529 getRequiredType().equals(other.getRequiredType()) &&
530 isTunnelParam() == other.isTunnelParam();
531 }
532
533 /**
534 * Ask whether the expression can be lifted out of a loop, assuming it has no dependencies
535 * on the controlling variable/focus of the loop
536 * @param forStreaming true if compiling streamable code
537 */
538 @Override
539 public boolean isLiftable(boolean forStreaming) {
540 return false;
541 }
542
543 /**
544 * Ask whether this expression is, or contains, the binding of a given variable
545 *
546 * @param binding the variable binding
547 * @return true if this expression is the variable binding (for example a ForExpression
548 * or LetExpression) or if it is a FLWOR expression that binds the variable in one of its
549 * clauses.
550 */
551 @Override
552 public boolean hasVariableBinding(Binding binding) {
553 return this == binding;
554 }
555
556 /**
557 * Get the item type of the items returned by evaluating this instruction
558 *
559 * @return the static item type of the instruction
560 */
561 /*@NotNull*/
562 @Override
563 public ItemType getItemType() {
564 return ErrorType.getInstance();
565 }
566
567 /**
568 * Get the cardinality of the sequence returned by evaluating this instruction
569 *
570 * @return the static cardinality
571 */
572 @Override
573 public int computeCardinality() {
574 return StaticProperty.ALLOWS_ZERO_OR_MORE;
575 }
576
577 /**
578 * Get the static properties of this expression (other than its type). The result is
579 * bit-signficant. These properties are used for optimizations. In general, if
580 * property bit is set, it is true, but if it is unset, the value is unknown.
581 *
582 * @return a set of flags indicating static properties of this expression
583 */
584 @Override
585 public int computeSpecialProperties() {
586 return StaticProperty.HAS_SIDE_EFFECTS;
587 }
588
589 /**
590 * Determine whether this instruction creates new nodes.
591 * This implementation returns a default value of false
592 *
593 * @return true if the instruction creates new nodes (or if it can't be proved that it doesn't)
594 */
595 @Override
596 public boolean mayCreateNewNodes() {
597 return false;
598 }
599
600 /**
601 * Get a name identifying the kind of expression, in terms meaningful to a user.
602 *
603 * @return a name identifying the kind of expression, in terms meaningful to a user.
604 * The name will always be in the form of a lexical XML QName, and should match the name used
605 * in explain() output displaying the expression.
606 */
607 @Override
608 public String getExpressionName() {
609 return "param";
610 }
611
612 /**
613 * Produce a short string identifying the expression for use in error messages
614 *
615 * @return a short string, sufficient to identify the expression
616 */
617 @Override
618 public String toShortString() {
619 return "$" + getVariableQName().getDisplayName();
620 }
621
622 /**
623 * Diagnostic print of expression structure. The abstract expression tree
624 * is written to the supplied output destination.
625 */
626
627 public void export(ExpressionPresenter out) throws XPathException {
628 out.startElement("param", this);
629 out.emitAttribute("name", getVariableQName());
630 out.emitAttribute("slot", "" + getSlotNumber());
631 String flags = getFlags();
632 if (!flags.isEmpty()) {
633 out.emitAttribute("flags", flags);
634 }
635 ExpressionPresenter.ExportOptions options = (ExpressionPresenter.ExportOptions) out.getOptions();
636 if (getRequiredType() != SequenceType.ANY_SEQUENCE) {
637 out.emitAttribute("as", getRequiredType().toExportString());
638 if (options.target.equals("JS") && options.targetVersion == 2) {
639 out.emitAttribute("asJ", getRequiredType().toExportString2());
640 }
641 }
642 if (getSelectExpression() != null) {
643 out.setChildRole("select");
644 getSelectExpression().export(out);
645 }
646 Expression conversion = getConversion();
647 if (conversion != null) {
648 out.setChildRole("conversion");
649 conversion.export(out);
650 }
651 out.endElement();
652 }
653
654 private String getFlags() {
655 String flags = "";
656 if (isTunnelParam()) {
657 flags += "t";
658 }
659 if (isRequiredParam()) {
660 flags += "r";
661 }
662 if (isImplicitlyRequiredParam()) {
663 flags += "i";
664 }
665 return flags;
666 }
667
668 /**
669 * Say that the bound value has the potential to be indexed
670 */
671 @Override
672 public void setIndexedVariable() {}
673
674 /**
675 * Ask whether the binding is to be indexed
676 *
677 * @return true if the variable value can be indexed
678 */
679 @Override
680 public boolean isIndexedVariable() {
681 return false;
682 }
683 }
684