flux_desugar/
resolver.rs

1pub(crate) mod refinement_resolver;
2
3use std::collections::hash_map;
4
5use flux_common::result::{ErrorCollector, ResultExt};
6use flux_errors::Errors;
7use flux_middle::{
8    ResolverOutput, Specs,
9    def_id::{FluxDefId, FluxLocalDefId, MaybeExternId},
10    fhir,
11    global_env::GlobalEnv,
12};
13use flux_syntax::surface::{self, Ident, visit::Visitor as _};
14use hir::{ItemId, ItemKind, OwnerId, def::DefKind};
15use rustc_data_structures::unord::{ExtendUnord, UnordMap};
16use rustc_errors::ErrorGuaranteed;
17use rustc_hash::FxHashMap;
18use rustc_hir::{
19    self as hir, CRATE_HIR_ID, CRATE_OWNER_ID, ParamName, PrimTy,
20    def::{
21        CtorOf,
22        Namespace::{self, *},
23        PerNS,
24    },
25    def_id::CRATE_DEF_ID,
26};
27use rustc_middle::{metadata::ModChild, ty::TyCtxt};
28use rustc_span::{Span, Symbol, def_id::DefId, sym, symbol::kw};
29
30use self::refinement_resolver::RefinementResolver;
31
32type Result<T = ()> = std::result::Result<T, ErrorGuaranteed>;
33
34pub(crate) fn resolve_crate(genv: GlobalEnv) -> ResolverOutput {
35    match try_resolve_crate(genv) {
36        Ok(output) => output,
37        Err(err) => genv.sess().abort(err),
38    }
39}
40
41fn try_resolve_crate(genv: GlobalEnv) -> Result<ResolverOutput> {
42    let specs = genv.collect_specs();
43    let mut resolver = CrateResolver::new(genv, specs);
44
45    genv.tcx().hir_walk_toplevel_module(&mut resolver);
46
47    resolver.into_output()
48}
49
50pub(crate) struct CrateResolver<'genv, 'tcx> {
51    genv: GlobalEnv<'genv, 'tcx>,
52    specs: &'genv Specs,
53    output: ResolverOutput,
54    ribs: PerNS<Vec<Rib>>,
55    /// A mapping from the names of all imported crates plus the special `crate` keyword to their
56    /// [`DefId`]
57    crates: UnordMap<Symbol, DefId>,
58    prelude: PerNS<Rib>,
59    qualifiers: UnordMap<Symbol, FluxLocalDefId>,
60    func_decls: UnordMap<Symbol, fhir::SpecFuncKind>,
61    sort_decls: UnordMap<Symbol, FluxDefId>,
62    primop_props: UnordMap<Symbol, FluxDefId>,
63    err: Option<ErrorGuaranteed>,
64    /// The most recent module we have visited. Used to check for visibility of other items from
65    /// this module.
66    current_module: OwnerId,
67}
68
69/// Map to keep track of names defined in a scope
70#[derive(Default)]
71struct DefinitionMap {
72    defined: FxHashMap<Ident, ()>,
73}
74
75impl DefinitionMap {
76    fn define(&mut self, name: Ident) -> std::result::Result<(), errors::DuplicateDefinition> {
77        match self.defined.entry(name) {
78            hash_map::Entry::Occupied(entry) => {
79                Err(errors::DuplicateDefinition {
80                    span: name.span,
81                    previous_definition: entry.key().span,
82                    name,
83                })
84            }
85            hash_map::Entry::Vacant(entry) => {
86                entry.insert(());
87                Ok(())
88            }
89        }
90    }
91}
92
93impl<'genv, 'tcx> CrateResolver<'genv, 'tcx> {
94    pub fn new(genv: GlobalEnv<'genv, 'tcx>, specs: &'genv Specs) -> Self {
95        Self {
96            genv,
97            output: ResolverOutput::default(),
98            specs,
99            ribs: PerNS { type_ns: vec![], value_ns: vec![], macro_ns: vec![] },
100            crates: mk_crate_mapping(genv.tcx()),
101            prelude: PerNS {
102                type_ns: builtin_types_rib(),
103                value_ns: Rib::new(RibKind::Normal),
104                macro_ns: Rib::new(RibKind::Normal),
105            },
106            err: None,
107            qualifiers: Default::default(),
108            func_decls: Default::default(),
109            primop_props: Default::default(),
110            sort_decls: Default::default(),
111            current_module: CRATE_OWNER_ID,
112        }
113    }
114
115    #[allow(clippy::disallowed_methods, reason = "`flux_items_by_parent` is the source of truth")]
116    fn define_flux_global_items(&mut self) {
117        // Note that names are defined globally so we check for duplicates globally in the crate.
118        let mut definitions = DefinitionMap::default();
119        for (parent, items) in &self.specs.flux_items_by_parent {
120            for item in items {
121                // NOTE: This is putting all items in the same namespace. In principle, we could have
122                // qualifiers in a different namespace.
123                definitions
124                    .define(item.name())
125                    .emit(&self.genv)
126                    .collect_err(&mut self.err);
127
128                match item {
129                    surface::FluxItem::Qualifier(qual) => {
130                        let def_id = FluxLocalDefId::new(parent.def_id, qual.name.name);
131                        self.qualifiers.insert(qual.name.name, def_id);
132                    }
133                    surface::FluxItem::FuncDef(defn) => {
134                        let parent = parent.def_id.to_def_id();
135                        let name = defn.name.name;
136                        let def_id = FluxDefId::new(parent, name);
137                        let kind = if defn.body.is_some() {
138                            fhir::SpecFuncKind::Def(def_id)
139                        } else {
140                            fhir::SpecFuncKind::Uif(def_id)
141                        };
142                        self.func_decls.insert(defn.name.name, kind);
143                    }
144                    surface::FluxItem::PrimOpProp(primop_prop) => {
145                        let name = primop_prop.name.name;
146                        let parent = parent.def_id.to_def_id();
147                        let def_id = FluxDefId::new(parent, name);
148                        self.primop_props.insert(name, def_id);
149                    }
150                    surface::FluxItem::SortDecl(sort_decl) => {
151                        let def_id = FluxDefId::new(parent.def_id.to_def_id(), sort_decl.name.name);
152                        self.sort_decls.insert(sort_decl.name.name, def_id);
153                    }
154                }
155            }
156        }
157
158        self.func_decls.extend_unord(
159            flux_middle::THEORY_FUNCS
160                .items()
161                .map(|(_, itf)| (itf.name, fhir::SpecFuncKind::Thy(itf.itf))),
162        );
163        self.func_decls
164            .insert(Symbol::intern("cast"), fhir::SpecFuncKind::Cast);
165    }
166
167    fn define_items(&mut self, item_ids: impl IntoIterator<Item = &'tcx ItemId>) {
168        for item_id in item_ids {
169            let item = self.genv.tcx().hir_item(*item_id);
170            let def_kind = match item.kind {
171                ItemKind::Use(path, kind) => {
172                    match kind {
173                        hir::UseKind::Single(ident) => {
174                            let name = ident.name;
175                            if let Some(res) = path.res.value_ns
176                                && let Ok(res) = fhir::Res::try_from(res)
177                            {
178                                self.define_res_in(name, res, ValueNS);
179                            }
180                            if let Some(res) = path.res.type_ns
181                                && let Ok(res) = fhir::Res::try_from(res)
182                            {
183                                self.define_res_in(name, res, TypeNS);
184                            }
185                        }
186                        hir::UseKind::Glob => {
187                            let is_prelude = is_prelude_import(self.genv.tcx(), item);
188                            for mod_child in self.glob_imports(path) {
189                                if let Ok(res) = fhir::Res::try_from(mod_child.res)
190                                    && let Some(ns @ (TypeNS | ValueNS)) = res.ns()
191                                {
192                                    let name = mod_child.ident.name;
193                                    if is_prelude {
194                                        self.define_in_prelude(name, res, ns);
195                                    } else {
196                                        self.define_res_in(name, res, ns);
197                                    }
198                                }
199                            }
200                        }
201                        hir::UseKind::ListStem => {}
202                    }
203                    continue;
204                }
205                ItemKind::TyAlias(..) => DefKind::TyAlias,
206                ItemKind::Enum(..) => DefKind::Enum,
207                ItemKind::Struct(..) => DefKind::Struct,
208                ItemKind::Trait(..) => DefKind::Trait,
209                ItemKind::Mod(..) => DefKind::Mod,
210                ItemKind::Const(..) => DefKind::Const,
211                ItemKind::ForeignMod { items, .. } => {
212                    self.define_foreign_items(items);
213                    continue;
214                }
215                _ => continue,
216            };
217            if let Some(ns) = def_kind.ns()
218                && let Some(ident) = item.kind.ident()
219            {
220                self.define_res_in(
221                    ident.name,
222                    fhir::Res::Def(def_kind, item.owner_id.to_def_id()),
223                    ns,
224                );
225            }
226        }
227    }
228
229    fn define_foreign_items(&mut self, items: &[rustc_hir::ForeignItemId]) {
230        for item_id in items {
231            let item = self.genv.tcx().hir_foreign_item(*item_id);
232            match item.kind {
233                rustc_hir::ForeignItemKind::Type => {
234                    self.define_res_in(
235                        item.ident.name,
236                        fhir::Res::Def(DefKind::ForeignTy, item.owner_id.to_def_id()),
237                        TypeNS,
238                    );
239                }
240                rustc_hir::ForeignItemKind::Fn(..) | rustc_hir::ForeignItemKind::Static(..) => {}
241            }
242        }
243    }
244
245    fn define_res_in(&mut self, name: Symbol, res: fhir::Res, ns: Namespace) {
246        self.ribs[ns].last_mut().unwrap().bindings.insert(name, res);
247    }
248
249    fn define_in_prelude(&mut self, name: Symbol, res: fhir::Res, ns: Namespace) {
250        self.prelude[ns].bindings.insert(name, res);
251    }
252
253    fn push_rib(&mut self, ns: Namespace, kind: RibKind) {
254        self.ribs[ns].push(Rib::new(kind));
255    }
256
257    fn pop_rib(&mut self, ns: Namespace) {
258        self.ribs[ns].pop();
259    }
260
261    fn define_generics(&mut self, def_id: MaybeExternId<OwnerId>) {
262        let generics = self
263            .genv
264            .tcx()
265            .hir_get_generics(def_id.local_id().def_id)
266            .unwrap();
267        for param in generics.params {
268            let def_kind = self.genv.tcx().def_kind(param.def_id);
269            if let ParamName::Plain(name) = param.name
270                && let Some(ns) = def_kind.ns()
271            {
272                debug_assert!(matches!(def_kind, DefKind::TyParam | DefKind::ConstParam));
273                let param_id = self.genv.maybe_extern_id(param.def_id).resolved_id();
274                self.define_res_in(name.name, fhir::Res::Def(def_kind, param_id), ns);
275            }
276        }
277    }
278
279    fn resolve_flux_items(&mut self, parent: OwnerId) {
280        let Some(items) = self.specs.flux_items_by_parent.get(&parent) else { return };
281        for item in items {
282            RefinementResolver::resolve_flux_item(self, item).collect_err(&mut self.err);
283        }
284    }
285
286    fn resolve_item(&mut self, item: &surface::Item) -> Result {
287        ItemResolver::run(self, |item_resolver| item_resolver.visit_item(item))?;
288        RefinementResolver::resolve_item(self, item)
289    }
290
291    fn resolve_trait_item(&mut self, item: &surface::TraitItemFn) -> Result {
292        ItemResolver::run(self, |item_resolver| item_resolver.visit_trait_item(item))?;
293        RefinementResolver::resolve_trait_item(self, item)
294    }
295
296    fn resolve_impl_item(&mut self, item: &surface::ImplItemFn) -> Result {
297        ItemResolver::run(self, |item_resolver| item_resolver.visit_impl_item(item))?;
298        RefinementResolver::resolve_impl_item(self, item)
299    }
300
301    fn resolve_path_with_ribs<S: Segment>(
302        &mut self,
303        segments: &[S],
304        ns: Namespace,
305    ) -> Option<fhir::PartialRes> {
306        let mut module: Option<Module> = None;
307        for (segment_idx, segment) in segments.iter().enumerate() {
308            let is_last = segment_idx + 1 == segments.len();
309            let ns = if is_last { ns } else { TypeNS };
310
311            let base_res = if let Some(module) = &module {
312                self.resolve_ident_in_module(module, segment.ident(), ns)?
313            } else {
314                self.resolve_ident_with_ribs(segment.ident(), ns)?
315            };
316
317            S::record_segment_res(self, segment, base_res);
318
319            if is_last {
320                return Some(fhir::PartialRes::new(base_res));
321            }
322
323            match base_res {
324                fhir::Res::Def(DefKind::Mod, module_id) => {
325                    module = Some(Module::new(ModuleKind::Mod, module_id));
326                }
327                fhir::Res::Def(DefKind::Trait, module_id) => {
328                    module = Some(Module::new(ModuleKind::Trait, module_id));
329                }
330                fhir::Res::Def(DefKind::Enum, module_id) => {
331                    module = Some(Module::new(ModuleKind::Enum, module_id));
332                }
333                _ => {
334                    return Some(fhir::PartialRes::with_unresolved_segments(
335                        base_res,
336                        segments.len() - segment_idx - 1,
337                    ));
338                }
339            }
340        }
341        None
342    }
343
344    fn resolve_ident_with_ribs(&self, ident: Ident, ns: Namespace) -> Option<fhir::Res> {
345        for rib in self.ribs[ns].iter().rev() {
346            if let Some(res) = rib.bindings.get(&ident.name) {
347                return Some(*res);
348            }
349            if matches!(rib.kind, RibKind::Module) {
350                break;
351            }
352        }
353        if ns == TypeNS
354            && let Some(crate_id) = self.crates.get(&ident.name)
355        {
356            return Some(fhir::Res::Def(DefKind::Mod, *crate_id));
357        }
358
359        if let Some(res) = self.prelude[ns].bindings.get(&ident.name) {
360            return Some(*res);
361        }
362        None
363    }
364
365    fn glob_imports(
366        &mut self,
367        path: &hir::UsePath,
368    ) -> impl Iterator<Item = &'tcx ModChild> + use<'tcx> {
369        // The path for the prelude import is not resolved anymore after <https://github.com/rust-lang/rust/pull/145322>,
370        // so we resolve all paths here. If this ever causes problems, we could use the resolution in the `UsePath` for
371        // non-prelude glob imports.
372        let tcx = self.genv.tcx();
373        let curr_mod = self.current_module.to_def_id();
374        self.resolve_path_with_ribs(path.segments, TypeNS)
375            .and_then(|partial_res| partial_res.full_res())
376            .and_then(|res| {
377                if let fhir::Res::Def(DefKind::Mod, module_id) = res {
378                    Some(module_id)
379                } else {
380                    None
381                }
382            })
383            .into_iter()
384            .flat_map(move |module_id| visible_module_children(tcx, module_id, curr_mod))
385    }
386
387    fn resolve_ident_in_module(
388        &self,
389        module: &Module,
390        ident: Ident,
391        ns: Namespace,
392    ) -> Option<fhir::Res> {
393        let tcx = self.genv.tcx();
394        match module.kind {
395            ModuleKind::Mod => {
396                let module_id = module.def_id;
397                let current_mod = self.current_module.to_def_id();
398                visible_module_children(tcx, module_id, current_mod)
399                    .find(|child| {
400                        child.res.matches_ns(ns) && tcx.hygienic_eq(ident, child.ident, current_mod)
401                    })
402                    .and_then(|child| fhir::Res::try_from(child.res).ok())
403            }
404            ModuleKind::Trait => {
405                let trait_id = module.def_id;
406                tcx.associated_items(trait_id)
407                    .find_by_ident_and_namespace(tcx, ident, ns, trait_id)
408                    .map(|assoc| fhir::Res::Def(assoc.kind.as_def_kind(), assoc.def_id))
409            }
410            ModuleKind::Enum => {
411                tcx.adt_def(module.def_id)
412                    .variants()
413                    .iter()
414                    .find(|data| data.name == ident.name)
415                    .and_then(|data| {
416                        let (kind, def_id) = match (ns, data.ctor) {
417                            (TypeNS, _) => (DefKind::Variant, data.def_id),
418                            (ValueNS, Some((ctor_kind, ctor_id))) => {
419                                (DefKind::Ctor(CtorOf::Variant, ctor_kind), ctor_id)
420                            }
421                            _ => return None,
422                        };
423                        Some(fhir::Res::Def(kind, def_id))
424                    })
425            }
426        }
427    }
428
429    pub fn into_output(self) -> Result<ResolverOutput> {
430        self.err.into_result()?;
431        Ok(self.output)
432    }
433}
434
435impl<'tcx> hir::intravisit::Visitor<'tcx> for CrateResolver<'_, 'tcx> {
436    type NestedFilter = rustc_middle::hir::nested_filter::All;
437
438    fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
439        self.genv.tcx()
440    }
441
442    fn visit_mod(&mut self, module: &'tcx hir::Mod<'tcx>, _s: Span, hir_id: hir::HirId) {
443        let old_mod = self.current_module;
444        self.current_module = hir_id.expect_owner();
445        self.push_rib(TypeNS, RibKind::Module);
446        self.push_rib(ValueNS, RibKind::Module);
447
448        self.define_items(module.item_ids);
449
450        // Flux items are made globally available as if they were defined at the top of the crate
451        if hir_id == CRATE_HIR_ID {
452            self.define_flux_global_items();
453        }
454
455        // But we resolve names in them as if they were defined in their containing module
456        self.resolve_flux_items(hir_id.expect_owner());
457
458        hir::intravisit::walk_mod(self, module);
459
460        self.pop_rib(ValueNS);
461        self.pop_rib(TypeNS);
462        self.current_module = old_mod;
463    }
464
465    fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
466        self.push_rib(TypeNS, RibKind::Normal);
467        self.push_rib(ValueNS, RibKind::Normal);
468
469        let item_ids = block.stmts.iter().filter_map(|stmt| {
470            if let hir::StmtKind::Item(item_id) = &stmt.kind { Some(item_id) } else { None }
471        });
472        self.define_items(item_ids);
473        self.resolve_flux_items(self.genv.tcx().hir_get_parent_item(block.hir_id));
474
475        hir::intravisit::walk_block(self, block);
476
477        self.pop_rib(ValueNS);
478        self.pop_rib(TypeNS);
479    }
480
481    fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
482        if self.genv.is_dummy(item.owner_id.def_id) {
483            return;
484        }
485        let def_id = self
486            .genv
487            .maybe_extern_id(item.owner_id.def_id)
488            .map(|def_id| OwnerId { def_id });
489
490        self.push_rib(TypeNS, RibKind::Normal);
491        self.push_rib(ValueNS, RibKind::Normal);
492
493        match item.kind {
494            ItemKind::Trait(..) => {
495                self.define_generics(def_id);
496                self.define_res_in(
497                    kw::SelfUpper,
498                    fhir::Res::SelfTyParam { trait_: def_id.resolved_id() },
499                    TypeNS,
500                );
501            }
502            ItemKind::Impl(hir::Impl { of_trait, .. }) => {
503                self.define_generics(def_id);
504                self.define_res_in(
505                    kw::SelfUpper,
506                    fhir::Res::SelfTyAlias {
507                        alias_to: def_id.resolved_id(),
508                        is_trait_impl: of_trait.is_some(),
509                    },
510                    TypeNS,
511                );
512            }
513            ItemKind::TyAlias(..) => {
514                self.define_generics(def_id);
515            }
516            ItemKind::Enum(..) => {
517                self.define_generics(def_id);
518                self.define_res_in(
519                    kw::SelfUpper,
520                    fhir::Res::SelfTyAlias { alias_to: def_id.resolved_id(), is_trait_impl: false },
521                    TypeNS,
522                );
523            }
524            ItemKind::Struct(..) => {
525                self.define_generics(def_id);
526                self.define_res_in(
527                    kw::SelfUpper,
528                    fhir::Res::SelfTyAlias { alias_to: def_id.resolved_id(), is_trait_impl: false },
529                    TypeNS,
530                );
531            }
532            ItemKind::Fn { .. } => {
533                self.define_generics(def_id);
534            }
535            _ => {}
536        }
537        if let Some(item) = self.specs.get_item(def_id.local_id()) {
538            self.resolve_item(item).collect_err(&mut self.err);
539        }
540
541        hir::intravisit::walk_item(self, item);
542
543        self.pop_rib(ValueNS);
544        self.pop_rib(TypeNS);
545    }
546
547    fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
548        let def_id = self
549            .genv
550            .maybe_extern_id(impl_item.owner_id.def_id)
551            .map(|def_id| OwnerId { def_id });
552
553        self.push_rib(TypeNS, RibKind::Normal);
554        if let Some(item) = self.specs.get_impl_item(def_id.local_id()) {
555            self.define_generics(def_id);
556            self.resolve_impl_item(item).collect_err(&mut self.err);
557        }
558        hir::intravisit::walk_impl_item(self, impl_item);
559        self.pop_rib(TypeNS);
560    }
561
562    fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
563        let def_id = self
564            .genv
565            .maybe_extern_id(trait_item.owner_id.def_id)
566            .map(|def_id| OwnerId { def_id });
567
568        self.push_rib(TypeNS, RibKind::Normal);
569        if let Some(item) = self.specs.get_trait_item(def_id.local_id()) {
570            self.define_generics(def_id);
571            self.resolve_trait_item(item).collect_err(&mut self.err);
572        }
573        hir::intravisit::walk_trait_item(self, trait_item);
574        self.pop_rib(TypeNS);
575    }
576}
577
578/// Akin to `rustc_resolve::Module` but specialized to what we support
579#[derive(Debug)]
580struct Module {
581    kind: ModuleKind,
582    def_id: DefId,
583}
584
585impl Module {
586    fn new(kind: ModuleKind, def_id: DefId) -> Self {
587        Self { kind, def_id }
588    }
589}
590
591/// Akin to `rustc_resolve::ModuleKind` but specialized to what we support
592#[derive(Debug)]
593enum ModuleKind {
594    Mod,
595    Trait,
596    Enum,
597}
598
599#[derive(Debug)]
600enum RibKind {
601    /// Any other rib without extra rules.
602    Normal,
603    /// We pass through a module. Lookups of items should stop here.
604    Module,
605}
606
607#[derive(Debug)]
608struct Rib {
609    kind: RibKind,
610    bindings: FxHashMap<Symbol, fhir::Res>,
611}
612
613impl Rib {
614    fn new(kind: RibKind) -> Self {
615        Self { kind, bindings: Default::default() }
616    }
617}
618
619fn module_children(tcx: TyCtxt<'_>, def_id: DefId) -> &[ModChild] {
620    #[expect(clippy::disallowed_methods, reason = "modules cannot have extern specs")]
621    if let Some(local_id) = def_id.as_local() {
622        tcx.module_children_local(local_id)
623    } else {
624        tcx.module_children(def_id)
625    }
626}
627
628/// Iterator over module children visible form `curr_mod`
629fn visible_module_children(
630    tcx: TyCtxt<'_>,
631    module_id: DefId,
632    curr_mod: DefId,
633) -> impl Iterator<Item = &ModChild> {
634    module_children(tcx, module_id)
635        .iter()
636        .filter(move |child| child.vis.is_accessible_from(curr_mod, tcx))
637}
638
639/// Return true if the item has a `#[prelude_import]` annotation
640fn is_prelude_import(tcx: TyCtxt, item: &hir::Item) -> bool {
641    tcx.hir_attrs(item.hir_id())
642        .iter()
643        .any(|attr| attr.path_matches(&[sym::prelude_import]))
644}
645
646/// Abstraction over a "segment" so we can use [`CrateResolver::resolve_path_with_ribs`] with paths
647/// from different sources  (e.g., [`surface::PathSegment`], [`surface::ExprPathSegment`])
648trait Segment: std::fmt::Debug {
649    fn record_segment_res(resolver: &mut CrateResolver, segment: &Self, res: fhir::Res);
650    fn ident(&self) -> Ident;
651}
652
653impl Segment for surface::PathSegment {
654    fn record_segment_res(resolver: &mut CrateResolver, segment: &Self, res: fhir::Res) {
655        resolver
656            .output
657            .path_res_map
658            .insert(segment.node_id, fhir::PartialRes::new(res));
659    }
660
661    fn ident(&self) -> Ident {
662        self.ident
663    }
664}
665
666impl Segment for surface::ExprPathSegment {
667    fn record_segment_res(resolver: &mut CrateResolver, segment: &Self, res: fhir::Res) {
668        resolver
669            .output
670            .expr_path_res_map
671            .insert(segment.node_id, fhir::PartialRes::new(res.map_param_id(|p| p)));
672    }
673
674    fn ident(&self) -> Ident {
675        self.ident
676    }
677}
678
679impl Segment for Ident {
680    fn record_segment_res(_resolver: &mut CrateResolver, _segment: &Self, _res: fhir::Res) {}
681
682    fn ident(&self) -> Ident {
683        *self
684    }
685}
686
687impl Segment for hir::PathSegment<'_> {
688    fn record_segment_res(_resolver: &mut CrateResolver, _segment: &Self, _res: fhir::Res) {}
689
690    fn ident(&self) -> Ident {
691        self.ident
692    }
693}
694
695struct ItemResolver<'a, 'genv, 'tcx> {
696    resolver: &'a mut CrateResolver<'genv, 'tcx>,
697    errors: Errors<'genv>,
698}
699
700impl<'a, 'genv, 'tcx> ItemResolver<'a, 'genv, 'tcx> {
701    fn run(
702        resolver: &'a mut CrateResolver<'genv, 'tcx>,
703        f: impl FnOnce(&mut ItemResolver),
704    ) -> Result {
705        let mut item_resolver = ItemResolver::new(resolver);
706        f(&mut item_resolver);
707        item_resolver.errors.into_result()
708    }
709
710    fn new(resolver: &'a mut CrateResolver<'genv, 'tcx>) -> Self {
711        let errors = Errors::new(resolver.genv.sess());
712        Self { resolver, errors }
713    }
714
715    fn resolve_type_path(&mut self, path: &surface::Path) {
716        self.resolve_path_in(path, TypeNS);
717    }
718
719    fn resolve_path_in(&mut self, path: &surface::Path, ns: Namespace) {
720        if let Some(partial_res) = self.resolver.resolve_path_with_ribs(&path.segments, ns) {
721            self.resolver
722                .output
723                .path_res_map
724                .insert(path.node_id, partial_res);
725        } else {
726            self.errors.emit(errors::UnresolvedPath::new(path));
727        }
728    }
729
730    fn resolve_reveal_and_qualifiers(&mut self, node_id: surface::NodeId, attrs: &[surface::Attr]) {
731        for attr in attrs {
732            match attr {
733                surface::Attr::Qualifiers(names) => self.resolve_qualifiers(node_id, names),
734                surface::Attr::Reveal(names) => self.resolve_reveals(node_id, names),
735                _ => {}
736            }
737        }
738    }
739
740    fn resolve_qualifiers(&mut self, node_id: surface::NodeId, qual_names: &[Ident]) {
741        let mut qualifiers = Vec::with_capacity(qual_names.len());
742        for qual in qual_names {
743            if let Some(def_id) = self.resolver.qualifiers.get(&qual.name) {
744                qualifiers.push(*def_id);
745            } else {
746                self.errors.emit(errors::UnknownQualifier::new(qual.span));
747            }
748        }
749        self.resolver
750            .output
751            .qualifier_res_map
752            .insert(node_id, qualifiers);
753    }
754
755    fn resolve_reveals(&mut self, item_id: surface::NodeId, reveal_names: &[Ident]) {
756        let mut reveals = Vec::with_capacity(reveal_names.len());
757        for reveal in reveal_names {
758            if let Some(spec) = self.resolver.func_decls.get(&reveal.name)
759                && let Some(def_id) = spec.def_id()
760            {
761                reveals.push(def_id);
762            } else {
763                self.errors
764                    .emit(errors::UnknownRevealDefinition::new(reveal.span));
765            }
766        }
767        self.resolver.output.reveal_res_map.insert(item_id, reveals);
768    }
769}
770
771impl surface::visit::Visitor for ItemResolver<'_, '_, '_> {
772    fn visit_item(&mut self, item: &surface::Item) {
773        self.resolve_reveal_and_qualifiers(item.node_id, &item.attrs);
774        surface::visit::walk_item(self, item);
775    }
776
777    fn visit_trait_item(&mut self, item: &surface::TraitItemFn) {
778        self.resolve_reveal_and_qualifiers(item.node_id, &item.attrs);
779        surface::visit::walk_trait_item(self, item);
780    }
781
782    fn visit_impl_item(&mut self, item: &surface::ImplItemFn) {
783        self.resolve_reveal_and_qualifiers(item.node_id, &item.attrs);
784        surface::visit::walk_impl_item(self, item);
785    }
786
787    fn visit_trait(&mut self, trait_: &surface::Trait) {
788        let mut definitions = DefinitionMap::default();
789        for assoc_reft in &trait_.assoc_refinements {
790            let _ = definitions.define(assoc_reft.name).emit(&self.errors);
791        }
792        surface::visit::walk_trait(self, trait_);
793    }
794
795    fn visit_impl(&mut self, impl_: &surface::Impl) {
796        let mut definitions = DefinitionMap::default();
797        for assoc_reft in &impl_.assoc_refinements {
798            let _ = definitions.define(assoc_reft.name).emit(&self.errors);
799        }
800        surface::visit::walk_impl(self, impl_);
801    }
802
803    fn visit_generic_arg(&mut self, arg: &surface::GenericArg) {
804        if let surface::GenericArgKind::Type(ty) = &arg.kind
805            && let Some(path) = ty.is_potential_const_arg()
806        {
807            // We parse const arguments as path types as we cannot distinguish them during
808            // parsing. We try to resolve that ambiguity by attempting resolution in both the
809            // type and value namespaces. If we resolved the path in the value namespace, we
810            // transform it into a generic const argument.
811            let check_ns = |ns| {
812                self.resolver
813                    .resolve_ident_with_ribs(path.last().ident, ns)
814                    .is_some()
815            };
816
817            if !check_ns(TypeNS) && check_ns(ValueNS) {
818                self.resolve_path_in(path, ValueNS);
819                return;
820            }
821        }
822        surface::visit::walk_generic_arg(self, arg);
823    }
824
825    fn visit_path(&mut self, path: &surface::Path) {
826        self.resolve_type_path(path);
827        surface::visit::walk_path(self, path);
828    }
829}
830
831fn builtin_types_rib() -> Rib {
832    Rib {
833        kind: RibKind::Normal,
834        bindings: PrimTy::ALL
835            .into_iter()
836            .map(|pty| (pty.name(), fhir::Res::PrimTy(pty)))
837            .collect(),
838    }
839}
840
841fn mk_crate_mapping(tcx: TyCtxt) -> UnordMap<Symbol, DefId> {
842    let mut map = UnordMap::default();
843    map.insert(kw::Crate, CRATE_DEF_ID.to_def_id());
844    for cnum in tcx.crates(()) {
845        let name = tcx.crate_name(*cnum);
846        if let Some(extern_crate) = tcx.extern_crate(*cnum)
847            && extern_crate.is_direct()
848        {
849            map.insert(name, cnum.as_def_id());
850        }
851    }
852    map
853}
854
855mod errors {
856    use flux_errors::E0999;
857    use flux_macros::Diagnostic;
858    use flux_syntax::surface;
859    use itertools::Itertools;
860    use rustc_span::{Ident, Span};
861
862    #[derive(Diagnostic)]
863    #[diag(desugar_unresolved_path, code = E0999)]
864    pub struct UnresolvedPath {
865        #[primary_span]
866        pub span: Span,
867        pub path: String,
868    }
869
870    impl UnresolvedPath {
871        pub fn new(path: &surface::Path) -> Self {
872            Self {
873                span: path.span,
874                path: path.segments.iter().map(|segment| segment.ident).join("::"),
875            }
876        }
877    }
878
879    #[derive(Diagnostic)]
880    #[diag(desugar_unknown_qualifier, code = E0999)]
881    pub(super) struct UnknownQualifier {
882        #[primary_span]
883        span: Span,
884    }
885
886    impl UnknownQualifier {
887        pub(super) fn new(span: Span) -> Self {
888            Self { span }
889        }
890    }
891
892    #[derive(Diagnostic)]
893    #[diag(desugar_unknown_reveal_definition, code = E0999)]
894    pub(super) struct UnknownRevealDefinition {
895        #[primary_span]
896        span: Span,
897    }
898
899    impl UnknownRevealDefinition {
900        pub(super) fn new(span: Span) -> Self {
901            Self { span }
902        }
903    }
904
905    #[derive(Diagnostic)]
906    #[diag(desugar_duplicate_definition, code = E0999)]
907    pub(super) struct DuplicateDefinition {
908        #[primary_span]
909        #[label]
910        pub span: Span,
911        #[label(desugar_previous_definition)]
912        pub previous_definition: Span,
913        pub name: Ident,
914    }
915}