Skip to content

Commit bb9e681

Browse files
authored
cognitive-complexity: handle direct recursion (#1149)
1 parent 3bc2404 commit bb9e681

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

rule/cognitive_complexity.go

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,9 @@ func (w cognitiveComplexityLinter) lintCognitiveComplexity() {
6767
f := w.file
6868
for _, decl := range f.AST.Decls {
6969
if fn, ok := decl.(*ast.FuncDecl); ok && fn.Body != nil {
70-
v := cognitiveComplexityVisitor{}
70+
v := cognitiveComplexityVisitor{
71+
name: fn.Name,
72+
}
7173
c := v.subTreeComplexity(fn.Body)
7274
if c > w.maxComplexity {
7375
w.onFailure(lint.Failure{
@@ -82,6 +84,7 @@ func (w cognitiveComplexityLinter) lintCognitiveComplexity() {
8284
}
8385

8486
type cognitiveComplexityVisitor struct {
87+
name *ast.Ident
8588
complexity int
8689
nestingLevel int
8790
}
@@ -125,8 +128,15 @@ func (v *cognitiveComplexityVisitor) Visit(n ast.Node) ast.Visitor {
125128
if n.Label != nil {
126129
v.complexity++
127130
}
131+
case *ast.CallExpr:
132+
if ident, ok := n.Fun.(*ast.Ident); ok {
133+
if ident.Obj == v.name.Obj && ident.Name == v.name.Name {
134+
// called by same function directly (direct recursion)
135+
v.complexity++
136+
return nil
137+
}
138+
}
128139
}
129-
// TODO handle (at least) direct recursion
130140

131141
return v
132142
}

testdata/cognitive_complexity.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -281,3 +281,13 @@ func (m *Migrator) MigrateIfNeeded(target *EtcdVersionPair) error { // MATCH /fu
281281

282282
// no regression test for issue #451
283283
func myFunc()
284+
285+
// Recursive functions
286+
func Walk(t *Tree, ch chan int) { // MATCH /function Walk has cognitive complexity 3 (> max enabled 0)/
287+
if t == nil { // +1
288+
return
289+
}
290+
Walk(t.Left, ch) // +1
291+
ch <- t.Value
292+
Walk(t.Right, ch) // +1
293+
}

0 commit comments

Comments
 (0)