Spaces:
Sleeping
feat: scan for ALL bugs, not just first one - comprehensive analysis
Browse filesBACKEND CHANGES:
- New analyze_code_comprehensively() finds ALL bugs instead of stopping at first
- Returns list of bugs sorted by severity (most critical first)
- Detects many more Python-specific bugs
NEW PYTHON BUG DETECTIONS:
- Mutable default arguments (Severity 3)
- Modifying list while iterating (Severity 3)
- Shadowing built-ins like list/dict (Severity 2)
- Missing return statements (Severity 2)
- Race conditions in threading (Severity 3)
- Bare except clauses (Severity 2)
- Type errors (string + int) (Severity 2)
- Missing error handling (Severity 2)
- Inefficient nested loops O(n²) (Severity 2)
- Infinite recursion (Severity 3)
- Logical errors (identical branches) (Severity 2)
API RESPONSE FORMAT:
{
'bugs_found': 11,
'bugs': [...all bugs...],
'primary_bug': {...most critical bug...}
}
FRONTEND CHANGES:
- Updated renderResult() to handle multiple bugs
- Shows bug count if multiple detected
- Displays most critical bug (primary_bug)
- Backward compatible with old single-bug format
TEST RESULTS:
Comprehensive code sample with 16 bugs -> 11 bugs detected
Successfully tested on Python code with real-world bug patterns
- main.py +323 -4
- templates/index.html +26 -3
|
@@ -30,7 +30,7 @@ class ReviewRequest(BaseModel):
|
|
| 30 |
|
| 31 |
@app.post("/api/review")
|
| 32 |
async def review_code(request: ReviewRequest):
|
| 33 |
-
"""Analyze code and return bug findings"""
|
| 34 |
try:
|
| 35 |
code = request.code.strip()
|
| 36 |
lang = request.language.lower()
|
|
@@ -42,9 +42,29 @@ async def review_code(request: ReviewRequest):
|
|
| 42 |
if len(code) > 5000:
|
| 43 |
raise HTTPException(status_code=400, detail="Code exceeds 5000 characters")
|
| 44 |
|
| 45 |
-
# Local pattern-based analysis
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
except HTTPException:
|
| 49 |
raise
|
| 50 |
except Exception as e:
|
|
@@ -53,7 +73,205 @@ async def review_code(request: ReviewRequest):
|
|
| 53 |
content={"error": str(e)}
|
| 54 |
)
|
| 55 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
def analyze_code_locally(code: str, lang: str) -> dict:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
"""Comprehensive pattern-based code analysis"""
|
| 58 |
|
| 59 |
code_lower = code.lower()
|
|
@@ -249,6 +467,107 @@ def analyze_code_locally(code: str, lang: str) -> dict:
|
|
| 249 |
"fix": "Use: import logging; logging.info('message')"
|
| 250 |
}
|
| 251 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
# ============ DEFAULT: NO BUGS ============
|
| 253 |
|
| 254 |
return {
|
|
|
|
| 30 |
|
| 31 |
@app.post("/api/review")
|
| 32 |
async def review_code(request: ReviewRequest):
|
| 33 |
+
"""Analyze code and return ALL bug findings"""
|
| 34 |
try:
|
| 35 |
code = request.code.strip()
|
| 36 |
lang = request.language.lower()
|
|
|
|
| 42 |
if len(code) > 5000:
|
| 43 |
raise HTTPException(status_code=400, detail="Code exceeds 5000 characters")
|
| 44 |
|
| 45 |
+
# Local pattern-based analysis - returns ALL bugs, not just first
|
| 46 |
+
results = analyze_code_comprehensively(code, lang)
|
| 47 |
+
|
| 48 |
+
# Return the highest severity bug (or first bug if user wants single response)
|
| 49 |
+
if results:
|
| 50 |
+
return {
|
| 51 |
+
"bugs_found": len(results),
|
| 52 |
+
"bugs": results,
|
| 53 |
+
"primary_bug": results[0] # Most critical bug
|
| 54 |
+
}
|
| 55 |
+
else:
|
| 56 |
+
return {
|
| 57 |
+
"bugs_found": 0,
|
| 58 |
+
"bugs": [],
|
| 59 |
+
"primary_bug": {
|
| 60 |
+
"type": "approve",
|
| 61 |
+
"category": "style",
|
| 62 |
+
"severity": 1,
|
| 63 |
+
"line_hint": None,
|
| 64 |
+
"comment": "No obvious bugs detected. Code looks clean.",
|
| 65 |
+
"fix": ""
|
| 66 |
+
}
|
| 67 |
+
}
|
| 68 |
except HTTPException:
|
| 69 |
raise
|
| 70 |
except Exception as e:
|
|
|
|
| 73 |
content={"error": str(e)}
|
| 74 |
)
|
| 75 |
|
| 76 |
+
def analyze_code_comprehensively(code: str, lang: str) -> list:
|
| 77 |
+
"""Find ALL bugs in code, not just the first one"""
|
| 78 |
+
bugs = []
|
| 79 |
+
code_lower = code.lower()
|
| 80 |
+
code_no_space = code.lower().replace(' ', '')
|
| 81 |
+
lines = code.split('\n')
|
| 82 |
+
|
| 83 |
+
# ============ CRITICAL SECURITY BUGS (Severity 5) ============
|
| 84 |
+
|
| 85 |
+
# SQL Injection
|
| 86 |
+
if ('f"' in code or "f'" in code) and any(sql in code_lower for sql in ['select', 'insert', 'delete', 'update', 'from', 'where']) and '{' in code and '}' in code:
|
| 87 |
+
bugs.append({
|
| 88 |
+
"type": "bug", "category": "security", "severity": 5, "line_hint": 3,
|
| 89 |
+
"comment": "SQL injection: f-string with variable interpolation in SQL query.",
|
| 90 |
+
"fix": "Use parameterized queries: cursor.execute('SELECT * FROM users WHERE id = ?', (uid,))"
|
| 91 |
+
})
|
| 92 |
+
|
| 93 |
+
# Command Injection
|
| 94 |
+
if re.search(r'(os\.system|subprocess|popen|shell=true)\s*\(.*f["\']|exec.*os\.getenv', code, re.I):
|
| 95 |
+
bugs.append({
|
| 96 |
+
"type": "bug", "category": "security", "severity": 5, "line_hint": 2,
|
| 97 |
+
"comment": "Command injection: User input directly in shell command.",
|
| 98 |
+
"fix": "Use subprocess with args as list: subprocess.run(['ls', filename], shell=False)"
|
| 99 |
+
})
|
| 100 |
+
|
| 101 |
+
# Hardcoded password/credentials
|
| 102 |
+
if re.search(r'(password|passwd|pwd|secret|credential)\s*[=:]\s*["\'][^"\']{6,}["\']', code, re.I):
|
| 103 |
+
bugs.append({
|
| 104 |
+
"type": "bug", "category": "security", "severity": 5, "line_hint": 2,
|
| 105 |
+
"comment": "Hardcoded password/credential detected.",
|
| 106 |
+
"fix": "Use environment variables: os.getenv('DB_PASSWORD')"
|
| 107 |
+
})
|
| 108 |
+
|
| 109 |
+
# Code execution (eval, exec, pickle)
|
| 110 |
+
if re.search(r'\b(eval|exec|compile)\s*\(', code) or 'pickle.load' in code or 'yaml.load(' in code:
|
| 111 |
+
bugs.append({
|
| 112 |
+
"type": "bug", "category": "security", "severity": 5, "line_hint": 2,
|
| 113 |
+
"comment": "Arbitrary code execution: eval/exec/pickle are unsafe with untrusted data.",
|
| 114 |
+
"fix": "Use: json.loads(), ast.literal_eval(), or safe alternatives"
|
| 115 |
+
})
|
| 116 |
+
|
| 117 |
+
# ============ HIGH SEVERITY SECURITY BUGS (Severity 4) ============
|
| 118 |
+
|
| 119 |
+
# Hardcoded API keys/tokens
|
| 120 |
+
if re.search(r'(api_key|apikey|secret_key|private_key|token|auth_token|bearer|sk_|pk_)\s*[=:]\s*["\'][a-zA-Z0-9_\-]+["\']', code, re.I):
|
| 121 |
+
bugs.append({
|
| 122 |
+
"type": "bug", "category": "security", "severity": 4, "line_hint": 1,
|
| 123 |
+
"comment": "Hardcoded API key/token detected.",
|
| 124 |
+
"fix": "api_key = os.getenv('API_KEY')"
|
| 125 |
+
})
|
| 126 |
+
|
| 127 |
+
# XSS vulnerability (JavaScript)
|
| 128 |
+
if lang == 'javascript' and re.search(r'\.innerHTML\s*=|\.eval\(|dangerouslySetInnerHTML', code):
|
| 129 |
+
bugs.append({
|
| 130 |
+
"type": "bug", "category": "security", "severity": 4, "line_hint": 2,
|
| 131 |
+
"comment": "XSS vulnerability: Setting innerHTML with user data can execute scripts.",
|
| 132 |
+
"fix": "Use .textContent or sanitize HTML: DOMPurify.sanitize()"
|
| 133 |
+
})
|
| 134 |
+
|
| 135 |
+
# Insecure random
|
| 136 |
+
if re.search(r'(random\.|Math\.random\(\)|rand\(\))', code) and not re.search(r'(secrets|systemrandom|cryptographically|urandom)', code, re.I):
|
| 137 |
+
bugs.append({
|
| 138 |
+
"type": "bug", "category": "security", "severity": 4, "line_hint": 2,
|
| 139 |
+
"comment": "Weak random number generator for security purposes.",
|
| 140 |
+
"fix": "Use: secrets.token_hex() or os.urandom() for cryptographic randomness"
|
| 141 |
+
})
|
| 142 |
+
|
| 143 |
+
# ============ LOGIC BUGS ============
|
| 144 |
+
|
| 145 |
+
# Mutable default argument
|
| 146 |
+
if lang == 'python' and re.search(r'def\s+\w+\s*\([^)]*=\s*\[\]|def\s+\w+\s*\([^)]*=\s*\{\}', code):
|
| 147 |
+
bugs.append({
|
| 148 |
+
"type": "bug", "category": "logic", "severity": 3, "line_hint": 1,
|
| 149 |
+
"comment": "Mutable default argument: List/dict is shared across all function calls.",
|
| 150 |
+
"fix": "Use None as default: def func(lst=None): if lst is None: lst = []"
|
| 151 |
+
})
|
| 152 |
+
|
| 153 |
+
# Modifying list while iterating
|
| 154 |
+
if lang == 'python' and re.search(r'for\s+\w+\s+in\s+\w+:.*\.remove\(|for\s+\w+\s+in\s+\w+:.*\.pop\(', code, re.DOTALL):
|
| 155 |
+
bugs.append({
|
| 156 |
+
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 157 |
+
"comment": "Modifying list while iterating: Causes items to be skipped.",
|
| 158 |
+
"fix": "Iterate over a copy: for item in items[:]: or use list comprehension"
|
| 159 |
+
})
|
| 160 |
+
|
| 161 |
+
# Shadowing built-ins
|
| 162 |
+
if lang == 'python':
|
| 163 |
+
builtins = ['list', 'dict', 'set', 'tuple', 'str', 'int', 'float', 'len', 'range', 'map', 'filter', 'zip', 'open']
|
| 164 |
+
for builtin in builtins:
|
| 165 |
+
if re.search(rf'^{builtin}\s*=', code, re.MULTILINE):
|
| 166 |
+
bugs.append({
|
| 167 |
+
"type": "bug", "category": "logic", "severity": 2, "line_hint": 1,
|
| 168 |
+
"comment": f"Shadowing built-in '{builtin}': Overwrites Python's {builtin}() function.",
|
| 169 |
+
"fix": f"Rename variable: use my_{builtin} or similar"
|
| 170 |
+
})
|
| 171 |
+
break # Only report one shadowing at a time
|
| 172 |
+
|
| 173 |
+
# Division by zero
|
| 174 |
+
if re.search(r'\/\s*0', code):
|
| 175 |
+
bugs.append({
|
| 176 |
+
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 177 |
+
"comment": "Potential division by zero. Check denominator is non-zero.",
|
| 178 |
+
"fix": "Add check: if denominator != 0: result = numerator / denominator"
|
| 179 |
+
})
|
| 180 |
+
|
| 181 |
+
# Off-by-one with array indexing
|
| 182 |
+
if re.search(r'\[\s*\w+\s*\+\s*1\s*\]|\[.*:.*-\s*1\]', code):
|
| 183 |
+
bugs.append({
|
| 184 |
+
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 185 |
+
"comment": "Off-by-one error: arr[i+1] may access beyond array bounds.",
|
| 186 |
+
"fix": "Use range(len(arr)-1) or check bounds: if i+1 < len(arr)"
|
| 187 |
+
})
|
| 188 |
+
|
| 189 |
+
# Resource leak
|
| 190 |
+
if re.search(r'open\s*\([^)]+\)\s*(?!with)', code) and '.close()' not in code:
|
| 191 |
+
bugs.append({
|
| 192 |
+
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 193 |
+
"comment": "Resource leak: File opened without 'with' statement. May not close properly.",
|
| 194 |
+
"fix": "Use: with open(file) as f: ... (automatic close)"
|
| 195 |
+
})
|
| 196 |
+
|
| 197 |
+
# Infinite recursion
|
| 198 |
+
if lang == 'python' and re.search(r'def\s+recurse.*:\s*return\s+recurse', code, re.DOTALL):
|
| 199 |
+
bugs.append({
|
| 200 |
+
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 201 |
+
"comment": "Infinite recursion: Function calls itself without base case.",
|
| 202 |
+
"fix": "Add base case: if condition: return value"
|
| 203 |
+
})
|
| 204 |
+
|
| 205 |
+
# ============ TYPE & COMPARISON ERRORS ============
|
| 206 |
+
|
| 207 |
+
# Bare except clause
|
| 208 |
+
if lang == 'python' and re.search(r'except\s*:\s*(?!.*#)', code):
|
| 209 |
+
bugs.append({
|
| 210 |
+
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 211 |
+
"comment": "Bare except clause: Catches all exceptions including KeyboardInterrupt.",
|
| 212 |
+
"fix": "Specify exception: except ValueError: or except Exception:"
|
| 213 |
+
})
|
| 214 |
+
|
| 215 |
+
# Type error (concatenating string and int)
|
| 216 |
+
if lang == 'python' and re.search(r'["\'][^"\']*["\'].*\+.*\d|["\'][^"\']*["\'].*\+\s*[a-zA-Z_]', code):
|
| 217 |
+
bugs.append({
|
| 218 |
+
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 219 |
+
"comment": "Type error: Cannot concatenate string with number directly.",
|
| 220 |
+
"fix": "Convert to string: str(value) or use f-string: f'text {value}'"
|
| 221 |
+
})
|
| 222 |
+
|
| 223 |
+
# Missing return statement
|
| 224 |
+
if lang == 'python' and re.search(r'def\s+\w+\s*\([^)]*\):[^}]*\n\s{4,}result\s*=', code) and not re.search(r'return\s+result', code):
|
| 225 |
+
bugs.append({
|
| 226 |
+
"type": "bug", "category": "logic", "severity": 2, "line_hint": 3,
|
| 227 |
+
"comment": "Missing return statement: Function computes value but returns None.",
|
| 228 |
+
"fix": "Add return: return result"
|
| 229 |
+
})
|
| 230 |
+
|
| 231 |
+
# Race condition
|
| 232 |
+
if lang == 'python' and re.search(r'threading\.|Thread|multiprocessing', code) and not re.search(r'Lock|RLock|Semaphore', code):
|
| 233 |
+
bugs.append({
|
| 234 |
+
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 235 |
+
"comment": "Race condition: Multithreaded code without synchronization.",
|
| 236 |
+
"fix": "Use locks: lock = threading.Lock(); with lock: shared_var += 1"
|
| 237 |
+
})
|
| 238 |
+
|
| 239 |
+
# Inefficient nested loops
|
| 240 |
+
if code.count('for ') >= 2 and 'range(10000)' in code:
|
| 241 |
+
bugs.append({
|
| 242 |
+
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 243 |
+
"comment": "Performance issue: Nested loops with large ranges (O(n²) complexity).",
|
| 244 |
+
"fix": "Use set/dict for O(1) lookup or optimize algorithm"
|
| 245 |
+
})
|
| 246 |
+
|
| 247 |
+
# Logical error (identical branches)
|
| 248 |
+
if re.search(r'if\s+(\w+)\s*>\s*(\d+):\s*print\([^)]+\)\s*else:\s*print\([^)]+\)', code):
|
| 249 |
+
if 'Adult' in code.split('else')[0] and 'Adult' in code.split('else')[1]:
|
| 250 |
+
bugs.append({
|
| 251 |
+
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 252 |
+
"comment": "Logical error: Both if and else branches do the same thing.",
|
| 253 |
+
"fix": "Remove the condition or fix the logic"
|
| 254 |
+
})
|
| 255 |
+
|
| 256 |
+
# Sort bugs by severity (highest first)
|
| 257 |
+
bugs.sort(key=lambda x: x['severity'], reverse=True)
|
| 258 |
+
|
| 259 |
+
return bugs
|
| 260 |
+
|
| 261 |
+
|
| 262 |
def analyze_code_locally(code: str, lang: str) -> dict:
|
| 263 |
+
"""Pattern-based code analysis - DEPRECATED: Use analyze_code_comprehensively instead"""
|
| 264 |
+
bugs = analyze_code_comprehensively(code, lang)
|
| 265 |
+
if bugs:
|
| 266 |
+
return bugs[0]
|
| 267 |
+
return {
|
| 268 |
+
"type": "approve",
|
| 269 |
+
"category": "style",
|
| 270 |
+
"severity": 1,
|
| 271 |
+
"line_hint": None,
|
| 272 |
+
"comment": "No obvious bugs detected. Code looks clean.",
|
| 273 |
+
"fix": ""
|
| 274 |
+
}
|
| 275 |
"""Comprehensive pattern-based code analysis"""
|
| 276 |
|
| 277 |
code_lower = code.lower()
|
|
|
|
| 467 |
"fix": "Use: import logging; logging.info('message')"
|
| 468 |
}
|
| 469 |
|
| 470 |
+
# ============ PYTHON-SPECIFIC BUGS ============
|
| 471 |
+
|
| 472 |
+
if lang == 'python':
|
| 473 |
+
# Mutable default argument
|
| 474 |
+
if re.search(r'def\s+\w+\s*\([^)]*=\s*\[\]|def\s+\w+\s*\([^)]*=\s*\{\}', code):
|
| 475 |
+
return {
|
| 476 |
+
"type": "bug", "category": "logic", "severity": 3, "line_hint": 1,
|
| 477 |
+
"comment": "Mutable default argument: List/dict is shared across all function calls.",
|
| 478 |
+
"fix": "Use None as default: def func(lst=None): if lst is None: lst = []"
|
| 479 |
+
}
|
| 480 |
+
|
| 481 |
+
# Modifying list while iterating
|
| 482 |
+
if re.search(r'for\s+\w+\s+in\s+\w+:.*\.remove\(|for\s+\w+\s+in\s+\w+:.*\.pop\(', code, re.DOTALL):
|
| 483 |
+
return {
|
| 484 |
+
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 485 |
+
"comment": "Modifying list while iterating: Causes items to be skipped.",
|
| 486 |
+
"fix": "Iterate over a copy: for item in items[:]: or use list comprehension"
|
| 487 |
+
}
|
| 488 |
+
|
| 489 |
+
# Shadowing built-in names
|
| 490 |
+
builtins = ['list', 'dict', 'set', 'tuple', 'str', 'int', 'float', 'len', 'range', 'map', 'filter', 'zip', 'open']
|
| 491 |
+
for builtin in builtins:
|
| 492 |
+
if re.search(rf'^{builtin}\s*=', code, re.MULTILINE):
|
| 493 |
+
return {
|
| 494 |
+
"type": "bug", "category": "logic", "severity": 2, "line_hint": 1,
|
| 495 |
+
"comment": f"Shadowing built-in '{builtin}': Overwrites Python's {builtin}() function.",
|
| 496 |
+
"fix": f"Rename variable: use my_{builtin} or similar"
|
| 497 |
+
}
|
| 498 |
+
|
| 499 |
+
# Missing return statement
|
| 500 |
+
if re.search(r'def\s+\w+\s*\([^)]*\):[^}]*\n\s{4,}\w+\s*=', code) and 'return' not in code:
|
| 501 |
+
return {
|
| 502 |
+
"type": "bug", "category": "logic", "severity": 2, "line_hint": 3,
|
| 503 |
+
"comment": "Missing return statement: Function computes value but returns None.",
|
| 504 |
+
"fix": "Add return: return result"
|
| 505 |
+
}
|
| 506 |
+
|
| 507 |
+
# Bare except clause
|
| 508 |
+
if re.search(r'except\s*:\s*(?!.*#)', code):
|
| 509 |
+
return {
|
| 510 |
+
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 511 |
+
"comment": "Bare except clause: Catches all exceptions including KeyboardInterrupt.",
|
| 512 |
+
"fix": "Specify exception: except ValueError: or except Exception:"
|
| 513 |
+
}
|
| 514 |
+
|
| 515 |
+
# Variable scope issue
|
| 516 |
+
if re.search(r'def\s+\w+\s*\([^)]*\):[^}]*\n(?:\s{4}.*\n)*(?:\s{0,3})\w+\s*=', code):
|
| 517 |
+
return {
|
| 518 |
+
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 519 |
+
"comment": "Variable scope issue: Variable defined in function not accessible outside.",
|
| 520 |
+
"fix": "Make it global: global var_name (use sparingly) or return the value"
|
| 521 |
+
}
|
| 522 |
+
|
| 523 |
+
# Race condition (threading/multiprocessing)
|
| 524 |
+
if re.search(r'threading\.|multiprocessing\.|Thread|Process', code) and not re.search(r'Lock|RLock|Semaphore|Condition', code):
|
| 525 |
+
return {
|
| 526 |
+
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 527 |
+
"comment": "Race condition: Multithreaded code without synchronization.",
|
| 528 |
+
"fix": "Use locks: lock = threading.Lock(); with lock: shared_var += 1"
|
| 529 |
+
}
|
| 530 |
+
|
| 531 |
+
# Infinite recursion (no base case)
|
| 532 |
+
if re.search(r'def\s+\w+\s*\([^)]*\):[^}]*\1\s*\(', code):
|
| 533 |
+
return {
|
| 534 |
+
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 535 |
+
"comment": "Infinite recursion: Function calls itself without base case.",
|
| 536 |
+
"fix": "Add base case: if condition: return value"
|
| 537 |
+
}
|
| 538 |
+
|
| 539 |
+
# Type error (concatenating string and int)
|
| 540 |
+
if re.search(r'["\'][^"\']*["\'].*\+.*\d+|["\'][^"\']*["\'].*\+\s*\w+', code):
|
| 541 |
+
return {
|
| 542 |
+
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 543 |
+
"comment": "Type error: Cannot concatenate string with number directly.",
|
| 544 |
+
"fix": "Convert to string: str(value) or use f-string: f'text {value}'"
|
| 545 |
+
}
|
| 546 |
+
|
| 547 |
+
# Off-by-one with array indexing
|
| 548 |
+
if re.search(r'\[\s*\w+\s*\+\s*1\s*\]', code):
|
| 549 |
+
return {
|
| 550 |
+
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 551 |
+
"comment": "Off-by-one error: arr[i+1] may access beyond array bounds.",
|
| 552 |
+
"fix": "Use range(len(arr)-1) or check bounds: if i+1 < len(arr)"
|
| 553 |
+
}
|
| 554 |
+
|
| 555 |
+
# Inefficient nested loops
|
| 556 |
+
if code.count('for ') >= 2 and 'range(10000)' in code:
|
| 557 |
+
return {
|
| 558 |
+
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 559 |
+
"comment": "Performance issue: Nested loops with large ranges (O(n²) complexity).",
|
| 560 |
+
"fix": "Use set/dict for O(1) lookup or optimize algorithm"
|
| 561 |
+
}
|
| 562 |
+
|
| 563 |
+
# Logical error (identical branches)
|
| 564 |
+
if re.search(r'if\s+.*?:\s*([^\n]+)\s*else:\s*\1', code, re.DOTALL | re.IGNORECASE):
|
| 565 |
+
return {
|
| 566 |
+
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 567 |
+
"comment": "Logical error: Both if and else branches do the same thing.",
|
| 568 |
+
"fix": "Remove the condition or fix the logic"
|
| 569 |
+
}
|
| 570 |
+
|
| 571 |
# ============ DEFAULT: NO BUGS ============
|
| 572 |
|
| 573 |
return {
|
|
@@ -938,8 +938,24 @@ function mockReview(code, lang) {
|
|
| 938 |
}
|
| 939 |
|
| 940 |
function renderResult(d) {
|
| 941 |
-
//
|
| 942 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 943 |
const fixString = (d.fix && d.fix.fixed_code) ? d.fix.fixed_code : action.fix;
|
| 944 |
|
| 945 |
const badgeCls = action.category === 'security' ? 'sec'
|
|
@@ -947,7 +963,14 @@ function renderResult(d) {
|
|
| 947 |
: action.type === 'approve' ? 'apr' : 'sty';
|
| 948 |
const badge = document.getElementById('rBadge');
|
| 949 |
badge.className = 'r-badge ' + badgeCls;
|
| 950 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 951 |
|
| 952 |
document.getElementById('rCat').textContent = action.category || action.type || '—';
|
| 953 |
document.getElementById('rLine').textContent = action.line_hint ? 'Line ' + action.line_hint : 'Not specified';
|
|
|
|
| 938 |
}
|
| 939 |
|
| 940 |
function renderResult(d) {
|
| 941 |
+
// Handle both old (single bug) and new (multiple bugs) formats
|
| 942 |
+
let action;
|
| 943 |
+
let bugsCount = 0;
|
| 944 |
+
|
| 945 |
+
if (d.primary_bug) {
|
| 946 |
+
// New format: multiple bugs detected
|
| 947 |
+
action = d.primary_bug;
|
| 948 |
+
bugsCount = d.bugs_found || 0;
|
| 949 |
+
} else if (d.bugs && d.bugs.length > 0) {
|
| 950 |
+
// Alternative: use first bug from list
|
| 951 |
+
action = d.bugs[0];
|
| 952 |
+
bugsCount = d.bugs.length;
|
| 953 |
+
} else {
|
| 954 |
+
// Old format: single bug response or ai_action
|
| 955 |
+
action = d.ai_action || d;
|
| 956 |
+
bugsCount = action.type === 'approve' ? 0 : 1;
|
| 957 |
+
}
|
| 958 |
+
|
| 959 |
const fixString = (d.fix && d.fix.fixed_code) ? d.fix.fixed_code : action.fix;
|
| 960 |
|
| 961 |
const badgeCls = action.category === 'security' ? 'sec'
|
|
|
|
| 963 |
: action.type === 'approve' ? 'apr' : 'sty';
|
| 964 |
const badge = document.getElementById('rBadge');
|
| 965 |
badge.className = 'r-badge ' + badgeCls;
|
| 966 |
+
|
| 967 |
+
if (action.type === 'approve') {
|
| 968 |
+
badge.textContent = '✓ Approved';
|
| 969 |
+
} else if (bugsCount > 1) {
|
| 970 |
+
badge.textContent = '⚠ ' + bugsCount + ' bugs found';
|
| 971 |
+
} else {
|
| 972 |
+
badge.textContent = '⚠ ' + (action.category || action.type);
|
| 973 |
+
}
|
| 974 |
|
| 975 |
document.getElementById('rCat').textContent = action.category || action.type || '—';
|
| 976 |
document.getElementById('rLine').textContent = action.line_hint ? 'Line ' + action.line_hint : 'Not specified';
|