| |
| |
| |
| |
|
|
|
|
| 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();
|
|
|
|
|
| const parserInfo = this.tokenizer.getParserInfo();
|
| if (!this._loggedParser) {
|
| console.log(`[COMPLEXITY] Using ${parserInfo.name} parser for accurate analysis`);
|
| this._loggedParser = true;
|
| }
|
| }
|
|
|
| |
| |
| |
| |
|
|
| analyze(filePath, content) {
|
|
|
| const langInfo = this.languageDetector.detectFromPath(filePath);
|
|
|
|
|
| const ast = this.tokenizer.parseToAST(content, filePath);
|
|
|
| let metrics;
|
|
|
| if (ast && this.tokenizer.hasExternalParser() && langInfo.language === 'javascript') {
|
|
|
| metrics = this.analyzeWithAST(filePath, content, ast, langInfo);
|
| } else {
|
|
|
| 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;
|
| }
|
|
|
| |
| |
| |
|
|
| 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'
|
| };
|
| }
|
|
|
| |
| |
|
|
| 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'
|
| };
|
| }
|
|
|
| |
| |
| |
|
|
| calculateCyclomaticComplexityFromTokens(codeTokens, langInfo = {language: 'javascript'}) {
|
| let complexity = 1;
|
|
|
|
|
| const config = langInfo.config || this.languageDetector.getConfig(langInfo.language);
|
| const decisionKeywords = config.keywords.control || ['if', 'for', 'while', 'case', 'catch', 'do'];
|
|
|
|
|
| complexity += this.tokenizer.countKeywords(codeTokens, decisionKeywords);
|
|
|
|
|
| const logicalOps = codeTokens.filter(t =>
|
| t.type === 'OPERATOR' && (t.value === '&&' || t.value === '||' || t.value === 'and' || t.value === 'or')
|
| );
|
| complexity += logicalOps.length;
|
|
|
|
|
| const ternaryOps = codeTokens.filter(t =>
|
| t.type === 'OPERATOR' && t.value === '?'
|
| );
|
| complexity += ternaryOps.length;
|
|
|
| return {
|
| total: complexity,
|
| average: complexity,
|
| perFunction: []
|
| };
|
| }
|
|
|
| |
| |
| |
|
|
| calculateCyclomaticComplexity(content) {
|
| 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 = content.match(pattern);
|
| if (matches) {
|
| complexity += matches.length;
|
| }
|
| });
|
|
|
|
|
| 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)
|
| };
|
| }
|
|
|
| |
| |
|
|
| calculateCognitiveComplexity(content) {
|
| let complexity = 0;
|
| const lines = content.split('\n');
|
| let nestingLevel = 0;
|
|
|
| lines.forEach(line => {
|
|
|
| const openBraces = (line.match(/\{/g) || []).length;
|
| const closeBraces = (line.match(/\}/g) || []).length;
|
|
|
|
|
| if (/\b(?:if|for|while|switch|catch)\s*\(/.test(line)) {
|
| complexity += (1 + nestingLevel);
|
| nestingLevel++;
|
| }
|
|
|
|
|
| if (/\&\&|\|\|/.test(line)) {
|
| complexity += 1;
|
| }
|
|
|
|
|
| nestingLevel += (openBraces - closeBraces);
|
| nestingLevel = Math.max(0, nestingLevel);
|
| });
|
|
|
| return {
|
| score: complexity,
|
| severity: this.getComplexitySeverity(complexity)
|
| };
|
| }
|
|
|
| |
| |
| |
| |
|
|
| calculateMaintainabilityIndex(content) {
|
| const loc = this.calculateLOC(content);
|
| const cc = this.calculateCyclomaticComplexity(content);
|
| const commentRatio = this.calculateCommentRatio(content);
|
|
|
|
|
| let mi = 100;
|
| mi -= (cc.total * 2);
|
| mi -= (Math.log(loc.total) * 5);
|
| mi += (commentRatio * 20);
|
|
|
| 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)
|
| }
|
| };
|
| }
|
|
|
| |
| |
| |
|
|
| calculateHalsteadMetrics(content) {
|
|
|
| const operators = [
|
| /\+(?!=)/g, /-(?!=)/g, /\*(?!=)/g, /\/(?!=)/g, /%/g,
|
| /===/g, /!==?/g, /<=?/g, />=?/g,
|
| /&&/g, /\|\|/g, /!/g,
|
| /=/g, /\+=/g, /-=/g, /\*=/g, /\/=/g,
|
| /\?/g, /:/g
|
| ];
|
|
|
|
|
| const identifiers = content.match(/\b[a-zA-Z_$][a-zA-Z0-9_$]*\b/g) || [];
|
| const literals = content.match(/\b\d+\b|'[^']*'|"[^"]*"|`[^`]*`/g) || [];
|
|
|
|
|
| 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;
|
|
|
|
|
| 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
|
| };
|
| }
|
|
|
| |
| |
|
|
| 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 };
|
| }
|
|
|
| |
| |
|
|
| calculateCommentRatio(content) {
|
| const loc = this.calculateLOC(content);
|
| return loc.code > 0 ? loc.comments / loc.code : 0;
|
| }
|
|
|
| |
| |
|
|
| extractFunctions(content) {
|
| const functions = [];
|
|
|
|
|
| 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;
|
|
|
|
|
| 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;
|
| }
|
|
|
| |
| |
|
|
| 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';
|
| }
|
|
|
| |
| |
|
|
| 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';
|
| }
|
|
|
| |
| |
|
|
| 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)
|
| };
|
| });
|
| }
|
|
|
| |
| |
|
|
| extractFunctionsDeep(content) {
|
| const functions = [];
|
| const lines = content.split('\n');
|
|
|
| const patterns = [
|
| /function\s+(\w+)\s*\(([^)]*)\)/,
|
| /(?:const|let|var)\s+(\w+)\s*=\s*function\s*\(([^)]*)\)/,
|
| /(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?\(([^)]*)\)\s*=>/,
|
| /(\w+)\s*\(([^)]*)\)\s*{/,
|
| /(?:async\s+)?(\w+)\s*\(([^)]*)\)\s*{/
|
| ];
|
|
|
| let inFunction = false;
|
| let braceCount = 0;
|
| let currentFunction = null;
|
| let functionBody = [];
|
|
|
| lines.forEach((line, lineIndex) => {
|
|
|
| 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;
|
| }
|
|
|
| |
| |
|
|
| 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;
|
| }
|
|
|
| |
| |
|
|
| calculateMaxNesting(code) {
|
| const lines = code.split('\n');
|
| let currentDepth = 0;
|
| let maxDepth = 0;
|
|
|
| lines.forEach(line => {
|
|
|
| if (/\b(?:if|for|while|switch|try|catch|function|class)\s*[\({]/.test(line)) {
|
| currentDepth++;
|
| maxDepth = Math.max(maxDepth, currentDepth);
|
| }
|
|
|
|
|
| const closeBraces = (line.match(/}/g) || []).length;
|
| currentDepth = Math.max(0, currentDepth - closeBraces);
|
| });
|
|
|
| return maxDepth;
|
| }
|
|
|
| |
| |
|
|
| countReturnPoints(functionBody) {
|
| const returns = functionBody.match(/\breturn\b/g);
|
| return returns ? returns.length : 0;
|
| }
|
|
|
| |
| |
|
|
| 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;
|
| }
|
|
|
| |
| |
|
|
| calculateFunctionCognitiveLoad(functionBody) {
|
| let load = 0;
|
| const lines = functionBody.split('\n');
|
| let nestingLevel = 0;
|
|
|
| lines.forEach(line => {
|
|
|
| if (/\b(?:if|for|while|switch)\s*\(/.test(line)) {
|
| load += (1 + nestingLevel * 2);
|
| nestingLevel++;
|
| }
|
|
|
|
|
| const andOr = (line.match(/\&\&|\|\|/g) || []).length;
|
| load += andOr;
|
|
|
|
|
| if (/\.then\(|\.catch\(|callback/.test(line)) {
|
| load += 2;
|
| }
|
|
|
|
|
| const closeBraces = (line.match(/}/g) || []).length;
|
| nestingLevel = Math.max(0, nestingLevel - closeBraces);
|
| });
|
|
|
| return load;
|
| }
|
|
|
| |
| |
|
|
| 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;
|
| }
|
|
|
| |
| |
|
|
| 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';
|
| }
|
|
|
| |
| |
|
|
| 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)
|
| };
|
| }
|
|
|
| |
| |
|
|
| 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)
|
| }))
|
| };
|
| }
|
|
|
| |
| |
|
|
| 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)
|
| }))
|
| };
|
| }
|
|
|
| |
| |
|
|
| 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'
|
| };
|
| }
|
|
|
| |
| |
|
|
| identifyComplexityIssues(metrics) {
|
| const issues = [];
|
|
|
|
|
| if (metrics.functionMetrics) {
|
| metrics.functionMetrics.forEach(fn => {
|
| if (fn.issues && fn.issues.length > 0) {
|
| issues.push(...fn.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;
|
| }
|
|
|
| |
| |
|
|
| 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]++;
|
|
|
|
|
| if (m.functionMetrics) {
|
| m.functionMetrics.forEach(fn => {
|
| allFunctions.push({
|
| ...fn,
|
| filePath: m.filePath
|
| });
|
| });
|
| }
|
|
|
|
|
| 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);
|
|
|
|
|
| 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
|
| }));
|
|
|
|
|
| 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
|
| }));
|
|
|
|
|
| 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
|
| }));
|
|
|
|
|
| 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
|
| }));
|
|
|
|
|
| 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
|
| }));
|
|
|
|
|
| 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
|
| }));
|
|
|
|
|
| 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
|
| }));
|
|
|
|
|
| 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 {
|
| 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
|
| };
|
| }
|
|
|
| |
| |
|
|
| 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 }));
|
| }
|
|
|
| |
| |
|
|
| getParserUsed() {
|
| return this.tokenizer.getParserUsed ? this.tokenizer.getParserUsed() : 'built-in';
|
| }
|
|
|
|
|
|
|
|
|
|
|
|
|
| |
| |
| |
|
|
| calculateCyclomaticFromAST(ast) {
|
| let total = 0;
|
| const perFunction = [];
|
|
|
| const traverse = (node, inFunction = null) => {
|
| if (!node || typeof node !== 'object') return;
|
|
|
| let localComplexity = 0;
|
|
|
|
|
| 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++;
|
| }
|
|
|
|
|
| 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,
|
| line: node.loc?.start?.line || 0
|
| };
|
| perFunction.push(currentFunction);
|
| }
|
|
|
| if (currentFunction && localComplexity > 0) {
|
| currentFunction.complexity += localComplexity;
|
| }
|
|
|
|
|
| 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
|
| };
|
| }
|
|
|
| |
| |
| |
|
|
| calculateCognitiveFromAST(ast) {
|
| let complexity = 0;
|
| let nestingLevel = 0;
|
|
|
| const traverse = (node, nesting = 0) => {
|
| if (!node || typeof node !== 'object') return;
|
|
|
|
|
| if (node.type === 'IfStatement') {
|
| complexity += (1 + nesting);
|
| traverse(node.consequent, nesting + 1);
|
| if (node.alternate) {
|
| if (node.alternate.type === 'IfStatement') {
|
| complexity += 1;
|
| }
|
| 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);
|
| }
|
|
|
|
|
| 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);
|
| }
|
|
|
| |
| |
| |
|
|
| 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,
|
| 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);
|
| }
|
|
|
|
|
| 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;
|
| }
|
|
|
| |
| |
|
|
| 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;
|
| }
|
|
|
| |
| |
|
|
| 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;
|
| }
|
|
|
| |
| |
|
|
| 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)
|
| };
|
| }
|
|
|
| |
| |
|
|
| 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
|
| }))
|
| };
|
| }
|
|
|
| |
| |
|
|
| 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
|
| }))
|
| };
|
| }
|
|
|
| |
| |
|
|
| 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
|
| }
|
| };
|
| }
|
|
|
| |
| |
|
|
| 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;
|
|
|
|
|
| if (node.type === 'BinaryExpression' || node.type === 'LogicalExpression' ||
|
| node.type === 'UnaryExpression' || node.type === 'UpdateExpression' ||
|
| node.type === 'AssignmentExpression') {
|
| operators.add(node.operator);
|
| operatorCount++;
|
| }
|
|
|
|
|
| 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)))
|
| };
|
| }
|
|
|
| |
| |
|
|
| 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;
|
|
|