use super::rules::{Cond, ENDINGS};
use super::{
Kind, Phrase, Reader, Tok, Token, identifier, is_word, list_of, phrase, shown, word_of,
};
#[derive(Debug, Clone)]
pub(super) enum Check {
Says { not: bool, text: String },
Scored { not: bool, label: String, line: u32 },
Ended {
not: bool,
ending: Option<&'static str>,
},
Moment { name: Option<String>, line: u32 },
Cond(bool, Cond),
}
#[derive(Debug, Clone)]
pub(super) struct StepRead {
pub(super) command: Option<String>,
pub(super) within: u32,
pub(super) why: Option<String>,
pub(super) checks: Vec<Check>,
pub(super) line: u32,
}
#[derive(Debug, Clone)]
pub(super) struct Test {
pub(super) name: String,
pub(super) purpose: Option<String>,
pub(super) after: Option<(u32, String)>,
pub(super) start_at: Option<Phrase>,
pub(super) holding: Vec<Phrase>,
pub(super) steps: Vec<StepRead>,
pub(super) line: u32,
pub(super) order: usize,
}
#[derive(Debug, Clone)]
pub(super) struct WalkthroughRead {
pub(super) name: String,
pub(super) tests: Vec<String>,
pub(super) line: u32,
pub(super) order: usize,
}
const TEST_FORM: &str = "A test is said as \"The test \"getting in\" is \"The key is in the \
box.\"\", and its steps after it: \"Type \"open box\" to find the key: it says \"brass \
key\".\", or \"Wait up to 2 turns for the farmer: the story has ended in victory.\"";
const CHECK_FORM: &str = "A step checks what is true after it, as a rule's condition is said \
(\"the player has the key\"), or \"it says \"brass key\"\", \"it does not say \"locked\"\", \
\"\"unlocking the door\" is scored\", \"the story has ended in victory\", or \"the moment \"the \
plank snaps\" is current\", joined by \"and\".";
impl Reader {
pub(super) fn test_sentence(&mut self, line: u32, t: &[Token]) -> bool {
let words: Vec<String> = t.iter().take(3).filter_map(word_of).collect();
let w: Vec<&str> = words.iter().map(String::as_str).collect();
let starts_step = matches!(
w.as_slice(),
["type", ..] | ["wait", ..] | ["it", "starts", ..]
);
if starts_step {
match self.open_test {
Some(test) => {
if test != usize::MAX {
self.test_step(line, test, t);
}
}
None => self.problem(
line,
format!(
"\"{}\" is part of a test, and comes after one: \"The test \"getting \
in\" is \"...\".\"",
shown(t)
),
),
}
return true;
}
self.open_test = None;
let named = |n: usize| matches!(t.get(n).map(|t| &t.tok), Some(Tok::Text(_)));
if is_word(t.first(), &["the"]) && is_word(t.get(1), &["test"]) && named(2) {
self.test(line, t);
return true;
}
if is_word(t.first(), &["the"]) && is_word(t.get(1), &["walkthrough"]) && named(2) {
self.walkthrough(line, t);
return true;
}
false
}
fn test(&mut self, line: u32, t: &[Token]) {
let Tok::Text(name) = &t[2].tok else { return };
let purpose = match &t[3..] {
[] => None,
[
is,
Token {
tok: Tok::Text(purpose),
..
},
] if is_word(Some(is), &["is"]) => Some(purpose.clone()),
_ => {
self.problem(line, format!("I can't read \"{}\". {TEST_FORM}", shown(t)));
self.open_test = Some(usize::MAX);
return;
}
};
if let Some(other) = self.tests.iter().find(|test| test.name == *name) {
let first = other.line;
self.problem(
line,
format!("There is already a test called \"{name}\", on line {first}."),
);
self.open_test = Some(usize::MAX);
return;
}
self.tests.push(Test {
name: name.clone(),
purpose,
after: None,
start_at: None,
holding: Vec::new(),
steps: Vec::new(),
line,
order: self.sentences,
});
self.open_test = Some(self.tests.len() - 1);
}
fn walkthrough(&mut self, line: u32, t: &[Token]) {
let Tok::Text(name) = &t[2].tok else { return };
let mut tests = Vec::new();
let mut ok = is_word(t.get(3), &["plays"]);
for token in t.iter().skip(4) {
match &token.tok {
Tok::Text(test) => tests.push(test.clone()),
Tok::Punct(',') => {}
Tok::Word(w) if matches!(w.to_lowercase().as_str(), "then" | "and") => {}
_ => ok = false,
}
}
if !ok || tests.is_empty() {
self.problem(
line,
format!(
"I can't read \"{}\". A walkthrough is said as \"The walkthrough \"the way \
through\" plays \"getting in\", then \"winning\".\"",
shown(t)
),
);
return;
}
self.walkthroughs.push(WalkthroughRead {
name: name.clone(),
tests,
line,
order: self.sentences,
});
}
fn test_step(&mut self, line: u32, test: usize, t: &[Token]) {
let first = word_of(&t[0]).unwrap_or_default();
if first == "it" {
self.test_start(line, test, t);
return;
}
let (command, within, rest) = if first == "type" {
match t.get(1).map(|t| &t.tok) {
Some(Tok::Text(command)) => (Some(command.clone()), 1, &t[2..]),
_ => {
self.problem(
line,
format!("I can't read \"{}\". A command is typed in quotation marks: \"Type \"open box\".\"", shown(t)),
);
return;
}
}
} else {
let rest = &t[1..];
let n = rest.len();
if n >= 4
&& is_word(rest.first(), &["up"])
&& is_word(rest.get(1), &["to"])
&& is_word(rest.get(3), &["turns", "turn"])
{
let count = word_of(&rest[2]).and_then(|w| number(&w));
let Some(count) = count else {
self.problem(line, format!("I can't read \"{}\". A wait is said as \"Wait up to 2 turns for the farmer: ...\".", shown(t)));
return;
};
(None, count, &rest[4..])
} else {
(None, 1, rest)
}
};
let colon = rest
.iter()
.position(|token| matches!(token.tok, Tok::Punct(':')));
let (why_tokens, check_tokens) = match colon {
Some(c) => (&rest[..c], &rest[c + 1..]),
None => (rest, &[][..]),
};
let why = if why_tokens.is_empty() {
None
} else {
match reason(why_tokens) {
Some(why) => Some(why),
None => {
self.problem(
line,
format!(
"I can't read why this step is there: \"{}\". Say it in words, \
before a colon: \"Type \"open box\" to find the key: ...\".",
shown(why_tokens)
),
);
return;
}
}
};
if command.is_none() && check_tokens.is_empty() {
self.problem(
line,
"A wait says what it waits for, after a colon: \"Wait up to 2 turns for the \
farmer: the story has ended in victory.\"",
);
return;
}
let mut checks = Vec::new();
if !check_tokens.is_empty() {
for part in split_and(check_tokens) {
match self.check(line, &part) {
Some(check) => checks.push(check),
None => return,
}
}
}
self.tests[test].steps.push(StepRead {
command,
within,
why,
checks,
line,
});
}
fn test_start(&mut self, line: u32, test: usize, t: &[Token]) {
let rest = &t[2..];
let bad = |reader: &mut Self| {
reader.problem(
line,
format!(
"I can't read \"{}\". Where a test starts is said as \"It starts after \
\"getting in\".\", \"It starts in the Office.\", or \"It starts with the \
player holding the key.\"",
shown(t)
),
);
};
match rest {
[
after,
Token {
tok: Tok::Text(name),
..
},
] if is_word(Some(after), &["after"]) => {
self.tests[test].after = Some((line, name.clone()));
}
[first, place @ ..] if is_word(Some(first), &["in", "on"]) => match phrase(place) {
Some(place) => self.tests[test].start_at = Some(place),
None => bad(self),
},
[with, the, player, holding, things @ ..]
if is_word(Some(with), &["with"])
&& is_word(Some(the), &["the"])
&& is_word(Some(player), &["player"])
&& is_word(Some(holding), &["holding"]) =>
{
match super::split_list(things) {
Some(things) if !things.is_empty() => {
self.tests[test].holding.extend(things);
}
_ => bad(self),
}
}
_ => bad(self),
}
}
fn check(&mut self, line: u32, tokens: &[Token]) -> Option<Check> {
let words: Vec<String> = tokens.iter().filter_map(word_of).collect();
let w: Vec<&str> = words.iter().map(String::as_str).collect();
let text = |n: usize| match tokens.get(n).map(|t| &t.tok) {
Some(Tok::Text(text)) => Some(text.clone()),
_ => None,
};
let bad = |reader: &mut Self| {
reader.problem(
line,
format!("I can't read the check \"{}\". {CHECK_FORM}", shown(tokens)),
);
None
};
if is_word(tokens.first(), &["it"]) {
return match (w.as_slice(), tokens.len()) {
(["it", "says"], 3) => text(2).map(|text| Check::Says { not: false, text }),
(["it", "does", "not", "say"], 5) => {
text(4).map(|text| Check::Says { not: true, text })
}
_ => None,
}
.or_else(|| bad(self));
}
if let Some(label) = text(0) {
return match w.as_slice() {
["is", "scored"] if tokens.len() == 3 => Some(Check::Scored {
not: false,
label,
line,
}),
["is", "not", "scored"] if tokens.len() == 4 => Some(Check::Scored {
not: true,
label,
line,
}),
_ => bad(self),
};
}
if let ["the", "moment", "is", "current"] = w.as_slice()
&& let Some(name) = text(2)
&& tokens.len() == 5
{
return Some(Check::Moment {
name: Some(name),
line,
});
}
if let ["no", "moment", "is", "current"] = w.as_slice() {
return Some(Check::Moment { name: None, line });
}
if let ["the", "story", "has", rest @ ..] = w.as_slice() {
let (not, rest) = match rest {
["not", rest @ ..] => (true, rest),
rest => (false, rest),
};
return match rest {
["ended"] => Some(Check::Ended { not, ending: None }),
["ended", "in", how] => match ENDINGS.iter().find(|(name, _)| name == how) {
Some((_, ending)) => Some(Check::Ended {
not,
ending: Some(ending),
}),
None => bad(self),
},
_ => bad(self),
};
}
if tokens.iter().any(|t| !matches!(t.tok, Tok::Word(_))) {
return bad(self);
}
self.condition(line, tokens)
.map(|(not, cond)| Check::Cond(not, cond))
}
pub(super) fn write_tests(&mut self) {
let tests = std::mem::take(&mut self.tests);
let mut ids = Vec::new();
for test in &tests {
let words: Vec<String> = test
.name
.split_whitespace()
.map(str::to_lowercase)
.collect();
let id = self.fresh_id(&words);
ids.push(id);
}
let id_of = |name: &str| {
tests
.iter()
.position(|t| t.name == name)
.map(|i| ids[i].clone())
};
for (n, test) in tests.iter().enumerate() {
let mut out: Vec<(u32, String)> = Vec::new();
let line = test.line;
let mut head = format!("{}: Scenario '{}'", ids[n], single_text(&test.name));
if let Some(purpose) = &test.purpose {
head.push_str(&format!(" '{}'", single_text(purpose)));
}
out.push((line, head));
if let Some((l, after)) = &test.after {
match id_of(after) {
Some(id) if id != ids[n] => out.push((*l, format!(" after = {id}"))),
Some(_) => self.problem(*l, "A test can't start after itself."),
None => {
let names: Vec<String> =
tests.iter().map(|t| format!("\"{}\"", t.name)).collect();
let names: Vec<&str> = names.iter().map(String::as_str).collect();
self.problem(
*l,
format!(
"There is no test called \"{after}\". The tests are {}.",
list_of(&names, "and")
),
);
}
}
}
if let Some(place) = &test.start_at
&& let Some(room) = self.resolve_room(place)
{
out.push((place.line, format!(" startAt = {}", self.objs[room].id)));
}
if !test.holding.is_empty() {
let mut held = Vec::new();
for thing in &test.holding {
if let Some(i) = self.resolve_obj(thing) {
if matches!(self.objs[i].kind, Kind::Room | Kind::Door | Kind::Topic) {
let name = self.objs[i].called();
self.problem(thing.line, format!("The player can't hold \"{name}\"."));
} else {
held.push(self.objs[i].id.clone());
}
}
}
out.push((line, format!(" holding = [{}]", held.join(", "))));
}
out.push((line, ";".to_owned()));
for step in &test.steps {
self.write_step(&mut out, step, &ids[n]);
}
self.written_tests.push((test.order, out));
}
let walkthroughs = std::mem::take(&mut self.walkthroughs);
for walk in walkthroughs {
let mut parts = Vec::new();
for name in &walk.tests {
match id_of(name) {
Some(id) => parts.push(id),
None => self.problem(walk.line, format!("There is no test called \"{name}\".")),
}
}
let words: Vec<String> = walk
.name
.split_whitespace()
.map(str::to_lowercase)
.collect();
let id = self.fresh_id(&words);
let out = vec![(
walk.line,
format!(
"{id}: Walkthrough '{}' [{}];",
single_text(&walk.name),
parts.join(", ")
),
)];
self.written_tests.push((walk.order, out));
}
}
fn write_step(&mut self, out: &mut Vec<(u32, String)>, step: &StepRead, test: &str) {
let line = step.line;
let why = step
.why
.as_ref()
.map(|why| format!(" '{}'", single_text(why)))
.unwrap_or_default();
match &step.command {
Some(command) => out.push((line, format!("Step '{}'{why}", single_text(command)))),
None => out.push((line, format!("Await{why}"))),
}
out.push((line, format!(" location = {test}")));
let mut tests = Vec::new();
let mut mentions = Vec::new();
let mut avoids = Vec::new();
for check in &step.checks {
match check {
Check::Says { not, text } => {
let quoted = format!("'{}'", single_text(text));
if *not {
avoids.push(quoted);
} else {
mentions.push(quoted);
}
}
Check::Scored { not, label, line } => {
match self.achievements.iter().find(|a| a.label == *label) {
Some(a) => {
tests.push(format!("{}{}.achieved", if *not { "!" } else { "" }, a.id))
}
None => self.problem(*line, format!("No rule scores \"{label}\".")),
}
}
Check::Ended { not, ending } => tests.push(match (ending, not) {
(Some(e), false) => format!("scenarioMemory.ending == {e}"),
(Some(e), true) => format!("scenarioMemory.ending != {e}"),
(None, false) => "scenarioMemory.ending != nil".to_owned(),
(None, true) => "scenarioMemory.ending == nil".to_owned(),
}),
Check::Moment { name, line } => match name {
Some(name) => {
if let Some(id) = self.moment_id(*line, name) {
tests.push(format!("choiceManager.current == {id}"));
}
}
None => tests.push("choiceManager.current == nil".to_owned()),
},
Check::Cond(not, cond) => {
if let Some(code) = self.cond_code(*not, cond) {
tests.push(code);
}
}
}
}
let list = |items: &[String]| match items {
[one] => one.clone(),
many => format!("[{}]", many.join(", ")),
};
if step.command.is_some() {
if !tests.is_empty() {
out.push((line, format!(" expect = ({})", tests.join(" && "))));
}
if !mentions.is_empty() {
out.push((line, format!(" mentions = {}", list(&mentions))));
}
if !avoids.is_empty() {
out.push((line, format!(" avoids = {}", list(&avoids))));
}
} else {
if !mentions.is_empty() || !avoids.is_empty() {
self.problem(
line,
"A wait waits for something to be true, not for what is said: check \
what is said with the step after it.",
);
}
if !tests.is_empty() {
out.push((line, format!(" until = ({})", tests.join(" && "))));
}
out.push((line, format!(" within = {}", step.within)));
}
out.push((line, ";".to_owned()));
}
pub(super) fn fresh_id(&mut self, words: &[String]) -> String {
let mut id = identifier(words);
if super::RESERVED.contains(&id.as_str()) {
id.push_str("Obj");
}
let base = id.clone();
let mut n = 2;
while self.used_ids.contains(&id) {
id = format!("{base}{n}");
n += 1;
}
self.used_ids.push(id.clone());
id
}
}
fn reason(tokens: &[Token]) -> Option<String> {
let tokens = match tokens {
[
Token {
tok: Tok::Punct(','),
..
},
rest @ ..,
] => rest,
tokens => tokens,
};
let mut out = String::new();
for token in tokens {
match &token.tok {
Tok::Word(word) => {
if !out.is_empty() {
out.push(' ');
}
out.push_str(word);
}
Tok::Punct(c @ (',' | ';')) => out.push(*c),
_ => return None,
}
}
let mut chars = out.chars();
let first = chars.next()?;
let mut why: String = first.to_uppercase().chain(chars).collect();
if !why.ends_with(['.', '?', '!']) {
why.push('.');
}
Some(why)
}
fn number(word: &str) -> Option<u32> {
let n = match word {
"one" => 1,
"two" => 2,
"three" => 3,
"four" => 4,
"five" => 5,
"six" => 6,
"seven" => 7,
"eight" => 8,
"nine" => 9,
"ten" => 10,
digits => digits.parse().ok()?,
};
(n > 0).then_some(n)
}
fn single_text(text: &str) -> String {
text.replace('\'', "\\'")
}
fn split_and(tokens: &[Token]) -> Vec<Vec<Token>> {
let mut parts = vec![Vec::new()];
for token in tokens {
if is_word(Some(token), &["and"]) {
parts.push(Vec::new());
} else if let Some(last) = parts.last_mut() {
last.push(token.clone());
}
}
parts
}
#[cfg(test)]
mod tests {
use super::super::{translate, translate_all};
const WORLD: &str = "The Hall is a room. The Yard is a room north of the Hall.\n\
The player is in the Hall.\n\
The key is a thing in the Hall. The box is an openable container in the Hall.\n\
Opening the box scores a point: \"opening the box\".\n";
fn hexicon(more: &str) -> String {
let translation = translate(&format!("{WORLD}{more}"));
assert!(
translation.problems.is_empty(),
"problems: {:?}",
translation.problems
);
translation.text()
}
fn has(text: &str, wanted: &str) {
assert!(text.contains(wanted), "no {wanted:?} in:\n{text}");
}
fn problem(more: &str, wanted: &str) {
let found = translate(&format!("{WORLD}{more}")).problems;
assert!(
found.iter().any(|(_, m)| m.contains(wanted)),
"{more:?}: wanted {wanted:?}, found {found:?}"
);
}
#[test]
fn a_test_is_a_scenario_with_its_steps() {
let text = hexicon(
"The test \"getting the key\" is \"The key is in the Hall.\"\n\
Type \"take key\" to have it: the player has the key and it says \"taken\".\n\
Type \"open box\": \"opening the box\" is scored and it does not say \"locked\".\n\
Type \"north\" to leave: the player is in the Yard and the story has not ended.",
);
has(
&text,
"gettingTheKey: Scenario 'getting the key' 'The key is in the Hall.'\n;\n\
Step 'take key' 'To have it.'\n location = gettingTheKey\n \
expect = (key.isIn(now.player))\n mentions = 'taken'\n;\n\
Step 'open box'\n location = gettingTheKey\n expect = (openingTheBox.achieved)\n \
avoids = 'locked'\n;\n\
Step 'north' 'To leave.'\n location = gettingTheKey\n \
expect = (now.player.isIn(yard) && scenarioMemory.ending == nil)\n;",
);
}
#[test]
fn where_a_test_starts_and_waits_and_walkthroughs() {
let text = hexicon(
"The test \"first\" is \"One.\"\nType \"look\".\n\
The test \"second\".\n\
It starts after \"first\".\n\
It starts in the Yard.\n\
It starts with the player holding the key and the box.\n\
Wait up to 3 turns for the end: the story has ended in victory.\n\
The walkthrough \"all\" plays \"first\", then \"second\".",
);
has(
&text,
"second: Scenario 'second'\n after = first\n startAt = yard\n \
holding = [key, box]\n;\n\
Await 'For the end.'\n location = second\n \
until = (scenarioMemory.ending == storyVictory)\n within = 3\n;",
);
has(&text, "all: Walkthrough 'all' [first, second];");
}
#[test]
fn sources_read_together_name_what_each_other_make() {
let translations = translate_all(&[
(
"start.hxe",
"The Hall is a room. The player is in the Hall. The key is a thing in the Hall.",
),
(
"tests.hxe",
"The test \"keys\".\nType \"take key\": the player has the key.",
),
]);
assert!(translations.iter().all(|t| t.problems.is_empty()));
assert!(
translations[1]
.text()
.contains("expect = (key.isIn(now.player))")
);
let source = translations[1].source(&["start.hxe", "tests.hxe"], 1);
assert!(
source.contains("#line 2 'tests.hxe'\n expect = (key.isIn(now.player))"),
"{source}"
);
let translations = translate_all(&[
("start.hxe", "The Hall is a room."),
("more.hxe", "The Hall is a room."),
]);
assert!(translations[0].problems.is_empty());
assert_eq!(
translations[1].problems,
[(
1,
"There is already something called \u{201c}the Hall\u{201d}, made on line 1 of \
start.hxe."
.to_owned()
)]
);
}
#[test]
fn how_a_thing_is_listed_in_a_room() {
let text = hexicon("The key is listed as \"A key glints on the floor.\"");
has(&text, " specialDesc = \"A key glints on the floor. \"\n");
}
#[test]
fn problems_with_tests() {
problem("Type \"look\".", "is part of a test, and comes after one");
problem(
"The test \"a\".\nType look.",
"A command is typed in quotation marks",
);
problem(
"The test \"a\".\nType \"look\": the key is shiny.",
"\u{201c}shiny\u{201d} is not something I know",
);
problem(
"The test \"a\".\nType \"look\": it whispers \"x\".",
"I can\u{2019}t read the check",
);
problem(
"The test \"a\".\nType \"look\": \"winning\" is scored.",
"No rule scores \u{201c}winning\u{201d}",
);
problem(
"The test \"a\".\nIt starts after \"b\".",
"There is no test called \u{201c}b\u{201d}",
);
problem(
"The test \"a\".\nWait up to 2 turns.",
"A wait says what it waits for",
);
problem(
"The test \"a\".\nThe test \"a\".",
"There is already a test called",
);
problem(
"The walkthrough \"w\" plays \"x\".",
"There is no test called \u{201c}x\u{201d}",
);
problem(
"The test \"a\".\nIt starts with the player holding the Yard.",
"The player can\u{2019}t hold",
);
}
}