Debian Codegraph @

net/sf/saxon/expr/instruct/Choose.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.expr.instruct;
9
10 import net.sf.saxon.expr.*;
11 import net.sf.saxon.expr.parser.*;
12 import net.sf.saxon.functions.BooleanFn;
13 import net.sf.saxon.functions.SystemFunction;
14 import net.sf.saxon.om.Item;
15 import net.sf.saxon.om.SequenceIterator;
16 import net.sf.saxon.om.StandardNames;
17 import net.sf.saxon.om.StructuredQName;
18 import net.sf.saxon.trace.ExpressionPresenter;
19 import net.sf.saxon.trans.XPathException;
20 import net.sf.saxon.tree.iter.EmptyIterator;
21 import net.sf.saxon.tree.util.FastStringBuffer;
22 import net.sf.saxon.type.*;
23 import net.sf.saxon.value.BooleanValue;
24 import net.sf.saxon.value.Cardinality;
25 import net.sf.saxon.value.SequenceType;
26
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.List;
30
31
32 /**
33 * Compiled representation of an xsl:choose or xsl:if element in the stylesheet.
34 * Also used for typeswitch in XQuery.
35 */
36
37 public class Choose extends Instruction implements ConditionalInstruction {
38
39 private Operand[] conditionOps;
40 private Operand[] actionOps;
41 private boolean isInstruction;
42
43
44 // The class implements both xsl:choose and xsl:if. There is a list of boolean
45 // expressions (conditions) and a list of corresponding actions: the conditions
46 // are evaluated in turn, and when one is found that is true, the corresponding
47 // action is evaluated. For xsl:if, there is always one condition and one action.
48 // An xsl:otherwise is compiled as if it were xsl:when test="true()". If no
49 // condition is satisfied, the instruction returns an empty sequence.
50
51
52
53 public final static OperandRole CHOICE_ACTION =
54 new OperandRole(OperandRole.IN_CHOICE_GROUP, OperandUsage.TRANSMISSION, SequenceType.ANY_SEQUENCE);
55
56
57 /**
58 * Construct an xsl:choose instruction
59 *
60 * @param conditions the conditions to be tested, in order
61 * @param actions the actions to be taken when the corresponding condition is true
62 */
63
64 public Choose(Expression[] conditions, Expression[] actions) {
65 conditionOps = new Operand[conditions.length];
66 for (int i=0; i<conditions.length; i++) {
67 conditionOps[i] = new Operand(this, conditions[i], OperandRole.INSPECT);
68 }
69 actionOps = new Operand[actions.length];
70 for (int i=0; i<actions.length; i++) {
71 actionOps[i] = new Operand(this, actions[i], CHOICE_ACTION);
72 }
73 }
74
75 /**
76 * Make a simple conditional expression (if (condition) then (thenExp) else (elseExp)
77 *
78 * @param condition the condition to be tested
79 * @param thenExp the expression to be evaluated if the condition is true
80 * @param elseExp the expression to be evaluated if the condition is false
81 * @return the expression
82 */
83
84 public static Expression makeConditional(Expression condition, Expression thenExp, Expression elseExp) {
85 if (Literal.isEmptySequence(elseExp)) {
86 Expression[] conditions = new Expression[]{condition};
87 Expression[] actions = new Expression[]{thenExp};
88 return new Choose(conditions, actions);
89 } else {
90 Expression[] conditions = new Expression[]{condition, Literal.makeLiteral(BooleanValue.TRUE, condition)};
91 Expression[] actions = new Expression[]{thenExp, elseExp};
92 return new Choose(conditions, actions);
93 }
94 }
95
96 /**
97 * Make a simple conditional expression (if (condition) then (thenExp) else ()
98 *
99 * @param condition the condition to be tested
100 * @param thenExp the expression to be evaluated if the condition is true
101 * @return the expression
102 */
103
104 public static Expression makeConditional(Expression condition, Expression thenExp) {
105 Expression[] conditions = new Expression[]{condition};
106 Expression[] actions = new Expression[]{thenExp};
107 return new Choose(conditions, actions);
108 }
109
110 /**
111 * Say whether this choose expression originates as an XSLT instruction
112 *
113 * @param inst true if this is an xsl:choose or xsl:if instruction
114 */
115
116 public void setInstruction(boolean inst) {
117 isInstruction = inst;
118 }
119
120 /**
121 * Ask whether this expression is an instruction. In XSLT streamability analysis this
122 * is used to distinguish constructs corresponding to XSLT instructions from other constructs.
123 *
124 * @return true if this construct originates as an XSLT instruction
125 */
126
127 @Override
128 public boolean isInstruction() {
129 return isInstruction;
130 }
131
132
133 public int size() {
134 return conditionOps.length;
135 }
136
137 /**
138 * Test whether an expression is a single-branch choose, that is, an expression of the form
139 * if (condition) then exp else ()
140 *
141 * @param exp the expression to be tested
142 * @return true if the expression is a choose expression and there is only one condition,
143 * so that the expression returns () if this condition is false
144 */
145
146 public static boolean isSingleBranchChoice(Expression exp) {
147 return exp instanceof Choose && ((Choose) exp).size() == 1;
148 }
149
150 public int getNumberOfConditions() {
151 return size();
152 }
153
154 public Expression getCondition(int i) {
155 return conditionOps[i].getChildExpression();
156 }
157
158 public void setCondition(int i, Expression condition) {
159 conditionOps[i].setChildExpression(condition);
160 }
161
162 public Iterable<Operand> conditions() {
163 return Arrays.asList(conditionOps);
164 }
165
166 /**
167 * Get i'th action operand
168 * @param i the action number
169 * @return the i'th action to be evaluated when the corresponding condition is true
170 */
171
172 public Operand getActionOperand(int i) {
173 return actionOps[i];
174 }
175
176 /**
177 * Get i'th action to be performed
178 *
179 * @param i the action number
180 * @return the i'th action to be evaluated when the corresponding condition is true
181 */
182
183 public Expression getAction(int i) {
184 return actionOps[i].getChildExpression();
185 }
186
187 public void setAction(int i, Expression action) {
188 actionOps[i].setChildExpression(action);
189 }
190
191 public Iterable<Operand> actions() {
192 return Arrays.asList(actionOps);
193 }
194
195 @Override
196 public Iterable<Operand> operands() {
197 List<Operand> operanda = new ArrayList<Operand>(size()*2);
198 for (int i=0; i<size(); i++) {
199 operanda.add(conditionOps[i]);
200 operanda.add(actionOps[i]);
201 }
202 return operanda;
203 }
204
205 /**
206 * Ask whether common subexpressions found in the operands of this expression can
207 * be extracted and evaluated outside the expression itself. The result is irrelevant
208 * in the case of operands evaluated with a different focus, which will never be
209 * extracted in this way, even if they have no focus dependency.
210 *
211 * @return false for this kind of expression
212 */
213 @Override
214 public boolean allowExtractingCommonSubexpressions() {
215 return false;
216 }
217
218 /**
219 * Atomize all the action expressions
220 */
221
222 public void atomizeActions() {
223 for (int i=0; i<size(); i++) {
224 setAction(i, Atomizer.makeAtomizer(getAction(i), null));
225 }
226 }
227
228 /**
229 * Get the name of this instruction for diagnostic and tracing purposes
230 * We assume that if there was
231 * only one condition then it was an xsl:if; this is not necessarily so, but
232 * it's adequate for tracing purposes.
233 */
234
235
236 public int getInstructionNameCode() {
237 return size() == 1 ? StandardNames.XSL_IF : StandardNames.XSL_CHOOSE;
238 }
239
240 /**
241 * Simplify an expression. This performs any static optimization (by rewriting the expression
242 * as a different expression).
243 *
244 *
245 *
246 * @throws XPathException if an error is discovered during expression
247 * rewriting
248 */
249
250 /*@NotNull*/
251 public Expression simplify() throws XPathException {
252 for (int i = 0; i < size(); i++) {
253 setCondition(i, getCondition(i).simplify());
254 try {
255 setAction(i, getAction(i).simplify());
256 } catch (XPathException err) {
257 // mustn't throw the error unless the branch is actually selected, unless its a type error
258 if (err.isTypeError()) {
259 throw err;
260 } else {
261 setAction(i, new ErrorExpression(err));
262 }
263 }
264 }
265 return this;
266 }
267
268 private Expression removeRedundantBranches(ExpressionVisitor visitor) {
269 Expression result = removeRedundantBranches0(visitor);
270 if (result != this) {
271 ExpressionTool.copyLocationInfo(this, result);
272 }
273 return result;
274 }
275
276 private Expression removeRedundantBranches0(ExpressionVisitor visitor) {
277 // Eliminate a redundant if (false)
278
279 boolean compress = false;
280 for (int i = 0; i < size(); i++) {
281 Expression condition = getCondition(i);
282 if (condition instanceof Literal) {
283 compress = true;
284 break;
285 }
286 }
287 int size = size();
288 boolean changed = false;
289 if (compress) {
290 List<Expression> conditions = new ArrayList<Expression>(size);
291 List<Expression> actions = new ArrayList<Expression>(size);
292 for (int i = 0; i < size; i++) {
293 Expression condition = getCondition(i);
294 if (!Literal.hasEffectiveBooleanValue(condition, false)) {
295 conditions.add(condition);
296 actions.add(getAction(i));
297 }
298 if (Literal.hasEffectiveBooleanValue(condition, true)) {
299 break;
300 }
301 }
302 if (conditions.isEmpty()) {
303 Literal lit = Literal.makeEmptySequence();
304 ExpressionTool.copyLocationInfo(this, lit);
305 return lit;
306 } else if (conditions.size() == 1 && Literal.hasEffectiveBooleanValue(conditions.get(0), true)) {
307 return actions.get(0);
308 } else if (conditions.size() != size) {
309 Expression[] c = conditions.toArray(new Expression[conditions.size()]);
310 Expression[] a = actions.toArray(new Expression[actions.size()]);
311 Choose result = new Choose(c, a);
312 result.setRetainedStaticContext(getRetainedStaticContext());
313 return result;
314 }
315 }
316
317 // See if only condition left is: if (true) then x else ()
318
319 if (size() == 1 && Literal.hasEffectiveBooleanValue(getCondition(0), true)) {
320 return getAction(0);
321 }
322
323 // Eliminate a redundant <xsl:otherwise/> or "when (test) then ()"
324
325 if (Literal.isEmptySequence(getAction(size() - 1))) {
326 if (size() == 1) {
327 Literal lit = Literal.makeEmptySequence();
328 ExpressionTool.copyLocationInfo(this, lit);
329 return lit;
330 } else {
331 Expression[] conditions = new Expression[size-1];
332 Expression[] actions = new Expression[size-1];
333 for (int i = 0; i < size-1; i++) {
334 conditions[i] = getCondition(i);
335 actions[i] = getAction(i);
336 }
337 return new Choose(conditions, actions);
338 }
339 }
340
341 // Flatten an "else if"
342
343 if (Literal.hasEffectiveBooleanValue(getCondition(size - 1), true) &&
344 getAction(size - 1) instanceof Choose) {
345 Choose choose2 = (Choose) getAction(size - 1);
346 int newLen = size + choose2.size() - 1;
347 Expression[] c2 = new Expression[newLen];
348 Expression[] a2 = new Expression[newLen];
349 for (int i=0; i<size-1; i++) {
350 c2[i] = getCondition(i);
351 a2[i] = getAction(i);
352 }
353 for (int i=0; i<choose2.size(); i++) {
354 c2[i + size - 1] = choose2.getCondition(i);
355 a2[i + size - 1] = choose2.getAction(i);
356 }
357 return new Choose(c2, a2);
358 }
359
360 // Rewrite "if (EXP) then true() else false()" as boolean(EXP)
361
362 if (size == 2 &&
363 Literal.isConstantBoolean(getAction(0), true) &&
364 Literal.isConstantBoolean(getAction(1), false) &&
365 Literal.hasEffectiveBooleanValue(getCondition(1), true)) {
366 TypeHierarchy th = visitor.getConfiguration().getTypeHierarchy();
367 if (th.isSubType(getCondition(0).getItemType(), BuiltInAtomicType.BOOLEAN) &&
368 getCondition(0).getCardinality() == StaticProperty.EXACTLY_ONE) {
369 return getCondition(0);
370 } else {
371 return SystemFunction.makeCall("boolean", getRetainedStaticContext(), getCondition(0));
372 }
373 }
374 return this;
375 }
376
377 /*@NotNull*/
378 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
379 TypeHierarchy th = visitor.getConfiguration().getTypeHierarchy();
380 for (int i = 0; i < size(); i++) {
381 conditionOps[i].typeCheck(visitor, contextInfo);
382 XPathException err = TypeChecker.ebvError(getCondition(i), th);
383 if (err != null) {
384 err.setLocator(getCondition(i).getLocation());
385 err.maybeSetFailingExpression(getCondition(i));
386 throw err;
387 }
388 }
389 // Check that each of the action branches satisfies the expected type. This is a stronger check than checking the
390 // type of the top-level expression. It's important with tail recursion not to wrap a tail call in a type checking
391 // expression just because a dynamic type check is needed on a different branch of the choice.
392 for (int i = 0; i < size(); i++) {
393 try {
394 actionOps[i].typeCheck(visitor, contextInfo);
395 } catch (XPathException err) {
396 err.maybeSetLocation(getLocation());
397 err.maybeSetFailingExpression(getAction(i));
398 // mustn't throw the error unless the branch is actually selected, unless its a static or type error
399 if (err.isStaticError()) {
400 throw err;
401 } else if (err.isTypeError()) {
402 // if this is an "empty" else branch, don't be draconian about the error handling. It might be
403 // the user knows the otherwise branch isn't needed because one of the when branches will always
404 // be satisfied.
405 // Also, don't throw a type error if the branch will never be executed; this can happen with
406 // a typeswitch where the purpose of the condition is to test the type.
407 if (Literal.isEmptySequence(getAction(i)) || Literal.hasEffectiveBooleanValue(getCondition(i), false)) {
408 setAction(i, new ErrorExpression(err));
409 } else {
410 throw err;
411 }
412 } else {
413 setAction(i, new ErrorExpression(err));
414 }
415 }
416 }
417 Expression reduced = removeRedundantBranches(visitor);
418 if (reduced != this) {
419 return reduced.typeCheck(visitor, contextInfo);
420 }
421 return reduced;
422 }
423
424 /**
425 * Determine whether this expression implements its own method for static type checking
426 *
427 * @return true - this expression has a non-trivial implementation of the staticTypeCheck()
428 * method
429 */
430
431 public boolean implementsStaticTypeCheck() {
432 return true;
433 }
434
435 /**
436 * Static type checking for conditional expressions is delegated to the expression itself,
437 * and is performed separately on each branch of the conditional, so that dynamic checks are
438 * added only on those branches where the check is actually required. This also results in a static
439 * type error if any branch is incapable of delivering a value of the required type. One reason
440 * for this approach is to avoid doing dynamic type checking on a recursive function call as this
441 * prevents tail-call optimization being used.
442 *
443 *
444 * @param req the required type
445 * @param backwardsCompatible true if backwards compatibility mode applies
446 * @param role the role of the expression in relation to the required type
447 * @param visitor an expression visitor
448 * @return the expression after type checking (perhaps augmented with dynamic type checking code)
449 * @throws XPathException if failures occur, for example if the static type of one branch of the conditional
450 * is incompatible with the required type
451 */
452
453 public Expression staticTypeCheck(SequenceType req,
454 boolean backwardsCompatible,
455 RoleDiagnostic role, ExpressionVisitor visitor)
456 throws XPathException {
457 int size = size();
458 TypeChecker tc = getConfiguration().getTypeChecker(backwardsCompatible);
459 for (int i = 0; i < size; i++) {
460 try {
461 setAction(i, tc.staticTypeCheck(getAction(i), req, role, visitor));
462 } catch (XPathException err) {
463 if (err.isStaticError()) {
464 throw err;
465 }
466 // else if (err.isTypeError()) {
467 // visitor.issueWarning("Branch " + (i + 1) + " of conditional will fail with a type error if executed. "
468 // + err.getMessage(), getLocation());
469 // }
470 ErrorExpression ee = new ErrorExpression(err);
471 ExpressionTool.copyLocationInfo(getAction(i), ee);
472 setAction(i, ee);
473 }
474 }
475 // If the last condition isn't true(), then we need to consider the fall-through case, which returns
476 // an empty sequence
477 if (!Literal.hasEffectiveBooleanValue(getCondition(size - 1), true) &&
478 !Cardinality.allowsZero(req.getCardinality())) {
479 Expression[] c = new Expression[size + 1];
480 Expression[] a = new Expression[size + 1];
481 for (int i=0; i<size; i++) {
482 c[i] = getCondition(i);
483 a[i] = getAction(i);
484 }
485 c[size] = Literal.makeLiteral(BooleanValue.TRUE, this);
486 String cond = size == 1 ? "The condition is not" : "None of the conditions is";
487 String message =
488 "Conditional expression: " + cond + " satisfied, so an empty sequence is returned, " +
489 "but this is not allowed as the " + role.getMessage();
490 ErrorExpression errExp = new ErrorExpression(message, role.getErrorCode(), true);
491 ExpressionTool.copyLocationInfo(this, errExp);
492 a[size] = errExp;
493 return new Choose(c, a);
494 }
495 return this;
496 }
497
498 /*@NotNull*/
499 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType) throws XPathException {
500 int size = size();
501 for (int i = 0; i < size; i++) {
502 conditionOps[i].optimize(visitor, contextItemType);
503 Expression ebv = BooleanFn.rewriteEffectiveBooleanValue(getCondition(i), visitor, contextItemType);
504 if (ebv != null && ebv != getCondition(i)) {
505 setCondition(i, ebv);
506 }
507 if (getCondition(i) instanceof Literal &&
508 !(((Literal) getCondition(i)).getValue() instanceof BooleanValue)) {
509 final boolean b;
510 try {
511 b = ((Literal) getCondition(i)).getValue().effectiveBooleanValue();
512 } catch (XPathException err) {
513 err.setLocation(getLocation());
514 throw err;
515 }
516 setCondition(i, Literal.makeLiteral(BooleanValue.get(b), this));
517 }
518 }
519 for (int i = 0; i < size; i++) {
520 try {
521 actionOps[i].optimize(visitor, contextItemType);
522 } catch (XPathException err) {
523 // mustn't throw the error unless the branch is actually selected, unless its a type error
524 if (err.isTypeError()) {
525 throw err;
526 } else {
527 ErrorExpression ee = new ErrorExpression(err);
528 ExpressionTool.copyLocationInfo(actionOps[i].getChildExpression(), ee);
529 setAction(i, ee);
530 }
531 }
532 if (getAction(i) instanceof ErrorExpression &&
533 ((ErrorExpression)getAction(i)).isTypeError() &&
534 !Literal.isConstantBoolean(getCondition(i), false) &&
535 !Literal.isConstantBoolean(getCondition(i), true)) {
536 // Bug 3933: avoid the warning for an implicit xsl:otherwise branch (constant condition = true)
537 visitor.issueWarning("Branch " + (i + 1) + " of conditional will fail with a type error if executed. "
538 + ((ErrorExpression) getAction(i)).getMessage(), getAction(i).getLocation());
539 }
540 }
541
542 if (size == 0) {
543 return Literal.makeEmptySequence();
544 }
545 Expression e = removeRedundantBranches(visitor);
546 if (e instanceof Choose) {
547 return visitor.obtainOptimizer().trySwitch((Choose) e, visitor);
548 } else {
549 return e;
550 }
551 }
552
553 /**
554 * Copy an expression. This makes a deep copy.
555 *
556 * @return the copy of the original expression
557 * @param rebindings
558 */
559
560 /*@NotNull*/
561 public Expression copy(RebindingMap rebindings) {
562 int size = size();
563 Expression[] c2 = new Expression[size];
564 Expression[] a2 = new Expression[size];
565 for (int c = 0; c < size; c++) {
566 c2[c] = getCondition(c).copy(rebindings);
567 a2[c] = getAction(c).copy(rebindings);
568 }
569 Choose ch2 = new Choose(c2, a2);
570 ExpressionTool.copyLocationInfo(this, ch2);
571 ch2.setInstruction(isInstruction());
572 return ch2;
573 }
574
575
576 /**
577 * Check to ensure that this expression does not contain any updating subexpressions.
578 * This check is overridden for those expressions that permit updating subexpressions.
579 *
580 * @throws net.sf.saxon.trans.XPathException
581 * if the expression has a non-permitted updateing subexpression
582 */
583
584 public void checkForUpdatingSubexpressions() throws XPathException {
585 for (Operand o : conditions()) {
586 Expression condition = o.getChildExpression();
587 condition.checkForUpdatingSubexpressions();
588 if (condition.isUpdatingExpression()) {
589 XPathException err = new XPathException(
590 "Updating expression appears in a context where it is not permitted", "XUST0001");
591 err.setLocator(condition.getLocation());
592 throw err;
593 }
594 }
595 boolean updating = false;
596 boolean nonUpdating = false;
597 for (Operand o : actions()) {
598 Expression act = o.getChildExpression();
599 act.checkForUpdatingSubexpressions();
600 if (ExpressionTool.isNotAllowedInUpdatingContext(act)) {
601 if (updating) {
602 XPathException err = new XPathException(
603 "If any branch of a conditional is an updating expression, then all must be updating expressions (or vacuous)",
604 "XUST0001");
605 err.setLocator(act.getLocation());
606 throw err;
607 }
608 nonUpdating = true;
609 }
610 if (act.isUpdatingExpression()) {
611 if (nonUpdating) {
612 XPathException err = new XPathException(
613 "If any branch of a conditional is an updating expression, then all must be updating expressions (or vacuous)",
614 "XUST0001");
615 err.setLocator(act.getLocation());
616 throw err;
617 }
618 updating = true;
619 }
620 }
621 }
622
623 /**
624 * Determine whether this is an updating expression as defined in the XQuery update specification
625 *
626 * @return true if this is an updating expression
627 */
628
629 public boolean isUpdatingExpression() {
630 for (Operand o : actions()) {
631 if (o.getChildExpression().isUpdatingExpression()) {
632 return true;
633 }
634 }
635 return false;
636 }
637
638 /**
639 * Determine whether this is a vacuous expression as defined in the XQuery update specification
640 *
641 * @return true if this expression is vacuous
642 */
643
644 public boolean isVacuousExpression() {
645 // The Choose is vacuous if all branches are vacuous
646 for (Operand action : actions()) {
647 if (!action.getChildExpression().isVacuousExpression()) {
648 return false;
649 }
650 }
651 return true;
652 }
653
654 /**
655 * An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process().
656 * This method indicates which of these methods is prefered. For instructions this is the process() method.
657 */
658
659 public int getImplementationMethod() {
660 int m = Expression.PROCESS_METHOD | Expression.ITERATE_METHOD | Expression.WATCH_METHOD;
661 if (!Cardinality.allowsMany(getCardinality())) {
662 m |= Expression.EVALUATE_METHOD;
663 }
664 return m;
665 }
666
667 /**
668 * Mark tail-recursive calls on functions. For most expressions, this does nothing.
669 *
670 * @return 0 if no tail call was found; 1 if a tail call on a different function was found;
671 * 2 if a tail recursive call was found and if this call accounts for the whole of the value.
672 */
673
674 public int markTailFunctionCalls(StructuredQName qName, int arity) {
675 int result = UserFunctionCall.NOT_TAIL_CALL;
676 for (Operand action : actions()) {
677 result = Math.max(result, action.getChildExpression().markTailFunctionCalls(qName, arity));
678 }
679 return result;
680 }
681
682 /**
683 * Get the item type of the items returned by evaluating this instruction
684 *
685 * @return the static item type of the instruction
686 */
687
688 /*@NotNull*/
689 public ItemType getItemType() {
690 TypeHierarchy th = getConfiguration().getTypeHierarchy();
691 ItemType type = getAction(0).getItemType();
692 for (int i = 1; i < size(); i++) {
693 type = Type.getCommonSuperType(type, getAction(i).getItemType(), th);
694 }
695 return type;
696 }
697
698 /**
699 * Get the static type of the expression as a UType, following precisely the type
700 * inference rules defined in the XSLT 3.0 specification.
701 *
702 * @return the static item type of the expression according to the XSLT 3.0 defined rules
703 * @param contextItemType
704 */
705 @Override
706 public UType getStaticUType(UType contextItemType) {
707 if (isInstruction()) {
708 return super.getStaticUType(contextItemType);
709 } else {
710 UType type = getAction(0).getStaticUType(contextItemType);
711 for (int i = 1; i < size(); i++) {
712 type = type.union(getAction(i).getStaticUType(contextItemType));
713 }
714 return type;
715 }
716 }
717
718 /**
719 * Compute the cardinality of the sequence returned by evaluating this instruction
720 *
721 * @return the static cardinality
722 */
723
724 public int computeCardinality() {
725 int card = 0;
726 boolean includesTrue = false;
727 for (int i = 0; i < size(); i++) {
728 card = Cardinality.union(card, getAction(i).getCardinality());
729 if (Literal.hasEffectiveBooleanValue(getCondition(i), true)) {
730 includesTrue = true;
731 }
732 }
733 if (!includesTrue) {
734 // we may drop off the end and return an empty sequence (typical for xsl:if)
735 card = Cardinality.union(card, StaticProperty.ALLOWS_ZERO);
736 }
737 return card;
738 }
739
740 /**
741 * Get the static properties of this expression (other than its type). The result is
742 * bit-signficant. These properties are used for optimizations. In general, if
743 * property bit is set, it is true, but if it is unset, the value is unknown.
744 *
745 * @return a set of flags indicating static properties of this expression
746 */
747
748 public int computeSpecialProperties() {
749 // The special properties of a conditional are those which are common to every branch of the conditional
750 int props = getAction(0).getSpecialProperties();
751 for (int i = 1; i < size(); i++) {
752 props &= getAction(i).getSpecialProperties();
753 }
754 return props;
755 }
756
757 /**
758 * Determine whether this instruction creates new nodes.
759 * This implementation returns true if any of the "actions" creates new nodes.
760 * (Nodes created by the conditions can't contribute to the result).
761 */
762
763 public final boolean mayCreateNewNodes() {
764 for (Operand action : actions()) {
765 int props = action.getChildExpression().getSpecialProperties();
766 if ((props & StaticProperty.NO_NODES_NEWLY_CREATED) == 0) {
767 return true;
768 }
769 }
770 return false;
771 }
772
773 /**
774 * Replace this expression by a simpler expression that delivers the results without regard
775 * to order.
776 *
777 * @param retainAllNodes set to true if the result must contain exactly the same nodes as the
778 * original; set to false if the result can eliminate (or introduce) duplicates.
779 * @param forStreaming set to true if optimizing for streaming
780 */
781 @Override
782 public Expression unordered(boolean retainAllNodes, boolean forStreaming) throws XPathException {
783 for (int i = 0; i < size(); i++) {
784 setAction(i, getAction(i).unordered(retainAllNodes, forStreaming));
785 }
786 return this;
787 }
788
789 /**
790 * Check that any elements and attributes constructed or returned by this expression are acceptable
791 * in the content model of a given complex type. It's always OK to say yes, since the check will be
792 * repeated at run-time. The process of checking element and attribute constructors against the content
793 * model of a complex type also registers the type of content expected of those constructors, so the
794 * static validation can continue recursively.
795 */
796
797 public void checkPermittedContents(SchemaType parentType, boolean whole) throws XPathException {
798 for (Operand action : actions()) {
799 action.getChildExpression().checkPermittedContents(parentType, whole);
800 }
801 }
802
803
804 /**
805 * Add a representation of this expression to a PathMap. The PathMap captures a map of the nodes visited
806 * by an expression in a source tree.
807 * <p>The default implementation of this method assumes that an expression does no navigation other than
808 * the navigation done by evaluating its subexpressions, and that the subexpressions are evaluated in the
809 * same context as the containing expression. The method must be overridden for any expression
810 * where these assumptions do not hold. For example, implementations exist for AxisExpression, ParentExpression,
811 * and RootExpression (because they perform navigation), and for the doc(), document(), and collection()
812 * functions because they create a new navigation root. Implementations also exist for PathExpression and
813 * FilterExpression because they have subexpressions that are evaluated in a different context from the
814 * calling expression.</p>
815 *
816 * @param pathMap the PathMap to which the expression should be added
817 * @param pathMapNodeSet the set of PathMap nodes to which the paths from this expression should be appended
818 * @return the pathMapNode representing the focus established by this expression, in the case where this
819 * expression is the first operand of a path expression or filter expression. For an expression that does
820 * navigation, it represents the end of the arc in the path map that describes the navigation route. For other
821 * expressions, it is the same as the input pathMapNode.
822 */
823
824 public PathMap.PathMapNodeSet addToPathMap(PathMap pathMap, PathMap.PathMapNodeSet pathMapNodeSet) {
825 // expressions used in a condition contribute paths, but these do not contribute to the result
826 for (Operand condition : conditions()) {
827 condition.getChildExpression().addToPathMap(pathMap, pathMapNodeSet);
828 }
829 PathMap.PathMapNodeSet result = new PathMap.PathMapNodeSet();
830 for (Operand action : actions()) {
831 PathMap.PathMapNodeSet temp = action.getChildExpression().addToPathMap(pathMap, pathMapNodeSet);
832 result.addNodeSet(temp);
833 }
834 return result;
835 }
836
837 /**
838 * The toString() method for an expression attempts to give a representation of the expression
839 * in an XPath-like form, but there is no guarantee that the syntax will actually be true XPath.
840 * In the case of XSLT instructions, the toString() method gives an abstracted view of the syntax
841 *
842 * @return a representation of the expression as a string
843 */
844
845 public String toString() {
846 FastStringBuffer sb = new FastStringBuffer(FastStringBuffer.C64);
847 sb.append("if (");
848 for (int i = 0; i < size(); i++) {
849 sb.append(getCondition(i).toString());
850 sb.append(") then (");
851 sb.append(getAction(i).toString());
852 if (i == size() - 1) {
853 sb.append(")");
854 } else {
855 sb.append(") else if (");
856 }
857 }
858 return sb.toString();
859 }
860
861 @Override
862 public String toShortString() {
863 return "if(" + getCondition(0).toShortString() + ") then ... else ...";
864 }
865
866 /**
867 * Diagnostic print of expression structure. The abstract expression tree
868 * is written to the supplied output destination.
869 */
870
871 public void export(ExpressionPresenter out) throws XPathException {
872 out.startElement("choose", this);
873 for (int i = 0; i < size(); i++) {
874 getCondition(i).export(out);
875 getAction(i).export(out);
876 }
877 out.endElement();
878 }
879
880 /**
881 * Process this instruction, that is, choose an xsl:when or xsl:otherwise child
882 * and process it.
883 *
884 * @param context the dynamic context of this transformation
885 * @return a TailCall, if the chosen branch ends with a call of call-template or
886 * apply-templates. It is the caller's responsibility to execute such a TailCall.
887 * If there is no TailCall, returns null.
888 * @throws XPathException if any non-recoverable dynamic error occurs
889 */
890
891 public TailCall processLeavingTail(XPathContext context) throws XPathException {
892 int i = choose(context);
893 if (i >= 0) {
894 Expression action = getAction(i);
895 if (action instanceof TailCallReturner) {
896 return ((TailCallReturner) action).processLeavingTail(context);
897 } else {
898 action.process(context);
899 return null;
900 }
901 }
902 return null;
903 }
904
905 /**
906 * Identify which of the choices to take
907 * @param context the dynamic context
908 * @return integer the index of the first choice that matches, zero-based; or -1 if none of the choices
909 * matches
910 * @throws XPathException if evaluating a condition fails
911 */
912
913 private int choose(XPathContext context) throws XPathException {
914 int size = size();
915 for (int i = 0; i < size; i++) {
916 final boolean b;
917 try {
918 b = getCondition(i).effectiveBooleanValue(context);
919 } catch (XPathException e) {
920 e.maybeSetFailingExpression(getCondition(i));
921 throw e;
922 }
923 if (b) {
924 return i;
925 }
926 }
927 return -1;
928 }
929
930 /**
931 * Evaluate an expression as a single item. This always returns either a single Item or
932 * null (denoting the empty sequence). No conversion is done. This method should not be
933 * used unless the static type of the expression is a subtype of "item" or "item?": that is,
934 * it should not be called if the expression may return a sequence. There is no guarantee that
935 * this condition will be detected.
936 *
937 * @param context The context in which the expression is to be evaluated
938 * @return the node or atomic value that results from evaluating the
939 * expression; or null to indicate that the result is an empty
940 * sequence
941 * @throws XPathException if any dynamic error occurs evaluating the
942 * expression
943 */
944
945 public Item evaluateItem(XPathContext context) throws XPathException {
946 int i = choose(context);
947 return i < 0 ? null : getAction(i).evaluateItem(context);
948 }
949
950 /**
951 * Return an Iterator to iterate over the values of a sequence. The value of every
952 * expression can be regarded as a sequence, so this method is supported for all
953 * expressions. This default implementation relies on the process() method: it
954 * "pushes" the results of the instruction to a sequence in memory, and then
955 * iterates over this in-memory sequence.
956 * <p>In principle instructions should implement a pipelined iterate() method that
957 * avoids the overhead of intermediate storage.</p>
958 *
959 * @param context supplies the context for evaluation
960 * @return a SequenceIterator that can be used to iterate over the result
961 * of the expression
962 * @throws XPathException if any dynamic error occurs evaluating the
963 * expression
964 */
965
966 /*@NotNull*/
967 public SequenceIterator<?> iterate(XPathContext context) throws XPathException {
968 int i = choose(context);
969 return i < 0 ? EmptyIterator.emptyIterator() : getAction(i).iterate(context);
970 }
971
972
973 /**
974 * Evaluate an updating expression, adding the results to a Pending Update List.
975 * The default implementation of this method, which is used for non-updating expressions,
976 * throws an UnsupportedOperationException
977 *
978 * @param context the XPath dynamic evaluation context
979 * @param pul the pending update list to which the results should be written
980 */
981
982 public void evaluatePendingUpdates(XPathContext context, PendingUpdateList pul) throws XPathException {
983 int i = choose(context);
984 if (i >= 0) {
985 getAction(i).evaluatePendingUpdates(context, pul);
986 }
987 }
988
989 /**
990 * Get a name identifying the kind of expression, in terms meaningful to a user.
991 *
992 * @return a name identifying the kind of expression, in terms meaningful to a user.
993 * The name will always be in the form of a lexical XML QName, and should match the name used
994 * in explain() output displaying the expression.
995 */
996 @Override
997 public String getExpressionName() {
998 return "choose";
999 }
1000
1001 @Override
1002 public String getStreamerName() {
1003 return "Choose";
1004 }
1005 }
1006