Skip to content

[Diagnostics] Improve warning suggestion for var in for loop #76946

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions include/swift/AST/DiagnosticsSema.def
Original file line number Diff line number Diff line change
Expand Up @@ -7032,6 +7032,10 @@ WARNING(variable_never_mutated, none,
"variable %0 was never mutated; "
"consider %select{removing 'var' to make it|changing to 'let'}1 constant",
(Identifier, bool))
WARNING(variable_tuple_elt_never_mutated, none,
"variable %0 was never mutated; "
"consider changing the pattern to 'case (..., let %1, ...)'",
(Identifier, StringRef))
WARNING(variable_never_read, none,
"variable %0 was written to, but never read",
(Identifier))
Expand Down
16 changes: 14 additions & 2 deletions lib/Sema/MiscDiagnostics.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4102,8 +4102,20 @@ VarDeclUsageChecker::~VarDeclUsageChecker() {

// If this is a parameter explicitly marked 'var', remove it.
if (FixItLoc.isInvalid()) {
Diags.diagnose(var->getLoc(), diag::variable_never_mutated,
var->getName(), true);
bool suggestCaseLet = false;
if (auto *stmt = var->getRecursiveParentPatternStmt()) {
// Suggest 'var' -> 'case let' conversion
// in case of 'for' loop and invalid because it's
// tuple variable.
suggestCaseLet = isa<ForEachStmt>(stmt);
}
if (suggestCaseLet)
Diags.diagnose(var->getLoc(), diag::variable_tuple_elt_never_mutated,
var->getName(), var->getNameStr());
else
Diags.diagnose(var->getLoc(), diag::variable_never_mutated,
var->getName(), true);

}
else {
bool suggestLet = true;
Expand Down
8 changes: 8 additions & 0 deletions test/decl/var/usage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -563,3 +563,11 @@ func testUselessCastWithInvalidParam(foo: Any?) -> Int {
if let bar = foo as? Foo { return 42 } // expected-warning {{value 'bar' was defined but never used; consider replacing with boolean test}} {{6-16=}} {{20-23=is}}
else { return 54 }
}

// https://github.com/swiftlang/swift/issues/72811
func testEnumeratedForLoop(a: [Int]) {
for var (b, c) in a.enumerated() { // expected-warning {{variable 'b' was never mutated; consider changing the pattern to 'case (..., let b, ...)'}}
c = b
let _ = c
}
}