From 2c41c54e0c5b80c749cb1c4a7baf0fcdfbf1e579 Mon Sep 17 00:00:00 2001 From: Micha Reiser Date: Sat, 3 Jun 2023 16:06:14 +0200 Subject: [PATCH] Format `ExprName` (#4803) --- .../src/expression/expr_name.rs | 45 +++++++++++++++++-- 1 file changed, 42 insertions(+), 3 deletions(-) diff --git a/crates/ruff_python_formatter/src/expression/expr_name.rs b/crates/ruff_python_formatter/src/expression/expr_name.rs index b19333ff4c..18605603e5 100644 --- a/crates/ruff_python_formatter/src/expression/expr_name.rs +++ b/crates/ruff_python_formatter/src/expression/expr_name.rs @@ -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 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)) + ); } }