Skip to main content

rune/runtime/
unit.rs

1//! A single execution unit in the rune virtual machine.
2//!
3//! A unit consists of a sequence of instructions, and lookaside tables for
4//! metadata like function locations.
5
6#[cfg(feature = "byte-code")]
7mod byte_code;
8mod storage;
9
10use core::fmt;
11
12#[cfg(feature = "musli02")]
13use musli_core02::mode::Binary;
14#[cfg(feature = "musli02")]
15use musli_core02::{Decode, Encode};
16#[cfg(feature = "serde")]
17use serde::de::DeserializeOwned;
18#[cfg(feature = "serde")]
19use serde::{Deserialize, Serialize};
20
21use crate as rune;
22use crate::alloc::prelude::*;
23use crate::alloc::{self, Box, String, Vec};
24use crate::hash;
25use crate::runtime::{
26    Address, Call, ConstValue, ConstValueBuf, DebugInfo, Inst, Rtti, StaticString,
27};
28use crate::sync::Arc;
29use crate::Hash;
30
31pub use self::storage::{ArrayUnit, EncodeError, UnitEncoder, UnitStorage};
32pub(crate) use self::storage::{BadInstruction, BadJump};
33
34#[cfg(feature = "byte-code")]
35pub use self::byte_code::ByteCodeUnit;
36
37/// Default storage implementation to use.
38#[cfg(not(rune_byte_code))]
39pub type DefaultStorage = ArrayUnit;
40/// Default storage implementation to use.
41#[cfg(rune_byte_code)]
42pub type DefaultStorage = ByteCodeUnit;
43
44/// Instructions and debug info from a single compilation.
45///
46/// See [`rune::prepare`] for more.
47#[derive(Debug, TryClone, Default)]
48#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
49#[cfg_attr(feature = "serde", serde(bound = "S: Serialize + DeserializeOwned"))]
50#[cfg_attr(feature = "musli02", derive(Decode, Encode), musli(crate = musli_core02))]
51#[cfg_attr(feature = "musli02", musli(Binary, bound = {S: Encode<Binary>}, decode_bound<'de, A> = {S: Decode<'de, Binary, A>}))]
52#[try_clone(bound = {S: TryClone})]
53pub struct Unit<S = DefaultStorage> {
54    /// The information needed to execute the program.
55    #[cfg_attr(feature = "serde", serde(flatten))]
56    logic: Logic<S>,
57    /// Debug info if available for unit.
58    debug: Option<Box<DebugInfo>>,
59}
60
61assert_impl!(Unit<DefaultStorage>: Send + Sync);
62
63/// Instructions from a single source file.
64#[derive(Debug, TryClone, Default)]
65#[cfg_attr(
66    feature = "serde",
67    derive(Serialize, Deserialize),
68    serde(rename = "Unit")
69)]
70#[cfg_attr(feature = "musli02", derive(Decode, Encode), musli(crate = musli_core02))]
71#[try_clone(bound = {S: TryClone})]
72pub struct Logic<S = DefaultStorage> {
73    /// Storage for the unit.
74    storage: S,
75    /// Where functions are located in the collection of instructions.
76    functions: hash::Map<UnitFn>,
77    /// Static strings.
78    static_strings: Vec<Arc<StaticString>>,
79    /// A static byte string.
80    static_bytes: Vec<Vec<u8>>,
81    /// Slots used for object keys.
82    ///
83    /// This is used when an object is used in a pattern match, to avoid having
84    /// to send the collection of keys to the virtual machine.
85    ///
86    /// All keys are sorted with the default string sort.
87    static_object_keys: Vec<Box<[String]>>,
88    /// Drop sets.
89    drop_sets: Vec<Arc<[Address]>>,
90    /// Runtime information for types.
91    rtti: hash::Map<Arc<Rtti>>,
92    /// Named constants
93    constants: hash::Map<ConstValueBuf>,
94    /// Initializers for statics declared in this unit, indexed by slot.
95    ///
96    /// A slot without an initializer has to be assigned before it can be read.
97    globals: Vec<Option<ConstValueBuf>>,
98    /// Maps the type hash of a static item to the slot it has been assigned.
99    globals_rev: hash::Map<usize>,
100}
101
102impl<S> crate::runtime::LookupRtti for Unit<S> {
103    #[inline]
104    fn lookup_rtti(&self, hash: &Hash) -> Option<&Arc<Rtti>> {
105        Unit::lookup_rtti(self, hash)
106    }
107}
108
109impl<S> Unit<S> {
110    /// Constructs a new unit from a pair of data and debug info.
111    #[inline]
112    pub fn from_parts(data: Logic<S>, debug: Option<DebugInfo>) -> alloc::Result<Self> {
113        Ok(Self {
114            logic: data,
115            debug: debug.map(Box::try_new).transpose()?,
116        })
117    }
118
119    /// Construct a new unit with the given content.
120    #[allow(clippy::too_many_arguments)]
121    #[inline]
122    pub(crate) fn new(
123        storage: S,
124        functions: hash::Map<UnitFn>,
125        static_strings: Vec<Arc<StaticString>>,
126        static_bytes: Vec<Vec<u8>>,
127        static_object_keys: Vec<Box<[String]>>,
128        drop_sets: Vec<Arc<[Address]>>,
129        rtti: hash::Map<Arc<Rtti>>,
130        debug: Option<Box<DebugInfo>>,
131        constants: hash::Map<ConstValueBuf>,
132        globals: Vec<Option<ConstValueBuf>>,
133        globals_rev: hash::Map<usize>,
134    ) -> Self {
135        Self {
136            logic: Logic {
137                storage,
138                functions,
139                static_strings,
140                static_bytes,
141                static_object_keys,
142                drop_sets,
143                rtti,
144                constants,
145                globals,
146                globals_rev,
147            },
148            debug,
149        }
150    }
151
152    /// Access unit data.
153    #[inline]
154    pub fn logic(&self) -> &Logic<S> {
155        &self.logic
156    }
157
158    /// Access debug information for the given location if it is available.
159    #[inline]
160    pub fn debug_info(&self) -> Option<&DebugInfo> {
161        Some(&**self.debug.as_ref()?)
162    }
163
164    /// Get raw underlying instructions storage.
165    #[inline]
166    pub(crate) fn instructions(&self) -> &S {
167        &self.logic.storage
168    }
169
170    /// Iterate over all static strings in the unit.
171    #[cfg(feature = "cli")]
172    #[inline]
173    pub(crate) fn iter_static_strings(&self) -> impl Iterator<Item = &Arc<StaticString>> + '_ {
174        self.logic.static_strings.iter()
175    }
176
177    /// Iterate over all static bytes in the unit.
178    #[cfg(feature = "cli")]
179    #[inline]
180    pub(crate) fn iter_static_bytes(&self) -> impl Iterator<Item = &[u8]> + '_ {
181        self.logic.static_bytes.iter().map(|v| &**v)
182    }
183
184    /// Iterate over all available drop sets.
185    #[cfg(feature = "cli")]
186    #[inline]
187    pub(crate) fn iter_static_drop_sets(&self) -> impl Iterator<Item = &[Address]> + '_ {
188        self.logic.drop_sets.iter().map(|v| &**v)
189    }
190
191    /// Iterate over all constants in the unit.
192    #[cfg(feature = "cli")]
193    #[inline]
194    pub(crate) fn iter_constants(&self) -> impl Iterator<Item = (&Hash, &ConstValue)> + '_ {
195        self.logic
196            .constants
197            .iter()
198            .map(|(hash, value)| (hash, &**value))
199    }
200
201    /// Iterate over all static object keys in the unit.
202    #[cfg(feature = "cli")]
203    #[inline]
204    pub(crate) fn iter_static_object_keys(&self) -> impl Iterator<Item = (usize, &[String])> + '_ {
205        use core::iter;
206
207        let mut it = self.logic.static_object_keys.iter().enumerate();
208
209        iter::from_fn(move || {
210            let (n, s) = it.next()?;
211            Some((n, &s[..]))
212        })
213    }
214
215    /// Iterate over dynamic functions.
216    #[cfg(feature = "cli")]
217    #[inline]
218    pub(crate) fn iter_functions(&self) -> impl Iterator<Item = (Hash, &UnitFn)> + '_ {
219        self.logic.functions.iter().map(|(h, f)| (*h, f))
220    }
221
222    /// Lookup the static string by slot, if it exists.
223    #[inline]
224    pub(crate) fn lookup_string(&self, slot: usize) -> Option<&Arc<StaticString>> {
225        self.logic.static_strings.get(slot)
226    }
227
228    /// Lookup the static byte string by slot, if it exists.
229    #[inline]
230    pub(crate) fn lookup_bytes(&self, slot: usize) -> Option<&[u8]> {
231        Some(self.logic.static_bytes.get(slot)?)
232    }
233
234    /// Lookup the static object keys by slot, if it exists.
235    #[inline]
236    pub(crate) fn lookup_object_keys(&self, slot: usize) -> Option<&[String]> {
237        Some(self.logic.static_object_keys.get(slot)?)
238    }
239
240    #[inline]
241    pub(crate) fn lookup_drop_set(&self, set: usize) -> Option<&[Address]> {
242        Some(self.logic.drop_sets.get(set)?)
243    }
244
245    /// Lookup run-time information for the given type hash.
246    #[inline]
247    pub(crate) fn lookup_rtti(&self, hash: &Hash) -> Option<&Arc<Rtti>> {
248        self.logic.rtti.get(hash)
249    }
250
251    /// Lookup a function in the unit.
252    #[inline]
253    pub(crate) fn function(&self, hash: &Hash) -> Option<&UnitFn> {
254        self.logic.functions.get(hash)
255    }
256
257    /// Lookup a constant from the unit.
258    #[inline]
259    pub(crate) fn constant(&self, hash: &Hash) -> Option<&ConstValue> {
260        Some(self.logic.constants.get(hash)?)
261    }
262
263    /// The number of static slots declared in this unit.
264    ///
265    /// This is the size that a [`Globals`] storage constructed for this unit
266    /// will have.
267    ///
268    /// [`Globals`]: crate::runtime::Globals
269    #[inline]
270    pub fn globals_len(&self) -> usize {
271        self.logic.globals.len()
272    }
273
274    /// Lookup the slot assigned to the static item with the given type hash.
275    ///
276    /// This is how a caller addresses a static by item without having to know
277    /// its slot.
278    #[inline]
279    pub fn global_slot(&self, hash: &Hash) -> Option<usize> {
280        self.logic.globals_rev.get(hash).copied()
281    }
282
283    /// Lookup the initializer for the given static slot, if it has one.
284    #[inline]
285    pub(crate) fn global_init(&self, slot: usize) -> Option<&ConstValue> {
286        Some(self.logic.globals.get(slot)?.as_ref()?)
287    }
288
289    /// Iterate over all static slots in the unit.
290    #[cfg(feature = "cli")]
291    #[inline]
292    pub(crate) fn iter_globals(&self) -> impl Iterator<Item = (usize, Option<&ConstValue>)> + '_ {
293        self.logic
294            .globals
295            .iter()
296            .enumerate()
297            .map(|(slot, init)| (slot, init.as_deref()))
298    }
299}
300
301impl<S> Unit<S>
302where
303    S: UnitStorage,
304{
305    #[inline]
306    pub(crate) fn translate(&self, jump: usize) -> Result<usize, BadJump> {
307        self.logic.storage.translate(jump)
308    }
309
310    /// Get the instruction at the given instruction pointer.
311    #[inline]
312    pub(crate) fn instruction_at(
313        &self,
314        ip: usize,
315    ) -> Result<Option<(Inst, usize)>, BadInstruction> {
316        self.logic.storage.get(ip)
317    }
318
319    /// Iterate over all instructions in order.
320    #[cfg(feature = "emit")]
321    #[inline]
322    pub(crate) fn iter_instructions(&self) -> impl Iterator<Item = (usize, Inst)> + '_ {
323        self.logic.storage.iter()
324    }
325}
326
327/// The kind and necessary information on registered functions.
328#[derive(Debug, Clone, Copy)]
329#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
330#[cfg_attr(feature = "musli02", derive(Decode, Encode), musli(crate = musli_core02))]
331pub(crate) enum UnitFn {
332    /// Instruction offset of a function inside of the unit.
333    Offset {
334        /// Offset of the registered function.
335        offset: usize,
336        /// The way the function is called.
337        call: Call,
338        /// The number of arguments the function takes.
339        args: usize,
340        /// If the offset is a closure, this indicates the number of captures in
341        /// the first argument.
342        captures: Option<usize>,
343    },
344    /// An empty constructor of the type identified by the given hash.
345    EmptyStruct {
346        /// The type hash of the empty.
347        hash: Hash,
348    },
349    /// A tuple constructor of the type identified by the given hash.
350    TupleStruct {
351        /// The type hash of the tuple.
352        hash: Hash,
353        /// The number of arguments the tuple takes.
354        args: usize,
355    },
356}
357
358impl TryClone for UnitFn {
359    #[inline]
360    fn try_clone(&self) -> alloc::Result<Self> {
361        Ok(*self)
362    }
363}
364
365impl fmt::Display for UnitFn {
366    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
367        match self {
368            Self::Offset {
369                offset,
370                call,
371                args,
372                captures,
373            } => {
374                write!(
375                    f,
376                    "offset offset={offset}, call={call}, args={args}, captures={captures:?}"
377                )?;
378            }
379            Self::EmptyStruct { hash } => {
380                write!(f, "unit hash={hash}")?;
381            }
382            Self::TupleStruct { hash, args } => {
383                write!(f, "tuple hash={hash}, args={args}")?;
384            }
385        }
386
387        Ok(())
388    }
389}
390
391#[cfg(test)]
392static_assertions::assert_impl_all!(Unit: Send, Sync);