mirror of
https://github.com/astral-sh/ruff.git
synced 2025-09-26 11:59:10 +00:00
Remove AstNode
and AnyNode
(#15479)
While looking into potential AST optimizations, I noticed the `AstNode` trait and `AnyNode` type aren't used anywhere in Ruff or Red Knot. It looks like they might be historical artifacts of previous ways of consuming AST nodes? - `AstNode::cast`, `AstNode::cast_ref`, and `AstNode::can_cast` are not used anywhere. - Since `cast_ref` isn't needed anymore, the `Ref` associated type isn't either. This is a pure refactoring, with no intended behavior changes.
This commit is contained in:
parent
8e3633f55a
commit
98ef564170
24 changed files with 52 additions and 5349 deletions
|
@ -4,7 +4,6 @@ use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation};
|
|||
use ruff_macros::{derive_message_formats, ViolationMetadata};
|
||||
use ruff_python_ast::comparable::ComparableExpr;
|
||||
use ruff_python_ast::parenthesize::parenthesized_range;
|
||||
use ruff_python_ast::AstNode;
|
||||
use ruff_python_ast::{self as ast, Expr, ExprCall, ExprContext};
|
||||
use ruff_python_codegen::Generator;
|
||||
use ruff_python_trivia::CommentRanges;
|
||||
|
@ -324,7 +323,7 @@ fn get_parametrize_name_range(
|
|||
) -> Option<TextRange> {
|
||||
parenthesized_range(
|
||||
expr.into(),
|
||||
call.arguments.as_any_node_ref(),
|
||||
(&call.arguments).into(),
|
||||
comment_ranges,
|
||||
source,
|
||||
)
|
||||
|
|
|
@ -3,7 +3,7 @@ use std::ops::Range;
|
|||
use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Diagnostic, Edit, Fix};
|
||||
use ruff_macros::{derive_message_formats, ViolationMetadata};
|
||||
use ruff_python_ast::parenthesize::parenthesized_range;
|
||||
use ruff_python_ast::{AstNode, Expr, ExprBinOp, ExprCall, Operator};
|
||||
use ruff_python_ast::{Expr, ExprBinOp, ExprCall, Operator};
|
||||
use ruff_python_semantic::SemanticModel;
|
||||
use ruff_python_trivia::CommentRanges;
|
||||
use ruff_text_size::{Ranged, TextRange};
|
||||
|
@ -134,12 +134,6 @@ fn parent_and_next_path_fragment_range(
|
|||
|
||||
Some((
|
||||
parent.range(),
|
||||
parenthesized_range(
|
||||
right.into(),
|
||||
parent.as_any_node_ref(),
|
||||
comment_ranges,
|
||||
source,
|
||||
)
|
||||
.unwrap_or(range),
|
||||
parenthesized_range(right.into(), parent.into(), comment_ranges, source).unwrap_or(range),
|
||||
))
|
||||
}
|
||||
|
|
|
@ -2,7 +2,7 @@ use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation};
|
|||
use ruff_macros::{derive_message_formats, ViolationMetadata};
|
||||
use ruff_python_ast::parenthesize::parenthesized_range;
|
||||
use ruff_python_ast::{
|
||||
self as ast, AstNode, Expr, ExprEllipsisLiteral, ExprLambda, Identifier, Parameter,
|
||||
self as ast, Expr, ExprEllipsisLiteral, ExprLambda, Identifier, Parameter,
|
||||
ParameterWithDefault, Parameters, Stmt,
|
||||
};
|
||||
use ruff_python_semantic::SemanticModel;
|
||||
|
@ -263,7 +263,7 @@ fn replace_trailing_ellipsis_with_original_expr(
|
|||
) -> String {
|
||||
let original_expr_range = parenthesized_range(
|
||||
(&lambda.body).into(),
|
||||
lambda.as_any_node_ref(),
|
||||
lambda.into(),
|
||||
checker.comment_ranges(),
|
||||
checker.source(),
|
||||
)
|
||||
|
|
|
@ -4,7 +4,7 @@ use ruff_macros::{derive_message_formats, ViolationMetadata};
|
|||
use ruff_python_ast as ast;
|
||||
use ruff_python_ast::comparable::ComparableExpr;
|
||||
use ruff_python_ast::parenthesize::parenthesized_range;
|
||||
use ruff_python_ast::{AstNode, ExprBinOp, ExpressionRef, Operator};
|
||||
use ruff_python_ast::{ExprBinOp, ExpressionRef, Operator};
|
||||
use ruff_text_size::{Ranged, TextRange};
|
||||
|
||||
use crate::checkers::ast::Checker;
|
||||
|
@ -147,7 +147,7 @@ fn augmented_assignment(
|
|||
let locator = checker.locator();
|
||||
|
||||
let right_operand_ref = ExpressionRef::from(right_operand);
|
||||
let parent = original_expr.as_any_node_ref();
|
||||
let parent = original_expr.into();
|
||||
let comment_ranges = checker.comment_ranges();
|
||||
let source = checker.source();
|
||||
|
||||
|
|
|
@ -4,7 +4,6 @@ use itertools::Itertools;
|
|||
use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
|
||||
use ruff_macros::{derive_message_formats, ViolationMetadata};
|
||||
use ruff_python_ast::parenthesize::parenthesized_range;
|
||||
use ruff_python_ast::AstNode;
|
||||
use ruff_python_ast::{self as ast, Arguments, Expr};
|
||||
use ruff_python_semantic::SemanticModel;
|
||||
use ruff_text_size::Ranged;
|
||||
|
@ -110,7 +109,7 @@ fn convert_to_reduce(iterable: &Expr, call: &ast::ExprCall, checker: &Checker) -
|
|||
let iterable = checker.locator().slice(
|
||||
parenthesized_range(
|
||||
iterable.into(),
|
||||
call.arguments.as_any_node_ref(),
|
||||
(&call.arguments).into(),
|
||||
checker.comment_ranges(),
|
||||
checker.locator().contents(),
|
||||
)
|
||||
|
|
|
@ -23,9 +23,8 @@
|
|||
# is, `StmtIf` will become `if_stmt`.)
|
||||
#
|
||||
# anynode_is_label: foo_bar
|
||||
# Controls the name of the AnyNode::foo_bar, AnyNode::is_foo_bar, and
|
||||
# AnyNodeRef::is_foo_bar methods. The default is the group name in
|
||||
# snake_case.
|
||||
# Controls the name of the AnyNodeRef::is_foo_bar method. The default is the
|
||||
# group name in snake_case.
|
||||
#
|
||||
# ref_enum_ty:
|
||||
# The name of the reference enum that we create for this group. The default
|
||||
|
|
|
@ -265,141 +265,6 @@ def write_ref_enum(out: list[str], groups: list[Group]) -> None:
|
|||
""")
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# AnyNode
|
||||
|
||||
|
||||
def write_anynode(out: list[str], groups: list[Group]) -> None:
|
||||
"""
|
||||
Create the AnyNode type.
|
||||
|
||||
```rust
|
||||
pub enum AnyNode {
|
||||
...
|
||||
TypeParamTypeVar(TypeParamTypeVar),
|
||||
TypeParamTypeVarTuple(TypeParamTypeVarTuple),
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
Also creates:
|
||||
- `impl From<TypeParam> for AnyNode`
|
||||
- `impl From<TypeParamTypeVarTuple> for AnyNode`
|
||||
- `impl Ranged for AnyNode`
|
||||
- `fn AnyNode::type_param(self) -> Option<TypeParam>`
|
||||
- `fn AnyNode::is_type_param(&self) -> bool`
|
||||
- `fn AnyNode::is_type_param_type_var(&self) -> bool`
|
||||
- `fn AnyNode::as_ref(&self) -> AnyNodeRef`
|
||||
|
||||
The name of the `type_param` and `is_type_param` methods can be customized
|
||||
via the `anynode_is_label` group option.
|
||||
"""
|
||||
|
||||
out.append("""
|
||||
#[derive(Clone, Debug, is_macro::Is, PartialEq)]
|
||||
pub enum AnyNode {
|
||||
""")
|
||||
for group in groups:
|
||||
for node in group.nodes:
|
||||
out.append(f"{node.name}({node.ty}),")
|
||||
out.append("""
|
||||
}
|
||||
""")
|
||||
|
||||
for group in groups:
|
||||
if group.name != "ungrouped":
|
||||
out.append(f"""
|
||||
impl From<{group.owned_enum_ty}> for AnyNode {{
|
||||
fn from(node: {group.owned_enum_ty}) -> AnyNode {{
|
||||
match node {{
|
||||
""")
|
||||
for node in group.nodes:
|
||||
out.append(
|
||||
f"""{group.owned_enum_ty}::{node.variant}(node) => AnyNode::{node.name}(node),"""
|
||||
)
|
||||
out.append("""
|
||||
}
|
||||
}
|
||||
}
|
||||
""")
|
||||
|
||||
for node in group.nodes:
|
||||
out.append(f"""
|
||||
impl From<{node.ty}> for AnyNode {{
|
||||
fn from(node: {node.ty}) -> AnyNode {{
|
||||
AnyNode::{node.name}(node)
|
||||
}}
|
||||
}}
|
||||
""")
|
||||
|
||||
out.append("""
|
||||
impl ruff_text_size::Ranged for AnyNode {
|
||||
fn range(&self) -> ruff_text_size::TextRange {
|
||||
match self {
|
||||
""")
|
||||
for group in groups:
|
||||
for node in group.nodes:
|
||||
out.append(f"""AnyNode::{node.name}(node) => node.range(),""")
|
||||
out.append("""
|
||||
}
|
||||
}
|
||||
}
|
||||
""")
|
||||
|
||||
for group in groups:
|
||||
if group.name == "ungrouped":
|
||||
continue
|
||||
out.append(f"""
|
||||
impl AnyNode {{
|
||||
pub fn {group.anynode_is_label}(self) -> Option<{group.owned_enum_ty}> {{
|
||||
match self {{
|
||||
""")
|
||||
for node in group.nodes:
|
||||
out.append(
|
||||
f"""AnyNode::{node.name}(node) => Some({group.owned_enum_ty}::{node.variant}(node)),"""
|
||||
)
|
||||
out.append("""
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
""")
|
||||
|
||||
for group in groups:
|
||||
if group.name == "ungrouped":
|
||||
continue
|
||||
out.append(f"""
|
||||
impl AnyNode {{
|
||||
pub const fn is_{group.anynode_is_label}(&self) -> bool {{
|
||||
matches!(self,
|
||||
""")
|
||||
for i, node in enumerate(group.nodes):
|
||||
if i > 0:
|
||||
out.append("|")
|
||||
out.append(f"""AnyNode::{node.name}(_)""")
|
||||
out.append("""
|
||||
)
|
||||
}
|
||||
}
|
||||
""")
|
||||
|
||||
out.append("""
|
||||
impl AnyNode {
|
||||
pub const fn as_ref(&self) -> AnyNodeRef {
|
||||
match self {
|
||||
""")
|
||||
for group in groups:
|
||||
for node in group.nodes:
|
||||
out.append(
|
||||
f"""AnyNode::{node.name}(node) => AnyNodeRef::{node.name}(node),"""
|
||||
)
|
||||
out.append("""
|
||||
}
|
||||
}
|
||||
}
|
||||
""")
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# AnyNodeRef
|
||||
|
||||
|
@ -424,7 +289,6 @@ def write_anynoderef(out: list[str], groups: list[Group]) -> None:
|
|||
- `impl Ranged for AnyNodeRef<'_>`
|
||||
- `fn AnyNodeRef::as_ptr(&self) -> std::ptr::NonNull<()>`
|
||||
- `fn AnyNodeRef::visit_preorder(self, visitor &mut impl SourceOrderVisitor)`
|
||||
- `fn AnyNode::is_type_param(&self) -> bool`
|
||||
"""
|
||||
|
||||
out.append("""
|
||||
|
@ -565,7 +429,6 @@ def write_nodekind(out: list[str], groups: list[Group]) -> None:
|
|||
}
|
||||
|
||||
Also creates:
|
||||
- `fn AnyNode::kind(&self) -> NodeKind`
|
||||
- `fn AnyNodeRef::kind(self) -> NodeKind`
|
||||
```
|
||||
"""
|
||||
|
@ -581,20 +444,6 @@ def write_nodekind(out: list[str], groups: list[Group]) -> None:
|
|||
}
|
||||
""")
|
||||
|
||||
out.append("""
|
||||
impl AnyNode {
|
||||
pub const fn kind(&self) -> NodeKind {
|
||||
match self {
|
||||
""")
|
||||
for group in groups:
|
||||
for node in group.nodes:
|
||||
out.append(f"""AnyNode::{node.name}(_) => NodeKind::{node.name},""")
|
||||
out.append("""
|
||||
}
|
||||
}
|
||||
}
|
||||
""")
|
||||
|
||||
out.append("""
|
||||
impl AnyNodeRef<'_> {
|
||||
pub const fn kind(self) -> NodeKind {
|
||||
|
@ -610,110 +459,6 @@ def write_nodekind(out: list[str], groups: list[Group]) -> None:
|
|||
""")
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# AstNode
|
||||
|
||||
|
||||
def write_astnode(out: list[str], groups: list[Group]) -> None:
|
||||
"""
|
||||
Creates AstNode trait impls:
|
||||
- `impl AstNode for TypeParam`
|
||||
- `impl AstNode for TypeParamTypeVar`
|
||||
"""
|
||||
|
||||
for group in groups:
|
||||
if group.name != "ungrouped":
|
||||
out.append(f"""
|
||||
impl crate::AstNode for {group.owned_enum_ty} {{
|
||||
type Ref<'a> = {group.ref_enum_ty}<'a>;
|
||||
|
||||
fn cast(node: AnyNode) -> Option<Self>
|
||||
where
|
||||
Self: Sized,
|
||||
{{
|
||||
match node {{
|
||||
""")
|
||||
for node in group.nodes:
|
||||
out.append(
|
||||
f"""AnyNode::{node.name}(node) => Some({group.owned_enum_ty}::{node.variant}(node)),"""
|
||||
)
|
||||
out.append("""
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn cast_ref(node: AnyNodeRef) -> Option<Self::Ref<'_>> {
|
||||
match node {
|
||||
""")
|
||||
for node in group.nodes:
|
||||
out.append(
|
||||
f"""AnyNodeRef::{node.name}(node) => Some({group.ref_enum_ty}::{node.variant}(node)),"""
|
||||
)
|
||||
out.append("""
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn can_cast(kind: NodeKind) -> bool {
|
||||
matches!(kind,
|
||||
""")
|
||||
for i, node in enumerate(group.nodes):
|
||||
if i > 0:
|
||||
out.append("|")
|
||||
out.append(f"""NodeKind::{node.name}""")
|
||||
out.append("""
|
||||
)
|
||||
}
|
||||
|
||||
fn as_any_node_ref(&self) -> AnyNodeRef {
|
||||
AnyNodeRef::from(self)
|
||||
}
|
||||
|
||||
fn into_any_node(self) -> AnyNode {
|
||||
AnyNode::from(self)
|
||||
}
|
||||
}
|
||||
""")
|
||||
|
||||
for node in group.nodes:
|
||||
out.append(f"""
|
||||
impl crate::AstNode for {node.ty} {{
|
||||
type Ref<'a> = &'a Self;
|
||||
|
||||
fn cast(kind: AnyNode) -> Option<Self>
|
||||
where
|
||||
Self: Sized,
|
||||
{{
|
||||
if let AnyNode::{node.name}(node) = kind {{
|
||||
Some(node)
|
||||
}} else {{
|
||||
None
|
||||
}}
|
||||
}}
|
||||
|
||||
fn cast_ref(kind: AnyNodeRef) -> Option<&Self> {{
|
||||
if let AnyNodeRef::{node.name}(node) = kind {{
|
||||
Some(node)
|
||||
}} else {{
|
||||
None
|
||||
}}
|
||||
}}
|
||||
|
||||
fn can_cast(kind: NodeKind) -> bool {{
|
||||
matches!(kind, NodeKind::{node.name})
|
||||
}}
|
||||
|
||||
fn as_any_node_ref(&self) -> AnyNodeRef {{
|
||||
AnyNodeRef::from(self)
|
||||
}}
|
||||
|
||||
fn into_any_node(self) -> AnyNode {{
|
||||
AnyNode::from(self)
|
||||
}}
|
||||
}}
|
||||
""")
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# Format and write output
|
||||
|
||||
|
@ -723,10 +468,8 @@ def generate(groups: list[Group]) -> list[str]:
|
|||
write_preamble(out)
|
||||
write_owned_enum(out, groups)
|
||||
write_ref_enum(out, groups)
|
||||
write_anynode(out, groups)
|
||||
write_anynoderef(out, groups)
|
||||
write_nodekind(out, groups)
|
||||
write_astnode(out, groups)
|
||||
return out
|
||||
|
||||
|
||||
|
|
5004
crates/ruff_python_ast/src/generated.rs
generated
5004
crates/ruff_python_ast/src/generated.rs
generated
File diff suppressed because it is too large
Load diff
|
@ -4,7 +4,6 @@ use std::path::Path;
|
|||
pub use expression::*;
|
||||
pub use generated::*;
|
||||
pub use int::*;
|
||||
pub use node::AstNode;
|
||||
pub use nodes::*;
|
||||
|
||||
pub mod comparable;
|
||||
|
|
|
@ -1,26 +1,8 @@
|
|||
use crate::visitor::source_order::SourceOrderVisitor;
|
||||
use crate::{
|
||||
self as ast, Alias, AnyNode, AnyNodeRef, AnyParameterRef, ArgOrKeyword, MatchCase, NodeKind,
|
||||
PatternArguments, PatternKeyword,
|
||||
self as ast, Alias, AnyNodeRef, AnyParameterRef, ArgOrKeyword, MatchCase, PatternArguments,
|
||||
PatternKeyword,
|
||||
};
|
||||
use ruff_text_size::Ranged;
|
||||
|
||||
pub trait AstNode: Ranged {
|
||||
type Ref<'a>;
|
||||
|
||||
fn cast(kind: AnyNode) -> Option<Self>
|
||||
where
|
||||
Self: Sized;
|
||||
fn cast_ref(kind: AnyNodeRef<'_>) -> Option<Self::Ref<'_>>;
|
||||
|
||||
fn can_cast(kind: NodeKind) -> bool;
|
||||
|
||||
/// Returns the [`AnyNodeRef`] referencing this node.
|
||||
fn as_any_node_ref(&self) -> AnyNodeRef;
|
||||
|
||||
/// Consumes `self` and returns its [`AnyNode`] representation.
|
||||
fn into_any_node(self) -> AnyNode;
|
||||
}
|
||||
|
||||
impl ast::ModModule {
|
||||
pub(crate) fn visit_source_order<'a, V>(&'a self, visitor: &mut V)
|
||||
|
|
|
@ -28,11 +28,11 @@ nodes_file = (
|
|||
.read_text()
|
||||
)
|
||||
node_lines = (
|
||||
nodes_file.split("pub enum AnyNode {")[1].split("}")[0].strip().splitlines()
|
||||
nodes_file.split("pub enum AnyNodeRef<'a> {")[1].split("}")[0].strip().splitlines()
|
||||
)
|
||||
nodes = []
|
||||
for node_line in node_lines:
|
||||
node = node_line.split("(")[1].split(")")[0].split("::")[-1].split("<")[0]
|
||||
node = node_line.split("(")[1].split(")")[0].split("::")[-1].removeprefix("&'a ")
|
||||
# `FString` has a custom implementation while the formatting for
|
||||
# `FStringLiteralElement`, `FStringFormatSpec` and `FStringExpressionElement` are handled by the `FString`
|
||||
# implementation.
|
||||
|
|
|
@ -184,7 +184,7 @@ mod tests {
|
|||
use insta::assert_debug_snapshot;
|
||||
|
||||
use ruff_formatter::SourceCode;
|
||||
use ruff_python_ast::AnyNode;
|
||||
use ruff_python_ast::AnyNodeRef;
|
||||
use ruff_python_ast::{StmtBreak, StmtContinue};
|
||||
use ruff_python_trivia::{CommentLinePosition, CommentRanges};
|
||||
use ruff_text_size::{TextRange, TextSize};
|
||||
|
@ -194,13 +194,13 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn debug() {
|
||||
let continue_statement = AnyNode::from(StmtContinue {
|
||||
let continue_statement = StmtContinue {
|
||||
range: TextRange::new(TextSize::new(18), TextSize::new(26)),
|
||||
});
|
||||
};
|
||||
|
||||
let break_statement = AnyNode::from(StmtBreak {
|
||||
let break_statement = StmtBreak {
|
||||
range: TextRange::new(TextSize::new(55), TextSize::new(60)),
|
||||
});
|
||||
};
|
||||
|
||||
let source = r"# leading comment
|
||||
continue; # trailing
|
||||
|
@ -213,7 +213,7 @@ break;
|
|||
let mut comments_map: CommentsMap = MultiMap::new();
|
||||
|
||||
comments_map.push_leading(
|
||||
continue_statement.as_ref().into(),
|
||||
AnyNodeRef::from(&continue_statement).into(),
|
||||
SourceComment::new(
|
||||
source_code.slice(TextRange::at(TextSize::new(0), TextSize::new(17))),
|
||||
CommentLinePosition::OwnLine,
|
||||
|
@ -221,7 +221,7 @@ break;
|
|||
);
|
||||
|
||||
comments_map.push_trailing(
|
||||
continue_statement.as_ref().into(),
|
||||
AnyNodeRef::from(&continue_statement).into(),
|
||||
SourceComment::new(
|
||||
source_code.slice(TextRange::at(TextSize::new(28), TextSize::new(10))),
|
||||
CommentLinePosition::EndOfLine,
|
||||
|
@ -229,7 +229,7 @@ break;
|
|||
);
|
||||
|
||||
comments_map.push_leading(
|
||||
break_statement.as_ref().into(),
|
||||
AnyNodeRef::from(&break_statement).into(),
|
||||
SourceComment::new(
|
||||
source_code.slice(TextRange::at(TextSize::new(39), TextSize::new(15))),
|
||||
CommentLinePosition::OwnLine,
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
use std::borrow::Cow;
|
||||
|
||||
use ruff_formatter::{format_args, write, FormatError, FormatOptions, SourceCode};
|
||||
use ruff_python_ast::{AnyNodeRef, AstNode, NodeKind, PySourceType};
|
||||
use ruff_python_ast::{AnyNodeRef, NodeKind, PySourceType};
|
||||
use ruff_python_trivia::{
|
||||
is_pragma_comment, lines_after, lines_after_ignoring_trivia, lines_before, CommentLinePosition,
|
||||
};
|
||||
|
@ -13,11 +13,11 @@ use crate::prelude::*;
|
|||
use crate::statement::suite::should_insert_blank_line_after_class_in_stub_file;
|
||||
|
||||
/// Formats the leading comments of a node.
|
||||
pub(crate) fn leading_node_comments<T>(node: &T) -> FormatLeadingComments
|
||||
pub(crate) fn leading_node_comments<'a, T>(node: T) -> FormatLeadingComments<'a>
|
||||
where
|
||||
T: AstNode,
|
||||
T: Into<AnyNodeRef<'a>>,
|
||||
{
|
||||
FormatLeadingComments::Node(node.as_any_node_ref())
|
||||
FormatLeadingComments::Node(node.into())
|
||||
}
|
||||
|
||||
/// Formats the passed comments as leading comments
|
||||
|
@ -192,11 +192,11 @@ impl Format<PyFormatContext<'_>> for FormatTrailingComments<'_> {
|
|||
}
|
||||
|
||||
/// Formats the dangling comments of `node`.
|
||||
pub(crate) fn dangling_node_comments<T>(node: &T) -> FormatDanglingComments
|
||||
pub(crate) fn dangling_node_comments<'a, T>(node: T) -> FormatDanglingComments<'a>
|
||||
where
|
||||
T: AstNode,
|
||||
T: Into<AnyNodeRef<'a>>,
|
||||
{
|
||||
FormatDanglingComments::Node(node.as_any_node_ref())
|
||||
FormatDanglingComments::Node(node.into())
|
||||
}
|
||||
|
||||
pub(crate) fn dangling_comments(comments: &[SourceComment]) -> FormatDanglingComments {
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
use ruff_formatter::{write, FormatError};
|
||||
use ruff_python_ast::{AnyNodeRef, AstNode};
|
||||
use ruff_python_ast::AnyNodeRef;
|
||||
use ruff_python_ast::{Expr, ExprSlice, ExprUnaryOp, UnaryOp};
|
||||
use ruff_python_trivia::{SimpleToken, SimpleTokenKind, SimpleTokenizer};
|
||||
use ruff_text_size::{Ranged, TextRange};
|
||||
|
@ -36,7 +36,7 @@ impl FormatNodeRule<ExprSlice> for FormatExprSlice {
|
|||
// to handle newlines and spacing, or the node is None and we insert the corresponding
|
||||
// slice of dangling comments
|
||||
let comments = f.context().comments().clone();
|
||||
let slice_dangling_comments = comments.dangling(item.as_any_node_ref());
|
||||
let slice_dangling_comments = comments.dangling(item);
|
||||
// Put the dangling comments (where the nodes are missing) into buckets
|
||||
let first_colon_partition_index =
|
||||
slice_dangling_comments.partition_point(|x| x.start() < first_colon.start());
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
use ruff_formatter::{write, FormatRuleWithOptions};
|
||||
use ruff_python_ast::{AnyNodeRef, AstNode};
|
||||
use ruff_python_ast::AnyNodeRef;
|
||||
use ruff_python_ast::{Expr, ExprSubscript};
|
||||
|
||||
use crate::expression::expr_tuple::TupleParentheses;
|
||||
|
@ -35,7 +35,7 @@ impl FormatNodeRule<ExprSubscript> for FormatExprSubscript {
|
|||
let call_chain_layout = self.call_chain_layout.apply_in_node(item, f);
|
||||
|
||||
let comments = f.context().comments().clone();
|
||||
let dangling_comments = comments.dangling(item.as_any_node_ref());
|
||||
let dangling_comments = comments.dangling(item);
|
||||
debug_assert!(
|
||||
dangling_comments.len() <= 1,
|
||||
"A subscript expression can only have a single dangling comment, the one after the bracket"
|
||||
|
|
|
@ -4,10 +4,10 @@ use tracing::Level;
|
|||
pub use range::format_range;
|
||||
use ruff_formatter::prelude::*;
|
||||
use ruff_formatter::{format, write, FormatError, Formatted, PrintError, Printed, SourceCode};
|
||||
use ruff_python_ast::AstNode;
|
||||
use ruff_python_ast::Mod;
|
||||
use ruff_python_ast::{AnyNodeRef, Mod};
|
||||
use ruff_python_parser::{parse, AsMode, ParseError, Parsed};
|
||||
use ruff_python_trivia::CommentRanges;
|
||||
use ruff_text_size::Ranged;
|
||||
|
||||
use crate::comments::{
|
||||
has_skip_comment, leading_comments, trailing_comments, Comments, SourceComment,
|
||||
|
@ -43,23 +43,23 @@ mod verbatim;
|
|||
/// 'ast is the lifetime of the source code (input), 'buf is the lifetime of the buffer (output)
|
||||
pub(crate) type PyFormatter<'ast, 'buf> = Formatter<'buf, PyFormatContext<'ast>>;
|
||||
|
||||
/// Rule for formatting a Python [`AstNode`].
|
||||
/// Rule for formatting a Python AST node.
|
||||
pub(crate) trait FormatNodeRule<N>
|
||||
where
|
||||
N: AstNode,
|
||||
N: Ranged,
|
||||
for<'a> AnyNodeRef<'a>: From<&'a N>,
|
||||
{
|
||||
fn fmt(&self, node: &N, f: &mut PyFormatter) -> FormatResult<()> {
|
||||
let comments = f.context().comments().clone();
|
||||
|
||||
let node_comments = comments.leading_dangling_trailing(node.as_any_node_ref());
|
||||
let node_ref = AnyNodeRef::from(node);
|
||||
let node_comments = comments.leading_dangling_trailing(node_ref);
|
||||
|
||||
if self.is_suppressed(node_comments.trailing, f.context()) {
|
||||
suppressed_node(node.as_any_node_ref()).fmt(f)
|
||||
suppressed_node(node_ref).fmt(f)
|
||||
} else {
|
||||
leading_comments(node_comments.leading).fmt(f)?;
|
||||
|
||||
let node_ref = node.as_any_node_ref();
|
||||
|
||||
// Emit source map information for nodes that are valid "narrowing" targets
|
||||
// in range formatting. Never emit source map information if they're disabled
|
||||
// for performance reasons.
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
use ruff_formatter::{format_args, write, FormatRuleWithOptions};
|
||||
use ruff_python_ast::Parameters;
|
||||
use ruff_python_ast::{AnyNodeRef, AstNode};
|
||||
use ruff_python_ast::{AnyNodeRef, Parameters};
|
||||
use ruff_python_trivia::{CommentLinePosition, SimpleToken, SimpleTokenKind, SimpleTokenizer};
|
||||
use ruff_text_size::{Ranged, TextRange, TextSize};
|
||||
|
||||
|
@ -165,7 +164,7 @@ impl FormatNodeRule<Parameters> for FormatParameters {
|
|||
token("*"),
|
||||
vararg.format()
|
||||
]);
|
||||
last_node = Some(vararg.as_any_node_ref());
|
||||
last_node = Some(vararg.as_ref().into());
|
||||
} else if !kwonlyargs.is_empty() {
|
||||
// Given very strange comment placement, comments here may not actually have been
|
||||
// marked as `StarLeading`/`StarTrailing`, but that's fine since we still produce
|
||||
|
@ -201,7 +200,7 @@ impl FormatNodeRule<Parameters> for FormatParameters {
|
|||
token("**"),
|
||||
kwarg.format()
|
||||
]);
|
||||
last_node = Some(kwarg.as_any_node_ref());
|
||||
last_node = Some(kwarg.as_ref().into());
|
||||
}
|
||||
|
||||
joiner.finish()?;
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
use ruff_formatter::write;
|
||||
use ruff_python_ast::AstNode;
|
||||
use ruff_python_ast::{Pattern, PatternArguments};
|
||||
use ruff_python_trivia::{SimpleTokenKind, SimpleTokenizer};
|
||||
use ruff_text_size::{Ranged, TextRange, TextSize};
|
||||
|
@ -63,7 +62,7 @@ impl FormatNodeRule<PatternArguments> for FormatPatternArguments {
|
|||
// )
|
||||
// ```
|
||||
let comments = f.context().comments().clone();
|
||||
let dangling_comments = comments.dangling(item.as_any_node_ref());
|
||||
let dangling_comments = comments.dangling(item);
|
||||
|
||||
write!(
|
||||
f,
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
use ruff_formatter::{format_args, write};
|
||||
use ruff_python_ast::AstNode;
|
||||
use ruff_python_ast::StmtGlobal;
|
||||
|
||||
use crate::comments::SourceComment;
|
||||
|
@ -14,7 +13,7 @@ impl FormatNodeRule<StmtGlobal> for FormatStmtGlobal {
|
|||
// Join the `global` names, breaking across continuation lines if necessary, unless the
|
||||
// `global` statement has a trailing comment, in which case, breaking the names would
|
||||
// move the comment "off" of the `global` statement.
|
||||
if f.context().comments().has_trailing(item.as_any_node_ref()) {
|
||||
if f.context().comments().has_trailing(item) {
|
||||
let joined = format_with(|f| {
|
||||
f.join_with(format_args![token(","), space()])
|
||||
.entries(item.names.iter().formatted())
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
use ruff_formatter::write;
|
||||
use ruff_python_ast::AstNode;
|
||||
use ruff_python_ast::StmtImportFrom;
|
||||
use ruff_text_size::Ranged;
|
||||
|
||||
|
@ -62,7 +61,7 @@ impl FormatNodeRule<StmtImportFrom> for FormatStmtImportFrom {
|
|||
// )
|
||||
// ```
|
||||
let comments = f.context().comments().clone();
|
||||
let parenthesized_comments = comments.dangling(item.as_any_node_ref());
|
||||
let parenthesized_comments = comments.dangling(item);
|
||||
|
||||
if parenthesized_comments.is_empty() {
|
||||
parenthesize_if_expands(&names).fmt(f)
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
use ruff_formatter::{format_args, write};
|
||||
use ruff_python_ast::AstNode;
|
||||
use ruff_python_ast::StmtNonlocal;
|
||||
|
||||
use crate::comments::SourceComment;
|
||||
|
@ -14,7 +13,7 @@ impl FormatNodeRule<StmtNonlocal> for FormatStmtNonlocal {
|
|||
// Join the `nonlocal` names, breaking across continuation lines if necessary, unless the
|
||||
// `nonlocal` statement has a trailing comment, in which case, breaking the names would
|
||||
// move the comment "off" of the `nonlocal` statement.
|
||||
if f.context().comments().has_trailing(item.as_any_node_ref()) {
|
||||
if f.context().comments().has_trailing(item) {
|
||||
let joined = format_with(|f| {
|
||||
f.join_with(format_args![token(","), space()])
|
||||
.entries(item.names.iter().formatted())
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
use ruff_formatter::{format_args, write};
|
||||
use ruff_python_ast::AstNode;
|
||||
use ruff_python_ast::{Stmt, StmtWhile};
|
||||
use ruff_text_size::Ranged;
|
||||
|
||||
|
@ -22,7 +21,7 @@ impl FormatNodeRule<StmtWhile> for FormatStmtWhile {
|
|||
} = item;
|
||||
|
||||
let comments = f.context().comments().clone();
|
||||
let dangling_comments = comments.dangling(item.as_any_node_ref());
|
||||
let dangling_comments = comments.dangling(item);
|
||||
|
||||
let body_start = body.first().map_or(test.end(), Stmt::start);
|
||||
let or_else_comments_start =
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
use ruff_formatter::{format_args, write, FormatContext, FormatError};
|
||||
use ruff_python_ast::StmtWith;
|
||||
use ruff_python_ast::{AstNode, WithItem};
|
||||
use ruff_python_ast::{StmtWith, WithItem};
|
||||
use ruff_python_trivia::{SimpleTokenKind, SimpleTokenizer};
|
||||
use ruff_text_size::{Ranged, TextRange};
|
||||
|
||||
|
@ -36,7 +35,7 @@ impl FormatNodeRule<StmtWith> for FormatStmtWith {
|
|||
// ...
|
||||
// ```
|
||||
let comments = f.context().comments().clone();
|
||||
let dangling_comments = comments.dangling(with_stmt.as_any_node_ref());
|
||||
let dangling_comments = comments.dangling(with_stmt);
|
||||
let partition_point = dangling_comments.partition_point(|comment| {
|
||||
with_stmt
|
||||
.items
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
use ruff_formatter::FormatResult;
|
||||
use ruff_python_ast::AstNode;
|
||||
use ruff_python_ast::TypeParams;
|
||||
use ruff_text_size::Ranged;
|
||||
|
||||
|
@ -21,7 +20,7 @@ impl FormatNodeRule<TypeParams> for FormatTypeParams {
|
|||
// c,
|
||||
// ] = ...
|
||||
let comments = f.context().comments().clone();
|
||||
let dangling_comments = comments.dangling(item.as_any_node_ref());
|
||||
let dangling_comments = comments.dangling(item);
|
||||
|
||||
let items = format_with(|f| {
|
||||
f.join_comma_separated(item.end())
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue