Format ExprName (#4803)

This commit is contained in:
Micha Reiser 2023-06-03 16:06:14 +02:00 committed by GitHub
parent d6daa61563
commit 2c41c54e0c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -1,5 +1,6 @@
use crate::{verbatim_text, FormatNodeRule, PyFormatter};
use ruff_formatter::{write, Buffer, FormatResult};
use crate::prelude::*;
use crate::FormatNodeRule;
use ruff_formatter::{write, FormatContext};
use rustpython_parser::ast::ExprName;
#[derive(Default)]
@ -7,6 +8,44 @@ pub struct FormatExprName;
impl FormatNodeRule<ExprName> for FormatExprName {
fn fmt_fields(&self, item: &ExprName, f: &mut PyFormatter) -> FormatResult<()> {
write!(f, [verbatim_text(item.range)])
let ExprName { id, range, ctx: _ } = item;
debug_assert_eq!(
id.as_str(),
f.context()
.source_code()
.slice(*range)
.text(f.context().source_code())
);
write!(f, [source_text_slice(*range, ContainsNewlines::No)])
}
}
#[cfg(test)]
mod tests {
use ruff_text_size::{TextRange, TextSize};
use rustpython_parser::ast::{ModModule, Ranged};
use rustpython_parser::Parse;
#[test]
fn name_range_with_comments() {
let source = ModModule::parse("a # comment", "file.py").unwrap();
let expression_statement = source
.body
.first()
.expect("Expected non-empty body")
.as_expr_stmt()
.unwrap();
let name = expression_statement
.value
.as_name_expr()
.expect("Expected name expression");
assert_eq!(
name.range(),
TextRange::at(TextSize::new(0), TextSize::new(1))
);
}
}