lib.rs 134.9 KB
Newer Older
1
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 3 4 5 6 7 8 9 10
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

11
#![crate_name = "rustc_resolve"]
12
#![unstable(feature = "rustc_private", issue = "27812")]
13 14
#![crate_type = "dylib"]
#![crate_type = "rlib"]
15
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
A
Alex Crichton 已提交
16
      html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
17
      html_root_url = "https://doc.rust-lang.org/nightly/")]
18
#![cfg_attr(not(stage0), deny(warnings))]
19

T
Fallout  
Tamir Duberstein 已提交
20
#![feature(associated_consts)]
A
Alex Crichton 已提交
21
#![feature(rustc_diagnostic_macros)]
22
#![feature(rustc_private)]
A
Alex Crichton 已提交
23
#![feature(staged_api)]
24

C
corentih 已提交
25 26 27 28
#[macro_use]
extern crate log;
#[macro_use]
extern crate syntax;
29 30
extern crate syntax_pos;
extern crate rustc_errors as errors;
31
extern crate arena;
C
corentih 已提交
32
#[macro_use]
33 34
extern crate rustc;

S
Steven Fackler 已提交
35 36 37 38 39
use self::Namespace::*;
use self::FallbackSuggestion::*;
use self::TypeParameters::*;
use self::RibKind::*;

40
use rustc::hir::map::{Definitions, DefCollector};
41
use rustc::hir::{self, PrimTy, TyBool, TyChar, TyFloat, TyInt, TyUint, TyStr};
42
use rustc::middle::cstore::CrateLoader;
43 44
use rustc::session::Session;
use rustc::lint;
45
use rustc::hir::def::*;
46
use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId};
47
use rustc::ty;
S
Seo Sanghyeon 已提交
48
use rustc::hir::{Freevar, FreevarMap, TraitCandidate, TraitMap, GlobMap};
49
use rustc::util::nodemap::{NodeMap, NodeSet, FxHashMap, FxHashSet};
50

J
Jeffrey Seyfried 已提交
51
use syntax::ext::hygiene::{Mark, SyntaxContext};
52
use syntax::ast::{self, FloatTy};
J
Jeffrey Seyfried 已提交
53
use syntax::ast::{CRATE_NODE_ID, Name, NodeId, Ident, SpannedIdent, IntTy, UintTy};
J
Jeffrey Seyfried 已提交
54
use syntax::ext::base::SyntaxExtension;
J
Jeffrey Seyfried 已提交
55
use syntax::ext::base::Determinacy::{Determined, Undetermined};
56
use syntax::symbol::{Symbol, keywords};
57
use syntax::util::lev_distance::find_best_match_for_name;
58

59
use syntax::visit::{self, FnKind, Visitor};
60
use syntax::attr;
61 62 63
use syntax::ast::{Arm, BindingMode, Block, Crate, Expr, ExprKind};
use syntax::ast::{FnDecl, ForeignItem, ForeignItemKind, Generics};
use syntax::ast::{Item, ItemKind, ImplItem, ImplItemKind};
64 65
use syntax::ast::{Local, Mutability, Pat, PatKind, Path};
use syntax::ast::{PathSegment, PathParameters, QSelf, TraitItemKind, TraitRef, Ty, TyKind};
66

67
use syntax_pos::{Span, DUMMY_SP};
68 69
use errors::DiagnosticBuilder;

70
use std::cell::{Cell, RefCell};
71
use std::fmt;
72
use std::mem::replace;
73
use std::rc::Rc;
74

75
use resolve_imports::{ImportDirective, ImportDirectiveSubclass, NameResolution, ImportResolver};
J
Jeffrey Seyfried 已提交
76
use macros::{InvocationData, LegacyBinding, LegacyScope};
77

78 79
// NB: This module needs to be declared first so diagnostics are
// registered before they are used.
J
Jeffrey Seyfried 已提交
80
mod diagnostics;
81

82
mod macros;
A
Alex Crichton 已提交
83
mod check_unused;
84
mod build_reduced_graph;
85
mod resolve_imports;
86

87 88
enum SuggestionType {
    Macro(String),
89
    Function(Symbol),
90 91 92
    NotFound,
}

93
/// Candidates for a name resolution failure
J
Jeffrey Seyfried 已提交
94
struct SuggestedCandidates {
95 96 97 98
    name: String,
    candidates: Vec<Path>,
}

J
Jeffrey Seyfried 已提交
99
enum ResolutionError<'a> {
100
    /// error E0401: can't use type parameters from outer function
101
    TypeParametersFromOuterFunction,
102
    /// error E0402: cannot use an outer type parameter in this context
103
    OuterTypeParameterContext,
104
    /// error E0403: the name is already used for a type parameter in this type parameter list
C
Chris Stankus 已提交
105
    NameAlreadyUsedInTypeParameterList(Name, &'a Span),
106
    /// error E0404: is not a trait
107
    IsNotATrait(&'a str, &'a str),
108
    /// error E0405: use of undeclared trait name
109
    UndeclaredTraitName(&'a str, SuggestedCandidates),
110
    /// error E0407: method is not a member of trait
111
    MethodNotMemberOfTrait(Name, &'a str),
112 113 114 115
    /// error E0437: type is not a member of trait
    TypeNotMemberOfTrait(Name, &'a str),
    /// error E0438: const is not a member of trait
    ConstNotMemberOfTrait(Name, &'a str),
M
Manish Goregaokar 已提交
116 117
    /// error E0408: variable `{}` from pattern #{} is not bound in pattern #{}
    VariableNotBoundInPattern(Name, usize, usize),
118
    /// error E0409: variable is bound with different mode in pattern #{} than in pattern #1
M
Mikhail Modin 已提交
119
    VariableBoundWithDifferentMode(Name, usize, Span),
120
    /// error E0411: use of `Self` outside of an impl or trait
121
    SelfUsedOutsideImplOrTrait,
122
    /// error E0412: use of undeclared
123
    UseOfUndeclared(&'a str, &'a str, SuggestedCandidates),
124
    /// error E0415: identifier is bound more than once in this parameter list
125
    IdentifierBoundMoreThanOnceInParameterList(&'a str),
126
    /// error E0416: identifier is bound more than once in the same pattern
127
    IdentifierBoundMoreThanOnceInSamePattern(&'a str),
128
    /// error E0423: is a struct variant name, but this expression uses it like a function name
129
    StructVariantUsedAsFunction(&'a str),
130
    /// error E0424: `self` is not available in a static method
131
    SelfNotAvailableInStaticMethod,
132
    /// error E0425: unresolved name
133 134 135 136 137
    UnresolvedName {
        path: &'a str,
        message: &'a str,
        context: UnresolvedNameContext<'a>,
        is_static_method: bool,
G
ggomez 已提交
138 139
        is_field: bool,
        def: Def,
140
    },
141
    /// error E0426: use of undeclared label
142
    UndeclaredLabel(&'a str),
143
    /// error E0429: `self` imports are only allowed within a { } list
144
    SelfImportsOnlyAllowedWithin,
145
    /// error E0430: `self` import can only appear once in the list
146
    SelfImportCanOnlyAppearOnceInTheList,
147
    /// error E0431: `self` import can only appear in an import list with a non-empty prefix
148
    SelfImportOnlyInImportListWithNonEmptyPrefix,
149
    /// error E0432: unresolved import
150
    UnresolvedImport(Option<(&'a str, &'a str)>),
151
    /// error E0433: failed to resolve
152
    FailedToResolve(&'a str),
153
    /// error E0434: can't capture dynamic environment in a fn item
154
    CannotCaptureDynamicEnvironmentInFnItem,
155
    /// error E0435: attempt to use a non-constant value in a constant
156
    AttemptToUseNonConstantValueInConstant,
157
    /// error E0530: X bindings cannot shadow Ys
158
    BindingShadowsSomethingUnacceptable(&'a str, Name, &'a NameBinding<'a>),
159
    /// error E0531: unresolved pattern path kind `name`
160
    PatPathUnresolved(&'a str, &'a Path),
161
    /// error E0532: expected pattern path kind, found another pattern path kind
162
    PatPathUnexpected(&'a str, &'a str, &'a Path),
163 164
}

165
/// Context of where `ResolutionError::UnresolvedName` arose.
166
#[derive(Clone, PartialEq, Eq, Debug)]
167 168
enum UnresolvedNameContext<'a> {
    /// `PathIsMod(parent)` indicates that a given path, used in
169
    /// expression context, actually resolved to a module rather than
170 171 172
    /// a value. The optional expression attached to the variant is the
    /// the parent of the erroneous path expression.
    PathIsMod(Option<&'a Expr>),
173 174 175 176

    /// `Other` means we have no extra information about the context
    /// of the unresolved name error. (Maybe we could eliminate all
    /// such cases; but for now, this is an information-free default.)
177 178 179
    Other,
}

180
fn resolve_error<'b, 'a: 'b, 'c>(resolver: &'b Resolver<'a>,
181
                                 span: syntax_pos::Span,
182
                                 resolution_error: ResolutionError<'c>) {
N
Nick Cameron 已提交
183
    resolve_struct_error(resolver, span, resolution_error).emit();
N
Nick Cameron 已提交
184 185
}

186
fn resolve_struct_error<'b, 'a: 'b, 'c>(resolver: &'b Resolver<'a>,
187
                                        span: syntax_pos::Span,
188 189
                                        resolution_error: ResolutionError<'c>)
                                        -> DiagnosticBuilder<'a> {
N
Nick Cameron 已提交
190
    match resolution_error {
191
        ResolutionError::TypeParametersFromOuterFunction => {
192 193 194 195 196
            let mut err = struct_span_err!(resolver.session,
                                           span,
                                           E0401,
                                           "can't use type parameters from outer function; \
                                           try using a local type parameter instead");
197
            err.span_label(span, &format!("use of type variable from outer function"));
198
            err
C
corentih 已提交
199
        }
200
        ResolutionError::OuterTypeParameterContext => {
N
Nick Cameron 已提交
201 202 203 204
            struct_span_err!(resolver.session,
                             span,
                             E0402,
                             "cannot use an outer type parameter in this context")
C
corentih 已提交
205
        }
C
Chris Stankus 已提交
206 207 208 209 210 211 212 213 214 215 216
        ResolutionError::NameAlreadyUsedInTypeParameterList(name, first_use_span) => {
             let mut err = struct_span_err!(resolver.session,
                                            span,
                                            E0403,
                                            "the name `{}` is already used for a type parameter \
                                            in this type parameter list",
                                            name);
             err.span_label(span, &format!("already used"));
             err.span_label(first_use_span.clone(), &format!("first use of `{}`", name));
             err

C
corentih 已提交
217
        }
218
        ResolutionError::IsNotATrait(name, kind_name) => {
R
Ryan Scott 已提交
219 220 221 222 223
            let mut err = struct_span_err!(resolver.session,
                                           span,
                                           E0404,
                                           "`{}` is not a trait",
                                           name);
224
            err.span_label(span, &format!("expected trait, found {}", kind_name));
R
Ryan Scott 已提交
225
            err
C
corentih 已提交
226
        }
227 228 229 230 231 232
        ResolutionError::UndeclaredTraitName(name, candidates) => {
            let mut err = struct_span_err!(resolver.session,
                                           span,
                                           E0405,
                                           "trait `{}` is not in scope",
                                           name);
233
            show_candidates(&mut err, &candidates);
234
            err.span_label(span, &format!("`{}` is not in scope", name));
235
            err
C
corentih 已提交
236
        }
237
        ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
C
crypto-universe 已提交
238 239 240 241 242 243
            let mut err = struct_span_err!(resolver.session,
                                           span,
                                           E0407,
                                           "method `{}` is not a member of trait `{}`",
                                           method,
                                           trait_);
244
            err.span_label(span, &format!("not a member of trait `{}`", trait_));
C
crypto-universe 已提交
245
            err
C
corentih 已提交
246
        }
247
        ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
S
Shyam Sundar B 已提交
248
            let mut err = struct_span_err!(resolver.session,
N
Nick Cameron 已提交
249 250 251 252
                             span,
                             E0437,
                             "type `{}` is not a member of trait `{}`",
                             type_,
S
Shyam Sundar B 已提交
253
                             trait_);
254
            err.span_label(span, &format!("not a member of trait `{}`", trait_));
S
Shyam Sundar B 已提交
255
            err
C
corentih 已提交
256
        }
257
        ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
S
Shyam Sundar B 已提交
258
            let mut err = struct_span_err!(resolver.session,
N
Nick Cameron 已提交
259 260 261 262
                             span,
                             E0438,
                             "const `{}` is not a member of trait `{}`",
                             const_,
S
Shyam Sundar B 已提交
263
                             trait_);
264
            err.span_label(span, &format!("not a member of trait `{}`", trait_));
S
Shyam Sundar B 已提交
265
            err
C
corentih 已提交
266
        }
M
Manish Goregaokar 已提交
267
        ResolutionError::VariableNotBoundInPattern(variable_name, from, to) => {
268
            let mut err = struct_span_err!(resolver.session,
N
Nick Cameron 已提交
269 270
                             span,
                             E0408,
M
Manish Goregaokar 已提交
271
                             "variable `{}` from pattern #{} is not bound in pattern #{}",
N
Nick Cameron 已提交
272
                             variable_name,
M
Manish Goregaokar 已提交
273
                             from,
274 275 276
                             to);
            err.span_label(span, &format!("pattern doesn't bind `{}`", variable_name));
            err
C
corentih 已提交
277
        }
M
Mikhail Modin 已提交
278 279 280 281
        ResolutionError::VariableBoundWithDifferentMode(variable_name,
                                                        pattern_number,
                                                        first_binding_span) => {
            let mut err = struct_span_err!(resolver.session,
N
Nick Cameron 已提交
282 283 284 285 286
                             span,
                             E0409,
                             "variable `{}` is bound with different mode in pattern #{} than in \
                              pattern #1",
                             variable_name,
M
Mikhail Modin 已提交
287 288 289 290
                             pattern_number);
            err.span_label(span, &format!("bound in different ways"));
            err.span_label(first_binding_span, &format!("first binding"));
            err
C
corentih 已提交
291
        }
292
        ResolutionError::SelfUsedOutsideImplOrTrait => {
293 294 295 296
            let mut err = struct_span_err!(resolver.session,
                                           span,
                                           E0411,
                                           "use of `Self` outside of an impl or trait");
J
Jonathan Turner 已提交
297
            err.span_label(span, &format!("used outside of impl or trait"));
298
            err
C
corentih 已提交
299
        }
300 301 302 303 304 305 306
        ResolutionError::UseOfUndeclared(kind, name, candidates) => {
            let mut err = struct_span_err!(resolver.session,
                                           span,
                                           E0412,
                                           "{} `{}` is undefined or not in scope",
                                           kind,
                                           name);
307
            show_candidates(&mut err, &candidates);
308
            err.span_label(span, &format!("undefined or not in scope"));
309
            err
C
corentih 已提交
310
        }
311
        ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
312
            let mut err = struct_span_err!(resolver.session,
N
Nick Cameron 已提交
313 314 315
                             span,
                             E0415,
                             "identifier `{}` is bound more than once in this parameter list",
316
                             identifier);
317
            err.span_label(span, &format!("used as parameter more than once"));
318
            err
C
corentih 已提交
319
        }
320
        ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
321
            let mut err = struct_span_err!(resolver.session,
N
Nick Cameron 已提交
322 323 324
                             span,
                             E0416,
                             "identifier `{}` is bound more than once in the same pattern",
325
                             identifier);
326
            err.span_label(span, &format!("used in a pattern more than once"));
327
            err
C
corentih 已提交
328
        }
329
        ResolutionError::StructVariantUsedAsFunction(path_name) => {
K
Knight 已提交
330
            let mut err = struct_span_err!(resolver.session,
N
Nick Cameron 已提交
331 332 333 334
                             span,
                             E0423,
                             "`{}` is the name of a struct or struct variant, but this expression \
                             uses it like a function name",
K
Knight 已提交
335 336 337
                             path_name);
            err.span_label(span, &format!("struct called like a function"));
            err
C
corentih 已提交
338
        }
339
        ResolutionError::SelfNotAvailableInStaticMethod => {
340
            let mut err = struct_span_err!(resolver.session,
N
Nick Cameron 已提交
341 342
                             span,
                             E0424,
343 344 345 346
                             "`self` is not available in a static method");
            err.span_label(span, &format!("not available in static method"));
            err.note(&format!("maybe a `self` argument is missing?"));
            err
C
corentih 已提交
347
        }
348
        ResolutionError::UnresolvedName { path, message: msg, context, is_static_method,
G
ggomez 已提交
349
                                          is_field, def } => {
N
Nick Cameron 已提交
350 351 352
            let mut err = struct_span_err!(resolver.session,
                                           span,
                                           E0425,
J
Jonathan Turner 已提交
353 354 355 356 357 358 359 360
                                           "unresolved name `{}`",
                                           path);
            if msg != "" {
                err.span_label(span, &msg);
            } else {
                err.span_label(span, &format!("unresolved name"));
            }

361
            match context {
362 363 364 365 366 367
                UnresolvedNameContext::Other => {
                    if msg.is_empty() && is_static_method && is_field {
                        err.help("this is an associated function, you don't have access to \
                                  this type's fields or methods");
                    }
                }
368
                UnresolvedNameContext::PathIsMod(parent) => {
369
                    err.help(&match parent.map(|parent| &parent.node) {
370
                        Some(&ExprKind::Field(_, ident)) => {
G
ggomez 已提交
371
                            format!("to reference an item from the `{module}` module, \
372 373 374
                                     use `{module}::{ident}`",
                                    module = path,
                                    ident = ident.node)
375
                        }
V
Vadim Petrochenkov 已提交
376
                        Some(&ExprKind::MethodCall(ident, ..)) => {
G
ggomez 已提交
377
                            format!("to call a function from the `{module}` module, \
378 379 380 381 382
                                     use `{module}::{ident}(..)`",
                                    module = path,
                                    ident = ident.node)
                        }
                        _ => {
G
ggomez 已提交
383 384
                            format!("{def} `{module}` cannot be used as an expression",
                                    def = def.kind_name(),
385 386 387
                                    module = path)
                        }
                    });
388 389
                }
            }
N
Nick Cameron 已提交
390
            err
C
corentih 已提交
391
        }
392
        ResolutionError::UndeclaredLabel(name) => {
C
crypto-universe 已提交
393 394 395 396 397 398 399
            let mut err = struct_span_err!(resolver.session,
                                           span,
                                           E0426,
                                           "use of undeclared label `{}`",
                                           name);
            err.span_label(span, &format!("undeclared label `{}`",&name));
            err
C
corentih 已提交
400
        }
401
        ResolutionError::SelfImportsOnlyAllowedWithin => {
N
Nick Cameron 已提交
402 403 404 405 406
            struct_span_err!(resolver.session,
                             span,
                             E0429,
                             "{}",
                             "`self` imports are only allowed within a { } list")
C
corentih 已提交
407
        }
408
        ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
N
Nick Cameron 已提交
409 410 411 412
            struct_span_err!(resolver.session,
                             span,
                             E0430,
                             "`self` import can only appear once in the list")
C
corentih 已提交
413
        }
414
        ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
N
Nick Cameron 已提交
415 416 417 418 419
            struct_span_err!(resolver.session,
                             span,
                             E0431,
                             "`self` import can only appear in an import list with a \
                              non-empty prefix")
420
        }
421
        ResolutionError::UnresolvedImport(name) => {
422
            let msg = match name {
K
Knight 已提交
423
                Some((n, _)) => format!("unresolved import `{}`", n),
C
corentih 已提交
424
                None => "unresolved import".to_owned(),
425
            };
K
Knight 已提交
426 427 428 429 430
            let mut err = struct_span_err!(resolver.session, span, E0432, "{}", msg);
            if let Some((_, p)) = name {
                err.span_label(span, &p);
            }
            err
C
corentih 已提交
431
        }
432
        ResolutionError::FailedToResolve(msg) => {
J
Jonathan Turner 已提交
433 434
            let mut err = struct_span_err!(resolver.session, span, E0433,
                                           "failed to resolve. {}", msg);
435 436
            err.span_label(span, &msg);
            err
C
corentih 已提交
437
        }
438
        ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
N
Nick Cameron 已提交
439 440 441 442 443 444
            struct_span_err!(resolver.session,
                             span,
                             E0434,
                             "{}",
                             "can't capture dynamic environment in a fn item; use the || { ... } \
                              closure form instead")
C
corentih 已提交
445 446
        }
        ResolutionError::AttemptToUseNonConstantValueInConstant => {
S
Shyam Sundar B 已提交
447
            let mut err = struct_span_err!(resolver.session,
N
Nick Cameron 已提交
448 449
                             span,
                             E0435,
S
Shyam Sundar B 已提交
450 451 452
                             "attempt to use a non-constant value in a constant");
            err.span_label(span, &format!("non-constant used with constant"));
            err
C
corentih 已提交
453
        }
454
        ResolutionError::BindingShadowsSomethingUnacceptable(what_binding, name, binding) => {
455
            let shadows_what = PathResolution::new(binding.def()).kind_name();
456 457
            let mut err = struct_span_err!(resolver.session,
                                           span,
458
                                           E0530,
459 460
                                           "{}s cannot shadow {}s", what_binding, shadows_what);
            err.span_label(span, &format!("cannot be named the same as a {}", shadows_what));
461 462 463
            let participle = if binding.is_import() { "imported" } else { "defined" };
            let msg = &format!("a {} `{}` is {} here", shadows_what, name, participle);
            err.span_label(binding.span, msg);
464 465 466 467 468
            err
        }
        ResolutionError::PatPathUnresolved(expected_what, path) => {
            struct_span_err!(resolver.session,
                             span,
469
                             E0531,
470 471
                             "unresolved {} `{}`",
                             expected_what,
472
                             path)
473 474 475 476
        }
        ResolutionError::PatPathUnexpected(expected_what, found_what, path) => {
            struct_span_err!(resolver.session,
                             span,
477
                             E0532,
478 479 480
                             "expected {}, found {} `{}`",
                             expected_what,
                             found_what,
481
                             path)
482
        }
N
Nick Cameron 已提交
483
    }
484 485
}

N
Niko Matsakis 已提交
486
#[derive(Copy, Clone)]
487
struct BindingInfo {
488
    span: Span,
489
    binding_mode: BindingMode,
490 491 492
}

// Map from the name in a pattern to its binding mode.
493
type BindingMap = FxHashMap<Ident, BindingInfo>;
494

495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum PatternSource {
    Match,
    IfLet,
    WhileLet,
    Let,
    For,
    FnParam,
}

impl PatternSource {
    fn is_refutable(self) -> bool {
        match self {
            PatternSource::Match | PatternSource::IfLet | PatternSource::WhileLet => true,
            PatternSource::Let | PatternSource::For | PatternSource::FnParam  => false,
        }
    }
    fn descr(self) -> &'static str {
        match self {
            PatternSource::Match => "match binding",
            PatternSource::IfLet => "if let binding",
            PatternSource::WhileLet => "while let binding",
            PatternSource::Let => "let binding",
            PatternSource::For => "for binding",
            PatternSource::FnParam => "function parameter",
        }
    }
522 523
}

N
Niko Matsakis 已提交
524
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
G
Garming Sam 已提交
525
pub enum Namespace {
526
    TypeNS,
C
corentih 已提交
527
    ValueNS,
528
    MacroNS,
529 530
}

J
Jeffrey Seyfried 已提交
531 532 533 534
#[derive(Clone, Default, Debug)]
pub struct PerNS<T> {
    value_ns: T,
    type_ns: T,
535
    macro_ns: Option<T>,
J
Jeffrey Seyfried 已提交
536 537 538 539 540 541 542 543
}

impl<T> ::std::ops::Index<Namespace> for PerNS<T> {
    type Output = T;
    fn index(&self, ns: Namespace) -> &T {
        match ns {
            ValueNS => &self.value_ns,
            TypeNS => &self.type_ns,
544
            MacroNS => self.macro_ns.as_ref().unwrap(),
J
Jeffrey Seyfried 已提交
545 546 547 548 549 550 551 552 553
        }
    }
}

impl<T> ::std::ops::IndexMut<Namespace> for PerNS<T> {
    fn index_mut(&mut self, ns: Namespace) -> &mut T {
        match ns {
            ValueNS => &mut self.value_ns,
            TypeNS => &mut self.type_ns,
554
            MacroNS => self.macro_ns.as_mut().unwrap(),
J
Jeffrey Seyfried 已提交
555 556 557 558
        }
    }
}

559 560
impl<'a, 'tcx> Visitor<'tcx> for Resolver<'a> {
    fn visit_item(&mut self, item: &'tcx Item) {
A
Alex Crichton 已提交
561
        self.resolve_item(item);
562
    }
563
    fn visit_arm(&mut self, arm: &'tcx Arm) {
A
Alex Crichton 已提交
564
        self.resolve_arm(arm);
565
    }
566
    fn visit_block(&mut self, block: &'tcx Block) {
A
Alex Crichton 已提交
567
        self.resolve_block(block);
568
    }
569
    fn visit_expr(&mut self, expr: &'tcx Expr) {
570
        self.resolve_expr(expr, None);
571
    }
572
    fn visit_local(&mut self, local: &'tcx Local) {
A
Alex Crichton 已提交
573
        self.resolve_local(local);
574
    }
575
    fn visit_ty(&mut self, ty: &'tcx Ty) {
A
Alex Crichton 已提交
576
        self.resolve_type(ty);
577
    }
578 579 580
    fn visit_poly_trait_ref(&mut self,
                            tref: &'tcx ast::PolyTraitRef,
                            m: &'tcx ast::TraitBoundModifier) {
J
Jeffrey Seyfried 已提交
581 582 583
        let ast::Path { ref segments, span, global } = tref.trait_ref.path;
        let path: Vec<_> = segments.iter().map(|seg| seg.identifier).collect();
        let def = self.resolve_trait_reference(&path, global, None, span);
584
        self.record_def(tref.trait_ref.ref_id, def);
585
        visit::walk_poly_trait_ref(self, tref, m);
586
    }
C
corentih 已提交
587
    fn visit_variant(&mut self,
588 589
                     variant: &'tcx ast::Variant,
                     generics: &'tcx Generics,
C
corentih 已提交
590
                     item_id: ast::NodeId) {
591 592 593
        if let Some(ref dis_expr) = variant.node.disr_expr {
            // resolve the discriminator expr as a constant
            self.with_constant_rib(|this| {
594
                this.visit_expr(dis_expr);
595 596 597
            });
        }

598
        // `visit::walk_variant` without the discriminant expression.
C
corentih 已提交
599 600 601 602 603
        self.visit_variant_data(&variant.node.data,
                                variant.node.name,
                                generics,
                                item_id,
                                variant.span);
604
    }
605
    fn visit_foreign_item(&mut self, foreign_item: &'tcx ForeignItem) {
606
        let type_parameters = match foreign_item.node {
607
            ForeignItemKind::Fn(_, ref generics) => {
608
                HasTypeParameters(generics, ItemRibKind)
609
            }
610
            ForeignItemKind::Static(..) => NoTypeParameters,
611 612
        };
        self.with_type_parameter_rib(type_parameters, |this| {
613
            visit::walk_foreign_item(this, foreign_item);
614 615 616
        });
    }
    fn visit_fn(&mut self,
617 618
                function_kind: FnKind<'tcx>,
                declaration: &'tcx FnDecl,
619 620 621
                _: Span,
                node_id: NodeId) {
        let rib_kind = match function_kind {
V
Vadim Petrochenkov 已提交
622
            FnKind::ItemFn(_, generics, ..) => {
623 624 625
                self.visit_generics(generics);
                ItemRibKind
            }
626
            FnKind::Method(_, sig, _, _) => {
627
                self.visit_generics(&sig.generics);
V
Vadim Petrochenkov 已提交
628
                MethodRibKind(!sig.decl.has_self())
629
            }
630
            FnKind::Closure(_) => ClosureRibKind(node_id),
631
        };
632 633

        // Create a value rib for the function.
J
Jeffrey Seyfried 已提交
634
        self.ribs[ValueNS].push(Rib::new(rib_kind));
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663

        // Create a label rib for the function.
        self.label_ribs.push(Rib::new(rib_kind));

        // Add each argument to the rib.
        let mut bindings_list = FxHashMap();
        for argument in &declaration.inputs {
            self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);

            self.visit_ty(&argument.ty);

            debug!("(resolving function) recorded argument");
        }
        visit::walk_fn_ret_ty(self, &declaration.output);

        // Resolve the function body.
        match function_kind {
            FnKind::ItemFn(.., body) |
            FnKind::Method(.., body) => {
                self.visit_block(body);
            }
            FnKind::Closure(body) => {
                self.visit_expr(body);
            }
        };

        debug!("(resolving function) leaving function");

        self.label_ribs.pop();
J
Jeffrey Seyfried 已提交
664
        self.ribs[ValueNS].pop();
665
    }
666
}
667

668
pub type ErrorMessage = Option<(Span, String)>;
669

670 671 672
enum FallbackSuggestion {
    NoSuggestion,
    Field,
673
    TraitItem,
674
    TraitMethod(String),
675 676
}

N
Niko Matsakis 已提交
677
#[derive(Copy, Clone)]
678
enum TypeParameters<'a, 'b> {
679
    NoTypeParameters,
C
corentih 已提交
680
    HasTypeParameters(// Type parameters.
681
                      &'b Generics,
682

C
corentih 已提交
683
                      // The kind of the rib used for type parameters.
684
                      RibKind<'a>),
685 686
}

687
// The rib kind controls the translation of local
688
// definitions (`Def::Local`) to upvars (`Def::Upvar`).
N
Niko Matsakis 已提交
689
#[derive(Copy, Clone, Debug)]
690
enum RibKind<'a> {
691 692
    // No translation needs to be applied.
    NormalRibKind,
693

694 695
    // We passed through a closure scope at the given node ID.
    // Translate upvars as appropriate.
696
    ClosureRibKind(NodeId /* func id */),
697

698
    // We passed through an impl or trait and are now in one of its
699
    // methods. Allow references to ty params that impl or trait
700 701
    // binds. Disallow any other upvars (including other ty params that are
    // upvars).
702 703 704
    //
    // The boolean value represents the fact that this method is static or not.
    MethodRibKind(bool),
705

706 707
    // We passed through an item scope. Disallow upvars.
    ItemRibKind,
708 709

    // We're in a constant item. Can't refer to dynamic stuff.
C
corentih 已提交
710
    ConstantItemRibKind,
711

712 713
    // We passed through a module.
    ModuleRibKind(Module<'a>),
714 715

    // We passed through a `macro_rules!` statement with the given expansion
716
    MacroDefinition(Mark),
717 718
}

719
/// One local scope.
J
Jorge Aparicio 已提交
720
#[derive(Debug)]
721
struct Rib<'a> {
722
    bindings: FxHashMap<Ident, Def>,
723
    kind: RibKind<'a>,
B
Brian Anderson 已提交
724
}
725

726 727
impl<'a> Rib<'a> {
    fn new(kind: RibKind<'a>) -> Rib<'a> {
728
        Rib {
729
            bindings: FxHashMap(),
C
corentih 已提交
730
            kind: kind,
731
        }
732 733 734
    }
}

735
/// A definition along with the index of the rib it was found on
J
Jeffrey Seyfried 已提交
736
#[derive(Copy, Clone)]
737 738
struct LocalDef {
    ribs: Option<(Namespace, usize)>,
C
corentih 已提交
739
    def: Def,
740 741
}

742 743
enum LexicalScopeBinding<'a> {
    Item(&'a NameBinding<'a>),
J
Jeffrey Seyfried 已提交
744
    Def(Def),
745 746
}

747
impl<'a> LexicalScopeBinding<'a> {
748
    fn item(self) -> Option<&'a NameBinding<'a>> {
749
        match self {
750
            LexicalScopeBinding::Item(binding) => Some(binding),
751 752 753 754 755
            _ => None,
        }
    }
}

756
#[derive(Copy, Clone, PartialEq)]
J
Jeffrey Seyfried 已提交
757 758 759 760 761 762 763 764 765 766 767 768 769 770
enum PathScope {
    Global,
    Lexical,
    Import,
}

#[derive(Clone)]
enum PathResult<'a> {
    Module(Module<'a>),
    NonModule(PathResolution),
    Indeterminate,
    Failed(String, bool /* is the error from the last segment? */),
}

J
Jeffrey Seyfried 已提交
771 772 773
enum ModuleKind {
    Block(NodeId),
    Def(Def, Name),
774 775
}

776
/// One node in the tree of modules.
777
pub struct ModuleData<'a> {
J
Jeffrey Seyfried 已提交
778 779
    parent: Option<Module<'a>>,
    kind: ModuleKind,
780

781
    // The node id of the closest normal module (`mod`) ancestor (including this module).
J
Jeffrey Seyfried 已提交
782
    normal_ancestor_id: Option<NodeId>,
783

784 785
    resolutions: RefCell<FxHashMap<(Ident, Namespace), &'a RefCell<NameResolution<'a>>>>,
    legacy_macro_resolutions: RefCell<Vec<(Mark, Ident, Span)>>,
786
    macro_resolutions: RefCell<Vec<(Box<[Ident]>, PathScope, Span)>>,
787

788 789 790
    // Macro invocations that can expand into items in this module.
    unresolved_invocations: RefCell<FxHashSet<Mark>>,

791
    no_implicit_prelude: bool,
792

793
    glob_importers: RefCell<Vec<&'a ImportDirective<'a>>>,
794
    globs: RefCell<Vec<&'a ImportDirective<'a>>>,
795

J
Jeffrey Seyfried 已提交
796
    // Used to memoize the traits in this module for faster searches through all traits in scope.
797
    traits: RefCell<Option<Box<[(Ident, &'a NameBinding<'a>)]>>>,
J
Jeffrey Seyfried 已提交
798

799 800 801
    // Whether this module is populated. If not populated, any attempt to
    // access the children must be preceded with a
    // `populate_module_if_necessary` call.
802
    populated: Cell<bool>,
803 804
}

805
pub type Module<'a> = &'a ModuleData<'a>;
806

807
impl<'a> ModuleData<'a> {
808
    fn new(parent: Option<Module<'a>>, kind: ModuleKind) -> Self {
809
        ModuleData {
J
Jeffrey Seyfried 已提交
810 811
            parent: parent,
            kind: kind,
812
            normal_ancestor_id: None,
813
            resolutions: RefCell::new(FxHashMap()),
814
            legacy_macro_resolutions: RefCell::new(Vec::new()),
815
            macro_resolutions: RefCell::new(Vec::new()),
816
            unresolved_invocations: RefCell::new(FxHashSet()),
817
            no_implicit_prelude: false,
818
            glob_importers: RefCell::new(Vec::new()),
819
            globs: RefCell::new((Vec::new())),
J
Jeffrey Seyfried 已提交
820
            traits: RefCell::new(None),
821
            populated: Cell::new(true),
822
        }
B
Brian Anderson 已提交
823 824
    }

825 826 827
    fn for_each_child<F: FnMut(Ident, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
        for (&(ident, ns), name_resolution) in self.resolutions.borrow().iter() {
            name_resolution.borrow().binding.map(|binding| f(ident, ns, binding));
828 829 830
        }
    }

J
Jeffrey Seyfried 已提交
831 832 833 834 835 836 837
    fn def(&self) -> Option<Def> {
        match self.kind {
            ModuleKind::Def(def, _) => Some(def),
            _ => None,
        }
    }

838
    fn def_id(&self) -> Option<DefId> {
J
Jeffrey Seyfried 已提交
839
        self.def().as_ref().map(Def::def_id)
840 841
    }

842
    // `self` resolves to the first module ancestor that `is_normal`.
843
    fn is_normal(&self) -> bool {
J
Jeffrey Seyfried 已提交
844 845
        match self.kind {
            ModuleKind::Def(Def::Mod(_), _) => true,
846 847 848 849 850
            _ => false,
        }
    }

    fn is_trait(&self) -> bool {
J
Jeffrey Seyfried 已提交
851 852
        match self.kind {
            ModuleKind::Def(Def::Trait(_), _) => true,
853
            _ => false,
854
        }
B
Brian Anderson 已提交
855
    }
856 857 858 859

    fn is_local(&self) -> bool {
        self.normal_ancestor_id.is_some()
    }
V
Victor Berger 已提交
860 861
}

862
impl<'a> fmt::Debug for ModuleData<'a> {
863
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
J
Jeffrey Seyfried 已提交
864
        write!(f, "{:?}", self.def())
865 866 867
    }
}

868
// Records a possibly-private value, type, or module definition.
869
#[derive(Clone, Debug)]
870
pub struct NameBinding<'a> {
871
    kind: NameBindingKind<'a>,
872
    expansion: Mark,
873
    span: Span,
874
    vis: ty::Visibility,
875 876
}

877
pub trait ToNameBinding<'a> {
J
Jeffrey Seyfried 已提交
878
    fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a>;
879 880
}

J
Jeffrey Seyfried 已提交
881 882
impl<'a> ToNameBinding<'a> for &'a NameBinding<'a> {
    fn to_name_binding(self, _: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
883 884 885 886
        self
    }
}

887
#[derive(Clone, Debug)]
888
enum NameBindingKind<'a> {
889
    Def(Def),
890
    Module(Module<'a>),
891 892
    Import {
        binding: &'a NameBinding<'a>,
893
        directive: &'a ImportDirective<'a>,
894
        used: Cell<bool>,
895
    },
896 897 898 899
    Ambiguity {
        b1: &'a NameBinding<'a>,
        b2: &'a NameBinding<'a>,
    }
900 901
}

902 903
struct PrivacyError<'a>(Span, Name, &'a NameBinding<'a>);

J
Jeffrey Seyfried 已提交
904 905 906
struct AmbiguityError<'a> {
    span: Span,
    name: Name,
907
    lexical: bool,
J
Jeffrey Seyfried 已提交
908 909 910 911
    b1: &'a NameBinding<'a>,
    b2: &'a NameBinding<'a>,
}

912
impl<'a> NameBinding<'a> {
J
Jeffrey Seyfried 已提交
913
    fn module(&self) -> Option<Module<'a>> {
914
        match self.kind {
J
Jeffrey Seyfried 已提交
915
            NameBindingKind::Module(module) => Some(module),
916
            NameBindingKind::Import { binding, .. } => binding.module(),
J
Jeffrey Seyfried 已提交
917
            _ => None,
918 919 920
        }
    }

921
    fn def(&self) -> Def {
922
        match self.kind {
923
            NameBindingKind::Def(def) => def,
J
Jeffrey Seyfried 已提交
924
            NameBindingKind::Module(module) => module.def().unwrap(),
925
            NameBindingKind::Import { binding, .. } => binding.def(),
926
            NameBindingKind::Ambiguity { .. } => Def::Err,
927
        }
928
    }
929

J
Jeffrey Seyfried 已提交
930 931 932 933 934 935 936 937
    fn get_macro(&self, resolver: &mut Resolver<'a>) -> Rc<SyntaxExtension> {
        match self.kind {
            NameBindingKind::Import { binding, .. } => binding.get_macro(resolver),
            NameBindingKind::Ambiguity { b1, .. } => b1.get_macro(resolver),
            _ => resolver.get_macro(self.def()),
        }
    }

938 939 940 941 942 943 944
    // We sometimes need to treat variants as `pub` for backwards compatibility
    fn pseudo_vis(&self) -> ty::Visibility {
        if self.is_variant() { ty::Visibility::Public } else { self.vis }
    }

    fn is_variant(&self) -> bool {
        match self.kind {
945 946
            NameBindingKind::Def(Def::Variant(..)) |
            NameBindingKind::Def(Def::VariantCtor(..)) => true,
947 948
            _ => false,
        }
949 950
    }

951
    fn is_extern_crate(&self) -> bool {
952 953 954 955 956 957 958 959
        match self.kind {
            NameBindingKind::Import {
                directive: &ImportDirective {
                    subclass: ImportDirectiveSubclass::ExternCrate, ..
                }, ..
            } => true,
            _ => false,
        }
960
    }
961 962 963 964 965 966 967

    fn is_import(&self) -> bool {
        match self.kind {
            NameBindingKind::Import { .. } => true,
            _ => false,
        }
    }
968 969 970 971

    fn is_glob_import(&self) -> bool {
        match self.kind {
            NameBindingKind::Import { directive, .. } => directive.is_glob(),
972
            NameBindingKind::Ambiguity { b1, .. } => b1.is_glob_import(),
973 974 975 976 977
            _ => false,
        }
    }

    fn is_importable(&self) -> bool {
978
        match self.def() {
979 980 981 982
            Def::AssociatedConst(..) | Def::Method(..) | Def::AssociatedTy(..) => false,
            _ => true,
        }
    }
983 984
}

985
/// Interns the names of the primitive types.
F
Felix S. Klock II 已提交
986
struct PrimitiveTypeTable {
987
    primitive_types: FxHashMap<Name, PrimTy>,
988
}
989

990
impl PrimitiveTypeTable {
K
Kevin Butler 已提交
991
    fn new() -> PrimitiveTypeTable {
992
        let mut table = PrimitiveTypeTable { primitive_types: FxHashMap() };
C
corentih 已提交
993 994 995

        table.intern("bool", TyBool);
        table.intern("char", TyChar);
996 997
        table.intern("f32", TyFloat(FloatTy::F32));
        table.intern("f64", TyFloat(FloatTy::F64));
998 999 1000 1001 1002
        table.intern("isize", TyInt(IntTy::Is));
        table.intern("i8", TyInt(IntTy::I8));
        table.intern("i16", TyInt(IntTy::I16));
        table.intern("i32", TyInt(IntTy::I32));
        table.intern("i64", TyInt(IntTy::I64));
C
corentih 已提交
1003
        table.intern("str", TyStr);
1004 1005 1006 1007 1008
        table.intern("usize", TyUint(UintTy::Us));
        table.intern("u8", TyUint(UintTy::U8));
        table.intern("u16", TyUint(UintTy::U16));
        table.intern("u32", TyUint(UintTy::U32));
        table.intern("u64", TyUint(UintTy::U64));
K
Kevin Butler 已提交
1009 1010 1011 1012

        table
    }

1013
    fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1014
        self.primitive_types.insert(Symbol::intern(string), primitive_type);
1015 1016 1017
    }
}

1018
/// The main resolver class.
1019
pub struct Resolver<'a> {
E
Eduard Burtescu 已提交
1020
    session: &'a Session,
1021

1022
    pub definitions: Definitions,
1023

1024 1025
    // Maps the node id of a statement to the expansions of the `macro_rules!`s
    // immediately above the statement (if appropriate).
1026
    macros_at_scope: FxHashMap<NodeId, Vec<Mark>>,
1027

1028
    graph_root: Module<'a>,
1029

1030 1031
    prelude: Option<Module<'a>>,

1032
    trait_item_map: FxHashMap<(Name, DefId), bool /* is static method? */>,
1033

V
Vadim Petrochenkov 已提交
1034 1035
    // Names of fields of an item `DefId` accessible with dot syntax.
    // Used for hints during error reporting.
1036
    field_names: FxHashMap<DefId, Vec<Name>>,
1037

1038 1039 1040 1041
    // All imports known to succeed or fail.
    determined_imports: Vec<&'a ImportDirective<'a>>,

    // All non-determined imports.
1042
    indeterminate_imports: Vec<&'a ImportDirective<'a>>,
1043 1044

    // The module that represents the current item scope.
1045
    current_module: Module<'a>,
1046

J
Jeffrey Seyfried 已提交
1047
    // The current set of local scopes for types and values.
1048
    // FIXME #4948: Reuse ribs to avoid allocation.
J
Jeffrey Seyfried 已提交
1049
    ribs: PerNS<Vec<Rib<'a>>>,
1050

1051
    // The current set of local scopes, for labels.
1052
    label_ribs: Vec<Rib<'a>>,
1053

1054
    // The trait that the current context can refer to.
1055 1056 1057 1058
    current_trait_ref: Option<(DefId, TraitRef)>,

    // The current self type if inside an impl (used for better errors).
    current_self_type: Option<Ty>,
1059

1060
    // The idents for the primitive types.
E
Eduard Burtescu 已提交
1061
    primitive_type_table: PrimitiveTypeTable,
1062

1063
    def_map: DefMap,
1064
    pub freevars: FreevarMap,
1065
    freevars_seen: NodeMap<NodeMap<usize>>,
1066 1067
    pub export_map: ExportMap,
    pub trait_map: TraitMap,
1068

1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
    // A map from nodes to modules, both normal (`mod`) modules and anonymous modules.
    // Anonymous modules are pseudo-modules that are implicitly created around items
    // contained within blocks.
    //
    // For example, if we have this:
    //
    //  fn f() {
    //      fn g() {
    //          ...
    //      }
    //  }
    //
    // There will be an anonymous module created around `g` with the ID of the
    // entry block for `f`.
1083
    module_map: NodeMap<Module<'a>>,
1084
    extern_crate_roots: FxHashMap<(CrateNum, bool /* MacrosOnly? */), Module<'a>>,
1085

1086
    pub make_glob_map: bool,
1087 1088
    // Maps imports to the names of items actually imported (this actually maps
    // all imports, but only glob imports are actually interesting).
1089
    pub glob_map: GlobMap,
1090

1091 1092
    used_imports: FxHashSet<(NodeId, Namespace)>,
    used_crates: FxHashSet<CrateNum>,
1093
    pub maybe_unused_trait_imports: NodeSet,
G
Garming Sam 已提交
1094

1095
    privacy_errors: Vec<PrivacyError<'a>>,
J
Jeffrey Seyfried 已提交
1096
    ambiguity_errors: Vec<AmbiguityError<'a>>,
1097
    disallowed_shadowing: Vec<&'a LegacyBinding<'a>>,
1098 1099

    arenas: &'a ResolverArenas<'a>,
1100
    dummy_binding: &'a NameBinding<'a>,
1101
    use_extern_macros: bool, // true if `#![feature(use_extern_macros)]`
1102

1103
    pub exported_macros: Vec<ast::MacroDef>,
1104
    crate_loader: &'a mut CrateLoader,
1105
    macro_names: FxHashSet<Name>,
1106
    builtin_macros: FxHashMap<Name, &'a NameBinding<'a>>,
1107
    lexical_macro_resolutions: Vec<(Name, &'a Cell<LegacyScope<'a>>)>,
J
Jeffrey Seyfried 已提交
1108 1109
    macro_map: FxHashMap<DefId, Rc<SyntaxExtension>>,
    macro_exports: Vec<Export>,
1110 1111

    // Maps the `Mark` of an expansion to its containing module or block.
1112
    invocations: FxHashMap<Mark, &'a InvocationData<'a>>,
1113 1114 1115

    // Avoid duplicated errors for "name already defined".
    name_already_seen: FxHashMap<Name, Span>,
1116 1117
}

1118
pub struct ResolverArenas<'a> {
1119
    modules: arena::TypedArena<ModuleData<'a>>,
1120
    local_modules: RefCell<Vec<Module<'a>>>,
1121
    name_bindings: arena::TypedArena<NameBinding<'a>>,
1122
    import_directives: arena::TypedArena<ImportDirective<'a>>,
1123
    name_resolutions: arena::TypedArena<RefCell<NameResolution<'a>>>,
1124
    invocation_data: arena::TypedArena<InvocationData<'a>>,
J
Jeffrey Seyfried 已提交
1125
    legacy_bindings: arena::TypedArena<LegacyBinding<'a>>,
1126 1127 1128
}

impl<'a> ResolverArenas<'a> {
1129
    fn alloc_module(&'a self, module: ModuleData<'a>) -> Module<'a> {
1130 1131 1132 1133 1134 1135 1136 1137
        let module = self.modules.alloc(module);
        if module.def_id().map(|def_id| def_id.is_local()).unwrap_or(true) {
            self.local_modules.borrow_mut().push(module);
        }
        module
    }
    fn local_modules(&'a self) -> ::std::cell::Ref<'a, Vec<Module<'a>>> {
        self.local_modules.borrow()
1138 1139 1140 1141
    }
    fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
        self.name_bindings.alloc(name_binding)
    }
1142 1143
    fn alloc_import_directive(&'a self, import_directive: ImportDirective<'a>)
                              -> &'a ImportDirective {
1144 1145
        self.import_directives.alloc(import_directive)
    }
1146 1147 1148
    fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
        self.name_resolutions.alloc(Default::default())
    }
1149 1150 1151
    fn alloc_invocation_data(&'a self, expansion_data: InvocationData<'a>)
                             -> &'a InvocationData<'a> {
        self.invocation_data.alloc(expansion_data)
J
Jeffrey Seyfried 已提交
1152
    }
J
Jeffrey Seyfried 已提交
1153 1154 1155
    fn alloc_legacy_binding(&'a self, binding: LegacyBinding<'a>) -> &'a LegacyBinding<'a> {
        self.legacy_bindings.alloc(binding)
    }
1156 1157
}

1158
impl<'a> ty::NodeIdTree for Resolver<'a> {
1159 1160
    fn is_descendant_of(&self, mut node: NodeId, ancestor: NodeId) -> bool {
        while node != ancestor {
J
Jeffrey Seyfried 已提交
1161
            node = match self.module_map[&node].parent {
J
Jeffrey Seyfried 已提交
1162
                Some(parent) => parent.normal_ancestor_id.unwrap(),
1163
                None => return false,
1164
            }
1165
        }
J
Jeffrey Seyfried 已提交
1166
        true
1167 1168 1169
    }
}

1170
impl<'a> hir::lowering::Resolver for Resolver<'a> {
J
Jeffrey Seyfried 已提交
1171
    fn resolve_hir_path(&mut self, path: &mut hir::Path, is_value: bool) {
1172
        let namespace = if is_value { ValueNS } else { TypeNS };
J
Jeffrey Seyfried 已提交
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
        let hir::Path { ref segments, span, global, ref mut def } = *path;
        let path: Vec<_> = segments.iter().map(|seg| Ident::with_empty_ctxt(seg.name)).collect();
        let scope = if global { PathScope::Global } else { PathScope::Lexical };
        match self.resolve_path(&path, scope, Some(namespace), Some(span)) {
            PathResult::Module(module) => *def = module.def().unwrap(),
            PathResult::NonModule(path_res) if path_res.depth == 0 => *def = path_res.base_def,
            PathResult::NonModule(..) => match self.resolve_path(&path, scope, None, Some(span)) {
                PathResult::Failed(msg, _) => {
                    resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
                }
                _ => {}
            },
            PathResult::Indeterminate => unreachable!(),
            PathResult::Failed(msg, _) => {
                resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
1188 1189 1190 1191
            }
        }
    }

1192 1193 1194 1195
    fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution> {
        self.def_map.get(&id).cloned()
    }

1196 1197
    fn definitions(&mut self) -> &mut Definitions {
        &mut self.definitions
1198 1199 1200
    }
}

1201
impl<'a> Resolver<'a> {
1202
    pub fn new(session: &'a Session,
1203
               krate: &Crate,
1204
               make_glob_map: MakeGlobMap,
1205
               crate_loader: &'a mut CrateLoader,
1206
               arenas: &'a ResolverArenas<'a>)
1207
               -> Resolver<'a> {
1208
        let root_def = Def::Mod(DefId::local(CRATE_DEF_INDEX));
1209
        let graph_root = arenas.alloc_module(ModuleData {
1210 1211
            normal_ancestor_id: Some(CRATE_NODE_ID),
            no_implicit_prelude: attr::contains_name(&krate.attrs, "no_implicit_prelude"),
1212
            ..ModuleData::new(None, ModuleKind::Def(root_def, keywords::Invalid.name()))
1213
        });
1214 1215
        let mut module_map = NodeMap();
        module_map.insert(CRATE_NODE_ID, graph_root);
K
Kevin Butler 已提交
1216

1217 1218 1219
        let mut definitions = Definitions::new();
        DefCollector::new(&mut definitions).collect_root();

1220
        let mut invocations = FxHashMap();
1221 1222
        invocations.insert(Mark::root(),
                           arenas.alloc_invocation_data(InvocationData::root(graph_root)));
1223

K
Kevin Butler 已提交
1224 1225 1226
        Resolver {
            session: session,

1227
            definitions: definitions,
1228
            macros_at_scope: FxHashMap(),
1229

K
Kevin Butler 已提交
1230 1231
            // The outermost module has def ID 0; this is not reflected in the
            // AST.
1232
            graph_root: graph_root,
1233
            prelude: None,
K
Kevin Butler 已提交
1234

1235 1236
            trait_item_map: FxHashMap(),
            field_names: FxHashMap(),
K
Kevin Butler 已提交
1237

1238
            determined_imports: Vec::new(),
1239
            indeterminate_imports: Vec::new(),
K
Kevin Butler 已提交
1240

1241
            current_module: graph_root,
J
Jeffrey Seyfried 已提交
1242 1243 1244
            ribs: PerNS {
                value_ns: vec![Rib::new(ModuleRibKind(graph_root))],
                type_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1245
                macro_ns: None,
J
Jeffrey Seyfried 已提交
1246
            },
1247
            label_ribs: Vec::new(),
K
Kevin Butler 已提交
1248 1249 1250 1251 1252 1253

            current_trait_ref: None,
            current_self_type: None,

            primitive_type_table: PrimitiveTypeTable::new(),

1254
            def_map: NodeMap(),
1255 1256
            freevars: NodeMap(),
            freevars_seen: NodeMap(),
1257 1258
            export_map: NodeMap(),
            trait_map: NodeMap(),
1259
            module_map: module_map,
1260
            extern_crate_roots: FxHashMap(),
K
Kevin Butler 已提交
1261

1262
            make_glob_map: make_glob_map == MakeGlobMap::Yes,
1263
            glob_map: NodeMap(),
G
Garming Sam 已提交
1264

1265 1266
            used_imports: FxHashSet(),
            used_crates: FxHashSet(),
S
Seo Sanghyeon 已提交
1267 1268
            maybe_unused_trait_imports: NodeSet(),

1269
            privacy_errors: Vec::new(),
1270
            ambiguity_errors: Vec::new(),
1271
            disallowed_shadowing: Vec::new(),
1272 1273

            arenas: arenas,
1274 1275
            dummy_binding: arenas.alloc_name_binding(NameBinding {
                kind: NameBindingKind::Def(Def::Err),
1276
                expansion: Mark::root(),
1277 1278 1279
                span: DUMMY_SP,
                vis: ty::Visibility::Public,
            }),
1280
            use_extern_macros: session.features.borrow().use_extern_macros,
1281

1282
            exported_macros: Vec::new(),
1283
            crate_loader: crate_loader,
1284 1285
            macro_names: FxHashSet(),
            builtin_macros: FxHashMap(),
J
Jeffrey Seyfried 已提交
1286
            lexical_macro_resolutions: Vec::new(),
J
Jeffrey Seyfried 已提交
1287 1288
            macro_map: FxHashMap(),
            macro_exports: Vec::new(),
1289
            invocations: invocations,
1290
            name_already_seen: FxHashMap(),
1291 1292 1293
        }
    }

1294
    pub fn arenas() -> ResolverArenas<'a> {
1295 1296
        ResolverArenas {
            modules: arena::TypedArena::new(),
1297
            local_modules: RefCell::new(Vec::new()),
1298
            name_bindings: arena::TypedArena::new(),
1299
            import_directives: arena::TypedArena::new(),
1300
            name_resolutions: arena::TypedArena::new(),
1301
            invocation_data: arena::TypedArena::new(),
J
Jeffrey Seyfried 已提交
1302
            legacy_bindings: arena::TypedArena::new(),
K
Kevin Butler 已提交
1303 1304
        }
    }
1305

J
Jeffrey Seyfried 已提交
1306 1307 1308 1309
    fn per_ns<T, F: FnMut(&mut Self, Namespace) -> T>(&mut self, mut f: F) -> PerNS<T> {
        PerNS {
            type_ns: f(self, TypeNS),
            value_ns: f(self, ValueNS),
1310 1311 1312 1313
            macro_ns: match self.use_extern_macros {
                true => Some(f(self, MacroNS)),
                false => None,
            },
J
Jeffrey Seyfried 已提交
1314 1315 1316
        }
    }

1317 1318
    /// Entry point to crate resolution.
    pub fn resolve_crate(&mut self, krate: &Crate) {
1319
        ImportResolver { resolver: self }.finalize_imports();
1320
        self.current_module = self.graph_root;
1321
        self.finalize_current_module_macro_resolutions();
1322 1323 1324
        visit::walk_crate(self, krate);

        check_unused::check_crate(self, krate);
1325
        self.report_errors();
1326
        self.crate_loader.postprocess(krate);
1327 1328
    }

1329
    fn new_module(&self, parent: Module<'a>, kind: ModuleKind, local: bool) -> Module<'a> {
1330
        self.arenas.alloc_module(ModuleData {
1331 1332
            normal_ancestor_id: if local { self.current_module.normal_ancestor_id } else { None },
            populated: Cell::new(local),
1333
            ..ModuleData::new(Some(parent), kind)
1334
        })
1335 1336
    }

1337
    fn record_use(&mut self, ident: Ident, ns: Namespace, binding: &'a NameBinding<'a>, span: Span)
1338
                  -> bool /* true if an error was reported */ {
1339
        // track extern crates for unused_extern_crate lint
1340
        if let Some(DefId { krate, .. }) = binding.module().and_then(ModuleData::def_id) {
1341 1342 1343
            self.used_crates.insert(krate);
        }

1344 1345 1346 1347
        match binding.kind {
            NameBindingKind::Import { directive, binding, ref used } if !used.get() => {
                used.set(true);
                self.used_imports.insert((directive.id, ns));
1348 1349
                self.add_to_glob_map(directive.id, ident);
                self.record_use(ident, ns, binding, span)
1350 1351 1352
            }
            NameBindingKind::Import { .. } => false,
            NameBindingKind::Ambiguity { b1, b2 } => {
1353
                self.ambiguity_errors.push(AmbiguityError {
1354
                    span: span, name: ident.name, lexical: false, b1: b1, b2: b2,
1355
                });
1356 1357 1358
                true
            }
            _ => false
1359
        }
1360
    }
1361

1362
    fn add_to_glob_map(&mut self, id: NodeId, ident: Ident) {
1363
        if self.make_glob_map {
1364
            self.glob_map.entry(id).or_insert_with(FxHashSet).insert(ident.name);
1365
        }
1366 1367
    }

1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
    /// This resolves the identifier `ident` in the namespace `ns` in the current lexical scope.
    /// More specifically, we proceed up the hierarchy of scopes and return the binding for
    /// `ident` in the first scope that defines it (or None if no scopes define it).
    ///
    /// A block's items are above its local variables in the scope hierarchy, regardless of where
    /// the items are defined in the block. For example,
    /// ```rust
    /// fn f() {
    ///    g(); // Since there are no local variables in scope yet, this resolves to the item.
    ///    let g = || {};
    ///    fn g() {}
    ///    g(); // This resolves to the local variable `g` since it shadows the item.
    /// }
    /// ```
1382
    ///
1383 1384
    /// Invariant: This must only be called during main resolution, not during
    /// import resolution.
1385
    fn resolve_ident_in_lexical_scope(&mut self,
1386
                                      mut ident: Ident,
1387
                                      ns: Namespace,
1388
                                      record_used: Option<Span>)
1389
                                      -> Option<LexicalScopeBinding<'a>> {
1390
        if ns == TypeNS {
1391
            ident = ident.unhygienize();
1392
        }
1393

1394
        // Walk backwards up the ribs in scope.
J
Jeffrey Seyfried 已提交
1395 1396
        for i in (0 .. self.ribs[ns].len()).rev() {
            if let Some(def) = self.ribs[ns][i].bindings.get(&ident).cloned() {
1397
                // The ident resolves to a type parameter or local variable.
J
Jeffrey Seyfried 已提交
1398 1399 1400 1401
                return Some(LexicalScopeBinding::Def(if let Some(span) = record_used {
                    self.adjust_local_def(LocalDef { ribs: Some((ns, i)), def: def }, span)
                } else {
                    def
1402
                }));
1403 1404
            }

J
Jeffrey Seyfried 已提交
1405
            if let ModuleRibKind(module) = self.ribs[ns][i].kind {
1406
                let item = self.resolve_ident_in_module(module, ident, ns, false, record_used);
J
Jeffrey Seyfried 已提交
1407
                if let Ok(binding) = item {
1408 1409
                    // The ident resolves to an item.
                    return Some(LexicalScopeBinding::Item(binding));
1410
                }
1411

J
Jeffrey Seyfried 已提交
1412
                if let ModuleKind::Block(..) = module.kind { // We can see through blocks
1413
                } else if !module.no_implicit_prelude {
J
Jeffrey Seyfried 已提交
1414
                    return self.prelude.and_then(|prelude| {
1415
                        self.resolve_ident_in_module(prelude, ident, ns, false, None).ok()
J
Jeffrey Seyfried 已提交
1416 1417 1418
                    }).map(LexicalScopeBinding::Item)
                } else {
                    return None;
1419
                }
1420
            }
1421

J
Jeffrey Seyfried 已提交
1422
            if let MacroDefinition(mac) = self.ribs[ns][i].kind {
1423 1424
                // If an invocation of this macro created `ident`, give up on `ident`
                // and switch to `ident`'s source from the macro definition.
1425 1426 1427
                let (source_ctxt, source_macro) = ident.ctxt.source();
                if source_macro == mac {
                    ident.ctxt = source_ctxt;
1428 1429
                }
            }
1430
        }
1431

1432 1433 1434
        None
    }

1435 1436 1437 1438 1439 1440 1441 1442
    fn resolve_crate_var(&mut self, mut crate_var_ctxt: SyntaxContext) -> Module<'a> {
        while crate_var_ctxt.source().0 != SyntaxContext::empty() {
            crate_var_ctxt = crate_var_ctxt.source().0;
        }
        let module = self.invocations[&crate_var_ctxt.source().1].module.get();
        if module.is_local() { self.graph_root } else { module }
    }

1443 1444
    // AST resolution
    //
1445
    // We maintain a list of value ribs and type ribs.
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
    //
    // Simultaneously, we keep track of the current position in the module
    // graph in the `current_module` pointer. When we go to resolve a name in
    // the value or type namespaces, we first look through all the ribs and
    // then query the module graph. When we resolve a name in the module
    // namespace, we can skip all the ribs (since nested modules are not
    // allowed within blocks in Rust) and jump straight to the current module
    // graph node.
    //
    // Named implementations are handled separately. When we find a method
    // call, we consult the module node to find all of the implementations in
    // scope. This information is lazily cached in the module node. We then
    // generate a fake "implementation scope" containing all the
    // implementations thus found, for compatibility with old resolve pass.

1461
    fn with_scope<F>(&mut self, id: NodeId, f: F)
C
corentih 已提交
1462
        where F: FnOnce(&mut Resolver)
J
Jorge Aparicio 已提交
1463
    {
1464 1465
        let module = self.module_map.get(&id).cloned(); // clones a reference
        if let Some(module) = module {
1466
            // Move down in the graph.
1467
            let orig_module = replace(&mut self.current_module, module);
J
Jeffrey Seyfried 已提交
1468 1469
            self.ribs[ValueNS].push(Rib::new(ModuleRibKind(module)));
            self.ribs[TypeNS].push(Rib::new(ModuleRibKind(module)));
1470

1471
            self.finalize_current_module_macro_resolutions();
1472
            f(self);
1473

1474
            self.current_module = orig_module;
J
Jeffrey Seyfried 已提交
1475 1476
            self.ribs[ValueNS].pop();
            self.ribs[TypeNS].pop();
1477 1478 1479
        } else {
            f(self);
        }
1480 1481
    }

S
Seo Sanghyeon 已提交
1482 1483
    /// Searches the current set of local scopes for labels.
    /// Stops after meeting a closure.
1484
    fn search_label(&self, mut ident: Ident) -> Option<Def> {
1485 1486 1487 1488 1489
        for rib in self.label_ribs.iter().rev() {
            match rib.kind {
                NormalRibKind => {
                    // Continue
                }
1490 1491 1492
                MacroDefinition(mac) => {
                    // If an invocation of this macro created `ident`, give up on `ident`
                    // and switch to `ident`'s source from the macro definition.
1493 1494 1495
                    let (source_ctxt, source_macro) = ident.ctxt.source();
                    if source_macro == mac {
                        ident.ctxt = source_ctxt;
1496 1497
                    }
                }
1498 1499
                _ => {
                    // Do not resolve labels across function boundary
C
corentih 已提交
1500
                    return None;
1501 1502
                }
            }
1503
            let result = rib.bindings.get(&ident).cloned();
S
Seo Sanghyeon 已提交
1504
            if result.is_some() {
C
corentih 已提交
1505
                return result;
1506 1507 1508 1509 1510
            }
        }
        None
    }

1511
    fn resolve_item(&mut self, item: &Item) {
1512
        let name = item.ident.name;
1513

C
corentih 已提交
1514
        debug!("(resolving item) resolving {}", name);
1515

1516
        match item.node {
1517 1518
            ItemKind::Enum(_, ref generics) |
            ItemKind::Ty(_, ref generics) |
1519
            ItemKind::Struct(_, ref generics) |
1520
            ItemKind::Union(_, ref generics) |
V
Vadim Petrochenkov 已提交
1521
            ItemKind::Fn(.., ref generics, _) => {
1522
                self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind),
1523
                                             |this| visit::walk_item(this, item));
1524 1525
            }

1526
            ItemKind::DefaultImpl(_, ref trait_ref) => {
1527
                self.with_optional_trait_ref(Some(trait_ref), |_, _| {}, None);
1528
            }
V
Vadim Petrochenkov 已提交
1529
            ItemKind::Impl(.., ref generics, ref opt_trait_ref, ref self_type, ref impl_items) =>
1530
                self.resolve_implementation(generics,
1531
                                            opt_trait_ref,
J
Jonas Schievink 已提交
1532
                                            &self_type,
1533
                                            item.id,
1534
                                            impl_items),
1535

1536
            ItemKind::Trait(_, ref generics, ref bounds, ref trait_items) => {
1537
                // Create a new rib for the trait-wide type parameters.
1538
                self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
1539
                    let local_def_id = this.definitions.local_def_id(item.id);
1540
                    this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
1541
                        this.visit_generics(generics);
1542
                        walk_list!(this, visit_ty_param_bound, bounds);
1543 1544

                        for trait_item in trait_items {
1545
                            match trait_item.node {
1546
                                TraitItemKind::Const(_, ref default) => {
1547 1548 1549 1550 1551
                                    // Only impose the restrictions of
                                    // ConstRibKind if there's an actual constant
                                    // expression in a provided default.
                                    if default.is_some() {
                                        this.with_constant_rib(|this| {
1552
                                            visit::walk_trait_item(this, trait_item)
1553 1554
                                        });
                                    } else {
1555
                                        visit::walk_trait_item(this, trait_item)
1556 1557
                                    }
                                }
1558
                                TraitItemKind::Method(ref sig, _) => {
1559 1560
                                    let type_parameters =
                                        HasTypeParameters(&sig.generics,
V
Vadim Petrochenkov 已提交
1561
                                                          MethodRibKind(!sig.decl.has_self()));
1562
                                    this.with_type_parameter_rib(type_parameters, |this| {
1563
                                        visit::walk_trait_item(this, trait_item)
1564
                                    });
1565
                                }
1566
                                TraitItemKind::Type(..) => {
1567
                                    this.with_type_parameter_rib(NoTypeParameters, |this| {
1568
                                        visit::walk_trait_item(this, trait_item)
1569
                                    });
1570
                                }
1571
                                TraitItemKind::Macro(_) => panic!("unexpanded macro in resolve!"),
1572 1573 1574
                            };
                        }
                    });
1575
                });
1576 1577
            }

1578
            ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
1579
                self.with_scope(item.id, |this| {
1580
                    visit::walk_item(this, item);
1581
                });
1582 1583
            }

1584
            ItemKind::Const(..) | ItemKind::Static(..) => {
A
Alex Crichton 已提交
1585
                self.with_constant_rib(|this| {
1586
                    visit::walk_item(this, item);
1587
                });
1588
            }
1589

1590
            ItemKind::Use(ref view_path) => {
1591
                match view_path.node {
1592
                    ast::ViewPathList(ref prefix, ref items) => {
J
Jeffrey Seyfried 已提交
1593 1594
                        let path: Vec<_> =
                            prefix.segments.iter().map(|seg| seg.identifier).collect();
1595 1596
                        // Resolve prefix of an import with empty braces (issue #28388)
                        if items.is_empty() && !prefix.segments.is_empty() {
J
Jeffrey Seyfried 已提交
1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610
                            let (scope, span) = (PathScope::Import, prefix.span);
                            // FIXME(#38012) This should be a module path, not anything in TypeNS.
                            let result =
                                self.resolve_path(&path, scope, Some(TypeNS), Some(span));
                            let (def, msg) = match result {
                                PathResult::Module(module) => (module.def().unwrap(), None),
                                PathResult::NonModule(res) if res.depth == 0 =>
                                    (res.base_def, None),
                                PathResult::NonModule(_) => {
                                    // Resolve a module path for better errors
                                    match self.resolve_path(&path, scope, None, Some(span)) {
                                        PathResult::Failed(msg, _) => (Def::Err, Some(msg)),
                                        _ => unreachable!(),
                                    }
1611
                                }
J
Jeffrey Seyfried 已提交
1612 1613 1614 1615 1616
                                PathResult::Indeterminate => unreachable!(),
                                PathResult::Failed(msg, _) => (Def::Err, Some(msg)),
                            };
                            if let Some(msg) = msg {
                                resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
1617
                            }
J
Jeffrey Seyfried 已提交
1618
                            self.record_def(item.id, PathResolution::new(def));
1619 1620 1621
                        }
                    }
                    _ => {}
W
we 已提交
1622 1623 1624
                }
            }

1625
            ItemKind::ExternCrate(_) => {
1626
                // do nothing, these are just around to be encoded
1627
            }
1628 1629

            ItemKind::Mac(_) => panic!("unexpanded macro in resolve!"),
1630 1631 1632
        }
    }

1633
    fn with_type_parameter_rib<'b, F>(&'b mut self, type_parameters: TypeParameters<'a, 'b>, f: F)
C
corentih 已提交
1634
        where F: FnOnce(&mut Resolver)
J
Jorge Aparicio 已提交
1635
    {
1636
        match type_parameters {
1637
            HasTypeParameters(generics, rib_kind) => {
1638
                let mut function_type_rib = Rib::new(rib_kind);
1639
                let mut seen_bindings = FxHashMap();
1640
                for type_parameter in &generics.ty_params {
1641
                    let name = type_parameter.ident.name;
1642
                    debug!("with_type_parameter_rib: {}", type_parameter.id);
1643

C
Chris Stankus 已提交
1644 1645
                    if seen_bindings.contains_key(&name) {
                        let span = seen_bindings.get(&name).unwrap();
1646 1647
                        resolve_error(self,
                                      type_parameter.span,
C
Chris Stankus 已提交
1648 1649
                                      ResolutionError::NameAlreadyUsedInTypeParameterList(name,
                                                                                          span));
1650
                    }
C
Chris Stankus 已提交
1651
                    seen_bindings.entry(name).or_insert(type_parameter.span);
1652

1653
                    // plain insert (no renaming)
1654
                    let def_id = self.definitions.local_def_id(type_parameter.id);
1655
                    let def = Def::TyParam(def_id);
1656
                    function_type_rib.bindings.insert(Ident::with_empty_ctxt(name), def);
1657
                    self.record_def(type_parameter.id, PathResolution::new(def));
1658
                }
J
Jeffrey Seyfried 已提交
1659
                self.ribs[TypeNS].push(function_type_rib);
1660 1661
            }

B
Brian Anderson 已提交
1662
            NoTypeParameters => {
1663 1664 1665 1666
                // Nothing to do.
            }
        }

A
Alex Crichton 已提交
1667
        f(self);
1668

J
Jeffrey Seyfried 已提交
1669
        if let HasTypeParameters(..) = type_parameters {
J
Jeffrey Seyfried 已提交
1670
            self.ribs[TypeNS].pop();
1671 1672 1673
        }
    }

C
corentih 已提交
1674 1675
    fn with_label_rib<F>(&mut self, f: F)
        where F: FnOnce(&mut Resolver)
J
Jorge Aparicio 已提交
1676
    {
1677
        self.label_ribs.push(Rib::new(NormalRibKind));
A
Alex Crichton 已提交
1678
        f(self);
J
Jeffrey Seyfried 已提交
1679
        self.label_ribs.pop();
1680
    }
1681

C
corentih 已提交
1682 1683
    fn with_constant_rib<F>(&mut self, f: F)
        where F: FnOnce(&mut Resolver)
J
Jorge Aparicio 已提交
1684
    {
J
Jeffrey Seyfried 已提交
1685 1686
        self.ribs[ValueNS].push(Rib::new(ConstantItemRibKind));
        self.ribs[TypeNS].push(Rib::new(ConstantItemRibKind));
A
Alex Crichton 已提交
1687
        f(self);
J
Jeffrey Seyfried 已提交
1688 1689
        self.ribs[TypeNS].pop();
        self.ribs[ValueNS].pop();
1690 1691
    }

F
Felix S. Klock II 已提交
1692
    fn resolve_trait_reference(&mut self,
J
Jeffrey Seyfried 已提交
1693 1694 1695 1696
                               path: &[Ident],
                               global: bool,
                               generics: Option<&Generics>,
                               span: Span)
1697
                               -> PathResolution {
J
Jeffrey Seyfried 已提交
1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714
        let scope = if global { PathScope::Global } else { PathScope::Lexical };
        let def = match self.resolve_path(path, scope, None, Some(span)) {
            PathResult::Module(module) => Some(module.def().unwrap()),
            PathResult::NonModule(..) => return err_path_resolution(),
            PathResult::Failed(msg, false) => {
                resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
                return err_path_resolution();
            }
            _ => match self.resolve_path(path, scope, Some(TypeNS), None) {
                PathResult::NonModule(path_resolution) => Some(path_resolution.base_def),
                _ => None,
            },
        };

        if let Some(def) = def {
            if let Def::Trait(_) = def {
                return PathResolution::new(def);
1715
            }
1716

J
Jeffrey Seyfried 已提交
1717 1718
            let mut err = resolve_struct_error(self, span, {
                ResolutionError::IsNotATrait(&names_to_string(path), def.kind_name())
1719
            });
1720
            if let Some(generics) = generics {
J
Jeffrey Seyfried 已提交
1721
                if let Some(span) = generics.span_for_name(&names_to_string(path)) {
1722 1723 1724
                    err.span_label(span, &"type parameter defined here");
                }
            }
1725 1726

            // If it's a typedef, give a note
J
Jeffrey Seyfried 已提交
1727
            if let Def::TyAlias(..) = def {
1728
                err.note(&format!("type aliases cannot be used for traits"));
1729
            }
1730
            err.emit();
1731
        } else {
1732
            // find possible candidates
J
Jeffrey Seyfried 已提交
1733 1734
            let is_trait = |def| match def { Def::Trait(_) => true, _ => false };
            let candidates = self.lookup_candidates(path.last().unwrap().name, TypeNS, is_trait);
1735

J
Jeffrey Seyfried 已提交
1736 1737
            let path = names_to_string(path);
            resolve_error(self, span, ResolutionError::UndeclaredTraitName(&path, candidates));
1738 1739
        }
        err_path_resolution()
1740 1741
    }

1742 1743
    fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
        where F: FnOnce(&mut Resolver) -> T
J
Jorge Aparicio 已提交
1744
    {
1745 1746 1747 1748 1749 1750 1751
        // Handle nested impls (inside fn bodies)
        let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
        let result = f(self);
        self.current_self_type = previous_value;
        result
    }

1752 1753 1754 1755 1756
    fn with_optional_trait_ref<T, F>(&mut self,
                                     opt_trait_ref: Option<&TraitRef>,
                                     f: F,
                                     generics: Option<&Generics>)
        -> T
1757
        where F: FnOnce(&mut Resolver, Option<DefId>) -> T
J
Jorge Aparicio 已提交
1758
    {
1759
        let mut new_val = None;
1760
        let mut new_id = None;
E
Eduard Burtescu 已提交
1761
        if let Some(trait_ref) = opt_trait_ref {
J
Jeffrey Seyfried 已提交
1762 1763 1764
            let ast::Path { ref segments, span, global } = trait_ref.path;
            let path: Vec<_> = segments.iter().map(|seg| seg.identifier).collect();
            let path_res = self.resolve_trait_reference(&path, global, generics, span);
1765 1766 1767
            assert!(path_res.depth == 0);
            self.record_def(trait_ref.ref_id, path_res);
            if path_res.base_def != Def::Err {
1768 1769
                new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
                new_id = Some(path_res.base_def.def_id());
1770
            }
1771
            visit::walk_trait_ref(self, trait_ref);
1772
        }
1773
        let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
1774
        let result = f(self, new_id);
1775 1776 1777 1778
        self.current_trait_ref = original_trait_ref;
        result
    }

1779 1780 1781 1782 1783 1784
    fn with_self_rib<F>(&mut self, self_def: Def, f: F)
        where F: FnOnce(&mut Resolver)
    {
        let mut self_type_rib = Rib::new(NormalRibKind);

        // plain insert (no renaming, types are not currently hygienic....)
1785
        self_type_rib.bindings.insert(keywords::SelfType.ident(), self_def);
J
Jeffrey Seyfried 已提交
1786
        self.ribs[TypeNS].push(self_type_rib);
1787
        f(self);
J
Jeffrey Seyfried 已提交
1788
        self.ribs[TypeNS].pop();
1789 1790
    }

F
Felix S. Klock II 已提交
1791
    fn resolve_implementation(&mut self,
1792 1793 1794
                              generics: &Generics,
                              opt_trait_reference: &Option<TraitRef>,
                              self_type: &Ty,
1795
                              item_id: NodeId,
1796
                              impl_items: &[ImplItem]) {
1797
        // If applicable, create a rib for the type parameters.
1798
        self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
1799
            // Resolve the type parameters.
1800
            this.visit_generics(generics);
1801

1802
            // Resolve the trait reference, if necessary.
1803
            this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
1804
                // Resolve the self type.
1805
                this.visit_ty(self_type);
1806

1807 1808
                let item_def_id = this.definitions.local_def_id(item_id);
                this.with_self_rib(Def::SelfTy(trait_id, Some(item_def_id)), |this| {
1809 1810
                    this.with_current_self_type(self_type, |this| {
                        for impl_item in impl_items {
1811
                            this.resolve_visibility(&impl_item.vis);
1812
                            match impl_item.node {
1813
                                ImplItemKind::Const(..) => {
1814
                                    // If this is a trait impl, ensure the const
1815
                                    // exists in trait
1816
                                    this.check_trait_item(impl_item.ident.name,
1817 1818
                                                          impl_item.span,
                                        |n, s| ResolutionError::ConstNotMemberOfTrait(n, s));
1819
                                    visit::walk_impl_item(this, impl_item);
1820
                                }
1821
                                ImplItemKind::Method(ref sig, _) => {
1822 1823
                                    // If this is a trait impl, ensure the method
                                    // exists in trait
1824
                                    this.check_trait_item(impl_item.ident.name,
1825 1826
                                                          impl_item.span,
                                        |n, s| ResolutionError::MethodNotMemberOfTrait(n, s));
1827 1828 1829 1830 1831

                                    // We also need a new scope for the method-
                                    // specific type parameters.
                                    let type_parameters =
                                        HasTypeParameters(&sig.generics,
V
Vadim Petrochenkov 已提交
1832
                                                          MethodRibKind(!sig.decl.has_self()));
1833
                                    this.with_type_parameter_rib(type_parameters, |this| {
1834
                                        visit::walk_impl_item(this, impl_item);
1835 1836
                                    });
                                }
1837
                                ImplItemKind::Type(ref ty) => {
1838
                                    // If this is a trait impl, ensure the type
1839
                                    // exists in trait
1840
                                    this.check_trait_item(impl_item.ident.name,
1841 1842
                                                          impl_item.span,
                                        |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
1843

1844 1845
                                    this.visit_ty(ty);
                                }
1846
                                ImplItemKind::Macro(_) => panic!("unexpanded macro in resolve!"),
1847
                            }
1848
                        }
1849
                    });
1850
                });
1851
            }, Some(&generics));
1852
        });
1853 1854
    }

1855
    fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
C
corentih 已提交
1856 1857 1858 1859
        where F: FnOnce(Name, &str) -> ResolutionError
    {
        // If there is a TraitRef in scope for an impl, then the method must be in the
        // trait.
1860
        if let Some((did, ref trait_ref)) = self.current_trait_ref {
1861
            if !self.trait_item_map.contains_key(&(name, did)) {
1862
                let path_str = path_names_to_string(&trait_ref.path, 0);
J
Jonas Schievink 已提交
1863
                resolve_error(self, span, err(name, &path_str));
1864 1865 1866 1867
            }
        }
    }

E
Eduard Burtescu 已提交
1868
    fn resolve_local(&mut self, local: &Local) {
1869
        // Resolve the type.
1870
        walk_list!(self, visit_ty, &local.ty);
1871

1872
        // Resolve the initializer.
1873
        walk_list!(self, visit_expr, &local.init);
1874 1875

        // Resolve the pattern.
1876
        self.resolve_pattern(&local.pat, PatternSource::Let, &mut FxHashMap());
1877 1878
    }

J
John Clements 已提交
1879 1880 1881 1882
    // build a map from pattern identifiers to binding-info's.
    // this is done hygienically. This could arise for a macro
    // that expands into an or-pattern where one 'x' was from the
    // user and one 'x' came from the macro.
E
Eduard Burtescu 已提交
1883
    fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
1884
        let mut binding_map = FxHashMap();
1885 1886 1887 1888 1889 1890 1891 1892

        pat.walk(&mut |pat| {
            if let PatKind::Ident(binding_mode, ident, ref sub_pat) = pat.node {
                if sub_pat.is_some() || match self.def_map.get(&pat.id) {
                    Some(&PathResolution { base_def: Def::Local(..), .. }) => true,
                    _ => false,
                } {
                    let binding_info = BindingInfo { span: ident.span, binding_mode: binding_mode };
1893
                    binding_map.insert(ident.node, binding_info);
1894 1895 1896
                }
            }
            true
1897
        });
1898 1899

        binding_map
1900 1901
    }

J
John Clements 已提交
1902 1903
    // check that all of the arms in an or-pattern have exactly the
    // same set of bindings, with the same binding modes for each.
F
Felix S. Klock II 已提交
1904
    fn check_consistent_bindings(&mut self, arm: &Arm) {
1905
        if arm.pats.is_empty() {
C
corentih 已提交
1906
            return;
1907
        }
J
Jonas Schievink 已提交
1908
        let map_0 = self.binding_mode_map(&arm.pats[0]);
D
Daniel Micay 已提交
1909
        for (i, p) in arm.pats.iter().enumerate() {
J
Jonas Schievink 已提交
1910
            let map_i = self.binding_mode_map(&p);
1911

1912
            for (&key, &binding_0) in &map_0 {
1913
                match map_i.get(&key) {
C
corentih 已提交
1914
                    None => {
1915 1916
                        let error = ResolutionError::VariableNotBoundInPattern(key.name, 1, i + 1);
                        resolve_error(self, p.span, error);
C
corentih 已提交
1917 1918 1919 1920 1921
                    }
                    Some(binding_i) => {
                        if binding_0.binding_mode != binding_i.binding_mode {
                            resolve_error(self,
                                          binding_i.span,
M
Mikhail Modin 已提交
1922 1923 1924 1925
                                          ResolutionError::VariableBoundWithDifferentMode(
                                              key.name,
                                              i + 1,
                                              binding_0.span));
C
corentih 已提交
1926
                        }
1927
                    }
1928 1929 1930
                }
            }

1931
            for (&key, &binding) in &map_i {
1932
                if !map_0.contains_key(&key) {
1933 1934
                    resolve_error(self,
                                  binding.span,
1935
                                  ResolutionError::VariableNotBoundInPattern(key.name, i + 1, 1));
1936 1937 1938
                }
            }
        }
1939 1940
    }

F
Felix S. Klock II 已提交
1941
    fn resolve_arm(&mut self, arm: &Arm) {
J
Jeffrey Seyfried 已提交
1942
        self.ribs[ValueNS].push(Rib::new(NormalRibKind));
1943

1944
        let mut bindings_list = FxHashMap();
1945
        for pattern in &arm.pats {
1946
            self.resolve_pattern(&pattern, PatternSource::Match, &mut bindings_list);
1947 1948
        }

1949 1950 1951 1952
        // This has to happen *after* we determine which
        // pat_idents are variants
        self.check_consistent_bindings(arm);

1953
        walk_list!(self, visit_expr, &arm.guard);
J
Jonas Schievink 已提交
1954
        self.visit_expr(&arm.body);
1955

J
Jeffrey Seyfried 已提交
1956
        self.ribs[ValueNS].pop();
1957 1958
    }

E
Eduard Burtescu 已提交
1959
    fn resolve_block(&mut self, block: &Block) {
1960
        debug!("(resolving block) entering block");
1961
        // Move down in the graph, if there's an anonymous module rooted here.
1962
        let orig_module = self.current_module;
1963
        let anonymous_module = self.module_map.get(&block.id).cloned(); // clones a reference
1964

1965
        let mut num_macro_definition_ribs = 0;
1966 1967
        if let Some(anonymous_module) = anonymous_module {
            debug!("(resolving block) found anonymous module, moving down");
J
Jeffrey Seyfried 已提交
1968 1969
            self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
            self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
1970
            self.current_module = anonymous_module;
1971
            self.finalize_current_module_macro_resolutions();
1972
        } else {
J
Jeffrey Seyfried 已提交
1973
            self.ribs[ValueNS].push(Rib::new(NormalRibKind));
1974 1975 1976
        }

        // Descend into the block.
1977 1978
        for stmt in &block.stmts {
            if let Some(marks) = self.macros_at_scope.remove(&stmt.id) {
1979
                num_macro_definition_ribs += marks.len() as u32;
1980
                for mark in marks {
J
Jeffrey Seyfried 已提交
1981
                    self.ribs[ValueNS].push(Rib::new(MacroDefinition(mark)));
1982
                    self.label_ribs.push(Rib::new(MacroDefinition(mark)));
1983 1984 1985 1986 1987
                }
            }

            self.visit_stmt(stmt);
        }
1988 1989

        // Move back up.
J
Jeffrey Seyfried 已提交
1990
        self.current_module = orig_module;
1991
        for _ in 0 .. num_macro_definition_ribs {
J
Jeffrey Seyfried 已提交
1992
            self.ribs[ValueNS].pop();
1993
            self.label_ribs.pop();
1994
        }
J
Jeffrey Seyfried 已提交
1995
        self.ribs[ValueNS].pop();
J
Jeffrey Seyfried 已提交
1996
        if let Some(_) = anonymous_module {
J
Jeffrey Seyfried 已提交
1997
            self.ribs[TypeNS].pop();
G
Garming Sam 已提交
1998
        }
1999
        debug!("(resolving block) leaving block");
2000 2001
    }

F
Felix S. Klock II 已提交
2002
    fn resolve_type(&mut self, ty: &Ty) {
J
Jeffrey Seyfried 已提交
2003 2004 2005 2006 2007 2008 2009 2010
        if let TyKind::Path(ref maybe_qself, ref path) = ty.node {
            // This is a path in the type namespace. Walk through scopes looking for it.
            if let Some(def) =
                    self.resolve_possibly_assoc_item(ty.id, maybe_qself.as_ref(), path, TypeNS) {
                match def.base_def {
                    Def::Mod(..) if def.depth == 0 => {
                        self.session.span_err(path.span, "expected type, found module");
                        self.record_def(ty.id, err_path_resolution());
2011
                    }
J
Jeffrey Seyfried 已提交
2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030
                    _ => {
                        // Write the result into the def map.
                        debug!("(resolving type) writing resolution for `{}` (id {}) = {:?}",
                               path_names_to_string(path, 0), ty.id, def);
                        self.record_def(ty.id, def);
                   }
                }
            } else {
                self.record_def(ty.id, err_path_resolution());
                // Keep reporting some errors even if they're ignored above.
                let kind = if maybe_qself.is_some() { "associated type" } else { "type name" };
                let is_invalid_self_type_name = {
                    path.segments.len() > 0 &&
                    maybe_qself.is_none() &&
                    path.segments[0].identifier.name == keywords::SelfType.name()
                };

                if is_invalid_self_type_name {
                    resolve_error(self, ty.span, ResolutionError::SelfUsedOutsideImplOrTrait);
2031
                } else {
J
Jeffrey Seyfried 已提交
2032 2033 2034 2035 2036 2037 2038 2039 2040
                    let type_name = path.segments.last().unwrap().identifier.name;
                    let candidates = self.lookup_candidates(type_name, TypeNS, |def| {
                        match def {
                            Def::Trait(_) |
                            Def::Enum(_) |
                            Def::Struct(_) |
                            Def::Union(_) |
                            Def::TyAlias(_) => true,
                            _ => false,
G
Guillaume Gomez 已提交
2041
                        }
J
Jeffrey Seyfried 已提交
2042 2043 2044 2045 2046
                    });

                    let name = &path_names_to_string(path, 0);
                    let error = ResolutionError::UseOfUndeclared(kind, name, candidates);
                    resolve_error(self, ty.span, error);
2047
                }
2048
            }
2049
        }
2050
        // Resolve embedded types.
2051
        visit::walk_ty(self, ty);
2052 2053
    }

2054
    fn fresh_binding(&mut self,
J
Jeffrey Seyfried 已提交
2055
                     ident: &SpannedIdent,
2056 2057 2058
                     pat_id: NodeId,
                     outer_pat_id: NodeId,
                     pat_src: PatternSource,
2059
                     bindings: &mut FxHashMap<Ident, NodeId>)
2060 2061
                     -> PathResolution {
        // Add the binding to the local ribs, if it
2062 2063
        // doesn't already exist in the bindings map. (We
        // must not add it if it's in the bindings map
2064 2065
        // because that breaks the assumptions later
        // passes make about or-patterns.)
2066
        let mut def = Def::Local(self.definitions.local_def_id(pat_id));
2067
        match bindings.get(&ident.node).cloned() {
2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086
            Some(id) if id == outer_pat_id => {
                // `Variant(a, a)`, error
                resolve_error(
                    self,
                    ident.span,
                    ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
                        &ident.node.name.as_str())
                );
            }
            Some(..) if pat_src == PatternSource::FnParam => {
                // `fn f(a: u8, a: u8)`, error
                resolve_error(
                    self,
                    ident.span,
                    ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
                        &ident.node.name.as_str())
                );
            }
            Some(..) if pat_src == PatternSource::Match => {
2087 2088
                // `Variant1(a) | Variant2(a)`, ok
                // Reuse definition from the first `a`.
J
Jeffrey Seyfried 已提交
2089
                def = self.ribs[ValueNS].last_mut().unwrap().bindings[&ident.node];
2090 2091 2092 2093 2094 2095
            }
            Some(..) => {
                span_bug!(ident.span, "two bindings with the same name from \
                                       unexpected pattern source {:?}", pat_src);
            }
            None => {
2096
                // A completely fresh binding, add to the lists if it's valid.
2097
                if ident.node.name != keywords::Invalid.name() {
2098
                    bindings.insert(ident.node, outer_pat_id);
J
Jeffrey Seyfried 已提交
2099
                    self.ribs[ValueNS].last_mut().unwrap().bindings.insert(ident.node, def);
2100
                }
2101
            }
2102
        }
2103

2104
        PathResolution::new(def)
2105
    }
2106

2107
    fn resolve_pattern_path<ExpectedFn>(&mut self,
2108 2109 2110 2111 2112 2113
                                        pat_id: NodeId,
                                        qself: Option<&QSelf>,
                                        path: &Path,
                                        namespace: Namespace,
                                        expected_fn: ExpectedFn,
                                        expected_what: &str)
2114 2115
        where ExpectedFn: FnOnce(Def) -> bool
    {
2116 2117 2118
        let resolution = if let Some(resolution) = self.resolve_possibly_assoc_item(pat_id,
                                                                        qself, path, namespace) {
            if resolution.depth == 0 {
2119
                if expected_fn(resolution.base_def) || resolution.base_def == Def::Err {
2120
                    resolution
2121
                } else {
2122 2123 2124 2125 2126 2127
                    resolve_error(
                        self,
                        path.span,
                        ResolutionError::PatPathUnexpected(expected_what,
                                                           resolution.kind_name(), path)
                    );
2128 2129
                    err_path_resolution()
                }
2130 2131 2132 2133
            } else {
                // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
                // or `<T>::A::B`. If `B` should be resolved in value namespace then
                // it needs to be added to the trait map.
2134 2135 2136 2137
                if namespace == ValueNS {
                    let item_name = path.segments.last().unwrap().identifier.name;
                    let traits = self.get_traits_containing_item(item_name);
                    self.trait_map.insert(pat_id, traits);
2138
                }
2139
                resolution
2140
            }
2141
        } else {
J
Jeffrey Seyfried 已提交
2142 2143
            let error = ResolutionError::PatPathUnresolved(expected_what, path);
            resolve_error(self, path.span, error);
2144
            err_path_resolution()
2145
        };
2146

2147 2148 2149
        self.record_def(pat_id, resolution);
    }

V
Vadim Petrochenkov 已提交
2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161
    fn resolve_struct_path(&mut self, node_id: NodeId, path: &Path) {
        // Resolution logic is equivalent for expressions and patterns,
        // reuse `resolve_pattern_path` for both.
        self.resolve_pattern_path(node_id, None, path, TypeNS, |def| {
            match def {
                Def::Struct(..) | Def::Union(..) | Def::Variant(..) |
                Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => true,
                _ => false,
            }
        }, "struct, variant or union type");
    }

2162 2163 2164 2165 2166
    fn resolve_pattern(&mut self,
                       pat: &Pat,
                       pat_src: PatternSource,
                       // Maps idents to the node ID for the
                       // outermost pattern that binds them.
2167
                       bindings: &mut FxHashMap<Ident, NodeId>) {
2168
        // Visit all direct subpatterns of this pattern.
2169 2170 2171 2172 2173 2174
        let outer_pat_id = pat.id;
        pat.walk(&mut |pat| {
            match pat.node {
                PatKind::Ident(bmode, ref ident, ref opt_pat) => {
                    // First try to resolve the identifier as some existing
                    // entity, then fall back to a fresh binding.
2175
                    let binding = self.resolve_ident_in_lexical_scope(ident.node, ValueNS, None)
2176
                                      .and_then(LexicalScopeBinding::item);
2177
                    let resolution = binding.map(NameBinding::def).and_then(|def| {
2178 2179
                        let always_binding = !pat_src.is_refutable() || opt_pat.is_some() ||
                                             bmode != BindingMode::ByValue(Mutability::Immutable);
2180
                        match def {
2181 2182 2183 2184
                            Def::StructCtor(_, CtorKind::Const) |
                            Def::VariantCtor(_, CtorKind::Const) |
                            Def::Const(..) if !always_binding => {
                                // A unit struct/variant or constant pattern.
2185
                                self.record_use(ident.node, ValueNS, binding.unwrap(), ident.span);
2186
                                Some(PathResolution::new(def))
2187
                            }
2188
                            Def::StructCtor(..) | Def::VariantCtor(..) |
2189
                            Def::Const(..) | Def::Static(..) => {
2190
                                // A fresh binding that shadows something unacceptable.
2191
                                resolve_error(
2192
                                    self,
2193 2194
                                    ident.span,
                                    ResolutionError::BindingShadowsSomethingUnacceptable(
2195
                                        pat_src.descr(), ident.node.name, binding.unwrap())
2196
                                );
2197
                                None
2198
                            }
2199
                            Def::Local(..) | Def::Upvar(..) | Def::Fn(..) | Def::Err => {
2200 2201
                                // These entities are explicitly allowed
                                // to be shadowed by fresh bindings.
2202
                                None
2203 2204 2205
                            }
                            def => {
                                span_bug!(ident.span, "unexpected definition for an \
2206
                                                       identifier in pattern: {:?}", def);
2207
                            }
2208
                        }
2209
                    }).unwrap_or_else(|| {
2210
                        self.fresh_binding(ident, pat.id, outer_pat_id, pat_src, bindings)
2211
                    });
2212 2213

                    self.record_def(pat.id, resolution);
2214 2215
                }

2216
                PatKind::TupleStruct(ref path, ..) => {
2217 2218
                    self.resolve_pattern_path(pat.id, None, path, ValueNS, |def| {
                        match def {
2219 2220
                            Def::StructCtor(_, CtorKind::Fn) |
                            Def::VariantCtor(_, CtorKind::Fn) => true,
2221
                            _ => false,
2222
                        }
2223
                    }, "tuple struct/variant");
2224 2225
                }

2226 2227
                PatKind::Path(ref qself, ref path) => {
                    self.resolve_pattern_path(pat.id, qself.as_ref(), path, ValueNS, |def| {
2228
                        match def {
2229 2230
                            Def::StructCtor(_, CtorKind::Const) |
                            Def::VariantCtor(_, CtorKind::Const) |
2231
                            Def::Const(..) | Def::AssociatedConst(..) => true,
2232
                            _ => false,
2233
                        }
2234
                    }, "unit struct/variant or constant");
2235 2236
                }

V
Vadim Petrochenkov 已提交
2237
                PatKind::Struct(ref path, ..) => {
V
Vadim Petrochenkov 已提交
2238
                    self.resolve_struct_path(pat.id, path);
2239
                }
2240 2241

                _ => {}
2242
            }
2243
            true
2244
        });
2245

2246
        visit::walk_pat(self, pat);
2247 2248
    }

2249 2250 2251
    /// Handles paths that may refer to associated items
    fn resolve_possibly_assoc_item(&mut self,
                                   id: NodeId,
2252
                                   maybe_qself: Option<&QSelf>,
2253
                                   path: &Path,
J
Jeffrey Seyfried 已提交
2254
                                   ns: Namespace)
2255
                                   -> Option<PathResolution> {
J
Jeffrey Seyfried 已提交
2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266
        let ast::Path { ref segments, global, span } = *path;
        let path: Vec<_> = segments.iter().map(|seg| seg.identifier).collect();
        let scope = if global { PathScope::Global } else { PathScope::Lexical };

        if let Some(qself) = maybe_qself {
            if qself.position == 0 {
                // FIXME: Create some fake resolution that can't possibly be a type.
                return Some(PathResolution {
                    base_def: Def::Mod(self.definitions.local_def_id(ast::CRATE_NODE_ID)),
                    depth: path.len(),
                });
2267
            }
J
Jeffrey Seyfried 已提交
2268 2269
            // Make sure the trait is valid.
            self.resolve_trait_reference(&path[..qself.position], global, None, span);
2270 2271
        }

J
Jeffrey Seyfried 已提交
2272 2273 2274 2275 2276 2277 2278
        let result = match self.resolve_path(&path, scope, Some(ns), Some(span)) {
            PathResult::NonModule(path_res) => match path_res.base_def {
                Def::Trait(..) if maybe_qself.is_some() => return None,
                _ => path_res,
            },
            PathResult::Module(module) if !module.is_normal() => {
                PathResolution::new(module.def().unwrap())
V
Cleanup  
Vadim Petrochenkov 已提交
2279
            }
2280 2281 2282 2283 2284 2285
            // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
            // don't report an error right away, but try to fallback to a primitive type.
            // So, we are still able to successfully resolve something like
            //
            // use std::u8; // bring module u8 in scope
            // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
V
Cleanup  
Vadim Petrochenkov 已提交
2286 2287
            //     u8::max_value() // OK, resolves to associated function <u8>::max_value,
            //                     // not to non-existent std::u8::max_value
2288 2289 2290 2291
            // }
            //
            // Such behavior is required for backward compatibility.
            // The same fallback is used when `a` resolves to nothing.
2292 2293 2294
            PathResult::Module(..) | PathResult::Failed(..)
                    if scope == PathScope::Lexical && (ns == TypeNS || path.len() > 1) &&
                       self.primitive_type_table.primitive_types.contains_key(&path[0].name) => {
J
Jeffrey Seyfried 已提交
2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309
                PathResolution {
                    base_def: Def::PrimTy(self.primitive_type_table.primitive_types[&path[0].name]),
                    depth: segments.len() - 1,
                }
            }
            PathResult::Module(module) => PathResolution::new(module.def().unwrap()),
            PathResult::Failed(msg, false) => {
                resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
                err_path_resolution()
            }
            _ => return None,
        };

        if path.len() == 1 || result.base_def == Def::Err {
            return Some(result);
N
Nick Cameron 已提交
2310
        }
2311

J
Jeffrey Seyfried 已提交
2312 2313 2314 2315 2316
        let unqualified_result = {
            match self.resolve_path(&[*path.last().unwrap()], PathScope::Lexical, Some(ns), None) {
                PathResult::NonModule(path_res) => path_res.base_def,
                PathResult::Module(module) => module.def().unwrap(),
                _ => return Some(result),
N
Nick Cameron 已提交
2317
            }
J
Jeffrey Seyfried 已提交
2318 2319 2320 2321
        };
        if result.base_def == unqualified_result && path[0].name != "$crate" {
            let lint = lint::builtin::UNUSED_QUALIFICATIONS;
            self.session.add_lint(lint, id, span, "unnecessary qualification".to_string());
2322
        }
N
Nick Cameron 已提交
2323

J
Jeffrey Seyfried 已提交
2324
        Some(result)
2325 2326
    }

J
Jeffrey Seyfried 已提交
2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363
    fn resolve_path(&mut self,
                    path: &[Ident],
                    scope: PathScope,
                    opt_ns: Option<Namespace>, // `None` indicates a module path
                    record_used: Option<Span>)
                    -> PathResult<'a> {
        let (mut module, allow_self) = match scope {
            PathScope::Lexical => (None, true),
            PathScope::Import => (Some(self.graph_root), true),
            PathScope::Global => (Some(self.graph_root), false),
        };
        let mut allow_super = allow_self;

        for (i, &ident) in path.iter().enumerate() {
            let is_last = i == path.len() - 1;
            let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };

            if i == 0 && allow_self && ns == TypeNS && ident.name == keywords::SelfValue.name() {
                module = Some(self.module_map[&self.current_module.normal_ancestor_id.unwrap()]);
                continue
            } else if i == 0 && allow_self && ns == TypeNS && ident.name == "$crate" {
                module = Some(self.resolve_crate_var(ident.ctxt));
                continue
            } else if allow_super && ns == TypeNS && ident.name == keywords::Super.name() {
                let current_module = if i == 0 { self.current_module } else { module.unwrap() };
                let self_module = self.module_map[&current_module.normal_ancestor_id.unwrap()];
                if let Some(parent) = self_module.parent {
                    module = Some(self.module_map[&parent.normal_ancestor_id.unwrap()]);
                    continue
                } else {
                    let msg = "There are too many initial `super`s.".to_string();
                    return PathResult::Failed(msg, false);
                }
            }
            allow_super = false;

            let binding = if let Some(module) = module {
2364
                self.resolve_ident_in_module(module, ident, ns, false, record_used)
2365
            } else if opt_ns == Some(MacroNS) {
2366
                self.resolve_lexical_macro_path_segment(ident, ns, record_used)
J
Jeffrey Seyfried 已提交
2367 2368 2369
            } else {
                match self.resolve_ident_in_lexical_scope(ident, ns, record_used) {
                    Some(LexicalScopeBinding::Item(binding)) => Ok(binding),
2370 2371
                    Some(LexicalScopeBinding::Def(def))
                            if opt_ns == Some(TypeNS) || opt_ns == Some(ValueNS) => {
J
Jeffrey Seyfried 已提交
2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382
                        return PathResult::NonModule(PathResolution {
                            base_def: def,
                            depth: path.len() - 1,
                        });
                    }
                    _ => Err(if record_used.is_some() { Determined } else { Undetermined }),
                }
            };

            match binding {
                Ok(binding) => {
J
Jeffrey Seyfried 已提交
2383
                    if let Some(next_module) = binding.module() {
J
Jeffrey Seyfried 已提交
2384 2385 2386
                        module = Some(next_module);
                    } else if binding.def() == Def::Err {
                        return PathResult::NonModule(err_path_resolution());
2387
                    } else if opt_ns.is_some() && !(opt_ns == Some(MacroNS) && !is_last) {
J
Jeffrey Seyfried 已提交
2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405
                        return PathResult::NonModule(PathResolution {
                            base_def: binding.def(),
                            depth: path.len() - i - 1,
                        });
                    } else {
                        return PathResult::Failed(format!("Not a module `{}`", ident), is_last);
                    }
                }
                Err(Undetermined) => return PathResult::Indeterminate,
                Err(Determined) => {
                    if let Some(module) = module {
                        if opt_ns.is_some() && !module.is_normal() {
                            return PathResult::NonModule(PathResolution {
                                base_def: module.def().unwrap(),
                                depth: path.len() - i,
                            });
                        }
                    }
2406
                    let msg = if module.and_then(ModuleData::def) == self.graph_root.def() {
J
Jeffrey Seyfried 已提交
2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423
                        let is_mod = |def| match def { Def::Mod(..) => true, _ => false };
                        let mut candidates =
                            self.lookup_candidates(ident.name, TypeNS, is_mod).candidates;
                        candidates.sort_by_key(|path| (path.segments.len(), path.to_string()));
                        if let Some(candidate) = candidates.get(0) {
                            format!("Did you mean `{}`?", candidate)
                        } else {
                            format!("Maybe a missing `extern crate {};`?", ident)
                        }
                    } else if i == 0 {
                        format!("Use of undeclared type or module `{}`", ident)
                    } else {
                        format!("Could not find `{}` in `{}`", ident, path[i - 1])
                    };
                    return PathResult::Failed(msg, is_last);
                }
            }
2424 2425
        }

J
Jeffrey Seyfried 已提交
2426
        PathResult::Module(module.unwrap())
2427 2428 2429
    }

    // Resolve a local definition, potentially adjusting for closures.
2430
    fn adjust_local_def(&mut self, local_def: LocalDef, span: Span) -> Def {
2431
        let ribs = match local_def.ribs {
J
Jeffrey Seyfried 已提交
2432 2433
            Some((ns, i)) => &self.ribs[ns][i + 1..],
            None => &[] as &[_],
2434 2435 2436
        };
        let mut def = local_def.def;
        match def {
2437
            Def::Upvar(..) => {
2438
                span_bug!(span, "unexpected {:?} in bindings", def)
2439
            }
2440
            Def::Local(def_id) => {
2441 2442
                for rib in ribs {
                    match rib.kind {
2443
                        NormalRibKind | ModuleRibKind(..) | MacroDefinition(..) => {
2444 2445 2446 2447
                            // Nothing to do. Continue.
                        }
                        ClosureRibKind(function_id) => {
                            let prev_def = def;
2448
                            let node_id = self.definitions.as_local_node_id(def_id).unwrap();
2449

C
corentih 已提交
2450 2451 2452
                            let seen = self.freevars_seen
                                           .entry(function_id)
                                           .or_insert_with(|| NodeMap());
2453
                            if let Some(&index) = seen.get(&node_id) {
2454
                                def = Def::Upvar(def_id, index, function_id);
2455 2456
                                continue;
                            }
C
corentih 已提交
2457 2458 2459
                            let vec = self.freevars
                                          .entry(function_id)
                                          .or_insert_with(|| vec![]);
2460
                            let depth = vec.len();
C
corentih 已提交
2461 2462 2463 2464
                            vec.push(Freevar {
                                def: prev_def,
                                span: span,
                            });
2465

2466
                            def = Def::Upvar(def_id, depth, function_id);
2467 2468
                            seen.insert(node_id, depth);
                        }
2469
                        ItemRibKind | MethodRibKind(_) => {
2470 2471 2472
                            // This was an attempt to access an upvar inside a
                            // named function item. This is not allowed, so we
                            // report an error.
C
corentih 已提交
2473 2474 2475
                            resolve_error(self,
                                          span,
                                          ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
2476
                            return Def::Err;
2477 2478 2479
                        }
                        ConstantItemRibKind => {
                            // Still doesn't deal with upvars
C
corentih 已提交
2480 2481 2482
                            resolve_error(self,
                                          span,
                                          ResolutionError::AttemptToUseNonConstantValueInConstant);
2483
                            return Def::Err;
2484 2485 2486 2487
                        }
                    }
                }
            }
2488
            Def::TyParam(..) | Def::SelfTy(..) => {
2489 2490
                for rib in ribs {
                    match rib.kind {
2491
                        NormalRibKind | MethodRibKind(_) | ClosureRibKind(..) |
2492
                        ModuleRibKind(..) | MacroDefinition(..) => {
2493 2494 2495 2496 2497 2498 2499 2500 2501
                            // Nothing to do. Continue.
                        }
                        ItemRibKind => {
                            // This was an attempt to use a type parameter outside
                            // its scope.

                            resolve_error(self,
                                          span,
                                          ResolutionError::TypeParametersFromOuterFunction);
2502
                            return Def::Err;
2503 2504 2505 2506
                        }
                        ConstantItemRibKind => {
                            // see #9186
                            resolve_error(self, span, ResolutionError::OuterTypeParameterContext);
2507
                            return Def::Err;
2508 2509 2510 2511 2512 2513
                        }
                    }
                }
            }
            _ => {}
        }
2514
        return def;
2515 2516
    }

2517 2518
    // Calls `f` with a `Resolver` whose current lexical scope is `module`'s lexical scope,
    // i.e. the module's items and the prelude (unless the module is `#[no_implicit_prelude]`).
J
Jeffrey Seyfried 已提交
2519
    // FIXME #34673: This needs testing.
2520 2521 2522 2523
    pub fn with_module_lexical_scope<T, F>(&mut self, module: Module<'a>, f: F) -> T
        where F: FnOnce(&mut Resolver<'a>) -> T,
    {
        self.with_empty_ribs(|this| {
J
Jeffrey Seyfried 已提交
2524 2525
            this.ribs[ValueNS].push(Rib::new(ModuleRibKind(module)));
            this.ribs[TypeNS].push(Rib::new(ModuleRibKind(module)));
2526 2527 2528 2529 2530 2531 2532
            f(this)
        })
    }

    fn with_empty_ribs<T, F>(&mut self, f: F) -> T
        where F: FnOnce(&mut Resolver<'a>) -> T,
    {
J
Jeffrey Seyfried 已提交
2533
        let ribs = replace(&mut self.ribs, PerNS::<Vec<Rib>>::default());
2534 2535 2536
        let label_ribs = replace(&mut self.label_ribs, Vec::new());

        let result = f(self);
J
Jeffrey Seyfried 已提交
2537
        self.ribs = ribs;
2538 2539 2540 2541
        self.label_ribs = label_ribs;
        result
    }

2542
    fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
2543
        fn extract_node_id(t: &Ty) -> Option<NodeId> {
2544
            match t.node {
2545 2546
                TyKind::Path(None, _) => Some(t.id),
                TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
2547 2548 2549 2550 2551 2552 2553
                // This doesn't handle the remaining `Ty` variants as they are not
                // that commonly the self_type, it might be interesting to provide
                // support for those in future.
                _ => None,
            }
        }

2554
        if let Some(node_id) = self.current_self_type.as_ref().and_then(extract_node_id) {
2555
            // Look for a field with the same name in the current self_type.
2556 2557
            if let Some(resolution) = self.def_map.get(&node_id) {
                match resolution.base_def {
2558
                    Def::Struct(did) | Def::Union(did) if resolution.depth == 0 => {
V
Vadim Petrochenkov 已提交
2559 2560
                        if let Some(field_names) = self.field_names.get(&did) {
                            if field_names.iter().any(|&field_name| name == field_name) {
2561 2562
                                return Field;
                            }
2563
                        }
2564
                    }
2565 2566
                    _ => {}
                }
2567
            }
2568 2569 2570
        }

        // Look for a method in the current trait.
2571
        if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
2572 2573
            if let Some(&is_static_method) = self.trait_item_map.get(&(name, trait_did)) {
                if is_static_method {
2574
                    return TraitMethod(path_names_to_string(&trait_ref.path, 0));
2575 2576
                } else {
                    return TraitItem;
2577 2578 2579 2580 2581 2582 2583
                }
            }
        }

        NoSuggestion
    }

2584
    fn find_best_match(&mut self, name: &str) -> SuggestionType {
J
Jeffrey Seyfried 已提交
2585
        if let Some(macro_name) = self.macro_names.iter().find(|&n| n == &name) {
2586 2587 2588
            return SuggestionType::Macro(format!("{}!", macro_name));
        }

J
Jeffrey Seyfried 已提交
2589
        let names = self.ribs[ValueNS]
2590 2591
                    .iter()
                    .rev()
2592
                    .flat_map(|rib| rib.bindings.keys().map(|ident| &ident.name));
2593

2594
        if let Some(found) = find_best_match_for_name(names, name, None) {
2595
            if found != name {
2596
                return SuggestionType::Function(found);
2597
            }
2598
        } SuggestionType::NotFound
2599 2600
    }

J
Jeffrey Seyfried 已提交
2601
    fn resolve_labeled_block(&mut self, label: Option<SpannedIdent>, id: NodeId, block: &Block) {
2602
        if let Some(label) = label {
2603
            let def = Def::Label(id);
2604
            self.with_label_rib(|this| {
J
Jeffrey Seyfried 已提交
2605
                this.label_ribs.last_mut().unwrap().bindings.insert(label.node, def);
2606 2607 2608 2609 2610 2611 2612
                this.visit_block(block);
            });
        } else {
            self.visit_block(block);
        }
    }

2613
    fn resolve_expr(&mut self, expr: &Expr, parent: Option<&Expr>) {
P
Patrick Walton 已提交
2614 2615
        // First, record candidate traits for this expression if it could
        // result in the invocation of a method call.
2616 2617 2618

        self.record_candidate_traits_for_expr_if_necessary(expr);

2619
        // Next, resolve the node.
2620
        match expr.node {
2621
            ExprKind::Path(ref maybe_qself, ref path) => {
2622 2623
                // This is a local path in the value namespace. Walk through
                // scopes looking for it.
2624 2625
                if let Some(path_res) = self.resolve_possibly_assoc_item(expr.id,
                                                            maybe_qself.as_ref(), path, ValueNS) {
2626
                    // Check if struct variant
2627 2628 2629
                    let is_struct_variant = match path_res.base_def {
                        Def::VariantCtor(_, CtorKind::Fictive) => true,
                        _ => false,
2630 2631
                    };
                    if is_struct_variant {
2632
                        let path_name = path_names_to_string(path, 0);
2633

N
Nick Cameron 已提交
2634 2635
                        let mut err = resolve_struct_error(self,
                                        expr.span,
J
Jonas Schievink 已提交
2636
                                        ResolutionError::StructVariantUsedAsFunction(&path_name));
2637

C
corentih 已提交
2638
                        let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
2639
                                          path_name);
J
Jeffrey Seyfried 已提交
2640
                        err.help(&msg);
N
Nick Cameron 已提交
2641
                        err.emit();
2642
                        self.record_def(expr.id, err_path_resolution());
2643
                    } else {
2644
                        // Write the result into the def map.
2645
                        debug!("(resolving expr) resolved `{}`",
2646
                               path_names_to_string(path, 0));
2647

2648 2649
                        // Partial resolutions will need the set of traits in scope,
                        // so they can be completed during typeck.
2650
                        if path_res.depth != 0 {
2651
                            let method_name = path.segments.last().unwrap().identifier.name;
2652
                            let traits = self.get_traits_containing_item(method_name);
2653 2654 2655
                            self.trait_map.insert(expr.id, traits);
                        }

2656
                        self.record_def(expr.id, path_res);
2657
                    }
2658 2659
                } else {
                    // Be helpful if the name refers to a struct
2660
                    let path_name = path_names_to_string(path, 0);
J
Jeffrey Seyfried 已提交
2661 2662 2663 2664 2665 2666 2667
                    let ast::Path { ref segments, global, .. } = *path;
                    let path: Vec<_> = segments.iter().map(|seg| seg.identifier).collect();
                    let scope = if global { PathScope::Global } else { PathScope::Lexical };
                    let type_res = match self.resolve_path(&path, scope, Some(TypeNS), None) {
                        PathResult::NonModule(type_res) => Some(type_res),
                        _ => None,
                    };
2668 2669

                    self.record_def(expr.id, err_path_resolution());
2670

2671
                    if let Some(Def::Struct(..)) = type_res.map(|r| r.base_def) {
J
Jeffrey Seyfried 已提交
2672 2673
                        let error_variant =
                            ResolutionError::StructVariantUsedAsFunction(&path_name);
2674 2675 2676 2677 2678
                        let mut err = resolve_struct_error(self, expr.span, error_variant);

                        let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
                                          path_name);

J
Jeffrey Seyfried 已提交
2679
                        err.help(&msg);
2680 2681 2682
                        err.emit();
                    } else {
                        // Keep reporting some errors even if they're ignored above.
J
Jeffrey Seyfried 已提交
2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695
                        let mut method_scope = false;
                        let mut is_static = false;
                        self.ribs[ValueNS].iter().rev().all(|rib| {
                            method_scope = match rib.kind {
                                MethodRibKind(is_static_) => {
                                    is_static = is_static_;
                                    true
                                }
                                ItemRibKind | ConstantItemRibKind => false,
                                _ => return true, // Keep advancing
                            };
                            false // Stop advancing
                        });
2696

J
Jeffrey Seyfried 已提交
2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713
                        if method_scope && keywords::SelfValue.name() == &*path_name {
                            let error = ResolutionError::SelfNotAvailableInStaticMethod;
                            resolve_error(self, expr.span, error);
                        } else {
                            let fallback =
                                self.find_fallback_in_self_type(path.last().unwrap().name);
                            let (mut msg, is_field) = match fallback {
                                NoSuggestion => {
                                    // limit search to 5 to reduce the number
                                    // of stupid suggestions
                                    (match self.find_best_match(&path_name) {
                                        SuggestionType::Macro(s) => {
                                            format!("the macro `{}`", s)
                                        }
                                        SuggestionType::Function(s) => format!("`{}`", s),
                                        SuggestionType::NotFound => "".to_string(),
                                    }, false)
2714
                                }
J
Jeffrey Seyfried 已提交
2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725
                                Field => {
                                    (if is_static && method_scope {
                                        "".to_string()
                                    } else {
                                        format!("`self.{}`", path_name)
                                    }, true)
                                }
                                TraitItem => (format!("to call `self.{}`", path_name), false),
                                TraitMethod(path_str) =>
                                    (format!("to call `{}::{}`", path_str, path_name), false),
                            };
2726

J
Jeffrey Seyfried 已提交
2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737
                            let mut context = UnresolvedNameContext::Other;
                            let mut def = Def::Err;
                            if !msg.is_empty() {
                                msg = format!("did you mean {}?", msg);
                            } else {
                                // we display a help message if this is a module
                                if let PathResult::Module(module) =
                                        self.resolve_path(&path, scope, None, None) {
                                    def = module.def().unwrap();
                                    context = UnresolvedNameContext::PathIsMod(parent);
                                }
2738
                            }
J
Jeffrey Seyfried 已提交
2739 2740 2741 2742 2743 2744 2745 2746 2747 2748

                            let error = ResolutionError::UnresolvedName {
                                path: &path_name,
                                message: &msg,
                                context: context,
                                is_static_method: method_scope && is_static,
                                is_field: is_field,
                                def: def,
                            };
                            resolve_error(self, expr.span, error);
V
Vincent Belliard 已提交
2749
                        }
2750 2751 2752
                    }
                }

2753
                visit::walk_expr(self, expr);
2754 2755
            }

V
Vadim Petrochenkov 已提交
2756
            ExprKind::Struct(ref path, ..) => {
V
Vadim Petrochenkov 已提交
2757
                self.resolve_struct_path(expr.id, path);
2758

2759
                visit::walk_expr(self, expr);
2760 2761
            }

2762
            ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
2763
                match self.search_label(label.node) {
2764
                    None => {
2765
                        self.record_def(expr.id, err_path_resolution());
2766
                        resolve_error(self,
2767
                                      label.span,
2768
                                      ResolutionError::UndeclaredLabel(&label.node.name.as_str()));
2769
                    }
2770
                    Some(def @ Def::Label(_)) => {
2771
                        // Since this def is a label, it is never read.
2772
                        self.record_def(expr.id, PathResolution::new(def));
2773 2774
                    }
                    Some(_) => {
2775
                        span_bug!(expr.span, "label wasn't mapped to a label def!");
2776 2777
                    }
                }
2778 2779 2780

                // visit `break` argument if any
                visit::walk_expr(self, expr);
2781
            }
2782 2783 2784 2785

            ExprKind::IfLet(ref pattern, ref subexpression, ref if_block, ref optional_else) => {
                self.visit_expr(subexpression);

J
Jeffrey Seyfried 已提交
2786
                self.ribs[ValueNS].push(Rib::new(NormalRibKind));
2787
                self.resolve_pattern(pattern, PatternSource::IfLet, &mut FxHashMap());
2788
                self.visit_block(if_block);
J
Jeffrey Seyfried 已提交
2789
                self.ribs[ValueNS].pop();
2790 2791 2792 2793

                optional_else.as_ref().map(|expr| self.visit_expr(expr));
            }

J
Jeffrey Seyfried 已提交
2794 2795 2796 2797 2798 2799 2800
            ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),

            ExprKind::While(ref subexpression, ref block, label) => {
                self.visit_expr(subexpression);
                self.resolve_labeled_block(label, expr.id, &block);
            }

2801 2802
            ExprKind::WhileLet(ref pattern, ref subexpression, ref block, label) => {
                self.visit_expr(subexpression);
J
Jeffrey Seyfried 已提交
2803
                self.ribs[ValueNS].push(Rib::new(NormalRibKind));
2804
                self.resolve_pattern(pattern, PatternSource::WhileLet, &mut FxHashMap());
2805

J
Jeffrey Seyfried 已提交
2806
                self.resolve_labeled_block(label, expr.id, block);
2807

J
Jeffrey Seyfried 已提交
2808
                self.ribs[ValueNS].pop();
2809 2810 2811 2812
            }

            ExprKind::ForLoop(ref pattern, ref subexpression, ref block, label) => {
                self.visit_expr(subexpression);
J
Jeffrey Seyfried 已提交
2813
                self.ribs[ValueNS].push(Rib::new(NormalRibKind));
2814
                self.resolve_pattern(pattern, PatternSource::For, &mut FxHashMap());
2815

J
Jeffrey Seyfried 已提交
2816
                self.resolve_labeled_block(label, expr.id, block);
2817

J
Jeffrey Seyfried 已提交
2818
                self.ribs[ValueNS].pop();
2819 2820 2821
            }

            ExprKind::Field(ref subexpression, _) => {
2822 2823
                self.resolve_expr(subexpression, Some(expr));
            }
2824
            ExprKind::MethodCall(_, ref types, ref arguments) => {
2825 2826 2827 2828 2829 2830 2831 2832 2833
                let mut arguments = arguments.iter();
                self.resolve_expr(arguments.next().unwrap(), Some(expr));
                for argument in arguments {
                    self.resolve_expr(argument, None);
                }
                for ty in types.iter() {
                    self.visit_ty(ty);
                }
            }
2834

B
Brian Anderson 已提交
2835
            _ => {
2836
                visit::walk_expr(self, expr);
2837 2838 2839 2840
            }
        }
    }

E
Eduard Burtescu 已提交
2841
    fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
2842
        match expr.node {
2843
            ExprKind::Field(_, name) => {
2844 2845 2846 2847
                // FIXME(#6890): Even though you can't treat a method like a
                // field, we need to add any trait methods we find that match
                // the field name so that we can do some nice error reporting
                // later on in typeck.
2848
                let traits = self.get_traits_containing_item(name.node.name);
2849
                self.trait_map.insert(expr.id, traits);
2850
            }
V
Vadim Petrochenkov 已提交
2851
            ExprKind::MethodCall(name, ..) => {
C
corentih 已提交
2852
                debug!("(recording candidate traits for expr) recording traits for {}",
2853
                       expr.id);
2854
                let traits = self.get_traits_containing_item(name.node.name);
2855
                self.trait_map.insert(expr.id, traits);
2856
            }
2857
            _ => {
2858 2859 2860 2861 2862
                // Nothing to do.
            }
        }
    }

S
Seo Sanghyeon 已提交
2863
    fn get_traits_containing_item(&mut self, name: Name) -> Vec<TraitCandidate> {
C
corentih 已提交
2864
        debug!("(getting traits containing item) looking for '{}'", name);
E
Eduard Burtescu 已提交
2865

S
Seo Sanghyeon 已提交
2866 2867 2868 2869
        fn add_trait_info(found_traits: &mut Vec<TraitCandidate>,
                          trait_def_id: DefId,
                          import_id: Option<NodeId>,
                          name: Name) {
2870
            debug!("(adding trait info) found trait {:?} for method '{}'",
C
corentih 已提交
2871 2872
                   trait_def_id,
                   name);
S
Seo Sanghyeon 已提交
2873 2874 2875 2876
            found_traits.push(TraitCandidate {
                def_id: trait_def_id,
                import_id: import_id,
            });
E
Eduard Burtescu 已提交
2877
        }
2878

2879
        let mut found_traits = Vec::new();
J
Jeffrey Seyfried 已提交
2880 2881 2882
        // Look for the current trait.
        if let Some((trait_def_id, _)) = self.current_trait_ref {
            if self.trait_item_map.contains_key(&(name, trait_def_id)) {
S
Seo Sanghyeon 已提交
2883
                add_trait_info(&mut found_traits, trait_def_id, None, name);
E
Eduard Burtescu 已提交
2884
            }
J
Jeffrey Seyfried 已提交
2885
        }
2886

J
Jeffrey Seyfried 已提交
2887 2888
        let mut search_module = self.current_module;
        loop {
E
Eduard Burtescu 已提交
2889
            // Look for trait children.
2890
            let mut search_in_module = |this: &mut Self, module: Module<'a>| {
J
Jeffrey Seyfried 已提交
2891 2892 2893
                let mut traits = module.traits.borrow_mut();
                if traits.is_none() {
                    let mut collected_traits = Vec::new();
2894
                    module.for_each_child(|name, ns, binding| {
J
Jeffrey Seyfried 已提交
2895
                        if ns != TypeNS { return }
2896
                        if let Def::Trait(_) = binding.def() {
2897
                            collected_traits.push((name, binding));
J
Jeffrey Seyfried 已提交
2898 2899 2900
                        }
                    });
                    *traits = Some(collected_traits.into_boxed_slice());
2901
                }
J
Jeffrey Seyfried 已提交
2902

2903
                for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
2904
                    let trait_def_id = binding.def().def_id();
2905
                    if this.trait_item_map.contains_key(&(name, trait_def_id)) {
S
Seo Sanghyeon 已提交
2906 2907 2908
                        let mut import_id = None;
                        if let NameBindingKind::Import { directive, .. } = binding.kind {
                            let id = directive.id;
2909
                            this.maybe_unused_trait_imports.insert(id);
2910
                            this.add_to_glob_map(id, trait_name);
S
Seo Sanghyeon 已提交
2911 2912 2913
                            import_id = Some(id);
                        }
                        add_trait_info(&mut found_traits, trait_def_id, import_id, name);
J
Jeffrey Seyfried 已提交
2914 2915 2916
                    }
                }
            };
2917
            search_in_module(self, search_module);
2918

J
Jeffrey Seyfried 已提交
2919 2920 2921
            if let ModuleKind::Block(..) = search_module.kind {
                search_module = search_module.parent.unwrap();
            } else {
2922
                if !search_module.no_implicit_prelude {
J
Jeffrey Seyfried 已提交
2923
                    self.prelude.map(|prelude| search_in_module(self, prelude));
2924
                }
J
Jeffrey Seyfried 已提交
2925
                break;
E
Eduard Burtescu 已提交
2926
            }
2927 2928
        }

E
Eduard Burtescu 已提交
2929
        found_traits
2930 2931
    }

2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951
    /// When name resolution fails, this method can be used to look up candidate
    /// entities with the expected name. It allows filtering them using the
    /// supplied predicate (which should be used to only accept the types of
    /// definitions expected e.g. traits). The lookup spans across all crates.
    ///
    /// NOTE: The method does not look into imports, but this is not a problem,
    /// since we report the definitions (thus, the de-aliased imports).
    fn lookup_candidates<FilterFn>(&mut self,
                                   lookup_name: Name,
                                   namespace: Namespace,
                                   filter_fn: FilterFn) -> SuggestedCandidates
        where FilterFn: Fn(Def) -> bool {

        let mut lookup_results = Vec::new();
        let mut worklist = Vec::new();
        worklist.push((self.graph_root, Vec::new(), false));

        while let Some((in_module,
                        path_segments,
                        in_module_is_extern)) = worklist.pop() {
2952
            self.populate_module_if_necessary(in_module);
2953

2954
            in_module.for_each_child(|ident, ns, name_binding| {
2955 2956

                // avoid imports entirely
2957
                if name_binding.is_import() && !name_binding.is_extern_crate() { return; }
2958 2959

                // collect results based on the filter function
2960
                if ident.name == lookup_name && ns == namespace {
2961
                    if filter_fn(name_binding.def()) {
2962 2963 2964 2965 2966 2967
                        // create the path
                        let params = PathParameters::none();
                        let segment = PathSegment {
                            identifier: ident,
                            parameters: params,
                        };
2968
                        let span = name_binding.span;
2969 2970 2971 2972
                        let mut segms = path_segments.clone();
                        segms.push(segment);
                        let path = Path {
                            span: span,
J
Jeffrey Seyfried 已提交
2973
                            global: false,
2974 2975 2976 2977 2978 2979 2980 2981 2982
                            segments: segms,
                        };
                        // the entity is accessible in the following cases:
                        // 1. if it's defined in the same crate, it's always
                        // accessible (since private entities can be made public)
                        // 2. if it's defined in another crate, it's accessible
                        // only if both the module is public and the entity is
                        // declared as public (due to pruning, we don't explore
                        // outside crate private modules => no need to check this)
2983
                        if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
2984 2985 2986 2987 2988 2989
                            lookup_results.push(path);
                        }
                    }
                }

                // collect submodules to explore
J
Jeffrey Seyfried 已提交
2990
                if let Some(module) = name_binding.module() {
2991
                    // form the path
2992 2993
                    let mut path_segments = path_segments.clone();
                    path_segments.push(PathSegment {
2994
                        identifier: ident,
2995 2996
                        parameters: PathParameters::none(),
                    });
2997

2998
                    if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
2999
                        // add the module to the lookup
3000
                        let is_extern = in_module_is_extern || name_binding.is_extern_crate();
J
Jeffrey Seyfried 已提交
3001
                        if !worklist.iter().any(|&(m, ..)| m.def() == module.def()) {
3002 3003
                            worklist.push((module, path_segments, is_extern));
                        }
3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014
                    }
                }
            })
        }

        SuggestedCandidates {
            name: lookup_name.as_str().to_string(),
            candidates: lookup_results,
        }
    }

3015 3016
    fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
        debug!("(recording def) recording {:?} for {}", resolution, node_id);
3017
        if let Some(prev_res) = self.def_map.insert(node_id, resolution) {
3018
            panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution);
3019
        }
3020 3021
    }

3022
    fn resolve_visibility(&mut self, vis: &ast::Visibility) -> ty::Visibility {
J
Jeffrey Seyfried 已提交
3023
        let (segments, span, id) = match *vis {
3024 3025
            ast::Visibility::Public => return ty::Visibility::Public,
            ast::Visibility::Crate(_) => return ty::Visibility::Restricted(ast::CRATE_NODE_ID),
J
Jeffrey Seyfried 已提交
3026
            ast::Visibility::Restricted { ref path, id } => (&path.segments, path.span, id),
3027
            ast::Visibility::Inherited => {
J
Jeffrey Seyfried 已提交
3028
                return ty::Visibility::Restricted(self.current_module.normal_ancestor_id.unwrap());
3029
            }
3030 3031
        };

J
Jeffrey Seyfried 已提交
3032
        let path: Vec<_> = segments.iter().map(|seg| seg.identifier).collect();
3033
        let mut path_resolution = err_path_resolution();
J
Jeffrey Seyfried 已提交
3034 3035
        let vis = match self.resolve_path(&path, PathScope::Import, None, Some(span)) {
            PathResult::Module(module) => {
J
Jeffrey Seyfried 已提交
3036
                path_resolution = PathResolution::new(module.def().unwrap());
J
Jeffrey Seyfried 已提交
3037
                ty::Visibility::Restricted(module.normal_ancestor_id.unwrap())
3038
            }
J
Jeffrey Seyfried 已提交
3039 3040
            PathResult::Failed(msg, _) => {
                self.session.span_err(span, &format!("failed to resolve module path. {}", msg));
3041 3042
                ty::Visibility::Public
            }
J
Jeffrey Seyfried 已提交
3043
            _ => ty::Visibility::Public,
3044
        };
3045
        self.def_map.insert(id, path_resolution);
3046 3047
        if !self.is_accessible(vis) {
            let msg = format!("visibilities can only be restricted to ancestor modules");
J
Jeffrey Seyfried 已提交
3048
            self.session.span_err(span, &msg);
3049 3050 3051 3052
        }
        vis
    }

3053
    fn is_accessible(&self, vis: ty::Visibility) -> bool {
J
Jeffrey Seyfried 已提交
3054
        vis.is_accessible_from(self.current_module.normal_ancestor_id.unwrap(), self)
3055 3056
    }

3057
    fn is_accessible_from(&self, vis: ty::Visibility, module: Module<'a>) -> bool {
J
Jeffrey Seyfried 已提交
3058
        vis.is_accessible_from(module.normal_ancestor_id.unwrap(), self)
3059 3060
    }

3061 3062
    fn report_errors(&mut self) {
        self.report_shadowing_errors();
3063
        let mut reported_spans = FxHashSet();
3064

3065
        for &AmbiguityError { span, name, b1, b2, lexical } in &self.ambiguity_errors {
3066
            if !reported_spans.insert(span) { continue }
3067 3068 3069 3070 3071
            let participle = |binding: &NameBinding| {
                if binding.is_import() { "imported" } else { "defined" }
            };
            let msg1 = format!("`{}` could resolve to the name {} here", name, participle(b1));
            let msg2 = format!("`{}` could also resolve to the name {} here", name, participle(b2));
3072 3073 3074
            self.session.struct_span_err(span, &format!("`{}` is ambiguous", name))
                .span_note(b1.span, &msg1)
                .span_note(b2.span, &msg2)
3075
                .note(&if !lexical && b1.is_glob_import() {
3076
                    format!("consider adding an explicit import of `{}` to disambiguate", name)
3077 3078 3079 3080 3081 3082
                } else if let Def::Macro(..) = b1.def() {
                    format!("macro-expanded {} do not shadow",
                            if b1.is_import() { "macro imports" } else { "macros" })
                } else {
                    format!("macro-expanded {} do not shadow when used in a macro invocation path",
                            if b1.is_import() { "imports" } else { "items" })
3083
                })
3084 3085 3086
                .emit();
        }

3087 3088 3089 3090
        for &PrivacyError(span, name, binding) in &self.privacy_errors {
            if !reported_spans.insert(span) { continue }
            if binding.is_extern_crate() {
                // Warn when using an inaccessible extern crate.
3091 3092 3093 3094
                let node_id = match binding.kind {
                    NameBindingKind::Import { directive, .. } => directive.id,
                    _ => unreachable!(),
                };
3095 3096 3097
                let msg = format!("extern crate `{}` is private", name);
                self.session.add_lint(lint::builtin::INACCESSIBLE_EXTERN_CRATE, node_id, span, msg);
            } else {
3098
                let def = binding.def();
3099 3100 3101 3102
                self.session.span_err(span, &format!("{} `{}` is private", def.kind_name(), name));
            }
        }
    }
3103

3104
    fn report_shadowing_errors(&mut self) {
J
Jeffrey Seyfried 已提交
3105
        for (name, scope) in replace(&mut self.lexical_macro_resolutions, Vec::new()) {
3106
            self.resolve_legacy_scope(scope, name, true);
J
Jeffrey Seyfried 已提交
3107 3108
        }

3109
        let mut reported_errors = FxHashSet();
3110
        for binding in replace(&mut self.disallowed_shadowing, Vec::new()) {
3111
            if self.resolve_legacy_scope(&binding.parent, binding.name, false).is_some() &&
3112 3113 3114
               reported_errors.insert((binding.name, binding.span)) {
                let msg = format!("`{}` is already in scope", binding.name);
                self.session.struct_span_err(binding.span, &msg)
3115 3116
                    .note("macro-expanded `macro_rules!`s may not shadow \
                           existing macros (see RFC 1560)")
3117 3118 3119 3120 3121
                    .emit();
            }
        }
    }

3122
    fn report_conflict(&mut self,
3123
                       parent: Module,
3124
                       ident: Ident,
3125 3126 3127 3128
                       ns: Namespace,
                       binding: &NameBinding,
                       old_binding: &NameBinding) {
        // Error on the second of two conflicting names
3129
        if old_binding.span.lo > binding.span.lo {
3130
            return self.report_conflict(parent, ident, ns, old_binding, binding);
3131 3132
        }

J
Jeffrey Seyfried 已提交
3133 3134 3135 3136
        let container = match parent.kind {
            ModuleKind::Def(Def::Mod(_), _) => "module",
            ModuleKind::Def(Def::Trait(_), _) => "trait",
            ModuleKind::Block(..) => "block",
3137 3138 3139
            _ => "enum",
        };

3140
        let (participle, noun) = match old_binding.is_import() {
3141 3142 3143 3144
            true => ("imported", "import"),
            false => ("defined", "definition"),
        };

3145
        let (name, span) = (ident.name, binding.span);
3146 3147 3148 3149 3150 3151 3152

        if let Some(s) = self.name_already_seen.get(&name) {
            if s == &span {
                return;
            }
        }

3153 3154 3155
        let msg = {
            let kind = match (ns, old_binding.module()) {
                (ValueNS, _) => "a value",
3156
                (MacroNS, _) => "a macro",
3157
                (TypeNS, _) if old_binding.is_extern_crate() => "an extern crate",
J
Jeffrey Seyfried 已提交
3158 3159
                (TypeNS, Some(module)) if module.is_normal() => "a module",
                (TypeNS, Some(module)) if module.is_trait() => "a trait",
3160 3161 3162 3163 3164 3165 3166
                (TypeNS, _) => "a type",
            };
            format!("{} named `{}` has already been {} in this {}",
                    kind, name, participle, container)
        };

        let mut err = match (old_binding.is_extern_crate(), binding.is_extern_crate()) {
3167 3168 3169 3170 3171
            (true, true) => {
                let mut e = struct_span_err!(self.session, span, E0259, "{}", msg);
                e.span_label(span, &format!("`{}` was already imported", name));
                e
            },
3172
            (true, _) | (_, true) if binding.is_import() && old_binding.is_import() => {
C
crypto-universe 已提交
3173 3174 3175 3176
                let mut e = struct_span_err!(self.session, span, E0254, "{}", msg);
                e.span_label(span, &"already imported");
                e
            },
M
Mohit Agarwal 已提交
3177 3178 3179 3180 3181
            (true, _) | (_, true) => {
                let mut e = struct_span_err!(self.session, span, E0260, "{}", msg);
                e.span_label(span, &format!("`{}` already imported", name));
                e
            },
3182
            _ => match (old_binding.is_import(), binding.is_import()) {
T
trixnz 已提交
3183 3184 3185 3186 3187
                (false, false) => {
                    let mut e = struct_span_err!(self.session, span, E0428, "{}", msg);
                    e.span_label(span, &format!("already defined"));
                    e
                },
A
Adam Medziński 已提交
3188 3189 3190 3191 3192
                (true, true) => {
                    let mut e = struct_span_err!(self.session, span, E0252, "{}", msg);
                    e.span_label(span, &format!("already imported"));
                    e
                },
3193
                _ => {
3194 3195 3196
                    let mut e = struct_span_err!(self.session, span, E0255, "{}", msg);
                    e.span_label(span, &format!("`{}` was already imported", name));
                    e
3197
                }
3198 3199 3200
            },
        };

3201
        if old_binding.span != syntax_pos::DUMMY_SP {
3202
            err.span_label(old_binding.span, &format!("previous {} of `{}` here", noun, name));
3203 3204
        }
        err.emit();
3205
        self.name_already_seen.insert(name, span);
3206 3207
    }
}
3208

3209
fn names_to_string(names: &[Ident]) -> String {
3210 3211
    let mut first = true;
    let mut result = String::new();
3212
    for ident in names {
3213 3214 3215 3216 3217
        if first {
            first = false
        } else {
            result.push_str("::")
        }
3218
        result.push_str(&ident.name.as_str());
C
corentih 已提交
3219
    }
3220 3221 3222 3223
    result
}

fn path_names_to_string(path: &Path, depth: usize) -> String {
3224 3225 3226
    let names: Vec<_> =
        path.segments[..path.segments.len() - depth].iter().map(|seg| seg.identifier).collect();
    names_to_string(&names)
3227 3228
}

3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251
/// When an entity with a given name is not available in scope, we search for
/// entities with that name in all crates. This method allows outputting the
/// results of this search in a programmer-friendly way
fn show_candidates(session: &mut DiagnosticBuilder,
                   candidates: &SuggestedCandidates) {

    let paths = &candidates.candidates;

    if paths.len() > 0 {
        // don't show more than MAX_CANDIDATES results, so
        // we're consistent with the trait suggestions
        const MAX_CANDIDATES: usize = 5;

        // we want consistent results across executions, but candidates are produced
        // by iterating through a hash map, so make sure they are ordered:
        let mut path_strings: Vec<_> = paths.into_iter()
                                            .map(|p| path_names_to_string(&p, 0))
                                            .collect();
        path_strings.sort();

        // behave differently based on how many candidates we have:
        if !paths.is_empty() {
            if paths.len() == 1 {
3252
                session.help(
T
tiehuis 已提交
3253
                    &format!("you can import it into scope: `use {};`.",
3254 3255 3256
                        &path_strings[0]),
                );
            } else {
3257
                session.help("you can import several candidates \
3258 3259 3260 3261 3262
                    into scope (`use ...;`):");
                let count = path_strings.len() as isize - MAX_CANDIDATES as isize + 1;

                for (idx, path_string) in path_strings.iter().enumerate() {
                    if idx == MAX_CANDIDATES - 1 && count > 1 {
3263
                        session.help(
3264 3265 3266 3267
                            &format!("  and {} other candidates", count).to_string(),
                        );
                        break;
                    } else {
3268
                        session.help(
3269 3270 3271 3272 3273 3274 3275 3276
                            &format!("  `{}`", path_string).to_string(),
                        );
                    }
                }
            }
        }
    } else {
        // nothing found:
3277
        session.help(
3278 3279 3280 3281 3282 3283 3284
            &format!("no candidates by the name of `{}` found in your \
            project; maybe you misspelled the name or forgot to import \
            an external crate?", candidates.name.to_string()),
        );
    };
}

3285
/// A somewhat inefficient routine to obtain the name of a module.
3286
fn module_to_string(module: Module) -> String {
3287 3288
    let mut names = Vec::new();

3289
    fn collect_mod(names: &mut Vec<Ident>, module: Module) {
J
Jeffrey Seyfried 已提交
3290 3291
        if let ModuleKind::Def(_, name) = module.kind {
            if let Some(parent) = module.parent {
3292
                names.push(Ident::with_empty_ctxt(name));
J
Jeffrey Seyfried 已提交
3293
                collect_mod(names, parent);
3294
            }
J
Jeffrey Seyfried 已提交
3295 3296
        } else {
            // danger, shouldn't be ident?
3297
            names.push(Ident::from_str("<opaque>"));
J
Jeffrey Seyfried 已提交
3298
            collect_mod(names, module.parent.unwrap());
3299 3300 3301 3302
        }
    }
    collect_mod(&mut names, module);

3303
    if names.is_empty() {
3304 3305
        return "???".to_string();
    }
3306
    names_to_string(&names.into_iter().rev().collect::<Vec<_>>())
3307 3308
}

3309
fn err_path_resolution() -> PathResolution {
3310
    PathResolution::new(Def::Err)
3311 3312
}

N
Niko Matsakis 已提交
3313
#[derive(PartialEq,Copy, Clone)]
3314 3315
pub enum MakeGlobMap {
    Yes,
C
corentih 已提交
3316
    No,
3317 3318
}

3319
__build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }