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::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,
139 if let break_result @ Some(..) = visitor(self, scope, use_prelude, ctxt) {
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 {
151 | ExpnKind::Macro(MacroKind::Bang | MacroKind::Derive, _) => {
152 Scope::DeriveHelpersCompat
154 _ => Scope::DeriveHelpers(expn_data.parent.expect_local()),
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)
162 MacroRulesScope::Invocation(invoc_id) => {
163 Scope::MacroRules(self.invocation_parent_scopes[&invoc_id].macro_rules)
165 MacroRulesScope::Empty => Scope::Module(module, None),
167 Scope::CrateRoot => match ns {
169 ctxt.adjust(ExpnId::root());
172 ValueNS | MacroNS => break,
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,
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))
185 ctxt.adjust(ExpnId::root());
187 TypeNS => Scope::ExternPrelude,
188 ValueNS => Scope::StdLibPrelude,
189 MacroNS => Scope::MacroUsePrelude,
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,
204 Scope::BuiltinTypes => break, // nowhere else to search
211 fn hygienic_lexical_parent(
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));
221 if let ModuleKind::Block = module.kind {
222 return Some((module.parent.unwrap().nearest_item_scope(), None));
225 // We need to support the next case under a deprecation warning
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 { ... }
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)
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)
249 return Some((parent, derive_fallback_lint_id));
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).
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,
267 /// g(); // Since there are no local variables in scope yet, this resolves to the item.
270 /// g(); // This resolves to the local variable `g` since it shadows the item.
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(
281 parent_scope: &ParentScope<'a>,
282 finalize: Option<Finalize>,
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));
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)
299 (ident.span.normalize_to_macro_rules(), ident.span.normalize_to_macros_2_0())
301 ident.span = general_span;
302 let normalized_ident = Ident { span: normalized_span, ..ident };
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)
313 // The ident resolves to a type parameter or local variable.
314 return Some(LexicalScopeBinding::Res(self.validate_res_from_ribs(
318 finalize.map(|finalize| finalize.path_span),
319 *original_rib_ident_def,
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();
336 ModuleKind::Block => {} // We can see through blocks
340 let item = self.resolve_ident_in_module_unadjusted(
341 ModuleOrUniformRoot::Module(module),
348 if let Ok(binding) = item {
349 // The ident resolves to an item.
350 return Some(LexicalScopeBinding::Item(binding));
353 self.early_resolve_ident_in_lexical_scope(
355 ScopeSet::Late(ns, module, finalize.map(|finalize| finalize.node_id)),
362 .map(LexicalScopeBinding::Item)
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(
374 scope_set: ScopeSet<'a>,
375 parent_scope: &ParentScope<'a>,
376 finalize: Option<Finalize>,
378 ignore_binding: Option<&'a NameBinding<'a>>,
379 ) -> Result<&'a NameBinding<'a>, Determinacy> {
380 bitflags::bitflags! {
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;
390 assert!(force || !finalize.is_some()); // `finalize` implies `force`
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);
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),
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
409 // use prefix::*; // imports another `m` - innermost solution
410 // // weak, cannot shadow the outer `m`, need to report ambiguity error
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;
418 // Go through all the scopes and try to resolve the name.
419 let break_result = self.visit_scopes(
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| {
427 (res, ty::Visibility::Public, span, LocalExpnId::ROOT)
428 .to_name_binding(arenas),
432 let result = match scope {
433 Scope::DeriveHelpers(expn_id) => {
434 if let Some(attr) = this
437 .and_then(|attrs| attrs.iter().rfind(|i| ident == **i))
440 Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper),
441 ty::Visibility::Public,
445 .to_name_binding(this.arenas);
446 Ok((binding, Flags::empty()))
448 Err(Determinacy::Determined)
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(
457 Some(MacroKind::Derive),
462 Ok((Some(ext), _)) => {
463 if ext.helper_attrs.contains(&ident.name) {
465 Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat),
472 Ok(_) | Err(Determinacy::Determined) => {}
473 Err(Determinacy::Undetermined) => {
474 result = Err(Determinacy::Undetermined)
480 Scope::MacroRules(macro_rules_scope) => match macro_rules_scope.get() {
481 MacroRulesScope::Binding(macro_rules_binding)
482 if ident == macro_rules_binding.ident =>
484 Ok((macro_rules_binding.binding, Flags::MACRO_RULES))
486 MacroRulesScope::Invocation(_) => Err(Determinacy::Undetermined),
487 _ => Err(Determinacy::Determined),
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),
501 Ok(binding) => Ok((binding, Flags::MODULE | Flags::MISC_SUGGEST_CRATE)),
502 Err((Determinacy::Undetermined, Weak::No)) => {
503 return Some(Err(Determinacy::determined(force)));
505 Err((Determinacy::Undetermined, Weak::Yes)) => {
506 Err(Determinacy::Undetermined)
508 Err((Determinacy::Determined, _)) => Err(Determinacy::Determined),
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),
517 adjusted_parent_scope,
518 !matches!(scope_set, ScopeSet::Late(..)),
524 if let Some(lint_id) = derive_fallback_lint_id {
525 this.lint_buffer.buffer_lint_with_diagnostic(
526 PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
530 "cannot find {} `{}` in this scope",
534 BuiltinLintDiagnostics::ProcMacroDeriveResolutionFallback(
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
546 Ok((binding, Flags::MODULE | misc_flags))
548 Err((Determinacy::Undetermined, Weak::No)) => {
549 return Some(Err(Determinacy::determined(force)));
551 Err((Determinacy::Undetermined, Weak::Yes)) => {
552 Err(Determinacy::Undetermined)
554 Err((Determinacy::Determined, _)) => Err(Determinacy::Determined),
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(),
565 Scope::BuiltinAttrs => {
566 if is_builtin_attr_name(ident.name) {
568 Res::NonMacroAttr(NonMacroAttrKind::Builtin(ident.name)),
573 Err(Determinacy::Determined)
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(),
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),
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),
599 if use_prelude || this.is_builtin_macro(binding.res()) {
600 result = Ok((binding, Flags::MISC_FROM_PRELUDE));
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),
614 if sub_namespace_match(binding.macro_kind(), macro_kind) =>
616 if finalize.is_none() || matches!(scope_set, ScopeSet::Late(..)) {
617 return Some(Ok(binding));
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(..)))
628 Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
629 let derive_helper_compat =
630 Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
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
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(
646 || flags.contains(Flags::MACRO_RULES)
647 && innermost_flags.contains(Flags::MODULE)
648 && !this.disambiguate_macro_rules_vs_modularized(
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)
659 Some(AmbiguityKind::MoreExpandedVsOuter)
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
672 AmbiguityErrorMisc::None
675 this.ambiguity_errors.push(AmbiguityError {
678 b1: innermost_binding,
680 misc1: misc(innermost_flags),
683 return Some(Ok(innermost_binding));
687 // Found the first solution.
688 innermost_result = Some((binding, flags));
691 Ok(..) | Err(Determinacy::Determined) => {}
692 Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined,
699 if let Some(break_result) = break_result {
703 // The first found solution was the only one, return it.
704 if let Some((binding, _)) = innermost_result {
708 Err(Determinacy::determined(determinacy == Determinacy::Determined || force))
711 #[instrument(level = "debug", skip(self))]
712 pub(crate) fn maybe_resolve_ident_in_module(
714 module: ModuleOrUniformRoot<'a>,
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)
723 #[instrument(level = "debug", skip(self))]
724 pub(crate) fn resolve_ident_in_module(
726 module: ModuleOrUniformRoot<'a>,
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)
737 #[instrument(level = "debug", skip(self))]
738 fn resolve_ident_in_module_ext(
740 module: ModuleOrUniformRoot<'a>,
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;
750 ModuleOrUniformRoot::Module(m) => {
751 if let Some(def) = ident.span.normalize_to_macros_2_0_and_adjust(m.expansion) {
753 ParentScope { module: self.expn_def_scope(def), ..*parent_scope };
754 adjusted_parent_scope = &tmp_parent_scope;
757 ModuleOrUniformRoot::ExternPrelude => {
758 ident.span.normalize_to_macros_2_0_and_adjust(ExpnId::root());
760 ModuleOrUniformRoot::CrateRootAndExternPrelude | ModuleOrUniformRoot::CurrentScope => {
764 self.resolve_ident_in_module_unadjusted_ext(
768 adjusted_parent_scope,
775 #[instrument(level = "debug", skip(self))]
776 fn resolve_ident_in_module_unadjusted(
778 module: ModuleOrUniformRoot<'a>,
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(
794 .map_err(|(determinacy, _)| determinacy)
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(
802 module: ModuleOrUniformRoot<'a>,
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(
818 ScopeSet::AbsolutePath(ns),
824 return binding.map_err(|determinacy| (determinacy, Weak::No));
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()) {
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))
836 Err((Determined, Weak::No))
839 ModuleOrUniformRoot::CurrentScope => {
840 assert!(!restricted_shadowing);
842 if ident.name == kw::Crate || ident.name == kw::DollarCrate {
843 let module = self.resolve_crate_root(ident);
845 (module, ty::Visibility::Public, module.span, LocalExpnId::ROOT)
846 .to_name_binding(self.arenas);
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_...`.
855 let scopes = ScopeSet::All(ns, true);
856 let binding = self.early_resolve_ident_in_lexical_scope(
864 return binding.map_err(|determinacy| (determinacy, Weak::No));
868 let key = self.new_key(ident, ns);
870 self.resolution(module, key).try_borrow_mut().map_err(|_| (Determined, Weak::No))?; // This happens when there is a cycle of imports.
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]
879 .filter_map(|binding| match (binding, ignore_binding) {
880 (Some(binding), Some(ignored)) if ptr::eq(binding, ignored) => None,
884 let Some(binding) = binding else {
885 return Err((Determined, Weak::No));
888 if !self.is_accessible_from(binding.vis, parent_scope.module) {
890 self.privacy_errors.push(PrivacyError {
893 dedup_span: path_span,
896 return Err((Determined, Weak::No));
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()
906 self.ambiguity_errors.push(AmbiguityError {
907 kind: AmbiguityKind::GlobVsExpanded,
911 misc1: AmbiguityErrorMisc::None,
912 misc2: AmbiguityErrorMisc::None,
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));
922 self.record_use(ident, binding, restricted_shadowing);
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));
930 let usable = this.is_accessible_from(binding.vis, parent_scope.module);
931 if usable { Ok(binding) } else { Err((Determined, Weak::No)) }
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);
941 // --- From now on we either have a glob resolution or no resolution. ---
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 {
949 if !self.is_accessible_from(import_vis, parent_scope.module) {
952 let Some(module) = single_import.imported_module.get() else {
953 return Err((Undetermined, Weak::No));
955 let ImportKind::Single { source: ident, .. } = single_import.kind else {
958 match self.resolve_ident_in_module(
962 &single_import.parent_scope,
966 Err(Determined) => continue,
968 if !self.is_accessible_from(binding.vis, single_import.parent_scope.module) =>
972 Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::No)),
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).
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);
993 return Err((Undetermined, Weak::No));
997 // --- From now on we have no resolution. ---
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`.
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));
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 {
1017 if !self.is_accessible_from(import_vis, parent_scope.module) {
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)),
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)) => {
1031 ParentScope { module: self.expn_def_scope(def), ..*parent_scope };
1032 adjusted_parent_scope = &tmp_parent_scope;
1037 let result = self.resolve_ident_in_module_unadjusted(
1038 ModuleOrUniformRoot::Module(module),
1041 adjusted_parent_scope,
1047 Err(Determined) => continue,
1049 if !self.is_accessible_from(binding.vis, glob_import.parent_scope.module) =>
1053 Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::Yes)),
1057 // No resolution and no one else can define the name - determinate error.
1058 Err((Determined, Weak::No))
1061 /// Validate a local resolution (from ribs).
1062 #[instrument(level = "debug", skip(self, all_ribs))]
1063 fn validate_res_from_ribs(
1068 finalize: Option<Span>,
1069 original_rib_ident_def: Ident,
1070 all_ribs: &[Rib<'a>],
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..];
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
1082 ResolutionError::ForwardDeclaredGenericParam
1084 self.report_error(span, res_error);
1086 assert_eq!(res, Res::Err);
1092 use ResolutionError::*;
1093 let mut res_err = None;
1098 | ClosureOrAsyncRibKind
1100 | MacroDefinition(..)
1101 | ForwardGenericParamBanRibKind => {
1102 // Nothing to do. Continue.
1104 ItemRibKind(_) | AssocItemRibKind => {
1105 // This was an attempt to access an upvar inside a
1106 // named function item. This is not allowed, so we
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
1113 res_err = Some((span, CannotCaptureDynamicEnvironmentInFnItem));
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",
1127 AttemptToUseNonConstantValueInConstant(
1128 ident, "let", kind_str,
1134 AttemptToUseNonConstantValueInConstant(
1135 original_rib_ident_def,
1141 self.report_error(span, resolution_error);
1145 ConstParamTyRibKind => {
1146 if let Some(span) = finalize {
1147 self.report_error(span, ParamInTyOfConstParam(rib_ident.name));
1151 InlineAsmSymRibKind => {
1152 if let Some(span) = finalize {
1153 self.report_error(span, InvalidAsmSym);
1159 if let Some((span, res_err)) = res_err {
1160 self.report_error(span, res_err);
1164 Res::Def(DefKind::TyParam, _) | Res::SelfTy { .. } => {
1166 let has_generic_params: HasGenericParams = match rib.kind {
1168 | ClosureOrAsyncRibKind
1170 | MacroDefinition(..)
1171 | InlineAsmSymRibKind
1173 | ForwardGenericParamBanRibKind => {
1174 // Nothing to do. Continue.
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)
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)) }
1190 if let Some(span) = finalize {
1193 ResolutionError::ParamInNonTrivialAnonConst {
1194 name: rib_ident.name,
1198 self.session.delay_span_bug(span, CG_BUG_STR);
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 {
1214 ResolutionError::ParamInTyOfConstParam(rib_ident.name),
1221 if let Some(span) = finalize {
1224 ResolutionError::GenericParamsFromOuterFunction(
1233 Res::Def(DefKind::ConstParam, _) => {
1235 let has_generic_params = match rib.kind {
1237 | ClosureOrAsyncRibKind
1239 | MacroDefinition(..)
1240 | InlineAsmSymRibKind
1242 | ForwardGenericParamBanRibKind => continue,
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)
1250 if let Some(span) = finalize {
1253 ResolutionError::ParamInNonTrivialAnonConst {
1254 name: rib_ident.name,
1258 self.session.delay_span_bug(span, CG_BUG_STR);
1267 ItemRibKind(has_generic_params) => has_generic_params,
1268 ConstParamTyRibKind => {
1269 if let Some(span) = finalize {
1272 ResolutionError::ParamInTyOfConstParam(rib_ident.name),
1279 // This was an attempt to use a const parameter outside its scope.
1280 if let Some(span) = finalize {
1283 ResolutionError::GenericParamsFromOuterFunction(
1297 #[instrument(level = "debug", skip(self))]
1298 pub(crate) fn maybe_resolve_path(
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)
1307 #[instrument(level = "debug", skip(self))]
1308 pub(crate) fn resolve_path(
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)
1319 pub(crate) fn resolve_path_with_ribs(
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);
1330 let mut module = None;
1331 let mut allow_super = true;
1332 let mut second_binding = None;
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));
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;
1351 allow_super &= ns == TypeNS && (name == kw::SelfLower || name == kw::Super);
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)),
1359 Some(ModuleOrUniformRoot::Module(module)) => Some(module),
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),
1371 return PathResult::failed(ident.span, false, finalize.is_some(), || {
1372 ("there are too many leading `super` keywords".to_string(), None)
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),
1383 if name == kw::PathRoot && ident.span.rust_2018() {
1384 module = Some(ModuleOrUniformRoot::ExternPrelude);
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);
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)));
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()
1406 format!("`{}`", name)
1408 let label = if i == 1 && path[0].ident.name == kw::PathRoot {
1409 format!("global paths cannot start with {}", name_str)
1411 format!("{} in paths can only be used in start position", name_str)
1417 enum FindBindingResult<'a> {
1418 Binding(Result<&'a NameBinding<'a>, Determinacy>),
1421 let find_binding_in_ns = |this: &mut Self, ns| {
1422 let binding = if let Some(module) = module {
1423 this.resolve_ident_in_module(
1431 } else if let Some(ribs) = ribs
1432 && let Some(TypeNS | ValueNS) = opt_ns
1434 match this.resolve_ident_in_lexical_scope(
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())),
1449 let scopes = ScopeSet::All(ns, opt_ns.is_none());
1450 this.early_resolve_ident_in_lexical_scope(
1459 FindBindingResult::Binding(binding)
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(
1469 FindBindingResult::Binding(binding) => binding,
1474 second_binding = Some(binding);
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() {
1486 "cannot use a tool module through an import",
1488 .span_note(binding.span, "the tool module imported here")
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(
1503 return PathResult::failed(ident.span, is_last, finalize.is_some(), || {
1504 let label = format!(
1505 "`{ident}` is {} {}, not a module",
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(),
1524 return PathResult::failed(ident.span, is_last, finalize.is_some(), || {
1525 self.report_path_resolution_error(
1540 self.lint_if_path_starts_with_module(finalize, path, second_binding);
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),