1 // ignore-tidy-filelength
3 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
5 #![feature(crate_visibility_modifier)]
6 #![feature(label_break_value)]
8 #![feature(rustc_diagnostic_macros)]
9 #![cfg_attr(bootstrap, feature(type_alias_enum_variants))]
11 #![recursion_limit="256"]
13 #![deny(rust_2018_idioms)]
15 #![deny(unused_lifetimes)]
17 pub use rustc
::hir
::def
::{Namespace, PerNS}
;
19 use GenericParameters
::*;
21 use smallvec
::smallvec
;
23 use rustc
::hir
::map
::{Definitions, DefCollector}
;
24 use rustc
::hir
::{self, PrimTy, Bool, Char, Float, Int, Uint, Str}
;
25 use rustc
::middle
::cstore
::CrateStore
;
26 use rustc
::session
::Session
;
28 use rustc
::hir
::def
::{
29 self, DefKind
, PartialRes
, CtorKind
, CtorOf
, NonMacroAttrKind
, ExportMap
31 use rustc
::hir
::def
::Namespace
::*;
32 use rustc
::hir
::def_id
::{CRATE_DEF_INDEX, LOCAL_CRATE, DefId}
;
33 use rustc
::hir
::{TraitCandidate, TraitMap, GlobMap}
;
34 use rustc
::ty
::{self, DefIdTree}
;
35 use rustc
::util
::nodemap
::{NodeMap, NodeSet, FxHashMap, FxHashSet, DefIdMap}
;
36 use rustc
::{bug, span_bug}
;
38 use rustc_metadata
::creader
::CrateLoader
;
39 use rustc_metadata
::cstore
::CStore
;
41 use syntax
::source_map
::SourceMap
;
42 use syntax
::ext
::hygiene
::{Mark, Transparency, SyntaxContext}
;
43 use syntax
::ast
::{self, Name, NodeId, Ident, FloatTy, IntTy, UintTy}
;
44 use syntax
::ext
::base
::{SyntaxExtension, SyntaxExtensionKind}
;
45 use syntax
::ext
::base
::Determinacy
::{self, Determined, Undetermined}
;
46 use syntax
::ext
::base
::MacroKind
;
47 use syntax
::symbol
::{Symbol, kw, sym}
;
48 use syntax
::util
::lev_distance
::find_best_match_for_name
;
50 use syntax
::visit
::{self, FnKind, Visitor}
;
52 use syntax
::ast
::{CRATE_NODE_ID, Arm, IsAsync, BindingMode, Block, Crate, Expr, ExprKind}
;
53 use syntax
::ast
::{FnDecl, ForeignItem, ForeignItemKind, GenericParamKind, Generics}
;
54 use syntax
::ast
::{Item, ItemKind, ImplItem, ImplItemKind}
;
55 use syntax
::ast
::{Label, Local, Mutability, Pat, PatKind, Path}
;
56 use syntax
::ast
::{QSelf, TraitItemKind, TraitRef, Ty, TyKind}
;
58 use syntax
::{span_err, struct_span_err, unwrap_or, walk_list}
;
60 use syntax_pos
::{Span, DUMMY_SP, MultiSpan}
;
61 use errors
::{Applicability, DiagnosticBuilder, DiagnosticId}
;
65 use std
::cell
::{Cell, RefCell}
;
66 use std
::{cmp, fmt, iter, mem, ptr}
;
67 use std
::collections
::BTreeSet
;
68 use std
::mem
::replace
;
69 use rustc_data_structures
::ptr_key
::PtrKey
;
70 use rustc_data_structures
::sync
::Lrc
;
71 use smallvec
::SmallVec
;
73 use diagnostics
::{find_span_of_binding_until_next_binding, extend_span_to_previous_binding}
;
74 use resolve_imports
::{ImportDirective, ImportDirectiveSubclass, NameResolution, ImportResolver}
;
75 use macros
::{InvocationData, LegacyBinding, ParentScope}
;
77 type Res
= def
::Res
<NodeId
>;
79 // N.B., this module needs to be declared first so diagnostics are
80 // registered before they are used.
85 mod build_reduced_graph
;
88 fn is_known_tool(name
: Name
) -> bool
{
89 ["clippy", "rustfmt"].contains(&&*name
.as_str())
99 AbsolutePath(Namespace
),
104 /// A free importable items suggested in case of resolution failure.
105 struct ImportSuggestion
{
110 /// A field or associated item from self type suggested in case of resolution failure.
111 enum AssocSuggestion
{
118 struct BindingError
{
120 origin
: BTreeSet
<Span
>,
121 target
: BTreeSet
<Span
>,
124 struct TypoSuggestion
{
127 /// The kind of the binding ("crate", "module", etc.)
130 /// An appropriate article to refer to the binding ("a", "an", etc.)
131 article
: &'
static str,
134 impl PartialOrd
for BindingError
{
135 fn partial_cmp(&self, other
: &BindingError
) -> Option
<cmp
::Ordering
> {
136 Some(self.cmp(other
))
140 impl PartialEq
for BindingError
{
141 fn eq(&self, other
: &BindingError
) -> bool
{
142 self.name
== other
.name
146 impl Ord
for BindingError
{
147 fn cmp(&self, other
: &BindingError
) -> cmp
::Ordering
{
148 self.name
.cmp(&other
.name
)
152 /// A vector of spans and replacements, a message and applicability.
153 type Suggestion
= (Vec
<(Span
, String
)>, String
, Applicability
);
155 enum ResolutionError
<'a
> {
156 /// Error E0401: can't use type or const parameters from outer function.
157 GenericParamsFromOuterFunction(Res
),
158 /// Error E0403: the name is already used for a type or const parameter in this generic
160 NameAlreadyUsedInParameterList(Name
, &'a Span
),
161 /// Error E0407: method is not a member of trait.
162 MethodNotMemberOfTrait(Name
, &'a
str),
163 /// Error E0437: type is not a member of trait.
164 TypeNotMemberOfTrait(Name
, &'a
str),
165 /// Error E0438: const is not a member of trait.
166 ConstNotMemberOfTrait(Name
, &'a
str),
167 /// Error E0408: variable `{}` is not bound in all patterns.
168 VariableNotBoundInPattern(&'a BindingError
),
169 /// Error E0409: variable `{}` is bound in inconsistent ways within the same match arm.
170 VariableBoundWithDifferentMode(Name
, Span
),
171 /// Error E0415: identifier is bound more than once in this parameter list.
172 IdentifierBoundMoreThanOnceInParameterList(&'a
str),
173 /// Error E0416: identifier is bound more than once in the same pattern.
174 IdentifierBoundMoreThanOnceInSamePattern(&'a
str),
175 /// Error E0426: use of undeclared label.
176 UndeclaredLabel(&'a
str, Option
<Name
>),
177 /// Error E0429: `self` imports are only allowed within a `{ }` list.
178 SelfImportsOnlyAllowedWithin
,
179 /// Error E0430: `self` import can only appear once in the list.
180 SelfImportCanOnlyAppearOnceInTheList
,
181 /// Error E0431: `self` import can only appear in an import list with a non-empty prefix.
182 SelfImportOnlyInImportListWithNonEmptyPrefix
,
183 /// Error E0433: failed to resolve.
184 FailedToResolve { label: String, suggestion: Option<Suggestion> }
,
185 /// Error E0434: can't capture dynamic environment in a fn item.
186 CannotCaptureDynamicEnvironmentInFnItem
,
187 /// Error E0435: attempt to use a non-constant value in a constant.
188 AttemptToUseNonConstantValueInConstant
,
189 /// Error E0530: `X` bindings cannot shadow `Y`s.
190 BindingShadowsSomethingUnacceptable(&'a
str, Name
, &'a NameBinding
<'a
>),
191 /// Error E0128: type parameters with a default cannot use forward-declared identifiers.
192 ForwardDeclaredTyParam
, // FIXME(const_generics:defaults)
193 /// Error E0671: const parameter cannot depend on type parameter.
194 ConstParamDependentOnTypeParam
,
197 /// Combines an error with provided span and emits it.
199 /// This takes the error provided, combines it with the span and any additional spans inside the
200 /// error and emits it.
201 fn resolve_error
<'sess
, 'a
>(resolver
: &'sess Resolver
<'_
>,
203 resolution_error
: ResolutionError
<'a
>) {
204 resolve_struct_error(resolver
, span
, resolution_error
).emit();
207 fn resolve_struct_error
<'sess
, 'a
>(resolver
: &'sess Resolver
<'_
>,
209 resolution_error
: ResolutionError
<'a
>)
210 -> DiagnosticBuilder
<'sess
> {
211 match resolution_error
{
212 ResolutionError
::GenericParamsFromOuterFunction(outer_res
) => {
213 let mut err
= struct_span_err
!(resolver
.session
,
216 "can't use generic parameters from outer function",
218 err
.span_label(span
, format
!("use of generic parameter from outer function"));
220 let cm
= resolver
.session
.source_map();
222 Res
::SelfTy(maybe_trait_defid
, maybe_impl_defid
) => {
223 if let Some(impl_span
) = maybe_impl_defid
.and_then(|def_id
| {
224 resolver
.definitions
.opt_span(def_id
)
227 reduce_impl_span_to_impl_keyword(cm
, impl_span
),
228 "`Self` type implicitly declared here, by this `impl`",
231 match (maybe_trait_defid
, maybe_impl_defid
) {
233 err
.span_label(span
, "can't use `Self` here");
236 err
.span_label(span
, "use a type here instead");
238 (None
, None
) => bug
!("`impl` without trait nor type?"),
242 Res
::Def(DefKind
::TyParam
, def_id
) => {
243 if let Some(span
) = resolver
.definitions
.opt_span(def_id
) {
244 err
.span_label(span
, "type parameter from outer function");
247 Res
::Def(DefKind
::ConstParam
, def_id
) => {
248 if let Some(span
) = resolver
.definitions
.opt_span(def_id
) {
249 err
.span_label(span
, "const parameter from outer function");
253 bug
!("GenericParamsFromOuterFunction should only be used with Res::SelfTy, \
258 // Try to retrieve the span of the function signature and generate a new message with
259 // a local type or const parameter.
260 let sugg_msg
= &format
!("try using a local generic parameter instead");
261 if let Some((sugg_span
, new_snippet
)) = cm
.generate_local_type_param_snippet(span
) {
262 // Suggest the modification to the user
267 Applicability
::MachineApplicable
,
269 } else if let Some(sp
) = cm
.generate_fn_name_span(span
) {
271 format
!("try adding a local generic parameter in this method instead"));
273 err
.help(&format
!("try using a local generic parameter instead"));
278 ResolutionError
::NameAlreadyUsedInParameterList(name
, first_use_span
) => {
279 let mut err
= struct_span_err
!(resolver
.session
,
282 "the name `{}` is already used for a generic \
283 parameter in this list of generic parameters",
285 err
.span_label(span
, "already used");
286 err
.span_label(first_use_span
.clone(), format
!("first use of `{}`", name
));
289 ResolutionError
::MethodNotMemberOfTrait(method
, trait_
) => {
290 let mut err
= struct_span_err
!(resolver
.session
,
293 "method `{}` is not a member of trait `{}`",
296 err
.span_label(span
, format
!("not a member of trait `{}`", trait_
));
299 ResolutionError
::TypeNotMemberOfTrait(type_
, trait_
) => {
300 let mut err
= struct_span_err
!(resolver
.session
,
303 "type `{}` is not a member of trait `{}`",
306 err
.span_label(span
, format
!("not a member of trait `{}`", trait_
));
309 ResolutionError
::ConstNotMemberOfTrait(const_
, trait_
) => {
310 let mut err
= struct_span_err
!(resolver
.session
,
313 "const `{}` is not a member of trait `{}`",
316 err
.span_label(span
, format
!("not a member of trait `{}`", trait_
));
319 ResolutionError
::VariableNotBoundInPattern(binding_error
) => {
320 let target_sp
= binding_error
.target
.iter().cloned().collect
::<Vec
<_
>>();
321 let msp
= MultiSpan
::from_spans(target_sp
.clone());
322 let msg
= format
!("variable `{}` is not bound in all patterns", binding_error
.name
);
323 let mut err
= resolver
.session
.struct_span_err_with_code(
326 DiagnosticId
::Error("E0408".into()),
328 for sp
in target_sp
{
329 err
.span_label(sp
, format
!("pattern doesn't bind `{}`", binding_error
.name
));
331 let origin_sp
= binding_error
.origin
.iter().cloned();
332 for sp
in origin_sp
{
333 err
.span_label(sp
, "variable not in all patterns");
337 ResolutionError
::VariableBoundWithDifferentMode(variable_name
,
338 first_binding_span
) => {
339 let mut err
= struct_span_err
!(resolver
.session
,
342 "variable `{}` is bound in inconsistent \
343 ways within the same match arm",
345 err
.span_label(span
, "bound in different ways");
346 err
.span_label(first_binding_span
, "first binding");
349 ResolutionError
::IdentifierBoundMoreThanOnceInParameterList(identifier
) => {
350 let mut err
= struct_span_err
!(resolver
.session
,
353 "identifier `{}` is bound more than once in this parameter list",
355 err
.span_label(span
, "used as parameter more than once");
358 ResolutionError
::IdentifierBoundMoreThanOnceInSamePattern(identifier
) => {
359 let mut err
= struct_span_err
!(resolver
.session
,
362 "identifier `{}` is bound more than once in the same pattern",
364 err
.span_label(span
, "used in a pattern more than once");
367 ResolutionError
::UndeclaredLabel(name
, lev_candidate
) => {
368 let mut err
= struct_span_err
!(resolver
.session
,
371 "use of undeclared label `{}`",
373 if let Some(lev_candidate
) = lev_candidate
{
376 "a label with a similar name exists in this scope",
377 lev_candidate
.to_string(),
378 Applicability
::MaybeIncorrect
,
381 err
.span_label(span
, format
!("undeclared label `{}`", name
));
385 ResolutionError
::SelfImportsOnlyAllowedWithin
=> {
386 struct_span_err
!(resolver
.session
,
390 "`self` imports are only allowed within a { } list")
392 ResolutionError
::SelfImportCanOnlyAppearOnceInTheList
=> {
393 let mut err
= struct_span_err
!(resolver
.session
, span
, E0430
,
394 "`self` import can only appear once in an import list");
395 err
.span_label(span
, "can only appear once in an import list");
398 ResolutionError
::SelfImportOnlyInImportListWithNonEmptyPrefix
=> {
399 let mut err
= struct_span_err
!(resolver
.session
, span
, E0431
,
400 "`self` import can only appear in an import list with \
401 a non-empty prefix");
402 err
.span_label(span
, "can only appear in an import list with a non-empty prefix");
405 ResolutionError
::FailedToResolve { label, suggestion }
=> {
406 let mut err
= struct_span_err
!(resolver
.session
, span
, E0433
,
407 "failed to resolve: {}", &label
);
408 err
.span_label(span
, label
);
410 if let Some((suggestions
, msg
, applicability
)) = suggestion
{
411 err
.multipart_suggestion(&msg
, suggestions
, applicability
);
416 ResolutionError
::CannotCaptureDynamicEnvironmentInFnItem
=> {
417 let mut err
= struct_span_err
!(resolver
.session
,
421 "can't capture dynamic environment in a fn item");
422 err
.help("use the `|| { ... }` closure form instead");
425 ResolutionError
::AttemptToUseNonConstantValueInConstant
=> {
426 let mut err
= struct_span_err
!(resolver
.session
, span
, E0435
,
427 "attempt to use a non-constant value in a constant");
428 err
.span_label(span
, "non-constant value");
431 ResolutionError
::BindingShadowsSomethingUnacceptable(what_binding
, name
, binding
) => {
432 let shadows_what
= binding
.descr();
433 let mut err
= struct_span_err
!(resolver
.session
, span
, E0530
, "{}s cannot shadow {}s",
434 what_binding
, shadows_what
);
435 err
.span_label(span
, format
!("cannot be named the same as {} {}",
436 binding
.article(), shadows_what
));
437 let participle
= if binding
.is_import() { "imported" }
else { "defined" }
;
438 let msg
= format
!("the {} `{}` is {} here", shadows_what
, name
, participle
);
439 err
.span_label(binding
.span
, msg
);
442 ResolutionError
::ForwardDeclaredTyParam
=> {
443 let mut err
= struct_span_err
!(resolver
.session
, span
, E0128
,
444 "type parameters with a default cannot use \
445 forward declared identifiers");
447 span
, "defaulted type parameters cannot be forward declared".to_string());
450 ResolutionError
::ConstParamDependentOnTypeParam
=> {
451 let mut err
= struct_span_err
!(
455 "const parameters cannot depend on type parameters"
457 err
.span_label(span
, format
!("const parameter depends on type parameter"));
463 /// Adjust the impl span so that just the `impl` keyword is taken by removing
464 /// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
465 /// everything after the first whitespace (`"impl Iterator for A" -> "impl"`).
467 /// *Attention*: the method used is very fragile since it essentially duplicates the work of the
468 /// parser. If you need to use this function or something similar, please consider updating the
469 /// `source_map` functions and this function to something more robust.
470 fn reduce_impl_span_to_impl_keyword(cm
: &SourceMap
, impl_span
: Span
) -> Span
{
471 let impl_span
= cm
.span_until_char(impl_span
, '
<'
);
472 let impl_span
= cm
.span_until_whitespace(impl_span
);
476 #[derive(Copy, Clone, Debug)]
479 binding_mode
: BindingMode
,
482 /// Map from the name in a pattern to its binding mode.
483 type BindingMap
= FxHashMap
<Ident
, BindingInfo
>;
485 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
494 fn descr(self) -> &'
static str {
496 PatternSource
::Match
=> "match binding",
497 PatternSource
::Let
=> "let binding",
498 PatternSource
::For
=> "for binding",
499 PatternSource
::FnParam
=> "function parameter",
504 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
505 enum AliasPossibility
{
510 #[derive(Copy, Clone, Debug)]
511 enum PathSource
<'a
> {
512 // Type paths `Path`.
514 // Trait paths in bounds or impls.
515 Trait(AliasPossibility
),
516 // Expression paths `path`, with optional parent context.
517 Expr(Option
<&'a Expr
>),
518 // Paths in path patterns `Path`.
520 // Paths in struct expressions and patterns `Path { .. }`.
522 // Paths in tuple struct patterns `Path(..)`.
524 // `m::A::B` in `<T as m::A>::B::C`.
525 TraitItem(Namespace
),
526 // Path in `pub(path)`
530 impl<'a
> PathSource
<'a
> {
531 fn namespace(self) -> Namespace
{
533 PathSource
::Type
| PathSource
::Trait(_
) | PathSource
::Struct
|
534 PathSource
::Visibility
=> TypeNS
,
535 PathSource
::Expr(..) | PathSource
::Pat
| PathSource
::TupleStruct
=> ValueNS
,
536 PathSource
::TraitItem(ns
) => ns
,
540 fn global_by_default(self) -> bool
{
542 PathSource
::Visibility
=> true,
543 PathSource
::Type
| PathSource
::Expr(..) | PathSource
::Pat
|
544 PathSource
::Struct
| PathSource
::TupleStruct
|
545 PathSource
::Trait(_
) | PathSource
::TraitItem(..) => false,
549 fn defer_to_typeck(self) -> bool
{
551 PathSource
::Type
| PathSource
::Expr(..) | PathSource
::Pat
|
552 PathSource
::Struct
| PathSource
::TupleStruct
=> true,
553 PathSource
::Trait(_
) | PathSource
::TraitItem(..) |
554 PathSource
::Visibility
=> false,
558 fn descr_expected(self) -> &'
static str {
560 PathSource
::Type
=> "type",
561 PathSource
::Trait(_
) => "trait",
562 PathSource
::Pat
=> "unit struct/variant or constant",
563 PathSource
::Struct
=> "struct, variant or union type",
564 PathSource
::TupleStruct
=> "tuple struct/variant",
565 PathSource
::Visibility
=> "module",
566 PathSource
::TraitItem(ns
) => match ns
{
567 TypeNS
=> "associated type",
568 ValueNS
=> "method or associated constant",
569 MacroNS
=> bug
!("associated macro"),
571 PathSource
::Expr(parent
) => match parent
.map(|p
| &p
.node
) {
572 // "function" here means "anything callable" rather than `DefKind::Fn`,
573 // this is not precise but usually more helpful than just "value".
574 Some(&ExprKind
::Call(..)) => "function",
580 fn is_expected(self, res
: Res
) -> bool
{
582 PathSource
::Type
=> match res
{
583 Res
::Def(DefKind
::Struct
, _
)
584 | Res
::Def(DefKind
::Union
, _
)
585 | Res
::Def(DefKind
::Enum
, _
)
586 | Res
::Def(DefKind
::Trait
, _
)
587 | Res
::Def(DefKind
::TraitAlias
, _
)
588 | Res
::Def(DefKind
::TyAlias
, _
)
589 | Res
::Def(DefKind
::AssocTy
, _
)
591 | Res
::Def(DefKind
::TyParam
, _
)
593 | Res
::Def(DefKind
::Existential
, _
)
594 | Res
::Def(DefKind
::ForeignTy
, _
) => true,
597 PathSource
::Trait(AliasPossibility
::No
) => match res
{
598 Res
::Def(DefKind
::Trait
, _
) => true,
601 PathSource
::Trait(AliasPossibility
::Maybe
) => match res
{
602 Res
::Def(DefKind
::Trait
, _
) => true,
603 Res
::Def(DefKind
::TraitAlias
, _
) => true,
606 PathSource
::Expr(..) => match res
{
607 Res
::Def(DefKind
::Ctor(_
, CtorKind
::Const
), _
)
608 | Res
::Def(DefKind
::Ctor(_
, CtorKind
::Fn
), _
)
609 | Res
::Def(DefKind
::Const
, _
)
610 | Res
::Def(DefKind
::Static
, _
)
612 | Res
::Def(DefKind
::Fn
, _
)
613 | Res
::Def(DefKind
::Method
, _
)
614 | Res
::Def(DefKind
::AssocConst
, _
)
616 | Res
::Def(DefKind
::ConstParam
, _
) => true,
619 PathSource
::Pat
=> match res
{
620 Res
::Def(DefKind
::Ctor(_
, CtorKind
::Const
), _
) |
621 Res
::Def(DefKind
::Const
, _
) | Res
::Def(DefKind
::AssocConst
, _
) |
622 Res
::SelfCtor(..) => true,
625 PathSource
::TupleStruct
=> match res
{
626 Res
::Def(DefKind
::Ctor(_
, CtorKind
::Fn
), _
) | Res
::SelfCtor(..) => true,
629 PathSource
::Struct
=> match res
{
630 Res
::Def(DefKind
::Struct
, _
)
631 | Res
::Def(DefKind
::Union
, _
)
632 | Res
::Def(DefKind
::Variant
, _
)
633 | Res
::Def(DefKind
::TyAlias
, _
)
634 | Res
::Def(DefKind
::AssocTy
, _
)
635 | Res
::SelfTy(..) => true,
638 PathSource
::TraitItem(ns
) => match res
{
639 Res
::Def(DefKind
::AssocConst
, _
)
640 | Res
::Def(DefKind
::Method
, _
) if ns
== ValueNS
=> true,
641 Res
::Def(DefKind
::AssocTy
, _
) if ns
== TypeNS
=> true,
644 PathSource
::Visibility
=> match res
{
645 Res
::Def(DefKind
::Mod
, _
) => true,
651 fn error_code(self, has_unexpected_resolution
: bool
) -> &'
static str {
652 __diagnostic_used
!(E0404
);
653 __diagnostic_used
!(E0405
);
654 __diagnostic_used
!(E0412
);
655 __diagnostic_used
!(E0422
);
656 __diagnostic_used
!(E0423
);
657 __diagnostic_used
!(E0425
);
658 __diagnostic_used
!(E0531
);
659 __diagnostic_used
!(E0532
);
660 __diagnostic_used
!(E0573
);
661 __diagnostic_used
!(E0574
);
662 __diagnostic_used
!(E0575
);
663 __diagnostic_used
!(E0576
);
664 __diagnostic_used
!(E0577
);
665 __diagnostic_used
!(E0578
);
666 match (self, has_unexpected_resolution
) {
667 (PathSource
::Trait(_
), true) => "E0404",
668 (PathSource
::Trait(_
), false) => "E0405",
669 (PathSource
::Type
, true) => "E0573",
670 (PathSource
::Type
, false) => "E0412",
671 (PathSource
::Struct
, true) => "E0574",
672 (PathSource
::Struct
, false) => "E0422",
673 (PathSource
::Expr(..), true) => "E0423",
674 (PathSource
::Expr(..), false) => "E0425",
675 (PathSource
::Pat
, true) | (PathSource
::TupleStruct
, true) => "E0532",
676 (PathSource
::Pat
, false) | (PathSource
::TupleStruct
, false) => "E0531",
677 (PathSource
::TraitItem(..), true) => "E0575",
678 (PathSource
::TraitItem(..), false) => "E0576",
679 (PathSource
::Visibility
, true) => "E0577",
680 (PathSource
::Visibility
, false) => "E0578",
685 // A minimal representation of a path segment. We use this in resolve because
686 // we synthesize 'path segments' which don't have the rest of an AST or HIR
688 #[derive(Clone, Copy, Debug)]
695 fn from_path(path
: &Path
) -> Vec
<Segment
> {
696 path
.segments
.iter().map(|s
| s
.into()).collect()
699 fn from_ident(ident
: Ident
) -> Segment
{
706 fn names_to_string(segments
: &[Segment
]) -> String
{
707 names_to_string(&segments
.iter()
708 .map(|seg
| seg
.ident
)
709 .collect
::<Vec
<_
>>())
713 impl<'a
> From
<&'a ast
::PathSegment
> for Segment
{
714 fn from(seg
: &'a ast
::PathSegment
) -> Segment
{
722 struct UsePlacementFinder
{
723 target_module
: NodeId
,
728 impl UsePlacementFinder
{
729 fn check(krate
: &Crate
, target_module
: NodeId
) -> (Option
<Span
>, bool
) {
730 let mut finder
= UsePlacementFinder
{
735 visit
::walk_crate(&mut finder
, krate
);
736 (finder
.span
, finder
.found_use
)
740 impl<'tcx
> Visitor
<'tcx
> for UsePlacementFinder
{
743 module
: &'tcx ast
::Mod
,
745 _
: &[ast
::Attribute
],
748 if self.span
.is_some() {
751 if node_id
!= self.target_module
{
752 visit
::walk_mod(self, module
);
755 // find a use statement
756 for item
in &module
.items
{
758 ItemKind
::Use(..) => {
759 // don't suggest placing a use before the prelude
760 // import or other generated ones
761 if item
.span
.ctxt().outer_expn_info().is_none() {
762 self.span
= Some(item
.span
.shrink_to_lo());
763 self.found_use
= true;
767 // don't place use before extern crate
768 ItemKind
::ExternCrate(_
) => {}
769 // but place them before the first other item
770 _
=> if self.span
.map_or(true, |span
| item
.span
< span
) {
771 if item
.span
.ctxt().outer_expn_info().is_none() {
772 // don't insert between attributes and an item
773 if item
.attrs
.is_empty() {
774 self.span
= Some(item
.span
.shrink_to_lo());
776 // find the first attribute on the item
777 for attr
in &item
.attrs
{
778 if self.span
.map_or(true, |span
| attr
.span
< span
) {
779 self.span
= Some(attr
.span
.shrink_to_lo());
790 /// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
791 impl<'a
, 'tcx
> Visitor
<'tcx
> for Resolver
<'a
> {
792 fn visit_item(&mut self, item
: &'tcx Item
) {
793 self.resolve_item(item
);
795 fn visit_arm(&mut self, arm
: &'tcx Arm
) {
796 self.resolve_arm(arm
);
798 fn visit_block(&mut self, block
: &'tcx Block
) {
799 self.resolve_block(block
);
801 fn visit_anon_const(&mut self, constant
: &'tcx ast
::AnonConst
) {
802 debug
!("visit_anon_const {:?}", constant
);
803 self.with_constant_rib(|this
| {
804 visit
::walk_anon_const(this
, constant
);
807 fn visit_expr(&mut self, expr
: &'tcx Expr
) {
808 self.resolve_expr(expr
, None
);
810 fn visit_local(&mut self, local
: &'tcx Local
) {
811 self.resolve_local(local
);
813 fn visit_ty(&mut self, ty
: &'tcx Ty
) {
815 TyKind
::Path(ref qself
, ref path
) => {
816 self.smart_resolve_path(ty
.id
, qself
.as_ref(), path
, PathSource
::Type
);
818 TyKind
::ImplicitSelf
=> {
819 let self_ty
= Ident
::with_empty_ctxt(kw
::SelfUpper
);
820 let res
= self.resolve_ident_in_lexical_scope(self_ty
, TypeNS
, Some(ty
.id
), ty
.span
)
821 .map_or(Res
::Err
, |d
| d
.res());
822 self.record_partial_res(ty
.id
, PartialRes
::new(res
));
826 visit
::walk_ty(self, ty
);
828 fn visit_poly_trait_ref(&mut self,
829 tref
: &'tcx ast
::PolyTraitRef
,
830 m
: &'tcx ast
::TraitBoundModifier
) {
831 self.smart_resolve_path(tref
.trait_ref
.ref_id
, None
,
832 &tref
.trait_ref
.path
, PathSource
::Trait(AliasPossibility
::Maybe
));
833 visit
::walk_poly_trait_ref(self, tref
, m
);
835 fn visit_foreign_item(&mut self, foreign_item
: &'tcx ForeignItem
) {
836 let generic_params
= match foreign_item
.node
{
837 ForeignItemKind
::Fn(_
, ref generics
) => {
838 HasGenericParams(generics
, ItemRibKind
)
840 ForeignItemKind
::Static(..) => NoGenericParams
,
841 ForeignItemKind
::Ty
=> NoGenericParams
,
842 ForeignItemKind
::Macro(..) => NoGenericParams
,
844 self.with_generic_param_rib(generic_params
, |this
| {
845 visit
::walk_foreign_item(this
, foreign_item
);
848 fn visit_fn(&mut self,
849 function_kind
: FnKind
<'tcx
>,
850 declaration
: &'tcx FnDecl
,
854 debug
!("(resolving function) entering function");
855 let rib_kind
= match function_kind
{
856 FnKind
::ItemFn(..) => FnItemRibKind
,
857 FnKind
::Method(..) => AssocItemRibKind
,
858 FnKind
::Closure(_
) => NormalRibKind
,
861 // Create a value rib for the function.
862 self.ribs
[ValueNS
].push(Rib
::new(rib_kind
));
864 // Create a label rib for the function.
865 self.label_ribs
.push(Rib
::new(rib_kind
));
867 // Add each argument to the rib.
868 let mut bindings_list
= FxHashMap
::default();
869 for argument
in &declaration
.inputs
{
870 self.resolve_pattern(&argument
.pat
, PatternSource
::FnParam
, &mut bindings_list
);
872 self.visit_ty(&argument
.ty
);
874 debug
!("(resolving function) recorded argument");
876 visit
::walk_fn_ret_ty(self, &declaration
.output
);
878 // Resolve the function body, potentially inside the body of an async closure
879 match function_kind
{
880 FnKind
::ItemFn(.., body
) |
881 FnKind
::Method(.., body
) => {
882 self.visit_block(body
);
884 FnKind
::Closure(body
) => {
885 self.visit_expr(body
);
889 debug
!("(resolving function) leaving function");
891 self.label_ribs
.pop();
892 self.ribs
[ValueNS
].pop();
895 fn visit_generics(&mut self, generics
: &'tcx Generics
) {
896 // For type parameter defaults, we have to ban access
897 // to following type parameters, as the InternalSubsts can only
898 // provide previous type parameters as they're built. We
899 // put all the parameters on the ban list and then remove
900 // them one by one as they are processed and become available.
901 let mut default_ban_rib
= Rib
::new(ForwardTyParamBanRibKind
);
902 let mut found_default
= false;
903 default_ban_rib
.bindings
.extend(generics
.params
.iter()
904 .filter_map(|param
| match param
.kind
{
905 GenericParamKind
::Const { .. }
|
906 GenericParamKind
::Lifetime { .. }
=> None
,
907 GenericParamKind
::Type { ref default, .. }
=> {
908 found_default
|= default.is_some();
910 Some((Ident
::with_empty_ctxt(param
.ident
.name
), Res
::Err
))
917 // We also ban access to type parameters for use as the types of const parameters.
918 let mut const_ty_param_ban_rib
= Rib
::new(TyParamAsConstParamTy
);
919 const_ty_param_ban_rib
.bindings
.extend(generics
.params
.iter()
921 if let GenericParamKind
::Type { .. }
= param
.kind
{
927 .map(|param
| (Ident
::with_empty_ctxt(param
.ident
.name
), Res
::Err
)));
929 for param
in &generics
.params
{
931 GenericParamKind
::Lifetime { .. }
=> self.visit_generic_param(param
),
932 GenericParamKind
::Type { ref default, .. }
=> {
933 for bound
in ¶m
.bounds
{
934 self.visit_param_bound(bound
);
937 if let Some(ref ty
) = default {
938 self.ribs
[TypeNS
].push(default_ban_rib
);
940 default_ban_rib
= self.ribs
[TypeNS
].pop().unwrap();
943 // Allow all following defaults to refer to this type parameter.
944 default_ban_rib
.bindings
.remove(&Ident
::with_empty_ctxt(param
.ident
.name
));
946 GenericParamKind
::Const { ref ty }
=> {
947 self.ribs
[TypeNS
].push(const_ty_param_ban_rib
);
949 for bound
in ¶m
.bounds
{
950 self.visit_param_bound(bound
);
955 const_ty_param_ban_rib
= self.ribs
[TypeNS
].pop().unwrap();
959 for p
in &generics
.where_clause
.predicates
{
960 self.visit_where_predicate(p
);
965 #[derive(Copy, Clone)]
966 enum GenericParameters
<'a
, 'b
> {
968 HasGenericParams(// Type parameters.
971 // The kind of the rib used for type parameters.
975 /// The rib kind restricts certain accesses,
976 /// e.g. to a `Res::Local` of an outer item.
977 #[derive(Copy, Clone, Debug)]
979 /// No restriction needs to be applied.
982 /// We passed through an impl or trait and are now in one of its
983 /// methods or associated types. Allow references to ty params that impl or trait
984 /// binds. Disallow any other upvars (including other ty params that are
988 /// We passed through a function definition. Disallow upvars.
989 /// Permit only those const parameters that are specified in the function's generics.
992 /// We passed through an item scope. Disallow upvars.
995 /// We're in a constant item. Can't refer to dynamic stuff.
998 /// We passed through a module.
999 ModuleRibKind(Module
<'a
>),
1001 /// We passed through a `macro_rules!` statement
1002 MacroDefinition(DefId
),
1004 /// All bindings in this rib are type parameters that can't be used
1005 /// from the default of a type parameter because they're not declared
1006 /// before said type parameter. Also see the `visit_generics` override.
1007 ForwardTyParamBanRibKind
,
1009 /// We forbid the use of type parameters as the types of const parameters.
1010 TyParamAsConstParamTy
,
1013 /// A single local scope.
1015 /// A rib represents a scope names can live in. Note that these appear in many places, not just
1016 /// around braces. At any place where the list of accessible names (of the given namespace)
1017 /// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
1018 /// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
1021 /// Different [rib kinds](enum.RibKind) are transparent for different names.
1023 /// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
1024 /// resolving, the name is looked up from inside out.
1026 struct Rib
<'a
, R
= Res
> {
1027 bindings
: FxHashMap
<Ident
, R
>,
1031 impl<'a
, R
> Rib
<'a
, R
> {
1032 fn new(kind
: RibKind
<'a
>) -> Rib
<'a
, R
> {
1034 bindings
: Default
::default(),
1040 /// An intermediate resolution result.
1042 /// This refers to the thing referred by a name. The difference between `Res` and `Item` is that
1043 /// items are visible in their whole block, while `Res`es only from the place they are defined
1045 enum LexicalScopeBinding
<'a
> {
1046 Item(&'a NameBinding
<'a
>),
1050 impl<'a
> LexicalScopeBinding
<'a
> {
1051 fn item(self) -> Option
<&'a NameBinding
<'a
>> {
1053 LexicalScopeBinding
::Item(binding
) => Some(binding
),
1058 fn res(self) -> Res
{
1060 LexicalScopeBinding
::Item(binding
) => binding
.res(),
1061 LexicalScopeBinding
::Res(res
) => res
,
1066 #[derive(Copy, Clone, Debug)]
1067 enum ModuleOrUniformRoot
<'a
> {
1071 /// Virtual module that denotes resolution in crate root with fallback to extern prelude.
1072 CrateRootAndExternPrelude
,
1074 /// Virtual module that denotes resolution in extern prelude.
1075 /// Used for paths starting with `::` on 2018 edition.
1078 /// Virtual module that denotes resolution in current scope.
1079 /// Used only for resolving single-segment imports. The reason it exists is that import paths
1080 /// are always split into two parts, the first of which should be some kind of module.
1084 impl ModuleOrUniformRoot
<'_
> {
1085 fn same_def(lhs
: Self, rhs
: Self) -> bool
{
1087 (ModuleOrUniformRoot
::Module(lhs
),
1088 ModuleOrUniformRoot
::Module(rhs
)) => lhs
.def_id() == rhs
.def_id(),
1089 (ModuleOrUniformRoot
::CrateRootAndExternPrelude
,
1090 ModuleOrUniformRoot
::CrateRootAndExternPrelude
) |
1091 (ModuleOrUniformRoot
::ExternPrelude
, ModuleOrUniformRoot
::ExternPrelude
) |
1092 (ModuleOrUniformRoot
::CurrentScope
, ModuleOrUniformRoot
::CurrentScope
) => true,
1098 #[derive(Clone, Debug)]
1099 enum PathResult
<'a
> {
1100 Module(ModuleOrUniformRoot
<'a
>),
1101 NonModule(PartialRes
),
1106 suggestion
: Option
<Suggestion
>,
1107 is_error_from_last_segment
: bool
,
1112 /// An anonymous module; e.g., just a block.
1116 /// fn f() {} // (1)
1117 /// { // This is an anonymous module
1118 /// f(); // This resolves to (2) as we are inside the block.
1119 /// fn f() {} // (2)
1121 /// f(); // Resolves to (1)
1125 /// Any module with a name.
1129 /// * A normal module ‒ either `mod from_file;` or `mod from_block { }`.
1130 /// * A trait or an enum (it implicitly contains associated types, methods and variant
1132 Def(DefKind
, DefId
, Name
),
1136 /// Get name of the module.
1137 pub fn name(&self) -> Option
<Name
> {
1139 ModuleKind
::Block(..) => None
,
1140 ModuleKind
::Def(.., name
) => Some(*name
),
1145 /// One node in the tree of modules.
1146 pub struct ModuleData
<'a
> {
1147 parent
: Option
<Module
<'a
>>,
1150 // The def id of the closest normal module (`mod`) ancestor (including this module).
1151 normal_ancestor_id
: DefId
,
1153 resolutions
: RefCell
<FxHashMap
<(Ident
, Namespace
), &'a RefCell
<NameResolution
<'a
>>>>,
1154 single_segment_macro_resolutions
: RefCell
<Vec
<(Ident
, MacroKind
, ParentScope
<'a
>,
1155 Option
<&'a NameBinding
<'a
>>)>>,
1156 multi_segment_macro_resolutions
: RefCell
<Vec
<(Vec
<Segment
>, Span
, MacroKind
, ParentScope
<'a
>,
1158 builtin_attrs
: RefCell
<Vec
<(Ident
, ParentScope
<'a
>)>>,
1160 // Macro invocations that can expand into items in this module.
1161 unresolved_invocations
: RefCell
<FxHashSet
<Mark
>>,
1163 no_implicit_prelude
: bool
,
1165 glob_importers
: RefCell
<Vec
<&'a ImportDirective
<'a
>>>,
1166 globs
: RefCell
<Vec
<&'a ImportDirective
<'a
>>>,
1168 // Used to memoize the traits in this module for faster searches through all traits in scope.
1169 traits
: RefCell
<Option
<Box
<[(Ident
, &'a NameBinding
<'a
>)]>>>,
1171 // Whether this module is populated. If not populated, any attempt to
1172 // access the children must be preceded with a
1173 // `populate_module_if_necessary` call.
1174 populated
: Cell
<bool
>,
1176 /// Span of the module itself. Used for error reporting.
1182 type Module
<'a
> = &'a ModuleData
<'a
>;
1184 impl<'a
> ModuleData
<'a
> {
1185 fn new(parent
: Option
<Module
<'a
>>,
1187 normal_ancestor_id
: DefId
,
1189 span
: Span
) -> Self {
1194 resolutions
: Default
::default(),
1195 single_segment_macro_resolutions
: RefCell
::new(Vec
::new()),
1196 multi_segment_macro_resolutions
: RefCell
::new(Vec
::new()),
1197 builtin_attrs
: RefCell
::new(Vec
::new()),
1198 unresolved_invocations
: Default
::default(),
1199 no_implicit_prelude
: false,
1200 glob_importers
: RefCell
::new(Vec
::new()),
1201 globs
: RefCell
::new(Vec
::new()),
1202 traits
: RefCell
::new(None
),
1203 populated
: Cell
::new(normal_ancestor_id
.is_local()),
1209 fn for_each_child
<F
: FnMut(Ident
, Namespace
, &'a NameBinding
<'a
>)>(&self, mut f
: F
) {
1210 for (&(ident
, ns
), name_resolution
) in self.resolutions
.borrow().iter() {
1211 name_resolution
.borrow().binding
.map(|binding
| f(ident
, ns
, binding
));
1215 fn for_each_child_stable
<F
: FnMut(Ident
, Namespace
, &'a NameBinding
<'a
>)>(&self, mut f
: F
) {
1216 let resolutions
= self.resolutions
.borrow();
1217 let mut resolutions
= resolutions
.iter().collect
::<Vec
<_
>>();
1218 resolutions
.sort_by_cached_key(|&(&(ident
, ns
), _
)| (ident
.as_str(), ns
));
1219 for &(&(ident
, ns
), &resolution
) in resolutions
.iter() {
1220 resolution
.borrow().binding
.map(|binding
| f(ident
, ns
, binding
));
1224 fn res(&self) -> Option
<Res
> {
1226 ModuleKind
::Def(kind
, def_id
, _
) => Some(Res
::Def(kind
, def_id
)),
1231 fn def_kind(&self) -> Option
<DefKind
> {
1233 ModuleKind
::Def(kind
, ..) => Some(kind
),
1238 fn def_id(&self) -> Option
<DefId
> {
1240 ModuleKind
::Def(_
, def_id
, _
) => Some(def_id
),
1245 // `self` resolves to the first module ancestor that `is_normal`.
1246 fn is_normal(&self) -> bool
{
1248 ModuleKind
::Def(DefKind
::Mod
, _
, _
) => true,
1253 fn is_trait(&self) -> bool
{
1255 ModuleKind
::Def(DefKind
::Trait
, _
, _
) => true,
1260 fn nearest_item_scope(&'a
self) -> Module
<'a
> {
1261 if self.is_trait() { self.parent.unwrap() }
else { self }
1264 fn is_ancestor_of(&self, mut other
: &Self) -> bool
{
1265 while !ptr
::eq(self, other
) {
1266 if let Some(parent
) = other
.parent
{
1276 impl<'a
> fmt
::Debug
for ModuleData
<'a
> {
1277 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1278 write
!(f
, "{:?}", self.res())
1282 /// Records a possibly-private value, type, or module definition.
1283 #[derive(Clone, Debug)]
1284 pub struct NameBinding
<'a
> {
1285 kind
: NameBindingKind
<'a
>,
1286 ambiguity
: Option
<(&'a NameBinding
<'a
>, AmbiguityKind
)>,
1289 vis
: ty
::Visibility
,
1292 pub trait ToNameBinding
<'a
> {
1293 fn to_name_binding(self, arenas
: &'a ResolverArenas
<'a
>) -> &'a NameBinding
<'a
>;
1296 impl<'a
> ToNameBinding
<'a
> for &'a NameBinding
<'a
> {
1297 fn to_name_binding(self, _
: &'a ResolverArenas
<'a
>) -> &'a NameBinding
<'a
> {
1302 #[derive(Clone, Debug)]
1303 enum NameBindingKind
<'a
> {
1304 Res(Res
, /* is_macro_export */ bool
),
1307 binding
: &'a NameBinding
<'a
>,
1308 directive
: &'a ImportDirective
<'a
>,
1313 impl<'a
> NameBindingKind
<'a
> {
1314 /// Is this a name binding of a import?
1315 fn is_import(&self) -> bool
{
1317 NameBindingKind
::Import { .. }
=> true,
1323 struct PrivacyError
<'a
>(Span
, Ident
, &'a NameBinding
<'a
>);
1325 struct UseError
<'a
> {
1326 err
: DiagnosticBuilder
<'a
>,
1327 /// Attach `use` statements for these candidates.
1328 candidates
: Vec
<ImportSuggestion
>,
1329 /// The `NodeId` of the module to place the use-statements in.
1331 /// Whether the diagnostic should state that it's "better".
1335 #[derive(Clone, Copy, PartialEq, Debug)]
1336 enum AmbiguityKind
{
1340 LegacyHelperVsPrelude
,
1345 MoreExpandedVsOuter
,
1348 impl AmbiguityKind
{
1349 fn descr(self) -> &'
static str {
1351 AmbiguityKind
::Import
=>
1352 "name vs any other name during import resolution",
1353 AmbiguityKind
::BuiltinAttr
=>
1354 "built-in attribute vs any other name",
1355 AmbiguityKind
::DeriveHelper
=>
1356 "derive helper attribute vs any other name",
1357 AmbiguityKind
::LegacyHelperVsPrelude
=>
1358 "legacy plugin helper attribute vs name from prelude",
1359 AmbiguityKind
::LegacyVsModern
=>
1360 "`macro_rules` vs non-`macro_rules` from other module",
1361 AmbiguityKind
::GlobVsOuter
=>
1362 "glob import vs any other name from outer scope during import/macro resolution",
1363 AmbiguityKind
::GlobVsGlob
=>
1364 "glob import vs glob import in the same module",
1365 AmbiguityKind
::GlobVsExpanded
=>
1366 "glob import vs macro-expanded name in the same \
1367 module during import/macro resolution",
1368 AmbiguityKind
::MoreExpandedVsOuter
=>
1369 "macro-expanded name vs less macro-expanded name \
1370 from outer scope during import/macro resolution",
1375 /// Miscellaneous bits of metadata for better ambiguity error reporting.
1376 #[derive(Clone, Copy, PartialEq)]
1377 enum AmbiguityErrorMisc
{
1384 struct AmbiguityError
<'a
> {
1385 kind
: AmbiguityKind
,
1387 b1
: &'a NameBinding
<'a
>,
1388 b2
: &'a NameBinding
<'a
>,
1389 misc1
: AmbiguityErrorMisc
,
1390 misc2
: AmbiguityErrorMisc
,
1393 impl<'a
> NameBinding
<'a
> {
1394 fn module(&self) -> Option
<Module
<'a
>> {
1396 NameBindingKind
::Module(module
) => Some(module
),
1397 NameBindingKind
::Import { binding, .. }
=> binding
.module(),
1402 fn res(&self) -> Res
{
1404 NameBindingKind
::Res(res
, _
) => res
,
1405 NameBindingKind
::Module(module
) => module
.res().unwrap(),
1406 NameBindingKind
::Import { binding, .. }
=> binding
.res(),
1410 fn is_ambiguity(&self) -> bool
{
1411 self.ambiguity
.is_some() || match self.kind
{
1412 NameBindingKind
::Import { binding, .. }
=> binding
.is_ambiguity(),
1417 // We sometimes need to treat variants as `pub` for backwards compatibility.
1418 fn pseudo_vis(&self) -> ty
::Visibility
{
1419 if self.is_variant() && self.res().def_id().is_local() {
1420 ty
::Visibility
::Public
1426 fn is_variant(&self) -> bool
{
1428 NameBindingKind
::Res(Res
::Def(DefKind
::Variant
, _
), _
) |
1429 NameBindingKind
::Res(Res
::Def(DefKind
::Ctor(CtorOf
::Variant
, ..), _
), _
) => true,
1434 fn is_extern_crate(&self) -> bool
{
1436 NameBindingKind
::Import
{
1437 directive
: &ImportDirective
{
1438 subclass
: ImportDirectiveSubclass
::ExternCrate { .. }
, ..
1441 NameBindingKind
::Module(
1442 &ModuleData { kind: ModuleKind::Def(DefKind::Mod, def_id, _), .. }
1443 ) => def_id
.index
== CRATE_DEF_INDEX
,
1448 fn is_import(&self) -> bool
{
1450 NameBindingKind
::Import { .. }
=> true,
1455 fn is_glob_import(&self) -> bool
{
1457 NameBindingKind
::Import { directive, .. }
=> directive
.is_glob(),
1462 fn is_importable(&self) -> bool
{
1464 Res
::Def(DefKind
::AssocConst
, _
)
1465 | Res
::Def(DefKind
::Method
, _
)
1466 | Res
::Def(DefKind
::AssocTy
, _
) => false,
1471 fn is_macro_def(&self) -> bool
{
1473 NameBindingKind
::Res(Res
::Def(DefKind
::Macro(..), _
), _
) => true,
1478 fn macro_kind(&self) -> Option
<MacroKind
> {
1480 Res
::Def(DefKind
::Macro(kind
), _
) => Some(kind
),
1481 Res
::NonMacroAttr(..) => Some(MacroKind
::Attr
),
1486 fn descr(&self) -> &'
static str {
1487 if self.is_extern_crate() { "extern crate" }
else { self.res().descr() }
1490 fn article(&self) -> &'
static str {
1491 if self.is_extern_crate() { "an" }
else { self.res().article() }
1494 // Suppose that we resolved macro invocation with `invoc_parent_expansion` to binding `binding`
1495 // at some expansion round `max(invoc, binding)` when they both emerged from macros.
1496 // Then this function returns `true` if `self` may emerge from a macro *after* that
1497 // in some later round and screw up our previously found resolution.
1498 // See more detailed explanation in
1499 // https://github.com/rust-lang/rust/pull/53778#issuecomment-419224049
1500 fn may_appear_after(&self, invoc_parent_expansion
: Mark
, binding
: &NameBinding
<'_
>) -> bool
{
1501 // self > max(invoc, binding) => !(self <= invoc || self <= binding)
1502 // Expansions are partially ordered, so "may appear after" is an inversion of
1503 // "certainly appears before or simultaneously" and includes unordered cases.
1504 let self_parent_expansion
= self.expansion
;
1505 let other_parent_expansion
= binding
.expansion
;
1506 let certainly_before_other_or_simultaneously
=
1507 other_parent_expansion
.is_descendant_of(self_parent_expansion
);
1508 let certainly_before_invoc_or_simultaneously
=
1509 invoc_parent_expansion
.is_descendant_of(self_parent_expansion
);
1510 !(certainly_before_other_or_simultaneously
|| certainly_before_invoc_or_simultaneously
)
1514 /// Interns the names of the primitive types.
1516 /// All other types are defined somewhere and possibly imported, but the primitive ones need
1517 /// special handling, since they have no place of origin.
1518 struct PrimitiveTypeTable
{
1519 primitive_types
: FxHashMap
<Name
, PrimTy
>,
1522 impl PrimitiveTypeTable
{
1523 fn new() -> PrimitiveTypeTable
{
1524 let mut table
= FxHashMap
::default();
1526 table
.insert(sym
::bool
, Bool
);
1527 table
.insert(sym
::char, Char
);
1528 table
.insert(sym
::f32, Float(FloatTy
::F32
));
1529 table
.insert(sym
::f64, Float(FloatTy
::F64
));
1530 table
.insert(sym
::isize, Int(IntTy
::Isize
));
1531 table
.insert(sym
::i8, Int(IntTy
::I8
));
1532 table
.insert(sym
::i16, Int(IntTy
::I16
));
1533 table
.insert(sym
::i32, Int(IntTy
::I32
));
1534 table
.insert(sym
::i64, Int(IntTy
::I64
));
1535 table
.insert(sym
::i128
, Int(IntTy
::I128
));
1536 table
.insert(sym
::str, Str
);
1537 table
.insert(sym
::usize, Uint(UintTy
::Usize
));
1538 table
.insert(sym
::u8, Uint(UintTy
::U8
));
1539 table
.insert(sym
::u16, Uint(UintTy
::U16
));
1540 table
.insert(sym
::u32, Uint(UintTy
::U32
));
1541 table
.insert(sym
::u64, Uint(UintTy
::U64
));
1542 table
.insert(sym
::u128
, Uint(UintTy
::U128
));
1543 Self { primitive_types: table }
1547 #[derive(Debug, Default, Clone)]
1548 pub struct ExternPreludeEntry
<'a
> {
1549 extern_crate_item
: Option
<&'a NameBinding
<'a
>>,
1550 pub introduced_by_item
: bool
,
1553 /// The main resolver class.
1555 /// This is the visitor that walks the whole crate.
1556 pub struct Resolver
<'a
> {
1557 session
: &'a Session
,
1560 pub definitions
: Definitions
,
1562 graph_root
: Module
<'a
>,
1564 prelude
: Option
<Module
<'a
>>,
1565 pub extern_prelude
: FxHashMap
<Ident
, ExternPreludeEntry
<'a
>>,
1567 /// N.B., this is used only for better diagnostics, not name resolution itself.
1568 has_self
: FxHashSet
<DefId
>,
1570 /// Names of fields of an item `DefId` accessible with dot syntax.
1571 /// Used for hints during error reporting.
1572 field_names
: FxHashMap
<DefId
, Vec
<Name
>>,
1574 /// All imports known to succeed or fail.
1575 determined_imports
: Vec
<&'a ImportDirective
<'a
>>,
1577 /// All non-determined imports.
1578 indeterminate_imports
: Vec
<&'a ImportDirective
<'a
>>,
1580 /// The module that represents the current item scope.
1581 current_module
: Module
<'a
>,
1583 /// The current set of local scopes for types and values.
1584 /// FIXME #4948: Reuse ribs to avoid allocation.
1585 ribs
: PerNS
<Vec
<Rib
<'a
>>>,
1587 /// The current set of local scopes, for labels.
1588 label_ribs
: Vec
<Rib
<'a
, NodeId
>>,
1590 /// The trait that the current context can refer to.
1591 current_trait_ref
: Option
<(Module
<'a
>, TraitRef
)>,
1593 /// The current self type if inside an impl (used for better errors).
1594 current_self_type
: Option
<Ty
>,
1596 /// The current self item if inside an ADT (used for better errors).
1597 current_self_item
: Option
<NodeId
>,
1599 /// FIXME: Refactor things so that these fields are passed through arguments and not resolver.
1600 /// We are resolving a last import segment during import validation.
1601 last_import_segment
: bool
,
1602 /// This binding should be ignored during in-module resolution, so that we don't get
1603 /// "self-confirming" import resolutions during import validation.
1604 blacklisted_binding
: Option
<&'a NameBinding
<'a
>>,
1606 /// The idents for the primitive types.
1607 primitive_type_table
: PrimitiveTypeTable
,
1609 /// Resolutions for nodes that have a single resolution.
1610 partial_res_map
: NodeMap
<PartialRes
>,
1611 /// Resolutions for import nodes, which have multiple resolutions in different namespaces.
1612 import_res_map
: NodeMap
<PerNS
<Option
<Res
>>>,
1613 /// Resolutions for labels (node IDs of their corresponding blocks or loops).
1614 label_res_map
: NodeMap
<NodeId
>,
1616 pub export_map
: ExportMap
<NodeId
>,
1617 pub trait_map
: TraitMap
,
1619 /// A map from nodes to anonymous modules.
1620 /// Anonymous modules are pseudo-modules that are implicitly created around items
1621 /// contained within blocks.
1623 /// For example, if we have this:
1631 /// There will be an anonymous module created around `g` with the ID of the
1632 /// entry block for `f`.
1633 block_map
: NodeMap
<Module
<'a
>>,
1634 module_map
: FxHashMap
<DefId
, Module
<'a
>>,
1635 extern_module_map
: FxHashMap
<(DefId
, bool
/* MacrosOnly? */), Module
<'a
>>,
1636 binding_parent_modules
: FxHashMap
<PtrKey
<'a
, NameBinding
<'a
>>, Module
<'a
>>,
1638 /// Maps glob imports to the names of items actually imported.
1639 pub glob_map
: GlobMap
,
1641 used_imports
: FxHashSet
<(NodeId
, Namespace
)>,
1642 pub maybe_unused_trait_imports
: NodeSet
,
1643 pub maybe_unused_extern_crates
: Vec
<(NodeId
, Span
)>,
1645 /// A list of labels as of yet unused. Labels will be removed from this map when
1646 /// they are used (in a `break` or `continue` statement)
1647 pub unused_labels
: FxHashMap
<NodeId
, Span
>,
1649 /// Privacy errors are delayed until the end in order to deduplicate them.
1650 privacy_errors
: Vec
<PrivacyError
<'a
>>,
1651 /// Ambiguity errors are delayed for deduplication.
1652 ambiguity_errors
: Vec
<AmbiguityError
<'a
>>,
1653 /// `use` injections are delayed for better placement and deduplication.
1654 use_injections
: Vec
<UseError
<'a
>>,
1655 /// Crate-local macro expanded `macro_export` referred to by a module-relative path.
1656 macro_expanded_macro_export_errors
: BTreeSet
<(Span
, Span
)>,
1658 arenas
: &'a ResolverArenas
<'a
>,
1659 dummy_binding
: &'a NameBinding
<'a
>,
1661 crate_loader
: &'a
mut CrateLoader
<'a
>,
1662 macro_names
: FxHashSet
<Ident
>,
1663 builtin_macros
: FxHashMap
<Name
, &'a NameBinding
<'a
>>,
1664 macro_use_prelude
: FxHashMap
<Name
, &'a NameBinding
<'a
>>,
1665 pub all_macros
: FxHashMap
<Name
, Res
>,
1666 macro_map
: FxHashMap
<DefId
, Lrc
<SyntaxExtension
>>,
1667 non_macro_attrs
: [Lrc
<SyntaxExtension
>; 2],
1668 macro_defs
: FxHashMap
<Mark
, DefId
>,
1669 local_macro_def_scopes
: FxHashMap
<NodeId
, Module
<'a
>>,
1671 /// List of crate local macros that we need to warn about as being unused.
1672 /// Right now this only includes macro_rules! macros, and macros 2.0.
1673 unused_macros
: FxHashSet
<DefId
>,
1675 /// Maps the `Mark` of an expansion to its containing module or block.
1676 invocations
: FxHashMap
<Mark
, &'a InvocationData
<'a
>>,
1678 /// Avoid duplicated errors for "name already defined".
1679 name_already_seen
: FxHashMap
<Name
, Span
>,
1681 potentially_unused_imports
: Vec
<&'a ImportDirective
<'a
>>,
1683 /// Table for mapping struct IDs into struct constructor IDs,
1684 /// it's not used during normal resolution, only for better error reporting.
1685 struct_constructors
: DefIdMap
<(Res
, ty
::Visibility
)>,
1687 /// Only used for better errors on `fn(): fn()`.
1688 current_type_ascription
: Vec
<Span
>,
1690 injected_crate
: Option
<Module
<'a
>>,
1693 /// Nothing really interesting here; it just provides memory for the rest of the crate.
1695 pub struct ResolverArenas
<'a
> {
1696 modules
: arena
::TypedArena
<ModuleData
<'a
>>,
1697 local_modules
: RefCell
<Vec
<Module
<'a
>>>,
1698 name_bindings
: arena
::TypedArena
<NameBinding
<'a
>>,
1699 import_directives
: arena
::TypedArena
<ImportDirective
<'a
>>,
1700 name_resolutions
: arena
::TypedArena
<RefCell
<NameResolution
<'a
>>>,
1701 invocation_data
: arena
::TypedArena
<InvocationData
<'a
>>,
1702 legacy_bindings
: arena
::TypedArena
<LegacyBinding
<'a
>>,
1705 impl<'a
> ResolverArenas
<'a
> {
1706 fn alloc_module(&'a
self, module
: ModuleData
<'a
>) -> Module
<'a
> {
1707 let module
= self.modules
.alloc(module
);
1708 if module
.def_id().map(|def_id
| def_id
.is_local()).unwrap_or(true) {
1709 self.local_modules
.borrow_mut().push(module
);
1713 fn local_modules(&'a
self) -> std
::cell
::Ref
<'a
, Vec
<Module
<'a
>>> {
1714 self.local_modules
.borrow()
1716 fn alloc_name_binding(&'a
self, name_binding
: NameBinding
<'a
>) -> &'a NameBinding
<'a
> {
1717 self.name_bindings
.alloc(name_binding
)
1719 fn alloc_import_directive(&'a
self, import_directive
: ImportDirective
<'a
>)
1720 -> &'a ImportDirective
<'_
> {
1721 self.import_directives
.alloc(import_directive
)
1723 fn alloc_name_resolution(&'a
self) -> &'a RefCell
<NameResolution
<'a
>> {
1724 self.name_resolutions
.alloc(Default
::default())
1726 fn alloc_invocation_data(&'a
self, expansion_data
: InvocationData
<'a
>)
1727 -> &'a InvocationData
<'a
> {
1728 self.invocation_data
.alloc(expansion_data
)
1730 fn alloc_legacy_binding(&'a
self, binding
: LegacyBinding
<'a
>) -> &'a LegacyBinding
<'a
> {
1731 self.legacy_bindings
.alloc(binding
)
1735 impl<'a
, 'b
> ty
::DefIdTree
for &'a Resolver
<'b
> {
1736 fn parent(self, id
: DefId
) -> Option
<DefId
> {
1738 LOCAL_CRATE
=> self.definitions
.def_key(id
.index
).parent
,
1739 _
=> self.cstore
.def_key(id
).parent
,
1740 }.map(|index
| DefId { index, ..id }
)
1744 /// This interface is used through the AST→HIR step, to embed full paths into the HIR. After that
1745 /// the resolver is no longer needed as all the relevant information is inline.
1746 impl<'a
> hir
::lowering
::Resolver
for Resolver
<'a
> {
1747 fn resolve_ast_path(
1752 self.resolve_ast_path_cb(path
, is_value
,
1753 |resolver
, span
, error
| resolve_error(resolver
, span
, error
))
1756 fn resolve_str_path(
1759 crate_root
: Option
<Symbol
>,
1760 components
: &[Symbol
],
1762 ) -> (ast
::Path
, Res
) {
1763 let root
= if crate_root
.is_some() {
1768 let segments
= iter
::once(Ident
::with_empty_ctxt(root
))
1770 crate_root
.into_iter()
1771 .chain(components
.iter().cloned())
1772 .map(Ident
::with_empty_ctxt
)
1773 ).map(|i
| self.new_ast_path_segment(i
)).collect
::<Vec
<_
>>();
1775 let path
= ast
::Path
{
1780 let res
= self.resolve_ast_path(&path
, is_value
);
1784 fn get_partial_res(&mut self, id
: NodeId
) -> Option
<PartialRes
> {
1785 self.partial_res_map
.get(&id
).cloned()
1788 fn get_import_res(&mut self, id
: NodeId
) -> PerNS
<Option
<Res
>> {
1789 self.import_res_map
.get(&id
).cloned().unwrap_or_default()
1792 fn get_label_res(&mut self, id
: NodeId
) -> Option
<NodeId
> {
1793 self.label_res_map
.get(&id
).cloned()
1796 fn definitions(&mut self) -> &mut Definitions
{
1797 &mut self.definitions
1801 impl<'a
> Resolver
<'a
> {
1802 /// Rustdoc uses this to resolve things in a recoverable way. `ResolutionError<'a>`
1803 /// isn't something that can be returned because it can't be made to live that long,
1804 /// and also it's a private type. Fortunately rustdoc doesn't need to know the error,
1805 /// just that an error occurred.
1806 pub fn resolve_str_path_error(&mut self, span
: Span
, path_str
: &str, is_value
: bool
)
1807 -> Result
<(ast
::Path
, Res
), ()> {
1808 let mut errored
= false;
1810 let path
= if path_str
.starts_with("::") {
1813 segments
: iter
::once(Ident
::with_empty_ctxt(kw
::PathRoot
))
1815 path_str
.split("::").skip(1).map(Ident
::from_str
)
1817 .map(|i
| self.new_ast_path_segment(i
))
1825 .map(Ident
::from_str
)
1826 .map(|i
| self.new_ast_path_segment(i
))
1830 let res
= self.resolve_ast_path_cb(&path
, is_value
, |_
, _
, _
| errored
= true);
1831 if errored
|| res
== def
::Res
::Err
{
1838 /// Like `resolve_ast_path`, but takes a callback in case there was an error.
1839 // FIXME(eddyb) use `Result` or something instead of callbacks.
1840 fn resolve_ast_path_cb
<F
>(
1846 where F
: for<'c
, 'b
> FnOnce(&'c
mut Resolver
<'_
>, Span
, ResolutionError
<'b
>)
1848 let namespace
= if is_value { ValueNS }
else { TypeNS }
;
1849 let span
= path
.span
;
1850 let path
= Segment
::from_path(&path
);
1851 // FIXME(Manishearth): intra-doc links won't get warned of epoch changes.
1852 match self.resolve_path_without_parent_scope(&path
, Some(namespace
), true,
1853 span
, CrateLint
::No
) {
1854 PathResult
::Module(ModuleOrUniformRoot
::Module(module
)) =>
1855 module
.res().unwrap(),
1856 PathResult
::NonModule(path_res
) if path_res
.unresolved_segments() == 0 =>
1857 path_res
.base_res(),
1858 PathResult
::NonModule(..) => {
1859 error_callback(self, span
, ResolutionError
::FailedToResolve
{
1860 label
: String
::from("type-relative paths are not supported in this context"),
1865 PathResult
::Module(..) | PathResult
::Indeterminate
=> unreachable
!(),
1866 PathResult
::Failed { span, label, suggestion, .. }
=> {
1867 error_callback(self, span
, ResolutionError
::FailedToResolve
{
1876 fn new_ast_path_segment(&self, ident
: Ident
) -> ast
::PathSegment
{
1877 let mut seg
= ast
::PathSegment
::from_ident(ident
);
1878 seg
.id
= self.session
.next_node_id();
1883 impl<'a
> Resolver
<'a
> {
1884 pub fn new(session
: &'a Session
,
1888 crate_loader
: &'a
mut CrateLoader
<'a
>,
1889 arenas
: &'a ResolverArenas
<'a
>)
1891 let root_def_id
= DefId
::local(CRATE_DEF_INDEX
);
1892 let root_module_kind
= ModuleKind
::Def(
1897 let graph_root
= arenas
.alloc_module(ModuleData
{
1898 no_implicit_prelude
: attr
::contains_name(&krate
.attrs
, sym
::no_implicit_prelude
),
1899 ..ModuleData
::new(None
, root_module_kind
, root_def_id
, Mark
::root(), krate
.span
)
1901 let mut module_map
= FxHashMap
::default();
1902 module_map
.insert(DefId
::local(CRATE_DEF_INDEX
), graph_root
);
1904 let mut definitions
= Definitions
::default();
1905 DefCollector
::new(&mut definitions
, Mark
::root())
1906 .collect_root(crate_name
, session
.local_crate_disambiguator());
1908 let mut extern_prelude
: FxHashMap
<Ident
, ExternPreludeEntry
<'_
>> =
1909 session
.opts
.externs
.iter().map(|kv
| (Ident
::from_str(kv
.0), Default
::default()))
1912 if !attr
::contains_name(&krate
.attrs
, sym
::no_core
) {
1913 extern_prelude
.insert(Ident
::with_empty_ctxt(sym
::core
), Default
::default());
1914 if !attr
::contains_name(&krate
.attrs
, sym
::no_std
) {
1915 extern_prelude
.insert(Ident
::with_empty_ctxt(sym
::std
), Default
::default());
1916 if session
.rust_2018() {
1917 extern_prelude
.insert(Ident
::with_empty_ctxt(sym
::meta
), Default
::default());
1922 let mut invocations
= FxHashMap
::default();
1923 invocations
.insert(Mark
::root(),
1924 arenas
.alloc_invocation_data(InvocationData
::root(graph_root
)));
1926 let mut macro_defs
= FxHashMap
::default();
1927 macro_defs
.insert(Mark
::root(), root_def_id
);
1929 let non_macro_attr
= |mark_used
| Lrc
::new(SyntaxExtension
::default(
1930 SyntaxExtensionKind
::NonMacroAttr { mark_used }
, session
.edition()
1940 // The outermost module has def ID 0; this is not reflected in the
1946 has_self
: FxHashSet
::default(),
1947 field_names
: FxHashMap
::default(),
1949 determined_imports
: Vec
::new(),
1950 indeterminate_imports
: Vec
::new(),
1952 current_module
: graph_root
,
1954 value_ns
: vec
![Rib
::new(ModuleRibKind(graph_root
))],
1955 type_ns
: vec
![Rib
::new(ModuleRibKind(graph_root
))],
1956 macro_ns
: vec
![Rib
::new(ModuleRibKind(graph_root
))],
1958 label_ribs
: Vec
::new(),
1960 current_trait_ref
: None
,
1961 current_self_type
: None
,
1962 current_self_item
: None
,
1963 last_import_segment
: false,
1964 blacklisted_binding
: None
,
1966 primitive_type_table
: PrimitiveTypeTable
::new(),
1968 partial_res_map
: Default
::default(),
1969 import_res_map
: Default
::default(),
1970 label_res_map
: Default
::default(),
1971 export_map
: FxHashMap
::default(),
1972 trait_map
: Default
::default(),
1974 block_map
: Default
::default(),
1975 extern_module_map
: FxHashMap
::default(),
1976 binding_parent_modules
: FxHashMap
::default(),
1978 glob_map
: Default
::default(),
1980 used_imports
: FxHashSet
::default(),
1981 maybe_unused_trait_imports
: Default
::default(),
1982 maybe_unused_extern_crates
: Vec
::new(),
1984 unused_labels
: FxHashMap
::default(),
1986 privacy_errors
: Vec
::new(),
1987 ambiguity_errors
: Vec
::new(),
1988 use_injections
: Vec
::new(),
1989 macro_expanded_macro_export_errors
: BTreeSet
::new(),
1992 dummy_binding
: arenas
.alloc_name_binding(NameBinding
{
1993 kind
: NameBindingKind
::Res(Res
::Err
, false),
1995 expansion
: Mark
::root(),
1997 vis
: ty
::Visibility
::Public
,
2001 macro_names
: FxHashSet
::default(),
2002 builtin_macros
: FxHashMap
::default(),
2003 macro_use_prelude
: FxHashMap
::default(),
2004 all_macros
: FxHashMap
::default(),
2005 macro_map
: FxHashMap
::default(),
2006 non_macro_attrs
: [non_macro_attr(false), non_macro_attr(true)],
2009 local_macro_def_scopes
: FxHashMap
::default(),
2010 name_already_seen
: FxHashMap
::default(),
2011 potentially_unused_imports
: Vec
::new(),
2012 struct_constructors
: Default
::default(),
2013 unused_macros
: FxHashSet
::default(),
2014 current_type_ascription
: Vec
::new(),
2015 injected_crate
: None
,
2019 pub fn arenas() -> ResolverArenas
<'a
> {
2023 fn non_macro_attr(&self, mark_used
: bool
) -> Lrc
<SyntaxExtension
> {
2024 self.non_macro_attrs
[mark_used
as usize].clone()
2027 /// Runs the function on each namespace.
2028 fn per_ns
<F
: FnMut(&mut Self, Namespace
)>(&mut self, mut f
: F
) {
2034 fn macro_def(&self, mut ctxt
: SyntaxContext
) -> DefId
{
2036 match self.macro_defs
.get(&ctxt
.outer()) {
2037 Some(&def_id
) => return def_id
,
2038 None
=> ctxt
.remove_mark(),
2043 /// Entry point to crate resolution.
2044 pub fn resolve_crate(&mut self, krate
: &Crate
) {
2045 ImportResolver { resolver: self }
.finalize_imports();
2046 self.current_module
= self.graph_root
;
2047 self.finalize_current_module_macro_resolutions();
2049 visit
::walk_crate(self, krate
);
2051 check_unused
::check_crate(self, krate
);
2052 self.report_errors(krate
);
2053 self.crate_loader
.postprocess(krate
);
2060 normal_ancestor_id
: DefId
,
2064 let module
= ModuleData
::new(Some(parent
), kind
, normal_ancestor_id
, expansion
, span
);
2065 self.arenas
.alloc_module(module
)
2068 fn record_use(&mut self, ident
: Ident
, ns
: Namespace
,
2069 used_binding
: &'a NameBinding
<'a
>, is_lexical_scope
: bool
) {
2070 if let Some((b2
, kind
)) = used_binding
.ambiguity
{
2071 self.ambiguity_errors
.push(AmbiguityError
{
2072 kind
, ident
, b1
: used_binding
, b2
,
2073 misc1
: AmbiguityErrorMisc
::None
,
2074 misc2
: AmbiguityErrorMisc
::None
,
2077 if let NameBindingKind
::Import { directive, binding, ref used }
= used_binding
.kind
{
2078 // Avoid marking `extern crate` items that refer to a name from extern prelude,
2079 // but not introduce it, as used if they are accessed from lexical scope.
2080 if is_lexical_scope
{
2081 if let Some(entry
) = self.extern_prelude
.get(&ident
.modern()) {
2082 if let Some(crate_item
) = entry
.extern_crate_item
{
2083 if ptr
::eq(used_binding
, crate_item
) && !entry
.introduced_by_item
{
2090 directive
.used
.set(true);
2091 self.used_imports
.insert((directive
.id
, ns
));
2092 self.add_to_glob_map(&directive
, ident
);
2093 self.record_use(ident
, ns
, binding
, false);
2098 fn add_to_glob_map(&mut self, directive
: &ImportDirective
<'_
>, ident
: Ident
) {
2099 if directive
.is_glob() {
2100 self.glob_map
.entry(directive
.id
).or_default().insert(ident
.name
);
2104 /// This resolves the identifier `ident` in the namespace `ns` in the current lexical scope.
2105 /// More specifically, we proceed up the hierarchy of scopes and return the binding for
2106 /// `ident` in the first scope that defines it (or None if no scopes define it).
2108 /// A block's items are above its local variables in the scope hierarchy, regardless of where
2109 /// the items are defined in the block. For example,
2112 /// g(); // Since there are no local variables in scope yet, this resolves to the item.
2115 /// g(); // This resolves to the local variable `g` since it shadows the item.
2119 /// Invariant: This must only be called during main resolution, not during
2120 /// import resolution.
2121 fn resolve_ident_in_lexical_scope(&mut self,
2124 record_used_id
: Option
<NodeId
>,
2126 -> Option
<LexicalScopeBinding
<'a
>> {
2127 assert
!(ns
== TypeNS
|| ns
== ValueNS
);
2128 if ident
.name
== kw
::Invalid
{
2129 return Some(LexicalScopeBinding
::Res(Res
::Err
));
2131 ident
.span
= if ident
.name
== kw
::SelfUpper
{
2132 // FIXME(jseyfried) improve `Self` hygiene
2133 ident
.span
.with_ctxt(SyntaxContext
::empty())
2134 } else if ns
== TypeNS
{
2137 ident
.span
.modern_and_legacy()
2140 // Walk backwards up the ribs in scope.
2141 let record_used
= record_used_id
.is_some();
2142 let mut module
= self.graph_root
;
2143 for i
in (0 .. self.ribs
[ns
].len()).rev() {
2144 debug
!("walk rib\n{:?}", self.ribs
[ns
][i
].bindings
);
2145 if let Some(res
) = self.ribs
[ns
][i
].bindings
.get(&ident
).cloned() {
2146 // The ident resolves to a type parameter or local variable.
2147 return Some(LexicalScopeBinding
::Res(
2148 self.validate_res_from_ribs(ns
, i
, res
, record_used
, path_span
),
2152 module
= match self.ribs
[ns
][i
].kind
{
2153 ModuleRibKind(module
) => module
,
2154 MacroDefinition(def
) if def
== self.macro_def(ident
.span
.ctxt()) => {
2155 // If an invocation of this macro created `ident`, give up on `ident`
2156 // and switch to `ident`'s source from the macro definition.
2157 ident
.span
.remove_mark();
2163 let item
= self.resolve_ident_in_module_unadjusted(
2164 ModuleOrUniformRoot
::Module(module
),
2170 if let Ok(binding
) = item
{
2171 // The ident resolves to an item.
2172 return Some(LexicalScopeBinding
::Item(binding
));
2176 ModuleKind
::Block(..) => {}
, // We can see through blocks
2181 ident
.span
= ident
.span
.modern();
2182 let mut poisoned
= None
;
2184 let opt_module
= if let Some(node_id
) = record_used_id
{
2185 self.hygienic_lexical_parent_with_compatibility_fallback(module
, &mut ident
.span
,
2186 node_id
, &mut poisoned
)
2188 self.hygienic_lexical_parent(module
, &mut ident
.span
)
2190 module
= unwrap_or
!(opt_module
, break);
2191 let orig_current_module
= self.current_module
;
2192 self.current_module
= module
; // Lexical resolutions can never be a privacy error.
2193 let result
= self.resolve_ident_in_module_unadjusted(
2194 ModuleOrUniformRoot
::Module(module
),
2200 self.current_module
= orig_current_module
;
2204 if let Some(node_id
) = poisoned
{
2205 self.session
.buffer_lint_with_diagnostic(
2206 lint
::builtin
::PROC_MACRO_DERIVE_RESOLUTION_FALLBACK
,
2207 node_id
, ident
.span
,
2208 &format
!("cannot find {} `{}` in this scope", ns
.descr(), ident
),
2209 lint
::builtin
::BuiltinLintDiagnostics
::
2210 ProcMacroDeriveResolutionFallback(ident
.span
),
2213 return Some(LexicalScopeBinding
::Item(binding
))
2215 Err(Determined
) => continue,
2216 Err(Undetermined
) =>
2217 span_bug
!(ident
.span
, "undetermined resolution during main resolution pass"),
2221 if !module
.no_implicit_prelude
{
2223 if let Some(binding
) = self.extern_prelude_get(ident
, !record_used
) {
2224 return Some(LexicalScopeBinding
::Item(binding
));
2227 if ns
== TypeNS
&& is_known_tool(ident
.name
) {
2228 let binding
= (Res
::ToolMod
, ty
::Visibility
::Public
,
2229 DUMMY_SP
, Mark
::root()).to_name_binding(self.arenas
);
2230 return Some(LexicalScopeBinding
::Item(binding
));
2232 if let Some(prelude
) = self.prelude
{
2233 if let Ok(binding
) = self.resolve_ident_in_module_unadjusted(
2234 ModuleOrUniformRoot
::Module(prelude
),
2240 return Some(LexicalScopeBinding
::Item(binding
));
2248 fn hygienic_lexical_parent(&mut self, module
: Module
<'a
>, span
: &mut Span
)
2249 -> Option
<Module
<'a
>> {
2250 if !module
.expansion
.outer_is_descendant_of(span
.ctxt()) {
2251 return Some(self.macro_def_scope(span
.remove_mark()));
2254 if let ModuleKind
::Block(..) = module
.kind
{
2255 return Some(module
.parent
.unwrap());
2261 fn hygienic_lexical_parent_with_compatibility_fallback(&mut self, module
: Module
<'a
>,
2262 span
: &mut Span
, node_id
: NodeId
,
2263 poisoned
: &mut Option
<NodeId
>)
2264 -> Option
<Module
<'a
>> {
2265 if let module @
Some(..) = self.hygienic_lexical_parent(module
, span
) {
2269 // We need to support the next case under a deprecation warning
2272 // ---- begin: this comes from a proc macro derive
2273 // mod implementation_details {
2274 // // Note that `MyStruct` is not in scope here.
2275 // impl SomeTrait for MyStruct { ... }
2279 // So we have to fall back to the module's parent during lexical resolution in this case.
2280 if let Some(parent
) = module
.parent
{
2281 // Inner module is inside the macro, parent module is outside of the macro.
2282 if module
.expansion
!= parent
.expansion
&&
2283 module
.expansion
.is_descendant_of(parent
.expansion
) {
2284 // The macro is a proc macro derive
2285 if module
.expansion
.looks_like_proc_macro_derive() {
2286 if parent
.expansion
.outer_is_descendant_of(span
.ctxt()) {
2287 *poisoned
= Some(node_id
);
2288 return module
.parent
;
2297 fn resolve_ident_in_module(
2299 module
: ModuleOrUniformRoot
<'a
>,
2302 parent_scope
: Option
<&ParentScope
<'a
>>,
2305 ) -> Result
<&'a NameBinding
<'a
>, Determinacy
> {
2306 self.resolve_ident_in_module_ext(
2307 module
, ident
, ns
, parent_scope
, record_used
, path_span
2308 ).map_err(|(determinacy
, _
)| determinacy
)
2311 fn resolve_ident_in_module_ext(
2313 module
: ModuleOrUniformRoot
<'a
>,
2316 parent_scope
: Option
<&ParentScope
<'a
>>,
2319 ) -> Result
<&'a NameBinding
<'a
>, (Determinacy
, Weak
)> {
2320 let orig_current_module
= self.current_module
;
2322 ModuleOrUniformRoot
::Module(module
) => {
2323 if let Some(def
) = ident
.span
.modernize_and_adjust(module
.expansion
) {
2324 self.current_module
= self.macro_def_scope(def
);
2327 ModuleOrUniformRoot
::ExternPrelude
=> {
2328 ident
.span
.modernize_and_adjust(Mark
::root());
2330 ModuleOrUniformRoot
::CrateRootAndExternPrelude
|
2331 ModuleOrUniformRoot
::CurrentScope
=> {
2335 let result
= self.resolve_ident_in_module_unadjusted_ext(
2336 module
, ident
, ns
, parent_scope
, false, record_used
, path_span
,
2338 self.current_module
= orig_current_module
;
2342 fn resolve_crate_root(&mut self, ident
: Ident
) -> Module
<'a
> {
2343 let mut ctxt
= ident
.span
.ctxt();
2344 let mark
= if ident
.name
== kw
::DollarCrate
{
2345 // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
2346 // we don't want to pretend that the `macro_rules!` definition is in the `macro`
2347 // as described in `SyntaxContext::apply_mark`, so we ignore prepended modern marks.
2348 // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!`
2349 // definitions actually produced by `macro` and `macro` definitions produced by
2350 // `macro_rules!`, but at least such configurations are not stable yet.
2351 ctxt
= ctxt
.modern_and_legacy();
2352 let mut iter
= ctxt
.marks().into_iter().rev().peekable();
2353 let mut result
= None
;
2354 // Find the last modern mark from the end if it exists.
2355 while let Some(&(mark
, transparency
)) = iter
.peek() {
2356 if transparency
== Transparency
::Opaque
{
2357 result
= Some(mark
);
2363 // Then find the last legacy mark from the end if it exists.
2364 for (mark
, transparency
) in iter
{
2365 if transparency
== Transparency
::SemiTransparent
{
2366 result
= Some(mark
);
2373 ctxt
= ctxt
.modern();
2374 ctxt
.adjust(Mark
::root())
2376 let module
= match mark
{
2377 Some(def
) => self.macro_def_scope(def
),
2378 None
=> return self.graph_root
,
2380 self.get_module(DefId { index: CRATE_DEF_INDEX, ..module.normal_ancestor_id }
)
2383 fn resolve_self(&mut self, ctxt
: &mut SyntaxContext
, module
: Module
<'a
>) -> Module
<'a
> {
2384 let mut module
= self.get_module(module
.normal_ancestor_id
);
2385 while module
.span
.ctxt().modern() != *ctxt
{
2386 let parent
= module
.parent
.unwrap_or_else(|| self.macro_def_scope(ctxt
.remove_mark()));
2387 module
= self.get_module(parent
.normal_ancestor_id
);
2394 // We maintain a list of value ribs and type ribs.
2396 // Simultaneously, we keep track of the current position in the module
2397 // graph in the `current_module` pointer. When we go to resolve a name in
2398 // the value or type namespaces, we first look through all the ribs and
2399 // then query the module graph. When we resolve a name in the module
2400 // namespace, we can skip all the ribs (since nested modules are not
2401 // allowed within blocks in Rust) and jump straight to the current module
2404 // Named implementations are handled separately. When we find a method
2405 // call, we consult the module node to find all of the implementations in
2406 // scope. This information is lazily cached in the module node. We then
2407 // generate a fake "implementation scope" containing all the
2408 // implementations thus found, for compatibility with old resolve pass.
2410 pub fn with_scope
<F
, T
>(&mut self, id
: NodeId
, f
: F
) -> T
2411 where F
: FnOnce(&mut Resolver
<'_
>) -> T
2413 let id
= self.definitions
.local_def_id(id
);
2414 let module
= self.module_map
.get(&id
).cloned(); // clones a reference
2415 if let Some(module
) = module
{
2416 // Move down in the graph.
2417 let orig_module
= replace(&mut self.current_module
, module
);
2418 self.ribs
[ValueNS
].push(Rib
::new(ModuleRibKind(module
)));
2419 self.ribs
[TypeNS
].push(Rib
::new(ModuleRibKind(module
)));
2421 self.finalize_current_module_macro_resolutions();
2424 self.current_module
= orig_module
;
2425 self.ribs
[ValueNS
].pop();
2426 self.ribs
[TypeNS
].pop();
2433 /// Searches the current set of local scopes for labels. Returns the first non-`None` label that
2434 /// is returned by the given predicate function
2436 /// Stops after meeting a closure.
2437 fn search_label
<P
, R
>(&self, mut ident
: Ident
, pred
: P
) -> Option
<R
>
2438 where P
: Fn(&Rib
<'_
, NodeId
>, Ident
) -> Option
<R
>
2440 for rib
in self.label_ribs
.iter().rev() {
2443 // If an invocation of this macro created `ident`, give up on `ident`
2444 // and switch to `ident`'s source from the macro definition.
2445 MacroDefinition(def
) => {
2446 if def
== self.macro_def(ident
.span
.ctxt()) {
2447 ident
.span
.remove_mark();
2451 // Do not resolve labels across function boundary
2455 let r
= pred(rib
, ident
);
2463 fn resolve_adt(&mut self, item
: &Item
, generics
: &Generics
) {
2464 debug
!("resolve_adt");
2465 self.with_current_self_item(item
, |this
| {
2466 this
.with_generic_param_rib(HasGenericParams(generics
, ItemRibKind
), |this
| {
2467 let item_def_id
= this
.definitions
.local_def_id(item
.id
);
2468 this
.with_self_rib(Res
::SelfTy(None
, Some(item_def_id
)), |this
| {
2469 visit
::walk_item(this
, item
);
2475 fn future_proof_import(&mut self, use_tree
: &ast
::UseTree
) {
2476 let segments
= &use_tree
.prefix
.segments
;
2477 if !segments
.is_empty() {
2478 let ident
= segments
[0].ident
;
2479 if ident
.is_path_segment_keyword() || ident
.span
.rust_2015() {
2483 let nss
= match use_tree
.kind
{
2484 ast
::UseTreeKind
::Simple(..) if segments
.len() == 1 => &[TypeNS
, ValueNS
][..],
2487 let report_error
= |this
: &Self, ns
| {
2488 let what
= if ns
== TypeNS { "type parameters" }
else { "local variables" }
;
2489 this
.session
.span_err(ident
.span
, &format
!("imports cannot refer to {}", what
));
2493 match self.resolve_ident_in_lexical_scope(ident
, ns
, None
, use_tree
.prefix
.span
) {
2494 Some(LexicalScopeBinding
::Res(..)) => {
2495 report_error(self, ns
);
2497 Some(LexicalScopeBinding
::Item(binding
)) => {
2498 let orig_blacklisted_binding
=
2499 mem
::replace(&mut self.blacklisted_binding
, Some(binding
));
2500 if let Some(LexicalScopeBinding
::Res(..)) =
2501 self.resolve_ident_in_lexical_scope(ident
, ns
, None
,
2502 use_tree
.prefix
.span
) {
2503 report_error(self, ns
);
2505 self.blacklisted_binding
= orig_blacklisted_binding
;
2510 } else if let ast
::UseTreeKind
::Nested(use_trees
) = &use_tree
.kind
{
2511 for (use_tree
, _
) in use_trees
{
2512 self.future_proof_import(use_tree
);
2517 fn resolve_item(&mut self, item
: &Item
) {
2518 let name
= item
.ident
.name
;
2519 debug
!("(resolving item) resolving {} ({:?})", name
, item
.node
);
2522 ItemKind
::Ty(_
, ref generics
) |
2523 ItemKind
::Existential(_
, ref generics
) |
2524 ItemKind
::Fn(_
, _
, ref generics
, _
) => {
2525 self.with_generic_param_rib(
2526 HasGenericParams(generics
, ItemRibKind
),
2527 |this
| visit
::walk_item(this
, item
)
2531 ItemKind
::Enum(_
, ref generics
) |
2532 ItemKind
::Struct(_
, ref generics
) |
2533 ItemKind
::Union(_
, ref generics
) => {
2534 self.resolve_adt(item
, generics
);
2537 ItemKind
::Impl(.., ref generics
, ref opt_trait_ref
, ref self_type
, ref impl_items
) =>
2538 self.resolve_implementation(generics
,
2544 ItemKind
::Trait(.., ref generics
, ref bounds
, ref trait_items
) => {
2545 // Create a new rib for the trait-wide type parameters.
2546 self.with_generic_param_rib(HasGenericParams(generics
, ItemRibKind
), |this
| {
2547 let local_def_id
= this
.definitions
.local_def_id(item
.id
);
2548 this
.with_self_rib(Res
::SelfTy(Some(local_def_id
), None
), |this
| {
2549 this
.visit_generics(generics
);
2550 walk_list
!(this
, visit_param_bound
, bounds
);
2552 for trait_item
in trait_items
{
2553 let generic_params
= HasGenericParams(&trait_item
.generics
,
2555 this
.with_generic_param_rib(generic_params
, |this
| {
2556 match trait_item
.node
{
2557 TraitItemKind
::Const(ref ty
, ref default) => {
2560 // Only impose the restrictions of
2561 // ConstRibKind for an actual constant
2562 // expression in a provided default.
2563 if let Some(ref expr
) = *default{
2564 this
.with_constant_rib(|this
| {
2565 this
.visit_expr(expr
);
2569 TraitItemKind
::Method(_
, _
) => {
2570 visit
::walk_trait_item(this
, trait_item
)
2572 TraitItemKind
::Type(..) => {
2573 visit
::walk_trait_item(this
, trait_item
)
2575 TraitItemKind
::Macro(_
) => {
2576 panic
!("unexpanded macro in resolve!")
2585 ItemKind
::TraitAlias(ref generics
, ref bounds
) => {
2586 // Create a new rib for the trait-wide type parameters.
2587 self.with_generic_param_rib(HasGenericParams(generics
, ItemRibKind
), |this
| {
2588 let local_def_id
= this
.definitions
.local_def_id(item
.id
);
2589 this
.with_self_rib(Res
::SelfTy(Some(local_def_id
), None
), |this
| {
2590 this
.visit_generics(generics
);
2591 walk_list
!(this
, visit_param_bound
, bounds
);
2596 ItemKind
::Mod(_
) | ItemKind
::ForeignMod(_
) => {
2597 self.with_scope(item
.id
, |this
| {
2598 visit
::walk_item(this
, item
);
2602 ItemKind
::Static(ref ty
, _
, ref expr
) |
2603 ItemKind
::Const(ref ty
, ref expr
) => {
2604 debug
!("resolve_item ItemKind::Const");
2605 self.with_item_rib(|this
| {
2607 this
.with_constant_rib(|this
| {
2608 this
.visit_expr(expr
);
2613 ItemKind
::Use(ref use_tree
) => {
2614 self.future_proof_import(use_tree
);
2617 ItemKind
::ExternCrate(..) |
2618 ItemKind
::MacroDef(..) | ItemKind
::GlobalAsm(..) => {
2619 // do nothing, these are just around to be encoded
2622 ItemKind
::Mac(_
) => panic
!("unexpanded macro in resolve!"),
2626 fn with_generic_param_rib
<'b
, F
>(&'b
mut self, generic_params
: GenericParameters
<'a
, 'b
>, f
: F
)
2627 where F
: FnOnce(&mut Resolver
<'_
>)
2629 debug
!("with_generic_param_rib");
2630 match generic_params
{
2631 HasGenericParams(generics
, rib_kind
) => {
2632 let mut function_type_rib
= Rib
::new(rib_kind
);
2633 let mut function_value_rib
= Rib
::new(rib_kind
);
2634 let mut seen_bindings
= FxHashMap
::default();
2635 for param
in &generics
.params
{
2637 GenericParamKind
::Lifetime { .. }
=> {}
2638 GenericParamKind
::Type { .. }
=> {
2639 let ident
= param
.ident
.modern();
2640 debug
!("with_generic_param_rib: {}", param
.id
);
2642 if seen_bindings
.contains_key(&ident
) {
2643 let span
= seen_bindings
.get(&ident
).unwrap();
2644 let err
= ResolutionError
::NameAlreadyUsedInParameterList(
2648 resolve_error(self, param
.ident
.span
, err
);
2650 seen_bindings
.entry(ident
).or_insert(param
.ident
.span
);
2652 // Plain insert (no renaming).
2655 self.definitions
.local_def_id(param
.id
),
2657 function_type_rib
.bindings
.insert(ident
, res
);
2658 self.record_partial_res(param
.id
, PartialRes
::new(res
));
2660 GenericParamKind
::Const { .. }
=> {
2661 let ident
= param
.ident
.modern();
2662 debug
!("with_generic_param_rib: {}", param
.id
);
2664 if seen_bindings
.contains_key(&ident
) {
2665 let span
= seen_bindings
.get(&ident
).unwrap();
2666 let err
= ResolutionError
::NameAlreadyUsedInParameterList(
2670 resolve_error(self, param
.ident
.span
, err
);
2672 seen_bindings
.entry(ident
).or_insert(param
.ident
.span
);
2675 DefKind
::ConstParam
,
2676 self.definitions
.local_def_id(param
.id
),
2678 function_value_rib
.bindings
.insert(ident
, res
);
2679 self.record_partial_res(param
.id
, PartialRes
::new(res
));
2683 self.ribs
[ValueNS
].push(function_value_rib
);
2684 self.ribs
[TypeNS
].push(function_type_rib
);
2687 NoGenericParams
=> {
2694 if let HasGenericParams(..) = generic_params
{
2695 self.ribs
[TypeNS
].pop();
2696 self.ribs
[ValueNS
].pop();
2700 fn with_label_rib
<F
>(&mut self, f
: F
)
2701 where F
: FnOnce(&mut Resolver
<'_
>)
2703 self.label_ribs
.push(Rib
::new(NormalRibKind
));
2705 self.label_ribs
.pop();
2708 fn with_item_rib
<F
>(&mut self, f
: F
)
2709 where F
: FnOnce(&mut Resolver
<'_
>)
2711 self.ribs
[ValueNS
].push(Rib
::new(ItemRibKind
));
2712 self.ribs
[TypeNS
].push(Rib
::new(ItemRibKind
));
2714 self.ribs
[TypeNS
].pop();
2715 self.ribs
[ValueNS
].pop();
2718 fn with_constant_rib
<F
>(&mut self, f
: F
)
2719 where F
: FnOnce(&mut Resolver
<'_
>)
2721 debug
!("with_constant_rib");
2722 self.ribs
[ValueNS
].push(Rib
::new(ConstantItemRibKind
));
2723 self.label_ribs
.push(Rib
::new(ConstantItemRibKind
));
2725 self.label_ribs
.pop();
2726 self.ribs
[ValueNS
].pop();
2729 fn with_current_self_type
<T
, F
>(&mut self, self_type
: &Ty
, f
: F
) -> T
2730 where F
: FnOnce(&mut Resolver
<'_
>) -> T
2732 // Handle nested impls (inside fn bodies)
2733 let previous_value
= replace(&mut self.current_self_type
, Some(self_type
.clone()));
2734 let result
= f(self);
2735 self.current_self_type
= previous_value
;
2739 fn with_current_self_item
<T
, F
>(&mut self, self_item
: &Item
, f
: F
) -> T
2740 where F
: FnOnce(&mut Resolver
<'_
>) -> T
2742 let previous_value
= replace(&mut self.current_self_item
, Some(self_item
.id
));
2743 let result
= f(self);
2744 self.current_self_item
= previous_value
;
2748 /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
2749 fn with_optional_trait_ref
<T
, F
>(&mut self, opt_trait_ref
: Option
<&TraitRef
>, f
: F
) -> T
2750 where F
: FnOnce(&mut Resolver
<'_
>, Option
<DefId
>) -> T
2752 let mut new_val
= None
;
2753 let mut new_id
= None
;
2754 if let Some(trait_ref
) = opt_trait_ref
{
2755 let path
: Vec
<_
> = Segment
::from_path(&trait_ref
.path
);
2756 let res
= self.smart_resolve_path_fragment(
2760 trait_ref
.path
.span
,
2761 PathSource
::Trait(AliasPossibility
::No
),
2762 CrateLint
::SimplePath(trait_ref
.ref_id
),
2764 if res
!= Res
::Err
{
2765 new_id
= Some(res
.def_id());
2766 let span
= trait_ref
.path
.span
;
2767 if let PathResult
::Module(ModuleOrUniformRoot
::Module(module
)) =
2768 self.resolve_path_without_parent_scope(
2773 CrateLint
::SimplePath(trait_ref
.ref_id
),
2776 new_val
= Some((module
, trait_ref
.clone()));
2780 let original_trait_ref
= replace(&mut self.current_trait_ref
, new_val
);
2781 let result
= f(self, new_id
);
2782 self.current_trait_ref
= original_trait_ref
;
2786 fn with_self_rib
<F
>(&mut self, self_res
: Res
, f
: F
)
2787 where F
: FnOnce(&mut Resolver
<'_
>)
2789 let mut self_type_rib
= Rib
::new(NormalRibKind
);
2791 // Plain insert (no renaming, since types are not currently hygienic)
2792 self_type_rib
.bindings
.insert(Ident
::with_empty_ctxt(kw
::SelfUpper
), self_res
);
2793 self.ribs
[TypeNS
].push(self_type_rib
);
2795 self.ribs
[TypeNS
].pop();
2798 fn with_self_struct_ctor_rib
<F
>(&mut self, impl_id
: DefId
, f
: F
)
2799 where F
: FnOnce(&mut Resolver
<'_
>)
2801 let self_res
= Res
::SelfCtor(impl_id
);
2802 let mut self_type_rib
= Rib
::new(NormalRibKind
);
2803 self_type_rib
.bindings
.insert(Ident
::with_empty_ctxt(kw
::SelfUpper
), self_res
);
2804 self.ribs
[ValueNS
].push(self_type_rib
);
2806 self.ribs
[ValueNS
].pop();
2809 fn resolve_implementation(&mut self,
2810 generics
: &Generics
,
2811 opt_trait_reference
: &Option
<TraitRef
>,
2814 impl_items
: &[ImplItem
]) {
2815 debug
!("resolve_implementation");
2816 // If applicable, create a rib for the type parameters.
2817 self.with_generic_param_rib(HasGenericParams(generics
, ItemRibKind
), |this
| {
2818 // Dummy self type for better errors if `Self` is used in the trait path.
2819 this
.with_self_rib(Res
::SelfTy(None
, None
), |this
| {
2820 // Resolve the trait reference, if necessary.
2821 this
.with_optional_trait_ref(opt_trait_reference
.as_ref(), |this
, trait_id
| {
2822 let item_def_id
= this
.definitions
.local_def_id(item_id
);
2823 this
.with_self_rib(Res
::SelfTy(trait_id
, Some(item_def_id
)), |this
| {
2824 if let Some(trait_ref
) = opt_trait_reference
.as_ref() {
2825 // Resolve type arguments in the trait path.
2826 visit
::walk_trait_ref(this
, trait_ref
);
2828 // Resolve the self type.
2829 this
.visit_ty(self_type
);
2830 // Resolve the generic parameters.
2831 this
.visit_generics(generics
);
2832 // Resolve the items within the impl.
2833 this
.with_current_self_type(self_type
, |this
| {
2834 this
.with_self_struct_ctor_rib(item_def_id
, |this
| {
2835 debug
!("resolve_implementation with_self_struct_ctor_rib");
2836 for impl_item
in impl_items
{
2837 this
.resolve_visibility(&impl_item
.vis
);
2839 // We also need a new scope for the impl item type parameters.
2840 let generic_params
= HasGenericParams(&impl_item
.generics
,
2842 this
.with_generic_param_rib(generic_params
, |this
| {
2843 use self::ResolutionError
::*;
2844 match impl_item
.node
{
2845 ImplItemKind
::Const(..) => {
2847 "resolve_implementation ImplItemKind::Const",
2849 // If this is a trait impl, ensure the const
2851 this
.check_trait_item(
2855 |n
, s
| ConstNotMemberOfTrait(n
, s
),
2858 this
.with_constant_rib(|this
| {
2859 visit
::walk_impl_item(this
, impl_item
)
2862 ImplItemKind
::Method(..) => {
2863 // If this is a trait impl, ensure the method
2865 this
.check_trait_item(impl_item
.ident
,
2868 |n
, s
| MethodNotMemberOfTrait(n
, s
));
2870 visit
::walk_impl_item(this
, impl_item
);
2872 ImplItemKind
::Type(ref ty
) => {
2873 // If this is a trait impl, ensure the type
2875 this
.check_trait_item(impl_item
.ident
,
2878 |n
, s
| TypeNotMemberOfTrait(n
, s
));
2882 ImplItemKind
::Existential(ref bounds
) => {
2883 // If this is a trait impl, ensure the type
2885 this
.check_trait_item(impl_item
.ident
,
2888 |n
, s
| TypeNotMemberOfTrait(n
, s
));
2890 for bound
in bounds
{
2891 this
.visit_param_bound(bound
);
2894 ImplItemKind
::Macro(_
) =>
2895 panic
!("unexpanded macro in resolve!"),
2907 fn check_trait_item
<F
>(&mut self, ident
: Ident
, ns
: Namespace
, span
: Span
, err
: F
)
2908 where F
: FnOnce(Name
, &str) -> ResolutionError
<'_
>
2910 // If there is a TraitRef in scope for an impl, then the method must be in the
2912 if let Some((module
, _
)) = self.current_trait_ref
{
2913 if self.resolve_ident_in_module(
2914 ModuleOrUniformRoot
::Module(module
),
2921 let path
= &self.current_trait_ref
.as_ref().unwrap().1.path
;
2922 resolve_error(self, span
, err(ident
.name
, &path_names_to_string(path
)));
2927 fn resolve_local(&mut self, local
: &Local
) {
2928 // Resolve the type.
2929 walk_list
!(self, visit_ty
, &local
.ty
);
2931 // Resolve the initializer.
2932 walk_list
!(self, visit_expr
, &local
.init
);
2934 // Resolve the pattern.
2935 self.resolve_pattern(&local
.pat
, PatternSource
::Let
, &mut FxHashMap
::default());
2938 // build a map from pattern identifiers to binding-info's.
2939 // this is done hygienically. This could arise for a macro
2940 // that expands into an or-pattern where one 'x' was from the
2941 // user and one 'x' came from the macro.
2942 fn binding_mode_map(&mut self, pat
: &Pat
) -> BindingMap
{
2943 let mut binding_map
= FxHashMap
::default();
2945 pat
.walk(&mut |pat
| {
2946 if let PatKind
::Ident(binding_mode
, ident
, ref sub_pat
) = pat
.node
{
2947 if sub_pat
.is_some() || match self.partial_res_map
.get(&pat
.id
)
2948 .map(|res
| res
.base_res()) {
2949 Some(Res
::Local(..)) => true,
2952 let binding_info
= BindingInfo { span: ident.span, binding_mode: binding_mode }
;
2953 binding_map
.insert(ident
, binding_info
);
2962 // Checks that all of the arms in an or-pattern have exactly the
2963 // same set of bindings, with the same binding modes for each.
2964 fn check_consistent_bindings(&mut self, pats
: &[P
<Pat
>]) {
2965 if pats
.is_empty() {
2969 let mut missing_vars
= FxHashMap
::default();
2970 let mut inconsistent_vars
= FxHashMap
::default();
2971 for (i
, p
) in pats
.iter().enumerate() {
2972 let map_i
= self.binding_mode_map(&p
);
2974 for (j
, q
) in pats
.iter().enumerate() {
2979 let map_j
= self.binding_mode_map(&q
);
2980 for (&key
, &binding_i
) in &map_i
{
2981 if map_j
.is_empty() { // Account for missing bindings when
2982 let binding_error
= missing_vars
// `map_j` has none.
2984 .or_insert(BindingError
{
2986 origin
: BTreeSet
::new(),
2987 target
: BTreeSet
::new(),
2989 binding_error
.origin
.insert(binding_i
.span
);
2990 binding_error
.target
.insert(q
.span
);
2992 for (&key_j
, &binding_j
) in &map_j
{
2993 match map_i
.get(&key_j
) {
2994 None
=> { // missing binding
2995 let binding_error
= missing_vars
2997 .or_insert(BindingError
{
2999 origin
: BTreeSet
::new(),
3000 target
: BTreeSet
::new(),
3002 binding_error
.origin
.insert(binding_j
.span
);
3003 binding_error
.target
.insert(p
.span
);
3005 Some(binding_i
) => { // check consistent binding
3006 if binding_i
.binding_mode
!= binding_j
.binding_mode
{
3009 .or_insert((binding_j
.span
, binding_i
.span
));
3017 let mut missing_vars
= missing_vars
.iter().collect
::<Vec
<_
>>();
3018 missing_vars
.sort();
3019 for (_
, v
) in missing_vars
{
3021 *v
.origin
.iter().next().unwrap(),
3022 ResolutionError
::VariableNotBoundInPattern(v
));
3024 let mut inconsistent_vars
= inconsistent_vars
.iter().collect
::<Vec
<_
>>();
3025 inconsistent_vars
.sort();
3026 for (name
, v
) in inconsistent_vars
{
3027 resolve_error(self, v
.0, ResolutionError
::VariableBoundWithDifferentMode(*name
, v
.1));
3031 fn resolve_arm(&mut self, arm
: &Arm
) {
3032 self.ribs
[ValueNS
].push(Rib
::new(NormalRibKind
));
3034 self.resolve_pats(&arm
.pats
, PatternSource
::Match
);
3036 if let Some(ref expr
) = arm
.guard
{
3037 self.visit_expr(expr
)
3039 self.visit_expr(&arm
.body
);
3041 self.ribs
[ValueNS
].pop();
3044 /// Arising from `source`, resolve a sequence of patterns (top level or-patterns).
3045 fn resolve_pats(&mut self, pats
: &[P
<Pat
>], source
: PatternSource
) {
3046 let mut bindings_list
= FxHashMap
::default();
3048 self.resolve_pattern(pat
, source
, &mut bindings_list
);
3050 // This has to happen *after* we determine which pat_idents are variants
3051 self.check_consistent_bindings(pats
);
3054 fn resolve_block(&mut self, block
: &Block
) {
3055 debug
!("(resolving block) entering block");
3056 // Move down in the graph, if there's an anonymous module rooted here.
3057 let orig_module
= self.current_module
;
3058 let anonymous_module
= self.block_map
.get(&block
.id
).cloned(); // clones a reference
3060 let mut num_macro_definition_ribs
= 0;
3061 if let Some(anonymous_module
) = anonymous_module
{
3062 debug
!("(resolving block) found anonymous module, moving down");
3063 self.ribs
[ValueNS
].push(Rib
::new(ModuleRibKind(anonymous_module
)));
3064 self.ribs
[TypeNS
].push(Rib
::new(ModuleRibKind(anonymous_module
)));
3065 self.current_module
= anonymous_module
;
3066 self.finalize_current_module_macro_resolutions();
3068 self.ribs
[ValueNS
].push(Rib
::new(NormalRibKind
));
3071 // Descend into the block.
3072 for stmt
in &block
.stmts
{
3073 if let ast
::StmtKind
::Item(ref item
) = stmt
.node
{
3074 if let ast
::ItemKind
::MacroDef(..) = item
.node
{
3075 num_macro_definition_ribs
+= 1;
3076 let res
= self.definitions
.local_def_id(item
.id
);
3077 self.ribs
[ValueNS
].push(Rib
::new(MacroDefinition(res
)));
3078 self.label_ribs
.push(Rib
::new(MacroDefinition(res
)));
3082 self.visit_stmt(stmt
);
3086 self.current_module
= orig_module
;
3087 for _
in 0 .. num_macro_definition_ribs
{
3088 self.ribs
[ValueNS
].pop();
3089 self.label_ribs
.pop();
3091 self.ribs
[ValueNS
].pop();
3092 if anonymous_module
.is_some() {
3093 self.ribs
[TypeNS
].pop();
3095 debug
!("(resolving block) leaving block");
3098 fn fresh_binding(&mut self,
3101 outer_pat_id
: NodeId
,
3102 pat_src
: PatternSource
,
3103 bindings
: &mut FxHashMap
<Ident
, NodeId
>)
3105 // Add the binding to the local ribs, if it
3106 // doesn't already exist in the bindings map. (We
3107 // must not add it if it's in the bindings map
3108 // because that breaks the assumptions later
3109 // passes make about or-patterns.)
3110 let ident
= ident
.modern_and_legacy();
3111 let mut res
= Res
::Local(pat_id
);
3112 match bindings
.get(&ident
).cloned() {
3113 Some(id
) if id
== outer_pat_id
=> {
3114 // `Variant(a, a)`, error
3118 ResolutionError
::IdentifierBoundMoreThanOnceInSamePattern(
3122 Some(..) if pat_src
== PatternSource
::FnParam
=> {
3123 // `fn f(a: u8, a: u8)`, error
3127 ResolutionError
::IdentifierBoundMoreThanOnceInParameterList(
3131 Some(..) if pat_src
== PatternSource
::Match
||
3132 pat_src
== PatternSource
::Let
=> {
3133 // `Variant1(a) | Variant2(a)`, ok
3134 // Reuse definition from the first `a`.
3135 res
= self.ribs
[ValueNS
].last_mut().unwrap().bindings
[&ident
];
3138 span_bug
!(ident
.span
, "two bindings with the same name from \
3139 unexpected pattern source {:?}", pat_src
);
3142 // A completely fresh binding, add to the lists if it's valid.
3143 if ident
.name
!= kw
::Invalid
{
3144 bindings
.insert(ident
, outer_pat_id
);
3145 self.ribs
[ValueNS
].last_mut().unwrap().bindings
.insert(ident
, res
);
3153 fn resolve_pattern(&mut self,
3155 pat_src
: PatternSource
,
3156 // Maps idents to the node ID for the
3157 // outermost pattern that binds them.
3158 bindings
: &mut FxHashMap
<Ident
, NodeId
>) {
3159 // Visit all direct subpatterns of this pattern.
3160 let outer_pat_id
= pat
.id
;
3161 pat
.walk(&mut |pat
| {
3162 debug
!("resolve_pattern pat={:?} node={:?}", pat
, pat
.node
);
3164 PatKind
::Ident(bmode
, ident
, ref opt_pat
) => {
3165 // First try to resolve the identifier as some existing
3166 // entity, then fall back to a fresh binding.
3167 let binding
= self.resolve_ident_in_lexical_scope(ident
, ValueNS
,
3169 .and_then(LexicalScopeBinding
::item
);
3170 let res
= binding
.map(NameBinding
::res
).and_then(|res
| {
3171 let is_syntactic_ambiguity
= opt_pat
.is_none() &&
3172 bmode
== BindingMode
::ByValue(Mutability
::Immutable
);
3174 Res
::Def(DefKind
::Ctor(_
, CtorKind
::Const
), _
) |
3175 Res
::Def(DefKind
::Const
, _
) if is_syntactic_ambiguity
=> {
3176 // Disambiguate in favor of a unit struct/variant
3177 // or constant pattern.
3178 self.record_use(ident
, ValueNS
, binding
.unwrap(), false);
3181 Res
::Def(DefKind
::Ctor(..), _
)
3182 | Res
::Def(DefKind
::Const
, _
)
3183 | Res
::Def(DefKind
::Static
, _
) => {
3184 // This is unambiguously a fresh binding, either syntactically
3185 // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
3186 // to something unusable as a pattern (e.g., constructor function),
3187 // but we still conservatively report an error, see
3188 // issues/33118#issuecomment-233962221 for one reason why.
3192 ResolutionError
::BindingShadowsSomethingUnacceptable(
3193 pat_src
.descr(), ident
.name
, binding
.unwrap())
3197 Res
::Def(DefKind
::Fn
, _
) | Res
::Err
=> {
3198 // These entities are explicitly allowed
3199 // to be shadowed by fresh bindings.
3203 span_bug
!(ident
.span
, "unexpected resolution for an \
3204 identifier in pattern: {:?}", res
);
3207 }).unwrap_or_else(|| {
3208 self.fresh_binding(ident
, pat
.id
, outer_pat_id
, pat_src
, bindings
)
3211 self.record_partial_res(pat
.id
, PartialRes
::new(res
));
3214 PatKind
::TupleStruct(ref path
, ..) => {
3215 self.smart_resolve_path(pat
.id
, None
, path
, PathSource
::TupleStruct
);
3218 PatKind
::Path(ref qself
, ref path
) => {
3219 self.smart_resolve_path(pat
.id
, qself
.as_ref(), path
, PathSource
::Pat
);
3222 PatKind
::Struct(ref path
, ..) => {
3223 self.smart_resolve_path(pat
.id
, None
, path
, PathSource
::Struct
);
3231 visit
::walk_pat(self, pat
);
3234 // High-level and context dependent path resolution routine.
3235 // Resolves the path and records the resolution into definition map.
3236 // If resolution fails tries several techniques to find likely
3237 // resolution candidates, suggest imports or other help, and report
3238 // errors in user friendly way.
3239 fn smart_resolve_path(&mut self,
3241 qself
: Option
<&QSelf
>,
3243 source
: PathSource
<'_
>) {
3244 self.smart_resolve_path_fragment(
3247 &Segment
::from_path(path
),
3250 CrateLint
::SimplePath(id
),
3254 fn smart_resolve_path_fragment(&mut self,
3256 qself
: Option
<&QSelf
>,
3259 source
: PathSource
<'_
>,
3260 crate_lint
: CrateLint
)
3262 let ns
= source
.namespace();
3263 let is_expected
= &|res
| source
.is_expected(res
);
3265 let report_errors
= |this
: &mut Self, res
: Option
<Res
>| {
3266 let (err
, candidates
) = this
.smart_resolve_report_errors(path
, span
, source
, res
);
3267 let def_id
= this
.current_module
.normal_ancestor_id
;
3268 let node_id
= this
.definitions
.as_local_node_id(def_id
).unwrap();
3269 let better
= res
.is_some();
3270 this
.use_injections
.push(UseError { err, candidates, node_id, better }
);
3271 PartialRes
::new(Res
::Err
)
3274 let partial_res
= match self.resolve_qpath_anywhere(
3280 source
.defer_to_typeck(),
3281 source
.global_by_default(),
3284 Some(partial_res
) if partial_res
.unresolved_segments() == 0 => {
3285 if is_expected(partial_res
.base_res()) || partial_res
.base_res() == Res
::Err
{
3288 // Add a temporary hack to smooth the transition to new struct ctor
3289 // visibility rules. See #38932 for more details.
3291 if let Res
::Def(DefKind
::Struct
, def_id
) = partial_res
.base_res() {
3292 if let Some((ctor_res
, ctor_vis
))
3293 = self.struct_constructors
.get(&def_id
).cloned() {
3294 if is_expected(ctor_res
) && self.is_accessible(ctor_vis
) {
3295 let lint
= lint
::builtin
::LEGACY_CONSTRUCTOR_VISIBILITY
;
3296 self.session
.buffer_lint(lint
, id
, span
,
3297 "private struct constructors are not usable through \
3298 re-exports in outer modules",
3300 res
= Some(PartialRes
::new(ctor_res
));
3305 res
.unwrap_or_else(|| report_errors(self, Some(partial_res
.base_res())))
3308 Some(partial_res
) if source
.defer_to_typeck() => {
3309 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
3310 // or `<T>::A::B`. If `B` should be resolved in value namespace then
3311 // it needs to be added to the trait map.
3313 let item_name
= path
.last().unwrap().ident
;
3314 let traits
= self.get_traits_containing_item(item_name
, ns
);
3315 self.trait_map
.insert(id
, traits
);
3318 let mut std_path
= vec
![Segment
::from_ident(Ident
::with_empty_ctxt(sym
::std
))];
3319 std_path
.extend(path
);
3320 if self.primitive_type_table
.primitive_types
.contains_key(&path
[0].ident
.name
) {
3321 let cl
= CrateLint
::No
;
3323 if let PathResult
::Module(_
) | PathResult
::NonModule(_
) =
3324 self.resolve_path_without_parent_scope(&std_path
, ns
, false, span
, cl
)
3326 // check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
3327 let item_span
= path
.iter().last().map(|segment
| segment
.ident
.span
)
3329 debug
!("accessed item from `std` submodule as a bare type {:?}", std_path
);
3330 let mut hm
= self.session
.confused_type_with_std_module
.borrow_mut();
3331 hm
.insert(item_span
, span
);
3332 // In some places (E0223) we only have access to the full path
3333 hm
.insert(span
, span
);
3338 _
=> report_errors(self, None
)
3341 if let PathSource
::TraitItem(..) = source {}
else {
3342 // Avoid recording definition of `A::B` in `<T as A>::B::C`.
3343 self.record_partial_res(id
, partial_res
);
3348 /// Only used in a specific case of type ascription suggestions
3350 fn get_colon_suggestion_span(&self, start
: Span
) -> Span
{
3351 let cm
= self.session
.source_map();
3352 start
.to(cm
.next_point(start
))
3355 fn type_ascription_suggestion(
3357 err
: &mut DiagnosticBuilder
<'_
>,
3360 debug
!("type_ascription_suggetion {:?}", base_span
);
3361 let cm
= self.session
.source_map();
3362 let base_snippet
= cm
.span_to_snippet(base_span
);
3363 debug
!("self.current_type_ascription {:?}", self.current_type_ascription
);
3364 if let Some(sp
) = self.current_type_ascription
.last() {
3367 // Try to find the `:`; bail on first non-':' / non-whitespace.
3368 sp
= cm
.next_point(sp
);
3369 if let Ok(snippet
) = cm
.span_to_snippet(sp
.to(cm
.next_point(sp
))) {
3370 let line_sp
= cm
.lookup_char_pos(sp
.hi()).line
;
3371 let line_base_sp
= cm
.lookup_char_pos(base_span
.lo()).line
;
3373 let mut show_label
= true;
3374 if line_sp
!= line_base_sp
{
3375 err
.span_suggestion_short(
3377 "did you mean to use `;` here instead?",
3379 Applicability
::MaybeIncorrect
,
3382 let colon_sp
= self.get_colon_suggestion_span(sp
);
3383 let after_colon_sp
= self.get_colon_suggestion_span(
3384 colon_sp
.shrink_to_hi(),
3386 if !cm
.span_to_snippet(after_colon_sp
).map(|s
| s
== " ")
3389 err
.span_suggestion(
3391 "maybe you meant to write a path separator here",
3393 Applicability
::MaybeIncorrect
,
3397 if let Ok(base_snippet
) = base_snippet
{
3398 let mut sp
= after_colon_sp
;
3400 // Try to find an assignment
3401 sp
= cm
.next_point(sp
);
3402 let snippet
= cm
.span_to_snippet(sp
.to(cm
.next_point(sp
)));
3404 Ok(ref x
) if x
.as_str() == "=" => {
3405 err
.span_suggestion(
3407 "maybe you meant to write an assignment here",
3408 format
!("let {}", base_snippet
),
3409 Applicability
::MaybeIncorrect
,
3414 Ok(ref x
) if x
.as_str() == "\n" => break,
3422 err
.span_label(base_span
,
3423 "expecting a type here because of type ascription");
3426 } else if !snippet
.trim().is_empty() {
3427 debug
!("tried to find type ascription `:` token, couldn't find it");
3437 fn self_type_is_available(&mut self, span
: Span
) -> bool
{
3438 let binding
= self.resolve_ident_in_lexical_scope(Ident
::with_empty_ctxt(kw
::SelfUpper
),
3439 TypeNS
, None
, span
);
3440 if let Some(LexicalScopeBinding
::Res(res
)) = binding { res != Res::Err }
else { false }
3443 fn self_value_is_available(&mut self, self_span
: Span
, path_span
: Span
) -> bool
{
3444 let ident
= Ident
::new(kw
::SelfLower
, self_span
);
3445 let binding
= self.resolve_ident_in_lexical_scope(ident
, ValueNS
, None
, path_span
);
3446 if let Some(LexicalScopeBinding
::Res(res
)) = binding { res != Res::Err }
else { false }
3449 // Resolve in alternative namespaces if resolution in the primary namespace fails.
3450 fn resolve_qpath_anywhere(
3453 qself
: Option
<&QSelf
>,
3455 primary_ns
: Namespace
,
3457 defer_to_typeck
: bool
,
3458 global_by_default
: bool
,
3459 crate_lint
: CrateLint
,
3460 ) -> Option
<PartialRes
> {
3461 let mut fin_res
= None
;
3462 // FIXME: can't resolve paths in macro namespace yet, macros are
3463 // processed by the little special hack below.
3464 for (i
, ns
) in [primary_ns
, TypeNS
, ValueNS
, /*MacroNS*/].iter().cloned().enumerate() {
3465 if i
== 0 || ns
!= primary_ns
{
3466 match self.resolve_qpath(id
, qself
, path
, ns
, span
, global_by_default
, crate_lint
) {
3467 // If defer_to_typeck, then resolution > no resolution,
3468 // otherwise full resolution > partial resolution > no resolution.
3469 Some(partial_res
) if partial_res
.unresolved_segments() == 0 ||
3471 return Some(partial_res
),
3472 partial_res
=> if fin_res
.is_none() { fin_res = partial_res }
,
3476 if primary_ns
!= MacroNS
&&
3477 (self.macro_names
.contains(&path
[0].ident
.modern()) ||
3478 self.builtin_macros
.get(&path
[0].ident
.name
).cloned()
3479 .and_then(NameBinding
::macro_kind
) == Some(MacroKind
::Bang
) ||
3480 self.macro_use_prelude
.get(&path
[0].ident
.name
).cloned()
3481 .and_then(NameBinding
::macro_kind
) == Some(MacroKind
::Bang
)) {
3482 // Return some dummy definition, it's enough for error reporting.
3483 return Some(PartialRes
::new(Res
::Def(
3484 DefKind
::Macro(MacroKind
::Bang
),
3485 DefId
::local(CRATE_DEF_INDEX
),
3491 /// Handles paths that may refer to associated items.
3495 qself
: Option
<&QSelf
>,
3499 global_by_default
: bool
,
3500 crate_lint
: CrateLint
,
3501 ) -> Option
<PartialRes
> {
3503 "resolve_qpath(id={:?}, qself={:?}, path={:?}, \
3504 ns={:?}, span={:?}, global_by_default={:?})",
3513 if let Some(qself
) = qself
{
3514 if qself
.position
== 0 {
3515 // This is a case like `<T>::B`, where there is no
3516 // trait to resolve. In that case, we leave the `B`
3517 // segment to be resolved by type-check.
3518 return Some(PartialRes
::with_unresolved_segments(
3519 Res
::Def(DefKind
::Mod
, DefId
::local(CRATE_DEF_INDEX
)), path
.len()
3523 // Make sure `A::B` in `<T as A::B>::C` is a trait item.
3525 // Currently, `path` names the full item (`A::B::C`, in
3526 // our example). so we extract the prefix of that that is
3527 // the trait (the slice upto and including
3528 // `qself.position`). And then we recursively resolve that,
3529 // but with `qself` set to `None`.
3531 // However, setting `qself` to none (but not changing the
3532 // span) loses the information about where this path
3533 // *actually* appears, so for the purposes of the crate
3534 // lint we pass along information that this is the trait
3535 // name from a fully qualified path, and this also
3536 // contains the full span (the `CrateLint::QPathTrait`).
3537 let ns
= if qself
.position
+ 1 == path
.len() { ns }
else { TypeNS }
;
3538 let partial_res
= self.smart_resolve_path_fragment(
3541 &path
[..=qself
.position
],
3543 PathSource
::TraitItem(ns
),
3544 CrateLint
::QPathTrait
{
3546 qpath_span
: qself
.path_span
,
3550 // The remaining segments (the `C` in our example) will
3551 // have to be resolved by type-check, since that requires doing
3552 // trait resolution.
3553 return Some(PartialRes
::with_unresolved_segments(
3554 partial_res
.base_res(),
3555 partial_res
.unresolved_segments() + path
.len() - qself
.position
- 1,
3559 let result
= match self.resolve_path_without_parent_scope(
3566 PathResult
::NonModule(path_res
) => path_res
,
3567 PathResult
::Module(ModuleOrUniformRoot
::Module(module
)) if !module
.is_normal() => {
3568 PartialRes
::new(module
.res().unwrap())
3570 // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
3571 // don't report an error right away, but try to fallback to a primitive type.
3572 // So, we are still able to successfully resolve something like
3574 // use std::u8; // bring module u8 in scope
3575 // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
3576 // u8::max_value() // OK, resolves to associated function <u8>::max_value,
3577 // // not to non-existent std::u8::max_value
3580 // Such behavior is required for backward compatibility.
3581 // The same fallback is used when `a` resolves to nothing.
3582 PathResult
::Module(ModuleOrUniformRoot
::Module(_
)) |
3583 PathResult
::Failed { .. }
3584 if (ns
== TypeNS
|| path
.len() > 1) &&
3585 self.primitive_type_table
.primitive_types
3586 .contains_key(&path
[0].ident
.name
) => {
3587 let prim
= self.primitive_type_table
.primitive_types
[&path
[0].ident
.name
];
3588 PartialRes
::with_unresolved_segments(Res
::PrimTy(prim
), path
.len() - 1)
3590 PathResult
::Module(ModuleOrUniformRoot
::Module(module
)) =>
3591 PartialRes
::new(module
.res().unwrap()),
3592 PathResult
::Failed { is_error_from_last_segment: false, span, label, suggestion }
=> {
3593 resolve_error(self, span
, ResolutionError
::FailedToResolve { label, suggestion }
);
3594 PartialRes
::new(Res
::Err
)
3596 PathResult
::Module(..) | PathResult
::Failed { .. }
=> return None
,
3597 PathResult
::Indeterminate
=> bug
!("indetermined path result in resolve_qpath"),
3600 if path
.len() > 1 && !global_by_default
&& result
.base_res() != Res
::Err
&&
3601 path
[0].ident
.name
!= kw
::PathRoot
&&
3602 path
[0].ident
.name
!= kw
::DollarCrate
{
3603 let unqualified_result
= {
3604 match self.resolve_path_without_parent_scope(
3605 &[*path
.last().unwrap()],
3611 PathResult
::NonModule(path_res
) => path_res
.base_res(),
3612 PathResult
::Module(ModuleOrUniformRoot
::Module(module
)) =>
3613 module
.res().unwrap(),
3614 _
=> return Some(result
),
3617 if result
.base_res() == unqualified_result
{
3618 let lint
= lint
::builtin
::UNUSED_QUALIFICATIONS
;
3619 self.session
.buffer_lint(lint
, id
, span
, "unnecessary qualification")
3626 fn resolve_path_without_parent_scope(
3629 opt_ns
: Option
<Namespace
>, // `None` indicates a module path in import
3632 crate_lint
: CrateLint
,
3633 ) -> PathResult
<'a
> {
3634 // Macro and import paths must have full parent scope available during resolution,
3635 // other paths will do okay with parent module alone.
3636 assert
!(opt_ns
!= None
&& opt_ns
!= Some(MacroNS
));
3637 let parent_scope
= ParentScope { module: self.current_module, ..self.dummy_parent_scope() }
;
3638 self.resolve_path(path
, opt_ns
, &parent_scope
, record_used
, path_span
, crate_lint
)
3644 opt_ns
: Option
<Namespace
>, // `None` indicates a module path in import
3645 parent_scope
: &ParentScope
<'a
>,
3648 crate_lint
: CrateLint
,
3649 ) -> PathResult
<'a
> {
3650 let mut module
= None
;
3651 let mut allow_super
= true;
3652 let mut second_binding
= None
;
3653 self.current_module
= parent_scope
.module
;
3656 "resolve_path(path={:?}, opt_ns={:?}, record_used={:?}, \
3657 path_span={:?}, crate_lint={:?})",
3665 for (i
, &Segment { ident, id }
) in path
.iter().enumerate() {
3666 debug
!("resolve_path ident {} {:?} {:?}", i
, ident
, id
);
3667 let record_segment_res
= |this
: &mut Self, res
| {
3669 if let Some(id
) = id
{
3670 if !this
.partial_res_map
.contains_key(&id
) {
3671 assert
!(id
!= ast
::DUMMY_NODE_ID
, "Trying to resolve dummy id");
3672 this
.record_partial_res(id
, PartialRes
::new(res
));
3678 let is_last
= i
== path
.len() - 1;
3679 let ns
= if is_last { opt_ns.unwrap_or(TypeNS) }
else { TypeNS }
;
3680 let name
= ident
.name
;
3682 allow_super
&= ns
== TypeNS
&&
3683 (name
== kw
::SelfLower
||
3687 if allow_super
&& name
== kw
::Super
{
3688 let mut ctxt
= ident
.span
.ctxt().modern();
3689 let self_module
= match i
{
3690 0 => Some(self.resolve_self(&mut ctxt
, self.current_module
)),
3692 Some(ModuleOrUniformRoot
::Module(module
)) => Some(module
),
3696 if let Some(self_module
) = self_module
{
3697 if let Some(parent
) = self_module
.parent
{
3698 module
= Some(ModuleOrUniformRoot
::Module(
3699 self.resolve_self(&mut ctxt
, parent
)));
3703 let msg
= "there are too many initial `super`s.".to_string();
3704 return PathResult
::Failed
{
3708 is_error_from_last_segment
: false,
3712 if name
== kw
::SelfLower
{
3713 let mut ctxt
= ident
.span
.ctxt().modern();
3714 module
= Some(ModuleOrUniformRoot
::Module(
3715 self.resolve_self(&mut ctxt
, self.current_module
)));
3718 if name
== kw
::PathRoot
&& ident
.span
.rust_2018() {
3719 module
= Some(ModuleOrUniformRoot
::ExternPrelude
);
3722 if name
== kw
::PathRoot
&&
3723 ident
.span
.rust_2015() && self.session
.rust_2018() {
3724 // `::a::b` from 2015 macro on 2018 global edition
3725 module
= Some(ModuleOrUniformRoot
::CrateRootAndExternPrelude
);
3728 if name
== kw
::PathRoot
||
3729 name
== kw
::Crate
||
3730 name
== kw
::DollarCrate
{
3731 // `::a::b`, `crate::a::b` or `$crate::a::b`
3732 module
= Some(ModuleOrUniformRoot
::Module(
3733 self.resolve_crate_root(ident
)));
3739 // Report special messages for path segment keywords in wrong positions.
3740 if ident
.is_path_segment_keyword() && i
!= 0 {
3741 let name_str
= if name
== kw
::PathRoot
{
3742 "crate root".to_string()
3744 format
!("`{}`", name
)
3746 let label
= if i
== 1 && path
[0].ident
.name
== kw
::PathRoot
{
3747 format
!("global paths cannot start with {}", name_str
)
3749 format
!("{} in paths can only be used in start position", name_str
)
3751 return PathResult
::Failed
{
3755 is_error_from_last_segment
: false,
3759 let binding
= if let Some(module
) = module
{
3760 self.resolve_ident_in_module(module
, ident
, ns
, None
, record_used
, path_span
)
3761 } else if opt_ns
.is_none() || opt_ns
== Some(MacroNS
) {
3762 assert
!(ns
== TypeNS
);
3763 let scopes
= if opt_ns
.is_none() { ScopeSet::Import(ns) }
else { ScopeSet::Module }
;
3764 self.early_resolve_ident_in_lexical_scope(ident
, scopes
, parent_scope
, record_used
,
3765 record_used
, path_span
)
3767 let record_used_id
=
3768 if record_used { crate_lint.node_id().or(Some(CRATE_NODE_ID)) }
else { None }
;
3769 match self.resolve_ident_in_lexical_scope(ident
, ns
, record_used_id
, path_span
) {
3770 // we found a locally-imported or available item/module
3771 Some(LexicalScopeBinding
::Item(binding
)) => Ok(binding
),
3772 // we found a local variable or type param
3773 Some(LexicalScopeBinding
::Res(res
))
3774 if opt_ns
== Some(TypeNS
) || opt_ns
== Some(ValueNS
) => {
3775 record_segment_res(self, res
);
3776 return PathResult
::NonModule(PartialRes
::with_unresolved_segments(
3780 _
=> Err(Determinacy
::determined(record_used
)),
3787 second_binding
= Some(binding
);
3789 let res
= binding
.res();
3790 let maybe_assoc
= opt_ns
!= Some(MacroNS
) && PathSource
::Type
.is_expected(res
);
3791 if let Some(next_module
) = binding
.module() {
3792 module
= Some(ModuleOrUniformRoot
::Module(next_module
));
3793 record_segment_res(self, res
);
3794 } else if res
== Res
::ToolMod
&& i
+ 1 != path
.len() {
3795 if binding
.is_import() {
3796 self.session
.struct_span_err(
3797 ident
.span
, "cannot use a tool module through an import"
3799 binding
.span
, "the tool module imported here"
3802 let res
= Res
::NonMacroAttr(NonMacroAttrKind
::Tool
);
3803 return PathResult
::NonModule(PartialRes
::new(res
));
3804 } else if res
== Res
::Err
{
3805 return PathResult
::NonModule(PartialRes
::new(Res
::Err
));
3806 } else if opt_ns
.is_some() && (is_last
|| maybe_assoc
) {
3807 self.lint_if_path_starts_with_module(
3813 return PathResult
::NonModule(PartialRes
::with_unresolved_segments(
3814 res
, path
.len() - i
- 1
3817 let label
= format
!(
3818 "`{}` is {} {}, not a module",
3824 return PathResult
::Failed
{
3828 is_error_from_last_segment
: is_last
,
3832 Err(Undetermined
) => return PathResult
::Indeterminate
,
3833 Err(Determined
) => {
3834 if let Some(ModuleOrUniformRoot
::Module(module
)) = module
{
3835 if opt_ns
.is_some() && !module
.is_normal() {
3836 return PathResult
::NonModule(PartialRes
::with_unresolved_segments(
3837 module
.res().unwrap(), path
.len() - i
3841 let module_res
= match module
{
3842 Some(ModuleOrUniformRoot
::Module(module
)) => module
.res(),
3845 let (label
, suggestion
) = if module_res
== self.graph_root
.res() {
3846 let is_mod
= |res
| {
3847 match res { Res::Def(DefKind::Mod, _) => true, _ => false }
3849 let mut candidates
=
3850 self.lookup_import_candidates(ident
, TypeNS
, is_mod
);
3851 candidates
.sort_by_cached_key(|c
| {
3852 (c
.path
.segments
.len(), c
.path
.to_string())
3854 if let Some(candidate
) = candidates
.get(0) {
3856 String
::from("unresolved import"),
3858 vec
![(ident
.span
, candidate
.path
.to_string())],
3859 String
::from("a similar path exists"),
3860 Applicability
::MaybeIncorrect
,
3863 } else if !ident
.is_reserved() {
3864 (format
!("maybe a missing `extern crate {};`?", ident
), None
)
3866 // the parser will already have complained about the keyword being used
3867 return PathResult
::NonModule(PartialRes
::new(Res
::Err
));
3870 (format
!("use of undeclared type or module `{}`", ident
), None
)
3872 (format
!("could not find `{}` in `{}`", ident
, path
[i
- 1].ident
), None
)
3874 return PathResult
::Failed
{
3878 is_error_from_last_segment
: is_last
,
3884 self.lint_if_path_starts_with_module(crate_lint
, path
, path_span
, second_binding
);
3886 PathResult
::Module(match module
{
3887 Some(module
) => module
,
3888 None
if path
.is_empty() => ModuleOrUniformRoot
::CurrentScope
,
3889 _
=> span_bug
!(path_span
, "resolve_path: non-empty path `{:?}` has no module", path
),
3893 fn lint_if_path_starts_with_module(
3895 crate_lint
: CrateLint
,
3898 second_binding
: Option
<&NameBinding
<'_
>>,
3900 let (diag_id
, diag_span
) = match crate_lint
{
3901 CrateLint
::No
=> return,
3902 CrateLint
::SimplePath(id
) => (id
, path_span
),
3903 CrateLint
::UsePath { root_id, root_span }
=> (root_id
, root_span
),
3904 CrateLint
::QPathTrait { qpath_id, qpath_span }
=> (qpath_id
, qpath_span
),
3907 let first_name
= match path
.get(0) {
3908 // In the 2018 edition this lint is a hard error, so nothing to do
3909 Some(seg
) if seg
.ident
.span
.rust_2015() && self.session
.rust_2015() => seg
.ident
.name
,
3913 // We're only interested in `use` paths which should start with
3914 // `{{root}}` currently.
3915 if first_name
!= kw
::PathRoot
{
3920 // If this import looks like `crate::...` it's already good
3921 Some(Segment { ident, .. }
) if ident
.name
== kw
::Crate
=> return,
3922 // Otherwise go below to see if it's an extern crate
3924 // If the path has length one (and it's `PathRoot` most likely)
3925 // then we don't know whether we're gonna be importing a crate or an
3926 // item in our crate. Defer this lint to elsewhere
3930 // If the first element of our path was actually resolved to an
3931 // `ExternCrate` (also used for `crate::...`) then no need to issue a
3932 // warning, this looks all good!
3933 if let Some(binding
) = second_binding
{
3934 if let NameBindingKind
::Import { directive: d, .. }
= binding
.kind
{
3935 // Careful: we still want to rewrite paths from
3936 // renamed extern crates.
3937 if let ImportDirectiveSubclass
::ExternCrate { source: None, .. }
= d
.subclass
{
3943 let diag
= lint
::builtin
::BuiltinLintDiagnostics
3944 ::AbsPathWithModule(diag_span
);
3945 self.session
.buffer_lint_with_diagnostic(
3946 lint
::builtin
::ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE
,
3948 "absolute paths must start with `self`, `super`, \
3949 `crate`, or an external crate name in the 2018 edition",
3953 // Validate a local resolution (from ribs).
3954 fn validate_res_from_ribs(
3962 debug
!("validate_res_from_ribs({:?})", res
);
3963 let ribs
= &self.ribs
[ns
][rib_index
+ 1..];
3965 // An invalid forward use of a type parameter from a previous default.
3966 if let ForwardTyParamBanRibKind
= self.ribs
[ns
][rib_index
].kind
{
3968 resolve_error(self, span
, ResolutionError
::ForwardDeclaredTyParam
);
3970 assert_eq
!(res
, Res
::Err
);
3974 // An invalid use of a type parameter as the type of a const parameter.
3975 if let TyParamAsConstParamTy
= self.ribs
[ns
][rib_index
].kind
{
3977 resolve_error(self, span
, ResolutionError
::ConstParamDependentOnTypeParam
);
3979 assert_eq
!(res
, Res
::Err
);
3985 use ResolutionError
::*;
3986 let mut res_err
= None
;
3990 NormalRibKind
| ModuleRibKind(..) | MacroDefinition(..) |
3991 ForwardTyParamBanRibKind
| TyParamAsConstParamTy
=> {
3992 // Nothing to do. Continue.
3994 ItemRibKind
| FnItemRibKind
| AssocItemRibKind
=> {
3995 // This was an attempt to access an upvar inside a
3996 // named function item. This is not allowed, so we
3999 // We don't immediately trigger a resolve error, because
4000 // we want certain other resolution errors (namely those
4001 // emitted for `ConstantItemRibKind` below) to take
4003 res_err
= Some(CannotCaptureDynamicEnvironmentInFnItem
);
4006 ConstantItemRibKind
=> {
4007 // Still doesn't deal with upvars
4009 resolve_error(self, span
, AttemptToUseNonConstantValueInConstant
);
4015 if let Some(res_err
) = res_err
{
4016 resolve_error(self, span
, res_err
);
4020 Res
::Def(DefKind
::TyParam
, _
) | Res
::SelfTy(..) => {
4023 NormalRibKind
| AssocItemRibKind
|
4024 ModuleRibKind(..) | MacroDefinition(..) | ForwardTyParamBanRibKind
|
4025 ConstantItemRibKind
| TyParamAsConstParamTy
=> {
4026 // Nothing to do. Continue.
4028 ItemRibKind
| FnItemRibKind
=> {
4029 // This was an attempt to use a type parameter outside its scope.
4034 ResolutionError
::GenericParamsFromOuterFunction(res
),
4042 Res
::Def(DefKind
::ConstParam
, _
) => {
4043 let mut ribs
= ribs
.iter().peekable();
4044 if let Some(Rib { kind: FnItemRibKind, .. }
) = ribs
.peek() {
4045 // When declaring const parameters inside function signatures, the first rib
4046 // is always a `FnItemRibKind`. In this case, we can skip it, to avoid it
4047 // (spuriously) conflicting with the const param.
4051 if let ItemRibKind
| FnItemRibKind
= rib
.kind
{
4052 // This was an attempt to use a const parameter outside its scope.
4057 ResolutionError
::GenericParamsFromOuterFunction(res
),
4069 fn lookup_assoc_candidate
<FilterFn
>(&mut self,
4072 filter_fn
: FilterFn
)
4073 -> Option
<AssocSuggestion
>
4074 where FilterFn
: Fn(Res
) -> bool
4076 fn extract_node_id(t
: &Ty
) -> Option
<NodeId
> {
4078 TyKind
::Path(None
, _
) => Some(t
.id
),
4079 TyKind
::Rptr(_
, ref mut_ty
) => extract_node_id(&mut_ty
.ty
),
4080 // This doesn't handle the remaining `Ty` variants as they are not
4081 // that commonly the self_type, it might be interesting to provide
4082 // support for those in future.
4087 // Fields are generally expected in the same contexts as locals.
4088 if filter_fn(Res
::Local(ast
::DUMMY_NODE_ID
)) {
4089 if let Some(node_id
) = self.current_self_type
.as_ref().and_then(extract_node_id
) {
4090 // Look for a field with the same name in the current self_type.
4091 if let Some(resolution
) = self.partial_res_map
.get(&node_id
) {
4092 match resolution
.base_res() {
4093 Res
::Def(DefKind
::Struct
, did
) | Res
::Def(DefKind
::Union
, did
)
4094 if resolution
.unresolved_segments() == 0 => {
4095 if let Some(field_names
) = self.field_names
.get(&did
) {
4096 if field_names
.iter().any(|&field_name
| ident
.name
== field_name
) {
4097 return Some(AssocSuggestion
::Field
);
4107 // Look for associated items in the current trait.
4108 if let Some((module
, _
)) = self.current_trait_ref
{
4109 if let Ok(binding
) = self.resolve_ident_in_module(
4110 ModuleOrUniformRoot
::Module(module
),
4117 let res
= binding
.res();
4119 return Some(if self.has_self
.contains(&res
.def_id()) {
4120 AssocSuggestion
::MethodWithSelf
4122 AssocSuggestion
::AssocItem
4131 fn lookup_typo_candidate
<FilterFn
>(
4135 filter_fn
: FilterFn
,
4137 ) -> Option
<TypoSuggestion
>
4139 FilterFn
: Fn(Res
) -> bool
,
4141 let add_module_candidates
= |module
: Module
<'_
>, names
: &mut Vec
<TypoSuggestion
>| {
4142 for (&(ident
, _
), resolution
) in module
.resolutions
.borrow().iter() {
4143 if let Some(binding
) = resolution
.borrow().binding
{
4144 if filter_fn(binding
.res()) {
4145 names
.push(TypoSuggestion
{
4146 candidate
: ident
.name
,
4147 article
: binding
.res().article(),
4148 kind
: binding
.res().descr(),
4155 let mut names
= Vec
::new();
4156 if path
.len() == 1 {
4157 // Search in lexical scope.
4158 // Walk backwards up the ribs in scope and collect candidates.
4159 for rib
in self.ribs
[ns
].iter().rev() {
4160 // Locals and type parameters
4161 for (ident
, &res
) in &rib
.bindings
{
4163 names
.push(TypoSuggestion
{
4164 candidate
: ident
.name
,
4165 article
: res
.article(),
4171 if let ModuleRibKind(module
) = rib
.kind
{
4172 // Items from this module
4173 add_module_candidates(module
, &mut names
);
4175 if let ModuleKind
::Block(..) = module
.kind
{
4176 // We can see through blocks
4178 // Items from the prelude
4179 if !module
.no_implicit_prelude
{
4180 names
.extend(self.extern_prelude
.clone().iter().flat_map(|(ident
, _
)| {
4182 .maybe_process_path_extern(ident
.name
, ident
.span
)
4183 .and_then(|crate_id
| {
4184 let crate_mod
= Res
::Def(
4188 index
: CRATE_DEF_INDEX
,
4192 if filter_fn(crate_mod
) {
4193 Some(TypoSuggestion
{
4194 candidate
: ident
.name
,
4204 if let Some(prelude
) = self.prelude
{
4205 add_module_candidates(prelude
, &mut names
);
4212 // Add primitive types to the mix
4213 if filter_fn(Res
::PrimTy(Bool
)) {
4215 self.primitive_type_table
.primitive_types
.iter().map(|(name
, _
)| {
4219 kind
: "primitive type",
4225 // Search in module.
4226 let mod_path
= &path
[..path
.len() - 1];
4227 if let PathResult
::Module(module
) = self.resolve_path_without_parent_scope(
4228 mod_path
, Some(TypeNS
), false, span
, CrateLint
::No
4230 if let ModuleOrUniformRoot
::Module(module
) = module
{
4231 add_module_candidates(module
, &mut names
);
4236 let name
= path
[path
.len() - 1].ident
.name
;
4237 // Make sure error reporting is deterministic.
4238 names
.sort_by_cached_key(|suggestion
| suggestion
.candidate
.as_str());
4240 match find_best_match_for_name(
4241 names
.iter().map(|suggestion
| &suggestion
.candidate
),
4245 Some(found
) if found
!= name
=> names
4247 .find(|suggestion
| suggestion
.candidate
== found
),
4252 fn with_resolved_label
<F
>(&mut self, label
: Option
<Label
>, id
: NodeId
, f
: F
)
4253 where F
: FnOnce(&mut Resolver
<'_
>)
4255 if let Some(label
) = label
{
4256 self.unused_labels
.insert(id
, label
.ident
.span
);
4257 self.with_label_rib(|this
| {
4258 let ident
= label
.ident
.modern_and_legacy();
4259 this
.label_ribs
.last_mut().unwrap().bindings
.insert(ident
, id
);
4267 fn resolve_labeled_block(&mut self, label
: Option
<Label
>, id
: NodeId
, block
: &Block
) {
4268 self.with_resolved_label(label
, id
, |this
| this
.visit_block(block
));
4271 fn resolve_expr(&mut self, expr
: &Expr
, parent
: Option
<&Expr
>) {
4272 // First, record candidate traits for this expression if it could
4273 // result in the invocation of a method call.
4275 self.record_candidate_traits_for_expr_if_necessary(expr
);
4277 // Next, resolve the node.
4279 ExprKind
::Path(ref qself
, ref path
) => {
4280 self.smart_resolve_path(expr
.id
, qself
.as_ref(), path
, PathSource
::Expr(parent
));
4281 visit
::walk_expr(self, expr
);
4284 ExprKind
::Struct(ref path
, ..) => {
4285 self.smart_resolve_path(expr
.id
, None
, path
, PathSource
::Struct
);
4286 visit
::walk_expr(self, expr
);
4289 ExprKind
::Break(Some(label
), _
) | ExprKind
::Continue(Some(label
)) => {
4290 let node_id
= self.search_label(label
.ident
, |rib
, ident
| {
4291 rib
.bindings
.get(&ident
.modern_and_legacy()).cloned()
4295 // Search again for close matches...
4296 // Picks the first label that is "close enough", which is not necessarily
4297 // the closest match
4298 let close_match
= self.search_label(label
.ident
, |rib
, ident
| {
4299 let names
= rib
.bindings
.iter().filter_map(|(id
, _
)| {
4300 if id
.span
.ctxt() == label
.ident
.span
.ctxt() {
4306 find_best_match_for_name(names
, &*ident
.as_str(), None
)
4308 self.record_partial_res(expr
.id
, PartialRes
::new(Res
::Err
));
4311 ResolutionError
::UndeclaredLabel(&label
.ident
.as_str(),
4315 // Since this res is a label, it is never read.
4316 self.label_res_map
.insert(expr
.id
, node_id
);
4317 self.unused_labels
.remove(&node_id
);
4321 // visit `break` argument if any
4322 visit
::walk_expr(self, expr
);
4325 ExprKind
::Let(ref pats
, ref scrutinee
) => {
4326 self.visit_expr(scrutinee
);
4327 self.resolve_pats(pats
, PatternSource
::Let
);
4330 ExprKind
::If(ref cond
, ref then
, ref opt_else
) => {
4331 self.ribs
[ValueNS
].push(Rib
::new(NormalRibKind
));
4332 self.visit_expr(cond
);
4333 self.visit_block(then
);
4334 self.ribs
[ValueNS
].pop();
4336 opt_else
.as_ref().map(|expr
| self.visit_expr(expr
));
4339 ExprKind
::Loop(ref block
, label
) => self.resolve_labeled_block(label
, expr
.id
, &block
),
4341 ExprKind
::While(ref subexpression
, ref block
, label
) => {
4342 self.with_resolved_label(label
, expr
.id
, |this
| {
4343 this
.ribs
[ValueNS
].push(Rib
::new(NormalRibKind
));
4344 this
.visit_expr(subexpression
);
4345 this
.visit_block(block
);
4346 this
.ribs
[ValueNS
].pop();
4350 ExprKind
::ForLoop(ref pattern
, ref subexpression
, ref block
, label
) => {
4351 self.visit_expr(subexpression
);
4352 self.ribs
[ValueNS
].push(Rib
::new(NormalRibKind
));
4353 self.resolve_pattern(pattern
, PatternSource
::For
, &mut FxHashMap
::default());
4355 self.resolve_labeled_block(label
, expr
.id
, block
);
4357 self.ribs
[ValueNS
].pop();
4360 ExprKind
::Block(ref block
, label
) => self.resolve_labeled_block(label
, block
.id
, block
),
4362 // Equivalent to `visit::walk_expr` + passing some context to children.
4363 ExprKind
::Field(ref subexpression
, _
) => {
4364 self.resolve_expr(subexpression
, Some(expr
));
4366 ExprKind
::MethodCall(ref segment
, ref arguments
) => {
4367 let mut arguments
= arguments
.iter();
4368 self.resolve_expr(arguments
.next().unwrap(), Some(expr
));
4369 for argument
in arguments
{
4370 self.resolve_expr(argument
, None
);
4372 self.visit_path_segment(expr
.span
, segment
);
4375 ExprKind
::Call(ref callee
, ref arguments
) => {
4376 self.resolve_expr(callee
, Some(expr
));
4377 for argument
in arguments
{
4378 self.resolve_expr(argument
, None
);
4381 ExprKind
::Type(ref type_expr
, _
) => {
4382 self.current_type_ascription
.push(type_expr
.span
);
4383 visit
::walk_expr(self, expr
);
4384 self.current_type_ascription
.pop();
4386 // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to
4387 // resolve the arguments within the proper scopes so that usages of them inside the
4388 // closure are detected as upvars rather than normal closure arg usages.
4390 _
, IsAsync
::Async { .. }
, _
,
4391 ref fn_decl
, ref body
, _span
,
4393 let rib_kind
= NormalRibKind
;
4394 self.ribs
[ValueNS
].push(Rib
::new(rib_kind
));
4395 // Resolve arguments:
4396 let mut bindings_list
= FxHashMap
::default();
4397 for argument
in &fn_decl
.inputs
{
4398 self.resolve_pattern(&argument
.pat
, PatternSource
::FnParam
, &mut bindings_list
);
4399 self.visit_ty(&argument
.ty
);
4401 // No need to resolve return type-- the outer closure return type is
4402 // FunctionRetTy::Default
4404 // Now resolve the inner closure
4406 // No need to resolve arguments: the inner closure has none.
4407 // Resolve the return type:
4408 visit
::walk_fn_ret_ty(self, &fn_decl
.output
);
4410 self.visit_expr(body
);
4412 self.ribs
[ValueNS
].pop();
4415 visit
::walk_expr(self, expr
);
4420 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr
: &Expr
) {
4422 ExprKind
::Field(_
, ident
) => {
4423 // FIXME(#6890): Even though you can't treat a method like a
4424 // field, we need to add any trait methods we find that match
4425 // the field name so that we can do some nice error reporting
4426 // later on in typeck.
4427 let traits
= self.get_traits_containing_item(ident
, ValueNS
);
4428 self.trait_map
.insert(expr
.id
, traits
);
4430 ExprKind
::MethodCall(ref segment
, ..) => {
4431 debug
!("(recording candidate traits for expr) recording traits for {}",
4433 let traits
= self.get_traits_containing_item(segment
.ident
, ValueNS
);
4434 self.trait_map
.insert(expr
.id
, traits
);
4442 fn get_traits_containing_item(&mut self, mut ident
: Ident
, ns
: Namespace
)
4443 -> Vec
<TraitCandidate
> {
4444 debug
!("(getting traits containing item) looking for '{}'", ident
.name
);
4446 let mut found_traits
= Vec
::new();
4447 // Look for the current trait.
4448 if let Some((module
, _
)) = self.current_trait_ref
{
4449 if self.resolve_ident_in_module(
4450 ModuleOrUniformRoot
::Module(module
),
4457 let def_id
= module
.def_id().unwrap();
4458 found_traits
.push(TraitCandidate { def_id: def_id, import_ids: smallvec![] }
);
4462 ident
.span
= ident
.span
.modern();
4463 let mut search_module
= self.current_module
;
4465 self.get_traits_in_module_containing_item(ident
, ns
, search_module
, &mut found_traits
);
4466 search_module
= unwrap_or
!(
4467 self.hygienic_lexical_parent(search_module
, &mut ident
.span
), break
4471 if let Some(prelude
) = self.prelude
{
4472 if !search_module
.no_implicit_prelude
{
4473 self.get_traits_in_module_containing_item(ident
, ns
, prelude
, &mut found_traits
);
4480 fn get_traits_in_module_containing_item(&mut self,
4484 found_traits
: &mut Vec
<TraitCandidate
>) {
4485 assert
!(ns
== TypeNS
|| ns
== ValueNS
);
4486 let mut traits
= module
.traits
.borrow_mut();
4487 if traits
.is_none() {
4488 let mut collected_traits
= Vec
::new();
4489 module
.for_each_child(|name
, ns
, binding
| {
4490 if ns
!= TypeNS { return }
4491 match binding
.res() {
4492 Res
::Def(DefKind
::Trait
, _
) |
4493 Res
::Def(DefKind
::TraitAlias
, _
) => collected_traits
.push((name
, binding
)),
4497 *traits
= Some(collected_traits
.into_boxed_slice());
4500 for &(trait_name
, binding
) in traits
.as_ref().unwrap().iter() {
4501 // Traits have pseudo-modules that can be used to search for the given ident.
4502 if let Some(module
) = binding
.module() {
4503 let mut ident
= ident
;
4504 if ident
.span
.glob_adjust(
4510 if self.resolve_ident_in_module_unadjusted(
4511 ModuleOrUniformRoot
::Module(module
),
4517 let import_ids
= self.find_transitive_imports(&binding
.kind
, trait_name
);
4518 let trait_def_id
= module
.def_id().unwrap();
4519 found_traits
.push(TraitCandidate { def_id: trait_def_id, import_ids }
);
4521 } else if let Res
::Def(DefKind
::TraitAlias
, _
) = binding
.res() {
4522 // For now, just treat all trait aliases as possible candidates, since we don't
4523 // know if the ident is somewhere in the transitive bounds.
4524 let import_ids
= self.find_transitive_imports(&binding
.kind
, trait_name
);
4525 let trait_def_id
= binding
.res().def_id();
4526 found_traits
.push(TraitCandidate { def_id: trait_def_id, import_ids }
);
4528 bug
!("candidate is not trait or trait alias?")
4533 fn find_transitive_imports(&mut self, mut kind
: &NameBindingKind
<'_
>,
4534 trait_name
: Ident
) -> SmallVec
<[NodeId
; 1]> {
4535 let mut import_ids
= smallvec
![];
4536 while let NameBindingKind
::Import { directive, binding, .. }
= kind
{
4537 self.maybe_unused_trait_imports
.insert(directive
.id
);
4538 self.add_to_glob_map(&directive
, trait_name
);
4539 import_ids
.push(directive
.id
);
4540 kind
= &binding
.kind
;
4545 fn lookup_import_candidates_from_module
<FilterFn
>(&mut self,
4546 lookup_ident
: Ident
,
4547 namespace
: Namespace
,
4548 start_module
: &'a ModuleData
<'a
>,
4550 filter_fn
: FilterFn
)
4551 -> Vec
<ImportSuggestion
>
4552 where FilterFn
: Fn(Res
) -> bool
4554 let mut candidates
= Vec
::new();
4555 let mut seen_modules
= FxHashSet
::default();
4556 let not_local_module
= crate_name
.name
!= kw
::Crate
;
4557 let mut worklist
= vec
![(start_module
, Vec
::<ast
::PathSegment
>::new(), not_local_module
)];
4559 while let Some((in_module
,
4561 in_module_is_extern
)) = worklist
.pop() {
4562 self.populate_module_if_necessary(in_module
);
4564 // We have to visit module children in deterministic order to avoid
4565 // instabilities in reported imports (#43552).
4566 in_module
.for_each_child_stable(|ident
, ns
, name_binding
| {
4567 // avoid imports entirely
4568 if name_binding
.is_import() && !name_binding
.is_extern_crate() { return; }
4569 // avoid non-importable candidates as well
4570 if !name_binding
.is_importable() { return; }
4572 // collect results based on the filter function
4573 if ident
.name
== lookup_ident
.name
&& ns
== namespace
{
4574 let res
= name_binding
.res();
4577 let mut segms
= path_segments
.clone();
4578 if lookup_ident
.span
.rust_2018() {
4579 // crate-local absolute paths start with `crate::` in edition 2018
4580 // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
4582 0, ast
::PathSegment
::from_ident(crate_name
)
4586 segms
.push(ast
::PathSegment
::from_ident(ident
));
4588 span
: name_binding
.span
,
4591 // the entity is accessible in the following cases:
4592 // 1. if it's defined in the same crate, it's always
4593 // accessible (since private entities can be made public)
4594 // 2. if it's defined in another crate, it's accessible
4595 // only if both the module is public and the entity is
4596 // declared as public (due to pruning, we don't explore
4597 // outside crate private modules => no need to check this)
4598 if !in_module_is_extern
|| name_binding
.vis
== ty
::Visibility
::Public
{
4599 let did
= match res
{
4600 Res
::Def(DefKind
::Ctor(..), did
) => self.parent(did
),
4601 _
=> res
.opt_def_id(),
4603 candidates
.push(ImportSuggestion { did, path }
);
4608 // collect submodules to explore
4609 if let Some(module
) = name_binding
.module() {
4611 let mut path_segments
= path_segments
.clone();
4612 path_segments
.push(ast
::PathSegment
::from_ident(ident
));
4614 let is_extern_crate_that_also_appears_in_prelude
=
4615 name_binding
.is_extern_crate() &&
4616 lookup_ident
.span
.rust_2018();
4618 let is_visible_to_user
=
4619 !in_module_is_extern
|| name_binding
.vis
== ty
::Visibility
::Public
;
4621 if !is_extern_crate_that_also_appears_in_prelude
&& is_visible_to_user
{
4622 // add the module to the lookup
4623 let is_extern
= in_module_is_extern
|| name_binding
.is_extern_crate();
4624 if seen_modules
.insert(module
.def_id().unwrap()) {
4625 worklist
.push((module
, path_segments
, is_extern
));
4635 /// When name resolution fails, this method can be used to look up candidate
4636 /// entities with the expected name. It allows filtering them using the
4637 /// supplied predicate (which should be used to only accept the types of
4638 /// definitions expected, e.g., traits). The lookup spans across all crates.
4640 /// N.B., the method does not look into imports, but this is not a problem,
4641 /// since we report the definitions (thus, the de-aliased imports).
4642 fn lookup_import_candidates
<FilterFn
>(&mut self,
4643 lookup_ident
: Ident
,
4644 namespace
: Namespace
,
4645 filter_fn
: FilterFn
)
4646 -> Vec
<ImportSuggestion
>
4647 where FilterFn
: Fn(Res
) -> bool
4649 let mut suggestions
= self.lookup_import_candidates_from_module(
4650 lookup_ident
, namespace
, self.graph_root
, Ident
::with_empty_ctxt(kw
::Crate
), &filter_fn
4653 if lookup_ident
.span
.rust_2018() {
4654 let extern_prelude_names
= self.extern_prelude
.clone();
4655 for (ident
, _
) in extern_prelude_names
.into_iter() {
4656 if let Some(crate_id
) = self.crate_loader
.maybe_process_path_extern(ident
.name
,
4658 let crate_root
= self.get_module(DefId
{
4660 index
: CRATE_DEF_INDEX
,
4662 self.populate_module_if_necessary(&crate_root
);
4664 suggestions
.extend(self.lookup_import_candidates_from_module(
4665 lookup_ident
, namespace
, crate_root
, ident
, &filter_fn
));
4673 fn find_module(&mut self, def_id
: DefId
) -> Option
<(Module
<'a
>, ImportSuggestion
)> {
4674 let mut result
= None
;
4675 let mut seen_modules
= FxHashSet
::default();
4676 let mut worklist
= vec
![(self.graph_root
, Vec
::new())];
4678 while let Some((in_module
, path_segments
)) = worklist
.pop() {
4679 // abort if the module is already found
4680 if result
.is_some() { break; }
4682 self.populate_module_if_necessary(in_module
);
4684 in_module
.for_each_child_stable(|ident
, _
, name_binding
| {
4685 // abort if the module is already found or if name_binding is private external
4686 if result
.is_some() || !name_binding
.vis
.is_visible_locally() {
4689 if let Some(module
) = name_binding
.module() {
4691 let mut path_segments
= path_segments
.clone();
4692 path_segments
.push(ast
::PathSegment
::from_ident(ident
));
4693 let module_def_id
= module
.def_id().unwrap();
4694 if module_def_id
== def_id
{
4696 span
: name_binding
.span
,
4697 segments
: path_segments
,
4699 result
= Some((module
, ImportSuggestion { did: Some(def_id), path }
));
4701 // add the module to the lookup
4702 if seen_modules
.insert(module_def_id
) {
4703 worklist
.push((module
, path_segments
));
4713 fn collect_enum_variants(&mut self, def_id
: DefId
) -> Option
<Vec
<Path
>> {
4714 self.find_module(def_id
).map(|(enum_module
, enum_import_suggestion
)| {
4715 self.populate_module_if_necessary(enum_module
);
4717 let mut variants
= Vec
::new();
4718 enum_module
.for_each_child_stable(|ident
, _
, name_binding
| {
4719 if let Res
::Def(DefKind
::Variant
, _
) = name_binding
.res() {
4720 let mut segms
= enum_import_suggestion
.path
.segments
.clone();
4721 segms
.push(ast
::PathSegment
::from_ident(ident
));
4722 variants
.push(Path
{
4723 span
: name_binding
.span
,
4732 fn record_partial_res(&mut self, node_id
: NodeId
, resolution
: PartialRes
) {
4733 debug
!("(recording res) recording {:?} for {}", resolution
, node_id
);
4734 if let Some(prev_res
) = self.partial_res_map
.insert(node_id
, resolution
) {
4735 panic
!("path resolved multiple times ({:?} before, {:?} now)", prev_res
, resolution
);
4739 fn resolve_visibility(&mut self, vis
: &ast
::Visibility
) -> ty
::Visibility
{
4741 ast
::VisibilityKind
::Public
=> ty
::Visibility
::Public
,
4742 ast
::VisibilityKind
::Crate(..) => {
4743 ty
::Visibility
::Restricted(DefId
::local(CRATE_DEF_INDEX
))
4745 ast
::VisibilityKind
::Inherited
=> {
4746 ty
::Visibility
::Restricted(self.current_module
.normal_ancestor_id
)
4748 ast
::VisibilityKind
::Restricted { ref path, id, .. }
=> {
4749 // For visibilities we are not ready to provide correct implementation of "uniform
4750 // paths" right now, so on 2018 edition we only allow module-relative paths for now.
4751 // On 2015 edition visibilities are resolved as crate-relative by default,
4752 // so we are prepending a root segment if necessary.
4753 let ident
= path
.segments
.get(0).expect("empty path in visibility").ident
;
4754 let crate_root
= if ident
.is_path_segment_keyword() {
4756 } else if ident
.span
.rust_2018() {
4757 let msg
= "relative paths are not supported in visibilities on 2018 edition";
4758 self.session
.struct_span_err(ident
.span
, msg
)
4762 format
!("crate::{}", path
),
4763 Applicability
::MaybeIncorrect
,
4766 return ty
::Visibility
::Public
;
4768 let ctxt
= ident
.span
.ctxt();
4769 Some(Segment
::from_ident(Ident
::new(
4770 kw
::PathRoot
, path
.span
.shrink_to_lo().with_ctxt(ctxt
)
4774 let segments
= crate_root
.into_iter()
4775 .chain(path
.segments
.iter().map(|seg
| seg
.into())).collect
::<Vec
<_
>>();
4776 let res
= self.smart_resolve_path_fragment(
4781 PathSource
::Visibility
,
4782 CrateLint
::SimplePath(id
),
4784 if res
== Res
::Err
{
4785 ty
::Visibility
::Public
4787 let vis
= ty
::Visibility
::Restricted(res
.def_id());
4788 if self.is_accessible(vis
) {
4791 self.session
.span_err(path
.span
, "visibilities can only be restricted \
4792 to ancestor modules");
4793 ty
::Visibility
::Public
4800 fn is_accessible(&self, vis
: ty
::Visibility
) -> bool
{
4801 vis
.is_accessible_from(self.current_module
.normal_ancestor_id
, self)
4804 fn is_accessible_from(&self, vis
: ty
::Visibility
, module
: Module
<'a
>) -> bool
{
4805 vis
.is_accessible_from(module
.normal_ancestor_id
, self)
4808 fn set_binding_parent_module(&mut self, binding
: &'a NameBinding
<'a
>, module
: Module
<'a
>) {
4809 if let Some(old_module
) = self.binding_parent_modules
.insert(PtrKey(binding
), module
) {
4810 if !ptr
::eq(module
, old_module
) {
4811 span_bug
!(binding
.span
, "parent module is reset for binding");
4816 fn disambiguate_legacy_vs_modern(
4818 legacy
: &'a NameBinding
<'a
>,
4819 modern
: &'a NameBinding
<'a
>,
4821 // Some non-controversial subset of ambiguities "modern macro name" vs "macro_rules"
4822 // is disambiguated to mitigate regressions from macro modularization.
4823 // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general.
4824 match (self.binding_parent_modules
.get(&PtrKey(legacy
)),
4825 self.binding_parent_modules
.get(&PtrKey(modern
))) {
4826 (Some(legacy
), Some(modern
)) =>
4827 legacy
.normal_ancestor_id
== modern
.normal_ancestor_id
&&
4828 modern
.is_ancestor_of(legacy
),
4833 fn binding_description(&self, b
: &NameBinding
<'_
>, ident
: Ident
, from_prelude
: bool
) -> String
{
4834 if b
.span
.is_dummy() {
4835 let add_built_in
= match b
.res() {
4836 // These already contain the "built-in" prefix or look bad with it.
4837 Res
::NonMacroAttr(..) | Res
::PrimTy(..) | Res
::ToolMod
=> false,
4840 let (built_in
, from
) = if from_prelude
{
4841 ("", " from prelude")
4842 } else if b
.is_extern_crate() && !b
.is_import() &&
4843 self.session
.opts
.externs
.get(&ident
.as_str()).is_some() {
4844 ("", " passed with `--extern`")
4845 } else if add_built_in
{
4851 let article
= if built_in
.is_empty() { b.article() }
else { "a" }
;
4852 format
!("{a}{built_in} {thing}{from}",
4853 a
= article
, thing
= b
.descr(), built_in
= built_in
, from
= from
)
4855 let introduced
= if b
.is_import() { "imported" }
else { "defined" }
;
4856 format
!("the {thing} {introduced} here",
4857 thing
= b
.descr(), introduced
= introduced
)
4861 fn report_ambiguity_error(&self, ambiguity_error
: &AmbiguityError
<'_
>) {
4862 let AmbiguityError { kind, ident, b1, b2, misc1, misc2 }
= *ambiguity_error
;
4863 let (b1
, b2
, misc1
, misc2
, swapped
) = if b2
.span
.is_dummy() && !b1
.span
.is_dummy() {
4864 // We have to print the span-less alternative first, otherwise formatting looks bad.
4865 (b2
, b1
, misc2
, misc1
, true)
4867 (b1
, b2
, misc1
, misc2
, false)
4870 let mut err
= struct_span_err
!(self.session
, ident
.span
, E0659
,
4871 "`{ident}` is ambiguous ({why})",
4872 ident
= ident
, why
= kind
.descr());
4873 err
.span_label(ident
.span
, "ambiguous name");
4875 let mut could_refer_to
= |b
: &NameBinding
<'_
>, misc
: AmbiguityErrorMisc
, also
: &str| {
4876 let what
= self.binding_description(b
, ident
, misc
== AmbiguityErrorMisc
::FromPrelude
);
4877 let note_msg
= format
!("`{ident}` could{also} refer to {what}",
4878 ident
= ident
, also
= also
, what
= what
);
4880 let mut help_msgs
= Vec
::new();
4881 if b
.is_glob_import() && (kind
== AmbiguityKind
::GlobVsGlob
||
4882 kind
== AmbiguityKind
::GlobVsExpanded
||
4883 kind
== AmbiguityKind
::GlobVsOuter
&&
4884 swapped
!= also
.is_empty()) {
4885 help_msgs
.push(format
!("consider adding an explicit import of \
4886 `{ident}` to disambiguate", ident
= ident
))
4888 if b
.is_extern_crate() && ident
.span
.rust_2018() {
4889 help_msgs
.push(format
!(
4890 "use `::{ident}` to refer to this {thing} unambiguously",
4891 ident
= ident
, thing
= b
.descr(),
4894 if misc
== AmbiguityErrorMisc
::SuggestCrate
{
4895 help_msgs
.push(format
!(
4896 "use `crate::{ident}` to refer to this {thing} unambiguously",
4897 ident
= ident
, thing
= b
.descr(),
4899 } else if misc
== AmbiguityErrorMisc
::SuggestSelf
{
4900 help_msgs
.push(format
!(
4901 "use `self::{ident}` to refer to this {thing} unambiguously",
4902 ident
= ident
, thing
= b
.descr(),
4906 err
.span_note(b
.span
, ¬e_msg
);
4907 for (i
, help_msg
) in help_msgs
.iter().enumerate() {
4908 let or
= if i
== 0 { "" }
else { "or " }
;
4909 err
.help(&format
!("{}{}", or
, help_msg
));
4913 could_refer_to(b1
, misc1
, "");
4914 could_refer_to(b2
, misc2
, " also");
4918 fn report_errors(&mut self, krate
: &Crate
) {
4919 self.report_with_use_injections(krate
);
4921 for &(span_use
, span_def
) in &self.macro_expanded_macro_export_errors
{
4922 let msg
= "macro-expanded `macro_export` macros from the current crate \
4923 cannot be referred to by absolute paths";
4924 self.session
.buffer_lint_with_diagnostic(
4925 lint
::builtin
::MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS
,
4926 CRATE_NODE_ID
, span_use
, msg
,
4927 lint
::builtin
::BuiltinLintDiagnostics
::
4928 MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def
),
4932 for ambiguity_error
in &self.ambiguity_errors
{
4933 self.report_ambiguity_error(ambiguity_error
);
4936 let mut reported_spans
= FxHashSet
::default();
4937 for &PrivacyError(dedup_span
, ident
, binding
) in &self.privacy_errors
{
4938 if reported_spans
.insert(dedup_span
) {
4939 span_err
!(self.session
, ident
.span
, E0603
, "{} `{}` is private",
4940 binding
.descr(), ident
.name
);
4945 fn report_with_use_injections(&mut self, krate
: &Crate
) {
4946 for UseError { mut err, candidates, node_id, better }
in self.use_injections
.drain(..) {
4947 let (span
, found_use
) = UsePlacementFinder
::check(krate
, node_id
);
4948 if !candidates
.is_empty() {
4949 show_candidates(&mut err
, span
, &candidates
, better
, found_use
);
4955 fn report_conflict
<'b
>(&mut self,
4959 new_binding
: &NameBinding
<'b
>,
4960 old_binding
: &NameBinding
<'b
>) {
4961 // Error on the second of two conflicting names
4962 if old_binding
.span
.lo() > new_binding
.span
.lo() {
4963 return self.report_conflict(parent
, ident
, ns
, old_binding
, new_binding
);
4966 let container
= match parent
.kind
{
4967 ModuleKind
::Def(DefKind
::Mod
, _
, _
) => "module",
4968 ModuleKind
::Def(DefKind
::Trait
, _
, _
) => "trait",
4969 ModuleKind
::Block(..) => "block",
4973 let old_noun
= match old_binding
.is_import() {
4975 false => "definition",
4978 let new_participle
= match new_binding
.is_import() {
4983 let (name
, span
) = (ident
.name
, self.session
.source_map().def_span(new_binding
.span
));
4985 if let Some(s
) = self.name_already_seen
.get(&name
) {
4991 let old_kind
= match (ns
, old_binding
.module()) {
4992 (ValueNS
, _
) => "value",
4993 (MacroNS
, _
) => "macro",
4994 (TypeNS
, _
) if old_binding
.is_extern_crate() => "extern crate",
4995 (TypeNS
, Some(module
)) if module
.is_normal() => "module",
4996 (TypeNS
, Some(module
)) if module
.is_trait() => "trait",
4997 (TypeNS
, _
) => "type",
5000 let msg
= format
!("the name `{}` is defined multiple times", name
);
5002 let mut err
= match (old_binding
.is_extern_crate(), new_binding
.is_extern_crate()) {
5003 (true, true) => struct_span_err
!(self.session
, span
, E0259
, "{}", msg
),
5004 (true, _
) | (_
, true) => match new_binding
.is_import() && old_binding
.is_import() {
5005 true => struct_span_err
!(self.session
, span
, E0254
, "{}", msg
),
5006 false => struct_span_err
!(self.session
, span
, E0260
, "{}", msg
),
5008 _
=> match (old_binding
.is_import(), new_binding
.is_import()) {
5009 (false, false) => struct_span_err
!(self.session
, span
, E0428
, "{}", msg
),
5010 (true, true) => struct_span_err
!(self.session
, span
, E0252
, "{}", msg
),
5011 _
=> struct_span_err
!(self.session
, span
, E0255
, "{}", msg
),
5015 err
.note(&format
!("`{}` must be defined only once in the {} namespace of this {}",
5020 err
.span_label(span
, format
!("`{}` re{} here", name
, new_participle
));
5022 self.session
.source_map().def_span(old_binding
.span
),
5023 format
!("previous {} of the {} `{}` here", old_noun
, old_kind
, name
),
5026 // See https://github.com/rust-lang/rust/issues/32354
5027 use NameBindingKind
::Import
;
5028 let directive
= match (&new_binding
.kind
, &old_binding
.kind
) {
5029 // If there are two imports where one or both have attributes then prefer removing the
5030 // import without attributes.
5031 (Import { directive: new, .. }
, Import { directive: old, .. }
) if {
5032 !new_binding
.span
.is_dummy() && !old_binding
.span
.is_dummy() &&
5033 (new
.has_attributes
|| old
.has_attributes
)
5035 if old
.has_attributes
{
5036 Some((new
, new_binding
.span
, true))
5038 Some((old
, old_binding
.span
, true))
5041 // Otherwise prioritize the new binding.
5042 (Import { directive, .. }
, other
) if !new_binding
.span
.is_dummy() =>
5043 Some((directive
, new_binding
.span
, other
.is_import())),
5044 (other
, Import { directive, .. }
) if !old_binding
.span
.is_dummy() =>
5045 Some((directive
, old_binding
.span
, other
.is_import())),
5049 // Check if the target of the use for both bindings is the same.
5050 let duplicate
= new_binding
.res().opt_def_id() == old_binding
.res().opt_def_id();
5051 let has_dummy_span
= new_binding
.span
.is_dummy() || old_binding
.span
.is_dummy();
5052 let from_item
= self.extern_prelude
.get(&ident
)
5053 .map(|entry
| entry
.introduced_by_item
)
5055 // Only suggest removing an import if both bindings are to the same def, if both spans
5056 // aren't dummy spans. Further, if both bindings are imports, then the ident must have
5057 // been introduced by a item.
5058 let should_remove_import
= duplicate
&& !has_dummy_span
&&
5059 ((new_binding
.is_extern_crate() || old_binding
.is_extern_crate()) || from_item
);
5062 Some((directive
, span
, true)) if should_remove_import
&& directive
.is_nested() =>
5063 self.add_suggestion_for_duplicate_nested_use(&mut err
, directive
, span
),
5064 Some((directive
, _
, true)) if should_remove_import
&& !directive
.is_glob() => {
5065 // Simple case - remove the entire import. Due to the above match arm, this can
5066 // only be a single use so just remove it entirely.
5067 err
.tool_only_span_suggestion(
5068 directive
.use_span_with_attributes
,
5069 "remove unnecessary import",
5071 Applicability
::MaybeIncorrect
,
5074 Some((directive
, span
, _
)) =>
5075 self.add_suggestion_for_rename_of_use(&mut err
, name
, directive
, span
),
5080 self.name_already_seen
.insert(name
, span
);
5083 /// This function adds a suggestion to change the binding name of a new import that conflicts
5084 /// with an existing import.
5086 /// ```ignore (diagnostic)
5087 /// help: you can use `as` to change the binding name of the import
5089 /// LL | use foo::bar as other_bar;
5090 /// | ^^^^^^^^^^^^^^^^^^^^^
5092 fn add_suggestion_for_rename_of_use(
5094 err
: &mut DiagnosticBuilder
<'_
>,
5096 directive
: &ImportDirective
<'_
>,
5099 let suggested_name
= if name
.as_str().chars().next().unwrap().is_uppercase() {
5100 format
!("Other{}", name
)
5102 format
!("other_{}", name
)
5105 let mut suggestion
= None
;
5106 match directive
.subclass
{
5107 ImportDirectiveSubclass
::SingleImport { type_ns_only: true, .. }
=>
5108 suggestion
= Some(format
!("self as {}", suggested_name
)),
5109 ImportDirectiveSubclass
::SingleImport { source, .. }
=> {
5110 if let Some(pos
) = source
.span
.hi().0.checked_sub(binding_span
.lo().0)
5111 .map(|pos
| pos
as usize) {
5112 if let Ok(snippet
) = self.session
.source_map()
5113 .span_to_snippet(binding_span
) {
5114 if pos
<= snippet
.len() {
5115 suggestion
= Some(format
!(
5119 if snippet
.ends_with(";") { ";" }
else { "" }
5125 ImportDirectiveSubclass
::ExternCrate { source, target, .. }
=>
5126 suggestion
= Some(format
!(
5127 "extern crate {} as {};",
5128 source
.unwrap_or(target
.name
),
5131 _
=> unreachable
!(),
5134 let rename_msg
= "you can use `as` to change the binding name of the import";
5135 if let Some(suggestion
) = suggestion
{
5136 err
.span_suggestion(
5140 Applicability
::MaybeIncorrect
,
5143 err
.span_label(binding_span
, rename_msg
);
5147 /// This function adds a suggestion to remove a unnecessary binding from an import that is
5148 /// nested. In the following example, this function will be invoked to remove the `a` binding
5149 /// in the second use statement:
5151 /// ```ignore (diagnostic)
5152 /// use issue_52891::a;
5153 /// use issue_52891::{d, a, e};
5156 /// The following suggestion will be added:
5158 /// ```ignore (diagnostic)
5159 /// use issue_52891::{d, a, e};
5160 /// ^-- help: remove unnecessary import
5163 /// If the nested use contains only one import then the suggestion will remove the entire
5166 /// It is expected that the directive provided is a nested import - this isn't checked by the
5167 /// function. If this invariant is not upheld, this function's behaviour will be unexpected
5168 /// as characters expected by span manipulations won't be present.
5169 fn add_suggestion_for_duplicate_nested_use(
5171 err
: &mut DiagnosticBuilder
<'_
>,
5172 directive
: &ImportDirective
<'_
>,
5175 assert
!(directive
.is_nested());
5176 let message
= "remove unnecessary import";
5178 // Two examples will be used to illustrate the span manipulations we're doing:
5180 // - Given `use issue_52891::{d, a, e};` where `a` is a duplicate then `binding_span` is
5181 // `a` and `directive.use_span` is `issue_52891::{d, a, e};`.
5182 // - Given `use issue_52891::{d, e, a};` where `a` is a duplicate then `binding_span` is
5183 // `a` and `directive.use_span` is `issue_52891::{d, e, a};`.
5185 let (found_closing_brace
, span
) = find_span_of_binding_until_next_binding(
5186 self.session
, binding_span
, directive
.use_span
,
5189 // If there was a closing brace then identify the span to remove any trailing commas from
5190 // previous imports.
5191 if found_closing_brace
{
5192 if let Some(span
) = extend_span_to_previous_binding(self.session
, span
) {
5193 err
.tool_only_span_suggestion(span
, message
, String
::new(),
5194 Applicability
::MaybeIncorrect
);
5196 // Remove the entire line if we cannot extend the span back, this indicates a
5197 // `issue_52891::{self}` case.
5198 err
.span_suggestion(directive
.use_span_with_attributes
, message
, String
::new(),
5199 Applicability
::MaybeIncorrect
);
5205 err
.span_suggestion(span
, message
, String
::new(), Applicability
::MachineApplicable
);
5208 fn extern_prelude_get(&mut self, ident
: Ident
, speculative
: bool
)
5209 -> Option
<&'a NameBinding
<'a
>> {
5210 if ident
.is_path_segment_keyword() {
5211 // Make sure `self`, `super` etc produce an error when passed to here.
5214 self.extern_prelude
.get(&ident
.modern()).cloned().and_then(|entry
| {
5215 if let Some(binding
) = entry
.extern_crate_item
{
5216 if !speculative
&& entry
.introduced_by_item
{
5217 self.record_use(ident
, TypeNS
, binding
, false);
5221 let crate_id
= if !speculative
{
5222 self.crate_loader
.process_path_extern(ident
.name
, ident
.span
)
5223 } else if let Some(crate_id
) =
5224 self.crate_loader
.maybe_process_path_extern(ident
.name
, ident
.span
) {
5229 let crate_root
= self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX }
);
5230 self.populate_module_if_necessary(&crate_root
);
5231 Some((crate_root
, ty
::Visibility
::Public
, DUMMY_SP
, Mark
::root())
5232 .to_name_binding(self.arenas
))
5238 fn is_self_type(path
: &[Segment
], namespace
: Namespace
) -> bool
{
5239 namespace
== TypeNS
&& path
.len() == 1 && path
[0].ident
.name
== kw
::SelfUpper
5242 fn is_self_value(path
: &[Segment
], namespace
: Namespace
) -> bool
{
5243 namespace
== ValueNS
&& path
.len() == 1 && path
[0].ident
.name
== kw
::SelfLower
5246 fn names_to_string(idents
: &[Ident
]) -> String
{
5247 let mut result
= String
::new();
5248 for (i
, ident
) in idents
.iter()
5249 .filter(|ident
| ident
.name
!= kw
::PathRoot
)
5252 result
.push_str("::");
5254 result
.push_str(&ident
.as_str());
5259 fn path_names_to_string(path
: &Path
) -> String
{
5260 names_to_string(&path
.segments
.iter()
5261 .map(|seg
| seg
.ident
)
5262 .collect
::<Vec
<_
>>())
5265 /// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
5266 fn import_candidate_to_enum_paths(suggestion
: &ImportSuggestion
) -> (String
, String
) {
5267 let variant_path
= &suggestion
.path
;
5268 let variant_path_string
= path_names_to_string(variant_path
);
5270 let path_len
= suggestion
.path
.segments
.len();
5271 let enum_path
= ast
::Path
{
5272 span
: suggestion
.path
.span
,
5273 segments
: suggestion
.path
.segments
[0..path_len
- 1].to_vec(),
5275 let enum_path_string
= path_names_to_string(&enum_path
);
5277 (variant_path_string
, enum_path_string
)
5280 /// When an entity with a given name is not available in scope, we search for
5281 /// entities with that name in all crates. This method allows outputting the
5282 /// results of this search in a programmer-friendly way
5283 fn show_candidates(err
: &mut DiagnosticBuilder
<'_
>,
5284 // This is `None` if all placement locations are inside expansions
5286 candidates
: &[ImportSuggestion
],
5290 // we want consistent results across executions, but candidates are produced
5291 // by iterating through a hash map, so make sure they are ordered:
5292 let mut path_strings
: Vec
<_
> =
5293 candidates
.into_iter().map(|c
| path_names_to_string(&c
.path
)).collect();
5294 path_strings
.sort();
5296 let better
= if better { "better " }
else { "" }
;
5297 let msg_diff
= match path_strings
.len() {
5298 1 => " is found in another module, you can import it",
5299 _
=> "s are found in other modules, you can import them",
5301 let msg
= format
!("possible {}candidate{} into scope", better
, msg_diff
);
5303 if let Some(span
) = span
{
5304 for candidate
in &mut path_strings
{
5305 // produce an additional newline to separate the new use statement
5306 // from the directly following item.
5307 let additional_newline
= if found_use
{
5312 *candidate
= format
!("use {};\n{}", candidate
, additional_newline
);
5315 err
.span_suggestions(
5318 path_strings
.into_iter(),
5319 Applicability
::Unspecified
,
5324 for candidate
in path_strings
{
5326 msg
.push_str(&candidate
);
5331 /// A somewhat inefficient routine to obtain the name of a module.
5332 fn module_to_string(module
: Module
<'_
>) -> Option
<String
> {
5333 let mut names
= Vec
::new();
5335 fn collect_mod(names
: &mut Vec
<Ident
>, module
: Module
<'_
>) {
5336 if let ModuleKind
::Def(.., name
) = module
.kind
{
5337 if let Some(parent
) = module
.parent
{
5338 names
.push(Ident
::with_empty_ctxt(name
));
5339 collect_mod(names
, parent
);
5342 // danger, shouldn't be ident?
5343 names
.push(Ident
::from_str("<opaque>"));
5344 collect_mod(names
, module
.parent
.unwrap());
5347 collect_mod(&mut names
, module
);
5349 if names
.is_empty() {
5352 Some(names_to_string(&names
.into_iter()
5354 .collect
::<Vec
<_
>>()))
5357 #[derive(Copy, Clone, Debug)]
5359 /// Do not issue the lint.
5362 /// This lint applies to some arbitrary path; e.g., `impl ::foo::Bar`.
5363 /// In this case, we can take the span of that path.
5366 /// This lint comes from a `use` statement. In this case, what we
5367 /// care about really is the *root* `use` statement; e.g., if we
5368 /// have nested things like `use a::{b, c}`, we care about the
5370 UsePath { root_id: NodeId, root_span: Span }
,
5372 /// This is the "trait item" from a fully qualified path. For example,
5373 /// we might be resolving `X::Y::Z` from a path like `<T as X::Y>::Z`.
5374 /// The `path_span` is the span of the to the trait itself (`X::Y`).
5375 QPathTrait { qpath_id: NodeId, qpath_span: Span }
,
5379 fn node_id(&self) -> Option
<NodeId
> {
5381 CrateLint
::No
=> None
,
5382 CrateLint
::SimplePath(id
) |
5383 CrateLint
::UsePath { root_id: id, .. }
|
5384 CrateLint
::QPathTrait { qpath_id: id, .. }
=> Some(id
),
5389 __build_diagnostic_array
! { librustc_resolve, DIAGNOSTICS }