buildlang 1.15.0

BuildLang (buildc): an effects-oriented compiler with a verified C path, shader output, experimental backends, opt-in linear types, and re-checkable accountability + scientific-runtime receipts
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
//! In-module runtime for the WASM backend: a bump heap and Vec handles.
//!
//! The heap global `$__heap` grows up from above the shadow stack and calls
//! `memory.grow` when it reaches the end of memory; a failed grow traps.
//! A Vec is an i32 handle to a 12-byte header `{ptr, len, cap}`, so copying
//! a Vec value shares the vector, as `BuildVecHandle` does in the C runtime.
//! Element widths follow the element type (u8 is one byte, u32 four, u64
//! eight). Out-of-bounds `get`/`set` and `pop` on an empty vector trap.

use std::collections::BTreeSet;

use super::super::wasm_bin;
use super::*;

/// (suffix, width, value type, load, store)
const ELEMS: [(&str, u32, &str, &str, &str); 14] = [
    ("struct", 4, "i32", "i32.load", "i32.store"),
    ("BuildVecHandle", 4, "i32", "i32.load", "i32.store"),
    ("str", 4, "i32", "i32.load", "i32.store"),
    ("i8", 1, "i32", "i32.load8_s", "i32.store8"),
    ("u8", 1, "i32", "i32.load8_u", "i32.store8"),
    ("i16", 2, "i32", "i32.load16_s", "i32.store16"),
    ("u16", 2, "i32", "i32.load16_u", "i32.store16"),
    ("i32", 4, "i32", "i32.load", "i32.store"),
    ("u32", 4, "i32", "i32.load", "i32.store"),
    ("i64", 8, "i64", "i64.load", "i64.store"),
    ("u64", 8, "i64", "i64.load", "i64.store"),
    ("isize", 8, "i64", "i64.load", "i64.store"),
    ("usize", 8, "i64", "i64.load", "i64.store"),
    ("f64", 8, "f64", "f64.load", "f64.store"),
];

pub(super) struct RtFunc {
    pub(super) name: String,
    params: Vec<&'static str>,
    ret: Option<&'static str>,
    locals: Vec<&'static str>,
    body: String,
}

#[derive(Default)]
pub(super) struct RtState {
    pub(super) funcs: Vec<RtFunc>,
    pub(super) structs: HashMap<String, super::structs::StructLayout>,
}

fn mir_of(valtype: &str) -> MirType {
    match valtype {
        "i64" => MirType::i64(),
        "f64" => MirType::f64(),
        _ => MirType::i32(),
    }
}

/// Runtime helper that implements a MIR call name, if any.
pub(super) fn runtime_target(name: &str) -> Option<String> {
    match name {
        "Vec_new" | "vec_new" => return Some("__vec_new".into()),
        "build_hvec_len" => return Some("__vec_len".into()),
        "build_string_len" => return Some("__str_len".into()),
        "build_string_byte_at" => return Some("__str_byte_at".into()),
        "build_string_concat" => return Some("__str_concat".into()),
        _ => {}
    }
    let rest = name.strip_prefix("build_hvec_")?;
    let (op, sfx) = rest.split_once('_')?;
    let sfx = if sfx.starts_with(|c: char| c.is_ascii_uppercase()) {
        "struct"
    } else {
        sfx
    };
    let known = ELEMS.iter().any(|e| e.0 == sfx);
    (known && matches!(op, "push" | "get" | "set" | "pop")).then(|| format!("__vec_{op}_{sfx}"))
}

/// Runtime element suffix for a Vec element type (matches the lowering's names).
pub(super) fn vec_elem_suffix(ty: &MirType) -> Option<&'static str> {
    Some(match ty {
        MirType::Int(IntSize::I8, s) => {
            if *s {
                "i8"
            } else {
                "u8"
            }
        }
        MirType::Int(IntSize::I16, s) => {
            if *s {
                "i16"
            } else {
                "u16"
            }
        }
        MirType::Int(IntSize::I32, s) => {
            if *s {
                "i32"
            } else {
                "u32"
            }
        }
        MirType::Int(IntSize::I64, s) => {
            if *s {
                "i64"
            } else {
                "u64"
            }
        }
        MirType::Int(IntSize::ISize, s) => {
            if *s {
                "isize"
            } else {
                "usize"
            }
        }
        MirType::Bool => "i32",
        MirType::Float(FloatSize::F64) => "f64",
        MirType::Vec(_) => "BuildVecHandle",
        MirType::Struct(n) if n.as_ref() == "BuildString" => "str",
        MirType::Struct(_) => "struct",
        _ => return None,
    })
}

const ALLOC: &str =
    "global.get $__heap\nlocal.tee $t1\nlocal.get $p0\ni32.add\ni32.const 7\ni32.add\n\
i32.const -8\ni32.and\nlocal.tee $t0\nglobal.set $__heap\nblock $done\nloop $grow\nlocal.get $t0\n\
memory.size\ni32.const 16\ni32.shl\ni32.le_u\nbr_if $done\ni32.const 1\nmemory.grow\ni32.const -1\n\
i32.eq\nif\nunreachable\nend\nbr $grow\nend\nend\nlocal.get $t1\n";

const LEN_FIELD: &str = "local.get $p0\ni32.const 4\ni32.add\n";

fn bounds_check() -> String {
    format!(
        "local.get $p1\n{LEN_FIELD}i32.load\ni64.extend_i32_u\ni64.ge_u\nif\nunreachable\nend\n"
    )
}

fn elem_addr(index: &str, w: u32) -> String {
    format!("local.get $p0\ni32.load\n{index}i32.const {w}\ni32.mul\ni32.add\n")
}

fn build_func(name: &str) -> Option<RtFunc> {
    if let Some(rf) = build_str_func(name) {
        return Some(rf);
    }
    let f = |params: Vec<&'static str>, ret, locals: Vec<&'static str>, body: String| RtFunc {
        name: name.to_string(),
        params,
        ret,
        locals,
        body,
    };
    match name {
        "__alloc" => {
            return Some(f(
                vec!["i32"],
                Some("i32"),
                vec!["i32", "i32"],
                ALLOC.into(),
            ))
        }
        "__vec_new" => {
            return Some(f(
                vec![],
                Some("i32"),
                vec![],
                "i32.const 12\ncall $__alloc\n".into(),
            ))
        }
        "__vec_len" => {
            let body = format!("{LEN_FIELD}i32.load\ni64.extend_i32_u\n");
            return Some(f(vec!["i32"], Some("i64"), vec![], body));
        }
        _ => {}
    }
    let rest = name.strip_prefix("__vec_")?;
    let (op, sfx) = rest.split_once('_')?;
    let &(_, w, vt, load, store) = ELEMS.iter().find(|e| e.0 == sfx)?;
    let wrap_idx = "local.get $p1\ni32.wrap_i64\n";
    Some(match op {
        "push" => {
            let body = format!(
                "{LEN_FIELD}i32.load\nlocal.set $t0\nlocal.get $t0\nlocal.get $p0\ni32.const 8\ni32.add\n\
i32.load\ni32.eq\nif\nlocal.get $t0\ni32.const 1\ni32.shl\nlocal.tee $t1\ni32.const 4\nlocal.get $t1\n\
i32.const 4\ni32.gt_u\nselect\nlocal.set $t1\nlocal.get $p0\ni32.const 8\ni32.add\nlocal.get $t1\n\
i32.store\nlocal.get $t1\ni32.const {w}\ni32.mul\ncall $__alloc\nlocal.set $t2\nlocal.get $t2\n\
local.get $p0\ni32.load\nlocal.get $t0\ni32.const {w}\ni32.mul\nmemory.copy\nlocal.get $p0\n\
local.get $t2\ni32.store\nend\n{}local.get $p1\n{store}\n{LEN_FIELD}local.get $t0\ni32.const 1\n\
i32.add\ni32.store\n",
                elem_addr("local.get $t0\n", w)
            );
            f(vec!["i32", vt], None, vec!["i32", "i32", "i32"], body)
        }
        "get" => {
            let body = format!("{}{}{load}\n", bounds_check(), elem_addr(wrap_idx, w));
            f(vec!["i32", "i64"], Some(vt), vec![], body)
        }
        "set" => {
            let body = format!(
                "{}{}local.get $p2\n{store}\n",
                bounds_check(),
                elem_addr(wrap_idx, w)
            );
            f(vec!["i32", "i64", vt], None, vec![], body)
        }
        "pop" => {
            let body = format!(
                "{LEN_FIELD}i32.load\ni32.eqz\nif\nunreachable\nend\n{LEN_FIELD}{LEN_FIELD}i32.load\n\
i32.const 1\ni32.sub\nlocal.tee $t0\ni32.store\n{}{load}\n",
                elem_addr("local.get $t0\n", w)
            );
            f(vec!["i32"], Some(vt), vec!["i32"], body)
        }
        _ => return None,
    })
}

impl WasmBackend {
    /// Collect the runtime helpers this module calls; returns their result types.
    pub(super) fn plan_runtime(&mut self, mir: &MirModule) -> Vec<(String, MirType)> {
        let mut names = BTreeSet::new();
        // Every module exports an allocator and a string constructor for its host.
        names.insert("__str_new".to_string());
        for func in &mir.functions {
            for block in func.blocks.iter().flatten() {
                if let Some(MirTerminator::Call {
                    func: MirValue::Function(n) | MirValue::Global(n),
                    ..
                }) = &block.terminator
                {
                    if let Some(t) = runtime_target(n) {
                        names.insert(t);
                    }
                    if n.as_ref() == "build_sprintf" {
                        names.insert("__fmt_hex".to_string());
                        names.insert("__str_concat".to_string());
                    }
                }
            }
        }
        for func in &mir.functions {
            for stmt in func.blocks.iter().flatten().flat_map(|b| b.stmts.iter()) {
                let (op, base, elem) = match &stmt.kind {
                    MirStmtKind::Assign {
                        value: MirRValue::IndexAccess { base, elem_ty, .. },
                        ..
                    } => ("get", base, elem_ty),
                    MirStmtKind::IndexStore { base, elem_ty, .. } => ("set", base, elem_ty),
                    _ => continue,
                };
                let is_str = matches!(base, MirValue::Local(id) if func.locals.iter().any(|l| l.id == *id && is_build_string(&l.ty)));
                if is_str && op == "get" {
                    names.insert("__str_byte_at".to_string());
                }
                let is_vec = matches!(base, MirValue::Local(id) if func.locals.iter().any(|l| l.id == *id && matches!(l.ty, MirType::Vec(_))));
                if let (true, Some(sfx)) = (is_vec, vec_elem_suffix(elem)) {
                    names.insert(format!("__vec_{op}_{sfx}"));
                }
            }
        }
        if names.contains("__str_concat") || names.contains("__fmt_hex") {
            names.insert("__str_new".to_string());
        }
        self.rt = RtState::default();
        if names.is_empty() {
            return Vec::new();
        }
        self.rt.funcs.push(build_func("__alloc").expect("alloc"));
        for n in names {
            if let Some(rf) = build_func(&n) {
                self.rt.funcs.push(rf);
            }
        }
        self.rt
            .funcs
            .iter()
            .map(|rf| (rf.name.clone(), rf.ret.map(mir_of).unwrap_or(MirType::Void)))
            .collect()
    }

    /// `v[i]` read or write on a Vec handle through the runtime helpers.
    pub(super) fn gen_vec_access(
        &mut self,
        op: &str,
        base: &MirValue,
        index: &MirValue,
        value: Option<&MirRValue>,
        elem_ty: &MirType,
        func: &MirFunction,
    ) -> CodegenResult<()> {
        let Some(sfx) = vec_elem_suffix(elem_ty) else {
            return Err(CodegenError::Unsupported(format!(
                "Vec of {:?} in WASM",
                elem_ty
            )));
        };
        self.gen_value(base, func)?;
        self.gen_value(index, func)?;
        if self.emit_type(&self.infer_value_type(index, func)?) == "i32" {
            self.emit_line("i64.extend_i32_u");
        }
        if let Some(v) = value {
            self.gen_rvalue(v, func)?;
        }
        self.emit_line(&format!("call $__vec_{op}_{sfx}"));
        Ok(())
    }

    /// Push call arguments, converting to a runtime helper's parameter types.
    pub(super) fn gen_call_args(
        &mut self,
        callee: &str,
        args: &[MirValue],
        func: &MirFunction,
    ) -> CodegenResult<()> {
        let params = self
            .rt
            .funcs
            .iter()
            .find(|rf| rf.name == callee)
            .map(|rf| rf.params.clone());
        for (i, arg) in args.iter().enumerate() {
            self.gen_value(arg, func)?;
            let want = params.as_ref().and_then(|p| p.get(i)).copied();
            let have = self.emit_type(&self.infer_value_type(arg, func)?);
            match (have, want) {
                ("i32", Some("i64")) => self.emit_line("i64.extend_i32_u"),
                ("i64", Some("i32")) => self.emit_line("i32.wrap_i64"),
                _ => {}
            }
        }
        Ok(())
    }

    /// Runtime helpers as WAT text.
    pub(super) fn runtime_wat(&mut self) {
        let mut text = String::new();
        for rf in &self.rt.funcs {
            text.push_str(&format!("(func ${}", rf.name));
            for (i, p) in rf.params.iter().enumerate() {
                text.push_str(&format!(" (param $p{} {})", i, p));
            }
            if let Some(r) = rf.ret {
                text.push_str(&format!(" (result {})", r));
            }
            text.push('\n');
            for (i, l) in rf.locals.iter().enumerate() {
                text.push_str(&format!("  (local $t{} {})\n", i, l));
            }
            for line in rf.body.lines() {
                text.push_str(&format!("  {}\n", line));
            }
            text.push_str(")\n");
        }
        for line in text.lines() {
            self.emit_line(line);
        }
    }

    /// Runtime helpers as (type, body) pairs for the binary module.
    pub(super) fn runtime_binary(
        &self,
        func_index: &HashMap<String, u32>,
        global_index: &HashMap<String, u32>,
    ) -> CodegenResult<Vec<(wasm_bin::FuncType, Vec<u8>)>> {
        let mut out = Vec::new();
        for rf in &self.rt.funcs {
            let vt = |t: &&str| wasm_bin::valtype(t).map_err(CodegenError::Internal);
            let params = rf
                .params
                .iter()
                .map(vt)
                .collect::<CodegenResult<Vec<u8>>>()?;
            let results = rf.ret.iter().map(vt).collect::<CodegenResult<Vec<u8>>>()?;
            let locals = rf
                .locals
                .iter()
                .map(vt)
                .collect::<CodegenResult<Vec<u8>>>()?;
            let mut idx = HashMap::new();
            for i in 0..rf.params.len() {
                idx.insert(format!("$p{}", i), i as u32);
            }
            for i in 0..rf.locals.len() {
                idx.insert(format!("$t{}", i), (rf.params.len() + i) as u32);
            }
            let body =
                wasm_bin::assemble_body(&rf.body, &locals, &idx, func_index, global_index)
                    .map_err(|e| CodegenError::Internal(format!("runtime `{}`: {}", rf.name, e)))?;
            out.push(((params, results), body));
        }
        Ok(out)
    }
}

// Strings. A string value is an i32 handle to an 8-byte header {ptr, len}.
// Strings are immutable (concatenation and formatting build new strings), so
// sharing a handle behaves like the C backend's by-value BuildString. A null
// handle (0) reads as the empty string because addresses 0..15 stay zero.

const STR_NEW: &str = "i32.const 8\ncall $__alloc\nlocal.tee $t0\nlocal.get $p0\ni32.store\n\
local.get $t0\ni32.const 4\ni32.add\nlocal.get $p1\ni32.store\nlocal.get $t0\n";

const STR_CONCAT: &str = "local.get $p0\ni32.const 4\ni32.add\ni32.load\nlocal.set $t0\n\
local.get $p1\ni32.const 4\ni32.add\ni32.load\nlocal.set $t1\nlocal.get $t0\nlocal.get $t1\n\
i32.add\ncall $__alloc\nlocal.set $t2\nlocal.get $t2\nlocal.get $p0\ni32.load\nlocal.get $t0\n\
memory.copy\nlocal.get $t2\nlocal.get $t0\ni32.add\nlocal.get $p1\ni32.load\nlocal.get $t1\n\
memory.copy\nlocal.get $t2\nlocal.get $t0\nlocal.get $t1\ni32.add\ncall $__str_new\n";

const STR_BYTE_AT: &str = "local.get $p1\nlocal.get $p0\ni32.const 4\ni32.add\ni32.load\n\
i64.extend_i32_u\ni64.ge_u\nif\ni32.const 0\nreturn\nend\nlocal.get $p0\ni32.load\n\
local.get $p1\ni32.wrap_i64\ni32.add\ni32.load8_u\n";

/// Lower-case hex of an unsigned value, zero-padded to a minimum width.
const FMT_HEX: &str = "i32.const 0\nlocal.set $t0\nlocal.get $p0\nlocal.set $t1\nblock $c_done\n\
loop $c\nlocal.get $t0\ni32.const 1\ni32.add\nlocal.set $t0\nlocal.get $t1\ni64.const 4\n\
i64.shr_u\nlocal.tee $t1\ni64.eqz\nbr_if $c_done\nbr $c\nend\nend\nlocal.get $t0\nlocal.get $p1\n\
local.get $t0\nlocal.get $p1\ni32.gt_s\nselect\nlocal.set $t0\nlocal.get $t0\ncall $__alloc\n\
local.set $t2\nlocal.get $p0\nlocal.set $t1\nlocal.get $t0\nlocal.set $t3\nblock $f_done\n\
loop $f\nlocal.get $t3\ni32.eqz\nbr_if $f_done\nlocal.get $t3\ni32.const 1\ni32.sub\n\
local.set $t3\nlocal.get $t1\ni32.wrap_i64\ni32.const 15\ni32.and\nlocal.tee $t4\n\
i32.const 48\ni32.add\nlocal.get $t4\ni32.const 87\ni32.add\nlocal.get $t4\ni32.const 10\n\
i32.lt_u\nselect\nlocal.set $t4\nlocal.get $t2\nlocal.get $t3\ni32.add\nlocal.get $t4\n\
i32.store8\nlocal.get $t1\ni64.const 4\ni64.shr_u\nlocal.set $t1\nbr $f\nend\nend\n\
local.get $t2\nlocal.get $t0\ncall $__str_new\n";

fn build_str_func(name: &str) -> Option<RtFunc> {
    let (params, ret, locals, body): (Vec<&'static str>, _, Vec<&'static str>, &str) = match name {
        "__str_new" => (vec!["i32", "i32"], Some("i32"), vec!["i32"], STR_NEW),
        "__str_concat" => (vec!["i32", "i32"], Some("i32"), vec!["i32"; 3], STR_CONCAT),
        "__str_len" => (
            vec!["i32"],
            Some("i64"),
            vec![],
            "local.get $p0\ni32.const 4\ni32.add\ni32.load\ni64.extend_i32_u\n",
        ),
        "__str_byte_at" => (vec!["i32", "i64"], Some("i32"), vec![], STR_BYTE_AT),
        "__fmt_hex" => (
            vec!["i64", "i32"],
            Some("i32"),
            vec!["i32", "i64", "i32", "i32", "i32"],
            FMT_HEX,
        ),
        _ => return None,
    };
    Some(RtFunc {
        name: name.to_string(),
        params,
        ret,
        locals,
        body: body.to_string(),
    })
}

fn is_build_string(ty: &MirType) -> bool {
    matches!(ty, MirType::Struct(n) if n.as_ref() == "BuildString")
}

impl WasmBackend {
    /// `s[i]` on a string: the byte, or 0 past the end (as `build_string_byte_at` in C).
    pub(super) fn gen_str_index(
        &mut self,
        base: &MirValue,
        index: &MirValue,
        func: &MirFunction,
    ) -> CodegenResult<bool> {
        if !is_build_string(&self.infer_value_type(base, func)?) {
            return Ok(false);
        }
        self.gen_value(base, func)?;
        self.gen_value(index, func)?;
        if self.emit_type(&self.infer_value_type(index, func)?) == "i32" {
            self.emit_line("i64.extend_i32_u");
        }
        self.emit_line("call $__str_byte_at");
        Ok(true)
    }

    /// `format!` lowered at the call site: literal pieces and holes concatenated.
    pub(super) fn gen_sprintf(
        &mut self,
        fmt: &str,
        args: &[MirValue],
        func: &MirFunction,
    ) -> CodegenResult<()> {
        let mut pieces = vec![String::new()];
        let mut holes = Vec::new();
        let mut chars = fmt.chars().peekable();
        while let Some(c) = chars.next() {
            match c {
                '{' if chars.peek() == Some(&'{') => {
                    chars.next();
                    pieces.last_mut().unwrap().push('{');
                }
                '}' if chars.peek() == Some(&'}') => {
                    chars.next();
                    pieces.last_mut().unwrap().push('}');
                }
                '{' => {
                    let spec: String = chars.by_ref().take_while(|d| *d != '}').collect();
                    holes.push(spec);
                    pieces.push(String::new());
                }
                other => pieces.last_mut().unwrap().push(other),
            }
        }
        // The lowering hands over a C printf format ("%02x", "%s").
        if fmt.contains('%') {
            pieces = vec![String::new()];
            holes.clear();
            let mut it = fmt.chars().peekable();
            while let Some(c) = it.next() {
                if c != '%' {
                    pieces.last_mut().unwrap().push(c);
                    continue;
                }
                if it.peek() == Some(&'%') {
                    it.next();
                    pieces.last_mut().unwrap().push('%');
                    continue;
                }
                let mut width = String::new();
                while let Some(d) = it
                    .peek()
                    .copied()
                    .filter(|d| d.is_ascii_digit() || *d == '-')
                {
                    width.push(d);
                    it.next();
                }
                while matches!(it.peek(), Some('l' | 'h' | 'z' | 'j')) {
                    it.next();
                }
                holes.push(match it.next().unwrap_or(' ') {
                    's' => String::new(),
                    'x' => format!(":{}x", width),
                    other => format!("%{width}{other}"),
                });
                pieces.push(String::new());
            }
        }

        if holes.len() != args.len() {
            return Err(CodegenError::Unsupported(format!(
                "format `{fmt}` does not match its argument count"
            )));
        }
        let first = self.lit_string(pieces[0].as_bytes());
        self.emit_line(&format!("i32.const {}", first));
        for (i, spec) in holes.iter().enumerate() {
            let arg = &args[i];
            let ty = self.infer_value_type(arg, func)?;
            let hex = spec
                .strip_prefix(':')
                .and_then(|s| s.strip_suffix('x'))
                .filter(|_| matches!(ty, MirType::Int(..)));
            if spec.is_empty() && is_build_string(&ty) {
                self.gen_value(arg, func)?;
            } else if let Some(width) = hex {
                let width: u32 = width.trim_start_matches('0').parse().unwrap_or(0);
                self.gen_value(arg, func)?;
                if self.emit_type(&ty) == "i32" {
                    self.emit_line("i64.extend_i32_u");
                }
                self.emit_line(&format!("i32.const {}", width));
                self.emit_line("call $__fmt_hex");
            } else {
                return Err(CodegenError::Unsupported(format!(
                    "format hole `{{{spec}}}` for a {:?} value in WASM",
                    ty
                )));
            }
            self.emit_line("call $__str_concat");
            if !pieces[i + 1].is_empty() {
                let lit = self.lit_string(pieces[i + 1].as_bytes());
                self.emit_line(&format!("i32.const {}", lit));
                self.emit_line("call $__str_concat");
            }
        }
        Ok(())
    }
}