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