vinith17 commited on
Commit
748fdb2
Β·
1 Parent(s): e3f03e2

feat: comprehensive 30-rule pattern analyzer covering security/logic/style/concurrency across all languages

Browse files
Files changed (1) hide show
  1. main.py +418 -73
main.py CHANGED
@@ -158,82 +158,427 @@ def analyze_code_with_llm(code: str, lang: str) -> list:
158
  logger.warning(f"LLM analysis failed ({type(e).__name__}: {e}). Using fallback analysis.")
159
  return analyze_code_comprehensively(code, lang)
160
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
 
162
  def analyze_code_comprehensively(code: str, lang: str) -> list:
163
- """Fallback pattern-based bug detection when LLM is unavailable"""
 
 
 
 
164
  bugs = []
165
- code_lower = code.lower()
166
-
167
- # SQL Injection
168
- 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:
169
- bugs.append({
170
- "type": "bug", "category": "security", "severity": 5, "line_hint": "SQL query line",
171
- "comment": "SQL injection: f-string with variable interpolation in SQL query.",
172
- "fix": "Use parameterized queries: cursor.execute('SELECT * FROM users WHERE id = ?', (uid,))",
173
- "confidence": 0.95,
174
- "languages": ["python", "javascript", "typescript"]
175
- })
176
-
177
- # Hardcoded credentials
178
- if re.search(r'(password|passwd|pwd|secret|credential)\s*[=:]\s*["\'][^"\']{6,}["\']', code, re.I):
179
- bugs.append({
180
- "type": "bug", "category": "security", "severity": 5, "line_hint": "credential line",
181
- "comment": "Hardcoded password/credential detected.",
182
- "fix": "Use environment variables: os.getenv('DB_PASSWORD')",
183
- "confidence": 0.98,
184
- "languages": ["python", "javascript", "typescript", "java", "go", "cpp"]
185
- })
186
-
187
- # Code execution vulnerabilities
188
- if re.search(r'\b(eval|exec|compile)\s*\(', code) or 'pickle.load' in code or 'yaml.load(' in code:
189
- bugs.append({
190
- "type": "bug", "category": "security", "severity": 5, "line_hint": "eval/exec/pickle line",
191
- "comment": "Arbitrary code execution: eval/exec/pickle are unsafe with untrusted data.",
192
- "fix": "Use: json.loads(), ast.literal_eval(), or safe alternatives",
193
- "confidence": 0.99,
194
- "languages": ["python", "javascript"]
195
- })
196
-
197
- # Hardcoded API keys
198
- if re.search(r'(api_key|apikey|secret_key|token|bearer)\s*[=:]\s*["\'][a-zA-Z0-9_\-]{8,}["\']', code, re.I):
199
- bugs.append({
200
- "type": "bug", "category": "security", "severity": 4, "line_hint": "API key line",
201
- "comment": "Hardcoded API key/token detected.",
202
- "fix": "Use environment variables: api_key = os.getenv('API_KEY')",
203
- "confidence": 0.96,
204
- "languages": ["python", "javascript", "typescript", "java", "go"]
205
- })
206
-
207
- # Mutable default argument (Python)
208
- if lang == 'python' and re.search(r'def\s+\w+\s*\([^)]*=\s*\[\]|def\s+\w+\s*\([^)]*=\s*\{\}', code):
209
- bugs.append({
210
- "type": "bug", "category": "logic", "severity": 3, "line_hint": "function definition",
211
- "comment": "Mutable default argument: List/dict is shared across all function calls.",
212
- "fix": "Use None as default: def func(lst=None): if lst is None: lst = []",
213
- "confidence": 0.98,
214
- "languages": ["python"]
215
- })
216
-
217
- # Off-by-one errors
218
- if re.search(r'range\(len\([^)]+\)\s*-\s*1\)', code):
219
- bugs.append({
220
- "type": "bug", "category": "logic", "severity": 3, "line_hint": "loop range",
221
- "comment": "Off-by-one error: range(len(x)-1) skips the last element.",
222
- "fix": "Use range(len(arr)) or enumerate(arr)",
223
- "confidence": 0.85,
224
- "languages": ["python", "javascript", "java", "go", "cpp"]
225
- })
226
-
227
- # Division by zero
228
- if re.search(r'\/\s*0(?![a-zA-Z0-9])', code):
229
- bugs.append({
230
- "type": "bug", "category": "logic", "severity": 3, "line_hint": "division line",
231
- "comment": "Potential division by zero. Check denominator is non-zero.",
232
- "fix": "Add check: if denominator != 0: result = numerator / denominator",
233
- "confidence": 0.99,
234
- "languages": ["python", "javascript", "java", "go", "cpp"]
235
- })
236
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
237
  return bugs
238
 
239
 
 
158
  logger.warning(f"LLM analysis failed ({type(e).__name__}: {e}). Using fallback analysis.")
159
  return analyze_code_comprehensively(code, lang)
160
 
161
+ def _make_bug(category, severity, line_hint, comment, fix, confidence, lang_list):
162
+ return {
163
+ "type": "bug",
164
+ "category": category,
165
+ "severity": severity,
166
+ "line_hint": line_hint,
167
+ "comment": comment,
168
+ "fix": fix,
169
+ "confidence": confidence,
170
+ "languages": lang_list,
171
+ }
172
+
173
+
174
+ def _find_line(code: str, pattern) -> int | None:
175
+ """Return 1-indexed line number for the first regex match, or None."""
176
+ for i, line in enumerate(code.splitlines(), 1):
177
+ if re.search(pattern, line, re.I):
178
+ return i
179
+ return None
180
+
181
 
182
  def analyze_code_comprehensively(code: str, lang: str) -> list:
183
+ """
184
+ Exhaustive pattern-based bug detector.
185
+ Runs ALL rules in a single pass and returns every bug found.
186
+ Covers: security, logic, style, concurrency, resource management.
187
+ """
188
  bugs = []
189
+ ALL_LANGS = ["python", "javascript", "typescript", "java", "go", "cpp"]
190
+
191
+ # ── SECURITY ──────────────────────────────────────────────────────────
192
+
193
+ # 1. SQL Injection via f-string / concatenation
194
+ if re.search(r'(f["\'].*?\{.*?\}.*?(SELECT|INSERT|DELETE|UPDATE|WHERE)|'
195
+ r'["\'].*?SELECT.*?\+.*?["\'])', code, re.I | re.S):
196
+ ln = _find_line(code, r'(SELECT|INSERT|DELETE|UPDATE|WHERE)')
197
+ bugs.append(_make_bug(
198
+ "security", 5, ln,
199
+ "SQL Injection: user input interpolated directly into SQL query via f-string or concatenation.",
200
+ "Use parameterized queries:\n cursor.execute('SELECT * FROM users WHERE id = ?', (uid,))",
201
+ 0.96, ["python", "javascript", "typescript", "java"]
202
+ ))
203
+
204
+ # 2. Hardcoded passwords / credentials
205
+ if re.search(r'(password|passwd|pwd|db_pass|secret)\s*[=:]\s*["\'][^"\']{4,}["\']', code, re.I):
206
+ ln = _find_line(code, r'(password|passwd|pwd|db_pass|secret)\s*[=:]')
207
+ bugs.append(_make_bug(
208
+ "security", 5, ln,
209
+ "Hardcoded credential: plaintext password stored directly in source code.",
210
+ "Read from environment:\n password = os.environ.get('DB_PASSWORD')\n # Never hardcode secrets",
211
+ 0.97, ALL_LANGS
212
+ ))
213
+
214
+ # 3. Hardcoded API key / token / secret key
215
+ if re.search(r'(api_key|apikey|access_key|secret_key|auth_token|bearer|private_key)'
216
+ r'\s*[=:]\s*["\'][A-Za-z0-9_\-\.]{8,}["\']', code, re.I):
217
+ ln = _find_line(code, r'(api_key|apikey|access_key|secret_key|auth_token|bearer|private_key)')
218
+ bugs.append(_make_bug(
219
+ "security", 5, ln,
220
+ "Hardcoded API key/token/secret detected. Exposed in version control.",
221
+ "Move to environment variable:\n api_key = os.environ.get('API_KEY')\n if not api_key: raise ValueError('API_KEY not set')",
222
+ 0.96, ALL_LANGS
223
+ ))
224
+
225
+ # 4. Arbitrary code execution
226
+ if re.search(r'\b(eval|exec)\s*\(', code, re.I):
227
+ ln = _find_line(code, r'\b(eval|exec)\s*\(')
228
+ bugs.append(_make_bug(
229
+ "security", 5, ln,
230
+ "Arbitrary code execution: eval()/exec() with untrusted input enables Remote Code Execution.",
231
+ "Use safe alternatives:\n # Python: ast.literal_eval() for literals\n # JS: JSON.parse() for data\n # Never pass user input to eval/exec",
232
+ 0.99, ["python", "javascript", "typescript"]
233
+ ))
234
+
235
+ # 5. Insecure deserialization
236
+ if re.search(r'pickle\.(load|loads|Unpickler)|yaml\.load\s*\([^)]*\)(?!.*Loader=yaml\.SafeLoader)', code):
237
+ ln = _find_line(code, r'pickle\.(load|loads)|yaml\.load')
238
+ bugs.append(_make_bug(
239
+ "security", 5, ln,
240
+ "Insecure deserialization: pickle/yaml.load with untrusted data enables arbitrary code execution.",
241
+ "# pickle: avoid entirely for untrusted data\n"
242
+ "# yaml: use yaml.safe_load(data) instead of yaml.load(data)",
243
+ 0.98, ["python"]
244
+ ))
245
+
246
+ # 6. Command injection (shell=True / os.system)
247
+ if re.search(r'os\.system\s*\(|subprocess\.(call|run|Popen)\s*\(.*shell\s*=\s*True', code, re.S):
248
+ ln = _find_line(code, r'os\.system|shell\s*=\s*True')
249
+ bugs.append(_make_bug(
250
+ "security", 5, ln,
251
+ "Command injection risk: shell=True or os.system() with user input allows arbitrary command execution.",
252
+ "Use subprocess with a list and shell=False:\n"
253
+ " subprocess.run(['ls', '-la'], shell=False, capture_output=True)",
254
+ 0.95, ["python"]
255
+ ))
256
+
257
+ # 7. Path traversal
258
+ if re.search(r'open\s*\(\s*(request\.|f["\']|.*\+)', code, re.I):
259
+ ln = _find_line(code, r'open\s*\(')
260
+ bugs.append(_make_bug(
261
+ "security", 4, ln,
262
+ "Path traversal risk: file path constructed from user input without sanitisation.",
263
+ "Validate and restrict paths:\n"
264
+ " import pathlib\n"
265
+ " safe = pathlib.Path('/safe/base').resolve() / user_input\n"
266
+ " assert str(safe).startswith('/safe/base')",
267
+ 0.80, ["python", "javascript", "typescript"]
268
+ ))
269
+
270
+ # 8. Weak hashing algorithm
271
+ if re.search(r'\b(md5|sha1)\b', code, re.I) and re.search(r'(password|passwd|pwd|hash)', code, re.I):
272
+ ln = _find_line(code, r'\b(md5|sha1)\b')
273
+ bugs.append(_make_bug(
274
+ "security", 4, ln,
275
+ "Weak hashing: MD5/SHA-1 are cryptographically broken and must not be used for passwords.",
276
+ "Use bcrypt or Argon2:\n"
277
+ " import bcrypt\n"
278
+ " hashed = bcrypt.hashpw(password.encode(), bcrypt.gensalt())",
279
+ 0.94, ALL_LANGS
280
+ ))
281
+
282
+ # 9. Debug mode left on
283
+ if re.search(r'(app\.run|debug)\s*[=(]\s*True', code, re.I):
284
+ ln = _find_line(code, r'debug\s*[=(]\s*True')
285
+ bugs.append(_make_bug(
286
+ "security", 3, ln,
287
+ "Debug mode enabled in production: exposes stack traces, interactive debugger, and sensitive data.",
288
+ "Disable debug before deploying:\n"
289
+ " debug = os.environ.get('DEBUG', 'false').lower() == 'true'\n"
290
+ " app.run(debug=debug)",
291
+ 0.92, ["python", "javascript"]
292
+ ))
293
+
294
+ # ── LOGIC ───────────────────────────────────────────────────────────
295
+
296
+ # 10. Off-by-one: range(len(x) - 1)
297
+ if re.search(r'range\s*\(\s*len\s*\([^)]+\)\s*-\s*1\s*\)', code):
298
+ ln = _find_line(code, r'range\s*\(\s*len')
299
+ bugs.append(_make_bug(
300
+ "logic", 3, ln,
301
+ "Off-by-one error: range(len(x) - 1) skips the last element of the sequence.",
302
+ "Fix: use range(len(arr)) to include all elements\n"
303
+ " for i in range(len(numbers)): # not range(len(numbers)-1)\n"
304
+ " # Or better: for item in numbers:",
305
+ 0.88, ALL_LANGS
306
+ ))
307
+
308
+ # 11. Mutable default argument
309
+ if lang in ('python',) and re.search(r'def\s+\w+\s*\([^)]*=\s*(\[\]|\{\}|set\(\))', code):
310
+ ln = _find_line(code, r'def\s+\w+\s*\([^)]*=\s*(\[\]|\{\})')
311
+ bugs.append(_make_bug(
312
+ "logic", 4, ln,
313
+ "Mutable default argument: the list/dict is shared across all calls β€” state leaks between invocations.",
314
+ "Use None as sentinel:\n"
315
+ " def func(items=None):\n"
316
+ " if items is None:\n"
317
+ " items = []",
318
+ 0.98, ["python"]
319
+ ))
320
+
321
+ # 12. Division without zero guard
322
+ if re.search(r'\w+\s*/\s*\w+', code) and not re.search(r'if.*!=\s*0|if.*> 0|try', code):
323
+ ln = _find_line(code, r'\w+\s*/\s*\w+(?!\s*/)')
324
+ if ln:
325
+ bugs.append(_make_bug(
326
+ "logic", 3, ln,
327
+ "Potential division by zero: denominator is not checked before division.",
328
+ "Guard the division:\n"
329
+ " if denominator != 0:\n"
330
+ " result = numerator / denominator\n"
331
+ " else:\n"
332
+ " result = 0 # or raise ValueError",
333
+ 0.75, ALL_LANGS
334
+ ))
335
+
336
+ # 13. Strict > / < where edge case matters (balance/transfer pattern)
337
+ if re.search(r'(balance|amount|total|price|quota)\s*[><!]=?\s*\w+', code, re.I) \
338
+ and not re.search(r'>=|<=', code):
339
+ ln = _find_line(code, r'(balance|amount|total|price|quota)\s*[><]')
340
+ if ln:
341
+ bugs.append(_make_bug(
342
+ "logic", 3, ln,
343
+ "Edge-case boundary bug: strict > or < comparison may miss the equality case (e.g., exact balance transfer).",
344
+ "Use >= or <= to include the boundary:\n"
345
+ " if account.balance >= amount: # not >",
346
+ 0.80, ALL_LANGS
347
+ ))
348
+
349
+ # 14. Return value of function never used (assignment to _)
350
+ if re.search(r'\bNone\s*==\s*\w+|\w+\s*==\s*None\b', code) \
351
+ and not re.search(r'\bis\s+None\b|\bis\s+not\s+None\b', code):
352
+ ln = _find_line(code, r'\bNone\s*==|\w+\s*==\s*None')
353
+ if ln:
354
+ bugs.append(_make_bug(
355
+ "logic", 2, ln,
356
+ "None comparison using == instead of 'is': PEP 8 and Python docs require 'is None' / 'is not None'.",
357
+ "Fix:\n if value is None: # correct\n if value is not None: # correct\n # NOT: if value == None",
358
+ 0.95, ["python"]
359
+ ))
360
+
361
+ # 15. Infinite loop risk (while True without break/return)
362
+ wt = re.search(r'while\s+True\s*:', code)
363
+ if wt and not re.search(r'\bbreak\b|\breturn\b|\braise\b|\bsys\.exit\b', code):
364
+ ln = _find_line(code, r'while\s+True\s*:')
365
+ bugs.append(_make_bug(
366
+ "logic", 4, ln,
367
+ "Infinite loop: while True loop with no break, return, or raise β€” program will hang.",
368
+ "Add an exit condition:\n"
369
+ " while True:\n"
370
+ " # ... your logic ...\n"
371
+ " if exit_condition:\n"
372
+ " break",
373
+ 0.87, ALL_LANGS
374
+ ))
375
+
376
+ # 16. Unchecked index access on potentially empty list
377
+ if re.search(r'\w+\[\s*0\s*\]|\w+\[\s*-1\s*\]', code) \
378
+ and not re.search(r'if\s+\w+|len\s*\(', code):
379
+ ln = _find_line(code, r'\w+\[\s*0\s*\]|\w+\[\s*-1\s*\]')
380
+ if ln:
381
+ bugs.append(_make_bug(
382
+ "logic", 3, ln,
383
+ "Unchecked index access: accessing index [0] or [-1] on a potentially empty collection causes IndexError.",
384
+ "Guard before accessing:\n"
385
+ " if items:\n"
386
+ " first = items[0]",
387
+ 0.72, ALL_LANGS
388
+ ))
389
+
390
+ # 17. Bare except (swallows all errors silently)
391
+ if re.search(r'except\s*:', code) or re.search(r'except\s+Exception\s*:', code):
392
+ ln = _find_line(code, r'except\s*:|except\s+Exception\s*:')
393
+ bugs.append(_make_bug(
394
+ "logic", 3, ln,
395
+ "Bare except clause: catches and silences ALL exceptions including SystemExit and KeyboardInterrupt.",
396
+ "Catch specific exceptions:\n"
397
+ " try:\n"
398
+ " risky_call()\n"
399
+ " except ValueError as e:\n"
400
+ " logger.error('Bad value: %s', e)\n"
401
+ " except IOError as e:\n"
402
+ " logger.error('IO error: %s', e)",
403
+ 0.93, ["python"]
404
+ ))
405
+
406
+ # 18. Missing return in all branches
407
+ if lang == "python" and re.search(r'def\s+\w+', code):
408
+ fn_body = re.split(r'def\s+\w+[^:]*:', code)
409
+ for body in fn_body[1:]:
410
+ indent_lines = [l for l in body.splitlines() if l.strip()]
411
+ has_if = any(re.match(r'\s+if\b', l) for l in indent_lines)
412
+ has_return = re.search(r'\breturn\b', body)
413
+ has_else_return = re.search(r'else:\s*\n\s+return', body)
414
+ if has_if and has_return and not has_else_return:
415
+ ln = _find_line(code, r'def\s+\w+')
416
+ bugs.append(_make_bug(
417
+ "logic", 2, ln,
418
+ "Inconsistent return: function returns a value in some branches but falls through (returns None) in others.",
419
+ "Ensure all branches return explicitly:\n"
420
+ " def func(x):\n"
421
+ " if x > 0:\n"
422
+ " return x\n"
423
+ " return 0 # explicit fallback",
424
+ 0.70, ["python"]
425
+ ))
426
+ break
427
+
428
+ # ── JAVASCRIPT / TYPESCRIPT SPECIFIC ────────────────────────────────
429
+
430
+ if lang in ('javascript', 'typescript'):
431
+ # 19. var instead of let/const
432
+ if re.search(r'\bvar\s+\w+', code):
433
+ ln = _find_line(code, r'\bvar\s+\w+')
434
+ bugs.append(_make_bug(
435
+ "style", 2, ln,
436
+ "Deprecated var: function-scoped and hoisted variables cause subtle bugs. Use const or let.",
437
+ "Replace:\n const name = value; // for constants\n let count = 0; // for reassignable values",
438
+ 0.97, ["javascript", "typescript"]
439
+ ))
440
+
441
+ # 20. Loose equality (== instead of ===)
442
+ if re.search(r'[^=!<>]==[^=]|[^=]!=[^=]', code):
443
+ ln = _find_line(code, r'[^=!<>]==[^=]|[^=]!=[^=]')
444
+ bugs.append(_make_bug(
445
+ "logic", 3, ln,
446
+ "Type coercion bug: == and != perform implicit type conversion. Use === and !== for strict equality.",
447
+ "Replace == with ===:\n if (value === null) // strict\n if (count !== 0) // strict",
448
+ 0.94, ["javascript", "typescript"]
449
+ ))
450
+
451
+ # 21. Async without await
452
+ if re.search(r'async\s+function|async\s*\(', code) and not re.search(r'\bawait\b', code):
453
+ ln = _find_line(code, r'async\s+function|async\s*\(')
454
+ bugs.append(_make_bug(
455
+ "logic", 3, ln,
456
+ "async function without await: function is marked async but never awaits β€” returns an unwrapped Promise.",
457
+ "Add await to async calls:\n async function getUser() {\n const user = await fetchUser(); // not fetchUser()\n return user;\n }",
458
+ 0.85, ["javascript", "typescript"]
459
+ ))
460
+
461
+ # ── JAVA SPECIFIC ────────────────────────────────────────────────────
462
+
463
+ if lang == 'java':
464
+ # 22. NullPointerException risk
465
+ if re.search(r'\w+\.equals\s*\(\s*["\']', code):
466
+ ln = _find_line(code, r'\w+\.equals\s*\(\s*["\']')
467
+ bugs.append(_make_bug(
468
+ "logic", 3, ln,
469
+ "NullPointerException risk: calling .equals() on a variable that might be null.",
470
+ "Compare with literal on the left:\n if (\"expected\".equals(variable)) // null-safe",
471
+ 0.91, ["java"]
472
+ ))
473
+
474
+ # 23. == for String comparison
475
+ if re.search(r'String.*==|==.*String', code):
476
+ ln = _find_line(code, r'String.*==|==.*String')
477
+ bugs.append(_make_bug(
478
+ "logic", 4, ln,
479
+ "String identity comparison: == compares references, not content. Two equal strings may be different objects.",
480
+ "Use .equals():\n if (str1.equals(str2)) // content comparison",
481
+ 0.95, ["java"]
482
+ ))
483
+
484
+ # ── STYLE / QUALITY ──────────────────────────────────────────────────
485
+
486
+ # 24. print() instead of logging (Python)
487
+ if lang == 'python' and re.search(r'\bprint\s*\(', code) \
488
+ and not re.search(r'import logging|logging\.(info|error|debug|warning)', code):
489
+ ln = _find_line(code, r'\bprint\s*\(')
490
+ bugs.append(_make_bug(
491
+ "style", 1, ln,
492
+ "print() in production code: use the logging module for structured, level-aware output.",
493
+ "Replace print with logging:\n"
494
+ " import logging\n"
495
+ " logger = logging.getLogger(__name__)\n"
496
+ " logger.info('message: %s', value)",
497
+ 0.80, ["python"]
498
+ ))
499
+
500
+ # 25. TODO / FIXME left in code
501
+ if re.search(r'\b(TODO|FIXME|HACK|XXX)\b', code, re.I):
502
+ ln = _find_line(code, r'\b(TODO|FIXME|HACK|XXX)\b')
503
+ bugs.append(_make_bug(
504
+ "style", 1, ln,
505
+ "Unresolved TODO/FIXME comment: technical debt marker left in production code.",
506
+ "Resolve the TODO or create a tracked issue:\n"
507
+ " # Before: # TODO: handle edge case\n"
508
+ " # After: implement the fix and remove the comment",
509
+ 0.99, ALL_LANGS
510
+ ))
511
+
512
+ # 26. Magic numbers
513
+ if re.search(r'(?<!["\'\w])\b(?!0\b|1\b)[2-9]\d{2,}\b(?!["\'\w])', code) \
514
+ and lang in ('python', 'javascript', 'typescript', 'java'):
515
+ ln = _find_line(code, r'(?<!["\'\w])\b(?!0\b|1\b)[2-9]\d{2,}\b')
516
+ if ln:
517
+ bugs.append(_make_bug(
518
+ "style", 1, ln,
519
+ "Magic number: unexplained numeric literal reduces readability and maintainability.",
520
+ "Define a named constant:\n"
521
+ " MAX_RETRIES = 500\n"
522
+ " TIMEOUT_MS = 3000",
523
+ 0.70, ALL_LANGS
524
+ ))
525
+
526
+ # 27. Empty catch block
527
+ if re.search(r'except.*:\s*\n\s*(pass|#)', code) or \
528
+ re.search(r'catch\s*\([^)]*\)\s*\{\s*\}', code):
529
+ ln = _find_line(code, r'except.*:\s*$|catch\s*\(')
530
+ bugs.append(_make_bug(
531
+ "logic", 3, ln,
532
+ "Empty exception handler: errors are silently swallowed, making debugging impossible.",
533
+ "At minimum log the exception:\n"
534
+ " except Exception as e:\n"
535
+ " logger.error('Unexpected error: %s', e, exc_info=True)\n"
536
+ " raise # re-raise if you cannot handle it",
537
+ 0.95, ALL_LANGS
538
+ ))
539
+
540
+ # 28. Resource leak (file opened but no context manager)
541
+ if re.search(r'\bopen\s*\(', code) and not re.search(r'\bwith\s+open\b', code) and lang == 'python':
542
+ ln = _find_line(code, r'\bopen\s*\(')
543
+ bugs.append(_make_bug(
544
+ "logic", 3, ln,
545
+ "Resource leak: file opened without a 'with' statement β€” file may not be closed on exception.",
546
+ "Use context manager:\n"
547
+ " with open('file.txt', 'r') as f:\n"
548
+ " data = f.read()\n"
549
+ " # file is automatically closed",
550
+ 0.93, ["python"]
551
+ ))
552
+
553
+ # 29. Deprecated Python 2 constructs
554
+ if lang == 'python' and re.search(r'\bprint\s+[^(]|\bxrange\b|\breduce\s*\(|urllib2\b', code):
555
+ ln = _find_line(code, r'\bxrange\b|\bprint\s+[^(]')
556
+ if ln:
557
+ bugs.append(_make_bug(
558
+ "style", 2, ln,
559
+ "Python 2 syntax: xrange(), print statement, and urllib2 do not exist in Python 3.",
560
+ "Update to Python 3:\n"
561
+ " range() instead of xrange()\n"
562
+ " print() function\n"
563
+ " urllib.request instead of urllib2",
564
+ 0.99, ["python"]
565
+ ))
566
+
567
+ # 30. Concurrency: thread-unsafe global state mutation
568
+ if re.search(r'global\s+\w+', code) and re.search(r'Thread|threading|asyncio', code):
569
+ ln = _find_line(code, r'global\s+\w+')
570
+ bugs.append(_make_bug(
571
+ "logic", 4, ln,
572
+ "Thread-unsafe global mutation: modifying global variables from multiple threads causes race conditions.",
573
+ "Use threading.Lock() to protect shared state:\n"
574
+ " _lock = threading.Lock()\n"
575
+ " with _lock:\n"
576
+ " global_counter += 1",
577
+ 0.82, ["python", "java", "go", "cpp"]
578
+ ))
579
+
580
+ # Sort: highest severity first, then confidence
581
+ bugs.sort(key=lambda b: (b["severity"], b["confidence"]), reverse=True)
582
  return bugs
583
 
584