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
use crate::{
    garbage_collector::GcRootPtr,
    marshal::Marshal,
    reflection::{ArgumentReflection, ReturnTypeReflection},
    GarbageCollector, Runtime,
};
use mun_memory::{
    gc::{GcPtr, GcRuntime, HasIndirectionPtr},
    Type,
};
use std::{
    ptr::{self, NonNull},
    sync::Arc,
};

/// Represents a Mun struct pointer.
#[repr(transparent)]
#[derive(Clone)]
pub struct RawStruct(GcPtr);

impl RawStruct {
    /// Returns a pointer to the struct memory.
    pub unsafe fn get_ptr(&self) -> *const u8 {
        self.0.deref()
    }
}

/// Type-agnostic wrapper for interoperability with a Mun struct. This is merely a reference to the
/// Mun struct, that will be garbage collected unless it is rooted.
#[derive(Clone)]
pub struct StructRef<'s> {
    raw: RawStruct,
    runtime: &'s Runtime,
}

impl<'s> StructRef<'s> {
    /// Creates a `StructRef` that wraps a raw Mun struct.
    fn new<'r>(raw: RawStruct, runtime: &'r Runtime) -> Self
    where
        'r: 's,
    {
        Self { raw, runtime }
    }

    /// Consumes the `StructRef`, returning a raw Mun struct.
    pub fn into_raw(self) -> RawStruct {
        self.raw
    }

    /// Roots the `StructRef`.
    pub fn root(self) -> RootedStruct {
        RootedStruct::new(&self.runtime.gc, self.raw)
    }

    /// Returns the type information of the struct.
    pub fn type_info(&self) -> Type {
        self.runtime.gc.ptr_type(self.raw.0)
    }

    /// Returns the struct's field at the specified `offset`.
    ///
    /// # Safety
    ///
    /// The offset must be the location of a variable of type T.
    unsafe fn get_field_ptr_unchecked<T>(&self, offset: usize) -> NonNull<T> {
        // SAFETY: self.raw's memory pointer is never null
        let ptr = self.raw.get_ptr();

        NonNull::new_unchecked(ptr.add(offset).cast::<T>() as *mut T)
    }

    /// Retrieves the value of the field corresponding to the specified `field_name`.
    pub fn get<T: ReturnTypeReflection + Marshal<'s>>(&self, field_name: &str) -> Result<T, String>
    where
        T: 's,
    {
        let type_info = self.type_info();

        // Safety: `as_struct` is guaranteed to return `Some` for `StructRef`s.
        let struct_info = type_info.as_struct().unwrap();

        let field_info = struct_info
            .fields()
            .find_by_name(field_name)
            .ok_or_else(|| {
                format!(
                    "Struct `{}` does not contain field `{}`.",
                    type_info.name(),
                    field_name
                )
            })?;

        if !T::accepts_type(&field_info.ty()) {
            return Err(format!(
                "Mismatched types for `{}::{}`. Expected: `{}`. Found: `{}`.",
                type_info.name(),
                field_name,
                T::type_hint(),
                field_info.ty().name(),
            ));
        };

        // SAFETY: The offset in the ABI is always valid.
        let field_ptr = unsafe { self.get_field_ptr_unchecked::<T::MunType>(field_info.offset()) };
        Ok(Marshal::marshal_from_ptr(
            field_ptr,
            self.runtime,
            &field_info.ty(),
        ))
    }

    /// Replaces the value of the field corresponding to the specified `field_name` and returns the
    /// old value.
    pub fn replace<T: ArgumentReflection + Marshal<'s>>(
        &mut self,
        field_name: &str,
        value: T,
    ) -> Result<T, String>
    where
        T: 's,
    {
        let type_info = self.type_info();

        // Safety: `as_struct` is guaranteed to return `Some` for `StructRef`s.
        let struct_info = type_info.as_struct().unwrap();

        let field_info = struct_info
            .fields()
            .find_by_name(field_name)
            .ok_or_else(|| {
                format!(
                    "Struct `{}` does not contain field `{}`.",
                    type_info.name(),
                    field_name
                )
            })?;

        let value_type = value.type_info(self.runtime);
        if field_info.ty() != value_type {
            return Err(format!(
                "Mismatched types for `{}::{}`. Expected: `{}`. Found: `{}`.",
                type_info.name(),
                field_name,
                value_type.name(),
                field_info.ty()
            ));
        }

        // SAFETY: The offset in the ABI is always valid.
        let field_ptr = unsafe { self.get_field_ptr_unchecked::<T::MunType>(field_info.offset()) };
        let old = Marshal::marshal_from_ptr(field_ptr, self.runtime, &field_info.ty());
        Marshal::marshal_to_ptr(value, field_ptr, &field_info.ty());
        Ok(old)
    }

    /// Sets the value of the field corresponding to the specified `field_name`.
    pub fn set<T: ArgumentReflection + Marshal<'s>>(
        &mut self,
        field_name: &str,
        value: T,
    ) -> Result<(), String> {
        let type_info = self.type_info();

        // Safety: `as_struct` is guaranteed to return `Some` for `StructRef`s.
        let struct_info = type_info.as_struct().unwrap();

        let field_info = struct_info
            .fields()
            .find_by_name(field_name)
            .ok_or_else(|| {
                format!(
                    "Struct `{}` does not contain field `{}`.",
                    type_info.name(),
                    field_name
                )
            })?;

        let value_type = value.type_info(self.runtime);
        if field_info.ty() != value_type {
            return Err(format!(
                "Mismatched types for `{}::{}`. Expected: `{}`. Found: `{}`.",
                type_info.name(),
                field_name,
                value_type.name(),
                field_info.ty()
            ));
        }

        // SAFETY: The offset in the ABI is always valid.
        let field_ptr = unsafe { self.get_field_ptr_unchecked::<T::MunType>(field_info.offset()) };
        Marshal::marshal_to_ptr(value, field_ptr, &field_info.ty());
        Ok(())
    }
}

impl<'r> ArgumentReflection for StructRef<'r> {
    fn type_info(&self, _runtime: &Runtime) -> Type {
        self.type_info()
    }
}

impl<'s> Marshal<'s> for StructRef<'s> {
    type MunType = RawStruct;

    fn marshal_from<'r>(value: Self::MunType, runtime: &'r Runtime) -> Self
    where
        'r: 's,
    {
        StructRef::new(value, runtime)
    }

    fn marshal_into<'r>(self) -> Self::MunType {
        self.into_raw()
    }

    fn marshal_from_ptr<'r>(
        ptr: NonNull<Self::MunType>,
        runtime: &'r Runtime,
        type_info: &Type,
    ) -> StructRef<'s>
    where
        Self: 's,
        'r: 's,
    {
        let struct_info = type_info.as_struct().unwrap();

        // Copy the contents of the struct based on what kind of pointer we are dealing with
        let gc_handle = if struct_info.is_value_struct() {
            // For a value struct, `ptr` points to a struct value.

            // Create a new object using the runtime's intrinsic
            let mut gc_handle = runtime.gc().alloc(type_info);

            // Construct
            let src = ptr.cast::<u8>().as_ptr() as *const _;
            let dest = unsafe { gc_handle.deref_mut::<u8>() };
            unsafe { ptr::copy_nonoverlapping(src, dest, type_info.value_layout().size()) };

            gc_handle
        } else {
            // For a gc struct, `ptr` points to a `GcPtr`.
            unsafe { *ptr.cast::<GcPtr>().as_ptr() }
        };

        StructRef::new(RawStruct(gc_handle), runtime)
    }

    fn marshal_to_ptr(value: Self, mut ptr: NonNull<Self::MunType>, type_info: &Type) {
        let struct_info = type_info.as_struct().unwrap();
        if struct_info.is_value_struct() {
            let dest = ptr.cast::<u8>().as_ptr();
            unsafe {
                ptr::copy_nonoverlapping(
                    value.into_raw().get_ptr(),
                    dest,
                    type_info.value_layout().size(),
                )
            };
        } else {
            unsafe { *ptr.as_mut() = value.into_raw() };
        }
    }
}

impl<'r> ReturnTypeReflection for StructRef<'r> {
    /// Returns true if this specified type can be stored in an instance of this type
    fn accepts_type(ty: &Type) -> bool {
        ty.is_struct()
    }

    fn type_hint() -> &'static str {
        "struct"
    }
}

/// Type-agnostic wrapper for interoperability with a Mun struct, that has been rooted. To marshal,
/// obtain a `StructRef` for the `RootedStruct`.
#[derive(Clone)]
pub struct RootedStruct {
    handle: GcRootPtr,
}

impl RootedStruct {
    /// Creates a `RootedStruct` that wraps a raw Mun struct.
    fn new(gc: &Arc<GarbageCollector>, raw: RawStruct) -> Self {
        assert!(gc.ptr_type(raw.0).is_struct());
        Self {
            handle: GcRootPtr::new(gc, raw.0),
        }
    }

    /// Converts the `RootedStruct` into a `StructRef`, using an external shared reference to a
    /// `Runtime`.
    pub fn as_ref<'r>(&self, runtime: &'r Runtime) -> StructRef<'r> {
        assert_eq!(Arc::as_ptr(&runtime.gc), self.handle.runtime().as_ptr());
        StructRef::new(RawStruct(self.handle.handle()), runtime)
    }
}