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