Skip to content

Commit

Permalink
Add note about scopes on assignment (#37)
Browse files Browse the repository at this point in the history
  • Loading branch information
ckaznocha authored Nov 9, 2024
1 parent bb12ee5 commit e286abb
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
13 changes: 12 additions & 1 deletion intrange.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@ func checkForStmt(pass *analysis.Pass, forStmt *ast.ForStmt) {
return
}

initAssign := init.Tok == token.ASSIGN

if len(init.Lhs) != 1 || len(init.Rhs) != 1 {
return
}
Expand Down Expand Up @@ -229,6 +231,15 @@ func checkForStmt(pass *analysis.Pass, forStmt *ast.ForStmt) {
return
}

if initAssign {
pass.Report(analysis.Diagnostic{
Pos: forStmt.Pos(),
Message: msg + "\nBecause the key is not part of the loop's scope, take care to consider side effects.",
})

return
}

rangeX := operandToString(pass, initIdent, operand)

pass.Report(analysis.Diagnostic{
Expand Down Expand Up @@ -523,7 +534,7 @@ func operandToString(pass *analysis.Pass, i *ast.Ident, operand ast.Expr) string
return s
}

if len(s) > 2 && s[len(s)-1:] == ")" {
if len(s) > 2 && s[len(s)-1] == ')' {
return s
}

Expand Down
6 changes: 6 additions & 0 deletions testdata/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -335,3 +335,9 @@ func issue27() {
func notLen(any) int {
return 0
}

func issue33() {
var i int
for i = 0; i < 10; i++ { // want `for loop can be changed to use an integer range \(Go 1\.22\+\)\nBecause the key is not part of the loop's scope, take care to consider side effects.`
}
}
6 changes: 6 additions & 0 deletions testdata/main.go.golden
Original file line number Diff line number Diff line change
Expand Up @@ -335,3 +335,9 @@ func issue27() {
func notLen(any) int {
return 0
}

func issue33() {
var i int
for i = 0; i < 10; i++ { // want `for loop can be changed to use an integer range \(Go 1\.22\+\)\nBecause the key is not part of the loop's scope, take care to consider side effects.`
}
}

0 comments on commit e286abb

Please sign in to comment.