Skip to content
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
3 changes: 2 additions & 1 deletion domain/complexity.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,8 @@ type ComplexityMetrics struct {
Edges int `json:"edges" yaml:"edges"`

// Nesting depth
NestingDepth int `json:"nesting_depth" yaml:"nesting_depth"`
NestingDepth int `json:"nesting_depth" yaml:"nesting_depth"`
DeepestNestingLine int `json:"deepest_nesting_line" yaml:"deepest_nesting_line"`

// Statement counts
IfStatements int `json:"if_statements" yaml:"if_statements"`
Expand Down
6 changes: 5 additions & 1 deletion domain/suggestion.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,8 +127,12 @@ func generateComplexitySuggestions(resp *ComplexityResponse) []Suggestion {
desc = fmt.Sprintf("Function '%s' has cyclomatic complexity of %d.", f.Name, complexity)
if f.Metrics.NestingDepth > 4 {
desc += " Consider using early returns or guard clauses to reduce nesting depth."
deepestLine := f.Metrics.DeepestNestingLine
if deepestLine == 0 {
deepestLine = f.StartLine
}
steps = []string{
fmt.Sprintf("Identify the deepest nested block at line %d", f.StartLine),
fmt.Sprintf("Identify the deepest nested block at line %d", deepestLine),
"Convert nested conditions to early returns or guard clauses",
fmt.Sprintf("Re-run: pyscn analyze %s", f.FilePath),
}
Expand Down
29 changes: 28 additions & 1 deletion domain/suggestion_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ func TestGenerateSuggestions_ComplexityNestingDepth(t *testing.T) {
ScopeKind: AnalysisScopeFunction,
FilePath: "a.py",
StartLine: 42,
Metrics: ComplexityMetrics{Complexity: 25, NestingDepth: 5},
Metrics: ComplexityMetrics{Complexity: 25, NestingDepth: 5, DeepestNestingLine: 57},
},
},
},
Expand All @@ -95,6 +95,33 @@ func TestGenerateSuggestions_ComplexityNestingDepth(t *testing.T) {
if !strings.Contains(suggestions[0].Steps[1], "guard clauses") {
t.Errorf("expected 'guard clauses' in steps for deep nesting, got: %v", suggestions[0].Steps)
}
if suggestions[0].Steps[0] != "Identify the deepest nested block at line 57" {
t.Errorf("expected step to point at the deepest nested block, got: %s", suggestions[0].Steps[0])
}
}

func TestGenerateSuggestions_ComplexityNestingDepthWithoutLine(t *testing.T) {
resp := &AnalyzeResponse{
Complexity: &ComplexityResponse{
Functions: []FunctionComplexity{
{
Name: "deep_func",
ScopeKind: AnalysisScopeFunction,
FilePath: "a.py",
StartLine: 42,
Metrics: ComplexityMetrics{Complexity: 25, NestingDepth: 5},
},
},
},
}

suggestions := GenerateSuggestions(resp)
if len(suggestions) != 1 {
t.Fatalf("expected 1 suggestion, got %d", len(suggestions))
}
if suggestions[0].Steps[0] != "Identify the deepest nested block at line 42" {
t.Errorf("expected step to fall back to the function's start line, got: %s", suggestions[0].Steps[0])
}
}

func TestGenerateSuggestions_ComplexityDefault(t *testing.T) {
Expand Down
7 changes: 6 additions & 1 deletion internal/analyzer/complexity.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ type ComplexityResult struct {

// Nesting depth
NestingDepth int
DeepestNestingLine int
CognitiveComplexity int

// Decision points breakdown
Expand Down Expand Up @@ -107,11 +108,14 @@ func CalculateComplexityWithConfig(cfg *CFG, complexityConfig *config.Complexity
// Calculate nesting depth and location from the original AST node if available.
// The same node feeds CalculateCognitiveComplexity above via cfgSourceNode.
nestingDepth := 0
deepestNestingLine := 0
startLine := 0
startCol := 0
endLine := 0
if sourceNode != nil {
nestingDepth = CalculateMaxNestingDepth(sourceNode).MaxDepth
nesting := CalculateMaxNestingDepth(sourceNode)
nestingDepth = nesting.MaxDepth
deepestNestingLine = nesting.DeepestNestingLine

startLine = sourceNode.Location.StartLine
startCol = sourceNode.Location.StartCol
Expand All @@ -128,6 +132,7 @@ func CalculateComplexityWithConfig(cfg *CFG, complexityConfig *config.Complexity
StartCol: startCol,
EndLine: endLine,
NestingDepth: nestingDepth,
DeepestNestingLine: deepestNestingLine,
CognitiveComplexity: reportedMetrics.CognitiveComplexity,
IfStatements: reportedMetrics.IfStatements,
LoopStatements: reportedMetrics.LoopStatements,
Expand Down
1 change: 1 addition & 0 deletions service/complexity_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,7 @@ func (s *ComplexityServiceImpl) calculateScopeComplexities(filePath string, cfgs
Nodes: result.Nodes,
Edges: result.Edges,
NestingDepth: result.NestingDepth,
DeepestNestingLine: result.DeepestNestingLine,
IfStatements: result.IfStatements,
LoopStatements: result.LoopStatements,
ExceptionHandlers: result.ExceptionHandlers,
Expand Down
34 changes: 34 additions & 0 deletions service/complexity_service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,40 @@ def handle(value):
assert.Equal(t, 5, handler.Metrics.CognitiveComplexity)
})

t.Run("functions carry the line of their deepest nested block", func(t *testing.T) {
tempDir := t.TempDir()
filePath := tempDir + "/deep_nesting.py"
content := []byte(`def handle(events, a, b, c):
"""Process events."""
total = 0
for e in events:
if e.kind == 1:
if a:
if b:
if c:
if e.value > 10:
total += e.value
elif e.value > 5:
total -= 1
elif e.kind == 2:
total += 2
return total
`)
err := os.WriteFile(filePath, content, 0644)
require.NoError(t, err)

req := newDefaultComplexityRequest(filePath)

response, err := service.Analyze(ctx, req)

require.NoError(t, err)
require.NotNil(t, response)
handler := findFunctionComplexity(response.Functions, "handle")
require.NotNil(t, handler)
assert.Equal(t, 1, handler.StartLine)
assert.Equal(t, 9, handler.Metrics.DeepestNestingLine)
})

t.Run("module-level complexity includes cognitive and nesting metrics", func(t *testing.T) {
tempDir := t.TempDir()
filePath := tempDir + "/module_control_flow.py"
Expand Down
1 change: 1 addition & 0 deletions website/docs/output/schemas.md
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,7 @@ The standalone complexity formatter uses `by_directory` at the report root besid
| `nodes` | integer | CFG node count. |
| `edges` | integer | CFG edge count. |
| `nesting_depth` | integer | Maximum nesting depth. |
| `deepest_nesting_line` | integer | Line of the deepest nested block. |
| `if_statements` | integer | Count of `if` statements. |
| `loop_statements` | integer | Count of `for`/`while` loops. |
| `exception_handlers` | integer | Count of `except` clauses. |
Expand Down
Loading