Skip to content
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

staticcheck: add check for modifying return variables within deferred function/statement #1512

Open
iJustErikk opened this issue Apr 2, 2024 · 2 comments

Comments

@iJustErikk
Copy link

iJustErikk commented Apr 2, 2024

I'd like to propose a check for modifying return variables within a deferred function or statement. In the case of errors, they end up getting swallowed, so this can be quite an interesting foot-gun.

Here is a small program that should trigger this proposed lint:

package main

import "fmt"

func test() int {
  var res int
  defer func() {
    res += 1
  }()
  return res
}

func main() {
	fmt.Printf("%d", test())
}

This should not be triggered by setting named returns.

This should also work in the unholy cases of redeclaring the return variables in the deferred functions or with nested deferred functions.

@iJustErikk iJustErikk added the needs-triage Newly filed issue that needs triage label Apr 2, 2024
@iJustErikk
Copy link
Author

I can take this up some weekend from now if we agree on the behavior

@dominikh
Copy link
Owner

dominikh commented Apr 2, 2024

This seems like a more general case of #590 and it is non-trivial to implement correctly, especially with our current representation of closures and defer statements, which considers all variables that are closed over as escaping to the heap, which means we can't rely on SSA for tracking their def-use chains.

@dominikh dominikh added new-check and removed needs-triage Newly filed issue that needs triage labels Apr 2, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants