Skip to content

refactor (rule/cyclomatic): replace AST walker by iteration over declarations #1161

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

Merged
merged 1 commit into from
Dec 4, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 10 additions & 33 deletions rule/cyclomatic.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,53 +38,30 @@ func (r *CyclomaticRule) Apply(file *lint.File, arguments lint.Arguments) []lint
r.configureOnce.Do(func() { r.configure(arguments) })

var failures []lint.Failure
fileAst := file.AST

walker := lintCyclomatic{
file: file,
complexity: r.maxComplexity,
onFailure: func(failure lint.Failure) {
failures = append(failures, failure)
},
}

ast.Walk(walker, fileAst)

return failures
}

// Name returns the rule name.
func (*CyclomaticRule) Name() string {
return "cyclomatic"
}

type lintCyclomatic struct {
file *lint.File
complexity int
onFailure func(lint.Failure)
}

func (w lintCyclomatic) Visit(_ ast.Node) ast.Visitor {
f := w.file
for _, decl := range f.AST.Decls {
for _, decl := range file.AST.Decls {
fn, ok := decl.(*ast.FuncDecl)
if !ok {
continue
}

c := complexity(fn)
if c > w.complexity {
w.onFailure(lint.Failure{
if c > r.maxComplexity {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You merged, but this would have been simpler

Suggested change
if c > r.maxComplexity {
if c <= r.maxComplexity {
continue
}

failures = append(failures, lint.Failure{
Confidence: 1,
Category: "maintenance",
Failure: fmt.Sprintf("function %s has cyclomatic complexity %d (> max enabled %d)",
funcName(fn), c, w.complexity),
funcName(fn), c, r.maxComplexity),
Node: fn,
})
}
}

return nil
return failures
}

// Name returns the rule name.
func (*CyclomaticRule) Name() string {
return "cyclomatic"
}

// funcName returns the name representation of a function or method:
Expand Down
Loading