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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
//! Types that directly reference data managed by Julia.
//!
//! In this module you'll find types that represent Julia's managed types. These are mutable types
//! like [`Module`], [`DataType`], and [`Array`] which are defined by the C API and provide access
//! to some specific functionality from that API. For example, [`Module`] provides access to the
//! contents of Julia modules, and [`Array`] access to the contents of Julia arrays.
//!
//! The most common of these types is [`Value`], which represents some arbitrary managed data.
//! Whenever you call a Julia function its arguments must be of this type, and a new one is
//! returned. All managed data is a valid [`Value`] and can be converted to that type by calling
//! [`Managed::as_value`].
//!
//! One useful guarantee provided by managed types is that they point to existing data which won't
//! be freed until its lifetime has expired. If data is returned that isn't rooted, jlrs returns a
//! [`Ref`] instead of the managed type. Because the data isn't rooted it's not guaranteed to
//! remain valid while it can be used. For more information about rooting see the documentation of
//! the [`memory`] module.
//!
//! [`memory`]: crate::memory
//! [`DataType`]: crate::data::managed::datatype::DataType
//! [`Array`]: crate::data::managed::array::Array

// NB: inspect layout of builtin types with:
/*
function inspect(ty)
    for (a, b) in zip(fieldnames(ty), fieldtypes(ty))
        println(a, ": ", b, " (", isconst(ty, a) ? "const" : "mut", ")")
    end
end
*/

macro_rules! impl_construct_type_managed {
    ($ty:ident, 1, $jl_ty:expr) => {
        unsafe impl crate::data::types::construct_type::ConstructType for $ty<'_> {
            type Static = $ty<'static>;

            const CACHEABLE: bool = false;

            #[inline]
            fn construct_type_uncached<'target, 'current, 'borrow, Tgt>(
                target: Tgt,
            ) -> $crate::data::managed::value::ValueData<'target, 'static, Tgt>
            where
                Tgt: $crate::memory::target::Target<'target>,
            {
                unsafe {
                    target.data_from_ptr(
                        NonNull::new_unchecked($jl_ty.cast::<::jl_sys::jl_value_t>()),
                        $crate::private::Private,
                    )
                }
            }

            #[inline]
            fn base_type<'target, Tgt>(_target: &Tgt) -> Option<$crate::data::managed::value::Value<'target, 'static>>
            where
                Tgt: crate::memory::target::Target<'target>,
            {
                unsafe {
                    let ptr = NonNull::new_unchecked($jl_ty.cast::<::jl_sys::jl_value_t>());
                    Some(<$crate::data::managed::value::Value as $crate::data::managed::private::ManagedPriv>::wrap_non_null(
                        ptr,
                        $crate::private::Private,
                    ))
                }
            }
        }
    };
    ($ty:ident, 2, $jl_ty:expr) => {
        unsafe impl crate::data::types::construct_type::ConstructType for $ty<'_, '_> {
            type Static = $ty<'static, 'static>;

            const CACHEABLE: bool = false;

            #[inline]
            fn construct_type_uncached<'target, 'current, 'borrow, Tgt>(
                target: Tgt,
            ) -> $crate::data::managed::value::ValueData<'target, 'static, Tgt>
            where
                Tgt: $crate::memory::target::Target<'target>,
            {
                unsafe {
                    target.data_from_ptr(
                        NonNull::new_unchecked($jl_ty.cast::<::jl_sys::jl_value_t>()),
                        $crate::private::Private,
                    )
                }
            }

            #[inline]
            fn base_type<'target, Tgt>(_target: &Tgt) -> Option<$crate::data::managed::value::Value<'target, 'static>>
            where
                Tgt: crate::memory::target::Target<'target>,
            {
                unsafe {
                    let ptr = NonNull::new_unchecked($jl_ty.cast::<::jl_sys::jl_value_t>());
                    Some(<$crate::data::managed::value::Value as $crate::data::managed::private::ManagedPriv>::wrap_non_null(
                        ptr,
                        $crate::private::Private,
                    ))
                }
            }
        }
    };
}

macro_rules! impl_ccall_arg_managed {
    ($ty:ident, 1) => {
        unsafe impl<'scope> $crate::convert::ccall_types::CCallArg for $ty<'scope> {
            type CCallArgType = $crate::data::managed::value::Value<'scope, 'static>;
            type FunctionArgType = $ty<'scope>;
        }

        unsafe impl $crate::convert::ccall_types::CCallReturn
            for $crate::data::managed::Ref<'static, 'static, $ty<'static>>
        {
            type CCallReturnType = $crate::data::managed::value::Value<'static, 'static>;
            type FunctionReturnType = $ty<'static>;
            type ReturnAs = Self;

            #[inline]
            unsafe fn return_or_throw(self) -> Self::ReturnAs {
                self
            }
        }
    };

    ($ty:ident, 2) => {
        unsafe impl<'scope, 'data> $crate::convert::ccall_types::CCallArg for $ty<'scope, 'data> {
            type CCallArgType = $crate::data::managed::value::Value<'static, 'static>;
            type FunctionArgType = $ty<'scope, 'data>;
        }

        unsafe impl $crate::convert::ccall_types::CCallReturn
            for $crate::data::managed::Ref<'static, 'static, $ty<'static, 'static>>
        {
            type CCallReturnType = $crate::data::managed::value::Value<'static, 'static>;
            type FunctionReturnType = $ty<'static, 'static>;
            type ReturnAs = Self;

            #[inline]
            unsafe fn return_or_throw(self) -> Self::ReturnAs {
                self
            }
        }
    };
}

macro_rules! impl_into_typed {
    ($ty:ident) => {
        impl<'scope, 'data> $crate::data::managed::value::typed::AsTyped<'scope, 'data>
            for $ty<'scope>
        {
            #[inline]
            fn as_typed(
                self,
            ) -> $crate::error::JlrsResult<
                $crate::data::managed::value::typed::TypedValue<'scope, 'data, Self>,
            > {
                unsafe {
                    Ok(
                        $crate::data::managed::value::typed::TypedValue::wrap_non_null(
                            self.unwrap_non_null($crate::private::Private).cast(),
                            $crate::private::Private,
                        ),
                    )
                }
            }
        }
    };
}

macro_rules! impl_valid_layout {
    ($ref_type:ident, $type:ident, $type_obj:ident) => {
        unsafe impl $crate::data::layout::valid_layout::ValidLayout for $ref_type<'_> {
            fn valid_layout(ty: $crate::data::managed::value::Value) -> bool {
                if ty.is::<$crate::data::managed::datatype::DataType>() {
                    let dt = unsafe { ty.cast_unchecked::<$crate::data::managed::datatype::DataType>() };
                    dt.is::<$type>()
                } else {
                    false
                }
            }

            fn type_object<'target, Tgt>(
                _: &Tgt
            ) -> $crate::data::managed::value::Value<'target, 'static>
            where
                Tgt: $crate::memory::target::Target<'target>
            {
                unsafe {
                    <$crate::data::managed::value::Value as $crate::data::managed::private::ManagedPriv>::wrap_non_null(
                        std::ptr::NonNull::new_unchecked($type_obj.cast()),
                        $crate::private::Private
                    )
                }
            }

            const IS_REF: bool = true;
        }

        unsafe impl $crate::data::layout::valid_layout::ValidField for Option<$ref_type<'_>> {
            #[inline]
            fn valid_field(ty: $crate::data::managed::value::Value) -> bool {
                if ty.is::<$crate::data::managed::datatype::DataType>() {
                    let dt = unsafe { ty.cast_unchecked::<$crate::data::managed::datatype::DataType>() };
                    dt.is::<$type>()
                } else {
                    false
                }
            }
        }

        unsafe impl $crate::data::layout::valid_layout::ValidLayout for $type<'_> {
            #[inline]
            fn valid_layout(ty: $crate::data::managed::value::Value) -> bool {
                if ty.is::<$crate::data::managed::datatype::DataType>() {
                    let dt = unsafe { ty.cast_unchecked::<$crate::data::managed::datatype::DataType>() };
                    dt.is::<$type>()
                } else {
                    false
                }
            }

            fn type_object<'target, Tgt>(
                _: &Tgt
            ) -> $crate::data::managed::value::Value<'target, 'static>
            where
                Tgt: $crate::memory::target::Target<'target>
            {
                unsafe {
                    <$crate::data::managed::value::Value as $crate::data::managed::private::ManagedPriv>::wrap_non_null(
                        std::ptr::NonNull::new_unchecked($type_obj.cast()),
                        $crate::private::Private
                    )
                }
            }

            const IS_REF: bool = true;
        }

        unsafe impl $crate::data::layout::valid_layout::ValidField for Option<$type<'_>> {
            #[inline]
            fn valid_field(ty: $crate::data::managed::value::Value) -> bool {
                if ty.is::<$crate::data::managed::datatype::DataType>() {
                    let dt = unsafe { ty.cast_unchecked::<$crate::data::managed::datatype::DataType>() };
                    dt.is::<$type>()
                } else {
                    false
                }
            }
        }
    };
}

macro_rules! impl_debug {
    ($type:ty) => {
        impl ::std::fmt::Debug for $type {
            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
                match <Self as $crate::data::managed::Managed>::display_string(*self) {
                    Ok(s) => f.write_str(&s),
                    Err(e) => f.write_fmt(format_args!("<Cannot display value: {}>", e)),
                }
            }
        }
    };
}

pub mod array;
pub mod ccall_ref;
pub mod datatype;
pub mod function;
#[cfg(feature = "internal-types")]
pub mod internal;
pub mod module;
pub mod parachute;
pub mod rust_result;
pub mod simple_vector;
pub mod string;
pub mod symbol;
pub mod task;
pub mod type_name;
pub mod type_var;
pub mod union;
pub mod union_all;
pub mod value;

use std::{
    ffi::c_void,
    fmt::{Debug, Formatter, Result as FmtResult},
    marker::PhantomData,
    ptr::NonNull,
};

use jl_sys::jl_stderr_obj;

use self::module::JlrsCore;
use crate::{
    call::Call,
    data::{
        layout::valid_layout::{ValidField, ValidLayout},
        managed::{module::Module, private::ManagedPriv as _, string::JuliaString, value::Value},
    },
    error::{JlrsError, JlrsResult, CANNOT_DISPLAY_VALUE},
    memory::target::{unrooted::Unrooted, Target},
    private::Private,
};

/// Trait implemented by `Ref`.
pub trait ManagedRef<'scope, 'data>:
    private::ManagedRef<'scope, 'data> + Copy + Debug + ValidLayout
{
    /// The managed type associated with this `Ref`.
    type Managed: Managed<'scope, 'data>;
}

impl<'scope, 'data, T> ManagedRef<'scope, 'data> for Ref<'scope, 'data, T>
where
    T: Managed<'scope, 'data>,
    Self: Copy + ValidLayout,
    Option<Self>: ValidField,
{
    type Managed = T;
}

/// Trait implemented by all managed types.
pub trait Managed<'scope, 'data>: private::ManagedPriv<'scope, 'data> {
    /// `Self`, but with arbitrary lifetimes. Used to construct the appropriate type in generic
    /// contexts.
    type TypeConstructor<'target, 'da>: Managed<'target, 'da>;

    /// Convert the data to a `Ref`.
    #[inline]
    fn as_ref(self) -> Ref<'scope, 'data, Self> {
        Ref::wrap(self.unwrap_non_null(Private))
    }

    /// Convert the data to a `Value`.
    #[inline]
    fn as_value(self) -> Value<'scope, 'data> {
        // Safety: Managed types can always be converted to a Value
        unsafe { Value::wrap_non_null(self.unwrap_non_null(Private).cast(), Private) }
    }

    /// Use the target to reroot this data.
    #[inline]
    fn root<'target, T>(self, target: T) -> T::Data<'data, Self::TypeConstructor<'target, 'data>>
    where
        T: Target<'target>,
    {
        unsafe { target.data_from_ptr(self.unwrap_non_null(Private).cast(), Private) }
    }

    /// Returns a new `Unrooted`.
    #[inline]
    fn unrooted_target(self) -> Unrooted<'scope> {
        unsafe { Unrooted::new() }
    }

    /// Convert the data to its display string, i.e. the string that is shown when calling
    /// `Base.show`.
    fn display_string(self) -> JlrsResult<String> {
        // Safety: all Julia data that is accessed is globally rooted, the result is converted
        // to a String before the GC can free it.
        let global = self.unrooted_target();

        let s = unsafe {
            JlrsCore::value_string(&global)
                .call1(&global, self.as_value())
                .map_err(|e| e.as_value().error_string_or(CANNOT_DISPLAY_VALUE))
                .map_err(|e| JlrsError::exception(format!("JlrsCore.valuestring failed: {}", e)))?
                .as_value()
                .cast::<JuliaString>()?
                .as_str()?
                .to_string()
        };

        Ok(s)
    }

    /// Convert the data to its error string, i.e. the string that is shown when calling
    /// `Base.showerror`. This string can contain ANSI color codes if this is enabled by calling
    /// [`Julia::error_color`] or [`AsyncJulia::error_color`].
    ///
    /// [`Julia::error_color`]: crate::runtime::sync_rt::Julia::error_color
    /// [`AsyncJulia::error_color`]: crate::runtime::async_rt::AsyncJulia::error_color
    fn error_string(self) -> JlrsResult<String> {
        // Safety: all Julia data that is accessed is globally rooted, the result is converted
        // to a String before the GC can free it.
        let global = self.unrooted_target();

        let s = unsafe {
            JlrsCore::error_string(&global)
                .call1(&global, self.as_value())
                .map_err(|e| e.as_value().error_string_or(CANNOT_DISPLAY_VALUE))
                .map_err(|e| JlrsError::exception(format!("JlrsCore.errorstring failed: {}", e)))?
                .as_value()
                .cast::<JuliaString>()?
                .as_str()?
                .to_string()
        };

        Ok(s)
    }

    #[doc(hidden)]
    unsafe fn print_error(self) {
        let unrooted = Unrooted::new();
        let stderr = Value::wrap_non_null(NonNull::new_unchecked(jl_stderr_obj()), Private);
        let showerror = Module::base(&unrooted)
            .global(unrooted, "showerror")
            .unwrap()
            .as_value();
        showerror.call2(unrooted, stderr, self.as_value()).ok();
    }

    /// Convert the data to its display string, i.e. the string that is shown by calling
    /// `Base.display`, or some default value.
    fn display_string_or<S: Into<String>>(self, default: S) -> String {
        self.display_string().unwrap_or(default.into())
    }

    /// Convert the data to its error string, i.e. the string that is shown when this value is
    /// thrown as an exception, or some default value.
    fn error_string_or<S: Into<String>>(self, default: S) -> String {
        self.error_string().unwrap_or(default.into())
    }

    /// Extends the `'scope` lifetime to `'static`, which allows this managed data to be leaked
    /// from a scope.
    ///
    /// This method only extends the `'scope` lifetime, the `'data` lifetime must already be
    /// `'static`. This method should only be used to return Julia data from a `ccall`ed function,
    /// and in combination with the `ForeignType` trait to store references to Julia data in types
    /// that that implement that trait.
    #[inline]
    fn leak(self) -> Ref<'static, 'data, Self::TypeConstructor<'static, 'data>> {
        self.as_ref().leak()
    }
}

/// The managed type `W<'target, 'data>` assocatiated with the reference type `T<'scope, 'data>`.
pub type ManagedType<'target, 'scope, 'data, T> =
    <<T as ManagedRef<'scope, 'data>>::Managed as Managed<'scope, 'data>>::TypeConstructor<
        'target,
        'data,
    >;

impl<'scope, 'data, W> Managed<'scope, 'data> for W
where
    W: private::ManagedPriv<'scope, 'data>,
{
    type TypeConstructor<'target, 'da> = Self::TypeConstructorPriv<'target, 'da>;
}

/// A reference to Julia data that is not guaranteed to be rooted.
///
/// Managed types are generally guaranteed to wrap valid, rooted data. In some cases this
/// guarantee is too strong. The garbage collector uses the roots as a starting point to
/// determine what values can be reached, as long as you can guarantee a value is reachable it's
/// safe to use. Whenever data is not rooted jlrs returns a `Ref`. Because it's not rooted it's
/// unsafe to use.
#[repr(transparent)]
pub struct Ref<'scope, 'data, T: Managed<'scope, 'data>>(
    NonNull<T::Wraps>,
    PhantomData<&'scope ()>,
    PhantomData<&'data ()>,
);

impl<'scope, 'data, T> Clone for Ref<'scope, 'data, T>
where
    T: Managed<'scope, 'data>,
{
    #[inline]
    fn clone(&self) -> Self {
        Ref(self.0, PhantomData, PhantomData)
    }
}

impl<'scope, 'data, T> Copy for Ref<'scope, 'data, T> where T: Managed<'scope, 'data> {}

impl<'scope, 'data, T: Managed<'scope, 'data>> Debug for Ref<'scope, 'data, T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        write!(f, "Ref<{}>", T::NAME)
    }
}

impl<'scope, 'data, W: Managed<'scope, 'data>> Ref<'scope, 'data, W> {
    /// Use `target` to root this data.
    ///
    /// Safety: The data pointed to by `self` must not have been freed by the GC yet.
    #[inline]
    pub unsafe fn root<'target, T>(
        self,
        target: T,
    ) -> T::Data<'data, W::TypeConstructor<'target, 'data>>
    where
        T: Target<'target>,
    {
        target.data_from_ptr(self.ptr().cast(), Private)
    }

    #[inline]
    pub(crate) fn wrap(ptr: NonNull<W::Wraps>) -> Self {
        Ref(ptr, PhantomData, PhantomData)
    }

    /// Assume the reference still points to valid Julia data and convert it to its managed type.
    ///
    /// Safety: a reference is only guaranteed to be valid as long as it's reachable from some
    /// GC root. If the reference is unreachable, the GC can free it. The GC can run whenever a
    /// safepoint is reached, this is typically the case when new Julia data is allocated.
    #[inline]
    pub unsafe fn as_managed(self) -> W {
        W::wrap_non_null(self.ptr(), Private)
    }

    /// Assume the reference still points to valid Julia data and convert it to a `Value`.
    ///
    /// Safety: a reference is only guaranteed to be valid as long as it's reachable from some
    /// GC root. If the reference is unreachable, the GC can free it. The GC can run whenever a
    /// safepoint is reached, this is typically the case when new Julia data is allocated.
    #[inline]
    pub unsafe fn as_value(self) -> Value<'scope, 'data> {
        Value::wrap_non_null(self.data_ptr().cast(), Private)
    }

    /// Extends the `'data` lifetime to `'static`.
    ///
    /// Safety: this method should only be used when no data borrowed from Rust is referenced by
    /// this Julia data.
    #[inline]
    pub unsafe fn assume_owned(self) -> Ref<'scope, 'static, W::TypeConstructor<'scope, 'static>> {
        Ref::wrap(self.ptr().cast())
    }

    /// Extends the `'scope` lifetime to `'static`, which allows this reference to Julia data to
    /// be leaked from a scope.
    ///
    /// Safety: this method should only be called to return Julia data from a `ccall`ed function
    /// or when storing Julia data in a foreign type.
    #[inline]
    pub fn leak(self) -> Ref<'static, 'data, W::TypeConstructor<'static, 'data>> {
        Ref::wrap(self.ptr().cast())
    }

    /// Returns a pointer to the data,
    #[inline]
    pub fn data_ptr(self) -> NonNull<c_void> {
        self.ptr().cast()
    }

    #[inline]
    pub(crate) fn ptr(self) -> NonNull<W::Wraps> {
        self.0
    }
}

#[inline]
pub fn leak<'scope, 'data, M: Managed<'scope, 'data>>(
    data: M,
) -> Ref<'static, 'data, M::TypeConstructor<'static, 'data>> {
    data.as_ref().leak()
}

#[inline]
pub unsafe fn assume_rooted<'scope, M: Managed<'scope, 'static>>(
    data: Ref<'scope, 'static, M>,
) -> M {
    data.as_managed()
}

#[inline]
pub unsafe fn erase_scope_lifetime<'scope, 'data, M: Managed<'scope, 'data>>(
    data: M,
) -> M::TypeConstructor<'static, 'data> {
    data.leak().as_managed()
}

pub(crate) mod private {
    use std::{fmt::Debug, ptr::NonNull};

    use crate::{
        data::managed::{value::Value, Ref},
        private::Private,
    };

    pub trait ManagedPriv<'scope, 'data>: Copy + Debug {
        type Wraps;
        type TypeConstructorPriv<'target, 'da>: ManagedPriv<'target, 'da>;
        const NAME: &'static str;

        // Safety: `inner` must point to valid data. If it is not
        // rooted, it must never be used after becoming unreachable.
        unsafe fn wrap_non_null(inner: NonNull<Self::Wraps>, _: Private) -> Self;

        // Safety: `Self` must be the correct type for `value`.
        #[inline]
        unsafe fn from_value_unchecked(value: Value<'scope, 'data>, _: Private) -> Self {
            Self::wrap_non_null(value.unwrap_non_null(Private).cast(), Private)
        }

        fn unwrap_non_null(self, _: Private) -> NonNull<Self::Wraps>;

        #[inline]
        fn unwrap(self, _: Private) -> *mut Self::Wraps {
            self.unwrap_non_null(Private).as_ptr()
        }
    }

    pub trait ManagedRef<'scope, 'data> {}

    impl<'scope, 'data, T> ManagedRef<'scope, 'data> for Ref<'scope, 'data, T> where
        T: ManagedPriv<'scope, 'data>
    {
    }
}