Skip to content

Commit

Permalink
Detect noqa directives for multi-line f-strings
Browse files Browse the repository at this point in the history
  • Loading branch information
dhruvmanila committed Sep 14, 2023
1 parent 4df8e0a commit 0a404ec
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions crates/ruff/src/directives.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,27 @@ fn extract_noqa_line_for(lxr: &[LexResult], locator: &Locator, indexer: &Indexer
break;
}

// F-strings can be multi-line even without triple quotes. For example,
//
// ```python
// f"foo {
// x
// *
// y
// }"
// ```
//
// We expect `noqa` directives on the last line of the f-string.
Tok::FStringEnd => {
// SAFETY: If we're at the end of a f-string, the indexer must have a
// corresponding f-string range for it.
let f_string_start = indexer.f_string_range(range.start()).unwrap().start();
string_mappings.push(TextRange::new(
locator.line_start(f_string_start),
range.end(),
));
}

// For multi-line strings, we expect `noqa` directives on the last line of the
// string.
Tok::String {
Expand Down Expand Up @@ -429,6 +450,50 @@ ghi
NoqaMapping::from_iter([TextRange::new(TextSize::from(6), TextSize::from(28))])
);

let contents = "x = f'abc {
a
*
b
}'
y = 2
";
assert_eq!(
noqa_mappings(contents),
NoqaMapping::from_iter([TextRange::new(TextSize::from(0), TextSize::from(32))])
);

let contents = "x = f'''abc
def
ghi
'''
y = 2
z = x + 1";
assert_eq!(
noqa_mappings(contents),
NoqaMapping::from_iter([TextRange::new(TextSize::from(0), TextSize::from(23))])
);

let contents = "x = 1
y = f'''abc
def
ghi
'''
z = 2";
assert_eq!(
noqa_mappings(contents),
NoqaMapping::from_iter([TextRange::new(TextSize::from(6), TextSize::from(29))])
);

let contents = "x = 1
y = f'''abc
def
ghi
'''";
assert_eq!(
noqa_mappings(contents),
NoqaMapping::from_iter([TextRange::new(TextSize::from(6), TextSize::from(29))])
);

let contents = r"x = \
1";
assert_eq!(
Expand Down

0 comments on commit 0a404ec

Please sign in to comment.