rsemu 0.0.2

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
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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
//! 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
    debug <machine>     Run it under a debugger, stopped, on :1234
    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
    --bios <file>       Bind the `bios` media slot: a PC's system firmware.
                        rsemu ships none — point this at your own copy, the
                        way you would point qemu at one. Running a firmware
                        binary as a guest is ordinary use whatever its licence;
                        redistributing it is not, which is why there is a flag
                        here and no file in the repository
    --vgabios <file>    Bind the `vgabios` media slot: a video option ROM
    --floppy <file>     Bind the `floppy` media slot: a raw diskette image
    --flash0 <file>     Bind the `flash0` media slot: a NOR flash bank's
                        contents. `riscv-virt` boots UEFI out of it.
    --flash1 <file>     Bind the `flash1` media slot: the second NOR bank,
                        which is where UEFI keeps its variables.
    --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
    --screenshot <file> Write the machine's display to a PNG when the run ends.
                        Needs a build with `display-png` and a machine with a
                        display; a machine with neither says so rather than
                        writing nothing
    --gdb <addr>        Listen for GDB on <addr> and hold the machine stopped
                        until it attaches. `1234`, `:1234` and `host:1234` all
                        work; a bare port binds the loopback interface only,
                        because the far end can read and write all of guest
                        memory. `rsemu debug` implies `--gdb :1234`
    -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..]),
        #[cfg(feature = "gdb")]
        "debug" => debug(&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,
    /// Where to write a PNG of the display when the run ends, if `--screenshot`
    /// was given.
    screenshot: Option<String>,
    quiet: bool,
    /// Where to listen for a debugger, if `--gdb` was given.
    #[cfg(feature = "gdb")]
    gdb: Option<String>,
}

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);
            }
        }
    }

    // Same for a `firmware` slot. `spi-panel` is a demonstration board rather
    // than a product, so `rsemu run spi-panel` with no arguments draws its own
    // test picture instead of executing an empty ROM.
    if !images.iter().any(|(slot, _)| slot == "firmware")
        && let Some(image) = builtin_firmware(&parsed.machine)
    {
        images.push((String::from("firmware"), image));
    }

    // And for the NOR flash banks a `riscv-virt` has: nothing bound means a
    // board with blank parts on it, which is what a factory ships and what a
    // UEFI build will format for itself. Naming the slots explicitly on every
    // run to say "empty" would be ceremony, and an unbound slot is an error by
    // design (`machine::realize`).
    for slot in ["flash0", "flash1"] {
        if !images.iter().any(|(bound, _)| bound == slot) {
            images.push((String::from(slot), Vec::new()));
        }
    }

    // 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());
    }

    // A host gets a typed handle on a display device at the one moment the
    // concrete type exists: construction. Installed unconditionally rather than
    // only under `--screenshot`, so that asking for a screenshot after the fact
    // is never the thing that changes how the machine was built.
    if let Err(e) = install_capture(&mut options) {
        return fail(&e);
    }

    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 debugger, if one was asked for, owns when the machine advances — so it
    // is checked before the console loop, which would otherwise own that.
    #[cfg(feature = "gdb")]
    if let Some(addr) = parsed.gdb.clone() {
        let port = match console_port(&parsed) {
            Ok(port) => port,
            Err(e) => {
                eprintln!("rsemu: {e}");
                return ExitCode::from(2);
            }
        };
        return debug_session(&mut machine, &addr, port.as_ref(), &parsed);
    }

    // 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);
        write_screenshot(&parsed);
        return ExitCode::FAILURE;
    }
    summarise(&machine);
    if !write_screenshot(&parsed) {
        return ExitCode::FAILURE;
    }
    ExitCode::SUCCESS
}

/// Wrap the machine's bindings so a display device hands the host a handle.
///
/// One arm per device family that publishes a scanout, exactly like the
/// registration lists in `machine::catalog`: a family that is not named here is
/// not in the build, and that is visible by reading the code.
#[allow(unused_variables, unused_mut)]
fn install_capture(options: &mut rsemu::machine::BuildOptions) -> rsemu::Result<()> {
    #[cfg(feature = "dev-nes-ppu")]
    rsemu::host::display::nes::capture::install(options)?;
    #[cfg(feature = "dev-pc-video")]
    rsemu::host::display::pc::capture::install(options)?;
    Ok(())
}

/// The display of the machine just built, if it has one this build can see.
///
/// Only the PNG path calls it, so a build without an encoder has no use for it
/// — and the compiler is right to say so rather than being told to be quiet
/// about a function that might one day be called.
#[cfg(feature = "display-png")]
#[allow(unused_mut)]
fn take_scanout() -> Option<Box<dyn rsemu::host::display::Scanout>> {
    #[cfg(feature = "dev-pc-video")]
    if let Some(s) = rsemu::host::display::pc::capture::take() {
        return Some(Box::new(s));
    }
    #[cfg(feature = "dev-nes-ppu")]
    if let Some(s) = rsemu::host::display::nes::capture::take() {
        return Some(Box::new(s));
    }
    None
}

/// Write `--screenshot`'s PNG, reporting whether the run should still count as
/// a success.
///
/// Returns true when nothing was asked for. A `--screenshot` that could not be
/// honoured is an error rather than a silence: the user asked for a file and
/// there has to be one, or a reason.
fn write_screenshot(args: &RunArgs) -> bool {
    let Some(path) = args.screenshot.as_deref() else {
        return true;
    };
    #[cfg(not(feature = "display-png"))]
    {
        let _ = path;
        eprintln!("rsemu: --screenshot needs a build with the `display-png` feature");
        false
    }
    #[cfg(feature = "display-png")]
    {
        use rsemu::host::display::{Surface, png};
        let Some(scanout) = take_scanout() else {
            eprintln!("rsemu: --screenshot: this machine has no display");
            return false;
        };
        let mut surface = Surface::for_scanout(scanout.as_ref());
        scanout.capture(&mut surface);
        let bytes = match png::encode(&surface) {
            Ok(b) => b,
            Err(e) => {
                eprintln!("rsemu: --screenshot: {e}");
                return false;
            }
        };
        match std::fs::write(path, &bytes) {
            Ok(()) => {
                if !args.quiet {
                    println!(
                        "screenshot  {path} ({}x{}, {} bytes)",
                        surface.width(),
                        surface.height(),
                        bytes.len()
                    );
                }
                true
            }
            Err(e) => {
                eprintln!("rsemu: cannot write {path}: {e}");
                false
            }
        }
    }
}

/// `rsemu debug <machine>`: `run` with a debugger attached (`ROADMAP.md` §2).
///
/// The only difference from `run --gdb` is the default: `debug` with no
/// `--gdb` listens on `:1234`, which is the port every GDB user already has in
/// their fingers.
#[cfg(feature = "gdb")]
fn debug(args: &[String]) -> ExitCode {
    let mut args = args.to_vec();
    if !args.iter().any(|a| a == "--gdb") {
        args.push(String::from("--gdb"));
        args.push(String::from(":1234"));
    }
    run(&args)
}

/// Run a machine with the gdbstub in charge of when it advances.
///
/// The machine is held stopped until a debugger attaches, so `target remote`
/// lands on the reset vector rather than wherever a free-running guest had got
/// to. A console, if the machine opened one, is pumped between session turns —
/// so a guest can be typed at and stepped through at the same time.
#[cfg(feature = "gdb")]
fn debug_session(
    machine: &mut Machine,
    addr: &str,
    port: Option<&Arc<CharPort>>,
    args: &RunArgs,
) -> ExitCode {
    use rsemu::host::gdb::{ExitReason, GdbServer};

    let mut server = match GdbServer::bind(addr) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("rsemu: cannot listen on `{addr}`: {e}");
            return ExitCode::FAILURE;
        }
    };
    if !args.quiet {
        match server.local_addr() {
            Ok(bound) => eprintln!("  gdbstub listening on {bound} — the machine is stopped"),
            Err(_) => eprintln!("  gdbstub listening — the machine is stopped"),
        }
        eprintln!("  attach with: gdb -ex 'target remote {addr}'");
        // Which devices became GDB threads, and — the hour-saving part — which
        // of them upstream GDB has no architecture for. A target description
        // tells GDB what the registers *are*; it still needs a gdbarch to know
        // what the machine *is*, and for a 6502 it has none. It says
        // "Architecture rejected target-supplied description", falls back to its
        // own register layout, and `target remote` then fails outright. That is
        // a property of GDB, not of this stub, and reading it here beats
        // discovering it from that message.
        let mut thread = 0u32;
        for entry in machine.devices() {
            let Some(arch) = rsemu::host::gdb::arch::for_class(entry.class().name) else {
                continue;
            };
            thread += 1;
            match arch.architecture {
                Some(name) => eprintln!(
                    "  thread {thread}: {} ({}), gdb architecture `{name}`",
                    entry.path(),
                    entry.class().name
                ),
                None => eprintln!(
                    "  thread {thread}: {} ({}) — upstream gdb has no architecture for\n    \
                     this core, so it rejects the target description and `target remote`\n    \
                     fails. The protocol is served in full to any client that reads the\n    \
                     description rather than insisting on a gdbarch.",
                    entry.path(),
                    entry.class().name
                ),
            }
        }
        eprintln!();
    }

    let terminal = port.map(|_| Terminal::open());
    let status = match rsemu::host::gdb::serve(machine, &mut server, |_| {
        if let (Some(term), Some(port)) = (terminal.as_ref(), port) {
            term.pump(port);
            if term.interrupted() {
                return false;
            }
        }
        true
    }) {
        Ok(ExitReason::Killed | ExitReason::Stopped) => ExitCode::SUCCESS,
        Err(e) => {
            eprintln!("rsemu: {e}");
            ExitCode::FAILURE
        }
    };
    if let Some(term) = terminal {
        term.flush();
    }
    if !args.quiet {
        println!();
        summarise(machine);
    }
    status
}

/// 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.
/// The image a machine's `firmware` slot falls back to, if it has one.
///
/// Unlike [`builtin_rom`] there is no monitor to choose between: this is one
/// board's own demonstration program.
fn builtin_firmware(machine: &str) -> Option<Vec<u8>> {
    let stem = machine
        .rsplit('/')
        .next()
        .unwrap_or(machine)
        .strip_suffix(".machine")
        .unwrap_or_else(|| machine.rsplit('/').next().unwrap_or(machine));
    match stem {
        #[cfg(feature = "machine-spi-panel")]
        "spi-panel" => Some(rsemu::dev::lcd::demo::PANEL_DEMO.to_vec()),
        _ => {
            let _ = stem;
            None
        }
    }
}

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(),
        screenshot: None,
        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,
        #[cfg(feature = "gdb")]
        gdb: None,
    };
    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 {
            // One arm, because every one of these is `--<slot> <file>` and a
            // list is easier to extend than a match with a line each. They
            // exist at all because `--media bios=…` is correct and nobody
            // types it.
            "--cart" | "--rom" | "--disk" | "--bios" | "--vgabios" | "--floppy" | "--flash0"
            | "--flash1" => {
                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)?),
            #[cfg(feature = "gdb")]
            "--gdb" => out.gdb = Some(value(arg)?),
            "--console" => out.console = Some(value(arg)?),
            "--headless" => out.headless = true,
            "--screenshot" => out.screenshot = Some(value(arg)?),
            "-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
}