Package net.sf.saxon.expr

## Class ForExpression

- java.lang.Object
- - net.sf.saxon.expr.Expression
  - - net.sf.saxon.expr.Assignation
    - - net.sf.saxon.expr.ForExpression

- All Implemented Interfaces:
    `Binding`, `ExportAgent`, `LocalBinding`, `Locatable`, `IdentityComparable`, `Traceable`
  Direct Known Subclasses:
    `OuterForExpression`

      public class ForExpression
      extends Assignation

  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.

- - ### Nested Class Summary

    Nested Classes
    Modifier and Type | Class | Description
    --- | --- | ---
    `static class` | `ForExpression.MappingAction` | The MappingAction represents the action to be taken for each item in the source sequence.

  - ### Field Summary

    - ### Fields inherited from class net.sf.saxon.expr.Assignation

      `hasLoopingReference, isIndexedVariable, references, requiredType, slotNumber, variableName`

    - ### Fields inherited from class net.sf.saxon.expr.Expression

      `EFFECTIVE_BOOLEAN_VALUE, EVALUATE_METHOD, ITEM_FEED_METHOD, ITERATE_METHOD, MAX_COST, MAX_SEQUENCE_LENGTH, MAX_STRING_LENGTH, PROCESS_METHOD, staticProperties, UNBOUNDED_LOWER, UNBOUNDED_UPPER, UPDATE_METHOD, WATCH_METHOD`

  - ### Constructor Summary

    Constructors
    Constructor | Description
    --- | ---
    `ForExpression()` | Create a "for" expression (for $x at $p in SEQUENCE return ACTION)

  - ### Method Summary

    All Methods Instance Methods Concrete Methods
    Modifier and Type | Method | Description
    --- | --- | ---
    `void` | `checkPermittedContents​(SchemaType parentType, boolean whole)` | Check that any elements and attributes constructed or returned by this expression are acceptable in the content model of a given complex type.
    `int` | `computeCardinality()` | Determine the static cardinality of the expression
    `Expression` | `copy​(RebindingMap rebindings)` | Copy an expression.
    `void` | `evaluatePendingUpdates​(XPathContext context, PendingUpdateList pul)` | Evaluate an updating expression, adding the results to a Pending Update List.
    `protected void` | `explainSpecializedAttributes​(ExpressionPresenter out)` |
    `void` | `export​(ExpressionPresenter out)` | Diagnostic print of expression structure.
    `java.lang.String` | `getExpressionName()` | Get a name identifying the kind of expression, in terms meaningful to a user.
    `int` | `getImplementationMethod()` | An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process().
    `IntegerValue[]` | `getIntegerBounds()` | 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.
    `ItemType` | `getItemType()` | Determine the data type of the items returned by the expression, if possible
    `protected int` | `getRangeVariableCardinality()` | Get the cardinality of the range variable
    `UType` | `getStaticUType​(UType contextItemType)` | Get the static type of the expression as a UType, following precisely the type inference rules defined in the XSLT 3.0 specification.
    `java.lang.String` | `getStreamerName()` | Get the (partial) name of a class that supports streaming of this kind of expression
    `boolean` | `isVacuousExpression()` | Determine whether this is a vacuous expression as defined in the XQuery update specification
    `SequenceIterator` | `iterate​(XPathContext context)` | Iterate over the sequence of values
    `int` | `markTailFunctionCalls​(StructuredQName qName, int arity)` | Mark tail function calls: only possible if the for expression iterates zero or one times.
    `Expression` | `optimize​(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType)` | Optimize the expression
    `void` | `process​(Outputter output, XPathContext context)` | Process this expression as an instruction, writing results to the current outputter
    `java.lang.String` | `toShortString()` | Produce a short string identifying the expression for use in error messages
    `java.lang.String` | `toString()` | The toString() method for an expression attempts to give a representation of the expression in an XPath-like form, but there is no guarantee that the syntax will actually be true XPath.
    `Expression` | `typeCheck​(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo)` | Type-check the expression
    `Expression` | `unordered​(boolean retainAllNodes, boolean forStreaming)` | Replace this expression by a simpler expression that delivers the results without regard to order.

    - ### Methods inherited from class net.sf.saxon.expr.Assignation

      `addReference, addToPathMap, checkForUpdatingSubexpressions, computeDependencies, evaluateVariable, getAction, getActionOp, getCost, getIntegerBoundsForVariable, getLocalSlotNumber, getNominalReferenceCount, getObjectName, getRequiredSlots, getRequiredType, getSequence, getSequenceOp, getVariableEQName, getVariableName, getVariableQName, hasVariableBinding, isAssignable, isGlobal, isIndexedVariable, isUpdatingExpression, operands, rebuildReferenceList, refineTypeInformation, removeDeadReferences, replaceVariable, setAction, setIndexedVariable, setRequiredType, setSequence, setSlotNumber, setVariableQName, suppressValidation, verifyReferences`

    - ### Methods inherited from class net.sf.saxon.expr.Expression

      `adoptChildExpression, allowExtractingCommonSubexpressions, checkedOperands, computeHashCode, computeSpecialProperties, computeStaticProperties, dynamicError, effectiveBooleanValue, equals, evaluateAsString, evaluateItem, explain, getCardinality, getConfiguration, getDependencies, getEvaluationMethod, getExtraProperty, getInterpretedExpression, getIntrinsicDependencies, getLocalRetainedStaticContext, getLocation, getNetCost, getPackageData, getParentExpression, getProperties, getProperty, getRetainedStaticContext, getScopingExpression, getSlotsUsed, getSpecialProperties, getStaticBaseURI, getStaticBaseURIString, getStaticType, getTracingTag, hasCompatibleStaticContext, hashCode, hasSpecialProperty, identityHashCode, implementsStaticTypeCheck, isCallOn, isEqual, isIdentical, isInstruction, isLiftable, isMultiThreaded, isStaticPropertiesKnown, isSubtreeExpression, operandList, operandSparseList, optimizeChildren, prepareForStreaming, resetLocalStaticProperties, restoreParentPointers, setEvaluationMethod, setExtraProperty, setFiltered, setFlattened, setLocation, setParentExpression, setRetainedStaticContext, setRetainedStaticContextLocally, setRetainedStaticContextThoroughly, setStaticProperty, simplify, simplifyChildren, staticTypeCheck, toPattern, typeCheckChildren, typeError, verifyParentPointers`

    - ### Methods inherited from class java.lang.Object

      `clone, finalize, getClass, notify, notifyAll, wait, wait, wait`

    - ### Methods inherited from interface net.sf.saxon.trace.Traceable

      `gatherProperties`

- - ### Constructor Detail

    - #### ForExpression

          public ForExpression()

      Create a "for" expression (for $x at $p in SEQUENCE return ACTION)

  - ### Method Detail

    - #### getExpressionName

          public java.lang.String getExpressionName()

      Get a name identifying the kind of expression, in terms meaningful to a user.
      Overrides:
        `getExpressionName` in class `Expression`
      Returns:
        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.

    - #### typeCheck

          public Expression typeCheck​(ExpressionVisitor visitor,
                                      ContextItemStaticInfo contextInfo)
                               throws XPathException

      Type-check the expression
      Overrides:
        `typeCheck` in class `Expression`
      Parameters:
        `visitor` - an expression visitor
        `contextInfo` - Information available statically about the context item: whether it is (possibly) absent; its static type; its streaming posture.
      Returns:
        the original expression, rewritten to perform necessary run-time type checks, and to perform other type-related optimizations
      Throws:
        `XPathException` - if an error is discovered during this phase (typically a type error)

    - #### getRangeVariableCardinality

          protected int getRangeVariableCardinality()

      Get the cardinality of the range variable
      Returns:
        the cardinality of the range variable (StaticProperty.EXACTLY_ONE). Can be overridden in a subclass

    - #### optimize

          public Expression optimize​(ExpressionVisitor visitor,
                                     ContextItemStaticInfo contextItemType)
                              throws XPathException

      Optimize the expression
      Overrides:
        `optimize` in class `Expression`
      Parameters:
        `visitor` - an expression visitor
        `contextItemType` - the static type of "." at the point where this expression is invoked. The parameter is set to null if it is known statically that the context item will be undefined. If the type of the context item is not known statically, the argument is set to `Type.ITEM_TYPE`
      Returns:
        the original expression, rewritten if appropriate to optimize execution
      Throws:
        `XPathException` - if an error is discovered during this phase (typically a type error)

    - #### unordered

          public Expression unordered​(boolean retainAllNodes,
                                      boolean forStreaming)
                               throws XPathException

      Replace this expression by a simpler expression that delivers the results without regard to order.
      Overrides:
        `unordered` in class `Assignation`
      Parameters:
        `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.
        `forStreaming` - set to true if optimizing for streaming
      Returns:
        an expression that delivers the same nodes in a more convenient order
      Throws:
        `XPathException` - if the rewrite fails

    - #### getIntegerBounds

          public IntegerValue[] getIntegerBounds()

      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.
      Overrides:
        `getIntegerBounds` in class `Expression`
      Returns:
        the lower and upper bounds of integer values in the result, or null to indicate unknown or not applicable.

    - #### copy

          public Expression copy​(RebindingMap rebindings)

      Copy an expression. This makes a deep copy.
      Specified by:
        `copy` in class `Expression`
      Parameters:
        `rebindings` - variables that need to be re-bound
      Returns:
        the copy of the original expression

    - #### markTailFunctionCalls

          public int markTailFunctionCalls​(StructuredQName qName,
                                           int arity)

      Mark tail function calls: only possible if the for expression iterates zero or one times. (This arises in XSLT/XPath, which does not have a LET expression, so FOR gets used instead)
      Overrides:
        `markTailFunctionCalls` in class `Expression`
      Parameters:
        `qName` - the name of the function
        `arity` - the arity (number of parameters) of the function
      Returns:
        `UserFunctionCall.NOT_TAIL_CALL` if no tail call was found; `UserFunctionCall.FOREIGN_TAIL_CALL` if a tail call on a different function was found; `UserFunctionCall.SELF_TAIL_CALL` if a tail recursive call was found and if this call accounts for the whole of the value.

    - #### isVacuousExpression

          public boolean isVacuousExpression()

      Determine whether this is a vacuous expression as defined in the XQuery update specification
      Overrides:
        `isVacuousExpression` in class `Expression`
      Returns:
        true if this expression is vacuous

    - #### getImplementationMethod

          public int getImplementationMethod()

      An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process(). This method indicates which of these methods is provided. This implementation provides both iterate() and process() methods natively.
      Specified by:
        `getImplementationMethod` in class `Expression`
      Returns:
        the implementation method, for example `Expression.ITERATE_METHOD` or `Expression.EVALUATE_METHOD` or `Expression.PROCESS_METHOD`

    - #### checkPermittedContents

          public void checkPermittedContents​(SchemaType parentType,
                                             boolean whole)
                                      throws XPathException

      Check that any elements and attributes constructed or returned by this expression are acceptable in the content model of a given complex type. It's always OK to say yes, since the check will be repeated at run-time. The process of checking element and attribute constructors against the content model of a complex type also registers the type of content expected of those constructors, so the static validation can continue recursively.
      Overrides:
        `checkPermittedContents` in class `Expression`
      Parameters:
        `parentType` - the "given complex type": the method is checking that the nodes returned by this expression are acceptable members of the content model of this type
        `whole` - if true, we want to check that the value of this expression satisfies the content model as a whole; if false we want to check that the value of the expression is acceptable as one part of the content
      Throws:
        `XPathException` - if the value delivered by this expression cannot be part of the content model of the given type

    - #### iterate

          public SequenceIterator iterate​(XPathContext context)
                                   throws XPathException

      Iterate over the sequence of values
      Overrides:
        `iterate` in class `Expression`
      Parameters:
        `context` - supplies the context for evaluation
      Returns:
        a SequenceIterator that can be used to iterate over the result of the expression
      Throws:
        `XPathException` - if any dynamic error occurs evaluating the expression

    - #### process

          public void process​(Outputter output,
                              XPathContext context)
                       throws XPathException

      Process this expression as an instruction, writing results to the current outputter
      Overrides:
        `process` in class `Expression`
      Parameters:
        `output` - the destination for the result
        `context` - The dynamic context, giving access to the current node, the current variables, etc.
      Throws:
        `XPathException` - if a dynamic error occurs

    - #### evaluatePendingUpdates

          public void evaluatePendingUpdates​(XPathContext context,
                                             PendingUpdateList pul)
                                      throws XPathException

      Evaluate an updating expression, adding the results to a Pending Update List. The default implementation of this method, which is used for non-updating expressions, throws an UnsupportedOperationException
      Overrides:
        `evaluatePendingUpdates` in class `Expression`
      Parameters:
        `context` - the XPath dynamic evaluation context
        `pul` - the pending update list to which the results should be written
      Throws:
        `XPathException` - if evaluation fails

    - #### getItemType

          public ItemType getItemType()

      Determine the data type of the items returned by the expression, if possible
      Specified by:
        `getItemType` in class `Expression`
      Returns:
        one of the values Type.STRING, Type.BOOLEAN, Type.NUMBER, Type.NODE, or Type.ITEM (meaning not known in advance)

    - #### getStaticUType

          public UType getStaticUType​(UType contextItemType)

      Get the static type of the expression as a UType, following precisely the type inference rules defined in the XSLT 3.0 specification.
      Overrides:
        `getStaticUType` in class `Expression`
      Parameters:
        `contextItemType` - the static type of the context item
      Returns:
        the static item type of the expression according to the XSLT 3.0 defined rules

    - #### computeCardinality

          public int computeCardinality()

      Determine the static cardinality of the expression
      Specified by:
        `computeCardinality` in class `Expression`
      Returns:
        the computed cardinality, as one of the values `StaticProperty.ALLOWS_ZERO_OR_ONE`, `StaticProperty.EXACTLY_ONE`, `StaticProperty.ALLOWS_ONE_OR_MORE`, `StaticProperty.ALLOWS_ZERO_OR_MORE`. May also return `StaticProperty.ALLOWS_ZERO` if the result is known to be an empty sequence, or `StaticProperty.ALLOWS_MANY` if if is known to return a sequence of length two or more.

    - #### toString

          public java.lang.String toString()

      The toString() method for an expression attempts to give a representation of the expression in an XPath-like form, but there is no guarantee that the syntax will actually be true XPath. In the case of XSLT instructions, the toString() method gives an abstracted view of the syntax
      Overrides:
        `toString` in class `Expression`
      Returns:
        a representation of the expression as a string

    - #### toShortString

          public java.lang.String toShortString()

      Description copied from class: `Expression`
      Produce a short string identifying the expression for use in error messages
      Overrides:
        `toShortString` in class `Expression`
      Returns:
        a short string, sufficient to identify the expression

    - #### export

          public void export​(ExpressionPresenter out)
                      throws XPathException

      Diagnostic print of expression structure. The abstract expression tree is written to the supplied output destination.
      Specified by:
        `export` in interface `ExportAgent`
      Specified by:
        `export` in class `Expression`
      Parameters:
        `out` - the expression presenter used to display the structure
      Throws:
        `XPathException` - if the export fails, for example if an expression is found that won't work in the target environment.

    - #### explainSpecializedAttributes

          protected void explainSpecializedAttributes​(ExpressionPresenter out)

    - #### getStreamerName

          public java.lang.String getStreamerName()

      Description copied from class: `Expression`
      Get the (partial) name of a class that supports streaming of this kind of expression
      Overrides:
        `getStreamerName` in class `Expression`
      Returns:
        the partial name of a class that can be instantiated to provide streaming support in Saxon-EE, or null if there is no such class