Wado

WEP: Tagged Template Literals

Context

A template string `id = ${id}` renders every interpolation through Display. That is the right default for text and the wrong one for every structured sink: a SQL query wants ${id} bound as a parameter, an HTML fragment wants ${name} escaped for the context the literal text put it in, a log line wants ${user.id} as a typed field beside the message, a URL wants each segment percent-encoded. Each of these sinks is a function of two things the untagged template throws away — the literal text around a hole, and the hole's value in its own type.

A tag names that function: sql`SELECT * FROM users WHERE id = ${id}` hands sql the literal segments and the typed values instead of a rendered String. The surface is JavaScript's; the model underneath is Wado's own.

The original design of this feature was a compile-time decoder — a tag was an effect-free fn(String) -> T run by the compiler, motivated by embedding base64 blobs and validating regex literals. Both motivations have since been served elsewhere: b"…" byte strings and #include_bytes embed binary as a constant data segment, and Kiln validates file-shaped DSL inputs. What no other mechanism serves is the interpolation case above, and it does not need compile-time execution at all. So this WEP puts the tag's job where the remaining demand is, and treats folding at compile time as an optimization the optimizer may perform, never as the semantics.

Three things the language has grown since decide the shape:

Together they let the static part of a template live where a tag body reads it as a constant. Its specifiers, its arity and the type at each hole live in a type. Its literal segments live in the value, as string literals. That is what makes a tagged template cost what the untagged one costs.

Decision

Surface

let q = sql`SELECT * FROM users WHERE id = ${id} AND name = ${user.name}`;
let s = String::format`${dir}/bin/run`;

A tag is a path expression — a function name or a static method path — written directly before the backtick, with no whitespace between. The backtick is a postfix on the path, at the precedence of a call. Only a path may be a tag: a call result, a closure, or a parenthesized expression is not one, so f()`x` and (g)`x` are syntax errors.

The template body is lexed exactly as an untagged one: ${expr} and ${expr:spec} holes, { and } literal, \$ the only escape a hole needs. The tag changes nothing about how the literal reads, only about what it means.

A tag is an ordinary function — any effects, any return type — whose first parameter is satisfied by ReflectTemplate. The template is its one written argument, and ordinary call resolution fills the trailing parameters that declare a default. Nothing about being a tag appears on the declaration; a function is a tag because a call site wrote it before a backtick. A first parameter of any other type is reported as a tag's missing bound, naming the type it takes, since the template's own type is one no source spells.

The template type

Each template literal that carries a tag denotes a value of a compiler-synthesized struct type, unique to that template's shape. The shape is its delimiters and the list of its holes, each a type and a specifier. Two templates with the same shape denote the same type and share every instantiation of the tag, whatever their literal text, so tag`a=${a}` and tag`b: ${b}` are one type where a and b share one. The type is anonymous — nothing in the source can name it — and is reached only through the bound the tag declares.

The value holds one field per hole, then the literal text: each segment twice, with escapes processed and as written. The text is per site, so it lives in the value, and the type stays one per shape. A segment field is a String built from the literal, which constant object globalization hoists as it hoists any constant literal, and a tag reads a segment as a StrSlice over it.

The name the type shows a reader, in a diagnostic and as Reflect::decl_name(), is its holes, each spelled as its type and specifier, cut to 50 characters with ...: sql`id = ${id:04}` is named `${i32:04}`. The name describes the shape but does not identify it: past the cut, two shapes can read alike.

A hole's field carries its value without copying it and without boxing it. A type whose reference is a bare GC handle — struct, List, String, i128 — is held as &V; a type whose reference the compiler would box — a primitive, an enum, flags, a variant, a function — is held as V, since a scalar copy is free and a box is an allocation. One predicate decides, the one Reference Representation boxes by. The tag never sees the difference: TemplateHole::get answers V either way.

The type is one of the reflected kinds, under the same seal as the five declaration kinds: compiler-synthesized, a user impl a compile error, callable only where T is concrete. It is pub like the rest of the family: a tag names it in its own bound, and tags are written in ordinary packages. The seal is what makes that safe: only the compiler can satisfy the bound, so naming it is all a caller gains.

#[compiler_item("reflect_template")]
pub trait ReflectTemplate: Reflect {
    /// The hole types as a tuple `[V_0, V_1, …]` — the payload pack.
    type Holes;

    /// The per-hole member tuple `[TemplateHole<Self, V_0>, TemplateHole<Self, V_1>, …]`.
    type Members;

    /// Returns the per-hole members.
    fn members() -> Self::Members;

    /// The literal text of `t` after the last hole; the whole template when it
    /// has none. Escapes processed.
    fn tail(t: &Self) -> StrSlice;

    /// `tail(t)` with escapes preserved.
    fn raw_tail(t: &Self) -> StrSlice;

    /// How many `#`s delimit the template on each end: 0 for `` `…` ``.
    fn hashes() -> i32;
}

A hole is a member handle like StructField: sealed, fields private, minted only by members(), and not itself reflectable. Like every member handle it is prelude API, so a helper that takes one names it.

#[compiler_item("template_hole")]
pub struct TemplateHole<T, affine V> { … }

impl<T, affine V> TemplateHole<T, V> {
    /// The hole's position in the template, from 0.
    pub fn index(&self) -> i32;

    /// The literal text of `t` between the previous hole (or the start) and
    /// this one, escapes processed.
    pub fn lit(&self, t: &T) -> StrSlice;

    /// `lit(t)` with escapes preserved: `\n` is a backslash and an `n`.
    pub fn raw(&self, t: &T) -> StrSlice;

    /// A reference to the hole's value in `t`, which reaches an affine hole.
    pub fn get_ref(&self, t: &T) -> &V;

    /// The specifier as written after the `:`, or `None` without one.
    pub fn spec(&self) -> Option<String>;

    /// Whether the hole wrote a `:spec`.
    pub fn has_spec(&self) -> bool;

    /// Renders the value through the trait method the specifier's type
    /// selects (`Display::fmt` when it names none), on a `Formatter` carrying
    /// the specifier's fill, alignment, sign, width and precision over `f`'s
    /// buffer.
    pub fn fmt(&self, t: &T, f: &mut Formatter);
}

impl<T, V> TemplateHole<T, V> {
    /// The hole's value in `t`. A read-only use shares the storage, as a
    /// `StructField::get` does; only a mutation copies.
    pub fn get(&self, t: &T) -> V;
}

index(), spec() and has_spec() return constants of the shape. lit and raw view the text t refers to, which at a literal site is the constant written there. fmt's body is synthesized per hole, so the choice of trait method — a compile-time decision, as in an untagged template — is closed inside it. The tag never sees a pre-rendered String it did not ask for, and a tag that rejects specifiers reads has_spec().

The literal segments are the same string in two spellings, both fields of the value, and the one a tag never reads is a field nothing passes. That is the whole cooked-versus-raw mechanism: no mode, no marker type, and no inspection of the tag's signature. A raw segment of a cooked template is still a template segment, so it spells only the escapes the language has, and \p is an error. A text full of backslashes, such as a regular expression, is a raw template, #`…`#, which takes every backslash as itself, so both of its spellings are the text as written (WEP: Re).

The prelude has no counterpart of JavaScript's String.raw tag. A raw template already renders its text as written with no tag, and a tag over a cooked template could only keep the escapes the lexer accepts. The # count is part of the shape, which hashes() answers as a constant. A runtime field on every template value was the alternative: it keeps a cooked and a raw template of the same holes one type, at the cost of a field in every String::format call, raw or not.

A template value inspects as the template it was written as: its delimiters, the raw segments, and each hole's value inspected and followed by its specifier. The form is a blanket impl Inspect over ReflectTemplate in the prelude, as every other kind's is, reading the holes through get_ref so that an affine hole renders too. A struct of the holes was the alternative. It drops the text, and == compares the text, so a failing assert on two values differing only in their text would show them alike.

A width in ${t:>4?} pads each hole's value and leaves the text alone, as a list's pads each element. A template value can be a table cell, and Rust's Debug hands the width to each field in the same way.

Desugaring

sql`SELECT * FROM users WHERE id = ${id} AND name = ${user.name}`

lowers to

$tagged: {
    sql($Tmpl_a3f1 {
        h0: id, h1: &user.name,
        s0: "SELECT * FROM users WHERE id = ", r0: "SELECT * FROM users WHERE id = ",
        s1: " AND name = ", r1: " AND name = ",
        s2: "", r2: "",
    })
}

id is an i32, so its hole holds the value; user.name is a String, so its hole holds the handle. s{k} is segment k with escapes processed, r{k} as written. A hole that names storage is read or referenced where it stands: a local, a global, or a field or element path rooted at one. Any other hole expression is evaluated once into a local of the block, which the literal then reads or references.

The holes are evaluated in source order, the order an untagged template evaluates them, and the literal is built after the last of them. So a hole is read in situ only while nothing after it can write that storage. A hole that names storage and is followed by one that does not is bound at its own position too, and the tag then sees the value the storage held there. That is what holds String::format`${a} ${bump(&mut a)}` to what `${a} ${bump(&mut a)}` renders.

The struct literal is the only place the synthesized type is built. Passing it by value copies scalars and handles, never the storage a handle points at. Referencing a local of a handle type marks nothing on that local: only a box-target type's local is retagged by a reference, and those holes are held by value.

The synthesized impl ReflectTemplate carries each hole's index and whether it has a specifier as literals in its members() body. TemplateHole::get projects the field at the hole's index, dereferencing a handle field, and lit, raw, tail and raw_tail project a segment field.

Writing a tag

A tag binds its template through ReflectTemplate, binds the hole pack off Holes, and walks members():

fn sql<T: ReflectTemplate<Holes = [..V]>, ..V: ToSqlParam>(t: T) -> SqlQuery {
    let mut query = "";
    let mut params: List<SqlParam> = [];
    for let h of ReflectTemplate::<T>::members() {
        query.push_str(h.lit(&t));
        query.push_str("?");
        params.push(h.get(&t).to_sql_param());
    }
    query.push_str(ReflectTemplate::<T>::tail(&t));
    return SqlQuery { query, params };
}

..V: ToSqlParam is what makes sql`… ${some_struct}` a bound error naming the type, rather than a missing-method error inside the unrolled body. The walk is tuple for-of, so a state carried across holes is a local, and one per hole is the .enumerate() index:

fn html<T: ReflectTemplate<Holes = [..V]>, ..V: Display>(t: T) -> Html {
    let mut out = "";
    let mut ctx = HtmlContext::Text;
    for let h of ReflectTemplate::<T>::members() {
        out.push_str(h.lit(&t));
        ctx = ctx.advance(&h.lit(&t));    // attribute? script? text?
        ctx.escape_into(h.get(&t), &mut out);
    }
    out.push_str(ReflectTemplate::<T>::tail(&t));
    return Html { out };
}

A tag with no use for holes constrains the pack to the empty tuple.

fn regex<T: ReflectTemplate<Holes = []>>(t: T) -> Regex {
    return Regex::compile(ReflectTemplate::<T>::tail(&t)).unwrap();
}

members() walks a pack, so those are the two spellings it can be called under. A concrete tuple (Holes = [List<i32>]) binds no pack, and the call is an error naming the binding it needs.

A hole's specifier is part of the template, not of the tag, so every hole's type implements the trait its specifier selects (Display when it names none) under any tag, whether or not the tag renders it. A tag counting its holes rejects ${pt} over a Pt with no Display, as String::format does. A template then means one thing to its type checker whichever tag reads it. The cost falls on a tag that reads only get, such as sql: a hole whose type has no Display is written ${pt:?} there.

A hole's type may mention a type parameter of the enclosing item. The shape is then generic over that parameter, and the item's instantiation instantiates the tag with it. The specifier's trait, and any bound the tag places on its pack, is met through the bounds the item declares, as for any call: `${x}` over x: X asks for X: Display, as a call of push_display(&x) would. A generic body that cannot name the bound passes its tag a concrete value instead.

The untagged template is a tag

An untagged template is sugar for a call of the String::format tag, which a program may also call by name. It names the prelude's String wherever it stands, even where an import takes the name or the module has no prelude. The tag is a static method rather than a prelude function, so it leaves the name format free for a program's own items:

impl String {
    pub fn format<T: ReflectTemplate<Holes = [..V]>, ..V>(t: T) -> String {
        let mut out = "";
        for let h of ReflectTemplate::<T>::members() {
            out.push_str(h.lit(&t));
            h.fmt(&t, &mut Formatter::new(&mut out));
        }
        out.push_str(ReflectTemplate::<T>::tail(&t));
        return out;
    }
}

What a template string compiles to is written in Wado, where a reader can see it, and the per-hole rendering is the one piece the compiler synthesizes (TemplateHole::fmt). It replaced a direct lowering of the untagged case (String Template Desugaring), which rendered each hole before it evaluated the next.

Cost

What the tag body compiles to, once monomorphized, inlined and folded:

The residue is the code a hand-written builder would be: one constant append per segment and one typed operation per hole. That is the design's claim, and a wir_expect fixture holds a tag to it. Where a read fails to fold, that is the optimizer's gap to close, not a reason to move the segments into a runtime value.

Each distinct template shape instantiates the tag once, so sites that differ only in their text share one instantiation, and an unoptimized build compiles the tag once per shape. Where the optimizer specializes, it clones that instantiation per distinct text, as inlining a builder at each site would, within param_spec's cap on clones.

Compile-time evaluation

A tag call is a call. Whether it runs at compile time is decided the way every other call is: niri folds a pure call over constant arguments when it can, and a wasm-CTFE backend may fold more once it exists (NIR Interpreter). A hole-less template under a pure tag — regex`^[a-z]+$` — is a candidate; a template with holes is a candidate only where the holes are constant. Nothing in the tag's meaning depends on the outcome, and a tag may carry effects. A program that wants a hole-less tag evaluated once writes a global, which the lazy-init path already guarantees.

Deliberate omissions

Alternatives considered

Type-level strings. The segments could ride as type arguments — Template<"SELECT ", " AND ", [..V]> — instead of in a synthesized nominal type. It is the more general mechanism: a Route<"/users/{id}"> or a Regex<"…"> would name its literal in its type, and #[param] could carry a value parameter the same way. It needs value parameters in the type system and a second pack alongside ..V, neither of which exists, and it buys a tagged template nothing the synthesized type does not. Should it arrive, the synthesized type can be re-expressed as an instance of it without changing what a tag can observe, since the type is unnameable.

Compile-time execution as the semantics — the original design. A tag was an effect-free fn(String) -> T the compiler ran. It required a whole-program evaluator the toolchain does not have, restricted tags to pure functions, and solved a problem (base64`…`) that literals and #include_bytes since solved better. Kept as an optimization opportunity, dropped as a promise.

Consequences

Implementation

The template type is an anonymous struct — the precedent is the struct literal { x: 1, y: "s" }, which already satisfies ReflectStruct through the same machinery (tests/fixtures/reflect_anon_struct.wado) — and ReflectTemplate follows ReflectStruct at every step of the reflect pipeline. Nothing below introduces a mechanism; each item names the existing one it extends.

Type table (tir.rs)

Prelude (lib/core/prelude/traits.wado, lib/core/builtin.wado)

Parser and AST

Annotate (elaborator/tagged_template.rs)

resolve_tagged_template records facts on the expression's AstId and returns the tag's result type:

  1. Resolve each hole expression with no expected type; validate segments through the same unescape gate resolve_template_string runs.
  2. Build the shape, intern it, make_struct(StructDef::Anon(shape)), and on a first sighting register StructFieldInfo under anon_struct_fields and push the TirStruct onto pending_anonymous_structs — the minting resolve_anonymous_struct_literal does, factored into one helper both call.
  3. Resolve the tag as a one-argument call whose argument type is known and has no AST: resolve_call_with_args is resolve_call over arguments already typed, keyed by the template's AstId, so signature lookup, instantiation, the projection of ..V from Holes, the bound check and the StaticMethodDispatch fact are the ones a spelled call records. A tag of any other arity, or one the call path cannot find, is that path's diagnostic. A tag naming a value is refused before the call is resolved, and one that resolves without a dispatch fact after it.
  4. Record the template type under the template's AstId (tagged_templates); place-ness and the segments are reify's to read off the AST.
  5. The tag identifier's use→def edge falls out of the call resolution.

Reify

reify_tagged_template reifies each hole in order, binding one that is not a place to a let $hole_{n}_{k} local, and builds the Call the dispatch fact names over a StructLiteral whose field h{k} is the place or local, referenced when the field type is &V_k, and whose segment fields are string literals, cooked through unescape_template_segment and raw verbatim. With locals the call sits in a labeled block that breaks with its value. The TirStruct reaches the module through the pending list reify already drains.

{n} is FunctionContext::fresh_serial, taken before the holes are reified. The serial advances on read, so a template nested inside a hole mints its own $hole_{n+1}_{k} and $tagged_{n+1} instead of the enclosing template's names (issue #1987).

Reflect resolution (elaborator/reflect.rs, solver_bridge.rs, trait_query.rs)

Synthesis (synthesis/traits.rs, synthesis/template.rs)

Optimizer (optimize/param_spec.rs, optimize/multi_value_param.rs)

A segment reaches the tag as a field of its argument, so folding it takes three things the optimizer gains here.

Fixtures

Order

Prelude and registry first, so every later step compiles against the trait; then the reflect resolution, since the call-site bound check needs the kind before any tag call can be typed; then parser, annotate and reify; then synthesis and the fold; then the prelude tags and fixtures.

Roadmap

An untagged template is sugar for String::format. The compiler first lowered it on a path of its own that rendered each hole before it evaluated the next. The items below closed that, in this order.

The cost gap is measured inside the guest by this program, so the runner's start-up stays out of it. Run it with wado run -O2 bench.wado; each phase reports the time one iteration of its loop took.

use { Stdout } from "core:cli";
use { Benchmark } from "core:benchmark";
use { MonotonicClock } from "wasi:clocks";

struct Pt { x: i32, y: i32 }

export fn run() with (Stdout, MonotonicClock) {
    let mut bench = Benchmark { name: "template" };
    bench.work_per_iter = Option::Some(100000.0);
    bench.unit = "templates";
    bench.run("warm-up", || {
        let mut total = 0;
        for let i of 0..<100000 { total += `i=${i}`.len(); }
        return total;
    });
    bench.run("untagged all", || {
        let mut total = 0;
        for let i of 0..<100000 {
            let p = Pt { x: i, y: i * 2 };
            total += `i=${i:05} f=${(i as f64) / 3.0:.2} h=${i:#x} p=${p:?} end`.len();
        }
        return total;
    });
    bench.run("format all", || {
        let mut total = 0;
        for let i of 0..<100000 {
            let p = Pt { x: i, y: i * 2 };
            total += String::format`i=${i:05} f=${(i as f64) / 3.0:.2} h=${i:#x} p=${p:?} end`.len();
        }
        return total;
    });
    bench.run("untagged i05", || {
        let mut total = 0;
        for let i of 0..<100000 { total += `i=${i:05} end`.len(); }
        return total;
    });
    bench.run("format i05", || {
        let mut total = 0;
        for let i of 0..<100000 { total += String::format`i=${i:05} end`.len(); }
        return total;
    });
    bench.run("untagged f.2", || {
        let mut total = 0;
        for let i of 0..<100000 { total += `f=${(i as f64) / 3.0:.2} end`.len(); }
        return total;
    });
    bench.run("format f.2", || {
        let mut total = 0;
        for let i of 0..<100000 { total += String::format`f=${(i as f64) / 3.0:.2} end`.len(); }
        return total;
    });
    bench.run("untagged #x", || {
        let mut total = 0;
        for let i of 0..<100000 { total += `h=${i:#x} end`.len(); }
        return total;
    });
    bench.run("format #x", || {
        let mut total = 0;
        for let i of 0..<100000 { total += String::format`h=${i:#x} end`.len(); }
        return total;
    });
    bench.run("untagged p?", || {
        let mut total = 0;
        for let i of 0..<100000 {
            let p = Pt { x: i, y: i * 2 };
            total += `p=${p:?} end`.len();
        }
        return total;
    });
    bench.run("format p?", || {
        let mut total = 0;
        for let i of 0..<100000 {
            let p = Pt { x: i, y: i * 2 };
            total += String::format`p=${p:?} end`.len();
        }
        return total;
    });
}

The first phase a program runs is slower and varies between runs, so a warm-up phase takes that cost. Three runs:

Template String::format time per iteration, untagged = 1
the four holes 0.80 to 0.82
${i:05} alone 1.03 to 1.04
${f:.2} alone 1.03 to 1.06
${i:#x} alone 1.06 to 1.11
${p:?} alone 0.99 to 1.04

Known gaps

References