mirror of
https://github.com/apple/swift.git
synced 2025-12-21 12:14:44 +01:00
[Dignostics] Diagnose weak declarations with non-optional types
Diagnose situations where `weak` attribute is used with a non-optional type
in declaration e.g. `weak var x: <Type>`:
```swift
class X {
}
weak var x: X = ...
```
`weak` declaration is required to use an optional type e.g. `X?`.
This commit is contained in:
@@ -7776,3 +7776,27 @@ bool UnsupportedRuntimeCheckedCastFailure::diagnoseAsError() {
|
||||
.fixItReplace(getCastRange(), "as");
|
||||
return true;
|
||||
}
|
||||
|
||||
bool InvalidWeakAttributeUse::diagnoseAsError() {
|
||||
auto *pattern =
|
||||
dyn_cast_or_null<NamedPattern>(getAnchor().dyn_cast<Pattern *>());
|
||||
if (!pattern)
|
||||
return false;
|
||||
|
||||
auto *var = pattern->getDecl();
|
||||
auto varType = getType(var);
|
||||
|
||||
auto diagnostic =
|
||||
emitDiagnosticAt(var, diag::invalid_ownership_not_optional,
|
||||
ReferenceOwnership::Weak, varType);
|
||||
|
||||
auto typeRange = var->getTypeSourceRangeForDiagnostics();
|
||||
if (varType->hasSimpleTypeRepr()) {
|
||||
diagnostic.fixItInsertAfter(typeRange.End, "?");
|
||||
} else {
|
||||
diagnostic.fixItInsert(typeRange.Start, "(")
|
||||
.fixItInsertAfter(typeRange.End, ")?");
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user