use RibKind::*;
use crate::{path_names_to_string, BindingError, CrateLint, LexicalScopeBinding};
use crate::{Module, ModuleOrUniformRoot, ParentScope, PathResult};
use crate::{ResolutionError, Resolver, Segment, UseError};
use rustc_ast::ptr::P;
use rustc_ast::visit::{self, AssocCtxt, FnCtxt, FnKind, Visitor};
use rustc_ast::*;
use rustc_ast::{unwrap_or, walk_list};
use rustc_ast_lowering::ResolverAstLowering;
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_errors::DiagnosticId;
use rustc_hir::def::Namespace::{self, *};
use rustc_hir::def::{self, CtorKind, DefKind, PartialRes, PerNS};
use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
use rustc_hir::TraitCandidate;
use rustc_middle::{bug, span_bug};
use rustc_session::lint;
use rustc_span::symbol::{kw, sym, Ident, Symbol};
use rustc_span::Span;
use smallvec::{smallvec, SmallVec};
use rustc_span::source_map::{respan, Spanned};
use std::collections::BTreeSet;
use std::mem::{replace, take};
use tracing::debug;
mod diagnostics;
crate mod lifetimes;
type Res = def::Res<NodeId>;
type IdentMap<T> = FxHashMap<Ident, T>;
type BindingMap = IdentMap<BindingInfo>;
#[derive(Copy, Clone, Debug)]
struct BindingInfo {
span: Span,
binding_mode: BindingMode,
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum PatternSource {
Match,
Let,
For,
FnParam,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum IsRepeatExpr {
No,
Yes,
}
impl PatternSource {
fn descr(self) -> &'static str {
match self {
PatternSource::Match => "match binding",
PatternSource::Let => "let binding",
PatternSource::For => "for binding",
PatternSource::FnParam => "function parameter",
}
}
}
#[derive(PartialEq)]
enum PatBoundCtx {
Product,
Or,
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
crate enum HasGenericParams {
Yes,
No,
}
#[derive(Copy, Clone, Debug)]
crate enum RibKind<'a> {
NormalRibKind,
AssocItemRibKind,
ClosureOrAsyncRibKind,
FnItemRibKind,
ItemRibKind(HasGenericParams),
ConstantItemRibKind(bool),
ModuleRibKind(Module<'a>),
MacroDefinition(DefId),
ForwardTyParamBanRibKind,
ConstParamTyRibKind,
}
impl RibKind<'_> {
crate fn contains_params(&self) -> bool {
match self {
NormalRibKind
| ClosureOrAsyncRibKind
| FnItemRibKind
| ConstantItemRibKind(_)
| ModuleRibKind(_)
| MacroDefinition(_)
| ConstParamTyRibKind => false,
AssocItemRibKind | ItemRibKind(_) | ForwardTyParamBanRibKind => true,
}
}
}
#[derive(Debug)]
crate struct Rib<'a, R = Res> {
pub bindings: IdentMap<R>,
pub kind: RibKind<'a>,
}
impl<'a, R> Rib<'a, R> {
fn new(kind: RibKind<'a>) -> Rib<'a, R> {
Rib { bindings: Default::default(), kind }
}
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
crate enum AliasPossibility {
No,
Maybe,
}
#[derive(Copy, Clone, Debug)]
crate enum PathSource<'a> {
Type,
Trait(AliasPossibility),
Expr(Option<&'a Expr>),
Pat,
Struct,
TupleStruct(Span, &'a [Span]),
TraitItem(Namespace),
}
impl<'a> PathSource<'a> {
fn namespace(self) -> Namespace {
match self {
PathSource::Type | PathSource::Trait(_) | PathSource::Struct => TypeNS,
PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct(..) => ValueNS,
PathSource::TraitItem(ns) => ns,
}
}
fn defer_to_typeck(self) -> bool {
match self {
PathSource::Type
| PathSource::Expr(..)
| PathSource::Pat
| PathSource::Struct
| PathSource::TupleStruct(..) => true,
PathSource::Trait(_) | PathSource::TraitItem(..) => false,
}
}
fn descr_expected(self) -> &'static str {
match &self {
PathSource::Type => "type",
PathSource::Trait(_) => "trait",
PathSource::Pat => "unit struct, unit variant or constant",
PathSource::Struct => "struct, variant or union type",
PathSource::TupleStruct(..) => "tuple struct or tuple variant",
PathSource::TraitItem(ns) => match ns {
TypeNS => "associated type",
ValueNS => "method or associated constant",
MacroNS => bug!("associated macro"),
},
PathSource::Expr(parent) => match parent.as_ref().map(|p| &p.kind) {
Some(ExprKind::Call(call_expr, _)) => match &call_expr.kind {
ExprKind::Path(_, path) => {
let mut msg = "function";
if let Some(segment) = path.segments.iter().last() {
if let Some(c) = segment.ident.to_string().chars().next() {
if c.is_uppercase() {
msg = "function, tuple struct or tuple variant";
}
}
}
msg
}
_ => "function",
},
_ => "value",
},
}
}
fn is_call(self) -> bool {
matches!(self, PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. })))
}
crate fn is_expected(self, res: Res) -> bool {
match self {
PathSource::Type => matches!(res, Res::Def(
DefKind::Struct
| DefKind::Union
| DefKind::Enum
| DefKind::Trait
| DefKind::TraitAlias
| DefKind::TyAlias
| DefKind::AssocTy
| DefKind::TyParam
| DefKind::OpaqueTy
| DefKind::ForeignTy,
_,
)
| Res::PrimTy(..)
| Res::SelfTy(..)),
PathSource::Trait(AliasPossibility::No) => matches!(res, Res::Def(DefKind::Trait, _)),
PathSource::Trait(AliasPossibility::Maybe) => {
matches!(res, Res::Def(DefKind::Trait | DefKind::TraitAlias, _))
}
PathSource::Expr(..) => matches!(res, Res::Def(
DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn)
| DefKind::Const
| DefKind::Static
| DefKind::Fn
| DefKind::AssocFn
| DefKind::AssocConst
| DefKind::ConstParam,
_,
)
| Res::Local(..)
| Res::SelfCtor(..)),
PathSource::Pat => matches!(res, Res::Def(
DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::AssocConst,
_,
)
| Res::SelfCtor(..)),
PathSource::TupleStruct(..) => res.expected_in_tuple_struct_pat(),
PathSource::Struct => matches!(res, Res::Def(
DefKind::Struct
| DefKind::Union
| DefKind::Variant
| DefKind::TyAlias
| DefKind::AssocTy,
_,
)
| Res::SelfTy(..)),
PathSource::TraitItem(ns) => match res {
Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) if ns == ValueNS => true,
Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
_ => false,
},
}
}
fn error_code(self, has_unexpected_resolution: bool) -> DiagnosticId {
use rustc_errors::error_code;
match (self, has_unexpected_resolution) {
(PathSource::Trait(_), true) => error_code!(E0404),
(PathSource::Trait(_), false) => error_code!(E0405),
(PathSource::Type, true) => error_code!(E0573),
(PathSource::Type, false) => error_code!(E0412),
(PathSource::Struct, true) => error_code!(E0574),
(PathSource::Struct, false) => error_code!(E0422),
(PathSource::Expr(..), true) => error_code!(E0423),
(PathSource::Expr(..), false) => error_code!(E0425),
(PathSource::Pat | PathSource::TupleStruct(..), true) => error_code!(E0532),
(PathSource::Pat | PathSource::TupleStruct(..), false) => error_code!(E0531),
(PathSource::TraitItem(..), true) => error_code!(E0575),
(PathSource::TraitItem(..), false) => error_code!(E0576),
}
}
}
#[derive(Default)]
struct DiagnosticMetadata<'ast> {
current_trait_assoc_items: Option<&'ast [P<AssocItem>]>,
current_self_type: Option<Ty>,
current_self_item: Option<NodeId>,
current_item: Option<&'ast Item>,
currently_processing_generics: bool,
current_function: Option<(FnKind<'ast>, Span)>,
unused_labels: FxHashMap<NodeId, Span>,
current_type_ascription: Vec<Span>,
current_let_binding: Option<(Span, Option<Span>, Option<Span>)>,
in_if_condition: Option<&'ast Expr>,
current_trait_object: Option<&'ast [ast::GenericBound]>,
current_where_predicate: Option<&'ast WherePredicate>,
}
struct LateResolutionVisitor<'a, 'b, 'ast> {
r: &'b mut Resolver<'a>,
parent_scope: ParentScope<'a>,
ribs: PerNS<Vec<Rib<'a>>>,
label_ribs: Vec<Rib<'a, NodeId>>,
current_trait_ref: Option<(Module<'a>, TraitRef)>,
diagnostic_metadata: DiagnosticMetadata<'ast>,
in_func_body: bool,
}
impl<'a: 'ast, 'ast> Visitor<'ast> for LateResolutionVisitor<'a, '_, 'ast> {
fn visit_item(&mut self, item: &'ast Item) {
let prev = replace(&mut self.diagnostic_metadata.current_item, Some(item));
let old_ignore = replace(&mut self.in_func_body, false);
self.resolve_item(item);
self.in_func_body = old_ignore;
self.diagnostic_metadata.current_item = prev;
}
fn visit_arm(&mut self, arm: &'ast Arm) {
self.resolve_arm(arm);
}
fn visit_block(&mut self, block: &'ast Block) {
self.resolve_block(block);
}
fn visit_anon_const(&mut self, constant: &'ast AnonConst) {
self.resolve_anon_const(constant, IsRepeatExpr::No);
}
fn visit_expr(&mut self, expr: &'ast Expr) {
self.resolve_expr(expr, None);
}
fn visit_local(&mut self, local: &'ast Local) {
let local_spans = match local.pat.kind {
PatKind::Wild => None,
_ => Some((
local.pat.span,
local.ty.as_ref().map(|ty| ty.span),
local.init.as_ref().map(|init| init.span),
)),
};
let original = replace(&mut self.diagnostic_metadata.current_let_binding, local_spans);
self.resolve_local(local);
self.diagnostic_metadata.current_let_binding = original;
}
fn visit_ty(&mut self, ty: &'ast Ty) {
let prev = self.diagnostic_metadata.current_trait_object;
match ty.kind {
TyKind::Path(ref qself, ref path) => {
self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
}
TyKind::ImplicitSelf => {
let self_ty = Ident::with_dummy_span(kw::SelfUpper);
let res = self
.resolve_ident_in_lexical_scope(self_ty, TypeNS, Some(ty.id), ty.span)
.map_or(Res::Err, |d| d.res());
self.r.record_partial_res(ty.id, PartialRes::new(res));
}
TyKind::TraitObject(ref bounds, ..) => {
self.diagnostic_metadata.current_trait_object = Some(&bounds[..]);
}
_ => (),
}
visit::walk_ty(self, ty);
self.diagnostic_metadata.current_trait_object = prev;
}
fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef, m: &'ast TraitBoundModifier) {
self.smart_resolve_path(
tref.trait_ref.ref_id,
None,
&tref.trait_ref.path,
PathSource::Trait(AliasPossibility::Maybe),
);
visit::walk_poly_trait_ref(self, tref, m);
}
fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
match foreign_item.kind {
ForeignItemKind::Fn(_, _, ref generics, _)
| ForeignItemKind::TyAlias(_, ref generics, ..) => {
self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
visit::walk_foreign_item(this, foreign_item);
});
}
ForeignItemKind::Static(..) => {
self.with_item_rib(HasGenericParams::No, |this| {
visit::walk_foreign_item(this, foreign_item);
});
}
ForeignItemKind::MacCall(..) => {
visit::walk_foreign_item(self, foreign_item);
}
}
}
fn visit_fn(&mut self, fn_kind: FnKind<'ast>, sp: Span, _: NodeId) {
let rib_kind = match fn_kind {
FnKind::Fn(.., None) => return visit::walk_fn(self, fn_kind, sp),
FnKind::Fn(FnCtxt::Free | FnCtxt::Foreign, ..) => FnItemRibKind,
FnKind::Fn(FnCtxt::Assoc(_), ..) => NormalRibKind,
FnKind::Closure(..) => ClosureOrAsyncRibKind,
};
let previous_value = self.diagnostic_metadata.current_function;
if matches!(fn_kind, FnKind::Fn(..)) {
self.diagnostic_metadata.current_function = Some((fn_kind, sp));
}
debug!("(resolving function) entering function");
let declaration = fn_kind.decl();
self.with_rib(ValueNS, rib_kind, |this| {
this.with_label_rib(rib_kind, |this| {
this.resolve_params(&declaration.inputs);
visit::walk_fn_ret_ty(this, &declaration.output);
let previous_state = replace(&mut this.in_func_body, true);
match fn_kind {
FnKind::Fn(.., body) => walk_list!(this, visit_block, body),
FnKind::Closure(_, body) => this.visit_expr(body),
};
debug!("(resolving function) leaving function");
this.in_func_body = previous_state;
})
});
self.diagnostic_metadata.current_function = previous_value;
}
fn visit_generics(&mut self, generics: &'ast Generics) {
let mut default_ban_rib = Rib::new(ForwardTyParamBanRibKind);
let mut found_default = false;
default_ban_rib.bindings.extend(generics.params.iter().filter_map(
|param| match param.kind {
GenericParamKind::Const { .. } | GenericParamKind::Lifetime { .. } => None,
GenericParamKind::Type { ref default, .. } => {
found_default |= default.is_some();
found_default.then_some((Ident::with_dummy_span(param.ident.name), Res::Err))
}
},
));
if self.diagnostic_metadata.current_self_item.is_some() {
default_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
}
for param in &generics.params {
match param.kind {
GenericParamKind::Lifetime => self.visit_generic_param(param),
GenericParamKind::Type { ref default } => {
for bound in ¶m.bounds {
self.visit_param_bound(bound);
}
if let Some(ref ty) = default {
self.ribs[TypeNS].push(default_ban_rib);
self.with_rib(ValueNS, ForwardTyParamBanRibKind, |this| {
this.visit_ty(ty);
});
default_ban_rib = self.ribs[TypeNS].pop().unwrap();
}
default_ban_rib.bindings.remove(&Ident::with_dummy_span(param.ident.name));
}
GenericParamKind::Const { ref ty, kw_span: _ } => {
for bound in ¶m.bounds {
self.visit_param_bound(bound);
}
self.ribs[TypeNS].push(Rib::new(ConstParamTyRibKind));
self.ribs[ValueNS].push(Rib::new(ConstParamTyRibKind));
self.visit_ty(ty);
self.ribs[TypeNS].pop().unwrap();
self.ribs[ValueNS].pop().unwrap();
}
}
}
for p in &generics.where_clause.predicates {
self.visit_where_predicate(p);
}
}
fn visit_generic_arg(&mut self, arg: &'ast GenericArg) {
debug!("visit_generic_arg({:?})", arg);
let prev = replace(&mut self.diagnostic_metadata.currently_processing_generics, true);
match arg {
GenericArg::Type(ref ty) => {
if let TyKind::Path(ref qself, ref path) = ty.kind {
if path.segments.len() == 1 && path.segments[0].args.is_none() {
let mut check_ns = |ns| {
self.resolve_ident_in_lexical_scope(
path.segments[0].ident,
ns,
None,
path.span,
)
.is_some()
};
if !check_ns(TypeNS) && check_ns(ValueNS) {
self.with_constant_rib(IsRepeatExpr::No, true, |this| {
this.smart_resolve_path(
ty.id,
qself.as_ref(),
path,
PathSource::Expr(None),
);
if let Some(ref qself) = *qself {
this.visit_ty(&qself.ty);
}
this.visit_path(path, ty.id);
});
self.diagnostic_metadata.currently_processing_generics = prev;
return;
}
}
}
self.visit_ty(ty);
}
GenericArg::Lifetime(lt) => self.visit_lifetime(lt),
GenericArg::Const(ct) => self.visit_anon_const(ct),
}
self.diagnostic_metadata.currently_processing_generics = prev;
}
fn visit_where_predicate(&mut self, p: &'ast WherePredicate) {
debug!("visit_where_predicate {:?}", p);
let previous_value =
replace(&mut self.diagnostic_metadata.current_where_predicate, Some(p));
visit::walk_where_predicate(self, p);
self.diagnostic_metadata.current_where_predicate = previous_value;
}
}
impl<'a: 'ast, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> {
fn new(resolver: &'b mut Resolver<'a>) -> LateResolutionVisitor<'a, 'b, 'ast> {
let graph_root = resolver.graph_root;
let parent_scope = ParentScope::module(graph_root, resolver);
let start_rib_kind = ModuleRibKind(graph_root);
LateResolutionVisitor {
r: resolver,
parent_scope,
ribs: PerNS {
value_ns: vec![Rib::new(start_rib_kind)],
type_ns: vec![Rib::new(start_rib_kind)],
macro_ns: vec![Rib::new(start_rib_kind)],
},
label_ribs: Vec::new(),
current_trait_ref: None,
diagnostic_metadata: DiagnosticMetadata::default(),
in_func_body: false,
}
}
fn resolve_ident_in_lexical_scope(
&mut self,
ident: Ident,
ns: Namespace,
record_used_id: Option<NodeId>,
path_span: Span,
) -> Option<LexicalScopeBinding<'a>> {
self.r.resolve_ident_in_lexical_scope(
ident,
ns,
&self.parent_scope,
record_used_id,
path_span,
&self.ribs[ns],
)
}
fn resolve_path(
&mut self,
path: &[Segment],
opt_ns: Option<Namespace>,
record_used: bool,
path_span: Span,
crate_lint: CrateLint,
) -> PathResult<'a> {
self.r.resolve_path_with_ribs(
path,
opt_ns,
&self.parent_scope,
record_used,
path_span,
crate_lint,
Some(&self.ribs),
)
}
fn with_rib<T>(
&mut self,
ns: Namespace,
kind: RibKind<'a>,
work: impl FnOnce(&mut Self) -> T,
) -> T {
self.ribs[ns].push(Rib::new(kind));
let ret = work(self);
self.ribs[ns].pop();
ret
}
fn with_scope<T>(&mut self, id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
let id = self.r.local_def_id(id);
let module = self.r.module_map.get(&id).cloned();
if let Some(module) = module {
let orig_module = replace(&mut self.parent_scope.module, module);
self.with_rib(ValueNS, ModuleRibKind(module), |this| {
this.with_rib(TypeNS, ModuleRibKind(module), |this| {
let ret = f(this);
this.parent_scope.module = orig_module;
ret
})
})
} else {
f(self)
}
}
fn resolve_label(&self, mut label: Ident) -> Option<NodeId> {
let mut suggestion = None;
let original_span = label.span;
for i in (0..self.label_ribs.len()).rev() {
let rib = &self.label_ribs[i];
if let MacroDefinition(def) = rib.kind {
if def == self.r.macro_def(label.span.ctxt()) {
label.span.remove_mark();
}
}
let ident = label.normalize_to_macro_rules();
if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
return if self.is_label_valid_from_rib(i) {
Some(*id)
} else {
self.report_error(
original_span,
ResolutionError::UnreachableLabel {
name: label.name,
definition_span: ident.span,
suggestion,
},
);
None
};
}
suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
}
self.report_error(
original_span,
ResolutionError::UndeclaredLabel { name: label.name, suggestion },
);
None
}
fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
let ribs = &self.label_ribs[rib_index + 1..];
for rib in ribs {
match rib.kind {
NormalRibKind | MacroDefinition(..) => {
}
AssocItemRibKind
| ClosureOrAsyncRibKind
| FnItemRibKind
| ItemRibKind(..)
| ConstantItemRibKind(_)
| ModuleRibKind(..)
| ForwardTyParamBanRibKind
| ConstParamTyRibKind => {
return false;
}
}
}
true
}
fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
debug!("resolve_adt");
self.with_current_self_item(item, |this| {
this.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
let item_def_id = this.r.local_def_id(item.id).to_def_id();
this.with_self_rib(Res::SelfTy(None, Some((item_def_id, false))), |this| {
visit::walk_item(this, item);
});
});
});
}
fn future_proof_import(&mut self, use_tree: &UseTree) {
let segments = &use_tree.prefix.segments;
if !segments.is_empty() {
let ident = segments[0].ident;
if ident.is_path_segment_keyword() || ident.span.rust_2015() {
return;
}
let nss = match use_tree.kind {
UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
_ => &[TypeNS],
};
let report_error = |this: &Self, ns| {
let what = if ns == TypeNS { "type parameters" } else { "local variables" };
if this.should_report_errs() {
this.r
.session
.span_err(ident.span, &format!("imports cannot refer to {}", what));
}
};
for &ns in nss {
match self.resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span) {
Some(LexicalScopeBinding::Res(..)) => {
report_error(self, ns);
}
Some(LexicalScopeBinding::Item(binding)) => {
let orig_unusable_binding =
replace(&mut self.r.unusable_binding, Some(binding));
if let Some(LexicalScopeBinding::Res(..)) = self
.resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span)
{
report_error(self, ns);
}
self.r.unusable_binding = orig_unusable_binding;
}
None => {}
}
}
} else if let UseTreeKind::Nested(use_trees) = &use_tree.kind {
for (use_tree, _) in use_trees {
self.future_proof_import(use_tree);
}
}
}
fn resolve_item(&mut self, item: &'ast Item) {
let name = item.ident.name;
debug!("(resolving item) resolving {} ({:?})", name, item.kind);
match item.kind {
ItemKind::TyAlias(_, ref generics, _, _) | ItemKind::Fn(_, _, ref generics, _) => {
self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
visit::walk_item(this, item)
});
}
ItemKind::Enum(_, ref generics)
| ItemKind::Struct(_, ref generics)
| ItemKind::Union(_, ref generics) => {
self.resolve_adt(item, generics);
}
ItemKind::Impl {
ref generics,
ref of_trait,
ref self_ty,
items: ref impl_items,
..
} => {
self.resolve_implementation(generics, of_trait, &self_ty, item.id, impl_items);
}
ItemKind::Trait(.., ref generics, ref bounds, ref trait_items) => {
self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
let local_def_id = this.r.local_def_id(item.id).to_def_id();
this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
this.visit_generics(generics);
walk_list!(this, visit_param_bound, bounds);
let walk_assoc_item = |this: &mut Self, generics, item| {
this.with_generic_param_rib(generics, AssocItemRibKind, |this| {
visit::walk_assoc_item(this, item, AssocCtxt::Trait)
});
};
for item in trait_items {
this.with_trait_items(trait_items, |this| {
match &item.kind {
AssocItemKind::Const(_, ty, default) => {
this.visit_ty(ty);
if let Some(expr) = default {
this.with_constant_rib(
IsRepeatExpr::No,
true,
|this| this.visit_expr(expr),
);
}
}
AssocItemKind::Fn(_, _, generics, _) => {
walk_assoc_item(this, generics, item);
}
AssocItemKind::TyAlias(_, generics, _, _) => {
walk_assoc_item(this, generics, item);
}
AssocItemKind::MacCall(_) => {
panic!("unexpanded macro in resolve!")
}
};
});
}
});
});
}
ItemKind::TraitAlias(ref generics, ref bounds) => {
self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
let local_def_id = this.r.local_def_id(item.id).to_def_id();
this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
this.visit_generics(generics);
walk_list!(this, visit_param_bound, bounds);
});
});
}
ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
self.with_scope(item.id, |this| {
visit::walk_item(this, item);
});
}
ItemKind::Static(ref ty, _, ref expr) | ItemKind::Const(_, ref ty, ref expr) => {
debug!("resolve_item ItemKind::Const");
self.with_item_rib(HasGenericParams::No, |this| {
this.visit_ty(ty);
if let Some(expr) = expr {
this.with_constant_rib(IsRepeatExpr::No, true, |this| {
this.visit_expr(expr)
});
}
});
}
ItemKind::Use(ref use_tree) => {
self.future_proof_import(use_tree);
}
ItemKind::ExternCrate(..) | ItemKind::MacroDef(..) | ItemKind::GlobalAsm(..) => {
}
ItemKind::MacCall(_) => panic!("unexpanded macro in resolve!"),
}
}
fn with_generic_param_rib<'c, F>(&'c mut self, generics: &'c Generics, kind: RibKind<'a>, f: F)
where
F: FnOnce(&mut Self),
{
debug!("with_generic_param_rib");
let mut function_type_rib = Rib::new(kind);
let mut function_value_rib = Rib::new(kind);
let mut seen_bindings = FxHashMap::default();
if let AssocItemRibKind = kind {
let mut add_bindings_for_ns = |ns| {
let parent_rib = self.ribs[ns]
.iter()
.rfind(|r| matches!(r.kind, ItemRibKind(_)))
.expect("associated item outside of an item");
seen_bindings
.extend(parent_rib.bindings.iter().map(|(ident, _)| (*ident, ident.span)));
};
add_bindings_for_ns(ValueNS);
add_bindings_for_ns(TypeNS);
}
for param in &generics.params {
if let GenericParamKind::Lifetime { .. } = param.kind {
continue;
}
let def_kind = match param.kind {
GenericParamKind::Type { .. } => DefKind::TyParam,
GenericParamKind::Const { .. } => DefKind::ConstParam,
_ => unreachable!(),
};
let ident = param.ident.normalize_to_macros_2_0();
debug!("with_generic_param_rib: {}", param.id);
if seen_bindings.contains_key(&ident) {
let span = seen_bindings.get(&ident).unwrap();
let err = ResolutionError::NameAlreadyUsedInParameterList(ident.name, *span);
self.report_error(param.ident.span, err);
}
seen_bindings.entry(ident).or_insert(param.ident.span);
let res = Res::Def(def_kind, self.r.local_def_id(param.id).to_def_id());
match param.kind {
GenericParamKind::Type { .. } => {
function_type_rib.bindings.insert(ident, res);
self.r.record_partial_res(param.id, PartialRes::new(res));
}
GenericParamKind::Const { .. } => {
function_value_rib.bindings.insert(ident, res);
self.r.record_partial_res(param.id, PartialRes::new(res));
}
_ => unreachable!(),
}
}
self.ribs[ValueNS].push(function_value_rib);
self.ribs[TypeNS].push(function_type_rib);
f(self);
self.ribs[TypeNS].pop();
self.ribs[ValueNS].pop();
}
fn with_label_rib(&mut self, kind: RibKind<'a>, f: impl FnOnce(&mut Self)) {
self.label_ribs.push(Rib::new(kind));
f(self);
self.label_ribs.pop();
}
fn with_item_rib(&mut self, has_generic_params: HasGenericParams, f: impl FnOnce(&mut Self)) {
let kind = ItemRibKind(has_generic_params);
self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
}
fn with_constant_rib(
&mut self,
is_repeat: IsRepeatExpr,
is_trivial: bool,
f: impl FnOnce(&mut Self),
) {
debug!("with_constant_rib: is_repeat={:?} is_trivial={}", is_repeat, is_trivial);
self.with_rib(ValueNS, ConstantItemRibKind(is_trivial), |this| {
this.with_rib(
TypeNS,
ConstantItemRibKind(is_repeat == IsRepeatExpr::Yes || is_trivial),
|this| {
this.with_label_rib(ConstantItemRibKind(is_trivial), f);
},
)
});
}
fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
let previous_value =
replace(&mut self.diagnostic_metadata.current_self_type, Some(self_type.clone()));
let result = f(self);
self.diagnostic_metadata.current_self_type = previous_value;
result
}
fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
let previous_value =
replace(&mut self.diagnostic_metadata.current_self_item, Some(self_item.id));
let result = f(self);
self.diagnostic_metadata.current_self_item = previous_value;
result
}
fn with_trait_items<T>(
&mut self,
trait_items: &'ast Vec<P<AssocItem>>,
f: impl FnOnce(&mut Self) -> T,
) -> T {
let trait_assoc_items = replace(
&mut self.diagnostic_metadata.current_trait_assoc_items,
Some(&trait_items[..]),
);
let result = f(self);
self.diagnostic_metadata.current_trait_assoc_items = trait_assoc_items;
result
}
fn with_optional_trait_ref<T>(
&mut self,
opt_trait_ref: Option<&TraitRef>,
f: impl FnOnce(&mut Self, Option<DefId>) -> T,
) -> T {
let mut new_val = None;
let mut new_id = None;
if let Some(trait_ref) = opt_trait_ref {
let path: Vec<_> = Segment::from_path(&trait_ref.path);
let res = self.smart_resolve_path_fragment(
trait_ref.ref_id,
None,
&path,
trait_ref.path.span,
PathSource::Trait(AliasPossibility::No),
CrateLint::SimplePath(trait_ref.ref_id),
);
let res = res.base_res();
if res != Res::Err {
new_id = Some(res.def_id());
let span = trait_ref.path.span;
if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = self.resolve_path(
&path,
Some(TypeNS),
false,
span,
CrateLint::SimplePath(trait_ref.ref_id),
) {
new_val = Some((module, trait_ref.clone()));
}
}
}
let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
let result = f(self, new_id);
self.current_trait_ref = original_trait_ref;
result
}
fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
let mut self_type_rib = Rib::new(NormalRibKind);
self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
self.ribs[ns].push(self_type_rib);
f(self);
self.ribs[ns].pop();
}
fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
self.with_self_rib_ns(TypeNS, self_res, f)
}
fn resolve_implementation(
&mut self,
generics: &'ast Generics,
opt_trait_reference: &'ast Option<TraitRef>,
self_type: &'ast Ty,
item_id: NodeId,
impl_items: &'ast [P<AssocItem>],
) {
debug!("resolve_implementation");
self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
this.with_self_rib(Res::SelfTy(None, None), |this| {
this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
let item_def_id = this.r.local_def_id(item_id).to_def_id();
this.with_self_rib(Res::SelfTy(trait_id, Some((item_def_id, false))), |this| {
if let Some(trait_ref) = opt_trait_reference.as_ref() {
visit::walk_trait_ref(this, trait_ref);
}
this.visit_ty(self_type);
this.visit_generics(generics);
this.with_current_self_type(self_type, |this| {
this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
for item in impl_items {
use crate::ResolutionError::*;
match &item.kind {
AssocItemKind::Const(_default, _ty, _expr) => {
debug!("resolve_implementation AssocItemKind::Const",);
this.check_trait_item(
item.ident,
ValueNS,
item.span,
|n, s| ConstNotMemberOfTrait(n, s),
);
this.with_constant_rib(
IsRepeatExpr::No,
true,
|this| {
visit::walk_assoc_item(
this,
item,
AssocCtxt::Impl,
)
},
);
}
AssocItemKind::Fn(_, _, generics, _) => {
this.with_generic_param_rib(
generics,
AssocItemRibKind,
|this| {
this.check_trait_item(
item.ident,
ValueNS,
item.span,
|n, s| MethodNotMemberOfTrait(n, s),
);
visit::walk_assoc_item(
this,
item,
AssocCtxt::Impl,
)
},
);
}
AssocItemKind::TyAlias(_, generics, _, _) => {
this.with_generic_param_rib(
generics,
AssocItemRibKind,
|this| {
this.check_trait_item(
item.ident,
TypeNS,
item.span,
|n, s| TypeNotMemberOfTrait(n, s),
);
visit::walk_assoc_item(
this,
item,
AssocCtxt::Impl,
)
},
);
}
AssocItemKind::MacCall(_) => {
panic!("unexpanded macro in resolve!")
}
}
}
});
});
});
});
});
});
}
fn check_trait_item<F>(&mut self, ident: Ident, ns: Namespace, span: Span, err: F)
where
F: FnOnce(Symbol, &str) -> ResolutionError<'_>,
{
if let Some((module, _)) = self.current_trait_ref {
if self
.r
.resolve_ident_in_module(
ModuleOrUniformRoot::Module(module),
ident,
ns,
&self.parent_scope,
false,
span,
)
.is_err()
{
let path = &self.current_trait_ref.as_ref().unwrap().1.path;
self.report_error(span, err(ident.name, &path_names_to_string(path)));
}
}
}
fn resolve_params(&mut self, params: &'ast [Param]) {
let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
for Param { pat, ty, .. } in params {
self.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
self.visit_ty(ty);
debug!("(resolving function / closure) recorded parameter");
}
}
fn resolve_local(&mut self, local: &'ast Local) {
debug!("resolving local ({:?})", local);
walk_list!(self, visit_ty, &local.ty);
walk_list!(self, visit_expr, &local.init);
self.resolve_pattern_top(&local.pat, PatternSource::Let);
}
fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
let mut binding_map = FxHashMap::default();
pat.walk(&mut |pat| {
match pat.kind {
PatKind::Ident(binding_mode, ident, ref sub_pat)
if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
{
binding_map.insert(ident, BindingInfo { span: ident.span, binding_mode });
}
PatKind::Or(ref ps) => {
for bm in self.check_consistent_bindings(ps) {
binding_map.extend(bm);
}
return false;
}
_ => {}
}
true
});
binding_map
}
fn is_base_res_local(&self, nid: NodeId) -> bool {
matches!(self.r.partial_res_map.get(&nid).map(|res| res.base_res()), Some(Res::Local(..)))
}
fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) -> Vec<BindingMap> {
let mut missing_vars = FxHashMap::default();
let mut inconsistent_vars = FxHashMap::default();
let maps = pats.iter().map(|pat| self.binding_mode_map(pat)).collect::<Vec<_>>();
for (map_outer, pat_outer) in pats.iter().enumerate().map(|(idx, pat)| (&maps[idx], pat)) {
let inners = pats
.iter()
.enumerate()
.filter(|(_, pat)| pat.id != pat_outer.id)
.flat_map(|(idx, _)| maps[idx].iter())
.map(|(key, binding)| (key.name, map_outer.get(&key), binding));
for (name, info, &binding_inner) in inners {
match info {
None => {
let binding_error =
missing_vars.entry(name).or_insert_with(|| BindingError {
name,
origin: BTreeSet::new(),
target: BTreeSet::new(),
could_be_path: name.as_str().starts_with(char::is_uppercase),
});
binding_error.origin.insert(binding_inner.span);
binding_error.target.insert(pat_outer.span);
}
Some(binding_outer) => {
if binding_outer.binding_mode != binding_inner.binding_mode {
inconsistent_vars
.entry(name)
.or_insert((binding_inner.span, binding_outer.span));
}
}
}
}
}
let mut missing_vars = missing_vars.iter_mut().collect::<Vec<_>>();
missing_vars.sort_by_key(|(sym, _err)| sym.as_str());
for (name, mut v) in missing_vars {
if inconsistent_vars.contains_key(name) {
v.could_be_path = false;
}
self.report_error(
*v.origin.iter().next().unwrap(),
ResolutionError::VariableNotBoundInPattern(v),
);
}
let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
inconsistent_vars.sort();
for (name, v) in inconsistent_vars {
self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
}
maps
}
fn check_consistent_bindings_top(&mut self, pat: &'ast Pat) {
pat.walk(&mut |pat| match pat.kind {
PatKind::Or(ref ps) => {
self.check_consistent_bindings(ps);
false
}
_ => true,
})
}
fn resolve_arm(&mut self, arm: &'ast Arm) {
self.with_rib(ValueNS, NormalRibKind, |this| {
this.resolve_pattern_top(&arm.pat, PatternSource::Match);
walk_list!(this, visit_expr, &arm.guard);
this.visit_expr(&arm.body);
});
}
fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
self.resolve_pattern(pat, pat_src, &mut bindings);
}
fn resolve_pattern(
&mut self,
pat: &'ast Pat,
pat_src: PatternSource,
bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
) {
self.resolve_pattern_inner(pat, pat_src, bindings);
self.check_consistent_bindings_top(pat);
visit::walk_pat(self, pat);
}
fn resolve_pattern_inner(
&mut self,
pat: &Pat,
pat_src: PatternSource,
bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
) {
pat.walk(&mut |pat| {
debug!("resolve_pattern pat={:?} node={:?}", pat, pat.kind);
match pat.kind {
PatKind::Ident(bmode, ident, ref sub) => {
let has_sub = sub.is_some();
let res = self
.try_resolve_as_non_binding(pat_src, pat, bmode, ident, has_sub)
.unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
self.r.record_partial_res(pat.id, PartialRes::new(res));
}
PatKind::TupleStruct(ref path, ref sub_patterns) => {
self.smart_resolve_path(
pat.id,
None,
path,
PathSource::TupleStruct(
pat.span,
self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
),
);
}
PatKind::Path(ref qself, ref path) => {
self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
}
PatKind::Struct(ref path, ..) => {
self.smart_resolve_path(pat.id, None, path, PathSource::Struct);
}
PatKind::Or(ref ps) => {
bindings.push((PatBoundCtx::Or, Default::default()));
for p in ps {
bindings.push((PatBoundCtx::Product, Default::default()));
self.resolve_pattern_inner(p, pat_src, bindings);
let collected = bindings.pop().unwrap().1;
bindings.last_mut().unwrap().1.extend(collected);
}
let collected = bindings.pop().unwrap().1;
bindings.last_mut().unwrap().1.extend(collected);
return false;
}
_ => {}
}
true
});
}
fn fresh_binding(
&mut self,
ident: Ident,
pat_id: NodeId,
pat_src: PatternSource,
bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
) -> Res {
let ident = ident.normalize_to_macro_rules();
let mut bound_iter = bindings.iter().filter(|(_, set)| set.contains(&ident));
let already_bound_and = bound_iter.clone().any(|(ctx, _)| *ctx == PatBoundCtx::Product);
let already_bound_or = bound_iter.any(|(ctx, _)| *ctx == PatBoundCtx::Or);
if already_bound_and {
use ResolutionError::*;
let error = match pat_src {
PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
_ => IdentifierBoundMoreThanOnceInSamePattern,
};
self.report_error(ident.span, error(ident.name));
}
let ident_valid = ident.name != kw::Invalid;
if ident_valid {
bindings.last_mut().unwrap().1.insert(ident);
}
if already_bound_or {
self.innermost_rib_bindings(ValueNS)[&ident]
} else {
let res = Res::Local(pat_id);
if ident_valid {
self.innermost_rib_bindings(ValueNS).insert(ident, res);
}
res
}
}
fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut IdentMap<Res> {
&mut self.ribs[ns].last_mut().unwrap().bindings
}
fn try_resolve_as_non_binding(
&mut self,
pat_src: PatternSource,
pat: &Pat,
bm: BindingMode,
ident: Ident,
has_sub: bool,
) -> Option<Res> {
let is_syntactic_ambiguity = !has_sub && bm == BindingMode::ByValue(Mutability::Not);
let ls_binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, pat.span)?;
let (res, binding) = match ls_binding {
LexicalScopeBinding::Item(binding)
if is_syntactic_ambiguity && binding.is_ambiguity() =>
{
self.r.record_use(ident, ValueNS, binding, false);
return None;
}
LexicalScopeBinding::Item(binding) => (binding.res(), Some(binding)),
LexicalScopeBinding::Res(res) => (res, None),
};
match res {
Res::SelfCtor(_)
| Res::Def(
DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::ConstParam,
_,
) if is_syntactic_ambiguity => {
if let Some(binding) = binding {
self.r.record_use(ident, ValueNS, binding, false);
}
Some(res)
}
Res::Def(DefKind::Ctor(..) | DefKind::Const | DefKind::Static, _) => {
self.report_error(
ident.span,
ResolutionError::BindingShadowsSomethingUnacceptable(
pat_src.descr(),
ident.name,
binding.expect("no binding for a ctor or static"),
),
);
None
}
Res::Def(DefKind::Fn, _) | Res::Local(..) | Res::Err => {
None
}
_ => span_bug!(
ident.span,
"unexpected resolution for an identifier in pattern: {:?}",
res,
),
}
}
fn smart_resolve_path(
&mut self,
id: NodeId,
qself: Option<&QSelf>,
path: &Path,
source: PathSource<'ast>,
) {
self.smart_resolve_path_fragment(
id,
qself,
&Segment::from_path(path),
path.span,
source,
CrateLint::SimplePath(id),
);
}
fn smart_resolve_path_fragment(
&mut self,
id: NodeId,
qself: Option<&QSelf>,
path: &[Segment],
span: Span,
source: PathSource<'ast>,
crate_lint: CrateLint,
) -> PartialRes {
tracing::debug!(
"smart_resolve_path_fragment(id={:?},qself={:?},path={:?}",
id,
qself,
path
);
let ns = source.namespace();
let is_expected = &|res| source.is_expected(res);
let report_errors = |this: &mut Self, res: Option<Res>| {
if this.should_report_errs() {
let (err, candidates) = this.smart_resolve_report_errors(path, span, source, res);
let def_id = this.parent_scope.module.normal_ancestor_id;
let instead = res.is_some();
let suggestion =
if res.is_none() { this.report_missing_type_error(path) } else { None };
this.r.use_injections.push(UseError {
err,
candidates,
def_id,
instead,
suggestion,
});
}
PartialRes::new(Res::Err)
};
let report_errors_for_call = |this: &mut Self, parent_err: Spanned<ResolutionError<'a>>| {
if !source.is_call() {
return Some(parent_err);
}
let path = if let Some((_, path)) = path.split_last() {
path
} else {
return Some(parent_err);
};
let (mut err, candidates) =
this.smart_resolve_report_errors(path, span, PathSource::Type, None);
if candidates.is_empty() {
err.cancel();
return Some(parent_err);
}
let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
parent_err.cancel();
err.message = take(&mut parent_err.message);
err.code = take(&mut parent_err.code);
err.children = take(&mut parent_err.children);
drop(parent_err);
let def_id = this.parent_scope.module.normal_ancestor_id;
if this.should_report_errs() {
this.r.use_injections.push(UseError {
err,
candidates,
def_id,
instead: false,
suggestion: None,
});
} else {
err.cancel();
}
None
};
let partial_res = match self.resolve_qpath_anywhere(
id,
qself,
path,
ns,
span,
source.defer_to_typeck(),
crate_lint,
) {
Ok(Some(partial_res)) if partial_res.unresolved_segments() == 0 => {
if is_expected(partial_res.base_res()) || partial_res.base_res() == Res::Err {
partial_res
} else {
report_errors(self, Some(partial_res.base_res()))
}
}
Ok(Some(partial_res)) if source.defer_to_typeck() => {
if ns == ValueNS {
let item_name = path.last().unwrap().ident;
let traits = self.get_traits_containing_item(item_name, ns);
self.r.trait_map.insert(id, traits);
}
let mut std_path = vec![Segment::from_ident(Ident::with_dummy_span(sym::std))];
std_path.extend(path);
if self.r.primitive_type_table.primitive_types.contains_key(&path[0].ident.name) {
if let PathResult::Module(_) | PathResult::NonModule(_) =
self.resolve_path(&std_path, Some(ns), false, span, CrateLint::No)
{
let item_span =
path.iter().last().map(|segment| segment.ident.span).unwrap_or(span);
let mut hm = self.r.session.confused_type_with_std_module.borrow_mut();
hm.insert(item_span, span);
hm.insert(span, span);
}
}
partial_res
}
Err(err) => {
if let Some(err) = report_errors_for_call(self, err) {
self.report_error(err.span, err.node);
}
PartialRes::new(Res::Err)
}
_ => report_errors(self, None),
};
if let PathSource::TraitItem(..) = source {
} else {
self.r.record_partial_res(id, partial_res);
}
partial_res
}
fn self_type_is_available(&mut self, span: Span) -> bool {
let binding = self.resolve_ident_in_lexical_scope(
Ident::with_dummy_span(kw::SelfUpper),
TypeNS,
None,
span,
);
if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
}
fn self_value_is_available(&mut self, self_span: Span, path_span: Span) -> bool {
let ident = Ident::new(kw::SelfLower, self_span);
let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, path_span);
if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
}
fn report_error(&self, span: Span, resolution_error: ResolutionError<'_>) {
if self.should_report_errs() {
self.r.report_error(span, resolution_error);
}
}
#[inline]
fn should_report_errs(&self) -> bool {
!(self.r.session.opts.actually_rustdoc && self.in_func_body)
}
fn resolve_qpath_anywhere(
&mut self,
id: NodeId,
qself: Option<&QSelf>,
path: &[Segment],
primary_ns: Namespace,
span: Span,
defer_to_typeck: bool,
crate_lint: CrateLint,
) -> Result<Option<PartialRes>, Spanned<ResolutionError<'a>>> {
let mut fin_res = None;
for (i, ns) in [primary_ns, TypeNS, ValueNS].iter().cloned().enumerate() {
if i == 0 || ns != primary_ns {
match self.resolve_qpath(id, qself, path, ns, span, crate_lint)? {
Some(partial_res)
if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
{
return Ok(Some(partial_res));
}
partial_res => {
if fin_res.is_none() {
fin_res = partial_res
}
}
}
}
}
assert!(primary_ns != MacroNS);
if qself.is_none() {
let path_seg = |seg: &Segment| PathSegment::from_ident(seg.ident);
let path = Path { segments: path.iter().map(path_seg).collect(), span, tokens: None };
if let Ok((_, res)) =
self.r.resolve_macro_path(&path, None, &self.parent_scope, false, false)
{
return Ok(Some(PartialRes::new(res)));
}
}
Ok(fin_res)
}
fn resolve_qpath(
&mut self,
id: NodeId,
qself: Option<&QSelf>,
path: &[Segment],
ns: Namespace,
span: Span,
crate_lint: CrateLint,
) -> Result<Option<PartialRes>, Spanned<ResolutionError<'a>>> {
debug!(
"resolve_qpath(id={:?}, qself={:?}, path={:?}, ns={:?}, span={:?})",
id, qself, path, ns, span,
);
if let Some(qself) = qself {
if qself.position == 0 {
return Ok(Some(PartialRes::with_unresolved_segments(
Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX)),
path.len(),
)));
}
let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
let partial_res = self.smart_resolve_path_fragment(
id,
None,
&path[..=qself.position],
span,
PathSource::TraitItem(ns),
CrateLint::QPathTrait { qpath_id: id, qpath_span: qself.path_span },
);
return Ok(Some(PartialRes::with_unresolved_segments(
partial_res.base_res(),
partial_res.unresolved_segments() + path.len() - qself.position - 1,
)));
}
let result = match self.resolve_path(&path, Some(ns), true, span, crate_lint) {
PathResult::NonModule(path_res) => path_res,
PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
PartialRes::new(module.res().unwrap())
}
PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
if (ns == TypeNS || path.len() > 1)
&& self
.r
.primitive_type_table
.primitive_types
.contains_key(&path[0].ident.name) =>
{
let prim = self.r.primitive_type_table.primitive_types[&path[0].ident.name];
PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
}
PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
PartialRes::new(module.res().unwrap())
}
PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
return Err(respan(span, ResolutionError::FailedToResolve { label, suggestion }));
}
PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"),
};
if path.len() > 1
&& result.base_res() != Res::Err
&& path[0].ident.name != kw::PathRoot
&& path[0].ident.name != kw::DollarCrate
{
let unqualified_result = {
match self.resolve_path(
&[*path.last().unwrap()],
Some(ns),
false,
span,
CrateLint::No,
) {
PathResult::NonModule(path_res) => path_res.base_res(),
PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
module.res().unwrap()
}
_ => return Ok(Some(result)),
}
};
if result.base_res() == unqualified_result {
let lint = lint::builtin::UNUSED_QUALIFICATIONS;
self.r.lint_buffer.buffer_lint(lint, id, span, "unnecessary qualification")
}
}
Ok(Some(result))
}
fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
if let Some(label) = label {
if label.ident.as_str().as_bytes()[1] != b'_' {
self.diagnostic_metadata.unused_labels.insert(id, label.ident.span);
}
self.with_label_rib(NormalRibKind, |this| {
let ident = label.ident.normalize_to_macro_rules();
this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
f(this);
});
} else {
f(self);
}
}
fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
self.with_resolved_label(label, id, |this| this.visit_block(block));
}
fn resolve_block(&mut self, block: &'ast Block) {
debug!("(resolving block) entering block");
let orig_module = self.parent_scope.module;
let anonymous_module = self.r.block_map.get(&block.id).cloned();
let mut num_macro_definition_ribs = 0;
if let Some(anonymous_module) = anonymous_module {
debug!("(resolving block) found anonymous module, moving down");
self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
self.parent_scope.module = anonymous_module;
} else {
self.ribs[ValueNS].push(Rib::new(NormalRibKind));
}
for stmt in &block.stmts {
if let StmtKind::Item(ref item) = stmt.kind {
if let ItemKind::MacroDef(..) = item.kind {
num_macro_definition_ribs += 1;
let res = self.r.local_def_id(item.id).to_def_id();
self.ribs[ValueNS].push(Rib::new(MacroDefinition(res)));
self.label_ribs.push(Rib::new(MacroDefinition(res)));
}
}
self.visit_stmt(stmt);
}
self.parent_scope.module = orig_module;
for _ in 0..num_macro_definition_ribs {
self.ribs[ValueNS].pop();
self.label_ribs.pop();
}
self.ribs[ValueNS].pop();
if anonymous_module.is_some() {
self.ribs[TypeNS].pop();
}
debug!("(resolving block) leaving block");
}
fn resolve_anon_const(&mut self, constant: &'ast AnonConst, is_repeat: IsRepeatExpr) {
debug!("resolve_anon_const {:?} is_repeat: {:?}", constant, is_repeat);
self.with_constant_rib(
is_repeat,
constant.value.is_potential_trivial_const_param(),
|this| {
visit::walk_anon_const(this, constant);
},
);
}
fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
self.record_candidate_traits_for_expr_if_necessary(expr);
match expr.kind {
ExprKind::Path(ref qself, ref path) => {
self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
visit::walk_expr(self, expr);
}
ExprKind::Struct(ref path, ..) => {
self.smart_resolve_path(expr.id, None, path, PathSource::Struct);
visit::walk_expr(self, expr);
}
ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
if let Some(node_id) = self.resolve_label(label.ident) {
self.r.label_res_map.insert(expr.id, node_id);
self.diagnostic_metadata.unused_labels.remove(&node_id);
}
visit::walk_expr(self, expr);
}
ExprKind::Let(ref pat, ref scrutinee) => {
self.visit_expr(scrutinee);
self.resolve_pattern_top(pat, PatternSource::Let);
}
ExprKind::If(ref cond, ref then, ref opt_else) => {
self.with_rib(ValueNS, NormalRibKind, |this| {
let old = this.diagnostic_metadata.in_if_condition.replace(cond);
this.visit_expr(cond);
this.diagnostic_metadata.in_if_condition = old;
this.visit_block(then);
});
if let Some(expr) = opt_else {
self.visit_expr(expr);
}
}
ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
ExprKind::While(ref cond, ref block, label) => {
self.with_resolved_label(label, expr.id, |this| {
this.with_rib(ValueNS, NormalRibKind, |this| {
this.visit_expr(cond);
this.visit_block(block);
})
});
}
ExprKind::ForLoop(ref pat, ref iter_expr, ref block, label) => {
self.visit_expr(iter_expr);
self.with_rib(ValueNS, NormalRibKind, |this| {
this.resolve_pattern_top(pat, PatternSource::For);
this.resolve_labeled_block(label, expr.id, block);
});
}
ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
ExprKind::Field(ref subexpression, _) => {
self.resolve_expr(subexpression, Some(expr));
}
ExprKind::MethodCall(ref segment, ref arguments, _) => {
let mut arguments = arguments.iter();
self.resolve_expr(arguments.next().unwrap(), Some(expr));
for argument in arguments {
self.resolve_expr(argument, None);
}
self.visit_path_segment(expr.span, segment);
}
ExprKind::Call(ref callee, ref arguments) => {
self.resolve_expr(callee, Some(expr));
for argument in arguments {
self.resolve_expr(argument, None);
}
}
ExprKind::Type(ref type_expr, ref ty) => {
self.diagnostic_metadata
.current_type_ascription
.push(type_expr.span.between(ty.span));
visit::walk_expr(self, expr);
self.diagnostic_metadata.current_type_ascription.pop();
}
ExprKind::Closure(_, Async::Yes { .. }, _, ref fn_decl, ref body, _span) => {
self.with_rib(ValueNS, NormalRibKind, |this| {
this.with_label_rib(ClosureOrAsyncRibKind, |this| {
this.resolve_params(&fn_decl.inputs);
{
visit::walk_fn_ret_ty(this, &fn_decl.output);
this.visit_expr(body);
}
})
});
}
ExprKind::Async(..) | ExprKind::Closure(..) => {
self.with_label_rib(ClosureOrAsyncRibKind, |this| visit::walk_expr(this, expr));
}
ExprKind::Repeat(ref elem, ref ct) => {
self.visit_expr(elem);
self.resolve_anon_const(ct, IsRepeatExpr::Yes);
}
_ => {
visit::walk_expr(self, expr);
}
}
}
fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
match expr.kind {
ExprKind::Field(_, ident) => {
let traits = self.get_traits_containing_item(ident, ValueNS);
self.r.trait_map.insert(expr.id, traits);
}
ExprKind::MethodCall(ref segment, ..) => {
debug!("(recording candidate traits for expr) recording traits for {}", expr.id);
let traits = self.get_traits_containing_item(segment.ident, ValueNS);
self.r.trait_map.insert(expr.id, traits);
}
_ => {
}
}
}
fn get_traits_containing_item(
&mut self,
mut ident: Ident,
ns: Namespace,
) -> Vec<TraitCandidate> {
debug!("(getting traits containing item) looking for '{}'", ident.name);
let mut found_traits = Vec::new();
if let Some((module, _)) = self.current_trait_ref {
if self
.r
.resolve_ident_in_module(
ModuleOrUniformRoot::Module(module),
ident,
ns,
&self.parent_scope,
false,
module.span,
)
.is_ok()
{
let def_id = module.def_id().unwrap();
found_traits.push(TraitCandidate { def_id, import_ids: smallvec![] });
}
}
ident.span = ident.span.normalize_to_macros_2_0();
let mut search_module = self.parent_scope.module;
loop {
self.r.get_traits_in_module_containing_item(
ident,
ns,
search_module,
&mut found_traits,
&self.parent_scope,
);
search_module =
unwrap_or!(self.r.hygienic_lexical_parent(search_module, &mut ident.span), break);
}
if let Some(prelude) = self.r.prelude {
if !search_module.no_implicit_prelude {
self.r.get_traits_in_module_containing_item(
ident,
ns,
prelude,
&mut found_traits,
&self.parent_scope,
);
}
}
found_traits
}
}
impl<'a> Resolver<'a> {
pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
let mut late_resolution_visitor = LateResolutionVisitor::new(self);
visit::walk_crate(&mut late_resolution_visitor, krate);
for (id, span) in late_resolution_visitor.diagnostic_metadata.unused_labels.iter() {
self.lint_buffer.buffer_lint(lint::builtin::UNUSED_LABELS, *id, *span, "unused label");
}
}
}