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 `imports.rs`.
10 use crate::{path_names_to_string, BindingError, CrateLint, LexicalScopeBinding};
11 use crate::{Module, ModuleOrUniformRoot, ParentScope, PathResult};
12 use crate::{ResolutionError, Resolver, Segment, UseError};
14 use rustc_ast::ptr::P;
15 use rustc_ast::visit::{self, AssocCtxt, FnCtxt, FnKind, Visitor};
17 use rustc_ast::{unwrap_or, walk_list};
18 use rustc_ast_lowering::ResolverAstLowering;
19 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
20 use rustc_errors::DiagnosticId;
21 use rustc_hir::def::Namespace::{self, *};
22 use rustc_hir::def::{self, CtorKind, DefKind, PartialRes, PerNS};
23 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
24 use rustc_hir::TraitCandidate;
25 use rustc_middle::{bug, span_bug};
26 use rustc_session::lint;
27 use rustc_span::symbol::{kw, sym, Ident, Symbol};
29 use smallvec::{smallvec, SmallVec};
31 use rustc_span::source_map::{respan, Spanned};
32 use std::collections::{hash_map::Entry, BTreeSet};
33 use std::mem::{replace, take};
39 type Res = def::Res<NodeId>;
41 type IdentMap<T> = FxHashMap<Ident, T>;
43 /// Map from the name in a pattern to its binding mode.
44 type BindingMap = IdentMap<BindingInfo>;
46 #[derive(Copy, Clone, Debug)]
49 binding_mode: BindingMode,
52 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
60 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
67 fn descr(self) -> &'static str {
69 PatternSource::Match => "match binding",
70 PatternSource::Let => "let binding",
71 PatternSource::For => "for binding",
72 PatternSource::FnParam => "function parameter",
77 /// Denotes whether the context for the set of already bound bindings is a `Product`
78 /// or `Or` context. This is used in e.g., `fresh_binding` and `resolve_pattern_inner`.
79 /// See those functions for more information.
82 /// A product pattern context, e.g., `Variant(a, b)`.
84 /// An or-pattern context, e.g., `p_0 | ... | p_n`.
88 /// Does this the item (from the item rib scope) allow generic parameters?
89 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
90 crate enum HasGenericParams {
95 /// The rib kind restricts certain accesses,
96 /// e.g. to a `Res::Local` of an outer item.
97 #[derive(Copy, Clone, Debug)]
98 crate enum RibKind<'a> {
99 /// No restriction needs to be applied.
102 /// We passed through an impl or trait and are now in one of its
103 /// methods or associated types. Allow references to ty params that impl or trait
104 /// binds. Disallow any other upvars (including other ty params that are
108 /// We passed through a closure. Disallow labels.
109 ClosureOrAsyncRibKind,
111 /// We passed through a function definition. Disallow upvars.
112 /// Permit only those const parameters that are specified in the function's generics.
115 /// We passed through an item scope. Disallow upvars.
116 ItemRibKind(HasGenericParams),
118 /// We're in a constant item. Can't refer to dynamic stuff.
120 /// The `bool` indicates if this constant may reference generic parameters
121 /// and is used to only allow generic parameters to be used in trivial constant expressions.
122 ConstantItemRibKind(bool),
124 /// We passed through a module.
125 ModuleRibKind(Module<'a>),
127 /// We passed through a `macro_rules!` statement
128 MacroDefinition(DefId),
130 /// All bindings in this rib are type parameters that can't be used
131 /// from the default of a type parameter because they're not declared
132 /// before said type parameter. Also see the `visit_generics` override.
133 ForwardTyParamBanRibKind,
135 /// We are inside of the type of a const parameter. Can't refer to any
141 /// Whether this rib kind contains generic parameters, as opposed to local
143 crate fn contains_params(&self) -> bool {
146 | ClosureOrAsyncRibKind
148 | ConstantItemRibKind(_)
151 | ConstParamTyRibKind => false,
152 AssocItemRibKind | ItemRibKind(_) | ForwardTyParamBanRibKind => true,
157 /// A single local scope.
159 /// A rib represents a scope names can live in. Note that these appear in many places, not just
160 /// around braces. At any place where the list of accessible names (of the given namespace)
161 /// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
162 /// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
165 /// Different [rib kinds](enum.RibKind) are transparent for different names.
167 /// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
168 /// resolving, the name is looked up from inside out.
170 crate struct Rib<'a, R = Res> {
171 pub bindings: IdentMap<R>,
172 pub kind: RibKind<'a>,
175 impl<'a, R> Rib<'a, R> {
176 fn new(kind: RibKind<'a>) -> Rib<'a, R> {
177 Rib { bindings: Default::default(), kind }
181 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
182 crate enum AliasPossibility {
187 #[derive(Copy, Clone, Debug)]
188 crate enum PathSource<'a> {
189 // Type paths `Path`.
191 // Trait paths in bounds or impls.
192 Trait(AliasPossibility),
193 // Expression paths `path`, with optional parent context.
194 Expr(Option<&'a Expr>),
195 // Paths in path patterns `Path`.
197 // Paths in struct expressions and patterns `Path { .. }`.
199 // Paths in tuple struct patterns `Path(..)`.
200 TupleStruct(Span, &'a [Span]),
201 // `m::A::B` in `<T as m::A>::B::C`.
202 TraitItem(Namespace),
205 impl<'a> PathSource<'a> {
206 fn namespace(self) -> Namespace {
208 PathSource::Type | PathSource::Trait(_) | PathSource::Struct => TypeNS,
209 PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct(..) => ValueNS,
210 PathSource::TraitItem(ns) => ns,
214 fn defer_to_typeck(self) -> bool {
217 | PathSource::Expr(..)
220 | PathSource::TupleStruct(..) => true,
221 PathSource::Trait(_) | PathSource::TraitItem(..) => false,
225 fn descr_expected(self) -> &'static str {
227 PathSource::Type => "type",
228 PathSource::Trait(_) => "trait",
229 PathSource::Pat => "unit struct, unit variant or constant",
230 PathSource::Struct => "struct, variant or union type",
231 PathSource::TupleStruct(..) => "tuple struct or tuple variant",
232 PathSource::TraitItem(ns) => match ns {
233 TypeNS => "associated type",
234 ValueNS => "method or associated constant",
235 MacroNS => bug!("associated macro"),
237 PathSource::Expr(parent) => match parent.as_ref().map(|p| &p.kind) {
238 // "function" here means "anything callable" rather than `DefKind::Fn`,
239 // this is not precise but usually more helpful than just "value".
240 Some(ExprKind::Call(call_expr, _)) => match &call_expr.kind {
241 ExprKind::Path(_, path) => {
242 let mut msg = "function";
243 if let Some(segment) = path.segments.iter().last() {
244 if let Some(c) = segment.ident.to_string().chars().next() {
245 if c.is_uppercase() {
246 msg = "function, tuple struct or tuple variant";
259 fn is_call(self) -> bool {
260 matches!(self, PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. })))
263 crate fn is_expected(self, res: Res) -> bool {
265 PathSource::Type => matches!(res, Res::Def(
270 | DefKind::TraitAlias
275 | DefKind::ForeignTy,
280 PathSource::Trait(AliasPossibility::No) => matches!(res, Res::Def(DefKind::Trait, _)),
281 PathSource::Trait(AliasPossibility::Maybe) => {
282 matches!(res, Res::Def(DefKind::Trait | DefKind::TraitAlias, _))
284 PathSource::Expr(..) => matches!(res, Res::Def(
285 DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn)
290 | DefKind::AssocConst
291 | DefKind::ConstParam,
295 | Res::SelfCtor(..)),
296 PathSource::Pat => matches!(res, Res::Def(
297 DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::AssocConst,
300 | Res::SelfCtor(..)),
301 PathSource::TupleStruct(..) => res.expected_in_tuple_struct_pat(),
302 PathSource::Struct => matches!(res, Res::Def(
311 PathSource::TraitItem(ns) => match res {
312 Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) if ns == ValueNS => true,
313 Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
319 fn error_code(self, has_unexpected_resolution: bool) -> DiagnosticId {
320 use rustc_errors::error_code;
321 match (self, has_unexpected_resolution) {
322 (PathSource::Trait(_), true) => error_code!(E0404),
323 (PathSource::Trait(_), false) => error_code!(E0405),
324 (PathSource::Type, true) => error_code!(E0573),
325 (PathSource::Type, false) => error_code!(E0412),
326 (PathSource::Struct, true) => error_code!(E0574),
327 (PathSource::Struct, false) => error_code!(E0422),
328 (PathSource::Expr(..), true) => error_code!(E0423),
329 (PathSource::Expr(..), false) => error_code!(E0425),
330 (PathSource::Pat | PathSource::TupleStruct(..), true) => error_code!(E0532),
331 (PathSource::Pat | PathSource::TupleStruct(..), false) => error_code!(E0531),
332 (PathSource::TraitItem(..), true) => error_code!(E0575),
333 (PathSource::TraitItem(..), false) => error_code!(E0576),
339 struct DiagnosticMetadata<'ast> {
340 /// The current trait's associated items' ident, used for diagnostic suggestions.
341 current_trait_assoc_items: Option<&'ast [P<AssocItem>]>,
343 /// The current self type if inside an impl (used for better errors).
344 current_self_type: Option<Ty>,
346 /// The current self item if inside an ADT (used for better errors).
347 current_self_item: Option<NodeId>,
349 /// The current trait (used to suggest).
350 current_item: Option<&'ast Item>,
352 /// When processing generics and encountering a type not found, suggest introducing a type
354 currently_processing_generics: bool,
356 /// The current enclosing (non-closure) function (used for better errors).
357 current_function: Option<(FnKind<'ast>, Span)>,
359 /// A list of labels as of yet unused. Labels will be removed from this map when
360 /// they are used (in a `break` or `continue` statement)
361 unused_labels: FxHashMap<NodeId, Span>,
363 /// Only used for better errors on `fn(): fn()`.
364 current_type_ascription: Vec<Span>,
366 /// Only used for better errors on `let <pat>: <expr, not type>;`.
367 current_let_binding: Option<(Span, Option<Span>, Option<Span>)>,
369 /// Used to detect possible `if let` written without `let` and to provide structured suggestion.
370 in_if_condition: Option<&'ast Expr>,
372 /// If we are currently in a trait object definition. Used to point at the bounds when
373 /// encountering a struct or enum.
374 current_trait_object: Option<&'ast [ast::GenericBound]>,
376 /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
377 current_where_predicate: Option<&'ast WherePredicate>,
380 struct LateResolutionVisitor<'a, 'b, 'ast> {
381 r: &'b mut Resolver<'a>,
383 /// The module that represents the current item scope.
384 parent_scope: ParentScope<'a>,
386 /// The current set of local scopes for types and values.
387 /// FIXME #4948: Reuse ribs to avoid allocation.
388 ribs: PerNS<Vec<Rib<'a>>>,
390 /// The current set of local scopes, for labels.
391 label_ribs: Vec<Rib<'a, NodeId>>,
393 /// The trait that the current context can refer to.
394 current_trait_ref: Option<(Module<'a>, TraitRef)>,
396 /// Fields used to add information to diagnostic errors.
397 diagnostic_metadata: DiagnosticMetadata<'ast>,
399 /// State used to know whether to ignore resolution errors for function bodies.
401 /// In particular, rustdoc uses this to avoid giving errors for `cfg()` items.
402 /// In most cases this will be `None`, in which case errors will always be reported.
403 /// If it is `true`, then it will be updated when entering a nested function or trait body.
407 /// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
408 impl<'a: 'ast, 'ast> Visitor<'ast> for LateResolutionVisitor<'a, '_, 'ast> {
409 fn visit_item(&mut self, item: &'ast Item) {
410 let prev = replace(&mut self.diagnostic_metadata.current_item, Some(item));
411 // Always report errors in items we just entered.
412 let old_ignore = replace(&mut self.in_func_body, false);
413 self.resolve_item(item);
414 self.in_func_body = old_ignore;
415 self.diagnostic_metadata.current_item = prev;
417 fn visit_arm(&mut self, arm: &'ast Arm) {
418 self.resolve_arm(arm);
420 fn visit_block(&mut self, block: &'ast Block) {
421 self.resolve_block(block);
423 fn visit_anon_const(&mut self, constant: &'ast AnonConst) {
424 // We deal with repeat expressions explicitly in `resolve_expr`.
425 self.resolve_anon_const(constant, IsRepeatExpr::No);
427 fn visit_expr(&mut self, expr: &'ast Expr) {
428 self.resolve_expr(expr, None);
430 fn visit_local(&mut self, local: &'ast Local) {
431 let local_spans = match local.pat.kind {
432 // We check for this to avoid tuple struct fields.
433 PatKind::Wild => None,
436 local.ty.as_ref().map(|ty| ty.span),
437 local.init.as_ref().map(|init| init.span),
440 let original = replace(&mut self.diagnostic_metadata.current_let_binding, local_spans);
441 self.resolve_local(local);
442 self.diagnostic_metadata.current_let_binding = original;
444 fn visit_ty(&mut self, ty: &'ast Ty) {
445 let prev = self.diagnostic_metadata.current_trait_object;
447 TyKind::Path(ref qself, ref path) => {
448 self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
450 TyKind::ImplicitSelf => {
451 let self_ty = Ident::with_dummy_span(kw::SelfUpper);
453 .resolve_ident_in_lexical_scope(self_ty, TypeNS, Some(ty.id), ty.span)
454 .map_or(Res::Err, |d| d.res());
455 self.r.record_partial_res(ty.id, PartialRes::new(res));
457 TyKind::TraitObject(ref bounds, ..) => {
458 self.diagnostic_metadata.current_trait_object = Some(&bounds[..]);
462 visit::walk_ty(self, ty);
463 self.diagnostic_metadata.current_trait_object = prev;
465 fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef, m: &'ast TraitBoundModifier) {
466 self.smart_resolve_path(
467 tref.trait_ref.ref_id,
469 &tref.trait_ref.path,
470 PathSource::Trait(AliasPossibility::Maybe),
472 visit::walk_poly_trait_ref(self, tref, m);
474 fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
475 match foreign_item.kind {
476 ForeignItemKind::Fn(_, _, ref generics, _)
477 | ForeignItemKind::TyAlias(_, ref generics, ..) => {
478 self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
479 visit::walk_foreign_item(this, foreign_item);
482 ForeignItemKind::Static(..) => {
483 self.with_item_rib(HasGenericParams::No, |this| {
484 visit::walk_foreign_item(this, foreign_item);
487 ForeignItemKind::MacCall(..) => {
488 visit::walk_foreign_item(self, foreign_item);
492 fn visit_fn(&mut self, fn_kind: FnKind<'ast>, sp: Span, _: NodeId) {
493 let rib_kind = match fn_kind {
494 // Bail if there's no body.
495 FnKind::Fn(.., None) => return visit::walk_fn(self, fn_kind, sp),
496 FnKind::Fn(FnCtxt::Free | FnCtxt::Foreign, ..) => FnItemRibKind,
497 FnKind::Fn(FnCtxt::Assoc(_), ..) => NormalRibKind,
498 FnKind::Closure(..) => ClosureOrAsyncRibKind,
500 let previous_value = self.diagnostic_metadata.current_function;
501 if matches!(fn_kind, FnKind::Fn(..)) {
502 self.diagnostic_metadata.current_function = Some((fn_kind, sp));
504 debug!("(resolving function) entering function");
505 let declaration = fn_kind.decl();
507 // Create a value rib for the function.
508 self.with_rib(ValueNS, rib_kind, |this| {
509 // Create a label rib for the function.
510 this.with_label_rib(rib_kind, |this| {
511 // Add each argument to the rib.
512 this.resolve_params(&declaration.inputs);
514 visit::walk_fn_ret_ty(this, &declaration.output);
516 // Ignore errors in function bodies if this is rustdoc
517 // Be sure not to set this until the function signature has been resolved.
518 let previous_state = replace(&mut this.in_func_body, true);
519 // Resolve the function body, potentially inside the body of an async closure
521 FnKind::Fn(.., body) => walk_list!(this, visit_block, body),
522 FnKind::Closure(_, body) => this.visit_expr(body),
525 debug!("(resolving function) leaving function");
526 this.in_func_body = previous_state;
529 self.diagnostic_metadata.current_function = previous_value;
532 fn visit_generics(&mut self, generics: &'ast Generics) {
533 // For type parameter defaults, we have to ban access
534 // to following type parameters, as the InternalSubsts can only
535 // provide previous type parameters as they're built. We
536 // put all the parameters on the ban list and then remove
537 // them one by one as they are processed and become available.
538 let mut default_ban_rib = Rib::new(ForwardTyParamBanRibKind);
539 let mut found_default = false;
540 default_ban_rib.bindings.extend(generics.params.iter().filter_map(
541 |param| match param.kind {
542 GenericParamKind::Const { .. } | GenericParamKind::Lifetime { .. } => None,
543 GenericParamKind::Type { ref default, .. } => {
544 found_default |= default.is_some();
545 found_default.then_some((Ident::with_dummy_span(param.ident.name), Res::Err))
550 // rust-lang/rust#61631: The type `Self` is essentially
551 // another type parameter. For ADTs, we consider it
552 // well-defined only after all of the ADT type parameters have
553 // been provided. Therefore, we do not allow use of `Self`
554 // anywhere in ADT type parameter defaults.
556 // (We however cannot ban `Self` for defaults on *all* generic
557 // lists; e.g. trait generics can usefully refer to `Self`,
558 // such as in the case of `trait Add<Rhs = Self>`.)
559 if self.diagnostic_metadata.current_self_item.is_some() {
560 // (`Some` if + only if we are in ADT's generics.)
561 default_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
564 for param in &generics.params {
566 GenericParamKind::Lifetime => self.visit_generic_param(param),
567 GenericParamKind::Type { ref default } => {
568 for bound in ¶m.bounds {
569 self.visit_param_bound(bound);
572 if let Some(ref ty) = default {
573 self.ribs[TypeNS].push(default_ban_rib);
574 self.with_rib(ValueNS, ForwardTyParamBanRibKind, |this| {
575 // HACK: We use an empty `ForwardTyParamBanRibKind` here which
576 // is only used to forbid the use of const parameters inside of
579 // While the rib name doesn't really fit here, it does allow us to use the same
580 // code for both const and type parameters.
583 default_ban_rib = self.ribs[TypeNS].pop().unwrap();
586 // Allow all following defaults to refer to this type parameter.
587 default_ban_rib.bindings.remove(&Ident::with_dummy_span(param.ident.name));
589 GenericParamKind::Const { ref ty, kw_span: _ } => {
590 for bound in ¶m.bounds {
591 self.visit_param_bound(bound);
593 self.ribs[TypeNS].push(Rib::new(ConstParamTyRibKind));
594 self.ribs[ValueNS].push(Rib::new(ConstParamTyRibKind));
596 self.ribs[TypeNS].pop().unwrap();
597 self.ribs[ValueNS].pop().unwrap();
601 for p in &generics.where_clause.predicates {
602 self.visit_where_predicate(p);
606 fn visit_generic_arg(&mut self, arg: &'ast GenericArg) {
607 debug!("visit_generic_arg({:?})", arg);
608 let prev = replace(&mut self.diagnostic_metadata.currently_processing_generics, true);
610 GenericArg::Type(ref ty) => {
611 // We parse const arguments as path types as we cannot distinguish them during
612 // parsing. We try to resolve that ambiguity by attempting resolution the type
613 // namespace first, and if that fails we try again in the value namespace. If
614 // resolution in the value namespace succeeds, we have an generic const argument on
616 if let TyKind::Path(ref qself, ref path) = ty.kind {
617 // We cannot disambiguate multi-segment paths right now as that requires type
619 if path.segments.len() == 1 && path.segments[0].args.is_none() {
620 let mut check_ns = |ns| {
621 self.resolve_ident_in_lexical_scope(
622 path.segments[0].ident,
629 if !check_ns(TypeNS) && check_ns(ValueNS) {
630 // This must be equivalent to `visit_anon_const`, but we cannot call it
631 // directly due to visitor lifetimes so we have to copy-paste some code.
633 // Note that we might not be inside of an repeat expression here,
634 // but considering that `IsRepeatExpr` is only relevant for
635 // non-trivial constants this is doesn't matter.
636 self.with_constant_rib(IsRepeatExpr::No, true, |this| {
637 this.smart_resolve_path(
641 PathSource::Expr(None),
644 if let Some(ref qself) = *qself {
645 this.visit_ty(&qself.ty);
647 this.visit_path(path, ty.id);
650 self.diagnostic_metadata.currently_processing_generics = prev;
658 GenericArg::Lifetime(lt) => self.visit_lifetime(lt),
659 GenericArg::Const(ct) => self.visit_anon_const(ct),
661 self.diagnostic_metadata.currently_processing_generics = prev;
664 fn visit_where_predicate(&mut self, p: &'ast WherePredicate) {
665 debug!("visit_where_predicate {:?}", p);
667 replace(&mut self.diagnostic_metadata.current_where_predicate, Some(p));
668 visit::walk_where_predicate(self, p);
669 self.diagnostic_metadata.current_where_predicate = previous_value;
673 impl<'a: 'ast, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> {
674 fn new(resolver: &'b mut Resolver<'a>) -> LateResolutionVisitor<'a, 'b, 'ast> {
675 // During late resolution we only track the module component of the parent scope,
676 // although it may be useful to track other components as well for diagnostics.
677 let graph_root = resolver.graph_root;
678 let parent_scope = ParentScope::module(graph_root, resolver);
679 let start_rib_kind = ModuleRibKind(graph_root);
680 LateResolutionVisitor {
684 value_ns: vec![Rib::new(start_rib_kind)],
685 type_ns: vec![Rib::new(start_rib_kind)],
686 macro_ns: vec![Rib::new(start_rib_kind)],
688 label_ribs: Vec::new(),
689 current_trait_ref: None,
690 diagnostic_metadata: DiagnosticMetadata::default(),
691 // errors at module scope should always be reported
696 fn resolve_ident_in_lexical_scope(
700 record_used_id: Option<NodeId>,
702 ) -> Option<LexicalScopeBinding<'a>> {
703 self.r.resolve_ident_in_lexical_scope(
716 opt_ns: Option<Namespace>, // `None` indicates a module path in import
719 crate_lint: CrateLint,
720 ) -> PathResult<'a> {
721 self.r.resolve_path_with_ribs(
734 // We maintain a list of value ribs and type ribs.
736 // Simultaneously, we keep track of the current position in the module
737 // graph in the `parent_scope.module` pointer. When we go to resolve a name in
738 // the value or type namespaces, we first look through all the ribs and
739 // then query the module graph. When we resolve a name in the module
740 // namespace, we can skip all the ribs (since nested modules are not
741 // allowed within blocks in Rust) and jump straight to the current module
744 // Named implementations are handled separately. When we find a method
745 // call, we consult the module node to find all of the implementations in
746 // scope. This information is lazily cached in the module node. We then
747 // generate a fake "implementation scope" containing all the
748 // implementations thus found, for compatibility with old resolve pass.
750 /// Do some `work` within a new innermost rib of the given `kind` in the given namespace (`ns`).
755 work: impl FnOnce(&mut Self) -> T,
757 self.ribs[ns].push(Rib::new(kind));
758 let ret = work(self);
763 fn with_scope<T>(&mut self, id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
764 let id = self.r.local_def_id(id);
765 let module = self.r.module_map.get(&id).cloned(); // clones a reference
766 if let Some(module) = module {
767 // Move down in the graph.
768 let orig_module = replace(&mut self.parent_scope.module, module);
769 self.with_rib(ValueNS, ModuleRibKind(module), |this| {
770 this.with_rib(TypeNS, ModuleRibKind(module), |this| {
772 this.parent_scope.module = orig_module;
781 /// Searches the current set of local scopes for labels. Returns the `NodeId` of the resolved
782 /// label and reports an error if the label is not found or is unreachable.
783 fn resolve_label(&self, mut label: Ident) -> Option<NodeId> {
784 let mut suggestion = None;
786 // Preserve the original span so that errors contain "in this macro invocation"
788 let original_span = label.span;
790 for i in (0..self.label_ribs.len()).rev() {
791 let rib = &self.label_ribs[i];
793 if let MacroDefinition(def) = rib.kind {
794 // If an invocation of this macro created `ident`, give up on `ident`
795 // and switch to `ident`'s source from the macro definition.
796 if def == self.r.macro_def(label.span.ctxt()) {
797 label.span.remove_mark();
801 let ident = label.normalize_to_macro_rules();
802 if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
803 return if self.is_label_valid_from_rib(i) {
808 ResolutionError::UnreachableLabel {
810 definition_span: ident.span,
819 // Diagnostics: Check if this rib contains a label with a similar name, keep track of
820 // the first such label that is encountered.
821 suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
826 ResolutionError::UndeclaredLabel { name: label.name, suggestion },
831 /// Determine whether or not a label from the `rib_index`th label rib is reachable.
832 fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
833 let ribs = &self.label_ribs[rib_index + 1..];
837 NormalRibKind | MacroDefinition(..) => {
838 // Nothing to do. Continue.
842 | ClosureOrAsyncRibKind
845 | ConstantItemRibKind(_)
847 | ForwardTyParamBanRibKind
848 | ConstParamTyRibKind => {
857 fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
858 debug!("resolve_adt");
859 self.with_current_self_item(item, |this| {
860 this.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
861 let item_def_id = this.r.local_def_id(item.id).to_def_id();
862 this.with_self_rib(Res::SelfTy(None, Some((item_def_id, false))), |this| {
863 visit::walk_item(this, item);
869 fn future_proof_import(&mut self, use_tree: &UseTree) {
870 let segments = &use_tree.prefix.segments;
871 if !segments.is_empty() {
872 let ident = segments[0].ident;
873 if ident.is_path_segment_keyword() || ident.span.rust_2015() {
877 let nss = match use_tree.kind {
878 UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
881 let report_error = |this: &Self, ns| {
882 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
883 if this.should_report_errs() {
886 .span_err(ident.span, &format!("imports cannot refer to {}", what));
891 match self.resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span) {
892 Some(LexicalScopeBinding::Res(..)) => {
893 report_error(self, ns);
895 Some(LexicalScopeBinding::Item(binding)) => {
896 let orig_unusable_binding =
897 replace(&mut self.r.unusable_binding, Some(binding));
898 if let Some(LexicalScopeBinding::Res(..)) = self
899 .resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span)
901 report_error(self, ns);
903 self.r.unusable_binding = orig_unusable_binding;
908 } else if let UseTreeKind::Nested(use_trees) = &use_tree.kind {
909 for (use_tree, _) in use_trees {
910 self.future_proof_import(use_tree);
915 fn resolve_item(&mut self, item: &'ast Item) {
916 let name = item.ident.name;
917 debug!("(resolving item) resolving {} ({:?})", name, item.kind);
920 ItemKind::TyAlias(_, ref generics, _, _) | ItemKind::Fn(_, _, ref generics, _) => {
921 self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
922 visit::walk_item(this, item)
926 ItemKind::Enum(_, ref generics)
927 | ItemKind::Struct(_, ref generics)
928 | ItemKind::Union(_, ref generics) => {
929 self.resolve_adt(item, generics);
936 items: ref impl_items,
939 self.resolve_implementation(generics, of_trait, &self_ty, item.id, impl_items);
942 ItemKind::Trait(.., ref generics, ref bounds, ref trait_items) => {
943 // Create a new rib for the trait-wide type parameters.
944 self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
945 let local_def_id = this.r.local_def_id(item.id).to_def_id();
946 this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
947 this.visit_generics(generics);
948 walk_list!(this, visit_param_bound, bounds);
950 let walk_assoc_item = |this: &mut Self, generics, item| {
951 this.with_generic_param_rib(generics, AssocItemRibKind, |this| {
952 visit::walk_assoc_item(this, item, AssocCtxt::Trait)
956 this.with_trait_items(trait_items, |this| {
957 for item in trait_items {
959 AssocItemKind::Const(_, ty, default) => {
961 // Only impose the restrictions of `ConstRibKind` for an
962 // actual constant expression in a provided default.
963 if let Some(expr) = default {
964 // We allow arbitrary const expressions inside of associated consts,
965 // even if they are potentially not const evaluatable.
967 // Type parameters can already be used and as associated consts are
968 // not used as part of the type system, this is far less surprising.
969 this.with_constant_rib(
972 |this| this.visit_expr(expr),
976 AssocItemKind::Fn(_, _, generics, _) => {
977 walk_assoc_item(this, generics, item);
979 AssocItemKind::TyAlias(_, generics, _, _) => {
980 walk_assoc_item(this, generics, item);
982 AssocItemKind::MacCall(_) => {
983 panic!("unexpanded macro in resolve!")
992 ItemKind::TraitAlias(ref generics, ref bounds) => {
993 // Create a new rib for the trait-wide type parameters.
994 self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
995 let local_def_id = this.r.local_def_id(item.id).to_def_id();
996 this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
997 this.visit_generics(generics);
998 walk_list!(this, visit_param_bound, bounds);
1003 ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
1004 self.with_scope(item.id, |this| {
1005 visit::walk_item(this, item);
1009 ItemKind::Static(ref ty, _, ref expr) | ItemKind::Const(_, ref ty, ref expr) => {
1010 debug!("resolve_item ItemKind::Const");
1011 self.with_item_rib(HasGenericParams::No, |this| {
1013 if let Some(expr) = expr {
1014 // We already forbid generic params because of the above item rib,
1015 // so it doesn't matter whether this is a trivial constant.
1016 this.with_constant_rib(IsRepeatExpr::No, true, |this| {
1017 this.visit_expr(expr)
1023 ItemKind::Use(ref use_tree) => {
1024 self.future_proof_import(use_tree);
1027 ItemKind::ExternCrate(..) | ItemKind::MacroDef(..) | ItemKind::GlobalAsm(..) => {
1028 // do nothing, these are just around to be encoded
1031 ItemKind::MacCall(_) => panic!("unexpanded macro in resolve!"),
1035 fn with_generic_param_rib<'c, F>(&'c mut self, generics: &'c Generics, kind: RibKind<'a>, f: F)
1037 F: FnOnce(&mut Self),
1039 debug!("with_generic_param_rib");
1040 let mut function_type_rib = Rib::new(kind);
1041 let mut function_value_rib = Rib::new(kind);
1042 let mut seen_bindings = FxHashMap::default();
1044 // We also can't shadow bindings from the parent item
1045 if let AssocItemRibKind = kind {
1046 let mut add_bindings_for_ns = |ns| {
1047 let parent_rib = self.ribs[ns]
1049 .rfind(|r| matches!(r.kind, ItemRibKind(_)))
1050 .expect("associated item outside of an item");
1052 .extend(parent_rib.bindings.iter().map(|(ident, _)| (*ident, ident.span)));
1054 add_bindings_for_ns(ValueNS);
1055 add_bindings_for_ns(TypeNS);
1058 for param in &generics.params {
1059 if let GenericParamKind::Lifetime { .. } = param.kind {
1063 let ident = param.ident.normalize_to_macros_2_0();
1064 debug!("with_generic_param_rib: {}", param.id);
1066 match seen_bindings.entry(ident) {
1067 Entry::Occupied(entry) => {
1068 let span = *entry.get();
1069 let err = ResolutionError::NameAlreadyUsedInParameterList(ident.name, span);
1070 self.report_error(param.ident.span, err);
1072 Entry::Vacant(entry) => {
1073 entry.insert(param.ident.span);
1077 // Plain insert (no renaming).
1078 let (rib, def_kind) = match param.kind {
1079 GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam),
1080 GenericParamKind::Const { .. } => (&mut function_value_rib, DefKind::ConstParam),
1081 _ => unreachable!(),
1083 let res = Res::Def(def_kind, self.r.local_def_id(param.id).to_def_id());
1084 self.r.record_partial_res(param.id, PartialRes::new(res));
1085 rib.bindings.insert(ident, res);
1088 self.ribs[ValueNS].push(function_value_rib);
1089 self.ribs[TypeNS].push(function_type_rib);
1093 self.ribs[TypeNS].pop();
1094 self.ribs[ValueNS].pop();
1097 fn with_label_rib(&mut self, kind: RibKind<'a>, f: impl FnOnce(&mut Self)) {
1098 self.label_ribs.push(Rib::new(kind));
1100 self.label_ribs.pop();
1103 fn with_item_rib(&mut self, has_generic_params: HasGenericParams, f: impl FnOnce(&mut Self)) {
1104 let kind = ItemRibKind(has_generic_params);
1105 self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
1108 // HACK(min_const_generics,const_evaluatable_unchecked): We
1109 // want to keep allowing `[0; std::mem::size_of::<*mut T>()]`
1110 // with a future compat lint for now. We do this by adding an
1111 // additional special case for repeat expressions.
1113 // Note that we intentionally still forbid `[0; N + 1]` during
1114 // name resolution so that we don't extend the future
1115 // compat lint to new cases.
1116 fn with_constant_rib(
1118 is_repeat: IsRepeatExpr,
1120 f: impl FnOnce(&mut Self),
1122 debug!("with_constant_rib: is_repeat={:?} is_trivial={}", is_repeat, is_trivial);
1123 self.with_rib(ValueNS, ConstantItemRibKind(is_trivial), |this| {
1126 ConstantItemRibKind(is_repeat == IsRepeatExpr::Yes || is_trivial),
1128 this.with_label_rib(ConstantItemRibKind(is_trivial), f);
1134 fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
1135 // Handle nested impls (inside fn bodies)
1136 let previous_value =
1137 replace(&mut self.diagnostic_metadata.current_self_type, Some(self_type.clone()));
1138 let result = f(self);
1139 self.diagnostic_metadata.current_self_type = previous_value;
1143 fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
1144 let previous_value =
1145 replace(&mut self.diagnostic_metadata.current_self_item, Some(self_item.id));
1146 let result = f(self);
1147 self.diagnostic_metadata.current_self_item = previous_value;
1151 /// When evaluating a `trait` use its associated types' idents for suggestions in E0412.
1152 fn with_trait_items<T>(
1154 trait_items: &'ast Vec<P<AssocItem>>,
1155 f: impl FnOnce(&mut Self) -> T,
1157 let trait_assoc_items = replace(
1158 &mut self.diagnostic_metadata.current_trait_assoc_items,
1159 Some(&trait_items[..]),
1161 let result = f(self);
1162 self.diagnostic_metadata.current_trait_assoc_items = trait_assoc_items;
1166 /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
1167 fn with_optional_trait_ref<T>(
1169 opt_trait_ref: Option<&TraitRef>,
1170 f: impl FnOnce(&mut Self, Option<DefId>) -> T,
1172 let mut new_val = None;
1173 let mut new_id = None;
1174 if let Some(trait_ref) = opt_trait_ref {
1175 let path: Vec<_> = Segment::from_path(&trait_ref.path);
1176 let res = self.smart_resolve_path_fragment(
1180 trait_ref.path.span,
1181 PathSource::Trait(AliasPossibility::No),
1182 CrateLint::SimplePath(trait_ref.ref_id),
1184 let res = res.base_res();
1185 if res != Res::Err {
1186 new_id = Some(res.def_id());
1187 let span = trait_ref.path.span;
1188 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = self.resolve_path(
1193 CrateLint::SimplePath(trait_ref.ref_id),
1195 new_val = Some((module, trait_ref.clone()));
1199 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
1200 let result = f(self, new_id);
1201 self.current_trait_ref = original_trait_ref;
1205 fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
1206 let mut self_type_rib = Rib::new(NormalRibKind);
1208 // Plain insert (no renaming, since types are not currently hygienic)
1209 self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
1210 self.ribs[ns].push(self_type_rib);
1212 self.ribs[ns].pop();
1215 fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
1216 self.with_self_rib_ns(TypeNS, self_res, f)
1219 fn resolve_implementation(
1221 generics: &'ast Generics,
1222 opt_trait_reference: &'ast Option<TraitRef>,
1223 self_type: &'ast Ty,
1225 impl_items: &'ast [P<AssocItem>],
1227 debug!("resolve_implementation");
1228 // If applicable, create a rib for the type parameters.
1229 self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
1230 // Dummy self type for better errors if `Self` is used in the trait path.
1231 this.with_self_rib(Res::SelfTy(None, None), |this| {
1232 // Resolve the trait reference, if necessary.
1233 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
1234 let item_def_id = this.r.local_def_id(item_id).to_def_id();
1235 this.with_self_rib(Res::SelfTy(trait_id, Some((item_def_id, false))), |this| {
1236 if let Some(trait_ref) = opt_trait_reference.as_ref() {
1237 // Resolve type arguments in the trait path.
1238 visit::walk_trait_ref(this, trait_ref);
1240 // Resolve the self type.
1241 this.visit_ty(self_type);
1242 // Resolve the generic parameters.
1243 this.visit_generics(generics);
1244 // Resolve the items within the impl.
1245 this.with_current_self_type(self_type, |this| {
1246 this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
1247 debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
1248 for item in impl_items {
1249 use crate::ResolutionError::*;
1251 AssocItemKind::Const(_default, _ty, _expr) => {
1252 debug!("resolve_implementation AssocItemKind::Const",);
1253 // If this is a trait impl, ensure the const
1255 this.check_trait_item(
1259 |n, s| ConstNotMemberOfTrait(n, s),
1262 // We allow arbitrary const expressions inside of associated consts,
1263 // even if they are potentially not const evaluatable.
1265 // Type parameters can already be used and as associated consts are
1266 // not used as part of the type system, this is far less surprising.
1267 this.with_constant_rib(
1271 visit::walk_assoc_item(
1279 AssocItemKind::Fn(_, _, generics, _) => {
1280 // We also need a new scope for the impl item type parameters.
1281 this.with_generic_param_rib(
1285 // If this is a trait impl, ensure the method
1287 this.check_trait_item(
1291 |n, s| MethodNotMemberOfTrait(n, s),
1294 visit::walk_assoc_item(
1302 AssocItemKind::TyAlias(_, generics, _, _) => {
1303 // We also need a new scope for the impl item type parameters.
1304 this.with_generic_param_rib(
1308 // If this is a trait impl, ensure the type
1310 this.check_trait_item(
1314 |n, s| TypeNotMemberOfTrait(n, s),
1317 visit::walk_assoc_item(
1325 AssocItemKind::MacCall(_) => {
1326 panic!("unexpanded macro in resolve!")
1338 fn check_trait_item<F>(&mut self, ident: Ident, ns: Namespace, span: Span, err: F)
1340 F: FnOnce(Symbol, &str) -> ResolutionError<'_>,
1342 // If there is a TraitRef in scope for an impl, then the method must be in the
1344 if let Some((module, _)) = self.current_trait_ref {
1347 .resolve_ident_in_module(
1348 ModuleOrUniformRoot::Module(module),
1357 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
1358 self.report_error(span, err(ident.name, &path_names_to_string(path)));
1363 fn resolve_params(&mut self, params: &'ast [Param]) {
1364 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
1365 for Param { pat, ty, .. } in params {
1366 self.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
1368 debug!("(resolving function / closure) recorded parameter");
1372 fn resolve_local(&mut self, local: &'ast Local) {
1373 debug!("resolving local ({:?})", local);
1374 // Resolve the type.
1375 walk_list!(self, visit_ty, &local.ty);
1377 // Resolve the initializer.
1378 walk_list!(self, visit_expr, &local.init);
1380 // Resolve the pattern.
1381 self.resolve_pattern_top(&local.pat, PatternSource::Let);
1384 /// build a map from pattern identifiers to binding-info's.
1385 /// this is done hygienically. This could arise for a macro
1386 /// that expands into an or-pattern where one 'x' was from the
1387 /// user and one 'x' came from the macro.
1388 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
1389 let mut binding_map = FxHashMap::default();
1391 pat.walk(&mut |pat| {
1393 PatKind::Ident(binding_mode, ident, ref sub_pat)
1394 if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
1396 binding_map.insert(ident, BindingInfo { span: ident.span, binding_mode });
1398 PatKind::Or(ref ps) => {
1399 // Check the consistency of this or-pattern and
1400 // then add all bindings to the larger map.
1401 for bm in self.check_consistent_bindings(ps) {
1402 binding_map.extend(bm);
1415 fn is_base_res_local(&self, nid: NodeId) -> bool {
1416 matches!(self.r.partial_res_map.get(&nid).map(|res| res.base_res()), Some(Res::Local(..)))
1419 /// Checks that all of the arms in an or-pattern have exactly the
1420 /// same set of bindings, with the same binding modes for each.
1421 fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) -> Vec<BindingMap> {
1422 let mut missing_vars = FxHashMap::default();
1423 let mut inconsistent_vars = FxHashMap::default();
1425 // 1) Compute the binding maps of all arms.
1426 let maps = pats.iter().map(|pat| self.binding_mode_map(pat)).collect::<Vec<_>>();
1428 // 2) Record any missing bindings or binding mode inconsistencies.
1429 for (map_outer, pat_outer) in pats.iter().enumerate().map(|(idx, pat)| (&maps[idx], pat)) {
1430 // Check against all arms except for the same pattern which is always self-consistent.
1434 .filter(|(_, pat)| pat.id != pat_outer.id)
1435 .flat_map(|(idx, _)| maps[idx].iter())
1436 .map(|(key, binding)| (key.name, map_outer.get(&key), binding));
1438 for (name, info, &binding_inner) in inners {
1441 // The inner binding is missing in the outer.
1443 missing_vars.entry(name).or_insert_with(|| BindingError {
1445 origin: BTreeSet::new(),
1446 target: BTreeSet::new(),
1447 could_be_path: name.as_str().starts_with(char::is_uppercase),
1449 binding_error.origin.insert(binding_inner.span);
1450 binding_error.target.insert(pat_outer.span);
1452 Some(binding_outer) => {
1453 if binding_outer.binding_mode != binding_inner.binding_mode {
1454 // The binding modes in the outer and inner bindings differ.
1457 .or_insert((binding_inner.span, binding_outer.span));
1464 // 3) Report all missing variables we found.
1465 let mut missing_vars = missing_vars.iter_mut().collect::<Vec<_>>();
1466 missing_vars.sort_by_key(|(sym, _err)| sym.as_str());
1468 for (name, mut v) in missing_vars {
1469 if inconsistent_vars.contains_key(name) {
1470 v.could_be_path = false;
1473 *v.origin.iter().next().unwrap(),
1474 ResolutionError::VariableNotBoundInPattern(v),
1478 // 4) Report all inconsistencies in binding modes we found.
1479 let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
1480 inconsistent_vars.sort();
1481 for (name, v) in inconsistent_vars {
1482 self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
1485 // 5) Finally bubble up all the binding maps.
1489 /// Check the consistency of the outermost or-patterns.
1490 fn check_consistent_bindings_top(&mut self, pat: &'ast Pat) {
1491 pat.walk(&mut |pat| match pat.kind {
1492 PatKind::Or(ref ps) => {
1493 self.check_consistent_bindings(ps);
1500 fn resolve_arm(&mut self, arm: &'ast Arm) {
1501 self.with_rib(ValueNS, NormalRibKind, |this| {
1502 this.resolve_pattern_top(&arm.pat, PatternSource::Match);
1503 walk_list!(this, visit_expr, &arm.guard);
1504 this.visit_expr(&arm.body);
1508 /// Arising from `source`, resolve a top level pattern.
1509 fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
1510 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
1511 self.resolve_pattern(pat, pat_src, &mut bindings);
1517 pat_src: PatternSource,
1518 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
1520 self.resolve_pattern_inner(pat, pat_src, bindings);
1521 // This has to happen *after* we determine which pat_idents are variants:
1522 self.check_consistent_bindings_top(pat);
1523 visit::walk_pat(self, pat);
1526 /// Resolve bindings in a pattern. This is a helper to `resolve_pattern`.
1530 /// A stack of sets of bindings accumulated.
1532 /// In each set, `PatBoundCtx::Product` denotes that a found binding in it should
1533 /// be interpreted as re-binding an already bound binding. This results in an error.
1534 /// Meanwhile, `PatBound::Or` denotes that a found binding in the set should result
1535 /// in reusing this binding rather than creating a fresh one.
1537 /// When called at the top level, the stack must have a single element
1538 /// with `PatBound::Product`. Otherwise, pushing to the stack happens as
1539 /// or-patterns (`p_0 | ... | p_n`) are encountered and the context needs
1540 /// to be switched to `PatBoundCtx::Or` and then `PatBoundCtx::Product` for each `p_i`.
1541 /// When each `p_i` has been dealt with, the top set is merged with its parent.
1542 /// When a whole or-pattern has been dealt with, the thing happens.
1544 /// See the implementation and `fresh_binding` for more details.
1545 fn resolve_pattern_inner(
1548 pat_src: PatternSource,
1549 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
1551 // Visit all direct subpatterns of this pattern.
1552 pat.walk(&mut |pat| {
1553 debug!("resolve_pattern pat={:?} node={:?}", pat, pat.kind);
1555 PatKind::Ident(bmode, ident, ref sub) => {
1556 // First try to resolve the identifier as some existing entity,
1557 // then fall back to a fresh binding.
1558 let has_sub = sub.is_some();
1560 .try_resolve_as_non_binding(pat_src, pat, bmode, ident, has_sub)
1561 .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
1562 self.r.record_partial_res(pat.id, PartialRes::new(res));
1564 PatKind::TupleStruct(ref path, ref sub_patterns) => {
1565 self.smart_resolve_path(
1569 PathSource::TupleStruct(
1571 self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
1575 PatKind::Path(ref qself, ref path) => {
1576 self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
1578 PatKind::Struct(ref path, ..) => {
1579 self.smart_resolve_path(pat.id, None, path, PathSource::Struct);
1581 PatKind::Or(ref ps) => {
1582 // Add a new set of bindings to the stack. `Or` here records that when a
1583 // binding already exists in this set, it should not result in an error because
1584 // `V1(a) | V2(a)` must be allowed and are checked for consistency later.
1585 bindings.push((PatBoundCtx::Or, Default::default()));
1587 // Now we need to switch back to a product context so that each
1588 // part of the or-pattern internally rejects already bound names.
1589 // For example, `V1(a) | V2(a, a)` and `V1(a, a) | V2(a)` are bad.
1590 bindings.push((PatBoundCtx::Product, Default::default()));
1591 self.resolve_pattern_inner(p, pat_src, bindings);
1592 // Move up the non-overlapping bindings to the or-pattern.
1593 // Existing bindings just get "merged".
1594 let collected = bindings.pop().unwrap().1;
1595 bindings.last_mut().unwrap().1.extend(collected);
1597 // This or-pattern itself can itself be part of a product,
1598 // e.g. `(V1(a) | V2(a), a)` or `(a, V1(a) | V2(a))`.
1599 // Both cases bind `a` again in a product pattern and must be rejected.
1600 let collected = bindings.pop().unwrap().1;
1601 bindings.last_mut().unwrap().1.extend(collected);
1603 // Prevent visiting `ps` as we've already done so above.
1616 pat_src: PatternSource,
1617 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
1619 // Add the binding to the local ribs, if it doesn't already exist in the bindings map.
1620 // (We must not add it if it's in the bindings map because that breaks the assumptions
1621 // later passes make about or-patterns.)
1622 let ident = ident.normalize_to_macro_rules();
1624 let mut bound_iter = bindings.iter().filter(|(_, set)| set.contains(&ident));
1625 // Already bound in a product pattern? e.g. `(a, a)` which is not allowed.
1626 let already_bound_and = bound_iter.clone().any(|(ctx, _)| *ctx == PatBoundCtx::Product);
1627 // Already bound in an or-pattern? e.g. `V1(a) | V2(a)`.
1628 // This is *required* for consistency which is checked later.
1629 let already_bound_or = bound_iter.any(|(ctx, _)| *ctx == PatBoundCtx::Or);
1631 if already_bound_and {
1632 // Overlap in a product pattern somewhere; report an error.
1633 use ResolutionError::*;
1634 let error = match pat_src {
1635 // `fn f(a: u8, a: u8)`:
1636 PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
1638 _ => IdentifierBoundMoreThanOnceInSamePattern,
1640 self.report_error(ident.span, error(ident.name));
1643 // Record as bound if it's valid:
1644 let ident_valid = ident.name != kw::Invalid;
1646 bindings.last_mut().unwrap().1.insert(ident);
1649 if already_bound_or {
1650 // `Variant1(a) | Variant2(a)`, ok
1651 // Reuse definition from the first `a`.
1652 self.innermost_rib_bindings(ValueNS)[&ident]
1654 let res = Res::Local(pat_id);
1656 // A completely fresh binding add to the set if it's valid.
1657 self.innermost_rib_bindings(ValueNS).insert(ident, res);
1663 fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut IdentMap<Res> {
1664 &mut self.ribs[ns].last_mut().unwrap().bindings
1667 fn try_resolve_as_non_binding(
1669 pat_src: PatternSource,
1675 // An immutable (no `mut`) by-value (no `ref`) binding pattern without
1676 // a sub pattern (no `@ $pat`) is syntactically ambiguous as it could
1677 // also be interpreted as a path to e.g. a constant, variant, etc.
1678 let is_syntactic_ambiguity = !has_sub && bm == BindingMode::ByValue(Mutability::Not);
1680 let ls_binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, pat.span)?;
1681 let (res, binding) = match ls_binding {
1682 LexicalScopeBinding::Item(binding)
1683 if is_syntactic_ambiguity && binding.is_ambiguity() =>
1685 // For ambiguous bindings we don't know all their definitions and cannot check
1686 // whether they can be shadowed by fresh bindings or not, so force an error.
1687 // issues/33118#issuecomment-233962221 (see below) still applies here,
1688 // but we have to ignore it for backward compatibility.
1689 self.r.record_use(ident, ValueNS, binding, false);
1692 LexicalScopeBinding::Item(binding) => (binding.res(), Some(binding)),
1693 LexicalScopeBinding::Res(res) => (res, None),
1697 Res::SelfCtor(_) // See #70549.
1699 DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::ConstParam,
1701 ) if is_syntactic_ambiguity => {
1702 // Disambiguate in favor of a unit struct/variant or constant pattern.
1703 if let Some(binding) = binding {
1704 self.r.record_use(ident, ValueNS, binding, false);
1708 Res::Def(DefKind::Ctor(..) | DefKind::Const | DefKind::Static, _) => {
1709 // This is unambiguously a fresh binding, either syntactically
1710 // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
1711 // to something unusable as a pattern (e.g., constructor function),
1712 // but we still conservatively report an error, see
1713 // issues/33118#issuecomment-233962221 for one reason why.
1716 ResolutionError::BindingShadowsSomethingUnacceptable(
1719 binding.expect("no binding for a ctor or static"),
1724 Res::Def(DefKind::Fn, _) | Res::Local(..) | Res::Err => {
1725 // These entities are explicitly allowed to be shadowed by fresh bindings.
1730 "unexpected resolution for an identifier in pattern: {:?}",
1736 // High-level and context dependent path resolution routine.
1737 // Resolves the path and records the resolution into definition map.
1738 // If resolution fails tries several techniques to find likely
1739 // resolution candidates, suggest imports or other help, and report
1740 // errors in user friendly way.
1741 fn smart_resolve_path(
1744 qself: Option<&QSelf>,
1746 source: PathSource<'ast>,
1748 self.smart_resolve_path_fragment(
1751 &Segment::from_path(path),
1754 CrateLint::SimplePath(id),
1758 fn smart_resolve_path_fragment(
1761 qself: Option<&QSelf>,
1764 source: PathSource<'ast>,
1765 crate_lint: CrateLint,
1768 "smart_resolve_path_fragment(id={:?},qself={:?},path={:?}",
1773 let ns = source.namespace();
1775 let report_errors = |this: &mut Self, res: Option<Res>| {
1776 if this.should_report_errs() {
1777 let (err, candidates) = this.smart_resolve_report_errors(path, span, source, res);
1779 let def_id = this.parent_scope.module.normal_ancestor_id;
1780 let instead = res.is_some();
1782 if res.is_none() { this.report_missing_type_error(path) } else { None };
1784 this.r.use_injections.push(UseError {
1793 PartialRes::new(Res::Err)
1796 // For paths originating from calls (like in `HashMap::new()`), tries
1797 // to enrich the plain `failed to resolve: ...` message with hints
1798 // about possible missing imports.
1800 // Similar thing, for types, happens in `report_errors` above.
1801 let report_errors_for_call = |this: &mut Self, parent_err: Spanned<ResolutionError<'a>>| {
1802 if !source.is_call() {
1803 return Some(parent_err);
1806 // Before we start looking for candidates, we have to get our hands
1807 // on the type user is trying to perform invocation on; basically:
1808 // we're transforming `HashMap::new` into just `HashMap`
1809 let path = if let Some((_, path)) = path.split_last() {
1812 return Some(parent_err);
1815 let (mut err, candidates) =
1816 this.smart_resolve_report_errors(path, span, PathSource::Type, None);
1818 if candidates.is_empty() {
1820 return Some(parent_err);
1823 // There are two different error messages user might receive at
1825 // - E0412 cannot find type `{}` in this scope
1826 // - E0433 failed to resolve: use of undeclared type or module `{}`
1828 // The first one is emitted for paths in type-position, and the
1829 // latter one - for paths in expression-position.
1831 // Thus (since we're in expression-position at this point), not to
1832 // confuse the user, we want to keep the *message* from E0432 (so
1833 // `parent_err`), but we want *hints* from E0412 (so `err`).
1835 // And that's what happens below - we're just mixing both messages
1836 // into a single one.
1837 let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
1839 parent_err.cancel();
1841 err.message = take(&mut parent_err.message);
1842 err.code = take(&mut parent_err.code);
1843 err.children = take(&mut parent_err.children);
1847 let def_id = this.parent_scope.module.normal_ancestor_id;
1849 if this.should_report_errs() {
1850 this.r.use_injections.push(UseError {
1861 // We don't return `Some(parent_err)` here, because the error will
1862 // be already printed as part of the `use` injections
1866 let partial_res = match self.resolve_qpath_anywhere(
1872 source.defer_to_typeck(),
1875 Ok(Some(partial_res)) if partial_res.unresolved_segments() == 0 => {
1876 if source.is_expected(partial_res.base_res()) || partial_res.base_res() == Res::Err
1880 report_errors(self, Some(partial_res.base_res()))
1884 Ok(Some(partial_res)) if source.defer_to_typeck() => {
1885 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
1886 // or `<T>::A::B`. If `B` should be resolved in value namespace then
1887 // it needs to be added to the trait map.
1889 let item_name = path.last().unwrap().ident;
1890 let traits = self.get_traits_containing_item(item_name, ns);
1891 self.r.trait_map.insert(id, traits);
1894 if self.r.primitive_type_table.primitive_types.contains_key(&path[0].ident.name) {
1895 let mut std_path = Vec::with_capacity(1 + path.len());
1897 std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
1898 std_path.extend(path);
1899 if let PathResult::Module(_) | PathResult::NonModule(_) =
1900 self.resolve_path(&std_path, Some(ns), false, span, CrateLint::No)
1902 // Check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
1904 path.iter().last().map(|segment| segment.ident.span).unwrap_or(span);
1906 let mut hm = self.r.session.confused_type_with_std_module.borrow_mut();
1907 hm.insert(item_span, span);
1908 hm.insert(span, span);
1916 if let Some(err) = report_errors_for_call(self, err) {
1917 self.report_error(err.span, err.node);
1920 PartialRes::new(Res::Err)
1923 _ => report_errors(self, None),
1926 if let PathSource::TraitItem(..) = source {
1928 // Avoid recording definition of `A::B` in `<T as A>::B::C`.
1929 self.r.record_partial_res(id, partial_res);
1935 fn self_type_is_available(&mut self, span: Span) -> bool {
1936 let binding = self.resolve_ident_in_lexical_scope(
1937 Ident::with_dummy_span(kw::SelfUpper),
1942 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
1945 fn self_value_is_available(&mut self, self_span: Span, path_span: Span) -> bool {
1946 let ident = Ident::new(kw::SelfLower, self_span);
1947 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, path_span);
1948 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
1951 /// A wrapper around [`Resolver::report_error`].
1953 /// This doesn't emit errors for function bodies if this is rustdoc.
1954 fn report_error(&self, span: Span, resolution_error: ResolutionError<'_>) {
1955 if self.should_report_errs() {
1956 self.r.report_error(span, resolution_error);
1961 /// If we're actually rustdoc then avoid giving a name resolution error for `cfg()` items.
1962 fn should_report_errs(&self) -> bool {
1963 !(self.r.session.opts.actually_rustdoc && self.in_func_body)
1966 // Resolve in alternative namespaces if resolution in the primary namespace fails.
1967 fn resolve_qpath_anywhere(
1970 qself: Option<&QSelf>,
1972 primary_ns: Namespace,
1974 defer_to_typeck: bool,
1975 crate_lint: CrateLint,
1976 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'a>>> {
1977 let mut fin_res = None;
1979 for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
1980 if i == 0 || ns != primary_ns {
1981 match self.resolve_qpath(id, qself, path, ns, span, crate_lint)? {
1983 if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
1985 return Ok(Some(partial_res));
1988 if fin_res.is_none() {
1989 fin_res = partial_res;
1996 assert!(primary_ns != MacroNS);
1998 if qself.is_none() {
1999 let path_seg = |seg: &Segment| PathSegment::from_ident(seg.ident);
2000 let path = Path { segments: path.iter().map(path_seg).collect(), span, tokens: None };
2001 if let Ok((_, res)) =
2002 self.r.resolve_macro_path(&path, None, &self.parent_scope, false, false)
2004 return Ok(Some(PartialRes::new(res)));
2011 /// Handles paths that may refer to associated items.
2015 qself: Option<&QSelf>,
2019 crate_lint: CrateLint,
2020 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'a>>> {
2022 "resolve_qpath(id={:?}, qself={:?}, path={:?}, ns={:?}, span={:?})",
2023 id, qself, path, ns, span,
2026 if let Some(qself) = qself {
2027 if qself.position == 0 {
2028 // This is a case like `<T>::B`, where there is no
2029 // trait to resolve. In that case, we leave the `B`
2030 // segment to be resolved by type-check.
2031 return Ok(Some(PartialRes::with_unresolved_segments(
2032 Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX)),
2037 // Make sure `A::B` in `<T as A::B>::C` is a trait item.
2039 // Currently, `path` names the full item (`A::B::C`, in
2040 // our example). so we extract the prefix of that that is
2041 // the trait (the slice upto and including
2042 // `qself.position`). And then we recursively resolve that,
2043 // but with `qself` set to `None`.
2045 // However, setting `qself` to none (but not changing the
2046 // span) loses the information about where this path
2047 // *actually* appears, so for the purposes of the crate
2048 // lint we pass along information that this is the trait
2049 // name from a fully qualified path, and this also
2050 // contains the full span (the `CrateLint::QPathTrait`).
2051 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
2052 let partial_res = self.smart_resolve_path_fragment(
2055 &path[..=qself.position],
2057 PathSource::TraitItem(ns),
2058 CrateLint::QPathTrait { qpath_id: id, qpath_span: qself.path_span },
2061 // The remaining segments (the `C` in our example) will
2062 // have to be resolved by type-check, since that requires doing
2063 // trait resolution.
2064 return Ok(Some(PartialRes::with_unresolved_segments(
2065 partial_res.base_res(),
2066 partial_res.unresolved_segments() + path.len() - qself.position - 1,
2070 let result = match self.resolve_path(&path, Some(ns), true, span, crate_lint) {
2071 PathResult::NonModule(path_res) => path_res,
2072 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
2073 PartialRes::new(module.res().unwrap())
2075 // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
2076 // don't report an error right away, but try to fallback to a primitive type.
2077 // So, we are still able to successfully resolve something like
2079 // use std::u8; // bring module u8 in scope
2080 // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
2081 // u8::max_value() // OK, resolves to associated function <u8>::max_value,
2082 // // not to non-existent std::u8::max_value
2085 // Such behavior is required for backward compatibility.
2086 // The same fallback is used when `a` resolves to nothing.
2087 PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
2088 if (ns == TypeNS || path.len() > 1)
2091 .primitive_type_table
2093 .contains_key(&path[0].ident.name) =>
2095 let prim = self.r.primitive_type_table.primitive_types[&path[0].ident.name];
2096 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
2098 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
2099 PartialRes::new(module.res().unwrap())
2101 PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
2102 return Err(respan(span, ResolutionError::FailedToResolve { label, suggestion }));
2104 PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
2105 PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"),
2109 && result.base_res() != Res::Err
2110 && path[0].ident.name != kw::PathRoot
2111 && path[0].ident.name != kw::DollarCrate
2113 let unqualified_result = {
2114 match self.resolve_path(
2115 &[*path.last().unwrap()],
2121 PathResult::NonModule(path_res) => path_res.base_res(),
2122 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
2123 module.res().unwrap()
2125 _ => return Ok(Some(result)),
2128 if result.base_res() == unqualified_result {
2129 let lint = lint::builtin::UNUSED_QUALIFICATIONS;
2130 self.r.lint_buffer.buffer_lint(lint, id, span, "unnecessary qualification")
2137 fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
2138 if let Some(label) = label {
2139 if label.ident.as_str().as_bytes()[1] != b'_' {
2140 self.diagnostic_metadata.unused_labels.insert(id, label.ident.span);
2142 self.with_label_rib(NormalRibKind, |this| {
2143 let ident = label.ident.normalize_to_macro_rules();
2144 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
2152 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
2153 self.with_resolved_label(label, id, |this| this.visit_block(block));
2156 fn resolve_block(&mut self, block: &'ast Block) {
2157 debug!("(resolving block) entering block");
2158 // Move down in the graph, if there's an anonymous module rooted here.
2159 let orig_module = self.parent_scope.module;
2160 let anonymous_module = self.r.block_map.get(&block.id).cloned(); // clones a reference
2162 let mut num_macro_definition_ribs = 0;
2163 if let Some(anonymous_module) = anonymous_module {
2164 debug!("(resolving block) found anonymous module, moving down");
2165 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
2166 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
2167 self.parent_scope.module = anonymous_module;
2169 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
2172 // Descend into the block.
2173 for stmt in &block.stmts {
2174 if let StmtKind::Item(ref item) = stmt.kind {
2175 if let ItemKind::MacroDef(..) = item.kind {
2176 num_macro_definition_ribs += 1;
2177 let res = self.r.local_def_id(item.id).to_def_id();
2178 self.ribs[ValueNS].push(Rib::new(MacroDefinition(res)));
2179 self.label_ribs.push(Rib::new(MacroDefinition(res)));
2183 self.visit_stmt(stmt);
2187 self.parent_scope.module = orig_module;
2188 for _ in 0..num_macro_definition_ribs {
2189 self.ribs[ValueNS].pop();
2190 self.label_ribs.pop();
2192 self.ribs[ValueNS].pop();
2193 if anonymous_module.is_some() {
2194 self.ribs[TypeNS].pop();
2196 debug!("(resolving block) leaving block");
2199 fn resolve_anon_const(&mut self, constant: &'ast AnonConst, is_repeat: IsRepeatExpr) {
2200 debug!("resolve_anon_const {:?} is_repeat: {:?}", constant, is_repeat);
2201 self.with_constant_rib(
2203 constant.value.is_potential_trivial_const_param(),
2205 visit::walk_anon_const(this, constant);
2210 fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
2211 // First, record candidate traits for this expression if it could
2212 // result in the invocation of a method call.
2214 self.record_candidate_traits_for_expr_if_necessary(expr);
2216 // Next, resolve the node.
2218 ExprKind::Path(ref qself, ref path) => {
2219 self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
2220 visit::walk_expr(self, expr);
2223 ExprKind::Struct(ref path, ..) => {
2224 self.smart_resolve_path(expr.id, None, path, PathSource::Struct);
2225 visit::walk_expr(self, expr);
2228 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
2229 if let Some(node_id) = self.resolve_label(label.ident) {
2230 // Since this res is a label, it is never read.
2231 self.r.label_res_map.insert(expr.id, node_id);
2232 self.diagnostic_metadata.unused_labels.remove(&node_id);
2235 // visit `break` argument if any
2236 visit::walk_expr(self, expr);
2239 ExprKind::Let(ref pat, ref scrutinee) => {
2240 self.visit_expr(scrutinee);
2241 self.resolve_pattern_top(pat, PatternSource::Let);
2244 ExprKind::If(ref cond, ref then, ref opt_else) => {
2245 self.with_rib(ValueNS, NormalRibKind, |this| {
2246 let old = this.diagnostic_metadata.in_if_condition.replace(cond);
2247 this.visit_expr(cond);
2248 this.diagnostic_metadata.in_if_condition = old;
2249 this.visit_block(then);
2251 if let Some(expr) = opt_else {
2252 self.visit_expr(expr);
2256 ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
2258 ExprKind::While(ref cond, ref block, label) => {
2259 self.with_resolved_label(label, expr.id, |this| {
2260 this.with_rib(ValueNS, NormalRibKind, |this| {
2261 this.visit_expr(cond);
2262 this.visit_block(block);
2267 ExprKind::ForLoop(ref pat, ref iter_expr, ref block, label) => {
2268 self.visit_expr(iter_expr);
2269 self.with_rib(ValueNS, NormalRibKind, |this| {
2270 this.resolve_pattern_top(pat, PatternSource::For);
2271 this.resolve_labeled_block(label, expr.id, block);
2275 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
2277 // Equivalent to `visit::walk_expr` + passing some context to children.
2278 ExprKind::Field(ref subexpression, _) => {
2279 self.resolve_expr(subexpression, Some(expr));
2281 ExprKind::MethodCall(ref segment, ref arguments, _) => {
2282 let mut arguments = arguments.iter();
2283 self.resolve_expr(arguments.next().unwrap(), Some(expr));
2284 for argument in arguments {
2285 self.resolve_expr(argument, None);
2287 self.visit_path_segment(expr.span, segment);
2290 ExprKind::Call(ref callee, ref arguments) => {
2291 self.resolve_expr(callee, Some(expr));
2292 for argument in arguments {
2293 self.resolve_expr(argument, None);
2296 ExprKind::Type(ref type_expr, ref ty) => {
2297 // `ParseSess::type_ascription_path_suggestions` keeps spans of colon tokens in
2298 // type ascription. Here we are trying to retrieve the span of the colon token as
2299 // well, but only if it's written without spaces `expr:Ty` and therefore confusable
2300 // with `expr::Ty`, only in this case it will match the span from
2301 // `type_ascription_path_suggestions`.
2302 self.diagnostic_metadata
2303 .current_type_ascription
2304 .push(type_expr.span.between(ty.span));
2305 visit::walk_expr(self, expr);
2306 self.diagnostic_metadata.current_type_ascription.pop();
2308 // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to
2309 // resolve the arguments within the proper scopes so that usages of them inside the
2310 // closure are detected as upvars rather than normal closure arg usages.
2311 ExprKind::Closure(_, Async::Yes { .. }, _, ref fn_decl, ref body, _span) => {
2312 self.with_rib(ValueNS, NormalRibKind, |this| {
2313 this.with_label_rib(ClosureOrAsyncRibKind, |this| {
2314 // Resolve arguments:
2315 this.resolve_params(&fn_decl.inputs);
2316 // No need to resolve return type --
2317 // the outer closure return type is `FnRetTy::Default`.
2319 // Now resolve the inner closure
2321 // No need to resolve arguments: the inner closure has none.
2322 // Resolve the return type:
2323 visit::walk_fn_ret_ty(this, &fn_decl.output);
2325 this.visit_expr(body);
2330 ExprKind::Async(..) | ExprKind::Closure(..) => {
2331 self.with_label_rib(ClosureOrAsyncRibKind, |this| visit::walk_expr(this, expr));
2333 ExprKind::Repeat(ref elem, ref ct) => {
2334 self.visit_expr(elem);
2335 self.resolve_anon_const(ct, IsRepeatExpr::Yes);
2338 visit::walk_expr(self, expr);
2343 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
2345 ExprKind::Field(_, ident) => {
2346 // FIXME(#6890): Even though you can't treat a method like a
2347 // field, we need to add any trait methods we find that match
2348 // the field name so that we can do some nice error reporting
2349 // later on in typeck.
2350 let traits = self.get_traits_containing_item(ident, ValueNS);
2351 self.r.trait_map.insert(expr.id, traits);
2353 ExprKind::MethodCall(ref segment, ..) => {
2354 debug!("(recording candidate traits for expr) recording traits for {}", expr.id);
2355 let traits = self.get_traits_containing_item(segment.ident, ValueNS);
2356 self.r.trait_map.insert(expr.id, traits);
2364 fn get_traits_containing_item(
2368 ) -> Vec<TraitCandidate> {
2369 debug!("(getting traits containing item) looking for '{}'", ident.name);
2371 let mut found_traits = Vec::new();
2372 // Look for the current trait.
2373 if let Some((module, _)) = self.current_trait_ref {
2376 .resolve_ident_in_module(
2377 ModuleOrUniformRoot::Module(module),
2386 let def_id = module.def_id().unwrap();
2387 found_traits.push(TraitCandidate { def_id, import_ids: smallvec![] });
2391 ident.span = ident.span.normalize_to_macros_2_0();
2392 let mut search_module = self.parent_scope.module;
2394 self.r.get_traits_in_module_containing_item(
2402 unwrap_or!(self.r.hygienic_lexical_parent(search_module, &mut ident.span), break);
2405 if let Some(prelude) = self.r.prelude {
2406 if !search_module.no_implicit_prelude {
2407 self.r.get_traits_in_module_containing_item(
2421 impl<'a> Resolver<'a> {
2422 pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
2423 let mut late_resolution_visitor = LateResolutionVisitor::new(self);
2424 visit::walk_crate(&mut late_resolution_visitor, krate);
2425 for (id, span) in late_resolution_visitor.diagnostic_metadata.unused_labels.iter() {
2426 self.lint_buffer.buffer_lint(lint::builtin::UNUSED_LABELS, *id, *span, "unused label");