1 //! "Late resolution" is the pass that resolves most of names in a crate beside imports and macros.
2 //! It runs when the crate is fully expanded and its module structure is fully built.
3 //! So it just walks through the crate and resolves all the expressions, types, etc.
5 //! If you wonder why there's no `early.rs`, that's because it's split into three files -
6 //! `build_reduced_graph.rs`, `macros.rs` and `resolve_imports.rs`.
10 use crate::{path_names_to_string, BindingError, CrateLint, LexicalScopeBinding};
11 use crate::{Module, ModuleOrUniformRoot, NameBindingKind, ParentScope, PathResult};
12 use crate::{ResolutionError, Resolver, Segment, UseError};
15 use rustc::{bug, lint, span_bug};
16 use rustc::hir::def::{self, PartialRes, DefKind, CtorKind, PerNS};
17 use rustc::hir::def::Namespace::{self, *};
18 use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX};
19 use rustc::hir::TraitCandidate;
20 use rustc::util::nodemap::{FxHashMap, FxHashSet};
21 use smallvec::{smallvec, SmallVec};
22 use syntax::{unwrap_or, walk_list};
25 use syntax::symbol::{kw, sym};
26 use syntax::util::lev_distance::find_best_match_for_name;
27 use syntax::visit::{self, Visitor, FnKind};
30 use std::collections::BTreeSet;
31 use std::mem::replace;
33 use rustc_error_codes::*;
37 type Res = def::Res<NodeId>;
39 type IdentMap<T> = FxHashMap<Ident, T>;
41 /// Map from the name in a pattern to its binding mode.
42 type BindingMap = IdentMap<BindingInfo>;
44 #[derive(Copy, Clone, Debug)]
47 binding_mode: BindingMode,
50 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
59 fn descr(self) -> &'static str {
61 PatternSource::Match => "match binding",
62 PatternSource::Let => "let binding",
63 PatternSource::For => "for binding",
64 PatternSource::FnParam => "function parameter",
69 /// Denotes whether the context for the set of already bound bindings is a `Product`
70 /// or `Or` context. This is used in e.g., `fresh_binding` and `resolve_pattern_inner`.
71 /// See those functions for more information.
74 /// A product pattern context, e.g., `Variant(a, b)`.
76 /// An or-pattern context, e.g., `p_0 | ... | p_n`.
80 /// Does this the item (from the item rib scope) allow generic parameters?
81 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
82 crate enum HasGenericParams { Yes, No }
84 /// The rib kind restricts certain accesses,
85 /// e.g. to a `Res::Local` of an outer item.
86 #[derive(Copy, Clone, Debug)]
87 crate enum RibKind<'a> {
88 /// No restriction needs to be applied.
91 /// We passed through an impl or trait and are now in one of its
92 /// methods or associated types. Allow references to ty params that impl or trait
93 /// binds. Disallow any other upvars (including other ty params that are
97 /// We passed through a function definition. Disallow upvars.
98 /// Permit only those const parameters that are specified in the function's generics.
101 /// We passed through an item scope. Disallow upvars.
102 ItemRibKind(HasGenericParams),
104 /// We're in a constant item. Can't refer to dynamic stuff.
107 /// We passed through a module.
108 ModuleRibKind(Module<'a>),
110 /// We passed through a `macro_rules!` statement
111 MacroDefinition(DefId),
113 /// All bindings in this rib are type parameters that can't be used
114 /// from the default of a type parameter because they're not declared
115 /// before said type parameter. Also see the `visit_generics` override.
116 ForwardTyParamBanRibKind,
120 // Whether this rib kind contains generic parameters, as opposed to local
122 crate fn contains_params(&self) -> bool {
126 | ConstantItemRibKind
128 | MacroDefinition(_) => false,
131 | ForwardTyParamBanRibKind => true,
136 /// A single local scope.
138 /// A rib represents a scope names can live in. Note that these appear in many places, not just
139 /// around braces. At any place where the list of accessible names (of the given namespace)
140 /// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
141 /// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
144 /// Different [rib kinds](enum.RibKind) are transparent for different names.
146 /// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
147 /// resolving, the name is looked up from inside out.
149 crate struct Rib<'a, R = Res> {
150 pub bindings: IdentMap<R>,
151 pub kind: RibKind<'a>,
154 impl<'a, R> Rib<'a, R> {
155 fn new(kind: RibKind<'a>) -> Rib<'a, R> {
157 bindings: Default::default(),
163 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
164 crate enum AliasPossibility {
169 #[derive(Copy, Clone, Debug)]
170 crate enum PathSource<'a> {
171 // Type paths `Path`.
173 // Trait paths in bounds or impls.
174 Trait(AliasPossibility),
175 // Expression paths `path`, with optional parent context.
176 Expr(Option<&'a Expr>),
177 // Paths in path patterns `Path`.
179 // Paths in struct expressions and patterns `Path { .. }`.
181 // Paths in tuple struct patterns `Path(..)`.
183 // `m::A::B` in `<T as m::A>::B::C`.
184 TraitItem(Namespace),
187 impl<'a> PathSource<'a> {
188 fn namespace(self) -> Namespace {
190 PathSource::Type | PathSource::Trait(_) | PathSource::Struct => TypeNS,
191 PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct => ValueNS,
192 PathSource::TraitItem(ns) => ns,
196 fn defer_to_typeck(self) -> bool {
198 PathSource::Type | PathSource::Expr(..) | PathSource::Pat |
199 PathSource::Struct | PathSource::TupleStruct => true,
200 PathSource::Trait(_) | PathSource::TraitItem(..) => false,
204 fn descr_expected(self) -> &'static str {
206 PathSource::Type => "type",
207 PathSource::Trait(_) => "trait",
208 PathSource::Pat => "unit struct, unit variant or constant",
209 PathSource::Struct => "struct, variant or union type",
210 PathSource::TupleStruct => "tuple struct or tuple variant",
211 PathSource::TraitItem(ns) => match ns {
212 TypeNS => "associated type",
213 ValueNS => "method or associated constant",
214 MacroNS => bug!("associated macro"),
216 PathSource::Expr(parent) => match &parent.as_ref().map(|p| &p.kind) {
217 // "function" here means "anything callable" rather than `DefKind::Fn`,
218 // this is not precise but usually more helpful than just "value".
219 Some(ExprKind::Call(call_expr, _)) => {
220 match &call_expr.kind {
221 ExprKind::Path(_, path) => {
222 let mut msg = "function";
223 if let Some(segment) = path.segments.iter().last() {
224 if let Some(c) = segment.ident.to_string().chars().next() {
225 if c.is_uppercase() {
226 msg = "function, tuple struct or tuple variant";
240 crate fn is_expected(self, res: Res) -> bool {
242 PathSource::Type => match res {
243 Res::Def(DefKind::Struct, _)
244 | Res::Def(DefKind::Union, _)
245 | Res::Def(DefKind::Enum, _)
246 | Res::Def(DefKind::Trait, _)
247 | Res::Def(DefKind::TraitAlias, _)
248 | Res::Def(DefKind::TyAlias, _)
249 | Res::Def(DefKind::AssocTy, _)
251 | Res::Def(DefKind::TyParam, _)
253 | Res::Def(DefKind::OpaqueTy, _)
254 | Res::Def(DefKind::ForeignTy, _) => true,
257 PathSource::Trait(AliasPossibility::No) => match res {
258 Res::Def(DefKind::Trait, _) => true,
261 PathSource::Trait(AliasPossibility::Maybe) => match res {
262 Res::Def(DefKind::Trait, _) => true,
263 Res::Def(DefKind::TraitAlias, _) => true,
266 PathSource::Expr(..) => match res {
267 Res::Def(DefKind::Ctor(_, CtorKind::Const), _)
268 | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _)
269 | Res::Def(DefKind::Const, _)
270 | Res::Def(DefKind::Static, _)
272 | Res::Def(DefKind::Fn, _)
273 | Res::Def(DefKind::Method, _)
274 | Res::Def(DefKind::AssocConst, _)
276 | Res::Def(DefKind::ConstParam, _) => true,
279 PathSource::Pat => match res {
280 Res::Def(DefKind::Ctor(_, CtorKind::Const), _) |
281 Res::Def(DefKind::Const, _) | Res::Def(DefKind::AssocConst, _) |
282 Res::SelfCtor(..) => true,
285 PathSource::TupleStruct => match res {
286 Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..) => true,
289 PathSource::Struct => match res {
290 Res::Def(DefKind::Struct, _)
291 | Res::Def(DefKind::Union, _)
292 | Res::Def(DefKind::Variant, _)
293 | Res::Def(DefKind::TyAlias, _)
294 | Res::Def(DefKind::AssocTy, _)
295 | Res::SelfTy(..) => true,
298 PathSource::TraitItem(ns) => match res {
299 Res::Def(DefKind::AssocConst, _)
300 | Res::Def(DefKind::Method, _) if ns == ValueNS => true,
301 Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
307 fn error_code(self, has_unexpected_resolution: bool) -> &'static str {
308 syntax::diagnostic_used!(E0404);
309 syntax::diagnostic_used!(E0405);
310 syntax::diagnostic_used!(E0412);
311 syntax::diagnostic_used!(E0422);
312 syntax::diagnostic_used!(E0423);
313 syntax::diagnostic_used!(E0425);
314 syntax::diagnostic_used!(E0531);
315 syntax::diagnostic_used!(E0532);
316 syntax::diagnostic_used!(E0573);
317 syntax::diagnostic_used!(E0574);
318 syntax::diagnostic_used!(E0575);
319 syntax::diagnostic_used!(E0576);
320 match (self, has_unexpected_resolution) {
321 (PathSource::Trait(_), true) => "E0404",
322 (PathSource::Trait(_), false) => "E0405",
323 (PathSource::Type, true) => "E0573",
324 (PathSource::Type, false) => "E0412",
325 (PathSource::Struct, true) => "E0574",
326 (PathSource::Struct, false) => "E0422",
327 (PathSource::Expr(..), true) => "E0423",
328 (PathSource::Expr(..), false) => "E0425",
329 (PathSource::Pat, true) | (PathSource::TupleStruct, true) => "E0532",
330 (PathSource::Pat, false) | (PathSource::TupleStruct, false) => "E0531",
331 (PathSource::TraitItem(..), true) => "E0575",
332 (PathSource::TraitItem(..), false) => "E0576",
338 struct DiagnosticMetadata {
339 /// The current trait's associated types' ident, used for diagnostic suggestions.
340 current_trait_assoc_types: Vec<Ident>,
342 /// The current self type if inside an impl (used for better errors).
343 current_self_type: Option<Ty>,
345 /// The current self item if inside an ADT (used for better errors).
346 current_self_item: Option<NodeId>,
348 /// The current enclosing funciton (used for better errors).
349 current_function: Option<Span>,
351 /// A list of labels as of yet unused. Labels will be removed from this map when
352 /// they are used (in a `break` or `continue` statement)
353 unused_labels: FxHashMap<NodeId, Span>,
355 /// Only used for better errors on `fn(): fn()`.
356 current_type_ascription: Vec<Span>,
358 /// Only used for better errors on `let <pat>: <expr, not type>;`.
359 current_let_binding: Option<(Span, Option<Span>, Option<Span>)>,
362 struct LateResolutionVisitor<'a, 'b> {
363 r: &'b mut Resolver<'a>,
365 /// The module that represents the current item scope.
366 parent_scope: ParentScope<'a>,
368 /// The current set of local scopes for types and values.
369 /// FIXME #4948: Reuse ribs to avoid allocation.
370 ribs: PerNS<Vec<Rib<'a>>>,
372 /// The current set of local scopes, for labels.
373 label_ribs: Vec<Rib<'a, NodeId>>,
375 /// The trait that the current context can refer to.
376 current_trait_ref: Option<(Module<'a>, TraitRef)>,
378 /// Fields used to add information to diagnostic errors.
379 diagnostic_metadata: DiagnosticMetadata,
382 /// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
383 impl<'a, 'tcx> Visitor<'tcx> for LateResolutionVisitor<'a, '_> {
384 fn visit_item(&mut self, item: &'tcx Item) {
385 self.resolve_item(item);
387 fn visit_arm(&mut self, arm: &'tcx Arm) {
388 self.resolve_arm(arm);
390 fn visit_block(&mut self, block: &'tcx Block) {
391 self.resolve_block(block);
393 fn visit_anon_const(&mut self, constant: &'tcx AnonConst) {
394 debug!("visit_anon_const {:?}", constant);
395 self.with_constant_rib(|this| {
396 visit::walk_anon_const(this, constant);
399 fn visit_expr(&mut self, expr: &'tcx Expr) {
400 self.resolve_expr(expr, None);
402 fn visit_local(&mut self, local: &'tcx Local) {
403 let local_spans = match local.pat.kind {
404 // We check for this to avoid tuple struct fields.
405 PatKind::Wild => None,
408 local.ty.as_ref().map(|ty| ty.span),
409 local.init.as_ref().map(|init| init.span),
412 let original = replace(&mut self.diagnostic_metadata.current_let_binding, local_spans);
413 self.resolve_local(local);
414 self.diagnostic_metadata.current_let_binding = original;
416 fn visit_ty(&mut self, ty: &'tcx Ty) {
418 TyKind::Path(ref qself, ref path) => {
419 self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
421 TyKind::ImplicitSelf => {
422 let self_ty = Ident::with_dummy_span(kw::SelfUpper);
423 let res = self.resolve_ident_in_lexical_scope(self_ty, TypeNS, Some(ty.id), ty.span)
424 .map_or(Res::Err, |d| d.res());
425 self.r.record_partial_res(ty.id, PartialRes::new(res));
429 visit::walk_ty(self, ty);
431 fn visit_poly_trait_ref(&mut self,
432 tref: &'tcx PolyTraitRef,
433 m: &'tcx TraitBoundModifier) {
434 self.smart_resolve_path(tref.trait_ref.ref_id, None,
435 &tref.trait_ref.path, PathSource::Trait(AliasPossibility::Maybe));
436 visit::walk_poly_trait_ref(self, tref, m);
438 fn visit_foreign_item(&mut self, foreign_item: &'tcx ForeignItem) {
439 match foreign_item.kind {
440 ForeignItemKind::Fn(_, ref generics) => {
441 self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
442 visit::walk_foreign_item(this, foreign_item);
445 ForeignItemKind::Static(..) => {
446 self.with_item_rib(HasGenericParams::No, |this| {
447 visit::walk_foreign_item(this, foreign_item);
450 ForeignItemKind::Ty | ForeignItemKind::Macro(..) => {
451 visit::walk_foreign_item(self, foreign_item);
455 fn visit_fn(&mut self, fn_kind: FnKind<'tcx>, declaration: &'tcx FnDecl, sp: Span, _: NodeId) {
456 let previous_value = replace(&mut self.diagnostic_metadata.current_function, Some(sp));
457 debug!("(resolving function) entering function");
458 let rib_kind = match fn_kind {
459 FnKind::ItemFn(..) => FnItemRibKind,
460 FnKind::Method(..) | FnKind::Closure(_) => NormalRibKind,
463 // Create a value rib for the function.
464 self.with_rib(ValueNS, rib_kind, |this| {
465 // Create a label rib for the function.
466 this.with_label_rib(rib_kind, |this| {
467 // Add each argument to the rib.
468 this.resolve_params(&declaration.inputs);
470 visit::walk_fn_ret_ty(this, &declaration.output);
472 // Resolve the function body, potentially inside the body of an async closure
474 FnKind::ItemFn(.., body) |
475 FnKind::Method(.., body) => this.visit_block(body),
476 FnKind::Closure(body) => this.visit_expr(body),
479 debug!("(resolving function) leaving function");
482 self.diagnostic_metadata.current_function = previous_value;
485 fn visit_generics(&mut self, generics: &'tcx Generics) {
486 // For type parameter defaults, we have to ban access
487 // to following type parameters, as the InternalSubsts can only
488 // provide previous type parameters as they're built. We
489 // put all the parameters on the ban list and then remove
490 // them one by one as they are processed and become available.
491 let mut default_ban_rib = Rib::new(ForwardTyParamBanRibKind);
492 let mut found_default = false;
493 default_ban_rib.bindings.extend(generics.params.iter()
494 .filter_map(|param| match param.kind {
495 GenericParamKind::Const { .. } |
496 GenericParamKind::Lifetime { .. } => None,
497 GenericParamKind::Type { ref default, .. } => {
498 found_default |= default.is_some();
499 found_default.then_some((Ident::with_dummy_span(param.ident.name), Res::Err))
503 // rust-lang/rust#61631: The type `Self` is essentially
504 // another type parameter. For ADTs, we consider it
505 // well-defined only after all of the ADT type parameters have
506 // been provided. Therefore, we do not allow use of `Self`
507 // anywhere in ADT type parameter defaults.
509 // (We however cannot ban `Self` for defaults on *all* generic
510 // lists; e.g. trait generics can usefully refer to `Self`,
511 // such as in the case of `trait Add<Rhs = Self>`.)
512 if self.diagnostic_metadata.current_self_item.is_some() {
513 // (`Some` if + only if we are in ADT's generics.)
514 default_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
517 for param in &generics.params {
519 GenericParamKind::Lifetime { .. } => self.visit_generic_param(param),
520 GenericParamKind::Type { ref default, .. } => {
521 for bound in ¶m.bounds {
522 self.visit_param_bound(bound);
525 if let Some(ref ty) = default {
526 self.ribs[TypeNS].push(default_ban_rib);
528 default_ban_rib = self.ribs[TypeNS].pop().unwrap();
531 // Allow all following defaults to refer to this type parameter.
532 default_ban_rib.bindings.remove(&Ident::with_dummy_span(param.ident.name));
534 GenericParamKind::Const { ref ty } => {
535 for bound in ¶m.bounds {
536 self.visit_param_bound(bound);
542 for p in &generics.where_clause.predicates {
543 self.visit_where_predicate(p);
547 fn visit_generic_arg(&mut self, arg: &'tcx GenericArg) {
548 debug!("visit_generic_arg({:?})", arg);
550 GenericArg::Type(ref ty) => {
551 // We parse const arguments as path types as we cannot distiguish them durring
552 // parsing. We try to resolve that ambiguity by attempting resolution the type
553 // namespace first, and if that fails we try again in the value namespace. If
554 // resolution in the value namespace succeeds, we have an generic const argument on
556 if let TyKind::Path(ref qself, ref path) = ty.kind {
557 // We cannot disambiguate multi-segment paths right now as that requires type
559 if path.segments.len() == 1 && path.segments[0].args.is_none() {
560 let mut check_ns = |ns| self.resolve_ident_in_lexical_scope(
561 path.segments[0].ident, ns, None, path.span
564 if !check_ns(TypeNS) && check_ns(ValueNS) {
565 // This must be equivalent to `visit_anon_const`, but we cannot call it
566 // directly due to visitor lifetimes so we have to copy-paste some code.
567 self.with_constant_rib(|this| {
568 this.smart_resolve_path(
572 PathSource::Expr(None)
575 if let Some(ref qself) = *qself {
576 this.visit_ty(&qself.ty);
578 this.visit_path(path, ty.id);
588 GenericArg::Lifetime(lt) => self.visit_lifetime(lt),
589 GenericArg::Const(ct) => self.visit_anon_const(ct),
594 impl<'a, 'b> LateResolutionVisitor<'a, '_> {
595 fn new(resolver: &'b mut Resolver<'a>) -> LateResolutionVisitor<'a, 'b> {
596 // During late resolution we only track the module component of the parent scope,
597 // although it may be useful to track other components as well for diagnostics.
598 let graph_root = resolver.graph_root;
599 let parent_scope = ParentScope::module(graph_root);
600 let start_rib_kind = ModuleRibKind(graph_root);
601 LateResolutionVisitor {
605 value_ns: vec![Rib::new(start_rib_kind)],
606 type_ns: vec![Rib::new(start_rib_kind)],
607 macro_ns: vec![Rib::new(start_rib_kind)],
609 label_ribs: Vec::new(),
610 current_trait_ref: None,
611 diagnostic_metadata: DiagnosticMetadata::default(),
615 fn resolve_ident_in_lexical_scope(&mut self,
618 record_used_id: Option<NodeId>,
620 -> Option<LexicalScopeBinding<'a>> {
621 self.r.resolve_ident_in_lexical_scope(
622 ident, ns, &self.parent_scope, record_used_id, path_span, &self.ribs[ns]
629 opt_ns: Option<Namespace>, // `None` indicates a module path in import
632 crate_lint: CrateLint,
633 ) -> PathResult<'a> {
634 self.r.resolve_path_with_ribs(
635 path, opt_ns, &self.parent_scope, record_used, path_span, crate_lint, Some(&self.ribs)
641 // We maintain a list of value ribs and type ribs.
643 // Simultaneously, we keep track of the current position in the module
644 // graph in the `parent_scope.module` pointer. When we go to resolve a name in
645 // the value or type namespaces, we first look through all the ribs and
646 // then query the module graph. When we resolve a name in the module
647 // namespace, we can skip all the ribs (since nested modules are not
648 // allowed within blocks in Rust) and jump straight to the current module
651 // Named implementations are handled separately. When we find a method
652 // call, we consult the module node to find all of the implementations in
653 // scope. This information is lazily cached in the module node. We then
654 // generate a fake "implementation scope" containing all the
655 // implementations thus found, for compatibility with old resolve pass.
657 /// Do some `work` within a new innermost rib of the given `kind` in the given namespace (`ns`).
662 work: impl FnOnce(&mut Self) -> T,
664 self.ribs[ns].push(Rib::new(kind));
665 let ret = work(self);
670 fn with_scope<T>(&mut self, id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
671 let id = self.r.definitions.local_def_id(id);
672 let module = self.r.module_map.get(&id).cloned(); // clones a reference
673 if let Some(module) = module {
674 // Move down in the graph.
675 let orig_module = replace(&mut self.parent_scope.module, module);
676 self.with_rib(ValueNS, ModuleRibKind(module), |this| {
677 this.with_rib(TypeNS, ModuleRibKind(module), |this| {
679 this.parent_scope.module = orig_module;
688 /// Searches the current set of local scopes for labels. Returns the first non-`None` label that
689 /// is returned by the given predicate function
691 /// Stops after meeting a closure.
692 fn search_label<P, R>(&self, mut ident: Ident, pred: P) -> Option<R>
693 where P: Fn(&Rib<'_, NodeId>, Ident) -> Option<R>
695 for rib in self.label_ribs.iter().rev() {
698 // If an invocation of this macro created `ident`, give up on `ident`
699 // and switch to `ident`'s source from the macro definition.
700 MacroDefinition(def) => {
701 if def == self.r.macro_def(ident.span.ctxt()) {
702 ident.span.remove_mark();
706 // Do not resolve labels across function boundary
710 let r = pred(rib, ident);
718 fn resolve_adt(&mut self, item: &Item, generics: &Generics) {
719 debug!("resolve_adt");
720 self.with_current_self_item(item, |this| {
721 this.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
722 let item_def_id = this.r.definitions.local_def_id(item.id);
723 this.with_self_rib(Res::SelfTy(None, Some(item_def_id)), |this| {
724 visit::walk_item(this, item);
730 fn future_proof_import(&mut self, use_tree: &UseTree) {
731 let segments = &use_tree.prefix.segments;
732 if !segments.is_empty() {
733 let ident = segments[0].ident;
734 if ident.is_path_segment_keyword() || ident.span.rust_2015() {
738 let nss = match use_tree.kind {
739 UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
742 let report_error = |this: &Self, ns| {
743 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
744 this.r.session.span_err(ident.span, &format!("imports cannot refer to {}", what));
748 match self.resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span) {
749 Some(LexicalScopeBinding::Res(..)) => {
750 report_error(self, ns);
752 Some(LexicalScopeBinding::Item(binding)) => {
753 let orig_blacklisted_binding =
754 replace(&mut self.r.blacklisted_binding, Some(binding));
755 if let Some(LexicalScopeBinding::Res(..)) =
756 self.resolve_ident_in_lexical_scope(ident, ns, None,
757 use_tree.prefix.span) {
758 report_error(self, ns);
760 self.r.blacklisted_binding = orig_blacklisted_binding;
765 } else if let UseTreeKind::Nested(use_trees) = &use_tree.kind {
766 for (use_tree, _) in use_trees {
767 self.future_proof_import(use_tree);
772 fn resolve_item(&mut self, item: &Item) {
773 let name = item.ident.name;
774 debug!("(resolving item) resolving {} ({:?})", name, item.kind);
777 ItemKind::TyAlias(_, ref generics) |
778 ItemKind::Fn(_, ref generics, _) => {
779 self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes),
780 |this| visit::walk_item(this, item));
783 ItemKind::Enum(_, ref generics) |
784 ItemKind::Struct(_, ref generics) |
785 ItemKind::Union(_, ref generics) => {
786 self.resolve_adt(item, generics);
789 ItemKind::Impl(.., ref generics, ref opt_trait_ref, ref self_type, ref impl_items) =>
790 self.resolve_implementation(generics,
796 ItemKind::Trait(.., ref generics, ref bounds, ref trait_items) => {
797 // Create a new rib for the trait-wide type parameters.
798 self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
799 let local_def_id = this.r.definitions.local_def_id(item.id);
800 this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
801 this.visit_generics(generics);
802 walk_list!(this, visit_param_bound, bounds);
804 for trait_item in trait_items {
805 this.with_trait_items(trait_items, |this| {
806 this.with_generic_param_rib(&trait_item.generics, AssocItemRibKind,
808 match trait_item.kind {
809 TraitItemKind::Const(ref ty, ref default) => {
812 // Only impose the restrictions of
813 // ConstRibKind for an actual constant
814 // expression in a provided default.
815 if let Some(ref expr) = *default{
816 this.with_constant_rib(|this| {
817 this.visit_expr(expr);
821 TraitItemKind::Method(_, _) => {
822 visit::walk_trait_item(this, trait_item)
824 TraitItemKind::Type(..) => {
825 visit::walk_trait_item(this, trait_item)
827 TraitItemKind::Macro(_) => {
828 panic!("unexpanded macro in resolve!")
838 ItemKind::TraitAlias(ref generics, ref bounds) => {
839 // Create a new rib for the trait-wide type parameters.
840 self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
841 let local_def_id = this.r.definitions.local_def_id(item.id);
842 this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
843 this.visit_generics(generics);
844 walk_list!(this, visit_param_bound, bounds);
849 ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
850 self.with_scope(item.id, |this| {
851 visit::walk_item(this, item);
855 ItemKind::Static(ref ty, _, ref expr) |
856 ItemKind::Const(ref ty, ref expr) => {
857 debug!("resolve_item ItemKind::Const");
858 self.with_item_rib(HasGenericParams::No, |this| {
860 this.with_constant_rib(|this| {
861 this.visit_expr(expr);
866 ItemKind::Use(ref use_tree) => {
867 self.future_proof_import(use_tree);
870 ItemKind::ExternCrate(..) |
871 ItemKind::MacroDef(..) | ItemKind::GlobalAsm(..) => {
872 // do nothing, these are just around to be encoded
875 ItemKind::Mac(_) => panic!("unexpanded macro in resolve!"),
879 fn with_generic_param_rib<'c, F>(&'c mut self, generics: &'c Generics, kind: RibKind<'a>, f: F)
880 where F: FnOnce(&mut Self)
882 debug!("with_generic_param_rib");
883 let mut function_type_rib = Rib::new(kind);
884 let mut function_value_rib = Rib::new(kind);
885 let mut seen_bindings = FxHashMap::default();
887 // We also can't shadow bindings from the parent item
888 if let AssocItemRibKind = kind {
889 let mut add_bindings_for_ns = |ns| {
890 let parent_rib = self.ribs[ns].iter()
891 .rfind(|r| if let ItemRibKind(_) = r.kind { true } else { false })
892 .expect("associated item outside of an item");
893 seen_bindings.extend(
894 parent_rib.bindings.iter().map(|(ident, _)| (*ident, ident.span)),
897 add_bindings_for_ns(ValueNS);
898 add_bindings_for_ns(TypeNS);
901 for param in &generics.params {
902 if let GenericParamKind::Lifetime { .. } = param.kind {
906 let def_kind = match param.kind {
907 GenericParamKind::Type { .. } => DefKind::TyParam,
908 GenericParamKind::Const { .. } => DefKind::ConstParam,
912 let ident = param.ident.modern();
913 debug!("with_generic_param_rib: {}", param.id);
915 if seen_bindings.contains_key(&ident) {
916 let span = seen_bindings.get(&ident).unwrap();
917 let err = ResolutionError::NameAlreadyUsedInParameterList(
921 self.r.report_error(param.ident.span, err);
923 seen_bindings.entry(ident).or_insert(param.ident.span);
925 // Plain insert (no renaming).
926 let res = Res::Def(def_kind, self.r.definitions.local_def_id(param.id));
929 GenericParamKind::Type { .. } => {
930 function_type_rib.bindings.insert(ident, res);
931 self.r.record_partial_res(param.id, PartialRes::new(res));
933 GenericParamKind::Const { .. } => {
934 function_value_rib.bindings.insert(ident, res);
935 self.r.record_partial_res(param.id, PartialRes::new(res));
941 self.ribs[ValueNS].push(function_value_rib);
942 self.ribs[TypeNS].push(function_type_rib);
946 self.ribs[TypeNS].pop();
947 self.ribs[ValueNS].pop();
950 fn with_label_rib(&mut self, kind: RibKind<'a>, f: impl FnOnce(&mut Self)) {
951 self.label_ribs.push(Rib::new(kind));
953 self.label_ribs.pop();
956 fn with_item_rib(&mut self, has_generic_params: HasGenericParams, f: impl FnOnce(&mut Self)) {
957 let kind = ItemRibKind(has_generic_params);
958 self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
961 fn with_constant_rib(&mut self, f: impl FnOnce(&mut Self)) {
962 debug!("with_constant_rib");
963 self.with_rib(ValueNS, ConstantItemRibKind, |this| {
964 this.with_label_rib(ConstantItemRibKind, f);
968 fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
969 // Handle nested impls (inside fn bodies)
970 let previous_value = replace(
971 &mut self.diagnostic_metadata.current_self_type,
972 Some(self_type.clone()),
974 let result = f(self);
975 self.diagnostic_metadata.current_self_type = previous_value;
979 fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
980 let previous_value = replace(
981 &mut self.diagnostic_metadata.current_self_item,
984 let result = f(self);
985 self.diagnostic_metadata.current_self_item = previous_value;
989 /// When evaluating a `trait` use its associated types' idents for suggestionsa in E0412.
990 fn with_trait_items<T>(
992 trait_items: &Vec<TraitItem>,
993 f: impl FnOnce(&mut Self) -> T,
995 let trait_assoc_types = replace(
996 &mut self.diagnostic_metadata.current_trait_assoc_types,
997 trait_items.iter().filter_map(|item| match &item.kind {
998 TraitItemKind::Type(bounds, _) if bounds.len() == 0 => Some(item.ident),
1002 let result = f(self);
1003 self.diagnostic_metadata.current_trait_assoc_types = trait_assoc_types;
1007 /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
1008 fn with_optional_trait_ref<T>(
1010 opt_trait_ref: Option<&TraitRef>,
1011 f: impl FnOnce(&mut Self, Option<DefId>) -> T
1013 let mut new_val = None;
1014 let mut new_id = None;
1015 if let Some(trait_ref) = opt_trait_ref {
1016 let path: Vec<_> = Segment::from_path(&trait_ref.path);
1017 let res = self.smart_resolve_path_fragment(
1021 trait_ref.path.span,
1022 PathSource::Trait(AliasPossibility::No),
1023 CrateLint::SimplePath(trait_ref.ref_id),
1025 if res != Res::Err {
1026 new_id = Some(res.def_id());
1027 let span = trait_ref.path.span;
1028 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1034 CrateLint::SimplePath(trait_ref.ref_id),
1037 new_val = Some((module, trait_ref.clone()));
1041 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
1042 let result = f(self, new_id);
1043 self.current_trait_ref = original_trait_ref;
1047 fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
1048 let mut self_type_rib = Rib::new(NormalRibKind);
1050 // Plain insert (no renaming, since types are not currently hygienic)
1051 self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
1052 self.ribs[ns].push(self_type_rib);
1054 self.ribs[ns].pop();
1057 fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
1058 self.with_self_rib_ns(TypeNS, self_res, f)
1061 fn resolve_implementation(&mut self,
1062 generics: &Generics,
1063 opt_trait_reference: &Option<TraitRef>,
1066 impl_items: &[ImplItem]) {
1067 debug!("resolve_implementation");
1068 // If applicable, create a rib for the type parameters.
1069 self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
1070 // Dummy self type for better errors if `Self` is used in the trait path.
1071 this.with_self_rib(Res::SelfTy(None, None), |this| {
1072 // Resolve the trait reference, if necessary.
1073 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
1074 let item_def_id = this.r.definitions.local_def_id(item_id);
1075 this.with_self_rib(Res::SelfTy(trait_id, Some(item_def_id)), |this| {
1076 if let Some(trait_ref) = opt_trait_reference.as_ref() {
1077 // Resolve type arguments in the trait path.
1078 visit::walk_trait_ref(this, trait_ref);
1080 // Resolve the self type.
1081 this.visit_ty(self_type);
1082 // Resolve the generic parameters.
1083 this.visit_generics(generics);
1084 // Resolve the items within the impl.
1085 this.with_current_self_type(self_type, |this| {
1086 this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
1087 debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
1088 for impl_item in impl_items {
1089 // We also need a new scope for the impl item type parameters.
1090 this.with_generic_param_rib(&impl_item.generics,
1093 use crate::ResolutionError::*;
1094 match impl_item.kind {
1095 ImplItemKind::Const(..) => {
1097 "resolve_implementation ImplItemKind::Const",
1099 // If this is a trait impl, ensure the const
1101 this.check_trait_item(
1105 |n, s| ConstNotMemberOfTrait(n, s),
1108 this.with_constant_rib(|this| {
1109 visit::walk_impl_item(this, impl_item)
1112 ImplItemKind::Method(..) => {
1113 // If this is a trait impl, ensure the method
1115 this.check_trait_item(impl_item.ident,
1118 |n, s| MethodNotMemberOfTrait(n, s));
1120 visit::walk_impl_item(this, impl_item);
1122 ImplItemKind::TyAlias(ref ty) => {
1123 // If this is a trait impl, ensure the type
1125 this.check_trait_item(impl_item.ident,
1128 |n, s| TypeNotMemberOfTrait(n, s));
1132 ImplItemKind::Macro(_) =>
1133 panic!("unexpanded macro in resolve!"),
1145 fn check_trait_item<F>(&mut self, ident: Ident, ns: Namespace, span: Span, err: F)
1146 where F: FnOnce(Name, &str) -> ResolutionError<'_>
1148 // If there is a TraitRef in scope for an impl, then the method must be in the
1150 if let Some((module, _)) = self.current_trait_ref {
1151 if self.r.resolve_ident_in_module(
1152 ModuleOrUniformRoot::Module(module),
1159 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
1160 self.r.report_error(span, err(ident.name, &path_names_to_string(path)));
1165 fn resolve_params(&mut self, params: &[Param]) {
1166 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
1167 for Param { pat, ty, .. } in params {
1168 self.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
1170 debug!("(resolving function / closure) recorded parameter");
1174 fn resolve_local(&mut self, local: &Local) {
1175 // Resolve the type.
1176 walk_list!(self, visit_ty, &local.ty);
1178 // Resolve the initializer.
1179 walk_list!(self, visit_expr, &local.init);
1181 // Resolve the pattern.
1182 self.resolve_pattern_top(&local.pat, PatternSource::Let);
1185 /// build a map from pattern identifiers to binding-info's.
1186 /// this is done hygienically. This could arise for a macro
1187 /// that expands into an or-pattern where one 'x' was from the
1188 /// user and one 'x' came from the macro.
1189 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
1190 let mut binding_map = FxHashMap::default();
1192 pat.walk(&mut |pat| {
1194 PatKind::Ident(binding_mode, ident, ref sub_pat)
1195 if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
1197 binding_map.insert(ident, BindingInfo { span: ident.span, binding_mode });
1199 PatKind::Or(ref ps) => {
1200 // Check the consistency of this or-pattern and
1201 // then add all bindings to the larger map.
1202 for bm in self.check_consistent_bindings(ps) {
1203 binding_map.extend(bm);
1216 fn is_base_res_local(&self, nid: NodeId) -> bool {
1217 match self.r.partial_res_map.get(&nid).map(|res| res.base_res()) {
1218 Some(Res::Local(..)) => true,
1223 /// Checks that all of the arms in an or-pattern have exactly the
1224 /// same set of bindings, with the same binding modes for each.
1225 fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) -> Vec<BindingMap> {
1226 let mut missing_vars = FxHashMap::default();
1227 let mut inconsistent_vars = FxHashMap::default();
1229 // 1) Compute the binding maps of all arms.
1230 let maps = pats.iter()
1231 .map(|pat| self.binding_mode_map(pat))
1232 .collect::<Vec<_>>();
1234 // 2) Record any missing bindings or binding mode inconsistencies.
1235 for (map_outer, pat_outer) in pats.iter().enumerate().map(|(idx, pat)| (&maps[idx], pat)) {
1236 // Check against all arms except for the same pattern which is always self-consistent.
1237 let inners = pats.iter().enumerate()
1238 .filter(|(_, pat)| pat.id != pat_outer.id)
1239 .flat_map(|(idx, _)| maps[idx].iter())
1240 .map(|(key, binding)| (key.name, map_outer.get(&key), binding));
1242 for (name, info, &binding_inner) in inners {
1244 None => { // The inner binding is missing in the outer.
1245 let binding_error = missing_vars
1247 .or_insert_with(|| BindingError {
1249 origin: BTreeSet::new(),
1250 target: BTreeSet::new(),
1251 could_be_path: name.as_str().starts_with(char::is_uppercase),
1253 binding_error.origin.insert(binding_inner.span);
1254 binding_error.target.insert(pat_outer.span);
1256 Some(binding_outer) => {
1257 if binding_outer.binding_mode != binding_inner.binding_mode {
1258 // The binding modes in the outer and inner bindings differ.
1261 .or_insert((binding_inner.span, binding_outer.span));
1268 // 3) Report all missing variables we found.
1269 let mut missing_vars = missing_vars.iter_mut().collect::<Vec<_>>();
1270 missing_vars.sort();
1271 for (name, mut v) in missing_vars {
1272 if inconsistent_vars.contains_key(name) {
1273 v.could_be_path = false;
1275 self.r.report_error(
1276 *v.origin.iter().next().unwrap(),
1277 ResolutionError::VariableNotBoundInPattern(v));
1280 // 4) Report all inconsistencies in binding modes we found.
1281 let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
1282 inconsistent_vars.sort();
1283 for (name, v) in inconsistent_vars {
1284 self.r.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
1287 // 5) Finally bubble up all the binding maps.
1291 /// Check the consistency of the outermost or-patterns.
1292 fn check_consistent_bindings_top(&mut self, pat: &Pat) {
1293 pat.walk(&mut |pat| match pat.kind {
1294 PatKind::Or(ref ps) => {
1295 self.check_consistent_bindings(ps);
1302 fn resolve_arm(&mut self, arm: &Arm) {
1303 self.with_rib(ValueNS, NormalRibKind, |this| {
1304 this.resolve_pattern_top(&arm.pat, PatternSource::Match);
1305 walk_list!(this, visit_expr, &arm.guard);
1306 this.visit_expr(&arm.body);
1310 /// Arising from `source`, resolve a top level pattern.
1311 fn resolve_pattern_top(&mut self, pat: &Pat, pat_src: PatternSource) {
1312 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
1313 self.resolve_pattern(pat, pat_src, &mut bindings);
1319 pat_src: PatternSource,
1320 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
1322 self.resolve_pattern_inner(pat, pat_src, bindings);
1323 // This has to happen *after* we determine which pat_idents are variants:
1324 self.check_consistent_bindings_top(pat);
1325 visit::walk_pat(self, pat);
1328 /// Resolve bindings in a pattern. This is a helper to `resolve_pattern`.
1332 /// A stack of sets of bindings accumulated.
1334 /// In each set, `PatBoundCtx::Product` denotes that a found binding in it should
1335 /// be interpreted as re-binding an already bound binding. This results in an error.
1336 /// Meanwhile, `PatBound::Or` denotes that a found binding in the set should result
1337 /// in reusing this binding rather than creating a fresh one.
1339 /// When called at the top level, the stack must have a single element
1340 /// with `PatBound::Product`. Otherwise, pushing to the stack happens as
1341 /// or-patterns (`p_0 | ... | p_n`) are encountered and the context needs
1342 /// to be switched to `PatBoundCtx::Or` and then `PatBoundCtx::Product` for each `p_i`.
1343 /// When each `p_i` has been dealt with, the top set is merged with its parent.
1344 /// When a whole or-pattern has been dealt with, the thing happens.
1346 /// See the implementation and `fresh_binding` for more details.
1347 fn resolve_pattern_inner(
1350 pat_src: PatternSource,
1351 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
1353 // Visit all direct subpatterns of this pattern.
1354 pat.walk(&mut |pat| {
1355 debug!("resolve_pattern pat={:?} node={:?}", pat, pat.kind);
1357 PatKind::Ident(bmode, ident, ref sub) => {
1358 // First try to resolve the identifier as some existing entity,
1359 // then fall back to a fresh binding.
1360 let has_sub = sub.is_some();
1361 let res = self.try_resolve_as_non_binding(pat_src, pat, bmode, ident, has_sub)
1362 .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
1363 self.r.record_partial_res(pat.id, PartialRes::new(res));
1365 PatKind::TupleStruct(ref path, ..) => {
1366 self.smart_resolve_path(pat.id, None, path, PathSource::TupleStruct);
1368 PatKind::Path(ref qself, ref path) => {
1369 self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
1371 PatKind::Struct(ref path, ..) => {
1372 self.smart_resolve_path(pat.id, None, path, PathSource::Struct);
1374 PatKind::Or(ref ps) => {
1375 // Add a new set of bindings to the stack. `Or` here records that when a
1376 // binding already exists in this set, it should not result in an error because
1377 // `V1(a) | V2(a)` must be allowed and are checked for consistency later.
1378 bindings.push((PatBoundCtx::Or, Default::default()));
1380 // Now we need to switch back to a product context so that each
1381 // part of the or-pattern internally rejects already bound names.
1382 // For example, `V1(a) | V2(a, a)` and `V1(a, a) | V2(a)` are bad.
1383 bindings.push((PatBoundCtx::Product, Default::default()));
1384 self.resolve_pattern_inner(p, pat_src, bindings);
1385 // Move up the non-overlapping bindings to the or-pattern.
1386 // Existing bindings just get "merged".
1387 let collected = bindings.pop().unwrap().1;
1388 bindings.last_mut().unwrap().1.extend(collected);
1390 // This or-pattern itself can itself be part of a product,
1391 // e.g. `(V1(a) | V2(a), a)` or `(a, V1(a) | V2(a))`.
1392 // Both cases bind `a` again in a product pattern and must be rejected.
1393 let collected = bindings.pop().unwrap().1;
1394 bindings.last_mut().unwrap().1.extend(collected);
1396 // Prevent visiting `ps` as we've already done so above.
1409 pat_src: PatternSource,
1410 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
1412 // Add the binding to the local ribs, if it doesn't already exist in the bindings map.
1413 // (We must not add it if it's in the bindings map because that breaks the assumptions
1414 // later passes make about or-patterns.)
1415 let ident = ident.modern_and_legacy();
1417 let mut bound_iter = bindings.iter().filter(|(_, set)| set.contains(&ident));
1418 // Already bound in a product pattern? e.g. `(a, a)` which is not allowed.
1419 let already_bound_and = bound_iter.clone().any(|(ctx, _)| *ctx == PatBoundCtx::Product);
1420 // Already bound in an or-pattern? e.g. `V1(a) | V2(a)`.
1421 // This is *required* for consistency which is checked later.
1422 let already_bound_or = bound_iter.any(|(ctx, _)| *ctx == PatBoundCtx::Or);
1424 if already_bound_and {
1425 // Overlap in a product pattern somewhere; report an error.
1426 use ResolutionError::*;
1427 let error = match pat_src {
1428 // `fn f(a: u8, a: u8)`:
1429 PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
1431 _ => IdentifierBoundMoreThanOnceInSamePattern,
1433 self.r.report_error(ident.span, error(&ident.as_str()));
1436 // Record as bound if it's valid:
1437 let ident_valid = ident.name != kw::Invalid;
1439 bindings.last_mut().unwrap().1.insert(ident);
1442 if already_bound_or {
1443 // `Variant1(a) | Variant2(a)`, ok
1444 // Reuse definition from the first `a`.
1445 self.innermost_rib_bindings(ValueNS)[&ident]
1447 let res = Res::Local(pat_id);
1449 // A completely fresh binding add to the set if it's valid.
1450 self.innermost_rib_bindings(ValueNS).insert(ident, res);
1456 fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut IdentMap<Res> {
1457 &mut self.ribs[ns].last_mut().unwrap().bindings
1460 fn try_resolve_as_non_binding(
1462 pat_src: PatternSource,
1468 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, pat.span)?.item()?;
1469 let res = binding.res();
1471 // An immutable (no `mut`) by-value (no `ref`) binding pattern without
1472 // a sub pattern (no `@ $pat`) is syntactically ambiguous as it could
1473 // also be interpreted as a path to e.g. a constant, variant, etc.
1474 let is_syntactic_ambiguity = !has_sub && bm == BindingMode::ByValue(Mutability::Immutable);
1477 Res::Def(DefKind::Ctor(_, CtorKind::Const), _) |
1478 Res::Def(DefKind::Const, _) if is_syntactic_ambiguity => {
1479 // Disambiguate in favor of a unit struct/variant or constant pattern.
1480 self.r.record_use(ident, ValueNS, binding, false);
1483 Res::Def(DefKind::Ctor(..), _)
1484 | Res::Def(DefKind::Const, _)
1485 | Res::Def(DefKind::Static, _) => {
1486 // This is unambiguously a fresh binding, either syntactically
1487 // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
1488 // to something unusable as a pattern (e.g., constructor function),
1489 // but we still conservatively report an error, see
1490 // issues/33118#issuecomment-233962221 for one reason why.
1491 self.r.report_error(
1493 ResolutionError::BindingShadowsSomethingUnacceptable(
1501 Res::Def(DefKind::Fn, _) | Res::Err => {
1502 // These entities are explicitly allowed to be shadowed by fresh bindings.
1506 span_bug!(ident.span, "unexpected resolution for an \
1507 identifier in pattern: {:?}", res);
1512 // High-level and context dependent path resolution routine.
1513 // Resolves the path and records the resolution into definition map.
1514 // If resolution fails tries several techniques to find likely
1515 // resolution candidates, suggest imports or other help, and report
1516 // errors in user friendly way.
1517 fn smart_resolve_path(&mut self,
1519 qself: Option<&QSelf>,
1521 source: PathSource<'_>) {
1522 self.smart_resolve_path_fragment(
1525 &Segment::from_path(path),
1528 CrateLint::SimplePath(id),
1532 fn smart_resolve_path_fragment(&mut self,
1534 qself: Option<&QSelf>,
1537 source: PathSource<'_>,
1538 crate_lint: CrateLint)
1540 let ns = source.namespace();
1541 let is_expected = &|res| source.is_expected(res);
1543 let report_errors = |this: &mut Self, res: Option<Res>| {
1544 let (err, candidates) = this.smart_resolve_report_errors(path, span, source, res);
1545 let def_id = this.parent_scope.module.normal_ancestor_id;
1546 let node_id = this.r.definitions.as_local_node_id(def_id).unwrap();
1547 let better = res.is_some();
1548 this.r.use_injections.push(UseError { err, candidates, node_id, better });
1549 PartialRes::new(Res::Err)
1552 let partial_res = match self.resolve_qpath_anywhere(
1558 source.defer_to_typeck(),
1561 Some(partial_res) if partial_res.unresolved_segments() == 0 => {
1562 if is_expected(partial_res.base_res()) || partial_res.base_res() == Res::Err {
1565 report_errors(self, Some(partial_res.base_res()))
1568 Some(partial_res) if source.defer_to_typeck() => {
1569 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
1570 // or `<T>::A::B`. If `B` should be resolved in value namespace then
1571 // it needs to be added to the trait map.
1573 let item_name = path.last().unwrap().ident;
1574 let traits = self.get_traits_containing_item(item_name, ns);
1575 self.r.trait_map.insert(id, traits);
1578 let mut std_path = vec![Segment::from_ident(Ident::with_dummy_span(sym::std))];
1579 std_path.extend(path);
1580 if self.r.primitive_type_table.primitive_types.contains_key(&path[0].ident.name) {
1581 let cl = CrateLint::No;
1583 if let PathResult::Module(_) | PathResult::NonModule(_) =
1584 self.resolve_path(&std_path, ns, false, span, cl) {
1585 // check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
1586 let item_span = path.iter().last().map(|segment| segment.ident.span)
1588 debug!("accessed item from `std` submodule as a bare type {:?}", std_path);
1589 let mut hm = self.r.session.confused_type_with_std_module.borrow_mut();
1590 hm.insert(item_span, span);
1591 // In some places (E0223) we only have access to the full path
1592 hm.insert(span, span);
1597 _ => report_errors(self, None)
1600 if let PathSource::TraitItem(..) = source {} else {
1601 // Avoid recording definition of `A::B` in `<T as A>::B::C`.
1602 self.r.record_partial_res(id, partial_res);
1607 fn self_type_is_available(&mut self, span: Span) -> bool {
1608 let binding = self.resolve_ident_in_lexical_scope(
1609 Ident::with_dummy_span(kw::SelfUpper),
1614 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
1617 fn self_value_is_available(&mut self, self_span: Span, path_span: Span) -> bool {
1618 let ident = Ident::new(kw::SelfLower, self_span);
1619 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, path_span);
1620 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
1623 // Resolve in alternative namespaces if resolution in the primary namespace fails.
1624 fn resolve_qpath_anywhere(
1627 qself: Option<&QSelf>,
1629 primary_ns: Namespace,
1631 defer_to_typeck: bool,
1632 crate_lint: CrateLint,
1633 ) -> Option<PartialRes> {
1634 let mut fin_res = None;
1635 for (i, ns) in [primary_ns, TypeNS, ValueNS].iter().cloned().enumerate() {
1636 if i == 0 || ns != primary_ns {
1637 match self.resolve_qpath(id, qself, path, ns, span, crate_lint) {
1638 // If defer_to_typeck, then resolution > no resolution,
1639 // otherwise full resolution > partial resolution > no resolution.
1640 Some(partial_res) if partial_res.unresolved_segments() == 0 ||
1642 return Some(partial_res),
1643 partial_res => if fin_res.is_none() { fin_res = partial_res },
1649 assert!(primary_ns != MacroNS);
1650 if qself.is_none() {
1651 let path_seg = |seg: &Segment| PathSegment::from_ident(seg.ident);
1652 let path = Path { segments: path.iter().map(path_seg).collect(), span };
1653 if let Ok((_, res)) = self.r.resolve_macro_path(
1654 &path, None, &self.parent_scope, false, false
1656 return Some(PartialRes::new(res));
1663 /// Handles paths that may refer to associated items.
1667 qself: Option<&QSelf>,
1671 crate_lint: CrateLint,
1672 ) -> Option<PartialRes> {
1674 "resolve_qpath(id={:?}, qself={:?}, path={:?}, ns={:?}, span={:?})",
1682 if let Some(qself) = qself {
1683 if qself.position == 0 {
1684 // This is a case like `<T>::B`, where there is no
1685 // trait to resolve. In that case, we leave the `B`
1686 // segment to be resolved by type-check.
1687 return Some(PartialRes::with_unresolved_segments(
1688 Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX)), path.len()
1692 // Make sure `A::B` in `<T as A::B>::C` is a trait item.
1694 // Currently, `path` names the full item (`A::B::C`, in
1695 // our example). so we extract the prefix of that that is
1696 // the trait (the slice upto and including
1697 // `qself.position`). And then we recursively resolve that,
1698 // but with `qself` set to `None`.
1700 // However, setting `qself` to none (but not changing the
1701 // span) loses the information about where this path
1702 // *actually* appears, so for the purposes of the crate
1703 // lint we pass along information that this is the trait
1704 // name from a fully qualified path, and this also
1705 // contains the full span (the `CrateLint::QPathTrait`).
1706 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
1707 let partial_res = self.smart_resolve_path_fragment(
1710 &path[..=qself.position],
1712 PathSource::TraitItem(ns),
1713 CrateLint::QPathTrait {
1715 qpath_span: qself.path_span,
1719 // The remaining segments (the `C` in our example) will
1720 // have to be resolved by type-check, since that requires doing
1721 // trait resolution.
1722 return Some(PartialRes::with_unresolved_segments(
1723 partial_res.base_res(),
1724 partial_res.unresolved_segments() + path.len() - qself.position - 1,
1728 let result = match self.resolve_path(&path, Some(ns), true, span, crate_lint) {
1729 PathResult::NonModule(path_res) => path_res,
1730 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
1731 PartialRes::new(module.res().unwrap())
1733 // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
1734 // don't report an error right away, but try to fallback to a primitive type.
1735 // So, we are still able to successfully resolve something like
1737 // use std::u8; // bring module u8 in scope
1738 // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
1739 // u8::max_value() // OK, resolves to associated function <u8>::max_value,
1740 // // not to non-existent std::u8::max_value
1743 // Such behavior is required for backward compatibility.
1744 // The same fallback is used when `a` resolves to nothing.
1745 PathResult::Module(ModuleOrUniformRoot::Module(_)) |
1746 PathResult::Failed { .. }
1747 if (ns == TypeNS || path.len() > 1) &&
1748 self.r.primitive_type_table.primitive_types
1749 .contains_key(&path[0].ident.name) => {
1750 let prim = self.r.primitive_type_table.primitive_types[&path[0].ident.name];
1751 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
1753 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
1754 PartialRes::new(module.res().unwrap()),
1755 PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
1756 self.r.report_error(span, ResolutionError::FailedToResolve { label, suggestion });
1757 PartialRes::new(Res::Err)
1759 PathResult::Module(..) | PathResult::Failed { .. } => return None,
1760 PathResult::Indeterminate => bug!("indetermined path result in resolve_qpath"),
1763 if path.len() > 1 && result.base_res() != Res::Err &&
1764 path[0].ident.name != kw::PathRoot &&
1765 path[0].ident.name != kw::DollarCrate {
1766 let unqualified_result = {
1767 match self.resolve_path(
1768 &[*path.last().unwrap()],
1774 PathResult::NonModule(path_res) => path_res.base_res(),
1775 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
1776 module.res().unwrap(),
1777 _ => return Some(result),
1780 if result.base_res() == unqualified_result {
1781 let lint = lint::builtin::UNUSED_QUALIFICATIONS;
1782 self.r.lint_buffer.buffer_lint(lint, id, span, "unnecessary qualification")
1789 fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
1790 if let Some(label) = label {
1791 if label.ident.as_str().as_bytes()[1] != b'_' {
1792 self.diagnostic_metadata.unused_labels.insert(id, label.ident.span);
1794 self.with_label_rib(NormalRibKind, |this| {
1795 let ident = label.ident.modern_and_legacy();
1796 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
1804 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &Block) {
1805 self.with_resolved_label(label, id, |this| this.visit_block(block));
1808 fn resolve_block(&mut self, block: &Block) {
1809 debug!("(resolving block) entering block");
1810 // Move down in the graph, if there's an anonymous module rooted here.
1811 let orig_module = self.parent_scope.module;
1812 let anonymous_module = self.r.block_map.get(&block.id).cloned(); // clones a reference
1814 let mut num_macro_definition_ribs = 0;
1815 if let Some(anonymous_module) = anonymous_module {
1816 debug!("(resolving block) found anonymous module, moving down");
1817 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
1818 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
1819 self.parent_scope.module = anonymous_module;
1821 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
1824 // Descend into the block.
1825 for stmt in &block.stmts {
1826 if let StmtKind::Item(ref item) = stmt.kind {
1827 if let ItemKind::MacroDef(..) = item.kind {
1828 num_macro_definition_ribs += 1;
1829 let res = self.r.definitions.local_def_id(item.id);
1830 self.ribs[ValueNS].push(Rib::new(MacroDefinition(res)));
1831 self.label_ribs.push(Rib::new(MacroDefinition(res)));
1835 self.visit_stmt(stmt);
1839 self.parent_scope.module = orig_module;
1840 for _ in 0 .. num_macro_definition_ribs {
1841 self.ribs[ValueNS].pop();
1842 self.label_ribs.pop();
1844 self.ribs[ValueNS].pop();
1845 if anonymous_module.is_some() {
1846 self.ribs[TypeNS].pop();
1848 debug!("(resolving block) leaving block");
1851 fn resolve_expr(&mut self, expr: &Expr, parent: Option<&Expr>) {
1852 // First, record candidate traits for this expression if it could
1853 // result in the invocation of a method call.
1855 self.record_candidate_traits_for_expr_if_necessary(expr);
1857 // Next, resolve the node.
1859 ExprKind::Path(ref qself, ref path) => {
1860 self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
1861 visit::walk_expr(self, expr);
1864 ExprKind::Struct(ref path, ..) => {
1865 self.smart_resolve_path(expr.id, None, path, PathSource::Struct);
1866 visit::walk_expr(self, expr);
1869 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
1870 let node_id = self.search_label(label.ident, |rib, ident| {
1871 rib.bindings.get(&ident.modern_and_legacy()).cloned()
1875 // Search again for close matches...
1876 // Picks the first label that is "close enough", which is not necessarily
1877 // the closest match
1878 let close_match = self.search_label(label.ident, |rib, ident| {
1879 let names = rib.bindings.iter().filter_map(|(id, _)| {
1880 if id.span.ctxt() == label.ident.span.ctxt() {
1886 find_best_match_for_name(names, &ident.as_str(), None)
1888 self.r.record_partial_res(expr.id, PartialRes::new(Res::Err));
1889 self.r.report_error(
1891 ResolutionError::UndeclaredLabel(&label.ident.as_str(), close_match),
1895 // Since this res is a label, it is never read.
1896 self.r.label_res_map.insert(expr.id, node_id);
1897 self.diagnostic_metadata.unused_labels.remove(&node_id);
1901 // visit `break` argument if any
1902 visit::walk_expr(self, expr);
1905 ExprKind::Let(ref pat, ref scrutinee) => {
1906 self.visit_expr(scrutinee);
1907 self.resolve_pattern_top(pat, PatternSource::Let);
1910 ExprKind::If(ref cond, ref then, ref opt_else) => {
1911 self.with_rib(ValueNS, NormalRibKind, |this| {
1912 this.visit_expr(cond);
1913 this.visit_block(then);
1915 opt_else.as_ref().map(|expr| self.visit_expr(expr));
1918 ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
1920 ExprKind::While(ref cond, ref block, label) => {
1921 self.with_resolved_label(label, expr.id, |this| {
1922 this.with_rib(ValueNS, NormalRibKind, |this| {
1923 this.visit_expr(cond);
1924 this.visit_block(block);
1929 ExprKind::ForLoop(ref pat, ref iter_expr, ref block, label) => {
1930 self.visit_expr(iter_expr);
1931 self.with_rib(ValueNS, NormalRibKind, |this| {
1932 this.resolve_pattern_top(pat, PatternSource::For);
1933 this.resolve_labeled_block(label, expr.id, block);
1937 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
1939 // Equivalent to `visit::walk_expr` + passing some context to children.
1940 ExprKind::Field(ref subexpression, _) => {
1941 self.resolve_expr(subexpression, Some(expr));
1943 ExprKind::MethodCall(ref segment, ref arguments) => {
1944 let mut arguments = arguments.iter();
1945 self.resolve_expr(arguments.next().unwrap(), Some(expr));
1946 for argument in arguments {
1947 self.resolve_expr(argument, None);
1949 self.visit_path_segment(expr.span, segment);
1952 ExprKind::Call(ref callee, ref arguments) => {
1953 self.resolve_expr(callee, Some(expr));
1954 for argument in arguments {
1955 self.resolve_expr(argument, None);
1958 ExprKind::Type(ref type_expr, _) => {
1959 self.diagnostic_metadata.current_type_ascription.push(type_expr.span);
1960 visit::walk_expr(self, expr);
1961 self.diagnostic_metadata.current_type_ascription.pop();
1963 // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to
1964 // resolve the arguments within the proper scopes so that usages of them inside the
1965 // closure are detected as upvars rather than normal closure arg usages.
1966 ExprKind::Closure(_, IsAsync::Async { .. }, _, ref fn_decl, ref body, _span) => {
1967 self.with_rib(ValueNS, NormalRibKind, |this| {
1968 // Resolve arguments:
1969 this.resolve_params(&fn_decl.inputs);
1970 // No need to resolve return type --
1971 // the outer closure return type is `FunctionRetTy::Default`.
1973 // Now resolve the inner closure
1975 // No need to resolve arguments: the inner closure has none.
1976 // Resolve the return type:
1977 visit::walk_fn_ret_ty(this, &fn_decl.output);
1979 this.visit_expr(body);
1984 visit::walk_expr(self, expr);
1989 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
1991 ExprKind::Field(_, ident) => {
1992 // FIXME(#6890): Even though you can't treat a method like a
1993 // field, we need to add any trait methods we find that match
1994 // the field name so that we can do some nice error reporting
1995 // later on in typeck.
1996 let traits = self.get_traits_containing_item(ident, ValueNS);
1997 self.r.trait_map.insert(expr.id, traits);
1999 ExprKind::MethodCall(ref segment, ..) => {
2000 debug!("(recording candidate traits for expr) recording traits for {}",
2002 let traits = self.get_traits_containing_item(segment.ident, ValueNS);
2003 self.r.trait_map.insert(expr.id, traits);
2011 fn get_traits_containing_item(&mut self, mut ident: Ident, ns: Namespace)
2012 -> Vec<TraitCandidate> {
2013 debug!("(getting traits containing item) looking for '{}'", ident.name);
2015 let mut found_traits = Vec::new();
2016 // Look for the current trait.
2017 if let Some((module, _)) = self.current_trait_ref {
2018 if self.r.resolve_ident_in_module(
2019 ModuleOrUniformRoot::Module(module),
2026 let def_id = module.def_id().unwrap();
2027 found_traits.push(TraitCandidate { def_id: def_id, import_ids: smallvec![] });
2031 ident.span = ident.span.modern();
2032 let mut search_module = self.parent_scope.module;
2034 self.get_traits_in_module_containing_item(ident, ns, search_module, &mut found_traits);
2035 search_module = unwrap_or!(
2036 self.r.hygienic_lexical_parent(search_module, &mut ident.span), break
2040 if let Some(prelude) = self.r.prelude {
2041 if !search_module.no_implicit_prelude {
2042 self.get_traits_in_module_containing_item(ident, ns, prelude, &mut found_traits);
2049 fn get_traits_in_module_containing_item(&mut self,
2053 found_traits: &mut Vec<TraitCandidate>) {
2054 assert!(ns == TypeNS || ns == ValueNS);
2055 let mut traits = module.traits.borrow_mut();
2056 if traits.is_none() {
2057 let mut collected_traits = Vec::new();
2058 module.for_each_child(self.r, |_, name, ns, binding| {
2059 if ns != TypeNS { return }
2060 match binding.res() {
2061 Res::Def(DefKind::Trait, _) |
2062 Res::Def(DefKind::TraitAlias, _) => collected_traits.push((name, binding)),
2066 *traits = Some(collected_traits.into_boxed_slice());
2069 for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
2070 // Traits have pseudo-modules that can be used to search for the given ident.
2071 if let Some(module) = binding.module() {
2072 let mut ident = ident;
2073 if ident.span.glob_adjust(
2079 if self.r.resolve_ident_in_module_unadjusted(
2080 ModuleOrUniformRoot::Module(module),
2087 let import_ids = self.find_transitive_imports(&binding.kind, trait_name);
2088 let trait_def_id = module.def_id().unwrap();
2089 found_traits.push(TraitCandidate { def_id: trait_def_id, import_ids });
2091 } else if let Res::Def(DefKind::TraitAlias, _) = binding.res() {
2092 // For now, just treat all trait aliases as possible candidates, since we don't
2093 // know if the ident is somewhere in the transitive bounds.
2094 let import_ids = self.find_transitive_imports(&binding.kind, trait_name);
2095 let trait_def_id = binding.res().def_id();
2096 found_traits.push(TraitCandidate { def_id: trait_def_id, import_ids });
2098 bug!("candidate is not trait or trait alias?")
2103 fn find_transitive_imports(&mut self, mut kind: &NameBindingKind<'_>,
2104 trait_name: Ident) -> SmallVec<[NodeId; 1]> {
2105 let mut import_ids = smallvec![];
2106 while let NameBindingKind::Import { directive, binding, .. } = kind {
2107 self.r.maybe_unused_trait_imports.insert(directive.id);
2108 self.r.add_to_glob_map(&directive, trait_name);
2109 import_ids.push(directive.id);
2110 kind = &binding.kind;
2116 impl<'a> Resolver<'a> {
2117 pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
2118 let mut late_resolution_visitor = LateResolutionVisitor::new(self);
2119 visit::walk_crate(&mut late_resolution_visitor, krate);
2120 for (id, span) in late_resolution_visitor.diagnostic_metadata.unused_labels.iter() {
2121 self.lint_buffer.buffer_lint(lint::builtin::UNUSED_LABELS, *id, *span, "unused label");