feat(prettier): implement format function for ObjectExpression (#1344)

This commit is contained in:
Dunqing 2023-11-16 16:01:36 +08:00 committed by GitHub
parent 638bd1ce23
commit 95268c9e0d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 48 additions and 19 deletions

View file

@ -12,6 +12,7 @@ use oxc_ast::ast::*;
mod binaryish;
mod block;
mod call_expression;
mod object;
mod statement;
mod ternary;
@ -800,19 +801,22 @@ impl<'a> Format<'a> for ArrayExpression<'a> {
impl<'a> Format<'a> for ObjectExpression<'a> {
fn format(&self, p: &mut Prettier<'a>) -> Doc<'a> {
Doc::Line
p.print_object_properties(&self.properties)
}
}
impl<'a> Format<'a> for ObjectPropertyKind<'a> {
fn format(&self, p: &mut Prettier<'a>) -> Doc<'a> {
Doc::Line
match self {
ObjectPropertyKind::ObjectProperty(prop) => prop.format(p),
ObjectPropertyKind::SpreadProperty(prop) => prop.format(p),
}
}
}
impl<'a> Format<'a> for ObjectProperty<'a> {
fn format(&self, p: &mut Prettier<'a>) -> Doc<'a> {
Doc::Line
array!(p, format!(p, self.key), ss!(": "), format!(p, self.value))
}
}
@ -1277,20 +1281,7 @@ impl<'a> Format<'a> for BindingPattern<'a> {
impl<'a> Format<'a> for ObjectPattern<'a> {
fn format(&self, p: &mut Prettier<'a>) -> Doc<'a> {
let mut parts = p.vec();
parts.push(ss!("{"));
parts.push(Doc::Line);
let len = self.properties.len();
self.properties.iter().map(|prop| prop.format(p)).enumerate().for_each(|(i, prop)| {
parts.push(prop);
if i < len - 1 {
parts.push(Doc::Str(","));
parts.push(Doc::Line);
}
});
parts.push(Doc::Line);
parts.push(ss!("}"));
Doc::Group(parts)
p.print_object_properties(&self.properties)
}
}

View file

@ -0,0 +1,39 @@
use oxc_allocator::Vec;
use crate::{doc::Doc, ss, Prettier};
use super::Format;
impl<'a> Prettier<'a> {
pub(super) fn print_object_properties<F: Format<'a>>(
&mut self,
properties: &Vec<'a, F>,
) -> Doc<'a> {
let mut parts = self.vec();
parts.push(ss!("{"));
if self.options.bracket_spacing {
parts.push(Doc::Line);
} else {
parts.push(Doc::Softline);
};
let len = properties.len();
properties.iter().map(|prop| prop.format(self)).enumerate().for_each(|(i, prop)| {
parts.push(prop);
if i < len - 1 {
parts.push(Doc::Str(","));
parts.push(Doc::Line);
}
});
if self.options.bracket_spacing {
parts.push(Doc::Line);
} else {
parts.push(Doc::Softline);
}
parts.push(ss!("}"));
Doc::Group(parts)
}
}

View file

@ -1,4 +1,4 @@
Compatibility: 7/173 (4.05%)
Compatibility: 8/173 (4.62%)
# Failed
@ -18,7 +18,6 @@ Compatibility: 7/173 (4.05%)
* binary_math
* bind-expressions
* bom
* bracket-spacing
* break-calls
* call/first-argument-expansion
* call/invalid