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};
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};
17 ConstantHasGenerics, ConstantItemKind, HasGenericParams, PathSource, Rib, RibKind,
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};
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>(
35 scope_set: ScopeSet<'a>,
36 parent_scope: &ParentScope<'a>,
38 mut visitor: impl FnMut(
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):
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).
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).
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).
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),
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(),
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),
104 let mut ctxt = ctxt.normalize_to_macros_2_0();
105 let mut use_prelude = !module.no_implicit_prelude;
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))
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());
128 Scope::CrateRoot => true,
129 Scope::Module(..) => true,
130 Scope::RegisteredAttrs => use_prelude,
131 Scope::MacroUsePrelude => use_prelude || rust_2015,
132 Scope::BuiltinAttrs => true,
133 Scope::ExternPrelude => use_prelude || is_absolute_path,
134 Scope::ToolPrelude => use_prelude,
135 Scope::StdLibPrelude => use_prelude || ns == MacroNS,
136 Scope::BuiltinTypes => true,
140 if let break_result @ Some(..) = visitor(self, scope, use_prelude, ctxt) {
145 scope = match scope {
146 Scope::DeriveHelpers(LocalExpnId::ROOT) => Scope::DeriveHelpersCompat,
147 Scope::DeriveHelpers(expn_id) => {
148 // Derive helpers are not visible to code generated by bang or derive macros.
149 let expn_data = expn_id.expn_data();
150 match expn_data.kind {
152 | ExpnKind::Macro(MacroKind::Bang | MacroKind::Derive, _) => {
153 Scope::DeriveHelpersCompat
155 _ => Scope::DeriveHelpers(expn_data.parent.expect_local()),
158 Scope::DeriveHelpersCompat => Scope::MacroRules(parent_scope.macro_rules),
159 Scope::MacroRules(macro_rules_scope) => match macro_rules_scope.get() {
160 MacroRulesScope::Binding(binding) => {
161 Scope::MacroRules(binding.parent_macro_rules_scope)
163 MacroRulesScope::Invocation(invoc_id) => {
164 Scope::MacroRules(self.invocation_parent_scopes[&invoc_id].macro_rules)
166 MacroRulesScope::Empty => Scope::Module(module, None),
168 Scope::CrateRoot => match ns {
170 ctxt.adjust(ExpnId::root());
173 ValueNS | MacroNS => break,
175 Scope::Module(module, prev_lint_id) => {
176 use_prelude = !module.no_implicit_prelude;
177 let derive_fallback_lint_id = match scope_set {
178 ScopeSet::Late(.., lint_id) => lint_id,
181 match self.hygienic_lexical_parent(module, &mut ctxt, derive_fallback_lint_id) {
182 Some((parent_module, lint_id)) => {
183 Scope::Module(parent_module, lint_id.or(prev_lint_id))
186 ctxt.adjust(ExpnId::root());
188 TypeNS => Scope::ExternPrelude,
189 ValueNS => Scope::StdLibPrelude,
190 MacroNS => Scope::RegisteredAttrs,
195 Scope::RegisteredAttrs => Scope::MacroUsePrelude,
196 Scope::MacroUsePrelude => Scope::StdLibPrelude,
197 Scope::BuiltinAttrs => break, // nowhere else to search
198 Scope::ExternPrelude if is_absolute_path => break,
199 Scope::ExternPrelude => Scope::ToolPrelude,
200 Scope::ToolPrelude => Scope::StdLibPrelude,
201 Scope::StdLibPrelude => match ns {
202 TypeNS => Scope::BuiltinTypes,
203 ValueNS => break, // nowhere else to search
204 MacroNS => Scope::BuiltinAttrs,
206 Scope::BuiltinTypes => break, // nowhere else to search
213 fn hygienic_lexical_parent(
216 ctxt: &mut SyntaxContext,
217 derive_fallback_lint_id: Option<NodeId>,
218 ) -> Option<(Module<'a>, Option<NodeId>)> {
219 if !module.expansion.outer_expn_is_descendant_of(*ctxt) {
220 return Some((self.expn_def_scope(ctxt.remove_mark()), None));
223 if let ModuleKind::Block = module.kind {
224 return Some((module.parent.unwrap().nearest_item_scope(), None));
227 // We need to support the next case under a deprecation warning
230 // ---- begin: this comes from a proc macro derive
231 // mod implementation_details {
232 // // Note that `MyStruct` is not in scope here.
233 // impl SomeTrait for MyStruct { ... }
237 // So we have to fall back to the module's parent during lexical resolution in this case.
238 if derive_fallback_lint_id.is_some() {
239 if let Some(parent) = module.parent {
240 // Inner module is inside the macro, parent module is outside of the macro.
241 if module.expansion != parent.expansion
242 && module.expansion.is_descendant_of(parent.expansion)
244 // The macro is a proc macro derive
245 if let Some(def_id) = module.expansion.expn_data().macro_def_id {
246 let ext = self.get_macro_by_def_id(def_id).ext;
247 if ext.builtin_name.is_none()
248 && ext.macro_kind() == MacroKind::Derive
249 && parent.expansion.outer_expn_is_descendant_of(*ctxt)
251 return Some((parent, derive_fallback_lint_id));
261 /// This resolves the identifier `ident` in the namespace `ns` in the current lexical scope.
262 /// More specifically, we proceed up the hierarchy of scopes and return the binding for
263 /// `ident` in the first scope that defines it (or None if no scopes define it).
265 /// A block's items are above its local variables in the scope hierarchy, regardless of where
266 /// the items are defined in the block. For example,
269 /// g(); // Since there are no local variables in scope yet, this resolves to the item.
272 /// g(); // This resolves to the local variable `g` since it shadows the item.
276 /// Invariant: This must only be called during main resolution, not during
277 /// import resolution.
278 #[tracing::instrument(level = "debug", skip(self, ribs))]
279 pub(crate) fn resolve_ident_in_lexical_scope(
283 parent_scope: &ParentScope<'a>,
284 finalize: Option<Finalize>,
286 ignore_binding: Option<&'a NameBinding<'a>>,
287 ) -> Option<LexicalScopeBinding<'a>> {
288 assert!(ns == TypeNS || ns == ValueNS);
289 let orig_ident = ident;
290 if ident.name == kw::Empty {
291 return Some(LexicalScopeBinding::Res(Res::Err));
293 let (general_span, normalized_span) = if ident.name == kw::SelfUpper {
294 // FIXME(jseyfried) improve `Self` hygiene
295 let empty_span = ident.span.with_ctxt(SyntaxContext::root());
296 (empty_span, empty_span)
297 } else if ns == TypeNS {
298 let normalized_span = ident.span.normalize_to_macros_2_0();
299 (normalized_span, normalized_span)
301 (ident.span.normalize_to_macro_rules(), ident.span.normalize_to_macros_2_0())
303 ident.span = general_span;
304 let normalized_ident = Ident { span: normalized_span, ..ident };
306 // Walk backwards up the ribs in scope.
307 let mut module = self.graph_root;
308 for i in (0..ribs.len()).rev() {
309 debug!("walk rib\n{:?}", ribs[i].bindings);
310 // Use the rib kind to determine whether we are resolving parameters
311 // (macro 2.0 hygiene) or local variables (`macro_rules` hygiene).
312 let rib_ident = if ribs[i].kind.contains_params() { normalized_ident } else { ident };
313 if let Some((original_rib_ident_def, res)) = ribs[i].bindings.get_key_value(&rib_ident)
315 // The ident resolves to a type parameter or local variable.
316 return Some(LexicalScopeBinding::Res(self.validate_res_from_ribs(
320 finalize.map(|finalize| finalize.path_span),
321 *original_rib_ident_def,
326 module = match ribs[i].kind {
327 ModuleRibKind(module) => module,
328 MacroDefinition(def) if def == self.macro_def(ident.span.ctxt()) => {
329 // If an invocation of this macro created `ident`, give up on `ident`
330 // and switch to `ident`'s source from the macro definition.
331 ident.span.remove_mark();
338 ModuleKind::Block => {} // We can see through blocks
342 let item = self.resolve_ident_in_module_unadjusted(
343 ModuleOrUniformRoot::Module(module),
350 if let Ok(binding) = item {
351 // The ident resolves to an item.
352 return Some(LexicalScopeBinding::Item(binding));
355 self.early_resolve_ident_in_lexical_scope(
357 ScopeSet::Late(ns, module, finalize.map(|finalize| finalize.node_id)),
364 .map(LexicalScopeBinding::Item)
367 /// Resolve an identifier in lexical scope.
368 /// This is a variation of `fn resolve_ident_in_lexical_scope` that can be run during
369 /// expansion and import resolution (perhaps they can be merged in the future).
370 /// The function is used for resolving initial segments of macro paths (e.g., `foo` in
371 /// `foo::bar!(); or `foo!();`) and also for import paths on 2018 edition.
372 #[tracing::instrument(level = "debug", skip(self, scope_set))]
373 pub(crate) fn early_resolve_ident_in_lexical_scope(
376 scope_set: ScopeSet<'a>,
377 parent_scope: &ParentScope<'a>,
378 finalize: Option<Finalize>,
380 ignore_binding: Option<&'a NameBinding<'a>>,
381 ) -> Result<&'a NameBinding<'a>, Determinacy> {
382 bitflags::bitflags! {
384 const MACRO_RULES = 1 << 0;
385 const MODULE = 1 << 1;
386 const MISC_SUGGEST_CRATE = 1 << 2;
387 const MISC_SUGGEST_SELF = 1 << 3;
388 const MISC_FROM_PRELUDE = 1 << 4;
392 assert!(force || !finalize.is_some()); // `finalize` implies `force`
394 // Make sure `self`, `super` etc produce an error when passed to here.
395 if orig_ident.is_path_segment_keyword() {
396 return Err(Determinacy::Determined);
399 let (ns, macro_kind, is_import) = match scope_set {
400 ScopeSet::All(ns, is_import) => (ns, None, is_import),
401 ScopeSet::AbsolutePath(ns) => (ns, None, false),
402 ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind), false),
403 ScopeSet::Late(ns, ..) => (ns, None, false),
406 // This is *the* result, resolution from the scope closest to the resolved identifier.
407 // However, sometimes this result is "weak" because it comes from a glob import or
408 // a macro expansion, and in this case it cannot shadow names from outer scopes, e.g.
409 // mod m { ... } // solution in outer scope
411 // use prefix::*; // imports another `m` - innermost solution
412 // // weak, cannot shadow the outer `m`, need to report ambiguity error
415 // So we have to save the innermost solution and continue searching in outer scopes
416 // to detect potential ambiguities.
417 let mut innermost_result: Option<(&NameBinding<'_>, Flags)> = None;
418 let mut determinacy = Determinacy::Determined;
420 // Go through all the scopes and try to resolve the name.
421 let break_result = self.visit_scopes(
424 orig_ident.span.ctxt(),
425 |this, scope, use_prelude, ctxt| {
426 let ident = Ident::new(orig_ident.name, orig_ident.span.with_ctxt(ctxt));
427 let ok = |res, span, arenas| {
429 (res, ty::Visibility::Public, span, LocalExpnId::ROOT)
430 .to_name_binding(arenas),
434 let result = match scope {
435 Scope::DeriveHelpers(expn_id) => {
436 if let Some(attr) = this
439 .and_then(|attrs| attrs.iter().rfind(|i| ident == **i))
442 Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper),
443 ty::Visibility::Public,
447 .to_name_binding(this.arenas);
448 Ok((binding, Flags::empty()))
450 Err(Determinacy::Determined)
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(
459 Some(MacroKind::Derive),
464 Ok((Some(ext), _)) => {
465 if ext.helper_attrs.contains(&ident.name) {
467 Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat),
474 Ok(_) | Err(Determinacy::Determined) => {}
475 Err(Determinacy::Undetermined) => {
476 result = Err(Determinacy::Undetermined)
482 Scope::MacroRules(macro_rules_scope) => match macro_rules_scope.get() {
483 MacroRulesScope::Binding(macro_rules_binding)
484 if ident == macro_rules_binding.ident =>
486 Ok((macro_rules_binding.binding, Flags::MACRO_RULES))
488 MacroRulesScope::Invocation(_) => Err(Determinacy::Undetermined),
489 _ => Err(Determinacy::Determined),
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),
503 Ok(binding) => Ok((binding, Flags::MODULE | Flags::MISC_SUGGEST_CRATE)),
504 Err((Determinacy::Undetermined, Weak::No)) => {
505 return Some(Err(Determinacy::determined(force)));
507 Err((Determinacy::Undetermined, Weak::Yes)) => {
508 Err(Determinacy::Undetermined)
510 Err((Determinacy::Determined, _)) => Err(Determinacy::Determined),
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),
519 adjusted_parent_scope,
520 !matches!(scope_set, ScopeSet::Late(..)),
526 if let Some(lint_id) = derive_fallback_lint_id {
527 this.lint_buffer.buffer_lint_with_diagnostic(
528 PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
532 "cannot find {} `{}` in this scope",
536 BuiltinLintDiagnostics::ProcMacroDeriveResolutionFallback(
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
548 Ok((binding, Flags::MODULE | misc_flags))
550 Err((Determinacy::Undetermined, Weak::No)) => {
551 return Some(Err(Determinacy::determined(force)));
553 Err((Determinacy::Undetermined, Weak::Yes)) => {
554 Err(Determinacy::Undetermined)
556 Err((Determinacy::Determined, _)) => Err(Determinacy::Determined),
559 Scope::RegisteredAttrs => match this.registered_attrs.get(&ident).cloned() {
561 Res::NonMacroAttr(NonMacroAttrKind::Registered),
565 None => Err(Determinacy::Determined),
567 Scope::MacroUsePrelude => {
568 match this.macro_use_prelude.get(&ident.name).cloned() {
569 Some(binding) => Ok((binding, Flags::MISC_FROM_PRELUDE)),
570 None => Err(Determinacy::determined(
571 this.graph_root.unexpanded_invocations.borrow().is_empty(),
575 Scope::BuiltinAttrs => {
576 if is_builtin_attr_name(ident.name) {
578 Res::NonMacroAttr(NonMacroAttrKind::Builtin(ident.name)),
583 Err(Determinacy::Determined)
586 Scope::ExternPrelude => {
587 match this.extern_prelude_get(ident, finalize.is_some()) {
588 Some(binding) => Ok((binding, Flags::empty())),
589 None => Err(Determinacy::determined(
590 this.graph_root.unexpanded_invocations.borrow().is_empty(),
594 Scope::ToolPrelude => match this.registered_tools.get(&ident).cloned() {
595 Some(ident) => ok(Res::ToolMod, ident.span, this.arenas),
596 None => Err(Determinacy::Determined),
598 Scope::StdLibPrelude => {
599 let mut result = Err(Determinacy::Determined);
600 if let Some(prelude) = this.prelude {
601 if let Ok(binding) = this.resolve_ident_in_module_unadjusted(
602 ModuleOrUniformRoot::Module(prelude),
609 if use_prelude || this.is_builtin_macro(binding.res()) {
610 result = Ok((binding, Flags::MISC_FROM_PRELUDE));
616 Scope::BuiltinTypes => match PrimTy::from_name(ident.name) {
617 Some(prim_ty) => ok(Res::PrimTy(prim_ty), DUMMY_SP, this.arenas),
618 None => Err(Determinacy::Determined),
624 if sub_namespace_match(binding.macro_kind(), macro_kind) =>
626 if finalize.is_none() || matches!(scope_set, ScopeSet::Late(..)) {
627 return Some(Ok(binding));
630 if let Some((innermost_binding, innermost_flags)) = innermost_result {
631 // Found another solution, if the first one was "weak", report an error.
632 let (res, innermost_res) = (binding.res(), innermost_binding.res());
633 if res != innermost_res {
634 let is_builtin = |res| {
635 matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Builtin(..)))
638 Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
639 let derive_helper_compat =
640 Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
642 let ambiguity_error_kind = if is_import {
643 Some(AmbiguityKind::Import)
644 } else if is_builtin(innermost_res) || is_builtin(res) {
645 Some(AmbiguityKind::BuiltinAttr)
646 } else if innermost_res == derive_helper_compat
647 || res == derive_helper_compat && innermost_res != derive_helper
649 Some(AmbiguityKind::DeriveHelper)
650 } else if innermost_flags.contains(Flags::MACRO_RULES)
651 && flags.contains(Flags::MODULE)
652 && !this.disambiguate_macro_rules_vs_modularized(
656 || flags.contains(Flags::MACRO_RULES)
657 && innermost_flags.contains(Flags::MODULE)
658 && !this.disambiguate_macro_rules_vs_modularized(
663 Some(AmbiguityKind::MacroRulesVsModularized)
664 } else if innermost_binding.is_glob_import() {
665 Some(AmbiguityKind::GlobVsOuter)
666 } else if innermost_binding
667 .may_appear_after(parent_scope.expansion, binding)
669 Some(AmbiguityKind::MoreExpandedVsOuter)
673 if let Some(kind) = ambiguity_error_kind {
674 let misc = |f: Flags| {
675 if f.contains(Flags::MISC_SUGGEST_CRATE) {
676 AmbiguityErrorMisc::SuggestCrate
677 } else if f.contains(Flags::MISC_SUGGEST_SELF) {
678 AmbiguityErrorMisc::SuggestSelf
679 } else if f.contains(Flags::MISC_FROM_PRELUDE) {
680 AmbiguityErrorMisc::FromPrelude
682 AmbiguityErrorMisc::None
685 this.ambiguity_errors.push(AmbiguityError {
688 b1: innermost_binding,
690 misc1: misc(innermost_flags),
693 return Some(Ok(innermost_binding));
697 // Found the first solution.
698 innermost_result = Some((binding, flags));
701 Ok(..) | Err(Determinacy::Determined) => {}
702 Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined,
709 if let Some(break_result) = break_result {
713 // The first found solution was the only one, return it.
714 if let Some((binding, _)) = innermost_result {
718 Err(Determinacy::determined(determinacy == Determinacy::Determined || force))
721 #[tracing::instrument(level = "debug", skip(self))]
722 pub(crate) fn maybe_resolve_ident_in_module(
724 module: ModuleOrUniformRoot<'a>,
727 parent_scope: &ParentScope<'a>,
728 ) -> Result<&'a NameBinding<'a>, Determinacy> {
729 self.resolve_ident_in_module_ext(module, ident, ns, parent_scope, None, None)
730 .map_err(|(determinacy, _)| determinacy)
733 #[tracing::instrument(level = "debug", skip(self))]
734 pub(crate) fn resolve_ident_in_module(
736 module: ModuleOrUniformRoot<'a>,
739 parent_scope: &ParentScope<'a>,
740 finalize: Option<Finalize>,
741 ignore_binding: Option<&'a NameBinding<'a>>,
742 ) -> Result<&'a NameBinding<'a>, Determinacy> {
743 self.resolve_ident_in_module_ext(module, ident, ns, parent_scope, finalize, ignore_binding)
744 .map_err(|(determinacy, _)| determinacy)
747 #[tracing::instrument(level = "debug", skip(self))]
748 fn resolve_ident_in_module_ext(
750 module: ModuleOrUniformRoot<'a>,
753 parent_scope: &ParentScope<'a>,
754 finalize: Option<Finalize>,
755 ignore_binding: Option<&'a NameBinding<'a>>,
756 ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> {
757 let tmp_parent_scope;
758 let mut adjusted_parent_scope = parent_scope;
760 ModuleOrUniformRoot::Module(m) => {
761 if let Some(def) = ident.span.normalize_to_macros_2_0_and_adjust(m.expansion) {
763 ParentScope { module: self.expn_def_scope(def), ..*parent_scope };
764 adjusted_parent_scope = &tmp_parent_scope;
767 ModuleOrUniformRoot::ExternPrelude => {
768 ident.span.normalize_to_macros_2_0_and_adjust(ExpnId::root());
770 ModuleOrUniformRoot::CrateRootAndExternPrelude | ModuleOrUniformRoot::CurrentScope => {
774 self.resolve_ident_in_module_unadjusted_ext(
778 adjusted_parent_scope,
785 #[tracing::instrument(level = "debug", skip(self))]
786 fn resolve_ident_in_module_unadjusted(
788 module: ModuleOrUniformRoot<'a>,
791 parent_scope: &ParentScope<'a>,
792 finalize: Option<Finalize>,
793 ignore_binding: Option<&'a NameBinding<'a>>,
794 ) -> Result<&'a NameBinding<'a>, Determinacy> {
795 self.resolve_ident_in_module_unadjusted_ext(
804 .map_err(|(determinacy, _)| determinacy)
807 /// Attempts to resolve `ident` in namespaces `ns` of `module`.
808 /// Invariant: if `finalize` is `Some`, expansion and import resolution must be complete.
809 #[tracing::instrument(level = "debug", skip(self))]
810 fn resolve_ident_in_module_unadjusted_ext(
812 module: ModuleOrUniformRoot<'a>,
815 parent_scope: &ParentScope<'a>,
816 restricted_shadowing: bool,
817 finalize: Option<Finalize>,
818 // This binding should be ignored during in-module resolution, so that we don't get
819 // "self-confirming" import resolutions during import validation and checking.
820 ignore_binding: Option<&'a NameBinding<'a>>,
821 ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> {
822 let module = match module {
823 ModuleOrUniformRoot::Module(module) => module,
824 ModuleOrUniformRoot::CrateRootAndExternPrelude => {
825 assert!(!restricted_shadowing);
826 let binding = self.early_resolve_ident_in_lexical_scope(
828 ScopeSet::AbsolutePath(ns),
834 return binding.map_err(|determinacy| (determinacy, Weak::No));
836 ModuleOrUniformRoot::ExternPrelude => {
837 assert!(!restricted_shadowing);
838 return if ns != TypeNS {
839 Err((Determined, Weak::No))
840 } else if let Some(binding) = self.extern_prelude_get(ident, finalize.is_some()) {
842 } else if !self.graph_root.unexpanded_invocations.borrow().is_empty() {
843 // Macro-expanded `extern crate` items can add names to extern prelude.
844 Err((Undetermined, Weak::No))
846 Err((Determined, Weak::No))
849 ModuleOrUniformRoot::CurrentScope => {
850 assert!(!restricted_shadowing);
852 if ident.name == kw::Crate || ident.name == kw::DollarCrate {
853 let module = self.resolve_crate_root(ident);
855 (module, ty::Visibility::Public, module.span, LocalExpnId::ROOT)
856 .to_name_binding(self.arenas);
858 } else if ident.name == kw::Super || ident.name == kw::SelfLower {
859 // FIXME: Implement these with renaming requirements so that e.g.
860 // `use super;` doesn't work, but `use super as name;` does.
861 // Fall through here to get an error from `early_resolve_...`.
865 let scopes = ScopeSet::All(ns, true);
866 let binding = self.early_resolve_ident_in_lexical_scope(
874 return binding.map_err(|determinacy| (determinacy, Weak::No));
878 let key = self.new_key(ident, ns);
880 self.resolution(module, key).try_borrow_mut().map_err(|_| (Determined, Weak::No))?; // This happens when there is a cycle of imports.
882 if let Some(Finalize { path_span, report_private, .. }) = finalize {
883 // If the primary binding is unusable, search further and return the shadowed glob
884 // binding if it exists. What we really want here is having two separate scopes in
885 // a module - one for non-globs and one for globs, but until that's done use this
886 // hack to avoid inconsistent resolution ICEs during import validation.
887 let binding = [resolution.binding, resolution.shadowed_glob]
889 .filter_map(|binding| match (binding, ignore_binding) {
890 (Some(binding), Some(ignored)) if ptr::eq(binding, ignored) => None,
894 let Some(binding) = binding else {
895 return Err((Determined, Weak::No));
898 if !self.is_accessible_from(binding.vis, parent_scope.module) {
900 self.privacy_errors.push(PrivacyError {
903 dedup_span: path_span,
906 return Err((Determined, Weak::No));
910 // Forbid expanded shadowing to avoid time travel.
911 if let Some(shadowed_glob) = resolution.shadowed_glob
912 && restricted_shadowing
913 && binding.expansion != LocalExpnId::ROOT
914 && binding.res() != shadowed_glob.res()
916 self.ambiguity_errors.push(AmbiguityError {
917 kind: AmbiguityKind::GlobVsExpanded,
921 misc1: AmbiguityErrorMisc::None,
922 misc2: AmbiguityErrorMisc::None,
926 if !restricted_shadowing && binding.expansion != LocalExpnId::ROOT {
927 if let NameBindingKind::Res(_, true) = binding.kind {
928 self.macro_expanded_macro_export_errors.insert((path_span, binding.span));
932 self.record_use(ident, binding, restricted_shadowing);
936 let check_usable = |this: &mut Self, binding: &'a NameBinding<'a>| {
937 if let Some(ignored) = ignore_binding && ptr::eq(binding, ignored) {
938 return Err((Determined, Weak::No));
940 let usable = this.is_accessible_from(binding.vis, parent_scope.module);
941 if usable { Ok(binding) } else { Err((Determined, Weak::No)) }
944 // Items and single imports are not shadowable, if we have one, then it's determined.
945 if let Some(binding) = resolution.binding {
946 if !binding.is_glob_import() {
947 return check_usable(self, binding);
951 // --- From now on we either have a glob resolution or no resolution. ---
953 // Check if one of single imports can still define the name,
954 // if it can then our result is not determined and can be invalidated.
955 for single_import in &resolution.single_imports {
956 if !self.is_accessible_from(single_import.vis.get(), parent_scope.module) {
959 let Some(module) = single_import.imported_module.get() else {
960 return Err((Undetermined, Weak::No));
962 let ImportKind::Single { source: ident, .. } = single_import.kind else {
965 match self.resolve_ident_in_module(
969 &single_import.parent_scope,
973 Err(Determined) => continue,
975 if !self.is_accessible_from(binding.vis, single_import.parent_scope.module) =>
979 Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::No)),
983 // So we have a resolution that's from a glob import. This resolution is determined
984 // if it cannot be shadowed by some new item/import expanded from a macro.
985 // This happens either if there are no unexpanded macros, or expanded names cannot
986 // shadow globs (that happens in macro namespace or with restricted shadowing).
988 // Additionally, any macro in any module can plant names in the root module if it creates
989 // `macro_export` macros, so the root module effectively has unresolved invocations if any
990 // module has unresolved invocations.
991 // However, it causes resolution/expansion to stuck too often (#53144), so, to make
992 // progress, we have to ignore those potential unresolved invocations from other modules
993 // and prohibit access to macro-expanded `macro_export` macros instead (unless restricted
994 // shadowing is enabled, see `macro_expanded_macro_export_errors`).
995 let unexpanded_macros = !module.unexpanded_invocations.borrow().is_empty();
996 if let Some(binding) = resolution.binding {
997 if !unexpanded_macros || ns == MacroNS || restricted_shadowing {
998 return check_usable(self, binding);
1000 return Err((Undetermined, Weak::No));
1004 // --- From now on we have no resolution. ---
1006 // Now we are in situation when new item/import can appear only from a glob or a macro
1007 // expansion. With restricted shadowing names from globs and macro expansions cannot
1008 // shadow names from outer scopes, so we can freely fallback from module search to search
1009 // in outer scopes. For `early_resolve_ident_in_lexical_scope` to continue search in outer
1010 // scopes we return `Undetermined` with `Weak::Yes`.
1012 // Check if one of unexpanded macros can still define the name,
1013 // if it can then our "no resolution" result is not determined and can be invalidated.
1014 if unexpanded_macros {
1015 return Err((Undetermined, Weak::Yes));
1018 // Check if one of glob imports can still define the name,
1019 // if it can then our "no resolution" result is not determined and can be invalidated.
1020 for glob_import in module.globs.borrow().iter() {
1021 if !self.is_accessible_from(glob_import.vis.get(), parent_scope.module) {
1024 let module = match glob_import.imported_module.get() {
1025 Some(ModuleOrUniformRoot::Module(module)) => module,
1026 Some(_) => continue,
1027 None => return Err((Undetermined, Weak::Yes)),
1029 let tmp_parent_scope;
1030 let (mut adjusted_parent_scope, mut ident) =
1031 (parent_scope, ident.normalize_to_macros_2_0());
1032 match ident.span.glob_adjust(module.expansion, glob_import.span) {
1033 Some(Some(def)) => {
1035 ParentScope { module: self.expn_def_scope(def), ..*parent_scope };
1036 adjusted_parent_scope = &tmp_parent_scope;
1041 let result = self.resolve_ident_in_module_unadjusted(
1042 ModuleOrUniformRoot::Module(module),
1045 adjusted_parent_scope,
1051 Err(Determined) => continue,
1053 if !self.is_accessible_from(binding.vis, glob_import.parent_scope.module) =>
1057 Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::Yes)),
1061 // No resolution and no one else can define the name - determinate error.
1062 Err((Determined, Weak::No))
1065 /// Validate a local resolution (from ribs).
1066 #[tracing::instrument(level = "debug", skip(self, all_ribs))]
1067 fn validate_res_from_ribs(
1072 finalize: Option<Span>,
1073 original_rib_ident_def: Ident,
1074 all_ribs: &[Rib<'a>],
1076 const CG_BUG_STR: &str = "min_const_generics resolve check didn't stop compilation";
1077 debug!("validate_res_from_ribs({:?})", res);
1078 let ribs = &all_ribs[rib_index + 1..];
1080 // An invalid forward use of a generic parameter from a previous default.
1081 if let ForwardGenericParamBanRibKind = all_ribs[rib_index].kind {
1082 if let Some(span) = finalize {
1083 let res_error = if rib_ident.name == kw::SelfUpper {
1084 ResolutionError::SelfInGenericParamDefault
1086 ResolutionError::ForwardDeclaredGenericParam
1088 self.report_error(span, res_error);
1090 assert_eq!(res, Res::Err);
1096 use ResolutionError::*;
1097 let mut res_err = None;
1102 | ClosureOrAsyncRibKind
1104 | MacroDefinition(..)
1105 | ForwardGenericParamBanRibKind => {
1106 // Nothing to do. Continue.
1108 ItemRibKind(_) | AssocItemRibKind => {
1109 // This was an attempt to access an upvar inside a
1110 // named function item. This is not allowed, so we
1112 if let Some(span) = finalize {
1113 // We don't immediately trigger a resolve error, because
1114 // we want certain other resolution errors (namely those
1115 // emitted for `ConstantItemRibKind` below) to take
1117 res_err = Some((span, CannotCaptureDynamicEnvironmentInFnItem));
1120 ConstantItemRibKind(_, item) => {
1121 // Still doesn't deal with upvars
1122 if let Some(span) = finalize {
1123 let (span, resolution_error) =
1124 if let Some((ident, constant_item_kind)) = item {
1125 let kind_str = match constant_item_kind {
1126 ConstantItemKind::Const => "const",
1127 ConstantItemKind::Static => "static",
1131 AttemptToUseNonConstantValueInConstant(
1132 ident, "let", kind_str,
1138 AttemptToUseNonConstantValueInConstant(
1139 original_rib_ident_def,
1145 self.report_error(span, resolution_error);
1149 ConstParamTyRibKind => {
1150 if let Some(span) = finalize {
1151 self.report_error(span, ParamInTyOfConstParam(rib_ident.name));
1155 InlineAsmSymRibKind => {
1156 if let Some(span) = finalize {
1157 self.report_error(span, InvalidAsmSym);
1163 if let Some((span, res_err)) = res_err {
1164 self.report_error(span, res_err);
1168 Res::Def(DefKind::TyParam, _) | Res::SelfTy { .. } => {
1170 let has_generic_params: HasGenericParams = match rib.kind {
1172 | ClosureOrAsyncRibKind
1174 | MacroDefinition(..)
1175 | InlineAsmSymRibKind
1177 | ForwardGenericParamBanRibKind => {
1178 // Nothing to do. Continue.
1182 ConstantItemRibKind(trivial, _) => {
1183 let features = self.session.features_untracked();
1184 // HACK(min_const_generics): We currently only allow `N` or `{ N }`.
1185 if !(trivial == ConstantHasGenerics::Yes
1186 || features.generic_const_exprs)
1188 // HACK(min_const_generics): If we encounter `Self` in an anonymous constant
1189 // we can't easily tell if it's generic at this stage, so we instead remember
1190 // this and then enforce the self type to be concrete later on.
1191 if let Res::SelfTy { trait_, alias_to: Some((def, _)) } = res {
1192 res = Res::SelfTy { trait_, alias_to: Some((def, true)) }
1194 if let Some(span) = finalize {
1197 ResolutionError::ParamInNonTrivialAnonConst {
1198 name: rib_ident.name,
1202 self.session.delay_span_bug(span, CG_BUG_STR);
1212 // This was an attempt to use a type parameter outside its scope.
1213 ItemRibKind(has_generic_params) => has_generic_params,
1214 ConstParamTyRibKind => {
1215 if let Some(span) = finalize {
1218 ResolutionError::ParamInTyOfConstParam(rib_ident.name),
1225 if let Some(span) = finalize {
1228 ResolutionError::GenericParamsFromOuterFunction(
1237 Res::Def(DefKind::ConstParam, _) => {
1239 let has_generic_params = match rib.kind {
1241 | ClosureOrAsyncRibKind
1243 | MacroDefinition(..)
1244 | InlineAsmSymRibKind
1246 | ForwardGenericParamBanRibKind => continue,
1248 ConstantItemRibKind(trivial, _) => {
1249 let features = self.session.features_untracked();
1250 // HACK(min_const_generics): We currently only allow `N` or `{ N }`.
1251 if !(trivial == ConstantHasGenerics::Yes
1252 || features.generic_const_exprs)
1254 if let Some(span) = finalize {
1257 ResolutionError::ParamInNonTrivialAnonConst {
1258 name: rib_ident.name,
1262 self.session.delay_span_bug(span, CG_BUG_STR);
1271 ItemRibKind(has_generic_params) => has_generic_params,
1272 ConstParamTyRibKind => {
1273 if let Some(span) = finalize {
1276 ResolutionError::ParamInTyOfConstParam(rib_ident.name),
1283 // This was an attempt to use a const parameter outside its scope.
1284 if let Some(span) = finalize {
1287 ResolutionError::GenericParamsFromOuterFunction(
1301 #[tracing::instrument(level = "debug", skip(self))]
1302 pub(crate) fn maybe_resolve_path(
1305 opt_ns: Option<Namespace>, // `None` indicates a module path in import
1306 parent_scope: &ParentScope<'a>,
1307 ) -> PathResult<'a> {
1308 self.resolve_path_with_ribs(path, opt_ns, parent_scope, None, None, None)
1311 #[tracing::instrument(level = "debug", skip(self))]
1312 pub(crate) fn resolve_path(
1315 opt_ns: Option<Namespace>, // `None` indicates a module path in import
1316 parent_scope: &ParentScope<'a>,
1317 finalize: Option<Finalize>,
1318 ignore_binding: Option<&'a NameBinding<'a>>,
1319 ) -> PathResult<'a> {
1320 self.resolve_path_with_ribs(path, opt_ns, parent_scope, finalize, None, ignore_binding)
1323 pub(crate) fn resolve_path_with_ribs(
1326 opt_ns: Option<Namespace>, // `None` indicates a module path in import
1327 parent_scope: &ParentScope<'a>,
1328 finalize: Option<Finalize>,
1329 ribs: Option<&PerNS<Vec<Rib<'a>>>>,
1330 ignore_binding: Option<&'a NameBinding<'a>>,
1331 ) -> PathResult<'a> {
1332 debug!("resolve_path(path={:?}, opt_ns={:?}, finalize={:?})", path, opt_ns, finalize);
1334 let mut module = None;
1335 let mut allow_super = true;
1336 let mut second_binding = None;
1338 for (i, &Segment { ident, id, .. }) in path.iter().enumerate() {
1339 debug!("resolve_path ident {} {:?} {:?}", i, ident, id);
1340 let record_segment_res = |this: &mut Self, res| {
1341 if finalize.is_some() {
1342 if let Some(id) = id {
1343 if !this.partial_res_map.contains_key(&id) {
1344 assert!(id != ast::DUMMY_NODE_ID, "Trying to resolve dummy id");
1345 this.record_partial_res(id, PartialRes::new(res));
1351 let is_last = i == path.len() - 1;
1352 let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
1353 let name = ident.name;
1355 allow_super &= ns == TypeNS && (name == kw::SelfLower || name == kw::Super);
1358 if allow_super && name == kw::Super {
1359 let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
1360 let self_module = match i {
1361 0 => Some(self.resolve_self(&mut ctxt, parent_scope.module)),
1363 Some(ModuleOrUniformRoot::Module(module)) => Some(module),
1367 if let Some(self_module) = self_module {
1368 if let Some(parent) = self_module.parent {
1369 module = Some(ModuleOrUniformRoot::Module(
1370 self.resolve_self(&mut ctxt, parent),
1375 return PathResult::failed(ident.span, false, finalize.is_some(), || {
1376 ("there are too many leading `super` keywords".to_string(), None)
1380 if name == kw::SelfLower {
1381 let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
1382 module = Some(ModuleOrUniformRoot::Module(
1383 self.resolve_self(&mut ctxt, parent_scope.module),
1387 if name == kw::PathRoot && ident.span.rust_2018() {
1388 module = Some(ModuleOrUniformRoot::ExternPrelude);
1391 if name == kw::PathRoot && ident.span.rust_2015() && self.session.rust_2018() {
1392 // `::a::b` from 2015 macro on 2018 global edition
1393 module = Some(ModuleOrUniformRoot::CrateRootAndExternPrelude);
1396 if name == kw::PathRoot || name == kw::Crate || name == kw::DollarCrate {
1397 // `::a::b`, `crate::a::b` or `$crate::a::b`
1398 module = Some(ModuleOrUniformRoot::Module(self.resolve_crate_root(ident)));
1404 // Report special messages for path segment keywords in wrong positions.
1405 if ident.is_path_segment_keyword() && i != 0 {
1406 return PathResult::failed(ident.span, false, finalize.is_some(), || {
1407 let name_str = if name == kw::PathRoot {
1408 "crate root".to_string()
1410 format!("`{}`", name)
1412 let label = if i == 1 && path[0].ident.name == kw::PathRoot {
1413 format!("global paths cannot start with {}", name_str)
1415 format!("{} in paths can only be used in start position", name_str)
1421 enum FindBindingResult<'a> {
1422 Binding(Result<&'a NameBinding<'a>, Determinacy>),
1425 let find_binding_in_ns = |this: &mut Self, ns| {
1426 let binding = if let Some(module) = module {
1427 this.resolve_ident_in_module(
1435 } else if let Some(ribs) = ribs
1436 && let Some(TypeNS | ValueNS) = opt_ns
1438 match this.resolve_ident_in_lexical_scope(
1446 // we found a locally-imported or available item/module
1447 Some(LexicalScopeBinding::Item(binding)) => Ok(binding),
1448 // we found a local variable or type param
1449 Some(LexicalScopeBinding::Res(res)) => return FindBindingResult::Res(res),
1450 _ => Err(Determinacy::determined(finalize.is_some())),
1453 let scopes = ScopeSet::All(ns, opt_ns.is_none());
1454 this.early_resolve_ident_in_lexical_scope(
1463 FindBindingResult::Binding(binding)
1465 let binding = match find_binding_in_ns(self, ns) {
1466 FindBindingResult::Res(res) => {
1467 record_segment_res(self, res);
1468 return PathResult::NonModule(PartialRes::with_unresolved_segments(
1473 FindBindingResult::Binding(binding) => binding,
1478 second_binding = Some(binding);
1480 let res = binding.res();
1481 let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(res);
1482 if let Some(next_module) = binding.module() {
1483 module = Some(ModuleOrUniformRoot::Module(next_module));
1484 record_segment_res(self, res);
1485 } else if res == Res::ToolMod && i + 1 != path.len() {
1486 if binding.is_import() {
1490 "cannot use a tool module through an import",
1492 .span_note(binding.span, "the tool module imported here")
1495 let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
1496 return PathResult::NonModule(PartialRes::new(res));
1497 } else if res == Res::Err {
1498 return PathResult::NonModule(PartialRes::new(Res::Err));
1499 } else if opt_ns.is_some() && (is_last || maybe_assoc) {
1500 self.lint_if_path_starts_with_module(finalize, path, second_binding);
1501 record_segment_res(self, res);
1502 return PathResult::NonModule(PartialRes::with_unresolved_segments(
1507 return PathResult::failed(ident.span, is_last, finalize.is_some(), || {
1508 let label = format!(
1509 "`{ident}` is {} {}, not a module",
1517 Err(Undetermined) => return PathResult::Indeterminate,
1518 Err(Determined) => {
1519 if let Some(ModuleOrUniformRoot::Module(module)) = module {
1520 if opt_ns.is_some() && !module.is_normal() {
1521 return PathResult::NonModule(PartialRes::with_unresolved_segments(
1522 module.res().unwrap(),
1528 return PathResult::failed(ident.span, is_last, finalize.is_some(), || {
1529 self.report_path_resolution_error(
1544 self.lint_if_path_starts_with_module(finalize, path, second_binding);
1546 PathResult::Module(match module {
1547 Some(module) => module,
1548 None if path.is_empty() => ModuleOrUniformRoot::CurrentScope,
1549 _ => bug!("resolve_path: non-empty path `{:?}` has no module", path),