rustcall_julia_core 0.4.1

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
//! Resolving the type path an `impl` header writes to the struct it names.
//!
//! Rust does not require an `impl C` to live next to `struct C`: it is legal in
//! any module that has `C` in scope, and in a multi-file crate the two are
//! routinely in different files. Both scans — `#[pymethods]` blocks for
//! `#[pyclass]` structs (#275) and `#[julia] impl` blocks for `#[julia]`
//! structs (#315) — collect the structs and the impl blocks of the whole crate
//! separately and marry them afterwards, and this module is the one resolver
//! they share: the qualifier written in front of the type (`crate::a::C`,
//! `super::C`, `self::C`, `a::C`, a bare `C`), the `use` declarations of the
//! impl's module, and finally the one struct of that name anywhere.

use syn::{Ident, ItemType, ItemUse, Type};

use crate::types::unparen;

/// Where a written path is rooted, which decides what a qualifier may match.
///
/// `crate::a::C` and `a::C` are **not** the same struct when the enclosing
/// module `m` also has an `a`: the first is `a::C` at the crate root, the
/// second is `m::a::C` (2018 paths) or, through a `use`, whatever brought `a`
/// into scope. Collapsing the two attached a `#[pymethods]` block to the wrong
/// class, which Phase 2 then compiled into a call to the wrong type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PathAnchor {
    /// `crate::…` — the crate root, and nothing else.
    Crate,
    /// `self::…` — the module the path was written in, and nothing else.
    SelfModule,
    /// A bare path: the enclosing module first, then the crate root.
    Relative,
    /// `super::…` (repeated `n` times): the module `n` levels above the one
    /// the path was written in, and nothing else. Treating it as
    /// uninformative sent `impl super::C` to a same-named `C` in the impl's
    /// own module (#307 review).
    Super(usize),
    /// A path this matcher cannot follow: `super` after another segment,
    /// which Rust itself rejects, or a qualified `<T as Trait>::C`. Nothing is
    /// matched on the qualifier at all.
    Unknown,
}

/// A path qualifier: where it is rooted and the module segments it names,
/// without the type's own name (`a::b::C` -> `["a", "b"]`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PathQualifier {
    pub anchor: PathAnchor,
    pub segments: Vec<String>,
}

impl PathQualifier {
    pub fn relative(segments: Vec<String>) -> Self {
        PathQualifier {
            anchor: PathAnchor::Relative,
            segments,
        }
    }

    /// Whether the qualifier says nothing (a bare `impl C`, or a path this
    /// matcher cannot follow).
    pub fn is_uninformative(&self) -> bool {
        self.anchor == PathAnchor::Unknown
            || (self.anchor == PathAnchor::Relative && self.segments.is_empty())
    }

    /// Whether the qualifier names one place and one place only, so that when
    /// no struct is found there the block must be dropped rather than matched
    /// by its bare name: `super::C` is never the impl's own module's `C`.
    pub fn forbids_fallback(&self) -> bool {
        matches!(self.anchor, PathAnchor::Super(_))
    }

    /// The module paths this qualifier can name, from inside `module_path`,
    /// nearest first. A `super::` that walks past the crate root names
    /// nothing.
    pub fn candidates(&self, module_path: &[String]) -> Vec<Vec<String>> {
        let mut nested = module_path.to_vec();
        nested.extend(self.segments.iter().cloned());
        match self.anchor {
            PathAnchor::Unknown => Vec::new(),
            PathAnchor::Crate => vec![self.segments.clone()],
            PathAnchor::SelfModule => vec![nested],
            PathAnchor::Relative => vec![nested, self.segments.clone()],
            PathAnchor::Super(levels) => {
                if levels > module_path.len() {
                    return Vec::new();
                }
                let mut base = module_path[..module_path.len() - levels].to_vec();
                base.extend(self.segments.iter().cloned());
                vec![base]
            }
        }
    }

    /// The module path the **proc-macro** takes the struct to live at when it
    /// expands `#[julia] impl <qualifier>::C` inside the `#[julia]` modules
    /// `symbol_path` (#315).
    ///
    /// The macro sees the header and the marked modules around it, nothing
    /// else — not the struct, not the `use` declarations of a file module, not
    /// whether a segment names a file module (transparent to the symbol
    /// scheme, #300) or a marked inline one. So it reads the header literally:
    /// `crate::a::C` is `a::C`; `self::C` and a bare `C` are in the impl's own
    /// marked path; `super::C` one level up from it, and a `super::` that
    /// walks past the marked root lands at the crate root, because the file
    /// modules above it qualify nothing; a relative `a::C` is `a` below the
    /// impl's path, as a 2018 path is; a path it cannot follow is treated as
    /// bare. The extraction pass, which knows where the struct really is,
    /// compares this against the struct's own path and refuses the impl when
    /// they disagree, so the symbols the macro emits and the manifest describes
    /// cannot drift apart.
    pub fn macro_target_path(&self, symbol_path: &[String]) -> Vec<String> {
        let below = |base: &[String]| {
            let mut out = base.to_vec();
            out.extend(self.segments.iter().cloned());
            out
        };
        match self.anchor {
            PathAnchor::Crate => self.segments.clone(),
            PathAnchor::SelfModule | PathAnchor::Relative => below(symbol_path),
            PathAnchor::Unknown => symbol_path.to_vec(),
            PathAnchor::Super(levels) if levels <= symbol_path.len() => {
                below(&symbol_path[..symbol_path.len() - levels])
            }
            PathAnchor::Super(_) => self.segments.clone(),
        }
    }

    /// The qualifier as the header spelled it, for diagnostics
    /// (`crate::a::` for `impl crate::a::C`; empty for a bare `impl C`).
    pub fn display_prefix(&self) -> String {
        let mut parts: Vec<String> = match self.anchor {
            PathAnchor::Crate => vec!["crate".to_string()],
            PathAnchor::SelfModule => vec!["self".to_string()],
            PathAnchor::Super(levels) => vec!["super".to_string(); levels],
            PathAnchor::Relative | PathAnchor::Unknown => Vec::new(),
        };
        parts.extend(self.segments.iter().cloned());
        if parts.is_empty() {
            String::new()
        } else {
            format!("{}::", parts.join("::"))
        }
    }
}

/// The qualifier of a path type, anchor included. A qualified path
/// (`<T as Trait>::C`) cannot be followed.
pub fn type_path_qualifier(ty: &Type) -> PathQualifier {
    let Type::Path(p) = unparen(ty) else {
        return PathQualifier::relative(Vec::new());
    };
    if p.qself.is_some() {
        return PathQualifier {
            anchor: PathAnchor::Unknown,
            segments: Vec::new(),
        };
    }
    path_qualifier(p.path.segments.iter().map(|s| s.ident.to_string()))
}

/// The qualifier of a path type written in a crate of the given edition, or
/// `None` for a path this resolver cannot follow: a qualified `<T as Tr>::C`,
/// or a leading `::` outside edition 2015. A leading `::` names the current
/// crate's root only in edition 2015 (what RustCall compiles a `rust"""`
/// block as: `rustc` with no `--edition`); since 2018 it starts in the extern
/// prelude, whose crates no scan here indexes, and it must not be confused
/// with a same-named local module. The one rule for every resolution of a
/// written type path — a `type` alias ([`import_of_type_alias`]), a PyO3
/// return type, a `#[julia]` return type ([`names_struct`], #518).
pub fn edition_type_qualifier(path: &syn::TypePath, edition_2015: bool) -> Option<PathQualifier> {
    if path.qself.is_some() || (path.path.leading_colon.is_some() && !edition_2015) {
        return None;
    }
    let mut qualifier = path_qualifier(path.path.segments.iter().map(|s| s.ident.to_string()));
    if path.path.leading_colon.is_some() {
        qualifier.anchor = PathAnchor::Crate;
    }
    Some(qualifier)
}

/// Split a written path into its anchor and its module segments, dropping the
/// final segment (the item's own name).
pub fn path_qualifier(segments: impl IntoIterator<Item = String>) -> PathQualifier {
    let all: Vec<String> = segments.into_iter().collect();
    let mut anchor = PathAnchor::Relative;
    let mut out = Vec::new();
    let mut levels = 0usize;
    let count = all.len();
    for (i, name) in all.into_iter().enumerate() {
        if i == 0 {
            match name.as_str() {
                "crate" => {
                    anchor = PathAnchor::Crate;
                    continue;
                }
                "self" => {
                    anchor = PathAnchor::SelfModule;
                    continue;
                }
                "super" => {
                    levels = 1;
                    anchor = PathAnchor::Super(levels);
                    continue;
                }
                _ => {}
            }
        } else if name == "super" {
            // A run of leading `super`s walks up one level each; a `super`
            // after a named segment is not a path Rust accepts.
            if matches!(anchor, PathAnchor::Super(_)) && out.is_empty() {
                levels += 1;
                anchor = PathAnchor::Super(levels);
                continue;
            }
            return PathQualifier {
                anchor: PathAnchor::Unknown,
                segments: Vec::new(),
            };
        }
        if i + 1 < count {
            out.push(name);
        }
    }
    PathQualifier {
        anchor,
        segments: out,
    }
}

/// One `use` path in scope: where it was written, the name it binds, and the
/// module path it names.
#[derive(Debug, Clone)]
pub struct ScannedImport {
    pub module_path: Vec<String>,
    /// The name the import binds — the last segment, or the `as` alias.
    pub alias: String,
    /// The full path it names, anchor stripped: `crate::a::C` -> `["a", "C"]`.
    pub path: Vec<String>,
    /// Where that path is rooted, so `use crate::a::C;` and `use a::C;` are
    /// not confused when the enclosing module also has an `a`.
    pub qualifier: PathQualifier,
    /// Whether this is a glob import such as `use crate::model::*`.  Globs
    /// cannot name one alias, but they still disambiguate a bare impl header
    /// to the imported module (#303).
    pub glob: bool,
}

/// What a bare `impl C` in `module_path` could be referring to through the
/// `use` declaration `item`.
pub fn imports_of_use(item: &ItemUse, module_path: &[String]) -> Vec<ScannedImport> {
    let mut bindings = Vec::new();
    let mut prefix = Vec::new();
    flatten_use_tree(&item.tree, &mut prefix, &mut bindings);
    bindings
        .into_iter()
        .map(|(alias, anchored, glob)| {
            let qualifier = if glob {
                // `path_qualifier` normally drops the final item segment.
                // Add a sentinel so the module prefix of a glob remains in
                // the candidate path.
                path_qualifier(
                    anchored
                        .iter()
                        .cloned()
                        .chain(std::iter::once("__rustcall_glob__".to_string())),
                )
            } else {
                path_qualifier(anchored.iter().cloned())
            };
            // The anchor segments are not part of the module path; the
            // qualifier keeps what they meant.
            let path: Vec<String> = anchored
                .into_iter()
                .filter(|s| s != "crate" && s != "self" && s != "super")
                .collect();
            ScannedImport {
                module_path: module_path.to_vec(),
                alias,
                path,
                qualifier,
                glob,
            }
        })
        .collect()
}

/// Treat a plain path type alias as a local import for impl resolution. Rust
/// accepts `type Alias = crate::model::C; #[pymethods] impl Alias { ... }`,
/// while the scanner otherwise only sees the spelling `Alias` (#303).
///
/// A leading `::` names this crate's root only in edition 2015. In edition
/// 2018 and later it starts in the extern prelude, whose crates this scanner
/// does not index, so it must not accidentally resolve to a same-named local
/// module.
pub fn import_of_type_alias(
    item: &ItemType,
    module_path: &[String],
    edition_2015: bool,
) -> Option<ScannedImport> {
    let Type::Path(path) = unparen(&item.ty) else {
        return None;
    };
    let qualifier = edition_type_qualifier(path, edition_2015)?;
    let path = path
        .path
        .segments
        .iter()
        .map(|s| s.ident.to_string())
        .filter(|s| s != "crate" && s != "self" && s != "super")
        .collect();
    Some(ScannedImport {
        module_path: module_path.to_vec(),
        alias: item.ident.to_string(),
        path,
        qualifier,
        glob: false,
    })
}

/// Flatten a `use` tree into the names it binds and the paths they name,
/// **anchor included**.
///
/// `use crate::a::{C, D as E};` yields `("C", ["crate", "a", "C"])` and
/// `("E", ["crate", "a", "D"])`; the caller splits the anchor off with
/// [`path_qualifier`], so `use crate::a::C;` and `use a::C;` stay distinct.
/// A glob (`use a::*;`) binds no name it can be matched on; it is recorded as
/// `("*", prefix, true)` so the caller can still scope an `impl` of an
/// unqualified name through it.
/// `super::` is kept: [`path_qualifier`] resolves it against the module the
/// `use` was written in, like any other anchor (#307 review).
fn flatten_use_tree(
    tree: &syn::UseTree,
    prefix: &mut Vec<String>,
    out: &mut Vec<(String, Vec<String>, bool)>,
) {
    match tree {
        syn::UseTree::Path(path) => {
            let segment = path.ident.to_string();
            prefix.push(segment);
            flatten_use_tree(&path.tree, prefix, out);
            prefix.pop();
        }
        syn::UseTree::Name(name) => {
            let mut full = prefix.clone();
            let alias = if name.ident == "self" && !prefix.is_empty() {
                prefix.last().unwrap().clone()
            } else {
                full.push(name.ident.to_string());
                name.ident.to_string()
            };
            out.push((alias, full, false));
        }
        syn::UseTree::Rename(rename) => {
            let mut full = prefix.clone();
            if rename.ident != "self" || prefix.is_empty() {
                full.push(rename.ident.to_string());
            }
            out.push((rename.rename.to_string(), full, false));
        }
        syn::UseTree::Group(group) => {
            for item in &group.items {
                flatten_use_tree(item, prefix, out);
            }
        }
        // A glob binds no name this matcher can key on; record its prefix.
        syn::UseTree::Glob(_) => out.push(("*".to_string(), prefix.clone(), true)),
    }
}

/// An `impl` header as far as resolution is concerned: the type's own name,
/// the qualifier written in front of it, and the module the block sits in.
#[derive(Debug, Clone)]
pub struct ImplHeader {
    pub target: Ident,
    pub qualifier: PathQualifier,
    pub module_path: Vec<String>,
}

impl ImplHeader {
    /// The header of an inherent `impl`; `None` for a trait impl or a target
    /// that is not a path type.
    pub fn of(item: &syn::ItemImpl, module_path: &[String]) -> Option<Self> {
        if item.trait_.is_some() {
            return None;
        }
        Self::of_any(item, module_path)
    }

    /// The header of any `impl`, a trait impl's included; `None` for a target
    /// that is not a path type. A `#[julia]` trait impl is wrapped by the proc
    /// macro, and its refused methods are reported (#503).
    pub fn of_any(item: &syn::ItemImpl, module_path: &[String]) -> Option<Self> {
        let target = crate::types::last_ident(&item.self_ty)?.clone();
        Some(ImplHeader {
            target,
            qualifier: type_path_qualifier(&item.self_ty),
            module_path: module_path.to_vec(),
        })
    }

    /// The header as written, `impl crate::a::C`, for diagnostics.
    pub fn display(&self) -> String {
        format!("impl {}{}", self.qualifier.display_prefix(), self.target)
    }
}

/// A struct a header can be matched against: its name and the module it is
/// declared in.
pub trait Located {
    fn name(&self) -> &str;
    fn module_path(&self) -> &[String];
    fn visible_from(&self, _module_path: &[String]) -> bool {
        true
    }
}

/// Whether a declaration can be imported from this module within the crate.
/// This is distinct from external-wrapper reachability: `pub(crate)` is
/// importable internally even though a wrapper crate cannot name it.
pub fn visible_from(vis: &syn::Visibility, defined_in: &[String], from: &[String]) -> bool {
    let restricted = match vis {
        syn::Visibility::Public(_) => return true,
        syn::Visibility::Inherited => return from.starts_with(defined_in),
        syn::Visibility::Restricted(restricted) => restricted,
    };
    let parts: Vec<String> = restricted
        .path
        .segments
        .iter()
        .map(|s| s.ident.to_string())
        .collect();
    let (mut scope, consumed) = match parts.first().map(String::as_str) {
        Some("crate") => (Vec::new(), 1),
        Some("self") => (defined_in.to_vec(), 1),
        Some("super") => {
            let levels = parts.iter().take_while(|s| *s == "super").count();
            if levels > defined_in.len() {
                return false;
            }
            (defined_in[..defined_in.len() - levels].to_vec(), levels)
        }
        _ => (Vec::new(), 0),
    };
    scope.extend(parts.into_iter().skip(consumed));
    from.starts_with(&scope)
}

/// Why a header matched no struct, for the diagnostic of a scan that must not
/// drop the block silently (#315).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Unresolved {
    /// No struct of that name is where the header points (or anywhere, for a
    /// bare name).
    NotFound,
    /// A bare name that several modules declare, and nothing — qualifier,
    /// `use`, the impl's own module — picks one; the paths of the candidates.
    Ambiguous(Vec<Vec<String>>),
}

/// Locate the struct an `impl` header names among `structs`.
///
/// A header is matched, in order, to: the struct named by an explicit
/// qualifier (`impl a::C`, resolved against the impl's own module and against
/// the crate root); the struct of that name in the impl's own module; the one
/// a `use` in that module brought into scope under that name; and finally the
/// one struct of that name anywhere in the crate. When two modules declare
/// structs of the same name and nothing disambiguates, the block is not
/// attached to a guess — a wrong `Struct::method` would not compile — and the
/// caller decides how to report that.
pub fn locate<T: Located>(
    structs: &[T],
    header: &ImplHeader,
    imports: &[ScannedImport],
) -> Result<usize, Unresolved> {
    locate_with_fallback(structs, header, imports, Fallback::Any)
}

/// Resolve a return type using the same imports as impl targets, but never
/// discard a written qualifier to match an unrelated same-named class.
pub fn locate_type<T: Located>(
    structs: &[T],
    header: &ImplHeader,
    imports: &[ScannedImport],
) -> Result<usize, Unresolved> {
    locate_with_fallback(structs, header, imports, Fallback::Unqualified)
}

/// Whether the type `ty`, written in `module_path`, names `structs[own]` —
/// the struct an impl header spelling its type `own_ty` was resolved to —
/// **with certainty** (#518).
///
/// The path is resolved as [`locate`] resolves a header — its qualifier
/// (`crate::`, `self::`, `super::`, a module, a module a `use .. as` renamed),
/// then the struct of that name in `module_path`, then a `use` in
/// `module_path` that binds the name (`use super::Gauge as Meter`) — and no
/// further: a glob import, or the one struct of that name anywhere, is how
/// [`locate`] picks a block's struct when nothing else does, not proof that
/// a type names it. Only `structs` are candidates, so a name that resolves to
/// anything else (`type Meter = f64`, a struct the scan did not select)
/// names none of them. The path is anchored by [`edition_type_qualifier`]:
/// a leading `::` is the crate root in edition 2015 (`-> ::Gauge` in a
/// `rust"""` block) and names nothing since 2018, and a qualified
/// `<T as Tr>::Meter` names nothing. The generic arguments must be spelled as
/// the header spells them: `Buf<i64>` is not `impl Buf<i32>`'s own type.
pub fn names_struct<T: Located>(
    structs: &[T],
    own: usize,
    own_ty: &Type,
    ty: &Type,
    module_path: &[String],
    imports: &[ScannedImport],
    edition_2015: bool,
) -> bool {
    let (Type::Path(path), Type::Path(own_path)) = (unparen(ty), unparen(own_ty)) else {
        return false;
    };
    let Some(qualifier) = edition_type_qualifier(path, edition_2015) else {
        return false;
    };
    let (Some(last), Some(own_last)) = (path.path.segments.last(), own_path.path.segments.last())
    else {
        return false;
    };
    let (args, own_args) = (&last.arguments, &own_last.arguments);
    if quote::quote!(#args).to_string() != quote::quote!(#own_args).to_string() {
        return false;
    }
    let header = ImplHeader {
        target: last.ident.clone(),
        qualifier,
        module_path: module_path.to_vec(),
    };
    locate_with_fallback(structs, &header, imports, Fallback::None) == Ok(own)
}

/// How far [`locate_with_fallback`] may reach once the written path and the
/// scope it was written in have said all they can.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Fallback {
    /// A glob import, then the one struct of that name anywhere — and a
    /// qualified header whose qualifier matched nothing is read as its bare
    /// name ([`locate`]).
    Any,
    /// A written qualifier is kept ([`locate_type`]); a bare name still
    /// falls back to a glob import and to the one struct of that name.
    Unqualified,
    /// Nothing beyond the path, the module's own structs and the `use`
    /// declarations that bind the name ([`names_struct`]).
    None,
}

fn locate_with_fallback<T: Located>(
    structs: &[T],
    header: &ImplHeader,
    imports: &[ScannedImport],
    fallback: Fallback,
) -> Result<usize, Unresolved> {
    let name = header.target.to_string();
    let named = |s: &T| s.name() == name;

    if !header.qualifier.is_uninformative() {
        // An imported module alias is part of the path's meaning:
        // `use crate::z as alias; impl alias::C` names `z::C`, not a class
        // called `C` next to the impl. Refusing an unresolved alias also
        // avoids silently attaching the methods to a same-named local class
        // (#303).
        let alias_import = if header.qualifier.anchor == PathAnchor::Relative {
            header.qualifier.segments.first().and_then(|alias| {
                imports.iter().find(|import| {
                    import.module_path == header.module_path
                        && !import.glob
                        && import.alias == *alias
                })
            })
        } else {
            None
        };
        if let Some(import) = alias_import {
            let mut segments = import.path.clone();
            segments.extend(header.qualifier.segments.iter().skip(1).cloned());
            let imported = PathQualifier {
                anchor: import.qualifier.anchor,
                segments,
            };
            for candidate in imported.candidates(&header.module_path) {
                if let Some(i) = structs
                    .iter()
                    .position(|s| named(s) && s.module_path() == candidate.as_slice())
                {
                    return Ok(i);
                }
            }
            return Err(Unresolved::NotFound);
        }
        // `impl a::C` inside module `m` means `m::a::C`, or `a::C` from the
        // crate root — try both, nearest first. `impl crate::a::C` means
        // only the second, and `impl self::a::C` only the first. A path
        // resolved with certainty ([`names_struct`]) takes only the first:
        // since edition 2018 a relative `a::C` reaches the crate root's `a`
        // only through a `use`, which the alias step above has followed.
        let mut candidates = header.qualifier.candidates(&header.module_path);
        if fallback == Fallback::None && header.qualifier.anchor == PathAnchor::Relative {
            candidates.truncate(1);
        }
        for candidate in candidates {
            if let Some(i) = structs
                .iter()
                .position(|s| named(s) && s.module_path() == candidate.as_slice())
            {
                return Ok(i);
            }
        }
        // `impl super::C` names the parent module's `C` and nothing else:
        // with none there, attaching to a `C` in the impl's own module —
        // or to the one `C` anywhere — would be exactly the wrong struct
        // (#307 review).
        if fallback != Fallback::Any || header.qualifier.forbids_fallback() {
            return Err(Unresolved::NotFound);
        }
    }

    if let Some(i) = structs
        .iter()
        .position(|s| named(s) && s.module_path() == header.module_path.as_slice())
    {
        return Ok(i);
    }

    // A bare `impl C` is disambiguated by whatever brought `C` into scope:
    // `use crate::a::C;` in the impl's module names `a::C` exactly, even
    // though the impl itself writes no qualifier.
    for import in imports {
        if import.module_path != header.module_path || import.alias != name {
            continue;
        }
        let target = import.path.last().map(String::as_str).unwrap_or(&name);
        for candidate in import.qualifier.candidates(&header.module_path) {
            if let Some(i) = structs
                .iter()
                .position(|s| s.name() == target && s.module_path() == candidate.as_slice())
            {
                return Ok(i);
            }
        }
    }

    if fallback == Fallback::None {
        return Err(Unresolved::NotFound);
    }

    // A glob has no alias to compare, but `use a::*; impl C` is still scoped
    // to `a::C` before Rust considers unrelated same-named structs.  Only
    // accept a class whose module is exactly the imported module; this avoids
    // treating a nested module's private implementation as re-exported.
    for import in imports {
        if import.module_path != header.module_path || !import.glob {
            continue;
        }
        for candidate in import.qualifier.candidates(&header.module_path) {
            if let Some(i) = structs.iter().position(|s| {
                named(s)
                    && s.module_path() == candidate.as_slice()
                    && s.visible_from(&header.module_path)
            }) {
                return Ok(i);
            }
        }
    }

    let matching: Vec<usize> = structs
        .iter()
        .enumerate()
        .filter(|(_, s)| named(s))
        .map(|(i, _)| i)
        .collect();
    match matching.as_slice() {
        [one] => Ok(*one),
        [] => Err(Unresolved::NotFound),
        many => Err(Unresolved::Ambiguous(
            many.iter()
                .map(|&i| structs[i].module_path().to_vec())
                .collect(),
        )),
    }
}