1use Determinacy::*;
2use Namespace::*;
3use rustc_ast::{self as ast, NodeId};
4use rustc_errors::ErrorGuaranteed;
5use rustc_hir::def::{DefKind, MacroKinds, Namespace, NonMacroAttrKind, PartialRes, PerNS};
6use rustc_middle::bug;
7use rustc_session::lint::builtin::PROC_MACRO_DERIVE_RESOLUTION_FALLBACK;
8use rustc_session::parse::feature_err;
9use rustc_span::hygiene::{ExpnId, ExpnKind, LocalExpnId, MacroKind, SyntaxContext};
10use rustc_span::{Ident, Span, kw, sym};
11use tracing::{debug, instrument};
12
13use crate::errors::{ParamKindInEnumDiscriminant, ParamKindInNonTrivialAnonConst};
14use crate::imports::{Import, NameResolution};
15use crate::late::{ConstantHasGenerics, NoConstantGenericsReason, PathSource, Rib, RibKind};
16use crate::macros::{MacroRulesScope, sub_namespace_match};
17use crate::{
18 AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, BindingKey, CmResolver, Determinacy,
19 Finalize, ImportKind, LexicalScopeBinding, Module, ModuleKind, ModuleOrUniformRoot,
20 NameBinding, NameBindingKind, ParentScope, PathResult, PrivacyError, Res, ResolutionError,
21 Resolver, Scope, ScopeSet, Segment, Stage, Used, Weak, errors,
22};
23
24#[derive(Copy, Clone)]
25pub enum UsePrelude {
26 No,
27 Yes,
28}
29
30impl From<UsePrelude> for bool {
31 fn from(up: UsePrelude) -> bool {
32 matches!(up, UsePrelude::Yes)
33 }
34}
35
36#[derive(Debug, PartialEq, Clone, Copy)]
37enum Shadowing {
38 Restricted,
39 Unrestricted,
40}
41
42impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
43 pub(crate) fn visit_scopes<'r, T>(
47 mut self: CmResolver<'r, 'ra, 'tcx>,
48 scope_set: ScopeSet<'ra>,
49 parent_scope: &ParentScope<'ra>,
50 ctxt: SyntaxContext,
51 derive_fallback_lint_id: Option<NodeId>,
52 mut visitor: impl FnMut(
53 &mut CmResolver<'r, 'ra, 'tcx>,
54 Scope<'ra>,
55 UsePrelude,
56 SyntaxContext,
57 ) -> Option<T>,
58 ) -> Option<T> {
59 let rust_2015 = ctxt.edition().is_rust_2015();
101 let (ns, macro_kind) = match scope_set {
102 ScopeSet::All(ns) | ScopeSet::ModuleAndExternPrelude(ns, _) => (ns, None),
103 ScopeSet::ExternPrelude => (TypeNS, None),
104 ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind)),
105 };
106 let module = match scope_set {
107 ScopeSet::ModuleAndExternPrelude(_, module) => module,
109 _ => parent_scope.module.nearest_item_scope(),
111 };
112 let module_and_extern_prelude = matches!(scope_set, ScopeSet::ModuleAndExternPrelude(..));
113 let extern_prelude = matches!(scope_set, ScopeSet::ExternPrelude);
114 let mut scope = match ns {
115 _ if module_and_extern_prelude => Scope::Module(module, None),
116 _ if extern_prelude => Scope::ExternPreludeItems,
117 TypeNS | ValueNS => Scope::Module(module, None),
118 MacroNS => Scope::DeriveHelpers(parent_scope.expansion),
119 };
120 let mut ctxt = ctxt.normalize_to_macros_2_0();
121 let mut use_prelude = !module.no_implicit_prelude;
122
123 loop {
124 let visit = match scope {
125 Scope::DeriveHelpers(expn_id) => {
127 !(expn_id == parent_scope.expansion && macro_kind == Some(MacroKind::Derive))
128 }
129 Scope::DeriveHelpersCompat => true,
130 Scope::MacroRules(macro_rules_scope) => {
131 while let MacroRulesScope::Invocation(invoc_id) = macro_rules_scope.get() {
136 if let Some(next_scope) = self.output_macro_rules_scopes.get(&invoc_id) {
137 macro_rules_scope.set(next_scope.get());
138 } else {
139 break;
140 }
141 }
142 true
143 }
144 Scope::Module(..) => true,
145 Scope::MacroUsePrelude => use_prelude || rust_2015,
146 Scope::BuiltinAttrs => true,
147 Scope::ExternPreludeItems | Scope::ExternPreludeFlags => {
148 use_prelude || module_and_extern_prelude || extern_prelude
149 }
150 Scope::ToolPrelude => use_prelude,
151 Scope::StdLibPrelude => use_prelude || ns == MacroNS,
152 Scope::BuiltinTypes => true,
153 };
154
155 if visit {
156 let use_prelude = if use_prelude { UsePrelude::Yes } else { UsePrelude::No };
157 if let break_result @ Some(..) = visitor(&mut self, scope, use_prelude, ctxt) {
158 return break_result;
159 }
160 }
161
162 scope = match scope {
163 Scope::DeriveHelpers(LocalExpnId::ROOT) => Scope::DeriveHelpersCompat,
164 Scope::DeriveHelpers(expn_id) => {
165 let expn_data = expn_id.expn_data();
167 match expn_data.kind {
168 ExpnKind::Root
169 | ExpnKind::Macro(MacroKind::Bang | MacroKind::Derive, _) => {
170 Scope::DeriveHelpersCompat
171 }
172 _ => Scope::DeriveHelpers(expn_data.parent.expect_local()),
173 }
174 }
175 Scope::DeriveHelpersCompat => Scope::MacroRules(parent_scope.macro_rules),
176 Scope::MacroRules(macro_rules_scope) => match macro_rules_scope.get() {
177 MacroRulesScope::Binding(binding) => {
178 Scope::MacroRules(binding.parent_macro_rules_scope)
179 }
180 MacroRulesScope::Invocation(invoc_id) => {
181 Scope::MacroRules(self.invocation_parent_scopes[&invoc_id].macro_rules)
182 }
183 MacroRulesScope::Empty => Scope::Module(module, None),
184 },
185 Scope::Module(..) if module_and_extern_prelude => match ns {
186 TypeNS => {
187 ctxt.adjust(ExpnId::root());
188 Scope::ExternPreludeItems
189 }
190 ValueNS | MacroNS => break,
191 },
192 Scope::Module(module, prev_lint_id) => {
193 use_prelude = !module.no_implicit_prelude;
194 match self.hygienic_lexical_parent(module, &mut ctxt, derive_fallback_lint_id) {
195 Some((parent_module, lint_id)) => {
196 Scope::Module(parent_module, lint_id.or(prev_lint_id))
197 }
198 None => {
199 ctxt.adjust(ExpnId::root());
200 match ns {
201 TypeNS => Scope::ExternPreludeItems,
202 ValueNS => Scope::StdLibPrelude,
203 MacroNS => Scope::MacroUsePrelude,
204 }
205 }
206 }
207 }
208 Scope::MacroUsePrelude => Scope::StdLibPrelude,
209 Scope::BuiltinAttrs => break, Scope::ExternPreludeItems => Scope::ExternPreludeFlags,
211 Scope::ExternPreludeFlags if module_and_extern_prelude || extern_prelude => break,
212 Scope::ExternPreludeFlags => Scope::ToolPrelude,
213 Scope::ToolPrelude => Scope::StdLibPrelude,
214 Scope::StdLibPrelude => match ns {
215 TypeNS => Scope::BuiltinTypes,
216 ValueNS => break, MacroNS => Scope::BuiltinAttrs,
218 },
219 Scope::BuiltinTypes => break, };
221 }
222
223 None
224 }
225
226 fn hygienic_lexical_parent(
227 &self,
228 module: Module<'ra>,
229 ctxt: &mut SyntaxContext,
230 derive_fallback_lint_id: Option<NodeId>,
231 ) -> Option<(Module<'ra>, Option<NodeId>)> {
232 if !module.expansion.outer_expn_is_descendant_of(*ctxt) {
233 return Some((self.expn_def_scope(ctxt.remove_mark()), None));
234 }
235
236 if let ModuleKind::Block = module.kind {
237 return Some((module.parent.unwrap().nearest_item_scope(), None));
238 }
239
240 if derive_fallback_lint_id.is_some()
252 && let Some(parent) = module.parent
253 && module.expansion != parent.expansion
255 && module.expansion.is_descendant_of(parent.expansion)
257 && let Some(def_id) = module.expansion.expn_data().macro_def_id
259 {
260 let ext = &self.get_macro_by_def_id(def_id).ext;
261 if ext.builtin_name.is_none()
262 && ext.macro_kinds() == MacroKinds::DERIVE
263 && parent.expansion.outer_expn_is_descendant_of(*ctxt)
264 {
265 return Some((parent, derive_fallback_lint_id));
266 }
267 }
268
269 None
270 }
271
272 #[instrument(level = "debug", skip(self, ribs))]
290 pub(crate) fn resolve_ident_in_lexical_scope(
291 &mut self,
292 mut ident: Ident,
293 ns: Namespace,
294 parent_scope: &ParentScope<'ra>,
295 finalize: Option<Finalize>,
296 ribs: &[Rib<'ra>],
297 ignore_binding: Option<NameBinding<'ra>>,
298 ) -> Option<LexicalScopeBinding<'ra>> {
299 assert!(ns == TypeNS || ns == ValueNS);
300 let orig_ident = ident;
301 let (general_span, normalized_span) = if ident.name == kw::SelfUpper {
302 let empty_span = ident.span.with_ctxt(SyntaxContext::root());
304 (empty_span, empty_span)
305 } else if ns == TypeNS {
306 let normalized_span = ident.span.normalize_to_macros_2_0();
307 (normalized_span, normalized_span)
308 } else {
309 (ident.span.normalize_to_macro_rules(), ident.span.normalize_to_macros_2_0())
310 };
311 ident.span = general_span;
312 let normalized_ident = Ident { span: normalized_span, ..ident };
313
314 for (i, rib) in ribs.iter().enumerate().rev() {
316 debug!("walk rib\n{:?}", rib.bindings);
317 let rib_ident = if rib.kind.contains_params() { normalized_ident } else { ident };
320 if let Some((original_rib_ident_def, res)) = rib.bindings.get_key_value(&rib_ident) {
321 return Some(LexicalScopeBinding::Res(self.validate_res_from_ribs(
323 i,
324 rib_ident,
325 *res,
326 finalize.map(|finalize| finalize.path_span),
327 *original_rib_ident_def,
328 ribs,
329 )));
330 } else if let RibKind::Block(Some(module)) = rib.kind
331 && let Ok(binding) = self.cm().resolve_ident_in_module_unadjusted(
332 ModuleOrUniformRoot::Module(module),
333 ident,
334 ns,
335 parent_scope,
336 Shadowing::Unrestricted,
337 finalize.map(|finalize| Finalize { used: Used::Scope, ..finalize }),
338 ignore_binding,
339 None,
340 )
341 {
342 return Some(LexicalScopeBinding::Item(binding));
344 } else if let RibKind::Module(module) = rib.kind {
345 let parent_scope = &ParentScope { module, ..*parent_scope };
347 let finalize = finalize.map(|f| Finalize { stage: Stage::Late, ..f });
348 return self
349 .cm()
350 .resolve_ident_in_scope_set(
351 orig_ident,
352 ScopeSet::All(ns),
353 parent_scope,
354 finalize,
355 finalize.is_some(),
356 ignore_binding,
357 None,
358 )
359 .ok()
360 .map(LexicalScopeBinding::Item);
361 }
362
363 if let RibKind::MacroDefinition(def) = rib.kind
364 && def == self.macro_def(ident.span.ctxt())
365 {
366 ident.span.remove_mark();
369 }
370 }
371
372 unreachable!()
373 }
374
375 #[instrument(level = "debug", skip(self))]
377 pub(crate) fn resolve_ident_in_scope_set<'r>(
378 self: CmResolver<'r, 'ra, 'tcx>,
379 orig_ident: Ident,
380 scope_set: ScopeSet<'ra>,
381 parent_scope: &ParentScope<'ra>,
382 finalize: Option<Finalize>,
383 force: bool,
384 ignore_binding: Option<NameBinding<'ra>>,
385 ignore_import: Option<Import<'ra>>,
386 ) -> Result<NameBinding<'ra>, Determinacy> {
387 bitflags::bitflags! {
388 #[derive(Clone, Copy)]
389 struct Flags: u8 {
390 const MACRO_RULES = 1 << 0;
391 const MODULE = 1 << 1;
392 const MISC_SUGGEST_CRATE = 1 << 2;
393 const MISC_SUGGEST_SELF = 1 << 3;
394 const MISC_FROM_PRELUDE = 1 << 4;
395 }
396 }
397
398 assert!(force || finalize.is_none()); if orig_ident.is_path_segment_keyword() {
402 return Err(Determinacy::Determined);
403 }
404
405 let (ns, macro_kind) = match scope_set {
406 ScopeSet::All(ns) | ScopeSet::ModuleAndExternPrelude(ns, _) => (ns, None),
407 ScopeSet::ExternPrelude => (TypeNS, None),
408 ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind)),
409 };
410
411 let mut innermost_result: Option<(NameBinding<'_>, Flags)> = None;
423 let mut determinacy = Determinacy::Determined;
424 let mut extern_prelude_item_binding = None;
425 let mut extern_prelude_flag_binding = None;
426 macro finalize_scope() {
428 if innermost_result.is_none() { finalize } else { None }
429 }
430
431 let derive_fallback_lint_id = match finalize {
433 Some(Finalize { node_id, stage: Stage::Late, .. }) => Some(node_id),
434 _ => None,
435 };
436 let break_result = self.visit_scopes(
437 scope_set,
438 parent_scope,
439 orig_ident.span.ctxt(),
440 derive_fallback_lint_id,
441 |this, scope, use_prelude, ctxt| {
442 let ident = Ident::new(orig_ident.name, orig_ident.span.with_ctxt(ctxt));
443 let result = match scope {
444 Scope::DeriveHelpers(expn_id) => {
445 if let Some(binding) = this.helper_attrs.get(&expn_id).and_then(|attrs| {
446 attrs.iter().rfind(|(i, _)| ident == *i).map(|(_, binding)| *binding)
447 }) {
448 Ok((binding, Flags::empty()))
449 } else {
450 Err(Determinacy::Determined)
451 }
452 }
453 Scope::DeriveHelpersCompat => {
454 let mut result = Err(Determinacy::Determined);
455 for derive in parent_scope.derives {
456 let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
457 match this.reborrow().resolve_macro_path(
458 derive,
459 MacroKind::Derive,
460 parent_scope,
461 true,
462 force,
463 ignore_import,
464 None,
465 ) {
466 Ok((Some(ext), _)) => {
467 if ext.helper_attrs.contains(&ident.name) {
468 let binding = this.arenas.new_pub_res_binding(
469 Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat),
470 derive.span,
471 LocalExpnId::ROOT,
472 );
473 result = Ok((binding, Flags::empty()));
474 break;
475 }
476 }
477 Ok(_) | Err(Determinacy::Determined) => {}
478 Err(Determinacy::Undetermined) => {
479 result = Err(Determinacy::Undetermined)
480 }
481 }
482 }
483 result
484 }
485 Scope::MacroRules(macro_rules_scope) => match macro_rules_scope.get() {
486 MacroRulesScope::Binding(macro_rules_binding)
487 if ident == macro_rules_binding.ident =>
488 {
489 Ok((macro_rules_binding.binding, Flags::MACRO_RULES))
490 }
491 MacroRulesScope::Invocation(_) => Err(Determinacy::Undetermined),
492 _ => Err(Determinacy::Determined),
493 },
494 Scope::Module(module, derive_fallback_lint_id) => {
495 let (adjusted_parent_scope, adjusted_finalize) =
497 if matches!(scope_set, ScopeSet::ModuleAndExternPrelude(..)) {
498 (parent_scope, finalize)
499 } else {
500 (
501 &ParentScope { module, ..*parent_scope },
502 finalize.map(|f| Finalize { used: Used::Scope, ..f }),
503 )
504 };
505 let binding = this.reborrow().resolve_ident_in_module_unadjusted(
506 ModuleOrUniformRoot::Module(module),
507 ident,
508 ns,
509 adjusted_parent_scope,
510 Shadowing::Restricted,
511 adjusted_finalize,
512 ignore_binding,
513 ignore_import,
514 );
515 match binding {
516 Ok(binding) => {
517 if let Some(lint_id) = derive_fallback_lint_id {
518 this.get_mut().lint_buffer.buffer_lint(
519 PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
520 lint_id,
521 orig_ident.span,
522 errors::ProcMacroDeriveResolutionFallback {
523 span: orig_ident.span,
524 ns_descr: ns.descr(),
525 ident,
526 },
527 );
528 }
529 let misc_flags = if module == this.graph_root {
530 Flags::MISC_SUGGEST_CRATE
531 } else if module.is_normal() {
532 Flags::MISC_SUGGEST_SELF
533 } else {
534 Flags::empty()
535 };
536 Ok((binding, Flags::MODULE | misc_flags))
537 }
538 Err((Determinacy::Undetermined, Weak::No)) => {
539 return Some(Err(Determinacy::determined(force)));
540 }
541 Err((Determinacy::Undetermined, Weak::Yes)) => {
542 Err(Determinacy::Undetermined)
543 }
544 Err((Determinacy::Determined, _)) => Err(Determinacy::Determined),
545 }
546 }
547 Scope::MacroUsePrelude => {
548 match this.macro_use_prelude.get(&ident.name).cloned() {
549 Some(binding) => Ok((binding, Flags::MISC_FROM_PRELUDE)),
550 None => Err(Determinacy::determined(
551 this.graph_root.unexpanded_invocations.borrow().is_empty(),
552 )),
553 }
554 }
555 Scope::BuiltinAttrs => match this.builtin_attrs_bindings.get(&ident.name) {
556 Some(binding) => Ok((*binding, Flags::empty())),
557 None => Err(Determinacy::Determined),
558 },
559 Scope::ExternPreludeItems => {
560 match this.reborrow().extern_prelude_get_item(ident, finalize.is_some()) {
562 Some(binding) => {
563 extern_prelude_item_binding = Some(binding);
564 Ok((binding, Flags::empty()))
565 }
566 None => Err(Determinacy::determined(
567 this.graph_root.unexpanded_invocations.borrow().is_empty(),
568 )),
569 }
570 }
571 Scope::ExternPreludeFlags => {
572 match this.extern_prelude_get_flag(ident, finalize_scope!().is_some()) {
573 Some(binding) => {
574 extern_prelude_flag_binding = Some(binding);
575 Ok((binding, Flags::empty()))
576 }
577 None => Err(Determinacy::Determined),
578 }
579 }
580 Scope::ToolPrelude => match this.registered_tool_bindings.get(&ident) {
581 Some(binding) => Ok((*binding, Flags::empty())),
582 None => Err(Determinacy::Determined),
583 },
584 Scope::StdLibPrelude => {
585 let mut result = Err(Determinacy::Determined);
586 if let Some(prelude) = this.prelude
587 && let Ok(binding) = this.reborrow().resolve_ident_in_module_unadjusted(
588 ModuleOrUniformRoot::Module(prelude),
589 ident,
590 ns,
591 parent_scope,
592 Shadowing::Unrestricted,
593 None,
594 ignore_binding,
595 ignore_import,
596 )
597 && (matches!(use_prelude, UsePrelude::Yes)
598 || this.is_builtin_macro(binding.res()))
599 {
600 result = Ok((binding, Flags::MISC_FROM_PRELUDE));
601 }
602
603 result
604 }
605 Scope::BuiltinTypes => match this.builtin_types_bindings.get(&ident.name) {
606 Some(binding) => {
607 if matches!(ident.name, sym::f16)
608 && !this.tcx.features().f16()
609 && !ident.span.allows_unstable(sym::f16)
610 && finalize_scope!().is_some()
611 {
612 feature_err(
613 this.tcx.sess,
614 sym::f16,
615 ident.span,
616 "the type `f16` is unstable",
617 )
618 .emit();
619 }
620 if matches!(ident.name, sym::f128)
621 && !this.tcx.features().f128()
622 && !ident.span.allows_unstable(sym::f128)
623 && finalize_scope!().is_some()
624 {
625 feature_err(
626 this.tcx.sess,
627 sym::f128,
628 ident.span,
629 "the type `f128` is unstable",
630 )
631 .emit();
632 }
633 Ok((*binding, Flags::empty()))
634 }
635 None => Err(Determinacy::Determined),
636 },
637 };
638
639 match result {
640 Ok((binding, flags)) => {
641 if !sub_namespace_match(binding.macro_kinds(), macro_kind) {
642 return None;
643 }
644
645 if matches!(finalize, None | Some(Finalize { stage: Stage::Late, .. })) {
650 return Some(Ok(binding));
651 }
652
653 if let Some((innermost_binding, innermost_flags)) = innermost_result {
654 let (res, innermost_res) = (binding.res(), innermost_binding.res());
656 if res != innermost_res {
657 let is_builtin = |res| {
658 matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Builtin(..)))
659 };
660 let derive_helper =
661 Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
662 let derive_helper_compat =
663 Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
664
665 let ambiguity_error_kind = if is_builtin(innermost_res)
666 || is_builtin(res)
667 {
668 Some(AmbiguityKind::BuiltinAttr)
669 } else if innermost_res == derive_helper_compat
670 || res == derive_helper_compat && innermost_res != derive_helper
671 {
672 Some(AmbiguityKind::DeriveHelper)
673 } else if innermost_flags.contains(Flags::MACRO_RULES)
674 && flags.contains(Flags::MODULE)
675 && !this.disambiguate_macro_rules_vs_modularized(
676 innermost_binding,
677 binding,
678 )
679 || flags.contains(Flags::MACRO_RULES)
680 && innermost_flags.contains(Flags::MODULE)
681 && !this.disambiguate_macro_rules_vs_modularized(
682 binding,
683 innermost_binding,
684 )
685 {
686 Some(AmbiguityKind::MacroRulesVsModularized)
687 } else if innermost_binding.is_glob_import() {
688 Some(AmbiguityKind::GlobVsOuter)
689 } else if innermost_binding
690 .may_appear_after(parent_scope.expansion, binding)
691 {
692 Some(AmbiguityKind::MoreExpandedVsOuter)
693 } else {
694 None
695 };
696 let issue_145575_hack = Some(binding)
700 == extern_prelude_flag_binding
701 && extern_prelude_item_binding.is_some()
702 && extern_prelude_item_binding != Some(innermost_binding);
703 if let Some(kind) = ambiguity_error_kind
704 && !issue_145575_hack
705 {
706 let misc = |f: Flags| {
707 if f.contains(Flags::MISC_SUGGEST_CRATE) {
708 AmbiguityErrorMisc::SuggestCrate
709 } else if f.contains(Flags::MISC_SUGGEST_SELF) {
710 AmbiguityErrorMisc::SuggestSelf
711 } else if f.contains(Flags::MISC_FROM_PRELUDE) {
712 AmbiguityErrorMisc::FromPrelude
713 } else {
714 AmbiguityErrorMisc::None
715 }
716 };
717 this.get_mut().ambiguity_errors.push(AmbiguityError {
718 kind,
719 ident: orig_ident,
720 b1: innermost_binding,
721 b2: binding,
722 warning: false,
723 misc1: misc(innermost_flags),
724 misc2: misc(flags),
725 });
726 return Some(Ok(innermost_binding));
727 }
728 }
729 } else {
730 innermost_result = Some((binding, flags));
732 }
733 }
734 Err(Determinacy::Determined) => {}
735 Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined,
736 }
737
738 None
739 },
740 );
741
742 if let Some(break_result) = break_result {
743 return break_result;
744 }
745
746 if let Some((binding, _)) = innermost_result {
748 return Ok(binding);
749 }
750
751 Err(Determinacy::determined(determinacy == Determinacy::Determined || force))
752 }
753
754 #[instrument(level = "debug", skip(self))]
755 pub(crate) fn maybe_resolve_ident_in_module<'r>(
756 self: CmResolver<'r, 'ra, 'tcx>,
757 module: ModuleOrUniformRoot<'ra>,
758 ident: Ident,
759 ns: Namespace,
760 parent_scope: &ParentScope<'ra>,
761 ignore_import: Option<Import<'ra>>,
762 ) -> Result<NameBinding<'ra>, Determinacy> {
763 self.resolve_ident_in_module(module, ident, ns, parent_scope, None, None, ignore_import)
764 .map_err(|(determinacy, _)| determinacy)
765 }
766
767 #[instrument(level = "debug", skip(self))]
768 pub(crate) fn resolve_ident_in_module<'r>(
769 self: CmResolver<'r, 'ra, 'tcx>,
770 module: ModuleOrUniformRoot<'ra>,
771 mut ident: Ident,
772 ns: Namespace,
773 parent_scope: &ParentScope<'ra>,
774 finalize: Option<Finalize>,
775 ignore_binding: Option<NameBinding<'ra>>,
776 ignore_import: Option<Import<'ra>>,
777 ) -> Result<NameBinding<'ra>, (Determinacy, Weak)> {
778 let tmp_parent_scope;
779 let mut adjusted_parent_scope = parent_scope;
780 match module {
781 ModuleOrUniformRoot::Module(m) => {
782 if let Some(def) = ident.span.normalize_to_macros_2_0_and_adjust(m.expansion) {
783 tmp_parent_scope =
784 ParentScope { module: self.expn_def_scope(def), ..*parent_scope };
785 adjusted_parent_scope = &tmp_parent_scope;
786 }
787 }
788 ModuleOrUniformRoot::ExternPrelude => {
789 ident.span.normalize_to_macros_2_0_and_adjust(ExpnId::root());
790 }
791 ModuleOrUniformRoot::ModuleAndExternPrelude(..) | ModuleOrUniformRoot::CurrentScope => {
792 }
794 }
795 self.resolve_ident_in_module_unadjusted(
796 module,
797 ident,
798 ns,
799 adjusted_parent_scope,
800 Shadowing::Unrestricted,
801 finalize,
802 ignore_binding,
803 ignore_import,
804 )
805 }
806 #[instrument(level = "debug", skip(self))]
809 fn resolve_ident_in_module_unadjusted<'r>(
810 mut self: CmResolver<'r, 'ra, 'tcx>,
811 module: ModuleOrUniformRoot<'ra>,
812 ident: Ident,
813 ns: Namespace,
814 parent_scope: &ParentScope<'ra>,
815 shadowing: Shadowing,
816 finalize: Option<Finalize>,
817 ignore_binding: Option<NameBinding<'ra>>,
820 ignore_import: Option<Import<'ra>>,
821 ) -> Result<NameBinding<'ra>, (Determinacy, Weak)> {
822 let module = match module {
823 ModuleOrUniformRoot::Module(module) => module,
824 ModuleOrUniformRoot::ModuleAndExternPrelude(module) => {
825 assert_eq!(shadowing, Shadowing::Unrestricted);
826 let binding = self.resolve_ident_in_scope_set(
827 ident,
828 ScopeSet::ModuleAndExternPrelude(ns, module),
829 parent_scope,
830 finalize,
831 finalize.is_some(),
832 ignore_binding,
833 ignore_import,
834 );
835 return binding.map_err(|determinacy| (determinacy, Weak::No));
836 }
837 ModuleOrUniformRoot::ExternPrelude => {
838 assert_eq!(shadowing, Shadowing::Unrestricted);
839 return if ns != TypeNS {
840 Err((Determined, Weak::No))
841 } else {
842 let binding = self.resolve_ident_in_scope_set(
843 ident,
844 ScopeSet::ExternPrelude,
845 parent_scope,
846 finalize,
847 finalize.is_some(),
848 ignore_binding,
849 ignore_import,
850 );
851 return binding.map_err(|determinacy| (determinacy, Weak::No));
852 };
853 }
854 ModuleOrUniformRoot::CurrentScope => {
855 assert_eq!(shadowing, Shadowing::Unrestricted);
856 if ns == TypeNS {
857 if ident.name == kw::Crate || ident.name == kw::DollarCrate {
858 let module = self.resolve_crate_root(ident);
859 return Ok(module.self_binding.unwrap());
860 } else if ident.name == kw::Super || ident.name == kw::SelfLower {
861 }
865 }
866
867 let binding = self.resolve_ident_in_scope_set(
868 ident,
869 ScopeSet::All(ns),
870 parent_scope,
871 finalize,
872 finalize.is_some(),
873 ignore_binding,
874 ignore_import,
875 );
876 return binding.map_err(|determinacy| (determinacy, Weak::No));
877 }
878 };
879
880 let key = BindingKey::new(ident, ns);
881 let resolution = &*self
885 .resolution_or_default(module, key)
886 .try_borrow_mut()
887 .map_err(|_| (Determined, Weak::No))?;
888
889 let binding = [resolution.non_glob_binding, resolution.glob_binding]
894 .into_iter()
895 .find_map(|binding| if binding == ignore_binding { None } else { binding });
896
897 if let Some(finalize) = finalize {
898 return self.get_mut().finalize_module_binding(
899 ident,
900 binding,
901 if resolution.non_glob_binding.is_some() { resolution.glob_binding } else { None },
902 parent_scope,
903 finalize,
904 shadowing,
905 );
906 }
907
908 let check_usable = |this: CmResolver<'r, 'ra, 'tcx>, binding: NameBinding<'ra>| {
909 let usable = this.is_accessible_from(binding.vis, parent_scope.module);
910 if usable { Ok(binding) } else { Err((Determined, Weak::No)) }
911 };
912
913 if let Some(binding) = binding
915 && !binding.is_glob_import()
916 {
917 return check_usable(self, binding);
918 }
919
920 if self.reborrow().single_import_can_define_name(
925 &resolution,
926 binding,
927 ns,
928 ignore_import,
929 ignore_binding,
930 parent_scope,
931 ) {
932 return Err((Undetermined, Weak::No));
933 }
934
935 if let Some(binding) = binding {
948 if binding.determined() || ns == MacroNS || shadowing == Shadowing::Restricted {
949 return check_usable(self, binding);
950 } else {
951 return Err((Undetermined, Weak::No));
952 }
953 }
954
955 if !module.unexpanded_invocations.borrow().is_empty() {
966 return Err((Undetermined, Weak::Yes));
967 }
968
969 for glob_import in module.globs.borrow().iter() {
972 if ignore_import == Some(*glob_import) {
973 continue;
974 }
975 if !self.is_accessible_from(glob_import.vis, parent_scope.module) {
976 continue;
977 }
978 let module = match glob_import.imported_module.get() {
979 Some(ModuleOrUniformRoot::Module(module)) => module,
980 Some(_) => continue,
981 None => return Err((Undetermined, Weak::Yes)),
982 };
983 let tmp_parent_scope;
984 let (mut adjusted_parent_scope, mut ident) =
985 (parent_scope, ident.normalize_to_macros_2_0());
986 match ident.span.glob_adjust(module.expansion, glob_import.span) {
987 Some(Some(def)) => {
988 tmp_parent_scope =
989 ParentScope { module: self.expn_def_scope(def), ..*parent_scope };
990 adjusted_parent_scope = &tmp_parent_scope;
991 }
992 Some(None) => {}
993 None => continue,
994 };
995 let result = self.reborrow().resolve_ident_in_module_unadjusted(
996 ModuleOrUniformRoot::Module(module),
997 ident,
998 ns,
999 adjusted_parent_scope,
1000 Shadowing::Unrestricted,
1001 None,
1002 ignore_binding,
1003 ignore_import,
1004 );
1005
1006 match result {
1007 Err((Determined, _)) => continue,
1008 Ok(binding)
1009 if !self.is_accessible_from(binding.vis, glob_import.parent_scope.module) =>
1010 {
1011 continue;
1012 }
1013 Ok(_) | Err((Undetermined, _)) => return Err((Undetermined, Weak::Yes)),
1014 }
1015 }
1016
1017 Err((Determined, Weak::No))
1019 }
1020
1021 fn finalize_module_binding(
1022 &mut self,
1023 ident: Ident,
1024 binding: Option<NameBinding<'ra>>,
1025 shadowed_glob: Option<NameBinding<'ra>>,
1026 parent_scope: &ParentScope<'ra>,
1027 finalize: Finalize,
1028 shadowing: Shadowing,
1029 ) -> Result<NameBinding<'ra>, (Determinacy, Weak)> {
1030 let Finalize { path_span, report_private, used, root_span, .. } = finalize;
1031
1032 let Some(binding) = binding else {
1033 return Err((Determined, Weak::No));
1034 };
1035
1036 if !self.is_accessible_from(binding.vis, parent_scope.module) {
1037 if report_private {
1038 self.privacy_errors.push(PrivacyError {
1039 ident,
1040 binding,
1041 dedup_span: path_span,
1042 outermost_res: None,
1043 source: None,
1044 parent_scope: *parent_scope,
1045 single_nested: path_span != root_span,
1046 });
1047 } else {
1048 return Err((Determined, Weak::No));
1049 }
1050 }
1051
1052 if let Some(shadowed_glob) = shadowed_glob
1054 && shadowing == Shadowing::Restricted
1055 && finalize.stage == Stage::Early
1056 && binding.expansion != LocalExpnId::ROOT
1057 && binding.res() != shadowed_glob.res()
1058 {
1059 self.ambiguity_errors.push(AmbiguityError {
1060 kind: AmbiguityKind::GlobVsExpanded,
1061 ident,
1062 b1: binding,
1063 b2: shadowed_glob,
1064 warning: false,
1065 misc1: AmbiguityErrorMisc::None,
1066 misc2: AmbiguityErrorMisc::None,
1067 });
1068 }
1069
1070 if shadowing == Shadowing::Unrestricted
1071 && binding.expansion != LocalExpnId::ROOT
1072 && let NameBindingKind::Import { import, .. } = binding.kind
1073 && matches!(import.kind, ImportKind::MacroExport)
1074 {
1075 self.macro_expanded_macro_export_errors.insert((path_span, binding.span));
1076 }
1077
1078 self.record_use(ident, binding, used);
1079 return Ok(binding);
1080 }
1081
1082 fn single_import_can_define_name<'r>(
1085 mut self: CmResolver<'r, 'ra, 'tcx>,
1086 resolution: &NameResolution<'ra>,
1087 binding: Option<NameBinding<'ra>>,
1088 ns: Namespace,
1089 ignore_import: Option<Import<'ra>>,
1090 ignore_binding: Option<NameBinding<'ra>>,
1091 parent_scope: &ParentScope<'ra>,
1092 ) -> bool {
1093 for single_import in &resolution.single_imports {
1094 if ignore_import == Some(*single_import) {
1095 continue;
1096 }
1097 if !self.is_accessible_from(single_import.vis, parent_scope.module) {
1098 continue;
1099 }
1100 if let Some(ignored) = ignore_binding
1101 && let NameBindingKind::Import { import, .. } = ignored.kind
1102 && import == *single_import
1103 {
1104 continue;
1105 }
1106
1107 let Some(module) = single_import.imported_module.get() else {
1108 return true;
1109 };
1110 let ImportKind::Single { source, target, bindings, .. } = &single_import.kind else {
1111 unreachable!();
1112 };
1113 if source != target {
1114 if bindings.iter().all(|binding| binding.get().binding().is_none()) {
1115 return true;
1116 } else if bindings[ns].get().binding().is_none() && binding.is_some() {
1117 return true;
1118 }
1119 }
1120
1121 match self.reborrow().resolve_ident_in_module(
1122 module,
1123 *source,
1124 ns,
1125 &single_import.parent_scope,
1126 None,
1127 ignore_binding,
1128 ignore_import,
1129 ) {
1130 Err((Determined, _)) => continue,
1131 Ok(binding)
1132 if !self.is_accessible_from(binding.vis, single_import.parent_scope.module) =>
1133 {
1134 continue;
1135 }
1136 Ok(_) | Err((Undetermined, _)) => {
1137 return true;
1138 }
1139 }
1140 }
1141
1142 false
1143 }
1144
1145 #[instrument(level = "debug", skip(self, all_ribs))]
1147 fn validate_res_from_ribs(
1148 &mut self,
1149 rib_index: usize,
1150 rib_ident: Ident,
1151 mut res: Res,
1152 finalize: Option<Span>,
1153 original_rib_ident_def: Ident,
1154 all_ribs: &[Rib<'ra>],
1155 ) -> Res {
1156 debug!("validate_res_from_ribs({:?})", res);
1157 let ribs = &all_ribs[rib_index + 1..];
1158
1159 if let RibKind::ForwardGenericParamBan(reason) = all_ribs[rib_index].kind {
1162 if let Some(span) = finalize {
1163 let res_error = if rib_ident.name == kw::SelfUpper {
1164 ResolutionError::ForwardDeclaredSelf(reason)
1165 } else {
1166 ResolutionError::ForwardDeclaredGenericParam(rib_ident.name, reason)
1167 };
1168 self.report_error(span, res_error);
1169 }
1170 assert_eq!(res, Res::Err);
1171 return Res::Err;
1172 }
1173
1174 match res {
1175 Res::Local(_) => {
1176 use ResolutionError::*;
1177 let mut res_err = None;
1178
1179 for rib in ribs {
1180 match rib.kind {
1181 RibKind::Normal
1182 | RibKind::Block(..)
1183 | RibKind::FnOrCoroutine
1184 | RibKind::Module(..)
1185 | RibKind::MacroDefinition(..)
1186 | RibKind::ForwardGenericParamBan(_) => {
1187 }
1189 RibKind::Item(..) | RibKind::AssocItem => {
1190 if let Some(span) = finalize {
1194 res_err = Some((span, CannotCaptureDynamicEnvironmentInFnItem));
1199 }
1200 }
1201 RibKind::ConstantItem(_, item) => {
1202 if let Some(span) = finalize {
1204 let (span, resolution_error) = match item {
1205 None if rib_ident.name == kw::SelfLower => {
1206 (span, LowercaseSelf)
1207 }
1208 None => {
1209 let sm = self.tcx.sess.source_map();
1215 let type_span = match sm.span_look_ahead(
1216 original_rib_ident_def.span,
1217 ":",
1218 None,
1219 ) {
1220 None => {
1221 Some(original_rib_ident_def.span.shrink_to_hi())
1222 }
1223 Some(_) => None,
1224 };
1225 (
1226 rib_ident.span,
1227 AttemptToUseNonConstantValueInConstant {
1228 ident: original_rib_ident_def,
1229 suggestion: "const",
1230 current: "let",
1231 type_span,
1232 },
1233 )
1234 }
1235 Some((ident, kind)) => (
1236 span,
1237 AttemptToUseNonConstantValueInConstant {
1238 ident,
1239 suggestion: "let",
1240 current: kind.as_str(),
1241 type_span: None,
1242 },
1243 ),
1244 };
1245 self.report_error(span, resolution_error);
1246 }
1247 return Res::Err;
1248 }
1249 RibKind::ConstParamTy => {
1250 if let Some(span) = finalize {
1251 self.report_error(
1252 span,
1253 ParamInTyOfConstParam { name: rib_ident.name },
1254 );
1255 }
1256 return Res::Err;
1257 }
1258 RibKind::InlineAsmSym => {
1259 if let Some(span) = finalize {
1260 self.report_error(span, InvalidAsmSym);
1261 }
1262 return Res::Err;
1263 }
1264 }
1265 }
1266 if let Some((span, res_err)) = res_err {
1267 self.report_error(span, res_err);
1268 return Res::Err;
1269 }
1270 }
1271 Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } => {
1272 for rib in ribs {
1273 let (has_generic_params, def_kind) = match rib.kind {
1274 RibKind::Normal
1275 | RibKind::Block(..)
1276 | RibKind::FnOrCoroutine
1277 | RibKind::Module(..)
1278 | RibKind::MacroDefinition(..)
1279 | RibKind::InlineAsmSym
1280 | RibKind::AssocItem
1281 | RibKind::ForwardGenericParamBan(_) => {
1282 continue;
1284 }
1285
1286 RibKind::ConstParamTy => {
1287 if !self.tcx.features().generic_const_parameter_types() {
1288 if let Some(span) = finalize {
1289 self.report_error(
1290 span,
1291 ResolutionError::ParamInTyOfConstParam {
1292 name: rib_ident.name,
1293 },
1294 );
1295 }
1296 return Res::Err;
1297 } else {
1298 continue;
1299 }
1300 }
1301
1302 RibKind::ConstantItem(trivial, _) => {
1303 if let ConstantHasGenerics::No(cause) = trivial {
1304 if let Res::SelfTyAlias {
1309 alias_to: def,
1310 forbid_generic: _,
1311 is_trait_impl,
1312 } = res
1313 {
1314 res = Res::SelfTyAlias {
1315 alias_to: def,
1316 forbid_generic: true,
1317 is_trait_impl,
1318 }
1319 } else {
1320 if let Some(span) = finalize {
1321 let error = match cause {
1322 NoConstantGenericsReason::IsEnumDiscriminant => {
1323 ResolutionError::ParamInEnumDiscriminant {
1324 name: rib_ident.name,
1325 param_kind: ParamKindInEnumDiscriminant::Type,
1326 }
1327 }
1328 NoConstantGenericsReason::NonTrivialConstArg => {
1329 ResolutionError::ParamInNonTrivialAnonConst {
1330 name: rib_ident.name,
1331 param_kind:
1332 ParamKindInNonTrivialAnonConst::Type,
1333 }
1334 }
1335 };
1336 let _: ErrorGuaranteed = self.report_error(span, error);
1337 }
1338
1339 return Res::Err;
1340 }
1341 }
1342
1343 continue;
1344 }
1345
1346 RibKind::Item(has_generic_params, def_kind) => {
1348 (has_generic_params, def_kind)
1349 }
1350 };
1351
1352 if let Some(span) = finalize {
1353 self.report_error(
1354 span,
1355 ResolutionError::GenericParamsFromOuterItem(
1356 res,
1357 has_generic_params,
1358 def_kind,
1359 ),
1360 );
1361 }
1362 return Res::Err;
1363 }
1364 }
1365 Res::Def(DefKind::ConstParam, _) => {
1366 for rib in ribs {
1367 let (has_generic_params, def_kind) = match rib.kind {
1368 RibKind::Normal
1369 | RibKind::Block(..)
1370 | RibKind::FnOrCoroutine
1371 | RibKind::Module(..)
1372 | RibKind::MacroDefinition(..)
1373 | RibKind::InlineAsmSym
1374 | RibKind::AssocItem
1375 | RibKind::ForwardGenericParamBan(_) => continue,
1376
1377 RibKind::ConstParamTy => {
1378 if !self.tcx.features().generic_const_parameter_types() {
1379 if let Some(span) = finalize {
1380 self.report_error(
1381 span,
1382 ResolutionError::ParamInTyOfConstParam {
1383 name: rib_ident.name,
1384 },
1385 );
1386 }
1387 return Res::Err;
1388 } else {
1389 continue;
1390 }
1391 }
1392
1393 RibKind::ConstantItem(trivial, _) => {
1394 if let ConstantHasGenerics::No(cause) = trivial {
1395 if let Some(span) = finalize {
1396 let error = match cause {
1397 NoConstantGenericsReason::IsEnumDiscriminant => {
1398 ResolutionError::ParamInEnumDiscriminant {
1399 name: rib_ident.name,
1400 param_kind: ParamKindInEnumDiscriminant::Const,
1401 }
1402 }
1403 NoConstantGenericsReason::NonTrivialConstArg => {
1404 ResolutionError::ParamInNonTrivialAnonConst {
1405 name: rib_ident.name,
1406 param_kind: ParamKindInNonTrivialAnonConst::Const {
1407 name: rib_ident.name,
1408 },
1409 }
1410 }
1411 };
1412 self.report_error(span, error);
1413 }
1414
1415 return Res::Err;
1416 }
1417
1418 continue;
1419 }
1420
1421 RibKind::Item(has_generic_params, def_kind) => {
1422 (has_generic_params, def_kind)
1423 }
1424 };
1425
1426 if let Some(span) = finalize {
1428 self.report_error(
1429 span,
1430 ResolutionError::GenericParamsFromOuterItem(
1431 res,
1432 has_generic_params,
1433 def_kind,
1434 ),
1435 );
1436 }
1437 return Res::Err;
1438 }
1439 }
1440 _ => {}
1441 }
1442
1443 res
1444 }
1445
1446 #[instrument(level = "debug", skip(self))]
1447 pub(crate) fn maybe_resolve_path<'r>(
1448 self: CmResolver<'r, 'ra, 'tcx>,
1449 path: &[Segment],
1450 opt_ns: Option<Namespace>, parent_scope: &ParentScope<'ra>,
1452 ignore_import: Option<Import<'ra>>,
1453 ) -> PathResult<'ra> {
1454 self.resolve_path_with_ribs(
1455 path,
1456 opt_ns,
1457 parent_scope,
1458 None,
1459 None,
1460 None,
1461 None,
1462 ignore_import,
1463 )
1464 }
1465 #[instrument(level = "debug", skip(self))]
1466 pub(crate) fn resolve_path<'r>(
1467 self: CmResolver<'r, 'ra, 'tcx>,
1468 path: &[Segment],
1469 opt_ns: Option<Namespace>, parent_scope: &ParentScope<'ra>,
1471 finalize: Option<Finalize>,
1472 ignore_binding: Option<NameBinding<'ra>>,
1473 ignore_import: Option<Import<'ra>>,
1474 ) -> PathResult<'ra> {
1475 self.resolve_path_with_ribs(
1476 path,
1477 opt_ns,
1478 parent_scope,
1479 None,
1480 finalize,
1481 None,
1482 ignore_binding,
1483 ignore_import,
1484 )
1485 }
1486
1487 pub(crate) fn resolve_path_with_ribs<'r>(
1488 mut self: CmResolver<'r, 'ra, 'tcx>,
1489 path: &[Segment],
1490 opt_ns: Option<Namespace>, parent_scope: &ParentScope<'ra>,
1492 source: Option<PathSource<'_, '_, '_>>,
1493 finalize: Option<Finalize>,
1494 ribs: Option<&PerNS<Vec<Rib<'ra>>>>,
1495 ignore_binding: Option<NameBinding<'ra>>,
1496 ignore_import: Option<Import<'ra>>,
1497 ) -> PathResult<'ra> {
1498 let mut module = None;
1499 let mut module_had_parse_errors = false;
1500 let mut allow_super = true;
1501 let mut second_binding = None;
1502
1503 let privacy_errors_len = self.privacy_errors.len();
1505 fn record_segment_res<'r, 'ra, 'tcx>(
1506 mut this: CmResolver<'r, 'ra, 'tcx>,
1507 finalize: Option<Finalize>,
1508 res: Res,
1509 id: Option<NodeId>,
1510 ) {
1511 if finalize.is_some()
1512 && let Some(id) = id
1513 && !this.partial_res_map.contains_key(&id)
1514 {
1515 assert!(id != ast::DUMMY_NODE_ID, "Trying to resolve dummy id");
1516 this.get_mut().record_partial_res(id, PartialRes::new(res));
1517 }
1518 }
1519
1520 for (segment_idx, &Segment { ident, id, .. }) in path.iter().enumerate() {
1521 debug!("resolve_path ident {} {:?} {:?}", segment_idx, ident, id);
1522
1523 let is_last = segment_idx + 1 == path.len();
1524 let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
1525 let name = ident.name;
1526
1527 allow_super &= ns == TypeNS && (name == kw::SelfLower || name == kw::Super);
1528
1529 if ns == TypeNS {
1530 if allow_super && name == kw::Super {
1531 let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
1532 let self_module = match segment_idx {
1533 0 => Some(self.resolve_self(&mut ctxt, parent_scope.module)),
1534 _ => match module {
1535 Some(ModuleOrUniformRoot::Module(module)) => Some(module),
1536 _ => None,
1537 },
1538 };
1539 if let Some(self_module) = self_module
1540 && let Some(parent) = self_module.parent
1541 {
1542 module =
1543 Some(ModuleOrUniformRoot::Module(self.resolve_self(&mut ctxt, parent)));
1544 continue;
1545 }
1546 return PathResult::failed(
1547 ident,
1548 false,
1549 finalize.is_some(),
1550 module_had_parse_errors,
1551 module,
1552 || ("there are too many leading `super` keywords".to_string(), None),
1553 );
1554 }
1555 if segment_idx == 0 {
1556 if name == kw::SelfLower {
1557 let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
1558 let self_mod = self.resolve_self(&mut ctxt, parent_scope.module);
1559 if let Some(res) = self_mod.res() {
1560 record_segment_res(self.reborrow(), finalize, res, id);
1561 }
1562 module = Some(ModuleOrUniformRoot::Module(self_mod));
1563 continue;
1564 }
1565 if name == kw::PathRoot && ident.span.at_least_rust_2018() {
1566 module = Some(ModuleOrUniformRoot::ExternPrelude);
1567 continue;
1568 }
1569 if name == kw::PathRoot
1570 && ident.span.is_rust_2015()
1571 && self.tcx.sess.at_least_rust_2018()
1572 {
1573 let crate_root = self.resolve_crate_root(ident);
1575 module = Some(ModuleOrUniformRoot::ModuleAndExternPrelude(crate_root));
1576 continue;
1577 }
1578 if name == kw::PathRoot || name == kw::Crate || name == kw::DollarCrate {
1579 let crate_root = self.resolve_crate_root(ident);
1581 if let Some(res) = crate_root.res() {
1582 record_segment_res(self.reborrow(), finalize, res, id);
1583 }
1584 module = Some(ModuleOrUniformRoot::Module(crate_root));
1585 continue;
1586 }
1587 }
1588 }
1589
1590 if ident.is_path_segment_keyword() && segment_idx != 0 {
1592 return PathResult::failed(
1593 ident,
1594 false,
1595 finalize.is_some(),
1596 module_had_parse_errors,
1597 module,
1598 || {
1599 let name_str = if name == kw::PathRoot {
1600 "crate root".to_string()
1601 } else {
1602 format!("`{name}`")
1603 };
1604 let label = if segment_idx == 1 && path[0].ident.name == kw::PathRoot {
1605 format!("global paths cannot start with {name_str}")
1606 } else {
1607 format!("{name_str} in paths can only be used in start position")
1608 };
1609 (label, None)
1610 },
1611 );
1612 }
1613
1614 let binding = if let Some(module) = module {
1615 self.reborrow()
1616 .resolve_ident_in_module(
1617 module,
1618 ident,
1619 ns,
1620 parent_scope,
1621 finalize,
1622 ignore_binding,
1623 ignore_import,
1624 )
1625 .map_err(|(determinacy, _)| determinacy)
1626 } else if let Some(ribs) = ribs
1627 && let Some(TypeNS | ValueNS) = opt_ns
1628 {
1629 assert!(ignore_import.is_none());
1630 match self.get_mut().resolve_ident_in_lexical_scope(
1631 ident,
1632 ns,
1633 parent_scope,
1634 finalize,
1635 &ribs[ns],
1636 ignore_binding,
1637 ) {
1638 Some(LexicalScopeBinding::Item(binding)) => Ok(binding),
1640 Some(LexicalScopeBinding::Res(res)) => {
1642 record_segment_res(self.reborrow(), finalize, res, id);
1643 return PathResult::NonModule(PartialRes::with_unresolved_segments(
1644 res,
1645 path.len() - 1,
1646 ));
1647 }
1648 _ => Err(Determinacy::determined(finalize.is_some())),
1649 }
1650 } else {
1651 self.reborrow().resolve_ident_in_scope_set(
1652 ident,
1653 ScopeSet::All(ns),
1654 parent_scope,
1655 finalize,
1656 finalize.is_some(),
1657 ignore_binding,
1658 ignore_import,
1659 )
1660 };
1661
1662 match binding {
1663 Ok(binding) => {
1664 if segment_idx == 1 {
1665 second_binding = Some(binding);
1666 }
1667 let res = binding.res();
1668
1669 if finalize.is_some() {
1673 for error in &mut self.get_mut().privacy_errors[privacy_errors_len..] {
1674 error.outermost_res = Some((res, ident));
1675 error.source = match source {
1676 Some(PathSource::Struct(Some(expr)))
1677 | Some(PathSource::Expr(Some(expr))) => Some(expr.clone()),
1678 _ => None,
1679 };
1680 }
1681 }
1682
1683 let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(res);
1684 if let Some(def_id) = binding.res().module_like_def_id() {
1685 if self.mods_with_parse_errors.contains(&def_id) {
1686 module_had_parse_errors = true;
1687 }
1688 module = Some(ModuleOrUniformRoot::Module(self.expect_module(def_id)));
1689 record_segment_res(self.reborrow(), finalize, res, id);
1690 } else if res == Res::ToolMod && !is_last && opt_ns.is_some() {
1691 if binding.is_import() {
1692 self.dcx().emit_err(errors::ToolModuleImported {
1693 span: ident.span,
1694 import: binding.span,
1695 });
1696 }
1697 let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
1698 return PathResult::NonModule(PartialRes::new(res));
1699 } else if res == Res::Err {
1700 return PathResult::NonModule(PartialRes::new(Res::Err));
1701 } else if opt_ns.is_some() && (is_last || maybe_assoc) {
1702 if let Some(finalize) = finalize {
1703 self.get_mut().lint_if_path_starts_with_module(
1704 finalize,
1705 path,
1706 second_binding,
1707 );
1708 }
1709 record_segment_res(self.reborrow(), finalize, res, id);
1710 return PathResult::NonModule(PartialRes::with_unresolved_segments(
1711 res,
1712 path.len() - segment_idx - 1,
1713 ));
1714 } else {
1715 return PathResult::failed(
1716 ident,
1717 is_last,
1718 finalize.is_some(),
1719 module_had_parse_errors,
1720 module,
1721 || {
1722 let label = format!(
1723 "`{ident}` is {} {}, not a module",
1724 res.article(),
1725 res.descr()
1726 );
1727 (label, None)
1728 },
1729 );
1730 }
1731 }
1732 Err(Undetermined) => return PathResult::Indeterminate,
1733 Err(Determined) => {
1734 if let Some(ModuleOrUniformRoot::Module(module)) = module
1735 && opt_ns.is_some()
1736 && !module.is_normal()
1737 {
1738 return PathResult::NonModule(PartialRes::with_unresolved_segments(
1739 module.res().unwrap(),
1740 path.len() - segment_idx,
1741 ));
1742 }
1743
1744 let mut this = self.reborrow();
1745 return PathResult::failed(
1746 ident,
1747 is_last,
1748 finalize.is_some(),
1749 module_had_parse_errors,
1750 module,
1751 || {
1752 this.get_mut().report_path_resolution_error(
1753 path,
1754 opt_ns,
1755 parent_scope,
1756 ribs,
1757 ignore_binding,
1758 ignore_import,
1759 module,
1760 segment_idx,
1761 ident,
1762 )
1763 },
1764 );
1765 }
1766 }
1767 }
1768
1769 if let Some(finalize) = finalize {
1770 self.get_mut().lint_if_path_starts_with_module(finalize, path, second_binding);
1771 }
1772
1773 PathResult::Module(match module {
1774 Some(module) => module,
1775 None if path.is_empty() => ModuleOrUniformRoot::CurrentScope,
1776 _ => bug!("resolve_path: non-empty path `{:?}` has no module", path),
1777 })
1778 }
1779}