Debian Codegraph @

net/sf/saxon/type/SpecificFunctionType.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.expr.Expression;
11 import net.sf.saxon.expr.StaticProperty;
12 import net.sf.saxon.expr.parser.RoleDiagnostic;
13 import net.sf.saxon.ma.arrays.ArrayItem;
14 import net.sf.saxon.ma.arrays.ArrayItemType;
15 import net.sf.saxon.ma.map.KeyValuePair;
16 import net.sf.saxon.ma.map.MapItem;
17 import net.sf.saxon.ma.map.MapType;
18 import net.sf.saxon.om.Function;
19 import net.sf.saxon.om.Item;
20 import net.sf.saxon.om.GroundedValue;
21 import net.sf.saxon.om.Sequence;
22 import net.sf.saxon.query.AnnotationList;
23 import net.sf.saxon.trans.Err;
24 import net.sf.saxon.trans.SaxonErrorCode;
25 import net.sf.saxon.trans.XPathException;
26 import net.sf.saxon.tree.util.FastStringBuffer;
27 import net.sf.saxon.value.SequenceType;
28
29 import java.util.Objects;
30 import java.util.Optional;
31
32 /**
33 * An instance of this class represents a specific function item type, for example
34 * function(xs:int) as xs:boolean
35 */
36 public class SpecificFunctionType extends AnyFunctionType {
37
38 private SequenceType[] argTypes;
39 private SequenceType resultType;
40 private AnnotationList annotations;
41
42 public SpecificFunctionType(SequenceType[] argTypes, SequenceType resultType) {
43 this.argTypes = Objects.requireNonNull(argTypes);
44 this.resultType = Objects.requireNonNull(resultType);
45 this.annotations = AnnotationList.EMPTY;
46 }
47
48 public SpecificFunctionType(SequenceType[] argTypes, SequenceType resultType, AnnotationList annotations) {
49 this.argTypes = Objects.requireNonNull(argTypes);
50 this.resultType = Objects.requireNonNull(resultType);
51 this.annotations = Objects.requireNonNull(annotations);
52 }
53
54 /**
55 * Get the arity (number of arguments) of this function type
56 *
57 * @return the number of argument types in the function signature
58 */
59
60 public int getArity() {
61 return argTypes.length;
62 }
63
64 /**
65 * Get the argument types
66 *
67 * @return the list of argument types
68 */
69
70 public SequenceType[] getArgumentTypes() {
71 return argTypes;
72 }
73
74 /**
75 * Get the result type
76 *
77 * @return the result type
78 */
79
80 public SequenceType getResultType() {
81 return resultType;
82 }
83
84 /**
85 * Get the list of annotation assertions defined on this function item type.
86 *
87 * @return the list of annotation assertions, or an empty list if there are none
88 */
89
90 @Override
91 public AnnotationList getAnnotationAssertions() {
92 return annotations;
93 }
94
95 /**
96 * Ask whether values of this type are atomizable
97 *
98 * @return true if some or all instances of this type can be successfully atomized; false
99 * * if no instances of this type can be atomized
100 * @param th The type hierarchy cache
101 */
102 @Override
103 public boolean isAtomizable(TypeHierarchy th) {
104 // An instance of a specific function type can be atomized only if it is an array, which
105 // means there must be a single argument and it must be of type xs:integer or a supertype.
106 if (getArity() != 1) {
107 return false;
108 }
109 ItemType argType = getArgumentTypes()[0].getPrimaryType();
110 return th.isSubType(BuiltInAtomicType.INTEGER, argType);
111 }
112
113 /**
114 * Produce a representation of this type name for use in error messages.
115 *
116 * @return a string representation of the type, in notation resembling but not necessarily
117 * identical to XPath syntax
118 */
119 public String toString() {
120 FastStringBuffer sb = new FastStringBuffer(100);
121 sb.append("(function(");
122 for (int i = 0; i < argTypes.length; i++) {
123 sb.append(argTypes[i].toString());
124 if (i < argTypes.length - 1) {
125 sb.append(", ");
126 }
127 }
128 sb.append(") as ");
129 sb.append(resultType.toString());
130 sb.append(')');
131 return sb.toString();
132 }
133
134 public String toExportString() {
135 FastStringBuffer sb = new FastStringBuffer(100);
136 sb.append("(function(");
137 for (int i = 0; i < argTypes.length; i++) {
138 sb.append(argTypes[i].toExportString());
139 if (i < argTypes.length - 1) {
140 sb.append(", ");
141 }
142 }
143 sb.append(") as ");
144 sb.append(resultType.toExportString());
145 sb.append(')');
146 return sb.toString();
147 }
148
149
150 /**
151 * Test whether this function type equals another function type
152 */
153
154 public boolean equals(Object other) {
155 if (other instanceof SpecificFunctionType) {
156 SpecificFunctionType f2 = (SpecificFunctionType) other;
157 if (!resultType.equals(f2.resultType)) {
158 return false;
159 }
160 if (argTypes.length != f2.argTypes.length) {
161 return false;
162 }
163 for (int i = 0; i < argTypes.length; i++) {
164 if (!argTypes[i].equals(f2.argTypes[i])) {
165 return false;
166 }
167 }
168 // Compare the annotations
169 if (!getAnnotationAssertions().equals(f2.getAnnotationAssertions())) {
170 return false;
171 }
172 return true;
173 }
174 return false;
175 }
176
177 /**
178 * Returns a hash code value for the object.
179 */
180 @Override
181 public int hashCode() {
182 int h = resultType.hashCode() ^ argTypes.length;
183 for (SequenceType argType : argTypes) {
184 h ^= argType.hashCode();
185 }
186 return h;
187 }
188
189 /**
190 * Determine the relationship of one function item type to another. This method is only concerned
191 * with the type signatures of the two function item types, and not with their annotation assertions.
192 *
193 * @return for example {@link TypeHierarchy#SUBSUMES}, {@link TypeHierarchy#SAME_TYPE}
194 */
195
196 public int relationship(FunctionItemType other, TypeHierarchy th) {
197 if (other == AnyFunctionType.getInstance() || other instanceof AnyFunctionTypeWithAssertions) {
198 return TypeHierarchy.SUBSUMED_BY;
199 } else if (equals(other)) {
200 return TypeHierarchy.SAME_TYPE;
201 } else if (other instanceof ArrayItemType || other instanceof MapType) {
202 int rrel = other.relationship(this, th);
203 switch (rrel) {
204 case TypeHierarchy.SUBSUMES:
205 return TypeHierarchy.SUBSUMED_BY;
206 case TypeHierarchy.SUBSUMED_BY:
207 return TypeHierarchy.SUBSUMES;
208 default:
209 return rrel;
210 }
211 } else {
212 if (argTypes.length != other.getArgumentTypes().length) {
213 return TypeHierarchy.DISJOINT;
214 }
215 boolean wider = false;
216 boolean narrower = false;
217 for (int i = 0; i < argTypes.length; i++) {
218 int argRel = th.sequenceTypeRelationship(argTypes[i], other.getArgumentTypes()[i]);
219 switch (argRel) {
220 case TypeHierarchy.DISJOINT:
221 return TypeHierarchy.DISJOINT;
222 case TypeHierarchy.SUBSUMES:
223 narrower = true;
224 break;
225 case TypeHierarchy.SUBSUMED_BY:
226 wider = true;
227 break;
228 case TypeHierarchy.OVERLAPS:
229 wider = true;
230 narrower = true;
231 break;
232 case TypeHierarchy.SAME_TYPE:
233 default:
234 break;
235 }
236 }
237
238 int resRel = th.sequenceTypeRelationship(resultType, other.getResultType());
239 switch (resRel) {
240 case TypeHierarchy.DISJOINT:
241 return TypeHierarchy.DISJOINT;
242 case TypeHierarchy.SUBSUMES:
243 wider = true;
244 break;
245 case TypeHierarchy.SUBSUMED_BY:
246 narrower = true;
247 break;
248 case TypeHierarchy.OVERLAPS:
249 wider = true;
250 narrower = true;
251 break;
252 case TypeHierarchy.SAME_TYPE:
253 default:
254 break;
255 }
256
257 if (wider) {
258 if (narrower) {
259 return TypeHierarchy.OVERLAPS;
260 } else {
261 return TypeHierarchy.SUBSUMES;
262 }
263 } else {
264 if (narrower) {
265 return TypeHierarchy.SUBSUMED_BY;
266 } else {
267 return TypeHierarchy.SAME_TYPE;
268 }
269 }
270 }
271 }
272
273 /**
274 * Test whether a given item conforms to this type
275 *
276 *
277 * @param item The item to be tested
278 * @param th the type hierarchy cache
279 * @return true if the item is an instance of this type; false otherwise
280 */
281 @Override
282 public boolean matches(Item item, TypeHierarchy th) {
283 if (!(item instanceof Function)) {
284 return false;
285 }
286
287
288 if (item instanceof MapItem) {
289 // Bug 2938: Essentially a map is an instance of function(X) as Y
290 // if (a) X is a subtype of xs:anyAtomicType, and (b) all the values in the map are instances of Y
291 if (getArity() == 1 &&
292 argTypes[0].getCardinality() == StaticProperty.EXACTLY_ONE &&
293 argTypes[0].getPrimaryType().isPlainType()) {
294 for (KeyValuePair pair : ((MapItem) item).keyValuePairs()) {
295 try {
296 if (!resultType.matches(pair.value, th)) {
297 return false;
298 }
299 } catch (XPathException e) {
300 return false;
301 }
302 }
303 return true;
304 } else {
305 return false;
306 }
307 }
308
309 if (item instanceof ArrayItem) {
310 // Bug 2938: Essentially a array is an instance of function(X) as Y
311 // if (a) X is a subtype of xs:integer, and (b) all the values in the array are instances of Y
312 if (getArity() == 1 &&
313 argTypes[0].getCardinality() == StaticProperty.EXACTLY_ONE &&
314 argTypes[0].getPrimaryType().isPlainType()) {
315 int rel = th.relationship(argTypes[0].getPrimaryType(), BuiltInAtomicType.INTEGER);
316 if (!(rel == TypeHierarchy.SAME_TYPE || rel == TypeHierarchy.SUBSUMED_BY)) {
317 return false;
318 }
319 for (Sequence<?> member : ((ArrayItem) item).members()) {
320 try {
321 if (!resultType.matches(member, th)) {
322 return false;
323 }
324 } catch (XPathException e) {
325 return false;
326 }
327 }
328 return true;
329 } else {
330 return false;
331 }
332 }
333
334 int rel = th.relationship(((Function) item).getFunctionItemType(), this);
335 return rel == TypeHierarchy.SAME_TYPE || rel == TypeHierarchy.SUBSUMED_BY;
336 }
337
338 /**
339 * Get extra diagnostic information about why a supplied item does not conform to this
340 * item type, if available. If extra information is returned, it should be in the form of a complete
341 * sentence, minus the closing full stop. No information should be returned for obvious cases.
342 *
343 * @param item the item that doesn't match this type
344 * @param th the type hierarchy cache
345 * @return optionally, a message explaining why the item does not match the type
346 */
347 @Override
348 public Optional<String> explainMismatch(Item item, TypeHierarchy th) {
349 if (!(item instanceof Function)) {
350 return Optional.empty();
351 }
352
353 if (item instanceof MapItem) {
354 if (getArity() == 1) {
355 if (argTypes[0].getCardinality() == StaticProperty.EXACTLY_ONE &&
356 argTypes[0].getPrimaryType().isPlainType()) {
357 for (KeyValuePair pair : ((MapItem) item).keyValuePairs()) {
358 try {
359 if (!resultType.matches(pair.value, th)) {
360 String s = "The supplied map contains an entry with key (" + pair.key +
361 ") whose corresponding value (" + Err.depictSequence(pair.value) +
362 ") is not an instance of the return type in the function signature (" +
363 resultType + ")";
364 Optional<String> more = resultType.explainMismatch(pair.value, th);
365 if (more.isPresent()) {
366 s = s + ". " + more.get();
367 }
368 return Optional.of(s);
369 }
370 } catch (XPathException e) {
371 return Optional.empty();
372 }
373 }
374 } else {
375 String s = "The function argument is of type " + argTypes[0] +
376 "; a map can only be supplied for a function type whose argument type is atomic";
377 return Optional.of(s);
378 }
379 } else {
380 String s = "The function arity is " + getArity() + "; a map can only be supplied for a function type with arity 1";
381 return Optional.of(s);
382 }
383 }
384
385 if (item instanceof ArrayItem) {
386 // Bug 2938: Essentially a array is an instance of function(X) as Y
387 // if (a) X is a subtype of xs:integer, and (b) all the values in the array are instances of Y
388 if (getArity() == 1) {
389 if (argTypes[0].getCardinality() == StaticProperty.EXACTLY_ONE &&
390 argTypes[0].getPrimaryType().isPlainType()) {
391 int rel = th.relationship(argTypes[0].getPrimaryType(), BuiltInAtomicType.INTEGER);
392 if (!(rel == TypeHierarchy.SAME_TYPE || rel == TypeHierarchy.SUBSUMED_BY)) {
393 String s = "The function expects an argument of type " + argTypes[0] +
394 "; an array can only be supplied for a function that expects an integer";
395 return Optional.of(s);
396 } else {
397 for (GroundedValue<?> member : (ArrayItem) item) {
398 try {
399 if (!resultType.matches(member, th)) {
400 String s = "The supplied array contains an entry (" + Err.depictSequence(member) +
401 ") is not an instance of the return type in the function signature (" +
402 resultType + ")";
403 Optional<String> more = resultType.explainMismatch(member, th);
404 if (more.isPresent()) {
405 s = s + ". " + more.get();
406 }
407 return Optional.of(s);
408 }
409 } catch (XPathException e) {
410 return Optional.empty();
411 }
412 }
413 }
414 } else {
415 String s = "The function argument is of type " + argTypes[0] +
416 "; an array can only be supplied for a function type whose argument type is xs:integer";
417 return Optional.of(s);
418 }
419 } else {
420 String s = "The function arity is " + getArity() + "; an array can only be supplied for a function type with arity 1";
421 return Optional.of(s);
422 }
423 }
424
425 FunctionItemType other = ((Function) item).getFunctionItemType();
426 if (getArity() != ((Function) item).getArity()) {
427 String s = "The required function arity is " + getArity() +
428 "; the supplied function has arity " + ((Function) item).getArity();
429 return Optional.of(s);
430 }
431 int rel = th.sequenceTypeRelationship(resultType, other.getResultType());
432 if (rel != TypeHierarchy.SAME_TYPE && rel != TypeHierarchy.SUBSUMES) {
433 String s = "The return type of the required function is " + resultType + " but the return"
434 + "type of the supplied function is " + other.getResultType();
435 return Optional.of(s);
436 }
437 for (int j=0; j<getArity(); j++) {
438 rel = th.sequenceTypeRelationship(argTypes[j], other.getArgumentTypes()[j]);
439 if (rel != TypeHierarchy.SAME_TYPE && rel != TypeHierarchy.SUBSUMED_BY) {
440 String s = "The type of the " + RoleDiagnostic.ordinal(j+1) +
441 " argument of the required function is " + argTypes[j] + " but the declared"
442 + "type of the corresponding argument of the supplied function is " +
443 other.getArgumentTypes()[j];
444 return Optional.of(s);
445 }
446 }
447 return Optional.empty();
448 }
449
450 public Expression makeFunctionSequenceCoercer(Expression exp, RoleDiagnostic role)
451 throws XPathException {
452 return exp.getConfiguration().makeFunctionSequenceCoercer(this, exp, role);
453 }
454
455 /**
456 * Generate Javascript code to test whether an item conforms to this item type
457 *
458 * @return a Javascript instruction or sequence of instructions, which can be used as the body
459 * of a Javascript function, and which returns a boolean indication whether the value of the
460 * variable "item" is an instance of this item type.
461 * @throws XPathException if JS code cannot be generated for this item type, for example because
462 * the test is schema-aware.
463 * @param knownToBe
464 * @param targetVersion
465 */
466 @Override
467 public String generateJavaScriptItemTypeTest(ItemType knownToBe, int targetVersion) throws XPathException {
468 throw new XPathException("Cannot generate JS code for function type tests", SaxonErrorCode.SXJS0001);
469 }
470 }