Skip to content

Commit 1d903b2

Browse files
authored
Merge pull request #81882 from DougGregor/unsafe-implied-conformance
[Strict memory safety] Improve Fix-Its for implied conformances
2 parents 0309879 + 9af5884 commit 1d903b2

File tree

2 files changed

+35
-3
lines changed

2 files changed

+35
-3
lines changed

lib/Sema/TypeCheckProtocol.cpp

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2691,10 +2691,28 @@ checkIndividualConformance(NormalProtocolConformance *conformance) {
26912691
}
26922692

26932693
if (!unsafeUses.empty()) {
2694-
Context.Diags.diagnose(
2694+
// Primary diagnostic along with a Fix-It to add @unsafe in the appropriate
2695+
// place.
2696+
{
2697+
auto diag = Context.Diags.diagnose(
26952698
conformance->getLoc(), diag::conformance_involves_unsafe,
2696-
conformance->getType(), Proto)
2697-
.fixItInsert(conformance->getProtocolNameLoc(), "@unsafe ");
2699+
conformance->getType(), Proto);
2700+
2701+
// Find the original explicit conformance, where we can add the Fix-It.
2702+
auto explicitConformance = conformance;
2703+
while (explicitConformance->getSourceKind() ==
2704+
ConformanceEntryKind::Implied) {
2705+
explicitConformance =
2706+
explicitConformance->ProtocolConformance::getImplyingConformance();
2707+
}
2708+
2709+
if (explicitConformance->getSourceKind() ==
2710+
ConformanceEntryKind::Explicit) {
2711+
diag.fixItInsert(explicitConformance->getProtocolNameLoc(),
2712+
"@unsafe ");
2713+
}
2714+
}
2715+
26982716
for (const auto& unsafeUse : unsafeUses)
26992717
diagnoseUnsafeUse(unsafeUse);
27002718
}

test/Unsafe/safe.swift

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -359,3 +359,17 @@ func testSwitch(se: SomeEnum) {
359359

360360
if case unsafe someEnumValue = unsafe se { }
361361
}
362+
363+
@unsafe class SomeClass {}
364+
@unsafe class SomeClassWrapper { }
365+
366+
protocol Associated {
367+
associatedtype Associated
368+
}
369+
370+
protocol CustomAssociated: Associated { }
371+
372+
// expected-warning@+1{{conformance of 'SomeClass' to protocol 'Associated' involves unsafe code}}{{22-22=@unsafe }}
373+
extension SomeClass: CustomAssociated {
374+
typealias Associated = SomeClassWrapper // expected-note{{unsafe type 'SomeClass.Associated' (aka 'SomeClassWrapper') cannot satisfy safe associated type 'Associated'}}
375+
}

0 commit comments

Comments
 (0)