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