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