Debian Codegraph @

net/sf/saxon/type/NumericType.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2013 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.type;
9
10 import com.saxonica.ee.schema.UserSimpleType;
11 import net.sf.saxon.expr.Expression;
12 import net.sf.saxon.lib.ConversionRules;
13 import net.sf.saxon.lib.NamespaceConstant;
14 import net.sf.saxon.om.*;
15 import net.sf.saxon.trans.XPathException;
16 import net.sf.saxon.value.*;
17
18 import java.util.ArrayList;
19 import java.util.List;
20
21 import static net.sf.saxon.type.SchemaComponent.ValidationStatus.VALIDATED;
22
23 /**
24 * Singleton class representing the class xs:numeric as defined in XPath 3.1: a union type
25 * whose members are xs:double, xs:decimal, and xs:float
26 */
27 public class NumericType implements UnionType, PlainType {
28
29 private final static NumericType THE_INSTANCE = new NumericType();
30
31 public static NumericType getInstance() {
32 return THE_INSTANCE;
33 }
34
35 private List<PlainType> members;
36
37 private NumericType() {}
38
39 public StructuredQName getTypeName() {
40 return new StructuredQName("xs", NamespaceConstant.SCHEMA, "numeric");
41 }
42
43 /**
44 * Get the genre of this item
45 *
46 * @return the genre
47 */
48 @Override
49 public Genre getGenre() {
50 return Genre.ATOMIC;
51 }
52
53 /**
54 * Get an alphabetic code representing the type, or at any rate, the nearest built-in type
55 * from which this type is derived. The codes are designed so that for any two built-in types
56 * A and B, alphaCode(A) is a prefix of alphaCode(B) if and only if A is a supertype of B.
57 *
58 * @return the alphacode for the nearest containing built-in type
59 */
60 @Override
61 public String getAlphaCode() {
62 return "A";
63 }
64
65 /**
66 * Ask whether the union contains a list type among its member types
67 *
68 * @return true of one of the member types is a list type
69 */
70 public boolean containsListType() {
71 return false;
72 }
73
74 /**
75 * Get the "plain" types in the transitive membership. Plain types are atomic types and union types that
76 * are defined directly in terms of other plain types, without adding any restriction facets.
77 *
78 * @return the atomic types and plain union types in the transitive membership of the union type.
79 */
80 public synchronized Iterable<PlainType> getPlainMemberTypes() {
81 if (members == null) {
82 members = new ArrayList<>();
83 members.add(BuiltInAtomicType.DOUBLE);
84 members.add(BuiltInAtomicType.FLOAT);
85 members.add(BuiltInAtomicType.DECIMAL);
86 }
87 return members;
88 }
89
90 /**
91 * Get the result type of a cast operation to this union type, as a sequence type.
92 *
93 * @return the result type of casting, as precisely as possible. For example, if all the member types of
94 * the union are derived from the same primitive type, this will return that primitive type.
95 */
96 public SequenceType getResultTypeOfCast() {
97 return SequenceType.ATOMIC_SEQUENCE;
98 }
99
100 /**
101 * Determine whether this item type is a plain type (that is, whether it can ONLY match
102 * atomic values)
103 *
104 * @return true if this is ANY_ATOMIC_TYPE or a subtype thereof, or a
105 * "plain" union type (that is, unions of atomic types that impose no further restrictions)
106 */
107 public boolean isPlainType() {
108 return true;
109 }
110
111 /**
112 * Test whether a given item conforms to this type
113 *
114 *
115 *
116 * @param item The item to be tested
117 * @param th The type hierarchy cache
118 * @return true if the item is an instance of this type; false otherwise
119 */
120 public boolean matches(Item item, TypeHierarchy th) {
121 return item instanceof NumericValue;
122 }
123
124 /**
125 * Get the primitive item type corresponding to this item type. For item(),
126 * this is Type.ITEM. For node(), it is Type.NODE. For specific node kinds,
127 * it is the value representing the node kind, for example Type.ELEMENT.
128 * For anyAtomicValue and union types it is Type.ATOMIC_VALUE. For numeric it is Type.NUMBER.
129 * For other atomic types it is the primitive type as defined in XML Schema,
130 * except that integer, xs:dayTimeDuration, and xs:yearMonthDuration
131 * are considered to be primitive types.
132 *
133 * @return the corresponding primitive type
134 */
135 public AtomicType getPrimitiveItemType() {
136 return BuiltInAtomicType.ANY_ATOMIC;
137 }
138
139 /**
140 * Get the primitive type corresponding to this item type. For item(),
141 * this is Type.ITEM. For node(), it is Type.NODE. For specific node kinds,
142 * it is the value representing the node kind, for example Type.ELEMENT.
143 * For anyAtomicValue it is BuiltInAtomicType.ANY_ATOMIC. For numeric it is Type.NUMBER.
144 * For other atomic types it is the primitive type as defined in XML Schema,
145 * except that INTEGER is considered to be a primitive type.
146 *
147 * @return the integer fingerprint of the corresponding primitive type
148 */
149 public int getPrimitiveType() {
150 return BuiltInAtomicType.ANY_ATOMIC.getFingerprint();
151 }
152
153 /**
154 * Get the corresponding {@link net.sf.saxon.type.UType}. A UType is a union of primitive item
155 * types.
156 *
157 * @return the smallest UType that subsumes this item type
158 */
159 public UType getUType() {
160 return UType.NUMERIC;
161 }
162
163 /**
164 * Get the item type of the atomic values that will be produced when an item
165 * of this type is atomized
166 *
167 * @return the best available item type of the atomic values that will be produced when an item
168 * of this type is atomized, or null if it is known that atomization will throw an error.
169 */
170 public PlainType getAtomizedItemType() {
171 return this;
172 }
173
174 /**
175 * Ask whether values of this type are atomizable
176 *
177 * @return true unless it is known that these items will be elements with element-only
178 * content, or function items, in which case return false
179 * @param th The type hierarchy cache
180 */
181 public boolean isAtomizable(TypeHierarchy th) {
182 return true;
183 }
184
185 /**
186 * Test whether this Simple Type is an atomic type
187 *
188 * @return true if this is an atomic type
189 */
190 public boolean isAtomicType() {
191 return false;
192 }
193
194 /**
195 * Test whether this Simple Type is a list type
196 *
197 * @return true if this is a list type
198 */
199 public boolean isListType() {
200 return false;
201 }
202
203 /**
204 * Test whether this Simple Type is a union type
205 *
206 * @return true if this is a union type
207 */
208 public boolean isUnionType() {
209 return true;
210 }
211
212 /**
213 * Return true if this is an external object type, that is, a Saxon-defined type for external
214 * Java or .NET objects
215 *
216 * @return true if this is an external type
217 */
218 public boolean isExternalType() {
219 return false;
220 }
221
222 /**
223 * Determine whether this is a built-in type or a user-defined type
224 *
225 * @return true if this is a built-in type
226 */
227 public boolean isBuiltInType() {
228 return true;
229 }
230
231 /**
232 * Get the built-in type from which this type is derived by restriction
233 *
234 * @return the built-in type from which this type is derived by restriction. This will not necessarily
235 * be a primitive type.
236 */
237 public SchemaType getBuiltInBaseType() {
238 return AnySimpleType.getInstance();
239 }
240
241 /**
242 * Get the typed value corresponding to a given string value, assuming it is
243 * valid against this type
244 *
245 * @param value the string value
246 * @param resolver a namespace resolver used to resolve any namespace prefixes appearing
247 * in the content of values. Can supply null, in which case any namespace-sensitive content
248 * will be rejected.
249 * @param rules the conversion rules from the configuration
250 * @return an iterator over the atomic sequence comprising the typed value. The objects
251 * returned by this SequenceIterator will all be of type {@link net.sf.saxon.value.AtomicValue},
252 * The next() method on the iterator throws no checked exceptions, although it is not actually
253 * declared as an UnfailingIterator.
254 * @throws net.sf.saxon.type.ValidationException
255 * if the supplied value is not in the lexical space of the data type
256 */
257 public AtomicSequence getTypedValue(CharSequence value, NamespaceResolver resolver, ConversionRules rules) throws ValidationException {
258 try {
259 double d = StringToDouble.getInstance().stringToNumber(value);
260 return new DoubleValue(d);
261 } catch (NumberFormatException e) {
262 throw new ValidationFailure(e.getMessage()).makeException();
263 }
264 }
265
266 /**
267 * Check whether a given input string is valid according to this SimpleType
268 *
269 * @param value the input string to be checked
270 * @param nsResolver a namespace resolver used to resolve namespace prefixes if the type
271 * is namespace sensitive. The value supplied may be null; in this case any namespace-sensitive
272 * content will throw an UnsupportedOperationException.
273 * @param rules the conversion rules from the configuration
274 * @return null if validation succeeds; or return a ValidationFailure describing the validation failure
275 * if validation fails. Note that the exception is returned rather than being thrown.
276 * @throws UnsupportedOperationException if the type is namespace-sensitive and no namespace
277 * resolver is supplied
278 */
279 public ValidationFailure validateContent(CharSequence value, NamespaceResolver nsResolver, ConversionRules rules) {
280 try {
281 StringToDouble.getInstance().stringToNumber(value);
282 return null;
283 } catch (NumberFormatException e) {
284 return new ValidationFailure(e.getMessage());
285 }
286 }
287
288 /**
289 * Validate an atomic value, which is known to be an instance of one of the member types of the
290 * union, against any facets (pattern facets or enumeration facets) defined at the level of the
291 * union itself.
292 *
293 * @param value the Atomic Value to be checked. This must be an instance of a member type of the
294 * union
295 * @param rules the ConversionRules for the Configuration
296 * @return a ValidationFailure if the value is not valid; null if it is valid.
297 */
298 @Override
299 public ValidationFailure checkAgainstFacets(AtomicValue value, ConversionRules rules) {
300 return null;
301 }
302
303 /**
304 * Test whether this type is namespace sensitive, that is, if a namespace context is needed
305 * to translate between the lexical space and the value space. This is true for types derived
306 * from, or containing, QNames and NOTATIONs
307 *
308 * @return true if the type is namespace-sensitive
309 */
310 public boolean isNamespaceSensitive() {
311 return false;
312 }
313
314 /**
315 * Determine how values of this simple type are whitespace-normalized.
316 *
317 * @return one of {@link net.sf.saxon.value.Whitespace#PRESERVE}, {@link net.sf.saxon.value.Whitespace#COLLAPSE},
318 * {@link net.sf.saxon.value.Whitespace#REPLACE}.
319 */
320 public int getWhitespaceAction() {
321 return Whitespace.COLLAPSE;
322 }
323
324 /**
325 * Apply any pre-lexical facets, other than whitespace. At the moment the only such
326 * facet is saxon:preprocess
327 *
328 * @param input the value to be preprocessed
329 * @return the value after preprocessing
330 */
331 public CharSequence preprocess(CharSequence input) {
332 return input;
333 }
334
335 /**
336 * Reverse any pre-lexical facets, other than whitespace. At the moment the only such
337 * facet is saxon:preprocess. This is called when converting a value of this type to
338 * a string
339 *
340 * @param input the value to be postprocessed: this is the "ordinary" result of converting
341 * the value to a string
342 * @return the value after postprocessing
343 */
344 public CharSequence postprocess(CharSequence input) {
345 return input;
346 }
347
348 /**
349 * Get the local name of this type
350 *
351 * @return the local name of this type definition, if it has one. Return null in the case of an
352 * anonymous type.
353 */
354 public String getName() {
355 return "numeric";
356 }
357
358 /**
359 * Get the target namespace of this type
360 *
361 * @return the target namespace of this type definition, if it has one. Return null in the case
362 * of an anonymous type, and in the case of a global type defined in a no-namespace schema.
363 */
364 public String getTargetNamespace() {
365 return NamespaceConstant.SCHEMA;
366 }
367
368 /**
369 * Get the fingerprint of the name of this type
370 *
371 * @return the fingerprint. Returns an invented fingerprint for an anonymous type.
372 */
373 public int getFingerprint() {
374 return StandardNames.XS_NUMERIC;
375 }
376
377 /**
378 * Get the display name of the type: that is, a lexical QName with an arbitrary prefix
379 *
380 * @return a lexical QName identifying the type. In the case of an anonymous type, an internally-generated
381 * name is returned
382 */
383 public String getDisplayName() {
384 return "xs:numeric";
385 }
386
387 /**
388 * Get the name of this type as an EQName, that is, a string in the format Q{uri}local.
389 *
390 * @return an EQName identifying the type. In the case of an anonymous type, an internally-generated
391 * name is returned
392 */
393 public String getEQName() {
394 return "Q(" + NamespaceConstant.SCHEMA + "}numeric";
395 }
396
397 /**
398 * Get the name of the type as a StructuredQName
399 *
400 * @return a StructuredQName identifying the type. In the case of an anonymous type, an internally-generated
401 * name is returned
402 */
403 public StructuredQName getStructuredQName() {
404 return new StructuredQName("xs", NamespaceConstant.SCHEMA, "numeric");
405 }
406
407 /**
408 * Test whether this SchemaType is a complex type
409 *
410 * @return true if this SchemaType is a complex type
411 */
412 public boolean isComplexType() {
413 return false;
414 }
415
416 /**
417 * Test whether this SchemaType is a simple type
418 *
419 * @return true if this SchemaType is a simple type
420 */
421 public boolean isSimpleType() {
422 return true;
423 }
424
425 /**
426 * Test whether this is an anonymous type
427 *
428 * @return true if this SchemaType is an anonymous type
429 */
430 public boolean isAnonymousType() {
431 return false;
432 }
433
434 /**
435 * Returns the value of the 'block' attribute for this type, as a bit-significant
436 * integer with fields such as {@link net.sf.saxon.type.SchemaType#DERIVATION_LIST} and {@link net.sf.saxon.type.SchemaType#DERIVATION_EXTENSION}.
437 * This corresponds to the property "prohibited substitutions" in the schema component model.
438 *
439 * @return the value of the 'block' attribute for this type
440 */
441 public int getBlock() {
442 return 0;
443 }
444
445 /**
446 * Returns the base type that this type inherits from. This method can be used to get the
447 * base type of a type that is known to be valid.
448 * If this type is a Simpletype that is a built in primitive type then null is returned.
449 *
450 * @return the base type, or null if this is xs:anyType (the root of the type hierarchy)
451 */
452 public SchemaType getBaseType() {
453 return AnySimpleType.getInstance();
454 }
455
456 /**
457 * Gets the integer code of the derivation method used to derive this type from its
458 * parent. Returns zero for primitive types.
459 *
460 * @return a numeric code representing the derivation method, for example {@link net.sf.saxon.type.SchemaType#DERIVATION_RESTRICTION}
461 */
462 public int getDerivationMethod() {
463 return SchemaType.DERIVATION_RESTRICTION;
464 }
465
466 /**
467 * Get the types of derivation that are not permitted, by virtue of the "final" property.
468 *
469 * @return the types of derivation that are not permitted, as a bit-significant integer
470 * containing bits such as {@link net.sf.saxon.type.SchemaType#DERIVATION_EXTENSION}
471 */
472 public int getFinalProhibitions() {
473 return 0;
474 }
475
476 /**
477 * Determines whether derivation (of a particular kind)
478 * from this type is allowed, based on the "final" property
479 *
480 * @param derivation the kind of derivation, for example {@link net.sf.saxon.type.SchemaType#DERIVATION_LIST}
481 * @return true if this kind of derivation is allowed
482 */
483 public boolean allowsDerivation(int derivation) {
484 return true;
485 }
486
487 /**
488 * Analyze an XPath expression to see whether the expression is capable of delivering a value of this
489 * type. This method is called during static analysis of a query or stylesheet to give compile-time
490 * warnings when "impossible" paths are used.
491 *
492 * @param expression the expression that delivers the content
493 * @param kind the node kind whose content is being delivered: {@link Type#ELEMENT},
494 * {@link Type#ATTRIBUTE}, or {@link Type#DOCUMENT}
495 * @throws net.sf.saxon.trans.XPathException
496 * if the expression will never deliver a value of the correct type
497 */
498 public void analyzeContentExpression(Expression expression, int kind) throws XPathException {
499 BuiltInAtomicType.analyzeContentExpression(this, expression, kind);
500 }
501
502 /**
503 * Get the typed value of a node that is annotated with this schema type.
504 *
505 * @param node the node whose typed value is required
506 * @return the typed value.
507 * @throws net.sf.saxon.trans.XPathException
508 * if the node cannot be atomized, for example if this is a complex type
509 * with element-only content
510 * @since 8.5. Changed in 9.5 to return the new type AtomicSequence
511 */
512 public AtomicSequence atomize(NodeInfo node) throws XPathException {
513 throw new UnsupportedOperationException(); // nodes are never annotated with a union type
514 }
515
516 /**
517 * Test whether this is the same type as another type. They are considered to be the same type
518 * if they are derived from the same type definition in the original XML representation (which
519 * can happen when there are multiple includes of the same file)
520 *
521 * @param other the other type
522 * @return true if this is the same type as other
523 */
524 public boolean isSameType(SchemaType other) {
525 return other instanceof NumericType;
526 }
527
528 /**
529 * Get a description of this type for use in error messages. This is the same as the display name
530 * in the case of named types; for anonymous types it identifies the type by its position in a source
531 * schema document.
532 *
533 * @return text identifing the type, for use in a phrase such as "the type XXXX".
534 */
535 public String getDescription() {
536 return "xs:numeric";
537 }
538
539 /**
540 * Get the URI of the schema document where the type was originally defined.
541 *
542 * @return the URI of the schema document. Returns null if the information is unknown or if this
543 * is a built-in type
544 */
545 public String getSystemId() {
546 return null;
547 }
548
549 /**
550 * Ask whether this type is an ID type. This is defined to be any simple type
551 * who typed value may contain atomic values of type xs:ID: that is, it includes types derived
552 * from ID by restriction, list, or union. Note that for a node to be treated
553 * as an ID in XSD 1.0, its typed value must be a *single* atomic value of type ID; the type of the
554 * node, however, can still allow a list. But in XSD 1.1, a list of IDs is permitted
555 *
556 * @return true if this type is an ID type
557 */
558 public boolean isIdType() {
559 return false;
560 }
561
562 /**
563 * Ask whether this type is an IDREF or IDREFS type. This is defined to be any simple type
564 * who typed value may contain atomic values of type xs:IDREF: that is, it includes types derived
565 * from IDREF or IDREFS by restriction, list, or union
566 *
567 * @return true if this type is an IDREF type
568 */
569 public boolean isIdRefType() {
570 return false;
571 }
572
573 /**
574 * Get the validation status of this component.
575 */
576 public ValidationStatus getValidationStatus() {
577 return VALIDATED;
578 }
579
580 /**
581 * Get the redefinition level. This is zero for a component that has not been redefined;
582 * for a redefinition of a level-0 component, it is 1; for a redefinition of a level-N
583 * component, it is N+1. This concept is used to support the notion of "pervasive" redefinition:
584 * if a component is redefined at several levels, the top level wins, but it is an error to have
585 * two versions of the component at the same redefinition level.
586 *
587 * @return the redefinition level
588 */
589 public int getRedefinitionLevel() {
590 return 0;
591 }
592
593 /**
594 * Return a string representation of this ItemType suitable for use in stylesheet
595 * export files. This differs from the result of toString() in that it will not contain
596 * any references to anonymous types. Note that it may also use the Saxon extended syntax
597 * for union types and tuple types. The default implementation returns the result of
598 * calling {@code toString()}.
599 *
600 * @return the string representation as an instance of the XPath SequenceType construct
601 */
602 @Override
603 public String toExportString() {
604 return toString();
605 }
606
607 @Override
608 public String toString() {
609 return "xs:numeric";
610 }
611
612 /**
613 * Generate Javascript code to test whether an item conforms to this item type
614 *
615 * @return a Javascript instruction or sequence of instructions, which can be used as the body
616 * of a Javascript function, and which returns a boolean indication whether the value of the
617 * variable "item" is an instance of this item type.
618 * @param knownToBe An item type that the supplied item is known to conform to; the generated code
619 * can assume that the item is an instance of this type.
620 * @param targetVersion The version of Saxon-JS for which code is being generated. Currently either 1 or 2.
621
622 */
623 @Override
624 public String generateJavaScriptItemTypeTest(ItemType knownToBe, int targetVersion) {
625 if (targetVersion == 1) {
626 return "return SaxonJS.U.Atomic.numeric.matches(item);";
627 } else {
628 return "return SaxonJS.U.isNumeric(item);";
629 }
630 }
631
632 /**
633 * Generate Javascript code to convert a supplied Javascript value to this item type,
634 * if conversion is possible, or throw an error otherwise.
635 *
636 * @param errorCode the error to be thrown if conversion is not possible
637 * @param targetVersion the version of Saxon-JS: 1 or 2.
638 * @return a Javascript instruction or sequence of instructions, which can be used as the body
639 * of a Javascript function, and which returns the result of conversion to this type, or throws
640 * an error if conversion is not possible. The variable "val" will hold the supplied Javascript
641 * value.
642 */
643 public String generateJavaScriptItemTypeAcceptor(String errorCode, int targetVersion) throws XPathException {
644 return BuiltInAtomicType.DOUBLE.generateJavaScriptItemTypeAcceptor(errorCode, targetVersion);
645 }
646
647 /**
648 * Check that this type is validly derived from a given type, following the rules for the Schema Component
649 * Constraint "Is Type Derivation OK (Simple)" (3.14.6) or "Is Type Derivation OK (Complex)" (3.4.6) as
650 * appropriate.
651 *
652 * @param base the base type; the algorithm tests whether derivation from this type is permitted
653 * @param block the derivations that are blocked by the relevant element declaration
654 * @throws net.sf.saxon.type.SchemaException if the derivation is not allowed
655 */
656 public void checkTypeDerivationIsOK(SchemaType base, int block) throws SchemaException {
657 //#ifdefined SCHEMA
658 String s = UserSimpleType.isTypeDerivationOK(this, base, block);
659 if (s != null) {
660 throw new SchemaException(s);
661 }
662 //#endif
663 }
664
665 //#ifdefined SCHEMA
666
667 /**
668 * Get the schema component in the form of a function item. This allows schema information
669 * to be made visible to XSLT or XQuery code. The function makes available the contents of the
670 * schema component as defined in the XSD specification. The function takes a string as argument
671 * representing a property name, and returns the corresponding property of the schema component.
672 * There is also a property "class" which returns the kind of schema component, for example
673 * "Attribute Declaration".
674 *
675 * @return the schema component represented as a function from property names to property values.
676 */
677 public Function getComponentAsFunction() {
678 return UserSimpleType.getComponentAsFunction(this);
679 }
680
681 //#endif
682
683 }
684