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:
- Variadic type parameters and tuple enumeration walk a heterogeneous tuple with one body per element, unrolled.
- Reflection exposes a declaration's structure as a sealed, compiler-synthesized trait whose member handles are constants, so a walk over them folds to the code a hand-written body would be.
- Constant object globalization
hoists a closed constant expression to a global, and
niriprojects fields back out of one.
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:
for let h of members()is unrolled — one straight-line block per hole.members()is a closed constant expression: globalization hoists it, and everyindex()/has_spec()is a field projected out of that global, whichnirifolds to the literal.lit(t)/raw(t)views a segment field of the template, at an indexmembers()makes constant. The field is a string literal, which specialization folds into the tag's clone and globalization hoists. A segment field the tag never reads is passed nowhere.get()is a projection of the template struct's field at a constant index, folded to a direct field read after inlining, asStructField::getis. Its result binds read-only in every tag above, so the value-copy planner shares the storage rather than copying it — the pathcore:serde'sf.get(self)already takes.- A hole holds a handle or a scalar, so nothing a handle points at is copied
into the tag, and no last-use analysis is asked to elide a copy. A hole bound
at its own position for evaluation order copies what a
letwould.
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
- No tag on a non-path expression, and no whitespace between the tag and the
backtick: the grammar stays a postfix on a path, which is what the reserved
<position andwado formatcan hold. - No compile-time execution in the semantics, per the above.
- No
Template<..V>runtime value holding the segments as an array. An array costs an allocation and an indexed load per segment at every evaluation, and left the specifier as either a lost type or a pre-rendered string. The type carries the specifiers, and each segment is a field of the value, read at an index the walk makes constant. - No segment text in the type. A type per text instantiates the tag once per distinct literal however alike two sites are, which costs every build the compile time and size an optimized one may choose to spend.
- No sink trait (
begin/lit/hole/finish) as the tag protocol. It reaches the same cost, but a tag that needs the whole template — to count holes before emitting, or to read a later segment — cannot be written against it, and it would make a tag a type rather than a function. - No literal index into
MembersorHoles: a pack is walked, never indexed (WEP 2026-03-14). - No hole source text. A tag reading it would make the spelling of a hole part
of the shape, so
tag`${a}`andtag`${b}`would instantiate the tag twice over one layout.
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
- A tagged template costs what an untagged one costs: constant appends and
typed operations, no runtime segment table, no value copies.
String::formatdoes not hold to this yet; the roadmap carries it. - Tag authors write one generic function, in Wado, against traits the language already has. SQL, HTML with contextual escaping, structured logging, URL building and raw strings are library code.
- The
ReflectTemplatekind is a sixth entry underReflect, synthesized per template shape rather than per declaration.TemplateHolejoins the other member handles under the same seal. - Type checking of the walk body is at monomorphization, as it is for every
pack walk. A pack bound (
..V: Trait) makes the common failure a bound error at the call site; a failure inside the body needs the call-site, element and body locations the variadic WEP already asks for. Enforcing that bound closed a gap every projected pack had: the bound check ran before the projection made the pack concrete and never asked again, so..F: TraitoffFieldTypesheld for any struct. - The binary grows by one tag instantiation per template shape, and where the optimizer specializes, by one clone per distinct text, as it would by inlining a builder at each site.
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)
AnonShape::Template(TemplateShape)besideFieldsandSynthetic.TemplateShape { holes: Vec<TemplateHole>, quote: Quote }, each hole{ ty, spec: Option<String> }. The shape is the interning key, so two sites of one shape reach oneAnonStructIdthroughintern_shape, as struct literals do.- The struct's fields are derived from the shape:
h{k}typedhole_field_type(V_k), which is&V_kwhereV_kis not a box target andV_kwhere it is, then oneStringper segment spelling,s{k}cooked andr{k}raw.TemplateShape::segment_keynumbers them2kand2k + 1, the keybuiltin::template_segmenttakes. The box-target predicate moves out oflower::plan::boxing'screate_needed_box_typesinto oneTypeTable::is_boxed_reference_target, which the boxing pass then consumes, so the two cannot drift. It is the single predicate Reference Representation calls for. reflect_kindanswersReflectTemplatefor aStruct { def: Anon(shape) }whose shape is a template;is_sealed_reflect_memberadds theTemplateHolehandle.anon_struct_manglerenders a template shape under a$tmplprefix over the shape's hash, andanon_struct_namerenders the reader's name above, whichReflect::decl_name()answers. The mangle is fixed when the shape is interned: it renders the hole types, and erasure later redirects a newtype among them to its base, so a second rendering would name a struct WIR never registered — the same failure a struct literal with a newtype field had.
Prelude (lib/core/prelude/traits.wado, lib/core/builtin.wado)
#[compiler_item("reflect_template")] pub trait ReflectTemplate: ReflectwithHoles,Members,members(),tail(t),raw_tail(t), each method carrying its owncompiler_item.#[compiler_item("template_hole")] pub struct TemplateHole<T, affine V> { index, spec }with the constant accessors reading fields, and four bridged ones:getisbuiltin::hole_get::<T, V>(t, self.index),get_refisbuiltin::hole_ref::<T, V>(t, self.index),fmtisbuiltin::hole_fmt::<T>(t, self.index, f), andlit/rawarebuiltin::template_segment::<T>(t, 2 * self.index)and… + 1. The builtins are bodyless markers besidestruct_field_get.core:preludere-exports it with the other member handles.compiler_item.rsgainsReflectTemplate,ReflectTemplateHoleand the three method items, inALL,attr_name,expected_kind,is_required.String::formatin the string module, written as the tag above.
Parser and AST
Expr::TaggedTemplate(Box<TaggedTemplateExpr { id, tag: Expr, template: TemplateStringExpr, span }>), the tag always anExpr::Ident. A new variant rather than a field onTemplateStringExpr: a tagged template is a call, and the arms that treat a template as a string literal (overload classification'sArgClass::StrLit, newtype literal coercion) must not see it. Every exhaustive match then names the arm; the visitor walks the tag so hover, references and comment attachment reach it.parse_postfix_exprtakes aTemplateStringLitarm: the receiver must beExpr::Identandexpr.span().end == peek().span.start. Whitespace and comments never reach the token stream, so a byte gap is the adjacency test. A non-path receiver is a syntax error naming the rule; a gap falls through to the ordinary unexpected-token error.unparseprints the tag then the template with nothing between, in both printers.Wado.g4addstaggedTemplate : (tagOwner '::')* tagName templateStringtoprimaryandprimaryNoStruct; the grammar cannot see the gap, so the whitespace case is acompile_errorfixture undercheck-grammar's second invariant.Wado.highlights.scmcapturestagNameas@function, and the LSP's call heuristic reads an adjacent template as a call, so both sides colour the tag alike.
Annotate (elaborator/tagged_template.rs)
resolve_tagged_template records facts on the expression's AstId and returns
the tag's result type:
- Resolve each hole expression with no expected type; validate segments through
the same unescape gate
resolve_template_stringruns. - Build the shape, intern it,
make_struct(StructDef::Anon(shape)), and on a first sighting registerStructFieldInfounderanon_struct_fieldsand push theTirStructontopending_anonymous_structs— the mintingresolve_anonymous_struct_literaldoes, factored into one helper both call. - Resolve the tag as a one-argument call whose argument type is known and has
no AST:
resolve_call_with_argsisresolve_callover arguments already typed, keyed by the template'sAstId, so signature lookup, instantiation, the projection of..VfromHoles, the bound check and theStaticMethodDispatchfact 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. - Record the template type under the template's
AstId(tagged_templates); place-ness and the segments are reify's to read off the AST. - 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)
ReflectDispatch::Templateand aTemplateMethods::resolvereading the method names off the registry, reached through theReflectTemplatearm ofreflect_dispatch_of.reflect_template_holesreads hole types off the shape. The concrete resolver typesmembers()aspayload_members_ty(ReflectTemplateHole, T, holes)andtail(&T)/raw_tail(&T)asString. The generic resolver, for a body written againstT: ReflectTemplate<Holes = [..V]>, typesmembers()as the mapped pack[..TemplateHole<T, V>]throughpayload_member_pack_bound_ty, andemit_missing_pack_boundspellsHoles = [..V].concrete_reflect_assoc_typegains the template arm, so a call site projectsHolesandMembersbefore synthesis has registered them.solver_bridge:ReflectTemplatejoinsREFLECT; every template shape lowers under the oneDeclKey::TemplateShapehead with its hole types as the arguments, andstate_reflect_factsstates it visible from every module.trait_query:OnBoundTrait::ReflectTemplate,on_bound_of, andreflect_members_visibleanswering true.- The seal list in
orchestration.rsnamesReflectTemplate.
Synthesis (synthesis/traits.rs, synthesis/template.rs)
collect_reflect_targetsroutes a template-shapedTirStructtogenerate_template_reflect_implsinstead of the struct kind. Per shape it emitsdecl_nameandwire_name_policyunder the root, registersHoles = [V_k]andMembers = [TemplateHole<T, V_k>], and emitsmembers()throughgenerate_template_members_fnwith oneTemplateHoleliteral per hole, plustail(t)andraw_tail(t)reading the last segment fields. The impl is recorded intoTraitEnvlike the struct kind's.- Four bridges per shape, minted beside
generate_field_bridge_helpers:$hole_get$<shape>$<V>(one per erased hole type,match indexover the holes of that type, dereferencing a handle field), its by-reference twin$hole_ref$<shape>$<V>,$template_segment$<shape>(match keyover the segment fields) and$hole_fmt$<shape>(match index, each arm rendering its hole:trait_fmt_callon the hole's value with theFormatterbuild_formatter_literalbuilds overf.buf, orfitself when the specifier sets no field).$hole_fmtis minted inline-always: its index is a constant at every siteTemplateHole::fmtreaches oncemembers()folds, so the splice keeps one arm where a call would keep the whole dispatch, which the threshold refuses. lower/translate.rsfoldsbuiltin::hole_get/hole_ref/hole_fmt/template_segmentcalls to the bridge names beside itsstruct_field_getarm;name.rsowns the names.- An open template shape gets no bridge. Each concrete shape only a
substitution reaches gets its own:
$hole_fmtinside the monomorphization fixpoint,$hole_get,$hole_refand$template_segmentafter monomorphization beside$field_get. The roadmap's generic template shapes item says why.
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.
param_speckeys a clone on a closed literal (String { repr: packed"…", used: n }) as on a scalar, and on the fields of a struct passed by value to a parameter the body never rebinds. A read of a bound slot becomes a fresh copy of the literal, as the literal at the call builds a fresh object. A callee reading its parameter throughlet r = &p, which inlining a&selfmethod mints, is summarized and substituted throughrtoo.- A call to a clone is specialized again on the slots it left open, so a
constant that settles a round after the one that minted the clone still
reaches it. Without that, a segment literal binding first would lock the
call out of the
Formatterconstantsprepare_int_writefolds on. multi_value_parampasses a by-value aggregate's read fields alone, as it already did for a&S, so the segments a clone folded are not passed.
Fixtures
tagged_template_sql.wado: typed holes through aToParampack bound.wir_expect:O2pins what is left — one constant byte array per segment, and oneParamconstruction per hole reading the hole field directly.wir_not_expect:O2denies$hole_get,$hole_fmt,members,to_paramand anypush_strcall.tagged_template_html.wado: state carried across holes.tagged_template_members.wado: everyTemplateHoleaccessor and the tails, with and without holes.tagged_template_holes.wado: hole evaluation order and count, a scalar hole's copy, a handle hole's sharing, two sites of one shape.tagged_template_hole_order.wado: a hole a later hole mutates carries the value it had at its own position.tagged_template_qualified_tag.wado: a static-method path on an imported type as the tag.tagged_template_tag_default_arg.wado: a tag whose trailing parameter has a default, filled at the site.tagged_template_format_equiv.wado:String::formatagainst the untagged form over the specifier matrix.tagged_template_decl_name.wado: the reader's name, specifiers and the cut included.tagged_template_inspect.wado: a value inspects as the template it was written as, in both forms, through an affine hole and through a hole whose type is a parameter; a width pads each hole; a hole handle inspects as its fields; and anassertcaptures a template value.tagged_template_shape_is_its_holes.wado: two templates differing only in their text, or in how a hole is spelled, are one type, each value carrying its own text.anon_struct_newtype_field.wado,reflect_pack_bound_free_fn_error.wado: the two pre-existing defects the work surfaced, pinned.- Errors: a non-path tag, a path that is neither a function nor a static
method, an undefined tag, a tag whose parameter is not
ReflectTemplate, whitespace before the backtick in statement and argument position, a tag of the wrong arity, an unsatisfied..Vbound naming the hole type, a concreteHolesbinding, a tag call whose effect the caller leaves undeclared. Each is one diagnostic.
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.
-
[x] Open anonymous shapes. A shape whose types mention a type parameter of the enclosing item is open. An anonymous shape's identity is its types, so substituting into an open shape interns the substituted shape:
{ a: X }atX = i32is the{ a: i32 }a concrete body writes.TypeTable::subst_recre-interns, andany_constituentlooks into the shape, socontains_type_paramreports it open. A closed shape is never re-interned: erasing an effect row changes no layout. An open shape emits noTirStruct. Monomorphization emits one for each concrete shape it interns, throughTirStruct::anonymous, as elaboration does for a written shape.Synthesis derives a shape's impls before monomorphization, so a substituted shape has none of its own. One concrete shape is where any number of open origins, and a literal, meet:
{ a: X }atX = i32,{ a: Y }atY = i32and a written{ a: 3 }are one type.subst_recrecords, per origin, the substitution that reaches the shape, over every parameter the origin mentions, and composes the records when a substituted shape is substituted again. Binding the origin against the shape cannot recover a record: a pack field or a projection binds no parameter. Monomorphization instantiates each origin's methods and associated types under its record (Monomorphizer::instantiate_shape_substitution), one method of a name per shape. As with a generic struct, an open shape's methods leave the module and its field bridges are minted after monomorphization, per concrete shape.A generic struct per shape was the alternative. It would need a
DefId, and theDefTableis fixed before elaboration mints a shape. It would also make{ a: X }atX = i32a type apart from{ a: i32 }.Done: a struct literal whose field mentions a type parameter compiles and runs at each instantiation, and its derived
Inspect,Eq,Ord,Serialize,DeserializeandReflectStructserve each one (anon_struct_type_param_field.wado). WIR build used to panic on one withunsubstituted TypeParam. -
[x] The specifier's trait checked at the template.
resolve_template_partsaskstype_implements_traitfor each hole's trait, so the check reads the declared bounds and runs under either form and every tag. WIR build used to catch a concrete hole that lacked the trait only when it found the call it could not resolve, and a generic hole only once instantiated.Done:
`${x}`overx: Xcompiles underX: Displayand reports the missing bound without it,${x:x}reports a missingLowerHexunderX: Displayalone (template_hole_trait_bound.wado,template_hole_trait_unbounded_error.wado), and a tag that never callsfmtrejects a hole lacking its specifier's trait (tagged_template_spec_trait_error.wado). -
[x] Generic template shapes. A template shape is open as the first item makes any shape. Each concrete template shape that monomorphization reaches instantiates each origin's
ReflectTemplateimpl as the first item instantiates any shape's methods.A hole is held by
&unless that would box it, so an open shape holds a hole of typeXby&, while the shapeX = i32reaches holds thei32by value. Substituting into an open shape's field types would therefore disagree with the concrete shape's layout. Three things follow.- Only a closed type decides how a hole is held (
tir::hold_hole). Reify holds the holes of a closed shape's literal, and monomorphization those of an open one once substituted, marking a local it takes&of as address-taken. - Synthesis gives an open shape no
$hole_fmt,$hole_getor$hole_ref. Their bodies read the fields, so none can be substituted from the open shape. - Each concrete shape only a substitution reaches is given its own helpers.
$hole_fmtis built inside the monomorphization fixpoint, so what it calls is instantiated in turn.$hole_getand$hole_refare minted after monomorphization, as$field_getis, because they group the holes by their type. Two holes ofXandYshare that type only once both arei32.
Done:
tag`${x}`overx: Xreaches the tag at each instantiation, including one a substitution reaches twice and one a literal also writes (tagged_template_generic_hole.wado). A tag's pack bound is checked against the declared bounds, andString::format`${x}`reports the missing bound`${x}`reports (tagged_template_generic_hole_bound_error.wado). - Only a closed type decides how a hole is held (
-
[x]
String::formatat the direct lowering's cost. Read offwado dump -O2, aString::formatsite cost more than the direct lowering in the places below. Each is closed where it arose:- The direct lowering sizes the buffer from the segment lengths.
String::formatsumstail(&t).len()and, per hole,lit(&t).len()plus a guess of 16 for the rendered hole. That folds to a constant, andString::formatstarts fromString::with_capacityof it. - A
Stringhole with no specifier is a plain append.String::formatreaches it throughDisplay::fmtandFormatter::pad, which fold to the same append onceparam_specspecializespadon theFormatter's constant fields.$hole_fmthands the formatter on as&mut Formatter { … }, soparam_specroots a reference local bound to a struct literal as it roots a struct local. - The radix renderer (
${i:#x}) is spliced into the site. Its call sits in abreakvalue in$hole_fmt, andinlinerescans every splice it makes, not only one at a statement, so the chain reachesu64::fmt_basewhile it still fits. - The direct lowering's buffer was lifted out of a loop by a pass of its own.
A
String::formatcall at a loop site stays a call, so there is nothing to lift, and the benchmark below ran the same with that pass skipped. - A
String::formatcall stays a call, since its body allocates. It runs once per iteration of the loop holding its site, soinlinestarts a function only loops reach at a loop site, and its callees splice as they would in the loop. A one-hole template's struct reachesString::formatas the hole itself:sroa_paramreads a parameter's uses off the body rather than the address-taken mark lowering left, which outlives the&tit recorded.
Done:
tagged_template_format_direct_cost.wadoholds aString::formatsite to a constant-sized buffer, noFormatter, nofmt_baseorpadcall, and the radix prefix a constant.tagged_template_format_loop_site.wadoholds one in a loop to no template struct and no call to the radix helpers. A single-hole site still pays its call intoString::format, which the measurement below shows as up to 1.11. - The direct lowering sizes the buffer from the segment lengths.
-
[x] One path. An untagged template reifies as the
String::formatcall, and the direct lowering (synthesis::template::build_template_block) is deleted withoptimize::tmpl_hoist, which only it fed. Reify resolves the call through theCompilerItemregistry rather than by name, so it reaches the prelude'sStringunder an import that takes the name (template_string_names_prelude_string.wado), and mints the shape of a template it synthesizes itself, anassert's failure message. The holes' types are the ones reify settles, so a hole whose type annotate leaves to later inference still renders.Done: no code path builds a
$tmplblock, and`${r} ${bump(&mut a)}`overr = &arenders whatString::formatrenders (template_string_hole_order.wado).
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
- A shape is interned per module, as struct literals are, so two modules writing one template instantiate the tag twice. Cross-module sharing is a size optimization the interner's key can take later.
- A concrete tuple binding for
Holes(Holes = [List<i32>]). It fixes the arity, somembers()would have a fixed type, but no tag has needed one;FieldTypesandCasePayloadsshare the limit. - A tag with a turbofish (
f::<T>`…`): the bare-turbofish path leaves the identifier's span at the name, so adjacency fails and the site is a syntax error. Nothing needs it yet. - A tag that is not a function or a static method — a variant case, a closure-typed binding — is a diagnostic. Reify rebuilds a tag call only from a static dispatch, and neither records one.
- Whether
match typegains atemplatearm for theTemplatecase Total Reflection gives the type. - A tag answered by a blanket impl (
i32::label`…`). It is not a tagged-template gap: the same static method fails the same way when spelled as a call, and is pinned as#[TODO]inreflect_pack_blanket_static_todo.wado. - A hole that is an affine place is read where the tag runs, not at its own
position, since it cannot be copied. A later hole that writes it shows
through:
`${c:?} ${c.bump()}`renderscafter the bump. The specification states this as an exception to evaluation order, andtemplate_affine_place_hole_reads_after_later_holes.wadopins it. - The monomorphization-time diagnostics the variadic WEP lists — call site, element index, body location — are what a failing tag body reports through, and are still open there.
Related WEPs
- String Template Desugaring — the untagged lowering, and
TemplateHole::fmt's per-specifier body - Compile-Time Tuple Enumeration — the walk
- Variadic Type Parameters — the pack bound and pack binding
- Library-Defined Derivation over
Reflect*— the kind and member-handle model this joins - Constant Object Globalization — why
members()is free - Template Format Specifiers — what
has_spec()andfmt()reflect - Markup Dialect — the HTML consumer
References
- MDN: Template literals
- Scala: String interpolation — interpolators as library methods over a
StringContext
