Debian Codegraph @

net/sf/saxon/expr/instruct/ForEachGroup.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.Controller;
11 import net.sf.saxon.event.PipelineConfiguration;
12 import net.sf.saxon.expr.*;
13 import net.sf.saxon.expr.parser.*;
14 import net.sf.saxon.expr.sort.*;
15 import net.sf.saxon.functions.CurrentGroupCall;
16 import net.sf.saxon.lib.StringCollator;
17 import net.sf.saxon.lib.TraceListener;
18 import net.sf.saxon.om.*;
19 import net.sf.saxon.pattern.Pattern;
20 import net.sf.saxon.trace.ExpressionPresenter;
21 import net.sf.saxon.trans.Err;
22 import net.sf.saxon.trans.XPathException;
23 import net.sf.saxon.type.ErrorType;
24 import net.sf.saxon.type.ItemType;
25 import net.sf.saxon.type.SchemaType;
26 import net.sf.saxon.value.AtomicValue;
27 import net.sf.saxon.value.StringValue;
28
29 import java.net.URI;
30 import java.net.URISyntaxException;
31
32
33 /**
34 * Handler for xsl:for-each-group elements in stylesheet. This is a new instruction
35 * defined in XSLT 2.0
36 */
37
38 public class ForEachGroup extends Instruction
39 implements SortKeyEvaluator, ContextMappingFunction<Item<?>>, ContextSwitchingExpression {
40
41 public static final int GROUP_BY = 0;
42 public static final int GROUP_ADJACENT = 1;
43 public static final int GROUP_STARTING = 2;
44 public static final int GROUP_ENDING = 3;
45
46 private byte algorithm;
47 private int keyItemType;
48 private StringCollator collator = null; // collation used for the grouping comparisons
49 private transient AtomicComparer[] sortComparators = null; // comparators used for sorting the groups
50 private boolean composite = false;
51 private boolean isInFork = false;
52
53 private Operand selectOp;
54 private Operand actionOp;
55 private Operand keyOp;
56 private Operand collationOp;
57 private Operand sortKeysOp;
58
59
60 /**
61 * Create a for-each-group instruction
62 * @param select the select expression (selects the population to be grouped)
63 * @param action the body of the for-each-group (applied to each group in turn)
64 * @param algorithm one of group-by, group-adjacent, group-starting-with, group-ending-with
65 * @param key expression to evaluate the grouping key
66 * @param collator user for comparing strings
67 * @param collationNameExpression expression that yields the name of the collation to be used
68 * @param sortKeys list of xsl:sort keys for sorting the groups. May be null.
69 */
70
71 public ForEachGroup(Expression select,
72 Expression action,
73 byte algorithm,
74 Expression key,
75 StringCollator collator,
76 Expression collationNameExpression,
77 SortKeyDefinitionList sortKeys) {
78 selectOp = new Operand(this, select, OperandRole.FOCUS_CONTROLLING_SELECT);
79 actionOp = new Operand(this, action, OperandRole.FOCUS_CONTROLLED_ACTION);
80 OperandRole keyRole = (algorithm == GROUP_ENDING || algorithm == GROUP_STARTING) ? OperandRole.PATTERN : OperandRole.NEW_FOCUS_ATOMIC;
81 keyOp = new Operand(this, key, keyRole);
82 if (collationNameExpression != null) {
83 collationOp = new Operand(this, collationNameExpression, OperandRole.SINGLE_ATOMIC);
84 }
85 if (sortKeys != null) {
86 sortKeysOp = new Operand(this, sortKeys, OperandRole.SINGLE_ATOMIC);
87 }
88 this.algorithm = algorithm;
89 this.collator = collator;
90 for (Operand o : operands()) {
91 adoptChildExpression(o.getChildExpression());
92 }
93 }
94
95 /**
96 * Get the name of this instruction for diagnostic and tracing purposes
97 *
98 * @return the name of the instruction
99 */
100
101 public int getInstructionNameCode() {
102 return StandardNames.XSL_FOR_EACH_GROUP;
103 }
104
105 @Override
106 public Iterable<Operand> operands() {
107 return operandSparseList(selectOp, actionOp, keyOp, collationOp, sortKeysOp);
108 }
109
110 /**
111 * Get the select expression
112 *
113 * @return the select expression
114 */
115
116 public Expression getSelectExpression() {
117 return selectOp.getChildExpression();
118 }
119
120 /**
121 * Get the action expression (the content of the for-each-group)
122 *
123 * @return the body of the xsl:for-each-group instruction
124 */
125
126 public Expression getActionExpression() {
127 return actionOp.getChildExpression();
128 }
129
130 /**
131 * Get the grouping algorithm (one of group-by, group-adjacent, group-starting-with, group-ending-with)
132 *
133 * @return one of group-by, group-adjacent, group-starting-with, group-ending-with
134 */
135
136 public byte getAlgorithm() {
137 return algorithm;
138 }
139
140 /**
141 * Get the grouping key expression expression (the group-by or group-adjacent expression, or a
142 * PatternSponsor containing the group-starting-with or group-ending-with expression)
143 *
144 * @return the expression used to calculate grouping keys
145 */
146
147 public Expression getGroupingKey() {
148 return keyOp.getChildExpression();
149 }
150
151 /**
152 * Get the primitive item type of the key
153 *
154 * @return the primitive item type of the grouping key
155 */
156
157 public int getKeyItemType() {
158 return keyItemType;
159 }
160
161 /**
162 * Get the sort keys defined at the for-each-group level, that is, the keys for sorting the groups
163 *
164 * @return the definitions of the sort keys defined as children of the xsl:for-each-group element,
165 * or null if there are no sort keys
166 */
167
168 public SortKeyDefinitionList getSortKeyDefinitions() {
169 return sortKeysOp == null ? null : (SortKeyDefinitionList)sortKeysOp.getChildExpression();
170 }
171
172 /**
173 * Get the statically-allocated sort key comparators for sorting at the group level, if known
174 *
175 * @return the comparators used for comparing sort key values, one entry in the array for each
176 * nested xsl:sort element
177 */
178
179 public AtomicComparer[] getSortKeyComparators() {
180 return sortComparators;
181 }
182
183 /**
184 * Get the statically-determined collator, or null if the collation was not determined statically
185 *
186 * @return the collation, if known statically, or null if not
187 */
188
189 /*@Nullable*/
190 public StringCollator getCollation() {
191 return collator;
192 }
193
194 /**
195 * Get the static base URI of the instruction
196 *
197 * @return the static base URI if known, or null otherwise
198 */
199
200 /*@Nullable*/
201 public URI getBaseURI() {
202 try {
203 return getRetainedStaticContext().getStaticBaseUri();
204 } catch (XPathException err) {
205 return null;
206 }
207 }
208
209 public boolean isComposite() {
210 return composite;
211 }
212
213 public void setComposite(boolean composite) {
214 this.composite = composite;
215 }
216
217 public boolean isInFork() {
218 return isInFork;
219 }
220
221 public void setIsInFork(boolean inFork) {
222 isInFork = inFork;
223 }
224
225 /**
226 * Ask whether common subexpressions found in the operands of this expression can
227 * be extracted and evaluated outside the expression itself. The result is irrelevant
228 * in the case of operands evaluated with a different focus, which will never be
229 * extracted in this way, even if they have no focus dependency.
230 *
231 * @return false for this kind of expression
232 */
233 @Override
234 public boolean allowExtractingCommonSubexpressions() {
235 return false;
236 }
237
238 /*@NotNull*/
239 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
240
241 selectOp.typeCheck(visitor, contextInfo);
242 if (collationOp != null) {
243 collationOp.typeCheck(visitor, contextInfo);
244 }
245
246 ItemType selectedItemType = getSelectExpression().getItemType();
247 if (selectedItemType == ErrorType.getInstance()) {
248 return Literal.makeEmptySequence();
249 }
250
251 for (Operand o : operands()) {
252 fixupGroupReferences(this, this, selectedItemType, false);
253 }
254
255 ContextItemStaticInfo cit = visitor.getConfiguration().makeContextItemStaticInfo(selectedItemType, false);
256 cit.setContextSettingExpression(getSelectExpression());
257
258 actionOp.typeCheck(visitor, cit);
259 keyOp.typeCheck(visitor, cit);
260
261 if (Literal.isEmptySequence(getSelectExpression())) {
262 return getSelectExpression();
263 }
264 if (Literal.isEmptySequence(getActionExpression())) {
265 return getActionExpression();
266 }
267 if (getSortKeyDefinitions() != null) {
268
269 boolean allFixed = true;
270 for (SortKeyDefinition sk : getSortKeyDefinitions()) {
271 Expression sortKey = sk.getSortKey();
272 sortKey = sortKey.typeCheck(visitor, cit);
273 if (sk.isBackwardsCompatible()) {
274 sortKey = FirstItemExpression.makeFirstItemExpression(sortKey);
275 } else {
276 RoleDiagnostic role =
277 new RoleDiagnostic(RoleDiagnostic.INSTRUCTION, "xsl:sort/select", 0);
278 role.setErrorCode("XTTE1020");
279 sortKey = CardinalityChecker.makeCardinalityChecker(sortKey, StaticProperty.ALLOWS_ZERO_OR_ONE, role);
280 }
281 sk.setSortKey(sortKey, true);
282 sk.typeCheck(visitor, contextInfo);
283 if (sk.isFixed()) {
284 AtomicComparer comp = sk.makeComparator(
285 visitor.getStaticContext().makeEarlyEvaluationContext());
286 sk.setFinalComparator(comp);
287 } else {
288 allFixed = false;
289 }
290 }
291 if (allFixed) {
292 sortComparators = new AtomicComparer[getSortKeyDefinitions().size()];
293 for (int i = 0; i < getSortKeyDefinitions().size(); i++) {
294 sortComparators[i] = getSortKeyDefinitions().getSortKeyDefinition(i).getFinalComparator();
295 }
296 }
297 }
298 keyItemType = getGroupingKey().getItemType().getPrimitiveType();
299
300 return this;
301 }
302
303 private static void fixupGroupReferences(Expression exp, ForEachGroup feg, ItemType selectedItemType, boolean isInLoop) {
304 if (exp == null) {
305 // no action
306 } else if (exp instanceof CurrentGroupCall) {
307 ((CurrentGroupCall) exp).setControllingInstruction(feg, selectedItemType, isInLoop);
308 } else if (exp instanceof ForEachGroup) {
309 // a current-group() reference to the outer for-each-group can occur in the select expression
310 // or in the AVTs of a contained xsl:sort
311 ForEachGroup feg2 = (ForEachGroup)exp;
312 if (feg2 == feg) {
313 fixupGroupReferences(feg2.getActionExpression(), feg, selectedItemType, false);
314 } else {
315 fixupGroupReferences(feg2.getSelectExpression(), feg, selectedItemType, isInLoop);
316 fixupGroupReferences(feg2.getGroupingKey(), feg, selectedItemType, isInLoop);
317 if (feg2.getSortKeyDefinitions() != null) {
318 for (SortKeyDefinition skd : feg2.getSortKeyDefinitions()) {
319 fixupGroupReferences(skd.getOrder(), feg, selectedItemType, isInLoop);
320 fixupGroupReferences(skd.getCaseOrder(), feg, selectedItemType, isInLoop);
321 fixupGroupReferences(skd.getDataTypeExpression(), feg, selectedItemType, isInLoop);
322 fixupGroupReferences(skd.getLanguage(), feg, selectedItemType, isInLoop);
323 fixupGroupReferences(skd.getCollationNameExpression(), feg, selectedItemType, isInLoop);
324 fixupGroupReferences(skd.getOrder(), feg, selectedItemType, isInLoop);
325 }
326 }
327 }
328
329 } else {
330 for (Operand o : exp.operands()) {
331 fixupGroupReferences(o.getChildExpression(), feg, selectedItemType, isInLoop || o.isEvaluatedRepeatedly());
332 }
333 }
334 }
335
336 /*@NotNull*/
337 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType) throws XPathException {
338 selectOp.optimize(visitor, contextItemType);
339 ItemType selectedItemType = getSelectExpression().getItemType();
340 ContextItemStaticInfo sit = visitor.getConfiguration().makeContextItemStaticInfo(selectedItemType, false);
341 sit.setContextSettingExpression(getSelectExpression());
342 actionOp.optimize(visitor, sit);
343 keyOp.optimize(visitor, sit);
344
345 if (Literal.isEmptySequence(getSelectExpression())) {
346 return getSelectExpression();
347 }
348 if (Literal.isEmptySequence(getActionExpression())) {
349 return getActionExpression();
350 }
351 // Optimize the sort key definitions
352 if (getSortKeyDefinitions() != null) {
353 for (SortKeyDefinition skd : getSortKeyDefinitions()) {
354 Expression sortKey = skd.getSortKey();
355 sortKey = sortKey.optimize(visitor, sit);
356 skd.setSortKey(sortKey, true);
357 }
358 }
359 if (collationOp != null) {
360 collationOp.optimize(visitor, contextItemType);
361 }
362 if (collator == null && (getCollationNameExpression() instanceof StringLiteral)) {
363 String collation = ((StringLiteral) getCollationNameExpression()).getStringValue();
364 URI collationURI;
365 try {
366 collationURI = new URI(collation);
367 if (!collationURI.isAbsolute()) {
368 collationURI = getStaticBaseURI().resolve(collationURI);
369 final String collationNameString = collationURI.toString();
370 setCollationNameExpression(new StringLiteral(collationNameString));
371 collator = visitor.getConfiguration().getCollation(collationNameString);
372 if (collator == null) {
373 XPathException err = new XPathException("Unknown collation " + Err.wrap(collationURI.toString(), Err.URI));
374 err.setErrorCode("XTDE1110");
375 err.setLocation(getLocation());
376 throw err;
377 }
378 }
379 } catch (URISyntaxException err) {
380 XPathException e = new XPathException("Collation name '" + getCollationNameExpression() + "' is not a valid URI");
381 e.setErrorCode("XTDE1110");
382 e.setLocation(getLocation());
383 throw e;
384 }
385 }
386 return this;
387 }
388
389 /**
390 * Copy an expression. This makes a deep copy.
391 *
392 * @return the copy of the original expression
393 * @param rebindings a mutable list of (old binding, new binding) pairs
394 * that is used to update the bindings held in any
395 * local variable references that are copied.
396 */
397
398 /*@NotNull*/
399 public Expression copy(RebindingMap rebindings) {
400 SortKeyDefinition[] newKeyDef = null;
401 if (getSortKeyDefinitions() != null) {
402 newKeyDef = new SortKeyDefinition[getSortKeyDefinitions().size()];
403 for (int i = 0; i < getSortKeyDefinitions().size(); i++) {
404 newKeyDef[i] = getSortKeyDefinitions().getSortKeyDefinition(i).copy(rebindings);
405 }
406 }
407 ForEachGroup feg = new ForEachGroup(
408 getSelectExpression().copy(rebindings),
409 getActionExpression().copy(rebindings),
410 algorithm,
411 getGroupingKey().copy(rebindings),
412 collator,
413 getCollationNameExpression().copy(rebindings),
414 newKeyDef == null ? null : new SortKeyDefinitionList(newKeyDef));
415 ExpressionTool.copyLocationInfo(this, feg);
416 feg.setComposite(isComposite());
417 fixupGroupReferences(feg, feg, getSelectExpression().getItemType(), false);
418 return feg;
419 }
420
421
422 /**
423 * Get the item type of the items returned by evaluating this instruction
424 *
425 * @return the static item type of the instruction
426 */
427
428 /*@NotNull*/
429 public ItemType getItemType() {
430 return getActionExpression().getItemType();
431 }
432
433 /**
434 * Compute the dependencies of an expression, as the union of the
435 * dependencies of its subexpressions. (This is overridden for path expressions
436 * and filter expressions, where the dependencies of a subexpression are not all
437 * propogated). This method should be called only once, to compute the dependencies;
438 * after that, getDependencies should be used.
439 *
440 * @return the depencies, as a bit-mask
441 */
442
443 public int computeDependencies() {
444 // some of the dependencies in the "action" part and in the grouping and sort keys aren't relevant,
445 // because they don't depend on values set outside the for-each-group expression
446 int dependencies = 0;
447 dependencies |= getSelectExpression().getDependencies();
448 dependencies |= getGroupingKey().getDependencies() & ~StaticProperty.DEPENDS_ON_FOCUS;
449 dependencies |= getActionExpression().getDependencies()
450 & ~(StaticProperty.DEPENDS_ON_FOCUS | StaticProperty.DEPENDS_ON_CURRENT_GROUP);
451 if (getSortKeyDefinitions() != null) {
452 for (SortKeyDefinition skd : getSortKeyDefinitions()) {
453 dependencies |= skd.getSortKey().getDependencies() & ~StaticProperty.DEPENDS_ON_FOCUS;
454 Expression e = skd.getCaseOrder();
455 if (e != null && !(e instanceof Literal)) {
456 dependencies |= e.getDependencies();
457 }
458 e = skd.getDataTypeExpression();
459 if (e != null && !(e instanceof Literal)) {
460 dependencies |= e.getDependencies();
461 }
462 e = skd.getLanguage();
463 if (e != null && !(e instanceof Literal)) {
464 dependencies |= e.getDependencies();
465 }
466 }
467 }
468 if (getCollationNameExpression() != null) {
469 dependencies |= getCollationNameExpression().getDependencies();
470 }
471 return dependencies;
472 }
473
474 /**
475 * Get the static properties of this expression (other than its type). The result is
476 * bit-signficant. These properties are used for optimizations. In general, if
477 * property bit is set, it is true, but if it is unset, the value is unknown.
478 *
479 * @return a set of flags indicating static properties of this expression
480 */
481 @Override
482 public int computeSpecialProperties() {
483 int p = super.computeSpecialProperties();
484 p |= getActionExpression().getSpecialProperties() & StaticProperty.ALL_NODES_UNTYPED;
485 return p;
486 }
487
488 /**
489 * Determine whether this instruction creates new nodes.
490 * This implementation returns true if the "action" creates new nodes.
491 * (Nodes created by the condition can't contribute to the result).
492 */
493
494 public final boolean mayCreateNewNodes() {
495 int props = getActionExpression().getSpecialProperties();
496 return (props & StaticProperty.NO_NODES_NEWLY_CREATED) == 0;
497 }
498
499 /**
500 * Get the (partial) name of a class that supports streaming of this kind of expression
501 *
502 * @return the partial name of a class that can be instantiated to provide streaming support in Saxon-EE,
503 * or null if there is no such class
504 */
505 @Override
506 public String getStreamerName() {
507 return "ForEachGroup";
508 }
509
510 /**
511 * Add a representation of this expression to a PathMap. The PathMap captures a map of the nodes visited
512 * by an expression in a source tree.
513 * <p>The default implementation of this method assumes that an expression does no navigation other than
514 * the navigation done by evaluating its subexpressions, and that the subexpressions are evaluated in the
515 * same context as the containing expression. The method must be overridden for any expression
516 * where these assumptions do not hold. For example, implementations exist for AxisExpression, ParentExpression,
517 * and RootExpression (because they perform navigation), and for the doc(), document(), and collection()
518 * functions because they create a new navigation root. Implementations also exist for PathExpression and
519 * FilterExpression because they have subexpressions that are evaluated in a different context from the
520 * calling expression.</p>
521 *
522 * @param pathMap the PathMap to which the expression should be added
523 * @param pathMapNodeSet the set of nodes within the path map
524 * @return the pathMapNode representing the focus established by this expression, in the case where this
525 * expression is the first operand of a path expression or filter expression. For an expression that does
526 * navigation, it represents the end of the arc in the path map that describes the navigation route. For other
527 * expressions, it is the same as the input pathMapNode.
528 */
529
530 public PathMap.PathMapNodeSet addToPathMap(PathMap pathMap, PathMap.PathMapNodeSet pathMapNodeSet) {
531 PathMap.PathMapNodeSet target = getSelectExpression().addToPathMap(pathMap, pathMapNodeSet);
532 if (getCollationNameExpression() != null) {
533 getCollationNameExpression().addToPathMap(pathMap, pathMapNodeSet);
534 }
535 if (getSortKeyDefinitions() != null) {
536 for (SortKeyDefinition skd : getSortKeyDefinitions()) {
537 skd.getSortKey().addToPathMap(pathMap, target);
538 Expression e = skd.getOrder();
539 if (e != null) {
540 e.addToPathMap(pathMap, pathMapNodeSet);
541 }
542 e = skd.getCaseOrder();
543 if (e != null) {
544 e.addToPathMap(pathMap, pathMapNodeSet);
545 }
546 e = skd.getDataTypeExpression();
547 if (e != null) {
548 e.addToPathMap(pathMap, pathMapNodeSet);
549 }
550 e = skd.getLanguage();
551 if (e != null) {
552 e.addToPathMap(pathMap, pathMapNodeSet);
553 }
554 e = skd.getCollationNameExpression();
555 if (e != null) {
556 e.addToPathMap(pathMap, pathMapNodeSet);
557 }
558 }
559 }
560 return getActionExpression().addToPathMap(pathMap, target);
561 }
562
563
564 /**
565 * Check that any elements and attributes constructed or returned by this expression are acceptable
566 * in the content model of a given complex type. It's always OK to say yes, since the check will be
567 * repeated at run-time. The process of checking element and attribute constructors against the content
568 * model of a complex type also registers the type of content expected of those constructors, so the
569 * static validation can continue recursively.
570 */
571
572 public void checkPermittedContents(SchemaType parentType, boolean whole) throws XPathException {
573 getActionExpression().checkPermittedContents(parentType, false);
574 }
575
576 public TailCall processLeavingTail(XPathContext context) throws XPathException {
577 Controller controller = context.getController();
578 assert controller != null;
579 PipelineConfiguration pipe = context.getReceiver().getPipelineConfiguration();
580
581 GroupIterator groupIterator = getGroupIterator(context);
582 XPathContextMajor c2 = context.newContext();
583 c2.setOrigin(this);
584 FocusIterator focusIterator = c2.trackFocus(groupIterator);
585 c2.setCurrentGroupIterator(groupIterator);
586 c2.setCurrentTemplateRule(null);
587 pipe.setXPathContext(c2);
588
589 if (controller.isTracing()) {
590 TraceListener listener = controller.getTraceListener();
591 assert listener != null;
592 Item item;
593 while ((item = focusIterator.next()) != null) {
594 listener.startCurrentItem(item);
595 getActionExpression().process(c2);
596 listener.endCurrentItem(item);
597 }
598 } else {
599 while (focusIterator.next() != null) {
600 getActionExpression().process(c2);
601 }
602 }
603
604 pipe.setXPathContext(context);
605 return null;
606 }
607
608 /**
609 * Get the expression which, on evaluation, yields the name of the collation to be used
610 *
611 * @return the expression that returns the collation name
612 */
613
614 public Expression getCollationNameExpression() {
615 return collationOp == null ? null : collationOp.getChildExpression();
616 }
617
618 /**
619 * Get (and if necessary, create) the comparator used for comparing grouping key values
620 *
621 * @param context XPath dynamic context
622 * @return a StringCollator suitable for comparing the values of grouping keys
623 * @throws XPathException if a failure occurs evaluating the expression that determines the collation name
624 */
625
626 private StringCollator getCollator(XPathContext context) throws XPathException {
627 if (getCollationNameExpression() != null) {
628 StringValue collationValue = (StringValue) getCollationNameExpression().evaluateItem(context);
629 assert collationValue != null;
630 String cname = collationValue.getStringValue();
631 try {
632 return context.getConfiguration().getCollation(cname, getStaticBaseURIString(), "FOCH0002");
633 } catch (XPathException e) {
634 e.setLocation(getLocation());
635 throw e;
636 }
637
638 } else {
639 // Fallback - this shouldn't happen
640 return CodepointCollator.getInstance();
641 }
642 }
643
644 private GroupIterator getGroupIterator(XPathContext context) throws XPathException {
645 return getGroupIterator(getSelectExpression(), context);
646 }
647
648 public GroupIterator getGroupIterator(Expression select, XPathContext context) throws XPathException {
649
650 // get an iterator over the groups in "order of first appearance"
651
652 GroupIterator groupIterator;
653 switch (algorithm) {
654 case GROUP_BY: {
655 StringCollator coll = collator;
656 if (coll==null) {
657 // The collation is determined at run-time
658 coll = getCollator(context);
659 }
660 XPathContext c2 = context.newMinorContext();
661 FocusIterator<?> population = c2.trackFocus(select.iterate(context));
662 groupIterator = new GroupByIterator(population, getGroupingKey(), c2, coll, composite);
663 break;
664 }
665 case GROUP_ADJACENT: {
666 StringCollator coll = collator;
667 if (coll==null) {
668 // The collation is determined at run-time
669 coll = getCollator(context);
670 }
671 groupIterator = new GroupAdjacentIterator(select, getGroupingKey(), context, coll, composite);
672 break;
673 }
674 case GROUP_STARTING:
675 groupIterator = new GroupStartingIterator(select, (Pattern) getGroupingKey(), context);
676 break;
677 case GROUP_ENDING:
678 groupIterator = new GroupEndingIterator(select, (Pattern) getGroupingKey(), context);
679 break;
680 default:
681 throw new AssertionError("Unknown grouping algorithm");
682 }
683
684 // now iterate over the leading nodes of the groups
685
686 if (getSortKeyDefinitions() != null) {
687 AtomicComparer[] comps = sortComparators;
688 XPathContext xpc = context.newMinorContext();
689 if (comps == null) {
690 comps = new AtomicComparer[getSortKeyDefinitions().size()];
691 for (int s = 0; s < getSortKeyDefinitions().size(); s++) {
692 comps[s] = getSortKeyDefinitions().getSortKeyDefinition(s).makeComparator(xpc);
693 }
694 }
695 groupIterator = new SortedGroupIterator(xpc, groupIterator, this, comps);
696
697 }
698
699 return groupIterator;
700 }
701
702 /**
703 * Return an Iterator to iterate over the values of a sequence. The value of every
704 * expression can be regarded as a sequence, so this method is supported for all
705 * expressions. This default implementation relies on the process() method: it
706 * "pushes" the results of the instruction to a sequence in memory, and then
707 * iterates over this in-memory sequence.
708 * <p>In principle instructions should implement a pipelined iterate() method that
709 * avoids the overhead of intermediate storage.</p>
710 *
711 * @param context supplies the context for evaluation
712 * @return a SequenceIterator that can be used to iterate over the result
713 * of the expression
714 * @throws XPathException if any dynamic error occurs evaluating the
715 * expression
716 */
717
718 /*@NotNull*/
719 public SequenceIterator<?> iterate(XPathContext context) throws XPathException {
720 GroupIterator master = getGroupIterator(context);
721 XPathContextMajor c2 = context.newContext();
722 c2.setOrigin(this);
723 c2.trackFocus(master);
724 c2.setCurrentGroupIterator(master);
725 c2.setCurrentTemplateRule(null);
726 return new ContextMappingIterator<>(this, c2);
727 }
728
729 /**
730 * Map one item to a sequence.
731 *
732 * @param context The processing context. This is supplied only for mapping constructs that
733 * set the context node, position, and size. Otherwise it is null.
734 * @return either (a) a SequenceIterator over the sequence of items that the supplied input
735 * item maps to, or (b) an Item if it maps to a single item, or (c) null if it maps to an empty
736 * sequence.
737 */
738
739 public SequenceIterator<?> map(XPathContext context) throws XPathException {
740 return getActionExpression().iterate(context);
741 }
742
743 /**
744 * Callback for evaluating the sort keys
745 */
746
747 public AtomicValue evaluateSortKey(int n, XPathContext c) throws XPathException {
748 return (AtomicValue) getSortKeyDefinitions().getSortKeyDefinition(n).getSortKey().evaluateItem(c);
749 }
750
751
752 public SortKeyDefinitionList getSortKeyDefinitionList() {
753 if (sortKeysOp == null) {
754 return null;
755 }
756 return (SortKeyDefinitionList) sortKeysOp.getChildExpression();
757 }
758
759 /**
760 * Diagnostic print of expression structure. The abstract expression tree
761 * is written to the supplied output destination.
762 */
763
764 public void export(ExpressionPresenter out) throws XPathException {
765 out.startElement("forEachGroup", this);
766 out.emitAttribute("algorithm", getAlgorithmName(algorithm));
767 String flags = "";
768 if (composite) {
769 flags = "c";
770 }
771 if (isInFork()) {
772 flags += "k";
773 }
774 if (!flags.isEmpty()) {
775 out.emitAttribute("flags", flags);
776 }
777 out.setChildRole("select");
778 getSelectExpression().export(out);
779 if (algorithm == GROUP_BY || algorithm == GROUP_ADJACENT) {
780 out.setChildRole("key");
781 getGroupingKey().export(out);
782 } else {
783 out.setChildRole("match");
784 getGroupingKey().export(out);
785 }
786 if (getSortKeyDefinitions() != null) {
787 out.setChildRole("sort");
788 getSortKeyDefinitionList().export(out);
789 }
790 if (getCollationNameExpression() != null) {
791 out.setChildRole("collation");
792 getCollationNameExpression().export(out);
793 }
794 out.setChildRole("content");
795 getActionExpression().export(out);
796 out.endElement();
797 }
798
799 private static String getAlgorithmName(byte algorithm) {
800 switch (algorithm) {
801 case GROUP_BY:
802 return "by";
803 case GROUP_ADJACENT:
804 return "adjacent";
805 case GROUP_STARTING:
806 return "starting";
807 case GROUP_ENDING:
808 return "ending";
809 default:
810 return "** unknown algorithm **";
811 }
812 }
813
814 public void setSelect(Expression select) {
815 selectOp.setChildExpression(select);
816 }
817
818 public void setAction(Expression action) {
819 actionOp.setChildExpression(action);
820 }
821
822 public void setKey(Expression key) {
823 keyOp.setChildExpression(key);
824 }
825
826 public void setCollationNameExpression(Expression collationNameExpression) {
827 if (collationOp == null) {
828 collationOp = new Operand(this, collationNameExpression, OperandRole.SINGLE_ATOMIC);
829 } else {
830 collationOp.setChildExpression(collationNameExpression);
831 }
832 }
833
834 public void setSortKeyDefinitions(SortKeyDefinitionList sortKeyDefinitions) {
835 if (sortKeysOp == null) {
836 sortKeysOp = new Operand(this, sortKeyDefinitions, OperandRole.SINGLE_ATOMIC);
837 } else {
838 sortKeysOp.setChildExpression(sortKeyDefinitions);
839 }
840 }
841 }
842