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

cognitive-complexity: handle direct recursion #1149

Merged
Merged
Show file tree
Hide file tree
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
14 changes: 12 additions & 2 deletions rule/cognitive_complexity.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,9 @@ func (w cognitiveComplexityLinter) lintCognitiveComplexity() {
f := w.file
for _, decl := range f.AST.Decls {
if fn, ok := decl.(*ast.FuncDecl); ok && fn.Body != nil {
v := cognitiveComplexityVisitor{}
v := cognitiveComplexityVisitor{
name: fn.Name,
}
c := v.subTreeComplexity(fn.Body)
if c > w.maxComplexity {
w.onFailure(lint.Failure{
Expand All @@ -82,6 +84,7 @@ func (w cognitiveComplexityLinter) lintCognitiveComplexity() {
}

type cognitiveComplexityVisitor struct {
name *ast.Ident
complexity int
nestingLevel int
}
Expand Down Expand Up @@ -125,8 +128,15 @@ func (v *cognitiveComplexityVisitor) Visit(n ast.Node) ast.Visitor {
if n.Label != nil {
v.complexity++
}
case *ast.CallExpr:
if ident, ok := n.Fun.(*ast.Ident); ok {
if ident.Obj == v.name.Obj && ident.Name == v.name.Name {
// called by same function directly (direct recursion)
v.complexity++
return nil
}
}
}
// TODO handle (at least) direct recursion

return v
}
Expand Down
10 changes: 10 additions & 0 deletions testdata/cognitive_complexity.go
Original file line number Diff line number Diff line change
Expand Up @@ -281,3 +281,13 @@ func (m *Migrator) MigrateIfNeeded(target *EtcdVersionPair) error { // MATCH /fu

// no regression test for issue #451
func myFunc()

// Recursive functions
func Walk(t *Tree, ch chan int) { // MATCH /function Walk has cognitive complexity 3 (> max enabled 0)/
if t == nil { // +1
return
}
Walk(t.Left, ch) // +1
ch <- t.Value
Walk(t.Right, ch) // +1
}