rustc_resolve/
ident.rs

1use Determinacy::*;
2use Namespace::*;
3use rustc_ast::{self as ast, NodeId};
4use rustc_errors::ErrorGuaranteed;
5use rustc_hir::def::{DefKind, MacroKinds, Namespace, NonMacroAttrKind, PartialRes, PerNS};
6use rustc_middle::bug;
7use rustc_session::lint::builtin::PROC_MACRO_DERIVE_RESOLUTION_FALLBACK;
8use rustc_session::parse::feature_err;
9use rustc_span::hygiene::{ExpnId, ExpnKind, LocalExpnId, MacroKind, SyntaxContext};
10use rustc_span::{Ident, Span, kw, sym};
11use tracing::{debug, instrument};
12
13use crate::errors::{ParamKindInEnumDiscriminant, ParamKindInNonTrivialAnonConst};
14use crate::imports::{Import, NameResolution};
15use crate::late::{ConstantHasGenerics, NoConstantGenericsReason, PathSource, Rib, RibKind};
16use crate::macros::{MacroRulesScope, sub_namespace_match};
17use crate::{
18    AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, BindingKey, CmResolver, Determinacy,
19    Finalize, ImportKind, LexicalScopeBinding, Module, ModuleKind, ModuleOrUniformRoot,
20    NameBinding, NameBindingKind, ParentScope, PathResult, PrivacyError, Res, ResolutionError,
21    Resolver, Scope, ScopeSet, Segment, Stage, Used, Weak, errors,
22};
23
24#[derive(Copy, Clone)]
25pub enum UsePrelude {
26    No,
27    Yes,
28}
29
30impl From<UsePrelude> for bool {
31    fn from(up: UsePrelude) -> bool {
32        matches!(up, UsePrelude::Yes)
33    }
34}
35
36#[derive(Debug, PartialEq, Clone, Copy)]
37enum Shadowing {
38    Restricted,
39    Unrestricted,
40}
41
42impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
43    /// A generic scope visitor.
44    /// Visits scopes in order to resolve some identifier in them or perform other actions.
45    /// If the callback returns `Some` result, we stop visiting scopes and return it.
46    pub(crate) fn visit_scopes<'r, T>(
47        mut self: CmResolver<'r, 'ra, 'tcx>,
48        scope_set: ScopeSet<'ra>,
49        parent_scope: &ParentScope<'ra>,
50        ctxt: SyntaxContext,
51        derive_fallback_lint_id: Option<NodeId>,
52        mut visitor: impl FnMut(
53            &mut CmResolver<'r, 'ra, 'tcx>,
54            Scope<'ra>,
55            UsePrelude,
56            SyntaxContext,
57        ) -> Option<T>,
58    ) -> Option<T> {
59        // General principles:
60        // 1. Not controlled (user-defined) names should have higher priority than controlled names
61        //    built into the language or standard library. This way we can add new names into the
62        //    language or standard library without breaking user code.
63        // 2. "Closed set" below means new names cannot appear after the current resolution attempt.
64        // Places to search (in order of decreasing priority):
65        // (Type NS)
66        // 1. FIXME: Ribs (type parameters), there's no necessary infrastructure yet
67        //    (open set, not controlled).
68        // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
69        //    (open, not controlled).
70        // 3. Extern prelude (open, the open part is from macro expansions, not controlled).
71        // 4. Tool modules (closed, controlled right now, but not in the future).
72        // 5. Standard library prelude (de-facto closed, controlled).
73        // 6. Language prelude (closed, controlled).
74        // (Value NS)
75        // 1. FIXME: Ribs (local variables), there's no necessary infrastructure yet
76        //    (open set, not controlled).
77        // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
78        //    (open, not controlled).
79        // 3. Standard library prelude (de-facto closed, controlled).
80        // (Macro NS)
81        // 1-3. Derive helpers (open, not controlled). All ambiguities with other names
82        //    are currently reported as errors. They should be higher in priority than preludes
83        //    and probably even names in modules according to the "general principles" above. They
84        //    also should be subject to restricted shadowing because are effectively produced by
85        //    derives (you need to resolve the derive first to add helpers into scope), but they
86        //    should be available before the derive is expanded for compatibility.
87        //    It's mess in general, so we are being conservative for now.
88        // 1-3. `macro_rules` (open, not controlled), loop through `macro_rules` scopes. Have higher
89        //    priority than prelude macros, but create ambiguities with macros in modules.
90        // 1-3. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
91        //    (open, not controlled). Have higher priority than prelude macros, but create
92        //    ambiguities with `macro_rules`.
93        // 4. `macro_use` prelude (open, the open part is from macro expansions, not controlled).
94        // 4a. User-defined prelude from macro-use
95        //    (open, the open part is from macro expansions, not controlled).
96        // 4b. "Standard library prelude" part implemented through `macro-use` (closed, controlled).
97        // 4c. Standard library prelude (de-facto closed, controlled).
98        // 6. Language prelude: builtin attributes (closed, controlled).
99
100        let rust_2015 = ctxt.edition().is_rust_2015();
101        let (ns, macro_kind) = match scope_set {
102            ScopeSet::All(ns) | ScopeSet::ModuleAndExternPrelude(ns, _) => (ns, None),
103            ScopeSet::ExternPrelude => (TypeNS, None),
104            ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind)),
105        };
106        let module = match scope_set {
107            // Start with the specified module.
108            ScopeSet::ModuleAndExternPrelude(_, module) => module,
109            // Jump out of trait or enum modules, they do not act as scopes.
110            _ => parent_scope.module.nearest_item_scope(),
111        };
112        let module_and_extern_prelude = matches!(scope_set, ScopeSet::ModuleAndExternPrelude(..));
113        let extern_prelude = matches!(scope_set, ScopeSet::ExternPrelude);
114        let mut scope = match ns {
115            _ if module_and_extern_prelude => Scope::Module(module, None),
116            _ if extern_prelude => Scope::ExternPreludeItems,
117            TypeNS | ValueNS => Scope::Module(module, None),
118            MacroNS => Scope::DeriveHelpers(parent_scope.expansion),
119        };
120        let mut ctxt = ctxt.normalize_to_macros_2_0();
121        let mut use_prelude = !module.no_implicit_prelude;
122
123        loop {
124            let visit = match scope {
125                // Derive helpers are not in scope when resolving derives in the same container.
126                Scope::DeriveHelpers(expn_id) => {
127                    !(expn_id == parent_scope.expansion && macro_kind == Some(MacroKind::Derive))
128                }
129                Scope::DeriveHelpersCompat => true,
130                Scope::MacroRules(macro_rules_scope) => {
131                    // Use "path compression" on `macro_rules` scope chains. This is an optimization
132                    // used to avoid long scope chains, see the comments on `MacroRulesScopeRef`.
133                    // As another consequence of this optimization visitors never observe invocation
134                    // scopes for macros that were already expanded.
135                    while let MacroRulesScope::Invocation(invoc_id) = macro_rules_scope.get() {
136                        if let Some(next_scope) = self.output_macro_rules_scopes.get(&invoc_id) {
137                            macro_rules_scope.set(next_scope.get());
138                        } else {
139                            break;
140                        }
141                    }
142                    true
143                }
144                Scope::Module(..) => true,
145                Scope::MacroUsePrelude => use_prelude || rust_2015,
146                Scope::BuiltinAttrs => true,
147                Scope::ExternPreludeItems | Scope::ExternPreludeFlags => {
148                    use_prelude || module_and_extern_prelude || extern_prelude
149                }
150                Scope::ToolPrelude => use_prelude,
151                Scope::StdLibPrelude => use_prelude || ns == MacroNS,
152                Scope::BuiltinTypes => true,
153            };
154
155            if visit {
156                let use_prelude = if use_prelude { UsePrelude::Yes } else { UsePrelude::No };
157                if let break_result @ Some(..) = visitor(&mut self, scope, use_prelude, ctxt) {
158                    return break_result;
159                }
160            }
161
162            scope = match scope {
163                Scope::DeriveHelpers(LocalExpnId::ROOT) => Scope::DeriveHelpersCompat,
164                Scope::DeriveHelpers(expn_id) => {
165                    // Derive helpers are not visible to code generated by bang or derive macros.
166                    let expn_data = expn_id.expn_data();
167                    match expn_data.kind {
168                        ExpnKind::Root
169                        | ExpnKind::Macro(MacroKind::Bang | MacroKind::Derive, _) => {
170                            Scope::DeriveHelpersCompat
171                        }
172                        _ => Scope::DeriveHelpers(expn_data.parent.expect_local()),
173                    }
174                }
175                Scope::DeriveHelpersCompat => Scope::MacroRules(parent_scope.macro_rules),
176                Scope::MacroRules(macro_rules_scope) => match macro_rules_scope.get() {
177                    MacroRulesScope::Binding(binding) => {
178                        Scope::MacroRules(binding.parent_macro_rules_scope)
179                    }
180                    MacroRulesScope::Invocation(invoc_id) => {
181                        Scope::MacroRules(self.invocation_parent_scopes[&invoc_id].macro_rules)
182                    }
183                    MacroRulesScope::Empty => Scope::Module(module, None),
184                },
185                Scope::Module(..) if module_and_extern_prelude => match ns {
186                    TypeNS => {
187                        ctxt.adjust(ExpnId::root());
188                        Scope::ExternPreludeItems
189                    }
190                    ValueNS | MacroNS => break,
191                },
192                Scope::Module(module, prev_lint_id) => {
193                    use_prelude = !module.no_implicit_prelude;
194                    match self.hygienic_lexical_parent(module, &mut ctxt, derive_fallback_lint_id) {
195                        Some((parent_module, lint_id)) => {
196                            Scope::Module(parent_module, lint_id.or(prev_lint_id))
197                        }
198                        None => {
199                            ctxt.adjust(ExpnId::root());
200                            match ns {
201                                TypeNS => Scope::ExternPreludeItems,
202                                ValueNS => Scope::StdLibPrelude,
203                                MacroNS => Scope::MacroUsePrelude,
204                            }
205                        }
206                    }
207                }
208                Scope::MacroUsePrelude => Scope::StdLibPrelude,
209                Scope::BuiltinAttrs => break, // nowhere else to search
210                Scope::ExternPreludeItems => Scope::ExternPreludeFlags,
211                Scope::ExternPreludeFlags if module_and_extern_prelude || extern_prelude => break,
212                Scope::ExternPreludeFlags => Scope::ToolPrelude,
213                Scope::ToolPrelude => Scope::StdLibPrelude,
214                Scope::StdLibPrelude => match ns {
215                    TypeNS => Scope::BuiltinTypes,
216                    ValueNS => break, // nowhere else to search
217                    MacroNS => Scope::BuiltinAttrs,
218                },
219                Scope::BuiltinTypes => break, // nowhere else to search
220            };
221        }
222
223        None
224    }
225
226    fn hygienic_lexical_parent(
227        &self,
228        module: Module<'ra>,
229        ctxt: &mut SyntaxContext,
230        derive_fallback_lint_id: Option<NodeId>,
231    ) -> Option<(Module<'ra>, Option<NodeId>)> {
232        if !module.expansion.outer_expn_is_descendant_of(*ctxt) {
233            return Some((self.expn_def_scope(ctxt.remove_mark()), None));
234        }
235
236        if let ModuleKind::Block = module.kind {
237            return Some((module.parent.unwrap().nearest_item_scope(), None));
238        }
239
240        // We need to support the next case under a deprecation warning
241        // ```
242        // struct MyStruct;
243        // ---- begin: this comes from a proc macro derive
244        // mod implementation_details {
245        //     // Note that `MyStruct` is not in scope here.
246        //     impl SomeTrait for MyStruct { ... }
247        // }
248        // ---- end
249        // ```
250        // So we have to fall back to the module's parent during lexical resolution in this case.
251        if derive_fallback_lint_id.is_some()
252            && let Some(parent) = module.parent
253            // Inner module is inside the macro
254            && module.expansion != parent.expansion
255            // Parent module is outside of the macro
256            && module.expansion.is_descendant_of(parent.expansion)
257            // The macro is a proc macro derive
258            && let Some(def_id) = module.expansion.expn_data().macro_def_id
259        {
260            let ext = &self.get_macro_by_def_id(def_id).ext;
261            if ext.builtin_name.is_none()
262                && ext.macro_kinds() == MacroKinds::DERIVE
263                && parent.expansion.outer_expn_is_descendant_of(*ctxt)
264            {
265                return Some((parent, derive_fallback_lint_id));
266            }
267        }
268
269        None
270    }
271
272    /// This resolves the identifier `ident` in the namespace `ns` in the current lexical scope.
273    /// More specifically, we proceed up the hierarchy of scopes and return the binding for
274    /// `ident` in the first scope that defines it (or None if no scopes define it).
275    ///
276    /// A block's items are above its local variables in the scope hierarchy, regardless of where
277    /// the items are defined in the block. For example,
278    /// ```rust
279    /// fn f() {
280    ///    g(); // Since there are no local variables in scope yet, this resolves to the item.
281    ///    let g = || {};
282    ///    fn g() {}
283    ///    g(); // This resolves to the local variable `g` since it shadows the item.
284    /// }
285    /// ```
286    ///
287    /// Invariant: This must only be called during main resolution, not during
288    /// import resolution.
289    #[instrument(level = "debug", skip(self, ribs))]
290    pub(crate) fn resolve_ident_in_lexical_scope(
291        &mut self,
292        mut ident: Ident,
293        ns: Namespace,
294        parent_scope: &ParentScope<'ra>,
295        finalize: Option<Finalize>,
296        ribs: &[Rib<'ra>],
297        ignore_binding: Option<NameBinding<'ra>>,
298    ) -> Option<LexicalScopeBinding<'ra>> {
299        assert!(ns == TypeNS || ns == ValueNS);
300        let orig_ident = ident;
301        let (general_span, normalized_span) = if ident.name == kw::SelfUpper {
302            // FIXME(jseyfried) improve `Self` hygiene
303            let empty_span = ident.span.with_ctxt(SyntaxContext::root());
304            (empty_span, empty_span)
305        } else if ns == TypeNS {
306            let normalized_span = ident.span.normalize_to_macros_2_0();
307            (normalized_span, normalized_span)
308        } else {
309            (ident.span.normalize_to_macro_rules(), ident.span.normalize_to_macros_2_0())
310        };
311        ident.span = general_span;
312        let normalized_ident = Ident { span: normalized_span, ..ident };
313
314        // Walk backwards up the ribs in scope.
315        for (i, rib) in ribs.iter().enumerate().rev() {
316            debug!("walk rib\n{:?}", rib.bindings);
317            // Use the rib kind to determine whether we are resolving parameters
318            // (macro 2.0 hygiene) or local variables (`macro_rules` hygiene).
319            let rib_ident = if rib.kind.contains_params() { normalized_ident } else { ident };
320            if let Some((original_rib_ident_def, res)) = rib.bindings.get_key_value(&rib_ident) {
321                // The ident resolves to a type parameter or local variable.
322                return Some(LexicalScopeBinding::Res(self.validate_res_from_ribs(
323                    i,
324                    rib_ident,
325                    *res,
326                    finalize.map(|finalize| finalize.path_span),
327                    *original_rib_ident_def,
328                    ribs,
329                )));
330            } else if let RibKind::Block(Some(module)) = rib.kind
331                && let Ok(binding) = self.cm().resolve_ident_in_module_unadjusted(
332                    ModuleOrUniformRoot::Module(module),
333                    ident,
334                    ns,
335                    parent_scope,
336                    Shadowing::Unrestricted,
337                    finalize.map(|finalize| Finalize { used: Used::Scope, ..finalize }),
338                    ignore_binding,
339                    None,
340                )
341            {
342                // The ident resolves to an item in a block.
343                return Some(LexicalScopeBinding::Item(binding));
344            } else if let RibKind::Module(module) = rib.kind {
345                // Encountered a module item, abandon ribs and look into that module and preludes.
346                let parent_scope = &ParentScope { module, ..*parent_scope };
347                let finalize = finalize.map(|f| Finalize { stage: Stage::Late, ..f });
348                return self
349                    .cm()
350                    .resolve_ident_in_scope_set(
351                        orig_ident,
352                        ScopeSet::All(ns),
353                        parent_scope,
354                        finalize,
355                        finalize.is_some(),
356                        ignore_binding,
357                        None,
358                    )
359                    .ok()
360                    .map(LexicalScopeBinding::Item);
361            }
362
363            if let RibKind::MacroDefinition(def) = rib.kind
364                && def == self.macro_def(ident.span.ctxt())
365            {
366                // If an invocation of this macro created `ident`, give up on `ident`
367                // and switch to `ident`'s source from the macro definition.
368                ident.span.remove_mark();
369            }
370        }
371
372        unreachable!()
373    }
374
375    /// Resolve an identifier in the specified set of scopes.
376    #[instrument(level = "debug", skip(self))]
377    pub(crate) fn resolve_ident_in_scope_set<'r>(
378        self: CmResolver<'r, 'ra, 'tcx>,
379        orig_ident: Ident,
380        scope_set: ScopeSet<'ra>,
381        parent_scope: &ParentScope<'ra>,
382        finalize: Option<Finalize>,
383        force: bool,
384        ignore_binding: Option<NameBinding<'ra>>,
385        ignore_import: Option<Import<'ra>>,
386    ) -> Result<NameBinding<'ra>, Determinacy> {
387        bitflags::bitflags! {
388            #[derive(Clone, Copy)]
389            struct Flags: u8 {
390                const MACRO_RULES          = 1 << 0;
391                const MODULE               = 1 << 1;
392                const MISC_SUGGEST_CRATE   = 1 << 2;
393                const MISC_SUGGEST_SELF    = 1 << 3;
394                const MISC_FROM_PRELUDE    = 1 << 4;
395            }
396        }
397
398        assert!(force || finalize.is_none()); // `finalize` implies `force`
399
400        // Make sure `self`, `super` etc produce an error when passed to here.
401        if orig_ident.is_path_segment_keyword() {
402            return Err(Determinacy::Determined);
403        }
404
405        let (ns, macro_kind) = match scope_set {
406            ScopeSet::All(ns) | ScopeSet::ModuleAndExternPrelude(ns, _) => (ns, None),
407            ScopeSet::ExternPrelude => (TypeNS, None),
408            ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind)),
409        };
410
411        // This is *the* result, resolution from the scope closest to the resolved identifier.
412        // However, sometimes this result is "weak" because it comes from a glob import or
413        // a macro expansion, and in this case it cannot shadow names from outer scopes, e.g.
414        // mod m { ... } // solution in outer scope
415        // {
416        //     use prefix::*; // imports another `m` - innermost solution
417        //                    // weak, cannot shadow the outer `m`, need to report ambiguity error
418        //     m::mac!();
419        // }
420        // So we have to save the innermost solution and continue searching in outer scopes
421        // to detect potential ambiguities.
422        let mut innermost_result: Option<(NameBinding<'_>, Flags)> = None;
423        let mut determinacy = Determinacy::Determined;
424        let mut extern_prelude_item_binding = None;
425        let mut extern_prelude_flag_binding = None;
426        // Shadowed bindings don't need to be marked as used or non-speculatively loaded.
427        macro finalize_scope() {
428            if innermost_result.is_none() { finalize } else { None }
429        }
430
431        // Go through all the scopes and try to resolve the name.
432        let derive_fallback_lint_id = match finalize {
433            Some(Finalize { node_id, stage: Stage::Late, .. }) => Some(node_id),
434            _ => None,
435        };
436        let break_result = self.visit_scopes(
437            scope_set,
438            parent_scope,
439            orig_ident.span.ctxt(),
440            derive_fallback_lint_id,
441            |this, scope, use_prelude, ctxt| {
442                let ident = Ident::new(orig_ident.name, orig_ident.span.with_ctxt(ctxt));
443                let result = match scope {
444                    Scope::DeriveHelpers(expn_id) => {
445                        if let Some(binding) = this.helper_attrs.get(&expn_id).and_then(|attrs| {
446                            attrs.iter().rfind(|(i, _)| ident == *i).map(|(_, binding)| *binding)
447                        }) {
448                            Ok((binding, Flags::empty()))
449                        } else {
450                            Err(Determinacy::Determined)
451                        }
452                    }
453                    Scope::DeriveHelpersCompat => {
454                        let mut result = Err(Determinacy::Determined);
455                        for derive in parent_scope.derives {
456                            let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
457                            match this.reborrow().resolve_macro_path(
458                                derive,
459                                MacroKind::Derive,
460                                parent_scope,
461                                true,
462                                force,
463                                ignore_import,
464                                None,
465                            ) {
466                                Ok((Some(ext), _)) => {
467                                    if ext.helper_attrs.contains(&ident.name) {
468                                        let binding = this.arenas.new_pub_res_binding(
469                                            Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat),
470                                            derive.span,
471                                            LocalExpnId::ROOT,
472                                        );
473                                        result = Ok((binding, Flags::empty()));
474                                        break;
475                                    }
476                                }
477                                Ok(_) | Err(Determinacy::Determined) => {}
478                                Err(Determinacy::Undetermined) => {
479                                    result = Err(Determinacy::Undetermined)
480                                }
481                            }
482                        }
483                        result
484                    }
485                    Scope::MacroRules(macro_rules_scope) => match macro_rules_scope.get() {
486                        MacroRulesScope::Binding(macro_rules_binding)
487                            if ident == macro_rules_binding.ident =>
488                        {
489                            Ok((macro_rules_binding.binding, Flags::MACRO_RULES))
490                        }
491                        MacroRulesScope::Invocation(_) => Err(Determinacy::Undetermined),
492                        _ => Err(Determinacy::Determined),
493                    },
494                    Scope::Module(module, derive_fallback_lint_id) => {
495                        // FIXME: use `finalize_scope` here.
496                        let (adjusted_parent_scope, adjusted_finalize) =
497                            if matches!(scope_set, ScopeSet::ModuleAndExternPrelude(..)) {
498                                (parent_scope, finalize)
499                            } else {
500                                (
501                                    &ParentScope { module, ..*parent_scope },
502                                    finalize.map(|f| Finalize { used: Used::Scope, ..f }),
503                                )
504                            };
505                        let binding = this.reborrow().resolve_ident_in_module_unadjusted(
506                            ModuleOrUniformRoot::Module(module),
507                            ident,
508                            ns,
509                            adjusted_parent_scope,
510                            Shadowing::Restricted,
511                            adjusted_finalize,
512                            ignore_binding,
513                            ignore_import,
514                        );
515                        match binding {
516                            Ok(binding) => {
517                                if let Some(lint_id) = derive_fallback_lint_id {
518                                    this.get_mut().lint_buffer.buffer_lint(
519                                        PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
520                                        lint_id,
521                                        orig_ident.span,
522                                        errors::ProcMacroDeriveResolutionFallback {
523                                            span: orig_ident.span,
524                                            ns_descr: ns.descr(),
525                                            ident,
526                                        },
527                                    );
528                                }
529                                let misc_flags = if module == this.graph_root {
530                                    Flags::MISC_SUGGEST_CRATE
531                                } else if module.is_normal() {
532                                    Flags::MISC_SUGGEST_SELF
533                                } else {
534                                    Flags::empty()
535                                };
536                                Ok((binding, Flags::MODULE | misc_flags))
537                            }
538                            Err((Determinacy::Undetermined, Weak::No)) => {
539                                return Some(Err(Determinacy::determined(force)));
540                            }
541                            Err((Determinacy::Undetermined, Weak::Yes)) => {
542                                Err(Determinacy::Undetermined)
543                            }
544                            Err((Determinacy::Determined, _)) => Err(Determinacy::Determined),
545                        }
546                    }
547                    Scope::MacroUsePrelude => {
548                        match this.macro_use_prelude.get(&ident.name).cloned() {
549                            Some(binding) => Ok((binding, Flags::MISC_FROM_PRELUDE)),
550                            None => Err(Determinacy::determined(
551                                this.graph_root.unexpanded_invocations.borrow().is_empty(),
552                            )),
553                        }
554                    }
555                    Scope::BuiltinAttrs => match this.builtin_attrs_bindings.get(&ident.name) {
556                        Some(binding) => Ok((*binding, Flags::empty())),
557                        None => Err(Determinacy::Determined),
558                    },
559                    Scope::ExternPreludeItems => {
560                        // FIXME: use `finalize_scope` here.
561                        match this.reborrow().extern_prelude_get_item(ident, finalize.is_some()) {
562                            Some(binding) => {
563                                extern_prelude_item_binding = Some(binding);
564                                Ok((binding, Flags::empty()))
565                            }
566                            None => Err(Determinacy::determined(
567                                this.graph_root.unexpanded_invocations.borrow().is_empty(),
568                            )),
569                        }
570                    }
571                    Scope::ExternPreludeFlags => {
572                        match this.extern_prelude_get_flag(ident, finalize_scope!().is_some()) {
573                            Some(binding) => {
574                                extern_prelude_flag_binding = Some(binding);
575                                Ok((binding, Flags::empty()))
576                            }
577                            None => Err(Determinacy::Determined),
578                        }
579                    }
580                    Scope::ToolPrelude => match this.registered_tool_bindings.get(&ident) {
581                        Some(binding) => Ok((*binding, Flags::empty())),
582                        None => Err(Determinacy::Determined),
583                    },
584                    Scope::StdLibPrelude => {
585                        let mut result = Err(Determinacy::Determined);
586                        if let Some(prelude) = this.prelude
587                            && let Ok(binding) = this.reborrow().resolve_ident_in_module_unadjusted(
588                                ModuleOrUniformRoot::Module(prelude),
589                                ident,
590                                ns,
591                                parent_scope,
592                                Shadowing::Unrestricted,
593                                None,
594                                ignore_binding,
595                                ignore_import,
596                            )
597                            && (matches!(use_prelude, UsePrelude::Yes)
598                                || this.is_builtin_macro(binding.res()))
599                        {
600                            result = Ok((binding, Flags::MISC_FROM_PRELUDE));
601                        }
602
603                        result
604                    }
605                    Scope::BuiltinTypes => match this.builtin_types_bindings.get(&ident.name) {
606                        Some(binding) => {
607                            if matches!(ident.name, sym::f16)
608                                && !this.tcx.features().f16()
609                                && !ident.span.allows_unstable(sym::f16)
610                                && finalize_scope!().is_some()
611                            {
612                                feature_err(
613                                    this.tcx.sess,
614                                    sym::f16,
615                                    ident.span,
616                                    "the type `f16` is unstable",
617                                )
618                                .emit();
619                            }
620                            if matches!(ident.name, sym::f128)
621                                && !this.tcx.features().f128()
622                                && !ident.span.allows_unstable(sym::f128)
623                                && finalize_scope!().is_some()
624                            {
625                                feature_err(
626                                    this.tcx.sess,
627                                    sym::f128,
628                                    ident.span,
629                                    "the type `f128` is unstable",
630                                )
631                                .emit();
632                            }
633                            Ok((*binding, Flags::empty()))
634                        }
635                        None => Err(Determinacy::Determined),
636                    },
637                };
638
639                match result {
640                    Ok((binding, flags)) => {
641                        if !sub_namespace_match(binding.macro_kinds(), macro_kind) {
642                            return None;
643                        }
644
645                        // Below we report various ambiguity errors.
646                        // We do not need to report them if we are either in speculative resolution,
647                        // or in late resolution when everything is already imported and expanded
648                        // and no ambiguities exist.
649                        if matches!(finalize, None | Some(Finalize { stage: Stage::Late, .. })) {
650                            return Some(Ok(binding));
651                        }
652
653                        if let Some((innermost_binding, innermost_flags)) = innermost_result {
654                            // Found another solution, if the first one was "weak", report an error.
655                            let (res, innermost_res) = (binding.res(), innermost_binding.res());
656                            if res != innermost_res {
657                                let is_builtin = |res| {
658                                    matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Builtin(..)))
659                                };
660                                let derive_helper =
661                                    Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
662                                let derive_helper_compat =
663                                    Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
664
665                                let ambiguity_error_kind = if is_builtin(innermost_res)
666                                    || is_builtin(res)
667                                {
668                                    Some(AmbiguityKind::BuiltinAttr)
669                                } else if innermost_res == derive_helper_compat
670                                    || res == derive_helper_compat && innermost_res != derive_helper
671                                {
672                                    Some(AmbiguityKind::DeriveHelper)
673                                } else if innermost_flags.contains(Flags::MACRO_RULES)
674                                    && flags.contains(Flags::MODULE)
675                                    && !this.disambiguate_macro_rules_vs_modularized(
676                                        innermost_binding,
677                                        binding,
678                                    )
679                                    || flags.contains(Flags::MACRO_RULES)
680                                        && innermost_flags.contains(Flags::MODULE)
681                                        && !this.disambiguate_macro_rules_vs_modularized(
682                                            binding,
683                                            innermost_binding,
684                                        )
685                                {
686                                    Some(AmbiguityKind::MacroRulesVsModularized)
687                                } else if innermost_binding.is_glob_import() {
688                                    Some(AmbiguityKind::GlobVsOuter)
689                                } else if innermost_binding
690                                    .may_appear_after(parent_scope.expansion, binding)
691                                {
692                                    Some(AmbiguityKind::MoreExpandedVsOuter)
693                                } else {
694                                    None
695                                };
696                                // Skip ambiguity errors for extern flag bindings "overridden"
697                                // by extern item bindings.
698                                // FIXME: Remove with lang team approval.
699                                let issue_145575_hack = Some(binding)
700                                    == extern_prelude_flag_binding
701                                    && extern_prelude_item_binding.is_some()
702                                    && extern_prelude_item_binding != Some(innermost_binding);
703                                if let Some(kind) = ambiguity_error_kind
704                                    && !issue_145575_hack
705                                {
706                                    let misc = |f: Flags| {
707                                        if f.contains(Flags::MISC_SUGGEST_CRATE) {
708                                            AmbiguityErrorMisc::SuggestCrate
709                                        } else if f.contains(Flags::MISC_SUGGEST_SELF) {
710                                            AmbiguityErrorMisc::SuggestSelf
711                                        } else if f.contains(Flags::MISC_FROM_PRELUDE) {
712                                            AmbiguityErrorMisc::FromPrelude
713                                        } else {
714                                            AmbiguityErrorMisc::None
715                                        }
716                                    };
717                                    this.get_mut().ambiguity_errors.push(AmbiguityError {
718                                        kind,
719                                        ident: orig_ident,
720                                        b1: innermost_binding,
721                                        b2: binding,
722                                        warning: false,
723                                        misc1: misc(innermost_flags),
724                                        misc2: misc(flags),
725                                    });
726                                    return Some(Ok(innermost_binding));
727                                }
728                            }
729                        } else {
730                            // Found the first solution.
731                            innermost_result = Some((binding, flags));
732                        }
733                    }
734                    Err(Determinacy::Determined) => {}
735                    Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined,
736                }
737
738                None
739            },
740        );
741
742        if let Some(break_result) = break_result {
743            return break_result;
744        }
745
746        // The first found solution was the only one, return it.
747        if let Some((binding, _)) = innermost_result {
748            return Ok(binding);
749        }
750
751        Err(Determinacy::determined(determinacy == Determinacy::Determined || force))
752    }
753
754    #[instrument(level = "debug", skip(self))]
755    pub(crate) fn maybe_resolve_ident_in_module<'r>(
756        self: CmResolver<'r, 'ra, 'tcx>,
757        module: ModuleOrUniformRoot<'ra>,
758        ident: Ident,
759        ns: Namespace,
760        parent_scope: &ParentScope<'ra>,
761        ignore_import: Option<Import<'ra>>,
762    ) -> Result<NameBinding<'ra>, Determinacy> {
763        self.resolve_ident_in_module(module, ident, ns, parent_scope, None, None, ignore_import)
764            .map_err(|(determinacy, _)| determinacy)
765    }
766
767    #[instrument(level = "debug", skip(self))]
768    pub(crate) fn resolve_ident_in_module<'r>(
769        self: CmResolver<'r, 'ra, 'tcx>,
770        module: ModuleOrUniformRoot<'ra>,
771        mut ident: Ident,
772        ns: Namespace,
773        parent_scope: &ParentScope<'ra>,
774        finalize: Option<Finalize>,
775        ignore_binding: Option<NameBinding<'ra>>,
776        ignore_import: Option<Import<'ra>>,
777    ) -> Result<NameBinding<'ra>, (Determinacy, Weak)> {
778        let tmp_parent_scope;
779        let mut adjusted_parent_scope = parent_scope;
780        match module {
781            ModuleOrUniformRoot::Module(m) => {
782                if let Some(def) = ident.span.normalize_to_macros_2_0_and_adjust(m.expansion) {
783                    tmp_parent_scope =
784                        ParentScope { module: self.expn_def_scope(def), ..*parent_scope };
785                    adjusted_parent_scope = &tmp_parent_scope;
786                }
787            }
788            ModuleOrUniformRoot::ExternPrelude => {
789                ident.span.normalize_to_macros_2_0_and_adjust(ExpnId::root());
790            }
791            ModuleOrUniformRoot::ModuleAndExternPrelude(..) | ModuleOrUniformRoot::CurrentScope => {
792                // No adjustments
793            }
794        }
795        self.resolve_ident_in_module_unadjusted(
796            module,
797            ident,
798            ns,
799            adjusted_parent_scope,
800            Shadowing::Unrestricted,
801            finalize,
802            ignore_binding,
803            ignore_import,
804        )
805    }
806    /// Attempts to resolve `ident` in namespaces `ns` of `module`.
807    /// Invariant: if `finalize` is `Some`, expansion and import resolution must be complete.
808    #[instrument(level = "debug", skip(self))]
809    fn resolve_ident_in_module_unadjusted<'r>(
810        mut self: CmResolver<'r, 'ra, 'tcx>,
811        module: ModuleOrUniformRoot<'ra>,
812        ident: Ident,
813        ns: Namespace,
814        parent_scope: &ParentScope<'ra>,
815        shadowing: Shadowing,
816        finalize: Option<Finalize>,
817        // This binding should be ignored during in-module resolution, so that we don't get
818        // "self-confirming" import resolutions during import validation and checking.
819        ignore_binding: Option<NameBinding<'ra>>,
820        ignore_import: Option<Import<'ra>>,
821    ) -> Result<NameBinding<'ra>, (Determinacy, Weak)> {
822        let module = match module {
823            ModuleOrUniformRoot::Module(module) => module,
824            ModuleOrUniformRoot::ModuleAndExternPrelude(module) => {
825                assert_eq!(shadowing, Shadowing::Unrestricted);
826                let binding = self.resolve_ident_in_scope_set(
827                    ident,
828                    ScopeSet::ModuleAndExternPrelude(ns, module),
829                    parent_scope,
830                    finalize,
831                    finalize.is_some(),
832                    ignore_binding,
833                    ignore_import,
834                );
835                return binding.map_err(|determinacy| (determinacy, Weak::No));
836            }
837            ModuleOrUniformRoot::ExternPrelude => {
838                assert_eq!(shadowing, Shadowing::Unrestricted);
839                return if ns != TypeNS {
840                    Err((Determined, Weak::No))
841                } else {
842                    let binding = self.resolve_ident_in_scope_set(
843                        ident,
844                        ScopeSet::ExternPrelude,
845                        parent_scope,
846                        finalize,
847                        finalize.is_some(),
848                        ignore_binding,
849                        ignore_import,
850                    );
851                    return binding.map_err(|determinacy| (determinacy, Weak::No));
852                };
853            }
854            ModuleOrUniformRoot::CurrentScope => {
855                assert_eq!(shadowing, Shadowing::Unrestricted);
856                if ns == TypeNS {
857                    if ident.name == kw::Crate || ident.name == kw::DollarCrate {
858                        let module = self.resolve_crate_root(ident);
859                        return Ok(module.self_binding.unwrap());
860                    } else if ident.name == kw::Super || ident.name == kw::SelfLower {
861                        // FIXME: Implement these with renaming requirements so that e.g.
862                        // `use super;` doesn't work, but `use super as name;` does.
863                        // Fall through here to get an error from `early_resolve_...`.
864                    }
865                }
866
867                let binding = self.resolve_ident_in_scope_set(
868                    ident,
869                    ScopeSet::All(ns),
870                    parent_scope,
871                    finalize,
872                    finalize.is_some(),
873                    ignore_binding,
874                    ignore_import,
875                );
876                return binding.map_err(|determinacy| (determinacy, Weak::No));
877            }
878        };
879
880        let key = BindingKey::new(ident, ns);
881        // `try_borrow_mut` is required to ensure exclusive access, even if the resulting binding
882        // doesn't need to be mutable. It will fail when there is a cycle of imports, and without
883        // the exclusive access infinite recursion will crash the compiler with stack overflow.
884        let resolution = &*self
885            .resolution_or_default(module, key)
886            .try_borrow_mut()
887            .map_err(|_| (Determined, Weak::No))?;
888
889        // If the primary binding is unusable, search further and return the shadowed glob
890        // binding if it exists. What we really want here is having two separate scopes in
891        // a module - one for non-globs and one for globs, but until that's done use this
892        // hack to avoid inconsistent resolution ICEs during import validation.
893        let binding = [resolution.non_glob_binding, resolution.glob_binding]
894            .into_iter()
895            .find_map(|binding| if binding == ignore_binding { None } else { binding });
896
897        if let Some(finalize) = finalize {
898            return self.get_mut().finalize_module_binding(
899                ident,
900                binding,
901                if resolution.non_glob_binding.is_some() { resolution.glob_binding } else { None },
902                parent_scope,
903                finalize,
904                shadowing,
905            );
906        }
907
908        let check_usable = |this: CmResolver<'r, 'ra, 'tcx>, binding: NameBinding<'ra>| {
909            let usable = this.is_accessible_from(binding.vis, parent_scope.module);
910            if usable { Ok(binding) } else { Err((Determined, Weak::No)) }
911        };
912
913        // Items and single imports are not shadowable, if we have one, then it's determined.
914        if let Some(binding) = binding
915            && !binding.is_glob_import()
916        {
917            return check_usable(self, binding);
918        }
919
920        // --- From now on we either have a glob resolution or no resolution. ---
921
922        // Check if one of single imports can still define the name,
923        // if it can then our result is not determined and can be invalidated.
924        if self.reborrow().single_import_can_define_name(
925            &resolution,
926            binding,
927            ns,
928            ignore_import,
929            ignore_binding,
930            parent_scope,
931        ) {
932            return Err((Undetermined, Weak::No));
933        }
934
935        // So we have a resolution that's from a glob import. This resolution is determined
936        // if it cannot be shadowed by some new item/import expanded from a macro.
937        // This happens either if there are no unexpanded macros, or expanded names cannot
938        // shadow globs (that happens in macro namespace or with restricted shadowing).
939        //
940        // Additionally, any macro in any module can plant names in the root module if it creates
941        // `macro_export` macros, so the root module effectively has unresolved invocations if any
942        // module has unresolved invocations.
943        // However, it causes resolution/expansion to stuck too often (#53144), so, to make
944        // progress, we have to ignore those potential unresolved invocations from other modules
945        // and prohibit access to macro-expanded `macro_export` macros instead (unless restricted
946        // shadowing is enabled, see `macro_expanded_macro_export_errors`).
947        if let Some(binding) = binding {
948            if binding.determined() || ns == MacroNS || shadowing == Shadowing::Restricted {
949                return check_usable(self, binding);
950            } else {
951                return Err((Undetermined, Weak::No));
952            }
953        }
954
955        // --- From now on we have no resolution. ---
956
957        // Now we are in situation when new item/import can appear only from a glob or a macro
958        // expansion. With restricted shadowing names from globs and macro expansions cannot
959        // shadow names from outer scopes, so we can freely fallback from module search to search
960        // in outer scopes. For `resolve_ident_in_scope_set` to continue search in outer
961        // scopes we return `Undetermined` with `Weak::Yes`.
962
963        // Check if one of unexpanded macros can still define the name,
964        // if it can then our "no resolution" result is not determined and can be invalidated.
965        if !module.unexpanded_invocations.borrow().is_empty() {
966            return Err((Undetermined, Weak::Yes));
967        }
968
969        // Check if one of glob imports can still define the name,
970        // if it can then our "no resolution" result is not determined and can be invalidated.
971        for glob_import in module.globs.borrow().iter() {
972            if ignore_import == Some(*glob_import) {
973                continue;
974            }
975            if !self.is_accessible_from(glob_import.vis, parent_scope.module) {
976                continue;
977            }
978            let module = match glob_import.imported_module.get() {
979                Some(ModuleOrUniformRoot::Module(module)) => module,
980                Some(_) => continue,
981                None => return Err((Undetermined, Weak::Yes)),
982            };
983            let tmp_parent_scope;
984            let (mut adjusted_parent_scope, mut ident) =
985                (parent_scope, ident.normalize_to_macros_2_0());
986            match ident.span.glob_adjust(module.expansion, glob_import.span) {
987                Some(Some(def)) => {
988                    tmp_parent_scope =
989                        ParentScope { module: self.expn_def_scope(def), ..*parent_scope };
990                    adjusted_parent_scope = &tmp_parent_scope;
991                }
992                Some(None) => {}
993                None => continue,
994            };
995            let result = self.reborrow().resolve_ident_in_module_unadjusted(
996                ModuleOrUniformRoot::Module(module),
997                ident,
998                ns,
999                adjusted_parent_scope,
1000                Shadowing::Unrestricted,
1001                None,
1002                ignore_binding,
1003                ignore_import,
1004            );
1005
1006            match result {
1007                Err((Determined, _)) => continue,
1008                Ok(binding)
1009                    if !self.is_accessible_from(binding.vis, glob_import.parent_scope.module) =>
1010                {
1011                    continue;
1012                }
1013                Ok(_) | Err((Undetermined, _)) => return Err((Undetermined, Weak::Yes)),
1014            }
1015        }
1016
1017        // No resolution and no one else can define the name - determinate error.
1018        Err((Determined, Weak::No))
1019    }
1020
1021    fn finalize_module_binding(
1022        &mut self,
1023        ident: Ident,
1024        binding: Option<NameBinding<'ra>>,
1025        shadowed_glob: Option<NameBinding<'ra>>,
1026        parent_scope: &ParentScope<'ra>,
1027        finalize: Finalize,
1028        shadowing: Shadowing,
1029    ) -> Result<NameBinding<'ra>, (Determinacy, Weak)> {
1030        let Finalize { path_span, report_private, used, root_span, .. } = finalize;
1031
1032        let Some(binding) = binding else {
1033            return Err((Determined, Weak::No));
1034        };
1035
1036        if !self.is_accessible_from(binding.vis, parent_scope.module) {
1037            if report_private {
1038                self.privacy_errors.push(PrivacyError {
1039                    ident,
1040                    binding,
1041                    dedup_span: path_span,
1042                    outermost_res: None,
1043                    source: None,
1044                    parent_scope: *parent_scope,
1045                    single_nested: path_span != root_span,
1046                });
1047            } else {
1048                return Err((Determined, Weak::No));
1049            }
1050        }
1051
1052        // Forbid expanded shadowing to avoid time travel.
1053        if let Some(shadowed_glob) = shadowed_glob
1054            && shadowing == Shadowing::Restricted
1055            && finalize.stage == Stage::Early
1056            && binding.expansion != LocalExpnId::ROOT
1057            && binding.res() != shadowed_glob.res()
1058        {
1059            self.ambiguity_errors.push(AmbiguityError {
1060                kind: AmbiguityKind::GlobVsExpanded,
1061                ident,
1062                b1: binding,
1063                b2: shadowed_glob,
1064                warning: false,
1065                misc1: AmbiguityErrorMisc::None,
1066                misc2: AmbiguityErrorMisc::None,
1067            });
1068        }
1069
1070        if shadowing == Shadowing::Unrestricted
1071            && binding.expansion != LocalExpnId::ROOT
1072            && let NameBindingKind::Import { import, .. } = binding.kind
1073            && matches!(import.kind, ImportKind::MacroExport)
1074        {
1075            self.macro_expanded_macro_export_errors.insert((path_span, binding.span));
1076        }
1077
1078        self.record_use(ident, binding, used);
1079        return Ok(binding);
1080    }
1081
1082    // Checks if a single import can define the `Ident` corresponding to `binding`.
1083    // This is used to check whether we can definitively accept a glob as a resolution.
1084    fn single_import_can_define_name<'r>(
1085        mut self: CmResolver<'r, 'ra, 'tcx>,
1086        resolution: &NameResolution<'ra>,
1087        binding: Option<NameBinding<'ra>>,
1088        ns: Namespace,
1089        ignore_import: Option<Import<'ra>>,
1090        ignore_binding: Option<NameBinding<'ra>>,
1091        parent_scope: &ParentScope<'ra>,
1092    ) -> bool {
1093        for single_import in &resolution.single_imports {
1094            if ignore_import == Some(*single_import) {
1095                continue;
1096            }
1097            if !self.is_accessible_from(single_import.vis, parent_scope.module) {
1098                continue;
1099            }
1100            if let Some(ignored) = ignore_binding
1101                && let NameBindingKind::Import { import, .. } = ignored.kind
1102                && import == *single_import
1103            {
1104                continue;
1105            }
1106
1107            let Some(module) = single_import.imported_module.get() else {
1108                return true;
1109            };
1110            let ImportKind::Single { source, target, bindings, .. } = &single_import.kind else {
1111                unreachable!();
1112            };
1113            if source != target {
1114                if bindings.iter().all(|binding| binding.get().binding().is_none()) {
1115                    return true;
1116                } else if bindings[ns].get().binding().is_none() && binding.is_some() {
1117                    return true;
1118                }
1119            }
1120
1121            match self.reborrow().resolve_ident_in_module(
1122                module,
1123                *source,
1124                ns,
1125                &single_import.parent_scope,
1126                None,
1127                ignore_binding,
1128                ignore_import,
1129            ) {
1130                Err((Determined, _)) => continue,
1131                Ok(binding)
1132                    if !self.is_accessible_from(binding.vis, single_import.parent_scope.module) =>
1133                {
1134                    continue;
1135                }
1136                Ok(_) | Err((Undetermined, _)) => {
1137                    return true;
1138                }
1139            }
1140        }
1141
1142        false
1143    }
1144
1145    /// Validate a local resolution (from ribs).
1146    #[instrument(level = "debug", skip(self, all_ribs))]
1147    fn validate_res_from_ribs(
1148        &mut self,
1149        rib_index: usize,
1150        rib_ident: Ident,
1151        mut res: Res,
1152        finalize: Option<Span>,
1153        original_rib_ident_def: Ident,
1154        all_ribs: &[Rib<'ra>],
1155    ) -> Res {
1156        debug!("validate_res_from_ribs({:?})", res);
1157        let ribs = &all_ribs[rib_index + 1..];
1158
1159        // An invalid forward use of a generic parameter from a previous default
1160        // or in a const param ty.
1161        if let RibKind::ForwardGenericParamBan(reason) = all_ribs[rib_index].kind {
1162            if let Some(span) = finalize {
1163                let res_error = if rib_ident.name == kw::SelfUpper {
1164                    ResolutionError::ForwardDeclaredSelf(reason)
1165                } else {
1166                    ResolutionError::ForwardDeclaredGenericParam(rib_ident.name, reason)
1167                };
1168                self.report_error(span, res_error);
1169            }
1170            assert_eq!(res, Res::Err);
1171            return Res::Err;
1172        }
1173
1174        match res {
1175            Res::Local(_) => {
1176                use ResolutionError::*;
1177                let mut res_err = None;
1178
1179                for rib in ribs {
1180                    match rib.kind {
1181                        RibKind::Normal
1182                        | RibKind::Block(..)
1183                        | RibKind::FnOrCoroutine
1184                        | RibKind::Module(..)
1185                        | RibKind::MacroDefinition(..)
1186                        | RibKind::ForwardGenericParamBan(_) => {
1187                            // Nothing to do. Continue.
1188                        }
1189                        RibKind::Item(..) | RibKind::AssocItem => {
1190                            // This was an attempt to access an upvar inside a
1191                            // named function item. This is not allowed, so we
1192                            // report an error.
1193                            if let Some(span) = finalize {
1194                                // We don't immediately trigger a resolve error, because
1195                                // we want certain other resolution errors (namely those
1196                                // emitted for `ConstantItemRibKind` below) to take
1197                                // precedence.
1198                                res_err = Some((span, CannotCaptureDynamicEnvironmentInFnItem));
1199                            }
1200                        }
1201                        RibKind::ConstantItem(_, item) => {
1202                            // Still doesn't deal with upvars
1203                            if let Some(span) = finalize {
1204                                let (span, resolution_error) = match item {
1205                                    None if rib_ident.name == kw::SelfLower => {
1206                                        (span, LowercaseSelf)
1207                                    }
1208                                    None => {
1209                                        // If we have a `let name = expr;`, we have the span for
1210                                        // `name` and use that to see if it is followed by a type
1211                                        // specifier. If not, then we know we need to suggest
1212                                        // `const name: Ty = expr;`. This is a heuristic, it will
1213                                        // break down in the presence of macros.
1214                                        let sm = self.tcx.sess.source_map();
1215                                        let type_span = match sm.span_look_ahead(
1216                                            original_rib_ident_def.span,
1217                                            ":",
1218                                            None,
1219                                        ) {
1220                                            None => {
1221                                                Some(original_rib_ident_def.span.shrink_to_hi())
1222                                            }
1223                                            Some(_) => None,
1224                                        };
1225                                        (
1226                                            rib_ident.span,
1227                                            AttemptToUseNonConstantValueInConstant {
1228                                                ident: original_rib_ident_def,
1229                                                suggestion: "const",
1230                                                current: "let",
1231                                                type_span,
1232                                            },
1233                                        )
1234                                    }
1235                                    Some((ident, kind)) => (
1236                                        span,
1237                                        AttemptToUseNonConstantValueInConstant {
1238                                            ident,
1239                                            suggestion: "let",
1240                                            current: kind.as_str(),
1241                                            type_span: None,
1242                                        },
1243                                    ),
1244                                };
1245                                self.report_error(span, resolution_error);
1246                            }
1247                            return Res::Err;
1248                        }
1249                        RibKind::ConstParamTy => {
1250                            if let Some(span) = finalize {
1251                                self.report_error(
1252                                    span,
1253                                    ParamInTyOfConstParam { name: rib_ident.name },
1254                                );
1255                            }
1256                            return Res::Err;
1257                        }
1258                        RibKind::InlineAsmSym => {
1259                            if let Some(span) = finalize {
1260                                self.report_error(span, InvalidAsmSym);
1261                            }
1262                            return Res::Err;
1263                        }
1264                    }
1265                }
1266                if let Some((span, res_err)) = res_err {
1267                    self.report_error(span, res_err);
1268                    return Res::Err;
1269                }
1270            }
1271            Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } => {
1272                for rib in ribs {
1273                    let (has_generic_params, def_kind) = match rib.kind {
1274                        RibKind::Normal
1275                        | RibKind::Block(..)
1276                        | RibKind::FnOrCoroutine
1277                        | RibKind::Module(..)
1278                        | RibKind::MacroDefinition(..)
1279                        | RibKind::InlineAsmSym
1280                        | RibKind::AssocItem
1281                        | RibKind::ForwardGenericParamBan(_) => {
1282                            // Nothing to do. Continue.
1283                            continue;
1284                        }
1285
1286                        RibKind::ConstParamTy => {
1287                            if !self.tcx.features().generic_const_parameter_types() {
1288                                if let Some(span) = finalize {
1289                                    self.report_error(
1290                                        span,
1291                                        ResolutionError::ParamInTyOfConstParam {
1292                                            name: rib_ident.name,
1293                                        },
1294                                    );
1295                                }
1296                                return Res::Err;
1297                            } else {
1298                                continue;
1299                            }
1300                        }
1301
1302                        RibKind::ConstantItem(trivial, _) => {
1303                            if let ConstantHasGenerics::No(cause) = trivial {
1304                                // HACK(min_const_generics): If we encounter `Self` in an anonymous
1305                                // constant we can't easily tell if it's generic at this stage, so
1306                                // we instead remember this and then enforce the self type to be
1307                                // concrete later on.
1308                                if let Res::SelfTyAlias {
1309                                    alias_to: def,
1310                                    forbid_generic: _,
1311                                    is_trait_impl,
1312                                } = res
1313                                {
1314                                    res = Res::SelfTyAlias {
1315                                        alias_to: def,
1316                                        forbid_generic: true,
1317                                        is_trait_impl,
1318                                    }
1319                                } else {
1320                                    if let Some(span) = finalize {
1321                                        let error = match cause {
1322                                            NoConstantGenericsReason::IsEnumDiscriminant => {
1323                                                ResolutionError::ParamInEnumDiscriminant {
1324                                                    name: rib_ident.name,
1325                                                    param_kind: ParamKindInEnumDiscriminant::Type,
1326                                                }
1327                                            }
1328                                            NoConstantGenericsReason::NonTrivialConstArg => {
1329                                                ResolutionError::ParamInNonTrivialAnonConst {
1330                                                    name: rib_ident.name,
1331                                                    param_kind:
1332                                                        ParamKindInNonTrivialAnonConst::Type,
1333                                                }
1334                                            }
1335                                        };
1336                                        let _: ErrorGuaranteed = self.report_error(span, error);
1337                                    }
1338
1339                                    return Res::Err;
1340                                }
1341                            }
1342
1343                            continue;
1344                        }
1345
1346                        // This was an attempt to use a type parameter outside its scope.
1347                        RibKind::Item(has_generic_params, def_kind) => {
1348                            (has_generic_params, def_kind)
1349                        }
1350                    };
1351
1352                    if let Some(span) = finalize {
1353                        self.report_error(
1354                            span,
1355                            ResolutionError::GenericParamsFromOuterItem(
1356                                res,
1357                                has_generic_params,
1358                                def_kind,
1359                            ),
1360                        );
1361                    }
1362                    return Res::Err;
1363                }
1364            }
1365            Res::Def(DefKind::ConstParam, _) => {
1366                for rib in ribs {
1367                    let (has_generic_params, def_kind) = match rib.kind {
1368                        RibKind::Normal
1369                        | RibKind::Block(..)
1370                        | RibKind::FnOrCoroutine
1371                        | RibKind::Module(..)
1372                        | RibKind::MacroDefinition(..)
1373                        | RibKind::InlineAsmSym
1374                        | RibKind::AssocItem
1375                        | RibKind::ForwardGenericParamBan(_) => continue,
1376
1377                        RibKind::ConstParamTy => {
1378                            if !self.tcx.features().generic_const_parameter_types() {
1379                                if let Some(span) = finalize {
1380                                    self.report_error(
1381                                        span,
1382                                        ResolutionError::ParamInTyOfConstParam {
1383                                            name: rib_ident.name,
1384                                        },
1385                                    );
1386                                }
1387                                return Res::Err;
1388                            } else {
1389                                continue;
1390                            }
1391                        }
1392
1393                        RibKind::ConstantItem(trivial, _) => {
1394                            if let ConstantHasGenerics::No(cause) = trivial {
1395                                if let Some(span) = finalize {
1396                                    let error = match cause {
1397                                        NoConstantGenericsReason::IsEnumDiscriminant => {
1398                                            ResolutionError::ParamInEnumDiscriminant {
1399                                                name: rib_ident.name,
1400                                                param_kind: ParamKindInEnumDiscriminant::Const,
1401                                            }
1402                                        }
1403                                        NoConstantGenericsReason::NonTrivialConstArg => {
1404                                            ResolutionError::ParamInNonTrivialAnonConst {
1405                                                name: rib_ident.name,
1406                                                param_kind: ParamKindInNonTrivialAnonConst::Const {
1407                                                    name: rib_ident.name,
1408                                                },
1409                                            }
1410                                        }
1411                                    };
1412                                    self.report_error(span, error);
1413                                }
1414
1415                                return Res::Err;
1416                            }
1417
1418                            continue;
1419                        }
1420
1421                        RibKind::Item(has_generic_params, def_kind) => {
1422                            (has_generic_params, def_kind)
1423                        }
1424                    };
1425
1426                    // This was an attempt to use a const parameter outside its scope.
1427                    if let Some(span) = finalize {
1428                        self.report_error(
1429                            span,
1430                            ResolutionError::GenericParamsFromOuterItem(
1431                                res,
1432                                has_generic_params,
1433                                def_kind,
1434                            ),
1435                        );
1436                    }
1437                    return Res::Err;
1438                }
1439            }
1440            _ => {}
1441        }
1442
1443        res
1444    }
1445
1446    #[instrument(level = "debug", skip(self))]
1447    pub(crate) fn maybe_resolve_path<'r>(
1448        self: CmResolver<'r, 'ra, 'tcx>,
1449        path: &[Segment],
1450        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1451        parent_scope: &ParentScope<'ra>,
1452        ignore_import: Option<Import<'ra>>,
1453    ) -> PathResult<'ra> {
1454        self.resolve_path_with_ribs(
1455            path,
1456            opt_ns,
1457            parent_scope,
1458            None,
1459            None,
1460            None,
1461            None,
1462            ignore_import,
1463        )
1464    }
1465    #[instrument(level = "debug", skip(self))]
1466    pub(crate) fn resolve_path<'r>(
1467        self: CmResolver<'r, 'ra, 'tcx>,
1468        path: &[Segment],
1469        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1470        parent_scope: &ParentScope<'ra>,
1471        finalize: Option<Finalize>,
1472        ignore_binding: Option<NameBinding<'ra>>,
1473        ignore_import: Option<Import<'ra>>,
1474    ) -> PathResult<'ra> {
1475        self.resolve_path_with_ribs(
1476            path,
1477            opt_ns,
1478            parent_scope,
1479            None,
1480            finalize,
1481            None,
1482            ignore_binding,
1483            ignore_import,
1484        )
1485    }
1486
1487    pub(crate) fn resolve_path_with_ribs<'r>(
1488        mut self: CmResolver<'r, 'ra, 'tcx>,
1489        path: &[Segment],
1490        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1491        parent_scope: &ParentScope<'ra>,
1492        source: Option<PathSource<'_, '_, '_>>,
1493        finalize: Option<Finalize>,
1494        ribs: Option<&PerNS<Vec<Rib<'ra>>>>,
1495        ignore_binding: Option<NameBinding<'ra>>,
1496        ignore_import: Option<Import<'ra>>,
1497    ) -> PathResult<'ra> {
1498        let mut module = None;
1499        let mut module_had_parse_errors = false;
1500        let mut allow_super = true;
1501        let mut second_binding = None;
1502
1503        // We'll provide more context to the privacy errors later, up to `len`.
1504        let privacy_errors_len = self.privacy_errors.len();
1505        fn record_segment_res<'r, 'ra, 'tcx>(
1506            mut this: CmResolver<'r, 'ra, 'tcx>,
1507            finalize: Option<Finalize>,
1508            res: Res,
1509            id: Option<NodeId>,
1510        ) {
1511            if finalize.is_some()
1512                && let Some(id) = id
1513                && !this.partial_res_map.contains_key(&id)
1514            {
1515                assert!(id != ast::DUMMY_NODE_ID, "Trying to resolve dummy id");
1516                this.get_mut().record_partial_res(id, PartialRes::new(res));
1517            }
1518        }
1519
1520        for (segment_idx, &Segment { ident, id, .. }) in path.iter().enumerate() {
1521            debug!("resolve_path ident {} {:?} {:?}", segment_idx, ident, id);
1522
1523            let is_last = segment_idx + 1 == path.len();
1524            let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
1525            let name = ident.name;
1526
1527            allow_super &= ns == TypeNS && (name == kw::SelfLower || name == kw::Super);
1528
1529            if ns == TypeNS {
1530                if allow_super && name == kw::Super {
1531                    let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
1532                    let self_module = match segment_idx {
1533                        0 => Some(self.resolve_self(&mut ctxt, parent_scope.module)),
1534                        _ => match module {
1535                            Some(ModuleOrUniformRoot::Module(module)) => Some(module),
1536                            _ => None,
1537                        },
1538                    };
1539                    if let Some(self_module) = self_module
1540                        && let Some(parent) = self_module.parent
1541                    {
1542                        module =
1543                            Some(ModuleOrUniformRoot::Module(self.resolve_self(&mut ctxt, parent)));
1544                        continue;
1545                    }
1546                    return PathResult::failed(
1547                        ident,
1548                        false,
1549                        finalize.is_some(),
1550                        module_had_parse_errors,
1551                        module,
1552                        || ("there are too many leading `super` keywords".to_string(), None),
1553                    );
1554                }
1555                if segment_idx == 0 {
1556                    if name == kw::SelfLower {
1557                        let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
1558                        let self_mod = self.resolve_self(&mut ctxt, parent_scope.module);
1559                        if let Some(res) = self_mod.res() {
1560                            record_segment_res(self.reborrow(), finalize, res, id);
1561                        }
1562                        module = Some(ModuleOrUniformRoot::Module(self_mod));
1563                        continue;
1564                    }
1565                    if name == kw::PathRoot && ident.span.at_least_rust_2018() {
1566                        module = Some(ModuleOrUniformRoot::ExternPrelude);
1567                        continue;
1568                    }
1569                    if name == kw::PathRoot
1570                        && ident.span.is_rust_2015()
1571                        && self.tcx.sess.at_least_rust_2018()
1572                    {
1573                        // `::a::b` from 2015 macro on 2018 global edition
1574                        let crate_root = self.resolve_crate_root(ident);
1575                        module = Some(ModuleOrUniformRoot::ModuleAndExternPrelude(crate_root));
1576                        continue;
1577                    }
1578                    if name == kw::PathRoot || name == kw::Crate || name == kw::DollarCrate {
1579                        // `::a::b`, `crate::a::b` or `$crate::a::b`
1580                        let crate_root = self.resolve_crate_root(ident);
1581                        if let Some(res) = crate_root.res() {
1582                            record_segment_res(self.reborrow(), finalize, res, id);
1583                        }
1584                        module = Some(ModuleOrUniformRoot::Module(crate_root));
1585                        continue;
1586                    }
1587                }
1588            }
1589
1590            // Report special messages for path segment keywords in wrong positions.
1591            if ident.is_path_segment_keyword() && segment_idx != 0 {
1592                return PathResult::failed(
1593                    ident,
1594                    false,
1595                    finalize.is_some(),
1596                    module_had_parse_errors,
1597                    module,
1598                    || {
1599                        let name_str = if name == kw::PathRoot {
1600                            "crate root".to_string()
1601                        } else {
1602                            format!("`{name}`")
1603                        };
1604                        let label = if segment_idx == 1 && path[0].ident.name == kw::PathRoot {
1605                            format!("global paths cannot start with {name_str}")
1606                        } else {
1607                            format!("{name_str} in paths can only be used in start position")
1608                        };
1609                        (label, None)
1610                    },
1611                );
1612            }
1613
1614            let binding = if let Some(module) = module {
1615                self.reborrow()
1616                    .resolve_ident_in_module(
1617                        module,
1618                        ident,
1619                        ns,
1620                        parent_scope,
1621                        finalize,
1622                        ignore_binding,
1623                        ignore_import,
1624                    )
1625                    .map_err(|(determinacy, _)| determinacy)
1626            } else if let Some(ribs) = ribs
1627                && let Some(TypeNS | ValueNS) = opt_ns
1628            {
1629                assert!(ignore_import.is_none());
1630                match self.get_mut().resolve_ident_in_lexical_scope(
1631                    ident,
1632                    ns,
1633                    parent_scope,
1634                    finalize,
1635                    &ribs[ns],
1636                    ignore_binding,
1637                ) {
1638                    // we found a locally-imported or available item/module
1639                    Some(LexicalScopeBinding::Item(binding)) => Ok(binding),
1640                    // we found a local variable or type param
1641                    Some(LexicalScopeBinding::Res(res)) => {
1642                        record_segment_res(self.reborrow(), finalize, res, id);
1643                        return PathResult::NonModule(PartialRes::with_unresolved_segments(
1644                            res,
1645                            path.len() - 1,
1646                        ));
1647                    }
1648                    _ => Err(Determinacy::determined(finalize.is_some())),
1649                }
1650            } else {
1651                self.reborrow().resolve_ident_in_scope_set(
1652                    ident,
1653                    ScopeSet::All(ns),
1654                    parent_scope,
1655                    finalize,
1656                    finalize.is_some(),
1657                    ignore_binding,
1658                    ignore_import,
1659                )
1660            };
1661
1662            match binding {
1663                Ok(binding) => {
1664                    if segment_idx == 1 {
1665                        second_binding = Some(binding);
1666                    }
1667                    let res = binding.res();
1668
1669                    // Mark every privacy error in this path with the res to the last element. This allows us
1670                    // to detect the item the user cares about and either find an alternative import, or tell
1671                    // the user it is not accessible.
1672                    if finalize.is_some() {
1673                        for error in &mut self.get_mut().privacy_errors[privacy_errors_len..] {
1674                            error.outermost_res = Some((res, ident));
1675                            error.source = match source {
1676                                Some(PathSource::Struct(Some(expr)))
1677                                | Some(PathSource::Expr(Some(expr))) => Some(expr.clone()),
1678                                _ => None,
1679                            };
1680                        }
1681                    }
1682
1683                    let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(res);
1684                    if let Some(def_id) = binding.res().module_like_def_id() {
1685                        if self.mods_with_parse_errors.contains(&def_id) {
1686                            module_had_parse_errors = true;
1687                        }
1688                        module = Some(ModuleOrUniformRoot::Module(self.expect_module(def_id)));
1689                        record_segment_res(self.reborrow(), finalize, res, id);
1690                    } else if res == Res::ToolMod && !is_last && opt_ns.is_some() {
1691                        if binding.is_import() {
1692                            self.dcx().emit_err(errors::ToolModuleImported {
1693                                span: ident.span,
1694                                import: binding.span,
1695                            });
1696                        }
1697                        let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
1698                        return PathResult::NonModule(PartialRes::new(res));
1699                    } else if res == Res::Err {
1700                        return PathResult::NonModule(PartialRes::new(Res::Err));
1701                    } else if opt_ns.is_some() && (is_last || maybe_assoc) {
1702                        if let Some(finalize) = finalize {
1703                            self.get_mut().lint_if_path_starts_with_module(
1704                                finalize,
1705                                path,
1706                                second_binding,
1707                            );
1708                        }
1709                        record_segment_res(self.reborrow(), finalize, res, id);
1710                        return PathResult::NonModule(PartialRes::with_unresolved_segments(
1711                            res,
1712                            path.len() - segment_idx - 1,
1713                        ));
1714                    } else {
1715                        return PathResult::failed(
1716                            ident,
1717                            is_last,
1718                            finalize.is_some(),
1719                            module_had_parse_errors,
1720                            module,
1721                            || {
1722                                let label = format!(
1723                                    "`{ident}` is {} {}, not a module",
1724                                    res.article(),
1725                                    res.descr()
1726                                );
1727                                (label, None)
1728                            },
1729                        );
1730                    }
1731                }
1732                Err(Undetermined) => return PathResult::Indeterminate,
1733                Err(Determined) => {
1734                    if let Some(ModuleOrUniformRoot::Module(module)) = module
1735                        && opt_ns.is_some()
1736                        && !module.is_normal()
1737                    {
1738                        return PathResult::NonModule(PartialRes::with_unresolved_segments(
1739                            module.res().unwrap(),
1740                            path.len() - segment_idx,
1741                        ));
1742                    }
1743
1744                    let mut this = self.reborrow();
1745                    return PathResult::failed(
1746                        ident,
1747                        is_last,
1748                        finalize.is_some(),
1749                        module_had_parse_errors,
1750                        module,
1751                        || {
1752                            this.get_mut().report_path_resolution_error(
1753                                path,
1754                                opt_ns,
1755                                parent_scope,
1756                                ribs,
1757                                ignore_binding,
1758                                ignore_import,
1759                                module,
1760                                segment_idx,
1761                                ident,
1762                            )
1763                        },
1764                    );
1765                }
1766            }
1767        }
1768
1769        if let Some(finalize) = finalize {
1770            self.get_mut().lint_if_path_starts_with_module(finalize, path, second_binding);
1771        }
1772
1773        PathResult::Module(match module {
1774            Some(module) => module,
1775            None if path.is_empty() => ModuleOrUniformRoot::CurrentScope,
1776            _ => bug!("resolve_path: non-empty path `{:?}` has no module", path),
1777        })
1778    }
1779}