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