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