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