@@ -1015,21 +1015,11 @@ NullablePtr<Pattern> TypeChecker::trySimplifyExprPattern(ExprPattern *EP,
1015
1015
Type patternTy) {
1016
1016
auto *subExpr = EP->getSubExpr ();
1017
1017
auto &ctx = EP->getDeclContext ()->getASTContext ();
1018
-
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
- }
1018
+ const auto wrappedType = patternTy->getOptionalObjectType ();
1029
1019
1030
1020
// case nil is equivalent to .none when switching on Optionals.
1031
- if (auto *NLE = dyn_cast<NilLiteralExpr>(EP-> getSubExpr () )) {
1032
- if (patternTy-> getOptionalObjectType () ) {
1021
+ if (auto *NLE = dyn_cast<NilLiteralExpr>(subExpr )) {
1022
+ if (wrappedType ) {
1033
1023
auto *NoneEnumElement = ctx.getOptionalNoneDecl ();
1034
1024
return EnumElementPattern::createImplicit (
1035
1025
patternTy, NLE->getLoc (), DeclNameLoc (NLE->getLoc ()), NoneEnumElement,
@@ -1045,7 +1035,30 @@ NullablePtr<Pattern> TypeChecker::trySimplifyExprPattern(ExprPattern *EP,
1045
1035
return nullptr ;
1046
1036
}
1047
1037
}
1048
- return nullptr ;
1038
+ // Try to simplify a Boolean literal expression to a BoolPattern,
1039
+ // recursively handling multiple levels of optionality if necessary.
1040
+ const auto *BLE = dyn_cast_or_null<BooleanLiteralExpr>(
1041
+ subExpr->getSemanticsProvidingExpr ());
1042
+ if (!BLE)
1043
+ return nullptr ;
1044
+ // If the type is Bool, return a BoolPattern.
1045
+ if (patternTy->isBool ()) {
1046
+ auto *BP = new (ctx) BoolPattern (BLE->getLoc (), BLE->getValue ());
1047
+ BP->setType (patternTy);
1048
+ return BP;
1049
+ }
1050
+ // If the pattern type is optional, attempt to simplify the wrapped type.
1051
+ // `true` and `false` are treated as if they had "?" appended
1052
+ // for each level of optionality.
1053
+ if (wrappedType) {
1054
+ auto simplified = trySimplifyExprPattern (EP, wrappedType);
1055
+ if (auto P = simplified.getPtrOrNull ()) {
1056
+ auto OP = OptionalSomePattern::createImplicit (ctx, P, P->getEndLoc ());
1057
+ OP->setType (patternTy);
1058
+ return OP;
1059
+ }
1060
+ }
1061
+ return nullptr ;
1049
1062
}
1050
1063
1051
1064
// / Perform top-down type coercion on the given pattern.
0 commit comments