forked from astral-sh/ruff
-
Notifications
You must be signed in to change notification settings - Fork 0
/
expr_name.rs
68 lines (59 loc) · 1.69 KB
/
expr_name.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use ruff_formatter::write;
use ruff_python_ast::AnyNodeRef;
use ruff_python_ast::ExprName;
use crate::comments::SourceComment;
use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses};
use crate::prelude::*;
#[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;
write!(f, [source_text_slice(*range)])
}
fn fmt_dangling_comments(
&self,
dangling_comments: &[SourceComment],
_f: &mut PyFormatter,
) -> FormatResult<()> {
// Node cannot have dangling comments
debug_assert!(dangling_comments.is_empty());
Ok(())
}
}
impl NeedsParentheses for ExprName {
fn needs_parentheses(
&self,
_parent: AnyNodeRef,
_context: &PyFormatContext,
) -> OptionalParentheses {
OptionalParentheses::BestFit
}
}
#[cfg(test)]
mod tests {
use ruff_python_parser::parse_program;
use ruff_text_size::{Ranged, TextRange, TextSize};
#[test]
fn name_range_with_comments() {
let source = parse_program("a # comment").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))
);
}
}