feat(prettier): add print_return_or_throw_argument (#1347)

This commit is contained in:
Boshen 2023-11-16 17:16:30 +08:00 committed by GitHub
parent 66aae99c63
commit aee733d250
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 28 additions and 22 deletions

View file

@ -1,7 +1,7 @@
#[allow(clippy::wildcard_imports)]
use oxc_ast::ast::*;
use crate::{doc::Doc, ss, Format, Prettier};
use crate::{doc::Doc, group, hardline, if_break, indent, softline, ss, Format, Prettier};
impl<'a> Prettier<'a> {
pub(super) fn print_function(&mut self, func: &Function<'a>) -> Doc<'a> {
@ -30,4 +30,29 @@ impl<'a> Prettier<'a> {
}
Doc::Array(parts)
}
pub(super) fn print_return_or_throw_argument(
&mut self,
argument: Option<&Expression<'a>>,
is_return: bool,
) -> Doc<'a> {
let mut parts = self.vec();
parts.push(ss!(if is_return { "return" } else { "throw" }));
if let Some(argument) = argument {
parts.push(ss!(" "));
parts.push(group![
self,
if_break!(self, "("),
indent!(self, softline!(), argument.format(self)),
softline!(),
if_break!(self, ")")
]);
}
parts.push(self.str(";"));
parts.push(hardline!());
Doc::Array(parts)
}
}

View file

@ -254,21 +254,7 @@ impl<'a> Format<'a> for SwitchCase<'a> {
impl<'a> Format<'a> for ReturnStatement<'a> {
fn format(&self, p: &mut Prettier<'a>) -> Doc<'a> {
let mut parts = p.vec();
parts.push(ss!("return"));
if let Some(argument) = &self.argument {
parts.push(ss!(" "));
parts.push(group![
p,
if_break!(p, "("),
indent!(p, softline!(), format!(p, argument)),
softline!(),
if_break!(p, ")")
]);
}
parts.push(p.str(";"));
parts.push(hardline!());
Doc::Array(parts)
p.print_return_or_throw_argument(self.argument.as_ref(), true)
}
}
@ -317,12 +303,7 @@ impl<'a> Format<'a> for CatchClause<'a> {
impl<'a> Format<'a> for ThrowStatement<'a> {
fn format(&self, p: &mut Prettier<'a>) -> Doc<'a> {
let mut parts = p.vec();
parts.push(ss!("throw "));
parts.push(ss!(" "));
parts.push(format!(p, self.argument));
Doc::Array(parts)
p.print_return_or_throw_argument(Some(&self.argument), false)
}
}