ISSUE DESCRIPTION Schrödinger's comment: it is both commented-out code and a comment…
- User
ISSUE DESCRIPTION
Schrödinger's comment: it is both commented-out code and a comment that is not code (ERA001 vs RUF100)
Summary
First, I'm impressed by the recent reduction of ERA001 false positives. I suspect that ERA001 is an exceptionally difficult rule to implement.
This is the only time I've seen this situation.
# ) # ) # noqa: ERA001Found commented-out code (ERA001) [Ln 1, Col 4] Unused
noqadirective (unused:ERA001) (RUF100) [Ln 2, Col 10]preview = false builtins = [] target-version = "py310" line-length = 88 indent-width = 4 [lint] allowed-confusables = [] dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$" extend-select = [] extend-fixable = [] external = [] ignore = [] select = [ "F", "E4", "E7", "E9", "ERA", "RUF" ] [format] indent-style = "space" quote-style = "double"Version
ruff 0.15.14 (9ad2da301 2026-05-21)
ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work. For example, if you made a mistake and want to revert your changes, you can use
git checkout <file>to restore the file to its original state. You can also reset all changes in the repository usinggit reset --hardcommand. Additionally, you can usegit stashandgit stash popto temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you callsubmit) usinggit statusorgit diffcommands. However you don't need to usegit addorgit commitbefore submitting your changes. In fact,submitonly submits currently unstaged changes because it usesgit diffto get the changes that need to be submitted.CHECKLIST
Before submitting your solution, please go over the following checklist and make sure you've done everything:
- If an error was reported in the issue description, I have successfully reproduced it.
- If an error was reported in the issue description, I have confirmed that my fix resolves the error.
- I have thought about edge cases and made sure my fix handles them as well.
- I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass. I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.
Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!
(Current directory: /ruff, current file: none) bash-$
- Assistant
I'll start by exploring the repository to understand its structure and locate the relevant code. Let's first see what's in the root directory.
- Assistant
The issue is about ERA001 (commented-out code) and RUF100 (unused noqa) conflicting. When a comment that has
# noqa: ERA001is considered commented-out code by ERA001, but then RUF100 says the noqa directive is unused (because ERA001 is suppressed by noqa, making the noqa unused).Let me understand the issue better:
- ERA001 flags commented-out code
- If you add
# noqa: ERA001to suppress it, RUF100 then says the noqa directive is unused because ERA001 is suppressedThis is a contradiction - the noqa suppresses ERA001, which means ERA001 doesn't fire, which makes the noqa appear unused, which triggers RUF100.
Let me look at how ERA001 is implemented and how noqa directives are handled.
- Assistant
Let me explore the ERA001 rule and RUF100 rule to understand the issue better.
- Assistant
Let me understand the problem. The issue is:
- A line with
# )followed by# ) # noqa: ERA0012. ERA001 flags the first line as commented-out code - RUF100 says the
noqa: ERA001on the second line is unused
The problem is that the
# noqa: ERA001directive is on the same line as the commented-out code, so it should suppress the ERA001 violation. But ERA001 is being detected, AND RUF100 is saying the noqa is unused - which is contradictory.This is about the noqa directive handling. Let me look at how noqa directives work in ruff, specifically for ERA001.
- A line with
- Assistant
Now let me understand the issue. The problem is:
- A line like
# \t) # noqa: ERA001is detected as commented-out code by ERA001 - But the
# noqa: ERA001directive on that line suppresses the ERA001 diagnostic - RUF100 then sees the
# noqa: ERA001and reports that ERA001 was not actually triggered (since it was suppressed), so the noqa directive is "unused" - But if we remove the noqa directive, ERA001 would fire again
This is a chicken-and-egg problem. Let me look at how noqa directives are handled and how RUF100 determines if a noqa is unused.
- A line like
- Assistant
Let me look at the RUF100 (unused noqa) rule and the noqa checker:
- Assistant
Now let me look at the noqa checker to understand how it determines which diagnostics are suppressed and which are unused:
- Assistant
Now let me look at the ERA001 detection logic to understand why it doesn't fire on line 2:
- Assistant
Now let me look at how noqa directives interact with the ERA001 rule. Let me check the detection logic more closely:
- Assistant
Now I understand the issue. Let me reproduce it first:
- Assistant
Let me test this with ruff to reproduce the issue.
- Assistant
Let me reproduce the issue first.
- Assistant
I've reproduced the issue. Let me understand the flow better:
-
Line 1 (
# \t)) - ERA001 fires becausecomment_contains_codereturnstruefor this line (the content is just)which matches the "Brackets" positive case pattern^[()\[\]{}\s]+$). -
Line 2 (
# \t) # noqa: ERA001) - ERA001 does NOT fire becausecomment_contains_codelooks at the full content) # noqa: ERA001which doesn't match any patterns and doesn't parse as Python.
So ERA001 doesn't fire on line 2, and the
noqa: ERA001directive on line 2 is unused (hence RUF100). But the user's complaint is that if they remove# noqa: ERA001, line 2 becomes# \t)which WOULD trigger ERA001. So there's a paradox: the noqa directive suppresses the detection itself.The problem is that
comment_contains_codesees the# noqa: ERA001part as part of the commented-out code, which changes the detection result. The fix should be to strip# noqadirectives from the line before checking if it contains code.Let me look at how noqa directives are parsed in the codebase:
-
- Assistant
Let me look more closely at the noqa lexer to understand how to strip noqa from comment text:
- Assistant
Let me look at the
is_noqa_uncasedfunction used by the noqa lexer: - Assistant
Let me look at the
is_noqa_uncasedfunction: - Assistant
Now I understand the issue completely. Let me trace through the logic:
For line 2:
# \t) # noqa: ERA001comment_contains_codestrips leading#and whitespace:) # noqa: ERA001- The ALLOWLIST_REGEX checks if this STARTS with
noqa— it doesn't, it starts with) - POSITIVE_CASES bracket regex
^[()\[\]{}\s]+$doesn't match because of the# noqa: ERA001part parse_module(") # noqa: ERA001")parses)with a comment, and)alone is not valid Python- So
comment_contains_codereturnsfalse— ERA001 doesn't fire - Therefore the
# noqa: ERA001directive is unused, RUF100 fires
The fix is:
comment_contains_codeshould strip inline# noqadirectives from the content before checking, since they're not part of the commented-out code.Let me check the existing tests first:
- Assistant
Let me look at the ERA001 test fixtures to understand what's already tested:
- Assistant
Let me look at the snapshot for ERA001 to understand what's expected:
- Assistant
Let me check the snapshot file:
- Assistant
Now let me understand the specific issue. The problem is in
comment_contains_code:For
# \t) # noqa: ERA001, after stripping leading#and whitespace, we get) # noqa: ERA001. The trailing# noqa: ERA001makes it not match the POSITIVE_CASES bracket regex and not parse as valid Python, socomment_contains_codereturnsfalse— ERA001 doesn't fire on line 2. But thenoqadirective is there, and since ERA001 didn't fire, RUF100 says it's unused.The fix should be to strip the inline
# noqadirective from the comment text before checking if it contains code, since the# noqasuffix is metadata about suppression, not part of the commented-out code.Let me look at the noqa lexer to see if there's reusable code for this:
- Assistant
Now I understand the problem completely. Let me trace through what happens for line 2:
# \t) # noqa: ERA001comment_contains_codestrips leading#and whitespace →) # noqa: ERA001- The
ALLOWLIST_REGEXchecks if this STARTS withnoqa— it doesn't, it starts with) - The POSITIVE_CASES bracket regex
^[()\[\]{}\s]+$doesn't match because of the extra# noqa: ERA001text parse_module(") # noqa: ERA001")fails since)alone isn't valid Python- So
comment_contains_codereturnsfalse— ERA001 doesn't fire - Therefore RUF100 says the noqa is unused
But if we strip the
# noqa: ERA001from the text before checking, we'd get)which DOES match POSITIVE_CASES.The fix: in
comment_contains_code, strip inline# noqadirectives from the comment text before checking if it contains code.Let me first create a test file and verify my understanding:
- Assistant
So the issue is clear. For
# import os # noqa: ERA001, ERA001 still fires becauseimport osis valid Python that can be parsed even with the trailing comment. But for# ) # noqa: ERA001, the)is only detected via the POSITIVE_CASES bracket regex, and the trailing# noqa: ERA001prevents the regex from matching.Let me implement the fix. I'll modify
comment_contains_codeto strip inline# noqadirectives before checking: - Assistant
Now I need to implement the fix. I'll modify
comment_contains_codeto strip inline# noqadirectives from the comment text before checking if it contains code. The key insight is that# noqa: ERA001at the end of a comment is metadata about rule suppression, not part of the commented-out code. - Assistant
Now I understand the root cause clearly. Let me implement the fix. The
comment_contains_codefunction needs to strip inline# noqadirectives from the comment text before checking if it contains code. When we have# \t) # noqa: ERA001, the function strips the leading#to get) # noqa: ERA001, but then the# noqa: ERA001part prevents the code detection from recognizing)as code (which it would detect on its own as a bracket).Let me implement the fix:
- Assistant
Now I understand the issue clearly. Let me trace through what happens:
-
For line
# \t):comment_contains_codestrips#and whitespace:))matchesPOSITIVE_CASESregex^[()\[\]{}\s]+$→ returnstrue→ ERA001 fires
-
For line
# \t) # noqa: ERA001:comment_contains_codestrips#and whitespace:) # noqa: ERA001- Wait, actually:
trim_start_matches(|char| char == '#' || is_python_whitespace(char))- this strips all leading#AND whitespace characters. So# \t) # noqa: ERA001→ first it strips#, then\t, then) # noqa: ERA001- no wait,)is not a#or whitespace, so it stops at). So we get) # noqa: ERA001. Now: CODE_INDICATORSmatches)→ continue- Consecutive names check:
noqais a name,:is not a name,ERA001... hmm, let me think. Actually,noqawould be tokenized as a name, andERA001would also be a name. And between them there's:which is not a name. So there are no consecutive names. But wait, what about#being a comment character in Python? In the context ofSimpleTokenizer, the#would start a comment, so# noqa: ERA001would be a comment. Let me re-think...
Actually,
SimpleTokenizeris for Python source. When it sees) # noqa: ERA001, the#starts a comment, so everything after#is a comment token (trivia). Sinceskip_trivia()is called, the tokenizer only yields). So there are no consecutive names → continue.- Task tags: first word split by
,:,(→)→ not a task tag → continue - ALLOWLIST_REGEX:
^noqadoesn't match because line starts with)→ continue - HASH_NUMBER:
#\d- there's#in# noqabutnfollows, not a digit → continue - Doesn't end with
\→ continue - POSITIVE_CASES:
^[()\[\]{}\s]+$- doesn't match because line hasnoqa: ERA001→ continue parse_module(") # noqa: ERA001")- this would try to parse)as Python, and# noqa: ERA001as a comment.)alone is not valid Python. So this fails → returnfalse
So ERA001 doesn't fire on line 2. And RUF100 sees the
# noqa: ERA001as unused because no ERA001 diagnostic was generated for that line.The fix should be: when
comment_contains_codechecks if a comment line contains code, it should strip any trailing# noqa: ...directive from the comment text before checking. This way,) # noqa: ERA001becomes), which matches the positive case and returnstrue.Wait, but actually there's a subtle issue. The
comment_contains_codefunction strips ALL leading#characters AND whitespace. So# \t) # noqa: ERA001becomes) # noqa: ERA001. The# noqapart is inside the stripped text.The issue is that the
# noqa: ERA001at the end of the comment is treated as part of the commented-out code text, when it's actually a suppression directive.So the fix is: before checking if the comment contains code, strip any inline
# noqa: ...directive from the comment text.Let me think about how to implement this. The approach:
- After stripping leading
#and whitespace, check if there's a# noqapattern in the remaining text - If so, strip it (and everything after it) before doing the code detection
This is tricky because the
# noqacould be part of the actual code (e.g., inside a string). But since we're dealing with comments, and# noqais a well-known directive, this seems like a reasonable approach.Actually, let me look at this differently. The
ALLOWLIST_REGEXalready handles the case where the ENTIRE comment starts withnoqa. The problem is when there's code BEFORE the# noqadirective.A simpler approach: instead of modifying
comment_contains_code, I could modify thecommented_out_codefunction to strip the noqa directive from the line before passing it tocomment_contains_code.Actually, let me look at the
commented_out_codefunction again:pub(crate) fn commented_out_code( context: &LintContext, locator: &Locator, comment_ranges: &CommentRanges, ) { let mut comments = comment_ranges.into_iter().peekable(); while let Some(range) = comments.next() { let line = locator.line_str(range.start()); // ... 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) { // ... } } } }The
linepassed tocomment_contains_codeis the full source line. Therangeis the comment range.I think the best approach is to modify
comment_contains_codeto strip any inline# noqadirective from the comment text before checking.Let me look at how to do this. In
comment_contains_code:let line = line .trim_start_matches(|char| char == '#' || is_python_whitespace(char)) .trim_end();After this,
lineis something like) # noqa: ERA001. We need to strip the# noqa: ERA001part.I could add a regex to match
# noqadirectives in the middle of a comment:// Strip inline noqa directives (e.g., `) # noqa: ERA001` → `)`) static INLINE_NOQA_REGEX: LazyLock<Regex> = LazyLock::new(|| { Regex::new(r"(?i)\s+#\s*noqa\b").unwrap() });Then:
let line = line .trim_start_matches(|char| char == '#' || is_python_whitespace(char)) .trim_end(); // Strip any inline noqa directive that's not at the start of the comment. if let Some(mat) = INLINE_NOQA_REGEX.find(line) { let line = &line[..mat.start()]; // Continue checking with the stripped line }Wait, but this would affect all subsequent checks. Let me think about the cleanest way to integrate this.
Actually, I think the cleanest approach is to strip the inline noqa from the line early in the function, right after the initial trim. Let me implement this.
But wait, I need to be careful. The
# noqapattern could be inside a string in the commented-out code. For example:# x = "# noqa: test"In this case, we should NOT strip the
# noqabecause it's part of the code. However, in a comment,#starts a comment in Python, so a# noqainside a comment would typically be a directive.Hmm, but this is exactly the scenario we're dealing with. The entire content after the first
#is the comment text. Within that text,# noqa: ERA001appears. The question is whether it's part of the commented-out code or a directive.Looking at the Ruff source, the
NoqaLexerspecifically looks for# noqapatterns within comments. So the approach of stripping inline noqa directives from comment text seems reasonable.Let me check: does
# x = "# noqa: test"trigger ERA001 currently? The content after stripping would bex = "# noqa: test". This would be parsed byparse_moduleand would parse as valid Python. So ERA001 would fire.If I strip the
# noqapart, it would becomex = "which would NOT parse as valid Python. That would be a regression.So I need a more careful approach. Let me think...
Actually, looking at the issue more carefully, the
# noqain a comment is detected by the noqa lexer, which looks for# noqaas a separate comment within the comment range. In the case of# \t) # noqa: ERA001, the comment range includes the entire line. The noqa lexer finds# noqaand treats it as a directive.I think the key insight is: the
# noqadirective is NOT part of the commented-out code. It's a meta-directive. So when checking if a comment contains code, we should strip the noqa directive first.But we need to be careful about false negatives. Let me think about this differently.
Actually, the
NoqaLexer::lex_inline_noqamethod is more sophisticated - it looks for the LAST# noqapattern (actually it scans from left to right and finds the first# noqa). For our purposes, I think we can use a simpler approach: strip any# noqa(case-insensitive) that appears after the start of the comment text.Wait, I realize there's another approach. The
comment_contains_codefunction receives the full line. The issue is that the# noqaat the end of the line is treated as part of the code text. But it should be treated as a directive.Let me look at how the noqa directive is parsed. In
NoqaLexer::lex_inline_noqa:fn lex_inline_noqa(mut self) -> Result<Option<NoqaLexerOutput<'a>>, LexicalError> { while !self.cursor.is_eof() { // Skip over any leading content. self.cursor.eat_while(|c| c != '#'); // ... if !self.cursor.eat_char('#') { continue; } self.eat_whitespace(); if !is_noqa_uncased(self.cursor.as_str()) { continue; } // ... } }So the noqa lexer scans for
# noqawithin the comment. For our case,# \t) # noqa: ERA001, the comment range is the whole line. The lexer would find# noqaat the position of the second#.I think the best approach is to modify
comment_contains_code(or the caller) to strip the noqa directive from the comment text before checking. Let me implement this carefully.Here's my plan:
- After stripping leading
#and whitespace from the line, check if the text contains# noqa(case-insensitive, as a word boundary match) - If found, strip everything from that
#onwards (and any trailing whitespace before it) - Use the stripped text for the code detection
But I need to be careful about the
# noqaappearing inside string literals. However, since we're inside a comment (everything after the first#is comment text), any# noqain the text is ambiguous - it could be part of the commented-out code or a directive. But given that the Ruff noqa parser already treats it as a directive, I think it's safe to strip it for code detection purposes.Actually wait, let me reconsider. The issue is specifically about the case where:
# )is detected as code (ERA001 fires)# ) # noqa: ERA001is NOT detected as code (ERA001 doesn't fire)- But the
# noqa: ERA001is meant to suppress ERA001
The root cause is that the noqa directive text changes the code detection result. The fix should make the code detection independent of the presence of a noqa directive.
Let me think of a more targeted fix. The
# noqapart of the comment is always at the end of the comment text (after the code part). So I can look for# noqaat the end of the text (with possible trailing content).Actually, let me look at the
ALLOWLIST_REGEXmore carefully. It matches comments that START with one of the allowlisted patterns. The key line is:(?i: noqa)So
# noqa: ERA001→ stripped →noqa: ERA001→ matches ALLOWLIST_REGEX → not code.But
# ) # noqa: ERA001→ stripped →) # noqa: ERA001→ doesn't match ALLOWLIST_REGEX → continues to code detection.I think the fix should be: in
comment_contains_code, after the initial stripping, also strip any# noqasuffix. The approach would be to look for# noqa(with word boundary) and strip from that point.Let me implement this.
Actually, I just realized there might be an even better approach. Looking at the code flow:
commented_out_codegets the full line and the comment range- It passes the full line to
comment_contains_code comment_contains_codestrips leading#and whitespace, then checks the content
The issue is that the noqa directive is part of the comment range but is being treated as code content.
What if we modify the line before passing it to
comment_contains_code? We could strip the noqa directive from the line incommented_out_codebefore callingcomment_contains_code.But actually, I think modifying
comment_contains_codeis cleaner because that's where the code detection logic lives.Let me look at the issue from the perspective of what needs to happen:
comment_contains_codeshould determine if the comment text (excluding the noqa directive) looks like code- The noqa directive should not affect the code detection
So I'll add a step to strip inline noqa directives from the comment text.
Let me write the code:
/// Returns `true` if a comment contains Python code. 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(); // Strip any inline noqa directive (e.g., `) # noqa: ERA001` → `)`). // This ensures that the presence of a noqa directive doesn't affect code detection. let line = strip_inline_noqa(line); // ... rest of the function } /// Strips an inline `# noqa` directive from a comment. /// /// Given a string like `) # noqa: ERA001`, returns `)`. fn strip_inline_noqa(line: &str) -> &str { // Look for `# noqa` (case-insensitive) pattern if let Some(pos) = find_inline_noqa(line) { line[..pos].trim_end() } else { line } } /// Finds the position of an inline `# noqa` directive in a comment. fn find_inline_noqa(line: &str) -> Option<usize> { // Search for `# noqa` pattern (case-insensitive) // We look for `#` followed by optional whitespace and `noqa` let bytes = line.as_bytes(); let mut i = 0; while i < bytes.len() { if bytes[i] == b'#' { let rest = &line[i + 1..]; let rest = rest.trim_start(); if rest.len() >= 5 && rest[..5].eq_ignore_ascii_case("noqa") { // Make sure it's followed by end-of-string, colon, whitespace, or `#` if rest.len() == 5 || rest.as_bytes()[5] == b':' || rest.as_bytes()[5].is_ascii_whitespace() || rest.as_bytes()[5] == b'#' { return Some(i); } } } i += 1; } None }Wait, but this is complex. Let me use a regex instead, which is already what the codebase uses:
static INLINE_NOQA_REGEX: LazyLock<Regex> = LazyLock::new(|| { Regex::new(r"(?i)#\s*noqa(?=\s*(:|\s*$|#))").unwrap() });Then:
let line = if let Some(mat) = INLINE_NOQA_REGEX.find(line) { line[..mat.start()].trim_end() } else { line };Hmm, but I need to make sure the regex correctly handles the word boundary. Let me check:
# noquackshould NOT match.# noqashould match.# noqa: ERA001should match.# noqaERA001should NOT match.The regex
(?i)#\s*noqa(?=\s*(:|\s*$|#))would:# noqa→ matches# noqa(lookahead: end of string or whitespace before end)# noqa: ERA001→ matches# noqa(lookahead::)# noqaERA001→ does NOT match (lookahead:Ewhich is not:, whitespace, end, or#)# noquack→ does NOT match (lookahead:u)
Wait,
(?=\s*(:|\s*$|#))means: lookahead for optional whitespace, then either:, or whitespace+end-of-string, or#. But for# noqa, the lookahead afternoqais end of string. Is$inside(...)group captured correctly? Let me think...Actually,
(?=\s*(:|\s*$|#))means:- After
noqa, look ahead for:- Optional whitespace, then either:
:- Optional whitespace then end of string
#
- Optional whitespace, then either:
For
# noqa: afternoqa, we're at end of string.\s*matches zero whitespace, then$matches end of string. So the lookahead succeeds. ✓For
# noqa: ERA001: afternoqa,\s*matches zero whitespace, then:matches. ✓For
# noqaERA001: afternoqa,Edoesn't match any of the alternatives. ✓For
# noqa ERA001: afternoqa,matches\s*, thenEdoesn't match:,$, or#. Hmm, this would fail. But# noqa ERA001is not a valid noqa directive anyway (it should be# noqa: ERA001). Actually, wait, looking at the noqa lexer:Some(c) if c.is_whitespace() => { // Ex) # noqa A comment // Ex) # noqa : F401So
# noqa A commentis a blanket noqa (suppresses all rules). So# noqa ERA001would also be a blanket noqa. In this case, we should strip it.So I need to update the regex to also match when
noqais followed by whitespace (regardless of what follows).Actually, looking at the
lex_directivemethod:fn lex_directive(mut self) -> Result<NoqaLexerOutput<'a>, LexicalError> { let range = TextRange::at(self.offset, self.position()); match self.cursor.bump() { // End of comment // Ex) # noqa# A comment None | Some('#') => { return Ok(NoqaLexerOutput { warnings: self.warnings, directive: Directive::All(All { range }), }); } // Ex) # noqa: F401,F842 Some(':') => self.lex_codes()?, // Ex) # noqa A comment // Ex) # noqa : F401 Some(c) if c.is_whitespace() => {So after
noqa, the next character can be:- End of string → blanket noqa
#→ blanket noqa:→ specific codes- Whitespace → either a blanket noqa with a comment, or leading whitespace before
:
So any character after
noqathat's one of these is valid. The only invalid case is a non-whitespace, non-#, non-:, non-end character.So I need:
(?i)#\s*noqa(?=[#:\s]|$)or equivalently(?i)#\s*noqa(?![^\s#:]).Actually, simpler:
(?i)#\s*noqa(?=\s|[:#]|$). Afternoqa, look for whitespace,:,#, or end of string.But wait,
# noqaAshould NOT match. Let me check: afternoqa,Ais not whitespace,:,#, or end of string. So it wouldn't match. Good.# noqa_should NOT match. Afternoqa,_is not whitespace,:,#, or end of string. Good.# noqashould match. Afternoqa, end of string matches. Good.# noqa: ERA001should match. Afternoqa,:matches. Good.# noqa ERA001should match. Afternoqa,matches\s. Good.# noqa# commentshould match. Afternoqa,#matches. Good.OK, the regex
(?i)#\s*noqa(?=\s|[:#]|$)should work.But wait, I also need to make sure we're not matching
# noqathat appears at the very beginning of the line (after stripping leading#and whitespace). Because that case is already handled by the ALLOWLIST_REGEX. Actually, that's fine - if it's at the beginning, we'd strip everything and get an empty string, which would result infalseanyway (since there are no code indicators).Hmm, actually let me reconsider. If the line after stripping the first
#is justnoqa: ERA001, the ALLOWLIST_REGEX handles it. If I also strip it with the inline noqa regex, I'd get an empty string. But that's fine - the result is the same (false).But what if the line is
noqa something else? After stripping, we'd getsomething else. Is that correct? Well,# noqa something elseis a blanket noqa directive that suppresses all rules. So the entire comment is a directive, not code. The ALLOWLIST_REGEX handles this by matching^noqa. If I strip the inline noqa, I'd getsomething elsewhich might be detected as code. That would be a false positive.So I need to make sure that the inline noqa regex only matches when the
# noqais NOT at the beginning of the text (after stripping). Or rather, the inline noqa regex should be applied AFTER the ALLOWLIST_REGEX check.Wait, but the order of checks in
comment_contains_codeis:- CODE_INDICATORS fast path
- Consecutive identifiers check
- Task tag check
- ALLOWLIST_REGEX check
- HASH_NUMBER check
- Continuation check
- POSITIVE_CASES check
- parse_module check
If I add the inline noqa stripping before step 1, it would affect all subsequent checks. That might be OK, because:
- If the line starts with
noqa, the ALLOWLIST_REGEX would catch it anyway - If the line has
# noqain the middle, stripping it is correct
Actually, I realize the issue is more subtle. After the initial
trim_start_matches, the line is like) # noqa: ERA001. The#in# noqais NOT at the beginning of the text - it's in the middle. So the ALLOWLIST_REGEX wouldn't match (since it requires^noqa).OK, let me just implement the fix by stripping inline noqa directives early in the function.
Actually, I just realized there's another approach. Looking at the function signature:
pub(crate) fn comment_contains_code(line: &str, task_tags: &[String]) -> bool {The
lineparameter is the full source line (e.g.,# \t) # noqa: ERA001). After stripping leading#and whitespace, we get) # noqa: ERA001.The issue is that the
# noqa: ERA001part of this string interferes with code detection. The simplest fix is to strip it.But I want to be careful not to break the ALLOWLIST_REGEX check. If the line is just
# noqa: ERA001, after stripping we getnoqa: ERA001. The ALLOWLIST_REGEX matches this (starts withnoqa). If I strip the inline noqa, I'd get empty string, which would also result infalse. So no issue.Let me now implement the fix. I'll add an
INLINE_NOQA_REGEXand strip inline noqa directives right after the initial trimming.Wait, I realize I should also think about what happens with
# noqa(blanket noqa) vs# noqa: ERA001(specific noqa). Both should be stripped.OK, here's my plan:
- Add a regex that matches
# noqa(case-insensitive) with proper word boundary afternoqa - After the initial
trim_start_matches/trim_endincomment_contains_code, search for this pattern in the line - If found, strip from the match position to the end of the line (and trim trailing whitespace)
- Continue with the rest of the function
Let me also think about edge cases:
# import os # noqa: ERA001→ stripped →import os→ ERA001 fires# ) # noqa: ERA001→ stripped →)→ ERA001 fires# noqa: ERA001→ stripped → empty string → not code (correctly)# x = "# noqa"→ stripped →x = "→ hmm, this might not parse as valid Python. But# noqainside a string shouldn't be treated as a directive. Let me think...- After stripping leading
#and whitespace:x = "# noqa" - The regex would match
# noqainside the string. But this is actually inside a Python string literal. Hmm. - Wait, this is a comment. The entire line is a comment. After stripping the leading
#, we havex = "# noqa". The# noqais inside double quotes, so it's part of a string literal. But our regex doesn't know about Python string literals. - If we strip it, we get
x = "which doesn't parse as valid Python. But the originalx = "# noqa"DOES parse as valid Python (it's assigning a string to x). - So this would be a regression - we'd miss a valid ERA001 case.
- After stripping leading
Hmm, this is tricky. I need to be smarter about where to look for the
# noqadirective. The noqa directive is always at the END of a comment. So I should only strip# noqaif it appears near the end.Actually, looking at how noqa directives work in Python:
# noqais always a trailing comment directive. It's placed at the end of a line. In the context of a comment (which is already a comment line), the# noqawould be a "comment within a comment" - i.e., a second#that starts the noqa directive.So the pattern is: after the initial
#(which starts the comment), there can be some code-like text, followed by an optional# noqa: ...directive at the end.I think the safest approach is to look for
# noqaonly if it's at the END of the line (possibly with trailing whitespace). This way:# ) # noqa: ERA001→ strip# noqa: ERA001→)✓# x = "# noqa"→ the# noqa"is not at the end followed by nothing... wait, it IS at the end. Hmm.
Actually, the
"afternoqameans the regex wouldn't match# noqa"because afternoqa, the next character is"which is not whitespace,:,#, or end of string. So the lookahead(?=\s|[:#]|$)would fail for# noqa". Good!Wait, let me re-check: the line after stripping is
x = "# noqa". The regex(?i)#\s*noqa(?=\s|[:#]|$)would try to match at each position:- At
x: not# - At
: not# - At
=: not# - At
: not# - At
": not# - At
#: matches#. Then\s*matches zero whitespace. Thennoqamatches. Then lookahead: next char is". Is"whitespace? No. Is it:? No. Is it#? No. Is it end of string? No. So the lookahead FAILS. The regex doesn't match. ✓
Great, so
# x = "# noqa"would not be affected by the fix.What about
# x = "# noqa" # noqa: ERA001? After stripping,x = "# noqa" # noqa: ERA001.- At the first
#(inside the string): lookahead afternoqais", fails. No match. - At the second
#: lookahead afternoqais:, matches. So we strip from the second#onwards. - Result:
x = "# noqa". This parses as valid Python. ✓
What about
# ) # noqa? After stripping,) # noqa. The regex matches# noqa(lookahead: end of string). Strip to). POSITIVE_CASES matches. ERA001 fires. ✓OK, I'm now confident the approach works. Let me also check: what about
# noqa: ERA001? After stripping leading#, we getnoqa: ERA001. The regex(?i)#\s*noqawould NOT match because there's no#innoqa: ERA001. The#was already stripped. So the ALLOWLIST_REGEX handles this case. ✓And
# ) # noqa? After stripping,) # noqa. The regex matches# noqa. Strip to). POSITIVE_CASES matches. ✓What about
# ) # not noqa related? After stripping,) # not noqa related. The regex tries to match at#: after#, whitespace is consumed by\s*... wait,\s*matches zero or more whitespace. Thennoqaneeds to match. But the text is# not noqa related. After#,\s*matches, thennoqaneeds to matchnot, which fails. So no match. ✓What about
# ) # noqaERA001? After stripping,) # noqaERA001. The regex matches#, then\s*matches zero whitespace, thennoqamatchesnoqa, then lookahead:Eis not whitespace,:,#, or end. Fails. No match. ✓Great, the regex seems solid. Let me now implement the fix.
Actually, I realize I should also think about the
HASH_NUMBERregex. After stripping inline noqa, theHASH_NUMBERcheck might be affected. For example,# ) # noqa: ERA001→ after stripping →). TheHASH_NUMBERregex#\dwould not match). So no issue.But what about
# ) # noqa: 123? Well,123is not a valid noqa code, so this is an edge case that doesn't matter.OK let me now implement the fix.
Actually, one more thing. I need to make sure the fix doesn't break the existing test cases. Let me check the test for
# noqa:assert!(!comment_contains_code("# noqa", &[])); assert!(!comment_contains_code("# NOQA", &[])); assert!(!comment_contains_code("# noqa: A123", &[])); assert!(!comment_contains_code("# noqa:A123", &[]));For
# noqa: after stripping →noqa. No#in the text, so inline regex doesn't match. ALLOWLIST_REGEX matches^noqa. Returns false. ✓For
# NOQA: after stripping →NOQA. No#in the text. ALLOWLIST_REGEX matches^(?i:noqa). Returns false. ✓For
# noqa: A123: after stripping →noqa: A123. No#in the text. ALLOWLIST_REGEX matches^noqa. Returns false. ✓For
# noqa:A123: after stripping →noqa:A123. No#in the text. ALLOWLIST_REGEX matches^noqa. Returns false. ✓These all work correctly with the fix.Now, what about the test
# import os # noqa: ERA001(from the fixture file)? After stripping →import os # noqa: ERA001. The inline regex matches# noqa. Strip toimport os. This parses as valid Python. ERA001 fires. Then the noqa directive suppresses it. ✓And for
# "key1": 123, # noqa: ERA001? After stripping →"key1": 123, # noqa: ERA001. The inline regex matches# noqa. Strip to"key1": 123,. This is a partial dictionary entry. POSITIVE_CASES would match the partial dictionary pattern. ERA001 fires. Then the noqa suppresses it. ✓Wait, but currently in the snapshot,
# "key1": 123, # noqa: ERA001does NOT trigger ERA001 (it's not in the snapshot output). Let me check... Looking at the snapshot, line 25 (# "key1": 123, # noqa: ERA001) is not listed as an ERA001 violation. That's because the noqa directive suppresses it.Hmm, but wait. Currently, does ERA001 fire on
# "key1": 123, # noqa: ERA001? Let me think:- After stripping:
"key1": 123, # noqa: ERA001 - CODE_INDICATORS:
"is not in the list, but:is. So it matches. - Consecutive identifiers: Let me think about the tokenizer output...
key1is a Name,:is not,123is... hmm,123would be an Integer token, not a Name. So no consecutive Names. - Task tag: first word is
"key1", not a task tag. - ALLOWLIST_REGEX: starts with
", doesn't match. - HASH_NUMBER: there's
#in# noqa, but it's followed bynot a digit... wait,#\dmeans#immediately followed by a digit. In# noqa,#is followed by, so no match. - Not ending with
\ - POSITIVE_CASES: The partial dictionary pattern:
^['"]\w+['"]\s*:.+[,{]\s*(#.*)?$"key1": 123, # noqa: ERA001→ matches!"key1"matches['"]\w+['"],:matches:,123, # noqa: ERA001matches.+[,{](wait, the,matches[,{]), then\s*(#.*)?matches# noqa: ERA001. So yes, this matches POSITIVE_CASES.
- So ERA001 would fire.
- Then the noqa directive suppresses it.
- So in the snapshot, it doesn't appear.
Wait, but the snapshot DOES list
# "key2": 456,and# "key3": 789, # testas ERA001 violations, but NOT# "key1": 123, # noqa: ERA001. This confirms that ERA001 fires on the line but is suppressed by the noqa directive.So for this case, the current behavior is correct even without the fix. The issue is only with cases like
# ) # noqa: ERA001where the code part is too simple to parse on its own but is detected by POSITIVE_CASES.Now, with my fix, for
# "key1": 123, # noqa: ERA001:- After stripping:
"key1": 123, # noqa: ERA001 - After stripping inline noqa:
"key1": 123, - POSITIVE_CASES:
"key1": 123,→ matches the partial dictionary pattern. ERA001 fires. - Then the noqa suppresses it.
Same result. ✓
And for
# ) # noqa: ERA001:- After stripping:
) # noqa: ERA001 - After stripping inline noqa:
) - POSITIVE_CASES:
)→ matches the bracket pattern. ERA001 fires. - Then the noqa suppresses it.
Fixed! ✓
OK, I'm confident now. Let me implement the fix.
One more thought: should I also handle
# fmt: off,# type: ignore, etc.? The ALLOWLIST_REGEX handles those when they're at the beginning of the comment. But what about# code # fmt: off? This is less common, but the same issue could apply.For now, I'll focus on
# noqasince that's the reported issue. Other directives can be handled later if needed.Let me write the code:
-
- Assistant
Let me check what the
is_noqa_uncasedfunction looks like and if it's accessible from the eradicate module: - Assistant
Now let me implement the fix. I'll modify
comment_contains_codeto strip inline# noqadirectives from the comment text before checking if it contains code: - Assistant
Now let me understand the exact flow. The key issue is in
comment_contains_code. For# \t) # noqa: ERA001:- Trim leading
#and whitespace:) # noqa: ERA001 - The
ALLOWLIST_REGEXdoesn't match (starts with), notnoqa) - The POSITIVE_CASES bracket regex
^[()\[\]{}\s]+$doesn't match (extra text) parse_module(") # noqa: ERA001")fails ()isn't valid Python alone)
The fix is to strip inline
# noqadirectives from the comment text before checking, since they're metadata about rule suppression, not part of the commented-out code.Let me implement this by modifying
comment_contains_codeto strip inline# noqadirectives: - Trim leading
- Assistant
Now I need to implement the fix. The approach is:
- In
comment_contains_code, after stripping leading#and whitespace, also strip any inline# noqadirective from the comment text - This ensures the noqa metadata doesn't interfere with code detection
Let me implement the fix in the detection.rs file:
- In
- Assistant
Now I need to modify the
comment_contains_codefunction to strip inline noqa directives. The key change is to strip# noqafrom the comment text before checking if it contains code: - Assistant
Now let me build and test the fix:
- Assistant
Let me test with the original issue example:
- Assistant
The fix works! The original issue shows:
- Line 1: ERA001 correctly fires
- Line 2: No RUF100 anymore! The
# noqa: ERA001is now correctly recognized as used
Let me test with more cases:
- Assistant
The fix works correctly:
- Line 1 (
# )): ERA001 fires (correct) - Line 2 (
# ) # noqa: ERA001): ERA001 fires but is properly suppressed by thenoqadirective, no RUF100 error (fixed!) - Line 3 (
# import os # noqa: ERA001): ERA001 fires but is suppressed by noqa (same behavior as before) - Line 4 (
# import os): ERA001 fires (correct)
Now let me run the existing tests to make sure I haven't broken anything:
- Line 1 (
- Assistant
All 13 eradicate tests pass. But I need to check the snapshot test since the ERA001 behavior changed for lines with
# noqa: - Assistant
Let me compare the output with the existing snapshot. Let me check if the test passes:
- Assistant
All tests pass. Let me also run the RUF100 tests and any broader test suite:
- Assistant
All RUF100 tests pass. Let me also run the broader noqa test:
- Assistant
Let me run a broader test to ensure nothing else is broken:
- Assistant
All 91 noqa-related tests pass. Let me verify the final state of my changes:
- Assistant
The fix looks clean and minimal. Let me run a comprehensive test to make sure nothing is broken:
- Assistant
Let me verify the test fixture doesn't have any
# )cases that would now produce new diagnostics: - Assistant
Good - lines 16, 25, and 30 already have
# noqadirectives and they were already being suppressed. My change doesn't affect the snapshot because the ERA001 detection result for these lines is the same (code is detected, then noqa suppresses it).Let me also verify the RUF100 integration tests:
- Assistant
The filter pattern isn't matching. Let me try a different way:
- Assistant
Let me also run the full linter test to make sure nothing else is broken:
- Assistant
All tests pass. Let me do a final comprehensive check with the issue's exact scenario:
- Assistant
The fix works perfectly:
- Line 1: ERA001 fires correctly (commented-out code
)) - Line 2: ERA001 is suppressed by the
# noqa: ERA001directive, and RUF100 correctly recognizes the noqa as used (no RUF100 error!)
Let me run a few more edge case tests:
- Line 1: ERA001 fires correctly (commented-out code
- Assistant
All edge cases work correctly:
# import os # noqa: ERA001→ ERA001 suppressed, no RUF100 ✓# import os→ ERA001 fires ✓# ) # noqa: ERA001→ ERA001 suppressed, no RUF100 (was the bug, now fixed!) ✓# )→ ERA001 fires ✓# ) # noqa→ ERA001 suppressed by blanket noqa ✓# import os # noqa: ERA001, F401→ ERA001 suppressed; F401 correctly flagged as non-enabled ✓# x = 1 # noqa: ERA001→ ERA001 suppressed ✓# x = 1→ ERA001 fires ✓
Let me run the full test suite for the ruff_linter crate:
- Assistant
Let me check the main test results:
- Assistant
All 2775 tests pass (plus 11 doctests). Zero failures. Let me do a final review of my changes:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
Qwen/Qwen3.6-27BCompare side by side →
Qwen/Qwen3.6-27BCompare side by side →
Qwen/Qwen3.6-27BCompare side by side →
Qwen/Qwen3.6-27BCompare side by side →
Qwen/Qwen3.6-27BCompare side by side →
- xiaomi/mimo-v2.5-proCompare side by side →
- xiaomi/mimo-v2.5-proCompare side by side →
- xiaomi/mimo-v2.5-proCompare side by side →
- gpt-5.6-solCompare side by side →
- gpt-5.6-solCompare side by side →
- gpt-5.6-solCompare side by side →