Debian Codegraph @

net/sf/saxon/type/TypeHierarchy.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.type;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.expr.*;
12 import net.sf.saxon.expr.parser.Location;
13 import net.sf.saxon.expr.parser.RoleDiagnostic;
14 import net.sf.saxon.lib.ConversionRules;
15 import net.sf.saxon.lib.FunctionAnnotationHandler;
16 import net.sf.saxon.ma.map.MapType;
17 import net.sf.saxon.om.Item;
18 import net.sf.saxon.om.Sequence;
19 import net.sf.saxon.om.SequenceIterator;
20 import net.sf.saxon.om.SequenceTool;
21 import net.sf.saxon.pattern.*;
22 import net.sf.saxon.query.Annotation;
23 import net.sf.saxon.query.AnnotationList;
24 import net.sf.saxon.trans.XPathException;
25 import net.sf.saxon.value.*;
26 import net.sf.saxon.z.IntHashSet;
27 import net.sf.saxon.z.IntSet;
28 import net.sf.saxon.z.IntUniversalSet;
29
30 import java.util.*;
31 import java.util.concurrent.ConcurrentHashMap;
32
33 /**
34 * This class exists to provide answers to questions about the type hierarchy. Because
35 * such questions are potentially expensive, it caches the answers. There is one instance of
36 * this class for a Configuration.
37 */
38
39 public class TypeHierarchy {
40
41 private Map<ItemTypePair, Integer> map;
42 protected Configuration config;
43
44 /**
45 * Constant denoting relationship between two types: A is the same type as B
46 */
47 public static final int SAME_TYPE = 0;
48 /**
49 * Constant denoting relationship between two types: A subsumes B
50 */
51 public static final int SUBSUMES = 1;
52 /**
53 * Constant denoting relationship between two types: A is subsumed by B
54 */
55 public static final int SUBSUMED_BY = 2;
56 /**
57 * Constant denoting relationship between two types: A overlaps B
58 */
59 public static final int OVERLAPS = 3;
60 /**
61 * Constant denoting relationship between two types: A is disjoint from B
62 */
63 public static final int DISJOINT = 4;
64
65 //private String[] relnames = {"SAME", "SUBSUMES", "SUBSUMED_BY", "OVERLAPS", "DISJOINT"};
66
67 /**
68 * Create the type hierarchy cache for a configuration
69 *
70 * @param config the configuration
71 */
72
73 public TypeHierarchy(Configuration config) {
74 this.config = config;
75 map = new ConcurrentHashMap<>();
76 }
77
78 /**
79 * Apply the function conversion rules to a value, given a required type.
80 *
81 * @param value a value to be converted
82 * @param requiredType the required type
83 * @param role identifies the value to be converted in error messages
84 * @param locator identifies the location for error messages
85 * @return the converted value
86 * @throws net.sf.saxon.trans.XPathException
87 * if the value cannot be converted to the required type
88 */
89
90 public Sequence<?> applyFunctionConversionRules(Sequence<?> value, SequenceType requiredType, final RoleDiagnostic role, Location locator)
91 throws XPathException {
92 ItemType suppliedItemType = SequenceTool.getItemType(value, this);
93
94 SequenceIterator<?> iterator = value.iterate();
95 final ItemType requiredItemType = requiredType.getPrimaryType();
96
97 if (requiredItemType.isPlainType()) {
98
99 // step 1: apply atomization if necessary
100
101 if (!suppliedItemType.isPlainType()) {
102 try {
103 iterator = Atomizer.getAtomizingIterator(iterator, false);
104 } catch (XPathException e) {
105 ValidationFailure vf = new ValidationFailure(
106 "Failed to atomize the " + role.getMessage() + ": " + e.getMessage());
107 vf.setErrorCode("XPTY0117");
108 throw vf.makeException();
109 }
110 suppliedItemType = suppliedItemType.getAtomizedItemType();
111 }
112
113 // step 2: convert untyped atomic values to target item type
114
115 if (relationship(suppliedItemType, BuiltInAtomicType.UNTYPED_ATOMIC) != DISJOINT &&
116 !isSubType(BuiltInAtomicType.UNTYPED_ATOMIC, requiredItemType)) {
117 final boolean nsSensitive = ((SimpleType) requiredItemType).isNamespaceSensitive();
118 ItemMappingFunction<Item<?>, Item<?>> converter;
119 if (nsSensitive) {
120 converter = item -> {
121 if (item instanceof UntypedAtomicValue) {
122 ValidationFailure vf = new ValidationFailure(
123 "Failed to convert the " + role.getMessage() + ": " +
124 "Implicit conversion of untypedAtomic value to " + requiredItemType +
125 " is not allowed");
126 vf.setErrorCode("XPTY0117");
127 throw vf.makeException();
128 } else {
129 return item;
130 }
131 };
132 } else if (((SimpleType) requiredItemType).isUnionType()) {
133 final ConversionRules rules = config.getConversionRules();
134 converter = item -> {
135 if (item instanceof UntypedAtomicValue) {
136 try {
137 return ((SimpleType) requiredItemType).getTypedValue(
138 item.getStringValueCS(), null, rules).head();
139 } catch (ValidationException ve) {
140 ve.setErrorCode("XPTY0004");
141 throw ve;
142 }
143 } else {
144 return item;
145 }
146 };
147 } else {
148 converter = item -> {
149 if (item instanceof UntypedAtomicValue) {
150 return Converter.convert(
151 (UntypedAtomicValue) item, (AtomicType) requiredItemType, config.getConversionRules());
152 } else {
153 return item;
154 }
155 };
156 }
157 iterator = new ItemMappingIterator<>(iterator, converter, true);
158 }
159
160 // step 3: apply numeric promotion
161
162 if (requiredItemType.equals(BuiltInAtomicType.DOUBLE)) {
163 ItemMappingFunction<Item<?>, Item<?>> promoter = item -> {
164 if (item instanceof NumericValue) {
165 return (DoubleValue) Converter.convert(
166 (NumericValue)item, BuiltInAtomicType.DOUBLE, config.getConversionRules()).asAtomic();
167 } else {
168 throw new XPathException(
169 "Failed to convert the " + role.getMessage() + ": " +
170 "Cannot promote non-numeric value to xs:double", "XPTY0004");
171 }
172 };
173 iterator = new ItemMappingIterator<>(iterator, promoter, true);
174 } else if (requiredItemType.equals(BuiltInAtomicType.FLOAT)) {
175 ItemMappingFunction<Item<?>, Item<?>> promoter = item -> {
176 if (item instanceof DoubleValue) {
177 throw new XPathException(
178 "Failed to convert the " + role.getMessage() + ": " +
179 "Cannot promote xs:double value to xs:float", "XPTY0004");
180 } else if (item instanceof NumericValue) {
181 return (FloatValue) Converter.convert(
182 (NumericValue)item, BuiltInAtomicType.FLOAT, config.getConversionRules()).asAtomic();
183 } else {
184 throw new XPathException(
185 "Failed to convert the " + role.getMessage() + ": " +
186 "Cannot promote non-numeric value to xs:float", "XPTY0004");
187 }
188 };
189 iterator = new ItemMappingIterator<>(iterator, promoter, true);
190 }
191
192 // step 4: apply URI-to-string promotion
193
194 if (requiredItemType.equals(BuiltInAtomicType.STRING) &&
195 relationship(suppliedItemType, BuiltInAtomicType.ANY_URI) != DISJOINT) {
196 ItemMappingFunction<Item<?>, Item<?>> promoter = item -> {
197 if (item instanceof AnyURIValue) {
198 return new StringValue(item.getStringValueCS());
199 } else {
200 return item;
201 }
202 };
203 iterator = new ItemMappingIterator<>(iterator, promoter, true);
204 }
205 }
206
207 // step 5: apply function coercion
208
209 iterator = applyFunctionCoercion(iterator, suppliedItemType, requiredItemType, locator);
210
211 // Add a check that the values conform to the required type
212
213 int relation = relationship(suppliedItemType, requiredItemType);
214
215 if (!(relation == SAME_TYPE || relation == SUBSUMED_BY)) {
216 ItemTypeCheckingFunction<Item<?>> itemChecker =
217 new ItemTypeCheckingFunction<>(requiredItemType, role, locator, config);
218 iterator = new ItemMappingIterator<>(iterator, itemChecker, true);
219 }
220
221 if (requiredType.getCardinality() != StaticProperty.ALLOWS_ZERO_OR_MORE) {
222 iterator = new CardinalityCheckingIterator<>(iterator, requiredType.getCardinality(), role, locator);
223 }
224
225 return SequenceTool.toMemoSequence(iterator);
226
227 }
228
229 /**
230 * Apply function coercion when function items are supplied as arguments to a function call.
231 * This does not happen in Saxon-HE, so the implementation is subclassed in Saxon-PE/EE
232 *
233 * @param iterator An iterator over the supplied value of the parameter
234 * @param suppliedItemType the item type of the supplied value
235 * @param requiredItemType the required item type (typically a function item type)
236 * @param locator information for diagnostics
237 * @return an iterator over the converted value
238 */
239
240 protected SequenceIterator<?> applyFunctionCoercion(SequenceIterator<?> iterator,
241 ItemType suppliedItemType, ItemType requiredItemType,
242 Location locator) {
243 return iterator;
244 }
245
246 /**
247 * Get the Saxon configuration to which this type hierarchy belongs
248 *
249 * @return the configuration
250 */
251
252 public Configuration getConfiguration() {
253 return config;
254 }
255
256 /**
257 * Determine whether type A is type B or one of its subtypes, recursively.
258 * "Subtype" here means a type that is subsumed, that is, a type whose instances
259 * are a subset of the instances of the other type.
260 *
261 * @param subtype identifies the first type
262 * @param supertype identifies the second type
263 * @return true if the first type is the second type or is subsumed by the second type
264 */
265
266 public boolean isSubType(ItemType subtype, /*@NotNull*/ ItemType supertype) {
267 int relation = relationship(subtype, supertype);
268 return relation == SAME_TYPE || relation == SUBSUMED_BY;
269 }
270
271 /**
272 * Determine the relationship of one item type to another.
273 *
274 * @param t1 the first item type
275 * @param t2 the second item type
276 * @return {@link #SAME_TYPE} if the types are the same; {@link #SUBSUMES} if the first
277 * type subsumes the second (that is, all instances of the second type are also instances
278 * of the first); {@link #SUBSUMED_BY} if the second type subsumes the first;
279 * {@link #OVERLAPS} if the two types overlap (have a non-empty intersection, but neither
280 * subsumes the other); {@link #DISJOINT} if the two types are disjoint (have an empty intersection)
281 */
282
283 public int relationship(/*@Nullable*/ ItemType t1, /*@NotNull*/ ItemType t2) {
284 if (t1 == null) {
285 throw new NullPointerException();
286 }
287 t1 = stabilize(t1);
288 t2 = stabilize(t2);
289 if (t1.equals(t2)) {
290 return SAME_TYPE;
291 }
292 // Before we look in the cache, which involves computing hash keys, check for some simple and common cases
293 if (t2 instanceof AnyItemType) {
294 return SUBSUMED_BY;
295 }
296 if (t1 instanceof AnyItemType) {
297 return SUBSUMES;
298 }
299 if (t1 instanceof ErrorType) {
300 return SUBSUMED_BY;
301 }
302 if (t2 instanceof ErrorType) {
303 return SUBSUMES;
304 }
305 ItemTypePair pair = new ItemTypePair(t1, t2);
306 Integer result = map.get(pair);
307 if (result == null) {
308 result = computeRelationship(t1, t2);
309 map.put(pair, result);
310 }
311 return result;
312 }
313
314 /**
315 * Replace an item type, where necessary, by one that can safely be stored in the cache
316 * without causing garbage collection problems. Specifically, a SameNameTest cannot be stored
317 * in the cache because it contains a reference to a node in a document.
318 * @param in the supplied item type
319 * @return either the supplied item type, or an equivalent that can safely be cached.
320 */
321
322 private static ItemType stabilize(ItemType in) {
323 if (in instanceof SameNameTest) {
324 // we don't want to put a SameNameTest in the cache because it locks down the referenced document
325 return ((SameNameTest)in).getEquivalentNameTest();
326 } else {
327 return in;
328 }
329 }
330
331 /**
332 * Determine the relationship of one item type to another. This should be equivalent to the
333 * rules for subtype-itemType(t1, t2) (in the XPath31 specification section 2.5.6.2), except that
334 * we are computing a more precise relationship:
335 *
336 * <ul>
337 * <li>If subtype(A, B) and subtype(B, A) then SAME_TYPE</li>
338 * <li>Else, if subtype(A, B) then SUBSUMED_BY</li>
339 * <li>Else, if subtype(A, B) then SUBSUMES</li>
340 * <li>Else, if the value spaces of A and B have a non-empty intersection then OVERLAPS</li>
341 * <li>Else, DISJOINT.</li>
342 * </ul>
343 *
344 * @param t1 the first item type
345 * @param t2 the second item type
346 * @return {@link #SAME_TYPE} if the types are the same; {@link #SUBSUMES} if the first
347 * type subsumes the second (that is, all instances of the second type are also instances
348 * of the first); {@link #SUBSUMED_BY} if the second type subsumes the first;
349 * {@link #OVERLAPS} if the two types overlap (have a non-empty intersection, but neither
350 * subsumes the other); {@link #DISJOINT} if the two types are disjoint (have an empty intersection)
351 */
352
353 private int computeRelationship(ItemType t1, ItemType t2) {
354 //System.err.println("computeRelationship " + t1 + ", " + t2);
355 requireTrueItemType(t1);
356 requireTrueItemType(t2);
357 try {
358 if (t1 == t2) {
359 return SAME_TYPE;
360 }
361 if (t1 instanceof AnyItemType) {
362 if (t2 instanceof AnyItemType) {
363 return SAME_TYPE;
364 } else {
365 return SUBSUMES;
366 }
367 } else if (t2 instanceof AnyItemType) {
368 return SUBSUMED_BY;
369 } else if (t1.isPlainType()) {
370 if (t2 instanceof NodeTest || t2 instanceof FunctionItemType || t2 instanceof JavaExternalObjectType) {
371 return DISJOINT;
372 } else if (t1 == BuiltInAtomicType.ANY_ATOMIC && t2.isPlainType()) {
373 return SUBSUMES;
374 } else if (t2 == BuiltInAtomicType.ANY_ATOMIC) {
375 return SUBSUMED_BY;
376 } else if (t1 instanceof AtomicType && t2 instanceof AtomicType) {
377 if (((AtomicType) t1).getFingerprint() == ((AtomicType) t2).getFingerprint()) {
378 return SAME_TYPE;
379 }
380 AtomicType t = (AtomicType)t2;
381 while (true) {
382 if (((AtomicType) t1).getFingerprint() == t.getFingerprint()) {
383 return SUBSUMES;
384 }
385 SchemaType st = t.getBaseType();
386 if (st instanceof AtomicType) {
387 t = (AtomicType)st;
388 } else {
389 break;
390 }
391 }
392 t = (AtomicType)t1;
393 while (true) {
394 if (t.getFingerprint() == ((AtomicType) t2).getFingerprint()) {
395 return SUBSUMED_BY;
396 }
397 SchemaType st = t.getBaseType();
398 if (st instanceof AtomicType) {
399 t = (AtomicType)st;
400 } else {
401 break;
402 }
403 }
404 return DISJOINT;
405
406 } else if (!t1.isAtomicType() && t2.isPlainType()) {
407 // relationship(union, atomic) or relationship(union, union)
408 Set<? extends PlainType> s1 = toSet(((PlainType) t1).getPlainMemberTypes());
409 Set<? extends PlainType> s2 = toSet(((PlainType) t2).getPlainMemberTypes());
410
411 if (!unionOverlaps(s1, s2)) {
412 return DISJOINT;
413 }
414
415 boolean gt = s1.containsAll(s2);
416 boolean lt = s2.containsAll(s1);
417 if (gt && lt) {
418 return SAME_TYPE;
419 } else if (gt) {
420 return SUBSUMES;
421 } else if (lt) {
422 return SUBSUMED_BY;
423 } else if (unionSubsumes(s1, s2)) {
424 return SUBSUMES;
425 } else if (unionSubsumes(s2, s1)) {
426 return SUBSUMED_BY;
427 } else {
428 return OVERLAPS;
429 }
430
431 } else if (t1 instanceof AtomicType) {
432 // relationship (atomic, union)
433 int r = relationship(t2, t1);
434 return inverseRelationship(r);
435
436 } else {
437 // all options exhausted
438 throw new IllegalStateException();
439 }
440 } else if (t1 instanceof NodeTest) {
441 if (t2.isPlainType() || t2 instanceof FunctionItemType) {
442 return DISJOINT;
443 } else {
444 // both types are NodeTests
445 if (t1 instanceof AnyNodeTest) {
446 if (t2 instanceof AnyNodeTest) {
447 return SAME_TYPE;
448 } else {
449 return SUBSUMES;
450 }
451 } else if (t2 instanceof AnyNodeTest) {
452 return SUBSUMED_BY;
453 } else if (t2 instanceof ErrorType) {
454 return DISJOINT;
455 } else {
456 // first find the relationship between the node kinds allowed
457 int nodeKindRelationship;
458 UType m1 = t1.getUType();
459 UType m2 = t2.getUType();
460 if (!m1.overlaps(m2)) {
461 return DISJOINT;
462 } else if (m1.equals(m2)) {
463 nodeKindRelationship = SAME_TYPE;
464 } else if (m2.subsumes(m1)) {
465 nodeKindRelationship = SUBSUMED_BY;
466 } else if (m1.subsumes(m2)) {
467 nodeKindRelationship = SUBSUMES;
468 } else {
469 nodeKindRelationship = OVERLAPS;
470 }
471
472 // Now find the relationship between the node names allowed. See bug 3713
473 int nodeNameRelationship;
474 Optional<IntSet> on1 = ((NodeTest) t1).getRequiredNodeNames();
475 Optional<IntSet> on2 = ((NodeTest) t2).getRequiredNodeNames();
476
477 if (t1 instanceof QNameTest && t2 instanceof QNameTest) {
478 nodeNameRelationship = nameTestRelationship((QNameTest)t1, (QNameTest)t2);
479 } else if (on1.isPresent() && on1.get() instanceof IntUniversalSet) {
480 if (on2.isPresent() && on2.get() instanceof IntUniversalSet) {
481 nodeNameRelationship = SAME_TYPE;
482 } else {
483 nodeNameRelationship = SUBSUMES;
484 }
485 } else if (on2.isPresent() && on2.get() instanceof IntUniversalSet) {
486 nodeNameRelationship = SUBSUMED_BY;
487 } else if (!(on1.isPresent() && on2.isPresent())) {
488 nodeNameRelationship = t1.equals(t2) ? SAME_TYPE : OVERLAPS;
489 } else {
490 IntSet n1 = on1.get();
491 IntSet n2 = on2.get();
492 if (n1.containsAll(n2)) {
493 if (n1.size() == n2.size()) {
494 nodeNameRelationship = SAME_TYPE;
495 } else {
496 nodeNameRelationship = SUBSUMES;
497 }
498 } else if (n2.containsAll(n1)) {
499 nodeNameRelationship = SUBSUMED_BY;
500 } else if (IntHashSet.containsSome(n1, n2)) {
501 nodeNameRelationship = OVERLAPS;
502 } else {
503 nodeNameRelationship = DISJOINT;
504 }
505 }
506
507 // now find the relationship between the content types allowed
508
509 int contentRelationship = computeContentRelationship(t1, t2, on1, on2);
510
511 // now analyse the three different relationsships
512
513 if (nodeKindRelationship == SAME_TYPE &&
514 nodeNameRelationship == SAME_TYPE &&
515 contentRelationship == SAME_TYPE) {
516 return SAME_TYPE;
517 } else if ((nodeKindRelationship == SAME_TYPE || nodeKindRelationship == SUBSUMES) &&
518 (nodeNameRelationship == SAME_TYPE || nodeNameRelationship == SUBSUMES) &&
519 (contentRelationship == SAME_TYPE || contentRelationship == SUBSUMES)) {
520 return SUBSUMES;
521 } else if ((nodeKindRelationship == SAME_TYPE || nodeKindRelationship == SUBSUMED_BY) &&
522 (nodeNameRelationship == SAME_TYPE || nodeNameRelationship == SUBSUMED_BY) &&
523 (contentRelationship == SAME_TYPE || contentRelationship == SUBSUMED_BY)) {
524 return SUBSUMED_BY;
525 } else if (nodeNameRelationship == DISJOINT || contentRelationship == DISJOINT) {
526 return DISJOINT;
527 } else {
528 return OVERLAPS;
529 }
530 }
531 }
532 } else if (t1 instanceof AnyExternalObjectType) {
533 if (!(t2 instanceof AnyExternalObjectType)) {
534 return DISJOINT;
535 }
536 if (t1 instanceof JavaExternalObjectType) {
537 if (t2 == AnyExternalObjectType.THE_INSTANCE) {
538 return SUBSUMED_BY;
539 } else if (t2 instanceof JavaExternalObjectType) {
540 return ((JavaExternalObjectType)t1).getRelationship((JavaExternalObjectType)t2);
541 } else {
542 return DISJOINT;
543 }
544 }
545 if (t2 instanceof JavaExternalObjectType) {
546 return SUBSUMES;
547 } else {
548 return DISJOINT;
549 }
550 } else {
551 // t1 is a FunctionItemType
552 if (t1 instanceof MapType && t2 instanceof MapType) {
553 if (t1 == MapType.EMPTY_MAP_TYPE) {
554 return SUBSUMED_BY;
555 } else if (t2 == MapType.EMPTY_MAP_TYPE) {
556 return SUBSUMES;
557 }
558 if (t1 == MapType.ANY_MAP_TYPE) {
559 return SUBSUMES;
560 } else if (t2 == MapType.ANY_MAP_TYPE) {
561 return SUBSUMED_BY;
562 }
563 AtomicType k1 = ((MapType)t1).getKeyType();
564 AtomicType k2 = ((MapType)t2).getKeyType();
565 SequenceType v1 = ((MapType)t1).getValueType();
566 SequenceType v2 = ((MapType)t2).getValueType();
567 int keyRel = relationship(k1, k2);
568 int valueRel = sequenceTypeRelationship(v1, v2);
569 int rel = combineRelationships(keyRel, valueRel);
570 if (rel == SAME_TYPE || rel == SUBSUMES || rel == SUBSUMED_BY) {
571 return rel;
572 }
573 // For other relationships, it's more complex because of the need to compare as function type,
574 // so just fall through
575 }
576 if (t2 instanceof FunctionItemType) {
577 int signatureRelationship = ((FunctionItemType) t1).relationship((FunctionItemType) t2, this);
578 if (signatureRelationship == DISJOINT) {
579 return DISJOINT;
580 } else {
581 int assertionRelationship = SAME_TYPE;
582 AnnotationList first = ((FunctionItemType) t1).getAnnotationAssertions();
583 AnnotationList second = ((FunctionItemType) t2).getAnnotationAssertions();
584 Set<String> namespaces = new HashSet<>();
585 for (Annotation a : first) {
586 namespaces.add(a.getAnnotationQName().getURI());
587 }
588 for (Annotation a : second) {
589 namespaces.add(a.getAnnotationQName().getURI());
590 }
591 for (String ns : namespaces) {
592 FunctionAnnotationHandler handler = config.getFunctionAnnotationHandler(ns);
593 if (handler != null) {
594 int localRel = SAME_TYPE;
595 AnnotationList firstFiltered = first.filterByNamespace(ns);
596 AnnotationList secondFiltered = second.filterByNamespace(ns);
597 if (firstFiltered.isEmpty()) {
598 if (secondFiltered.isEmpty()) {
599 // no action
600 } else {
601 localRel = SUBSUMES;
602 }
603 } else {
604 if (secondFiltered.isEmpty()) {
605 localRel = SUBSUMED_BY;
606 } else {
607 localRel = handler.relationship(firstFiltered, secondFiltered);
608 }
609 }
610 assertionRelationship = combineRelationships(assertionRelationship, localRel);
611 }
612 }
613 return combineRelationships(signatureRelationship, assertionRelationship);
614 }
615 } else {
616 return DISJOINT;
617 }
618 }
619 } catch (MissingComponentException e) {
620 return OVERLAPS;
621 }
622 }
623
624 private static void requireTrueItemType(ItemType t) {
625 Objects.requireNonNull(t);
626 if (!t.isTrueItemType()) {
627 throw new AssertionError(t + " is a non-pure union type");
628 }
629 }
630
631 private static int nameTestRelationship(QNameTest t1, QNameTest t2) {
632 if (t1.equals(t2)) {
633 return SAME_TYPE;
634 }
635 if (t2 instanceof NameTest) {
636 return t1.matches(((NameTest) t2).getMatchingNodeName()) ? SUBSUMES : DISJOINT;
637 }
638 if (t1 instanceof NameTest) {
639 return t2.matches(((NameTest) t1).getMatchingNodeName()) ? SUBSUMED_BY : DISJOINT;
640 }
641 if (t2 instanceof SameNameTest) {
642 return t1.matches(((SameNameTest) t2).getMatchingNodeName()) ? SUBSUMES : DISJOINT;
643 }
644 if (t1 instanceof SameNameTest) {
645 return t2.matches(((SameNameTest) t1).getMatchingNodeName()) ? SUBSUMED_BY : DISJOINT;
646 }
647 if (t1 instanceof NamespaceTest && t2 instanceof NamespaceTest) {
648 return DISJOINT;
649 }
650 if (t1 instanceof LocalNameTest && t2 instanceof LocalNameTest) {
651 return DISJOINT;
652 }
653 return OVERLAPS;
654 }
655
656 private static int combineRelationships(int rel1, int rel2) {
657 if (rel1 == SAME_TYPE &&
658 rel2 == SAME_TYPE) {
659 return SAME_TYPE;
660 } else if ((rel1 == SAME_TYPE || rel1 == SUBSUMES) &&
661 (rel2 == SAME_TYPE || rel2 == SUBSUMES)) {
662 return SUBSUMES;
663 } else if ((rel1 == SAME_TYPE || rel1 == SUBSUMED_BY) &&
664 (rel2 == SAME_TYPE || rel2 == SUBSUMED_BY)) {
665 return SUBSUMED_BY;
666 } else if (rel1 == DISJOINT ||
667 rel2 == DISJOINT) {
668 return DISJOINT;
669 } else {
670 return OVERLAPS;
671 }
672 }
673
674
675 /**
676 * Convert a collection to a set
677 *
678 * @param in the input collection
679 * @param <X> the member type of the collection
680 * @return a set with the same members as the supplied collection
681 */
682
683
684 private static <X> Set<X> toSet(Iterable<X> in) {
685 Set<X> s = new HashSet<>();
686 for (X x : in) {
687 s.add(x);
688 }
689 return s;
690 }
691
692 /**
693 * Ask whether one union type subsumes another
694 * @param s1 the member types of the first union type
695 * @param s2 the member types of the second union type
696 * @return true if every type t2 in s2 is subsumed by the first union type; except that
697 * we assume this is the case only if t2 is subsumed by some member type of the first union type.
698 */
699
700 private boolean unionSubsumes(Set<? extends PlainType> s1, Set<? extends PlainType> s2) {
701 // s1 subsumes s2 if every t2 in s2 is subsumed by some t1 in s1 (we'll discount the possibility
702 // of some t2 in s2 being subsumed by a combination of multiple types in s1)
703 for (PlainType t2 : s2) {
704 boolean t2isSubsumed = false;
705 for (PlainType t1 : s1) {
706 int rel = relationship(t1, t2);
707 if (rel == SUBSUMES || rel == SAME_TYPE) {
708 t2isSubsumed = true;
709 break;
710 }
711 }
712 if (!t2isSubsumed) {
713 return false;
714 }
715 }
716 return true;
717 }
718
719 /**
720 * Ask whether two union types are disjoint
721 * @param s1 the set of member types of the first union type
722 * @param s2 the set of member types of the second union type
723 * @return true if some S1 in s1 has instances in common with some S2 in s2
724 */
725
726 private boolean unionOverlaps(Set<? extends PlainType> s1, Set<? extends PlainType> s2) {
727 for (PlainType t2 : s2) {
728 for (PlainType t1 : s1) {
729 int rel = relationship(t1, t2);
730 if (rel != DISJOINT) {
731 return true;
732 }
733 }
734 }
735 return false;
736 }
737
738
739 /**
740 * Compute the relationship between the allowed content-types of two types,
741 * for example attribute(*, xs:integer) and attribute(xs:string). Note that
742 * although such types are fairly meaningless in a non-schema-aware environment,
743 * they are permitted, and supported in Saxon-HE.
744 *
745 * @param t1 the first type
746 * @param t2 the second types
747 * @param n1 the set of element names allowed by the first type
748 * @param n2 the set of element names allowed by the second type
749 * @return the relationship (same type, subsumes, overlaps, subsumed-by)
750 */
751 protected int computeContentRelationship(ItemType t1, ItemType t2, Optional<IntSet> n1, Optional<IntSet> n2) {
752 int contentRelationship;
753 if (t1 instanceof DocumentNodeTest) {
754 if (t2 instanceof DocumentNodeTest) {
755 contentRelationship = relationship(((DocumentNodeTest) t1).getElementTest(),
756 ((DocumentNodeTest) t2).getElementTest());
757 } else {
758 contentRelationship = SUBSUMED_BY;
759 }
760 } else if (t2 instanceof DocumentNodeTest) {
761 contentRelationship = SUBSUMES;
762 } else {
763 SchemaType s1 = ((NodeTest) t1).getContentType();
764 SchemaType s2 = ((NodeTest) t2).getContentType();
765 contentRelationship = schemaTypeRelationship(s1, s2);
766 }
767
768 boolean nillable1 = ((NodeTest) t1).isNillable();
769 boolean nillable2 = ((NodeTest) t2).isNillable();
770
771 // Adjust the results to take nillability into account
772 // Note: although nodes cannot be nilled in a non-schema-aware environment,
773 // nillability still affects the relationships between types, for example
774 // element(e) and element(e, xs:anyType): see xslt3 test higher-order-functions-034.
775
776 if (nillable1 != nillable2) {
777 switch (contentRelationship) {
778 case SUBSUMES:
779 if (nillable2) {
780 contentRelationship = OVERLAPS;
781 break;
782 }
783 case SUBSUMED_BY:
784 if (nillable1) {
785 contentRelationship = OVERLAPS;
786 break;
787 }
788 case SAME_TYPE:
789 if (nillable1) {
790 contentRelationship = SUBSUMES;
791 } else {
792 contentRelationship = SUBSUMED_BY;
793 }
794 break;
795 default:
796 break;
797 }
798 }
799 return contentRelationship;
800 }
801
802 /**
803 * Get the relationship of two sequence types to each other
804 * @param s1 the first type
805 * @param s2 the second type
806 * @return the relationship, as one of the constants
807 * {@link net.sf.saxon.type.TypeHierarchy#SAME_TYPE}, {@link net.sf.saxon.type.TypeHierarchy#SUBSUMES},
808 * {@link net.sf.saxon.type.TypeHierarchy#SUBSUMED_BY}, {@link net.sf.saxon.type.TypeHierarchy#DISJOINT},
809 * {@link #OVERLAPS}
810 */
811
812 public int sequenceTypeRelationship(SequenceType s1, SequenceType s2) {
813 int c1 = s1.getCardinality();
814 int c2 = s2.getCardinality();
815 int cardRel;
816 if (c1 == c2) {
817 cardRel = SAME_TYPE;
818 } else if (Cardinality.subsumes(c1, c2)) {
819 cardRel = SUBSUMES;
820 } else if (Cardinality.subsumes(c2, c1)) {
821 cardRel = SUBSUMED_BY;
822 } else if (c1 == StaticProperty.EMPTY && !Cardinality.allowsZero(c2)) {
823 return DISJOINT;
824 } else if (c2 == StaticProperty.EMPTY && !Cardinality.allowsZero(c1)) {
825 return DISJOINT;
826 } else {
827 cardRel = TypeHierarchy.OVERLAPS;
828 }
829
830 int itemRel = relationship(s1.getPrimaryType(), s2.getPrimaryType());
831
832 if (itemRel == DISJOINT) {
833 return DISJOINT;
834 }
835
836 if (cardRel == SAME_TYPE || cardRel == itemRel) {
837 return itemRel;
838 }
839
840 if (itemRel == SAME_TYPE) {
841 return cardRel;
842 }
843
844 return OVERLAPS;
845 }
846
847 /**
848 * Get the relationship of two schema types to each other
849 *
850 * @param s1 the first type
851 * @param s2 the second type
852 * @return the relationship of the two types, as one of the constants
853 * {@link net.sf.saxon.type.TypeHierarchy#SAME_TYPE}, {@link net.sf.saxon.type.TypeHierarchy#SUBSUMES},
854 * {@link net.sf.saxon.type.TypeHierarchy#SUBSUMED_BY}, {@link net.sf.saxon.type.TypeHierarchy#DISJOINT}
855 */
856
857 public int schemaTypeRelationship(SchemaType s1, SchemaType s2) {
858 if (s1.isSameType(s2)) {
859 return SAME_TYPE;
860 }
861 if (s1 instanceof AnyType) {
862 return SUBSUMES;
863 }
864 if (s2 instanceof AnyType) {
865 return SUBSUMED_BY;
866 }
867 if (s1 instanceof Untyped && (s2 == BuiltInAtomicType.ANY_ATOMIC || s2 == BuiltInAtomicType.UNTYPED_ATOMIC)) {
868 return OVERLAPS;
869 }
870 if (s2 instanceof Untyped && (s1 == BuiltInAtomicType.ANY_ATOMIC || s1 == BuiltInAtomicType.UNTYPED_ATOMIC)) {
871 return OVERLAPS;
872 }
873 if (s1 instanceof PlainType && ((PlainType)s1).isPlainType()
874 && s2 instanceof PlainType && ((PlainType) s2).isPlainType()) {
875 return relationship((ItemType)s1, (ItemType)s2);
876
877 // See bug 4007. Technically, this isn't quite right. If U is union(X,Y), and V is union(X,Y,Z),
878 // then itemType-subtype(U, V) is true (XPath31 2.5.6.2 rule 2), but derives-from(U, V) is false.
879 // We're computing the derives-from relationship here (for example, to assess whether element(*, U)
880 // is substitutable for element(*, V) in a function signature), and by delegating to test the
881 // item type relationship, we are returning true for this case when it should be false.
882 // It's not clear whether this difference in the spec is intentional, and it doesn't cause
883 // any test cases to fail, so I decided to leave it. I don't think it causes any problems
884 // with type safety, because elements and attributes validated against union(X, Y) will have
885 // a type annotation of either X or Y, which means they will be accepted as instances of
886 // element(*, union(X,Y,Z)): that is, the instances of element(*, union(X,Y)) are indeed
887 // a subset of the instances of element(*, union(X,Y,Z)). MHK 2018-11-08.
888 }
889 SchemaType t1 = s1;
890 while ((t1 = t1.getBaseType()) != null) {
891 if (t1.isSameType(s2)) {
892 return SUBSUMED_BY;
893 }
894 }
895 SchemaType t2 = s2;
896 while ((t2 = t2.getBaseType()) != null) {
897 if (t2.isSameType(s1)) {
898 return SUBSUMES;
899 }
900 }
901 return DISJOINT;
902 }
903
904
905 public static int inverseRelationship(int relation) {
906 switch (relation) {
907 case SAME_TYPE:
908 return SAME_TYPE;
909 case SUBSUMES:
910 return SUBSUMED_BY;
911 case SUBSUMED_BY:
912 return SUBSUMES;
913 case OVERLAPS:
914 return OVERLAPS;
915 case DISJOINT:
916 return DISJOINT;
917 default:
918 throw new IllegalArgumentException();
919 }
920 }
921
922 public ItemType getGenericFunctionItemType() {
923 return AnyItemType.getInstance();
924 }
925
926
927
928 private static class ItemTypePair {
929 ItemType s;
930 ItemType t;
931
932 public ItemTypePair(ItemType s, ItemType t) {
933 this.s = s;
934 this.t = t;
935 }
936
937 /**
938 * Returns a hash code value for the object.
939 *
940 * @return a hash code value for this object.
941 * @see Object#equals(Object)
942 * @see java.util.Hashtable
943 */
944 public int hashCode() {
945 return s.hashCode() ^ t.hashCode();
946 }
947
948 /**
949 * Indicates whether some other object is "equal to" this one.
950 */
951
952 public boolean equals(Object obj) {
953 if (obj instanceof ItemTypePair) {
954 final ItemTypePair pair = (ItemTypePair) obj;
955 return s.equals(pair.s) && t.equals(pair.t);
956 } else {
957 return false;
958 }
959 }
960 }
961
962
963 }
964