1use std::ops::ControlFlow;
2
3use Determinacy::*;
4use Namespace::*;
5use rustc_ast::{self as ast, NodeId};
6use rustc_errors::ErrorGuaranteed;
7use rustc_hir::def::{DefKind, MacroKinds, Namespace, NonMacroAttrKind, PartialRes, PerNS};
8use rustc_middle::{bug, span_bug};
9use rustc_session::diagnostics::feature_err;
10use rustc_session::lint::builtin::PROC_MACRO_DERIVE_RESOLUTION_FALLBACK;
11use rustc_span::edition::Edition;
12use rustc_span::hygiene::{ExpnId, ExpnKind, LocalExpnId, MacroKind, SyntaxContext};
13use rustc_span::{Ident, Span, kw, sym};
14use smallvec::SmallVec;
15use tracing::{debug, instrument};
16
17use crate::diagnostics::{ParamKindInEnumDiscriminant, ParamKindInNonTrivialAnonConst};
18use crate::hygiene::Macros20NormalizedSyntaxContext;
19use crate::imports::{Import, NameResolution, cycle_detection};
20use crate::late::{
21 ConstantHasGenerics, DiagMetadata, NoConstantGenericsReason, PathSource, Rib, RibKind,
22};
23use crate::macros::{MacroRulesScope, sub_namespace_match};
24use crate::{
25 AmbiguityError, AmbiguityKind, AmbiguityWarning, BindingKey, CmResolver, Decl, DeclKind,
26 Determinacy, ExternModule, Finalize, IdentKey, ImportKind, ImportSummary, LateDecl,
27 LocalModule, Module, ModuleKind, ModuleOrUniformRoot, ParentScope, PathResult, PrivacyError,
28 Res, ResolutionError, Resolver, Scope, ScopeSet, Segment, Stage, Symbol, Used, diagnostics,
29 module_to_string,
30};
31
32#[derive(#[automatically_derived]
impl ::core::marker::Copy for UsePrelude { }Copy, #[automatically_derived]
impl ::core::clone::Clone for UsePrelude {
#[inline]
fn clone(&self) -> UsePrelude { *self }
}Clone)]
33pub enum UsePrelude {
34 No,
35 Yes,
36}
37
38impl From<UsePrelude> for bool {
39 fn from(up: UsePrelude) -> bool {
40 #[allow(non_exhaustive_omitted_patterns)] match up {
UsePrelude::Yes => true,
_ => false,
}matches!(up, UsePrelude::Yes)
41 }
42}
43
44#[derive(#[automatically_derived]
impl ::core::fmt::Debug for Shadowing {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
Shadowing::Restricted => "Restricted",
Shadowing::Unrestricted => "Unrestricted",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for Shadowing {
#[inline]
fn eq(&self, other: &Shadowing) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::clone::Clone for Shadowing {
#[inline]
fn clone(&self) -> Shadowing { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Shadowing { }Copy)]
45enum Shadowing {
46 Restricted,
47 Unrestricted,
48}
49
50impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
51 pub(crate) fn visit_scopes<'r, T>(
55 mut self: CmResolver<'r, 'ra, 'tcx>,
56 scope_set: ScopeSet<'ra>,
57 parent_scope: &ParentScope<'ra>,
58 mut ctxt: Macros20NormalizedSyntaxContext,
59 orig_ident_span: Span,
60 derive_fallback_lint_id: Option<NodeId>,
61 mut visitor: impl FnMut(
62 CmResolver<'_, 'ra, 'tcx>,
63 Scope<'ra>,
64 UsePrelude,
65 Macros20NormalizedSyntaxContext,
66 ) -> ControlFlow<T>,
67 ) -> Option<T> {
68 let (ns, macro_kind) = match scope_set {
110 ScopeSet::All(ns)
111 | ScopeSet::Module(ns, _)
112 | ScopeSet::ModuleAndExternPrelude(ns, _) => (ns, None),
113 ScopeSet::ExternPrelude => (TypeNS, None),
114 ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind)),
115 };
116 let module = match scope_set {
117 ScopeSet::Module(_, module) | ScopeSet::ModuleAndExternPrelude(_, module) => module,
119 _ => parent_scope.module.nearest_item_scope(),
121 };
122 let module_only = #[allow(non_exhaustive_omitted_patterns)] match scope_set {
ScopeSet::Module(..) => true,
_ => false,
}matches!(scope_set, ScopeSet::Module(..));
123 let module_and_extern_prelude = #[allow(non_exhaustive_omitted_patterns)] match scope_set {
ScopeSet::ModuleAndExternPrelude(..) => true,
_ => false,
}matches!(scope_set, ScopeSet::ModuleAndExternPrelude(..));
124 let extern_prelude = #[allow(non_exhaustive_omitted_patterns)] match scope_set {
ScopeSet::ExternPrelude => true,
_ => false,
}matches!(scope_set, ScopeSet::ExternPrelude);
125 let mut scope = match ns {
126 _ if module_only || module_and_extern_prelude => Scope::ModuleNonGlobs(module, None),
127 _ if extern_prelude => Scope::ExternPreludeItems,
128 TypeNS | ValueNS => Scope::ModuleNonGlobs(module, None),
129 MacroNS => Scope::DeriveHelpers(parent_scope.expansion),
130 };
131 let mut use_prelude = !module.no_implicit_prelude;
132
133 loop {
134 let visit = match scope {
135 Scope::DeriveHelpers(expn_id) => {
137 !(expn_id == parent_scope.expansion && macro_kind == Some(MacroKind::Derive))
138 }
139 Scope::DeriveHelpersCompat => true,
140 Scope::MacroRules(macro_rules_scope) => {
141 let mut scope = macro_rules_scope.get();
146 while let MacroRulesScope::Invocation(invoc_id) = scope {
147 if let Some(next) = self.output_macro_rules_scopes.get(&invoc_id) {
148 scope = next.get();
149 macro_rules_scope.set(scope);
150 } else {
151 break;
152 }
153 }
154 true
155 }
156 Scope::ModuleNonGlobs(..) | Scope::ModuleGlobs(..) => true,
157 Scope::MacroUsePrelude => use_prelude || orig_ident_span.is_rust_2015(),
158 Scope::BuiltinAttrs => true,
159 Scope::ExternPreludeItems | Scope::ExternPreludeFlags => {
160 use_prelude || module_and_extern_prelude || extern_prelude
161 }
162 Scope::ToolAttributePrelude => use_prelude,
163 Scope::StdLibPrelude => use_prelude || ns == MacroNS,
164 Scope::BuiltinTypes => true,
165 };
166
167 if visit {
168 let use_prelude = if use_prelude { UsePrelude::Yes } else { UsePrelude::No };
169 if let ControlFlow::Break(break_result) =
170 visitor(self.reborrow(), scope, use_prelude, ctxt)
171 {
172 return Some(break_result);
173 }
174 }
175
176 scope = match scope {
177 Scope::DeriveHelpers(LocalExpnId::ROOT) => Scope::DeriveHelpersCompat,
178 Scope::DeriveHelpers(expn_id) => {
179 let expn_data = expn_id.expn_data();
181 match expn_data.kind {
182 ExpnKind::Root
183 | ExpnKind::Macro(MacroKind::Bang | MacroKind::Derive, _) => {
184 Scope::DeriveHelpersCompat
185 }
186 _ => Scope::DeriveHelpers(expn_data.parent.expect_local()),
187 }
188 }
189 Scope::DeriveHelpersCompat => Scope::MacroRules(parent_scope.macro_rules),
190 Scope::MacroRules(macro_rules_scope) => match macro_rules_scope.get() {
191 MacroRulesScope::Def(binding) => {
192 Scope::MacroRules(binding.parent_macro_rules_scope)
193 }
194 MacroRulesScope::Invocation(invoc_id) => {
195 Scope::MacroRules(self.invocation_parent_scopes[&invoc_id].macro_rules)
196 }
197 MacroRulesScope::Empty => Scope::ModuleNonGlobs(module, None),
198 },
199 Scope::ModuleNonGlobs(module, lint_id) => Scope::ModuleGlobs(module, lint_id),
200 Scope::ModuleGlobs(..) if module_only => break,
201 Scope::ModuleGlobs(..) if module_and_extern_prelude => match ns {
202 TypeNS => {
203 ctxt.update_unchecked(|ctxt| ctxt.adjust(ExpnId::root()));
204 Scope::ExternPreludeItems
205 }
206 ValueNS | MacroNS => break,
207 },
208 Scope::ModuleGlobs(module, prev_lint_id) => {
209 use_prelude = !module.no_implicit_prelude;
210 match self.hygienic_lexical_parent(module, &mut ctxt, derive_fallback_lint_id) {
211 Some((parent_module, lint_id)) => {
212 Scope::ModuleNonGlobs(parent_module, lint_id.or(prev_lint_id))
213 }
214 None => {
215 ctxt.update_unchecked(|ctxt| ctxt.adjust(ExpnId::root()));
216 match ns {
217 TypeNS => Scope::ExternPreludeItems,
218 ValueNS => Scope::StdLibPrelude,
219 MacroNS => Scope::MacroUsePrelude,
220 }
221 }
222 }
223 }
224 Scope::MacroUsePrelude => Scope::StdLibPrelude,
225 Scope::BuiltinAttrs => break, Scope::ExternPreludeItems => Scope::ExternPreludeFlags,
227 Scope::ExternPreludeFlags if module_and_extern_prelude || extern_prelude => break,
228 Scope::ExternPreludeFlags => Scope::ToolAttributePrelude,
229 Scope::ToolAttributePrelude => Scope::StdLibPrelude,
230 Scope::StdLibPrelude => match ns {
231 TypeNS => Scope::BuiltinTypes,
232 ValueNS => break, MacroNS => Scope::BuiltinAttrs,
234 },
235 Scope::BuiltinTypes => break, };
237 }
238
239 None
240 }
241
242 fn hygienic_lexical_parent(
243 &self,
244 module: Module<'ra>,
245 ctxt: &mut Macros20NormalizedSyntaxContext,
246 derive_fallback_lint_id: Option<NodeId>,
247 ) -> Option<(Module<'ra>, Option<NodeId>)> {
248 if !module.expansion.outer_expn_is_descendant_of(**ctxt) {
249 let expn_id = ctxt.update_unchecked(|ctxt| ctxt.remove_mark());
250 return Some((self.expn_def_scope(expn_id), None));
251 }
252
253 if let ModuleKind::Block = module.kind {
254 return Some((module.parent.unwrap().nearest_item_scope(), None));
255 }
256
257 if derive_fallback_lint_id.is_some()
269 && let Some(parent) = module.parent
270 && module.expansion != parent.expansion
272 && module.expansion.is_descendant_of(parent.expansion)
274 && let Some(def_id) = module.expansion.expn_data().macro_def_id
276 {
277 let ext = self.get_macro_by_def_id(def_id);
278 if ext.builtin_name.is_none()
279 && ext.macro_kinds() == MacroKinds::DERIVE
280 && parent.expansion.outer_expn_is_descendant_of(**ctxt)
281 {
282 return Some((parent, derive_fallback_lint_id));
283 }
284 }
285
286 None
287 }
288
289 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("resolve_ident_in_lexical_scope",
"rustc_resolve::ident", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
::tracing_core::__macro_support::Option::Some(306u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ident")
}> =
::tracing::__macro_support::FieldName::new("ident");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ns")
}> =
::tracing::__macro_support::FieldName::new("ns");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("parent_scope")
}> =
::tracing::__macro_support::FieldName::new("parent_scope");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("finalize")
}> =
::tracing::__macro_support::FieldName::new("finalize");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ignore_decl")
}> =
::tracing::__macro_support::FieldName::new("ignore_decl");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("diag_metadata")
}> =
::tracing::__macro_support::FieldName::new("diag_metadata");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ns)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_scope)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&finalize)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_decl)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&diag_metadata)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Option<LateDecl<'ra>> = loop {};
return __tracing_attr_fake_return;
}
{
let orig_ident = ident;
let (general_span, normalized_span) =
if ident.name == kw::SelfUpper {
let empty_span =
ident.span.with_ctxt(SyntaxContext::root());
(empty_span, empty_span)
} else if ns == TypeNS {
let normalized_span = ident.span.normalize_to_macros_2_0();
(normalized_span, normalized_span)
} else {
(ident.span.normalize_to_macro_rules(),
ident.span.normalize_to_macros_2_0())
};
ident.span = general_span;
let normalized_ident = Ident { span: normalized_span, ..ident };
for (i, rib) in ribs.iter().enumerate().rev() {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/ident.rs:333",
"rustc_resolve::ident", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
::tracing_core::__macro_support::Option::Some(333u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("walk rib\n{0:?}",
rib.bindings) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let rib_ident =
if rib.kind.contains_params() {
normalized_ident
} else { ident };
if let Some((original_rib_ident_def, res)) =
rib.bindings.get_key_value(&rib_ident) {
return Some(LateDecl::RibDef(self.validate_res_from_ribs(i,
rib_ident, *res, finalize.map(|_| general_span),
*original_rib_ident_def, ribs, diag_metadata)));
} else if let RibKind::Block(Some(module)) = rib.kind &&
let Ok(binding) =
self.cm_mut().resolve_ident_in_scope_set(ident,
ScopeSet::Module(ns, module.to_module()), parent_scope,
finalize.map(|finalize|
Finalize { used: Used::Scope, ..finalize }), ignore_decl,
None) {
return Some(LateDecl::Decl(binding));
} else if let RibKind::Module(module) = rib.kind {
let parent_scope =
&ParentScope {
module: module.to_module(),
..*parent_scope
};
let finalize =
finalize.map(|f| Finalize { stage: Stage::Late, ..f });
return self.cm_mut().resolve_ident_in_scope_set(orig_ident,
ScopeSet::All(ns), parent_scope, finalize, ignore_decl,
None).ok().map(LateDecl::Decl);
}
if let RibKind::MacroDefinition(def) = rib.kind &&
def == self.macro_def(ident.span.ctxt()) {
ident.span.remove_mark();
}
}
::core::panicking::panic("internal error: entered unreachable code")
}
}
}#[instrument(level = "debug", skip(self, ribs))]
307 pub(crate) fn resolve_ident_in_lexical_scope(
308 &mut self,
309 mut ident: Ident,
310 ns: Namespace,
311 parent_scope: &ParentScope<'ra>,
312 finalize: Option<Finalize>,
313 ribs: &[Rib<'ra>],
314 ignore_decl: Option<Decl<'ra>>,
315 diag_metadata: Option<&DiagMetadata<'_>>,
316 ) -> Option<LateDecl<'ra>> {
317 let orig_ident = ident;
318 let (general_span, normalized_span) = if ident.name == kw::SelfUpper {
319 let empty_span = ident.span.with_ctxt(SyntaxContext::root());
321 (empty_span, empty_span)
322 } else if ns == TypeNS {
323 let normalized_span = ident.span.normalize_to_macros_2_0();
324 (normalized_span, normalized_span)
325 } else {
326 (ident.span.normalize_to_macro_rules(), ident.span.normalize_to_macros_2_0())
327 };
328 ident.span = general_span;
329 let normalized_ident = Ident { span: normalized_span, ..ident };
330
331 for (i, rib) in ribs.iter().enumerate().rev() {
333 debug!("walk rib\n{:?}", rib.bindings);
334 let rib_ident = if rib.kind.contains_params() { normalized_ident } else { ident };
337 if let Some((original_rib_ident_def, res)) = rib.bindings.get_key_value(&rib_ident) {
338 return Some(LateDecl::RibDef(self.validate_res_from_ribs(
340 i,
341 rib_ident,
342 *res,
343 finalize.map(|_| general_span),
344 *original_rib_ident_def,
345 ribs,
346 diag_metadata,
347 )));
348 } else if let RibKind::Block(Some(module)) = rib.kind
349 && let Ok(binding) = self.cm_mut().resolve_ident_in_scope_set(
350 ident,
351 ScopeSet::Module(ns, module.to_module()),
352 parent_scope,
353 finalize.map(|finalize| Finalize { used: Used::Scope, ..finalize }),
354 ignore_decl,
355 None,
356 )
357 {
358 return Some(LateDecl::Decl(binding));
360 } else if let RibKind::Module(module) = rib.kind {
361 let parent_scope = &ParentScope { module: module.to_module(), ..*parent_scope };
363 let finalize = finalize.map(|f| Finalize { stage: Stage::Late, ..f });
364 return self
365 .cm_mut()
366 .resolve_ident_in_scope_set(
367 orig_ident,
368 ScopeSet::All(ns),
369 parent_scope,
370 finalize,
371 ignore_decl,
372 None,
373 )
374 .ok()
375 .map(LateDecl::Decl);
376 }
377
378 if let RibKind::MacroDefinition(def) = rib.kind
379 && def == self.macro_def(ident.span.ctxt())
380 {
381 ident.span.remove_mark();
384 }
385 }
386
387 unreachable!()
388 }
389
390 pub(crate) fn resolve_ident_in_scope_set<'r>(
392 self: CmResolver<'r, 'ra, 'tcx>,
393 orig_ident: Ident,
394 scope_set: ScopeSet<'ra>,
395 parent_scope: &ParentScope<'ra>,
396 finalize: Option<Finalize>,
397 ignore_decl: Option<Decl<'ra>>,
398 ignore_import: Option<Import<'ra>>,
399 ) -> Result<Decl<'ra>, Determinacy> {
400 self.resolve_ident_in_scope_set_inner(
401 IdentKey::new(orig_ident),
402 orig_ident.span,
403 scope_set,
404 parent_scope,
405 finalize,
406 ignore_decl,
407 ignore_import,
408 )
409 }
410
411 fn resolve_ident_in_scope_set_inner<'r>(
412 self: CmResolver<'r, 'ra, 'tcx>,
413 ident: IdentKey,
414 orig_ident_span: Span,
415 scope_set: ScopeSet<'ra>,
416 parent_scope: &ParentScope<'ra>,
417 finalize: Option<Finalize>,
418 ignore_decl: Option<Decl<'ra>>,
419 ignore_import: Option<Import<'ra>>,
420 ) -> Result<Decl<'ra>, Determinacy> {
421 if ident.name.is_path_segment_keyword() {
423 return Err(Determinacy::Determined);
424 }
425
426 let (ns, macro_kind) = match scope_set {
427 ScopeSet::All(ns)
428 | ScopeSet::Module(ns, _)
429 | ScopeSet::ModuleAndExternPrelude(ns, _) => (ns, None),
430 ScopeSet::ExternPrelude => (TypeNS, None),
431 ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind)),
432 };
433 let derive_fallback_lint_id = match finalize {
434 Some(Finalize { node_id, stage: Stage::Late, .. }) => Some(node_id),
435 _ => None,
436 };
437
438 let mut innermost_results: SmallVec<[(Decl<'_>, Scope<'_>); 2]> = SmallVec::new();
450 let mut determinacy = Determinacy::Determined;
451
452 let break_result = self.visit_scopes(
454 scope_set,
455 parent_scope,
456 ident.ctxt,
457 orig_ident_span,
458 derive_fallback_lint_id,
459 |mut this, scope, use_prelude, ctxt| {
460 let ident = IdentKey { name: ident.name, ctxt };
461 let res = match this.reborrow().resolve_ident_in_scope(
462 ident,
463 orig_ident_span,
464 ns,
465 scope,
466 use_prelude,
467 scope_set,
468 parent_scope,
469 if innermost_results.is_empty() { finalize } else { None },
471 ignore_decl,
472 ignore_import,
473 ) {
474 Ok(decl) => Ok(decl),
475 Err(ControlFlow::Break(determinacy)) if innermost_results.is_empty() => {
480 return ControlFlow::Break(Err(determinacy));
481 }
482 Err(determinacy) => Err(determinacy.into_value()),
483 };
484 match res {
485 Ok(decl) if sub_namespace_match(decl.macro_kinds(), macro_kind) => {
486 let import = match finalize {
491 None | Some(Finalize { stage: Stage::Late, .. }) => {
492 return ControlFlow::Break(Ok(decl));
493 }
494 Some(Finalize { import, .. }) => import,
495 };
496 this.get_mut().maybe_push_glob_vs_glob_vis_ambiguity(
497 ident,
498 orig_ident_span,
499 decl,
500 import,
501 );
502
503 if let Some(&(innermost_decl, _)) = innermost_results.first() {
504 if this.get_mut().maybe_push_ambiguity(
506 ident,
507 orig_ident_span,
508 ns,
509 scope_set,
510 parent_scope,
511 decl,
512 scope,
513 &innermost_results,
514 import,
515 ) {
516 return ControlFlow::Break(Ok(innermost_decl));
518 }
519 }
520
521 innermost_results.push((decl, scope));
522 }
523 Ok(_) | Err(Determinacy::Determined) => {}
524 Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined,
525 }
526
527 ControlFlow::Continue(())
528 },
529 );
530
531 if let Some(break_result) = break_result {
533 return break_result;
534 }
535
536 match innermost_results.first() {
538 Some(&(decl, ..)) => Ok(decl),
539 None => Err(determinacy),
540 }
541 }
542
543 fn resolve_ident_in_scope<'r>(
544 mut self: CmResolver<'r, 'ra, 'tcx>,
545 ident: IdentKey,
546 orig_ident_span: Span,
547 ns: Namespace,
548 scope: Scope<'ra>,
549 use_prelude: UsePrelude,
550 scope_set: ScopeSet<'ra>,
551 parent_scope: &ParentScope<'ra>,
552 finalize: Option<Finalize>,
553 ignore_decl: Option<Decl<'ra>>,
554 ignore_import: Option<Import<'ra>>,
555 ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
556 let ret = match scope {
557 Scope::DeriveHelpers(expn_id) => {
558 if let Some(decl) = self
559 .helper_attrs
560 .get(&expn_id)
561 .and_then(|attrs| attrs.iter().rfind(|(i, ..)| ident == *i).map(|(.., d)| *d))
562 {
563 Ok(decl)
564 } else {
565 Err(Determinacy::Determined)
566 }
567 }
568 Scope::DeriveHelpersCompat => {
569 let mut result = Err(Determinacy::Determined);
570 for derive in parent_scope.derives {
571 let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
572 match self.reborrow().resolve_derive_macro_path(
573 derive,
574 parent_scope,
575 false,
576 ignore_import,
577 ) {
578 Ok((Some(ext), _)) => {
579 if ext.helper_attrs.contains(&ident.name) {
580 let decl = self.arenas.new_pub_def_decl(
581 Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat),
582 derive.span,
583 LocalExpnId::ROOT,
584 );
585 result = Ok(decl);
586 break;
587 }
588 }
589 Ok(_) | Err(Determinacy::Determined) => {}
590 Err(Determinacy::Undetermined) => result = Err(Determinacy::Undetermined),
591 }
592 }
593 result
594 }
595 Scope::MacroRules(macro_rules_scope) => match macro_rules_scope.get() {
596 MacroRulesScope::Def(macro_rules_def) if ident == macro_rules_def.ident => {
597 Ok(macro_rules_def.decl)
598 }
599 MacroRulesScope::Invocation(_) => Err(Determinacy::Undetermined),
600 _ => Err(Determinacy::Determined),
601 },
602 Scope::ModuleNonGlobs(module, derive_fallback_lint_id) => {
603 let (adjusted_parent_scope, adjusted_finalize) = if #[allow(non_exhaustive_omitted_patterns)] match scope_set {
ScopeSet::Module(..) | ScopeSet::ModuleAndExternPrelude(..) => true,
_ => false,
}matches!(
604 scope_set,
605 ScopeSet::Module(..) | ScopeSet::ModuleAndExternPrelude(..)
606 ) {
607 (parent_scope, finalize)
608 } else {
609 (
610 &ParentScope { module, ..*parent_scope },
611 finalize.map(|f| Finalize { used: Used::Scope, ..f }),
612 )
613 };
614 let shadowing = if #[allow(non_exhaustive_omitted_patterns)] match scope_set {
ScopeSet::Module(..) => true,
_ => false,
}matches!(scope_set, ScopeSet::Module(..)) {
615 Shadowing::Unrestricted
616 } else {
617 Shadowing::Restricted
618 };
619 let decl = if module.is_local() {
620 self.reborrow().resolve_ident_in_local_module_non_globs_unadjusted(
621 module.expect_local(),
622 ident,
623 orig_ident_span,
624 ns,
625 adjusted_parent_scope,
626 shadowing,
627 adjusted_finalize,
628 ignore_decl,
629 ignore_import,
630 )
631 } else {
632 self.reborrow().resolve_ident_in_extern_module_non_globs_unadjusted(
633 module.expect_extern(),
634 ident,
635 orig_ident_span,
636 ns,
637 adjusted_parent_scope,
638 shadowing,
639 adjusted_finalize,
640 ignore_decl,
641 )
642 };
643
644 match decl {
645 Ok(decl) => {
646 if let Some(lint_id) = derive_fallback_lint_id {
647 self.get_mut().lint_buffer.buffer_lint(
648 PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
649 lint_id,
650 orig_ident_span,
651 diagnostics::ProcMacroDeriveResolutionFallback {
652 span: orig_ident_span,
653 ns_descr: ns.descr(),
654 ident: ident.name,
655 },
656 );
657 }
658 Ok(decl)
659 }
660 Err(ControlFlow::Continue(determinacy)) => Err(determinacy),
661 Err(ControlFlow::Break(..)) => return decl,
662 }
663 }
664 Scope::ModuleGlobs(module, _) if !module.is_local() => {
665 Err(Determined)
667 }
668 Scope::ModuleGlobs(module, derive_fallback_lint_id) => {
669 let (adjusted_parent_scope, adjusted_finalize) = if #[allow(non_exhaustive_omitted_patterns)] match scope_set {
ScopeSet::Module(..) | ScopeSet::ModuleAndExternPrelude(..) => true,
_ => false,
}matches!(
670 scope_set,
671 ScopeSet::Module(..) | ScopeSet::ModuleAndExternPrelude(..)
672 ) {
673 (parent_scope, finalize)
674 } else {
675 (
676 &ParentScope { module, ..*parent_scope },
677 finalize.map(|f| Finalize { used: Used::Scope, ..f }),
678 )
679 };
680 let binding = self.reborrow().resolve_ident_in_module_globs_unadjusted(
681 module.expect_local(),
682 ident,
683 orig_ident_span,
684 ns,
685 adjusted_parent_scope,
686 if #[allow(non_exhaustive_omitted_patterns)] match scope_set {
ScopeSet::Module(..) => true,
_ => false,
}matches!(scope_set, ScopeSet::Module(..)) {
687 Shadowing::Unrestricted
688 } else {
689 Shadowing::Restricted
690 },
691 adjusted_finalize,
692 ignore_decl,
693 ignore_import,
694 );
695 match binding {
696 Ok(binding) => {
697 if let Some(lint_id) = derive_fallback_lint_id {
698 self.get_mut().lint_buffer.buffer_lint(
699 PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
700 lint_id,
701 orig_ident_span,
702 diagnostics::ProcMacroDeriveResolutionFallback {
703 span: orig_ident_span,
704 ns_descr: ns.descr(),
705 ident: ident.name,
706 },
707 );
708 }
709 Ok(binding)
710 }
711 Err(ControlFlow::Continue(determinacy)) => Err(determinacy),
712 Err(ControlFlow::Break(..)) => return binding,
713 }
714 }
715 Scope::MacroUsePrelude => match self.macro_use_prelude.get(&ident.name).cloned() {
716 Some(decl) => Ok(decl),
717 None => {
718 Err(Determinacy::determined(!self.graph_root.has_unexpanded_invocations(&self)))
719 }
720 },
721 Scope::BuiltinAttrs => match self.builtin_attr_decls.get(&ident.name) {
722 Some(decl) => Ok(*decl),
723 None => Err(Determinacy::Determined),
724 },
725 Scope::ExternPreludeItems => {
726 match self.reborrow().extern_prelude_get_item(
727 ident,
728 orig_ident_span,
729 finalize.is_some(),
730 ) {
731 Some(decl) => Ok(decl),
732 None => Err(Determinacy::determined(
733 !self.graph_root.has_unexpanded_invocations(&self),
734 )),
735 }
736 }
737 Scope::ExternPreludeFlags => {
738 match self.extern_prelude_get_flag(ident, orig_ident_span, finalize.is_some()) {
739 Some(decl) => Ok(decl),
740 None => Err(Determinacy::Determined),
741 }
742 }
743 Scope::ToolAttributePrelude => match self.registered_attr_tool_decls.get(&ident) {
744 Some(decl) => Ok(*decl),
745 None => Err(Determinacy::Determined),
746 },
747 Scope::StdLibPrelude => {
748 let mut result = Err(Determinacy::Determined);
749 if let Some(prelude) = self.prelude
750 && let Ok(decl) = self.reborrow().resolve_ident_in_scope_set_inner(
751 ident,
752 orig_ident_span,
753 ScopeSet::Module(ns, prelude),
754 parent_scope,
755 None,
756 ignore_decl,
757 ignore_import,
758 )
759 && (#[allow(non_exhaustive_omitted_patterns)] match use_prelude {
UsePrelude::Yes => true,
_ => false,
}matches!(use_prelude, UsePrelude::Yes) || self.is_builtin_macro(decl.res()))
760 {
761 result = Ok(decl)
762 }
763
764 result
765 }
766 Scope::BuiltinTypes => match self.builtin_type_decls.get(&ident.name) {
767 Some(decl) => {
768 if #[allow(non_exhaustive_omitted_patterns)] match ident.name {
sym::f16 => true,
_ => false,
}matches!(ident.name, sym::f16)
769 && !self.features.f16()
770 && !orig_ident_span.allows_unstable(sym::f16)
771 && finalize.is_some()
772 {
773 feature_err(
774 self.tcx.sess,
775 sym::f16,
776 orig_ident_span,
777 "the type `f16` is unstable",
778 )
779 .emit();
780 }
781 if #[allow(non_exhaustive_omitted_patterns)] match ident.name {
sym::f128 => true,
_ => false,
}matches!(ident.name, sym::f128)
782 && !self.features.f128()
783 && !orig_ident_span.allows_unstable(sym::f128)
784 && finalize.is_some()
785 {
786 feature_err(
787 self.tcx.sess,
788 sym::f128,
789 orig_ident_span,
790 "the type `f128` is unstable",
791 )
792 .emit();
793 }
794 Ok(*decl)
795 }
796 None => Err(Determinacy::Determined),
797 },
798 };
799
800 ret.map_err(ControlFlow::Continue)
801 }
802
803 fn maybe_push_glob_vs_glob_vis_ambiguity(
804 &mut self,
805 ident: IdentKey,
806 orig_ident_span: Span,
807 decl: Decl<'ra>,
808 import: Option<ImportSummary>,
809 ) {
810 let Some(import) = import else { return };
811 let vis1 = self.import_decl_vis(decl, import);
812 let vis2 = self.import_decl_vis_ext(decl, import, true);
813 if vis1 != vis2 {
814 self.ambiguity_errors.push(AmbiguityError {
815 kind: AmbiguityKind::GlobVsGlob,
816 ambig_vis: Some((vis1, vis2)),
817 ident: ident.orig(orig_ident_span),
818 b1: decl.ambiguity_vis_max.get().unwrap_or(decl),
819 b2: decl.ambiguity_vis_min.get().unwrap_or(decl),
820 scope1: Scope::ModuleGlobs(decl.parent_module.unwrap(), None),
821 scope2: Scope::ModuleGlobs(decl.parent_module.unwrap(), None),
822 warning: Some(AmbiguityWarning::GlobImport),
823 });
824 }
825 }
826
827 fn maybe_push_ambiguity(
828 &mut self,
829 ident: IdentKey,
830 orig_ident_span: Span,
831 ns: Namespace,
832 scope_set: ScopeSet<'ra>,
833 parent_scope: &ParentScope<'ra>,
834 decl: Decl<'ra>,
835 scope: Scope<'ra>,
836 innermost_results: &[(Decl<'ra>, Scope<'ra>)],
837 import: Option<ImportSummary>,
838 ) -> bool {
839 let (innermost_decl, innermost_scope) = innermost_results[0];
840 let (res, innermost_res) = (decl.res(), innermost_decl.res());
841 let ambig_vis = if res != innermost_res {
842 None
843 } else if let Some(import) = import
844 && let vis1 = self.import_decl_vis(decl, import)
845 && let vis2 = self.import_decl_vis(innermost_decl, import)
846 && vis1 != vis2
847 {
848 Some((vis1, vis2))
849 } else {
850 return false;
851 };
852
853 let module_only = #[allow(non_exhaustive_omitted_patterns)] match scope_set {
ScopeSet::Module(..) => true,
_ => false,
}matches!(scope_set, ScopeSet::Module(..));
856 let is_builtin = |res| #[allow(non_exhaustive_omitted_patterns)] match res {
Res::NonMacroAttr(NonMacroAttrKind::Builtin(..)) => true,
_ => false,
}matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Builtin(..)));
857 let derive_helper = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
858 let derive_helper_compat = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
859
860 let ambiguity_error_kind = if is_builtin(innermost_res) || is_builtin(res) {
861 Some(AmbiguityKind::BuiltinAttr)
862 } else if innermost_res == derive_helper_compat {
863 Some(AmbiguityKind::DeriveHelper)
864 } else if res == derive_helper_compat && innermost_res != derive_helper {
865 ::rustc_middle::util::bug::span_bug_fmt(orig_ident_span,
format_args!("impossible inner resolution kind"))span_bug!(orig_ident_span, "impossible inner resolution kind")
866 } else if #[allow(non_exhaustive_omitted_patterns)] match innermost_scope {
Scope::MacroRules(_) => true,
_ => false,
}matches!(innermost_scope, Scope::MacroRules(_))
867 && #[allow(non_exhaustive_omitted_patterns)] match scope {
Scope::ModuleNonGlobs(..) | Scope::ModuleGlobs(..) => true,
_ => false,
}matches!(scope, Scope::ModuleNonGlobs(..) | Scope::ModuleGlobs(..))
868 && !self.disambiguate_macro_rules_vs_modularized(innermost_decl, decl)
869 {
870 Some(AmbiguityKind::MacroRulesVsModularized)
871 } else if #[allow(non_exhaustive_omitted_patterns)] match scope {
Scope::MacroRules(_) => true,
_ => false,
}matches!(scope, Scope::MacroRules(_))
872 && #[allow(non_exhaustive_omitted_patterns)] match innermost_scope {
Scope::ModuleNonGlobs(..) | Scope::ModuleGlobs(..) => true,
_ => false,
}matches!(innermost_scope, Scope::ModuleNonGlobs(..) | Scope::ModuleGlobs(..))
873 {
874 ::rustc_middle::util::bug::span_bug_fmt(orig_ident_span,
format_args!("ambiguous scoped macro resolutions with path-based scope resolution as first candidate"))span_bug!(
880 orig_ident_span,
881 "ambiguous scoped macro resolutions with path-based \
882 scope resolution as first candidate"
883 )
884 } else if innermost_decl.is_glob_import() {
885 Some(AmbiguityKind::GlobVsOuter)
886 } else if !module_only && innermost_decl.may_appear_after(parent_scope.expansion, decl) {
887 Some(AmbiguityKind::MoreExpandedVsOuter)
888 } else if innermost_decl.expansion != LocalExpnId::ROOT
889 && (!module_only || ns == MacroNS)
890 && let Scope::ModuleGlobs(m1, _) = scope
891 && let Scope::ModuleNonGlobs(m2, _) = innermost_scope
892 && m1 == m2
893 {
894 Some(AmbiguityKind::GlobVsExpanded)
898 } else {
899 None
900 };
901
902 if let Some(kind) = ambiguity_error_kind {
903 let issue_145575_hack = #[allow(non_exhaustive_omitted_patterns)] match scope {
Scope::ExternPreludeFlags => true,
_ => false,
}matches!(scope, Scope::ExternPreludeFlags)
907 && innermost_results[1..]
908 .iter()
909 .any(|(b, s)| #[allow(non_exhaustive_omitted_patterns)] match s {
Scope::ExternPreludeItems => true,
_ => false,
}matches!(s, Scope::ExternPreludeItems) && *b != innermost_decl);
910 let issue_149681_hack = match scope {
914 Scope::ModuleGlobs(m1, _)
915 if innermost_results[1..]
916 .iter()
917 .any(|(_, s)| #[allow(non_exhaustive_omitted_patterns)] match *s {
Scope::ModuleNonGlobs(m2, _) if m1 == m2 => true,
_ => false,
}matches!(*s, Scope::ModuleNonGlobs(m2, _) if m1 == m2)) =>
918 {
919 true
920 }
921 _ => false,
922 };
923
924 if issue_145575_hack || issue_149681_hack {
925 self.issue_145575_hack_applied = true;
926 } else {
927 let is_issue_147319_hack = orig_ident_span.edition() <= Edition::Edition2024
930 && #[allow(non_exhaustive_omitted_patterns)] match ident.name {
sym::panic => true,
_ => false,
}matches!(ident.name, sym::panic)
931 && #[allow(non_exhaustive_omitted_patterns)] match scope {
Scope::StdLibPrelude => true,
_ => false,
}matches!(scope, Scope::StdLibPrelude)
932 && #[allow(non_exhaustive_omitted_patterns)] match innermost_scope {
Scope::ModuleGlobs(_, _) => true,
_ => false,
}matches!(innermost_scope, Scope::ModuleGlobs(_, _))
933 && ((self.is_specific_builtin_macro(res, sym::std_panic)
934 && self.is_specific_builtin_macro(innermost_res, sym::core_panic))
935 || (self.is_specific_builtin_macro(res, sym::core_panic)
936 && self.is_specific_builtin_macro(innermost_res, sym::std_panic)));
937
938 let warning = if ambig_vis.is_some() {
939 Some(AmbiguityWarning::GlobImport)
940 } else if is_issue_147319_hack {
941 Some(AmbiguityWarning::PanicImport)
942 } else {
943 None
944 };
945
946 self.ambiguity_errors.push(AmbiguityError {
947 kind,
948 ambig_vis,
949 ident: ident.orig(orig_ident_span),
950 b1: innermost_decl,
951 b2: decl,
952 scope1: innermost_scope,
953 scope2: scope,
954 warning,
955 });
956 return true;
957 }
958 }
959
960 false
961 }
962
963 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("maybe_resolve_ident_in_module",
"rustc_resolve::ident", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
::tracing_core::__macro_support::Option::Some(963u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("module")
}> =
::tracing::__macro_support::FieldName::new("module");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ident")
}> =
::tracing::__macro_support::FieldName::new("ident");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ns")
}> =
::tracing::__macro_support::FieldName::new("ns");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("parent_scope")
}> =
::tracing::__macro_support::FieldName::new("parent_scope");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ignore_import")
}> =
::tracing::__macro_support::FieldName::new("ignore_import");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&module)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ns)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_scope)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_import)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Result<Decl<'ra>, Determinacy> =
loop {};
return __tracing_attr_fake_return;
}
{
self.resolve_ident_in_module(module, ident, ns, parent_scope,
None, None, ignore_import)
}
}
}#[instrument(level = "debug", skip(self))]
964 pub(crate) fn maybe_resolve_ident_in_module<'r>(
965 self: CmResolver<'r, 'ra, 'tcx>,
966 module: ModuleOrUniformRoot<'ra>,
967 ident: Ident,
968 ns: Namespace,
969 parent_scope: &ParentScope<'ra>,
970 ignore_import: Option<Import<'ra>>,
971 ) -> Result<Decl<'ra>, Determinacy> {
972 self.resolve_ident_in_module(module, ident, ns, parent_scope, None, None, ignore_import)
973 }
974
975 fn resolve_super_in_module(
976 &self,
977 ident: Ident,
978 module: Option<Module<'ra>>,
979 parent_scope: &ParentScope<'ra>,
980 ) -> Option<Module<'ra>> {
981 let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
982 module
983 .unwrap_or_else(|| self.resolve_self(&mut ctxt, parent_scope.module))
984 .parent
985 .map(|parent| self.resolve_self(&mut ctxt, parent))
986 }
987
988 pub(crate) fn path_root_is_crate_root(&self, ident: Ident) -> bool {
989 ident.name == kw::PathRoot && ident.span.is_rust_2015() && self.tcx.sess.is_rust_2015()
990 }
991
992 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("resolve_ident_in_module",
"rustc_resolve::ident", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
::tracing_core::__macro_support::Option::Some(992u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("module")
}> =
::tracing::__macro_support::FieldName::new("module");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ident")
}> =
::tracing::__macro_support::FieldName::new("ident");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ns")
}> =
::tracing::__macro_support::FieldName::new("ns");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("parent_scope")
}> =
::tracing::__macro_support::FieldName::new("parent_scope");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("finalize")
}> =
::tracing::__macro_support::FieldName::new("finalize");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ignore_decl")
}> =
::tracing::__macro_support::FieldName::new("ignore_decl");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ignore_import")
}> =
::tracing::__macro_support::FieldName::new("ignore_import");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&module)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ns)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_scope)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&finalize)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_decl)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_import)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Result<Decl<'ra>, Determinacy> =
loop {};
return __tracing_attr_fake_return;
}
{
match module {
ModuleOrUniformRoot::Module(module) => {
if ns == TypeNS {
if ident.name == kw::SelfLower {
return Ok(module.self_decl.unwrap());
}
if ident.name == kw::Super &&
let Some(module) =
self.resolve_super_in_module(ident, Some(module),
parent_scope) {
return Ok(module.self_decl.unwrap());
}
}
let (ident_key, def) =
IdentKey::new_adjusted(ident, module.expansion);
let adjusted_parent_scope =
match def {
Some(def) =>
ParentScope {
module: self.expn_def_scope(def),
..*parent_scope
},
None => *parent_scope,
};
self.resolve_ident_in_scope_set_inner(ident_key, ident.span,
ScopeSet::Module(ns, module), &adjusted_parent_scope,
finalize, ignore_decl, ignore_import)
}
ModuleOrUniformRoot::OpenModule(sym) => {
let open_ns_name =
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::{1}", sym.as_str(),
ident.name))
});
let ns_ident =
IdentKey::with_root_ctxt(Symbol::intern(&open_ns_name));
match self.extern_prelude_get_flag(ns_ident, ident.span,
finalize.is_some()) {
Some(decl) => Ok(decl),
None => Err(Determinacy::Determined),
}
}
ModuleOrUniformRoot::ModuleAndExternPrelude(module) =>
self.resolve_ident_in_scope_set(ident,
ScopeSet::ModuleAndExternPrelude(ns, module), parent_scope,
finalize, ignore_decl, ignore_import),
ModuleOrUniformRoot::ExternPrelude => {
if ns != TypeNS {
Err(Determined)
} else {
self.resolve_ident_in_scope_set_inner(IdentKey::new_adjusted(ident,
ExpnId::root()).0, ident.span, ScopeSet::ExternPrelude,
parent_scope, finalize, ignore_decl, ignore_import)
}
}
ModuleOrUniformRoot::CurrentScope => {
if ns == TypeNS {
if ident.name == kw::SelfLower {
let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
let module =
self.resolve_self(&mut ctxt, parent_scope.module);
return Ok(module.self_decl.unwrap());
}
if ident.name == kw::Super &&
let Some(module) =
self.resolve_super_in_module(ident, None, parent_scope) {
return Ok(module.self_decl.unwrap());
}
if ident.name == kw::Crate || ident.name == kw::DollarCrate
|| self.path_root_is_crate_root(ident) {
let module = self.resolve_crate_root(ident);
return Ok(module.self_decl.unwrap());
}
}
self.resolve_ident_in_scope_set(ident, ScopeSet::All(ns),
parent_scope, finalize, ignore_decl, ignore_import)
}
}
}
}
}#[instrument(level = "debug", skip(self))]
993 pub(crate) fn resolve_ident_in_module<'r>(
994 self: CmResolver<'r, 'ra, 'tcx>,
995 module: ModuleOrUniformRoot<'ra>,
996 ident: Ident,
997 ns: Namespace,
998 parent_scope: &ParentScope<'ra>,
999 finalize: Option<Finalize>,
1000 ignore_decl: Option<Decl<'ra>>,
1001 ignore_import: Option<Import<'ra>>,
1002 ) -> Result<Decl<'ra>, Determinacy> {
1003 match module {
1004 ModuleOrUniformRoot::Module(module) => {
1005 if ns == TypeNS {
1006 if ident.name == kw::SelfLower {
1007 return Ok(module.self_decl.unwrap());
1008 }
1009 if ident.name == kw::Super
1010 && let Some(module) =
1011 self.resolve_super_in_module(ident, Some(module), parent_scope)
1012 {
1013 return Ok(module.self_decl.unwrap());
1014 }
1015 }
1016
1017 let (ident_key, def) = IdentKey::new_adjusted(ident, module.expansion);
1018 let adjusted_parent_scope = match def {
1019 Some(def) => ParentScope { module: self.expn_def_scope(def), ..*parent_scope },
1020 None => *parent_scope,
1021 };
1022 self.resolve_ident_in_scope_set_inner(
1023 ident_key,
1024 ident.span,
1025 ScopeSet::Module(ns, module),
1026 &adjusted_parent_scope,
1027 finalize,
1028 ignore_decl,
1029 ignore_import,
1030 )
1031 }
1032 ModuleOrUniformRoot::OpenModule(sym) => {
1033 let open_ns_name = format!("{}::{}", sym.as_str(), ident.name);
1034 let ns_ident = IdentKey::with_root_ctxt(Symbol::intern(&open_ns_name));
1035 match self.extern_prelude_get_flag(ns_ident, ident.span, finalize.is_some()) {
1036 Some(decl) => Ok(decl),
1037 None => Err(Determinacy::Determined),
1038 }
1039 }
1040 ModuleOrUniformRoot::ModuleAndExternPrelude(module) => self.resolve_ident_in_scope_set(
1041 ident,
1042 ScopeSet::ModuleAndExternPrelude(ns, module),
1043 parent_scope,
1044 finalize,
1045 ignore_decl,
1046 ignore_import,
1047 ),
1048 ModuleOrUniformRoot::ExternPrelude => {
1049 if ns != TypeNS {
1050 Err(Determined)
1051 } else {
1052 self.resolve_ident_in_scope_set_inner(
1053 IdentKey::new_adjusted(ident, ExpnId::root()).0,
1054 ident.span,
1055 ScopeSet::ExternPrelude,
1056 parent_scope,
1057 finalize,
1058 ignore_decl,
1059 ignore_import,
1060 )
1061 }
1062 }
1063 ModuleOrUniformRoot::CurrentScope => {
1064 if ns == TypeNS {
1065 if ident.name == kw::SelfLower {
1066 let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
1067 let module = self.resolve_self(&mut ctxt, parent_scope.module);
1068 return Ok(module.self_decl.unwrap());
1069 }
1070 if ident.name == kw::Super
1071 && let Some(module) =
1072 self.resolve_super_in_module(ident, None, parent_scope)
1073 {
1074 return Ok(module.self_decl.unwrap());
1075 }
1076 if ident.name == kw::Crate
1077 || ident.name == kw::DollarCrate
1078 || self.path_root_is_crate_root(ident)
1079 {
1080 let module = self.resolve_crate_root(ident);
1081 return Ok(module.self_decl.unwrap());
1082 }
1083 }
1084
1085 self.resolve_ident_in_scope_set(
1086 ident,
1087 ScopeSet::All(ns),
1088 parent_scope,
1089 finalize,
1090 ignore_decl,
1091 ignore_import,
1092 )
1093 }
1094 }
1095 }
1096
1097 fn resolve_ident_in_extern_module_non_globs_unadjusted<'r>(
1099 mut self: CmResolver<'r, 'ra, 'tcx>,
1100 module: ExternModule<'ra>,
1101 ident: IdentKey,
1102 orig_ident_span: Span,
1103 ns: Namespace,
1104 parent_scope: &ParentScope<'ra>,
1105 shadowing: Shadowing,
1106 finalize: Option<Finalize>,
1107 ignore_decl: Option<Decl<'ra>>,
1110 ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
1111 let key = BindingKey::new(ident, ns);
1112 let resolution =
1113 &*self.resolution(module.to_module(), key).ok_or(ControlFlow::Continue(Determined))?;
1114
1115 let binding = resolution.non_glob_decl.filter(|b| Some(*b) != ignore_decl);
1116
1117 if let Some(finalize) = finalize {
1118 return self.get_mut().finalize_module_binding(
1119 ident,
1120 orig_ident_span,
1121 binding,
1122 parent_scope,
1123 finalize,
1124 shadowing,
1125 );
1126 }
1127
1128 if let Some(binding) = binding {
1130 let accessible = self.is_accessible_from(binding.vis(), parent_scope.module);
1131 return if accessible { Ok(binding) } else { Err(ControlFlow::Break(Determined)) };
1132 }
1133 Err(ControlFlow::Continue(Determined))
1134 }
1135
1136 fn resolve_ident_in_local_module_non_globs_unadjusted<'r>(
1138 mut self: CmResolver<'r, 'ra, 'tcx>,
1139 module: LocalModule<'ra>,
1140 ident: IdentKey,
1141 orig_ident_span: Span,
1142 ns: Namespace,
1143 parent_scope: &ParentScope<'ra>,
1144 shadowing: Shadowing,
1145 finalize: Option<Finalize>,
1146 ignore_decl: Option<Decl<'ra>>,
1149 ignore_import: Option<Import<'ra>>,
1150 ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
1151 let key = BindingKey::new(ident, ns);
1152 let resolution = self.resolution(module.to_module(), key);
1153
1154 let binding =
1155 resolution.as_ref().and_then(|r| r.non_glob_decl).filter(|b| Some(*b) != ignore_decl);
1156
1157 if let Some(finalize) = finalize {
1158 if !!module.has_unexpanded_invocations(&self) {
::core::panicking::panic("assertion failed: !module.has_unexpanded_invocations(&self)")
};assert!(!module.has_unexpanded_invocations(&self));
1160 return self.get_mut().finalize_module_binding(
1161 ident,
1162 orig_ident_span,
1163 binding,
1164 parent_scope,
1165 finalize,
1166 shadowing,
1167 );
1168 }
1169
1170 if let Some(binding) = binding {
1172 let accessible = self.is_accessible_from(binding.vis(), parent_scope.module);
1173 return if accessible { Ok(binding) } else { Err(ControlFlow::Break(Determined)) };
1174 }
1175
1176 if let Some(resolution) = resolution {
1177 let _cycle_guard = cycle_detection::enter_cycle_detector(module, key)
1180 .map_err(|_| ControlFlow::Continue(Determined))?;
1181
1182 if self.reborrow().single_import_can_define_name(
1184 &resolution,
1185 None,
1186 ns,
1187 ignore_import,
1188 ignore_decl,
1189 parent_scope,
1190 ) {
1191 return Err(ControlFlow::Break(Undetermined));
1192 }
1193 }
1194
1195 if module.has_unexpanded_invocations(&self) {
1197 return Err(ControlFlow::Continue(Undetermined));
1198 }
1199
1200 Err(ControlFlow::Continue(Determined))
1202 }
1203
1204 fn resolve_ident_in_module_globs_unadjusted<'r>(
1206 mut self: CmResolver<'r, 'ra, 'tcx>,
1207 module: LocalModule<'ra>,
1208 ident: IdentKey,
1209 orig_ident_span: Span,
1210 ns: Namespace,
1211 parent_scope: &ParentScope<'ra>,
1212 shadowing: Shadowing,
1213 finalize: Option<Finalize>,
1214 ignore_decl: Option<Decl<'ra>>,
1215 ignore_import: Option<Import<'ra>>,
1216 ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
1217 let key = BindingKey::new(ident, ns);
1218 let resolution = self.resolution(module.to_module(), key);
1219
1220 let binding =
1221 resolution.as_ref().and_then(|r| r.glob_decl).filter(|b| Some(*b) != ignore_decl);
1222
1223 if let Some(finalize) = finalize {
1224 if !!module.has_unexpanded_invocations(&self) {
::core::panicking::panic("assertion failed: !module.has_unexpanded_invocations(&self)")
};assert!(!module.has_unexpanded_invocations(&self));
1226 return self.get_mut().finalize_module_binding(
1227 ident,
1228 orig_ident_span,
1229 binding,
1230 parent_scope,
1231 finalize,
1232 shadowing,
1233 );
1234 }
1235
1236 let _cycle_guard = cycle_detection::enter_cycle_detector(module, key)
1239 .map_err(|_| ControlFlow::Continue(Determined))?;
1240
1241 if let Some(resolution) = resolution {
1244 if self.reborrow().single_import_can_define_name(
1245 &resolution,
1246 binding,
1247 ns,
1248 ignore_import,
1249 ignore_decl,
1250 parent_scope,
1251 ) {
1252 return Err(ControlFlow::Break(Undetermined));
1253 }
1254 }
1255
1256 if let Some(binding) = binding {
1269 return if binding.determined(&self)
1270 || ns == MacroNS
1271 || shadowing == Shadowing::Restricted
1272 {
1273 let accessible = self.is_accessible_from(binding.vis(), parent_scope.module);
1274 if accessible { Ok(binding) } else { Err(ControlFlow::Break(Determined)) }
1275 } else {
1276 Err(ControlFlow::Break(Undetermined))
1277 };
1278 }
1279
1280 if module.has_unexpanded_invocations(&self) {
1288 return Err(ControlFlow::Continue(Undetermined));
1289 }
1290
1291 for glob_import in module.globs.borrow_checked(&self).iter() {
1294 if ignore_import == Some(*glob_import) {
1295 continue;
1296 }
1297 if !self.is_accessible_from(glob_import.vis, parent_scope.module) {
1298 continue;
1299 }
1300 let module = match glob_import.imported_module.get() {
1301 Some(ModuleOrUniformRoot::Module(module)) => module,
1302 Some(_) => continue,
1303 None => return Err(ControlFlow::Continue(Undetermined)),
1304 };
1305 let tmp_parent_scope;
1306 let (mut adjusted_parent_scope, mut adjusted_ident) = (parent_scope, ident);
1307 match adjusted_ident
1308 .ctxt
1309 .update_unchecked(|ctxt| ctxt.glob_adjust(module.expansion, glob_import.span))
1310 {
1311 Some(Some(def)) => {
1312 tmp_parent_scope =
1313 ParentScope { module: self.expn_def_scope(def), ..*parent_scope };
1314 adjusted_parent_scope = &tmp_parent_scope;
1315 }
1316 Some(None) => {}
1317 None => continue,
1318 };
1319 let result = self.reborrow().resolve_ident_in_scope_set_inner(
1320 adjusted_ident,
1321 orig_ident_span,
1322 ScopeSet::Module(ns, module),
1323 adjusted_parent_scope,
1324 None,
1325 ignore_decl,
1326 ignore_import,
1327 );
1328
1329 match result {
1330 Err(Determined) => continue,
1331 Ok(binding)
1332 if !self.is_accessible_from(binding.vis(), glob_import.parent_scope.module) =>
1333 {
1334 continue;
1335 }
1336 Ok(_) | Err(Undetermined) => return Err(ControlFlow::Continue(Undetermined)),
1337 }
1338 }
1339
1340 Err(ControlFlow::Continue(Determined))
1342 }
1343
1344 fn finalize_module_binding(
1345 &mut self,
1346 ident: IdentKey,
1347 orig_ident_span: Span,
1348 binding: Option<Decl<'ra>>,
1349 parent_scope: &ParentScope<'ra>,
1350 finalize: Finalize,
1351 shadowing: Shadowing,
1352 ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
1353 let Finalize { path_span, report_private, used, root_span, .. } = finalize;
1354
1355 let Some(binding) = binding else {
1356 return Err(ControlFlow::Continue(Determined));
1357 };
1358
1359 let ident = ident.orig(orig_ident_span);
1360 if !self.is_accessible_from(binding.vis(), parent_scope.module) {
1361 if report_private {
1362 self.privacy_errors.push(PrivacyError {
1363 ident,
1364 decl: binding,
1365 dedup_span: path_span,
1366 outermost_res: None,
1367 source: None,
1368 parent_scope: *parent_scope,
1369 single_nested: path_span != root_span,
1370 });
1371 } else {
1372 return Err(ControlFlow::Break(Determined));
1373 }
1374 }
1375
1376 if shadowing == Shadowing::Unrestricted
1377 && binding.expansion != LocalExpnId::ROOT
1378 && let DeclKind::Import { import, .. } = binding.kind
1379 && #[allow(non_exhaustive_omitted_patterns)] match import.kind {
ImportKind::MacroExport => true,
_ => false,
}matches!(import.kind, ImportKind::MacroExport)
1380 {
1381 self.macro_expanded_macro_export_errors.insert((path_span, binding.span));
1382 }
1383
1384 self.record_use(ident, binding, used);
1385 return Ok(binding);
1386 }
1387
1388 fn single_import_can_define_name<'r>(
1391 mut self: CmResolver<'r, 'ra, 'tcx>,
1392 resolution: &NameResolution<'ra>,
1393 binding: Option<Decl<'ra>>,
1394 ns: Namespace,
1395 ignore_import: Option<Import<'ra>>,
1396 ignore_decl: Option<Decl<'ra>>,
1397 parent_scope: &ParentScope<'ra>,
1398 ) -> bool {
1399 for single_import in &resolution.single_imports {
1400 if let Some(decl) = resolution.non_glob_decl
1401 && let DeclKind::Import { import, .. } = decl.kind
1402 && import == *single_import
1403 {
1404 continue;
1407 }
1408 if ignore_import == Some(*single_import) {
1409 continue;
1410 }
1411 if !self.is_accessible_from(single_import.vis, parent_scope.module) {
1412 continue;
1413 }
1414 if let Some(ignored) = ignore_decl
1415 && let DeclKind::Import { import, .. } = ignored.kind
1416 && import == *single_import
1417 {
1418 continue;
1419 }
1420
1421 let Some(module) = single_import.imported_module.get() else {
1422 return true;
1423 };
1424 let ImportKind::Single { source, target, decls, .. } = &single_import.kind else {
1425 ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1426 };
1427 if source != target {
1428 if decls.iter().all(|d| d.get().decl().is_none()) {
1429 return true;
1430 } else if decls[ns].get().decl().is_none() && binding.is_some() {
1431 return true;
1432 }
1433 }
1434
1435 match self.reborrow().resolve_ident_in_module(
1436 module,
1437 *source,
1438 ns,
1439 &single_import.parent_scope,
1440 None,
1441 ignore_decl,
1442 None,
1443 ) {
1444 Err(Determined) => continue,
1445 Ok(binding)
1446 if !self
1447 .is_accessible_from(binding.vis(), single_import.parent_scope.module) =>
1448 {
1449 continue;
1450 }
1451 Ok(_) | Err(Undetermined) => return true,
1452 }
1453 }
1454
1455 false
1456 }
1457
1458 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("validate_res_from_ribs",
"rustc_resolve::ident", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
::tracing_core::__macro_support::Option::Some(1459u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("rib_index")
}> =
::tracing::__macro_support::FieldName::new("rib_index");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("rib_ident")
}> =
::tracing::__macro_support::FieldName::new("rib_ident");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("res")
}> =
::tracing::__macro_support::FieldName::new("res");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("finalize")
}> =
::tracing::__macro_support::FieldName::new("finalize");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("original_rib_ident_def")
}> =
::tracing::__macro_support::FieldName::new("original_rib_ident_def");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("diag_metadata")
}> =
::tracing::__macro_support::FieldName::new("diag_metadata");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&rib_index
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&rib_ident)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&finalize)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&original_rib_ident_def)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&diag_metadata)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Res = loop {};
return __tracing_attr_fake_return;
}
{
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/ident.rs:1470",
"rustc_resolve::ident", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
::tracing_core::__macro_support::Option::Some(1470u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("validate_res_from_ribs({0:?})",
res) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let ribs = &all_ribs[rib_index + 1..];
if let RibKind::ForwardGenericParamBan(reason) =
all_ribs[rib_index].kind {
if let Some(span) = finalize {
let res_error =
if rib_ident.name == kw::SelfUpper {
ResolutionError::ForwardDeclaredSelf(reason)
} else {
ResolutionError::ForwardDeclaredGenericParam(rib_ident.name,
reason)
};
self.report_error(span, res_error);
}
{
match (&res, &Res::Err) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
return Res::Err;
}
match res {
Res::Local(_) => {
use ResolutionError::*;
let mut res_err = None;
for rib in ribs {
match rib.kind {
RibKind::Normal | RibKind::Block(..) |
RibKind::FnOrCoroutine | RibKind::Module(..) |
RibKind::MacroDefinition(..) |
RibKind::ForwardGenericParamBan(_) => {}
RibKind::Item(..) | RibKind::AssocItem => {
if let Some(span) = finalize {
res_err =
Some((span, CannotCaptureDynamicEnvironmentInFnItem));
}
}
RibKind::ConstantItem(_, item) => {
if let Some(span) = finalize {
let (span, resolution_error) =
match item {
None if rib_ident.name == kw::SelfLower => {
(span, LowercaseSelf)
}
None => {
let sm = self.tcx.sess.source_map();
let type_span =
match sm.span_followed_by(original_rib_ident_def.span, ":")
{
None => { Some(original_rib_ident_def.span.shrink_to_hi()) }
Some(_) => None,
};
(rib_ident.span,
AttemptToUseNonConstantValueInConstant {
ident: original_rib_ident_def,
suggestion: "const",
current: "let",
type_span,
})
}
Some((ident, kind)) =>
(span,
AttemptToUseNonConstantValueInConstant {
ident,
suggestion: "let",
current: kind.as_str(),
type_span: None,
}),
};
self.report_error(span, resolution_error);
}
return Res::Err;
}
RibKind::ConstParamTy => {
if let Some(span) = finalize {
self.report_error(span,
ParamInTyOfConstParam { name: rib_ident.name });
}
return Res::Err;
}
RibKind::InlineAsmSym => {
if let Some(span) = finalize {
self.report_error(span, InvalidAsmSym);
}
return Res::Err;
}
}
}
if let Some((span, res_err)) = res_err {
self.report_error(span, res_err);
return Res::Err;
}
}
Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } |
Res::SelfTyAlias { .. } => {
for rib in ribs {
let (has_generic_params, def_kind) =
match rib.kind {
RibKind::Normal | RibKind::Block(..) |
RibKind::FnOrCoroutine | RibKind::Module(..) |
RibKind::MacroDefinition(..) | RibKind::InlineAsmSym |
RibKind::AssocItem | RibKind::ForwardGenericParamBan(_) => {
continue;
}
RibKind::ConstParamTy => {
if !self.features.generic_const_parameter_types() {
if let Some(span) = finalize {
self.report_error(span,
ResolutionError::ParamInTyOfConstParam {
name: rib_ident.name,
});
}
return Res::Err;
} else { continue; }
}
RibKind::ConstantItem(trivial, _) => {
if let ConstantHasGenerics::No(cause) = trivial &&
!#[allow(non_exhaustive_omitted_patterns)] match res {
Res::SelfTyAlias { .. } => true,
_ => false,
} {
if let Some(span) = finalize {
let error =
match cause {
NoConstantGenericsReason::IsEnumDiscriminant => {
ResolutionError::ParamInEnumDiscriminant {
name: rib_ident.name,
param_kind: ParamKindInEnumDiscriminant::Type,
}
}
NoConstantGenericsReason::NonTrivialConstArg => {
ResolutionError::ParamInNonTrivialAnonConst {
is_gca: self.features.generic_const_args(),
name: rib_ident.name,
param_kind: ParamKindInNonTrivialAnonConst::Type,
}
}
};
let _: ErrorGuaranteed = self.report_error(span, error);
}
return Res::Err;
}
continue;
}
RibKind::Item(has_generic_params, def_kind) => {
(has_generic_params, def_kind)
}
};
if let Some(span) = finalize {
let item =
if let Some(diag_metadata) = diag_metadata &&
let Some(current_item) = diag_metadata.current_item {
let label_span =
current_item.kind.ident().map(|i|
i.span).unwrap_or(current_item.span);
Some((label_span, current_item.span,
current_item.kind.clone()))
} else { None };
self.report_error(span,
ResolutionError::GenericParamsFromOuterItem {
outer_res: res,
has_generic_params,
def_kind,
inner_item: item,
current_self_ty: diag_metadata.and_then(|m|
m.current_self_type.as_ref()).and_then(|ty|
{
self.tcx.sess.source_map().span_to_snippet(ty.span).ok()
}),
});
}
return Res::Err;
}
}
Res::Def(DefKind::ConstParam, _) => {
for rib in ribs {
let (has_generic_params, def_kind) =
match rib.kind {
RibKind::Normal | RibKind::Block(..) |
RibKind::FnOrCoroutine | RibKind::Module(..) |
RibKind::MacroDefinition(..) | RibKind::InlineAsmSym |
RibKind::AssocItem | RibKind::ForwardGenericParamBan(_) =>
continue,
RibKind::ConstParamTy => {
if !self.features.generic_const_parameter_types() {
if let Some(span) = finalize {
self.report_error(span,
ResolutionError::ParamInTyOfConstParam {
name: rib_ident.name,
});
}
return Res::Err;
} else { continue; }
}
RibKind::ConstantItem(trivial, _) => {
if let ConstantHasGenerics::No(cause) = trivial {
if let Some(span) = finalize {
let error =
match cause {
NoConstantGenericsReason::IsEnumDiscriminant => {
ResolutionError::ParamInEnumDiscriminant {
name: rib_ident.name,
param_kind: ParamKindInEnumDiscriminant::Const,
}
}
NoConstantGenericsReason::NonTrivialConstArg => {
ResolutionError::ParamInNonTrivialAnonConst {
is_gca: self.features.generic_const_args(),
name: rib_ident.name,
param_kind: ParamKindInNonTrivialAnonConst::Const {
name: rib_ident.name,
},
}
}
};
self.report_error(span, error);
}
return Res::Err;
}
continue;
}
RibKind::Item(has_generic_params, def_kind) => {
(has_generic_params, def_kind)
}
};
if let Some(span) = finalize {
let item =
if let Some(diag_metadata) = diag_metadata &&
let Some(current_item) = diag_metadata.current_item {
let label_span =
current_item.kind.ident().map(|i|
i.span).unwrap_or(current_item.span);
Some((label_span, current_item.span,
current_item.kind.clone()))
} else { None };
self.report_error(span,
ResolutionError::GenericParamsFromOuterItem {
outer_res: res,
has_generic_params,
def_kind,
inner_item: item,
current_self_ty: diag_metadata.and_then(|m|
m.current_self_type.as_ref()).and_then(|ty|
{
self.tcx.sess.source_map().span_to_snippet(ty.span).ok()
}),
});
}
return Res::Err;
}
}
_ => {}
}
res
}
}
}#[instrument(level = "debug", skip(self, all_ribs))]
1460 fn validate_res_from_ribs(
1461 &self,
1462 rib_index: usize,
1463 rib_ident: Ident,
1464 res: Res,
1465 finalize: Option<Span>,
1466 original_rib_ident_def: Ident,
1467 all_ribs: &[Rib<'ra>],
1468 diag_metadata: Option<&DiagMetadata<'_>>,
1469 ) -> Res {
1470 debug!("validate_res_from_ribs({:?})", res);
1471 let ribs = &all_ribs[rib_index + 1..];
1472
1473 if let RibKind::ForwardGenericParamBan(reason) = all_ribs[rib_index].kind {
1476 if let Some(span) = finalize {
1477 let res_error = if rib_ident.name == kw::SelfUpper {
1478 ResolutionError::ForwardDeclaredSelf(reason)
1479 } else {
1480 ResolutionError::ForwardDeclaredGenericParam(rib_ident.name, reason)
1481 };
1482 self.report_error(span, res_error);
1483 }
1484 assert_eq!(res, Res::Err);
1485 return Res::Err;
1486 }
1487
1488 match res {
1489 Res::Local(_) => {
1490 use ResolutionError::*;
1491 let mut res_err = None;
1492
1493 for rib in ribs {
1494 match rib.kind {
1495 RibKind::Normal
1496 | RibKind::Block(..)
1497 | RibKind::FnOrCoroutine
1498 | RibKind::Module(..)
1499 | RibKind::MacroDefinition(..)
1500 | RibKind::ForwardGenericParamBan(_) => {
1501 }
1503 RibKind::Item(..) | RibKind::AssocItem => {
1504 if let Some(span) = finalize {
1508 res_err = Some((span, CannotCaptureDynamicEnvironmentInFnItem));
1513 }
1514 }
1515 RibKind::ConstantItem(_, item) => {
1516 if let Some(span) = finalize {
1518 let (span, resolution_error) = match item {
1519 None if rib_ident.name == kw::SelfLower => {
1520 (span, LowercaseSelf)
1521 }
1522 None => {
1523 let sm = self.tcx.sess.source_map();
1529 let type_span = match sm
1530 .span_followed_by(original_rib_ident_def.span, ":")
1531 {
1532 None => {
1533 Some(original_rib_ident_def.span.shrink_to_hi())
1534 }
1535 Some(_) => None,
1536 };
1537 (
1538 rib_ident.span,
1539 AttemptToUseNonConstantValueInConstant {
1540 ident: original_rib_ident_def,
1541 suggestion: "const",
1542 current: "let",
1543 type_span,
1544 },
1545 )
1546 }
1547 Some((ident, kind)) => (
1548 span,
1549 AttemptToUseNonConstantValueInConstant {
1550 ident,
1551 suggestion: "let",
1552 current: kind.as_str(),
1553 type_span: None,
1554 },
1555 ),
1556 };
1557 self.report_error(span, resolution_error);
1558 }
1559 return Res::Err;
1560 }
1561 RibKind::ConstParamTy => {
1562 if let Some(span) = finalize {
1563 self.report_error(
1564 span,
1565 ParamInTyOfConstParam { name: rib_ident.name },
1566 );
1567 }
1568 return Res::Err;
1569 }
1570 RibKind::InlineAsmSym => {
1571 if let Some(span) = finalize {
1572 self.report_error(span, InvalidAsmSym);
1573 }
1574 return Res::Err;
1575 }
1576 }
1577 }
1578 if let Some((span, res_err)) = res_err {
1579 self.report_error(span, res_err);
1580 return Res::Err;
1581 }
1582 }
1583 Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } => {
1584 for rib in ribs {
1585 let (has_generic_params, def_kind) = match rib.kind {
1586 RibKind::Normal
1587 | RibKind::Block(..)
1588 | RibKind::FnOrCoroutine
1589 | RibKind::Module(..)
1590 | RibKind::MacroDefinition(..)
1591 | RibKind::InlineAsmSym
1592 | RibKind::AssocItem
1593 | RibKind::ForwardGenericParamBan(_) => {
1594 continue;
1596 }
1597
1598 RibKind::ConstParamTy => {
1599 if !self.features.generic_const_parameter_types() {
1600 if let Some(span) = finalize {
1601 self.report_error(
1602 span,
1603 ResolutionError::ParamInTyOfConstParam {
1604 name: rib_ident.name,
1605 },
1606 );
1607 }
1608 return Res::Err;
1609 } else {
1610 continue;
1611 }
1612 }
1613
1614 RibKind::ConstantItem(trivial, _) => {
1615 if let ConstantHasGenerics::No(cause) = trivial
1616 && !matches!(res, Res::SelfTyAlias { .. })
1617 {
1618 if let Some(span) = finalize {
1619 let error = match cause {
1620 NoConstantGenericsReason::IsEnumDiscriminant => {
1621 ResolutionError::ParamInEnumDiscriminant {
1622 name: rib_ident.name,
1623 param_kind: ParamKindInEnumDiscriminant::Type,
1624 }
1625 }
1626 NoConstantGenericsReason::NonTrivialConstArg => {
1627 ResolutionError::ParamInNonTrivialAnonConst {
1628 is_gca: self.features.generic_const_args(),
1629 name: rib_ident.name,
1630 param_kind: ParamKindInNonTrivialAnonConst::Type,
1631 }
1632 }
1633 };
1634 let _: ErrorGuaranteed = self.report_error(span, error);
1635 }
1636
1637 return Res::Err;
1638 }
1639
1640 continue;
1641 }
1642
1643 RibKind::Item(has_generic_params, def_kind) => {
1645 (has_generic_params, def_kind)
1646 }
1647 };
1648
1649 if let Some(span) = finalize {
1650 let item = if let Some(diag_metadata) = diag_metadata
1651 && let Some(current_item) = diag_metadata.current_item
1652 {
1653 let label_span = current_item
1654 .kind
1655 .ident()
1656 .map(|i| i.span)
1657 .unwrap_or(current_item.span);
1658 Some((label_span, current_item.span, current_item.kind.clone()))
1659 } else {
1660 None
1661 };
1662 self.report_error(
1663 span,
1664 ResolutionError::GenericParamsFromOuterItem {
1665 outer_res: res,
1666 has_generic_params,
1667 def_kind,
1668 inner_item: item,
1669 current_self_ty: diag_metadata
1670 .and_then(|m| m.current_self_type.as_ref())
1671 .and_then(|ty| {
1672 self.tcx.sess.source_map().span_to_snippet(ty.span).ok()
1673 }),
1674 },
1675 );
1676 }
1677 return Res::Err;
1678 }
1679 }
1680 Res::Def(DefKind::ConstParam, _) => {
1681 for rib in ribs {
1682 let (has_generic_params, def_kind) = match rib.kind {
1683 RibKind::Normal
1684 | RibKind::Block(..)
1685 | RibKind::FnOrCoroutine
1686 | RibKind::Module(..)
1687 | RibKind::MacroDefinition(..)
1688 | RibKind::InlineAsmSym
1689 | RibKind::AssocItem
1690 | RibKind::ForwardGenericParamBan(_) => continue,
1691
1692 RibKind::ConstParamTy => {
1693 if !self.features.generic_const_parameter_types() {
1694 if let Some(span) = finalize {
1695 self.report_error(
1696 span,
1697 ResolutionError::ParamInTyOfConstParam {
1698 name: rib_ident.name,
1699 },
1700 );
1701 }
1702 return Res::Err;
1703 } else {
1704 continue;
1705 }
1706 }
1707
1708 RibKind::ConstantItem(trivial, _) => {
1709 if let ConstantHasGenerics::No(cause) = trivial {
1710 if let Some(span) = finalize {
1711 let error = match cause {
1712 NoConstantGenericsReason::IsEnumDiscriminant => {
1713 ResolutionError::ParamInEnumDiscriminant {
1714 name: rib_ident.name,
1715 param_kind: ParamKindInEnumDiscriminant::Const,
1716 }
1717 }
1718 NoConstantGenericsReason::NonTrivialConstArg => {
1719 ResolutionError::ParamInNonTrivialAnonConst {
1720 is_gca: self.features.generic_const_args(),
1721 name: rib_ident.name,
1722 param_kind: ParamKindInNonTrivialAnonConst::Const {
1723 name: rib_ident.name,
1724 },
1725 }
1726 }
1727 };
1728 self.report_error(span, error);
1729 }
1730
1731 return Res::Err;
1732 }
1733
1734 continue;
1735 }
1736
1737 RibKind::Item(has_generic_params, def_kind) => {
1738 (has_generic_params, def_kind)
1739 }
1740 };
1741
1742 if let Some(span) = finalize {
1744 let item = if let Some(diag_metadata) = diag_metadata
1745 && let Some(current_item) = diag_metadata.current_item
1746 {
1747 let label_span = current_item
1748 .kind
1749 .ident()
1750 .map(|i| i.span)
1751 .unwrap_or(current_item.span);
1752 Some((label_span, current_item.span, current_item.kind.clone()))
1753 } else {
1754 None
1755 };
1756 self.report_error(
1757 span,
1758 ResolutionError::GenericParamsFromOuterItem {
1759 outer_res: res,
1760 has_generic_params,
1761 def_kind,
1762 inner_item: item,
1763 current_self_ty: diag_metadata
1764 .and_then(|m| m.current_self_type.as_ref())
1765 .and_then(|ty| {
1766 self.tcx.sess.source_map().span_to_snippet(ty.span).ok()
1767 }),
1768 },
1769 );
1770 }
1771 return Res::Err;
1772 }
1773 }
1774 _ => {}
1775 }
1776
1777 res
1778 }
1779
1780 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("maybe_resolve_path",
"rustc_resolve::ident", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
::tracing_core::__macro_support::Option::Some(1780u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("path")
}> =
::tracing::__macro_support::FieldName::new("path");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("opt_ns")
}> =
::tracing::__macro_support::FieldName::new("opt_ns");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("parent_scope")
}> =
::tracing::__macro_support::FieldName::new("parent_scope");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ignore_import")
}> =
::tracing::__macro_support::FieldName::new("ignore_import");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&opt_ns)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_scope)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_import)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: PathResult<'ra> = loop {};
return __tracing_attr_fake_return;
}
{
self.resolve_path_with_ribs(path, opt_ns, parent_scope, None,
None, None, None, ignore_import, None)
}
}
}#[instrument(level = "debug", skip(self))]
1781 pub(crate) fn maybe_resolve_path<'r>(
1782 self: CmResolver<'r, 'ra, 'tcx>,
1783 path: &[Segment],
1784 opt_ns: Option<Namespace>, parent_scope: &ParentScope<'ra>,
1786 ignore_import: Option<Import<'ra>>,
1787 ) -> PathResult<'ra> {
1788 self.resolve_path_with_ribs(
1789 path,
1790 opt_ns,
1791 parent_scope,
1792 None,
1793 None,
1794 None,
1795 None,
1796 ignore_import,
1797 None,
1798 )
1799 }
1800 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("resolve_path",
"rustc_resolve::ident", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
::tracing_core::__macro_support::Option::Some(1800u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("path")
}> =
::tracing::__macro_support::FieldName::new("path");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("opt_ns")
}> =
::tracing::__macro_support::FieldName::new("opt_ns");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("parent_scope")
}> =
::tracing::__macro_support::FieldName::new("parent_scope");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("finalize")
}> =
::tracing::__macro_support::FieldName::new("finalize");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ignore_decl")
}> =
::tracing::__macro_support::FieldName::new("ignore_decl");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ignore_import")
}> =
::tracing::__macro_support::FieldName::new("ignore_import");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&opt_ns)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_scope)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&finalize)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_decl)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_import)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: PathResult<'ra> = loop {};
return __tracing_attr_fake_return;
}
{
self.resolve_path_with_ribs(path, opt_ns, parent_scope, None,
finalize, None, ignore_decl, ignore_import, None)
}
}
}#[instrument(level = "debug", skip(self))]
1801 pub(crate) fn resolve_path<'r>(
1802 self: CmResolver<'r, 'ra, 'tcx>,
1803 path: &[Segment],
1804 opt_ns: Option<Namespace>, parent_scope: &ParentScope<'ra>,
1806 finalize: Option<Finalize>,
1807 ignore_decl: Option<Decl<'ra>>,
1808 ignore_import: Option<Import<'ra>>,
1809 ) -> PathResult<'ra> {
1810 self.resolve_path_with_ribs(
1811 path,
1812 opt_ns,
1813 parent_scope,
1814 None,
1815 finalize,
1816 None,
1817 ignore_decl,
1818 ignore_import,
1819 None,
1820 )
1821 }
1822
1823 pub(crate) fn resolve_path_with_ribs<'r>(
1824 mut self: CmResolver<'r, 'ra, 'tcx>,
1825 path: &[Segment],
1826 opt_ns: Option<Namespace>, parent_scope: &ParentScope<'ra>,
1828 source: Option<PathSource<'_, '_, '_>>,
1829 finalize: Option<Finalize>,
1830 ribs: Option<&PerNS<Vec<Rib<'ra>>>>,
1831 ignore_decl: Option<Decl<'ra>>,
1832 ignore_import: Option<Import<'ra>>,
1833 diag_metadata: Option<&DiagMetadata<'_>>,
1834 ) -> PathResult<'ra> {
1835 let mut module = None;
1836 let mut module_had_parse_errors = !self.mods_with_parse_errors.is_empty()
1837 && self
1838 .mods_with_parse_errors
1839 .contains(&parent_scope.module.nearest_parent_mod().to_def_id());
1840 let mut allow_super = true;
1841 let mut second_binding = None;
1842
1843 let privacy_errors_len = self.privacy_errors.len();
1845 fn record_segment_res<'r, 'ra, 'tcx>(
1846 mut this: CmResolver<'r, 'ra, 'tcx>,
1847 finalize: Option<Finalize>,
1848 res: Res,
1849 id: Option<NodeId>,
1850 ) {
1851 if finalize.is_some()
1852 && let Some(id) = id
1853 && !this.partial_res_map.contains_key(&id)
1854 {
1855 if !(id != ast::DUMMY_NODE_ID) {
{
::core::panicking::panic_fmt(format_args!("Trying to resolve dummy id"));
}
};assert!(id != ast::DUMMY_NODE_ID, "Trying to resolve dummy id");
1856 this.get_mut().record_partial_res(id, PartialRes::new(res));
1857 }
1858 }
1859
1860 for (segment_idx, &Segment { ident, id, .. }) in path.iter().enumerate() {
1861 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/ident.rs:1861",
"rustc_resolve::ident", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
::tracing_core::__macro_support::Option::Some(1861u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolve_path ident {0} {1:?} {2:?}",
segment_idx, ident, id) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("resolve_path ident {} {:?} {:?}", segment_idx, ident, id);
1862
1863 let is_last = segment_idx + 1 == path.len();
1864 let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
1865 let name = ident.name;
1866
1867 allow_super &= ns == TypeNS && (name == kw::SelfLower || name == kw::Super);
1868
1869 if ns == TypeNS {
1870 if allow_super && name == kw::Super {
1871 let parent = if segment_idx == 0 {
1872 self.resolve_super_in_module(ident, None, parent_scope)
1873 } else if let Some(ModuleOrUniformRoot::Module(module)) = module {
1874 self.resolve_super_in_module(ident, Some(module), parent_scope)
1875 } else {
1876 None
1877 };
1878 if let Some(parent) = parent {
1879 module = Some(ModuleOrUniformRoot::Module(parent));
1880 continue;
1881 }
1882 let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
1883 let current_module = self.resolve_self(&mut ctxt, parent_scope.module);
1884 let current_module_path = module_to_string(current_module)
1885 .map_or_else(|| "crate".to_string(), |path| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("crate::{0}", path))
})format!("crate::{path}"));
1886 return PathResult::failed(
1887 ident,
1888 false,
1889 finalize.is_some(),
1890 module_had_parse_errors,
1891 module,
1892 || {
1893 (
1894 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("too many leading `super` keywords within `{0}`",
current_module_path))
})format!(
1895 "too many leading `super` keywords within `{current_module_path}`"
1896 ),
1897 "this `super` would go above the crate root".to_string(),
1898 None,
1899 None,
1900 )
1901 },
1902 );
1903 }
1904 if segment_idx == 0 {
1905 if name == kw::SelfLower {
1906 let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
1907 let self_mod = self.resolve_self(&mut ctxt, parent_scope.module);
1908 if let Some(res) = self_mod.res() {
1909 record_segment_res(self.reborrow(), finalize, res, id);
1910 }
1911 module = Some(ModuleOrUniformRoot::Module(self_mod));
1912 continue;
1913 }
1914 if name == kw::PathRoot && ident.span.at_least_rust_2018() {
1915 module = Some(ModuleOrUniformRoot::ExternPrelude);
1916 continue;
1917 }
1918 if name == kw::PathRoot
1919 && ident.span.is_rust_2015()
1920 && self.tcx.sess.at_least_rust_2018()
1921 {
1922 let crate_root = self.resolve_crate_root(ident);
1924 module = Some(ModuleOrUniformRoot::ModuleAndExternPrelude(crate_root));
1925 continue;
1926 }
1927 if name == kw::PathRoot || name == kw::Crate || name == kw::DollarCrate {
1928 let crate_root = self.resolve_crate_root(ident);
1930 if let Some(res) = crate_root.res() {
1931 record_segment_res(self.reborrow(), finalize, res, id);
1932 }
1933 module = Some(ModuleOrUniformRoot::Module(crate_root));
1934 continue;
1935 }
1936 }
1937 }
1938
1939 let allow_trailing_self = is_last && name == kw::SelfLower;
1940
1941 if ident.is_path_segment_keyword() && segment_idx != 0 && !allow_trailing_self {
1943 return PathResult::failed(
1944 ident,
1945 false,
1946 finalize.is_some(),
1947 module_had_parse_errors,
1948 module,
1949 || {
1950 let name_str = if name == kw::PathRoot {
1951 "the crate root".to_string()
1952 } else {
1953 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", name))
})format!("`{name}`")
1954 };
1955 let (message, label) = if segment_idx == 1
1956 && path[0].ident.name == kw::PathRoot
1957 {
1958 (
1959 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("global paths cannot start with {0}",
name_str))
})format!("global paths cannot start with {name_str}"),
1960 "cannot start with this".to_string(),
1961 )
1962 } else if name == kw::SelfLower {
1963 (
1964 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`self` in paths can only be used in start position or last position"))
})format!(
1965 "`self` in paths can only be used in start position or last position"
1966 ),
1967 "can only be used in path start position or last position"
1968 .to_string(),
1969 )
1970 } else {
1971 (
1972 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} in paths can only be used in start position",
name_str))
})format!("{name_str} in paths can only be used in start position"),
1973 "can only be used in path start position".to_string(),
1974 )
1975 };
1976 (message, label, None, None)
1977 },
1978 );
1979 }
1980
1981 let binding = if let Some(module) = module {
1982 self.reborrow().resolve_ident_in_module(
1983 module,
1984 ident,
1985 ns,
1986 parent_scope,
1987 finalize,
1988 ignore_decl,
1989 ignore_import,
1990 )
1991 } else if let Some(ribs) = ribs
1992 && let Some(TypeNS | ValueNS) = opt_ns
1993 {
1994 if !ignore_import.is_none() {
::core::panicking::panic("assertion failed: ignore_import.is_none()")
};assert!(ignore_import.is_none());
1995 match self.get_mut().resolve_ident_in_lexical_scope(
1996 ident,
1997 ns,
1998 parent_scope,
1999 finalize,
2000 &ribs[ns],
2001 ignore_decl,
2002 diag_metadata,
2003 ) {
2004 Some(LateDecl::Decl(binding)) => Ok(binding),
2006 Some(LateDecl::RibDef(res)) => {
2008 record_segment_res(self.reborrow(), finalize, res, id);
2009 return PathResult::NonModule(PartialRes::with_unresolved_segments(
2010 res,
2011 path.len() - 1,
2012 ));
2013 }
2014 _ => Err(Determinacy::determined(finalize.is_some())),
2015 }
2016 } else {
2017 self.reborrow().resolve_ident_in_scope_set(
2018 ident,
2019 ScopeSet::All(ns),
2020 parent_scope,
2021 finalize,
2022 ignore_decl,
2023 ignore_import,
2024 )
2025 };
2026
2027 match binding {
2028 Ok(binding) => {
2029 if segment_idx == 1 {
2030 second_binding = Some(binding);
2031 }
2032 let res = binding.res();
2033
2034 if finalize.is_some() {
2038 for error in &mut self.get_mut().privacy_errors[privacy_errors_len..] {
2039 error.outermost_res = Some((res, ident));
2040 error.source = match source {
2041 Some(PathSource::Struct(Some(expr)))
2042 | Some(PathSource::Expr(Some(expr))) => Some(expr.clone()),
2043 _ => None,
2044 };
2045 }
2046 }
2047
2048 let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(res);
2049 if let Res::OpenMod(sym) = binding.res() {
2050 module = Some(ModuleOrUniformRoot::OpenModule(sym));
2051 record_segment_res(self.reborrow(), finalize, res, id);
2052 } else if let Some(def_id) = binding.res().module_like_def_id() {
2053 if self.mods_with_parse_errors.contains(&def_id) {
2054 module_had_parse_errors = true;
2055 }
2056 module = Some(ModuleOrUniformRoot::Module(self.expect_module(def_id)));
2057 record_segment_res(self.reborrow(), finalize, res, id);
2058 } else if res == Res::ToolMod && !is_last && opt_ns.is_some() {
2059 if binding.is_import() {
2060 self.dcx().emit_err(diagnostics::ToolModuleImported {
2061 span: ident.span,
2062 import: binding.span,
2063 });
2064 }
2065 let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
2066 return PathResult::NonModule(PartialRes::new(res));
2067 } else if res == Res::Err {
2068 return PathResult::NonModule(PartialRes::new(Res::Err));
2069 } else if opt_ns.is_some() && (is_last || maybe_assoc) {
2070 if let Some(finalize) = finalize {
2071 self.get_mut().lint_if_path_starts_with_module(
2072 finalize,
2073 path,
2074 second_binding,
2075 );
2076 }
2077 record_segment_res(self.reborrow(), finalize, res, id);
2078 return PathResult::NonModule(PartialRes::with_unresolved_segments(
2079 res,
2080 path.len() - segment_idx - 1,
2081 ));
2082 } else {
2083 return PathResult::failed(
2084 ident,
2085 is_last,
2086 finalize.is_some(),
2087 module_had_parse_errors,
2088 module,
2089 || {
2090 let import_inherent_item_error_flag =
2091 self.features.import_trait_associated_functions()
2092 && #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union |
DefKind::ForeignTy, _) => true,
_ => false,
}matches!(
2093 res,
2094 Res::Def(
2095 DefKind::Struct
2096 | DefKind::Enum
2097 | DefKind::Union
2098 | DefKind::ForeignTy,
2099 _
2100 )
2101 );
2102 let label = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{3}` is {0} {1}, not a module{2}",
res.article(), res.descr(),
if import_inherent_item_error_flag {
" or a trait"
} else { "" }, ident))
})format!(
2104 "`{ident}` is {} {}, not a module{}",
2105 res.article(),
2106 res.descr(),
2107 if import_inherent_item_error_flag {
2108 " or a trait"
2109 } else {
2110 ""
2111 }
2112 );
2113 let scope = match &path[..segment_idx] {
2114 [.., prev] => {
2115 if prev.ident.name == kw::PathRoot {
2116 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the crate root"))
})format!("the crate root")
2117 } else {
2118 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", prev.ident))
})format!("`{}`", prev.ident)
2119 }
2120 }
2121 _ => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this scope"))
})format!("this scope"),
2122 };
2123 let message = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot find module `{0}` in {1}",
ident, scope))
})format!("cannot find module `{ident}` in {scope}");
2126 let note = if import_inherent_item_error_flag {
2127 Some(
2128 "cannot import inherent associated items, only trait associated items".to_string(),
2129 )
2130 } else {
2131 None
2132 };
2133 (message, label, None, note)
2134 },
2135 );
2136 }
2137 }
2138 Err(Undetermined) if finalize.is_none() => return PathResult::Indeterminate,
2139 Err(Determined | Undetermined) => {
2140 if let Some(ModuleOrUniformRoot::Module(module)) = module
2141 && opt_ns.is_some()
2142 && !module.is_normal()
2143 {
2144 return PathResult::NonModule(PartialRes::with_unresolved_segments(
2145 module.res().unwrap(),
2146 path.len() - segment_idx,
2147 ));
2148 }
2149
2150 let mut this = self.reborrow();
2151 return PathResult::failed(
2152 ident,
2153 is_last,
2154 finalize.is_some(),
2155 module_had_parse_errors,
2156 module,
2157 || {
2158 let (message, label, suggestion) =
2159 this.get_mut().report_path_resolution_error(
2160 path,
2161 opt_ns,
2162 parent_scope,
2163 ribs,
2164 ignore_decl,
2165 ignore_import,
2166 module,
2167 segment_idx,
2168 ident,
2169 diag_metadata,
2170 );
2171 (message, label, suggestion, None)
2172 },
2173 );
2174 }
2175 }
2176 }
2177
2178 if let Some(finalize) = finalize {
2179 self.get_mut().lint_if_path_starts_with_module(finalize, path, second_binding);
2180 }
2181
2182 PathResult::Module(match module {
2183 Some(module) => module,
2184 None if path.is_empty() => ModuleOrUniformRoot::CurrentScope,
2185 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("resolve_path: non-empty path `{0:?}` has no module",
path))bug!("resolve_path: non-empty path `{:?}` has no module", path),
2186 })
2187 }
2188}