Debian Codegraph @

net/sf/saxon/ma/map/MapType.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.ma.map;
9
10 import net.sf.saxon.expr.Expression;
11 import net.sf.saxon.expr.StaticProperty;
12 import net.sf.saxon.expr.parser.RoleDiagnostic;
13 import net.sf.saxon.om.Genre;
14 import net.sf.saxon.om.Item;
15 import net.sf.saxon.trans.Err;
16 import net.sf.saxon.trans.XPathException;
17 import net.sf.saxon.tree.util.FastStringBuffer;
18 import net.sf.saxon.type.*;
19 import net.sf.saxon.value.Cardinality;
20 import net.sf.saxon.value.SequenceType;
21
22 import java.util.Optional;
23
24 /**
25 * An instance of this class represents a specific map item type, for example
26 * map(x:integer, element(employee))
27 */
28 public class MapType extends AnyFunctionType {
29
30 public final static MapType ANY_MAP_TYPE = new MapType(BuiltInAtomicType.ANY_ATOMIC, SequenceType.ANY_SEQUENCE);
31
32 // The type of a map with no entries. It's handled specially in some static type inferencing rules
33 public final static MapType EMPTY_MAP_TYPE = new MapType(BuiltInAtomicType.ANY_ATOMIC, SequenceType.ANY_SEQUENCE, true);
34
35 /**
36 * A type that allows a sequence of zero or one map items
37 */
38 public static final SequenceType OPTIONAL_MAP_ITEM =
39 SequenceType.makeSequenceType(ANY_MAP_TYPE, StaticProperty.ALLOWS_ZERO_OR_ONE);
40 public static final SequenceType SINGLE_MAP_ITEM =
41 SequenceType.makeSequenceType(ANY_MAP_TYPE, StaticProperty.ALLOWS_ONE);
42 public static final SequenceType SEQUENCE_OF_MAPS =
43 SequenceType.makeSequenceType(ANY_MAP_TYPE, StaticProperty.ALLOWS_ZERO_OR_MORE);
44
45 private AtomicType keyType;
46 private SequenceType valueType;
47 private boolean mustBeEmpty;
48
49 public MapType(AtomicType keyType, SequenceType valueType) {
50 this.keyType = keyType;
51 this.valueType = valueType;
52 this.mustBeEmpty = false;
53 }
54
55 public MapType(AtomicType keyType, SequenceType valueType, boolean mustBeEmpty) {
56 this.keyType = keyType;
57 this.valueType = valueType;
58 this.mustBeEmpty = mustBeEmpty;
59 }
60
61 /**
62 * Determine the Genre (top-level classification) of this type
63 *
64 * @return the Genre to which this type belongs, specifically {@link Genre#MAP}
65 */
66 @Override
67 public Genre getGenre() {
68 return Genre.MAP;
69 }
70
71 /**
72 * Get the type of the keys
73 * @return the type to which all keys must conform
74 */
75
76 public AtomicType getKeyType() {
77 return keyType;
78 }
79
80 /**
81 * Get the type of the indexed values
82 * @return the type to which all associated values must conform
83 */
84
85 public SequenceType getValueType() {
86 return valueType;
87 }
88
89 /**
90 * Ask whether this function item type is a map type. In this case function coercion (to the map type)
91 * will never succeed.
92 *
93 * @return true if this FunctionItemType is a map type
94 */
95 @Override
96 public boolean isMapType() {
97 return true;
98 }
99
100 /**
101 * Ask whether this function item type is an array type. In this case function coercion (to the array type)
102 * will never succeed.
103 *
104 * @return true if this FunctionItemType is an array type
105 */
106 @Override
107 public boolean isArrayType() {
108 return false;
109 }
110
111 /**
112 * Get an alphabetic code representing the type, or at any rate, the nearest built-in type
113 * from which this type is derived. The codes are designed so that for any two built-in types
114 * A and B, alphaCode(A) is a prefix of alphaCode(B) if and only if A is a supertype of B.
115 *
116 * @return the alphacode for the nearest containing built-in type
117 */
118 @Override
119 public String getAlphaCode() {
120 return "FM";
121 }
122
123 /**
124 * Ask whether values of this type are atomizable
125 *
126 * @return true if some or all instances of this type can be successfully atomized; false
127 * * if no instances of this type can be atomized
128 * @param th The type hierarchy cache
129 */
130
131 public boolean isAtomizable(TypeHierarchy th) {
132 return false;
133 }
134
135 /**
136 * Test whether a given item conforms to this type
137 *
138 * @param item The item to be tested
139 * @param th
140 * @return true if the item is an instance of this type; false otherwise
141 */
142 @Override
143 public boolean matches(Item item, TypeHierarchy th) {
144 if (!(item instanceof MapItem)){
145 return false;
146 }
147 if (((MapItem) item).isEmpty()) {
148 return true;
149 } else if (mustBeEmpty) {
150 return false;
151 }
152 if (this == ANY_MAP_TYPE) {
153 return true;
154 } else {
155 return ((MapItem)item).conforms(keyType, valueType, th);
156 }
157 }
158
159 /**
160 * Get the arity (number of arguments) of this function type
161 *
162 * @return the number of argument types in the function signature
163 */
164
165 public int getArity() {
166 return 1;
167 }
168
169 /**
170 * Get the argument types of this map, viewed as a function
171 *
172 * @return the list of argument types of this map, viewed as a function
173 */
174
175 public SequenceType[] getArgumentTypes() {
176 // regardless of the key type, a function call on this map can supply any atomic value
177 return new SequenceType[]{SequenceType.makeSequenceType(BuiltInAtomicType.ANY_ATOMIC, StaticProperty.EXACTLY_ONE)};
178 }
179
180 /**
181 * Get the result type of this map, viewed as a function
182 *
183 * @return the result type of this map, viewed as a function
184 */
185
186 public SequenceType getResultType() {
187 // a function call on this map can always return ()
188 if (Cardinality.allowsZero(valueType.getCardinality())) {
189 return valueType;
190 } else {
191 return SequenceType.makeSequenceType(
192 valueType.getPrimaryType(), Cardinality.union(valueType.getCardinality(), StaticProperty.ALLOWS_ZERO));
193 }
194 }
195
196 /**
197 * Produce a representation of this type name for use in error messages.
198 *
199 * @return a string representation of the type, in notation resembling but not necessarily
200 * identical to XPath syntax
201 */
202 public String toString() {
203 if (this == ANY_MAP_TYPE) {
204 return "map(*)";
205 } else if (this == EMPTY_MAP_TYPE) {
206 return "map(\u00B0)";
207 } else {
208 FastStringBuffer sb = new FastStringBuffer(100);
209 sb.append("map(");
210 sb.append(keyType.toString());
211 sb.append(", ");
212 sb.append(valueType.toString());
213 sb.append(")");
214 return sb.toString();
215 }
216 }
217
218 /**
219 * Return a string representation of this ItemType suitable for use in stylesheet
220 * export files. This differs from the result of toString() in that it will not contain
221 * any references to anonymous types. Note that it may also use the Saxon extended syntax
222 * for union types and tuple types. The default implementation returns the result of
223 * calling {@code #toString()}.
224 *
225 * @return the string representation as an instance of the XPath SequenceType construct
226 */
227 @Override
228 public String toExportString() {
229 if (this == ANY_MAP_TYPE) {
230 return "map(*)";
231 } else if (this == EMPTY_MAP_TYPE) {
232 return "map(\u00B0)";
233 } else {
234 FastStringBuffer sb = new FastStringBuffer(100);
235 sb.append("map(");
236 sb.append(keyType.toExportString());
237 sb.append(", ");
238 sb.append(valueType.toExportString());
239 sb.append(")");
240 return sb.toString();
241 }
242 }
243
244 /**
245 * Test whether this function type equals another function type
246 */
247
248 public boolean equals(Object other) {
249 if (this == other) {
250 return true;
251 }
252 if (other instanceof MapType) {
253 MapType f2 = (MapType) other;
254 return keyType.equals(f2.keyType) && valueType.equals(f2.valueType) && mustBeEmpty == f2.mustBeEmpty;
255 }
256 return false;
257 }
258
259 /**
260 * Returns a hash code value for the object.
261 */
262 @Override
263 public int hashCode() {
264 return keyType.hashCode() ^ valueType.hashCode();
265 }
266
267 /**
268 * Determine the relationship of one function item type to another
269 *
270 * @return for example {@link net.sf.saxon.type.TypeHierarchy#SUBSUMES}, {@link net.sf.saxon.type.TypeHierarchy#SAME_TYPE}
271 */
272
273 public int relationship(FunctionItemType other, TypeHierarchy th) {
274 if (other == AnyFunctionType.getInstance()) {
275 return TypeHierarchy.SUBSUMED_BY;
276 } else if (equals(other)) {
277 return TypeHierarchy.SAME_TYPE;
278 } else if (other == MapType.ANY_MAP_TYPE) {
279 return TypeHierarchy.SUBSUMED_BY;
280 } else if (other.isArrayType()) {
281 return TypeHierarchy.DISJOINT;
282 } else if (other instanceof TupleItemType) {
283 return TypeHierarchy.inverseRelationship(other.relationship(this, th));
284 } else if (other instanceof MapType) {
285 // See bug 3720. Two map types can never be disjoint because the empty
286 // map is an instance of every map type
287 MapType f2 = (MapType) other;
288 int keyRel = th.relationship(keyType, f2.keyType);
289 if (keyRel == TypeHierarchy.DISJOINT) {
290 return TypeHierarchy.OVERLAPS;
291 }
292 int valueRel = th.sequenceTypeRelationship(valueType, f2.valueType);
293
294 if (valueRel == TypeHierarchy.DISJOINT) {
295 return TypeHierarchy.OVERLAPS;
296 }
297 if (keyRel == valueRel) {
298 return keyRel;
299 }
300 if ((keyRel == TypeHierarchy.SAME_TYPE || keyRel == TypeHierarchy.SUBSUMES) &&
301 (valueRel == TypeHierarchy.SAME_TYPE || valueRel == TypeHierarchy.SUBSUMES)) {
302 return TypeHierarchy.SUBSUMES;
303 }
304 if ((keyRel == TypeHierarchy.SAME_TYPE || keyRel == TypeHierarchy.SUBSUMED_BY) &&
305 (valueRel == TypeHierarchy.SAME_TYPE || valueRel == TypeHierarchy.SUBSUMED_BY)) {
306 return TypeHierarchy.SUBSUMED_BY;
307 }
308 return TypeHierarchy.OVERLAPS;
309 } else {
310 int rel = TypeHierarchy.DISJOINT;
311 //#ifdefined HOF
312 rel = new SpecificFunctionType(getArgumentTypes(), getResultType()).relationship(other, th);
313 //#endif
314 return rel;
315 }
316 }
317
318 /**
319 * Get extra diagnostic information about why a supplied item does not conform to this
320 * item type, if available. If extra information is returned, it should be in the form of a complete
321 * sentence, minus the closing full stop. No information should be returned for obvious cases.
322 *
323 * @param item the item that doesn't match this type
324 * @param th the type hierarchy cache
325 * @return optionally, a message explaining why the item does not match the type
326 */
327 @Override
328 public Optional<String> explainMismatch(Item item, TypeHierarchy th) {
329 if (item instanceof MapItem) {
330 for (KeyValuePair kvp : ((MapItem)item).keyValuePairs()) {
331 if (!keyType.matches(kvp.key, th)) {
332 String s = "The map contains a key (" + kvp.key + ") of type " + kvp.key.getItemType() +
333 " that is not an instance of the required type " + keyType;
334 return Optional.of(s);
335 }
336 try {
337 if (!valueType.matches(kvp.value, th)) {
338 String s = "The map contains an entry with key (" + kvp.key +
339 ") whose corresponding value (" + Err.depictSequence(kvp.value) +
340 ") is not an instance of the required type " + valueType;
341 Optional<String> more = valueType.explainMismatch(kvp.value, th);
342 if (more.isPresent()) {
343 s = s + ". " + more.get();
344 }
345 return Optional.of(s);
346 }
347 } catch (XPathException e) {
348 // continue
349 }
350 }
351 }
352 return Optional.empty();
353 }
354
355 @Override
356 public Expression makeFunctionSequenceCoercer(Expression exp, RoleDiagnostic role)
357 throws XPathException {
358 Expression result = exp;
359 //#ifdefined HOF
360 result = new SpecificFunctionType(getArgumentTypes(), getResultType()).makeFunctionSequenceCoercer(exp, role);
361 //#endif
362 return result;
363 }
364
365 /**
366 * Generate Javascript code to test whether an item conforms to this item type
367 *
368 * @param knownToBe a type that this item is known to conform to
369 * @param targetVersion
370 * @return a Javascript instruction or sequence of instructions, which can be used as the body
371 * of a Javascript function, and which returns a boolean indication whether the value of the
372 * variable "item" is an instance of this item type.
373 * @throws XPathException if JS code cannot be generated for this item type, for example because
374 * the test is schema-aware.
375 */
376 @Override
377 public String generateJavaScriptItemTypeTest(ItemType knownToBe, int targetVersion) throws XPathException {
378 if (this == ANY_MAP_TYPE) {
379 return "return SaxonJS.U.isMap(item)";
380 }
381 FastStringBuffer fsb = new FastStringBuffer(256);
382 fsb.append("function k(item) {" + keyType.generateJavaScriptItemTypeTest(BuiltInAtomicType.ANY_ATOMIC, targetVersion) + "};");
383 fsb.append("function v(item) {" + valueType.getPrimaryType().generateJavaScriptItemTypeTest(AnyItemType.getInstance(), targetVersion) + "};");
384 int card = valueType.getCardinality();
385 fsb.append(Cardinality.generateJavaScriptChecker(card));
386 if (targetVersion == 1) {
387 fsb.append("return SaxonJS.U.isMap(item) && item.conforms(k, v, c);");
388 } else {
389 fsb.append("return SaxonJS.U.isConstrainedMap(item, k, v, c);");
390 }
391 return fsb.toString();
392 }
393 }
394
395 // Copyright (c) 2011-2016 Saxonica Limited.