/** * PatternAnalyzer - Detects common code patterns and anti-patterns * Multi-language support for JavaScript, Python, Java, C#, Go, PHP, Ruby, SQL */ const EnhancedTokenizer = require('./enhanced-tokenizer'); const LanguageDetector = require('./language-detector'); class PatternAnalyzer { constructor() { this.patterns = this.initializePatterns(); this.tokenizer = new EnhancedTokenizer(); this.languageDetector = new LanguageDetector(); } /** * Initialize pattern definitions */ initializePatterns() { return { // Good Patterns goodPatterns: [ { name: 'Dependency Injection', pattern: /constructor\s*\([^)]*\)\s*{\s*this\.\w+\s*=\s*\w+/, benefit: 'Improves testability and modularity', category: 'design' }, { name: 'Error Handling', pattern: /try\s*{[^}]*}\s*catch\s*\(/, benefit: 'Proper error handling', category: 'reliability' }, { name: 'Async/Await', pattern: /async\s+(?:function|\w+\s*\([^)]*\)\s*=>)/, benefit: 'Modern asynchronous code', category: 'modern' }, { name: 'Destructuring', pattern: /(?:const|let|var)\s*{\s*\w+/, benefit: 'Clean and readable code', category: 'modern' }, { name: 'Template Literals', pattern: /`[^`]*\$\{[^}]+\}[^`]*`/, benefit: 'Better string interpolation', category: 'modern' }, { name: 'Arrow Functions', pattern: /\([^)]*\)\s*=>/, benefit: 'Concise function syntax', category: 'modern' }, { name: 'Optional Chaining', pattern: /\?\./, benefit: 'Safe property access', category: 'modern' }, { name: 'Nullish Coalescing', pattern: /\?\?/, benefit: 'Better default value handling', category: 'modern' }, { name: 'Spread Operator', pattern: /\.\.\.\w+/, benefit: 'Clean array/object manipulation', category: 'modern' } ], // Anti-Patterns antiPatterns: [ { name: 'Callback Hell', pattern: /function\s*\([^)]*\)\s*{\s*\w+\([^,]*,\s*function\s*\([^)]*\)\s*{\s*\w+\([^,]*,\s*function/, issue: 'Deeply nested callbacks', suggestion: 'Use Promises or async/await', severity: 'HIGH', category: 'async' }, { name: 'Pyramid of Doom', pattern: /\s{8,}if\s*\([^)]*\)\s*{\s*\s{12,}if\s*\([^)]*\)\s*{/, issue: 'Deeply nested conditionals', suggestion: 'Extract functions or use early returns', severity: 'MEDIUM', category: 'complexity' }, { name: 'Magic Numbers', pattern: /[^a-zA-Z_]\d{2,}[^a-zA-Z_0-9]/, issue: 'Hardcoded numeric values', suggestion: 'Use named constants', severity: 'LOW', category: 'maintainability' }, { name: 'Global Variables', pattern: /^(?:var|let)\s+\w+\s*=/m, issue: 'Global scope pollution', suggestion: 'Use modules or encapsulation', severity: 'MEDIUM', category: 'architecture' }, { name: 'Empty Catch', pattern: /(?:catch|except)\s*(?:\([^)]*\))?\s*(?::|{)\s*(?:pass\s*)?(?:}|$)/gm, issue: 'Swallowing errors without handling (JS/Python/Java/C#/etc)', suggestion: 'Log or handle errors properly', severity: 'HIGH', category: 'reliability' }, { name: 'Comment-Only Catch', pattern: /(?:catch|except)\s*(?:\([^)]*\))?\s*(?::|{)\s*(?:\/\/|#)[^\n]*\n\s*(?:}|$)/gm, issue: 'Catch block only contains comments (multi-language)', suggestion: 'Add proper error handling or logging', severity: 'HIGH', category: 'reliability' }, { name: 'Console-Only Error Handling', pattern: /(?:catch|except)\s*(?:\([^)]*\))?\s*(?::|{)\s*(?:console\.(?:log|error|warn)|print|echo|println|NSLog|Debug\.WriteLine)\([^)]*\);\s*(?:}|$)/gm, issue: 'Error only logged without proper handling (multi-language)', suggestion: 'Add error recovery, user notification, or monitoring', severity: 'MEDIUM', category: 'reliability' }, { name: 'Silent Return in Catch', pattern: /(?:catch|except)\s*(?:\([^)]*\))?\s*(?::|{)\s*return\s*;?\s*(?:}|$)/gm, issue: 'Silently returning without error handling (multi-language)', suggestion: 'Log error or notify user before returning', severity: 'HIGH', category: 'reliability' }, { name: 'Var Usage', pattern: /\bvar\s+\w+/, issue: 'Using var instead of const/let', suggestion: 'Use const or let for block scoping', severity: 'LOW', category: 'modern' }, { name: 'Function Too Long', pattern: null, // Checked by line count issue: 'Function exceeds reasonable length', suggestion: 'Break into smaller functions', severity: 'MEDIUM', category: 'complexity' }, { name: 'Too Many Parameters', pattern: /function\s+\w+\s*\([^)]{80,}\)/, issue: 'Function has too many parameters', suggestion: 'Use object parameter or split function', severity: 'MEDIUM', category: 'design' }, { name: 'No Default Case', pattern: /switch\s*\([^)]+\)\s*{(?:(?!default:)[^}])*}/, issue: 'Switch without default case', suggestion: 'Add default case for safety', severity: 'LOW', category: 'reliability' }, { name: 'Direct DOM Manipulation', pattern: /document\.(?:getElementById|querySelector|createElement)/, issue: 'Direct DOM access in framework code', suggestion: 'Use framework methods', severity: 'MEDIUM', category: 'framework' }, { name: 'Emoji Usage', pattern: /[\u{1F300}-\u{1F9FF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}\u{1F000}-\u{1F02F}\u{1F0A0}-\u{1F0FF}\u{1F100}-\u{1F64F}\u{1F680}-\u{1F6FF}\u{1F900}-\u{1F9FF}\u{1FA00}-\u{1FA6F}\u{1FA70}-\u{1FAFF}\u{2300}-\u{23FF}\u{2B50}\u{2934}\u{2935}\u{3030}\u{303D}\u{3297}\u{3299}\u{FE0F}]/gu, issue: 'Emoji characters in source code', suggestion: 'Remove emojis - use text labels or icons instead', severity: 'MEDIUM', category: 'maintainability' }, // SQL Injection Risk { name: 'SQL Injection Risk', pattern: /(?:execute|query|exec|prepare)\s*\(\s*["`'](?:SELECT|INSERT|UPDATE|DELETE|DROP).*?\+.*?["`']\s*\)/gi, issue: 'Potential SQL injection vulnerability (string concatenation)', suggestion: 'Use parameterized queries or prepared statements', severity: 'CRITICAL', category: 'security' }, // Hardcoded Credentials { name: 'Hardcoded Credentials', pattern: /(?:password|passwd|pwd|secret|api_key|apikey|token|auth)\s*=\s*["`'][^"`'\s]{8,}["`']/gi, issue: 'Hardcoded credentials in source code', suggestion: 'Use environment variables or secure credential storage', severity: 'CRITICAL', category: 'security' }, // eval() Usage { name: 'Dangerous eval Usage', pattern: /\beval\s*\(/g, issue: 'Use of eval() is dangerous and can lead to code injection', suggestion: 'Use safer alternatives like JSON.parse() or Function constructor', severity: 'CRITICAL', category: 'security' }, // TODO in Production Code { name: 'TODO Comments', pattern: /(?:\/\/|\/\*|#|\-\-)\s*TODO:?/gi, issue: 'Unfinished work or technical debt', suggestion: 'Complete implementation or create task ticket', severity: 'LOW', category: 'maintainability' }, // FIXME in Production Code { name: 'FIXME Comments', pattern: /(?:\/\/|\/\*|#|\-\-)\s*FIXME:?/gi, issue: 'Known bugs or issues that need fixing', suggestion: 'Fix the issue or create bug ticket', severity: 'HIGH', category: 'reliability' }, // XXX/HACK Comments { name: 'HACK Comments', pattern: /(?:\/\/|\/\*|#|\-\-)\s*(?:XXX|HACK):?/gi, issue: 'Workarounds or hacky solutions', suggestion: 'Refactor to use proper solution', severity: 'MEDIUM', category: 'maintainability' }, // Debugger Statements { name: 'Debugger Statements', pattern: /\bdebugger\s*;/g, issue: 'Debug breakpoints left in production code', suggestion: 'Remove debugger statements', severity: 'HIGH', category: 'quality' }, // console.log in Production { name: 'Console Statements', pattern: /console\.(?:log|debug|info|warn)\s*\(/g, issue: 'Console statements may leak sensitive info or affect performance', suggestion: 'Remove or replace with proper logging framework', severity: 'LOW', category: 'quality' }, // Nested Try-Catch { name: 'Nested Try-Catch', pattern: /try\s*{[^}]*try\s*{/g, issue: 'Nested try-catch blocks increase complexity', suggestion: 'Refactor to single error handling layer', severity: 'MEDIUM', category: 'complexity' }, // Multiple Returns { name: 'Multiple Return Points', pattern: /return\s+[^;]+;(?:[^}]*return\s+[^;]+;){3,}/g, issue: 'Too many return statements in single function', suggestion: 'Simplify logic or use early returns pattern consistently', severity: 'LOW', category: 'complexity' }, // Deep Nesting (Generic) { name: 'Deep Nesting', pattern: /\s{16,}(?:if|for|while|switch)\s*\(/g, issue: 'Code nested too deeply (4+ levels)', suggestion: 'Extract nested logic into separate functions', severity: 'MEDIUM', category: 'complexity' }, // Large File Size (will be checked separately) { name: 'Large File', pattern: null, issue: 'File exceeds recommended size', suggestion: 'Split into smaller modules', severity: 'LOW', category: 'maintainability' }, // Python-specific { name: 'Python pickle Usage', pattern: /pickle\.loads?\s*\(/g, issue: 'Unsafe deserialization with pickle', suggestion: 'Use JSON or validate input', severity: 'CRITICAL', category: 'security', languages: ['python'] }, { name: 'Python exec/eval', pattern: /\b(?:exec|eval)\s*\(/g, issue: 'Dynamic code execution is dangerous', suggestion: 'Avoid exec/eval or sanitize input', severity: 'CRITICAL', category: 'security', languages: ['python'] }, // Java-specific { name: 'Java Deserialization', pattern: /ObjectInputStream|readObject/g, issue: 'Unsafe deserialization vulnerability', suggestion: 'Validate deserialized objects', severity: 'CRITICAL', category: 'security', languages: ['java'] }, { name: 'Java Reflection', pattern: /Class\.forName|Method\.invoke/g, issue: 'Reflection can bypass security', suggestion: 'Use compile-time alternatives', severity: 'HIGH', category: 'security', languages: ['java'] }, // PHP-specific { name: 'PHP shell_exec', pattern: /(?:shell_exec|exec|system|passthru|proc_open)\s*\(/g, issue: 'Command injection vulnerability', suggestion: 'Validate and escape all inputs', severity: 'CRITICAL', category: 'security', languages: ['php'] }, { name: 'PHP unserialize', pattern: /unserialize\s*\(/g, issue: 'Unsafe deserialization', suggestion: 'Use JSON instead', severity: 'CRITICAL', category: 'security', languages: ['php'] }, // Go-specific { name: 'Go Command Injection', pattern: /exec\.Command\s*\([^)]*\+/g, issue: 'Command injection risk', suggestion: 'Use exec.Command with separate arguments', severity: 'HIGH', category: 'security', languages: ['go'] }, // Ruby-specific { name: 'Ruby Marshal.load', pattern: /Marshal\.load/g, issue: 'Unsafe deserialization', suggestion: 'Use JSON instead', severity: 'CRITICAL', category: 'security', languages: ['ruby'] }, { name: 'Ruby Command Execution', pattern: /`[^`]*`|%x\{|system\s*\(|exec\s*\(/g, issue: 'Command injection risk', suggestion: 'Validate inputs', severity: 'HIGH', category: 'security', languages: ['ruby'] }, // SQL-specific { name: 'Dynamic SQL', pattern: /EXECUTE\s+[@\w]+|EXEC\s*\(|sp_executesql/gi, issue: 'Dynamic SQL can lead to injection', suggestion: 'Use parameterized queries', severity: 'HIGH', category: 'security', languages: ['sql'] }, { name: 'xp_cmdshell', pattern: /xp_cmdshell/gi, issue: 'OS command execution from SQL', suggestion: 'Avoid xp_cmdshell', severity: 'CRITICAL', category: 'security', languages: ['sql'] } ], // Code Smells codeSmells: [ { name: 'Duplicate Code', check: 'duplication', category: 'duplication' }, { name: 'Long Method', check: 'longMethod', category: 'complexity' }, { name: 'Large Class', check: 'largeClass', category: 'complexity' }, { name: 'Feature Envy', pattern: /this\.\w+\.\w+\.\w+\.\w+/, issue: 'Excessive chaining', category: 'coupling' }, { name: 'Data Clumps', check: 'repeatedParameters', category: 'design' } ] }; } /** * Analyze file for patterns */ analyze(filePath, content) { // Detect language const langInfo = this.languageDetector.detectFromPath(filePath); const findings = { filePath, language: langInfo.language, goodPatterns: this.detectGoodPatterns(content, langInfo.language), antiPatterns: this.detectAntiPatterns(content, langInfo.language), codeSmells: this.detectCodeSmells(content, langInfo.language), annotations: this.detectAnnotations(content, filePath), score: 0, recommendations: [] }; findings.score = this.calculateScore(findings); findings.recommendations = this.generateRecommendations(findings); return findings; } /** * Detect annotations (TODO/FIXME/BUG) using Tokenizer * 100% accurate - no false positives from strings or commented-out code */ detectAnnotations(content, filePath) { const tokens = this.tokenizer.tokenize(content, filePath); const annotations = this.tokenizer.findAnnotations(tokens); return annotations.map(ann => ({ type: ann.type, text: ann.text, line: ann.line, author: ann.author || 'Unknown', context: ann.context || '' })); } /** * Detect good patterns */ detectGoodPatterns(content, language = 'javascript') { const found = []; this.patterns.goodPatterns.forEach(pattern => { if (!pattern.pattern) return; // Filter language-specific patterns if (pattern.languages && !pattern.languages.includes(language)) { return; // Skip if not applicable to this language } const matches = content.match(pattern.pattern); if (matches) { found.push({ name: pattern.name, count: matches.length, benefit: pattern.benefit, category: pattern.category }); } }); return found; } /** * Detect anti-patterns */ detectAntiPatterns(content, language = 'javascript') { const found = []; this.patterns.antiPatterns.forEach(antiPattern => { if (!antiPattern.pattern) return; // Filter language-specific patterns if (antiPattern.languages && !antiPattern.languages.includes(language)) { return; // Skip if not applicable to this language } const matches = content.match(antiPattern.pattern); if (matches) { found.push({ name: antiPattern.name, count: matches.length, issue: antiPattern.issue, suggestion: antiPattern.suggestion, severity: antiPattern.severity, category: antiPattern.category }); } }); // Check for long functions const functions = this.extractFunctions(content); const longFunctions = functions.filter(f => f.lines > 50); if (longFunctions.length > 0) { found.push({ name: 'Function Too Long', count: longFunctions.length, issue: 'Functions exceed 50 lines', suggestion: 'Break into smaller functions', severity: 'MEDIUM', category: 'complexity' }); } // Check for large files const lines = content.split('\n').length; if (lines > 500) { found.push({ name: 'Large File', count: 1, issue: `File has ${lines} lines (recommended: < 500)`, suggestion: 'Split into smaller modules', severity: lines > 1000 ? 'HIGH' : 'MEDIUM', category: 'maintainability' }); } return found; } /** * Detect code smells */ detectCodeSmells(content, language = 'javascript') { const smells = []; // Feature Envy (excessive chaining) const chains = content.match(/this\.\w+\.\w+\.\w+\.\w+/g); if (chains && chains.length > 0) { smells.push({ name: 'Feature Envy', count: chains.length, issue: 'Excessive method chaining', category: 'coupling' }); } // Duplicate code (simple check for repeated lines) const lines = content.split('\n').filter(l => l.trim().length > 20); const duplicates = this.findDuplicateLines(lines); if (duplicates.length > 0) { smells.push({ name: 'Duplicate Code', count: duplicates.length, issue: 'Code duplication detected', category: 'duplication' }); } // Large class const classMatch = content.match(/class\s+\w+\s*{([^}]+)}/); if (classMatch) { const methods = (classMatch[1].match(/\w+\s*\([^)]*\)\s*{/g) || []).length; if (methods > 20) { smells.push({ name: 'Large Class', count: methods, issue: 'Class has too many methods', category: 'complexity' }); } } // Data clumps (repeated parameter patterns) const paramPatterns = {}; const funcMatches = content.match(/function\s+\w+\s*\(([^)]+)\)/g) || []; funcMatches.forEach(match => { const params = match.match(/\(([^)]+)\)/)[1]; paramPatterns[params] = (paramPatterns[params] || 0) + 1; }); Object.entries(paramPatterns).forEach(([params, count]) => { if (count > 2 && params.split(',').length > 2) { smells.push({ name: 'Data Clumps', count, issue: 'Same parameters repeated across functions', category: 'design' }); } }); return smells; } /** * Find duplicate lines */ findDuplicateLines(lines) { const lineCount = {}; const duplicates = []; lines.forEach(line => { const trimmed = line.trim(); if (trimmed.length > 20) { lineCount[trimmed] = (lineCount[trimmed] || 0) + 1; } }); Object.entries(lineCount).forEach(([line, count]) => { if (count > 1) { duplicates.push({ line, occurrences: count }); } }); return duplicates; } /** * Extract functions */ extractFunctions(content) { const functions = []; const lines = content.split('\n'); let inFunction = false; let braceCount = 0; let startLine = 0; let currentFunction = ''; lines.forEach((line, index) => { if (/(?:function\s+\w+|(?:const|let|var)\s+\w+\s*=\s*(?:async\s+)?\()/.test(line)) { inFunction = true; startLine = index; currentFunction = line.match(/(?:function\s+(\w+)|(?:const|let|var)\s+(\w+))/)?.[1] || 'anonymous'; } if (inFunction) { braceCount += (line.match(/{/g) || []).length; braceCount -= (line.match(/}/g) || []).length; if (braceCount === 0 && index > startLine) { functions.push({ name: currentFunction, lines: index - startLine + 1 }); inFunction = false; } } }); return functions; } /** * Calculate pattern score */ calculateScore(findings) { let score = 100; // Add points for good patterns findings.goodPatterns.forEach(gp => { score += gp.count * 2; }); // Deduct for anti-patterns findings.antiPatterns.forEach(ap => { if (ap.severity === 'HIGH') score -= ap.count * 10; else if (ap.severity === 'MEDIUM') score -= ap.count * 5; else score -= ap.count * 2; }); // Deduct for code smells findings.codeSmells.forEach(cs => { score -= cs.count * 3; }); return Math.max(0, Math.min(100, score)); } /** * Generate recommendations */ generateRecommendations(findings) { const recommendations = []; // Prioritize high severity anti-patterns const highSeverity = findings.antiPatterns.filter(ap => ap.severity === 'HIGH'); if (highSeverity.length > 0) { recommendations.push({ priority: 'HIGH', message: `Address ${highSeverity.length} high-severity anti-patterns`, actions: highSeverity.map(ap => ap.suggestion) }); } // Code smell recommendations if (findings.codeSmells.length > 3) { recommendations.push({ priority: 'MEDIUM', message: 'Refactor to address code smells', actions: findings.codeSmells.slice(0, 3).map(cs => `Fix ${cs.name}`) }); } // Suggest modern patterns const modernPatterns = ['Async/Await', 'Optional Chaining', 'Nullish Coalescing']; const missingModern = modernPatterns.filter(mp => !findings.goodPatterns.some(gp => gp.name === mp) ); if (missingModern.length > 0) { recommendations.push({ priority: 'LOW', message: 'Consider using modern JavaScript features', actions: missingModern.map(mp => `Adopt ${mp}`) }); } return recommendations; } /** * Generate pattern report */ generateReport(allFindings) { const summary = { totalFiles: allFindings.length, averageScore: 0, goodPatternUsage: {}, antiPatternCount: {}, codeSmellCount: {}, topIssues: [], bestPractices: [] }; allFindings.forEach(finding => { summary.averageScore += finding.score; // Count good patterns finding.goodPatterns.forEach(gp => { summary.goodPatternUsage[gp.name] = (summary.goodPatternUsage[gp.name] || 0) + gp.count; }); // Count anti-patterns finding.antiPatterns.forEach(ap => { summary.antiPatternCount[ap.name] = (summary.antiPatternCount[ap.name] || 0) + ap.count; }); // Count code smells finding.codeSmells.forEach(cs => { summary.codeSmellCount[cs.name] = (summary.codeSmellCount[cs.name] || 0) + cs.count; }); }); summary.averageScore = Math.round(summary.averageScore / allFindings.length); // Top issues summary.topIssues = Object.entries(summary.antiPatternCount) .sort((a, b) => b[1] - a[1]) .slice(0, 5) .map(([name, count]) => ({ name, count })); // Best practices summary.bestPractices = Object.entries(summary.goodPatternUsage) .sort((a, b) => b[1] - a[1]) .slice(0, 5) .map(([name, count]) => ({ name, count })); return summary; } } module.exports = PatternAnalyzer;