Debian Codegraph @

net/sf/saxon/functions/Minimax.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.functions;
9
10 import net.sf.saxon.expr.*;
11 import net.sf.saxon.expr.parser.ContextItemStaticInfo;
12 import net.sf.saxon.expr.parser.ExpressionVisitor;
13 import net.sf.saxon.expr.sort.AtomicComparer;
14 import net.sf.saxon.expr.sort.DescendingComparer;
15 import net.sf.saxon.expr.sort.GenericAtomicComparer;
16 import net.sf.saxon.lib.ConversionRules;
17 import net.sf.saxon.om.Sequence;
18 import net.sf.saxon.om.SequenceIterator;
19 import net.sf.saxon.om.ZeroOrOne;
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.*;
24 import net.sf.saxon.value.*;
25
26 import java.util.Properties;
27
28
29 /**
30 * This class implements the min() and max() functions, with the collation argument already known.
31 */
32
33 public abstract class Minimax extends CollatingFunctionFixed {
34
35
36 private PlainType argumentType = BuiltInAtomicType.ANY_ATOMIC;
37 private boolean ignoreNaN = false;
38
39
40 /**
41 * Method to be implemented in subclasses to indicate whether the function implements
42 * fn:min() or fn:max()
43 * @return true if this is the fn:max() function
44 */
45
46 public abstract boolean isMaxFunction();
47
48 /**
49 * Indicate whether NaN values should be ignored. For the external min() and max() function, a
50 * NaN value in the input causes the result to be NaN. Internally, however, min() and max() are also
51 * used in such a way that NaN values should be ignored. This is the case for internally-generated min() and max()
52 * functions used to support general comparisons.
53 *
54 * @param ignore true if NaN values are to be ignored when computing the min or max.
55 */
56
57 public void setIgnoreNaN(boolean ignore) {
58 ignoreNaN = ignore;
59 }
60
61 /**
62 * Test whether NaN values are to be ignored
63 *
64 * @return true if NaN values are to be ignored. This is the case for internally-generated min() and max()
65 * functions used to support general comparisons
66 */
67
68 public boolean isIgnoreNaN() {
69 return ignoreNaN;
70 }
71
72
73 public AtomicComparer getComparer() {
74 return getPreAllocatedAtomicComparer();
75 }
76
77 public PlainType getArgumentType() {
78 return argumentType;
79 }
80
81 /**
82 * Static analysis: preallocate a comparer if possible
83 */
84
85 @Override
86 public void supplyTypeInformation(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType, Expression[] arguments) {
87 ItemType type = arguments[0].getItemType();
88 argumentType = type.getAtomizedItemType();
89 if (argumentType instanceof AtomicType) {
90 if (argumentType == BuiltInAtomicType.UNTYPED_ATOMIC) {
91 argumentType = BuiltInAtomicType.DOUBLE;
92 }
93 preAllocateComparer((AtomicType) argumentType, (AtomicType) argumentType, visitor.getStaticContext());
94 }
95 }
96
97 /*@NotNull*/
98 public ItemType getResultItemType(Expression[] args) {
99 TypeHierarchy th = getRetainedStaticContext().getConfiguration().getTypeHierarchy();
100 ItemType base = Atomizer.getAtomizedItemType(args[0], false, th);
101 if (base.equals(BuiltInAtomicType.UNTYPED_ATOMIC)) {
102 base = BuiltInAtomicType.DOUBLE;
103 }
104 return base.getPrimitiveItemType();
105 }
106
107 /**
108 * Determine the cardinality of the function.
109 */
110
111 public int getCardinality(Expression[] arguments) {
112 if (!Cardinality.allowsZero(arguments[0].getCardinality())) {
113 return StaticProperty.EXACTLY_ONE;
114 } else {
115 return StaticProperty.ALLOWS_ZERO_OR_ONE;
116 }
117 }
118
119 @Override
120 public Expression makeOptimizedFunctionCall(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo, Expression... arguments) throws XPathException {
121 // test for a singleton: this often happens after (A<B) is rewritten as (min(A) lt max(B))
122 int card = arguments[0].getCardinality();
123 if (!Cardinality.allowsMany(card)) {
124 ItemType it = arguments[0].getItemType().getPrimitiveItemType();
125 if (it instanceof BuiltInAtomicType && ((BuiltInAtomicType)it).isOrdered(false)) {
126 TypeHierarchy th = visitor.getConfiguration().getTypeHierarchy();
127 if (th.relationship(it, BuiltInAtomicType.UNTYPED_ATOMIC) != TypeHierarchy.DISJOINT) {
128 return UntypedSequenceConverter.makeUntypedSequenceConverter(
129 visitor.getConfiguration(), arguments[0], BuiltInAtomicType.DOUBLE).typeCheck(visitor, contextInfo);
130 } else {
131 return arguments[0];
132 }
133 }
134 }
135 return null;
136 }
137
138
139 public AtomicComparer getAtomicComparer(XPathContext context) {
140 AtomicComparer comparer = getPreAllocatedAtomicComparer();
141 if (comparer != null) {
142 return comparer;
143 }
144 PlainType type = argumentType.getPrimitiveItemType();
145 if (type.equals(BuiltInAtomicType.UNTYPED_ATOMIC)) {
146 type = BuiltInAtomicType.DOUBLE;
147 }
148 BuiltInAtomicType prim = (BuiltInAtomicType) type;
149 return GenericAtomicComparer.makeAtomicComparer(prim, prim, getStringCollator(), context);
150 }
151
152 /**
153 * Static method to evaluate the minimum or maximum of a sequence
154 *
155 * @param iter Iterator over the input sequence
156 * @param isMaxFunction true for the max() function, false for min()
157 * @param atomicComparer an AtomicComparer used to compare values
158 * @param ignoreNaN true if NaN values are to be ignored
159 * @param context dynamic evaluation context
160 * @return the min or max value in the sequence, according to the rules of the fn:min() or fn:max() functions
161 * @throws XPathException typically if non-comparable values are found in the sequence
162 */
163 /*@Nullable*/
164 public static AtomicValue minimax(SequenceIterator iter, boolean isMaxFunction,
165 AtomicComparer atomicComparer, boolean ignoreNaN, XPathContext context)
166 throws XPathException {
167
168 ConversionRules rules = context.getConfiguration().getConversionRules();
169 StringToDouble converter = context.getConfiguration().getConversionRules().getStringToDoubleConverter();
170 boolean foundDouble = false;
171 boolean foundFloat = false;
172 boolean foundNaN = false;
173 boolean foundString = false;
174
175 // For the max function, reverse the collator
176 if (isMaxFunction) {
177 atomicComparer = new DescendingComparer(atomicComparer);
178 }
179 atomicComparer = atomicComparer.provideContext(context);
180
181 // Process the sequence, retaining the min (or max) so far. This will be an actual value found
182 // in the sequence. At the same time, remember if a double and/or float has been encountered
183 // anywhere in the sequence, and if so, convert the min/max to double/float at the end. This is
184 // done to avoid problems if a decimal is converted first to a float and then to a double.
185
186 // Get the first value in the sequence, ignoring any NaN values if we are ignoring NaN values
187 AtomicValue min;
188 AtomicValue prim;
189
190 while (true) { // loop only repeats if first item is NaN
191 min = (AtomicValue) iter.next();
192 if (min == null) {
193 return null;
194 }
195 prim = min;
196 if (min instanceof UntypedAtomicValue) {
197 try {
198 min = new DoubleValue(converter.stringToNumber(min.getStringValueCS()));
199 prim = min;
200 foundDouble = true;
201 } catch (NumberFormatException e) {
202 XPathException de = new XPathException("Failure converting " + Err.wrap(min.getStringValueCS()) + " to a number");
203 de.setErrorCode("FORG0001");
204 de.setXPathContext(context);
205 throw de;
206 }
207 } else {
208 if (prim instanceof DoubleValue) {
209 foundDouble = true;
210 } else if (prim instanceof FloatValue) {
211 foundFloat = true;
212 } else if (prim instanceof StringValue && !(prim instanceof AnyURIValue)) {
213 foundString = true;
214 }
215 }
216 if (prim.isNaN()) {
217 // if there's a NaN in the sequence, return NaN, unless ignoreNaN is set
218 if (ignoreNaN) {
219 //continue; // ignore the NaN and treat the next item as the first real one
220 } else if (prim instanceof DoubleValue) {
221 return min; // return double NaN
222 } else {
223 // we can't ignore a float NaN, because we might need to promote it to a double NaN
224 foundNaN = true;
225 min = FloatValue.NaN;
226 break;
227 }
228 } else {
229 if (!prim.getPrimitiveType().isOrdered(false)) {
230 XPathException de = new XPathException("Type " + prim.getPrimitiveType() + " is not an ordered type");
231 de.setErrorCode("FORG0006");
232 de.setIsTypeError(true);
233 de.setXPathContext(context);
234 throw de;
235 }
236 break; // process the rest of the sequence
237 }
238 }
239
240 while (true) {
241 AtomicValue test = (AtomicValue) iter.next();
242 if (test == null) {
243 break;
244 }
245 AtomicValue test2 = test;
246 prim = test2;
247 if (test instanceof UntypedAtomicValue) {
248 try {
249 test2 = new DoubleValue(converter.stringToNumber(test.getStringValueCS()));
250 if (foundNaN) {
251 return DoubleValue.NaN;
252 }
253 prim = test2;
254 foundDouble = true;
255 } catch (NumberFormatException e) {
256 XPathException de = new XPathException("Failure converting " + Err.wrap(test.getStringValueCS()) + " to a number");
257 de.setErrorCode("FORG0001");
258 de.setXPathContext(context);
259 throw de;
260 }
261 } else {
262 if (prim instanceof DoubleValue) {
263 if (foundNaN) {
264 return DoubleValue.NaN;
265 }
266 foundDouble = true;
267 } else if (prim instanceof FloatValue) {
268 foundFloat = true;
269 } else if (prim instanceof StringValue && !(prim instanceof AnyURIValue)) {
270 foundString = true;
271 }
272 }
273 if (prim.isNaN()) {
274 // if there's a double NaN in the sequence, return NaN, unless ignoreNaN is set
275 if (ignoreNaN) {
276 //continue;
277 } else if (foundDouble) {
278 return DoubleValue.NaN;
279 } else {
280 // can't return float NaN until we know whether to promote it
281 foundNaN = true;
282 }
283 } else {
284 try {
285 if (atomicComparer.compareAtomicValues(prim, min) < 0) {
286 min = test2;
287 }
288 } catch (ClassCastException err) {
289 if (min.getItemType() == test2.getItemType()) {
290 // internal error
291 throw err;
292 } else {
293 XPathException de = new XPathException("Cannot compare " + min.getItemType() + " with " + test2.getItemType());
294 de.setErrorCode("FORG0006");
295 de.setIsTypeError(true);
296 de.setXPathContext(context);
297 throw de;
298 }
299 }
300 }
301 }
302 if (foundNaN) {
303 return FloatValue.NaN;
304 }
305 if (foundDouble) {
306 if (!(min instanceof DoubleValue)) {
307 min = Converter.convert(min, BuiltInAtomicType.DOUBLE, rules);
308 }
309 } else if (foundFloat) {
310 if (!(min instanceof FloatValue)) {
311 min = Converter.convert(min, BuiltInAtomicType.FLOAT, rules);
312 }
313 } else if (min instanceof AnyURIValue && foundString) {
314 min = Converter.convert(min, BuiltInAtomicType.STRING, rules);
315 }
316 return min;
317
318 }
319
320 /**
321 * Evaluate the function
322 *
323 * @param context the dynamic evaluation context
324 * @param arguments the values of the arguments, supplied as Sequences
325 * @return the result of the evaluation, in the form of a Sequence
326 * @throws net.sf.saxon.trans.XPathException if a dynamic error occurs during the evaluation of the expression
327 */
328 public ZeroOrOne<AtomicValue> call(XPathContext context, Sequence[] arguments) throws XPathException {
329 return new ZeroOrOne<>(
330 minimax(arguments[0].iterate(), isMaxFunction(), getAtomicComparer(context), ignoreNaN, context));
331 }
332
333 @Override
334 public void exportAttributes(ExpressionPresenter out) {
335 super.exportAttributes(out);
336 if (ignoreNaN) {
337 out.emitAttribute("flags", "i");
338 }
339 }
340
341 @Override
342 public void importAttributes(Properties attributes) throws XPathException {
343 super.importAttributes(attributes);
344 String flags = attributes.getProperty("flags");
345 if (flags != null && flags.contains("i")) {
346 setIgnoreNaN(true);
347 }
348 }
349
350 public String getStreamerName() {
351 return "Minimax";
352 }
353
354 /**
355 * Concrete subclass to define the fn:min() function
356 */
357
358 public static class Min extends Minimax {
359 public boolean isMaxFunction() {
360 return false;
361 }
362 }
363
364 /**
365 * Concrete subclass to define the fn:max() function
366 */
367
368 public static class Max extends Minimax {
369 public boolean isMaxFunction() {
370 return true;
371 }
372 }
373
374 }
375