Skip to main content

quilt/
machine.rs

1//! Machines: stateful evaluators of a language.
2//!
3//! A [`Machine`] is the semantic twin of [`Language`](crate::lang::Language):
4//! where a `Language` says what a fragment *is* (text → term), a `Machine`
5//! says what it *does*, and remembers — fed programs over time, it
6//! accumulates definitions and effects, and answers queries with the literal
7//! spelling of the value. See `docs/design/machines.md` for the full design
8//! (meta-machines, `↓` on machines, REPL/Jupyter/DB providers); this module
9//! is phase 1: the trait, the [`Answer`], the replay-based [`ScriptMachine`],
10//! and the [`Park`] of live per-language defaults that
11//! [`Multi`](crate::multi::Multi) carries.
12//!
13//! The trait traffics in terms ([`Machine::feed`]), like every other Quilt
14//! interface — tenet 2 is about the *end user* writing plain source text,
15//! not about internal APIs. The validated textual doors live where the
16//! `Language` that can parse lives: [`Multi::feed_on`] takes user text in,
17//! and [`Multi::eval_on`] parses the answered literal back out. A provider
18//! whose *wire* is text (a subprocess's stdin) coparses internally — its
19//! business, not the caller's — and exposes that raw door as inherent
20//! `feed_str`/`type_of_str` methods on the concrete type. Like `lift`, this
21//! module has no tree-sitter dependency and is part of the runtime-only
22//! build.
23//!
24//! [`Multi::feed_on`]: crate::multi::Multi::feed_on
25//! [`Multi::eval_on`]: crate::multi::Multi::eval_on
26
27use crate::lang::InnerKind;
28use crate::prelude::*;
29use crate::qterm::QTerm;
30use miette::{bail, IntoDiagnostic, WrapErr};
31use std::collections::BTreeMap;
32use std::process::Command;
33
34// The one *native* provider: a document held in-process, whose definitions
35// are elements with ids. Term-only, so it belongs on this runtime path like
36// the rest of the module.
37pub mod html;
38pub use html::HtmlMachine;
39
40// Machines named by the Nix content address of everything they run, and
41// spawned from it with an empty environment.
42pub mod pin;
43pub use pin::{qspawn_pinned, Pin};
44
45/**************************************************************/
46
47/// What a [`ScriptMachine`] needs to know about a language: how to run a
48/// script of it, and how to spell "print this value as a literal".
49///
50/// Declared per language via
51/// [`Language::machine_spec`](crate::lang::Language::machine_spec), the same
52/// pattern as [`hashbang`](crate::lang::Language::hashbang) — and usually
53/// derived from it, via [`MachineSpec::from_hashbang`].
54#[derive(Debug, Clone)]
55pub struct MachineSpec {
56    /// The interpreter to execute, e.g. `python3`.
57    pub program: Box<str>,
58    /// Arguments that precede the script path, e.g.
59    /// `--experimental-strip-types` for node.
60    pub args: Box<[Box<str>]>,
61    /// The spelling of "print the value of this expression as a literal of
62    /// this language", with `{}` standing for the expression — e.g. Python's
63    /// `print(repr({}))`. This is what makes an [`Answer::value`] the inverse
64    /// of lift: the machine answers with source that re-denotes the value.
65    pub print_wrap: Box<str>,
66    /// Suffix for the temp script file, e.g. `.py` (some runners sniff it).
67    pub suffix: Box<str>,
68    /// Environment variables set for the interpreter (overriding inherited
69    /// values) — e.g. the `PYTHONPATH` that makes `from quilt import *`
70    /// resolve, the same path `reduce_py` teaches its one-shot script.
71    pub env: Box<[(Box<str>, Box<str>)]>,
72    /// The spelling of the *typing* judgment, when the language has one:
73    /// "print the type of this expression", `{}` standing for the
74    /// expression — python's `print(type({}).__name__)`, Lean's `#check {}`.
75    /// `None` gives [`Machine::type_of`]'s honest default error.
76    pub type_wrap: Option<Box<str>>,
77    /// Start the interpreter with an **empty** environment, so that nothing
78    /// of the caller's (`PATH`, `PYTHONPATH`, locale, …) reaches it: only
79    /// [`env`](Self::env) is set. Off for the registered specs, which mean
80    /// "the interpreter this shell would run"; on for a [pinned](pin)
81    /// machine, where the point is that the spec alone decides what runs.
82    pub clear_env: bool,
83    /// What this machine *is*, when the spec knows exactly: see
84    /// [`Machine::identity`]. `None` for an interpreter found on `PATH`.
85    pub identity: Option<Box<str>>,
86}
87
88impl MachineSpec {
89    /// Derive the runner from a shebang line (unwrapping `env` the way
90    /// [`parse_hashbang`](crate::lang::parse_hashbang) does), supplying the
91    /// two spellings the shebang cannot: the print wrapper and the suffix.
92    ///
93    /// `None` when the shebang names no interpreter.
94    #[must_use]
95    pub fn from_hashbang(hashbang: &str, print_wrap: &str, suffix: &str) -> Option<MachineSpec> {
96        let (program, args) = crate::lang::parse_hashbang(hashbang)?;
97        Some(MachineSpec {
98            program: program.into(),
99            args: args.iter().map(|a| Box::from(*a)).collect(),
100            print_wrap: print_wrap.into(),
101            suffix: suffix.into(),
102            env: Box::default(),
103            type_wrap: None,
104            clear_env: false,
105            identity: None,
106        })
107    }
108}
109
110/**************************************************************/
111
112/// A machine's reply to one fed fragment.
113#[derive(Debug, Clone, Default)]
114pub struct Answer {
115    /// The value as a literal of the machine's own language — the inverse of
116    /// lift — when the fragment was a query ([`InnerKind::Expr`]) and the
117    /// value has a literal spelling. `None` for definitions and effects.
118    pub value: Option<Box<str>>,
119    /// A residue: when a value has no literal spelling (an open file, a
120    /// closure), the machine binds it to a fresh name and answers with the
121    /// reference instead. The value stays in the machine. (No phase-1
122    /// provider produces residues yet; the field is the protocol's.)
123    pub name: Option<Box<str>>,
124    /// Everything the feed wrote to stdout, for display and diagnostics.
125    /// For a replay-based machine this includes the replayed history's
126    /// output, not only the new fragment's.
127    pub stdout: Box<str>,
128    /// Everything the feed wrote to stderr.
129    pub stderr: Box<str>,
130}
131
132/**************************************************************/
133
134/// A stateful evaluator of one language.
135///
136/// The message sorts are [`InnerKind`] — already the vocabulary "for
137/// communicating between parsers" (`lang.rs`), and equally the vocabulary
138/// for communicating with machines:
139///
140/// * [`Item`](InnerKind::Item) — a definition: extends the environment.
141/// * [`Stmt`](InnerKind::Stmt) — an effect: runs against the environment.
142/// * [`Expr`](InnerKind::Expr) — a query: answers the value's denotation.
143/// * [`File`](InnerKind::File) / [`Block`](InnerKind::Block) — a batch.
144///
145/// The laws a well-behaved machine satisfies (asserted by the conformance
146/// battery as providers grow): *denotation* — evaluating a literal answers
147/// that literal; *sequencing* — `feed(p1); feed(p2)` behaves as feeding
148/// `p1; p2` to a fresh machine; *isolation* — two machines share nothing.
149///
150/// `Send` is a supertrait because parked machines travel with their `Multi`
151/// (test harnesses hold one behind a `Mutex`); a machine is a handle to a
152/// process or connection, which sends fine.
153///
154/// The trait traffics in **terms**, like every other Quilt interface. Tenet
155/// 2 is about the *end user* writing plain source text rather than builder
156/// calls — it says nothing about internal APIs, and the parser that can turn
157/// user text into a term lives with the `Language`, not here. So the
158/// validated textual door is [`Multi::feed_on`](crate::multi::Multi::feed_on)
159/// at the rim; a provider whose *wire* is text (a subprocess's stdin)
160/// coparses internally, which is its business and no caller's.
161pub trait Machine: Send {
162    /// The language this machine speaks (a registry key, e.g. `"py"`).
163    fn lang(&self) -> &str;
164
165    /// Which machine this is, when that is known exactly: a name for
166    /// everything it runs, such that two machines with the same identity
167    /// are the same interpreter, libraries, arguments and environment. A
168    /// [pinned](pin) machine answers its content address.
169    ///
170    /// `None` — the default — is the honest answer for an interpreter found
171    /// on `PATH`: [`lang`](Machine::lang) says what it speaks, and nothing
172    /// says which build of it answered. A caller that records what a machine
173    /// said (a cache, a log, a signed result) keys on this, and should refuse
174    /// to when it is `None`.
175    fn identity(&self) -> Option<&str> {
176        None
177    }
178
179    /// Feed one term. Definitions and effects accumulate; queries answer.
180    fn feed(&mut self, kind: InnerKind, term: &QTerm) -> Result<Answer>;
181
182    /// Query a term's value: [`feed`](Machine::feed) as [`InnerKind::Expr`].
183    fn eval(&mut self, term: &QTerm) -> Result<Answer> {
184        self.feed(InnerKind::Expr, term)
185    }
186
187    /// The *typing* judgment: answer the type of the term, as a literal of
188    /// this language's type spellings (`int`, `42 : ℕ`, `unsat`). An
189    /// evaluator asks "what value"; a checker — Lean, a solver, an LSP —
190    /// asks this instead, and a proof language's machine may support *only*
191    /// this and Item-checking. Defaults to an honest error, the same
192    /// pattern as the operator spellings on `MetaLanguage`.
193    fn type_of(&mut self, term: &QTerm) -> Result<Answer> {
194        let _ = term;
195        bail!(
196            "the {} machine has no typing judgment registered (no type_wrap in its spec)",
197            self.lang()
198        )
199    }
200}
201
202/**************************************************************/
203
204/// An opaque snapshot of one machine's state, for fork and rollback. The
205/// encoding is the providing machine's own; restoring into a different
206/// provider fails at decode rather than corrupting anything.
207pub struct Snapshot(Box<[u8]>);
208
209/// Machines that can checkpoint and roll back their environment — Racket
210/// namespaces, Smalltalk images, a solver's `push`/`pop`, and (trivially,
211/// exactly) a [`ScriptMachine`]'s history.
212pub trait SnapshotMachine: Machine {
213    fn snapshot(&self) -> Result<Snapshot>;
214    fn restore(&mut self, snapshot: &Snapshot) -> Result<()>;
215}
216
217/// Machines that can be forked into a live sibling: the fork starts from this
218/// machine's environment, and the two diverge from there, sharing nothing the
219/// [isolation law](Machine) would notice.
220///
221/// This is not [`SnapshotMachine`] spelled differently. Restoring replaces a
222/// machine's state, so one handle lives one timeline at a time; a fork leaves
223/// both alive, which is what exploring several contexts from one expensive
224/// start wants. A process that took seconds to load is forked once for each
225/// hypothesis, not reloaded for each. A solver's `push`/`pop` is a snapshot and
226/// not a fork; an immutable environment, such as Lean's, is both for free.
227pub trait ForkMachine: Machine {
228    fn fork(&self) -> Result<Box<dyn ForkMachine>>;
229}
230
231/// What a bounded run of a [`MeteredMachine`] came back with.
232#[derive(Debug, Clone, Copy, PartialEq, Eq)]
233pub enum RunResult {
234    Finished,
235    Suspended,
236}
237
238/// Machines whose execution is resource-bounded and resumable — the shape of
239/// nanobots' `StateMachine` (gas checked per basic block, explicit yields)
240/// and of wasmtime's fuel. No provider in this crate implements it yet; the
241/// trait is here so the downstream shape and the machine family agree.
242pub trait MeteredMachine: Machine {
243    fn add_gas(&mut self, amount: u32);
244    fn run(&mut self, max_gas: u32) -> Result<RunResult>;
245}
246
247/// One definition a machine's environment holds.
248pub struct Def {
249    pub name: Box<str>,
250    pub kind: InnerKind,
251}
252
253/// Machines that can enumerate what they hold — the machine-side symbol
254/// table `quilt-lsp` wants to inject into projections (issue #193).
255pub trait IntrospectMachine: Machine {
256    fn defs(&self) -> Result<Vec<Def>>;
257}
258
259/**************************************************************/
260
261/// The degenerate machine: no live process, state as replayed history.
262///
263/// Definitions and effects are buffered; every feed writes
264/// `history + fragment` to a temp script and runs it through a fresh
265/// interpreter process ([`MachineSpec`]), so definitions accumulate across
266/// feeds even though nothing persists between processes. This recovers
267/// today's one-shot `↓` as the zero-infrastructure default — with the honest
268/// cost that *effects in the history re-run on every feed*, so it is only
269/// faithful for effect-free preludes. A persistent provider (REPL, Jupyter,
270/// DB — see the design doc) lifts that restriction behind the same trait.
271///
272/// A query's answer is the last non-empty stdout line of the run, produced by
273/// the spec's `print_wrap` spelling. A fragment whose run fails does not
274/// enter the history.
275///
276/// An [`Answer::stdout`] is what *this* feed printed: the replayed history
277/// prints again on every run, and that prefix is stripped — the output of
278/// a feed should not depend on which provider the language happens to have.
279/// (History whose output varies between runs defeats the stripping; that is
280/// the replay model's honest cost, not a framing bug.)
281pub struct ScriptMachine {
282    lang: Box<str>,
283    spec: MachineSpec,
284    /// Every successfully fed non-query fragment, in feed order.
285    history: Vec<Box<str>>,
286    /// What running the history alone printed, last time it was run — the
287    /// prefix every later run's stdout starts with.
288    replayed: Box<str>,
289}
290
291impl ScriptMachine {
292    #[must_use]
293    pub fn new(lang: &str, spec: MachineSpec) -> ScriptMachine {
294        ScriptMachine {
295            lang: lang.into(),
296            spec,
297            history: Vec::new(),
298            replayed: Box::default(),
299        }
300    }
301
302    /// `stdout` with the history's own output removed from the front.
303    fn fresh(&self, stdout: &str) -> Box<str> {
304        stdout
305            .strip_prefix(&*self.replayed)
306            .unwrap_or(stdout)
307            .into()
308    }
309
310    /// The replayed prelude plus `frag`, as one script.
311    fn script_with(&self, frag: &str) -> String {
312        let mut script = String::new();
313        for fed in &self.history {
314            script.push_str(fed);
315            script.push('\n');
316        }
317        script.push_str(frag);
318        script.push('\n');
319        script
320    }
321
322    /// Write `script` to a temp file and run it through the spec's
323    /// interpreter, capturing both streams. A non-zero exit is an error
324    /// carrying the captured stderr.
325    fn run(&self, script: &str) -> Result<(Box<str>, Box<str>)> {
326        let file = tempfile::Builder::new()
327            .suffix(&*self.spec.suffix)
328            .tempfile()
329            .into_diagnostic()?;
330        std::fs::write(file.path(), script).into_diagnostic()?;
331        let spec = &self.spec;
332        let output = interpreter(&spec.program, &spec.args, &spec.env, spec.clear_env)
333            .arg(file.path())
334            .output()
335            .into_diagnostic()
336            .wrap_err_with(|| format!("failed to run {:?}", self.spec.program))?;
337        let stdout: Box<str> = String::from_utf8_lossy(&output.stdout).into();
338        let stderr: Box<str> = String::from_utf8_lossy(&output.stderr).into();
339        if !output.status.success() {
340            // A checker's rejection is its output, not a crash: Lean reports
341            // errors on stdout and leaves stderr empty.
342            bail!(
343                "{} machine: {:?} failed with {}:\n{stdout}{stderr}",
344                self.lang,
345                self.spec.program,
346                output.status
347            );
348        }
349        Ok((stdout, stderr))
350    }
351}
352
353impl ScriptMachine {
354    /// Run `history + wrapped` and read the last non-empty stdout line as
355    /// the answered literal — the shared shape of the value and typing
356    /// queries.
357    fn query(&self, wrapped: &str) -> Result<Answer> {
358        let (stdout, stderr) = self.run(&self.script_with(wrapped))?;
359        let value = stdout
360            .lines()
361            .rev()
362            .find(|line| !line.trim().is_empty())
363            .map(|line| Box::from(line.trim()));
364        Ok(Answer {
365            value,
366            name: None,
367            stdout: self.fresh(&stdout),
368            stderr,
369        })
370    }
371}
372
373impl ScriptMachine {
374    /// The raw-text door on the concrete provider (this machine's wire *is*
375    /// text). Callers holding a term go through [`Machine::feed`]; callers
376    /// holding user-typed source go through
377    /// [`Multi::feed_on`](crate::multi::Multi::feed_on), which parses first.
378    pub fn feed_str(&mut self, kind: InnerKind, src: &str) -> Result<Answer> {
379        if kind == InnerKind::Expr {
380            self.query(&self.spec.print_wrap.replace("{}", src))
381        } else {
382            let (stdout, stderr) = self.run(&self.script_with(src))?;
383            let fresh = self.fresh(&stdout);
384            self.history.push(src.into());
385            self.replayed = stdout;
386            Ok(Answer {
387                value: None,
388                name: None,
389                stdout: fresh,
390                stderr,
391            })
392        }
393    }
394
395    /// Raw-text twin of [`Machine::type_of`].
396    pub fn type_of_str(&mut self, expr: &str) -> Result<Answer> {
397        let Some(wrap) = &self.spec.type_wrap else {
398            bail!(
399                "the {} machine has no typing judgment registered (no type_wrap in its spec)",
400                self.lang
401            )
402        };
403        self.query(&wrap.replace("{}", expr))
404    }
405}
406
407impl Machine for ScriptMachine {
408    fn lang(&self) -> &str {
409        &self.lang
410    }
411
412    fn identity(&self) -> Option<&str> {
413        self.spec.identity.as_deref()
414    }
415
416    fn feed(&mut self, kind: InnerKind, term: &QTerm) -> Result<Answer> {
417        self.feed_str(kind, term.coparse().trim())
418    }
419
420    fn type_of(&mut self, term: &QTerm) -> Result<Answer> {
421        self.type_of_str(term.coparse().trim())
422    }
423}
424
425/// A [`ScriptMachine`]'s whole state is its history, so snapshots are exact
426/// and free: the replay model's one honest advantage over a live process.
427impl ForkMachine for ScriptMachine {
428    /// State is history, so a fork is a copy of it.
429    fn fork(&self) -> Result<Box<dyn ForkMachine>> {
430        Ok(Box::new(ScriptMachine {
431            lang: self.lang.clone(),
432            spec: self.spec.clone(),
433            history: self.history.clone(),
434            replayed: self.replayed.clone(),
435        }))
436    }
437}
438
439impl SnapshotMachine for ScriptMachine {
440    fn snapshot(&self) -> Result<Snapshot> {
441        Ok(Snapshot(
442            postcard::to_stdvec(&self.history).into_diagnostic()?.into(),
443        ))
444    }
445
446    fn restore(&mut self, snapshot: &Snapshot) -> Result<()> {
447        self.history = postcard::from_bytes(&snapshot.0).into_diagnostic()?;
448        Ok(())
449    }
450}
451
452/**************************************************************/
453
454/// What a [`ReplMachine`] needs to know about a language: how to start its
455/// interactive interpreter, how to spell a value query, and how to spell
456/// "print exactly this text" — the sentinel that marks where one feed's
457/// output ends.
458///
459/// Declared per language via
460/// [`Language::repl_spec`](crate::lang::Language::repl_spec), preferred over
461/// [`machine_spec`](crate::lang::Language::machine_spec) when both exist.
462#[derive(Debug, Clone)]
463pub struct ReplSpec {
464    /// The interpreter to run and keep alive, e.g. `bash`.
465    pub program: Box<str>,
466    pub args: Box<[Box<str>]>,
467    /// The spelling of "print the value of this expression as a literal",
468    /// with `{}` standing for the expression — for the shells,
469    /// `echo $(( {} ))` (a shell query is an arithmetic expression).
470    pub print_wrap: Box<str>,
471    /// The spelling of "print exactly this text on its own line", with `{}`
472    /// standing for the text. Fed after every fragment with a fresh sentinel;
473    /// the machine reads output until the sentinel comes back, which is how
474    /// one feed's output is separated from the next without any framing
475    /// support from the interpreter.
476    ///
477    /// The protocol has one more bit: an interpreter that can tell the
478    /// fragment *failed* echoes the sentinel followed by ` !` instead, and
479    /// the feed is an error carrying what stderr said — the same contract
480    /// the replay machine gets from a non-zero exit. The shells spell this
481    /// off `$?`; the python and node kernels off the exception they caught.
482    pub echo_wrap: Box<str>,
483    /// Environment variables set for the interpreter (overriding inherited
484    /// values); see [`MachineSpec::env`].
485    pub env: Box<[(Box<str>, Box<str>)]>,
486    /// The typing-judgment spelling; see [`MachineSpec::type_wrap`].
487    pub type_wrap: Option<Box<str>>,
488    /// The spelling of "print exactly this text on its own line **on
489    /// stderr**", with `{}` standing for the text — `echo {} >&2` for the
490    /// shells. When present, every feed is framed on both streams: the
491    /// machine reads stderr up to the sentinel too, so an [`Answer::stderr`]
492    /// is exactly what *this* feed said rather than whatever had arrived by
493    /// the time stdout's sentinel did (a traceback's last lines used to be
494    /// a race). `None` keeps the best-effort drain, for interpreters with
495    /// no way to echo to stderr (`sqlite3`).
496    pub echo_err_wrap: Option<Box<str>>,
497    /// Start the interpreter with an empty environment; see
498    /// [`MachineSpec::clear_env`].
499    pub clear_env: bool,
500    /// What this machine is, when the spec knows exactly; see
501    /// [`MachineSpec::identity`].
502    pub identity: Option<Box<str>>,
503}
504
505/// The interpreter a spec names, with the environment it asks for: the
506/// caller's plus `env`, or — with `clear_env` — `env` alone.
507fn interpreter(
508    program: &str,
509    args: &[Box<str>],
510    env: &[(Box<str>, Box<str>)],
511    clear_env: bool,
512) -> Command {
513    let mut command = Command::new(program);
514    command.args(args.iter().map(AsRef::<str>::as_ref));
515    if clear_env {
516        command.env_clear();
517    }
518    command.envs(env.iter().map(|(k, v)| (&**k, &**v)));
519    command
520}
521
522/// How long a [`ReplMachine`] waits for a feed's sentinel before declaring
523/// the interpreter hung.
524const REPL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
525
526/// A persistent machine: one long-lived interpreter process, fed fragments
527/// on stdin. State is real process state — definitions persist because the
528/// process does — so, unlike [`ScriptMachine`], effects run exactly once and
529/// nothing is replayed.
530///
531/// The wire protocol is the least an interactive interpreter can offer:
532/// write the fragment, write an `echo` of a fresh sentinel, read stdout
533/// until the sentinel comes back. An interpreter that dies (or never echoes
534/// within [`REPL_TIMEOUT`]) turns the feed into an error carrying whatever
535/// stderr said. This is the phase-3 provider from `docs/design/machines.md`;
536/// it fits any interpreter whose input is a statement stream (the shells,
537/// `sqlite3`), while block-structured REPLs (python's `...` continuations)
538/// need the richer per-language protocols that come later.
539pub struct ReplMachine {
540    lang: Box<str>,
541    spec: ReplSpec,
542    child: std::process::Child,
543    stdin: std::process::ChildStdin,
544    /// Lines the reader thread has pulled off the interpreter's stdout.
545    stdout: std::sync::mpsc::Receiver<String>,
546    /// Lines the other reader thread has pulled off its stderr.
547    stderr: std::sync::mpsc::Receiver<String>,
548    /// Feed counter, salting the sentinel.
549    feeds: usize,
550}
551
552impl ReplMachine {
553    /// Start the interpreter and attach the stream readers.
554    pub fn spawn(lang: &str, spec: ReplSpec) -> Result<ReplMachine> {
555        use std::io::{BufRead as _, BufReader};
556
557        let mut child = interpreter(&spec.program, &spec.args, &spec.env, spec.clear_env)
558            .stdin(std::process::Stdio::piped())
559            .stdout(std::process::Stdio::piped())
560            .stderr(std::process::Stdio::piped())
561            .spawn()
562            .into_diagnostic()
563            .wrap_err_with(|| format!("failed to start {:?}", spec.program))?;
564        let stdin = child.stdin.take().expect("stdin was piped");
565        let stdout_pipe = child.stdout.take().expect("stdout was piped");
566        let stderr_pipe = child.stderr.take().expect("stderr was piped");
567
568        // One reader thread per stream, each feeding a channel of lines.
569        // Lines are read as bytes and converted lossily: an interpreter that
570        // writes a byte sequence that is not UTF-8 (macOS's bash 3.2 does,
571        // for a multibyte character right after a `$var`) must not end the
572        // stream — `lines()` would, and the machine would then look dead.
573        let lines_of = |pipe: Box<dyn std::io::Read + Send>| {
574            let (tx, rx) = std::sync::mpsc::channel();
575            std::thread::spawn(move || {
576                let mut reader = BufReader::new(pipe);
577                let mut buf = Vec::new();
578                loop {
579                    buf.clear();
580                    match reader.read_until(b'\n', &mut buf) {
581                        Ok(0) | Err(_) => break,
582                        Ok(_) => {}
583                    }
584                    if buf.last() == Some(&b'\n') {
585                        buf.pop();
586                        if buf.last() == Some(&b'\r') {
587                            buf.pop();
588                        }
589                    }
590                    if tx.send(String::from_utf8_lossy(&buf).into_owned()).is_err() {
591                        break;
592                    }
593                }
594            });
595            rx
596        };
597        let stdout = lines_of(Box::new(stdout_pipe));
598        let stderr = lines_of(Box::new(stderr_pipe));
599
600        Ok(ReplMachine {
601            lang: lang.into(),
602            spec,
603            child,
604            stdin,
605            stdout,
606            stderr,
607            feeds: 0,
608        })
609    }
610
611    /// Take whatever stderr has said so far — the best-effort answer, for a
612    /// spec with no stderr echo, and for reporting a dead interpreter.
613    fn drain_stderr(&self) -> Box<str> {
614        let mut out = String::new();
615        while let Ok(line) = self.stderr.try_recv() {
616            out.push_str(&line);
617            out.push('\n');
618        }
619        out.into()
620    }
621
622    /// Read stderr up to this feed's sentinel — exact, when the spec can
623    /// echo to stderr.
624    fn stderr_until(&self, sentinel: &str) -> Result<Box<str>> {
625        use std::sync::mpsc::RecvTimeoutError;
626        let mut out = String::new();
627        loop {
628            match self.stderr.recv_timeout(REPL_TIMEOUT) {
629                Ok(line) if line.trim() == sentinel => return Ok(out.into()),
630                Ok(line) => {
631                    out.push_str(&line);
632                    out.push('\n');
633                }
634                Err(RecvTimeoutError::Timeout) => bail!(
635                    "{} machine: {:?} did not echo on stderr within {REPL_TIMEOUT:?}",
636                    self.lang,
637                    self.spec.program
638                ),
639                Err(RecvTimeoutError::Disconnected) => bail!(
640                    "{} machine: {:?} exited mid-feed:\n{out}",
641                    self.lang,
642                    self.spec.program
643                ),
644            }
645        }
646    }
647}
648
649impl ReplMachine {
650    /// One sentinel-framed exchange: write `payload`, read until the
651    /// sentinel, answer with the collected output (`value` from the last
652    /// non-empty line when `collect_value`).
653    fn exchange(&mut self, payload: &str, collect_value: bool) -> Result<Answer> {
654        use std::io::Write as _;
655        use std::sync::mpsc::RecvTimeoutError;
656
657        self.feeds += 1;
658        let sentinel = format!("__QUILT_REPL_DONE_{}__", self.feeds);
659        let mut input = format!(
660            "{payload}\n{}\n",
661            self.spec.echo_wrap.replace("{}", &sentinel)
662        );
663        if let Some(err_wrap) = &self.spec.echo_err_wrap {
664            input.push_str(&err_wrap.replace("{}", &sentinel));
665            input.push('\n');
666        }
667        if let Err(e) = self
668            .stdin
669            .write_all(input.as_bytes())
670            .and_then(|()| self.stdin.flush())
671        {
672            bail!(
673                "{} machine: {:?} is gone ({e}):\n{}",
674                self.lang,
675                self.spec.program,
676                self.drain_stderr()
677            );
678        }
679
680        let rejected = format!("{sentinel} !");
681        let mut failed = false;
682        let mut lines = Vec::new();
683        loop {
684            match self.stdout.recv_timeout(REPL_TIMEOUT) {
685                Ok(line) if line.trim() == sentinel => break,
686                Ok(line) if line.trim() == rejected => {
687                    failed = true;
688                    break;
689                }
690                Ok(line) => lines.push(line),
691                Err(RecvTimeoutError::Timeout) => bail!(
692                    "{} machine: {:?} did not answer within {REPL_TIMEOUT:?}",
693                    self.lang,
694                    self.spec.program
695                ),
696                Err(RecvTimeoutError::Disconnected) => bail!(
697                    "{} machine: {:?} exited mid-feed:\n{}",
698                    self.lang,
699                    self.spec.program,
700                    self.drain_stderr()
701                ),
702            }
703        }
704
705        let value = collect_value
706            .then(|| {
707                lines
708                    .iter()
709                    .rev()
710                    .find(|line| !line.trim().is_empty())
711                    .map(|line| Box::from(line.trim()))
712            })
713            .flatten();
714        let stderr = if self.spec.echo_err_wrap.is_some() {
715            self.stderr_until(&sentinel)?
716        } else {
717            self.drain_stderr()
718        };
719        if failed {
720            bail!(
721                "{} machine: {:?} rejected the fragment:\n{stderr}",
722                self.lang,
723                self.spec.program
724            );
725        }
726        Ok(Answer {
727            value,
728            name: None,
729            stdout: lines.join("\n").into(),
730            stderr,
731        })
732    }
733}
734
735impl ReplMachine {
736    /// The raw-text door on the concrete provider; see
737    /// [`ScriptMachine::feed_str`] for who belongs at which door.
738    pub fn feed_str(&mut self, kind: InnerKind, src: &str) -> Result<Answer> {
739        if kind == InnerKind::Expr {
740            let payload = self.spec.print_wrap.replace("{}", src);
741            self.exchange(&payload, true)
742        } else {
743            self.exchange(src, false)
744        }
745    }
746
747    /// Raw-text twin of [`Machine::type_of`].
748    pub fn type_of_str(&mut self, expr: &str) -> Result<Answer> {
749        let Some(wrap) = &self.spec.type_wrap else {
750            bail!(
751                "the {} machine has no typing judgment registered (no type_wrap in its spec)",
752                self.lang
753            )
754        };
755        let payload = wrap.replace("{}", expr);
756        self.exchange(&payload, true)
757    }
758}
759
760impl Machine for ReplMachine {
761    fn lang(&self) -> &str {
762        &self.lang
763    }
764
765    fn identity(&self) -> Option<&str> {
766        self.spec.identity.as_deref()
767    }
768
769    fn feed(&mut self, kind: InnerKind, term: &QTerm) -> Result<Answer> {
770        self.feed_str(kind, term.coparse().trim())
771    }
772
773    fn type_of(&mut self, term: &QTerm) -> Result<Answer> {
774        self.type_of_str(term.coparse().trim())
775    }
776}
777
778impl Drop for ReplMachine {
779    fn drop(&mut self) {
780        let _ = self.child.kill();
781        let _ = self.child.wait();
782    }
783}
784
785/**************************************************************/
786
787/// Every language quilt knows how to run as a machine, in table order.
788///
789/// The table is *data* — program names, print/echo wrappers, a suffix — and
790/// carries no parsing knowledge, which is why it lives here on the
791/// runtime-only path rather than behind the `parse` feature with the
792/// `Language` registry (issue #273). Three consumers read it and cannot
793/// disagree: [`Language::machine_spec`](crate::lang::Language::machine_spec)
794/// and [`repl_spec`](crate::lang::Language::repl_spec) delegate into it, the
795/// conformance battery drives the machine those return, and [`qspawn`] — what
796/// `lang⟨M⟩` expands to in a Rust ground program, which has no registry at
797/// all — reads it directly.
798pub const REGISTERED_SPECS: &[&str] = &[
799    "lean",
800    "lean4",
801    "python",
802    "py",
803    "typescript",
804    "ts",
805    "sql",
806    "bash",
807    "zsh",
808    "html",
809];
810
811/// Whether `lang` has a registered machine — native, persistent or replay.
812///
813/// A host's `spawn_str` asks before it spells `lang⟨M⟩`, so a machine no
814/// provider backs is a diagnostic at expansion time — pointing at the glyph in
815/// the source — rather than a failure inside generated code.
816#[must_use]
817pub fn has_spec(lang: &str) -> bool {
818    native_machine(lang).is_some() || repl_spec(lang).is_some() || script_spec(lang).is_some()
819}
820
821/// The in-process machine registered for `lang`, if any: no interpreter,
822/// state held as a term. HTML's is the [`HtmlMachine`] — a document whose
823/// definitions are its ids. Preferred over both subprocess providers by
824/// [`qspawn`] and [`spawn_machine`], since it is the only one that can
825/// answer with the same term it was fed.
826#[must_use]
827pub fn native_machine(lang: &str) -> Option<Box<dyn Machine>> {
828    match lang {
829        "html" => Some(Box::new(HtmlMachine::default())),
830        _ => None,
831    }
832}
833
834/// The Python kernel behind the persistent python machine: a stdin loop
835/// exec-ing each sentinel-framed chunk in one namespace. Framing is the
836/// [`ReplSpec`]'s: a chunk ends at the line `echo_wrap` spells, so the
837/// kernel matches that spelling (and `echo_err_wrap`'s) rather than parsing
838/// Python incrementally — which is what lets `def`/`if`/`else` blocks cross
839/// lines without the `...` continuation protocol a real REPL needs. The
840/// quilt runtime is pre-imported when it is built, the way quilt-python's
841/// `run()` pre-imports it into the namespace it returns.
842const PYTHON_KERNEL: &str = r#"
843import re, sys, traceback
844ns = {"__name__": "__quilt__"}
845try:
846    exec("from quilt import *", ns)
847except ImportError:
848    pass
849mark = re.compile(r'^print\("(__QUILT_REPL_DONE_\d+__)"(, file=sys\.stderr)?\)$')
850buf = []
851for line in sys.stdin:
852    line = line.rstrip("\n")
853    m = mark.match(line)
854    if m is None:
855        buf.append(line)
856        continue
857    if m.group(2):
858        sys.stderr.write(m.group(1) + "\n")
859        sys.stderr.flush()
860        continue
861    src = "\n".join(buf) + "\n"
862    buf = []
863    failed = ""
864    try:
865        exec(compile(src, "<quilt>", "exec"), ns)
866    except Exception:
867        traceback.print_exc()
868        failed = " !"
869    sys.stdout.flush()
870    sys.stderr.flush()
871    print(m.group(1) + failed)
872    sys.stdout.flush()
873"#;
874
875/// The Node kernel behind the persistent typescript machine, the twin of
876/// [`PYTHON_KERNEL`]: one `vm` context kept for the life of the process, so
877/// a top-level `const` in one chunk is visible to the next (the REPL's
878/// semantics). Type annotations are stripped on a syntax error, as the Node
879/// runtime's `↓` does. The quilt-wasm runtime's builders are made globals of
880/// the context when the package is built (`bin/build-ts`), so an expanded
881/// `html↖…↗` in a chunk resolves without an `import` — which a `vm` script
882/// could not have.
883const TYPESCRIPT_KERNEL: &str = r#"
884const vm = require("node:vm"), rl = require("node:readline"), mod = require("node:module");
885const ctx = vm.createContext(Object.assign(Object.create(globalThis), { require, console, process }));
886try { Object.assign(ctx, require(process.env.QUILT_WASM_PKG)); } catch {}
887// A chunk's top-level errors are caught by `run` below, but a *rejected*
888// promise it returns (an unawaited `fetch`, say) surfaces later, off this
889// process's default handler — which is fatal (Node 15+) and would take the
890// whole kernel, and every cell still to come in this session, down with it.
891// Logging it where a synchronous throw already goes keeps one bad promise
892// from being worse than a bug a `try`/`catch` would have caught.
893process.on("uncaughtException", (e) => console.error(e && e.stack ? e.stack : String(e)));
894process.on("unhandledRejection", (e) => console.error(e && e.stack ? e.stack : String(e)));
895const mark = /^console\.(log|error)\("(__QUILT_REPL_DONE_\d+__)"\)$/;
896let buf = [];
897function run(src) {
898  try {
899    return vm.runInContext(src, ctx, { filename: "<quilt>" });
900  } catch (e) {
901    if (e?.name !== "SyntaxError" || typeof mod.stripTypeScriptTypes !== "function") throw e;
902    let stripped;
903    try { stripped = mod.stripTypeScriptTypes(src, { mode: "strip" }); } catch { throw e; }
904    return vm.runInContext(stripped, ctx, { filename: "<quilt>" });
905  }
906}
907rl.createInterface({ input: process.stdin, terminal: false }).on("line", (line) => {
908  const m = mark.exec(line);
909  if (!m) { buf.push(line); return; }
910  if (m[1] === "error") { console.error(m[2]); return; }
911  const src = buf.join("\n");
912  buf = [];
913  let failed = "";
914  try { run(src); } catch (e) { console.error(e && e.stack ? e.stack : String(e)); failed = " !"; }
915  console.log(m[2] + failed);
916});
917"#;
918
919/// The persistent-REPL spec registered for `lang`, if any. See
920/// [`REGISTERED_SPECS`]; the per-provider reasoning lives on the
921/// [`Language::repl_spec`](crate::lang::Language::repl_spec) impl that
922/// delegates here.
923#[must_use]
924pub fn repl_spec(lang: &str) -> Option<ReplSpec> {
925    let (program, args, print_wrap, echo_wrap, echo_err_wrap, type_wrap): (
926        _,
927        &[&str],
928        _,
929        _,
930        Option<&str>,
931        _,
932    ) = match lang {
933        // `-batch` so sqlite3 reads stdin without its interactive banner, and
934        // `-bail` so a failed statement is an error rather than silence.
935        "sql" => (
936            "sqlite3",
937            &["-batch", "-bail"],
938            "SELECT {};",
939            "SELECT '{}';",
940            None,
941            Some("SELECT typeof({});"),
942        ),
943        // A shell query is an arithmetic expression, so that is what "print
944        // the value of this expression" means for both shells. The echo
945        // reads `$?` first: a fragment whose last command failed is
946        // rejected, which is what a non-zero status means to a shell.
947        "bash" => (
948            "bash",
949            &[],
950            "echo $(( {} ))",
951            "[ $? -eq 0 ] && echo {} || echo '{} !'",
952            Some("echo {} >&2"),
953            None,
954        ),
955        "zsh" => (
956            "zsh",
957            &[],
958            "echo $(( {} ))",
959            "[ $? -eq 0 ] && echo {} || echo '{} !'",
960            Some("echo {} >&2"),
961            None,
962        ),
963        // `-u`: unbuffered, so a chunk's output precedes its sentinel. The
964        // echo spellings are the ones the kernel's regex matches.
965        "python" | "py" => (
966            "python3",
967            &["-u", "-c", PYTHON_KERNEL],
968            "print(repr({}))",
969            "print(\"{}\")",
970            Some("print(\"{}\", file=sys.stderr)"),
971            Some("print(type({}).__name__)"),
972        ),
973        // `--no-warnings`: stripping types is experimental in some Node
974        // versions, and the warning would land in the first feed's stderr.
975        "typescript" | "ts" => (
976            "node",
977            &["--no-warnings", "-e", TYPESCRIPT_KERNEL],
978            "console.log(JSON.stringify({}))",
979            "console.log(\"{}\")",
980            Some("console.error(\"{}\")"),
981            Some("console.log(typeof ({}))"),
982        ),
983        _ => return None,
984    };
985    let env: Box<[(Box<str>, Box<str>)]> = match lang {
986        // The `PYTHONPATH` that makes `from quilt import *` resolve — the
987        // same path the script spec and `reduce_py` teach.
988        "python" | "py" => Box::new([(
989            "PYTHONPATH".into(),
990            concat!(env!("CARGO_MANIFEST_DIR"), "/../quilt-python").into(),
991        )]),
992        // Where the kernel finds the quilt-wasm runtime, when built; and no
993        // ANSI colour in `console.log` output, whatever the caller's
994        // terminal says (`FORCE_COLOR` outranks `NO_COLOR` in Node).
995        "typescript" | "ts" => Box::new([
996            (
997                "QUILT_WASM_PKG".into(),
998                concat!(
999                    env!("CARGO_MANIFEST_DIR"),
1000                    "/../quilt-wasm/pkg/quilt_wasm.js"
1001                )
1002                .into(),
1003            ),
1004            ("FORCE_COLOR".into(), "0".into()),
1005        ]),
1006        _ => Box::default(),
1007    };
1008    Some(ReplSpec {
1009        program: program.into(),
1010        args: args.iter().map(|a| Box::from(*a)).collect(),
1011        print_wrap: print_wrap.into(),
1012        echo_wrap: echo_wrap.into(),
1013        env,
1014        type_wrap: type_wrap.map(Box::from),
1015        echo_err_wrap: echo_err_wrap.map(Box::from),
1016        clear_env: false,
1017        identity: None,
1018    })
1019}
1020
1021/// The replay-script spec registered for `lang`, if any. See
1022/// [`REGISTERED_SPECS`].
1023#[must_use]
1024pub fn script_spec(lang: &str) -> Option<MachineSpec> {
1025    match lang {
1026        "python" | "py" => {
1027            let mut spec =
1028                MachineSpec::from_hashbang("#!/usr/bin/env python3", "print(repr({}))", ".py")?;
1029            // The `PYTHONPATH` that makes `from quilt import *` resolve — the
1030            // same path `reduce_py` teaches its one-shot script.
1031            spec.env = Box::new([(
1032                "PYTHONPATH".into(),
1033                concat!(env!("CARGO_MANIFEST_DIR"), "/../quilt-python").into(),
1034            )]);
1035            // The typing judgment: `type_of("21 + 21")` answers `int`.
1036            spec.type_wrap = Some("print(type({}).__name__)".into());
1037            Some(spec)
1038        }
1039        "typescript" | "ts" => MachineSpec::from_hashbang(
1040            "#!/usr/bin/env -S node --experimental-strip-types",
1041            "console.log(JSON.stringify({}))",
1042            ".ts",
1043        ),
1044        // A proof language: feeding a `theorem` checks it, and a rejected proof
1045        // is a failed feed that stays out of the history. Lean is effect-free,
1046        // so replay is exact here rather than the degenerate case it is for an
1047        // interpreter, and `#check` is the typing judgment.
1048        "lean" | "lean4" => Some(MachineSpec {
1049            program: "lean".into(),
1050            args: Box::default(),
1051            print_wrap: "#eval {}".into(),
1052            suffix: ".lean".into(),
1053            env: Box::default(),
1054            type_wrap: Some("#check {}".into()),
1055            clear_env: false,
1056            identity: None,
1057        }),
1058        _ => None,
1059    }
1060}
1061
1062/// Spawn a machine for `lang` from the registered table, preferring native,
1063/// then persistent, then replay — what `lang⟨M⟩` expands to in Rust
1064/// (issue #273).
1065///
1066/// The registry-driven [`spawn_machine`] is the same choice made through a
1067/// [`Language`](crate::lang::Language); this one needs no registry, so it is
1068/// available to a Rust ground program built runtime-only
1069/// (`default-features = false`), which is how expanded `.rs.quilt` files are
1070/// built.
1071pub fn qspawn(lang: &str) -> Result<Box<dyn Machine>> {
1072    if let Some(machine) = native_machine(lang) {
1073        return Ok(machine);
1074    }
1075    if let Some(spec) = repl_spec(lang) {
1076        return Ok(Box::new(ReplMachine::spawn(lang, spec)?));
1077    }
1078    if let Some(spec) = script_spec(lang) {
1079        return Ok(Box::new(ScriptMachine::new(lang, spec)));
1080    }
1081    bail!(
1082        "no machine is registered for {lang:?}; quilt knows: {}",
1083        REGISTERED_SPECS.join(", ")
1084    )
1085}
1086
1087/**************************************************************/
1088
1089/// Spawn the best machine a [`Language`](crate::lang::Language) declares: its
1090/// [`native_machine`](crate::lang::Language::native_machine) when it has
1091/// one, else the persistent [`ReplMachine`] when the language has a
1092/// [`repl_spec`](crate::lang::Language::repl_spec), else the replay-based
1093/// [`ScriptMachine`] from its
1094/// [`machine_spec`](crate::lang::Language::machine_spec), else an error.
1095/// Shared by [`Multi`](crate::multi::Multi) and the conformance battery, so
1096/// the machine a claim is verified against is the machine users get.
1097pub fn spawn_machine<L: crate::lang::Language + ?Sized>(
1098    lang_name: &str,
1099    lang: &L,
1100) -> Result<Box<dyn Machine>> {
1101    if let Some(machine) = lang.native_machine() {
1102        return Ok(machine);
1103    }
1104    if let Some(spec) = lang.repl_spec() {
1105        return Ok(Box::new(ReplMachine::spawn(lang_name, spec)?));
1106    }
1107    if let Some(spec) = lang.machine_spec() {
1108        return Ok(Box::new(ScriptMachine::new(lang_name, spec)));
1109    }
1110    bail!("language {lang_name:?} has no machine: no native, repl or script provider registered")
1111}
1112
1113/**************************************************************/
1114
1115/// The pool of live default machines, one per language, spawned on first
1116/// use. [`Multi`](crate::multi::Multi) carries one so that successive
1117/// reduces in a run share definitions; `quilt run` will keep it warm for the
1118/// run's duration (phase 2).
1119#[derive(Default)]
1120pub struct Park {
1121    machines: BTreeMap<Box<str>, Box<dyn Machine>>,
1122}
1123
1124impl Park {
1125    #[must_use]
1126    pub fn contains(&self, lang: &str) -> bool {
1127        self.machines.contains_key(lang)
1128    }
1129
1130    /// Adopt `machine` as the default for `lang`, replacing any previous one.
1131    pub fn insert(&mut self, lang: &str, machine: Box<dyn Machine>) {
1132        self.machines.insert(lang.into(), machine);
1133    }
1134
1135    /// The default machine for `lang`, if one has been parked.
1136    pub fn get_mut(&mut self, lang: &str) -> Option<&mut (dyn Machine + 'static)> {
1137        self.machines.get_mut(lang).map(AsMut::as_mut)
1138    }
1139}
1140
1141/**************************************************************/
1142
1143#[cfg(test)]
1144mod tests {
1145    use super::*;
1146
1147    /// POSIX sh as a machine: definitions are assignments, queries are
1148    /// arithmetic. Hermetic on every dev platform, no language feature
1149    /// needed.
1150    fn sh_machine() -> ScriptMachine {
1151        ScriptMachine::new(
1152            "sh",
1153            MachineSpec {
1154                program: "sh".into(),
1155                args: Box::default(),
1156                print_wrap: "echo $(( {} ))".into(),
1157                suffix: ".sh".into(),
1158                env: Box::default(),
1159                type_wrap: None,
1160                clear_env: false,
1161                identity: None,
1162            },
1163        )
1164    }
1165
1166    #[test]
1167    fn definitions_accumulate_and_queries_answer() {
1168        let mut m = sh_machine();
1169        let fed = m.feed_str(InnerKind::Item, "x=5").unwrap();
1170        assert_eq!(fed.value, None);
1171        let ask = m.feed_str(InnerKind::Expr, "x + 2").unwrap();
1172        assert_eq!(ask.value.as_deref(), Some("7"));
1173        // The environment survives the query: ask again.
1174        let ask = m.feed_str(InnerKind::Expr, "x * x").unwrap();
1175        assert_eq!(ask.value.as_deref(), Some("25"));
1176    }
1177
1178    #[test]
1179    fn forks_start_equal_and_diverge() {
1180        let mut a = sh_machine();
1181        a.feed_str(InnerKind::Item, "x=5").unwrap();
1182        let mut b = a.fork().unwrap();
1183        // Neither sees what the other does next, and both stay alive.
1184        a.feed_str(InnerKind::Item, "x=6").unwrap();
1185        b.feed(InnerKind::Item, &crate::qterm::qleaf("code", "y=7"))
1186            .unwrap();
1187        assert_eq!(
1188            &*a.feed_str(InnerKind::Expr, "x").unwrap().value.unwrap(),
1189            "6"
1190        );
1191        let x = b.feed(InnerKind::Expr, &crate::qterm::qleaf("code", "x"));
1192        assert_eq!(x.unwrap().value.as_deref(), Some("5"));
1193    }
1194
1195    #[test]
1196    fn lean_judges_what_it_is_fed() {
1197        let has_lean = Command::new("lean").arg("--version").output().is_ok();
1198        if !has_lean {
1199            return;
1200        }
1201        let mut m = ScriptMachine::new("lean", script_spec("lean").unwrap());
1202        m.feed_str(InnerKind::Item, "def twice (n : Nat) := n + n")
1203            .unwrap();
1204        m.feed_str(InnerKind::Item, "theorem t : twice 2 = 4 := rfl")
1205            .unwrap();
1206        let v = m.feed_str(InnerKind::Expr, "twice 21").unwrap();
1207        assert_eq!(v.value.as_deref(), Some("42"));
1208        let ty = m.type_of_str("twice").unwrap();
1209        assert_eq!(ty.value.as_deref(), Some("twice (n : Nat) : Nat"));
1210
1211        // A false theorem is rejected, says why, and stays out of the history.
1212        let no = m.feed_str(InnerKind::Item, "theorem no : 1 = 2 := rfl");
1213        assert!(no.unwrap_err().to_string().contains("failed"));
1214        let v = m.feed_str(InnerKind::Expr, "twice 1").unwrap();
1215        assert_eq!(v.value.as_deref(), Some("2"));
1216    }
1217
1218    #[test]
1219    fn machines_are_isolated() {
1220        let mut a = sh_machine();
1221        let mut b = sh_machine();
1222        a.feed_str(InnerKind::Item, "x=1").unwrap();
1223        b.feed_str(InnerKind::Item, "x=100").unwrap();
1224        assert_eq!(
1225            a.feed_str(InnerKind::Expr, "x + 1")
1226                .unwrap()
1227                .value
1228                .as_deref(),
1229            Some("2")
1230        );
1231        assert_eq!(
1232            b.feed_str(InnerKind::Expr, "x + 1")
1233                .unwrap()
1234                .value
1235                .as_deref(),
1236            Some("101")
1237        );
1238    }
1239
1240    #[test]
1241    fn failed_feeds_stay_out_of_history() {
1242        let mut m = sh_machine();
1243        m.feed_str(InnerKind::Item, "x=5").unwrap();
1244        assert!(m.feed_str(InnerKind::Stmt, "exit 3").is_err());
1245        // The failed fragment was not recorded, so the machine still answers.
1246        let ask = m.feed_str(InnerKind::Expr, "x + 2").unwrap();
1247        assert_eq!(ask.value.as_deref(), Some("7"));
1248    }
1249
1250    /// A query does not re-print what the history printed: the replayed
1251    /// prefix is stripped, so stdout is this feed's own.
1252    #[test]
1253    fn replayed_output_is_not_reported_again() {
1254        let mut m = sh_machine();
1255        let fed = m.feed_str(InnerKind::Stmt, "echo hi").unwrap();
1256        assert_eq!(&*fed.stdout, "hi\n");
1257        let ask = m.feed_str(InnerKind::Expr, "1 + 1").unwrap();
1258        assert_eq!(ask.value.as_deref(), Some("2"));
1259        assert_eq!(&*ask.stdout, "2\n", "got: {:?}", ask.stdout);
1260        let fed = m.feed_str(InnerKind::Stmt, "echo again").unwrap();
1261        assert_eq!(&*fed.stdout, "again\n");
1262    }
1263
1264    /// POSIX sh as a *persistent* machine, for the [`ReplMachine`] tests.
1265    fn sh_repl() -> ReplMachine {
1266        ReplMachine::spawn(
1267            "sh",
1268            ReplSpec {
1269                program: "sh".into(),
1270                args: Box::default(),
1271                print_wrap: "echo $(( {} ))".into(),
1272                echo_wrap: "echo {}".into(),
1273                env: Box::default(),
1274                type_wrap: None,
1275                echo_err_wrap: Some("echo {} >&2".into()),
1276                clear_env: false,
1277                identity: None,
1278            },
1279        )
1280        .unwrap()
1281    }
1282
1283    /// With a stderr echo, what a feed said on stderr is exactly this feed's
1284    /// — read up to the sentinel, not whatever had arrived.
1285    #[test]
1286    fn stderr_is_framed_per_feed() {
1287        let mut m = sh_repl();
1288        let a = m.feed_str(InnerKind::Stmt, "echo oops >&2").unwrap();
1289        assert_eq!(&*a.stderr, "oops\n");
1290        let b = m.feed_str(InnerKind::Expr, "1 + 1").unwrap();
1291        assert_eq!(&*b.stderr, "", "the next feed starts clean");
1292    }
1293
1294    /// The registered shells report a failed fragment as an error — the
1295    /// sentinel's one extra bit — and stay usable afterwards.
1296    #[test]
1297    fn bash_rejects_a_failing_fragment() {
1298        let mut m = ReplMachine::spawn("bash", repl_spec("bash").unwrap()).unwrap();
1299        m.feed_str(InnerKind::Item, "x=5").unwrap();
1300        let err = m.feed_str(InnerKind::Stmt, "false").unwrap_err();
1301        assert!(err.to_string().contains("rejected"), "{err}");
1302        let err = m
1303            .feed_str(InnerKind::Stmt, "echo boom >&2; exit_code_of_nothing")
1304            .unwrap_err();
1305        assert!(err.to_string().contains("boom"), "carries stderr: {err}");
1306        assert_eq!(
1307            m.feed_str(InnerKind::Expr, "x + 1")
1308                .unwrap()
1309                .value
1310                .as_deref(),
1311            Some("6")
1312        );
1313    }
1314
1315    /// The python kernel: one process, definitions persist, blocks cross
1316    /// lines, an exception is reported on stderr and leaves the kernel
1317    /// usable, and effects run exactly once.
1318    #[test]
1319    fn python_kernel_is_a_persistent_machine() {
1320        let mut m = ReplMachine::spawn("py", repl_spec("py").unwrap()).unwrap();
1321        let fed = m.feed_str(InnerKind::Stmt, "print('once')").unwrap();
1322        assert_eq!(&*fed.stdout, "once");
1323        m.feed_str(
1324            InnerKind::Item,
1325            "def f(x):\n    if x > 1:\n        return x * 2\n    else:\n        return x",
1326        )
1327        .unwrap();
1328        let ask = m.feed_str(InnerKind::Expr, "f(21)").unwrap();
1329        assert_eq!(ask.value.as_deref(), Some("42"));
1330        assert!(!ask.stdout.contains("once"), "no replay: {:?}", ask.stdout);
1331        let bad = m.feed_str(InnerKind::Expr, "undefined_name").unwrap_err();
1332        assert!(bad.to_string().contains("NameError"), "{bad}");
1333        let ask = m.feed_str(InnerKind::Expr, "f(1)").unwrap();
1334        assert_eq!(ask.value.as_deref(), Some("1"), "still alive");
1335        assert_eq!(
1336            m.type_of_str("f(21)").unwrap().value.as_deref(),
1337            Some("int")
1338        );
1339    }
1340
1341    /// The node kernel, held to the same shape.
1342    #[test]
1343    fn typescript_kernel_is_a_persistent_machine() {
1344        let mut m = ReplMachine::spawn("ts", repl_spec("ts").unwrap()).unwrap();
1345        m.feed_str(InnerKind::Item, "const y: number = 40").unwrap();
1346        let ask = m.feed_str(InnerKind::Expr, "y + 2").unwrap();
1347        assert_eq!(ask.value.as_deref(), Some("42"));
1348        let bad = m.feed_str(InnerKind::Expr, "nope").unwrap_err();
1349        assert!(bad.to_string().contains("ReferenceError"), "{bad}");
1350        let ask = m.feed_str(InnerKind::Expr, "[y, 'a']").unwrap();
1351        assert_eq!(ask.value.as_deref(), Some("[40,\"a\"]"));
1352        assert_eq!(m.type_of_str("y").unwrap().value.as_deref(), Some("number"));
1353    }
1354
1355    /// The native provider wins the spawn order, and answers with the term
1356    /// it was fed.
1357    #[test]
1358    fn html_is_native() {
1359        let mut m = qspawn("html").unwrap();
1360        assert_eq!(m.lang(), "html");
1361        let ask = m.feed(InnerKind::Expr, &leaf("text", "hi")).unwrap();
1362        assert_eq!(ask.value.as_deref(), Some("hi"));
1363        assert!(has_spec("html"));
1364    }
1365
1366    #[test]
1367    fn repl_state_persists_without_replay() {
1368        let mut m = sh_repl();
1369        let fed = m.feed_str(InnerKind::Stmt, "echo hi").unwrap();
1370        assert!(fed.stdout.contains("hi"));
1371        m.feed_str(InnerKind::Item, "x=5").unwrap();
1372        let ask = m.feed_str(InnerKind::Expr, "x + 2").unwrap();
1373        assert_eq!(ask.value.as_deref(), Some("7"));
1374        // The effect ran exactly once: the query's own output does not
1375        // re-print "hi" — a live process, not replayed history.
1376        assert!(!ask.stdout.contains("hi"), "got: {:?}", ask.stdout);
1377    }
1378
1379    #[test]
1380    fn a_dead_repl_is_an_error() {
1381        let mut m = sh_repl();
1382        assert!(m.feed_str(InnerKind::Stmt, "exit 0").is_err());
1383    }
1384
1385    /// A snapshot is the whole state of a script machine, so restore rolls
1386    /// definitions back exactly.
1387    #[test]
1388    fn snapshots_roll_definitions_back() {
1389        let mut m = sh_machine();
1390        m.feed_str(InnerKind::Item, "x=5").unwrap();
1391        let snap = m.snapshot().unwrap();
1392        m.feed_str(InnerKind::Item, "x=9").unwrap();
1393        assert_eq!(
1394            m.feed_str(InnerKind::Expr, "x").unwrap().value.as_deref(),
1395            Some("9")
1396        );
1397        m.restore(&snap).unwrap();
1398        assert_eq!(
1399            m.feed_str(InnerKind::Expr, "x").unwrap().value.as_deref(),
1400            Some("5")
1401        );
1402    }
1403
1404    /// A machine without a `type_wrap` refuses the typing judgment with an
1405    /// actionable message rather than a broken query.
1406    #[test]
1407    fn no_type_wrap_is_an_honest_error() {
1408        let mut m = sh_machine();
1409        let err = m.type_of_str("1 + 1").unwrap_err();
1410        assert!(err.to_string().contains("typing judgment"), "got: {err}");
1411    }
1412
1413    /// The spec `PythonProvider` registers, exercised without the `parse`
1414    /// feature (the tuple is kept in sync by the `Multi`-level test in
1415    /// `multi.rs`, which goes through the provider).
1416    #[test]
1417    fn python_answers_its_own_literals() {
1418        let spec =
1419            MachineSpec::from_hashbang("#!/usr/bin/env python3", "print(repr({}))", ".py").unwrap();
1420        let mut m = ScriptMachine::new("py", spec);
1421        m.feed_str(InnerKind::Item, "def f(x):\n    return x * 2")
1422            .unwrap();
1423        assert_eq!(
1424            m.feed_str(InnerKind::Expr, "f(21)")
1425                .unwrap()
1426                .value
1427                .as_deref(),
1428            Some("42")
1429        );
1430        // repr() answers a *literal*: a string comes back quoted.
1431        assert_eq!(
1432            m.feed_str(InnerKind::Expr, "'ab' * 2")
1433                .unwrap()
1434                .value
1435                .as_deref(),
1436            Some("'abab'")
1437        );
1438    }
1439
1440    /// `clear_env` starts the interpreter with the spec's environment and
1441    /// nothing of the caller's; without it the caller's is inherited.
1442    #[test]
1443    fn a_cleared_environment_holds_only_what_the_spec_sets() {
1444        if std::env::var_os("HOME").is_none() {
1445            return;
1446        }
1447        let spec = |clear_env| ReplSpec {
1448            // By path: with no `PATH` there is nothing to look a name up in.
1449            program: "/bin/sh".into(),
1450            args: Box::default(),
1451            print_wrap: "echo $(( {} ))".into(),
1452            echo_wrap: "echo {}".into(),
1453            env: Box::new([("ONLY".into(), "set".into())]),
1454            type_wrap: None,
1455            echo_err_wrap: Some("echo {} >&2".into()),
1456            clear_env,
1457            identity: None,
1458        };
1459        let says = |clear_env| {
1460            let mut m = ReplMachine::spawn("sh", spec(clear_env)).unwrap();
1461            let a = m
1462                .feed_str(InnerKind::Stmt, "echo ${HOME:+home}:$ONLY")
1463                .unwrap();
1464            a.stdout.trim().to_string()
1465        };
1466        assert_eq!(says(false), "home:set");
1467        assert_eq!(says(true), ":set");
1468    }
1469
1470    /// A machine found on `PATH` doesn't claim to know which it is; one
1471    /// whose spec says so does.
1472    #[test]
1473    fn identity_is_none_unless_the_spec_knows() {
1474        assert_eq!(sh_repl().identity(), None);
1475        assert_eq!(sh_machine().identity(), None);
1476        let mut spec = sh_machine().spec.clone();
1477        spec.identity = Some("0123-sh".into());
1478        assert_eq!(ScriptMachine::new("sh", spec).identity(), Some("0123-sh"));
1479    }
1480
1481    /// The typing judgment answers the type's spelling, and sees the fed
1482    /// definitions like any other query.
1483    #[test]
1484    fn python_answers_types() {
1485        let spec = MachineSpec {
1486            type_wrap: Some("print(type({}).__name__)".into()),
1487            ..MachineSpec::from_hashbang("#!/usr/bin/env python3", "print(repr({}))", ".py")
1488                .unwrap()
1489        };
1490        let mut m = ScriptMachine::new("py", spec);
1491        assert_eq!(
1492            m.type_of_str("21 + 21").unwrap().value.as_deref(),
1493            Some("int")
1494        );
1495        m.feed_str(InnerKind::Item, "s = 'hi'").unwrap();
1496        assert_eq!(
1497            m.type_of_str("s * 2").unwrap().value.as_deref(),
1498            Some("str")
1499        );
1500    }
1501}