mirror of
https://github.com/astral-sh/ruff.git
synced 2025-09-15 06:45:21 +00:00
perf(formatter): Improve is_expression_parenthesized
performance (#5825)
This commit is contained in:
parent
1aa851796e
commit
3b32e3a8fe
2 changed files with 27 additions and 9 deletions
|
@ -1,6 +1,6 @@
|
|||
use crate::context::NodeLevel;
|
||||
use crate::prelude::*;
|
||||
use crate::trivia::{first_non_trivia_token, first_non_trivia_token_rev, Token, TokenKind};
|
||||
use crate::trivia::{first_non_trivia_token, SimpleTokenizer, Token, TokenKind};
|
||||
use ruff_formatter::prelude::tag::Condition;
|
||||
use ruff_formatter::{format_args, write, Argument, Arguments};
|
||||
use ruff_python_ast::node::AnyNodeRef;
|
||||
|
@ -72,19 +72,27 @@ pub enum Parentheses {
|
|||
}
|
||||
|
||||
pub(crate) fn is_expression_parenthesized(expr: AnyNodeRef, contents: &str) -> bool {
|
||||
matches!(
|
||||
// First test if there's a closing parentheses because it tends to be cheaper.
|
||||
if matches!(
|
||||
first_non_trivia_token(expr.end(), contents),
|
||||
Some(Token {
|
||||
kind: TokenKind::RParen,
|
||||
..
|
||||
})
|
||||
) && matches!(
|
||||
first_non_trivia_token_rev(expr.start(), contents),
|
||||
Some(Token {
|
||||
kind: TokenKind::LParen,
|
||||
..
|
||||
})
|
||||
)
|
||||
) {
|
||||
let mut tokenizer =
|
||||
SimpleTokenizer::up_to_without_back_comment(expr.start(), contents).skip_trivia();
|
||||
|
||||
matches!(
|
||||
tokenizer.next_back(),
|
||||
Some(Token {
|
||||
kind: TokenKind::LParen,
|
||||
..
|
||||
})
|
||||
)
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Formats `content` enclosed by the `left` and `right` parentheses. The implementation also ensures
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue