1use std::{
2 any::Any,
3 fmt,
4 marker::PhantomData,
5 ops::Deref,
6 rc::Rc,
7 sync::atomic::{AtomicU32, Ordering},
8};
9
10use crate::{MiraError, Result, Runtime, RuntimeErrorKind};
11
12use super::{MiraArray, MiraFunction, MiraModule, MiraRecord, MiraValue};
13
14static NEXT_ARENA_ID: AtomicU32 = AtomicU32::new(1);
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17struct ArenaKey(u64);
18
19impl ArenaKey {
20 fn new(arena_id: u32, index: usize, category: &'static str) -> Result<Self> {
21 let index = u32::try_from(index)
22 .ok()
23 .and_then(|index| index.checked_add(1))
24 .ok_or_else(|| MiraError::runtime(RuntimeErrorKind::ArenaExhausted { category }))?;
25 Ok(Self((u64::from(arena_id) << 32) | u64::from(index)))
26 }
27
28 fn arena_id(self) -> u32 {
29 (self.0 >> 32) as u32
30 }
31
32 fn index(self) -> usize {
33 ((self.0 as u32) - 1) as usize
34 }
35}
36
37#[derive(Debug)]
38struct Arena<T> {
39 values: Vec<T>,
40}
41
42impl<T> Arena<T> {
43 fn new() -> Self {
44 Self { values: Vec::new() }
45 }
46
47 fn insert(&mut self, arena_id: u32, category: &'static str, value: T) -> Result<ArenaKey> {
48 let key = ArenaKey::new(arena_id, self.values.len(), category)?;
49 self.values.push(value);
50 Ok(key)
51 }
52
53 fn get(&self, arena_id: u32, category: &'static str, key: ArenaKey) -> Result<&T> {
54 if key.arena_id() != arena_id {
55 return Err(MiraError::runtime(RuntimeErrorKind::ForeignHandle));
56 }
57 self.values
58 .get(key.index())
59 .ok_or_else(|| MiraError::runtime(RuntimeErrorKind::InvalidHandle { category }))
60 }
61
62 fn get_mut(&mut self, arena_id: u32, category: &'static str, key: ArenaKey) -> Result<&mut T> {
63 if key.arena_id() != arena_id {
64 return Err(MiraError::runtime(RuntimeErrorKind::ForeignHandle));
65 }
66 self.values
67 .get_mut(key.index())
68 .ok_or_else(|| MiraError::runtime(RuntimeErrorKind::InvalidHandle { category }))
69 }
70}
71
72pub struct MiraHandle<T: Any + ?Sized> {
74 key: ArenaKey,
75 marker: PhantomData<&'static T>,
76}
77
78impl<T: Any + ?Sized> Copy for MiraHandle<T> {}
79
80impl<T: Any + ?Sized> Clone for MiraHandle<T> {
81 fn clone(&self) -> Self {
82 *self
83 }
84}
85
86impl<T: Any + ?Sized> fmt::Debug for MiraHandle<T> {
87 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
88 formatter
89 .debug_struct("MiraHandle")
90 .field("arena", &self.key.arena_id())
91 .field("slot", &self.key.index())
92 .finish()
93 }
94}
95
96impl<T: Any + ?Sized> PartialEq for MiraHandle<T> {
97 fn eq(&self, other: &Self) -> bool {
98 self.key == other.key
99 }
100}
101
102impl<T: Any + ?Sized> Eq for MiraHandle<T> {}
103
104impl<T: Any + ?Sized> std::hash::Hash for MiraHandle<T> {
105 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
106 self.key.hash(state);
107 }
108}
109
110impl<T: Any + ?Sized> MiraHandle<T> {
111 fn new(key: ArenaKey) -> Self {
112 Self {
113 key,
114 marker: PhantomData,
115 }
116 }
117}
118
119macro_rules! impl_handle_cast {
120 ($trait:path, $erase:ident) => {
121 impl<T: $trait> MiraHandle<T> {
122 pub fn $erase(self) -> MiraHandle<dyn $trait> {
124 MiraHandle::new(self.key)
125 }
126 }
127
128 impl MiraHandle<dyn $trait> {
129 #[doc(hidden)]
135 pub unsafe fn upcast<T: $trait>(self) -> MiraHandle<T> {
136 MiraHandle::new(self.key)
137 }
138 }
139 };
140}
141
142impl_handle_cast!(MiraArray, erase_array);
143impl_handle_cast!(MiraRecord, erase_record);
144impl_handle_cast!(MiraFunction, erase_function);
145impl_handle_cast!(MiraModule, erase_module);
146
147pub enum MiraManageable {
149 Value(MiraValue),
151 String(String),
153 Array(Box<dyn MiraArray>),
155 Record(Box<dyn MiraRecord>),
157 Function(Rc<dyn MiraFunction>),
159 Module(Box<dyn MiraModule>),
161}
162
163impl From<MiraValue> for MiraManageable {
164 fn from(value: MiraValue) -> Self {
165 Self::Value(value)
166 }
167}
168
169impl From<String> for MiraManageable {
170 fn from(value: String) -> Self {
171 Self::String(value)
172 }
173}
174
175impl From<&str> for MiraManageable {
176 fn from(value: &str) -> Self {
177 Self::String(value.to_owned())
178 }
179}
180
181impl MiraManageable {
182 pub fn from_array(value: impl MiraArray) -> Self {
184 Self::Array(Box::new(value))
185 }
186
187 pub fn from_record(value: impl MiraRecord) -> Self {
189 Self::Record(Box::new(value))
190 }
191
192 pub fn from_function(value: impl MiraFunction) -> Self {
194 Self::Function(Rc::new(value))
195 }
196
197 pub fn from_module(value: impl MiraModule) -> Self {
199 Self::Module(Box::new(value))
200 }
201
202 pub fn map_module(
204 name: impl Into<String>,
205 values: indexmap::IndexMap<String, MiraValue>,
206 ) -> Self {
207 crate::value::types::map_module(name, values)
208 }
209}
210
211pub(crate) struct MiraArena {
212 id: u32,
213 strings: Arena<String>,
214 arrays: Arena<Box<dyn MiraArray>>,
215 records: Arena<Box<dyn MiraRecord>>,
216 functions: Arena<Rc<dyn MiraFunction>>,
217 modules: Arena<Box<dyn MiraModule>>,
218}
219
220impl MiraArena {
221 pub(crate) fn new() -> Self {
222 let id = NEXT_ARENA_ID.fetch_add(1, Ordering::Relaxed);
223 assert_ne!(id, 0, "MiraScript arena identifier space exhausted");
224 Self {
225 id,
226 strings: Arena::new(),
227 arrays: Arena::new(),
228 records: Arena::new(),
229 functions: Arena::new(),
230 modules: Arena::new(),
231 }
232 }
233}
234
235impl Runtime {
236 pub fn insert(&mut self, value: impl Into<MiraManageable>) -> Result<MiraValue> {
238 match value.into() {
239 MiraManageable::Value(value) => {
240 self.validate_value(value)?;
241 Ok(value)
242 }
243 MiraManageable::String(value) => Ok(MiraValue::String(self.insert_string(value)?)),
244 MiraManageable::Array(value) => {
245 let key = self.arena.arrays.insert(self.arena.id, "array", value)?;
246 Ok(MiraValue::Array(MiraHandle::new(key)))
247 }
248 MiraManageable::Record(value) => {
249 let key = self.arena.records.insert(self.arena.id, "record", value)?;
250 Ok(MiraValue::Record(MiraHandle::new(key)))
251 }
252 MiraManageable::Function(value) => {
253 let key = self
254 .arena
255 .functions
256 .insert(self.arena.id, "function", value)?;
257 Ok(MiraValue::Function(MiraHandle::new(key)))
258 }
259 MiraManageable::Module(value) => {
260 let key = self.arena.modules.insert(self.arena.id, "module", value)?;
261 Ok(MiraValue::Module(MiraHandle::new(key)))
262 }
263 }
264 }
265
266 pub fn insert_string(&mut self, value: impl Into<String>) -> Result<MiraHandle<String>> {
268 let key = self
269 .arena
270 .strings
271 .insert(self.arena.id, "string", value.into())?;
272 Ok(MiraHandle::new(key))
273 }
274
275 pub fn get_string(&self, handle: MiraHandle<String>) -> Result<&str> {
277 self.arena
278 .strings
279 .get(self.arena.id, "string", handle.key)
280 .map(Deref::deref)
281 }
282
283 pub fn get_string_mut(&mut self, handle: MiraHandle<String>) -> Result<&mut String> {
285 self.arena
286 .strings
287 .get_mut(self.arena.id, "string", handle.key)
288 }
289
290 pub fn insert_array<T: MiraArray>(&mut self, value: T) -> Result<MiraHandle<T>> {
292 let key = self
293 .arena
294 .arrays
295 .insert(self.arena.id, "array", Box::new(value))?;
296 Ok(MiraHandle::new(key))
297 }
298
299 pub fn insert_record<T: MiraRecord>(&mut self, value: T) -> Result<MiraHandle<T>> {
301 let key = self
302 .arena
303 .records
304 .insert(self.arena.id, "record", Box::new(value))?;
305 Ok(MiraHandle::new(key))
306 }
307
308 pub fn insert_function<T: MiraFunction>(&mut self, value: T) -> Result<MiraHandle<T>> {
310 let key = self
311 .arena
312 .functions
313 .insert(self.arena.id, "function", Rc::new(value))?;
314 Ok(MiraHandle::new(key))
315 }
316
317 pub fn insert_module<T: MiraModule>(&mut self, value: T) -> Result<MiraHandle<T>> {
319 let key = self
320 .arena
321 .modules
322 .insert(self.arena.id, "module", Box::new(value))?;
323 Ok(MiraHandle::new(key))
324 }
325
326 pub(crate) fn get_array_dyn(
327 &self,
328 handle: MiraHandle<dyn MiraArray>,
329 ) -> Result<&dyn MiraArray> {
330 self.arena
331 .arrays
332 .get(self.arena.id, "array", handle.key)
333 .map(|value| value.as_ref())
334 }
335
336 pub(crate) fn get_record_dyn(
337 &self,
338 handle: MiraHandle<dyn MiraRecord>,
339 ) -> Result<&dyn MiraRecord> {
340 self.arena
341 .records
342 .get(self.arena.id, "record", handle.key)
343 .map(|value| value.as_ref())
344 }
345
346 pub(crate) fn get_function_dyn(
347 &self,
348 handle: MiraHandle<dyn MiraFunction>,
349 ) -> Result<Rc<dyn MiraFunction>> {
350 self.arena
351 .functions
352 .get(self.arena.id, "function", handle.key)
353 .map(Rc::clone)
354 }
355
356 pub(crate) fn get_module_dyn(
357 &self,
358 handle: MiraHandle<dyn MiraModule>,
359 ) -> Result<&dyn MiraModule> {
360 self.arena
361 .modules
362 .get(self.arena.id, "module", handle.key)
363 .map(|value| value.as_ref())
364 }
365
366 pub fn get_array<T: MiraArray>(&self, handle: MiraHandle<T>) -> Result<&T> {
368 let value = self.arena.arrays.get(self.arena.id, "array", handle.key)?;
369 let value: &dyn Any = value.resolve(self)?.unwrap_or(value.as_ref());
370 value.downcast_ref::<T>().ok_or_else(|| {
371 MiraError::runtime(RuntimeErrorKind::HandleTypeMismatch { category: "array" })
372 })
373 }
374
375 pub fn get_array_mut<T: MiraArray>(&mut self, handle: MiraHandle<T>) -> Result<&mut T> {
377 let value = self
378 .arena
379 .arrays
380 .get_mut(self.arena.id, "array", handle.key)?;
381 let value: &mut dyn Any = value.as_mut();
382 value.downcast_mut::<T>().ok_or_else(|| {
383 MiraError::runtime(RuntimeErrorKind::HandleTypeMismatch { category: "array" })
384 })
385 }
386
387 pub fn get_record<T: MiraRecord>(&self, handle: MiraHandle<T>) -> Result<&T> {
389 let value = self
390 .arena
391 .records
392 .get(self.arena.id, "record", handle.key)?;
393 let value: &dyn Any = value.resolve(self)?.unwrap_or(value.as_ref());
394 value.downcast_ref::<T>().ok_or_else(|| {
395 MiraError::runtime(RuntimeErrorKind::HandleTypeMismatch { category: "record" })
396 })
397 }
398
399 pub fn get_record_mut<T: MiraRecord>(&mut self, handle: MiraHandle<T>) -> Result<&mut T> {
401 let value = self
402 .arena
403 .records
404 .get_mut(self.arena.id, "record", handle.key)?;
405 let value: &mut dyn Any = value.as_mut();
406 value.downcast_mut::<T>().ok_or_else(|| {
407 MiraError::runtime(RuntimeErrorKind::HandleTypeMismatch { category: "record" })
408 })
409 }
410
411 pub fn get_function<T: MiraFunction>(&self, handle: MiraHandle<T>) -> Result<&T> {
413 let value = self
414 .arena
415 .functions
416 .get(self.arena.id, "function", handle.key)?;
417 let value: &dyn Any = value.as_ref();
418 value.downcast_ref::<T>().ok_or_else(|| {
419 MiraError::runtime(RuntimeErrorKind::HandleTypeMismatch {
420 category: "function",
421 })
422 })
423 }
424
425 pub fn get_module<T: MiraModule>(&self, handle: MiraHandle<T>) -> Result<&T> {
427 let value = self
428 .arena
429 .modules
430 .get(self.arena.id, "module", handle.key)?;
431 let value: &dyn Any = value.as_ref();
432 value.downcast_ref::<T>().ok_or_else(|| {
433 MiraError::runtime(RuntimeErrorKind::HandleTypeMismatch { category: "module" })
434 })
435 }
436
437 pub fn get_module_mut<T: MiraModule>(&mut self, handle: MiraHandle<T>) -> Result<&mut T> {
439 let value = self
440 .arena
441 .modules
442 .get_mut(self.arena.id, "module", handle.key)?;
443 let value: &mut dyn Any = value.as_mut();
444 value.downcast_mut::<T>().ok_or_else(|| {
445 MiraError::runtime(RuntimeErrorKind::HandleTypeMismatch { category: "module" })
446 })
447 }
448
449 pub(crate) fn validate_value(&self, value: MiraValue) -> Result<()> {
450 match value {
451 MiraValue::String(handle) => self.get_string(handle).map(|_| ()),
452 MiraValue::Array(handle) => self.get_array_dyn(handle).map(|_| ()),
453 MiraValue::Record(handle) => self.get_record_dyn(handle).map(|_| ()),
454 MiraValue::Function(handle) => self.get_function_dyn(handle).map(|_| ()),
455 MiraValue::Module(handle) => self.get_module_dyn(handle).map(|_| ()),
456 MiraValue::Extern(_) => Err(MiraError::runtime(RuntimeErrorKind::InvalidHandle {
457 category: "extern",
458 })),
459 MiraValue::Nil
460 | MiraValue::Boolean(_)
461 | MiraValue::Number(_)
462 | MiraValue::StaticStr(_) => Ok(()),
463 }
464 }
465}