Skip to main content

yomi_core/package/
ctx.rs

1//! The entry to state that command functions receive.
2
3use super::*;
4use crate::vm::InterruptHandle;
5
6/// The type-erased entry that the VM passes to functions (the material for making a `Ctx`).
7pub(crate) struct Env<'a> {
8    pub index: usize,
9    pub packages: &'a [PackageEntry],
10    pub before: &'a [SliceBox],
11    pub own: &'a mut SliceBox,
12    pub after: &'a [SliceBox],
13    pub persistent: &'a mut SliceBox,
14    pub rng: &'a mut Rng,
15    pub interrupt: &'a InterruptHandle,
16}
17
18/// The entry to state that command functions receive.
19///
20/// Effect commands get `&mut Ctx<P>`, query commands get `&Ctx<P>`. They can read and write only the state slice and
21/// persistent slice of their own package `P`, and can read the state of other packages only for those declared in
22/// `P::DEPENDS` ([`Ctx::dep`]). There is no time and no files.
23pub struct Ctx<'a, P: Package> {
24    pub(super) state: &'a mut P::State,
25    pub(super) persistent: &'a mut P::Persistent,
26    pub(super) before: &'a [SliceBox],
27    pub(super) after: &'a [SliceBox],
28    pub(super) index: usize,
29    pub(super) packages: &'a [PackageEntry],
30    pub(super) rng: &'a mut Rng,
31    pub(super) interrupt: &'a InterruptHandle,
32}
33
34impl<'a, P: Package> Ctx<'a, P> {
35    /// Makes a context from the environment of running a command. `Err` if the state types do not match.
36    pub(crate) fn new(env: Env<'a>) -> Result<Self, CommandError> {
37        let state = env.own.downcast_mut::<P::State>().ok_or_else(|| {
38            CommandError::with_code("core.state_type_mismatch", [("package", P::NAME.into())])
39        })?;
40        let persistent = env
41            .persistent
42            .downcast_mut::<P::Persistent>()
43            .ok_or_else(|| {
44                CommandError::with_code(
45                    "core.persistent_type_mismatch",
46                    [("package", P::NAME.into())],
47                )
48            })?;
49        Ok(Self {
50            state,
51            persistent,
52            before: env.before,
53            after: env.after,
54            index: env.index,
55            packages: env.packages,
56            rng: env.rng,
57            interrupt: env.interrupt,
58        })
59    }
60
61    /// Whether an interrupt is requested for the running VM (`spec/host/01-execution.md`, 1.9a). A long command checks this
62    /// now and then, and returns [`CommandError::interrupted`] if it is `true`.
63    pub fn interrupted(&self) -> bool {
64        self.interrupt.is_interrupted()
65    }
66
67    /// The state slice of its own package (read).
68    pub fn state(&self) -> &P::State {
69        self.state
70    }
71
72    /// The state slice of its own package (write). Only effect commands receive `&mut Ctx`.
73    pub fn state_mut(&mut self) -> &mut P::State {
74        self.state
75    }
76
77    /// The persistent slice of its own package (read).
78    pub fn persistent(&self) -> &P::Persistent {
79        self.persistent
80    }
81
82    /// The persistent slice of its own package (write). Not undone by rollback.
83    pub fn persistent_mut(&mut self) -> &mut P::Persistent {
84        self.persistent
85    }
86
87    /// The core's random generator (the same sequence as `random` in scripts). Needs `&mut`, so only effect commands can use
88    /// it.
89    pub fn rng(&mut self) -> &mut Rng {
90        self.rng
91    }
92
93    /// The state slice of dependency package `Q` (read only).
94    ///
95    /// `Err` if `Q` is not in `P::DEPENDS` or is not registered (becomes a runtime error).
96    pub fn dep<Q: Package>(&self) -> Result<&Q::State, CommandError> {
97        if !P::DEPENDS.contains(&Q::NAME) {
98            return Err(CommandError::with_code(
99                "core.dep_not_declared",
100                [("package", P::NAME.into()), ("dep", Q::NAME.into())],
101            ));
102        }
103        let j = self
104            .packages
105            .iter()
106            .position(|e| e.name == Q::NAME)
107            .ok_or_else(|| {
108                CommandError::with_code("core.dep_not_registered", [("dep", Q::NAME.into())])
109            })?;
110        let slot = match j.cmp(&self.index) {
111            std::cmp::Ordering::Less => &self.before[j],
112            std::cmp::Ordering::Greater => &self.after[j - self.index - 1],
113            std::cmp::Ordering::Equal => {
114                return Err(CommandError::with_code(
115                    "core.dep_is_self",
116                    [("package", P::NAME.into())],
117                ));
118            }
119        };
120        slot.downcast_ref::<Q::State>().ok_or_else(|| {
121            CommandError::with_code("core.state_type_mismatch", [("package", Q::NAME.into())])
122        })
123    }
124}