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
pub mod exception;
pub mod generic;
pub mod traits;
pub mod tyck;
pub mod value_typed;
pub mod wrapper;

use std::marker::PhantomData;
use std::mem::{MaybeUninit, transmute};

use unchecked_unwrap::UncheckedUnwrap;
use xjbutil::mem::move_to_heap;
use xjbutil::unchecked::UnsafeFrom;
use xjbutil::void::Void;
use xjbutil::wide_ptr::WidePointer;

use crate::data::generic::{GENERIC_TYPE_MASK, GenericTypeVT};
use crate::data::traits::StaticBase;
use crate::data::value_typed::{VALUE_TYPE_MASK, ValueTypedData};
use crate::data::wrapper::{DynBase, OwnershipInfo, Wrapper};

#[cfg(any(test, feature = "bench"))]
use std::fmt::{Debug, Formatter};
#[cfg(any(test, feature = "bench"))]
use crate::data::value_typed::{VALUE_TYPE_TAG_MASK, ValueTypeTag};

pub const TAG_BITS_MASK: u8 = 0b00000_111;
pub const TAG_BITS_MASK_USIZE: usize = TAG_BITS_MASK as usize;

pub const PTR_BITS_MASK: u8 = !TAG_BITS_MASK;
pub const PTR_BITS_MASK_USIZE: usize = !TAG_BITS_MASK_USIZE;

/// A generic stack value of Pr47. A stack value may be
///   * A *value-typed data*, see `pr47::data::value_typed::ValueTypedData`
///   * A *normal reference* to "heap" object, see `pr47::data::wrapper::DynBase`
///   * A *custom pointer* to container objects created in Pr47 VM, see
///     `pr47::data::wrapper::custom_vt::ContainerVT`
///
/// A normal reference may be either *owned*, or *shared/mutably shared from Rust*. Check
/// documentation of `pr47::data::wrapper::Wrapper` for more information. A custom pointer should
/// never be shared from Rust, since it is only used when creating containers from Pr47 VM.
///
/// Pr47 uses tagged pointers to distinguish these three kinds of values:
///
/// ```text
/// +-----------------------------+
/// |         WidePointer         |
/// +--------------+--------------+
/// |      ptr     |  vtable/len  |
/// +-------|------+--------------+
///         |
///         |
/// +------------------------------+---+---+---+
/// |        PTR-BITS ... 3        | 2 | 1 | 0 |
/// +------------------------------+---+---+---+
/// | 8 byte aligned pointer value | U | C | V |
/// +------------------------------+---+---+---+
/// ```
///
///   * `U`: Unused
///   * `C`: Container
///   * `V`: Value-typed
///
/// Since `pr47::data::wrapper::Wrapper` is 8 byte aligned, it is safe to use such a tagged-pointer
#[repr(C)]
#[derive(Clone, Copy)]
pub union Value {
    pub ptr: *mut dyn DynBase,
    pub ptr_repr: WidePointer,
    pub vt_data: ValueTypedData,
}

impl Value {
    /// Create a new "owned" `Value`
    pub fn new_owned<T>(data: T) -> Self
        where T: 'static,
              Void: StaticBase<T>
    {
        Self {
            ptr: move_to_heap(Wrapper::new_owned(data)).as_ptr()
        }
    }

    pub fn new_container(wrapper: *mut Wrapper<()>, vt: *const GenericTypeVT) -> Self {
        let ptr: usize = (wrapper as usize) | (GENERIC_TYPE_MASK as usize);
        let trivia: usize = vt as _;

        Self {
            ptr_repr: WidePointer {
                ptr, trivia
            }
        }
    }

    /// Create a new "shared" `Value`
    pub fn new_shared<T>(data: &T) -> Self
        where T: 'static,
              Void: StaticBase<T>
    {
        Self {
            ptr: move_to_heap(Wrapper::new_ref(data as *const T)).as_ptr()
        }
    }

    /// Create a new "mutably shared" `Value`
    pub fn new_mut_shared<T>(data: &mut T) -> Self
        where T: 'static,
              Void: StaticBase<T>
    {
        Self {
            ptr: move_to_heap(Wrapper::new_mut_ref(data as *mut T)).as_ptr()
        }
    }

    #[inline(always)] pub fn new_raw_value(tag: usize, repr: u64) -> Self {
        Self {
            vt_data: ValueTypedData::new_raw(tag, repr)
        }
    }

    /// Create a new integer `Value`
    #[inline(always)] pub fn new_int(int_value: i64) -> Self {
        Self {
            vt_data: ValueTypedData::from(int_value)
        }
    }

    /// Create a new floating point number `Value`
    #[inline(always)] pub fn new_float(float_value: f64) -> Self {
        Self {
            vt_data: ValueTypedData::from(float_value)
        }
    }

    /// Create a new character `Value`
    #[inline(always)] pub fn new_char(char_value: char) -> Self {
        Self {
            vt_data: ValueTypedData::from(char_value)
        }
    }

    /// Create a new boolean `Value`
    #[inline(always)] pub fn new_bool(bool_value: bool) -> Self {
        Self {
            vt_data: ValueTypedData::from(bool_value)
        }
    }

    /// Create a new `null` `Value`
    #[inline(always)] pub const fn new_null() -> Self {
        Self {
            ptr_repr: WidePointer::new(0, 0)
        }
    }

    /// Check if a `Value` is `null`.
    pub fn is_null(&self) -> bool {
        unsafe { self.ptr_repr.ptr == 0 }
    }

    /// Check if a `Value` is value-typed
    pub fn is_value(&self) -> bool {
        unsafe {
            self.ptr_repr.ptr & (VALUE_TYPE_MASK as usize) != 0
        }
    }

    /// Check if a `Value` is reference-typed
    pub fn is_ref(&self) -> bool {
        unsafe {
            self.ptr_repr.ptr & (VALUE_TYPE_MASK as usize) == 0
        }
    }

    /// Check if a `Value` is a custom pointer
    pub fn is_container(&self) -> bool {
        unsafe {
            self.ptr_repr.ptr & (GENERIC_TYPE_MASK as usize) != 0
        }
    }

    /// Assuming that `self` may be a custom pointer, get the untagged pointer
    #[inline(always)] pub unsafe fn untagged_ptr_field(&self) -> usize {
        self.ptr_repr.ptr & !TAG_BITS_MASK_USIZE
    }

    /// Assuming that `self` may be a custom pointer, get the reference counting
    pub unsafe fn ref_count(&self) -> u32 {
        #[cfg(debug_assertions)] self.assert_shared();
        *(self.untagged_ptr_field() as *const u32)
    }

    /// Given that `self` **MUST NOT** be a custom pointer, get the reference counting
    pub unsafe fn ref_count_norm(&self) -> u32 {
        #[cfg(debug_assertions)] self.assert_shared();
        debug_assert!(!self.is_container());
        *(self.ptr_repr.ptr as *const u32)
    }

    /// Assuming that `self` may be a custom pointer, increase the reference counting
    pub unsafe fn incr_ref_count(&self) {
        #[cfg(debug_assertions)] self.assert_shared();
        *(self.untagged_ptr_field() as *mut u32) += 1
    }

    /// Given that `self` **MUST NOT** be a custom pointer, increase the reference counting
    pub unsafe fn incr_ref_count_norm(&self) {
        #[cfg(debug_assertions)] self.assert_shared();
        debug_assert!(!self.is_container());
        *(self.ptr_repr.ptr as *mut u32) += 1
    }

    /// Assuming that `self` may be a custom pointer, decrease the reference counting
    pub unsafe fn decr_ref_count(&self) {
        #[cfg(debug_assertions)] self.assert_shared();
        *(self.untagged_ptr_field() as *mut u32) -= 1
    }

    /// Given that `self` **MUST NOT** be a custom pointer, decrease the reference counting
    pub unsafe fn decr_ref_count_norm(&self) {
        #[cfg(debug_assertions)] self.assert_shared();
        debug_assert!(!self.is_container());
        *(self.ptr_repr.ptr as *mut u32) -= 1
    }

    /// Assert `self` to be in a shared status, thus the reference-counting field of `self`
    /// is valid.
    #[cfg(debug_assertions)]
    fn assert_shared(&self) {
        let ownership_info: OwnershipInfo = unsafe { self.ownership_info() };
        assert!(ownership_info == OwnershipInfo::SharedFromRust
                || ownership_info == OwnershipInfo::SharedToRust);
    }

    /// Given that `self` **MUST** be a reference, assuming that `self` may be a custom pointer, get
    /// the ownership info
    pub unsafe fn ownership_info(&self) -> OwnershipInfo {
        debug_assert!(self.is_ref());
        UnsafeFrom::unsafe_from(*((self.untagged_ptr_field() + 4usize) as *const u8))
    }

    /// Given that `self` **MUST** be a reference and **MUST NOT** be a custom pointer, get the
    /// ownership info
    #[cfg_attr(not(debug_assertions), inline(always))]
    pub unsafe fn ownership_info_norm(&self) -> OwnershipInfo {
        debug_assert!(self.is_ref());
        debug_assert!(!self.is_container());
        UnsafeFrom::unsafe_from(*((self.ptr_repr.ptr + 4usize) as *const u8))
    }

    /// Given that `self` **MUST** be a reference, assuming that `self` may be a custom pointer,
    /// set the ownership info
    pub unsafe fn set_ownership_info(&self, ownership_info: OwnershipInfo) {
        debug_assert!(self.is_ref());
        *((self.untagged_ptr_field() + 4usize) as *mut u8) = ownership_info as u8;
    }

    /// Given that `self` **MUST** be a reference and **MUST NOT** be a custom pointer, set the
    /// ownership info
    pub unsafe fn set_ownership_info_norm(&self, ownership_info: OwnershipInfo) {
        debug_assert!(self.is_ref());
        debug_assert!(!self.is_container());
        *((self.ptr_repr.ptr + 4usize) as *mut u8) = ownership_info as u8;
    }

    /// Given that `self` **MUST** be a reference, assuming that `self` may be a custom pointer,
    /// get the GC information
    pub unsafe fn gc_info(&self) -> u8 {
        debug_assert!(self.is_ref());
        *((self.untagged_ptr_field() + 5usize) as *mut u8)
    }

    /// Given that `self` **MUST** be a reference and **MUST NOT** be a custom pointer, get the
    /// GC information
    pub unsafe fn gc_info_norm(&self) -> u8 {
        debug_assert!(self.is_ref());
        debug_assert!(!self.is_container());
        *((self.ptr_repr.ptr + 5usize) as *mut u8)
    }

    /// Given that `self` **MUST** be a reference, assuming that `self` may be a custom pointer,
    /// set the GC information
    pub unsafe fn set_gc_info(&self, gc_info: u8) {
        debug_assert!(self.is_ref());
        *((self.untagged_ptr_field() + 5usize) as *mut u8) = gc_info;
    }

    /// Given that `self` **MUST** be a reference and **MUST BOT** be a custom pointer, set the GC
    /// information
    #[cfg_attr(not(debug_assertions), inline)]
    pub unsafe fn set_gc_info_norm(&self, gc_info: u8) {
        debug_assert!(self.is_ref());
        debug_assert!(!self.is_container());
        *((self.ptr_repr.ptr + 5usize) as *mut u8) = gc_info;
    }

    #[cfg_attr(not(debug_assertions), inline)]
    pub unsafe fn get_as_dyn_base(&self) -> *mut dyn DynBase {
        debug_assert!(self.is_ref());
        debug_assert!(!self.is_container());
        transmute::<WidePointer, &mut dyn DynBase>(self.ptr_repr)
    }

    /// Given that `self` **MUST** be a reference, assuming that `self` may be a custom pointer,
    /// get a pointer to the referenced data
    #[cfg_attr(not(debug_assertions), inline)]
    pub unsafe fn get_as_mut_ptr<T>(&self) -> *mut T
        where T: 'static,
              Void: StaticBase<T>
    {
        debug_assert!(self.ownership_info().is_readable());
        let data_offset: usize = *((self.untagged_ptr_field() + 6usize) as *mut u8) as usize;
        if self.ownership_info().is_owned() {
            (self.untagged_ptr_field() + data_offset as usize) as *mut T
        } else {
            let ptr: *const *mut T = (self.untagged_ptr_field() + data_offset) as *const *mut T;
            *ptr
        }
    }

    /// Given that `self` **MUST** be a reference and **MUST NOT** be a custom pointer, get a
    /// pointer to the referenced data
    #[cfg_attr(not(debug_assertions), inline)]
    pub unsafe fn get_as_mut_ptr_norm<T>(&self) -> *mut T
        where T: 'static,
              Void: StaticBase<T>
    {
        debug_assert!(self.ownership_info().is_readable());
        let data_offset: usize = *((self.ptr_repr.ptr + 6usize) as *mut u8) as usize;
        if self.ownership_info_norm().is_owned() {
            (self.ptr_repr.ptr + data_offset as usize) as *mut T
        } else {
            let ptr: *const *mut T = (self.ptr_repr.ptr + data_offset) as *const *mut T;
            *ptr
        }
    }

    /// Given that `self` **MUST** be a reference to `T` typed VM-owned data, assuming that `self`
    /// may be a custom pointer, move the referenced data out
    pub unsafe fn move_out<T>(&self) -> T
        where T: 'static,
              Void: StaticBase<T>
    {
        debug_assert!(self.is_ref());
        let mut maybe_uninit: MaybeUninit<T> = MaybeUninit::uninit();
        if !self.is_container() {
            let dyn_base: *mut dyn DynBase = self.ptr;
            #[cfg(debug_assertions)]
            dyn_base.as_mut().unchecked_unwrap().move_out_ck(
                &mut maybe_uninit as *mut _ as *mut (),
                <Void as StaticBase<T>>::type_id()
            );
            #[cfg(not(debug_assertions))]
            dyn_base.as_mut().unchecked_unwrap().move_out(
                &mut maybe_uninit as *mut _ as *mut ()
            );
        } else {
            let this_ptr: *mut () = self.untagged_ptr_field() as *mut ();
            let custom_vt: *const GenericTypeVT = self.ptr_repr.trivia as *const _;

            #[cfg(debug_assertions)]
            (custom_vt.as_ref().unchecked_unwrap().move_out_fn) (
                this_ptr,
                &mut maybe_uninit as *mut _ as *mut (),
                <Void as StaticBase<T>>::type_id()
            );
            #[cfg(not(debug_assertions))]
            (custom_vt.as_ref().unchecked_unwrap().move_out_fn) (
                this_ptr,
                &mut maybe_uninit as *mut _ as *mut (),
            );
        }
        maybe_uninit.assume_init()
    }

    /// Given that `self` **MUST** be a reference to `T` typed VM-owned data, and **MUST NOT** be a
    /// custom pointer, move out the referenced data out
    pub unsafe fn move_out_norm<T>(&self) -> T
        where T: 'static,
              Void: StaticBase<T>
    {
        debug_assert!(self.is_ref());
        debug_assert!(!self.is_container());
        let mut maybe_uninit: MaybeUninit<T> = MaybeUninit::uninit();
        let dyn_base: *mut dyn DynBase = self.ptr;
        #[cfg(debug_assertions)]
        dyn_base.as_mut().unchecked_unwrap().move_out_ck(
            &mut maybe_uninit as *mut _ as *mut (),
            <Void as StaticBase<T>>::type_id()
        );
        #[cfg(not(debug_assertions))]
            dyn_base.as_mut().unchecked_unwrap().move_out(
            &mut maybe_uninit as *mut _ as *mut ()
        );
        maybe_uninit.assume_init()
    }
}

#[cfg(any(test, feature = "bench"))]
impl Debug for Value {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        if self.is_value() {
            unsafe {
                match ValueTypeTag::unsafe_from((self.vt_data.tag as u8) & VALUE_TYPE_TAG_MASK) {
                    ValueTypeTag::Int => write!(f, "IntV({})", self.vt_data.inner.int_value),
                    ValueTypeTag::Float => write!(f, "FloatV({})", self.vt_data.inner.float_value),
                    ValueTypeTag::Char => write!(f, "CharV('{}')", self.vt_data.inner.char_value),
                    ValueTypeTag::Bool => write!(f, "BoolV({})", self.vt_data.inner.bool_value)
                }
            }
        } else if self.is_container() {
            unsafe {
                write!(f, "CustomContainer(ptr = {:X}, vt = {:X})",
                       self.ptr_repr.trivia, self.ptr_repr.ptr)
            }
        } else if self.is_null() {
            write!(f, "Null")
        } else {
            unsafe {
                write!(f, "Reference(ptr = {:X})", self.ptr_repr.ptr)
            }
        }
    }
}

#[repr(transparent)]
pub struct TypedValue<T: 'static> {
    pub inner: Value,
    _phantom: PhantomData<T>
}

impl<T> TypedValue<T>
    where T: 'static,
          Void: StaticBase<T>
{
    // TODO
}

impl TypedValue<i64> {
    // TODO
}

impl TypedValue<f64> {
    // TODO
}

impl TypedValue<char> {
    // TODO
}

impl TypedValue<bool> {
    // TODO
}

#[cfg(test)]
mod test;