8000 feat(formatter): fill in implementations by Boshen · Pull Request #10816 · oxc-project/oxc · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

feat(formatter): fill in implementations #10816

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

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to 8000 load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 97 additions & 18 deletions crates/oxc_formatter/src/parentheses/expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ impl<'a> NeedsParentheses<'a> for NumericLiteral<'a> {
if let AstKind::MemberExpression(MemberExpression::StaticMemberExpression(e)) =
stack.parent()
{
return e.object.span() == self.span;
return e.object.without_parentheses().span() == self.span;
}
false
}
Expand All @@ -92,7 +92,8 @@ impl<'a> NeedsParentheses<'a> for ArrayExpression<'a> {

impl<'a> NeedsParentheses<'a> for ObjectExpression<'a> {
fn needs_parentheses(&self, stack: &ParentStack<'a>) -> bool {
false
is_class_extends(stack.parent(), self.span)
|| is_first_in_statement(stack, FirstInStatementMode::ExpressionStatementOrArrow)
}
}

Expand Down Expand Up @@ -128,13 +129,14 @@ impl<'a> NeedsParentheses<'a> for PrivateFieldExpression<'a> {

impl<'a> NeedsParentheses<'a> for CallExpression<'a> {
fn needs_parentheses(&self, stack: &ParentStack<'a>) -> bool {
matches!(stack.parent(), AstKind::ExportDefaultDeclaration(_))
// TODO
matches!(stack.parent(), AstKind::NewExpression(_) | AstKind::ExportDefaultDeclaration(_))
}
}

impl<'a> NeedsParentheses<'a> for NewExpression<'a> {
fn needs_parentheses(&self, stack: &ParentStack<'a>) -> bool {
false
is_class_extends(stack.parent(), self.span)
}
}

Expand Down Expand Up @@ -201,8 +203,9 @@ impl<'a> NeedsParentheses<'a> for LogicalExpression<'a> {

impl<'a> NeedsParentheses<'a> for ConditionalExpression<'a> {
fn needs_parentheses(&self, stack: &ParentStack<'a>) -> bool {
matches!(
stack.parent(),
let parent = stack.parent();
if matches!(
parent,
AstKind::UnaryExpression(_)
| AstKind::AwaitExpression(_)
| AstKind::TSTypeAssertion(_)
Expand All @@ -211,22 +214,37 @@ impl<'a> NeedsParentheses<'a> for ConditionalExpression<'a> {
| AstKind::SpreadElement(_)
| AstKind::LogicalExpression(_)
| AstKind::BinaryExpression(_)
)
) {
return true;
}
if let AstKind::ConditionalExpression(e) = parent {
e.test.without_parentheses().span() == self.span
} else {
update_or_lower_expression_needs_parens(self.span, parent)
}
}
}

impl<'a> NeedsParentheses<'a> for Function<'a> {
fn needs_parentheses(&self, stack: &ParentStack<'a>) -> bool {
if self.r#type == FunctionType::FunctionExpression {
return matches!(stack.parent(), AstKind::ExportDefaultDeclaration(_));
if self.r#type != FunctionType::FunctionExpression {
return false;
}
false
matches!(
stack.parent(),
AstKind::CallExpression(_) | AstKind::NewExpression(_) | AstKind::TemplateLiteral(_)
) || is_first_in_statement(stack, FirstInStatementMode::ExpressionOrExportDefault)
}
}

impl<'a> NeedsParentheses<'a> for AssignmentExpression<'a> {
fn needs_parentheses(&self, stack: &ParentStack<'a>) -> bool {
matches!(stack.parent(), AstKind::ExportDefaultDeclaration(_))
// TODO
match stack.parent() {
AstKind::ArrowFunctionExpression(arrow) => arrow.body.span == self.span,
AstKind::ExportDefaultDeclaration(_) => true,
_ => false,
}
}
}

Expand Down Expand Up @@ -257,10 +275,16 @@ impl<'a> NeedsParentheses<'a> for ChainExpression<'a> {

impl<'a> NeedsParentheses<'a> for Class<'a> {
fn needs_parentheses(&self, stack: &ParentStack<'a>) -> bool {
if self.r#type == ClassType::ClassExpression {
return matches!(stack.parent(), AstKind::ExportDefaultDeclaration(_));
if self.r#type != ClassType::ClassExpression {
return false;
}
match stack.parent() {
AstKind::CallExpression(_)
| AstKind::NewExpression(_)
| AstKind::ExportDefaultDeclaration(_) => true,
parent if is_class_extends(parent, self.span) => true,
_ => is_first_in_statement(stack, FirstInStatementMode::ExpressionOrExportDefault),
}
false
}
}

Expand All @@ -273,7 +297,23 @@ impl<'a> NeedsParentheses<'a> for ParenthesizedExpression<'a> {
impl<'a> NeedsParentheses<'a> for ArrowFunctionExpression<'a> {
fn needs_parentheses(&self, stack: &ParentStack<'a>) -> bool {
let parent = stack.parent();
matches!(parent, AstKind::AwaitExpression(_))
if matches!(
parent,
AstKind::TSAsExpression(_)
| AstKind::TSSatisfiesExpression(_)
| AstKind::TSTypeAssertion(_)
| AstKind::UnaryExpression(_)
| AstKind::AwaitExpression(_)
| AstKind::LogicalExpression(_)
| AstKind::BinaryExpression(_)
) {
return true;
}
if let AstKind::ConditionalExpression(e) = parent {
e.test.without_parentheses().span() == self.span
} else {
update_or_lower_expression_needs_parens(self.span, parent)
}
}
}

Expand All @@ -287,7 +327,7 @@ impl<'a> NeedsParentheses<'a> for YieldExpression<'a> {

impl<'a> NeedsParentheses<'a> for ImportExpression<'a> {
fn needs_parentheses(&self, stack: &ParentStack<'a>) -> bool {
false
matches!(stack.parent(), AstKind::NewExpression(_))
}
}

Expand Down Expand Up @@ -335,12 +375,18 @@ impl<'a> NeedsParentheses<'a> for TSTypeAssertion<'a> {

impl<'a> NeedsParentheses<'a> for TSNonNullExpression<'a> {
fn needs_parentheses(&self, stack: &ParentStack<'a>) -> bool {
false
let parent = stack.parent();
is_class_extends(parent, self.span)
|| (matches!(parent, AstKind::NewExpression(_))
&& member_chain_callee_needs_parens(&self.expression))
}
}

impl<'a> NeedsParentheses<'a> for TSInstantiationExpression<'a> {
fn needs_parentheses(&self, stack: &ParentStack<'a>) -> bool {
if let AstKind::MemberExpression(e) = stack.parent() {
return e.object().without_parentheses().span() == self.span;
}
false
}
}
Expand Down Expand Up @@ -382,6 +428,16 @@ fn binary_like_needs_parens<'a>(current: BinaryLike<'a, '_>, stack: &ParentStack
}
}

fn member_chain_callee_needs_parens(e: &Expression) -> bool {
std::iter::successors(Some(e), |e| match e {
Expression::ComputedMemberExpression(e) => Some(&e.object),
Expression::StaticMemberExpression(e) => Some(&e.object),
Expression::TSNonNullExpression(e) => Some(&e.expression),
_ => None,
})
.any(|object| matches!(object, Expression::CallExpression(_)))
}

#[derive(Clone, Copy)]
enum UnaryLike<'a, 'b> {
UpdateExpression(&'b UpdateExpression<'a>),
Expand Down Expand Up @@ -427,6 +483,22 @@ fn update_or_lower_expression_needs_parens(span: Span, parent: AstKind<'_>) -> b
false
}

#[derive(Debug, Clone, Copy)]
pub enum FirstInStatementMode {
/// Considers [JsExpressionStatement] and the body of [JsArrowFunctionExpression] as the first statement.
ExpressionStatementOrArrow,
/// Considers [JsExpressionStatement] and [JsExportDefaultExpressionClause] as the first statement.
ExpressionOrExportDefault,
}

/// Returns `true` if this node is at the start of an expression (depends on the passed `mode`).
///
/// Traverses upwards the tree for as long as the `node` is the left most expression until the node isn't
/// the left most node or reached a statement.
fn is_first_in_statement(stack: &ParentStack, mode: FirstInStatementMode) -> bool {
matches!(stack.parent(), AstKind::ExpressionStatement(_) | AstKind::ExportDefaultDeclaration(_))
}

fn await_or_yield_needs_parens(span: Span, parent: AstKind<'_>) -> bool {
if matches!(
parent,
Expand All @@ -440,7 +512,7 @@ fn await_or_yield_needs_parens(span: Span, parent: AstKind<'_>) -> bool {
return true;
}
if let AstKind::ConditionalExpression(e) = parent {
e.test.span() == span
e.test.without_parentheses().span() == span
} else {
update_or_lower_expression_needs_parens(span, parent)
}
Expand All @@ -449,3 +521,10 @@ fn await_or_yield_needs_parens(span: Span, parent: AstKind<'_>) -> bool {
fn ts_as_or_satisfies_needs_parens(stack: &ParentStack<'_>) -> bool {
matches!(stack.parent(), AstKind::SimpleAssignmentTarget(_))
}

fn is_class_extends(parent: AstKind, span: Span) -> bool {
if let AstKind::Class(c) = parent {
return c.super_class.as_ref().is_some_and(|c| c.without_parentheses().span() == span);
}
false
}
96 changes: 79 additions & 17 deletions crates/oxc_formatter/src/write/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ use crate::{
separated::FormatSeparatedIter,
token::number::{NumberFormatOptions, format_number_token},
trivia::FormatLeadingComments,
write,
},
options::{FormatTrailingCommas, QuoteProperties, TrailingSeparator},
parentheses::NeedsParentheses,
Expand Down Expand Up @@ -1308,7 +1309,38 @@ impl<'a> FormatWrite<'a> for BindingRestElement<'a> {

impl<'a> FormatWrite<'a> for FormalParameters<'a> {
fn write(&self, f: &mut Formatter<'_, 'a>) -> FormatResult<()> {
write!(f, ["(", ParameterList::with_layout(self, ParameterLayout::Default), ")"])
let parentheses_not_needed = true; // self
// .as_arrow_function_expression()
// .is_some_and(|expression| can_avoid_parentheses(&expression, f));
let has_any_decorated_parameter = false; // list.has_any_decorated_parameter();
let can_hug = false;
// should_hug_function_parameters(self, f.context().comments(), parentheses_not_needed)?
// && !has_any_decorated_parameter;
let layout = if !self.has_parameter() {
ParameterLayout::NoParameters
} else if can_hug
/* || self.is_in_test_call()? */
{
ParameterLayout::Hug
} else {
ParameterLayout::Default
};

write!(f, "(")?;

match layout {
ParameterLayout::NoParameters => {
write!(f, format_dangling_comments(self.span).with_soft_block_indent())?;
}
ParameterLayout::Hug => {
write!(f, ParameterList::with_layout(self, layout))?;
}
ParameterLayout::Default => {
write!(f, soft_block_indent(&ParameterList::with_layout(self, layout)))?;
}
}

write!(f, ")")
}
}

Expand Down Expand Up @@ -2528,24 +2560,22 @@ impl<'a> FormatWrite<'a> for TSTypeParameter<'a> {

impl<'a> FormatWrite<'a> for TSTypeParameterDeclaration<'a> {
fn write(&self, f: &mut Formatter<'_, 'a>) -> FormatResult<()> {
Ok(())
write!(f, ["<", self.params, ">"])
}
}

impl<'a> FormatWrite<'a> for TSTypeAliasDeclaration<'a> {
fn write(&self, f: &mut Formatter<'_, 'a>) -> FormatResult<()> {
let assignment_like = format_with(|f| {
write!(f, [self.id, self.type_parameters, space(), "=", space(), self.type_annotation])
});
write!(
f,
[
self.declare.then_some("declare "),
"type",
space(),
self.id,
self.type_parameters,
space(),
"=",
space(),
self.type_annotation,
group(&assignment_like),
OptionalSemicolon
]
)
Expand Down Expand Up @@ -2653,12 +2683,45 @@ impl<'a> FormatWrite<'a> for TSInterfaceDeclaration<'a> {

impl<'a> FormatWrite<'a> for TSInterfaceBody<'a> {
fn write(&self, f: &mut Formatter<'_, 'a>) -> FormatResult<()> {
Ok(())
// let last_index = self.body.len().saturating_sub(1);
let source_text = f.context().source_text();
let mut joiner = f.join_nodes_with_soft_line();
for (index, sig) in self.body.iter().enumerate() {
joiner.entry(sig.span(), source_text, sig);
}
joiner.finish()
}
}

impl<'a> FormatWrite<'a> for TSPropertySignature<'a> {
fn write(&self, f: &mut Formatter<'_, 'a>) -> FormatResult<()> {
if self.readonly {
write!(f, "readonly")?;
}
if self.computed {
write!(f, [space(), "[", self.key, "]"])?;
} else {
match &self.key {
PropertyKey::StaticIdentifier(key) => {
write!(f, self.key)?;
}
PropertyKey::PrivateIdentifier(key) => {
write!(f, self.key)?;
}
PropertyKey::StringLiteral(key) => {
write!(f, self.key)?;
}
key => {
write!(f, key)?;
}
}
}
if self.optional {
write!(f, "?")?;
}
if let Some(type_annotation) = &self.type_annotation {
write!(f, [":", space(), type_annotation])?;
}
Ok(())
}
}
Expand Down Expand Up @@ -2924,16 +2987,15 @@ impl<'a> FormatWrite<'a> for TSMappedType<'a> {
if let Some(name_type) = &name_type {
write!(f, [space(), "as", space(), name_type])?;
}
write!(f, "]")
write!(f, "]")?;
match self.optional {
Some(TSMappedTypeModifierOperator::True) => write!(f, "?"),
Some(TSMappedTypeModifierOperator::Plus) => write!(f, "+?"),
Some(TSMappedTypeModifierOperator::Minus) => write!(f, "-?"),
None => Ok(()),
}
});

match self.optional {
Some(TSMappedTypeModifierOperator::True) => write!(f, "?")?,
Some(TSMappedTypeModifierOperator::Plus) => write!(f, "+?")?,
Some(TSMappedTypeModifierOperator::Minus) => write!(f, "-?")?,
None => {}
}

write!(f, [space(), group(&format_inner_inner)])?;
if let Some(type_annotation) = &self.type_annotation {
write!(f, [":", space(), type_annotation])?;
Expand Down
Loading
Loading
0