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