Skip to content

Commit 232f20f

Browse files
committed
[Constraint solver] Generate constraints for “is” patterns.
Generate a checked-cast constraint for an “is” pattern, which otherwise doesn’t change the type. This is hard to validate because checked-cast constraints never actually fail.
1 parent ee90374 commit 232f20f

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

lib/Sema/CSGen.cpp

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2198,6 +2198,13 @@ namespace {
21982198
///
21992199
/// \param pattern The pattern.
22002200
Type getTypeForPattern(Pattern *pattern, ConstraintLocatorBuilder locator) {
2201+
// If there's no pattern, then we have an unknown subpattern. Create a
2202+
// type variable.
2203+
if (!pattern) {
2204+
return CS.createTypeVariable(CS.getConstraintLocator(locator),
2205+
TVO_CanBindToNoEscape);
2206+
}
2207+
22012208
switch (pattern->getKind()) {
22022209
case PatternKind::Paren:
22032210
// Parentheses don't affect the type.
@@ -2264,10 +2271,25 @@ namespace {
22642271
return OptionalType::get(subPatternType);
22652272
}
22662273

2274+
case PatternKind::Is: {
2275+
auto isPattern = cast<IsPattern>(pattern);
2276+
Type subPatternType =
2277+
getTypeForPattern(isPattern->getSubPattern(), locator);
2278+
2279+
// Make sure we can cast from the subpattern type to the type we're
2280+
// checking; if it's impossible, fail.
2281+
if (Type castType =
2282+
resolveTypeReferenceInExpression(isPattern->getCastTypeLoc())) {
2283+
CS.addConstraint(
2284+
ConstraintKind::CheckedCast, subPatternType, castType, locator);
2285+
}
2286+
2287+
return subPatternType;
2288+
}
2289+
22672290
// Refutable patterns occur when checking the PatternBindingDecls in an
22682291
// if/let or while/let condition. They always require an initial value,
22692292
// so they always allow unspecified types.
2270-
case PatternKind::Is:
22712293
case PatternKind::EnumElement:
22722294
case PatternKind::Bool:
22732295
case PatternKind::Expr:

0 commit comments

Comments
 (0)