Debian Codegraph @

net/sf/saxon/value/AtomicValue.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.value;
9
10 import net.sf.saxon.event.ReceiverOptions;
11 import net.sf.saxon.tree.jiter.MonoIterator;
12 import net.sf.saxon.expr.StaticContext;
13 import net.sf.saxon.expr.StaticProperty;
14 import net.sf.saxon.expr.XPathContext;
15 import net.sf.saxon.expr.parser.ExplicitLocation;
16 import net.sf.saxon.expr.sort.AtomicMatchKey;
17 import net.sf.saxon.expr.sort.CodepointCollator;
18 import net.sf.saxon.functions.AccessorFn;
19 import net.sf.saxon.lib.StringCollator;
20 import net.sf.saxon.om.*;
21 import net.sf.saxon.trans.Err;
22 import net.sf.saxon.trans.NoDynamicContextException;
23 import net.sf.saxon.trans.XPathException;
24 import net.sf.saxon.tree.iter.SingleAtomicIterator;
25 import net.sf.saxon.type.*;
26
27 import java.util.Iterator;
28
29
30 /**
31 * The AtomicValue class corresponds to the concept of an atomic value in the
32 * XPath 2.0 data model. Atomic values belong to one of the 19 primitive types
33 * defined in XML Schema; or they are of type xs:untypedAtomic; or they are
34 * "external objects", representing a Saxon extension to the XPath 2.0 type system.
35 * <p>The AtomicValue class contains some methods that are suitable for applications
36 * to use, and many others that are designed for internal use by Saxon itself.
37 * These have not been fully classified. At present, therefore, none of the methods on this
38 * class should be considered to be part of the public Saxon API.</p>
39 *
40 * @author Michael H. Kay
41 */
42
43 public abstract class AtomicValue
44 implements Item<AtomicValue>, AtomicSequence, ConversionResult, IdentityComparable {
45
46 protected AtomicType typeLabel;
47
48 /**
49 * Atomize the item.
50 *
51 * @return the result of atomization
52 * @throws net.sf.saxon.trans.XPathException
53 * if atomization is not allowed for this kind of item
54 */
55
56 public AtomicSequence atomize() throws XPathException {
57 return this;
58 }
59
60 /**
61 * To implement {@link net.sf.saxon.om.Sequence}, this method returns the item itself
62 *
63 * @return this item
64 */
65
66 public final AtomicValue head() {
67 return this;
68 }
69
70 /**
71 * Get the length of the sequence
72 *
73 * @return the number of items in the sequence (always one)
74 */
75
76 public int getLength() {
77 return 1;
78 }
79
80 /**
81 * To implement {@link net.sf.saxon.om.Sequence}, this method returns a singleton iterator
82 * that delivers this item in the form of a sequence
83 *
84 * @return a singleton iterator that returns this item
85 */
86
87 public final SingleAtomicIterator iterate() {
88 return new SingleAtomicIterator(this);
89 }
90
91 /**
92 * Set the type label on this atomic value. Note that this modifies the value, so it must only called
93 * if the caller is confident that the value is not shared. In other cases,
94 * use {@link #copyAsSubType(net.sf.saxon.type.AtomicType)}
95 *
96 * @param type the type label to be set
97 */
98
99 public void setTypeLabel(AtomicType type) {
100 typeLabel = type;
101 }
102
103 /**
104 * Get a Comparable value that implements the XML Schema ordering comparison semantics for this value.
105 * An implementation must be provided for all atomic types.
106 * <p>In the case of data types that are partially ordered, the returned Comparable extends the standard
107 * semantics of the compareTo() method by returning the value {@link SequenceTool#INDETERMINATE_ORDERING} when there
108 * is no defined order relationship between two given values. This value is also returned when two values
109 * of different types are compared.</p>
110 *
111 * @return a Comparable that follows XML Schema comparison rules
112 */
113
114 public abstract Comparable getSchemaComparable();
115
116 /**
117 * Get an object value that implements the XPath equality and ordering comparison semantics for this value.
118 * If the ordered parameter is set to true, the result will be a Comparable and will support a compareTo()
119 * method with the semantics of the XPath lt/gt operator, provided that the other operand is also obtained
120 * using the getXPathComparable() method. In all cases the result will support equals() and hashCode() methods
121 * that support the semantics of the XPath eq operator, again provided that the other operand is also obtained
122 * using the getXPathComparable() method. A collation is supplied for comparing strings, and an implicit timezone
123 * for comparing date/time values that have no saved timezone.
124 *
125 *
126 * @param ordered true if an ordered comparison is required. In this case the result is null if the
127 * type is unordered; in other cases the returned value will be a Comparable.
128 * @param collator the collation to be used when comparing strings
129 * @param implicitTimezone the implicit timezone in the dynamic context, used when comparing
130 * dates/times with and without timezone
131 * @return an Object whose equals() and hashCode() methods implement the XPath comparison semantics
132 * with respect to this atomic value. If ordered is specified, the result will either be null if
133 * no ordering is defined, or will be a Comparable
134 * @throws NoDynamicContextException if the supplied implicit timezone is "NO_TIMEZONE" (meaning
135 * unknown), and the implicit timezone is actually required because the value in question is a date/time
136 * value with no timezone. This can cause a failure to evaluate expressions statically (because the implicit
137 * timezone is not known statically), and it will then be caught, meaning that the expression has to be
138 * evaluated dynamically.
139 */
140
141 public abstract AtomicMatchKey getXPathComparable(boolean ordered, StringCollator collator, int implicitTimezone)
142 throws NoDynamicContextException;
143
144 /**
145 * Get a value whose equals() method follows the "same key" rules for comparing the keys of a map.
146 * @return a value with the property that the equals() and hashCode() methods follow the rules for comparing
147 * keys in maps.
148 */
149
150 public AtomicMatchKey asMapKey() {
151 try {
152 return getXPathComparable(false, CodepointCollator.getInstance(), CalendarValue.NO_TIMEZONE);
153 } catch (NoDynamicContextException e) {
154 // Should not happen
155 throw new IllegalStateException("No implicit timezone available");
156 }
157 }
158
159 /**
160 * The equals() methods on atomic values is defined to follow the semantics of eq when applied
161 * to two atomic values. When the other operand is not an atomic value, the result is undefined
162 * (may be false, may be an exception). When the other operand is an atomic value that cannot be
163 * compared with this one, the method must throw a ClassCastException.
164 * <p>The hashCode() method is consistent with equals().</p>
165 *
166 * @param o the other value
167 * @return true if the other operand is an atomic value and the two values are equal as defined
168 * by the XPath eq operator
169 */
170
171 public abstract boolean equals(Object o);
172
173 /**
174 * Determine whether two atomic values are identical, as determined by XML Schema rules. This is a stronger
175 * test than equality (even schema-equality); for example two dateTime values are not identical unless
176 * they are in the same timezone.
177 * <p>Note that even this check ignores the type annotation of the value. The integer 3 and the short 3
178 * are considered identical, even though they are not fully interchangeable. "Identical" means the
179 * same point in the value space, regardless of type annotation.</p>
180 * <p>NaN is identical to itself.</p>
181 *
182 * @param v the other value to be compared with this one
183 * @return true if the two values are identical, false otherwise.
184 */
185
186 public boolean isIdentical(/*@NotNull*/ AtomicValue v) {
187 // default implementation
188 return getSchemaComparable().equals(v.getSchemaComparable());
189 }
190
191 /**
192 * Determine whether two IdentityComparable objects are identical. This is a stronger
193 * test than equality (even schema-equality); for example two dateTime values are not identical unless
194 * they are in the same timezone.
195 *
196 * @param other the value to be compared
197 * @return true if the two values are identical, false otherwise
198 */
199
200 public boolean isIdentical(IdentityComparable other) {
201 return other instanceof AtomicValue && isIdentical((AtomicValue) other);
202 }
203
204 /**
205 * Get a hashCode that offers the guarantee that if A.isIdentical(B), then A.identityHashCode() == B.identityHashCode()
206 *
207 * @return a hashCode suitable for use when testing for identity.
208 */
209 public int identityHashCode() {
210 // default implementation, which presumes that if two objects are identical then they are equal.
211 return hashCode();
212 }
213
214 /**
215 * Get the value of the item as a CharSequence. This is in some cases more efficient than
216 * the version of the method that returns a String.
217 */
218
219 public final CharSequence getStringValueCS() {
220 CharSequence cs = getPrimitiveStringValue();
221 try {
222 return typeLabel.postprocess(cs);
223 } catch (XPathException err) {
224 // Ignore any XPath errors that occur during postprocessing
225 return cs;
226 }
227 }
228
229 /**
230 * Get the canonical lexical representation as defined in XML Schema. This is not always the same
231 * as the result of casting to a string according to the XPath rules.
232 *
233 * @return the canonical lexical representation if defined in XML Schema; otherwise, the result
234 * of casting to string according to the XPath 2.0 rules
235 */
236 public CharSequence getCanonicalLexicalRepresentation() {
237 return getStringValueCS();
238 }
239
240 /**
241 * Process the instruction, without returning any tail calls
242 *
243 * @param context The dynamic context, giving access to the current node,
244 * the current variables, etc.
245 * @throws XPathException if the current receiver fails for any reason, for example
246 * with a serialization error due to invalid characters in the content
247 */
248
249 public void process(/*@NotNull*/ XPathContext context) throws XPathException {
250 context.getReceiver().append(this, ExplicitLocation.UNKNOWN_LOCATION, ReceiverOptions.ALL_NAMESPACES);
251 }
252
253 /**
254 * Get the n'th item in the sequence (starting from 0). This is defined for all
255 * Values, but its real benefits come for a sequence Value stored extensionally
256 * (or for a MemoClosure, once all the values have been read)
257 *
258 * @param n position of the required item, counting from zero.
259 * @return the n'th item in the sequence, where the first item in the sequence is
260 * numbered zero. If n is negative or &gt;= the length of the sequence, returns null.
261 */
262
263 /*@Nullable*/
264 public final AtomicValue itemAt(int n) {
265 return n == 0 ? head() : null;
266 }
267
268
269 /**
270 * Determine the data type of the value
271 *
272 * @return the type annotation of the atomic value
273 */
274
275 /*@NotNull*/
276 public final AtomicType getItemType() {
277 return typeLabel;
278 }
279
280 /**
281 * Determine the primitive type of the value. This delivers the same answer as
282 * getItemType().getPrimitiveItemType(). The primitive types are
283 * the 19 primitive types of XML Schema, plus xs:integer, xs:dayTimeDuration and xs:yearMonthDuration,
284 * and xs:untypedAtomic. For external objects, the result is xs:anyAtomicType.
285 *
286 * @return the primitive type
287 */
288
289 public abstract BuiltInAtomicType getPrimitiveType();
290
291 /**
292 * Determine the UType of the value. This delivers the same answer as
293 * getItemType().getUType()
294 * @return the primitive UType
295 */
296
297 public final UType getUType() {
298 return getItemType().getUType();
299 }
300
301 /**
302 * Determine the static cardinality
303 *
304 * @return code identifying the cardinality
305 * @see net.sf.saxon.value.Cardinality
306 */
307
308 public final int getCardinality() {
309 return StaticProperty.EXACTLY_ONE;
310 }
311
312 /**
313 * Create a copy of this atomic value, with a different type label
314 *
315 * @param typeLabel the type label of the new copy. The caller is responsible for checking that
316 * the value actually conforms to this type.
317 * @return the copied value
318 */
319
320 public abstract AtomicValue copyAsSubType(AtomicType typeLabel);
321
322 /**
323 * Test whether the value is the special value NaN
324 *
325 * @return true if the value is float NaN or double NaN or precisionDecimal NaN; otherwise false
326 */
327
328 public boolean isNaN() {
329 return false;
330 }
331
332 /**
333 * Convert the value to a string, using the serialization rules.
334 * For atomic values this is the same as a cast; for sequence values
335 * it gives a space-separated list. This method is refined for AtomicValues
336 * so that it never throws an Exception.
337 */
338
339 public final String getStringValue() {
340 return getStringValueCS().toString();
341 }
342
343 /**
344 * Convert the value to a string, using the serialization rules for the primitive type.
345 * This is the result of conversion to a string except that postprocessing defined by the
346 * saxon:preprocess facet is not (yet) applied.
347 *
348 * @return the value converted to a string according to the rules for the primitive type
349 */
350
351 protected abstract CharSequence getPrimitiveStringValue();
352
353
354 /**
355 * Get the effective boolean value of the value
356 *
357 * @return true, unless the value is boolean false, numeric zero, or
358 * zero-length string
359 * @throws XPathException if effective boolean value is not defined for this type (the default behaviour)
360 */
361 public boolean effectiveBooleanValue() throws XPathException {
362 XPathException err = new XPathException("Effective boolean value is not defined for an atomic value of type " +
363 Type.displayTypeName(this));
364 err.setIsTypeError(true);
365 err.setErrorCode("FORG0006");
366 throw err;
367 // unless otherwise specified in a subclass
368 }
369
370 /**
371 * Method to extract components of a value. Implemented by some subclasses,
372 * but defined at this level for convenience
373 *
374 * @param component identifies the required component, as a constant defined in class
375 * {@link net.sf.saxon.functions.AccessorFn}
376 * @return the value of the requested component of this value
377 * @throws net.sf.saxon.trans.XPathException
378 * if a dynamic error occurs
379 * @throws UnsupportedOperationException if applied to a value of a type that has no components
380 */
381
382 public AtomicValue getComponent(AccessorFn.Component component) throws XPathException {
383 throw new UnsupportedOperationException("Data type does not support component extraction");
384 }
385
386 /**
387 * Check statically that the results of the expression are capable of constructing the content
388 * of a given schema type.
389 *
390 * @param parentType The schema type
391 * @param env the static context
392 * @param whole true if this atomic value accounts for the entire content of the containing node
393 * @throws net.sf.saxon.trans.XPathException
394 * if the expression doesn't match the required content type
395 */
396
397 public void checkPermittedContents(/*@NotNull*/ SchemaType parentType, /*@NotNull*/ StaticContext env, boolean whole) throws XPathException {
398 if (whole) {
399 SimpleType stype = null;
400 if (parentType instanceof SimpleType) {
401 stype = (SimpleType) parentType;
402 } else if (parentType instanceof ComplexType && ((ComplexType) parentType).isSimpleContent()) {
403 stype = ((ComplexType) parentType).getSimpleContentType();
404 }
405 if (stype != null && !stype.isNamespaceSensitive()) {
406 // Can't validate namespace-sensitive content statically
407 ValidationFailure err = stype.validateContent(
408 getStringValueCS(), null, env.getConfiguration().getConversionRules());
409 if (err != null) {
410 throw err.makeException();
411 }
412 return;
413 }
414 }
415 if (parentType instanceof ComplexType &&
416 !((ComplexType) parentType).isSimpleContent() &&
417 !((ComplexType) parentType).isMixedContent() &&
418 !Whitespace.isWhite(getStringValueCS())) {
419 XPathException err = new XPathException("Complex type " + parentType.getDescription() +
420 " does not allow text content " +
421 Err.wrap(getStringValueCS()));
422 err.setIsTypeError(true);
423 throw err;
424 }
425 }
426
427 /**
428 * Check that the value can be handled in Saxon-JS
429 * @throws XPathException if it can't be handled in Saxon-JS
430 */
431
432 public void checkValidInJavascript() throws XPathException {
433 // default - no action
434 }
435
436
437 /**
438 * Calling this method on a ConversionResult returns the AtomicValue that results
439 * from the conversion if the conversion was successful, and throws a ValidationException
440 * explaining the conversion error otherwise.
441 * <p>Use this method if you are calling a conversion method that returns a ConversionResult,
442 * and if you want to throw an exception if the conversion fails.</p>
443 *
444 * @return the atomic value that results from the conversion if the conversion was successful
445 */
446
447 /*@NotNull*/
448 public AtomicValue asAtomic() {
449 return this;
450 }
451
452 /**
453 * Get string value. In general toString() for an atomic value displays the value as it would be
454 * written in XPath: that is, as a literal if available, or as a call on a constructor function
455 * otherwise.
456 */
457
458 public String toString() {
459 return typeLabel + "(\"" + getStringValueCS() + "\")";
460 }
461
462 /**
463 * Returns a Java iterator over the atomic sequence.
464 *
465 * @return an Iterator.
466 */
467
468 public Iterator<AtomicValue> iterator() {
469 return new MonoIterator<>(this);
470 }
471
472 /**
473 * Get the genre of this item
474 *
475 * @return the genre: specifically, {@link Genre#ATOMIC};
476 */
477 @Override
478 public final Genre getGenre() {
479 return Genre.ATOMIC;
480 }
481
482 }
483