//! Prettier's `language-handlebars/printer-glimmer.js`. It writes the parts of the document in order.
//!
//! Where Prettier's output would parse differently from the template, this deviates, and a comment says what Prettier
//! does.
use super::Options;
use super::ast::{self, Call, Head, Kind, NOTHING, Node, NodeId, Range, Tree};
use super::lexer::id_len;
use super::tokenizer::is_void_tag;
use crate::doc::{Align, Branch, Docs, Mark};
use crate::embed::{Embed, Kind as Purpose, Request};
use crate::stack::Stack;
use crate::strings;
use std::borrow::Cow;
const HTML_WHITE_SPACE: &[u8] = b"\t\n\x0C\r ";
/// `string.toUpperCase() === string`, for the first UTF-16 code unit of a tag name.
fn starts_with_upper_case(tag: &[u8]) -> bool {
!tag.first().is_some_and(u8::is_ascii_lowercase)
}
/// Tells if the words have whitespace on each side.
#[derive(Copy, Clone, Default)]
struct SurroundingWhitespace {
before: bool,
after: bool,
}
/// A text's neighbors in a `ConcatStatement`.
#[derive(Copy, Clone, Default)]
struct Neighbors {
follows_mustache: bool,
precedes_mustache: bool,
}
/// A style sheet that is embedded in a template.
enum StyleSheet {
/// As the host formats it.
Text(String),
/// As `crate::css` formats it.
Document(crate::css::Document),
}
/// A text's parent.
#[derive(Copy, Clone, PartialEq, Eq)]
enum Parent {
Template,
Block,
Element,
Style,
}
/// The characters to escape when a text is printed.
#[derive(Copy, Clone)]
enum Escapes {
Nothing,
/// `{{`. A mustache in a text must have been escaped in the source.
Mustaches,
/// `{{` and the quote around the text.
MustachesAndQuote(u8),
}
pub(crate) struct Printer<'a, 'p> {
pub(crate) tree: &'a Tree,
/// `options.originalText`, with the front matter replaced with spaces.
pub(crate) source: &'a str,
pub(crate) front_matter: &'a str,
pub(crate) options: &'p Options,
/// `options.htmlWhitespaceSensitivity !== "ignore"`
pub(crate) is_white_space_sensitive: bool,
pub(crate) single_quote: bool,
/// The ignore directive.
pub(crate) ignore: &'p [u8],
pub(crate) docs: &'p mut Docs<'a>,
pub(crate) embed: &'p mut dyn Embed,
/// The open containers, and what each added to `indents`.
pub(crate) open: Vec<(Mark, isize)>,
/// How many indents are open, for the code of other languages.
pub(crate) indents: usize,
/// The number of enclosing elements in which all whitespace is significant.
pub(crate) pre_depth: usize,
pub(crate) stack: Stack,
}
impl<'a> Printer<'a, '_> {
fn text(&self, text: ast::Text) -> &'a [u8] {
self.tree.text(self.source.as_bytes(), text)
}
/// Emits `bytes`, borrowed if they are a part of the source.
fn put(&mut self, bytes: &[u8]) {
let start = (bytes.as_ptr() as usize).wrapping_sub(self.source.as_ptr() as usize);
match self.source.get(start..start + bytes.len()) {
Some(text) => self.docs.text(text),
None => self.docs.owned(&String::from_utf8_lossy(bytes)),
}
}
fn close(&mut self) {
if let Some((mark, added)) = self.open.pop() {
self.indents = self.indents.saturating_add_signed(-added);
self.docs.close(mark);
}
}
fn open_fill(&mut self) {
let mark = self.docs.fill();
self.open.push((mark, 0));
}
fn open_part(&mut self) {
let mark = self.docs.part();
self.open.push((mark, 0));
}
fn open_if_break(&mut self, branch: Branch) {
let mark = self.docs.if_break(branch, None);
self.open.push((mark, 0));
}
/// Ends the contents of `ifBreak` for a broken group and starts those for a flat one.
fn otherwise(&mut self) {
self.close();
self.open_if_break(Branch::Flat);
}
fn open_dedent(&mut self) {
let mark = self.docs.align(Align::Dedent);
let added = -isize::from(self.indents > 0);
self.indents = self.indents.saturating_add_signed(added);
self.open.push((mark, added));
}
fn open_root(&mut self) {
let mark = self.docs.align(Align::Mark);
self.open.push((mark, 0));
}
fn list(&self, range: Range) -> &'a [NodeId] {
self.tree.list(range)
}
#[inline]
fn token(&mut self, text: &'static str) {
self.docs.text(text);
}
fn start_group(&mut self) {
let mark = self.docs.group();
self.open.push((mark, 0));
}
fn start_indent(&mut self) {
let mark = self.docs.indent();
self.indents += 1;
self.open.push((mark, 1));
}
/// `generateHardlines`
fn hard_lines(&mut self, count: usize) {
for _ in 0..count.min(2) {
self.docs.hardline();
}
}
/// Prints a `line`, or as many `hardline`s as `white_space` has line breaks, at most two. With `is_dedented`, each
/// is wrapped in a `dedent`.
fn breaks(&mut self, white_space: &[u8], is_dedented: bool) {
let new_lines = strings::count_char(white_space, b'\n');
for _ in 0..new_lines.clamp(1, 2) {
if is_dedented {
self.open_dedent();
}
match new_lines {
0 => self.docs.line(),
_ => self.docs.hardline(),
}
if is_dedented {
self.close();
}
}
}
/// Prints a text that can contain line breaks.
fn verbatim(&mut self, text: &[u8]) {
self.put(text);
}
/// `replaceEndOfLine(text)`
fn with_literal_lines(&mut self, text: &[u8], escapes: Escapes) {
for (index, line) in strings::split(text, b"\n").enumerate() {
if index > 0 {
self.docs.literalline_without_break_parent();
self.docs.break_parent();
}
self.with_escapes(line, escapes);
}
}
fn with_escapes(&mut self, mut text: &[u8], escapes: Escapes) {
match escapes {
Escapes::Nothing => self.put(text),
Escapes::Mustaches => self.escaped(text),
// Prettier prints the quote unescaped.
Escapes::MustachesAndQuote(quote) => {
while let Some(at) = strings::index_of_char_usize(text, quote) {
self.escaped(&text[..at]);
self.token(if quote == b'"' { """ } else { "'" });
text = &text[at + 1..];
}
self.escaped(text);
}
}
}
/// `text.replaceAll("{{", "\\{{")`: a mustache in a text must have been escaped in the source.
fn escaped(&mut self, mut text: &[u8]) {
while let Some(at) = strings::index_of(text, b"{{") {
self.put(&text[..at]);
self.token("\\{{");
text = &text[at + 2..];
}
self.put(text);
}
/// `fill(getTextValueParts(text))`, where `text` is `words` plus the whitespace that `surrounding` describes.
fn fill(&mut self, words: &[u8], surrounding: SurroundingWhitespace) {
self.open_fill();
if surrounding.before {
self.empty_part();
self.separator();
}
let mut rest = words;
loop {
let len = strings::index_of_any(rest, HTML_WHITE_SPACE).unwrap_or(rest.len());
self.open_part();
self.escaped(&rest[..len]);
self.close();
rest = &rest[len..];
if rest.is_empty() {
break;
}
self.separator();
rest = rest.trim_ascii_start();
}
if surrounding.after {
self.separator();
self.empty_part();
}
self.close();
}
fn separator(&mut self) {
self.open_part();
self.docs.line();
self.close();
}
fn empty_part(&mut self) {
self.open_part();
self.close();
}
// ───────────────────────────── utilities.js ─────────────────────────────
/// `isWhitespaceNode`. Prettier uses JavaScript's definition of whitespace, which includes a no-break space. HTML's
/// doesn't.
fn is_white_space_node(&self, node: NodeId) -> bool {
matches!(self.tree.kind(node), Kind::Text { chars } if self.text(chars).trim_ascii_start().is_empty())
}
fn are_white_space(&self, nodes: &[NodeId]) -> bool {
nodes.iter().all(|node| self.is_white_space_node(*node))
}
/// `isVoidElement`. Prettier treats `
` as `
`, even if it has children.
fn is_void_element(&self, tag: &[u8], children: &[NodeId], is_self_closing: bool) -> bool {
let is_void_tag = || is_void_tag(&tag.to_ascii_lowercase()) && !starts_with_upper_case(tag);
let is_glimmer_component = || {
!tag.starts_with(b":") && (starts_with_upper_case(tag) || strings::contains_char(tag, b'.'))
};
is_self_closing || ((is_void_tag() || is_glimmer_component()) && self.are_white_space(children))
}
/// `isPrettierIgnoreNode`
fn is_prettier_ignore(&self, node: NodeId) -> bool {
matches!(self.tree.kind(node), Kind::MustacheComment { value } if strings::trim_js_whitespace(self.text(value)) == self.ignore)
}
/// Prints the node's source text.
fn ignored(&mut self, node: Node) {
self.verbatim(
self.source.as_bytes().get(node.start as usize..node.end as usize).unwrap_or_default(),
);
}
// ───────────────────────────── statements ─────────────────────────────
pub(crate) fn template(&mut self, template: NodeId) {
if let Kind::Template { body } = self.tree.kind(template) {
self.start_group();
self.children(self.list(body), Parent::Template, None);
self.close();
}
}
/// `path.map(print, "body")` or `"children"`. `outer` is set if `nodes` is the `{{else}}` part of that block.
fn children(&mut self, nodes: &'a [NodeId], parent: Parent, outer: Option<(Call, u8)>) {
if !self.stack.has_room() {
return;
}
for (index, &id) in nodes.iter().enumerate() {
let node = self.tree.node(id);
let is_verbatim = node.is_verbatim
|| self.is_prettier_ignore(id)
|| (index >= 2 && self.is_prettier_ignore(nodes[index - 2]));
if let Kind::Text { chars } = node.kind {
let mut chars = Cow::Borrowed(self.text(chars));
// Add a backslash, or the last one would escape the `{{` that's printed next. Before a mustache the
// tree already has the extra one (Prettier's `addBackslash`).
if chars.ends_with(b"\\")
&& match nodes.get(index + 1).map(|next| self.tree.kind(*next)) {
Some(Kind::MustacheComment { .. }) => true,
// When whitespace is insignificant, the block goes on the next line anyway.
Some(Kind::BlockStatement { .. }) => {
self.is_white_space_sensitive || self.pre_depth > 0 || is_verbatim
}
Some(_) => false,
None => parent == Parent::Block && self.is_white_space_sensitive,
}
{
chars.to_mut().push(b'\\');
}
match is_verbatim {
true => self.escaped(&chars),
false => self.text_node(&chars, nodes, index, parent),
}
continue;
}
if is_verbatim {
self.ignored(node);
continue;
}
match node.kind {
Kind::Element { .. } => {
let follows_element =
index > 0 && matches!(self.tree.kind(nodes[index - 1]), Kind::Element { .. });
self.element(node, follows_element);
}
Kind::BlockStatement { .. } => {
let outer = outer.filter(|outer| nodes.len() == 1 && self.is_else_if(id, *outer));
self.block_statement(node, outer.map(|outer| outer.1));
}
Kind::Mustache { .. } => self.mustache_node(node, false),
Kind::Value { code, is_trusting } => self.value(code, is_trusting, false),
Kind::Directive { name, args } => self.directive(self.text(name), self.text(args)),
Kind::Section { .. } => self.section(node),
Kind::Opaque => self.ignored(node),
Kind::MustacheComment { value } => self.mustache_comment(node, self.text(value)),
Kind::Comment { value } => {
self.token("");
}
Kind::Doctype => self.ignored(node),
Kind::FrontMatter => self.print_front_matter(self.front_matter),
_ => {}
}
}
}
fn mustache_comment(&mut self, node: Node, value: &[u8]) {
// Tempura's comments, `{{! note }}` and `{{! note !}}`, have no dashes to add or drop.
if self.options.is_tempura {
return self.ignored(node);
}
let is_tilde =
|at: Option| at.and_then(|at| self.source.as_bytes().get(at)) == Some(&b'~');
let strips_left = is_tilde(Some(node.start as usize + 2));
let strips_right = is_tilde((node.end as usize).checked_sub(3));
// Prettier only checks the first condition. Without dashes, the second would parse as a comment that ends at
// `--}}`, and the third as one that strips the following whitespace.
let needs_dashes = strings::contains(value, b"}}")
|| value.starts_with(b"--")
|| (value.ends_with(b"~") && !strips_right);
let dashes = if needs_dashes { "--" } else { "" };
self.token(if strips_left { "{{~!" } else { "{{!" });
self.token(dashes);
self.verbatim(value);
self.token(dashes);
self.token(if strips_right { "~}}" } else { "}}" });
}
/// Prettier's `printEmbedFrontMatter`, or `printFrontMatter` where that doesn't apply.
fn print_front_matter(&mut self, raw: &'a str) {
let Some(matter) = crate::front_matter::parse(raw).filter(|it| it.language == "yaml") else {
return self.verbatim(raw.as_bytes());
};
let value = matter.value.trim();
let mut formatted = String::new();
if !value.is_empty() {
let request = Request {
code: value,
language: "yaml",
kind: Purpose::FrontMatter,
indent: 0,
width: self.options.width,
module: true,
};
match self.embed.format(request) {
Some(text) => formatted = text.trim_end_matches(['\n', '\r']).to_owned(),
None => return self.verbatim(raw.as_bytes()),
}
}
self.open_root();
self.put(matter.start.as_bytes());
self.put(matter.explicit.unwrap_or_default().as_bytes());
self.docs.hardline();
if !formatted.is_empty() {
self.with_literal_lines(formatted.as_bytes(), Escapes::Nothing);
self.docs.hardline();
}
self.put(matter.end.as_bytes());
self.close();
}
// ───────────────────────────── elements ─────────────────────────────
/// `embed`: formats the style sheet of a `