Add compile error for overwriting a value that was never used #20250
Labels
proposal
This issue suggests modifications. If it also has the "accepted" label then it is planned.
Milestone
Proposal
Add a compiler error for when you overwrite the value in a local var, but have never used it beforehand. The following code would produce an error:
In addition, overwriting
undefined
would be exempted from this. This remains valid:What counts as using?
_ = foo
) would show the reader that the value is intentionally being discardedvolatile
is always marked as having being usedfoo_ptr.*
marksfoo_ptr
as used (it's the same as reading the value offoo_ptr
, then going to that address in memory)+=
,-=
,*=
, etcAssigning to the variable would reset its
used
flag unless a pointer has been taken to it or it is volatile. Assigning to a variable that doesn't have itsused
flag set would be a compiler error.Details to flesh out
Should overwriting struct fields be a compiler error?
i.e. should
var x: Foo = .{}; x.bar = 4;
be a compiler error?I think not, just because there are legitimate use cases for something like this:
Should overwriting global vars be a compiler error?
I also think not
You would have to check ALL occurrences of the global variable, leading to confusing error messages caused by very far away code. This change should be similar in scope to the "local variable is never mutated" change.
Does overwriting the variable have to unconditionally happen?
i.e. should this code produce an error?
I'm tempted to say that this code should error, because if you've NEVER read
3
fromx
beforehand then why didn't you decide if it should be3
or4
withvar x = if(myCondition()) 4 else 3
. However, there may be legitimate usecases for something like this I can't think of.Should detecting overwrites happen in complex control flow (i.e. loops)?
I want to say yes, but I don't know how much more complicated that would make the detection. In particular, consider:
In a perfect world, this should definitely error; however, detecting such cases might make implementing this somewhat more complex (in this case it would just have to go through the loop a second time, but there could be edge cases I can't think of) especially since this is basically a lint check and there's technically not anything WRONG with the code itself. It may not be worth the extra effort.
The text was updated successfully, but these errors were encountered: