lamina-codegen 0.2.0

Codegen utilities for Lamina (register allocation, ABI, frame management)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
//! Common ABI trait and utilities for code generation backends.
//!
//! A trait that all ABI implementations must follow,
//! reducing code duplication and giving a consistent interface.
//!
//! # Application Binary Interface (ABI) Overview
//!
//! Lamina uses platform C ABIs for function calls. The ABI implementation is
//! abstracted through the `Abi` trait, which gives a consistent interface
//! across all backends.
//!
//! ## Common ABI Contract
//!
//! ### Function Name Mangling
//!
//! All backends apply platform-specific symbol mangling:
//! - **macOS**: Functions are prefixed with underscore (e.g., `main` → `_main`)
//! - **Linux/Windows**: Functions use their original names (e.g., `main` → `main`)
//!
//! The `mangle_function_name()` method handles this automatically.
//!
//! ### Argument Passing
//!
//! - Arguments are passed using the platform C ABI register order
//! - Overflow arguments (beyond register capacity) are spilled to the stack
//! - Integer arguments use 64-bit slots, even for narrower integer types (i8, i16, i32)
//! - Floating-point arguments follow platform-specific rules
//!
//! **Example: Function call with 3 arguments (RISC-V)**
//! ```text
//! # Arguments: a0=arg1, a1=arg2, a2=arg3
//! mv a0, t0        # Load arg1 to a0
//! mv a1, t1        # Load arg2 to a1
//! mv a2, t2        # Load arg3 to a2
//! call my_function # Call function
//! ```
//!
//! **Example: Function call with 10 arguments (x86_64 System V)**
//! ```text
//! # First 6 args in registers: rdi, rsi, rdx, rcx, r8, r9
//! # Remaining 4 args on stack (16-byte aligned)
//! mov %rdi, %rax   # arg1
//! mov %rsi, %rbx   # arg2
//! # ... args 3-6 in rdx, rcx, r8, r9
//! push %r10        # arg7 on stack
//! push %r11        # arg8 on stack
//! push %r12        # arg9 on stack
//! push %r13        # arg10 on stack
//! call my_function
//! add $32, %rsp    # Clean up stack
//! ```
//!
//! ### Return Values
//!
//! - Integer return values use the C ABI integer return register
//! - Floating-point return values use the FP return register (if applicable)
//! - Void functions return nothing
//!
//! **Example: Return value handling**
//! ```text
//! # RISC-V: return value in a0 (integer) or fa0 (float)
//! call my_function
//! mv t0, a0        # Save integer return value
//!
//! # x86_64: return value in rax (integer) or xmm0 (float)
//! call my_function
//! mov %rax, %rbx   # Save integer return value
//! ```
//!
//! ### Builtin Functions
//!
//! Builtin functions can be overridden via the `LAMINA_BUILTINS` environment variable:
//!
//! ```bash
//! LAMINA_BUILTINS="malloc=jemalloc_malloc,dealloc=jemalloc_free"
//! ```
//!
//! Every runtime helper the compiler calls is a [`RuntimeSymbol`]. Keys are the
//! C names (`malloc`, `free`, `exit`, `memcpy`, `memmove`, `memset`), plus the
//! legacy alias `dealloc` (free).
//! The compiler-rt routines for 128-bit integers (`__divti3`, `__floattidf`, ...)
//! are keys too, so an embedder can supply them. Platform decoration (`_free`
//! on macOS) is applied to the override as well.
//!
//! ## Backend-Specific ABIs
//!
//! See the documentation in each backend's ABI module:
//! - `x86_64::abi` - System V AMD64 and Microsoft x64
//! - `aarch64::abi` - AAPCS64
//! - `riscv::abi` - RISC-V calling convention
//! - `wasm::abi` - WebAssembly stack-based calling

use crate::target_support::os_uses_macho;
use lamina_platform::TargetOperatingSystem;
use std::{collections::HashMap, env, error::Error, fmt};

/// Runtime helpers the compiler calls by name.
///
/// Each variant names a C symbol. Emission sites use the variant, never a string
/// literal, so `LAMINA_BUILTINS` can retarget every one of them.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RuntimeSymbol {
    Malloc,
    Free,
    Exit,
    Memcpy,
    Memmove,
    Memset,
    /// compiler-rt `__divti3`: 128-bit integer arithmetic and conversion, called by i128 lowering.
    Divti3,
    /// compiler-rt `__udivti3`: 128-bit integer arithmetic and conversion, called by i128 lowering.
    Udivti3,
    /// compiler-rt `__modti3`: 128-bit integer arithmetic and conversion, called by i128 lowering.
    Modti3,
    /// compiler-rt `__umodti3`: 128-bit integer arithmetic and conversion, called by i128 lowering.
    Umodti3,
    /// compiler-rt `__divdi3`: 64-bit signed division, called when a 32-bit target splits an i64.
    Divdi3,
    /// compiler-rt `__udivdi3`: 64-bit unsigned division, called when a 32-bit target splits an i64.
    Udivdi3,
    /// compiler-rt `__moddi3`: 64-bit signed remainder, called when a 32-bit target splits an i64.
    Moddi3,
    /// compiler-rt `__umoddi3`: 64-bit unsigned remainder, called when a 32-bit target splits an i64.
    Umoddi3,
    /// compiler-rt `__floatdidf`: 64-bit integer to double, called when a 32-bit target splits an i64.
    Floatdidf,
    /// compiler-rt `__floatundidf`: 64-bit unsigned to double, called when a 32-bit target splits an i64.
    Floatundidf,
    /// compiler-rt `__floatdisf`: 64-bit integer to float, called when a 32-bit target splits an i64.
    Floatdisf,
    /// compiler-rt `__floatundisf`: 64-bit unsigned to float, called when a 32-bit target splits an i64.
    Floatundisf,
    /// compiler-rt `__fixdfdi`: double to 64-bit integer, called when a 32-bit target splits an i64.
    Fixdfdi,
    /// compiler-rt `__fixunsdfdi`: double to 64-bit unsigned, called when a 32-bit target splits an i64.
    Fixunsdfdi,
    /// compiler-rt `__fixsfdi`: float to 64-bit integer, called when a 32-bit target splits an i64.
    Fixsfdi,
    /// compiler-rt `__fixunssfdi`: float to 64-bit unsigned, called when a 32-bit target splits an i64.
    Fixunssfdi,
    /// compiler-rt `__floattidf`: 128-bit integer arithmetic and conversion, called by i128 lowering.
    Floattidf,
    /// compiler-rt `__floatuntidf`: 128-bit integer arithmetic and conversion, called by i128 lowering.
    Floatuntidf,
    /// compiler-rt `__fixdfti`: 128-bit integer arithmetic and conversion, called by i128 lowering.
    Fixdfti,
    /// compiler-rt `__fixunsdfti`: 128-bit integer arithmetic and conversion, called by i128 lowering.
    Fixunsdfti,
    /// compiler-rt `__floattisf`: 128-bit integer arithmetic and conversion, called by i128 lowering.
    Floattisf,
    /// compiler-rt `__floatuntisf`: 128-bit integer arithmetic and conversion, called by i128 lowering.
    Floatuntisf,
    /// compiler-rt `__fixsfti`: 128-bit integer arithmetic and conversion, called by i128 lowering.
    Fixsfti,
    /// compiler-rt `__fixunssfti`: 128-bit integer arithmetic and conversion, called by i128 lowering.
    Fixunssfti,
}

impl RuntimeSymbol {
    pub const ALL: [RuntimeSymbol; 30] = [
        RuntimeSymbol::Malloc,
        RuntimeSymbol::Free,
        RuntimeSymbol::Exit,
        RuntimeSymbol::Memcpy,
        RuntimeSymbol::Memmove,
        RuntimeSymbol::Memset,
        RuntimeSymbol::Divti3,
        RuntimeSymbol::Udivti3,
        RuntimeSymbol::Modti3,
        RuntimeSymbol::Umodti3,
        RuntimeSymbol::Divdi3,
        RuntimeSymbol::Udivdi3,
        RuntimeSymbol::Moddi3,
        RuntimeSymbol::Umoddi3,
        RuntimeSymbol::Floatdidf,
        RuntimeSymbol::Floatundidf,
        RuntimeSymbol::Floatdisf,
        RuntimeSymbol::Floatundisf,
        RuntimeSymbol::Fixdfdi,
        RuntimeSymbol::Fixunsdfdi,
        RuntimeSymbol::Fixsfdi,
        RuntimeSymbol::Fixunssfdi,
        RuntimeSymbol::Floattidf,
        RuntimeSymbol::Floatuntidf,
        RuntimeSymbol::Fixdfti,
        RuntimeSymbol::Fixunsdfti,
        RuntimeSymbol::Floattisf,
        RuntimeSymbol::Floatuntisf,
        RuntimeSymbol::Fixsfti,
        RuntimeSymbol::Fixunssfti,
    ];

    /// The undecorated C symbol name.
    pub const fn c_name(self) -> &'static str {
        match self {
            RuntimeSymbol::Malloc => "malloc",
            RuntimeSymbol::Free => "free",
            RuntimeSymbol::Exit => "exit",
            RuntimeSymbol::Memcpy => "memcpy",
            RuntimeSymbol::Memmove => "memmove",
            RuntimeSymbol::Memset => "memset",
            RuntimeSymbol::Divti3 => "__divti3",
            RuntimeSymbol::Udivti3 => "__udivti3",
            RuntimeSymbol::Modti3 => "__modti3",
            RuntimeSymbol::Umodti3 => "__umodti3",
            RuntimeSymbol::Divdi3 => "__divdi3",
            RuntimeSymbol::Udivdi3 => "__udivdi3",
            RuntimeSymbol::Moddi3 => "__moddi3",
            RuntimeSymbol::Umoddi3 => "__umoddi3",
            RuntimeSymbol::Floatdidf => "__floatdidf",
            RuntimeSymbol::Floatundidf => "__floatundidf",
            RuntimeSymbol::Floatdisf => "__floatdisf",
            RuntimeSymbol::Floatundisf => "__floatundisf",
            RuntimeSymbol::Fixdfdi => "__fixdfdi",
            RuntimeSymbol::Fixunsdfdi => "__fixunsdfdi",
            RuntimeSymbol::Fixsfdi => "__fixsfdi",
            RuntimeSymbol::Fixunssfdi => "__fixunssfdi",
            RuntimeSymbol::Floattidf => "__floattidf",
            RuntimeSymbol::Floatuntidf => "__floatuntidf",
            RuntimeSymbol::Fixdfti => "__fixdfti",
            RuntimeSymbol::Fixunsdfti => "__fixunsdfti",
            RuntimeSymbol::Floattisf => "__floattisf",
            RuntimeSymbol::Floatuntisf => "__floatuntisf",
            RuntimeSymbol::Fixsfti => "__fixsfti",
            RuntimeSymbol::Fixunssfti => "__fixunssfti",
        }
    }

    /// Looks up a symbol by its C name, as MIR call sites spell it.
    pub fn from_c_name(name: &str) -> Option<Self> {
        Self::ALL.into_iter().find(|symbol| symbol.c_name() == name)
    }

    /// Looks up a symbol by a `LAMINA_BUILTINS` key or builtin name.
    ///
    /// Accepts the C name plus the legacy key `dealloc` (free).
    pub fn from_builtin_name(name: &str) -> Option<Self> {
        match name {
            "dealloc" => Some(RuntimeSymbol::Free),
            _ => Self::from_c_name(name),
        }
    }
}

/// Resolves runtime helper names to the symbols the emitted code must reference.
///
/// Overrides name the C symbol. Platform decoration (the Mach-O leading
/// underscore) is applied on top, the same way it is for every other C symbol.
pub struct BuiltinLibrary {
    target_os: TargetOperatingSystem,
    overrides: HashMap<RuntimeSymbol, String>,
}

impl BuiltinLibrary {
    pub fn new(
        target_os: TargetOperatingSystem,
        overrides: HashMap<RuntimeSymbol, String>,
    ) -> Self {
        Self {
            target_os,
            overrides,
        }
    }

    /// The library `LAMINA_BUILTINS` describes, or why that value could not be read.
    pub fn from_env(target_os: TargetOperatingSystem) -> Result<Self, BuiltinOverrideError> {
        Ok(Self::new(target_os, builtin_overrides_from_env()?))
    }

    /// [`Self::from_env`] for callers with nowhere to put the error.
    ///
    /// A `LAMINA_BUILTINS` the compiler cannot read is refused by the codegen entry
    /// point before any backend runs, so reaching this with an unreadable value means
    /// the caller skipped that entry point; it then behaves as if nothing was set.
    pub fn from_env_or_unset(target_os: TargetOperatingSystem) -> Self {
        Self::new(target_os, builtin_overrides_from_env().unwrap_or_default())
    }

    pub fn has_overrides(&self) -> bool {
        !self.overrides.is_empty()
    }

    /// The undecorated C name for a symbol. MIR call sites carry this name and the
    /// backend's function mangling adds any platform prefix.
    pub fn c_name(&self, symbol: RuntimeSymbol) -> &str {
        self.overrides
            .get(&symbol)
            .map_or(symbol.c_name(), String::as_str)
    }

    /// The final symbol to reference from directly emitted code.
    pub fn symbol(&self, symbol: RuntimeSymbol) -> String {
        decorate_symbol(self.target_os, self.c_name(symbol))
    }

    pub fn resolve(&self, name: &str) -> Option<String> {
        RuntimeSymbol::from_builtin_name(name).map(|symbol| self.symbol(symbol))
    }
}

fn decorate_symbol(target_os: TargetOperatingSystem, name: &str) -> String {
    if os_uses_macho(target_os) {
        format!("_{name}")
    } else {
        name.to_string()
    }
}

/// Why a `LAMINA_BUILTINS` value could not be read.
///
/// An override that cannot be understood is reported rather than dropped: a typo in
/// the variable would otherwise leave the default symbol in the output, with nothing
/// said about it.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum BuiltinOverrideError {
    /// An entry with no `=`, so it names neither a builtin nor a replacement.
    MalformedEntry(String),
    /// An entry whose left side is not a runtime helper this compiler calls.
    UnknownBuiltin(String),
    /// An entry with an empty builtin name or an empty replacement symbol.
    EmptySide(String),
    /// Two entries naming the same builtin, with different replacements.
    Conflict {
        builtin: &'static str,
        first: String,
        second: String,
    },
}

impl fmt::Display for BuiltinOverrideError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            BuiltinOverrideError::MalformedEntry(entry) => {
                write!(f, "LAMINA_BUILTINS entry `{entry}` is not `name=symbol`")
            }
            BuiltinOverrideError::UnknownBuiltin(name) => write!(
                f,
                "LAMINA_BUILTINS names `{name}`, which is not a runtime helper this compiler calls; the names are {}",
                builtin_name_list()
            ),
            BuiltinOverrideError::EmptySide(entry) => {
                write!(f, "LAMINA_BUILTINS entry `{entry}` leaves one side empty")
            }
            BuiltinOverrideError::Conflict {
                builtin,
                first,
                second,
            } => write!(
                f,
                "LAMINA_BUILTINS sets `{builtin}` twice, to `{first}` and to `{second}`"
            ),
        }
    }
}

impl Error for BuiltinOverrideError {}

fn builtin_name_list() -> String {
    let mut names: Vec<&str> = RuntimeSymbol::ALL
        .into_iter()
        .map(RuntimeSymbol::c_name)
        .collect();
    names.push("dealloc");
    names.sort_unstable();
    names.join(", ")
}

/// Parses `name=symbol,name=symbol`.
///
/// Every entry must name a runtime helper and a replacement symbol. An entry that does
/// not is an error, not a silent omission: it reaches the real codegen path, and a
/// dropped override would change the emitted symbols without saying so.
pub fn parse_builtin_overrides(
    value: &str,
) -> Result<HashMap<RuntimeSymbol, String>, BuiltinOverrideError> {
    let mut overrides: HashMap<RuntimeSymbol, String> = HashMap::new();
    for entry in value.split(',') {
        if entry.trim().is_empty() {
            continue;
        }
        let Some((name, symbol)) = entry.split_once('=') else {
            return Err(BuiltinOverrideError::MalformedEntry(
                entry.trim().to_owned(),
            ));
        };
        let name = name.trim();
        let symbol = symbol.trim();
        if name.is_empty() || symbol.is_empty() {
            return Err(BuiltinOverrideError::EmptySide(entry.trim().to_owned()));
        }
        let Some(runtime) = RuntimeSymbol::from_builtin_name(name) else {
            return Err(BuiltinOverrideError::UnknownBuiltin(name.to_owned()));
        };
        if let Some(first) = overrides.get(&runtime)
            && first != symbol
        {
            return Err(BuiltinOverrideError::Conflict {
                builtin: runtime.c_name(),
                first: first.clone(),
                second: symbol.to_owned(),
            });
        }
        overrides.insert(runtime, symbol.to_owned());
    }
    Ok(overrides)
}

fn builtin_overrides_from_env() -> Result<HashMap<RuntimeSymbol, String>, BuiltinOverrideError> {
    match env::var("LAMINA_BUILTINS") {
        Ok(value) => parse_builtin_overrides(&value),
        Err(_) => Ok(HashMap::new()),
    }
}

/// Trait defining the common interface for all ABI implementations.
///
/// This contract covers name mangling, builtin symbol mapping, and the
/// minimal calling convention expectations shared by MIR backends.
///
/// ## Calling Convention Assumptions
/// - Arguments are passed using the platform C ABI register order, with
///   overflow arguments spilled to the stack.
/// - Integer arguments use 64-bit slots, even for narrower integer types.
/// - Return values use the C ABI integer return register when present.
///
/// ## Builtins
/// - Builtins are resolved by `call_stub`, which can be overridden with
///   the `LAMINA_BUILTINS` environment variable.
/// - The builtin map recognizes every [`RuntimeSymbol`].
///
/// ## Naming
/// - Backends must apply platform-specific symbol mangling, such as
///   the underscore prefix on macOS.
pub trait Abi {
    /// Returns the target operating system for this ABI instance.
    fn target_os(&self) -> TargetOperatingSystem;

    /// Returns the mangled function name with platform-specific prefix.
    ///
    /// This method handles platform-specific symbol naming conventions,
    /// such as the underscore prefix on macOS.
    fn mangle_function_name(&self, name: &str) -> String;

    fn builtin_library(&self) -> BuiltinLibrary {
        BuiltinLibrary::from_env_or_unset(self.target_os())
    }

    /// Maps well-known intrinsic/runtime names to platform symbol stubs.
    ///
    /// Returns `None` if the name is not a known intrinsic that needs
    /// special handling. This lets backends map internal names
    /// (like "dealloc") to platform-specific symbols (like "_free" on macOS).
    ///
    /// Default implementation returns `None` for all names, meaning
    /// no special mapping is needed.
    fn call_stub(&self, name: &str) -> Option<String> {
        self.builtin_library().resolve(name)
    }
}

/// Helper function to mangle function names for macOS (adds underscore prefix).
///
/// This is a common pattern used by multiple backends, so we provide
/// it as a shared utility function.
pub fn mangle_macos_name(name: &str) -> String {
    if name == "main" {
        "_main".to_string()
    } else {
        format!("_{name}")
    }
}

/// Helper function to get the platform-specific printf symbol name.
///
/// Returns "_printf" on macOS, "printf" on other platforms.
pub fn get_printf_symbol(target_os: TargetOperatingSystem) -> &'static str {
    match target_os {
        os if os_uses_macho(os) => "_printf",
        _ => "printf",
    }
}

/// Helper function to get the platform-specific malloc symbol name.
///
/// Returns "_malloc" on macOS, "malloc" on other platforms.
pub fn get_malloc_symbol(target_os: TargetOperatingSystem) -> &'static str {
    match target_os {
        os if os_uses_macho(os) => "_malloc",
        _ => "malloc",
    }
}

/// Helper function to get the platform-specific free symbol name.
///
/// Returns "_free" on macOS, "free" on other platforms.
pub fn get_free_symbol(target_os: TargetOperatingSystem) -> &'static str {
    match target_os {
        os if os_uses_macho(os) => "_free",
        _ => "free",
    }
}

/// Helper function to create a common call_stub implementation.
///
/// Resolves a builtin name through the environment-configured [`BuiltinLibrary`].
/// Backends can use this to reduce duplication in their `call_stub` implementations.
pub fn common_call_stub(name: &str, target_os: TargetOperatingSystem) -> Option<String> {
    BuiltinLibrary::from_env_or_unset(target_os).resolve(name)
}

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

    #[test]
    fn test_mangle_macos_name() {
        assert_eq!(mangle_macos_name("main"), "_main");
        assert_eq!(mangle_macos_name("foo"), "_foo");
        assert_eq!(mangle_macos_name("my_function"), "_my_function");
    }

    #[test]
    fn test_get_printf_symbol() {
        assert_eq!(get_printf_symbol(TargetOperatingSystem::MacOS), "_printf");
        assert_eq!(get_printf_symbol(TargetOperatingSystem::IOS), "_printf");
        assert_eq!(
            get_printf_symbol(TargetOperatingSystem::VisionOS),
            "_printf"
        );
        assert_eq!(get_printf_symbol(TargetOperatingSystem::Linux), "printf");
        assert_eq!(get_printf_symbol(TargetOperatingSystem::Windows), "printf");
    }

    #[test]
    fn test_get_malloc_symbol() {
        assert_eq!(get_malloc_symbol(TargetOperatingSystem::MacOS), "_malloc");
        assert_eq!(get_malloc_symbol(TargetOperatingSystem::IOS), "_malloc");
        assert_eq!(get_malloc_symbol(TargetOperatingSystem::Linux), "malloc");
        assert_eq!(get_malloc_symbol(TargetOperatingSystem::Windows), "malloc");
    }

    #[test]
    fn test_get_free_symbol() {
        assert_eq!(get_free_symbol(TargetOperatingSystem::MacOS), "_free");
        assert_eq!(get_free_symbol(TargetOperatingSystem::TvOS), "_free");
        assert_eq!(get_free_symbol(TargetOperatingSystem::Linux), "free");
        assert_eq!(get_free_symbol(TargetOperatingSystem::Windows), "free");
    }

    #[test]
    fn test_builtin_library_default_symbols() {
        let lib_macos = BuiltinLibrary::from_env_or_unset(TargetOperatingSystem::MacOS);
        assert_eq!(lib_macos.resolve("malloc"), Some("_malloc".to_string()));
        assert_eq!(lib_macos.resolve("dealloc"), Some("_free".to_string()));

        let lib_linux = BuiltinLibrary::from_env_or_unset(TargetOperatingSystem::Linux);
        assert_eq!(lib_linux.resolve("malloc"), Some("malloc".to_string()));
        assert_eq!(lib_linux.resolve("dealloc"), Some("free".to_string()));
    }

    #[test]
    fn test_builtin_library_unknown_symbol() {
        let lib = BuiltinLibrary::from_env_or_unset(TargetOperatingSystem::Linux);
        assert_eq!(lib.resolve("unknown_function"), None);
    }

    #[test]
    fn test_common_call_stub() {
        assert_eq!(
            common_call_stub("malloc", TargetOperatingSystem::MacOS),
            Some("_malloc".to_string())
        );
        assert_eq!(
            common_call_stub("dealloc", TargetOperatingSystem::Linux),
            Some("free".to_string())
        );
        assert_eq!(
            common_call_stub("unknown", TargetOperatingSystem::Linux),
            None
        );
    }
}

#[cfg(test)]
mod runtime_symbol_tests {
    use super::*;

    fn all_overridden(os: TargetOperatingSystem) -> BuiltinLibrary {
        let overrides = RuntimeSymbol::ALL
            .into_iter()
            .map(|symbol| (symbol, format!("k_{}", symbol.c_name())))
            .collect();
        BuiltinLibrary::new(os, overrides)
    }

    #[test]
    fn default_symbols_keep_c_names_and_platform_decoration() {
        let linux = BuiltinLibrary::new(TargetOperatingSystem::Linux, HashMap::new());
        let macos = BuiltinLibrary::new(TargetOperatingSystem::MacOS, HashMap::new());
        assert!(!linux.has_overrides());
        for symbol in RuntimeSymbol::ALL {
            assert_eq!(linux.c_name(symbol), symbol.c_name());
            assert_eq!(linux.symbol(symbol), symbol.c_name());
            assert_eq!(macos.c_name(symbol), symbol.c_name());
            assert_eq!(macos.symbol(symbol), format!("_{}", symbol.c_name()));
        }
    }

    #[test]
    fn overrides_replace_every_symbol() {
        for os in [TargetOperatingSystem::Linux, TargetOperatingSystem::MacOS] {
            let lib = all_overridden(os);
            assert!(lib.has_overrides());
            for symbol in RuntimeSymbol::ALL {
                let expected_c = format!("k_{}", symbol.c_name());
                assert_eq!(lib.c_name(symbol), expected_c);
                assert_eq!(
                    lib.resolve(symbol.c_name()),
                    Some(decorate_symbol(os, &expected_c))
                );
            }
        }
    }

    #[test]
    fn resolve_maps_legacy_builtin_keys() {
        let lib = BuiltinLibrary::new(
            TargetOperatingSystem::Linux,
            parse_builtin_overrides("dealloc=k_free").expect("a known builtin parses"),
        );
        assert_eq!(lib.resolve("dealloc"), Some("k_free".to_string()));
        assert_eq!(lib.resolve("free"), Some("k_free".to_string()));
        assert_eq!(lib.resolve("write"), None);
    }

    #[test]
    fn parse_builtin_overrides_accepts_padded_known_entries() {
        let parsed =
            parse_builtin_overrides(" malloc = k_alloc ,exit=k_exit").expect("both are builtins");
        assert_eq!(parsed.len(), 2);
        assert_eq!(
            parsed.get(&RuntimeSymbol::Malloc).map(String::as_str),
            Some("k_alloc")
        );
        assert_eq!(
            parsed.get(&RuntimeSymbol::Exit).map(String::as_str),
            Some("k_exit")
        );
    }

    #[test]
    fn parse_builtin_overrides_refuses_what_it_cannot_apply() {
        assert_eq!(
            parse_builtin_overrides("malloc=k_alloc,bogus=x"),
            Err(BuiltinOverrideError::UnknownBuiltin("bogus".to_owned()))
        );
        assert_eq!(
            parse_builtin_overrides("memset="),
            Err(BuiltinOverrideError::EmptySide("memset=".to_owned()))
        );
        assert_eq!(
            parse_builtin_overrides("=y"),
            Err(BuiltinOverrideError::EmptySide("=y".to_owned()))
        );
        assert_eq!(
            parse_builtin_overrides("malloc"),
            Err(BuiltinOverrideError::MalformedEntry("malloc".to_owned()))
        );
        assert_eq!(
            parse_builtin_overrides("free=a,dealloc=b"),
            Err(BuiltinOverrideError::Conflict {
                builtin: "free",
                first: "a".to_owned(),
                second: "b".to_owned(),
            })
        );
        assert!(parse_builtin_overrides("free=a,dealloc=a").is_ok());
        assert!(parse_builtin_overrides("").is_ok());
    }

    #[test]
    fn unknown_builtin_message_lists_the_names() {
        let message = BuiltinOverrideError::UnknownBuiltin("bogus".to_owned()).to_string();
        assert!(message.contains("bogus"), "{message}");
        assert!(message.contains("malloc"), "{message}");
        assert!(message.contains("__divti3"), "{message}");
    }

    #[test]
    fn from_c_name_round_trips_every_symbol() {
        for symbol in RuntimeSymbol::ALL {
            assert_eq!(RuntimeSymbol::from_c_name(symbol.c_name()), Some(symbol));
            assert_eq!(
                RuntimeSymbol::from_builtin_name(symbol.c_name()),
                Some(symbol)
            );
        }
        assert_eq!(RuntimeSymbol::from_c_name("print"), None);
    }
}