Debian Codegraph @

net/sf/saxon/expr/NumberSequenceFormatter.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;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.expr.instruct.NumberInstruction;
12 import net.sf.saxon.expr.number.NumberFormatter;
13 import net.sf.saxon.expr.parser.ContextItemStaticInfo;
14 import net.sf.saxon.expr.parser.ExpressionTool;
15 import net.sf.saxon.expr.parser.ExpressionVisitor;
16 import net.sf.saxon.expr.parser.RebindingMap;
17 import net.sf.saxon.functions.Number_1;
18 import net.sf.saxon.lib.ConversionRules;
19 import net.sf.saxon.lib.Numberer;
20 import net.sf.saxon.om.SequenceIterator;
21 import net.sf.saxon.trace.ExpressionPresenter;
22 import net.sf.saxon.trans.XPathException;
23 import net.sf.saxon.type.*;
24 import net.sf.saxon.value.*;
25
26 import java.math.BigInteger;
27 import java.util.ArrayList;
28 import java.util.List;
29
30 /**
31 * This expression performs the formatting part of the logic of the xsl:number instruction
32 * It takes as input a sequence of integers, which may either be supplied directly as the
33 * value attribute of xsl:number, or may be computed by counting nodes. The expression
34 * returns a string.
35 */
36
37 public class NumberSequenceFormatter extends Expression {
38
39 private Operand valueOp;
40 private Operand formatOp;
41 private Operand groupSizeOp;
42 private Operand groupSeparatorOp;
43 private Operand letterValueOp;
44 private Operand ordinalOp;
45 private Operand startAtOp;
46 private Operand langOp;
47
48 private NumberFormatter formatter = null;
49 private Numberer numberer = null;
50 private boolean backwardsCompatible;
51
52 /**
53 * Construct a NumberSequenceFormatter
54 *
55 * @param value the expression supplied in the value attribute, or
56 * the {@link NumberInstruction} which computes the place-marker
57 * @param format the expression supplied in the format attribute
58 * @param groupSize the expression supplied in the group-size attribute
59 * @param groupSeparator the expression supplied in the grouping-separator attribute
60 * @param letterValue the expression supplied in the letter-value attribute
61 * @param ordinal the expression supplied in the ordinal attribute
62 * @param startAt the expression supplied in the start-at attribute
63 * @param lang the expression supplied in the lang attribute
64 * @param formatter A NumberFormatter to be used
65 * @param backwardsCompatible true if running in 1.0 compatibility mode with a real value attribute
66 */
67
68 public NumberSequenceFormatter(Expression value,
69 Expression format,
70 Expression groupSize,
71 Expression groupSeparator,
72 Expression letterValue,
73 Expression ordinal,
74 Expression startAt,
75 Expression lang,
76 NumberFormatter formatter,
77 boolean backwardsCompatible) {
78
79 if (value != null) {
80 valueOp = new Operand(this, value, OperandRole.SINGLE_ATOMIC);
81 }
82 if (format != null) {
83 formatOp = new Operand(this, format, OperandRole.SINGLE_ATOMIC);
84 }
85 if (groupSize != null) {
86 groupSizeOp = new Operand(this, groupSize, OperandRole.SINGLE_ATOMIC);
87 }
88 if (groupSeparator != null) {
89 groupSeparatorOp = new Operand(this, groupSeparator, OperandRole.SINGLE_ATOMIC);
90 }
91 if (letterValue != null) {
92 letterValueOp = new Operand(this, letterValue, OperandRole.SINGLE_ATOMIC);
93 }
94 if (ordinal != null) {
95 ordinalOp = new Operand(this, ordinal, OperandRole.SINGLE_ATOMIC);
96 }
97 //if (startAt != null) {
98 startAtOp = new Operand(this, startAt, OperandRole.SINGLE_ATOMIC);
99 //}
100 if (lang != null) {
101 langOp = new Operand(this, lang, OperandRole.SINGLE_ATOMIC);
102 }
103
104 this.formatter = formatter;
105 this.backwardsCompatible = backwardsCompatible;
106
107 if (formatter == null && format instanceof StringLiteral) {
108 this.formatter = new NumberFormatter();
109 this.formatter.prepare(((StringLiteral)format).getStringValue());
110 }
111 }
112
113 /**
114 * Simplify an expression. This performs any static optimization (by rewriting the expression
115 * as a different expression). The default implementation simplifies its operands.
116 *
117 * @return the simplified expression (or the original if unchanged, or if modified in-situ)
118 * @throws XPathException if an error is discovered during expression
119 * rewriting
120 */
121 @Override
122 public Expression simplify() throws XPathException {
123 if (valueOp != null && !valueOp.getChildExpression().getItemType().isPlainType()) {
124 valueOp.setChildExpression(Atomizer.makeAtomizer(valueOp.getChildExpression(), null));
125 }
126 preallocateNumberer(getConfiguration());
127 return super.simplify();
128 }
129
130 public void preallocateNumberer(Configuration config) throws XPathException {
131 if (langOp == null) {
132 numberer = config.makeNumberer(null, null);
133 } else {
134 if (langOp.getChildExpression() instanceof StringLiteral) {
135 String language = ((StringLiteral) langOp.getChildExpression()).getStringValue();
136 if (!language.isEmpty()) {
137 ValidationFailure vf = StringConverter.StringToLanguage.INSTANCE.validate(language);
138 if (vf != null) {
139 langOp.setChildExpression(new StringLiteral(StringValue.EMPTY_STRING));
140 throw new XPathException("The lang attribute must be a valid language code", "XTDE0030");
141 }
142 }
143 numberer = config.makeNumberer(language, null);
144 } // else we allocate a numberer at run-time
145 }
146 }
147
148
149 @Override
150 public Iterable<Operand> operands() {
151 return operandSparseList(valueOp, formatOp, groupSizeOp,
152 groupSeparatorOp, letterValueOp, ordinalOp, startAtOp, langOp);
153 }
154
155 private boolean isFixed(Operand op) {
156 return op==null || op.getChildExpression() instanceof Literal;
157 }
158
159 private boolean hasFixedOperands() {
160 for (Operand o : operands()) {
161 if (!isFixed(o)) {
162 return false;
163 }
164 }
165 return true;
166 }
167
168 @Override
169 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
170 optimizeChildren(visitor, contextInfo);
171 if (hasFixedOperands()) {
172 StringValue val = evaluateItem(visitor.makeDynamicContext());
173 StringLiteral literal = new StringLiteral(val);
174 ExpressionTool.copyLocationInfo(this, literal);
175 return literal;
176 } else {
177 return this;
178 }
179 }
180
181 /**
182 * Copy an expression. This makes a deep copy.
183 *
184 * @return the copy of the original expression
185 * @param rebindings variables that need to be re-bound
186 */
187
188 /*@NotNull*/
189 public Expression copy(RebindingMap rebindings) {
190 NumberSequenceFormatter exp = new NumberSequenceFormatter(
191 copy(valueOp), copy(formatOp),
192 copy(groupSizeOp), copy(groupSeparatorOp), copy(letterValueOp),
193 copy(ordinalOp), copy(startAtOp),
194 copy(langOp), formatter, backwardsCompatible);
195 ExpressionTool.copyLocationInfo(this, exp);
196 return exp;
197 }
198
199 private Expression copy(Operand op) {
200 return op == null ? null : op.getChildExpression().copy(new RebindingMap());
201 }
202
203 /*@NotNull*/
204 public ItemType getItemType() {
205 return BuiltInAtomicType.STRING;
206 }
207
208 public int computeCardinality() {
209 return StaticProperty.EXACTLY_ONE;
210 }
211
212 /**
213 * An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process().
214 * This method indicates which of these methods is provided directly. The other methods will always be available
215 * indirectly, using an implementation that relies on one of the other methods.
216 *
217 * @return the implementation method, for example {@link #ITERATE_METHOD} or {@link #EVALUATE_METHOD} or
218 * {@link #PROCESS_METHOD}
219 */
220 @Override
221 public int getImplementationMethod() {
222 return EVALUATE_METHOD;
223 }
224
225 public StringValue evaluateItem(XPathContext context) throws XPathException {
226 long value = -1;
227 List<Object> vec = new ArrayList<>(4); // a list whose items may be of type either Long or
228 // BigInteger or the string to be output (e.g. "NaN")
229 final ConversionRules rules = context.getConfiguration().getConversionRules();
230 String startAv = startAtOp.getChildExpression().evaluateAsString(context).toString();
231 List<Integer> startValues = parseStartAtValue(startAv);
232
233
234 SequenceIterator iter = valueOp.getChildExpression().iterate(context);
235 AtomicValue val;
236 int pos = 0;
237 while ((val = (AtomicValue)iter.next()) != null) {
238 if (backwardsCompatible && !vec.isEmpty()) {
239 break;
240 }
241 int startValue = startValues.size() > pos ? startValues.get(pos) : startValues.get(startValues.size()-1);
242 pos++;
243 try {
244 NumericValue num;
245 if (val instanceof NumericValue) {
246 num = (NumericValue) val;
247 } else {
248 num = Number_1.convert(val, context.getConfiguration());
249 }
250 if (num.isNaN()) {
251 throw new XPathException("NaN"); // thrown to be caught
252 }
253 num = num.round(0);
254 if (num.compareTo(Int64Value.MAX_LONG) > 0) {
255 BigInteger bi = ((BigIntegerValue) Converter.convert(num, BuiltInAtomicType.INTEGER, rules).asAtomic()).asBigInteger();
256 if (startValue != 1) {
257 bi = bi.add(BigInteger.valueOf(startValue - 1));
258 }
259 vec.add(bi);
260 } else {
261 if (num.compareTo(Int64Value.ZERO) < 0) {
262 throw new XPathException("The numbers to be formatted must not be negative");
263 // thrown to be caught
264 }
265 long i = ((NumericValue) Converter.convert(num, BuiltInAtomicType.INTEGER, rules).asAtomic()).longValue();
266 i += startValue - 1;
267 vec.add(i);
268 }
269 } catch (XPathException err) {
270 if (backwardsCompatible) {
271 vec.add("NaN");
272 } else {
273 vec.add(val.getStringValue());
274 XPathException e = new XPathException("Cannot convert supplied value to an integer. " + err.getMessage());
275 e.setErrorCode("XTDE0980");
276 e.setLocation(getLocation());
277 e.setXPathContext(context);
278 throw e;
279 }
280 }
281 }
282 if (backwardsCompatible && vec.isEmpty()) {
283 vec.add("NaN");
284 }
285
286 int gpsize = 0;
287 String gpseparator = "";
288 String letterVal;
289 String ordinalVal = null;
290
291 if (groupSizeOp != null) {
292 String g = groupSizeOp.getChildExpression().evaluateAsString(context).toString();
293 try {
294 gpsize = Integer.parseInt(g);
295 } catch (NumberFormatException err) {
296 XPathException e = new XPathException("grouping-size must be numeric");
297 e.setXPathContext(context);
298 e.setErrorCode("XTDE0030");
299 e.setLocation(getLocation());
300 throw e;
301 }
302 }
303
304 if (groupSeparatorOp != null) {
305 gpseparator = groupSeparatorOp.getChildExpression().evaluateAsString(context).toString();
306 }
307
308 if (ordinalOp != null) {
309 ordinalVal = ordinalOp.getChildExpression().evaluateAsString(context).toString();
310 }
311
312 // Use the numberer decided at compile time if possible; otherwise try to get it from
313 // a table of numberers indexed by language; if not there, load the relevant class and
314 // add it to the table.
315 Numberer numb = numberer;
316 if (numb == null) {
317 if (langOp == null) {
318 numb = context.getConfiguration().makeNumberer(null, null);
319 } else {
320 String language = langOp.getChildExpression().evaluateAsString(context).toString();
321 ValidationFailure vf = StringConverter.StringToLanguage.INSTANCE.validate(language);
322 if (vf != null) {
323 throw new XPathException("The lang attribute of xsl:number must be a valid language code", "XTDE0030");
324 }
325 numb = context.getConfiguration().makeNumberer(language, null);
326 }
327 }
328
329 if (letterValueOp == null) {
330 letterVal = "";
331 } else {
332 letterVal = letterValueOp.getChildExpression().evaluateAsString(context).toString();
333 if (!("alphabetic".equals(letterVal) || "traditional".equals(letterVal))) {
334 XPathException e = new XPathException("letter-value must be \"traditional\" or \"alphabetic\"");
335 e.setXPathContext(context);
336 e.setErrorCode("XTDE0030");
337 e.setLocation(getLocation());
338 throw e;
339 }
340 }
341
342 NumberFormatter nf;
343 if (formatter == null) { // format not known until run-time
344 nf = new NumberFormatter();
345 nf.prepare(formatOp.getChildExpression().evaluateAsString(context).toString());
346 } else {
347 nf = formatter;
348 }
349
350 CharSequence s = nf.format(vec, gpsize, gpseparator, letterVal, ordinalVal, numb);
351 return new StringValue(s);
352 }
353
354 public List<Integer> parseStartAtValue(String value) throws XPathException {
355 List<Integer> list = new ArrayList<>();
356 String[] tokens = value.split("\\s+");
357 for (String tok : tokens) {
358 try {
359 int n = Integer.parseInt(tok);
360 list.add(n);
361 } catch (NumberFormatException err) {
362 XPathException e = new XPathException("Invalid start-at value: non-integer component {" + tok + "}");
363 e.setErrorCode("XTDE0030");
364 e.setLocation(getLocation());
365 throw e;
366 }
367 }
368 if (list.isEmpty()) {
369 XPathException e = new XPathException("Invalid start-at value: no numeric components found");
370 e.setErrorCode("XTDE0030");
371 e.setLocation(getLocation());
372 throw e;
373 }
374 return list;
375 }
376
377 /**
378 * Diagnostic print of expression structure. The abstract expression tree
379 * is written to the supplied output destination.
380 */
381
382 public void export(ExpressionPresenter out) throws XPathException {
383 out.startElement("numSeqFmt", this);
384 String flags = "";
385 if (backwardsCompatible) {
386 flags += "1";
387 }
388 if (!flags.isEmpty()) {
389 out.emitAttribute("flags", flags);
390 }
391 if (valueOp != null) {
392 out.setChildRole("value");
393 valueOp.getChildExpression().export(out);
394 }
395 if (formatOp != null) {
396 out.setChildRole("format");
397 formatOp.getChildExpression().export(out);
398 }
399 if (startAtOp != null) {
400 out.setChildRole("startAt");
401 startAtOp.getChildExpression().export(out);
402 }
403 if (langOp != null) {
404 out.setChildRole("lang");
405 langOp.getChildExpression().export(out);
406 }
407 if (ordinalOp != null) {
408 out.setChildRole("ordinal");
409 ordinalOp.getChildExpression().export(out);
410 }
411 if (groupSeparatorOp != null) {
412 out.setChildRole("gpSep");
413 groupSeparatorOp.getChildExpression().export(out);
414 }
415 if (groupSizeOp != null) {
416 out.setChildRole("gpSize");
417 groupSizeOp.getChildExpression().export(out);
418 }
419 out.endElement();
420 }
421 }
422