hexicon-compiler 0.2.0

The Hexicon compiler: source text to a program image
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
//! Tests in English: scenarios, their steps and what each checks, and
//! walkthroughs, for Hexad's scenarios extension and `hexicon test`.
//!
//! ```text
//! The test "getting in" is "The key is in the box."
//! Type "open box" to find the key: it says "brass key".
//! Type "take key. unlock door with key" to get in: the door is unlocked
//! and "unlocking the door" is scored.
//!
//! The test "winning" is "The lamp ends the story."
//! It starts after "getting in".
//! Wait up to 2 turns for the farmer: the story has ended in victory.
//!
//! The walkthrough "the way through" plays "getting in", then "winning".
//! ```
//!
//! A test is a `Scenario`, a "Type" a `Step` in it, and a "Wait" an
//! `Await`; what follows the colon is what the step checks.

use super::rules::{Cond, ENDINGS};
use super::{
    Kind, Phrase, Reader, Tok, Token, identifier, is_word, list_of, phrase, shown, word_of,
};

/// What a step checks.
#[derive(Debug, Clone)]
pub(super) enum Check {
    /// It says "brass key"; it does not say "locked".
    Says { not: bool, text: String },
    /// "unlocking the door" is scored.
    Scored { not: bool, label: String, line: u32 },
    /// The story has ended (in victory).
    Ended {
        not: bool,
        ending: Option<&'static str>,
    },
    /// The moment "the plank snaps" is current; no moment is current.
    Moment { name: Option<String>, line: u32 },
    /// A condition, as rules have.
    Cond(bool, Cond),
}

#[derive(Debug, Clone)]
pub(super) struct StepRead {
    /// The command, for a "Type"; for a "Wait", how many turns it waits.
    pub(super) command: Option<String>,
    pub(super) within: u32,
    pub(super) why: Option<String>,
    pub(super) checks: Vec<Check>,
    pub(super) line: u32,
}

#[derive(Debug, Clone)]
pub(super) struct Test {
    pub(super) name: String,
    pub(super) purpose: Option<String>,
    pub(super) after: Option<(u32, String)>,
    pub(super) start_at: Option<Phrase>,
    pub(super) holding: Vec<Phrase>,
    pub(super) steps: Vec<StepRead>,
    pub(super) line: u32,
    pub(super) order: usize,
}

#[derive(Debug, Clone)]
pub(super) struct WalkthroughRead {
    pub(super) name: String,
    pub(super) tests: Vec<String>,
    pub(super) line: u32,
    pub(super) order: usize,
}

const TEST_FORM: &str = "A test is said as \"The test \"getting in\" is \"The key is in the \
box.\"\", and its steps after it: \"Type \"open box\" to find the key: it says \"brass \
key\".\", or \"Wait up to 2 turns for the farmer: the story has ended in victory.\"";

const CHECK_FORM: &str = "A step checks what is true after it, as a rule's condition is said \
(\"the player has the key\"), or \"it says \"brass key\"\", \"it does not say \"locked\"\", \
\"\"unlocking the door\" is scored\", \"the story has ended in victory\", or \"the moment \"the \
plank snaps\" is current\", joined by \"and\".";

impl Reader {
    /// A sentence of a test, or of a walkthrough. Whether it was one.
    pub(super) fn test_sentence(&mut self, line: u32, t: &[Token]) -> bool {
        let words: Vec<String> = t.iter().take(3).filter_map(word_of).collect();
        let w: Vec<&str> = words.iter().map(String::as_str).collect();
        let starts_step = matches!(
            w.as_slice(),
            ["type", ..] | ["wait", ..] | ["it", "starts", ..]
        );
        if starts_step {
            match self.open_test {
                Some(test) => {
                    if test != usize::MAX {
                        self.test_step(line, test, t);
                    }
                }
                None => self.problem(
                    line,
                    format!(
                        "\"{}\" is part of a test, and comes after one: \"The test \"getting \
                         in\" is \"...\".\"",
                        shown(t)
                    ),
                ),
            }
            return true;
        }
        self.open_test = None;
        let named = |n: usize| matches!(t.get(n).map(|t| &t.tok), Some(Tok::Text(_)));
        if is_word(t.first(), &["the"]) && is_word(t.get(1), &["test"]) && named(2) {
            self.test(line, t);
            return true;
        }
        if is_word(t.first(), &["the"]) && is_word(t.get(1), &["walkthrough"]) && named(2) {
            self.walkthrough(line, t);
            return true;
        }
        false
    }

    /// "The test "getting in" is "The key is in the box."".
    fn test(&mut self, line: u32, t: &[Token]) {
        let Tok::Text(name) = &t[2].tok else { return };
        let purpose = match &t[3..] {
            [] => None,
            [
                is,
                Token {
                    tok: Tok::Text(purpose),
                    ..
                },
            ] if is_word(Some(is), &["is"]) => Some(purpose.clone()),
            _ => {
                self.problem(line, format!("I can't read \"{}\". {TEST_FORM}", shown(t)));
                self.open_test = Some(usize::MAX);
                return;
            }
        };
        if let Some(other) = self.tests.iter().find(|test| test.name == *name) {
            let first = other.line;
            self.problem(
                line,
                format!("There is already a test called \"{name}\", on line {first}."),
            );
            self.open_test = Some(usize::MAX);
            return;
        }
        self.tests.push(Test {
            name: name.clone(),
            purpose,
            after: None,
            start_at: None,
            holding: Vec::new(),
            steps: Vec::new(),
            line,
            order: self.sentences,
        });
        self.open_test = Some(self.tests.len() - 1);
    }

    /// "The walkthrough "the way through" plays "getting in", then
    /// "winning"."
    fn walkthrough(&mut self, line: u32, t: &[Token]) {
        let Tok::Text(name) = &t[2].tok else { return };
        let mut tests = Vec::new();
        let mut ok = is_word(t.get(3), &["plays"]);
        for token in t.iter().skip(4) {
            match &token.tok {
                Tok::Text(test) => tests.push(test.clone()),
                Tok::Punct(',') => {}
                Tok::Word(w) if matches!(w.to_lowercase().as_str(), "then" | "and") => {}
                _ => ok = false,
            }
        }
        if !ok || tests.is_empty() {
            self.problem(
                line,
                format!(
                    "I can't read \"{}\". A walkthrough is said as \"The walkthrough \"the way \
                     through\" plays \"getting in\", then \"winning\".\"",
                    shown(t)
                ),
            );
            return;
        }
        self.walkthroughs.push(WalkthroughRead {
            name: name.clone(),
            tests,
            line,
            order: self.sentences,
        });
    }

    /// A sentence of the test before it: where it starts, or a step.
    fn test_step(&mut self, line: u32, test: usize, t: &[Token]) {
        let first = word_of(&t[0]).unwrap_or_default();
        if first == "it" {
            self.test_start(line, test, t);
            return;
        }
        // The command, for "Type"; how many turns, for "Wait".
        let (command, within, rest) = if first == "type" {
            match t.get(1).map(|t| &t.tok) {
                Some(Tok::Text(command)) => (Some(command.clone()), 1, &t[2..]),
                _ => {
                    self.problem(
                        line,
                        format!("I can't read \"{}\". A command is typed in quotation marks: \"Type \"open box\".\"", shown(t)),
                    );
                    return;
                }
            }
        } else {
            // Wait up to 2 turns.
            let rest = &t[1..];
            let n = rest.len();
            if n >= 4
                && is_word(rest.first(), &["up"])
                && is_word(rest.get(1), &["to"])
                && is_word(rest.get(3), &["turns", "turn"])
            {
                let count = word_of(&rest[2]).and_then(|w| number(&w));
                let Some(count) = count else {
                    self.problem(line, format!("I can't read \"{}\". A wait is said as \"Wait up to 2 turns for the farmer: ...\".", shown(t)));
                    return;
                };
                (None, count, &rest[4..])
            } else {
                (None, 1, rest)
            }
        };
        // Why it is there, before the colon; what it checks, after it.
        let colon = rest
            .iter()
            .position(|token| matches!(token.tok, Tok::Punct(':')));
        let (why_tokens, check_tokens) = match colon {
            Some(c) => (&rest[..c], &rest[c + 1..]),
            None => (rest, &[][..]),
        };
        let why = if why_tokens.is_empty() {
            None
        } else {
            match reason(why_tokens) {
                Some(why) => Some(why),
                None => {
                    self.problem(
                        line,
                        format!(
                            "I can't read why this step is there: \"{}\". Say it in words, \
                             before a colon: \"Type \"open box\" to find the key: ...\".",
                            shown(why_tokens)
                        ),
                    );
                    return;
                }
            }
        };
        if command.is_none() && check_tokens.is_empty() {
            self.problem(
                line,
                "A wait says what it waits for, after a colon: \"Wait up to 2 turns for the \
                 farmer: the story has ended in victory.\"",
            );
            return;
        }
        let mut checks = Vec::new();
        if !check_tokens.is_empty() {
            for part in split_and(check_tokens) {
                match self.check(line, &part) {
                    Some(check) => checks.push(check),
                    None => return,
                }
            }
        }
        self.tests[test].steps.push(StepRead {
            command,
            within,
            why,
            checks,
            line,
        });
    }

    /// "It starts after "getting in".", "It starts in the Office.", "It
    /// starts with the player holding the key."
    fn test_start(&mut self, line: u32, test: usize, t: &[Token]) {
        let rest = &t[2..];
        let bad = |reader: &mut Self| {
            reader.problem(
                line,
                format!(
                    "I can't read \"{}\". Where a test starts is said as \"It starts after \
                     \"getting in\".\", \"It starts in the Office.\", or \"It starts with the \
                     player holding the key.\"",
                    shown(t)
                ),
            );
        };
        match rest {
            [
                after,
                Token {
                    tok: Tok::Text(name),
                    ..
                },
            ] if is_word(Some(after), &["after"]) => {
                self.tests[test].after = Some((line, name.clone()));
            }
            [first, place @ ..] if is_word(Some(first), &["in", "on"]) => match phrase(place) {
                Some(place) => self.tests[test].start_at = Some(place),
                None => bad(self),
            },
            [with, the, player, holding, things @ ..]
                if is_word(Some(with), &["with"])
                    && is_word(Some(the), &["the"])
                    && is_word(Some(player), &["player"])
                    && is_word(Some(holding), &["holding"]) =>
            {
                match super::split_list(things) {
                    Some(things) if !things.is_empty() => {
                        self.tests[test].holding.extend(things);
                    }
                    _ => bad(self),
                }
            }
            _ => bad(self),
        }
    }

    /// One thing a step checks.
    fn check(&mut self, line: u32, tokens: &[Token]) -> Option<Check> {
        let words: Vec<String> = tokens.iter().filter_map(word_of).collect();
        let w: Vec<&str> = words.iter().map(String::as_str).collect();
        let text = |n: usize| match tokens.get(n).map(|t| &t.tok) {
            Some(Tok::Text(text)) => Some(text.clone()),
            _ => None,
        };
        let bad = |reader: &mut Self| {
            reader.problem(
                line,
                format!("I can't read the check \"{}\". {CHECK_FORM}", shown(tokens)),
            );
            None
        };
        // It says "...".
        if is_word(tokens.first(), &["it"]) {
            return match (w.as_slice(), tokens.len()) {
                (["it", "says"], 3) => text(2).map(|text| Check::Says { not: false, text }),
                (["it", "does", "not", "say"], 5) => {
                    text(4).map(|text| Check::Says { not: true, text })
                }
                _ => None,
            }
            .or_else(|| bad(self));
        }
        // "lighting the lamp" is scored.
        if let Some(label) = text(0) {
            return match w.as_slice() {
                ["is", "scored"] if tokens.len() == 3 => Some(Check::Scored {
                    not: false,
                    label,
                    line,
                }),
                ["is", "not", "scored"] if tokens.len() == 4 => Some(Check::Scored {
                    not: true,
                    label,
                    line,
                }),
                _ => bad(self),
            };
        }
        // The moment "..." is current; no moment is current.
        if let ["the", "moment", "is", "current"] = w.as_slice()
            && let Some(name) = text(2)
            && tokens.len() == 5
        {
            return Some(Check::Moment {
                name: Some(name),
                line,
            });
        }
        if let ["no", "moment", "is", "current"] = w.as_slice() {
            return Some(Check::Moment { name: None, line });
        }
        // The story has ended in victory.
        if let ["the", "story", "has", rest @ ..] = w.as_slice() {
            let (not, rest) = match rest {
                ["not", rest @ ..] => (true, rest),
                rest => (false, rest),
            };
            return match rest {
                ["ended"] => Some(Check::Ended { not, ending: None }),
                ["ended", "in", how] => match ENDINGS.iter().find(|(name, _)| name == how) {
                    Some((_, ending)) => Some(Check::Ended {
                        not,
                        ending: Some(ending),
                    }),
                    None => bad(self),
                },
                _ => bad(self),
            };
        }
        if tokens.iter().any(|t| !matches!(t.tok, Tok::Word(_))) {
            return bad(self);
        }
        self.condition(line, tokens)
            .map(|(not, cond)| Check::Cond(not, cond))
    }

    // ---- the second reading ----

    /// Each test and walkthrough, written.
    pub(super) fn write_tests(&mut self) {
        let tests = std::mem::take(&mut self.tests);
        let mut ids = Vec::new();
        for test in &tests {
            let words: Vec<String> = test
                .name
                .split_whitespace()
                .map(str::to_lowercase)
                .collect();
            let id = self.fresh_id(&words);
            ids.push(id);
        }
        let id_of = |name: &str| {
            tests
                .iter()
                .position(|t| t.name == name)
                .map(|i| ids[i].clone())
        };
        for (n, test) in tests.iter().enumerate() {
            let mut out: Vec<(u32, String)> = Vec::new();
            let line = test.line;
            let mut head = format!("{}: Scenario '{}'", ids[n], single_text(&test.name));
            if let Some(purpose) = &test.purpose {
                head.push_str(&format!(" '{}'", single_text(purpose)));
            }
            out.push((line, head));
            if let Some((l, after)) = &test.after {
                match id_of(after) {
                    Some(id) if id != ids[n] => out.push((*l, format!("    after = {id}"))),
                    Some(_) => self.problem(*l, "A test can't start after itself."),
                    None => {
                        let names: Vec<String> =
                            tests.iter().map(|t| format!("\"{}\"", t.name)).collect();
                        let names: Vec<&str> = names.iter().map(String::as_str).collect();
                        self.problem(
                            *l,
                            format!(
                                "There is no test called \"{after}\". The tests are {}.",
                                list_of(&names, "and")
                            ),
                        );
                    }
                }
            }
            if let Some(place) = &test.start_at
                && let Some(room) = self.resolve_room(place)
            {
                out.push((place.line, format!("    startAt = {}", self.objs[room].id)));
            }
            if !test.holding.is_empty() {
                let mut held = Vec::new();
                for thing in &test.holding {
                    if let Some(i) = self.resolve_obj(thing) {
                        if matches!(self.objs[i].kind, Kind::Room | Kind::Door | Kind::Topic) {
                            let name = self.objs[i].called();
                            self.problem(thing.line, format!("The player can't hold \"{name}\"."));
                        } else {
                            held.push(self.objs[i].id.clone());
                        }
                    }
                }
                out.push((line, format!("    holding = [{}]", held.join(", "))));
            }
            out.push((line, ";".to_owned()));
            for step in &test.steps {
                self.write_step(&mut out, step, &ids[n]);
            }
            self.written_tests.push((test.order, out));
        }
        let walkthroughs = std::mem::take(&mut self.walkthroughs);
        for walk in walkthroughs {
            let mut parts = Vec::new();
            for name in &walk.tests {
                match id_of(name) {
                    Some(id) => parts.push(id),
                    None => self.problem(walk.line, format!("There is no test called \"{name}\".")),
                }
            }
            let words: Vec<String> = walk
                .name
                .split_whitespace()
                .map(str::to_lowercase)
                .collect();
            let id = self.fresh_id(&words);
            let out = vec![(
                walk.line,
                format!(
                    "{id}: Walkthrough '{}' [{}];",
                    single_text(&walk.name),
                    parts.join(", ")
                ),
            )];
            self.written_tests.push((walk.order, out));
        }
    }

    fn write_step(&mut self, out: &mut Vec<(u32, String)>, step: &StepRead, test: &str) {
        let line = step.line;
        let why = step
            .why
            .as_ref()
            .map(|why| format!(" '{}'", single_text(why)))
            .unwrap_or_default();
        match &step.command {
            Some(command) => out.push((line, format!("Step '{}'{why}", single_text(command)))),
            None => out.push((line, format!("Await{why}"))),
        }
        out.push((line, format!("    location = {test}")));
        let mut tests = Vec::new();
        let mut mentions = Vec::new();
        let mut avoids = Vec::new();
        for check in &step.checks {
            match check {
                Check::Says { not, text } => {
                    let quoted = format!("'{}'", single_text(text));
                    if *not {
                        avoids.push(quoted);
                    } else {
                        mentions.push(quoted);
                    }
                }
                Check::Scored { not, label, line } => {
                    match self.achievements.iter().find(|a| a.label == *label) {
                        Some(a) => {
                            tests.push(format!("{}{}.achieved", if *not { "!" } else { "" }, a.id))
                        }
                        None => self.problem(*line, format!("No rule scores \"{label}\".")),
                    }
                }
                Check::Ended { not, ending } => tests.push(match (ending, not) {
                    (Some(e), false) => format!("scenarioMemory.ending == {e}"),
                    (Some(e), true) => format!("scenarioMemory.ending != {e}"),
                    (None, false) => "scenarioMemory.ending != nil".to_owned(),
                    (None, true) => "scenarioMemory.ending == nil".to_owned(),
                }),
                Check::Moment { name, line } => match name {
                    Some(name) => {
                        if let Some(id) = self.moment_id(*line, name) {
                            tests.push(format!("choiceManager.current == {id}"));
                        }
                    }
                    None => tests.push("choiceManager.current == nil".to_owned()),
                },
                Check::Cond(not, cond) => {
                    if let Some(code) = self.cond_code(*not, cond) {
                        tests.push(code);
                    }
                }
            }
        }
        let list = |items: &[String]| match items {
            [one] => one.clone(),
            many => format!("[{}]", many.join(", ")),
        };
        if step.command.is_some() {
            if !tests.is_empty() {
                out.push((line, format!("    expect = ({})", tests.join(" && "))));
            }
            if !mentions.is_empty() {
                out.push((line, format!("    mentions = {}", list(&mentions))));
            }
            if !avoids.is_empty() {
                out.push((line, format!("    avoids = {}", list(&avoids))));
            }
        } else {
            if !mentions.is_empty() || !avoids.is_empty() {
                self.problem(
                    line,
                    "A wait waits for something to be true, not for what is said: check \
                     what is said with the step after it.",
                );
            }
            if !tests.is_empty() {
                out.push((line, format!("    until = ({})", tests.join(" && "))));
            }
            out.push((line, format!("    within = {}", step.within)));
        }
        out.push((line, ";".to_owned()));
    }

    /// A name in Hexicon not yet given, made from words.
    pub(super) fn fresh_id(&mut self, words: &[String]) -> String {
        let mut id = identifier(words);
        if super::RESERVED.contains(&id.as_str()) {
            id.push_str("Obj");
        }
        let base = id.clone();
        let mut n = 2;
        while self.used_ids.contains(&id) {
            id = format!("{base}{n}");
            n += 1;
        }
        self.used_ids.push(id.clone());
        id
    }
}

/// Why a step is there, from its words: "to find the key", "To find the
/// key."
fn reason(tokens: &[Token]) -> Option<String> {
    // "Type "take key", to have it": the comma after the command is not
    // the reason's.
    let tokens = match tokens {
        [
            Token {
                tok: Tok::Punct(','),
                ..
            },
            rest @ ..,
        ] => rest,
        tokens => tokens,
    };
    let mut out = String::new();
    for token in tokens {
        match &token.tok {
            Tok::Word(word) => {
                if !out.is_empty() {
                    out.push(' ');
                }
                out.push_str(word);
            }
            Tok::Punct(c @ (',' | ';')) => out.push(*c),
            _ => return None,
        }
    }
    let mut chars = out.chars();
    let first = chars.next()?;
    let mut why: String = first.to_uppercase().chain(chars).collect();
    if !why.ends_with(['.', '?', '!']) {
        why.push('.');
    }
    Some(why)
}

/// A number of turns, in digits or words.
fn number(word: &str) -> Option<u32> {
    let n = match word {
        "one" => 1,
        "two" => 2,
        "three" => 3,
        "four" => 4,
        "five" => 5,
        "six" => 6,
        "seven" => 7,
        "eight" => 8,
        "nine" => 9,
        "ten" => 10,
        digits => digits.parse().ok()?,
    };
    (n > 0).then_some(n)
}

/// Quoted text, already Hexicon text, for a string in single quotes.
fn single_text(text: &str) -> String {
    text.replace('\'', "\\'")
}

/// Tokens split at each "and" that is a word, not inside quoted text.
fn split_and(tokens: &[Token]) -> Vec<Vec<Token>> {
    let mut parts = vec![Vec::new()];
    for token in tokens {
        if is_word(Some(token), &["and"]) {
            parts.push(Vec::new());
        } else if let Some(last) = parts.last_mut() {
            last.push(token.clone());
        }
    }
    parts
}

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

    const WORLD: &str = "The Hall is a room. The Yard is a room north of the Hall.\n\
                         The player is in the Hall.\n\
                         The key is a thing in the Hall. The box is an openable container in the Hall.\n\
                         Opening the box scores a point: \"opening the box\".\n";

    fn hexicon(more: &str) -> String {
        let translation = translate(&format!("{WORLD}{more}"));
        assert!(
            translation.problems.is_empty(),
            "problems: {:?}",
            translation.problems
        );
        translation.text()
    }

    fn has(text: &str, wanted: &str) {
        assert!(text.contains(wanted), "no {wanted:?} in:\n{text}");
    }

    fn problem(more: &str, wanted: &str) {
        let found = translate(&format!("{WORLD}{more}")).problems;
        assert!(
            found.iter().any(|(_, m)| m.contains(wanted)),
            "{more:?}: wanted {wanted:?}, found {found:?}"
        );
    }

    #[test]
    fn a_test_is_a_scenario_with_its_steps() {
        let text = hexicon(
            "The test \"getting the key\" is \"The key is in the Hall.\"\n\
             Type \"take key\" to have it: the player has the key and it says \"taken\".\n\
             Type \"open box\": \"opening the box\" is scored and it does not say \"locked\".\n\
             Type \"north\" to leave: the player is in the Yard and the story has not ended.",
        );
        has(
            &text,
            "gettingTheKey: Scenario 'getting the key' 'The key is in the Hall.'\n;\n\
             Step 'take key' 'To have it.'\n    location = gettingTheKey\n    \
             expect = (key.isIn(now.player))\n    mentions = 'taken'\n;\n\
             Step 'open box'\n    location = gettingTheKey\n    expect = (openingTheBox.achieved)\n    \
             avoids = 'locked'\n;\n\
             Step 'north' 'To leave.'\n    location = gettingTheKey\n    \
             expect = (now.player.isIn(yard) && scenarioMemory.ending == nil)\n;",
        );
    }

    #[test]
    fn where_a_test_starts_and_waits_and_walkthroughs() {
        let text = hexicon(
            "The test \"first\" is \"One.\"\nType \"look\".\n\
             The test \"second\".\n\
             It starts after \"first\".\n\
             It starts in the Yard.\n\
             It starts with the player holding the key and the box.\n\
             Wait up to 3 turns for the end: the story has ended in victory.\n\
             The walkthrough \"all\" plays \"first\", then \"second\".",
        );
        has(
            &text,
            "second: Scenario 'second'\n    after = first\n    startAt = yard\n    \
             holding = [key, box]\n;\n\
             Await 'For the end.'\n    location = second\n    \
             until = (scenarioMemory.ending == storyVictory)\n    within = 3\n;",
        );
        has(&text, "all: Walkthrough 'all' [first, second];");
    }

    #[test]
    fn sources_read_together_name_what_each_other_make() {
        let translations = translate_all(&[
            (
                "start.hxe",
                "The Hall is a room. The player is in the Hall. The key is a thing in the Hall.",
            ),
            (
                "tests.hxe",
                "The test \"keys\".\nType \"take key\": the player has the key.",
            ),
        ]);
        assert!(translations.iter().all(|t| t.problems.is_empty()));
        assert!(
            translations[1]
                .text()
                .contains("expect = (key.isIn(now.player))")
        );
        // Each line is reported as its own source's.
        let source = translations[1].source(&["start.hxe", "tests.hxe"], 1);
        assert!(
            source.contains("#line 2 'tests.hxe'\n    expect = (key.isIn(now.player))"),
            "{source}"
        );
        // A sentence about another source's thing is reported in its own.
        let translations = translate_all(&[
            ("start.hxe", "The Hall is a room."),
            ("more.hxe", "The Hall is a room."),
        ]);
        assert!(translations[0].problems.is_empty());
        assert_eq!(
            translations[1].problems,
            [(
                1,
                "There is already something called \u{201c}the Hall\u{201d}, made on line 1 of \
                 start.hxe."
                    .to_owned()
            )]
        );
    }

    #[test]
    fn how_a_thing_is_listed_in_a_room() {
        let text = hexicon("The key is listed as \"A key glints on the floor.\"");
        has(&text, "    specialDesc = \"A key glints on the floor. \"\n");
    }

    #[test]
    fn problems_with_tests() {
        problem("Type \"look\".", "is part of a test, and comes after one");
        problem(
            "The test \"a\".\nType look.",
            "A command is typed in quotation marks",
        );
        problem(
            "The test \"a\".\nType \"look\": the key is shiny.",
            "\u{201c}shiny\u{201d} is not something I know",
        );
        problem(
            "The test \"a\".\nType \"look\": it whispers \"x\".",
            "I can\u{2019}t read the check",
        );
        problem(
            "The test \"a\".\nType \"look\": \"winning\" is scored.",
            "No rule scores \u{201c}winning\u{201d}",
        );
        problem(
            "The test \"a\".\nIt starts after \"b\".",
            "There is no test called \u{201c}b\u{201d}",
        );
        problem(
            "The test \"a\".\nWait up to 2 turns.",
            "A wait says what it waits for",
        );
        problem(
            "The test \"a\".\nThe test \"a\".",
            "There is already a test called",
        );
        problem(
            "The walkthrough \"w\" plays \"x\".",
            "There is no test called \u{201c}x\u{201d}",
        );
        problem(
            "The test \"a\".\nIt starts with the player holding the Yard.",
            "The player can\u{2019}t hold",
        );
    }
}