rustcall_julia_core 0.3.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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
//! FFI manifest model.
//!
//! The manifest is the single source of truth that Julia consumes. It describes
//! every symbol the generated shared library exposes, plus the information
//! Julia needs for generic monomorphization. It is produced by the same `syn`
//! visitors that drive wrapper code generation, so it always reflects what was
//! actually generated.
//!
//! Serialized as TOML so that Julia can read it with the standard-library
//! `TOML` module without extra dependencies.

use serde::{Deserialize, Serialize};

/// The manifest compatibility identifier: the **`MAJOR.MINOR` of the RustCall
/// release** this crate ships in, so `"0.7"` for every v0.7.x. Julia derives
/// the same string from its `Project.toml` and refuses a manifest whose
/// `schema_version` differs (#372).
///
/// Through v0.3.x this was an integer bumped on every manifest edit (the
/// history below, last value 13). Tying it to the release instead means: a
/// **patch** release never changes the identifier, so cached artifacts and an
/// installed extractor stay valid across it; a **minor** release always does,
/// so every consumer rebuilds once and a manifest can change shape freely
/// inside that release; and the extractor and the package cannot disagree,
/// because `test/test_schema_version.jl` reads this constant back through
/// the extractor's `schema-version` output and compares it with the
/// `MAJOR.MINOR` of `Project.toml`. It is a **literal** here, not derived
/// from this crate's version: since #451 the published crates carry a
/// semver of their own (`0.1.0` at first), so a package minor release edits
/// this line by hand (the unit test below only pins its shape). A pre-v0.4
/// consumer meets a string where it expects `13` and refuses it, which is
/// the intended answer.
///
/// History of the integer scheme:
/// * 1: initial manifest (#264).
/// * 2: string ABI (#242): `Arg.abi`, `Method.return_abi` and the
///   `has_owned_string_helper` / `has_borrowed_string_helper` flags decide
///   how a consumer must call the exported symbols (`(ptr, len)` pairs and
///   `<name>_RustCallOwnedString` buffers), so a version-1 consumer must not
///   load a version-2 manifest, nor the reverse.
/// * 3: additive `#[julia]` (#279): the annotated item keeps its name and the
///   exported entry point is a wrapper emitted next to it, so `Function.symbol`
///   and `Method.symbol` now differ from `name` for *every* wrapped item
///   (`rustcall_<fn>` / `rustcall_<Struct>_<method>`), not only for generic
///   instantiations. A version-2 consumer would `dlsym` the Rust name and find
///   nothing.
/// * 4: one vocabulary for the type contract (#276): `Function.return_abi`
///   replaces the pair of `has_*_string_helper` booleans as the *normative*
///   description of a free function's return (the booleans stay, derived, for
///   one release), `Field.abi` says how a field getter returns its value so
///   Julia never re-derives it from the type spelling, and
///   `Method.returns_boxed_struct` states explicitly what Julia used to infer
///   by comparing `return_type` against `"Self"`. A version-3 consumer would
///   read a `String` field getter as an opaque value.
/// * 5: PyO3 crate scan (#275 Phase 1): items carrying only PyO3 attributes are
///   reported alongside `#[julia]` ones with a PyO3 [`Attribute`] origin,
///   every function / struct / method carries [`Function::vis`] and
///   [`Function::skip_reason`], and a `PyResult<T>` return is reported as
///   [`ReturnKind::PyResult`]. `Function::cfg_features` names the crate features
///   an item's `#[cfg]` predicate depends on, so a consumer can reconcile a
///   leniently evaluated scan with a feature set without reading Rust `cfg`
///   syntax. A version-4 consumer would treat a `#[pyfunction]` as an exported
///   `#[julia]` function and `dlsym` a symbol that no wrapper crate has emitted
///   yet.
/// * 6: `Result` / `Option` on struct methods (#268). A `#[julia]` method
///   returning `Result<T, E>` / `Option<T>` is now lowered exactly like a free
///   function — the wrapper returns `CResult_<Struct>_<method>` /
///   `COption_<Struct>_<method>` instead of the type as written — so
///   [`Method::return_kind`] reports [`ReturnKind::Result`] /
///   [`ReturnKind::Option`] where it always said [`ReturnKind::Plain`], with
///   the payload types in [`Method::ok_type`] / [`Method::err_type`] /
///   [`Method::inner_type`]. That is an **ABI change** for those methods, not
///   just a richer description: a version-5 consumer would read a two-payload
///   aggregate as the scalar it used to be. The same version adds
///   [`Function::ok_abi`] / [`Function::err_abi`] / [`Function::inner_abi`] and
///   their `Method` counterparts, which say whether a payload travels as an
///   owned `<owner>_RustCallOwnedString` buffer — the composition of the
///   `Result` and string lowerings that makes `Result<String, String>` work.
///   The same version 6 bump also covers the PyO3 wrapper crate (#275 Phase
///   2), landing together since neither shipped separately: the manifest a
///   wrapper build emits
///   describes generated entry points rather than a scan, so a `py_*` entry can
///   now have `exported = true` and a filled-in `return_abi`, a `PyResult`
///   entry's `err_type` is the `i32` code the wrapper reports
///   (`crate::wrap::PYERR_CODE`) rather than being empty, and the
///   [`skip_reason`] vocabulary gains the four reasons the *generator* can
///   refuse an item for. A version-5 consumer would read a wrapper manifest as
///   a scan and never call anything. Within version 6, additively:
///   [`Method::cfg`] and [`Field::cfg`] carry a class member's own undecided
///   `#[cfg]` predicate (serialized only when non-empty), so a wrapper
///   generated from a lenient scan refuses the member the way it refuses an
///   item; no consumer reads the column, only the generator (#307 review).
///   Also additive within version 6: [`Method::attribute`], the attribute of
///   the impl block a method came from (serialized only when there is one),
///   so the dual-binding attribute deprecated by #275 Phase 3 was reported
///   even on a `#[julia] struct`.
/// * **6 → 7**: two changes, landing in one breaking release (v0.3.0).
///   (a) The dual-binding proc-macro is removed (#312), and with it its value
///   of the [`Attribute`] vocabulary. A version-6 consumer could still meet
///   that origin — and bind the item under its as-written, non-lowered
///   signature — so the two must not read each other's manifests.
///   (b) Module-qualified symbols (#300). Every exported symbol is derived
///   from the item's **FFI name** — [`Function::ffi_name`] /
///   [`Struct::ffi_name`], the item's name with its module path folded in
///   (`crate::codegen::symbol_stem`: `a::run` -> `a__run`) — so two `run`s or
///   two `struct C` in different modules of one crate no longer want the same
///   `rustcall_run` / `C_free`. `Function.symbol` / `Method.symbol` and the
///   field accessors are qualified accordingly, and crate mode now records
///   [`Function::module_path`] / [`Struct::module_path`] for `#[julia]` items
///   (the chain of `#[julia]`-marked inline modules) instead of an empty list.
///   A version-6 consumer would derive `<Struct>_free` and
///   `<owner>_free_rust_string` from the bare name and release a buffer through
///   a symbol that no longer exists.
///
/// * **8** adds [`Method::string_owner`] (#342), the stem a method's string
///   buffers hang off, and it is a *breaking* addition rather than an additive
///   one. Since #342 an inline manifest can hold both buffer shapes at once —
///   a method sharing its struct's buffers, and a cross-module method carrying
///   its own — so a consumer that does not read the column falls back to
///   deriving `<Struct>_free_rust_string` by flavour. For a cross-module
///   method returning an owned `String`, the expanded library exports only
///   `<Struct>_<method>_free_rust_string`, and where the struct has no local
///   string helper at all that derived symbol does not exist: the buffer is
///   never released and leaks, silently. `src/manifest.jl` validates exact
///   equality, so bumping the version is what makes such a consumer refuse the
///   manifest instead of using the wrong owner (#342 review).
/// * **9** adds [`Function::callable_path`] and [`Struct::callable_path`]
///   (#303): wrappers must call the externally reachable re-export instead
///   of a canonical definition inside a private module.
/// * **10** adds the owned-vector field ABI. [`Field::vec_element`] states the
///   element spelling and [`Field::free_symbol`] names the allocator-matched
///   release export; an older consumer would otherwise read the returned
///   `(ptr, len, cap)` aggregate as a Rust `Vec<T>` value.
/// * **11** widens the `PyResult` ABI: `String` / `&str` success values use
///   [`Function::ok_abi`] / [`Method::ok_abi`] to declare an owned string
///   payload, and a class-valued `PyResult<Self>` stores an owned pointer in
///   the success slot. A schema-10 consumer ignores those shapes and would
///   decode the aggregate with the wrong field type.
/// * **12** records PyO3 class object shape (`extends`, `subclass`, `dict`,
///   `weakref`) and each argument's Python parameter kind/default expression,
///   so wrapper generation can select Python-owned dispatch without reparsing
///   Rust attributes. Default expressions remain diagnostic manifest data;
///   generated wrappers ask PyO3's in-crate dispatcher to evaluate them in
///   their original lexical scope.
/// * **13** adds [`Struct::python_owned_handle`], the wrapper generator's
///   authoritative handle decision. Consumers must not re-infer it after
///   skipped methods have been filtered from the binding surface.
/// * **0.4.x** (additive, #296): [`Arg::abi`] gains `"callback"`, with
///   [`Arg::callback_args`] / [`Arg::callback_return`] carrying the function
///   pointer's signature. A consumer that does not know the column sees an
///   argument it cannot describe and fails closed, as before.
/// * **0.7** (additive, #491): the [`skip_reason`] vocabulary gains
///   [`skip_reason::UNSAFE_FN`], set on a `#[julia]` function or method that
///   is an `unsafe fn`. Codegen refused such an item before the value
///   existed and still does; a consumer that ignores the reason emits a
///   binding for an item whose build fails, as before. Additive within 0.7
///   (#503): every item the codegen refuses stays in the manifest with a
///   [`skip_reason`] from [`skip_reason::CODEGEN_REFUSALS`] — a generic or
///   `impl Trait` signature the flavour cannot wrap, a `Result` / `Option`
///   payload that cannot cross the C ABI, a `Self` the wrapper cannot spell,
///   a lowered string whose lifetime the wrapper cannot honour — decided by
///   [`crate::refusal`], the one place the `compile_error!` comes from too.
pub const SCHEMA_VERSION: &str = "0.7";

#[cfg(test)]
mod schema_version_tests {
    use super::SCHEMA_VERSION;

    /// The identifier is the `MAJOR.MINOR` of the RustCall.jl **release**, not
    /// of this crate: `rustcall_julia_core` is published on crates.io and its semver
    /// moves on its own, while the identifier is the manifest contract between
    /// RustCall.jl and the extractor, both of which ship from one tree. It is
    /// therefore a literal here, cross-checked where both sides exist — the
    /// extractor's `schema-version` output against `MANIFEST_SCHEMA_VERSION`
    /// (from `Project.toml`) in `test/test_schema_version.jl`. This test only
    /// pins its shape.
    #[test]
    fn schema_version_is_major_minor() {
        let parts: Vec<&str> = SCHEMA_VERSION.split('.').collect();
        assert_eq!(parts.len(), 2, "SCHEMA_VERSION must be MAJOR.MINOR");
        for part in parts {
            assert!(
                !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit()),
                "SCHEMA_VERSION components must be numeric, got {SCHEMA_VERSION}"
            );
        }
    }
}

/// Vocabulary of [`Function::skip_reason`] / [`Struct::skip_reason`] /
/// [`Method::skip_reason`]. An empty reason means the item is wrappable.
///
/// The values are a closed set so Julia can group and translate them; anything
/// carrying a detail appends it after a `:`.
pub mod skip_reason {
    /// The item is not `pub`, so a wrapper crate compiled outside the scanned
    /// crate cannot name it (`E0603`).
    pub const NOT_PUBLIC: &str = "not_public";
    /// The signature mentions a type that only exists with a live Python
    /// interpreter (`PyObject`, `Py<T>`, `Bound<'_, T>`, `Python<'_>`,
    /// `PyRef`, anything under `pyo3::`). The offending type follows the colon.
    pub const PYO3_TYPE: &str = "pyo3_type";
    /// A `#[pymodule]` initialiser: it exists to be called by the Python
    /// import machinery and has no meaning without an interpreter.
    pub const PYMODULE: &str = "pymodule";
    /// A generic item: monomorphization of PyO3 items is not part of #275.
    pub const GENERIC: &str = "generic";
    /// A method whose `#[pyclass]` is itself skipped (the reason follows the
    /// colon), so there is no handle type to hang it off.
    pub const OWNER_SKIPPED: &str = "owner_skipped";
    /// Another item already claims this entry's exported symbol (it follows the
    /// colon). Since #300 the symbol folds the module path in, so items in
    /// different modules no longer collide; what remains is a coincidence
    /// such as a crate-root `fn a__run` next to `a::run`, or a `#[julia]` item
    /// and a PyO3 entry on one name. A single wrapper crate cannot export a
    /// symbol twice.
    pub const SYMBOL_COLLISION: &str = "symbol_collision";
    /// The wrapper generator cannot lower an argument: its type is neither
    /// FFI-compatible nor a `String` / `&str`, or its name is not an
    /// identifier. The spelling follows the colon (#275 Phase 2).
    pub const UNSUPPORTED_ARG: &str = "unsupported_arg";
    /// The wrapper generator cannot lower the return value: the type, or a
    /// `Result` / `Option` payload inside it, does not cross the C ABI as a
    /// single value. The spelling follows the colon (#275 Phase 2).
    pub const UNSUPPORTED_RETURN: &str = "unsupported_return";
    /// A `PyResult<T>` whose `Ok` type does not fit in the `CResult`
    /// aggregate (a `Vec`, an unrelated struct by value, ...). The spelling follows the
    /// colon. Widening this is tracked by #303 (#275 Phase 2).
    pub const PY_RESULT_PAYLOAD: &str = "py_result_payload";
    /// The item carries a `#[cfg(...)]` predicate the scan could not decide,
    /// so whether the build the wrapper links against has it at all is
    /// unknown; calling an item that is not there is a compile error in
    /// generated code. The predicate follows the colon (#275 Phase 2).
    pub const CFG_UNDECIDED: &str = "cfg_undecided";
    /// An `async fn`: its declared output is what the future resolves to, and
    /// a wrapper calling it would hand back the future — a type error in the
    /// generated crate, and nothing an `extern "C"` could return. The wrapper
    /// has no executor to drive it (#307 review).
    pub const ASYNC_FN: &str = "async_fn";
    /// A `#[staticmethod]` whose Julia name and arity another item already
    /// defines — a free function, or another class's static method of the
    /// same name: both become one untyped module-level Julia function, and the
    /// later definition would silently replace the earlier. The earlier
    /// item's qualified name follows the colon (#307 review).
    pub const JULIA_NAME_COLLISION: &str = "julia_name_collision";
    /// A `#[julia]` item that is an `unsafe fn` — a free function, or a method
    /// of a `#[julia]` struct (#491). Its `extern "C"` entry point would let
    /// Julia call it with none of the requirements its `unsafe` states
    /// upheld, so codegen refuses it with a `compile_error!` at the item;
    /// the reason lets the Julia generators name that refusal before anything
    /// is built.
    pub const UNSAFE_FN: &str = "unsafe_fn";
    /// A `#[julia]` item generic over type or const parameters the flavour
    /// cannot bind (#503): any generic item of a crate (the proc macro sees
    /// one item and cannot know the instantiations), a const-generic
    /// function of a `rust"""` block, or a method generic in its own right.
    /// The parameters follow the colon (`generic_signature:T, const N`).
    pub const GENERIC_SIGNATURE: &str = "generic_signature";
    /// A `#[julia]` function or method with `impl Trait` in its signature,
    /// which makes it generic (#503).
    pub const IMPL_TRAIT: &str = "impl_trait";
    /// A `#[julia]` function whose `Result` / `Option` payload cannot cross
    /// the C ABI (#503). The payload type follows the colon.
    pub const NON_FFI_PAYLOAD: &str = "non_ffi_payload";
    /// A method whose signature names a trait's `Self::X` in a trait impl
    /// whose trait the header names by a path the wrapper may not have in
    /// scope (#482, #503).
    pub const SELF_TRAIT_PATH: &str = "self_trait_path";
    /// A method whose signature has a `Self` the wrapper, a free function,
    /// cannot spell — inside a macro invocation, whose name follows the
    /// colon (#482, #503).
    pub const UNSPELLABLE_SELF: &str = "unspellable_self";
    /// An item whose returned reference borrows, by lifetime elision, a
    /// `&str` argument that arrives as a pointer and a length and is rebuilt
    /// for the call (#484, #503). The argument follows the colon.
    pub const LOWERED_STR_BORROW: &str = "lowered_str_borrow";
    /// An item one of whose lowered `&'a str` arguments names a lifetime the
    /// call cannot end inside the wrapper (#482, #503). The argument follows
    /// the colon.
    pub const LOWERED_STR_LIFETIME: &str = "lowered_str_lifetime";
    /// A trait-impl method whose typed receiver the wrapper cannot read — a
    /// type alias, a smart pointer, the type's own name, or `self: &mut Self`
    /// (#497, #509). Its wrapper calls `<S as Trait>::m(..)`, which passes the
    /// receiver exactly as declared. The receiver type follows the colon.
    pub const TRAIT_RECEIVER: &str = "trait_receiver";

    /// Every reason the `#[julia]` codegen itself refuses an item for, with a
    /// `compile_error!` at the item ([`crate::refusal`], #503). An item
    /// carrying one of them gets no wrapper and claims no symbol; Julia binds
    /// nothing for it and the boundary report lists it.
    pub const CODEGEN_REFUSALS: &[&str] = &[
        UNSAFE_FN,
        GENERIC_SIGNATURE,
        IMPL_TRAIT,
        NON_FFI_PAYLOAD,
        SELF_TRAIT_PATH,
        UNSPELLABLE_SELF,
        LOWERED_STR_BORROW,
        LOWERED_STR_LIFETIME,
        TRAIT_RECEIVER,
    ];

    /// Whether `reason` is one of [`CODEGEN_REFUSALS`], its detail aside.
    pub fn is_codegen_refusal(reason: &str) -> bool {
        let kind = reason.split(':').next().unwrap_or("");
        CODEGEN_REFUSALS.contains(&kind)
    }

    /// `"<kind>:<detail>"`, e.g. `"pyo3_type:Python<'_>"`.
    pub fn detailed(kind: &str, detail: &str) -> String {
        format!("{kind}:{detail}")
    }
}

/// Which pipeline produced the manifest.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Mode {
    /// `rust"""..."""` blocks: `#[julia]` items are expanded by the extractor CLI
    /// before `rustc` runs, all `pub fn` methods of `#[julia]` structs are wrapped,
    /// and generic items are reported for runtime monomorphization.
    Inline,
    /// `@rust_crate`: `#[julia]` items are expanded by the `rustcall_julia_macros`
    /// proc-macro inside Cargo; only explicitly attributed methods are wrapped.
    Crate,
}

impl Mode {
    pub fn parse(s: &str) -> Option<Mode> {
        match s {
            "inline" => Some(Mode::Inline),
            "crate" => Some(Mode::Crate),
            _ => None,
        }
    }
}

/// Which attribute (if any) marked an item.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Attribute {
    Julia,
    /// `#[derive(JuliaStruct)]` on a struct (inline mode only).
    DeriveJuliaStruct,
    /// `#[pyfunction]` with no RustCall attribute (#275). The item is reported
    /// so a Phase-2 wrapper crate can generate an `extern "C"` entry point for
    /// it; nothing exports it yet.
    PyFunction,
    /// `#[pyclass]` with no RustCall attribute (#275): an opaque handle, never
    /// `repr(C)`.
    PyClass,
    /// A method collected from a `#[pymethods]` block of a [`Attribute::PyClass`]
    /// struct (#275).
    PyMethods,
    /// A `#[pymodule]` initialiser (#275). Always skipped, see
    /// [`skip_reason::PYMODULE`].
    PyModule,
    /// No RustCall attribute: a plain function that is still reported so Julia
    /// can register return types for `@rust f(...)` calls without `::T`.
    None,
}

impl Attribute {
    /// Whether this origin comes from the PyO3 scan (#275) rather than from a
    /// RustCall attribute.
    pub fn is_pyo3_scan(self) -> bool {
        matches!(
            self,
            Attribute::PyFunction | Attribute::PyClass | Attribute::PyMethods | Attribute::PyModule
        )
    }

    /// `serde(skip_serializing_if)` predicate for the optional
    /// [`Method::attribute`] column: no attribute, nothing written.
    pub fn is_none(&self) -> bool {
        matches!(self, Attribute::None)
    }

    /// Whether RustCall generates an `extern "C"` wrapper for an item
    /// reported under this attribute, and with it a panic channel and any
    /// string buffers the signature needs.
    ///
    /// False for [`Attribute::None`]: a plain `#[no_mangle] extern "C"`
    /// function is reported only so Julia can register its return type. It is
    /// exported under its own name and claims no derived name, which is why a
    /// hand-written `release` / `release_take_panic` pair is two unrelated
    /// exports rather than a collision (#338).
    pub fn generates_wrapper(self) -> bool {
        !matches!(self, Attribute::None)
    }
}

/// The absence of an attribute, which is what a `#[serde(default)]` column
/// reads as when the extractor omitted it.
impl Default for Attribute {
    fn default() -> Self {
        Attribute::None
    }
}

/// Shape of a function's return value on the C ABI.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReturnKind {
    /// Returned as-is.
    #[default]
    Plain,
    /// `()` / no return type.
    Unit,
    /// `Result<T, E>` wrapped into `CResult_<fn>` `{ is_ok: u8, ok_value: T, err_value: E }`.
    Result,
    /// `Option<T>` wrapped into `COption_<fn>` `{ is_some: u8, value: T }`.
    Option,
    /// `PyResult<T>` (= `Result<T, PyErr>`) of a scanned PyO3 item (#275), with
    /// `T` in [`Function::ok_type`] / [`Method::ok_type`].
    ///
    /// Creating and dropping a `PyErr` without a Python interpreter is safe,
    /// but rendering one is not: `Display`/`Debug` on a `PyErr` panics inside
    /// pyo3 and the panic crossing `extern "C"` aborts the process. A Phase-2
    /// wrapper must therefore report the error as an opaque flag and never
    /// format it.
    PyResult,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Arg {
    pub name: String,
    pub rust_type: String,
    /// How the wrapper receives the argument: `""` as written (`rust_type`),
    /// `"string"` (`String`: `(ptr, len)` bytes copied into an owned String),
    /// `"str"` (`&str`, any lifetime: `(ptr, len)` bytes borrowed),
    /// `"callback"` (a C-ABI function pointer, passed as written; #296).
    #[serde(default)]
    pub abi: String,
    /// For `abi == "callback"`: the parameter spellings of the function
    /// pointer (`extern "C" fn(i64, f64) -> i64` → `["i64", "f64"]`), so the
    /// consumer builds the callback from the manifest rather than from Rust
    /// syntax (#264). Empty otherwise.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub callback_args: Vec<String>,
    /// For `abi == "callback"`: the return spelling of the function pointer,
    /// `""` for a unit or absent return. Empty otherwise.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub callback_return: String,
    /// Rust expression from `#[pyo3(signature = (...))]` / `#[args(...)]`.
    /// It is never evaluated by a manifest consumer; an empty value means the
    /// Python argument is required.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub python_default: String,
    /// `positional_only`, `positional_or_keyword`, `keyword_only`, `var_args`
    /// or `kw_args`; empty outside a declared PyO3 signature.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub python_kind: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TraitBound {
    pub trait_name: String,
    #[serde(default)]
    pub type_params: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TypeParam {
    pub name: String,
    #[serde(default)]
    pub bounds: Vec<TraitBound>,
}

/// A free function.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Function {
    pub name: String,
    /// The stem every generated symbol of the function hangs off
    /// (`crate::codegen::symbol_stem`, schema 7, #300): `name` at the crate
    /// root, module-qualified otherwise (`a::run` -> `a__run`). The wrapper is
    /// `rustcall_<ffi_name>` ([`Function::symbol`]) and a string result is
    /// released through `<ffi_name>_free_rust_string`.
    #[serde(default)]
    pub ffi_name: String,
    /// Exported C symbol. `#[julia]` is additive, so a wrapped function is
    /// exported as `rustcall_<name>` and never under `name` itself (#279); a
    /// plain `#[no_mangle] extern "C"` function keeps its own name.
    pub symbol: String,
    /// Which attribute the item was reported for. Since schema 5 this is also
    /// the *origin*: a `py_*` value means the entry came from the PyO3 scan of
    /// #275, not from a RustCall attribute.
    pub attribute: Attribute,
    /// Visibility as written: `"pub"`, `"pub(crate)"`, `"pub(super)"`,
    /// `"pub(in path)"`, or `""` for a private item. Only a `pub` item can be
    /// called from a wrapper crate compiled outside the scanned crate (#275).
    #[serde(default)]
    pub vis: String,
    /// Why this item cannot be wrapped, from the [`skip_reason`] vocabulary;
    /// empty when it can (#275). Always empty for `#[julia]` items, which are
    /// only reported when they are wrapped.
    #[serde(default)]
    pub skip_reason: String,
    /// The name the item is exposed under in Python (`#[pyo3(name = "...")]`),
    /// empty when it is the Rust name or the item is not a PyO3 one (#275).
    #[serde(default)]
    pub python_name: String,
    /// The Python attribute path of a **declarative** PyO3 module item
    /// (`#[pymodule] mod outer { ... }`, #424), below the imported module:
    /// empty for a direct item (`module.f`, and for every function-form
    /// crate), `["inner"]` for one in a nested `#[pymodule] mod inner`
    /// (`module.inner.g`). Additive within schema 0.6.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub python_path: Vec<String>,
    /// True when the generated code carries `#[no_mangle] extern "C"`.
    ///
    /// Always `false` for a PyO3-scanned item: [`Function::symbol`] names the
    /// wrapper a Phase-2 wrapper crate *will* emit, and nothing exports it yet.
    pub exported: bool,
    /// `#[cfg(...)]` predicate of the item (`unix`, `all(unix, feature = "x")`),
    /// empty when unconditional. Items whose predicate is false under the
    /// configuration given to the extractor are not reported at all.
    #[serde(default)]
    pub cfg: String,
    /// Crate features the item's `#[cfg(...)]` predicate depends on
    /// (`#[cfg(feature = "python")]` -> `["python"]`), empty when it has none.
    ///
    /// The crate scan evaluates `#[cfg]` leniently, so a feature-gated item is
    /// reported even though whether it exists depends on the feature set the
    /// crate is built with. This column lets a consumer reconcile the two by
    /// set membership, without handling Rust `cfg` syntax itself (#275, #264).
    #[serde(default)]
    pub cfg_features: Vec<String>,
    pub is_generic: bool,
    #[serde(default)]
    pub type_params: Vec<TypeParam>,
    #[serde(default)]
    pub args: Vec<Arg>,
    /// Return type as written in the source (`i32`, `Result<f64, i32>`, `()`).
    pub return_type: String,
    pub return_kind: ReturnKind,
    /// How the wrapper returns the value: `""` as written, `"string"` for an
    /// owned `<fn>_RustCallOwnedString` (a `String`, or a `&str` copied because
    /// it may borrow from a converted argument), `"str"` for a borrowed
    /// `<fn>_RustCallBorrowedString`. Same vocabulary as [`Arg::abi`] and
    /// [`Method::return_abi`]; this is the normative column since schema 4 and
    /// the `has_*_string_helper` booleans below are derived from it (#276).
    #[serde(default)]
    pub return_abi: String,
    /// `T` of `Result<T, E>`, empty otherwise.
    #[serde(default)]
    pub ok_type: String,
    /// `E` of `Result<T, E>`, empty otherwise.
    #[serde(default)]
    pub err_type: String,
    /// `T` of `Option<T>`, empty otherwise.
    #[serde(default)]
    pub inner_type: String,
    /// How each `Result` / `Option` payload travels: `""` as written,
    /// `"string"` for an owned `<fn>_RustCallOwnedString` buffer released
    /// through `<fn>_free_rust_string` (schema 6, #268). This is what makes
    /// the `Result` and string lowerings composable: `Result<String, String>`
    /// is one aggregate holding two such buffers, of which exactly the active
    /// one is initialized and must be released.
    #[serde(default)]
    pub ok_abi: String,
    #[serde(default)]
    pub err_abi: String,
    #[serde(default)]
    pub inner_abi: String,
    /// The function returns `String`: the wrapper returns
    /// `<fn>_RustCallOwnedString { ptr, len, cap }`, released through
    /// `<fn>_free_rust_string(ptr, len, cap)` (#242).
    ///
    /// Derived from [`Function::return_abi`] since schema 4 and kept for one
    /// release so a consumer that still reads the boolean keeps working (#276).
    #[serde(default)]
    pub has_owned_string_helper: bool,
    /// The function returns `&str`: the wrapper returns
    /// `<fn>_RustCallBorrowedString { ptr, len }` (#242). Derived from
    /// [`Function::return_abi`], see [`Function::has_owned_string_helper`].
    #[serde(default)]
    pub has_borrowed_string_helper: bool,
    /// Source of the function item (generic functions only), used for
    /// runtime monomorphization via `specialize`.
    #[serde(default)]
    pub source: String,
    /// Whether the body contains a `#[cfg(...)]` / `#[cfg_attr(...)]`
    /// attribute or a `cfg!(...)` macro. Item-level pruning never resolves
    /// those, so the body still depends on the configuration it is compiled
    /// under; a caller that later compiles the (specialized) source under
    /// another configuration than the one the item was extracted for must
    /// refuse rather than guess.
    #[serde(default)]
    pub body_has_cfg: bool,
    /// 1-based line of the item in the input file.
    pub line: usize,
    /// Enclosing inline modules (`mod api { mod deep { fn f } }` -> `["api", "deep"]`).
    /// `specialize` locates the function by `module_path::name` in the expanded source.
    ///
    /// What the list means depends on the origin (schema 7, #300): for an
    /// inline block it is every enclosing inline module; for a `#[julia]` item
    /// of a crate it is the chain of `#[julia]`-marked inline modules — the
    /// path the proc-macro folded into the symbol — with file modules
    /// (`mod a;`) transparent; for a PyO3-scanned item it is the real path of
    /// the crate's module tree. In every case [`Function::ffi_name`] is derived
    /// from it, and a consumer that lays items out per module keys on it.
    #[serde(default)]
    pub module_path: Vec<String>,
    /// External Rust spelling, including the item name, when re-exported from
    /// its canonical module. Empty means module_path + name (legacy manifests).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub callable_path: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Field {
    pub name: String,
    pub rust_type: String,
    /// How the generated getter returns the field: `""` as written
    /// (`rust_type`), `"string"` for an owned `<Struct>_RustCallOwnedString`
    /// released through `<Struct>_free_rust_string`, or `"vec"` for the
    /// owned buffer described by [`Field::vec_element`] and [`Field::free_symbol`]. Same vocabulary as
    /// [`Arg::abi`] / [`Method::return_abi`], so Julia never has to re-derive
    /// the lowering from the type spelling (#276).
    #[serde(default)]
    pub abi: String,
    /// Element type for the `"vec"` ABI. Empty for every other field.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub vec_element: String,
    /// Export that reconstructs and drops the owned vector returned by this
    /// getter. Empty unless `abi == "vec"` and a getter is emitted.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub free_symbol: String,
    /// Whether Julia may read this field through an exported getter.
    pub ffi_compatible: bool,
    /// Exported symbol that reads the field. Usually `<Struct>_get_<field>`; in
    /// inline mode a same-named method wrapper takes precedence. Empty if none.
    #[serde(default)]
    pub getter: String,
    /// Exported symbol that writes the field (`<Struct>_set_<field>`). Empty if none.
    #[serde(default)]
    pub setter: String,
    /// The name the field is exposed under in Python
    /// (`#[pyo3(get, name = "...")]`), empty when it is the Rust name or the
    /// struct is not a `#[pyclass]` (#275).
    #[serde(default)]
    pub python_name: String,
    /// Visibility of the field as written, in the vocabulary of
    /// [`Function::vis`]. A `#[pyo3(get)]` on a **private** field still gives
    /// Python a descriptor — pyo3 generates it inside the crate — but a wrapper
    /// crate compiled outside cannot read `Struct::field`, so only a `pub`
    /// field gets accessors from the PyO3 scan (#275).
    #[serde(default)]
    pub vis: String,
    /// `#[cfg(...)]` predicate on the field that the scan could not decide
    /// (see [`Function::cfg`]); empty — and then omitted — when there is
    /// none. A wrapper crate generated from a leniently evaluated scan refuses
    /// the accessors of such a field instead of naming a member the build it
    /// is compiled against may not have (#307 review).
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub cfg: String,
    /// Whether PyO3 exposes the field to Python (`#[pyo3(get)]`, or
    /// `get_all`), independent of whether a wrapper crate can read it
    /// ([`Field::ffi_compatible`]). The Python-host path reads through the
    /// object, so a private field of a private struct is readable even though
    /// it has no exported getter (#424). Additive within schema 0.6.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub pyo3_get: bool,
    /// Whether PyO3 exposes a setter for the field (`#[pyo3(set)]`, or
    /// `set_all`; never when the class is `frozen`). See [`Field::pyo3_get`].
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub pyo3_set: bool,
    /// The accessors this field had before a **symbol collision** took them.
    ///
    /// In memory only, and never serialized: it exists so the collision
    /// analysis can be run again from the state it found. Every other skip the
    /// analysis produces is a `skip_reason` it can simply clear and re-derive,
    /// but a field's accessors are *erased*, and the entry that took them may
    /// yet be refused by the generator — after which the field's own getter is
    /// valid again and there would be nothing left to restore it from
    /// (#392 review). Set by the first clearing only, so the original survives
    /// any number of passes.
    #[serde(skip)]
    pub precollision: Option<Box<FieldAccessors>>,
}

/// What [`Field::precollision`] remembers: everything a symbol collision
/// clears on a field.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct FieldAccessors {
    pub ffi_compatible: bool,
    pub getter: String,
    pub setter: String,
    pub free_symbol: String,
}

impl Field {
    /// Remember the accessors, once, before a collision clears them.
    pub fn remember_accessors(&mut self) {
        if self.precollision.is_none() {
            self.precollision = Some(Box::new(FieldAccessors {
                ffi_compatible: self.ffi_compatible,
                getter: self.getter.clone(),
                setter: self.setter.clone(),
                free_symbol: self.free_symbol.clone(),
            }));
        }
    }

    /// Put back what a collision cleared, so the analysis can decide again.
    pub fn restore_accessors(&mut self) {
        if let Some(saved) = &self.precollision {
            self.ffi_compatible = saved.ffi_compatible;
            self.getter = saved.getter.clone();
            self.setter = saved.setter.clone();
            self.free_symbol = saved.free_symbol.clone();
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Method {
    pub name: String,
    /// Exported C symbol of the wrapper (`rustcall_<Struct>_<method>`, #279).
    /// Empty for generic structs, whose wrappers are registered for
    /// monomorphization instead.
    pub symbol: String,
    pub is_static: bool,
    pub is_mutable: bool,
    pub is_constructor: bool,
    /// Visibility as written: `"pub"`, `"pub(crate)"`, `"pub(super)"`,
    /// `"pub(in path)"`, or `""` for a private item. Only a `pub` item can be
    /// called from a wrapper crate compiled outside the scanned crate (#275).
    #[serde(default)]
    pub vis: String,
    /// Why this item cannot be wrapped, from the [`skip_reason`] vocabulary;
    /// empty when it can (#275). Always empty for `#[julia]` items, which are
    /// only reported when they are wrapped.
    #[serde(default)]
    pub skip_reason: String,
    /// The name the item is exposed under in Python (`#[pyo3(name = "...")]`),
    /// empty when it is the Rust name or the item is not a PyO3 one (#275).
    #[serde(default)]
    pub python_name: String,
    /// `"getter"` / `"setter"` for a `#[getter]` / `#[setter]` method of a
    /// `#[pymethods]` block, empty otherwise (#275).
    #[serde(default)]
    pub accessor: String,
    /// The attribute of the **impl block** the method came from — `julia` for
    /// a `#[julia] impl`, `py_methods` for a scanned `#[pymethods]` block —
    /// which need not be the struct's own (#275 Phase 3). `None` — and then
    /// omitted — for an inline-mode impl, which carries no attribute. Additive
    /// within schema 6, like [`Method::cfg`].
    #[serde(default, skip_serializing_if = "Attribute::is_none")]
    pub attribute: Attribute,
    /// Shape of the return value, as for a free function. A `#[julia]` method
    /// returning `Result<T, E>` / `Option<T>` is [`ReturnKind::Result`] /
    /// [`ReturnKind::Option`] (schema 6, #268); a scanned `#[pymethods]` method
    /// returning `PyResult<T>` is [`ReturnKind::PyResult`] with `T` in
    /// [`Method::ok_type`], so a Phase-2 wrapper never has to re-read the Rust
    /// type spelling (#275).
    #[serde(default)]
    pub return_kind: ReturnKind,
    /// `T` of a `PyResult<T>` / `Result<T, E>` return, empty otherwise (#275).
    #[serde(default)]
    pub ok_type: String,
    /// `E` of a `Result<T, E>` return, empty otherwise (#275).
    #[serde(default)]
    pub err_type: String,
    /// `T` of an `Option<T>` return, empty otherwise (#275).
    #[serde(default)]
    pub inner_type: String,
    /// The stem this method's string buffers hang off:
    /// `<owner>_RustCallOwnedString`, `<owner>_free_rust_string` and
    /// `<owner>_RustCallBorrowedString` — for a string return
    /// ([`Method::return_abi`]) as much as for a string `Result` / `Option`
    /// payload ([`Method::ok_abi`]).
    ///
    /// The struct's own [`Struct::ffi_name`] when the wrapper is emitted next
    /// to the struct and shares its buffers; `<ffi_name>_<method>`
    /// (`crate::codegen::method_string_owner`) when the wrapper declares its
    /// own — every crate-flavour method, and since #342 an inline method whose
    /// `#[julia] impl` block sits in another module than its struct, whose
    /// wrapper is emitted at the block. One inline manifest can hold both
    /// shapes, so the manifest **states** the owner rather than leaving a
    /// consumer to infer it from the flavour, exactly as schema 6 states the
    /// payload ABIs instead of leaving them to be read off the spelling
    /// (#268). Empty when no `#[julia]` wrapper exists (a scanned
    /// `#[pymethods]` entry, a generic struct's methods, whose wrappers are
    /// monomorphized under names Julia chooses); a consumer then falls back to
    /// its flavour's derivation. Additive within schema 7.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub string_owner: String,
    /// The trait of the impl block the method was written in, as the header
    /// spells it (`tr::Limits`); empty — and then omitted — for an inherent
    /// method. A method is identified by `(trait_path, name)`: a refused
    /// `#[julia]` method of a trait impl is recorded on its struct (#503) and
    /// must not be merged with an inherent method, or another trait's, of the
    /// same name. Additive within schema 0.7. Describing a trait impl's
    /// wrapped methods is #506.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub trait_path: String,
    /// How each `Result` / `Option` payload travels: `""` as written,
    /// `"string"` for an owned `<owner>_RustCallOwnedString` buffer released
    /// through `<owner>_free_rust_string` (schema 6, #268), the owner being
    /// [`Method::string_owner`].
    #[serde(default)]
    pub ok_abi: String,
    #[serde(default)]
    pub err_abi: String,
    #[serde(default)]
    pub inner_abi: String,
    /// Whether the wrapper boxes the result and returns `*mut Struct`
    /// (`crate::codegen::returns_boxed_struct`). Julia used to infer this by
    /// comparing `return_type` against `"Self"` and the struct name, which
    /// disagreed with codegen for a non-static method called `new` (#276).
    #[serde(default)]
    pub returns_boxed_struct: bool,
    #[serde(default)]
    pub args: Vec<Arg>,
    pub return_type: String,
    /// How the wrapper returns the value: `""` as written, `"string"` for an
    /// owned `<owner>_RustCallOwnedString` (a `String`, or a `&str` copied
    /// because it may borrow from a converted argument), `"str"` for a
    /// borrowed `<owner>_RustCallBorrowedString`, the owner being
    /// [`Method::string_owner`].
    #[serde(default)]
    pub return_abi: String,
    /// For generic structs: the generic wrapper source registered for
    /// monomorphization. Empty otherwise.
    #[serde(default)]
    pub generic_wrapper: String,
    /// For generic structs: the name of [`Method::generic_wrapper`], the
    /// [`GenericWrapper::name`] a consumer registers and monomorphizes it
    /// under — `<ffi_name>_<method>`, module-qualified like every other name
    /// of the struct (#462). Empty — and then omitted — otherwise. Additive
    /// within schema 0.6.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub generic_wrapper_name: String,
    /// `#[cfg(...)]` predicate on the method that the scan could not decide
    /// (see [`Function::cfg`]); empty — and then omitted — when there is
    /// none. A wrapper crate generated from a leniently evaluated scan refuses
    /// such a method with [`skip_reason::CFG_UNDECIDED`], as it refuses an
    /// item (#307 review).
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub cfg: String,
    /// Whether the method carries `#[classmethod]` (#424). [`Method::is_static`]
    /// is true for it too — neither takes a `self` receiver — but Python's call
    /// passes the class as the first argument, so a Python-host binding drops
    /// that argument rather than requiring it from Julia. Additive within
    /// schema 0.6.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub is_classmethod: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Struct {
    pub name: String,
    /// The stem every generated symbol of the struct hangs off
    /// (`crate::codegen::symbol_stem`, schema 7, #300): `name` at the crate
    /// root, module-qualified otherwise (`a::C` -> `a__C`). The destructor is
    /// `<ffi_name>_free`, the accessors `<ffi_name>_get_<field>` /
    /// `<ffi_name>_set_<field>`, the clone `<ffi_name>_clone`, the shared
    /// string buffer `<ffi_name>_RustCallOwnedString` /
    /// `<ffi_name>_free_rust_string`, and a method's symbol
    /// `rustcall_<ffi_name>_<method>` with its per-method buffer
    /// `<ffi_name>_<method>_RustCallOwnedString` (crate flavour).
    #[serde(default)]
    pub ffi_name: String,
    pub attribute: Attribute,
    /// Visibility as written: `"pub"`, `"pub(crate)"`, `"pub(super)"`,
    /// `"pub(in path)"`, or `""` for a private item. Only a `pub` item can be
    /// called from a wrapper crate compiled outside the scanned crate (#275).
    #[serde(default)]
    pub vis: String,
    /// Why this item cannot be wrapped, from the [`skip_reason`] vocabulary;
    /// empty when it can (#275). Always empty for `#[julia]` items, which are
    /// only reported when they are wrapped.
    #[serde(default)]
    pub skip_reason: String,
    /// The name the item is exposed under in Python (`#[pyo3(name = "...")]`),
    /// empty when it is the Rust name or the item is not a PyO3 one (#275).
    #[serde(default)]
    pub python_name: String,
    /// The Python attribute path of a **declarative** PyO3 module class
    /// (`#[pymodule] mod outer { ... }`, #424), below the imported module:
    /// empty for a direct class (`module.Point`) and for every function-form
    /// crate, `["inner"]` for one in a nested module
    /// (`module.inner.Point`). See [`Function::python_path`].
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub python_path: Vec<String>,
    /// Base type named by `#[pyclass(extends = ...)]`; empty for ordinary
    /// classes and non-PyO3 structs. This selects a Python-owned handle.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub pyo3_extends: String,
    /// Object-shape flags from `#[pyclass(...)]` (`subclass`, `dict`,
    /// `weakref`). They are data for the wrapper, not inferred from docs.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub pyo3_options: Vec<String>,
    /// Whether this wrapper stores a Python object rather than a boxed Rust
    /// `Self`. Set before wrapper generation filters unsupported methods;
    /// consumers use it for image pinning and finalizer liveness.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub python_owned_handle: bool,

    /// `#[cfg(...)]` predicate of the struct item, see [`Function::cfg`].
    #[serde(default)]
    pub cfg: String,
    /// Crate features the predicate depends on, see [`Function::cfg_features`].
    #[serde(default)]
    pub cfg_features: Vec<String>,
    #[serde(default)]
    pub type_params: Vec<TypeParam>,
    #[serde(default)]
    pub fields: Vec<Field>,
    #[serde(default)]
    pub methods: Vec<Method>,
    /// Other derives seen alongside `JuliaStruct` (e.g. `Clone`).
    #[serde(default)]
    pub derives: Vec<String>,
    /// Whether a `<Struct>_clone` wrapper was generated.
    pub has_clone: bool,
    /// Whether the `<Struct>_RustCallOwnedString` / `<Struct>_free_rust_string`
    /// helpers were generated (inline mode).
    pub has_owned_string_helper: bool,
    /// Whether the `<Struct>_RustCallBorrowedString` helper was generated (inline mode).
    pub has_borrowed_string_helper: bool,
    /// Source of the struct and its impl blocks (generic structs only), used as
    /// context for runtime monomorphization.
    #[serde(default)]
    pub context_source: String,
    /// Generic accessor / free wrappers registered for monomorphization
    /// (generic structs only).
    #[serde(default)]
    pub generic_wrappers: Vec<GenericWrapper>,
    pub line: usize,
    /// Enclosing inline modules of the struct (see [`Function::module_path`]).
    #[serde(default)]
    pub module_path: Vec<String>,
    /// External Rust spelling; canonical identity remains module_path + name.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub callable_path: Vec<String>,
}

/// A generic wrapper of a generic inline struct. In inline mode the wrapper is
/// also emitted (non-exported) into the expanded source next to the struct so
/// that `specialize` can instantiate it in place with all module-scoped names
/// available.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GenericWrapper {
    pub name: String,
    pub source: String,
    /// Type parameter names as declared by the wrapper, in the order of the
    /// struct's own parameters (an `impl<U> Wrapper<U>` wrapper lists `U` where
    /// the struct declares `T`), followed by method-level parameters.
    #[serde(default)]
    pub type_params: Vec<String>,
}

/// `` `a::C` (line 3) `` — how [`Manifest::symbol_owners`] names an item.
fn symbol_owner(path: &[String], name: &str, line: usize) -> String {
    let mut segments = path.to_vec();
    segments.push(name.to_string());
    format!("`{}` (line {line})", segments.join("::"))
}

impl Function {
    /// Every name this `#[julia]` function's generated code defines — its
    /// wrapper, the reader of that wrapper's panic channel, the slot the
    /// reader drains and, when it returns a string, the buffer type and its
    /// release function — with the owner label of [`Manifest::symbol_owners`].
    /// Empty when it defines none (a PyO3 item, an unexported or generic one,
    /// an undecided `#[cfg]`).
    ///
    /// The panic reader is as much an export as the wrapper itself
    /// (`crate::codegen::panic_channel` emits it `#[no_mangle]` next to it),
    /// so a crate-root `#[julia] fn a__run_take_panic` next to `a::run` is a
    /// duplicate symbol even though the two wrappers differ (#338). Only a
    /// wrapper RustCall generates has one: a plain `#[no_mangle] extern "C"`
    /// function is reported so Julia can register its return type, is
    /// exported under its own name, and adds nothing — a hand-written
    /// `release` / `release_take_panic` pair is two unrelated exports, not a
    /// collision.
    pub fn claims(&self) -> Vec<(crate::claims::Claim, String)> {
        if self.attribute.is_pyo3_scan() {
            return Vec::new();
        }
        let who = symbol_owner(&self.module_path, &self.name, self.line);
        crate::claims::function_claims(self, crate::claims::Policy::JULIA)
            .into_iter()
            .map(|claim| (claim, who.clone()))
            .collect()
    }
}

impl Struct {
    /// The exported symbols this `#[julia]` struct claims — `free`, the field
    /// accessors, the method wrappers, the panic-channel reader every one of
    /// those wrappers exports next to itself, and the release functions of the
    /// owned-string buffers they use — with the owner label of
    /// [`Manifest::symbol_owners`].
    ///
    /// A buffer's release function is claimed once however many items share
    /// it: an inline method wrapped next to its struct shares the struct's
    /// (`string_owner == ffi_name`), one wrapped at a `#[julia] impl` block in
    /// another module declares its own (#342).
    pub fn claims(&self) -> Vec<(crate::claims::Claim, String)> {
        if self.attribute.is_pyo3_scan() {
            return Vec::new();
        }
        let who = symbol_owner(&self.module_path, &self.name, self.line);
        crate::claims::struct_claims(self, crate::claims::Policy::JULIA)
            .into_iter()
            .map(|claim| (claim, who.clone()))
            .collect()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Manifest {
    /// See [`SCHEMA_VERSION`]: the `MAJOR.MINOR` of the producing release.
    pub schema_version: String,
    pub mode: Mode,
    #[serde(default)]
    pub functions: Vec<Function>,
    #[serde(default)]
    pub structs: Vec<Struct>,
}

impl Manifest {
    pub fn new(mode: Mode) -> Self {
        Manifest {
            schema_version: SCHEMA_VERSION.to_string(),
            mode,
            functions: Vec::new(),
            structs: Vec::new(),
        }
    }

    /// Merge another manifest (e.g. from a second source file) into this one.
    pub fn merge(&mut self, other: Manifest) {
        self.functions.extend(other.functions);
        self.structs.extend(other.structs);
    }

    /// Sort entries so output is deterministic regardless of file order.
    pub fn sort(&mut self) {
        self.functions.sort_by(|a, b| {
            a.module_path
                .cmp(&b.module_path)
                .then(a.name.cmp(&b.name))
                .then(a.line.cmp(&b.line))
        });
        self.structs.sort_by(|a, b| {
            a.module_path
                .cmp(&b.module_path)
                .then(a.name.cmp(&b.name))
                .then(a.line.cmp(&b.line))
        });
    }

    /// Every exported symbol a `#[julia]` item of this manifest claims, with
    /// the item that claims it (`module::name`, line) — the input of the
    /// crate-wide duplicate check (#300).
    ///
    /// The scheme keeps items in different modules apart by construction, so
    /// what this catches is a coincidence it cannot exclude: two file modules
    /// (which are transparent to the scheme) both defining `#[julia] fn run`,
    /// or a crate-root `fn a__run` next to `a::run`. Items whose `#[cfg]` the
    /// scan could not decide are left out — two variants of one function under
    /// mutually exclusive predicates are the normal shape of a portable crate,
    /// not a clash. PyO3-scanned items are not listed either: the scan marks
    /// their clashes with a `skip_reason` (`crate::pyo3`).
    pub fn symbol_owners(&self) -> Vec<(String, String)> {
        self.claim_owners()
            .into_iter()
            .filter(|(claim, _)| claim.exported)
            .map(|(claim, who)| (claim.name, who))
            .collect()
    }

    /// The same, widened to every name the generated code defines: the
    /// exported ones plus the module-private panic slots and helper types.
    /// Two generated items wanting one private name is a duplicate definition
    /// rustc reports inside generated code, which is exactly what this
    /// machinery exists to pre-empt (#338).
    pub fn claim_owners(&self) -> Vec<(crate::claims::Claim, String)> {
        let mut out = Vec::new();
        for f in &self.functions {
            out.extend(f.claims());
        }
        for s in &self.structs {
            out.extend(s.claims());
        }
        out
    }

    /// Symbols [`Manifest::symbol_owners`] lists twice, as
    /// `(symbol, first owner, second owner)` in the order they were claimed.
    ///
    /// The crate scan claims incrementally as it walks files, so it reports a
    /// duplicate itself (`crate::extract::CrateScan`). Inline expansion builds
    /// one manifest for one block and asks this instead, so a `rust"""` block
    /// whose generated symbols collide fails with a `compile_error!` naming
    /// both items rather than with rustc's duplicate-symbol diagnostic
    /// pointing into generated code (#342 review).
    pub fn duplicate_symbols(&self) -> Vec<(String, String, String)> {
        self.duplicate_claims()
            .into_iter()
            .filter(|(claim, _, _)| claim.exported)
            .map(|(claim, first, second)| (claim.name, first, second))
            .collect()
    }

    /// The same over every generated name, exported or not, so a caller can
    /// tell a reader which kind of clash it is looking at: a `#[no_mangle]`
    /// symbol the `cdylib` cannot export twice, or an internal item — a panic
    /// slot, a string buffer type — the crate cannot define twice (#338).
    pub fn duplicate_claims(&self) -> Vec<(crate::claims::Claim, String, String)> {
        let mut seen: Vec<(crate::claims::Claim, String)> = Vec::new();
        let mut out = Vec::new();
        for (claim, who) in self.claim_owners() {
            // Same name is not enough: an exported symbol is crate-global,
            // while a private item has to be unique only in its own module
            // and its own Rust namespace (#338 review).
            match seen.iter().find(|(c, _)| c.clashes_with(&claim)) {
                Some((_, first)) => out.push((claim, first.clone(), who)),
                None => seen.push((claim, who)),
            }
        }
        out
    }

    pub fn to_toml(&self) -> Result<String, toml::ser::Error> {
        toml::to_string(self)
    }

    pub fn from_toml(s: &str) -> Result<Manifest, toml::de::Error> {
        toml::from_str(s)
    }
}