Skip to main content

flux_desugar/
resolver.rs

1pub(crate) mod refinement_resolver;
2
3use std::collections::hash_map;
4
5use flux_common::{
6    bug,
7    result::{ErrorCollector, ErrorEmitter, ResultExt},
8};
9use flux_errors::Errors;
10use flux_middle::{
11    FluxItemDecl, ResolverOutput, Specs,
12    def_id::{FluxDefId, MaybeExternId},
13    fhir,
14    fhir::{
15        Namespace::{self, *},
16        PerNS,
17    },
18    global_env::GlobalEnv,
19};
20use flux_syntax::{
21    surface::{self, Ident, visit::Visitor as _},
22    symbols::sym,
23};
24use hir::{ItemId, ItemKind, OwnerId, def::DefKind};
25use itertools::Itertools;
26use rustc_data_structures::unord::{ExtendUnord, UnordMap};
27use rustc_errors::ErrorGuaranteed;
28use rustc_hir::{
29    self as hir, CRATE_OWNER_ID, ParamName, PrimTy, def::CtorOf, def_id::CRATE_DEF_ID,
30};
31use rustc_middle::{middle::resolve::ModChild, ty::TyCtxt};
32use rustc_span::{Span, Symbol, def_id::DefId, symbol::kw};
33
34use self::refinement_resolver::{ImplicitParamCollector, RefinementResolver};
35
36type Result<T = ()> = std::result::Result<T, ErrorGuaranteed>;
37
38/// The reason a name lookup (`resolve_ident_with_ribs`, `resolve_ident_in_module`,
39/// `resolve_path_with_ribs`) failed.
40enum ResolveError {
41    NotFound,
42    /// The name resolved to two or more distinct, competing bindings (e.g. two different glob
43    /// imports bringing in different items under the same name) with nothing more specific to
44    /// disambiguate. Carries everything needed to emit [`errors::AmbiguousName`], so that callers
45    /// deep in the path walk don't have to reconstruct which segment went wrong.
46    Ambiguous(Ambiguity),
47    /// The name resolved to a generic parameter (or `Self`) of an outer item.
48    OuterGeneric(Span),
49}
50
51impl ResolveError {
52    /// Emits the error. A [`ResolveError::NotFound`] is reported with the diagnostic built by
53    /// `not_found`, since only the caller knows what was being looked for.
54    #[track_caller]
55    fn emit<'a, D: rustc_errors::Diagnostic<'a>>(
56        self,
57        emitter: &'a impl ErrorEmitter,
58        not_found: impl FnOnce() -> D,
59    ) -> ErrorGuaranteed {
60        match self {
61            Self::NotFound => emitter.emit(not_found()),
62            Self::Ambiguous(ambiguity) => emitter.emit(errors::AmbiguousName::new(ambiguity)),
63            Self::OuterGeneric(span) => emitter.emit(errors::OuterGeneric { span }),
64        }
65    }
66}
67
68/// A name that two competing glob imports bind to different items:
69///
70/// ```ignore
71/// mod a { pub struct S; }
72/// mod b { pub struct S; }
73///
74/// use a::*;
75/// use b::*;
76///
77/// #[flux::spec(fn(x: S))]
78/// fn f(x: a::S) {}
79/// ```
80#[derive(Clone, Copy, Debug)]
81struct Ambiguity {
82    /// The use site that hit the ambiguity: the `S` inside the signature.
83    span: Span,
84    /// The contested name: `S`.
85    name: Symbol,
86    /// Where the first candidate was brought into scope: the `use a::*;` statement.
87    first: Span,
88    /// Same for the second candidate: `use b::*;`. It can coincide with `first` when a single
89    /// glob imports a module that is itself ambiguously re-exporting the name.
90    second: Span,
91}
92
93pub(crate) fn resolve_crate(genv: GlobalEnv) -> ResolverOutput {
94    match try_resolve_crate(genv) {
95        Ok(output) => output,
96        Err(err) => genv.sess().abort(err),
97    }
98}
99
100fn try_resolve_crate(genv: GlobalEnv) -> Result<ResolverOutput> {
101    let specs = genv.collect_specs();
102    let mut resolver = CrateResolver::new(genv, specs);
103
104    genv.tcx().hir_walk_toplevel_module(&mut resolver);
105
106    resolver.into_output()
107}
108
109pub(crate) struct CrateResolver<'genv, 'tcx> {
110    genv: GlobalEnv<'genv, 'tcx>,
111    specs: &'genv Specs,
112    output: ResolverOutput,
113    ribs: PerNS<Vec<Rib>>,
114    /// A mapping from the names of all imported crates to their [`DefId`]
115    crates: UnordMap<Symbol, DefId>,
116    /// Names available everywhere: Rust builtin types plus flux's global funcs (theory funcs, `cast`)
117    /// and primitive sorts.
118    prelude: PerNS<Rib>,
119    err: Option<ErrorGuaranteed>,
120    /// The most recent module we have visited. Used to check for visibility of other items from
121    /// this module.
122    current_module: OwnerId,
123}
124
125/// Map to keep track of names defined in a scope
126#[derive(Default)]
127struct DefinitionMap {
128    defined: UnordMap<Ident, ()>,
129}
130
131impl DefinitionMap {
132    fn define(&mut self, name: Ident) -> std::result::Result<(), errors::DuplicateDefinition> {
133        match self.defined.entry(name) {
134            hash_map::Entry::Occupied(entry) => {
135                Err(errors::DuplicateDefinition {
136                    span: name.span,
137                    previous_definition: entry.key().span,
138                    name: name.name,
139                })
140            }
141            hash_map::Entry::Vacant(entry) => {
142                entry.insert(());
143                Ok(())
144            }
145        }
146    }
147}
148
149impl<'genv, 'tcx> CrateResolver<'genv, 'tcx> {
150    pub fn new(genv: GlobalEnv<'genv, 'tcx>, specs: &'genv Specs) -> Self {
151        Self {
152            genv,
153            output: ResolverOutput::default(),
154            specs,
155            ribs: PerNS {
156                type_ns: vec![],
157                value_ns: vec![],
158                macro_ns: vec![],
159                flux_fn_ns: vec![],
160                hint_ns: vec![],
161            },
162            crates: mk_crate_mapping(genv.tcx()),
163            prelude: PerNS {
164                type_ns: builtin_types_rib(),
165                value_ns: Rib::new(RibKind::Misc),
166                macro_ns: Rib::new(RibKind::Misc),
167                flux_fn_ns: theory_funcs_rib(),
168                hint_ns: Rib::new(RibKind::Misc),
169            },
170            err: None,
171            current_module: CRATE_OWNER_ID,
172        }
173    }
174
175    /// Defines the flux items declared in `scope` (a module or a block) in the innermost rib.
176    #[allow(
177        clippy::disallowed_methods,
178        reason = "`flux_items_by_scope` is the source of truth for `FluxDefId`"
179    )]
180    fn define_flux_items(&mut self, scope: hir::HirId) {
181        let Some(decls) = self.specs.flux_items_by_scope.get(&scope) else { return };
182        for FluxItemDecl { declarer, item } in decls {
183            match item {
184                surface::FluxItem::PrimOpProp(prop) => {
185                    let def_id = FluxDefId::new(declarer.to_def_id(), prop.name.name);
186                    self.define_res_in(
187                        fhir::Res::Property(def_id),
188                        HintNS,
189                        BindingSource::Explicit(prop.name),
190                    );
191                }
192                surface::FluxItem::Qualifier(qual) => {
193                    let def_id = FluxDefId::new(declarer.to_def_id(), qual.name.name);
194                    self.define_res_in(
195                        fhir::Res::Qualifier(def_id),
196                        HintNS,
197                        BindingSource::Explicit(qual.name),
198                    );
199                }
200                surface::FluxItem::Axiom(axiom) => {
201                    let def_id = FluxDefId::new(declarer.to_def_id(), axiom.name.name);
202                    self.define_res_in(
203                        fhir::Res::Axiom(def_id),
204                        HintNS,
205                        BindingSource::Explicit(axiom.name),
206                    );
207                }
208                surface::FluxItem::FuncDef(defn) => {
209                    let def_id = FluxDefId::new(declarer.to_def_id(), defn.name.name);
210                    let kind = fhir::SpecFuncKind::Def(def_id);
211                    self.define_res_in(
212                        fhir::Res::GlobalFunc(kind),
213                        ReftNS,
214                        BindingSource::Explicit(defn.name),
215                    );
216                }
217                surface::FluxItem::SortDecl(sort_decl) => {
218                    let def_id = FluxDefId::new(declarer.to_def_id(), sort_decl.name.name);
219                    self.define_res_in(
220                        fhir::Res::UserSort(def_id),
221                        TypeNS,
222                        BindingSource::Explicit(sort_decl.name),
223                    );
224                }
225                surface::FluxItem::Use(use_tree) => {
226                    // Flux's `use` has no glob form, so every name it brings in is explicit.
227                    for (ident, res, ns) in self.resolve_flux_use_tree(use_tree) {
228                        self.define_res_in(res, ns, BindingSource::Explicit(ident));
229                    }
230                }
231            }
232        }
233    }
234
235    fn define_items(&mut self, item_ids: impl IntoIterator<Item = &'tcx ItemId>) {
236        for item_id in item_ids {
237            let item = self.genv.tcx().hir_item(*item_id);
238            let def_kind = match item.kind {
239                ItemKind::Use(use_tree) => {
240                    let is_prelude = is_prelude_import(self.genv.tcx(), item);
241                    self.define_use_tree(&use_tree, &mut vec![], is_prelude, item.span);
242                    continue;
243                }
244                ItemKind::ForeignMod { items, .. } => {
245                    self.define_foreign_items(items);
246                    continue;
247                }
248                ItemKind::TyAlias(..)
249                | ItemKind::Enum(..)
250                | ItemKind::Struct(..)
251                | ItemKind::Union(..)
252                | ItemKind::Trait { .. }
253                | ItemKind::Mod(..)
254                | ItemKind::Const(..) => self.genv.def_kind(item.owner_id),
255                _ => continue,
256            };
257            if let Some(ns) = def_kind.ns().map(Namespace::from)
258                && let Some(ident) = item.kind.ident()
259            {
260                self.define_res_in(
261                    fhir::Res::Def(def_kind, item.owner_id.to_def_id()),
262                    ns,
263                    BindingSource::Explicit(ident),
264                );
265            }
266        }
267    }
268
269    fn define_foreign_items(&mut self, items: &[rustc_hir::ForeignItemId]) {
270        for item_id in items {
271            let item = self.genv.tcx().hir_foreign_item(*item_id);
272            match item.kind {
273                rustc_hir::ForeignItemKind::Type => {
274                    self.define_res_in(
275                        fhir::Res::Def(DefKind::ForeignTy, item.owner_id.to_def_id()),
276                        TypeNS,
277                        BindingSource::Explicit(item.ident),
278                    );
279                }
280                rustc_hir::ForeignItemKind::Fn(..) | rustc_hir::ForeignItemKind::Static(..) => {}
281            }
282        }
283    }
284
285    /// Define the name in `source` in the innermost rib of `ns`.
286    fn define_res_in(
287        &mut self,
288        res: fhir::Res<surface::NodeId>,
289        ns: Namespace,
290        source: BindingSource,
291    ) {
292        let ident = source.ident();
293        if ident.name == kw::Underscore {
294            return;
295        }
296        let entry = self.ribs[ns]
297            .last_mut()
298            .unwrap()
299            .bindings
300            .entry(ident.name)
301            .or_default();
302
303        if let Some(prev) = entry.define(source, res) {
304            if let fhir::Res::Param(..) = prev.res {
305                self.emit(errors::DuplicateParam {
306                    span: ident.span,
307                    name: ident.name,
308                    first_use: prev.span,
309                });
310            } else {
311                self.emit(errors::DuplicateDefinition {
312                    span: ident.span,
313                    previous_definition: prev.span,
314                    name: ident.name,
315                });
316            }
317        }
318    }
319
320    /// Define `ident` in the prelude of `ns`. The prelude is only ever populated from the single
321    /// `#[prelude_import]` glob, so unlike [`Self::define_res_in`] it keeps plain last-one-wins
322    /// semantics: there is no second glob to be ambiguous with.
323    fn define_in_prelude(&mut self, ident: Ident, res: fhir::Res<surface::NodeId>, ns: Namespace) {
324        self.prelude[ns]
325            .bindings
326            .insert(ident.name, NameResolution::from_explicit(Binding { span: ident.span, res }));
327    }
328
329    fn push_rib(&mut self, ns: Namespace, kind: RibKind) {
330        self.ribs[ns].push(Rib::new(kind));
331    }
332
333    fn pop_rib(&mut self, ns: Namespace) {
334        self.ribs[ns].pop();
335    }
336
337    fn define_generics(&mut self, def_id: MaybeExternId<OwnerId>) {
338        let generics = self
339            .genv
340            .tcx()
341            .hir_get_generics(def_id.local_id().def_id)
342            .unwrap();
343        for param in generics.params {
344            let def_kind = self.genv.tcx().def_kind(param.def_id);
345            if let ParamName::Plain(name) = param.name
346                && let Some(ns) = def_kind.ns().map(Namespace::from)
347            {
348                debug_assert!(matches!(def_kind, DefKind::TyParam | DefKind::ConstParam));
349                let param_id = self.genv.maybe_extern_id(param.def_id).resolved_id();
350                self.define_res_in(
351                    fhir::Res::Def(def_kind, param_id),
352                    ns,
353                    BindingSource::Explicit(name),
354                );
355            }
356        }
357    }
358
359    fn resolve_flux_items(&mut self, scope: hir::HirId) {
360        let Some(decls) = self.specs.flux_items_by_scope.get(&scope) else { return };
361        for ns in [TypeNS, ValueNS, ReftNS, HintNS] {
362            self.push_rib(ns, RibKind::Item);
363        }
364        for FluxItemDecl { item, .. } in decls {
365            self.resolve_flux_item(item, MaybeExternId::Local(scope.owner))
366                .collect_err(&mut self.err);
367        }
368        for ns in [TypeNS, ValueNS, ReftNS, HintNS] {
369            self.pop_rib(ns);
370        }
371    }
372
373    fn resolve_flux_item(
374        &mut self,
375        item: &surface::FluxItem,
376        parent: MaybeExternId<OwnerId>,
377    ) -> Result {
378        if let surface::FluxItem::Use(_) = item {
379            // Use paths are resolved `CrateResolver::resolve_flux_use_tree`
380            return Ok(());
381        }
382        ItemResolver::run(self, parent, |vis| vis.visit_flux_item(item))?;
383        // Sort variables share the type namespace with sorts/types (see [`fhir::Namespace`]).
384        self.push_rib(TypeNS, RibKind::Misc);
385        for (idx, ident) in item.sort_vars().iter().enumerate() {
386            self.define_res_in(fhir::Res::SortParam(idx), TypeNS, BindingSource::Explicit(*ident));
387        }
388        let result =
389            RefinementResolver::run(self, Default::default(), |vis| vis.visit_flux_item(item));
390        self.pop_rib(TypeNS);
391        result
392    }
393
394    fn resolve_item(&mut self, item: &surface::Item, item_id: MaybeExternId<OwnerId>) -> Result {
395        ItemResolver::run(self, item_id, |vis| vis.visit_item(item))?;
396        let params = ImplicitParamCollector::run(self, |vis| vis.visit_item(item))?;
397        RefinementResolver::run(self, params, |vis| vis.visit_item(item))
398    }
399
400    fn resolve_trait_item(
401        &mut self,
402        item: &surface::TraitItemFn,
403        item_id: MaybeExternId<OwnerId>,
404    ) -> Result {
405        ItemResolver::run(self, item_id, |vis| vis.visit_trait_item(item))?;
406        let params = ImplicitParamCollector::run(self, |vis| vis.visit_trait_item(item))?;
407        RefinementResolver::run(self, params, |vis| vis.visit_trait_item(item))
408    }
409
410    fn resolve_impl_item(
411        &mut self,
412        item: &surface::ImplItemFn,
413        item_id: MaybeExternId<OwnerId>,
414    ) -> Result {
415        ItemResolver::run(self, item_id, |vis| vis.visit_impl_item(item))?;
416        let params = ImplicitParamCollector::run(self, |vis| vis.visit_impl_item(item))?;
417        RefinementResolver::run(self, params, |vis| vis.visit_impl_item(item))
418    }
419
420    fn resolve_path_with_ribs<S: Segment>(
421        &mut self,
422        segments: &[S],
423        ns: Namespace,
424    ) -> std::result::Result<fhir::PartialRes<surface::NodeId>, ResolveError> {
425        let result = self.resolve_path_with_ribs_inner(segments, ns);
426        let fallback = match &result {
427            Ok(res) => matches!(res.full_res(), Some(fhir::Res::Def(DefKind::Mod, _))),
428            Err(ResolveError::NotFound) => true,
429            Err(ResolveError::Ambiguous(_) | ResolveError::OuterGeneric(_)) => false,
430        };
431        // Retry a primitive when ordinary lookup finds a module or fails.
432        // See: https://github.com/rust-lang/rust/blob/12c4d3f34dcb4715784d2fa0e8443853e0592194/compiler/rustc_resolve/src/late.rs#L5069-L5071
433        if fallback
434            && (ns == TypeNS || (ns == ValueNS && segments.len() > 1))
435            && let Some(first) = segments.first()
436        {
437            let name = first.ident().name;
438            let prim = PrimTy::from_name(name).map(fhir::Res::PrimTy).or_else(|| {
439                fhir::PrimSort::ALL
440                    .into_iter()
441                    .find(|sort| sort.name() == name)
442                    .map(fhir::Res::PrimSort)
443            });
444            if let Some(res) = prim {
445                S::record_segment_res(self, first, res);
446                return Ok(fhir::PartialRes::with_unresolved_segments(res, segments.len() - 1));
447            }
448        }
449        result
450    }
451
452    /// Ordinary path lookup, also used for imports where modules must not become primitives.
453    fn resolve_path_with_ribs_inner<S: Segment>(
454        &mut self,
455        segments: &[S],
456        ns: Namespace,
457    ) -> std::result::Result<fhir::PartialRes<surface::NodeId>, ResolveError> {
458        let mut module: Option<Module> = None;
459        for (segment_idx, segment) in segments.iter().enumerate() {
460            let is_last = segment_idx + 1 == segments.len();
461            let ns = if is_last { ns } else { TypeNS };
462
463            let base_res = if let Some(module) = module {
464                self.resolve_ident_in_module(module, segment.ident(), ns)?
465            } else {
466                self.resolve_ident_with_ribs(segment.ident(), ns)?
467            };
468
469            S::record_segment_res(self, segment, base_res);
470
471            if is_last {
472                return Ok(fhir::PartialRes::new(base_res));
473            }
474
475            match base_res {
476                fhir::Res::Def(DefKind::Mod, module_id) => {
477                    module = Some(Module::new(ModuleKind::Mod, module_id));
478                }
479                fhir::Res::Def(DefKind::Trait, module_id) => {
480                    module = Some(Module::new(ModuleKind::Trait, module_id));
481                }
482                fhir::Res::Def(DefKind::Enum, module_id) => {
483                    module = Some(Module::new(ModuleKind::Enum, module_id));
484                }
485                _ => {
486                    return Ok(fhir::PartialRes::with_unresolved_segments(
487                        base_res,
488                        segments.len() - segment_idx - 1,
489                    ));
490                }
491            }
492        }
493        Err(ResolveError::NotFound)
494    }
495
496    fn resolve_flux_use_tree(
497        &mut self,
498        use_tree: &surface::UseTree,
499    ) -> Vec<(Ident, fhir::Res<surface::NodeId>, Namespace)> {
500        self.resolve_flux_use_tree_rec(use_tree, None, &mut vec![])
501    }
502
503    fn resolve_flux_use_tree_rec(
504        &mut self,
505        use_tree: &surface::UseTree,
506        mut resolved_module_id: Option<DefId>,
507        resolved_prefix: &mut Vec<Ident>,
508    ) -> Vec<(Ident, fhir::Res<surface::NodeId>, Namespace)> {
509        let Some((last, all_but_last)) = use_tree.prefix.segments.split_last() else {
510            bug!("path must have at least one segment")
511        };
512        let module_segments = match &use_tree.kind {
513            surface::UseTreeKind::Simple => all_but_last,
514            surface::UseTreeKind::Nested(_) => &use_tree.prefix.segments[..],
515        };
516
517        for segment in module_segments {
518            let ident = segment.ident();
519            let res = if let Some(module_id) = resolved_module_id {
520                let module = Module::new(ModuleKind::Mod, module_id);
521                self.resolve_ident_in_module(module, ident, TypeNS)
522            } else {
523                self.resolve_ident_with_ribs(ident, TypeNS)
524            };
525            let res = match res {
526                Ok(res) => res,
527                Err(err) => {
528                    self.emit_resolve_err(err, || {
529                        errors::UnresolvedImport::new(ident, resolved_module_id, resolved_prefix)
530                    });
531                    return vec![];
532                }
533            };
534            if let fhir::Res::Def(DefKind::Mod, def_id) = res {
535                resolved_module_id = Some(def_id);
536            } else {
537                self.emit_not_a_module(ident, resolved_prefix);
538                return vec![];
539            }
540            resolved_prefix.push(ident);
541        }
542
543        match &use_tree.kind {
544            surface::UseTreeKind::Simple => {
545                let mut resolutions = vec![];
546                // An import names an item in every namespace at once, so an ambiguity in any one
547                // of them is an error even if the others resolve. Keeping only the first means one
548                // import is one error.
549                let mut error = None;
550                for ns in [TypeNS, ValueNS, ReftNS, HintNS] {
551                    let res = if let Some(module_id) = resolved_module_id {
552                        let module = Module::new(ModuleKind::Mod, module_id);
553                        self.resolve_ident_in_module(module, last.ident(), ns)
554                    } else {
555                        self.resolve_ident_with_ribs(last.ident(), ns)
556                    };
557                    match res {
558                        Ok(res) => resolutions.push((last.ident(), res, ns)),
559                        Err(ResolveError::NotFound) => {}
560                        Err(err) => error = error.or(Some(err)),
561                    }
562                }
563                if resolutions.is_empty() {
564                    error = error.or(Some(ResolveError::NotFound));
565                }
566                if let Some(err) = error {
567                    self.emit_resolve_err(err, || {
568                        errors::UnresolvedImport::new(
569                            last.ident,
570                            resolved_module_id,
571                            resolved_prefix,
572                        )
573                    });
574                }
575                resolutions
576            }
577            surface::UseTreeKind::Nested(items) => {
578                let mut resolutions = vec![];
579                for item in items {
580                    let len = resolved_prefix.len();
581                    resolutions.extend(self.resolve_flux_use_tree_rec(
582                        item,
583                        resolved_module_id,
584                        resolved_prefix,
585                    ));
586                    resolved_prefix.truncate(len);
587                }
588                resolutions
589            }
590        }
591    }
592
593    fn resolve_ident_with_ribs(
594        &self,
595        ident: Ident,
596        ns: Namespace,
597    ) -> std::result::Result<fhir::Res<surface::NodeId>, ResolveError> {
598        let mut ribs = self.ribs[ns].iter().rev();
599        let mut crossed_item = false;
600        while let Some(rib) = ribs.next() {
601            // An ambiguous name is still a name: it stops the climb here rather than falling
602            // through to outer scopes or the prelude.
603            if let Some(name_res) = rib.bindings.get(&ident.name)
604                && let Some(res) = name_res.resolve(ident)
605            {
606                // Like in rust, nested items cannot mention generics of outer items
607                let res = res.map_err(ResolveError::Ambiguous)?;
608                if crossed_item
609                    && matches!(
610                        res,
611                        fhir::Res::Def(DefKind::TyParam | DefKind::ConstParam, _)
612                            | fhir::Res::SelfTyParam { .. }
613                            | fhir::Res::SelfTyAlias { .. }
614                    )
615                {
616                    return Err(ResolveError::OuterGeneric(ident.span));
617                }
618                return Ok(res);
619            }
620            match rib.kind {
621                // A module boundary stops item resolution.
622                RibKind::Module => break,
623                RibKind::Item => crossed_item = true,
624                // A variant is a barrier that hides refinement params bound in the `refined_by` *enclosing*
625                // scope, but not other refinement bindings in other scopes (e.g. flux funcs in the parent module).
626                // FIXME: this is skipping potential names defined inside a `const _ = { ... }` or other similar
627                // "transparent modules".
628                RibKind::Variant => {
629                    ribs.take_while_ref(|rib| !matches!(rib.kind, RibKind::Module))
630                        .for_each(drop);
631                }
632                _ => {}
633            }
634        }
635        if ns == TypeNS {
636            if let Some(crate_id) = self.crates.get(&ident.name) {
637                return Ok(fhir::Res::Def(DefKind::Mod, *crate_id));
638            }
639            // FIXME: `crate`, `self` and `super` should only be allowed as the first segment
640            if ident.name == kw::Crate {
641                return Ok(fhir::Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()));
642            }
643            if ident.name == kw::SelfLower {
644                return Ok(fhir::Res::Def(DefKind::Mod, self.current_module.to_def_id()));
645            }
646            if ident.name == kw::Super
647                && let Some(parent) = self.genv.tcx().opt_local_parent(self.current_module.def_id)
648            {
649                return Ok(fhir::Res::Def(DefKind::Mod, parent.to_def_id()));
650            }
651        }
652
653        if let Some(name_res) = self.prelude[ns].bindings.get(&ident.name)
654            && let Some(res) = name_res.resolve(ident)
655        {
656            return res.map_err(ResolveError::Ambiguous);
657        }
658        Err(ResolveError::NotFound)
659    }
660
661    /// Defines the names brought into scope by a `use` tree. `prefix` accumulates the segments of
662    /// the enclosing nested trees, because the path of a nested tree is relative to its parent.
663    fn define_use_tree(
664        &mut self,
665        use_tree: &hir::UseTree<'tcx>,
666        prefix: &mut Vec<hir::PathSegment<'tcx>>,
667        is_prelude: bool,
668        glob_span: Span,
669    ) {
670        let path = use_tree.prefix;
671        match use_tree.kind {
672            hir::UseKind::Single(mut ident) => {
673                // For a nested `self` import, e.g., `use foo::{self}`, rustc doesn't strip the
674                // `self` because the path of the nested tree is relative. The name it defines is
675                // the last segment of the enclosing prefix (`foo`).
676                if ident.name == kw::SelfLower
677                    && let Some(last) = prefix.last()
678                {
679                    ident = Ident::new(last.ident.name, ident.span);
680                }
681                if let Some(res) = path.res.value_ns
682                    && let Ok(res) = fhir::Res::try_from(res)
683                {
684                    self.define_res_in(res, ValueNS, BindingSource::Explicit(ident));
685                }
686                if let Some(res) = path.res.type_ns
687                    && let Ok(res) = fhir::Res::try_from(res)
688                {
689                    self.define_res_in(res, TypeNS, BindingSource::Explicit(ident));
690                }
691            }
692            hir::UseKind::Glob => {
693                let len = prefix.len();
694                prefix.extend_from_slice(path.segments);
695                for mod_child in self.glob_imports(prefix) {
696                    if let Ok(res) = fhir::Res::try_from(mod_child.res)
697                        && let Some(ns @ (TypeNS | ValueNS)) = res.ns()
698                    {
699                        if is_prelude {
700                            self.define_in_prelude(mod_child.ident, res, ns);
701                        } else {
702                            let source = BindingSource::Glob { ident: mod_child.ident, glob_span };
703                            self.define_res_in(res, ns, source);
704                        }
705                    }
706                }
707                prefix.truncate(len);
708            }
709            hir::UseKind::Nested { items } => {
710                let len = prefix.len();
711                prefix.extend_from_slice(path.segments);
712                for (nested, _, _) in items {
713                    self.define_use_tree(nested, prefix, is_prelude, glob_span);
714                }
715                prefix.truncate(len);
716            }
717        }
718    }
719
720    fn glob_imports(
721        &mut self,
722        segments: &[hir::PathSegment<'tcx>],
723    ) -> impl Iterator<Item = &'tcx ModChild> + use<'tcx> {
724        // The path for the prelude import is not resolved anymore after <https://github.com/rust-lang/rust/pull/145322>,
725        // so we resolve all paths here. If this ever causes problems, we could use the resolution in the `UsePath` for
726        // non-prelude glob imports.
727        let tcx = self.genv.tcx();
728        let curr_mod = self.current_module.to_def_id();
729        self.resolve_path_with_ribs_inner(segments, TypeNS)
730            .ok()
731            .and_then(|partial_res| partial_res.full_res())
732            .and_then(|res| {
733                if let fhir::Res::Def(DefKind::Mod, module_id) = res {
734                    Some(module_id)
735                } else {
736                    None
737                }
738            })
739            .into_iter()
740            .flat_map(move |module_id| visible_module_children(tcx, module_id, curr_mod))
741    }
742
743    fn resolve_ident_in_module(
744        &self,
745        module: Module,
746        ident: Ident,
747        ns: Namespace,
748    ) -> std::result::Result<fhir::Res<surface::NodeId>, ResolveError> {
749        let tcx = self.genv.tcx();
750        let res = match module.kind {
751            ModuleKind::Mod => {
752                let module_id = module.def_id;
753                let current_mod = self.current_module.to_def_id();
754
755                // Three sources, tried in order, first one with the name wins: the module's Rust
756                // children, then the ambiguous ones rustc leaves out of `module_children`, then
757                // its flux items. Only the first two have a Rust namespace to look in.
758                //
759                // Keeping them apart matters because the folds below read every candidate as a
760                // glob, so one pool would make `mod m { struct Bag; defs! { opaque sort Bag; } }`
761                // ambiguous at each `m::Bag`. It isn't: two explicit definitions clash as a
762                // duplicate definition, already reported when `m`'s rib was built.
763                let mut resolution: NameResolution = ns
764                    .to_rustc()
765                    .into_iter()
766                    .flat_map(|rustc_ns| {
767                        visible_module_children(tcx, module_id, current_mod).filter(move |child| {
768                            child.res.matches_ns(rustc_ns)
769                                && tcx.hygienic_eq(ident, child.ident, current_mod)
770                        })
771                    })
772                    .filter_map(|child| {
773                        Some(Binding {
774                            span: child.ident.span,
775                            res: fhir::Res::try_from(child.res).ok()?,
776                        })
777                    })
778                    .collect();
779                if resolution.is_empty() {
780                    // Still a Rust name, so it comes before any flux item.
781                    if let Some(ambiguity) = self.ambiguous_module_child(module_id, ident, ns) {
782                        return Err(ResolveError::Ambiguous(ambiguity));
783                    }
784                    resolution = self
785                        .genv
786                        .flux_module_children(module_id)
787                        .iter()
788                        .filter(|child| {
789                            child.res.ns() == Some(ns) && child.ident.name == ident.name
790                        })
791                        .map(|child| {
792                            Binding {
793                                span: child.ident.span,
794                                res: child.res.map_param_id(|id| match id {}),
795                            }
796                        })
797                        .collect();
798                }
799                resolution.resolve(ident)
800            }
801            ModuleKind::Trait => {
802                // Associated items are Rust items, so we only ever resolve them in a Rust namespace.
803                ns.to_rustc()
804                    .and_then(|rustc_ns| {
805                        let trait_id = module.def_id;
806                        tcx.associated_items(trait_id)
807                            .find_by_ident_and_namespace(tcx, ident, rustc_ns, trait_id)
808                            .map(|assoc| fhir::Res::Def(assoc.kind.as_def_kind(), assoc.def_id))
809                    })
810                    .map(Ok)
811            }
812            ModuleKind::Enum => {
813                tcx.adt_def(module.def_id)
814                    .variants()
815                    .iter()
816                    .find(|data| data.name == ident.name)
817                    .and_then(|data| {
818                        let (kind, def_id) = match (ns, data.ctor) {
819                            (TypeNS, _) => (DefKind::Variant, data.def_id),
820                            (ValueNS, Some((ctor_kind, ctor_id))) => {
821                                (DefKind::Ctor(CtorOf::Variant, ctor_kind), ctor_id)
822                            }
823                            _ => return None,
824                        };
825                        Some(fhir::Res::Def(kind, def_id))
826                    })
827                    .map(Ok)
828            }
829        };
830        match res {
831            Some(res) => res.map_err(ResolveError::Ambiguous),
832            None => Err(ResolveError::NotFound),
833        }
834    }
835
836    /// The ambiguity for `ident` in `module_id`, if the module's *own* glob re-exports bind the
837    /// name to two different items (`mod m { pub use a::*; pub use b::*; }`). rustc keeps such
838    /// bindings out of `module_children` — they go into a separate `ambig_module_children` map —
839    /// so they need their own lookup.
840    ///
841    /// Only *local* modules are covered. The data for a foreign module is reachable only through an
842    /// untracked `CStore` accessor, and rustc doesn't report `E0659` across a crate boundary
843    /// anyway: it resolves to the first candidate and fires the `ambiguous_glob_imports`
844    /// future-incompatibility lint instead (see rust-lang/rust#114095). We report those as
845    /// unresolved.
846    #[expect(clippy::disallowed_methods, reason = "modules cannot have extern specs")]
847    fn ambiguous_module_child(
848        &self,
849        module_id: DefId,
850        ident: Ident,
851        ns: Namespace,
852    ) -> Option<Ambiguity> {
853        let tcx = self.genv.tcx();
854        let module_id = module_id.as_local()?;
855        let rustc_ns = ns.to_rustc()?;
856        let current_mod = self.current_module.to_def_id();
857        let child = tcx
858            .resolutions(())
859            .ambig_module_children
860            .get(&module_id)?
861            .iter()
862            .find(|child| {
863                child.main.res.matches_ns(rustc_ns)
864                    && tcx.hygienic_eq(ident, child.main.ident, current_mod)
865                    && child.main.vis.is_accessible_from(current_mod, tcx)
866            })?;
867        Some(Ambiguity {
868            span: ident.span,
869            name: ident.name,
870            first: self.glob_span(&child.main),
871            second: self.glob_span(&child.second),
872        })
873    }
874
875    /// Where a module child was brought into its module: the `use ...::*;` statement it was
876    /// re-exported by, or the item's own definition. Mirrors rustc's `child_span`.
877    fn glob_span(&self, child: &ModChild) -> Span {
878        let def_id = child
879            .reexport_chain
880            .first()
881            .and_then(|reexport| reexport.id())
882            .unwrap_or_else(|| child.res.def_id());
883        self.genv.tcx().def_span(def_id)
884    }
885
886    pub fn into_output(self) -> Result<ResolverOutput> {
887        self.err.into_result()?;
888        Ok(self.output)
889    }
890
891    #[track_caller]
892    fn emit_resolve_err<D: rustc_errors::Diagnostic<'genv>>(
893        &mut self,
894        err: ResolveError,
895        not_found: impl FnOnce() -> D,
896    ) {
897        self.err.collect(err.emit(self.genv.sess(), not_found));
898    }
899
900    fn emit_not_a_module(&mut self, ident: Ident, resolved_prefix: &[Ident]) {
901        let name = Segment::format_iter(resolved_prefix.iter().chain(&[ident]));
902        self.emit(errors::UnresolvedImport {
903            span: ident.span,
904            name,
905            reason: format!("`{ident}` is not a module"),
906        });
907    }
908
909    #[track_caller]
910    fn emit(&mut self, err: impl rustc_errors::Diagnostic<'genv>) {
911        self.err.collect(self.genv.sess().emit_err(err));
912    }
913}
914
915impl<'tcx> hir::intravisit::Visitor<'tcx> for CrateResolver<'_, 'tcx> {
916    type NestedFilter = rustc_middle::hir::nested_filter::All;
917
918    fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
919        self.genv.tcx()
920    }
921
922    fn visit_mod(
923        &mut self,
924        module: &'tcx hir::Mod<'tcx>,
925        _s: Span,
926        mod_id: hir::def_id::LocalModId,
927    ) {
928        let owner_id = OwnerId { def_id: mod_id.to_local_def_id() };
929        let old_mod = self.current_module;
930        self.current_module = owner_id;
931        self.push_rib(TypeNS, RibKind::Module);
932        self.push_rib(ValueNS, RibKind::Module);
933        self.push_rib(ReftNS, RibKind::Module);
934        self.push_rib(HintNS, RibKind::Module);
935
936        self.define_items(module.item_ids);
937
938        // Flux items are defined in the module they are declared in.
939        let scope = hir::HirId::make_owner(owner_id.def_id);
940        self.define_flux_items(scope);
941
942        self.resolve_flux_items(scope);
943        hir::intravisit::walk_mod(self, module);
944
945        self.pop_rib(HintNS);
946        self.pop_rib(ReftNS);
947        self.pop_rib(ValueNS);
948        self.pop_rib(TypeNS);
949        self.current_module = old_mod;
950    }
951
952    fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
953        self.push_rib(TypeNS, RibKind::Misc);
954        self.push_rib(ValueNS, RibKind::Misc);
955        self.push_rib(ReftNS, RibKind::Misc);
956        self.push_rib(HintNS, RibKind::Misc);
957
958        let item_ids = block.stmts.iter().filter_map(|stmt| {
959            if let hir::StmtKind::Item(item_id) = &stmt.kind { Some(item_id) } else { None }
960        });
961        self.define_items(item_ids);
962        self.define_flux_items(block.hir_id);
963
964        self.resolve_flux_items(block.hir_id);
965        hir::intravisit::walk_block(self, block);
966
967        self.pop_rib(HintNS);
968        self.pop_rib(ReftNS);
969        self.pop_rib(ValueNS);
970        self.pop_rib(TypeNS);
971    }
972
973    fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
974        if self.genv.is_dummy(item.owner_id.def_id) {
975            return;
976        }
977        let def_id = self
978            .genv
979            .maybe_extern_id(item.owner_id.def_id)
980            .map(|def_id| OwnerId { def_id });
981
982        self.push_rib(TypeNS, RibKind::Item);
983        self.push_rib(ValueNS, RibKind::Item);
984
985        match item.kind {
986            ItemKind::Trait { .. } => {
987                self.define_generics(def_id);
988                self.define_res_in(
989                    fhir::Res::SelfTyParam { trait_: def_id.resolved_id() },
990                    TypeNS,
991                    BindingSource::Explicit(Ident::with_dummy_span(kw::SelfUpper)),
992                );
993            }
994            ItemKind::Impl(hir::Impl { of_trait, .. }) => {
995                self.define_generics(def_id);
996                self.define_res_in(
997                    fhir::Res::SelfTyAlias {
998                        alias_to: def_id.resolved_id(),
999                        is_trait_impl: of_trait.is_some(),
1000                    },
1001                    TypeNS,
1002                    BindingSource::Explicit(Ident::with_dummy_span(kw::SelfUpper)),
1003                );
1004            }
1005            ItemKind::TyAlias(..) => {
1006                self.define_generics(def_id);
1007            }
1008            ItemKind::Enum(..) => {
1009                self.define_generics(def_id);
1010                self.define_res_in(
1011                    fhir::Res::SelfTyAlias { alias_to: def_id.resolved_id(), is_trait_impl: false },
1012                    TypeNS,
1013                    BindingSource::Explicit(Ident::with_dummy_span(kw::SelfUpper)),
1014                );
1015            }
1016            ItemKind::Struct(..) => {
1017                self.define_generics(def_id);
1018                self.define_res_in(
1019                    fhir::Res::SelfTyAlias { alias_to: def_id.resolved_id(), is_trait_impl: false },
1020                    TypeNS,
1021                    BindingSource::Explicit(Ident::with_dummy_span(kw::SelfUpper)),
1022                );
1023            }
1024            ItemKind::Fn { .. } => {
1025                self.define_generics(def_id);
1026            }
1027            _ => {}
1028        }
1029        if let Some(item) = self.specs.get_item(def_id.local_id()) {
1030            self.resolve_item(item, def_id).collect_err(&mut self.err);
1031        }
1032
1033        hir::intravisit::walk_item(self, item);
1034
1035        self.pop_rib(ValueNS);
1036        self.pop_rib(TypeNS);
1037    }
1038
1039    fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1040        let def_id = self
1041            .genv
1042            .maybe_extern_id(impl_item.owner_id.def_id)
1043            .map(|def_id| OwnerId { def_id });
1044
1045        // Generics are defined in both namespaces (const params live in the value namespace), so
1046        // we need a rib in each to avoid leaking them into sibling items.
1047        self.push_rib(TypeNS, RibKind::Misc);
1048        self.push_rib(ValueNS, RibKind::Misc);
1049        if let Some(item) = self.specs.get_impl_item(def_id.local_id()) {
1050            self.define_generics(def_id);
1051            self.resolve_impl_item(item, def_id)
1052                .collect_err(&mut self.err);
1053        }
1054        hir::intravisit::walk_impl_item(self, impl_item);
1055        self.pop_rib(ValueNS);
1056        self.pop_rib(TypeNS);
1057    }
1058
1059    fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
1060        let def_id = self
1061            .genv
1062            .maybe_extern_id(trait_item.owner_id.def_id)
1063            .map(|def_id| OwnerId { def_id });
1064
1065        // Generics are defined in both namespaces (const params live in the value namespace), so
1066        // we need a rib in each to avoid leaking them into sibling items.
1067        self.push_rib(TypeNS, RibKind::Misc);
1068        self.push_rib(ValueNS, RibKind::Misc);
1069        if let Some(item) = self.specs.get_trait_item(def_id.local_id()) {
1070            self.define_generics(def_id);
1071            self.resolve_trait_item(item, def_id)
1072                .collect_err(&mut self.err);
1073        }
1074        hir::intravisit::walk_trait_item(self, trait_item);
1075        self.pop_rib(ValueNS);
1076        self.pop_rib(TypeNS);
1077    }
1078}
1079
1080/// Akin to `rustc_resolve::Module` but specialized to what we support
1081#[derive(Clone, Copy, Debug)]
1082struct Module {
1083    kind: ModuleKind,
1084    def_id: DefId,
1085}
1086
1087impl Module {
1088    fn new(kind: ModuleKind, def_id: DefId) -> Self {
1089        Self { kind, def_id }
1090    }
1091}
1092
1093/// Akin to `rustc_resolve::ModuleKind` but specialized to what we support
1094#[derive(Clone, Copy, Debug)]
1095enum ModuleKind {
1096    Mod,
1097    Trait,
1098    Enum,
1099}
1100
1101#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1102pub(crate) enum RibKind {
1103    /// An rib with no special rules.
1104    Misc,
1105    /// A module boundary. This is a barrier for item resolution.
1106    Module,
1107    /// An item boundary. Generic parameters (and `Self`) of outer items are not visible past it.
1108    Item,
1109    /// An enum variant. This is a barrier scope because variants are nested within `refined_by`
1110    /// params.
1111    Variant,
1112}
1113
1114/// The value stored for each binding in a [`Rib`]. Lookups and clash detection are keyed by the
1115/// name in the [`Rib`]'s map, so all a binding carries is where it came from, for diagnostics that
1116/// point at the previous location of a name.
1117#[derive(Clone, Copy, Debug)]
1118struct Binding {
1119    /// Where the name was brought into scope: the item, generic or param itself, or, for a
1120    /// glob-imported binding, the `use ...::*;` statement rather than the imported item's
1121    /// declaration, matching where rustc points its `E0659` notes.
1122    span: Span,
1123    res: fhir::Res<surface::NodeId>,
1124}
1125
1126/// How a name was brought into a rib. Explicit definitions (items, generics, params, single
1127/// `use`s, flux `use`s) shadow glob imports of the same name in the same namespace, regardless of
1128/// declaration order; only globs can be ambiguous with each other.
1129#[derive(Clone, Copy, Debug)]
1130enum BindingSource {
1131    /// A name written where it is defined: an item, generic, param or single `use`.
1132    Explicit(Ident),
1133    /// A glob-imported name: the imported item's ident, plus the span of the `use ...::*;`
1134    /// statement that brought it in, which is the one diagnostics cite.
1135    Glob { ident: Ident, glob_span: Span },
1136}
1137
1138impl BindingSource {
1139    fn ident(self) -> Ident {
1140        match self {
1141            BindingSource::Explicit(ident) | BindingSource::Glob { ident, .. } => ident,
1142        }
1143    }
1144
1145    /// Where the name was brought into scope.
1146    fn span(self) -> Span {
1147        match self {
1148            BindingSource::Explicit(ident) => ident.span,
1149            BindingSource::Glob { glob_span, .. } => glob_span,
1150        }
1151    }
1152}
1153
1154/// The glob-imported candidate(s) for a name, mirroring rustc's `glob_decl` slot.
1155#[derive(Clone, Copy, Debug)]
1156enum GlobBinding {
1157    Single(Binding),
1158    /// Two competing globs bound this name to different items. Frozen once set: further
1159    /// candidates never change it. We deliberately diverge from rustc here, which keeps updating
1160    /// the second span as new distinct competitors show up; with three or more globs we therefore
1161    /// report the first two rather than the first and the last.
1162    Ambiguous(Span, Span),
1163}
1164
1165/// All candidates for a single name in a single namespace, split into the two slots
1166/// (`non_glob_decl`/`glob_decl`). The non-glob slot always wins.
1167#[derive(Clone, Copy, Debug, Default)]
1168struct NameResolution {
1169    non_glob: Option<Binding>,
1170    glob: Option<GlobBinding>,
1171}
1172
1173impl NameResolution {
1174    fn from_explicit(binding: Binding) -> Self {
1175        Self { non_glob: Some(binding), glob: None }
1176    }
1177
1178    fn is_empty(&self) -> bool {
1179        self.non_glob.is_none() && self.glob.is_none()
1180    }
1181
1182    /// Define the binding. Return previously defined binding if there's a clash
1183    fn define(
1184        &mut self,
1185        source: BindingSource,
1186        res: fhir::Res<surface::NodeId>,
1187    ) -> Option<Binding> {
1188        let binding = Binding { span: source.span(), res };
1189        match source {
1190            BindingSource::Explicit(_) => {
1191                if let Some(prev) = self.non_glob {
1192                    Some(prev)
1193                } else {
1194                    self.non_glob = Some(binding);
1195                    None
1196                }
1197            }
1198            BindingSource::Glob { .. } => {
1199                self.add_glob(binding);
1200                None
1201            }
1202        }
1203    }
1204
1205    /// Fold one more glob candidate into the glob slot. A candidate resolving to the same item as
1206    /// the one already recorded (the same item reached through two different globs) is not an
1207    /// ambiguity.
1208    fn add_glob(&mut self, binding: Binding) {
1209        self.glob = Some(match self.glob {
1210            None => GlobBinding::Single(binding),
1211            Some(GlobBinding::Single(prev)) => {
1212                if prev.res == binding.res {
1213                    GlobBinding::Single(prev)
1214                } else {
1215                    GlobBinding::Ambiguous(prev.span, binding.span)
1216                }
1217            }
1218            Some(ambiguous @ GlobBinding::Ambiguous(..)) => ambiguous,
1219        });
1220    }
1221
1222    /// The resolution for `ident`, or `None` if this holds no candidate at all (in which case the
1223    /// caller should keep looking in outer scopes).
1224    fn resolve(
1225        &self,
1226        ident: Ident,
1227    ) -> Option<std::result::Result<fhir::Res<surface::NodeId>, Ambiguity>> {
1228        if let Some(binding) = self.non_glob {
1229            return Some(Ok(binding.res));
1230        }
1231        match self.glob? {
1232            GlobBinding::Single(binding) => Some(Ok(binding.res)),
1233            GlobBinding::Ambiguous(first, second) => {
1234                Some(Err(Ambiguity { span: ident.span, name: ident.name, first, second }))
1235            }
1236        }
1237    }
1238}
1239
1240impl FromIterator<Binding> for NameResolution {
1241    /// Fold a stream of *glob* candidates. Used to merge a module's children, where two entries
1242    /// for the same name can only come from an ambiguous glob re-export.
1243    fn from_iter<T: IntoIterator<Item = Binding>>(iter: T) -> Self {
1244        let mut resolution = Self::default();
1245        for binding in iter {
1246            resolution.add_glob(binding);
1247        }
1248        resolution
1249    }
1250}
1251
1252#[derive(Debug)]
1253struct Rib {
1254    kind: RibKind,
1255    bindings: UnordMap<Symbol, NameResolution>,
1256}
1257
1258impl Rib {
1259    fn new(kind: RibKind) -> Self {
1260        Self { kind, bindings: Default::default() }
1261    }
1262}
1263
1264fn module_children(tcx: TyCtxt<'_>, def_id: DefId) -> &[ModChild] {
1265    #[expect(clippy::disallowed_methods, reason = "modules cannot have extern specs")]
1266    if let Some(local_id) = def_id.as_local() {
1267        tcx.module_children_local(local_id)
1268    } else {
1269        tcx.module_children(def_id)
1270    }
1271}
1272
1273/// Iterator over module children visible form `curr_mod`
1274fn visible_module_children(
1275    tcx: TyCtxt<'_>,
1276    module_id: DefId,
1277    curr_mod: DefId,
1278) -> impl Iterator<Item = &ModChild> {
1279    module_children(tcx, module_id)
1280        .iter()
1281        .filter(move |child| child.vis.is_accessible_from(curr_mod, tcx))
1282}
1283
1284/// Return true if the item has a `#[prelude_import]` annotation
1285fn is_prelude_import(tcx: TyCtxt, item: &hir::Item) -> bool {
1286    tcx.hir_attrs(item.hir_id()).iter().any(|attr| {
1287        matches!(
1288            attr,
1289            rustc_attr_ir::Attribute::Parsed(rustc_attr_ir::AttributeKind::PreludeImport)
1290        )
1291    })
1292}
1293
1294/// Abstraction over a "segment" so we can use [`CrateResolver::resolve_path_with_ribs`] with paths
1295/// from different sources  (e.g., [`surface::PathSegment`], [`surface::ExprPathSegment`])
1296pub(crate) trait Segment: std::fmt::Debug {
1297    fn record_segment_res(
1298        resolver: &mut CrateResolver,
1299        segment: &Self,
1300        res: fhir::Res<surface::NodeId>,
1301    );
1302    fn ident(&self) -> Ident;
1303
1304    fn format_iter<'a>(segments: impl IntoIterator<Item = &'a Self>) -> String
1305    where
1306        Self: Sized + 'a,
1307    {
1308        segments.into_iter().map(|s| s.ident()).join("::")
1309    }
1310}
1311
1312impl Segment for surface::PathSegment {
1313    fn record_segment_res(
1314        resolver: &mut CrateResolver,
1315        segment: &Self,
1316        res: fhir::Res<surface::NodeId>,
1317    ) {
1318        resolver
1319            .output
1320            .path_res_map
1321            .insert(segment.node_id, fhir::PartialRes::new(res));
1322    }
1323
1324    fn ident(&self) -> Ident {
1325        self.ident
1326    }
1327}
1328
1329impl Segment for surface::ExprPathSegment {
1330    fn record_segment_res(
1331        resolver: &mut CrateResolver,
1332        segment: &Self,
1333        res: fhir::Res<surface::NodeId>,
1334    ) {
1335        resolver
1336            .output
1337            .path_res_map
1338            .insert(segment.node_id, fhir::PartialRes::new(res));
1339    }
1340
1341    fn ident(&self) -> Ident {
1342        self.ident
1343    }
1344}
1345
1346impl Segment for Ident {
1347    fn record_segment_res(
1348        _resolver: &mut CrateResolver,
1349        _segment: &Self,
1350        _res: fhir::Res<surface::NodeId>,
1351    ) {
1352    }
1353
1354    fn ident(&self) -> Ident {
1355        *self
1356    }
1357}
1358
1359impl Segment for hir::PathSegment<'_> {
1360    fn record_segment_res(
1361        _resolver: &mut CrateResolver,
1362        _segment: &Self,
1363        _res: fhir::Res<surface::NodeId>,
1364    ) {
1365    }
1366
1367    fn ident(&self) -> Ident {
1368        self.ident
1369    }
1370}
1371
1372struct ItemResolver<'a, 'genv, 'tcx> {
1373    resolver: &'a mut CrateResolver<'genv, 'tcx>,
1374    errors: Errors<'genv>,
1375    item_id: MaybeExternId<OwnerId>,
1376}
1377
1378impl<'a, 'genv, 'tcx> ItemResolver<'a, 'genv, 'tcx> {
1379    fn run(
1380        resolver: &'a mut CrateResolver<'genv, 'tcx>,
1381        item_id: MaybeExternId<OwnerId>,
1382        f: impl FnOnce(&mut ItemResolver),
1383    ) -> Result {
1384        let mut item_resolver = ItemResolver::new(resolver, item_id);
1385        f(&mut item_resolver);
1386        item_resolver.errors.into_result()
1387    }
1388
1389    fn new(resolver: &'a mut CrateResolver<'genv, 'tcx>, item_id: MaybeExternId<OwnerId>) -> Self {
1390        let errors = Errors::new(resolver.genv.sess());
1391        Self { resolver, errors, item_id }
1392    }
1393
1394    fn resolve_path_in(&mut self, ns: Namespace, path: &surface::Path) {
1395        match self.resolver.resolve_path_with_ribs(&path.segments, ns) {
1396            Ok(partial_res) => {
1397                self.resolver
1398                    .output
1399                    .path_res_map
1400                    .insert(path.node_id, partial_res);
1401            }
1402            Err(err) => {
1403                err.emit(&self.errors, || {
1404                    errors::UnresolvedName::new(path.span, &path.segments, ns.descr())
1405                });
1406            }
1407        }
1408    }
1409
1410    fn resolve_attrs(&mut self, node_id: surface::NodeId, attrs: &[surface::Attr]) {
1411        for attr in attrs {
1412            match attr {
1413                surface::Attr::Qualifiers(names) => self.resolve_qualifiers(node_id, names),
1414                surface::Attr::Axioms(names) => self.resolve_axioms(node_id, names),
1415                surface::Attr::Properties(names) => self.resolve_properties(node_id, names),
1416                surface::Attr::Reveal(names) => {
1417                    let reveals = self.resolve_func_defs(names);
1418                    self.resolver.output.reveal_res_map.insert(node_id, reveals);
1419                }
1420                surface::Attr::Hide(names) => {
1421                    let hides = self.resolve_func_defs(names);
1422                    self.resolver.output.hide_res_map.insert(node_id, hides);
1423                }
1424                surface::Attr::AssumeParametric(names) => {
1425                    self.resolve_parametric_params(node_id, names);
1426                }
1427                _ => {}
1428            }
1429        }
1430    }
1431
1432    fn resolve_parametric_params(&mut self, node_id: surface::NodeId, names: &[Ident]) {
1433        let tcx = self.resolver.genv.tcx();
1434        let generics = tcx.generics_of(self.item_id.resolved_id());
1435        let param_map: UnordMap<Symbol, DefId> = (0..generics.count())
1436            .map(|i| generics.param_at(i, tcx))
1437            .map(|p| (p.name, p.def_id))
1438            .collect();
1439        let mut params = Vec::with_capacity(names.len());
1440        for name in names {
1441            if let Some(&def_id) = param_map.get(&name.name) {
1442                params.push(def_id);
1443            } else {
1444                self.errors
1445                    .emit(errors::UnknownParametricParam::new(name.span));
1446            }
1447        }
1448        self.resolver
1449            .output
1450            .parametric_param_res_map
1451            .insert(node_id, params);
1452    }
1453
1454    /// Resolves the paths in a `#[qualifiers(...)]` attribute
1455    fn resolve_qualifiers(&mut self, node_id: surface::NodeId, paths: &[surface::ExprPath]) {
1456        let qualifiers = self.resolve_hints(
1457            paths,
1458            |res| {
1459                if let fhir::Res::Qualifier(def_id) = res { Some(def_id) } else { None }
1460            },
1461            errors::UnknownQualifier::new,
1462        );
1463        self.resolver
1464            .output
1465            .qualifier_res_map
1466            .insert(node_id, qualifiers);
1467    }
1468
1469    /// Resolves the paths in a `#[axioms(...)]` attribute
1470    fn resolve_axioms(&mut self, node_id: surface::NodeId, paths: &[surface::ExprPath]) {
1471        let axioms = self.resolve_hints(
1472            paths,
1473            |res| {
1474                if let fhir::Res::Axiom(def_id) = res { Some(def_id) } else { None }
1475            },
1476            errors::UnknownAxiom::new,
1477        );
1478        self.resolver.output.axiom_res_map.insert(node_id, axioms);
1479    }
1480
1481    /// Resolves the paths in a `#[properties(...)]` attribute
1482    fn resolve_properties(&mut self, node_id: surface::NodeId, paths: &[surface::ExprPath]) {
1483        let properties = self.resolve_hints(
1484            paths,
1485            |res| {
1486                if let fhir::Res::Property(def_id) = res { Some(def_id) } else { None }
1487            },
1488            errors::UnknownProperty::new,
1489        );
1490        self.resolver
1491            .output
1492            .property_res_map
1493            .insert(node_id, properties);
1494    }
1495
1496    /// Resolves paths to hints (qualifiers, axioms or properties) using the same scoping rules as other flux
1497    /// items, keeping those for which `select` returns a definition and reporting `mk_err` for the
1498    /// rest.
1499    fn resolve_hints<E: for<'b> rustc_errors::Diagnostic<'b>>(
1500        &mut self,
1501        paths: &[surface::ExprPath],
1502        select: impl Fn(fhir::Res<surface::NodeId>) -> Option<FluxDefId>,
1503        mk_err: impl Fn(Span) -> E,
1504    ) -> Vec<FluxDefId> {
1505        let mut def_ids = Vec::with_capacity(paths.len());
1506        for path in paths {
1507            match self.resolver.resolve_path_with_ribs(&path.segments, HintNS) {
1508                Ok(partial_res) => {
1509                    match partial_res.full_res().and_then(&select) {
1510                        Some(def_id) => def_ids.push(def_id),
1511                        None => {
1512                            self.errors.emit(mk_err(path.span));
1513                        }
1514                    }
1515                }
1516                Err(err) => {
1517                    err.emit(&self.errors, || mk_err(path.span));
1518                }
1519            }
1520        }
1521        def_ids
1522    }
1523
1524    /// Resolves the paths to function definitions in a `#[reveal(...)]` or `#[hide(...)]` attribute
1525    fn resolve_func_defs(&mut self, paths: &[surface::ExprPath]) -> Vec<(FluxDefId, Span)> {
1526        let mut def_ids = Vec::with_capacity(paths.len());
1527        for path in paths {
1528            match self.resolver.resolve_path_with_ribs(&path.segments, ReftNS) {
1529                Ok(partial_res) => {
1530                    match partial_res.full_res() {
1531                        Some(fhir::Res::GlobalFunc(kind)) if let Some(def_id) = kind.def_id() => {
1532                            def_ids.push((def_id, path.span));
1533                        }
1534                        _ => {
1535                            self.errors
1536                                .emit(errors::UnknownFuncDefinition::new(path.span));
1537                        }
1538                    }
1539                }
1540                Err(err) => {
1541                    err.emit(&self.errors, || errors::UnknownFuncDefinition::new(path.span));
1542                }
1543            }
1544        }
1545        def_ids
1546    }
1547}
1548
1549impl surface::visit::Visitor<'_> for ItemResolver<'_, '_, '_> {
1550    fn visit_item(&mut self, item: &surface::Item) {
1551        self.resolve_attrs(item.node_id, &item.attrs);
1552        surface::visit::walk_item(self, item);
1553    }
1554
1555    fn visit_trait_item(&mut self, item: &surface::TraitItemFn) {
1556        self.resolve_attrs(item.node_id, &item.attrs);
1557        surface::visit::walk_trait_item(self, item);
1558    }
1559
1560    fn visit_impl_item(&mut self, item: &surface::ImplItemFn) {
1561        self.resolve_attrs(item.node_id, &item.attrs);
1562        surface::visit::walk_impl_item(self, item);
1563    }
1564
1565    fn visit_trait(&mut self, trait_: &surface::Trait) {
1566        let mut definitions = DefinitionMap::default();
1567        for assoc_reft in &trait_.assoc_refinements {
1568            let _ = definitions.define(assoc_reft.name).emit(&self.errors);
1569        }
1570        surface::visit::walk_trait(self, trait_);
1571    }
1572
1573    fn visit_impl(&mut self, impl_: &surface::Impl) {
1574        let mut definitions = DefinitionMap::default();
1575        for assoc_reft in &impl_.assoc_refinements {
1576            let _ = definitions.define(assoc_reft.name).emit(&self.errors);
1577        }
1578        surface::visit::walk_impl(self, impl_);
1579    }
1580
1581    fn visit_generic_arg(&mut self, arg: &surface::GenericArg) {
1582        if let surface::GenericArgKind::Type(ty) = &arg.kind
1583            && let Some(path) = ty.is_potential_const_arg()
1584        {
1585            // We parse const arguments as path types as we cannot distinguish them during
1586            // parsing. We try to resolve that ambiguity by attempting resolution in both the
1587            // type and value namespaces. If we resolved the path in the value namespace, we
1588            // transform it into a generic const argument.
1589            // A name that is *ambiguous* in a namespace, or that is a forbidden outer generic,
1590            // still counts as present there: rerouting to the other namespace would hide the error
1591            // instead of reporting it. The real diagnostic comes from `resolve_path_in` below.
1592            let check_ns = |ns| {
1593                !matches!(
1594                    self.resolver.resolve_ident_with_ribs(path.last().ident, ns),
1595                    Err(ResolveError::NotFound)
1596                )
1597            };
1598
1599            if !check_ns(TypeNS) && check_ns(ValueNS) {
1600                self.resolve_path_in(ValueNS, path);
1601                return;
1602            }
1603        }
1604        surface::visit::walk_generic_arg(self, arg);
1605    }
1606
1607    fn visit_const_arg(&mut self, const_arg: &surface::ConstArg) {
1608        if let surface::ConstArgKind::Path(path) = &const_arg.kind {
1609            self.resolve_path_in(ValueNS, path);
1610            surface::visit::walk_path(self, path);
1611        }
1612    }
1613
1614    fn visit_path(&mut self, path: &surface::Path) {
1615        self.resolve_path_in(TypeNS, path);
1616        surface::visit::walk_path(self, path);
1617    }
1618}
1619
1620/// The [`Namespace::TypeNS`] prelude: builtin Rust types (`bool`, `i32`, `str`, ...) together with
1621/// the sort-only primitive sorts (`int`, `real`, `Set`, `Map`, `ptr`). Sorts and types share the
1622/// type namespace; `bool`/`char`/`str` are resolved as [`fhir::Res::PrimTy`] and their sort is
1623/// derived in `conv_sort_path` (see [`fhir::PrimSort`]).
1624fn builtin_types_rib() -> Rib {
1625    use flux_middle::fhir::PrimSort;
1626    let sorts = PrimSort::ALL.into_iter().map(|prim| {
1627        let ident = Ident::with_dummy_span(prim.name());
1628        (
1629            ident.name,
1630            NameResolution::from_explicit(Binding {
1631                span: ident.span,
1632                res: fhir::Res::PrimSort(prim),
1633            }),
1634        )
1635    });
1636    let types = PrimTy::ALL.into_iter().map(|pty| {
1637        let ident = Ident::with_dummy_span(pty.name());
1638        (
1639            ident.name,
1640            NameResolution::from_explicit(Binding {
1641                span: ident.span,
1642                res: fhir::Res::PrimTy(pty),
1643            }),
1644        )
1645    });
1646
1647    // Types go after such that they override sorts with the same name. Note this collects into a
1648    // map, so it is a plain last-one-wins overwrite, not the shadowing/ambiguity fold used for
1649    // user-written definitions.
1650    let bindings = sorts.chain(types).collect();
1651    Rib { kind: RibKind::Misc, bindings }
1652}
1653
1654/// The [`Namespace::ReftNS`] prelude: theory functions and `cast`.
1655fn theory_funcs_rib() -> Rib {
1656    let mut rib = Rib::new(RibKind::Misc);
1657    rib.bindings
1658        .extend_unord(flux_middle::THEORY_FUNCS.items().map(|(_, itf)| {
1659            let ident = Ident::with_dummy_span(itf.name);
1660            let res = fhir::Res::GlobalFunc(fhir::SpecFuncKind::Thy(itf.itf));
1661            (ident.name, NameResolution::from_explicit(Binding { span: ident.span, res }))
1662        }));
1663    let cast_ident = Ident::with_dummy_span(sym::cast);
1664    rib.bindings.insert(
1665        cast_ident.name,
1666        NameResolution::from_explicit(Binding {
1667            span: cast_ident.span,
1668            res: fhir::Res::GlobalFunc(fhir::SpecFuncKind::Cast),
1669        }),
1670    );
1671    rib
1672}
1673
1674fn mk_crate_mapping(tcx: TyCtxt) -> UnordMap<Symbol, DefId> {
1675    let mut map = UnordMap::default();
1676    for cnum in tcx.crates(()) {
1677        let name = tcx.crate_name(*cnum);
1678        if let Some(extern_crate) = tcx.extern_crate(*cnum)
1679            && extern_crate.is_direct()
1680        {
1681            map.insert(name, cnum.as_def_id());
1682        }
1683    }
1684    map
1685}
1686
1687mod errors {
1688    use flux_errors::E0999;
1689    use flux_macros::Diagnostic;
1690    use flux_syntax::surface::Ident;
1691    use rustc_span::{Span, Symbol, def_id::DefId};
1692
1693    use super::Segment;
1694
1695    /// A name that could not be resolved. `kind` is the user-facing description of what was being
1696    /// looked for (`"type"`, `"value"`, `"sort"`, ...); it is passed explicitly by each call site
1697    /// because it no longer matches the resolution [`Namespace`](flux_middle::fhir::Namespace)
1698    /// (e.g. sorts are resolved in the type namespace).
1699    #[derive(Diagnostic)]
1700    #[diag("cannot find {$kind} `{$name}` in this scope", code = E0999)]
1701    pub(crate) struct UnresolvedName {
1702        #[primary_span]
1703        #[label("not found in this scope")]
1704        span: Span,
1705        kind: &'static str,
1706        name: String,
1707    }
1708
1709    impl UnresolvedName {
1710        pub(crate) fn new<S: Segment>(span: Span, segments: &[S], kind: &'static str) -> Self {
1711            Self { span, name: Segment::format_iter(segments), kind }
1712        }
1713    }
1714
1715    /// An import path (`flux::use foo::bar::baz`) that could not be resolved. Unlike
1716    /// [`UnresolvedName`], this always reports the full requested path in the message and
1717    /// explains, via `reason`, what specifically went wrong at the failing segment (not found,
1718    /// or found but not a module).
1719    #[derive(Diagnostic)]
1720    #[diag("unresolved import `{$name}`", code = E0999)]
1721    pub(crate) struct UnresolvedImport {
1722        #[primary_span]
1723        #[label("{$reason}")]
1724        pub span: Span,
1725        pub name: String,
1726        pub reason: String,
1727    }
1728
1729    impl UnresolvedImport {
1730        /// The import segment `ident` was not found, in `module_id` if the prefix before it
1731        /// resolved to one, or in scope otherwise.
1732        pub(super) fn new(
1733            ident: Ident,
1734            module_id: Option<DefId>,
1735            resolved_prefix: &[Ident],
1736        ) -> Self {
1737            let reason = match module_id {
1738                None => "not found in this scope".to_string(),
1739                Some(_) => format!("no `{ident}` in `{}`", Segment::format_iter(resolved_prefix)),
1740            };
1741            let name = Segment::format_iter(resolved_prefix.iter().chain(&[ident]));
1742            Self { span: ident.span, name, reason }
1743        }
1744    }
1745
1746    #[derive(Diagnostic)]
1747    #[diag("can't use generic parameters from outer item", code = E0999)]
1748    #[note("nested items cannot mention the generic parameters or `Self` of outer items")]
1749    pub(super) struct OuterGeneric {
1750        #[primary_span]
1751        #[label("use of generic parameter from outer item")]
1752        pub span: Span,
1753    }
1754
1755    #[derive(Diagnostic)]
1756    #[diag("unknown qualifier", code = E0999)]
1757    pub(super) struct UnknownQualifier {
1758        #[primary_span]
1759        span: Span,
1760    }
1761
1762    impl UnknownQualifier {
1763        pub(super) fn new(span: Span) -> Self {
1764            Self { span }
1765        }
1766    }
1767
1768    #[derive(Diagnostic)]
1769    #[diag("unknown axiom", code = E0999)]
1770    pub(super) struct UnknownAxiom {
1771        #[primary_span]
1772        span: Span,
1773    }
1774
1775    impl UnknownAxiom {
1776        pub(super) fn new(span: Span) -> Self {
1777            Self { span }
1778        }
1779    }
1780
1781    #[derive(Diagnostic)]
1782    #[diag("unknown property", code = E0999)]
1783    pub(super) struct UnknownProperty {
1784        #[primary_span]
1785        span: Span,
1786    }
1787
1788    impl UnknownProperty {
1789        pub(super) fn new(span: Span) -> Self {
1790            Self { span }
1791        }
1792    }
1793
1794    #[derive(Diagnostic)]
1795    #[diag("unknown function definition", code = E0999)]
1796    pub(super) struct UnknownFuncDefinition {
1797        #[primary_span]
1798        span: Span,
1799    }
1800
1801    impl UnknownFuncDefinition {
1802        pub(super) fn new(span: Span) -> Self {
1803            Self { span }
1804        }
1805    }
1806
1807    #[derive(Diagnostic)]
1808    #[diag("unknown type parameter", code = E0999)]
1809    pub(super) struct UnknownParametricParam {
1810        #[primary_span]
1811        span: Span,
1812    }
1813
1814    impl UnknownParametricParam {
1815        pub(super) fn new(span: Span) -> Self {
1816            Self { span }
1817        }
1818    }
1819
1820    #[derive(Diagnostic)]
1821    #[diag("the name `{$name}` is defined multiple times", code = E0999)]
1822    pub(super) struct DuplicateDefinition {
1823        #[primary_span]
1824        #[label("`{$name}` redefined here")]
1825        pub span: Span,
1826        #[label("previous definition of `{$name}`")]
1827        pub previous_definition: Span,
1828        pub name: Symbol,
1829    }
1830
1831    /// A name bound to two different items by two competing glob imports, reported at the first
1832    /// use of the name (imports themselves are never an error). Mirrors rustc's `E0659`.
1833    #[derive(Diagnostic)]
1834    #[diag("the name `{$name}` is ambiguous", code = E0999)]
1835    #[note("two different items named `{$name}` are in scope through glob imports")]
1836    pub(super) struct AmbiguousName {
1837        #[primary_span]
1838        #[label("ambiguous name")]
1839        span: Span,
1840        name: Symbol,
1841        #[label("`{$name}` could refer to the item imported here")]
1842        first: Span,
1843        #[label("`{$name}` could also refer to the item imported here")]
1844        second: Option<Span>,
1845    }
1846
1847    impl AmbiguousName {
1848        pub(super) fn new(ambiguity: super::Ambiguity) -> Self {
1849            let super::Ambiguity { span, name, first, second } = ambiguity;
1850            // Both candidates can come from the same glob statement, when it imports a module
1851            // that is itself ambiguously glob re-exporting the name. Pointing a second, identical
1852            // label at it reads as a bug, so drop it.
1853            Self { span, name, first, second: (first != second).then_some(second) }
1854        }
1855    }
1856
1857    #[derive(Diagnostic)]
1858    #[diag("identifier `{$name}` is bound more than once in this parameter list", code = E0999)]
1859    pub(super) struct DuplicateParam {
1860        #[primary_span]
1861        #[label("used as a parameter more than once")]
1862        pub span: Span,
1863        pub name: Symbol,
1864        #[label("first use of `{$name}`")]
1865        pub first_use: Span,
1866    }
1867}