Debian Codegraph @

net/sf/saxon/expr/flwor/WindowClause.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.*;
13 import net.sf.saxon.functions.Count;
14 import net.sf.saxon.om.Item;
15 import net.sf.saxon.om.Sequence;
16 import net.sf.saxon.om.SequenceIterator;
17 import net.sf.saxon.trace.ExpressionPresenter;
18 import net.sf.saxon.trans.XPathException;
19 import net.sf.saxon.tree.iter.ListIterator;
20 import net.sf.saxon.type.ItemType;
21 import net.sf.saxon.type.TypeHierarchy;
22 import net.sf.saxon.value.Cardinality;
23 import net.sf.saxon.value.EmptySequence;
24 import net.sf.saxon.value.Int64Value;
25 import net.sf.saxon.value.SequenceType;
26 import net.sf.saxon.z.IntHashMap;
27
28 import java.util.Iterator;
29 import java.util.List;
30
31 /**
32 * Implements an XQuery 3.0 sliding or tumbling window clause within a FLWOR expression
33 */
34 public class WindowClause extends Clause {
35
36 private boolean sliding;
37 private boolean includeUnclosedWindows = true;
38 private Operand sequenceOp;
39 private Operand startConditionOp;
40 private Operand endConditionOp;
41 private IntHashMap<LocalVariableBinding> windowVars = new IntHashMap<>(10);
42 private ItemTypeCheckingFunction<Item<?>> itemTypeChecker;
43 private boolean windowMustBeSingleton;
44
45 public static final int WINDOW_VAR = 0;
46 public static final int START_ITEM = 1;
47 public static final int START_ITEM_POSITION = 2;
48 public static final int START_PREVIOUS_ITEM = 3;
49 public static final int START_NEXT_ITEM = 4;
50 public static final int END_ITEM = 5;
51 public static final int END_ITEM_POSITION = 6;
52 public static final int END_PREVIOUS_ITEM = 7;
53 public static final int END_NEXT_ITEM = 8;
54
55 public WindowClause() {
56 }
57
58 @Override
59 public int getClauseKey() {
60 return WINDOW;
61 }
62
63 public void setIsSlidingWindow(boolean sliding) {
64 this.sliding = sliding;
65 }
66
67 public boolean isSlidingWindow() {
68 return sliding;
69 }
70
71 public boolean isTumblingWindow() {
72 return !sliding;
73 }
74
75 public void setIncludeUnclosedWindows(boolean include) {
76 this.includeUnclosedWindows = include;
77 }
78
79 public boolean isIncludeUnclosedWindows() {
80 return includeUnclosedWindows;
81 }
82
83 public void initSequence(FLWORExpression flwor, Expression sequence) {
84 sequenceOp = new Operand(flwor, sequence, OperandRole.INSPECT);
85 }
86
87 public void setSequence(Expression sequence) {
88 sequenceOp.setChildExpression(sequence);
89 }
90
91 public Expression getSequence() {
92 return sequenceOp.getChildExpression();
93 }
94
95 public void initStartCondition(FLWORExpression flwor, Expression startCondition) {
96 startConditionOp = new Operand(flwor, startCondition, OperandRole.INSPECT);
97 }
98
99 public void setStartCondition(Expression startCondition) {
100 startConditionOp.setChildExpression(startCondition);
101 }
102
103 public Expression getStartCondition() {
104 return startConditionOp.getChildExpression();
105 }
106
107 public void initEndCondition(FLWORExpression flwor, Expression endCondition) {
108 endConditionOp = new Operand(flwor, endCondition, OperandRole.INSPECT);
109 }
110
111 public void setEndCondition(Expression endCondition) {
112 endConditionOp.setChildExpression(endCondition);
113 }
114
115 public Expression getEndCondition() {
116 return endConditionOp == null ? null : endConditionOp.getChildExpression();
117 }
118
119
120 public void setVariableBinding(int role, LocalVariableBinding binding) throws XPathException {
121 for (Iterator<LocalVariableBinding> iter = windowVars.valueIterator(); iter.hasNext(); ) {
122 if (iter.next().getVariableQName().equals(binding.getVariableQName())) {
123 throw new XPathException("Two variables in a window clause cannot have the same name (" +
124 binding.getVariableQName().getDisplayName() + ")", "XQST0103");
125 }
126 }
127 windowVars.put(role, binding);
128 }
129
130 public LocalVariableBinding getVariableBinding(int role) {
131 return windowVars.get(role);
132 }
133
134 public ItemTypeCheckingFunction<Item<?>> getItemTypeChecker() {
135 return itemTypeChecker;
136 }
137
138 public boolean isWindowMustBeSingleton() {
139 return windowMustBeSingleton;
140 }
141
142 @Override
143 public void typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
144 SequenceType requiredType = getVariableBinding(WindowClause.WINDOW_VAR).getRequiredType();
145 ItemType required = requiredType.getPrimaryType();
146 ItemType supplied = getSequence().getItemType();
147 Configuration config = visitor.getConfiguration();
148 TypeHierarchy th = config.getTypeHierarchy();
149 int rel = th.relationship(required, supplied);
150 switch (rel) {
151 case TypeHierarchy.SAME_TYPE:
152 case TypeHierarchy.SUBSUMES:
153 // no action
154 break;
155 case TypeHierarchy.OVERLAPS:
156 case TypeHierarchy.SUBSUMED_BY:
157 RoleDiagnostic role = new RoleDiagnostic(
158 RoleDiagnostic.VARIABLE,
159 getVariableBinding(WindowClause.WINDOW_VAR).getVariableQName().getDisplayName(), 0);
160 itemTypeChecker = new ItemTypeCheckingFunction<>(
161 required, role, getLocation(), config);
162 break;
163 case TypeHierarchy.DISJOINT:
164 String message = "The items in the window will always be instances of "
165 + supplied + ", never of the required type " + required;
166 throw new XPathException(message, "XPTY0004", getLocation());
167 }
168 windowMustBeSingleton = !Cardinality.allowsMany(requiredType.getCardinality());
169
170 if (requiredType.getCardinality() == StaticProperty.ALLOWS_ZERO) {
171 String message = "The value of the window variable can never be an empty sequence";
172 throw new XPathException(message, "XPTY0004", getLocation());
173 }
174 }
175
176 public void checkWindowContents(Window w) throws XPathException {
177 if (windowMustBeSingleton && w.contents.size() > 1) {
178 throw new XPathException("Required type of window allows only a single item; window has length " + w.contents.size(),
179 "XPTY0004", getLocation());
180 }
181 ItemTypeCheckingFunction<Item<?>> checker = getItemTypeChecker();
182 if (checker != null) {
183 SequenceIterator<?> check =
184 new ItemMappingIterator<>(new ListIterator<>(w.contents), checker);
185 Count.count(check); // a convenient way to consume the iterator and thus perform the checking
186 }
187 }
188
189 @Override
190 public Clause copy(FLWORExpression flwor, RebindingMap rebindings) {
191 WindowClause wc = new WindowClause();
192 wc.setLocation(getLocation());
193 wc.setPackageData(getPackageData());
194 wc.sliding = sliding;
195 wc.includeUnclosedWindows = includeUnclosedWindows;
196 wc.initSequence(flwor, getSequence().copy(rebindings));
197 wc.initStartCondition(flwor, getStartCondition().copy(rebindings));
198 wc.initEndCondition(flwor, getEndCondition().copy(rebindings));
199 wc.windowVars = windowVars;
200 return wc;
201 }
202
203 /**
204 * Get a pull-mode tuple stream that implements the functionality of this clause, taking its
205 * input from another tuple stream which this clause modifies
206 *
207 * @param base the input tuple stream
208 * @param context the dynamic evaluation context
209 * @return the output tuple stream
210 */
211 @Override
212 public TuplePull getPullStream(TuplePull base, XPathContext context) {
213 return new WindowClausePull(base, this, context);
214 }
215
216 /**
217 * Get a push-mode tuple stream that implements the functionality of this clause, supplying its
218 * output to another tuple stream
219 *
220 * @param destination the output tuple stream
221 * @param context the dynamic evaluation context
222 * @return the push tuple stream that implements the functionality of this clause of the FLWOR
223 * expression
224 */
225 @Override
226 public TuplePush getPushStream(TuplePush destination, XPathContext context) {
227 return new WindowClausePush(destination, this);
228 }
229
230 /**
231 * Process the subexpressions of this clause
232 *
233 * @param processor the expression processor used to process the subexpressions
234 */
235 @Override
236 public void processOperands(OperandProcessor processor) throws XPathException {
237 processor.processOperand(sequenceOp);
238 processor.processOperand(startConditionOp);
239 if (endConditionOp != null) {
240 processor.processOperand(endConditionOp);
241 }
242 }
243
244 @Override
245 public void addToPathMap(PathMap pathMap, PathMap.PathMapNodeSet pathMapNodeSet) {
246 throw new UnsupportedOperationException("Cannot use document projection with windowing");
247 }
248
249 /**
250 * Get the variables bound by this clause
251 *
252 * @return the variable bindings
253 */
254 @Override
255 public LocalVariableBinding[] getRangeVariables() {
256 LocalVariableBinding[] vars = new LocalVariableBinding[windowVars.size()];
257 int i = 0;
258 Iterator<LocalVariableBinding> iter = windowVars.valueIterator();
259 while (iter.hasNext()) {
260 vars[i++] = iter.next();
261 }
262 return vars;
263 }
264
265 /**
266 * Diagnostic print of expression structure. The abstract expression tree
267 * is written to the supplied output destination.
268 *
269 * @param out the expression presenter used to display the structure
270 */
271 @Override
272 public void explain(ExpressionPresenter out) throws XPathException {
273 out.startElement(isSlidingWindow() ? "slidingWindow" : "tumblingWindow");
274 out.startSubsidiaryElement("select");
275 getSequence().export(out);
276 out.endSubsidiaryElement();
277 out.startSubsidiaryElement("start");
278 getStartCondition().export(out);
279 out.endSubsidiaryElement();
280 if (endConditionOp != null) {
281 out.startSubsidiaryElement("end");
282 getEndCondition().export(out);
283 out.endSubsidiaryElement();
284 }
285 out.endElement();
286 }
287
288 /**
289 * Determine whether the current item is the start of a new window
290 *
291 * @param previous the item before the current item (null if the current item is the first)
292 * @param current the current item
293 * @param next the item after the current item (null if the current item is the last)
294 * @param position the position of the current item in the input sequence
295 * @param context the dynamic evaluation context
296 * @return true if the current item forms the start of a new window
297 * @throws XPathException if a failure occurs evaluating the conditions
298 */
299
300 protected boolean matchesStart(Item previous, Item current, Item next, int position, XPathContext context) throws XPathException {
301 WindowClause clause = this;
302 LocalVariableBinding binding;
303 binding = clause.getVariableBinding(WindowClause.START_ITEM);
304 if (binding != null) {
305 context.setLocalVariable(binding.getLocalSlotNumber(), current);
306 }
307 binding = clause.getVariableBinding(WindowClause.START_ITEM_POSITION);
308 if (binding != null) {
309 context.setLocalVariable(binding.getLocalSlotNumber(), new Int64Value(position));
310 }
311 binding = clause.getVariableBinding(WindowClause.START_NEXT_ITEM);
312 if (binding != null) {
313 context.setLocalVariable(binding.getLocalSlotNumber(), makeValue(next));
314 }
315 binding = clause.getVariableBinding(WindowClause.START_PREVIOUS_ITEM);
316 if (binding != null) {
317 context.setLocalVariable(binding.getLocalSlotNumber(), makeValue(previous));
318 }
319 return clause.getStartCondition().effectiveBooleanValue(context);
320 }
321
322 /**
323 * Determine whether the current item is the last item in a window
324 *
325 * @param window the window in question
326 * @param previous the item before the current item (null if the current item is the first)
327 * @param current the current item
328 * @param next the item after the current item (null if the current item is the last)
329 * @param position the position of the current item in the input sequence
330 * @param context the dynamic evaluation context
331 * @return true if the current item is the last item in the specified window
332 * @throws XPathException if a failure occurs evaluating the conditions
333 */
334
335 protected boolean matchesEnd(Window window, Item previous, Item current, Item next, int position, XPathContext context) throws XPathException {
336 WindowClause clause = this;
337 LocalVariableBinding binding;
338 binding = clause.getVariableBinding(WindowClause.START_ITEM);
339 if (binding != null) {
340 context.setLocalVariable(binding.getLocalSlotNumber(), window.startItem);
341 }
342 binding = clause.getVariableBinding(WindowClause.START_ITEM_POSITION);
343 if (binding != null) {
344 context.setLocalVariable(binding.getLocalSlotNumber(), new Int64Value(window.startPosition));
345 }
346 binding = clause.getVariableBinding(WindowClause.START_NEXT_ITEM);
347 if (binding != null) {
348 context.setLocalVariable(binding.getLocalSlotNumber(), makeValue(window.startNextItem));
349 }
350 binding = clause.getVariableBinding(WindowClause.START_PREVIOUS_ITEM);
351 if (binding != null) {
352 context.setLocalVariable(binding.getLocalSlotNumber(), makeValue(window.startPreviousItem));
353 }
354 binding = clause.getVariableBinding(WindowClause.END_ITEM);
355 if (binding != null) {
356 context.setLocalVariable(binding.getLocalSlotNumber(), current);
357 }
358 binding = clause.getVariableBinding(WindowClause.END_ITEM_POSITION);
359 if (binding != null) {
360 context.setLocalVariable(binding.getLocalSlotNumber(), new Int64Value(position));
361 }
362 binding = clause.getVariableBinding(WindowClause.END_NEXT_ITEM);
363 if (binding != null) {
364 context.setLocalVariable(binding.getLocalSlotNumber(), makeValue(next));
365 }
366 binding = clause.getVariableBinding(WindowClause.END_PREVIOUS_ITEM);
367 if (binding != null) {
368 context.setLocalVariable(binding.getLocalSlotNumber(), makeValue(previous));
369 }
370 return clause.getEndCondition().effectiveBooleanValue(context);
371 }
372
373 protected static Sequence<?> makeValue(/*@Nullable*/ Item item) {
374 if (item == null) {
375 return EmptySequence.getInstance();
376 } else {
377 return item;
378 }
379 }
380
381 /**
382 * Information about a window: the items making up the window, as well as the variables relating to the
383 * start and end of the window, and the status of the winoow in relation to the processing of the current
384 * input sequence.
385 */
386
387 protected static class Window {
388 public Item startItem;
389 public int startPosition;
390 public Item startPreviousItem;
391 public Item startNextItem;
392 public Item endItem;
393 public int endPosition = 0;
394 public Item endPreviousItem;
395 public Item endNextItem;
396 public List<Item<?>> contents;
397 public boolean isDespatched = false;
398
399 /**
400 * Ask whether we have found the last item in the window
401 *
402 * @return true if we have found the last item; false if we are still looking for it.
403 */
404 public boolean isFinished() {
405 return endPosition > 0;
406 }
407
408 /**
409 * Ask whether the tuple corresponding to this window has been despatched to the output tuple
410 * stream. This does not always happen immediately the end item is determined, because tuples
411 * corresponding to the various windows must be despached in order of their start items.
412 *
413 * @return true if the tuple corresponding to this window has been despatched.
414 */
415 public boolean isDespatched() {
416 return isDespatched;
417 }
418 }
419 }
420
421 // Copyright (c) 2011-2018 Saxonica Limited.