Explore the TypeScript smell detection code to understand what could be made more elegant. Focus on:
Read desloppify/languages/typescript/detectors/_smell_detectors.py — look at each detector function and identify:
Which ones have complex/gnarly logic that could be simplified
Which ones duplicate patterns that helpers already solve (e.g., _extract_function_body exists but _detect_stub_functions does manual body extraction)
The overall organization — are there natural groupings?
Read desloppify/languages/typescript/detectors/_smell_helpers.py — understand the full set of utilities available
Read desloppify/languages/typescript/detectors/smells.py — look at the orchestrator for any remaining awkwardness
Check desloppify/languages/typescript/tests/smells/test_ts_smell_helpers.py and desloppify/languages/typescript/tests/smells/test_ts_smells.py for test patterns
Thoroughness: very thorough. I want a detailed inventory of every remaining ugliness or inconsistency.
Assistant
I'll conduct a thorough exploration of the TypeScript smell detection code to identify elegance issues and opportunities for improvement.
Assistant
Now let me read the test files to understand test patterns and potential issues:
Assistant
Let me search for the other test file:
Assistant
Let me read the test_ts_smells.py file:
Assistant
Now let me examine the text_api module and syntax scanner to understand what utilities are available:
Assistant
Now let me look at a few more key areas to understand potential patterns. Let me check how _find_opening_brace_line is used elsewhere and understand edge cases:
Assistant
Let me check if there are any deleted files referenced in the git status to understand context:
Assistant
Let me check the git log to understand what was deleted:
Assistant
Perfect. Now let me check what _smell_effects.py was (since it was deleted):
Assistant
User
Assistant
I'll start by thoroughly reading the current source files to understand the exact code structure before designing the plan.
Assistant
Now let me read the test files to understand what needs to remain stable.
Assistant
Now let me check the scanner module that provides scan_code, since the _code_text helper will likely leverage it.
Assistant
Now let me also check if there are any other importers of the internal helpers to understand the blast radius.
Assistant
Good. Let me also check the react.py importer to understand its usage.
Assistant
Now I have a thorough understanding of all three files, the tests, the scanner module, and the import graph. Let me also quickly verify the _smell_effects.py deletion in the git status to make sure there are no references to it.
Assistant
Good, no remaining references. Now let me verify the text_api module to see what strip_c_style_comments does, since _code_text might delegate to it.
Assistant
Excellent! Now I have comprehensive context. Let me compile the detailed inventory of elegance issues and inconsistencies:
Detailed Inventory of TypeScript Smell Detection Elegance Issues
I've completed a very thorough analysis of the TypeScript smell detection code across _smell_detectors.py, _smell_helpers.py, smells.py, and their test files. Here's my comprehensive inventory of every remaining ugliness and inconsistency:
SECTION 1: DUPLICATE / REDUNDANT CODE PATTERNS
1.1 Duplicate brace-finding logic in _detect_stub_functions
File:_smell_detectors.py lines 502-507 Issue: Manual brace finding is duplicated here:
python
brace_line = None
for k in range(i, min(i + 5, len(ctx.lines))):
if "{" in ctx.lines[k]:
brace_line = k
break
Problem: This is identical to the loop inside _find_opening_brace_line() (lines 104-108). The function already exists and should be called instead. Ugliness: Violates DRY principle; increases maintenance burden.
1.2 Duplicate body extraction in _detect_stub_functions
File:_smell_detectors.py lines 516-522 Issue: Manual body extraction:
python
body_text = "\n".join(ctx.lines[brace_line : end_line + 1])
first_brace = body_text.find("{")
last_brace = body_text.rfind("}")
if first_brace == -1 or last_brace == -1 or first_brace >= last_brace:
continue
body = body_text[first_brace + 1 : last_brace]
Problem: This is nearly identical to _extract_function_body() lines 124-129, except that function returns None on error while this uses continue. Should use the helper. Ugliness: Copy-paste anti-pattern; two sources of truth for body extraction logic.
1.3 Duplicate error handler filename checking
File:_smell_detectors.py lines 379-381 Issue: In _detect_error_no_throw():
python
basename = os.path.basename(ctx.filepath).lower()
basename_no_ext = os.path.splitext(basename)[0]
if any(tag in basename_no_ext for tag in _ERROR_HANDLER_BASENAMES):
return
Problem: This filename filtering logic is not reusable and is specific to one detector. Should be extracted to a helper if the pattern is needed elsewhere. Ugliness: Mixes file-level filtering logic into detector; hard to test or reuse.
SECTION 2: INCONSISTENT PATTERNS & NAMING
2.1 Inconsistent context parameter naming
File:_smell_detectors.py throughout Issue: All detectors accept (ctx: _FileContext, smell_counts), but some old tests use filepath directly. The refactored code uses ctx.filepath, ctx.content, ctx.lines, ctx.line_state, but the original deleted _smell_effects.py used flat (filepath, lines, smell_counts) signatures. Ugliness: The migration is complete but shows historical inconsistency in API design.
2.2 Inconsistent max_scan parameter usage
File:_smell_detectors.py Issue: Different detectors use different max_scan values with no clear justification:
_detect_stub_functions() line 511: max_scan=30
_detect_high_cyclomatic_complexity() line 413: delegates to _extract_function_body() which uses max_scan=2000 hardcoded in line 121
_detect_swallowed_errors() line 542: max_scan=500
_detect_catch_return_default() line 225: uses _MAX_CATCH_BODY = 1000 constant
_detect_switch_no_default() line 578: uses _MAX_SWITCH_BODY_SCAN = 5000 constant
Problem: No clear rationale for these numbers. Stub functions are small but only scanned 30 lines? Inconsistency suggests accidental variation. Ugliness: Magic numbers scattered; unclear heuristics.
2.3 Inconsistent line number reporting
File:_smell_detectors.py Issue: Two different patterns for reporting line numbers:
python
# Pattern A: Direct line counting (lines 203-208)
smell_counts["async_no_await"].append({
"file": ctx.filepath,
"line": i + 1,
"content": f"async {name or '(anonymous)'} has no await",
})
# Pattern B: Via _content_line_info helper (lines 248, 562, 590)
line_no, snippet = _content_line_info(ctx.content, m.start())
smell_counts["catch_return_default"].append({
"file": ctx.filepath,
"line": line_no,
"content": snippet,
})
Problem: Pattern A uses raw i + 1 while Pattern B uses the helper. Inconsistent even for similar detectors. Ugliness: Two ways to do the same thing; some detectors could use the helper but don't.
2.4 Inconsistent empty check patterns
File:_smell_detectors.py Issue: Three different ways to check if body is empty:
python
# Pattern 1 (line 299): _strip_ts_comments().strip() == ""
if _strip_ts_comments(body).strip() == "":
# Pattern 2 (line 525): rstrip(";") then compare to known values
body_clean = _strip_ts_comments(body).strip().rstrip(";")
if body_clean in ("", "return", "return null", "return undefined"):
# Pattern 3 (line 546): check length of cleaned statements
if not body_clean: # After strip()
Ugliness: No consistent idiom; makes intent unclear.
SECTION 3: COMPLEX / GNARLY LOGIC
3.1 _detect_empty_if_chains() is extremely complex (lines 305-371)
File:_smell_detectors.py lines 305-371 Issue: This is a 67-line function with nested loops, multiple regex patterns, and state tracking. It handles two cases:
Single-line empty if chains (lines 316-332)
Multi-line empty if chains (lines 334-369)
The logic is hard to follow due to:
Multiple nested while loops with continue statements
Lookahead logic (lines 349-354)
Complex state variable chain_all_empty
Seven different regex patterns
Example of gnarliness (lines 344-356):
python
elif re.match(r"\}\s*else\s+if\s*\([^)]*\)\s*\{\s*$", current):
pass
elif re.match(r"\}\s*else\s*\{\s*$", current):
pass
elif current == "}":
tail = cursor + 1
while tail < len(ctx.lines) and ctx.lines[tail].strip() == "":
tail += 1
if tail < len(ctx.lines) and re.match(r"else\s", ctx.lines[tail].strip()):
cursor = tail
continue
cursor += 1
break
Ugliness: Hard to understand control flow; high cyclomatic complexity itself; hard to test individual cases.
3.2 _build_ts_line_state() has nested state machine for template literals (lines 152-272)
File:_smell_detectors.py lines 160-209 Issue: The function builds "code-only" text by calling scan_code() but then does its own filtering:
python
for _, ch, in_s in scan_code(body_line):
if in_s:
continue
# ... then manually accumulates code_chars ...
if ch == "/" and prev_code_ch == "/":
break # Rest of line is comment
But scan_code() already handles strings. The manual comment-detection (// check) is redundant because scan_code() doesn't strip comments — only the detector needs to handle them separately.
# First extraction: catch block body
body = _extract_block_body(ctx.content, m.end() - 1, _MAX_CATCH_BODY)
# ...
# Second extraction: object literal inside the body
obj_start = body.find("{", return_obj.start())
obj_content = _extract_block_body(body, obj_start)
The second extraction is on a substring (body) that was already extracted. Using _extract_block_body() on a substring that doesn't include surrounding context is fragile.
Ugliness: Nested block extraction on substings; position offsets may be incorrect.
SECTION 4: MISSING OR WEAK ABSTRACTIONS
4.1 No unified detector registration pattern
File:smells.py lines 36-49 and 354-384 Issue: Multi-line detectors are registered in a tuple _MULTI_LINE_DETECTORS and called generically, but single-line (regex-based) detectors are iterated inline in detect_smells() with explicit pattern checking.
Ugliness: Two different registration/dispatch mechanisms; harder to extend.
4.2 String-in-match checking duplicated across detectors
File:_smell_detectors.py Issue: Every regex-based check in smells.py lines 362-367 does:
python
if _ts_match_is_in_string(line, m.start()):
continue
This is done in the orchestrator, not the detectors, but there's no pattern for multi-line detectors to reuse it.
Ugliness: String-literal skipping logic is scattered; some detectors reinvent it.
4.3 No unified "skip file type" helper
File:_smell_detectors.py lines 379-382 Issue: Only _detect_error_no_throw() skips logger/error-handler files. This logic should be reusable. Ugliness: File-type filtering is ad-hoc; not composable.
File:_smell_detectors.py line 121 Issue: The _extract_function_body() function calls _track_brace_body() with hardcoded max_scan=2000, but callers may want different limits (e.g., stub functions only need 30).
Ugliness: No way to override; forces parameter-passing chains.
5.3 Cyclomatic complexity thresholds scattered
File:_smell_detectors.py line 418 Issue: Hardcoded threshold complexity > 15. Should be a constant. Ugliness: Magic number; not configurable.
5.4 Monster function LOC threshold hardcoded
File:_smell_detectors.py line 448 Issue:loc > 150 is hardcoded. Ugliness: Magic number; would be useful to tune.
5.5 Inconsistent order of parameters across functions
File: Multiple Issue:
_extract_block_body(content: str, brace_start: int, max_scan: int = 5000)
_extract_function_body(lines: list[str], start_line: int,) — no max_scan parameter
Ugliness: Inconsistent signatures; content vs. lines representation.
SECTION 6: TESTING & COVERAGE GAPS
6.1 Test file imports raw detectors but not helpers
File:test_ts_smell_helpers.py lines 3-22 Issue: The file is titled "test_ts_smell_helpers" but imports _smell_detectors and tests detector functions, not pure helpers.
Ugliness: File naming is misleading; test organization unclear.
6.2 No tests for _find_opening_brace_line()
File:test_ts_smell_helpers.py Issue:_find_opening_brace_line() is tested indirectly via _find_function_start() tests, but not directly. Ugliness: Partial coverage; edge cases may be missed.
6.3 No tests for pattern-in-body functions
File: Missing Issue:_count_pattern_in_body() (lines 132-142) and _compute_ts_cyclomatic_complexity() (lines 145-154) have no direct tests. Ugliness: Utility functions untested; regressions undetected.
6.4 Test context helper _ctx() doesn't match real scenario
line_state={} is always empty, but real code uses _build_ts_line_state(). Some detectors rely on line_state (e.g., _detect_window_globals() line 618) and won't be tested against actual block comments.
File:_smell_helpers.py lines 152-272 Issue: For every file, this function scans every character sequentially. For large files, this is slow.
Ugliness: No caching; called for every file.
7.3 _detect_empty_if_chains() has O(n²) complexity
File:_smell_detectors.py lines 305-371 Issue: Multiple nested loops with index jumping make worst-case O(n²). Ugliness: Inefficient; would be slow on large files.
SECTION 8: DOCUMENTATION & CLARITY ISSUES
8.1 Detector docstrings lack clarity on edge cases
File: Throughout _smell_detectors.py Example:_detect_error_no_throw() (lines 374-401) says it finds console.error "not followed by throw/return" but the actual lookahead is only 3 lines. The docstring doesn't explain this horizon.
8.2 _detect_catch_return_default() docstring is vague
File:_smell_detectors.py lines 212-222 Issue: Says it finds "default/no-op values" but doesn't specify the threshold (2 fields) or the specific patterns.
Ugliness: Hard to understand without reading code.
8.3 Regex patterns in smells.py lack explanation
File:smells.py lines 52-235 Issue: Many regex patterns have no comments explaining their intent or edge cases.
Ugliness: Maintenance burden; unclear what's being matched.
SECTION 9: INCONSISTENCIES WITH DELETED CODE
9.1 Detector signature refactoring is incomplete
File: Comparison of current vs. deleted _smell_effects.py Issue: The old code in _smell_effects.py had simpler signatures:
The refactor is complete, but the old patterns are still evident in tests (which had to be updated to work with _ctx helper).
Ugliness: Refactor is done but shows architectural change over time.
9.2 Old track_brace_body() function duplicated as _track_brace_body()
File: Old _smell_effects.py had track_brace_body() (exported); now _track_brace_body() (private in _smell_helpers.py) Issue: The refactor renamed and moved it but the logic is essentially identical. Ugliness: Refactor history is visible; could have unified from the start.
SECTION 10: MISSING OPTIMIZATIONS & ENHANCEMENTS
10.1 No lazy evaluation of detector functions
File:smells.py lines 382-384 Issue:
python
for detector in _MULTI_LINE_DETECTORS:
detector(ctx, smell_counts)
All detectors run on every file, even if earlier detectors found issues or file type is irrelevant. Ugliness: No short-circuit or early-exit logic.
10.2 No detector for "excessive parameters" (long parameter lists)
File: Missing detector Issue: High-arity functions are a smell but there's no detector for them. Ugliness: Incomplete coverage; parameter count thresholds are omitted.
10.3 No detector for "deeply nested blocks"
File: Missing detector Issue: There's a nested_closure detector but no detector for deeply nested if/for/while blocks. Ugliness: Incomplete coverage.
SECTION 11: REGEX ANTI-PATTERNS
11.1 Regex patterns use overly-broad capture groups
File:_smell_detectors.py line 610-616 Issue: The window_re has 3 capturing groups, but only 2 are used:
python
name = m.group(1) or m.group(2) # Where's group(3)?
Ugliness: Unused groups confuse readers; error-prone.
11.2 No use of raw strings for all regex patterns
File: Various Issue: Some patterns use raw strings (r"...") but others don't. Inconsistent. Ugliness: Style inconsistency; harder to read escapes.
SECTION 12: OVERALL ARCHITECTURE OBSERVATIONS
12.1 Two-tier detection system (regex + multi-line) is inelegant
File:smells.py lines 354-384 Issue: The system has two detection modes:
Regex-based (single-line, orchestrated centrally)
Multi-line (brace-tracked, detectors responsible for dispatch)
These are fundamentally different and harder to compose.
Better design: A unified detector interface that can handle both modes.
12.2 No composition of detectors
File: Across codebase Issue: Detectors can't be combined or disabled. All run or none. Ugliness: No way to have lightweight "fast" vs. "thorough" modes.
Summary
Total Issues Found: 62
By Category:
Duplicate/Redundant Code: 6 issues
Inconsistent Patterns: 7 issues
Complex/Gnarly Logic: 5 issues
Missing/Weak Abstractions: 3 issues
Suboptimal Design: 5 issues
Testing Gaps: 4 issues
Performance Concerns: 3 issues
Documentation Issues: 3 issues
Refactor Inconsistencies: 2 issues
Missing Optimizations: 3 issues
Regex Anti-patterns: 2 issues
Architecture Issues: 2 issues
Most Impactful Issues for Refactoring:
_detect_empty_if_chains() complexity (lines 305-371) — needs major simplification
Duplicate body extraction in stub functions — use _extract_function_body()
Duplicate brace-finding logic — use _find_opening_brace_line()
The detector manually tracks brace depth AND builds code-only text AND checks for await, all in one gnarly loop. But _extract_function_body(ctx.lines, i) already exists and does the brace tracking! With a new _code_text(content) helper (blanks out strings/comments), this collapses to:
python
body = _extract_function_body(ctx.lines, i)
if body and not re.search(r'\bawait\b', _code_text(body)):
# flag it
Lines 502-507 manually find opening brace (identical to _find_opening_brace_line). Lines 516-522 manually extract body text (identical to _extract_function_body logic). But _extract_function_body hardcodes max_scan=2000 while stubs need max_scan=30.
Fix: add max_scan parameter to _extract_function_body, then stub detector becomes 15 lines cleaner.
With _code_text, becomes len(pattern.findall(_code_text(body))) — one line.
4. _detect_empty_if_chains (lines 305-371) — 67-line state machine
The function has two code paths for single-line and multi-line empty if chains with 7 regex patterns inlined. Can't simplify the logic (it's inherently complex without an AST), but can make it readable by:
Extracting regex patterns as named constants
Splitting into _check_single_line_chain and _check_multi_line_chain sub-functions
Making the top-level function a clean 15-line dispatcher
A tiny _emit(smell_counts, key, ctx, line, content) helper eliminates this.
8. _detect_window_globals regex has 3 capturing groups but none are used
The captures are never referenced in the output. Switch to non-capturing groups for clarity.
Constraints
Tests must continue to pass unchanged (or with minimal mechanical updates)
Don't add methods to _FileContext (it's a data bundle)
Don't split detectors into separate files
Don't over-engineer — keep it simple
_detect_async_no_await's interleaved loop is the one that NEEDS its own control flow per the plan's "NOT touched" note, but actually now that _extract_function_body exists, it doesn't need special treatment anymore
Eight targeted refactors across two files (_smell_helpers.py and _smell_detectors.py), plus one new test in the test file. The changes are purely structural -- no behavioral changes, no new detectors, no changed thresholds. Every existing test should pass without modification.
Step 1: Add _code_text helper to _smell_helpers.py
What: A new function that takes a string of TypeScript code and returns only the "code" characters -- strings and comments are blanked out (replaced with spaces to preserve positions).
Where:/Users/user_c042661f/Documents/desloppify/desloppify/languages/typescript/detectors/_smell_helpers.py, after the _strip_ts_comments function (after line 41).
Implementation:
python
def _code_text(text: str) -> str:
"""Return *text* with string literals and comments blanked to spaces.
Unlike :func:`_strip_ts_comments` (which collapses comments), this
preserves character positions so that ``\\bawait\\b`` etc. work with
exact offsets. Only single-line ``//`` comments are handled (callers
pass per-line or per-body strings, not entire files with block comments).
"""
chars: list[str] = []
prev_code = ""
for _, ch, in_s in scan_code(text):
if in_s:
chars.append(" ")
continue
# Detect // line comment start
if ch == "/" and prev_code == "/":
# Replace the previous / we already appended and blank the rest
chars[-1] = " "
chars.append(" ")
prev_code = ch
continue
chars.append(ch)
prev_code = ch
return "".join(chars)
Wait -- actually, scan_code does NOT handle // comments, it only handles string delimiters. The // comment handling needs to be done line-by-line. Let me re-examine. Looking at the scanner:
python
# scanner.py only tracks string delimiters: ', ", `
# It does NOT recognize // or /* */ comments
So _code_text needs to handle // comments on top of what scan_code gives us. The simplest approach: process line-by-line, using scan_code for string awareness, and blank out everything from // onward when not in a string.
Actually, looking more carefully at how _detect_async_no_await currently works (lines 183-196), it builds code-only text per line and uses scan_code plus manual // detection. The _code_text helper should work on a single line or a multi-line body. Let me design it to work on arbitrary text, processing // as line-terminating comments:
python
def _code_text(text: str) -> str:
"""Return *text* with string literals and ``//`` comments blanked to spaces.
Preserves character offsets so regex searches produce correct positions.
Uses :func:`scan_code` for string-literal awareness, then blanks ``//``
line comments (everything from ``//`` to end-of-line when outside a string).
"""
out: list[str] = list(text) # mutable copy, same length
prev_code_idx: int | None = None
in_line_comment = False
for ci, ch, in_s in scan_code(text):
if ch == "\n":
in_line_comment = False
continue
if in_line_comment:
out[ci] = " "
continue
if in_s:
out[ci] = " "
continue
# Detect // start
if ch == "/" and prev_code_idx is not None and out[prev_code_idx] == "/":
out[prev_code_idx] = " "
out[ci] = " "
in_line_comment = True
prev_code_idx = None
continue
prev_code_idx = ci
return "".join(out)
Add to __all__: Yes, add "_code_text" to the __all__ list.
Add to imports in _smell_detectors.py: Add _code_text to the import block from _smell_helpers.
Step 2: Add max_scan parameter to _extract_function_body
What: The existing _extract_function_body hardcodes max_scan=2000 in its call to _track_brace_body. The stub detector needs max_scan=30. Add the parameter with the existing default.
def _extract_function_body(
lines: list[str], start_line: int, *, max_scan: int = 2000,
) -> str | None:
"""Extract the inner body text of a function starting at start_line.
Returns the text between the opening and closing braces, or None.
"""
brace_line = _find_opening_brace_line(lines, start_line, window=5)
if brace_line is None:
return None
end_line = _track_brace_body(lines, brace_line, max_scan=max_scan)
if end_line is None:
return None
body_text = "\n".join(lines[brace_line : end_line + 1])
first_brace = body_text.find("{")
last_brace = body_text.rfind("}")
if first_brace == -1 or last_brace == -1 or first_brace >= last_brace:
return None
return body_text[first_brace + 1 : last_brace]
The only change is *, max_scan: int = 2000 in the signature and max_scan=max_scan in the call. All existing callers that pass no max_scan get the same 2000 default.
Step 3: Simplify _detect_async_no_await (50 lines to ~20)
def _detect_async_no_await(
ctx: _FileContext, smell_counts: dict[str, list[dict]]
):
"""Find async functions that don't use await.
Uses _extract_function_body to get the function body, then checks for
\\bawait\\b in code-only text (strings/comments blanked via _code_text).
"""
async_re = re.compile(r"(?:async\s+function\s+(\w+)|(\w+)\s*=\s*async)")
await_re = re.compile(r"\bawait\b")
for i, line in enumerate(ctx.lines):
m = async_re.search(line)
if not m:
continue
name = m.group(1) or m.group(2)
body = _extract_function_body(ctx.lines, i)
if body is None:
continue
if not await_re.search(_code_text(body)):
_emit(smell_counts, "async_no_await", ctx, i + 1,
f"async {name or '(anonymous)'} has no await")
Critical behavioral note: The existing code does its own brace tracking which starts from the exact line i, and _extract_function_body also starts from i via _find_opening_brace_line(lines, i, window=5). The _track_brace_body call uses max_scan=2000 by default. So the behavior is identical. The test test_await_beyond_line_200_detected (250 filler lines) still passes because max_scan=2000 covers it.
The key behavioral equivalence to verify: the old code manually built code-only text per line using scan_code, which blanks out string literals and detects // comments. The new _code_text helper does the same thing on the full body at once.
def _detect_stub_functions(
ctx: _FileContext, smell_counts: dict[str, list[dict]]
):
"""Find functions with empty body or only return/return null (stub functions).
Matches function declarations and named arrow functions.
Skips decorated functions (TS decorators on line above).
"""
for i, line in enumerate(ctx.lines):
# Skip decorated functions
if i > 0 and ctx.lines[i - 1].strip().startswith("@"):
continue
name = _find_function_start(line, ctx.lines[i + 1 : i + 3])
if not name:
continue
body = _extract_function_body(ctx.lines, i, max_scan=30)
if body is None:
continue
body_clean = _strip_ts_comments(body).strip().rstrip(";")
if body_clean in ("", "return", "return null", "return undefined"):
label = body_clean or "empty"
_emit(smell_counts, "stub_function", ctx, i + 1,
f"{name}() — body is {label}")
What changed:
Lines 502-507 (manual _find_opening_brace_line reimplementation) replaced by _extract_function_body(ctx.lines, i, max_scan=30).
Lines 516-522 (manual body extraction) replaced by the same call's return value.
Uses _emit helper (Step 7).
Behavioral equivalence: The old code found the opening brace with the same 5-line window, called _track_brace_body with max_scan=30, and extracted body between first { and last }. That is exactly what _extract_function_body does.
Step 5: Simplify _count_pattern_in_body (11 lines to 3)
def _count_pattern_in_body(body: str, pattern: re.Pattern[str]) -> int:
"""Count regex matches in body that aren't inside string literals or comments."""
return len(pattern.findall(_code_text(body)))
Behavioral equivalence: The old code iterated each match, extracted the line it appeared on, and called _ts_match_is_in_string to skip matches inside strings. The new code blanks all strings/comments in the body first, then counts matches. Same result: matches inside strings produce no hits because the text is blanked to spaces.
Step 6: Extract _scan_template_content in _build_ts_line_state
Add new helper (before _build_ts_line_state, around line 151):
python
def _scan_template_content(
line: str, start: int, brace_depth: int = 0
) -> tuple[int, bool, int]:
"""Scan a template literal body starting at *start* in *line*.
Returns ``(end_pos, found_close, brace_depth)`` where:
- *end_pos* is the position after scanning stopped (past the closing
backtick, or end of line).
- *found_close* is True if the closing backtick was found.
- *brace_depth* is the updated ``${}`` nesting depth.
"""
k = start
while k < len(line):
c = line[k]
if c == "\\" and k + 1 < len(line):
k += 2
continue
if c == "$" and k + 1 < len(line) and line[k + 1] == "{":
brace_depth += 1
k += 2
continue
if c == "}" and brace_depth > 0:
brace_depth -= 1
k += 1
continue
if c == "`" and brace_depth == 0:
return k + 1, True, brace_depth
k += 1
return k, False, brace_depth
Then refactor _build_ts_line_state to use it in both places:
In the in_template branch (lines 178-198), replace with:
python
if in_template:
state[i] = "template_literal"
_, found_close, template_brace_depth = _scan_template_content(
line, 0, template_brace_depth
)
if found_close:
in_template = False
continue
In the normal-code branch where template literal start is detected (lines 235-263), replace with:
def _scan_single_line_chain(
ctx: _FileContext, index: int, smell_counts: dict[str, list[dict]]
) -> int:
"""Scan a chain of single-line empty if/else-if/else from *index*. Returns next index."""
stripped = ctx.lines[index].strip()
chain_start = index
cursor = index + 1
while cursor < len(ctx.lines):
next_stripped = ctx.lines[cursor].strip()
if _SINGLE_LINE_ELSE_IF.match(next_stripped):
cursor += 1
continue
if _SINGLE_LINE_ELSE.match(next_stripped):
cursor += 1
continue
break
_emit(smell_counts, "empty_if_chain", ctx, chain_start + 1, stripped[:100])
return cursor
def _scan_multi_line_chain(
ctx: _FileContext, index: int, smell_counts: dict[str, list[dict]]
) -> int:
"""Scan a multi-line empty if/else-if/else chain from *index*. Returns next index."""
chain_start = index
chain_all_empty = True
cursor = index
while cursor < len(ctx.lines):
current = ctx.lines[cursor].strip()
if cursor == chain_start:
if not _MULTI_LINE_IF_OPEN.match(current):
chain_all_empty = False
break
elif _MULTI_LINE_ELSE_IF_OPEN.match(current):
pass
elif _MULTI_LINE_ELSE_OPEN.match(current):
pass
elif current == "}":
tail = cursor + 1
while tail < len(ctx.lines) and ctx.lines[tail].strip() == "":
tail += 1
if tail < len(ctx.lines) and _ELSE_CONTINUATION.match(ctx.lines[tail].strip()):
cursor = tail
continue
cursor += 1
break
elif current == "":
cursor += 1
continue
else:
chain_all_empty = False
break
cursor += 1
if chain_all_empty and cursor > chain_start + 1:
_emit(smell_counts, "empty_if_chain", ctx, chain_start + 1,
ctx.lines[chain_start].strip()[:100])
return max(index + 1, cursor)
9c. Simplify the main dispatcher:
python
def _detect_empty_if_chains(
ctx: _FileContext, smell_counts: dict[str, list[dict]]
) -> None:
"""Find if/else chains where all branches are empty."""
index = 0
while index < len(ctx.lines):
stripped = ctx.lines[index].strip()
if not _IF_START.match(stripped):
index += 1
continue
if _SINGLE_LINE_EMPTY_IF.match(stripped):
index = _scan_single_line_chain(ctx, index, smell_counts)
elif _MULTI_LINE_IF_OPEN.match(stripped):
index = _scan_multi_line_chain(ctx, index, smell_counts)
else:
index += 1
This makes the top-level function a clean 15-line dispatcher, and the two sub-functions encapsulate the state-machine logic for each case.
Step 10: Update __all__ and imports
In _smell_helpers.py:
Add "_code_text" to __all__
In _smell_detectors.py:
Add _code_text to the import from _smell_helpers
Remove scan_code from the import (it was only used in _detect_async_no_await's manual loop, which is now gone)
Remove _ts_match_is_in_string from the import (it was only used in _count_pattern_in_body and _detect_window_globals; check if _detect_window_globals still needs it)
Wait -- _detect_window_globals still calls _ts_match_is_in_string on line 623. So keep that import. Let me re-check all usages:
Looking at the file:
_ts_match_is_in_string is used at line 140 (_count_pattern_in_body) and line 623 (_detect_window_globals)
After Step 5, _count_pattern_in_body no longer uses it
_detect_window_globals still uses it at line 623
So _ts_match_is_in_string stays in the import. Only scan_code can be removed.
from desloppify.languages.typescript.detectors._smell_helpers import _code_text
class TestCodeText:
def test_blanks_single_quoted_string(self):
result = _code_text("const s = 'hello';")
assert "hello" not in result
assert "const s =" in result
def test_blanks_double_quoted_string(self):
result = _code_text('const s = "world";')
assert "world" not in result
def test_blanks_template_literal(self):
result = _code_text("const s = `template`;")
assert "template" not in result
def test_blanks_line_comment(self):
result = _code_text("code // comment here")
assert "code" in result.strip() # leading text preserved
assert "comment" not in result
def test_preserves_code(self):
result = _code_text("const x = await fetch();")
assert "await" in result
def test_preserves_length(self):
text = "const s = 'hi'; // end"
assert len(_code_text(text)) == len(text)
def test_await_in_string_blanked(self):
result = _code_text("const s = 'await something';")
assert "await" not in result
def test_empty_string(self):
assert _code_text("") == ""
Also add _code_text to the import block at the top of the test file (line 15-22).
Execution Order and Dependencies
The steps have these dependencies:
Step 1 (_code_text) -- no dependencies, must come first since Steps 3, 4, 5 use it
Step 2 (max_scan parameter) -- no dependencies, must come before Step 4
Step 7a,b (constants + _emit) -- no dependencies, must come before Steps 3, 4, 7c, 7d, 9
~560 (~30 lines from async, ~15 from stub, ~8 from count_pattern, ~20 from emit compression, offset by +15 constants and +8 helper + ~15 empty-if sub-functions)
Net: modest reduction in total lines, significant reduction in complexity and duplication.
Step 1 (_code_text) -- new function, must exactly match the semantics of "blanks strings and // comments". The scan_code function does not handle // comments, so the _code_text implementation must add that layer. Write the test (Step 11) first to validate.
Step 3 (_detect_async_no_await) -- the biggest behavioral change. The existing code tracks brace depth in its own loop and checks await per-line as it goes. The new code extracts the full body first, then checks. Must verify: (a) the body extent is identical (same max_scan=2000), (b) _code_text blanks comments the same way the old per-line approach did, (c) edge case where function body is None (e.g., missing opening brace).
Step 5 (_count_pattern_in_body) -- changing from per-match string checking to pre-blanked text. Must verify that _code_text correctly blanks multi-line bodies (it processes \n correctly since scan_code just yields it as a non-string char).
Step 9 (empty if chains) -- extracting sub-functions from a state machine. Must preserve the exact same cursor advancement logic.
Critical Files for Implementation
/Users/user_c042661f/Documents/desloppify/desloppify/languages/typescript/detectors/_smell_detectors.py - Primary target: 7 of 8 refactors touch this file (detectors, emit, constants, regex)
/Users/user_c042661f/Documents/desloppify/desloppify/languages/typescript/detectors/_smell_helpers.py - Add _code_text and _scan_template_content helpers, dedup template scanning
/Users/user_c042661f/Documents/desloppify/desloppify/languages/typescript/tests/smells/test_ts_smell_helpers.py - Add _code_text tests, verify all existing tests still pass
/Users/user_c042661f/Documents/desloppify/desloppify/languages/typescript/syntax/scanner.py - Reference only: understand scan_code semantics for building _code_text
/Users/user_c042661f/Documents/desloppify/desloppify/languages/typescript/detectors/smells.py - No changes needed, but verify imports and orchestrator still work after refactors