hexicon 0.3.0

Hexicon, for writing interactive fiction: builds a game, plays it in a terminal, tests it, documents it, and serves editors
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
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
//! `hexicon test`: build a game for debugging, play its scenarios and
//! walkthroughs, and report how they went; or print a walkthrough.
//!
//! The game is built into a file of its own in the game's folder, beside
//! the image its manifest names, which is left alone, and played by
//! `hexicon run` with the same random choices and clock on every run, as
//! game-check plays games. The game is told, by its arguments, what to
//! play (`-scenario=<name>` for each named, `-walkthroughs` for every
//! walkthrough) and where to write what happened (`-hexicon-test=<file>`)
//! and the walkthroughs that pass, printed (`-hexicon-print=<file>`). The
//! scenario runner (Hexad's extension, extensions/scenarios) does so
//! at the first prompt, a line for each scenario or walkthrough, its notes
//! and its failure, and a last line, and quits:
//!
//! ```text
//! scenario <tab> name <tab> passed|failed|not run <tab> steps <tab> after
//! walkthrough <tab> name <tab> passed|failed <tab> steps <tab>
//! note <tab> name <tab> what is noted
//! failure <tab> name <tab> step <tab> command <tab> why <tab> what failed
//!         <tab> where <tab> what the game said <tab> kind
//!         <tab> scenario <tab> step in it
//! choice-moment <tab> moment <tab> begun|never begun <tab> symbol
//! choice <tab> moment <tab> label <tab> chosen|listed|never listed
//!        <tab> symbol
//! done <tab> passed <tab> failed <tab> not run
//! ```
//!
//! A failure's kind is the check that failed (mentions, avoids, expect,
//! check, until), or ended, or missing; in a walkthrough, its scenario and
//! the step in it are said too. A choice's symbol is the name in the
//! program of its moment, or of the thing it is in.
//!
//! The exit status is 0 if everything played passed, 1 if anything failed
//! or was not run, and 2 if the game could not be built or did not play
//! them. With `--report <file>`, what happened is written there too, in
//! JSON, for programs (VS Code's Testing view): see [`json_report`].

use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode, Stdio};

use crate::build::BuildMessage;
use crate::doc::TestPlaces;

/// The image the game is built into, the file its results go to, and the
/// file a printed walkthrough goes to, in the game's folder; all are
/// deleted afterwards.
const IMAGE: &str = ".hexicon-test.hxg";
const RESULTS: &str = ".hexicon-test-results.txt";
const PRINTED: &str = ".hexicon-test-printed.md";

/// The clock a game is played with, as game-check plays it.
const CLOCK: &str = "2000-01-01T09:15:00";

/// What to play, and how.
#[derive(Default)]
struct Asked<'a> {
    names: Vec<&'a str>,
    walkthroughs: bool,
    print: bool,
    for_players: bool,
}

pub(crate) fn run(args: &[&str], usage: &str) -> ExitCode {
    let mut manifest: Option<&str> = None;
    let mut transcript: Option<&str> = None;
    let mut report_file: Option<&str> = None;
    let mut library_dirs: Vec<&str> = Vec::new();
    let mut asked = Asked::default();
    let mut rest = args;
    while let Some((first, tail)) = rest.split_first() {
        match (*first, tail) {
            ("-f", [path, tail @ ..]) => {
                manifest = Some(path);
                rest = tail;
            }
            ("--library-path", [dir, tail @ ..]) => {
                library_dirs.push(dir);
                rest = tail;
            }
            ("--transcript", [path, tail @ ..]) => {
                transcript = Some(path);
                rest = tail;
            }
            ("--report", [path, tail @ ..]) => {
                report_file = Some(path);
                rest = tail;
            }
            ("--walkthroughs", _) => {
                asked.walkthroughs = true;
                rest = tail;
            }
            ("--for-players", _) => {
                asked.for_players = true;
                rest = tail;
            }
            ("--print", [name, tail @ ..]) => {
                asked.print = true;
                asked.names = vec![name];
                rest = tail;
            }
            (option, _) if option.starts_with('-') => {
                eprint!("{usage}");
                return ExitCode::from(2);
            }
            (name, _) => {
                asked.names.push(name);
                rest = tail;
            }
        }
    }
    if (asked.print && asked.names.len() != 1) || (asked.for_players && !asked.print) {
        eprint!("{usage}");
        return ExitCode::from(2);
    }

    // The game's folder: the manifest's, or this one.
    let folder = match manifest {
        Some(path) if Path::new(path).is_dir() => PathBuf::from(path),
        Some(path) => Path::new(path)
            .parent()
            .map(Path::to_path_buf)
            .unwrap_or_default(),
        None => PathBuf::from("."),
    };
    let folder = if folder.as_os_str().is_empty() {
        PathBuf::from(".")
    } else {
        folder
    };
    let image = folder.join(IMAGE);
    let results = folder.join(RESULTS);
    let printed = folder.join(PRINTED);
    let _ = std::fs::remove_file(&results);
    let _ = std::fs::remove_file(&printed);

    let mut project_args = vec!["-d".to_owned()];
    if let Some(path) = manifest {
        project_args.push("-f".to_owned());
        project_args.push(path.to_owned());
    }
    for dir in &library_dirs {
        project_args.push("--library-path".to_owned());
        project_args.push((*dir).to_owned());
    }
    // What the report, if one is asked for, says of a game that went no
    // further than this.
    let write_report = |text: String| {
        if let Some(path) = report_file
            && let Err(error) = std::fs::write(path, text)
        {
            eprintln!("hexicon test: {path}: {error}");
        }
    };
    let mut messages = Vec::new();
    let built = crate::build::build_project(
        &project_args,
        usage,
        None,
        Some(&image.to_string_lossy()),
        report_file.map(|_| &mut messages),
    );
    if built != ExitCode::SUCCESS {
        eprintln!("hexicon test: the game could not be built");
        write_report(json_report(&Reported::NotBuilt(&messages)));
        return ExitCode::from(2);
    }

    // The places are read only for a report; the problems, always.
    let places = if report_file.is_some() {
        crate::doc::test_places(&project_args)
    } else {
        TestPlaces {
            problems: crate::doc::choice_problems(&project_args)
                .into_iter()
                .map(|problem| (problem, None))
                .collect(),
            ..TestPlaces::default()
        }
    };
    let problems: Vec<&str> = places.problems.iter().map(|(p, _)| p.as_str()).collect();
    let played = play(&folder, &asked);
    let _ = std::fs::remove_file(&image);
    let said = match played {
        Ok(said) => said,
        Err(error) => {
            eprintln!("hexicon test: the game could not be played: {error}");
            write_report(json_report(&Reported::NotPlayed {
                messages: &messages,
                problem: format!("the game could not be played: {error}"),
            }));
            return ExitCode::from(2);
        }
    };
    if let Some(path) = transcript
        && let Err(error) = std::fs::write(path, &said)
    {
        eprintln!("hexicon test: {path}: {error}");
    }
    let lines = std::fs::read_to_string(&results).unwrap_or_default();
    let document = std::fs::read_to_string(&printed).unwrap_or_default();
    let _ = std::fs::remove_file(&results);
    let _ = std::fs::remove_file(&printed);

    let Some(results) = parse(&lines) else {
        eprintln!(
            "hexicon test: the game did not play its scenarios: does its \
             manifest include Hexad's extensions/scenarios? What it printed \
             ends:"
        );
        let tail: Vec<&str> = said.lines().rev().take(12).collect();
        for line in tail.iter().rev() {
            eprintln!("    {line}");
        }
        write_report(json_report(&Reported::NotPlayed {
            messages: &messages,
            problem: "the game did not play its scenarios: does its manifest include \
                      Hexad's extensions/scenarios?"
                .to_owned(),
        }));
        return ExitCode::from(2);
    };
    let (mut text, status) = text_report(&results, transcript.is_some());
    write_report(json_report(&Reported::Played {
        messages: &messages,
        results: &results,
        places: &places,
        status: if status == ExitCode::SUCCESS { 0 } else { 1 },
    }));
    if !problems.is_empty() {
        text.push_str("\nThe game's choices, read:\n");
        for problem in &problems {
            let _ = writeln!(text, "    {problem}");
        }
    }
    if asked.print {
        // The walkthrough is the output; how it went is said aside.
        eprint!("{text}");
        if status == ExitCode::SUCCESS {
            print!("{document}");
        }
    } else {
        print!("{text}");
    }
    status
}

/// Play the game built for testing, telling it what to play: what it
/// printed.
fn play(folder: &Path, asked: &Asked<'_>) -> std::io::Result<String> {
    let mut command = Command::new(std::env::current_exe()?);
    command
        .args([
            "run",
            "--no-random",
            "--clock",
            CLOCK,
            "--plain",
            "--no-pause",
            IMAGE,
        ])
        .arg(format!("-hexicon-test={RESULTS}"))
        .args(asked.names.iter().map(|name| format!("-scenario={name}")))
        .current_dir(folder)
        .env("TZ", "Etc/UTC")
        .stdin(Stdio::null());
    if asked.walkthroughs {
        command.arg("-walkthroughs");
    }
    if asked.print {
        command.arg(format!("-hexicon-print={PRINTED}"));
    }
    if asked.for_players {
        command.arg("-for-players");
    }
    let done = command.output()?;
    let mut said = String::from_utf8_lossy(&done.stdout).replace('\r', "");
    said.push_str(&String::from_utf8_lossy(&done.stderr).replace('\r', ""));
    Ok(said)
}

/// One scenario or walkthrough, as the game reported it.
struct Outcome {
    walkthrough: bool,
    name: String,
    outcome: String,
    steps: String,
    after: String,
    notes: Vec<String>,
    failure: Option<Failure>,
}

/// Where a scenario or walkthrough failed, as the game reported it.
struct Failure {
    /// The step: its number, or in a walkthrough `3 of “Saving it”`.
    step: String,
    command: String,
    why: String,
    /// What failed, in words.
    what: String,
    /// Where the check that failed is written (`file:line`), if it is.
    place: String,
    /// What the game said at the step.
    said: String,
    /// The check that failed: mentions, avoids, expect, check, until,
    /// ended, or missing; empty from a game built on an older Hexad.
    kind: String,
    /// In a walkthrough, the scenario the step is in, and its number there.
    scenario: String,
    step_in: String,
}

/// What became of a moment or a choice, as the game reported it.
enum Covered {
    Moment {
        name: String,
        state: String,
        symbol: String,
    },
    Choice {
        moment: String,
        label: String,
        state: String,
        symbol: String,
    },
}

/// What the game reported.
struct Results {
    outcomes: Vec<Outcome>,
    covered: Vec<Covered>,
    passed: usize,
    failed: usize,
    not_run: usize,
}

/// What the game reported, read from its lines; or None if it reported
/// nothing.
fn parse(lines: &str) -> Option<Results> {
    let mut outcomes: Vec<Outcome> = Vec::new();
    let mut covered = Vec::new();
    let mut done: Option<(usize, usize, usize)> = None;
    let owned = |s: &&str| (*s).to_owned();
    for line in lines.lines() {
        let fields: Vec<&str> = line.split('\t').collect();
        match fields.as_slice() {
            [
                kind @ ("scenario" | "walkthrough"),
                name,
                outcome,
                steps,
                after,
            ] => {
                outcomes.push(Outcome {
                    walkthrough: *kind == "walkthrough",
                    name: (*name).to_owned(),
                    outcome: (*outcome).to_owned(),
                    steps: (*steps).to_owned(),
                    after: (*after).to_owned(),
                    notes: Vec::new(),
                    failure: None,
                });
            }
            ["note", name, note] => {
                if let Some(found) = outcomes.iter_mut().rfind(|o| o.name == *name) {
                    found.notes.push((*note).to_owned());
                }
            }
            ["failure", name, rest @ ..] if rest.len() == 6 || rest.len() == 9 => {
                let more = |n: usize| rest.get(n).map(owned).unwrap_or_default();
                if let Some(found) = outcomes.iter_mut().rfind(|o| o.name == *name) {
                    found.failure = Some(Failure {
                        step: more(0),
                        command: more(1),
                        why: more(2),
                        what: more(3),
                        place: more(4),
                        said: more(5),
                        kind: more(6),
                        scenario: more(7),
                        step_in: more(8),
                    });
                }
            }
            ["choice-moment", name, state, symbol @ ..] if symbol.len() <= 1 => {
                covered.push(Covered::Moment {
                    name: (*name).to_owned(),
                    state: (*state).to_owned(),
                    symbol: symbol.first().map(owned).unwrap_or_default(),
                });
            }
            ["choice", moment, label, state, symbol @ ..] if symbol.len() <= 1 => {
                covered.push(Covered::Choice {
                    moment: (*moment).to_owned(),
                    label: (*label).to_owned(),
                    state: (*state).to_owned(),
                    symbol: symbol.first().map(owned).unwrap_or_default(),
                });
            }
            ["done", passed, failed, not_run] => {
                done = match (passed.parse(), failed.parse(), not_run.parse()) {
                    (Ok(p), Ok(f), Ok(n)) => Some((p, f, n)),
                    _ => None,
                };
            }
            _ => {}
        }
    }
    let (passed, failed, not_run) = done?;
    Some(Results {
        outcomes,
        covered,
        passed,
        failed,
        not_run,
    })
}

impl Covered {
    /// What was not played of it, in words; or None if it was played.
    fn unplayed(&self) -> Option<String> {
        match self {
            Covered::Moment { name, state, .. } => {
                (state != "begun").then(|| format!("{name}: never begun"))
            }
            Covered::Choice {
                moment,
                label,
                state,
                ..
            } => match state.as_str() {
                "chosen" => None,
                "listed" => Some(format!("{moment}: \"{label}\", listed, never chosen")),
                _ => Some(format!("{moment}: \"{label}\", never listed")),
            },
        }
    }
}

/// The report of what the game reported, and the exit status.
fn text_report(results: &Results, kept: bool) -> (String, ExitCode) {
    let mut out = String::new();
    if results.outcomes.is_empty() {
        out.push_str("There are no scenarios.\n");
        return (out, ExitCode::SUCCESS);
    }

    for outcome in &results.outcomes {
        let name = if outcome.walkthrough {
            format!("walkthrough: {}", outcome.name)
        } else {
            outcome.name.clone()
        };
        match outcome.outcome.as_str() {
            "passed" => {
                let s = if outcome.steps == "1" { "" } else { "s" };
                let _ = writeln!(out, "passed   {name} ({} step{s})", outcome.steps);
            }
            "not run" => {
                let _ = writeln!(
                    out,
                    "not run  {name}, since \"{}\" did not pass",
                    outcome.after
                );
            }
            _ => {
                let _ = writeln!(out, "FAILED   {name}");
                if let Some(failure) = &outcome.failure {
                    let step = &failure.step;
                    if step == "0" {
                        // Not a step: the scenario itself, which is not
                        // there.
                    } else if failure.command.is_empty() {
                        let _ = writeln!(out, "           at step {step}");
                    } else {
                        let _ = writeln!(out, "           at step {step}: {}", failure.command);
                    }
                    if !failure.why.is_empty() {
                        let _ = writeln!(out, "           why: {}", failure.why);
                    }
                    if failure.place.is_empty() {
                        let _ = writeln!(out, "           failed: {}", failure.what);
                    } else {
                        let _ = writeln!(
                            out,
                            "           failed: {}, at {}",
                            failure.what, failure.place
                        );
                    }
                    if !failure.said.is_empty() {
                        let _ = writeln!(out, "           the game said: {}", failure.said);
                    }
                }
            }
        }
        for note in &outcome.notes {
            let _ = writeln!(out, "           note: {note}");
        }
    }
    let (passed, failed, not_run) = (results.passed, results.failed, results.not_run);
    let _ = writeln!(out, "\n{passed} passed, {failed} failed, {not_run} not run");
    let choices = results
        .covered
        .iter()
        .filter(|c| matches!(c, Covered::Choice { .. }))
        .count();
    let unplayed: Vec<String> = results
        .covered
        .iter()
        .filter_map(Covered::unplayed)
        .collect();
    if choices > 0 {
        if unplayed.is_empty() {
            let _ = writeln!(out, "Every choice was chosen in a scenario.");
        } else {
            let _ = writeln!(out, "\nWhat the scenarios did not play of the choices:");
            for line in &unplayed {
                let _ = writeln!(out, "    {line}");
            }
        }
    }
    if failed + not_run == 0 {
        return (out, ExitCode::SUCCESS);
    }
    if !kept {
        out.push_str("(--transcript <file> keeps the whole of what the game said)\n");
    }
    (out, ExitCode::FAILURE)
}

/// How far `hexicon test` got, for its report.
enum Reported<'a> {
    /// The game could not be built: what the build said.
    NotBuilt(&'a [BuildMessage]),
    /// It was built, and did not play its scenarios: why.
    NotPlayed {
        messages: &'a [BuildMessage],
        problem: String,
    },
    /// It played them: what happened, and where it is written.
    Played {
        messages: &'a [BuildMessage],
        results: &'a Results,
        places: &'a TestPlaces,
        status: u8,
    },
}

/// A value of JSON.
enum Json {
    Null,
    Bool(bool),
    Number(usize),
    Text(String),
    List(Vec<Json>),
    Object(Vec<(&'static str, Json)>),
}

impl Json {
    fn text(s: &str) -> Json {
        Json::Text(s.to_owned())
    }

    /// Text, or null if it is empty.
    fn text_or_null(s: &str) -> Json {
        if s.is_empty() {
            Json::Null
        } else {
            Json::text(s)
        }
    }

    /// A number, or null if it is none, or 0.
    fn count_or_null(s: &str) -> Json {
        match s.parse::<usize>() {
            Ok(n) if n > 0 => Json::Number(n),
            _ => Json::Null,
        }
    }

    /// Written out, indented by `depth` levels.
    fn write(&self, out: &mut String, depth: usize) {
        let pad = |out: &mut String, depth: usize| out.push_str(&"  ".repeat(depth));
        match self {
            Json::Null => out.push_str("null"),
            Json::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
            Json::Number(n) => out.push_str(&n.to_string()),
            Json::Text(s) => {
                out.push('"');
                for c in s.chars() {
                    match c {
                        '"' => out.push_str("\\\""),
                        '\\' => out.push_str("\\\\"),
                        '\n' => out.push_str("\\n"),
                        '\r' => out.push_str("\\r"),
                        '\t' => out.push_str("\\t"),
                        c if (c as u32) < 0x20 => {
                            let _ = write!(out, "\\u{:04x}", c as u32);
                        }
                        c => out.push(c),
                    }
                }
                out.push('"');
            }
            Json::List(items) if items.is_empty() => out.push_str("[]"),
            Json::List(items) => {
                out.push_str("[\n");
                for (n, item) in items.iter().enumerate() {
                    pad(out, depth + 1);
                    item.write(out, depth + 1);
                    out.push_str(if n + 1 < items.len() { ",\n" } else { "\n" });
                }
                pad(out, depth);
                out.push(']');
            }
            Json::Object(fields) => {
                out.push_str("{\n");
                for (n, (key, value)) in fields.iter().enumerate() {
                    pad(out, depth + 1);
                    let _ = write!(out, "\"{key}\": ");
                    value.write(out, depth + 1);
                    out.push_str(if n + 1 < fields.len() { ",\n" } else { "\n" });
                }
                pad(out, depth);
                out.push('}');
            }
        }
    }
}

/// A file as the report names it: a built-in one (`<hexicon>/...`) as it
/// is, and the game's own with its whole path.
fn report_file(file: &str) -> String {
    let path = Path::new(file);
    if file.starts_with('<') || path.is_absolute() {
        return file.to_owned();
    }
    let file = file.strip_prefix("./").unwrap_or(file);
    match std::env::current_dir() {
        Ok(dir) => dir.join(file).to_string_lossy().into_owned(),
        Err(_) => file.to_owned(),
    }
}

/// A place in the report: its file and line.
fn place_json(file: &str, line: u32) -> Json {
    Json::Object(vec![
        ("file", Json::Text(report_file(file))),
        ("line", Json::Number(line as usize)),
    ])
}

/// A place as the game gives it (`file:line`), or null.
fn place_text_json(place: &str) -> Json {
    match place.rsplit_once(':') {
        Some((file, line)) if !file.is_empty() => match line.trim().parse::<u32>() {
            Ok(line) => place_json(file, line),
            Err(_) => Json::Null,
        },
        _ => Json::Null,
    }
}

fn doc_place_json(place: Option<&hexicon_compiler::DocPlace>) -> Json {
    place.map_or(Json::Null, |p| place_json(&p.file, p.line))
}

/// What `hexicon test --report` writes: JSON, for programs.
///
/// ```text
/// {
///   "version": 1,
///   "status": 0 | 1 | 2,          the exit status
///   "built": true | false,
///   "played": true | false,       whether its scenarios were played
///   "problem": text | null,       why they were not, if it was built
///   "buildMessages": [{ "severity", "file", "line", "message" }],
///   "passed", "failed", "notRun": numbers,
///   "results": [{
///     "name", "walkthrough": true | false,
///     "outcome": "passed" | "failed" | "not run",
///     "steps": number,            the steps it played
///     "after": name | null,       the scenario it starts after
///     "place": place | null,      where it is written
///     "notes": [text],
///     "failure": null | {
///       "step": number | null,    the step that failed (in a walkthrough,
///                                 counted from the walkthrough's start)
///       "scenario": name | null,  in a walkthrough, the scenario it is in
///       "stepInScenario": number | null,
///       "command", "why": text,
///       "kind": "mentions" | "avoids" | "expect" | "check" | "until" |
///               "ended" | "missing" | null,
///       "description": text,      what failed, in words
///       "place": place | null,    where the check that failed is written,
///                                 if it is a method (expect, a check,
///                                 until), not a value (mentions, avoids)
///       "stepPlace": place | null, where the step is written
///       "gameSaid": text
///     }
///   }],
///   "choices": {
///     "count": number,            how many choices the game has
///     "unplayed": [{ "moment", "label": text | null,
///                    "state": "never begun" | "listed" | "never listed",
///                    "place": place | null }],
///     "problems": [{ "message", "place": place | null }]
///   }
/// }
/// ```
///
/// A place is `{ "file", "line" }`: the game's own files by their whole
/// paths, Hexicon's built-in ones as `<hexicon>/...`.
fn json_report(reported: &Reported<'_>) -> String {
    let (status, built, played, problem, messages) = match reported {
        Reported::NotBuilt(messages) => (2, false, false, None, *messages),
        Reported::NotPlayed { messages, problem } => (2, true, false, Some(problem), *messages),
        Reported::Played {
            messages, status, ..
        } => (*status, true, true, None, *messages),
    };
    let messages = messages
        .iter()
        .map(|m| {
            Json::Object(vec![
                ("severity", Json::text(m.severity)),
                (
                    "file",
                    if m.file.is_empty() {
                        Json::Null
                    } else {
                        Json::Text(report_file(&m.file))
                    },
                ),
                (
                    "line",
                    if m.line == 0 {
                        Json::Null
                    } else {
                        Json::Number(m.line as usize)
                    },
                ),
                ("message", Json::text(&m.message)),
            ])
        })
        .collect();
    let mut fields = vec![
        ("version", Json::Number(1)),
        ("status", Json::Number(usize::from(status))),
        ("built", Json::Bool(built)),
        ("played", Json::Bool(played)),
        ("problem", problem.map_or(Json::Null, |p| Json::text(p))),
        ("buildMessages", Json::List(messages)),
    ];
    let (results, places) = match reported {
        Reported::Played {
            results, places, ..
        } => (Some(*results), Some(*places)),
        _ => (None, None),
    };
    let count = |n: Option<usize>| Json::Number(n.unwrap_or(0));
    fields.push(("passed", count(results.map(|r| r.passed))));
    fields.push(("failed", count(results.map(|r| r.failed))));
    fields.push(("notRun", count(results.map(|r| r.not_run))));
    let empty = TestPlaces::default();
    let places = places.unwrap_or(&empty);
    let outcomes = results.map_or(&[][..], |r| &r.outcomes[..]);
    let outcomes = outcomes
        .iter()
        .map(|o| {
            let scenario_of = |name: &str| places.scenarios.iter().find(|(n, ..)| n == name);
            let place = scenario_of(&o.name).map(|(_, place, _)| place);
            let failure = o.failure.as_ref().map_or(Json::Null, |f| {
                let step = if f.scenario.is_empty() {
                    Json::count_or_null(&f.step)
                } else {
                    // A walkthrough's step, counted on from its start.
                    match (o.steps.parse::<usize>(), f.step_in.parse::<usize>()) {
                        (Ok(before), Ok(n)) => Json::Number(before + n),
                        _ => Json::Null,
                    }
                };
                // The step's own place: the n-th of its scenario's.
                let (scenario, n) = if f.scenario.is_empty() {
                    (o.name.as_str(), f.step.parse::<usize>().ok())
                } else {
                    (f.scenario.as_str(), f.step_in.parse::<usize>().ok())
                };
                let step_place = n
                    .filter(|n| *n > 0)
                    .and_then(|n| scenario_of(scenario)?.2.get(n - 1));
                Json::Object(vec![
                    ("step", step),
                    ("scenario", Json::text_or_null(&f.scenario)),
                    ("stepInScenario", Json::count_or_null(&f.step_in)),
                    ("command", Json::text(&f.command)),
                    ("why", Json::text(&f.why)),
                    ("kind", Json::text_or_null(&f.kind)),
                    ("description", Json::text(&f.what)),
                    ("place", place_text_json(&f.place)),
                    ("stepPlace", doc_place_json(step_place)),
                    ("gameSaid", Json::text(&f.said)),
                ])
            });
            Json::Object(vec![
                ("name", Json::text(&o.name)),
                ("walkthrough", Json::Bool(o.walkthrough)),
                ("outcome", Json::text(&o.outcome)),
                ("steps", Json::Number(o.steps.parse().unwrap_or(0))),
                ("after", Json::text_or_null(&o.after)),
                ("place", doc_place_json(place)),
                (
                    "notes",
                    Json::List(o.notes.iter().map(|n| Json::text(n)).collect()),
                ),
                ("failure", failure),
            ])
        })
        .collect();
    fields.push(("results", Json::List(outcomes)));
    let covered = results.map_or(&[][..], |r| &r.covered[..]);
    let choices = covered
        .iter()
        .filter(|c| matches!(c, Covered::Choice { .. }))
        .count();
    let unplayed = covered
        .iter()
        .filter(|c| c.unplayed().is_some())
        .map(|c| match c {
            Covered::Moment {
                name,
                state,
                symbol,
            } => Json::Object(vec![
                ("moment", Json::text(name)),
                ("label", Json::Null),
                ("state", Json::text(state)),
                ("place", doc_place_json(places.objects.get(symbol))),
            ]),
            Covered::Choice {
                moment,
                label,
                state,
                symbol,
            } => {
                let place = places
                    .choices
                    .iter()
                    .find(|(owner, l, _)| owner == symbol && l == label)
                    .map(|(_, _, place)| place)
                    .or_else(|| places.objects.get(symbol));
                Json::Object(vec![
                    ("moment", Json::text(moment)),
                    ("label", Json::text(label)),
                    ("state", Json::text(state)),
                    ("place", doc_place_json(place)),
                ])
            }
        })
        .collect();
    let problems = places
        .problems
        .iter()
        .map(|(message, place)| {
            Json::Object(vec![
                ("message", Json::text(message)),
                ("place", doc_place_json(place.as_ref())),
            ])
        })
        .collect();
    fields.push((
        "choices",
        Json::Object(vec![
            ("count", Json::Number(choices)),
            ("unplayed", Json::List(unplayed)),
            ("problems", Json::List(problems)),
        ]),
    ));
    let mut out = String::new();
    Json::Object(fields).write(&mut out, 0);
    out.push('\n');
    out
}

#[cfg(test)]
mod tests {
    use super::{parse, text_report};

    /// The text report of the results, and its exit status.
    fn report(lines: &str, kept: bool) -> Option<(String, std::process::ExitCode)> {
        parse(lines).map(|results| text_report(&results, kept))
    }

    #[test]
    fn what_the_scenarios_did_not_play_of_the_choices_is_said() {
        let lines = "scenario\tsaving it\tpassed\t2\t\n\
                     choice-moment\tsnap\tbegun\n\
                     choice\tsnap\tGrab it\tchosen\n\
                     choice\tsnap\tShout\tlisted\n\
                     choice-moment\toffer\tnever begun\n\
                     choice\toffer\tBuy\tnever listed\n\
                     done\t1\t0\t0\n";
        let (text, _) = report(lines, false).expect("a report");
        assert!(text.contains("What the scenarios did not play of the choices:"));
        assert!(text.contains("snap: \"Shout\", listed, never chosen"));
        assert!(text.contains("offer: never begun"));
        assert!(text.contains("offer: \"Buy\", never listed"));
        assert!(!text.contains("Grab it"));
        // With every choice chosen, it says so; with none, nothing.
        let all = "scenario\tsaving it\tpassed\t2\t\n\
                   choice-moment\tsnap\tbegun\n\
                   choice\tsnap\tGrab it\tchosen\n\
                   done\t1\t0\t0\n";
        let (text, _) = report(all, false).expect("a report");
        assert!(text.contains("Every choice was chosen in a scenario."));
        let none = "scenario\tsaving it\tpassed\t2\t\ndone\t1\t0\t0\n";
        let (text, _) = report(none, false).expect("a report");
        assert!(!text.contains("choice"));
    }

    /// What the game reports of a walkthrough that fails in its second
    /// scenario, a name that is no scenario, and a choice not chosen.
    const FAILED: &str = "scenario\tgetting in\tpassed\t2\t\n\
        walkthrough\tthe way\tfailed\t2\t\n\
        note\tthe way\tringing has given conditions\n\
        failure\tthe way\t1 of \u{201c}ringing\u{201d}\tpull rope\tIt rings.\t\
        expect is not true\ttests.hxn:41\tNothing.\texpect\tringing\t1\n\
        scenario\tnothing\tfailed\t0\t\n\
        failure\tnothing\t0\t\t\tthere is no scenario or walkthrough of that name\t\t\tmissing\t\t\n\
        choice-moment\tsnap\tbegun\tsnap\n\
        choice\tsnap\tShout \"hey\"\tlisted\tsnap\n\
        done\t1\t2\t0\n";

    #[test]
    fn the_text_report_is_as_it_was_with_the_new_fields() {
        let (text, status) = report(FAILED, true).expect("a report");
        assert_eq!(status, std::process::ExitCode::FAILURE);
        assert!(text.contains(
            "FAILED   walkthrough: the way\n           \
             at step 1 of \u{201c}ringing\u{201d}: pull rope\n           why: It rings.\n           \
             failed: expect is not true, at tests.hxn:41\n           the game said: Nothing.\n           \
             note: ringing has given conditions\n"
        ));
        assert!(text.contains(
            "FAILED   nothing\n           failed: there is no scenario or walkthrough of that name\n"
        ));
        // A game on an older Hexad, with fewer fields, is read as before.
        let old = "scenario\tx\tfailed\t1\t\n\
                   failure\tx\t1\tlook\t\tit does not mention \u{201c}y\u{201d}\t\tDark.\n\
                   done\t0\t1\t0\n";
        let (text, _) = report(old, true).expect("a report");
        assert!(text.contains("at step 1: look\n           failed: it does not mention"));
    }

    #[test]
    fn the_json_report_says_where_and_what_failed() {
        use super::{Reported, json_report};
        use crate::doc::TestPlaces;
        use hexicon_compiler::DocPlace;
        let at = |line| DocPlace {
            file: "<hexicon>/tests.hxn".to_owned(),
            line,
        };
        let places = TestPlaces {
            scenarios: vec![
                ("ringing".to_owned(), at(30), vec![at(31), at(35)]),
                ("the way".to_owned(), at(50), Vec::new()),
            ],
            objects: [("snap".to_owned(), at(70))].into_iter().collect(),
            choices: vec![("snap".to_owned(), "Shout \"hey\"".to_owned(), at(72))],
            problems: vec![("snap: it has no way out".to_owned(), Some(at(70)))],
        };
        let results = parse(FAILED).expect("results");
        let json = json_report(&Reported::Played {
            messages: &[],
            results: &results,
            places: &places,
            status: 1,
        });
        for wanted in [
            "\"version\": 1,\n",
            "\"status\": 1,\n",
            "\"passed\": 1,\n  \"failed\": 2,\n  \"notRun\": 0,\n",
            // The walkthrough's step: two before, and the first of
            // "ringing", which is written at line 31.
            "\"step\": 3,\n        \"scenario\": \"ringing\",\n        \"stepInScenario\": 1,\n",
            "\"kind\": \"expect\",\n        \"description\": \"expect is not true\",\n        \
             \"place\": {\n          \"file\": ",
            "\"stepPlace\": {\n          \"file\": \"<hexicon>/tests.hxn\",\n          \"line\": 31\n",
            "\"place\": {\n        \"file\": \"<hexicon>/tests.hxn\",\n        \"line\": 50\n",
            "\"notes\": [\n        \"ringing has given conditions\"\n      ],\n",
            "\"step\": null,",
            "\"kind\": \"missing\",",
            "\"count\": 1,\n",
            "\"label\": \"Shout \\\"hey\\\"\",\n        \"state\": \"listed\",\n        \"place\": {\n          \
             \"file\": \"<hexicon>/tests.hxn\",\n          \"line\": 72\n",
            "\"message\": \"snap: it has no way out\",",
        ] {
            assert!(json.contains(wanted), "no {wanted:?} in:\n{json}");
        }
        // A game that could not be built says what its build said.
        let messages = [crate::build::BuildMessage {
            severity: "error",
            file: "<hexicon>/start.hxn".to_owned(),
            line: 3,
            message: "a\tb".to_owned(),
        }];
        let json = json_report(&Reported::NotBuilt(&messages));
        assert!(json.contains("\"status\": 2,\n  \"built\": false,\n  \"played\": false,\n"));
        assert!(
            json.contains("\"line\": 3,\n      \"message\": \"a\\tb\"\n"),
            "{json}"
        );
    }
}