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