use std::time::Duration;
use viperjs::api::{Engine, Error};
const EXPECTED: &str = "4210";
const FIXTURE: &str = "var orders = [
{ sku: 'A-1', price: 1299 },
{ sku: 'B-7', price: 2450 },
{ sku: 'C-3', price: 461 }
];";
const MAX_ROUNDS: usize = 8;
const DRAFTS: &[(&str, &str)] = &[
(
"a hand-written walk",
"(function () {
var total = 0, at = 0;
while (at < orders.length) { total = total + orders[at].details.price }
return total;
}()",
),
(
"a fold that folds the wrong thing",
"orders.reduce(function (total) { return total + 1 }, 0)",
),
];
fn main() {
println!("task: answer with the total of every order's `price`\nexpecting: {EXPECTED}\n");
let solved: Vec<bool> = DRAFTS
.iter()
.map(|(label, draft)| solve(label, draft))
.collect();
assert_eq!(
solved,
[true, false],
"the loop's outcome is not the one this example is written to show"
);
}
fn solve(label: &str, draft: &str) -> bool {
println!("=== draft: {label} ===");
let mut source = draft.to_string();
for round in 1..=MAX_ROUNDS {
println!("--- round {round} ---\n{}", indent(&source));
let rejection = match attempt(&source) {
Ok(answer) => {
println!("accepted, and it answers {answer}\n");
return true;
}
Err(rejection) => rejection,
};
println!("rejected: {}", rejection.feedback());
let Some(patch) = repair(&source, &rejection) else {
println!("no rule applies — stopping.\n");
return false;
};
if patch.source == source {
println!("the patch changed nothing — stopping.\n");
return false;
}
println!("patch: {}\n", patch.what);
source = patch.source;
}
println!("give up: still not {EXPECTED} after {MAX_ROUNDS} rounds\n");
false
}
enum Rejection {
Unparsed(String),
Threw(String),
Ranaway,
Wrong(String),
NotTheScript(String),
}
impl Rejection {
fn feedback(&self) -> String {
match self {
Self::Unparsed(said) => format!(
"it is not a program yet — the parser said: {said}. Nothing ran, so there is \
nothing here about the data."
),
Self::Threw(said) => {
format!("it ran and threw: {said}. Something it assumed about the data is not so.")
}
Self::Ranaway => "it did not finish inside the time it was given, and was stopped. \
That is a loop whose condition never becomes false."
.to_string(),
Self::Wrong(got) => format!(
"it ran, finished, and answered {got} where the total is {EXPECTED}. Nothing went \
wrong — this is a working program that computes something else, so there is no \
error message to go on."
),
Self::NotTheScript(said) => format!("the sandbox itself is at fault: {said}"),
}
}
}
fn attempt(source: &str) -> Result<String, Rejection> {
let mut engine = sandbox();
engine.eval(FIXTURE).expect("the host's own fixture runs");
let value = engine.eval(source).map_err(classify)?;
let answer = engine.text(value).map_err(classify)?;
if answer == EXPECTED {
Ok(answer)
} else {
Err(Rejection::Wrong(answer))
}
}
fn classify(error: Error) -> Rejection {
match error {
Error::Syntax { message, .. } => Rejection::Unparsed(message),
Error::Thrown(said) => Rejection::Threw(said),
Error::Interrupted => Rejection::Ranaway,
Error::Collected => {
Rejection::NotTheScript("it answered with a value already freed".to_string())
}
Error::Engine(fault) => Rejection::NotTheScript(format!(
"a fault DR-0002 says no input can cause: {fault:?}"
)),
}
}
struct Patch {
what: String,
source: String,
}
fn repair(source: &str, rejection: &Rejection) -> Option<Patch> {
match rejection {
Rejection::Unparsed(said) => close_the_delimiter(source, said),
Rejection::Threw(said) if said.contains("not an object") => drop_the_dead_link(source),
Rejection::Ranaway => advance_the_counter(source),
Rejection::Threw(_) | Rejection::Wrong(_) | Rejection::NotTheScript(_) => None,
}
}
fn close_the_delimiter(source: &str, said: &str) -> Option<Patch> {
let wanted = said.split('`').nth(1)?;
if !matches!(wanted, ")" | "}" | "]") {
return None;
}
let patched = format!("{source}{wanted}");
parses(&patched).then(|| Patch {
what: format!("appended the `{wanted}` the parser asked for, and it parses now"),
source: patched,
})
}
fn drop_the_dead_link(source: &str) -> Option<Patch> {
for name in links_read_through(source) {
if ask(&format!(
"orders.some(function (o) {{ return '{name}' in Object(o) }})"
)) {
continue;
}
return Some(Patch {
what: format!("no order has a `{name}`, so the read goes straight through it"),
source: source.replace(&format!(".{name}."), "."),
});
}
None
}
fn advance_the_counter(source: &str) -> Option<Patch> {
let head = source.find("while (")? + "while (".len();
let condition_end = head + source[head..].find(')')?;
let name = identifier_at(&source[head..condition_end])?;
let open = condition_end + source[condition_end..].find('{')?;
let close = matching_brace(source, open)?;
if assigns(&source[open + 1..close], &name) {
return None;
}
let mut patched = String::from(source[..close].trim_end());
patched.push_str(&format!("\n {name} = {name} + 1;\n"));
patched.push_str(&source[close..]);
Some(Patch {
what: format!("the condition tests `{name}` and the body never writes it — advancing it"),
source: patched,
})
}
fn parses(source: &str) -> bool {
let mut engine = Engine::new();
engine.set_time_budget(Some(Duration::from_millis(5)));
!matches!(engine.eval(source), Err(Error::Syntax { .. }))
}
fn ask(question: &str) -> bool {
let mut engine = sandbox();
engine.eval(FIXTURE).expect("the host's own fixture runs");
engine
.eval(question)
.and_then(|value| engine.text(value))
.is_ok_and(|answer| answer == "true")
}
fn sandbox() -> Engine {
let mut engine = Engine::new();
engine.set_time_budget(Some(Duration::from_millis(50)));
engine.set_heap_budget(8 * 1024 * 1024);
engine
}
fn links_read_through(source: &str) -> Vec<String> {
let bytes = source.as_bytes();
let mut found = Vec::new();
let mut at = 0;
while at < bytes.len() {
if bytes[at] != b'.' {
at += 1;
continue;
}
let start = at + 1;
let mut end = start;
while end < bytes.len() && is_name_byte(bytes[end]) {
end += 1;
}
if end > start && bytes.get(end) == Some(&b'.') {
found.push(source[start..end].to_string());
}
at = end.max(start);
}
found
}
fn identifier_at(text: &str) -> Option<String> {
let start = text.find(|c: char| is_name_byte(c as u8))?;
let end = text[start..]
.find(|c: char| !is_name_byte(c as u8))
.map_or(text.len(), |at| start + at);
Some(text[start..end].to_string())
}
fn matching_brace(source: &str, open: usize) -> Option<usize> {
let mut depth = 0_usize;
for (at, byte) in source.bytes().enumerate().skip(open) {
match byte {
b'{' => depth += 1,
b'}' => {
depth -= 1;
if depth == 0 {
return Some(at);
}
}
_ => {}
}
}
None
}
fn assigns(body: &str, name: &str) -> bool {
body.match_indices(name).any(|(at, _)| {
let before = body[..at].bytes().next_back();
if before.is_some_and(|byte| is_name_byte(byte) || byte == b'.') {
return false;
}
let after = body[at + name.len()..].trim_start();
match after.as_bytes() {
[b'=', b'=', ..] => false,
[b'=', ..] | [b'+', b'+', ..] | [b'-', b'-', ..] => true,
[b'+', b'=', ..] | [b'-', b'=', ..] => true,
_ => false,
}
})
}
const fn is_name_byte(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$'
}
fn indent(source: &str) -> String {
source
.lines()
.map(|line| format!(" {line}"))
.collect::<Vec<_>>()
.join("\n")
}