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