Debian Codegraph @

net/sf/saxon/functions/Sum.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.Location;
12 import net.sf.saxon.lib.ConversionRules;
13 import net.sf.saxon.om.Item;
14 import net.sf.saxon.om.Sequence;
15 import net.sf.saxon.om.SequenceIterator;
16 import net.sf.saxon.trans.XPathException;
17 import net.sf.saxon.type.*;
18 import net.sf.saxon.value.*;
19
20
21 /**
22 * Implementation of the fn:sum function
23 */
24 public class Sum extends FoldingFunction {
25
26 /*@NotNull*/
27 public ItemType getResultItemType(Expression[] args) {
28 TypeHierarchy th = getRetainedStaticContext().getConfiguration().getTypeHierarchy();
29 ItemType base = Atomizer.getAtomizedItemType(args[0], false, th);
30 if (base.equals(BuiltInAtomicType.UNTYPED_ATOMIC)) {
31 base = BuiltInAtomicType.DOUBLE;
32 }
33 if (Cardinality.allowsZero(args[0].getCardinality())) {
34 if (getArity() == 1) {
35 return Type.getCommonSuperType(base, BuiltInAtomicType.INTEGER, th);
36 } else {
37 return Type.getCommonSuperType(base, args[1].getItemType(), th);
38 }
39 } else {
40 return base.getPrimitiveItemType();
41 }
42 }
43
44 public int getCardinality(Expression[] arguments) {
45 if (getArity() == 1 || arguments[1].getCardinality() == 1) {
46 return StaticProperty.EXACTLY_ONE;
47 } else {
48 return StaticProperty.ALLOWS_ZERO_OR_ONE;
49 }
50 }
51
52 /**
53 * Create the Fold object which actually performs the evaluation.
54 *
55 * @param context the dynamic evaluation context
56 * @param additionalArguments the values of all arguments other than the first.
57 * @return the Fold object used to compute the function
58 */
59 @Override
60 public Fold getFold(XPathContext context, Sequence... additionalArguments) throws XPathException {
61 if (additionalArguments.length > 0) {
62 AtomicValue z = (AtomicValue)additionalArguments[0].head();
63 return new SumFold(context, z);
64 } else {
65 return new SumFold(context, Int64Value.ZERO);
66 }
67 }
68
69 /**
70 * Static method to compute a total, invoked from compiled bytecode
71 * @param in the sequence of items to be summed
72 * @param context dynamic context for evaluation
73 * @param locator expression location for diagnostics
74 * @return null if the input is empty, otherwise the total as defined by the semantics of the sum() function
75 * @throws XPathException if a dynamic error occurs
76 */
77
78 public static AtomicValue total(SequenceIterator<?> in, XPathContext context, Location locator) throws XPathException {
79 try {
80 SumFold fold = new SumFold(context, null);
81 in.forEachOrFail(fold::processItem);
82 return (AtomicValue)fold.result().head();
83 } catch (XPathException e) {
84 e.maybeSetLocation(locator);
85 throw e;
86 }
87 }
88
89 /**
90 * Implementation of Fold class to do the summation in push mode
91 */
92
93 private static class SumFold implements Fold {
94 private XPathContext context;
95 private AtomicValue zeroValue; // null means empty sequence
96 private AtomicValue data;
97 private boolean atStart = true;
98 private ConversionRules rules;
99 private StringConverter toDouble;
100
101 public SumFold(XPathContext context, AtomicValue zeroValue) {
102 this.context = context;
103 this.zeroValue = zeroValue;
104 this.rules = context.getConfiguration().getConversionRules();
105 this.toDouble = BuiltInAtomicType.DOUBLE.getStringConverter(rules);
106 }
107
108 /**
109 * Process one item in the input sequence, returning a new copy of the working data
110 *
111 * @param item the item to be processed from the input sequence
112 * @throws net.sf.saxon.trans.XPathException if a dynamic error occurs
113 */
114 public void processItem(Item<?> item) throws XPathException {
115 AtomicValue next = (AtomicValue)item;
116 if (atStart) {
117 atStart = false;
118 if (next instanceof UntypedAtomicValue) {
119 data = toDouble.convert(next).asAtomic();
120 return;
121 } else if (next instanceof NumericValue || next instanceof DayTimeDurationValue || next instanceof YearMonthDurationValue) {
122 data = next;
123 return;
124 } else {
125 XPathException err = new XPathException(
126 "Input to sum() contains a value of type " +
127 next.getPrimitiveType().getDisplayName() +
128 " which is neither numeric, nor a duration");
129 err.setXPathContext(context);
130 err.setErrorCode("FORG0006");
131 throw err;
132 }
133 }
134
135 if (data instanceof NumericValue) {
136 if (next instanceof UntypedAtomicValue) {
137 next = toDouble.convert(next).asAtomic();
138 } else if (!(next instanceof NumericValue)) {
139 XPathException err = new XPathException("Input to sum() contains a mix of numeric and non-numeric values");
140 err.setXPathContext(context);
141 err.setErrorCode("FORG0006");
142 throw err;
143 }
144 data = ArithmeticExpression.compute(data, Calculator.PLUS, next, context);
145 } else if (data instanceof DurationValue) {
146 if (!((data instanceof DayTimeDurationValue) || (data instanceof YearMonthDurationValue))) {
147 XPathException err = new XPathException("Input to sum() contains a duration that is neither a dayTimeDuration nor a yearMonthDuration");
148 err.setXPathContext(context);
149 err.setErrorCode("FORG0006");
150 throw err;
151 }
152 if (!(next instanceof DurationValue)) {
153 XPathException err = new XPathException("Input to sum() contains a mix of duration and non-duration values");
154 err.setXPathContext(context);
155 err.setErrorCode("FORG0006");
156 throw err;
157 }
158 data = ((DurationValue) data).add((DurationValue) next);
159 } else {
160 XPathException err = new XPathException(
161 "Input to sum() contains a value of type " +
162 data.getPrimitiveType().getDisplayName() +
163 " which is neither numeric, nor a duration");
164 err.setXPathContext(context);
165 err.setErrorCode("FORG0006");
166 throw err;
167 }
168 }
169
170 /**
171 * Ask whether the computation has completed. A function that can deliver its final
172 * result without reading the whole input should return true; this will be followed
173 * by a call on result() to deliver the final result.
174 * @return true if the result of the function is now available even though not all
175 * items in the sequence have been processed
176 */
177 public boolean isFinished() {
178 return data instanceof DoubleValue && data.isNaN();
179 }
180
181 /**
182 * Compute the final result of the function, when all the input has been processed
183 *
184 * @return the result of the function
185 */
186 public Sequence<?> result() {
187 if (atStart) {
188 return zeroValue == null ? EmptySequence.getInstance() : zeroValue;
189 } else {
190 return data;
191 }
192 }
193 }
194
195 public String getCompilerName() {
196 return "SumCompiler";
197 }
198
199 }
200