Join GitHub today
GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.Sign up
proposal: spec: consider more strict "declared and not used" check (go/vet or even spec) #20802
The following code
compiles without errors even though it is obviously incorrect: Inside the block of the
Arguably, assignments to fields/elements of composite type variables shouldn't be counted as uses. Their effect is lost if the variable itself is never used and they may hide the fact that the variable is not used.
(This was the underlying cause for #20789.)
It's surprisingly tricky to detect "weakly used" variables in the general case. In the simple example above, where x is a variable of struct type T and its field f field is not a reference, it suffices to prove that all references to x occur "on the left side" of an assignment. However, this simple check is inadequate for selections that are indirect. If the type of x.f is a pointer or reference, then the sequence of assignments
A sound check strong enough to catch the bug that motivated this proposal would require SSA form and a simple escape analysis, which is more complex than belongs in the language spec, but possibly appropriate for vet.
I've sketched a simpler heuristic for vet in https://go-review.googlesource.com/c/47670.
@mvdan Unless a compiler accepts exactly the set of programs the spec requires it to accept, it is implementing a dialect of the language. Dialects cause problems for users because programs that work with one compiler or analysis tool don't work with another.