[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:
Pavel Yaskevich
2021-09-06 12:58:37 -07:00
parent 3fac0fefc9
commit 60d931612c
3 changed files with 45 additions and 1 deletions

View File

@@ -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;
}