Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Format ExprName #4803

Merged
merged 1 commit into from
Jun 3, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 42 additions & 3 deletions crates/ruff_python_formatter/src/expression/expr_name.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,51 @@
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)]
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))
);
}
}