rustcall_julia_core 0.4.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
//! Inline expansion for `rust"""..."""` blocks.
//!
//! Applies the same transformations the proc-macro applies inside a crate, but
//! ahead of `rustc`, so inline blocks need neither Cargo nor a proc-macro
//! dependency:
//!
//! * `#[julia] fn`            -> `#[no_mangle] pub extern "C" fn` (+ `CResult`/`COption` wrappers)
//! * `#[julia] fn f<T>`       -> plain `pub fn` reported for runtime monomorphization
//! * `#[julia] struct` / `#[derive(JuliaStruct)] struct` -> `pub struct` + `_free`, accessors, method wrappers
//! * generic `#[julia] struct`-> wrappers reported for runtime monomorphization
//! * everything else          -> unchanged
//!
//! The manifest is built from the very same items, so it always matches the
//! emitted code.

use syn::{Item, Visibility};

use crate::attrs::{rustcall_attribute, strip_julia_struct_derive, strip_rustcall_attrs};
use crate::cfg::{predicate_string, CfgSet};
use crate::codegen::{
    inline_generic_method_refusals, inline_generic_wrappers, inline_struct_wrappers,
    panic_hook_items, transform_function, PanicHook,
};
use crate::extract::{fn_args, function_entry};
use crate::manifest::{Attribute, Field, Manifest, Method, Mode, Struct};
use crate::model::{ModelTree, StructModel};
use crate::types::{
    generic_field_has_accessors, generics_to_type_params, has_type_params, return_type_to_string,
    type_to_string,
};

pub struct Expanded {
    /// Transformed Rust source, ready for `rustc`.
    pub source: String,
    pub manifest: Manifest,
}

fn items_of(tokens: proc_macro2::TokenStream) -> Result<Vec<Item>, syn::Error> {
    let file: syn::File = syn::parse2(tokens)?;
    Ok(file.items)
}

fn unparse_items(items: Vec<Item>) -> String {
    unparse_file(Vec::new(), items)
}

fn unparse_file(attrs: Vec<syn::Attribute>, items: Vec<Item>) -> String {
    let file = syn::File {
        shebang: None,
        attrs,
        items,
    };
    prettyplease::unparse(&file)
}

pub fn expand(source: &str) -> Result<Expanded, syn::Error> {
    expand_with_cfg(source, None)
}

/// Like [`expand`], but items disabled under `cfg` are dropped before
/// expansion, so the manifest only reports what rustc will compile. Without a
/// configuration every item is kept and its predicate is recorded.
pub fn expand_with_cfg(source: &str, cfg: Option<&CfgSet>) -> Result<Expanded, syn::Error> {
    let mut file = syn::parse_file(source)?;
    if let Some(set) = cfg {
        // Crate-level `#![cfg(...)]` first: a disabled crate compiles to
        // nothing, so none of its items may be reported.
        crate::cfg::prune_file_or_error(set, &mut file)?;
    }
    let mut manifest = Manifest::new(Mode::Inline);
    // Structs and their impl blocks are matched across the whole block first
    // (#315), so an `impl super::Gauge` inside `mod ops` wraps `Gauge`'s
    // methods next to the struct.
    let tree = ModelTree::collect(&file.items, Mode::Inline);
    let mut out = expand_items(&file.items, &mut manifest, &[], &[], &tree)?;

    // Two generated `#[no_mangle]` items of one block wanting the same symbol
    // (#342 review). The scheme keeps items in different modules apart by
    // construction, so what is left is a coincidence it cannot exclude — a
    // struct `Foo_bar` next to a `Foo::bar` that hands back an owned string,
    // both wanting `Foo_bar_free_rust_string`. rustc would report it inside
    // generated code; say which two items collide instead.
    for (claim, first, second) in manifest.duplicate_claims() {
        let symbol = &claim.name;
        let msg = if claim.exported {
            format!(
                "RustCall would export the symbol `{symbol}` twice in this block: for {first} \
                 and for {second}. The scheme derives every symbol from the item's name and \
                 module path (`rustcall_<fn>`, `rustcall_<Struct>_<method>`, `<Struct>_free`, \
                 `<Struct>_get_<field>`, `<owner>_free_rust_string`, ... — #300), so two items \
                 whose names differ only where the scheme joins them meet here. Rename one of \
                 them."
            )
        } else {
            format!(
                "RustCall would define the item `{symbol}` twice in this block: for {first} \
                 and for {second}. It is not exported and not one you wrote — it is {}. Two of \
                 them in one module are a duplicate definition rustc would report inside \
                 generated code. Rename one of the items (#338).",
                crate::claims::internal_origin(&claim)
            )
        };
        out.insert(0, syn::parse_quote! { compile_error!(#msg); });
    }

    // The quiet panic hook (#304). This is the half the proc-macro cannot do:
    // the expander sees the whole block, so the depth counter and the hook that
    // reads it are placed once, at the root, where every wrapper in the block —
    // submodules included — reaches them as `crate::__RustCallBoundary`.
    out.extend(items_of(panic_hook_items())?);

    Ok(Expanded {
        // Crate-level inner attributes (`#![allow(...)]`, `//!` docs) are kept;
        // ordinary comments are not part of the AST and are dropped.
        source: unparse_file(file.attrs.clone(), out),
        manifest,
    })
}

/// Expand one level of items. Inline modules (`mod m { ... }`) are expanded
/// recursively so `#[julia]` items inside them are transformed and reported,
/// and every exported symbol is qualified by the module path (#300): the
/// expander sees the whole block, so — unlike the proc-macro — it needs no
/// `#[julia]` marker on the module (one is accepted and stripped).
///
/// `enclosing_cfg` is the `#[cfg]` of every enclosing module, folded into each
/// entry's `cfg` / `cfg_features` (#300 review).
fn expand_items(
    items: &[Item],
    manifest: &mut Manifest,
    module_path: &[String],
    enclosing_cfg: &[syn::Attribute],
    tree: &ModelTree,
) -> Result<Vec<Item>, syn::Error> {
    let mut out: Vec<Item> = Vec::new();
    let push_fn = |manifest: &mut Manifest, entry: crate::manifest::Function| {
        manifest.functions.push(entry);
    };

    for item in items {
        // `#[julia]` on a kind it does not support: refused before anything
        // is built, as the crate scan refuses it (#503 review). There is no
        // manifest entry to carry it, so the expansion fails with the
        // refusal's message at the item.
        if let Some(refusal) = crate::refusal::julia_item_refusal(item) {
            return Err(syn::Error::new(
                refusal.span,
                format!("{} ({})", refusal.message, refusal.detail),
            ));
        }
        match item {
            Item::Fn(f) => {
                let attribute = rustcall_attribute(&f.attrs);
                match attribute {
                    Attribute::Julia => {
                        let mut f = f.clone();
                        strip_rustcall_attrs(&mut f.attrs);
                        // The entry carries the codegen's refusal, if any, as
                        // its `skip_reason` (#503): the same decision
                        // `transform_function` emits the `compile_error!` for.
                        push_fn(
                            manifest,
                            function_entry(&f, attribute, Mode::Inline, module_path, enclosing_cfg),
                        );
                        let refusal =
                            crate::refusal::function_refusal(&f, module_path, Mode::Inline);
                        if refusal.is_none() && !has_type_params(&f.sig.generics) {
                            out.extend(items_of(transform_function(
                                f,
                                module_path,
                                PanicHook::FileOwned,
                            ))?);
                        } else {
                            // A generic function is emitted unwrapped and
                            // monomorphized on demand (`specialize`); a refused
                            // one is kept as written, next to its refusal —
                            // a generic `unsafe fn` among them (#491): its
                            // specialized wrapper would call it from a safe
                            // body, and Julia registers nothing for it.
                            if let Some(refusal) = refusal {
                                out.extend(items_of(
                                    refusal.compile_error(&crate::cfg::cfg_attrs(&f.attrs)),
                                )?);
                            }
                            f.vis = Visibility::Public(Default::default());
                            out.push(Item::Fn(f));
                        }
                    }
                    _ => {
                        push_fn(
                            manifest,
                            function_entry(
                                f,
                                Attribute::None,
                                Mode::Inline,
                                module_path,
                                enclosing_cfg,
                            ),
                        );
                        out.push(item.clone());
                    }
                }
            }
            Item::Struct(s) => {
                let Some(model) = tree.find(module_path, &s.ident.to_string()) else {
                    out.push(item.clone());
                    continue;
                };
                let mut s = s.clone();
                strip_rustcall_attrs(&mut s.attrs);
                strip_julia_struct_derive(&mut s.attrs);
                s.vis = Visibility::Public(Default::default());
                out.push(Item::Struct(s.clone()));

                if model.is_generic() {
                    let entry = generic_struct_entry(model, &s, module_path, enclosing_cfg);
                    // Emit the generic wrappers (not exported) next to the struct so
                    // `specialize` can instantiate them in place, with every
                    // module-scoped name in reach.
                    for w in &entry.generic_wrappers {
                        let f: syn::File = syn::parse_str(&w.source)?;
                        out.extend(f.items);
                    }
                    // A method generic in its own right is refused (#477).
                    out.extend(items_of(inline_generic_method_refusals(model))?);
                    manifest.structs.push(entry);
                } else {
                    let (tokens, meta) = inline_struct_wrappers(model, module_path);
                    out.extend(items_of(tokens)?);
                    let entry = concrete_struct_entry(model, &meta, module_path, enclosing_cfg);
                    manifest.structs.push(entry);
                }
            }
            Item::Impl(imp) => {
                let mut imp = imp.clone();
                strip_rustcall_attrs(&mut imp.attrs);
                for ii in &mut imp.items {
                    if let syn::ImplItem::Fn(func) = ii {
                        strip_rustcall_attrs(&mut func.attrs);
                    }
                }
                out.push(Item::Impl(imp));
            }
            Item::Mod(m) => match &m.content {
                Some((brace, inner)) => {
                    let mut m = m.clone();
                    // A `#[julia]` marker on the module is the crate-mode
                    // spelling of what the expander sees for itself (#300).
                    strip_rustcall_attrs(&mut m.attrs);
                    let mut path = module_path.to_vec();
                    path.push(m.ident.to_string());
                    let cfg = crate::cfg::effective_cfg_attrs(enclosing_cfg, &m.attrs);
                    m.content = Some((*brace, expand_items(inner, manifest, &path, &cfg, tree)?));
                    out.push(Item::Mod(m));
                }
                None => out.push(item.clone()),
            },
            other => out.push(other.clone()),
        }
    }

    // The wrappers of `#[julia] impl` blocks that sit in *this* module while
    // their struct lives elsewhere (#342). They are emitted here, where the
    // types their signatures name are in scope, spelling the struct the way
    // the header does; the exported symbol still follows the struct, so this
    // changes nothing a caller can see.
    for foreign in tree.foreign_methods(module_path) {
        out.extend(items_of(crate::codegen::inline_foreign_method_wrapper(
            foreign.self_ty,
            foreign.struct_name,
            foreign.struct_module_path,
            foreign.method,
        ))?);
    }

    for name in symbol_collisions(items, &out) {
        let msg = format!(
            "RustCall generates an item named `{name}` in this module, but the block already \
             defines one. `#[julia]` keeps the annotated item and emits its `extern \"C\"` entry \
             point next to it (`rustcall_<fn>`, `rustcall_<Struct>_<method>`, `<Struct>_free`, \
             `<Struct>_get_<field>`, `CResult_<fn>`, `<fn>_RustCallOwnedString`, ... — with the \
             module path folded into `<fn>` / `<Struct>` inside a module, #300), so rename \
             the conflicting item (#279)."
        );
        out.insert(0, syn::parse_quote! { compile_error!(#msg); });
    }

    Ok(out)
}

/// Rust name-resolution namespace of an item: `struct Foo` and `fn Foo` may
/// coexist, `fn Foo` and `const Foo` may not.
fn item_key(item: &Item) -> Option<(u8, String)> {
    const TYPE_NS: u8 = 0;
    const VALUE_NS: u8 = 1;
    match item {
        Item::Fn(f) => Some((VALUE_NS, f.sig.ident.to_string())),
        Item::Const(c) => Some((VALUE_NS, c.ident.to_string())),
        Item::Static(s) => Some((VALUE_NS, s.ident.to_string())),
        Item::Struct(s) => Some((TYPE_NS, s.ident.to_string())),
        Item::Enum(e) => Some((TYPE_NS, e.ident.to_string())),
        Item::Union(u) => Some((TYPE_NS, u.ident.to_string())),
        Item::Trait(t) => Some((TYPE_NS, t.ident.to_string())),
        Item::Type(t) => Some((TYPE_NS, t.ident.to_string())),
        Item::Mod(m) => Some((TYPE_NS, m.ident.to_string())),
        _ => None,
    }
}

fn key_counts(items: &[Item]) -> std::collections::HashMap<(u8, String), usize> {
    let mut counts = std::collections::HashMap::new();
    for item in items {
        if let Some(key) = item_key(item) {
            *counts.entry(key).or_insert(0) += 1;
        }
    }
    counts
}

/// Names that the wrappers generated for one module level would take away from
/// an item the user wrote there.
///
/// `#[julia]` is additive (#279), so the exported symbols are chosen not to
/// collide with the annotated items themselves (`rustcall_<fn>`); a *different*
/// user item may still happen to carry a generated name. Inline expansion sees
/// the whole module and can say so precisely, which is worth a clear error
/// rather than a duplicate-definition diagnostic pointing at generated code.
/// The proc-macro sees one item at a time and cannot make this check.
fn symbol_collisions(original: &[Item], expanded: &[Item]) -> Vec<String> {
    let before = key_counts(original);
    let after = key_counts(expanded);
    let mut clashes: Vec<String> = after
        .iter()
        .filter(|(key, count)| **count > before.get(*key).copied().unwrap_or(0))
        .filter(|(key, _)| before.contains_key(*key))
        .map(|((_, name), _)| name.clone())
        .collect();
    clashes.sort();
    clashes
}

/// `symbols` doubles as "this struct's methods are wrapped here": a concrete
/// struct gets `extern "C"` wrappers with exported symbols, a generic one gets
/// generic wrappers registered for monomorphization instead. Only the former
/// lower `Result` / `Option` (#268).
///
/// `module_path` is the struct's own module: a method whose block sits there
/// is wrapped next to the struct and shares its string buffers, one from a
/// block elsewhere carries buffers of its own (#342). The manifest states
/// which (`Method.string_owner`) instead of leaving Julia to derive it from
/// the flavour.
fn methods_of(
    model: &StructModel,
    symbols: bool,
    stem: &str,
    module_path: &[String],
) -> Vec<Method> {
    let struct_name = &model.item.ident;
    let bare: syn::Type = syn::parse_quote!(#struct_name);
    model
        .methods
        .iter()
        // A method the codegen refuses — generic in its own right (#471 for a
        // concrete struct, #477 for a generic one, whose instantiation binds
        // only the struct's parameters), `unsafe` (#491), or one whose wrapper
        // cannot be written (#482, #484) — is kept here with the refusal as
        // its `skip_reason` (#503), a concrete struct's and a generic
        // struct's alike, so the Julia generators name it. It gets no wrapper
        // (nor, on a generic struct, a generic wrapper), and Julia binds
        // nothing for it. The site is the one the wrapper would be emitted
        // at: beside the struct, or at a block in another module (#342).
        .map(|m| {
            let site = if !symbols {
                crate::refusal::MethodSite::InlineGeneric { struct_name }
            } else {
                crate::refusal::MethodSite::Inline {
                    self_ty: match &m.site {
                        Some(site) if !m.is_local_to(module_path) => &site.self_ty,
                        _ => &bare,
                    },
                    struct_name,
                }
            };
            let refusal = crate::refusal::method_refusal(site, m);
            let shape = crate::extract::method_return_shape(struct_name, m, symbols);
            Method {
                name: m.name(),
                trait_path: m.trait_path(),
                julia_name: String::new(),
                symbol: if symbols {
                    crate::codegen::method_symbol_of(stem, &m.method_stem())
                } else {
                    String::new()
                },
                string_owner: match (symbols, m.is_local_to(module_path)) {
                    (false, _) => String::new(),
                    (true, true) => stem.to_string(),
                    (true, false) => crate::codegen::method_string_owner(stem, &m.method_stem()),
                },
                is_static: m.is_static(),
                is_mutable: m.is_mutable(),
                is_constructor: m.is_constructor(struct_name),
                is_classmethod: false,
                vis: crate::attrs::visibility_string(&m.func.vis),
                skip_reason: refusal.map(|r| r.skip_reason()).unwrap_or_default(),
                python_name: String::new(),
                accessor: String::new(),
                attribute: m.attribute,
                return_kind: shape.kind,
                ok_type: shape.ok_type,
                err_type: shape.err_type,
                inner_type: shape.inner_type,
                ok_abi: shape.ok_abi,
                err_abi: shape.err_abi,
                inner_abi: shape.inner_abi,
                returns_boxed_struct: m.returns_boxed_struct(struct_name),
                args: fn_args(&m.func.sig),
                return_type: return_type_to_string(&m.func.sig.output),
                return_abi: crate::codegen::return_abi(&m.func.sig).to_string(),
                generic_wrapper: String::new(),
                generic_wrapper_name: String::new(),
                // The block's and its modules' predicates gate the method as
                // much as its own do (#300 review, #315).
                cfg: crate::cfg::predicate_string(&crate::cfg::effective_cfg_attrs(
                    &m.enclosing_cfg,
                    &m.func.attrs,
                )),
                py_return: None,
            }
        })
        .collect()
}

fn fields_of(model: &StructModel, accessors: &[(String, String, String)]) -> Vec<Field> {
    model
        .named_fields()
        .iter()
        .map(|(name, ty)| {
            let acc = accessors.iter().find(|(f, _, _)| *name == *f);
            Field {
                name: name.to_string(),
                rust_type: type_to_string(ty),
                abi: crate::codegen::field_abi(ty).to_string(),
                vec_element: String::new(),
                free_symbol: String::new(),
                ffi_compatible: acc.is_some(),
                getter: acc.map(|a| a.1.clone()).unwrap_or_default(),
                setter: acc.map(|a| a.2.clone()).unwrap_or_default(),
                python_name: String::new(),
                vis: String::new(),
                cfg: String::new(),
                pyo3_get: false,
                pyo3_set: false,
                precollision: None,
                py_shape: None,
            }
        })
        .collect()
}

fn concrete_struct_entry(
    model: &StructModel,
    meta: &crate::codegen::InlineStructMeta,
    module_path: &[String],
    enclosing_cfg: &[syn::Attribute],
) -> Struct {
    let stem = crate::codegen::symbol_stem(module_path, &model.name());
    let effective_cfg = crate::cfg::effective_cfg_attrs(enclosing_cfg, &model.item.attrs);
    Struct {
        callable_path: Vec::new(),
        cfg: predicate_string(&effective_cfg),
        cfg_features: crate::cfg::predicate_features(&effective_cfg),
        name: model.name(),
        attribute: model.attribute,
        vis: crate::attrs::visibility_string(&model.item.vis),
        skip_reason: String::new(),
        python_name: String::new(),
        python_path: Vec::new(),
        pyo3_extends: String::new(),
        pyo3_options: Vec::new(),
        python_owned_handle: false,
        type_params: Vec::new(),
        fields: fields_of(model, &meta.accessors),
        methods: methods_of(model, true, &stem, module_path),
        ffi_name: stem,
        derives: model.derives.clone(),
        has_clone: meta.has_clone,
        has_owned_string_helper: meta.has_owned_string_helper,
        has_borrowed_string_helper: meta.has_borrowed_string_helper,
        context_source: String::new(),
        generic_wrappers: Vec::new(),
        line: model.line,
        module_path: module_path.to_vec(),
    }
}

fn generic_struct_entry(
    model: &StructModel,
    stripped_struct: &syn::ItemStruct,
    module_path: &[String],
    enclosing_cfg: &[syn::Attribute],
) -> Struct {
    let effective_cfg = crate::cfg::effective_cfg_attrs(enclosing_cfg, &model.item.attrs);
    // Every wrapper name hangs off the struct's FFI name, module path folded
    // in (#300, #462), and the manifest states each one so a consumer never
    // re-derives it.
    let stem = crate::codegen::symbol_stem(module_path, &model.name());
    let wrappers = inline_generic_wrappers(model, module_path);
    let wrapper_names: Vec<&str> = wrappers.iter().map(|w| w.name.as_str()).collect();
    let type_params = model.type_param_names();
    let accessors: Vec<(String, String, String)> = model
        .named_fields()
        .iter()
        .filter(|(_, ty)| generic_field_has_accessors(ty, &type_params))
        .map(|(n, _)| {
            let getter = crate::codegen::field_getter_symbol(&stem, &n.to_string());
            let setter = crate::codegen::field_setter_symbol(&stem, &n.to_string());
            let has_setter = wrapper_names.contains(&setter.as_str());
            (
                n.to_string(),
                getter,
                if has_setter { setter } else { String::new() },
            )
        })
        .collect();

    let mut context_items: Vec<Item> = vec![Item::Struct(stripped_struct.clone())];
    for imp in &model.impls {
        let mut imp = imp.clone();
        strip_rustcall_attrs(&mut imp.attrs);
        for ii in &mut imp.items {
            if let syn::ImplItem::Fn(func) = ii {
                strip_rustcall_attrs(&mut func.attrs);
            }
        }
        context_items.push(Item::Impl(imp));
    }

    // A generic struct exports nothing itself: its wrappers are instantiated
    // by `specialize` under names Julia chooses.
    let mut methods = methods_of(model, false, &stem, module_path);
    for m in &mut methods {
        let wrapper_name = crate::codegen::generic_method_wrapper_name(&stem, &m.name);
        if let Some(w) = wrappers.iter().find(|w| w.name == wrapper_name) {
            m.generic_wrapper = w.source.clone();
            m.generic_wrapper_name = wrapper_name;
        }
    }

    Struct {
        callable_path: Vec::new(),
        cfg: predicate_string(&effective_cfg),
        cfg_features: crate::cfg::predicate_features(&effective_cfg),
        name: model.name(),
        ffi_name: stem,
        attribute: model.attribute,
        vis: crate::attrs::visibility_string(&model.item.vis),
        skip_reason: String::new(),
        python_name: String::new(),
        python_path: Vec::new(),
        pyo3_extends: String::new(),
        pyo3_options: Vec::new(),
        python_owned_handle: false,
        type_params: generics_to_type_params(&model.item.generics),
        fields: fields_of(model, &accessors),
        methods,
        derives: model.derives.clone(),
        has_clone: false,
        has_owned_string_helper: false,
        has_borrowed_string_helper: false,
        context_source: unparse_items(context_items),
        generic_wrappers: wrappers,
        line: model.line,
        module_path: module_path.to_vec(),
    }
}