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

simple: enforce early return in loops #1334

Open
nfx opened this issue Nov 15, 2022 · 3 comments · May be fixed by #1340
Open

simple: enforce early return in loops #1334

nfx opened this issue Nov 15, 2022 · 3 comments · May be fixed by #1340

Comments

@nfx
Copy link

nfx commented Nov 15, 2022

Early returns help to reduce nesting levels. I wonder how much effort is it to implement with staticcheck.io. Examples are:

unwanted:

for _, v := range x {
    if condition {
        // do stuff
    }
}

wanted:

for _, v := range x {
    if negatedCondition {
        continue
    }
    // do stuff
}
@nfx nfx added the needs-triage Newly filed issue that needs triage label Nov 15, 2022
@dominikh dominikh added new-check and removed needs-triage Newly filed issue that needs triage labels Nov 15, 2022
@dominikh dominikh changed the title New check: enforce early return in loops simple: enforce early return in loops Nov 15, 2022
@dominikh
Copy link
Owner

Related: #187.

I wonder how much effort is it to implement with staticcheck.io

It should be fairly simple to implement a check that flags the code. Adding an automated suggested fix would be problematic due to the way go/ast handles comments.

However, it won't be a high priority for me in the near future, as I want to concentrate on correctness issues for the time being, not stylistic ones.

@dgryski
Copy link

dgryski commented Nov 16, 2022

This is pretty straightforward to implement with ruleguard or semgrep.

Edit:

rules:
  - id: loop-nesting
    patterns:
    - pattern: |
              for ... {
                if ... {
                  ...
                }
              }
    message: "reduce nesting in loop with continue"
    languages: [go]
    severity: ERROR

Edit: So I ran this on all the Go code on my machine and basically triggered nothing but false positives. Probably there needs to be some logic to ignore blocks with 'break' or 'return' in the indented body, and maybe a minimum indented body length.

@nfx
Copy link
Author

nfx commented Nov 17, 2022

@dominikh great that you agree this check is simple. I'll see if I can find time to make a PR

@param108 param108 linked a pull request Dec 8, 2022 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants