nightshade 0.13.2

A cross-platform data-oriented game engine.
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
//! Free-form input parsing.
//!
//! Maps typed text like "take key" or "n" or "look at the drip" onto the
//! index of the matching entry in the engine's current [`Choice`] menu.
//! Falls through to a digit shortcut when the player just wants the numbered
//! form. Matching is choice-list-driven: we only consider verbs/nouns the
//! engine is currently offering, so disambiguation stays tight.
//!
//! Vocabulary follows the Inform 7 standard verb library. The authoritative
//! enum — [`Verb`] — lives in [`verb`]. Compound phrases like `pick up`,
//! `put down`, `look at`, and `talk to` are rewritten before the verb-token
//! lookup.

use crate::interactive_fiction::data::{
    Choice, ChoiceAction, EntityKind, ExamineTarget, Placeholder, RefusalCategory, RuntimeState,
    Verb, VerbResponses,
};
use crate::interactive_fiction::engine::Engine;
use std::str::FromStr;

/// The result of parsing one line of input.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Parsed {
    /// Pick the choice at this menu index.
    Choose(usize),
    /// Meta command: quit the game.
    Quit,
    /// Meta command: undo the last turn.
    Undo,
    /// Meta command: show the list of currently available actions.
    Help,
    /// Meta command: re-describe the player's current room without
    /// advancing a turn. Fired when the player types `look`, `l`,
    /// `x`, `examine`, `inspect`, or `exits` with no noun — and the
    /// current menu doesn't have a `ChoiceAction::Look` (e.g. when the
    /// player is inside a dialogue).
    DescribeRoom,
    /// `take all` / `get all` / `grab all` / `take everything`. The
    /// view should pick every currently-visible `Take` choice in
    /// order.
    TakeAll,
    /// `drop all` / `drop everything`. The view should pick every
    /// currently-visible `Drop` choice in order.
    DropAll,
    /// `examine all` / `x all`. The view should pick every currently-
    /// visible examine choice in order.
    ExamineAll,
    /// Input was empty (whitespace-only).
    Empty,
    /// Nothing in the current menu matched.
    NoMatch,
    /// More than one choice matched; player must be more specific.
    Ambiguous,
    /// The parser recognised the verb but found no target for it. The
    /// attached string is the verb-appropriate refusal line, already
    /// rendered via [`VerbResponses`]. The view should print it as
    /// narration without advancing a turn.
    Refuse(String),
}

pub fn extract_noun(raw: &str) -> Option<String> {
    let normalized = raw.trim().to_lowercase();
    if normalized.is_empty() {
        return None;
    }
    match split_verb_and_noun(&normalized) {
        Some((_, noun)) if !noun.is_empty() => Some(noun),
        _ => None,
    }
}

pub fn parse(engine: &Engine, state: &RuntimeState, choices: &[Choice], raw: &str) -> Parsed {
    let normalized = raw.trim().to_lowercase();
    if normalized.is_empty() {
        return Parsed::Empty;
    }

    match normalized.as_str() {
        "q" | "quit" => return Parsed::Quit,
        "u" | "undo" | "oops" => return Parsed::Undo,
        "help" | "h" | "commands" | "?" => return Parsed::Help,
        _ => {}
    }

    if let Ok(number) = normalized.parse::<usize>()
        && number >= 1
        && number <= choices.len()
    {
        return Parsed::Choose(number - 1);
    }

    if let Some(matched) = direction_only(engine, state, choices, &normalized) {
        return matched;
    }

    let (verb, noun) = match split_verb_and_noun(&normalized) {
        Some(parsed) => parsed,
        None => return label_match(engine, state, choices, &normalized),
    };

    let parsed = dispatch_verb(engine, state, choices, verb, &noun);
    if !matches!(parsed, Parsed::NoMatch) {
        return parsed;
    }

    // Graceful fallback: verbs like `open`, `push`, `smell` that couldn't
    // find their specialised target in the menu still deserve to *say
    // something* if the noun names an examinable feature. `Verb::accepts_examine_fallback`
    // excludes categorical mismatches (you can't "eat the wall" by
    // examining it) so only interaction-like verbs fall through.
    if !noun.is_empty() && verb.accepts_examine_fallback() {
        let fallback = find_examine(engine, choices, &noun);
        if !matches!(fallback, Parsed::NoMatch) {
            return fallback;
        }
    }

    let labeled = label_match(engine, state, choices, &normalized);
    if !matches!(labeled, Parsed::NoMatch) {
        return labeled;
    }

    // Verb-specific refusal rather than a flat "can't do that". The
    // player is typing in English — meeting them with a refusal that
    // acknowledges the verb ("That wouldn't taste good.") reads far
    // less frustrating than silence.
    Parsed::Refuse(refusal_for(engine, verb, &noun))
}

/// Split the normalized input into a canonical `(Verb, noun)` pair, applying
/// multi-word rewrites (`pick up X` → `(Take, X)`, `look at X` → `(Examine, X)`)
/// and stripping leading prepositions/articles from the noun.
fn split_verb_and_noun(input: &str) -> Option<(Verb, String)> {
    if let Some((verb, rest)) = match_compound_phrase(input) {
        return Some((verb, normalize_noun(rest)));
    }

    let (head, rest) = split_head(input);
    let verb = Verb::from_str(head).ok()?;
    let noun = normalize_noun_for_verb(verb, rest);
    Some((verb, noun))
}

/// Compound verb phrases that rewrite to a different canonical verb.
/// Checked longest-first so `look at` wins over `look`.
const COMPOUND_PHRASES: &[(&str, Verb)] = &[
    ("pick up", Verb::Take),
    ("put down", Verb::Drop),
    ("put on", Verb::Wear),
    ("take off", Verb::Remove),
    ("open up", Verb::Open),
    ("look at", Verb::Examine),
    ("look into", Verb::Examine),
    ("look inside", Verb::Examine),
    ("look in", Verb::Examine),
    ("look under", Verb::Examine),
    ("look behind", Verb::Examine),
    ("look on", Verb::Examine),
    ("listen to", Verb::Listen),
    ("talk to", Verb::Talk),
    ("talk with", Verb::Talk),
    ("speak to", Verb::Talk),
    ("speak with", Verb::Talk),
    ("wake up", Verb::Wake),
    ("turn on", Verb::Use),
    ("turn off", Verb::Use),
    ("switch on", Verb::Use),
    ("switch off", Verb::Use),
    ("climb up", Verb::Climb),
    ("climb on", Verb::Climb),
    ("climb down", Verb::Climb),
    ("climb off", Verb::Climb),
    ("climb onto", Verb::Climb),
    ("get in", Verb::Enter),
    ("get into", Verb::Enter),
    ("get inside", Verb::Enter),
    ("get on", Verb::Enter),
    ("get out", Verb::Leave),
    ("get off", Verb::Leave),
    ("go in", Verb::Enter),
    ("go into", Verb::Enter),
    ("go inside", Verb::Enter),
    ("go out", Verb::Leave),
    ("go outside", Verb::Leave),
];

fn match_compound_phrase(input: &str) -> Option<(Verb, &str)> {
    for (phrase, verb) in COMPOUND_PHRASES {
        if let Some(rest) = strip_phrase_prefix(input, phrase) {
            return Some((*verb, rest));
        }
    }
    None
}

fn strip_phrase_prefix<'a>(input: &'a str, phrase: &str) -> Option<&'a str> {
    let rest = input.strip_prefix(phrase)?;
    if rest.is_empty() {
        return Some(rest);
    }
    if rest.starts_with(char::is_whitespace) {
        Some(rest.trim_start())
    } else {
        None
    }
}

fn split_head(input: &str) -> (&str, &str) {
    match input.find(char::is_whitespace) {
        Some(idx) => (&input[..idx], input[idx..].trim_start()),
        None => (input, ""),
    }
}

fn normalize_noun(rest: &str) -> String {
    rest.trim()
        .trim_start_matches("the ")
        .trim_start_matches("a ")
        .trim_start_matches("an ")
        .trim()
        .to_string()
}

fn normalize_noun_for_verb(verb: Verb, rest: &str) -> String {
    let trimmed = rest.trim();
    let without_prep = match verb {
        Verb::Talk => strip_leading_word(trimmed, &["to", "with"]),
        Verb::Look => strip_leading_word(trimmed, &["at"]),
        Verb::Listen => strip_leading_word(trimmed, &["to"]),
        _ => trimmed,
    };
    let primary_object = match verb {
        // "ask wizard about magic" / "tell guard about plot" — only the
        // first noun is addressable in our model; strip the secondary
        // clause so the NPC match works.
        Verb::Ask | Verb::Consult => split_on_connector(without_prep, &[" about ", " regarding "]),
        // "give key to guard" / "show badge to guard" — the recipient is
        // the relevant NPC or item in our menu.
        Verb::Give | Verb::Show => split_after_connector(without_prep, &[" to "]),
        _ => without_prep,
    };
    normalize_noun(primary_object)
}

fn strip_leading_word<'a>(input: &'a str, prepositions: &[&str]) -> &'a str {
    for prep in prepositions {
        if let Some(rest) = input.strip_prefix(prep)
            && (rest.is_empty() || rest.starts_with(char::is_whitespace))
        {
            return rest.trim_start();
        }
    }
    input
}

fn split_on_connector<'a>(input: &'a str, connectors: &[&str]) -> &'a str {
    for connector in connectors {
        if let Some(idx) = input.find(connector) {
            return &input[..idx];
        }
    }
    input
}

fn split_after_connector<'a>(input: &'a str, connectors: &[&str]) -> &'a str {
    for connector in connectors {
        if let Some(idx) = input.find(connector) {
            return input[idx + connector.len()..].trim_start();
        }
    }
    input
}

/// Build the rendered refusal line for a verb that nothing matched.
/// The world's `VerbResponses::refusal_overrides` can re-route any verb
/// to a different category — the author never has to touch the parser.
fn refusal_for(engine: &Engine, verb: Verb, noun: &str) -> String {
    let responses = &engine.world().verb_responses;
    let category = responses.refusal_category(verb);
    let template = match category {
        RefusalCategory::Default => &responses.refusal_default,
        RefusalCategory::Taste => &responses.refusal_taste,
        RefusalCategory::Consume => &responses.refusal_consume,
        RefusalCategory::Violence => &responses.refusal_violence,
        RefusalCategory::Affection => &responses.refusal_affection,
        RefusalCategory::Manipulation => &responses.refusal_manipulation,
        RefusalCategory::Jump => &responses.refusal_jump,
        RefusalCategory::Exchange => &responses.refusal_exchange,
        RefusalCategory::Wake => &responses.refusal_wake,
    };
    VerbResponses::render(template, &[(Placeholder::Noun, noun)])
}

fn dispatch_verb(
    engine: &Engine,
    state: &RuntimeState,
    choices: &[Choice],
    verb: Verb,
    noun: &str,
) -> Parsed {
    match verb {
        Verb::Look => {
            if noun.is_empty() || is_room_reference(engine, state, noun) {
                describe_room_or_look_action(choices)
            } else {
                find_examine(engine, choices, noun)
            }
        }
        Verb::Examine | Verb::Smell | Verb::Listen | Verb::Touch => {
            if noun.is_empty() || is_room_reference(engine, state, noun) {
                describe_room_or_look_action(choices)
            } else if is_all_keyword(noun)
                && has_any(choices, |action| matches!(action, ChoiceAction::Examine(_)))
            {
                Parsed::ExamineAll
            } else {
                find_examine(engine, choices, noun)
            }
        }
        Verb::Eat | Verb::Drink => consume_response_for(engine, state, noun),
        Verb::Taste => Parsed::NoMatch,
        Verb::Exits => describe_room_or_look_action(choices),
        Verb::Inventory => find_simple(choices, |action| matches!(action, ChoiceAction::Inventory)),
        // Wait is a no-noun verb in Inform. If the player types "wait five
        // minutes" we silently ignore the noun and just pass a turn —
        // better UX than rejecting the command for a meaningless modifier.
        Verb::Wait => find_simple(choices, |action| matches!(action, ChoiceAction::Wait)),
        Verb::Leave => {
            let dialogue_leave = find_simple(choices, |action| {
                matches!(action, ChoiceAction::LeaveDialogue)
            });
            if !matches!(dialogue_leave, Parsed::NoMatch) {
                dialogue_leave
            } else {
                go_for_keyword(engine, state, choices, "out")
            }
        }
        Verb::Take => {
            if is_all_keyword(noun) {
                if has_any(choices, |action| matches!(action, ChoiceAction::Take(_))) {
                    Parsed::TakeAll
                } else {
                    Parsed::NoMatch
                }
            } else {
                item_verb(engine, choices, noun, |action| {
                    matches!(action, ChoiceAction::Take(_))
                })
            }
        }
        Verb::Drop => {
            if is_all_keyword(noun) {
                if has_any(choices, |action| matches!(action, ChoiceAction::Drop(_))) {
                    Parsed::DropAll
                } else {
                    Parsed::NoMatch
                }
            } else {
                item_verb(engine, choices, noun, |action| {
                    matches!(action, ChoiceAction::Drop(_))
                })
            }
        }
        Verb::Throw | Verb::Put | Verb::Remove => item_verb(engine, choices, noun, |action| {
            matches!(action, ChoiceAction::Drop(_))
        }),
        Verb::Use
        | Verb::Open
        | Verb::Close
        | Verb::Unlock
        | Verb::Lock
        | Verb::Switch
        | Verb::Push
        | Verb::Pull
        | Verb::Turn
        | Verb::Squeeze
        | Verb::Rub
        | Verb::Wave
        | Verb::Swing
        | Verb::Burn
        | Verb::Cut
        | Verb::Tie
        | Verb::Wear
        | Verb::Insert
        | Verb::Fill => {
            // Prefer entity-open: `open the mirror` on a fixture beats
            // `use the mirror` on a same-named item (the two shouldn't
            // collide in practice, but entities are the more specific
            // target for manipulation verbs).
            let entity = entity_open(engine, choices, noun, KindFilter::Any);
            if !matches!(entity, Parsed::NoMatch) {
                entity
            } else {
                item_verb(engine, choices, noun, |action| {
                    matches!(action, ChoiceAction::Use(_))
                })
            }
        }
        Verb::Read | Verb::Consult => item_verb(engine, choices, noun, |action| {
            matches!(action, ChoiceAction::Read(_))
        }),
        Verb::Go => find_go(engine, state, choices, noun),
        Verb::Enter => {
            if noun.is_empty() {
                go_for_keyword(engine, state, choices, "in")
            } else {
                find_go(engine, state, choices, noun)
            }
        }
        Verb::Climb => {
            if noun.is_empty() {
                go_for_keyword(engine, state, choices, "up")
            } else {
                find_go(engine, state, choices, noun)
            }
        }
        Verb::Jump => Parsed::NoMatch,
        Verb::Talk | Verb::Ask => {
            // Talk / ask address any addressable entity (character or
            // object) with a dialogue. This is deliberate — "talk to
            // the mirror" / "ask the sign about the path" are
            // legitimate, and authors who want to keep objects
            // non-addressable can leave dialogue off them entirely.
            entity_open(engine, choices, noun, KindFilter::Any)
        }
        Verb::Kiss | Verb::Attack | Verb::Wake | Verb::Apologise => {
            // Affection / violence / waking target people. `kiss the
            // mirror` or `attack the wall` refuses via
            // `refusal_affection`/`refusal_violence` rather than
            // silently opening the object's dialogue.
            entity_open(engine, choices, noun, KindFilter::CharacterOnly)
        }
        Verb::Give | Verb::Show | Verb::Buy => Parsed::NoMatch,
    }
}

fn has_any(choices: &[Choice], predicate: impl Fn(&ChoiceAction) -> bool) -> bool {
    choices.iter().any(|choice| predicate(&choice.action))
}

fn consume_response_for(engine: &Engine, state: &RuntimeState, noun: &str) -> Parsed {
    use crate::interactive_fiction::data::ItemLocation;

    let effective = if noun.is_empty() {
        state.last_noun.as_deref().unwrap_or("")
    } else {
        noun
    };
    if effective.is_empty() {
        return Parsed::NoMatch;
    }
    for (item_id, item) in &engine.world().items {
        if !item_matches_noun(engine, item_id, effective) {
            continue;
        }
        let reachable = match state.item_locations.get(item_id) {
            Some(ItemLocation::Inventory) => true,
            Some(ItemLocation::Room(r)) => r == &state.current_room,
            _ => false,
        };
        if !reachable {
            continue;
        }
        if let Some(response) = &item.properties.consume_response {
            let rendered = engine.resolve_text(state, response);
            return Parsed::Refuse(rendered);
        }
    }
    Parsed::NoMatch
}

/// Prefer the current menu's `Look` action when available — that way
/// room-level `look` fires the action's transcript echo and any
/// `OnLook`-style rules wired to it. If no `Look` action is present
/// (typically because the player is inside a dialogue), fall back to
/// `Parsed::DescribeRoom` so the view can re-describe the room
/// without changing menus.
fn describe_room_or_look_action(choices: &[Choice]) -> Parsed {
    let via_menu = find_simple(choices, |action| matches!(action, ChoiceAction::Look));
    if matches!(via_menu, Parsed::NoMatch) {
        Parsed::DescribeRoom
    } else {
        via_menu
    }
}

fn item_verb(
    engine: &Engine,
    choices: &[Choice],
    rest: &str,
    action_matches: impl Fn(&ChoiceAction) -> bool,
) -> Parsed {
    if rest.is_empty() {
        return Parsed::NoMatch;
    }
    let matches = indexes_of_item_action(engine, choices, rest, action_matches);
    match matches.len() {
        0 => Parsed::NoMatch,
        1 => Parsed::Choose(matches[0]),
        _ => Parsed::Ambiguous,
    }
}

/// Which entity kinds a parser lookup accepts. `Open`/`Use`/`Talk`/`Ask`
/// accept either kind; social verbs like `Kiss`/`Attack` only address
/// characters.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum KindFilter {
    Any,
    CharacterOnly,
}

/// Find a `ChoiceAction::Open` in `choices` whose entity matches the
/// noun and passes the kind filter. Used by `Verb::Open`, `Verb::Use`,
/// and the social verbs as the primary lookup before falling back to
/// item dispatch.
fn entity_open(engine: &Engine, choices: &[Choice], noun: &str, kind: KindFilter) -> Parsed {
    if noun.is_empty() {
        return Parsed::NoMatch;
    }
    let noun = noun
        .trim_start_matches("the ")
        .trim_start_matches("a ")
        .trim_start_matches("an ")
        .trim();
    let matches: Vec<usize> = choices
        .iter()
        .enumerate()
        .filter_map(|(i, choice)| {
            let ChoiceAction::Open(entity_id) = &choice.action else {
                return None;
            };
            if !entity_matches_noun(engine, entity_id, noun) {
                return None;
            }
            if kind == KindFilter::CharacterOnly {
                let entity = engine.world().entities.get(entity_id)?;
                if !matches!(entity.kind, EntityKind::Character { .. }) {
                    return None;
                }
            }
            Some(i)
        })
        .collect();
    match matches.len() {
        0 => Parsed::NoMatch,
        1 => Parsed::Choose(matches[0]),
        _ => Parsed::Ambiguous,
    }
}

fn is_all_keyword(noun: &str) -> bool {
    matches!(noun.trim(), "all" | "everything")
}

/// True when the noun is a generic room pronoun (`here`, `around`) or the
/// player's current room's own name. This lets `look around` and
/// `examine bedroom` both describe the current room.
fn is_room_reference(engine: &Engine, state: &RuntimeState, noun: &str) -> bool {
    let trimmed = noun.trim();
    if matches!(
        trimmed,
        "around" | "here" | "room" | "place" | "surroundings"
    ) {
        return true;
    }
    let Some(room) = engine.world().rooms.get(&state.current_room) else {
        return false;
    };
    noun_matches_phrase(&room.name, trimmed)
}

fn find_simple(choices: &[Choice], predicate: impl Fn(&ChoiceAction) -> bool) -> Parsed {
    let matches: Vec<usize> = choices
        .iter()
        .enumerate()
        .filter(|(_, choice)| predicate(&choice.action))
        .map(|(i, _)| i)
        .collect();
    match matches.len() {
        0 => Parsed::NoMatch,
        1 => Parsed::Choose(matches[0]),
        _ => Parsed::Ambiguous,
    }
}

fn direction_only(
    engine: &Engine,
    state: &RuntimeState,
    choices: &[Choice],
    input: &str,
) -> Option<Parsed> {
    // Only intercept if the input is a pure direction word with no verb.
    let expanded = expand_direction(input)?;
    let matches = go_indexes_for_direction(engine, state, choices, expanded);
    Some(match matches.len() {
        0 => return None,
        1 => Parsed::Choose(matches[0]),
        _ => Parsed::Ambiguous,
    })
}

fn find_go(engine: &Engine, state: &RuntimeState, choices: &[Choice], rest: &str) -> Parsed {
    if rest.is_empty() {
        return Parsed::NoMatch;
    }
    let wanted = expand_direction(rest).unwrap_or(rest);
    go_for_keyword(engine, state, choices, wanted)
}

fn go_for_keyword(
    engine: &Engine,
    state: &RuntimeState,
    choices: &[Choice],
    keyword: &str,
) -> Parsed {
    let matches = go_indexes_for_direction(engine, state, choices, keyword);
    match matches.len() {
        0 => Parsed::NoMatch,
        1 => Parsed::Choose(matches[0]),
        _ => Parsed::Ambiguous,
    }
}

fn go_indexes_for_direction(
    engine: &Engine,
    state: &RuntimeState,
    choices: &[Choice],
    wanted: &str,
) -> Vec<usize> {
    let Some(room) = engine.world().rooms.get(&state.current_room) else {
        return Vec::new();
    };
    choices
        .iter()
        .enumerate()
        .filter_map(|(i, choice)| {
            let ChoiceAction::Go { exit_index, .. } = choice.action else {
                return None;
            };
            let exit = room.exits.get(exit_index)?;
            let direction = exit.direction.to_lowercase();
            if matches_direction(&direction, wanted) {
                Some(i)
            } else {
                None
            }
        })
        .collect()
}

fn matches_direction(direction: &str, wanted: &str) -> bool {
    if direction == wanted {
        return true;
    }
    if direction.starts_with(wanted) {
        return true;
    }
    // The exit direction is often "north (to the cottage)"; match if the
    // wanted word appears as a whole word inside the direction phrase, or as
    // the first word's prefix.
    let first_word = direction.split_whitespace().next().unwrap_or("");
    if first_word == wanted || first_word.starts_with(wanted) {
        return true;
    }
    direction
        .split_whitespace()
        .any(|word| word.trim_matches(|character: char| !character.is_alphanumeric()) == wanted)
}

fn expand_direction(input: &str) -> Option<&'static str> {
    let trimmed = input.trim();
    Some(match trimmed {
        "n" | "north" => "north",
        "s" | "south" => "south",
        "e" | "east" => "east",
        "w" | "west" => "west",
        "up" => "up",
        "d" | "down" => "down",
        "ne" | "northeast" => "northeast",
        "nw" | "northwest" => "northwest",
        "se" | "southeast" => "southeast",
        "sw" | "southwest" => "southwest",
        "in" | "inside" => "in",
        "out" | "outside" => "out",
        _ => return None,
    })
}

fn find_examine(engine: &Engine, choices: &[Choice], noun: &str) -> Parsed {
    if noun.is_empty() {
        return Parsed::NoMatch;
    }
    let noun = noun
        .trim_start_matches("the ")
        .trim_start_matches("a ")
        .trim_start_matches("an ")
        .trim();

    // Two-pass match: first try exact-phrase (handles `examine coat`
    // when both `coat` and `coat hook` keywords exist — the phrase
    // `coat` should win over the partial word match inside `coat
    // hook`). Fall back to partial-word matching only if exact
    // returned nothing.
    let mut exact: Vec<usize> = Vec::new();
    let mut partial: Vec<usize> = Vec::new();
    for (index, choice) in choices.iter().enumerate() {
        let ChoiceAction::Examine(target) = &choice.action else {
            continue;
        };
        let phrase = match target {
            ExamineTarget::Item(item) => engine.world().items.get(item).map(|i| i.name.clone()),
            ExamineTarget::Entity(entity) => {
                engine.world().entities.get(entity).map(|e| e.name.clone())
            }
            ExamineTarget::Keyword(keyword) => Some(keyword.clone()),
        };
        let synonyms: Vec<String> = match target {
            ExamineTarget::Item(item) => engine
                .world()
                .items
                .get(item)
                .map(|i| i.synonyms.clone())
                .unwrap_or_default(),
            ExamineTarget::Entity(entity) => engine
                .world()
                .entities
                .get(entity)
                .map(|e| e.synonyms.clone())
                .unwrap_or_default(),
            ExamineTarget::Keyword(_) => Vec::new(),
        };
        let mut exact_hit = false;
        let mut partial_hit = false;
        if let Some(phrase) = &phrase {
            if phrase_exact_match(phrase, noun) {
                exact_hit = true;
            } else if noun_matches_phrase(phrase, noun) {
                partial_hit = true;
            }
        }
        for synonym in &synonyms {
            if phrase_exact_match(synonym, noun) {
                exact_hit = true;
            } else if noun_matches_phrase(synonym, noun) {
                partial_hit = true;
            }
        }
        if exact_hit {
            exact.push(index);
        } else if partial_hit {
            partial.push(index);
        }
    }

    let winners = if !exact.is_empty() { exact } else { partial };
    match winners.len() {
        0 => Parsed::NoMatch,
        1 => Parsed::Choose(winners[0]),
        _ => Parsed::Ambiguous,
    }
}

/// True when the noun equals the phrase after both have had their
/// leading articles stripped.
fn phrase_exact_match(phrase: &str, noun: &str) -> bool {
    strip_articles(&phrase.to_lowercase()) == strip_articles(&noun.to_lowercase())
}

fn indexes_of_item_action(
    engine: &Engine,
    choices: &[Choice],
    rest: &str,
    action_matches: impl Fn(&ChoiceAction) -> bool,
) -> Vec<usize> {
    let noun = rest
        .trim_start_matches("the ")
        .trim_start_matches("a ")
        .trim_start_matches("an ")
        .trim();
    if noun.is_empty() {
        return Vec::new();
    }
    choices
        .iter()
        .enumerate()
        .filter_map(|(i, choice)| {
            if !action_matches(&choice.action) {
                return None;
            }
            let item_id = match &choice.action {
                ChoiceAction::Take(id)
                | ChoiceAction::Drop(id)
                | ChoiceAction::Use(id)
                | ChoiceAction::Read(id) => id,
                ChoiceAction::Examine(ExamineTarget::Item(id)) => id,
                _ => return None,
            };
            if item_matches_noun(engine, item_id, noun) {
                Some(i)
            } else {
                None
            }
        })
        .collect()
}

fn item_matches_noun(
    engine: &Engine,
    item_id: &crate::interactive_fiction::data::ItemId,
    noun: &str,
) -> bool {
    let Some(item) = engine.world().items.get(item_id) else {
        return false;
    };
    if noun_matches_phrase(&item.name, noun) {
        return true;
    }
    item.synonyms
        .iter()
        .any(|synonym| noun_matches_phrase(synonym, noun))
}

fn entity_matches_noun(
    engine: &Engine,
    entity_id: &crate::interactive_fiction::data::EntityId,
    noun: &str,
) -> bool {
    let Some(entity) = engine.world().entities.get(entity_id) else {
        return false;
    };
    if noun_matches_phrase(&entity.name, noun) {
        return true;
    }
    entity
        .synonyms
        .iter()
        .any(|synonym| noun_matches_phrase(synonym, noun))
}

/// Case-insensitive check: does the player's `noun` identify the given phrase?
/// True when the phrase equals the noun after stripping leading articles, or
/// when any whole word inside the phrase equals the noun (so "key" matches
/// "iron key", and "picture frame" matches "the picture frame").
fn noun_matches_phrase(phrase: &str, noun: &str) -> bool {
    let phrase = strip_articles(&phrase.to_lowercase());
    let noun = strip_articles(&noun.to_lowercase());
    if phrase == noun {
        return true;
    }
    phrase.split_whitespace().any(|word| {
        let word = word.trim_matches(|character: char| !character.is_alphanumeric());
        word == noun
    })
}

/// Strip `the `/`a `/`an ` from the start of a lowercase phrase.
fn strip_articles(phrase: &str) -> String {
    phrase
        .trim_start_matches("the ")
        .trim_start_matches("a ")
        .trim_start_matches("an ")
        .trim()
        .to_string()
}

fn label_match(engine: &Engine, state: &RuntimeState, choices: &[Choice], input: &str) -> Parsed {
    let mut matches: Vec<usize> = Vec::new();
    for (index, choice) in choices.iter().enumerate() {
        let label = engine.resolve_text(state, &choice.label).to_lowercase();
        if label.contains(input) {
            matches.push(index);
        }
    }
    match matches.len() {
        0 => Parsed::NoMatch,
        1 => Parsed::Choose(matches[0]),
        _ => Parsed::Ambiguous,
    }
}