feat(prettier): basic print of TemplateLiteral (#1426)

This commit is contained in:
Wenzhe Wang 2023-11-19 13:51:47 +08:00 committed by GitHub
parent 902d4d0bab
commit c1450d8e90
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 65 additions and 2 deletions

View file

@ -18,6 +18,7 @@ mod module;
mod object;
mod statement;
mod string;
mod template_literal;
mod ternary;
use std::borrow::Cow;
@ -35,6 +36,7 @@ use crate::{
use self::{
array::Array,
binaryish::{BinaryishLeft, BinaryishOperator},
template_literal::TemplateLiteralPrinter,
};
pub trait Format<'a> {
@ -755,7 +757,10 @@ impl<'a> Format<'a> for TSQualifiedName<'a> {
impl<'a> Format<'a> for TSTemplateLiteralType<'a> {
fn format(&self, p: &mut Prettier<'a>) -> Doc<'a> {
Doc::Line
template_literal::print_template_literal(
p,
&TemplateLiteralPrinter::TSTemplateLiteralType(self),
)
}
}
@ -1618,7 +1623,14 @@ impl<'a> Format<'a> for ImportExpression<'a> {
impl<'a> Format<'a> for TemplateLiteral<'a> {
fn format(&self, p: &mut Prettier<'a>) -> Doc<'a> {
Doc::Line
template_literal::print_template_literal(p, &TemplateLiteralPrinter::TemplateLiteral(self))
}
}
impl<'a> Format<'a> for TemplateElement {
fn format(&self, p: &mut Prettier<'a>) -> Doc<'a> {
// TODO: `replaceEndOfLine`
p.str(self.value.raw.as_str())
}
}

View file

@ -0,0 +1,51 @@
use oxc_ast::ast::{TemplateLiteral, *};
use crate::{doc::Doc, format::Format, ss, Prettier};
#[allow(clippy::enum_variant_names)]
pub enum TemplateLiteralPrinter<'a, 'b> {
TemplateLiteral(&'b TemplateLiteral<'a>),
TSTemplateLiteralType(&'b TSTemplateLiteralType<'a>),
}
impl<'a, 'b> TemplateLiteralPrinter<'a, 'b> {
fn quasis(&self) -> &[TemplateElement] {
match self {
Self::TemplateLiteral(template_literal) => &template_literal.quasis,
Self::TSTemplateLiteralType(template_literal) => &template_literal.quasis,
}
}
fn get_nth_expr_doc(&self, p: &mut Prettier<'a>, index: usize) -> Option<Doc<'a>> {
match self {
Self::TemplateLiteral(template_literal) => {
template_literal.expressions.get(index).map(|expression| expression.format(p))
}
Self::TSTemplateLiteralType(template_literal) => {
template_literal.types.get(index).map(|type_| type_.format(p))
}
}
}
}
pub(super) fn print_template_literal<'a>(
p: &mut Prettier<'a>,
template_literal: &TemplateLiteralPrinter<'a, '_>,
) -> Doc<'a> {
let mut parts = p.vec();
parts.push(ss!("`"));
for (index, quais) in template_literal.quasis().iter().enumerate() {
parts.push(quais.format(p));
let Some(expr_doc) = template_literal.get_nth_expr_doc(p, index) else {
break;
};
parts.push(ss!("${"));
parts.push(expr_doc);
parts.push(ss!("}"));
}
parts.push(ss!("`"));
Doc::Array(parts)
}