1#[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#[cfg(not(rune_byte_code))]
39pub type DefaultStorage = ArrayUnit;
40#[cfg(rune_byte_code)]
42pub type DefaultStorage = ByteCodeUnit;
43
44#[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 #[cfg_attr(feature = "serde", serde(flatten))]
56 logic: Logic<S>,
57 debug: Option<Box<DebugInfo>>,
59}
60
61assert_impl!(Unit<DefaultStorage>: Send + Sync);
62
63#[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: S,
75 functions: hash::Map<UnitFn>,
77 static_strings: Vec<Arc<StaticString>>,
79 static_bytes: Vec<Vec<u8>>,
81 static_object_keys: Vec<Box<[String]>>,
88 drop_sets: Vec<Arc<[Address]>>,
90 rtti: hash::Map<Arc<Rtti>>,
92 constants: hash::Map<ConstValueBuf>,
94 globals: Vec<Option<ConstValueBuf>>,
98 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 #[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 #[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 #[inline]
154 pub fn logic(&self) -> &Logic<S> {
155 &self.logic
156 }
157
158 #[inline]
160 pub fn debug_info(&self) -> Option<&DebugInfo> {
161 Some(&**self.debug.as_ref()?)
162 }
163
164 #[inline]
166 pub(crate) fn instructions(&self) -> &S {
167 &self.logic.storage
168 }
169
170 #[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 #[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 #[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 #[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 #[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 #[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 #[inline]
224 pub(crate) fn lookup_string(&self, slot: usize) -> Option<&Arc<StaticString>> {
225 self.logic.static_strings.get(slot)
226 }
227
228 #[inline]
230 pub(crate) fn lookup_bytes(&self, slot: usize) -> Option<&[u8]> {
231 Some(self.logic.static_bytes.get(slot)?)
232 }
233
234 #[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 #[inline]
247 pub(crate) fn lookup_rtti(&self, hash: &Hash) -> Option<&Arc<Rtti>> {
248 self.logic.rtti.get(hash)
249 }
250
251 #[inline]
253 pub(crate) fn function(&self, hash: &Hash) -> Option<&UnitFn> {
254 self.logic.functions.get(hash)
255 }
256
257 #[inline]
259 pub(crate) fn constant(&self, hash: &Hash) -> Option<&ConstValue> {
260 Some(self.logic.constants.get(hash)?)
261 }
262
263 #[inline]
270 pub fn globals_len(&self) -> usize {
271 self.logic.globals.len()
272 }
273
274 #[inline]
279 pub fn global_slot(&self, hash: &Hash) -> Option<usize> {
280 self.logic.globals_rev.get(hash).copied()
281 }
282
283 #[inline]
285 pub(crate) fn global_init(&self, slot: usize) -> Option<&ConstValue> {
286 Some(self.logic.globals.get(slot)?.as_ref()?)
287 }
288
289 #[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 #[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 #[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#[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 Offset {
334 offset: usize,
336 call: Call,
338 args: usize,
340 captures: Option<usize>,
343 },
344 EmptyStruct {
346 hash: Hash,
348 },
349 TupleStruct {
351 hash: Hash,
353 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);