Skip to main content

yomi_core/
repl.rs

1//! The REPL core API (section 7.8 of `spec/host/07-repl.md`).
2//!
3//! A [`Repl`] runs expressions, statements, declarations and script lines on a **copy** of the script's environment. REPL
4//! declarations (`fn`, `struct`, `enum`, `import`, `identity`) and variables (`let`) exist only inside the `Repl`. The
5//! script's `Program` is not changed, and neither is the `Vm` unless [`Repl::apply`] is called.
6//!
7//! How it works: for each input, the `Repl` builds an extended program that adds a `<repl>` module (the REPL declarations
8//! and an `<input>` label that runs the input) to the script's program (which keeps the compiled sources), swaps it into a
9//! copy of the `Vm`, and runs it. REPL variables, and the local variables of a stop point entered with `:repl`, are held as
10//! variables of the `<repl>` module. Input runs on a further copy of the copy (`Core`). On a runtime error or
11//! [`Repl::abort`], that copy is simply discarded, returning to the state before the input.
12
13mod classify;
14#[cfg(test)]
15mod tests;
16mod types;
17
18use std::collections::HashSet;
19use std::sync::Arc;
20
21use crate::compile::compile_modules;
22use crate::compile::repl::{
23    DeclEntry, InputAst, REPL_MODULE, ReplCompile, ReplVar, VarKind, compile_repl,
24};
25use crate::diag::{DiagArg, DiagCode, Diagnostic, Severity};
26use crate::package::Package;
27use crate::program::{ProgRef, Program};
28use crate::registry::{CommandId, Kind, Registry};
29use crate::syntax::ast::{Pos, TypeDeclKind};
30use crate::syntax::parser::{
31    ANY_IDENTITY, IdentMap, parse_expr_line, scan_identities, scan_imports,
32};
33use crate::value::{Ty, Value};
34use crate::vm::InterruptHandle;
35use crate::vm::repl::{ApplyFail, ApplyTarget, start_module};
36use crate::vm::{Input, Variable, Vm, VmConfig, VmError, VmErrorKind, Yield};
37
38use classify::{Parsed, classify};
39pub use types::*;
40
41/// The copied environment, and the REPL declarations and variables.
42#[derive(Debug)]
43struct Core<'a> {
44    vm: Vm<'a>,
45    /// Things declared in the REPL (in declaration order).
46    decls: Vec<DeclEntry>,
47    /// REPL variables (the variables of the `<repl>` module that come after the variables of the script's modules).
48    vars: Vec<ReplVar>,
49}
50
51impl<'a> Core<'a> {
52    /// Copies the execution state (for trial runs that can be undone on failure).
53    fn fork(&self) -> Core<'a> {
54        Core {
55            vm: self.vm.fork(),
56            decls: self.decls.clone(),
57            vars: self.vars.clone(),
58        }
59    }
60}
61
62/// The input being run.
63#[derive(Debug)]
64struct Pending<'a> {
65    core: Core<'a>,
66    input_label: usize,
67    expr_ty: Option<Ty>,
68    lets: Vec<String>,
69    declared: Vec<Declared>,
70}
71
72/// A REPL.
73#[derive(Debug)]
74pub struct Repl<'a> {
75    registry: &'a Registry,
76    /// The script's program (before declarations are added).
77    base: ProgRef<'a>,
78    /// The name of the current module.
79    cur_module: Option<String>,
80    /// The (committed) state before the input.
81    core: Core<'a>,
82    /// The state when started (or, after `apply` has applied changes, at that time). `reset` returns to it.
83    baseline: Core<'a>,
84    /// The input being run.
85    pending: Option<Pending<'a>>,
86    /// The number of the `attach`ed VM, and how many times it has advanced past stop points.
87    attached: Option<(u64, u64)>,
88}
89
90/// Turns a misuse of the API into a `VmError`.
91fn misuse(kind: VmErrorKind) -> VmError {
92    VmError {
93        kind,
94        module: None,
95        label: None,
96        line: None,
97    }
98}
99
100impl<'a> Repl<'a> {
101    /// Starts with an empty environment without a script.
102    pub fn empty(registry: &'a Registry, cfg: VmConfig) -> Result<Self, VmError> {
103        let program = compile_modules(&[], registry).map_err(|_| misuse(VmErrorKind::Poisoned))?;
104        let base = ProgRef::Shared(Arc::new(program));
105        let vm = Vm::new_inner(base.clone(), registry, cfg, false)?;
106        Self::build(registry, base, vm, None, Vec::new(), None)
107    }
108
109    /// Starts on a copy of the state at the start of the script's start label (before running). The start label may be
110    /// missing.
111    pub fn from_program(
112        program: &'a Program,
113        registry: &'a Registry,
114        cfg: VmConfig,
115    ) -> Result<Self, VmError> {
116        let base = ProgRef::Borrowed(program);
117        let cur = start_module(program, &cfg.start).map(|i| program.modules[i].clone());
118        let vm = Vm::new_inner(base.clone(), registry, cfg, false)?;
119        Self::build(registry, base, vm, cur, Vec::new(), None)
120    }
121
122    /// Starts on a copy of a stopped VM. `vm` is not changed (until `apply` is called). `Err` if it is not stopped.
123    pub fn attach(vm: &Vm<'a>) -> Result<Self, VmError> {
124        if !vm.is_stopped() {
125            return Err(misuse(VmErrorKind::NotStopped));
126        }
127        let base = vm.program_ref().clone();
128        let (cur, locals) = Self::stop_context(&base, vm);
129        Self::build(
130            vm.registry(),
131            base,
132            vm.fork(),
133            Some(cur),
134            locals,
135            Some(vm.identity()),
136        )
137    }
138
139    /// The name of the module of the stop point, and the label's local variables (excluding hidden `for` variables; for
140    /// duplicate names, the later one).
141    fn stop_context(base: &ProgRef<'a>, vm: &Vm<'_>) -> (String, Vec<(String, Ty, Value)>) {
142        let code = &base.labels[vm.label_index()];
143        let module = base.modules[code.module as usize].clone();
144        let mut locals: Vec<(String, Ty, Value)> = Vec::new();
145        for (l, v) in code.locals.iter().zip(vm.raw_locals()) {
146            // Variables of function types are not used at the stop point (their values may refer to an old program)
147            if l.name.starts_with('$') || l.ty.contains_fn() {
148                continue;
149            }
150            match locals.iter_mut().find(|(n, _, _)| *n == l.name) {
151                Some(slot) => *slot = (l.name.clone(), l.ty.clone(), v.clone()),
152                None => locals.push((l.name.clone(), l.ty.clone(), v.clone())),
153            }
154        }
155        (module, locals)
156    }
157
158    /// Builds the environment that runs REPL input.
159    fn build(
160        registry: &'a Registry,
161        base: ProgRef<'a>,
162        vm: Vm<'a>,
163        cur_module: Option<String>,
164        locals: Vec<(String, Ty, Value)>,
165        attached: Option<(u64, u64)>,
166    ) -> Result<Self, VmError> {
167        let core = Self::initial_core(registry, &base, vm, cur_module.as_deref(), locals)?;
168        let baseline = core.fork();
169        Ok(Self {
170            registry,
171            base,
172            cur_module,
173            core,
174            baseline,
175            pending: None,
176            attached,
177        })
178    }
179
180    /// The initial environment without declarations (the local variables of the stop point are held as REPL variables).
181    fn initial_core(
182        registry: &'a Registry,
183        base: &ProgRef<'a>,
184        mut vm: Vm<'a>,
185        cur_module: Option<&str>,
186        locals: Vec<(String, Ty, Value)>,
187    ) -> Result<Core<'a>, VmError> {
188        let vars: Vec<ReplVar> = locals
189            .iter()
190            .map(|(n, t, _)| ReplVar {
191                name: n.clone(),
192                ty: t.clone(),
193                kind: VarKind::StopLocal,
194            })
195            .collect();
196        let input = InputAst::Stmts(Vec::new());
197        let rc = ReplCompile {
198            cur_module,
199            decls: &[],
200            vars: &vars,
201            input: &input,
202        };
203        let (program, outcome, _) =
204            compile_repl(base, registry, &rc).map_err(|_| misuse(VmErrorKind::Poisoned))?;
205        let repl_idx = base.modules.len() as u32;
206        let cur = cur_module
207            .and_then(|m| base.modules.iter().position(|x| x == m))
208            .map(|c| (repl_idx, c as u32));
209        vm.set_program(ProgRef::Shared(Arc::new(program)), cur)?;
210        let n_base = base.globals.len();
211        for (i, (_, _, v)) in locals.into_iter().enumerate() {
212            vm.set_global(n_base + i, v);
213        }
214        Ok(Core {
215            vm,
216            decls: Vec::new(),
217            vars: outcome.vars,
218        })
219    }
220
221    /// The table of identities used to parse input (identities of the current module and of `import`ed modules, including
222    /// REPL declarations).
223    fn idents(&self) -> IdentMap {
224        let mut map = IdentMap::new();
225        for (name, src) in self.base.modules.iter().zip(&self.base.sources) {
226            map.insert(name.clone(), scan_identities(src));
227        }
228        let mut usable: HashSet<String> = HashSet::new();
229        let mut imports: Vec<String> = Vec::new();
230        if let Some(cur) = &self.cur_module {
231            if let Some(set) = map.get(cur) {
232                usable.extend(set.iter().cloned());
233            }
234            if let Some(i) = self.base.modules.iter().position(|m| m == cur) {
235                imports.extend(scan_imports(&self.base.sources[i]));
236            }
237        }
238        for d in &self.core.decls {
239            match d {
240                DeclEntry::Import(i) => imports.push(i.path.clone()),
241                DeclEntry::Identity(x) => {
242                    usable.insert(x.name.clone());
243                }
244                _ => {}
245            }
246        }
247        for m in imports {
248            if let Some(set) = map.get(&m) {
249                usable.extend(set.iter().cloned());
250            }
251        }
252        map.insert(REPL_MODULE.to_string(), usable);
253        map
254    }
255
256    /// Type-checks input and prepares to run it (does not run it).
257    ///
258    /// If the previous input has not finished (before `Done`, a runtime error or `abort`), returns `Err` without diagnostics.
259    /// When diagnostics are returned, the state of the `Repl` is unchanged.
260    pub fn submit(&mut self, input: &str) -> Result<Submitted, Vec<Diagnostic>> {
261        if self.pending.is_some() {
262            return Err(Vec::new());
263        }
264        let idents = self.idents();
265        let parsed = classify(input, &idents, true)?;
266        let mut cand = self.core.decls.clone();
267        let mut new_names: Vec<Declared> = Vec::new();
268        let mut replaced: Vec<(String, Pos)> = Vec::new();
269        let (ast, declaration) = match parsed {
270            Parsed::Empty => (InputAst::Stmts(Vec::new()), false),
271            Parsed::Command => {
272                let pos = Pos { line: 1, col: 1 };
273                return Err(vec![Diagnostic {
274                    module: REPL_MODULE.to_string(),
275                    line: pos.line,
276                    col: pos.col,
277                    severity: Severity::Error,
278                    code: DiagCode::UnexpectedToken,
279                    args: vec![("found", DiagArg::Str(":".to_string()))],
280                }]);
281            }
282            Parsed::Expr(e) => (InputAst::Expr(e), false),
283            Parsed::Stmts(b) => (InputAst::Stmts(b), false),
284            Parsed::Decls(entries) => {
285                for e in entries {
286                    new_names.push(match &e {
287                        DeclEntry::Import(i) => Declared::Import { name: i.shown() },
288                        DeclEntry::Identity(i) => Declared::Identity {
289                            name: i.name.clone(),
290                        },
291                        DeclEntry::Type(t) => Declared::Type {
292                            name: t.name.clone(),
293                        },
294                        DeclEntry::Fn(f) => Declared::Fn {
295                            name: f.name.clone(),
296                        },
297                    });
298                    match &e {
299                        // A REPL `fn` with the same name replaces the body (only when the types are the same; checked later)
300                        DeclEntry::Fn(f) => {
301                            let old = cand
302                                .iter()
303                                .position(|d| matches!(d, DeclEntry::Fn(g) if g.name == f.name));
304                            match old {
305                                Some(i) => {
306                                    replaced.push((f.name.clone(), f.pos));
307                                    cand[i] = e;
308                                }
309                                None => cand.push(e),
310                            }
311                        }
312                        // Writing the same `import` again does nothing
313                        DeclEntry::Import(i) => {
314                            let dup = cand
315                                .iter()
316                                .any(|d| matches!(d, DeclEntry::Import(g) if g.path == i.path && g.local == i.local));
317                            if !dup {
318                                cand.push(e);
319                            }
320                        }
321                        _ => cand.push(e),
322                    }
323                }
324                (InputAst::Stmts(Vec::new()), true)
325            }
326        };
327        let rc = ReplCompile {
328            cur_module: self.cur_module.as_deref(),
329            decls: &cand,
330            vars: &self.core.vars,
331            input: &ast,
332        };
333        let (program, outcome, diags) = match compile_repl(&self.base, self.registry, &rc) {
334            Ok(x) => x,
335            Err(d) => return Err(only_repl(d)),
336        };
337        // A `fn` can be replaced only when its parameter and return types are the same
338        for (name, pos) in &replaced {
339            if fn_signature(self.core.vm.program_ref(), name) != fn_signature(&program, name) {
340                return Err(vec![Diagnostic {
341                    module: REPL_MODULE.to_string(),
342                    line: pos.line,
343                    col: pos.col,
344                    severity: Severity::Error,
345                    code: DiagCode::DuplicateName,
346                    args: vec![("name", DiagArg::Str(name.clone()))],
347                }]);
348            }
349        }
350        let warnings = only_repl(diags);
351        let kind = match (&ast, declaration) {
352            (InputAst::Expr(_), _) => {
353                InputKind::Expression(outcome.input_ty.clone().unwrap_or(Ty::Unit))
354            }
355            (_, true) => InputKind::Declaration,
356            _ => InputKind::Statement,
357        };
358        let mut core = self.core.fork();
359        let repl_idx = self.base.modules.len() as u32;
360        let cur = self
361            .cur_module
362            .as_deref()
363            .and_then(|m| self.base.modules.iter().position(|x| x == m))
364            .map(|c| (repl_idx, c as u32));
365        let program = Arc::new(program);
366        core.vm
367            .set_program(ProgRef::Shared(program.clone()), cur)
368            .map_err(|_| Vec::new())?;
369        let n_base = self.base.globals.len();
370        for (i, v) in outcome.vars.iter().enumerate() {
371            let changed = self.core.vars.get(i).is_none_or(|o| o.ty != v.ty);
372            if changed {
373                core.vm
374                    .set_global(n_base + i, v.ty.default_in(program.types()));
375            }
376        }
377        core.decls = cand;
378        core.vars = outcome.vars.clone();
379        core.vm.begin_input(outcome.input_label);
380        self.pending = Some(Pending {
381            core,
382            input_label: outcome.input_label,
383            expr_ty: outcome.input_ty.clone(),
384            lets: outcome.lets.clone(),
385            declared: new_names,
386        });
387        Ok(Submitted { kind, warnings })
388    }
389
390    /// Runs the prepared input until the next stop point (or the end).
391    ///
392    /// On a runtime error, the input is discarded (the `Repl` returns to the state before the input, and `submit` can be
393    /// called again).
394    pub fn run(&mut self) -> Result<ReplYield, VmError> {
395        let Some(p) = self.pending.as_mut() else {
396            return Err(misuse(VmErrorKind::Ended));
397        };
398        match p.core.vm.run() {
399            Ok(Yield::Stop { command, args, id }) => Ok(ReplYield::Stop { command, args, id }),
400            Ok(_) => {
401                let p = self.pending.take().expect("実行中の入力");
402                Ok(self.finish(p))
403            }
404            Err(e) => {
405                // If `run` was called while stopped (a misuse), keep the input. Otherwise, discard it
406                if e.kind != VmErrorKind::AlreadyStopped {
407                    self.pending = None;
408                }
409                Err(e)
410            }
411        }
412    }
413
414    /// The result when running the input has finished. Commits the state.
415    fn finish(&mut self, mut p: Pending<'a>) -> ReplYield {
416        let ended = p.core.vm.label_index() != p.input_label;
417        let value = match (&p.expr_ty, ended) {
418            (Some(ty), false) => p.core.vm.stack_top().map(|v| (v, ty.clone())),
419            _ => None,
420        };
421        p.core.vm.clear_stack();
422        let n_base = self.base.globals.len();
423        let mut declared: Vec<Declared> = Vec::new();
424        for name in &p.lets {
425            if let Some(i) = p.core.vars.iter().position(|v| v.name == *name) {
426                declared.push(Declared::Let {
427                    name: name.clone(),
428                    value: p.core.vm.raw_globals()[n_base + i].clone(),
429                    ty: p.core.vars[i].ty.clone(),
430                });
431            }
432        }
433        declared.extend(std::mem::take(&mut p.declared));
434        self.core = p.core;
435        ReplYield::Done {
436            value,
437            declared,
438            ended,
439        }
440    }
441
442    /// Resumes stopped input with the return value of the stop command.
443    ///
444    /// Misuse such as a return value of the wrong type returns `Err` and stays stopped. On a runtime error, the input is
445    /// discarded.
446    pub fn resume(&mut self, input: Input) -> Result<(), VmError> {
447        let Some(p) = self.pending.as_mut() else {
448            return Err(misuse(VmErrorKind::NotStopped));
449        };
450        let r = p.core.vm.resume(input);
451        if r.is_err() && p.core.vm.is_poisoned() {
452            self.pending = None;
453        }
454        r
455    }
456
457    /// Discards input that is running (including stopped). The `Repl` returns to the state before the input.
458    pub fn abort(&mut self) {
459        self.pending = None;
460    }
461
462    /// Reads the state slice of package `P` (read only). While input is running, reads that input's state; otherwise, the
463    /// state of the committed copy. Used by the host after `run` to read and show cues for sound and images. `None` if `P`
464    /// is not registered.
465    pub fn package_state<P: Package>(&self) -> Option<&P::State> {
466        match &self.pending {
467            Some(p) => p.core.vm.package_state::<P>(),
468            None => self.core.vm.package_state::<P>(),
469        }
470    }
471
472    /// Finds the type of an expression (does not evaluate it). `Err` if it is not an expression.
473    pub fn type_of(&self, input: &str) -> Result<Ty, Vec<Diagnostic>> {
474        let text = input.trim_end();
475        if text.contains('\n') {
476            return Err(vec![Diagnostic {
477                module: REPL_MODULE.to_string(),
478                line: 1,
479                col: 1,
480                severity: Severity::Error,
481                code: DiagCode::UnexpectedToken,
482                args: vec![("found", DiagArg::Str("\n".to_string()))],
483            }]);
484        }
485        let e = parse_expr_line(text, REPL_MODULE, 1).map_err(|d| vec![d])?;
486        let ast = InputAst::Expr(e);
487        let rc = ReplCompile {
488            cur_module: self.cur_module.as_deref(),
489            decls: &self.core.decls,
490            vars: &self.core.vars,
491            input: &ast,
492        };
493        match compile_repl(&self.base, self.registry, &rc) {
494            Ok((_, outcome, _)) => Ok(outcome.input_ty.unwrap_or(Ty::Unit)),
495            Err(d) => Err(only_repl(d)),
496        }
497    }
498
499    /// The list of variables of the copy: script module variables, host-declared variables, local variables of the stop point
500    /// (`local` is true), and REPL `let` variables, in that order. REPL `let` variables have `module` `Some("<repl>")`.
501    pub fn variables(&self) -> Vec<Variable> {
502        let vm = &self.core.vm;
503        let n_base = self.base.globals.len();
504        let mut all = vm.module_and_host_variables();
505        let host = all.split_off(vm.raw_globals().len());
506        let repl_vars = all.split_off(n_base);
507        let mut out = all;
508        out.extend(host);
509        for (v, var) in repl_vars.iter().zip(&self.core.vars) {
510            if var.kind == VarKind::StopLocal {
511                out.push(Variable {
512                    module: None,
513                    local: true,
514                    ..v.clone()
515                });
516            }
517        }
518        for (v, var) in repl_vars.into_iter().zip(&self.core.vars) {
519            if var.kind == VarKind::Let {
520                out.push(v);
521            }
522        }
523        out
524    }
525
526    /// The `fn`s, types, `import`s and `identity`s declared in the REPL (in declaration order).
527    pub fn defs(&self) -> Vec<Def> {
528        let program = self.core.vm.program_ref();
529        let repl_idx = self.base.modules.len() as u32;
530        self.core
531            .decls
532            .iter()
533            .map(|d| match d {
534                DeclEntry::Import(i) => Def::Import { name: i.shown() },
535                DeclEntry::Identity(i) => Def::Identity {
536                    name: i.name.clone(),
537                },
538                DeclEntry::Type(t) => match t.kind {
539                    TypeDeclKind::Struct(_) => Def::Struct {
540                        name: t.name.clone(),
541                    },
542                    TypeDeclKind::Enum(_) => Def::Enum {
543                        name: t.name.clone(),
544                    },
545                },
546                DeclEntry::Fn(f) => {
547                    let code = program
548                        .fns
549                        .iter()
550                        .find(|c| c.module == repl_idx && c.name == f.name);
551                    Def::Fn {
552                        name: f.name.clone(),
553                        params: code
554                            .map(|c| {
555                                c.locals[..c.params as usize]
556                                    .iter()
557                                    .map(|l| (l.name.clone(), l.ty.clone()))
558                                    .collect()
559                            })
560                            .unwrap_or_default(),
561                        ret: code.and_then(|c| c.ret.clone()),
562                    }
563                }
564            })
565            .collect()
566    }
567
568    /// The token that interrupts a running input from another thread (`spec/host/01-execution.md`, 1.9a). An interrupted input
569    /// is discarded like any other runtime error.
570    pub fn interrupt_handle(&self) -> InterruptHandle {
571        self.core.vm.interrupt_handle()
572    }
573
574    /// Discards the REPL declarations and returns the copy to the state when started (or, after `apply`, at that time).
575    pub fn reset(&mut self) -> Result<(), VmError> {
576        self.pending = None;
577        self.core = self.baseline.fork();
578        Ok(())
579    }
580
581    /// Applies the variables changed in the copy to the `attach`ed `vm` (section 7.3.6 of `spec/host/07-repl.md`). Either
582    /// all are applied or none.
583    ///
584    /// Only `save var`s, `Kind::Save` variables and local variables of the stop point whose values differ are applied.
585    /// `persistent var`s are not applied and are listed in `Applied::skipped`. A `Repl` made with `from_program` or `empty`,
586    /// and one whose input is running, gives `NotAttached`.
587    pub fn apply(&mut self, vm: &mut Vm<'a>) -> Result<Applied, ApplyError> {
588        let Some(att) = self.attached else {
589            return Err(ApplyError::NotAttached);
590        };
591        if self.pending.is_some() {
592            return Err(ApplyError::NotAttached);
593        }
594        if vm.identity() != att || !vm.is_stopped() {
595            return Err(ApplyError::VmChanged);
596        }
597        let n_base = self.base.globals.len();
598        let mine = &self.core.vm;
599        let mut changes: Vec<(ApplyTarget, Value)> = Vec::new();
600        let mut skipped: Vec<Name> = Vec::new();
601        for (i, g) in self.base.globals.iter().enumerate() {
602            let (a, b) = (&mine.raw_globals()[i], &vm.raw_globals()[i]);
603            if a == b {
604                continue;
605            }
606            if g.persistent {
607                skipped.push(Name {
608                    module: Some(self.base.modules[g.module as usize].clone()),
609                    name: g.name.clone(),
610                });
611            } else {
612                changes.push((ApplyTarget::Global(i), a.clone()));
613            }
614        }
615        for (i, d) in self.registry.vars().iter().enumerate() {
616            let (a, b) = (&mine.raw_host_vars()[i], &vm.raw_host_vars()[i]);
617            if a == b {
618                continue;
619            }
620            match d.kind {
621                Kind::Save => changes.push((ApplyTarget::Host(i), a.clone())),
622                _ => skipped.push(host_name(&d.name)),
623            }
624        }
625        let code = &self.base.labels[vm.label_index()];
626        for (j, var) in self.core.vars.iter().enumerate() {
627            if var.kind != VarKind::StopLocal {
628                continue;
629            }
630            let Some(slot) = code.locals.iter().rposition(|l| l.name == var.name) else {
631                continue;
632            };
633            let a = &mine.raw_globals()[n_base + j];
634            if *a != vm.raw_locals()[slot] {
635                changes.push((ApplyTarget::Local(slot), a.clone()));
636            }
637        }
638        if changes.is_empty() {
639            return Ok(Applied {
640                variables: Vec::new(),
641                skipped,
642            });
643        }
644        let name_of = |vm: &Vm<'a>, t: ApplyTarget| {
645            let v = vm.variable_of(t);
646            Name {
647                module: v.module,
648                name: v.name,
649            }
650        };
651        if let Err(fail) = vm.apply_values(&changes) {
652            let invalid = |i: usize, reason| ApplyError::Invalid {
653                name: name_of(vm, changes[i].0),
654                reason,
655            };
656            return Err(match fail {
657                ApplyFail::Type(i) => invalid(i, ApplyInvalid::Type),
658                ApplyFail::ValueTooLarge(i) => invalid(i, ApplyInvalid::ValueTooLarge),
659                ApplyFail::MemoryLimit(i) => invalid(i, ApplyInvalid::MemoryLimit),
660                ApplyFail::NotSavable(i) => invalid(i, ApplyInvalid::NotSavable),
661                ApplyFail::StopArgs(e) => ApplyError::StopArgs(e),
662            });
663        }
664        let variables = changes.iter().map(|(t, _)| vm.variable_of(*t)).collect();
665        // Make the base of `reset` a copy of the script after applying (the REPL declarations are discarded)
666        let (cur, locals) = Self::stop_context(&self.base, vm);
667        if let Ok(core) =
668            Self::initial_core(self.registry, &self.base, vm.fork(), Some(&cur), locals)
669        {
670            self.baseline = core;
671        }
672        Ok(Applied { variables, skipped })
673    }
674}
675
676/// The name of a host-declared variable (`namespace.variable`).
677fn host_name(full: &str) -> Name {
678    let (ns, name) = full.split_once('.').unwrap_or(("", full));
679    Name {
680        module: Some(ns.to_string()),
681        name: name.to_string(),
682    }
683}
684
685/// Keeps only the diagnostics of the REPL module (warnings of the script's modules were handled when the script was
686/// compiled).
687fn only_repl(diags: Vec<Diagnostic>) -> Vec<Diagnostic> {
688    diags
689        .into_iter()
690        .filter(|d| d.module == REPL_MODULE)
691        .collect()
692}
693
694/// The parameter and return types of a REPL `fn`.
695fn fn_signature(program: &Program, name: &str) -> Option<(Vec<Ty>, Option<Ty>)> {
696    let repl_idx = program.modules.iter().position(|m| m == REPL_MODULE)? as u32;
697    program
698        .fns
699        .iter()
700        .find(|c| c.module == repl_idx && c.name == name)
701        .map(|c| {
702            (
703                c.locals[..c.params as usize]
704                    .iter()
705                    .map(|l| l.ty.clone())
706                    .collect(),
707                c.ret.clone(),
708            )
709        })
710}