Class Expression
- java.lang.Object
-
- net.sf.saxon.expr.Expression
-
- All Implemented Interfaces:
ExportAgent
,Locatable
,IdentityComparable
,Traceable
- Direct Known Subclasses:
Assignation
,AttributeGetter
,AxisExpression
,BasicUpdatingExpression
,BinaryExpression
,CompiledExpression
,ConditionalSorter
,ContextItemExpression
,CopyModifyExpression
,CurrentGroupCall
,CurrentGroupingKeyCall
,ErrorExpression
,EvaluateInstr
,FLWORExpression
,FunctionCall
,IndexedFilterExpression
,Instruction
,IntegerRangeTest
,IsLastExpression
,JAXPVariableReference
,Literal
,NumberInstruction
,NumberSequenceFormatter
,PartialApply
,PseudoExpression
,RootExpression
,SimpleExpression
,SortExpression
,SquareArrayConstructor
,SuppliedParameterReference
,SwitchExpression
,TryCatch
,TupleExpression
,UnaryExpression
,UserFunctionReference
,VariableReference
public abstract class Expression extends java.lang.Object implements IdentityComparable, ExportAgent, Locatable, Traceable
Interface supported by an XPath expression. This includes both compile-time and run-time methods.Two expressions are considered equal if they return the same result when evaluated in the same context.
Expressions manage their own subexpressions but must observe certain conventions when doing so. Every expression must implement the methods operands() and getOperand(N) to access the operands of the expression; here N is an integer identifier for the subexpression which is unique among the subexpressions and whose allocation is a matter for each expression to determined. So a subexpression of an expression can change (during optimization rewrite, for example), then (a) the expression must implement the method setOperandExpression(N, expr) to effect the change, and (b) calling this method must cause a call on adoptChildExpression(N, expr) which is implemented in the expression class itself, and takes responsibility for maintaining the consistency of the tree, e.g. by invalidating cached information.
The default implementations of methods such as operands() work for expressions that have no subexpressions.
-
-
Field Summary
Fields Modifier and Type Field Description static int
EFFECTIVE_BOOLEAN_VALUE
static int
EVALUATE_METHOD
static int
ITEM_FEED_METHOD
static int
ITERATE_METHOD
static double
MAX_COST
static IntegerValue
MAX_SEQUENCE_LENGTH
static IntegerValue
MAX_STRING_LENGTH
static int
PROCESS_METHOD
protected int
staticProperties
static IntegerValue
UNBOUNDED_LOWER
static IntegerValue
UNBOUNDED_UPPER
static int
UPDATE_METHOD
static int
WATCH_METHOD
-
Constructor Summary
Constructors Constructor Description Expression()
-
Method Summary
All Methods Instance Methods Abstract Methods Concrete Methods Modifier and Type Method Description PathMap.PathMapNodeSet
addToPathMap(PathMap pathMap, PathMap.PathMapNodeSet pathMapNodeSet)
Add a representation of this expression to a PathMap.void
adoptChildExpression(Expression child)
Set up a parent-child relationship between this expression and a given child expression.boolean
allowExtractingCommonSubexpressions()
Ask whether common subexpressions found in the operands of this expression can be extracted and evaluated outside the expression itself.java.lang.Iterable<Operand>
checkedOperands()
Get the immediate sub-expressions of this expression, verifying that the parent pointers in the child expressions are correct.void
checkForUpdatingSubexpressions()
Check to ensure that this expression does not contain any inappropriate updating subexpressions.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.protected abstract int
computeCardinality()
Compute the static cardinality of this expressionint
computeDependencies()
Compute the dependencies of an expression, as the union of the dependencies of its subexpressions.protected int
computeHashCode()
Compute a hash code, which will then be cached for later useprotected int
computeSpecialProperties()
Compute the special properties of this expression.void
computeStaticProperties()
Compute the static properties.abstract Expression
copy(RebindingMap rebindings)
Copy an expression.protected void
dynamicError(java.lang.String message, java.lang.String code, XPathContext context)
Method used in subclasses to signal a dynamic errorboolean
effectiveBooleanValue(XPathContext context)
Get the effective boolean value of the expression.boolean
equals(java.lang.Object obj)
The equals() test for expressions returns true if it can be determined that two expressions (given their static context) will return the same result in all circumstances.java.lang.CharSequence
evaluateAsString(XPathContext context)
Evaluate an expression as a String.Item
evaluateItem(XPathContext context)
Evaluate an expression as a single item.void
evaluatePendingUpdates(XPathContext context, PendingUpdateList pul)
Evaluate an updating expression, adding the results to a Pending Update List.void
explain(Logger out)
Diagnostic print of expression structure.abstract void
export(ExpressionPresenter out)
Diagnostic print of expression structure.int
getCardinality()
Determine the static cardinality of the expression.Configuration
getConfiguration()
Get the configuration containing this expressiondouble
getCost()
Return the estimated cost of evaluating an expression.int
getDependencies()
Determine which aspects of the context the expression depends on.int
getEvaluationMethod()
java.lang.String
getExpressionName()
Get a name identifying the kind of expression, in terms meaningful to a user.java.lang.Object
getExtraProperty(java.lang.String name)
Get the value of an extra property on the expressionabstract 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.Expression
getInterpretedExpression()
Get the interpreted form of the expression.int
getIntrinsicDependencies()
Determine the intrinsic dependencies of an expression, that is, those which are not derived from the dependencies of its subexpressions.abstract ItemType
getItemType()
Determine the static item type of the expression, as precisely possible.RetainedStaticContext
getLocalRetainedStaticContext()
Location
getLocation()
Get the location of the expressionint
getNetCost()
Return the net cost of evaluating this expression, excluding the cost of evaluating its operands.StructuredQName
getObjectName()
Get a name identifying the object of the expression, for example a function name, template name, variable name, key name, element name, etc.PackageData
getPackageData()
Get information about the containing packageExpression
getParentExpression()
Get the parent expression of this expression in the expression tree.java.util.Iterator<java.lang.String>
getProperties()
Get an iterator over all the properties available.java.lang.Object
getProperty(java.lang.String name)
RetainedStaticContext
getRetainedStaticContext()
Get the retained static context of the expressionExpression
getScopingExpression()
Get the innermost scoping expression of this expression, for expressions that directly depend on something in the dynamic context.int[]
getSlotsUsed()
Get the local variables (identified by their slot numbers) on which this expression depends.int
getSpecialProperties()
Get the static properties of this expression (other than its type).java.net.URI
getStaticBaseURI()
Get the saved static base URI as a URIjava.lang.String
getStaticBaseURIString()
Get the saved static base URI as a stringSequenceType
getStaticType()
Get the static type of the expression as a SequenceType: this is the combination of the item type and the cardinality.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 expressionjava.lang.String
getTracingTag()
protected boolean
hasCompatibleStaticContext(Expression other)
Ask whether the static context of this expression is compatible with the static context of another expression.int
hashCode()
The hashCode() for an expression has semantics corresponding to equals().boolean
hasSpecialProperty(int property)
Ask whether a particular "special property" is present for this expressionboolean
hasVariableBinding(Binding binding)
Ask whether this expression is, or contains, the binding of a given variableint
identityHashCode()
Get a hashCode that offers the guarantee that if A.isIdentical(B), then A.identityHashCode() == B.identityHashCode()boolean
implementsStaticTypeCheck()
Determine whether this expression implements its own method for static type checkingboolean
isCallOn(java.lang.Class<? extends SystemFunction> function)
Ask whether this expression is a call on a particular functionboolean
isEqual(Expression other)
Test if this is expression is equivalent to another.boolean
isIdentical(IdentityComparable other)
Determine whether two IdentityComparable objects are identical.boolean
isInstruction()
Ask whether this expression is an instruction.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 loopboolean
isMultiThreaded(Configuration config)
Ask whether the expression is multithreaded (that is, whether its operands are evaluated in parallel)boolean
isStaticPropertiesKnown()
Ask whether the static properties of the expression have been computedboolean
isSubtreeExpression()
Determine whether the expression can be evaluated without reference to the part of the context document outside the subtree rooted at the context node.boolean
isUpdatingExpression()
Determine whether this is an updating expression as defined in the XQuery update specificationboolean
isVacuousExpression()
Determine whether this is a vacuous expression as defined in the XQuery update specificationSequenceIterator
iterate(XPathContext context)
Return an Iterator to iterate over the values of a sequence.int
markTailFunctionCalls(StructuredQName qName, int arity)
Mark tail-recursive calls on stylesheet functions.protected java.util.List<Operand>
operandList(Operand... a)
Helper method for subclasses to build a list of operandsjava.lang.Iterable<Operand>
operands()
Get the immediate sub-expressions of this expression, with information about the relationship of each expression to its parent expression.protected java.util.List<Operand>
operandSparseList(Operand... a)
Helper method for subclasses to build a list of operandsExpression
optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo)
Perform optimisation of an expression and its subexpressions.protected void
optimizeChildren(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo)
Perform optimization of the children of this expression (and their children, recursively) This method is provided as a helper for implementations of theoptimize(net.sf.saxon.expr.parser.ExpressionVisitor, net.sf.saxon.expr.parser.ContextItemStaticInfo)
method, since optimizing the children is an inevitable part of optimizing the expression itselfvoid
prepareForStreaming()
void
process(Outputter output, XPathContext context)
Process the instruction, without returning any tail callsvoid
resetLocalStaticProperties()
Reset the static properties of the expression to -1, so that they have to be recomputed next time they are used.void
restoreParentPointers()
Restore parent pointers for the subtree rooted at this expressionvoid
setEvaluationMethod(int method)
void
setExtraProperty(java.lang.String name, java.lang.Object value)
Set an extra property on the expression.void
setFiltered(boolean filtered)
Mark an expression as filtered: that is, it appears as the base expression in a filter expression.void
setFlattened(boolean flattened)
Mark an expression as being "flattened".void
setLocation(Location id)
Set the location on an expression.void
setParentExpression(Expression parent)
Set the parent expression of this expression in the expression tree.void
setRetainedStaticContext(RetainedStaticContext rsc)
Set the retained static contextvoid
setRetainedStaticContextLocally(RetainedStaticContext rsc)
Set the parts of the static context that might be needed by the function, without passing them on to subexpressions.void
setRetainedStaticContextThoroughly(RetainedStaticContext rsc)
Set the retained static context on this expression and on all subexpressions in the expression tree.void
setStaticProperty(int prop)
Set a static property on an expression.Expression
simplify()
Simplify an expression.protected void
simplifyChildren()
Simplify this expression.Expression
staticTypeCheck(SequenceType req, boolean backwardsCompatible, RoleDiagnostic role, ExpressionVisitor visitor)
Static type checking of some expressions is delegated to the expression itself, by calling this method.void
suppressValidation(int parentValidationMode)
Suppress validation on contained element constructors, on the grounds that the parent element is already performing validation.Pattern
toPattern(Configuration config)
Convert this expression to an equivalent XSLT patternjava.lang.String
toShortString()
Produce a short string identifying the expression for use in error messagesjava.lang.String
toString()
The toString() method for an expression attempts to give a representation of the expression in an XPath-like form.Expression
typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo)
Perform type checking of an expression and its subexpressions.protected void
typeCheckChildren(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo)
Perform type checking of the children of this expression (and their children, recursively) This method is provided as a helper for implementations of thetypeCheck(net.sf.saxon.expr.parser.ExpressionVisitor, net.sf.saxon.expr.parser.ContextItemStaticInfo)
method, since checking the children is an inevitable part of checking the expression itse.fprotected void
typeError(java.lang.String message, java.lang.String errorCode, XPathContext context)
Method used in subclasses to signal a runtime type errorExpression
unordered(boolean retainAllNodes, boolean forStreaming)
Replace this expression by a simpler expression that delivers the results without regard to order.Expression
verifyParentPointers()
Verify that parent pointers are correct throughout the subtree rooted at this expression-
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
-
-
-
-
Field Detail
-
EVALUATE_METHOD
public static final int EVALUATE_METHOD
- See Also:
- Constant Field Values
-
ITERATE_METHOD
public static final int ITERATE_METHOD
- See Also:
- Constant Field Values
-
PROCESS_METHOD
public static final int PROCESS_METHOD
- See Also:
- Constant Field Values
-
WATCH_METHOD
public static final int WATCH_METHOD
- See Also:
- Constant Field Values
-
ITEM_FEED_METHOD
public static final int ITEM_FEED_METHOD
- See Also:
- Constant Field Values
-
EFFECTIVE_BOOLEAN_VALUE
public static final int EFFECTIVE_BOOLEAN_VALUE
- See Also:
- Constant Field Values
-
UPDATE_METHOD
public static final int UPDATE_METHOD
- See Also:
- Constant Field Values
-
staticProperties
protected int staticProperties
-
MAX_COST
public static final double MAX_COST
- See Also:
- Constant Field Values
-
UNBOUNDED_LOWER
public static final IntegerValue UNBOUNDED_LOWER
-
UNBOUNDED_UPPER
public static final IntegerValue UNBOUNDED_UPPER
-
MAX_STRING_LENGTH
public static final IntegerValue MAX_STRING_LENGTH
-
MAX_SEQUENCE_LENGTH
public static final IntegerValue MAX_SEQUENCE_LENGTH
-
-
Method Detail
-
getExpressionName
public java.lang.String getExpressionName()
Get a name identifying the kind of expression, in terms meaningful to a user.- 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 export() output displaying the expression.
-
operands
public java.lang.Iterable<Operand> operands()
Get the immediate sub-expressions of this expression, with information about the relationship of each expression to its parent expression. Default implementation works off the results of iterateSubExpressions()If the expression is a Callable, then it is required that the order of the operands returned by this function is the same as the order of arguments supplied to the corresponding call() method.
- Returns:
- an iterator containing the sub-expressions of this expression
-
getInterpretedExpression
public Expression getInterpretedExpression()
Get the interpreted form of the expression. Normally this returns the expression unchanged; but on a CompiledExpression (the result of bytecode generation) it returns the original interpreted form.- Returns:
- the interpreted form of this expression
-
checkedOperands
public final java.lang.Iterable<Operand> checkedOperands()
Get the immediate sub-expressions of this expression, verifying that the parent pointers in the child expressions are correct.- Returns:
- the list of sub-expressions, in the same way as with the
operands()
method, but with additional checking
-
operandList
protected java.util.List<Operand> operandList(Operand... a)
Helper method for subclasses to build a list of operands- Parameters:
a
- the sequence of operands (which must all be non-null)- Returns:
- a list of operands
-
operandSparseList
protected java.util.List<Operand> operandSparseList(Operand... a)
Helper method for subclasses to build a list of operands- Parameters:
a
- the sequence of operands; any null values in the list are ignored- Returns:
- a list of operands
-
getParentExpression
public Expression getParentExpression()
Get the parent expression of this expression in the expression tree.- Returns:
- the parent expression. Null if at the root of the tree, for example, the expression representing the body of a function or template.
-
setParentExpression
public void setParentExpression(Expression parent)
Set the parent expression of this expression in the expression tree.- Parameters:
parent
- the parent expression
-
verifyParentPointers
public Expression verifyParentPointers() throws java.lang.IllegalStateException
Verify that parent pointers are correct throughout the subtree rooted at this expression- Returns:
- the expression
- Throws:
java.lang.IllegalStateException
- if invalid parent pointers are found
-
restoreParentPointers
public void restoreParentPointers()
Restore parent pointers for the subtree rooted at this expression
-
getImplementationMethod
public abstract 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 directly. The other methods will always be available indirectly, using an implementation that relies on one of the other methods.- Returns:
- the implementation method, for example
ITERATE_METHOD
orEVALUATE_METHOD
orPROCESS_METHOD
-
implementsStaticTypeCheck
public boolean implementsStaticTypeCheck()
Determine whether this expression implements its own method for static type checking- Returns:
- true if this expression has a non-trivial implementation of the staticTypeCheck() method
-
hasVariableBinding
public boolean hasVariableBinding(Binding binding)
Ask whether this expression is, or contains, the binding of a given variable- Parameters:
binding
- the variable binding- Returns:
- true if this expression is the variable binding (for example a ForExpression or LetExpression) or if it is a FLWOR expression that binds the variable in one of its clauses.
-
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- Parameters:
forStreaming
- true if we are optimizing for streamed evaluation- Returns:
- true if the expression can be loop lifted
-
getScopingExpression
public Expression getScopingExpression()
Get the innermost scoping expression of this expression, for expressions that directly depend on something in the dynamic context. For example, in the case of a local variable reference this is the expression that causes the relevant variable to be bound; for a context item expression it is the innermost focus-setting container. For expressions that have no intrinsic dependency on the dynamic context, the value returned is null; the scoping container for such an expression is the innermost scoping container of its operands.- Returns:
- the innermost scoping container of this expression
-
isMultiThreaded
public boolean isMultiThreaded(Configuration config)
Ask whether the expression is multithreaded (that is, whether its operands are evaluated in parallel)- Parameters:
config
- the Saxon configuration- Returns:
- true if execution will be multithreaded
-
allowExtractingCommonSubexpressions
public boolean allowExtractingCommonSubexpressions()
Ask whether common subexpressions found in the operands of this expression can be extracted and evaluated outside the expression itself. The result is irrelevant in the case of operands evaluated with a different focus, which will never be extracted in this way, even if they have no focus dependency.- Returns:
- true by default, unless overridden in a subclass
-
simplify
public Expression simplify() throws XPathException
Simplify an expression. This performs any static optimization (by rewriting the expression as a different expression). The default implementation simplifies its operands.- Returns:
- the simplified expression (or the original if unchanged, or if modified in-situ)
- Throws:
XPathException
- if an error is discovered during expression rewriting
-
simplifyChildren
protected final void simplifyChildren() throws XPathException
Simplify this expression. This performs any static optimization (by rewriting the expression as a different expression). The default implementation simplifies its operands.- Throws:
XPathException
- if an error is discovered during expression rewriting
-
setRetainedStaticContext
public void setRetainedStaticContext(RetainedStaticContext rsc)
Set the retained static context- Parameters:
rsc
- the static context to be retained
-
setRetainedStaticContextThoroughly
public void setRetainedStaticContextThoroughly(RetainedStaticContext rsc)
Set the retained static context on this expression and on all subexpressions in the expression tree. The supplied retained static context is applied to all subexpressions, unless they have a closer ancestor with an existing retained static context, in which case that is used instead,- Parameters:
rsc
- the static context to be retained
-
setRetainedStaticContextLocally
public void setRetainedStaticContextLocally(RetainedStaticContext rsc)
Set the parts of the static context that might be needed by the function, without passing them on to subexpressions. Used for dynamic function calls only.- Parameters:
rsc
- the retained static context
-
getRetainedStaticContext
public final RetainedStaticContext getRetainedStaticContext()
Get the retained static context of the expression- Returns:
- the retained static context
-
getLocalRetainedStaticContext
public RetainedStaticContext getLocalRetainedStaticContext()
-
getStaticBaseURIString
public java.lang.String getStaticBaseURIString()
Get the saved static base URI as a string- Returns:
- the static base URI
-
getStaticBaseURI
public java.net.URI getStaticBaseURI() throws XPathException
Get the saved static base URI as a URI- Returns:
- the static base URI as a URI
- Throws:
XPathException
- if the static base URI is not a valid URI
-
isCallOn
public boolean isCallOn(java.lang.Class<? extends SystemFunction> function)
Ask whether this expression is a call on a particular function- Parameters:
function
- the implementation class of the function in question- Returns:
- true if the expression is a call on the function
-
typeCheck
public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException
Perform type checking of an expression and its subexpressions. This is the second phase of static optimization.This checks statically that the operands of the expression have the correct type; if necessary it generates code to do run-time type checking or type conversion. A static type error is reported only if execution cannot possibly succeed, that is, if a run-time type error is inevitable. The call may return a modified form of the expression.
This method is called after all references to functions and variables have been resolved to the declaration of the function or variable. However, the types of such functions and variables may not be accurately known if they have not been explicitly declared.
- Parameters:
visitor
- an expression visitorcontextInfo
- 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)
-
typeCheckChildren
protected final void typeCheckChildren(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException
Perform type checking of the children of this expression (and their children, recursively) This method is provided as a helper for implementations of thetypeCheck(net.sf.saxon.expr.parser.ExpressionVisitor, net.sf.saxon.expr.parser.ContextItemStaticInfo)
method, since checking the children is an inevitable part of checking the expression itse.f- Parameters:
visitor
- an expression visitorcontextInfo
- Information available statically about the context item: whether it is (possibly) absent; its static type; its streaming posture.- Throws:
XPathException
- if an error is discovered during this phase (typically a type error)
-
staticTypeCheck
public Expression staticTypeCheck(SequenceType req, boolean backwardsCompatible, RoleDiagnostic role, ExpressionVisitor visitor) throws XPathException
Static type checking of some expressions is delegated to the expression itself, by calling this method. The default implementation of the method throws UnsupportedOperationException. If there is a non-default implementation, then implementsStaticTypeCheck() will return true- Parameters:
req
- the required typebackwardsCompatible
- true if backwards compatibility mode appliesrole
- the role of the expression in relation to the required typevisitor
- an expression visitor- Returns:
- the expression after type checking (perhaps augmented with dynamic type checking code)
- Throws:
XPathException
- if failures occur, for example if the static type of one branch of the conditional is incompatible with the required type
-
optimize
public Expression 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.
- Parameters:
visitor
- an expression visitorcontextInfo
- 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 toType.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)
-
optimizeChildren
protected final void optimizeChildren(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException
Perform optimization of the children of this expression (and their children, recursively) This method is provided as a helper for implementations of theoptimize(net.sf.saxon.expr.parser.ExpressionVisitor, net.sf.saxon.expr.parser.ContextItemStaticInfo)
method, since optimizing the children is an inevitable part of optimizing the expression itself- Parameters:
visitor
- an expression visitorcontextInfo
- Information available statically about the context item: whether it is (possibly) absent; its static type; its streaming posture.- Throws:
XPathException
- if an error is discovered during this phase (typically a type error)
-
prepareForStreaming
public void prepareForStreaming() throws XPathException
- Throws:
XPathException
-
getCost
public double getCost()
Return the estimated cost of evaluating an expression. This is a very crude measure based on the syntactic form of the expression (we have no knowledge of data values). We take the cost of evaluating a simple scalar comparison or arithmetic expression as 1 (one), and we assume that a sequence has length 5. The resulting estimates may be used, for example, to reorder the predicates in a filter expression so cheaper predicates are evaluated first.- Returns:
- an estimate of the gross cost of evaluating the expression, including the cost of evaluating its operands.
-
getNetCost
public int getNetCost()
Return the net cost of evaluating this expression, excluding the cost of evaluating its operands. We take the cost of evaluating a simple scalar comparison or arithmetic expression as 1 (one).- Returns:
- the intrinsic cost of this operation, excluding the costs of evaluating the operands
-
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.- 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 the result is to be optimized for streaming- Returns:
- an expression that delivers the same nodes in a more convenient order
- Throws:
XPathException
- if the rewrite fails
-
getSpecialProperties
public final int getSpecialProperties()
Get the static properties of this expression (other than its type). The result is bit-signficant. These properties are used for optimizations. In general, if property bit is set, it is true, but if it is unset, the value is unknown.- Returns:
- a set of flags indicating static properties of this expression
-
hasSpecialProperty
public boolean hasSpecialProperty(int property)
Ask whether a particular "special property" is present for this expression- Parameters:
property
- the property in question, as an integer code in theStaticProperty
class- Returns:
- true if the given property is present
-
getCardinality
public int getCardinality()
Determine the static cardinality of the expression. This establishes how many items there will be in the result of the expression, at compile time (i.e., without actually evaluating the result.- Returns:
- one of the values Cardinality.ONE_OR_MORE, Cardinality.ZERO_OR_MORE, Cardinality.EXACTLY_ONE, Cardinality.ZERO_OR_ONE, Cardinality.EMPTY. This default implementation returns ZERO_OR_MORE (which effectively gives no information).
-
getItemType
public abstract ItemType getItemType()
Determine the static item type of the expression, as precisely possible. All expression return sequences, in general; this method determines the type of the items within the sequence, assuming that (a) this is known in advance, and (b) it is the same for all items in the sequence.This method should always return a result, though it may be the best approximation that is available at the time.
- Returns:
- a value such as Type.STRING, Type.BOOLEAN, Type.NUMBER, Type.NODE, or Type.ITEM (meaning not known at compile time)
-
getStaticType
public SequenceType getStaticType()
Get the static type of the expression as a SequenceType: this is the combination of the item type and the cardinality.- Returns:
- the static type of the expression
-
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.- 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
-
getDependencies
public int getDependencies()
Determine which aspects of the context the expression depends on. The result is a bitwise-or'ed value composed from constants such as XPathContext.VARIABLES and XPathContext.CURRENT_NODE. The default implementation combines the intrinsic dependencies of this expression with the dependencies of the subexpressions, computed recursively. This is overridden for expressions such as FilterExpression where a subexpression's dependencies are not necessarily inherited by the parent expression.- Returns:
- a set of bit-significant flags identifying the dependencies of the expression
-
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.- Returns:
- the lower and upper bounds of integer values in the result, or null to indicate unknown or not applicable.
-
setFlattened
public void setFlattened(boolean flattened)
Mark an expression as being "flattened". This is a collective term that includes extracting the string value or typed value, or operations such as simple value construction that concatenate text nodes before atomizing. The implication of all of these is that although the expression might return nodes, the identity of the nodes has no significance. This is called during type checking of the parent expression.- Parameters:
flattened
- set to true if the result of the expression is atomized or otherwise turned into an atomic value
-
setFiltered
public void setFiltered(boolean filtered)
Mark an expression as filtered: that is, it appears as the base expression in a filter expression. This notification currently has no effect except when the expression is a variable reference.- Parameters:
filtered
- if true, marks this expression as the base of a filter expression
-
evaluateItem
public Item evaluateItem(XPathContext context) throws XPathException
Evaluate an expression as a single item. This always returns either a single Item or null (denoting the empty sequence). No conversion is done. This method should not be used unless the static type of the expression is a subtype of "item" or "item?": that is, it should not be called if the expression may return a sequence. There is no guarantee that this condition will be detected.- Parameters:
context
- The context in which the expression is to be evaluated- Returns:
- the node or atomic value that results from evaluating the expression; or null to indicate that the result is an empty sequence
- Throws:
XPathException
- if any dynamic error occurs evaluating the expression
-
iterate
public SequenceIterator iterate(XPathContext context) throws XPathException
Return an Iterator to iterate over the values of a sequence. The value of every expression can be regarded as a sequence, so this method is supported for all expressions. This default implementation handles iteration for expressions that return singleton values: for non-singleton expressions, the subclass must provide its own implementation.- 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
-
effectiveBooleanValue
public boolean effectiveBooleanValue(XPathContext context) throws XPathException
Get the effective boolean value of the expression. This returns false if the value is the empty sequence, a zero-length string, a number equal to zero, or the boolean false. Otherwise it returns true.- Parameters:
context
- The context in which the expression is to be evaluated- Returns:
- the effective boolean value
- Throws:
XPathException
- if any dynamic error occurs evaluating the expression
-
evaluateAsString
public java.lang.CharSequence evaluateAsString(XPathContext context) throws XPathException
Evaluate an expression as a String. This function must only be called in contexts where it is known that the expression will return a single string (or where an empty sequence is to be treated as a zero-length string). Implementations should not attempt to convert the result to a string, other than converting () to "". This method is used mainly to evaluate expressions produced by compiling an attribute value template.- Parameters:
context
- The context in which the expression is to be evaluated- Returns:
- the value of the expression, evaluated in the current context. The expression must return a string or (); if the value of the expression is (), this method returns "".
- Throws:
XPathException
- if any dynamic error occurs evaluating the expressionjava.lang.ClassCastException
- if the result type of the expression is not xs:string?, xs:untypedAtomic?, or xs:anyURI?
-
process
public void process(Outputter output, XPathContext context) throws XPathException
Process the instruction, without returning any tail calls- Parameters:
output
- the destination for the resultcontext
- 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- Parameters:
context
- the XPath dynamic evaluation contextpul
- the pending update list to which the results should be written- Throws:
XPathException
- if evaluation failsjava.lang.UnsupportedOperationException
- if the expression is not an updating expression
-
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.
For subclasses of Expression that represent XPath expressions, the result should always be a string that parses as an XPath 3.0 expression. The expression produced should be equivalent to the original making certain assumptions about the static context. In general the expansion will make no assumptions about namespace bindings, except that (a) the prefix "xs" is used to refer to the XML Schema namespace, and (b) the default function namespace is assumed to be the "fn" namespace.
In the case of XSLT instructions and XQuery expressions, the toString() method gives an abstracted view of the syntax that is not designed in general to be parseable.
- Overrides:
toString
in classjava.lang.Object
- Returns:
- a representation of the expression as a string
-
toShortString
public java.lang.String toShortString()
Produce a short string identifying the expression for use in error messages- Returns:
- a short string, sufficient to identify the expression
-
export
public abstract 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 interfaceExportAgent
- 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.
-
explain
public final void explain(Logger out)
Diagnostic print of expression structure. The abstract expression tree is written to the supplied outputstream.- Parameters:
out
- the expression presenter used to display the structure
-
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.- 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 typewhole
- 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
-
adoptChildExpression
public void adoptChildExpression(Expression child)
Set up a parent-child relationship between this expression and a given child expression.Note: many calls on this method are now redundant, but are kept in place for "belt-and-braces" reasons. The rule is that an implementation of simplify(), typeCheck(), or optimize() that returns a value other than "this" is required to set the location information and parent pointer in the new child expression. However, in the past this was often left to the caller, which did it by calling this method, either unconditionally on return from one of these methods, or after testing that the returned object was not the same as the original.
- Parameters:
child
- the child expression
-
setLocation
public void setLocation(Location id)
Set the location on an expression.- Parameters:
id
- the location
-
getLocation
public final Location getLocation()
Get the location of the expression- Specified by:
getLocation
in interfaceLocatable
- Returns:
- a location identifier, which can be turned into real location information by reference to a location provider
-
getConfiguration
public Configuration getConfiguration()
Get the configuration containing this expression- Returns:
- the containing Configuration
-
getPackageData
public PackageData getPackageData()
Get information about the containing package- Returns:
- package data
-
isInstruction
public boolean isInstruction()
Ask whether this expression is an instruction. In XSLT streamability analysis this is used to distinguish constructs corresponding to XSLT instructions from other constructs, typically XPath expressions (but also things like attribute constructors on a literal result element, references to attribute sets, etc. However, an XPath expression within a text value template in a text node of an XSLT stylesheet is treated as an instruction. In a non-XSLT environment (such as XQuery) this property has no meaning and its setting is undefined.- Returns:
- true if this construct originates as an XSLT instruction
-
computeStaticProperties
public final void computeStaticProperties()
Compute the static properties. This should only be done once for each expression.
-
resetLocalStaticProperties
public void resetLocalStaticProperties()
Reset the static properties of the expression to -1, so that they have to be recomputed next time they are used.
-
isStaticPropertiesKnown
public boolean isStaticPropertiesKnown()
Ask whether the static properties of the expression have been computed- Returns:
- true if the static properties have been computed
-
computeCardinality
protected abstract int computeCardinality()
Compute the static cardinality of this 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 returnStaticProperty.ALLOWS_ZERO
if the result is known to be an empty sequence, orStaticProperty.ALLOWS_MANY
if if is known to return a sequence of length two or more.
-
computeSpecialProperties
protected int computeSpecialProperties()
Compute the special properties of this expression. These properties are denoted by a bit-significant integer, possible values are in classStaticProperty
. The "special" properties are properties other than cardinality and dependencies, and most of them relate to properties of node sequences, for example whether the nodes are in document order.- Returns:
- the special properties, as a bit-significant integer
-
computeDependencies
public int computeDependencies()
Compute the dependencies of an expression, as the union of the dependencies of its subexpressions. (This is overridden for path expressions and filter expressions, where the dependencies of a subexpression are not all propogated). This method should be called only once, to compute the dependencies; after that, getDependencies should be used.- Returns:
- the depencies, as a bit-mask
-
getIntrinsicDependencies
public int getIntrinsicDependencies()
Determine the intrinsic dependencies of an expression, that is, those which are not derived from the dependencies of its subexpressions. For example, position() has an intrinsic dependency on the context position, while (position()+1) does not. The default implementation of the method returns 0, indicating "no dependencies".- Returns:
- a set of bit-significant flags identifying the "intrinsic" dependencies. The flags are documented in class net.sf.saxon.value.StaticProperty
-
setStaticProperty
public void setStaticProperty(int prop)
Set a static property on an expression. Used when inlining functions to retain properties of the inlined function (though this is only partially successful because the properties can be recomputed later- Parameters:
prop
- the property to be set
-
checkForUpdatingSubexpressions
public void checkForUpdatingSubexpressions() throws XPathException
Check to ensure that this expression does not contain any inappropriate updating subexpressions. This check is overridden for those expressions that permit updating subexpressions.- Throws:
XPathException
- if the expression has a non-permitted updating subexpression
-
isUpdatingExpression
public boolean isUpdatingExpression()
Determine whether this is an updating expression as defined in the XQuery update specification- Returns:
- true if this is an updating expression
-
isVacuousExpression
public boolean isVacuousExpression()
Determine whether this is a vacuous expression as defined in the XQuery update specification- Returns:
- true if this expression is vacuous
-
copy
public abstract Expression copy(RebindingMap rebindings)
Copy an expression. This makes a deep copy.- 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
-
suppressValidation
public void suppressValidation(int parentValidationMode)
Suppress validation on contained element constructors, on the grounds that the parent element is already performing validation. The default implementation does nothing.- Parameters:
parentValidationMode
- the kind of validation being performed on the parent expression
-
markTailFunctionCalls
public int markTailFunctionCalls(StructuredQName qName, int arity)
Mark tail-recursive calls on stylesheet functions. For most expressions, this does nothing.- Parameters:
qName
- the name of the functionarity
- 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.
-
toPattern
public Pattern toPattern(Configuration config) throws XPathException
Convert this expression to an equivalent XSLT pattern- Parameters:
config
- the Saxon configuration- Returns:
- the equivalent pattern
- Throws:
XPathException
- if conversion is not possible
-
getSlotsUsed
public final int[] getSlotsUsed()
Get the local variables (identified by their slot numbers) on which this expression depends. Should only be called if the caller has established that there is a dependency on local variables.- Returns:
- an array of integers giving the slot numbers of the local variables referenced in this expression.
-
dynamicError
protected void dynamicError(java.lang.String message, java.lang.String code, XPathContext context) throws XPathException
Method used in subclasses to signal a dynamic error- Parameters:
message
- the error messagecode
- the error codecontext
- the XPath dynamic context- Throws:
XPathException
- always thrown, to signal a dynamic error
-
typeError
protected void typeError(java.lang.String message, java.lang.String errorCode, XPathContext context) throws XPathException
Method used in subclasses to signal a runtime type error- Parameters:
message
- the error messageerrorCode
- the error codecontext
- the XPath dynamic context- Throws:
XPathException
- always thrown, to signal a dynamic error
-
getTracingTag
public java.lang.String getTracingTag()
-
getObjectName
public StructuredQName getObjectName()
Description copied from interface:Traceable
Get a name identifying the object of the expression, for example a function name, template name, variable name, key name, element name, etc. This is used only where the name is known statically.- Specified by:
getObjectName
in interfaceTraceable
- Returns:
- the QName of the object declared or manipulated by this instruction or expression
-
getProperty
public java.lang.Object getProperty(java.lang.String name)
-
getProperties
public java.util.Iterator<java.lang.String> getProperties()
Get an iterator over all the properties available. The values returned by the iterator will be of type String, and each string can be supplied as input to the getProperty() method to retrieve the value of the property. The iterator may return properties whose value is null.- Returns:
- an iterator over the properties
-
addToPathMap
public PathMap.PathMapNodeSet addToPathMap(PathMap pathMap, PathMap.PathMapNodeSet pathMapNodeSet)
Add a representation of this expression to a PathMap. The PathMap captures a map of the nodes visited by an expression in a source tree.The default implementation of this method assumes that an expression does no navigation other than the navigation done by evaluating its subexpressions, and that the subexpressions are evaluated in the same context as the containing expression. The method must be overridden for any expression where these assumptions do not hold. For example, implementations exist for AxisExpression, ParentExpression, and RootExpression (because they perform navigation), and for the doc(), document(), and collection() functions because they create a new navigation root. Implementations also exist for PathExpression and FilterExpression because they have subexpressions that are evaluated in a different context from the calling expression.
- Parameters:
pathMap
- the PathMap to which the expression should be addedpathMapNodeSet
- the PathMapNodeSet to which the paths embodied in this expression should be added- Returns:
- the pathMapNodeSet representing the points in the source document that are both reachable by this expression, and that represent possible results of this expression. For an expression that does navigation, it represents the end of the arc in the path map that describes the navigation route. For other expressions, it is the same as the input pathMapNode.
-
isSubtreeExpression
public boolean isSubtreeExpression()
Determine whether the expression can be evaluated without reference to the part of the context document outside the subtree rooted at the context node.- Returns:
- true if the expression has no dependencies on the context node, or if the only dependencies on the context node are downward selections using the self, child, descendant, attribute, and namespace axes.
-
setEvaluationMethod
public void setEvaluationMethod(int method)
-
getEvaluationMethod
public int getEvaluationMethod()
-
equals
public boolean equals(java.lang.Object obj)
The equals() test for expressions returns true if it can be determined that two expressions (given their static context) will return the same result in all circumstances. The value false is returned if this is not the case or if it cannot be determined to be the case.During the various phases of compilation, expression objects are mutable. Changing an expression may change its hashCode, and may change the result of equals() comparisons. Expressions should therefore not be held in data structures such as maps and sets that depend on equality comparison unless they are no longer subject to such mutation.
- Overrides:
equals
in classjava.lang.Object
- Parameters:
obj
- the other operand; the result is false if this is not an Expression- Returns:
- true if the other operand is an expression and if it can be determined that the two expressions are equivalent, in the sense that they will always return the same result.
-
isEqual
public final boolean isEqual(Expression other)
Test if this is expression is equivalent to another. This method first compares the hash codes, allowing a quick exit if the expressions are not equal (except that computing the hash code may itself be expensive...).- Parameters:
other
- the other expression- Returns:
- true if the two expressions are equal in the sense of the equals() method
-
hashCode
public final int hashCode()
The hashCode() for an expression has semantics corresponding to equals(). Because computing a hashCode may be expensive, it is computed lazily on first reference and saved with the expression.- Overrides:
hashCode
in classjava.lang.Object
- Returns:
- a hashCode which is the same for two expressions that are equal().
-
hasCompatibleStaticContext
protected boolean hasCompatibleStaticContext(Expression other)
Ask whether the static context of this expression is compatible with the static context of another expression. The static contexts are considered compatible if either (a) neither expression depends on the static context, or (b) both expressions depend on the static context and the two static contexts compare equal.- Parameters:
other
- the other expression- Returns:
- true if the two expressions have equivalent static contexts
-
computeHashCode
protected int computeHashCode()
Compute a hash code, which will then be cached for later use- Returns:
- a computed hash code
-
isIdentical
public boolean isIdentical(IdentityComparable other)
Determine whether two IdentityComparable objects are identical. This is a stronger test than equality (even schema-equality); for example two dateTime values are not identical unless they are in the same timezone. In the case of expressions, we test object identity, since the normal equality test ignores the location of the expression.- Specified by:
isIdentical
in interfaceIdentityComparable
- Parameters:
other
- the value to be compared with- Returns:
- true if the two values are indentical, false otherwise
-
identityHashCode
public int identityHashCode()
Get a hashCode that offers the guarantee that if A.isIdentical(B), then A.identityHashCode() == B.identityHashCode()- Specified by:
identityHashCode
in interfaceIdentityComparable
- Returns:
- a hashCode suitable for use when testing for identity.
-
setExtraProperty
public void setExtraProperty(java.lang.String name, java.lang.Object value)
Set an extra property on the expression. (Used for Saxon-EE properties, e.g. properties relating to streaming).- Parameters:
name
- the name of the propertyvalue
- the value of the property, or null to remove the property
-
getExtraProperty
public java.lang.Object getExtraProperty(java.lang.String name)
Get the value of an extra property on the expression- Parameters:
name
- the name of the property- Returns:
- the value of the property if set, or null otherwise
-
getStreamerName
public java.lang.String getStreamerName()
Get the (partial) name of a class that supports streaming of this kind of 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
-
-