use crate::lang::InnerKind;
use crate::prelude::*;
use crate::qterm::QTerm;
use miette::{bail, IntoDiagnostic, WrapErr};
use std::collections::BTreeMap;
use std::process::Command;
pub mod html;
pub use html::HtmlMachine;
pub mod pin;
pub use pin::{qspawn_pinned, Pin};
#[derive(Debug, Clone)]
pub struct MachineSpec {
pub program: Box<str>,
pub args: Box<[Box<str>]>,
pub print_wrap: Box<str>,
pub suffix: Box<str>,
pub env: Box<[(Box<str>, Box<str>)]>,
pub type_wrap: Option<Box<str>>,
pub clear_env: bool,
pub identity: Option<Box<str>>,
}
impl MachineSpec {
#[must_use]
pub fn from_hashbang(hashbang: &str, print_wrap: &str, suffix: &str) -> Option<MachineSpec> {
let (program, args) = crate::lang::parse_hashbang(hashbang)?;
Some(MachineSpec {
program: program.into(),
args: args.iter().map(|a| Box::from(*a)).collect(),
print_wrap: print_wrap.into(),
suffix: suffix.into(),
env: Box::default(),
type_wrap: None,
clear_env: false,
identity: None,
})
}
}
#[derive(Debug, Clone, Default)]
pub struct Answer {
pub value: Option<Box<str>>,
pub name: Option<Box<str>>,
pub stdout: Box<str>,
pub stderr: Box<str>,
}
pub trait Machine: Send {
fn lang(&self) -> &str;
fn identity(&self) -> Option<&str> {
None
}
fn feed(&mut self, kind: InnerKind, term: &QTerm) -> Result<Answer>;
fn eval(&mut self, term: &QTerm) -> Result<Answer> {
self.feed(InnerKind::Expr, term)
}
fn type_of(&mut self, term: &QTerm) -> Result<Answer> {
let _ = term;
bail!(
"the {} machine has no typing judgment registered (no type_wrap in its spec)",
self.lang()
)
}
}
pub struct Snapshot(Box<[u8]>);
pub trait SnapshotMachine: Machine {
fn snapshot(&self) -> Result<Snapshot>;
fn restore(&mut self, snapshot: &Snapshot) -> Result<()>;
}
pub trait ForkMachine: Machine {
fn fork(&self) -> Result<Box<dyn ForkMachine>>;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RunResult {
Finished,
Suspended,
}
pub trait MeteredMachine: Machine {
fn add_gas(&mut self, amount: u32);
fn run(&mut self, max_gas: u32) -> Result<RunResult>;
}
pub struct Def {
pub name: Box<str>,
pub kind: InnerKind,
}
pub trait IntrospectMachine: Machine {
fn defs(&self) -> Result<Vec<Def>>;
}
pub struct ScriptMachine {
lang: Box<str>,
spec: MachineSpec,
history: Vec<Box<str>>,
replayed: Box<str>,
}
impl ScriptMachine {
#[must_use]
pub fn new(lang: &str, spec: MachineSpec) -> ScriptMachine {
ScriptMachine {
lang: lang.into(),
spec,
history: Vec::new(),
replayed: Box::default(),
}
}
fn fresh(&self, stdout: &str) -> Box<str> {
stdout
.strip_prefix(&*self.replayed)
.unwrap_or(stdout)
.into()
}
fn script_with(&self, frag: &str) -> String {
let mut script = String::new();
for fed in &self.history {
script.push_str(fed);
script.push('\n');
}
script.push_str(frag);
script.push('\n');
script
}
fn run(&self, script: &str) -> Result<(Box<str>, Box<str>)> {
let file = tempfile::Builder::new()
.suffix(&*self.spec.suffix)
.tempfile()
.into_diagnostic()?;
std::fs::write(file.path(), script).into_diagnostic()?;
let spec = &self.spec;
let output = interpreter(&spec.program, &spec.args, &spec.env, spec.clear_env)
.arg(file.path())
.output()
.into_diagnostic()
.wrap_err_with(|| format!("failed to run {:?}", self.spec.program))?;
let stdout: Box<str> = String::from_utf8_lossy(&output.stdout).into();
let stderr: Box<str> = String::from_utf8_lossy(&output.stderr).into();
if !output.status.success() {
bail!(
"{} machine: {:?} failed with {}:\n{stdout}{stderr}",
self.lang,
self.spec.program,
output.status
);
}
Ok((stdout, stderr))
}
}
impl ScriptMachine {
fn query(&self, wrapped: &str) -> Result<Answer> {
let (stdout, stderr) = self.run(&self.script_with(wrapped))?;
let value = stdout
.lines()
.rev()
.find(|line| !line.trim().is_empty())
.map(|line| Box::from(line.trim()));
Ok(Answer {
value,
name: None,
stdout: self.fresh(&stdout),
stderr,
})
}
}
impl ScriptMachine {
pub fn feed_str(&mut self, kind: InnerKind, src: &str) -> Result<Answer> {
if kind == InnerKind::Expr {
self.query(&self.spec.print_wrap.replace("{}", src))
} else {
let (stdout, stderr) = self.run(&self.script_with(src))?;
let fresh = self.fresh(&stdout);
self.history.push(src.into());
self.replayed = stdout;
Ok(Answer {
value: None,
name: None,
stdout: fresh,
stderr,
})
}
}
pub fn type_of_str(&mut self, expr: &str) -> Result<Answer> {
let Some(wrap) = &self.spec.type_wrap else {
bail!(
"the {} machine has no typing judgment registered (no type_wrap in its spec)",
self.lang
)
};
self.query(&wrap.replace("{}", expr))
}
}
impl Machine for ScriptMachine {
fn lang(&self) -> &str {
&self.lang
}
fn identity(&self) -> Option<&str> {
self.spec.identity.as_deref()
}
fn feed(&mut self, kind: InnerKind, term: &QTerm) -> Result<Answer> {
self.feed_str(kind, term.coparse().trim())
}
fn type_of(&mut self, term: &QTerm) -> Result<Answer> {
self.type_of_str(term.coparse().trim())
}
}
impl ForkMachine for ScriptMachine {
fn fork(&self) -> Result<Box<dyn ForkMachine>> {
Ok(Box::new(ScriptMachine {
lang: self.lang.clone(),
spec: self.spec.clone(),
history: self.history.clone(),
replayed: self.replayed.clone(),
}))
}
}
impl SnapshotMachine for ScriptMachine {
fn snapshot(&self) -> Result<Snapshot> {
Ok(Snapshot(
postcard::to_stdvec(&self.history).into_diagnostic()?.into(),
))
}
fn restore(&mut self, snapshot: &Snapshot) -> Result<()> {
self.history = postcard::from_bytes(&snapshot.0).into_diagnostic()?;
Ok(())
}
}
#[derive(Debug, Clone)]
pub struct ReplSpec {
pub program: Box<str>,
pub args: Box<[Box<str>]>,
pub print_wrap: Box<str>,
pub echo_wrap: Box<str>,
pub env: Box<[(Box<str>, Box<str>)]>,
pub type_wrap: Option<Box<str>>,
pub echo_err_wrap: Option<Box<str>>,
pub clear_env: bool,
pub identity: Option<Box<str>>,
}
fn interpreter(
program: &str,
args: &[Box<str>],
env: &[(Box<str>, Box<str>)],
clear_env: bool,
) -> Command {
let mut command = Command::new(program);
command.args(args.iter().map(AsRef::<str>::as_ref));
if clear_env {
command.env_clear();
}
command.envs(env.iter().map(|(k, v)| (&**k, &**v)));
command
}
const REPL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
pub struct ReplMachine {
lang: Box<str>,
spec: ReplSpec,
child: std::process::Child,
stdin: std::process::ChildStdin,
stdout: std::sync::mpsc::Receiver<String>,
stderr: std::sync::mpsc::Receiver<String>,
feeds: usize,
}
impl ReplMachine {
pub fn spawn(lang: &str, spec: ReplSpec) -> Result<ReplMachine> {
use std::io::{BufRead as _, BufReader};
let mut child = interpreter(&spec.program, &spec.args, &spec.env, spec.clear_env)
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.into_diagnostic()
.wrap_err_with(|| format!("failed to start {:?}", spec.program))?;
let stdin = child.stdin.take().expect("stdin was piped");
let stdout_pipe = child.stdout.take().expect("stdout was piped");
let stderr_pipe = child.stderr.take().expect("stderr was piped");
let lines_of = |pipe: Box<dyn std::io::Read + Send>| {
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let mut reader = BufReader::new(pipe);
let mut buf = Vec::new();
loop {
buf.clear();
match reader.read_until(b'\n', &mut buf) {
Ok(0) | Err(_) => break,
Ok(_) => {}
}
if buf.last() == Some(&b'\n') {
buf.pop();
if buf.last() == Some(&b'\r') {
buf.pop();
}
}
if tx.send(String::from_utf8_lossy(&buf).into_owned()).is_err() {
break;
}
}
});
rx
};
let stdout = lines_of(Box::new(stdout_pipe));
let stderr = lines_of(Box::new(stderr_pipe));
Ok(ReplMachine {
lang: lang.into(),
spec,
child,
stdin,
stdout,
stderr,
feeds: 0,
})
}
fn drain_stderr(&self) -> Box<str> {
let mut out = String::new();
while let Ok(line) = self.stderr.try_recv() {
out.push_str(&line);
out.push('\n');
}
out.into()
}
fn stderr_until(&self, sentinel: &str) -> Result<Box<str>> {
use std::sync::mpsc::RecvTimeoutError;
let mut out = String::new();
loop {
match self.stderr.recv_timeout(REPL_TIMEOUT) {
Ok(line) if line.trim() == sentinel => return Ok(out.into()),
Ok(line) => {
out.push_str(&line);
out.push('\n');
}
Err(RecvTimeoutError::Timeout) => bail!(
"{} machine: {:?} did not echo on stderr within {REPL_TIMEOUT:?}",
self.lang,
self.spec.program
),
Err(RecvTimeoutError::Disconnected) => bail!(
"{} machine: {:?} exited mid-feed:\n{out}",
self.lang,
self.spec.program
),
}
}
}
}
impl ReplMachine {
fn exchange(&mut self, payload: &str, collect_value: bool) -> Result<Answer> {
use std::io::Write as _;
use std::sync::mpsc::RecvTimeoutError;
self.feeds += 1;
let sentinel = format!("__QUILT_REPL_DONE_{}__", self.feeds);
let mut input = format!(
"{payload}\n{}\n",
self.spec.echo_wrap.replace("{}", &sentinel)
);
if let Some(err_wrap) = &self.spec.echo_err_wrap {
input.push_str(&err_wrap.replace("{}", &sentinel));
input.push('\n');
}
if let Err(e) = self
.stdin
.write_all(input.as_bytes())
.and_then(|()| self.stdin.flush())
{
bail!(
"{} machine: {:?} is gone ({e}):\n{}",
self.lang,
self.spec.program,
self.drain_stderr()
);
}
let rejected = format!("{sentinel} !");
let mut failed = false;
let mut lines = Vec::new();
loop {
match self.stdout.recv_timeout(REPL_TIMEOUT) {
Ok(line) if line.trim() == sentinel => break,
Ok(line) if line.trim() == rejected => {
failed = true;
break;
}
Ok(line) => lines.push(line),
Err(RecvTimeoutError::Timeout) => bail!(
"{} machine: {:?} did not answer within {REPL_TIMEOUT:?}",
self.lang,
self.spec.program
),
Err(RecvTimeoutError::Disconnected) => bail!(
"{} machine: {:?} exited mid-feed:\n{}",
self.lang,
self.spec.program,
self.drain_stderr()
),
}
}
let value = collect_value
.then(|| {
lines
.iter()
.rev()
.find(|line| !line.trim().is_empty())
.map(|line| Box::from(line.trim()))
})
.flatten();
let stderr = if self.spec.echo_err_wrap.is_some() {
self.stderr_until(&sentinel)?
} else {
self.drain_stderr()
};
if failed {
bail!(
"{} machine: {:?} rejected the fragment:\n{stderr}",
self.lang,
self.spec.program
);
}
Ok(Answer {
value,
name: None,
stdout: lines.join("\n").into(),
stderr,
})
}
}
impl ReplMachine {
pub fn feed_str(&mut self, kind: InnerKind, src: &str) -> Result<Answer> {
if kind == InnerKind::Expr {
let payload = self.spec.print_wrap.replace("{}", src);
self.exchange(&payload, true)
} else {
self.exchange(src, false)
}
}
pub fn type_of_str(&mut self, expr: &str) -> Result<Answer> {
let Some(wrap) = &self.spec.type_wrap else {
bail!(
"the {} machine has no typing judgment registered (no type_wrap in its spec)",
self.lang
)
};
let payload = wrap.replace("{}", expr);
self.exchange(&payload, true)
}
}
impl Machine for ReplMachine {
fn lang(&self) -> &str {
&self.lang
}
fn identity(&self) -> Option<&str> {
self.spec.identity.as_deref()
}
fn feed(&mut self, kind: InnerKind, term: &QTerm) -> Result<Answer> {
self.feed_str(kind, term.coparse().trim())
}
fn type_of(&mut self, term: &QTerm) -> Result<Answer> {
self.type_of_str(term.coparse().trim())
}
}
impl Drop for ReplMachine {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
pub const REGISTERED_SPECS: &[&str] = &[
"lean",
"lean4",
"python",
"py",
"typescript",
"ts",
"sql",
"bash",
"zsh",
"html",
];
#[must_use]
pub fn has_spec(lang: &str) -> bool {
native_machine(lang).is_some() || repl_spec(lang).is_some() || script_spec(lang).is_some()
}
#[must_use]
pub fn native_machine(lang: &str) -> Option<Box<dyn Machine>> {
match lang {
"html" => Some(Box::new(HtmlMachine::default())),
_ => None,
}
}
const PYTHON_KERNEL: &str = r#"
import re, sys, traceback
ns = {"__name__": "__quilt__"}
try:
exec("from quilt import *", ns)
except ImportError:
pass
mark = re.compile(r'^print\("(__QUILT_REPL_DONE_\d+__)"(, file=sys\.stderr)?\)$')
buf = []
for line in sys.stdin:
line = line.rstrip("\n")
m = mark.match(line)
if m is None:
buf.append(line)
continue
if m.group(2):
sys.stderr.write(m.group(1) + "\n")
sys.stderr.flush()
continue
src = "\n".join(buf) + "\n"
buf = []
failed = ""
try:
exec(compile(src, "<quilt>", "exec"), ns)
except Exception:
traceback.print_exc()
failed = " !"
sys.stdout.flush()
sys.stderr.flush()
print(m.group(1) + failed)
sys.stdout.flush()
"#;
const TYPESCRIPT_KERNEL: &str = r#"
const vm = require("node:vm"), rl = require("node:readline"), mod = require("node:module");
const ctx = vm.createContext(Object.assign(Object.create(globalThis), { require, console, process }));
try { Object.assign(ctx, require(process.env.QUILT_WASM_PKG)); } catch {}
// A chunk's top-level errors are caught by `run` below, but a *rejected*
// promise it returns (an unawaited `fetch`, say) surfaces later, off this
// process's default handler — which is fatal (Node 15+) and would take the
// whole kernel, and every cell still to come in this session, down with it.
// Logging it where a synchronous throw already goes keeps one bad promise
// from being worse than a bug a `try`/`catch` would have caught.
process.on("uncaughtException", (e) => console.error(e && e.stack ? e.stack : String(e)));
process.on("unhandledRejection", (e) => console.error(e && e.stack ? e.stack : String(e)));
const mark = /^console\.(log|error)\("(__QUILT_REPL_DONE_\d+__)"\)$/;
let buf = [];
function run(src) {
try {
return vm.runInContext(src, ctx, { filename: "<quilt>" });
} catch (e) {
if (e?.name !== "SyntaxError" || typeof mod.stripTypeScriptTypes !== "function") throw e;
let stripped;
try { stripped = mod.stripTypeScriptTypes(src, { mode: "strip" }); } catch { throw e; }
return vm.runInContext(stripped, ctx, { filename: "<quilt>" });
}
}
rl.createInterface({ input: process.stdin, terminal: false }).on("line", (line) => {
const m = mark.exec(line);
if (!m) { buf.push(line); return; }
if (m[1] === "error") { console.error(m[2]); return; }
const src = buf.join("\n");
buf = [];
let failed = "";
try { run(src); } catch (e) { console.error(e && e.stack ? e.stack : String(e)); failed = " !"; }
console.log(m[2] + failed);
});
"#;
#[must_use]
pub fn repl_spec(lang: &str) -> Option<ReplSpec> {
let (program, args, print_wrap, echo_wrap, echo_err_wrap, type_wrap): (
_,
&[&str],
_,
_,
Option<&str>,
_,
) = match lang {
"sql" => (
"sqlite3",
&["-batch", "-bail"],
"SELECT {};",
"SELECT '{}';",
None,
Some("SELECT typeof({});"),
),
"bash" => (
"bash",
&[],
"echo $(( {} ))",
"[ $? -eq 0 ] && echo {} || echo '{} !'",
Some("echo {} >&2"),
None,
),
"zsh" => (
"zsh",
&[],
"echo $(( {} ))",
"[ $? -eq 0 ] && echo {} || echo '{} !'",
Some("echo {} >&2"),
None,
),
"python" | "py" => (
"python3",
&["-u", "-c", PYTHON_KERNEL],
"print(repr({}))",
"print(\"{}\")",
Some("print(\"{}\", file=sys.stderr)"),
Some("print(type({}).__name__)"),
),
"typescript" | "ts" => (
"node",
&["--no-warnings", "-e", TYPESCRIPT_KERNEL],
"console.log(JSON.stringify({}))",
"console.log(\"{}\")",
Some("console.error(\"{}\")"),
Some("console.log(typeof ({}))"),
),
_ => return None,
};
let env: Box<[(Box<str>, Box<str>)]> = match lang {
"python" | "py" => Box::new([(
"PYTHONPATH".into(),
concat!(env!("CARGO_MANIFEST_DIR"), "/../quilt-python").into(),
)]),
"typescript" | "ts" => Box::new([
(
"QUILT_WASM_PKG".into(),
concat!(
env!("CARGO_MANIFEST_DIR"),
"/../quilt-wasm/pkg/quilt_wasm.js"
)
.into(),
),
("FORCE_COLOR".into(), "0".into()),
]),
_ => Box::default(),
};
Some(ReplSpec {
program: program.into(),
args: args.iter().map(|a| Box::from(*a)).collect(),
print_wrap: print_wrap.into(),
echo_wrap: echo_wrap.into(),
env,
type_wrap: type_wrap.map(Box::from),
echo_err_wrap: echo_err_wrap.map(Box::from),
clear_env: false,
identity: None,
})
}
#[must_use]
pub fn script_spec(lang: &str) -> Option<MachineSpec> {
match lang {
"python" | "py" => {
let mut spec =
MachineSpec::from_hashbang("#!/usr/bin/env python3", "print(repr({}))", ".py")?;
spec.env = Box::new([(
"PYTHONPATH".into(),
concat!(env!("CARGO_MANIFEST_DIR"), "/../quilt-python").into(),
)]);
spec.type_wrap = Some("print(type({}).__name__)".into());
Some(spec)
}
"typescript" | "ts" => MachineSpec::from_hashbang(
"#!/usr/bin/env -S node --experimental-strip-types",
"console.log(JSON.stringify({}))",
".ts",
),
"lean" | "lean4" => Some(MachineSpec {
program: "lean".into(),
args: Box::default(),
print_wrap: "#eval {}".into(),
suffix: ".lean".into(),
env: Box::default(),
type_wrap: Some("#check {}".into()),
clear_env: false,
identity: None,
}),
_ => None,
}
}
pub fn qspawn(lang: &str) -> Result<Box<dyn Machine>> {
if let Some(machine) = native_machine(lang) {
return Ok(machine);
}
if let Some(spec) = repl_spec(lang) {
return Ok(Box::new(ReplMachine::spawn(lang, spec)?));
}
if let Some(spec) = script_spec(lang) {
return Ok(Box::new(ScriptMachine::new(lang, spec)));
}
bail!(
"no machine is registered for {lang:?}; quilt knows: {}",
REGISTERED_SPECS.join(", ")
)
}
pub fn spawn_machine<L: crate::lang::Language + ?Sized>(
lang_name: &str,
lang: &L,
) -> Result<Box<dyn Machine>> {
if let Some(machine) = lang.native_machine() {
return Ok(machine);
}
if let Some(spec) = lang.repl_spec() {
return Ok(Box::new(ReplMachine::spawn(lang_name, spec)?));
}
if let Some(spec) = lang.machine_spec() {
return Ok(Box::new(ScriptMachine::new(lang_name, spec)));
}
bail!("language {lang_name:?} has no machine: no native, repl or script provider registered")
}
#[derive(Default)]
pub struct Park {
machines: BTreeMap<Box<str>, Box<dyn Machine>>,
}
impl Park {
#[must_use]
pub fn contains(&self, lang: &str) -> bool {
self.machines.contains_key(lang)
}
pub fn insert(&mut self, lang: &str, machine: Box<dyn Machine>) {
self.machines.insert(lang.into(), machine);
}
pub fn get_mut(&mut self, lang: &str) -> Option<&mut (dyn Machine + 'static)> {
self.machines.get_mut(lang).map(AsMut::as_mut)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn sh_machine() -> ScriptMachine {
ScriptMachine::new(
"sh",
MachineSpec {
program: "sh".into(),
args: Box::default(),
print_wrap: "echo $(( {} ))".into(),
suffix: ".sh".into(),
env: Box::default(),
type_wrap: None,
clear_env: false,
identity: None,
},
)
}
#[test]
fn definitions_accumulate_and_queries_answer() {
let mut m = sh_machine();
let fed = m.feed_str(InnerKind::Item, "x=5").unwrap();
assert_eq!(fed.value, None);
let ask = m.feed_str(InnerKind::Expr, "x + 2").unwrap();
assert_eq!(ask.value.as_deref(), Some("7"));
let ask = m.feed_str(InnerKind::Expr, "x * x").unwrap();
assert_eq!(ask.value.as_deref(), Some("25"));
}
#[test]
fn forks_start_equal_and_diverge() {
let mut a = sh_machine();
a.feed_str(InnerKind::Item, "x=5").unwrap();
let mut b = a.fork().unwrap();
a.feed_str(InnerKind::Item, "x=6").unwrap();
b.feed(InnerKind::Item, &crate::qterm::qleaf("code", "y=7"))
.unwrap();
assert_eq!(
&*a.feed_str(InnerKind::Expr, "x").unwrap().value.unwrap(),
"6"
);
let x = b.feed(InnerKind::Expr, &crate::qterm::qleaf("code", "x"));
assert_eq!(x.unwrap().value.as_deref(), Some("5"));
}
#[test]
fn lean_judges_what_it_is_fed() {
let has_lean = Command::new("lean").arg("--version").output().is_ok();
if !has_lean {
return;
}
let mut m = ScriptMachine::new("lean", script_spec("lean").unwrap());
m.feed_str(InnerKind::Item, "def twice (n : Nat) := n + n")
.unwrap();
m.feed_str(InnerKind::Item, "theorem t : twice 2 = 4 := rfl")
.unwrap();
let v = m.feed_str(InnerKind::Expr, "twice 21").unwrap();
assert_eq!(v.value.as_deref(), Some("42"));
let ty = m.type_of_str("twice").unwrap();
assert_eq!(ty.value.as_deref(), Some("twice (n : Nat) : Nat"));
let no = m.feed_str(InnerKind::Item, "theorem no : 1 = 2 := rfl");
assert!(no.unwrap_err().to_string().contains("failed"));
let v = m.feed_str(InnerKind::Expr, "twice 1").unwrap();
assert_eq!(v.value.as_deref(), Some("2"));
}
#[test]
fn machines_are_isolated() {
let mut a = sh_machine();
let mut b = sh_machine();
a.feed_str(InnerKind::Item, "x=1").unwrap();
b.feed_str(InnerKind::Item, "x=100").unwrap();
assert_eq!(
a.feed_str(InnerKind::Expr, "x + 1")
.unwrap()
.value
.as_deref(),
Some("2")
);
assert_eq!(
b.feed_str(InnerKind::Expr, "x + 1")
.unwrap()
.value
.as_deref(),
Some("101")
);
}
#[test]
fn failed_feeds_stay_out_of_history() {
let mut m = sh_machine();
m.feed_str(InnerKind::Item, "x=5").unwrap();
assert!(m.feed_str(InnerKind::Stmt, "exit 3").is_err());
let ask = m.feed_str(InnerKind::Expr, "x + 2").unwrap();
assert_eq!(ask.value.as_deref(), Some("7"));
}
#[test]
fn replayed_output_is_not_reported_again() {
let mut m = sh_machine();
let fed = m.feed_str(InnerKind::Stmt, "echo hi").unwrap();
assert_eq!(&*fed.stdout, "hi\n");
let ask = m.feed_str(InnerKind::Expr, "1 + 1").unwrap();
assert_eq!(ask.value.as_deref(), Some("2"));
assert_eq!(&*ask.stdout, "2\n", "got: {:?}", ask.stdout);
let fed = m.feed_str(InnerKind::Stmt, "echo again").unwrap();
assert_eq!(&*fed.stdout, "again\n");
}
fn sh_repl() -> ReplMachine {
ReplMachine::spawn(
"sh",
ReplSpec {
program: "sh".into(),
args: Box::default(),
print_wrap: "echo $(( {} ))".into(),
echo_wrap: "echo {}".into(),
env: Box::default(),
type_wrap: None,
echo_err_wrap: Some("echo {} >&2".into()),
clear_env: false,
identity: None,
},
)
.unwrap()
}
#[test]
fn stderr_is_framed_per_feed() {
let mut m = sh_repl();
let a = m.feed_str(InnerKind::Stmt, "echo oops >&2").unwrap();
assert_eq!(&*a.stderr, "oops\n");
let b = m.feed_str(InnerKind::Expr, "1 + 1").unwrap();
assert_eq!(&*b.stderr, "", "the next feed starts clean");
}
#[test]
fn bash_rejects_a_failing_fragment() {
let mut m = ReplMachine::spawn("bash", repl_spec("bash").unwrap()).unwrap();
m.feed_str(InnerKind::Item, "x=5").unwrap();
let err = m.feed_str(InnerKind::Stmt, "false").unwrap_err();
assert!(err.to_string().contains("rejected"), "{err}");
let err = m
.feed_str(InnerKind::Stmt, "echo boom >&2; exit_code_of_nothing")
.unwrap_err();
assert!(err.to_string().contains("boom"), "carries stderr: {err}");
assert_eq!(
m.feed_str(InnerKind::Expr, "x + 1")
.unwrap()
.value
.as_deref(),
Some("6")
);
}
#[test]
fn python_kernel_is_a_persistent_machine() {
let mut m = ReplMachine::spawn("py", repl_spec("py").unwrap()).unwrap();
let fed = m.feed_str(InnerKind::Stmt, "print('once')").unwrap();
assert_eq!(&*fed.stdout, "once");
m.feed_str(
InnerKind::Item,
"def f(x):\n if x > 1:\n return x * 2\n else:\n return x",
)
.unwrap();
let ask = m.feed_str(InnerKind::Expr, "f(21)").unwrap();
assert_eq!(ask.value.as_deref(), Some("42"));
assert!(!ask.stdout.contains("once"), "no replay: {:?}", ask.stdout);
let bad = m.feed_str(InnerKind::Expr, "undefined_name").unwrap_err();
assert!(bad.to_string().contains("NameError"), "{bad}");
let ask = m.feed_str(InnerKind::Expr, "f(1)").unwrap();
assert_eq!(ask.value.as_deref(), Some("1"), "still alive");
assert_eq!(
m.type_of_str("f(21)").unwrap().value.as_deref(),
Some("int")
);
}
#[test]
fn typescript_kernel_is_a_persistent_machine() {
let mut m = ReplMachine::spawn("ts", repl_spec("ts").unwrap()).unwrap();
m.feed_str(InnerKind::Item, "const y: number = 40").unwrap();
let ask = m.feed_str(InnerKind::Expr, "y + 2").unwrap();
assert_eq!(ask.value.as_deref(), Some("42"));
let bad = m.feed_str(InnerKind::Expr, "nope").unwrap_err();
assert!(bad.to_string().contains("ReferenceError"), "{bad}");
let ask = m.feed_str(InnerKind::Expr, "[y, 'a']").unwrap();
assert_eq!(ask.value.as_deref(), Some("[40,\"a\"]"));
assert_eq!(m.type_of_str("y").unwrap().value.as_deref(), Some("number"));
}
#[test]
fn html_is_native() {
let mut m = qspawn("html").unwrap();
assert_eq!(m.lang(), "html");
let ask = m.feed(InnerKind::Expr, &leaf("text", "hi")).unwrap();
assert_eq!(ask.value.as_deref(), Some("hi"));
assert!(has_spec("html"));
}
#[test]
fn repl_state_persists_without_replay() {
let mut m = sh_repl();
let fed = m.feed_str(InnerKind::Stmt, "echo hi").unwrap();
assert!(fed.stdout.contains("hi"));
m.feed_str(InnerKind::Item, "x=5").unwrap();
let ask = m.feed_str(InnerKind::Expr, "x + 2").unwrap();
assert_eq!(ask.value.as_deref(), Some("7"));
assert!(!ask.stdout.contains("hi"), "got: {:?}", ask.stdout);
}
#[test]
fn a_dead_repl_is_an_error() {
let mut m = sh_repl();
assert!(m.feed_str(InnerKind::Stmt, "exit 0").is_err());
}
#[test]
fn snapshots_roll_definitions_back() {
let mut m = sh_machine();
m.feed_str(InnerKind::Item, "x=5").unwrap();
let snap = m.snapshot().unwrap();
m.feed_str(InnerKind::Item, "x=9").unwrap();
assert_eq!(
m.feed_str(InnerKind::Expr, "x").unwrap().value.as_deref(),
Some("9")
);
m.restore(&snap).unwrap();
assert_eq!(
m.feed_str(InnerKind::Expr, "x").unwrap().value.as_deref(),
Some("5")
);
}
#[test]
fn no_type_wrap_is_an_honest_error() {
let mut m = sh_machine();
let err = m.type_of_str("1 + 1").unwrap_err();
assert!(err.to_string().contains("typing judgment"), "got: {err}");
}
#[test]
fn python_answers_its_own_literals() {
let spec =
MachineSpec::from_hashbang("#!/usr/bin/env python3", "print(repr({}))", ".py").unwrap();
let mut m = ScriptMachine::new("py", spec);
m.feed_str(InnerKind::Item, "def f(x):\n return x * 2")
.unwrap();
assert_eq!(
m.feed_str(InnerKind::Expr, "f(21)")
.unwrap()
.value
.as_deref(),
Some("42")
);
assert_eq!(
m.feed_str(InnerKind::Expr, "'ab' * 2")
.unwrap()
.value
.as_deref(),
Some("'abab'")
);
}
#[test]
fn a_cleared_environment_holds_only_what_the_spec_sets() {
if std::env::var_os("HOME").is_none() {
return;
}
let spec = |clear_env| ReplSpec {
program: "/bin/sh".into(),
args: Box::default(),
print_wrap: "echo $(( {} ))".into(),
echo_wrap: "echo {}".into(),
env: Box::new([("ONLY".into(), "set".into())]),
type_wrap: None,
echo_err_wrap: Some("echo {} >&2".into()),
clear_env,
identity: None,
};
let says = |clear_env| {
let mut m = ReplMachine::spawn("sh", spec(clear_env)).unwrap();
let a = m
.feed_str(InnerKind::Stmt, "echo ${HOME:+home}:$ONLY")
.unwrap();
a.stdout.trim().to_string()
};
assert_eq!(says(false), "home:set");
assert_eq!(says(true), ":set");
}
#[test]
fn identity_is_none_unless_the_spec_knows() {
assert_eq!(sh_repl().identity(), None);
assert_eq!(sh_machine().identity(), None);
let mut spec = sh_machine().spec.clone();
spec.identity = Some("0123-sh".into());
assert_eq!(ScriptMachine::new("sh", spec).identity(), Some("0123-sh"));
}
#[test]
fn python_answers_types() {
let spec = MachineSpec {
type_wrap: Some("print(type({}).__name__)".into()),
..MachineSpec::from_hashbang("#!/usr/bin/env python3", "print(repr({}))", ".py")
.unwrap()
};
let mut m = ScriptMachine::new("py", spec);
assert_eq!(
m.type_of_str("21 + 21").unwrap().value.as_deref(),
Some("int")
);
m.feed_str(InnerKind::Item, "s = 'hi'").unwrap();
assert_eq!(
m.type_of_str("s * 2").unwrap().value.as_deref(),
Some("str")
);
}
}