Debian Codegraph @

net/sf/saxon/expr/parser/ExpressionTool.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.parser;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.Controller;
12 import net.sf.saxon.event.Receiver;
13 import net.sf.saxon.event.SequenceOutputter;
14 import net.sf.saxon.expr.*;
15 import net.sf.saxon.expr.flwor.Clause;
16 import net.sf.saxon.expr.flwor.FLWORExpression;
17 import net.sf.saxon.expr.flwor.LocalVariableBinding;
18 import net.sf.saxon.expr.instruct.*;
19 import net.sf.saxon.expr.sort.ConditionalSorter;
20 import net.sf.saxon.expr.sort.DocumentSorter;
21 import net.sf.saxon.functions.*;
22 import net.sf.saxon.lib.Logger;
23 import net.sf.saxon.lib.NamespaceConstant;
24 import net.sf.saxon.lib.StandardLogger;
25 import net.sf.saxon.ma.arrays.ArrayItem;
26 import net.sf.saxon.ma.map.MapItem;
27 import net.sf.saxon.om.*;
28 import net.sf.saxon.pattern.Pattern;
29 import net.sf.saxon.query.QueryModule;
30 import net.sf.saxon.style.Compilation;
31 import net.sf.saxon.style.ExpressionContext;
32 import net.sf.saxon.trans.Err;
33 import net.sf.saxon.trans.SymbolicName;
34 import net.sf.saxon.trans.XPathException;
35 import net.sf.saxon.tree.util.FastStringBuffer;
36 import net.sf.saxon.type.AnyItemType;
37 import net.sf.saxon.type.ItemType;
38 import net.sf.saxon.value.*;
39
40 import javax.xml.transform.SourceLocator;
41 import java.io.File;
42 import java.net.URI;
43 import java.net.URISyntaxException;
44 import java.util.Iterator;
45 import java.util.List;
46 import java.util.function.Predicate;
47
48 /**
49 * This class, ExpressionTool, contains a number of useful static methods
50 * for manipulating expressions. Most importantly, it provides the factory
51 * method make() for constructing a new expression
52 */
53
54 public class ExpressionTool {
55
56 public static final int UNDECIDED = -1;
57 public static final int EVALUATE_LITERAL = 0;
58 public static final int EVALUATE_VARIABLE = 1;
59 public static final int MAKE_CLOSURE = 3;
60 public static final int MAKE_MEMO_CLOSURE = 4;
61 public static final int RETURN_EMPTY_SEQUENCE = 5;
62 public static final int EVALUATE_AND_MATERIALIZE_VARIABLE = 6;
63 public static final int CALL_EVALUATE_OPTIONAL_ITEM = 7;
64 public static final int ITERATE_AND_MATERIALIZE = 8;
65 public static final int PROCESS = 9;
66 public static final int LAZY_TAIL_EXPRESSION = 10;
67 public static final int SHARED_APPEND_EXPRESSION = 11;
68 public static final int MAKE_INDEXED_VARIABLE = 12;
69 public static final int MAKE_SINGLETON_CLOSURE = 13;
70 public static final int EVALUATE_SUPPLIED_PARAMETER = 14;
71 public static final int STREAMING_ARGUMENT = 15;
72 public static final int CALL_EVALUATE_SINGLE_ITEM = 16;
73
74 private ExpressionTool() {
75 }
76
77 /**
78 * Parse an XPath expression. This performs the basic analysis of the expression against the
79 * grammar, it binds variable references and function calls to variable definitions and
80 * function definitions, and it performs context-independent expression rewriting for
81 * optimization purposes.
82 *
83 * @param expression The expression (as a character string)
84 * @param env An object giving information about the compile-time
85 * context of the expression
86 * @param start position of the first significant character in the expression
87 * @param terminator The token that marks the end of this expression; typically
88 * Token.EOF, but may for example be a right curly brace
89 * @param codeInjector true allows injection of tracing, debugging, or performance monitoring code; null if
90 * not required
91 * @return an object of type Expression
92 * @throws XPathException if the expression contains a static error
93 */
94
95 /*@NotNull*/
96 public static Expression make(String expression, StaticContext env,
97 int start, int terminator,
98 CodeInjector codeInjector) throws XPathException {
99 int languageLevel = env.getXPathVersion();
100 XPathParser parser = env.getConfiguration().newExpressionParser("XP", false, languageLevel);
101 if (codeInjector != null) {
102 parser.setCodeInjector(codeInjector);
103 }
104 if (terminator == -1) {
105 terminator = Token.EOF;
106 }
107 Expression exp = parser.parse(expression, start, terminator, env);
108 // TODO: parser.parse() already sets the retained static context
109 setDeepRetainedStaticContext(exp, env.makeRetainedStaticContext());
110 exp = exp.simplify();
111 return exp;
112 }
113
114 /**
115 * Ensure that every node in the expression tree has a retained static context.
116 * A node that already has a retained static context will propagate it to its children.
117 * @param exp the root of the expression tree
118 * @param rsc the retained static context to be applied to nodes that do not already have one,
119 * and that do not have an ancestor with an existing retained static context.
120 */
121
122 public static void setDeepRetainedStaticContext(Expression exp, RetainedStaticContext rsc) {
123 if (exp.getLocalRetainedStaticContext() == null) {
124 exp.setRetainedStaticContextLocally(rsc);
125 } else {
126 rsc = exp.getLocalRetainedStaticContext();
127 }
128 for (Operand o : exp.operands()) {
129 setDeepRetainedStaticContext(o.getChildExpression(), rsc);
130 }
131 }
132
133 /**
134 * Copy location information (the line number and reference to the container) from one expression
135 * to another
136 *
137 * @param from the expression containing the location information
138 * @param to the expression to which the information is to be copied
139 */
140
141 public static void copyLocationInfo(Expression from, Expression to) {
142 if (from != null && to != null) {
143 if (to.getLocation() == null || to.getLocation() == ExplicitLocation.UNKNOWN_LOCATION) {
144 to.setLocation(from.getLocation());
145 }
146 if (to.getLocalRetainedStaticContext() == null) {
147 to.setRetainedStaticContextLocally(from.getLocalRetainedStaticContext());
148 }
149 }
150 }
151
152 /**
153 * Remove unwanted sorting from an expression, at compile time, if and only if it is known
154 * that the result of the expression will be homogeneous (all nodes, or all atomic values).
155 * This is done when we need the effective boolean value of a sequence: the EBV of a
156 * homogenous sequence does not depend on its order, but this is not true when atomic
157 * values and nodes are mixed: (N, AV) is true, but (AV, N) is an error.
158 *
159 * @param exp the expression to be optimized
160 * @param forStreaming true if streamed evaluation of the expression is required
161 * @return the expression after rewriting
162 * @throws net.sf.saxon.trans.XPathException if a static error is found while doing the rewrite
163 */
164
165 public static Expression unsortedIfHomogeneous(Expression exp, boolean forStreaming)
166 throws XPathException {
167 if (exp instanceof Literal) {
168 return exp; // fast exit
169 }
170 if (exp.getItemType() instanceof AnyItemType) {
171 return exp;
172 } else {
173 return exp.unordered(false, forStreaming);
174 }
175 }
176
177 /**
178 * Get an expression evaluator to be used when lazy evaluation of an expression is
179 * preferred. This method is called at compile time, after all optimizations have been done,
180 * to determine the preferred strategy for lazy evaluation, depending on the type of expression.
181 *
182 * @param exp the expression to be evaluated
183 * @param repeatable true if the returned value needs to be readable more than once
184 * @return an expression evaluator
185 */
186
187 public static Evaluator lazyEvaluator(Expression exp, boolean repeatable) {
188 if (exp instanceof Literal) {
189 return Evaluator.LITERAL;
190
191 } else if (exp instanceof VariableReference) {
192 return Evaluator.VARIABLE;
193
194 } else if (exp instanceof SuppliedParameterReference) {
195 return Evaluator.SUPPLIED_PARAMETER;
196
197 } else if ((exp.getDependencies() &
198 (StaticProperty.DEPENDS_ON_POSITION |
199 StaticProperty.DEPENDS_ON_LAST |
200 StaticProperty.DEPENDS_ON_CURRENT_ITEM |
201 StaticProperty.DEPENDS_ON_CURRENT_GROUP |
202 StaticProperty.DEPENDS_ON_REGEX_GROUP)) != 0) {
203 // we can't save these values in the closure, so we evaluate
204 // the expression now if they are needed
205 return eagerEvaluator(exp);
206
207 } else if (exp instanceof ErrorExpression) {
208 return Evaluator.SINGLE_ITEM;
209 // evaluateItem() on an error expression throws the latent exception
210
211 } else if (!Cardinality.allowsMany(exp.getCardinality())) {
212 // singleton expressions are always evaluated eagerly
213 return eagerEvaluator(exp);
214
215 } else if (exp instanceof TailExpression) {
216 // Treat tail recursion as a special case, to avoid creating a deeply-nested
217 // tree of Closures.
218 TailExpression tail = (TailExpression) exp;
219 Expression base = tail.getBaseExpression();
220 if (base instanceof VariableReference) {
221 return Evaluator.LAZY_TAIL;
222 } else if (repeatable) {
223 return Evaluator.MEMO_CLOSURE;
224 } else {
225 return Evaluator.LAZY_SEQUENCE;
226 }
227
228 } else if (exp instanceof Block && ((Block) exp).isCandidateForSharedAppend()) {
229 // If the expression is a Block, that is, it is appending a value to a sequence,
230 // then we have the opportunity to use a shared list underpinning the old value and
231 // the new. This takes precedence over lazy evaluation (it would be possible to do this
232 // lazily, but more difficult). We currently do this for any Block that has a variable
233 // reference as one of its subexpressions. The most common case is that the first argument is a reference
234 // to an argument of recursive function, where the recursive function returns the result of
235 // appending to the sequence.
236 return Evaluator.SHARED_APPEND;
237
238 } else if (repeatable) {
239 // create a Closure, a wrapper for the expression and its context
240 return Evaluator.MEMO_CLOSURE;
241 } else {
242 return Evaluator.LAZY_SEQUENCE;
243 }
244 }
245
246
247 /**
248 * Get the evaluator to be used when eager evaluation of an expression is
249 * preferred. This method is called at compile time, after all optimizations have been done,
250 * to determine the preferred strategy for lazy evaluation, depending on the type of expression.
251 *
252 * @param exp the expression to be evaluated
253 * @return an integer constant identifying the evaluation mode
254 */
255
256 public static Evaluator eagerEvaluator(Expression exp) {
257 if (exp instanceof Literal && !(((Literal) exp).getValue() instanceof Closure)) {
258 return Evaluator.LITERAL;
259 }
260 if (exp instanceof VariableReference) {
261 return Evaluator.VARIABLE;
262 }
263 int m = exp.getImplementationMethod();
264 if ((m & Expression.EVALUATE_METHOD) != 0 && !Cardinality.allowsMany(exp.getCardinality())) {
265 if (Cardinality.allowsZero(exp.getCardinality())) {
266 return Evaluator.OPTIONAL_ITEM;
267 } else {
268 return Evaluator.SINGLE_ITEM;
269 }
270
271 } else if ((m & Expression.ITERATE_METHOD) != 0) {
272 return Evaluator.EAGER_SEQUENCE;
273 } else {
274 return Evaluator.PROCESS;
275 }
276 }
277
278
279 /**
280 * Do lazy evaluation of an expression. This will return a value, which may optionally
281 * be a SequenceIntent, which is a wrapper around an iterator over the value of the expression.
282 *
283 * @param exp the expression to be evaluated
284 * @param evaluationMode the evaluation mode for this expression
285 * @param context the run-time evaluation context for the expression. If
286 * the expression is not evaluated immediately, then parts of the
287 * context on which the expression depends need to be saved as part of
288 * the Closure
289 * @param ref an indication of how the value will be used. The value 1 indicates that the value
290 * is only expected to be used once, so that there is no need to keep it in memory. A small value >1
291 * indicates multiple references, so the value will be saved when first evaluated. The special value
292 * FILTERED indicates a reference within a loop of the form {@code $x[predicate]}, indicating that the value
293 * should be saved in a way that permits indexing.
294 * @return a value: either the actual value obtained by evaluating the
295 * expression, or a Closure containing all the information needed to
296 * evaluate it later
297 * @throws XPathException if any error occurs in evaluating the
298 * expression
299 */
300
301 public static Sequence<?> evaluate(
302 Expression exp, int evaluationMode, XPathContext context, int ref)
303 throws XPathException {
304 switch (evaluationMode) {
305
306 case EVALUATE_LITERAL:
307 return ((Literal) exp).getValue();
308
309 case EVALUATE_VARIABLE:
310 return ((VariableReference) exp).evaluateVariable(context);
311
312 case EVALUATE_SUPPLIED_PARAMETER:
313 return ((SuppliedParameterReference) exp).evaluateVariable(context);
314
315 case MAKE_CLOSURE:
316 return Closure.make(exp, context, ref);
317 //return SequenceExtent.makeSequenceExtent(exp.iterate(context));
318
319 case MAKE_MEMO_CLOSURE:
320 return Closure.make(exp, context, ref == 1 ? 10 : ref);
321 //return SequenceExtent.makeSequenceExtent(exp.iterate(context));
322
323 case MAKE_SINGLETON_CLOSURE:
324 return new SingletonClosure(exp, context);
325 //return SequenceExtent.makeSequenceExtent(exp.iterate(context));
326
327 case RETURN_EMPTY_SEQUENCE:
328 return EmptySequence.getInstance();
329
330 case EVALUATE_AND_MATERIALIZE_VARIABLE:
331 Sequence<?> v = ((VariableReference) exp).evaluateVariable(context);
332 if (v instanceof Closure) {
333 return v.iterate().materialize();
334 } else {
335 return v;
336 }
337
338 case CALL_EVALUATE_OPTIONAL_ITEM:
339 Item item = exp.evaluateItem(context);
340 if (item == null) {
341 return EmptySequence.getInstance();
342 } else {
343 return item;
344 }
345
346 case CALL_EVALUATE_SINGLE_ITEM:
347 return exp.evaluateItem(context);
348
349 case UNDECIDED:
350 case ITERATE_AND_MATERIALIZE:
351 if (ref == FilterExpression.FILTERED) {
352 return context.getConfiguration().makeSequenceExtent(exp, ref, context);
353 } else {
354 return exp.iterate(context).materialize();
355 }
356
357 case PROCESS:
358 return Evaluator.PROCESS.evaluate(exp, context);
359
360 case LAZY_TAIL_EXPRESSION: {
361 TailExpression tail = (TailExpression) exp;
362 VariableReference vr = (VariableReference) tail.getBaseExpression();
363 Sequence<?> base = evaluate(vr, EVALUATE_VARIABLE, context, ref);
364 if (base instanceof MemoClosure) {
365 SequenceIterator<?> it = base.iterate();
366 base = it.materialize();
367 }
368 if (base instanceof IntegerRange) {
369 long start = ((IntegerRange) base).getStart() + tail.getStart() - 1;
370 long end = ((IntegerRange) base).getEnd();
371 if (start == end) {
372 return Int64Value.makeIntegerValue(end);
373 } else if (start > end) {
374 return EmptySequence.getInstance();
375 } else {
376 return new IntegerRange(start, end);
377 }
378 }
379 if (base instanceof SequenceExtent) {
380 if (tail.getStart() > ((SequenceExtent) base).getLength()) {
381 return EmptySequence.getInstance();
382 } else {
383 return new SequenceExtent(
384 (SequenceExtent) base,
385 tail.getStart() - 1,
386 ((SequenceExtent) base).getLength() - tail.getStart() + 1).reduce();
387 }
388 }
389
390 return Closure.make(tail, context, ref);
391 }
392
393 case SHARED_APPEND_EXPRESSION: {
394 return Evaluator.SHARED_APPEND.evaluate(exp, context);
395 }
396
397 case MAKE_INDEXED_VARIABLE:
398 return context.getConfiguration().obtainOptimizer().makeIndexedValue(exp.iterate(context));
399
400 case STREAMING_ARGUMENT:
401 return context.getConfiguration().obtainOptimizer().evaluateStreamingArgument(exp, context);
402
403 default:
404 throw new IllegalArgumentException("Unknown evaluation mode " + evaluationMode);
405
406 }
407 }
408
409 /**
410 * Do lazy evaluation of an expression. This will return a value, which may optionally
411 * be a SequenceIntent, which is a wrapper around an iterator over the value of the expression.
412 *
413 * @param exp the expression to be evaluated
414 * @param context the run-time evaluation context for the expression. If
415 * the expression is not evaluated immediately, then parts of the
416 * context on which the expression depends need to be saved as part of
417 * the Closure
418 * @param repeatable an indication of how the value will be used. The value false indicates that the value
419 * is only expected to be used once, so that there is no need to keep it in memory. The value true
420 * indicates multiple references, so the value will be saved when first evaluated.
421 * @return a value: either the actual value obtained by evaluating the
422 * expression, or a Closure containing all the information needed to
423 * evaluate it later
424 * @throws XPathException if any error occurs in evaluating the
425 * expression
426 */
427
428 public static Sequence<?> lazyEvaluate(Expression exp, XPathContext context, boolean repeatable) throws XPathException {
429 Evaluator evaluator = lazyEvaluator(exp, repeatable);
430 return evaluator.evaluate(exp, context);
431 }
432
433 /**
434 * Evaluate an expression now; lazy evaluation is not permitted in this case
435 *
436 * @param exp the expression to be evaluated
437 * @param context the run-time evaluation context
438 * @return the result of evaluating the expression
439 * @throws net.sf.saxon.trans.XPathException if any dynamic error occurs evaluating the
440 * expression
441 */
442
443 public static GroundedValue<?> eagerEvaluate(Expression exp, XPathContext context) throws XPathException {
444 Evaluator evaluator = eagerEvaluator(exp);
445 return evaluator.evaluate(exp, context).materialize();
446 }
447
448 /**
449 * Scan an expression to find and mark any recursive tail function calls
450 *
451 * @param exp the expression to be analyzed
452 * @param qName the name of the containing function
453 * @param arity the arity of the containing function
454 * @return 0 if no tail call was found; 1 if a tail call to a different function was found;
455 * 2 if a tail call to the specified function was found. In this case the
456 * UserFunctionCall object representing the tail function call will also have been marked as
457 * a tail call.
458 */
459
460 public static int markTailFunctionCalls(Expression exp, StructuredQName qName, int arity) {
461 return exp.markTailFunctionCalls(qName, arity);
462 }
463
464 /**
465 * Construct indent string, for diagnostic output
466 *
467 * @param level the indentation level (the number of spaces to return)
468 * @return a string of "level*2" spaces
469 */
470
471 public static String indent(int level) {
472 FastStringBuffer fsb = new FastStringBuffer(level);
473 for (int i = 0; i < level; i++) {
474 fsb.append(" ");
475 }
476 return fsb.toString();
477 }
478
479 /**
480 * Ask whether one expression is a subexpression of another
481 * @param a the containing expression
482 * @param b the putative contained expression
483 * @return true if and only if b is a subexpression (at some level) of a
484 */
485
486 public static boolean contains(Expression a, Expression b) {
487 Expression temp = b;
488 while (temp != null) {
489 if (temp == a) {
490 return true;
491 } else {
492 temp = temp.getParentExpression();
493 }
494 }
495 return false;
496 }
497
498 /**
499 * Determine whether an expression contains a LocalParamSetter subexpression
500 *
501 * @param exp the expression to be tested
502 * @return true if the exprssion contains a local parameter setter
503 */
504
505 public static boolean containsLocalParam(Expression exp) {
506 return contains(exp, true, e -> e instanceof LocalParam);
507 }
508
509 /**
510 * Determine whether an expression contains a local variable reference,
511 * other than a reference to a local variable whose binding occurs
512 * within this expression
513 *
514 * @param exp the expression to be tested
515 * @return true if the expression contains a local variable reference to a local
516 * variable declared outside this expression.
517 */
518
519 public static boolean containsLocalVariableReference(final Expression exp) {
520 return contains(exp, false, e -> {
521 if (e instanceof LocalVariableReference) {
522 LocalVariableReference vref = (LocalVariableReference)e;
523 LocalBinding binding = vref.getBinding();
524 return !(binding instanceof Expression && contains(exp, (Expression) binding));
525 }
526 return false;
527 });
528 }
529
530 /**
531 * Test whether a given expression is, or contains, at any depth, an expression that satisfies a supplied
532 * condition
533 *
534 * @param exp the given expression
535 * @param sameFocusOnly if true, only subexpressions evaluated in the same focus are searched. If false,
536 * all subexpressions are searched
537 * @param predicate the condition to be satisfied
538 * @return true if the given expression is or contains an expression that satisfies the condition.
539 */
540
541 public static boolean contains(Expression exp, boolean sameFocusOnly, Predicate<Expression> predicate) {
542 if (predicate.test(exp)) {
543 return true;
544 }
545 for (Operand info : exp.operands()) {
546 if ((info.hasSameFocus() || !sameFocusOnly) && contains(info.getChildExpression(), sameFocusOnly, predicate)) {
547 return true;
548 }
549 }
550 return false;
551 }
552
553 /**
554 * Determine whether an expression possible calls (directly or indirectly) xsl:result-document, or
555 * has other context dependencies that prevent function inlining,
556 * which we assume is true if it contains a template call.
557 * A call on result-document disqualifies the function from being
558 * inlined, because error XTDE1480 would then not be detected. We don't have to worry about functions
559 * containing further function calls because they are disqualified from inlining anyway.
560 *
561 * @param exp the expression to be tested
562 * @return true if there is any possibility that calling the function might result in a call on
563 * xsl:result-document
564 */
565
566 public static boolean changesXsltContext(Expression exp) {
567 exp = exp.getInterpretedExpression();
568 if (exp instanceof ResultDocument || exp instanceof CallTemplate || exp instanceof ApplyTemplates ||
569 exp instanceof NextMatch || exp instanceof ApplyImports || exp.isCallOn(RegexGroup.class)
570 || exp.isCallOn(CurrentGroup.class)) {
571 return true;
572 }
573 for (Operand o : exp.operands()) {
574 if (changesXsltContext(o.getChildExpression())) {
575 return true;
576 }
577 }
578 return false;
579 }
580
581 /**
582 * Return true if a given expression is evaluated repeatedly
583 * when a given ancestor expression is evaluated once
584 *
585 * @param child the expression to be tested
586 * @param ancestor the ancestor expression. May be null, in which case the search goes all the way
587 * to the base of the stack.
588 * @return true if the current expression is evaluated repeatedly
589 */
590
591 public static boolean isLoopingSubexpression(Expression child, Expression ancestor) {
592 while (true) {
593
594 Expression parent = child.getParentExpression();
595 if (parent == null) {
596 return false;
597 }
598 if (hasLoopingSubexpression(parent, child)) {
599 return true;
600 }
601 if (parent == ancestor) {
602 return false;
603 }
604 child = parent;
605 }
606 }
607
608 public static boolean isLoopingReference(VariableReference reference, Binding binding) {
609 Expression child = reference;
610 Expression parent = child.getParentExpression();
611 while (true) {
612 if (parent == null) {
613 // haven't found the binding on the stack, so the safe thing is to assume we're in a loop
614 return true;
615 }
616 if (parent instanceof FLWORExpression) {
617 if (parent.hasVariableBinding(binding)) {
618 // The variable is declared in one of the clauses of the FLWOR expression
619 return ((FLWORExpression) parent).hasLoopingVariableReference(binding);
620 } else {
621 // The variable is declared outside the FLWOR expression
622 if (hasLoopingSubexpression(parent, child)) {
623 return true;
624 }
625 }
626 } else if (parent.getExpressionName().equals("tryCatch")) {
627 return true; // not actually a loop, but it's a simple way to prevent inlining of variables (test QT3 try-007)
628 } else {
629 if (parent instanceof ForEachGroup && parent.hasVariableBinding(binding)) {
630 return false;
631 }
632 if (hasLoopingSubexpression(parent, child)) {
633 return true;
634 }
635 if (parent.hasVariableBinding(binding)) {
636 return false;
637 }
638 }
639 child = parent;
640 parent = child.getParentExpression();
641 }
642 }
643
644 public static boolean hasLoopingSubexpression(Expression parent, Expression child) {
645 for (Operand info : parent.operands()) {
646 if (info.getChildExpression() == child) {
647 return info.isEvaluatedRepeatedly();
648 }
649 }
650 return false;
651 }
652
653 /**
654 * Get the focus-setting container of an expression
655 *
656 * *
657 * <p>Note, this always returns an expression or null. Unlike the like-named concept in the
658 * spec, it can't return a component such as a template or an attribute set.</p>
659 * @param exp the expression whose focus-setting container is required
660 * @return the focus-setting container, or null if the focus for the expression is the same as the
661 * focus for the containing component as a whole
662 */
663
664 public static Expression getFocusSettingContainer(Expression exp) {
665 Expression child = exp;
666 Expression parent = child.getParentExpression();
667 while (parent != null) {
668 Operand o = findOperand(parent, child);
669 if (o == null) {
670 throw new AssertionError();
671 }
672 if (!o.hasSameFocus()) {
673 return parent;
674 }
675 child = parent;
676 parent = child.getParentExpression();
677 }
678 return null;
679 }
680
681 /**
682 * Get the context-document-setting container of an expression. This is the same as the
683 * focus-setting container, except when the context-setting operand is a single-document node-set,
684 * in which case we can go up one more level. For example, given /a/b[/d/e = 3], the predicate
685 * /d/e = 3 can be loop-lifted from the filter expression, because it is known that the base
686 * expression /a/b is a single-document node-set.
687 *
688 * @param exp the expression whose document-context-setting container is required
689 * @return the context-document-setting container, or null if the focus for the expression is the same as the
690 * focus for the containing component as a whole
691 */
692
693 public static Expression getContextDocumentSettingContainer(Expression exp) {
694 Expression child = exp;
695 Expression parent = child.getParentExpression();
696 while (parent != null) {
697 if (parent instanceof ContextSwitchingExpression) {
698 ContextSwitchingExpression switcher = (ContextSwitchingExpression)parent;
699 if (child == switcher.getActionExpression()) {
700 if (switcher.getSelectExpression().hasSpecialProperty(StaticProperty.CONTEXT_DOCUMENT_NODESET)) {
701 parent.resetLocalStaticProperties();
702 parent.getSpecialProperties();
703 return getContextDocumentSettingContainer(parent);
704 }
705 }
706 }
707 Operand o = findOperand(parent, child);
708 if (o == null) {
709 throw new AssertionError();
710 }
711 if (!o.hasSameFocus()) {
712 return parent;
713 }
714 child = parent;
715 parent = child.getParentExpression();
716 }
717 return null;
718 }
719
720 /**
721 * Reset the static properties for the current expression and for all its containing expressions.
722 * This should be done whenever the expression is changed in a way that might
723 * affect the properties. It causes the properties to be recomputed next time they are needed.
724 *
725 * @param exp the expression whose properties are to be reset; the method also resets local
726 * properties for all its ancestor expressions.
727 */
728
729 public static void resetStaticProperties(Expression exp) {
730 int i = 0;
731 while (exp != null) {
732 exp.resetLocalStaticProperties();
733 exp = exp.getParentExpression();
734 if (i++ > 100000) {
735 throw new IllegalStateException("Loop in parent expression chain");
736 }
737 }
738 }
739
740 /**
741 * Return true if two objects are equal or if both are null
742 *
743 * @param x the first object
744 * @param y the second object
745 * @return true if both x and y are null or if x.equals(y)
746 */
747
748 public static boolean equalOrNull(Object x, Object y) {
749 if (x == null) {
750 return y == null;
751 } else {
752 return x.equals(y);
753 }
754 }
755
756 /**
757 * Helper method to construct an iterator over the results of the expression when all that
758 * the expression itself offers is a process() method. This builds the entire results of the
759 * expression as a sequence in memory and then iterates over it.
760 *
761 * @param context the dynamic evaluation context
762 * @return an iterator over the results of the expression
763 * @throws XPathException if a dynamic error occurs
764 */
765
766 public static SequenceIterator<?> getIteratorFromProcessMethod(
767 Expression exp, XPathContext context) throws XPathException {
768 Controller controller = context.getController();
769 assert controller != null;
770 Receiver saved = context.getReceiver();
771 SequenceOutputter seq = controller.allocateSequenceOutputter(20);
772 seq.getPipelineConfiguration().setHostLanguage(exp.getPackageData().getHostLanguage());
773 context.setReceiver(seq);
774 exp.process(context);
775 context.setReceiver(saved);
776 seq.close();
777 return seq.iterate();
778 }
779
780 /**
781 * Helper method to construct an item representing the results of the expression when all that
782 * the expression itself offers is a process() method.
783 *
784 * @param context the dynamic evaluation context
785 * @return an iterator over the results of the expression
786 * @throws XPathException if a dynamic error occurs
787 */
788
789 public static Item getItemFromProcessMethod(Expression exp, XPathContext context) throws XPathException {
790 Controller controller = context.getController();
791 assert controller != null;
792 Receiver saved = context.getReceiver();
793 SequenceOutputter seq = controller.allocateSequenceOutputter(1);
794 seq.getPipelineConfiguration().setHostLanguage(exp.getPackageData().getHostLanguage());
795 context.setReceiver(seq);
796
797 exp.process(context);
798
799 context.setReceiver(saved);
800 seq.close();
801 Item result = seq.getFirstItem();
802 seq.reset();
803 return result;
804 }
805
806 @FunctionalInterface
807 public interface ExpressionPredicate {
808 boolean test(Expression e);
809 }
810
811 /**
812 * Allocate slot numbers to range variables
813 *
814 * @param exp the expression whose range variables need to have slot numbers assigned
815 * @param nextFree the next slot number that is available for allocation
816 * @param frame a SlotManager object that is used to track the mapping of slot numbers
817 * to variable names for debugging purposes. May be null.
818 * @return the next unallocated slot number.
819 */
820
821 public static int allocateSlots(Expression exp, int nextFree, SlotManager frame) {
822
823 if (exp instanceof Assignation) {
824 ((Assignation) exp).setSlotNumber(nextFree);
825 int count = ((Assignation) exp).getRequiredSlots();
826 nextFree += count;
827 if (frame != null) {
828 frame.allocateSlotNumber(((Assignation) exp).getVariableQName());
829 }
830 }
831 if (exp instanceof LocalParam && ((LocalParam) exp).getSlotNumber() < 0) {
832 ((LocalParam) exp).setSlotNumber(nextFree++);
833 }
834
835 if (exp instanceof FLWORExpression) {
836 for (Clause c : ((FLWORExpression) exp).getClauseList()) {
837 for (LocalVariableBinding b : c.getRangeVariables()) {
838 b.setSlotNumber(nextFree++);
839 frame.allocateSlotNumber(b.getVariableQName());
840 }
841 }
842 }
843 if (exp instanceof VariableReference) {
844 VariableReference var = (VariableReference) exp;
845 Binding binding = var.getBinding();
846 if (exp instanceof LocalVariableReference) {
847 ((LocalVariableReference) var).setSlotNumber(((LocalBinding) binding).getLocalSlotNumber());
848 }
849 if (binding instanceof Assignation && ((LocalBinding) binding).getLocalSlotNumber() < 0) {
850 // This indicates something badly wrong: we've found a variable reference on the tree, that's
851 // bound to a variable declaration that is no longer on the tree. All we can do is print diagnostics.
852 // The most common reason for this failure is that the declaration of the variable was removed
853 // from the tree in the mistaken belief that there were no references to the variable. Variable
854 // references are counted during the typeCheck phase, so this can happen if typeCheck() fails to
855 // visit some branch of the expression tree.
856 Assignation decl = (Assignation) binding;
857 Logger err;
858 try {
859 err = exp.getConfiguration().getLogger();
860 } catch (Exception ex) {
861 err = new StandardLogger();
862 }
863 String msg = "*** Internal Saxon error: local variable encountered whose binding has been deleted";
864 err.error(msg);
865 err.error("Variable name: " + decl.getVariableName());
866 err.error("Line number of reference: " + var.getLocation().getLineNumber() + " in " + var.getLocation().getSystemId());
867 err.error("Line number of declaration: " + decl.getLocation().getLineNumber() + " in " + decl.getLocation().getSystemId());
868 err.error("DECLARATION:");
869 try {
870 decl.explain(err);
871 } catch (Exception e) {
872 // ignore the secondary error
873 }
874 throw new IllegalStateException(msg);
875 }
876
877 }
878
879 if (exp instanceof Pattern) {
880 nextFree = ((Pattern) exp).allocateSlots(frame, nextFree);
881 } else {
882 for (Operand o : exp.operands()) {
883 nextFree = allocateSlots(o.getChildExpression(), nextFree, frame);
884 }
885 }
886 return nextFree;
887
888 // Note, we allocate a distinct slot to each range variable, even if the
889 // scopes don't overlap. This isn't strictly necessary, but might help
890 // debugging.
891 }
892
893 /**
894 * Determine the effective boolean value of a sequence, given an iterator over the sequence
895 *
896 * @param iterator An iterator over the sequence whose effective boolean value is required
897 * @return the effective boolean value
898 * @throws XPathException if a dynamic error occurs
899 */
900 public static boolean effectiveBooleanValue(SequenceIterator iterator) throws XPathException {
901 Item first = iterator.next();
902 if (first == null) {
903 return false;
904 }
905 if (first instanceof NodeInfo) {
906 iterator.close();
907 return true;
908 } else if (first instanceof AtomicValue) {
909 if (first instanceof BooleanValue) {
910 if (iterator.next() != null) {
911 iterator.close();
912 ebvError("a sequence of two or more items starting with a boolean");
913 }
914 iterator.close();
915 return ((BooleanValue) first).getBooleanValue();
916 } else if (first instanceof StringValue) { // includes anyURI value
917 if (iterator.next() != null) {
918 iterator.close();
919 ebvError("a sequence of two or more items starting with a string");
920 }
921 return !((StringValue) first).isZeroLength();
922 } else if (first instanceof NumericValue) {
923 if (iterator.next() != null) {
924 iterator.close();
925 ebvError("a sequence of two or more items starting with a numeric value");
926 }
927 final NumericValue n = (NumericValue) first;
928 return (n.compareTo(0) != 0) && !n.isNaN();
929 } else {
930 iterator.close();
931 ebvError("a sequence starting with an atomic value of type " + ((AtomicValue) first).getItemType().getTypeName().getDisplayName());
932 return false;
933 }
934 } else if (first instanceof Function) {
935 iterator.close();
936 if (first instanceof ArrayItem) {
937 ebvError("a sequence starting with an array item (" + first.toShortString() + ")");
938 return false;
939 } else if (first instanceof MapItem) {
940 ebvError("a sequence starting with a map (" + first.toShortString() + ")");
941 return false;
942 } else {
943 ebvError("a sequence starting with a function (" + first.toShortString() + ")");
944 return false;
945 }
946 } else if (first instanceof ObjectValue) {
947 if (iterator.next() != null) {
948 iterator.close();
949 ebvError("a sequence of two or more items starting with an external object value");
950 }
951 return true;
952 }
953 ebvError("a sequence starting with an item of unknown kind");
954 return false;
955 }
956
957 /**
958 * Determine the effective boolean value of a single item
959 *
960 * @param item the item whose effective boolean value is required
961 * @return the effective boolean value
962 * @throws XPathException if a dynamic error occurs
963 */
964 public static boolean effectiveBooleanValue(Item item) throws XPathException {
965 if (item == null) {
966 return false;
967 }
968 if (item instanceof NodeInfo) {
969 return true;
970 } else {
971 if (item instanceof BooleanValue) {
972 return ((BooleanValue) item).getBooleanValue();
973 } else if (item instanceof StringValue) { // includes anyURI value
974 return !((StringValue) item).isZeroLength();
975 } else if (item instanceof NumericValue) {
976 final NumericValue n = (NumericValue) item;
977 return (n.compareTo(0) != 0) && !n.isNaN();
978 } else if (item instanceof ExternalObject) {
979 return true;
980 } else {
981 ebvError("an atomic value other than a boolean, number, string, or URI");
982 return false;
983 }
984 }
985 }
986
987 /**
988 * Report an error in computing the effective boolean value of an expression
989 *
990 * @param reason the nature of the error
991 * @throws XPathException always
992 */
993
994 public static void ebvError(String reason) throws XPathException {
995 XPathException err = new XPathException("Effective boolean value is not defined for " + reason);
996 err.setErrorCode("FORG0006");
997 err.setIsTypeError(true);
998 throw err;
999 }
1000
1001 /**
1002 * Report an error in computing the effective boolean value of an expression
1003 *
1004 * @param reason the nature of the error
1005 * @throws XPathException always
1006 */
1007
1008 public static void ebvError(String reason, Expression cause) throws XPathException {
1009 XPathException err = new XPathException("Effective boolean value is not defined for " + reason);
1010 err.setErrorCode("FORG0006");
1011 err.setIsTypeError(true);
1012 err.setFailingExpression(cause);
1013 throw err;
1014 }
1015
1016 /**
1017 * Ask whether an expression has a dependency on the focus
1018 *
1019 * @param exp the expression
1020 * @return true if the value of the expression depends on the context item, position, or size
1021 */
1022
1023 public static boolean dependsOnFocus(Expression exp) {
1024 return (exp.getDependencies() & StaticProperty.DEPENDS_ON_FOCUS) != 0;
1025 }
1026
1027 /**
1028 * Determine whether an expression depends on any one of a set of variables
1029 *
1030 * @param exp the expression being tested
1031 * @param bindingList the set of variables being tested
1032 * @return true if the expression depends on one of the given variables
1033 */
1034
1035 public static boolean dependsOnVariable(Expression exp, final Binding[] bindingList) {
1036 return !(bindingList == null || bindingList.length == 0) &&
1037 contains(exp, false, e -> {
1038 if (e instanceof VariableReference) {
1039 for (Binding binding : bindingList) {
1040 if (((VariableReference) e).getBinding() == binding) {
1041 return true;
1042 }
1043 }
1044 }
1045 return false;
1046 });
1047 }
1048
1049 /**
1050 * Gather a list of all the variable bindings on which a given expression depends.
1051 * In the light of spec bug 29590, this only considers variable references that
1052 * are unconditionally evaluated: that is, it ignores variable references appearing
1053 * in the then/else branches of a conditional or equivalent. Cycles involving
1054 * conditional evaluation are detected dynamically.
1055 *
1056 * @param e the expression being tested
1057 * @param list a list to which the bindings are to be added. The items in this list must
1058 * implement {@link Binding}
1059 */
1060
1061 public static void gatherReferencedVariables(Expression e, List<Binding> list) {
1062 if (e instanceof VariableReference) {
1063 Binding binding = ((VariableReference) e).getBinding();
1064 if (!list.contains(binding)) {
1065 list.add(binding);
1066 }
1067 } else {
1068 for (Operand o : e.operands()) {
1069 if (!o.getOperandRole().isInChoiceGroup()) {
1070 gatherReferencedVariables(o.getChildExpression(), list);
1071 }
1072 }
1073 }
1074 }
1075
1076 /**
1077 * Determine whether the expression contains any variable references or calls to user-written functions
1078 *
1079 * @param exp the expression being tested
1080 * @return true if the expression includes a variable reference or function call, or an XSLT construct
1081 * equivalent to a function call (e.g call-template). Also returns true if the expression includes
1082 * a variable binding element, as (a) this is likely to mean it also contains a reference, and (b)
1083 * it also needs to be caught on the same paths.
1084 */
1085
1086 public static boolean refersToVariableOrFunction(Expression exp) {
1087 return contains(exp, false,
1088 e -> e instanceof VariableReference
1089 || e instanceof UserFunctionCall
1090 || e instanceof Binding
1091 || e instanceof CallTemplate
1092 || e instanceof ApplyTemplates
1093 || e instanceof ApplyImports
1094 || isCallOnSystemFunction(e, "function-lookup")
1095 || e.isCallOn(ApplyFn.class));
1096 }
1097
1098 public static boolean isCallOnSystemFunction(Expression e, String localName) {
1099 return e instanceof StaticFunctionCall && localName.equals(((StaticFunctionCall)e).getFunctionName().getLocalPart());
1100 }
1101
1102 /**
1103 * Determine whether an expression contains a call on the function with a given name
1104 *
1105 * @param exp The expression being tested
1106 * @param qName The name of the function
1107 * @param sameFocusOnly If true, only expressions with the same (top-level) focus are searched
1108 * @return true if the expression contains a call on the function
1109 */
1110
1111 public static boolean callsFunction(Expression exp, final StructuredQName qName, boolean sameFocusOnly) {
1112 return contains(exp, sameFocusOnly,
1113 e -> e instanceof FunctionCall && qName.equals(((FunctionCall) e).getFunctionName())
1114 );
1115 }
1116
1117 /**
1118 * Determine whether an expression has a subexpression of a given implementation class
1119 *
1120 * @param exp The expression being tested
1121 * @param subClass The implementation class of the sought subexpression
1122 * @return true if the expression contains a subexpression that is an instance of the specified class
1123 */
1124
1125 public static boolean containsSubexpression(Expression exp, final Class<? extends Expression> subClass) {
1126 return contains(exp, false, e -> subClass.isAssignableFrom(e.getClass()));
1127 }
1128
1129
1130 /**
1131 * Gather a list of all the user-defined functions which a given expression calls directly
1132 *
1133 * @param e the expression being tested
1134 * @param list a list of the functions that are called. The items in this list must
1135 * be objects of class {@link UserFunction}
1136 */
1137
1138 public static void gatherCalledFunctions(Expression e, List<UserFunction> list) {
1139 if (e instanceof UserFunctionCall) {
1140 UserFunction function = ((UserFunctionCall) e).getFunction();
1141 if (!list.contains(function)) {
1142 list.add(function);
1143 }
1144 } else {
1145 for (Operand o : e.operands()) {
1146 gatherCalledFunctions(o.getChildExpression(), list);
1147 }
1148 }
1149 }
1150
1151 /**
1152 * Gather a list of the names of the user-defined functions which a given expression calls directly
1153 *
1154 * @param e the expression being tested
1155 * @param list a list of the functions that are called. The items in this list are strings in the format
1156 * "{uri}local/arity"
1157 */
1158
1159 public static void gatherCalledFunctionNames(Expression e, List<SymbolicName> list) {
1160 if (e instanceof UserFunctionCall) {
1161 list.add(((UserFunctionCall) e).getSymbolicName());
1162 } else {
1163 for (Operand o : e.operands()) {
1164 gatherCalledFunctionNames(o.getChildExpression(), list);
1165 }
1166 }
1167 }
1168
1169 /**
1170 * Optimize the implementation of a component such as a function, template, or global variable
1171 *
1172 * @param body the expression forming the body of the component
1173 * @param compilation the current compilation. May be null.
1174 * @param visitor the expression visitor
1175 * @param cisi information about the context item for evaluation of the component body
1176 * @param extractGlobals true if constant expressions are to be extracted as global variables
1177 * @return the optimized expression body
1178 * @throws XPathException if anything goes wrong
1179 */
1180
1181 public static Expression optimizeComponentBody(
1182 Expression body, final Compilation compilation, ExpressionVisitor visitor, ContextItemStaticInfo cisi, boolean extractGlobals)
1183 throws XPathException {
1184 final Configuration config = visitor.getConfiguration();
1185 Optimizer opt = visitor.obtainOptimizer();
1186 StaticContext env = visitor.getStaticContext();
1187 boolean compileWithTracing = config.isCompileWithTracing();
1188 if (!compileWithTracing) {
1189 // Bug 3472 - desperate attempts to discover whether tracing was enabled for this particular compilation
1190 if (compilation != null) {
1191 compileWithTracing = compilation.getCompilerInfo().isCompileWithTracing();
1192 } else if (env instanceof QueryModule) {
1193 compileWithTracing = ((QueryModule) env).getUserQueryContext().isCompileWithTracing();
1194 } else if (env instanceof ExpressionContext) {
1195 compileWithTracing = ((ExpressionContext) env).getStyleElement().getCompilation().getCompilerInfo().isCompileWithTracing();
1196 }
1197 }
1198 if (opt.isOptionSet(OptimizerOptions.MISCELLANEOUS) && !compileWithTracing) {
1199 ExpressionTool.resetPropertiesWithinSubtree(body);
1200 if (opt.isOptionSet(OptimizerOptions.MISCELLANEOUS)) {
1201 body = body.optimize(visitor, cisi);
1202 }
1203 body.setParentExpression(null);
1204 if (opt.isOptionSet(OptimizerOptions.LOOP_LIFTING)) {
1205 body = LoopLifter.process(body, visitor, cisi);
1206 }
1207 if (extractGlobals && compilation != null) {
1208 Expression exp2 = opt.promoteExpressionsToGlobal(body, compilation.getPrincipalStylesheetModule(), visitor);
1209 if (exp2 != null) {
1210 // Try another optimization pass: extracting global variables can identify things that are indexable
1211 ExpressionTool.resetPropertiesWithinSubtree(exp2);
1212 body = exp2.optimize(visitor, cisi);
1213 }
1214 }
1215 } else {
1216 body = avoidDocumentSort(body);
1217 }
1218
1219 if (!visitor.isOptimizeForStreaming()) {
1220 body = opt.eliminateCommonSubexpressions(body);
1221 }
1222 opt.injectByteCodeCandidates(body);
1223 opt.prepareForStreaming(body);
1224
1225 computeEvaluationModesForUserFunctionCalls(body);
1226 body.restoreParentPointers();
1227 return body;
1228 }
1229
1230 /**
1231 * An optimization-lite pass over the expression tree that attempts to eliminate unnecessary
1232 * sorting into document order. We avoid a full optimization when STRICT_STREAMABILITY analysis
1233 * is requested, because it rewrites non-streamable expressions into streamable expressions;
1234 * but to get the streamability right, we need as a minimum to eliminate unwanted document sort
1235 * operations.
1236 */
1237
1238 private static Expression avoidDocumentSort(Expression exp) {
1239 if (exp instanceof DocumentSorter) {
1240 Expression base = ((DocumentSorter) exp).getBaseExpression();
1241 if (base.hasSpecialProperty(StaticProperty.ORDERED_NODESET)) {
1242 return base;
1243 }
1244 return exp;
1245 } else if (exp instanceof ConditionalSorter) {
1246 DocumentSorter sorter = ((ConditionalSorter) exp).getDocumentSorter();
1247 Expression eliminatedSorter = avoidDocumentSort(sorter);
1248 if (eliminatedSorter != sorter) {
1249 return eliminatedSorter;
1250 }
1251 }
1252 for (Operand o : exp.operands()) {
1253 o.setChildExpression(avoidDocumentSort(o.getChildExpression()));
1254 }
1255 return exp;
1256 }
1257
1258 /**
1259 * Compute argument evaluation modes for all calls on user defined functions with
1260 * a specified expression
1261 */
1262
1263 public static void computeEvaluationModesForUserFunctionCalls(Expression exp) throws XPathException {
1264 ExpressionTool.processExpressionTree(exp, null, (expression, result) -> {
1265 if (expression instanceof UserFunctionCall) {
1266 ((UserFunctionCall) expression).allocateArgumentEvaluators();
1267 }
1268 if (expression instanceof LocalParam) {
1269 ((LocalParam)expression).computeEvaluationMode();
1270 }
1271 return false;
1272 });
1273 }
1274
1275 /**
1276 * Clear all computed streamability properties for an expression and its contained subtree
1277 * @param exp the expression whose streamability data is to be reset
1278 * @throws XPathException should not happen
1279 */
1280
1281 public static void clearStreamabilityData(Expression exp) throws XPathException {
1282 ExpressionTool.processExpressionTree(exp, null, (expression, result) -> {
1283 expression.setExtraProperty("P+S", null);
1284 expression.setExtraProperty("inversion", null);
1285 return false;
1286 });
1287 }
1288
1289 /**
1290 * Reset cached static properties within a subtree, meaning that they have to be
1291 * recalulated next time they are required
1292 *
1293 * @param exp the root of the subtree within which static properties should be reset
1294 */
1295
1296 public static void resetPropertiesWithinSubtree(Expression exp) {
1297 exp.resetLocalStaticProperties();
1298 if (exp instanceof LocalVariableReference) {
1299 LocalVariableReference ref = (LocalVariableReference) exp;
1300 Binding binding = ref.getBinding();
1301 if (binding instanceof Assignation) {
1302 binding.addReference(ref, ref.isInLoop());
1303 }
1304 }
1305 for (Operand o : exp.operands()) {
1306 resetPropertiesWithinSubtree(o.getChildExpression());
1307 o.getChildExpression().setParentExpression(exp);
1308 }
1309
1310 }
1311
1312 /**
1313 * Resolve calls to the XSLT current() function within an expression
1314 *
1315 * @param exp the expression within which calls to current() should be resolved
1316 * @return the expression after resolving calls to current()
1317 */
1318
1319 public static Expression resolveCallsToCurrentFunction(Expression exp) {
1320 if (exp.isCallOn(Current.class)) {
1321 ContextItemExpression cie = new ContextItemExpression();
1322 copyLocationInfo(exp, cie);
1323 return cie;
1324 } else {
1325 if (callsFunction(exp, Current.FN_CURRENT, true)) {
1326 // replace trivial (same-focus) calls to current by a simple "."
1327 replaceTrivialCallsToCurrent(exp);
1328 }
1329 if (callsFunction(exp, Current.FN_CURRENT, false)) {
1330 // replace non-trivial (different-focus) calls to current by a variable reference
1331 LetExpression let = new LetExpression();
1332 let.setVariableQName(
1333 new StructuredQName("vv", NamespaceConstant.SAXON_GENERATED_VARIABLE, "current" + exp.hashCode()));
1334 let.setRequiredType(SequenceType.SINGLE_ITEM);
1335 let.setSequence(new CurrentItemExpression());
1336 replaceCallsToCurrent(exp, let);
1337 let.setAction(exp);
1338 return let;
1339 } else {
1340 return exp;
1341 }
1342 }
1343 }
1344
1345 /**
1346 * Get a list of all references to a particular variable within a subtree
1347 *
1348 * @param exp the expression at the root of the subtree
1349 * @param binding the variable binding whose references are sought
1350 * @param list a list to be populated with the references to this variable
1351 */
1352
1353 public static void gatherVariableReferences(Expression exp, Binding binding, List<VariableReference> list) {
1354 if (exp instanceof VariableReference &&
1355 ((VariableReference) exp).getBinding() == binding) {
1356 list.add((VariableReference) exp);
1357 } else {
1358 for (Operand o : exp.operands()) {
1359 gatherVariableReferences(o.getChildExpression(), binding, list);
1360 }
1361 }
1362 }
1363
1364 /**
1365 * Process every node on a subtree of the expression tree using a supplied action.
1366 *
1367 * @param root the root of the subtree to be processed
1368 * @param result an arbitrary object that is passed to each action call and that can be
1369 * updated to gather results of the processing
1370 * @param action an action to be performed on each node of the expression tree. Processing
1371 * stops if any action returns the value true
1372 * @return true if any call on the action operand returned true
1373 * @throws XPathException if the callback throws an error
1374 */
1375
1376 public static boolean processExpressionTree(Expression root, Object result, ExpressionAction action) throws XPathException {
1377 boolean done = action.process(root, result);
1378 if (!done) {
1379 for (Operand o : root.operands()) {
1380 done = processExpressionTree(o.getChildExpression(), result, action);
1381 if (done) {
1382 return true;
1383 }
1384 }
1385 }
1386 return false;
1387 }
1388
1389 // /**
1390 // * Process all references to a particular variable within a subtree
1391 // *
1392 // * @param exp the expression at the root of the subtree
1393 // * @param binding the variable binding whose references are sought
1394 // * @param action the action to be applied to all references to this variable
1395 // * @return true if processing finished early at the request of an action invocation; false if processing ran to completion
1396 // */
1397 //
1398 // public static boolean processVariableReferences(Expression exp, Binding binding, ExpressionAction<VariableReference> action) throws XPathException {
1399 // if (exp instanceof VariableReference && ((VariableReference) exp).getBinding() == binding) {
1400 // return action.process((VariableReference) exp);
1401 // } else {
1402 // for (Operand o : exp.operands()) {
1403 // boolean done = processVariableReferences(o.getChildExpression(), binding, action);
1404 // if (done) {
1405 // return true;
1406 // }
1407 // }
1408 // return false;
1409 // }
1410 // }
1411
1412 /**
1413 * Callback for selecting expressions in the tree
1414 */
1415
1416 public interface ExpressionSelector {
1417 boolean matches(Expression exp);
1418 }
1419
1420 /**
1421 * Replace all selected subexpressions within a subtree
1422 *
1423 * @param exp the expression at the root of the subtree
1424 * @param selector callback to determine whether a subexpression is selected
1425 * @param replacement the expression to be used in place of the variable reference
1426 * @param mustCopy if true, the replacement expression must be copied before use
1427 * @return true if a replacement has been performed (in which case the replacement expression
1428 * must be copied before being used again).
1429 */
1430
1431 public static boolean replaceSelectedSubexpressions(
1432 Expression exp, ExpressionSelector selector, Expression replacement, boolean mustCopy) {
1433 boolean replaced = false;
1434 for (Operand o : exp.operands()) {
1435 if (replaced) {
1436 mustCopy = true;
1437 }
1438 Expression child = o.getChildExpression();
1439 if (selector.matches(child)) {
1440 Expression e2 = mustCopy ? replacement.copy(new RebindingMap()) : replacement;
1441 o.setChildExpression(e2);
1442 replaced = true;
1443 } else {
1444 replaced = replaceSelectedSubexpressions(child, selector, replacement, mustCopy);
1445 }
1446 }
1447 return replaced;
1448 }
1449
1450 /**
1451 * Replace all references to a particular variable within a subtree
1452 *
1453 * @param exp the expression at the root of the subtree
1454 * @param binding the variable binding whose references are sought
1455 * @param replacement the expression to be used in place of the variable reference
1456 * @param mustCopy true if the replacement expression must be copied before use
1457 */
1458
1459 public static void replaceVariableReferences(Expression exp, final Binding binding, Expression replacement, boolean mustCopy) {
1460 ExpressionSelector selector =
1461 child -> child instanceof VariableReference && ((VariableReference) child).getBinding() == binding;
1462 replaceSelectedSubexpressions(exp, selector, replacement, mustCopy);
1463 }
1464
1465 /**
1466 * Determine how often a variable is referenced. This is the number of times
1467 * it is referenced at run-time: so a reference in a loop counts as "many". This code
1468 * currently handles local variables (Let expressions) and function parameters. It is
1469 * not currently used for XSLT template parameters. It's not the end of the world if
1470 * the answer is wrong (unless it's wrongly given as zero), but if wrongly returned as
1471 * 1 then the variable will be repeatedly evaluated.
1472 *
1473 * @param exp the expression within which variable references are to be counted
1474 * @param binding identifies the variable of interest
1475 * @param inLoop true if the expression is within a loop, in which case a reference counts as many.
1476 * This should be set to false on the initial call, it may be set to true on an internal recursive
1477 * call
1478 * @return the number of references. The interesting values are 0, 1, "many" (represented
1479 * by any value &gt;1), and the special value FILTERED, which indicates that there are
1480 * multiple references and one or more of them is of the form {@code $x[....]} indicating that an
1481 * index might be useful.
1482 */
1483
1484 public static int getReferenceCount(Expression exp, Binding binding, boolean inLoop) {
1485 int rcount = 0;
1486 if (exp instanceof VariableReference && ((VariableReference) exp).getBinding() == binding) {
1487 if (((VariableReference) exp).isFiltered()) {
1488 return FilterExpression.FILTERED;
1489 } else {
1490 rcount += inLoop ? 10 : 1;
1491 }
1492 } else if ((exp.getDependencies() & StaticProperty.DEPENDS_ON_LOCAL_VARIABLES) == 0) {
1493 return 0;
1494 } else {
1495 for (Operand info : exp.operands()) {
1496 Expression child = info.getChildExpression();
1497 boolean childLoop = inLoop || info.isEvaluatedRepeatedly();
1498 rcount += getReferenceCount(child, binding, childLoop);
1499 if (rcount >= FilterExpression.FILTERED) {
1500 break;
1501 }
1502 }
1503 }
1504 return rcount;
1505 }
1506
1507 /**
1508 * Get the size of an expression tree (the number of subexpressions it contains)
1509 *
1510 * @param exp the expression whose size is required
1511 * @return the size of the expression tree, as the number of nodes
1512 */
1513
1514 public static int expressionSize(Expression exp) {
1515 exp = exp.getInterpretedExpression();
1516 int total = 1;
1517 for (Operand o : exp.operands()) {
1518 total += expressionSize(o.getChildExpression());
1519 }
1520 return total;
1521 }
1522
1523
1524 /**
1525 * Rebind all variable references to a binding
1526 *
1527 * @param exp the expression whose contained variable references are to be rebound
1528 * @param oldBinding the old binding for the variable references
1529 * @param newBinding the new binding to which the variables should be rebound
1530 */
1531
1532 public static void rebindVariableReferences(
1533 Expression exp, Binding oldBinding, Binding newBinding) {
1534 if (exp instanceof VariableReference) {
1535 if (((VariableReference) exp).getBinding() == oldBinding) {
1536 ((VariableReference) exp).fixup(newBinding);
1537 }
1538 } else {
1539 for (Operand o : exp.operands()) {
1540 rebindVariableReferences(o.getChildExpression(), oldBinding, newBinding);
1541 }
1542 }
1543 }
1544
1545 /**
1546 * Make a mapping expression. The resulting expression will include logic to check that the first operand
1547 * returns nodes, and that the expression as a whole is homogeneous, unless the caller requests otherwise.
1548 *
1549 * @param start the start expression (the first operand of "/")
1550 * @param step the step expression (the second operand of "/")
1551 * @return the resulting expression.
1552 */
1553
1554 /*@NotNull*/
1555 public static Expression makePathExpression(Expression start, Expression step) {
1556
1557 // the expression /.. is sometimes used to represent the empty node-set. Applying this simplification
1558 // now avoids generating warnings for this case.
1559 if (start instanceof RootExpression &&
1560 step instanceof AxisExpression && ((AxisExpression) step).getAxis() == AxisInfo.PARENT) {
1561 return Literal.makeEmptySequence();
1562 }
1563
1564 SlashExpression expr = new SlashExpression(start, step);
1565
1566 // If start is a path expression such as a, and step is b/c, then
1567 // instead of a/(b/c) we construct (a/b)/c. This is because it often avoids
1568 // a sort.
1569
1570 // The "/" operator in XPath 2.0 is not always left-associative. Problems
1571 // can occur if position() and last() are used on the rhs, or if node-constructors
1572 // appear, e.g. //b/../<d/>. So we only do this rewrite if the step is a path
1573 // expression in which both operands are axis expressions optionally with predicates
1574
1575 if (step instanceof SlashExpression) {
1576 SlashExpression stepPath = (SlashExpression) step;
1577 if (isFilteredAxisPath(stepPath.getSelectExpression()) && isFilteredAxisPath(stepPath.getActionExpression())) {
1578 expr.setStart(ExpressionTool.makePathExpression(start, stepPath.getSelectExpression()));
1579 expr.setStep(stepPath.getActionExpression());
1580 }
1581 }
1582
1583 return expr;
1584 }
1585
1586
1587 /**
1588 * Find the operand corresponding to a particular child expression
1589 *
1590 * @param parentExpression the parent expression
1591 * @param childExpression the child expression
1592 * @return the relevant operand, or null if not found
1593 */
1594
1595 public static Operand findOperand(Expression parentExpression, Expression childExpression) {
1596 for (Operand o : parentExpression.operands()) {
1597 if (o.getChildExpression() == childExpression) {
1598 return o;
1599 }
1600 }
1601 return null;
1602 }
1603
1604 /**
1605 * Determine whether an expression is an axis step with optional filter predicates.
1606 *
1607 * @param exp the expression to be examined
1608 * @return true if the supplied expression is an AxisExpression, or an AxisExpression wrapped by one
1609 * or more filter expressions
1610 */
1611
1612 private static boolean isFilteredAxisPath(Expression exp) {
1613 return unfilteredExpression(exp, true) instanceof AxisExpression;
1614 }
1615
1616 /**
1617 * Get the expression that remains after removing any filter predicates
1618 *
1619 * @param exp the expression to be examined
1620 * @param allowPositional true if positional predicates are allowed
1621 * @return the expression underlying exp after removing any predicates
1622 */
1623
1624 public static Expression unfilteredExpression(Expression exp, boolean allowPositional) {
1625 if (exp instanceof FilterExpression && (allowPositional || !((FilterExpression) exp).isFilterIsPositional())) {
1626 return unfilteredExpression(((FilterExpression) exp).getSelectExpression(), allowPositional);
1627 } else if (exp instanceof SingleItemFilter && allowPositional) {
1628 return unfilteredExpression(((SingleItemFilter) exp).getBaseExpression(), allowPositional);
1629 } else {
1630 return exp;
1631 }
1632 }
1633
1634 /**
1635 * Try to factor out dependencies on the context item, by rewriting an expression f(.) as
1636 * let $dot := . return f($dot). This is not always possible, for example where f() is an extension
1637 * function call that uses XPathContext as an implicit argument. However, doing this increases the
1638 * chances of distributing a "where" condition in a FLWOR expression to the individual input sequences
1639 * selected by the "for" clauses.
1640 *
1641 * @param exp the expression from which references to "." should be factored out if possible
1642 * @param contextItemType the static type of the context item
1643 * @return either the expression, after binding "." to a local variable and replacing all references to it;
1644 * or null, if no changes were made.
1645 */
1646
1647 public static Expression tryToFactorOutDot(Expression exp, ItemType contextItemType) {
1648 if (exp instanceof ContextItemExpression) {
1649 return null;
1650 } else if (exp instanceof LetExpression && ((LetExpression) exp).getSequence() instanceof ContextItemExpression) {
1651 Expression action = ((LetExpression) exp).getAction();
1652 boolean changed = factorOutDot(action, (LetExpression) exp);
1653 if (changed) {
1654 exp.resetLocalStaticProperties();
1655 }
1656 return exp;
1657 } else if ((exp.getDependencies() &
1658 (StaticProperty.DEPENDS_ON_CONTEXT_ITEM | StaticProperty.DEPENDS_ON_CONTEXT_DOCUMENT)) != 0) {
1659 LetExpression let = new LetExpression();
1660 let.setVariableQName(
1661 new StructuredQName("saxon", NamespaceConstant.SAXON, "dot" + exp.hashCode()));
1662 let.setRequiredType(SequenceType.makeSequenceType(contextItemType, StaticProperty.EXACTLY_ONE));
1663 let.setSequence(new ContextItemExpression());
1664 let.setAction(exp);
1665 boolean changed = factorOutDot(exp, let);
1666 if (changed) {
1667 return let;
1668 } else {
1669 return exp;
1670 }
1671 } else {
1672 return null;
1673 }
1674 }
1675
1676 /**
1677 * Replace references to the context item with references to a variable
1678 *
1679 * @param exp the expression in which the replacement is to take place
1680 * @param variable the declaration of the variable
1681 * @return true if replacement has taken place (at any level)
1682 */
1683
1684 public static boolean factorOutDot(Expression exp, Binding variable) {
1685 boolean changed = false;
1686 if ((exp.getDependencies() &
1687 (StaticProperty.DEPENDS_ON_CONTEXT_ITEM | StaticProperty.DEPENDS_ON_CONTEXT_DOCUMENT)) != 0) {
1688 for (Operand info : exp.operands()) {
1689 if (info.hasSameFocus()) {
1690 Expression child = info.getChildExpression();
1691 if (child instanceof ContextItemExpression) {
1692 VariableReference ref = variable.isGlobal() ?
1693 new GlobalVariableReference((GlobalVariable) variable) :
1694 new LocalVariableReference((LocalBinding) variable);
1695 copyLocationInfo(child, ref);
1696 info.setChildExpression(ref);
1697 changed = true;
1698 } else if (child instanceof AxisExpression ||
1699 child instanceof RootExpression) {
1700 VariableReference ref = variable.isGlobal() ?
1701 new GlobalVariableReference((GlobalVariable) variable) :
1702 new LocalVariableReference((LocalBinding) variable);
1703 copyLocationInfo(child, ref);
1704 Expression path = ExpressionTool.makePathExpression(ref, child);
1705 info.setChildExpression(path);
1706 changed = true;
1707 } else {
1708 changed |= factorOutDot(child, variable);
1709 }
1710 }
1711 }
1712 }
1713 if (changed) {
1714 exp.resetLocalStaticProperties();
1715 }
1716 return changed;
1717 }
1718
1719 /**
1720 * Inline variable references.
1721 *
1722 * @param expr the expression containing the variable references to be inlined
1723 * @param binding the variable binding to be inlined
1724 * @param replacement the expression to be used as a replacement for the variable reference
1725 * @return true if any replacement was carried out within the subtree of this expression
1726 */
1727
1728 public static boolean inlineVariableReferences(Expression expr, Binding binding, Expression replacement) {
1729 return inlineVariableReferencesInternal(expr, binding, replacement);
1730 }
1731
1732 public static boolean inlineVariableReferencesInternal(Expression expr, Binding binding, Expression replacement) {
1733 if (expr instanceof TryCatch && !(replacement instanceof Literal)) {
1734 // Don't inline variable references within a try/catch, as this will lead to errors in the
1735 // variable's initializer being incorrectly caught by the catch clause. See XSLT3 test try-029.
1736 return false;
1737 } else {
1738 boolean found = false;
1739 for (Operand o : expr.operands()) {
1740 Expression child = o.getChildExpression();
1741 if (child instanceof VariableReference &&
1742 ((VariableReference) child).getBinding() == binding) {
1743 Expression copy;
1744 try {
1745 copy = replacement.copy(new RebindingMap());
1746 ExpressionTool.copyLocationInfo(child, copy);
1747 } catch (UnsupportedOperationException err) {
1748 // If we can't make a copy, return the original. This is safer than it seems,
1749 // because on the paths where this happens, we are merely moving the expression from
1750 // one place to another, not replicating it
1751 copy = replacement;
1752 }
1753 o.setChildExpression(copy);
1754 found = true;
1755 } else {
1756 found |= inlineVariableReferencesInternal(child, binding, replacement);
1757 }
1758 }
1759 if (found) {
1760 expr.resetLocalStaticProperties();
1761 }
1762 return found;
1763 }
1764 }
1765
1766 /**
1767 * Replace trivial calls to current() by a context item expression ({@code .}).
1768 *
1769 * @param expr the expression potentially containing the calls to be replaced
1770 * @return true if any replacement was carried out within the subtree of this expression
1771 */
1772
1773 public static boolean replaceTrivialCallsToCurrent(Expression expr) {
1774 boolean found = false;
1775 for (Operand o : expr.operands()) {
1776 if (o.hasSameFocus()) {
1777 Expression child = o.getChildExpression();
1778 if (child.isCallOn(Current.class)) {
1779 CurrentItemExpression var = new CurrentItemExpression();
1780 ExpressionTool.copyLocationInfo(child, var);
1781 o.setChildExpression(var);
1782 found = true;
1783 } else {
1784 found = replaceTrivialCallsToCurrent(child);
1785 }
1786 }
1787 }
1788 if (found) {
1789 expr.resetLocalStaticProperties();
1790 }
1791 return found;
1792 }
1793
1794 /**
1795 * Replace calls to current() by a variable reference.
1796 *
1797 * @param expr the expression potentially containing the calls to be replaced
1798 * @param binding the variable binding to be referenced
1799 * @return true if any replacement was carried out within the subtree of this expression
1800 */
1801
1802 public static boolean replaceCallsToCurrent(Expression expr, LocalBinding binding) {
1803 boolean found = false;
1804 for (Operand o : expr.operands()) {
1805 Expression child = o.getChildExpression();
1806 if (child.isCallOn(Current.class)) {
1807 LocalVariableReference var = new LocalVariableReference(binding);
1808 ExpressionTool.copyLocationInfo(child, var);
1809 o.setChildExpression(var);
1810 binding.addReference(var, true);
1811 found = true;
1812 } else {
1813 found = replaceCallsToCurrent(child, binding);
1814 }
1815 }
1816 if (found) {
1817 expr.resetLocalStaticProperties();
1818 }
1819 return found;
1820 }
1821
1822
1823 /**
1824 * Determine whether the expression is either an updating expression, or an expression that is permitted
1825 * in a context where updating expressions are allowed
1826 *
1827 * @param exp the expression under test
1828 * @return true if the expression is neither an updating expression, nor an empty sequence,
1829 * nor a call on error()
1830 */
1831
1832 public static boolean isNotAllowedInUpdatingContext(Expression exp) {
1833 return !exp.isUpdatingExpression() && !exp.isVacuousExpression();
1834 }
1835
1836
1837 public static String getCurrentDirectory() {
1838 String dir;
1839 try {
1840 dir = System.getProperty("user.dir");
1841 } catch (Exception geterr) {
1842 // this doesn't work when running an applet
1843 return null;
1844 }
1845 if (!dir.endsWith("/")) {
1846 dir = dir + '/';
1847 }
1848
1849 URI currentDirectoryURL = new File(dir).toURI();
1850 return currentDirectoryURL.toString();
1851 }
1852
1853 /**
1854 * Determine the base URI of an expression, so that it can be saved on the expression tree for use
1855 * when the expression is evaluated
1856 *
1857 * @param env the static context
1858 * @param locator location of the expression for error messages
1859 * @param fail if true, the method throws an exception when there is no absolute base URI; otherwise, the
1860 * method returns null
1861 * @return the absolute base URI of the expression
1862 * @throws net.sf.saxon.trans.XPathException if an error occurs
1863 */
1864
1865 public static URI getBaseURI(StaticContext env, SourceLocator locator, boolean fail) throws XPathException {
1866 URI expressionBaseURI = null;
1867 String base = null;
1868 try {
1869 base = env.getStaticBaseURI();
1870 if (base == null) {
1871 base = getCurrentDirectory();
1872 }
1873 if (base != null) {
1874 expressionBaseURI = new URI(base);
1875 }
1876 } catch (URISyntaxException e) {
1877 // perhaps escaping special characters will fix the problem
1878
1879 String esc = IriToUri.iriToUri(base).toString();
1880 try {
1881 expressionBaseURI = new URI(esc);
1882 } catch (URISyntaxException e2) {
1883 // don't fail unless the base URI is actually needed (it usually isn't)
1884 expressionBaseURI = null;
1885 }
1886
1887 if (expressionBaseURI == null && fail) {
1888 XPathException err = new XPathException("The base URI " + Err.wrap(env.getStaticBaseURI(), Err.URI) +
1889 " is not a valid URI");
1890 err.setLocator(locator);
1891 throw err;
1892 }
1893 }
1894 return expressionBaseURI;
1895 }
1896
1897 /**
1898 * Display an expression adding parentheses if it is possible they are necessary
1899 * because the expression has sub-expressions
1900 *
1901 * @param exp the expression to be displayed
1902 * @return a representation of the expression in parentheses
1903 */
1904
1905 public static String parenthesize(Expression exp) {
1906 if (exp.operands().iterator().hasNext()) {
1907 return "(" + exp.toString() + ")";
1908 } else {
1909 return exp.toString();
1910 }
1911 }
1912
1913 public static String parenthesizeShort(Expression exp) {
1914 if (hasTwoOrMoreOperands(exp)) {
1915 return "(" + exp.toShortString() + ")";
1916 } else {
1917 return exp.toShortString();
1918 }
1919 }
1920
1921 private static boolean hasTwoOrMoreOperands(Expression exp) {
1922 Iterator ops = exp.operands().iterator();
1923 if (!ops.hasNext()) {
1924 return false;
1925 }
1926 ops.next();
1927 return ops.hasNext();
1928 }
1929
1930
1931 public static void validateTree(Expression exp) {
1932 try {
1933 for (Operand o : exp.checkedOperands()) {
1934 validateTree(o.getChildExpression());
1935 }
1936 } catch (IllegalStateException e) {
1937 e.printStackTrace();
1938 }
1939 }
1940
1941 /**
1942 * Ask whether a supplied expression is a nested node constructor.
1943 * That is, return true if the child expression creates nodes that will only be
1944 * used as children of some parent node (meaning that they never need to be copied).
1945 * @param child child expression to be tested
1946 * @return true if the node constructed by the child expression does not need to be copied.
1947 */
1948
1949 public static boolean isLocalConstructor(Expression child) {
1950 if (!(child instanceof ParentNodeConstructor || child instanceof SimpleNodeConstructor)) {
1951 return false;
1952 }
1953 Expression parent = child.getParentExpression();
1954 while (parent != null) {
1955 if (parent instanceof ParentNodeConstructor) {
1956 return true;
1957 }
1958 Operand o = findOperand(parent, child);
1959 if (o.getUsage() != OperandUsage.TRANSMISSION) {
1960 return false;
1961 }
1962 child = parent;
1963 parent = parent.getParentExpression();
1964 }
1965 return false;
1966 }
1967 }
1968