Debian Codegraph @

net/sf/saxon/expr/sort/DocumentSorter.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.Configuration;
11 import net.sf.saxon.expr.*;
12 import net.sf.saxon.expr.parser.*;
13 import net.sf.saxon.om.AxisInfo;
14 import net.sf.saxon.om.SequenceIterator;
15 import net.sf.saxon.pattern.AnyNodeTest;
16 import net.sf.saxon.pattern.Pattern;
17 import net.sf.saxon.trace.ExpressionPresenter;
18 import net.sf.saxon.trans.XPathException;
19 import net.sf.saxon.type.TypeHierarchy;
20 import net.sf.saxon.value.Cardinality;
21 import net.sf.saxon.value.SequenceType;
22
23
24 /**
25 * A DocumentSorter is an expression that sorts a sequence of nodes into
26 * document order.
27 */
28 public class DocumentSorter extends UnaryExpression {
29
30 private ItemOrderComparer comparer;
31
32 public DocumentSorter(Expression base) {
33 super(base);
34 int props = base.getSpecialProperties();
35 if (((props & StaticProperty.CONTEXT_DOCUMENT_NODESET) != 0) ||
36 (props & StaticProperty.SINGLE_DOCUMENT_NODESET) != 0) {
37 comparer = LocalOrderComparer.getInstance();
38 } else {
39 comparer = GlobalOrderComparer.getInstance();
40 }
41 }
42
43 public DocumentSorter(Expression base, boolean intraDocument) {
44 super(base);
45 if (intraDocument) {
46 comparer = LocalOrderComparer.getInstance();
47 } else {
48 comparer = GlobalOrderComparer.getInstance();
49 }
50 }
51
52 protected OperandRole getOperandRole() {
53 return OperandRole.SAME_FOCUS_ACTION;
54 }
55
56 /**
57 * Get a name identifying the kind of expression, in terms meaningful to a user.
58 *
59 * @return a name identifying the kind of expression, in terms meaningful to a user.
60 * The name will always be in the form of a lexical XML QName, and should match the name used
61 * in explain() output displaying the expression.
62 */
63
64 public String getExpressionName() {
65 return "docOrder";
66 }
67
68 public ItemOrderComparer getComparer() {
69 return comparer;
70 }
71
72 /*@NotNull*/
73 public Expression simplify() throws XPathException {
74 Expression operand = getBaseExpression().simplify();
75 if (operand.hasSpecialProperty(StaticProperty.ORDERED_NODESET)) {
76 // this can happen as a result of further simplification
77 return operand;
78 }
79 return this;
80 }
81
82 @Override
83 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
84 Expression e2 = super.typeCheck(visitor, contextInfo);
85 if (e2 != this) {
86 return e2;
87 }
88 TypeHierarchy th = visitor.getConfiguration().getTypeHierarchy();
89 if (th.relationship(getBaseExpression().getItemType(), AnyNodeTest.getInstance()) == TypeHierarchy.DISJOINT) {
90 return getBaseExpression();
91 }
92 RoleDiagnostic role = new RoleDiagnostic(RoleDiagnostic.MISC, "document-order sorter", 0);
93 Expression operand = visitor.getConfiguration().getTypeChecker(false).staticTypeCheck(
94 getBaseExpression(), SequenceType.NODE_SEQUENCE, role, visitor);
95 setBaseExpression(operand);
96 return this;
97 }
98
99 /*@NotNull*/
100 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
101 getOperand().optimize(visitor, contextInfo);
102 Expression sortable = getBaseExpression();
103 boolean tryHarder = sortable.isStaticPropertiesKnown();
104 while (true) {
105 if (sortable.hasSpecialProperty(StaticProperty.ORDERED_NODESET)) {
106 // this can happen as a result of further simplification
107 return sortable;
108 }
109 if (!Cardinality.allowsMany(sortable.getCardinality())) {
110 return sortable;
111 }
112
113 if (sortable instanceof SlashExpression) {
114 SlashExpression slash = (SlashExpression)sortable;
115
116 // Bug 3389: try to rewrite sort(conditionalSort($var/child::x) / child::y)
117 // as conditionalSort($var, (child::x/child::y))
118 Expression lhs = slash.getLhsExpression();
119 Expression rhs = slash.getRhsExpression();
120 if (lhs instanceof ConditionalSorter &&
121 slash.getRhsExpression().hasSpecialProperty(StaticProperty.PEER_NODESET)) {
122 ConditionalSorter c = (ConditionalSorter) lhs;
123 DocumentSorter d = c.getDocumentSorter();
124 Expression condition = c.getCondition();
125 Expression s = new SlashExpression(d.getBaseExpression(), rhs);
126 s = s.optimize(visitor, contextInfo);
127 return new ConditionalSorter(condition, new DocumentSorter(s));
128 }
129 // docOrder(docOrder(A)/B) can be rewritten as docOrder(A/B). However, this may not always
130 // be wise, because the inner docOrder might eliminate many duplicates, reducing the cost
131 // of the /B operation. We therefore do it only if B is a low-cost operation.
132 if (lhs instanceof DocumentSorter && rhs instanceof AxisExpression && ((AxisExpression)rhs).getAxis() == AxisInfo.CHILD) {
133 SlashExpression s1 = new SlashExpression(((DocumentSorter)lhs).getBaseExpression(), rhs);
134 ExpressionTool.copyLocationInfo(this, s1);
135 return new DocumentSorter(s1).optimize(visitor, contextInfo);
136 }
137 // docOrder(A/B) can be rewritten as docOrder(B) in the case where B returns nodes
138 // and is independent of the focus. We already know it returns nodes otherwise we wouldn't be here.
139 if (!ExpressionTool.dependsOnFocus(rhs) &&
140 !rhs.hasSpecialProperty(StaticProperty.HAS_SIDE_EFFECTS) &&
141 rhs.hasSpecialProperty(StaticProperty.NO_NODES_NEWLY_CREATED)) {
142 setBaseExpression(slash.getRhsExpression());
143 return optimize(visitor, contextInfo);
144 }
145 }
146 // Try once more after recomputing the static properties of the expression
147 if (tryHarder) {
148 sortable.resetLocalStaticProperties();
149 tryHarder = false;
150 } else {
151 break;
152 }
153 }
154 if (sortable instanceof SlashExpression && !visitor.isOptimizeForStreaming() && !(getParentExpression() instanceof ConditionalSorter)) {
155 return visitor.obtainOptimizer().makeConditionalDocumentSorter(
156 this, (SlashExpression) sortable);
157 }
158 return this;
159 }
160
161 /**
162 * Return the net cost of evaluating this expression, excluding the cost of evaluating
163 * its operands. We take the cost of evaluating a simple scalar comparison or arithmetic
164 * expression as 1 (one).
165 *
166 * @return the intrinsic cost of this operation, excluding the costs of evaluating
167 * the operands
168 */
169 @Override
170 public int getNetCost() {
171 return 30;
172 }
173
174 /**
175 * Replace this expression by a simpler expression that delivers the results without regard
176 * to order.
177 *
178 * @param retainAllNodes set to true if the result must contain exactly the same nodes as the
179 * original; set to false if the result can eliminate (or introduce) duplicates.
180 * @param forStreaming set to true if optimizing for streaming
181 */
182 @Override
183 public Expression unordered(boolean retainAllNodes, boolean forStreaming) throws XPathException {
184 Expression operand = getBaseExpression().unordered(retainAllNodes, forStreaming);
185 if (operand.hasSpecialProperty(StaticProperty.ORDERED_NODESET)) {
186 return operand;
187 }
188 if (!retainAllNodes) {
189 return operand;
190 } else if (operand instanceof SlashExpression) {
191 // handle the common case of //section/head where it is safe to remove sorting, because
192 // no duplicates need to be removed
193 SlashExpression exp = (SlashExpression)operand;
194 Expression a = exp.getSelectExpression();
195 Expression b = exp.getActionExpression();
196 a = ExpressionTool.unfilteredExpression(a, false);
197 b = ExpressionTool.unfilteredExpression(b, false);
198 if (a instanceof AxisExpression &&
199 (((AxisExpression)a).getAxis() == AxisInfo.DESCENDANT || ((AxisExpression)a).getAxis() == AxisInfo.DESCENDANT_OR_SELF) &&
200 b instanceof AxisExpression &&
201 ((AxisExpression)b).getAxis() == AxisInfo.CHILD) {
202 return operand.unordered(retainAllNodes, false);
203 }
204 }
205 setBaseExpression(operand);
206 return this;
207 }
208
209
210 public int computeSpecialProperties() {
211 return getBaseExpression().getSpecialProperties() | StaticProperty.ORDERED_NODESET;
212 }
213
214 /**
215 * Copy an expression. This makes a deep copy.
216 *
217 * @return the copy of the original expression
218 * @param rebindings variables that need to be re-bound
219 */
220
221 /*@NotNull*/
222 public Expression copy(RebindingMap rebindings) {
223 DocumentSorter ds = new DocumentSorter(getBaseExpression().copy(rebindings));
224 ExpressionTool.copyLocationInfo(this, ds);
225 return ds;
226 }
227
228 /**
229 * Convert this expression to an equivalent XSLT pattern
230 *
231 * @param config the Saxon configuration
232 * @return the equivalent pattern
233 * @throws net.sf.saxon.trans.XPathException
234 * if conversion is not possible
235 */
236 @Override
237 public Pattern toPattern(Configuration config) throws XPathException {
238 return getBaseExpression().toPattern(config);
239 }
240
241 /**
242 * An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process().
243 * This method indicates which of these methods is provided directly. The other methods will always be available
244 * indirectly, using an implementation that relies on one of the other methods.
245 *
246 * @return the implementation method, for example {@link #ITERATE_METHOD} or {@link #EVALUATE_METHOD} or
247 * {@link #PROCESS_METHOD}
248 */
249 @Override
250 public int getImplementationMethod() {
251 return ITERATE_METHOD;
252 }
253
254 /*@NotNull*/
255 public SequenceIterator<?> iterate(XPathContext context) throws XPathException {
256 return new DocumentOrderIterator(getBaseExpression().iterate(context), comparer);
257 }
258
259 public boolean effectiveBooleanValue(XPathContext context) throws XPathException {
260 return getBaseExpression().effectiveBooleanValue(context);
261 }
262
263 /**
264 * Diagnostic print of expression structure. The abstract expression tree
265 * is written to the supplied output destination.
266 */
267
268 public void export(ExpressionPresenter out) throws XPathException {
269 out.startElement("docOrder", this);
270 out.emitAttribute("intra", comparer instanceof LocalOrderComparer ? "1" : "0");
271 getBaseExpression().export(out);
272 out.endElement();
273 }
274
275
276 /**
277 * Get the (partial) name of a class that supports streaming of this kind of expression
278 *
279 * @return the partial name of a class that can be instantiated to provide streaming support in Saxon-EE,
280 * or null if there is no such class
281 */
282 @Override
283 public String getStreamerName() {
284 return "DocumentSorterAdjunct";
285 }
286 }
287