]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/lib.rs
Deny `internal` in stage0
[rust.git] / src / librustc_resolve / lib.rs
1 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
2
3 #![feature(crate_visibility_modifier)]
4 #![feature(label_break_value)]
5 #![feature(nll)]
6 #![feature(rustc_diagnostic_macros)]
7 #![feature(type_alias_enum_variants)]
8
9 #![recursion_limit="256"]
10
11 #![deny(rust_2018_idioms)]
12 #![deny(internal)]
13
14 pub use rustc::hir::def::{Namespace, PerNS};
15
16 use GenericParameters::*;
17 use RibKind::*;
18
19 use rustc::hir::map::{Definitions, DefCollector};
20 use rustc::hir::{self, PrimTy, Bool, Char, Float, Int, Uint, Str};
21 use rustc::middle::cstore::CrateStore;
22 use rustc::session::Session;
23 use rustc::lint;
24 use rustc::hir::def::{
25     self, PathResolution, CtorKind, CtorOf, NonMacroAttrKind, DefMap, ImportMap, ExportMap
26 };
27 use rustc::hir::def::Namespace::*;
28 use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, DefId};
29 use rustc::hir::{Freevar, FreevarMap, TraitCandidate, TraitMap, GlobMap};
30 use rustc::ty::{self, DefIdTree};
31 use rustc::util::nodemap::{NodeMap, NodeSet, FxHashMap, FxHashSet, DefIdMap};
32 use rustc::{bug, span_bug};
33
34 use rustc_metadata::creader::CrateLoader;
35 use rustc_metadata::cstore::CStore;
36
37 use syntax::source_map::SourceMap;
38 use syntax::ext::hygiene::{Mark, Transparency, SyntaxContext};
39 use syntax::ast::{self, Name, NodeId, Ident, FloatTy, IntTy, UintTy};
40 use syntax::ext::base::SyntaxExtension;
41 use syntax::ext::base::Determinacy::{self, Determined, Undetermined};
42 use syntax::ext::base::MacroKind;
43 use syntax::symbol::{Symbol, keywords};
44 use syntax::util::lev_distance::find_best_match_for_name;
45
46 use syntax::visit::{self, FnKind, Visitor};
47 use syntax::attr;
48 use syntax::ast::{CRATE_NODE_ID, Arm, IsAsync, BindingMode, Block, Crate, Expr, ExprKind};
49 use syntax::ast::{FnDecl, ForeignItem, ForeignItemKind, GenericParamKind, Generics};
50 use syntax::ast::{Item, ItemKind, ImplItem, ImplItemKind};
51 use syntax::ast::{Label, Local, Mutability, Pat, PatKind, Path};
52 use syntax::ast::{QSelf, TraitItemKind, TraitRef, Ty, TyKind};
53 use syntax::ptr::P;
54 use syntax::{span_err, struct_span_err, unwrap_or, walk_list};
55
56 use syntax_pos::{Span, DUMMY_SP, MultiSpan};
57 use errors::{Applicability, DiagnosticBuilder, DiagnosticId};
58
59 use log::debug;
60
61 use std::cell::{Cell, RefCell};
62 use std::{cmp, fmt, iter, mem, ptr};
63 use std::collections::BTreeSet;
64 use std::mem::replace;
65 use rustc_data_structures::ptr_key::PtrKey;
66 use rustc_data_structures::sync::Lrc;
67
68 use error_reporting::{find_span_of_binding_until_next_binding, extend_span_to_previous_binding};
69 use resolve_imports::{ImportDirective, ImportDirectiveSubclass, NameResolution, ImportResolver};
70 use macros::{InvocationData, LegacyBinding, ParentScope};
71
72 type Def = def::Def<NodeId>;
73
74 // N.B., this module needs to be declared first so diagnostics are
75 // registered before they are used.
76 mod diagnostics;
77 mod error_reporting;
78 mod macros;
79 mod check_unused;
80 mod build_reduced_graph;
81 mod resolve_imports;
82
83 fn is_known_tool(name: Name) -> bool {
84     ["clippy", "rustfmt"].contains(&&*name.as_str())
85 }
86
87 enum Weak {
88     Yes,
89     No,
90 }
91
92 enum ScopeSet {
93     Import(Namespace),
94     AbsolutePath(Namespace),
95     Macro(MacroKind),
96     Module,
97 }
98
99 /// A free importable items suggested in case of resolution failure.
100 struct ImportSuggestion {
101     did: Option<DefId>,
102     path: Path,
103 }
104
105 /// A field or associated item from self type suggested in case of resolution failure.
106 enum AssocSuggestion {
107     Field,
108     MethodWithSelf,
109     AssocItem,
110 }
111
112 #[derive(Eq)]
113 struct BindingError {
114     name: Name,
115     origin: BTreeSet<Span>,
116     target: BTreeSet<Span>,
117 }
118
119 struct TypoSuggestion {
120     candidate: Symbol,
121
122     /// The kind of the binding ("crate", "module", etc.)
123     kind: &'static str,
124
125     /// An appropriate article to refer to the binding ("a", "an", etc.)
126     article: &'static str,
127 }
128
129 impl PartialOrd for BindingError {
130     fn partial_cmp(&self, other: &BindingError) -> Option<cmp::Ordering> {
131         Some(self.cmp(other))
132     }
133 }
134
135 impl PartialEq for BindingError {
136     fn eq(&self, other: &BindingError) -> bool {
137         self.name == other.name
138     }
139 }
140
141 impl Ord for BindingError {
142     fn cmp(&self, other: &BindingError) -> cmp::Ordering {
143         self.name.cmp(&other.name)
144     }
145 }
146
147 /// A vector of spans and replacements, a message and applicability.
148 type Suggestion = (Vec<(Span, String)>, String, Applicability);
149
150 enum ResolutionError<'a> {
151     /// Error E0401: can't use type or const parameters from outer function.
152     GenericParamsFromOuterFunction(Def),
153     /// Error E0403: the name is already used for a type or const parameter in this generic
154     /// parameter list.
155     NameAlreadyUsedInParameterList(Name, &'a Span),
156     /// Error E0407: method is not a member of trait.
157     MethodNotMemberOfTrait(Name, &'a str),
158     /// Error E0437: type is not a member of trait.
159     TypeNotMemberOfTrait(Name, &'a str),
160     /// Error E0438: const is not a member of trait.
161     ConstNotMemberOfTrait(Name, &'a str),
162     /// Error E0408: variable `{}` is not bound in all patterns.
163     VariableNotBoundInPattern(&'a BindingError),
164     /// Error E0409: variable `{}` is bound in inconsistent ways within the same match arm.
165     VariableBoundWithDifferentMode(Name, Span),
166     /// Error E0415: identifier is bound more than once in this parameter list.
167     IdentifierBoundMoreThanOnceInParameterList(&'a str),
168     /// Error E0416: identifier is bound more than once in the same pattern.
169     IdentifierBoundMoreThanOnceInSamePattern(&'a str),
170     /// Error E0426: use of undeclared label.
171     UndeclaredLabel(&'a str, Option<Name>),
172     /// Error E0429: `self` imports are only allowed within a `{ }` list.
173     SelfImportsOnlyAllowedWithin,
174     /// Error E0430: `self` import can only appear once in the list.
175     SelfImportCanOnlyAppearOnceInTheList,
176     /// Error E0431: `self` import can only appear in an import list with a non-empty prefix.
177     SelfImportOnlyInImportListWithNonEmptyPrefix,
178     /// Error E0433: failed to resolve.
179     FailedToResolve { label: String, suggestion: Option<Suggestion> },
180     /// Error E0434: can't capture dynamic environment in a fn item.
181     CannotCaptureDynamicEnvironmentInFnItem,
182     /// Error E0435: attempt to use a non-constant value in a constant.
183     AttemptToUseNonConstantValueInConstant,
184     /// Error E0530: `X` bindings cannot shadow `Y`s.
185     BindingShadowsSomethingUnacceptable(&'a str, Name, &'a NameBinding<'a>),
186     /// Error E0128: type parameters with a default cannot use forward-declared identifiers.
187     ForwardDeclaredTyParam, // FIXME(const_generics:defaults)
188 }
189
190 /// Combines an error with provided span and emits it.
191 ///
192 /// This takes the error provided, combines it with the span and any additional spans inside the
193 /// error and emits it.
194 fn resolve_error<'sess, 'a>(resolver: &'sess Resolver<'_>,
195                             span: Span,
196                             resolution_error: ResolutionError<'a>) {
197     resolve_struct_error(resolver, span, resolution_error).emit();
198 }
199
200 fn resolve_struct_error<'sess, 'a>(resolver: &'sess Resolver<'_>,
201                                    span: Span,
202                                    resolution_error: ResolutionError<'a>)
203                                    -> DiagnosticBuilder<'sess> {
204     match resolution_error {
205         ResolutionError::GenericParamsFromOuterFunction(outer_def) => {
206             let mut err = struct_span_err!(resolver.session,
207                 span,
208                 E0401,
209                 "can't use generic parameters from outer function",
210             );
211             err.span_label(span, format!("use of generic parameter from outer function"));
212
213             let cm = resolver.session.source_map();
214             match outer_def {
215                 Def::SelfTy(maybe_trait_defid, maybe_impl_defid) => {
216                     if let Some(impl_span) = maybe_impl_defid.and_then(|def_id| {
217                         resolver.definitions.opt_span(def_id)
218                     }) {
219                         err.span_label(
220                             reduce_impl_span_to_impl_keyword(cm, impl_span),
221                             "`Self` type implicitly declared here, by this `impl`",
222                         );
223                     }
224                     match (maybe_trait_defid, maybe_impl_defid) {
225                         (Some(_), None) => {
226                             err.span_label(span, "can't use `Self` here");
227                         }
228                         (_, Some(_)) => {
229                             err.span_label(span, "use a type here instead");
230                         }
231                         (None, None) => bug!("`impl` without trait nor type?"),
232                     }
233                     return err;
234                 },
235                 Def::TyParam(def_id) => {
236                     if let Some(span) = resolver.definitions.opt_span(def_id) {
237                         err.span_label(span, "type variable from outer function");
238                     }
239                 }
240                 Def::ConstParam(def_id) => {
241                     if let Some(span) = resolver.definitions.opt_span(def_id) {
242                         err.span_label(span, "const variable from outer function");
243                     }
244                 }
245                 _ => {
246                     bug!("GenericParamsFromOuterFunction should only be used with Def::SelfTy, \
247                          Def::TyParam");
248                 }
249             }
250
251             // Try to retrieve the span of the function signature and generate a new message with
252             // a local type or const parameter.
253             let sugg_msg = &format!("try using a local generic parameter instead");
254             if let Some((sugg_span, new_snippet)) = cm.generate_local_type_param_snippet(span) {
255                 // Suggest the modification to the user
256                 err.span_suggestion(
257                     sugg_span,
258                     sugg_msg,
259                     new_snippet,
260                     Applicability::MachineApplicable,
261                 );
262             } else if let Some(sp) = cm.generate_fn_name_span(span) {
263                 err.span_label(sp,
264                     format!("try adding a local generic parameter in this method instead"));
265             } else {
266                 err.help(&format!("try using a local generic parameter instead"));
267             }
268
269             err
270         }
271         ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => {
272              let mut err = struct_span_err!(resolver.session,
273                                             span,
274                                             E0403,
275                                             "the name `{}` is already used for a generic \
276                                             parameter in this list of generic parameters",
277                                             name);
278              err.span_label(span, "already used");
279              err.span_label(first_use_span.clone(), format!("first use of `{}`", name));
280              err
281         }
282         ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
283             let mut err = struct_span_err!(resolver.session,
284                                            span,
285                                            E0407,
286                                            "method `{}` is not a member of trait `{}`",
287                                            method,
288                                            trait_);
289             err.span_label(span, format!("not a member of trait `{}`", trait_));
290             err
291         }
292         ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
293             let mut err = struct_span_err!(resolver.session,
294                              span,
295                              E0437,
296                              "type `{}` is not a member of trait `{}`",
297                              type_,
298                              trait_);
299             err.span_label(span, format!("not a member of trait `{}`", trait_));
300             err
301         }
302         ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
303             let mut err = struct_span_err!(resolver.session,
304                              span,
305                              E0438,
306                              "const `{}` is not a member of trait `{}`",
307                              const_,
308                              trait_);
309             err.span_label(span, format!("not a member of trait `{}`", trait_));
310             err
311         }
312         ResolutionError::VariableNotBoundInPattern(binding_error) => {
313             let target_sp = binding_error.target.iter().cloned().collect::<Vec<_>>();
314             let msp = MultiSpan::from_spans(target_sp.clone());
315             let msg = format!("variable `{}` is not bound in all patterns", binding_error.name);
316             let mut err = resolver.session.struct_span_err_with_code(
317                 msp,
318                 &msg,
319                 DiagnosticId::Error("E0408".into()),
320             );
321             for sp in target_sp {
322                 err.span_label(sp, format!("pattern doesn't bind `{}`", binding_error.name));
323             }
324             let origin_sp = binding_error.origin.iter().cloned();
325             for sp in origin_sp {
326                 err.span_label(sp, "variable not in all patterns");
327             }
328             err
329         }
330         ResolutionError::VariableBoundWithDifferentMode(variable_name,
331                                                         first_binding_span) => {
332             let mut err = struct_span_err!(resolver.session,
333                              span,
334                              E0409,
335                              "variable `{}` is bound in inconsistent \
336                              ways within the same match arm",
337                              variable_name);
338             err.span_label(span, "bound in different ways");
339             err.span_label(first_binding_span, "first binding");
340             err
341         }
342         ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
343             let mut err = struct_span_err!(resolver.session,
344                              span,
345                              E0415,
346                              "identifier `{}` is bound more than once in this parameter list",
347                              identifier);
348             err.span_label(span, "used as parameter more than once");
349             err
350         }
351         ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
352             let mut err = struct_span_err!(resolver.session,
353                              span,
354                              E0416,
355                              "identifier `{}` is bound more than once in the same pattern",
356                              identifier);
357             err.span_label(span, "used in a pattern more than once");
358             err
359         }
360         ResolutionError::UndeclaredLabel(name, lev_candidate) => {
361             let mut err = struct_span_err!(resolver.session,
362                                            span,
363                                            E0426,
364                                            "use of undeclared label `{}`",
365                                            name);
366             if let Some(lev_candidate) = lev_candidate {
367                 err.span_label(span, format!("did you mean `{}`?", lev_candidate));
368             } else {
369                 err.span_label(span, format!("undeclared label `{}`", name));
370             }
371             err
372         }
373         ResolutionError::SelfImportsOnlyAllowedWithin => {
374             struct_span_err!(resolver.session,
375                              span,
376                              E0429,
377                              "{}",
378                              "`self` imports are only allowed within a { } list")
379         }
380         ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
381             let mut err = struct_span_err!(resolver.session, span, E0430,
382                                            "`self` import can only appear once in an import list");
383             err.span_label(span, "can only appear once in an import list");
384             err
385         }
386         ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
387             let mut err = struct_span_err!(resolver.session, span, E0431,
388                                            "`self` import can only appear in an import list with \
389                                             a non-empty prefix");
390             err.span_label(span, "can only appear in an import list with a non-empty prefix");
391             err
392         }
393         ResolutionError::FailedToResolve { label, suggestion } => {
394             let mut err = struct_span_err!(resolver.session, span, E0433,
395                                            "failed to resolve: {}", &label);
396             err.span_label(span, label);
397
398             if let Some((suggestions, msg, applicability)) = suggestion {
399                 err.multipart_suggestion(&msg, suggestions, applicability);
400             }
401
402             err
403         }
404         ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
405             let mut err = struct_span_err!(resolver.session,
406                                            span,
407                                            E0434,
408                                            "{}",
409                                            "can't capture dynamic environment in a fn item");
410             err.help("use the `|| { ... }` closure form instead");
411             err
412         }
413         ResolutionError::AttemptToUseNonConstantValueInConstant => {
414             let mut err = struct_span_err!(resolver.session, span, E0435,
415                                            "attempt to use a non-constant value in a constant");
416             err.span_label(span, "non-constant value");
417             err
418         }
419         ResolutionError::BindingShadowsSomethingUnacceptable(what_binding, name, binding) => {
420             let shadows_what = binding.descr();
421             let mut err = struct_span_err!(resolver.session, span, E0530, "{}s cannot shadow {}s",
422                                            what_binding, shadows_what);
423             err.span_label(span, format!("cannot be named the same as {} {}",
424                                          binding.article(), shadows_what));
425             let participle = if binding.is_import() { "imported" } else { "defined" };
426             let msg = format!("the {} `{}` is {} here", shadows_what, name, participle);
427             err.span_label(binding.span, msg);
428             err
429         }
430         ResolutionError::ForwardDeclaredTyParam => {
431             let mut err = struct_span_err!(resolver.session, span, E0128,
432                                            "type parameters with a default cannot use \
433                                             forward declared identifiers");
434             err.span_label(
435                 span, "defaulted type parameters cannot be forward declared".to_string());
436             err
437         }
438     }
439 }
440
441 /// Adjust the impl span so that just the `impl` keyword is taken by removing
442 /// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
443 /// everything after the first whitespace (`"impl Iterator for A" -> "impl"`).
444 ///
445 /// *Attention*: the method used is very fragile since it essentially duplicates the work of the
446 /// parser. If you need to use this function or something similar, please consider updating the
447 /// `source_map` functions and this function to something more robust.
448 fn reduce_impl_span_to_impl_keyword(cm: &SourceMap, impl_span: Span) -> Span {
449     let impl_span = cm.span_until_char(impl_span, '<');
450     let impl_span = cm.span_until_whitespace(impl_span);
451     impl_span
452 }
453
454 #[derive(Copy, Clone, Debug)]
455 struct BindingInfo {
456     span: Span,
457     binding_mode: BindingMode,
458 }
459
460 /// Map from the name in a pattern to its binding mode.
461 type BindingMap = FxHashMap<Ident, BindingInfo>;
462
463 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
464 enum PatternSource {
465     Match,
466     IfLet,
467     WhileLet,
468     Let,
469     For,
470     FnParam,
471 }
472
473 impl PatternSource {
474     fn descr(self) -> &'static str {
475         match self {
476             PatternSource::Match => "match binding",
477             PatternSource::IfLet => "if let binding",
478             PatternSource::WhileLet => "while let binding",
479             PatternSource::Let => "let binding",
480             PatternSource::For => "for binding",
481             PatternSource::FnParam => "function parameter",
482         }
483     }
484 }
485
486 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
487 enum AliasPossibility {
488     No,
489     Maybe,
490 }
491
492 #[derive(Copy, Clone, Debug)]
493 enum PathSource<'a> {
494     // Type paths `Path`.
495     Type,
496     // Trait paths in bounds or impls.
497     Trait(AliasPossibility),
498     // Expression paths `path`, with optional parent context.
499     Expr(Option<&'a Expr>),
500     // Paths in path patterns `Path`.
501     Pat,
502     // Paths in struct expressions and patterns `Path { .. }`.
503     Struct,
504     // Paths in tuple struct patterns `Path(..)`.
505     TupleStruct,
506     // `m::A::B` in `<T as m::A>::B::C`.
507     TraitItem(Namespace),
508     // Path in `pub(path)`
509     Visibility,
510 }
511
512 impl<'a> PathSource<'a> {
513     fn namespace(self) -> Namespace {
514         match self {
515             PathSource::Type | PathSource::Trait(_) | PathSource::Struct |
516             PathSource::Visibility => TypeNS,
517             PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct => ValueNS,
518             PathSource::TraitItem(ns) => ns,
519         }
520     }
521
522     fn global_by_default(self) -> bool {
523         match self {
524             PathSource::Visibility => true,
525             PathSource::Type | PathSource::Expr(..) | PathSource::Pat |
526             PathSource::Struct | PathSource::TupleStruct |
527             PathSource::Trait(_) | PathSource::TraitItem(..) => false,
528         }
529     }
530
531     fn defer_to_typeck(self) -> bool {
532         match self {
533             PathSource::Type | PathSource::Expr(..) | PathSource::Pat |
534             PathSource::Struct | PathSource::TupleStruct => true,
535             PathSource::Trait(_) | PathSource::TraitItem(..) |
536             PathSource::Visibility => false,
537         }
538     }
539
540     fn descr_expected(self) -> &'static str {
541         match self {
542             PathSource::Type => "type",
543             PathSource::Trait(_) => "trait",
544             PathSource::Pat => "unit struct/variant or constant",
545             PathSource::Struct => "struct, variant or union type",
546             PathSource::TupleStruct => "tuple struct/variant",
547             PathSource::Visibility => "module",
548             PathSource::TraitItem(ns) => match ns {
549                 TypeNS => "associated type",
550                 ValueNS => "method or associated constant",
551                 MacroNS => bug!("associated macro"),
552             },
553             PathSource::Expr(parent) => match parent.map(|p| &p.node) {
554                 // "function" here means "anything callable" rather than `Def::Fn`,
555                 // this is not precise but usually more helpful than just "value".
556                 Some(&ExprKind::Call(..)) => "function",
557                 _ => "value",
558             },
559         }
560     }
561
562     fn is_expected(self, def: Def) -> bool {
563         match self {
564             PathSource::Type => match def {
565                 Def::Struct(..) | Def::Union(..) | Def::Enum(..) |
566                 Def::Trait(..) | Def::TraitAlias(..) | Def::TyAlias(..) |
567                 Def::AssociatedTy(..) | Def::PrimTy(..) | Def::TyParam(..) |
568                 Def::SelfTy(..) | Def::Existential(..) | Def::ForeignTy(..) => true,
569                 _ => false,
570             },
571             PathSource::Trait(AliasPossibility::No) => match def {
572                 Def::Trait(..) => true,
573                 _ => false,
574             },
575             PathSource::Trait(AliasPossibility::Maybe) => match def {
576                 Def::Trait(..) => true,
577                 Def::TraitAlias(..) => true,
578                 _ => false,
579             },
580             PathSource::Expr(..) => match def {
581                 Def::Ctor(_, _, CtorKind::Const) | Def::Ctor(_, _, CtorKind::Fn) |
582                 Def::Const(..) | Def::Static(..) | Def::Local(..) | Def::Upvar(..) |
583                 Def::Fn(..) | Def::Method(..) | Def::AssociatedConst(..) |
584                 Def::SelfCtor(..) | Def::ConstParam(..) => true,
585                 _ => false,
586             },
587             PathSource::Pat => match def {
588                 Def::Ctor(_, _, CtorKind::Const) |
589                 Def::Const(..) | Def::AssociatedConst(..) |
590                 Def::SelfCtor(..) => true,
591                 _ => false,
592             },
593             PathSource::TupleStruct => match def {
594                 Def::Ctor(_, _, CtorKind::Fn) | Def::SelfCtor(..) => true,
595                 _ => false,
596             },
597             PathSource::Struct => match def {
598                 Def::Struct(..) | Def::Union(..) | Def::Variant(..) |
599                 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => true,
600                 _ => false,
601             },
602             PathSource::TraitItem(ns) => match def {
603                 Def::AssociatedConst(..) | Def::Method(..) if ns == ValueNS => true,
604                 Def::AssociatedTy(..) if ns == TypeNS => true,
605                 _ => false,
606             },
607             PathSource::Visibility => match def {
608                 Def::Mod(..) => true,
609                 _ => false,
610             },
611         }
612     }
613
614     fn error_code(self, has_unexpected_resolution: bool) -> &'static str {
615         __diagnostic_used!(E0404);
616         __diagnostic_used!(E0405);
617         __diagnostic_used!(E0412);
618         __diagnostic_used!(E0422);
619         __diagnostic_used!(E0423);
620         __diagnostic_used!(E0425);
621         __diagnostic_used!(E0531);
622         __diagnostic_used!(E0532);
623         __diagnostic_used!(E0573);
624         __diagnostic_used!(E0574);
625         __diagnostic_used!(E0575);
626         __diagnostic_used!(E0576);
627         __diagnostic_used!(E0577);
628         __diagnostic_used!(E0578);
629         match (self, has_unexpected_resolution) {
630             (PathSource::Trait(_), true) => "E0404",
631             (PathSource::Trait(_), false) => "E0405",
632             (PathSource::Type, true) => "E0573",
633             (PathSource::Type, false) => "E0412",
634             (PathSource::Struct, true) => "E0574",
635             (PathSource::Struct, false) => "E0422",
636             (PathSource::Expr(..), true) => "E0423",
637             (PathSource::Expr(..), false) => "E0425",
638             (PathSource::Pat, true) | (PathSource::TupleStruct, true) => "E0532",
639             (PathSource::Pat, false) | (PathSource::TupleStruct, false) => "E0531",
640             (PathSource::TraitItem(..), true) => "E0575",
641             (PathSource::TraitItem(..), false) => "E0576",
642             (PathSource::Visibility, true) => "E0577",
643             (PathSource::Visibility, false) => "E0578",
644         }
645     }
646 }
647
648 // A minimal representation of a path segment. We use this in resolve because
649 // we synthesize 'path segments' which don't have the rest of an AST or HIR
650 // `PathSegment`.
651 #[derive(Clone, Copy, Debug)]
652 pub struct Segment {
653     ident: Ident,
654     id: Option<NodeId>,
655 }
656
657 impl Segment {
658     fn from_path(path: &Path) -> Vec<Segment> {
659         path.segments.iter().map(|s| s.into()).collect()
660     }
661
662     fn from_ident(ident: Ident) -> Segment {
663         Segment {
664             ident,
665             id: None,
666         }
667     }
668
669     fn names_to_string(segments: &[Segment]) -> String {
670         names_to_string(&segments.iter()
671                             .map(|seg| seg.ident)
672                             .collect::<Vec<_>>())
673     }
674 }
675
676 impl<'a> From<&'a ast::PathSegment> for Segment {
677     fn from(seg: &'a ast::PathSegment) -> Segment {
678         Segment {
679             ident: seg.ident,
680             id: Some(seg.id),
681         }
682     }
683 }
684
685 struct UsePlacementFinder {
686     target_module: NodeId,
687     span: Option<Span>,
688     found_use: bool,
689 }
690
691 impl UsePlacementFinder {
692     fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, bool) {
693         let mut finder = UsePlacementFinder {
694             target_module,
695             span: None,
696             found_use: false,
697         };
698         visit::walk_crate(&mut finder, krate);
699         (finder.span, finder.found_use)
700     }
701 }
702
703 impl<'tcx> Visitor<'tcx> for UsePlacementFinder {
704     fn visit_mod(
705         &mut self,
706         module: &'tcx ast::Mod,
707         _: Span,
708         _: &[ast::Attribute],
709         node_id: NodeId,
710     ) {
711         if self.span.is_some() {
712             return;
713         }
714         if node_id != self.target_module {
715             visit::walk_mod(self, module);
716             return;
717         }
718         // find a use statement
719         for item in &module.items {
720             match item.node {
721                 ItemKind::Use(..) => {
722                     // don't suggest placing a use before the prelude
723                     // import or other generated ones
724                     if item.span.ctxt().outer().expn_info().is_none() {
725                         self.span = Some(item.span.shrink_to_lo());
726                         self.found_use = true;
727                         return;
728                     }
729                 },
730                 // don't place use before extern crate
731                 ItemKind::ExternCrate(_) => {}
732                 // but place them before the first other item
733                 _ => if self.span.map_or(true, |span| item.span < span ) {
734                     if item.span.ctxt().outer().expn_info().is_none() {
735                         // don't insert between attributes and an item
736                         if item.attrs.is_empty() {
737                             self.span = Some(item.span.shrink_to_lo());
738                         } else {
739                             // find the first attribute on the item
740                             for attr in &item.attrs {
741                                 if self.span.map_or(true, |span| attr.span < span) {
742                                     self.span = Some(attr.span.shrink_to_lo());
743                                 }
744                             }
745                         }
746                     }
747                 },
748             }
749         }
750     }
751 }
752
753 /// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
754 impl<'a, 'tcx> Visitor<'tcx> for Resolver<'a> {
755     fn visit_item(&mut self, item: &'tcx Item) {
756         self.resolve_item(item);
757     }
758     fn visit_arm(&mut self, arm: &'tcx Arm) {
759         self.resolve_arm(arm);
760     }
761     fn visit_block(&mut self, block: &'tcx Block) {
762         self.resolve_block(block);
763     }
764     fn visit_anon_const(&mut self, constant: &'tcx ast::AnonConst) {
765         debug!("visit_anon_const {:?}", constant);
766         self.with_constant_rib(|this| {
767             visit::walk_anon_const(this, constant);
768         });
769     }
770     fn visit_expr(&mut self, expr: &'tcx Expr) {
771         self.resolve_expr(expr, None);
772     }
773     fn visit_local(&mut self, local: &'tcx Local) {
774         self.resolve_local(local);
775     }
776     fn visit_ty(&mut self, ty: &'tcx Ty) {
777         match ty.node {
778             TyKind::Path(ref qself, ref path) => {
779                 self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
780             }
781             TyKind::ImplicitSelf => {
782                 let self_ty = keywords::SelfUpper.ident();
783                 let def = self.resolve_ident_in_lexical_scope(self_ty, TypeNS, Some(ty.id), ty.span)
784                               .map_or(Def::Err, |d| d.def());
785                 self.record_def(ty.id, PathResolution::new(def));
786             }
787             _ => (),
788         }
789         visit::walk_ty(self, ty);
790     }
791     fn visit_poly_trait_ref(&mut self,
792                             tref: &'tcx ast::PolyTraitRef,
793                             m: &'tcx ast::TraitBoundModifier) {
794         self.smart_resolve_path(tref.trait_ref.ref_id, None,
795                                 &tref.trait_ref.path, PathSource::Trait(AliasPossibility::Maybe));
796         visit::walk_poly_trait_ref(self, tref, m);
797     }
798     fn visit_foreign_item(&mut self, foreign_item: &'tcx ForeignItem) {
799         let generic_params = match foreign_item.node {
800             ForeignItemKind::Fn(_, ref generics) => {
801                 HasGenericParams(generics, ItemRibKind)
802             }
803             ForeignItemKind::Static(..) => NoGenericParams,
804             ForeignItemKind::Ty => NoGenericParams,
805             ForeignItemKind::Macro(..) => NoGenericParams,
806         };
807         self.with_generic_param_rib(generic_params, |this| {
808             visit::walk_foreign_item(this, foreign_item);
809         });
810     }
811     fn visit_fn(&mut self,
812                 function_kind: FnKind<'tcx>,
813                 declaration: &'tcx FnDecl,
814                 _: Span,
815                 node_id: NodeId)
816     {
817         debug!("(resolving function) entering function");
818         let (rib_kind, asyncness) = match function_kind {
819             FnKind::ItemFn(_, ref header, ..) =>
820                 (FnItemRibKind, header.asyncness.node),
821             FnKind::Method(_, ref sig, _, _) =>
822                 (TraitOrImplItemRibKind, sig.header.asyncness.node),
823             FnKind::Closure(_) =>
824                 // Async closures aren't resolved through `visit_fn`-- they're
825                 // processed separately
826                 (ClosureRibKind(node_id), IsAsync::NotAsync),
827         };
828
829         // Create a value rib for the function.
830         self.ribs[ValueNS].push(Rib::new(rib_kind));
831
832         // Create a label rib for the function.
833         self.label_ribs.push(Rib::new(rib_kind));
834
835         // Add each argument to the rib.
836         let mut bindings_list = FxHashMap::default();
837         for argument in &declaration.inputs {
838             self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
839
840             self.visit_ty(&argument.ty);
841
842             debug!("(resolving function) recorded argument");
843         }
844         visit::walk_fn_ret_ty(self, &declaration.output);
845
846         // Resolve the function body, potentially inside the body of an async closure
847         if let IsAsync::Async { closure_id, .. } = asyncness {
848             let rib_kind = ClosureRibKind(closure_id);
849             self.ribs[ValueNS].push(Rib::new(rib_kind));
850             self.label_ribs.push(Rib::new(rib_kind));
851         }
852
853         match function_kind {
854             FnKind::ItemFn(.., body) |
855             FnKind::Method(.., body) => {
856                 self.visit_block(body);
857             }
858             FnKind::Closure(body) => {
859                 self.visit_expr(body);
860             }
861         };
862
863         // Leave the body of the async closure
864         if asyncness.is_async() {
865             self.label_ribs.pop();
866             self.ribs[ValueNS].pop();
867         }
868
869         debug!("(resolving function) leaving function");
870
871         self.label_ribs.pop();
872         self.ribs[ValueNS].pop();
873     }
874
875     fn visit_generics(&mut self, generics: &'tcx Generics) {
876         // For type parameter defaults, we have to ban access
877         // to following type parameters, as the InternalSubsts can only
878         // provide previous type parameters as they're built. We
879         // put all the parameters on the ban list and then remove
880         // them one by one as they are processed and become available.
881         let mut default_ban_rib = Rib::new(ForwardTyParamBanRibKind);
882         let mut found_default = false;
883         default_ban_rib.bindings.extend(generics.params.iter()
884             .filter_map(|param| match param.kind {
885                 GenericParamKind::Const { .. } |
886                 GenericParamKind::Lifetime { .. } => None,
887                 GenericParamKind::Type { ref default, .. } => {
888                     found_default |= default.is_some();
889                     if found_default {
890                         Some((Ident::with_empty_ctxt(param.ident.name), Def::Err))
891                     } else {
892                         None
893                     }
894                 }
895             }));
896
897         for param in &generics.params {
898             match param.kind {
899                 GenericParamKind::Lifetime { .. } => self.visit_generic_param(param),
900                 GenericParamKind::Type { ref default, .. } => {
901                     for bound in &param.bounds {
902                         self.visit_param_bound(bound);
903                     }
904
905                     if let Some(ref ty) = default {
906                         self.ribs[TypeNS].push(default_ban_rib);
907                         self.visit_ty(ty);
908                         default_ban_rib = self.ribs[TypeNS].pop().unwrap();
909                     }
910
911                     // Allow all following defaults to refer to this type parameter.
912                     default_ban_rib.bindings.remove(&Ident::with_empty_ctxt(param.ident.name));
913                 }
914                 GenericParamKind::Const { ref ty } => {
915                     for bound in &param.bounds {
916                         self.visit_param_bound(bound);
917                     }
918
919                     self.visit_ty(ty);
920                 }
921             }
922         }
923         for p in &generics.where_clause.predicates {
924             self.visit_where_predicate(p);
925         }
926     }
927 }
928
929 #[derive(Copy, Clone)]
930 enum GenericParameters<'a, 'b> {
931     NoGenericParams,
932     HasGenericParams(// Type parameters.
933                       &'b Generics,
934
935                       // The kind of the rib used for type parameters.
936                       RibKind<'a>),
937 }
938
939 /// The rib kind controls the translation of local
940 /// definitions (`Def::Local`) to upvars (`Def::Upvar`).
941 #[derive(Copy, Clone, Debug)]
942 enum RibKind<'a> {
943     /// No translation needs to be applied.
944     NormalRibKind,
945
946     /// We passed through a closure scope at the given `NodeId`.
947     /// Translate upvars as appropriate.
948     ClosureRibKind(NodeId /* func id */),
949
950     /// We passed through an impl or trait and are now in one of its
951     /// methods or associated types. Allow references to ty params that impl or trait
952     /// binds. Disallow any other upvars (including other ty params that are
953     /// upvars).
954     TraitOrImplItemRibKind,
955
956     /// We passed through a function definition. Disallow upvars.
957     /// Permit only those const parameters that are specified in the function's generics.
958     FnItemRibKind,
959
960     /// We passed through an item scope. Disallow upvars.
961     ItemRibKind,
962
963     /// We're in a constant item. Can't refer to dynamic stuff.
964     ConstantItemRibKind,
965
966     /// We passed through a module.
967     ModuleRibKind(Module<'a>),
968
969     /// We passed through a `macro_rules!` statement
970     MacroDefinition(DefId),
971
972     /// All bindings in this rib are type parameters that can't be used
973     /// from the default of a type parameter because they're not declared
974     /// before said type parameter. Also see the `visit_generics` override.
975     ForwardTyParamBanRibKind,
976 }
977
978 /// A single local scope.
979 ///
980 /// A rib represents a scope names can live in. Note that these appear in many places, not just
981 /// around braces. At any place where the list of accessible names (of the given namespace)
982 /// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
983 /// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
984 /// etc.
985 ///
986 /// Different [rib kinds](enum.RibKind) are transparent for different names.
987 ///
988 /// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
989 /// resolving, the name is looked up from inside out.
990 #[derive(Debug)]
991 struct Rib<'a> {
992     bindings: FxHashMap<Ident, Def>,
993     kind: RibKind<'a>,
994 }
995
996 impl<'a> Rib<'a> {
997     fn new(kind: RibKind<'a>) -> Rib<'a> {
998         Rib {
999             bindings: Default::default(),
1000             kind,
1001         }
1002     }
1003 }
1004
1005 /// An intermediate resolution result.
1006 ///
1007 /// This refers to the thing referred by a name. The difference between `Def` and `Item` is that
1008 /// items are visible in their whole block, while defs only from the place they are defined
1009 /// forward.
1010 enum LexicalScopeBinding<'a> {
1011     Item(&'a NameBinding<'a>),
1012     Def(Def),
1013 }
1014
1015 impl<'a> LexicalScopeBinding<'a> {
1016     fn item(self) -> Option<&'a NameBinding<'a>> {
1017         match self {
1018             LexicalScopeBinding::Item(binding) => Some(binding),
1019             _ => None,
1020         }
1021     }
1022
1023     fn def(self) -> Def {
1024         match self {
1025             LexicalScopeBinding::Item(binding) => binding.def(),
1026             LexicalScopeBinding::Def(def) => def,
1027         }
1028     }
1029 }
1030
1031 #[derive(Copy, Clone, Debug)]
1032 enum ModuleOrUniformRoot<'a> {
1033     /// Regular module.
1034     Module(Module<'a>),
1035
1036     /// Virtual module that denotes resolution in crate root with fallback to extern prelude.
1037     CrateRootAndExternPrelude,
1038
1039     /// Virtual module that denotes resolution in extern prelude.
1040     /// Used for paths starting with `::` on 2018 edition.
1041     ExternPrelude,
1042
1043     /// Virtual module that denotes resolution in current scope.
1044     /// Used only for resolving single-segment imports. The reason it exists is that import paths
1045     /// are always split into two parts, the first of which should be some kind of module.
1046     CurrentScope,
1047 }
1048
1049 impl ModuleOrUniformRoot<'_> {
1050     fn same_def(lhs: Self, rhs: Self) -> bool {
1051         match (lhs, rhs) {
1052             (ModuleOrUniformRoot::Module(lhs),
1053              ModuleOrUniformRoot::Module(rhs)) => lhs.def() == rhs.def(),
1054             (ModuleOrUniformRoot::CrateRootAndExternPrelude,
1055              ModuleOrUniformRoot::CrateRootAndExternPrelude) |
1056             (ModuleOrUniformRoot::ExternPrelude, ModuleOrUniformRoot::ExternPrelude) |
1057             (ModuleOrUniformRoot::CurrentScope, ModuleOrUniformRoot::CurrentScope) => true,
1058             _ => false,
1059         }
1060     }
1061 }
1062
1063 #[derive(Clone, Debug)]
1064 enum PathResult<'a> {
1065     Module(ModuleOrUniformRoot<'a>),
1066     NonModule(PathResolution),
1067     Indeterminate,
1068     Failed {
1069         span: Span,
1070         label: String,
1071         suggestion: Option<Suggestion>,
1072         is_error_from_last_segment: bool,
1073     },
1074 }
1075
1076 enum ModuleKind {
1077     /// An anonymous module; e.g., just a block.
1078     ///
1079     /// ```
1080     /// fn main() {
1081     ///     fn f() {} // (1)
1082     ///     { // This is an anonymous module
1083     ///         f(); // This resolves to (2) as we are inside the block.
1084     ///         fn f() {} // (2)
1085     ///     }
1086     ///     f(); // Resolves to (1)
1087     /// }
1088     /// ```
1089     Block(NodeId),
1090     /// Any module with a name.
1091     ///
1092     /// This could be:
1093     ///
1094     /// * A normal module â€’ either `mod from_file;` or `mod from_block { }`.
1095     /// * A trait or an enum (it implicitly contains associated types, methods and variant
1096     ///   constructors).
1097     Def(Def, Name),
1098 }
1099
1100 impl ModuleKind {
1101     /// Get name of the module.
1102     pub fn name(&self) -> Option<Name> {
1103         match self {
1104             ModuleKind::Block(..) => None,
1105             ModuleKind::Def(_, name) => Some(*name),
1106         }
1107     }
1108 }
1109
1110 /// One node in the tree of modules.
1111 pub struct ModuleData<'a> {
1112     parent: Option<Module<'a>>,
1113     kind: ModuleKind,
1114
1115     // The def id of the closest normal module (`mod`) ancestor (including this module).
1116     normal_ancestor_id: DefId,
1117
1118     resolutions: RefCell<FxHashMap<(Ident, Namespace), &'a RefCell<NameResolution<'a>>>>,
1119     single_segment_macro_resolutions: RefCell<Vec<(Ident, MacroKind, ParentScope<'a>,
1120                                                    Option<&'a NameBinding<'a>>)>>,
1121     multi_segment_macro_resolutions: RefCell<Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'a>,
1122                                                   Option<Def>)>>,
1123     builtin_attrs: RefCell<Vec<(Ident, ParentScope<'a>)>>,
1124
1125     // Macro invocations that can expand into items in this module.
1126     unresolved_invocations: RefCell<FxHashSet<Mark>>,
1127
1128     no_implicit_prelude: bool,
1129
1130     glob_importers: RefCell<Vec<&'a ImportDirective<'a>>>,
1131     globs: RefCell<Vec<&'a ImportDirective<'a>>>,
1132
1133     // Used to memoize the traits in this module for faster searches through all traits in scope.
1134     traits: RefCell<Option<Box<[(Ident, &'a NameBinding<'a>)]>>>,
1135
1136     // Whether this module is populated. If not populated, any attempt to
1137     // access the children must be preceded with a
1138     // `populate_module_if_necessary` call.
1139     populated: Cell<bool>,
1140
1141     /// Span of the module itself. Used for error reporting.
1142     span: Span,
1143
1144     expansion: Mark,
1145 }
1146
1147 type Module<'a> = &'a ModuleData<'a>;
1148
1149 impl<'a> ModuleData<'a> {
1150     fn new(parent: Option<Module<'a>>,
1151            kind: ModuleKind,
1152            normal_ancestor_id: DefId,
1153            expansion: Mark,
1154            span: Span) -> Self {
1155         ModuleData {
1156             parent,
1157             kind,
1158             normal_ancestor_id,
1159             resolutions: Default::default(),
1160             single_segment_macro_resolutions: RefCell::new(Vec::new()),
1161             multi_segment_macro_resolutions: RefCell::new(Vec::new()),
1162             builtin_attrs: RefCell::new(Vec::new()),
1163             unresolved_invocations: Default::default(),
1164             no_implicit_prelude: false,
1165             glob_importers: RefCell::new(Vec::new()),
1166             globs: RefCell::new(Vec::new()),
1167             traits: RefCell::new(None),
1168             populated: Cell::new(normal_ancestor_id.is_local()),
1169             span,
1170             expansion,
1171         }
1172     }
1173
1174     fn for_each_child<F: FnMut(Ident, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
1175         for (&(ident, ns), name_resolution) in self.resolutions.borrow().iter() {
1176             name_resolution.borrow().binding.map(|binding| f(ident, ns, binding));
1177         }
1178     }
1179
1180     fn for_each_child_stable<F: FnMut(Ident, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
1181         let resolutions = self.resolutions.borrow();
1182         let mut resolutions = resolutions.iter().collect::<Vec<_>>();
1183         resolutions.sort_by_cached_key(|&(&(ident, ns), _)| (ident.as_str(), ns));
1184         for &(&(ident, ns), &resolution) in resolutions.iter() {
1185             resolution.borrow().binding.map(|binding| f(ident, ns, binding));
1186         }
1187     }
1188
1189     fn def(&self) -> Option<Def> {
1190         match self.kind {
1191             ModuleKind::Def(def, _) => Some(def),
1192             _ => None,
1193         }
1194     }
1195
1196     fn def_id(&self) -> Option<DefId> {
1197         self.def().as_ref().map(Def::def_id)
1198     }
1199
1200     // `self` resolves to the first module ancestor that `is_normal`.
1201     fn is_normal(&self) -> bool {
1202         match self.kind {
1203             ModuleKind::Def(Def::Mod(_), _) => true,
1204             _ => false,
1205         }
1206     }
1207
1208     fn is_trait(&self) -> bool {
1209         match self.kind {
1210             ModuleKind::Def(Def::Trait(_), _) => true,
1211             _ => false,
1212         }
1213     }
1214
1215     fn nearest_item_scope(&'a self) -> Module<'a> {
1216         if self.is_trait() { self.parent.unwrap() } else { self }
1217     }
1218
1219     fn is_ancestor_of(&self, mut other: &Self) -> bool {
1220         while !ptr::eq(self, other) {
1221             if let Some(parent) = other.parent {
1222                 other = parent;
1223             } else {
1224                 return false;
1225             }
1226         }
1227         true
1228     }
1229 }
1230
1231 impl<'a> fmt::Debug for ModuleData<'a> {
1232     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1233         write!(f, "{:?}", self.def())
1234     }
1235 }
1236
1237 /// Records a possibly-private value, type, or module definition.
1238 #[derive(Clone, Debug)]
1239 pub struct NameBinding<'a> {
1240     kind: NameBindingKind<'a>,
1241     ambiguity: Option<(&'a NameBinding<'a>, AmbiguityKind)>,
1242     expansion: Mark,
1243     span: Span,
1244     vis: ty::Visibility,
1245 }
1246
1247 pub trait ToNameBinding<'a> {
1248     fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a>;
1249 }
1250
1251 impl<'a> ToNameBinding<'a> for &'a NameBinding<'a> {
1252     fn to_name_binding(self, _: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
1253         self
1254     }
1255 }
1256
1257 #[derive(Clone, Debug)]
1258 enum NameBindingKind<'a> {
1259     Def(Def, /* is_macro_export */ bool),
1260     Module(Module<'a>),
1261     Import {
1262         binding: &'a NameBinding<'a>,
1263         directive: &'a ImportDirective<'a>,
1264         used: Cell<bool>,
1265     },
1266 }
1267
1268 impl<'a> NameBindingKind<'a> {
1269     /// Is this a name binding of a import?
1270     fn is_import(&self) -> bool {
1271         match *self {
1272             NameBindingKind::Import { .. } => true,
1273             _ => false,
1274         }
1275     }
1276 }
1277
1278 struct PrivacyError<'a>(Span, Ident, &'a NameBinding<'a>);
1279
1280 struct UseError<'a> {
1281     err: DiagnosticBuilder<'a>,
1282     /// Attach `use` statements for these candidates.
1283     candidates: Vec<ImportSuggestion>,
1284     /// The `NodeId` of the module to place the use-statements in.
1285     node_id: NodeId,
1286     /// Whether the diagnostic should state that it's "better".
1287     better: bool,
1288 }
1289
1290 #[derive(Clone, Copy, PartialEq, Debug)]
1291 enum AmbiguityKind {
1292     Import,
1293     BuiltinAttr,
1294     DeriveHelper,
1295     LegacyHelperVsPrelude,
1296     LegacyVsModern,
1297     GlobVsOuter,
1298     GlobVsGlob,
1299     GlobVsExpanded,
1300     MoreExpandedVsOuter,
1301 }
1302
1303 impl AmbiguityKind {
1304     fn descr(self) -> &'static str {
1305         match self {
1306             AmbiguityKind::Import =>
1307                 "name vs any other name during import resolution",
1308             AmbiguityKind::BuiltinAttr =>
1309                 "built-in attribute vs any other name",
1310             AmbiguityKind::DeriveHelper =>
1311                 "derive helper attribute vs any other name",
1312             AmbiguityKind::LegacyHelperVsPrelude =>
1313                 "legacy plugin helper attribute vs name from prelude",
1314             AmbiguityKind::LegacyVsModern =>
1315                 "`macro_rules` vs non-`macro_rules` from other module",
1316             AmbiguityKind::GlobVsOuter =>
1317                 "glob import vs any other name from outer scope during import/macro resolution",
1318             AmbiguityKind::GlobVsGlob =>
1319                 "glob import vs glob import in the same module",
1320             AmbiguityKind::GlobVsExpanded =>
1321                 "glob import vs macro-expanded name in the same \
1322                  module during import/macro resolution",
1323             AmbiguityKind::MoreExpandedVsOuter =>
1324                 "macro-expanded name vs less macro-expanded name \
1325                  from outer scope during import/macro resolution",
1326         }
1327     }
1328 }
1329
1330 /// Miscellaneous bits of metadata for better ambiguity error reporting.
1331 #[derive(Clone, Copy, PartialEq)]
1332 enum AmbiguityErrorMisc {
1333     SuggestCrate,
1334     SuggestSelf,
1335     FromPrelude,
1336     None,
1337 }
1338
1339 struct AmbiguityError<'a> {
1340     kind: AmbiguityKind,
1341     ident: Ident,
1342     b1: &'a NameBinding<'a>,
1343     b2: &'a NameBinding<'a>,
1344     misc1: AmbiguityErrorMisc,
1345     misc2: AmbiguityErrorMisc,
1346 }
1347
1348 impl<'a> NameBinding<'a> {
1349     fn module(&self) -> Option<Module<'a>> {
1350         match self.kind {
1351             NameBindingKind::Module(module) => Some(module),
1352             NameBindingKind::Import { binding, .. } => binding.module(),
1353             _ => None,
1354         }
1355     }
1356
1357     fn def(&self) -> Def {
1358         match self.kind {
1359             NameBindingKind::Def(def, _) => def,
1360             NameBindingKind::Module(module) => module.def().unwrap(),
1361             NameBindingKind::Import { binding, .. } => binding.def(),
1362         }
1363     }
1364
1365     fn is_ambiguity(&self) -> bool {
1366         self.ambiguity.is_some() || match self.kind {
1367             NameBindingKind::Import { binding, .. } => binding.is_ambiguity(),
1368             _ => false,
1369         }
1370     }
1371
1372     // We sometimes need to treat variants as `pub` for backwards compatibility.
1373     fn pseudo_vis(&self) -> ty::Visibility {
1374         if self.is_variant() && self.def().def_id().is_local() {
1375             ty::Visibility::Public
1376         } else {
1377             self.vis
1378         }
1379     }
1380
1381     fn is_variant(&self) -> bool {
1382         match self.kind {
1383             NameBindingKind::Def(Def::Variant(..), _) |
1384             NameBindingKind::Def(Def::Ctor(_, CtorOf::Variant, ..), _) => true,
1385             _ => false,
1386         }
1387     }
1388
1389     fn is_extern_crate(&self) -> bool {
1390         match self.kind {
1391             NameBindingKind::Import {
1392                 directive: &ImportDirective {
1393                     subclass: ImportDirectiveSubclass::ExternCrate { .. }, ..
1394                 }, ..
1395             } => true,
1396             NameBindingKind::Module(
1397                 &ModuleData { kind: ModuleKind::Def(Def::Mod(def_id), _), .. }
1398             ) => def_id.index == CRATE_DEF_INDEX,
1399             _ => false,
1400         }
1401     }
1402
1403     fn is_import(&self) -> bool {
1404         match self.kind {
1405             NameBindingKind::Import { .. } => true,
1406             _ => false,
1407         }
1408     }
1409
1410     fn is_glob_import(&self) -> bool {
1411         match self.kind {
1412             NameBindingKind::Import { directive, .. } => directive.is_glob(),
1413             _ => false,
1414         }
1415     }
1416
1417     fn is_importable(&self) -> bool {
1418         match self.def() {
1419             Def::AssociatedConst(..) | Def::Method(..) | Def::AssociatedTy(..) => false,
1420             _ => true,
1421         }
1422     }
1423
1424     fn is_macro_def(&self) -> bool {
1425         match self.kind {
1426             NameBindingKind::Def(Def::Macro(..), _) => true,
1427             _ => false,
1428         }
1429     }
1430
1431     fn macro_kind(&self) -> Option<MacroKind> {
1432         match self.def() {
1433             Def::Macro(_, kind) => Some(kind),
1434             Def::NonMacroAttr(..) => Some(MacroKind::Attr),
1435             _ => None,
1436         }
1437     }
1438
1439     fn descr(&self) -> &'static str {
1440         if self.is_extern_crate() { "extern crate" } else { self.def().kind_name() }
1441     }
1442
1443     fn article(&self) -> &'static str {
1444         if self.is_extern_crate() { "an" } else { self.def().article() }
1445     }
1446
1447     // Suppose that we resolved macro invocation with `invoc_parent_expansion` to binding `binding`
1448     // at some expansion round `max(invoc, binding)` when they both emerged from macros.
1449     // Then this function returns `true` if `self` may emerge from a macro *after* that
1450     // in some later round and screw up our previously found resolution.
1451     // See more detailed explanation in
1452     // https://github.com/rust-lang/rust/pull/53778#issuecomment-419224049
1453     fn may_appear_after(&self, invoc_parent_expansion: Mark, binding: &NameBinding<'_>) -> bool {
1454         // self > max(invoc, binding) => !(self <= invoc || self <= binding)
1455         // Expansions are partially ordered, so "may appear after" is an inversion of
1456         // "certainly appears before or simultaneously" and includes unordered cases.
1457         let self_parent_expansion = self.expansion;
1458         let other_parent_expansion = binding.expansion;
1459         let certainly_before_other_or_simultaneously =
1460             other_parent_expansion.is_descendant_of(self_parent_expansion);
1461         let certainly_before_invoc_or_simultaneously =
1462             invoc_parent_expansion.is_descendant_of(self_parent_expansion);
1463         !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
1464     }
1465 }
1466
1467 /// Interns the names of the primitive types.
1468 ///
1469 /// All other types are defined somewhere and possibly imported, but the primitive ones need
1470 /// special handling, since they have no place of origin.
1471 #[derive(Default)]
1472 struct PrimitiveTypeTable {
1473     primitive_types: FxHashMap<Name, PrimTy>,
1474 }
1475
1476 impl PrimitiveTypeTable {
1477     fn new() -> PrimitiveTypeTable {
1478         let mut table = PrimitiveTypeTable::default();
1479
1480         table.intern("bool", Bool);
1481         table.intern("char", Char);
1482         table.intern("f32", Float(FloatTy::F32));
1483         table.intern("f64", Float(FloatTy::F64));
1484         table.intern("isize", Int(IntTy::Isize));
1485         table.intern("i8", Int(IntTy::I8));
1486         table.intern("i16", Int(IntTy::I16));
1487         table.intern("i32", Int(IntTy::I32));
1488         table.intern("i64", Int(IntTy::I64));
1489         table.intern("i128", Int(IntTy::I128));
1490         table.intern("str", Str);
1491         table.intern("usize", Uint(UintTy::Usize));
1492         table.intern("u8", Uint(UintTy::U8));
1493         table.intern("u16", Uint(UintTy::U16));
1494         table.intern("u32", Uint(UintTy::U32));
1495         table.intern("u64", Uint(UintTy::U64));
1496         table.intern("u128", Uint(UintTy::U128));
1497         table
1498     }
1499
1500     fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1501         self.primitive_types.insert(Symbol::intern(string), primitive_type);
1502     }
1503 }
1504
1505 #[derive(Debug, Default, Clone)]
1506 pub struct ExternPreludeEntry<'a> {
1507     extern_crate_item: Option<&'a NameBinding<'a>>,
1508     pub introduced_by_item: bool,
1509 }
1510
1511 /// The main resolver class.
1512 ///
1513 /// This is the visitor that walks the whole crate.
1514 pub struct Resolver<'a> {
1515     session: &'a Session,
1516     cstore: &'a CStore,
1517
1518     pub definitions: Definitions,
1519
1520     graph_root: Module<'a>,
1521
1522     prelude: Option<Module<'a>>,
1523     pub extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'a>>,
1524
1525     /// N.B., this is used only for better diagnostics, not name resolution itself.
1526     has_self: FxHashSet<DefId>,
1527
1528     /// Names of fields of an item `DefId` accessible with dot syntax.
1529     /// Used for hints during error reporting.
1530     field_names: FxHashMap<DefId, Vec<Name>>,
1531
1532     /// All imports known to succeed or fail.
1533     determined_imports: Vec<&'a ImportDirective<'a>>,
1534
1535     /// All non-determined imports.
1536     indeterminate_imports: Vec<&'a ImportDirective<'a>>,
1537
1538     /// The module that represents the current item scope.
1539     current_module: Module<'a>,
1540
1541     /// The current set of local scopes for types and values.
1542     /// FIXME #4948: Reuse ribs to avoid allocation.
1543     ribs: PerNS<Vec<Rib<'a>>>,
1544
1545     /// The current set of local scopes, for labels.
1546     label_ribs: Vec<Rib<'a>>,
1547
1548     /// The trait that the current context can refer to.
1549     current_trait_ref: Option<(Module<'a>, TraitRef)>,
1550
1551     /// The current self type if inside an impl (used for better errors).
1552     current_self_type: Option<Ty>,
1553
1554     /// The current self item if inside an ADT (used for better errors).
1555     current_self_item: Option<NodeId>,
1556
1557     /// FIXME: Refactor things so that these fields are passed through arguments and not resolver.
1558     /// We are resolving a last import segment during import validation.
1559     last_import_segment: bool,
1560     /// This binding should be ignored during in-module resolution, so that we don't get
1561     /// "self-confirming" import resolutions during import validation.
1562     blacklisted_binding: Option<&'a NameBinding<'a>>,
1563
1564     /// The idents for the primitive types.
1565     primitive_type_table: PrimitiveTypeTable,
1566
1567     def_map: DefMap,
1568     import_map: ImportMap,
1569     pub freevars: FreevarMap,
1570     freevars_seen: NodeMap<NodeMap<usize>>,
1571     pub export_map: ExportMap<NodeId>,
1572     pub trait_map: TraitMap,
1573
1574     /// A map from nodes to anonymous modules.
1575     /// Anonymous modules are pseudo-modules that are implicitly created around items
1576     /// contained within blocks.
1577     ///
1578     /// For example, if we have this:
1579     ///
1580     ///  fn f() {
1581     ///      fn g() {
1582     ///          ...
1583     ///      }
1584     ///  }
1585     ///
1586     /// There will be an anonymous module created around `g` with the ID of the
1587     /// entry block for `f`.
1588     block_map: NodeMap<Module<'a>>,
1589     module_map: FxHashMap<DefId, Module<'a>>,
1590     extern_module_map: FxHashMap<(DefId, bool /* MacrosOnly? */), Module<'a>>,
1591     binding_parent_modules: FxHashMap<PtrKey<'a, NameBinding<'a>>, Module<'a>>,
1592
1593     /// Maps glob imports to the names of items actually imported.
1594     pub glob_map: GlobMap,
1595
1596     used_imports: FxHashSet<(NodeId, Namespace)>,
1597     pub maybe_unused_trait_imports: NodeSet,
1598     pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
1599
1600     /// A list of labels as of yet unused. Labels will be removed from this map when
1601     /// they are used (in a `break` or `continue` statement)
1602     pub unused_labels: FxHashMap<NodeId, Span>,
1603
1604     /// Privacy errors are delayed until the end in order to deduplicate them.
1605     privacy_errors: Vec<PrivacyError<'a>>,
1606     /// Ambiguity errors are delayed for deduplication.
1607     ambiguity_errors: Vec<AmbiguityError<'a>>,
1608     /// `use` injections are delayed for better placement and deduplication.
1609     use_injections: Vec<UseError<'a>>,
1610     /// Crate-local macro expanded `macro_export` referred to by a module-relative path.
1611     macro_expanded_macro_export_errors: BTreeSet<(Span, Span)>,
1612
1613     arenas: &'a ResolverArenas<'a>,
1614     dummy_binding: &'a NameBinding<'a>,
1615
1616     crate_loader: &'a mut CrateLoader<'a>,
1617     macro_names: FxHashSet<Ident>,
1618     builtin_macros: FxHashMap<Name, &'a NameBinding<'a>>,
1619     macro_use_prelude: FxHashMap<Name, &'a NameBinding<'a>>,
1620     pub all_macros: FxHashMap<Name, Def>,
1621     macro_map: FxHashMap<DefId, Lrc<SyntaxExtension>>,
1622     macro_defs: FxHashMap<Mark, DefId>,
1623     local_macro_def_scopes: FxHashMap<NodeId, Module<'a>>,
1624
1625     /// List of crate local macros that we need to warn about as being unused.
1626     /// Right now this only includes macro_rules! macros, and macros 2.0.
1627     unused_macros: FxHashSet<DefId>,
1628
1629     /// Maps the `Mark` of an expansion to its containing module or block.
1630     invocations: FxHashMap<Mark, &'a InvocationData<'a>>,
1631
1632     /// Avoid duplicated errors for "name already defined".
1633     name_already_seen: FxHashMap<Name, Span>,
1634
1635     potentially_unused_imports: Vec<&'a ImportDirective<'a>>,
1636
1637     /// Table for mapping struct IDs into struct constructor IDs,
1638     /// it's not used during normal resolution, only for better error reporting.
1639     struct_constructors: DefIdMap<(Def, ty::Visibility)>,
1640
1641     /// Only used for better errors on `fn(): fn()`.
1642     current_type_ascription: Vec<Span>,
1643
1644     injected_crate: Option<Module<'a>>,
1645 }
1646
1647 /// Nothing really interesting here; it just provides memory for the rest of the crate.
1648 #[derive(Default)]
1649 pub struct ResolverArenas<'a> {
1650     modules: arena::TypedArena<ModuleData<'a>>,
1651     local_modules: RefCell<Vec<Module<'a>>>,
1652     name_bindings: arena::TypedArena<NameBinding<'a>>,
1653     import_directives: arena::TypedArena<ImportDirective<'a>>,
1654     name_resolutions: arena::TypedArena<RefCell<NameResolution<'a>>>,
1655     invocation_data: arena::TypedArena<InvocationData<'a>>,
1656     legacy_bindings: arena::TypedArena<LegacyBinding<'a>>,
1657 }
1658
1659 impl<'a> ResolverArenas<'a> {
1660     fn alloc_module(&'a self, module: ModuleData<'a>) -> Module<'a> {
1661         let module = self.modules.alloc(module);
1662         if module.def_id().map(|def_id| def_id.is_local()).unwrap_or(true) {
1663             self.local_modules.borrow_mut().push(module);
1664         }
1665         module
1666     }
1667     fn local_modules(&'a self) -> std::cell::Ref<'a, Vec<Module<'a>>> {
1668         self.local_modules.borrow()
1669     }
1670     fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
1671         self.name_bindings.alloc(name_binding)
1672     }
1673     fn alloc_import_directive(&'a self, import_directive: ImportDirective<'a>)
1674                               -> &'a ImportDirective<'_> {
1675         self.import_directives.alloc(import_directive)
1676     }
1677     fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
1678         self.name_resolutions.alloc(Default::default())
1679     }
1680     fn alloc_invocation_data(&'a self, expansion_data: InvocationData<'a>)
1681                              -> &'a InvocationData<'a> {
1682         self.invocation_data.alloc(expansion_data)
1683     }
1684     fn alloc_legacy_binding(&'a self, binding: LegacyBinding<'a>) -> &'a LegacyBinding<'a> {
1685         self.legacy_bindings.alloc(binding)
1686     }
1687 }
1688
1689 impl<'a, 'b: 'a> ty::DefIdTree for &'a Resolver<'b> {
1690     fn parent(self, id: DefId) -> Option<DefId> {
1691         match id.krate {
1692             LOCAL_CRATE => self.definitions.def_key(id.index).parent,
1693             _ => self.cstore.def_key(id).parent,
1694         }.map(|index| DefId { index, ..id })
1695     }
1696 }
1697
1698 /// This interface is used through the AST→HIR step, to embed full paths into the HIR. After that
1699 /// the resolver is no longer needed as all the relevant information is inline.
1700 impl<'a> hir::lowering::Resolver for Resolver<'a> {
1701     fn resolve_hir_path(
1702         &mut self,
1703         path: &ast::Path,
1704         is_value: bool,
1705     ) -> hir::Path {
1706         self.resolve_hir_path_cb(path, is_value,
1707                                  |resolver, span, error| resolve_error(resolver, span, error))
1708     }
1709
1710     fn resolve_str_path(
1711         &mut self,
1712         span: Span,
1713         crate_root: Option<&str>,
1714         components: &[&str],
1715         is_value: bool
1716     ) -> hir::Path {
1717         let root = if crate_root.is_some() {
1718             keywords::PathRoot
1719         } else {
1720             keywords::Crate
1721         };
1722         let segments = iter::once(root.ident())
1723             .chain(
1724                 crate_root.into_iter()
1725                     .chain(components.iter().cloned())
1726                     .map(Ident::from_str)
1727             ).map(|i| self.new_ast_path_segment(i)).collect::<Vec<_>>();
1728
1729
1730         let path = ast::Path {
1731             span,
1732             segments,
1733         };
1734
1735         self.resolve_hir_path(&path, is_value)
1736     }
1737
1738     fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution> {
1739         self.def_map.get(&id).cloned()
1740     }
1741
1742     fn get_import(&mut self, id: NodeId) -> PerNS<Option<PathResolution>> {
1743         self.import_map.get(&id).cloned().unwrap_or_default()
1744     }
1745
1746     fn definitions(&mut self) -> &mut Definitions {
1747         &mut self.definitions
1748     }
1749 }
1750
1751 impl<'a> Resolver<'a> {
1752     /// Rustdoc uses this to resolve things in a recoverable way. `ResolutionError<'a>`
1753     /// isn't something that can be returned because it can't be made to live that long,
1754     /// and also it's a private type. Fortunately rustdoc doesn't need to know the error,
1755     /// just that an error occurred.
1756     pub fn resolve_str_path_error(&mut self, span: Span, path_str: &str, is_value: bool)
1757         -> Result<hir::Path, ()> {
1758         let mut errored = false;
1759
1760         let path = if path_str.starts_with("::") {
1761             ast::Path {
1762                 span,
1763                 segments: iter::once(keywords::PathRoot.ident())
1764                     .chain({
1765                         path_str.split("::").skip(1).map(Ident::from_str)
1766                     })
1767                     .map(|i| self.new_ast_path_segment(i))
1768                     .collect(),
1769             }
1770         } else {
1771             ast::Path {
1772                 span,
1773                 segments: path_str
1774                     .split("::")
1775                     .map(Ident::from_str)
1776                     .map(|i| self.new_ast_path_segment(i))
1777                     .collect(),
1778             }
1779         };
1780         let path = self.resolve_hir_path_cb(&path, is_value, |_, _, _| errored = true);
1781         if errored || path.def == def::Def::Err {
1782             Err(())
1783         } else {
1784             Ok(path)
1785         }
1786     }
1787
1788     /// Like `resolve_hir_path`, but takes a callback in case there was an error.
1789     fn resolve_hir_path_cb<F>(
1790         &mut self,
1791         path: &ast::Path,
1792         is_value: bool,
1793         error_callback: F,
1794     ) -> hir::Path
1795         where F: for<'c, 'b> FnOnce(&'c mut Resolver<'_>, Span, ResolutionError<'b>)
1796     {
1797         let namespace = if is_value { ValueNS } else { TypeNS };
1798         let span = path.span;
1799         let segments = &path.segments;
1800         let path = Segment::from_path(&path);
1801         // FIXME(Manishearth): intra-doc links won't get warned of epoch changes.
1802         let def = match self.resolve_path_without_parent_scope(&path, Some(namespace), true,
1803                                                                span, CrateLint::No) {
1804             PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
1805                 module.def().unwrap(),
1806             PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 =>
1807                 path_res.base_def(),
1808             PathResult::NonModule(..) => {
1809                 error_callback(self, span, ResolutionError::FailedToResolve {
1810                     label: String::from("type-relative paths are not supported in this context"),
1811                     suggestion: None,
1812                 });
1813                 Def::Err
1814             }
1815             PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
1816             PathResult::Failed { span, label, suggestion, .. } => {
1817                 error_callback(self, span, ResolutionError::FailedToResolve {
1818                     label,
1819                     suggestion,
1820                 });
1821                 Def::Err
1822             }
1823         };
1824
1825         let segments: Vec<_> = segments.iter().map(|seg| {
1826             let mut hir_seg = hir::PathSegment::from_ident(seg.ident);
1827             hir_seg.def = Some(self.def_map.get(&seg.id).map_or(def::Def::Err, |p| {
1828                 p.base_def().map_id(|_| panic!("unexpected node_id"))
1829             }));
1830             hir_seg
1831         }).collect();
1832         hir::Path {
1833             span,
1834             def: def.map_id(|_| panic!("unexpected node_id")),
1835             segments: segments.into(),
1836         }
1837     }
1838
1839     fn new_ast_path_segment(&self, ident: Ident) -> ast::PathSegment {
1840         let mut seg = ast::PathSegment::from_ident(ident);
1841         seg.id = self.session.next_node_id();
1842         seg
1843     }
1844 }
1845
1846 impl<'a> Resolver<'a> {
1847     pub fn new(session: &'a Session,
1848                cstore: &'a CStore,
1849                krate: &Crate,
1850                crate_name: &str,
1851                crate_loader: &'a mut CrateLoader<'a>,
1852                arenas: &'a ResolverArenas<'a>)
1853                -> Resolver<'a> {
1854         let root_def_id = DefId::local(CRATE_DEF_INDEX);
1855         let root_module_kind = ModuleKind::Def(Def::Mod(root_def_id), keywords::Invalid.name());
1856         let graph_root = arenas.alloc_module(ModuleData {
1857             no_implicit_prelude: attr::contains_name(&krate.attrs, "no_implicit_prelude"),
1858             ..ModuleData::new(None, root_module_kind, root_def_id, Mark::root(), krate.span)
1859         });
1860         let mut module_map = FxHashMap::default();
1861         module_map.insert(DefId::local(CRATE_DEF_INDEX), graph_root);
1862
1863         let mut definitions = Definitions::new();
1864         DefCollector::new(&mut definitions, Mark::root())
1865             .collect_root(crate_name, session.local_crate_disambiguator());
1866
1867         let mut extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'_>> =
1868             session.opts.externs.iter().map(|kv| (Ident::from_str(kv.0), Default::default()))
1869                                        .collect();
1870
1871         if !attr::contains_name(&krate.attrs, "no_core") {
1872             extern_prelude.insert(Ident::from_str("core"), Default::default());
1873             if !attr::contains_name(&krate.attrs, "no_std") {
1874                 extern_prelude.insert(Ident::from_str("std"), Default::default());
1875                 if session.rust_2018() {
1876                     extern_prelude.insert(Ident::from_str("meta"), Default::default());
1877                 }
1878             }
1879         }
1880
1881         let mut invocations = FxHashMap::default();
1882         invocations.insert(Mark::root(),
1883                            arenas.alloc_invocation_data(InvocationData::root(graph_root)));
1884
1885         let mut macro_defs = FxHashMap::default();
1886         macro_defs.insert(Mark::root(), root_def_id);
1887
1888         Resolver {
1889             session,
1890
1891             cstore,
1892
1893             definitions,
1894
1895             // The outermost module has def ID 0; this is not reflected in the
1896             // AST.
1897             graph_root,
1898             prelude: None,
1899             extern_prelude,
1900
1901             has_self: FxHashSet::default(),
1902             field_names: FxHashMap::default(),
1903
1904             determined_imports: Vec::new(),
1905             indeterminate_imports: Vec::new(),
1906
1907             current_module: graph_root,
1908             ribs: PerNS {
1909                 value_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1910                 type_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1911                 macro_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1912             },
1913             label_ribs: Vec::new(),
1914
1915             current_trait_ref: None,
1916             current_self_type: None,
1917             current_self_item: None,
1918             last_import_segment: false,
1919             blacklisted_binding: None,
1920
1921             primitive_type_table: PrimitiveTypeTable::new(),
1922
1923             def_map: Default::default(),
1924             import_map: Default::default(),
1925             freevars: Default::default(),
1926             freevars_seen: Default::default(),
1927             export_map: FxHashMap::default(),
1928             trait_map: Default::default(),
1929             module_map,
1930             block_map: Default::default(),
1931             extern_module_map: FxHashMap::default(),
1932             binding_parent_modules: FxHashMap::default(),
1933
1934             glob_map: Default::default(),
1935
1936             used_imports: FxHashSet::default(),
1937             maybe_unused_trait_imports: Default::default(),
1938             maybe_unused_extern_crates: Vec::new(),
1939
1940             unused_labels: FxHashMap::default(),
1941
1942             privacy_errors: Vec::new(),
1943             ambiguity_errors: Vec::new(),
1944             use_injections: Vec::new(),
1945             macro_expanded_macro_export_errors: BTreeSet::new(),
1946
1947             arenas,
1948             dummy_binding: arenas.alloc_name_binding(NameBinding {
1949                 kind: NameBindingKind::Def(Def::Err, false),
1950                 ambiguity: None,
1951                 expansion: Mark::root(),
1952                 span: DUMMY_SP,
1953                 vis: ty::Visibility::Public,
1954             }),
1955
1956             crate_loader,
1957             macro_names: FxHashSet::default(),
1958             builtin_macros: FxHashMap::default(),
1959             macro_use_prelude: FxHashMap::default(),
1960             all_macros: FxHashMap::default(),
1961             macro_map: FxHashMap::default(),
1962             invocations,
1963             macro_defs,
1964             local_macro_def_scopes: FxHashMap::default(),
1965             name_already_seen: FxHashMap::default(),
1966             potentially_unused_imports: Vec::new(),
1967             struct_constructors: Default::default(),
1968             unused_macros: FxHashSet::default(),
1969             current_type_ascription: Vec::new(),
1970             injected_crate: None,
1971         }
1972     }
1973
1974     pub fn arenas() -> ResolverArenas<'a> {
1975         Default::default()
1976     }
1977
1978     /// Runs the function on each namespace.
1979     fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1980         f(self, TypeNS);
1981         f(self, ValueNS);
1982         f(self, MacroNS);
1983     }
1984
1985     fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1986         loop {
1987             match self.macro_defs.get(&ctxt.outer()) {
1988                 Some(&def_id) => return def_id,
1989                 None => ctxt.remove_mark(),
1990             };
1991         }
1992     }
1993
1994     /// Entry point to crate resolution.
1995     pub fn resolve_crate(&mut self, krate: &Crate) {
1996         ImportResolver { resolver: self }.finalize_imports();
1997         self.current_module = self.graph_root;
1998         self.finalize_current_module_macro_resolutions();
1999
2000         visit::walk_crate(self, krate);
2001
2002         check_unused::check_crate(self, krate);
2003         self.report_errors(krate);
2004         self.crate_loader.postprocess(krate);
2005     }
2006
2007     fn new_module(
2008         &self,
2009         parent: Module<'a>,
2010         kind: ModuleKind,
2011         normal_ancestor_id: DefId,
2012         expansion: Mark,
2013         span: Span,
2014     ) -> Module<'a> {
2015         let module = ModuleData::new(Some(parent), kind, normal_ancestor_id, expansion, span);
2016         self.arenas.alloc_module(module)
2017     }
2018
2019     fn record_use(&mut self, ident: Ident, ns: Namespace,
2020                   used_binding: &'a NameBinding<'a>, is_lexical_scope: bool) {
2021         if let Some((b2, kind)) = used_binding.ambiguity {
2022             self.ambiguity_errors.push(AmbiguityError {
2023                 kind, ident, b1: used_binding, b2,
2024                 misc1: AmbiguityErrorMisc::None,
2025                 misc2: AmbiguityErrorMisc::None,
2026             });
2027         }
2028         if let NameBindingKind::Import { directive, binding, ref used } = used_binding.kind {
2029             // Avoid marking `extern crate` items that refer to a name from extern prelude,
2030             // but not introduce it, as used if they are accessed from lexical scope.
2031             if is_lexical_scope {
2032                 if let Some(entry) = self.extern_prelude.get(&ident.modern()) {
2033                     if let Some(crate_item) = entry.extern_crate_item {
2034                         if ptr::eq(used_binding, crate_item) && !entry.introduced_by_item {
2035                             return;
2036                         }
2037                     }
2038                 }
2039             }
2040             used.set(true);
2041             directive.used.set(true);
2042             self.used_imports.insert((directive.id, ns));
2043             self.add_to_glob_map(&directive, ident);
2044             self.record_use(ident, ns, binding, false);
2045         }
2046     }
2047
2048     #[inline]
2049     fn add_to_glob_map(&mut self, directive: &ImportDirective<'_>, ident: Ident) {
2050         if directive.is_glob() {
2051             self.glob_map.entry(directive.id).or_default().insert(ident.name);
2052         }
2053     }
2054
2055     /// This resolves the identifier `ident` in the namespace `ns` in the current lexical scope.
2056     /// More specifically, we proceed up the hierarchy of scopes and return the binding for
2057     /// `ident` in the first scope that defines it (or None if no scopes define it).
2058     ///
2059     /// A block's items are above its local variables in the scope hierarchy, regardless of where
2060     /// the items are defined in the block. For example,
2061     /// ```rust
2062     /// fn f() {
2063     ///    g(); // Since there are no local variables in scope yet, this resolves to the item.
2064     ///    let g = || {};
2065     ///    fn g() {}
2066     ///    g(); // This resolves to the local variable `g` since it shadows the item.
2067     /// }
2068     /// ```
2069     ///
2070     /// Invariant: This must only be called during main resolution, not during
2071     /// import resolution.
2072     fn resolve_ident_in_lexical_scope(&mut self,
2073                                       mut ident: Ident,
2074                                       ns: Namespace,
2075                                       record_used_id: Option<NodeId>,
2076                                       path_span: Span)
2077                                       -> Option<LexicalScopeBinding<'a>> {
2078         assert!(ns == TypeNS  || ns == ValueNS);
2079         if ident.name == keywords::Invalid.name() {
2080             return Some(LexicalScopeBinding::Def(Def::Err));
2081         }
2082         ident.span = if ident.name == keywords::SelfUpper.name() {
2083             // FIXME(jseyfried) improve `Self` hygiene
2084             ident.span.with_ctxt(SyntaxContext::empty())
2085         } else if ns == TypeNS {
2086             ident.span.modern()
2087         } else {
2088             ident.span.modern_and_legacy()
2089         };
2090
2091         // Walk backwards up the ribs in scope.
2092         let record_used = record_used_id.is_some();
2093         let mut module = self.graph_root;
2094         for i in (0 .. self.ribs[ns].len()).rev() {
2095             debug!("walk rib\n{:?}", self.ribs[ns][i].bindings);
2096             if let Some(def) = self.ribs[ns][i].bindings.get(&ident).cloned() {
2097                 // The ident resolves to a type parameter or local variable.
2098                 return Some(LexicalScopeBinding::Def(
2099                     self.adjust_local_def(ns, i, def, record_used, path_span)
2100                 ));
2101             }
2102
2103             module = match self.ribs[ns][i].kind {
2104                 ModuleRibKind(module) => module,
2105                 MacroDefinition(def) if def == self.macro_def(ident.span.ctxt()) => {
2106                     // If an invocation of this macro created `ident`, give up on `ident`
2107                     // and switch to `ident`'s source from the macro definition.
2108                     ident.span.remove_mark();
2109                     continue
2110                 }
2111                 _ => continue,
2112             };
2113
2114             let item = self.resolve_ident_in_module_unadjusted(
2115                 ModuleOrUniformRoot::Module(module),
2116                 ident,
2117                 ns,
2118                 record_used,
2119                 path_span,
2120             );
2121             if let Ok(binding) = item {
2122                 // The ident resolves to an item.
2123                 return Some(LexicalScopeBinding::Item(binding));
2124             }
2125
2126             match module.kind {
2127                 ModuleKind::Block(..) => {}, // We can see through blocks
2128                 _ => break,
2129             }
2130         }
2131
2132         ident.span = ident.span.modern();
2133         let mut poisoned = None;
2134         loop {
2135             let opt_module = if let Some(node_id) = record_used_id {
2136                 self.hygienic_lexical_parent_with_compatibility_fallback(module, &mut ident.span,
2137                                                                          node_id, &mut poisoned)
2138             } else {
2139                 self.hygienic_lexical_parent(module, &mut ident.span)
2140             };
2141             module = unwrap_or!(opt_module, break);
2142             let orig_current_module = self.current_module;
2143             self.current_module = module; // Lexical resolutions can never be a privacy error.
2144             let result = self.resolve_ident_in_module_unadjusted(
2145                 ModuleOrUniformRoot::Module(module),
2146                 ident,
2147                 ns,
2148                 record_used,
2149                 path_span,
2150             );
2151             self.current_module = orig_current_module;
2152
2153             match result {
2154                 Ok(binding) => {
2155                     if let Some(node_id) = poisoned {
2156                         self.session.buffer_lint_with_diagnostic(
2157                             lint::builtin::PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
2158                             node_id, ident.span,
2159                             &format!("cannot find {} `{}` in this scope", ns.descr(), ident),
2160                             lint::builtin::BuiltinLintDiagnostics::
2161                                 ProcMacroDeriveResolutionFallback(ident.span),
2162                         );
2163                     }
2164                     return Some(LexicalScopeBinding::Item(binding))
2165                 }
2166                 Err(Determined) => continue,
2167                 Err(Undetermined) =>
2168                     span_bug!(ident.span, "undetermined resolution during main resolution pass"),
2169             }
2170         }
2171
2172         if !module.no_implicit_prelude {
2173             if ns == TypeNS {
2174                 if let Some(binding) = self.extern_prelude_get(ident, !record_used) {
2175                     return Some(LexicalScopeBinding::Item(binding));
2176                 }
2177             }
2178             if ns == TypeNS && is_known_tool(ident.name) {
2179                 let binding = (Def::ToolMod, ty::Visibility::Public,
2180                                DUMMY_SP, Mark::root()).to_name_binding(self.arenas);
2181                 return Some(LexicalScopeBinding::Item(binding));
2182             }
2183             if let Some(prelude) = self.prelude {
2184                 if let Ok(binding) = self.resolve_ident_in_module_unadjusted(
2185                     ModuleOrUniformRoot::Module(prelude),
2186                     ident,
2187                     ns,
2188                     false,
2189                     path_span,
2190                 ) {
2191                     return Some(LexicalScopeBinding::Item(binding));
2192                 }
2193             }
2194         }
2195
2196         None
2197     }
2198
2199     fn hygienic_lexical_parent(&mut self, module: Module<'a>, span: &mut Span)
2200                                -> Option<Module<'a>> {
2201         if !module.expansion.is_descendant_of(span.ctxt().outer()) {
2202             return Some(self.macro_def_scope(span.remove_mark()));
2203         }
2204
2205         if let ModuleKind::Block(..) = module.kind {
2206             return Some(module.parent.unwrap());
2207         }
2208
2209         None
2210     }
2211
2212     fn hygienic_lexical_parent_with_compatibility_fallback(&mut self, module: Module<'a>,
2213                                                            span: &mut Span, node_id: NodeId,
2214                                                            poisoned: &mut Option<NodeId>)
2215                                                            -> Option<Module<'a>> {
2216         if let module @ Some(..) = self.hygienic_lexical_parent(module, span) {
2217             return module;
2218         }
2219
2220         // We need to support the next case under a deprecation warning
2221         // ```
2222         // struct MyStruct;
2223         // ---- begin: this comes from a proc macro derive
2224         // mod implementation_details {
2225         //     // Note that `MyStruct` is not in scope here.
2226         //     impl SomeTrait for MyStruct { ... }
2227         // }
2228         // ---- end
2229         // ```
2230         // So we have to fall back to the module's parent during lexical resolution in this case.
2231         if let Some(parent) = module.parent {
2232             // Inner module is inside the macro, parent module is outside of the macro.
2233             if module.expansion != parent.expansion &&
2234             module.expansion.is_descendant_of(parent.expansion) {
2235                 // The macro is a proc macro derive
2236                 if module.expansion.looks_like_proc_macro_derive() {
2237                     if parent.expansion.is_descendant_of(span.ctxt().outer()) {
2238                         *poisoned = Some(node_id);
2239                         return module.parent;
2240                     }
2241                 }
2242             }
2243         }
2244
2245         None
2246     }
2247
2248     fn resolve_ident_in_module(
2249         &mut self,
2250         module: ModuleOrUniformRoot<'a>,
2251         ident: Ident,
2252         ns: Namespace,
2253         parent_scope: Option<&ParentScope<'a>>,
2254         record_used: bool,
2255         path_span: Span
2256     ) -> Result<&'a NameBinding<'a>, Determinacy> {
2257         self.resolve_ident_in_module_ext(
2258             module, ident, ns, parent_scope, record_used, path_span
2259         ).map_err(|(determinacy, _)| determinacy)
2260     }
2261
2262     fn resolve_ident_in_module_ext(
2263         &mut self,
2264         module: ModuleOrUniformRoot<'a>,
2265         mut ident: Ident,
2266         ns: Namespace,
2267         parent_scope: Option<&ParentScope<'a>>,
2268         record_used: bool,
2269         path_span: Span
2270     ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> {
2271         let orig_current_module = self.current_module;
2272         match module {
2273             ModuleOrUniformRoot::Module(module) => {
2274                 ident.span = ident.span.modern();
2275                 if let Some(def) = ident.span.adjust(module.expansion) {
2276                     self.current_module = self.macro_def_scope(def);
2277                 }
2278             }
2279             ModuleOrUniformRoot::ExternPrelude => {
2280                 ident.span = ident.span.modern();
2281                 ident.span.adjust(Mark::root());
2282             }
2283             ModuleOrUniformRoot::CrateRootAndExternPrelude |
2284             ModuleOrUniformRoot::CurrentScope => {
2285                 // No adjustments
2286             }
2287         }
2288         let result = self.resolve_ident_in_module_unadjusted_ext(
2289             module, ident, ns, parent_scope, false, record_used, path_span,
2290         );
2291         self.current_module = orig_current_module;
2292         result
2293     }
2294
2295     fn resolve_crate_root(&mut self, ident: Ident) -> Module<'a> {
2296         let mut ctxt = ident.span.ctxt();
2297         let mark = if ident.name == keywords::DollarCrate.name() {
2298             // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
2299             // we don't want to pretend that the `macro_rules!` definition is in the `macro`
2300             // as described in `SyntaxContext::apply_mark`, so we ignore prepended modern marks.
2301             // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!`
2302             // definitions actually produced by `macro` and `macro` definitions produced by
2303             // `macro_rules!`, but at least such configurations are not stable yet.
2304             ctxt = ctxt.modern_and_legacy();
2305             let mut iter = ctxt.marks().into_iter().rev().peekable();
2306             let mut result = None;
2307             // Find the last modern mark from the end if it exists.
2308             while let Some(&(mark, transparency)) = iter.peek() {
2309                 if transparency == Transparency::Opaque {
2310                     result = Some(mark);
2311                     iter.next();
2312                 } else {
2313                     break;
2314                 }
2315             }
2316             // Then find the last legacy mark from the end if it exists.
2317             for (mark, transparency) in iter {
2318                 if transparency == Transparency::SemiTransparent {
2319                     result = Some(mark);
2320                 } else {
2321                     break;
2322                 }
2323             }
2324             result
2325         } else {
2326             ctxt = ctxt.modern();
2327             ctxt.adjust(Mark::root())
2328         };
2329         let module = match mark {
2330             Some(def) => self.macro_def_scope(def),
2331             None => return self.graph_root,
2332         };
2333         self.get_module(DefId { index: CRATE_DEF_INDEX, ..module.normal_ancestor_id })
2334     }
2335
2336     fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'a>) -> Module<'a> {
2337         let mut module = self.get_module(module.normal_ancestor_id);
2338         while module.span.ctxt().modern() != *ctxt {
2339             let parent = module.parent.unwrap_or_else(|| self.macro_def_scope(ctxt.remove_mark()));
2340             module = self.get_module(parent.normal_ancestor_id);
2341         }
2342         module
2343     }
2344
2345     // AST resolution
2346     //
2347     // We maintain a list of value ribs and type ribs.
2348     //
2349     // Simultaneously, we keep track of the current position in the module
2350     // graph in the `current_module` pointer. When we go to resolve a name in
2351     // the value or type namespaces, we first look through all the ribs and
2352     // then query the module graph. When we resolve a name in the module
2353     // namespace, we can skip all the ribs (since nested modules are not
2354     // allowed within blocks in Rust) and jump straight to the current module
2355     // graph node.
2356     //
2357     // Named implementations are handled separately. When we find a method
2358     // call, we consult the module node to find all of the implementations in
2359     // scope. This information is lazily cached in the module node. We then
2360     // generate a fake "implementation scope" containing all the
2361     // implementations thus found, for compatibility with old resolve pass.
2362
2363     pub fn with_scope<F, T>(&mut self, id: NodeId, f: F) -> T
2364         where F: FnOnce(&mut Resolver<'_>) -> T
2365     {
2366         let id = self.definitions.local_def_id(id);
2367         let module = self.module_map.get(&id).cloned(); // clones a reference
2368         if let Some(module) = module {
2369             // Move down in the graph.
2370             let orig_module = replace(&mut self.current_module, module);
2371             self.ribs[ValueNS].push(Rib::new(ModuleRibKind(module)));
2372             self.ribs[TypeNS].push(Rib::new(ModuleRibKind(module)));
2373
2374             self.finalize_current_module_macro_resolutions();
2375             let ret = f(self);
2376
2377             self.current_module = orig_module;
2378             self.ribs[ValueNS].pop();
2379             self.ribs[TypeNS].pop();
2380             ret
2381         } else {
2382             f(self)
2383         }
2384     }
2385
2386     /// Searches the current set of local scopes for labels. Returns the first non-`None` label that
2387     /// is returned by the given predicate function
2388     ///
2389     /// Stops after meeting a closure.
2390     fn search_label<P, R>(&self, mut ident: Ident, pred: P) -> Option<R>
2391         where P: Fn(&Rib<'_>, Ident) -> Option<R>
2392     {
2393         for rib in self.label_ribs.iter().rev() {
2394             match rib.kind {
2395                 NormalRibKind => {}
2396                 // If an invocation of this macro created `ident`, give up on `ident`
2397                 // and switch to `ident`'s source from the macro definition.
2398                 MacroDefinition(def) => {
2399                     if def == self.macro_def(ident.span.ctxt()) {
2400                         ident.span.remove_mark();
2401                     }
2402                 }
2403                 _ => {
2404                     // Do not resolve labels across function boundary
2405                     return None;
2406                 }
2407             }
2408             let r = pred(rib, ident);
2409             if r.is_some() {
2410                 return r;
2411             }
2412         }
2413         None
2414     }
2415
2416     fn resolve_adt(&mut self, item: &Item, generics: &Generics) {
2417         debug!("resolve_adt");
2418         self.with_current_self_item(item, |this| {
2419             this.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
2420                 let item_def_id = this.definitions.local_def_id(item.id);
2421                 this.with_self_rib(Def::SelfTy(None, Some(item_def_id)), |this| {
2422                     visit::walk_item(this, item);
2423                 });
2424             });
2425         });
2426     }
2427
2428     fn future_proof_import(&mut self, use_tree: &ast::UseTree) {
2429         let segments = &use_tree.prefix.segments;
2430         if !segments.is_empty() {
2431             let ident = segments[0].ident;
2432             if ident.is_path_segment_keyword() || ident.span.rust_2015() {
2433                 return;
2434             }
2435
2436             let nss = match use_tree.kind {
2437                 ast::UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
2438                 _ => &[TypeNS],
2439             };
2440             let report_error = |this: &Self, ns| {
2441                 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2442                 this.session.span_err(ident.span, &format!("imports cannot refer to {}", what));
2443             };
2444
2445             for &ns in nss {
2446                 match self.resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span) {
2447                     Some(LexicalScopeBinding::Def(..)) => {
2448                         report_error(self, ns);
2449                     }
2450                     Some(LexicalScopeBinding::Item(binding)) => {
2451                         let orig_blacklisted_binding =
2452                             mem::replace(&mut self.blacklisted_binding, Some(binding));
2453                         if let Some(LexicalScopeBinding::Def(..)) =
2454                                 self.resolve_ident_in_lexical_scope(ident, ns, None,
2455                                                                     use_tree.prefix.span) {
2456                             report_error(self, ns);
2457                         }
2458                         self.blacklisted_binding = orig_blacklisted_binding;
2459                     }
2460                     None => {}
2461                 }
2462             }
2463         } else if let ast::UseTreeKind::Nested(use_trees) = &use_tree.kind {
2464             for (use_tree, _) in use_trees {
2465                 self.future_proof_import(use_tree);
2466             }
2467         }
2468     }
2469
2470     fn resolve_item(&mut self, item: &Item) {
2471         let name = item.ident.name;
2472         debug!("(resolving item) resolving {} ({:?})", name, item.node);
2473
2474         match item.node {
2475             ItemKind::Ty(_, ref generics) |
2476             ItemKind::Fn(_, _, ref generics, _) |
2477             ItemKind::Existential(_, ref generics) => {
2478                 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind),
2479                                              |this| visit::walk_item(this, item));
2480             }
2481
2482             ItemKind::Enum(_, ref generics) |
2483             ItemKind::Struct(_, ref generics) |
2484             ItemKind::Union(_, ref generics) => {
2485                 self.resolve_adt(item, generics);
2486             }
2487
2488             ItemKind::Impl(.., ref generics, ref opt_trait_ref, ref self_type, ref impl_items) =>
2489                 self.resolve_implementation(generics,
2490                                             opt_trait_ref,
2491                                             &self_type,
2492                                             item.id,
2493                                             impl_items),
2494
2495             ItemKind::Trait(.., ref generics, ref bounds, ref trait_items) => {
2496                 // Create a new rib for the trait-wide type parameters.
2497                 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
2498                     let local_def_id = this.definitions.local_def_id(item.id);
2499                     this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
2500                         this.visit_generics(generics);
2501                         walk_list!(this, visit_param_bound, bounds);
2502
2503                         for trait_item in trait_items {
2504                             let generic_params = HasGenericParams(&trait_item.generics,
2505                                                                     TraitOrImplItemRibKind);
2506                             this.with_generic_param_rib(generic_params, |this| {
2507                                 match trait_item.node {
2508                                     TraitItemKind::Const(ref ty, ref default) => {
2509                                         this.visit_ty(ty);
2510
2511                                         // Only impose the restrictions of
2512                                         // ConstRibKind for an actual constant
2513                                         // expression in a provided default.
2514                                         if let Some(ref expr) = *default{
2515                                             this.with_constant_rib(|this| {
2516                                                 this.visit_expr(expr);
2517                                             });
2518                                         }
2519                                     }
2520                                     TraitItemKind::Method(_, _) => {
2521                                         visit::walk_trait_item(this, trait_item)
2522                                     }
2523                                     TraitItemKind::Type(..) => {
2524                                         visit::walk_trait_item(this, trait_item)
2525                                     }
2526                                     TraitItemKind::Macro(_) => {
2527                                         panic!("unexpanded macro in resolve!")
2528                                     }
2529                                 };
2530                             });
2531                         }
2532                     });
2533                 });
2534             }
2535
2536             ItemKind::TraitAlias(ref generics, ref bounds) => {
2537                 // Create a new rib for the trait-wide type parameters.
2538                 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
2539                     let local_def_id = this.definitions.local_def_id(item.id);
2540                     this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
2541                         this.visit_generics(generics);
2542                         walk_list!(this, visit_param_bound, bounds);
2543                     });
2544                 });
2545             }
2546
2547             ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
2548                 self.with_scope(item.id, |this| {
2549                     visit::walk_item(this, item);
2550                 });
2551             }
2552
2553             ItemKind::Static(ref ty, _, ref expr) |
2554             ItemKind::Const(ref ty, ref expr) => {
2555                 debug!("resolve_item ItemKind::Const");
2556                 self.with_item_rib(|this| {
2557                     this.visit_ty(ty);
2558                     this.with_constant_rib(|this| {
2559                         this.visit_expr(expr);
2560                     });
2561                 });
2562             }
2563
2564             ItemKind::Use(ref use_tree) => {
2565                 self.future_proof_import(use_tree);
2566             }
2567
2568             ItemKind::ExternCrate(..) |
2569             ItemKind::MacroDef(..) | ItemKind::GlobalAsm(..) => {
2570                 // do nothing, these are just around to be encoded
2571             }
2572
2573             ItemKind::Mac(_) => panic!("unexpanded macro in resolve!"),
2574         }
2575     }
2576
2577     fn with_generic_param_rib<'b, F>(&'b mut self, generic_params: GenericParameters<'a, 'b>, f: F)
2578         where F: FnOnce(&mut Resolver<'_>)
2579     {
2580         debug!("with_generic_param_rib");
2581         match generic_params {
2582             HasGenericParams(generics, rib_kind) => {
2583                 let mut function_type_rib = Rib::new(rib_kind);
2584                 let mut function_value_rib = Rib::new(rib_kind);
2585                 let mut seen_bindings = FxHashMap::default();
2586                 for param in &generics.params {
2587                     match param.kind {
2588                         GenericParamKind::Lifetime { .. } => {}
2589                         GenericParamKind::Type { .. } => {
2590                             let ident = param.ident.modern();
2591                             debug!("with_generic_param_rib: {}", param.id);
2592
2593                             if seen_bindings.contains_key(&ident) {
2594                                 let span = seen_bindings.get(&ident).unwrap();
2595                                 let err = ResolutionError::NameAlreadyUsedInParameterList(
2596                                     ident.name,
2597                                     span,
2598                                 );
2599                                 resolve_error(self, param.ident.span, err);
2600                             }
2601                             seen_bindings.entry(ident).or_insert(param.ident.span);
2602
2603                         // Plain insert (no renaming).
2604                         let def = Def::TyParam(self.definitions.local_def_id(param.id));
2605                             function_type_rib.bindings.insert(ident, def);
2606                             self.record_def(param.id, PathResolution::new(def));
2607                         }
2608                         GenericParamKind::Const { .. } => {
2609                             let ident = param.ident.modern();
2610                             debug!("with_generic_param_rib: {}", param.id);
2611
2612                             if seen_bindings.contains_key(&ident) {
2613                                 let span = seen_bindings.get(&ident).unwrap();
2614                                 let err = ResolutionError::NameAlreadyUsedInParameterList(
2615                                     ident.name,
2616                                     span,
2617                                 );
2618                                 resolve_error(self, param.ident.span, err);
2619                             }
2620                             seen_bindings.entry(ident).or_insert(param.ident.span);
2621
2622                             let def = Def::ConstParam(self.definitions.local_def_id(param.id));
2623                             function_value_rib.bindings.insert(ident, def);
2624                             self.record_def(param.id, PathResolution::new(def));
2625                         }
2626                     }
2627                 }
2628                 self.ribs[ValueNS].push(function_value_rib);
2629                 self.ribs[TypeNS].push(function_type_rib);
2630             }
2631
2632             NoGenericParams => {
2633                 // Nothing to do.
2634             }
2635         }
2636
2637         f(self);
2638
2639         if let HasGenericParams(..) = generic_params {
2640             self.ribs[TypeNS].pop();
2641             self.ribs[ValueNS].pop();
2642         }
2643     }
2644
2645     fn with_label_rib<F>(&mut self, f: F)
2646         where F: FnOnce(&mut Resolver<'_>)
2647     {
2648         self.label_ribs.push(Rib::new(NormalRibKind));
2649         f(self);
2650         self.label_ribs.pop();
2651     }
2652
2653     fn with_item_rib<F>(&mut self, f: F)
2654         where F: FnOnce(&mut Resolver<'_>)
2655     {
2656         self.ribs[ValueNS].push(Rib::new(ItemRibKind));
2657         self.ribs[TypeNS].push(Rib::new(ItemRibKind));
2658         f(self);
2659         self.ribs[TypeNS].pop();
2660         self.ribs[ValueNS].pop();
2661     }
2662
2663     fn with_constant_rib<F>(&mut self, f: F)
2664         where F: FnOnce(&mut Resolver<'_>)
2665     {
2666         debug!("with_constant_rib");
2667         self.ribs[ValueNS].push(Rib::new(ConstantItemRibKind));
2668         self.label_ribs.push(Rib::new(ConstantItemRibKind));
2669         f(self);
2670         self.label_ribs.pop();
2671         self.ribs[ValueNS].pop();
2672     }
2673
2674     fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2675         where F: FnOnce(&mut Resolver<'_>) -> T
2676     {
2677         // Handle nested impls (inside fn bodies)
2678         let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2679         let result = f(self);
2680         self.current_self_type = previous_value;
2681         result
2682     }
2683
2684     fn with_current_self_item<T, F>(&mut self, self_item: &Item, f: F) -> T
2685         where F: FnOnce(&mut Resolver<'_>) -> T
2686     {
2687         let previous_value = replace(&mut self.current_self_item, Some(self_item.id));
2688         let result = f(self);
2689         self.current_self_item = previous_value;
2690         result
2691     }
2692
2693     /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
2694     fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
2695         where F: FnOnce(&mut Resolver<'_>, Option<DefId>) -> T
2696     {
2697         let mut new_val = None;
2698         let mut new_id = None;
2699         if let Some(trait_ref) = opt_trait_ref {
2700             let path: Vec<_> = Segment::from_path(&trait_ref.path);
2701             let def = self.smart_resolve_path_fragment(
2702                 trait_ref.ref_id,
2703                 None,
2704                 &path,
2705                 trait_ref.path.span,
2706                 PathSource::Trait(AliasPossibility::No),
2707                 CrateLint::SimplePath(trait_ref.ref_id),
2708             ).base_def();
2709             if def != Def::Err {
2710                 new_id = Some(def.def_id());
2711                 let span = trait_ref.path.span;
2712                 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
2713                     self.resolve_path_without_parent_scope(
2714                         &path,
2715                         Some(TypeNS),
2716                         false,
2717                         span,
2718                         CrateLint::SimplePath(trait_ref.ref_id),
2719                     )
2720                 {
2721                     new_val = Some((module, trait_ref.clone()));
2722                 }
2723             }
2724         }
2725         let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2726         let result = f(self, new_id);
2727         self.current_trait_ref = original_trait_ref;
2728         result
2729     }
2730
2731     fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2732         where F: FnOnce(&mut Resolver<'_>)
2733     {
2734         let mut self_type_rib = Rib::new(NormalRibKind);
2735
2736         // Plain insert (no renaming, since types are not currently hygienic)
2737         self_type_rib.bindings.insert(keywords::SelfUpper.ident(), self_def);
2738         self.ribs[TypeNS].push(self_type_rib);
2739         f(self);
2740         self.ribs[TypeNS].pop();
2741     }
2742
2743     fn with_self_struct_ctor_rib<F>(&mut self, impl_id: DefId, f: F)
2744         where F: FnOnce(&mut Resolver<'_>)
2745     {
2746         let self_def = Def::SelfCtor(impl_id);
2747         let mut self_type_rib = Rib::new(NormalRibKind);
2748         self_type_rib.bindings.insert(keywords::SelfUpper.ident(), self_def);
2749         self.ribs[ValueNS].push(self_type_rib);
2750         f(self);
2751         self.ribs[ValueNS].pop();
2752     }
2753
2754     fn resolve_implementation(&mut self,
2755                               generics: &Generics,
2756                               opt_trait_reference: &Option<TraitRef>,
2757                               self_type: &Ty,
2758                               item_id: NodeId,
2759                               impl_items: &[ImplItem]) {
2760         debug!("resolve_implementation");
2761         // If applicable, create a rib for the type parameters.
2762         self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
2763             // Dummy self type for better errors if `Self` is used in the trait path.
2764             this.with_self_rib(Def::SelfTy(None, None), |this| {
2765                 // Resolve the trait reference, if necessary.
2766                 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2767                     let item_def_id = this.definitions.local_def_id(item_id);
2768                     this.with_self_rib(Def::SelfTy(trait_id, Some(item_def_id)), |this| {
2769                         if let Some(trait_ref) = opt_trait_reference.as_ref() {
2770                             // Resolve type arguments in the trait path.
2771                             visit::walk_trait_ref(this, trait_ref);
2772                         }
2773                         // Resolve the self type.
2774                         this.visit_ty(self_type);
2775                         // Resolve the generic parameters.
2776                         this.visit_generics(generics);
2777                         // Resolve the items within the impl.
2778                         this.with_current_self_type(self_type, |this| {
2779                             this.with_self_struct_ctor_rib(item_def_id, |this| {
2780                                 debug!("resolve_implementation with_self_struct_ctor_rib");
2781                                 for impl_item in impl_items {
2782                                     this.resolve_visibility(&impl_item.vis);
2783
2784                                     // We also need a new scope for the impl item type parameters.
2785                                     let generic_params = HasGenericParams(&impl_item.generics,
2786                                                                           TraitOrImplItemRibKind);
2787                                     this.with_generic_param_rib(generic_params, |this| {
2788                                         use self::ResolutionError::*;
2789                                         match impl_item.node {
2790                                             ImplItemKind::Const(..) => {
2791                                                 debug!(
2792                                                     "resolve_implementation ImplItemKind::Const",
2793                                                 );
2794                                                 // If this is a trait impl, ensure the const
2795                                                 // exists in trait
2796                                                 this.check_trait_item(
2797                                                     impl_item.ident,
2798                                                     ValueNS,
2799                                                     impl_item.span,
2800                                                     |n, s| ConstNotMemberOfTrait(n, s),
2801                                                 );
2802
2803                                                 this.with_constant_rib(|this| {
2804                                                     visit::walk_impl_item(this, impl_item)
2805                                                 });
2806                                             }
2807                                             ImplItemKind::Method(..) => {
2808                                                 // If this is a trait impl, ensure the method
2809                                                 // exists in trait
2810                                                 this.check_trait_item(impl_item.ident,
2811                                                                       ValueNS,
2812                                                                       impl_item.span,
2813                                                     |n, s| MethodNotMemberOfTrait(n, s));
2814
2815                                                 visit::walk_impl_item(this, impl_item);
2816                                             }
2817                                             ImplItemKind::Type(ref ty) => {
2818                                                 // If this is a trait impl, ensure the type
2819                                                 // exists in trait
2820                                                 this.check_trait_item(impl_item.ident,
2821                                                                       TypeNS,
2822                                                                       impl_item.span,
2823                                                     |n, s| TypeNotMemberOfTrait(n, s));
2824
2825                                                 this.visit_ty(ty);
2826                                             }
2827                                             ImplItemKind::Existential(ref bounds) => {
2828                                                 // If this is a trait impl, ensure the type
2829                                                 // exists in trait
2830                                                 this.check_trait_item(impl_item.ident,
2831                                                                       TypeNS,
2832                                                                       impl_item.span,
2833                                                     |n, s| TypeNotMemberOfTrait(n, s));
2834
2835                                                 for bound in bounds {
2836                                                     this.visit_param_bound(bound);
2837                                                 }
2838                                             }
2839                                             ImplItemKind::Macro(_) =>
2840                                                 panic!("unexpanded macro in resolve!"),
2841                                         }
2842                                     });
2843                                 }
2844                             });
2845                         });
2846                     });
2847                 });
2848             });
2849         });
2850     }
2851
2852     fn check_trait_item<F>(&mut self, ident: Ident, ns: Namespace, span: Span, err: F)
2853         where F: FnOnce(Name, &str) -> ResolutionError<'_>
2854     {
2855         // If there is a TraitRef in scope for an impl, then the method must be in the
2856         // trait.
2857         if let Some((module, _)) = self.current_trait_ref {
2858             if self.resolve_ident_in_module(
2859                 ModuleOrUniformRoot::Module(module),
2860                 ident,
2861                 ns,
2862                 None,
2863                 false,
2864                 span,
2865             ).is_err() {
2866                 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
2867                 resolve_error(self, span, err(ident.name, &path_names_to_string(path)));
2868             }
2869         }
2870     }
2871
2872     fn resolve_local(&mut self, local: &Local) {
2873         // Resolve the type.
2874         walk_list!(self, visit_ty, &local.ty);
2875
2876         // Resolve the initializer.
2877         walk_list!(self, visit_expr, &local.init);
2878
2879         // Resolve the pattern.
2880         self.resolve_pattern(&local.pat, PatternSource::Let, &mut FxHashMap::default());
2881     }
2882
2883     // build a map from pattern identifiers to binding-info's.
2884     // this is done hygienically. This could arise for a macro
2885     // that expands into an or-pattern where one 'x' was from the
2886     // user and one 'x' came from the macro.
2887     fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2888         let mut binding_map = FxHashMap::default();
2889
2890         pat.walk(&mut |pat| {
2891             if let PatKind::Ident(binding_mode, ident, ref sub_pat) = pat.node {
2892                 if sub_pat.is_some() || match self.def_map.get(&pat.id).map(|res| res.base_def()) {
2893                     Some(Def::Local(..)) => true,
2894                     _ => false,
2895                 } {
2896                     let binding_info = BindingInfo { span: ident.span, binding_mode: binding_mode };
2897                     binding_map.insert(ident, binding_info);
2898                 }
2899             }
2900             true
2901         });
2902
2903         binding_map
2904     }
2905
2906     // check that all of the arms in an or-pattern have exactly the
2907     // same set of bindings, with the same binding modes for each.
2908     fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) {
2909         if pats.is_empty() {
2910             return;
2911         }
2912
2913         let mut missing_vars = FxHashMap::default();
2914         let mut inconsistent_vars = FxHashMap::default();
2915         for (i, p) in pats.iter().enumerate() {
2916             let map_i = self.binding_mode_map(&p);
2917
2918             for (j, q) in pats.iter().enumerate() {
2919                 if i == j {
2920                     continue;
2921                 }
2922
2923                 let map_j = self.binding_mode_map(&q);
2924                 for (&key, &binding_i) in &map_i {
2925                     if map_j.is_empty() {                   // Account for missing bindings when
2926                         let binding_error = missing_vars    // map_j has none.
2927                             .entry(key.name)
2928                             .or_insert(BindingError {
2929                                 name: key.name,
2930                                 origin: BTreeSet::new(),
2931                                 target: BTreeSet::new(),
2932                             });
2933                         binding_error.origin.insert(binding_i.span);
2934                         binding_error.target.insert(q.span);
2935                     }
2936                     for (&key_j, &binding_j) in &map_j {
2937                         match map_i.get(&key_j) {
2938                             None => {  // missing binding
2939                                 let binding_error = missing_vars
2940                                     .entry(key_j.name)
2941                                     .or_insert(BindingError {
2942                                         name: key_j.name,
2943                                         origin: BTreeSet::new(),
2944                                         target: BTreeSet::new(),
2945                                     });
2946                                 binding_error.origin.insert(binding_j.span);
2947                                 binding_error.target.insert(p.span);
2948                             }
2949                             Some(binding_i) => {  // check consistent binding
2950                                 if binding_i.binding_mode != binding_j.binding_mode {
2951                                     inconsistent_vars
2952                                         .entry(key.name)
2953                                         .or_insert((binding_j.span, binding_i.span));
2954                                 }
2955                             }
2956                         }
2957                     }
2958                 }
2959             }
2960         }
2961         let mut missing_vars = missing_vars.iter().collect::<Vec<_>>();
2962         missing_vars.sort();
2963         for (_, v) in missing_vars {
2964             resolve_error(self,
2965                           *v.origin.iter().next().unwrap(),
2966                           ResolutionError::VariableNotBoundInPattern(v));
2967         }
2968         let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
2969         inconsistent_vars.sort();
2970         for (name, v) in inconsistent_vars {
2971             resolve_error(self, v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
2972         }
2973     }
2974
2975     fn resolve_arm(&mut self, arm: &Arm) {
2976         self.ribs[ValueNS].push(Rib::new(NormalRibKind));
2977
2978         let mut bindings_list = FxHashMap::default();
2979         for pattern in &arm.pats {
2980             self.resolve_pattern(&pattern, PatternSource::Match, &mut bindings_list);
2981         }
2982
2983         // This has to happen *after* we determine which pat_idents are variants.
2984         self.check_consistent_bindings(&arm.pats);
2985
2986         if let Some(ast::Guard::If(ref expr)) = arm.guard {
2987             self.visit_expr(expr)
2988         }
2989         self.visit_expr(&arm.body);
2990
2991         self.ribs[ValueNS].pop();
2992     }
2993
2994     fn resolve_block(&mut self, block: &Block) {
2995         debug!("(resolving block) entering block");
2996         // Move down in the graph, if there's an anonymous module rooted here.
2997         let orig_module = self.current_module;
2998         let anonymous_module = self.block_map.get(&block.id).cloned(); // clones a reference
2999
3000         let mut num_macro_definition_ribs = 0;
3001         if let Some(anonymous_module) = anonymous_module {
3002             debug!("(resolving block) found anonymous module, moving down");
3003             self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
3004             self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
3005             self.current_module = anonymous_module;
3006             self.finalize_current_module_macro_resolutions();
3007         } else {
3008             self.ribs[ValueNS].push(Rib::new(NormalRibKind));
3009         }
3010
3011         // Descend into the block.
3012         for stmt in &block.stmts {
3013             if let ast::StmtKind::Item(ref item) = stmt.node {
3014                 if let ast::ItemKind::MacroDef(..) = item.node {
3015                     num_macro_definition_ribs += 1;
3016                     let def = self.definitions.local_def_id(item.id);
3017                     self.ribs[ValueNS].push(Rib::new(MacroDefinition(def)));
3018                     self.label_ribs.push(Rib::new(MacroDefinition(def)));
3019                 }
3020             }
3021
3022             self.visit_stmt(stmt);
3023         }
3024
3025         // Move back up.
3026         self.current_module = orig_module;
3027         for _ in 0 .. num_macro_definition_ribs {
3028             self.ribs[ValueNS].pop();
3029             self.label_ribs.pop();
3030         }
3031         self.ribs[ValueNS].pop();
3032         if anonymous_module.is_some() {
3033             self.ribs[TypeNS].pop();
3034         }
3035         debug!("(resolving block) leaving block");
3036     }
3037
3038     fn fresh_binding(&mut self,
3039                      ident: Ident,
3040                      pat_id: NodeId,
3041                      outer_pat_id: NodeId,
3042                      pat_src: PatternSource,
3043                      bindings: &mut FxHashMap<Ident, NodeId>)
3044                      -> PathResolution {
3045         // Add the binding to the local ribs, if it
3046         // doesn't already exist in the bindings map. (We
3047         // must not add it if it's in the bindings map
3048         // because that breaks the assumptions later
3049         // passes make about or-patterns.)
3050         let ident = ident.modern_and_legacy();
3051         let mut def = Def::Local(pat_id);
3052         match bindings.get(&ident).cloned() {
3053             Some(id) if id == outer_pat_id => {
3054                 // `Variant(a, a)`, error
3055                 resolve_error(
3056                     self,
3057                     ident.span,
3058                     ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
3059                         &ident.as_str())
3060                 );
3061             }
3062             Some(..) if pat_src == PatternSource::FnParam => {
3063                 // `fn f(a: u8, a: u8)`, error
3064                 resolve_error(
3065                     self,
3066                     ident.span,
3067                     ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
3068                         &ident.as_str())
3069                 );
3070             }
3071             Some(..) if pat_src == PatternSource::Match ||
3072                         pat_src == PatternSource::IfLet ||
3073                         pat_src == PatternSource::WhileLet => {
3074                 // `Variant1(a) | Variant2(a)`, ok
3075                 // Reuse definition from the first `a`.
3076                 def = self.ribs[ValueNS].last_mut().unwrap().bindings[&ident];
3077             }
3078             Some(..) => {
3079                 span_bug!(ident.span, "two bindings with the same name from \
3080                                        unexpected pattern source {:?}", pat_src);
3081             }
3082             None => {
3083                 // A completely fresh binding, add to the lists if it's valid.
3084                 if ident.name != keywords::Invalid.name() {
3085                     bindings.insert(ident, outer_pat_id);
3086                     self.ribs[ValueNS].last_mut().unwrap().bindings.insert(ident, def);
3087                 }
3088             }
3089         }
3090
3091         PathResolution::new(def)
3092     }
3093
3094     fn resolve_pattern(&mut self,
3095                        pat: &Pat,
3096                        pat_src: PatternSource,
3097                        // Maps idents to the node ID for the
3098                        // outermost pattern that binds them.
3099                        bindings: &mut FxHashMap<Ident, NodeId>) {
3100         // Visit all direct subpatterns of this pattern.
3101         let outer_pat_id = pat.id;
3102         pat.walk(&mut |pat| {
3103             debug!("resolve_pattern pat={:?} node={:?}", pat, pat.node);
3104             match pat.node {
3105                 PatKind::Ident(bmode, ident, ref opt_pat) => {
3106                     // First try to resolve the identifier as some existing
3107                     // entity, then fall back to a fresh binding.
3108                     let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS,
3109                                                                       None, pat.span)
3110                                       .and_then(LexicalScopeBinding::item);
3111                     let resolution = binding.map(NameBinding::def).and_then(|def| {
3112                         let is_syntactic_ambiguity = opt_pat.is_none() &&
3113                             bmode == BindingMode::ByValue(Mutability::Immutable);
3114                         match def {
3115                             Def::Ctor(_, _, CtorKind::Const) |
3116                             Def::Const(..) if is_syntactic_ambiguity => {
3117                                 // Disambiguate in favor of a unit struct/variant
3118                                 // or constant pattern.
3119                                 self.record_use(ident, ValueNS, binding.unwrap(), false);
3120                                 Some(PathResolution::new(def))
3121                             }
3122                             Def::Ctor(..) | Def::Const(..) | Def::Static(..) => {
3123                                 // This is unambiguously a fresh binding, either syntactically
3124                                 // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
3125                                 // to something unusable as a pattern (e.g., constructor function),
3126                                 // but we still conservatively report an error, see
3127                                 // issues/33118#issuecomment-233962221 for one reason why.
3128                                 resolve_error(
3129                                     self,
3130                                     ident.span,
3131                                     ResolutionError::BindingShadowsSomethingUnacceptable(
3132                                         pat_src.descr(), ident.name, binding.unwrap())
3133                                 );
3134                                 None
3135                             }
3136                             Def::Fn(..) | Def::Err => {
3137                                 // These entities are explicitly allowed
3138                                 // to be shadowed by fresh bindings.
3139                                 None
3140                             }
3141                             def => {
3142                                 span_bug!(ident.span, "unexpected definition for an \
3143                                                        identifier in pattern: {:?}", def);
3144                             }
3145                         }
3146                     }).unwrap_or_else(|| {
3147                         self.fresh_binding(ident, pat.id, outer_pat_id, pat_src, bindings)
3148                     });
3149
3150                     self.record_def(pat.id, resolution);
3151                 }
3152
3153                 PatKind::TupleStruct(ref path, ..) => {
3154                     self.smart_resolve_path(pat.id, None, path, PathSource::TupleStruct);
3155                 }
3156
3157                 PatKind::Path(ref qself, ref path) => {
3158                     self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
3159                 }
3160
3161                 PatKind::Struct(ref path, ..) => {
3162                     self.smart_resolve_path(pat.id, None, path, PathSource::Struct);
3163                 }
3164
3165                 _ => {}
3166             }
3167             true
3168         });
3169
3170         visit::walk_pat(self, pat);
3171     }
3172
3173     // High-level and context dependent path resolution routine.
3174     // Resolves the path and records the resolution into definition map.
3175     // If resolution fails tries several techniques to find likely
3176     // resolution candidates, suggest imports or other help, and report
3177     // errors in user friendly way.
3178     fn smart_resolve_path(&mut self,
3179                           id: NodeId,
3180                           qself: Option<&QSelf>,
3181                           path: &Path,
3182                           source: PathSource<'_>)
3183                           -> PathResolution {
3184         self.smart_resolve_path_with_crate_lint(id, qself, path, source, CrateLint::SimplePath(id))
3185     }
3186
3187     /// A variant of `smart_resolve_path` where you also specify extra
3188     /// information about where the path came from; this extra info is
3189     /// sometimes needed for the lint that recommends rewriting
3190     /// absolute paths to `crate`, so that it knows how to frame the
3191     /// suggestion. If you are just resolving a path like `foo::bar`
3192     /// that appears in an arbitrary location, then you just want
3193     /// `CrateLint::SimplePath`, which is what `smart_resolve_path`
3194     /// already provides.
3195     fn smart_resolve_path_with_crate_lint(
3196         &mut self,
3197         id: NodeId,
3198         qself: Option<&QSelf>,
3199         path: &Path,
3200         source: PathSource<'_>,
3201         crate_lint: CrateLint
3202     ) -> PathResolution {
3203         self.smart_resolve_path_fragment(
3204             id,
3205             qself,
3206             &Segment::from_path(path),
3207             path.span,
3208             source,
3209             crate_lint,
3210         )
3211     }
3212
3213     fn smart_resolve_path_fragment(&mut self,
3214                                    id: NodeId,
3215                                    qself: Option<&QSelf>,
3216                                    path: &[Segment],
3217                                    span: Span,
3218                                    source: PathSource<'_>,
3219                                    crate_lint: CrateLint)
3220                                    -> PathResolution {
3221         let ns = source.namespace();
3222         let is_expected = &|def| source.is_expected(def);
3223
3224         let report_errors = |this: &mut Self, def: Option<Def>| {
3225             let (err, candidates) = this.smart_resolve_report_errors(path, span, source, def);
3226             let def_id = this.current_module.normal_ancestor_id;
3227             let node_id = this.definitions.as_local_node_id(def_id).unwrap();
3228             let better = def.is_some();
3229             this.use_injections.push(UseError { err, candidates, node_id, better });
3230             err_path_resolution()
3231         };
3232
3233         let resolution = match self.resolve_qpath_anywhere(
3234             id,
3235             qself,
3236             path,
3237             ns,
3238             span,
3239             source.defer_to_typeck(),
3240             source.global_by_default(),
3241             crate_lint,
3242         ) {
3243             Some(resolution) if resolution.unresolved_segments() == 0 => {
3244                 if is_expected(resolution.base_def()) || resolution.base_def() == Def::Err {
3245                     resolution
3246                 } else {
3247                     // Add a temporary hack to smooth the transition to new struct ctor
3248                     // visibility rules. See #38932 for more details.
3249                     let mut res = None;
3250                     if let Def::Struct(def_id) = resolution.base_def() {
3251                         if let Some((ctor_def, ctor_vis))
3252                                 = self.struct_constructors.get(&def_id).cloned() {
3253                             if is_expected(ctor_def) && self.is_accessible(ctor_vis) {
3254                                 let lint = lint::builtin::LEGACY_CONSTRUCTOR_VISIBILITY;
3255                                 self.session.buffer_lint(lint, id, span,
3256                                     "private struct constructors are not usable through \
3257                                      re-exports in outer modules",
3258                                 );
3259                                 res = Some(PathResolution::new(ctor_def));
3260                             }
3261                         }
3262                     }
3263
3264                     res.unwrap_or_else(|| report_errors(self, Some(resolution.base_def())))
3265                 }
3266             }
3267             Some(resolution) if source.defer_to_typeck() => {
3268                 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
3269                 // or `<T>::A::B`. If `B` should be resolved in value namespace then
3270                 // it needs to be added to the trait map.
3271                 if ns == ValueNS {
3272                     let item_name = path.last().unwrap().ident;
3273                     let traits = self.get_traits_containing_item(item_name, ns);
3274                     self.trait_map.insert(id, traits);
3275                 }
3276                 resolution
3277             }
3278             _ => report_errors(self, None)
3279         };
3280
3281         if let PathSource::TraitItem(..) = source {} else {
3282             // Avoid recording definition of `A::B` in `<T as A>::B::C`.
3283             self.record_def(id, resolution);
3284         }
3285         resolution
3286     }
3287
3288     /// Only used in a specific case of type ascription suggestions
3289     #[doc(hidden)]
3290     fn get_colon_suggestion_span(&self, start: Span) -> Span {
3291         let cm = self.session.source_map();
3292         start.to(cm.next_point(start))
3293     }
3294
3295     fn type_ascription_suggestion(
3296         &self,
3297         err: &mut DiagnosticBuilder<'_>,
3298         base_span: Span,
3299     ) {
3300         debug!("type_ascription_suggetion {:?}", base_span);
3301         let cm = self.session.source_map();
3302         let base_snippet = cm.span_to_snippet(base_span);
3303         debug!("self.current_type_ascription {:?}", self.current_type_ascription);
3304         if let Some(sp) = self.current_type_ascription.last() {
3305             let mut sp = *sp;
3306             loop {
3307                 // Try to find the `:`; bail on first non-':' / non-whitespace.
3308                 sp = cm.next_point(sp);
3309                 if let Ok(snippet) = cm.span_to_snippet(sp.to(cm.next_point(sp))) {
3310                     let line_sp = cm.lookup_char_pos(sp.hi()).line;
3311                     let line_base_sp = cm.lookup_char_pos(base_span.lo()).line;
3312                     if snippet == ":" {
3313                         let mut show_label = true;
3314                         if line_sp != line_base_sp {
3315                             err.span_suggestion_short(
3316                                 sp,
3317                                 "did you mean to use `;` here instead?",
3318                                 ";".to_string(),
3319                                 Applicability::MaybeIncorrect,
3320                             );
3321                         } else {
3322                             let colon_sp = self.get_colon_suggestion_span(sp);
3323                             let after_colon_sp = self.get_colon_suggestion_span(
3324                                 colon_sp.shrink_to_hi(),
3325                             );
3326                             if !cm.span_to_snippet(after_colon_sp).map(|s| s == " ")
3327                                 .unwrap_or(false)
3328                             {
3329                                 err.span_suggestion(
3330                                     colon_sp,
3331                                     "maybe you meant to write a path separator here",
3332                                     "::".to_string(),
3333                                     Applicability::MaybeIncorrect,
3334                                 );
3335                                 show_label = false;
3336                             }
3337                             if let Ok(base_snippet) = base_snippet {
3338                                 let mut sp = after_colon_sp;
3339                                 for _ in 0..100 {
3340                                     // Try to find an assignment
3341                                     sp = cm.next_point(sp);
3342                                     let snippet = cm.span_to_snippet(sp.to(cm.next_point(sp)));
3343                                     match snippet {
3344                                         Ok(ref x) if x.as_str() == "=" => {
3345                                             err.span_suggestion(
3346                                                 base_span,
3347                                                 "maybe you meant to write an assignment here",
3348                                                 format!("let {}", base_snippet),
3349                                                 Applicability::MaybeIncorrect,
3350                                             );
3351                                             show_label = false;
3352                                             break;
3353                                         }
3354                                         Ok(ref x) if x.as_str() == "\n" => break,
3355                                         Err(_) => break,
3356                                         Ok(_) => {}
3357                                     }
3358                                 }
3359                             }
3360                         }
3361                         if show_label {
3362                             err.span_label(base_span,
3363                                            "expecting a type here because of type ascription");
3364                         }
3365                         break;
3366                     } else if !snippet.trim().is_empty() {
3367                         debug!("tried to find type ascription `:` token, couldn't find it");
3368                         break;
3369                     }
3370                 } else {
3371                     break;
3372                 }
3373             }
3374         }
3375     }
3376
3377     fn self_type_is_available(&mut self, span: Span) -> bool {
3378         let binding = self.resolve_ident_in_lexical_scope(keywords::SelfUpper.ident(),
3379                                                           TypeNS, None, span);
3380         if let Some(LexicalScopeBinding::Def(def)) = binding { def != Def::Err } else { false }
3381     }
3382
3383     fn self_value_is_available(&mut self, self_span: Span, path_span: Span) -> bool {
3384         let ident = Ident::new(keywords::SelfLower.name(), self_span);
3385         let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, path_span);
3386         if let Some(LexicalScopeBinding::Def(def)) = binding { def != Def::Err } else { false }
3387     }
3388
3389     // Resolve in alternative namespaces if resolution in the primary namespace fails.
3390     fn resolve_qpath_anywhere(&mut self,
3391                               id: NodeId,
3392                               qself: Option<&QSelf>,
3393                               path: &[Segment],
3394                               primary_ns: Namespace,
3395                               span: Span,
3396                               defer_to_typeck: bool,
3397                               global_by_default: bool,
3398                               crate_lint: CrateLint)
3399                               -> Option<PathResolution> {
3400         let mut fin_res = None;
3401         // FIXME: can't resolve paths in macro namespace yet, macros are
3402         // processed by the little special hack below.
3403         for (i, ns) in [primary_ns, TypeNS, ValueNS, /*MacroNS*/].iter().cloned().enumerate() {
3404             if i == 0 || ns != primary_ns {
3405                 match self.resolve_qpath(id, qself, path, ns, span, global_by_default, crate_lint) {
3406                     // If defer_to_typeck, then resolution > no resolution,
3407                     // otherwise full resolution > partial resolution > no resolution.
3408                     Some(res) if res.unresolved_segments() == 0 || defer_to_typeck =>
3409                         return Some(res),
3410                     res => if fin_res.is_none() { fin_res = res },
3411                 };
3412             }
3413         }
3414         if primary_ns != MacroNS &&
3415            (self.macro_names.contains(&path[0].ident.modern()) ||
3416             self.builtin_macros.get(&path[0].ident.name).cloned()
3417                                .and_then(NameBinding::macro_kind) == Some(MacroKind::Bang) ||
3418             self.macro_use_prelude.get(&path[0].ident.name).cloned()
3419                                   .and_then(NameBinding::macro_kind) == Some(MacroKind::Bang)) {
3420             // Return some dummy definition, it's enough for error reporting.
3421             return Some(
3422                 PathResolution::new(Def::Macro(DefId::local(CRATE_DEF_INDEX), MacroKind::Bang))
3423             );
3424         }
3425         fin_res
3426     }
3427
3428     /// Handles paths that may refer to associated items.
3429     fn resolve_qpath(&mut self,
3430                      id: NodeId,
3431                      qself: Option<&QSelf>,
3432                      path: &[Segment],
3433                      ns: Namespace,
3434                      span: Span,
3435                      global_by_default: bool,
3436                      crate_lint: CrateLint)
3437                      -> Option<PathResolution> {
3438         debug!(
3439             "resolve_qpath(id={:?}, qself={:?}, path={:?}, \
3440              ns={:?}, span={:?}, global_by_default={:?})",
3441             id,
3442             qself,
3443             path,
3444             ns,
3445             span,
3446             global_by_default,
3447         );
3448
3449         if let Some(qself) = qself {
3450             if qself.position == 0 {
3451                 // This is a case like `<T>::B`, where there is no
3452                 // trait to resolve.  In that case, we leave the `B`
3453                 // segment to be resolved by type-check.
3454                 return Some(PathResolution::with_unresolved_segments(
3455                     Def::Mod(DefId::local(CRATE_DEF_INDEX)), path.len()
3456                 ));
3457             }
3458
3459             // Make sure `A::B` in `<T as A::B>::C` is a trait item.
3460             //
3461             // Currently, `path` names the full item (`A::B::C`, in
3462             // our example).  so we extract the prefix of that that is
3463             // the trait (the slice upto and including
3464             // `qself.position`). And then we recursively resolve that,
3465             // but with `qself` set to `None`.
3466             //
3467             // However, setting `qself` to none (but not changing the
3468             // span) loses the information about where this path
3469             // *actually* appears, so for the purposes of the crate
3470             // lint we pass along information that this is the trait
3471             // name from a fully qualified path, and this also
3472             // contains the full span (the `CrateLint::QPathTrait`).
3473             let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
3474             let res = self.smart_resolve_path_fragment(
3475                 id,
3476                 None,
3477                 &path[..=qself.position],
3478                 span,
3479                 PathSource::TraitItem(ns),
3480                 CrateLint::QPathTrait {
3481                     qpath_id: id,
3482                     qpath_span: qself.path_span,
3483                 },
3484             );
3485
3486             // The remaining segments (the `C` in our example) will
3487             // have to be resolved by type-check, since that requires doing
3488             // trait resolution.
3489             return Some(PathResolution::with_unresolved_segments(
3490                 res.base_def(), res.unresolved_segments() + path.len() - qself.position - 1
3491             ));
3492         }
3493
3494         let result = match self.resolve_path_without_parent_scope(
3495             &path,
3496             Some(ns),
3497             true,
3498             span,
3499             crate_lint,
3500         ) {
3501             PathResult::NonModule(path_res) => path_res,
3502             PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
3503                 PathResolution::new(module.def().unwrap())
3504             }
3505             // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
3506             // don't report an error right away, but try to fallback to a primitive type.
3507             // So, we are still able to successfully resolve something like
3508             //
3509             // use std::u8; // bring module u8 in scope
3510             // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
3511             //     u8::max_value() // OK, resolves to associated function <u8>::max_value,
3512             //                     // not to non-existent std::u8::max_value
3513             // }
3514             //
3515             // Such behavior is required for backward compatibility.
3516             // The same fallback is used when `a` resolves to nothing.
3517             PathResult::Module(ModuleOrUniformRoot::Module(_)) |
3518             PathResult::Failed { .. }
3519                     if (ns == TypeNS || path.len() > 1) &&
3520                        self.primitive_type_table.primitive_types
3521                            .contains_key(&path[0].ident.name) => {
3522                 let prim = self.primitive_type_table.primitive_types[&path[0].ident.name];
3523                 PathResolution::with_unresolved_segments(Def::PrimTy(prim), path.len() - 1)
3524             }
3525             PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
3526                 PathResolution::new(module.def().unwrap()),
3527             PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
3528                 resolve_error(self, span, ResolutionError::FailedToResolve { label, suggestion });
3529                 err_path_resolution()
3530             }
3531             PathResult::Module(..) | PathResult::Failed { .. } => return None,
3532             PathResult::Indeterminate => bug!("indetermined path result in resolve_qpath"),
3533         };
3534
3535         if path.len() > 1 && !global_by_default && result.base_def() != Def::Err &&
3536            path[0].ident.name != keywords::PathRoot.name() &&
3537            path[0].ident.name != keywords::DollarCrate.name() {
3538             let unqualified_result = {
3539                 match self.resolve_path_without_parent_scope(
3540                     &[*path.last().unwrap()],
3541                     Some(ns),
3542                     false,
3543                     span,
3544                     CrateLint::No,
3545                 ) {
3546                     PathResult::NonModule(path_res) => path_res.base_def(),
3547                     PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
3548                         module.def().unwrap(),
3549                     _ => return Some(result),
3550                 }
3551             };
3552             if result.base_def() == unqualified_result {
3553                 let lint = lint::builtin::UNUSED_QUALIFICATIONS;
3554                 self.session.buffer_lint(lint, id, span, "unnecessary qualification")
3555             }
3556         }
3557
3558         Some(result)
3559     }
3560
3561     fn resolve_path_without_parent_scope(
3562         &mut self,
3563         path: &[Segment],
3564         opt_ns: Option<Namespace>, // `None` indicates a module path in import
3565         record_used: bool,
3566         path_span: Span,
3567         crate_lint: CrateLint,
3568     ) -> PathResult<'a> {
3569         // Macro and import paths must have full parent scope available during resolution,
3570         // other paths will do okay with parent module alone.
3571         assert!(opt_ns != None && opt_ns != Some(MacroNS));
3572         let parent_scope = ParentScope { module: self.current_module, ..self.dummy_parent_scope() };
3573         self.resolve_path(path, opt_ns, &parent_scope, record_used, path_span, crate_lint)
3574     }
3575
3576     fn resolve_path(
3577         &mut self,
3578         path: &[Segment],
3579         opt_ns: Option<Namespace>, // `None` indicates a module path in import
3580         parent_scope: &ParentScope<'a>,
3581         record_used: bool,
3582         path_span: Span,
3583         crate_lint: CrateLint,
3584     ) -> PathResult<'a> {
3585         let mut module = None;
3586         let mut allow_super = true;
3587         let mut second_binding = None;
3588         self.current_module = parent_scope.module;
3589
3590         debug!(
3591             "resolve_path(path={:?}, opt_ns={:?}, record_used={:?}, \
3592              path_span={:?}, crate_lint={:?})",
3593             path,
3594             opt_ns,
3595             record_used,
3596             path_span,
3597             crate_lint,
3598         );
3599
3600         for (i, &Segment { ident, id }) in path.iter().enumerate() {
3601             debug!("resolve_path ident {} {:?} {:?}", i, ident, id);
3602             let record_segment_def = |this: &mut Self, def| {
3603                 if record_used {
3604                     if let Some(id) = id {
3605                         if !this.def_map.contains_key(&id) {
3606                             assert!(id != ast::DUMMY_NODE_ID, "Trying to resolve dummy id");
3607                             this.record_def(id, PathResolution::new(def));
3608                         }
3609                     }
3610                 }
3611             };
3612
3613             let is_last = i == path.len() - 1;
3614             let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
3615             let name = ident.name;
3616
3617             allow_super &= ns == TypeNS &&
3618                 (name == keywords::SelfLower.name() ||
3619                  name == keywords::Super.name());
3620
3621             if ns == TypeNS {
3622                 if allow_super && name == keywords::Super.name() {
3623                     let mut ctxt = ident.span.ctxt().modern();
3624                     let self_module = match i {
3625                         0 => Some(self.resolve_self(&mut ctxt, self.current_module)),
3626                         _ => match module {
3627                             Some(ModuleOrUniformRoot::Module(module)) => Some(module),
3628                             _ => None,
3629                         },
3630                     };
3631                     if let Some(self_module) = self_module {
3632                         if let Some(parent) = self_module.parent {
3633                             module = Some(ModuleOrUniformRoot::Module(
3634                                 self.resolve_self(&mut ctxt, parent)));
3635                             continue;
3636                         }
3637                     }
3638                     let msg = "there are too many initial `super`s.".to_string();
3639                     return PathResult::Failed {
3640                         span: ident.span,
3641                         label: msg,
3642                         suggestion: None,
3643                         is_error_from_last_segment: false,
3644                     };
3645                 }
3646                 if i == 0 {
3647                     if name == keywords::SelfLower.name() {
3648                         let mut ctxt = ident.span.ctxt().modern();
3649                         module = Some(ModuleOrUniformRoot::Module(
3650                             self.resolve_self(&mut ctxt, self.current_module)));
3651                         continue;
3652                     }
3653                     if name == keywords::PathRoot.name() && ident.span.rust_2018() {
3654                         module = Some(ModuleOrUniformRoot::ExternPrelude);
3655                         continue;
3656                     }
3657                     if name == keywords::PathRoot.name() &&
3658                        ident.span.rust_2015() && self.session.rust_2018() {
3659                         // `::a::b` from 2015 macro on 2018 global edition
3660                         module = Some(ModuleOrUniformRoot::CrateRootAndExternPrelude);
3661                         continue;
3662                     }
3663                     if name == keywords::PathRoot.name() ||
3664                        name == keywords::Crate.name() ||
3665                        name == keywords::DollarCrate.name() {
3666                         // `::a::b`, `crate::a::b` or `$crate::a::b`
3667                         module = Some(ModuleOrUniformRoot::Module(
3668                             self.resolve_crate_root(ident)));
3669                         continue;
3670                     }
3671                 }
3672             }
3673
3674             // Report special messages for path segment keywords in wrong positions.
3675             if ident.is_path_segment_keyword() && i != 0 {
3676                 let name_str = if name == keywords::PathRoot.name() {
3677                     "crate root".to_string()
3678                 } else {
3679                     format!("`{}`", name)
3680                 };
3681                 let label = if i == 1 && path[0].ident.name == keywords::PathRoot.name() {
3682                     format!("global paths cannot start with {}", name_str)
3683                 } else {
3684                     format!("{} in paths can only be used in start position", name_str)
3685                 };
3686                 return PathResult::Failed {
3687                     span: ident.span,
3688                     label,
3689                     suggestion: None,
3690                     is_error_from_last_segment: false,
3691                 };
3692             }
3693
3694             let binding = if let Some(module) = module {
3695                 self.resolve_ident_in_module(module, ident, ns, None, record_used, path_span)
3696             } else if opt_ns.is_none() || opt_ns == Some(MacroNS) {
3697                 assert!(ns == TypeNS);
3698                 let scopes = if opt_ns.is_none() { ScopeSet::Import(ns) } else { ScopeSet::Module };
3699                 self.early_resolve_ident_in_lexical_scope(ident, scopes, parent_scope, record_used,
3700                                                           record_used, path_span)
3701             } else {
3702                 let record_used_id =
3703                     if record_used { crate_lint.node_id().or(Some(CRATE_NODE_ID)) } else { None };
3704                 match self.resolve_ident_in_lexical_scope(ident, ns, record_used_id, path_span) {
3705                     // we found a locally-imported or available item/module
3706                     Some(LexicalScopeBinding::Item(binding)) => Ok(binding),
3707                     // we found a local variable or type param
3708                     Some(LexicalScopeBinding::Def(def))
3709                             if opt_ns == Some(TypeNS) || opt_ns == Some(ValueNS) => {
3710                         record_segment_def(self, def);
3711                         return PathResult::NonModule(PathResolution::with_unresolved_segments(
3712                             def, path.len() - 1
3713                         ));
3714                     }
3715                     _ => Err(Determinacy::determined(record_used)),
3716                 }
3717             };
3718
3719             match binding {
3720                 Ok(binding) => {
3721                     if i == 1 {
3722                         second_binding = Some(binding);
3723                     }
3724                     let def = binding.def();
3725                     let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(def);
3726                     if let Some(next_module) = binding.module() {
3727                         module = Some(ModuleOrUniformRoot::Module(next_module));
3728                         record_segment_def(self, def);
3729                     } else if def == Def::ToolMod && i + 1 != path.len() {
3730                         if binding.is_import() {
3731                             self.session.struct_span_err(
3732                                 ident.span, "cannot use a tool module through an import"
3733                             ).span_note(
3734                                 binding.span, "the tool module imported here"
3735                             ).emit();
3736                         }
3737                         let def = Def::NonMacroAttr(NonMacroAttrKind::Tool);
3738                         return PathResult::NonModule(PathResolution::new(def));
3739                     } else if def == Def::Err {
3740                         return PathResult::NonModule(err_path_resolution());
3741                     } else if opt_ns.is_some() && (is_last || maybe_assoc) {
3742                         self.lint_if_path_starts_with_module(
3743                             crate_lint,
3744                             path,
3745                             path_span,
3746                             second_binding,
3747                         );
3748                         return PathResult::NonModule(PathResolution::with_unresolved_segments(
3749                             def, path.len() - i - 1
3750                         ));
3751                     } else {
3752                         let label = format!(
3753                             "`{}` is {} {}, not a module",
3754                             ident,
3755                             def.article(),
3756                             def.kind_name(),
3757                         );
3758
3759                         return PathResult::Failed {
3760                             span: ident.span,
3761                             label,
3762                             suggestion: None,
3763                             is_error_from_last_segment: is_last,
3764                         };
3765                     }
3766                 }
3767                 Err(Undetermined) => return PathResult::Indeterminate,
3768                 Err(Determined) => {
3769                     if let Some(ModuleOrUniformRoot::Module(module)) = module {
3770                         if opt_ns.is_some() && !module.is_normal() {
3771                             return PathResult::NonModule(PathResolution::with_unresolved_segments(
3772                                 module.def().unwrap(), path.len() - i
3773                             ));
3774                         }
3775                     }
3776                     let module_def = match module {
3777                         Some(ModuleOrUniformRoot::Module(module)) => module.def(),
3778                         _ => None,
3779                     };
3780                     let (label, suggestion) = if module_def == self.graph_root.def() {
3781                         let is_mod = |def| match def { Def::Mod(..) => true, _ => false };
3782                         let mut candidates =
3783                             self.lookup_import_candidates(ident, TypeNS, is_mod);
3784                         candidates.sort_by_cached_key(|c| {
3785                             (c.path.segments.len(), c.path.to_string())
3786                         });
3787                         if let Some(candidate) = candidates.get(0) {
3788                             (
3789                                 String::from("unresolved import"),
3790                                 Some((
3791                                     vec![(ident.span, candidate.path.to_string())],
3792                                     String::from("a similar path exists"),
3793                                     Applicability::MaybeIncorrect,
3794                                 )),
3795                             )
3796                         } else if !ident.is_reserved() {
3797                             (format!("maybe a missing `extern crate {};`?", ident), None)
3798                         } else {
3799                             // the parser will already have complained about the keyword being used
3800                             return PathResult::NonModule(err_path_resolution());
3801                         }
3802                     } else if i == 0 {
3803                         (format!("use of undeclared type or module `{}`", ident), None)
3804                     } else {
3805                         (format!("could not find `{}` in `{}`", ident, path[i - 1].ident), None)
3806                     };
3807                     return PathResult::Failed {
3808                         span: ident.span,
3809                         label,
3810                         suggestion,
3811                         is_error_from_last_segment: is_last,
3812                     };
3813                 }
3814             }
3815         }
3816
3817         self.lint_if_path_starts_with_module(crate_lint, path, path_span, second_binding);
3818
3819         PathResult::Module(match module {
3820             Some(module) => module,
3821             None if path.is_empty() => ModuleOrUniformRoot::CurrentScope,
3822             _ => span_bug!(path_span, "resolve_path: non-empty path `{:?}` has no module", path),
3823         })
3824     }
3825
3826     fn lint_if_path_starts_with_module(
3827         &self,
3828         crate_lint: CrateLint,
3829         path: &[Segment],
3830         path_span: Span,
3831         second_binding: Option<&NameBinding<'_>>,
3832     ) {
3833         let (diag_id, diag_span) = match crate_lint {
3834             CrateLint::No => return,
3835             CrateLint::SimplePath(id) => (id, path_span),
3836             CrateLint::UsePath { root_id, root_span } => (root_id, root_span),
3837             CrateLint::QPathTrait { qpath_id, qpath_span } => (qpath_id, qpath_span),
3838         };
3839
3840         let first_name = match path.get(0) {
3841             // In the 2018 edition this lint is a hard error, so nothing to do
3842             Some(seg) if seg.ident.span.rust_2015() && self.session.rust_2015() => seg.ident.name,
3843             _ => return,
3844         };
3845
3846         // We're only interested in `use` paths which should start with
3847         // `{{root}}` currently.
3848         if first_name != keywords::PathRoot.name() {
3849             return
3850         }
3851
3852         match path.get(1) {
3853             // If this import looks like `crate::...` it's already good
3854             Some(Segment { ident, .. }) if ident.name == keywords::Crate.name() => return,
3855             // Otherwise go below to see if it's an extern crate
3856             Some(_) => {}
3857             // If the path has length one (and it's `PathRoot` most likely)
3858             // then we don't know whether we're gonna be importing a crate or an
3859             // item in our crate. Defer this lint to elsewhere
3860             None => return,
3861         }
3862
3863         // If the first element of our path was actually resolved to an
3864         // `ExternCrate` (also used for `crate::...`) then no need to issue a
3865         // warning, this looks all good!
3866         if let Some(binding) = second_binding {
3867             if let NameBindingKind::Import { directive: d, .. } = binding.kind {
3868                 // Careful: we still want to rewrite paths from
3869                 // renamed extern crates.
3870                 if let ImportDirectiveSubclass::ExternCrate { source: None, .. } = d.subclass {
3871                     return
3872                 }
3873             }
3874         }
3875
3876         let diag = lint::builtin::BuiltinLintDiagnostics
3877             ::AbsPathWithModule(diag_span);
3878         self.session.buffer_lint_with_diagnostic(
3879             lint::builtin::ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
3880             diag_id, diag_span,
3881             "absolute paths must start with `self`, `super`, \
3882             `crate`, or an external crate name in the 2018 edition",
3883             diag);
3884     }
3885
3886     // Resolve a local definition, potentially adjusting for closures.
3887     fn adjust_local_def(&mut self,
3888                         ns: Namespace,
3889                         rib_index: usize,
3890                         mut def: Def,
3891                         record_used: bool,
3892                         span: Span) -> Def {
3893         debug!("adjust_local_def");
3894         let ribs = &self.ribs[ns][rib_index + 1..];
3895
3896         // An invalid forward use of a type parameter from a previous default.
3897         if let ForwardTyParamBanRibKind = self.ribs[ns][rib_index].kind {
3898             if record_used {
3899                 resolve_error(self, span, ResolutionError::ForwardDeclaredTyParam);
3900             }
3901             assert_eq!(def, Def::Err);
3902             return Def::Err;
3903         }
3904
3905         match def {
3906             Def::Upvar(..) => {
3907                 span_bug!(span, "unexpected {:?} in bindings", def)
3908             }
3909             Def::Local(node_id) => {
3910                 use ResolutionError::*;
3911                 let mut res_err = None;
3912
3913                 for rib in ribs {
3914                     match rib.kind {
3915                         NormalRibKind | ModuleRibKind(..) | MacroDefinition(..) |
3916                         ForwardTyParamBanRibKind => {
3917                             // Nothing to do. Continue.
3918                         }
3919                         ClosureRibKind(function_id) => {
3920                             let prev_def = def;
3921
3922                             let seen = self.freevars_seen
3923                                            .entry(function_id)
3924                                            .or_default();
3925                             if let Some(&index) = seen.get(&node_id) {
3926                                 def = Def::Upvar(node_id, index, function_id);
3927                                 continue;
3928                             }
3929                             let vec = self.freevars
3930                                           .entry(function_id)
3931                                           .or_default();
3932                             let depth = vec.len();
3933                             def = Def::Upvar(node_id, depth, function_id);
3934
3935                             if record_used {
3936                                 vec.push(Freevar {
3937                                     def: prev_def,
3938                                     span,
3939                                 });
3940                                 seen.insert(node_id, depth);
3941                             }
3942                         }
3943                         ItemRibKind | FnItemRibKind | TraitOrImplItemRibKind => {
3944                             // This was an attempt to access an upvar inside a
3945                             // named function item. This is not allowed, so we
3946                             // report an error.
3947                             if record_used {
3948                                 // We don't immediately trigger a resolve error, because
3949                                 // we want certain other resolution errors (namely those
3950                                 // emitted for `ConstantItemRibKind` below) to take
3951                                 // precedence.
3952                                 res_err = Some(CannotCaptureDynamicEnvironmentInFnItem);
3953                             }
3954                         }
3955                         ConstantItemRibKind => {
3956                             // Still doesn't deal with upvars
3957                             if record_used {
3958                                 resolve_error(self, span, AttemptToUseNonConstantValueInConstant);
3959                             }
3960                             return Def::Err;
3961                         }
3962                     }
3963                 }
3964                 if let Some(res_err) = res_err {
3965                      resolve_error(self, span, res_err);
3966                      return Def::Err;
3967                 }
3968             }
3969             Def::TyParam(..) | Def::SelfTy(..) => {
3970                 for rib in ribs {
3971                     match rib.kind {
3972                         NormalRibKind | TraitOrImplItemRibKind | ClosureRibKind(..) |
3973                         ModuleRibKind(..) | MacroDefinition(..) | ForwardTyParamBanRibKind |
3974                         ConstantItemRibKind => {
3975                             // Nothing to do. Continue.
3976                         }
3977                         ItemRibKind | FnItemRibKind => {
3978                             // This was an attempt to use a type parameter outside its scope.
3979                             if record_used {
3980                                 resolve_error(
3981                                     self,
3982                                     span,
3983                                     ResolutionError::GenericParamsFromOuterFunction(def),
3984                                 );
3985                             }
3986                             return Def::Err;
3987                         }
3988                     }
3989                 }
3990             }
3991             Def::ConstParam(..) => {
3992                 let mut ribs = ribs.iter().peekable();
3993                 if let Some(Rib { kind: FnItemRibKind, .. }) = ribs.peek() {
3994                     // When declaring const parameters inside function signatures, the first rib
3995                     // is always a `FnItemRibKind`. In this case, we can skip it, to avoid it
3996                     // (spuriously) conflicting with the const param.
3997                     ribs.next();
3998                 }
3999                 for rib in ribs {
4000                     if let ItemRibKind | FnItemRibKind = rib.kind {
4001                         // This was an attempt to use a const parameter outside its scope.
4002                         if record_used {
4003                             resolve_error(
4004                                 self,
4005                                 span,
4006                                 ResolutionError::GenericParamsFromOuterFunction(def),
4007                             );
4008                         }
4009                         return Def::Err;
4010                     }
4011                 }
4012             }
4013             _ => {}
4014         }
4015         def
4016     }
4017
4018     fn lookup_assoc_candidate<FilterFn>(&mut self,
4019                                         ident: Ident,
4020                                         ns: Namespace,
4021                                         filter_fn: FilterFn)
4022                                         -> Option<AssocSuggestion>
4023         where FilterFn: Fn(Def) -> bool
4024     {
4025         fn extract_node_id(t: &Ty) -> Option<NodeId> {
4026             match t.node {
4027                 TyKind::Path(None, _) => Some(t.id),
4028                 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
4029                 // This doesn't handle the remaining `Ty` variants as they are not
4030                 // that commonly the self_type, it might be interesting to provide
4031                 // support for those in future.
4032                 _ => None,
4033             }
4034         }
4035
4036         // Fields are generally expected in the same contexts as locals.
4037         if filter_fn(Def::Local(ast::DUMMY_NODE_ID)) {
4038             if let Some(node_id) = self.current_self_type.as_ref().and_then(extract_node_id) {
4039                 // Look for a field with the same name in the current self_type.
4040                 if let Some(resolution) = self.def_map.get(&node_id) {
4041                     match resolution.base_def() {
4042                         Def::Struct(did) | Def::Union(did)
4043                                 if resolution.unresolved_segments() == 0 => {
4044                             if let Some(field_names) = self.field_names.get(&did) {
4045                                 if field_names.iter().any(|&field_name| ident.name == field_name) {
4046                                     return Some(AssocSuggestion::Field);
4047                                 }
4048                             }
4049                         }
4050                         _ => {}
4051                     }
4052                 }
4053             }
4054         }
4055
4056         // Look for associated items in the current trait.
4057         if let Some((module, _)) = self.current_trait_ref {
4058             if let Ok(binding) = self.resolve_ident_in_module(
4059                     ModuleOrUniformRoot::Module(module),
4060                     ident,
4061                     ns,
4062                     None,
4063                     false,
4064                     module.span,
4065                 ) {
4066                 let def = binding.def();
4067                 if filter_fn(def) {
4068                     return Some(if self.has_self.contains(&def.def_id()) {
4069                         AssocSuggestion::MethodWithSelf
4070                     } else {
4071                         AssocSuggestion::AssocItem
4072                     });
4073                 }
4074             }
4075         }
4076
4077         None
4078     }
4079
4080     fn lookup_typo_candidate<FilterFn>(
4081         &mut self,
4082         path: &[Segment],
4083         ns: Namespace,
4084         filter_fn: FilterFn,
4085         span: Span,
4086     ) -> Option<TypoSuggestion>
4087     where
4088         FilterFn: Fn(Def) -> bool,
4089     {
4090         let add_module_candidates = |module: Module<'_>, names: &mut Vec<TypoSuggestion>| {
4091             for (&(ident, _), resolution) in module.resolutions.borrow().iter() {
4092                 if let Some(binding) = resolution.borrow().binding {
4093                     if filter_fn(binding.def()) {
4094                         names.push(TypoSuggestion {
4095                             candidate: ident.name,
4096                             article: binding.def().article(),
4097                             kind: binding.def().kind_name(),
4098                         });
4099                     }
4100                 }
4101             }
4102         };
4103
4104         let mut names = Vec::new();
4105         if path.len() == 1 {
4106             // Search in lexical scope.
4107             // Walk backwards up the ribs in scope and collect candidates.
4108             for rib in self.ribs[ns].iter().rev() {
4109                 // Locals and type parameters
4110                 for (ident, def) in &rib.bindings {
4111                     if filter_fn(*def) {
4112                         names.push(TypoSuggestion {
4113                             candidate: ident.name,
4114                             article: def.article(),
4115                             kind: def.kind_name(),
4116                         });
4117                     }
4118                 }
4119                 // Items in scope
4120                 if let ModuleRibKind(module) = rib.kind {
4121                     // Items from this module
4122                     add_module_candidates(module, &mut names);
4123
4124                     if let ModuleKind::Block(..) = module.kind {
4125                         // We can see through blocks
4126                     } else {
4127                         // Items from the prelude
4128                         if !module.no_implicit_prelude {
4129                             names.extend(self.extern_prelude.clone().iter().flat_map(|(ident, _)| {
4130                                 self.crate_loader
4131                                     .maybe_process_path_extern(ident.name, ident.span)
4132                                     .and_then(|crate_id| {
4133                                         let crate_mod = Def::Mod(DefId {
4134                                             krate: crate_id,
4135                                             index: CRATE_DEF_INDEX,
4136                                         });
4137
4138                                         if filter_fn(crate_mod) {
4139                                             Some(TypoSuggestion {
4140                                                 candidate: ident.name,
4141                                                 article: "a",
4142                                                 kind: "crate",
4143                                             })
4144                                         } else {
4145                                             None
4146                                         }
4147                                     })
4148                             }));
4149
4150                             if let Some(prelude) = self.prelude {
4151                                 add_module_candidates(prelude, &mut names);
4152                             }
4153                         }
4154                         break;
4155                     }
4156                 }
4157             }
4158             // Add primitive types to the mix
4159             if filter_fn(Def::PrimTy(Bool)) {
4160                 names.extend(
4161                     self.primitive_type_table.primitive_types.iter().map(|(name, _)| {
4162                         TypoSuggestion {
4163                             candidate: *name,
4164                             article: "a",
4165                             kind: "primitive type",
4166                         }
4167                     })
4168                 )
4169             }
4170         } else {
4171             // Search in module.
4172             let mod_path = &path[..path.len() - 1];
4173             if let PathResult::Module(module) = self.resolve_path_without_parent_scope(
4174                 mod_path, Some(TypeNS), false, span, CrateLint::No
4175             ) {
4176                 if let ModuleOrUniformRoot::Module(module) = module {
4177                     add_module_candidates(module, &mut names);
4178                 }
4179             }
4180         }
4181
4182         let name = path[path.len() - 1].ident.name;
4183         // Make sure error reporting is deterministic.
4184         names.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
4185
4186         match find_best_match_for_name(
4187             names.iter().map(|suggestion| &suggestion.candidate),
4188             &name.as_str(),
4189             None,
4190         ) {
4191             Some(found) if found != name => names
4192                 .into_iter()
4193                 .find(|suggestion| suggestion.candidate == found),
4194             _ => None,
4195         }
4196     }
4197
4198     fn with_resolved_label<F>(&mut self, label: Option<Label>, id: NodeId, f: F)
4199         where F: FnOnce(&mut Resolver<'_>)
4200     {
4201         if let Some(label) = label {
4202             self.unused_labels.insert(id, label.ident.span);
4203             let def = Def::Label(id);
4204             self.with_label_rib(|this| {
4205                 let ident = label.ident.modern_and_legacy();
4206                 this.label_ribs.last_mut().unwrap().bindings.insert(ident, def);
4207                 f(this);
4208             });
4209         } else {
4210             f(self);
4211         }
4212     }
4213
4214     fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &Block) {
4215         self.with_resolved_label(label, id, |this| this.visit_block(block));
4216     }
4217
4218     fn resolve_expr(&mut self, expr: &Expr, parent: Option<&Expr>) {
4219         // First, record candidate traits for this expression if it could
4220         // result in the invocation of a method call.
4221
4222         self.record_candidate_traits_for_expr_if_necessary(expr);
4223
4224         // Next, resolve the node.
4225         match expr.node {
4226             ExprKind::Path(ref qself, ref path) => {
4227                 self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
4228                 visit::walk_expr(self, expr);
4229             }
4230
4231             ExprKind::Struct(ref path, ..) => {
4232                 self.smart_resolve_path(expr.id, None, path, PathSource::Struct);
4233                 visit::walk_expr(self, expr);
4234             }
4235
4236             ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
4237                 let def = self.search_label(label.ident, |rib, ident| {
4238                     rib.bindings.get(&ident.modern_and_legacy()).cloned()
4239                 });
4240                 match def {
4241                     None => {
4242                         // Search again for close matches...
4243                         // Picks the first label that is "close enough", which is not necessarily
4244                         // the closest match
4245                         let close_match = self.search_label(label.ident, |rib, ident| {
4246                             let names = rib.bindings.iter().map(|(id, _)| &id.name);
4247                             find_best_match_for_name(names, &*ident.as_str(), None)
4248                         });
4249                         self.record_def(expr.id, err_path_resolution());
4250                         resolve_error(self,
4251                                       label.ident.span,
4252                                       ResolutionError::UndeclaredLabel(&label.ident.as_str(),
4253                                                                        close_match));
4254                     }
4255                     Some(Def::Label(id)) => {
4256                         // Since this def is a label, it is never read.
4257                         self.record_def(expr.id, PathResolution::new(Def::Label(id)));
4258                         self.unused_labels.remove(&id);
4259                     }
4260                     Some(_) => {
4261                         span_bug!(expr.span, "label wasn't mapped to a label def!");
4262                     }
4263                 }
4264
4265                 // visit `break` argument if any
4266                 visit::walk_expr(self, expr);
4267             }
4268
4269             ExprKind::IfLet(ref pats, ref subexpression, ref if_block, ref optional_else) => {
4270                 self.visit_expr(subexpression);
4271
4272                 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
4273                 let mut bindings_list = FxHashMap::default();
4274                 for pat in pats {
4275                     self.resolve_pattern(pat, PatternSource::IfLet, &mut bindings_list);
4276                 }
4277                 // This has to happen *after* we determine which pat_idents are variants
4278                 self.check_consistent_bindings(pats);
4279                 self.visit_block(if_block);
4280                 self.ribs[ValueNS].pop();
4281
4282                 optional_else.as_ref().map(|expr| self.visit_expr(expr));
4283             }
4284
4285             ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
4286
4287             ExprKind::While(ref subexpression, ref block, label) => {
4288                 self.with_resolved_label(label, expr.id, |this| {
4289                     this.visit_expr(subexpression);
4290                     this.visit_block(block);
4291                 });
4292             }
4293
4294             ExprKind::WhileLet(ref pats, ref subexpression, ref block, label) => {
4295                 self.with_resolved_label(label, expr.id, |this| {
4296                     this.visit_expr(subexpression);
4297                     this.ribs[ValueNS].push(Rib::new(NormalRibKind));
4298                     let mut bindings_list = FxHashMap::default();
4299                     for pat in pats {
4300                         this.resolve_pattern(pat, PatternSource::WhileLet, &mut bindings_list);
4301                     }
4302                     // This has to happen *after* we determine which pat_idents are variants.
4303                     this.check_consistent_bindings(pats);
4304                     this.visit_block(block);
4305                     this.ribs[ValueNS].pop();
4306                 });
4307             }
4308
4309             ExprKind::ForLoop(ref pattern, ref subexpression, ref block, label) => {
4310                 self.visit_expr(subexpression);
4311                 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
4312                 self.resolve_pattern(pattern, PatternSource::For, &mut FxHashMap::default());
4313
4314                 self.resolve_labeled_block(label, expr.id, block);
4315
4316                 self.ribs[ValueNS].pop();
4317             }
4318
4319             ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
4320
4321             // Equivalent to `visit::walk_expr` + passing some context to children.
4322             ExprKind::Field(ref subexpression, _) => {
4323                 self.resolve_expr(subexpression, Some(expr));
4324             }
4325             ExprKind::MethodCall(ref segment, ref arguments) => {
4326                 let mut arguments = arguments.iter();
4327                 self.resolve_expr(arguments.next().unwrap(), Some(expr));
4328                 for argument in arguments {
4329                     self.resolve_expr(argument, None);
4330                 }
4331                 self.visit_path_segment(expr.span, segment);
4332             }
4333
4334             ExprKind::Call(ref callee, ref arguments) => {
4335                 self.resolve_expr(callee, Some(expr));
4336                 for argument in arguments {
4337                     self.resolve_expr(argument, None);
4338                 }
4339             }
4340             ExprKind::Type(ref type_expr, _) => {
4341                 self.current_type_ascription.push(type_expr.span);
4342                 visit::walk_expr(self, expr);
4343                 self.current_type_ascription.pop();
4344             }
4345             // Resolve the body of async exprs inside the async closure to which they desugar
4346             ExprKind::Async(_, async_closure_id, ref block) => {
4347                 let rib_kind = ClosureRibKind(async_closure_id);
4348                 self.ribs[ValueNS].push(Rib::new(rib_kind));
4349                 self.label_ribs.push(Rib::new(rib_kind));
4350                 self.visit_block(&block);
4351                 self.label_ribs.pop();
4352                 self.ribs[ValueNS].pop();
4353             }
4354             // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to
4355             // resolve the arguments within the proper scopes so that usages of them inside the
4356             // closure are detected as upvars rather than normal closure arg usages.
4357             ExprKind::Closure(
4358                 _, IsAsync::Async { closure_id: inner_closure_id, .. }, _,
4359                 ref fn_decl, ref body, _span,
4360             ) => {
4361                 let rib_kind = ClosureRibKind(expr.id);
4362                 self.ribs[ValueNS].push(Rib::new(rib_kind));
4363                 self.label_ribs.push(Rib::new(rib_kind));
4364                 // Resolve arguments:
4365                 let mut bindings_list = FxHashMap::default();
4366                 for argument in &fn_decl.inputs {
4367                     self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
4368                     self.visit_ty(&argument.ty);
4369                 }
4370                 // No need to resolve return type-- the outer closure return type is
4371                 // FunctionRetTy::Default
4372
4373                 // Now resolve the inner closure
4374                 {
4375                     let rib_kind = ClosureRibKind(inner_closure_id);
4376                     self.ribs[ValueNS].push(Rib::new(rib_kind));
4377                     self.label_ribs.push(Rib::new(rib_kind));
4378                     // No need to resolve arguments: the inner closure has none.
4379                     // Resolve the return type:
4380                     visit::walk_fn_ret_ty(self, &fn_decl.output);
4381                     // Resolve the body
4382                     self.visit_expr(body);
4383                     self.label_ribs.pop();
4384                     self.ribs[ValueNS].pop();
4385                 }
4386                 self.label_ribs.pop();
4387                 self.ribs[ValueNS].pop();
4388             }
4389             _ => {
4390                 visit::walk_expr(self, expr);
4391             }
4392         }
4393     }
4394
4395     fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
4396         match expr.node {
4397             ExprKind::Field(_, ident) => {
4398                 // FIXME(#6890): Even though you can't treat a method like a
4399                 // field, we need to add any trait methods we find that match
4400                 // the field name so that we can do some nice error reporting
4401                 // later on in typeck.
4402                 let traits = self.get_traits_containing_item(ident, ValueNS);
4403                 self.trait_map.insert(expr.id, traits);
4404             }
4405             ExprKind::MethodCall(ref segment, ..) => {
4406                 debug!("(recording candidate traits for expr) recording traits for {}",
4407                        expr.id);
4408                 let traits = self.get_traits_containing_item(segment.ident, ValueNS);
4409                 self.trait_map.insert(expr.id, traits);
4410             }
4411             _ => {
4412                 // Nothing to do.
4413             }
4414         }
4415     }
4416
4417     fn get_traits_containing_item(&mut self, mut ident: Ident, ns: Namespace)
4418                                   -> Vec<TraitCandidate> {
4419         debug!("(getting traits containing item) looking for '{}'", ident.name);
4420
4421         let mut found_traits = Vec::new();
4422         // Look for the current trait.
4423         if let Some((module, _)) = self.current_trait_ref {
4424             if self.resolve_ident_in_module(
4425                 ModuleOrUniformRoot::Module(module),
4426                 ident,
4427                 ns,
4428                 None,
4429                 false,
4430                 module.span,
4431             ).is_ok() {
4432                 let def_id = module.def_id().unwrap();
4433                 found_traits.push(TraitCandidate { def_id: def_id, import_id: None });
4434             }
4435         }
4436
4437         ident.span = ident.span.modern();
4438         let mut search_module = self.current_module;
4439         loop {
4440             self.get_traits_in_module_containing_item(ident, ns, search_module, &mut found_traits);
4441             search_module = unwrap_or!(
4442                 self.hygienic_lexical_parent(search_module, &mut ident.span), break
4443             );
4444         }
4445
4446         if let Some(prelude) = self.prelude {
4447             if !search_module.no_implicit_prelude {
4448                 self.get_traits_in_module_containing_item(ident, ns, prelude, &mut found_traits);
4449             }
4450         }
4451
4452         found_traits
4453     }
4454
4455     fn get_traits_in_module_containing_item(&mut self,
4456                                             ident: Ident,
4457                                             ns: Namespace,
4458                                             module: Module<'a>,
4459                                             found_traits: &mut Vec<TraitCandidate>) {
4460         assert!(ns == TypeNS || ns == ValueNS);
4461         let mut traits = module.traits.borrow_mut();
4462         if traits.is_none() {
4463             let mut collected_traits = Vec::new();
4464             module.for_each_child(|name, ns, binding| {
4465                 if ns != TypeNS { return }
4466                 match binding.def() {
4467                     Def::Trait(_) |
4468                     Def::TraitAlias(_) => collected_traits.push((name, binding)),
4469                     _ => (),
4470                 }
4471             });
4472             *traits = Some(collected_traits.into_boxed_slice());
4473         }
4474
4475         for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
4476             // Traits have pseudo-modules that can be used to search for the given ident.
4477             if let Some(module) = binding.module() {
4478                 let mut ident = ident;
4479                 if ident.span.glob_adjust(
4480                     module.expansion,
4481                     binding.span.ctxt().modern(),
4482                 ).is_none() {
4483                     continue
4484                 }
4485                 if self.resolve_ident_in_module_unadjusted(
4486                     ModuleOrUniformRoot::Module(module),
4487                     ident,
4488                     ns,
4489                     false,
4490                     module.span,
4491                 ).is_ok() {
4492                     let import_id = match binding.kind {
4493                         NameBindingKind::Import { directive, .. } => {
4494                             self.maybe_unused_trait_imports.insert(directive.id);
4495                             self.add_to_glob_map(&directive, trait_name);
4496                             Some(directive.id)
4497                         }
4498                         _ => None,
4499                     };
4500                     let trait_def_id = module.def_id().unwrap();
4501                     found_traits.push(TraitCandidate { def_id: trait_def_id, import_id });
4502                 }
4503             } else if let Def::TraitAlias(_) = binding.def() {
4504                 // For now, just treat all trait aliases as possible candidates, since we don't
4505                 // know if the ident is somewhere in the transitive bounds.
4506
4507                 let import_id = match binding.kind {
4508                     NameBindingKind::Import { directive, .. } => {
4509                         self.maybe_unused_trait_imports.insert(directive.id);
4510                         self.add_to_glob_map(&directive, trait_name);
4511                         Some(directive.id)
4512                     }
4513                     _ => None,
4514                 };
4515                 let trait_def_id = binding.def().def_id();
4516                 found_traits.push(TraitCandidate { def_id: trait_def_id, import_id });
4517             } else {
4518                 bug!("candidate is not trait or trait alias?")
4519             }
4520         }
4521     }
4522
4523     fn lookup_import_candidates_from_module<FilterFn>(&mut self,
4524                                           lookup_ident: Ident,
4525                                           namespace: Namespace,
4526                                           start_module: &'a ModuleData<'a>,
4527                                           crate_name: Ident,
4528                                           filter_fn: FilterFn)
4529                                           -> Vec<ImportSuggestion>
4530         where FilterFn: Fn(Def) -> bool
4531     {
4532         let mut candidates = Vec::new();
4533         let mut seen_modules = FxHashSet::default();
4534         let not_local_module = crate_name != keywords::Crate.ident();
4535         let mut worklist = vec![(start_module, Vec::<ast::PathSegment>::new(), not_local_module)];
4536
4537         while let Some((in_module,
4538                         path_segments,
4539                         in_module_is_extern)) = worklist.pop() {
4540             self.populate_module_if_necessary(in_module);
4541
4542             // We have to visit module children in deterministic order to avoid
4543             // instabilities in reported imports (#43552).
4544             in_module.for_each_child_stable(|ident, ns, name_binding| {
4545                 // avoid imports entirely
4546                 if name_binding.is_import() && !name_binding.is_extern_crate() { return; }
4547                 // avoid non-importable candidates as well
4548                 if !name_binding.is_importable() { return; }
4549
4550                 // collect results based on the filter function
4551                 if ident.name == lookup_ident.name && ns == namespace {
4552                     let def = name_binding.def();
4553                     if filter_fn(def) {
4554                         // create the path
4555                         let mut segms = path_segments.clone();
4556                         if lookup_ident.span.rust_2018() {
4557                             // crate-local absolute paths start with `crate::` in edition 2018
4558                             // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
4559                             segms.insert(
4560                                 0, ast::PathSegment::from_ident(crate_name)
4561                             );
4562                         }
4563
4564                         segms.push(ast::PathSegment::from_ident(ident));
4565                         let path = Path {
4566                             span: name_binding.span,
4567                             segments: segms,
4568                         };
4569                         // the entity is accessible in the following cases:
4570                         // 1. if it's defined in the same crate, it's always
4571                         // accessible (since private entities can be made public)
4572                         // 2. if it's defined in another crate, it's accessible
4573                         // only if both the module is public and the entity is
4574                         // declared as public (due to pruning, we don't explore
4575                         // outside crate private modules => no need to check this)
4576                         if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
4577                             let did = match def {
4578                                 Def::Ctor(did, ..) => self.parent(did),
4579                                 _ => def.opt_def_id(),
4580                             };
4581                             candidates.push(ImportSuggestion { did, path });
4582                         }
4583                     }
4584                 }
4585
4586                 // collect submodules to explore
4587                 if let Some(module) = name_binding.module() {
4588                     // form the path
4589                     let mut path_segments = path_segments.clone();
4590                     path_segments.push(ast::PathSegment::from_ident(ident));
4591
4592                     let is_extern_crate_that_also_appears_in_prelude =
4593                         name_binding.is_extern_crate() &&
4594                         lookup_ident.span.rust_2018();
4595
4596                     let is_visible_to_user =
4597                         !in_module_is_extern || name_binding.vis == ty::Visibility::Public;
4598
4599                     if !is_extern_crate_that_also_appears_in_prelude && is_visible_to_user {
4600                         // add the module to the lookup
4601                         let is_extern = in_module_is_extern || name_binding.is_extern_crate();
4602                         if seen_modules.insert(module.def_id().unwrap()) {
4603                             worklist.push((module, path_segments, is_extern));
4604                         }
4605                     }
4606                 }
4607             })
4608         }
4609
4610         candidates
4611     }
4612
4613     /// When name resolution fails, this method can be used to look up candidate
4614     /// entities with the expected name. It allows filtering them using the
4615     /// supplied predicate (which should be used to only accept the types of
4616     /// definitions expected, e.g., traits). The lookup spans across all crates.
4617     ///
4618     /// N.B., the method does not look into imports, but this is not a problem,
4619     /// since we report the definitions (thus, the de-aliased imports).
4620     fn lookup_import_candidates<FilterFn>(&mut self,
4621                                           lookup_ident: Ident,
4622                                           namespace: Namespace,
4623                                           filter_fn: FilterFn)
4624                                           -> Vec<ImportSuggestion>
4625         where FilterFn: Fn(Def) -> bool
4626     {
4627         let mut suggestions = self.lookup_import_candidates_from_module(
4628             lookup_ident, namespace, self.graph_root, keywords::Crate.ident(), &filter_fn);
4629
4630         if lookup_ident.span.rust_2018() {
4631             let extern_prelude_names = self.extern_prelude.clone();
4632             for (ident, _) in extern_prelude_names.into_iter() {
4633                 if let Some(crate_id) = self.crate_loader.maybe_process_path_extern(ident.name,
4634                                                                                     ident.span) {
4635                     let crate_root = self.get_module(DefId {
4636                         krate: crate_id,
4637                         index: CRATE_DEF_INDEX,
4638                     });
4639                     self.populate_module_if_necessary(&crate_root);
4640
4641                     suggestions.extend(self.lookup_import_candidates_from_module(
4642                         lookup_ident, namespace, crate_root, ident, &filter_fn));
4643                 }
4644             }
4645         }
4646
4647         suggestions
4648     }
4649
4650     fn find_module(&mut self,
4651                    module_def: Def)
4652                    -> Option<(Module<'a>, ImportSuggestion)>
4653     {
4654         let mut result = None;
4655         let mut seen_modules = FxHashSet::default();
4656         let mut worklist = vec![(self.graph_root, Vec::new())];
4657
4658         while let Some((in_module, path_segments)) = worklist.pop() {
4659             // abort if the module is already found
4660             if result.is_some() { break; }
4661
4662             self.populate_module_if_necessary(in_module);
4663
4664             in_module.for_each_child_stable(|ident, _, name_binding| {
4665                 // abort if the module is already found or if name_binding is private external
4666                 if result.is_some() || !name_binding.vis.is_visible_locally() {
4667                     return
4668                 }
4669                 if let Some(module) = name_binding.module() {
4670                     // form the path
4671                     let mut path_segments = path_segments.clone();
4672                     path_segments.push(ast::PathSegment::from_ident(ident));
4673                     if module.def() == Some(module_def) {
4674                         let path = Path {
4675                             span: name_binding.span,
4676                             segments: path_segments,
4677                         };
4678                         let did = module.def().and_then(|def| def.opt_def_id());
4679                         result = Some((module, ImportSuggestion { did, path }));
4680                     } else {
4681                         // add the module to the lookup
4682                         if seen_modules.insert(module.def_id().unwrap()) {
4683                             worklist.push((module, path_segments));
4684                         }
4685                     }
4686                 }
4687             });
4688         }
4689
4690         result
4691     }
4692
4693     fn collect_enum_variants(&mut self, enum_def: Def) -> Option<Vec<Path>> {
4694         if let Def::Enum(..) = enum_def {} else {
4695             panic!("Non-enum def passed to collect_enum_variants: {:?}", enum_def)
4696         }
4697
4698         self.find_module(enum_def).map(|(enum_module, enum_import_suggestion)| {
4699             self.populate_module_if_necessary(enum_module);
4700
4701             let mut variants = Vec::new();
4702             enum_module.for_each_child_stable(|ident, _, name_binding| {
4703                 if let Def::Variant(..) = name_binding.def() {
4704                     let mut segms = enum_import_suggestion.path.segments.clone();
4705                     segms.push(ast::PathSegment::from_ident(ident));
4706                     variants.push(Path {
4707                         span: name_binding.span,
4708                         segments: segms,
4709                     });
4710                 }
4711             });
4712             variants
4713         })
4714     }
4715
4716     fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
4717         debug!("(recording def) recording {:?} for {}", resolution, node_id);
4718         if let Some(prev_res) = self.def_map.insert(node_id, resolution) {
4719             panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution);
4720         }
4721     }
4722
4723     fn resolve_visibility(&mut self, vis: &ast::Visibility) -> ty::Visibility {
4724         match vis.node {
4725             ast::VisibilityKind::Public => ty::Visibility::Public,
4726             ast::VisibilityKind::Crate(..) => {
4727                 ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))
4728             }
4729             ast::VisibilityKind::Inherited => {
4730                 ty::Visibility::Restricted(self.current_module.normal_ancestor_id)
4731             }
4732             ast::VisibilityKind::Restricted { ref path, id, .. } => {
4733                 // For visibilities we are not ready to provide correct implementation of "uniform
4734                 // paths" right now, so on 2018 edition we only allow module-relative paths for now.
4735                 // On 2015 edition visibilities are resolved as crate-relative by default,
4736                 // so we are prepending a root segment if necessary.
4737                 let ident = path.segments.get(0).expect("empty path in visibility").ident;
4738                 let crate_root = if ident.is_path_segment_keyword() {
4739                     None
4740                 } else if ident.span.rust_2018() {
4741                     let msg = "relative paths are not supported in visibilities on 2018 edition";
4742                     self.session.struct_span_err(ident.span, msg)
4743                         .span_suggestion(
4744                             path.span,
4745                             "try",
4746                             format!("crate::{}", path),
4747                             Applicability::MaybeIncorrect,
4748                         )
4749                         .emit();
4750                     return ty::Visibility::Public;
4751                 } else {
4752                     let ctxt = ident.span.ctxt();
4753                     Some(Segment::from_ident(Ident::new(
4754                         keywords::PathRoot.name(), path.span.shrink_to_lo().with_ctxt(ctxt)
4755                     )))
4756                 };
4757
4758                 let segments = crate_root.into_iter()
4759                     .chain(path.segments.iter().map(|seg| seg.into())).collect::<Vec<_>>();
4760                 let def = self.smart_resolve_path_fragment(
4761                     id,
4762                     None,
4763                     &segments,
4764                     path.span,
4765                     PathSource::Visibility,
4766                     CrateLint::SimplePath(id),
4767                 ).base_def();
4768                 if def == Def::Err {
4769                     ty::Visibility::Public
4770                 } else {
4771                     let vis = ty::Visibility::Restricted(def.def_id());
4772                     if self.is_accessible(vis) {
4773                         vis
4774                     } else {
4775                         self.session.span_err(path.span, "visibilities can only be restricted \
4776                                                           to ancestor modules");
4777                         ty::Visibility::Public
4778                     }
4779                 }
4780             }
4781         }
4782     }
4783
4784     fn is_accessible(&self, vis: ty::Visibility) -> bool {
4785         vis.is_accessible_from(self.current_module.normal_ancestor_id, self)
4786     }
4787
4788     fn is_accessible_from(&self, vis: ty::Visibility, module: Module<'a>) -> bool {
4789         vis.is_accessible_from(module.normal_ancestor_id, self)
4790     }
4791
4792     fn set_binding_parent_module(&mut self, binding: &'a NameBinding<'a>, module: Module<'a>) {
4793         if let Some(old_module) = self.binding_parent_modules.insert(PtrKey(binding), module) {
4794             if !ptr::eq(module, old_module) {
4795                 span_bug!(binding.span, "parent module is reset for binding");
4796             }
4797         }
4798     }
4799
4800     fn disambiguate_legacy_vs_modern(
4801         &self,
4802         legacy: &'a NameBinding<'a>,
4803         modern: &'a NameBinding<'a>,
4804     ) -> bool {
4805         // Some non-controversial subset of ambiguities "modern macro name" vs "macro_rules"
4806         // is disambiguated to mitigate regressions from macro modularization.
4807         // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general.
4808         match (self.binding_parent_modules.get(&PtrKey(legacy)),
4809                self.binding_parent_modules.get(&PtrKey(modern))) {
4810             (Some(legacy), Some(modern)) =>
4811                 legacy.normal_ancestor_id == modern.normal_ancestor_id &&
4812                 modern.is_ancestor_of(legacy),
4813             _ => false,
4814         }
4815     }
4816
4817     fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
4818         if b.span.is_dummy() {
4819             let add_built_in = match b.def() {
4820                 // These already contain the "built-in" prefix or look bad with it.
4821                 Def::NonMacroAttr(..) | Def::PrimTy(..) | Def::ToolMod => false,
4822                 _ => true,
4823             };
4824             let (built_in, from) = if from_prelude {
4825                 ("", " from prelude")
4826             } else if b.is_extern_crate() && !b.is_import() &&
4827                         self.session.opts.externs.get(&ident.as_str()).is_some() {
4828                 ("", " passed with `--extern`")
4829             } else if add_built_in {
4830                 (" built-in", "")
4831             } else {
4832                 ("", "")
4833             };
4834
4835             let article = if built_in.is_empty() { b.article() } else { "a" };
4836             format!("{a}{built_in} {thing}{from}",
4837                     a = article, thing = b.descr(), built_in = built_in, from = from)
4838         } else {
4839             let introduced = if b.is_import() { "imported" } else { "defined" };
4840             format!("the {thing} {introduced} here",
4841                     thing = b.descr(), introduced = introduced)
4842         }
4843     }
4844
4845     fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError<'_>) {
4846         let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
4847         let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
4848             // We have to print the span-less alternative first, otherwise formatting looks bad.
4849             (b2, b1, misc2, misc1, true)
4850         } else {
4851             (b1, b2, misc1, misc2, false)
4852         };
4853
4854         let mut err = struct_span_err!(self.session, ident.span, E0659,
4855                                        "`{ident}` is ambiguous ({why})",
4856                                        ident = ident, why = kind.descr());
4857         err.span_label(ident.span, "ambiguous name");
4858
4859         let mut could_refer_to = |b: &NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
4860             let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
4861             let note_msg = format!("`{ident}` could{also} refer to {what}",
4862                                    ident = ident, also = also, what = what);
4863
4864             let mut help_msgs = Vec::new();
4865             if b.is_glob_import() && (kind == AmbiguityKind::GlobVsGlob ||
4866                                       kind == AmbiguityKind::GlobVsExpanded ||
4867                                       kind == AmbiguityKind::GlobVsOuter &&
4868                                       swapped != also.is_empty()) {
4869                 help_msgs.push(format!("consider adding an explicit import of \
4870                                         `{ident}` to disambiguate", ident = ident))
4871             }
4872             if b.is_extern_crate() && ident.span.rust_2018() {
4873                 help_msgs.push(format!(
4874                     "use `::{ident}` to refer to this {thing} unambiguously",
4875                     ident = ident, thing = b.descr(),
4876                 ))
4877             }
4878             if misc == AmbiguityErrorMisc::SuggestCrate {
4879                 help_msgs.push(format!(
4880                     "use `crate::{ident}` to refer to this {thing} unambiguously",
4881                     ident = ident, thing = b.descr(),
4882                 ))
4883             } else if misc == AmbiguityErrorMisc::SuggestSelf {
4884                 help_msgs.push(format!(
4885                     "use `self::{ident}` to refer to this {thing} unambiguously",
4886                     ident = ident, thing = b.descr(),
4887                 ))
4888             }
4889
4890             err.span_note(b.span, &note_msg);
4891             for (i, help_msg) in help_msgs.iter().enumerate() {
4892                 let or = if i == 0 { "" } else { "or " };
4893                 err.help(&format!("{}{}", or, help_msg));
4894             }
4895         };
4896
4897         could_refer_to(b1, misc1, "");
4898         could_refer_to(b2, misc2, " also");
4899         err.emit();
4900     }
4901
4902     fn report_errors(&mut self, krate: &Crate) {
4903         self.report_with_use_injections(krate);
4904
4905         for &(span_use, span_def) in &self.macro_expanded_macro_export_errors {
4906             let msg = "macro-expanded `macro_export` macros from the current crate \
4907                        cannot be referred to by absolute paths";
4908             self.session.buffer_lint_with_diagnostic(
4909                 lint::builtin::MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
4910                 CRATE_NODE_ID, span_use, msg,
4911                 lint::builtin::BuiltinLintDiagnostics::
4912                     MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def),
4913             );
4914         }
4915
4916         for ambiguity_error in &self.ambiguity_errors {
4917             self.report_ambiguity_error(ambiguity_error);
4918         }
4919
4920         let mut reported_spans = FxHashSet::default();
4921         for &PrivacyError(dedup_span, ident, binding) in &self.privacy_errors {
4922             if reported_spans.insert(dedup_span) {
4923                 span_err!(self.session, ident.span, E0603, "{} `{}` is private",
4924                           binding.descr(), ident.name);
4925             }
4926         }
4927     }
4928
4929     fn report_with_use_injections(&mut self, krate: &Crate) {
4930         for UseError { mut err, candidates, node_id, better } in self.use_injections.drain(..) {
4931             let (span, found_use) = UsePlacementFinder::check(krate, node_id);
4932             if !candidates.is_empty() {
4933                 show_candidates(&mut err, span, &candidates, better, found_use);
4934             }
4935             err.emit();
4936         }
4937     }
4938
4939     fn report_conflict<'b>(&mut self,
4940                        parent: Module<'_>,
4941                        ident: Ident,
4942                        ns: Namespace,
4943                        new_binding: &NameBinding<'b>,
4944                        old_binding: &NameBinding<'b>) {
4945         // Error on the second of two conflicting names
4946         if old_binding.span.lo() > new_binding.span.lo() {
4947             return self.report_conflict(parent, ident, ns, old_binding, new_binding);
4948         }
4949
4950         let container = match parent.kind {
4951             ModuleKind::Def(Def::Mod(_), _) => "module",
4952             ModuleKind::Def(Def::Trait(_), _) => "trait",
4953             ModuleKind::Block(..) => "block",
4954             _ => "enum",
4955         };
4956
4957         let old_noun = match old_binding.is_import() {
4958             true => "import",
4959             false => "definition",
4960         };
4961
4962         let new_participle = match new_binding.is_import() {
4963             true => "imported",
4964             false => "defined",
4965         };
4966
4967         let (name, span) = (ident.name, self.session.source_map().def_span(new_binding.span));
4968
4969         if let Some(s) = self.name_already_seen.get(&name) {
4970             if s == &span {
4971                 return;
4972             }
4973         }
4974
4975         let old_kind = match (ns, old_binding.module()) {
4976             (ValueNS, _) => "value",
4977             (MacroNS, _) => "macro",
4978             (TypeNS, _) if old_binding.is_extern_crate() => "extern crate",
4979             (TypeNS, Some(module)) if module.is_normal() => "module",
4980             (TypeNS, Some(module)) if module.is_trait() => "trait",
4981             (TypeNS, _) => "type",
4982         };
4983
4984         let msg = format!("the name `{}` is defined multiple times", name);
4985
4986         let mut err = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) {
4987             (true, true) => struct_span_err!(self.session, span, E0259, "{}", msg),
4988             (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() {
4989                 true => struct_span_err!(self.session, span, E0254, "{}", msg),
4990                 false => struct_span_err!(self.session, span, E0260, "{}", msg),
4991             },
4992             _ => match (old_binding.is_import(), new_binding.is_import()) {
4993                 (false, false) => struct_span_err!(self.session, span, E0428, "{}", msg),
4994                 (true, true) => struct_span_err!(self.session, span, E0252, "{}", msg),
4995                 _ => struct_span_err!(self.session, span, E0255, "{}", msg),
4996             },
4997         };
4998
4999         err.note(&format!("`{}` must be defined only once in the {} namespace of this {}",
5000                           name,
5001                           ns.descr(),
5002                           container));
5003
5004         err.span_label(span, format!("`{}` re{} here", name, new_participle));
5005         err.span_label(
5006             self.session.source_map().def_span(old_binding.span),
5007             format!("previous {} of the {} `{}` here", old_noun, old_kind, name),
5008         );
5009
5010         // See https://github.com/rust-lang/rust/issues/32354
5011         use NameBindingKind::Import;
5012         let directive = match (&new_binding.kind, &old_binding.kind) {
5013             // If there are two imports where one or both have attributes then prefer removing the
5014             // import without attributes.
5015             (Import { directive: new, .. }, Import { directive: old, .. }) if {
5016                 !new_binding.span.is_dummy() && !old_binding.span.is_dummy() &&
5017                     (new.has_attributes || old.has_attributes)
5018             } => {
5019                 if old.has_attributes {
5020                     Some((new, new_binding.span, true))
5021                 } else {
5022                     Some((old, old_binding.span, true))
5023                 }
5024             },
5025             // Otherwise prioritize the new binding.
5026             (Import { directive, .. }, other) if !new_binding.span.is_dummy() =>
5027                 Some((directive, new_binding.span, other.is_import())),
5028             (other, Import { directive, .. }) if !old_binding.span.is_dummy() =>
5029                 Some((directive, old_binding.span, other.is_import())),
5030             _ => None,
5031         };
5032
5033         // Check if the target of the use for both bindings is the same.
5034         let duplicate = new_binding.def().opt_def_id() == old_binding.def().opt_def_id();
5035         let has_dummy_span = new_binding.span.is_dummy() || old_binding.span.is_dummy();
5036         let from_item = self.extern_prelude.get(&ident)
5037             .map(|entry| entry.introduced_by_item)
5038             .unwrap_or(true);
5039         // Only suggest removing an import if both bindings are to the same def, if both spans
5040         // aren't dummy spans. Further, if both bindings are imports, then the ident must have
5041         // been introduced by a item.
5042         let should_remove_import = duplicate && !has_dummy_span &&
5043             ((new_binding.is_extern_crate() || old_binding.is_extern_crate()) || from_item);
5044
5045         match directive {
5046             Some((directive, span, true)) if should_remove_import && directive.is_nested() =>
5047                 self.add_suggestion_for_duplicate_nested_use(&mut err, directive, span),
5048             Some((directive, _, true)) if should_remove_import && !directive.is_glob() => {
5049                 // Simple case - remove the entire import. Due to the above match arm, this can
5050                 // only be a single use so just remove it entirely.
5051                 err.tool_only_span_suggestion(
5052                     directive.use_span_with_attributes,
5053                     "remove unnecessary import",
5054                     String::new(),
5055                     Applicability::MaybeIncorrect,
5056                 );
5057             },
5058             Some((directive, span, _)) =>
5059                 self.add_suggestion_for_rename_of_use(&mut err, name, directive, span),
5060             _ => {},
5061         }
5062
5063         err.emit();
5064         self.name_already_seen.insert(name, span);
5065     }
5066
5067     /// This function adds a suggestion to change the binding name of a new import that conflicts
5068     /// with an existing import.
5069     ///
5070     /// ```ignore (diagnostic)
5071     /// help: you can use `as` to change the binding name of the import
5072     ///    |
5073     /// LL | use foo::bar as other_bar;
5074     ///    |     ^^^^^^^^^^^^^^^^^^^^^
5075     /// ```
5076     fn add_suggestion_for_rename_of_use(
5077         &self,
5078         err: &mut DiagnosticBuilder<'_>,
5079         name: Symbol,
5080         directive: &ImportDirective<'_>,
5081         binding_span: Span,
5082     ) {
5083         let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() {
5084             format!("Other{}", name)
5085         } else {
5086             format!("other_{}", name)
5087         };
5088
5089         let mut suggestion = None;
5090         match directive.subclass {
5091             ImportDirectiveSubclass::SingleImport { type_ns_only: true, .. } =>
5092                 suggestion = Some(format!("self as {}", suggested_name)),
5093             ImportDirectiveSubclass::SingleImport { source, .. } => {
5094                 if let Some(pos) = source.span.hi().0.checked_sub(binding_span.lo().0)
5095                                                      .map(|pos| pos as usize) {
5096                     if let Ok(snippet) = self.session.source_map()
5097                                                      .span_to_snippet(binding_span) {
5098                         if pos <= snippet.len() {
5099                             suggestion = Some(format!(
5100                                 "{} as {}{}",
5101                                 &snippet[..pos],
5102                                 suggested_name,
5103                                 if snippet.ends_with(";") { ";" } else { "" }
5104                             ))
5105                         }
5106                     }
5107                 }
5108             }
5109             ImportDirectiveSubclass::ExternCrate { source, target, .. } =>
5110                 suggestion = Some(format!(
5111                     "extern crate {} as {};",
5112                     source.unwrap_or(target.name),
5113                     suggested_name,
5114                 )),
5115             _ => unreachable!(),
5116         }
5117
5118         let rename_msg = "you can use `as` to change the binding name of the import";
5119         if let Some(suggestion) = suggestion {
5120             err.span_suggestion(
5121                 binding_span,
5122                 rename_msg,
5123                 suggestion,
5124                 Applicability::MaybeIncorrect,
5125             );
5126         } else {
5127             err.span_label(binding_span, rename_msg);
5128         }
5129     }
5130
5131     /// This function adds a suggestion to remove a unnecessary binding from an import that is
5132     /// nested. In the following example, this function will be invoked to remove the `a` binding
5133     /// in the second use statement:
5134     ///
5135     /// ```ignore (diagnostic)
5136     /// use issue_52891::a;
5137     /// use issue_52891::{d, a, e};
5138     /// ```
5139     ///
5140     /// The following suggestion will be added:
5141     ///
5142     /// ```ignore (diagnostic)
5143     /// use issue_52891::{d, a, e};
5144     ///                      ^-- help: remove unnecessary import
5145     /// ```
5146     ///
5147     /// If the nested use contains only one import then the suggestion will remove the entire
5148     /// line.
5149     ///
5150     /// It is expected that the directive provided is a nested import - this isn't checked by the
5151     /// function. If this invariant is not upheld, this function's behaviour will be unexpected
5152     /// as characters expected by span manipulations won't be present.
5153     fn add_suggestion_for_duplicate_nested_use(
5154         &self,
5155         err: &mut DiagnosticBuilder<'_>,
5156         directive: &ImportDirective<'_>,
5157         binding_span: Span,
5158     ) {
5159         assert!(directive.is_nested());
5160         let message = "remove unnecessary import";
5161
5162         // Two examples will be used to illustrate the span manipulations we're doing:
5163         //
5164         // - Given `use issue_52891::{d, a, e};` where `a` is a duplicate then `binding_span` is
5165         //   `a` and `directive.use_span` is `issue_52891::{d, a, e};`.
5166         // - Given `use issue_52891::{d, e, a};` where `a` is a duplicate then `binding_span` is
5167         //   `a` and `directive.use_span` is `issue_52891::{d, e, a};`.
5168
5169         let (found_closing_brace, span) = find_span_of_binding_until_next_binding(
5170             self.session, binding_span, directive.use_span,
5171         );
5172
5173         // If there was a closing brace then identify the span to remove any trailing commas from
5174         // previous imports.
5175         if found_closing_brace {
5176             if let Some(span) = extend_span_to_previous_binding(self.session, span) {
5177                 err.tool_only_span_suggestion(span, message, String::new(),
5178                                               Applicability::MaybeIncorrect);
5179             } else {
5180                 // Remove the entire line if we cannot extend the span back, this indicates a
5181                 // `issue_52891::{self}` case.
5182                 err.span_suggestion(directive.use_span_with_attributes, message, String::new(),
5183                                     Applicability::MaybeIncorrect);
5184             }
5185
5186             return;
5187         }
5188
5189         err.span_suggestion(span, message, String::new(), Applicability::MachineApplicable);
5190     }
5191
5192     fn extern_prelude_get(&mut self, ident: Ident, speculative: bool)
5193                           -> Option<&'a NameBinding<'a>> {
5194         if ident.is_path_segment_keyword() {
5195             // Make sure `self`, `super` etc produce an error when passed to here.
5196             return None;
5197         }
5198         self.extern_prelude.get(&ident.modern()).cloned().and_then(|entry| {
5199             if let Some(binding) = entry.extern_crate_item {
5200                 if !speculative && entry.introduced_by_item {
5201                     self.record_use(ident, TypeNS, binding, false);
5202                 }
5203                 Some(binding)
5204             } else {
5205                 let crate_id = if !speculative {
5206                     self.crate_loader.process_path_extern(ident.name, ident.span)
5207                 } else if let Some(crate_id) =
5208                         self.crate_loader.maybe_process_path_extern(ident.name, ident.span) {
5209                     crate_id
5210                 } else {
5211                     return None;
5212                 };
5213                 let crate_root = self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
5214                 self.populate_module_if_necessary(&crate_root);
5215                 Some((crate_root, ty::Visibility::Public, DUMMY_SP, Mark::root())
5216                     .to_name_binding(self.arenas))
5217             }
5218         })
5219     }
5220 }
5221
5222 fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
5223     namespace == TypeNS && path.len() == 1 && path[0].ident.name == keywords::SelfUpper.name()
5224 }
5225
5226 fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
5227     namespace == ValueNS && path.len() == 1 && path[0].ident.name == keywords::SelfLower.name()
5228 }
5229
5230 fn names_to_string(idents: &[Ident]) -> String {
5231     let mut result = String::new();
5232     for (i, ident) in idents.iter()
5233                             .filter(|ident| ident.name != keywords::PathRoot.name())
5234                             .enumerate() {
5235         if i > 0 {
5236             result.push_str("::");
5237         }
5238         result.push_str(&ident.as_str());
5239     }
5240     result
5241 }
5242
5243 fn path_names_to_string(path: &Path) -> String {
5244     names_to_string(&path.segments.iter()
5245                         .map(|seg| seg.ident)
5246                         .collect::<Vec<_>>())
5247 }
5248
5249 /// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
5250 fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
5251     let variant_path = &suggestion.path;
5252     let variant_path_string = path_names_to_string(variant_path);
5253
5254     let path_len = suggestion.path.segments.len();
5255     let enum_path = ast::Path {
5256         span: suggestion.path.span,
5257         segments: suggestion.path.segments[0..path_len - 1].to_vec(),
5258     };
5259     let enum_path_string = path_names_to_string(&enum_path);
5260
5261     (variant_path_string, enum_path_string)
5262 }
5263
5264 /// When an entity with a given name is not available in scope, we search for
5265 /// entities with that name in all crates. This method allows outputting the
5266 /// results of this search in a programmer-friendly way
5267 fn show_candidates(err: &mut DiagnosticBuilder<'_>,
5268                    // This is `None` if all placement locations are inside expansions
5269                    span: Option<Span>,
5270                    candidates: &[ImportSuggestion],
5271                    better: bool,
5272                    found_use: bool) {
5273
5274     // we want consistent results across executions, but candidates are produced
5275     // by iterating through a hash map, so make sure they are ordered:
5276     let mut path_strings: Vec<_> =
5277         candidates.into_iter().map(|c| path_names_to_string(&c.path)).collect();
5278     path_strings.sort();
5279
5280     let better = if better { "better " } else { "" };
5281     let msg_diff = match path_strings.len() {
5282         1 => " is found in another module, you can import it",
5283         _ => "s are found in other modules, you can import them",
5284     };
5285     let msg = format!("possible {}candidate{} into scope", better, msg_diff);
5286
5287     if let Some(span) = span {
5288         for candidate in &mut path_strings {
5289             // produce an additional newline to separate the new use statement
5290             // from the directly following item.
5291             let additional_newline = if found_use {
5292                 ""
5293             } else {
5294                 "\n"
5295             };
5296             *candidate = format!("use {};\n{}", candidate, additional_newline);
5297         }
5298
5299         err.span_suggestions(
5300             span,
5301             &msg,
5302             path_strings.into_iter(),
5303             Applicability::Unspecified,
5304         );
5305     } else {
5306         let mut msg = msg;
5307         msg.push(':');
5308         for candidate in path_strings {
5309             msg.push('\n');
5310             msg.push_str(&candidate);
5311         }
5312     }
5313 }
5314
5315 /// A somewhat inefficient routine to obtain the name of a module.
5316 fn module_to_string(module: Module<'_>) -> Option<String> {
5317     let mut names = Vec::new();
5318
5319     fn collect_mod(names: &mut Vec<Ident>, module: Module<'_>) {
5320         if let ModuleKind::Def(_, name) = module.kind {
5321             if let Some(parent) = module.parent {
5322                 names.push(Ident::with_empty_ctxt(name));
5323                 collect_mod(names, parent);
5324             }
5325         } else {
5326             // danger, shouldn't be ident?
5327             names.push(Ident::from_str("<opaque>"));
5328             collect_mod(names, module.parent.unwrap());
5329         }
5330     }
5331     collect_mod(&mut names, module);
5332
5333     if names.is_empty() {
5334         return None;
5335     }
5336     Some(names_to_string(&names.into_iter()
5337                         .rev()
5338                         .collect::<Vec<_>>()))
5339 }
5340
5341 fn err_path_resolution() -> PathResolution {
5342     PathResolution::new(Def::Err)
5343 }
5344
5345 #[derive(Copy, Clone, Debug)]
5346 enum CrateLint {
5347     /// Do not issue the lint.
5348     No,
5349
5350     /// This lint applies to some arbitrary path; e.g., `impl ::foo::Bar`.
5351     /// In this case, we can take the span of that path.
5352     SimplePath(NodeId),
5353
5354     /// This lint comes from a `use` statement. In this case, what we
5355     /// care about really is the *root* `use` statement; e.g., if we
5356     /// have nested things like `use a::{b, c}`, we care about the
5357     /// `use a` part.
5358     UsePath { root_id: NodeId, root_span: Span },
5359
5360     /// This is the "trait item" from a fully qualified path. For example,
5361     /// we might be resolving  `X::Y::Z` from a path like `<T as X::Y>::Z`.
5362     /// The `path_span` is the span of the to the trait itself (`X::Y`).
5363     QPathTrait { qpath_id: NodeId, qpath_span: Span },
5364 }
5365
5366 impl CrateLint {
5367     fn node_id(&self) -> Option<NodeId> {
5368         match *self {
5369             CrateLint::No => None,
5370             CrateLint::SimplePath(id) |
5371             CrateLint::UsePath { root_id: id, .. } |
5372             CrateLint::QPathTrait { qpath_id: id, .. } => Some(id),
5373         }
5374     }
5375 }
5376
5377 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }