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::ty::Visibility;
9use rustc_middle::{bug, span_bug};
10use rustc_session::lint::builtin::PROC_MACRO_DERIVE_RESOLUTION_FALLBACK;
11use rustc_session::parse::feature_err;
12use rustc_span::edition::Edition;
13use rustc_span::hygiene::{ExpnId, ExpnKind, LocalExpnId, MacroKind, SyntaxContext};
14use rustc_span::{Ident, Span, kw, sym};
15use smallvec::SmallVec;
16use tracing::{debug, instrument};
17
18use crate::errors::{ParamKindInEnumDiscriminant, ParamKindInNonTrivialAnonConst};
19use crate::hygiene::Macros20NormalizedSyntaxContext;
20use crate::imports::{Import, NameResolution};
21use crate::late::{
22 ConstantHasGenerics, DiagMetadata, NoConstantGenericsReason, PathSource, Rib, RibKind,
23};
24use crate::macros::{MacroRulesScope, sub_namespace_match};
25use crate::{
26 AmbiguityError, AmbiguityKind, AmbiguityWarning, BindingKey, CmResolver, Decl, DeclKind,
27 Determinacy, Finalize, IdentKey, ImportKind, LateDecl, LocalModule, Module, ModuleKind,
28 ModuleOrUniformRoot, ParentScope, PathResult, PrivacyError, Res, ResolutionError, Resolver,
29 Scope, ScopeSet, Segment, Stage, Symbol, Used, errors,
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).ext;
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_vis = match finalize {
489 None | Some(Finalize { stage: Stage::Late, .. }) => {
490 return ControlFlow::Break(Ok(decl));
491 }
492 Some(Finalize { import_vis, .. }) => import_vis,
493 };
494
495 if let Some(&(innermost_decl, _)) = innermost_results.first() {
496 if this.get_mut().maybe_push_ambiguity(
498 ident,
499 orig_ident_span,
500 ns,
501 scope_set,
502 parent_scope,
503 decl,
504 scope,
505 &innermost_results,
506 import_vis,
507 ) {
508 return ControlFlow::Break(Ok(innermost_decl));
510 }
511 }
512
513 innermost_results.push((decl, scope));
514 }
515 Ok(_) | Err(Determinacy::Determined) => {}
516 Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined,
517 }
518
519 ControlFlow::Continue(())
520 },
521 );
522
523 if let Some(break_result) = break_result {
525 return break_result;
526 }
527
528 match innermost_results.first() {
530 Some(&(decl, ..)) => Ok(decl),
531 None => Err(determinacy),
532 }
533 }
534
535 fn resolve_ident_in_scope<'r>(
536 mut self: CmResolver<'r, 'ra, 'tcx>,
537 ident: IdentKey,
538 orig_ident_span: Span,
539 ns: Namespace,
540 scope: Scope<'ra>,
541 use_prelude: UsePrelude,
542 scope_set: ScopeSet<'ra>,
543 parent_scope: &ParentScope<'ra>,
544 finalize: Option<Finalize>,
545 ignore_decl: Option<Decl<'ra>>,
546 ignore_import: Option<Import<'ra>>,
547 ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
548 let ret = match scope {
549 Scope::DeriveHelpers(expn_id) => {
550 if let Some(decl) = self
551 .helper_attrs
552 .get(&expn_id)
553 .and_then(|attrs| attrs.iter().rfind(|(i, ..)| ident == *i).map(|(.., d)| *d))
554 {
555 Ok(decl)
556 } else {
557 Err(Determinacy::Determined)
558 }
559 }
560 Scope::DeriveHelpersCompat => {
561 let mut result = Err(Determinacy::Determined);
562 for derive in parent_scope.derives {
563 let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
564 match self.reborrow().resolve_derive_macro_path(
565 derive,
566 parent_scope,
567 false,
568 ignore_import,
569 ) {
570 Ok((Some(ext), _)) => {
571 if ext.helper_attrs.contains(&ident.name) {
572 let decl = self.arenas.new_pub_def_decl(
573 Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat),
574 derive.span,
575 LocalExpnId::ROOT,
576 );
577 result = Ok(decl);
578 break;
579 }
580 }
581 Ok(_) | Err(Determinacy::Determined) => {}
582 Err(Determinacy::Undetermined) => result = Err(Determinacy::Undetermined),
583 }
584 }
585 result
586 }
587 Scope::MacroRules(macro_rules_scope) => match macro_rules_scope.get() {
588 MacroRulesScope::Def(macro_rules_def) if ident == macro_rules_def.ident => {
589 Ok(macro_rules_def.decl)
590 }
591 MacroRulesScope::Invocation(_) => Err(Determinacy::Undetermined),
592 _ => Err(Determinacy::Determined),
593 },
594 Scope::ModuleNonGlobs(module, derive_fallback_lint_id) => {
595 let (adjusted_parent_scope, adjusted_finalize) = if #[allow(non_exhaustive_omitted_patterns)] match scope_set {
ScopeSet::Module(..) | ScopeSet::ModuleAndExternPrelude(..) => true,
_ => false,
}matches!(
596 scope_set,
597 ScopeSet::Module(..) | ScopeSet::ModuleAndExternPrelude(..)
598 ) {
599 (parent_scope, finalize)
600 } else {
601 (
602 &ParentScope { module, ..*parent_scope },
603 finalize.map(|f| Finalize { used: Used::Scope, ..f }),
604 )
605 };
606 let decl = self.reborrow().resolve_ident_in_module_non_globs_unadjusted(
607 module,
608 ident,
609 orig_ident_span,
610 ns,
611 adjusted_parent_scope,
612 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 adjusted_finalize,
618 ignore_decl,
619 ignore_import,
620 );
621 match decl {
622 Ok(decl) => {
623 if let Some(lint_id) = derive_fallback_lint_id {
624 self.get_mut().lint_buffer.buffer_lint(
625 PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
626 lint_id,
627 orig_ident_span,
628 errors::ProcMacroDeriveResolutionFallback {
629 span: orig_ident_span,
630 ns_descr: ns.descr(),
631 ident: ident.name,
632 },
633 );
634 }
635 Ok(decl)
636 }
637 Err(ControlFlow::Continue(determinacy)) => Err(determinacy),
638 Err(ControlFlow::Break(..)) => return decl,
639 }
640 }
641 Scope::ModuleGlobs(module, _)
642 if let ModuleKind::Def(_, def_id, _) = module.kind
643 && !def_id.is_local() =>
644 {
645 Err(Determined)
647 }
648 Scope::ModuleGlobs(module, derive_fallback_lint_id) => {
649 let (adjusted_parent_scope, adjusted_finalize) = if #[allow(non_exhaustive_omitted_patterns)] match scope_set {
ScopeSet::Module(..) | ScopeSet::ModuleAndExternPrelude(..) => true,
_ => false,
}matches!(
650 scope_set,
651 ScopeSet::Module(..) | ScopeSet::ModuleAndExternPrelude(..)
652 ) {
653 (parent_scope, finalize)
654 } else {
655 (
656 &ParentScope { module, ..*parent_scope },
657 finalize.map(|f| Finalize { used: Used::Scope, ..f }),
658 )
659 };
660 let binding = self.reborrow().resolve_ident_in_module_globs_unadjusted(
661 module.expect_local(),
662 ident,
663 orig_ident_span,
664 ns,
665 adjusted_parent_scope,
666 if #[allow(non_exhaustive_omitted_patterns)] match scope_set {
ScopeSet::Module(..) => true,
_ => false,
}matches!(scope_set, ScopeSet::Module(..)) {
667 Shadowing::Unrestricted
668 } else {
669 Shadowing::Restricted
670 },
671 adjusted_finalize,
672 ignore_decl,
673 ignore_import,
674 );
675 match binding {
676 Ok(binding) => {
677 if let Some(lint_id) = derive_fallback_lint_id {
678 self.get_mut().lint_buffer.buffer_lint(
679 PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
680 lint_id,
681 orig_ident_span,
682 errors::ProcMacroDeriveResolutionFallback {
683 span: orig_ident_span,
684 ns_descr: ns.descr(),
685 ident: ident.name,
686 },
687 );
688 }
689 Ok(binding)
690 }
691 Err(ControlFlow::Continue(determinacy)) => Err(determinacy),
692 Err(ControlFlow::Break(..)) => return binding,
693 }
694 }
695 Scope::MacroUsePrelude => match self.macro_use_prelude.get(&ident.name).cloned() {
696 Some(decl) => Ok(decl),
697 None => Err(Determinacy::determined(
698 self.graph_root.unexpanded_invocations.borrow().is_empty(),
699 )),
700 },
701 Scope::BuiltinAttrs => match self.builtin_attr_decls.get(&ident.name) {
702 Some(decl) => Ok(*decl),
703 None => Err(Determinacy::Determined),
704 },
705 Scope::ExternPreludeItems => {
706 match self.reborrow().extern_prelude_get_item(
707 ident,
708 orig_ident_span,
709 finalize.is_some(),
710 ) {
711 Some(decl) => Ok(decl),
712 None => Err(Determinacy::determined(
713 self.graph_root.unexpanded_invocations.borrow().is_empty(),
714 )),
715 }
716 }
717 Scope::ExternPreludeFlags => {
718 match self.extern_prelude_get_flag(ident, orig_ident_span, finalize.is_some()) {
719 Some(decl) => Ok(decl),
720 None => Err(Determinacy::Determined),
721 }
722 }
723 Scope::ToolPrelude => match self.registered_tool_decls.get(&ident) {
724 Some(decl) => Ok(*decl),
725 None => Err(Determinacy::Determined),
726 },
727 Scope::StdLibPrelude => {
728 let mut result = Err(Determinacy::Determined);
729 if let Some(prelude) = self.prelude
730 && let Ok(decl) = self.reborrow().resolve_ident_in_scope_set_inner(
731 ident,
732 orig_ident_span,
733 ScopeSet::Module(ns, prelude),
734 parent_scope,
735 None,
736 ignore_decl,
737 ignore_import,
738 )
739 && (#[allow(non_exhaustive_omitted_patterns)] match use_prelude {
UsePrelude::Yes => true,
_ => false,
}matches!(use_prelude, UsePrelude::Yes) || self.is_builtin_macro(decl.res()))
740 {
741 result = Ok(decl)
742 }
743
744 result
745 }
746 Scope::BuiltinTypes => match self.builtin_type_decls.get(&ident.name) {
747 Some(decl) => {
748 if #[allow(non_exhaustive_omitted_patterns)] match ident.name {
sym::f16 => true,
_ => false,
}matches!(ident.name, sym::f16)
749 && !self.tcx.features().f16()
750 && !orig_ident_span.allows_unstable(sym::f16)
751 && finalize.is_some()
752 {
753 feature_err(
754 self.tcx.sess,
755 sym::f16,
756 orig_ident_span,
757 "the type `f16` is unstable",
758 )
759 .emit();
760 }
761 if #[allow(non_exhaustive_omitted_patterns)] match ident.name {
sym::f128 => true,
_ => false,
}matches!(ident.name, sym::f128)
762 && !self.tcx.features().f128()
763 && !orig_ident_span.allows_unstable(sym::f128)
764 && finalize.is_some()
765 {
766 feature_err(
767 self.tcx.sess,
768 sym::f128,
769 orig_ident_span,
770 "the type `f128` is unstable",
771 )
772 .emit();
773 }
774 Ok(*decl)
775 }
776 None => Err(Determinacy::Determined),
777 },
778 };
779
780 ret.map_err(ControlFlow::Continue)
781 }
782
783 fn maybe_push_ambiguity(
784 &mut self,
785 ident: IdentKey,
786 orig_ident_span: Span,
787 ns: Namespace,
788 scope_set: ScopeSet<'ra>,
789 parent_scope: &ParentScope<'ra>,
790 decl: Decl<'ra>,
791 scope: Scope<'ra>,
792 innermost_results: &[(Decl<'ra>, Scope<'ra>)],
793 import_vis: Option<Visibility>,
794 ) -> bool {
795 let (innermost_decl, innermost_scope) = innermost_results[0];
796 let (res, innermost_res) = (decl.res(), innermost_decl.res());
797 let ambig_vis = if res != innermost_res {
798 None
799 } else if let Some(import_vis) = import_vis
800 && let min =
801 (|d: Decl<'_>| d.vis().min(import_vis.to_def_id(), self.tcx).expect_local())
802 && let (min1, min2) = (min(decl), min(innermost_decl))
803 && min1 != min2
804 {
805 Some((min1, min2))
806 } else {
807 return false;
808 };
809
810 let module_only = #[allow(non_exhaustive_omitted_patterns)] match scope_set {
ScopeSet::Module(..) => true,
_ => false,
}matches!(scope_set, ScopeSet::Module(..));
813 let is_builtin = |res| #[allow(non_exhaustive_omitted_patterns)] match res {
Res::NonMacroAttr(NonMacroAttrKind::Builtin(..)) => true,
_ => false,
}matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Builtin(..)));
814 let derive_helper = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
815 let derive_helper_compat = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
816
817 let ambiguity_error_kind = if is_builtin(innermost_res) || is_builtin(res) {
818 Some(AmbiguityKind::BuiltinAttr)
819 } else if innermost_res == derive_helper_compat {
820 Some(AmbiguityKind::DeriveHelper)
821 } else if res == derive_helper_compat && innermost_res != derive_helper {
822 ::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")
823 } else if #[allow(non_exhaustive_omitted_patterns)] match innermost_scope {
Scope::MacroRules(_) => true,
_ => false,
}matches!(innermost_scope, Scope::MacroRules(_))
824 && #[allow(non_exhaustive_omitted_patterns)] match scope {
Scope::ModuleNonGlobs(..) | Scope::ModuleGlobs(..) => true,
_ => false,
}matches!(scope, Scope::ModuleNonGlobs(..) | Scope::ModuleGlobs(..))
825 && !self.disambiguate_macro_rules_vs_modularized(innermost_decl, decl)
826 {
827 Some(AmbiguityKind::MacroRulesVsModularized)
828 } else if #[allow(non_exhaustive_omitted_patterns)] match scope {
Scope::MacroRules(_) => true,
_ => false,
}matches!(scope, Scope::MacroRules(_))
829 && #[allow(non_exhaustive_omitted_patterns)] match innermost_scope {
Scope::ModuleNonGlobs(..) | Scope::ModuleGlobs(..) => true,
_ => false,
}matches!(innermost_scope, Scope::ModuleNonGlobs(..) | Scope::ModuleGlobs(..))
830 {
831 ::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!(
837 orig_ident_span,
838 "ambiguous scoped macro resolutions with path-based \
839 scope resolution as first candidate"
840 )
841 } else if innermost_decl.is_glob_import() {
842 Some(AmbiguityKind::GlobVsOuter)
843 } else if !module_only && innermost_decl.may_appear_after(parent_scope.expansion, decl) {
844 Some(AmbiguityKind::MoreExpandedVsOuter)
845 } else if innermost_decl.expansion != LocalExpnId::ROOT
846 && (!module_only || ns == MacroNS)
847 && let Scope::ModuleGlobs(m1, _) = scope
848 && let Scope::ModuleNonGlobs(m2, _) = innermost_scope
849 && m1 == m2
850 {
851 Some(AmbiguityKind::GlobVsExpanded)
855 } else {
856 None
857 };
858
859 if let Some(kind) = ambiguity_error_kind {
860 let issue_145575_hack = #[allow(non_exhaustive_omitted_patterns)] match scope {
Scope::ExternPreludeFlags => true,
_ => false,
}matches!(scope, Scope::ExternPreludeFlags)
864 && innermost_results[1..]
865 .iter()
866 .any(|(b, s)| #[allow(non_exhaustive_omitted_patterns)] match s {
Scope::ExternPreludeItems => true,
_ => false,
}matches!(s, Scope::ExternPreludeItems) && *b != innermost_decl);
867 let issue_149681_hack = match scope {
871 Scope::ModuleGlobs(m1, _)
872 if innermost_results[1..]
873 .iter()
874 .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)) =>
875 {
876 true
877 }
878 _ => false,
879 };
880
881 if issue_145575_hack || issue_149681_hack {
882 self.issue_145575_hack_applied = true;
883 } else {
884 let is_issue_147319_hack = orig_ident_span.edition() <= Edition::Edition2024
887 && #[allow(non_exhaustive_omitted_patterns)] match ident.name {
sym::panic => true,
_ => false,
}matches!(ident.name, sym::panic)
888 && #[allow(non_exhaustive_omitted_patterns)] match scope {
Scope::StdLibPrelude => true,
_ => false,
}matches!(scope, Scope::StdLibPrelude)
889 && #[allow(non_exhaustive_omitted_patterns)] match innermost_scope {
Scope::ModuleGlobs(_, _) => true,
_ => false,
}matches!(innermost_scope, Scope::ModuleGlobs(_, _))
890 && ((self.is_specific_builtin_macro(res, sym::std_panic)
891 && self.is_specific_builtin_macro(innermost_res, sym::core_panic))
892 || (self.is_specific_builtin_macro(res, sym::core_panic)
893 && self.is_specific_builtin_macro(innermost_res, sym::std_panic)));
894
895 let warning = if ambig_vis.is_some() {
896 Some(AmbiguityWarning::GlobImport)
897 } else if is_issue_147319_hack {
898 Some(AmbiguityWarning::PanicImport)
899 } else {
900 None
901 };
902
903 self.ambiguity_errors.push(AmbiguityError {
904 kind,
905 ambig_vis,
906 ident: ident.orig(orig_ident_span),
907 b1: innermost_decl,
908 b2: decl,
909 scope1: innermost_scope,
910 scope2: scope,
911 warning,
912 });
913 return true;
914 }
915 }
916
917 false
918 }
919
920 #[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(920u32),
::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))]
921 pub(crate) fn maybe_resolve_ident_in_module<'r>(
922 self: CmResolver<'r, 'ra, 'tcx>,
923 module: ModuleOrUniformRoot<'ra>,
924 ident: Ident,
925 ns: Namespace,
926 parent_scope: &ParentScope<'ra>,
927 ignore_import: Option<Import<'ra>>,
928 ) -> Result<Decl<'ra>, Determinacy> {
929 self.resolve_ident_in_module(module, ident, ns, parent_scope, None, None, ignore_import)
930 }
931
932 fn resolve_super_in_module(
933 &self,
934 ident: Ident,
935 module: Option<Module<'ra>>,
936 parent_scope: &ParentScope<'ra>,
937 ) -> Option<Module<'ra>> {
938 let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
939 module
940 .unwrap_or_else(|| self.resolve_self(&mut ctxt, parent_scope.module))
941 .parent
942 .map(|parent| self.resolve_self(&mut ctxt, parent))
943 }
944
945 pub(crate) fn path_root_is_crate_root(&self, ident: Ident) -> bool {
946 ident.name == kw::PathRoot && ident.span.is_rust_2015() && self.tcx.sess.is_rust_2015()
947 }
948
949 #[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(949u32),
::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))]
950 pub(crate) fn resolve_ident_in_module<'r>(
951 self: CmResolver<'r, 'ra, 'tcx>,
952 module: ModuleOrUniformRoot<'ra>,
953 ident: Ident,
954 ns: Namespace,
955 parent_scope: &ParentScope<'ra>,
956 finalize: Option<Finalize>,
957 ignore_decl: Option<Decl<'ra>>,
958 ignore_import: Option<Import<'ra>>,
959 ) -> Result<Decl<'ra>, Determinacy> {
960 match module {
961 ModuleOrUniformRoot::Module(module) => {
962 if ns == TypeNS {
963 if ident.name == kw::SelfLower {
964 return Ok(module.self_decl.unwrap());
965 }
966 if ident.name == kw::Super
967 && let Some(module) =
968 self.resolve_super_in_module(ident, Some(module), parent_scope)
969 {
970 return Ok(module.self_decl.unwrap());
971 }
972 }
973
974 let (ident_key, def) = IdentKey::new_adjusted(ident, module.expansion);
975 let adjusted_parent_scope = match def {
976 Some(def) => ParentScope { module: self.expn_def_scope(def), ..*parent_scope },
977 None => *parent_scope,
978 };
979 self.resolve_ident_in_scope_set_inner(
980 ident_key,
981 ident.span,
982 ScopeSet::Module(ns, module),
983 &adjusted_parent_scope,
984 finalize,
985 ignore_decl,
986 ignore_import,
987 )
988 }
989 ModuleOrUniformRoot::OpenModule(sym) => {
990 let open_ns_name = format!("{}::{}", sym.as_str(), ident.name);
991 let ns_ident = IdentKey::with_root_ctxt(Symbol::intern(&open_ns_name));
992 match self.extern_prelude_get_flag(ns_ident, ident.span, finalize.is_some()) {
993 Some(decl) => Ok(decl),
994 None => Err(Determinacy::Determined),
995 }
996 }
997 ModuleOrUniformRoot::ModuleAndExternPrelude(module) => self.resolve_ident_in_scope_set(
998 ident,
999 ScopeSet::ModuleAndExternPrelude(ns, module),
1000 parent_scope,
1001 finalize,
1002 ignore_decl,
1003 ignore_import,
1004 ),
1005 ModuleOrUniformRoot::ExternPrelude => {
1006 if ns != TypeNS {
1007 Err(Determined)
1008 } else {
1009 self.resolve_ident_in_scope_set_inner(
1010 IdentKey::new_adjusted(ident, ExpnId::root()).0,
1011 ident.span,
1012 ScopeSet::ExternPrelude,
1013 parent_scope,
1014 finalize,
1015 ignore_decl,
1016 ignore_import,
1017 )
1018 }
1019 }
1020 ModuleOrUniformRoot::CurrentScope => {
1021 if ns == TypeNS {
1022 if ident.name == kw::SelfLower {
1023 let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
1024 let module = self.resolve_self(&mut ctxt, parent_scope.module);
1025 return Ok(module.self_decl.unwrap());
1026 }
1027 if ident.name == kw::Super
1028 && let Some(module) =
1029 self.resolve_super_in_module(ident, None, parent_scope)
1030 {
1031 return Ok(module.self_decl.unwrap());
1032 }
1033 if ident.name == kw::Crate
1034 || ident.name == kw::DollarCrate
1035 || self.path_root_is_crate_root(ident)
1036 {
1037 let module = self.resolve_crate_root(ident);
1038 return Ok(module.self_decl.unwrap());
1039 } else if ident.name == kw::Super {
1040 }
1044 }
1045
1046 self.resolve_ident_in_scope_set(
1047 ident,
1048 ScopeSet::All(ns),
1049 parent_scope,
1050 finalize,
1051 ignore_decl,
1052 ignore_import,
1053 )
1054 }
1055 }
1056 }
1057
1058 fn resolve_ident_in_module_non_globs_unadjusted<'r>(
1060 mut self: CmResolver<'r, 'ra, 'tcx>,
1061 module: Module<'ra>,
1062 ident: IdentKey,
1063 orig_ident_span: Span,
1064 ns: Namespace,
1065 parent_scope: &ParentScope<'ra>,
1066 shadowing: Shadowing,
1067 finalize: Option<Finalize>,
1068 ignore_decl: Option<Decl<'ra>>,
1071 ignore_import: Option<Import<'ra>>,
1072 ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
1073 let key = BindingKey::new(ident, ns);
1074 let resolution = &*self
1078 .resolution_or_default(module, key, orig_ident_span)
1079 .try_borrow_mut_unchecked()
1080 .map_err(|_| ControlFlow::Continue(Determined))?;
1081
1082 let binding = resolution.non_glob_decl.filter(|b| Some(*b) != ignore_decl);
1083
1084 if let Some(finalize) = finalize {
1085 return self.get_mut().finalize_module_binding(
1086 ident,
1087 orig_ident_span,
1088 binding,
1089 parent_scope,
1090 finalize,
1091 shadowing,
1092 );
1093 }
1094
1095 if let Some(binding) = binding {
1097 let accessible = self.is_accessible_from(binding.vis(), parent_scope.module);
1098 return if accessible { Ok(binding) } else { Err(ControlFlow::Break(Determined)) };
1099 }
1100
1101 if self.reborrow().single_import_can_define_name(
1103 &resolution,
1104 None,
1105 ns,
1106 ignore_import,
1107 ignore_decl,
1108 parent_scope,
1109 ) {
1110 return Err(ControlFlow::Break(Undetermined));
1111 }
1112
1113 if !module.unexpanded_invocations.borrow().is_empty() {
1115 return Err(ControlFlow::Continue(Undetermined));
1116 }
1117
1118 Err(ControlFlow::Continue(Determined))
1120 }
1121
1122 fn resolve_ident_in_module_globs_unadjusted<'r>(
1124 mut self: CmResolver<'r, 'ra, 'tcx>,
1125 module: LocalModule<'ra>,
1126 ident: IdentKey,
1127 orig_ident_span: Span,
1128 ns: Namespace,
1129 parent_scope: &ParentScope<'ra>,
1130 shadowing: Shadowing,
1131 finalize: Option<Finalize>,
1132 ignore_decl: Option<Decl<'ra>>,
1133 ignore_import: Option<Import<'ra>>,
1134 ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
1135 let key = BindingKey::new(ident, ns);
1136 let resolution = &*self
1140 .resolution_or_default(module.to_module(), key, orig_ident_span)
1141 .try_borrow_mut_unchecked()
1142 .map_err(|_| ControlFlow::Continue(Determined))?;
1143
1144 let binding = resolution.glob_decl.filter(|b| Some(*b) != ignore_decl);
1145
1146 if let Some(finalize) = finalize {
1147 return self.get_mut().finalize_module_binding(
1148 ident,
1149 orig_ident_span,
1150 binding,
1151 parent_scope,
1152 finalize,
1153 shadowing,
1154 );
1155 }
1156
1157 if self.reborrow().single_import_can_define_name(
1160 &resolution,
1161 binding,
1162 ns,
1163 ignore_import,
1164 ignore_decl,
1165 parent_scope,
1166 ) {
1167 return Err(ControlFlow::Break(Undetermined));
1168 }
1169
1170 if let Some(binding) = binding {
1183 return if binding.determined() || ns == MacroNS || shadowing == Shadowing::Restricted {
1184 let accessible = self.is_accessible_from(binding.vis(), parent_scope.module);
1185 if accessible { Ok(binding) } else { Err(ControlFlow::Break(Determined)) }
1186 } else {
1187 Err(ControlFlow::Break(Undetermined))
1188 };
1189 }
1190
1191 if !module.unexpanded_invocations.borrow().is_empty() {
1199 return Err(ControlFlow::Continue(Undetermined));
1200 }
1201
1202 for glob_import in module.globs.borrow().iter() {
1205 if ignore_import == Some(*glob_import) {
1206 continue;
1207 }
1208 if !self.is_accessible_from(glob_import.vis, parent_scope.module) {
1209 continue;
1210 }
1211 let module = match glob_import.imported_module.get() {
1212 Some(ModuleOrUniformRoot::Module(module)) => module,
1213 Some(_) => continue,
1214 None => return Err(ControlFlow::Continue(Undetermined)),
1215 };
1216 let tmp_parent_scope;
1217 let (mut adjusted_parent_scope, mut adjusted_ident) = (parent_scope, ident);
1218 match adjusted_ident
1219 .ctxt
1220 .update_unchecked(|ctxt| ctxt.glob_adjust(module.expansion, glob_import.span))
1221 {
1222 Some(Some(def)) => {
1223 tmp_parent_scope =
1224 ParentScope { module: self.expn_def_scope(def), ..*parent_scope };
1225 adjusted_parent_scope = &tmp_parent_scope;
1226 }
1227 Some(None) => {}
1228 None => continue,
1229 };
1230 let result = self.reborrow().resolve_ident_in_scope_set_inner(
1231 adjusted_ident,
1232 orig_ident_span,
1233 ScopeSet::Module(ns, module),
1234 adjusted_parent_scope,
1235 None,
1236 ignore_decl,
1237 ignore_import,
1238 );
1239
1240 match result {
1241 Err(Determined) => continue,
1242 Ok(binding)
1243 if !self.is_accessible_from(binding.vis(), glob_import.parent_scope.module) =>
1244 {
1245 continue;
1246 }
1247 Ok(_) | Err(Undetermined) => return Err(ControlFlow::Continue(Undetermined)),
1248 }
1249 }
1250
1251 Err(ControlFlow::Continue(Determined))
1253 }
1254
1255 fn finalize_module_binding(
1256 &mut self,
1257 ident: IdentKey,
1258 orig_ident_span: Span,
1259 binding: Option<Decl<'ra>>,
1260 parent_scope: &ParentScope<'ra>,
1261 finalize: Finalize,
1262 shadowing: Shadowing,
1263 ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
1264 let Finalize { path_span, report_private, used, root_span, .. } = finalize;
1265
1266 let Some(binding) = binding else {
1267 return Err(ControlFlow::Continue(Determined));
1268 };
1269
1270 let ident = ident.orig(orig_ident_span);
1271 if !self.is_accessible_from(binding.vis(), parent_scope.module) {
1272 if report_private {
1273 self.privacy_errors.push(PrivacyError {
1274 ident,
1275 decl: binding,
1276 dedup_span: path_span,
1277 outermost_res: None,
1278 source: None,
1279 parent_scope: *parent_scope,
1280 single_nested: path_span != root_span,
1281 });
1282 } else {
1283 return Err(ControlFlow::Break(Determined));
1284 }
1285 }
1286
1287 if shadowing == Shadowing::Unrestricted
1288 && binding.expansion != LocalExpnId::ROOT
1289 && let DeclKind::Import { import, .. } = binding.kind
1290 && #[allow(non_exhaustive_omitted_patterns)] match import.kind {
ImportKind::MacroExport => true,
_ => false,
}matches!(import.kind, ImportKind::MacroExport)
1291 {
1292 self.macro_expanded_macro_export_errors.insert((path_span, binding.span));
1293 }
1294
1295 self.record_use(ident, binding, used);
1296 return Ok(binding);
1297 }
1298
1299 fn single_import_can_define_name<'r>(
1302 mut self: CmResolver<'r, 'ra, 'tcx>,
1303 resolution: &NameResolution<'ra>,
1304 binding: Option<Decl<'ra>>,
1305 ns: Namespace,
1306 ignore_import: Option<Import<'ra>>,
1307 ignore_decl: Option<Decl<'ra>>,
1308 parent_scope: &ParentScope<'ra>,
1309 ) -> bool {
1310 for single_import in &resolution.single_imports {
1311 if let Some(decl) = resolution.non_glob_decl
1312 && let DeclKind::Import { import, .. } = decl.kind
1313 && import == *single_import
1314 {
1315 continue;
1318 }
1319 if ignore_import == Some(*single_import) {
1320 continue;
1321 }
1322 if !self.is_accessible_from(single_import.vis, parent_scope.module) {
1323 continue;
1324 }
1325 if let Some(ignored) = ignore_decl
1326 && let DeclKind::Import { import, .. } = ignored.kind
1327 && import == *single_import
1328 {
1329 continue;
1330 }
1331
1332 let Some(module) = single_import.imported_module.get() else {
1333 return true;
1334 };
1335 let ImportKind::Single { source, target, decls, .. } = &single_import.kind else {
1336 ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1337 };
1338 if source != target {
1339 if decls.iter().all(|d| d.get().decl().is_none()) {
1340 return true;
1341 } else if decls[ns].get().decl().is_none() && binding.is_some() {
1342 return true;
1343 }
1344 }
1345
1346 match self.reborrow().resolve_ident_in_module(
1347 module,
1348 *source,
1349 ns,
1350 &single_import.parent_scope,
1351 None,
1352 ignore_decl,
1353 None,
1354 ) {
1355 Err(Determined) => continue,
1356 Ok(binding)
1357 if !self
1358 .is_accessible_from(binding.vis(), single_import.parent_scope.module) =>
1359 {
1360 continue;
1361 }
1362 Ok(_) | Err(Undetermined) => return true,
1363 }
1364 }
1365
1366 false
1367 }
1368
1369 #[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(1370u32),
::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:1381",
"rustc_resolve::ident", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
::tracing_core::__macro_support::Option::Some(1381u32),
::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.tcx.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.tcx.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 span =
current_item.kind.ident().map(|i|
i.span).unwrap_or(current_item.span);
Some((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.tcx.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.tcx.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 span =
current_item.kind.ident().map(|i|
i.span).unwrap_or(current_item.span);
Some((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))]
1371 fn validate_res_from_ribs(
1372 &mut self,
1373 rib_index: usize,
1374 rib_ident: Ident,
1375 res: Res,
1376 finalize: Option<Span>,
1377 original_rib_ident_def: Ident,
1378 all_ribs: &[Rib<'ra>],
1379 diag_metadata: Option<&DiagMetadata<'_>>,
1380 ) -> Res {
1381 debug!("validate_res_from_ribs({:?})", res);
1382 let ribs = &all_ribs[rib_index + 1..];
1383
1384 if let RibKind::ForwardGenericParamBan(reason) = all_ribs[rib_index].kind {
1387 if let Some(span) = finalize {
1388 let res_error = if rib_ident.name == kw::SelfUpper {
1389 ResolutionError::ForwardDeclaredSelf(reason)
1390 } else {
1391 ResolutionError::ForwardDeclaredGenericParam(rib_ident.name, reason)
1392 };
1393 self.report_error(span, res_error);
1394 }
1395 assert_eq!(res, Res::Err);
1396 return Res::Err;
1397 }
1398
1399 match res {
1400 Res::Local(_) => {
1401 use ResolutionError::*;
1402 let mut res_err = None;
1403
1404 for rib in ribs {
1405 match rib.kind {
1406 RibKind::Normal
1407 | RibKind::Block(..)
1408 | RibKind::FnOrCoroutine
1409 | RibKind::Module(..)
1410 | RibKind::MacroDefinition(..)
1411 | RibKind::ForwardGenericParamBan(_) => {
1412 }
1414 RibKind::Item(..) | RibKind::AssocItem => {
1415 if let Some(span) = finalize {
1419 res_err = Some((span, CannotCaptureDynamicEnvironmentInFnItem));
1424 }
1425 }
1426 RibKind::ConstantItem(_, item) => {
1427 if let Some(span) = finalize {
1429 let (span, resolution_error) = match item {
1430 None if rib_ident.name == kw::SelfLower => {
1431 (span, LowercaseSelf)
1432 }
1433 None => {
1434 let sm = self.tcx.sess.source_map();
1440 let type_span = match sm
1441 .span_followed_by(original_rib_ident_def.span, ":")
1442 {
1443 None => {
1444 Some(original_rib_ident_def.span.shrink_to_hi())
1445 }
1446 Some(_) => None,
1447 };
1448 (
1449 rib_ident.span,
1450 AttemptToUseNonConstantValueInConstant {
1451 ident: original_rib_ident_def,
1452 suggestion: "const",
1453 current: "let",
1454 type_span,
1455 },
1456 )
1457 }
1458 Some((ident, kind)) => (
1459 span,
1460 AttemptToUseNonConstantValueInConstant {
1461 ident,
1462 suggestion: "let",
1463 current: kind.as_str(),
1464 type_span: None,
1465 },
1466 ),
1467 };
1468 self.report_error(span, resolution_error);
1469 }
1470 return Res::Err;
1471 }
1472 RibKind::ConstParamTy => {
1473 if let Some(span) = finalize {
1474 self.report_error(
1475 span,
1476 ParamInTyOfConstParam { name: rib_ident.name },
1477 );
1478 }
1479 return Res::Err;
1480 }
1481 RibKind::InlineAsmSym => {
1482 if let Some(span) = finalize {
1483 self.report_error(span, InvalidAsmSym);
1484 }
1485 return Res::Err;
1486 }
1487 }
1488 }
1489 if let Some((span, res_err)) = res_err {
1490 self.report_error(span, res_err);
1491 return Res::Err;
1492 }
1493 }
1494 Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } => {
1495 for rib in ribs {
1496 let (has_generic_params, def_kind) = match rib.kind {
1497 RibKind::Normal
1498 | RibKind::Block(..)
1499 | RibKind::FnOrCoroutine
1500 | RibKind::Module(..)
1501 | RibKind::MacroDefinition(..)
1502 | RibKind::InlineAsmSym
1503 | RibKind::AssocItem
1504 | RibKind::ForwardGenericParamBan(_) => {
1505 continue;
1507 }
1508
1509 RibKind::ConstParamTy => {
1510 if !self.tcx.features().generic_const_parameter_types() {
1511 if let Some(span) = finalize {
1512 self.report_error(
1513 span,
1514 ResolutionError::ParamInTyOfConstParam {
1515 name: rib_ident.name,
1516 },
1517 );
1518 }
1519 return Res::Err;
1520 } else {
1521 continue;
1522 }
1523 }
1524
1525 RibKind::ConstantItem(trivial, _) => {
1526 if let ConstantHasGenerics::No(cause) = trivial
1527 && !matches!(res, Res::SelfTyAlias { .. })
1528 {
1529 if let Some(span) = finalize {
1530 let error = match cause {
1531 NoConstantGenericsReason::IsEnumDiscriminant => {
1532 ResolutionError::ParamInEnumDiscriminant {
1533 name: rib_ident.name,
1534 param_kind: ParamKindInEnumDiscriminant::Type,
1535 }
1536 }
1537 NoConstantGenericsReason::NonTrivialConstArg => {
1538 ResolutionError::ParamInNonTrivialAnonConst {
1539 is_gca: self.tcx.features().generic_const_args(),
1540 name: rib_ident.name,
1541 param_kind: ParamKindInNonTrivialAnonConst::Type,
1542 }
1543 }
1544 };
1545 let _: ErrorGuaranteed = self.report_error(span, error);
1546 }
1547
1548 return Res::Err;
1549 }
1550
1551 continue;
1552 }
1553
1554 RibKind::Item(has_generic_params, def_kind) => {
1556 (has_generic_params, def_kind)
1557 }
1558 };
1559
1560 if let Some(span) = finalize {
1561 let item = if let Some(diag_metadata) = diag_metadata
1562 && let Some(current_item) = diag_metadata.current_item
1563 {
1564 let span = current_item
1565 .kind
1566 .ident()
1567 .map(|i| i.span)
1568 .unwrap_or(current_item.span);
1569 Some((span, current_item.kind.clone()))
1570 } else {
1571 None
1572 };
1573 self.report_error(
1574 span,
1575 ResolutionError::GenericParamsFromOuterItem {
1576 outer_res: res,
1577 has_generic_params,
1578 def_kind,
1579 inner_item: item,
1580 current_self_ty: diag_metadata
1581 .and_then(|m| m.current_self_type.as_ref())
1582 .and_then(|ty| {
1583 self.tcx.sess.source_map().span_to_snippet(ty.span).ok()
1584 }),
1585 },
1586 );
1587 }
1588 return Res::Err;
1589 }
1590 }
1591 Res::Def(DefKind::ConstParam, _) => {
1592 for rib in ribs {
1593 let (has_generic_params, def_kind) = match rib.kind {
1594 RibKind::Normal
1595 | RibKind::Block(..)
1596 | RibKind::FnOrCoroutine
1597 | RibKind::Module(..)
1598 | RibKind::MacroDefinition(..)
1599 | RibKind::InlineAsmSym
1600 | RibKind::AssocItem
1601 | RibKind::ForwardGenericParamBan(_) => continue,
1602
1603 RibKind::ConstParamTy => {
1604 if !self.tcx.features().generic_const_parameter_types() {
1605 if let Some(span) = finalize {
1606 self.report_error(
1607 span,
1608 ResolutionError::ParamInTyOfConstParam {
1609 name: rib_ident.name,
1610 },
1611 );
1612 }
1613 return Res::Err;
1614 } else {
1615 continue;
1616 }
1617 }
1618
1619 RibKind::ConstantItem(trivial, _) => {
1620 if let ConstantHasGenerics::No(cause) = trivial {
1621 if let Some(span) = finalize {
1622 let error = match cause {
1623 NoConstantGenericsReason::IsEnumDiscriminant => {
1624 ResolutionError::ParamInEnumDiscriminant {
1625 name: rib_ident.name,
1626 param_kind: ParamKindInEnumDiscriminant::Const,
1627 }
1628 }
1629 NoConstantGenericsReason::NonTrivialConstArg => {
1630 ResolutionError::ParamInNonTrivialAnonConst {
1631 is_gca: self.tcx.features().generic_const_args(),
1632 name: rib_ident.name,
1633 param_kind: ParamKindInNonTrivialAnonConst::Const {
1634 name: rib_ident.name,
1635 },
1636 }
1637 }
1638 };
1639 self.report_error(span, error);
1640 }
1641
1642 return Res::Err;
1643 }
1644
1645 continue;
1646 }
1647
1648 RibKind::Item(has_generic_params, def_kind) => {
1649 (has_generic_params, def_kind)
1650 }
1651 };
1652
1653 if let Some(span) = finalize {
1655 let item = if let Some(diag_metadata) = diag_metadata
1656 && let Some(current_item) = diag_metadata.current_item
1657 {
1658 let span = current_item
1659 .kind
1660 .ident()
1661 .map(|i| i.span)
1662 .unwrap_or(current_item.span);
1663 Some((span, current_item.kind.clone()))
1664 } else {
1665 None
1666 };
1667 self.report_error(
1668 span,
1669 ResolutionError::GenericParamsFromOuterItem {
1670 outer_res: res,
1671 has_generic_params,
1672 def_kind,
1673 inner_item: item,
1674 current_self_ty: diag_metadata
1675 .and_then(|m| m.current_self_type.as_ref())
1676 .and_then(|ty| {
1677 self.tcx.sess.source_map().span_to_snippet(ty.span).ok()
1678 }),
1679 },
1680 );
1681 }
1682 return Res::Err;
1683 }
1684 }
1685 _ => {}
1686 }
1687
1688 res
1689 }
1690
1691 #[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(1691u32),
::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))]
1692 pub(crate) fn maybe_resolve_path<'r>(
1693 self: CmResolver<'r, 'ra, 'tcx>,
1694 path: &[Segment],
1695 opt_ns: Option<Namespace>, parent_scope: &ParentScope<'ra>,
1697 ignore_import: Option<Import<'ra>>,
1698 ) -> PathResult<'ra> {
1699 self.resolve_path_with_ribs(
1700 path,
1701 opt_ns,
1702 parent_scope,
1703 None,
1704 None,
1705 None,
1706 None,
1707 ignore_import,
1708 None,
1709 )
1710 }
1711 #[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(1711u32),
::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))]
1712 pub(crate) fn resolve_path<'r>(
1713 self: CmResolver<'r, 'ra, 'tcx>,
1714 path: &[Segment],
1715 opt_ns: Option<Namespace>, parent_scope: &ParentScope<'ra>,
1717 finalize: Option<Finalize>,
1718 ignore_decl: Option<Decl<'ra>>,
1719 ignore_import: Option<Import<'ra>>,
1720 ) -> PathResult<'ra> {
1721 self.resolve_path_with_ribs(
1722 path,
1723 opt_ns,
1724 parent_scope,
1725 None,
1726 finalize,
1727 None,
1728 ignore_decl,
1729 ignore_import,
1730 None,
1731 )
1732 }
1733
1734 pub(crate) fn resolve_path_with_ribs<'r>(
1735 mut self: CmResolver<'r, 'ra, 'tcx>,
1736 path: &[Segment],
1737 opt_ns: Option<Namespace>, parent_scope: &ParentScope<'ra>,
1739 source: Option<PathSource<'_, '_, '_>>,
1740 finalize: Option<Finalize>,
1741 ribs: Option<&PerNS<Vec<Rib<'ra>>>>,
1742 ignore_decl: Option<Decl<'ra>>,
1743 ignore_import: Option<Import<'ra>>,
1744 diag_metadata: Option<&DiagMetadata<'_>>,
1745 ) -> PathResult<'ra> {
1746 let mut module = None;
1747 let mut module_had_parse_errors = !self.mods_with_parse_errors.is_empty()
1748 && self.mods_with_parse_errors.contains(&parent_scope.module.nearest_parent_mod());
1749 let mut allow_super = true;
1750 let mut second_binding = None;
1751
1752 let privacy_errors_len = self.privacy_errors.len();
1754 fn record_segment_res<'r, 'ra, 'tcx>(
1755 mut this: CmResolver<'r, 'ra, 'tcx>,
1756 finalize: Option<Finalize>,
1757 res: Res,
1758 id: Option<NodeId>,
1759 ) {
1760 if finalize.is_some()
1761 && let Some(id) = id
1762 && !this.partial_res_map.contains_key(&id)
1763 {
1764 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");
1765 this.get_mut().record_partial_res(id, PartialRes::new(res));
1766 }
1767 }
1768
1769 for (segment_idx, &Segment { ident, id, .. }) in path.iter().enumerate() {
1770 {
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:1770",
"rustc_resolve::ident", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
::tracing_core::__macro_support::Option::Some(1770u32),
::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);
1771
1772 let is_last = segment_idx + 1 == path.len();
1773 let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
1774 let name = ident.name;
1775
1776 allow_super &= ns == TypeNS && (name == kw::SelfLower || name == kw::Super);
1777
1778 if ns == TypeNS {
1779 if allow_super && name == kw::Super {
1780 let parent = if segment_idx == 0 {
1781 self.resolve_super_in_module(ident, None, parent_scope)
1782 } else if let Some(ModuleOrUniformRoot::Module(module)) = module {
1783 self.resolve_super_in_module(ident, Some(module), parent_scope)
1784 } else {
1785 None
1786 };
1787 if let Some(parent) = parent {
1788 module = Some(ModuleOrUniformRoot::Module(parent));
1789 continue;
1790 }
1791 return PathResult::failed(
1792 ident,
1793 false,
1794 finalize.is_some(),
1795 module_had_parse_errors,
1796 module,
1797 || {
1798 (
1799 "too many leading `super` keywords".to_string(),
1800 "there are too many leading `super` keywords".to_string(),
1801 None,
1802 )
1803 },
1804 );
1805 }
1806 if segment_idx == 0 {
1807 if name == kw::SelfLower {
1808 let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
1809 let self_mod = self.resolve_self(&mut ctxt, parent_scope.module);
1810 if let Some(res) = self_mod.res() {
1811 record_segment_res(self.reborrow(), finalize, res, id);
1812 }
1813 module = Some(ModuleOrUniformRoot::Module(self_mod));
1814 continue;
1815 }
1816 if name == kw::PathRoot && ident.span.at_least_rust_2018() {
1817 module = Some(ModuleOrUniformRoot::ExternPrelude);
1818 continue;
1819 }
1820 if name == kw::PathRoot
1821 && ident.span.is_rust_2015()
1822 && self.tcx.sess.at_least_rust_2018()
1823 {
1824 let crate_root = self.resolve_crate_root(ident);
1826 module = Some(ModuleOrUniformRoot::ModuleAndExternPrelude(crate_root));
1827 continue;
1828 }
1829 if name == kw::PathRoot || name == kw::Crate || name == kw::DollarCrate {
1830 let crate_root = self.resolve_crate_root(ident);
1832 if let Some(res) = crate_root.res() {
1833 record_segment_res(self.reborrow(), finalize, res, id);
1834 }
1835 module = Some(ModuleOrUniformRoot::Module(crate_root));
1836 continue;
1837 }
1838 }
1839 }
1840
1841 if ident.is_path_segment_keyword() && segment_idx != 0 {
1843 return PathResult::failed(
1844 ident,
1845 false,
1846 finalize.is_some(),
1847 module_had_parse_errors,
1848 module,
1849 || {
1850 let name_str = if name == kw::PathRoot {
1851 "the crate root".to_string()
1852 } else {
1853 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", name))
})format!("`{name}`")
1854 };
1855 let (message, label) = if segment_idx == 1
1856 && path[0].ident.name == kw::PathRoot
1857 {
1858 (
1859 ::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}"),
1860 "cannot start with this".to_string(),
1861 )
1862 } else {
1863 (
1864 ::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"),
1865 "can only be used in path start position".to_string(),
1866 )
1867 };
1868 (message, label, None)
1869 },
1870 );
1871 }
1872
1873 let binding = if let Some(module) = module {
1874 self.reborrow().resolve_ident_in_module(
1875 module,
1876 ident,
1877 ns,
1878 parent_scope,
1879 finalize,
1880 ignore_decl,
1881 ignore_import,
1882 )
1883 } else if let Some(ribs) = ribs
1884 && let Some(TypeNS | ValueNS) = opt_ns
1885 {
1886 if !ignore_import.is_none() {
::core::panicking::panic("assertion failed: ignore_import.is_none()")
};assert!(ignore_import.is_none());
1887 match self.get_mut().resolve_ident_in_lexical_scope(
1888 ident,
1889 ns,
1890 parent_scope,
1891 finalize,
1892 &ribs[ns],
1893 ignore_decl,
1894 diag_metadata,
1895 ) {
1896 Some(LateDecl::Decl(binding)) => Ok(binding),
1898 Some(LateDecl::RibDef(res)) => {
1900 record_segment_res(self.reborrow(), finalize, res, id);
1901 return PathResult::NonModule(PartialRes::with_unresolved_segments(
1902 res,
1903 path.len() - 1,
1904 ));
1905 }
1906 _ => Err(Determinacy::determined(finalize.is_some())),
1907 }
1908 } else {
1909 self.reborrow().resolve_ident_in_scope_set(
1910 ident,
1911 ScopeSet::All(ns),
1912 parent_scope,
1913 finalize,
1914 ignore_decl,
1915 ignore_import,
1916 )
1917 };
1918
1919 match binding {
1920 Ok(binding) => {
1921 if segment_idx == 1 {
1922 second_binding = Some(binding);
1923 }
1924 let res = binding.res();
1925
1926 if finalize.is_some() {
1930 for error in &mut self.get_mut().privacy_errors[privacy_errors_len..] {
1931 error.outermost_res = Some((res, ident));
1932 error.source = match source {
1933 Some(PathSource::Struct(Some(expr)))
1934 | Some(PathSource::Expr(Some(expr))) => Some(expr.clone()),
1935 _ => None,
1936 };
1937 }
1938 }
1939
1940 let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(res);
1941 if let Res::OpenMod(sym) = binding.res() {
1942 module = Some(ModuleOrUniformRoot::OpenModule(sym));
1943 record_segment_res(self.reborrow(), finalize, res, id);
1944 } else if let Some(def_id) = binding.res().module_like_def_id() {
1945 if self.mods_with_parse_errors.contains(&def_id) {
1946 module_had_parse_errors = true;
1947 }
1948 module = Some(ModuleOrUniformRoot::Module(self.expect_module(def_id)));
1949 record_segment_res(self.reborrow(), finalize, res, id);
1950 } else if res == Res::ToolMod && !is_last && opt_ns.is_some() {
1951 if binding.is_import() {
1952 self.dcx().emit_err(errors::ToolModuleImported {
1953 span: ident.span,
1954 import: binding.span,
1955 });
1956 }
1957 let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
1958 return PathResult::NonModule(PartialRes::new(res));
1959 } else if res == Res::Err {
1960 return PathResult::NonModule(PartialRes::new(Res::Err));
1961 } else if opt_ns.is_some() && (is_last || maybe_assoc) {
1962 if let Some(finalize) = finalize {
1963 self.get_mut().lint_if_path_starts_with_module(
1964 finalize,
1965 path,
1966 second_binding,
1967 );
1968 }
1969 record_segment_res(self.reborrow(), finalize, res, id);
1970 return PathResult::NonModule(PartialRes::with_unresolved_segments(
1971 res,
1972 path.len() - segment_idx - 1,
1973 ));
1974 } else {
1975 return PathResult::failed(
1976 ident,
1977 is_last,
1978 finalize.is_some(),
1979 module_had_parse_errors,
1980 module,
1981 || {
1982 let label = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{2}` is {0} {1}, not a module",
res.article(), res.descr(), ident))
})format!(
1983 "`{ident}` is {} {}, not a module",
1984 res.article(),
1985 res.descr()
1986 );
1987 let scope = match &path[..segment_idx] {
1988 [.., prev] => {
1989 if prev.ident.name == kw::PathRoot {
1990 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the crate root"))
})format!("the crate root")
1991 } else {
1992 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", prev.ident))
})format!("`{}`", prev.ident)
1993 }
1994 }
1995 _ => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this scope"))
})format!("this scope"),
1996 };
1997 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}");
2000 (message, label, None)
2001 },
2002 );
2003 }
2004 }
2005 Err(Undetermined) if finalize.is_none() => return PathResult::Indeterminate,
2006 Err(Determined | Undetermined) => {
2007 if let Some(ModuleOrUniformRoot::Module(module)) = module
2008 && opt_ns.is_some()
2009 && !module.is_normal()
2010 {
2011 return PathResult::NonModule(PartialRes::with_unresolved_segments(
2012 module.res().unwrap(),
2013 path.len() - segment_idx,
2014 ));
2015 }
2016
2017 let mut this = self.reborrow();
2018 return PathResult::failed(
2019 ident,
2020 is_last,
2021 finalize.is_some(),
2022 module_had_parse_errors,
2023 module,
2024 || {
2025 this.get_mut().report_path_resolution_error(
2026 path,
2027 opt_ns,
2028 parent_scope,
2029 ribs,
2030 ignore_decl,
2031 ignore_import,
2032 module,
2033 segment_idx,
2034 ident,
2035 diag_metadata,
2036 )
2037 },
2038 );
2039 }
2040 }
2041 }
2042
2043 if let Some(finalize) = finalize {
2044 self.get_mut().lint_if_path_starts_with_module(finalize, path, second_binding);
2045 }
2046
2047 PathResult::Module(match module {
2048 Some(module) => module,
2049 None if path.is_empty() => ModuleOrUniformRoot::CurrentScope,
2050 _ => ::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),
2051 })
2052 }
2053}