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