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
//! Conversation and hints in English.
//!
//! ```text
//! Greeted, the keeper says: "'Evening,' says the keeper."
//! Asked about the lamp, the keeper says: "'Upstairs.'"
//! Otherwise, the keeper says: "The keeper only shakes his head."
//!
//! The hint "How do I get in?" opens when the door is seen, and closes
//! when the door is unlocked. It says "Is there a key?", then "Look in
//! the box."
//! ```
//!
//! What a character says becomes one of Hexad's topic entries in the
//! character, and a hint a `Goal` in the hint menu, which opens and
//! closes as its conditions say.

use super::rules::Cond;
use super::{Kind, Phrase, Reader, Statement, Target, Tok, Token, is_word, phrase, shown, word_of};

/// How a character is spoken to, the words that say it, and Hexad's
/// topic entry for it, about something and about anything else.
const TRIGGERS: &[(&[&str], &str, &str)] = &[
    (
        &["asked", "or", "told", "about"],
        "AskTellTopic",
        "DefaultAskTellTopic",
    ),
    (&["asked", "about"], "AskTopic", "DefaultAskTopic"),
    (&["told", "about"], "TellTopic", "DefaultTellTopic"),
    (
        &["shown", "or", "given"],
        "GiveShowTopic",
        "DefaultGiveShowTopic",
    ),
    (&["shown"], "ShowTopic", "DefaultShowTopic"),
    (&["given"], "GiveTopic", "DefaultGiveTopic"),
];

/// A hint, as read.
#[derive(Debug, Clone)]
pub(super) struct Hint {
    pub(super) title: String,
    pub(super) opens: Vec<(bool, Cond)>,
    pub(super) closes: Vec<(bool, Cond)>,
    pub(super) steps: Vec<String>,
    pub(super) line: u32,
    pub(super) order: usize,
}

/// A hint, ready to write.
#[derive(Debug, Clone)]
pub(super) struct WrittenHint {
    pub(super) title: String,
    pub(super) opens: Option<String>,
    pub(super) closes: Option<String>,
    pub(super) steps: Vec<String>,
    pub(super) line: u32,
    pub(super) order: usize,
}

const TALK_FORM: &str = "What a character says is said as \"Greeted, the keeper says: \
\"...\"\", \"Said goodbye to, the keeper says: \"...\"\", \"Asked about the lamp, the keeper says: \"...\"\", or \"Otherwise, the keeper \
says: \"...\"\"; asked, told, asked or told, shown, given, or shown or given about anything \
else, as well.";

const HINT_FORM: &str = "A hint is said as \"The hint \"How do I get in?\" opens when the \
door is seen, and closes when the door is unlocked.\", and what it says after it: \"It says \
\"Is there a key?\", then \"Look in the box.\"\"";

impl Reader {
    /// A sentence of conversation or of a hint. Whether it was one.
    pub(super) fn talk_sentence(&mut self, line: u32, t: &[Token]) -> bool {
        // What the hint before says.
        if is_word(t.first(), &["it"])
            && is_word(t.get(1), &["says"])
            && let Some(hint) = self.open_hint
        {
            self.hint_steps(line, hint, t);
            return true;
        }
        self.open_hint = None;
        if is_word(t.first(), &["the"])
            && is_word(t.get(1), &["hint"])
            && matches!(t.get(2).map(|t| &t.tok), Some(Tok::Text(_)))
        {
            self.hint(line, t);
            return true;
        }
        let first = t.first().and_then(word_of).unwrap_or_default();
        if !matches!(
            first.as_str(),
            "greeted" | "said" | "asked" | "told" | "shown" | "given" | "otherwise"
        ) || !t.iter().any(|token| is_word(Some(token), &["says"]))
        {
            return false;
        }
        self.says(line, t);
        true
    }

    /// "Asked about the lamp, the keeper says: "..."".
    fn says(&mut self, line: u32, t: &[Token]) {
        let bad = |reader: &mut Self| {
            reader.problem(line, format!("I can't read \"{}\". {TALK_FORM}", shown(t)));
        };
        let Some(says) = t.iter().position(|token| is_word(Some(token), &["says"])) else {
            return bad(self);
        };
        let text = match &t[says + 1..] {
            [
                Token {
                    tok: Tok::Punct(':'),
                    ..
                },
                Token {
                    tok: Tok::Text(text),
                    ..
                },
            ] => text.clone(),
            _ => return bad(self),
        };
        // The character is after the last comma before "says".
        let Some(comma) = t[..says]
            .iter()
            .rposition(|token| matches!(token.tok, Tok::Punct(',')))
        else {
            return bad(self);
        };
        let Some(character) = phrase(&t[comma + 1..says]) else {
            return bad(self);
        };
        let Some(character) = self.subject(character) else {
            return;
        };
        let trigger = &t[..comma];
        let words: Vec<String> = trigger.iter().filter_map(word_of).collect();
        let (class, about) = if words == ["greeted"] {
            ("HelloTopic", Vec::new())
        } else if words == ["said", "goodbye", "to"] {
            ("ByeTopic", Vec::new())
        } else if words == ["otherwise"] {
            ("DefaultAnyTopic", Vec::new())
        } else {
            let Some((len, specific, default)) =
                TRIGGERS.iter().find_map(|(lead, specific, default)| {
                    (words.len() > lead.len() && words[..lead.len()] == **lead).then_some((
                        lead.len(),
                        *specific,
                        *default,
                    ))
                })
            else {
                return bad(self);
            };
            let rest = &trigger[len..];
            let rest_words = &words[len..];
            if rest_words == ["anything", "else"] {
                (default, Vec::new())
            } else {
                let mut about = Vec::new();
                for part in super::split_list(rest).unwrap_or_default() {
                    about.push(part);
                }
                if about.is_empty() {
                    return bad(self);
                }
                (specific, about)
            }
        };
        self.last_subject = Some(character.clone());
        self.add(
            line,
            Statement::Topic {
                character,
                class,
                about,
                text,
            },
        );
    }

    /// "The hint "How do I get in?" opens when ..., and closes when ...".
    fn hint(&mut self, line: u32, t: &[Token]) {
        let Some(Tok::Text(title)) = t.get(2).map(|t| t.tok.clone()) else {
            return;
        };
        let mut opens = Vec::new();
        let mut closes = Vec::new();
        // The rest: "opens when ...", "and closes when ...", in either order.
        let rest = &t[3..];
        let mut parts: Vec<(&str, Vec<Token>)> = Vec::new();
        let mut i = 0;
        while i < rest.len() {
            let word = word_of(&rest[i]).unwrap_or_default();
            if matches!(word.as_str(), "opens" | "closes") && is_word(rest.get(i + 1), &["when"]) {
                parts.push((if word == "opens" { "opens" } else { "closes" }, Vec::new()));
                i += 2;
                continue;
            }
            match parts.last_mut() {
                Some((_, tokens)) => tokens.push(rest[i].clone()),
                None => {
                    self.problem(line, format!("I can't read \"{}\". {HINT_FORM}", shown(t)));
                    return;
                }
            }
            i += 1;
        }
        for (which, mut tokens) in parts {
            // ", and" before the next part belongs to neither.
            while matches!(tokens.last().map(|t| &t.tok), Some(Tok::Punct(',')))
                || is_word(tokens.last(), &["and"])
            {
                tokens.pop();
                if matches!(tokens.last().map(|t| &t.tok), Some(Tok::Punct(','))) {
                    tokens.pop();
                }
            }
            if tokens.is_empty() {
                self.problem(line, format!("I can't read \"{}\". {HINT_FORM}", shown(t)));
                return;
            }
            let mut conds = Vec::new();
            for part in split_and(&tokens) {
                let Some(cond) = self.condition(line, &part) else {
                    self.open_hint = Some(usize::MAX);
                    return;
                };
                conds.push(cond);
            }
            if which == "opens" {
                opens.extend(conds);
            } else {
                closes.extend(conds);
            }
        }
        self.hints.push(Hint {
            title,
            opens,
            closes,
            steps: Vec::new(),
            line,
            order: self.sentences,
        });
        self.open_hint = Some(self.hints.len() - 1);
    }

    /// "It says "...", then "..."": a hint's steps, shown one at a time.
    fn hint_steps(&mut self, line: u32, hint: usize, t: &[Token]) {
        let mut steps = Vec::new();
        let mut ok = true;
        for token in &t[2..] {
            match &token.tok {
                Tok::Text(text) => steps.push(text.clone()),
                Tok::Punct(',') => {}
                Tok::Word(w) if matches!(w.to_lowercase().as_str(), "then" | "and") => {}
                _ => ok = false,
            }
        }
        if !ok || steps.is_empty() {
            self.problem(
                line,
                format!(
                    "I can't read \"{}\". What a hint says is said as \"It says \"Is there a \
                     key?\", then \"Look in the box.\"\"",
                    shown(t)
                ),
            );
            return;
        }
        if hint != usize::MAX {
            self.hints[hint].steps.extend(steps);
        }
    }

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

    /// What a character says, as a topic entry: its class, what it is
    /// about, and its text.
    pub(super) fn topic(
        &mut self,
        line: u32,
        character: &Phrase,
        class: &'static str,
        about: &[Phrase],
        text: &str,
    ) {
        let Some(c) = self.resolve_obj(character) else {
            return;
        };
        if !matches!(self.objs[c].kind, Kind::Man | Kind::Woman | Kind::Person) {
            let name = self.objs[c].called();
            self.problem(
                line,
                format!("\"{name}\" is not a character, so it says nothing: a character is a man, a woman, or a person."),
            );
            return;
        }
        let mut matches = Vec::new();
        for phrase in about {
            match self.resolve(phrase) {
                Ok(Target::Obj(i)) => matches.push(self.objs[i].id.clone()),
                Ok(_) => {
                    self.problem(
                        phrase.line,
                        format!(
                            "\"{}\" is not something to talk about: a thing or a topic is.",
                            phrase.shown()
                        ),
                    );
                    return;
                }
                Err(message) => {
                    self.problem(phrase.line, message);
                    return;
                }
            }
        }
        let matched = match matches.as_slice() {
            [] => None,
            [one] => Some(format!("@{one}")),
            many => Some(format!("[{}]", many.join(", "))),
        };
        self.objs[c]
            .topics
            .push((line, class, matched, text.to_owned()));
    }

    /// Each hint, made ready to write.
    pub(super) fn write_hints(&mut self) {
        let hints = std::mem::take(&mut self.hints);
        for hint in hints {
            if hint.steps.is_empty() {
                self.problem(
                    hint.line,
                    "This hint says nothing: say what it says after it, as \"It says \"Is there a key?\", then \"Look in the box.\"\"",
                );
                continue;
            }
            let test = |reader: &mut Self, conds: &[(bool, Cond)]| -> Option<Option<String>> {
                if conds.is_empty() {
                    return Some(None);
                }
                let mut codes = Vec::new();
                for (not, cond) in conds {
                    codes.push(reader.cond_code(*not, cond)?);
                }
                Some(Some(codes.join(" && ")))
            };
            let (Some(opens), Some(closes)) = (test(self, &hint.opens), test(self, &hint.closes))
            else {
                continue;
            };
            self.written_hints.push(WrittenHint {
                title: hint.title,
                opens,
                closes,
                steps: hint.steps,
                line: hint.line,
                order: hint.order,
            });
        }
    }

    /// A hint, as a `Goal` in the hint menu, `menu`.
    pub(super) fn write_hint(&self, out: &mut Vec<(u32, String)>, hint: &WrittenHint, menu: &str) {
        let line = hint.line;
        out.push((line, format!("Goal '{}'", single_text(&hint.title))));
        out.push((line, "    [".to_owned()));
        let n = hint.steps.len();
        for (i, step) in hint.steps.iter().enumerate() {
            let comma = if i + 1 < n { "," } else { "" };
            out.push((line, format!("        '{}'{comma}", single_text(step))));
        }
        out.push((line, "    ]".to_owned()));
        out.push((line, format!("    location = {menu}")));
        match &hint.opens {
            Some(test) => out.push((line, format!("    openWhenTrue = ({test})"))),
            None => out.push((line, "    goalState = OpenGoal".to_owned())),
        }
        if let Some(test) = &hint.closes {
            out.push((line, format!("    closeWhenTrue = ({test})")));
        }
        out.push((line, ";".to_owned()));
    }
}

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

/// Tokens split at each "and".
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;

    const WORLD: &str = "The Hall is a room. The player is in the Hall.\n\
                         Bob is a man in the Hall. The lamp is a thing in the Hall.\n\
                         The storm is a topic. The box is a container in the Hall.\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 what_a_character_says_becomes_topic_entries_in_it() {
        let text = hexicon(
            "Greeted, Bob says: \"'Hello.'\"\n\
             Asked about the lamp, Bob says: \"'Mine.'\"\n\
             Asked about the storm, the lamp, and the box, Bob says: \"'Wet.'\"\n\
             Told about the storm, Bob says: \"'I know.'\"\n\
             Asked or told about the box, Bob says: \"'Empty.'\"\n\
             Shown the lamp, Bob says: \"'Nice.'\"\n\
             Given the lamp, Bob says: \"'Thanks.'\"\n\
             Shown or given the box, Bob says: \"'No.'\"\n\
             Asked about anything else, Bob says: \"'Eh?'\"\n\
             Otherwise, Bob says: \"Bob shrugs.\"",
        );
        has(
            &text,
            "HelloTopic\n    \"<q>Hello.</q> \"\n    location = bob\n;",
        );
        has(
            &text,
            "AskTopic @lamp\n    \"<q>Mine.</q> \"\n    location = bob\n;",
        );
        has(&text, "AskTopic [storm, lamp, box]\n");
        has(&text, "TellTopic @storm\n");
        has(&text, "AskTellTopic @box\n");
        has(&text, "ShowTopic @lamp\n");
        has(&text, "GiveTopic @lamp\n");
        has(&text, "GiveShowTopic @box\n");
        has(&text, "DefaultAskTopic\n    \"<q>Eh?</q> \"\n");
        has(
            &text,
            "DefaultAnyTopic\n    \"Bob shrugs. \"\n    location = bob\n;",
        );
    }

    #[test]
    fn a_hint_is_a_goal_that_opens_and_closes() {
        let text = hexicon(
            "The hint \"Where is the lamp?\" opens when the box is seen and the player \
             does not have the lamp, and closes when the player has the lamp. It says \
             \"Look around.\", \"It's in the Hall.\", then \"Take it.\"\n\
             The hint \"How do I win?\" It says \"You can't.\"",
        );
        has(
            &text,
            "hintMenu: TopHintMenu 'Hints';\n\nGoal 'Where is the lamp?'\n    [\n        \
             'Look around.',\n        'It\\'s in the Hall.',\n        'Take it.'\n    ]\n    \
             location = hintMenu\n    openWhenTrue = (box.seen && !lamp.isIn(now.player))\n    \
             closeWhenTrue = (lamp.isIn(now.player))\n;",
        );
        has(
            &text,
            "Goal 'How do I win?'\n    [\n        'You can\\'t.'\n    ]\n    location = hintMenu\n    goalState = OpenGoal\n;",
        );
    }

    #[test]
    fn a_sentence_ends_at_a_quotation_s_end() {
        let text = hexicon("Greeted, Bob says: \"'Hello.'\"\nThe cup is a thing in the Hall.");
        has(&text, "cup: Thing 'cup'");
    }

    #[test]
    fn problems_with_talk_and_hints() {
        problem("Greeted, the lamp says: \"Hi.\"", "is not a character");
        problem(
            "Asked about the sea, Bob says: \"Hm.\"",
            "Nothing in the story is called",
        );
        problem("Asked about, Bob says: \"Hm.\"", "I can\u{2019}t read");
        problem("Greeted, Bob says \"Hi.\"", "I can\u{2019}t read");
        problem(
            "The hint \"Help?\" opens when the lamp is shiny. It says \"No.\"",
            "\u{201c}shiny\u{201d} is not something I know",
        );
        problem(
            "The hint \"Help?\" opens when the lamp is seen.",
            "This hint says nothing",
        );
        problem(
            "The hint \"Help?\" It says nothing useful.",
            "What a hint says is said as",
        );
    }
}