Package net.sf.saxon.pattern

## Class Pattern

- java.lang.Object
- - net.sf.saxon.expr.Expression
  - - net.sf.saxon.expr.PseudoExpression
    - - net.sf.saxon.pattern.Pattern

- All Implemented Interfaces:
    `ExportAgent`, `Locatable`, `IdentityComparable`, `Traceable`
  Direct Known Subclasses:
    `AncestorQualifiedPattern`, `AnchorPattern`, `BasePatternWithPredicate`, `BooleanExpressionPattern`, `GeneralNodePattern`, `GeneralPositionalPattern`, `ItemTypePattern`, `NodeSetPattern`, `NodeTestPattern`, `PatternThatSetsCurrent`, `SimplePositionalPattern`, `StreamingFunctionArgumentPattern`, `UniversalPattern`, `VennPattern`

      public abstract class Pattern
      extends PseudoExpression

  A Pattern represents the result of parsing an XSLT pattern string.

  Patterns are created by calling the static method Pattern.make(string).

  The pattern is used to test a particular node by calling match().

- - ### Field Summary

    - ### 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
    --- | ---
    `Pattern()` |

  - ### Method Summary

    All Methods Static Methods Instance Methods Abstract Methods Concrete Methods
    Modifier and Type | Method | Description
    --- | --- | ---
    `int` | `allocateSlots​(SlotManager slotManager, int nextFree)` | Allocate slots to any variables used within the pattern
    `void` | `bindCurrent​(LocalBinding binding)` | Replace any calls on current() by a variable reference bound to the supplied binding
    `Pattern` | `convertToTypedPattern​(java.lang.String val)` | Convert the pattern to a typed pattern, in which an element name is treated as schema-element(N)
    `abstract Pattern` | `copy​(RebindingMap rebindings)` | Copy an expression.
    `boolean` | `effectiveBooleanValue​(XPathContext context)` | Evaluate a pattern as a boolean expression, returning true if the context item matches the pattern
    `abstract void` | `export​(ExpressionPresenter presenter)` | Diagnostic print of expression structure.
    `double` | `getDefaultPriority()` | Determine the default priority to use if this pattern appears as a match pattern for a template with no explicit priority attribute.
    `int` | `getDependencies()` | Get the dependencies of the pattern.
    `int` | `getFingerprint()` | Determine the name fingerprint of nodes to which this pattern applies.
    `HostLanguage` | `getHostLanguage()` | Get the host language (XSLT, XQuery, XPath) used to implement the code in this container
    `abstract ItemType` | `getItemType()` | Get an ItemType that all the items matching this pattern must satisfy
    `java.lang.String` | `getOriginalText()` | Get the original text of the pattern, if known
    `abstract UType` | `getUType()` | Get a UType indicating which kinds of items this Pattern can match.
    `protected void` | `handleDynamicError​(XPathException ex, XPathContext context)` | Handle a dynamic error occurring in the course of pattern evaluation.
    `boolean` | `isLiftable​(boolean forStreaming)` | Ask whether the expression can be lifted out of a loop, assuming it has no dependencies on the controlling variable/focus of the loop
    `boolean` | `isMotionless()` | Test whether a pattern is motionless, that is, whether it can be evaluated against a node without repositioning the input stream.
    `boolean` | `isRecoverable()` | Ask whether dynamic errors in evaluating the pattern should be recovered.
    `static Pattern` | `make​(java.lang.String pattern, StaticContext env, PackageData packageData)` | Static factory method to make a Pattern by parsing a String.
    `abstract boolean` | `matches​(Item item, XPathContext context)` | Determine whether this Pattern matches the given item.
    `boolean` | `matchesBeneathAnchor​(NodeInfo node, NodeInfo anchor, XPathContext context)` | Determine whether this pattern matches a given Node within the subtree rooted at a given anchor node.
    `boolean` | `matchesCurrentGroup()` | Ask whether the pattern is anchored on a call on current-group()
    `Pattern` | `optimize​(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo)` | Perform optimisation of an expression and its subexpressions.
    `static boolean` | `patternContainsVariable​(Pattern pattern)` | Ask whether a pattern has dependencies on local variables
    `java.lang.String` | `reconstruct()` | Reconstruct a string representation of the pattern in cases where the original string is not available
    `protected static void` | `replaceCurrent​(Expression exp, LocalBinding binding)` | Replace any call to current() within a contained expression by a reference to a variable
    `SequenceIterator` | `selectNodes​(TreeInfo document, XPathContext context)` | Select all nodes in a document that match this pattern.
    `void` | `setOriginalText​(java.lang.String text)` | Set the original text of the pattern for use in diagnostics
    `void` | `setPriority​(double priority)` | Set a priority to override the default priority.
    `void` | `setRecoverable​(boolean recoverable)` | Aay whether dynamic errors in evaluating the pattern should be recovered.
    `Pattern` | `simplify()` | Simplify the pattern by applying any context-independent optimisations.
    `Pattern` | `toPattern​(Configuration config)` | Convert this expression to an equivalent XSLT pattern
    `java.lang.String` | `toShortString()` | Produce a short string identifying the expression for use in error messages
    `java.lang.String` | `toString()` | Get a string representation of the pattern.
    `Pattern` | `typeCheck​(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo)` | Type-check the pattern.

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

      `computeCardinality, evaluateAsString, evaluateItem, getImplementationMethod, iterate, process`

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

      `addToPathMap, adoptChildExpression, allowExtractingCommonSubexpressions, checkedOperands, checkForUpdatingSubexpressions, checkPermittedContents, computeDependencies, computeHashCode, computeSpecialProperties, computeStaticProperties, dynamicError, equals, evaluatePendingUpdates, explain, getCardinality, getConfiguration, getCost, getEvaluationMethod, getExpressionName, getExtraProperty, getIntegerBounds, getInterpretedExpression, getIntrinsicDependencies, getLocalRetainedStaticContext, getLocation, getNetCost, getObjectName, getPackageData, getParentExpression, getProperties, getProperty, getRetainedStaticContext, getScopingExpression, getSlotsUsed, getSpecialProperties, getStaticBaseURI, getStaticBaseURIString, getStaticType, getStaticUType, getStreamerName, getTracingTag, hasCompatibleStaticContext, hashCode, hasSpecialProperty, hasVariableBinding, identityHashCode, implementsStaticTypeCheck, isCallOn, isEqual, isIdentical, isInstruction, isMultiThreaded, isStaticPropertiesKnown, isSubtreeExpression, isUpdatingExpression, isVacuousExpression, markTailFunctionCalls, operandList, operands, operandSparseList, optimizeChildren, prepareForStreaming, resetLocalStaticProperties, restoreParentPointers, setEvaluationMethod, setExtraProperty, setFiltered, setFlattened, setLocation, setParentExpression, setRetainedStaticContext, setRetainedStaticContextLocally, setRetainedStaticContextThoroughly, setStaticProperty, simplifyChildren, staticTypeCheck, suppressValidation, typeCheckChildren, typeError, unordered, 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

    - #### Pattern

          public Pattern()

  - ### Method Detail

    - #### make

          public static Pattern make​(java.lang.String pattern,
                                     StaticContext env,
                                     PackageData packageData)
                              throws XPathException

      Static factory method to make a Pattern by parsing a String.
      Parameters:
        `pattern` - The pattern text as a String
        `env` - An object defining the compile-time context for the expression
        `packageData` - The package containing this pattern
      Returns:
        The pattern object
      Throws:
        `XPathException` - if the pattern is invalid

    - #### replaceCurrent

          protected static void replaceCurrent​(Expression exp,
                                               LocalBinding binding)

      Replace any call to current() within a contained expression by a reference to a variable
      Parameters:
        `exp` - the expression in which the replacement is to take place (which must not itself be a call to current())
        `binding` - the binding for the variable reference

    - #### patternContainsVariable

          public static boolean patternContainsVariable​(Pattern pattern)

      Ask whether a pattern has dependencies on local variables
      Parameters:
        `pattern` - the pattern (typically a pattern in an xsl:number or xsl:for-each-group); or null
      Returns:
        true if the pattern is non-null and has dependencies on local variables

    - #### isLiftable

          public boolean isLiftable​(boolean forStreaming)

      Ask whether the expression can be lifted out of a loop, assuming it has no dependencies on the controlling variable/focus of the loop
      Overrides:
        `isLiftable` in class `Expression`
      Parameters:
        `forStreaming` - true if we are generating code for streaming
      Returns:
        true if the expression can be loop lifted

    - #### bindCurrent

          public void bindCurrent​(LocalBinding binding)

      Replace any calls on current() by a variable reference bound to the supplied binding

    - #### matchesCurrentGroup

          public boolean matchesCurrentGroup()

      Ask whether the pattern is anchored on a call on current-group()
      Returns:
        true if calls on matchesBeneathAnchor should test with all nodes in the current group as anchor nodes. If false, only the first node in a group is treated as the anchor node

    - #### setOriginalText

          public void setOriginalText​(java.lang.String text)

      Set the original text of the pattern for use in diagnostics
      Parameters:
        `text` - the original text of the pattern

    - #### isRecoverable

          public boolean isRecoverable()

      Ask whether dynamic errors in evaluating the pattern should be recovered. This is the default for normal XSLT patterns, but patterns used internally to represent scannable streaming expressions are non-recoverable
      Returns:
        true if dynamic errors in pattern evaluation should be treated as recoverable (if an error occurs, the pattern is treated as non-matching; a warning is sent to the ErrorListener).

    - #### setRecoverable

          public void setRecoverable​(boolean recoverable)

      Aay whether dynamic errors in evaluating the pattern should be recovered. This is the default for normal XSLT patterns, but patterns used internally to represent scannable streaming expressions are non-recoverable
      Parameters:
        `recoverable` - true if dynamic errors in pattern evaluation should be treated as recoverable (if an error occurs, the pattern is treated as non-matching; a warning is sent to the ErrorListener).

    - #### handleDynamicError

          protected void handleDynamicError​(XPathException ex,
                                            XPathContext context)
                                     throws XPathException

      Handle a dynamic error occurring in the course of pattern evaluation. The effect depends on (a) whether the error is a circularity error, and (b) whether the pattern is marked as recoverable or not
      Parameters:
        `ex` - the exception
        `context` - the evaluation context
      Throws:
        `XPathException` - if the error is found to be non-recoverable

    - #### simplify

          public Pattern simplify()
                           throws XPathException

      Simplify the pattern by applying any context-independent optimisations. Default implementation does nothing.
      Overrides:
        `simplify` in class `Expression`
      Returns:
        the simplified expression (or the original if unchanged, or if modified in-situ)
      Throws:
        `XPathException` - if an error is discovered during expression rewriting

    - #### typeCheck

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

      Type-check the pattern.
      Overrides:
        `typeCheck` in class `Expression`
      Parameters:
        `visitor` - the expression visitor
        `contextInfo` - the type of the context item at the point where the pattern is defined. Set to null if it is known that the context item is undefined.
      Returns:
        the optimised Pattern
      Throws:
        `XPathException` - if an error is discovered during this phase (typically a type error)

    - #### getDependencies

          public int getDependencies()

      Get the dependencies of the pattern. The only interesting dependencies for a pattern are dependencies on local variables or on user-defined functions. These are analyzed in those patterns containing predicates.
      Overrides:
        `getDependencies` in class `Expression`
      Returns:
        the dependencies, as a bit-significant mask

    - #### allocateSlots

          public int allocateSlots​(SlotManager slotManager,
                                   int nextFree)

      Allocate slots to any variables used within the pattern
      Parameters:
        `slotManager` - the slot manager representing the stack frame for local variables
        `nextFree` - the next slot that is free to be allocated
      Returns:
        the next slot that is free to be allocated

    - #### isMotionless

          public boolean isMotionless()

      Test whether a pattern is motionless, that is, whether it can be evaluated against a node without repositioning the input stream. This is a necessary condition for patterns used as the match pattern of a streamed template rule.
      Returns:
        true if the pattern is motionless, that is, if it can be evaluated against a streamed node without changing the position in the streamed input file

    - #### effectiveBooleanValue

          public final boolean effectiveBooleanValue​(XPathContext context)
                                              throws XPathException

      Evaluate a pattern as a boolean expression, returning true if the context item matches the pattern
      Overrides:
        `effectiveBooleanValue` in class `PseudoExpression`
      Parameters:
        `context` - the evaluation context
      Returns:
        true if the context item matches the pattern
      Throws:
        `XPathException` - if an error occurs during pattern matching

    - #### matches

          public abstract boolean matches​(Item item,
                                          XPathContext context)
                                   throws XPathException

      Determine whether this Pattern matches the given item. This is the main external interface for matching patterns: it sets current() to the node being tested
      Parameters:
        `item` - The item to be tested against the Pattern
        `context` - The dynamic context.
      Returns:
        true if the node matches the Pattern, false otherwise
      Throws:
        `XPathException` - if an error occurs while matching the pattern (the caller will usually treat this the same as a false result)

    - #### matchesBeneathAnchor

          public boolean matchesBeneathAnchor​(NodeInfo node,
                                              NodeInfo anchor,
                                              XPathContext context)
                                       throws XPathException

      Determine whether this pattern matches a given Node within the subtree rooted at a given anchor node. This method is used when the pattern is used for streaming.
      Parameters:
        `node` - The NodeInfo representing the Element or other node to be tested against the Pattern
        `anchor` - The anchor node, which must match any AnchorPattern subpattern
        `context` - The dynamic context. Only relevant if the pattern uses variables, or contains calls on functions such as document() or key().
      Returns:
        true if the node matches the Pattern, false otherwise
      Throws:
        `XPathException` - if an error occurs while matching the pattern (the caller will usually treat this the same as a false result)

    - #### selectNodes

          public SequenceIterator selectNodes​(TreeInfo document,
                                              XPathContext context)
                                       throws XPathException

      Select all nodes in a document that match this pattern.
      Parameters:
        `document` - the document
        `context` - the dynamic evaluation context
      Returns:
        an iterator over the selected nodes in the document.
      Throws:
        `XPathException`

    - #### getUType

          public abstract UType getUType()

      Get a UType indicating which kinds of items this Pattern can match.
      Returns:
        a UType indicating all the primitive types of item that the pattern can match.

    - #### getFingerprint

          public int getFingerprint()

      Determine the name fingerprint of nodes to which this pattern applies. Used for optimisation.
      Returns:
        A fingerprint that the nodes must match, or -1 if it can match multiple fingerprints, or it if matches atomic values

    - #### getItemType

          public abstract ItemType getItemType()

      Get an ItemType that all the items matching this pattern must satisfy
      Overrides:
        `getItemType` in class `PseudoExpression`
      Returns:
        an ItemType, as specific as possible, which all the matching items satisfy

    - #### setPriority

          public void setPriority​(double priority)

      Set a priority to override the default priority. This is used when the pattern is written in a complex form such as a[true()] justifying a priority of 0.5, but then simplifies down to an NodeTestPattern
      Parameters:
        `priority` - the priority to be used if no explicit priority is given in the template rule

    - #### getDefaultPriority

          public double getDefaultPriority()

      Determine the default priority to use if this pattern appears as a match pattern for a template with no explicit priority attribute.
      Returns:
        the default priority for the pattern

    - #### getOriginalText

          public java.lang.String getOriginalText()

      Get the original text of the pattern, if known
      Returns:
        the original text of the pattern as written; this may be null in the case of a pattern constructed programmatically

    - #### toString

          public java.lang.String toString()

      Get a string representation of the pattern. This will be in a form similar to the original pattern text, but not necessarily identical. It is not guaranteed to be in legal pattern syntax.
      Overrides:
        `toString` in class `Expression`
      Returns:
        a representation of the expression as a string

    - #### reconstruct

          public java.lang.String reconstruct()

      Reconstruct a string representation of the pattern in cases where the original string is not available

    - #### getHostLanguage

          public HostLanguage getHostLanguage()

      Get the host language (XSLT, XQuery, XPath) used to implement the code in this container
      Returns:
        typically `HostLanguage.XSLT` or `HostLanguage.XQUERY`

    - #### convertToTypedPattern

          public Pattern convertToTypedPattern​(java.lang.String val)
                                        throws XPathException

      Convert the pattern to a typed pattern, in which an element name is treated as schema-element(N)
      Parameters:
        `val` - either "strict" or "lax" depending on the value of xsl:mode/@typed
      Returns:
        either the original pattern unchanged, or a new pattern as the result of the conversion
      Throws:
        `XPathException` - if the pattern cannot be converted

    - #### toPattern

          public Pattern toPattern​(Configuration config)

      Description copied from class: `Expression`
      Convert this expression to an equivalent XSLT pattern
      Overrides:
        `toPattern` in class `Expression`
      Parameters:
        `config` - the Saxon configuration
      Returns:
        the equivalent pattern

    - #### export

          public abstract void export​(ExpressionPresenter presenter)
                               throws XPathException

      Description copied from class: `Expression`
      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:
        `presenter` - 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.

    - #### copy

          public abstract Pattern copy​(RebindingMap rebindings)

      Description copied from class: `Expression`
      Copy an expression. This makes a deep copy.
      Specified by:
        `copy` in class `Expression`
      Parameters:
        `rebindings` - a mutable list of (old binding, new binding) pairs that is used to update the bindings held in any local variable references that are copied.
      Returns:
        the copy of the original expression

    - #### optimize

          public Pattern optimize​(ExpressionVisitor visitor,
                                  ContextItemStaticInfo contextInfo)
                           throws XPathException

      Perform optimisation of an expression and its subexpressions. This is the third and final phase of static optimization.

      This method is called after all references to functions and variables have been resolved to the declaration of the function or variable, and after all type checking has been done.

      Overrides:
        `optimize` in class `Expression`
      Parameters:
        `visitor` - an expression visitor
        `contextInfo` - 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)

    - #### 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