Let me think about this issue more carefully.
The issue is:
# ) # Line 1: Reports ERA001 (commented-out code)
# ) # noqa: ERA001 # Line 2: Reports RUF100 (unused noqa for ERA001)
The problem is:
- Line 1 has
# ) which is detected as commented-out code → ERA001 fires
- Line 2 has
# ) # noqa: ERA001 - this ALSO has # ) which should be detected as commented-out code → ERA001 should fire, BUT the # noqa: ERA001 suppresses it
- However, RUF100 says the noqa is unused for ERA001
Why would RUF100 say the noqa is unused?
Looking at the code in check_noqa.rs, the key logic is:
- When a diagnostic is generated, it's added to the context
- The noqa check then goes through and marks which diagnostics were suppressed by which noqa directives
- After that, RUF100 checks if any noqa directives matched no diagnostic
The issue is that # ) in line 2 might NOT be detected as commented-out code. Let me check the comment_contains_code function.
Looking at the detection code, the line # ) after stripping the leading # and whitespace becomes ). Let me trace through:
CODE_INDICATORS checks for (, ), etc. - ) is in there, so this passes
- The tokenizer check for consecutive names -
) is not a name, so this passes
- Task tags - no match
- Allowlist - no match (noqa is in the allowlist, but this line doesn't have noqa in the part before the noqa comment)
Wait, but the line is # ) # noqa: ERA001. When we extract the comment content, we get the whole comment including the noqa. Let me look at how comment_contains_code is called.
In commented_out_code.rs:
let line = locator.line_str(range.start());
This gives the full line content. Then:
if is_own_line_comment(line)
&& comment_contains_code(line, &context.settings().task_tags[..])
And in comment_contains_code:
let line = line
.trim_start_matches(|char| char == '#' || is_python_whitespace(char))
.trim_end();
So for # ) # noqa: ERA001:
- After trimming start (removing
#, spaces, tabs): ) # noqa: ERA001
- After trimming end:
) # noqa: ERA001
Then:
CODE_INDICATORS.is_match(") # noqa: ERA001") - yes, ) is found
- Tokenizer check: starts with
), which is SimpleTokenKind::RightParen, so no consecutive names issue
- Task tags: no
- Allowlist:
NOQA is in the allowlist regex, so ALLOWLIST_REGEX.is_match(") # noqa: ERA001") - let me check if "noqa" matches...
Looking at the ALLOWLIST_REGEX:
noqa
(case-insensitive)
So yes, it would match. That means for # ) # noqa: ERA001, comment_contains_code returns false because the allowlist contains "noqa"!
But wait, that's the allowlist for comments that contain noqa directives. The issue is that the noqa directive is in the same comment line. So when the comment contains # noqa, it's treated as NOT being code.
But then the problem is:
- Line 2:
# ) # noqa: ERA001 → comment_contains_code returns false (because "noqa" is in the allowlist) → ERA001 does NOT fire
- RUF100 sees that ERA001 was in the noqa but ERA001 didn't fire on this line → reports "unused noqa"
This is the bug! The # noqa: ERA001 is there to suppress a potential ERA001, but because "noqa" is in the allowlist, ERA001 never fires on that line, making the noqa appear unused.
Actually wait, let me re-read the issue. The user says:
# ) # Found commented-out code (ERA001) [Ln 1, Col 4]
# ) # noqa: ERA001 # Unused `noqa` directive (unused: `ERA001`) (RUF100) [Ln 2, Col 10]
So ERA001 fires on line 1 but NOT on line 2. And on line 2, RUF100 says the noqa is unused.
This confirms my analysis. The problem is that when a comment contains # noqa in it, the comment_contains_code function returns false (because of the allowlist), so ERA001 doesn't fire. But then RUF100 sees the noqa for ERA001 and thinks it's unused because ERA001 didn't fire.
This is a chicken-and-egg problem:
- To suppress ERA001, you add
# noqa: ERA001
- But the presence of
# noqa makes comment_contains_code return false
- So ERA001 doesn't fire
- So the noqa is flagged as unused
The fix should be: when checking for ERA001, the code detection should consider only the part of the comment BEFORE the noqa directive, not the whole comment including the noqa.
Actually, let me think about this differently. The issue is that # noqa is in the ALLOWLIST_REGEX which makes comment_contains_code return false. But this is intentional - we don't want to flag # noqa: E501 as code.
The problem is specifically with # noqa: ERA001 in the same comment. The noqa keyword causes the whole comment to not be flagged as code, but the user is trying to suppress the ERA001 for the code part.
I think the fix should be in the comment_contains_code function or in how the noqa directive is handled.
Actually, let me look at this from a different angle. The ERA001 detection is done on comment ranges. Let me see how the comment ranges are extracted.
Looking at the commented_out_code function:
for range in comment_ranges.into_iter() {
let line = locator.line_str(range.start());
...
if is_own_line_comment(line)
&& comment_contains_code(line, ...)
The line here is the entire line starting from #. So for # ) # noqa: ERA001, line would be # ) # noqa: ERA001.
Then comment_contains_code strips the leading # and whitespace to get ) # noqa: ERA001.
The allowlist check sees "noqa" and returns false.
But the real content that should be checked for code is just ). The # noqa: ERA001 is a separate noqa directive that shouldn't affect the code detection.
Hmm, but looking at how noqa directives are parsed... The comment # ) # noqa: ERA001 actually contains TWO comments:
# ) - the actual comment content
# noqa: ERA001 - the noqa directive
Wait, no. In Python, # ) # noqa: ERA001 is a single comment from # to end of line. The second # noqa: ERA001 is part of the same comment.
Actually, let me reconsider. The comment ranges are extracted from the tokenizer. Let me check how they work.
Actually, I think I need to understand this better. Let me create a test file and see what ruff does.
Let me think about the fix. The issue is that the noqa keyword in the comment is causing comment_contains_code to return false when it shouldn't for this specific case.
One approach would be to check for the noqa directive separately and only exclude the noqa part from the code detection. But that would require parsing the noqa directive from within the comment.
Another approach would be to not include "noqa" in the ALLOWLIST_REGEX, but that would cause # noqa to be flagged as code, which we don't want.
Actually, I think the issue is more subtle. Let me re-read the issue...
The user's configuration has:
select = ["F", "E4", "E7", "E9", "ERA", "RUF"]
And they're seeing:
# ) # ERA001: Found commented-out code
# ) # noqa: ERA001 # RUF100: Unused noqa for ERA001
Wait, I think I misunderstood. Let me look at the allowlist regex more carefully:
noqa
This is case-insensitive. So # noqa and # noqa: ERA001 would both match.
But the issue is: the content # ) should be detected as code. When the user adds # noqa: ERA001 to suppress it, the noqa makes the whole comment look like it's not code.
So the fix could be:
- In
comment_contains_code, when we see noqa in the comment, we should strip the noqa part and re-check the remaining content
- Or, we could handle this in the ERA001 detection logic specifically
Actually, thinking about this more, I think the right fix is to modify the ERA001 detection to properly handle noqa directives. When a comment contains a noqa directive, we should:
- Strip the noqa directive from the comment content
- Check if the remaining content is code
- If it is code and ERA001 would fire, suppress it (don't report ERA001) and don't report RUF100 for the noqa
This way:
# ) → ERA001 fires (code detected)
# ) # noqa: ERA001 → We detect ) as code, but suppress ERA001 due to noqa, and don't report RUF100
Let me look at how to implement this.
Actually, wait. Let me re-read the issue description again.
The issue says:
# )
# ) # noqa: ERA001
Found commented-out code (ERA001) [Ln 1, Col 4]
Unused noqa directive (unused: ERA001) (RUF100) [Ln 2, Col 10]
Hmm, but looking at the allowlist regex, noqa is matched case-insensitively. So # ) # noqa: ERA001 → after stripping # → ) # noqa: ERA001 → ALLOWLIST_REGEX.is_match(") # noqa: ERA001") → matches noqa → returns false.
So ERA001 doesn't fire on line 2 because the noqa makes it look like non-code. Then RUF100 sees the noqa directive for ERA001 but ERA001 didn't fire, so it reports unused.
Actually, I wonder if there's a more specific pattern here. Let me think about what the right behavior should be:
# print("hello") → should report ERA001
# print("hello") # noqa → should NOT report ERA001 (intentionally suppressed)
# ) # noqa: ERA001 → should NOT report ERA001 (intentionally suppressed), and the noqa should not be flagged as unused
But currently:
# print("hello") → ERA001 fires ✓
# print("hello") # noqa → comment_contains_code returns false → ERA001 doesn't fire ✓
# ) # noqa: ERA001 → comment_contains_code returns false → ERA001 doesn't fire ✓, BUT RUF100 says noqa is unused ✗
Wait, that doesn't make sense. If ERA001 doesn't fire on line 2, then the noqa should be unused, and RUF100 correctly reports it. But the user expects it to NOT be unused.
Hmm, but the user added # noqa: ERA001 specifically to suppress ERA001. So the user INTENDS for ERA001 to fire but then be suppressed. The current behavior prevents ERA001 from firing in the first place because of the allowlist.
I think the fundamental issue is: the allowlist should NOT prevent ERA001 from firing on comments that contain only code-like content plus a noqa directive.
Actually, let me think about this differently. The ALLOWLIST_REGEX check is meant to prevent false positives for comments that happen to look like code but are actually just comments. For example:
# type: ignore - not code, it's a type annotation
# noqa: E501 - not code, it's a noqa directive
# mypy: allow-untyped-calls - not code, it's a mypy directive
But when the comment is actually # ) # noqa: ERA001, the ) # noqa: ERA001 part:
- The
) is actual code (just a closing parenthesis)
- The
# noqa: ERA001 is a noqa directive
The allowlist shouldn't prevent the detection of ) as code.
I think the fix should be: when checking for noqa in the allowlist, we should only ignore the noqa part, not the entire comment. Specifically, for # noqa, we should strip the noqa part from the line and re-check.
Actually, let me think about this more carefully. The ALLOWLIST_REGEX is:
noqa
(case-insensitive). This is a general pattern that matches any occurrence of "noqa" in the line.
But the intent is to match lines that ARE only noqa directives, not lines that CONTAIN a noqa directive after actual code.
Hmm, but # print("hello") # noqa should also not be flagged as code, right? If we fix # ) # noqa: ERA001 to detect ) as code, then we'd also need to handle # print("hello") # noqa to not flag it as code.
Wait, actually # print("hello") # noqa - the print("hello") # noqa part:
- Does it contain "noqa"? Yes → ALLOWLIST_REGEX matches → returns
false
So print("hello") # noqa is also not flagged as code. That seems wrong... unless we want # print("hello") # noqa to not be flagged.
But wait, the user is adding # noqa: ERA001 to SUPPRESS ERA001. If ERA001 didn't fire in the first place, then the noqa is not needed and RUF100 correctly says it's unused.
OK, I think I finally understand the real issue:
- Without noqa:
# ) → ERA001 fires → user adds # noqa: ERA001 to suppress
- With noqa:
# ) # noqa: ERA001 → comment_contains_code returns false → ERA001 doesn't fire
- RUF100 says: "you have
# noqa: ERA001 but ERA001 didn't fire, so it's unused"
The root cause is that the allowlist is too broad - it prevents ERA001 from firing on comments that contain "noqa" anywhere, even when the actual code-like content should be detected.
The fix should be: in comment_contains_code, when we detect "noqa" in the allowlist, we should check if the content before the noqa is also code. If it is, we should still return true.
Let me look at how to implement this.
One approach:
- Before checking the allowlist, strip the noqa directive from the line
- Check if the remaining content is code
- If yes, return true (the noqa is there to suppress, not to indicate the comment is non-code)
Let me look at what the noqa directive looks like in the comment:
# noqa: ERA001 → after stripping # → ) # noqa: ERA001
- The
# noqa: part starts at some position in the line
We need to:
- Find the
# noqa directive in the line
- Strip it out
- Check if the remaining content is code
Actually, a simpler approach: check if the content BEFORE the noqa directive is code. If so, the comment contains code, and the noqa is there to suppress it.
Let me write a fix:
In comment_contains_code, before the allowlist check:
# Find and strip noqa directives
noqa_match = re.search(r'\s*#\s*noqa\b', line)
if noqa_match:
# Check if content before noqa is code
content_before_noqa = line[:noqa_match.start()].rstrip()
if content_before_noqa and comment_contains_code(content_before_noqa, task_tags):
return True
But this would be a recursive call, which is not ideal.
Actually, let me think about this differently. The key insight is:
# noqa alone (no code before it) should NOT be flagged as code
# print("hello") # noqa - should this be flagged? The user might have added noqa to suppress some other rule, and the code part is intentional to keep for documentation. So we should NOT flag it.
Hmm, but actually # print("hello") SHOULD be flagged as code (it's commented-out code). The noqa is there to suppress some OTHER rule (like E501 for line too long), not to suppress ERA001.
Wait, but in that case, # print("hello") # noqa: E501 - the noqa is for E501 (line too long), not for ERA001. So:
- ERA001 fires on
# print("hello") # noqa: E501 because comment_contains_code returns... let me check.
After stripping # → print("hello") # noqa: E501
CODE_INDICATORS.is_match("print("hello") # noqa: E501") → yes (( is found)
- Tokenizer check: consecutive names?
print is a name, ( is not a name, so no
- Task tags: no
- Allowlist:
noqa matches → returns false → ERA001 doesn't fire
So # print("hello") # noqa: E501 doesn't get flagged by ERA001. That seems like a false negative.
But the user's specific issue is different: # ) # noqa: ERA001 where the noqa is specifically for ERA001. In this case:
- User sees ERA001 on
# )
- User adds
# noqa: ERA001 to suppress it
- Now
# ) # noqa: ERA001 doesn't trigger ERA001 (because of allowlist)
- RUF100 says the noqa is unused
So the fix should ensure that when the noqa is specifically for ERA001, the ERA001 detection still "fires" conceptually (even if it gets suppressed), so RUF100 doesn't report it as unused.
But how do we communicate this? The ERA001 rule doesn't know about noqa directives - it just checks if the comment contains code. The noqa suppression happens later in the check_noqa phase.
I think the real fix is: in comment_contains_code, when we see "noqa" in the allowlist, we should strip the noqa part and re-check the remaining content. This way:
# ) # noqa: ERA001 → strip noqa → ) → is code → return true
# noqa: E501 → strip noqa → `` → is not code → return false
# print("hello") # noqa: E501 → strip noqa → print("hello") → is code → return true
This is the right behavior. Let me implement this.
Actually wait, for case 3, after stripping # we get print("hello") # noqa: E501. Then we strip the noqa part to get print("hello"). And print("hello") is code. So ERA001 would fire on # print("hello") # noqa: E501. That might be a false positive... or not? If the user writes # print("hello") # noqa: E501, the print("hello") IS commented-out code, and ERA001 should flag it. The noqa: E501 is for some other rule. The user should either:
a) Remove the commented-out code, or
b) Add # noqa: ERA001 to also suppress ERA001
So returning true for case 3 is actually the correct behavior.
Let me now implement the fix. I need to modify comment_contains_code to strip noqa directives before checking the allowlist.
Looking at the current code:
def comment_contains_code(line: &str, task_tags: &[String]) -> bool:
# ... initial stripping ...
# Ignore whitelisted comments.
if ALLOWLIST_REGEX.is_match(line):
return false
I need to add logic before the allowlist check to strip noqa directives and re-check.
Actually, let me think about this more carefully. The line at this point is the content after stripping leading # and whitespace. So it's something like:
) # noqa: ERA001
print("hello") # noqa: E501
noqa: E501
noqa
I need to find and strip the # noqa directive. The pattern would be \s*#\s*noqa (a noqa directive preceded by optional whitespace and #).
Wait, but the noqa directive is # noqa, which is already part of the comment. So the line is ) # noqa: ERA001, and I need to find # noqa within it.
Let me write the fix:
// If the line contains a `noqa` directive, check if the content before it is code.
// This handles the case where someone adds `# noqa: ERA001` to suppress ERA001
// for commented-out code.
let noqa_match = line.find("# noqa");
if let Some(noqa_pos) = noqa_match {
// Strip the noqa directive and check if the remaining content is code
let content_before_noqa = line[..noqa_pos].trim_end();
if !content_before_noqa.is_empty() && CODE_INDICATORS.is_match(content_before_noqa) {
return true;
}
}
// Ignore whitelisted comments.
if ALLOWLIST_REGEX.is_match(line) {
return false;
}
Hmm, but this is a bit fragile. What if the noqa is in a different format? Let me look at the noqa parsing to see all the formats.
Actually, let me also consider # nosemgrep: ... or other security-related suppressions. Let me check if those are also in the allowlist.
Looking at the ALLOWLIST_REGEX, I see:
nosec
So # nosec is also whitelisted. Similarly, I should handle # nosemgrep: ....
But for now, let me focus on the # noqa case since that's what the issue is about.
Wait, actually I realize there's a subtlety. The ALLOWLIST_REGEX also matches things like:
pyright
mypy:
type: ignore
ty: ignore
SPDX-License-Identifier:
fmt: on/off/skip
region|endregion
isort:
coding:
language=
These are all directives that make the comment NOT code. But noqa is special because it's a suppression that should come AFTER code, not instead of code.
Actually, I think the real issue is more general. The noqa pattern in the allowlist is too broad. It matches any line containing "noqa", even when the line also contains code.
Let me look at what the original eradicate.py does...
Actually, looking at the test cases:
assert!(!comment_contains_code("# noqa", &[]));
assert!(!comment_contains_code("# NOQA", &[]));
assert!(!comment_contains_code("# noqa: A123", &[]));
assert!(!comment_contains_code("# noqa:A123", &[]));
So # noqa, # noqa: A123, etc. are all expected to return false. But what about # ) # noqa: ERA001?
Looking at the tests, I don't see a test case for this. The issue is that # ) # noqa: ERA001 should be detected as containing code () is code).
OK let me implement the fix now. The approach is:
- Before checking the allowlist, strip
noqa directives and check if the remaining content is code
- If the remaining content contains code indicators and looks like it could be code, return true
Let me implement this.
Actually, I need to be more careful. The noqa directive could be # noqa, # noqa: CODE1, CODE2, # nosec, etc. I should strip all of these.
Actually, looking at the issue more carefully, the user's problem is specifically with # noqa: ERA001. So let me focus on that.
The fix: before checking the allowlist, strip the noqa directive from the line and check if the remaining content is code.
Let me also think about the regex approach. Instead of modifying the allowlist, I could modify it to only match when the ENTIRE line (minus leading/trailing whitespace) is a noqa directive.
Current regex:
noqa
This matches any occurrence of "noqa" anywhere in the line. But we want to match when the line is ONLY a noqa directive (possibly with codes).
A better regex would be:
^\s*noqa(?:\s*:\s*.+)?\s*$
But this would be a bigger change. Let me think about the minimal fix.
Actually, I think the best approach is to modify the allowlist regex to only match when the entire line (after stripping) is a noqa/nosec directive. Let me check what the current regex looks like:
^(?:
pyright
| pyrefly
| ruff\s*:\s*(disable|enable)
| mypy:
| type:\s*ignore
| ty:\s*ignore
| SPDX-License-Identifier:
| fmt:\s*(on|off|skip)
| region|endregion
| (?i:noqa)
| (?i:nosec)
| (?i:pylint)
| (?i:isort:\s*(on|off|skip|skip_file|split|dont-add-imports(:\s*\[.*?])?))
| (?i:coding[:=][\x20\t]*([-_.A-Z0-9]+))
| language=[-_.a-zA-Z0-9]+
)
The issue is that this regex matches anywhere in the line (no $ at the end). For noqa specifically, it would match # noqa: E501 and print("hello") # noqa: E501.
A better approach would be to add $ to the noqa and nosec patterns:
| (?i:noqa\s*(?::\s*\S+)?)\s*$
| (?i:nosec\b)\s*$
But this might be too restrictive. What about # noqa: E501 some explanation?
Actually, let me look at how noqa directives are parsed in general. The noqa directive format is:
# noqa
# noqa: CODE1, CODE2
# noqa: CODE1, CODE2 # some explanation
Hmm, the last one has an explanation after the noqa. Let me check how noqa parsing works.
Actually, looking at the issue, the user wrote:
# ) # noqa: ERA001
So the noqa is # noqa: ERA001, and there's no explanation after it.
I think the safest fix is to check if the line, after stripping the noqa directive, still contains code-like content. If so, the comment contains code.
Let me implement this:
// If the line contains a `noqa` directive, strip it and check if the remaining
// content looks like code. This prevents `# noqa: ERA001` from causing
// `comment_contains_code` to return `false` when the comment actually contains
// code (like `# ) # noqa: ERA001`).
let no_codes = line.find("# noqa");
if let Some(pos) = no_codes {
let before_noqa = line[..pos].trim_end();
if !before_noqa.is_empty() && CODE_INDICATORS.is_match(before_noqa) {
return true;
}
}
Wait, but I also need to handle # nosec. Let me also check that.
Actually, let me focus on # noqa first since that's the issue at hand.
Let me write the fix now. I'll modify the comment_contains_code function.
Actually, let me re-read the allowlist regex. The regex is:
(?x)
^
(?:
...
| (?i:noqa)
...
)
Note that there's a ^ at the start but no $ at the end. This means the regex matches anywhere in the line. So print("hello") # noqa: E501 would match because "noqa" is found in the line.
But wait, the issue is specifically about # ) # noqa: ERA001. After stripping the leading # :
- Line =
) # noqa: ERA001
CODE_INDICATORS.is_match(") # noqa: ERA001") → true (because of ))
- Tokenizer check → no consecutive names
- Task tags → no match
- Allowlist:
ALLOWLIST_REGEX.is_match(") # noqa: ERA001") → let me check...
The allowlist regex starts with ^ and then has the noqa pattern. Does ") # noqa: ERA001" match ^noqa? No, because the string starts with ), not noqa.
Wait, let me look at the regex more carefully:
^(?:
pyright
| pyrefly
| ruff\s*:\s*(disable|enable)
| mypy:
| type:\s*ignore
| ty:\s*ignore
| SPDX-License-Identifier:
| fmt:\s*(on|off|skip)
| region|endregion
| (?i:noqa)
| (?i:nosec)
...
)
With the ^ at the start, the regex must match from the beginning of the string. So ") # noqa: ERA001" would NOT match ^noqa because the string starts with ).
Hmm, so the allowlist wouldn't match for ) # noqa: ERA001. Let me re-check...
Actually wait, the regex is using .is_match() which searches for the regex anywhere in the string. But with ^ at the start, it anchors to the beginning. So the regex must start matching from position 0.
For ") # noqa: ERA001":
^ matches position 0
- Then it tries to match one of the alternatives at position 0
pyright → no, starts with )
noqa → no, starts with )
- ... none of the alternatives match at position 0
- So the regex does NOT match
So the allowlist does NOT match for ") # noqa: ERA001". That means comment_contains_code should continue to the next checks.
Let me trace through the rest:
CODE_INDICATORS.is_match(") # noqa: ERA001") → true () is found)
- Tokenizer:
) is not a name, so no consecutive names
- Task tags: no
- Allowlist: no match (as we just determined)
- HASH_NUMBER:
#\d → no match (the # is followed by space, not a digit)
- Ends with
\: no
- POSITIVE_CASES: does
") # noqa: ERA001" match any of these?
- Keywords:
^(?:elif\s+.*\s*:.*|else\s*:.*|try\s*:.*|finally\s*:.*|except.*:.*|case\s+.*\s*:.*)$ → no
- Partial dictionary:
^['"]\w+['"]\s*:.+[,{]\s*(#.*)?$ → no
- Multiline assignment:
^[(\[]\s*)?(?:\w+\s*,\s*)*\w+\s*([)\]]\s*)?=.*[(\[{]$ → no (no = sign)
- Brackets:
^[()\[\]{}\s]+$ → no, contains # and letters
So POSITIVE_CASES does NOT match.
Then we try parse_module(line):
parse_module(") # noqa: ERA001") → what happens?
The Python parser would try to parse ) # noqa: ERA001 as a module. This would fail because ) is not valid Python syntax at the start of a file.
So comment_contains_code(") # noqa: ERA001", &[]) → returns false because parse_module fails.
Wait, but the issue says ERA001 IS firing on line 1 (# )) but NOT on line 2 (# ) # noqa: ERA001). So my analysis is consistent with the issue - ERA001 doesn't fire on line 2.
But why doesn't ERA001 fire on line 2? Let me trace through again.
For line 2: # ) # noqa: ERA001
Wait, let me think about this more carefully. trim_start_matches removes characters from the start that match the predicate. The predicate is | char == '#' || is_python_whitespace(char).
For "# ) # noqa: ERA001":
- Position 0:
# → matches → strip
- Position 1:
(space) → whitespace → strip
- Position 2:
(tab) → whitespace → strip
- Position 3:
) → not # and not whitespace → stop
So after trim_start_matches, we get ") # noqa: ERA001".
After trim_end(), we get ") # noqa: ERA001".
Now:
CODE_INDICATORS.is_match(") # noqa: ERA001") → true () matches)
- Tokenizer: tokenize
) # noqa: ERA001
) → RightParen
- space → trivia (skipped)
# → Comment (skipped)
- After comment,
noqa: ERA001 → Name (noqa), Colon, Name (ERA001)
- So we have:
) # noqa: ERA001 → tokens: RightParen, Name, Colon, Name
- Check for consecutive names: Name, Colon → not consecutive. Colon, Name → not consecutive.
- So no consecutive names → this check passes
Hmm wait, but the tokenizer skips trivia (whitespace and comments). So # noqa: ERA001 is treated as a comment and skipped. The tokenizer sees ), then noqa (as a Name), then :, then ERA001 (as a Name).
Wait, but # starts a comment, so everything after # is skipped. So the tokens are just: ), noqa, :, ERA001 (with noqa being a Name, : being a Colon, ERA001 being a Name).
But ) is a RightParen, and noqa is a Name. They're not consecutive names (RightParen, not Name).
So the tokenizer check passes (no consecutive names).
- Task tags:
noqa is not a task tag
- Allowlist:
ALLOWLIST_REGEX.is_match(") # noqa: ERA001") → as I analyzed, the regex starts with ^ and must match at the beginning. Since the string starts with ), it doesn't match.
Wait, but I said earlier that ALLOWLIST_REGEX.is_match() searches for the regex anywhere in the string. Let me check...
Actually, Regex::is_match() checks if the regex matches any substring of the input. But with ^ at the start of the regex, it anchors to the beginning. So ^noqa would only match if the string starts with noqa.
Hmm, but looking at the regex:
^(?:
...
| (?i:noqa)
...
)
Without a $ at the end, the regex ^(?:...|noqa|...) would match any string that starts with one of the alternatives. For ") # noqa: ERA001":
- The string starts with
)
- None of the alternatives start with
)
- So the regex does NOT match
OK so I was right earlier. The allowlist doesn't match for ") # noqa: ERA001".
-
HASH_NUMBER: #\d → looking for # followed by a digit. In ") # noqa: ERA001", the # is followed by a space, not a digit. So no match.
-
Ends with \: no
-
POSITIVE_CASES: as I analyzed, none match.
-
parse_module(") # noqa: ERA001"):
- The Python parser tries to parse
) # noqa: ERA001 as a module
- This would fail because
) is not valid at the start of a file
- So
parse_module returns an error
So comment_contains_code(") # noqa: ERA001", &[]) → returns false because parse_module fails.
Now for line 1: # )
- After stripping:
)
CODE_INDICATORS.is_match(")") → true
- Tokenizer: just
), no consecutive names
- Task tags: no
- Allowlist: no match
- HASH_NUMBER: no match
- Ends with
\: no
- POSITIVE_CASES:
^[()\[\]{}\s]+$ → does ) match? Let me check:
^[()\[\]{}\s]+$ means the string consists only of (, ), [, ], {, }, or whitespace
) matches this pattern → YES
- So POSITIVE_CASES matches → return
true
Great! So:
- Line 1:
comment_contains_code(")", &[]) → true → ERA001 fires
- Line 2:
comment_contains_code(") # noqa: ERA001", &[]) → false → ERA001 doesn't fire
The reason is:
- For line 1,
) matches the POSITIVE_CASES regex ^[()\[\]{}\s]+$
- For line 2,
) # noqa: ERA001 does NOT match the POSITIVE_CASES regex because it contains # and letters
Then for line 2, it falls through to parse_module(") # noqa: ERA001") which fails.
So the issue is that the presence of # noqa: ERA001 in the comment prevents ) from being matched by the POSITIVE_CASES regex, and then parse_module fails.
The fix should be: strip the noqa directive from the line before checking for code. Specifically, when we see # noqa in the line, we should check if the content before it is code.
Let me implement this fix:
// If the line contains a `noqa` directive, strip it and re-check.
// This prevents the `# noqa` portion from interfering with code detection.
let no_codes = line.find("# noqa");
if let Some(pos) = no_codes {
let content_before_noqa = &line[..pos];
if comment_contains_code_inner(content_before_noqa.trim_end(), task_tags) {
return true;
}
}
But this would require a recursive call or a helper function. Alternatively, I could restructure the function.
Actually, let me think about a cleaner approach. I could strip the noqa directive from the line early on, before all the other checks:
pub(crate) fn comment_contains_code(line: &str, task_tags: &[String]) -> bool {
let line = line
.trim_start_matches(|char| char == '#' || is_python_whitespace(char))
.trim_end();
// Fast path: if none of the indicators are present, the line is not code.
if !CODE_INDICATORS.is_match(line) {
return false;
}
// If the line contains a `noqa` directive, strip it and re-check.
// This handles the case where someone adds `# noqa: ERA001` to suppress
// ERA001 for commented-out code like `# ) # noqa: ERA001`.
let no_codes = line.find("# noqa");
let content = if let Some(pos) = no_codes {
line[..pos].trim_end()
} else {
line
};
// ... rest of the checks use `content` instead of `line`
}
Hmm, but this would also affect other checks. For example, the tokenizer would tokenize content instead of line, which might have different results.
Actually, I think the cleanest approach is to handle the noqa stripping specifically for the positive cases check and the parse_module check:
// Fast path: if none of the indicators are present, the line is not code.
if !CODE_INDICATORS.is_match(line) {
return false;
}
// If the line contains a `noqa` directive, strip it and check the remaining content.
// This prevents the `# noqa` portion from masking commented-out code.
let (check_content, has_noqa) = {
match line.find("# noqa") {
Some(pos) => (&line[..pos].trim_end(), true),
None => (line, false),
}
};
// Fast path: if the content (without noqa) has no consecutive identifiers, it's not code.
let tokenizer = SimpleTokenizer::starts_at(TextSize::default(), check_content).skip_trivia();
if tokenizer.tuple_windows().any(|(first, second)| {
first.kind == SimpleTokenKind::Name && second.kind == SimpleTokenKind::Name
}) {
return false;
}
// Ignore task tag comments.
if check_content
.split(&[' ', ':', '('])
.next()
.is_some_and(|first| task_tags.iter().any(|tag| tag == first))
{
return false;
}
// Ignore whitelisted comments.
if ALLOWLIST_REGEX.is_match(check_content) {
return false;
}
// Ignore non-comment related hashes.
if HASH_NUMBER.is_match(check_content) {
return false;
}
// If the content ends in a continuation, assume it's code.
if check_content.ends_with('\\') {
return true;
}
// If the content matches any of the specified positive cases, assume it's code.
if POSITIVE_CASES.is_match(check_content) {
return true;
}
// Finally, compile the source code.
parse_module(check_content).is_ok()
Wait, but this changes the behavior for all cases, not just the noqa case. Let me think about whether this is correct for all cases.
For # print("hello"):
- line =
print("hello")
- has_noqa = false
- check_content =
print("hello")
parse_module("print("hello")") → should fail because it's not a valid module
- Wait, actually...
parse_module("print("hello")") → print("hello") IS valid Python! It's a function call statement.
Hmm, so parse_module would succeed for print("hello"), and ERA001 would fire on # print("hello"). That's correct.
For # ):
- line =
)
- has_noqa = false
- check_content =
)
- POSITIVE_CASES matches (
^[()\[\]{}\s]+$) → return true
For # ) # noqa: ERA001:
- line =
) # noqa: ERA001
- has_noqa = true
- check_content =
)
- POSITIVE_CASES matches (
^[()\[\]{}\s]+$) → return true
For # noqa:
- line =
noqa
- has_noqa = false (no
# noqa pattern)
- Hmm, wait. The line is
noqa after stripping. So there's no # noqa in it.
But actually, for # noqa, the stripping would give:
let line = line
.trim_start_matches(|char| char == '#' || is_python_whitespace(char))
.trim_end();
For "# noqa":
- Strip
# and whitespace → "noqa"
So line = "noqa", and line.find("# noqa") returns None because the # was already stripped.
Hmm, so my approach doesn't work for # noqa because the # was already stripped by the initial trimming.
Let me think about this differently. The initial stripping removes # and whitespace from the beginning. So:
# noqa → noqa
# noqa: E501 → noqa: E501
# ) # noqa: ERA001 → ) # noqa: ERA001
# print("hello") # noqa: E501 → print("hello") # noqa: E501
So the # noqa that was the first comment is already stripped. But the # noqa that comes after code (after initial code content) is NOT stripped.
For the issue case:
# ) # noqa: ERA001 → ) # noqa: ERA001 → we find # noqa and strip to get )
For # noqa:
# noqa → noqa → no # noqa to find
For # noqa: E501:
# noqa: E501 → noqa: E501 → no # noqa to find
For # print("hello") # noqa: E501:
# print("hello") # noqa: E501 → print("hello") # noqa: E501 → we find # noqa and strip to get print("hello")
OK so my approach handles the issue case and the case where there's code before noqa. For the pure # noqa and # noqa: E501 cases, the allowlist check would still catch them.
But wait, for # noqa: E501, after stripping we get noqa: E501. The allowlist regex would match this because noqa is in the regex. But with my change, we'd first strip # noqa from the content. But there's no # noqa in noqa: E501 (it starts with noqa, not # noqa).
Hmm, so my approach doesn't affect the # noqa: E501 case. The allowlist would still catch it.
OK wait, let me reconsider. For # noqa: E501:
- After stripping:
noqa: E501
CODE_INDICATORS.is_match("noqa: E501") → : is a code indicator → true
- Tokenizer:
noqa is a Name, : is Colon, E501 is... hmm, E501 would be parsed as a Name (alphanumeric).
- Consecutive names:
noqa (Name) and E501 (Name) with : (Colon) between them → not consecutive
- Task tags: no
- Allowlist:
ALLOWLIST_REGEX.is_match("noqa: E501") → the regex has ^(?:...|(?i:noqa)|...)) → does "noqa: E501" match ^noqa? Yes! ^noqa matches noqa at the start.
- So the allowlist matches → return
false
For # ) # noqa: ERA001:
- After stripping:
) # noqa: ERA001
CODE_INDICATORS.is_match(") # noqa: ERA001") → ) is a code indicator → true
- Tokenizer:
) is RightParen, noqa is Name, ERA001 is Name
- Consecutive names:
) (RightParen), noqa (Name) → not consecutive. noqa (Name), ERA001 (Name) → YES! They ARE consecutive (no trivia between them because # starts a comment which is skipped).
Wait, let me think about this. In ) # noqa: ERA001:
) → RightParen
→ whitespace (trivia, skipped)
# → comment start
noqa: ERA001 → comment content (skipped entirely)
So the tokens are: RightParen, EOF. The comment is completely skipped.
Hmm, that changes things. So the tokenizer would not see noqa at all because it's in a comment.
Let me verify: SimpleTokenizer in ruff should skip comments. So for ) # noqa: ERA001:
- Tokens:
) (RightParen), EOF
- No consecutive names → tokenizer check passes
OK so for ) # noqa: ERA001:
CODE_INDICATORS.is_match(") # noqa: ERA001") → true () matches)
- Tokenizer: no consecutive names → passes
- Task tags: no
- Allowlist:
ALLOWLIST_REGEX.is_match(") # noqa: ERA001") → regex starts with ^, tries to match at position 0, which is ). None of the alternatives start with ). → no match
- HASH_NUMBER:
#\d → no match (the # in the string is followed by space, not a digit)
- Ends with
\: no
- POSITIVE_CASES:
^[()\[\]{}\s]+$ → ) # noqa: ERA001 contains #, space, letters → no match
parse_module(") # noqa: ERA001") → fails
So comment_contains_code(") # noqa: ERA001", &[]) → false.
The issue is that ) # noqa: ERA001 doesn't match any positive cases and parse_module fails.
Now, if I strip # noqa: ERA001 to get ):
CODE_INDICATORS.is_match(")") → true
- Tokenizer: just
), no consecutive names
- Task tags: no
- Allowlist:
ALLOWLIST_REGEX.is_match(")") → no match
- HASH_NUMBER: no match
- Ends with
\: no
- POSITIVE_CASES:
^[()\[\]{}\s]+$ → ) matches! → return true
Great, so my approach works.
But wait, I also need to check that stripping # noqa doesn't break other cases. Let me trace through a few:
For # noqa:
- After stripping:
noqa
CODE_INDICATORS.is_match("noqa") → : is not in "noqa"... wait, is : a code indicator?
Looking at the code indicators:
static CODE_INDICATORS: LazyLock<AhoCorasick> = LazyLock::new(|| {
AhoCorasick::new([
"(", ")", "[", "]", "{", "}", ":", "=", "%", "return", "break", "continue", "import",
])
.unwrap()
});
Yes, : is a code indicator. So CODE_INDICATORS.is_match("noqa") → : is NOT in "noqa". Wait, let me check again. "noqa" doesn't contain any of (, ), [, ], {, }, :, =, %, "return", "break", "continue", "import". So CODE_INDICATORS.is_match("noqa") → false.
So the fast path catches noqa immediately → return false. No need for the allowlist check.
For # print("hello") # noqa: E501:
- After stripping:
print("hello") # noqa: E501
CODE_INDICATORS.is_match(...) → yes (( and ))
- Tokenizer:
print (Name), "hello" (String), ) (RightParen) → then # noqa: E501 is a comment → skip
- Consecutive names:
print (Name), "hello" (String) → not consecutive. "hello" (String), ) (RightParen) → not consecutive. → passes
- Task tags: no
- Allowlist:
ALLOWLIST_REGEX.is_match("print("hello") # noqa: E501") → starts with p, not in any alternative → no match
- HASH_NUMBER: no match
- Ends with
\: no
- POSITIVE_CASES: none match
parse_module("print("hello") # noqa: E501") → print("hello") # noqa: E501 is valid Python → parse_module succeeds → return true
OK so for this case, parse_module would succeed and return true, so ERA001 would fire. That's the correct behavior - print("hello") is code.
Now, if I strip # noqa: E501 to get print("hello"):
- Same result -
parse_module("print("hello")") → succeeds → true
So stripping doesn't change the result for this case.
For # type: ignore:
- After stripping:
type: ignore
CODE_INDICATORS.is_match("type: ignore") → : matches → true
- Tokenizer:
type (Name), : (Colon), ignore (Name)
- Consecutive names:
type (Name) and ignore (Name) with : (Colon) between → not consecutive
- Task tags: no
- Allowlist:
ALLOWLIST_REGEX.is_match("type: ignore") → matches type:\s*ignore → yes
- Return
false
OK so # type: ignore correctly returns false.
Now, what about my stripping approach? For type: ignore:
line.find("# noqa") → None (no # noqa in the string)
- So we don't strip anything
- Same result
Good, no change.
For # ruff: disable(E501):
- After stripping:
ruff: disable(E501)
CODE_INDICATORS.is_match("ruff: disable(E501)") → :, (, ) match → true
- Tokenizer:
ruff (Name), : (Colon), disable (Name), ( (LeftParen), E501 (Name), ) (RightParen)
- Consecutive names:
ruff (Name), disable (Name) with : (Colon) between → not consecutive. disable (Name), E501 (Name) with ( (LeftParen) between → not consecutive.
- Task tags: no
- Allowlist:
ALLOWLIST_REGEX.is_match("ruff: disable(E501)") → matches ruff\s*:\s*(disable|enable) → yes
- Return
false
OK so # ruff: disable(E501) correctly returns false.
Now, what if someone writes # x = 1 # ruff: disable(E501)? The noqa is for ruff disable, not for ERA001.
- After stripping:
x = 1 # ruff: disable(E501)
CODE_INDICATORS.is_match(...) → yes (= is a code indicator)
- Tokenizer:
x (Name), = (Eq), 1 (Int), then # ruff: disable(E501) is a comment
- Consecutive names:
x (Name), 1 (Int) → not consecutive. 1 (Int), ... (comment, skipped)
- Task tags: no
- Allowlist:
ALLOWLIST_REGEX.is_match("x = 1 # ruff: disable(E501)") → regex starts with ^, tries to match at x. No alternative starts with x. → no match
- HASH_NUMBER: no match
- Ends with
\: no
- POSITIVE_CASES: none match
parse_module("x = 1 # ruff: disable(E501)") → valid Python → true
So ERA001 would fire on # x = 1 # ruff: disable(E501). That's correct - x = 1 is code.
Now, if I strip # ruff: disable(E501) to get x = 1:
- Same result -
parse_module("x = 1") → valid → true
No change.
But what if I strip # noqa specifically? For # x = 1 # noqa: E501:
- After stripping:
x = 1 # noqa: E501
- I find
# noqa and strip to get x = 1
parse_module("x = 1") → valid → true
OK so the result is the same.
But what about # noqa: E501?
- After stripping:
noqa: E501
- I look for
# noqa but the string is noqa: E501 (no #) → no match
- So no stripping
- Allowlist:
ALLOWLIST_REGEX.is_match("noqa: E501") → matches ^noqa → yes
- Return
false
So # noqa: E501 correctly returns false.
Now, what about # ) # noqa: ERA001?
- After stripping:
) # noqa: ERA001
- I find
# noqa at some position and strip to get )
POSITIVE_CASES.is_match(")") → matches ^[()\[\]{}\s]+$ → yes
- Return
true
That's the fix! Now ERA001 would fire on # ) # noqa: ERA001, and then the noqa would suppress it. RUF100 would not flag the noqa as unused because ERA001 did fire (and was suppressed).
But wait, there's a subtlety. The check_noqa logic in check_noqa.rs determines which noqa directives suppress which diagnostics. Let me make sure the noqa suppression still works correctly.
Looking at the check_noqa logic:
- For each diagnostic, find the noqa directives on the same line
- If a noqa directive includes the diagnostic's code, suppress the diagnostic and record the match
So for # ) # noqa: ERA001:
- ERA001 fires at the position of the comment
- The noqa directive
# noqa: ERA001 is on the same line
- The noqa includes
ERA001
- So ERA001 is suppressed and the match is recorded
Then for RUF100:
- Check if the noqa directive has any unmatched codes
- Since ERA001 was suppressed (match recorded), ERA001 is matched
- So RUF100 does not flag it as unused
This is the correct behavior!
Now, there's one more thing to consider. The commented_out_code function in commented_out_code.rs reports the diagnostic at the comment range:
if is_own_line_comment(line)
&& comment_contains_code(line, &context.settings().task_tags[..])
{
if let Some(mut diagnostic) =
context.report_diagnostic_if_enabled(CommentedOutCode, range)
{
So the diagnostic is reported at the range (the comment range). And the noqa directive is also on the same line. So the noqa suppression should work.
OK, I'm now confident that the fix is correct. Let me implement it.
The fix is in comment_contains_code in detection.rs. I need to strip the # noqa directive from the line before checking for code.
Actually, let me think about the implementation more carefully. I should only strip the # noqa part if it appears in the middle of the line (not at the beginning). If the line starts with noqa, then it's just a noqa comment and should not be flagged as code.
Wait, but I already handle this. After stripping the leading # and whitespace, if the line is noqa, the CODE_INDICATORS check fails (no code indicators in "noqa"). So it returns false early.
The issue is only when # noqa appears in the middle of the line, like ) # noqa: ERA001. In this case:
CODE_INDICATORS matches (because of ))
- We should strip
# noqa: ERA001 and check if ) is code
But I also need to be careful about the regex matching. After stripping, we should use the stripped content for all subsequent checks.
Let me also think about whether I should use a regex to find and strip # noqa or just use find("# noqa"). The find("# noqa") approach would find the first occurrence of # noqa in the line. For ) # noqa: ERA001, it would find the position of # noqa and strip from there.
But what about ) # noqasomething? The find("# noqa") would still match because # noqa is a substring of # noqasomething. I should use # noqa\b (with word boundary) to be more precise.
Actually, looking at the allowlist regex, it uses noqa without a word boundary. So # noqasomething would also be whitelisted. Let me check if this is intentional.
Actually, # noqa is a standard Python comment convention. # noqasomething is not standard. But the allowlist regex doesn't have a word boundary, so it would match # noqasomething.
For simplicity, let me just use find("# noqa") without worrying about word boundaries. This might have some edge cases, but they're unlikely in practice.
Wait, actually I want to be more careful. Let me use a regex to match # noqa followed by optional whitespace, optional :, optional codes, and then end or whitespace. But that's complex.
Actually, the simplest approach is: find # noqa in the line and strip from that position. This handles the most common cases. If the noqa is followed by more content (like a comment), the stripped content would still be correct.
Hmm, but what about ) # noqa (no codes)? After stripping, we get ). The rest of the checks would determine if ) is code. Let me trace through:
CODE_INDICATORS.is_match(")") → true
- Tokenizer: just
), no consecutive names
- Task tags: no
- Allowlist:
ALLOWLIST_REGEX.is_match(")") → no match
- HASH_NUMBER: no match
- Ends with
\: no
- POSITIVE_CASES:
^[()\[\]{}\s]+$ → ) matches → yes
- Return
true
Good.
What about ) # noqa: (noqa with no codes)? After stripping, we get ). Same result.
What about ) # noqa: ERA001, F401? After stripping, we get ). Same result.
OK, I think my approach is correct. Let me implement it.
Actually, wait. I just realized that I need to handle the case where # noqa is at the beginning of the content. For example:
# noqa: E501 → after stripping: noqa: E501
find("# noqa") → None (because the # was stripped)
- So no stripping happens
- Allowlist:
ALLOWLIST_REGEX.is_match("noqa: E501") → matches → return false
This is correct. The allowlist catches pure noqa comments.
But what about # ) # noqa: E501?
- After stripping:
) # noqa: E501
find("# noqa") → finds # noqa → strip to get )
POSITIVE_CASES.is_match(")") → matches → return true
Correct.
What about # noqa: # )?
- After stripping:
noqa: # )
find("# noqa") → None (because # was stripped from the start)
CODE_INDICATORS.is_match("noqa: # )") → : and ) are code indicators → true
- Tokenizer:
noqa (Name), : (Colon), ) (RightParen) → no consecutive names
- Task tags: no
- Allowlist:
ALLOWLIST_REGEX.is_match("noqa: # )") → matches ^noqa → yes
- Return
false
Hmm, is this correct? # noqa: # ) means "ignore all lints, and also )". This is a weird comment but the # noqa at the beginning suggests the user intends it as a noqa comment, not as code. So returning false is correct.
OK, I'm satisfied with the approach. Let me also consider if there are other patterns besides # noqa that should be stripped. Looking at the allowlist regex:
pyright
mypy:
type: ignore
ty: ignore
SPDX-License-Identifier:
fmt: on/off/skip
region|endregion
pylint
nosec
isort:
coding:
language=
Most of these are at the beginning of the comment (after stripping). For example, # type: ignore → type: ignore, and # pylint: disable=E501 → pylint: disable=E501.
But what about # print("hello") # pylint: disable=E501? The # pylint: disable=E501 is a separate directive. Should we strip it?
Currently, without my fix:
CODE_INDICATORS.is_match("print("hello") # pylint: disable=E501") → yes ((, ))
- Tokenizer: no consecutive names (comment after
# is skipped)
- Allowlist:
ALLOWLIST_REGEX.is_match("print("hello") # pylint: disable=E501") → regex starts with ^, matches at p → no match (no alternative starts with p)
- POSITIVE_CASES: none match
parse_module("print("hello") # pylint: disable=E501") → valid → true
So ERA001 fires on # print("hello") # pylint: disable=E501. Is this correct? The print("hello") is code, and the # pylint: disable=E501 is a separate directive. So yes, ERA001 should fire.
Now, with my fix (only stripping # noqa):
find("# noqa") → None (no # noqa in the string)
- No stripping
- Same result
Good, no change.
What about # print("hello") # nosec?
find("# noqa") → None (it's nosec, not noqa)
ALLOWLIST_REGEX.is_match("print("hello") # nosec") → no match at position 0 (starts with p)
parse_module(...) → valid → true
So ERA001 fires. Is this correct? The print("hello") is code. The # nosec is a security lint suppression. So yes, ERA001 should fire.
What about # nosec?
- After stripping:
nosec
CODE_INDICATORS.is_match("nosec") → no code indicators → false (fast path)
- Return
false
Correct.
What about # x = 1 # nosec?
- After stripping:
x = 1 # nosec
find("# noqa") → None
CODE_INDICATORS.is_match("x = 1 # nosec") → yes (=)
- Tokenizer:
x (Name), = (Eq), 1 (Int), nosec (Name) → no consecutive names
- Allowlist: no match at position 0
parse_module("x = 1 # nosec") → valid → true
So ERA001 fires. Is this correct? Yes, x = 1 is code.
OK, I think the fix is correct. Let me also think about edge cases:
# ) # noqa → strip to ) → positive case → true ✓
# ) # noqa: ERA001 → strip to ) → positive case → true ✓
# ) # nosec → no # noqa found → ALLOWLIST_REGEX.is_match(") # nosec") → no match → parse_module(") # nosec") → fails → false
Hmm, case 3 is a problem. # ) # nosec should probably be detected as code () is code) with # nosec as a suppression directive. But currently, without my fix for nosec, ERA001 would not fire.
But the issue is specifically about # noqa: ERA001, not # nosec. Let me focus on fixing the # noqa case for now.
Actually, wait. Looking at case 3 more carefully:
# ) # nosec → after stripping: ) # nosec
CODE_INDICATORS.is_match(") # nosec") → yes ())
- Tokenizer:
) (RightParen), nosec (Name) → no consecutive names
- Task tags: no
- Allowlist:
ALLOWLIST_REGEX.is_match(") # nosec") → no match (doesn't start with any alternative)
- HASH_NUMBER: no match
- Ends with
\: no
- POSITIVE_CASES:
^[()\[\]{}\s]+$ → ) # nosec contains # and letters → no match
parse_module(") # nosec") → fails → return false
So # ) # nosec is not flagged as code. Is this correct? The ) is a real code fragment, but # nosec is a security suppression. I think this is a false negative.
But the issue is specifically about # noqa, so let me focus on that for now. I can add a separate fix for # nosec later if needed.
Let me also think about whether my fix could cause any regressions. The key question is: are there any cases where stripping # noqa from the line would cause comment_contains_code to return true when it should return false?
Consider # noqa: this is not code. After stripping: noqa: this is not code.
find("# noqa") → None (because # was stripped from the start)
- So no stripping
CODE_INDICATORS.is_match("noqa: this is not code") → : is a code indicator → true
- Tokenizer:
noqa (Name), : (Colon), this (Name), is (Name), not (Name), code (Name)
- Consecutive names:
this (Name), is (Name) → YES!
- Return
false
So this is correctly caught by the tokenizer check.
What about # noqa: 123? After stripping: noqa: 123.
CODE_INDICATORS.is_match("noqa: 123") → : → true
- Tokenizer:
noqa (Name), : (Colon), 123 (Int) → no consecutive names
- Task tags: no
- Allowlist:
ALLOWLIST_REGEX.is_match("noqa: 123") → matches ^noqa → yes
- Return
false
Correct.
What about # noqa: (code)? After stripping: noqa: (code).
find("# noqa") → None (no # in the string)
CODE_INDICATORS.is_match("noqa: (code)") → (, ) → true
- Tokenizer:
noqa (Name), : (Colon), code (Name) → no consecutive names
- Task tags: no
- Allowlist:
ALLOWLIST_REGEX.is_match("noqa: (code)") → matches ^noqa → yes
- Return
false
Correct.
What about # x = 1 # noqa? After stripping: x = 1 # noqa.
find("# noqa") → finds it → strip to get x = 1
parse_module("x = 1") → valid → true
Is this correct? # x = 1 # noqa - the x = 1 is code, and # noqa is meant to suppress all lints on this line. So ERA001 should fire (the code is commented out). The noqa would suppress ERA001, and RUF100 would not flag it.
This is the correct behavior.
What about # noqa? After stripping: noqa.
find("# noqa") → None
CODE_INDICATORS.is_match("noqa") → no code indicators → false (fast path)
- Return
false
Correct.
What about # )? After stripping: ).
find("# noqa") → None
POSITIVE_CASES.is_match(")") → yes
- Return
true
Correct (this is the case that triggers ERA001 without noqa).
What about # ) # noqa: ERA001 # some comment? After stripping: ) # noqa: ERA001 # some comment.
find("# noqa") → finds # noqa → strip to get ) → trim_end → )
POSITIVE_CASES.is_match(")") → yes
- Return
true
Correct.
OK I'm now confident the fix is correct and won't cause regressions. Let me implement it.
Let me now write the fix in the actual file.