Debian Codegraph @

net/sf/saxon/expr/LetExpression.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;
9
10 import net.sf.saxon.expr.instruct.DocumentInstr;
11 import net.sf.saxon.expr.instruct.TailCall;
12 import net.sf.saxon.expr.instruct.TailCallReturner;
13 import net.sf.saxon.expr.parser.*;
14 import net.sf.saxon.om.*;
15 import net.sf.saxon.trace.ExpressionPresenter;
16 import net.sf.saxon.trans.XPathException;
17 import net.sf.saxon.type.ItemType;
18 import net.sf.saxon.type.SchemaType;
19 import net.sf.saxon.type.UType;
20 import net.sf.saxon.value.IntegerValue;
21 import net.sf.saxon.value.SequenceType;
22
23 import java.util.ArrayList;
24
25
26 /**
27 * A LetExpression represents the XQuery construct let $x := expr return expr. It is used
28 * also for XSLT local variables.
29 */
30
31 public class LetExpression extends Assignation implements TailCallReturner {
32
33 //private int evaluationMode = ExpressionTool.UNDECIDED;
34 private Evaluator evaluator = null;
35 private boolean needsEagerEvaluation = false;
36 private boolean needsLazyEvaluation = false;
37 private boolean isInstruction;
38
39 /**
40 * Create a LetExpression
41 */
42
43 public LetExpression() {
44 //System.err.println("let");
45 }
46
47
48 /**
49 * Say whether this expression originates as an XSLT instruction
50 *
51 * @param inst true if this is an xsl:variable instruction
52 */
53
54 public void setInstruction(boolean inst) {
55 isInstruction = inst;
56 }
57
58 /**
59 * Ask whether this expression is an instruction. In XSLT streamability analysis this
60 * is used to distinguish constructs corresponding to XSLT instructions from other constructs.
61 *
62 * @return true if this construct originates as an XSLT instruction
63 */
64
65 @Override
66 public boolean isInstruction() {
67 return isInstruction;
68 }
69
70
71 /**
72 * Get a name identifying the kind of expression, in terms meaningful to a user.
73 *
74 * @return a name identifying the kind of expression, in terms meaningful to a user.
75 * The name will always be in the form of a lexical XML QName, and should match the name used
76 * in explain() output displaying the expression.
77 */
78
79 public String getExpressionName() {
80 return "let";
81 }
82
83 /**
84 * Say that this variable must be evaluated eagerly. This is a requirement for example
85 * for variables appearing within a try/catch, or for variables referenced from within
86 * a construct that uses multi-threading, for example xsl:result-document or a multi-threaded
87 * xsl:for-each.
88 * @param req set to true if eager evaluation is required
89 */
90
91 public void setNeedsEagerEvaluation(boolean req) {
92 if (req && needsLazyEvaluation) {
93 // No action - see bug #2903, Lazy evaluation wins
94 }
95 this.needsEagerEvaluation = req;
96 }
97
98 public void setNeedsLazyEvaluation(boolean req) {
99 if (req && needsEagerEvaluation) {
100 this.needsEagerEvaluation = false; // Bug 2903: lazy evaluation wins
101 }
102 this.needsLazyEvaluation = req;
103 }
104
105 public boolean isNeedsLazyEvaluation() {
106 return needsLazyEvaluation;
107 }
108
109 /**
110 * Ask whether the expression can be lifted out of a loop, assuming it has no dependencies
111 * on the controlling variable/focus of the loop
112 * @param forStreaming true if we are handling streaming code (where rewrites need to be more cautious)
113 */
114 @Override
115 public boolean isLiftable(boolean forStreaming) {
116 return super.isLiftable(forStreaming) && !needsEagerEvaluation;
117 }
118
119 @Override
120 public void resetLocalStaticProperties() {
121 super.resetLocalStaticProperties();
122 references = new ArrayList<>(); // bug 3233
123 if (evaluator == Evaluator.VARIABLE && !(getSequence() instanceof VariableReference)) {
124 evaluator = null;
125 setEvaluator();
126 }
127 }
128
129 /**
130 * Type-check the expression. This also has the side-effect of counting the number of references
131 * to the variable (treating references that occur within a loop specially)
132 */
133
134 /*@NotNull*/
135 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
136
137 // The order of events is critical here. First we ensure that the type of the
138 // sequence expression is established. This is used to establish the type of the variable,
139 // which in turn is required when type-checking the action part.
140
141 getSequenceOp().typeCheck(visitor, contextInfo);
142
143 RoleDiagnostic role = new RoleDiagnostic(RoleDiagnostic.VARIABLE, getVariableQName().getDisplayName(), 0);
144 //role.setSourceLocator(this);
145 setSequence(TypeChecker.strictTypeCheck(
146 getSequence(), requiredType, role, visitor.getStaticContext()));
147 final ItemType actualItemType = getSequence().getItemType();
148
149 refineTypeInformation(actualItemType,
150 getSequence().getCardinality(),
151 getSequence() instanceof Literal ? ((Literal) getSequence()).getValue() : null,
152 getSequence().getSpecialProperties(), this);
153
154 getActionOp().typeCheck(visitor, contextInfo);
155 return this;
156 }
157
158
159 /**
160 * Determine whether this expression implements its own method for static type checking
161 *
162 * @return true - this expression has a non-trivial implementation of the staticTypeCheck()
163 * method
164 */
165
166 public boolean implementsStaticTypeCheck() {
167 return true;
168 }
169
170 /**
171 * Static type checking for let expressions is delegated to the expression itself,
172 * and is performed on the "action" expression, to allow further delegation to the branches
173 * of a conditional
174 *
175 *
176 * @param req the required type
177 * @param backwardsCompatible true if backwards compatibility mode applies
178 * @param role the role of the expression in relation to the required type
179 * @param visitor an expression visitor
180 * @return the expression after type checking (perhaps augmented with dynamic type checking code)
181 * @throws XPathException if failures occur, for example if the static type of one branch of the conditional
182 * is incompatible with the required type
183 */
184
185 public Expression staticTypeCheck(SequenceType req,
186 boolean backwardsCompatible,
187 RoleDiagnostic role, ExpressionVisitor visitor)
188 throws XPathException {
189 TypeChecker tc = visitor.getConfiguration().getTypeChecker(backwardsCompatible);
190 setAction(tc.staticTypeCheck(getAction(), req, role, visitor));
191 return this;
192 }
193
194 /**
195 * Perform optimisation of an expression and its subexpressions.
196 * <p>This method is called after all references to functions and variables have been resolved
197 * to the declaration of the function or variable, and after all type checking has been done.</p>
198 *
199 * @param visitor an expression visitor
200 * @param contextItemType the static type of "." at the point where this expression is invoked.
201 * The parameter is set to null if it is known statically that the context item will be undefined.
202 * If the type of the context item is not known statically, the argument is set to
203 * {@link net.sf.saxon.type.Type#ITEM_TYPE}
204 * @return the original expression, rewritten if appropriate to optimize execution
205 * @throws XPathException if an error is discovered during this phase
206 * (typically a type error)
207 */
208
209 /*@NotNull*/
210 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType) throws XPathException {
211 Optimizer opt = visitor.obtainOptimizer();
212
213 // if this is a construct of the form "let $j := EXP return $j" replace it with EXP
214 // Remarkably, people do write this, and it can also be produced by previous rewrites
215 // Note that type checks will already have been added to the sequence expression
216
217 if (getAction() instanceof VariableReference &&
218 ((VariableReference) getAction()).getBinding() == this &&
219 !ExpressionTool.changesXsltContext(getSequence())) {
220 getSequenceOp().optimize(visitor, contextItemType);
221 opt.trace("Eliminated trivial variable " + getVariableName(), getSequence());
222 return getSequence();
223 }
224
225 if (getSequence() instanceof Literal && opt.isOptionSet(OptimizerOptions.INLINE_VARIABLES)) {
226 // inline the variable: replace all references by the constant value
227 // This relies on the fact that optimizing the action part will cause any references to be inlined
228 opt.trace("Inlined constant variable " + getVariableName(), getSequence());
229 replaceVariable(getSequence());
230 return getAction().optimize(visitor, contextItemType);
231 }
232
233 // if this is an XSLT construct of the form <xsl:variable>text</xsl:variable>, try to replace
234 // it by <xsl:variable select=""/>. This can be done if all the references to the variable use
235 // its value as a string (rather than, say, as a node or as a boolean)
236 if (getSequence() instanceof DocumentInstr && ((DocumentInstr) getSequence()).isTextOnly()) {
237 // Ensure the list of references is accurate
238 verifyReferences();
239 // Check whether all uses of the variable are atomized or stringified
240 if (allReferencesAreFlattened()) {
241 Expression stringValueExpression = ((DocumentInstr) getSequence()).getStringValueExpression();
242 stringValueExpression = stringValueExpression.typeCheck(visitor, contextItemType);
243 setSequence(stringValueExpression);
244 requiredType = SequenceType.SINGLE_UNTYPED_ATOMIC;
245 adoptChildExpression(getSequence());
246 refineTypeInformation(requiredType.getPrimaryType(), requiredType.getCardinality(), null, 0, this);
247 }
248 }
249
250 // If the initializing expression has (potential) side-effects, prevent optimizations such as elimination
251 // of unused variables
252 if (getSequence().hasSpecialProperty(StaticProperty.HAS_SIDE_EFFECTS)) {
253 needsEagerEvaluation = true;
254 }
255
256 // Removal of redundant variables, and inlining of variables that are only used once, depends on accurate
257 // knowledge of all references to the variable. The problem is that obtaining this knowledge can be expensive:
258 // see bug 2707. On the other hand, failing to do these optimizations is not fatal. So the general approach
259 // is that we limit the time spent discovering the information, and we don't do the optimization unless
260 // it is safe.
261
262 // Typically on entry to optimize(), the typeCheck() method has already been called, and this has set up
263 // a list of references. First we examine this list of references and remove any that are "dead", that is
264 // they no longer have this LetExpression as an ancestor in the expression tree. This function also checks
265 // whether any of these references are known to be in a loop, and returns true if so.
266
267 hasLoopingReference |= removeDeadReferences();
268
269 if (!needsEagerEvaluation) {
270
271 // If there are less than two references, and none is in a loop, then there is potential
272 // for optimization. But we now need to be absolutely sure that we have an accurate list
273 // of references.
274
275 boolean considerRemoval = ((references != null && references.size() < 2) || getSequence() instanceof VariableReference) &&
276 !isIndexedVariable && !hasLoopingReference && !needsEagerEvaluation;
277
278 if (considerRemoval) {
279 verifyReferences();
280 // At this point the list of references is either accurate, or null
281 considerRemoval = references != null;
282 }
283
284 if (considerRemoval && references.isEmpty()) {
285 // variable is not used - no need to evaluate it
286 getActionOp().optimize(visitor, contextItemType);
287 opt.trace("Eliminated unused variable " + getVariableName(), getAction());
288 return getAction();
289 }
290
291 // Don't inline context-dependent variables in a streamable template. See strmode011.
292 // The reason for this is that a variable <xsl:variable><xsl:copy-of select="."/></xsl:variable>
293 // can be evaluated in streaming mode, but an arbitrary expression using copy() inline can't (e.g.
294 // if it appears in a path expression or as an operand of an arithmetic expression)
295
296 if (considerRemoval && references.size() == 1 && ExpressionTool.dependsOnFocus(getSequence()) ) {
297 if (visitor.isOptimizeForStreaming()) {
298 considerRemoval = false;
299 }
300 // Disallow inlining if the focus of the variable reference differs from the containing binding.
301 Expression child = references.get(0);
302 Expression parent = child.getParentExpression();
303 while (parent != null && parent != this) {
304 Operand operand = ExpressionTool.findOperand(parent, child);
305 assert operand != null;
306 if (!operand.hasSameFocus()) {
307 considerRemoval = false;
308 break;
309 }
310 child = parent;
311 parent = child.getParentExpression();
312 }
313 }
314
315 if (considerRemoval && references.size() == 1) {
316 if (ExpressionTool.changesXsltContext(getSequence())) {
317 // Don't inline variables whose initializer might contain a call to xsl:result-document
318 considerRemoval = false;
319 } else if ((getSequence().getDependencies() & StaticProperty.DEPENDS_ON_CURRENT_GROUP) != 0) {
320 // Don't inline variables that depend on current-group() or current-grouping-key()
321 considerRemoval = false;
322 } else if (references.get(0).isInLoop()) {
323 // Don't inline variables where the variable reference is evaluated repeatedly
324 considerRemoval = false;
325 }
326 }
327
328 if (considerRemoval && (references.size() == 1 || getSequence() instanceof Literal ||
329 getSequence() instanceof VariableReference) &&
330 opt.isOptionSet(OptimizerOptions.INLINE_VARIABLES)) {
331 inlineReferences();
332 opt.trace("Inlined references to $" + getVariableName(), getAction());
333 references = null;
334 return getAction().optimize(visitor, contextItemType);
335 }
336 }
337
338 int tries = 0;
339 while (tries++ < 5) {
340 Expression seq0 = getSequence();
341 getSequenceOp().optimize(visitor, contextItemType);
342 if (getSequence() instanceof Literal && !isIndexedVariable) {
343 return optimize(visitor, contextItemType);
344 }
345 if (seq0 == getSequence()) {
346 break;
347 }
348 }
349
350 tries = 0;
351 while (tries++ < 5) {
352 Expression act0 = getAction();
353 getActionOp().optimize(visitor, contextItemType);
354 if (act0 == getAction()) {
355 break;
356 }
357 if (!isIndexedVariable && !needsEagerEvaluation) {
358 verifyReferences();
359 if (references != null && references.size() < 2) {
360 if (references.isEmpty()) {
361 // We may have removed references to the variable; try again at eliminating this expression.
362 hasLoopingReference = false;
363 return optimize(visitor, contextItemType);
364 } else {
365 // there is one remaining reference; try again at inlining if it's not in a loop
366 if (!references.get(0).isInLoop()) {
367 return optimize(visitor, contextItemType);
368 }
369 }
370 }
371 }
372 }
373
374 // Don't use lazy evaluation for a variable that is referenced inside the "try" part of a contained try catch (XSLT3 test try-031)
375
376 setEvaluator();
377 return this;
378 }
379
380 public void setEvaluator() {
381 if (needsEagerEvaluation) {
382 setEvaluator(ExpressionTool.eagerEvaluator(getSequence()));
383 } else if (isIndexedVariable()) {
384 setEvaluator(Evaluator.MAKE_INDEXED_VARIABLE);
385 } else if (evaluator == null) {
386 setEvaluator(ExpressionTool.lazyEvaluator(getSequence(), getNominalReferenceCount() > 1));
387 }
388 }
389
390 private void inlineReferences() {
391 // Note that the list of references might include references that are no longer reachable on the tree.
392 // We therefore take no action if (a) the parent of the reference is null, or (b) the reference is
393 // not found among the children of its parent.
394 for (VariableReference ref : references) {
395 Expression parent = ref.getParentExpression();
396 if (parent != null) {
397 Operand o = ExpressionTool.findOperand(parent, ref);
398 if (o != null) {
399 o.setChildExpression(getSequence().copy(new RebindingMap()));
400 }
401 ExpressionTool.resetStaticProperties(parent);
402 }
403 }
404 }
405
406 /**
407 * Return the estimated cost of evaluating an expression. This is a very crude measure based
408 * on the syntactic form of the expression (we have no knowledge of data values). We take
409 * the cost of evaluating a simple scalar comparison or arithmetic expression as 1 (one),
410 * and we assume that a sequence has length 5. The resulting estimates may be used, for
411 * example, to reorder the predicates in a filter expression so cheaper predicates are
412 * evaluated first.
413 */
414 @Override
415 public int getCost() {
416 return getSequence().getCost() + getAction().getCost();
417 }
418
419 /**
420 * Determine whether all references to this variable are using the value either
421 * (a) by atomizing it, or (b) by taking its string value. (This excludes usages
422 * such as testing the existence of a node or taking the effective boolean value).
423 *
424 * @return true if all references are known to atomize (or stringify) the value,
425 * false otherwise. The value false may indicate "not known".
426 */
427
428 private boolean allReferencesAreFlattened() {
429 if (references != null) {
430 for (VariableReference ref : references) {
431 if (!ref.isFlattened()) {
432 return false;
433 }
434 }
435 return true;
436 }
437 return false;
438 }
439
440 /**
441 * Determine whether this is a vacuous expression as defined in the XQuery update specification
442 *
443 * @return true if this expression is vacuous
444 */
445
446 public boolean isVacuousExpression() {
447 return getAction().isVacuousExpression();
448 }
449
450 /**
451 * Check that any elements and attributes constructed or returned by this expression are acceptable
452 * in the content model of a given complex type. It's always OK to say yes, since the check will be
453 * repeated at run-time. The process of checking element and attribute constructors against the content
454 * model of a complex type also registers the type of content expected of those constructors, so the
455 * static validation can continue recursively.
456 */
457
458 public void checkPermittedContents(SchemaType parentType, boolean whole) throws XPathException {
459 getAction().checkPermittedContents(parentType, whole);
460 }
461
462 /**
463 * For an expression that returns an integer or a sequence of integers, get
464 * a lower and upper bound on the values of the integers that may be returned, from
465 * static analysis. The default implementation returns null, meaning "unknown" or
466 * "not applicable". Other implementations return an array of two IntegerValue objects,
467 * representing the lower and upper bounds respectively. The values
468 * UNBOUNDED_LOWER and UNBOUNDED_UPPER are used by convention to indicate that
469 * the value may be arbitrarily large. The values MAX_STRING_LENGTH and MAX_SEQUENCE_LENGTH
470 * are used to indicate values limited by the size of a string or the size of a sequence.
471 *
472 * @return the lower and upper bounds of integer values in the result, or null to indicate
473 * unknown or not applicable.
474 */
475 /*@Nullable*/
476 @Override
477 public IntegerValue[] getIntegerBounds() {
478 return getAction().getIntegerBounds();
479 }
480
481 /**
482 * An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process().
483 * This method indicates which of these methods is provided directly. The other methods will always be available
484 * indirectly, using an implementation that relies on one of the other methods.
485 *
486 * @return the implementation method, for example {@link #ITERATE_METHOD} or {@link #EVALUATE_METHOD} or
487 * {@link #PROCESS_METHOD}
488 */
489 @Override
490 public int getImplementationMethod() {
491 return getAction().getImplementationMethod();
492 }
493
494
495
496 /**
497 * Iterate over the result of the expression to return a sequence of items
498 */
499
500 /*@NotNull*/
501 public SequenceIterator<?> iterate(XPathContext context) throws XPathException {
502 // minimize stack consumption by evaluating nested LET expressions iteratively
503 LetExpression let = this;
504 while (true) {
505 Sequence<?> val = let.eval(context);
506 context.setLocalVariable(let.getLocalSlotNumber(), val);
507 if (let.getAction() instanceof LetExpression) {
508 let = (LetExpression) let.getAction();
509 } else {
510 break;
511 }
512 }
513 return let.getAction().iterate(context);
514 }
515
516
517 /**
518 * Evaluate the variable.
519 *
520 * @param context the dynamic evaluation context
521 * @return the result of evaluating the expression that is bound to the variable
522 */
523
524 public Sequence<?> eval(XPathContext context) throws XPathException {
525 if (evaluator == null) {
526 setEvaluator(ExpressionTool.lazyEvaluator(getSequence(), getNominalReferenceCount() > 1));
527 }
528 try {
529 int savedOutputState = context.getTemporaryOutputState();
530 context.setTemporaryOutputState(StandardNames.XSL_VARIABLE);
531 Sequence<?> result = evaluator.evaluate(getSequence(), context);
532 context.setTemporaryOutputState(savedOutputState);
533 return result;
534 } catch (ClassCastException e) {
535 // Probably the evaluation mode is wrong, as a result of an expression rewrite. Try again.
536 assert false;
537 int savedOutputState = context.getTemporaryOutputState();
538 context.setTemporaryOutputState(StandardNames.XSL_VARIABLE);
539 Sequence<?> result = Evaluator.EAGER_SEQUENCE.evaluate(getSequence(), context);
540 context.setTemporaryOutputState(savedOutputState);
541 return result;
542 }
543 }
544
545 /**
546 * Evaluate the expression as a singleton
547 */
548
549 public Item evaluateItem(XPathContext context) throws XPathException {
550 // minimize stack consumption by evaluating nested LET expressions iteratively
551 LetExpression let = this;
552 while (true) {
553 Sequence<?> val = let.eval(context);
554 context.setLocalVariable(let.getLocalSlotNumber(), val);
555 if (let.getAction() instanceof LetExpression) {
556 let = (LetExpression) let.getAction();
557 } else {
558 break;
559 }
560 }
561 return let.getAction().evaluateItem(context);
562 }
563
564 /**
565 * Get the effective boolean value of the expression. This returns false if the value
566 * is the empty sequence, a zero-length string, a number equal to zero, or the boolean
567 * false. Otherwise it returns true.
568 *
569 * @param context The context in which the expression is to be evaluated
570 * @return the effective boolean value
571 * @throws net.sf.saxon.trans.XPathException
572 * if any dynamic error occurs evaluating the
573 * expression
574 */
575
576 public boolean effectiveBooleanValue(XPathContext context) throws XPathException {
577 // minimize stack consumption by evaluating nested LET expressions iteratively
578 LetExpression let = this;
579 while (true) {
580 Sequence<?> val = let.eval(context);
581 context.setLocalVariable(let.getLocalSlotNumber(), val);
582 if (let.getAction() instanceof LetExpression) {
583 let = (LetExpression) let.getAction();
584 } else {
585 break;
586 }
587 }
588 return let.getAction().effectiveBooleanValue(context);
589 }
590
591 /**
592 * Process this expression as an instruction, writing results to the current
593 * outputter
594 */
595
596 public void process(XPathContext context) throws XPathException {
597 // minimize stack consumption by evaluating nested LET expressions iteratively
598 LetExpression let = this;
599 while (true) {
600 Sequence<?> val = let.eval(context);
601 context.setLocalVariable(let.getLocalSlotNumber(), val);
602 if (let.getAction() instanceof LetExpression) {
603 let = (LetExpression) let.getAction();
604 } else {
605 break;
606 }
607 }
608 let.getAction().process(context);
609 }
610
611
612 /**
613 * Determine the data type of the items returned by the expression, if possible
614 *
615 * @return one of the values Type.STRING, Type.BOOLEAN, Type.NUMBER, Type.NODE,
616 * or Type.ITEM (meaning not known in advance)
617 */
618
619 /*@NotNull*/
620 public ItemType getItemType() {
621 return getAction().getItemType();
622 }
623
624 /**
625 * Get the static type of the expression as a UType, following precisely the type
626 * inference rules defined in the XSLT 3.0 specification.
627 *
628 * @return the static item type of the expression according to the XSLT 3.0 defined rules
629 * @param contextItemType the type of the context item
630 */
631 @Override
632 public UType getStaticUType(UType contextItemType) {
633 if (isInstruction()) {
634 return UType.ANY;
635 }
636 return getAction().getStaticUType(contextItemType);
637 }
638
639 /**
640 * Determine the static cardinality of the expression
641 */
642
643 public int computeCardinality() {
644 return getAction().getCardinality();
645 }
646
647 /**
648 * Get the static properties of this expression (other than its type). The result is
649 * bit-signficant. These properties are used for optimizations. In general, if
650 * property bit is set, it is true, but if it is unset, the value is unknown.
651 */
652
653 public int computeSpecialProperties() {
654 int props = getAction().getSpecialProperties();
655 int seqProps = getSequence().getSpecialProperties();
656 if ((seqProps & StaticProperty.NO_NODES_NEWLY_CREATED) == 0) {
657 props &= ~StaticProperty.NO_NODES_NEWLY_CREATED;
658 }
659 return props;
660 }
661
662 /**
663 * Mark tail function calls
664 */
665
666 public int markTailFunctionCalls(StructuredQName qName, int arity) {
667 return ExpressionTool.markTailFunctionCalls(getAction(), qName, arity);
668 }
669
670
671 /**
672 * Copy an expression. This makes a deep copy.
673 *
674 * @return the copy of the original expression
675 * @param rebindings variables whose binding needs to change
676 */
677
678 /*@NotNull*/
679 public Expression copy(RebindingMap rebindings) {
680 LetExpression let = new LetExpression();
681 ExpressionTool.copyLocationInfo(this, let);
682 let.isIndexedVariable = isIndexedVariable;
683 let.hasLoopingReference = hasLoopingReference;
684 let.setNeedsEagerEvaluation(needsEagerEvaluation);
685 let.setNeedsLazyEvaluation(needsLazyEvaluation);
686 let.setVariableQName(variableName);
687 let.setRequiredType(requiredType);
688 let.setSequence(getSequence().copy(rebindings));
689 let.setInstruction(isInstruction());
690 Expression newAction = getAction().copy(rebindings);
691 let.setAction(newAction);
692 ExpressionTool.rebindVariableReferences(newAction, this, let);
693 return let;
694 }
695
696 /**
697 * ProcessLeavingTail: called to do the real work of this instruction.
698 * The results of the instruction are written
699 * to the current Receiver, which can be obtained via the Controller.
700 *
701 * @param context The dynamic context of the transformation, giving access to the current node,
702 * the current variables, etc.
703 * @return null if the instruction has completed execution; or a TailCall indicating
704 * a function call or template call that is delegated to the caller, to be made after the stack has
705 * been unwound so as to save stack space.
706 */
707
708 public TailCall processLeavingTail(XPathContext context) throws XPathException {
709 // minimize stack consumption by evaluating nested LET expressions iteratively
710 LetExpression let = this;
711 while (true) {
712 Sequence<?> val = let.eval(context);
713 context.setLocalVariable(let.getLocalSlotNumber(), val);
714 if (let.getAction() instanceof LetExpression) {
715 let = (LetExpression) let.getAction();
716 } else {
717 break;
718 }
719 }
720 if (let.getAction() instanceof TailCallReturner) {
721 return ((TailCallReturner) let.getAction()).processLeavingTail(context);
722 } else {
723 let.getAction().process(context);
724 return null;
725 }
726 }
727
728 /**
729 * Evaluate an updating expression, adding the results to a Pending Update List.
730 * The default implementation of this method, which is used for non-updating expressions,
731 * throws an UnsupportedOperationException
732 *
733 * @param context the XPath dynamic evaluation context
734 * @param pul the pending update list to which the results should be written
735 */
736
737 public void evaluatePendingUpdates(XPathContext context, PendingUpdateList pul) throws XPathException {
738 // minimize stack consumption by evaluating nested LET expressions iteratively
739 LetExpression let = this;
740 while (true) {
741 Sequence<?> val = let.eval(context);
742 context.setLocalVariable(let.getLocalSlotNumber(), val);
743 if (let.getAction() instanceof LetExpression) {
744 let = (LetExpression) let.getAction();
745 } else {
746 break;
747 }
748 }
749 let.getAction().evaluatePendingUpdates(context, pul);
750 }
751
752
753 /**
754 * The toString() method for an expression attempts to give a representation of the expression
755 * in an XPath-like form, but there is no guarantee that the syntax will actually be true XPath.
756 * In the case of XSLT instructions, the toString() method gives an abstracted view of the syntax
757 *
758 * @return a representation of the expression as a string
759 */
760
761 public String toString() {
762 return "let $" + getVariableEQName() + " := " + getSequence() +
763 " return " + ExpressionTool.parenthesize(getAction());
764 }
765
766 /**
767 * Produce a short string identifying the expression for use in error messages
768 *
769 * @return a short string, sufficient to identify the expression
770 */
771 @Override
772 public String toShortString() {
773 return "let $" + getVariableName() + " := ...";
774 }
775
776 /**
777 * Diagnostic print of expression structure. The abstract expression tree
778 * is written to the supplied output destination.
779 */
780
781 public void export(ExpressionPresenter out) throws XPathException {
782 out.startElement("let", this);
783 out.emitAttribute("var", variableName);
784 out.emitAttribute("as", getSequence().getStaticType().toExportString());
785 ExpressionPresenter.ExportOptions options = (ExpressionPresenter.ExportOptions) out.getOptions();
786 if (options.target.equals("JS") && options.targetVersion == 2) {
787 out.emitAttribute("asJ", getSequence().getStaticType().toExportString2());
788 }
789 if (isIndexedVariable()) {
790 out.emitAttribute("indexable", "true");
791 }
792 out.emitAttribute("slot", getLocalSlotNumber() + "");
793 if (evaluator == null) {
794 setEvaluator(ExpressionTool.lazyEvaluator(getSequence(), getNominalReferenceCount() > 1));
795 }
796 out.emitAttribute("eval", getEvaluator().getCode() + "");
797 getSequence().export(out);
798 getAction().export(out);
799 out.endElement();
800 }
801
802 public void setEvaluator(Evaluator evaluator) {
803 this.evaluator = evaluator;
804 }
805
806 public void setEvaluationMode(int mode) {
807 this.evaluator = Evaluator.evaluatorForCode(mode);
808 }
809
810 public Evaluator getEvaluator() {
811 return evaluator;
812 }
813
814
815 }
816