net.sf.saxon.expr.instruct.Choose Maven / Gradle / Ivy
Show all versions of Saxon-HE Show documentation
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2015 Saxonica Limited.
// This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
// This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
package net.sf.saxon.expr.instruct;
import net.sf.saxon.evpull.EmptyEventIterator;
import net.sf.saxon.evpull.EventIterator;
import net.sf.saxon.expr.*;
import net.sf.saxon.expr.parser.*;
import net.sf.saxon.functions.BooleanFn;
import net.sf.saxon.functions.SystemFunction;
import net.sf.saxon.om.Item;
import net.sf.saxon.om.SequenceIterator;
import net.sf.saxon.om.StandardNames;
import net.sf.saxon.om.StructuredQName;
import net.sf.saxon.trace.ExpressionPresenter;
import net.sf.saxon.trans.XPathException;
import net.sf.saxon.tree.iter.EmptyIterator;
import net.sf.saxon.tree.util.FastStringBuffer;
import net.sf.saxon.type.*;
import net.sf.saxon.value.BooleanValue;
import net.sf.saxon.value.Cardinality;
import net.sf.saxon.value.SequenceType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* Compiled representation of an xsl:choose or xsl:if element in the stylesheet.
* Also used for typeswitch in XQuery.
*/
public class Choose extends Instruction {
private Operand[] conditionOps;
private Operand[] actionOps;
// The class implements both xsl:choose and xsl:if. There is a list of boolean
// expressions (conditions) and a list of corresponding actions: the conditions
// are evaluated in turn, and when one is found that is true, the corresponding
// action is evaluated. For xsl:if, there is always one condition and one action.
// An xsl:otherwise is compiled as if it were xsl:when test="true()". If no
// condition is satisfied, the instruction returns an empty sequence.
private final static OperandRole CHOICE_ACTION =
new OperandRole(OperandRole.IN_CHOICE_GROUP, OperandUsage.TRANSMISSION, SequenceType.ANY_SEQUENCE);
/**
* Construct an xsl:choose instruction
*
* @param conditions the conditions to be tested, in order
* @param actions the actions to be taken when the corresponding condition is true
*/
public Choose(Expression[] conditions, Expression[] actions) {
conditionOps = new Operand[conditions.length];
for (int i=0; i conditions() {
return Arrays.asList(conditionOps);
}
/**
* Get i'th action operand
* @param i the action number
* @return the i'th action to be evaluated when the corresponding condition is true
*/
public Operand getActionOperand(int i) {
return actionOps[i];
}
/**
* Get i'th action to be performed
*
* @param i the action number
* @return the i'th action to be evaluated when the corresponding condition is true
*/
public Expression getAction(int i) {
return actionOps[i].getChildExpression();
}
public void setAction(int i, Expression action) {
actionOps[i].setChildExpression(action);
}
public Iterable actions() {
return Arrays.asList(actionOps);
}
@Override
public Iterable operands() {
List operanda = new ArrayList(size()*2);
for (int i=0; i conditions = new ArrayList(size);
List actions = new ArrayList(size);
for (int i = 0; i < size; i++) {
Expression condition = getCondition(i);
if (!Literal.isConstantBoolean(condition, false)) {
conditions.add(condition);
actions.add(getAction(i));
}
if (Literal.isConstantBoolean(condition, true)) {
break;
}
}
if (conditions.isEmpty()) {
Literal lit = Literal.makeEmptySequence();
ExpressionTool.copyLocationInfo(this, lit);
return lit;
} else if (conditions.size() == 1 && Literal.isConstantBoolean(conditions.get(0), true)) {
return actions.get(0);
} else {
Expression[] c = conditions.toArray(new Expression[conditions.size()]);
Expression[] a = actions.toArray(new Expression[actions.size()]);
Choose result = new Choose(c, a);
result.setRetainedStaticContext(getRetainedStaticContext());
return result;
}
}
// See if only condition left is: if (true) then x else ()
if (size() == 1 && Literal.isConstantBoolean(getCondition(0), true)) {
return getAction(0);
}
// Eliminate a redundant or "when (test) then ()"
if (Literal.isEmptySequence(getAction(size() - 1))) {
if (size() == 1) {
return Literal.makeEmptySequence();
} else {
Expression[] conditions = new Expression[size-1];
Expression[] actions = new Expression[size-1];
for (int i = 0; i < size-1; i++) {
conditions[i] = getCondition(i);
actions[i] = getAction(i);
}
return new Choose(conditions, actions);
}
}
// Flatten an "else if"
if (Literal.isConstantBoolean(getCondition(size - 1), true) &&
getAction(size - 1) instanceof Choose) {
Choose choose2 = (Choose) getAction(size - 1);
int newLen = size + choose2.size() - 1;
Expression[] c2 = new Expression[newLen];
Expression[] a2 = new Expression[newLen];
for (int i=0; i
* 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.
*
* @param pathMap the PathMap to which the expression should be added
* @param pathMapNodeSet the set of PathMap nodes to which the paths from this expression should be appended
* @return the pathMapNode representing the focus established by this expression, in the case where this
* expression is the first operand of a path expression or filter 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.
*/
public PathMap.PathMapNodeSet addToPathMap(PathMap pathMap, PathMap.PathMapNodeSet pathMapNodeSet) {
// expressions used in a condition contribute paths, but these do not contribute to the result
for (Operand condition : conditions()) {
condition.getChildExpression().addToPathMap(pathMap, pathMapNodeSet);
}
PathMap.PathMapNodeSet result = new PathMap.PathMapNodeSet();
for (Operand action : actions()) {
PathMap.PathMapNodeSet temp = action.getChildExpression().addToPathMap(pathMap, pathMapNodeSet);
result.addNodeSet(temp);
}
return result;
}
/**
* 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
*
* @return a representation of the expression as a string
*/
public String toString() {
FastStringBuffer sb = new FastStringBuffer(FastStringBuffer.C64);
sb.append("if (");
for (int i = 0; i < size(); i++) {
sb.append(getCondition(i).toString());
sb.append(") then (");
sb.append(getAction(i).toString());
if (i == size() - 1) {
sb.append(")");
} else {
sb.append(") else if (");
}
}
return sb.toString();
}
@Override
public String toShortString() {
return "if(" + getCondition(0).toShortString() + ") then ... else ...";
}
/**
* Diagnostic print of expression structure. The abstract expression tree
* is written to the supplied output destination.
*/
public void export(ExpressionPresenter out) throws XPathException {
out.startElement("choose", this);
for (int i = 0; i < size(); i++) {
getCondition(i).export(out);
getAction(i).export(out);
}
out.endElement();
}
/**
* Process this instruction, that is, choose an xsl:when or xsl:otherwise child
* and process it.
*
* @param context the dynamic context of this transformation
* @return a TailCall, if the chosen branch ends with a call of call-template or
* apply-templates. It is the caller's responsibility to execute such a TailCall.
* If there is no TailCall, returns null.
* @throws XPathException if any non-recoverable dynamic error occurs
*/
public TailCall processLeavingTail(XPathContext context) throws XPathException {
int i = choose(context);
if (i >= 0) {
if (getAction(i) instanceof TailCallReturner) {
return ((TailCallReturner) getAction(i)).processLeavingTail(context);
} else {
getAction(i).process(context);
return null;
}
}
return null;
}
/**
* Identify which of the choices to take
* @param context the dynamic context
* @return integer the index of the first choice that matches, zero-based; or -1 if none of the choices
* matches
* @throws XPathException if evaluating a condition fails
*/
private int choose(XPathContext context) throws XPathException {
int size = size();
for (int i = 0; i < size; i++) {
final boolean b;
try {
b = getCondition(i).effectiveBooleanValue(context);
} catch (XPathException e) {
e.maybeSetLocation(getCondition(i).getLocation());
throw e;
}
if (b) {
return i;
}
}
return -1;
}
/**
* 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.
*
* @param context The context in which the expression is to be evaluated
* @return 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
*/
public Item evaluateItem(XPathContext context) throws XPathException {
int i = choose(context);
return i < 0 ? null : getAction(i).evaluateItem(context);
}
/**
* 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 relies on the process() method: it
* "pushes" the results of the instruction to a sequence in memory, and then
* iterates over this in-memory sequence.
*
* In principle instructions should implement a pipelined iterate() method that
* avoids the overhead of intermediate storage.
*
* @param context supplies the context for evaluation
* @return a SequenceIterator that can be used to iterate over the result
* of the expression
* @throws XPathException if any dynamic error occurs evaluating the
* expression
*/
/*@NotNull*/
public SequenceIterator iterate(XPathContext context) throws XPathException {
int i = choose(context);
return i < 0 ? EmptyIterator.emptyIterator() : getAction(i).iterate(context);
}
/**
* Deliver the result of the expression as a sequence of events.
*
* The events (of class {@link net.sf.saxon.evpull.PullEvent}) are either complete
* items, or one of startElement, endElement, startDocument, or endDocument, known
* as semi-nodes. The stream of events may also include a nested EventIterator.
* If a start-end pair exists in the sequence, then the events between
* this pair represent the content of the document or element. The content sequence will
* have been processed to the extent that any attribute and namespace nodes in the
* content sequence will have been merged into the startElement event. Namespace fixup
* will have been performed: that is, unique prefixes will have been allocated to element
* and attribute nodes, and all namespaces will be declared by means of a namespace node
* in the startElement event or in an outer startElement forming part of the sequence.
* However, duplicate namespaces may appear in the sequence.
* The content of an element or document may include adjacent or zero-length text nodes,
* atomic values, and nodes represented as nodes rather than broken down into events.
*
* @param context The dynamic evaluation context
* @return the result of the expression as an iterator over a sequence of PullEvent objects
* @throws net.sf.saxon.trans.XPathException
* if a dynamic error occurs during expression evaluation
*/
public EventIterator iterateEvents(XPathContext context) throws XPathException {
int i = choose(context);
return i < 0 ? EmptyEventIterator.getInstance() : getAction(i).iterateEvents(context);
}
/**
* 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
*
* @param context the XPath dynamic evaluation context
* @param pul the pending update list to which the results should be written
*/
public void evaluatePendingUpdates(XPathContext context, PendingUpdateList pul) throws XPathException {
int i = choose(context);
if (i >= 0) {
getAction(i).evaluatePendingUpdates(context, pul);
}
}
}