rune/runtime/value/
dynamic.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
use core::alloc::{Layout, LayoutError};
use core::cell::Cell;
use core::fmt;
use core::mem::{align_of, needs_drop, replace, size_of, take};
use core::ptr::{self, addr_of, addr_of_mut, NonNull};

use rust_alloc::sync::Arc;

use crate::alloc;
use crate::alloc::alloc::{Allocator, Global};
use crate::alloc::fmt::TryWrite;
use crate::hash::Hash;
use crate::runtime::{
    Access, AccessError, BorrowMut, BorrowRef, Formatter, IntoOutput, ProtocolCaller, Rtti,
    RttiKind, RuntimeError, Snapshot, TypeInfo, Value, VmResult,
};

#[derive(Debug)]
pub(crate) enum DynamicTakeError {
    Access(AccessError),
    Alloc(alloc::Error),
}

impl fmt::Display for DynamicTakeError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DynamicTakeError::Access(error) => error.fmt(f),
            DynamicTakeError::Alloc(error) => error.fmt(f),
        }
    }
}

impl core::error::Error for DynamicTakeError {}

impl From<AccessError> for DynamicTakeError {
    fn from(error: AccessError) -> Self {
        Self::Access(error)
    }
}

impl From<alloc::Error> for DynamicTakeError {
    fn from(error: alloc::Error) -> Self {
        Self::Alloc(error)
    }
}

/// A dynamic value defined at runtime.
///
/// This is an allocation-optimized container which allows an interior slice of
/// data `T` to be checked for access and `H` to be immutably accessed inside of
/// a single reference-counted container.
pub struct Dynamic<H, T> {
    shared: NonNull<Shared<H, T>>,
}

impl<H, T> Dynamic<H, T> {
    /// A dynamic value inside of the virtual machine.
    pub(crate) fn new(
        rtti: H,
        it: impl IntoIterator<Item = T, IntoIter: ExactSizeIterator>,
    ) -> alloc::Result<Self> {
        let it = it.into_iter();
        let this = Self::alloc(rtti, it.len())?;

        // Fill out the newly allocated container.
        unsafe {
            let data = Shared::as_data_ptr(this.shared);

            for (i, value) in it.enumerate() {
                data.add(i).write(value);
            }
        }

        Ok(this)
    }

    /// A dynamic value inside of the virtual machine.
    fn alloc(rtti: H, len: usize) -> alloc::Result<Self> {
        let layout = Shared::<H, T>::layout(len)?;

        let shared = Global.allocate(layout)?.cast::<Shared<H, T>>();

        // SAFETY: We've allocated space for both the shared header and the
        // trailing data.
        unsafe {
            shared.write(Shared {
                rtti,
                count: Cell::new(1),
                access: Access::new(),
                len,
                data: [],
            });
        }

        Ok(Self { shared })
    }

    /// Test if the value is sharable.
    #[inline]
    pub(crate) fn is_readable(&self) -> bool {
        // Safety: Since we have a reference to this shared, we know that the
        // inner is available.
        unsafe { self.shared.as_ref().access.is_shared() }
    }

    /// Test if the value is exclusively accessible.
    #[inline]
    pub(crate) fn is_writable(&self) -> bool {
        unsafe { self.shared.as_ref().access.is_exclusive() }
    }

    /// Get access snapshot of shared value.
    #[inline]
    pub(crate) fn snapshot(&self) -> Snapshot {
        // SAFETY: We know that the shared pointer is valid.
        unsafe { self.shared.as_ref().access.snapshot() }
    }

    /// Get the size of the dynamic collection of values.
    #[inline]
    pub(crate) fn len(&self) -> usize {
        // SAFETY: We know that the shared pointer is valid.
        unsafe { self.shared.as_ref().len }
    }

    /// Get runtime type information of the dynamic value.
    #[inline]
    pub(crate) fn rtti(&self) -> &H {
        // SAFETY: We know that the shared pointer is valid.
        unsafe { &self.shared.as_ref().rtti }
    }

    /// Borrow the interior data array by reference.
    #[inline]
    pub(crate) fn borrow_ref(&self) -> Result<BorrowRef<[T]>, AccessError> {
        // SAFETY: We know the layout is valid since it is reference counted.
        unsafe {
            let guard = self.shared.as_ref().access.shared()?;
            let data = Shared::as_data_ptr(self.shared);
            let data = NonNull::slice_from_raw_parts(data, self.shared.as_ref().len);
            Ok(BorrowRef::new(data, guard.into_raw()))
        }
    }

    /// Borrow the interior data array by mutable reference.
    #[inline]
    pub(crate) fn borrow_mut(&self) -> Result<BorrowMut<[T]>, AccessError> {
        // SAFETY: We know the layout is valid since it is reference counted.
        unsafe {
            let guard = self.shared.as_ref().access.exclusive()?;
            let data = Shared::as_data_ptr(self.shared);
            let data = NonNull::slice_from_raw_parts(data, self.shared.as_ref().len);
            Ok(BorrowMut::new(data, guard.into_raw()))
        }
    }

    /// Take the interior value and drop it if necessary.
    #[inline]
    pub(crate) fn drop(self) -> Result<(), AccessError> {
        // SAFETY: We've checked for the appropriate type just above.
        unsafe {
            self.shared.as_ref().access.try_take()?;
            let len = self.shared.as_ref().len;
            Shared::drop_values(self.shared, len);
            Ok(())
        }
    }
}

impl<H, T> Dynamic<H, T>
where
    H: Clone,
{
    /// Take the interior value and return a handle to the taken value.
    pub(crate) fn take(self) -> Result<Self, DynamicTakeError> {
        // SAFETY: We are checking the interior value for access before taking
        // it.
        unsafe {
            self.shared.as_ref().access.try_take()?;
            let len = self.shared.as_ref().len;
            let new = Self::alloc(self.rtti().clone(), len)?;
            let from = Shared::as_data_ptr(self.shared);
            let to = Shared::as_data_ptr(new.shared);
            to.copy_from_nonoverlapping(from, len);
            Ok(new)
        }
    }
}

impl<H, T> Drop for Dynamic<H, T> {
    fn drop(&mut self) {
        // Decrement a shared value.
        unsafe {
            Shared::dec(self.shared);
        }
    }
}

impl<H, T> Clone for Dynamic<H, T> {
    #[inline]
    fn clone(&self) -> Self {
        // SAFETY: We know that the inner value is live in this instance.
        unsafe {
            Shared::inc(self.shared);
        }

        Self {
            shared: self.shared,
        }
    }

    #[inline]
    fn clone_from(&mut self, source: &Self) {
        if ptr::eq(self.shared.as_ptr(), source.shared.as_ptr()) {
            return;
        }

        let old = replace(&mut self.shared, source.shared);

        // SAFETY: We know that the inner value is live in both instances.
        unsafe {
            Shared::dec(old);
            Shared::inc(self.shared);
        }
    }
}

#[repr(C)]
struct Shared<H, T> {
    /// Run time type information of the shared value.
    rtti: H,
    /// Reference count.
    count: Cell<usize>,
    /// Access flags.
    access: Access,
    /// The size of the dynamic value.
    len: usize,
    /// Start of data pointer. Only used for alignment.
    data: [T; 0],
}

impl<H, T> Shared<H, T> {
    #[inline]
    fn layout(len: usize) -> Result<Layout, LayoutError> {
        let array = Layout::array::<T>(len)?;
        Layout::from_size_align(
            size_of::<Shared<H, T>>() + array.size(),
            align_of::<Shared<H, T>>(),
        )
    }

    /// Get the rtti pointer in the shared container.
    #[inline]
    unsafe fn as_rtti_ptr(this: NonNull<Self>) -> NonNull<H> {
        NonNull::new_unchecked(addr_of_mut!((*this.as_ptr()).rtti))
    }

    /// Get the data pointer in the shared container.
    #[inline]
    unsafe fn as_data_ptr(this: NonNull<Self>) -> NonNull<T> {
        NonNull::new_unchecked(addr_of_mut!((*this.as_ptr()).data)).cast::<T>()
    }

    /// Increment the reference count of the inner value.
    #[inline]
    unsafe fn inc(this: NonNull<Self>) {
        let count_ref = &*addr_of!((*this.as_ptr()).count);
        let count = count_ref.get();

        debug_assert_ne!(
            count, 0,
            "Reference count of zero should only happen if Shared is incorrectly implemented"
        );

        if count == usize::MAX {
            crate::alloc::abort();
        }

        count_ref.set(count + 1);
    }

    /// Decrement the reference count in inner, and free the underlying data if
    /// it has reached zero.
    ///
    /// # Safety
    ///
    /// ProtocolCaller needs to ensure that `this` is a valid pointer.
    #[inline]
    unsafe fn dec(this: NonNull<Self>) {
        let count_ref = &*addr_of!((*this.as_ptr()).count);
        let access = &*addr_of!((*this.as_ptr()).access);
        let count = count_ref.get();

        debug_assert_ne!(
            count, 0,
            "Reference count of zero should only happen if Shared is incorrectly implemented"
        );

        let count = count - 1;
        count_ref.set(count);

        if count != 0 {
            return;
        }

        let len = (*this.as_ptr()).len;

        let Ok(layout) = Self::layout(len) else {
            unreachable!();
        };

        if !access.is_taken() {
            Self::drop_values(this, len);
        }

        if needs_drop::<H>() {
            Self::as_rtti_ptr(this).drop_in_place();
        }

        Global.deallocate(this.cast(), layout);
    }

    #[inline]
    unsafe fn drop_values(this: NonNull<Self>, len: usize) {
        if needs_drop::<T>() {
            let data = Self::as_data_ptr(this);
            NonNull::slice_from_raw_parts(data, len).drop_in_place();
        }
    }
}

impl<T> Dynamic<Arc<Rtti>, T> {
    /// Access type hash on the dynamic value.
    #[inline]
    pub(crate) fn type_hash(&self) -> Hash {
        self.rtti().hash
    }

    /// Access type information on the dynamic value.
    #[inline]
    pub(crate) fn type_info(&self) -> TypeInfo {
        self.rtti().clone().type_info()
    }

    /// Access a field by name.
    #[inline]
    pub(crate) fn get_field_ref(&self, key: &str) -> Result<Option<BorrowRef<'_, T>>, AccessError> {
        let Some(index) = self.rtti().fields.get(key) else {
            return Ok(None);
        };

        self.get_ref(*index)
    }

    /// Access a field mutably by name.
    #[inline]
    pub(crate) fn get_field_mut(&self, key: &str) -> Result<Option<BorrowMut<'_, T>>, AccessError> {
        let Some(index) = self.rtti().fields.get(key) else {
            return Ok(None);
        };

        self.get_mut(*index)
    }

    /// Access a field by index.
    #[inline]
    pub(crate) fn get_ref(&self, index: usize) -> Result<Option<BorrowRef<'_, T>>, AccessError> {
        // SAFETY: We know the layout is valid since it is reference counted.
        unsafe {
            let shared = self.shared.as_ref();

            if index >= shared.len {
                return Ok(None);
            }

            let guard = shared.access.shared()?;
            let data = Shared::as_data_ptr(self.shared).add(index);
            Ok(Some(BorrowRef::new(data, guard.into_raw())))
        }
    }

    /// Access a field mutably by index.
    #[inline]
    pub(crate) fn get_mut(&self, index: usize) -> Result<Option<BorrowMut<'_, T>>, AccessError> {
        // SAFETY: We know the layout is valid since it is reference counted.
        unsafe {
            let shared = self.shared.as_ref();

            if index >= shared.len {
                return Ok(None);
            }

            let guard = shared.access.exclusive()?;
            let data = Shared::as_data_ptr(self.shared).add(index);
            Ok(Some(BorrowMut::new(data, guard.into_raw())))
        }
    }
}

impl Dynamic<Arc<Rtti>, Value> {
    /// Debug print the dynamic value.
    pub(crate) fn debug_fmt_with(
        &self,
        f: &mut Formatter,
        caller: &mut dyn ProtocolCaller,
    ) -> VmResult<()> {
        let rtti = self.rtti();
        let values = vm_try!(self.borrow_ref());

        match rtti.kind {
            RttiKind::Empty => debug_empty(rtti, f),
            RttiKind::Tuple => debug_tuple(rtti, &values, f, caller),
            RttiKind::Struct => debug_struct(rtti, &values, f, caller),
        }
    }
}

fn debug_empty(rtti: &Rtti, f: &mut Formatter) -> VmResult<()> {
    vm_try!(write!(f, "{}", rtti.item));
    VmResult::Ok(())
}

fn debug_tuple(
    rtti: &Rtti,
    values: &[Value],
    f: &mut Formatter,
    caller: &mut dyn ProtocolCaller,
) -> VmResult<()> {
    vm_try!(write!(f, "{} (", rtti.item));

    let mut first = true;

    for value in values.iter() {
        if !take(&mut first) {
            vm_try!(write!(f, ", "));
        }

        vm_try!(value.debug_fmt_with(f, caller));
    }

    vm_try!(write!(f, ")"));
    VmResult::Ok(())
}

fn debug_struct(
    rtti: &Rtti,
    values: &[Value],
    f: &mut Formatter,
    caller: &mut dyn ProtocolCaller,
) -> VmResult<()> {
    vm_try!(write!(f, "{} {{", rtti.item));

    let mut first = true;

    for (index, field) in values.iter().enumerate() {
        let Some((name, _)) = rtti.fields.iter().find(|t| *t.1 == index) else {
            continue;
        };

        if !take(&mut first) {
            vm_try!(write!(f, ", "));
        }

        vm_try!(write!(f, "{name}: "));
        vm_try!(field.debug_fmt_with(f, caller));
    }

    vm_try!(write!(f, "}}"));
    VmResult::Ok(())
}

impl IntoOutput for Dynamic<Arc<Rtti>, Value> {
    #[inline]
    fn into_output(self) -> Result<Value, RuntimeError> {
        Ok(Value::from(self))
    }
}