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
use std::any::TypeId;
use std::mem::{ManuallyDrop, MaybeUninit};
use std::ptr::addr_of;

use unchecked_unwrap::UncheckedUnwrap;
use xjbutil::unchecked::UnsafeFrom;
use xjbutil::void::Void;

use crate::data::traits::{ChildrenType, StaticBase};
use crate::data::tyck::TyckInfo;

pub const OWN_INFO_READ_MASK: u8    = 0b000_1_0_0_0_0;
pub const OWN_INFO_WRITE_MASK: u8   = 0b000_0_1_0_0_0;
pub const OWN_INFO_MOVE_MASK: u8    = 0b000_0_0_1_0_0;
pub const OWN_INFO_COLLECT_MASK: u8 = 0b000_0_0_0_1_0;
pub const OWN_INFO_OWNED_MASK: u8   = 0b000_0_0_0_0_1;

/// Ownership information
///
/// At one time, a Pr47 heap value may be *owned by the VM*, *shared/mutably shared from Rust*,
/// *shared/mutably shared to Rust* or *moved to Rust* while only having a vacant shell.
#[repr(u8)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum OwnershipInfo {
    // R = Read
    // W = Write
    // M = Move
    // C = Collectable
    // O = Owned by VM
    //                        R W M C O
    VMOwned           = 0b000_1_1_1_1_1,
    SharedFromRust    = 0b000_1_0_0_1_0,
    MutSharedFromRust = 0b000_1_1_0_1_0,
    SharedToRust      = 0b000_1_0_0_0_1, // also used by global constant objects
    MutSharedToRust   = 0b000_0_0_0_0_1,
    MovedToRust       = 0b000_0_0_0_1_0
}

impl OwnershipInfo {
    #[inline(always)] pub fn is_readable(self) -> bool {
        (self as u8) & OWN_INFO_READ_MASK != 0
    }

    #[inline(always)] pub fn is_writeable(self) -> bool {
        (self as u8) & OWN_INFO_WRITE_MASK != 0
    }

    #[inline(always)] pub fn is_movable(self) -> bool {
        (self as u8) & OWN_INFO_MOVE_MASK != 0
    }

    #[inline(always)] pub fn is_collectable(self) -> bool {
        (self as u8) & OWN_INFO_COLLECT_MASK != 0
    }

    #[inline(always)] pub fn is_owned(self) -> bool {
        (self as u8) & OWN_INFO_OWNED_MASK != 0
    }
}

impl UnsafeFrom<u8> for OwnershipInfo {
    #[inline(always)] unsafe fn unsafe_from(data: u8) -> Self {
        std::mem::transmute::<u8, Self>(data)
    }
}

/// Internal representation of `Wrapper` data. Can be either
///   * A piece of owned data, represented by a `ManuallyDrop<MaybeUninit<T>>`
///   * A reference to data shared from Rust, represented by a `*mut T`
#[repr(C)]
pub union WrapperData<T: 'static> {
    pub owned: ManuallyDrop<MaybeUninit<T>>,
    pub ptr: *mut T
}

#[repr(C, align(8))]
pub struct Wrapper<T: 'static> {
    /* +0 */ pub refcount: u32,
    /* +4 */ pub ownership_info: u8,
    /* +5 */ pub gc_info: u8,
    /* +6 */ pub data_offset: u8,
    /* +7 */ pub ownership_info2: u8,

    /* +data_offset */ pub data: WrapperData<T>
}

impl<T: 'static> Drop for Wrapper<T> {
    fn drop(&mut self) {
        if self.ownership_info & OWN_INFO_COLLECT_MASK != 0 {
            if self.ownership_info & OWN_INFO_OWNED_MASK != 0 {
                let owned: T = unsafe { ManuallyDrop::take(&mut self.data.owned).assume_init() };
                drop(owned);
            }
        }
    }
}

impl<T: 'static> Wrapper<T> {
    pub fn new_owned(data: T) -> Self {
        let mut ret: Wrapper<T> = Self {
            refcount: 0,
            ownership_info: OwnershipInfo::VMOwned as u8,
            gc_info: 0,
            data_offset: 0,
            ownership_info2: 0,
            data: WrapperData {
                owned: ManuallyDrop::new(MaybeUninit::new(data))
            }
        };
        ret.data_offset = (addr_of!(ret.data) as usize - addr_of!(ret) as usize) as u8;
        ret
    }

    pub fn new_ref(ptr: *const T) -> Self {
        let mut ret: Wrapper<T> = Self {
            refcount: 1,
            ownership_info: OwnershipInfo::SharedFromRust as u8,
            gc_info: 0,
            data_offset: 0,
            ownership_info2: 0,
            data: WrapperData {
                ptr: ptr as *mut T
            }
        };
        ret.data_offset = (addr_of!(ret.data) as usize - addr_of!(ret) as usize) as u8;
        ret
    }

    pub fn new_mut_ref(ptr: *mut T) -> Self {
        let mut ret: Wrapper<T> = Self {
            refcount: 1,
            ownership_info: OwnershipInfo::MutSharedFromRust as u8,
            gc_info: 0,
            data_offset: 0,
            ownership_info2: 0,
            data: WrapperData {
                ptr
            }
        };
        ret.data_offset = (addr_of!(ret.data) as usize - addr_of!(ret) as usize) as u8;
        ret
    }
}

pub trait DynBase {
    fn dyn_type_id(&self) -> TypeId;

    fn dyn_type_name(&self) -> String;

    fn dyn_tyck(&self, tyck_info: &TyckInfo) -> bool;

    #[cfg(debug_assertions)]
    unsafe fn move_out_ck(&mut self, out: *mut (), type_id: TypeId);

    #[cfg(not(debug_assertions))]
    unsafe fn move_out(&mut self, out: *mut ());

    fn children(&self) -> ChildrenType;
}

impl<T: 'static> DynBase for Wrapper<T> where Void: StaticBase<T> {
    fn dyn_type_id(&self) -> TypeId {
        <Void as StaticBase<T>>::type_id()
    }

    fn dyn_type_name(&self) -> String {
        <Void as StaticBase<T>>::type_name()
    }

    fn dyn_tyck(&self, tyck_info: &TyckInfo) -> bool {
        <Void as StaticBase<T>>::tyck(tyck_info)
    }

    #[cfg(debug_assertions)]
    unsafe fn move_out_ck(&mut self, out: *mut (), type_id: TypeId) {
        debug_assert_eq!(self.dyn_type_id(), type_id);
        debug_assert!(OwnershipInfo::unsafe_from(self.ownership_info).is_movable());
        let dest: &mut MaybeUninit<T> = (out as *mut MaybeUninit<T>).as_mut().unchecked_unwrap();
        std::ptr::write(dest.as_mut_ptr(), ManuallyDrop::take(&mut self.data.owned).assume_init());
        self.ownership_info = OwnershipInfo::MovedToRust as u8;
    }

    #[cfg(not(debug_assertions))]
    unsafe fn move_out(&mut self, out: *mut ()) {
        let dest: &mut MaybeUninit<T>
            = (out as *mut MaybeUninit<T>).as_mut().unchecked_unwrap();
        std::ptr::write(dest.as_mut_ptr(), ManuallyDrop::take(&mut self.data.owned).assume_init());
        self.ownership_info = OwnershipInfo::MovedToRust as u8;
    }

    #[inline]
    fn children(&self) -> ChildrenType {
        let vself: *const T = if (self.ownership_info & OWN_INFO_OWNED_MASK) != 0 {
            unsafe { self.data.owned.as_ptr() }
        } else {
            debug_assert_ne!(self.ownership_info & OWN_INFO_READ_MASK, 0);
            unsafe { self.data.ptr }
        };
        <Void as StaticBase<T>>::children(vself)
    }
}