//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2018 Saxonica Limited. // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// package net.sf.saxon.expr.instruct; 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; /** * Compiled representation of an xsl:choose or xsl:if element in the stylesheet. * Also used for typeswitch in XQuery. */ public class Choose extends Instruction implements ConditionalInstruction { private Operand[] conditionOps; private Operand[] actionOps; private boolean isInstruction; // 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. public 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.hasEffectiveBooleanValue(condition, false)) { conditions.add(condition); actions.add(getAction(i)); } if (Literal.hasEffectiveBooleanValue(condition, true)) { break; } } if (conditions.isEmpty()) { Literal lit = Literal.makeEmptySequence(); ExpressionTool.copyLocationInfo(this, lit); return lit; } else if (conditions.size() == 1 && Literal.hasEffectiveBooleanValue(conditions.get(0), true)) { return actions.get(0); } else if (conditions.size() != size) { 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.hasEffectiveBooleanValue(getCondition(0), true)) { return getAction(0); } // Eliminate a redundant or "when (test) then ()" if (Literal.isEmptySequence(getAction(size() - 1))) { if (size() == 1) { Literal lit = Literal.makeEmptySequence(); ExpressionTool.copyLocationInfo(this, lit); return lit; } 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.hasEffectiveBooleanValue(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; iThe 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) { Expression action = getAction(i); if (action instanceof TailCallReturner) { return ((TailCallReturner) action).processLeavingTail(context); } else { action.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.maybeSetFailingExpression(getCondition(i)); 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); } /** * 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); } } /** * Get a name identifying the kind of expression, in terms meaningful to a user. * * @return a name identifying the kind of expression, in terms meaningful to a user. * The name will always be in the form of a lexical XML QName, and should match the name used * in explain() output displaying the expression. */ @Override public String getExpressionName() { return "choose"; } @Override public String getStreamerName() { return "Choose"; } }