Skip to content

Commit

Permalink
Fix false positive for uninitialized variables (#1159)
Browse files Browse the repository at this point in the history
  • Loading branch information
vladmos authored Apr 25, 2023
1 parent 43e3add commit a4c276b
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
14 changes: 13 additions & 1 deletion warn/warn_control_flow.go
Original file line number Diff line number Diff line change
Expand Up @@ -712,7 +712,7 @@ func collectLocalVariables(stmts []build.Expr) []*build.Ident {
return variables
}

// searchUninitializedVariables takes a list of statements (e.g. body of a block statement)
// findUninitializedVariables takes a list of statements (e.g. body of a block statement)
// and a map of previously initialized statements, and calls `callback` on all idents that are not
// initialized. An ident is considered initialized if it's initialized by every possible execution
// path (before or by `stmts`).
Expand Down Expand Up @@ -761,8 +761,20 @@ func findUninitializedVariables(stmts []build.Expr, previouslyInitialized map[st
}
}

walkBlockList := map[build.Expr]bool{}
build.WalkInterruptable(expr, func(expr build.Expr, stack []build.Expr) (err error) {
if walkBlockList[expr] {
return &build.StopTraversalError{}
}
switch expr := expr.(type) {
case *build.DefStmt:
// The header of the DefStmt may contain uninitialized variables (e.g.
// default values of parameters) and should be traversed.
// Its body shouldn't be traversed because it has another scope and will
// be analyzed by another call of `findUninitializedVariables`.
for _, stmt := range expr.Body {
walkBlockList[stmt] = true
}
case *build.Comprehension, *build.LambdaExpr:
// Comprehension and Lambda nodes are special, they have their own scope
// with variables that are only defined inside.
Expand Down
11 changes: 11 additions & 0 deletions warn/warn_control_flow_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1270,6 +1270,17 @@ def foo():
y = [baz.get(bar) for bar in bars]
x = lambda bar: baz.get(bar)
`,
[]string{},
scopeEverywhere)

checkFindings(t, "uninitialized", `
def foo():
def bar(x):
print(x)
for x, y in z:
bar(x)
`,
[]string{},
scopeEverywhere)
Expand Down

0 comments on commit a4c276b

Please sign in to comment.