rustcall_julia_core 0.7.0

Shared Rust core for RustCall.jl: FFI manifest model, syn-based extraction, wrapper codegen, generic specialization
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
//! Shared Rust core for RustCall.jl.
//!
//! This crate is the single place where Rust syntax is interpreted on behalf
//! of RustCall.jl. It is consumed by two front ends:
//!
//! * `rustcall_julia_macros_impl`, the `#[julia]` proc-macro a user's crate
//!   reaches through `rustcall_julia_macros` (the crates `@rust_crate`
//!   builds);
//! * `rustcall_extract` (CLI) for `rust"""` blocks, `@rust_crate` scanning and
//!   generic monomorphization.
//!
//! Julia never parses Rust source itself; it reads the [`manifest::Manifest`]
//! produced here.

pub mod attrs;
mod borrow_scope;
pub mod cfg;
pub mod claims;
pub mod codegen;
pub mod environment;
pub mod expand;
pub mod extract;
pub mod include_paths;
pub mod manifest;
pub mod model;
mod owned_returns;
pub mod paths;
pub mod public_routes;
pub mod pyo3;
// Embedded verbatim in generated PyO3 wrapper crates; compiled here for its tests.
#[cfg(test)]
mod python_stack;
pub mod receiver;
pub mod refusal;
pub mod specialize;
pub mod types;
pub mod wrap;

pub use manifest::{Manifest, Mode, SCHEMA_VERSION};

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn inline_manifest_matches_expanded_code() {
        let src = r#"
            #[julia]
            fn add(a: i32, b: i32) -> i32 { a + b }

            #[julia]
            fn safe_div(a: f64, b: f64) -> Option<f64> { if b == 0.0 { None } else { Some(a / b) } }

            #[julia]
            pub struct Point { x: f64, y: f64 }

            impl Point {
                pub fn new(x: f64, y: f64) -> Self { Self { x, y } }
                pub fn norm(&self) -> f64 { (self.x * self.x + self.y * self.y).sqrt() }
                fn private(&self) -> f64 { 0.0 }
            }

            #[no_mangle]
            pub extern "C" fn raw(a: u8) -> u8 { a }

            pub fn identity<T: Copy>(x: T) -> T where T: Clone { x }
        "#;
        let e = expand::expand(src).unwrap();
        let m = &e.manifest;

        let add = m.functions.iter().find(|f| f.name == "add").unwrap();
        assert!(add.exported);
        assert_eq!(add.return_kind, manifest::ReturnKind::Plain);
        assert_eq!(add.args.len(), 2);
        assert!(e.source.contains(
            "pub extern \"C\" fn rustcall_add(a: i32, b: i32) -> ::std::mem::MaybeUninit<i32>"
        ));

        let div = m.functions.iter().find(|f| f.name == "safe_div").unwrap();
        assert_eq!(div.return_kind, manifest::ReturnKind::Option);
        assert_eq!(div.inner_type, "f64");
        assert!(e.source.contains("COption_safe_div"));

        let raw = m.functions.iter().find(|f| f.name == "raw").unwrap();
        assert_eq!(raw.attribute, manifest::Attribute::None);
        assert!(raw.exported);

        let id = m.functions.iter().find(|f| f.name == "identity").unwrap();
        assert!(id.is_generic);
        assert!(!id.exported);
        assert_eq!(id.type_params[0].name, "T");
        let bounds: Vec<_> = id.type_params[0]
            .bounds
            .iter()
            .map(|b| b.trait_name.clone())
            .collect();
        assert_eq!(bounds, vec!["Copy", "Clone"]);
        assert!(id.source.contains("fn identity"));

        let p = &m.structs[0];
        assert_eq!(p.name, "Point");
        assert_eq!(p.fields.len(), 2);
        let names: Vec<_> = p.methods.iter().map(|m| m.name.clone()).collect();
        assert_eq!(names, vec!["new", "norm"]);
        assert!(p.methods[0].is_constructor);
        assert!(e.source.contains("pub extern \"C\" fn Point_free"));
        assert!(e.source.contains("pub extern \"C\" fn rustcall_Point_new"));
        assert!(e.source.contains("pub extern \"C\" fn Point_get_x"));
        assert!(!e.source.contains("#[julia]"));
    }

    #[test]
    fn julia_attr_inside_string_is_ignored() {
        let src = r##"
            fn f() -> &'static str { "#[julia] fn fake() {}" }
        "##;
        let e = expand::expand(src).unwrap();
        assert!(e
            .manifest
            .functions
            .iter()
            .all(|f| f.attribute == manifest::Attribute::None));
        assert!(!e.source.contains("extern \"C\" fn fake"));
    }

    #[test]
    fn nested_block_comments_and_raw_strings() {
        let src = r##"
            #[julia]
            fn f() -> i32 { /* outer /* inner */ } still outer */ let s = r#"{"#; let _ = s; 1 }
            #[julia]
            fn g() -> i32 { 2 }
        "##;
        let e = expand::expand(src).unwrap();
        let names: Vec<_> = e
            .manifest
            .functions
            .iter()
            .map(|f| f.name.clone())
            .collect();
        assert_eq!(names, vec!["f", "g"]);
    }

    #[test]
    fn where_clause_and_const_generic_expr() {
        let src = r#"
            #[julia]
            fn foo(x: [u8; { if 1 < 2 { 3 } else { 4 } }], y: i32) {}
            fn bar<T>(x: T) -> T where T: Copy { x }
        "#;
        let e = expand::expand(src).unwrap();
        let foo = &e.manifest.functions[0];
        assert_eq!(foo.args[1].rust_type, "i32");
        assert_eq!(foo.return_type, "()");
        let bar = &e.manifest.functions[1];
        assert_eq!(bar.return_type, "T");
        assert_eq!(bar.type_params[0].bounds[0].trait_name, "Copy");
    }

    #[test]
    fn crate_mode_follows_proc_macro_rules() {
        let src = r#"
            use rustcall_julia_macros::julia;
            #[julia]
            fn add(a: i32, b: i32) -> i32 { a + b }
            #[julia]
            fn parse(n: i32) -> Result<u32, i32> { Ok(n as u32) }
            #[julia]
            pub struct Counter { count: u32, name: String }
            #[julia]
            impl Counter {
                #[julia]
                pub fn new() -> Self { Self { count: 0, name: String::new() } }
                #[julia]
                pub fn increment(&mut self) { self.count += 1; }
                pub fn not_wrapped(&self) {}
            }
            impl Counter {
                pub fn also_not_wrapped(&self) {}
            }
        "#;
        let m = extract::extract(src, Mode::Crate).unwrap();
        assert_eq!(m.functions.len(), 2);
        assert_eq!(m.functions[1].return_kind, manifest::ReturnKind::Result);
        assert_eq!(m.functions[1].ok_type, "u32");
        let c = &m.structs[0];
        let names: Vec<_> = c.methods.iter().map(|m| m.name.clone()).collect();
        assert_eq!(names, vec!["new", "increment"]);
        assert_eq!(c.methods[0].symbol, "rustcall_Counter_new");
        assert!(c.fields.iter().all(|f| f.ffi_compatible));
    }

    #[test]
    fn generic_struct_reports_wrappers() {
        let src = r#"
            #[julia]
            pub struct Pair<T> { a: T, b: T }
            impl<T: Copy> Pair<T> {
                pub fn new(a: T, b: T) -> Self { Self { a, b } }
                pub fn first(&self) -> T { self.a }
            }
        "#;
        let e = expand::expand(src).unwrap();
        let s = &e.manifest.structs[0];
        assert_eq!(s.type_params[0].name, "T");
        let names: Vec<_> = s.generic_wrappers.iter().map(|w| w.name.clone()).collect();
        assert!(names.contains(&"Pair_new".to_string()));
        assert!(names.contains(&"Pair_first".to_string()));
        assert!(names.contains(&"Pair_free".to_string()));
        assert!(names.contains(&"Pair_get_a".to_string()));
        assert!(s.context_source.contains("pub struct Pair<T>"));
        // generic wrappers are emitted (unexported) so they can be specialized in place
        assert!(e.source.contains("pub fn Pair_free<T>"));
        assert!(!e.source.contains("extern \"C\" fn Pair_free"));
        let sp = specialize::specialize(
            &e.source,
            "Pair_first",
            &[("T".to_string(), "i32".to_string())],
            "Pair_first_i32",
        )
        .unwrap();
        let flat = sp.source.split_whitespace().collect::<Vec<_>>().join(" ");
        assert!(
            flat.contains(
                "pub extern \"C\" fn rustcall_Pair_first_i32( ptr: *const Pair<i32>, ) -> ::std::mem::MaybeUninit<i32>"
            ) || flat.contains(
                "pub extern \"C\" fn rustcall_Pair_first_i32(ptr: *const Pair<i32>) -> ::std::mem::MaybeUninit<i32>"
            ),
            "{flat}"
        );

        let full = format!("{}\n{}", s.context_source, s.generic_wrappers[0].source);
        let sp = specialize::specialize(
            &full,
            "Pair_new",
            &[("T".to_string(), "i32".to_string())],
            "Pair_new_i32",
        )
        .unwrap();
        let flat = sp.source.split_whitespace().collect::<Vec<_>>().join(" ");
        assert!(
            flat.contains(
                "pub extern \"C\" fn rustcall_Pair_new_i32( a: i32, b: i32, ) -> ::std::mem::MaybeUninit<*mut Pair<i32>>"
            ) || flat.contains(
                "pub extern \"C\" fn rustcall_Pair_new_i32(a: i32, b: i32) -> ::std::mem::MaybeUninit<*mut Pair<i32>>"
            ),
            "{flat}"
        );
    }

    #[test]
    fn inline_modules_are_expanded_recursively() {
        let src = r#"
            mod api {
                #[julia]
                pub fn inner_add(a: i32, b: i32) -> i32 { a + b }
                #[julia]
                pub struct P { x: f64 }
                impl P { pub fn new(x: f64) -> Self { Self { x } } }
                mod deep { #[julia] fn deeper() -> u8 { 1 } }
            }
            mod external;
        "#;
        let e = expand::expand(src).unwrap();
        let names: Vec<_> = e
            .manifest
            .functions
            .iter()
            .map(|f| f.name.clone())
            .collect();
        assert_eq!(names, vec!["inner_add", "deeper"]);
        assert_eq!(e.manifest.functions[1].module_path, vec!["api", "deep"]);
        assert_eq!(e.manifest.structs[0].name, "P");
        assert_eq!(e.manifest.structs[0].module_path, vec!["api"]);
        // Inline expansion qualifies every symbol by the module path it walks
        // (#300); the manifest says so in `ffi_name` / `symbol`.
        assert_eq!(e.manifest.functions[0].ffi_name, "api__inner_0add");
        assert_eq!(e.manifest.functions[0].symbol, "rustcall_api__inner_0add");
        assert_eq!(e.manifest.functions[1].symbol, "rustcall_api__deep__deeper");
        assert_eq!(e.manifest.structs[0].ffi_name, "api__P");
        assert_eq!(
            e.manifest.structs[0].methods[0].symbol,
            "rustcall_api__P_new"
        );
        assert!(e
            .source
            .contains("pub extern \"C\" fn rustcall_api__inner_0add"));
        assert!(e.source.contains("pub extern \"C\" fn rustcall_api__P_new"));
        assert!(e.source.contains("pub extern \"C\" fn api__P_free"));
        assert!(!e.source.contains("#[julia]"));
        assert!(e.source.contains("mod external;"));

        // Crate mode mirrors the proc-macro, which cannot see an unmarked
        // module: the block is refused with the fix in the message.
        let err = extract::extract(src, Mode::Crate).unwrap_err();
        assert!(matches!(err, extract::ExtractError::Unsupported(_)));
        let msg = err.to_string();
        assert!(msg.contains("`inner_add`"), "{msg}");
        assert!(msg.contains("#[julia] pub mod api"), "{msg}");

        // Marked modules are the crate-mode spelling of the same path.
        let marked = src
            .replace("mod api {", "#[julia] mod api {")
            .replace("mod deep {", "#[julia] mod deep {");
        let c = extract::extract(&marked, Mode::Crate).unwrap();
        assert_eq!(c.functions.len(), 2);
        assert_eq!(c.structs.len(), 1);
        assert_eq!(c.functions[0].symbol, "rustcall_api__inner_0add");
        assert_eq!(c.functions[0].module_path, vec!["api"]);
        assert_eq!(c.functions[1].symbol, "rustcall_api__deep__deeper");
        assert_eq!(c.structs[0].ffi_name, "api__P");
        assert_eq!(c.structs[0].module_path, vec!["api"]);
        // The expanded inline block and the crate manifest agree symbol for symbol
        // (the crate flavour wraps only `#[julia]` methods, so `P` has none here).
        assert_eq!(c.functions[0].symbol, e.manifest.functions[0].symbol);
        assert!(c.structs[0].methods.is_empty());
    }

    #[test]
    fn generic_wrappers_typecheck_generically() {
        let src = r#"
            #[julia]
            pub struct Bag<T> where T: Copy { items: Vec<Option<T>>, label: String, first: T }
            impl<T> Bag<T> where T: Copy {
                pub fn new(first: T) -> Self { Self { items: Vec::new(), label: String::new(), first } }
                pub fn first(&self) -> T { self.first }
            }
        "#;
        let e = expand::expand(src).unwrap();
        assert!(e.source.contains("String: Clone"));
        // A `Vec` field gets no accessor (#453).
        assert!(!e.source.contains("Bag_get_items"));
        assert!(e.source.contains("T: Copy"));
        // Prove it with rustc when available.
        if let Ok(rustc) = std::env::var("RUSTC").or_else(|_| Ok::<_, ()>("rustc".to_string())) {
            let dir = std::env::temp_dir()
                .join(format!("rustcall_julia_core_gen_{}", std::process::id()));
            std::fs::create_dir_all(&dir).unwrap();
            let file = dir.join("bag.rs");
            std::fs::write(&file, format!("#![allow(unused)]\n{}", e.source)).unwrap();
            if let Ok(out) = std::process::Command::new(rustc)
                .args(["--crate-type", "cdylib", "--edition", "2021", "-o"])
                .arg(dir.join("libbag.so"))
                .arg(&file)
                .output()
            {
                assert!(
                    out.status.success(),
                    "{}",
                    String::from_utf8_lossy(&out.stderr)
                );
            }
            let _ = std::fs::remove_dir_all(&dir);
        }
    }

    #[test]
    fn const_generics_are_not_exported() {
        let src = r#"
            #[julia]
            fn lookup<const N: usize>(x: [u8; N]) -> u8 { x[0] }
            pub fn plain<const N: usize>() -> usize { N }
        "#;
        let e = expand::expand(src).unwrap();
        let lookup = &e.manifest.functions[0];
        assert!(!lookup.exported);
        assert!(lookup.is_generic);
        assert!(e.source.contains("compile_error!"));
        assert!(!e.source.contains("extern \"C\" fn lookup"));
        let plain = &e.manifest.functions[1];
        assert!(!plain.exported && plain.is_generic);
        let err = specialize::specialize(&e.source, "plain", &[], "plain_1").unwrap_err();
        assert!(
            matches!(err, specialize::SpecializeError::UnboundParams(ref p) if p == &vec!["N".to_string()])
        );
    }

    #[test]
    fn impl_with_renamed_parameters() {
        let src = r#"
            #[julia]
            pub struct Wrapper<T> { value: T }
            impl<U: Copy> Wrapper<U> {
                pub fn new(value: U) -> Self { Self { value } }
                pub fn get(&self) -> U { self.value }
            }
        "#;
        let e = expand::expand(src).unwrap();
        assert!(e
            .source
            .contains("pub fn Wrapper_get<U: Copy>(ptr: *const Wrapper<U>) -> U"));
        let s = &e.manifest.structs[0];
        let get = s
            .generic_wrappers
            .iter()
            .find(|w| w.name == "Wrapper_get")
            .unwrap();
        assert_eq!(get.type_params, vec!["U"]);
        let free = s
            .generic_wrappers
            .iter()
            .find(|w| w.name == "Wrapper_free")
            .unwrap();
        assert_eq!(free.type_params, vec!["T"]);
        let sp = specialize::specialize(
            &e.source,
            "Wrapper_get",
            &[("U".into(), "i32".into())],
            "Wrapper_get_i32",
        )
        .unwrap();
        assert!(sp
            .source
            .contains("fn Wrapper_get_i32(ptr: *const Wrapper<i32>) -> i32"));
        assert!(e
            .source
            .contains("pub fn Wrapper_new<U: Copy>(value: U) -> *mut Wrapper<U>"));
        assert!(!e.source.contains("Wrapper<T>) -> U"));
    }

    #[test]
    fn impl_trait_arguments_are_not_exported() {
        let src = "#[julia] fn f(x: impl Copy) -> i32 { let _ = x; 1 }\n#[julia] fn g() -> impl Copy { 1 }\n#[julia] fn h(x: &impl Copy) {}";
        let e = expand::expand(src).unwrap();
        assert!(e
            .manifest
            .functions
            .iter()
            .all(|f| !f.exported && f.is_generic));
        assert_eq!(e.source.matches("compile_error!").count(), 3);
        // No wrapper for any of the three. The file-level quiet-panic hook of
        // #304 is `extern "C"` and always there, so the absence is asserted of
        // the wrappers themselves.
        for name in ["rustcall_f", "rustcall_g", "rustcall_h"] {
            assert!(!e.source.contains(name), "{name} should not be exported");
        }
    }

    /// #304: the quiet panic hook exists exactly where a generator writes the
    /// whole file, and the crate flavour does not so much as name it.
    #[test]
    fn only_the_file_owned_flavour_takes_a_boundary_guard() {
        let e = expand::expand("#[julia] pub fn f() -> i32 { 1 }").unwrap();
        // One guard in the wrapper, one set of shared items at the root.
        assert_eq!(
            e.source
                .matches("crate::__RustCallBoundary::enter()")
                .count(),
            1,
            "{}",
            e.source
        );
        assert_eq!(e.source.matches("pub struct __RustCallBoundary").count(), 1);
        assert_eq!(
            e.source.matches("fn __rustcall_install_panic_hook").count(),
            1
        );
        assert_eq!(
            e.source
                .matches("fn __rustcall_uninstall_panic_hook")
                .count(),
            1
        );

        // The proc-macro flavour: `#[julia]` is handed one item and cannot emit
        // the shared items, so it takes the guard from the runtime crate the
        // user's crate already depends on and defines nothing itself (#304).
        let item: syn::ItemFn = syn::parse_str("#[julia] pub fn f() -> i32 { 1 }").unwrap();
        let crate_flavour =
            codegen::transform_function(item, &[], codegen::PanicHook::Runtime).to_string();
        assert!(crate_flavour.contains("catch_unwind"));
        assert!(crate_flavour.contains(":: rustcall_julia_macros :: __RustCallBoundary :: enter"));
        assert!(!crate_flavour.contains("crate :: __RustCallBoundary"));
        assert!(!crate_flavour.contains("fn __rustcall_install_panic_hook"));

        // `External` is still the one flavour that takes no guard at all.
        let item: syn::ItemFn = syn::parse_str("#[julia] pub fn f() -> i32 { 1 }").unwrap();
        let bare = codegen::transform_function(item, &[], codegen::PanicHook::External).to_string();
        assert!(bare.contains("catch_unwind"));
        assert!(!bare.contains("__RustCallBoundary"));
    }

    /// Every wrapper of a block shares the one counter, whichever module it
    /// sits in: that is what the file-level placement buys, and what a
    /// per-wrapper counter could not give.
    #[test]
    fn every_wrapper_of_a_block_guards_against_the_same_counter() {
        let src = "#[julia] pub fn a() -> i32 { 1 }\n                   pub mod m { #[julia] pub fn b() -> i32 { 2 } }\n                   #[julia] pub struct S { pub v: i32 }";
        let e = expand::expand(src).unwrap();
        // Two functions, the struct's free, its accessors: every one of them.
        assert!(
            e.source
                .matches("crate::__RustCallBoundary::enter()")
                .count()
                >= 4,
            "{}",
            e.source
        );
        // ...and there is still exactly one of everything shared.
        assert_eq!(e.source.matches("pub struct __RustCallBoundary").count(), 1);
        assert_eq!(
            e.source
                .matches("static __RUSTCALL_QUIET_HOOK_LIVE")
                .count(),
            1
        );
    }

    #[test]
    fn manifest_roundtrips_through_toml() {
        let e = expand::expand("#[julia] fn a(x: i32) -> i32 { x }").unwrap();
        let toml = e.manifest.to_toml().unwrap();
        let back = Manifest::from_toml(&toml).unwrap();
        assert_eq!(back, e.manifest);
    }
}

mod optional_borrows;
mod slices;