-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdeadcode_engine.py
More file actions
executable file
·2587 lines (2305 loc) · 119 KB
/
Copy pathdeadcode_engine.py
File metadata and controls
executable file
·2587 lines (2305 loc) · 119 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Enhanced Dead Code Detection Engine for CodeLens — v3
Goes beyond the basic 0-ref_count check to find:
1. Unreachable code branches (code after return/throw/break)
2. Unused exports (exported but never imported)
3. Zombie CSS (CSS classes defined but never referenced in HTML/JS)
4. Dead event listeners (listeners on elements that don't exist)
5. Unused variables (declared but never read)
6. Unreachable catch blocks (catch for error type that can't be thrown)
Performance: Includes --max-results cap and file-count limits to prevent
timeout on very large codebases (100k+ files).
"""
import os
import re
import json
import time
from typing import Dict, List, Any, Optional, Set
from collections import defaultdict, Counter
from utils import DEFAULT_IGNORE_DIRS, safe_read_file, MAX_FILE_SIZE, logger, time_budget_expired
SOURCE_EXTENSIONS = {
".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx",
".py", ".rs", ".vue", ".svelte", ".css", ".scss", ".less",
".go", ".cc", ".cpp", ".cxx", ".c", ".h", ".hpp", ".hxx",
".lua", ".java", ".cs", ".php", ".zig",
".rb", ".ex", ".exs", ".swift", ".scala", ".sc",
".nim", ".nims", ".sh", ".bash", ".zsh", ".dart",
}
# Performance limits for large codebases
MAX_FILES_PER_CATEGORY = 5000 # Max files to scan per category
MAX_RESULTS_PER_CATEGORY = 200 # Max results to return per category
def detect_dead_code(
workspace: str,
categories: Optional[List[str]] = None,
config: Optional[Dict] = None,
max_results: int = MAX_RESULTS_PER_CATEGORY,
max_files: int = MAX_FILES_PER_CATEGORY
) -> Dict[str, Any]:
"""
Enhanced dead code detection beyond basic ref_count==0.
Args:
workspace: Absolute path to workspace
categories: Optional list of categories to check
(unreachable, unused_exports, zombie_css, unused_vars, dead_listeners)
config: CodeLens config
max_results: Max results per category (default 200)
max_files: Max files to scan per category (default 5000)
Returns:
Dict with all detected dead code, categorized and prioritized
"""
workspace = os.path.abspath(workspace)
valid_categories = {
"unreachable", "unused_exports", "zombie_css",
"unused_vars", "dead_listeners"
}
if categories:
categories = [c for c in categories if c in valid_categories]
else:
categories = list(valid_categories)
results: Dict[str, List[Dict]] = {cat: [] for cat in valid_categories}
files_scanned = 0
truncated = False
TIMEOUT_BUDGET = 90 # seconds — prevent hanging on huge repos
start_time = time.time()
timed_out = False
# Collect all exports and imports for cross-file analysis
all_exports: Dict[str, List[Dict]] = defaultdict(list) # file → exports
all_imports: Dict[str, Set[str]] = defaultdict(set) # file → imported names
same_file_usages: Dict[str, Set[str]] = defaultdict(set) # file → names used within the file
for root, dirs, filenames in os.walk(workspace):
dirs[:] = [d for d in dirs if d not in DEFAULT_IGNORE_DIRS and not d.startswith('.')]
if '.codelens' in root:
dirs.clear()
continue
for filename in filenames:
ext = os.path.splitext(filename)[1].lower()
if ext not in SOURCE_EXTENSIONS:
continue
# File-count limit to prevent timeout on huge repos
if files_scanned >= max_files:
truncated = True
break
# Time budget check — bail out before hanging
if time_budget_expired(start_time, TIMEOUT_BUDGET):
timed_out = True
truncated = True
break
file_path = os.path.join(root, filename)
rel_path = os.path.relpath(file_path, workspace)
# Use safe_read_file with size limit to avoid slow scans
content = safe_read_file(file_path, MAX_FILE_SIZE)
if content is None:
continue
files_scanned += 1
lines = content.split('\n')
# ─── Unreachable Code ────────────────────────
if "unreachable" in categories and ext in {".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx", ".py", ".rs", ".go", ".c", ".cpp", ".cxx", ".cc", ".h", ".hpp", ".php", ".rb", ".lua", ".ex", ".exs", ".nim", ".nims", ".java", ".cs", ".swift", ".scala", ".dart", ".sh", ".bash", ".zsh"}:
if len(results["unreachable"]) < max_results:
unreachable = _detect_unreachable_code(content, ext, rel_path)
results["unreachable"].extend(unreachable)
# ─── Unused Variables ────────────────────────
if "unused_vars" in categories and ext in {".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx", ".py", ".rs", ".go", ".c", ".cpp", ".cxx", ".cc", ".h", ".hpp", ".php", ".rb", ".lua", ".ex", ".exs", ".nim", ".nims", ".java", ".cs", ".swift", ".scala", ".dart", ".sh", ".bash", ".zsh"}:
if len(results["unused_vars"]) < max_results:
unused = _detect_unused_variables(content, ext, rel_path)
results["unused_vars"].extend(unused)
# ─── Collect exports/imports ─────────────────
if ext in {".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx"}:
_collect_js_exports_imports(content, ext, rel_path, all_exports, all_imports)
elif ext == ".py":
_collect_py_exports_imports(content, rel_path, all_exports, all_imports)
# Track same-file usage: find all names referenced in the file
_collect_py_same_file_usages(content, rel_path, same_file_usages)
elif ext == ".go":
_collect_go_exports_imports(content, rel_path, all_exports, all_imports)
# Issue #220: track same-file usage for non-Python languages
_collect_go_same_file_usages(content, rel_path, same_file_usages)
elif ext == ".rs":
_collect_rust_exports_imports(content, rel_path, all_exports, all_imports)
# Issue #220: track same-file usage for non-Python languages
_collect_rust_same_file_usages(content, rel_path, same_file_usages)
elif ext in {".c", ".cpp", ".cxx", ".cc", ".h", ".hpp", ".hxx"}:
_collect_c_exports_imports(content, rel_path, all_exports, all_imports)
# Issue #220: track same-file usage for non-Python languages
_collect_c_same_file_usages(content, rel_path, same_file_usages)
elif ext == ".lua":
_collect_lua_exports_imports(content, rel_path, all_exports, all_imports)
elif ext == ".php":
_collect_php_exports_imports(content, rel_path, all_exports, all_imports)
# Issue #220: track same-file usage for non-Python languages
_collect_php_same_file_usages(content, rel_path, same_file_usages)
elif ext in {".ex", ".exs"}:
_collect_elixir_exports_imports(content, rel_path, all_exports, all_imports)
elif ext == ".rb":
_collect_ruby_exports_imports(content, rel_path, all_exports, all_imports)
# Issue #220: track same-file usage for non-Python languages
_collect_ruby_same_file_usages(content, rel_path, same_file_usages)
elif ext in {".nim", ".nims"}:
_collect_nim_exports_imports(content, rel_path, all_exports, all_imports)
elif ext == ".java":
_collect_java_exports_imports(content, rel_path, all_exports, all_imports)
# Issue #220: track same-file usage for non-Python languages
_collect_java_same_file_usages(content, rel_path, same_file_usages)
elif ext == ".cs":
_collect_csharp_exports_imports(content, rel_path, all_exports, all_imports)
elif ext == ".swift":
_collect_swift_exports_imports(content, rel_path, all_exports, all_imports)
elif ext in {".scala", ".sc"}:
_collect_scala_exports_imports(content, rel_path, all_exports, all_imports)
elif ext == ".dart":
_collect_dart_exports_imports(content, rel_path, all_exports, all_imports)
elif ext in {".sh", ".bash", ".zsh"}:
_collect_shell_exports_imports(content, rel_path, all_exports, all_imports)
# ─── Collect name references (usages) for improved cross-file analysis ───
# For JS/TS/Python, import statements directly name what's imported, so
# the imports dict already captures usage. For Go, Rust, C, Lua, PHP,
# Elixir, Ruby etc., the import mechanism brings in packages/modules and
# names are used via qualified access (pkg.Func) or direct calls.
# This step collects those usage references so _detect_unused_exports
# can check if an exported name is actually used anywhere.
if ext in {".go", ".rs", ".c", ".cpp", ".cxx", ".cc", ".h", ".hpp", ".hxx",
".lua", ".php", ".ex", ".exs", ".rb", ".java", ".cs", ".swift",
".scala", ".sc", ".dart", ".nim", ".nims", ".sh", ".bash", ".zsh"}:
_collect_name_references(content, ext, rel_path, all_imports)
if truncated:
break
# ─── Unused Exports ──────────────────────────────────
if "unused_exports" in categories:
unused_exps = _detect_unused_exports(all_exports, all_imports, workspace, same_file_usages)
results["unused_exports"] = unused_exps[:max_results]
# ─── Zombie CSS ──────────────────────────────────────
if "zombie_css" in categories:
zombie = _detect_zombie_css(workspace)
results["zombie_css"] = zombie[:max_results]
# ─── Dead Event Listeners ────────────────────────────
if "dead_listeners" in categories:
dead = _detect_dead_listeners(workspace)
results["dead_listeners"] = dead[:max_results]
# Truncate any remaining categories
for cat in results:
if len(results[cat]) > max_results:
results[cat] = results[cat][:max_results]
truncated = True
# v6: Use the backend registry's ref_count data when available.
# Functions with ref_count == 0 and status == "dead" from the scan
# should be reported as dead code.
# Issue #220: pass same_file_usages so _detect_dead_from_registry can
# exempt symbols that are referenced within their own file (e.g. a Rust
# const used 10+ times in-file but never appearing as a CALLS edge
# because consts are not "called").
registry_dead = _detect_dead_from_registry(workspace, same_file_usages)
if registry_dead:
results["registry_dead"] = registry_dead[:max_results]
# v6.4: Add source classification to all findings and downgrade non-core severity
_TEST_EXAMPLE_PATTERNS = [
'/test/', '/tests/', '/__test', '/__tests__/',
'/example/', '/examples/', '/e2e/',
'/fixture/', '/fixtures/', '/mock/', '/mocks/',
'/stories/', '/storybook/', '/snippets/',
'/docs_src/', '/doc_src/', '/docs/examples/',
'/documentation/', '/tutorial/',
]
_CONFIG_PATTERNS = [
'.config.js', '.config.mjs', '.config.ts',
'webpack.config.', 'vite.config.', 'jest.config.',
'tsconfig.json', 'postcss.config.', 'tailwind.config.',
'babel.config.', 'eslint.config.',
]
def _classify_source(rel: str) -> str:
normalized = '/' + rel if not rel.startswith('/') else rel
for p in _TEST_EXAMPLE_PATTERNS:
if p in normalized or normalized.startswith(p.lstrip('/')):
return 'test'
for p in _CONFIG_PATTERNS:
if p in rel:
return 'config'
return 'core'
by_source = {"core": 0, "test": 0, "config": 0, "library_api": 0}
for cat, items in results.items():
for item in items:
# Preserve existing source if already set (e.g., library_api from unused_exports)
if item.get('source') in ('library_api',):
by_source['library_api'] = by_source.get('library_api', 0) + 1
continue
fpath = item.get('file', '')
source = _classify_source(fpath)
item['source'] = source
by_source[source] = by_source.get(source, 0) + 1
# Downgrade severity for non-core findings
if source in ('test', 'config'):
sev = item.get('severity', 'warning')
if sev == 'critical':
item['severity'] = 'warning'
item['downgraded'] = True
elif sev == 'warning':
item['severity'] = 'info'
item['downgraded'] = True
# Compute totals
total = sum(len(v) for v in results.values())
by_category = {k: len(v) for k, v in results.items() if v}
# Determine removal safety and recommended action based on findings
high_severity = sum(
1 for items in results.values()
for item in items
if item.get("severity") == "critical"
)
if high_severity > 0:
removal_safety = "dangerous"
recommended_action = "Review critical dead code before removal — some may be dynamically accessed"
elif total > 50:
removal_safety = "cautious"
recommended_action = "Large amount of dead code found — remove in batches with testing"
elif total > 10:
removal_safety = "mostly_safe"
recommended_action = "Moderate dead code found — review and remove with standard testing"
elif total > 0:
removal_safety = "safe"
recommended_action = "Small amount of dead code found — safe to remove"
else:
removal_safety = "clean"
recommended_action = "No dead code detected"
# Build categories dict (same as results, for API compatibility)
categories_dict = {k: v for k, v in results.items() if v}
# v8.2 (issue #5): enrich every finding with a confidence score so
# agents can rank actionable vs. needs-review findings. Scores are
# category-driven with modifier adjustments (test files, library API,
# downgraded severity, etc.). See scripts/confidence.py for the model.
try:
from confidence import enrich_findings
except ImportError:
# Defensive: never let confidence scoring break the engine.
enrich_findings = None
payload = {
"status": "ok",
"workspace": workspace,
"stats": {
"files_scanned": files_scanned,
"total_dead_code": total,
"by_category": by_category,
"truncated": truncated,
"by_source": by_source
},
"results": {k: v for k, v in results.items() if v},
"categories": categories_dict,
"categories_checked": list(categories),
"removal_safety": removal_safety,
"recommended_action": recommended_action,
"timed_out": timed_out,
"duration_ms": int((time.time() - start_time) * 1000),
}
if enrich_findings is not None:
payload = enrich_findings("dead_code", payload)
return payload
def _detect_unreachable_code(content: str, ext: str, rel_path: str) -> List[Dict]:
"""Detect code that comes after return/throw/break/continue and is therefore unreachable.
v6: Fixed function scope tracking by using brace depth tracking instead of
resetting in_function on every closing brace. Now only exits function scope
when the brace depth returns to the level it was at before the function started.
v5.10: Fixed Rust match arm false positives. In Rust, each match arm ends
with a terminal statement (return/expression), but the next arm is a separate
branch and NOT unreachable. We now track match arm boundaries (comma after
expression or closing brace) and reset the terminal flag at each new arm.
"""
items = []
lines = content.split('\n')
# v6: Track brace depth to know when a function truly ends
brace_depth = 0 # current brace nesting level
function_start_depth = -1 # brace depth when the current function started
in_function = False
found_terminal = False
terminal_line = 0
terminal_type = ""
terminal_depth = 0 # v7: brace depth where the terminal statement was found
terminal_indent = 0 # Python: indentation level of the terminal statement
# v5.10: Rust match arm tracking
in_match = False
match_start_depth = 0
last_arm_depth = 0
for i, line in enumerate(lines):
stripped = line.strip()
# v6: Update brace depth for every line (even comments/blanks may contain braces)
if ext != ".py":
for ch in stripped:
if ch == '{':
brace_depth += 1
elif ch == '}':
brace_depth -= 1
# Skip empty lines and comments
# Elixir: comments start with #
# Ruby: comments start with #
# Lua: comments start with --
if ext in {".ex", ".exs", ".rb"}:
if not stripped or stripped.startswith('#'):
if found_terminal:
continue
continue
elif not stripped or stripped.startswith('//') or stripped.startswith('#') or stripped.startswith('/*') or stripped.startswith('--'):
if found_terminal:
continue
continue
# v5.10: Track Rust match expressions
if ext == ".rs":
if re.match(r'\s*match\s+', stripped):
in_match = True
match_start_depth = brace_depth
# End match when we return to the depth where match started
if in_match and brace_depth <= match_start_depth and '{' not in stripped:
in_match = False
# Detect function start
if ext in {".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx"}:
if re.match(r'(?:export\s+)?(?:async\s+)?function\s+\w+', stripped):
in_function = True
found_terminal = False
function_start_depth = brace_depth # v6: record depth at function start
elif ext == ".py":
if re.match(r'(?:async\s+)?def\s+\w+', stripped):
in_function = True
found_terminal = False
# For Python, track the indentation of the def line
function_indent = len(line) - len(line.lstrip())
elif ext == ".rs":
if re.match(r'\s*(?:pub\s+)?(?:async\s+)?fn\s+\w+', stripped):
in_function = True
found_terminal = False
function_start_depth = brace_depth # v6: record depth at function start
elif ext == ".go":
if re.match(r'\s*func\s+(?:\([^)]+\)\s+)?\w+\s*\(', stripped):
in_function = True
found_terminal = False
function_start_depth = brace_depth
elif ext in {".c", ".cpp", ".cxx", ".cc", ".h", ".hpp", ".hxx"}:
if re.match(r'\s*(?:static\s+|inline\s+|extern\s+|virtual\s+|constexpr\s+)*'
r'(?:[\w:*&<>,\s]+?)\s+\w+(?:::\w+)*\s*\([^)]*\)\s*(?:const\s*)?(?:->\s*[\w:*&<>,\s]+\s*)?\{', stripped):
in_function = True
found_terminal = False
function_start_depth = brace_depth
elif ext == ".lua":
if re.match(r'\s*(?:local\s+)?function\s+[\w:.]+\s*\(', stripped):
in_function = True
found_terminal = False
elif ext == ".php":
if re.match(r'\s*(?:(?:public|private|protected|static|abstract|final)\s+)*function\s+\w+\s*\(', stripped):
in_function = True
found_terminal = False
function_start_depth = brace_depth
elif ext in {".ex", ".exs"}:
# Elixir: def/defp/defmacro start a function; they end at the next end
if re.match(r'\s*(?:def|defp|defmacro|defmacrop)\s+\w+', stripped):
in_function = True
found_terminal = False
elif ext == ".rb":
# Ruby: def starts a method; ends at the next end
if re.match(r'\s*def\s+\w+', stripped):
in_function = True
found_terminal = False
# Detect terminal statements
if in_function:
# Elixir: raise is a terminal statement
if ext in {".ex", ".exs"}:
if re.match(r'(?:return|raise|throw|exit)\b', stripped):
found_terminal = True
terminal_line = i # 0-based: next line has i+1 > i = True
terminal_type = stripped.split()[0]
terminal_depth = brace_depth
# Ruby: raise/return/throw are terminal
elif ext == ".rb":
if re.match(r'(?:return|raise|throw|fail|exit)\b', stripped):
found_terminal = True
terminal_line = i # 0-based: next line has i+1 > i = True
terminal_type = stripped.split()[0]
terminal_depth = brace_depth
elif re.match(r'(?:return|throw|break|continue)\s', stripped):
# v5.10: In Rust match arms, terminal statements are normal —
# the next arm is NOT unreachable. Skip reporting if we're in a match.
if ext == ".rs" and in_match:
found_terminal = False # Reset, don't flag match arm terminals
continue
# v8: Multi-line return statements in Rust/C-like languages.
# If the return line doesn't end with ';' or '}' or ')' or ']', the
# return expression continues on the next line — don't flag as terminal yet.
if ext in {".rs", ".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx"}:
if not stripped.endswith(';') and not stripped.endswith('}') and not stripped.endswith(')') and not stripped.endswith(']'):
continue # Not a complete return statement yet
# v9: Multi-line return statements in Python.
# If the return line has unclosed brackets/parens/braces, the
# expression continues on the next line — don't flag as terminal yet.
if ext == ".py":
open_count = stripped.count('(') + stripped.count('[') + stripped.count('{')
close_count = stripped.count(')') + stripped.count(']') + stripped.count('}')
if open_count > close_count:
# v10 (issue #105): Before skipping, check if we've already
# exited the block that contained the previous terminal
# statement. The classic false-positive pattern is:
# if x:
# return None # terminal at indent 8
# return { # indent 4 — multiline start
# "k": "v", # indent 8 — was flagged as
# } # unreachable (same indent
# # as the terminal inside if)
# The previous terminal was inside an `if` block; the
# current return is in the outer scope (lower indent),
# so the previous terminal is no longer relevant.
# Reset it so the multi-line return body is not flagged.
current_indent = len(line) - len(line.lstrip())
if found_terminal and terminal_indent > 0 and current_indent < terminal_indent:
found_terminal = False
continue # Return expression continues on the next line
found_terminal = True
terminal_line = i # 0-based: next line has i+1 > i = True
terminal_type = stripped.split()[0]
terminal_depth = brace_depth # v7: record depth of terminal statement
terminal_indent = len(lines[i]) - len(lines[i].lstrip()) # Python indent of terminal
# v5.10: Rust match arm separator — new arm starts after => or pattern
if ext == ".rs" and in_match:
# A new match arm pattern resets the terminal flag
if re.match(r'\s*[\w].*=>', stripped) or re.match(r'\s*_\s*=>', stripped):
found_terminal = False
continue
# Comma at match depth signals end of arm — next arm is not unreachable
if stripped.endswith(',') and brace_depth <= match_start_depth + 1:
found_terminal = False
continue
# v6: Detect function end via brace depth — only end function when
# depth returns to the level before the function started.
# This avoids resetting on every '}' (e.g. if-blocks inside functions).
if ext not in {".py", ".lua", ".ex", ".exs", ".rb"} and brace_depth < function_start_depth:
in_function = False
found_terminal = False
in_match = False
continue
# Lua: detect function end via 'end' keyword
if ext == ".lua" and stripped == 'end':
in_function = False
found_terminal = False
continue
# Elixir: detect function end via 'end' keyword
if ext in {".ex", ".exs"} and stripped == 'end':
in_function = False
found_terminal = False
continue
# Ruby: detect method end via 'end' keyword
if ext == ".rb" and stripped == 'end':
in_function = False
found_terminal = False
continue
# v7: If we've exited the scope where the terminal statement was found
# (e.g., closing brace of an if-block that contained a return),
# the code after the closing brace is still reachable.
# Reset found_terminal when brace depth drops to or below terminal_depth.
if found_terminal and ext != ".py" and brace_depth <= terminal_depth and stripped.startswith('}'):
found_terminal = False
continue
# Python: if the current line is at a lower indent than the
# terminal statement, we've exited the block containing the return.
# Code at this level is in a different branch and is reachable.
# Note: we use strict < (not <=) because code at the SAME indent
# as a return is in the same block and IS unreachable.
if ext == ".py" and in_function and found_terminal and terminal_indent > 0:
current_indent = len(line) - len(line.lstrip()) if stripped else 0
if current_indent < terminal_indent and stripped:
found_terminal = False
continue
# Check if we're at a lower indentation (function ended in Python)
if ext == ".py" and in_function and found_terminal:
current_indent = len(line) - len(line.lstrip()) if stripped else 0
if current_indent <= function_indent and stripped:
in_function = False
found_terminal = False
continue
# If we found a terminal statement and this is the next real code
_skip_prefixes = ('}', 'catch', 'except', 'elif', 'else', 'finally', '//', '#', 'end', '--')
# Elixir/Ruby: also skip 'rescue', 'after'
if ext in {".ex", ".exs"}:
_skip_prefixes = ('}', 'catch', 'except', 'elif', 'else', 'finally', '//', '#', 'end', 'rescue', 'after')
elif ext == ".rb":
_skip_prefixes = ('}', 'catch', 'except', 'elif', 'else', 'finally', '//', '#', 'end', 'rescue', 'ensure', 'elsif')
if found_terminal and i > terminal_line and not stripped.startswith(_skip_prefixes):
items.append({
"file": rel_path,
"line": i + 1,
"after": terminal_type,
"after_line": terminal_line + 1, # Convert to 1-based for output
"severity": "warning",
"message": f"Unreachable code after {terminal_type} on line {terminal_line + 1}",
"suggestion": f"Remove code after {terminal_type} or fix the control flow."
})
found_terminal = False # Only report first unreachable
elif found_terminal and stripped.startswith(('elif', 'else', 'except', 'finally')):
# New branch starts after a terminal statement — code in the new branch
# is reachable even though the previous branch had a return.
# Reset the terminal flag so we don't falsely flag code in this new branch.
found_terminal = False
return items
def _detect_unused_variables(content: str, ext: str, rel_path: str) -> List[Dict]:
"""Detect variables that are declared but never read."""
items = []
# Remove comments and strings for more accurate detection
clean_content = re.sub(r'//.*$', '', content, flags=re.MULTILINE)
# Use bounded quantifier to avoid catastrophic backtracking
clean_content = re.sub(r'/\*[\s\S]{0,50000}?\*/', '', clean_content)
if ext in {".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx"}:
# Find const/let/var declarations (including destructuring)
declared_vars = []
# Standard declarations: const/let/var x = ...
for m in re.finditer(r'(?:const|let|var)\s+(\w+)\s*=', clean_content):
declared_vars.append((m.group(1), m.start()))
# Object destructuring: const { a, b, c } = ...
for m in re.finditer(r'(?:const|let|var)\s*\{\s*([^}]+)\}\s*=', clean_content):
names_str = m.group(1)
for name_match in re.finditer(r'(\w+)(?:\s*:\s*\w+)?', names_str):
declared_vars.append((name_match.group(1), m.start()))
# Array destructuring: const [a, b, c] = ...
for m in re.finditer(r'(?:const|let|var)\s*\[\s*([^\]]+)\]\s*=', clean_content):
names_str = m.group(1)
for name_match in re.finditer(r'(\w+)', names_str):
declared_vars.append((name_match.group(1), m.start()))
for var_name, start_pos in declared_vars:
line_num = clean_content[:start_pos].count('\n') + 1
# Skip numeric literals that regex falsely captured as variable names
# (e.g., 300_000, 10000 from patterns like const 300_000 = ...)
if re.match(r'^\d[\d_]*$', var_name):
continue
# This detector only counts occurrences WITHIN THE SAME FILE
# (clean_content is this file's content). An `export const X = ...`
# is by definition meant to be used from OTHER files — this
# same-file heuristic has no way to see that usage and will always
# find exactly 1 occurrence (the declaration itself), false-flagging
# every exported value passed by reference elsewhere (e.g. Express
# middleware: `export const fooLimiter = rateLimit(...)` used as
# `app.post(path, fooLimiter)` in a different file — fooLimiter is
# never "called" or re-mentioned in its own file, so it looked
# unused here even though 3+ other files import and use it).
# Cross-file usage is `unused_exports`' job (it walks the import
# graph); this same-file scan must defer to it, not duplicate a
# weaker version of the same check.
_export_prefix = clean_content[max(0, start_pos - 20):start_pos]
if re.search(r'\bexport\s*$', _export_prefix):
continue
# Skip common patterns that are used indirectly
skip_names = {'_', 'e', 'err', 'error', 'res', 'req', 'ctx', 'props', 'state', 'ref', 'config', 'module'}
if var_name in skip_names or var_name.startswith('_'):
continue
# v6: Keep the ALL_CAPS skip but note that cross-file usage analysis
# would be more accurate. Constants like API_URL, MAX_RETRIES are
# typically used across files — skipping avoids false positives.
# TODO: Cross-file reference check for ALL_CAPS vars.
if var_name.isupper(): # Constants are often used elsewhere
continue
# Check if variable is used anywhere else in the file
# Count occurrences excluding the declaration
usage_pattern = r'\b' + re.escape(var_name) + r'\b'
all_occurrences = list(re.finditer(usage_pattern, clean_content))
if len(all_occurrences) <= 1:
items.append({
"file": rel_path,
"line": line_num,
"variable": var_name,
"severity": "info",
"message": f"Variable '{var_name}' declared but never used",
"suggestion": f"Remove unused variable '{var_name}' or prefix with _ to suppress."
})
elif ext == ".py":
# Find variable assignments (not in function signatures)
for m in re.finditer(r'^(\w+)\s*=\s*', clean_content, re.MULTILINE):
var_name = m.group(1)
line_num = clean_content[:m.start()].count('\n') + 1
skip_names = {'_', 'e', 'err', 'error', 'self', 'cls', 'main', 'logger'}
if var_name in skip_names or var_name.startswith('_'):
continue
# Skip Python type aliases: names ending in "Types" or "Type" that are
# type alias definitions (e.g., URLTypes = ..., HeaderTypes = ...).
# These are used in type annotations, not as runtime variables.
line_text = clean_content.split('\n')[line_num - 1] if line_num <= len(clean_content.split('\n')) else ''
if var_name.endswith('Types') or var_name.endswith('Type'):
# Check if RHS contains type-related patterns
rhs = line_text.split('=', 1)[1].strip() if '=' in line_text else ''
type_indicators = ['Union', 'Optional', 'List', 'Dict', 'Tuple', 'Set',
'Callable', 'Type', 'Sequence', 'Mapping', 'Iterable',
'AsyncIterator', 'Iterator', 'Any', 'Protocol',
'typing.', 'Annotated']
if any(ind in rhs for ind in type_indicators):
continue
# Skip TypeAlias annotations: e.g., URLTypes: TypeAlias = ...
if ': TypeAlias' in line_text or ': typealias' in line_text.lower():
continue
usage_pattern = r'\b' + re.escape(var_name) + r'\b'
all_occurrences = list(re.finditer(usage_pattern, clean_content))
if len(all_occurrences) <= 1:
items.append({
"file": rel_path,
"line": line_num,
"variable": var_name,
"severity": "info",
"message": f"Variable '{var_name}' assigned but never used",
"suggestion": f"Remove or use the variable."
})
# Detect unused Python imports
# Collect all import names and check if they're used in the file
import_names = [] # (name, line_num)
for m in re.finditer(r'^import\s+(\w+)', clean_content, re.MULTILINE):
name = m.group(1)
line_num = clean_content[:m.start()].count('\n') + 1
import_names.append((name, line_num))
for m in re.finditer(r'^from\s+[\w.]+\s+import\s+(.+)', clean_content, re.MULTILINE):
names_str = m.group(1)
line_num = clean_content[:m.start()].count('\n') + 1
for name_match in re.finditer(r'(\w+)', names_str):
name = name_match.group(1)
if name == 'as':
continue
import_names.append((name, line_num))
_import_skip = {'os', 'sys', 'logging'} # Commonly imported for side effects or implicit usage
_typing_imports = {'List', 'Dict', 'Tuple', 'Set', 'Optional', 'Union', 'Any',
'Callable', 'Iterable', 'Iterator', 'Sequence', 'Mapping',
'Type', 'TypeVar', 'Generic', 'Protocol', 'Awaitable',
'AsyncIterator', 'AsyncIterable', 'Coroutine', 'Final',
'ClassVar', 'Literal', ' overload', 'NamedTuple', 'TypedDict'}
for name, line_num in import_names:
if name in _import_skip:
continue
if name in _typing_imports:
continue # Typing imports are used in annotations, hard to detect via regex
if name.startswith('_'):
continue
# Check if the import is used in the file (not just the import line)
usage_pattern = r'\b' + re.escape(name) + r'\b'
all_occurrences = list(re.finditer(usage_pattern, clean_content))
if len(all_occurrences) <= 1:
items.append({
"file": rel_path,
"line": line_num,
"variable": name,
"severity": "info",
"message": f"Import '{name}' is never used",
"suggestion": f"Remove unused import '{name}'."
})
elif ext == ".go":
# Find variable declarations: var x type, x := expr
for m in re.finditer(r'(?:var\s+(\w+)\s+\w|(\w+)\s*:=)', clean_content):
var_name = m.group(1) or m.group(2)
line_num = clean_content[:m.start()].count('\n') + 1
skip_names = {'_', 'err', 'ok', 'ctx', 'req', 'res', 'w', 'r', 'b'}
if var_name in skip_names or var_name.startswith('_'):
continue
if var_name.isupper():
continue
usage_pattern = r'\b' + re.escape(var_name) + r'\b'
all_occurrences = list(re.finditer(usage_pattern, clean_content))
if len(all_occurrences) <= 1:
items.append({
"file": rel_path,
"line": line_num,
"variable": var_name,
"severity": "info",
"message": f"Variable '{var_name}' declared but never used",
"suggestion": f"Remove unused variable '{var_name}' or assign to '_'."
})
elif ext in {".c", ".cpp", ".cxx", ".cc", ".h", ".hpp", ".hxx"}:
# Find variable declarations: type name = ... or type name;
for m in re.finditer(r'(?:int|char|float|double|long|short|unsigned|void|auto|bool|size_t|ssize_t)\s+\*?\s*(\w+)\s*(?:=|;|\))', clean_content):
var_name = m.group(1)
line_num = clean_content[:m.start()].count('\n') + 1
skip_names = {'_', 'i', 'j', 'k', 'n', 'ret', 'rc', 'err', 'len', 'size', 'argc', 'argv'}
if var_name in skip_names or var_name.startswith('_'):
continue
if var_name.isupper():
continue
usage_pattern = r'\b' + re.escape(var_name) + r'\b'
all_occurrences = list(re.finditer(usage_pattern, clean_content))
if len(all_occurrences) <= 1:
items.append({
"file": rel_path,
"line": line_num,
"variable": var_name,
"severity": "info",
"message": f"Variable '{var_name}' declared but never used",
"suggestion": f"Remove unused variable '{var_name}' or cast to (void)."
})
elif ext == ".lua":
# Find local variable declarations: local name = ...
for m in re.finditer(r'local\s+(\w+)\s*=', clean_content):
var_name = m.group(1)
line_num = clean_content[:m.start()].count('\n') + 1
skip_names = {'_', 'self', 'err', 'ok', 'msg', 'k', 'v'}
if var_name in skip_names or var_name.startswith('_'):
continue
if var_name.isupper():
continue
usage_pattern = r'\b' + re.escape(var_name) + r'\b'
all_occurrences = list(re.finditer(usage_pattern, clean_content))
if len(all_occurrences) <= 1:
items.append({
"file": rel_path,
"line": line_num,
"variable": var_name,
"severity": "info",
"message": f"Variable '{var_name}' declared but never used",
"suggestion": f"Remove unused variable '{var_name}' or prefix with _."
})
elif ext == ".php":
# Find variable declarations: $name = ...
for m in re.finditer(r'\$(\w+)\s*=', clean_content):
var_name = m.group(1)
line_num = clean_content[:m.start()].count('\n') + 1
skip_names = {'_', 'this', 'e', 'err', 'request', 'response', 'app', 'router'}
if var_name in skip_names or var_name.startswith('_'):
continue
if var_name.isupper():
continue
usage_pattern = r'\$' + re.escape(var_name) + r'\b'
all_occurrences = list(re.finditer(usage_pattern, clean_content))
if len(all_occurrences) <= 1:
items.append({
"file": rel_path,
"line": line_num,
"variable": '$' + var_name,
"severity": "info",
"message": f"Variable '${var_name}' declared but never used",
"suggestion": f"Remove unused variable '${var_name}'."
})
elif ext == ".rs":
# Rust: let bindings and let mut bindings
# Find: let name = ... and let mut name = ...
for m in re.finditer(r'\blet\s+(?:mut\s+)?(\w+)\s*(?::|=\s*)', clean_content):
var_name = m.group(1)
line_num = clean_content[:m.start()].count('\n') + 1
skip_names = {'_', 'err', 'ok', 'e', 'ctx', 'req', 'res', 'buf', 'cfg', 'result', 'input', 'output', 'ret'}
if var_name in skip_names or var_name.startswith('_'):
continue
if var_name.isupper():
continue
# Skip common Rust patterns
if var_name in {'self', 'Self', 'true', 'false', 'None', 'Some', 'Ok', 'Err'}:
continue
usage_pattern = r'\b' + re.escape(var_name) + r'\b'
all_occurrences = list(re.finditer(usage_pattern, clean_content))
if len(all_occurrences) <= 1:
items.append({
"file": rel_path,
"line": line_num,
"variable": var_name,
"severity": "info",
"message": f"Variable '{var_name}' declared but never used",
"suggestion": f"Remove unused variable '{var_name}' or prefix with '_'."
})
elif ext in {".ex", ".exs"}:
# Elixir: variable assignments (name starts with lowercase)
for m in re.finditer(r'\b([a-z]\w*)\s*=\s*(?!=)', clean_content):
var_name = m.group(1)
line_num = clean_content[:m.start()].count('\n') + 1
skip_names = {'_', 'e', 'err', 'error', 'result', 'response', 'state', 'socket', 'conn', 'params', 'assigns'}
if var_name in skip_names or var_name.startswith('_'):
continue
# Skip Elixir special forms and common patterns
if var_name in {'def', 'defp', 'defmodule', 'do', 'end', 'true', 'false', 'nil', 'when', 'fn', 'use', 'import', 'alias', 'require'}:
continue
usage_pattern = r'\b' + re.escape(var_name) + r'\b'
all_occurrences = list(re.finditer(usage_pattern, clean_content))
if len(all_occurrences) <= 1:
items.append({
"file": rel_path,
"line": line_num,
"variable": var_name,
"severity": "info",
"message": f"Variable '{var_name}' assigned but never used",
"suggestion": f"Remove or prefix with '_'."
})
elif ext == ".rb":
# Ruby: local variable assignments (name = value)
for m in re.finditer(r'\b([a-z_]\w*)\s*=\s*', clean_content):
var_name = m.group(1)
line_num = clean_content[:m.start()].count('\n') + 1
skip_names = {'_', 'e', 'err', 'error', 'result', 'response', 'request', 'params', 'session'}
if var_name in skip_names or var_name.startswith('_'):
continue
if var_name in {'def', 'class', 'module', 'do', 'end', 'if', 'else', 'elsif', 'unless', 'true', 'false', 'nil', 'return', 'require', 'include', 'extend'}:
continue
usage_pattern = r'\b' + re.escape(var_name) + r'\b'
all_occurrences = list(re.finditer(usage_pattern, clean_content))
if len(all_occurrences) <= 1:
items.append({
"file": rel_path,
"line": line_num,
"variable": var_name,
"severity": "info",
"message": f"Variable '{var_name}' assigned but never used",
"suggestion": f"Remove or prefix with '_'."
})
return items[:100] # Cap to avoid noise
def _collect_js_exports_imports(
content: str, ext: str, rel_path: str,
exports: Dict[str, List[Dict]], imports: Dict[str, Set[str]]
):
"""Collect JS/TS export and import declarations."""
# Named exports: export const/function/class/abstract class/async function X
for m in re.finditer(r'export\s+(?:abstract\s+)?(?:const|let|var|function|class|async\s+function)\s+(\w+)', content):
exports[rel_path].append({
"name": m.group(1),
"type": "named_export",
"line": content[:m.start()].count('\n') + 1
})
# TypeScript-specific exports: export interface/type/enum/declare
if ext in {'.ts', '.tsx'}:
for m in re.finditer(r'export\s+(?:interface|type|enum|declare\s+const|declare\s+function|declare\s+class)\s+(\w+)', content):
exports[rel_path].append({
"name": m.group(1),
"type": "ts_export",
"line": content[:m.start()].count('\n') + 1
})
# Default exports
for m in re.finditer(r'export\s+default\s+(?:function\s+)?(\w+)', content):
exports[rel_path].append({
"name": m.group(1) or "default",
"type": "default_export",
"line": content[:m.start()].count('\n') + 1
})
# Re-exports: export { X } from ... vs local exports: export { X }
# export { X } without 'from' is a local definition being made public API.
# export { X } from './other' is a re-export from another module.
# export type { X } from './other' is a TypeScript type-only re-export.
# We distinguish these because local exports should not be flagged as unused
# (they are intentionally public API), while re-exports from other modules
# may be unnecessary if nothing imports them.
#
# Bug fix: a re-export ("export {X} from './y'" or "export type {X} from
# './y'") consumes X from the source module './y' — it IS a usage of X as
# far as the source file's own unused-exports check is concerned. Without
# recording these names in `imports`, any symbol that is only ever
# re-exported (never plain-imported) is incorrectly flagged as unused in
# its defining file (found via real-codebase validation: ProductAccess in
# google-auth-cache.ts, re-exported via `export type {...} from` in
# google-auth.ts, was a false positive).
for m in re.finditer(r'export\s+(?:type\s+)?\{([^}]+)\}(\s+from\s+[\'"\w./@-]+)?', content):
has_from = m.group(2) is not None
export_type = "re_export" if has_from else "local_export"
names = [n.strip().split(' as ')[0].strip() for n in m.group(1).split(',')]
for name in names:
if name:
exports[rel_path].append({
"name": name,
"type": export_type,
"line": content[:m.start()].count('\n') + 1
})
if has_from:
imports[rel_path].add(name)
# Imports (including TypeScript type-only imports)
for m in re.finditer(r'import\s+(?:type\s+)?(?:\{([^}]+)\}|\*\s+as\s+(\w+)|(\w+))\s+from', content):
if m.group(1): # Named imports
names = [n.strip().split(' as ')[0].strip() for n in m.group(1).split(',')]
for name in names:
if name:
imports[rel_path].add(name)
elif m.group(2): # Namespace import