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