Debian Codegraph @

net/sf/saxon/expr/sort/SortExpression.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.sort;
9
10 import net.sf.saxon.expr.*;
11 import net.sf.saxon.expr.parser.*;
12 import net.sf.saxon.om.SequenceIterator;
13 import net.sf.saxon.trace.ExpressionPresenter;
14 import net.sf.saxon.trans.XPathException;
15 import net.sf.saxon.tree.iter.EmptyIterator;
16 import net.sf.saxon.type.ItemType;
17 import net.sf.saxon.value.AtomicValue;
18 import net.sf.saxon.value.Cardinality;
19 import net.sf.saxon.value.SequenceType;
20
21 /**
22 * Expression equivalent to the imaginary syntax
23 * expr sortby (sort-key)+
24 */
25
26 public class SortExpression extends Expression
27 implements SortKeyEvaluator {
28
29 private Operand selectOp;
30 private Operand sortOp;
31 private transient AtomicComparer[] comparators = null;
32 // created early if all comparators can be created statically
33 // transient because Java RuleBasedCollator is not serializable
34
35 /**
36 * Create a sort expression
37 *
38 * @param select the expression whose result is to be sorted
39 * @param sortKeys the set of sort key definitions to be used, in major to minor order
40 */
41
42 public SortExpression(Expression select, SortKeyDefinitionList sortKeys) {
43 selectOp = new Operand(this, select, OperandRole.FOCUS_CONTROLLING_SELECT);
44 sortOp = new Operand(this, sortKeys, OperandRole.ATOMIC_SEQUENCE);
45 adoptChildExpression(select);
46 adoptChildExpression(sortKeys);
47 }
48
49 /**
50 * Get a name identifying the kind of expression, in terms meaningful to a user.
51 *
52 * @return a name identifying the kind of expression, in terms meaningful to a user.
53 * The name will always be in the form of a lexical XML QName, and should match the name used
54 * in explain() output displaying the expression.
55 */
56
57 public String getExpressionName() {
58 return "sort";
59 }
60
61 /**
62 * Get the operand representing the expresion being sorted
63 */
64
65 public Operand getBaseOperand() {
66 return selectOp;
67 }
68
69 /**
70 * Get the expression defining the sequence being sorted
71 *
72 * @return the expression whose result is to be sorted
73 */
74
75 public Expression getBaseExpression() {
76 return getSelect();
77 }
78
79 /**
80 * Get the comparators, if known statically. Otherwise, return null.
81 *
82 * @return The comparators, if they have been allocated; otherwise null
83 */
84
85 public AtomicComparer[] getComparators() {
86 return comparators;
87 }
88
89 /**
90 * Get the immediate sub-expressions of this expression, with information about the relationship
91 * of each expression to its parent expression. Default implementation
92 * returns a zero-length array, appropriate for an expression that has no
93 * sub-expressions.
94 *
95 * @return an iterator containing the sub-expressions of this expression
96 */
97 @Override
98 public Iterable<Operand> operands() {
99 return operandList(selectOp, sortOp);
100 }
101
102 private static final OperandRole SAME_FOCUS_SORT_KEY =
103 new OperandRole(OperandRole.HIGHER_ORDER, OperandUsage.ABSORPTION, SequenceType.OPTIONAL_ATOMIC);
104 private static final OperandRole NEW_FOCUS_SORT_KEY =
105 new OperandRole(OperandRole.USES_NEW_FOCUS | OperandRole.HIGHER_ORDER, OperandUsage.ABSORPTION, SequenceType.OPTIONAL_ATOMIC);
106
107
108 /**
109 * Add a representation of this expression to a PathMap. The PathMap captures a map of the nodes visited
110 * by an expression in a source tree.
111 * <p>The default implementation of this method assumes that an expression does no navigation other than
112 * the navigation done by evaluating its subexpressions, and that the subexpressions are evaluated in the
113 * same context as the containing expression. The method must be overridden for any expression
114 * where these assumptions do not hold. For example, implementations exist for AxisExpression, ParentExpression,
115 * and RootExpression (because they perform navigation), and for the doc(), document(), and collection()
116 * functions because they create a new navigation root. Implementations also exist for PathExpression and
117 * FilterExpression because they have subexpressions that are evaluated in a different context from the
118 * calling expression.</p>
119 *
120 * @param pathMap the PathMap to which the expression should be added
121 * @param pathMapNodeSet the PathMapNodeSet to which the paths embodied in this expression should be added
122 * @return the pathMapNode representing the focus established by this expression, in the case where this
123 * expression is the first operand of a path expression or filter expression. For an expression that does
124 * navigation, it represents the end of the arc in the path map that describes the navigation route. For other
125 * expressions, it is the same as the input pathMapNode.
126 */
127
128 public PathMap.PathMapNodeSet addToPathMap(PathMap pathMap, PathMap.PathMapNodeSet pathMapNodeSet) {
129 PathMap.PathMapNodeSet target = getSelect().addToPathMap(pathMap, pathMapNodeSet);
130 for (SortKeyDefinition sortKeyDefinition : getSortKeyDefinitionList()) {
131 if (sortKeyDefinition.isSetContextForSortKey()) {
132 sortKeyDefinition.getSortKey().addToPathMap(pathMap, target);
133 } else {
134 sortKeyDefinition.getSortKey().addToPathMap(pathMap, pathMapNodeSet);
135 }
136 Expression e = sortKeyDefinition.getOrder();
137 if (e != null) {
138 e.addToPathMap(pathMap, pathMapNodeSet);
139 }
140 e = sortKeyDefinition.getCaseOrder();
141 if (e != null) {
142 e.addToPathMap(pathMap, pathMapNodeSet);
143 }
144 e = sortKeyDefinition.getDataTypeExpression();
145 if (e != null) {
146 e.addToPathMap(pathMap, pathMapNodeSet);
147 }
148 e = sortKeyDefinition.getLanguage();
149 if (e != null) {
150 e.addToPathMap(pathMap, pathMapNodeSet);
151 }
152 e = sortKeyDefinition.getCollationNameExpression();
153 if (e != null) {
154 e.addToPathMap(pathMap, pathMapNodeSet);
155 }
156 }
157 return target;
158 }
159
160 /**
161 * Type-check the expression
162 */
163
164 /*@NotNull*/
165 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
166
167 selectOp.typeCheck(visitor, contextInfo);
168
169 Expression select2 = getSelect();
170 if (select2 != getSelect()) {
171 adoptChildExpression(select2);
172 setSelect(select2);
173 }
174 if (!Cardinality.allowsMany(select2.getCardinality())) {
175 // exit now because otherwise the type checking of the sort key can cause spurious failures
176 return select2;
177 }
178 ItemType sortedItemType = getSelect().getItemType();
179
180 boolean allKeysFixed = true;
181 for (SortKeyDefinition sortKeyDefinition : getSortKeyDefinitionList()) {
182 if (!sortKeyDefinition.isFixed()) {
183 allKeysFixed = false;
184 break;
185 }
186 }
187
188 if (allKeysFixed) {
189 comparators = new AtomicComparer[getSortKeyDefinitionList().size()];
190 }
191
192 TypeChecker tc = visitor.getConfiguration().getTypeChecker(false);
193 for (int i = 0; i < getSortKeyDefinitionList().size(); i++) {
194 SortKeyDefinition sortKeyDef = getSortKeyDefinition(i);
195 Expression sortKey = sortKeyDef.getSortKey();
196 if (sortKeyDef.isSetContextForSortKey()) {
197 ContextItemStaticInfo cit = visitor.getConfiguration().makeContextItemStaticInfo(sortedItemType, false);
198 sortKey = sortKey.typeCheck(visitor, cit);
199 } else {
200 sortKey = sortKey.typeCheck(visitor, contextInfo);
201 }
202 if (sortKeyDef.isBackwardsCompatible()) {
203 sortKey = FirstItemExpression.makeFirstItemExpression(sortKey);
204 } else {
205 RoleDiagnostic role =
206 new RoleDiagnostic(RoleDiagnostic.INSTRUCTION, "xsl:sort/select", 0);
207 role.setErrorCode("XTTE1020");
208 sortKey = tc.staticTypeCheck(sortKey, SequenceType.OPTIONAL_ATOMIC, role, visitor);
209 //sortKey = CardinalityChecker.makeCardinalityChecker(sortKey, StaticProperty.ALLOWS_ZERO_OR_ONE, role);
210 }
211 sortKeyDef.setSortKey(sortKey, sortKeyDef.isSetContextForSortKey());
212 sortKeyDef.typeCheck(visitor, contextInfo);
213 if (sortKeyDef.isFixed()) {
214 AtomicComparer comp = sortKeyDef.makeComparator(
215 visitor.getStaticContext().makeEarlyEvaluationContext());
216 sortKeyDef.setFinalComparator(comp);
217 if (allKeysFixed) {
218 comparators[i] = comp;
219 }
220 }
221 if (sortKeyDef.isSetContextForSortKey() && !ExpressionTool.dependsOnFocus(sortKey)) {
222 visitor.getStaticContext().issueWarning(
223 "Sort key will have no effect because its value does not depend on the context item",
224 sortKey.getLocation());
225 }
226
227 }
228 return this;
229 }
230
231 /**
232 * Perform optimisation of an expression and its subexpressions.
233 * <p>This method is called after all references to functions and variables have been resolved
234 * to the declaration of the function or variable, and after all type checking has been done.</p>
235 *
236 * @param visitor an expression visitor
237 * @param contextItemType the static type of "." at the point where this expression is invoked.
238 * The parameter is set to null if it is known statically that the context item will be undefined.
239 * If the type of the context item is not known statically, the argument is set to
240 * {@link net.sf.saxon.type.Type#ITEM_TYPE}
241 * @return the original expression, rewritten if appropriate to optimize execution
242 * @throws XPathException if an error is discovered during this phase
243 * (typically a type error)
244 */
245
246 /*@NotNull*/
247 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType) throws XPathException {
248 selectOp.optimize(visitor, contextItemType);
249
250 // optimize the sort keys
251 ContextItemStaticInfo cit;
252 if (getSortKeyDefinition(0).isSetContextForSortKey()) {
253 ItemType sortedItemType = getSelect().getItemType();
254 cit = visitor.getConfiguration().makeContextItemStaticInfo(sortedItemType, false);
255 } else {
256 cit = contextItemType;
257 }
258 for (SortKeyDefinition sortKeyDefinition : getSortKeyDefinitionList()) {
259 Expression sortKey = sortKeyDefinition.getSortKey();
260 sortKey = sortKey.optimize(visitor, cit);
261 sortKeyDefinition.setSortKey(sortKey, true);
262 }
263 if (Cardinality.allowsMany(getSelect().getCardinality())) {
264 return this;
265 } else {
266 return getSelect();
267 }
268 }
269
270 /**
271 * Copy an expression. This makes a deep copy.
272 *
273 * @return the copy of the original expression
274 * @param rebindings variables that need to be re-bound
275 */
276
277 /*@NotNull*/
278 public Expression copy(RebindingMap rebindings) {
279 int len = getSortKeyDefinitionList().size();
280 SortKeyDefinition[] sk2 = new SortKeyDefinition[len];
281 for (int i = 0; i < len; i++) {
282 sk2[i] = getSortKeyDefinition(i).copy(rebindings);
283 }
284 SortExpression se2 = new SortExpression(getSelect().copy(rebindings), new SortKeyDefinitionList(sk2));
285 ExpressionTool.copyLocationInfo(this, se2);
286 se2.comparators = comparators;
287 return se2;
288 }
289
290 /**
291 * Test whether a given expression is one of the sort keys
292 *
293 * @param child the given expression
294 * @return true if the given expression is one of the sort keys
295 */
296
297 public boolean isSortKey(Expression child) {
298 for (SortKeyDefinition sortKeyDefinition : getSortKeyDefinitionList()) {
299 Expression exp = sortKeyDefinition.getSortKey();
300 if (exp == child) {
301 return true;
302 }
303 }
304 return false;
305 }
306
307 /**
308 * Determine the static cardinality
309 */
310
311 public int computeCardinality() {
312 return getSelect().getCardinality();
313 }
314
315 /**
316 * Determine the data type of the items returned by the expression, if possible
317 *
318 * @return a value such as Type.STRING, Type.BOOLEAN, Type.NUMBER, Type.NODE,
319 * or Type.ITEM (meaning not known in advance)
320 */
321
322 /*@NotNull*/
323 public ItemType getItemType() {
324 return getSelect().getItemType();
325 }
326
327 /**
328 * Get the static properties of this expression (other than its type). The result is
329 * bit-significant. These properties are used for optimizations. In general, if
330 * property bit is set, it is true, but if it is unset, the value is unknown.
331 */
332
333 public int computeSpecialProperties() {
334 int props = 0;
335 if (getSelect().hasSpecialProperty(StaticProperty.CONTEXT_DOCUMENT_NODESET)) {
336 props |= StaticProperty.CONTEXT_DOCUMENT_NODESET;
337 }
338 if (getSelect().hasSpecialProperty(StaticProperty.SINGLE_DOCUMENT_NODESET)) {
339 props |= StaticProperty.SINGLE_DOCUMENT_NODESET;
340 }
341 if (getSelect().hasSpecialProperty(StaticProperty.NO_NODES_NEWLY_CREATED)) {
342 props |= StaticProperty.NO_NODES_NEWLY_CREATED;
343 }
344 return props;
345 }
346
347 /**
348 * An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process().
349 * This method indicates which of these methods is provided directly. The other methods will always be available
350 * indirectly, using an implementation that relies on one of the other methods.
351 *
352 * @return the implementation method, for example {@link #ITERATE_METHOD} or {@link #EVALUATE_METHOD} or
353 * {@link #PROCESS_METHOD}
354 */
355 @Override
356 public int getImplementationMethod() {
357 return ITERATE_METHOD;
358 }
359
360 /**
361 * Enumerate the results of the expression
362 */
363
364 /*@NotNull*/
365 public SequenceIterator<?> iterate(XPathContext context) throws XPathException {
366
367 SequenceIterator<?> iter = getSelect().iterate(context);
368 if (iter instanceof EmptyIterator) {
369 return iter;
370 }
371
372 AtomicComparer[] comps = comparators;
373 if (comparators == null) {
374 int len = getSortKeyDefinitionList().size();
375 comps = new AtomicComparer[len];
376 for (int s = 0; s < len; s++) {
377 AtomicComparer comp = getSortKeyDefinition(s).getFinalComparator();
378 if (comp == null) {
379 comp = getSortKeyDefinition(s).makeComparator(context);
380 }
381 comps[s] = comp;
382 }
383 }
384 iter = new SortedIterator(context, iter, this, comps, getSortKeyDefinition(0).isSetContextForSortKey());
385 ((SortedIterator) iter).setHostLanguage(getPackageData().getHostLanguage());
386 return iter;
387 }
388
389 /**
390 * Callback for evaluating the sort keys
391 */
392
393 public AtomicValue evaluateSortKey(int n, XPathContext c) throws XPathException {
394 return (AtomicValue) getSortKeyDefinition(n).getSortKey().evaluateItem(c);
395 }
396
397 @Override
398 public String toShortString() {
399 return "sort(" + getBaseExpression().toShortString() + ")";
400 }
401
402
403 /**
404 * Get the (partial) name of a class that supports streaming of this kind of expression
405 *
406 * @return the partial name of a class that can be instantiated to provide streaming support in Saxon-EE,
407 * or null if there is no such class
408 */
409 @Override
410 public String getStreamerName() {
411 return "SortExpression";
412 }
413
414 /**
415 * Diagnostic print of expression structure. The abstract expression tree
416 * is written to the supplied output destination.
417 */
418
419 public void export(ExpressionPresenter out) throws XPathException {
420 out.startElement("sort", this);
421 out.setChildRole("select");
422 getSelect().export(out);
423 getSortKeyDefinitionList().export(out);
424 out.endElement();
425 }
426
427 public Expression getSelect() {
428 return selectOp.getChildExpression();
429 }
430
431 public void setSelect(Expression select) {
432 selectOp.setChildExpression(select);
433 }
434
435 public SortKeyDefinitionList getSortKeyDefinitionList() {
436 return (SortKeyDefinitionList)sortOp.getChildExpression();
437 }
438
439 public SortKeyDefinition getSortKeyDefinition(int i) {
440 return getSortKeyDefinitionList().getSortKeyDefinition(i);
441 }
442
443 public void setSortKeyDefinitionList(SortKeyDefinitionList skd) {
444 sortOp.setChildExpression(skd);
445 }
446 }
447