Chahuadev-smart-roadmap / src /analyzers /complexity-analyzer.js
chahuadev's picture
Upload 74 files
4fea3ee verified
/**
* ComplexityAnalyzer - Calculates cyclomatic complexity and maintainability metrics
* Updated to use EnhancedTokenizer with optional external parser support
* Multi-language support for JavaScript, Python, Java, C#, Go, PHP, Ruby, and more
*/
const EnhancedTokenizer = require('./enhanced-tokenizer');
const LanguageDetector = require('./language-detector');
class ComplexityAnalyzer {
constructor() {
this.thresholds = {
complexity: { low: 5, medium: 10, high: 20 },
maintainability: { low: 40, medium: 60, high: 80 }
};
this.tokenizer = new EnhancedTokenizer();
this.languageDetector = new LanguageDetector();
// Log parser info once
const parserInfo = this.tokenizer.getParserInfo();
if (!this._loggedParser) {
console.log(`[COMPLEXITY] Using ${parserInfo.name} parser for accurate analysis`);
this._loggedParser = true;
}
}
/**
* Analyze file complexity with DEEP per-function analysis
* Now uses AST from Babel for maximum accuracy and insights
* Multi-language support - adapts complexity calculation per language
*/
analyze(filePath, content) {
// Detect language first
const langInfo = this.languageDetector.detectFromPath(filePath);
// Try to get AST for deep analysis (JS/TS only)
const ast = this.tokenizer.parseToAST(content, filePath);
let metrics;
if (ast && this.tokenizer.hasExternalParser() && langInfo.language === 'javascript') {
// USE AST - Maximum accuracy and depth (JS/TS only)
metrics = this.analyzeWithAST(filePath, content, ast, langInfo);
} else {
// Fallback to token-based analysis (multi-language)
const tokens = this.tokenizer.tokenize(content, filePath);
const codeTokens = this.tokenizer.filterCodeTokens(tokens);
metrics = this.analyzeWithTokens(filePath, content, codeTokens, langInfo);
}
metrics.language = langInfo.language;
metrics.rating = this.calculateRating(metrics);
metrics.issues = this.identifyComplexityIssues(metrics);
return metrics;
}
/**
* Analyze with AST (when @babel/parser available)
* This gives us 10x more insights than token-based
*/
analyzeWithAST(filePath, content, ast, langInfo) {
return {
filePath,
language: langInfo.language,
cyclomaticComplexity: this.calculateCyclomaticFromAST(ast),
cognitiveComplexity: this.calculateCognitiveFromAST(ast),
maintainabilityIndex: this.calculateMaintainabilityIndex(content),
halsteadMetrics: this.calculateHalsteadFromAST(ast),
linesOfCode: this.calculateLOC(content),
functionMetrics: this.analyzeFunctionsFromAST(ast, content),
nestingAnalysis: this.analyzeNestingFromAST(ast),
parameterAnalysis: this.analyzeParametersFromAST(ast),
returnPointAnalysis: this.analyzeReturnPointsFromAST(ast),
cognitiveLoad: this.calculateCognitiveLoadFromAST(ast),
modernFeatures: this.detectModernFeatures(ast),
rating: 'A'
};
}
/**
* Analyze with tokens (fallback - multi-language support)
*/
analyzeWithTokens(filePath, content, codeTokens, langInfo) {
const functions = this.extractFunctionsDeep(content, langInfo);
return {
filePath,
language: langInfo.language,
cyclomaticComplexity: this.calculateCyclomaticComplexityFromTokens(codeTokens, langInfo),
cognitiveComplexity: this.calculateCognitiveComplexity(content, langInfo),
maintainabilityIndex: this.calculateMaintainabilityIndex(content),
halsteadMetrics: this.calculateHalsteadMetrics(content, langInfo),
linesOfCode: this.calculateLOC(content),
functionMetrics: this.analyzeFunctionsDeep(functions, content, langInfo),
nestingAnalysis: this.analyzeNestingDepth(content, langInfo),
parameterAnalysis: this.analyzeParameters(functions),
returnPointAnalysis: this.analyzeReturnPoints(functions),
cognitiveLoad: this.calculateCognitiveLoad(content, langInfo),
rating: 'A'
};
}
/**
* Calculate Cyclomatic Complexity from Tokens (100% accurate)
* No false positives from comments or strings
*/
calculateCyclomaticComplexityFromTokens(codeTokens, langInfo = {language: 'javascript'}) {
let complexity = 1; // Base complexity
// Language-specific decision keywords
const config = langInfo.config || this.languageDetector.getConfig(langInfo.language);
const decisionKeywords = config.keywords.control || ['if', 'for', 'while', 'case', 'catch', 'do'];
// Count decision keywords
complexity += this.tokenizer.countKeywords(codeTokens, decisionKeywords);
// Count logical operators (&&, || or language equivalents)
const logicalOps = codeTokens.filter(t =>
t.type === 'OPERATOR' && (t.value === '&&' || t.value === '||' || t.value === 'and' || t.value === 'or')
);
complexity += logicalOps.length;
// Count ternary operators (?)
const ternaryOps = codeTokens.filter(t =>
t.type === 'OPERATOR' && t.value === '?'
);
complexity += ternaryOps.length;
return {
total: complexity,
average: complexity, // Will be updated in generateReport
perFunction: [] // Will be populated per function
};
}
/**
* Calculate Cyclomatic Complexity (McCabe) - Legacy method
* @deprecated Use calculateCyclomaticComplexityFromTokens for accuracy
*/
calculateCyclomaticComplexity(content) {
let complexity = 1; // Base complexity
// Decision points
const decisionPoints = [
/\bif\s*\(/g,
/\belse\s+if\s*\(/g,
/\bfor\s*\(/g,
/\bwhile\s*\(/g,
/\bcase\s+/g,
/\bcatch\s*\(/g,
/\&\&/g,
/\|\|/g,
/\?\s*[^:]+:/g, // Ternary
/\bdo\s*\{/g
];
decisionPoints.forEach(pattern => {
const matches = content.match(pattern);
if (matches) {
complexity += matches.length;
}
});
// Calculate per function
const functions = this.extractFunctions(content);
const perFunction = functions.map(fn => {
let fnComplexity = 1;
decisionPoints.forEach(pattern => {
const matches = fn.body.match(pattern);
if (matches) {
fnComplexity += matches.length;
}
});
return {
name: fn.name,
complexity: fnComplexity,
severity: this.getComplexitySeverity(fnComplexity)
};
});
return {
total: complexity,
average: functions.length > 0 ? Math.round(complexity / functions.length) : 0,
perFunction: perFunction.filter(f => f.complexity > 5) // Only show complex functions
};
}
/**
* Calculate Cognitive Complexity (considers nesting)
*/
calculateCognitiveComplexity(content) {
let complexity = 0;
const lines = content.split('\n');
let nestingLevel = 0;
lines.forEach(line => {
// Track nesting
const openBraces = (line.match(/\{/g) || []).length;
const closeBraces = (line.match(/\}/g) || []).length;
// Increment nesting
if (/\b(?:if|for|while|switch|catch)\s*\(/.test(line)) {
complexity += (1 + nestingLevel); // Add penalty for nesting
nestingLevel++;
}
// Logical operators add complexity
if (/\&\&|\|\|/.test(line)) {
complexity += 1;
}
// Adjust nesting level
nestingLevel += (openBraces - closeBraces);
nestingLevel = Math.max(0, nestingLevel);
});
return {
score: complexity,
severity: this.getComplexitySeverity(complexity)
};
}
/**
* Calculate Maintainability Index
* MI = 171 - 5.2 * ln(HV) - 0.23 * CC - 16.2 * ln(LOC)
* Simplified version using available metrics
*/
calculateMaintainabilityIndex(content) {
const loc = this.calculateLOC(content);
const cc = this.calculateCyclomaticComplexity(content);
const commentRatio = this.calculateCommentRatio(content);
// Simplified formula (0-100 scale)
let mi = 100;
mi -= (cc.total * 2); // Complexity penalty
mi -= (Math.log(loc.total) * 5); // Size penalty
mi += (commentRatio * 20); // Comment bonus
mi = Math.max(0, Math.min(100, Math.round(mi)));
return {
score: mi,
rating: mi >= 80 ? 'A' : mi >= 60 ? 'B' : mi >= 40 ? 'C' : 'D',
factors: {
linesOfCode: loc.total,
cyclomaticComplexity: cc.total,
commentRatio: Math.round(commentRatio * 100)
}
};
}
/**
* Calculate Halstead Metrics
* Measures program vocabulary and volume
*/
calculateHalsteadMetrics(content) {
// Operators
const operators = [
/\+(?!=)/g, /-(?!=)/g, /\*(?!=)/g, /\/(?!=)/g, /%/g,
/===/g, /!==?/g, /<=?/g, />=?/g,
/&&/g, /\|\|/g, /!/g,
/=/g, /\+=/g, /-=/g, /\*=/g, /\/=/g,
/\?/g, /:/g
];
// Operands (identifiers and literals)
const identifiers = content.match(/\b[a-zA-Z_$][a-zA-Z0-9_$]*\b/g) || [];
const literals = content.match(/\b\d+\b|'[^']*'|"[^"]*"|`[^`]*`/g) || [];
// Count unique and total
const uniqueOperators = new Set();
let totalOperators = 0;
operators.forEach(pattern => {
const matches = content.match(pattern);
if (matches) {
uniqueOperators.add(pattern.toString());
totalOperators += matches.length;
}
});
const uniqueOperands = new Set([...identifiers, ...literals]);
const totalOperands = identifiers.length + literals.length;
// Halstead metrics
const n1 = uniqueOperators.size;
const n2 = uniqueOperands.size;
const N1 = totalOperators;
const N2 = totalOperands;
const vocabulary = n1 + n2;
const length = N1 + N2;
const volume = length * Math.log2(vocabulary || 1);
const difficulty = (n1 / 2) * (N2 / (n2 || 1));
const effort = volume * difficulty;
return {
vocabulary,
length,
volume: Math.round(volume),
difficulty: Math.round(difficulty * 10) / 10,
effort: Math.round(effort),
estimatedBugs: Math.round(volume / 3000 * 100) / 100
};
}
/**
* Calculate Lines of Code
*/
calculateLOC(content) {
const lines = content.split('\n');
let total = lines.length;
let code = 0;
let comments = 0;
let blank = 0;
let inBlockComment = false;
lines.forEach(line => {
const trimmed = line.trim();
if (trimmed === '') {
blank++;
} else if (inBlockComment) {
comments++;
if (trimmed.includes('*/')) {
inBlockComment = false;
}
} else if (trimmed.startsWith('/*')) {
comments++;
inBlockComment = !trimmed.includes('*/');
} else if (trimmed.startsWith('//')) {
comments++;
} else {
code++;
}
});
return { total, code, comments, blank };
}
/**
* Calculate comment ratio
*/
calculateCommentRatio(content) {
const loc = this.calculateLOC(content);
return loc.code > 0 ? loc.comments / loc.code : 0;
}
/**
* Extract functions from content
*/
extractFunctions(content) {
const functions = [];
// Match function declarations
const functionPattern = /(?:function\s+(\w+)|(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?\([^)]*\)\s*=>)\s*\{/g;
let match;
while ((match = functionPattern.exec(content)) !== null) {
const name = match[1] || match[2];
const startIndex = match.index;
// Find function body (simple brace matching)
let braceCount = 0;
let endIndex = startIndex;
for (let i = startIndex; i < content.length; i++) {
if (content[i] === '{') braceCount++;
if (content[i] === '}') braceCount--;
if (braceCount === 0 && i > startIndex) {
endIndex = i;
break;
}
}
functions.push({
name,
body: content.substring(startIndex, endIndex)
});
}
return functions;
}
/**
* Get complexity severity level
*/
getComplexitySeverity(complexity) {
if (complexity > this.thresholds.complexity.high) return 'HIGH';
if (complexity > this.thresholds.complexity.medium) return 'MEDIUM';
if (complexity > this.thresholds.complexity.low) return 'LOW';
return 'MINIMAL';
}
/**
* Calculate overall rating
*/
calculateRating(metrics) {
const mi = metrics.maintainabilityIndex.score;
const cc = metrics.cyclomaticComplexity.total;
if (mi >= 80 && cc < 10) return 'A';
if (mi >= 60 && cc < 20) return 'B';
if (mi >= 40 && cc < 30) return 'C';
if (mi >= 20 && cc < 40) return 'D';
return 'F';
}
/**
* DEEP per-function analysis with exact metrics
*/
analyzeFunctionsDeep(functions, content) {
return functions.map(fn => {
const fnComplexity = this.calculateFunctionComplexity(fn.body);
const nestingDepth = this.calculateMaxNesting(fn.body);
const returnPoints = this.countReturnPoints(fn.body);
const paramCount = this.countParameters(fn.signature);
const cognitiveScore = this.calculateFunctionCognitiveLoad(fn.body);
return {
name: fn.name,
line: fn.startLine,
length: fn.lines,
cyclomaticComplexity: fnComplexity,
nestingDepth,
returnPoints,
parameterCount: paramCount,
cognitiveComplexity: cognitiveScore,
issues: this.identifyFunctionIssues(fn, fnComplexity, nestingDepth, returnPoints, paramCount),
severity: this.calculateFunctionSeverity(fnComplexity, nestingDepth, returnPoints, paramCount, fn.lines)
};
});
}
/**
* Extract functions with DEEP context (line numbers, signatures, full body)
*/
extractFunctionsDeep(content) {
const functions = [];
const lines = content.split('\n');
const patterns = [
/function\s+(\w+)\s*\(([^)]*)\)/, // function name(params)
/(?:const|let|var)\s+(\w+)\s*=\s*function\s*\(([^)]*)\)/, // const name = function(params)
/(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?\(([^)]*)\)\s*=>/, // const name = (params) =>
/(\w+)\s*\(([^)]*)\)\s*{/, // name(params) { - method syntax
/(?:async\s+)?(\w+)\s*\(([^)]*)\)\s*{/ // async name(params) {
];
let inFunction = false;
let braceCount = 0;
let currentFunction = null;
let functionBody = [];
lines.forEach((line, lineIndex) => {
// Check if line starts a function
for (const pattern of patterns) {
const match = pattern.exec(line);
if (match && !inFunction) {
inFunction = true;
braceCount = 0;
currentFunction = {
name: match[1] || 'anonymous',
signature: line.trim(),
startLine: lineIndex + 1,
body: '',
lines: 0
};
functionBody = [];
break;
}
}
if (inFunction) {
functionBody.push(line);
braceCount += (line.match(/{/g) || []).length;
braceCount -= (line.match(/}/g) || []).length;
if (braceCount === 0 && functionBody.length > 1) {
currentFunction.body = functionBody.join('\n');
currentFunction.lines = functionBody.length;
functions.push(currentFunction);
inFunction = false;
currentFunction = null;
functionBody = [];
}
}
});
return functions;
}
/**
* Calculate complexity for specific function
*/
calculateFunctionComplexity(functionBody) {
let complexity = 1;
const decisionPoints = [
/\bif\s*\(/g,
/\belse\s+if\s*\(/g,
/\bfor\s*\(/g,
/\bwhile\s*\(/g,
/\bcase\s+/g,
/\bcatch\s*\(/g,
/\&\&/g,
/\|\|/g,
/\?\s*[^:]+:/g,
/\bdo\s*\{/g
];
decisionPoints.forEach(pattern => {
const matches = functionBody.match(pattern);
if (matches) complexity += matches.length;
});
return complexity;
}
/**
* Calculate maximum nesting depth
*/
calculateMaxNesting(code) {
const lines = code.split('\n');
let currentDepth = 0;
let maxDepth = 0;
lines.forEach(line => {
// Increment depth for control structures
if (/\b(?:if|for|while|switch|try|catch|function|class)\s*[\({]/.test(line)) {
currentDepth++;
maxDepth = Math.max(maxDepth, currentDepth);
}
// Decrement for closing braces
const closeBraces = (line.match(/}/g) || []).length;
currentDepth = Math.max(0, currentDepth - closeBraces);
});
return maxDepth;
}
/**
* Count return points in function
*/
countReturnPoints(functionBody) {
const returns = functionBody.match(/\breturn\b/g);
return returns ? returns.length : 0;
}
/**
* Count function parameters
*/
countParameters(signature) {
const paramsMatch = signature.match(/\(([^)]*)\)/);
if (!paramsMatch || !paramsMatch[1].trim()) return 0;
const params = paramsMatch[1].split(',').filter(p => p.trim().length > 0);
return params.length;
}
/**
* Calculate cognitive load for specific function
*/
calculateFunctionCognitiveLoad(functionBody) {
let load = 0;
const lines = functionBody.split('\n');
let nestingLevel = 0;
lines.forEach(line => {
// Nesting structures increase cognitive load exponentially
if (/\b(?:if|for|while|switch)\s*\(/.test(line)) {
load += (1 + nestingLevel * 2); // Exponential penalty
nestingLevel++;
}
// Logical operators
const andOr = (line.match(/\&\&|\|\|/g) || []).length;
load += andOr;
// Callbacks and promises
if (/\.then\(|\.catch\(|callback/.test(line)) {
load += 2;
}
// Closing braces
const closeBraces = (line.match(/}/g) || []).length;
nestingLevel = Math.max(0, nestingLevel - closeBraces);
});
return load;
}
/**
* Identify specific function issues
*/
identifyFunctionIssues(fn, complexity, nesting, returns, params) {
const issues = [];
if (complexity > 20) {
issues.push({
type: 'HIGH_COMPLEXITY',
severity: 'CRITICAL',
message: `Cyclomatic complexity ${complexity} exceeds threshold (20)`,
line: fn.startLine
});
} else if (complexity > 10) {
issues.push({
type: 'MEDIUM_COMPLEXITY',
severity: 'HIGH',
message: `Cyclomatic complexity ${complexity} exceeds recommended threshold (10)`,
line: fn.startLine
});
}
if (nesting > 5) {
issues.push({
type: 'DEEP_NESTING',
severity: 'HIGH',
message: `Maximum nesting depth ${nesting} exceeds threshold (5)`,
line: fn.startLine
});
} else if (nesting > 3) {
issues.push({
type: 'MODERATE_NESTING',
severity: 'MEDIUM',
message: `Nesting depth ${nesting} should be reduced`,
line: fn.startLine
});
}
if (returns > 5) {
issues.push({
type: 'TOO_MANY_RETURNS',
severity: 'MEDIUM',
message: `Function has ${returns} return points (recommended: 1-3)`,
line: fn.startLine
});
}
if (params > 5) {
issues.push({
type: 'TOO_MANY_PARAMETERS',
severity: 'HIGH',
message: `Function has ${params} parameters (recommended: 5)`,
line: fn.startLine
});
} else if (params > 3) {
issues.push({
type: 'MANY_PARAMETERS',
severity: 'LOW',
message: `Consider reducing ${params} parameters`,
line: fn.startLine
});
}
if (fn.lines > 100) {
issues.push({
type: 'LONG_FUNCTION',
severity: 'HIGH',
message: `Function is ${fn.lines} lines (recommended: 50)`,
line: fn.startLine
});
} else if (fn.lines > 50) {
issues.push({
type: 'LONG_FUNCTION',
severity: 'MEDIUM',
message: `Function is ${fn.lines} lines, consider splitting`,
line: fn.startLine
});
}
return issues;
}
/**
* Calculate function severity level
*/
calculateFunctionSeverity(complexity, nesting, returns, params, length) {
let score = 0;
if (complexity > 20) score += 3;
else if (complexity > 10) score += 2;
else if (complexity > 5) score += 1;
if (nesting > 5) score += 3;
else if (nesting > 3) score += 2;
else if (nesting > 2) score += 1;
if (returns > 5) score += 2;
else if (returns > 3) score += 1;
if (params > 5) score += 2;
else if (params > 3) score += 1;
if (length > 100) score += 3;
else if (length > 50) score += 2;
if (score >= 8) return 'CRITICAL';
if (score >= 5) return 'HIGH';
if (score >= 3) return 'MEDIUM';
return 'LOW';
}
/**
* Analyze nesting depth distribution
*/
analyzeNestingDepth(content) {
const lines = content.split('\n');
let currentDepth = 0;
let maxDepth = 0;
const depthDistribution = {};
lines.forEach(line => {
if (/\b(?:if|for|while|switch|try|catch)\s*[\({]/.test(line)) {
currentDepth++;
maxDepth = Math.max(maxDepth, currentDepth);
depthDistribution[currentDepth] = (depthDistribution[currentDepth] || 0) + 1;
}
const closeBraces = (line.match(/}/g) || []).length;
currentDepth = Math.max(0, currentDepth - closeBraces);
});
return {
maxDepth,
distribution: depthDistribution,
averageDepth: Object.entries(depthDistribution).reduce((sum, [depth, count]) =>
sum + (parseInt(depth) * count), 0) / (Object.values(depthDistribution).reduce((s, c) => s + c, 0) || 1)
};
}
/**
* Analyze parameters across all functions
*/
analyzeParameters(functions) {
const paramCounts = functions.map(fn => this.countParameters(fn.signature));
const maxParams = Math.max(...paramCounts, 0);
const avgParams = paramCounts.length > 0 ?
paramCounts.reduce((sum, count) => sum + count, 0) / paramCounts.length : 0;
const highParamFunctions = functions.filter(fn =>
this.countParameters(fn.signature) > 5
);
return {
maxParameters: maxParams,
averageParameters: Math.round(avgParams * 10) / 10,
functionsWithManyParams: highParamFunctions.map(fn => ({
name: fn.name,
line: fn.startLine,
paramCount: this.countParameters(fn.signature)
}))
};
}
/**
* Analyze return points distribution
*/
analyzeReturnPoints(functions) {
const returnCounts = functions.map(fn => this.countReturnPoints(fn.body));
const maxReturns = Math.max(...returnCounts, 0);
const avgReturns = returnCounts.length > 0 ?
returnCounts.reduce((sum, count) => sum + count, 0) / returnCounts.length : 0;
const multiReturnFunctions = functions.filter(fn =>
this.countReturnPoints(fn.body) > 3
);
return {
maxReturnPoints: maxReturns,
averageReturnPoints: Math.round(avgReturns * 10) / 10,
functionsWithManyReturns: multiReturnFunctions.map(fn => ({
name: fn.name,
line: fn.startLine,
returnCount: this.countReturnPoints(fn.body)
}))
};
}
/**
* Calculate overall cognitive load
*/
calculateCognitiveLoad(content) {
let totalLoad = 0;
const functions = this.extractFunctionsDeep(content);
functions.forEach(fn => {
totalLoad += this.calculateFunctionCognitiveLoad(fn.body);
});
const avgLoad = functions.length > 0 ? totalLoad / functions.length : 0;
return {
total: totalLoad,
average: Math.round(avgLoad),
severity: avgLoad > 50 ? 'CRITICAL' : avgLoad > 30 ? 'HIGH' : avgLoad > 15 ? 'MEDIUM' : 'LOW'
};
}
/**
* Identify all complexity issues in file
*/
identifyComplexityIssues(metrics) {
const issues = [];
// Aggregate all function issues
if (metrics.functionMetrics) {
metrics.functionMetrics.forEach(fn => {
if (fn.issues && fn.issues.length > 0) {
issues.push(...fn.issues);
}
});
}
// File-level issues
if (metrics.cyclomaticComplexity.total > 100) {
issues.push({
type: 'FILE_TOO_COMPLEX',
severity: 'HIGH',
message: `File complexity ${metrics.cyclomaticComplexity.total} is very high`,
line: 1
});
}
if (metrics.nestingAnalysis.maxDepth > 6) {
issues.push({
type: 'FILE_DEEP_NESTING',
severity: 'HIGH',
message: `Maximum nesting depth ${metrics.nestingAnalysis.maxDepth} in file`,
line: 1
});
}
if (metrics.maintainabilityIndex.score < 40) {
issues.push({
type: 'LOW_MAINTAINABILITY',
severity: 'CRITICAL',
message: `Maintainability index ${metrics.maintainabilityIndex.score} is critically low`,
line: 1
});
}
return issues;
}
/**
* Generate complexity report with DEEP insights
*/
generateReport(allMetrics) {
const summary = {
totalFiles: allMetrics.length,
averageComplexity: 0,
averageMaintainability: 0,
ratingDistribution: { A: 0, B: 0, C: 0, D: 0, F: 0 },
mostComplex: [],
leastMaintainable: [],
worstFunctions: [],
deepestNesting: [],
mostParameters: [],
mostReturns: [],
highestCognitiveLoad: []
};
if (!allMetrics || allMetrics.length === 0) {
return {
average: 0,
total: 0,
fileCount: 0,
ratingDistribution: { A: 0, B: 0, C: 0, D: 0, F: 0 },
worstFunctions: [],
deepestNesting: [],
mostParameters: [],
mostReturns: [],
highestCognitiveLoad: []
};
}
let allFunctions = [];
let allIssues = [];
allMetrics.forEach(m => {
summary.averageComplexity += m.cyclomaticComplexity.total;
summary.averageMaintainability += m.maintainabilityIndex.score;
summary.ratingDistribution[m.rating]++;
// Collect all functions for ranking
if (m.functionMetrics) {
m.functionMetrics.forEach(fn => {
allFunctions.push({
...fn,
filePath: m.filePath
});
});
}
// Collect all issues
if (m.issues) {
allIssues.push(...m.issues.map(issue => ({
...issue,
filePath: m.filePath
})));
}
});
summary.averageComplexity = Math.round(summary.averageComplexity / allMetrics.length);
summary.averageMaintainability = Math.round(summary.averageMaintainability / allMetrics.length);
// Most complex files
summary.mostComplex = allMetrics
.sort((a, b) => b.cyclomaticComplexity.total - a.cyclomaticComplexity.total)
.slice(0, 10)
.map(m => ({
filePath: m.filePath,
complexity: m.cyclomaticComplexity.total,
functions: m.functionMetrics ? m.functionMetrics.length : 0
}));
// Least maintainable files
summary.leastMaintainable = allMetrics
.sort((a, b) => a.maintainabilityIndex.score - b.maintainabilityIndex.score)
.slice(0, 10)
.map(m => ({
filePath: m.filePath,
score: m.maintainabilityIndex.score,
rating: m.maintainabilityIndex.rating
}));
// Worst functions by complexity
summary.worstFunctions = allFunctions
.sort((a, b) => (b.cyclomaticComplexity || 0) - (a.cyclomaticComplexity || 0))
.slice(0, 20)
.map(fn => ({
name: fn.name,
filePath: fn.filePath,
line: fn.line,
cyclomaticComplexity: fn.cyclomaticComplexity,
nestingDepth: fn.nestingDepth,
cognitiveComplexity: fn.cognitiveComplexity,
severity: fn.severity
}));
// Deepest nesting
summary.deepestNesting = allFunctions
.sort((a, b) => (b.nestingDepth || 0) - (a.nestingDepth || 0))
.slice(0, 10)
.map(fn => ({
name: fn.name,
filePath: fn.filePath,
line: fn.line,
depth: fn.nestingDepth
}));
// Most parameters
summary.mostParameters = allFunctions
.sort((a, b) => (b.parameterCount || 0) - (a.parameterCount || 0))
.slice(0, 10)
.map(fn => ({
name: fn.name,
filePath: fn.filePath,
line: fn.line,
params: fn.parameterCount
}));
// Most return points
summary.mostReturns = allFunctions
.sort((a, b) => (b.returnPoints || 0) - (a.returnPoints || 0))
.slice(0, 10)
.map(fn => ({
name: fn.name,
filePath: fn.filePath,
line: fn.line,
returns: fn.returnPoints
}));
// Highest cognitive load
summary.highestCognitiveLoad = allFunctions
.sort((a, b) => (b.cognitiveComplexity || 0) - (a.cognitiveComplexity || 0))
.slice(0, 10)
.map(fn => ({
name: fn.name,
filePath: fn.filePath,
line: fn.line,
cognitiveLoad: fn.cognitiveComplexity
}));
// Issue summary
summary.totalIssues = allIssues.length;
summary.issuesBySeverity = {
CRITICAL: allIssues.filter(i => i.severity === 'CRITICAL').length,
HIGH: allIssues.filter(i => i.severity === 'HIGH').length,
MEDIUM: allIssues.filter(i => i.severity === 'MEDIUM').length,
LOW: allIssues.filter(i => i.severity === 'LOW').length
};
summary.topIssueTypes = this.aggregateIssueTypes(allIssues);
// Return in format expected by markdown reporter
return {
average: summary.averageComplexity,
total: allMetrics.reduce((sum, m) => sum + (m.cyclomaticComplexity?.total || 0), 0),
fileCount: allMetrics.length,
ratingDistribution: summary.ratingDistribution,
worstFunctions: summary.worstFunctions,
deepestNesting: summary.deepestNesting,
mostParameters: summary.mostParameters,
mostReturns: summary.mostReturns,
highestCognitiveLoad: summary.highestCognitiveLoad,
totalIssues: summary.totalIssues,
issuesBySeverity: summary.issuesBySeverity
};
}
/**
* Aggregate issue types for summary
*/
aggregateIssueTypes(allIssues) {
const typeCounts = {};
allIssues.forEach(issue => {
typeCounts[issue.type] = (typeCounts[issue.type] || 0) + 1;
});
return Object.entries(typeCounts)
.sort((a, b) => b[1] - a[1])
.slice(0, 10)
.map(([type, count]) => ({ type, count }));
}
/**
* Get parser used for analysis
*/
getParserUsed() {
return this.tokenizer.getParserUsed ? this.tokenizer.getParserUsed() : 'built-in';
}
// ============================================
// AST-BASED ANALYSIS METHODS
// These methods unlock the full power of Babel
// ============================================
/**
* Calculate Cyclomatic Complexity from AST
* More accurate than token-based counting
*/
calculateCyclomaticFromAST(ast) {
let total = 0;
const perFunction = [];
const traverse = (node, inFunction = null) => {
if (!node || typeof node !== 'object') return;
let localComplexity = 0;
// Decision points
if (node.type === 'IfStatement' || node.type === 'ConditionalExpression') {
localComplexity++;
total++;
}
if (node.type === 'ForStatement' || node.type === 'WhileStatement' ||
node.type === 'DoWhileStatement' || node.type === 'ForInStatement' ||
node.type === 'ForOfStatement') {
localComplexity++;
total++;
}
if (node.type === 'SwitchCase' && node.test !== null) {
localComplexity++;
total++;
}
if (node.type === 'CatchClause') {
localComplexity++;
total++;
}
if (node.type === 'LogicalExpression') {
localComplexity++;
total++;
}
// Track function context
let currentFunction = inFunction;
if (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' ||
node.type === 'ArrowFunctionExpression' || node.type === 'MethodDefinition') {
currentFunction = {
name: node.id?.name || node.key?.name || 'anonymous',
complexity: 1, // Base complexity
line: node.loc?.start?.line || 0
};
perFunction.push(currentFunction);
}
if (currentFunction && localComplexity > 0) {
currentFunction.complexity += localComplexity;
}
// Traverse children
for (const key in node) {
if (key === 'loc' || key === 'range' || key === 'start' || key === 'end') continue;
const child = node[key];
if (Array.isArray(child)) {
child.forEach(c => traverse(c, currentFunction));
} else if (child && typeof child === 'object') {
traverse(child, currentFunction);
}
}
};
traverse(ast);
return {
total: Math.max(total, 1),
average: perFunction.length > 0 ? total / perFunction.length : 1,
perFunction
};
}
/**
* Calculate Cognitive Complexity from AST
* Measures how hard code is to understand
*/
calculateCognitiveFromAST(ast) {
let complexity = 0;
let nestingLevel = 0;
const traverse = (node, nesting = 0) => {
if (!node || typeof node !== 'object') return;
// Increase complexity based on structure + nesting
if (node.type === 'IfStatement') {
complexity += (1 + nesting);
traverse(node.consequent, nesting + 1);
if (node.alternate) {
if (node.alternate.type === 'IfStatement') {
complexity += 1; // else if
}
traverse(node.alternate, nesting + 1);
}
return;
}
if (node.type === 'ForStatement' || node.type === 'WhileStatement' ||
node.type === 'DoWhileStatement' || node.type === 'ForInStatement' ||
node.type === 'ForOfStatement') {
complexity += (1 + nesting);
traverse(node.body, nesting + 1);
return;
}
if (node.type === 'SwitchStatement') {
complexity += (1 + nesting);
node.cases.forEach(c => traverse(c, nesting + 1));
return;
}
if (node.type === 'CatchClause') {
complexity += (1 + nesting);
traverse(node.body, nesting + 1);
return;
}
if (node.type === 'LogicalExpression') {
complexity += 1;
}
if (node.type === 'ConditionalExpression') {
complexity += (1 + nesting);
}
// Traverse children
for (const key in node) {
if (key === 'loc' || key === 'range' || key === 'start' || key === 'end') continue;
const child = node[key];
if (Array.isArray(child)) {
child.forEach(c => traverse(c, nesting));
} else if (child && typeof child === 'object') {
traverse(child, nesting);
}
}
};
traverse(ast);
return Math.max(complexity, 1);
}
/**
* Analyze functions from AST
* Extract detailed function metrics
*/
analyzeFunctionsFromAST(ast, content) {
const functions = [];
const traverse = (node) => {
if (!node || typeof node !== 'object') return;
if (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' ||
node.type === 'ArrowFunctionExpression') {
const funcInfo = {
name: node.id?.name || 'anonymous',
type: node.type,
async: node.async || false,
generator: node.generator || false,
params: node.params?.length || 0,
line: node.loc?.start?.line || 0,
endLine: node.loc?.end?.line || 0,
linesOfCode: (node.loc?.end?.line || 0) - (node.loc?.start?.line || 0) + 1,
returnPoints: this.countReturnsInNode(node.body),
complexity: this.calculateNodeComplexity(node.body)
};
functions.push(funcInfo);
}
if (node.type === 'MethodDefinition') {
const funcInfo = {
name: node.key?.name || 'method',
type: 'Method',
kind: node.kind, // get, set, constructor, method
static: node.static || false,
async: node.value?.async || false,
params: node.value?.params?.length || 0,
line: node.loc?.start?.line || 0,
endLine: node.loc?.end?.line || 0,
linesOfCode: (node.loc?.end?.line || 0) - (node.loc?.start?.line || 0) + 1,
returnPoints: this.countReturnsInNode(node.value?.body),
complexity: this.calculateNodeComplexity(node.value?.body)
};
functions.push(funcInfo);
}
// Traverse children
for (const key in node) {
if (key === 'loc' || key === 'range' || key === 'start' || key === 'end') continue;
const child = node[key];
if (Array.isArray(child)) {
child.forEach(traverse);
} else if (child && typeof child === 'object') {
traverse(child);
}
}
};
traverse(ast);
return functions;
}
/**
* Count return statements in a node
*/
countReturnsInNode(node) {
let count = 0;
const traverse = (n) => {
if (!n || typeof n !== 'object') return;
if (n.type === 'ReturnStatement') count++;
for (const key in n) {
if (key === 'loc' || key === 'range' || key === 'start' || key === 'end') continue;
const child = n[key];
if (Array.isArray(child)) {
child.forEach(traverse);
} else if (child && typeof child === 'object') {
traverse(child);
}
}
};
traverse(node);
return count;
}
/**
* Calculate complexity for a single node
*/
calculateNodeComplexity(node) {
let complexity = 1;
const traverse = (n) => {
if (!n || typeof n !== 'object') return;
if (n.type === 'IfStatement' || n.type === 'ForStatement' ||
n.type === 'WhileStatement' || n.type === 'SwitchCase' ||
n.type === 'CatchClause' || n.type === 'LogicalExpression') {
complexity++;
}
for (const key in n) {
if (key === 'loc' || key === 'range' || key === 'start' || key === 'end') continue;
const child = n[key];
if (Array.isArray(child)) {
child.forEach(traverse);
} else if (child && typeof child === 'object') {
traverse(child);
}
}
};
traverse(node);
return complexity;
}
/**
* Analyze nesting depth from AST
*/
analyzeNestingFromAST(ast) {
let maxDepth = 0;
const locations = [];
const traverse = (node, depth = 0) => {
if (!node || typeof node !== 'object') return;
if (node.type === 'IfStatement' || node.type === 'ForStatement' ||
node.type === 'WhileStatement' || node.type === 'SwitchStatement') {
const newDepth = depth + 1;
if (newDepth > maxDepth) {
maxDepth = newDepth;
if (maxDepth > 3) {
locations.push({
type: node.type,
depth: maxDepth,
line: node.loc?.start?.line || 0
});
}
}
for (const key in node) {
if (key === 'loc' || key === 'range' || key === 'start' || key === 'end') continue;
const child = node[key];
if (Array.isArray(child)) {
child.forEach(c => traverse(c, newDepth));
} else if (child && typeof child === 'object') {
traverse(child, newDepth);
}
}
return;
}
for (const key in node) {
if (key === 'loc' || key === 'range' || key === 'start' || key === 'end') continue;
const child = node[key];
if (Array.isArray(child)) {
child.forEach(c => traverse(c, depth));
} else if (child && typeof child === 'object') {
traverse(child, depth);
}
}
};
traverse(ast);
return {
maxDepth,
deeplyNested: locations.slice(0, 5)
};
}
/**
* Analyze parameters from AST
*/
analyzeParametersFromAST(ast) {
const functions = this.analyzeFunctionsFromAST(ast, '');
const longParams = functions.filter(f => f.params > 5);
return {
maxParams: functions.length > 0 ? Math.max(...functions.map(f => f.params)) : 0,
avgParams: functions.length > 0 ?
functions.reduce((sum, f) => sum + f.params, 0) / functions.length : 0,
longParameterLists: longParams.map(f => ({
name: f.name,
params: f.params,
line: f.line
}))
};
}
/**
* Analyze return points from AST
*/
analyzeReturnPointsFromAST(ast) {
const functions = this.analyzeFunctionsFromAST(ast, '');
const multiReturn = functions.filter(f => f.returnPoints > 3);
return {
maxReturns: functions.length > 0 ? Math.max(...functions.map(f => f.returnPoints)) : 0,
avgReturns: functions.length > 0 ?
functions.reduce((sum, f) => sum + f.returnPoints, 0) / functions.length : 0,
multipleReturnPoints: multiReturn.map(f => ({
name: f.name,
returns: f.returnPoints,
line: f.line
}))
};
}
/**
* Calculate cognitive load from AST
*/
calculateCognitiveLoadFromAST(ast) {
const nesting = this.analyzeNestingFromAST(ast);
const functions = this.analyzeFunctionsFromAST(ast, '');
const avgComplexity = functions.length > 0 ?
functions.reduce((sum, f) => sum + f.complexity, 0) / functions.length : 1;
return {
score: Math.round(avgComplexity * (1 + nesting.maxDepth * 0.5)),
factors: {
avgFunctionComplexity: avgComplexity.toFixed(2),
maxNestingDepth: nesting.maxDepth,
functionCount: functions.length
}
};
}
/**
* Calculate Halstead metrics from AST
*/
calculateHalsteadFromAST(ast) {
const operators = new Set();
const operands = new Set();
let operatorCount = 0;
let operandCount = 0;
const traverse = (node) => {
if (!node || typeof node !== 'object') return;
// Operators
if (node.type === 'BinaryExpression' || node.type === 'LogicalExpression' ||
node.type === 'UnaryExpression' || node.type === 'UpdateExpression' ||
node.type === 'AssignmentExpression') {
operators.add(node.operator);
operatorCount++;
}
// Operands
if (node.type === 'Identifier') {
operands.add(node.name);
operandCount++;
}
if (node.type === 'Literal' || node.type === 'NumericLiteral' ||
node.type === 'StringLiteral' || node.type === 'BooleanLiteral') {
operands.add(String(node.value));
operandCount++;
}
for (const key in node) {
if (key === 'loc' || key === 'range' || key === 'start' || key === 'end') continue;
const child = node[key];
if (Array.isArray(child)) {
child.forEach(traverse);
} else if (child && typeof child === 'object') {
traverse(child);
}
}
};
traverse(ast);
const n1 = operators.size;
const n2 = operands.size;
const N1 = operatorCount;
const N2 = operandCount;
const vocabulary = n1 + n2;
const length = N1 + N2;
const volume = length * Math.log2(vocabulary || 1);
return {
vocabulary,
length,
volume: Math.round(volume),
difficulty: (n1 / 2) * (N2 / (n2 || 1)),
effort: volume * ((n1 / 2) * (N2 / (n2 || 1)))
};
}
/**
* Detect modern JavaScript features from AST
*/
detectModernFeatures(ast) {
const features = {
asyncAwait: 0,
arrowFunctions: 0,
destructuring: 0,
spreadOperator: 0,
templateLiterals: 0,
classes: 0,
modules: 0,
optionalChaining: 0,
nullishCoalescing: 0
};
const traverse = (node) => {
if (!node || typeof node !== 'object') return;
if (node.async) features.asyncAwait++;
if (node.type === 'AwaitExpression') features.asyncAwait++;
if (node.type === 'ArrowFunctionExpression') features.arrowFunctions++;
if (node.type === 'ObjectPattern' || node.type === 'ArrayPattern') features.destructuring++;
if (node.type === 'SpreadElement' || node.type === 'RestElement') features.spreadOperator++;
if (node.type === 'TemplateLiteral') features.templateLiterals++;
if (node.type === 'ClassDeclaration' || node.type === 'ClassExpression') features.classes++;
if (node.type === 'ImportDeclaration' || node.type === 'ExportNamedDeclaration' ||
node.type === 'ExportDefaultDeclaration') features.modules++;
if (node.type === 'OptionalMemberExpression' || node.type === 'OptionalCallExpression') features.optionalChaining++;
if (node.type === 'LogicalExpression' && node.operator === '??') features.nullishCoalescing++;
for (const key in node) {
if (key === 'loc' || key === 'range' || key === 'start' || key === 'end') continue;
const child = node[key];
if (Array.isArray(child)) {
child.forEach(traverse);
} else if (child && typeof child === 'object') {
traverse(child);
}
}
};
traverse(ast);
return features;
}
}
module.exports = ComplexityAnalyzer;