Debian Codegraph @

net/sf/saxon/expr/instruct/ConditionalBlock.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.event.SignificantItemDetector;
11 import net.sf.saxon.expr.*;
12 import net.sf.saxon.expr.parser.ContextItemStaticInfo;
13 import net.sf.saxon.expr.parser.ExpressionTool;
14 import net.sf.saxon.expr.parser.ExpressionVisitor;
15 import net.sf.saxon.expr.parser.RebindingMap;
16 import net.sf.saxon.om.Action;
17 import net.sf.saxon.om.AxisInfo;
18 import net.sf.saxon.trace.ExpressionPresenter;
19 import net.sf.saxon.trans.XPathException;
20 import net.sf.saxon.type.*;
21 import net.sf.saxon.value.Cardinality;
22
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.List;
26
27
28 /**
29 * An XSLT 3.0 sequence constructor containing xsl:on-empty and/or xsl:on-non-empty instructions
30 */
31
32 public class ConditionalBlock extends Instruction {
33
34 private Operand[] operanda;
35 private boolean allNodesUntyped;
36
37 /**
38 * Create a block, supplying its child expressions
39 * @param children the child expressions in order
40 */
41
42 public ConditionalBlock(Expression[] children) {
43 operanda = new Operand[children.length];
44 for (int i=0; i<children.length; i++) {
45 operanda[i] = new Operand(this, children[i], OperandRole.SAME_FOCUS_ACTION);
46 }
47 }
48
49 /**
50 * Create a block, supplying its child expressions
51 *
52 * @param children the child expressions in order
53 */
54
55 public ConditionalBlock(List<Expression> children) {
56 this(children.toArray(new Expression[children.size()]));
57 }
58
59 /**
60 * Get the n'th child expression
61 * @param n the position of the child expression required (zero-based)
62 * @return the child expression at that position
63 */
64
65 public Expression getChildExpression(int n) {
66 return operanda[n].getChildExpression();
67 }
68
69 /**
70 * Get the number of children
71 * @return the number of child subexpressions
72 */
73
74 public int size() {
75 return operanda.length;
76 }
77
78 @Override
79 public Iterable<Operand> operands() {
80 return Arrays.asList(operanda);
81 }
82
83
84 public String getExpressionName() {
85 return "condSeq";
86 }
87
88 /**
89 * Get the children of this instruction
90 *
91 * @return the children of this instruction, as an array of Expression objects. May return
92 * a zero-length array if there are no children. Changes to the content of this array
93 * have no effect
94 * @deprecated since 9.7 - use the operands() iterator instead
95 */
96
97 public Expression[] getChildren() {
98 Expression[] result = new Expression[size()];
99 int i=0;
100 for (Operand o : operands()) {
101 result[i++] = o.getChildExpression();
102 }
103 return result;
104 }
105
106
107 public int computeSpecialProperties() {
108 if (size() == 0) {
109 // An empty sequence has all special properties except "has side effects".
110 return StaticProperty.SPECIAL_PROPERTY_MASK & ~StaticProperty.HAS_SIDE_EFFECTS;
111 }
112 int p = super.computeSpecialProperties();
113 if (allNodesUntyped) {
114 p |= StaticProperty.ALL_NODES_UNTYPED;
115 }
116 // if all the expressions are axis expressions, we have a same-document node-set
117 boolean allAxisExpressions = true;
118 boolean allChildAxis = true;
119 boolean allSubtreeAxis = true;
120 for (Operand o : operands()) {
121 Expression child = o.getChildExpression();
122 if (!(child instanceof AxisExpression)) {
123 allAxisExpressions = false;
124 allChildAxis = false;
125 allSubtreeAxis = false;
126 break;
127 }
128 byte axis = ((AxisExpression) child).getAxis();
129 if (axis != AxisInfo.CHILD) {
130 allChildAxis = false;
131 }
132 if (!AxisInfo.isSubtreeAxis[axis]) {
133 allSubtreeAxis = false;
134 }
135 }
136 if (allAxisExpressions) {
137 p |= StaticProperty.CONTEXT_DOCUMENT_NODESET |
138 StaticProperty.SINGLE_DOCUMENT_NODESET |
139 StaticProperty.NO_NODES_NEWLY_CREATED;
140 // if they all use the child axis, then we have a peer node-set
141 if (allChildAxis) {
142 p |= StaticProperty.PEER_NODESET;
143 }
144 if (allSubtreeAxis) {
145 p |= StaticProperty.SUBTREE_NODESET;
146 }
147 // special case: selecting attributes then children, node-set is sorted
148 if (size() == 2 &&
149 ((AxisExpression) getChildExpression(0)).getAxis() == AxisInfo.ATTRIBUTE &&
150 ((AxisExpression) getChildExpression(1)).getAxis() == AxisInfo.CHILD) {
151 p |= StaticProperty.ORDERED_NODESET;
152 }
153 }
154 return p;
155 }
156
157 /**
158 * Copy an expression. This makes a deep copy.
159 *
160 * @return the copy of the original expression
161 * @param rebindings variables to be rebound
162 */
163
164 /*@NotNull*/
165 public Expression copy(RebindingMap rebindings) {
166 Expression[] c2 = new Expression[size()];
167 for (int c = 0; c < size(); c++) {
168 c2[c] = getChildExpression(c).copy(rebindings);
169 }
170 ConditionalBlock b2 = new ConditionalBlock(c2);
171 for (int c = 0; c < size(); c++) {
172 b2.adoptChildExpression(c2[c]);
173 }
174 b2.allNodesUntyped = allNodesUntyped;
175 ExpressionTool.copyLocationInfo(this, b2);
176 return b2;
177 }
178
179 /**
180 * Determine the data type of the items returned by this expression
181 *
182 * @return the data type
183 */
184
185 /*@NotNull*/
186 public final ItemType getItemType() {
187 if (size() == 0) {
188 return ErrorType.getInstance();
189 }
190 ItemType t1 = getChildExpression(0).getItemType();
191 TypeHierarchy th = getConfiguration().getTypeHierarchy();
192 for (int i = 1; i < size(); i++) {
193 t1 = Type.getCommonSuperType(t1, getChildExpression(i).getItemType(), th);
194 if (t1 instanceof AnyItemType) {
195 return t1; // no point going any further
196 }
197 }
198 return t1;
199 }
200
201 /**
202 * Determine the cardinality of the expression
203 */
204
205 public final int getCardinality() {
206 if (size() == 0) {
207 return StaticProperty.EMPTY;
208 }
209 int c1 = getChildExpression(0).getCardinality();
210 for (int i = 1; i < size(); i++) {
211 c1 = Cardinality.sum(c1, getChildExpression(i).getCardinality());
212 if (c1 == StaticProperty.ALLOWS_ZERO_OR_MORE) {
213 break;
214 }
215 }
216 return c1;
217 }
218
219 /**
220 * Determine whether this instruction creates new nodes.
221 * This implementation returns true if any child instruction
222 * returns true.
223 */
224
225 public final boolean mayCreateNewNodes() {
226 return someOperandCreatesNewNodes();
227 }
228
229
230 /*@NotNull*/
231 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
232 typeCheckChildren(visitor, contextInfo);
233 if (Block.neverReturnsTypedNodes(this, visitor.getConfiguration().getTypeHierarchy())) {
234 resetLocalStaticProperties();
235 allNodesUntyped = true;
236 }
237 return this;
238 }
239
240 /*@NotNull*/
241 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
242 Expression e = super.optimize(visitor, contextInfo);
243 if (e != this) {
244 return e;
245 }
246 // This code was written when xsl:on-empty instructions were allowed anywhere, so it's more general
247 // than strictly necessary.
248 int lastOrdinaryInstruction = -1;
249 boolean alwaysNonEmpty = false;
250 boolean alwaysEmpty = true;
251 for (int c = 0; c < size(); c++) {
252 if (!(getChildExpression(c) instanceof OnEmptyExpr || getChildExpression(c) instanceof OnNonEmptyExpr)) {
253 lastOrdinaryInstruction = c;
254 if (getChildExpression(c).getItemType().getUType().intersection(UType.DOCUMENT.union(UType.TEXT)).equals(UType.VOID)) {
255 int card = getChildExpression(c).getCardinality();
256 if (!Cardinality.allowsZero(card)) {
257 alwaysNonEmpty = true;
258 }
259 if (card != StaticProperty.ALLOWS_ZERO) {
260 alwaysEmpty = false;
261 }
262 } else {
263 alwaysEmpty = false;
264 alwaysNonEmpty = false;
265 break;
266 }
267 }
268 }
269 if (alwaysEmpty) {
270 visitor.getStaticContext().issueWarning("The result of the sequence constructor will always be empty, so xsl:on-empty " +
271 "instructions will always be evaluated, and xsl:on-non-empty instructions will never be evaluated", getLocation());
272 List<Expression> retain = new ArrayList<Expression>();
273 for (int c = 0; c < size(); c++) {
274 if (getChildExpression(c) instanceof OnNonEmptyExpr) {
275 // no action
276 } else if (getChildExpression(c) instanceof OnEmptyExpr) {
277 retain.add(((OnEmptyExpr) getChildExpression(c)).getBaseExpression());
278 } else {
279 retain.add(getChildExpression(c));
280 }
281 }
282 return Block.makeBlock(retain);
283 }
284 if (alwaysNonEmpty) {
285 visitor.getStaticContext().issueWarning("The result of the sequence constructor will never be empty, so xsl:on-empty " +
286 "instructions will never be evaluated, and xsl:on-non-empty instructions will always be evaluated", getLocation());
287 List<Expression> retain = new ArrayList<Expression>();
288 for (int c = 0; c < size(); c++) {
289 if (getChildExpression(c) instanceof OnEmptyExpr) {
290 // no action
291 } else if (getChildExpression(c) instanceof OnNonEmptyExpr) {
292 retain.add(((OnNonEmptyExpr) getChildExpression(c)).getBaseExpression());
293 } else {
294 retain.add(getChildExpression(c));
295 }
296 }
297 return Block.makeBlock(retain);
298 }
299 if (lastOrdinaryInstruction == -1) {
300 // all instructions are either xsl:on-empty or xsl:on-non-empty
301 // We can discard the xsl:on-non-empty instructions, and make the on-empty instructions unconditional
302 List<Expression> retain = new ArrayList<Expression>();
303 for (int c = 0; c < size(); c++) {
304 if (getChildExpression(c) instanceof OnEmptyExpr) {
305 retain.add(((OnEmptyExpr) getChildExpression(c)).getBaseExpression());
306 }
307 }
308 return Block.makeBlock(retain);
309 }
310 return this;
311 }
312
313
314 /**
315 * Check that any elements and attributes constructed or returned by this expression are acceptable
316 * in the content model of a given complex type. It's always OK to say yes, since the check will be
317 * repeated at run-time. The process of checking element and attribute constructors against the content
318 * model of a complex type also registers the type of content expected of those constructors, so the
319 * static validation can continue recursively.
320 */
321
322 public void checkPermittedContents(SchemaType parentType, boolean whole) throws XPathException {
323 for (Operand o : operands()) {
324 Expression child = o.getChildExpression();
325 child.checkPermittedContents(parentType, false);
326 }
327 }
328
329 /**
330 * Diagnostic print of expression structure. The abstract expression tree
331 * is written to the supplied output destination.
332 */
333
334 public void export(ExpressionPresenter out) throws XPathException {
335 out.startElement("condSeq", this);
336 for (Operand o : operands()) {
337 Expression child = o.getChildExpression();
338 child.export(out);
339 }
340 out.endElement();
341 }
342
343 @Override
344 public String toShortString() {
345 return "(" + getChildExpression(0).toShortString() + ", ...)";
346 }
347
348
349
350 @SuppressWarnings("StatementWithEmptyBody")
351 public TailCall processLeavingTail(final XPathContext context) throws XPathException {
352 XPathContextMinor c2 = context.newMinorContext();
353
354 final List<OnNonEmptyExpr> onNonEmptyPending = new ArrayList<OnNonEmptyExpr>();
355
356 Action action = () -> {
357 for (Expression e : onNonEmptyPending) {
358 e.process(context);
359 }
360 };
361
362 SignificantItemDetector significantItemDetector = new SignificantItemDetector(context.getReceiver(), action);
363 c2.setReceiver(significantItemDetector);
364 for (Operand o : operands()) {
365 Expression child = o.getChildExpression();
366 try {
367 if (child instanceof OnEmptyExpr) {
368 // Ignore on-empty instructions until the end
369 } else if (child instanceof OnNonEmptyExpr) {
370 if (significantItemDetector.isEmpty()) {
371 onNonEmptyPending.add((OnNonEmptyExpr)child);
372 } else {
373 child.process(context);
374 }
375 } else {
376 child.process(c2);
377 }
378
379 } catch (XPathException e) {
380 e.maybeSetLocation(child.getLocation());
381 e.maybeSetContext(context);
382 throw e;
383 }
384 }
385 // At the end, if the content produced until now is empty, process the on-empty instructions
386 if (significantItemDetector.isEmpty()) {
387 for (Operand o : operands()) {
388 Expression child = o.getChildExpression();
389 if (child instanceof OnEmptyExpr) {
390 child.process(context);
391 }
392 }
393 }
394 return null;
395 }
396
397 /**
398 * An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process().
399 * This method indicates which of these methods is provided. This implementation provides both iterate() and
400 * process() methods natively.
401 */
402
403 public int getImplementationMethod() {
404 return PROCESS_METHOD;
405 }
406
407 /**
408 * Get the (partial) name of a class that supports streaming of this kind of expression
409 *
410 * @return the partial name of a class that can be instantiated to provide streaming support in Saxon-EE,
411 * or null if there is no such class
412 */
413 @Override
414 public String getStreamerName() {
415 return "ConditionalBlock";
416 }
417 }