Skip to main content

yomi_core/vm/
inspect.rs

1//! VM: inspecting and changing state, for the host.
2
3use super::*;
4
5impl<'a> Vm<'a> {
6    /// Whether it is stopped at a stop point. False when a load restored it with `LabelStart` (start with `run`).
7    pub fn is_stopped(&self) -> bool {
8        self.current.is_some()
9    }
10
11    /// The `Yield` while stopped.
12    pub fn current(&self) -> Option<&Yield> {
13        self.current.as_ref()
14    }
15
16    /// The list of variables (module variables, then local variables). Local variables are only those of the label being run.
17    pub fn variables(&self) -> Vec<Variable> {
18        let mut out = self.module_and_host_variables();
19        let code = &self.program.labels[self.label];
20        // Do not show the iteration state of `for` (hidden local variables whose names start with `$`), or variables of function
21        // types that are not used at the stop point
22        out.extend(
23            code.locals
24                .iter()
25                .zip(&self.locals)
26                .filter(|(l, _)| !l.name.starts_with('$') && !l.ty.contains_fn())
27                .map(|(l, v)| Variable {
28                    module: None,
29                    name: l.name.clone(),
30                    value: v.clone(),
31                    local: true,
32                    persistent: false,
33                }),
34        );
35        out
36    }
37
38    /// Module variables and host-declared variables (`variables` without local variables).
39    pub(crate) fn module_and_host_variables(&self) -> Vec<Variable> {
40        let mut out: Vec<Variable> = self
41            .program
42            .globals
43            .iter()
44            .zip(&self.globals)
45            .map(|(g, v)| Variable {
46                module: Some(self.program.modules[g.module as usize].clone()),
47                name: g.name.clone(),
48                value: v.clone(),
49                local: false,
50                persistent: g.persistent,
51            })
52            .collect();
53        // Host-declared variables. `module` is the namespace (the package name), `name` is the variable name
54        out.extend(
55            self.registry
56                .vars()
57                .iter()
58                .zip(&self.host_vars)
59                .map(|(d, v)| {
60                    let (ns, name) = d.name.split_once('.').unwrap_or(("", d.name.as_str()));
61                    Variable {
62                        module: Some(ns.to_string()),
63                        name: name.to_string(),
64                        value: v.clone(),
65                        local: false,
66                        persistent: d.kind == Kind::Persistent,
67                    }
68                }),
69        );
70        out
71    }
72
73    /// The name of the current label (without the module name).
74    pub fn label_name(&self) -> &str {
75        &self.program.labels[self.label].name
76    }
77
78    /// The name of the module containing the current label.
79    pub fn module_name(&self) -> &str {
80        &self.program.modules[self.program.labels[self.label].module as usize]
81    }
82
83    /// Passed stop points (`module.label#id`). The host saves them as persistent data (read by `seen`).
84    /// They grow when a stop point is reached (right before returning a `Yield`) and when an option is chosen.
85    pub fn seen_points(&self) -> Vec<String> {
86        self.seen.iter().cloned().collect()
87    }
88
89    /// Replaces the passed stop points (used to restore previously saved [`Vm::seen_points`]).
90    /// If they are needed to rebuild the arguments of a stop point on load, pass them with [`VmConfig::seen_points`].
91    pub fn set_seen_points<I, S>(&mut self, points: I)
92    where
93        I: IntoIterator<Item = S>,
94        S: Into<String>,
95    {
96        self.seen = points.into_iter().map(Into::into).collect();
97    }
98
99    /// The history of stop points (oldest first; up to the newest `VmConfig::history_limit` entries). Recorded every time a
100    /// stop point is reached. Included in saves and undone by rollback.
101    pub fn history(&self) -> &[Arc<StopRecord>] {
102        let start = self.history.len().saturating_sub(self.cfg.history_limit);
103        &self.history[start..]
104    }
105
106    /// The label (index into `Program::labels`) and the sequential number of the stop point in it, while stopped.
107    pub(crate) fn stop_position(&self) -> Option<(usize, u32)> {
108        match self.state {
109            State::Stopped { ordinal } => Some((self.label, ordinal)),
110            _ => None,
111        }
112    }
113
114    /// For a choice stop point, the numbers in the order written of the options in the list given to the host.
115    pub(crate) fn choice_origins(&self) -> &[u32] {
116        &self.choice.orig
117    }
118
119    /// The labels entered, as indices into `Program::labels`.
120    pub(crate) fn visited_indices(&self) -> &BTreeSet<u32> {
121        &self.visited
122    }
123
124    /// Labels entered (`module.label`). Read by `visited`.
125    pub fn visited_labels(&self) -> Vec<String> {
126        self.visited
127            .iter()
128            .map(|&l| label_path(&self.program, l as usize))
129            .collect()
130    }
131
132    /// `once` options already chosen (`module.label#id`).
133    pub fn chosen_once(&self) -> Vec<String> {
134        self.once_done
135            .iter()
136            .map(|(l, id)| format!("{}#{id}", label_path(&self.program, *l as usize)))
137            .collect()
138    }
139
140    /// The depth of the call stack (the number of frames pushed by `call` that have not returned yet).
141    pub fn call_depth(&self) -> usize {
142        self.frames.len()
143    }
144
145    /// Reads the state slice of package `P` (the host reads it at a stop point and reflects it on the screen and so on; read
146    /// only). `None` if `P` is not registered.
147    pub fn package_state<P: Package>(&self) -> Option<&P::State> {
148        let i = self
149            .registry
150            .package_entries()
151            .iter()
152            .position(|e| e.name == P::NAME)?;
153        self.states.get(i)?.downcast_ref::<P::State>()
154    }
155
156    /// Returns the cues added after the last `run` / `resume`, in the order they were added (the order written in the script).
157    ///
158    /// Cues are in each package's state (`cues`), and their order across packages is known from this table. Use each entry's
159    /// `package` (`Package::NAME`) and `index` (the position in that package's `cues`) to take them from `package_state`.
160    /// Emptied by the next `run` / `resume` and by loading or restoring.
161    pub fn cue_order(&self) -> impl Iterator<Item = CueRef<'_>> {
162        let entries = self.registry.package_entries();
163        self.cue_order.iter().map(move |&(p, index)| CueRef {
164            package: entries[p as usize].name.as_str(),
165            index,
166        })
167    }
168
169    /// Reads the persistent slice of package `P` (read only). `None` if `P` is not registered.
170    pub fn package_persistent<P: Package>(&self) -> Option<&P::Persistent> {
171        let i = self
172            .registry
173            .package_entries()
174            .iter()
175            .position(|e| e.name == P::NAME)?;
176        self.persist.get(i)?.downcast_ref::<P::Persistent>()
177    }
178
179    /// Reads the value of a host-declared variable ([`Registry::var`]). `None` if not registered.
180    pub fn get_var(&self, name: &str) -> Option<Value> {
181        let i = self.registry.var_index(name)?;
182        self.host_vars.get(i).cloned()
183    }
184
185    /// Writes a host-declared variable. `read_only` variables can be written too. `UnknownVariable` if the name does not
186    /// exist, `BadInput` if the type does not match (in both cases, the VM is unchanged).
187    pub fn set_var(&mut self, name: &str, value: Value) -> Result<(), VmError> {
188        let Some(i) = self.registry.var_index(name) else {
189            return Err(self.misuse(VmErrorKind::UnknownVariable(name.to_string())));
190        };
191        let Some(value) = value.normalized() else {
192            return Err(self.misuse(VmErrorKind::NonFiniteFloat));
193        };
194        let expected = self.registry.vars()[i].ty.clone();
195        if !value.matches_in(&expected, self.program.types()) {
196            return Err(self.misuse(VmErrorKind::BadInput {
197                found: value.ty(),
198                expected,
199            }));
200        }
201        self.host_vars[i] = value;
202        self.total_valid = false;
203        Ok(())
204    }
205}
206
207/// One entry of the table of cues in the order written ([`Vm::cue_order`]).
208#[derive(Debug, Clone, Copy, PartialEq, Eq)]
209pub struct CueRef<'a> {
210    /// The name of the package that added the cue (`Package::NAME`).
211    pub package: &'a str,
212    /// The position within the `cues` of that package's state.
213    pub index: usize,
214}