feat(prettier): print getter/setter function in PropertyKey (#1411)

This commit is contained in:
Dunqing 2023-11-18 21:59:22 +08:00 committed by GitHub
parent 98279fc6ff
commit f6ecd96e69
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 47 additions and 10 deletions

View file

@ -3,7 +3,11 @@ use oxc_ast::ast::*;
use crate::{doc::Doc, group, if_break, indent, softline, ss, Format, Prettier};
pub(super) fn print_function<'a>(p: &mut Prettier<'a>, func: &Function<'a>) -> Doc<'a> {
pub(super) fn print_function<'a>(
p: &mut Prettier<'a>,
func: &Function<'a>,
property_name: Option<&str>,
) -> Doc<'a> {
let mut parts = p.vec();
if let Some(comments) = p.print_leading_comments(func.span) {
parts.push(comments);
@ -11,11 +15,18 @@ pub(super) fn print_function<'a>(p: &mut Prettier<'a>, func: &Function<'a>) -> D
if func.r#async {
parts.push(ss!("async "));
}
if func.generator {
parts.push(ss!("function* "));
if let Some(name) = property_name {
parts.push(p.str(name));
} else {
parts.push(ss!("function "));
parts.push(ss!("function"));
if func.generator {
parts.push(ss!("*"));
}
parts.push(p.str(" "));
}
if let Some(type_params) = &func.type_parameters {
parts.push(type_params.format(p));
}

View file

@ -859,7 +859,7 @@ impl<'a> Format<'a> for VariableDeclarator<'a> {
impl<'a> Format<'a> for Function<'a> {
fn format(&self, p: &mut Prettier<'a>) -> Doc<'a> {
function::print_function(p, self)
function::print_function(p, self, None)
}
}
@ -1318,7 +1318,34 @@ impl<'a> Format<'a> for ObjectProperty<'a> {
if self.shorthand {
self.key.format(p)
} else {
group!(p, format!(p, self.key), ss!(": "), format!(p, self.value))
let mut parts = p.vec();
let mut method = self.method;
match self.kind {
PropertyKind::Get => {
parts.push(ss!("get "));
method = true;
}
PropertyKind::Set => {
parts.push(ss!("set "));
method = true;
}
PropertyKind::Init => (),
}
if method {
if let Expression::FunctionExpression(func_expr) = &self.value {
parts.push(function::print_function(
p,
func_expr,
Some(self.key.span().source_text(p.source_text)),
));
}
} else {
parts.push(format!(p, self.key));
parts.push(ss!(": "));
parts.push(format!(p, self.value));
}
Doc::Group(parts)
}
}
}

View file

@ -34,8 +34,9 @@ pub(super) fn print_object_properties<'a, F: Format<'a>>(
} else {
parts.push(Doc::Softline);
}
parts.push(ss!("}"));
Doc::Array(parts)
Doc::Group(parts)
};
content

View file

@ -1,4 +1,4 @@
Compatibility: 101/838 (12.05%)
Compatibility: 103/838 (12.29%)
# Failed
@ -756,12 +756,10 @@ Compatibility: 101/838 (12.05%)
* object-property-ignore/issue-5678.js
### objects
* objects/bigint-key.js
* objects/escape-sequence-key.js
* objects/expand.js
* objects/expression.js
* objects/getter-setter.js
* objects/method.js
* objects/range.js
* objects/right-break.js