Skip to content

Commit 7356f41

Browse files
Suyash SrijanSuyash Srijan
authored andcommitted
[typechecker] allow non-optional enum case match with optional enum
1 parent cf53143 commit 7356f41

File tree

2 files changed

+28
-12
lines changed

2 files changed

+28
-12
lines changed

lib/Sema/TypeCheckPattern.cpp

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1395,19 +1395,24 @@ bool TypeChecker::coercePatternToType(Pattern *&P, TypeResolution resolution,
13951395
goto recur;
13961396
}
13971397

1398-
auto diag = diagnose(EEP->getLoc(),
1399-
diag::enum_element_pattern_member_not_found,
1400-
EEP->getName().str(), type);
1401-
14021398
// If we have an optional type let's try to see if the case
1403-
// exists in its base type, if so we can suggest a fix-it for that.
1399+
// exists in its base type and create a new pattern which contains
1400+
// the enum case.
14041401
if (auto baseType = type->getOptionalObjectType()) {
14051402
if (lookupEnumMemberElement(*this, dc, baseType, EEP->getName(),
1406-
EEP->getLoc()))
1407-
diag.fixItInsertAfter(EEP->getEndLoc(), "?");
1403+
EEP->getLoc())) {
1404+
P = new (Context)
1405+
OptionalSomePattern(EEP, EEP->getEndLoc(), true);
1406+
P->setImplicit();
1407+
return coercePatternToType(P, resolution, type, options);
1408+
} else {
1409+
diagnose(EEP->getLoc(),
1410+
diag::enum_element_pattern_member_not_found,
1411+
EEP->getName().str(), type);
1412+
return true;
1413+
}
14081414
}
14091415
}
1410-
return true;
14111416
}
14121417
enumTy = type;
14131418
} else {

test/Constraints/patterns.swift

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,7 @@ enum SR2057 {
254254
}
255255

256256
let sr2057: SR2057?
257-
if case .foo = sr2057 { } // expected-error{{enum case 'foo' not found in type 'SR2057?'}}
257+
if case .foo = sr2057 { } // Ok
258258

259259

260260
// Invalid 'is' pattern
@@ -333,10 +333,10 @@ struct S_32241441 {
333333
func rdar32241441() {
334334
let s: S_32241441? = S_32241441()
335335

336-
switch s?.type {
337-
case .foo: // expected-error {{enum case 'foo' not found in type 'S_32241441.E_32241441?'}} {{12-12=?}}
336+
switch s?.type { // expected-error {{switch must be exhaustive}} expected-note {{add missing case: '.none'}}
337+
case .foo: // Ok
338338
break;
339-
case .bar: // expected-error {{enum case 'bar' not found in type 'S_32241441.E_32241441?'}} {{12-12=?}}
339+
case .bar: // Ok
340340
break;
341341
}
342342
}
@@ -409,4 +409,15 @@ func test8347() -> String {
409409
}
410410
}
411411

412+
enum SR_7799 {
413+
case baz
414+
case bar
415+
}
416+
417+
let sr7799: SR_7799? = .bar
412418

419+
switch sr7799 {
420+
case .bar?: break // Ok
421+
case .baz: break // Ok
422+
default: break
423+
}

0 commit comments

Comments
 (0)