rustcall_julia_core 0.6.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
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
//! Intermediate model of `#[julia]` structs and their impl blocks, built from a
//! parsed file and shared by extraction and code generation.

use syn::spanned::Spanned;
use syn::{ImplItem, ImplItemFn, Item, ItemImpl, ItemStruct, Type, Visibility};

use crate::attrs::{derive_list, is_julia_attr, rustcall_attribute};
use crate::manifest::{Attribute, Mode};

/// Where a method's `#[julia] impl` block was written: the module the block
/// sits in, and the path its header spells the struct with (`super::Gauge`).
///
/// A block may sit in another module than its struct (#315). The inline
/// expander emits such a block's wrappers **at the block** (#342), where the
/// types its signatures name are in scope, spelling the struct exactly as the
/// header does — which is what the proc-macro already does for the crate
/// flavour (`transform_impl_crate`).
#[derive(Debug, Clone)]
pub struct ImplSite {
    /// The module the block sits in, as a path from the crate root.
    pub module_path: Vec<String>,
    /// The impl header's own type path (`super::Gauge`, `crate::a::C`).
    pub self_ty: Type,
}

/// The header of the impl block a method was written in: what its signature's
/// `Self` and the block's own generics mean (#482). A generated wrapper
/// declares the block's generics and `where` clause, then the method's, and
/// spells `Self` as `self_ty` (`crate::environment`).
#[derive(Debug, Clone)]
pub struct ImplHost {
    /// The block's generics, `where` clause included (`impl<'x> Buf where ..`).
    pub generics: syn::Generics,
    /// The header's type as written (`Buf`, `super::Buf`).
    pub self_ty: Type,
    /// The trait of a trait impl, through which a bare `Self::Assoc` resolves.
    pub trait_: Option<syn::Path>,
}

impl ImplHost {
    pub fn of(imp: &ItemImpl) -> Self {
        ImplHost {
            generics: imp.generics.clone(),
            self_ty: (*imp.self_ty).clone(),
            trait_: imp.trait_.as_ref().map(|(_, path, _)| path.clone()),
        }
    }
}

#[derive(Debug, Clone)]
pub struct MethodModel {
    pub func: ImplItemFn,
    /// The RustCall attribute of the impl block the method was collected from
    /// (`Julia`, or `None` for an inline-mode impl that carries none).
    /// Recorded on the manifest entry (`Method.attribute`, #275 Phase 3).
    pub attribute: Attribute,
    /// The `#[cfg]` of the impl block and of every module enclosing it: the
    /// method exists only under those predicates as much as under its own
    /// (#300 review, #315). Empty for a wrapper generated from a lone method.
    pub enclosing_cfg: Vec<syn::Attribute>,
    /// Where the block that declared the method was written (#342). `None`
    /// for a method not collected from a block ([`MethodModel::from_fn`]) and
    /// for a block attached without a module (`attach_impl` with `None`),
    /// which is then its struct's neighbour.
    pub site: Option<ImplSite>,
    /// The header of the block the method was collected from (#482). `None`
    /// for a lone method ([`MethodModel::from_fn`]); its wrapper then takes
    /// the struct as `Self` and no generics of a block.
    pub host: Option<ImplHost>,
    /// Whether the declared return type, spelled otherwise than `Self` or the
    /// header, was **resolved** to the struct the block belongs to
    /// ([`crate::paths::names_struct`], #518): `-> super::Gauge` in `use
    /// super::Gauge as Meter; impl Meter`, `-> crate::Gauge` in `impl Gauge`.
    /// Only the inline expander resolves names ([`ModelTree::collect`]); the
    /// proc macro sees one block, so for the crate flavour this stays `false`
    /// and [`crate::codegen::returns_own_type`]'s spelling rule alone decides.
    pub returns_own_type_resolved: bool,
}

impl MethodModel {
    pub fn from_fn(func: &ImplItemFn, attribute: Attribute) -> Self {
        MethodModel {
            func: func.clone(),
            attribute,
            enclosing_cfg: Vec::new(),
            site: None,
            host: None,
            returns_own_type_resolved: false,
        }
    }

    pub fn name(&self) -> String {
        self.func.sig.ident.to_string()
    }

    /// The method's receiver (#509), read against the header of its block:
    /// a typed receiver may name the type as the header spells it. The one
    /// source of the wrapper's pointer, binding and call argument, and of the
    /// manifest's `is_static` / `is_mutable`.
    pub fn receiver(&self) -> crate::receiver::Receiver {
        crate::receiver::Receiver::of(&self.func.sig, self.host.as_ref().map(|h| &h.self_ty))
    }

    /// An associated function, which takes no object.
    pub fn is_static(&self) -> bool {
        self.receiver().is_static()
    }

    /// Whether the method borrows the object mutably
    /// ([`crate::receiver::Receiver::is_mutable`]).
    pub fn is_mutable(&self) -> bool {
        self.receiver().is_mutable()
    }

    /// The trait of the block the method was written in, as the header
    /// spells it (`tr::Limits`), or empty for an inherent method: the
    /// manifest's `Method.trait_path` (#503).
    pub fn trait_path(&self) -> String {
        self.host
            .as_ref()
            .and_then(|h| h.trait_.as_ref())
            .map(|path| {
                crate::types::type_to_string(&syn::Type::Path(syn::TypePath {
                    qself: None,
                    path: path.clone(),
                }))
            })
            .unwrap_or_default()
    }

    /// The part of every per-method name after the struct stem
    /// ([`crate::codegen::method_stem`], #506): the name, preceded by the
    /// trait's for a method of a trait impl.
    pub fn method_stem(&self) -> String {
        let trait_name = self
            .host
            .as_ref()
            .and_then(|h| h.trait_.as_ref())
            .and_then(crate::codegen::trait_name_of);
        crate::codegen::method_stem(trait_name.as_deref(), &self.name())
    }

    /// Whether the method returns the implementing type by value: its wrapper
    /// returns an owning pointer. Read from the return type and the block's
    /// header, never the name — spelled `Self` or as the header spells it
    /// ([`crate::codegen::returns_own_type`]), or resolved to the struct by
    /// the inline expander ([`MethodModel::returns_own_type_resolved`]). A
    /// type that merely shares the header's last segment is not it (#518).
    pub fn returns_boxed_struct(&self, struct_name: &syn::Ident) -> bool {
        self.returns_own_type_resolved
            || crate::codegen::returns_own_type(
                &self.func.sig.output,
                struct_name,
                self.host.as_ref().map(|h| &h.self_ty),
            )
    }

    /// An inherent static constructor returning `Result<Self, E>` with an
    /// FFI-representable error: a [`MethodModel::boxed_self_result`] Julia
    /// binds as the struct's constructor.
    pub fn fallible_constructor(
        &self,
        struct_name: &syn::Ident,
    ) -> Option<crate::types::ResultTypeInfo> {
        if !self.receiver().is_static() || !self.trait_path().is_empty() {
            return None;
        }
        self.boxed_self_result(struct_name)
    }

    /// Any method returning `Result<Self, E>` (or the struct as the header
    /// spells it) with an FFI-representable error, whatever its receiver:
    /// codegen boxes the successful value, so Julia receives an owning
    /// pointer of the image that ran the call (#559, #564). A receiver method
    /// (`fn duplicate(&self) -> Result<Self, String>`) is not a constructor —
    /// see [`MethodModel::fallible_constructor`] — but its `Ok` payload
    /// crosses the boundary exactly like one; returning `Self` by value inside
    /// the aggregate would hand Julia a Rust value it cannot own.
    pub fn boxed_self_result(
        &self,
        struct_name: &syn::Ident,
    ) -> Option<crate::types::ResultTypeInfo> {
        let syn::ReturnType::Type(_, ty) = &self.func.sig.output else {
            return None;
        };
        let result = crate::types::extract_result_type(ty)?;
        if !crate::refusal::payload_is_representable(&result.err_type) {
            return None;
        }
        let output = syn::ReturnType::Type(Default::default(), Box::new(result.ok_type.clone()));
        crate::codegen::returns_own_type(
            &output,
            struct_name,
            self.host.as_ref().map(|h| &h.self_ty),
        )
        .then_some(result)
    }

    /// Whether Julia binds the method as the struct's constructor (`Buf(..)`):
    /// an inherent method returning the type. A trait's `Self`-returning
    /// function (`Default::default`, `From::from`) keeps its own name, and
    /// would otherwise shadow the inherent constructor (#506).
    pub fn is_constructor(&self, struct_name: &syn::Ident) -> bool {
        self.trait_path().is_empty()
            && (self.returns_boxed_struct(struct_name)
                || self.fallible_constructor(struct_name).is_some())
    }

    /// Whether `other` is this method: the same name in the same trait (or
    /// both inherent). Two blocks may define a method of one name only when
    /// one is a trait impl, and then both are distinct methods (#503 review).
    pub fn is_same_method(&self, other: &MethodModel) -> bool {
        self.name() == other.name() && self.trait_path() == other.trait_path()
    }

    /// Whether the method's block sits in the same module as its struct, which
    /// is where `struct_module_path` points. A method with no recorded site is
    /// its struct's neighbour (#342).
    pub fn is_local_to(&self, struct_module_path: &[String]) -> bool {
        self.site
            .as_ref()
            .is_none_or(|site| site.module_path == struct_module_path)
    }
}

#[derive(Debug, Clone)]
pub struct StructModel {
    pub item: ItemStruct,
    pub attribute: Attribute,
    pub derives: Vec<String>,
    pub impls: Vec<ItemImpl>,
    pub methods: Vec<MethodModel>,
    pub line: usize,
}

impl StructModel {
    pub fn name(&self) -> String {
        self.item.ident.to_string()
    }

    pub fn is_generic(&self) -> bool {
        crate::types::has_type_params(&self.item.generics)
    }

    /// The struct's own type parameter names (`T` in `S<'a, T, const N: usize>`).
    pub fn type_param_names(&self) -> Vec<String> {
        self.item
            .generics
            .params
            .iter()
            .filter_map(|p| match p {
                syn::GenericParam::Type(tp) => Some(tp.ident.to_string()),
                _ => None,
            })
            .collect()
    }

    /// The `#[cfg]` / `#[cfg_attr]` attributes of the named field `name`: a
    /// generated accessor exists only where its field does (#462).
    pub fn field_cfg_attrs(&self, name: &syn::Ident) -> Vec<syn::Attribute> {
        match &self.item.fields {
            syn::Fields::Named(named) => named
                .named
                .iter()
                .find(|f| f.ident.as_ref() == Some(name))
                .map(|f| crate::cfg::cfg_attrs(&f.attrs))
                .unwrap_or_default(),
            _ => Vec::new(),
        }
    }

    /// Named fields `(ident, type)`; tuple and unit structs yield nothing.
    pub fn named_fields(&self) -> Vec<(syn::Ident, Type)> {
        match &self.item.fields {
            syn::Fields::Named(named) => named
                .named
                .iter()
                .filter_map(|f| f.ident.clone().map(|id| (id, f.ty.clone())))
                .collect(),
            _ => Vec::new(),
        }
    }

    /// The model of a struct item selected under `mode`: a `#[julia]` struct,
    /// or in inline mode also a `#[derive(JuliaStruct)]` one. `None` when the
    /// struct carries neither.
    pub fn of(s: &ItemStruct, mode: Mode) -> Option<StructModel> {
        let attribute = rustcall_attribute(&s.attrs);
        let selected = matches!(
            (mode, attribute),
            (_, Attribute::Julia) | (Mode::Inline, Attribute::DeriveJuliaStruct)
        );
        if !selected {
            return None;
        }
        Some(StructModel {
            item: s.clone(),
            attribute,
            derives: derive_list(&s.attrs)
                .into_iter()
                .filter(|d| d != "JuliaStruct")
                .collect(),
            impls: Vec::new(),
            methods: Vec::new(),
            line: s.span().start().line,
        })
    }

    /// Record an inherent impl block of this struct and the methods of it that
    /// get wrapped under `mode`. The caller has decided that the block is this
    /// struct's (by name at one level, or by resolved path across modules,
    /// #315); a method already seen under the same name is not added twice.
    /// `enclosing_cfg` is the `#[cfg]` of every module enclosing the block.
    ///
    /// `block_module` is the module the block sits in (both callers,
    /// [`ModelTree::collect`] and the crate scan, match across the module
    /// tree and pass it); `None` records the block as the struct's
    /// neighbour. It is recorded on every method as [`MethodModel::site`],
    /// which is what decides where the inline expander emits the wrapper
    /// (#342).
    pub fn attach_impl(
        &mut self,
        imp: &ItemImpl,
        mode: Mode,
        enclosing_cfg: &[syn::Attribute],
        block_module: Option<&[String]>,
    ) {
        self.attach_impl_resolving(imp, mode, enclosing_cfg, block_module, |_| false);
    }

    /// [`StructModel::attach_impl`] for a caller that resolves names: a
    /// method whose declared return type `names_self` says is this struct
    /// is recorded as returning it
    /// ([`MethodModel::returns_own_type_resolved`], #518).
    pub fn attach_impl_resolving(
        &mut self,
        imp: &ItemImpl,
        mode: Mode,
        enclosing_cfg: &[syn::Attribute],
        block_module: Option<&[String]>,
        names_self: impl Fn(&Type) -> bool,
    ) {
        self.impls.push(imp.clone());
        for mut m in wrapped_methods(imp, mode, enclosing_cfg) {
            m.returns_own_type_resolved =
                matches!(&m.func.sig.output, syn::ReturnType::Type(_, ty) if names_self(ty));
            m.site = block_module.map(|path| ImplSite {
                module_path: path.to_vec(),
                self_ty: (*imp.self_ty).clone(),
            });
            if !self.methods.iter().any(|seen| seen.is_same_method(&m)) {
                self.methods.push(m);
            }
        }
    }
}

/// Whether the block carries `#[julia]` itself, which in crate mode is what
/// makes its `#[julia]` methods get wrapped.
pub fn impl_has_julia(imp: &ItemImpl) -> bool {
    imp.attrs.iter().any(is_julia_attr)
}

/// The methods of an inherent impl block that get wrapped under `mode`, in
/// source order. Each carries the block's `#[cfg]` on top of `enclosing_cfg`,
/// the predicates of the modules around the block.
pub fn wrapped_methods(
    imp: &ItemImpl,
    mode: Mode,
    enclosing_cfg: &[syn::Attribute],
) -> Vec<MethodModel> {
    let has_julia = impl_has_julia(imp);
    let block_cfg = crate::cfg::effective_cfg_attrs(enclosing_cfg, &imp.attrs);
    // What the manifest records as the method's origin: the impl block's
    // attribute, which an inline-mode impl does not have.
    let impl_attribute = if has_julia {
        Attribute::Julia
    } else {
        Attribute::None
    };
    imp.items
        .iter()
        .filter_map(|ii| match ii {
            ImplItem::Fn(func) => Some(func),
            _ => None,
        })
        .filter(|func| match mode {
            // Historical inline rule: every `pub fn` of an inherent impl.
            Mode::Inline => matches!(func.vis, Visibility::Public(_)),
            // Proc-macro rule: `#[julia]` methods inside a `#[julia] impl`.
            Mode::Crate => has_julia && func.attrs.iter().any(is_julia_attr),
        })
        .map(|func| {
            let mut m = MethodModel::from_fn(func, impl_attribute);
            m.enclosing_cfg = block_cfg.clone();
            m.host = Some(ImplHost::of(imp));
            m
        })
        .collect()
}

/// The struct models of a whole item tree, every inherent impl block attached
/// to its struct wherever the block sits (#315).
///
/// This is the inline expander's view of a `rust"""` block: every inline module
/// counts, so a struct is identified by its module path and its name, and an
/// `impl super::Gauge` in `mod ops` or an `impl Gauge` next to a
/// `use crate::Gauge;` reaches the struct at the root exactly as a block next
/// to it does. Headers are resolved by the resolver the crate scans share
/// (`crate::paths::locate`). A block that names no selected struct is left
/// alone — an inherent impl of an ordinary struct is ordinary code.
#[derive(Debug, Default)]
pub struct ModelTree {
    entries: Vec<LocatedModel>,
    /// Every `use` of the block, for resolving borrowed arguments (#565).
    imports: Vec<crate::paths::ScannedImport>,
}

#[derive(Debug)]
struct LocatedModel {
    module_path: Vec<String>,
    name: String,
    model: StructModel,
}

/// An inherent impl block seen by [`ModelTree::collect`], with the `#[cfg]` of
/// the modules around it.
#[derive(Debug)]
struct ScannedBlock {
    item: ItemImpl,
    header: crate::paths::ImplHeader,
    enclosing_cfg: Vec<syn::Attribute>,
}

/// A selected struct's location alone, as [`crate::paths::names_struct`]
/// sees it.
#[derive(Debug)]
struct Place {
    module_path: Vec<String>,
    name: String,
}

impl crate::paths::Located for Place {
    fn name(&self) -> &str {
        &self.name
    }

    fn module_path(&self) -> &[String] {
        &self.module_path
    }
}

impl crate::paths::Located for LocatedModel {
    fn name(&self) -> &str {
        &self.name
    }

    fn module_path(&self) -> &[String] {
        &self.module_path
    }
}

impl ModelTree {
    pub fn collect(items: &[Item], mode: Mode) -> ModelTree {
        let mut tree = ModelTree::default();
        let mut impls: Vec<ScannedBlock> = Vec::new();
        let mut imports = Vec::new();
        let mut path = Vec::new();
        tree.walk(items, mode, &mut path, &[], &mut impls, &mut imports);
        // Where every selected struct is, for resolving a method's return
        // type while its struct's model is being extended.
        let places: Vec<Place> = tree
            .entries
            .iter()
            .map(|e| Place {
                module_path: e.module_path.clone(),
                name: e.name.clone(),
            })
            .collect();
        for block in &impls {
            if let Ok(index) = crate::paths::locate(&tree.entries, &block.header, &imports) {
                // A return type names the block's struct when it resolves
                // to it by the path machinery the header was resolved by
                // (#518) — `-> super::Gauge` in `impl Meter` — and never by
                // sharing the header's last segment.
                let names_self = |ty: &Type| {
                    crate::paths::names_struct(
                        &places,
                        index,
                        &block.item.self_ty,
                        ty,
                        &block.header.module_path,
                        &imports,
                        // RustCall compiles a `rust"""` block with `rustc`
                        // and no `--edition`: edition 2015, where a leading
                        // `::` is the crate root.
                        true,
                    )
                };
                tree.entries[index].model.attach_impl_resolving(
                    &block.item,
                    mode,
                    &block.enclosing_cfg,
                    Some(&block.header.module_path),
                    names_self,
                );
            }
        }
        tree.imports = imports;
        tree
    }

    /// The FFI name of the concrete struct of this block that the pointee
    /// `ty` of a borrowed argument, written in `module_path`, names with
    /// certainty ([`crate::paths::locate_borrowed_type`], #565). A generic
    /// struct is never a handle: Julia binds its instantiations instead.
    pub fn borrowed_handle(&self, ty: &Type, module_path: &[String]) -> Option<String> {
        // Edition 2015, like every `rust"""` block (see `collect`).
        let index = crate::paths::locate_borrowed_type(
            &self.entries,
            ty,
            module_path,
            &self.imports,
            true,
        )?;
        let entry = &self.entries[index];
        (!entry.model.is_generic())
            .then(|| crate::codegen::symbol_stem(&entry.module_path, &entry.name))
    }

    fn walk(
        &mut self,
        items: &[Item],
        mode: Mode,
        path: &mut Vec<String>,
        enclosing_cfg: &[syn::Attribute],
        impls: &mut Vec<ScannedBlock>,
        imports: &mut Vec<crate::paths::ScannedImport>,
    ) {
        for item in items {
            match item {
                Item::Struct(s) => {
                    if let Some(model) = StructModel::of(s, mode) {
                        self.entries.push(LocatedModel {
                            module_path: path.clone(),
                            name: model.name(),
                            model,
                        });
                    }
                }
                Item::Impl(imp) => {
                    if let Some(header) = crate::paths::ImplHeader::of(imp, path) {
                        impls.push(ScannedBlock {
                            item: imp.clone(),
                            header,
                            enclosing_cfg: enclosing_cfg.to_vec(),
                        });
                    }
                }
                Item::Use(u) => imports.extend(crate::paths::imports_of_use(u, path)),
                Item::Mod(m) => {
                    if let Some((_, inner)) = &m.content {
                        path.push(m.ident.to_string());
                        let cfg = crate::cfg::effective_cfg_attrs(enclosing_cfg, &m.attrs);
                        self.walk(inner, mode, path, &cfg, impls, imports);
                        path.pop();
                    }
                }
                _ => {}
            }
        }
    }

    /// The model of `name` declared directly in `module_path`, if selected.
    pub fn find(&self, module_path: &[String], name: &str) -> Option<&StructModel> {
        self.entries
            .iter()
            .find(|e| e.module_path == module_path && e.name == name)
            .map(|e| &e.model)
    }

    /// Every wrapped method whose `#[julia] impl` block sits in `module_path`
    /// while its struct lives somewhere else (#342).
    ///
    /// The inline expander emits these wrappers there, at the block, because a
    /// method signature is written in the block's scope: a module-local `type
    /// Count = i32;` is not in scope next to the struct. The exported symbol is
    /// crate-global and keeps following the struct, so where the wrapper is
    /// emitted changes nothing a caller can see.
    ///
    /// Generic structs are excluded: they export no wrapper at all, their
    /// generic wrappers are instantiated by `specialize` next to the struct.
    pub fn foreign_methods(&self, module_path: &[String]) -> Vec<ForeignMethod<'_>> {
        let mut out = Vec::new();
        for entry in &self.entries {
            if entry.model.is_generic() {
                continue;
            }
            for method in &entry.model.methods {
                let Some(site) = &method.site else { continue };
                if site.module_path != module_path || site.module_path == entry.module_path {
                    continue;
                }
                out.push(ForeignMethod {
                    struct_name: &entry.model.item.ident,
                    struct_module_path: &entry.module_path,
                    self_ty: &site.self_ty,
                    method,
                });
            }
        }
        out
    }
}

/// A method whose `#[julia] impl` block sits in another module than its struct
/// (#342), as reported by [`ModelTree::foreign_methods`].
#[derive(Debug)]
pub struct ForeignMethod<'a> {
    /// The **struct's own** identifier, which every exported symbol of the
    /// method hangs off together with [`ForeignMethod::struct_module_path`].
    /// Not the header's last segment: `use super::Gauge as Meter; impl Meter`
    /// still exports `rustcall_Gauge_<method>` (#342 review).
    pub struct_name: &'a syn::Ident,
    /// The module path of the **struct**, which every exported symbol of the
    /// method hangs off.
    pub struct_module_path: &'a [String],
    /// The impl header's own path — how the wrapper spells the struct in the
    /// module it is emitted into, which may be an alias.
    pub self_ty: &'a Type,
    pub method: &'a MethodModel,
}