@@ -1011,24 +1011,39 @@ void repairTupleOrAssociatedValuePatternIfApplicable(
1011
1011
}
1012
1012
}
1013
1013
1014
+ // / Try to simplify an `ExprPattern` with a Boolean literal sub-expression
1015
+ // / to a `BoolPattern`, recursively unwrapping optional types if necessary.
1016
+ static NullablePtr<Pattern> simplifyToBoolPattern (ASTContext &Ctx,
1017
+ const ExprPattern *EP,
1018
+ const BooleanLiteralExpr *BLE,
1019
+ Type patternTy) {
1020
+ // If the type is Bool, return a BoolPattern.
1021
+ if (patternTy->isBool ()) {
1022
+ auto *BP = new (Ctx) BoolPattern (BLE->getLoc (), BLE->getValue ());
1023
+ BP->setType (patternTy);
1024
+ return BP;
1025
+ }
1026
+ // If the pattern type is optional, attempt to simplify the wrapped type.
1027
+ // `true` and `false` are treated as if they had `?` appended
1028
+ // for each level of optionality.
1029
+ if (auto wrappedType = patternTy->getOptionalObjectType ()) {
1030
+ if (auto P =
1031
+ simplifyToBoolPattern (Ctx, EP, BLE, wrappedType).getPtrOrNull ()) {
1032
+ auto OP = OptionalSomePattern::createImplicit (Ctx, P, P->getEndLoc ());
1033
+ OP->setType (patternTy);
1034
+ return OP;
1035
+ }
1036
+ }
1037
+ return nullptr ;
1038
+ }
1039
+
1014
1040
NullablePtr<Pattern> TypeChecker::trySimplifyExprPattern (ExprPattern *EP,
1015
1041
Type patternTy) {
1016
1042
auto *subExpr = EP->getSubExpr ();
1017
1043
auto &ctx = EP->getDeclContext ()->getASTContext ();
1018
1044
1019
- if (patternTy->isBool ()) {
1020
- // The type is Bool.
1021
- // Check if the pattern is a Bool literal
1022
- auto *semanticSubExpr = subExpr->getSemanticsProvidingExpr ();
1023
- if (auto *BLE = dyn_cast<BooleanLiteralExpr>(semanticSubExpr)) {
1024
- auto *BP = new (ctx) BoolPattern (BLE->getLoc (), BLE->getValue ());
1025
- BP->setType (patternTy);
1026
- return BP;
1027
- }
1028
- }
1029
-
1030
1045
// case nil is equivalent to .none when switching on Optionals.
1031
- if (auto *NLE = dyn_cast<NilLiteralExpr>(EP-> getSubExpr () )) {
1046
+ if (auto *NLE = dyn_cast<NilLiteralExpr>(subExpr )) {
1032
1047
if (patternTy->getOptionalObjectType ()) {
1033
1048
auto *NoneEnumElement = ctx.getOptionalNoneDecl ();
1034
1049
return EnumElementPattern::createImplicit (
@@ -1045,7 +1060,13 @@ NullablePtr<Pattern> TypeChecker::trySimplifyExprPattern(ExprPattern *EP,
1045
1060
return nullptr ;
1046
1061
}
1047
1062
}
1048
- return nullptr ;
1063
+
1064
+ const auto *BLE =
1065
+ dyn_cast<BooleanLiteralExpr>(subExpr->getSemanticsProvidingExpr ());
1066
+ if (!BLE)
1067
+ return nullptr ;
1068
+
1069
+ return simplifyToBoolPattern (ctx, EP, BLE, patternTy);
1049
1070
}
1050
1071
1051
1072
// / Perform top-down type coercion on the given pattern.
0 commit comments