rustcall_julia_core 0.1.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
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
//! Manifest extraction.
//!
//! * `extract_crate(source)`: manifest for a crate source file, following the
//!   proc-macro's rules (what `rustcall_julia_macros` would actually generate).
//! * `extract_inline(source)`: manifest for a `rust"""` block; delegates to
//!   [`crate::expand::expand`] so the manifest and the expanded code cannot
//!   disagree.

use syn::spanned::Spanned;
use syn::{FnArg, Item, ItemFn, ItemImpl, Pat, ReturnType};

use crate::attrs::{has_no_mangle, rustcall_attribute};
use crate::cfg::{body_has_cfg, predicate_string, CfgSet};
use crate::codegen::{returns_boxed_struct, symbol_stem};

use crate::manifest::{
    Arg, Attribute, Field, Function, Manifest, Method, Mode, ReturnKind, Struct,
};
use crate::model::{impl_has_julia, wrapped_methods, StructModel};
use crate::paths::{imports_of_use, locate, ImplHeader, Located, ScannedImport, Unresolved};
use crate::types::{
    callback_signature, extract_option_type, extract_result_type, field_has_accessors,
    generics_to_type_params, has_impl_trait, has_type_params, is_str_ref_type, is_string_type,
    return_type_to_string, type_to_string,
};

pub fn extract(source: &str, mode: Mode) -> Result<Manifest, ExtractError> {
    extract_with_cfg(source, mode, None)
}

/// Like [`extract`], but items disabled under `cfg` are dropped first
/// (see [`crate::cfg::CfgSet::prune_items`]).
pub fn extract_with_cfg(
    source: &str,
    mode: Mode,
    cfg: Option<&CfgSet>,
) -> Result<Manifest, ExtractError> {
    match mode {
        Mode::Inline => Ok(crate::expand::expand_with_cfg(source, cfg)?.manifest),
        Mode::Crate => extract_crate_with_cfg(source, cfg),
    }
}

pub fn fn_args(sig: &syn::Signature) -> Vec<Arg> {
    sig.inputs
        .iter()
        .filter_map(|a| match a {
            FnArg::Typed(pt) => Some(typed_arg(pt)),
            FnArg::Receiver(_) => None,
        })
        .collect()
}

/// The manifest entry of one typed parameter: its name, spelling and `abi`,
/// plus — for a callback (#296) — the parameter and return spellings of the
/// function pointer, so a consumer can build the callback without reading
/// Rust syntax (#264).
pub fn typed_arg(pt: &syn::PatType) -> Arg {
    let (callback_args, callback_return) = match callback_signature(&pt.ty) {
        Some((inputs, output)) => (
            inputs.iter().map(type_to_string).collect(),
            output.as_ref().map(type_to_string).unwrap_or_default(),
        ),
        None => (Vec::new(), String::new()),
    };
    Arg {
        name: match pt.pat.as_ref() {
            Pat::Ident(pi) => pi.ident.to_string(),
            other => quote::quote!(#other).to_string(),
        },
        rust_type: type_to_string(&pt.ty),
        abi: arg_abi(&pt.ty).to_string(),
        callback_args,
        callback_return,
        python_default: String::new(),
        python_kind: String::new(),
    }
}

/// The return kind of a wrapper that does no `Result`/`Option` lowering:
/// `Unit` for `()` or no return type, `Plain` otherwise. Struct method
/// wrappers are in that category (`generate_method_wrapper*` never wraps a
/// `Result`), so their manifest entry says so explicitly rather than leaving a
/// consumer to infer it from the type spelling (#275, #276).
pub fn plain_return_kind(output: &ReturnType) -> ReturnKind {
    match output {
        ReturnType::Default => ReturnKind::Unit,
        ReturnType::Type(..) => {
            if return_type_to_string(output) == "()" {
                ReturnKind::Unit
            } else {
                ReturnKind::Plain
            }
        }
    }
}

/// The manifest return shape of a `#[julia]` struct method (#268).
///
/// Before #268 a method wrapper never wrapped `Result` / `Option`, so this was
/// always `Plain` / `Unit` and the payload columns were empty. Both wrapper
/// flavours now lower them exactly like a free function, and this is the one
/// place that says so, shared by inline expansion and crate extraction so the
/// manifest cannot disagree with the code that was generated.
#[derive(Debug, Default, Clone)]
pub struct MethodReturnShape {
    pub kind: ReturnKind,
    pub ok_type: String,
    pub err_type: String,
    pub inner_type: String,
    pub ok_abi: String,
    pub err_abi: String,
    pub inner_abi: String,
}

/// `wrapped` is false for the methods of a **generic** struct: those wrappers
/// are registered for monomorphization (`inline_generic_wrappers`) and return
/// the type as written, so their manifest entry must keep saying `Plain`.
pub fn method_return_shape(
    struct_name: &syn::Ident,
    func: &syn::ImplItemFn,
    wrapped: bool,
) -> MethodReturnShape {
    let output = &func.sig.output;
    let mut shape = MethodReturnShape {
        kind: plain_return_kind(output),
        ..Default::default()
    };
    // A constructor (`new`, or anything returning `Self`) is boxed before the
    // `Result` lowering is ever consulted, exactly as in `method_spec`.
    if !wrapped || returns_boxed_struct(struct_name, func) {
        return shape;
    }
    let ReturnType::Type(_, ty) = output else {
        return shape;
    };
    if crate::codegen::method_wraps_result(ty) {
        if let Some(r) = extract_result_type(ty) {
            shape.kind = ReturnKind::Result;
            shape.ok_type = type_to_string(&r.ok_type);
            shape.err_type = type_to_string(&r.err_type);
            shape.ok_abi = crate::codegen::payload_abi(&r.ok_type).to_string();
            shape.err_abi = crate::codegen::payload_abi(&r.err_type).to_string();
        }
    } else if crate::codegen::method_wraps_option(ty) {
        if let Some(o) = extract_option_type(ty) {
            shape.kind = ReturnKind::Option;
            shape.inner_type = type_to_string(&o.inner_type);
            shape.inner_abi = crate::codegen::payload_abi(&o.inner_type).to_string();
        }
    }
    shape
}

/// The manifest `abi` column of an argument type (see [`Arg::abi`]).
pub fn arg_abi(ty: &syn::Type) -> &'static str {
    if is_string_type(ty) {
        "string"
    } else if is_str_ref_type(ty) {
        "str"
    } else if callback_signature(ty).is_some() {
        "callback"
    } else {
        ""
    }
}

fn item_fn_source(func: &ItemFn) -> String {
    let file = syn::File {
        shebang: None,
        attrs: Vec::new(),
        items: vec![Item::Fn(func.clone())],
    };
    prettyplease::unparse(&file)
}

/// Build the manifest entry of a free function.
///
/// `wrapped` says whether RustCall codegen (`transform_function`) is applied,
/// which decides the `Result`/`Option` return kinds and the exported flag.
///
/// `enclosing_cfg` is the `#[cfg]` of every enclosing inline module: the
/// entry's `cfg` / `cfg_features` describe when the item exists, not only
/// what it wrote on itself (#300 review).
pub fn function_entry(
    func: &ItemFn,
    attribute: Attribute,
    wrapped: bool,
    module_path: &[String],
    enclosing_cfg: &[syn::Attribute],
) -> Function {
    let effective_cfg = crate::cfg::effective_cfg_attrs(enclosing_cfg, &func.attrs);
    let is_generic = has_type_params(&func.sig.generics) || has_impl_trait(&func.sig);
    let return_type = return_type_to_string(&func.sig.output);
    let mut ok_type = String::new();
    let mut err_type = String::new();
    let mut inner_type = String::new();
    // Schema 6 (#268): a `String` / `&str` payload travels as the function's
    // own owned-string buffer, so the manifest states it rather than leaving
    // Julia to re-derive it from the payload spelling.
    let mut ok_abi = String::new();
    let mut err_abi = String::new();
    let mut inner_abi = String::new();
    let return_kind = match &func.sig.output {
        ReturnType::Default => ReturnKind::Unit,
        ReturnType::Type(_, ty) => {
            if let (true, Some(r)) = (wrapped, extract_result_type(ty)) {
                ok_type = type_to_string(&r.ok_type);
                err_type = type_to_string(&r.err_type);
                ok_abi = crate::codegen::payload_abi(&r.ok_type).to_string();
                err_abi = crate::codegen::payload_abi(&r.err_type).to_string();
                ReturnKind::Result
            } else if let (true, Some(o)) = (wrapped, extract_option_type(ty)) {
                inner_type = type_to_string(&o.inner_type);
                inner_abi = crate::codegen::payload_abi(&o.inner_type).to_string();
                ReturnKind::Option
            } else if return_type == "()" {
                ReturnKind::Unit
            } else {
                ReturnKind::Plain
            }
        }
    };
    let exported = if is_generic {
        false
    } else if wrapped {
        true
    } else {
        has_no_mangle(&func.attrs)
            && func
                .sig
                .abi
                .as_ref()
                .and_then(|abi| abi.name.as_ref())
                .map(|n| n.value() == "C")
                .unwrap_or(false)
    };
    let name = func.sig.ident.to_string();
    let ffi_name = crate::codegen::symbol_stem(module_path, &name);
    // `#[julia]` is additive: the item keeps its name and the exported entry
    // point is the wrapper next to it (#279), qualified by the module path
    // (#300). A plain `#[no_mangle] extern "C"` function is exported under
    // its own name.
    let symbol = match attribute {
        Attribute::Julia if !is_generic => crate::codegen::function_symbol(module_path, &name),
        _ => name.clone(),
    };
    // The wrapper only lowers strings when it is actually generated; a generic
    // item is wrapped per instantiation (see `specialize`), not here.
    let return_abi = if wrapped && !is_generic {
        crate::codegen::return_abi(&func.sig)
    } else {
        ""
    };
    Function {
        callable_path: Vec::new(),
        name,
        ffi_name,
        symbol,
        attribute,
        vis: crate::attrs::visibility_string(&func.vis),
        skip_reason: String::new(),
        python_name: String::new(),
        python_path: Vec::new(),
        exported,
        cfg: predicate_string(&effective_cfg),
        cfg_features: crate::cfg::predicate_features(&effective_cfg),
        is_generic,
        type_params: generics_to_type_params(&func.sig.generics),
        args: fn_args(&func.sig),
        return_type,
        return_kind,
        return_abi: return_abi.to_string(),
        ok_type,
        err_type,
        inner_type,
        ok_abi,
        err_abi,
        inner_abi,
        // Derived from the normative `return_abi` column since schema 4 (#276).
        has_owned_string_helper: return_abi == "string",
        has_borrowed_string_helper: return_abi == "str",
        source: if is_generic {
            let mut stripped = func.clone();
            crate::attrs::strip_rustcall_attrs(&mut stripped.attrs);
            item_fn_source(&stripped)
        } else {
            String::new()
        },
        body_has_cfg: body_has_cfg(&func.block),
        line: func.span().start().line,
        module_path: module_path.to_vec(),
    }
}

/// Why crate extraction refuses a file (#300).
///
/// A parse failure is one thing — the CLI's `--skip-unparsable` skips such a
/// file, since an `include!()` fragment is not a module — and a `#[julia]` item
/// the proc-macro would export under a symbol the manifest cannot describe is
/// another: that must fail the scan, not be skipped.
#[derive(Debug)]
pub enum ExtractError {
    /// The source is not a complete Rust module.
    Parse(syn::Error),
    /// The source is valid but describes something RustCall refuses; the
    /// message names the item and the fix.
    Unsupported(String),
}

impl std::fmt::Display for ExtractError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ExtractError::Parse(e) => write!(f, "{e}"),
            ExtractError::Unsupported(msg) => f.write_str(msg),
        }
    }
}

impl std::error::Error for ExtractError {}

impl From<syn::Error> for ExtractError {
    fn from(e: syn::Error) -> Self {
        ExtractError::Parse(e)
    }
}

/// Manifest for a crate source file (proc-macro semantics).
pub fn extract_crate(source: &str) -> Result<Manifest, ExtractError> {
    extract_crate_with_cfg(source, None)
}

pub fn extract_crate_with_cfg(
    source: &str,
    cfg: Option<&CfgSet>,
) -> Result<Manifest, ExtractError> {
    extract_crate_with_cfg_scan(source, cfg, true)
}

/// Like [`extract_crate_with_cfg`], with the PyO3 scan (#275) switchable.
///
/// The scan is on by default: one file, treated as its own root. A caller that
/// can read files instead walks the crate's module tree with [`TreeScan`] —
/// which records the real `module_path` and the reachability of every
/// enclosing `mod` — and then passes `false` here so the per-file pass does
/// not report the same items a second time under the wrong path.
pub fn extract_crate_with_cfg_scan(
    source: &str,
    cfg: Option<&CfgSet>,
    pyo3_scan: bool,
) -> Result<Manifest, ExtractError> {
    let mut file = syn::parse_file(source)?;
    if let Some(set) = cfg {
        crate::cfg::prune_file_or_error(set, &mut file)?;
    }
    let mut manifest = Manifest::new(Mode::Crate);
    let mut scan = CrateScan::new();
    // A single source with no file behind it: an `include!` in it names a path
    // this layer cannot resolve, so the fragments it reports are dropped.
    scan.file(
        &file.items,
        &FilePosition::module(&[], true, &[]),
        &mut manifest,
        "",
    )?;
    scan.finish(&mut manifest)?;
    // Items that carry only PyO3 attributes (#275). Reported with a PyO3
    // origin, `exported = false` and the symbol a Phase-2 wrapper crate will
    // emit; an item that also carries `#[julia]` is owned by `#[julia]` and is
    // skipped by the scan (see `crate::pyo3`).
    if pyo3_scan {
        crate::pyo3::extract_pyo3_items(&file.items, &mut manifest);
    }
    Ok(manifest)
}

/// One `include!("...")` found while scanning a file (#315, #343).
///
/// `include!` is not a module: the fragment's items are compiled into the
/// module that includes them, so it is scanned at the **including item's**
/// position — the same module path, the same `#[julia] mod` chain, the same
/// `#[cfg]` — and only the file it is read from differs.
///
/// Following it needs the filesystem, so the scan reports it the way it
/// reports an out-of-line `mod` and the caller resolves it: `path` is relative
/// to the directory of the file the `include!` was written in. An out-of-line
/// `mod` **inside** the fragment then resolves against the *fragment's* own
/// directory, which is rustc's rule and the reason a fragment is scanned as a
/// file of its own rather than spliced into the including one: `include!(
/// "frag/api.rs")` in `src/lib.rs` with `mod nested;` inside `api.rs` wants
/// `src/frag/nested.rs`, and it wants that whether or not the `include!` sits
/// in an inline module.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PendingInclude {
    /// The literal argument, relative to the including **file's** directory.
    pub path: String,
    /// The position the fragment's items occupy.
    pub position: FilePosition,
}

/// Where a file sits when it is scanned.
///
/// A file of the module tree is scanned at its own module path with an empty
/// symbol path and `marked` true: its top level is expanded by the item-level
/// proc-macro, which sees no module ([`FilePosition::module`]). An `include!`d
/// fragment instead inherits the position of the `include!` item
/// ([`PendingInclude::position`]).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FilePosition {
    /// Where the file sits in the module tree; empty for the crate root.
    pub module_path: Vec<String>,
    /// Whether every `mod` on the way here is `pub` — what decides whether a
    /// PyO3 item is reachable from outside the crate.
    pub reachable: bool,
    /// The `#[cfg]` of every `mod` declaration on the way, which every item in
    /// the file inherits (#300 review).
    pub enclosing_cfg: Vec<syn::Attribute>,
    /// The chain of `#[julia]`-marked inline modules the file's items are
    /// expanded under — the path the proc-macro folds into their symbols.
    /// Empty for a file of the module tree.
    pub symbol_path: Vec<String>,
    /// Whether this level is a `#[julia]`-marked one; a file's top level is.
    pub marked: bool,
}

impl FilePosition {
    /// The position of a file of the module tree.
    pub fn module(
        module_path: &[String],
        reachable: bool,
        enclosing_cfg: &[syn::Attribute],
    ) -> Self {
        FilePosition {
            module_path: module_path.to_vec(),
            reachable,
            enclosing_cfg: enclosing_cfg.to_vec(),
            symbol_path: Vec::new(),
            marked: true,
        }
    }
}

/// What a scanned file pulls in and only a caller that can read files can
/// follow: its out-of-line `mod` declarations and its `include!` fragments.
///
/// Both are followed the same way — one more [`TreeScan::file`] call — so both
/// scans see every file exactly once, whichever of the two brought it in
/// (#343: before this the `#[julia]` walk followed `include!` by itself, so
/// the PyO3 scan never saw a fragment and a `mod` declared inside one was
/// never resolved at all).
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct PullIns {
    pub modules: Vec<crate::pyo3::PendingModule>,
    pub includes: Vec<PendingInclude>,
}

/// Both crate-wide scans of one crate — `#[julia]` items (#315) and PyO3 items
/// (#275) — fed one file of the module tree at a time.
///
/// A struct and its impl blocks may live in different files, so the structs
/// are only written to the manifest by [`TreeScan::finish`], once every file
/// has been seen. The caller — `rustcall-extract` — owns the walk: it resolves
/// each returned [`PullIns`] entry to a file and calls [`TreeScan::file`]
/// again; only it can touch the filesystem. Without a crate root every file is
/// fed as its own root (an empty `module_path`).
#[derive(Debug, Default)]
pub struct TreeScan {
    julia: CrateScan,
    pyo3: crate::pyo3::Pyo3Scan,
}

impl TreeScan {
    pub fn new() -> Self {
        TreeScan::default()
    }

    /// Scan with the target crate's Rust edition. This matters for a leading
    /// `::` path, which changed from crate-rooted to extern-rooted in 2018.
    pub fn with_edition(edition: &str) -> Self {
        Self {
            julia: CrateScan::default(),
            pyo3: crate::pyo3::Pyo3Scan::with_edition(edition),
        }
    }

    /// Scan generated includes using the target's Cargo build environment.
    /// With this context, unresolved include expressions are errors instead
    /// of silently omitting an API generated by the build script.
    pub fn with_include_environment(environment: crate::include_paths::IncludeEnvironment) -> Self {
        Self {
            julia: CrateScan {
                include_environment: Some(environment),
                ..CrateScan::default()
            },
            pyo3: crate::pyo3::Pyo3Scan::default(),
        }
    }

    pub fn with_include_environment_and_edition(
        environment: crate::include_paths::IncludeEnvironment,
        edition: &str,
    ) -> Self {
        Self {
            julia: CrateScan {
                include_environment: Some(environment),
                ..CrateScan::default()
            },
            pyo3: crate::pyo3::Pyo3Scan::with_edition(edition),
        }
    }

    /// Scan one file at `position` — a file of the module tree
    /// ([`FilePosition::module`]) or an `include!`d fragment — with `file`
    /// labelling it in diagnostics. `#[julia]` and PyO3 functions go straight
    /// into `manifest`; what the file pulls in is returned for the caller to
    /// follow.
    pub fn file(
        &mut self,
        source: &str,
        cfg: Option<&CfgSet>,
        position: &FilePosition,
        manifest: &mut Manifest,
        file: &str,
    ) -> Result<PullIns, ExtractError> {
        let mut parsed = syn::parse_file(source)?;
        if let Some(set) = cfg {
            crate::cfg::prune_file_or_error(set, &mut parsed)?;
        }
        let includes = self.julia.file(&parsed.items, position, manifest, file)?;
        let modules = self.pyo3.file(
            &parsed.items,
            &position.module_path,
            position.reachable,
            &position.enclosing_cfg,
            manifest,
        );
        Ok(PullIns { modules, includes })
    }

    /// Attach every impl block to its struct and write the structs of both
    /// scans to `manifest`.
    pub fn finish(self, manifest: &mut Manifest) -> Result<(), ExtractError> {
        self.julia.finish(manifest)?;
        self.pyo3.finish(manifest);
        Ok(())
    }
}

/// The error for a `#[julia]` item inside an inline module that is not itself
/// marked `#[julia]` (#300): the proc-macro would export it under the
/// crate-root symbol, and the manifest cannot describe that honestly.
fn unmarked_module_error(kind: &str, name: &str, full_path: &[String]) -> ExtractError {
    let module = full_path.last().map(String::as_str).unwrap_or("");
    ExtractError::Unsupported(format!(
        "#[julia] {kind} `{name}` sits in the inline module `{}`, which is not marked \
         `#[julia]`. The proc-macro cannot see the module an item is in, so it would \
         export `{name}` under the crate-root symbol; mark the module — `#[julia] pub mod \
         {module} {{ ... }}` — so the items inside it get module-qualified symbols (#300).",
        full_path.join("::")
    ))
}

/// `crate::a::b` for a module path, `crate` for the root.
fn crate_path(path: &[String]) -> String {
    if path.is_empty() {
        "crate".to_string()
    } else {
        format!("crate::{}", path.join("::"))
    }
}

/// Where an item is, for a diagnostic: `(line 3 in src/ops.rs)`, or just the
/// line for an in-memory source.
/// The error for a `#[julia] impl` whose target resolves to a struct that
/// carries no `#[julia]` (#315 review). The proc-macro wrapped the methods
/// with *that* type as the receiver, so attaching them to a same-named
/// annotated struct elsewhere would describe a wrapper that dereferences a
/// pointer to the wrong type.
fn plain_target_error(imp: &ScannedImpl, target: &Candidate) -> ExtractError {
    let header = imp.header.display();
    let where_ = location(imp.line, &imp.file);
    let name = &target.name;
    let module = if target.module_path.is_empty() {
        "the crate root".to_string()
    } else {
        format!("module `{}`", target.module_path.join("::"))
    };
    let declared = if target.file.is_empty() {
        String::new()
    } else {
        format!(" (in {})", target.file)
    };
    ExtractError::Unsupported(format!(
        "`{header}` {where_} names `{name}` in {module}{declared}, which is not a \
         `#[julia]` struct. Mark that struct with `#[julia]`, or point the block at the \
         annotated one with an explicit path (`impl crate::path::to::{name}`)."
    ))
}

fn location(line: usize, file: &str) -> String {
    if file.is_empty() {
        format!("(line {line})")
    } else {
        format!("(line {line} in {file})")
    }
}

/// Crate-wide state of the `#[julia]` scan (#315).
///
/// A `#[julia] struct` and its `#[julia] impl` blocks need not live together:
/// `impl C` is legal in any module that has `C` in scope, and in a multi-file
/// crate the two are routinely in different files (`struct Gauge` in `lib.rs`,
/// `impl crate::Gauge` in `ops.rs`). Matching them per file, or per module
/// level, silently dropped the methods of every such struct — the proc-macro
/// had emitted the wrappers, the manifest did not list them, and the Julia
/// module had no method. So the structs and the impl blocks of the whole tree
/// are collected first and married in [`CrateScan::finish`], the block's
/// header resolved through the same resolver the PyO3 scan uses
/// (`crate::paths`): `impl crate::Gauge`, `impl super::Gauge`, `impl Gauge`
/// next to a `use crate::Gauge;`, or a bare `impl Gauge` when the crate has
/// one.
///
/// Two paths are tracked for every item. Its **module path** is where it really
/// is — every module on the way, file (`mod ops;`) and inline — and is what
/// headers are resolved against. Its **symbol path** is the chain of `#[julia]`
/// inline modules the proc-macro folds into its symbols (#300); file modules
/// and unmarked inline modules are transparent to it, and an unmarked module
/// cuts the chain, because whatever is inside it is expanded by the item-level
/// macro, which sees no module at all. The manifest records the symbol path as
/// `module_path`, since that is what the symbols and the Julia layout follow.
///
/// Nothing is dropped silently: a block whose header names no `#[julia]`
/// struct, or an ambiguous one, fails the scan with the unresolved path, and so
/// does a block the proc-macro would give symbols other than the struct's own
/// (`impl_target_module_path` versus the struct's symbol path) — the macro
/// cannot see where the struct is declared, so the header has to spell it.
#[derive(Debug, Default)]
pub struct CrateScan {
    include_environment: Option<crate::include_paths::IncludeEnvironment>,
    structs: Vec<ScannedStruct>,
    /// Every struct the crate declares **without** `#[julia]`, by name and
    /// module. Rust resolves an `impl` header by scope, not by attribute, so a
    /// plain `struct C` in the block's own module is its target even when a
    /// `#[julia] struct C` exists elsewhere; without these the resolver would
    /// fall back to the annotated one and the manifest would name a wrapper
    /// whose receiver is the *other* type (#315 review).
    plain_structs: Vec<PlainStruct>,
    impls: Vec<ScannedImpl>,
    imports: Vec<ScannedImport>,
    /// Every name the generated code defines so far and the item that claims
    /// it, so a second claimant is reported with both locations (#300). A
    /// claim carries its Rust namespace and the scope it has to be unique in,
    /// because an exported symbol is crate-global while a private item only
    /// has to be unique in its own module (#338).
    claimed: Vec<(crate::claims::Claim, String)>,
}

#[derive(Debug)]
struct ScannedStruct {
    model: StructModel,
    name: String,
    module_path: Vec<String>,
    symbol_path: Vec<String>,
    /// The `#[cfg]` of every module enclosing the struct (#300 review).
    cfg: Vec<syn::Attribute>,
    file: String,
}

impl Located for ScannedStruct {
    fn name(&self) -> &str {
        &self.name
    }

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

/// A struct with no `#[julia]`: a resolution candidate, never a target.
#[derive(Debug)]
struct PlainStruct {
    name: String,
    module_path: Vec<String>,
    file: String,
}

/// A struct an `impl` header may name, annotated or not: `julia` is its index
/// in [`CrateScan::structs`] when it carries `#[julia]`, and `None` when it is
/// a [`PlainStruct`] (#315 review).
#[derive(Debug)]
struct Candidate {
    name: String,
    module_path: Vec<String>,
    julia: Option<usize>,
    file: String,
}

impl Located for Candidate {
    fn name(&self) -> &str {
        &self.name
    }

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

#[derive(Debug)]
struct ScannedImpl {
    item: ItemImpl,
    header: ImplHeader,
    symbol_path: Vec<String>,
    /// The `#[cfg]` of the block itself and of every module enclosing it: the
    /// block may sit in a gated module far from its struct, and its methods
    /// exist only under that predicate (#300 review).
    cfg: Vec<syn::Attribute>,
    /// The `#[cfg]` of the enclosing modules alone — the block's own
    /// predicate left out. This is the provenance a block shares with the
    /// struct copy it was written beside, and what tells cfg-exclusive copies
    /// of one fragment apart (#357 review).
    enclosing_cfg: Vec<syn::Attribute>,
    line: usize,
    file: String,
}

impl CrateScan {
    pub fn new() -> Self {
        CrateScan::default()
    }

    /// Scan one file at `position`, with `file` labelling it in diagnostics.
    ///
    /// `#[julia]` functions go straight into `manifest`; structs and impl
    /// blocks are held until [`CrateScan::finish`]. The `include!` fragments
    /// found are returned for the caller to read and feed back — a file's
    /// items are expanded by the item-level macro, which sees no module, so a
    /// file of the module tree starts with an empty symbol path, while a
    /// fragment keeps the one its `include!` sits under.
    pub fn file(
        &mut self,
        items: &[Item],
        position: &FilePosition,
        manifest: &mut Manifest,
        file: &str,
    ) -> Result<Vec<PendingInclude>, ExtractError> {
        let mut path = position.module_path.clone();
        let mut includes = Vec::new();
        self.level(
            items,
            &mut path,
            &position.symbol_path,
            &position.enclosing_cfg,
            position.marked,
            position.reachable,
            manifest,
            file,
            &mut includes,
        )?;
        Ok(includes)
    }

    /// One level of items; inline modules are visited recursively.
    ///
    /// `symbol_path` is the chain of `#[julia]`-marked inline modules leading
    /// here — the path the proc-macro folds into the symbols — and `marked`
    /// says whether *this* level is a marked one (a file's top level counts as
    /// marked): a `#[julia]` function or struct at an unmarked level is
    /// refused, see [`unmarked_module_error`]. An unmarked module cuts the
    /// chain: `codegen::transform_module` leaves it as written, so a marked
    /// module below it is expanded by the item-level macro and starts a chain
    /// of its own. `enclosing_cfg` is the `#[cfg]` of every enclosing module,
    /// which every entry below inherits (#300 review). `reachable` says
    /// whether every `mod` on the way here is `pub`; it means nothing to the
    /// `#[julia]` items themselves and is carried only so that an `include!`
    /// found here reports the position the PyO3 scan of the fragment needs.
    #[allow(clippy::too_many_arguments)]
    fn level(
        &mut self,
        items: &[Item],
        module_path: &mut Vec<String>,
        symbol_path: &[String],
        enclosing_cfg: &[syn::Attribute],
        marked: bool,
        reachable: bool,
        manifest: &mut Manifest,
        file: &str,
        includes: &mut Vec<PendingInclude>,
    ) -> Result<(), ExtractError> {
        for item in items {
            match item {
                Item::Fn(f) => {
                    let attribute = rustcall_attribute(&f.attrs);
                    if attribute != Attribute::None && !marked {
                        return Err(unmarked_module_error(
                            "function",
                            &f.sig.ident.to_string(),
                            module_path,
                        ));
                    }
                    if attribute == Attribute::Julia {
                        let entry = function_entry(f, attribute, true, symbol_path, enclosing_cfg);
                        for (claim, owner) in entry.claims() {
                            self.claim(claim, owner, file, module_path)?;
                        }
                        manifest.functions.push(entry);
                    }
                }
                // An `enum` or a `union` is a type an `impl` header resolves to
                // as readily as a struct, and neither can carry `#[julia]`:
                // recording them keeps a local one from being passed over for a
                // same-named annotated struct elsewhere (#315 review).
                Item::Enum(e) => {
                    self.plain_structs.push(PlainStruct {
                        name: e.ident.to_string(),
                        module_path: module_path.clone(),
                        file: file.to_string(),
                    });
                }
                Item::Union(u) => {
                    self.plain_structs.push(PlainStruct {
                        name: u.ident.to_string(),
                        module_path: module_path.clone(),
                        file: file.to_string(),
                    });
                }
                // `type Gauge = …;` names a type an inherent impl can be
                // written through, so it shadows a same-named annotated struct
                // in another module exactly as a local declaration does.
                Item::Type(t) => {
                    self.plain_structs.push(PlainStruct {
                        name: t.ident.to_string(),
                        module_path: module_path.clone(),
                        file: file.to_string(),
                    });
                }
                Item::Struct(s) => {
                    let Some(model) = StructModel::of(s, Mode::Crate) else {
                        // Not a `#[julia]` struct, but still a name an `impl`
                        // header can resolve to (#315 review).
                        self.plain_structs.push(PlainStruct {
                            name: s.ident.to_string(),
                            module_path: module_path.clone(),
                            file: file.to_string(),
                        });
                        continue;
                    };
                    if !marked {
                        return Err(unmarked_module_error("struct", &model.name(), module_path));
                    }
                    self.structs.push(ScannedStruct {
                        name: model.name(),
                        model,
                        module_path: module_path.clone(),
                        symbol_path: symbol_path.to_vec(),
                        cfg: enclosing_cfg.to_vec(),
                        file: file.to_string(),
                    });
                }
                Item::Impl(imp) => {
                    // A block without `#[julia]` wraps nothing in crate mode;
                    // one with it is attached in `finish`, wherever its struct
                    // is. An impl sits in an unmarked module legitimately: its
                    // symbols follow the struct, not the module.
                    if !impl_has_julia(imp) {
                        continue;
                    }
                    let Some(header) = ImplHeader::of(imp, module_path) else {
                        continue;
                    };
                    self.impls.push(ScannedImpl {
                        item: imp.clone(),
                        header,
                        symbol_path: symbol_path.to_vec(),
                        cfg: crate::cfg::effective_cfg_attrs(enclosing_cfg, &imp.attrs),
                        enclosing_cfg: enclosing_cfg.to_vec(),
                        line: imp.span().start().line,
                        file: file.to_string(),
                    });
                }
                Item::Use(u) => {
                    self.imports.extend(imports_of_use(u, module_path));
                }
                Item::Macro(m) if m.mac.path.is_ident("include") => {
                    // `include!("api.rs")` compiles that file's items into
                    // *this* module — no `mod` declaration reaches it, so the
                    // tree walk has to follow it or the items it exports
                    // disappear from the manifest while the proc-macro still
                    // wraps them (#315 review). Generated paths are resolved
                    // against explicit target build context when supplied.
                    // Reading it is the caller's job (#343), which is
                    // what lets the PyO3 scan see the fragment too and an
                    // out-of-line `mod` inside it be resolved against the
                    // fragment's own directory.
                    let path = match &self.include_environment {
                        Some(environment) => environment
                            .resolve(m.mac.tokens.clone())
                            .map_err(ExtractError::Unsupported)?,
                        None => {
                            let Ok(literal) = m.mac.parse_body::<syn::LitStr>() else {
                                continue;
                            };
                            literal.value()
                        }
                    };
                    includes.push(PendingInclude {
                        path,
                        position: FilePosition {
                            module_path: module_path.clone(),
                            reachable,
                            // The `include!` item carries `#[cfg]` of its own
                            // (`#[cfg(feature = "python")] include!("api.rs")`),
                            // and the fragment's items exist only under it as
                            // much as under the enclosing modules'. Dropping it
                            // left a lenient scan describing them as
                            // unconditional, so a generated wrapper would call
                            // items the dependency's feature set may not have
                            // (#343 review).
                            enclosing_cfg: crate::cfg::effective_cfg_attrs(enclosing_cfg, &m.attrs),
                            symbol_path: symbol_path.to_vec(),
                            marked,
                        },
                    });
                }
                Item::Mod(m) => {
                    let inner_reachable = reachable && matches!(m.vis, syn::Visibility::Public(_));
                    let Some((_, inner)) = &m.content else {
                        // `mod name;` lives in another file; the caller follows
                        // it (see `TreeScan`).
                        continue;
                    };
                    module_path.push(m.ident.to_string());
                    let cfg = crate::cfg::effective_cfg_attrs(enclosing_cfg, &m.attrs);
                    let result = if crate::codegen::is_marked_module(m) {
                        let mut inner_symbol = symbol_path.to_vec();
                        inner_symbol.push(m.ident.to_string());
                        self.level(
                            inner,
                            module_path,
                            &inner_symbol,
                            &cfg,
                            true,
                            inner_reachable,
                            manifest,
                            file,
                            includes,
                        )
                    } else {
                        self.level(
                            inner,
                            module_path,
                            &[],
                            &cfg,
                            false,
                            inner_reachable,
                            manifest,
                            file,
                            includes,
                        )
                    };
                    module_path.pop();
                    result?;
                }
                _ => {}
            }
        }
        Ok(())
    }

    /// Record `symbol` as claimed by `owner`, failing on the second claimant
    /// (#300).
    ///
    /// The symbol scheme keeps items of different modules apart, so a
    /// duplicate here is either two file modules — transparent to the scheme
    /// — defining the same `#[julia]` item, or a crate-root name that spells a
    /// qualified one. The `cdylib` could not export both, and a wrong binding
    /// is worse than no binding, so the scan fails closed and names the fix.
    fn claim(
        &mut self,
        claim: crate::claims::Claim,
        owner: String,
        file: &str,
        module: &[String],
    ) -> Result<(), ExtractError> {
        // The manifest's module path qualifies symbols; it is empty for every
        // file of the module tree, which is not where the wrapper's private
        // items land (#338 review).
        let claim = claim.in_real_module(module);
        let here = if file.is_empty() {
            owner
        } else {
            format!("{owner} in {file}")
        };
        let symbol = claim.name.clone();
        let symbol = &symbol;
        if let Some((_, first)) = self.claimed.iter().find(|(c, _)| c.clashes_with(&claim)) {
            let kind = crate::claims::clash_kind(&claim);
            let detail = if claim.exported {
                "Two #[julia] items of one crate export the same symbol; only inline modules \
                 marked `#[julia]` (`#[julia] pub mod name { ... }`) qualify a symbol by \
                 their name, while file modules (`mod name;`) do not. Wrap one of the items in \
                 a `#[julia]` module block or rename it (#300)."
                    .to_string()
            } else {
                format!(
                    "This name is not exported and not one you wrote: it is {}. Two of them in \
                     one crate are a duplicate definition rather than a duplicate export, and \
                     rustc would report it inside generated code. Rename one of the items \
                     (#338).",
                    crate::claims::internal_origin(&claim)
                )
            };
            return Err(ExtractError::Unsupported(format!(
                "duplicate {kind} `{symbol}`: claimed by {first} and by {here}. {detail}"
            )));
        }
        self.claimed.push((claim, here));
        Ok(())
    }

    /// Attach every `#[julia] impl` block to its struct and write the structs
    /// to `manifest`, in the order the structs were seen (the CLI sorts a
    /// multi-file manifest afterwards).
    ///
    /// Blocks are visited by (module path, line) so the result does not
    /// depend on the order the caller happened to visit files in.
    pub fn finish(mut self, manifest: &mut Manifest) -> Result<(), ExtractError> {
        let candidates: Vec<Candidate> = self
            .structs
            .iter()
            .enumerate()
            .map(|(i, s)| Candidate {
                name: s.name.clone(),
                module_path: s.module_path.clone(),
                julia: Some(i),
                file: s.file.clone(),
            })
            .chain(self.plain_structs.iter().map(|p| Candidate {
                name: p.name.clone(),
                module_path: p.module_path.clone(),
                julia: None,
                file: p.file.clone(),
            }))
            .collect();
        let mut impls = std::mem::take(&mut self.impls);
        impls.sort_by(|a, b| {
            a.header
                .module_path
                .cmp(&b.header.module_path)
                .then(a.line.cmp(&b.line))
                .then(a.file.cmp(&b.file))
        });

        for imp in &impls {
            // A block with no `#[julia]` method makes the proc-macro emit
            // nothing, whatever it names.
            if wrapped_methods(&imp.item, Mode::Crate, &imp.cfg).is_empty() {
                continue;
            }
            // Resolution follows Rust's own rules, so the plain structs are
            // candidates too; a header that lands on one names a type the
            // proc-macro wrapped as its receiver and RustCall cannot describe
            // (#315 review).
            let index = match locate(&candidates, &imp.header, &self.imports) {
                Ok(index) => match candidates[index].julia {
                    Some(julia) => julia,
                    None => return Err(plain_target_error(imp, &candidates[index])),
                },
                Err(why) => return Err(self.unresolved_impl(imp, why)),
            };
            // Two `#[julia]` structs of one name at one module path are cfg
            // variants of each other — a fragment included under
            // `#[cfg(feature = "x")]` and `#[cfg(not(feature = "x"))]`, both
            // scanned since #357. `locate` sees one name and lands on the
            // first; the block belongs to the variant under its own predicate,
            // or the other one ends up without the method (#357 review).
            for index in self.cfg_variants_for(index, &imp.enclosing_cfg) {
                self.check_symbol_path(imp, index)?;
                self.structs[index].model.attach_impl(
                    &imp.item,
                    Mode::Crate,
                    &imp.cfg,
                    Some(&imp.header.module_path),
                );
            }
        }

        for scanned in std::mem::take(&mut self.structs) {
            let entry = crate_struct_entry(&scanned.model, &scanned.symbol_path, &scanned.cfg);
            for (claim, owner) in entry.claims() {
                self.claim(claim, owner, &scanned.file, &scanned.module_path)?;
            }
            manifest.structs.push(entry);
        }
        Ok(())
    }

    /// The `#[julia]` structs at `index` — or the same-named struct at the same
    /// module path whose enclosing `#[cfg]` is `cfg` when there is one:
    /// cfg-exclusive copies of one declaration are distinct structs to the
    /// scan, and an impl block written beside one copy attaches to that copy.
    /// `cfg` is the block's *enclosing* predicate, not its effective one — a
    /// block that adds `#[cfg(feature = "y")]` of its own still sits beside
    /// exactly one copy, and its own predicate is carried by its methods.
    /// A block written *outside* every copy — at the crate root, or in a
    /// module gated on something else — applies to whichever copy rustc
    /// compiles, so it attaches to every copy its predicate can coexist with.
    fn cfg_variants_for(&self, index: usize, cfg: &[syn::Attribute]) -> Vec<usize> {
        let want = predicate_string(cfg);
        let here = &self.structs[index];
        let same = |s: &ScannedStruct| s.name == here.name && s.module_path == here.module_path;
        if predicate_string(&here.cfg) == want {
            return vec![index];
        }
        if let Some(exact) = self
            .structs
            .iter()
            .position(|s| same(s) && predicate_string(&s.cfg) == want)
        {
            return vec![exact];
        }
        // No copy sits under exactly this predicate: the block was written
        // outside them all — at the crate root, or in a module gated on
        // something else (`#[cfg(feature = "y")] mod ops { impl
        // crate::api::Gauge }`). rustc applies it to whichever copy it
        // compiles, so it attaches to every copy whose predicate can hold
        // together with the block's; only a copy *provably* exclusive with it
        // is left out (#357 review).
        let overlapping: Vec<usize> = self
            .structs
            .iter()
            .enumerate()
            .filter(|(_, s)| {
                same(s) && !crate::pyo3::cfg_exclusive(&predicate_string(&s.cfg), &want)
            })
            .map(|(i, _)| i)
            .collect();
        if !overlapping.is_empty() {
            return overlapping;
        }
        vec![index]
    }

    fn unresolved_impl(&self, imp: &ScannedImpl, why: Unresolved) -> ExtractError {
        let header = imp.header.display();
        let where_ = location(imp.line, &imp.file);
        let name = &imp.header.target;
        ExtractError::Unsupported(match why {
            Unresolved::NotFound => {
                let looked = if imp.header.qualifier.is_uninformative() {
                    "anywhere in the crate".to_string()
                } else {
                    let places: Vec<String> = imp
                        .header
                        .qualifier
                        .candidates(&imp.header.module_path)
                        .iter()
                        .map(|p| format!("`{}`", crate_path(p)))
                        .collect();
                    if places.is_empty() {
                        "where the header points (it walks above the crate root)".to_string()
                    } else {
                        format!("at {}", places.join(" or "))
                    }
                };
                format!(
                    "#[julia] `{header}` {where_} names no #[julia] struct: no `struct {name}` \
                     marked `#[julia]` is declared {looked}. A `#[julia] impl` block wraps the \
                     methods of a `#[julia]` struct, so mark the struct, or point the header at \
                     one that is (#315)."
                )
            }
            Unresolved::Ambiguous(paths) => {
                let places: Vec<String> = paths
                    .iter()
                    .map(|p| format!("`{}`", crate_path(p)))
                    .collect();
                let first = paths.first().map(|p| crate_path(p)).unwrap_or_default();
                format!(
                    "#[julia] `{header}` {where_} is ambiguous: `#[julia] struct {name}` is \
                     declared in {}, and neither the header nor a `use` in `{}` picks one. Write \
                     the struct's path in the header (`impl {first}::{name}`) (#315).",
                    places.join(" and "),
                    crate_path(&imp.header.module_path)
                )
            }
        })
    }

    /// Refuse a block the proc-macro would give other symbols than the struct
    /// it names has (#315).
    ///
    /// The macro derives a method's symbol from the header and the `#[julia]`
    /// modules around the block ([`crate::codegen::impl_target_module_path`]);
    /// it cannot see where the struct is declared. When that path is not the
    /// struct's own symbol path the wrappers would be exported under one stem
    /// and the struct's `free` / accessors under another, and Julia — which
    /// derives every method symbol from the struct's FFI name — would look for
    /// symbols that do not exist. The manifest cannot describe that honestly,
    /// so the scan fails and names the header that would.
    fn check_symbol_path(&self, imp: &ScannedImpl, index: usize) -> Result<(), ExtractError> {
        let scanned = &self.structs[index];
        let name = scanned.model.name();
        let macro_path = imp.header.qualifier.macro_target_path(&imp.symbol_path);
        // The macro reads the header's own last identifier, which a renamed
        // import makes something else entirely (`use crate::Gauge as Meter;
        // impl Meter` exports `rustcall_Meter_*`), so the stem is derived from
        // what the macro sees, not from the struct the header resolves to
        // (#315 review).
        let macro_stem = symbol_stem(&macro_path, &imp.header.target.to_string());
        let struct_stem = symbol_stem(&scanned.symbol_path, &name);
        if macro_stem == struct_stem {
            return Ok(());
        }
        let header = imp.header.display();
        let where_ = location(imp.line, &imp.file);
        let block_is = if imp.symbol_path.is_empty() {
            "outside any `#[julia]` module".to_string()
        } else {
            format!(
                "inside the `#[julia]` module `{}`",
                imp.symbol_path.join("::")
            )
        };
        let real = crate_path(&scanned.module_path);
        let fix = if scanned.module_path == scanned.symbol_path {
            format!("write the header as `impl {real}::{name}`")
        } else if scanned.symbol_path.is_empty() {
            format!(
                "bring the struct into scope (`use {real}::{name};`) and write `impl {name}` \
                 outside any `#[julia]` module — the modules in `{real}` are file modules or \
                 unmarked ones, transparent to the symbol scheme (#300), so a header naming \
                 them would qualify the symbols by them"
            )
        } else {
            format!(
                "bring the struct into scope (`use {real}::{name};`) and write `impl {name}` \
                 inside `#[julia] mod {}` (module path `{}`), or move the block next to the \
                 struct",
                scanned.symbol_path.last().map(String::as_str).unwrap_or(""),
                scanned.symbol_path.join("::")
            )
        };
        Err(ExtractError::Unsupported(format!(
            "#[julia] `{header}` {where_}, {block_is}, would export its methods as \
             `rustcall_{macro_stem}_<method>`, but the struct it names, `{real}::{name}`, has \
             the FFI name `{struct_stem}` (`{struct_stem}_free`, \
             `rustcall_{struct_stem}_<method>`). The proc-macro derives a method's symbol from \
             the impl header and the `#[julia]` modules around the block — it cannot see \
             where the struct is declared — so the header has to spell the struct's path: \
             {fix} (#315)."
        )))
    }
}

fn crate_struct_entry(
    model: &StructModel,
    module_path: &[String],
    enclosing_cfg: &[syn::Attribute],
) -> Struct {
    let struct_name = &model.item.ident;
    let effective_cfg = crate::cfg::effective_cfg_attrs(enclosing_cfg, &model.item.attrs);
    let stem = crate::codegen::symbol_stem(module_path, &struct_name.to_string());
    let fields = model
        .named_fields()
        .iter()
        .map(|(name, ty)| {
            let ffi_compatible = field_has_accessors(ty);
            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,
                getter: if ffi_compatible {
                    crate::codegen::field_getter_symbol(&stem, &name.to_string())
                } else {
                    String::new()
                },
                setter: if ffi_compatible {
                    crate::codegen::field_setter_symbol(&stem, &name.to_string())
                } else {
                    String::new()
                },
                python_name: String::new(),
                vis: String::new(),
                cfg: String::new(),
                pyo3_get: false,
                pyo3_set: false,
                precollision: None,
            }
        })
        .collect();
    // The crate flavour wraps every reported method, so the `Result` / `Option`
    // lowering applies to all of them (#268).
    let shapes: Vec<MethodReturnShape> = model
        .methods
        .iter()
        .map(|m| method_return_shape(struct_name, &m.func, true))
        .collect();
    let methods = model
        .methods
        .iter()
        .enumerate()
        .map(|(i, m)| Method {
            name: m.name(),
            symbol: crate::codegen::method_symbol_of(&stem, &m.name()),
            is_static: m.is_static,
            is_mutable: m.is_mutable,
            is_constructor: returns_boxed_struct(struct_name, &m.func),
            is_classmethod: false,
            vis: crate::attrs::visibility_string(&m.func.vis),
            skip_reason: String::new(),
            python_name: String::new(),
            accessor: String::new(),
            attribute: m.attribute,
            // The proc-macro emits every method's wrapper at its impl block,
            // with string buffers of its own (`method_wrapper_at_impl_site`),
            // wherever the block sits.
            string_owner: crate::codegen::method_string_owner(&stem, &m.name()),
            return_kind: shapes[i].kind,
            ok_type: shapes[i].ok_type.clone(),
            err_type: shapes[i].err_type.clone(),
            inner_type: shapes[i].inner_type.clone(),
            ok_abi: shapes[i].ok_abi.clone(),
            err_abi: shapes[i].err_abi.clone(),
            inner_abi: shapes[i].inner_abi.clone(),
            returns_boxed_struct: returns_boxed_struct(struct_name, &m.func),
            // 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,
            )),
            args: fn_args(&m.func.sig),
            return_type: return_type_to_string(&m.func.sig.output),
            // Crate method wrappers (`generate_method_wrapper_crate`) use the
            // same string ABI as inline ones, with per-method buffer types
            // (`<Struct>_<method>_RustCallOwnedString` / `_free_rust_string`).
            return_abi: crate::codegen::return_abi(&m.func.sig).to_string(),
            generic_wrapper: String::new(),
        })
        .collect();
    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,
        methods,
        derives: model.derives.clone(),
        has_clone: false,
        // A `String` field getter hands back an owned buffer, so the struct
        // carries `<Struct>_RustCallOwnedString` / `<Struct>_free_rust_string`
        // in crate mode too (#246).
        has_owned_string_helper: crate::codegen::crate_struct_needs_owned_string_helper(
            &model.item,
        ),
        has_borrowed_string_helper: false,
        context_source: String::new(),
        generic_wrappers: Vec::new(),
        line: model.line,
        module_path: module_path.to_vec(),
    }
}