rsemu 0.0.1

A multiplatform emulator in pure Rust, built bottom-up on a generic framework.
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
//! The `rsemu` command-line tool.
//!
//! The subcommand surface is fixed by `ROADMAP.md` §2 so that it does not drift
//! as components land. Commands whose machinery does not exist yet say exactly
//! that and exit non-zero, rather than pretending to work.
//!
//! This is the one place in the tree that opens a file. Everything below it is
//! `no_std`: a machine description arrives as text and a ROM image arrives as
//! bytes bound to a named media slot, so the emulation core never learns what a
//! path is (`CLAUDE.md`, and [`MediaTable`](rsemu::machine::MediaTable)).

use std::path::Path;
use std::process::ExitCode;
use std::sync::Arc;
use std::time::{Duration, Instant};

use rsemu::core::clock::GlobalTime;
use rsemu::host::chardev::{CharDevice, CharPort, ports};
use rsemu::host::terminal::Terminal;
use rsemu::machine::{Machine, catalog};

const USAGE: &str = "\
rsemu — a multiplatform emulator built bottom-up on a generic framework

USAGE:
    rsemu <COMMAND> [OPTIONS]

COMMANDS:
    run <machine>       Run a machine description
    machines            List machines this build can emulate
    devices             List registered device classes
    describe <class>    Show a device class: properties, defaults, buses
    convert <machine>   Convert a machine file between its text and JSON forms

RUN OPTIONS:
    <machine>           A path to a .machine file, or a name from `rsemu machines`
    --cart <file>       Bind the `cart` media slot (a NES cartridge)
    --rom <file>        Bind the `rom` media slot
    --monitor <name>    Bind the `rom` slot to one of rsemu's own monitor
                        images instead of a file: `rsmon` (the default, ours,
                        MIT) or `wozmon` (the 1976 Woz Monitor, public domain)
    --disk <file>       Bind the `disk` media slot
    --media <n>=<file>  Bind any media slot by name
    -p <name>=<value>   Override a `param` declared in the machine file
    --for <duration>    How much virtual time to run, as `1s`, `500ms`, `2m`
                        (default 1s, or forever with a console attached)
    --console <name>    Attach this terminal to a named character port. A
                        machine that opens exactly one is picked up on its own,
                        so `rsemu run apple1` is interactive already
    --headless          Do not attach a terminal, whatever the machine opened
    -q, --quiet         Only print the summary

OPTIONS:
    -h, --help          Print this help
    -V, --version       Print version and build configuration
";

fn main() -> ExitCode {
    // Hand-rolled argument parsing: the dependency policy has no room for a
    // CLI crate, and the surface is small enough that it does not need one.
    let args: Vec<String> = std::env::args().skip(1).collect();
    let Some(first) = args.first().map(String::as_str) else {
        print!("{USAGE}");
        return ExitCode::from(2);
    };

    match first {
        "-h" | "--help" | "help" => {
            print!("{USAGE}");
            ExitCode::SUCCESS
        }
        "-V" | "--version" | "version" => {
            println!("{}", rsemu::build_info());
            ExitCode::SUCCESS
        }
        "machines" => machines(),
        "devices" => devices(),
        "describe" => describe(args.get(1).map(String::as_str)),
        "run" => run(&args[1..]),
        "convert" => {
            eprintln!(
                "rsemu: {}",
                rsemu::Error::Unimplemented("the JSON projection (ROADMAP.md §5)")
            );
            ExitCode::from(2)
        }
        other => {
            eprintln!("rsemu: unknown command `{other}`\n");
            eprint!("{USAGE}");
            ExitCode::from(2)
        }
    }
}

// ---------------------------------------------------------------------------
// introspection
// ---------------------------------------------------------------------------

/// `rsemu machines` — the shipped catalog, filtered to what this build has.
fn machines() -> ExitCode {
    let machines = catalog::machines();
    if machines.is_empty() {
        // A machine is a feature set, so an empty catalog is a correct answer
        // about this build rather than a failure.
        println!("no machines in this build; rebuild with a `machine-*` feature");
        return ExitCode::SUCCESS;
    }
    for entry in machines {
        println!("{:<12} {}", entry.name, entry.summary);
        if !entry.media.is_empty() {
            let slots: Vec<String> = entry
                .media
                .iter()
                .map(|s| format!("--{s} <file>"))
                .collect();
            // "media", not "needs": a slot with no default is an error naming
            // itself when the machine is built, and `apple1` binds its own
            // monitor ROM when nothing else does.
            println!("{:<12} media {}", "", slots.join(", "));
        }
    }
    ExitCode::SUCCESS
}

/// `rsemu devices` — every class the registry can construct.
fn devices() -> ExitCode {
    let registry = match catalog::registry() {
        Ok(r) => r,
        Err(e) => return fail(&e),
    };
    if registry.is_empty() {
        println!("no device classes in this build");
        return ExitCode::SUCCESS;
    }
    for class in registry.classes() {
        println!("{:<16} {}", class.name, class.summary);
    }
    ExitCode::SUCCESS
}

/// `rsemu describe <class>` — one class, its version and its properties.
fn describe(class: Option<&str>) -> ExitCode {
    let Some(name) = class else {
        eprintln!("rsemu: describe needs a class name; `rsemu devices` lists them");
        return ExitCode::from(2);
    };
    let registry = match catalog::registry() {
        Ok(r) => r,
        Err(e) => return fail(&e),
    };
    let Some(class) = registry.get(name) else {
        // The registry composes the "is its feature enabled?" message and the
        // near-miss suggestion; reproducing them here would be a second copy.
        let e = registry
            .create(name, &rsemu::core::props::Props::new())
            .expect_err("a class that is not there cannot construct");
        return fail(&e);
    };
    println!("{} (v{})", class.name, class.version);
    println!("  {}", class.summary);
    if class.properties.is_empty() {
        println!("  no properties");
        return ExitCode::SUCCESS;
    }
    println!("  properties:");
    for p in class.properties {
        println!(
            "    {:<10} {:<10} {:<9} {}",
            p.name,
            p.kind.as_str(),
            if p.required { "required" } else { "optional" },
            p.summary
        );
    }
    ExitCode::SUCCESS
}

// ---------------------------------------------------------------------------
// run
// ---------------------------------------------------------------------------

/// Everything `rsemu run` was told.
struct RunArgs {
    machine: String,
    /// Media slot to file path, in the order they were given.
    media: Vec<(String, String)>,
    /// A built-in monitor image for the `rom` slot, if the user named one.
    monitor: Option<String>,
    params: Vec<(String, String)>,
    span: GlobalTime,
    /// Whether `--for` was given. Without it an interactive machine runs until
    /// the user stops it, and a headless one runs for a second.
    span_given: bool,
    /// The character port to attach this terminal to, if the user named one.
    console: Option<String>,
    /// Whether the user asked for no terminal at all.
    headless: bool,
    quiet: bool,
}

fn run(args: &[String]) -> ExitCode {
    let parsed = match parse_run(args) {
        Ok(a) => a,
        Err(e) => {
            eprintln!("rsemu: {e}");
            return ExitCode::from(2);
        }
    };

    // Read every image before building anything, so a typo'd path fails before
    // a machine is half assembled.
    let mut images: Vec<(String, Vec<u8>)> = Vec::new();
    for (slot, path) in &parsed.media {
        match std::fs::read(path) {
            Ok(bytes) => images.push((slot.clone(), bytes)),
            Err(e) => {
                eprintln!("rsemu: cannot read {path}: {e}");
                return ExitCode::FAILURE;
            }
        }
    }

    // A machine that wants a `rom` and was given no file gets a built-in one,
    // so `rsemu run apple1` and `rsemu run beneater-6502` work with no
    // arguments and no image of unclear provenance. Media nothing asked for is
    // ignored, so a machine with no `rom` slot is unaffected.
    if !images.iter().any(|(slot, _)| slot == "rom") {
        match builtin_rom(parsed.monitor.as_deref(), &parsed.machine) {
            Ok(Some(image)) => images.push((String::from("rom"), image)),
            Ok(None) => {}
            Err(e) => {
                eprintln!("rsemu: {e}");
                return ExitCode::from(2);
            }
        }
    }

    // A path wins over a catalog name, so a user editing a copy of a shipped
    // file gets their copy.
    let (name, source) = match load_description(&parsed.machine) {
        Ok(pair) => pair,
        Err(e) => {
            eprintln!("rsemu: {e}");
            return ExitCode::from(2);
        }
    };

    let mut options = match catalog::build_options() {
        Ok(o) => o,
        Err(e) => return fail(&e),
    };
    for (slot, bytes) in &images {
        options
            .realize
            .media
            .insert(slot.as_str(), bytes.as_slice());
    }
    for (key, value) in &parsed.params {
        options = options.with_param(key.clone(), value.clone());
    }

    let registry = match catalog::registry() {
        Ok(r) => r,
        Err(e) => return fail(&e),
    };
    let mut machine = match rsemu::machine::build(&name, &source, &registry, &options) {
        Ok(m) => m,
        // Front-end failures already carry `file:line:col` and a caret; realize
        // failures name the instance. Either way `{e}` is the whole report.
        Err(e) => return fail(&e),
    };

    if !parsed.quiet {
        describe_machine(&machine);
    }

    // A machine that opened a character port has a console; attach this
    // terminal to it and hand the keyboard over.
    match console_port(&parsed) {
        Err(e) => {
            eprintln!("rsemu: {e}");
            return ExitCode::from(2);
        }
        Ok(Some(port)) => return interact(&mut machine, &port, &parsed),
        Ok(None) => {}
    }

    if let Err(e) = machine.run_for(parsed.span) {
        eprintln!("rsemu: {e}");
        summarise(&machine);
        return ExitCode::FAILURE;
    }
    summarise(&machine);
    ExitCode::SUCCESS
}

/// Which character port this terminal should attach to, if any.
///
/// The machine has already been built, so every port its devices asked for is
/// open. One is unambiguous; several need `--console` to choose between them,
/// because guessing would put the keyboard on the wrong machine.
fn console_port(args: &RunArgs) -> Result<Option<Arc<CharPort>>, String> {
    if args.headless {
        return Ok(None);
    }
    if let Some(name) = &args.console {
        return ports::get(name).map(Some).ok_or_else(|| {
            format!(
                "no character port named `{name}`; this machine opened {}",
                list(&ports::names())
            )
        });
    }
    let names = ports::names();
    match names.len() {
        0 => Ok(None),
        1 => Ok(ports::get(&names[0])),
        _ => Err(format!(
            "this machine has {} character ports ({}); pick one with --console, or --headless",
            names.len(),
            list(&names)
        )),
    }
}

/// `a`, `b` and `c`, or "none".
fn list(names: &[String]) -> String {
    if names.is_empty() {
        return String::from("none");
    }
    names
        .iter()
        .map(|n| format!("`{n}`"))
        .collect::<Vec<String>>()
        .join(", ")
}

/// How much virtual time to advance between two visits to the terminal.
///
/// Ten milliseconds: short enough that a keystroke is picked up before the eye
/// notices, long enough that the scheduler is not the bottleneck.
const SLICE: GlobalTime = GlobalTime::from_nanos(10_000_000);

/// How many quiet slices after end-of-input before a piped session gives up.
///
/// Two virtual seconds: long enough for a paced 60-character-a-second display
/// to finish a screenful it was still emitting when the script ran out.
const IDLE_SLICES: u32 = 200;

/// Run the machine with the terminal attached, until the user stops it.
///
/// Virtual time is held to real time by sleeping off whatever the slice did not
/// use. Nothing below `host/` reads a clock (`CLAUDE.md`); this is `host/`'s
/// job, and it is why an Apple 1 here feels like an Apple 1 rather than
/// finishing a screenful of output before the terminal has drawn a line.
fn interact(machine: &mut Machine, port: &CharPort, args: &RunArgs) -> ExitCode {
    let term = Terminal::open();
    if !args.quiet {
        if term.is_raw() {
            eprintln!("  console attached — Ctrl-C to stop\n");
        } else {
            eprintln!(
                "  console attached, cooked mode — stdin could not be put in raw mode.\n  \
                 On a terminal that means input arrives a line at a time and is\n  \
                 echoed twice, once by the host and once by the guest.\n"
            );
        }
    }

    let deadline = args
        .span_given
        .then(|| machine.now().saturating_add(args.span));
    let started = Instant::now();
    let mut elapsed = GlobalTime::ZERO;
    let mut idle = 0u32;

    let status = loop {
        if term.interrupted() {
            break ExitCode::SUCCESS;
        }
        if deadline.is_some_and(|d| machine.now() >= d) {
            break ExitCode::SUCCESS;
        }
        let mut moved = term.pump(port);
        if let Err(e) = machine.run_until(machine.now().saturating_add(SLICE)) {
            eprintln!("\r\nrsemu: {e}");
            break ExitCode::FAILURE;
        }
        moved += term.pump(port);

        // A script on stdin has an end; a person does not. Once the input is
        // exhausted *and* the machine has gone quiet, there is nobody left to
        // wait for, so `printf … | rsemu run apple1` finishes rather than
        // hanging on a machine that will never be typed at again.
        if term.at_eof() && moved == 0 {
            idle += 1;
            if idle >= IDLE_SLICES {
                break ExitCode::SUCCESS;
            }
        } else {
            idle = 0;
        }

        // Hold virtual time to real time. A slice that took longer than its
        // own span to simulate simply does not sleep, and the machine runs
        // slow rather than jumping.
        elapsed = elapsed.saturating_add(SLICE);
        let target = Duration::from_nanos(elapsed.as_nanos());
        if let Some(wait) = target.checked_sub(started.elapsed()) {
            std::thread::sleep(wait);
        }
    };

    // Restore the terminal before anything else is printed on it.
    term.flush();
    drop(term);
    if !args.quiet {
        println!();
        summarise(machine);
    }
    status
}

/// A machine description by path, or by catalog name.
fn load_description(what: &str) -> Result<(String, String), String> {
    let path = Path::new(what);
    if path.is_file() {
        let text = std::fs::read_to_string(path).map_err(|e| format!("cannot read {what}: {e}"))?;
        return Ok((what.to_string(), text));
    }
    if let Some(entry) = catalog::machine(what) {
        return Ok((entry.name.to_string(), entry.source.to_string()));
    }
    // A name that looks like a path deserves the filesystem's complaint rather
    // than "not in the catalog", which would send the reader the wrong way.
    if what.contains('/') || what.ends_with(".machine") {
        return Err(format!("no such machine file: {what}"));
    }
    Err(format!(
        "no machine named `{what}`; `rsemu machines` lists this build's catalog"
    ))
}

/// The monitor image to bind to an unfilled `rom` slot.
///
/// `--monitor` names one explicitly; without it each board gets its own
/// default, which is always rsemu's own (`ROADMAP.md` §1 — the machine has to
/// demonstrate itself with nothing whose licence anyone has to think about).
/// `Ok(None)` means this build has no image to offer, which is not an error:
/// the machine may not want a `rom` slot at all.
fn builtin_rom(monitor: Option<&str>, machine: &str) -> Result<Option<Vec<u8>>, String> {
    // The Woz Monitor is only ported to one of these boards, so `wozmon` is
    // answered from the module that has it rather than per machine.
    #[cfg(feature = "dev-wdc")]
    if monitor == Some("wozmon") {
        return Ok(Some(rsemu::dev::wdc::WOZMON_IMAGE.to_vec()));
    }
    if let Some(name) = monitor
        && name != "rsmon"
    {
        return Err(format!(
            "--monitor {name}: this build has `rsmon`{}",
            if cfg!(feature = "dev-wdc") {
                " and `wozmon`"
            } else {
                ""
            }
        ));
    }
    let stem = machine
        .rsplit('/')
        .next()
        .unwrap_or(machine)
        .strip_suffix(".machine")
        .unwrap_or_else(|| machine.rsplit('/').next().unwrap_or(machine));
    match stem {
        #[cfg(feature = "dev-wdc")]
        "beneater-6502" => Ok(Some(rsemu::dev::wdc::RSMON_IMAGE.to_vec())),
        #[cfg(feature = "dev-apple1")]
        "apple1" => Ok(Some(rsemu::dev::apple1::RSMON.to_vec())),
        _ => Ok(None),
    }
}

fn parse_run(args: &[String]) -> Result<RunArgs, String> {
    let mut out = RunArgs {
        machine: String::new(),
        media: Vec::new(),
        monitor: None,
        params: Vec::new(),
        // One second of virtual time: long enough to prove a machine runs,
        // short enough that a broken one does not hang a terminal. There is no
        // "until the user quits" yet — that needs the host window (phase 3).
        span: GlobalTime::from_nanos(1_000_000_000),
        span_given: false,
        console: None,
        headless: false,
        quiet: false,
    };
    let mut i = 0;
    while i < args.len() {
        let arg = args[i].as_str();
        let mut value = |name: &str| -> Result<String, String> {
            i += 1;
            args.get(i)
                .cloned()
                .ok_or_else(|| format!("{name} needs a value"))
        };
        match arg {
            "--cart" | "--rom" | "--disk" => {
                let slot = arg.trim_start_matches('-').to_string();
                let path = value(arg)?;
                out.media.push((slot, path));
            }
            "--media" => {
                let spec = value(arg)?;
                let (slot, path) = spec
                    .split_once('=')
                    .ok_or_else(|| format!("--media wants <name>=<file>, got `{spec}`"))?;
                out.media.push((slot.to_string(), path.to_string()));
            }
            "-p" | "--param" => {
                let spec = value(arg)?;
                let (key, val) = spec
                    .split_once('=')
                    .ok_or_else(|| format!("-p wants <name>=<value>, got `{spec}`"))?;
                out.params.push((key.to_string(), val.to_string()));
            }
            "--for" => {
                let text = value(arg)?;
                let d = rsemu::core::props::parse_duration(&text)
                    .map_err(|e| format!("--for {text}: {e}"))?;
                // The timeline is in 2^-64-second units and durations are in
                // picoseconds; nanoseconds is the unit both agree on.
                out.span = GlobalTime::from_nanos(d.as_picos() / 1_000);
                out.span_given = true;
            }
            "--monitor" => out.monitor = Some(value(arg)?),
            "--console" => out.console = Some(value(arg)?),
            "--headless" => out.headless = true,
            "-q" | "--quiet" => out.quiet = true,
            other if other.starts_with('-') => {
                return Err(format!("unknown option `{other}`"));
            }
            other => {
                if !out.machine.is_empty() {
                    return Err(format!("`{other}`: only one machine at a time"));
                }
                out.machine = other.to_string();
            }
        }
        i += 1;
    }
    if out.machine.is_empty() {
        return Err(String::from(
            "run needs a machine; `rsemu machines` lists this build's catalog",
        ));
    }
    Ok(out)
}

/// What was assembled, before it starts running.
fn describe_machine(machine: &Machine) {
    println!("machine \"{}\"", machine.name());
    for space in machine.spaces() {
        println!("  space  {:<8} {} bits", space.name(), space.space().bits());
    }
    for device in machine.devices() {
        let clock = match device.domain() {
            Some(_) => "clocked",
            None => "",
        };
        println!(
            "  object {:<8} {:<16} {clock}",
            device.path(),
            device.class().name
        );
    }
}

/// Where the machine got to.
fn summarise(machine: &Machine) {
    println!("ran to {} ns of virtual time", machine.now().as_nanos());
    for device in machine.devices() {
        let Some(domain) = device.domain() else {
            continue;
        };
        if let Ok(ticks) = machine.clocks().ticks(domain) {
            println!("  {:<8} {ticks} ticks", device.path());
        }
    }
    match machine.state_hash() {
        // The regression method of §0 in one number: run deterministically for
        // N virtual units and compare this.
        Ok(hash) => println!("state hash {hash:#018x}"),
        Err(e) => eprintln!("rsemu: cannot hash state: {e}"),
    }
}

/// Print an error the way §5 promises and exit non-zero.
fn fail(e: &rsemu::Error) -> ExitCode {
    eprintln!("rsemu: {e}");
    ExitCode::FAILURE
}