Debian Codegraph @

net/sf/saxon/ma/map/TupleItemType.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.GroundedValue;
15 import net.sf.saxon.om.Item;
16 import net.sf.saxon.om.Sequence;
17 import net.sf.saxon.trans.Err;
18 import net.sf.saxon.trans.XPathException;
19 import net.sf.saxon.tree.iter.AtomicIterator;
20 import net.sf.saxon.tree.util.FastStringBuffer;
21 import net.sf.saxon.type.*;
22 import net.sf.saxon.value.AtomicValue;
23 import net.sf.saxon.value.Cardinality;
24 import net.sf.saxon.value.SequenceType;
25 import net.sf.saxon.value.StringValue;
26
27 import java.util.*;
28 import java.util.function.Function;
29
30 /**
31 * An instance of this class represents a specific tuple item type, for example
32 * tuple(x: xs:double, y: element(employee)).
33 *
34 * Tuple types are a Saxon extension introduced in Saxon 9.8. The syntax for constructing
35 * a tuple type requires Saxon-PE or higher, but the supporting code is included in
36 * Saxon-HE for convenience.
37 */
38 public class TupleItemType extends AnyFunctionType implements TupleType {
39
40 private Map<String, SequenceType> fields = new HashMap<>();
41 private Set<String> optionalFields;
42 private boolean extensible;
43
44 public TupleItemType(List<String> names, List<SequenceType> types) {
45 for (int i = 0; i < names.size(); i++) {
46 fields.put(names.get(i), types.get(i));
47 }
48 this.optionalFields = Collections.emptySet();
49 }
50
51 public TupleItemType(List<String> names, List<SequenceType> types, Set<String> optionalFields, boolean extensible) {
52 for (int i=0; i<names.size(); i++) {
53 fields.put(names.get(i), types.get(i));
54 }
55 this.optionalFields = optionalFields;
56 this.extensible = extensible;
57 }
58
59 /**
60 * Determine the Genre (top-level classification) of this type
61 *
62 * @return the Genre to which this type belongs, specifically {@link Genre#MAP}
63 */
64 @Override
65 public Genre getGenre() {
66 return Genre.MAP;
67 }
68
69 /**
70 * Ask whether this function item type is a map type. In this case function coercion (to the map type)
71 * will never succeed.
72 *
73 * @return true if this FunctionItemType is a map type
74 */
75 @Override
76 public boolean isMapType() {
77 return true;
78 }
79
80 /**
81 * Ask whether this function item type is an array type. In this case function coercion (to the array type)
82 * will never succeed.
83 *
84 * @return true if this FunctionItemType is an array type
85 */
86 @Override
87 public boolean isArrayType() {
88 return false;
89 }
90
91 /**
92 * Get the names of all the fields
93 *
94 * @return the names of the fields (in arbitrary order)
95 */
96 @Override
97 public Iterable<String> getFieldNames() {
98 return fields.keySet();
99 }
100
101 /**
102 * Get the type of a given field
103 * @param field the name of the field
104 * @return the type of the field if it is defined, or null otherwise
105 */
106
107 public SequenceType getFieldType(String field) {
108 return fields.get(field);
109 }
110
111 @Override
112 public boolean isOptional(String field) {
113 return optionalFields.contains(field);
114 }
115
116 /**
117 * Ask whether the tuple type is extensible, that is, whether fields other than those named are permitted
118 *
119 * @return true if fields other than the named fields are permitted to appear
120 */
121 @Override
122 public boolean isExtensible() {
123 return extensible;
124 }
125
126 /**
127 * Test whether a given item conforms to this type
128 *
129 * @param item The item to be tested
130 * @param th type hierarchy data
131 * @return true if the item is an instance of this type; false otherwise
132 */
133 @Override
134 public boolean matches(Item item, TypeHierarchy th) throws XPathException {
135 if (!(item instanceof MapItem)) {
136 return false;
137 }
138 MapItem map = (MapItem)item;
139 for (Map.Entry<String, SequenceType> field : fields.entrySet()) {
140 Sequence<?> val = map.get(new StringValue(field.getKey()));
141 if (val == null) {
142 if (!optionalFields.contains(field.getKey())) {
143 return false;
144 }
145 } else if (!field.getValue().matches(val, th)) {
146 return false;
147 }
148 }
149 if (!extensible) {
150 AtomicIterator keyIter = map.keys();
151 AtomicValue key;
152 while ((key = keyIter.next()) != null) {
153 if (!(key instanceof StringValue) || !fields.containsKey(key.getStringValue())) {
154 return false;
155 }
156 }
157 }
158 return true;
159 }
160
161 /**
162 * Get the arity (number of arguments) of this function type
163 *
164 * @return the number of argument types in the function signature
165 */
166
167 public int getArity() {
168 return 1;
169 }
170
171 /**
172 * Get the argument types of this map, viewed as a function
173 *
174 * @return the list of argument types of this map, viewed as a function
175 */
176
177 public SequenceType[] getArgumentTypes() {
178 // regardless of the key type, a function call on this map can supply any atomic value
179 return new SequenceType[]{SequenceType.SINGLE_ATOMIC};
180 }
181
182 /**
183 * Get the result type of this tuple type, viewed as a function
184 *
185 * @return the result type of this tuple type, viewed as a function
186 */
187
188 public SequenceType getResultType() {
189 if (extensible) {
190 return SequenceType.ANY_SEQUENCE;
191 } else {
192 ItemType resultType = null;
193 boolean allowsMany = false;
194 for (Map.Entry<String, SequenceType> field : fields.entrySet()) {
195 if (resultType == null) {
196 resultType = field.getValue().getPrimaryType();
197 } else {
198 resultType = Type.getCommonSuperType(resultType, field.getValue().getPrimaryType());
199 }
200 allowsMany = allowsMany || Cardinality.allowsMany(field.getValue().getCardinality());
201 }
202 return SequenceType.makeSequenceType(resultType,
203 allowsMany ? StaticProperty.ALLOWS_ZERO_OR_MORE : StaticProperty.ALLOWS_ZERO_OR_ONE);
204 }
205 }
206
207 /**
208 * Produce a representation of this type name for use in error messages.
209 *
210 * @return a string representation of the type, in notation resembling but not necessarily
211 * identical to XPath syntax
212 */
213 public String toString() {
214 return makeString(SequenceType::toString);
215 }
216
217 /**
218 * Return a string representation of this ItemType suitable for use in stylesheet
219 * export files. This differs from the result of toString() in that it will not contain
220 * any references to anonymous types. Note that it may also use the Saxon extended syntax
221 * for union types and tuple types.
222 *
223 * @return the string representation as an instance of the XPath ItemType construct
224 */
225 @Override
226 public String toExportString() {
227 return makeString(SequenceType::toExportString);
228 }
229
230 /**
231 * Return a string representation of the tuple type
232 * @param show a function to use for converting the types of the component fields to strings
233 * @return the string representation
234 */
235
236 private String makeString(Function<SequenceType, String> show) {
237 FastStringBuffer sb = new FastStringBuffer(100);
238 sb.append("tuple(");
239 boolean first = true;
240 for (Map.Entry<String, SequenceType> field : fields.entrySet()) {
241 if (first) {
242 first = false;
243 } else {
244 sb.append(", ");
245 }
246 sb.append(field.getKey());
247 if (isOptional(field.getKey())) {
248 sb.append("?");
249 }
250 sb.append(": ");
251 sb.append(show.apply(field.getValue()));
252 }
253 if (isExtensible()) {
254 sb.append(", *");
255 }
256 sb.append(")");
257 return sb.toString();
258 }
259
260 /**
261 * Test whether this function type equals another function type
262 */
263
264 public boolean equals(Object other) {
265 return this == other || other instanceof TupleItemType && fields.equals(((TupleItemType) other).fields);
266 }
267
268 /**
269 * Returns a hash code value for the object.
270 */
271 @Override
272 public int hashCode() {
273 return fields.hashCode();
274 }
275
276 /**
277 * Determine the relationship of one function item type to another
278 *
279 * @return for example {@link TypeHierarchy#SUBSUMES}, {@link TypeHierarchy#SAME_TYPE}
280 */
281
282 public int relationship(FunctionItemType other, TypeHierarchy th) {
283 if (other == AnyFunctionType.getInstance()) {
284 return TypeHierarchy.SUBSUMED_BY;
285 } else if (equals(other)) {
286 return TypeHierarchy.SAME_TYPE;
287 } else if (other == MapType.ANY_MAP_TYPE) {
288 return TypeHierarchy.SUBSUMED_BY;
289 } else if (other.isArrayType()) {
290 return TypeHierarchy.DISJOINT;
291 } else if (other instanceof MapType) {
292 MapType f2 = (MapType) other;
293 int keyRel = th.relationship(BuiltInAtomicType.STRING, f2.getKeyType());
294 if (keyRel == TypeHierarchy.DISJOINT) {
295 return TypeHierarchy.DISJOINT;
296 }
297 // Handle map(xs:string, item()*)
298 if (f2.getValueType().getPrimaryType().equals(AnyItemType.getInstance()) && f2.getValueType().getCardinality() == StaticProperty.ALLOWS_ZERO_OR_MORE) {
299 return TypeHierarchy.SUBSUMED_BY;
300 } else {
301 // The type of every field in the tuple must be a subtype of the map value type
302 for (SequenceType entry : fields.values()) {
303 int rel = th.sequenceTypeRelationship(entry, f2.getValueType());
304 if (!(rel == TypeHierarchy.SUBSUMED_BY || rel == TypeHierarchy.SAME_TYPE)) {
305 return TypeHierarchy.OVERLAPS;
306 }
307 }
308 return TypeHierarchy.SUBSUMED_BY;
309 }
310 } else {
311 int rel;
312 rel = new SpecificFunctionType(getArgumentTypes(), getResultType()).relationship(other, th);
313 return rel;
314 }
315 }
316
317 /**
318 * Get extra diagnostic information about why a supplied item does not conform to this
319 * item type, if available. If extra information is returned, it should be in the form of a complete
320 * sentence, minus the closing full stop. No information should be returned for obvious cases.
321 *
322 * @param item the item being matched
323 * @param th the type hierarchy cache
324 */
325 @Override
326 public Optional<String> explainMismatch(Item item, TypeHierarchy th) {
327 if (item instanceof MapItem) {
328 for (Map.Entry<String, SequenceType> entry : fields.entrySet()) {
329 String key = entry.getKey();
330 SequenceType required = entry.getValue();
331 GroundedValue value = ((MapItem) item).get(new StringValue(key));
332 if (value == null) {
333 if (!optionalFields.contains(key)) {
334 return Optional.of("Field " + key + " is absent, but is not declared optional");
335 }
336 } else {
337 try {
338 if (!required.matches(value, th)) {
339 String s = "Field " + key + " has value "
340 + Err.depictSequence(value)
341 + " which does not match the required type "
342 + required.toString();
343 Optional<String> more = required.explainMismatch(value, th);
344 if (more.isPresent()) {
345 s += ". " + more.get();
346 }
347 return Optional.of(s);
348 }
349 } catch (XPathException err) {
350 // shouldn't happen
351 return Optional.empty();
352 }
353 }
354 }
355 if (!extensible) {
356 AtomicIterator keyIter = ((MapItem)item).keys();
357 AtomicValue key;
358 while ((key = keyIter.next()) != null) {
359 if (!(key instanceof StringValue)) {
360 return Optional.of("Undeclared field " + key + " is present, but it is not a string, and the tuple type is not extensible");
361 } else if (!fields.containsKey(key.getStringValue())) {
362 return Optional.of("Undeclared field " + key + " is present, but the tuple type is not extensible");
363 }
364 }
365 }
366 }
367 return Optional.empty();
368 }
369
370 @Override
371 public Expression makeFunctionSequenceCoercer(Expression exp, RoleDiagnostic role)
372 throws XPathException {
373 return new SpecificFunctionType(getArgumentTypes(), getResultType()).makeFunctionSequenceCoercer(exp, role);
374 }
375
376 /**
377 * Generate Javascript code to test whether an item conforms to this item type
378 *
379 * @param knownToBe a type that this item is known to conform to
380 * @param targetVersion the target version of Saxon-JS
381 * @return a Javascript instruction or sequence of instructions, which can be used as the body
382 * of a Javascript function, and which returns a boolean indication whether the value of the
383 * variable "item" is an instance of this item type.
384 * @throws XPathException if JS code cannot be generated for this item type, for example because
385 * the test is schema-aware.
386 */
387 @Override
388 public String generateJavaScriptItemTypeTest(ItemType knownToBe, int targetVersion) throws XPathException {
389 throw new UnsupportedOperationException();
390 }
391 }
392
393 // Copyright (c) 2011-2016 Saxonica Limited.