//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2018 Saxonica Limited. // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// package net.sf.saxon.expr; import net.sf.saxon.Configuration; import net.sf.saxon.expr.flwor.OuterForExpression; import net.sf.saxon.expr.instruct.Choose; import net.sf.saxon.expr.parser.*; import net.sf.saxon.lib.Feature; import net.sf.saxon.om.Item; import net.sf.saxon.om.SequenceIterator; import net.sf.saxon.om.StructuredQName; import net.sf.saxon.trace.ExpressionPresenter; import net.sf.saxon.trace.LocationKind; import net.sf.saxon.trans.XPathException; import net.sf.saxon.type.ItemType; import net.sf.saxon.type.SchemaType; import net.sf.saxon.type.TypeHierarchy; import net.sf.saxon.type.UType; import net.sf.saxon.value.Cardinality; import net.sf.saxon.value.IntegerValue; import net.sf.saxon.value.SequenceType; import java.util.ArrayList; import java.util.List; /** * A ForExpression maps an expression over a sequence. * We use a ForExpression in preference to a FLWORExpression to handle simple cases * (roughly, the XPath subset). In 9.6, we no longer convert a FLWORExpression to a ForExpression * if there is a position variable, which simplifies the cases this class has to handle. */ public class ForExpression extends Assignation { int actionCardinality = StaticProperty.ALLOWS_MANY; /** * Create a "for" expression (for $x at $p in SEQUENCE return ACTION) */ public ForExpression() { } /** * Get a name identifying the kind of expression, in terms meaningful to a user. * * @return a name identifying the kind of expression, in terms meaningful to a user. * The name will always be in the form of a lexical XML QName, and should match the name used * in explain() output displaying the expression. */ public String getExpressionName() { return "for"; } /** * Type-check the expression */ /*@NotNull*/ public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException { // The order of events is critical here. First we ensure that the type of the // sequence expression is established. This is used to establish the type of the variable, // which in turn is required when type-checking the action part. getSequenceOp().typeCheck(visitor, contextInfo); if (Literal.isEmptySequence(getSequence()) && !(this instanceof OuterForExpression)) { return getSequence(); } if (requiredType != null) { // if declaration is null, we've already done the type checking in a previous pass final TypeHierarchy th = visitor.getConfiguration().getTypeHierarchy(); SequenceType decl = requiredType; SequenceType sequenceType = SequenceType.makeSequenceType( decl.getPrimaryType(), StaticProperty.ALLOWS_ZERO_OR_MORE); RoleDiagnostic role = new RoleDiagnostic(RoleDiagnostic.VARIABLE, variableName.getDisplayName(), 0); setSequence(TypeChecker.strictTypeCheck( getSequence(), sequenceType, role, visitor.getStaticContext())); ItemType actualItemType = getSequence().getItemType(); refineTypeInformation(actualItemType, getRangeVariableCardinality(), null, getSequence().getSpecialProperties(), this); } if (Literal.isEmptySequence(getAction())) { return getAction(); } getActionOp().typeCheck(visitor, contextInfo); actionCardinality = getAction().getCardinality(); return this; } /** * Get the cardinality of the range variable * * @return the cardinality of the range variable (StaticProperty.EXACTLY_ONE). Can be overridden * in a subclass */ protected int getRangeVariableCardinality() { return StaticProperty.EXACTLY_ONE; } /** * Optimize the expression */ /*@NotNull*/ public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType) throws XPathException { Configuration config = visitor.getConfiguration(); Optimizer opt = visitor.obtainOptimizer(); boolean debug = config.getBooleanProperty(Feature.TRACE_OPTIMIZER_DECISIONS); // Try to promote any WHERE clause appearing immediately within the FOR expression if (Choose.isSingleBranchChoice(getAction())) { getActionOp().optimize(visitor, contextItemType); } Expression p = promoteWhereClause(); if (p != null) { if (debug) { opt.trace("Promoted where clause in for $" + getVariableName(), p); } return p.optimize(visitor, contextItemType); } Expression seq0 = getSequence(); getSequenceOp().optimize(visitor, contextItemType); if (seq0 != getSequence()) { // if it changed, re-optimize return optimize(visitor, contextItemType); } if (Literal.isEmptySequence(getSequence()) && !(this instanceof OuterForExpression)) { return getSequence(); } Expression act0 = getAction(); getActionOp().optimize(visitor, contextItemType); if (act0 != getAction()) { // it's now worth re-attempting the "where" clause optimizations return optimize(visitor, contextItemType); } if (Literal.isEmptySequence(getAction())) { return getAction(); } // Simplify an expression of the form "for $b in a/b/c return $b/d". // (XQuery users seem to write these a lot!) if (getSequence() instanceof SlashExpression && getAction() instanceof SlashExpression) { SlashExpression path2 = (SlashExpression) getAction(); Expression start2 = path2.getSelectExpression(); Expression step2 = path2.getActionExpression(); if (start2 instanceof VariableReference && ((VariableReference) start2).getBinding() == this && ExpressionTool.getReferenceCount(getAction(), this, false) == 1 && ((step2.getDependencies() & (StaticProperty.DEPENDS_ON_POSITION | StaticProperty.DEPENDS_ON_LAST)) == 0)) { Expression newPath = new SlashExpression(getSequence(), path2.getActionExpression()); ExpressionTool.copyLocationInfo(this, newPath); newPath = newPath.simplify().typeCheck(visitor, contextItemType); if (newPath instanceof SlashExpression) { // if not, it has been wrapped in a DocumentSorter or Reverser, which makes it ineligible. // see test qxmp299, where this condition isn't satisfied if (debug) { opt.trace("Collapsed return clause of for $" + getVariableName() + " into path expression", newPath); } return newPath.optimize(visitor, contextItemType); } } } // Simplify an expression of the form "for $x in EXPR return $x". These sometimes // arise as a result of previous optimization steps. if (getAction() instanceof VariableReference && ((VariableReference) getAction()).getBinding() == this) { if (debug) { opt.trace("Collapsed redundant for expression $" + getVariableName(), getSequence()); } return getSequence(); } // If the cardinality of the sequence is exactly one, rewrite as a LET expression if (getSequence().getCardinality() == StaticProperty.EXACTLY_ONE) { LetExpression let = new LetExpression(); let.setVariableQName(variableName); let.setRequiredType(SequenceType.makeSequenceType( getSequence().getItemType(), StaticProperty.EXACTLY_ONE)); let.setSequence(getSequence()); let.setAction(getAction()); let.setSlotNumber(slotNumber); let.setRetainedStaticContextLocally(getRetainedStaticContext()); ExpressionTool.rebindVariableReferences(getAction(), this, let); return let.typeCheck(visitor, contextItemType).optimize(visitor, contextItemType); } return this; } /** * Replace this expression by a simpler expression that delivers the results without regard * to order. * * @param retainAllNodes set to true if the result must contain exactly the same nodes as the * original; set to false if the result can eliminate (or introduce) duplicates. * @param forStreaming set to true if optimizing for streaming */ @Override public Expression unordered(boolean retainAllNodes, boolean forStreaming) throws XPathException { setSequence(getSequence().unordered(retainAllNodes, forStreaming)); setAction(getAction().unordered(retainAllNodes, forStreaming)); return this; } /** * For an expression that returns an integer or a sequence of integers, get * a lower and upper bound on the values of the integers that may be returned, from * static analysis. The default implementation returns null, meaning "unknown" or * "not applicable". Other implementations return an array of two IntegerValue objects, * representing the lower and upper bounds respectively. The values * UNBOUNDED_LOWER and UNBOUNDED_UPPER are used by convention to indicate that * the value may be arbitrarily large. The values MAX_STRING_LENGTH and MAX_SEQUENCE_LENGTH * are used to indicate values limited by the size of a string or the size of a sequence. * * @return the lower and upper bounds of integer values in the result, or null to indicate * unknown or not applicable. */ /*@Nullable*/ @Override public IntegerValue[] getIntegerBounds() { return getAction().getIntegerBounds(); } /** * Promote a WHERE clause whose condition doesn't depend on the variable being bound. * This rewrites an expression of the form *
let $i := SEQ return if (C) then R else ()
*to the form:
*if (C) then (let $i := SEQ return R) else ()
* * @return an expression in which terms from the WHERE clause that can be extracted have been extracted */ /*@Nullable*/ protected Expression promoteWhereClause() { if (Choose.isSingleBranchChoice(getAction())) { Expression condition = ((Choose) getAction()).getCondition(0); Binding[] bindingList = new Binding[]{this}; List