Debian Codegraph @

net/sf/saxon/expr/flwor/GroupByClause.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.flwor;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.expr.*;
12 import net.sf.saxon.expr.parser.ContextItemStaticInfo;
13 import net.sf.saxon.expr.parser.ExpressionVisitor;
14 import net.sf.saxon.expr.parser.PathMap;
15 import net.sf.saxon.expr.parser.RebindingMap;
16 import net.sf.saxon.expr.sort.GenericAtomicComparer;
17 import net.sf.saxon.functions.DeepEqual;
18 import net.sf.saxon.om.Item;
19 import net.sf.saxon.om.Sequence;
20 import net.sf.saxon.om.SequenceIterator;
21 import net.sf.saxon.trace.ExpressionPresenter;
22 import net.sf.saxon.trans.XPathException;
23 import net.sf.saxon.tree.util.FastStringBuffer;
24 import net.sf.saxon.value.AtomicValue;
25 import net.sf.saxon.value.SequenceExtent;
26
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.LinkedList;
30 import java.util.List;
31
32 /**
33 * This class represents an "group by" clause in a FLWOR expression
34 */
35 public class GroupByClause extends Clause {
36
37 Configuration config;
38 LocalVariableBinding[] bindings; // Variables bound in the output tuple stream.
39 // There is one for each grouping variable, then one for each non-grouping variable
40 GenericAtomicComparer[] comparers; // One comparer per grouping variable
41
42 Operand retainedTupleOp;
43 Operand groupingTupleOp;
44 //TupleExpression retainedTupleExpression; // variables declared in the FLWOR expression other than grouping variables
45 //TupleExpression groupingTupleExpression; // variables listed in the group by clause
46
47 /**
48 * Create a group-by clause
49 *
50 * @param config the Saxon configuration
51 */
52
53 public GroupByClause(Configuration config) {
54 this.config = config;
55 }
56
57 @Override
58 public int getClauseKey() {
59 return GROUPBYCLAUSE;
60 }
61
62 @Override
63 public boolean containsNonInlineableVariableReference(Binding binding) {
64 return getRetainedTupleExpression().includesBinding(binding) ||
65 getGroupingTupleExpression().includesBinding(binding);
66 }
67
68
69 public GroupByClause copy(FLWORExpression flwor, RebindingMap rebindings) {
70 GroupByClause g2 = new GroupByClause(config);
71 g2.setLocation(getLocation());
72 g2.setPackageData(getPackageData());
73 g2.bindings = new LocalVariableBinding[bindings.length];
74 for (int i = 0; i < bindings.length; i++) {
75 g2.bindings[i] = bindings[i].copy();
76 }
77 g2.comparers = comparers;
78 g2.initRetainedTupleExpression(flwor, (TupleExpression)getRetainedTupleExpression().copy(rebindings));
79 g2.initGroupingTupleExpression(flwor, (TupleExpression)getGroupingTupleExpression().copy(rebindings));
80 return g2;
81 }
82
83 /**
84 * Initialize a tuple expression that evaluates all the non-grouping variables, returning the values these variables
85 * take in the grouping input stream
86 * @param flwor the containing FLWORExpression
87 * @param expr the tuple expression
88 */
89
90 public void initRetainedTupleExpression(FLWORExpression flwor, TupleExpression expr) {
91 retainedTupleOp = new Operand(flwor, expr, OperandRole.REPEAT_NAVIGATE_CONSTRAINED);
92 }
93
94 /**
95 * Set a tuple expression that evaluates all the non-grouping variables, returning the values these variables take
96 * in the grouping input stream
97 *
98 * @param expr the tuple expression
99 */
100
101 public void setRetainedTupleExpression(TupleExpression expr) {
102 retainedTupleOp.setChildExpression(expr);
103 }
104
105 /**
106 * Get the tuple expression that evaluates all the non-grouping variables, returning the values these variables
107 * take in the grouping input stream
108 *
109 * @return the tuple expression
110 */
111
112 public TupleExpression getRetainedTupleExpression() {
113 return (TupleExpression)retainedTupleOp.getChildExpression();
114 }
115
116 @Override
117 public void optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType) throws XPathException {
118 LinkedList<LocalVariableBinding> list = new LinkedList<>(Arrays.asList(bindings));
119 LinkedList<LocalVariableReference> retainingExpr = new LinkedList<>();
120 for (Operand o : getRetainedTupleExpression().operands()) {
121 retainingExpr.add((LocalVariableReference)o.getChildExpression());
122 }
123
124 int groupingSize = getGroupingTupleExpression().getSize();
125 for (int i = groupingSize; i < list.size(); i++) {
126 if (list.get(i).getNominalReferenceCount() == 0) {
127 list.remove(i);
128 retainingExpr.remove(i - groupingSize);
129 }
130 }
131 bindings = list.toArray(new LocalVariableBinding[0]);
132 getRetainedTupleExpression().setVariables(retainingExpr);
133 }
134
135 /**
136 * Initialize a tuple expression that evaluates all the grouping variables, returning the values these variables
137 * take in the input stream
138 * @param flwor the containing FLWORExpression
139 * @param expr the tuple expression
140 */
141
142 public void initGroupingTupleExpression(FLWORExpression flwor, TupleExpression expr) {
143 groupingTupleOp = new Operand(flwor, expr, OperandRole.REPEAT_NAVIGATE_CONSTRAINED);
144 }
145
146 /**
147 * Set a tuple expression that evaluates all the grouping variables, returning the values these variables
148 * take in the input stream
149 *
150 * @param expr the tuple expression
151 */
152
153 public void setGroupingTupleExpression(TupleExpression expr) {
154 groupingTupleOp.setChildExpression(expr);
155 }
156
157 /**
158 * Get the tuple expression that evaluates all the grouping variables, returning the values these variables
159 * take in the input stream
160 *
161 * @return the tuple expression
162 */
163
164 public TupleExpression getGroupingTupleExpression() {
165 return (TupleExpression)groupingTupleOp.getChildExpression();
166 }
167
168 /**
169 * Set the bindings of new variables created by the grouping clause, which constitute the variables
170 * appearing in the output (post-grouping) tuple stream. There will be one of these for each variable
171 * in the input (pre-grouping) stream; by convention the bindings for grouping variables precede the
172 * bindings for non-grouping (retained) variables, and the order is preserved.
173 *
174 * @param bindings the bindings of the variables created in the output stream
175 */
176
177 public void setVariableBindings(LocalVariableBinding[] bindings) {
178 this.bindings = bindings;
179 }
180
181 /**
182 * Get the variables bound by this clause
183 *
184 * @return the variable bindings
185 */
186
187 public LocalVariableBinding[] getRangeVariables() {
188 return bindings;
189 }
190
191 /**
192 * Set the comparers used for the grouping keys. There is one comparer for each grouping variable
193 *
194 * @param comparers the comparers for grouping keys.
195 */
196
197 public void setComparers(GenericAtomicComparer[] comparers) {
198 this.comparers = comparers;
199 }
200
201 /**
202 * Get a tuple stream that implements the functionality of this clause, taking its
203 * input from another tuple stream which this clause modifies
204 *
205 * @param base the input tuple stream
206 * @param context the XPath dynamic evaluation context
207 * @return the output tuple stream
208 */
209 @Override
210 public TuplePull getPullStream(TuplePull base, XPathContext context) {
211 return new GroupByClausePull(base, this, context);
212 }
213
214 /**
215 * Get a push-mode tuple stream that implements the functionality of this clause, supplying its
216 * output to another tuple stream
217 *
218 * @param destination the output tuple stream
219 * @param context the dynamic evaluation context
220 * @return the push tuple stream that implements the functionality of this clause of the FLWOR
221 * expression
222 */
223 @Override
224 public TuplePush getPushStream(TuplePush destination, XPathContext context) {
225 return new GroupByClausePush(destination, this, context);
226 }
227
228 /**
229 * Process the subexpressions of this clause
230 *
231 * @param processor the expression processor used to process the subexpressions
232 */
233 @Override
234 public void processOperands(OperandProcessor processor) throws XPathException {
235 processor.processOperand(groupingTupleOp);
236 processor.processOperand(retainedTupleOp);
237 }
238
239 /**
240 * Diagnostic print of expression structure. The abstract expression tree
241 * is written to the supplied output destination.
242 *
243 * @param out the expression presenter used to display the structure
244 */
245 @Override
246 public void explain(ExpressionPresenter out) {
247 out.startElement("group-by");
248 for (Operand o : getRetainedTupleExpression().operands()) {
249 LocalVariableReference ref = (LocalVariableReference)o.getChildExpression();
250 out.startSubsidiaryElement("by");
251 out.emitAttribute("var", ref.getDisplayName());
252 out.emitAttribute("slot", ref.getBinding().getLocalSlotNumber() + "");
253 out.endSubsidiaryElement();
254 }
255 out.endElement();
256 }
257
258 public String toString() {
259 FastStringBuffer fsb = new FastStringBuffer(FastStringBuffer.C64);
260 fsb.append("group by ... ");
261 return fsb.toString();
262 }
263
264 /**
265 * Inner class representing the contents of a tuple from the pre-grouping tuple stream;
266 * a set of such objects consitutes a group. The tuple from the input stream is represented
267 * as two Tuple objects, one holding the grouping key values and one holding everything else.
268 */
269
270 public static class ObjectToBeGrouped {
271 public Tuple groupingValues;
272 public Tuple retainedValues;
273 }
274
275
276 /**
277 * Process a group of tuples from the input stream to generate a single tuple in the output stream.
278 * This method takes a group of tuples as input, and sets all the required variables in the local
279 * stack frame as required to deliver this group as the current tuple in the post-grouping stream
280 *
281 * @param group the group of input tuples
282 * @param context the XPath dynamic evaluation context
283 * @throws XPathException if a dynamic error occurs
284 */
285
286 public void processGroup(List<ObjectToBeGrouped> group, XPathContext context) throws XPathException {
287 LocalVariableBinding[] bindings = getRangeVariables();
288 Sequence<?>[] groupingValues = group.get(0).groupingValues.getMembers();
289 for (int j = 0; j < groupingValues.length; j++) {
290 Sequence<?> v = groupingValues[j];
291 context.setLocalVariable(bindings[j].getLocalSlotNumber(), v);
292 }
293 for (int j = groupingValues.length; j < bindings.length; j++) {
294 List<Item<?>> concatenatedValue = new ArrayList<>();
295 for (ObjectToBeGrouped otbg : group) {
296 Sequence<?> val = otbg.retainedValues.getMembers()[j - groupingValues.length];
297 SequenceIterator<?> si = val.iterate();
298 Item<?> it;
299 while ((it = si.next()) != null) {
300 concatenatedValue.add(it);
301 }
302 }
303 SequenceExtent<Item<?>> se = new SequenceExtent<>(concatenatedValue);
304 context.setLocalVariable(bindings[j].getLocalSlotNumber(), se);
305 }
306 }
307
308
309 /**
310 * Callback to get the comparison key for a tuple. Two tuples are equal if their comparison
311 * keys compare equal using the equals() method.
312 * @param t the tuple whose comparison key is required
313 * @return a comparison key suitable for comparing with other tuples
314 */
315
316 public TupleComparisonKey getComparisonKey(Tuple t, GenericAtomicComparer[] comparers) {
317 return new TupleComparisonKey(t.getMembers(), comparers);
318 }
319
320 @Override
321 public void addToPathMap(PathMap pathMap, PathMap.PathMapNodeSet pathMapNodeSet) {
322 throw new UnsupportedOperationException("Cannot use document projection with group-by");
323 }
324
325 /**
326 * Inner class representing a tuple comparison key: that is, an arbitrary object whose equals() and hashCode()
327 * methods can be used to test whether two tuples have equivalent grouping keys
328 */
329
330 public class TupleComparisonKey {
331
332 // Note: this is over-engineered. Each grouping value is required to be either a single atomic
333 // value or an empty sequence.
334
335 private Sequence[] groupingValues;
336 private GenericAtomicComparer[] comparers;
337
338 public TupleComparisonKey(Sequence[] groupingValues, GenericAtomicComparer[] comparers) {
339 this.groupingValues = groupingValues;
340 this.comparers = comparers;
341 }
342
343 public int hashCode() {
344 int h = 0x77557755 ^ groupingValues.length;
345 for (int i = 0; i < groupingValues.length; i++) {
346 GenericAtomicComparer comparer = comparers[i];
347 int implicitTimezone = comparer.getContext().getImplicitTimezone();
348 try {
349 SequenceIterator atoms = groupingValues[i].iterate();
350 while (true) {
351 AtomicValue val = (AtomicValue) atoms.next();
352 if (val == null) {
353 break;
354 }
355 h ^= i + val.getXPathComparable(false, comparer.getCollator(), implicitTimezone).hashCode();
356 }
357 } catch (XPathException e) {
358 // ignore any errors
359 }
360 }
361 return h;
362 }
363
364 public boolean equals(Object other) {
365 if (!(other instanceof TupleComparisonKey)) {
366 return false;
367 }
368 if (groupingValues.length != ((TupleComparisonKey) other).groupingValues.length) {
369 return false;
370 }
371 for (int i = 0; i < groupingValues.length; i++) {
372 try {
373 if (!DeepEqual.deepEqual(
374 groupingValues[i].iterate(),
375 ((TupleComparisonKey) other).groupingValues[i].iterate(),
376 comparers[i], comparers[i].getContext(), 0)) {
377 return false;
378 }
379 } catch (XPathException e) {
380 return false;
381 }
382 }
383 return true;
384 }
385 }
386
387 }
388
389 // Copyright (c) 2011 Saxonica Limited.