jlrs 0.23.0

jlrs provides bindings to the Julia C API that enable Julia code to be called from Rust and more.
Documentation
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
//! Static references to global Julia data.
//!
//! Accessing global Julia data through the module system can be expensive. If the global is a
//! constant or never replaced with another value, this data is globally rooted so it's safe to
//! hold on to a reference to this data. This module provides [`StaticGlobal`] and [`StaticRef`],
//! and macros to create and access them.

use std::{
    marker::PhantomData,
    ptr::{NonNull, null_mut},
    sync::atomic::{AtomicPtr, Ordering},
};

use jl_sys::{jl_module_t, jl_sym_t, jl_symbol_n, jl_value_t};

use super::{
    managed::private::ManagedPriv,
    types::{construct_type::ConstructType, typecheck::Typecheck},
};
use crate::{
    data::{
        cache::{CacheMap, FnvCache, new_fnv_cache},
        managed::{Managed, module::Module, value::ValueUnbound},
    },
    error::{JlrsError, JlrsResult},
    gc_safe::GcSafeOnceLock,
    memory::{PTls, gc::mark_queue_obj, target::Target},
    prelude::{Symbol, Value},
    private::Private,
};

pub(crate) static CACHE: FnvCache<usize, ValueUnbound> = new_fnv_cache();

pub(crate) unsafe fn mark_static_data_cache(ptls: PTls, full: bool) {
    unsafe {
        if full || CACHE.is_dirty() {
            CACHE.map(|value| {
                mark_queue_obj(ptls, value.as_weak());
            });
            CACHE.clear_dirty();
        }
    }
}

pub(crate) static LOADING_PACKAGE: AtomicPtr<jl_module_t> = AtomicPtr::new(null_mut());

// Safety: must only be called by initialization functions generated by `julia_module!`.
#[doc(hidden)]
pub unsafe fn set_loading_package(module: Option<Module>) {
    match module {
        Some(module) => LOADING_PACKAGE.store(module.as_weak().ptr().as_ptr(), Ordering::Relaxed),
        None => LOADING_PACKAGE.store(null_mut(), Ordering::Relaxed),
    }
}

pub(crate) fn get_top_item<'target, Tgt, T>(target: &Tgt, item_name: &str) -> JlrsResult<T>
where
    T: Managed<'static, 'static> + Typecheck,
    Tgt: Target<'target>,
{
    let main = Module::main(target);

    unsafe {
        match item_name {
            "Main" => {
                if let Ok(main) = main.leak().as_value().cast::<T>() {
                    return Ok(main);
                } else {
                    Err(JlrsError::exception(format!(
                        "Item Main has the wrong type, expected {}",
                        T::NAME
                    )))?
                }
            }
            item => {
                // Is the currently loading package requested?
                let ptr = LOADING_PACKAGE.load(Ordering::Relaxed);
                if !ptr.is_null() {
                    let m = Module::wrap_non_null(NonNull::new_unchecked(ptr), Private);
                    if m.name().as_bytes() == item.as_bytes() {
                        if let Ok(module) = m.leak().as_value().cast::<T>() {
                            return Ok(module);
                        }
                    }
                }

                // Is a package named `item` requested?
                let module = Module::package_root_module(target, item);
                if let Some(module) = module {
                    if let Ok(module) = module.leak().as_value().cast::<T>() {
                        return Ok(module);
                    }
                }

                // Is there a global named `item` in `Main`?
                let global = main.global(target, item);
                match global {
                    Ok(global) => {
                        if let Ok(global) = global.leak().as_value().cast::<T>() {
                            return Ok(global);
                        } else {
                            Err(JlrsError::exception(format!(
                                "Item {item} has the wrong type, expected {}",
                                T::NAME
                            )))?
                        }
                    }
                    Err(_) => Err(JlrsError::exception(format!("Item {item} is unavailable")))?,
                }
            }
        }
    }
}

struct StaticDataInner<T>(ValueUnbound, PhantomData<T>);
unsafe impl<T> Send for StaticDataInner<T> {}
unsafe impl<T> Sync for StaticDataInner<T> {}

/// Static reference to arbitrary managed data. Guaranteed to be initialized at most once.
pub struct StaticGlobal<T> {
    global: GcSafeOnceLock<StaticDataInner<T>>,
    path: &'static str,
}

impl<T> StaticGlobal<T>
where
    T: Managed<'static, 'static> + Typecheck,
{
    /// Define a new static global available at `path`.
    ///
    /// The global is looked up only once when this data is accessedd for the first time. The
    /// `path` argument must be the full path to the data, e.g. `"Main.Submodule.Foo"`.
    #[inline]
    pub const fn new(path: &'static str) -> StaticGlobal<T> {
        StaticGlobal {
            global: GcSafeOnceLock::new(),
            path,
        }
    }

    /// Get the global data, look it up if it doesn't exist yet.
    ///
    /// The global must exist and be an instance of `T`. Otherwise this method will panic.
    #[inline]
    pub fn get_or_init<'target, Tgt>(&self, target: &Tgt) -> T
    where
        Tgt: Target<'target>,
    {
        unsafe {
            if let Some(global) = self.global.get() {
                return global.0.cast_unchecked::<T>();
            } else {
                self.init(target)
            }
        }
    }

    #[inline(never)]
    #[cold]
    unsafe fn init<'target, Tgt>(&self, target: &Tgt) -> T
    where
        Tgt: Target<'target>,
    {
        let global = self.global.get_or_init(|| unsafe {
            let split_path = self.path.split('.').collect::<Vec<_>>();
            let n_parts = split_path.len();
            let global = if n_parts == 1 {
                get_top_item(target, split_path[0]).unwrap()
            } else {
                let mut module = get_top_item::<_, Module>(target, split_path[0]).unwrap();

                for i in 1..n_parts - 1 {
                    module = module
                        .submodule(target, split_path[i])
                        .unwrap()
                        .as_managed();
                }

                module
                    .global(target, split_path[n_parts - 1])
                    .unwrap()
                    .leak()
                    .as_value()
            };

            let key = global.as_weak().ptr().as_ptr().addr();
            CACHE.insert(key, global);

            return StaticDataInner(global, PhantomData);
        });

        global.0.cast::<T>().unwrap()
    }
}

impl StaticGlobal<ValueUnbound> {
    /// Define a new static global available at `path`.
    ///
    /// The global is looked up only once when this data is accessedd for the first time. The
    /// `path` argument must be the full path to the data, e.g. `"Main.Submodule.Foo"`.
    pub const fn new_value(path: &'static str) -> StaticGlobal<ValueUnbound> {
        StaticGlobal {
            global: GcSafeOnceLock::new(),
            path,
        }
    }
}

/// Static reference to arbitrary managed data. Can be initialized multiple times.
///
/// In general, a `StaticRef` is faster than a `StaticGlobal`.
pub struct StaticSymbolRef {
    sym: AtomicPtr<jl_sym_t>,
    sym_s: &'static str,
}

impl StaticSymbolRef {
    /// Define a new static symbol.
    ///
    /// The symbol is initialized the first time `get_or_init` is called. The `sym_s` argument
    /// must be the symbol as a static string.
    #[inline]
    pub const fn new(sym_s: &'static str) -> StaticSymbolRef {
        StaticSymbolRef {
            sym: AtomicPtr::new(null_mut()),
            sym_s,
        }
    }

    /// Get the symbol, create it if it doesn't exist yet.
    #[inline]
    pub fn get_or_init<'target, Tgt>(&self, target: &Tgt) -> Symbol<'target>
    where
        Tgt: Target<'target>,
    {
        let ptr = self.sym.load(Ordering::Relaxed);
        if ptr.is_null() {
            // It's fine to initialize this multiple times. We're going to store the same data each time.
            self.init(target)
        } else {
            unsafe { Symbol::wrap_non_null(NonNull::new_unchecked(ptr), Private) }
        }
    }

    #[cold]
    #[inline(never)]
    fn init<'target, Tgt>(&self, _: &Tgt) -> Symbol<'target>
    where
        Tgt: Target<'target>,
    {
        unsafe {
            let bytes = self.sym_s.as_bytes();
            let n_bytes = bytes.len();
            let bytes_ptr = bytes.as_ptr().cast();

            let sym = jl_symbol_n(bytes_ptr, n_bytes);
            self.sym.store(sym, Ordering::Relaxed);

            Symbol::wrap_non_null(NonNull::new_unchecked(sym), Private)
        }
    }
}

/// Static reference to arbitrary managed data. Can be initialized multiple times.
///
/// In general, a `StaticRef` is faster than a `StaticGlobal`.
pub struct StaticRef<T: Managed<'static, 'static>> {
    global: AtomicPtr<T::Wraps>,
    path: &'static str,
}

impl<T> StaticRef<T>
where
    T: Managed<'static, 'static> + Typecheck,
{
    /// Define a new static ref available at `path`.
    ///
    /// The global is looked up if the ref is uninitialized. The `path` argument must be the full
    /// path to the data, e.g. `"Main.Submodule.Foo"`.
    #[inline]
    pub const fn new(path: &'static str) -> StaticRef<T> {
        StaticRef {
            global: AtomicPtr::new(null_mut()),
            path,
        }
    }

    /// Get the global data, look it up if it doesn't exist yet.
    ///
    /// The global must exist and be an instance of `T`. Otherwise this method will panic.
    #[inline]
    pub fn get_or_init<'target, Tgt>(&self, target: &Tgt) -> T
    where
        Tgt: Target<'target>,
    {
        let ptr = self.global.load(Ordering::Relaxed);
        if ptr.is_null() {
            // It's fine to initialize this multiple times. We're going to store the same data each time.
            self.init(target)
        } else {
            unsafe { T::wrap_non_null(NonNull::new_unchecked(ptr), Private) }
        }
    }

    #[cold]
    #[inline(never)]
    fn init<'target, Tgt>(&self, target: &Tgt) -> T
    where
        Tgt: Target<'target>,
    {
        unsafe {
            let split_path = self.path.split('.').collect::<Vec<_>>();
            let n_parts = split_path.len();
            if n_parts == 1 {
                return get_top_item(target, split_path[0]).unwrap();
            }

            let mut module = get_top_item::<_, Module>(target, split_path[0]).unwrap();

            for i in 1..n_parts - 1 {
                module = module
                    .submodule(target, split_path[i])
                    .unwrap()
                    .as_managed();
            }

            let global = module
                .global(target, split_path[n_parts - 1])
                .unwrap()
                .leak()
                .as_value();

            let key = global.as_weak().ptr().as_ptr().addr();
            CACHE.insert(key, global);

            let ptr = global.cast::<T>().unwrap().unwrap(Private);
            self.global.store(ptr, Ordering::Relaxed);
            T::wrap_non_null(NonNull::new_unchecked(ptr), Private)
        }
    }

    // Safety: The result of the evaluated command must be globally rooted.
    #[inline]
    pub(crate) unsafe fn get_or_eval<'target, Tgt>(&self, target: &Tgt) -> T
    where
        Tgt: Target<'target>,
    {
        unsafe {
            let ptr = self.global.load(Ordering::Relaxed);
            if ptr.is_null() {
                self.eval(target)
            } else {
                T::wrap_non_null(NonNull::new_unchecked(ptr), Private)
            }
        }
    }

    // Safety: The result of the evaluated command must be globally rooted.
    #[cold]
    #[inline(never)]
    unsafe fn eval<'target, Tgt>(&self, target: &Tgt) -> T
    where
        Tgt: Target<'target>,
    {
        unsafe {
            let global = Value::eval_string(target, self.path)
                .unwrap()
                .leak()
                .as_value();

            let key = global.as_weak().ptr().as_ptr().addr();
            CACHE.insert(key, global);

            let ptr = global.cast::<T>().unwrap().unwrap(Private);
            self.global.store(ptr, Ordering::Relaxed);
            T::wrap_non_null(NonNull::new_unchecked(ptr), Private)
        }
    }
}

/// Static reference to a constructible type.
pub struct StaticConstructibleType<T: ConstructType> {
    global: AtomicPtr<jl_value_t>,
    _marker: PhantomData<T>,
}

impl<T> StaticConstructibleType<T>
where
    T: ConstructType,
{
    /// Define a new static ref for the constructible type `T`.
    #[inline]
    pub const fn new() -> StaticConstructibleType<T> {
        StaticConstructibleType {
            global: AtomicPtr::new(null_mut()),
            _marker: PhantomData,
        }
    }

    /// Get the constructed type, construct it if it doesn't exist yet.
    #[inline]
    pub fn get_or_init<'target, Tgt>(&self, target: &Tgt) -> Value<'target, 'static>
    where
        Tgt: Target<'target>,
    {
        let ptr = self.global.load(Ordering::Relaxed);
        if ptr.is_null() {
            // It's fine to initialize this multiple times. We're going to store the same data each time.
            self.init(target)
        } else {
            unsafe { Value::wrap_non_null(NonNull::new_unchecked(ptr), Private) }
        }
    }

    #[cold]
    #[inline(never)]
    fn init<'target, Tgt>(&self, target: &Tgt) -> Value<'target, 'static>
    where
        Tgt: Target<'target>,
    {
        unsafe {
            let global = T::construct_type(target).as_value().leak().as_value();
            let key = global.as_weak().ptr().as_ptr().addr();
            CACHE.insert(key, global);

            let ptr = global.unwrap(Private);
            self.global.store(ptr, Ordering::Relaxed);

            global
        }
    }
}

/// Define a static global
#[macro_export]
macro_rules! define_static_global {
    ($(#[$meta:meta])* $vis:vis $ty:ident, $type:ty, $path:expr_2021) => {
        $(#[$meta])*
        $vis static $name: $crate::data::static_data::StaticGlobal<$type> =
            $crate::data::static_data::StaticGlobal::new($path);
    };
    ($(#[$meta:meta])* $vis:vis $name:ident, $path:expr_2021) => {
        $(#[$meta])*
        $vis static $name: $crate::data::static_data::StaticGlobal<
            $crate::data::managed::value::ValueUnbound,
        > = $crate::data::static_data::StaticGlobal::new_value($path);
    };
}

/// Define a static ref
#[macro_export]
macro_rules! define_static_ref {
    ($(#[$meta:meta])* $vis:vis $name:ident, $type:ty, $path:expr_2021) => {
        $(#[$meta])*
        $vis static $name: $crate::data::static_data::StaticRef<$type> =
            $crate::data::static_data::StaticRef::new($path);
    };
}

/// Define a static symbol
#[macro_export]
macro_rules! define_static_symbol_ref {
    ($(#[$meta:meta])+ $vis:vis $name:ident, $sym:expr_2021) => {
        $(#[$meta])+
        $vis static $name: $crate::data::static_data::StaticSymbolRef =
            $crate::data::static_data::StaticSymbolRef::new($sym);
    };
}

/// Use a previously defined static global
#[macro_export]
macro_rules! static_global {
    ($name:ident, $target:expr_2021) => {{ $name.get_or_init(&$target) }};
}
/// Use a previously defined static ref
#[macro_export]
macro_rules! static_ref {
    ($name:ident, $target:expr_2021) => {{ $name.get_or_init(&$target) }};
}
/// Use a previously defined static ref
#[macro_export]
macro_rules! static_symbol_ref {
    ($name:ident, $target:expr_2021) => {{ $name.get_or_init(&$target) }};
}

pub use define_static_global;
pub use define_static_ref;
pub use define_static_symbol_ref;
pub use static_global;
pub use static_ref;
pub use static_symbol_ref;

/// Define an inline static global.
///
/// `inline_static_global!(NAME, T, path, target)` is equivalent to
/// `{ define_static_global!(NAME, T, path); static_global!(NAME, target) }`
#[macro_export]
macro_rules! inline_static_global {
    ($(#[$meta:meta])* $name:ident, $type:ty, $path:expr_2021, $target:expr_2021) => {{
        $crate::data::static_data::define_static_global!($(#[$meta])* $name, $type, $path);
        $crate::data::static_data::static_global!($name, $target)
    }};
    ($(#[$meta:meta])* $name:ident, $path:expr_2021, $target:expr_2021) => {{
        $crate::data::static_data::define_static_global!($(#[$meta])* $name, $path);
        $crate::data::static_data::static_global!($name, $target)
    }};
}

/// Define an inline static ref.
///
/// `inline_static_ref!(NAME, T, path, target)` is equivalent to
/// `{ define_static_ref!(NAME, T, path); static_ref!(NAME, target) }`
#[macro_export]
macro_rules! inline_static_ref {
    ($(#[$meta:meta])* $name:ident, $type:ty, $path:expr_2021, $target:expr_2021) => {{
        $crate::data::static_data::define_static_ref!($(#[$meta])* $name, $type, $path);
        $crate::data::static_data::static_ref!($name, $target)
    }};
}

/// Define an inline static ref.
///
/// `inline_static_ref!(NAME, T, path, target)` is equivalent to
/// `{ define_static_ref!(NAME, T, path); static_ref!(NAME, target) }`
#[macro_export]
macro_rules! inline_static_symbol_ref {
    ($(#[$meta:meta])* $name:ident, $sym:expr_2021, $target:expr_2021) => {{
        $crate::data::static_data::define_static_symbol_ref!($(#[$meta])* $name, $sym);
        $crate::data::static_data::static_symbol_ref!($name, $target)
    }};
}

pub use inline_static_global;
pub use inline_static_ref;
pub use inline_static_symbol_ref;