1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
12 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
13 html_root_url = "https://doc.rust-lang.org/nightly/")]
15 #![feature(rustc_diagnostic_macros)]
16 #![feature(slice_sort_by_cached_key)]
22 extern crate syntax_pos;
23 extern crate rustc_errors as errors;
27 extern crate rustc_data_structures;
29 use self::Namespace::*;
30 use self::TypeParameters::*;
33 use rustc::hir::map::{Definitions, DefCollector};
34 use rustc::hir::{self, PrimTy, TyBool, TyChar, TyFloat, TyInt, TyUint, TyStr};
35 use rustc::middle::cstore::{CrateStore, CrateLoader};
36 use rustc::session::Session;
38 use rustc::hir::def::*;
39 use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, DefId};
41 use rustc::hir::{Freevar, FreevarMap, TraitCandidate, TraitMap, GlobMap};
42 use rustc::util::nodemap::{NodeMap, NodeSet, FxHashMap, FxHashSet, DefIdMap};
44 use syntax::codemap::{BytePos, CodeMap};
45 use syntax::ext::hygiene::{Mark, MarkKind, SyntaxContext};
46 use syntax::ast::{self, Name, NodeId, Ident, FloatTy, IntTy, UintTy};
47 use syntax::ext::base::SyntaxExtension;
48 use syntax::ext::base::Determinacy::{self, Determined, Undetermined};
49 use syntax::ext::base::MacroKind;
50 use syntax::symbol::{Symbol, keywords};
51 use syntax::util::lev_distance::find_best_match_for_name;
53 use syntax::visit::{self, FnKind, Visitor};
55 use syntax::ast::{Arm, BindingMode, Block, Crate, Expr, ExprKind};
56 use syntax::ast::{FnDecl, ForeignItem, ForeignItemKind, GenericParam, Generics};
57 use syntax::ast::{Item, ItemKind, ImplItem, ImplItemKind};
58 use syntax::ast::{Label, Local, Mutability, Pat, PatKind, Path};
59 use syntax::ast::{QSelf, TraitItemKind, TraitRef, Ty, TyKind};
60 use syntax::feature_gate::{feature_err, GateIssue};
63 use syntax_pos::{Span, DUMMY_SP, MultiSpan};
64 use errors::{DiagnosticBuilder, DiagnosticId};
66 use std::cell::{Cell, RefCell};
68 use std::collections::BTreeSet;
71 use std::mem::replace;
72 use rustc_data_structures::sync::Lrc;
74 use resolve_imports::{ImportDirective, ImportDirectiveSubclass, NameResolution, ImportResolver};
75 use macros::{InvocationData, LegacyBinding, LegacyScope, MacroBinding};
77 // NB: This module needs to be declared first so diagnostics are
78 // registered before they are used.
83 mod build_reduced_graph;
86 /// A free importable items suggested in case of resolution failure.
87 struct ImportSuggestion {
91 /// A field or associated item from self type suggested in case of resolution failure.
92 enum AssocSuggestion {
101 origin: BTreeSet<Span>,
102 target: BTreeSet<Span>,
105 impl PartialOrd for BindingError {
106 fn partial_cmp(&self, other: &BindingError) -> Option<cmp::Ordering> {
107 Some(self.cmp(other))
111 impl PartialEq for BindingError {
112 fn eq(&self, other: &BindingError) -> bool {
113 self.name == other.name
117 impl Ord for BindingError {
118 fn cmp(&self, other: &BindingError) -> cmp::Ordering {
119 self.name.cmp(&other.name)
123 enum ResolutionError<'a> {
124 /// error E0401: can't use type parameters from outer function
125 TypeParametersFromOuterFunction(Def),
126 /// error E0403: the name is already used for a type parameter in this type parameter list
127 NameAlreadyUsedInTypeParameterList(Name, &'a Span),
128 /// error E0407: method is not a member of trait
129 MethodNotMemberOfTrait(Name, &'a str),
130 /// error E0437: type is not a member of trait
131 TypeNotMemberOfTrait(Name, &'a str),
132 /// error E0438: const is not a member of trait
133 ConstNotMemberOfTrait(Name, &'a str),
134 /// error E0408: variable `{}` is not bound in all patterns
135 VariableNotBoundInPattern(&'a BindingError),
136 /// error E0409: variable `{}` is bound in inconsistent ways within the same match arm
137 VariableBoundWithDifferentMode(Name, Span),
138 /// error E0415: identifier is bound more than once in this parameter list
139 IdentifierBoundMoreThanOnceInParameterList(&'a str),
140 /// error E0416: identifier is bound more than once in the same pattern
141 IdentifierBoundMoreThanOnceInSamePattern(&'a str),
142 /// error E0426: use of undeclared label
143 UndeclaredLabel(&'a str, Option<Name>),
144 /// error E0429: `self` imports are only allowed within a { } list
145 SelfImportsOnlyAllowedWithin,
146 /// error E0430: `self` import can only appear once in the list
147 SelfImportCanOnlyAppearOnceInTheList,
148 /// error E0431: `self` import can only appear in an import list with a non-empty prefix
149 SelfImportOnlyInImportListWithNonEmptyPrefix,
150 /// error E0432: unresolved import
151 UnresolvedImport(Option<(Span, &'a str, &'a str)>),
152 /// error E0433: failed to resolve
153 FailedToResolve(&'a str),
154 /// error E0434: can't capture dynamic environment in a fn item
155 CannotCaptureDynamicEnvironmentInFnItem,
156 /// error E0435: attempt to use a non-constant value in a constant
157 AttemptToUseNonConstantValueInConstant,
158 /// error E0530: X bindings cannot shadow Ys
159 BindingShadowsSomethingUnacceptable(&'a str, Name, &'a NameBinding<'a>),
160 /// error E0128: type parameters with a default cannot use forward declared identifiers
161 ForwardDeclaredTyParam,
164 /// Combines an error with provided span and emits it
166 /// This takes the error provided, combines it with the span and any additional spans inside the
167 /// error and emits it.
168 fn resolve_error<'sess, 'a>(resolver: &'sess Resolver,
170 resolution_error: ResolutionError<'a>) {
171 resolve_struct_error(resolver, span, resolution_error).emit();
174 fn resolve_struct_error<'sess, 'a>(resolver: &'sess Resolver,
176 resolution_error: ResolutionError<'a>)
177 -> DiagnosticBuilder<'sess> {
178 match resolution_error {
179 ResolutionError::TypeParametersFromOuterFunction(outer_def) => {
180 let mut err = struct_span_err!(resolver.session,
183 "can't use type parameters from outer function");
184 err.span_label(span, "use of type variable from outer function");
186 let cm = resolver.session.codemap();
188 Def::SelfTy(_, maybe_impl_defid) => {
189 if let Some(impl_span) = maybe_impl_defid.map_or(None,
190 |def_id| resolver.definitions.opt_span(def_id)) {
191 err.span_label(reduce_impl_span_to_impl_keyword(cm, impl_span),
192 "`Self` type implicitely declared here, on the `impl`");
195 Def::TyParam(typaram_defid) => {
196 if let Some(typaram_span) = resolver.definitions.opt_span(typaram_defid) {
197 err.span_label(typaram_span, "type variable from outer function");
200 Def::Mod(..) | Def::Struct(..) | Def::Union(..) | Def::Enum(..) | Def::Variant(..) |
201 Def::Trait(..) | Def::TyAlias(..) | Def::TyForeign(..) | Def::TraitAlias(..) |
202 Def::AssociatedTy(..) | Def::PrimTy(..) | Def::Fn(..) | Def::Const(..) |
203 Def::Static(..) | Def::StructCtor(..) | Def::VariantCtor(..) | Def::Method(..) |
204 Def::AssociatedConst(..) | Def::Local(..) | Def::Upvar(..) | Def::Label(..) |
205 Def::Macro(..) | Def::GlobalAsm(..) | Def::Err =>
206 bug!("TypeParametersFromOuterFunction should only be used with Def::SelfTy or \
210 // Try to retrieve the span of the function signature and generate a new message with
211 // a local type parameter
212 let sugg_msg = "try using a local type parameter instead";
213 if let Some((sugg_span, new_snippet)) = generate_local_type_param_snippet(cm, span) {
214 // Suggest the modification to the user
215 err.span_suggestion(sugg_span,
218 } else if let Some(sp) = generate_fn_name_span(cm, span) {
219 err.span_label(sp, "try adding a local type parameter in this method instead");
221 err.help("try using a local type parameter instead");
226 ResolutionError::NameAlreadyUsedInTypeParameterList(name, first_use_span) => {
227 let mut err = struct_span_err!(resolver.session,
230 "the name `{}` is already used for a type parameter \
231 in this type parameter list",
233 err.span_label(span, "already used");
234 err.span_label(first_use_span.clone(), format!("first use of `{}`", name));
237 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
238 let mut err = struct_span_err!(resolver.session,
241 "method `{}` is not a member of trait `{}`",
244 err.span_label(span, format!("not a member of trait `{}`", trait_));
247 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
248 let mut err = struct_span_err!(resolver.session,
251 "type `{}` is not a member of trait `{}`",
254 err.span_label(span, format!("not a member of trait `{}`", trait_));
257 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
258 let mut err = struct_span_err!(resolver.session,
261 "const `{}` is not a member of trait `{}`",
264 err.span_label(span, format!("not a member of trait `{}`", trait_));
267 ResolutionError::VariableNotBoundInPattern(binding_error) => {
268 let target_sp = binding_error.target.iter().map(|x| *x).collect::<Vec<_>>();
269 let msp = MultiSpan::from_spans(target_sp.clone());
270 let msg = format!("variable `{}` is not bound in all patterns", binding_error.name);
271 let mut err = resolver.session.struct_span_err_with_code(
274 DiagnosticId::Error("E0408".into()),
276 for sp in target_sp {
277 err.span_label(sp, format!("pattern doesn't bind `{}`", binding_error.name));
279 let origin_sp = binding_error.origin.iter().map(|x| *x).collect::<Vec<_>>();
280 for sp in origin_sp {
281 err.span_label(sp, "variable not in all patterns");
285 ResolutionError::VariableBoundWithDifferentMode(variable_name,
286 first_binding_span) => {
287 let mut err = struct_span_err!(resolver.session,
290 "variable `{}` is bound in inconsistent \
291 ways within the same match arm",
293 err.span_label(span, "bound in different ways");
294 err.span_label(first_binding_span, "first binding");
297 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
298 let mut err = struct_span_err!(resolver.session,
301 "identifier `{}` is bound more than once in this parameter list",
303 err.span_label(span, "used as parameter more than once");
306 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
307 let mut err = struct_span_err!(resolver.session,
310 "identifier `{}` is bound more than once in the same pattern",
312 err.span_label(span, "used in a pattern more than once");
315 ResolutionError::UndeclaredLabel(name, lev_candidate) => {
316 let mut err = struct_span_err!(resolver.session,
319 "use of undeclared label `{}`",
321 if let Some(lev_candidate) = lev_candidate {
322 err.span_label(span, format!("did you mean `{}`?", lev_candidate));
324 err.span_label(span, format!("undeclared label `{}`", name));
328 ResolutionError::SelfImportsOnlyAllowedWithin => {
329 struct_span_err!(resolver.session,
333 "`self` imports are only allowed within a { } list")
335 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
336 let mut err = struct_span_err!(resolver.session, span, E0430,
337 "`self` import can only appear once in an import list");
338 err.span_label(span, "can only appear once in an import list");
341 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
342 let mut err = struct_span_err!(resolver.session, span, E0431,
343 "`self` import can only appear in an import list with \
344 a non-empty prefix");
345 err.span_label(span, "can only appear in an import list with a non-empty prefix");
348 ResolutionError::UnresolvedImport(name) => {
349 let (span, msg) = match name {
350 Some((sp, n, _)) => (sp, format!("unresolved import `{}`", n)),
351 None => (span, "unresolved import".to_owned()),
353 let mut err = struct_span_err!(resolver.session, span, E0432, "{}", msg);
354 if let Some((_, _, p)) = name {
355 err.span_label(span, p);
359 ResolutionError::FailedToResolve(msg) => {
360 let mut err = struct_span_err!(resolver.session, span, E0433,
361 "failed to resolve. {}", msg);
362 err.span_label(span, msg);
365 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
366 let mut err = struct_span_err!(resolver.session,
370 "can't capture dynamic environment in a fn item");
371 err.help("use the `|| { ... }` closure form instead");
374 ResolutionError::AttemptToUseNonConstantValueInConstant => {
375 let mut err = struct_span_err!(resolver.session, span, E0435,
376 "attempt to use a non-constant value in a constant");
377 err.span_label(span, "non-constant value");
380 ResolutionError::BindingShadowsSomethingUnacceptable(what_binding, name, binding) => {
381 let shadows_what = PathResolution::new(binding.def()).kind_name();
382 let mut err = struct_span_err!(resolver.session,
385 "{}s cannot shadow {}s", what_binding, shadows_what);
386 err.span_label(span, format!("cannot be named the same as a {}", shadows_what));
387 let participle = if binding.is_import() { "imported" } else { "defined" };
388 let msg = format!("a {} `{}` is {} here", shadows_what, name, participle);
389 err.span_label(binding.span, msg);
392 ResolutionError::ForwardDeclaredTyParam => {
393 let mut err = struct_span_err!(resolver.session, span, E0128,
394 "type parameters with a default cannot use \
395 forward declared identifiers");
396 err.span_label(span, format!("defaulted type parameters cannot be forward declared"));
402 /// Adjust the impl span so that just the `impl` keyword is taken by removing
403 /// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
404 /// everything after the first whitespace (`"impl Iterator for A" -> "impl"`)
406 /// Attention: The method used is very fragile since it essentially duplicates the work of the
407 /// parser. If you need to use this function or something similar, please consider updating the
408 /// codemap functions and this function to something more robust.
409 fn reduce_impl_span_to_impl_keyword(cm: &CodeMap, impl_span: Span) -> Span {
410 let impl_span = cm.span_until_char(impl_span, '<');
411 let impl_span = cm.span_until_whitespace(impl_span);
415 fn generate_fn_name_span(cm: &CodeMap, span: Span) -> Option<Span> {
416 let prev_span = cm.span_extend_to_prev_str(span, "fn", true);
417 cm.span_to_snippet(prev_span).map(|snippet| {
418 let len = snippet.find(|c: char| !c.is_alphanumeric() && c != '_')
419 .expect("no label after fn");
420 prev_span.with_hi(BytePos(prev_span.lo().0 + len as u32))
424 /// Take the span of a type parameter in a function signature and try to generate a span for the
425 /// function name (with generics) and a new snippet for this span with the pointed type parameter as
426 /// a new local type parameter.
429 /// ```rust,ignore (pseudo-Rust)
431 /// fn my_function(param: T)
432 /// // ^ Original span
435 /// fn my_function(param: T)
436 /// // ^^^^^^^^^^^ Generated span with snippet `my_function<T>`
439 /// Attention: The method used is very fragile since it essentially duplicates the work of the
440 /// parser. If you need to use this function or something similar, please consider updating the
441 /// codemap functions and this function to something more robust.
442 fn generate_local_type_param_snippet(cm: &CodeMap, span: Span) -> Option<(Span, String)> {
443 // Try to extend the span to the previous "fn" keyword to retrieve the function
445 let sugg_span = cm.span_extend_to_prev_str(span, "fn", false);
446 if sugg_span != span {
447 if let Ok(snippet) = cm.span_to_snippet(sugg_span) {
448 // Consume the function name
449 let mut offset = snippet.find(|c: char| !c.is_alphanumeric() && c != '_')
450 .expect("no label after fn");
452 // Consume the generics part of the function signature
453 let mut bracket_counter = 0;
454 let mut last_char = None;
455 for c in snippet[offset..].chars() {
457 '<' => bracket_counter += 1,
458 '>' => bracket_counter -= 1,
459 '(' => if bracket_counter == 0 { break; }
462 offset += c.len_utf8();
466 // Adjust the suggestion span to encompass the function name with its generics
467 let sugg_span = sugg_span.with_hi(BytePos(sugg_span.lo().0 + offset as u32));
469 // Prepare the new suggested snippet to append the type parameter that triggered
470 // the error in the generics of the function signature
471 let mut new_snippet = if last_char == Some('>') {
472 format!("{}, ", &snippet[..(offset - '>'.len_utf8())])
474 format!("{}<", &snippet[..offset])
476 new_snippet.push_str(&cm.span_to_snippet(span).unwrap_or("T".to_string()));
477 new_snippet.push('>');
479 return Some((sugg_span, new_snippet));
486 #[derive(Copy, Clone, Debug)]
489 binding_mode: BindingMode,
492 /// Map from the name in a pattern to its binding mode.
493 type BindingMap = FxHashMap<Ident, BindingInfo>;
495 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
506 fn descr(self) -> &'static str {
508 PatternSource::Match => "match binding",
509 PatternSource::IfLet => "if let binding",
510 PatternSource::WhileLet => "while let binding",
511 PatternSource::Let => "let binding",
512 PatternSource::For => "for binding",
513 PatternSource::FnParam => "function parameter",
518 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
519 enum AliasPossibility {
524 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
525 enum PathSource<'a> {
526 // Type paths `Path`.
528 // Trait paths in bounds or impls.
529 Trait(AliasPossibility),
530 // Expression paths `path`, with optional parent context.
531 Expr(Option<&'a Expr>),
532 // Paths in path patterns `Path`.
534 // Paths in struct expressions and patterns `Path { .. }`.
536 // Paths in tuple struct patterns `Path(..)`.
538 // `m::A::B` in `<T as m::A>::B::C`.
539 TraitItem(Namespace),
540 // Path in `pub(path)`
542 // Path in `use a::b::{...};`
546 impl<'a> PathSource<'a> {
547 fn namespace(self) -> Namespace {
549 PathSource::Type | PathSource::Trait(_) | PathSource::Struct |
550 PathSource::Visibility | PathSource::ImportPrefix => TypeNS,
551 PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct => ValueNS,
552 PathSource::TraitItem(ns) => ns,
556 fn global_by_default(self) -> bool {
558 PathSource::Visibility | PathSource::ImportPrefix => true,
559 PathSource::Type | PathSource::Expr(..) | PathSource::Pat |
560 PathSource::Struct | PathSource::TupleStruct |
561 PathSource::Trait(_) | PathSource::TraitItem(..) => false,
565 fn defer_to_typeck(self) -> bool {
567 PathSource::Type | PathSource::Expr(..) | PathSource::Pat |
568 PathSource::Struct | PathSource::TupleStruct => true,
569 PathSource::Trait(_) | PathSource::TraitItem(..) |
570 PathSource::Visibility | PathSource::ImportPrefix => false,
574 fn descr_expected(self) -> &'static str {
576 PathSource::Type => "type",
577 PathSource::Trait(_) => "trait",
578 PathSource::Pat => "unit struct/variant or constant",
579 PathSource::Struct => "struct, variant or union type",
580 PathSource::TupleStruct => "tuple struct/variant",
581 PathSource::Visibility => "module",
582 PathSource::ImportPrefix => "module or enum",
583 PathSource::TraitItem(ns) => match ns {
584 TypeNS => "associated type",
585 ValueNS => "method or associated constant",
586 MacroNS => bug!("associated macro"),
588 PathSource::Expr(parent) => match parent.map(|p| &p.node) {
589 // "function" here means "anything callable" rather than `Def::Fn`,
590 // this is not precise but usually more helpful than just "value".
591 Some(&ExprKind::Call(..)) => "function",
597 fn is_expected(self, def: Def) -> bool {
599 PathSource::Type => match def {
600 Def::Struct(..) | Def::Union(..) | Def::Enum(..) |
601 Def::Trait(..) | Def::TyAlias(..) | Def::AssociatedTy(..) |
602 Def::PrimTy(..) | Def::TyParam(..) | Def::SelfTy(..) |
603 Def::TyForeign(..) => true,
606 PathSource::Trait(AliasPossibility::No) => match def {
607 Def::Trait(..) => true,
610 PathSource::Trait(AliasPossibility::Maybe) => match def {
611 Def::Trait(..) => true,
612 Def::TraitAlias(..) => true,
615 PathSource::Expr(..) => match def {
616 Def::StructCtor(_, CtorKind::Const) | Def::StructCtor(_, CtorKind::Fn) |
617 Def::VariantCtor(_, CtorKind::Const) | Def::VariantCtor(_, CtorKind::Fn) |
618 Def::Const(..) | Def::Static(..) | Def::Local(..) | Def::Upvar(..) |
619 Def::Fn(..) | Def::Method(..) | Def::AssociatedConst(..) => true,
622 PathSource::Pat => match def {
623 Def::StructCtor(_, CtorKind::Const) |
624 Def::VariantCtor(_, CtorKind::Const) |
625 Def::Const(..) | Def::AssociatedConst(..) => true,
628 PathSource::TupleStruct => match def {
629 Def::StructCtor(_, CtorKind::Fn) | Def::VariantCtor(_, CtorKind::Fn) => true,
632 PathSource::Struct => match def {
633 Def::Struct(..) | Def::Union(..) | Def::Variant(..) |
634 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => true,
637 PathSource::TraitItem(ns) => match def {
638 Def::AssociatedConst(..) | Def::Method(..) if ns == ValueNS => true,
639 Def::AssociatedTy(..) if ns == TypeNS => true,
642 PathSource::ImportPrefix => match def {
643 Def::Mod(..) | Def::Enum(..) => true,
646 PathSource::Visibility => match def {
647 Def::Mod(..) => true,
653 fn error_code(self, has_unexpected_resolution: bool) -> &'static str {
654 __diagnostic_used!(E0404);
655 __diagnostic_used!(E0405);
656 __diagnostic_used!(E0412);
657 __diagnostic_used!(E0422);
658 __diagnostic_used!(E0423);
659 __diagnostic_used!(E0425);
660 __diagnostic_used!(E0531);
661 __diagnostic_used!(E0532);
662 __diagnostic_used!(E0573);
663 __diagnostic_used!(E0574);
664 __diagnostic_used!(E0575);
665 __diagnostic_used!(E0576);
666 __diagnostic_used!(E0577);
667 __diagnostic_used!(E0578);
668 match (self, has_unexpected_resolution) {
669 (PathSource::Trait(_), true) => "E0404",
670 (PathSource::Trait(_), false) => "E0405",
671 (PathSource::Type, true) => "E0573",
672 (PathSource::Type, false) => "E0412",
673 (PathSource::Struct, true) => "E0574",
674 (PathSource::Struct, false) => "E0422",
675 (PathSource::Expr(..), true) => "E0423",
676 (PathSource::Expr(..), false) => "E0425",
677 (PathSource::Pat, true) | (PathSource::TupleStruct, true) => "E0532",
678 (PathSource::Pat, false) | (PathSource::TupleStruct, false) => "E0531",
679 (PathSource::TraitItem(..), true) => "E0575",
680 (PathSource::TraitItem(..), false) => "E0576",
681 (PathSource::Visibility, true) | (PathSource::ImportPrefix, true) => "E0577",
682 (PathSource::Visibility, false) | (PathSource::ImportPrefix, false) => "E0578",
687 /// Different kinds of symbols don't influence each other.
689 /// Therefore, they have a separate universe (namespace).
690 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
697 /// Just a helper ‒ separate structure for each namespace.
698 #[derive(Clone, Default, Debug)]
699 pub struct PerNS<T> {
705 impl<T> ::std::ops::Index<Namespace> for PerNS<T> {
707 fn index(&self, ns: Namespace) -> &T {
709 ValueNS => &self.value_ns,
710 TypeNS => &self.type_ns,
711 MacroNS => &self.macro_ns,
716 impl<T> ::std::ops::IndexMut<Namespace> for PerNS<T> {
717 fn index_mut(&mut self, ns: Namespace) -> &mut T {
719 ValueNS => &mut self.value_ns,
720 TypeNS => &mut self.type_ns,
721 MacroNS => &mut self.macro_ns,
726 struct UsePlacementFinder {
727 target_module: NodeId,
732 impl UsePlacementFinder {
733 fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, bool) {
734 let mut finder = UsePlacementFinder {
739 visit::walk_crate(&mut finder, krate);
740 (finder.span, finder.found_use)
744 impl<'tcx> Visitor<'tcx> for UsePlacementFinder {
747 module: &'tcx ast::Mod,
749 _: &[ast::Attribute],
752 if self.span.is_some() {
755 if node_id != self.target_module {
756 visit::walk_mod(self, module);
759 // find a use statement
760 for item in &module.items {
762 ItemKind::Use(..) => {
763 // don't suggest placing a use before the prelude
764 // import or other generated ones
765 if item.span.ctxt().outer().expn_info().is_none() {
766 self.span = Some(item.span.shrink_to_lo());
767 self.found_use = true;
771 // don't place use before extern crate
772 ItemKind::ExternCrate(_) => {}
773 // but place them before the first other item
774 _ => if self.span.map_or(true, |span| item.span < span ) {
775 if item.span.ctxt().outer().expn_info().is_none() {
776 // don't insert between attributes and an item
777 if item.attrs.is_empty() {
778 self.span = Some(item.span.shrink_to_lo());
780 // find the first attribute on the item
781 for attr in &item.attrs {
782 if self.span.map_or(true, |span| attr.span < span) {
783 self.span = Some(attr.span.shrink_to_lo());
794 /// This thing walks the whole crate in DFS manner, visiting each item, resolving names as it goes.
795 impl<'a, 'tcx> Visitor<'tcx> for Resolver<'a> {
796 fn visit_item(&mut self, item: &'tcx Item) {
797 self.resolve_item(item);
799 fn visit_arm(&mut self, arm: &'tcx Arm) {
800 self.resolve_arm(arm);
802 fn visit_block(&mut self, block: &'tcx Block) {
803 self.resolve_block(block);
805 fn visit_anon_const(&mut self, constant: &'tcx ast::AnonConst) {
806 self.with_constant_rib(|this| {
807 visit::walk_anon_const(this, constant);
810 fn visit_expr(&mut self, expr: &'tcx Expr) {
811 self.resolve_expr(expr, None);
813 fn visit_local(&mut self, local: &'tcx Local) {
814 self.resolve_local(local);
816 fn visit_ty(&mut self, ty: &'tcx Ty) {
818 TyKind::Path(ref qself, ref path) => {
819 self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
821 TyKind::ImplicitSelf => {
822 let self_ty = keywords::SelfType.ident();
823 let def = self.resolve_ident_in_lexical_scope(self_ty, TypeNS, true, ty.span)
824 .map_or(Def::Err, |d| d.def());
825 self.record_def(ty.id, PathResolution::new(def));
829 visit::walk_ty(self, ty);
831 fn visit_poly_trait_ref(&mut self,
832 tref: &'tcx ast::PolyTraitRef,
833 m: &'tcx ast::TraitBoundModifier) {
834 self.smart_resolve_path(tref.trait_ref.ref_id, None,
835 &tref.trait_ref.path, PathSource::Trait(AliasPossibility::Maybe));
836 visit::walk_poly_trait_ref(self, tref, m);
838 fn visit_foreign_item(&mut self, foreign_item: &'tcx ForeignItem) {
839 let type_parameters = match foreign_item.node {
840 ForeignItemKind::Fn(_, ref generics) => {
841 HasTypeParameters(generics, ItemRibKind)
843 ForeignItemKind::Static(..) => NoTypeParameters,
844 ForeignItemKind::Ty => NoTypeParameters,
845 ForeignItemKind::Macro(..) => NoTypeParameters,
847 self.with_type_parameter_rib(type_parameters, |this| {
848 visit::walk_foreign_item(this, foreign_item);
851 fn visit_fn(&mut self,
852 function_kind: FnKind<'tcx>,
853 declaration: &'tcx FnDecl,
856 let rib_kind = match function_kind {
857 FnKind::ItemFn(..) => {
860 FnKind::Method(_, _, _, _) => {
861 TraitOrImplItemRibKind
863 FnKind::Closure(_) => ClosureRibKind(node_id),
866 // Create a value rib for the function.
867 self.ribs[ValueNS].push(Rib::new(rib_kind));
869 // Create a label rib for the function.
870 self.label_ribs.push(Rib::new(rib_kind));
872 // Add each argument to the rib.
873 let mut bindings_list = FxHashMap();
874 for argument in &declaration.inputs {
875 self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
877 self.visit_ty(&argument.ty);
879 debug!("(resolving function) recorded argument");
881 visit::walk_fn_ret_ty(self, &declaration.output);
883 // Resolve the function body.
884 match function_kind {
885 FnKind::ItemFn(.., body) |
886 FnKind::Method(.., body) => {
887 self.visit_block(body);
889 FnKind::Closure(body) => {
890 self.visit_expr(body);
894 debug!("(resolving function) leaving function");
896 self.label_ribs.pop();
897 self.ribs[ValueNS].pop();
899 fn visit_generics(&mut self, generics: &'tcx Generics) {
900 // For type parameter defaults, we have to ban access
901 // to following type parameters, as the Substs can only
902 // provide previous type parameters as they're built. We
903 // put all the parameters on the ban list and then remove
904 // them one by one as they are processed and become available.
905 let mut default_ban_rib = Rib::new(ForwardTyParamBanRibKind);
906 default_ban_rib.bindings.extend(generics.params.iter()
907 .filter_map(|p| if let GenericParam::Type(ref tp) = *p { Some(tp) } else { None })
908 .skip_while(|p| p.default.is_none())
909 .map(|p| (Ident::with_empty_ctxt(p.ident.name), Def::Err)));
911 for param in &generics.params {
913 GenericParam::Lifetime(_) => self.visit_generic_param(param),
914 GenericParam::Type(ref ty_param) => {
915 for bound in &ty_param.bounds {
916 self.visit_ty_param_bound(bound);
919 if let Some(ref ty) = ty_param.default {
920 self.ribs[TypeNS].push(default_ban_rib);
922 default_ban_rib = self.ribs[TypeNS].pop().unwrap();
925 // Allow all following defaults to refer to this type parameter.
926 default_ban_rib.bindings.remove(&Ident::with_empty_ctxt(ty_param.ident.name));
930 for p in &generics.where_clause.predicates { self.visit_where_predicate(p); }
934 #[derive(Copy, Clone)]
935 enum TypeParameters<'a, 'b> {
937 HasTypeParameters(// Type parameters.
940 // The kind of the rib used for type parameters.
944 /// The rib kind controls the translation of local
945 /// definitions (`Def::Local`) to upvars (`Def::Upvar`).
946 #[derive(Copy, Clone, Debug)]
948 /// No translation needs to be applied.
951 /// We passed through a closure scope at the given node ID.
952 /// Translate upvars as appropriate.
953 ClosureRibKind(NodeId /* func id */),
955 /// We passed through an impl or trait and are now in one of its
956 /// methods or associated types. Allow references to ty params that impl or trait
957 /// binds. Disallow any other upvars (including other ty params that are
959 TraitOrImplItemRibKind,
961 /// We passed through an item scope. Disallow upvars.
964 /// We're in a constant item. Can't refer to dynamic stuff.
967 /// We passed through a module.
968 ModuleRibKind(Module<'a>),
970 /// We passed through a `macro_rules!` statement
971 MacroDefinition(DefId),
973 /// All bindings in this rib are type parameters that can't be used
974 /// from the default of a type parameter because they're not declared
975 /// before said type parameter. Also see the `visit_generics` override.
976 ForwardTyParamBanRibKind,
981 /// A rib represents a scope names can live in. Note that these appear in many places, not just
982 /// around braces. At any place where the list of accessible names (of the given namespace)
983 /// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
984 /// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
987 /// Different [rib kinds](enum.RibKind) are transparent for different names.
989 /// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
990 /// resolving, the name is looked up from inside out.
993 bindings: FxHashMap<Ident, Def>,
998 fn new(kind: RibKind<'a>) -> Rib<'a> {
1000 bindings: FxHashMap(),
1006 /// An intermediate resolution result.
1008 /// This refers to the thing referred by a name. The difference between `Def` and `Item` is that
1009 /// items are visible in their whole block, while defs only from the place they are defined
1011 enum LexicalScopeBinding<'a> {
1012 Item(&'a NameBinding<'a>),
1016 impl<'a> LexicalScopeBinding<'a> {
1017 fn item(self) -> Option<&'a NameBinding<'a>> {
1019 LexicalScopeBinding::Item(binding) => Some(binding),
1024 fn def(self) -> Def {
1026 LexicalScopeBinding::Item(binding) => binding.def(),
1027 LexicalScopeBinding::Def(def) => def,
1032 #[derive(Clone, Debug)]
1033 enum PathResult<'a> {
1035 NonModule(PathResolution),
1037 Failed(Span, String, bool /* is the error from the last segment? */),
1041 /// An anonymous module, eg. just a block.
1045 /// fn f() {} // (1)
1046 /// { // This is an anonymous module
1047 /// f(); // This resolves to (2) as we are inside the block.
1048 /// fn f() {} // (2)
1050 /// f(); // Resolves to (1)
1054 /// Any module with a name.
1058 /// * A normal module ‒ either `mod from_file;` or `mod from_block { }`.
1059 /// * A trait or an enum (it implicitly contains associated types, methods and variant
1064 /// One node in the tree of modules.
1065 pub struct ModuleData<'a> {
1066 parent: Option<Module<'a>>,
1069 // The def id of the closest normal module (`mod`) ancestor (including this module).
1070 normal_ancestor_id: DefId,
1072 resolutions: RefCell<FxHashMap<(Ident, Namespace), &'a RefCell<NameResolution<'a>>>>,
1073 legacy_macro_resolutions: RefCell<Vec<(Mark, Ident, Span, MacroKind)>>,
1074 macro_resolutions: RefCell<Vec<(Box<[Ident]>, Span)>>,
1076 // Macro invocations that can expand into items in this module.
1077 unresolved_invocations: RefCell<FxHashSet<Mark>>,
1079 no_implicit_prelude: bool,
1081 glob_importers: RefCell<Vec<&'a ImportDirective<'a>>>,
1082 globs: RefCell<Vec<&'a ImportDirective<'a>>>,
1084 // Used to memoize the traits in this module for faster searches through all traits in scope.
1085 traits: RefCell<Option<Box<[(Ident, &'a NameBinding<'a>)]>>>,
1087 // Whether this module is populated. If not populated, any attempt to
1088 // access the children must be preceded with a
1089 // `populate_module_if_necessary` call.
1090 populated: Cell<bool>,
1092 /// Span of the module itself. Used for error reporting.
1098 type Module<'a> = &'a ModuleData<'a>;
1100 impl<'a> ModuleData<'a> {
1101 fn new(parent: Option<Module<'a>>,
1103 normal_ancestor_id: DefId,
1105 span: Span) -> Self {
1110 resolutions: RefCell::new(FxHashMap()),
1111 legacy_macro_resolutions: RefCell::new(Vec::new()),
1112 macro_resolutions: RefCell::new(Vec::new()),
1113 unresolved_invocations: RefCell::new(FxHashSet()),
1114 no_implicit_prelude: false,
1115 glob_importers: RefCell::new(Vec::new()),
1116 globs: RefCell::new(Vec::new()),
1117 traits: RefCell::new(None),
1118 populated: Cell::new(normal_ancestor_id.is_local()),
1124 fn for_each_child<F: FnMut(Ident, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
1125 for (&(ident, ns), name_resolution) in self.resolutions.borrow().iter() {
1126 name_resolution.borrow().binding.map(|binding| f(ident, ns, binding));
1130 fn for_each_child_stable<F: FnMut(Ident, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
1131 let resolutions = self.resolutions.borrow();
1132 let mut resolutions = resolutions.iter().collect::<Vec<_>>();
1133 resolutions.sort_by_cached_key(|&(&(ident, ns), _)| (ident.name.as_str(), ns));
1134 for &(&(ident, ns), &resolution) in resolutions.iter() {
1135 resolution.borrow().binding.map(|binding| f(ident, ns, binding));
1139 fn def(&self) -> Option<Def> {
1141 ModuleKind::Def(def, _) => Some(def),
1146 fn def_id(&self) -> Option<DefId> {
1147 self.def().as_ref().map(Def::def_id)
1150 // `self` resolves to the first module ancestor that `is_normal`.
1151 fn is_normal(&self) -> bool {
1153 ModuleKind::Def(Def::Mod(_), _) => true,
1158 fn is_trait(&self) -> bool {
1160 ModuleKind::Def(Def::Trait(_), _) => true,
1165 fn is_local(&self) -> bool {
1166 self.normal_ancestor_id.is_local()
1169 fn nearest_item_scope(&'a self) -> Module<'a> {
1170 if self.is_trait() { self.parent.unwrap() } else { self }
1174 impl<'a> fmt::Debug for ModuleData<'a> {
1175 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1176 write!(f, "{:?}", self.def())
1180 /// Records a possibly-private value, type, or module definition.
1181 #[derive(Clone, Debug)]
1182 pub struct NameBinding<'a> {
1183 kind: NameBindingKind<'a>,
1186 vis: ty::Visibility,
1189 pub trait ToNameBinding<'a> {
1190 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a>;
1193 impl<'a> ToNameBinding<'a> for &'a NameBinding<'a> {
1194 fn to_name_binding(self, _: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
1199 #[derive(Clone, Debug)]
1200 enum NameBindingKind<'a> {
1204 binding: &'a NameBinding<'a>,
1205 directive: &'a ImportDirective<'a>,
1209 b1: &'a NameBinding<'a>,
1210 b2: &'a NameBinding<'a>,
1214 struct PrivacyError<'a>(Span, Name, &'a NameBinding<'a>);
1216 struct UseError<'a> {
1217 err: DiagnosticBuilder<'a>,
1218 /// Attach `use` statements for these candidates
1219 candidates: Vec<ImportSuggestion>,
1220 /// The node id of the module to place the use statements in
1222 /// Whether the diagnostic should state that it's "better"
1226 struct AmbiguityError<'a> {
1230 b1: &'a NameBinding<'a>,
1231 b2: &'a NameBinding<'a>,
1234 impl<'a> NameBinding<'a> {
1235 fn module(&self) -> Option<Module<'a>> {
1237 NameBindingKind::Module(module) => Some(module),
1238 NameBindingKind::Import { binding, .. } => binding.module(),
1243 fn def(&self) -> Def {
1245 NameBindingKind::Def(def) => def,
1246 NameBindingKind::Module(module) => module.def().unwrap(),
1247 NameBindingKind::Import { binding, .. } => binding.def(),
1248 NameBindingKind::Ambiguity { .. } => Def::Err,
1252 fn def_ignoring_ambiguity(&self) -> Def {
1254 NameBindingKind::Import { binding, .. } => binding.def_ignoring_ambiguity(),
1255 NameBindingKind::Ambiguity { b1, .. } => b1.def_ignoring_ambiguity(),
1260 fn get_macro(&self, resolver: &mut Resolver<'a>) -> Lrc<SyntaxExtension> {
1261 resolver.get_macro(self.def_ignoring_ambiguity())
1264 // We sometimes need to treat variants as `pub` for backwards compatibility
1265 fn pseudo_vis(&self) -> ty::Visibility {
1266 if self.is_variant() && self.def().def_id().is_local() {
1267 ty::Visibility::Public
1273 fn is_variant(&self) -> bool {
1275 NameBindingKind::Def(Def::Variant(..)) |
1276 NameBindingKind::Def(Def::VariantCtor(..)) => true,
1281 fn is_extern_crate(&self) -> bool {
1283 NameBindingKind::Import {
1284 directive: &ImportDirective {
1285 subclass: ImportDirectiveSubclass::ExternCrate(_), ..
1292 fn is_import(&self) -> bool {
1294 NameBindingKind::Import { .. } => true,
1299 fn is_renamed_extern_crate(&self) -> bool {
1300 if let NameBindingKind::Import { directive, ..} = self.kind {
1301 if let ImportDirectiveSubclass::ExternCrate(Some(_)) = directive.subclass {
1308 fn is_glob_import(&self) -> bool {
1310 NameBindingKind::Import { directive, .. } => directive.is_glob(),
1311 NameBindingKind::Ambiguity { b1, .. } => b1.is_glob_import(),
1316 fn is_importable(&self) -> bool {
1318 Def::AssociatedConst(..) | Def::Method(..) | Def::AssociatedTy(..) => false,
1323 fn is_macro_def(&self) -> bool {
1325 NameBindingKind::Def(Def::Macro(..)) => true,
1330 fn descr(&self) -> &'static str {
1331 if self.is_extern_crate() { "extern crate" } else { self.def().kind_name() }
1335 /// Interns the names of the primitive types.
1337 /// All other types are defined somewhere and possibly imported, but the primitive ones need
1338 /// special handling, since they have no place of origin.
1339 struct PrimitiveTypeTable {
1340 primitive_types: FxHashMap<Name, PrimTy>,
1343 impl PrimitiveTypeTable {
1344 fn new() -> PrimitiveTypeTable {
1345 let mut table = PrimitiveTypeTable { primitive_types: FxHashMap() };
1347 table.intern("bool", TyBool);
1348 table.intern("char", TyChar);
1349 table.intern("f32", TyFloat(FloatTy::F32));
1350 table.intern("f64", TyFloat(FloatTy::F64));
1351 table.intern("isize", TyInt(IntTy::Isize));
1352 table.intern("i8", TyInt(IntTy::I8));
1353 table.intern("i16", TyInt(IntTy::I16));
1354 table.intern("i32", TyInt(IntTy::I32));
1355 table.intern("i64", TyInt(IntTy::I64));
1356 table.intern("i128", TyInt(IntTy::I128));
1357 table.intern("str", TyStr);
1358 table.intern("usize", TyUint(UintTy::Usize));
1359 table.intern("u8", TyUint(UintTy::U8));
1360 table.intern("u16", TyUint(UintTy::U16));
1361 table.intern("u32", TyUint(UintTy::U32));
1362 table.intern("u64", TyUint(UintTy::U64));
1363 table.intern("u128", TyUint(UintTy::U128));
1367 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1368 self.primitive_types.insert(Symbol::intern(string), primitive_type);
1372 /// The main resolver class.
1374 /// This is the visitor that walks the whole crate.
1375 pub struct Resolver<'a> {
1376 session: &'a Session,
1377 cstore: &'a CrateStore,
1379 pub definitions: Definitions,
1381 graph_root: Module<'a>,
1383 prelude: Option<Module<'a>>,
1384 extern_prelude: FxHashSet<Name>,
1386 /// n.b. This is used only for better diagnostics, not name resolution itself.
1387 has_self: FxHashSet<DefId>,
1389 /// Names of fields of an item `DefId` accessible with dot syntax.
1390 /// Used for hints during error reporting.
1391 field_names: FxHashMap<DefId, Vec<Name>>,
1393 /// All imports known to succeed or fail.
1394 determined_imports: Vec<&'a ImportDirective<'a>>,
1396 /// All non-determined imports.
1397 indeterminate_imports: Vec<&'a ImportDirective<'a>>,
1399 /// The module that represents the current item scope.
1400 current_module: Module<'a>,
1402 /// The current set of local scopes for types and values.
1403 /// FIXME #4948: Reuse ribs to avoid allocation.
1404 ribs: PerNS<Vec<Rib<'a>>>,
1406 /// The current set of local scopes, for labels.
1407 label_ribs: Vec<Rib<'a>>,
1409 /// The trait that the current context can refer to.
1410 current_trait_ref: Option<(Module<'a>, TraitRef)>,
1412 /// The current self type if inside an impl (used for better errors).
1413 current_self_type: Option<Ty>,
1415 /// The idents for the primitive types.
1416 primitive_type_table: PrimitiveTypeTable,
1419 pub freevars: FreevarMap,
1420 freevars_seen: NodeMap<NodeMap<usize>>,
1421 pub export_map: ExportMap,
1422 pub trait_map: TraitMap,
1424 /// A map from nodes to anonymous modules.
1425 /// Anonymous modules are pseudo-modules that are implicitly created around items
1426 /// contained within blocks.
1428 /// For example, if we have this:
1436 /// There will be an anonymous module created around `g` with the ID of the
1437 /// entry block for `f`.
1438 block_map: NodeMap<Module<'a>>,
1439 module_map: FxHashMap<DefId, Module<'a>>,
1440 extern_module_map: FxHashMap<(DefId, bool /* MacrosOnly? */), Module<'a>>,
1442 pub make_glob_map: bool,
1443 /// Maps imports to the names of items actually imported (this actually maps
1444 /// all imports, but only glob imports are actually interesting).
1445 pub glob_map: GlobMap,
1447 used_imports: FxHashSet<(NodeId, Namespace)>,
1448 pub maybe_unused_trait_imports: NodeSet,
1449 pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
1451 /// A list of labels as of yet unused. Labels will be removed from this map when
1452 /// they are used (in a `break` or `continue` statement)
1453 pub unused_labels: FxHashMap<NodeId, Span>,
1455 /// privacy errors are delayed until the end in order to deduplicate them
1456 privacy_errors: Vec<PrivacyError<'a>>,
1457 /// ambiguity errors are delayed for deduplication
1458 ambiguity_errors: Vec<AmbiguityError<'a>>,
1459 /// `use` injections are delayed for better placement and deduplication
1460 use_injections: Vec<UseError<'a>>,
1461 /// `use` injections for proc macros wrongly imported with #[macro_use]
1462 proc_mac_errors: Vec<macros::ProcMacError>,
1464 gated_errors: FxHashSet<Span>,
1465 disallowed_shadowing: Vec<&'a LegacyBinding<'a>>,
1467 arenas: &'a ResolverArenas<'a>,
1468 dummy_binding: &'a NameBinding<'a>,
1469 /// true if `#![feature(use_extern_macros)]`
1470 use_extern_macros: bool,
1472 crate_loader: &'a mut CrateLoader,
1473 macro_names: FxHashSet<Ident>,
1474 global_macros: FxHashMap<Name, &'a NameBinding<'a>>,
1475 pub all_macros: FxHashMap<Name, Def>,
1476 lexical_macro_resolutions: Vec<(Ident, &'a Cell<LegacyScope<'a>>)>,
1477 macro_map: FxHashMap<DefId, Lrc<SyntaxExtension>>,
1478 macro_defs: FxHashMap<Mark, DefId>,
1479 local_macro_def_scopes: FxHashMap<NodeId, Module<'a>>,
1480 macro_exports: Vec<Export>,
1481 pub whitelisted_legacy_custom_derives: Vec<Name>,
1482 pub found_unresolved_macro: bool,
1484 /// List of crate local macros that we need to warn about as being unused.
1485 /// Right now this only includes macro_rules! macros, and macros 2.0.
1486 unused_macros: FxHashSet<DefId>,
1488 /// Maps the `Mark` of an expansion to its containing module or block.
1489 invocations: FxHashMap<Mark, &'a InvocationData<'a>>,
1491 /// Avoid duplicated errors for "name already defined".
1492 name_already_seen: FxHashMap<Name, Span>,
1494 /// If `#![feature(proc_macro)]` is set
1495 proc_macro_enabled: bool,
1497 /// A set of procedural macros imported by `#[macro_use]` that have already been warned about
1498 warned_proc_macros: FxHashSet<Name>,
1500 potentially_unused_imports: Vec<&'a ImportDirective<'a>>,
1502 /// This table maps struct IDs into struct constructor IDs,
1503 /// it's not used during normal resolution, only for better error reporting.
1504 struct_constructors: DefIdMap<(Def, ty::Visibility)>,
1506 /// Only used for better errors on `fn(): fn()`
1507 current_type_ascription: Vec<Span>,
1509 injected_crate: Option<Module<'a>>,
1512 /// Nothing really interesting here, it just provides memory for the rest of the crate.
1513 pub struct ResolverArenas<'a> {
1514 modules: arena::TypedArena<ModuleData<'a>>,
1515 local_modules: RefCell<Vec<Module<'a>>>,
1516 name_bindings: arena::TypedArena<NameBinding<'a>>,
1517 import_directives: arena::TypedArena<ImportDirective<'a>>,
1518 name_resolutions: arena::TypedArena<RefCell<NameResolution<'a>>>,
1519 invocation_data: arena::TypedArena<InvocationData<'a>>,
1520 legacy_bindings: arena::TypedArena<LegacyBinding<'a>>,
1523 impl<'a> ResolverArenas<'a> {
1524 fn alloc_module(&'a self, module: ModuleData<'a>) -> Module<'a> {
1525 let module = self.modules.alloc(module);
1526 if module.def_id().map(|def_id| def_id.is_local()).unwrap_or(true) {
1527 self.local_modules.borrow_mut().push(module);
1531 fn local_modules(&'a self) -> ::std::cell::Ref<'a, Vec<Module<'a>>> {
1532 self.local_modules.borrow()
1534 fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
1535 self.name_bindings.alloc(name_binding)
1537 fn alloc_import_directive(&'a self, import_directive: ImportDirective<'a>)
1538 -> &'a ImportDirective {
1539 self.import_directives.alloc(import_directive)
1541 fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
1542 self.name_resolutions.alloc(Default::default())
1544 fn alloc_invocation_data(&'a self, expansion_data: InvocationData<'a>)
1545 -> &'a InvocationData<'a> {
1546 self.invocation_data.alloc(expansion_data)
1548 fn alloc_legacy_binding(&'a self, binding: LegacyBinding<'a>) -> &'a LegacyBinding<'a> {
1549 self.legacy_bindings.alloc(binding)
1553 impl<'a, 'b: 'a> ty::DefIdTree for &'a Resolver<'b> {
1554 fn parent(self, id: DefId) -> Option<DefId> {
1556 LOCAL_CRATE => self.definitions.def_key(id.index).parent,
1557 _ => self.cstore.def_key(id).parent,
1558 }.map(|index| DefId { index, ..id })
1562 /// This interface is used through the AST→HIR step, to embed full paths into the HIR. After that
1563 /// the resolver is no longer needed as all the relevant information is inline.
1564 impl<'a> hir::lowering::Resolver for Resolver<'a> {
1565 fn resolve_hir_path(&mut self, path: &mut hir::Path, is_value: bool) {
1566 self.resolve_hir_path_cb(path, is_value,
1567 |resolver, span, error| resolve_error(resolver, span, error))
1570 fn resolve_str_path(&mut self, span: Span, crate_root: Option<&str>,
1571 components: &[&str], is_value: bool) -> hir::Path {
1572 let mut path = hir::Path {
1575 segments: iter::once(keywords::CrateRoot.name()).chain({
1576 crate_root.into_iter().chain(components.iter().cloned()).map(Symbol::intern)
1577 }).map(hir::PathSegment::from_name).collect(),
1580 self.resolve_hir_path(&mut path, is_value);
1584 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution> {
1585 self.def_map.get(&id).cloned()
1588 fn definitions(&mut self) -> &mut Definitions {
1589 &mut self.definitions
1593 impl<'a> Resolver<'a> {
1594 /// Rustdoc uses this to resolve things in a recoverable way. ResolutionError<'a>
1595 /// isn't something that can be returned because it can't be made to live that long,
1596 /// and also it's a private type. Fortunately rustdoc doesn't need to know the error,
1597 /// just that an error occurred.
1598 pub fn resolve_str_path_error(&mut self, span: Span, path_str: &str, is_value: bool)
1599 -> Result<hir::Path, ()> {
1601 let mut errored = false;
1603 let mut path = if path_str.starts_with("::") {
1607 segments: iter::once(keywords::CrateRoot.name()).chain({
1608 path_str.split("::").skip(1).map(Symbol::intern)
1609 }).map(hir::PathSegment::from_name).collect(),
1615 segments: path_str.split("::").map(Symbol::intern)
1616 .map(hir::PathSegment::from_name).collect(),
1619 self.resolve_hir_path_cb(&mut path, is_value, |_, _, _| errored = true);
1620 if errored || path.def == Def::Err {
1627 /// resolve_hir_path, but takes a callback in case there was an error
1628 fn resolve_hir_path_cb<F>(&mut self, path: &mut hir::Path, is_value: bool, error_callback: F)
1629 where F: for<'c, 'b> FnOnce(&'c mut Resolver, Span, ResolutionError<'b>)
1631 let namespace = if is_value { ValueNS } else { TypeNS };
1632 let hir::Path { ref segments, span, ref mut def } = *path;
1633 let path: Vec<Ident> = segments.iter()
1634 .map(|seg| Ident::new(seg.name, span))
1636 // FIXME (Manishearth): Intra doc links won't get warned of epoch changes
1637 match self.resolve_path(&path, Some(namespace), true, span, None) {
1638 PathResult::Module(module) => *def = module.def().unwrap(),
1639 PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 =>
1640 *def = path_res.base_def(),
1641 PathResult::NonModule(..) => match self.resolve_path(&path, None, true, span, None) {
1642 PathResult::Failed(span, msg, _) => {
1643 error_callback(self, span, ResolutionError::FailedToResolve(&msg));
1647 PathResult::Indeterminate => unreachable!(),
1648 PathResult::Failed(span, msg, _) => {
1649 error_callback(self, span, ResolutionError::FailedToResolve(&msg));
1655 impl<'a> Resolver<'a> {
1656 pub fn new(session: &'a Session,
1657 cstore: &'a CrateStore,
1660 make_glob_map: MakeGlobMap,
1661 crate_loader: &'a mut CrateLoader,
1662 arenas: &'a ResolverArenas<'a>)
1664 let root_def_id = DefId::local(CRATE_DEF_INDEX);
1665 let root_module_kind = ModuleKind::Def(Def::Mod(root_def_id), keywords::Invalid.name());
1666 let graph_root = arenas.alloc_module(ModuleData {
1667 no_implicit_prelude: attr::contains_name(&krate.attrs, "no_implicit_prelude"),
1668 ..ModuleData::new(None, root_module_kind, root_def_id, Mark::root(), krate.span)
1670 let mut module_map = FxHashMap();
1671 module_map.insert(DefId::local(CRATE_DEF_INDEX), graph_root);
1673 let mut definitions = Definitions::new();
1674 DefCollector::new(&mut definitions, Mark::root())
1675 .collect_root(crate_name, session.local_crate_disambiguator());
1677 let mut invocations = FxHashMap();
1678 invocations.insert(Mark::root(),
1679 arenas.alloc_invocation_data(InvocationData::root(graph_root)));
1681 let features = session.features_untracked();
1683 let mut macro_defs = FxHashMap();
1684 macro_defs.insert(Mark::root(), root_def_id);
1693 // The outermost module has def ID 0; this is not reflected in the
1697 extern_prelude: session.opts.externs.iter().map(|kv| Symbol::intern(kv.0)).collect(),
1699 has_self: FxHashSet(),
1700 field_names: FxHashMap(),
1702 determined_imports: Vec::new(),
1703 indeterminate_imports: Vec::new(),
1705 current_module: graph_root,
1707 value_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1708 type_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1709 macro_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1711 label_ribs: Vec::new(),
1713 current_trait_ref: None,
1714 current_self_type: None,
1716 primitive_type_table: PrimitiveTypeTable::new(),
1719 freevars: NodeMap(),
1720 freevars_seen: NodeMap(),
1721 export_map: FxHashMap(),
1722 trait_map: NodeMap(),
1724 block_map: NodeMap(),
1725 extern_module_map: FxHashMap(),
1727 make_glob_map: make_glob_map == MakeGlobMap::Yes,
1728 glob_map: NodeMap(),
1730 used_imports: FxHashSet(),
1731 maybe_unused_trait_imports: NodeSet(),
1732 maybe_unused_extern_crates: Vec::new(),
1734 unused_labels: FxHashMap(),
1736 privacy_errors: Vec::new(),
1737 ambiguity_errors: Vec::new(),
1738 use_injections: Vec::new(),
1739 proc_mac_errors: Vec::new(),
1740 gated_errors: FxHashSet(),
1741 disallowed_shadowing: Vec::new(),
1744 dummy_binding: arenas.alloc_name_binding(NameBinding {
1745 kind: NameBindingKind::Def(Def::Err),
1746 expansion: Mark::root(),
1748 vis: ty::Visibility::Public,
1751 // The `proc_macro` and `decl_macro` features imply `use_extern_macros`
1753 features.use_extern_macros || features.proc_macro || features.decl_macro,
1756 macro_names: FxHashSet(),
1757 global_macros: FxHashMap(),
1758 all_macros: FxHashMap(),
1759 lexical_macro_resolutions: Vec::new(),
1760 macro_map: FxHashMap(),
1761 macro_exports: Vec::new(),
1764 local_macro_def_scopes: FxHashMap(),
1765 name_already_seen: FxHashMap(),
1766 whitelisted_legacy_custom_derives: Vec::new(),
1767 proc_macro_enabled: features.proc_macro,
1768 warned_proc_macros: FxHashSet(),
1769 potentially_unused_imports: Vec::new(),
1770 struct_constructors: DefIdMap(),
1771 found_unresolved_macro: false,
1772 unused_macros: FxHashSet(),
1773 current_type_ascription: Vec::new(),
1774 injected_crate: None,
1778 pub fn arenas() -> ResolverArenas<'a> {
1780 modules: arena::TypedArena::new(),
1781 local_modules: RefCell::new(Vec::new()),
1782 name_bindings: arena::TypedArena::new(),
1783 import_directives: arena::TypedArena::new(),
1784 name_resolutions: arena::TypedArena::new(),
1785 invocation_data: arena::TypedArena::new(),
1786 legacy_bindings: arena::TypedArena::new(),
1790 /// Runs the function on each namespace.
1791 fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1794 if self.use_extern_macros {
1799 fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1801 match self.macro_defs.get(&ctxt.outer()) {
1802 Some(&def_id) => return def_id,
1803 None => ctxt.remove_mark(),
1808 /// Entry point to crate resolution.
1809 pub fn resolve_crate(&mut self, krate: &Crate) {
1810 ImportResolver { resolver: self }.finalize_imports();
1811 self.current_module = self.graph_root;
1812 self.finalize_current_module_macro_resolutions();
1814 visit::walk_crate(self, krate);
1816 check_unused::check_crate(self, krate);
1817 self.report_errors(krate);
1818 self.crate_loader.postprocess(krate);
1825 normal_ancestor_id: DefId,
1829 let module = ModuleData::new(Some(parent), kind, normal_ancestor_id, expansion, span);
1830 self.arenas.alloc_module(module)
1833 fn record_use(&mut self, ident: Ident, ns: Namespace, binding: &'a NameBinding<'a>, span: Span)
1834 -> bool /* true if an error was reported */ {
1835 match binding.kind {
1836 NameBindingKind::Import { directive, binding, ref used }
1839 directive.used.set(true);
1840 self.used_imports.insert((directive.id, ns));
1841 self.add_to_glob_map(directive.id, ident);
1842 self.record_use(ident, ns, binding, span)
1844 NameBindingKind::Import { .. } => false,
1845 NameBindingKind::Ambiguity { b1, b2 } => {
1846 self.ambiguity_errors.push(AmbiguityError {
1847 span, name: ident.name, lexical: false, b1, b2,
1855 fn add_to_glob_map(&mut self, id: NodeId, ident: Ident) {
1856 if self.make_glob_map {
1857 self.glob_map.entry(id).or_insert_with(FxHashSet).insert(ident.name);
1861 /// This resolves the identifier `ident` in the namespace `ns` in the current lexical scope.
1862 /// More specifically, we proceed up the hierarchy of scopes and return the binding for
1863 /// `ident` in the first scope that defines it (or None if no scopes define it).
1865 /// A block's items are above its local variables in the scope hierarchy, regardless of where
1866 /// the items are defined in the block. For example,
1869 /// g(); // Since there are no local variables in scope yet, this resolves to the item.
1872 /// g(); // This resolves to the local variable `g` since it shadows the item.
1876 /// Invariant: This must only be called during main resolution, not during
1877 /// import resolution.
1878 fn resolve_ident_in_lexical_scope(&mut self,
1883 -> Option<LexicalScopeBinding<'a>> {
1885 ident.span = if ident.name == keywords::SelfType.name() {
1886 // FIXME(jseyfried) improve `Self` hygiene
1887 ident.span.with_ctxt(SyntaxContext::empty())
1893 // Walk backwards up the ribs in scope.
1894 let mut module = self.graph_root;
1895 for i in (0 .. self.ribs[ns].len()).rev() {
1896 if let Some(def) = self.ribs[ns][i].bindings.get(&ident).cloned() {
1897 // The ident resolves to a type parameter or local variable.
1898 return Some(LexicalScopeBinding::Def(
1899 self.adjust_local_def(ns, i, def, record_used, path_span)
1903 module = match self.ribs[ns][i].kind {
1904 ModuleRibKind(module) => module,
1905 MacroDefinition(def) if def == self.macro_def(ident.span.ctxt()) => {
1906 // If an invocation of this macro created `ident`, give up on `ident`
1907 // and switch to `ident`'s source from the macro definition.
1908 ident.span.remove_mark();
1914 let item = self.resolve_ident_in_module_unadjusted(
1915 module, ident, ns, false, record_used, path_span,
1917 if let Ok(binding) = item {
1918 // The ident resolves to an item.
1919 return Some(LexicalScopeBinding::Item(binding));
1923 ModuleKind::Block(..) => {}, // We can see through blocks
1928 ident.span = ident.span.modern();
1930 module = unwrap_or!(self.hygienic_lexical_parent(module, &mut ident.span), break);
1931 let orig_current_module = self.current_module;
1932 self.current_module = module; // Lexical resolutions can never be a privacy error.
1933 let result = self.resolve_ident_in_module_unadjusted(
1934 module, ident, ns, false, record_used, path_span,
1936 self.current_module = orig_current_module;
1939 Ok(binding) => return Some(LexicalScopeBinding::Item(binding)),
1940 Err(Undetermined) => return None,
1941 Err(Determined) => {}
1945 if !module.no_implicit_prelude {
1946 // `record_used` means that we don't try to load crates during speculative resolution
1947 if record_used && ns == TypeNS && self.extern_prelude.contains(&ident.name) {
1948 if !self.session.features_untracked().extern_prelude {
1949 feature_err(&self.session.parse_sess, "extern_prelude",
1950 ident.span, GateIssue::Language,
1951 "access to extern crates through prelude is experimental").emit();
1954 let crate_id = self.crate_loader.process_path_extern(ident.name, ident.span);
1955 let crate_root = self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
1956 self.populate_module_if_necessary(crate_root);
1958 let binding = (crate_root, ty::Visibility::Public,
1959 ident.span, Mark::root()).to_name_binding(self.arenas);
1960 return Some(LexicalScopeBinding::Item(binding));
1962 if let Some(prelude) = self.prelude {
1963 if let Ok(binding) = self.resolve_ident_in_module_unadjusted(prelude, ident, ns,
1964 false, false, path_span) {
1965 return Some(LexicalScopeBinding::Item(binding));
1973 fn hygienic_lexical_parent(&mut self, mut module: Module<'a>, span: &mut Span)
1974 -> Option<Module<'a>> {
1975 if !module.expansion.is_descendant_of(span.ctxt().outer()) {
1976 return Some(self.macro_def_scope(span.remove_mark()));
1979 if let ModuleKind::Block(..) = module.kind {
1980 return Some(module.parent.unwrap());
1983 let mut module_expansion = module.expansion.modern(); // for backward compatibility
1984 while let Some(parent) = module.parent {
1985 let parent_expansion = parent.expansion.modern();
1986 if module_expansion.is_descendant_of(parent_expansion) &&
1987 parent_expansion != module_expansion {
1988 return if parent_expansion.is_descendant_of(span.ctxt().outer()) {
1995 module_expansion = parent_expansion;
2001 fn resolve_ident_in_module(&mut self,
2005 ignore_unresolved_invocations: bool,
2008 -> Result<&'a NameBinding<'a>, Determinacy> {
2009 ident.span = ident.span.modern();
2010 let orig_current_module = self.current_module;
2011 if let Some(def) = ident.span.adjust(module.expansion) {
2012 self.current_module = self.macro_def_scope(def);
2014 let result = self.resolve_ident_in_module_unadjusted(
2015 module, ident, ns, ignore_unresolved_invocations, record_used, span,
2017 self.current_module = orig_current_module;
2021 fn resolve_crate_root(&mut self, mut ctxt: SyntaxContext, legacy: bool) -> Module<'a> {
2022 let mark = if legacy {
2023 // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
2024 // we don't want to pretend that the `macro_rules!` definition is in the `macro`
2025 // as described in `SyntaxContext::apply_mark`, so we ignore prepended modern marks.
2026 ctxt.marks().into_iter().find(|&mark| mark.kind() != MarkKind::Modern)
2028 ctxt = ctxt.modern();
2029 ctxt.adjust(Mark::root())
2031 let module = match mark {
2032 Some(def) => self.macro_def_scope(def),
2033 None => return self.graph_root,
2035 self.get_module(DefId { index: CRATE_DEF_INDEX, ..module.normal_ancestor_id })
2038 fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'a>) -> Module<'a> {
2039 let mut module = self.get_module(module.normal_ancestor_id);
2040 while module.span.ctxt().modern() != *ctxt {
2041 let parent = module.parent.unwrap_or_else(|| self.macro_def_scope(ctxt.remove_mark()));
2042 module = self.get_module(parent.normal_ancestor_id);
2049 // We maintain a list of value ribs and type ribs.
2051 // Simultaneously, we keep track of the current position in the module
2052 // graph in the `current_module` pointer. When we go to resolve a name in
2053 // the value or type namespaces, we first look through all the ribs and
2054 // then query the module graph. When we resolve a name in the module
2055 // namespace, we can skip all the ribs (since nested modules are not
2056 // allowed within blocks in Rust) and jump straight to the current module
2059 // Named implementations are handled separately. When we find a method
2060 // call, we consult the module node to find all of the implementations in
2061 // scope. This information is lazily cached in the module node. We then
2062 // generate a fake "implementation scope" containing all the
2063 // implementations thus found, for compatibility with old resolve pass.
2065 pub fn with_scope<F, T>(&mut self, id: NodeId, f: F) -> T
2066 where F: FnOnce(&mut Resolver) -> T
2068 let id = self.definitions.local_def_id(id);
2069 let module = self.module_map.get(&id).cloned(); // clones a reference
2070 if let Some(module) = module {
2071 // Move down in the graph.
2072 let orig_module = replace(&mut self.current_module, module);
2073 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(module)));
2074 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(module)));
2076 self.finalize_current_module_macro_resolutions();
2079 self.current_module = orig_module;
2080 self.ribs[ValueNS].pop();
2081 self.ribs[TypeNS].pop();
2088 /// Searches the current set of local scopes for labels. Returns the first non-None label that
2089 /// is returned by the given predicate function
2091 /// Stops after meeting a closure.
2092 fn search_label<P, R>(&self, mut ident: Ident, pred: P) -> Option<R>
2093 where P: Fn(&Rib, Ident) -> Option<R>
2095 for rib in self.label_ribs.iter().rev() {
2098 // If an invocation of this macro created `ident`, give up on `ident`
2099 // and switch to `ident`'s source from the macro definition.
2100 MacroDefinition(def) => {
2101 if def == self.macro_def(ident.span.ctxt()) {
2102 ident.span.remove_mark();
2106 // Do not resolve labels across function boundary
2110 let r = pred(rib, ident);
2118 fn resolve_item(&mut self, item: &Item) {
2119 let name = item.ident.name;
2121 debug!("(resolving item) resolving {}", name);
2123 self.check_proc_macro_attrs(&item.attrs);
2126 ItemKind::Enum(_, ref generics) |
2127 ItemKind::Ty(_, ref generics) |
2128 ItemKind::Struct(_, ref generics) |
2129 ItemKind::Union(_, ref generics) |
2130 ItemKind::Fn(.., ref generics, _) => {
2131 self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind),
2132 |this| visit::walk_item(this, item));
2135 ItemKind::Impl(.., ref generics, ref opt_trait_ref, ref self_type, ref impl_items) =>
2136 self.resolve_implementation(generics,
2142 ItemKind::Trait(.., ref generics, ref bounds, ref trait_items) => {
2143 // Create a new rib for the trait-wide type parameters.
2144 self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
2145 let local_def_id = this.definitions.local_def_id(item.id);
2146 this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
2147 this.visit_generics(generics);
2148 walk_list!(this, visit_ty_param_bound, bounds);
2150 for trait_item in trait_items {
2151 this.check_proc_macro_attrs(&trait_item.attrs);
2153 let type_parameters = HasTypeParameters(&trait_item.generics,
2154 TraitOrImplItemRibKind);
2155 this.with_type_parameter_rib(type_parameters, |this| {
2156 match trait_item.node {
2157 TraitItemKind::Const(ref ty, ref default) => {
2160 // Only impose the restrictions of
2161 // ConstRibKind for an actual constant
2162 // expression in a provided default.
2163 if let Some(ref expr) = *default{
2164 this.with_constant_rib(|this| {
2165 this.visit_expr(expr);
2169 TraitItemKind::Method(_, _) => {
2170 visit::walk_trait_item(this, trait_item)
2172 TraitItemKind::Type(..) => {
2173 visit::walk_trait_item(this, trait_item)
2175 TraitItemKind::Macro(_) => {
2176 panic!("unexpanded macro in resolve!")
2185 ItemKind::TraitAlias(ref generics, ref bounds) => {
2186 // Create a new rib for the trait-wide type parameters.
2187 self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
2188 let local_def_id = this.definitions.local_def_id(item.id);
2189 this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
2190 this.visit_generics(generics);
2191 walk_list!(this, visit_ty_param_bound, bounds);
2196 ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
2197 self.with_scope(item.id, |this| {
2198 visit::walk_item(this, item);
2202 ItemKind::Static(ref ty, _, ref expr) |
2203 ItemKind::Const(ref ty, ref expr) => {
2204 self.with_item_rib(|this| {
2206 this.with_constant_rib(|this| {
2207 this.visit_expr(expr);
2212 ItemKind::Use(ref use_tree) => {
2213 // Imports are resolved as global by default, add starting root segment.
2215 segments: use_tree.prefix.make_root().into_iter().collect(),
2216 span: use_tree.span,
2218 self.resolve_use_tree(item.id, use_tree, &path);
2221 ItemKind::ExternCrate(_) | ItemKind::MacroDef(..) | ItemKind::GlobalAsm(_) => {
2222 // do nothing, these are just around to be encoded
2225 ItemKind::Mac(_) => panic!("unexpanded macro in resolve!"),
2229 fn resolve_use_tree(&mut self, id: NodeId, use_tree: &ast::UseTree, prefix: &Path) {
2230 match use_tree.kind {
2231 ast::UseTreeKind::Nested(ref items) => {
2233 segments: prefix.segments
2235 .chain(use_tree.prefix.segments.iter())
2238 span: prefix.span.to(use_tree.prefix.span),
2241 if items.len() == 0 {
2242 // Resolve prefix of an import with empty braces (issue #28388).
2243 self.smart_resolve_path(id, None, &path, PathSource::ImportPrefix);
2245 for &(ref tree, nested_id) in items {
2246 self.resolve_use_tree(nested_id, tree, &path);
2250 ast::UseTreeKind::Simple(_) => {},
2251 ast::UseTreeKind::Glob => {},
2255 fn with_type_parameter_rib<'b, F>(&'b mut self, type_parameters: TypeParameters<'a, 'b>, f: F)
2256 where F: FnOnce(&mut Resolver)
2258 match type_parameters {
2259 HasTypeParameters(generics, rib_kind) => {
2260 let mut function_type_rib = Rib::new(rib_kind);
2261 let mut seen_bindings = FxHashMap();
2262 for param in &generics.params {
2263 if let GenericParam::Type(ref type_parameter) = *param {
2264 let ident = type_parameter.ident.modern();
2265 debug!("with_type_parameter_rib: {}", type_parameter.id);
2267 if seen_bindings.contains_key(&ident) {
2268 let span = seen_bindings.get(&ident).unwrap();
2269 let err = ResolutionError::NameAlreadyUsedInTypeParameterList(
2273 resolve_error(self, type_parameter.ident.span, err);
2275 seen_bindings.entry(ident).or_insert(type_parameter.ident.span);
2277 // plain insert (no renaming)
2278 let def_id = self.definitions.local_def_id(type_parameter.id);
2279 let def = Def::TyParam(def_id);
2280 function_type_rib.bindings.insert(ident, def);
2281 self.record_def(type_parameter.id, PathResolution::new(def));
2284 self.ribs[TypeNS].push(function_type_rib);
2287 NoTypeParameters => {
2294 if let HasTypeParameters(..) = type_parameters {
2295 self.ribs[TypeNS].pop();
2299 fn with_label_rib<F>(&mut self, f: F)
2300 where F: FnOnce(&mut Resolver)
2302 self.label_ribs.push(Rib::new(NormalRibKind));
2304 self.label_ribs.pop();
2307 fn with_item_rib<F>(&mut self, f: F)
2308 where F: FnOnce(&mut Resolver)
2310 self.ribs[ValueNS].push(Rib::new(ItemRibKind));
2311 self.ribs[TypeNS].push(Rib::new(ItemRibKind));
2313 self.ribs[TypeNS].pop();
2314 self.ribs[ValueNS].pop();
2317 fn with_constant_rib<F>(&mut self, f: F)
2318 where F: FnOnce(&mut Resolver)
2320 self.ribs[ValueNS].push(Rib::new(ConstantItemRibKind));
2322 self.ribs[ValueNS].pop();
2325 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2326 where F: FnOnce(&mut Resolver) -> T
2328 // Handle nested impls (inside fn bodies)
2329 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2330 let result = f(self);
2331 self.current_self_type = previous_value;
2335 /// This is called to resolve a trait reference from an `impl` (i.e. `impl Trait for Foo`)
2336 fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
2337 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2339 let mut new_val = None;
2340 let mut new_id = None;
2341 if let Some(trait_ref) = opt_trait_ref {
2342 let path: Vec<_> = trait_ref.path.segments.iter()
2343 .map(|seg| seg.ident)
2345 let def = self.smart_resolve_path_fragment(
2349 trait_ref.path.span,
2350 PathSource::Trait(AliasPossibility::No)
2352 if def != Def::Err {
2353 new_id = Some(def.def_id());
2354 let span = trait_ref.path.span;
2355 if let PathResult::Module(module) = self.resolve_path(&path, None, false, span,
2356 Some(trait_ref.ref_id)) {
2357 new_val = Some((module, trait_ref.clone()));
2361 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2362 let result = f(self, new_id);
2363 self.current_trait_ref = original_trait_ref;
2367 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2368 where F: FnOnce(&mut Resolver)
2370 let mut self_type_rib = Rib::new(NormalRibKind);
2372 // plain insert (no renaming, types are not currently hygienic....)
2373 self_type_rib.bindings.insert(keywords::SelfType.ident(), self_def);
2374 self.ribs[TypeNS].push(self_type_rib);
2376 self.ribs[TypeNS].pop();
2379 fn resolve_implementation(&mut self,
2380 generics: &Generics,
2381 opt_trait_reference: &Option<TraitRef>,
2384 impl_items: &[ImplItem]) {
2385 // If applicable, create a rib for the type parameters.
2386 self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
2387 // Dummy self type for better errors if `Self` is used in the trait path.
2388 this.with_self_rib(Def::SelfTy(None, None), |this| {
2389 // Resolve the trait reference, if necessary.
2390 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2391 let item_def_id = this.definitions.local_def_id(item_id);
2392 this.with_self_rib(Def::SelfTy(trait_id, Some(item_def_id)), |this| {
2393 if let Some(trait_ref) = opt_trait_reference.as_ref() {
2394 // Resolve type arguments in trait path
2395 visit::walk_trait_ref(this, trait_ref);
2397 // Resolve the self type.
2398 this.visit_ty(self_type);
2399 // Resolve the type parameters.
2400 this.visit_generics(generics);
2401 this.with_current_self_type(self_type, |this| {
2402 for impl_item in impl_items {
2403 this.check_proc_macro_attrs(&impl_item.attrs);
2404 this.resolve_visibility(&impl_item.vis);
2406 // We also need a new scope for the impl item type parameters.
2407 let type_parameters = HasTypeParameters(&impl_item.generics,
2408 TraitOrImplItemRibKind);
2409 this.with_type_parameter_rib(type_parameters, |this| {
2410 use self::ResolutionError::*;
2411 match impl_item.node {
2412 ImplItemKind::Const(..) => {
2413 // If this is a trait impl, ensure the const
2415 this.check_trait_item(impl_item.ident,
2418 |n, s| ConstNotMemberOfTrait(n, s));
2419 this.with_constant_rib(|this|
2420 visit::walk_impl_item(this, impl_item)
2423 ImplItemKind::Method(_, _) => {
2424 // If this is a trait impl, ensure the method
2426 this.check_trait_item(impl_item.ident,
2429 |n, s| MethodNotMemberOfTrait(n, s));
2431 visit::walk_impl_item(this, impl_item);
2433 ImplItemKind::Type(ref ty) => {
2434 // If this is a trait impl, ensure the type
2436 this.check_trait_item(impl_item.ident,
2439 |n, s| TypeNotMemberOfTrait(n, s));
2443 ImplItemKind::Macro(_) =>
2444 panic!("unexpanded macro in resolve!"),
2455 fn check_trait_item<F>(&mut self, ident: Ident, ns: Namespace, span: Span, err: F)
2456 where F: FnOnce(Name, &str) -> ResolutionError
2458 // If there is a TraitRef in scope for an impl, then the method must be in the
2460 if let Some((module, _)) = self.current_trait_ref {
2461 if self.resolve_ident_in_module(module, ident, ns, false, false, span).is_err() {
2462 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
2463 resolve_error(self, span, err(ident.name, &path_names_to_string(path)));
2468 fn resolve_local(&mut self, local: &Local) {
2469 // Resolve the type.
2470 walk_list!(self, visit_ty, &local.ty);
2472 // Resolve the initializer.
2473 walk_list!(self, visit_expr, &local.init);
2475 // Resolve the pattern.
2476 self.resolve_pattern(&local.pat, PatternSource::Let, &mut FxHashMap());
2479 // build a map from pattern identifiers to binding-info's.
2480 // this is done hygienically. This could arise for a macro
2481 // that expands into an or-pattern where one 'x' was from the
2482 // user and one 'x' came from the macro.
2483 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2484 let mut binding_map = FxHashMap();
2486 pat.walk(&mut |pat| {
2487 if let PatKind::Ident(binding_mode, ident, ref sub_pat) = pat.node {
2488 if sub_pat.is_some() || match self.def_map.get(&pat.id).map(|res| res.base_def()) {
2489 Some(Def::Local(..)) => true,
2492 let binding_info = BindingInfo { span: ident.span, binding_mode: binding_mode };
2493 binding_map.insert(ident, binding_info);
2502 // check that all of the arms in an or-pattern have exactly the
2503 // same set of bindings, with the same binding modes for each.
2504 fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) {
2505 if pats.is_empty() {
2509 let mut missing_vars = FxHashMap();
2510 let mut inconsistent_vars = FxHashMap();
2511 for (i, p) in pats.iter().enumerate() {
2512 let map_i = self.binding_mode_map(&p);
2514 for (j, q) in pats.iter().enumerate() {
2519 let map_j = self.binding_mode_map(&q);
2520 for (&key, &binding_i) in &map_i {
2521 if map_j.len() == 0 { // Account for missing bindings when
2522 let binding_error = missing_vars // map_j has none.
2524 .or_insert(BindingError {
2526 origin: BTreeSet::new(),
2527 target: BTreeSet::new(),
2529 binding_error.origin.insert(binding_i.span);
2530 binding_error.target.insert(q.span);
2532 for (&key_j, &binding_j) in &map_j {
2533 match map_i.get(&key_j) {
2534 None => { // missing binding
2535 let binding_error = missing_vars
2537 .or_insert(BindingError {
2539 origin: BTreeSet::new(),
2540 target: BTreeSet::new(),
2542 binding_error.origin.insert(binding_j.span);
2543 binding_error.target.insert(p.span);
2545 Some(binding_i) => { // check consistent binding
2546 if binding_i.binding_mode != binding_j.binding_mode {
2549 .or_insert((binding_j.span, binding_i.span));
2557 let mut missing_vars = missing_vars.iter().collect::<Vec<_>>();
2558 missing_vars.sort();
2559 for (_, v) in missing_vars {
2561 *v.origin.iter().next().unwrap(),
2562 ResolutionError::VariableNotBoundInPattern(v));
2564 let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
2565 inconsistent_vars.sort();
2566 for (name, v) in inconsistent_vars {
2567 resolve_error(self, v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
2571 fn resolve_arm(&mut self, arm: &Arm) {
2572 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
2574 let mut bindings_list = FxHashMap();
2575 for pattern in &arm.pats {
2576 self.resolve_pattern(&pattern, PatternSource::Match, &mut bindings_list);
2579 // This has to happen *after* we determine which pat_idents are variants
2580 self.check_consistent_bindings(&arm.pats);
2582 walk_list!(self, visit_expr, &arm.guard);
2583 self.visit_expr(&arm.body);
2585 self.ribs[ValueNS].pop();
2588 fn resolve_block(&mut self, block: &Block) {
2589 debug!("(resolving block) entering block");
2590 // Move down in the graph, if there's an anonymous module rooted here.
2591 let orig_module = self.current_module;
2592 let anonymous_module = self.block_map.get(&block.id).cloned(); // clones a reference
2594 let mut num_macro_definition_ribs = 0;
2595 if let Some(anonymous_module) = anonymous_module {
2596 debug!("(resolving block) found anonymous module, moving down");
2597 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
2598 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
2599 self.current_module = anonymous_module;
2600 self.finalize_current_module_macro_resolutions();
2602 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
2605 // Descend into the block.
2606 for stmt in &block.stmts {
2607 if let ast::StmtKind::Item(ref item) = stmt.node {
2608 if let ast::ItemKind::MacroDef(..) = item.node {
2609 num_macro_definition_ribs += 1;
2610 let def = self.definitions.local_def_id(item.id);
2611 self.ribs[ValueNS].push(Rib::new(MacroDefinition(def)));
2612 self.label_ribs.push(Rib::new(MacroDefinition(def)));
2616 self.visit_stmt(stmt);
2620 self.current_module = orig_module;
2621 for _ in 0 .. num_macro_definition_ribs {
2622 self.ribs[ValueNS].pop();
2623 self.label_ribs.pop();
2625 self.ribs[ValueNS].pop();
2626 if let Some(_) = anonymous_module {
2627 self.ribs[TypeNS].pop();
2629 debug!("(resolving block) leaving block");
2632 fn fresh_binding(&mut self,
2635 outer_pat_id: NodeId,
2636 pat_src: PatternSource,
2637 bindings: &mut FxHashMap<Ident, NodeId>)
2639 // Add the binding to the local ribs, if it
2640 // doesn't already exist in the bindings map. (We
2641 // must not add it if it's in the bindings map
2642 // because that breaks the assumptions later
2643 // passes make about or-patterns.)
2644 let mut def = Def::Local(pat_id);
2645 match bindings.get(&ident).cloned() {
2646 Some(id) if id == outer_pat_id => {
2647 // `Variant(a, a)`, error
2651 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2652 &ident.name.as_str())
2655 Some(..) if pat_src == PatternSource::FnParam => {
2656 // `fn f(a: u8, a: u8)`, error
2660 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2661 &ident.name.as_str())
2664 Some(..) if pat_src == PatternSource::Match ||
2665 pat_src == PatternSource::IfLet ||
2666 pat_src == PatternSource::WhileLet => {
2667 // `Variant1(a) | Variant2(a)`, ok
2668 // Reuse definition from the first `a`.
2669 def = self.ribs[ValueNS].last_mut().unwrap().bindings[&ident];
2672 span_bug!(ident.span, "two bindings with the same name from \
2673 unexpected pattern source {:?}", pat_src);
2676 // A completely fresh binding, add to the lists if it's valid.
2677 if ident.name != keywords::Invalid.name() {
2678 bindings.insert(ident, outer_pat_id);
2679 self.ribs[ValueNS].last_mut().unwrap().bindings.insert(ident, def);
2684 PathResolution::new(def)
2687 fn resolve_pattern(&mut self,
2689 pat_src: PatternSource,
2690 // Maps idents to the node ID for the
2691 // outermost pattern that binds them.
2692 bindings: &mut FxHashMap<Ident, NodeId>) {
2693 // Visit all direct subpatterns of this pattern.
2694 let outer_pat_id = pat.id;
2695 pat.walk(&mut |pat| {
2697 PatKind::Ident(bmode, ident, ref opt_pat) => {
2698 // First try to resolve the identifier as some existing
2699 // entity, then fall back to a fresh binding.
2700 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS,
2702 .and_then(LexicalScopeBinding::item);
2703 let resolution = binding.map(NameBinding::def).and_then(|def| {
2704 let is_syntactic_ambiguity = opt_pat.is_none() &&
2705 bmode == BindingMode::ByValue(Mutability::Immutable);
2707 Def::StructCtor(_, CtorKind::Const) |
2708 Def::VariantCtor(_, CtorKind::Const) |
2709 Def::Const(..) if is_syntactic_ambiguity => {
2710 // Disambiguate in favor of a unit struct/variant
2711 // or constant pattern.
2712 self.record_use(ident, ValueNS, binding.unwrap(), ident.span);
2713 Some(PathResolution::new(def))
2715 Def::StructCtor(..) | Def::VariantCtor(..) |
2716 Def::Const(..) | Def::Static(..) => {
2717 // This is unambiguously a fresh binding, either syntactically
2718 // (e.g. `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
2719 // to something unusable as a pattern (e.g. constructor function),
2720 // but we still conservatively report an error, see
2721 // issues/33118#issuecomment-233962221 for one reason why.
2725 ResolutionError::BindingShadowsSomethingUnacceptable(
2726 pat_src.descr(), ident.name, binding.unwrap())
2730 Def::Fn(..) | Def::Err => {
2731 // These entities are explicitly allowed
2732 // to be shadowed by fresh bindings.
2736 span_bug!(ident.span, "unexpected definition for an \
2737 identifier in pattern: {:?}", def);
2740 }).unwrap_or_else(|| {
2741 self.fresh_binding(ident, pat.id, outer_pat_id, pat_src, bindings)
2744 self.record_def(pat.id, resolution);
2747 PatKind::TupleStruct(ref path, ..) => {
2748 self.smart_resolve_path(pat.id, None, path, PathSource::TupleStruct);
2751 PatKind::Path(ref qself, ref path) => {
2752 self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
2755 PatKind::Struct(ref path, ..) => {
2756 self.smart_resolve_path(pat.id, None, path, PathSource::Struct);
2764 visit::walk_pat(self, pat);
2767 // High-level and context dependent path resolution routine.
2768 // Resolves the path and records the resolution into definition map.
2769 // If resolution fails tries several techniques to find likely
2770 // resolution candidates, suggest imports or other help, and report
2771 // errors in user friendly way.
2772 fn smart_resolve_path(&mut self,
2774 qself: Option<&QSelf>,
2778 let segments = &path.segments.iter()
2779 .map(|seg| seg.ident)
2780 .collect::<Vec<_>>();
2781 self.smart_resolve_path_fragment(id, qself, segments, path.span, source)
2784 fn smart_resolve_path_fragment(&mut self,
2786 qself: Option<&QSelf>,
2791 let ident_span = path.last().map_or(span, |ident| ident.span);
2792 let ns = source.namespace();
2793 let is_expected = &|def| source.is_expected(def);
2794 let is_enum_variant = &|def| if let Def::Variant(..) = def { true } else { false };
2796 // Base error is amended with one short label and possibly some longer helps/notes.
2797 let report_errors = |this: &mut Self, def: Option<Def>| {
2798 // Make the base error.
2799 let expected = source.descr_expected();
2800 let path_str = names_to_string(path);
2801 let code = source.error_code(def.is_some());
2802 let (base_msg, fallback_label, base_span) = if let Some(def) = def {
2803 (format!("expected {}, found {} `{}`", expected, def.kind_name(), path_str),
2804 format!("not a {}", expected),
2807 let item_str = path[path.len() - 1];
2808 let item_span = path[path.len() - 1].span;
2809 let (mod_prefix, mod_str) = if path.len() == 1 {
2810 (format!(""), format!("this scope"))
2811 } else if path.len() == 2 && path[0].name == keywords::CrateRoot.name() {
2812 (format!(""), format!("the crate root"))
2814 let mod_path = &path[..path.len() - 1];
2815 let mod_prefix = match this.resolve_path(mod_path, Some(TypeNS),
2816 false, span, None) {
2817 PathResult::Module(module) => module.def(),
2819 }.map_or(format!(""), |def| format!("{} ", def.kind_name()));
2820 (mod_prefix, format!("`{}`", names_to_string(mod_path)))
2822 (format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str),
2823 format!("not found in {}", mod_str),
2826 let code = DiagnosticId::Error(code.into());
2827 let mut err = this.session.struct_span_err_with_code(base_span, &base_msg, code);
2829 // Emit special messages for unresolved `Self` and `self`.
2830 if is_self_type(path, ns) {
2831 __diagnostic_used!(E0411);
2832 err.code(DiagnosticId::Error("E0411".into()));
2833 err.span_label(span, "`Self` is only available in traits and impls");
2834 return (err, Vec::new());
2836 if is_self_value(path, ns) {
2837 __diagnostic_used!(E0424);
2838 err.code(DiagnosticId::Error("E0424".into()));
2839 err.span_label(span, format!("`self` value is only available in \
2840 methods with `self` parameter"));
2841 return (err, Vec::new());
2844 // Try to lookup the name in more relaxed fashion for better error reporting.
2845 let ident = *path.last().unwrap();
2846 let candidates = this.lookup_import_candidates(ident.name, ns, is_expected);
2847 if candidates.is_empty() && is_expected(Def::Enum(DefId::local(CRATE_DEF_INDEX))) {
2848 let enum_candidates =
2849 this.lookup_import_candidates(ident.name, ns, is_enum_variant);
2850 let mut enum_candidates = enum_candidates.iter()
2851 .map(|suggestion| import_candidate_to_paths(&suggestion)).collect::<Vec<_>>();
2852 enum_candidates.sort();
2853 for (sp, variant_path, enum_path) in enum_candidates {
2855 let msg = format!("there is an enum variant `{}`, \
2861 err.span_suggestion(span, "you can try using the variant's enum",
2866 if path.len() == 1 && this.self_type_is_available(span) {
2867 if let Some(candidate) = this.lookup_assoc_candidate(ident, ns, is_expected) {
2868 let self_is_available = this.self_value_is_available(path[0].span, span);
2870 AssocSuggestion::Field => {
2871 err.span_suggestion(span, "try",
2872 format!("self.{}", path_str));
2873 if !self_is_available {
2874 err.span_label(span, format!("`self` value is only available in \
2875 methods with `self` parameter"));
2878 AssocSuggestion::MethodWithSelf if self_is_available => {
2879 err.span_suggestion(span, "try",
2880 format!("self.{}", path_str));
2882 AssocSuggestion::MethodWithSelf | AssocSuggestion::AssocItem => {
2883 err.span_suggestion(span, "try",
2884 format!("Self::{}", path_str));
2887 return (err, candidates);
2891 let mut levenshtein_worked = false;
2894 if let Some(candidate) = this.lookup_typo_candidate(path, ns, is_expected, span) {
2895 err.span_label(ident_span, format!("did you mean `{}`?", candidate));
2896 levenshtein_worked = true;
2899 // Try context dependent help if relaxed lookup didn't work.
2900 if let Some(def) = def {
2901 match (def, source) {
2902 (Def::Macro(..), _) => {
2903 err.span_label(span, format!("did you mean `{}!(...)`?", path_str));
2904 return (err, candidates);
2906 (Def::TyAlias(..), PathSource::Trait(_)) => {
2907 err.span_label(span, "type aliases cannot be used for traits");
2908 return (err, candidates);
2910 (Def::Mod(..), PathSource::Expr(Some(parent))) => match parent.node {
2911 ExprKind::Field(_, ident) => {
2912 err.span_label(parent.span, format!("did you mean `{}::{}`?",
2914 return (err, candidates);
2916 ExprKind::MethodCall(ref segment, ..) => {
2917 err.span_label(parent.span, format!("did you mean `{}::{}(...)`?",
2918 path_str, segment.ident));
2919 return (err, candidates);
2923 (Def::Enum(..), PathSource::TupleStruct)
2924 | (Def::Enum(..), PathSource::Expr(..)) => {
2925 if let Some(variants) = this.collect_enum_variants(def) {
2926 err.note(&format!("did you mean to use one \
2927 of the following variants?\n{}",
2929 .map(|suggestion| path_names_to_string(suggestion))
2930 .map(|suggestion| format!("- `{}`", suggestion))
2931 .collect::<Vec<_>>()
2935 err.note("did you mean to use one of the enum's variants?");
2937 return (err, candidates);
2939 (Def::Struct(def_id), _) if ns == ValueNS => {
2940 if let Some((ctor_def, ctor_vis))
2941 = this.struct_constructors.get(&def_id).cloned() {
2942 let accessible_ctor = this.is_accessible(ctor_vis);
2943 if is_expected(ctor_def) && !accessible_ctor {
2944 err.span_label(span, format!("constructor is not visible \
2945 here due to private fields"));
2948 err.span_label(span, format!("did you mean `{} {{ /* fields */ }}`?",
2951 return (err, candidates);
2953 (Def::Union(..), _) |
2954 (Def::Variant(..), _) |
2955 (Def::VariantCtor(_, CtorKind::Fictive), _) if ns == ValueNS => {
2956 err.span_label(span, format!("did you mean `{} {{ /* fields */ }}`?",
2958 return (err, candidates);
2960 (Def::SelfTy(..), _) if ns == ValueNS => {
2961 err.span_label(span, fallback_label);
2962 err.note("can't use `Self` as a constructor, you must use the \
2963 implemented struct");
2964 return (err, candidates);
2966 (Def::TyAlias(_), _) | (Def::AssociatedTy(..), _) if ns == ValueNS => {
2967 err.note("can't use a type alias as a constructor");
2968 return (err, candidates);
2975 if !levenshtein_worked {
2976 err.span_label(base_span, fallback_label);
2977 this.type_ascription_suggestion(&mut err, base_span);
2981 let report_errors = |this: &mut Self, def: Option<Def>| {
2982 let (err, candidates) = report_errors(this, def);
2983 let def_id = this.current_module.normal_ancestor_id;
2984 let node_id = this.definitions.as_local_node_id(def_id).unwrap();
2985 let better = def.is_some();
2986 this.use_injections.push(UseError { err, candidates, node_id, better });
2987 err_path_resolution()
2990 let resolution = match self.resolve_qpath_anywhere(id, qself, path, ns, span,
2991 source.defer_to_typeck(),
2992 source.global_by_default()) {
2993 Some(resolution) if resolution.unresolved_segments() == 0 => {
2994 if is_expected(resolution.base_def()) || resolution.base_def() == Def::Err {
2997 // Add a temporary hack to smooth the transition to new struct ctor
2998 // visibility rules. See #38932 for more details.
3000 if let Def::Struct(def_id) = resolution.base_def() {
3001 if let Some((ctor_def, ctor_vis))
3002 = self.struct_constructors.get(&def_id).cloned() {
3003 if is_expected(ctor_def) && self.is_accessible(ctor_vis) {
3004 let lint = lint::builtin::LEGACY_CONSTRUCTOR_VISIBILITY;
3005 self.session.buffer_lint(lint, id, span,
3006 "private struct constructors are not usable through \
3007 re-exports in outer modules",
3009 res = Some(PathResolution::new(ctor_def));
3014 res.unwrap_or_else(|| report_errors(self, Some(resolution.base_def())))
3017 Some(resolution) if source.defer_to_typeck() => {
3018 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
3019 // or `<T>::A::B`. If `B` should be resolved in value namespace then
3020 // it needs to be added to the trait map.
3022 let item_name = *path.last().unwrap();
3023 let traits = self.get_traits_containing_item(item_name, ns);
3024 self.trait_map.insert(id, traits);
3028 _ => report_errors(self, None)
3031 if let PathSource::TraitItem(..) = source {} else {
3032 // Avoid recording definition of `A::B` in `<T as A>::B::C`.
3033 self.record_def(id, resolution);
3038 fn type_ascription_suggestion(&self,
3039 err: &mut DiagnosticBuilder,
3041 debug!("type_ascription_suggetion {:?}", base_span);
3042 let cm = self.session.codemap();
3043 debug!("self.current_type_ascription {:?}", self.current_type_ascription);
3044 if let Some(sp) = self.current_type_ascription.last() {
3046 loop { // try to find the `:`, bail on first non-':'/non-whitespace
3047 sp = cm.next_point(sp);
3048 if let Ok(snippet) = cm.span_to_snippet(sp.to(cm.next_point(sp))) {
3049 debug!("snippet {:?}", snippet);
3050 let line_sp = cm.lookup_char_pos(sp.hi()).line;
3051 let line_base_sp = cm.lookup_char_pos(base_span.lo()).line;
3052 debug!("{:?} {:?}", line_sp, line_base_sp);
3054 err.span_label(base_span,
3055 "expecting a type here because of type ascription");
3056 if line_sp != line_base_sp {
3057 err.span_suggestion_short(sp,
3058 "did you mean to use `;` here instead?",
3062 } else if snippet.trim().len() != 0 {
3063 debug!("tried to find type ascription `:` token, couldn't find it");
3073 fn self_type_is_available(&mut self, span: Span) -> bool {
3074 let binding = self.resolve_ident_in_lexical_scope(keywords::SelfType.ident(),
3075 TypeNS, false, span);
3076 if let Some(LexicalScopeBinding::Def(def)) = binding { def != Def::Err } else { false }
3079 fn self_value_is_available(&mut self, self_span: Span, path_span: Span) -> bool {
3080 let ident = Ident::new(keywords::SelfValue.name(), self_span);
3081 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, false, path_span);
3082 if let Some(LexicalScopeBinding::Def(def)) = binding { def != Def::Err } else { false }
3085 // Resolve in alternative namespaces if resolution in the primary namespace fails.
3086 fn resolve_qpath_anywhere(&mut self,
3088 qself: Option<&QSelf>,
3090 primary_ns: Namespace,
3092 defer_to_typeck: bool,
3093 global_by_default: bool)
3094 -> Option<PathResolution> {
3095 let mut fin_res = None;
3096 // FIXME: can't resolve paths in macro namespace yet, macros are
3097 // processed by the little special hack below.
3098 for (i, ns) in [primary_ns, TypeNS, ValueNS, /*MacroNS*/].iter().cloned().enumerate() {
3099 if i == 0 || ns != primary_ns {
3100 match self.resolve_qpath(id, qself, path, ns, span, global_by_default) {
3101 // If defer_to_typeck, then resolution > no resolution,
3102 // otherwise full resolution > partial resolution > no resolution.
3103 Some(res) if res.unresolved_segments() == 0 || defer_to_typeck =>
3105 res => if fin_res.is_none() { fin_res = res },
3109 let is_global = self.global_macros.get(&path[0].name).cloned()
3110 .map(|binding| binding.get_macro(self).kind() == MacroKind::Bang).unwrap_or(false);
3111 if primary_ns != MacroNS && (is_global ||
3112 self.macro_names.contains(&path[0].modern())) {
3113 // Return some dummy definition, it's enough for error reporting.
3115 PathResolution::new(Def::Macro(DefId::local(CRATE_DEF_INDEX), MacroKind::Bang))
3121 /// Handles paths that may refer to associated items.
3122 fn resolve_qpath(&mut self,
3124 qself: Option<&QSelf>,
3128 global_by_default: bool)
3129 -> Option<PathResolution> {
3130 if let Some(qself) = qself {
3131 if qself.position == 0 {
3132 // FIXME: Create some fake resolution that can't possibly be a type.
3133 return Some(PathResolution::with_unresolved_segments(
3134 Def::Mod(DefId::local(CRATE_DEF_INDEX)), path.len()
3137 // Make sure `A::B` in `<T as A>::B::C` is a trait item.
3138 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
3139 let res = self.smart_resolve_path_fragment(id, None, &path[..qself.position + 1],
3140 span, PathSource::TraitItem(ns));
3141 return Some(PathResolution::with_unresolved_segments(
3142 res.base_def(), res.unresolved_segments() + path.len() - qself.position - 1
3146 let result = match self.resolve_path(&path, Some(ns), true, span, Some(id)) {
3147 PathResult::NonModule(path_res) => path_res,
3148 PathResult::Module(module) if !module.is_normal() => {
3149 PathResolution::new(module.def().unwrap())
3151 // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
3152 // don't report an error right away, but try to fallback to a primitive type.
3153 // So, we are still able to successfully resolve something like
3155 // use std::u8; // bring module u8 in scope
3156 // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
3157 // u8::max_value() // OK, resolves to associated function <u8>::max_value,
3158 // // not to non-existent std::u8::max_value
3161 // Such behavior is required for backward compatibility.
3162 // The same fallback is used when `a` resolves to nothing.
3163 PathResult::Module(..) | PathResult::Failed(..)
3164 if (ns == TypeNS || path.len() > 1) &&
3165 self.primitive_type_table.primitive_types
3166 .contains_key(&path[0].name) => {
3167 let prim = self.primitive_type_table.primitive_types[&path[0].name];
3168 PathResolution::with_unresolved_segments(Def::PrimTy(prim), path.len() - 1)
3170 PathResult::Module(module) => PathResolution::new(module.def().unwrap()),
3171 PathResult::Failed(span, msg, false) => {
3172 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
3173 err_path_resolution()
3175 PathResult::Failed(..) => return None,
3176 PathResult::Indeterminate => bug!("indetermined path result in resolve_qpath"),
3179 if path.len() > 1 && !global_by_default && result.base_def() != Def::Err &&
3180 path[0].name != keywords::CrateRoot.name() &&
3181 path[0].name != keywords::DollarCrate.name() {
3182 let unqualified_result = {
3183 match self.resolve_path(&[*path.last().unwrap()], Some(ns), false, span, None) {
3184 PathResult::NonModule(path_res) => path_res.base_def(),
3185 PathResult::Module(module) => module.def().unwrap(),
3186 _ => return Some(result),
3189 if result.base_def() == unqualified_result {
3190 let lint = lint::builtin::UNUSED_QUALIFICATIONS;
3191 self.session.buffer_lint(lint, id, span, "unnecessary qualification")
3198 fn resolve_path(&mut self,
3200 opt_ns: Option<Namespace>, // `None` indicates a module path
3203 node_id: Option<NodeId>) // None indicates that we don't care about linting
3206 let mut module = None;
3207 let mut allow_super = true;
3208 let mut second_binding = None;
3210 for (i, &ident) in path.iter().enumerate() {
3211 debug!("resolve_path ident {} {:?}", i, ident);
3212 let is_last = i == path.len() - 1;
3213 let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
3214 let name = ident.name;
3216 if i == 0 && ns == TypeNS && name == keywords::SelfValue.name() {
3217 let mut ctxt = ident.span.ctxt().modern();
3218 module = Some(self.resolve_self(&mut ctxt, self.current_module));
3220 } else if allow_super && ns == TypeNS && name == keywords::Super.name() {
3221 let mut ctxt = ident.span.ctxt().modern();
3222 let self_module = match i {
3223 0 => self.resolve_self(&mut ctxt, self.current_module),
3224 _ => module.unwrap(),
3226 if let Some(parent) = self_module.parent {
3227 module = Some(self.resolve_self(&mut ctxt, parent));
3230 let msg = "There are too many initial `super`s.".to_string();
3231 return PathResult::Failed(ident.span, msg, false);
3233 } else if i == 0 && ns == TypeNS && name == keywords::Extern.name() {
3236 allow_super = false;
3239 if (i == 0 && name == keywords::CrateRoot.name()) ||
3240 (i == 0 && name == keywords::Crate.name()) ||
3241 (i == 1 && name == keywords::Crate.name() &&
3242 path[0].name == keywords::CrateRoot.name()) {
3243 // `::a::b` or `::crate::a::b`
3244 module = Some(self.resolve_crate_root(ident.span.ctxt(), false));
3246 } else if i == 0 && name == keywords::DollarCrate.name() {
3248 module = Some(self.resolve_crate_root(ident.span.ctxt(), true));
3250 } else if i == 1 && !ident.is_path_segment_keyword() {
3251 let prev_name = path[0].name;
3252 if prev_name == keywords::Extern.name() ||
3253 prev_name == keywords::CrateRoot.name() &&
3254 self.session.features_untracked().extern_absolute_paths &&
3255 self.session.rust_2018() {
3256 // `::extern_crate::a::b`
3257 let crate_id = self.crate_loader.process_path_extern(name, ident.span);
3259 self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
3260 self.populate_module_if_necessary(crate_root);
3261 module = Some(crate_root);
3267 // Report special messages for path segment keywords in wrong positions.
3268 if name == keywords::CrateRoot.name() && i != 0 ||
3269 name == keywords::DollarCrate.name() && i != 0 ||
3270 name == keywords::SelfValue.name() && i != 0 ||
3271 name == keywords::SelfType.name() && i != 0 ||
3272 name == keywords::Super.name() && i != 0 ||
3273 name == keywords::Extern.name() && i != 0 ||
3274 // we allow crate::foo and ::crate::foo but nothing else
3275 name == keywords::Crate.name() && i > 1 &&
3276 path[0].name != keywords::CrateRoot.name() ||
3277 name == keywords::Crate.name() && path.len() == 1 {
3278 let name_str = if name == keywords::CrateRoot.name() {
3279 format!("crate root")
3281 format!("`{}`", name)
3283 let msg = if i == 1 && path[0].name == keywords::CrateRoot.name() {
3284 format!("global paths cannot start with {}", name_str)
3286 format!("{} in paths can only be used in start position", name_str)
3288 return PathResult::Failed(ident.span, msg, false);
3291 let binding = if let Some(module) = module {
3292 self.resolve_ident_in_module(module, ident, ns, false, record_used, path_span)
3293 } else if opt_ns == Some(MacroNS) {
3294 self.resolve_lexical_macro_path_segment(ident, ns, record_used, path_span)
3295 .map(MacroBinding::binding)
3297 match self.resolve_ident_in_lexical_scope(ident, ns, record_used, path_span) {
3298 // we found a locally-imported or available item/module
3299 Some(LexicalScopeBinding::Item(binding)) => Ok(binding),
3300 // we found a local variable or type param
3301 Some(LexicalScopeBinding::Def(def))
3302 if opt_ns == Some(TypeNS) || opt_ns == Some(ValueNS) => {
3303 return PathResult::NonModule(PathResolution::with_unresolved_segments(
3307 _ => Err(if record_used { Determined } else { Undetermined }),
3314 second_binding = Some(binding);
3316 let def = binding.def();
3317 let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(def);
3318 if let Some(next_module) = binding.module() {
3319 module = Some(next_module);
3320 } else if def == Def::Err {
3321 return PathResult::NonModule(err_path_resolution());
3322 } else if opt_ns.is_some() && (is_last || maybe_assoc) {
3323 self.lint_if_path_starts_with_module(
3329 return PathResult::NonModule(PathResolution::with_unresolved_segments(
3330 def, path.len() - i - 1
3333 return PathResult::Failed(ident.span,
3334 format!("Not a module `{}`", ident),
3338 Err(Undetermined) => return PathResult::Indeterminate,
3339 Err(Determined) => {
3340 if let Some(module) = module {
3341 if opt_ns.is_some() && !module.is_normal() {
3342 return PathResult::NonModule(PathResolution::with_unresolved_segments(
3343 module.def().unwrap(), path.len() - i
3347 let msg = if module.and_then(ModuleData::def) == self.graph_root.def() {
3348 let is_mod = |def| match def { Def::Mod(..) => true, _ => false };
3349 let mut candidates =
3350 self.lookup_import_candidates(name, TypeNS, is_mod);
3351 candidates.sort_by_cached_key(|c| {
3352 (c.path.segments.len(), c.path.to_string())
3354 if let Some(candidate) = candidates.get(0) {
3355 format!("Did you mean `{}`?", candidate.path)
3357 format!("Maybe a missing `extern crate {};`?", ident)
3360 format!("Use of undeclared type or module `{}`", ident)
3362 format!("Could not find `{}` in `{}`", ident, path[i - 1])
3364 return PathResult::Failed(ident.span, msg, is_last);
3369 self.lint_if_path_starts_with_module(node_id, path, path_span, second_binding);
3371 PathResult::Module(module.unwrap_or(self.graph_root))
3374 fn lint_if_path_starts_with_module(&self,
3378 second_binding: Option<&NameBinding>) {
3384 let first_name = match path.get(0) {
3385 Some(ident) => ident.name,
3389 // We're only interested in `use` paths which should start with
3390 // `{{root}}` or `extern` currently.
3391 if first_name != keywords::Extern.name() && first_name != keywords::CrateRoot.name() {
3396 // If this import looks like `crate::...` it's already good
3397 Some(name) if name.name == keywords::Crate.name() => return,
3398 // Otherwise go below to see if it's an extern crate
3400 // If the path has length one (and it's `CrateRoot` most likely)
3401 // then we don't know whether we're gonna be importing a crate or an
3402 // item in our crate. Defer this lint to elsewhere
3406 // If the first element of our path was actually resolved to an
3407 // `ExternCrate` (also used for `crate::...`) then no need to issue a
3408 // warning, this looks all good!
3409 if let Some(binding) = second_binding {
3410 if let NameBindingKind::Import { directive: d, .. } = binding.kind {
3411 if let ImportDirectiveSubclass::ExternCrate(..) = d.subclass {
3417 self.lint_path_starts_with_module(id, path_span);
3420 fn lint_path_starts_with_module(&self, id: NodeId, span: Span) {
3421 // In the 2018 edition this lint is a hard error, so nothing to do
3422 if self.session.rust_2018() {
3425 // In the 2015 edition there's no use in emitting lints unless the
3426 // crate's already enabled the feature that we're going to suggest
3427 if !self.session.features_untracked().crate_in_paths {
3430 let diag = lint::builtin::BuiltinLintDiagnostics
3431 ::AbsPathWithModule(span);
3432 self.session.buffer_lint_with_diagnostic(
3433 lint::builtin::ABSOLUTE_PATH_NOT_STARTING_WITH_CRATE,
3435 "absolute paths must start with `self`, `super`, \
3436 `crate`, or an external crate name in the 2018 edition",
3440 // Resolve a local definition, potentially adjusting for closures.
3441 fn adjust_local_def(&mut self,
3446 span: Span) -> Def {
3447 let ribs = &self.ribs[ns][rib_index + 1..];
3449 // An invalid forward use of a type parameter from a previous default.
3450 if let ForwardTyParamBanRibKind = self.ribs[ns][rib_index].kind {
3452 resolve_error(self, span, ResolutionError::ForwardDeclaredTyParam);
3454 assert_eq!(def, Def::Err);
3460 span_bug!(span, "unexpected {:?} in bindings", def)
3462 Def::Local(node_id) => {
3465 NormalRibKind | ModuleRibKind(..) | MacroDefinition(..) |
3466 ForwardTyParamBanRibKind => {
3467 // Nothing to do. Continue.
3469 ClosureRibKind(function_id) => {
3472 let seen = self.freevars_seen
3474 .or_insert_with(|| NodeMap());
3475 if let Some(&index) = seen.get(&node_id) {
3476 def = Def::Upvar(node_id, index, function_id);
3479 let vec = self.freevars
3481 .or_insert_with(|| vec![]);
3482 let depth = vec.len();
3483 def = Def::Upvar(node_id, depth, function_id);
3490 seen.insert(node_id, depth);
3493 ItemRibKind | TraitOrImplItemRibKind => {
3494 // This was an attempt to access an upvar inside a
3495 // named function item. This is not allowed, so we
3498 resolve_error(self, span,
3499 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
3503 ConstantItemRibKind => {
3504 // Still doesn't deal with upvars
3506 resolve_error(self, span,
3507 ResolutionError::AttemptToUseNonConstantValueInConstant);
3514 Def::TyParam(..) | Def::SelfTy(..) => {
3517 NormalRibKind | TraitOrImplItemRibKind | ClosureRibKind(..) |
3518 ModuleRibKind(..) | MacroDefinition(..) | ForwardTyParamBanRibKind |
3519 ConstantItemRibKind => {
3520 // Nothing to do. Continue.
3523 // This was an attempt to use a type parameter outside
3526 resolve_error(self, span,
3527 ResolutionError::TypeParametersFromOuterFunction(def));
3539 fn lookup_assoc_candidate<FilterFn>(&mut self,
3542 filter_fn: FilterFn)
3543 -> Option<AssocSuggestion>
3544 where FilterFn: Fn(Def) -> bool
3546 fn extract_node_id(t: &Ty) -> Option<NodeId> {
3548 TyKind::Path(None, _) => Some(t.id),
3549 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
3550 // This doesn't handle the remaining `Ty` variants as they are not
3551 // that commonly the self_type, it might be interesting to provide
3552 // support for those in future.
3557 // Fields are generally expected in the same contexts as locals.
3558 if filter_fn(Def::Local(ast::DUMMY_NODE_ID)) {
3559 if let Some(node_id) = self.current_self_type.as_ref().and_then(extract_node_id) {
3560 // Look for a field with the same name in the current self_type.
3561 if let Some(resolution) = self.def_map.get(&node_id) {
3562 match resolution.base_def() {
3563 Def::Struct(did) | Def::Union(did)
3564 if resolution.unresolved_segments() == 0 => {
3565 if let Some(field_names) = self.field_names.get(&did) {
3566 if field_names.iter().any(|&field_name| ident.name == field_name) {
3567 return Some(AssocSuggestion::Field);
3577 // Look for associated items in the current trait.
3578 if let Some((module, _)) = self.current_trait_ref {
3579 if let Ok(binding) =
3580 self.resolve_ident_in_module(module, ident, ns, false, false, module.span) {
3581 let def = binding.def();
3583 return Some(if self.has_self.contains(&def.def_id()) {
3584 AssocSuggestion::MethodWithSelf
3586 AssocSuggestion::AssocItem
3595 fn lookup_typo_candidate<FilterFn>(&mut self,
3598 filter_fn: FilterFn,
3601 where FilterFn: Fn(Def) -> bool
3603 let add_module_candidates = |module: Module, names: &mut Vec<Name>| {
3604 for (&(ident, _), resolution) in module.resolutions.borrow().iter() {
3605 if let Some(binding) = resolution.borrow().binding {
3606 if filter_fn(binding.def()) {
3607 names.push(ident.name);
3613 let mut names = Vec::new();
3614 if path.len() == 1 {
3615 // Search in lexical scope.
3616 // Walk backwards up the ribs in scope and collect candidates.
3617 for rib in self.ribs[ns].iter().rev() {
3618 // Locals and type parameters
3619 for (ident, def) in &rib.bindings {
3620 if filter_fn(*def) {
3621 names.push(ident.name);
3625 if let ModuleRibKind(module) = rib.kind {
3626 // Items from this module
3627 add_module_candidates(module, &mut names);
3629 if let ModuleKind::Block(..) = module.kind {
3630 // We can see through blocks
3632 // Items from the prelude
3633 if !module.no_implicit_prelude {
3634 names.extend(self.extern_prelude.iter().cloned());
3635 if let Some(prelude) = self.prelude {
3636 add_module_candidates(prelude, &mut names);
3643 // Add primitive types to the mix
3644 if filter_fn(Def::PrimTy(TyBool)) {
3645 for (name, _) in &self.primitive_type_table.primitive_types {
3650 // Search in module.
3651 let mod_path = &path[..path.len() - 1];
3652 if let PathResult::Module(module) = self.resolve_path(mod_path, Some(TypeNS),
3653 false, span, None) {
3654 add_module_candidates(module, &mut names);
3658 let name = path[path.len() - 1].name;
3659 // Make sure error reporting is deterministic.
3660 names.sort_by_cached_key(|name| name.as_str());
3661 match find_best_match_for_name(names.iter(), &name.as_str(), None) {
3662 Some(found) if found != name => Some(found),
3667 fn with_resolved_label<F>(&mut self, label: Option<Label>, id: NodeId, f: F)
3668 where F: FnOnce(&mut Resolver)
3670 if let Some(label) = label {
3671 self.unused_labels.insert(id, label.ident.span);
3672 let def = Def::Label(id);
3673 self.with_label_rib(|this| {
3674 this.label_ribs.last_mut().unwrap().bindings.insert(label.ident, def);
3682 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &Block) {
3683 self.with_resolved_label(label, id, |this| this.visit_block(block));
3686 fn resolve_expr(&mut self, expr: &Expr, parent: Option<&Expr>) {
3687 // First, record candidate traits for this expression if it could
3688 // result in the invocation of a method call.
3690 self.record_candidate_traits_for_expr_if_necessary(expr);
3692 // Next, resolve the node.
3694 ExprKind::Path(ref qself, ref path) => {
3695 self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
3696 visit::walk_expr(self, expr);
3699 ExprKind::Struct(ref path, ..) => {
3700 self.smart_resolve_path(expr.id, None, path, PathSource::Struct);
3701 visit::walk_expr(self, expr);
3704 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
3705 match self.search_label(label.ident, |rib, id| rib.bindings.get(&id).cloned()) {
3707 // Search again for close matches...
3708 // Picks the first label that is "close enough", which is not necessarily
3709 // the closest match
3710 let close_match = self.search_label(label.ident, |rib, ident| {
3711 let names = rib.bindings.iter().map(|(id, _)| &id.name);
3712 find_best_match_for_name(names, &*ident.name.as_str(), None)
3714 self.record_def(expr.id, err_path_resolution());
3717 ResolutionError::UndeclaredLabel(&label.ident.name.as_str(),
3720 Some(Def::Label(id)) => {
3721 // Since this def is a label, it is never read.
3722 self.record_def(expr.id, PathResolution::new(Def::Label(id)));
3723 self.unused_labels.remove(&id);
3726 span_bug!(expr.span, "label wasn't mapped to a label def!");
3730 // visit `break` argument if any
3731 visit::walk_expr(self, expr);
3734 ExprKind::IfLet(ref pats, ref subexpression, ref if_block, ref optional_else) => {
3735 self.visit_expr(subexpression);
3737 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
3738 let mut bindings_list = FxHashMap();
3740 self.resolve_pattern(pat, PatternSource::IfLet, &mut bindings_list);
3742 // This has to happen *after* we determine which pat_idents are variants
3743 self.check_consistent_bindings(pats);
3744 self.visit_block(if_block);
3745 self.ribs[ValueNS].pop();
3747 optional_else.as_ref().map(|expr| self.visit_expr(expr));
3750 ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
3752 ExprKind::While(ref subexpression, ref block, label) => {
3753 self.with_resolved_label(label, expr.id, |this| {
3754 this.visit_expr(subexpression);
3755 this.visit_block(block);
3759 ExprKind::WhileLet(ref pats, ref subexpression, ref block, label) => {
3760 self.with_resolved_label(label, expr.id, |this| {
3761 this.visit_expr(subexpression);
3762 this.ribs[ValueNS].push(Rib::new(NormalRibKind));
3763 let mut bindings_list = FxHashMap();
3765 this.resolve_pattern(pat, PatternSource::WhileLet, &mut bindings_list);
3767 // This has to happen *after* we determine which pat_idents are variants
3768 this.check_consistent_bindings(pats);
3769 this.visit_block(block);
3770 this.ribs[ValueNS].pop();
3774 ExprKind::ForLoop(ref pattern, ref subexpression, ref block, label) => {
3775 self.visit_expr(subexpression);
3776 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
3777 self.resolve_pattern(pattern, PatternSource::For, &mut FxHashMap());
3779 self.resolve_labeled_block(label, expr.id, block);
3781 self.ribs[ValueNS].pop();
3784 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
3786 // Equivalent to `visit::walk_expr` + passing some context to children.
3787 ExprKind::Field(ref subexpression, _) => {
3788 self.resolve_expr(subexpression, Some(expr));
3790 ExprKind::MethodCall(ref segment, ref arguments) => {
3791 let mut arguments = arguments.iter();
3792 self.resolve_expr(arguments.next().unwrap(), Some(expr));
3793 for argument in arguments {
3794 self.resolve_expr(argument, None);
3796 self.visit_path_segment(expr.span, segment);
3799 ExprKind::Call(ref callee, ref arguments) => {
3800 self.resolve_expr(callee, Some(expr));
3801 for argument in arguments {
3802 self.resolve_expr(argument, None);
3805 ExprKind::Type(ref type_expr, _) => {
3806 self.current_type_ascription.push(type_expr.span);
3807 visit::walk_expr(self, expr);
3808 self.current_type_ascription.pop();
3811 visit::walk_expr(self, expr);
3816 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3818 ExprKind::Field(_, ident) => {
3819 // FIXME(#6890): Even though you can't treat a method like a
3820 // field, we need to add any trait methods we find that match
3821 // the field name so that we can do some nice error reporting
3822 // later on in typeck.
3823 let traits = self.get_traits_containing_item(ident, ValueNS);
3824 self.trait_map.insert(expr.id, traits);
3826 ExprKind::MethodCall(ref segment, ..) => {
3827 debug!("(recording candidate traits for expr) recording traits for {}",
3829 let traits = self.get_traits_containing_item(segment.ident, ValueNS);
3830 self.trait_map.insert(expr.id, traits);
3838 fn get_traits_containing_item(&mut self, mut ident: Ident, ns: Namespace)
3839 -> Vec<TraitCandidate> {
3840 debug!("(getting traits containing item) looking for '{}'", ident.name);
3842 let mut found_traits = Vec::new();
3843 // Look for the current trait.
3844 if let Some((module, _)) = self.current_trait_ref {
3845 if self.resolve_ident_in_module(module, ident, ns, false, false, module.span).is_ok() {
3846 let def_id = module.def_id().unwrap();
3847 found_traits.push(TraitCandidate { def_id: def_id, import_id: None });
3851 ident.span = ident.span.modern();
3852 let mut search_module = self.current_module;
3854 self.get_traits_in_module_containing_item(ident, ns, search_module, &mut found_traits);
3856 unwrap_or!(self.hygienic_lexical_parent(search_module, &mut ident.span), break);
3859 if let Some(prelude) = self.prelude {
3860 if !search_module.no_implicit_prelude {
3861 self.get_traits_in_module_containing_item(ident, ns, prelude, &mut found_traits);
3868 fn get_traits_in_module_containing_item(&mut self,
3872 found_traits: &mut Vec<TraitCandidate>) {
3873 let mut traits = module.traits.borrow_mut();
3874 if traits.is_none() {
3875 let mut collected_traits = Vec::new();
3876 module.for_each_child(|name, ns, binding| {
3877 if ns != TypeNS { return }
3878 if let Def::Trait(_) = binding.def() {
3879 collected_traits.push((name, binding));
3882 *traits = Some(collected_traits.into_boxed_slice());
3885 for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
3886 let module = binding.module().unwrap();
3887 let mut ident = ident;
3888 if ident.span.glob_adjust(module.expansion, binding.span.ctxt().modern()).is_none() {
3891 if self.resolve_ident_in_module_unadjusted(module, ident, ns, false, false, module.span)
3893 let import_id = match binding.kind {
3894 NameBindingKind::Import { directive, .. } => {
3895 self.maybe_unused_trait_imports.insert(directive.id);
3896 self.add_to_glob_map(directive.id, trait_name);
3901 let trait_def_id = module.def_id().unwrap();
3902 found_traits.push(TraitCandidate { def_id: trait_def_id, import_id: import_id });
3907 /// When name resolution fails, this method can be used to look up candidate
3908 /// entities with the expected name. It allows filtering them using the
3909 /// supplied predicate (which should be used to only accept the types of
3910 /// definitions expected e.g. traits). The lookup spans across all crates.
3912 /// NOTE: The method does not look into imports, but this is not a problem,
3913 /// since we report the definitions (thus, the de-aliased imports).
3914 fn lookup_import_candidates<FilterFn>(&mut self,
3916 namespace: Namespace,
3917 filter_fn: FilterFn)
3918 -> Vec<ImportSuggestion>
3919 where FilterFn: Fn(Def) -> bool
3921 let mut candidates = Vec::new();
3922 let mut worklist = Vec::new();
3923 let mut seen_modules = FxHashSet();
3924 worklist.push((self.graph_root, Vec::new(), false));
3926 while let Some((in_module,
3928 in_module_is_extern)) = worklist.pop() {
3929 self.populate_module_if_necessary(in_module);
3931 // We have to visit module children in deterministic order to avoid
3932 // instabilities in reported imports (#43552).
3933 in_module.for_each_child_stable(|ident, ns, name_binding| {
3934 // avoid imports entirely
3935 if name_binding.is_import() && !name_binding.is_extern_crate() { return; }
3936 // avoid non-importable candidates as well
3937 if !name_binding.is_importable() { return; }
3939 // collect results based on the filter function
3940 if ident.name == lookup_name && ns == namespace {
3941 if filter_fn(name_binding.def()) {
3943 let mut segms = path_segments.clone();
3944 segms.push(ast::PathSegment::from_ident(ident));
3946 span: name_binding.span,
3949 // the entity is accessible in the following cases:
3950 // 1. if it's defined in the same crate, it's always
3951 // accessible (since private entities can be made public)
3952 // 2. if it's defined in another crate, it's accessible
3953 // only if both the module is public and the entity is
3954 // declared as public (due to pruning, we don't explore
3955 // outside crate private modules => no need to check this)
3956 if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
3957 candidates.push(ImportSuggestion { path: path });
3962 // collect submodules to explore
3963 if let Some(module) = name_binding.module() {
3965 let mut path_segments = path_segments.clone();
3966 path_segments.push(ast::PathSegment::from_ident(ident));
3968 if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
3969 // add the module to the lookup
3970 let is_extern = in_module_is_extern || name_binding.is_extern_crate();
3971 if seen_modules.insert(module.def_id().unwrap()) {
3972 worklist.push((module, path_segments, is_extern));
3982 fn find_module(&mut self,
3984 -> Option<(Module<'a>, ImportSuggestion)>
3986 let mut result = None;
3987 let mut worklist = Vec::new();
3988 let mut seen_modules = FxHashSet();
3989 worklist.push((self.graph_root, Vec::new()));
3991 while let Some((in_module, path_segments)) = worklist.pop() {
3992 // abort if the module is already found
3993 if let Some(_) = result { break; }
3995 self.populate_module_if_necessary(in_module);
3997 in_module.for_each_child_stable(|ident, _, name_binding| {
3998 // abort if the module is already found or if name_binding is private external
3999 if result.is_some() || !name_binding.vis.is_visible_locally() {
4002 if let Some(module) = name_binding.module() {
4004 let mut path_segments = path_segments.clone();
4005 path_segments.push(ast::PathSegment::from_ident(ident));
4006 if module.def() == Some(module_def) {
4008 span: name_binding.span,
4009 segments: path_segments,
4011 result = Some((module, ImportSuggestion { path: path }));
4013 // add the module to the lookup
4014 if seen_modules.insert(module.def_id().unwrap()) {
4015 worklist.push((module, path_segments));
4025 fn collect_enum_variants(&mut self, enum_def: Def) -> Option<Vec<Path>> {
4026 if let Def::Enum(..) = enum_def {} else {
4027 panic!("Non-enum def passed to collect_enum_variants: {:?}", enum_def)
4030 self.find_module(enum_def).map(|(enum_module, enum_import_suggestion)| {
4031 self.populate_module_if_necessary(enum_module);
4033 let mut variants = Vec::new();
4034 enum_module.for_each_child_stable(|ident, _, name_binding| {
4035 if let Def::Variant(..) = name_binding.def() {
4036 let mut segms = enum_import_suggestion.path.segments.clone();
4037 segms.push(ast::PathSegment::from_ident(ident));
4038 variants.push(Path {
4039 span: name_binding.span,
4048 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
4049 debug!("(recording def) recording {:?} for {}", resolution, node_id);
4050 if let Some(prev_res) = self.def_map.insert(node_id, resolution) {
4051 panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution);
4055 fn resolve_visibility(&mut self, vis: &ast::Visibility) -> ty::Visibility {
4057 ast::VisibilityKind::Public => ty::Visibility::Public,
4058 ast::VisibilityKind::Crate(..) => {
4059 ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))
4061 ast::VisibilityKind::Inherited => {
4062 ty::Visibility::Restricted(self.current_module.normal_ancestor_id)
4064 ast::VisibilityKind::Restricted { ref path, id, .. } => {
4065 // Visibilities are resolved as global by default, add starting root segment.
4066 let segments = path.make_root().iter().chain(path.segments.iter())
4067 .map(|seg| seg.ident)
4068 .collect::<Vec<_>>();
4069 let def = self.smart_resolve_path_fragment(id, None, &segments, path.span,
4070 PathSource::Visibility).base_def();
4071 if def == Def::Err {
4072 ty::Visibility::Public
4074 let vis = ty::Visibility::Restricted(def.def_id());
4075 if self.is_accessible(vis) {
4078 self.session.span_err(path.span, "visibilities can only be restricted \
4079 to ancestor modules");
4080 ty::Visibility::Public
4087 fn is_accessible(&self, vis: ty::Visibility) -> bool {
4088 vis.is_accessible_from(self.current_module.normal_ancestor_id, self)
4091 fn is_accessible_from(&self, vis: ty::Visibility, module: Module<'a>) -> bool {
4092 vis.is_accessible_from(module.normal_ancestor_id, self)
4095 fn report_errors(&mut self, krate: &Crate) {
4096 self.report_shadowing_errors();
4097 self.report_with_use_injections(krate);
4098 self.report_proc_macro_import(krate);
4099 let mut reported_spans = FxHashSet();
4101 for &AmbiguityError { span, name, b1, b2, lexical } in &self.ambiguity_errors {
4102 if !reported_spans.insert(span) { continue }
4103 let participle = |binding: &NameBinding| {
4104 if binding.is_import() { "imported" } else { "defined" }
4106 let msg1 = format!("`{}` could refer to the name {} here", name, participle(b1));
4107 let msg2 = format!("`{}` could also refer to the name {} here", name, participle(b2));
4108 let note = if b1.expansion == Mark::root() || !lexical && b1.is_glob_import() {
4109 format!("consider adding an explicit import of `{}` to disambiguate", name)
4110 } else if let Def::Macro(..) = b1.def() {
4111 format!("macro-expanded {} do not shadow",
4112 if b1.is_import() { "macro imports" } else { "macros" })
4114 format!("macro-expanded {} do not shadow when used in a macro invocation path",
4115 if b1.is_import() { "imports" } else { "items" })
4118 let mut err = struct_span_err!(self.session, span, E0659, "`{}` is ambiguous", name);
4119 err.span_note(b1.span, &msg1);
4121 Def::Macro(..) if b2.span == DUMMY_SP =>
4122 err.note(&format!("`{}` is also a builtin macro", name)),
4123 _ => err.span_note(b2.span, &msg2),
4125 err.note(¬e).emit();
4128 for &PrivacyError(span, name, binding) in &self.privacy_errors {
4129 if !reported_spans.insert(span) { continue }
4130 span_err!(self.session, span, E0603, "{} `{}` is private", binding.descr(), name);
4134 fn report_with_use_injections(&mut self, krate: &Crate) {
4135 for UseError { mut err, candidates, node_id, better } in self.use_injections.drain(..) {
4136 let (span, found_use) = UsePlacementFinder::check(krate, node_id);
4137 if !candidates.is_empty() {
4138 show_candidates(&mut err, span, &candidates, better, found_use);
4144 fn report_shadowing_errors(&mut self) {
4145 for (ident, scope) in replace(&mut self.lexical_macro_resolutions, Vec::new()) {
4146 self.resolve_legacy_scope(scope, ident, true);
4149 let mut reported_errors = FxHashSet();
4150 for binding in replace(&mut self.disallowed_shadowing, Vec::new()) {
4151 if self.resolve_legacy_scope(&binding.parent, binding.ident, false).is_some() &&
4152 reported_errors.insert((binding.ident, binding.span)) {
4153 let msg = format!("`{}` is already in scope", binding.ident);
4154 self.session.struct_span_err(binding.span, &msg)
4155 .note("macro-expanded `macro_rules!`s may not shadow \
4156 existing macros (see RFC 1560)")
4162 fn report_conflict<'b>(&mut self,
4166 new_binding: &NameBinding<'b>,
4167 old_binding: &NameBinding<'b>) {
4168 // Error on the second of two conflicting names
4169 if old_binding.span.lo() > new_binding.span.lo() {
4170 return self.report_conflict(parent, ident, ns, old_binding, new_binding);
4173 let container = match parent.kind {
4174 ModuleKind::Def(Def::Mod(_), _) => "module",
4175 ModuleKind::Def(Def::Trait(_), _) => "trait",
4176 ModuleKind::Block(..) => "block",
4180 let old_noun = match old_binding.is_import() {
4182 false => "definition",
4185 let new_participle = match new_binding.is_import() {
4190 let (name, span) = (ident.name, self.session.codemap().def_span(new_binding.span));
4192 if let Some(s) = self.name_already_seen.get(&name) {
4198 let old_kind = match (ns, old_binding.module()) {
4199 (ValueNS, _) => "value",
4200 (MacroNS, _) => "macro",
4201 (TypeNS, _) if old_binding.is_extern_crate() => "extern crate",
4202 (TypeNS, Some(module)) if module.is_normal() => "module",
4203 (TypeNS, Some(module)) if module.is_trait() => "trait",
4204 (TypeNS, _) => "type",
4207 let namespace = match ns {
4213 let msg = format!("the name `{}` is defined multiple times", name);
4215 let mut err = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) {
4216 (true, true) => struct_span_err!(self.session, span, E0259, "{}", msg),
4217 (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() {
4218 true => struct_span_err!(self.session, span, E0254, "{}", msg),
4219 false => struct_span_err!(self.session, span, E0260, "{}", msg),
4221 _ => match (old_binding.is_import(), new_binding.is_import()) {
4222 (false, false) => struct_span_err!(self.session, span, E0428, "{}", msg),
4223 (true, true) => struct_span_err!(self.session, span, E0252, "{}", msg),
4224 _ => struct_span_err!(self.session, span, E0255, "{}", msg),
4228 err.note(&format!("`{}` must be defined only once in the {} namespace of this {}",
4233 err.span_label(span, format!("`{}` re{} here", name, new_participle));
4234 if old_binding.span != DUMMY_SP {
4235 err.span_label(self.session.codemap().def_span(old_binding.span),
4236 format!("previous {} of the {} `{}` here", old_noun, old_kind, name));
4239 // See https://github.com/rust-lang/rust/issues/32354
4240 if old_binding.is_import() || new_binding.is_import() {
4241 let binding = if new_binding.is_import() && new_binding.span != DUMMY_SP {
4247 let cm = self.session.codemap();
4248 let rename_msg = "You can use `as` to change the binding name of the import";
4250 if let (Ok(snippet), false) = (cm.span_to_snippet(binding.span),
4251 binding.is_renamed_extern_crate()) {
4252 let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() {
4253 format!("Other{}", name)
4255 format!("other_{}", name)
4258 err.span_suggestion(binding.span,
4260 if snippet.ends_with(';') {
4261 format!("{} as {};",
4262 &snippet[..snippet.len()-1],
4265 format!("{} as {}", snippet, suggested_name)
4268 err.span_label(binding.span, rename_msg);
4273 self.name_already_seen.insert(name, span);
4276 fn check_proc_macro_attrs(&mut self, attrs: &[ast::Attribute]) {
4277 if self.proc_macro_enabled { return; }
4280 if attr.path.segments.len() > 1 {
4283 let ident = attr.path.segments[0].ident;
4284 let result = self.resolve_lexical_macro_path_segment(ident,
4288 if let Ok(binding) = result {
4289 if let SyntaxExtension::AttrProcMacro(..) = *binding.binding().get_macro(self) {
4290 attr::mark_known(attr);
4292 let msg = "attribute procedural macros are experimental";
4293 let feature = "proc_macro";
4295 feature_err(&self.session.parse_sess, feature,
4296 attr.span, GateIssue::Language, msg)
4297 .span_label(binding.span(), "procedural macro imported here")
4305 fn is_self_type(path: &[Ident], namespace: Namespace) -> bool {
4306 namespace == TypeNS && path.len() == 1 && path[0].name == keywords::SelfType.name()
4309 fn is_self_value(path: &[Ident], namespace: Namespace) -> bool {
4310 namespace == ValueNS && path.len() == 1 && path[0].name == keywords::SelfValue.name()
4313 fn names_to_string(idents: &[Ident]) -> String {
4314 let mut result = String::new();
4315 for (i, ident) in idents.iter()
4316 .filter(|ident| ident.name != keywords::CrateRoot.name())
4319 result.push_str("::");
4321 result.push_str(&ident.name.as_str());
4326 fn path_names_to_string(path: &Path) -> String {
4327 names_to_string(&path.segments.iter()
4328 .map(|seg| seg.ident)
4329 .collect::<Vec<_>>())
4332 /// Get the path for an enum and the variant from an `ImportSuggestion` for an enum variant.
4333 fn import_candidate_to_paths(suggestion: &ImportSuggestion) -> (Span, String, String) {
4334 let variant_path = &suggestion.path;
4335 let variant_path_string = path_names_to_string(variant_path);
4337 let path_len = suggestion.path.segments.len();
4338 let enum_path = ast::Path {
4339 span: suggestion.path.span,
4340 segments: suggestion.path.segments[0..path_len - 1].to_vec(),
4342 let enum_path_string = path_names_to_string(&enum_path);
4344 (suggestion.path.span, variant_path_string, enum_path_string)
4348 /// When an entity with a given name is not available in scope, we search for
4349 /// entities with that name in all crates. This method allows outputting the
4350 /// results of this search in a programmer-friendly way
4351 fn show_candidates(err: &mut DiagnosticBuilder,
4352 // This is `None` if all placement locations are inside expansions
4354 candidates: &[ImportSuggestion],
4358 // we want consistent results across executions, but candidates are produced
4359 // by iterating through a hash map, so make sure they are ordered:
4360 let mut path_strings: Vec<_> =
4361 candidates.into_iter().map(|c| path_names_to_string(&c.path)).collect();
4362 path_strings.sort();
4364 let better = if better { "better " } else { "" };
4365 let msg_diff = match path_strings.len() {
4366 1 => " is found in another module, you can import it",
4367 _ => "s are found in other modules, you can import them",
4369 let msg = format!("possible {}candidate{} into scope", better, msg_diff);
4371 if let Some(span) = span {
4372 for candidate in &mut path_strings {
4373 // produce an additional newline to separate the new use statement
4374 // from the directly following item.
4375 let additional_newline = if found_use {
4380 *candidate = format!("use {};\n{}", candidate, additional_newline);
4383 err.span_suggestions(span, &msg, path_strings);
4387 for candidate in path_strings {
4389 msg.push_str(&candidate);
4394 /// A somewhat inefficient routine to obtain the name of a module.
4395 fn module_to_string(module: Module) -> Option<String> {
4396 let mut names = Vec::new();
4398 fn collect_mod(names: &mut Vec<Ident>, module: Module) {
4399 if let ModuleKind::Def(_, name) = module.kind {
4400 if let Some(parent) = module.parent {
4401 names.push(Ident::with_empty_ctxt(name));
4402 collect_mod(names, parent);
4405 // danger, shouldn't be ident?
4406 names.push(Ident::from_str("<opaque>"));
4407 collect_mod(names, module.parent.unwrap());
4410 collect_mod(&mut names, module);
4412 if names.is_empty() {
4415 Some(names_to_string(&names.into_iter()
4417 .collect::<Vec<_>>()))
4420 fn err_path_resolution() -> PathResolution {
4421 PathResolution::new(Def::Err)
4424 #[derive(PartialEq,Copy, Clone)]
4425 pub enum MakeGlobMap {
4430 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }