|
| 1 | +package analyzer |
| 2 | + |
| 3 | +import ( |
| 4 | + "go/ast" |
| 5 | + "go/parser" |
| 6 | + "go/token" |
| 7 | + "math" |
| 8 | +) |
| 9 | + |
| 10 | +// Operator represents a unique operator in Halstead metrics |
| 11 | +type Operator struct { |
| 12 | + Token token.Token |
| 13 | + Name string |
| 14 | + Frequency int |
| 15 | +} |
| 16 | + |
| 17 | +// Operand represents a unique operand in Halstead metrics |
| 18 | +type Operand struct { |
| 19 | + Name string |
| 20 | + Frequency int |
| 21 | +} |
| 22 | + |
| 23 | +// MetricsResult stores the complexity metrics for a single file or function |
| 24 | +type MetricsResult struct { |
| 25 | + Name string `json:"name"` |
| 26 | + CyclomaticComplexity int `json:"cyclomaticComplexity"` |
| 27 | + CognitiveComplexity int `json:"cognitiveComplexity"` |
| 28 | + LinesOfCode int `json:"linesOfCode"` |
| 29 | + HalsteadVolume float64 `json:"halsteadVolume"` |
| 30 | + HalsteadDifficulty float64 `json:"halsteadDifficulty"` |
| 31 | + HalsteadEffort float64 `json:"halsteadEffort"` |
| 32 | + MaintainabilityIndex float64 `json:"maintainabilityIndex"` |
| 33 | + NestingLevel int `json:"nestingLevel"` |
| 34 | +} |
| 35 | + |
| 36 | +// FileAnalyzer handles the analysis of a single file |
| 37 | +type FileAnalyzer struct { |
| 38 | + fset *token.FileSet |
| 39 | + ast *ast.File |
| 40 | +} |
| 41 | + |
| 42 | +// NewFileAnalyzer creates a new analyzer for the given file content |
| 43 | +func NewFileAnalyzer(filename string, content []byte) (*FileAnalyzer, error) { |
| 44 | + fset := token.NewFileSet() |
| 45 | + node, err := parser.ParseFile(fset, filename, content, parser.AllErrors) |
| 46 | + if err != nil { |
| 47 | + return nil, err |
| 48 | + } |
| 49 | + |
| 50 | + return &FileAnalyzer{ |
| 51 | + fset: fset, |
| 52 | + ast: node, |
| 53 | + }, nil |
| 54 | +} |
| 55 | + |
| 56 | +// CalculateCyclomaticComplexity calculates McCabe's cyclomatic complexity |
| 57 | +func (fa *FileAnalyzer) CalculateCyclomaticComplexity(node ast.Node) int { |
| 58 | + complexity := 1 // Base complexity |
| 59 | + |
| 60 | + ast.Inspect(node, func(n ast.Node) bool { |
| 61 | + switch n := n.(type) { |
| 62 | + case *ast.IfStmt, *ast.ForStmt, *ast.RangeStmt, *ast.CaseClause, |
| 63 | + *ast.CommClause: |
| 64 | + complexity++ |
| 65 | + case *ast.BinaryExpr: |
| 66 | + if n.Op == token.LAND || n.Op == token.LOR { |
| 67 | + complexity++ |
| 68 | + } |
| 69 | + } |
| 70 | + return true |
| 71 | + }) |
| 72 | + |
| 73 | + return complexity |
| 74 | +} |
| 75 | + |
| 76 | +// CalculateCognitiveComplexity calculates cognitive complexity |
| 77 | +func (fa *FileAnalyzer) CalculateCognitiveComplexity(node ast.Node) int { |
| 78 | + complexity := 0 |
| 79 | + nestingLevel := 0 |
| 80 | + |
| 81 | + var inspect func(ast.Node) bool |
| 82 | + inspect = func(n ast.Node) bool { |
| 83 | + switch n := n.(type) { |
| 84 | + case *ast.IfStmt: |
| 85 | + complexity += 1 + nestingLevel |
| 86 | + nestingLevel++ |
| 87 | + ast.Inspect(n.Body, inspect) |
| 88 | + if n.Else != nil { |
| 89 | + complexity++ |
| 90 | + ast.Inspect(n.Else, inspect) |
| 91 | + } |
| 92 | + nestingLevel-- |
| 93 | + return false |
| 94 | + case *ast.ForStmt, *ast.RangeStmt: |
| 95 | + complexity += 1 + nestingLevel |
| 96 | + nestingLevel++ |
| 97 | + ast.Inspect(n, inspect) |
| 98 | + nestingLevel-- |
| 99 | + return false |
| 100 | + case *ast.SwitchStmt: |
| 101 | + complexity += 1 + nestingLevel |
| 102 | + nestingLevel++ |
| 103 | + ast.Inspect(n, inspect) |
| 104 | + nestingLevel-- |
| 105 | + return false |
| 106 | + } |
| 107 | + return true |
| 108 | + } |
| 109 | + |
| 110 | + ast.Inspect(node, inspect) |
| 111 | + return complexity |
| 112 | +} |
| 113 | + |
| 114 | +// calculateHalsteadMetrics calculates Halstead complexity metrics |
| 115 | +func (fa *FileAnalyzer) calculateHalsteadMetrics(node ast.Node) (volume, difficulty, effort float64) { |
| 116 | + operators := make(map[token.Token]int) |
| 117 | + operands := make(map[string]int) |
| 118 | + |
| 119 | + ast.Inspect(node, func(n ast.Node) bool { |
| 120 | + switch n := n.(type) { |
| 121 | + case *ast.BinaryExpr: |
| 122 | + operators[n.Op]++ |
| 123 | + case *ast.UnaryExpr: |
| 124 | + operators[n.Op]++ |
| 125 | + case *ast.Ident: |
| 126 | + operands[n.Name]++ |
| 127 | + case *ast.BasicLit: |
| 128 | + operands[n.Value]++ |
| 129 | + } |
| 130 | + return true |
| 131 | + }) |
| 132 | + |
| 133 | + n1 := float64(len(operators)) // unique operators |
| 134 | + n2 := float64(len(operands)) // unique operands |
| 135 | + N1 := float64(0) // total operators |
| 136 | + N2 := float64(0) // total operands |
| 137 | + |
| 138 | + for _, count := range operators { |
| 139 | + N1 += float64(count) |
| 140 | + } |
| 141 | + for _, count := range operands { |
| 142 | + N2 += float64(count) |
| 143 | + } |
| 144 | + |
| 145 | + vocabulary := n1 + n2 |
| 146 | + length := N1 + N2 |
| 147 | + volume = float64(length) * math.Log2(vocabulary) |
| 148 | + difficulty = (n1 / 2) * (N2 / n2) |
| 149 | + effort = difficulty * volume |
| 150 | + |
| 151 | + return volume, difficulty, effort |
| 152 | +} |
| 153 | + |
| 154 | +// CalculateMaintainabilityIndex calculates the maintainability index |
| 155 | +func (fa *FileAnalyzer) CalculateMaintainabilityIndex(cyclomatic int, halsteadVolume float64, linesOfCode int) float64 { |
| 156 | + // Original formula: MI = 171 - 5.2 * ln(HV) - 0.23 * CC - 16.2 * ln(LOC) |
| 157 | + mi := 171 - 5.2*math.Log(halsteadVolume) - 0.23*float64(cyclomatic) - 16.2*math.Log(float64(linesOfCode)) |
| 158 | + // Normalize to 0-100 scale |
| 159 | + mi = math.Max(0, math.Min(100, mi*100/171)) |
| 160 | + return mi |
| 161 | +} |
| 162 | + |
| 163 | +// CountLinesOfCode counts the number of non-empty lines in a function |
| 164 | +func (fa *FileAnalyzer) CountLinesOfCode(node ast.Node) int { |
| 165 | + start := fa.fset.Position(node.Pos()) |
| 166 | + end := fa.fset.Position(node.End()) |
| 167 | + return end.Line - start.Line + 1 |
| 168 | +} |
| 169 | + |
| 170 | +// AnalyzeFunction analyzes a single function and returns its metrics |
| 171 | +func (fa *FileAnalyzer) AnalyzeFunction(funcDecl *ast.FuncDecl) *MetricsResult { |
| 172 | + // Add validation for nil function declaration |
| 173 | + if funcDecl == nil || funcDecl.Name == nil { |
| 174 | + return nil |
| 175 | + } |
| 176 | + |
| 177 | + cyclomaticComplexity := fa.CalculateCyclomaticComplexity(funcDecl) |
| 178 | + cognitiveComplexity := fa.CalculateCognitiveComplexity(funcDecl) |
| 179 | + linesOfCode := fa.CountLinesOfCode(funcDecl) |
| 180 | + |
| 181 | + volume, difficulty, effort := fa.calculateHalsteadMetrics(funcDecl) |
| 182 | + |
| 183 | + // Add validation for edge cases |
| 184 | + if volume <= 0 { |
| 185 | + volume = 1 // Avoid log(0) in maintainability index calculation |
| 186 | + } |
| 187 | + if linesOfCode <= 0 { |
| 188 | + linesOfCode = 1 |
| 189 | + } |
| 190 | + |
| 191 | + maintainabilityIndex := fa.CalculateMaintainabilityIndex(cyclomaticComplexity, volume, linesOfCode) |
| 192 | + |
| 193 | + // Ensure all metrics are valid |
| 194 | + if math.IsNaN(volume) || math.IsInf(volume, 0) { |
| 195 | + volume = 0 |
| 196 | + } |
| 197 | + if math.IsNaN(difficulty) || math.IsInf(difficulty, 0) { |
| 198 | + difficulty = 0 |
| 199 | + } |
| 200 | + if math.IsNaN(effort) || math.IsInf(effort, 0) { |
| 201 | + effort = 0 |
| 202 | + } |
| 203 | + if math.IsNaN(maintainabilityIndex) || math.IsInf(maintainabilityIndex, 0) { |
| 204 | + maintainabilityIndex = 0 |
| 205 | + } |
| 206 | + |
| 207 | + return &MetricsResult{ |
| 208 | + Name: funcDecl.Name.Name, |
| 209 | + CyclomaticComplexity: cyclomaticComplexity, |
| 210 | + CognitiveComplexity: cognitiveComplexity, |
| 211 | + LinesOfCode: linesOfCode, |
| 212 | + HalsteadVolume: math.Round(volume*100) / 100, |
| 213 | + HalsteadDifficulty: math.Round(difficulty*100) / 100, |
| 214 | + HalsteadEffort: math.Round(effort*100) / 100, |
| 215 | + MaintainabilityIndex: math.Round(maintainabilityIndex*100) / 100, |
| 216 | + } |
| 217 | +} |
| 218 | + |
| 219 | +// AnalyzeFile analyzes the entire file and returns metrics for all functions |
| 220 | +func (fa *FileAnalyzer) AnalyzeFile() []*MetricsResult { |
| 221 | + var results []*MetricsResult |
| 222 | + |
| 223 | + ast.Inspect(fa.ast, func(n ast.Node) bool { |
| 224 | + if funcDecl, ok := n.(*ast.FuncDecl); ok { |
| 225 | + results = append(results, fa.AnalyzeFunction(funcDecl)) |
| 226 | + } |
| 227 | + return true |
| 228 | + }) |
| 229 | + |
| 230 | + return results |
| 231 | +} |
0 commit comments