Be thorough — I need exact function signatures, line counts, and repeated patterns to plan a clean refactor.
Assistant
I'll conduct a thorough exploration of the TypeScript smell detection code. Let me start with parallel searches to understand the structure.
Assistant
Now let me search for imports of these modules across the codebase:
Assistant
Let me read the react.py and fixer files to understand how they use the smell helpers:
Assistant
Now let me check the syntax scanner source to understand scan_code:
Assistant
Perfect! Now let me count the lines and get a summary of the test file organization:
Assistant
Excellent! Now let me create a comprehensive analysis document. Let me read a bit more of the _effects file reference to confirm the refactor status:
Assistant
Good—the file only exists in build/, meaning it's been merged into _smell_detectors.py. Now let me count the individual detector functions and their line ranges:
Assistant
User
Assistant
I'll start by thoroughly exploring the current codebase to understand the exact state of each file, then design a concrete plan.
Assistant
Now let me look at the test files, external consumers, and the existing _smell_effects.py to understand the full picture.
Assistant
Now let me check the external consumers more closely and the test_direct_coverage_modules file.
Assistant
Now let me check the __init__.py for the detectors package and see if there's already an __all__ or re-export pattern.
Assistant
Now let me look more closely at the brace-tracking patterns in react.py to understand whether those could also benefit from the shared utility.
Assistant
Now let me catalog every brace-tracking instance precisely to determine which can use _extract_block_body vs. which have unique needs.
Assistant
Let me now look at the line-info extraction pattern in all three instances in _smell_detectors.py to confirm they're structurally identical.
Assistant
Good. Now let me check the react.py line-info pattern too, and see the full structure of the _detect_dead_useeffects brace tracking (it tracks parens, not braces, which is different).
Assistant
Now I have a thorough understanding of all the code. Let me also check the _detect_async_no_await detector more carefully -- it does NOT use the standard brace-tracking pattern, it builds code_chars manually.
Assistant
Perfect! Now let me generate the comprehensive analysis report.
Comprehensive Analysis of TypeScript Smell Detection Code
I've thoroughly explored the TypeScript smell detection architecture post-refactor. Here's the complete technical breakdown:
1. _smell_detectors.py (710 lines)
Total Detectors: 12 main detector functions + 6 internal helper functions
The recent refactor merged _smell_effects.py into _smell_detectors.py, consolidating all 12 multi-line detector functions. The code is well-organized with clear helper functions, but exhibits 4-5 repeated patterns that could be abstracted. The test coverage is comprehensive (49 test methods across 13 test classes), with excellent use of _make_counts() helper. The orchestrator in smells.py cleanly separates regex-based detection from multi-line analysis, though the mixing of different input types (content vs. lines) suggests an opportunity for API standardization.
I'm designing a refactor plan to make the TypeScript smell detection code "beautiful" after an initial consolidation that merged 4 files into 3. The current state:
_smell_helpers.py (206 lines) — utilities: _strip_ts_comments, _ts_match_is_in_string, _track_brace_body, _build_ts_line_state, scan_code re-export. Also has import re that's now unused.
_smell_detectors.py (710 lines) — 12 detectors + 6 helpers, with a visible "merged detectors" seam at line 444. Key problems:
Brace-depth tracking loop is inlined 5+ times (same 10-line pattern)
_find_block_end exists but isn't actually called — detectors inline the same logic
Line-number-from-content-position calculated manually 3+ times (same 4-line pattern)
Detector signatures are inconsistent: 5 take (filepath, lines, counts), 2 take (filepath, content, counts), 3 take (filepath, content, lines, counts), 1 takes (filepath, lines, line_state, counts)
No __all__
smells.py (398 lines) — orchestrator imports 12 detector names individually, calls each with different argument patterns
Repeated patterns that should be extracted:
Pattern 1 — Brace-depth tracking (appears 5+ times in detectors):
python
depth = 0
body_end = None
for ci, ch, in_s in scan_code(content, brace_start, min(brace_start + N, len(content))):
if in_s: continue
if ch == "{": depth += 1
elif ch == "}":
depth -= 1
if depth == 0: body_end = ci; break
if body_end is None: continue
body = content[brace_start + 1 : body_end]
Pattern 2 — Line info from content position (appears 3 times):
Refactor _find_block_end from _smell_detectors to _smell_helpers — it's a utility, not a detector
Data-driven orchestrator in smells.py:
python
_MULTI_LINE_DETECTORS = [_detect_async_no_await, _detect_catch_return_default, ...]
ctx = _FileContext(filepath, content, lines, line_state)
for detector in _MULTI_LINE_DETECTORS:
detector(ctx, smell_counts)
__all__ on both modules
Remove import re from _smell_helpers.py (unused after prior refactor)
Reorganize _smell_detectors.py: helpers at top, detectors alphabetical, remove merge seam
Constraints:
External consumers (react.py, fixers/syntax_scan.py, fixers/if_chain.py) import _strip_ts_comments, _ts_match_is_in_string, scan_code — these APIs must not change
Tests in test_ts_smell_helpers.py (499 lines) will need mechanical updates for _FileContext
Design a concrete implementation plan with clear steps and file-by-file changes. Consider: which detectors actually benefit from _extract_block_body? Which ones have unique brace-tracking needs that can't use it? Is the test refactor tractable? What's the right test helper to make _FileContext less verbose in tests?
Now I have a complete picture. Let me compile the detailed analysis and plan.
I found 8 distinct depth = 0 brace/paren tracking loops in _smell_detectors.py. Here is each one classified by whether it can use a shared _extract_block_body utility:
CAN use _extract_block_body(content, brace_start, max_scan) -- the "content + offset" variant:
These all follow the identical pattern: find the closing } from a known brace_start position in the content string, then extract content[brace_start+1 : body_end].
Line
Detector
max_scan
Notes
218
_detect_catch_return_default (outer catch body)
_MAX_CATCH_BODY (1000)
Standard pattern
244
_detect_catch_return_default (inner returned object)
len(body) (no limit)
Same pattern but operates on extracted body substring
402
_detect_switch_no_default
_MAX_SWITCH_BODY_SCAN (5000)
Standard pattern
635
_detect_dead_useeffects (inner brace body)
len(text) (no limit)
Standard pattern, operates on text substring
664
_detect_swallowed_errors
500
Standard pattern
CANNOT use _extract_block_body -- unique logic:
Line
Detector
Why unique
31
_find_block_end (existing utility)
This IS the utility -- it just returns the end position, not the body
465
_detect_async_no_await
Builds code_chars per-line while tracking braces; checks for await during traversal. Fundamentally different control flow -- interleaves "find body" with "inspect body"
608
_detect_dead_useeffects (paren tracking)
Tracks parentheses, not braces. Different delimiter
Key insight: _detect_async_no_await absolutely cannot use _extract_block_body because it needs to accumulate code-only chars line-by-line and check for await during the scan. Extracting the body first and then searching would lose the comment-stripping behavior that comes from scan_code. It could theoretically be rewritten to use _extract_function_body + search stripped body, but it operates on content/lines, not line-indexed body -- and the current approach is actually more efficient (single pass). Leave it alone.
2. Line-Info Pattern Analysis
Three instances in _smell_detectors.py (lines 269, 431, 701) plus one in react.py (line 113):
Lines 269 and 431 are structurally identical -- both compute line_no, line_start, line_end, and produce content[line_start:line_end].strip()[:100].
Line 701 is slightly different -- it uses lines[line_no - 1].strip()[:100] instead of slicing content. This is because _detect_swallowed_errors has access to lines already. But _content_line_info can still be used here (it would return the snippet from content slicing, which is equivalent).
Proposed _content_line_info(content, pos) -> tuple[int, str] returns (line_number_1indexed, snippet_stripped_100chars). This cleanly replaces all three instances. The react.py instance (line 113) is out of scope for this refactor but could adopt it later.
The _FileContext NamedTuple solves this perfectly: every detector gets the same (ctx, smell_counts) signature. Detectors that only need lines just access ctx.lines. Detectors that need content access ctx.content. The line_state field is always available but only _detect_window_globals uses it.
This is cheap -- content and lines are already computed in the orchestrator, and line_state is already computed too. No new computation, just bundling.
4. Concrete Step-by-Step Plan
Phase 1: Add utilities to _smell_helpers.py (no behavioral changes)
Update imports: add _FileContext, _extract_block_body, _content_line_info, _find_block_end from _smell_helpers. Remove _find_block_end definition from this file.
Change all 12 detector signatures to (ctx: _FileContext, smell_counts: dict[str, list[dict]]). Internally, unpack what they need:
Detectors that used filepath now use ctx.filepath
Detectors that used lines now use ctx.lines
Detectors that used content now use ctx.content
_detect_window_globals uses ctx.line_state
Replace inline brace-tracking with _extract_block_body in these 4 detectors:
Replace line-info computation with _content_line_info in 3 places:
_detect_catch_return_default (line 269)
_detect_switch_no_default (line 431)
_detect_swallowed_errors (line 701): currently uses lines[line_no - 1] for snippet. Switch to _content_line_info for consistency; verify the output is identical (it will be, since lines comes from content.splitlines()).
Do NOT touch these detectors' internal logic:
_detect_async_no_await: unique single-pass brace+await scanning. Only change is signature.
_detect_dead_useeffects: has paren tracking (lines 608-622) which is unique, plus a secondary brace tracking (lines 635-646) which could use _extract_block_body on the text substring. Do refactor the secondary brace tracking at line 635 to use _extract_block_body(text, brace_pos). Leave the paren tracking alone.
Expected result: _smell_detectors.py shrinks from 710 to ~620 lines. The 5 inline brace-tracking loops (across 4 detectors) reduce to 5 one-liner calls to _extract_block_body. The 3 line-info computations reduce to 3 one-liner calls to _content_line_info.
Replace the 12 individual detector imports with a single import of the detector list, or keep explicit imports (for IDE support) but replace the 12-line call block with a loop.
Build _FileContext once per file in the loop body (line ~335):
Replace the 12 individual calls (lines 366-377) with:
python
for detector in _MULTI_LINE_DETECTORS:
detector(ctx, smell_counts)
Expected result: smells.py stays roughly the same size but the call site shrinks from 12 lines to 2, and adding a new detector becomes adding it to one tuple.
from desloppify.languages.typescript.detectors._smell_helpers import _FileContext
def _ctx(content: str, filepath: str = "test.ts") -> _FileContext:
"""Build a _FileContext for testing."""
lines = content.splitlines()
from desloppify.languages.typescript.detectors._smell_helpers import _build_ts_line_state
line_state = _build_ts_line_state(lines)
return _FileContext(filepath, content, lines, line_state)
Update all detector test calls. The changes are mechanical -- every test that calls a detector directly needs to pass ctx instead of positional args. Examples:
Or for the test that passes a custom line_state = {0: "block_comment"}, build the context manually.
For tests that construct lines as a list (not from content), add the "\n".join(lines) call to build content. This is the case for: TestDetectErrorNoThrow, TestDetectEmptyIfChains, TestDetectDeadUseeffects, TestDetectWindowGlobals, TestDetectMonsterFunctions, TestDetectStubFunctions.
For TestDetectWindowGlobals.test_skips_lines_in_block_comment, the test passes a custom line_state = {0: "block_comment"}. The _ctx helper would compute its own line_state, so this test needs to build _FileContext manually:
python
This is tractable: 19 test methods that call detectors directly, each needing a 1-line change to argument construction.
Line 178 references ts_smell_detectors._detect_swallowed_errors. This is just checking the function is callable -- no signature change needed. The assert callable(...) still works.
Phase 5: New utility tests
Add tests in test_ts_smell_helpers.py for the new utilities:
python
class TestExtractBlockBody:
def test_simple_block(self):
content = "catch (e) { console.log(e); }"
body = _extract_block_body(content, 10) # position of {
assert body is not None
assert "console.log" in body
def test_returns_none_on_unclosed(self):
assert _extract_block_body("{ unclosed", 0) is None
class TestContentLineInfo:
def test_first_line(self):
content = "line one\nline two\nline three"
line_no, snippet = _content_line_info(content, 2) # position in "line one"
assert line_no == 1
assert snippet == "line one"
def test_middle_line(self):
content = "line one\nline two\nline three"
line_no, snippet = _content_line_info(content, 12) # position in "line two"
assert line_no == 2
assert snippet == "line two"
5. Risk Assessment and Edge Cases
Risk: _extract_block_body behavioral equivalence. The inline loops do content[brace_start + 1 : body_end]. The utility must do the same. The key subtlety is that _find_block_end returns the position of the closing } itself, so content[brace_start + 1 : body_end] excludes both { and }. This matches the inline pattern exactly.
Risk: _detect_catch_return_default nested call. This detector calls _extract_block_body on the extracted body substring for the inner object. The brace_start for the inner call is relative to body, not content. This works correctly because _extract_block_body operates on whatever string is passed.
Risk: _detect_dead_useeffects secondary brace tracking. The text variable is built from "\n".join(lines[line_no:end_line + 1]), and brace_pos is an offset within text. Using _extract_block_body(text, brace_pos) works correctly.
Risk: Test _ctx helper computing line_state. For most tests this is fine -- the _build_ts_line_state call is cheap. The exception is TestDetectWindowGlobals.test_skips_lines_in_block_comment where the test needs a specific line_state to simulate being inside a block comment. This test must manually construct _FileContext rather than using _ctx.
Risk: External consumers.react.py, fixers/syntax_scan.py, and fixers/if_chain.py import _strip_ts_comments, _ts_match_is_in_string, and scan_code from _smell_helpers. These APIs are unchanged. _find_block_end is moving from _smell_detectors to _smell_helpers, but nobody outside _smell_detectors imports it. Safe.
6. Sequencing and Dependencies
The phases can be done in order but Phases 1-3 should ideally be a single commit (since Phase 3 depends on the signature changes in Phase 2, which depend on Phase 1's utilities). Phase 4 (tests) is tied to Phases 2-3.
Recommended commit structure:
Single commit: All of Phases 1-5 together. The refactor is purely mechanical and the tests validate correctness. Splitting across commits would create a state where tests fail.
Alternatively, if you want reviewable intermediate states:
Commit A: Phase 1 only (add utilities to _smell_helpers.py). Tests still pass since no signatures changed.
-3 (12-line call block -> tuple + loop, net wash with new imports)
test_ts_smell_helpers.py
500
~520
+20 (_ctx helper, new utility tests, slightly longer ctx construction lines)
Net
1814
~1785
-29
The real win is not line count but repetition elimination: 5 brace-tracking loops -> 5 one-liners, 3 line-info computations -> 3 one-liners, 5 different detector signatures -> 1 uniform signature.
/Users/user_c042661f/Documents/desloppify/desloppify/languages/typescript/detectors/_smell_detectors.py - Unify all 12 detector signatures to (ctx, counts), replace inline brace/line-info patterns with utility calls, reorganize alphabetically, add __all__
/Users/user_c042661f/Documents/desloppify/desloppify/languages/typescript/detectors/smells.py - Build _FileContext in loop, data-driven detector dispatch via _MULTI_LINE_DETECTORS tuple
/Users/user_c042661f/Documents/desloppify/desloppify/languages/typescript/tests/smells/test_ts_smell_helpers.py - Add _ctx test helper, mechanically update all 19 detector test call sites, add tests for new utilities
/Users/user_c042661f/Documents/desloppify/desloppify/tests/commands/test_direct_coverage_modules.py - Verify _detect_swallowed_errors callable check still works (likely no change needed)
Full content string input
Detects switch statements with ≥ 2 cases but no default
Uses scan_code() to extract switch body, then regex to check for \bcase\s+ and \bdefault\s*: