| 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.value; |
| 9 | |
| 10 | import net.sf.saxon.expr.*; |
| 11 | import net.sf.saxon.expr.instruct.SlotManager; |
| 12 | import net.sf.saxon.om.*; |
| 13 | import net.sf.saxon.trans.XPathException; |
| 14 | import net.sf.saxon.tree.iter.ManualIterator; |
| 15 | |
| 16 | /** |
| 17 | * A Closure represents a value that has not yet been evaluated: the value is represented |
| 18 | * by an expression, together with saved values of all the context variables that the |
| 19 | * expression depends on. |
| 20 | * <p>This Closure is designed for use when the value is only read once. If the value |
| 21 | * is read more than once, a new iterator over the underlying expression is obtained |
| 22 | * each time: this may (for example in the case of a filter expression) involve |
| 23 | * significant re-calculation.</p> |
| 24 | * <p>The expression may depend on local variables and on the context item; these values |
| 25 | * are held in the saved XPathContext object that is kept as part of the Closure, and they |
| 26 | * will always be read from that object. The expression may also depend on global variables; |
| 27 | * these are unchanging, so they can be read from the Bindery in the normal way. Expressions |
| 28 | * that depend on other contextual information, for example the values of position(), last(), |
| 29 | * current(), current-group(), should not be evaluated using this mechanism: they should |
| 30 | * always be evaluated eagerly. This means that the Closure does not need to keep a copy |
| 31 | * of these context variables.</p> |
| 32 | */ |
| 33 | |
| 34 | public class Closure implements Sequence<Item<?>>, ContextOriginator { |
| 35 | |
| 36 | protected Expression expression; |
| 37 | /*@Nullable*/ protected XPathContextMajor savedXPathContext; |
| 38 | protected int depth = 0; |
| 39 | |
| 40 | // The base iterator is used to copy items on demand from the underlying value |
| 41 | // to the reservoir. It only ever has one instance (for each Closure) and each |
| 42 | // item is read only once. |
| 43 | |
| 44 | protected SequenceIterator<?> inputIterator; |
| 45 | |
| 46 | /** |
| 47 | * Constructor should not be called directly, instances should be made using the make() method. |
| 48 | */ |
| 49 | public Closure() { |
| 50 | } |
| 51 | |
| 52 | /** |
| 53 | * Construct a Closure by supplying the expression and the set of context variables. |
| 54 | * |
| 55 | * @param expression the expression to be lazily evaluated |
| 56 | * @param context the dynamic context of the expression including for example the variables |
| 57 | * on which it depends |
| 58 | * @param ref the number of references to the value being lazily evaluated; this affects |
| 59 | * the kind of Closure that is created |
| 60 | * @return the Closure, a virtual value that can later be materialized when its content is required |
| 61 | * @throws net.sf.saxon.trans.XPathException |
| 62 | * if a dynamic error occurs |
| 63 | */ |
| 64 | |
| 65 | /*@NotNull*/ |
| 66 | public static Sequence<?> make( |
| 67 | Expression expression, XPathContext context, int ref) throws XPathException { |
| 68 | return context.getConfiguration().makeClosure(expression, ref, context); |
| 69 | } |
| 70 | |
| 71 | public void saveContext(/*@NotNull*/ Expression expression, /*@NotNull*/ XPathContext context) throws XPathException { |
| 72 | // Make a copy of all local variables. If the value of any local variable is a closure |
| 73 | // whose depth exceeds a certain threshold, we evaluate the closure eagerly to avoid |
| 74 | // creating deeply nested lists of Closures, which consume memory unnecessarily |
| 75 | |
| 76 | // We only copy the local variables if the expression has dependencies on local variables. |
| 77 | // What's more, we only copy those variables that the expression actually depends on. |
| 78 | |
| 79 | if ((expression.getDependencies() & StaticProperty.DEPENDS_ON_LOCAL_VARIABLES) != 0) { |
| 80 | StackFrame localStackFrame = context.getStackFrame(); |
| 81 | Sequence<?>[] local = localStackFrame.getStackFrameValues(); |
| 82 | int[] slotsUsed = expression.getSlotsUsed(); // computed on first call |
| 83 | if (local != null) { |
| 84 | final SlotManager stackFrameMap = localStackFrame.getStackFrameMap(); |
| 85 | final Sequence[] savedStackFrame = |
| 86 | new Sequence[stackFrameMap.getNumberOfVariables()]; |
| 87 | for (int i : slotsUsed) { |
| 88 | assert i < local.length; |
| 89 | if (local[i] instanceof Closure) { |
| 90 | int cdepth = ((Closure) local[i]).depth; |
| 91 | if (cdepth >= 10) { |
| 92 | local[i] = local[i].iterate().materialize(); |
| 93 | } else if (cdepth + 1 > depth) { |
| 94 | depth = cdepth + 1; |
| 95 | } |
| 96 | } |
| 97 | savedStackFrame[i] = local[i]; |
| 98 | } |
| 99 | |
| 100 | savedXPathContext.setStackFrame(stackFrameMap, savedStackFrame); |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | // Make a copy of the context item |
| 105 | FocusIterator currentIterator = context.getCurrentIterator(); |
| 106 | if (currentIterator != null) { |
| 107 | Item<?> contextItem = currentIterator.current(); |
| 108 | ManualIterator<?> single = new ManualIterator<>(contextItem); |
| 109 | savedXPathContext.setCurrentIterator(single); |
| 110 | // we don't save position() and last() because we have no way |
| 111 | // of restoring them. So the caller must ensure that a Closure is not |
| 112 | // created if the expression depends on position() or last() |
| 113 | } |
| 114 | |
| 115 | savedXPathContext.setReceiver(null); |
| 116 | } |
| 117 | |
| 118 | /** |
| 119 | * Get the first item in the sequence. |
| 120 | * |
| 121 | * @return the first item in the sequence if there is one, or null if the sequence |
| 122 | * is empty |
| 123 | * @throws net.sf.saxon.trans.XPathException |
| 124 | * in the situation where the sequence is evaluated lazily, and |
| 125 | * evaluation of the first item causes a dynamic error. |
| 126 | */ |
| 127 | public Item<?> head() throws XPathException { |
| 128 | return iterate().next(); |
| 129 | } |
| 130 | |
| 131 | public Expression getExpression() { |
| 132 | return expression; |
| 133 | } |
| 134 | |
| 135 | /*@Nullable*/ |
| 136 | public XPathContextMajor getSavedXPathContext() { |
| 137 | return savedXPathContext; |
| 138 | } |
| 139 | |
| 140 | public void setExpression(Expression expression) { |
| 141 | this.expression = expression; |
| 142 | } |
| 143 | |
| 144 | public void setSavedXPathContext(XPathContextMajor savedXPathContext) { |
| 145 | this.savedXPathContext = savedXPathContext; |
| 146 | } |
| 147 | |
| 148 | /** |
| 149 | * Evaluate the expression in a given context to return an iterator over a sequence |
| 150 | */ |
| 151 | |
| 152 | /*@NotNull*/ |
| 153 | public SequenceIterator<Item<?>> iterate() throws XPathException { |
| 154 | |
| 155 | if (inputIterator == null) { |
| 156 | inputIterator = expression.iterate(savedXPathContext); |
| 157 | return (SequenceIterator<Item<?>>)inputIterator; |
| 158 | } else { |
| 159 | // In an ideal world this shouldn't happen: if the value is needed more than once, we should |
| 160 | // have chosen a MemoClosure. |
| 161 | |
| 162 | // Changed Feb 2015 to throw an exception. Processing the expression more than once is not only |
| 163 | // inefficient, it is wrong in the case where node-identity affects the outcome. See for example |
| 164 | // test case fn-fold-left-018 |
| 165 | |
| 166 | //return inputIterator.getAnother(); |
| 167 | throw new IllegalStateException("A Closure can only be read once"); |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | /** |
| 172 | * Reduce a value to its simplest form. If the value is a closure or some other form of deferred value |
| 173 | * such as a FunctionCallPackage, then it is reduced to a SequenceExtent. If it is a SequenceExtent containing |
| 174 | * a single item, then it is reduced to that item. One consequence that is exploited by class FilterExpression |
| 175 | * is that if the value is a singleton numeric value, then the result will be an instance of NumericValue |
| 176 | * @return the simplified value |
| 177 | * @throws XPathException if an error occurs doing the lazy evaluation |
| 178 | */ |
| 179 | |
| 180 | public GroundedValue<?> reduce() throws XPathException { |
| 181 | return iterate().materialize(); |
| 182 | } |
| 183 | |
| 184 | @Override |
| 185 | public Sequence<Item<?>> makeRepeatable() throws XPathException { |
| 186 | return materialize(); |
| 187 | } |
| 188 | } |
| 189 |