Skip to content

Commit 2f1ed7e

Browse files
amyreeseAlexWaygood
authored andcommitted
Fix suppression indentation matching (#22903)
When loading suppression comments from tokens, fix the token lookback to look far enough back to find an indent token that isn't matched by a dedent token. This prevents the system from marking "enable" comments as having "invalid indentation". Fix #22869
1 parent edc61da commit 2f1ed7e

1 file changed

Lines changed: 78 additions & 1 deletion

File tree

crates/ruff_linter/src/suppression.rs

Lines changed: 78 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -501,9 +501,18 @@ impl<'a> SuppressionsBuilder<'a> {
501501
indents.clear();
502502

503503
let (before, after) = tokens.split_at(suppression.range.start());
504+
let mut count = 0;
504505
let last_indent = before
505506
.iter()
506-
.rfind(|token| token.kind() == TokenKind::Indent)
507+
.rfind(|token| {
508+
// look for the last indent not matched by a dedent
509+
count += match token.kind() {
510+
TokenKind::Dedent => 1,
511+
TokenKind::Indent => -1,
512+
_ => return false,
513+
};
514+
token.kind() == TokenKind::Indent && count < 0
515+
})
507516
.map(|token| self.source.slice(token))
508517
.unwrap_or_default();
509518

@@ -920,6 +929,74 @@ print('hello')
920929
);
921930
}
922931

932+
#[test]
933+
fn single_range_suppression_after_dedent() {
934+
let source = "
935+
def outer():
936+
def inner():
937+
pass
938+
939+
# ruff: disable[foo]
940+
print('hello')
941+
# ruff: enable[foo]
942+
943+
# ruff: disable[bar]
944+
print('hello')
945+
# ruff: enable[bar]
946+
";
947+
assert_debug_snapshot!(
948+
Suppressions::debug(source),
949+
@r##"
950+
Suppressions {
951+
valid: [
952+
Suppression {
953+
covered_source: "# ruff: disable[foo]\n print('hello')\n # ruff: enable[foo]",
954+
code: "foo",
955+
disable_comment: SuppressionComment {
956+
text: "# ruff: disable[foo]",
957+
action: Disable,
958+
codes: [
959+
"foo",
960+
],
961+
reason: "",
962+
},
963+
enable_comment: SuppressionComment {
964+
text: "# ruff: enable[foo]",
965+
action: Enable,
966+
codes: [
967+
"foo",
968+
],
969+
reason: "",
970+
},
971+
},
972+
Suppression {
973+
covered_source: "# ruff: disable[bar]\nprint('hello')\n# ruff: enable[bar]",
974+
code: "bar",
975+
disable_comment: SuppressionComment {
976+
text: "# ruff: disable[bar]",
977+
action: Disable,
978+
codes: [
979+
"bar",
980+
],
981+
reason: "",
982+
},
983+
enable_comment: SuppressionComment {
984+
text: "# ruff: enable[bar]",
985+
action: Enable,
986+
codes: [
987+
"bar",
988+
],
989+
reason: "",
990+
},
991+
},
992+
],
993+
invalid: [],
994+
errors: [],
995+
}
996+
"##,
997+
);
998+
}
999+
9231000
#[test]
9241001
fn single_range_suppression_implicit_match() {
9251002
let source = "

0 commit comments

Comments
 (0)