From dee67205deb42f4fd1c8ff4d2ea99f1b5e575688 Mon Sep 17 00:00:00 2001 From: Dhruv Manilawala Date: Tue, 18 Jun 2024 15:45:07 +0530 Subject: [PATCH] Avoid adding `noqa` comment for syntax error --- crates/ruff_linter/src/noqa.rs | 40 +++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/crates/ruff_linter/src/noqa.rs b/crates/ruff_linter/src/noqa.rs index dae0b0cf66651..51fc4596d7b3c 100644 --- a/crates/ruff_linter/src/noqa.rs +++ b/crates/ruff_linter/src/noqa.rs @@ -726,6 +726,12 @@ fn find_noqa_comments<'a>( // Mark any non-ignored diagnostics. for diagnostic in diagnostics { + // Syntax errors cannot be ignored by a `noqa` comment so we shouldn't add them either. + if diagnostic.kind.rule() == Rule::SyntaxError { + comments_by_line.push(None); + continue; + } + match &exemption { FileExemption::All(_) => { // If the file is exempted, don't add any noqa directives. @@ -1063,7 +1069,7 @@ mod tests { use crate::generate_noqa_edits; use crate::noqa::{add_noqa_inner, Directive, NoqaMapping, ParsedFileExemption}; - use crate::rules::pycodestyle::rules::AmbiguousVariableName; + use crate::rules::pycodestyle::rules::{AmbiguousVariableName, UselessSemicolon}; use crate::rules::pyflakes::rules::UnusedVariable; use crate::rules::pyupgrade::rules::PrintfStringFormatting; @@ -1380,4 +1386,36 @@ print( ))] ); } + + #[test] + fn syntax_error() { + let path = Path::new("/tmp/foo.txt"); + let source = "\ +foo; +bar = +"; + let diagnostics = [Diagnostic::new( + UselessSemicolon, + TextRange::new(4.into(), 5.into()), + )]; + let noqa_line_for = NoqaMapping::default(); + let comment_ranges = CommentRanges::default(); + let edits = generate_noqa_edits( + path, + &diagnostics, + &Locator::new(source), + &comment_ranges, + &[], + &noqa_line_for, + LineEnding::Lf, + ); + assert_eq!( + edits, + vec![Some(Edit::replacement( + " # noqa: E703\n".to_string(), + 4.into(), + 5.into() + ))] + ); + } }