use std::collections::HashMap;
mod choices;
mod rules;
mod scenarios;
mod talk;
pub fn is_english(name: &str) -> bool {
name.len() >= 4
&& name
.get(name.len() - 4..)
.is_some_and(|ext| ext.eq_ignore_ascii_case(".hxe"))
}
const FILE_SHIFT: u32 = 24;
const LINE_MASK: u32 = (1 << FILE_SHIFT) - 1;
fn split_line(line: u32) -> (usize, u32) {
((line >> FILE_SHIFT) as usize, line & LINE_MASK)
}
#[derive(Debug, Default)]
pub struct Translation {
pub lines: Vec<(u32, String)>,
pub problems: Vec<(u32, String)>,
}
impl Translation {
pub fn text(&self) -> String {
let mut out = String::new();
for (_, line) in &self.lines {
out.push_str(line);
out.push('\n');
}
out
}
pub fn source(&self, names: &[&str], n: usize) -> String {
let quoted = |file: usize| {
let name = names.get(file).copied().unwrap_or("");
format!("'{}'", name.replace('\\', "\\\\").replace('\'', "\\'"))
};
let mut out = String::new();
if !self.problems.is_empty() {
for (line, message) in &self.problems {
out.push_str(&format!("#line {line} {}\n#error {message}\n", quoted(n)));
}
return out;
}
let mut next = u32::MAX;
for (line, text) in &self.lines {
if *line != next {
let (file, local) = split_line(*line);
out.push_str(&format!("#line {local} {}\n", quoted(file)));
}
out.push_str(text);
out.push('\n');
next = line + 1;
}
out
}
}
pub fn translate(text: &str) -> Translation {
translate_all(&[("", text)]).remove(0)
}
pub fn translate_all(sources: &[(&str, &str)]) -> Vec<Translation> {
let mut reader = Reader::default();
for (n, (_, text)) in sources.iter().enumerate() {
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
let base = (n as u32) << FILE_SHIFT;
let items = read_items(text, base, &mut reader.problems);
reader.last_subject = None;
for item in items {
match item {
Item::Sentence(sentence) => reader.sentence(&sentence),
Item::Block(block) => reader.block(block),
}
}
reader.open_rule = None;
reader.open_hint = None;
reader.open_test = None;
reader.open_moment = None;
reader.open_choice = None;
}
let (lines, problems) = reader.finish(sources.len());
let failed = !problems.is_empty();
let names: Vec<&str> = sources.iter().map(|(name, _)| *name).collect();
lines
.into_iter()
.enumerate()
.map(|(n, lines)| Translation {
lines: if failed { Vec::new() } else { lines },
problems: problems
.iter()
.filter(|(line, _)| split_line(*line).0 == n)
.map(|(line, message)| {
(split_line(*line).1, typeset(&relocate(message, n, &names)))
})
.collect(),
})
.collect()
}
fn relocate(message: &str, n: usize, names: &[&str]) -> String {
let mut out = String::new();
let mut rest = message;
while let Some(at) = rest.find("line ") {
let (before, after) = rest.split_at(at + 5);
out.push_str(before);
let digits: String = after.chars().take_while(char::is_ascii_digit).collect();
rest = &after[digits.len()..];
match digits.parse::<u32>() {
Ok(line) => {
let (file, local) = split_line(line);
out.push_str(&local.to_string());
if file != n {
out.push_str(&format!(" of {}", names.get(file).copied().unwrap_or("")));
}
}
Err(_) => out.push_str(&digits),
}
}
out.push_str(rest);
out
}
fn typeset(message: &str) -> String {
let mut out = String::new();
let mut before = ' ';
for c in message.chars() {
match c {
'"' => out.push(
if before.is_whitespace() || matches!(before, '(' | '\u{201c}') {
'\u{201c}'
} else {
'\u{201d}'
},
),
'\'' => out.push('\u{2019}'),
c => out.push(c),
}
before = c;
}
out
}
#[derive(Debug, Clone, PartialEq)]
enum Tok {
Word(String),
Text(String),
Punct(char),
}
#[derive(Debug, Clone)]
struct Token {
tok: Tok,
line: u32,
}
#[derive(Debug, Clone)]
struct Sentence {
tokens: Vec<Token>,
line: u32,
}
type Lines = Vec<(u32, String)>;
#[derive(Debug, Clone)]
struct Block {
target: Option<Phrase>,
lines: Vec<(u32, String)>,
line: u32,
}
enum Item {
Sentence(Sentence),
Block(Block),
}
fn block_header(line: &str, number: u32) -> Option<Option<Phrase>> {
let rest = line.trim_end();
let rest = rest.strip_suffix(':')?;
let mut words = rest.split_whitespace();
if !words.next()?.eq_ignore_ascii_case("in") {
return None;
}
let second = words.next()?;
let (hexicon, comma) = match second.strip_suffix(',') {
Some(word) => (word, true),
None => (second, false),
};
if !hexicon.eq_ignore_ascii_case("hexicon") {
return None;
}
let rest: Vec<&str> = words.collect();
if rest.is_empty() {
return Some(None);
}
if !comma || !rest[0].eq_ignore_ascii_case("for") || rest.len() < 2 {
return None;
}
Some(Some(Phrase {
words: rest[1..].iter().map(|w| (*w).to_owned()).collect(),
line: number,
}))
}
struct Scanner<'p> {
items: Vec<Item>,
tokens: Vec<Token>,
word: String,
word_line: u32,
quote: Option<(u32, Vec<String>)>,
comment: usize,
may_end: bool,
problems: &'p mut Vec<(u32, String)>,
}
impl Scanner<'_> {
fn end_word(&mut self) {
if !self.word.is_empty() {
let word = std::mem::take(&mut self.word);
self.push(Tok::Word(word), self.word_line);
}
}
fn push(&mut self, tok: Tok, line: u32) {
if self.may_end {
self.may_end = false;
let carries_on = match &tok {
Tok::Word(word) => word.starts_with(|c: char| c.is_lowercase()),
Tok::Punct(c) => matches!(c, ',' | ';' | ':' | ')'),
Tok::Text(_) => false,
};
if !carries_on {
self.end_sentence();
}
}
self.tokens.push(Token { tok, line });
}
fn end_sentence(&mut self) {
self.end_word();
self.may_end = false;
if !self.tokens.is_empty() {
let tokens = std::mem::take(&mut self.tokens);
let line = tokens[0].line;
self.items.push(Item::Sentence(Sentence { tokens, line }));
}
}
fn line(&mut self, line: &str, number: u32) {
if let Some((_, lines)) = &mut self.quote {
lines.push(String::new());
}
for c in line.chars() {
if let Some((start, lines)) = &mut self.quote {
if c == '"' || c == '\u{201d}' || c == '\u{201c}' {
let start = *start;
let lines = std::mem::take(lines);
self.quote = None;
let ends = lines
.last()
.map(|l| l.trim_end().trim_end_matches(['\'', '\u{2019}', ')']))
.is_some_and(|l| l.ends_with(['.', '?', '!']));
let text = text_of(&lines);
self.push(Tok::Text(text), start);
self.may_end = ends;
} else if let Some(last) = lines.last_mut() {
last.push(c);
}
continue;
}
if self.comment > 0 {
match c {
'[' => self.comment += 1,
']' => self.comment -= 1,
_ => {}
}
continue;
}
match c {
'[' => {
self.end_word();
self.comment = 1;
}
'"' | '\u{201c}' | '\u{201d}' => {
self.end_word();
self.quote = Some((number, vec![String::new()]));
}
'.' => self.end_sentence(),
c if c.is_alphanumeric() || c == '-' || c == '_' => {
if self.word.is_empty() {
self.word_line = number;
}
self.word.push(c);
}
'\'' | '\u{2019}' if !self.word.is_empty() => self.word.push('\''),
c if c.is_whitespace() => self.end_word(),
c => {
self.end_word();
self.push(Tok::Punct(c), number);
}
}
}
self.end_word();
}
}
fn read_items(text: &str, base: u32, problems: &mut Vec<(u32, String)>) -> Vec<Item> {
let lines: Vec<&str> = text.lines().collect();
let mut scanner = Scanner {
items: Vec::new(),
tokens: Vec::new(),
word: String::new(),
word_line: 0,
quote: None,
comment: 0,
may_end: false,
problems,
};
let mut i = 0;
while i < lines.len() {
let line = lines[i];
let number = base + i as u32 + 1;
i += 1;
let at_start = !line.starts_with([' ', '\t']);
if at_start
&& scanner.quote.is_none()
&& scanner.comment == 0
&& let Some(target) = block_header(line, number)
{
if scanner.may_end {
scanner.end_sentence();
}
if !scanner.tokens.is_empty() || !scanner.word.is_empty() {
let at = scanner.tokens.first().map_or(number, |t| t.line);
scanner.problems.push((
at,
"This sentence has no full stop at its end, before the block of \
Hexicon after it."
.to_owned(),
));
scanner.end_sentence();
}
let mut block = Vec::new();
while i < lines.len() {
let line = lines[i];
if !line.trim().is_empty() && !line.starts_with([' ', '\t']) {
break;
}
block.push((base + i as u32 + 1, line.to_owned()));
i += 1;
}
while block.last().is_some_and(|(_, l)| l.trim().is_empty()) {
block.pop();
}
let indent = block
.iter()
.filter(|(_, l)| !l.trim().is_empty())
.map(|(_, l)| l.len() - l.trim_start().len())
.min()
.unwrap_or(0);
let lines = block
.into_iter()
.map(|(n, l)| (n, l.get(indent..).unwrap_or("").trim_end().to_owned()))
.collect::<Vec<_>>();
if lines.is_empty() {
scanner.problems.push((
number,
"A block of Hexicon has nothing in it: its lines go after it, \
each indented."
.to_owned(),
));
}
scanner.items.push(Item::Block(Block {
target,
lines,
line: number,
}));
continue;
}
scanner.line(line, number);
}
if let Some((start, _)) = scanner.quote {
scanner.problems.push((
start,
"This quoted text has no closing quotation mark.".to_owned(),
));
}
scanner.end_sentence();
scanner.items
}
fn text_of(lines: &[String]) -> String {
let mut paragraphs: Vec<String> = Vec::new();
let mut current: Vec<&str> = Vec::new();
for line in lines {
let line = line.trim();
if line.is_empty() {
if !current.is_empty() {
paragraphs.push(current.join(" "));
current.clear();
}
} else {
current.push(line);
}
}
if !current.is_empty() {
paragraphs.push(current.join(" "));
}
let joined = paragraphs.join("<.p>");
let chars: Vec<char> = joined.chars().collect();
let mut out = String::new();
let mut open = false;
for (i, &c) in chars.iter().enumerate() {
if c == '\'' || c == '\u{2018}' || c == '\u{2019}' {
let before = i.checked_sub(1).map(|j| chars[j]);
let after = chars.get(i + 1).copied();
let letter = |c: Option<char>| c.is_some_and(char::is_alphanumeric);
let possessive = before == Some('s')
&& after == Some(' ')
&& chars.get(i + 2).is_some_and(|c| c.is_lowercase());
if letter(before) && letter(after) || possessive {
out.push('\'');
} else if open && !letter(after) {
out.push_str("</q>");
open = false;
} else if !open && !letter(before) && after.is_some_and(|c| !c.is_whitespace()) {
out.push_str("<q>");
open = true;
} else {
out.push('\'');
}
continue;
}
out.push(c);
}
out.replace('\\', "\\\\").replace("<<", "\\<\\<")
}
#[derive(Debug, Clone, PartialEq)]
struct Phrase {
words: Vec<String>,
line: u32,
}
const ARTICLES: &[&str] = &["the", "a", "an", "some"];
const PRONOUNS: &[&str] = &["it", "he", "she", "him", "her", "they", "them"];
impl Phrase {
fn lower(&self) -> Vec<String> {
self.words.iter().map(|w| w.to_lowercase()).collect()
}
fn bare(&self) -> Vec<String> {
let lower = self.lower();
match lower.first() {
Some(first) if ARTICLES.contains(&first.as_str()) && lower.len() > 1 => {
lower[1..].to_vec()
}
_ => lower,
}
}
fn shown(&self) -> String {
let mut words = self.words.clone();
if let Some(first) = words.first_mut()
&& ARTICLES.contains(&first.to_lowercase().as_str())
{
*first = first.to_lowercase();
}
words.join(" ")
}
fn is_pronoun(&self) -> bool {
self.words.len() == 1 && PRONOUNS.contains(&self.words[0].to_lowercase().as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Kind {
Room,
Thing,
Container,
Surface,
Door,
Key,
Man,
Woman,
Person,
Fixture,
Decoration,
Topic,
}
const KINDS: &[(&str, Kind)] = &[
("room", Kind::Room),
("thing", Kind::Thing),
("container", Kind::Container),
("surface", Kind::Surface),
("supporter", Kind::Surface),
("door", Kind::Door),
("key", Kind::Key),
("man", Kind::Man),
("woman", Kind::Woman),
("person", Kind::Person),
("fixture", Kind::Fixture),
("decoration", Kind::Decoration),
("topic", Kind::Topic),
];
impl Kind {
fn is_person(self) -> bool {
matches!(self, Kind::Man | Kind::Woman | Kind::Person)
}
}
fn kind_of(word: &str) -> Option<Kind> {
KINDS
.iter()
.find(|(name, _)| *name == word)
.map(|(_, kind)| *kind)
}
fn kind_names() -> String {
list_of(
&KINDS.iter().map(|(name, _)| *name).collect::<Vec<_>>(),
"and",
)
}
const ADJECTIVES: &[(&str, &[(&str, &str)])] = &[
("openable", &[("isOpenable", "true")]),
("open", &[("isOpenable", "true"), ("isOpen", "true")]),
("closed", &[("isOpenable", "true"), ("isOpen", "nil")]),
("locked", &[("isLocked", "true")]),
("unlocked", &[("isLocked", "nil")]),
("lit", &[("isLit", "true")]),
("unlit", &[("isLit", "nil")]),
("dark", &[("isLit", "nil")]),
("switchable", &[("isSwitchable", "true")]),
("lightable", &[("isLightable", "true")]),
("wearable", &[("isWearable", "true")]),
("edible", &[("isEdible", "true")]),
("fixed", &[("isFixed", "true")]),
("portable", &[("isFixed", "nil")]),
("transparent", &[("isTransparent", "true")]),
("enterable", &[("isEnterable", "true")]),
("climbable", &[("isClimbable", "true")]),
("familiar", &[("familiar", "true")]),
];
const ROOM_ADJECTIVES: &[&str] = &["lit", "dark"];
fn adjective(word: &str) -> Option<&'static [(&'static str, &'static str)]> {
ADJECTIVES
.iter()
.find(|(name, _)| *name == word)
.map(|(_, props)| *props)
}
fn adjective_names(kind: Kind) -> String {
let names: Vec<&str> = ADJECTIVES
.iter()
.map(|(name, _)| *name)
.filter(|name| kind != Kind::Room || ROOM_ADJECTIVES.contains(name))
.filter(|name| kind != Kind::Topic || *name == "familiar")
.collect();
list_of(&names, "or")
}
const DIRECTIONS: &[(&str, &str, usize)] = &[
("north", "north", 1),
("south", "south", 0),
("east", "east", 3),
("west", "west", 2),
("northeast", "northeast", 5),
("southwest", "southwest", 4),
("northwest", "northwest", 7),
("southeast", "southeast", 6),
("up", "up", 9),
("down", "down", 8),
("inside", "in", 11),
("outside", "out", 10),
("port", "port", 13),
("starboard", "starboard", 12),
("fore", "fore", 15),
("aft", "aft", 14),
];
fn direction(word: &str) -> Option<usize> {
DIRECTIONS.iter().position(|(name, _, _)| *name == word)
}
fn list_of(items: &[&str], last: &str) -> String {
match items {
[] => String::new(),
[one] => (*one).to_owned(),
[rest @ .., final_one] => format!("{}, {last} {final_one}", rest.join(", ")),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Target {
Obj(usize),
Player,
Story,
}
#[derive(Debug, Clone)]
enum Statement {
Story {
title: String,
byline: Option<String>,
},
StoryProp { key: &'static str, value: String },
Begins(String),
StoryFlag(&'static str),
PlayerIn(Phrase),
Desc { subject: Phrase, text: String },
Place { subject: Phrase, place: Phrase },
Adjectives { subject: Phrase, words: Vec<String> },
AlsoCalled { subject: Phrase, names: Vec<Phrase> },
Exit {
dir: usize,
from: Phrase,
to: Phrase,
one_way: bool,
},
Unlocks { key: Phrase, target: Phrase },
Familiar(Phrase),
BlockFor(Phrase, Vec<(u32, String)>),
HexName { subject: Phrase, name: String },
SideDesc {
room: Phrase,
door: Phrase,
text: String,
},
Listed { subject: Phrase, text: String },
Topic {
character: Phrase,
class: &'static str,
about: Vec<Phrase>,
text: String,
},
}
#[derive(Debug)]
struct Obj {
name: String,
words: Vec<String>,
some: bool,
proper: bool,
kind: Kind,
id: String,
line: u32,
order: usize,
desc: Option<(u32, String)>,
location: Option<(u32, Target)>,
props: Vec<(u32, String, String)>,
adjectives: Vec<String>,
nouns: Vec<String>,
also: Vec<Vec<String>>,
exits: HashMap<usize, (String, u32, bool)>,
keys: Vec<(u32, usize)>,
sides: Vec<(usize, Phrase)>,
members: Vec<(u32, String)>,
after: Vec<(u32, String)>,
wanted_id: Option<(u32, String)>,
side_desc: [Option<(u32, String)>; 2],
topics: Vec<(u32, &'static str, Option<String>, String)>,
begins: Vec<(u32, String)>,
}
impl Obj {
fn called(&self) -> String {
if self.proper {
self.name.clone()
} else {
format!("the {}", self.name)
}
}
}
#[derive(Default)]
struct Reader {
problems: Vec<(u32, String)>,
statements: Vec<(u32, usize, Statement)>,
objs: Vec<Obj>,
story: Option<(u32, usize)>,
player: Option<(u32, usize)>,
free_blocks: Vec<(usize, Vec<(u32, String)>)>,
last_subject: Option<Phrase>,
failed: Vec<Vec<String>>,
sentences: usize,
rules: Vec<rules::Rule>,
open_rule: Option<usize>,
written: Vec<rules::Written>,
achievements: Vec<rules::Achievement>,
used_ids: Vec<String>,
scoring_line: u32,
scoring_order: usize,
hints: Vec<talk::Hint>,
written_hints: Vec<talk::WrittenHint>,
open_hint: Option<usize>,
tests: Vec<scenarios::Test>,
walkthroughs: Vec<scenarios::WalkthroughRead>,
open_test: Option<usize>,
written_tests: Vec<(usize, Vec<(u32, String)>)>,
moments: Vec<choices::Moment>,
open_moment: Option<usize>,
open_choice: Option<usize>,
written_moments: Vec<(usize, Vec<(u32, String)>)>,
thing_choices: Vec<(usize, choices::ChoiceRead)>,
}
fn word_of(token: &Token) -> Option<String> {
match &token.tok {
Tok::Word(word) => Some(word.to_lowercase()),
_ => None,
}
}
fn is_word(token: Option<&Token>, words: &[&str]) -> bool {
token
.and_then(word_of)
.is_some_and(|w| words.contains(&w.as_str()))
}
fn phrase(tokens: &[Token]) -> Option<Phrase> {
if tokens.is_empty() {
return None;
}
let mut words = Vec::new();
for token in tokens {
match &token.tok {
Tok::Word(word) => words.push(word.clone()),
_ => return None,
}
}
Some(Phrase {
words,
line: tokens[0].line,
})
}
fn shown(tokens: &[Token]) -> String {
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::Text(_) => {
if !out.is_empty() {
out.push(' ');
}
out.push_str("\"...\"");
}
Tok::Punct(c) => out.push(*c),
}
}
out
}
fn strip_one_way(tokens: &[Token]) -> (&[Token], bool) {
let n = tokens.len();
if n >= 3
&& matches!(tokens[n - 3].tok, Tok::Punct(','))
&& is_word(tokens.get(n - 2), &["one"])
&& is_word(tokens.get(n - 1), &["way"])
{
return (&tokens[..n - 3], true);
}
if n >= 4
&& matches!(tokens[n - 4].tok, Tok::Punct('('))
&& is_word(tokens.get(n - 3), &["one"])
&& is_word(tokens.get(n - 2), &["way"])
&& matches!(tokens[n - 1].tok, Tok::Punct(')'))
{
return (&tokens[..n - 4], true);
}
(tokens, false)
}
fn direction_of(tokens: &[Token]) -> Option<(usize, &[Token])> {
let dir = direction(&word_of(tokens.first()?)?)?;
if is_word(tokens.get(1), &["of", "from"]) {
Some((dir, &tokens[2..]))
} else {
None
}
}
const PATTERNS: &str = "A sentence can say what something is (\"The Hall is a room.\"), \
where it is (\"The lamp is in the Hall.\"), what it is like (\"The box is openable.\"), \
how rooms connect (\"North of the Hall is the Kitchen.\"), what else it is called \
(\"The lamp is also called the brass lamp.\"), what unlocks it (\"The key unlocks the \
door.\"), or its description, as quoted text after a sentence about it.";
impl Reader {
fn problem(&mut self, line: u32, message: impl Into<String>) {
let message = message.into();
if !message.is_empty() {
self.problems.push((line, message));
}
}
fn add(&mut self, line: u32, statement: Statement) {
let order = self.sentences;
self.statements.push((line, order, statement));
}
fn subject(&mut self, phrase: Phrase) -> Option<Phrase> {
if phrase.is_pronoun() {
match &self.last_subject {
Some(last) => Some(Phrase {
words: last.words.clone(),
line: phrase.line,
}),
None => {
self.problem(
phrase.line,
format!(
"\"{}\" has nothing to stand for: no sentence before this one \
names anything.",
phrase.shown()
),
);
None
}
}
} else {
Some(phrase)
}
}
fn sentence(&mut self, sentence: &Sentence) {
self.sentences += 1;
let t = &sentence.tokens;
let line = sentence.line;
if self.choice_sentence(line, t)
|| self.rule_continues(line, t)
|| self.rule_sentence(line, t)
|| self.talk_sentence(line, t)
|| self.test_sentence(line, t)
{
return;
}
if is_word(t.first(), &["the"])
&& is_word(t.get(1), &["player"])
&& is_word(t.get(2), &["carries"])
{
match phrase(&t[3..]) {
Some(thing) => {
let Some(thing) = self.subject(thing) else {
return;
};
self.last_subject = Some(thing.clone());
let place = Phrase {
words: vec!["player".to_owned()],
line,
};
self.add(
line,
Statement::Place {
subject: thing,
place,
},
);
}
None => self.problem(
line,
format!(
"I can't read \"{}\". What the player starts with is said as \"The \
player carries the lamp.\"",
shown(t)
),
),
}
return;
}
if is_word(t.first(), &["seen"]) && is_word(t.get(1), &["from"]) {
self.seen_from(line, t);
return;
}
if let [
Token {
tok: Tok::Text(text),
..
},
] = t.as_slice()
{
match self.last_subject.clone() {
Some(subject) => self.add(
line,
Statement::Desc {
subject,
text: text.clone(),
},
),
None => self.problem(
line,
"This quoted text describes nothing: a description comes after a \
sentence about what it describes.",
),
}
return;
}
if is_word(t.first(), &["everyone", "everybody"])
&& is_word(t.get(1), &["knows"])
&& is_word(t.get(2), &["of", "about"])
{
match phrase(&t[3..]) {
Some(p) => {
if let Some(p) = self.subject(p) {
self.last_subject = Some(p.clone());
self.add(line, Statement::Familiar(p));
}
}
None => self.problem(
line,
"Say what everyone knows of: \"Everyone knows of the lamp.\"",
),
}
return;
}
let verb = t
.iter()
.position(|token| is_word(Some(token), &["is", "are", "unlocks", "begins"]));
let Some(v) = verb else {
self.problem(line, format!("I can't read \"{}\". {PATTERNS}", shown(t)));
return;
};
let verb_word = word_of(&t[v]).unwrap_or_default();
let (left, right) = (&t[..v], &t[v + 1..]);
match verb_word.as_str() {
"begins" => self.begins(line, left, right, t),
"unlocks" => self.unlocks(line, left, right, t),
_ => self.is(line, left, right, t),
}
}
fn begins(&mut self, line: u32, left: &[Token], right: &[Token], t: &[Token]) {
let left = phrase(left).map(|p| p.bare());
let is_story = matches!(left.as_deref(), Some([w]) if w == "story" || w == "it");
let text = match right {
[
Token {
tok: Tok::Punct(':'),
..
},
Token {
tok: Tok::Text(text),
..
},
]
| [
Token {
tok: Tok::Text(text),
..
},
] => Some(text.clone()),
_ => None,
};
match (is_story, text) {
(true, Some(text)) => self.add(line, Statement::Begins(text)),
_ => self.problem(
line,
format!(
"I can't read \"{}\". How the story begins is said as \
The story begins: \"...\" (or It begins: \"...\", after the \
sentence about the story).",
shown(t)
),
),
}
}
fn unlocks(&mut self, line: u32, left: &[Token], right: &[Token], t: &[Token]) {
match (phrase(left), phrase(right)) {
(Some(key), Some(target)) => {
let Some(target) = self.subject(target) else {
return;
};
let Some(key) = self.subject(key) else { return };
self.last_subject = Some(key.clone());
self.add(line, Statement::Unlocks { key, target });
}
_ => self.problem(
line,
format!(
"I can't read \"{}\". What a key unlocks is said as \
\"The brass key unlocks the door.\"",
shown(t)
),
),
}
}
fn is(&mut self, line: u32, left: &[Token], right: &[Token], t: &[Token]) {
if let Some((dir, from)) = direction_of(left) {
let (to, one_way) = strip_one_way(right);
match (phrase(from), phrase(to)) {
(Some(from), Some(to)) => {
let Some(from) = self.subject(from) else {
return;
};
let Some(to) = self.subject(to) else { return };
self.last_subject = Some(to.clone());
self.add(
line,
Statement::Exit {
dir,
from,
to,
one_way,
},
);
}
_ => self.problem(
line,
format!(
"I can't read \"{}\". A way between rooms is said as \
\"North of the Hall is the Kitchen.\", and one with no \
way back as \"North of the Hall is the Kitchen, one way.\"",
shown(t)
),
),
}
return;
}
if let Some(p) = left
.iter()
.position(|token| word_of(token).is_some_and(|w| w.ends_with("'s")))
{
let owner = word_of(&left[p]).unwrap_or_default();
let owner = owner.trim_end_matches("'s").to_owned();
let key = phrase(&left[p + 1..]).map(|k| k.lower().join(" "));
let value = match right {
[
Token {
tok: Tok::Text(text),
..
},
] => Some(text.clone()),
_ => None,
};
let known: &[(&str, &'static str)] = &[
("ifid", "IFID"),
("byline", "byline"),
("version", "version"),
("headline", "headline"),
("genre", "genreName"),
("description", "desc"),
("author's email", "authorEmail"),
("email", "authorEmail"),
];
let found = key
.as_deref()
.and_then(|k| known.iter().find(|(name, _)| *name == k));
match (owner.as_str(), found, value) {
("story", Some((_, prop)), Some(value)) => {
self.last_subject = Some(Phrase {
words: vec!["story".to_owned()],
line,
});
self.add(line, Statement::StoryProp { key: prop, value });
}
("story", _, _) => self.problem(
line,
format!(
"I can't read \"{}\". What can be said of the story is its IFID, \
its byline, its version, its headline, its genre, its description, and its \
author's email, \
each as quoted text: The story's version is \"1\".",
shown(t)
),
),
_ => self.problem(
line,
format!(
"I can't read \"{}\". Only the story's details are said with \"'s\" \
(The story's version is \"1\"); what a thing is like is said of \
it: \"The box is openable.\"",
shown(t)
),
),
}
return;
}
let Some(subject) = phrase(left) else {
self.problem(line, format!("I can't read \"{}\". {PATTERNS}", shown(t)));
return;
};
let Some(subject) = self.subject(subject) else {
return;
};
let bare = subject.bare();
self.last_subject = Some(subject.clone());
if bare == ["story"] {
let words: Vec<String> = right.iter().map_while(word_of).collect();
let flag = match (words.as_slice(), right.len() == words.len()) {
([told, in_, choices], true)
if told == "told" && in_ == "in" && choices == "choices" =>
{
Some("choiceGame")
}
([told, in_, choices, alone], true)
if told == "told"
&& in_ == "in"
&& choices == "choices"
&& alone == "alone" =>
{
Some("choicesOnly")
}
_ => None,
};
if let Some(flag) = flag {
self.add(line, Statement::StoryFlag(flag));
return;
}
}
if bare == ["story"] {
self.story_sentence(line, right, t);
return;
}
if bare == ["player"] {
let place = match right.first() {
Some(_) if is_word(right.first(), &["in", "on"]) => phrase(&right[1..]),
_ => None,
};
match place {
Some(place) => {
if self.player.is_some() {
self.problem(line, "Where the player starts is already said.");
return;
}
self.player = Some((line, self.sentences));
self.add(line, Statement::PlayerIn(place));
}
None => self.problem(
line,
format!(
"I can't read \"{}\". Of the player, what can be said is where they \
start: \"The player is in the Hall.\"",
shown(t)
),
),
}
return;
}
if let Some((dir, from)) = direction_of(right) {
let (from, one_way) = strip_one_way(from);
match phrase(from) {
Some(from) => {
let Some(from) = self.subject(from) else {
return;
};
self.add(
line,
Statement::Exit {
dir,
from,
to: subject,
one_way,
},
);
}
None => self.problem(line, format!("I can't read \"{}\". {PATTERNS}", shown(t))),
}
return;
}
if is_word(right.first(), &["called"])
&& right.len() == 4
&& is_word(right.get(2), &["in"])
&& is_word(right.get(3), &["hexicon"])
&& let Tok::Word(name) = &right[1].tok
{
self.add(
line,
Statement::HexName {
subject,
name: name.clone(),
},
);
return;
}
if let [
listed,
as_,
Token {
tok: Tok::Text(text),
..
},
] = right
&& is_word(Some(listed), &["listed"])
&& is_word(Some(as_), &["as"])
{
self.add(
line,
Statement::Listed {
subject,
text: text.clone(),
},
);
return;
}
if is_word(right.first(), &["also"]) && is_word(right.get(1), &["called"]) {
let names = split_list(&right[2..]);
match names {
Some(names) if !names.is_empty() => {
self.add(line, Statement::AlsoCalled { subject, names });
}
_ => self.problem(
line,
format!(
"I can't read \"{}\". Other names are said as \"The lamp is also \
called the brass lamp and the lantern.\"",
shown(t)
),
),
}
return;
}
if is_word(right.first(), &["in", "on", "inside"]) {
match phrase(&right[1..]) {
Some(place) => {
let Some(place) = self.subject(place) else {
return;
};
self.add(line, Statement::Place { subject, place });
}
None => self.problem(
line,
format!(
"I can't read \"{}\". Where something is is said as \"The lamp \
is in the Hall.\"",
shown(t)
),
),
}
return;
}
if is_word(right.first(), &["a", "an"]) {
let made = self.objs.len();
self.define(line, subject.clone(), &right[1..], t);
if self.objs.len() == made {
self.failed.push(subject.bare());
}
return;
}
match split_list(right) {
Some(items) if items.iter().all(|p| p.words.len() == 1) => {
let words = items.iter().map(|p| p.words[0].to_lowercase()).collect();
self.add(line, Statement::Adjectives { subject, words });
}
_ => self.problem(line, format!("I can't read \"{}\". {PATTERNS}", shown(t))),
}
}
fn story_sentence(&mut self, line: u32, right: &[Token], t: &[Token]) {
let (title, rest) = match right {
[
Token {
tok: Tok::Text(title),
..
},
rest @ ..,
] => (title.clone(), rest),
_ => {
self.problem(
line,
format!(
"I can't read \"{}\". The story is named as \
The story is \"The Lighthouse\", by Jane Doe.",
shown(t)
),
);
return;
}
};
let rest = match rest {
[
Token {
tok: Tok::Punct(','),
..
},
rest @ ..,
] => rest,
rest => rest,
};
let byline = match rest {
[] => Some(None),
[
by,
Token {
tok: Tok::Text(author),
..
},
] if is_word(Some(by), &["by"]) => Some(Some(format!("by {author}"))),
[by, author @ ..] if is_word(Some(by), &["by"]) => {
phrase(author).map(|a| Some(format!("by {}", a.shown())))
}
_ => None,
};
let Some(byline) = byline else {
self.problem(
line,
format!(
"I can't read \"{}\". The story is named as \
The story is \"The Lighthouse\", by Jane Doe.",
shown(t)
),
);
return;
};
if let Some((first, _)) = self.story {
self.problem(
line,
format!("The story is already named, on line {first}."),
);
return;
}
self.story = Some((line, self.sentences));
self.add(line, Statement::Story { title, byline });
}
fn define(&mut self, line: u32, subject: Phrase, right: &[Token], t: &[Token]) {
let end = right
.iter()
.enumerate()
.position(|(i, token)| {
!matches!(token.tok, Tok::Word(_))
|| is_word(Some(token), &["in", "on", "inside"])
|| direction_of(&right[i..]).is_some()
})
.unwrap_or(right.len());
let words: Vec<String> = right[..end].iter().filter_map(word_of).collect();
let Some((kind_word, adjectives)) = words.split_last() else {
self.problem(
line,
format!(
"I can't read \"{}\". Say what kind of thing it is: \"The Hall is a room.\"",
shown(t)
),
);
return;
};
let Some(kind) = kind_of(kind_word) else {
self.problem(
line,
format!(
"\"{kind_word}\" is not a kind I know. The kinds are {}.",
kind_names()
),
);
return;
};
for adjective in adjectives {
if !self.adjective_fits(line, kind, adjective) {
return;
}
}
let mut rest = &right[end..];
let mut place = None;
let mut sides = Vec::new();
if is_word(rest.first(), &["in", "on", "inside"]) {
match phrase(&rest[1..]) {
Some(p) => {
let Some(p) = self.subject(p) else { return };
place = Some(p);
}
None => {
self.problem(
line,
format!(
"I can't read \"{}\". Where it is is said as \
\"The lamp is a thing in the Hall.\"",
shown(t)
),
);
return;
}
}
rest = &[];
}
let mut one_way = false;
if !rest.is_empty() {
let (r, ow) = strip_one_way(rest);
one_way = ow;
rest = r;
if let [
Token {
tok: Tok::Punct(','),
..
},
r @ ..,
] = rest
{
rest = r;
}
let Some(items) = split_ways(rest) else {
self.problem(
line,
format!(
"I can't read \"{}\". A door's sides are said as \
\"The oak door is a door, north of the Hall and south of the \
Kitchen.\"",
shown(t)
),
);
return;
};
sides = items;
}
let name_words = subject.bare();
let some = subject.lower().first().is_some_and(|w| w == "some");
let shown_words: Vec<String> = if subject.words.len() > name_words.len() {
subject.words[1..].to_vec()
} else {
subject.words.clone()
};
if let Some(other) = self.objs.iter().find(|o| o.words == name_words) {
let (first, name) = (other.line, other.called());
self.problem(
line,
format!("There is already something called \"{name}\", made on line {first}."),
);
return;
}
if name_words == ["player"] || name_words == ["story"] {
self.problem(
line,
format!(
"\"{}\" is the story's own; something the story makes needs another name.",
subject.shown()
),
);
return;
}
match kind {
Kind::Door => {
if sides.is_empty() {
self.problem(
line,
"Say where the door is, by the way it leads from each side: \
\"The oak door is a door, north of the Hall and south of the \
Kitchen.\"",
);
return;
}
if sides.len() > 2 {
self.problem(line, "A door has two sides, not more.");
return;
}
if place.is_some() || one_way {
self.problem(
line,
"A door is where its sides say: \"north of the Hall and south of \
the Kitchen\".",
);
return;
}
}
Kind::Room => {
if place.is_some() {
self.problem(line, "A room is not in anything; say how it connects to others: \"The Kitchen is a room north of the Hall.\"");
return;
}
}
_ => {
if !sides.is_empty() {
self.problem(
line,
"Only a room or a door can be said to be a way from a room: \
put a thing in a room with \"in\".",
);
return;
}
}
}
let mut props = Vec::new();
for adjective in adjectives {
for (prop, value) in adjective_props(kind, adjective) {
props.push((line, prop.to_owned(), value.to_owned()));
}
}
let door_sides = if kind == Kind::Door {
std::mem::take(&mut sides)
} else {
Vec::new()
};
self.objs.push(Obj {
name: shown_words.join(" "),
words: name_words,
some,
proper: subject.words.len() == shown_words.len(),
kind,
id: String::new(),
line,
order: self.sentences,
desc: None,
location: None,
props,
adjectives: Vec::new(),
nouns: Vec::new(),
also: Vec::new(),
exits: HashMap::new(),
keys: Vec::new(),
sides: door_sides,
members: Vec::new(),
after: Vec::new(),
wanted_id: None,
side_desc: [None, None],
topics: Vec::new(),
begins: Vec::new(),
});
if let Some(place) = place {
self.add(
line,
Statement::Place {
subject: subject.clone(),
place,
},
);
}
for (dir, from) in sides {
self.add(
line,
Statement::Exit {
dir,
from,
to: subject.clone(),
one_way,
},
);
}
}
fn adjective_fits(&mut self, line: u32, kind: Kind, word: &str) -> bool {
let known = adjective(word).is_some()
&& (kind != Kind::Room || ROOM_ADJECTIVES.contains(&word))
&& (kind != Kind::Topic || word == "familiar");
if !known {
let what = match kind {
Kind::Room => "a room",
Kind::Topic => "a topic",
_ => "a thing",
};
self.problem(
line,
format!(
"\"{word}\" is not something I know {what} can be. It can be {}.",
adjective_names(kind)
),
);
}
known
}
fn seen_from(&mut self, line: u32, t: &[Token]) {
let comma = t
.iter()
.position(|token| matches!(token.tok, Tok::Punct(',')));
let is = t.iter().position(|token| is_word(Some(token), &["is"]));
let parts = match (comma, is, t.last()) {
(
Some(c),
Some(v),
Some(Token {
tok: Tok::Text(text),
..
}),
) if c < v && v + 2 == t.len() => phrase(&t[2..c])
.zip(phrase(&t[c + 1..v]))
.map(|(room, door)| (room, door, text.clone())),
_ => None,
};
match parts {
Some((room, door, text)) => {
let Some(door) = self.subject(door) else {
return;
};
self.last_subject = Some(door.clone());
self.add(line, Statement::SideDesc { room, door, text });
}
None => self.problem(
line,
format!(
"I can't read \"{}\". A door's description from one side is said as \
Seen from the Kitchen, the oak door is \"...\".",
shown(t)
),
),
}
}
fn block(&mut self, block: Block) {
self.sentences += 1;
self.open_rule = None;
self.open_hint = None;
self.open_test = None;
self.open_moment = None;
self.open_choice = None;
match block.target {
Some(target) => {
let Some(target) = self.subject(target) else {
return;
};
self.add(block.line, Statement::BlockFor(target, block.lines));
}
None => self.free_blocks.push((self.sentences, block.lines)),
}
}
fn resolve(&self, phrase: &Phrase) -> Result<Target, String> {
let bare = phrase.bare();
if bare == ["player"] || bare == ["you"] {
return Ok(Target::Player);
}
if bare == ["story"] {
return Ok(Target::Story);
}
let failed = |words: &Vec<String>| bare.iter().all(|w| words.contains(w));
if self.failed.contains(&bare) {
return Err(String::new());
}
let exact: Vec<usize> = (0..self.objs.len())
.filter(|&i| self.objs[i].words == bare || self.objs[i].also.contains(&bare))
.collect();
if let [one] = exact.as_slice() {
return Ok(Target::Obj(*one));
}
let partial: Vec<usize> = (0..self.objs.len())
.filter(|&i| {
let obj = &self.objs[i];
bare.iter()
.all(|w| obj.words.contains(w) || obj.also.iter().any(|a| a.contains(w)))
})
.collect();
let last = bare.last();
let headed: Vec<usize> = partial
.iter()
.copied()
.filter(|&i| {
let obj = &self.objs[i];
obj.words.last() == last || obj.also.iter().any(|a| a.last() == last)
})
.collect();
let partial = if headed.len() == 1 { headed } else { partial };
match partial.as_slice() {
[one] => Ok(Target::Obj(*one)),
[] if self.failed.iter().any(failed) => Err(String::new()),
[] => {
let near = self.nearest(&bare.join(" "));
Err(match near {
Some(name) => format!(
"Nothing in the story is called \"{}\". Did you mean \"{name}\"?",
phrase.shown()
),
None => format!(
"Nothing in the story is called \"{}\": say what it is \
(\"The {} is a thing.\").",
phrase.shown(),
bare.join(" ")
),
})
}
many => {
let names: Vec<String> = many
.iter()
.map(|&i| format!("\"{}\"", self.objs[i].called()))
.collect();
let names: Vec<&str> = names.iter().map(String::as_str).collect();
Err(format!(
"\"{}\" could be {}; say which.",
phrase.shown(),
list_of(&names, "or")
))
}
}
}
fn nearest(&self, wanted: &str) -> Option<String> {
let mut best: Option<(usize, String)> = None;
for obj in &self.objs {
let name = obj.words.join(" ");
let distance = edit_distance(wanted, &name);
if distance <= (wanted.len() / 3).max(2)
&& best.as_ref().is_none_or(|(d, _)| distance < *d)
{
best = Some((distance, obj.called()));
}
}
best.map(|(_, name)| name)
}
fn resolve_obj(&mut self, phrase: &Phrase) -> Option<usize> {
match self.resolve(phrase) {
Ok(Target::Obj(i)) => Some(i),
Ok(_) => {
self.problem(
phrase.line,
format!("\"{}\" is not a thing or a room here.", phrase.shown()),
);
None
}
Err(message) => {
self.problem(phrase.line, message);
None
}
}
}
fn resolve_room(&mut self, phrase: &Phrase) -> Option<usize> {
let i = self.resolve_obj(phrase)?;
if self.objs[i].kind != Kind::Room {
self.problem(
phrase.line,
format!(
"\"{}\" is not a room, and only rooms connect by ways north, up, \
and the rest.",
phrase.shown()
),
);
return None;
}
Some(i)
}
#[allow(clippy::type_complexity)]
fn finish(mut self, files: usize) -> (Vec<Lines>, Vec<(u32, String)>) {
let statements = std::mem::take(&mut self.statements);
for (_, _, statement) in &statements {
if let Statement::AlsoCalled { subject, names } = statement {
let Some(i) = self.resolve_obj(subject) else {
continue;
};
for name in names {
let words = name.bare();
if let Some((noun, adjectives)) = words.split_last() {
let obj = &mut self.objs[i];
for adjective in adjectives {
if !obj.words.contains(adjective) && !obj.adjectives.contains(adjective)
{
obj.adjectives.push(adjective.clone());
}
}
if !obj.words.contains(noun) && !obj.nouns.contains(noun) {
obj.nouns.push(noun.clone());
}
obj.also.push(words.clone());
}
}
}
}
for (line, _, statement) in &statements {
if let Statement::HexName { subject, name } = statement {
let Some(i) = self.resolve_obj(subject) else {
continue;
};
let valid = name.starts_with(|c: char| c.is_ascii_alphabetic())
&& name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
if !valid || RESERVED.contains(&name.as_str()) {
self.problem(
*line,
format!(
"\"{name}\" can't be a name in Hexicon: one starts with a letter, \
has only letters, digits, and underscores, and is not one of the \
language's words."
),
);
continue;
}
if let Some(other) = self
.objs
.iter()
.find(|o| o.wanted_id.as_ref().is_some_and(|(_, w)| w == name))
{
let (first, who) =
(other.wanted_id.as_ref().map_or(0, |w| w.0), other.called());
self.problem(
*line,
format!("\"{name}\" is already {who}'s name in Hexicon, on line {first}."),
);
continue;
}
if let Some((first, _)) = &self.objs[i].wanted_id {
let first = *first;
let who = self.objs[i].called();
self.problem(
*line,
format!("{who}'s name in Hexicon is already said, on line {first}."),
);
continue;
}
self.objs[i].wanted_id = Some((*line, name.clone()));
}
}
self.make_ids();
let mut story: Option<StoryInfo> = None;
let mut player_at: Option<(u32, usize)> = None;
let mut explicit_exits: Vec<(u32, usize, usize, usize, bool)> = Vec::new();
for (line, order, statement) in statements {
match statement {
Statement::Story { title, byline } => {
let story = story.get_or_insert_with(StoryInfo::default);
story.line = line;
story.order = order;
story.title = Some(title);
story.byline = byline;
}
Statement::StoryProp { key, value } => {
story
.get_or_insert_with(StoryInfo::default)
.props
.push((line, key, value));
}
Statement::StoryFlag(flag) => {
story
.get_or_insert_with(StoryInfo::default)
.flags
.push((line, flag));
}
Statement::Begins(text) => {
let story = story.get_or_insert_with(StoryInfo::default);
if story.intro.is_some() {
self.problem(line, "How the story begins is already said.");
}
story.intro = Some((line, text));
}
Statement::PlayerIn(place) => {
if let Some(i) = self.resolve_obj(&place) {
player_at = Some((line, i));
}
}
Statement::Desc { subject, text } => match self.resolve(&subject) {
Ok(Target::Obj(i)) => {
if let Some((first, _)) = self.objs[i].desc {
let name = self.objs[i].called();
self.problem(
line,
format!("\"{name}\" already has its description, on line {first}."),
);
} else {
self.objs[i].desc = Some((line, text));
}
}
Ok(_) => self.problem(
line,
"This quoted text describes nothing: a description comes after a \
sentence about what it describes.",
),
Err(message) => self.problem(line, message),
},
Statement::Place { subject, place } => {
let Some(i) = self.resolve_obj(&subject) else {
continue;
};
if matches!(self.resolve(&place), Ok(Target::Player)) {
if matches!(self.objs[i].kind, Kind::Room | Kind::Door | Kind::Topic)
|| self.objs[i].kind.is_person()
{
let name = self.objs[i].called();
self.problem(line, format!("The player can't carry \"{name}\"."));
continue;
}
if let Some((first, _)) = self.objs[i].location {
let name = self.objs[i].called();
self.problem(
line,
format!("Where \"{name}\" is is already said, on line {first}."),
);
continue;
}
self.objs[i].location = Some((line, Target::Player));
continue;
}
let Some(p) = self.resolve_obj(&place) else {
continue;
};
let (kind, pkind) = (self.objs[i].kind, self.objs[p].kind);
if matches!(kind, Kind::Room | Kind::Door | Kind::Topic) {
let name = self.objs[i].called();
let what = match kind {
Kind::Room => "A room is not in anything",
Kind::Door => "A door is where its sides say",
_ => "A topic is not anywhere",
};
self.problem(
line,
format!("{what}, so \"{name}\" can't be put in a place."),
);
continue;
}
if matches!(pkind, Kind::Door | Kind::Topic) || p == i {
let name = self.objs[p].called();
self.problem(line, format!("Nothing can be in \"{name}\"."));
continue;
}
if let Some((first, _)) = self.objs[i].location {
let name = self.objs[i].called();
self.problem(
line,
format!("Where \"{name}\" is is already said, on line {first}."),
);
continue;
}
self.objs[i].location = Some((line, Target::Obj(p)));
}
Statement::Adjectives { subject, words } => {
let Some(i) = self.resolve_obj(&subject) else {
continue;
};
let kind = self.objs[i].kind;
for word in words {
if !self.adjective_fits(line, kind, &word) {
continue;
}
for (prop, value) in adjective_props(kind, &word) {
self.objs[i]
.props
.push((line, prop.to_owned(), value.to_owned()));
}
}
}
Statement::AlsoCalled { .. } => {}
Statement::Exit {
dir,
from,
to,
one_way,
} => {
let (Some(from), Some(to)) = (self.resolve_room(&from), self.resolve_room(&to))
else {
continue;
};
explicit_exits.push((line, from, dir, to, one_way));
}
Statement::Unlocks { key, target } => {
let (Some(k), Some(t)) = (self.resolve_obj(&key), self.resolve_obj(&target))
else {
continue;
};
if matches!(self.objs[t].kind, Kind::Room | Kind::Topic) {
let name = self.objs[t].called();
self.problem(line, format!("\"{name}\" can't be locked."));
continue;
}
self.objs[t].keys.push((line, k));
}
Statement::Familiar(subject) => {
let Some(i) = self.resolve_obj(&subject) else {
continue;
};
self.objs[i]
.props
.push((line, "familiar".to_owned(), "true".to_owned()));
}
Statement::BlockFor(target, lines) => match self.resolve(&target) {
Ok(Target::Obj(i)) => {
let (members, after) = split_block(&lines);
self.objs[i].members.extend(members);
self.objs[i].after.extend(after);
}
Ok(Target::Story) => {
let story = story.get_or_insert_with(StoryInfo::default);
let (members, after) = split_block(&lines);
story.members.extend(members);
story.after.extend(after);
}
Ok(Target::Player) => self.problem(
target.line,
"A block of Hexicon can't be for the player in English; put it \
in a source of the language.",
),
Err(message) => self.problem(target.line, message),
},
Statement::HexName { .. } => {}
Statement::Listed { subject, text } => {
let Some(i) = self.resolve_obj(&subject) else {
continue;
};
if matches!(self.objs[i].kind, Kind::Room | Kind::Topic) {
let name = self.objs[i].called();
self.problem(
line,
format!("\"{name}\" is not listed in a room, so it has no listing."),
);
continue;
}
self.objs[i].props.push((
line,
"specialDesc".to_owned(),
format!("\"{} \"", double(&text)),
));
}
Statement::Topic {
character,
class,
about,
text,
} => self.topic(line, &character, class, &about, &text),
Statement::SideDesc { room, door, text } => {
let Some(d) = self.resolve_obj(&door) else {
continue;
};
let Some(r) = self.resolve_room(&room) else {
continue;
};
if self.objs[d].kind != Kind::Door {
let name = self.objs[d].called();
self.problem(
line,
format!("\"{name}\" is not a door, so it has no sides."),
);
continue;
}
let side = self.objs[d].sides.iter().position(
|(_, side)| matches!(self.resolve(side), Ok(Target::Obj(s)) if s == r),
);
let Some(side) = side else {
let (name, room) = (self.objs[d].called(), self.objs[r].called());
self.problem(line, format!("\"{name}\" has no side in \"{room}\"."));
continue;
};
if let Some((first, _)) = &self.objs[d].side_desc[side] {
let first = *first;
self.problem(
line,
format!("That side's description is already said, on line {first}."),
);
continue;
}
self.objs[d].side_desc[side] = Some((line, text));
}
}
}
let mut door_exits = Vec::new();
for d in 0..self.objs.len() {
if self.objs[d].kind != Kind::Door {
continue;
}
let sides = std::mem::take(&mut self.objs[d].sides);
for (n, (dir, room)) in sides.iter().enumerate() {
if let Some(room) = self.resolve_room(room) {
door_exits.push((self.objs[d].line, room, *dir, d, n));
}
}
self.objs[d].sides = sides;
}
for &(line, from, dir, d, side) in &door_exits {
let id = if side == 0 {
self.objs[d].id.clone()
} else {
format!("{}OtherSide", self.objs[d].id)
};
self.set_exit(line, from, dir, id, true);
}
for &(line, from, dir, to, _) in &explicit_exits {
let id = self.objs[to].id.clone();
self.set_exit(line, from, dir, id, true);
}
for &(line, from, dir, to, one_way) in &explicit_exits {
if !one_way {
let back = DIRECTIONS[dir].2;
let id = self.objs[from].id.clone();
self.objs[to].exits.entry(back).or_insert((id, line, false));
}
}
if player_at.is_none()
&& let Some((line, _)) = self
.objs
.iter()
.find_map(|o| o.location.filter(|(_, at)| *at == Target::Player))
{
self.problem(
line,
"Say where the player starts (\"The player is in the Hall.\") for the player \
to carry something.",
);
}
self.name_moments();
self.write_rules();
self.write_hints();
self.write_moments();
self.write_tests();
if story.is_some() && player_at.is_none() && self.problems.is_empty() {
let line = story.as_ref().map_or(1, |s| s.line);
self.problem(
line,
"Say where the player starts: \"The player is in the Hall.\"",
);
}
let mut problems = std::mem::take(&mut self.problems);
problems.sort_by_key(|(line, _)| *line);
problems.dedup();
let lines = if problems.is_empty() {
self.write(story.as_ref(), player_at, files)
} else {
vec![Vec::new(); files]
};
(lines, problems)
}
fn set_exit(&mut self, line: u32, from: usize, dir: usize, id: String, said: bool) {
if let Some((have, first, true)) = self.objs[from].exits.get(&dir)
&& *have != id
{
let (first, name) = (*first, self.objs[from].called());
self.problem(
line,
format!(
"The way {} from \"{name}\" is already said, on line {first}.",
DIRECTIONS[dir].0
),
);
return;
}
self.objs[from].exits.insert(dir, (id, line, said));
}
fn make_ids(&mut self) {
let mut used: Vec<String> = vec!["me".to_owned(), "story".to_owned()];
used.extend(
self.objs
.iter()
.filter_map(|o| o.wanted_id.as_ref().map(|(_, id)| id.clone())),
);
for obj in &mut self.objs {
if let Some((_, id)) = &obj.wanted_id {
obj.id = id.clone();
continue;
}
let mut id = identifier(&obj.words);
if RESERVED.contains(&id.as_str()) {
id.push_str("Obj");
}
let base = id.clone();
let mut n = 2;
while used.contains(&id) {
id = format!("{base}{n}");
n += 1;
}
used.push(id.clone());
obj.id = id;
}
self.used_ids = used;
}
fn write(
&self,
story: Option<&StoryInfo>,
player_at: Option<(u32, usize)>,
files: usize,
) -> Vec<Lines> {
let mut outs: Vec<Lines> = (0..files)
.map(|n| vec![(((n as u32) << FILE_SHIFT) + 1, "import hexad;".to_owned())])
.collect();
let mut parts: Vec<(usize, Part)> = Vec::new();
if let Some(story) = story {
parts.push((story.order, Part::Story));
}
if let (Some((_, order)), Some(_)) = (self.player, player_at) {
parts.push((order, Part::Player));
}
for (i, obj) in self.objs.iter().enumerate() {
parts.push((obj.order, Part::Obj(i)));
}
for (i, (order, _)) in self.free_blocks.iter().enumerate() {
parts.push((*order, Part::Block(i)));
}
for (i, achievement) in self.achievements.iter().enumerate() {
parts.push((achievement.order, Part::Achievement(i)));
}
for (i, rule) in self.written.iter().enumerate() {
if rule.when == rules::When::EveryTurn {
parts.push((rule.order, Part::EveryTurn(i)));
}
}
for (i, hint) in self.written_hints.iter().enumerate() {
parts.push((hint.order, Part::Hint(i)));
}
for (i, (order, _)) in self.written_tests.iter().enumerate() {
parts.push((*order, Part::Test(i)));
}
for (i, (order, _)) in self.written_moments.iter().enumerate() {
parts.push((*order, Part::Moment(i)));
}
parts.sort_by_key(|(order, _)| *order);
let mut every_turn_ids = self.used_ids.clone();
let mut menu = String::new();
for (_, part) in parts {
let mut out: Lines = vec![(0, String::new())];
match part {
Part::Story => {
if let Some(story) = story {
self.write_story(&mut out, story, player_at.is_some());
}
}
Part::Player => {
if let Some((line, room)) = player_at {
out.push((line, "me: Player 'you'".to_owned()));
out.push((line, format!(" location = {}", self.objs[room].id)));
out.push((line, ";".to_owned()));
}
}
Part::Obj(i) => self.write_obj(&mut out, i),
Part::Block(i) => out.extend(self.free_blocks[i].1.iter().cloned()),
Part::Achievement(i) => {
let a = &self.achievements[i];
out.push((
a.line,
format!(
"{}: Achievement +{} \"{}\";",
a.id,
a.points,
double(&a.label)
),
));
}
Part::EveryTurn(i) => {
let mut id = "everyTurn".to_owned();
let mut n = 2;
while every_turn_ids.contains(&id) {
id = format!("everyTurn{n}");
n += 1;
}
every_turn_ids.push(id.clone());
self.write_every_turn(&mut out, &self.written[i], &id);
}
Part::Test(i) => out.extend(self.written_tests[i].1.iter().cloned()),
Part::Moment(i) => out.extend(self.written_moments[i].1.iter().cloned()),
Part::Hint(i) => {
if menu.is_empty() {
menu = "hintMenu".to_owned();
let mut n = 2;
while every_turn_ids.contains(&menu) {
menu = format!("hintMenu{n}");
n += 1;
}
every_turn_ids.push(menu.clone());
let line = self.written_hints[i].line;
out.push((line, format!("{menu}: TopHintMenu 'Hints';")));
out.push((line, String::new()));
}
self.write_hint(&mut out, &self.written_hints[i], &menu);
}
}
let home = out
.iter()
.find(|(line, _)| *line != 0)
.map_or(0, |(line, _)| split_line(*line).0);
if let Some(source) = outs.get_mut(home) {
source.extend(out);
}
}
for (n, out) in outs.iter_mut().enumerate() {
let mut next = ((n as u32) << FILE_SHIFT) + 1;
for (line, _) in out.iter_mut().rev() {
if *line == 0 {
*line = next;
} else {
next = *line;
}
}
}
outs
}
fn write_story(&self, out: &mut Vec<(u32, String)>, story: &StoryInfo, has_player: bool) {
let line = story.line.max(1);
out.push((line, "story: Story".to_owned()));
for (l, key, value) in &story.props {
if *key == "IFID" {
out.push((*l, format!(" IFID = '{}'", single(value))));
}
}
if let Some(title) = &story.title {
out.push((line, format!(" name = '{}'", single(title))));
}
if let Some(byline) = &story.byline {
out.push((line, format!(" byline = '{}'", single(byline))));
}
for (l, key, value) in &story.props {
if *key != "IFID" {
out.push((*l, format!(" {key} = '{}'", single(value))));
}
}
if has_player {
out.push((line, " protagonist = me".to_owned()));
}
for (l, flag) in &story.flags {
out.push((*l, format!(" {flag} = true")));
}
if let Some((l, text)) = &story.intro {
out.push((*l, " showIntro()".to_owned()));
out.push((*l, " {".to_owned()));
out.push((*l, format!(" \"{}\\b\";", double(text))));
out.push((*l, " }".to_owned()));
}
out.extend(story.members.iter().map(|(l, s)| (*l, format!(" {s}"))));
out.push((line, ";".to_owned()));
out.extend(story.after.iter().cloned());
}
fn write_obj(&self, out: &mut Vec<(u32, String)>, i: usize) {
let obj = &self.objs[i];
if obj.kind == Kind::Door && obj.sides.len() == 2 {
let other = format!("{}OtherSide", obj.id);
self.write_one(out, i, &obj.id, 0, Some(&other));
out.push((obj.line, String::new()));
self.write_one(out, i, &other, 1, Some(&obj.id));
} else {
self.write_one(out, i, &obj.id, 0, None);
}
}
fn write_one(
&self,
out: &mut Vec<(u32, String)>,
i: usize,
id: &str,
side: usize,
other: Option<&str>,
) {
let obj = &self.objs[i];
let line = obj.line;
let class = class_of(obj);
if obj.kind == Kind::Room {
out.push((line, format!("{id}: {class} '{}'", single(&obj.name))));
if !obj.adjectives.is_empty() || !obj.nouns.is_empty() {
out.push((line, format!(" vocab = '{}'", single(&vocab(obj)))));
}
} else {
out.push((line, format!("{id}: {class} '{}'", single(&vocab(obj)))));
}
if let Some((l, text)) = obj.side_desc[side].as_ref().or(obj.desc.as_ref()) {
out.push((*l, format!(" \"{} \"", double(text))));
}
if obj.kind == Kind::Door {
if let Some((_, room)) = obj.sides.get(side)
&& let Ok(Target::Obj(r)) = self.resolve(room)
{
out.push((line, format!(" location = {}", self.objs[r].id)));
}
if let Some(other) = other {
out.push((line, format!(" otherSide = {other}")));
}
} else if let Some((l, Target::Obj(p))) = obj.location {
out.push((l, format!(" location = {}", self.objs[p].id)));
} else if let Some((l, Target::Player)) = obj.location {
out.push((l, " location = me".to_owned()));
}
let mut props: Vec<&(u32, String, String)> = Vec::new();
for prop in &obj.props {
props.retain(|p| p.1 != prop.1);
props.push(prop);
}
let class_sets_open = class == "OpenableContainer";
for (l, prop, value) in props {
if class_sets_open && prop == "isOpenable" {
continue;
}
out.push((*l, format!(" {prop} = {value}")));
}
if obj
.props
.iter()
.any(|(_, p, v)| p == "isLocked" && v == "true")
&& obj.keys.is_empty()
{
out.push((line, " lockability = lockableWithoutKey".to_owned()));
}
if !obj.keys.is_empty() {
let keys: Vec<&str> = obj
.keys
.iter()
.map(|(_, k)| self.objs[*k].id.as_str())
.collect();
out.push((
obj.keys[0].0,
format!(" keyList = [{}]", keys.join(", ")),
));
}
let mut exits: Vec<(&usize, &(String, u32, bool))> = obj.exits.iter().collect();
exits.sort_by_key(|(dir, _)| **dir);
for (dir, (to, l, _)) in exits {
out.push((*l, format!(" {} = {to}", DIRECTIONS[*dir].1)));
}
out.extend(self.rule_members(i));
if side == 0 {
out.extend(self.begins_members(i));
}
if side == 0 {
out.extend(obj.members.iter().map(|(l, s)| (*l, format!(" {s}"))));
}
out.push((line, ";".to_owned()));
if side == 0 {
for (l, class, about, text) in &obj.topics {
let head = match about {
Some(about) => format!("{class} {about}"),
None => (*class).to_owned(),
};
out.push((*l, head));
out.push((*l, format!(" \"{} \"", double(text))));
out.push((*l, format!(" location = {id}")));
out.push((*l, ";".to_owned()));
}
out.extend(obj.after.iter().cloned());
}
}
}
enum Part {
Story,
Player,
Obj(usize),
Block(usize),
Achievement(usize),
EveryTurn(usize),
Hint(usize),
Test(usize),
Moment(usize),
}
#[derive(Default)]
struct StoryInfo {
line: u32,
order: usize,
title: Option<String>,
byline: Option<String>,
props: Vec<(u32, &'static str, String)>,
intro: Option<(u32, String)>,
flags: Vec<(u32, &'static str)>,
members: Vec<(u32, String)>,
after: Vec<(u32, String)>,
}
fn split_list(tokens: &[Token]) -> Option<Vec<Phrase>> {
let mut items = Vec::new();
let mut current: Vec<Token> = Vec::new();
for token in tokens {
let ends = matches!(token.tok, Tok::Punct(',')) || is_word(Some(token), &["and"]);
if ends {
if !current.is_empty() {
items.push(phrase(¤t)?);
current.clear();
}
} else {
current.push(token.clone());
}
}
if !current.is_empty() {
items.push(phrase(¤t)?);
}
Some(items)
}
fn split_ways(tokens: &[Token]) -> Option<Vec<(usize, Phrase)>> {
let mut ways = Vec::new();
for item in split_list(tokens)? {
let words = item.lower();
let dir = direction(words.first()?)?;
if !matches!(words.get(1).map(String::as_str), Some("of" | "from")) || words.len() < 3 {
return None;
}
ways.push((
dir,
Phrase {
words: item.words[2..].to_vec(),
line: item.line,
},
));
}
Some(ways)
}
fn split_block(lines: &[(u32, String)]) -> (Lines, Lines) {
let at = lines
.iter()
.position(|(_, l)| l.starts_with('+'))
.unwrap_or(lines.len());
(lines[..at].to_vec(), lines[at..].to_vec())
}
fn adjective_props(kind: Kind, word: &str) -> Vec<(&'static str, &'static str)> {
let props = adjective(word).unwrap_or(&[]);
props
.iter()
.copied()
.filter(|(prop, _)| !(kind == Kind::Container && *prop == "isOpenable"))
.chain(
(kind == Kind::Container && props.iter().any(|(p, _)| *p == "isOpenable"))
.then_some(("isOpenable", "true")),
)
.collect()
}
fn class_of(obj: &Obj) -> &'static str {
let openable = obj
.props
.iter()
.any(|(_, p, v)| p == "isOpenable" && v == "true");
match obj.kind {
Kind::Room => "Room",
Kind::Thing => "Thing",
Kind::Container if openable => "OpenableContainer",
Kind::Container => "Container",
Kind::Surface => "Surface",
Kind::Door => "Door",
Kind::Key => "Key",
Kind::Man | Kind::Woman | Kind::Person => "Actor",
Kind::Fixture => "Fixture",
Kind::Decoration => "Decoration",
Kind::Topic => "Topic",
}
}
fn vocab(obj: &Obj) -> String {
let mut name = obj.name.clone();
if obj.some {
name = format!("some {name}");
}
let mut nouns = obj.nouns.clone();
let pronoun = match obj.kind {
Kind::Man => Some("him"),
Kind::Woman => Some("her"),
_ => None,
};
let kind_noun = match obj.kind {
Kind::Man => Some("man"),
Kind::Woman => Some("woman"),
Kind::Person => Some("person"),
_ => None,
};
if let Some(noun) = kind_noun
&& !obj.words.iter().any(|w| w == noun)
&& !nouns.iter().any(|w| w == noun)
{
nouns.push(noun.to_owned());
}
let mut sections = vec![name, obj.adjectives.join(" "), nouns.join(" ")];
if let Some(pronoun) = pronoun {
sections.push(pronoun.to_owned());
}
while sections.len() > 1 && sections.last().is_some_and(String::is_empty) {
sections.pop();
}
sections.join("; ")
}
fn identifier(words: &[String]) -> String {
let mut id = String::new();
for word in words {
let clean: String = word.chars().filter(char::is_ascii_alphanumeric).collect();
let mut chars = clean.chars();
if let Some(first) = chars.next() {
if id.is_empty() {
id.push_str(&clean.to_ascii_lowercase());
} else {
id.push(first.to_ascii_uppercase());
id.push_str(chars.as_str());
}
}
}
if id.is_empty() || id.starts_with(|c: char| c.is_ascii_digit()) {
id.insert(0, 'x');
}
id
}
const RESERVED: &[&str] = &[
"and",
"argcount",
"break",
"case",
"catch",
"class",
"continue",
"default",
"definingobj",
"delegated",
"dictionary",
"do",
"else",
"enum",
"export",
"extern",
"false",
"finally",
"for",
"foreach",
"function",
"goto",
"grammar",
"if",
"import",
"in",
"inherited",
"intrinsic",
"invokee",
"is",
"local",
"me",
"method",
"modify",
"new",
"nil",
"not",
"object",
"operator",
"or",
"property",
"propertyset",
"replace",
"replaced",
"return",
"self",
"static",
"story",
"switch",
"targetobj",
"targetprop",
"template",
"throw",
"token",
"transient",
"true",
"try",
"while",
];
fn single(text: &str) -> String {
text.replace('\\', "\\\\").replace('\'', "\\'")
}
fn double(text: &str) -> String {
text.replace('"', "\\\"")
}
fn edit_distance(a: &str, b: &str) -> usize {
let a: Vec<char> = a.chars().collect();
let b: Vec<char> = b.chars().collect();
let mut row: Vec<usize> = (0..=b.len()).collect();
for i in 1..=a.len() {
let mut prev = row[0];
row[0] = i;
for j in 1..=b.len() {
let here = row[j];
row[j] = if a[i - 1] == b[j - 1] {
prev
} else {
1 + prev.min(row[j]).min(row[j - 1])
};
prev = here;
}
}
row[b.len()]
}
#[cfg(test)]
mod tests {
use super::translate;
fn hexicon(english: &str) -> String {
let translation = translate(english);
assert!(
translation.problems.is_empty(),
"problems: {:?}",
translation.problems
);
translation.text()
}
fn problems(english: &str) -> Vec<(u32, String)> {
translate(english).problems
}
fn has(text: &str, lines: &[&str]) {
for line in lines {
assert!(text.contains(line), "no {line:?} in:\n{text}");
}
}
#[test]
fn rooms_connect_both_ways_unless_one_way() {
let text = hexicon(
"The Hall is a room. \"A bare hall.\"\n\
The Kitchen is a room.\n\
North of the Hall is the Kitchen.\n\
The Cellar is a room. Down from the Kitchen is the Cellar, one way.\n\
The Attic is a room north of the Kitchen.",
);
has(
&text,
&[
"hall: Room 'Hall'\n \"A bare hall. \"\n north = kitchen\n;",
"kitchen: Room 'Kitchen'\n north = attic\n south = hall\n down = cellar\n;",
"cellar: Room 'Cellar'\n;",
"attic: Room 'Attic'\n south = kitchen\n;",
],
);
}
#[test]
fn a_way_said_is_kept_over_a_way_back() {
let text = hexicon(
"The Hall is a room. The Kitchen is a room. The Yard is a room.\n\
North of the Hall is the Kitchen.\n\
South of the Kitchen is the Yard.",
);
has(&text, &["kitchen: Room 'Kitchen'\n south = yard\n;"]);
}
#[test]
fn a_door_is_made_with_both_its_sides() {
let text = hexicon(
"The Hall is a room. The Kitchen is a room.\n\
The oak door is a door, north of the Hall and south of the Kitchen.\n\
The iron key is a key in the Hall. It unlocks the oak door.",
);
has(
&text,
&[
"oakDoor: Door 'oak door'\n location = hall\n otherSide = oakDoorOtherSide\n keyList = [ironKey]\n;",
"oakDoorOtherSide: Door 'oak door'\n location = kitchen\n otherSide = oakDoor\n keyList = [ironKey]\n;",
"hall: Room 'Hall'\n north = oakDoor\n;",
"kitchen: Room 'Kitchen'\n south = oakDoorOtherSide\n;",
],
);
}
#[test]
fn names_make_vocabulary_and_people_their_pronouns() {
let text = hexicon(
"The Hall is a room.\n\
The old keeper is a man in the Hall. He is also called the grey-bearded keeper.\n\
Mary is a woman in the Hall.\n\
Some water is a thing in the Hall.\n\
The lamp is a switchable thing in the Hall. It is also called the brass lantern.",
);
has(
&text,
&[
"oldKeeper: Actor 'old keeper; grey-bearded; man; him'",
"mary: Actor 'Mary; ; woman; her'",
"water: Thing 'some water'",
"lamp: Thing 'lamp; brass; lantern'\n location = hall\n isSwitchable = true",
],
);
}
#[test]
fn kinds_and_what_things_are_like_make_classes_and_properties() {
let text = hexicon(
"The Hall is a dark room.\n\
The box is an openable container in the Hall.\n\
The chest is a container in the Hall. It is closed and locked.\n\
The statue is a fixture in the Hall. Everyone knows of it.",
);
has(
&text,
&[
"hall: Room 'Hall'\n isLit = nil\n;",
"box: OpenableContainer 'box'\n location = hall\n;",
"chest: OpenableContainer 'chest'\n location = hall\n isOpen = nil\n isLocked = true\n lockability = lockableWithoutKey\n;",
"statue: Fixture 'statue'\n location = hall\n familiar = true\n;",
],
);
}
#[test]
fn quoted_text_is_made_hexicon_text() {
let text = hexicon(
"The Hall is a room. \"'Hello,' she says. 'It's the keepers' hall.'\n\nA << b.\"",
);
has(
&text,
&["\"<q>Hello,</q> she says. <q>It's the keepers' hall.</q><.p>A \\<\\< b. \""],
);
}
#[test]
fn the_story_and_the_player() {
let text = hexicon(
"The story is \"Night\", by Jane Doe.\n\
The story's IFID is \"ABC\".\n\
It begins: \"Dark.\"\n\
The Hall is a room. The player is in the Hall.",
);
has(
&text,
&[
"story: Story\n IFID = 'ABC'\n name = 'Night'\n byline = 'by Jane Doe'\n protagonist = me\n showIntro()\n {\n \"Dark.\\b\";\n }\n;",
"me: Player 'you'\n location = hall\n;",
],
);
}
#[test]
fn blocks_of_hexicon_go_in_their_place() {
let text = hexicon(
"The Hall is a room.\n\
The lamp is a thing in the Hall.\n\
\n\
In Hexicon, for the lamp:\n \
weight = 2\n \
+ Component 'wick';\n\
\n\
In Hexicon:\n \
x: object;\n",
);
has(
&text,
&[
"lamp: Thing 'lamp'\n location = hall\n weight = 2\n;\n+ Component 'wick';\n\nx: object;",
],
);
}
#[test]
fn each_line_is_reported_as_its_sentence() {
let translation = translate("The Hall is a room.\n\n\"A hall.\"\n");
let source = translation.source(&["start.hxe"], 0);
assert!(
source.contains(
"#line 1 'start.hxe'\nhall: Room 'Hall'\n#line 3 'start.hxe'\n \"A hall. \"\n#line 1 'start.hxe'\n;"
),
"{source}"
);
}
#[test]
fn problems_say_what_was_expected() {
let cases: &[(&str, u32, &str)] = &[
(
"The Hall is a palace.",
1,
"\u{201c}palace\u{201d} is not a kind I know",
),
(
"The Hall is a room.\nThe lamp is a thing in the Hal.",
2,
"Did you mean \u{201c}the Hall\u{201d}?",
),
(
"The Hall is a room. The Hall is a room.",
1,
"There is already something called \u{201c}the Hall\u{201d}",
),
(
"The Hall is a shiny room.",
1,
"\u{201c}shiny\u{201d} is not something I know a room can be",
),
(
"The red box is a container. The blue box is a container. The box is openable.",
1,
"\u{201c}the box\u{201d} could be \u{201c}the red box\u{201d}, or \u{201c}the blue box\u{201d}",
),
(
"The Hall is a room. \"A.\" \"B.\"",
1,
"already has its description",
),
(
"The Hall is a room. The Yard is a room. The Den is a room.\n\
North of the Hall is the Yard.\n\
North of the Hall is the Den.",
3,
"The way north from \u{201c}the Hall\u{201d} is already said, on line 2",
),
(
"The lamp is a thing.\nNorth of the lamp is the lamp.",
2,
"is not a room",
),
(
"The Hall is a room\nIn Hexicon:\n x: object;",
1,
"no full stop",
),
("Bob waves.", 1, "I can\u{2019}t read"),
("\"Hello.\"", 1, "describes nothing"),
(
"The Hall is a room. \"Unended",
1,
"no closing quotation mark",
),
];
for (english, line, wanted) in cases {
let found = problems(english);
assert!(
found.iter().any(|(l, m)| l == line && m.contains(wanted)),
"{english:?}: wanted {wanted:?} on line {line}, found {found:?}"
);
}
}
#[test]
fn a_thing_that_could_not_be_made_is_not_reported_again() {
let found = problems("The lamp is a lantern. It is in the Hall. The lamp is openable.");
assert_eq!(found.len(), 1, "{found:?}");
}
}