hypothalamus 0.4.0

An optimizing Brainfuck AOT compiler with an LLVM IR backend
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
//! Game Boy Advance ROM image builder.

use crate::driver::{CompilerConfig, DriverError};
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::{SystemTime, UNIX_EPOCH};

/// Size of the GBA cartridge header.
pub const HEADER_SIZE: usize = 0xC0;

/// Default GBA ROM title written into the header.
pub const ROM_TITLE: &[u8; 12] = b"HYPOTHALAM  ";

/// Default GBA game code written into the header.
pub const GAME_CODE: &[u8; 4] = b"HYBF";

/// Default GBA maker code written into the header.
pub const MAKER_CODE: &[u8; 2] = b"00";

const DEVKITARM_BIN: &str = "/opt/devkitpro/devkitARM/bin";
const GBA_TOOL_HINT: &str = "Install devkitARM or pass --gba-gcc /path/to/arm-none-eabi-gcc and --gba-objcopy /path/to/arm-none-eabi-objcopy.";

const NINTENDO_LOGO: [u8; 156] = [
    0x24, 0xFF, 0xAE, 0x51, 0x69, 0x9A, 0xA2, 0x21, 0x3D, 0x84, 0x82, 0x0A, 0x84, 0xE4, 0x09, 0xAD,
    0x11, 0x24, 0x8B, 0x98, 0xC0, 0x81, 0x7F, 0x21, 0xA3, 0x52, 0xBE, 0x19, 0x93, 0x09, 0xCE, 0x20,
    0x10, 0x46, 0x4A, 0x4A, 0xF8, 0x27, 0x31, 0xEC, 0x58, 0xC7, 0xE8, 0x33, 0x82, 0xE3, 0xCE, 0xBF,
    0x85, 0xF4, 0xDF, 0x94, 0xCE, 0x4B, 0x09, 0xC1, 0x94, 0x56, 0x8A, 0xC0, 0x13, 0x72, 0xA7, 0xFC,
    0x9F, 0x84, 0x4D, 0x73, 0xA3, 0xCA, 0x9A, 0x61, 0x58, 0x97, 0xA3, 0x27, 0xFC, 0x03, 0x98, 0x76,
    0x23, 0x1D, 0xC7, 0x61, 0x03, 0x04, 0xAE, 0x56, 0xBF, 0x38, 0x84, 0x00, 0x40, 0xA7, 0x0E, 0xFD,
    0xFF, 0x52, 0xFE, 0x03, 0x6F, 0x95, 0x30, 0xF1, 0x97, 0xFB, 0xC0, 0x85, 0x60, 0xD6, 0x80, 0x25,
    0xA9, 0x63, 0xBE, 0x03, 0x01, 0x4E, 0x38, 0xE2, 0xF9, 0xA2, 0x34, 0xFF, 0xBB, 0x3E, 0x03, 0x44,
    0x78, 0x00, 0x90, 0xCB, 0x88, 0x11, 0x3A, 0x94, 0x65, 0xC0, 0x7C, 0x63, 0x87, 0xF0, 0x3C, 0xAF,
    0xD6, 0x25, 0xE4, 0x8B, 0x38, 0x0A, 0xAC, 0x72, 0x21, 0xD4, 0xF8, 0x07,
];

/// Build a complete `.gba` ROM image from generated LLVM IR.
pub fn build_image(
    config: &CompilerConfig,
    module: &str,
    output: &Path,
) -> Result<(), DriverError> {
    let temp_dir = temporary_dir();
    fs::create_dir_all(&temp_dir).map_err(|source| DriverError::WriteFile {
        path: temp_dir.clone(),
        source,
    })?;

    let result = build_image_in_dir(config, module, output, &temp_dir);
    let _ = fs::remove_dir_all(&temp_dir);
    result
}

/// Patch the 192-byte GBA ROM header at the start of `rom`.
pub fn patch_header(rom: &mut Vec<u8>) {
    if rom.len() < HEADER_SIZE {
        rom.resize(HEADER_SIZE, 0);
    }

    rom[..HEADER_SIZE].fill(0);
    rom[0..4].copy_from_slice(&0xEA00002E_u32.to_le_bytes());
    rom[0x04..0xA0].copy_from_slice(&NINTENDO_LOGO);
    rom[0xA0..0xAC].copy_from_slice(ROM_TITLE);
    rom[0xAC..0xB0].copy_from_slice(GAME_CODE);
    rom[0xB0..0xB2].copy_from_slice(MAKER_CODE);
    rom[0xB2] = 0x96;
    rom[0xBD] = header_checksum(rom);
}

/// Return true when `rom` has the header fields Hypothalamus writes.
pub fn has_valid_header(rom: &[u8]) -> bool {
    rom.len() >= HEADER_SIZE
        && rom[0..4] == 0xEA00002E_u32.to_le_bytes()
        && rom[0x04..0xA0] == NINTENDO_LOGO
        && rom[0xA0..0xAC] == ROM_TITLE[..]
        && rom[0xAC..0xB0] == GAME_CODE[..]
        && rom[0xB0..0xB2] == MAKER_CODE[..]
        && rom[0xB2] == 0x96
        && rom[0xBD] == header_checksum(rom)
}

/// Compute the GBA header complement checksum byte.
pub fn header_checksum(rom: &[u8]) -> u8 {
    let sum = rom[0xA0..=0xBC]
        .iter()
        .fold(0_u8, |sum, byte| sum.wrapping_add(*byte));
    0_u8.wrapping_sub(sum).wrapping_sub(0x19)
}

/// Locate a GBA tool using an explicit override, `PATH`, then devkitPro.
pub fn find_gba_tool(override_path: Option<&Path>, name: &'static str) -> Option<PathBuf> {
    if let Some(path) = override_path {
        return Some(path.to_path_buf());
    }

    find_on_path(name).or_else(|| {
        let path = Path::new(DEVKITARM_BIN).join(name);
        path.is_file().then_some(path)
    })
}

fn build_image_in_dir(
    config: &CompilerConfig,
    module: &str,
    output: &Path,
    temp_dir: &Path,
) -> Result<(), DriverError> {
    let gcc = find_gba_tool(config.gba_gcc.as_deref(), "arm-none-eabi-gcc").ok_or(
        DriverError::ToolNotFound {
            tool: "arm-none-eabi-gcc",
            hint: GBA_TOOL_HINT,
        },
    )?;
    let objcopy = find_gba_tool(config.gba_objcopy.as_deref(), "arm-none-eabi-objcopy").ok_or(
        DriverError::ToolNotFound {
            tool: "arm-none-eabi-objcopy",
            hint: GBA_TOOL_HINT,
        },
    )?;

    let ll_path = if config.keep_ll {
        output.with_extension("ll")
    } else {
        temp_dir.join("program.ll")
    };
    write_file(&ll_path, module.as_bytes())?;

    let bf_object = temp_dir.join("program.o");
    compile_bf_object(config, &ll_path, &bf_object)?;

    let startup_source = temp_dir.join("gba_startup.S");
    let runtime_source = temp_dir.join("gba_runtime.c");
    let linker_script = temp_dir.join("gba.ld");
    write_file(&startup_source, STARTUP_ASM.as_bytes())?;
    write_file(&runtime_source, RUNTIME_C.as_bytes())?;
    write_file(&linker_script, LINKER_SCRIPT.as_bytes())?;

    let startup_object = temp_dir.join("gba_startup.o");
    let runtime_object = temp_dir.join("gba_runtime.o");
    let elf_path = temp_dir.join("program.elf");
    let raw_path = temp_dir.join("program.gba.raw");

    compile_startup(&gcc, &startup_source, &startup_object)?;
    compile_runtime(&gcc, &runtime_source, &runtime_object)?;
    link_elf(
        &gcc,
        &linker_script,
        &startup_object,
        &runtime_object,
        &bf_object,
        &elf_path,
    )?;
    objcopy_rom(&objcopy, &elf_path, &raw_path)?;

    let mut rom = fs::read(&raw_path).map_err(|source| DriverError::ReadSource {
        path: raw_path,
        source,
    })?;
    patch_header(&mut rom);
    write_file(output, &rom)
}

fn compile_bf_object(
    config: &CompilerConfig,
    ll_path: &Path,
    output: &Path,
) -> Result<(), DriverError> {
    let mut command = Command::new(&config.clang);
    command.arg("-Wno-override-module");
    command.arg(config.opt_level.clang_arg());
    command.arg("-ffreestanding");
    command.arg("-fno-builtin");
    command.arg("-fno-unwind-tables");
    command.arg("-fno-asynchronous-unwind-tables");
    if let Some(target_triple) = config.target.llvm_triple() {
        command.arg(format!("--target={target_triple}"));
    }
    command.args(config.target.clang_args());
    command.arg("-c");
    command.arg(ll_path);
    command.arg("-o");
    command.arg(output);
    run_command(command, &config.clang)
}

fn compile_startup(gcc: &Path, source: &Path, output: &Path) -> Result<(), DriverError> {
    let mut command = Command::new(gcc);
    command.args([
        "-mcpu=arm7tdmi",
        "-marm",
        "-mthumb-interwork",
        "-x",
        "assembler-with-cpp",
        "-c",
    ]);
    command.arg(source);
    command.arg("-o");
    command.arg(output);
    run_command(command, &gcc.display().to_string())
}

fn compile_runtime(gcc: &Path, source: &Path, output: &Path) -> Result<(), DriverError> {
    let mut command = Command::new(gcc);
    command.args([
        "-mcpu=arm7tdmi",
        "-mthumb",
        "-mthumb-interwork",
        "-ffreestanding",
        "-fno-builtin",
        "-fno-common",
        "-fno-jump-tables",
        "-fno-unwind-tables",
        "-fno-asynchronous-unwind-tables",
        "-Os",
        "-std=c99",
        "-c",
    ]);
    command.arg(source);
    command.arg("-o");
    command.arg(output);
    run_command(command, &gcc.display().to_string())
}

fn link_elf(
    gcc: &Path,
    linker_script: &Path,
    startup_object: &Path,
    runtime_object: &Path,
    bf_object: &Path,
    output: &Path,
) -> Result<(), DriverError> {
    let mut command = Command::new(gcc);
    command.args([
        "-mcpu=arm7tdmi",
        "-mthumb",
        "-mthumb-interwork",
        "-nostdlib",
        "-Wl,--gc-sections",
        "-Wl,--no-warn-execstack",
    ]);
    command.arg(format!("-Wl,-T,{}", linker_script.display()));
    command.arg(startup_object);
    command.arg(runtime_object);
    command.arg(bf_object);
    command.arg("-o");
    command.arg(output);
    run_command(command, &gcc.display().to_string())
}

fn objcopy_rom(objcopy: &Path, elf_path: &Path, output: &Path) -> Result<(), DriverError> {
    let mut command = Command::new(objcopy);
    command.arg("-O");
    command.arg("binary");
    command.arg(elf_path);
    command.arg(output);
    run_command(command, &objcopy.display().to_string())
}

fn run_command(mut command: Command, tool: &str) -> Result<(), DriverError> {
    let status = command.status().map_err(|source| DriverError::RunTool {
        tool: tool.to_string(),
        source,
    })?;

    if !status.success() {
        return Err(DriverError::ToolFailed {
            tool: tool.to_string(),
            status: status.to_string(),
        });
    }

    Ok(())
}

fn write_file(path: &Path, bytes: &[u8]) -> Result<(), DriverError> {
    fs::write(path, bytes).map_err(|source| DriverError::WriteFile {
        path: path.to_path_buf(),
        source,
    })
}

fn find_on_path(name: &str) -> Option<PathBuf> {
    env::var_os("PATH").and_then(|path| {
        env::split_paths(&path)
            .map(|dir| dir.join(name))
            .find(|path| path.is_file())
    })
}

fn temporary_dir() -> PathBuf {
    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|duration| duration.as_nanos())
        .unwrap_or_default();
    env::temp_dir().join(format!(
        "hypothalamus-gba-{}-{timestamp}",
        std::process::id()
    ))
}

const STARTUP_ASM: &str = r#"
    .section .gba_header, "a", %progbits
    .balign 4
    .global __gba_header
__gba_header:
    .space 192

    .section .text.start, "ax", %progbits
    .arm
    .global _start
    .type _start, %function
_start:
    ldr sp, =0x03007F00

    ldr r0, =__data_load
    ldr r1, =__data_start
    ldr r2, =__data_end
1:
    cmp r1, r2
    bhs 2f
    ldr r3, [r0], #4
    str r3, [r1], #4
    b 1b

2:
    ldr r0, =__bss_start
    ldr r1, =__bss_end
    mov r2, #0
3:
    cmp r0, r1
    bhs 4f
    str r2, [r0], #4
    b 3b

4:
    ldr r0, =runtime_main
    bx r0

5:
    b 5b
    .size _start, . - _start
"#;

const LINKER_SCRIPT: &str = r#"
ENTRY(_start)

MEMORY
{
  ROM   (rx)  : ORIGIN = 0x08000000, LENGTH = 32M
  EWRAM (rwx) : ORIGIN = 0x02000000, LENGTH = 256K
  IWRAM (rwx) : ORIGIN = 0x03000000, LENGTH = 32K
}

SECTIONS
{
  . = ORIGIN(ROM);

  .gba_header :
  {
    KEEP(*(.gba_header))
  } > ROM

  .text :
  {
    KEEP(*(.text.start*))
    *(.text*)
    *(.rodata*)
    *(.glue_7)
    *(.glue_7t)
  } > ROM

  . = ALIGN(4);

  __data_load = LOADADDR(.data);
  .data : ALIGN(4)
  {
    __data_start = .;
    *(.data*)
    . = ALIGN(4);
    __data_end = .;
  } > EWRAM AT > ROM

  .bss (NOLOAD) : ALIGN(4)
  {
    __bss_start = .;
    *(.bss*)
    *(COMMON)
    . = ALIGN(4);
    __bss_end = .;
  } > EWRAM

  /DISCARD/ :
  {
    *(.comment*)
    *(.note*)
    *(.ARM.exidx*)
    *(.ARM.extab*)
    *(.ARM.attributes)
  }
}
"#;

const RUNTIME_C: &str = r#"
typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned int u32;

extern void bf_main(void);

#define REG_DISPCNT (*(volatile u16 *)0x04000000)
#define REG_VCOUNT  (*(volatile u16 *)0x04000006)
#define VRAM        ((volatile u16 *)0x06000000)
#define SCREEN_W 240u
#define SCREEN_H 160u
#define CELL_W 6u
#define CELL_H 8u
#define COLS 40u
#define ROWS 20u
#define COLOR_BG 0x0000u
#define COLOR_FG 0x7FFFu

static u32 cursor_x;
static u32 cursor_y;

static void wait_vblank(void) {
    while (REG_VCOUNT >= 160u) {}
    while (REG_VCOUNT < 160u) {}
}

static void clear_screen(void) {
    for (u32 i = 0; i < SCREEN_W * SCREEN_H; i++) {
        VRAM[i] = COLOR_BG;
    }
    cursor_x = 0;
    cursor_y = 0;
}

static u8 glyph_row(u8 ch, u32 row) {
    if (ch >= 'a' && ch <= 'z') {
        ch = (u8)(ch - ('a' - 'A'));
    }

    switch (ch) {
    case 'A': switch (row) { case 0: return 0x0E; case 1: return 0x11; case 2: return 0x11; case 3: return 0x1F; case 4: return 0x11; case 5: return 0x11; case 6: return 0x11; } break;
    case 'B': switch (row) { case 0: return 0x1E; case 1: return 0x11; case 2: return 0x11; case 3: return 0x1E; case 4: return 0x11; case 5: return 0x11; case 6: return 0x1E; } break;
    case 'C': switch (row) { case 0: return 0x0E; case 1: return 0x11; case 2: return 0x10; case 3: return 0x10; case 4: return 0x10; case 5: return 0x11; case 6: return 0x0E; } break;
    case 'D': switch (row) { case 0: return 0x1E; case 1: return 0x11; case 2: return 0x11; case 3: return 0x11; case 4: return 0x11; case 5: return 0x11; case 6: return 0x1E; } break;
    case 'E': switch (row) { case 0: return 0x1F; case 1: return 0x10; case 2: return 0x10; case 3: return 0x1E; case 4: return 0x10; case 5: return 0x10; case 6: return 0x1F; } break;
    case 'F': switch (row) { case 0: return 0x1F; case 1: return 0x10; case 2: return 0x10; case 3: return 0x1E; case 4: return 0x10; case 5: return 0x10; case 6: return 0x10; } break;
    case 'G': switch (row) { case 0: return 0x0E; case 1: return 0x11; case 2: return 0x10; case 3: return 0x17; case 4: return 0x11; case 5: return 0x11; case 6: return 0x0E; } break;
    case 'H': switch (row) { case 0: return 0x11; case 1: return 0x11; case 2: return 0x11; case 3: return 0x1F; case 4: return 0x11; case 5: return 0x11; case 6: return 0x11; } break;
    case 'I': switch (row) { case 0: return 0x0E; case 1: return 0x04; case 2: return 0x04; case 3: return 0x04; case 4: return 0x04; case 5: return 0x04; case 6: return 0x0E; } break;
    case 'J': switch (row) { case 0: return 0x01; case 1: return 0x01; case 2: return 0x01; case 3: return 0x01; case 4: return 0x11; case 5: return 0x11; case 6: return 0x0E; } break;
    case 'K': switch (row) { case 0: return 0x11; case 1: return 0x12; case 2: return 0x14; case 3: return 0x18; case 4: return 0x14; case 5: return 0x12; case 6: return 0x11; } break;
    case 'L': switch (row) { case 0: return 0x10; case 1: return 0x10; case 2: return 0x10; case 3: return 0x10; case 4: return 0x10; case 5: return 0x10; case 6: return 0x1F; } break;
    case 'M': switch (row) { case 0: return 0x11; case 1: return 0x1B; case 2: return 0x15; case 3: return 0x15; case 4: return 0x11; case 5: return 0x11; case 6: return 0x11; } break;
    case 'N': switch (row) { case 0: return 0x11; case 1: return 0x19; case 2: return 0x15; case 3: return 0x13; case 4: return 0x11; case 5: return 0x11; case 6: return 0x11; } break;
    case 'O': switch (row) { case 0: return 0x0E; case 1: return 0x11; case 2: return 0x11; case 3: return 0x11; case 4: return 0x11; case 5: return 0x11; case 6: return 0x0E; } break;
    case 'P': switch (row) { case 0: return 0x1E; case 1: return 0x11; case 2: return 0x11; case 3: return 0x1E; case 4: return 0x10; case 5: return 0x10; case 6: return 0x10; } break;
    case 'Q': switch (row) { case 0: return 0x0E; case 1: return 0x11; case 2: return 0x11; case 3: return 0x11; case 4: return 0x15; case 5: return 0x12; case 6: return 0x0D; } break;
    case 'R': switch (row) { case 0: return 0x1E; case 1: return 0x11; case 2: return 0x11; case 3: return 0x1E; case 4: return 0x14; case 5: return 0x12; case 6: return 0x11; } break;
    case 'S': switch (row) { case 0: return 0x0F; case 1: return 0x10; case 2: return 0x10; case 3: return 0x0E; case 4: return 0x01; case 5: return 0x01; case 6: return 0x1E; } break;
    case 'T': switch (row) { case 0: return 0x1F; case 1: return 0x04; case 2: return 0x04; case 3: return 0x04; case 4: return 0x04; case 5: return 0x04; case 6: return 0x04; } break;
    case 'U': switch (row) { case 0: return 0x11; case 1: return 0x11; case 2: return 0x11; case 3: return 0x11; case 4: return 0x11; case 5: return 0x11; case 6: return 0x0E; } break;
    case 'V': switch (row) { case 0: return 0x11; case 1: return 0x11; case 2: return 0x11; case 3: return 0x11; case 4: return 0x11; case 5: return 0x0A; case 6: return 0x04; } break;
    case 'W': switch (row) { case 0: return 0x11; case 1: return 0x11; case 2: return 0x11; case 3: return 0x15; case 4: return 0x15; case 5: return 0x15; case 6: return 0x0A; } break;
    case 'X': switch (row) { case 0: return 0x11; case 1: return 0x11; case 2: return 0x0A; case 3: return 0x04; case 4: return 0x0A; case 5: return 0x11; case 6: return 0x11; } break;
    case 'Y': switch (row) { case 0: return 0x11; case 1: return 0x11; case 2: return 0x0A; case 3: return 0x04; case 4: return 0x04; case 5: return 0x04; case 6: return 0x04; } break;
    case 'Z': switch (row) { case 0: return 0x1F; case 1: return 0x01; case 2: return 0x02; case 3: return 0x04; case 4: return 0x08; case 5: return 0x10; case 6: return 0x1F; } break;
    case '0': switch (row) { case 0: return 0x0E; case 1: return 0x11; case 2: return 0x13; case 3: return 0x15; case 4: return 0x19; case 5: return 0x11; case 6: return 0x0E; } break;
    case '1': switch (row) { case 0: return 0x04; case 1: return 0x0C; case 2: return 0x04; case 3: return 0x04; case 4: return 0x04; case 5: return 0x04; case 6: return 0x0E; } break;
    case '2': switch (row) { case 0: return 0x0E; case 1: return 0x11; case 2: return 0x01; case 3: return 0x02; case 4: return 0x04; case 5: return 0x08; case 6: return 0x1F; } break;
    case '3': switch (row) { case 0: return 0x1E; case 1: return 0x01; case 2: return 0x01; case 3: return 0x0E; case 4: return 0x01; case 5: return 0x01; case 6: return 0x1E; } break;
    case '4': switch (row) { case 0: return 0x02; case 1: return 0x06; case 2: return 0x0A; case 3: return 0x12; case 4: return 0x1F; case 5: return 0x02; case 6: return 0x02; } break;
    case '5': switch (row) { case 0: return 0x1F; case 1: return 0x10; case 2: return 0x10; case 3: return 0x1E; case 4: return 0x01; case 5: return 0x01; case 6: return 0x1E; } break;
    case '6': switch (row) { case 0: return 0x0E; case 1: return 0x10; case 2: return 0x10; case 3: return 0x1E; case 4: return 0x11; case 5: return 0x11; case 6: return 0x0E; } break;
    case '7': switch (row) { case 0: return 0x1F; case 1: return 0x01; case 2: return 0x02; case 3: return 0x04; case 4: return 0x08; case 5: return 0x08; case 6: return 0x08; } break;
    case '8': switch (row) { case 0: return 0x0E; case 1: return 0x11; case 2: return 0x11; case 3: return 0x0E; case 4: return 0x11; case 5: return 0x11; case 6: return 0x0E; } break;
    case '9': switch (row) { case 0: return 0x0E; case 1: return 0x11; case 2: return 0x11; case 3: return 0x0F; case 4: return 0x01; case 5: return 0x01; case 6: return 0x0E; } break;
    case '!': switch (row) { case 0: return 0x04; case 1: return 0x04; case 2: return 0x04; case 3: return 0x04; case 4: return 0x04; case 5: return 0x00; case 6: return 0x04; } break;
    case '?': switch (row) { case 0: return 0x0E; case 1: return 0x11; case 2: return 0x01; case 3: return 0x02; case 4: return 0x04; case 5: return 0x00; case 6: return 0x04; } break;
    case '.': switch (row) { case 5: return 0x00; case 6: return 0x04; } break;
    case ',': switch (row) { case 5: return 0x04; case 6: return 0x08; } break;
    case ':': switch (row) { case 1: return 0x04; case 5: return 0x04; } break;
    case '-': switch (row) { case 3: return 0x1F; } break;
    case '+': switch (row) { case 2: return 0x04; case 3: return 0x1F; case 4: return 0x04; } break;
    case '/': switch (row) { case 0: return 0x01; case 1: return 0x02; case 2: return 0x02; case 3: return 0x04; case 4: return 0x08; case 5: return 0x08; case 6: return 0x10; } break;
    case '<': switch (row) { case 1: return 0x02; case 2: return 0x04; case 3: return 0x08; case 4: return 0x04; case 5: return 0x02; } break;
    case '>': switch (row) { case 1: return 0x08; case 2: return 0x04; case 3: return 0x02; case 4: return 0x04; case 5: return 0x08; } break;
    case '[': switch (row) { case 0: return 0x0E; case 1: return 0x08; case 2: return 0x08; case 3: return 0x08; case 4: return 0x08; case 5: return 0x08; case 6: return 0x0E; } break;
    case ']': switch (row) { case 0: return 0x0E; case 1: return 0x02; case 2: return 0x02; case 3: return 0x02; case 4: return 0x02; case 5: return 0x02; case 6: return 0x0E; } break;
    case ' ': return 0x00;
    default: switch (row) { case 0: return 0x1F; case 1: return 0x11; case 2: return 0x15; case 3: return 0x11; case 4: return 0x15; case 5: return 0x11; case 6: return 0x1F; } break;
    }
    return 0x00;
}

static void newline(void) {
    cursor_x = 0;
    cursor_y++;
    if (cursor_y >= ROWS) {
        clear_screen();
    }
}

static void draw_char(u8 ch) {
    u32 px = cursor_x * CELL_W;
    u32 py = cursor_y * CELL_H;
    for (u32 row = 0; row < CELL_H; row++) {
        u8 bits = 0;
        if (row > 0 && row < 8u) {
            bits = glyph_row(ch, row - 1u);
        }
        for (u32 col = 0; col < CELL_W; col++) {
            u16 color = COLOR_BG;
            if (col < 5u && (bits & (u8)(1u << (4u - col))) != 0u) {
                color = COLOR_FG;
            }
            VRAM[(py + row) * SCREEN_W + px + col] = color;
        }
    }
}

void bf_putchar(u8 byte) {
    if (byte == '\r') {
        return;
    }
    if (byte == '\n') {
        newline();
        return;
    }

    draw_char(byte);
    cursor_x++;
    if (cursor_x >= COLS) {
        newline();
    }
}

int bf_getchar(void) {
    return -1;
}

void runtime_main(void) {
    REG_DISPCNT = 0x0403u;
    clear_screen();
    bf_main();
    for (;;) {
        wait_vblank();
    }
}
"#;

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

    #[test]
    fn patches_valid_gba_header() {
        let mut rom = vec![0xAA; 512];

        patch_header(&mut rom);

        assert!(has_valid_header(&rom));
        assert_eq!(&rom[0xA0..0xAC], ROM_TITLE);
        assert_eq!(&rom[0xAC..0xB0], GAME_CODE);
        assert_eq!(&rom[0xB0..0xB2], MAKER_CODE);
        assert_eq!(rom[0xB2], 0x96);
    }

    #[test]
    fn patch_extends_short_roms() {
        let mut rom = Vec::new();

        patch_header(&mut rom);

        assert_eq!(rom.len(), HEADER_SIZE);
        assert!(has_valid_header(&rom));
    }
}