dmc-codegen 0.2.3

HTML and MDX body emitters for the dmc compiler
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
use crate::{
  NodeSink, WalkCtx, Walker,
  escape::{escape_attr, escape_text, escape_url},
};
use dmc_diagnostic::Code;
use dmc_parser::ast::*;
use duck_diagnostic::{DiagnosticEngine, diag};

#[derive(Debug, Clone, Copy, Default)]
pub struct RenderOptions {
  /// GFM disallowed raw HTML extension. When enabled, a fixed tag-name
  /// set gets its leading `<` escaped in raw HTML output.
  pub gfm_disallowed_raw_html: bool,
}

/// Emits static HTML by reacting to walker enter/leave events. Container
/// nodes split into `open_tag` / `close_tag` halves; leaves write their
/// markup once on enter. Tables are rendered up-front in `enter Table`
/// (rows + cells aren't `Node` variants the walker can surface) and
/// `in_table_depth` suppresses subsequent walker events on cell content.
///
/// Owns its own `DiagnosticEngine` during the walk; merge into the
/// caller's engine via `into_parts` after the walk completes.
pub struct HtmlEmitter {
  out: String,
  diag_engine: DiagnosticEngine<Code>,
  in_table_depth: usize,
  options: RenderOptions,
}

impl NodeSink for HtmlEmitter {
  fn enter(&mut self, node: &Node, ctx: &WalkCtx) {
    if self.in_table_depth > 0 {
      return;
    }
    self.maybe_separate_list_item_block_child(node, ctx);
    match node {
      Node::Text(t) => self.out.push_str(&escape_text(&t.value)),
      Node::InlineCode(c) => {
        self.out.push_str("<code>");
        self.out.push_str(&escape_text(&c.value));
        self.out.push_str("</code>");
      },
      Node::CodeBlock(cb) => self.code_block(cb),
      Node::Image(i) => self.image(i),
      Node::HorizontalRule(_) => self.out.push_str("<hr />\n"),
      Node::HardBreak(_) => self.out.push_str("<br />\n"),
      // Raw HTML: at block level we add a trailing `\n` to match the
      // CM reference layout (each block sits on its own line). Inside
      // a paragraph the same Html node represents an inline raw HTML
      // span and must NOT inject a newline before `</p>`.
      Node::Html(h) => {
        let value =
          if self.options.gfm_disallowed_raw_html { escape_disallowed_raw_html_tag(&h.value) } else { h.value.clone() };
        self.out.push_str(&value);
        let inline_context = matches!(ctx.parent, Some(Node::Paragraph(_)) | Some(Node::Heading(_)));
        if !inline_context && !value.ends_with('\n') {
          self.out.push('\n');
        }
      },
      Node::SoftBreak(_) => self.out.push('\n'),
      Node::JsxSelfClosing(s) => self.jsx_self_closing(s),
      Node::JsxExpression(e) => {
        // Trivial string-literal expressions (`{' '}`, `{"x"}`, `` {`y`} ``)
        // are idiomatic MDX for inline whitespace / inserted text. They
        // need no JS runtime, so render them as escaped text instead of
        // dropping + warning. Only genuinely dynamic expressions
        // (`{count}`, `{foo()}`) hit the GW002 path.
        if let Some(text) = string_literal_expression(&e.value) {
          self.out.push_str(&escape_text(&text));
        } else {
          self.diag(Code::HtmlExpressionDropped, format!("html: raw `{{...}}` expression dropped: {}", e.value.trim()));
        }
      },
      Node::Table(t) => {
        self.in_table_depth += 1;
        self.inline_table(t);
      },
      Node::Frontmatter(_) | Node::Import(_) | Node::Export(_) => {},
      _ => self.open_tag(node),
    }
  }

  fn leave(&mut self, node: &Node, _ctx: &WalkCtx) {
    if let Node::Table(_) = node {
      self.in_table_depth = self.in_table_depth.saturating_sub(1);
      return;
    }
    if self.in_table_depth > 0 {
      return;
    }
    self.close_tag(node);
  }
}

impl Default for HtmlEmitter {
  fn default() -> Self {
    Self::new()
  }
}

impl HtmlEmitter {
  pub fn new() -> Self {
    Self::new_with_options(RenderOptions::default())
  }

  pub fn new_with_options(options: RenderOptions) -> Self {
    Self { out: String::new(), diag_engine: DiagnosticEngine::new(), in_table_depth: 0, options }
  }

  pub fn into_string(self) -> String {
    self.out
  }

  /// Take both buffers: the rendered HTML and the per-emitter diagnostic
  /// engine. Caller merges the diags into a shared engine via
  /// `outer.extend(diag)`.
  pub fn into_parts(self) -> (String, DiagnosticEngine<Code>) {
    (self.out, self.diag_engine)
  }

  /// Drive the walker; return `(html, diag)`. Use when no other sink
  /// shares the walk.
  pub fn render(doc: &Document) -> (String, DiagnosticEngine<Code>) {
    let mut e = Self::new();
    Walker::new(doc).walk(&mut [&mut e]);
    e.into_parts()
  }

  pub fn render_with(doc: &Document, options: RenderOptions) -> (String, DiagnosticEngine<Code>) {
    let mut e = Self::new_with_options(options);
    Walker::new(doc).walk(&mut [&mut e]);
    e.into_parts()
  }

  fn diag(&mut self, code: Code, message: impl Into<String>) {
    self.diag_engine.emit(diag!(code, message.into()));
  }

  fn is_block_node(node: &Node) -> bool {
    matches!(
      node,
      Node::Paragraph(_)
        | Node::List(_)
        | Node::Blockquote(_)
        | Node::CodeBlock(_)
        | Node::Heading(_)
        | Node::HorizontalRule(_)
        | Node::Table(_)
        | Node::Html(_)
    )
  }

  fn maybe_separate_list_item_block_child(&mut self, node: &Node, ctx: &WalkCtx) {
    let Some(parent) = ctx.parent else {
      return;
    };
    if !matches!(parent, Node::ListItem(_) | Node::TaskListItem(_)) || ctx.index == 0 || !Self::is_block_node(node) {
      return;
    }
    let prev = Node::children_of(parent).get(ctx.index - 1);
    if prev.is_some_and(|n| !Self::is_block_node(n)) && !self.out.ends_with('\n') {
      self.out.push('\n');
    }
  }

  // container open / close (walker fills the children in between)

  /// Write the opening tag for a container node.
  fn open_tag(&mut self, node: &Node) {
    match node {
      Node::Heading(h) => match &h.id {
        Some(id) => self.out.push_str(&format!("<h{} id=\"{}\">", h.level, escape_attr(id))),
        None => self.out.push_str(&format!("<h{}>", h.level)),
      },
      Node::Paragraph(_) => self.out.push_str("<p>"),
      Node::Bold(_) => self.out.push_str("<strong>"),
      Node::Italic(_) => self.out.push_str("<em>"),
      Node::Strikethrough(_) => self.out.push_str("<del>"),
      Node::Blockquote(_) => self.out.push_str("<blockquote>\n"),
      Node::List(l) => {
        let tag = if l.ordered { "ol" } else { "ul" };
        self.out.push('<');
        self.out.push_str(tag);
        // remark-gfm tags any list with a `TaskListItem` child as
        // `class="contains-task-list"` on the parent `<ul>` / `<ol>`.
        if l.children.iter().any(|c| matches!(c, Node::TaskListItem(_))) {
          self.out.push_str(" class=\"contains-task-list\"");
        }
        if l.ordered
          && let Some(s) = l.start
          && s != 1
        {
          self.out.push_str(&format!(" start=\"{}\"", s));
        }
        self.out.push_str(">\n");
      },
      // CM emits `<li>\n` when the item has block children (loose
      // list / contains a paragraph). Tight items hug the inline
      // content directly after `<li>`.
      Node::ListItem(li) => {
        let has_block_child = li.children.first().is_some_and(|c| {
          matches!(
            c,
            Node::Paragraph(_)
              | Node::List(_)
              | Node::Blockquote(_)
              | Node::CodeBlock(_)
              | Node::Heading(_)
              | Node::HorizontalRule(_)
              | Node::Table(_)
              | Node::Html(_)
          )
        });
        if has_block_child {
          self.out.push_str("<li>\n");
        } else {
          self.out.push_str("<li>");
        }
      },
      Node::TaskListItem(t) => {
        // HTML5 self-closes void elements implicitly - match remark-gfm's
        // emitted markup which writes `<input type="checkbox" ...>` (no `/>`)
        // and follows it with a literal space before the item content.
        let checked = if t.checked { " checked" } else { "" };
        self.out.push_str(&format!("<li class=\"task-list-item\"><input type=\"checkbox\"{} disabled> ", checked));
      },
      Node::Link(l) => {
        self.out.push_str(&format!("<a href=\"{}\"", escape_attr(&escape_url(&l.href))));
        // CM 6.3 / 4.7: link title becomes the `title` attribute on
        // the anchor. (The autolink-headings transformer's tooltip
        // currently borrows the same field; if it ever needs distinct
        // semantics, route through a separate AST field.)
        if let Some(title) = &l.title {
          self.out.push_str(&format!(" title=\"{}\"", escape_attr(title)));
        }
        self.out.push('>');
      },
      Node::JsxElement(e) => {
        if e.name.is_empty() {
          self.diag(Code::MalformedJsxTagName, "html: JSX element has empty name; skipped".to_string());
          return;
        }
        // GFM Disallowed Raw HTML extension: a fixed set of tag names
        // get their leading `<` escaped (the tag wouldn't render
        // safely in a browser). Affects open + close tags.
        if self.options.gfm_disallowed_raw_html && is_disallowed_raw_html(&e.name) {
          self.out.push_str("&lt;");
        } else {
          self.out.push('<');
        }
        self.out.push_str(&e.name);
        for a in &e.attrs {
          self.jsx_attr(a);
        }
        self.out.push('>');
      },
      Node::JsxFragment(_) => {},
      _ => {},
    }
  }

  /// Write the closing tag for a container node opened by `open_tag`.
  /// Block-level closes get a trailing `\n` so the output matches the
  /// CommonMark reference renderer's line-per-block layout.
  fn close_tag(&mut self, node: &Node) {
    match node {
      Node::Heading(h) => self.out.push_str(&format!("</h{}>\n", h.level)),
      Node::Paragraph(_) => self.out.push_str("</p>\n"),
      Node::Bold(_) => self.out.push_str("</strong>"),
      Node::Italic(_) => self.out.push_str("</em>"),
      Node::Strikethrough(_) => self.out.push_str("</del>"),
      Node::Blockquote(_) => self.out.push_str("</blockquote>\n"),
      Node::List(l) => {
        let tag = if l.ordered { "ol" } else { "ul" };
        self.out.push_str(&format!("</{}>\n", tag));
      },
      Node::ListItem(_) | Node::TaskListItem(_) => self.out.push_str("</li>\n"),
      Node::Link(_) => self.out.push_str("</a>"),
      Node::JsxElement(e) if !e.name.is_empty() => {
        if self.options.gfm_disallowed_raw_html && is_disallowed_raw_html(&e.name) {
          self.out.push_str(&format!("&lt;/{}>", e.name));
        } else {
          self.out.push_str(&format!("</{}>", e.name));
        }
      },
      Node::JsxFragment(_) => {},
      _ => {},
    }
  }

  // leaf-shaped emitters

  fn code_block(&mut self, cb: &CodeBlock) {
    self.out.push_str("<pre><code");
    if let Some(lang) = &cb.lang {
      // CM reference output uses the bare `language-{lang}` class.
      self.out.push_str(&format!(" class=\"language-{}\"", escape_attr(lang)));
    }
    self.out.push('>');
    self.out.push_str(&escape_text(&cb.value));
    self.out.push_str("</code></pre>\n");
  }

  fn image(&mut self, i: &Image) {
    self.out.push_str(&format!("<img src=\"{}\" alt=\"{}\"", escape_attr(&escape_url(&i.src)), escape_attr(&i.alt)));
    if let Some(title) = &i.title {
      self.out.push_str(&format!(" title=\"{}\"", escape_attr(title)));
    }
    // CM reference output uses the XHTML self-closing slash on `<img>`
    // (matches `<hr />` / `<br />` style). Browsers treat both forms
    // identically.
    self.out.push_str(" />");
  }

  fn jsx_self_closing(&mut self, s: &JsxSelfClosing) {
    if s.name.is_empty() {
      self.diag(Code::MalformedJsxTagName, "html: self-closing JSX has empty name; skipped".to_string());
      return;
    }
    match s.name.as_str() {
      "MermaidSvg" => {
        if let Some(attr) = s.attrs.iter().find(|a| a.name == "svg")
          && let JsxAttrValue::String(svg) = &attr.value
        {
          self.out.push_str(svg);
        }
      },
      "MathMl" => {
        if let Some(attr) = s.attrs.iter().find(|a| a.name == "mathml")
          && let JsxAttrValue::String(mathml) = &attr.value
        {
          // Reverse the JSX-attribute escape applied by Math::preprocess_source
          // (`"` -> `&quot;`, `&` -> `&amp;`) before emitting raw HTML.
          let unescaped = mathml.replace("&quot;", "\"").replace("&amp;", "&");
          self.out.push_str(&unescaped);
        }
      },
      "PackageManagerTabs" => {
        self.out.push_str("<div class=\"gentledmc-pm-tabs\">");
        for pm in ["npm", "yarn", "pnpm", "bun"] {
          if let Some(attr) = s.attrs.iter().find(|a| a.name == pm)
            && let JsxAttrValue::String(cmd) = &attr.value
          {
            self.out.push_str(&format!(
              "<pre><code class=\"gentledmc-language-bash\" data-pm=\"{}\">{}</code></pre>",
              pm,
              escape_text(cmd)
            ));
          }
        }
        self.out.push_str("</div>");
      },
      _ => {
        self.out.push('<');
        self.out.push_str(&s.name);
        for a in &s.attrs {
          self.jsx_attr(a);
        }
        self.out.push_str(" />");
      },
    }
  }

  fn jsx_attr(&mut self, a: &JsxAttr) {
    self.out.push(' ');
    self.out.push_str(&a.name);
    match &a.value {
      // Match the rehype/shiki HTML output: boolean JSX attrs serialize
      // as empty-string attributes (`data-rehype-pretty-code-figure=""`).
      // It is semantically identical for the browser and keeps consumer
      // selectors that key off `[attr=""]` working.
      JsxAttrValue::Boolean => self.out.push_str("=\"\""),
      JsxAttrValue::String(s) => self.out.push_str(&format!("=\"{}\"", escape_attr(s))),
      JsxAttrValue::Expression(e) => self.out.push_str(&format!("={{{}}}", e)),
      // Spread attributes have no HTML representation; drop them. The
      // leading space pushed before the (empty) name comes back when
      // we pop it.
      JsxAttrValue::Spread(_) => {
        self.out.pop();
      },
    }
  }

  // table inline path (walker can't surface row/cell events)

  /// Render the entire `<table>...</table>` up-front. Cell content uses
  /// `inline_node` recursion since the walker is suppressed inside.
  fn inline_table(&mut self, t: &Table) {
    self.out.push_str("<table>\n");
    if let Some(header) = t.children.first() {
      self.out.push_str("<thead>\n<tr>\n");
      for (i, cell) in header.cells.iter().enumerate() {
        self.inline_cell("th", cell, t.align.get(i).copied().unwrap_or(TableAlign::None));
      }
      self.out.push_str("</tr>\n</thead>\n");
    }
    if t.children.len() > 1 {
      self.out.push_str("<tbody>\n");
      for row in &t.children[1..] {
        self.out.push_str("<tr>\n");
        for (i, cell) in row.cells.iter().enumerate() {
          self.inline_cell("td", cell, t.align.get(i).copied().unwrap_or(TableAlign::None));
        }
        self.out.push_str("</tr>\n");
      }
      self.out.push_str("</tbody>\n");
    }
    self.out.push_str("</table>\n");
  }

  fn inline_cell(&mut self, tag: &str, cell: &TableCell, align: TableAlign) {
    self.out.push('<');
    self.out.push_str(tag);
    let align_str = match align {
      TableAlign::Left => Some("left"),
      TableAlign::Right => Some("right"),
      TableAlign::Center => Some("center"),
      TableAlign::None => None,
    };
    if let Some(a) = align_str {
      self.out.push_str(&format!(" align=\"{}\"", a));
    }
    self.out.push('>');
    for c in &cell.children {
      self.inline_node(c);
    }
    self.out.push_str("</");
    self.out.push_str(tag);
    self.out.push_str(">\n");
  }

  /// Self-recursive render used only inside the table inline path. The
  /// walker is suppressed via `in_table_depth`, so cell content doesn't
  /// get a second pass.
  fn inline_node(&mut self, node: &Node) {
    match node {
      Node::Text(t) => self.out.push_str(&escape_text(&t.value)),
      Node::Bold(i) => self.wrap_tag("strong", &i.children),
      Node::Italic(i) => self.wrap_tag("em", &i.children),
      Node::Strikethrough(i) => self.wrap_tag("del", &i.children),
      Node::InlineCode(c) => {
        self.out.push_str("<code>");
        self.out.push_str(&escape_text(&c.value));
        self.out.push_str("</code>");
      },
      Node::Link(l) => {
        self.out.push_str(&format!("<a href=\"{}\"", escape_attr(&escape_url(&l.href))));
        if let Some(label) = &l.title {
          self.out.push_str(&format!(" aria-label=\"{}\"", escape_attr(label)));
        }
        self.out.push('>');
        for c in &l.children {
          self.inline_node(c);
        }
        self.out.push_str("</a>");
      },
      Node::Image(i) => self.image(i),
      Node::HardBreak(_) => self.out.push_str("<br />\n"),
      Node::SoftBreak(_) => self.out.push('\n'),
      Node::CodeBlock(cb) => self.code_block(cb),
      _ => {
        self.open_tag(node);
        for kid in Node::children_of(node) {
          self.inline_node(kid);
        }
        self.close_tag(node);
      },
    }
  }

  fn wrap_tag(&mut self, tag: &str, children: &[Node]) {
    self.out.push('<');
    self.out.push_str(tag);
    self.out.push('>');
    for c in children {
      self.inline_node(c);
    }
    self.out.push_str("</");
    self.out.push_str(tag);
    self.out.push('>');
  }
}

/// Convenience: render `doc` to HTML with a throwaway diagnostic engine.
/// GFM Disallowed Raw HTML extension: these tag names get their `<`
/// escaped to `&lt;` so they don't render in the browser. Comparison
/// is ASCII case-insensitive (`<XMP>` and `<xmp>` both match).
fn is_disallowed_raw_html(name: &str) -> bool {
  matches!(
    name.to_ascii_lowercase().as_str(),
    "title" | "textarea" | "style" | "xmp" | "iframe" | "noembed" | "noframes" | "script" | "plaintext"
  )
}

fn escape_disallowed_raw_html_tag(raw: &str) -> String {
  let bytes = raw.as_bytes();
  let mut out = String::with_capacity(raw.len());
  let mut i = 0;
  while i < bytes.len() {
    if bytes[i] == b'<' {
      let mut j = i + 1;
      if j < bytes.len() && bytes[j] == b'/' {
        j += 1;
      }
      let name_start = j;
      while j < bytes.len() && ((bytes[j] as char).is_ascii_alphanumeric() || bytes[j] == b'-') {
        j += 1;
      }
      if j > name_start && is_disallowed_raw_html(&raw[name_start..j]) {
        out.push_str("&lt;");
        i += 1;
        continue;
      }
    }
    out.push(bytes[i] as char);
    i += 1;
  }
  out
}

pub fn render_html(doc: &Document) -> String {
  let mut e = HtmlEmitter::new();
  Walker::new(doc).walk(&mut [&mut e]);
  e.into_string()
}

pub fn render_html_with(doc: &Document, options: RenderOptions) -> String {
  let mut e = HtmlEmitter::new_with_options(options);
  Walker::new(doc).walk(&mut [&mut e]);
  e.into_string()
}

/// Recognise a JSX expression whose entire body is a single string
/// literal (single-quoted, double-quoted, or backtick template with no
/// `${...}` interpolation). MDX authors use these as inline whitespace /
/// inserted text (`{' '}`, `{"x"}`, `` {`y`} ``); they need no JS
/// runtime, so the HTML emitter can lower them to plain text instead
/// of dropping + warning. Genuinely dynamic expressions (`{count}`,
/// `{foo()}`) return `None` and still trip GW002.
fn string_literal_expression(raw: &str) -> Option<String> {
  let s = raw.trim();
  if s.len() < 2 {
    return None;
  }
  let bytes = s.as_bytes();
  let q = bytes[0];
  if !matches!(q, b'\'' | b'"' | b'`') || bytes[bytes.len() - 1] != q {
    return None;
  }
  let inner = &s[1..s.len() - 1];
  // Reject template literals with interpolation - those need JS to
  // evaluate. `${` must be escaped (`\${`) or absent for the literal
  // to be safe to lower to plain text.
  if q == b'`' {
    let mut prev_backslash = false;
    let bs = inner.as_bytes();
    let mut i = 0;
    while i + 1 < bs.len() {
      if !prev_backslash && bs[i] == b'$' && bs[i + 1] == b'{' {
        return None;
      }
      prev_backslash = bs[i] == b'\\' && !prev_backslash;
      i += 1;
    }
  }
  // Decode the common JS escapes we expect to see in MDX prose:
  // `\n`, `\t`, `\r`, `\\`, `\'`, `\"`, `` \` ``. Anything else is
  // passed through verbatim - no need for full ECMA-262 escape
  // semantics here, the result is going straight into HTML text.
  let mut out = String::with_capacity(inner.len());
  let mut chars = inner.chars();
  while let Some(c) = chars.next() {
    if c != '\\' {
      out.push(c);
      continue;
    }
    match chars.next() {
      Some('n') => out.push('\n'),
      Some('t') => out.push('\t'),
      Some('r') => out.push('\r'),
      Some('\\') => out.push('\\'),
      Some('\'') => out.push('\''),
      Some('"') => out.push('"'),
      Some('`') => out.push('`'),
      Some(other) => {
        out.push('\\');
        out.push(other);
      },
      None => out.push('\\'),
    }
  }
  Some(out)
}

#[cfg(test)]
mod tests {
  use super::string_literal_expression;

  #[test]
  fn recognises_simple_quoted_strings() {
    assert_eq!(string_literal_expression("' '"), Some(" ".into()));
    assert_eq!(string_literal_expression("\"x\""), Some("x".into()));
    assert_eq!(string_literal_expression("`y`"), Some("y".into()));
  }

  #[test]
  fn rejects_template_with_interpolation() {
    assert!(string_literal_expression("`hi ${name}`").is_none());
  }

  #[test]
  fn rejects_dynamic_expression() {
    assert!(string_literal_expression("count").is_none());
    assert!(string_literal_expression("foo()").is_none());
    assert!(string_literal_expression("a + b").is_none());
  }

  #[test]
  fn decodes_common_escapes() {
    assert_eq!(string_literal_expression("'\\n'"), Some("\n".into()));
    assert_eq!(string_literal_expression("'\\\\'"), Some("\\".into()));
  }
}