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