<!-- Thank you for contributing to Ruff! To help us out with reviewing, please consider the following: - Does this pull request include a summary of the change? (See below.) - Does this pull request include a descriptive title? - Does this pull request include references to any relevant issues? --> ## Summary I started working on this because I assumed that I would need access to options inside of `NeedsParantheses` but it then turned out that I won't. Anyway, it kind of felt nice to pass fewer arguments. So I'm gonna put this out here to get your feedback if you prefer this over passing individual fiels. Oh, I sneeked in another change. I renamed `context.contents` to `source`. `contents` is too generic and doesn't tell you anything. <!-- What's the purpose of the change? What does it do, and why? --> ## Test Plan It compiles
65 lines
1.7 KiB
Rust
65 lines
1.7 KiB
Rust
use crate::expression::parentheses::{
|
|
default_expression_needs_parentheses, NeedsParentheses, Parentheses, Parenthesize,
|
|
};
|
|
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<()> {
|
|
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)])
|
|
}
|
|
}
|
|
|
|
impl NeedsParentheses for ExprName {
|
|
fn needs_parentheses(
|
|
&self,
|
|
parenthesize: Parenthesize,
|
|
context: &PyFormatContext,
|
|
) -> Parentheses {
|
|
default_expression_needs_parentheses(self.into(), parenthesize, context)
|
|
}
|
|
}
|
|
|
|
#[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))
|
|
);
|
|
}
|
|
}
|