Debian Codegraph @

net/sf/saxon/expr/parser/TypeChecker.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.expr.parser;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.expr.*;
12 import net.sf.saxon.lib.ConversionRules;
13 import net.sf.saxon.ma.map.MapType;
14 import net.sf.saxon.ma.map.TupleType;
15 import net.sf.saxon.om.*;
16 import net.sf.saxon.pattern.NodeTest;
17 import net.sf.saxon.trans.XPathException;
18 import net.sf.saxon.type.*;
19 import net.sf.saxon.value.AtomicValue;
20 import net.sf.saxon.value.Cardinality;
21 import net.sf.saxon.value.SequenceType;
22
23 /**
24 * This class provides Saxon's type checking capability. It contains a method,
25 * staticTypeCheck, which is called at compile time to perform type checking of
26 * an expression.
27 */
28
29 public class TypeChecker {
30
31 public TypeChecker() {
32 }
33
34 /**
35 * Check an expression against a required type, modifying it if necessary.
36 * <p>This method takes the supplied expression and checks to see whether it is
37 * known statically to conform to the specified type. There are three possible
38 * outcomes. If the static type of the expression is a subtype of the required
39 * type, the method returns the expression unchanged. If the static type of
40 * the expression is incompatible with the required type (for example, if the
41 * supplied type is integer and the required type is string) the method throws
42 * an exception (this results in a compile-time type error being reported). If
43 * the static type is a supertype of the required type, then a new expression
44 * is constructed that evaluates the original expression and checks the dynamic
45 * type of the result; this new expression is returned as the result of the
46 * method.</p>
47 * <p>The rules applied are those for function calling in XPath, that is, the rules
48 * that the argument of a function call must obey in relation to the signature of
49 * the function. Some contexts require slightly different rules (for example,
50 * operands of polymorphic operators such as "+"). In such cases this method cannot
51 * be used.</p>
52 * <p>Note that this method does <b>not</b> do recursive type-checking of the
53 * sub-expressions.</p>
54 *
55 * @param supplied The expression to be type-checked
56 * @param req The required type for the context in which the expression is used
57 * @param role Information about the role of the subexpression within the
58 * containing expression, used to provide useful error messages
59 * @param visitor An expression visitor
60 * @return The original expression if it is type-safe, or the expression
61 * wrapped in a run-time type checking expression if not.
62 * @throws XPathException if the supplied type is statically inconsistent with the
63 * required type (that is, if they have no common subtype)
64 */
65
66 public Expression staticTypeCheck(Expression supplied,
67 SequenceType req,
68 RoleDiagnostic role,
69 final ExpressionVisitor visitor)
70 throws XPathException {
71
72 // System.err.println("Static Type Check on expression (requiredType = " + req + "):"); supplied.display(10);
73
74 if (supplied.implementsStaticTypeCheck()) {
75 return supplied.staticTypeCheck(req, false, role, visitor);
76 }
77
78 Expression exp = supplied;
79 final StaticContext env = visitor.getStaticContext();
80 final Configuration config = env.getConfiguration();
81 final TypeHierarchy th = config.getTypeHierarchy();
82 final ContextItemStaticInfo defaultContextInfo = config.getDefaultContextItemStaticInfo();
83
84 final ItemType reqItemType = req.getPrimaryType();
85 int reqCard = req.getCardinality();
86 boolean allowsMany = Cardinality.allowsMany(reqCard);
87
88 ItemType suppliedItemType = null;
89 // item type of the supplied expression: null means not yet calculated
90 int suppliedCard = -1;
91 // cardinality of the supplied expression: -1 means not yet calculated
92
93 boolean cardOK = reqCard == StaticProperty.ALLOWS_ZERO_OR_MORE;
94 // Unless the required cardinality is zero-or-more (no constraints).
95 // check the static cardinality of the supplied expression
96 if (!cardOK) {
97 suppliedCard = exp.getCardinality();
98 cardOK = Cardinality.subsumes(reqCard, suppliedCard);
99 // May later find that cardinality is not OK after all, if atomization takes place
100 }
101
102 boolean itemTypeOK = reqItemType instanceof AnyItemType;
103 if (reqCard == StaticProperty.ALLOWS_ZERO) {
104 // required type is empty sequence; we don't need an item check because a cardinality check suffices
105 itemTypeOK = true;
106 }
107 // Unless the required item type and content type are ITEM (no constraints)
108 // check the static item type against the supplied expression.
109 // NOTE: we don't currently do any static inference regarding the content type
110 if (!itemTypeOK) {
111 suppliedItemType = exp.getItemType();
112 if (reqItemType == null || suppliedItemType == null) {
113 throw new NullPointerException();
114 }
115 int relation = th.relationship(reqItemType, suppliedItemType);
116 itemTypeOK = relation == TypeHierarchy.SAME_TYPE || relation == TypeHierarchy.SUBSUMES;
117 }
118
119
120 if (!itemTypeOK) {
121 // Now apply the conversions needed in 2.0 mode
122
123 if (reqItemType.isPlainType()) {
124
125 // rule 1: Atomize
126 if (!suppliedItemType.isPlainType() &&
127 !(suppliedCard == StaticProperty.EMPTY)) {
128 if (!suppliedItemType.isAtomizable(th)) {
129 String shortItemType;
130 if (suppliedItemType instanceof TupleType) {
131 shortItemType = "a tuple type";
132 } else if (suppliedItemType instanceof MapType) {
133 shortItemType = "a map type";
134 } else if (suppliedItemType instanceof FunctionItemType) {
135 shortItemType = "a function type";
136 } else if (suppliedItemType instanceof NodeTest) {
137 shortItemType = "an element type with element-only content";
138 } else {
139 shortItemType = suppliedItemType.toString();
140 }
141 XPathException err = new XPathException(
142 "An atomic value is required for the " + role.getMessage() +
143 ", but the supplied type is " + shortItemType + ", which cannot be atomized", "FOTY0013", supplied.getLocation());
144 err.setIsTypeError(true);
145 err.setFailingExpression(supplied);
146 throw err;
147 }
148
149 if (exp.getRetainedStaticContext() == null) {
150 exp.setRetainedStaticContextLocally(env.makeRetainedStaticContext());
151 }
152 Expression cexp = Atomizer.makeAtomizer(exp, role);
153 ExpressionTool.copyLocationInfo(exp, cexp);
154 exp = cexp;
155 cexp = exp.simplify();
156 ExpressionTool.copyLocationInfo(exp, cexp);
157 exp = cexp;
158 suppliedItemType = exp.getItemType();
159 suppliedCard = exp.getCardinality();
160 cardOK = Cardinality.subsumes(reqCard, suppliedCard);
161 }
162
163 // rule 2: convert untypedAtomic to the required type
164
165 // 2a: all supplied values are untyped atomic. Convert if necessary, and we're finished.
166
167 if (suppliedItemType.equals(BuiltInAtomicType.UNTYPED_ATOMIC)
168 && !(reqItemType.equals(BuiltInAtomicType.UNTYPED_ATOMIC) || reqItemType.equals(BuiltInAtomicType.ANY_ATOMIC))) {
169
170 if (((SimpleType) reqItemType).isNamespaceSensitive()) {
171 // See spec bug 11964
172 XPathException err = new XPathException("An untyped atomic value cannot be converted to a QName or NOTATION as required for the " + role.getMessage(), "XPTY0117", supplied.getLocation());
173 err.setIsTypeError(true);
174 throw err;
175 }
176 UntypedSequenceConverter cexp = UntypedSequenceConverter.makeUntypedSequenceConverter(config, exp, (PlainType) reqItemType);
177 cexp.setRoleDiagnostic(role);
178 ExpressionTool.copyLocationInfo(exp, cexp);
179 try {
180 if (exp instanceof Literal) {
181 exp = Literal.makeLiteral(
182 cexp.iterate(visitor.makeDynamicContext()).materialize(), exp);
183 ExpressionTool.copyLocationInfo(cexp, exp);
184 } else {
185 exp = cexp;
186 }
187 } catch (XPathException err) {
188 err.maybeSetLocation(exp.getLocation());
189 err.setFailingExpression(supplied);
190 err.setErrorCode(role.getErrorCode());
191 err.setIsStaticError(true);
192 throw err;
193 }
194 itemTypeOK = true;
195 suppliedItemType = reqItemType;
196 }
197
198 // 2b: some supplied values are untyped atomic. Convert these to the required type; but
199 // there may be other values in the sequence that won't convert and still need to be checked
200
201 if (suppliedItemType.equals(BuiltInAtomicType.ANY_ATOMIC)
202 && !(reqItemType.equals(BuiltInAtomicType.UNTYPED_ATOMIC) || reqItemType.equals(BuiltInAtomicType.ANY_ATOMIC))
203 && !exp.hasSpecialProperty(StaticProperty.NOT_UNTYPED_ATOMIC)) {
204
205 Expression conversion;
206 if (((SimpleType) reqItemType).isNamespaceSensitive()) {
207 conversion = UntypedSequenceConverter.makeUntypedSequenceRejector(config, exp, (PlainType) reqItemType);
208 } else {
209 UntypedSequenceConverter usc = UntypedSequenceConverter.makeUntypedSequenceConverter(config, exp, (PlainType) reqItemType);
210 usc.setRoleDiagnostic(role);
211 conversion = usc;
212 }
213 ExpressionTool.copyLocationInfo(exp, conversion);
214 try {
215 if (exp instanceof Literal) {
216 exp = Literal.makeLiteral(
217 conversion.iterate(visitor.makeDynamicContext()).materialize(), exp);
218 ExpressionTool.copyLocationInfo(supplied, exp);
219 } else {
220 exp = conversion;
221 }
222 suppliedItemType = exp.getItemType();
223 } catch (XPathException err) {
224 err.maybeSetLocation(exp.getLocation());
225 err.setIsStaticError(true);
226 throw err;
227 }
228 }
229
230 // Rule 3a: numeric promotion decimal -> float -> double
231
232 if (reqItemType instanceof AtomicType) {
233 int rt = ((AtomicType) reqItemType).getFingerprint();
234 if (rt == StandardNames.XS_DOUBLE &&
235 th.relationship(suppliedItemType, NumericType.getInstance()) != TypeHierarchy.DISJOINT) {
236 Expression cexp = makePromoterToDouble(exp);
237 if (cexp instanceof AtomicSequenceConverter) {
238 ((AtomicSequenceConverter) cexp).setRoleDiagnostic(role);
239 }
240 ExpressionTool.copyLocationInfo(exp, cexp);
241 exp = cexp;
242 try {
243 exp = exp.simplify().typeCheck(visitor, defaultContextInfo);
244 } catch (XPathException err) {
245 err.maybeSetLocation(exp.getLocation());
246 err.setIsStaticError(true);
247 throw err;
248 }
249 suppliedItemType = BuiltInAtomicType.DOUBLE;
250 suppliedCard = -1;
251
252 } else if (rt == StandardNames.XS_FLOAT &&
253 th.relationship(suppliedItemType, NumericType.getInstance()) != TypeHierarchy.DISJOINT &&
254 !th.isSubType(suppliedItemType, BuiltInAtomicType.DOUBLE)) {
255 Expression cexp = makePromoterToFloat(exp);
256 if (cexp instanceof AtomicSequenceConverter) {
257 ((AtomicSequenceConverter)cexp).setRoleDiagnostic(role);
258 }
259 ExpressionTool.copyLocationInfo(exp, cexp);
260 exp = cexp;
261 try {
262 exp = exp.simplify().typeCheck(visitor, defaultContextInfo);
263 } catch (XPathException err) {
264 err.maybeSetLocation(exp.getLocation());
265 err.setFailingExpression(supplied);
266 err.setIsStaticError(true);
267 throw err;
268 }
269 suppliedItemType = BuiltInAtomicType.FLOAT;
270 suppliedCard = -1;
271
272 }
273
274 // Rule 3b: promotion from anyURI -> string
275
276 if (rt == StandardNames.XS_STRING && th.isSubType(suppliedItemType, BuiltInAtomicType.ANY_URI)) {
277 itemTypeOK = true;
278 Expression cexp = makePromoterToString(exp);
279 if (cexp instanceof AtomicSequenceConverter) {
280 ((AtomicSequenceConverter) cexp).setRoleDiagnostic(role);
281 }
282 ExpressionTool.copyLocationInfo(exp, cexp);
283 exp = cexp;
284 try {
285 exp = exp.simplify().typeCheck(visitor, defaultContextInfo);
286 } catch (XPathException err) {
287 err.maybeSetLocation(exp.getLocation());
288 err.setFailingExpression(supplied);
289 err.setIsStaticError(true);
290 throw err;
291 }
292 suppliedItemType = BuiltInAtomicType.STRING;
293 suppliedCard = -1;
294 }
295 }
296
297 } else if (reqItemType instanceof FunctionItemType && !((FunctionItemType) reqItemType).isMapType()
298 && !((FunctionItemType) reqItemType).isArrayType()) {
299 int r = th.relationship(suppliedItemType, th.getGenericFunctionItemType());
300 if (r != TypeHierarchy.DISJOINT) {
301 if (!(suppliedItemType instanceof FunctionItemType)) {
302 exp = new ItemChecker(exp, th.getGenericFunctionItemType(), role);
303 suppliedItemType = th.getGenericFunctionItemType();
304 }
305 exp = makeFunctionSequenceCoercer(exp, (FunctionItemType) reqItemType, visitor, role);
306 itemTypeOK = true;
307 }
308
309 } else if (reqItemType instanceof JavaExternalObjectType &&
310 /*Sequence.class.isAssignableFrom(((JavaExternalObjectType) reqItemType).getJavaClass()) && */
311 reqCard == StaticProperty.EXACTLY_ONE) {
312
313 if (Sequence.class.isAssignableFrom(((JavaExternalObjectType) reqItemType).getJavaClass())) {
314 // special case: allow an extension function to call an instance method on the implementation type of an XDM value
315 // we leave the conversion to be sorted out at run-time
316 itemTypeOK = true;
317 } else if (supplied instanceof FunctionCall) {
318 // adjust the required type of the Java extension function call
319 // this does nothing unless supplied is an instanceof JavaExtensionFunctionCall
320 if (((FunctionCall) supplied).adjustRequiredType((JavaExternalObjectType) reqItemType)) {
321 itemTypeOK = true;
322 cardOK = true;
323 }
324
325 }
326
327 }
328
329 }
330
331 // If both the cardinality and item type are statically OK, return now.
332 if (itemTypeOK && cardOK) {
333 return exp;
334 }
335
336 // If we haven't evaluated the cardinality of the supplied expression, do it now
337 if (suppliedCard == -1) {
338 suppliedCard = exp.getCardinality();
339 if (!cardOK) {
340 cardOK = Cardinality.subsumes(reqCard, suppliedCard);
341 }
342 }
343
344 // If an empty sequence was explicitly supplied, and empty sequence is allowed,
345 // then the item type doesn't matter
346 if (cardOK && suppliedCard == StaticProperty.EMPTY) {
347 return exp;
348 }
349
350 // If the supplied value is () and () isn't allowed, fail now
351 if (suppliedCard == StaticProperty.EMPTY && ((reqCard & StaticProperty.ALLOWS_ZERO) == 0)) {
352 XPathException err = new XPathException("An empty sequence is not allowed as the " + role.getMessage(), role.getErrorCode(), supplied.getLocation());
353 err.setIsTypeError(role.isTypeError());
354 err.setFailingExpression(supplied);
355 throw err;
356 }
357
358 // Try a static type check. We only throw it out if the call cannot possibly succeed, unless
359 // pessimistic type checking is enabled
360
361 int relation = itemTypeOK ? TypeHierarchy.SUBSUMED_BY : th.relationship(suppliedItemType, reqItemType);
362
363 if (reqCard == StaticProperty.ALLOWS_ZERO) {
364 // No point doing any item checking if no items are allowed in the result
365 relation = TypeHierarchy.SAME_TYPE;
366 }
367 if (relation == TypeHierarchy.DISJOINT) {
368 // The item types may be disjoint, but if both the supplied and required types permit
369 // an empty sequence, we can't raise a static error. Raise a warning instead.
370 if (Cardinality.allowsZero(suppliedCard) &&
371 Cardinality.allowsZero(reqCard)) {
372 if (suppliedCard != StaticProperty.EMPTY) {
373 String msg = role.composeErrorMessage(reqItemType, supplied, th);
374 msg += ". The expression can succeed only if the supplied value is an empty sequence.";
375 visitor.issueWarning(msg, supplied.getLocation());
376 }
377 } else {
378 String msg = role.composeErrorMessage(reqItemType, supplied, th);
379 XPathException err = new XPathException(msg, role.getErrorCode(), supplied.getLocation());
380 err.setIsTypeError(role.isTypeError());
381 err.setFailingExpression(supplied);
382 throw err;
383 }
384 }
385
386 // Unless the type is guaranteed to match, add a dynamic type check,
387 // unless the value is already known in which case we might as well report
388 // the error now.
389
390 if (!(relation == TypeHierarchy.SAME_TYPE || relation == TypeHierarchy.SUBSUMED_BY)) {
391 if (exp instanceof Literal) {
392 // Try a more detailed check, since for maps, functions etc getItemType() can be imprecise
393 if (req.matches(((Literal) exp).getValue(), th)) {
394 return exp;
395 }
396 String msg = role.composeErrorMessage(reqItemType, supplied, th);
397 XPathException err = new XPathException(msg, role.getErrorCode(), supplied.getLocation());
398 err.setIsTypeError(role.isTypeError());
399 throw err;
400 } else {
401 Expression cexp = new ItemChecker(exp, reqItemType, role);
402 ExpressionTool.copyLocationInfo(exp, cexp);
403 exp = cexp;
404 }
405 }
406
407 if (!cardOK) {
408 if (exp instanceof Literal) {
409 XPathException err = new XPathException("Required cardinality of " + role.getMessage() +
410 " is " + Cardinality.toString(reqCard) +
411 "; supplied value has cardinality " +
412 Cardinality.toString(suppliedCard), role.getErrorCode(), supplied.getLocation());
413 err.setIsTypeError(role.isTypeError());
414 throw err;
415 } else {
416 Expression cexp = CardinalityChecker.makeCardinalityChecker(exp, reqCard, role);
417 ExpressionTool.copyLocationInfo(exp, cexp);
418 exp = cexp;
419 }
420 }
421
422 return exp;
423 }
424
425 public Expression makeArithmeticExpression(Expression lhs, int operator, Expression rhs) {
426 return new ArithmeticExpression(lhs, operator, rhs);
427 }
428
429 public Expression makeGeneralComparison(Expression lhs, int operator, Expression rhs) {
430 return new GeneralComparison20(lhs, operator, rhs);
431 }
432
433 public Expression processValueOf(Expression select, Configuration config) {
434 return select;
435 }
436
437 private static Expression makeFunctionSequenceCoercer(
438 Expression exp, FunctionItemType reqItemType, ExpressionVisitor visitor, RoleDiagnostic role) throws XPathException {
439 // Apply function coercion as defined in XPath 3.0.
440
441 return reqItemType.makeFunctionSequenceCoercer(exp, role);
442 }
443
444 /**
445 * Check an expression against a required type, modifying it if necessary. This
446 * is a variant of the method {@link #staticTypeCheck} used for expressions that
447 * declare variables in XQuery. In these contexts, conversions such as numeric
448 * type promotion and atomization are not allowed.
449 *
450 * @param supplied The expression to be type-checked
451 * @param req The required type for the context in which the expression is used
452 * @param role Information about the role of the subexpression within the
453 * containing expression, used to provide useful error messages
454 * @param env The static context containing the types being checked. At present
455 * this is used only to locate a NamePool
456 * @return The original expression if it is type-safe, or the expression
457 * wrapped in a run-time type checking expression if not.
458 * @throws XPathException if the supplied type is statically inconsistent with the
459 * required type (that is, if they have no common subtype)
460 */
461
462 public static Expression strictTypeCheck(Expression supplied,
463 SequenceType req,
464 RoleDiagnostic role,
465 StaticContext env)
466 throws XPathException {
467
468 // System.err.println("Strict Type Check on expression (requiredType = " + req + "):"); supplied.display(10);
469
470 Expression exp = supplied;
471 final TypeHierarchy th = env.getConfiguration().getTypeHierarchy();
472
473 ItemType reqItemType = req.getPrimaryType();
474 int reqCard = req.getCardinality();
475
476 ItemType suppliedItemType = null;
477 // item type of the supplied expression: null means not yet calculated
478 int suppliedCard = -1;
479 // cardinality of the supplied expression: -1 means not yet calculated
480
481 boolean cardOK = reqCard == StaticProperty.ALLOWS_ZERO_OR_MORE;
482 // Unless the required cardinality is zero-or-more (no constraints).
483 // check the static cardinality of the supplied expression
484 if (!cardOK) {
485 suppliedCard = exp.getCardinality();
486 cardOK = Cardinality.subsumes(reqCard, suppliedCard);
487 }
488
489 boolean itemTypeOK = req.getPrimaryType() instanceof AnyItemType;
490 // Unless the required item type and content type are ITEM (no constraints)
491 // check the static item type against the supplied expression.
492 // NOTE: we don't currently do any static inference regarding the content type
493 if (!itemTypeOK) {
494 suppliedItemType = exp.getItemType();
495 int relation = th.relationship(reqItemType, suppliedItemType);
496 itemTypeOK = relation == TypeHierarchy.SAME_TYPE || relation == TypeHierarchy.SUBSUMES;
497 }
498
499 // If both the cardinality and item type are statically OK, return now.
500 if (itemTypeOK && cardOK) {
501 return exp;
502 }
503
504 // If we haven't evaluated the cardinality of the supplied expression, do it now
505 if (suppliedCard == -1) {
506 if (suppliedItemType instanceof ErrorType) {
507 suppliedCard = StaticProperty.EMPTY;
508 } else {
509 suppliedCard = exp.getCardinality();
510 }
511 if (!cardOK) {
512 cardOK = Cardinality.subsumes(reqCard, suppliedCard);
513 }
514 }
515
516 // If an empty sequence was explicitly supplied, and empty sequence is allowed,
517 // then the item type doesn't matter
518 if (cardOK && suppliedCard == StaticProperty.EMPTY) {
519 return exp;
520 }
521
522 // If we haven't evaluated the item type of the supplied expression, do it now
523 if (suppliedItemType == null) {
524 suppliedItemType = exp.getItemType();
525 }
526
527 if (suppliedCard == StaticProperty.EMPTY && ((reqCard & StaticProperty.ALLOWS_ZERO) == 0)) {
528 XPathException err = new XPathException("An empty sequence is not allowed as the " + role.getMessage(), role.getErrorCode(), supplied.getLocation());
529 err.setIsTypeError(role.isTypeError());
530 throw err;
531 }
532
533 // Try a static type check. We only throw it out if the call cannot possibly succeed.
534
535 int relation = th.relationship(suppliedItemType, reqItemType);
536 if (relation == TypeHierarchy.DISJOINT) {
537 // The item types may be disjoint, but if both the supplied and required types permit
538 // an empty sequence, we can't raise a static error. Raise a warning instead.
539 if (Cardinality.allowsZero(suppliedCard) &&
540 Cardinality.allowsZero(reqCard)) {
541 if (suppliedCard != StaticProperty.EMPTY) {
542 String msg = "Required item type of " + role.getMessage() +
543 " is " + reqItemType +
544 "; supplied value (" + supplied.toShortString() + ") has item type " +
545 suppliedItemType +
546 ". The expression can succeed only if the supplied value is an empty sequence.";
547 env.issueWarning(msg, supplied.getLocation());
548 }
549 } else {
550 String msg = role.composeErrorMessage(reqItemType, supplied, th);
551 XPathException err = new XPathException(msg, role.getErrorCode(), supplied.getLocation());
552 err.setIsTypeError(role.isTypeError());
553 throw err;
554 }
555 }
556
557 // Unless the type is guaranteed to match, add a dynamic type check,
558 // unless the value is already known in which case we might as well report
559 // the error now.
560
561 if (!(relation == TypeHierarchy.SAME_TYPE || relation == TypeHierarchy.SUBSUMED_BY)) {
562 Expression cexp = new ItemChecker(exp, reqItemType, role);
563 cexp.adoptChildExpression(exp);
564 exp = cexp;
565 }
566
567 if (!cardOK) {
568 if (exp instanceof Literal) {
569 XPathException err = new XPathException("Required cardinality of " + role.getMessage() +
570 " is " + Cardinality.toString(reqCard) +
571 "; supplied value has cardinality " +
572 Cardinality.toString(suppliedCard), role.getErrorCode(), supplied.getLocation());
573 err.setIsTypeError(role.isTypeError());
574 throw err;
575 } else {
576 Expression cexp = CardinalityChecker.makeCardinalityChecker(exp, reqCard, role);
577 cexp.adoptChildExpression(exp);
578 exp = cexp;
579 }
580 }
581
582 return exp;
583 }
584
585 /**
586 * Test whether a given value conforms to a given type
587 *
588 * @param val the value
589 * @param requiredType the required type
590 * @param context XPath dynamic context
591 * @return an XPathException describing the error condition if the value doesn't conform;
592 * or null if it does.
593 * @throws XPathException if a failure occurs reading the value
594 */
595
596 /*@Nullable*/
597 public static XPathException testConformance(
598 Sequence<?> val, SequenceType requiredType, XPathContext context)
599 throws XPathException {
600 ItemType reqItemType = requiredType.getPrimaryType();
601 SequenceIterator<?> iter = val.iterate();
602 int count = 0;
603 Item item;
604 while ((item = iter.next()) != null) {
605 count++;
606 if (!reqItemType.matches(item, context.getConfiguration().getTypeHierarchy())) {
607 XPathException err = new XPathException("Required type is " + reqItemType +
608 "; supplied value has type " + UType.getUType(val.materialize()));
609 err.setIsTypeError(true);
610 err.setErrorCode("XPTY0004");
611 return err;
612 }
613 }
614
615 int reqCardinality = requiredType.getCardinality();
616 if (count == 0 && !Cardinality.allowsZero(reqCardinality)) {
617 XPathException err = new XPathException(
618 "Required type does not allow empty sequence, but supplied value is empty");
619 err.setIsTypeError(true);
620 err.setErrorCode("XPTY0004");
621 return err;
622 }
623 if (count > 1 && !Cardinality.allowsMany(reqCardinality)) {
624 XPathException err = new XPathException(
625 "Required type requires a singleton sequence; supplied value contains " + count + " items");
626 err.setIsTypeError(true);
627 err.setErrorCode("XPTY0004");
628 return err;
629 }
630 if (count > 0 && reqCardinality == StaticProperty.EMPTY) {
631 XPathException err = new XPathException(
632 "Required type requires an empty sequence, but supplied value is non-empty");
633 err.setIsTypeError(true);
634 err.setErrorCode("XPTY0004");
635 return err;
636 }
637 return null;
638 }
639
640 /**
641 * Test whether a given expression is capable of returning a value that has an effective boolean
642 * value.
643 *
644 * @param exp the given expression
645 * @param th the type hierarchy cache
646 * @return null if the expression is OK (optimistically), an exception object if not
647 */
648
649 public static XPathException ebvError(Expression exp, TypeHierarchy th) {
650 if (Cardinality.allowsZero(exp.getCardinality())) {
651 return null;
652 }
653 ItemType t = exp.getItemType();
654 if (th.relationship(t, Type.NODE_TYPE) == TypeHierarchy.DISJOINT &&
655 th.relationship(t, BuiltInAtomicType.BOOLEAN) == TypeHierarchy.DISJOINT &&
656 th.relationship(t, BuiltInAtomicType.STRING) == TypeHierarchy.DISJOINT &&
657 th.relationship(t, BuiltInAtomicType.ANY_URI) == TypeHierarchy.DISJOINT &&
658 th.relationship(t, BuiltInAtomicType.UNTYPED_ATOMIC) == TypeHierarchy.DISJOINT &&
659 th.relationship(t, NumericType.getInstance()) == TypeHierarchy.DISJOINT &&
660 !(t instanceof JavaExternalObjectType)) {
661 XPathException err = new XPathException(
662 "Effective boolean value is defined only for sequences containing " +
663 "booleans, strings, numbers, URIs, or nodes");
664 err.setErrorCode("FORG0006");
665 err.setIsTypeError(true);
666 return err;
667 }
668 return null;
669 }
670
671 private static Expression makePromoterToDouble(Expression exp) {
672 return makePromoter(exp, new Converter.PromoterToDouble(), BuiltInAtomicType.DOUBLE);
673 }
674
675 private static Expression makePromoterToFloat(Expression exp) {
676 return makePromoter(exp, new Converter.PromoterToFloat(), BuiltInAtomicType.FLOAT);
677 }
678
679 private static Expression makePromoterToString(Expression exp) {
680 return makePromoter(exp, new Converter.ToStringConverter(), BuiltInAtomicType.STRING);
681 }
682
683 private static Expression makePromoter(Expression exp, Converter converter, BuiltInAtomicType type) {
684 ConversionRules rules = exp.getConfiguration().getConversionRules();
685 converter.setConversionRules(rules);
686 if (exp instanceof Literal && ((Literal) exp).getValue() instanceof AtomicValue) {
687 ConversionResult result = converter.convert((AtomicValue) ((Literal) exp).getValue());
688 if (result instanceof AtomicValue) {
689 Literal converted = Literal.makeLiteral((AtomicValue) result, exp);
690 ExpressionTool.copyLocationInfo(exp, converted);
691 return converted;
692 }
693 }
694 AtomicSequenceConverter asc = new AtomicSequenceConverter(exp, type);
695 asc.setConverter(converter);
696 ExpressionTool.copyLocationInfo(exp, asc);
697 return asc;
698 }
699
700 }