use super::{
ADJECTIVES, Kind, Phrase, Reader, Target, Tok, Token, adjective, double, identifier, is_word,
list_of, phrase, shown, word_of,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum When {
Instead,
Before,
After,
EveryTurn,
}
const ACTIONS: &[(&str, &[&str])] = &[
("taking off", &["Doff"]),
("taking", &["Take"]),
("picking up", &["Take"]),
("dropping", &["Drop"]),
("examining", &["Examine"]),
("looking at", &["Examine"]),
("opening", &["Open"]),
("closing", &["Close"]),
("unlocking", &["Unlock", "UnlockWith"]),
("locking", &["Lock", "LockWith"]),
("switching on", &["SwitchOn"]),
("turning on", &["SwitchOn"]),
("switching off", &["SwitchOff"]),
("turning off", &["SwitchOff"]),
("lighting", &["Light"]),
("pushing", &["Push"]),
("pulling", &["Pull"]),
("moving", &["Move"]),
("turning", &["Turn"]),
("eating", &["Eat"]),
("drinking", &["Drink"]),
("wearing", &["Wear"]),
("entering", &["Enter"]),
("climbing", &["Climb"]),
("reading", &["Read"]),
("touching", &["Feel"]),
("feeling", &["Feel"]),
("smelling", &["SmellSomething"]),
("listening to", &["ListenTo"]),
("tasting", &["Taste"]),
("attacking", &["Attack"]),
("hitting", &["Attack"]),
("breaking", &["Break"]),
("burning", &["Burn"]),
("throwing", &["Throw"]),
("searching", &["Search"]),
("looking in", &["LookIn"]),
("looking under", &["LookUnder"]),
("looking behind", &["LookBehind"]),
("kissing", &["Kiss"]),
("talking to", &["TalkTo"]),
];
const STATES: &[(&str, &str)] = &[
("open", "{}.isOpen"),
("closed", "!{}.isOpen"),
("locked", "{}.isLocked"),
("unlocked", "!{}.isLocked"),
("lit", "{}.isLit"),
("unlit", "!{}.isLit"),
("dark", "!{}.isLit"),
("switched on", "{}.isOn"),
("switched off", "!{}.isOn"),
("visited", "{}.visited"),
("unvisited", "!{}.visited"),
("seen", "{}.seen"),
("unseen", "!{}.seen"),
("known", "{}.familiar"),
];
const CHANGES: &[(&str, &str)] = &[
("open", "{}.makeOpen(true);"),
("closed", "{}.makeOpen(nil);"),
("locked", "{}.makeLocked(true);"),
("unlocked", "{}.makeLocked(nil);"),
("lit", "{}.makeLit(true);"),
("unlit", "{}.makeLit(nil);"),
("dark", "{}.makeLit(nil);"),
("switched on", "{}.makeOn(true);"),
("switched off", "{}.makeOn(nil);"),
("known", "{}.familiar = true;"),
("familiar", "{}.familiar = true;"),
];
pub(super) const ENDINGS: &[(&str, &str)] = &[
("victory", "storyVictory"),
("defeat", "storyFailure"),
("failure", "storyFailure"),
("death", "storyDeath"),
];
#[derive(Debug, Clone)]
pub(super) enum Cond {
Is { subject: Phrase, state: String },
Has { subject: Phrase, thing: Phrase },
Here { thing: Phrase },
In { subject: Phrase, place: Phrase },
}
#[derive(Debug, Clone)]
pub(super) enum Effect {
Say(String),
Score { points: u32, label: String },
End(&'static str),
Now { subject: Phrase, state: String },
Move {
subject: Phrase,
place: Option<Phrase>,
},
Begin { name: String, line: u32 },
}
#[derive(Debug, Clone)]
pub(super) struct Rule {
pub(super) when: When,
pub(super) actions: &'static [&'static str],
pub(super) object: Option<Phrase>,
pub(super) conds: Vec<(bool, Cond)>,
pub(super) first_time: bool,
pub(super) effects: Vec<(u32, Effect)>,
pub(super) line: u32,
pub(super) order: usize,
pub(super) broken: bool,
}
const FAILED: usize = usize::MAX;
#[derive(Debug, Clone)]
pub(super) struct Written {
pub(super) when: When,
pub(super) actions: &'static [&'static str],
pub(super) object: Option<usize>,
pub(super) test: Option<String>,
pub(super) flag: Option<String>,
pub(super) body: Vec<(u32, String)>,
pub(super) line: u32,
pub(super) order: usize,
}
#[derive(Debug, Clone)]
pub(super) struct Achievement {
pub(super) id: String,
pub(super) label: String,
pub(super) points: u32,
pub(super) line: u32,
pub(super) order: usize,
}
pub(super) fn action_of(words: &[String]) -> Option<(usize, &'static [&'static str])> {
let mut best: Option<(usize, &'static [&'static str])> = None;
for (gerund, actions) in ACTIONS {
let parts: Vec<&str> = gerund.split(' ').collect();
if words.len() >= parts.len()
&& parts.iter().zip(words).all(|(p, w)| *p == w)
&& best.is_none_or(|(n, _)| parts.len() > n)
{
best = Some((parts.len(), actions));
}
}
best
}
fn action_names() -> String {
let names: Vec<&str> = ACTIONS.iter().map(|(gerund, _)| *gerund).collect();
list_of(&names, "and")
}
fn state_names() -> String {
let mut names: Vec<&str> = STATES.iter().map(|(name, _)| *name).collect();
for (name, _) in ADJECTIVES {
if !names.contains(name) {
names.push(name);
}
}
list_of(&names, "or")
}
fn points_of(tokens: &[Token]) -> Option<(u32, &[Token])> {
let first = word_of(tokens.first()?)?;
let n = match first.as_str() {
"a" | "one" => 1,
"two" => 2,
"three" => 3,
"four" => 4,
"five" => 5,
"six" => 6,
"seven" => 7,
"eight" => 8,
"nine" => 9,
"ten" => 10,
digits => digits.parse().ok()?,
};
let unit = word_of(tokens.get(1)?)?;
let ok = if n == 1 {
unit == "point"
} else {
unit == "points"
};
ok.then_some((n, &tokens[2..]))
}
fn label_of(tokens: &[Token]) -> Option<String> {
match tokens {
[
Token {
tok: Tok::Punct(':' | ','),
..
},
Token {
tok: Tok::Text(text),
..
},
]
| [
Token {
tok: Tok::Text(text),
..
},
] => Some(text.clone()),
_ => None,
}
}
pub(super) fn split_words_and(tokens: &[Token]) -> Vec<Vec<Token>> {
split_words(tokens, &["and"])
}
fn split_words(tokens: &[Token], at: &[&str]) -> Vec<Vec<Token>> {
let mut parts = vec![Vec::new()];
for token in tokens {
if is_word(Some(token), at) {
parts.push(Vec::new());
} else if let Some(last) = parts.last_mut() {
last.push(token.clone());
}
}
parts
}
const RULE_FORM: &str = "A rule is said as \"Instead of taking the lamp: \"It is too hot.\"\", \
\"After opening the box when the box is locked: ...\", or \"Every turn when the player is \
in the Hall: ...\", with a colon before what it does.";
const EFFECT_FORM: &str = "What a rule does is said after it: quoted text to show, \"It scores \
a point: \"lighting the lamp\".\", \"The story ends in victory.\", \"Now the box is open.\", \
\"Now the key is in the box.\", or \"The moment \"the plank snaps\" begins.\"";
impl Reader {
pub(super) fn rule_sentence(&mut self, line: u32, t: &[Token]) -> bool {
let first = t.first().and_then(word_of).unwrap_or_default();
let when = match first.as_str() {
"instead" => When::Instead,
"before" => When::Before,
"after" => When::After,
"every" if is_word(t.get(1), &["turn"]) => When::EveryTurn,
_ => return self.scoring_sentence(line, t),
};
let start = match when {
When::Instead => {
if !is_word(t.get(1), &["of"]) {
self.problem(line, format!("I can't read \"{}\". {RULE_FORM}", shown(t)));
self.open_rule = Some(FAILED);
return true;
}
2
}
When::EveryTurn => 2,
_ => 1,
};
let Some(colon) = t
.iter()
.position(|token| matches!(token.tok, Tok::Punct(':')))
else {
self.problem(
line,
format!(
"This rule has no colon before what it does: \"{}\". {RULE_FORM}",
shown(t)
),
);
self.open_rule = Some(FAILED);
return true;
};
let Some(rule) = self.rule_head(line, when, &t[start..colon], t) else {
self.open_rule = Some(FAILED);
return true;
};
self.rules.push(rule);
self.open_rule = Some(self.rules.len() - 1);
self.open_hint = None;
let body = &t[colon + 1..];
if !body.is_empty() {
self.rule_effect(line, body);
}
true
}
fn scoring_sentence(&mut self, line: u32, t: &[Token]) -> bool {
let words: Vec<String> = t.iter().map_while(word_of).collect();
if action_of(&words).is_none() {
return false;
}
let Some(scores) = t.iter().position(|token| is_word(Some(token), &["scores"])) else {
return false;
};
let Some(mut rule) = self.rule_head(line, When::After, &t[..scores], t) else {
self.open_rule = Some(FAILED);
return true;
};
match points_of(&t[scores + 1..])
.and_then(|(points, rest)| label_of(rest).map(|label| (points, label)))
{
Some((points, label)) => {
rule.effects.push((line, Effect::Score { points, label }));
self.rules.push(rule);
self.open_rule = Some(self.rules.len() - 1);
}
None => {
self.open_rule = Some(FAILED);
self.problem(
line,
format!(
"I can't read \"{}\". What scores is said as \"Opening the box scores a \
point: \"opening the box\".\", with what the point is for in quotation \
marks.",
shown(t)
),
)
}
}
true
}
fn rule_head(&mut self, line: u32, when: When, head: &[Token], t: &[Token]) -> Option<Rule> {
let order = self.sentences;
let Some(words) = phrase(head)
.map(|p| p.lower())
.or_else(|| (when == When::EveryTurn && head.is_empty()).then(Vec::new))
else {
self.problem(line, format!("I can't read \"{}\". {RULE_FORM}", shown(t)));
return None;
};
let mut head = head;
let mut first_time = false;
let n = words.len();
if n >= 4 && words[n - 4..] == ["for", "the", "first", "time"] {
first_time = true;
head = &head[..head.len() - 4];
}
let (what, conds) = match head
.iter()
.position(|token| is_word(Some(token), &["when"]))
{
Some(at) => (&head[..at], &head[at + 1..]),
None => (head, &[][..]),
};
let (actions, object) = if when == When::EveryTurn {
if !what.is_empty() {
self.problem(
line,
format!(
"I can't read \"{}\". Every turn's rule is said as \"Every turn: ...\" \
or \"Every turn when the player is in the Hall: ...\".",
shown(t)
),
);
return None;
}
(&[][..], None)
} else {
let lower: Vec<String> = what.iter().filter_map(word_of).collect();
let Some((len, actions)) = action_of(&lower) else {
let first = lower.first().cloned().unwrap_or_default();
self.problem(
line,
if first.ends_with("ing") {
format!(
"\"{first}\" is not an action I know. The actions are {}.",
action_names()
)
} else {
format!(
"I can't read \"{}\". A rule names an action on a thing: \
\"taking the lamp\". {RULE_FORM}",
shown(t)
)
},
);
return None;
};
let Some(object) = phrase(&what[len..]) else {
self.problem(
line,
format!(
"Say what the rule's action is done to: \"{} the lamp\".",
lower[..len].join(" ")
),
);
return None;
};
let object = self.subject(object)?;
(actions, Some(object))
};
if let Some(object) = &object {
self.last_subject = Some(object.clone());
}
let mut parsed = Vec::new();
if !conds.is_empty() {
for part in split_words(conds, &["and"]) {
parsed.push(self.condition(line, &part)?);
}
}
Some(Rule {
when,
actions,
object,
conds: parsed,
first_time,
effects: Vec::new(),
line,
order,
broken: false,
})
}
pub(super) fn condition(&mut self, line: u32, tokens: &[Token]) -> Option<(bool, Cond)> {
let words: Vec<String> = tokens.iter().filter_map(word_of).collect();
let bad = |reader: &mut Self| {
reader.problem(
line,
format!(
"I can't read the condition \"{}\". A condition is said as \"the lamp is \
lit\", \"the player has the key\", \"the keeper is here\", or \"the player \
is in the Hall\", or any of them with \"not\".",
shown(tokens)
),
);
None
};
let Some(v) = words.iter().position(|w| {
matches!(
w.as_str(),
"is" | "are" | "has" | "carries" | "holds" | "does"
)
}) else {
return bad(self);
};
let Some(subject) = phrase(&tokens[..v]) else {
return bad(self);
};
let subject = self.subject(subject)?;
let rest = &tokens[v + 1..];
let rest_words = &words[v + 1..];
match words[v].as_str() {
"has" | "carries" | "holds" => {
let thing = self.subject(phrase(rest)?)?;
Some((false, Cond::Has { subject, thing }))
}
"does" => {
if rest_words.len() >= 3
&& rest_words[0] == "not"
&& matches!(rest_words[1].as_str(), "have" | "carry" | "hold")
{
let thing = self.subject(phrase(&rest[2..])?)?;
Some((true, Cond::Has { subject, thing }))
} else {
bad(self)
}
}
_ => {
let not = rest_words.first().is_some_and(|w| w == "not");
let (rest, rest_words) = if not {
(&rest[1..], &rest_words[1..])
} else {
(rest, rest_words)
};
match rest_words {
[] => bad(self),
[here] if here == "here" => Some((not, Cond::Here { thing: subject })),
[first, ..] if matches!(first.as_str(), "in" | "on" | "inside") => {
let Some(place) = phrase(&rest[1..]) else {
return bad(self);
};
let place = self.subject(place)?;
Some((not, Cond::In { subject, place }))
}
[first, ..] if matches!(first.as_str(), "carrying" | "holding") => {
let Some(thing) = phrase(&rest[1..]) else {
return bad(self);
};
let thing = self.subject(thing)?;
Some((not, Cond::Has { subject, thing }))
}
words => {
let state = words.join(" ");
if STATES.iter().any(|(name, _)| *name == state)
|| adjective(&state).is_some()
{
Some((not, Cond::Is { subject, state }))
} else {
self.problem(
line,
format!(
"\"{state}\" is not something I know a thing can be. It \
can be {}.",
state_names()
),
);
None
}
}
}
}
}
}
pub(super) fn rule_continues(&mut self, line: u32, t: &[Token]) -> bool {
if self.open_rule.is_none() {
let words: Vec<String> = t.iter().take(3).filter_map(word_of).collect();
let is_effect = matches!(
words
.iter()
.map(String::as_str)
.collect::<Vec<_>>()
.as_slice(),
["it" | "this", "scores", ..] | ["the", "story", "ends"] | ["now", ..]
);
if is_effect {
self.problem(
line,
format!(
"\"{}\" is what a rule does, and comes after one: \"After opening the \
box: ...\".",
shown(t)
),
);
}
return is_effect;
}
match self.effect(t) {
Some(result) => {
self.add_effect(line, result);
true
}
None => {
self.open_rule = None;
false
}
}
}
fn rule_effect(&mut self, line: u32, t: &[Token]) {
let result = self.effect(t).unwrap_or_else(|| {
Err(format!(
"I can't read what this rule does: \"{}\". {EFFECT_FORM}",
shown(t)
))
});
self.add_effect(line, result);
}
fn add_effect(&mut self, line: u32, result: Result<Effect, String>) {
let Some(rule) = self.open_rule.filter(|&r| r != FAILED) else {
return;
};
match result {
Ok(effect) => self.rules[rule].effects.push((line, effect)),
Err(message) => {
self.rules[rule].broken = true;
self.problem(line, message);
}
}
}
pub(super) fn effect(&mut self, t: &[Token]) -> Option<Result<Effect, String>> {
if let [
Token {
tok: Tok::Text(text),
..
},
] = t
{
return Some(Ok(Effect::Say(text.clone())));
}
if let [
the,
moment,
Token {
tok: Tok::Text(name),
line,
},
begins,
] = t
&& is_word(Some(the), &["the"])
&& is_word(Some(moment), &["moment"])
&& is_word(Some(begins), &["begins"])
{
return Some(Ok(Effect::Begin {
name: name.clone(),
line: *line,
}));
}
let words: Vec<String> = t.iter().map_while(word_of).collect();
let w: Vec<&str> = words.iter().map(String::as_str).collect();
match w.as_slice() {
["it" | "this", "scores", ..] => Some(
points_of(&t[2..])
.and_then(|(points, rest)| label_of(rest).map(|label| (points, label)))
.map(|(points, label)| Effect::Score { points, label })
.ok_or_else(|| {
format!(
"I can't read \"{}\". A score is said as \"It scores a point: \
\"lighting the lamp\".\", with what it is for in quotation marks.",
shown(t)
)
}),
),
["the", "story", "ends", rest @ ..] => {
let ending = match rest {
[] if t.len() == 3 => Some("storyOver"),
["in", how] if t.len() == 5 => ENDINGS
.iter()
.find(|(name, _)| name == how)
.map(|(_, ending)| *ending),
_ => None,
};
Some(ending.map(Effect::End).ok_or_else(|| {
format!(
"I can't read \"{}\". The story ends in victory, in defeat, or in \
death, or simply ends: \"The story ends.\"",
shown(t)
)
}))
}
["now", ..] => Some(self.change(t)),
_ => None,
}
}
fn change(&mut self, t: &[Token]) -> Result<Effect, String> {
let bad = || {
format!(
"I can't read \"{}\". A change is said as \"Now the box is open.\", \"Now the \
key is in the box.\", or \"Now the key is nowhere.\"",
shown(t)
)
};
let Some(v) = t
.iter()
.position(|token| is_word(Some(token), &["is", "are"]))
else {
return Err(bad());
};
let subject = phrase(&t[1..v]).ok_or_else(bad)?;
let Some(subject) = self.subject(subject) else {
return Err(String::new());
};
let rest = &t[v + 1..];
let words: Vec<String> = rest.iter().filter_map(word_of).collect();
match words.first().map(String::as_str) {
Some("nowhere") if words.len() == 1 => Ok(Effect::Move {
subject,
place: None,
}),
Some("in" | "on" | "inside") => {
let place = phrase(&rest[1..]).ok_or_else(bad)?;
let Some(place) = self.subject(place) else {
return Err(String::new());
};
Ok(Effect::Move {
subject,
place: Some(place),
})
}
Some(_) => {
let state = words.join(" ");
if CHANGES.iter().any(|(name, _)| *name == state) || adjective(&state).is_some() {
Ok(Effect::Now { subject, state })
} else {
let names: Vec<&str> = CHANGES.iter().map(|(name, _)| *name).collect();
Err(format!(
"\"{state}\" is not something I know a thing can be made. It can be \
made {}.",
list_of(&names, "or")
))
}
}
None => Err(bad()),
}
}
fn rule_target(&mut self, phrase: &Phrase) -> Option<String> {
match self.resolve(phrase) {
Ok(Target::Obj(i)) => Some(self.objs[i].id.clone()),
Ok(Target::Player) => Some("now.player".to_owned()),
Ok(Target::Story) => {
self.problem(
phrase.line,
"The story is not a thing a rule can test or change.",
);
None
}
Err(message) => {
self.problem(phrase.line, message);
None
}
}
}
pub(super) fn cond_code(&mut self, not: bool, cond: &Cond) -> Option<String> {
let code = match cond {
Cond::Is { subject, state } => {
let o = self.rule_target(subject)?;
state_code(state, &o)
}
Cond::Has { subject, thing } => {
let s = self.rule_target(subject)?;
let t = self.rule_target(thing)?;
format!("{t}.isIn({s})")
}
Cond::Here { thing } => {
let t = self.rule_target(thing)?;
format!("{t}.isIn(now.player.getOutermostRoom())")
}
Cond::In { subject, place } => {
let s = self.rule_target(subject)?;
let p = self.rule_target(place)?;
format!("{s}.isIn({p})")
}
};
Some(if not {
match code.strip_prefix('!') {
Some(positive) => positive.to_owned(),
None => format!("!{code}"),
}
} else {
code
})
}
pub(super) fn effect_code(&mut self, effect: &Effect) -> Option<String> {
Some(match effect {
Effect::Say(text) => format!("\"{} \";", double(text)),
Effect::Score { points, label } => {
let id = self.achievement(*points, label)?;
format!("{id}.awardPointsOnce();")
}
Effect::End(ending) => format!("endStory({ending}, [endOptionUndo]);"),
Effect::Now { subject, state } => {
let o = self.rule_target(subject)?;
match CHANGES.iter().find(|(name, _)| name == state) {
Some((_, code)) => code.replace("{}", &o),
None => {
let props = adjective(state).unwrap_or(&[]);
props
.iter()
.map(|(prop, value)| format!("{o}.{prop} = {value};"))
.collect::<Vec<_>>()
.join(" ")
}
}
}
Effect::Begin { name, line } => {
let id = self.moment_id(*line, name)?;
format!("{id}.begin();")
}
Effect::Move { subject, place } => {
if matches!(self.resolve(subject), Ok(Target::Player)) {
self.problem(
subject.line,
"Moving the player is travel, which a rule can't do in English yet; \
use a block of Hexicon.",
);
return None;
}
let o = self.rule_target(subject)?;
let p = match place {
Some(place) => self.rule_target(place)?,
None => "nil".to_owned(),
};
format!("{o}.moveInto({p});")
}
})
}
fn achievement(&mut self, points: u32, label: &str) -> Option<String> {
if let Some(have) = self.achievements.iter().find(|a| a.label == label) {
if have.points != points {
let (line, first) = (self.scoring_line, have.line);
self.problem(
line,
format!(
"\"{label}\" scores {} on line {first}, so it can't score {points} here.",
have.points
),
);
return None;
}
return Some(have.id.clone());
}
let words: Vec<String> = label.split_whitespace().map(str::to_lowercase).collect();
let mut id = identifier(&words);
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());
self.achievements.push(Achievement {
id: id.clone(),
label: label.to_owned(),
points,
line: self.scoring_line,
order: self.scoring_order,
});
Some(id)
}
pub(super) fn write_rules(&mut self) {
let rules = std::mem::take(&mut self.rules);
let mut flags: Vec<String> = Vec::new();
for rule in rules.iter().filter(|r| !r.broken) {
let object = match &rule.object {
None => None,
Some(object) => match self.resolve(object) {
Ok(Target::Obj(i)) if self.objs[i].kind != Kind::Topic => Some(i),
Ok(Target::Obj(_)) => {
self.problem(object.line, "A topic is talked about, not acted on.");
continue;
}
Ok(_) => {
self.problem(
object.line,
"A rule is about an action on a thing or a room the story makes.",
);
continue;
}
Err(message) => {
self.problem(object.line, message);
continue;
}
},
};
if rule.effects.is_empty() {
self.problem(rule.line, format!("This rule does nothing. {EFFECT_FORM}"));
continue;
}
if rule.when == When::Instead
&& !rule
.effects
.iter()
.any(|(_, e)| matches!(e, Effect::Say(_)))
{
self.problem(
rule.line,
"A rule instead of an action says what happens instead: give it quoted \
text to show.",
);
continue;
}
let mut tests = Vec::new();
let mut ok = true;
for (not, cond) in &rule.conds {
match self.cond_code(*not, cond) {
Some(code) => tests.push(code),
None => ok = false,
}
}
let flag = rule.first_time.then(|| {
let base = match (rule.when, object) {
(When::EveryTurn, _) => "everyTurnDone".to_owned(),
(when, _) => {
let when = match when {
When::Instead => "instead",
When::Before => "before",
_ => "after",
};
format!("{when}{}Done", rule.actions[0])
}
};
let mut flag = base.clone();
let mut n = 2;
while flags.contains(&flag) {
flag = format!("{base}{n}");
n += 1;
}
flags.push(flag.clone());
flag
});
if let Some(flag) = &flag {
tests.push(format!("!{flag}"));
}
let mut body = Vec::new();
if let Some(flag) = &flag {
body.push((rule.line, format!("{flag} = true;")));
}
self.scoring_line = rule.line;
self.scoring_order = rule.order;
for (line, effect) in &rule.effects {
self.scoring_line = *line;
match self.effect_code(effect) {
Some(code) => body.push((*line, code)),
None => ok = false,
}
}
if !ok {
continue;
}
self.written.push(Written {
when: rule.when,
actions: rule.actions,
object,
test: (!tests.is_empty()).then(|| tests.join(" && ")),
flag,
body,
line: rule.line,
order: rule.order,
});
}
let always_instead: Vec<(usize, &str, u32)> = self
.written
.iter()
.filter(|r| r.when == When::Instead && r.test.is_none())
.filter_map(|r| r.object.map(|o| (o, r)))
.flat_map(|(o, r)| r.actions.iter().map(move |a| (o, *a, r.line)))
.collect();
let mut never = Vec::new();
for rule in self.written.iter().filter(|r| r.when == When::After) {
if let Some(object) = rule.object
&& let Some((_, _, first)) = always_instead
.iter()
.find(|(o, a, _)| *o == object && rule.actions.contains(a))
{
never.push((rule.line, *first));
}
}
for (line, first) in never {
self.problem(
line,
format!(
"The rule on line {first} happens instead of this action every time, so \
this rule after it never would: give that one a condition."
),
);
}
for when in [When::Instead, When::After] {
let mut seen: Vec<(usize, &str, u32)> = Vec::new();
let mut twice = Vec::new();
for rule in self
.written
.iter()
.filter(|r| r.when == when && r.test.is_none())
{
let Some(object) = rule.object else { continue };
for action in rule.actions {
if let Some((_, _, first)) =
seen.iter().find(|(o, a, _)| *o == object && a == action)
{
twice.push((rule.line, *first));
} else {
seen.push((object, action, rule.line));
}
}
}
for (line, first) in twice {
self.problem(
line,
format!(
"A rule on line {first} already does this every time, so this one \
would never apply: give one of them a condition."
),
);
}
}
}
pub(super) fn rule_members(&self, i: usize) -> Vec<(u32, String)> {
let mut out = Vec::new();
let rules: Vec<&Written> = self
.written
.iter()
.filter(|r| r.object == Some(i))
.collect();
if rules.is_empty() {
return out;
}
for rule in &rules {
if let Some(flag) = &rule.flag {
out.push((rule.line, format!(" {flag} = nil")));
}
}
let mut actions: Vec<&str> = Vec::new();
for rule in &rules {
if rule.when != When::Before {
for action in rule.actions {
if !actions.contains(action) {
actions.push(action);
}
}
}
}
for action in actions {
let of = |when: When| -> Vec<&Written> {
let mut found: Vec<&Written> = rules
.iter()
.copied()
.filter(|r| r.when == when && r.actions.contains(&action))
.collect();
found.sort_by_key(|r| r.test.is_none());
found
};
let insteads = of(When::Instead);
let afters = of(When::After);
let line = insteads
.iter()
.chain(&afters)
.map(|r| r.line)
.min()
.unwrap_or(0);
out.push((line, format!(" dobj {action}")));
out.push((line, " {".to_owned()));
if !insteads.is_empty() {
let always = insteads.iter().any(|r| r.test.is_none());
if always {
out.push((line, " verify() { }".to_owned()));
out.push((line, " check() { }".to_owned()));
} else {
let tests: Vec<String> = insteads
.iter()
.filter_map(|r| r.test.as_ref())
.map(|t| format!("({t})"))
.collect();
let unless = format!("if (!({})) inherited();", tests.join(" || "));
out.push((line, format!(" verify() {{ {unless} }}")));
out.push((line, format!(" check() {{ {unless} }}")));
}
}
out.push((line, " action()".to_owned()));
out.push((line, " {".to_owned()));
let mut chained = false;
let mut always = false;
for rule in &insteads {
match &rule.test {
Some(test) => {
let head = if chained { "else if" } else { "if" };
out.push((rule.line, format!(" {head} ({test})")));
chained = true;
}
None if chained => out.push((rule.line, " else".to_owned())),
None => {
body(&mut out, rule, 12);
always = true;
continue;
}
}
out.push((rule.line, " {".to_owned()));
body(&mut out, rule, 16);
out.push((rule.line, " }".to_owned()));
always |= rule.test.is_none();
}
if !always {
let indent = if chained {
out.push((line, " else".to_owned()));
out.push((line, " {".to_owned()));
16
} else {
12
};
let pad = " ".repeat(indent);
out.push((line, format!("{pad}inherited();")));
let alone = afters.len() == 1 && afters[0].test.is_none();
for (n, rule) in afters.iter().enumerate() {
if alone {
body(&mut out, rule, indent);
continue;
}
let head = match (&rule.test, n) {
(Some(test), 0) => format!("{pad}if ({test})"),
(Some(test), _) => format!("{pad}else if ({test})"),
(None, _) => format!("{pad}else"),
};
out.push((rule.line, head));
out.push((rule.line, format!("{pad}{{")));
body(&mut out, rule, indent + 4);
out.push((rule.line, format!("{pad}}}")));
}
if chained {
out.push((line, " }".to_owned()));
}
}
out.push((line, " }".to_owned()));
out.push((line, " }".to_owned()));
}
let befores: Vec<&&Written> = rules.iter().filter(|r| r.when == When::Before).collect();
if let Some(first) = befores.first().copied() {
out.push((first.line, " beforeAction()".to_owned()));
out.push((first.line, " {".to_owned()));
out.push((first.line, " inherited();".to_owned()));
for rule in &befores {
let actions: Vec<String> = rule
.actions
.iter()
.map(|a| format!("now.action.ofKind({a})"))
.collect();
let mut test = if actions.len() == 1 {
actions[0].clone()
} else {
format!("({})", actions.join(" || "))
};
test.push_str(" && now.dobj == self");
if let Some(t) = &rule.test {
test.push_str(&format!(" && {t}"));
}
out.push((rule.line, format!(" if ({test})")));
out.push((rule.line, " {".to_owned()));
body(&mut out, rule, 12);
out.push((rule.line, " }".to_owned()));
}
out.push((first.line, " }".to_owned()));
}
out
}
pub(super) fn write_every_turn(&self, out: &mut Vec<(u32, String)>, rule: &Written, id: &str) {
let line = rule.line;
out.push((line, format!("{id}: InitObject")));
if let Some(flag) = &rule.flag {
out.push((line, format!(" {flag} = nil")));
}
out.push((
line,
" execute() { new Daemon(self, &run, 0); }".to_owned(),
));
out.push((line, " run()".to_owned()));
out.push((line, " {".to_owned()));
match &rule.test {
Some(test) => {
out.push((line, format!(" if ({test})")));
out.push((line, " {".to_owned()));
body(out, rule, 12);
out.push((line, " }".to_owned()));
}
None => body(out, rule, 8),
}
out.push((line, " }".to_owned()));
out.push((line, ";".to_owned()));
}
}
fn body(out: &mut Vec<(u32, String)>, rule: &Written, indent: usize) {
for (line, code) in &rule.body {
out.push((*line, format!("{}{code}", " ".repeat(indent))));
}
}
fn state_code(state: &str, o: &str) -> String {
if let Some((_, code)) = STATES.iter().find(|(name, _)| *name == state) {
return code.replace("{}", o);
}
let props = adjective(state).unwrap_or(&[]);
let tests: Vec<String> = props
.iter()
.map(|(prop, value)| {
if *value == "nil" {
format!("!{o}.{prop}")
} else {
format!("{o}.{prop}")
}
})
.collect();
tests.join(" && ")
}
#[cfg(test)]
mod tests {
use super::super::translate;
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 lamp is a switchable thing in the Hall.\n\
The box is an openable container in the Hall.\n\
The coin is a thing in the box.\n";
fn hexicon(rules: &str) -> String {
let translation = translate(&format!("{WORLD}{rules}"));
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(rules: &str, wanted: &str) {
let found = translate(&format!("{WORLD}{rules}")).problems;
assert!(
found.iter().any(|(_, m)| m.contains(wanted)),
"{rules:?}: wanted {wanted:?}, found {found:?}"
);
}
#[test]
fn after_does_the_action_then_the_rule() {
let text = hexicon(
"After switching on the lamp: \"It flares.\" It scores a point: \"lighting \
the lamp\". The story ends in victory.",
);
has(
&text,
" dobj SwitchOn\n {\n action()\n {\n inherited();\n \
\"It flares. \";\n lightingTheLamp.awardPointsOnce();\n \
endStory(storyVictory, [endOptionUndo]);\n }\n }\n",
);
has(
&text,
"lightingTheLamp: Achievement +1 \"lighting the lamp\";",
);
}
#[test]
fn instead_lets_the_action_through_and_does_the_rule_in_its_place() {
let text = hexicon("Instead of taking the lamp: \"Too hot.\"");
has(
&text,
" dobj Take\n {\n verify() { }\n check() { }\n action()\n \
{\n \"Too hot. \";\n }\n }\n",
);
}
#[test]
fn rules_with_conditions_come_before_the_one_without() {
let text = hexicon(
"Instead of taking the lamp: \"No.\"\n\
Instead of taking the lamp when the lamp is switched on: \"Hot.\"\n\
After opening the box when the player has the lamp: \"Lit.\"\n\
After opening the box when the lamp is not here: \"Dark.\"",
);
has(
&text,
" action()\n {\n if (lamp.isOn)\n {\n \
\"Hot. \";\n }\n else\n {\n \"No. \";\n \
}\n }\n",
);
has(
&text,
" if (lamp.isIn(now.player))\n {\n \"Lit. \";\n \
}\n else if (!lamp.isIn(now.player.getOutermostRoom()))\n",
);
}
#[test]
fn an_instead_with_a_condition_keeps_the_class_s_verify_otherwise() {
let text = hexicon("Instead of taking the lamp when the player is in the Yard: \"No.\"");
has(
&text,
"verify() { if (!((now.player.isIn(yard)))) inherited(); }",
);
has(
&text,
"check() { if (!((now.player.isIn(yard)))) inherited(); }",
);
has(
&text,
" if (now.player.isIn(yard))\n {\n \"No. \";\n \
}\n else\n {\n inherited();\n }\n",
);
}
#[test]
fn an_action_with_rules_instead_and_after() {
let text = hexicon(
"Instead of taking the lamp when the lamp is switched on: \"Hot.\"\n\
After taking the lamp: \"Got it.\"",
);
has(
&text,
" else\n {\n inherited();\n \
\"Got it. \";\n }\n",
);
}
#[test]
fn before_is_a_notification_and_first_time_a_flag() {
let text = hexicon(
"Before taking the coin: \"You reach in.\"\n\
After taking the coin for the first time: \"Yours.\"",
);
has(
&text,
" beforeAction()\n {\n inherited();\n if (now.action.ofKind(Take) && \
now.dobj == self)\n {\n \"You reach in. \";\n }\n }\n",
);
has(&text, " afterTakeDone = nil\n");
has(
&text,
" if (!afterTakeDone)\n {\n afterTakeDone = true;\n",
);
}
#[test]
fn now_changes_things() {
let text = hexicon(
"After pushing the lamp: now the box is open. Now the coin is nowhere. Now the \
lamp is in the box. Now the lamp is wearable.",
);
has(&text, "box.makeOpen(true);");
has(&text, "coin.moveInto(nil);");
has(&text, "lamp.moveInto(box);");
has(&text, "lamp.isWearable = true;");
}
#[test]
fn an_action_that_scores_and_every_turn() {
let text = hexicon(
"Opening the box scores 2 points: \"opening the box\".\n\
Every turn when the player is in the Yard: \"Wind.\"",
);
has(&text, "openingTheBox: Achievement +2 \"opening the box\";");
has(
&text,
"everyTurn: InitObject\n execute() { new Daemon(self, &run, 0); }\n run()\n {\n \
if (now.player.isIn(yard))\n {\n \"Wind. \";\n }\n }\n;",
);
}
#[test]
fn unlocking_is_both_actions() {
let text = hexicon(
"The key is a key in the Hall. It unlocks the box.\nUnlocking the box scores a point: \"in\".",
);
has(&text, " dobj Unlock\n");
has(&text, " dobj UnlockWith\n");
}
#[test]
fn a_name_in_hexicon_and_a_door_s_side() {
let translation = translate(
"The Hall is a room. The Yard is a room.\n\
The gate is a door, north of the Hall and south of the Yard. \"A gate.\"\n\
It is called hallGate in Hexicon.\n\
Seen from the Yard, the gate is \"The gate home.\"",
);
assert!(
translation.problems.is_empty(),
"{:?}",
translation.problems
);
let text = translation.text();
has(&text, "hallGate: Door 'gate'\n \"A gate. \"\n");
has(
&text,
"hallGateOtherSide: Door 'gate'\n \"The gate home. \"\n",
);
}
#[test]
fn problems_with_rules() {
problem(
"Instead of frobbing the lamp: \"No.\"",
"\u{201c}frobbing\u{201d} is not an action I know",
);
problem(
"After taking the lamp when the lamp is shiny: \"Hm.\"",
"\u{201c}shiny\u{201d} is not something I know",
);
problem(
"It scores a point: \"x\".",
"is what a rule does, and comes after one",
);
problem("Instead of taking the lamp \"No.\"", "no colon");
problem(
"After taking the lamp: \"One.\"\nAfter taking the lamp: \"Two.\"",
"already does this every time",
);
problem(
"After taking the lamp: now the lamp is purple.",
"\u{201c}purple\u{201d} is not something I know a thing can be made",
);
problem(
"After taking the lamp: the story ends in triumph.",
"The story ends in victory",
);
problem(
"Taking the lamp scores a point: \"a\".\nOpening the box scores 2 points: \"a\".",
"scores 1 on line",
);
problem("After taking the lamp:", "This rule does nothing");
problem(
"Instead of taking the lamp: now the box is open.",
"give it quoted text",
);
problem(
"Instead of taking the lamp: \"No.\"\nAfter taking the lamp: \"Yes.\"",
"this rule after it never would",
);
problem(
"Every turn: now the player is in the Yard.",
"Moving the player is travel",
);
}
#[test]
fn what_follows_a_rule_that_could_not_be_read_is_not_reported_again() {
let found = translate(&format!(
"{WORLD}After taking the lamp when the lamp is shiny: \"Hm.\"\nIt scores a point: \"x\"."
))
.problems;
assert_eq!(found.len(), 1, "{found:?}");
let found = translate(&format!(
"{WORLD}Before taking the lamp: now the lamp is purple."
))
.problems;
assert_eq!(found.len(), 1, "{found:?}");
}
}