lib.rs 143.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)]
21
#![feature(borrow_state)]
V
Vadim Petrochenkov 已提交
22
#![feature(dotdot_in_tuple_patterns)]
A
Alex Crichton 已提交
23
#![feature(rustc_diagnostic_macros)]
24
#![feature(rustc_private)]
A
Alex Crichton 已提交
25
#![feature(staged_api)]
26

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

S
Steven Fackler 已提交
37 38 39 40 41 42 43 44
use self::Namespace::*;
use self::ResolveResult::*;
use self::FallbackSuggestion::*;
use self::TypeParameters::*;
use self::RibKind::*;
use self::UseLexicalScopeFlag::*;
use self::ModulePrefixResult::*;

45
use rustc::hir::map::{Definitions, DefCollector};
46
use rustc::hir::{self, PrimTy, TyBool, TyChar, TyFloat, TyInt, TyUint, TyStr};
47
use rustc::middle::cstore::CrateLoader;
48 49
use rustc::session::Session;
use rustc::lint;
50
use rustc::hir::def::*;
51
use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId};
52
use rustc::ty;
S
Seo Sanghyeon 已提交
53 54
use rustc::hir::{Freevar, FreevarMap, TraitCandidate, TraitMap, GlobMap};
use rustc::util::nodemap::{NodeMap, NodeSet, FnvHashMap, FnvHashSet};
55

56
use syntax::ext::base::MultiItemModifier;
J
Jeffrey Seyfried 已提交
57
use syntax::ext::hygiene::Mark;
58
use syntax::ast::{self, FloatTy};
59
use syntax::ast::{CRATE_NODE_ID, Name, NodeId, IntTy, UintTy};
60
use syntax::parse::token::{self, keywords};
61
use syntax::util::lev_distance::find_best_match_for_name;
62

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

71
use syntax_pos::{Span, DUMMY_SP};
72 73
use errors::DiagnosticBuilder;

74
use std::cell::{Cell, RefCell};
75
use std::fmt;
76
use std::mem::replace;
77
use std::rc::Rc;
78

79
use resolve_imports::{ImportDirective, NameResolution};
J
Jeffrey Seyfried 已提交
80
use macros::ExpansionData;
81

82 83
// NB: This module needs to be declared first so diagnostics are
// registered before they are used.
J
Jeffrey Seyfried 已提交
84
mod diagnostics;
85

86
mod macros;
A
Alex Crichton 已提交
87
mod check_unused;
88
mod build_reduced_graph;
89
mod resolve_imports;
90

91 92
enum SuggestionType {
    Macro(String),
93
    Function(token::InternedString),
94 95 96
    NotFound,
}

97
/// Candidates for a name resolution failure
J
Jeffrey Seyfried 已提交
98
struct SuggestedCandidates {
99 100 101 102
    name: String,
    candidates: Vec<Path>,
}

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

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

    /// `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.)
183 184 185
    Other,
}

186
fn resolve_error<'b, 'a: 'b, 'c>(resolver: &'b Resolver<'a>,
187
                                 span: syntax_pos::Span,
188
                                 resolution_error: ResolutionError<'c>) {
N
Nick Cameron 已提交
189
    resolve_struct_error(resolver, span, resolution_error).emit();
N
Nick Cameron 已提交
190 191
}

192
fn resolve_struct_error<'b, 'a: 'b, 'c>(resolver: &'b Resolver<'a>,
193
                                        span: syntax_pos::Span,
194 195
                                        resolution_error: ResolutionError<'c>)
                                        -> DiagnosticBuilder<'a> {
196
    if !resolver.emit_errors {
N
Nick Cameron 已提交
197
        return resolver.session.diagnostic().struct_dummy();
198
    }
N
Nick Cameron 已提交
199

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

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

N
Niko Matsakis 已提交
503
#[derive(Copy, Clone)]
504
struct BindingInfo {
505
    span: Span,
506
    binding_mode: BindingMode,
507 508 509
}

// Map from the name in a pattern to its binding mode.
510
type BindingMap = FnvHashMap<ast::Ident, BindingInfo>;
511

512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
#[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",
        }
    }
539 540
}

N
Niko Matsakis 已提交
541
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
G
Garming Sam 已提交
542
pub enum Namespace {
543
    TypeNS,
C
corentih 已提交
544
    ValueNS,
545 546
}

547
impl<'a> Visitor for Resolver<'a> {
548
    fn visit_item(&mut self, item: &Item) {
A
Alex Crichton 已提交
549
        self.resolve_item(item);
550
    }
551
    fn visit_arm(&mut self, arm: &Arm) {
A
Alex Crichton 已提交
552
        self.resolve_arm(arm);
553
    }
554
    fn visit_block(&mut self, block: &Block) {
A
Alex Crichton 已提交
555
        self.resolve_block(block);
556
    }
557
    fn visit_expr(&mut self, expr: &Expr) {
558
        self.resolve_expr(expr, None);
559
    }
560
    fn visit_local(&mut self, local: &Local) {
A
Alex Crichton 已提交
561
        self.resolve_local(local);
562
    }
563
    fn visit_ty(&mut self, ty: &Ty) {
A
Alex Crichton 已提交
564
        self.resolve_type(ty);
565
    }
566
    fn visit_poly_trait_ref(&mut self, tref: &ast::PolyTraitRef, m: &ast::TraitBoundModifier) {
567 568
        match self.resolve_trait_reference(tref.trait_ref.ref_id, &tref.trait_ref.path, 0) {
            Ok(def) => self.record_def(tref.trait_ref.ref_id, def),
C
corentih 已提交
569 570
            Err(_) => {
                // error already reported
571
                self.record_def(tref.trait_ref.ref_id, err_path_resolution())
C
corentih 已提交
572
            }
573
        }
574
        visit::walk_poly_trait_ref(self, tref, m);
575
    }
C
corentih 已提交
576
    fn visit_variant(&mut self,
577
                     variant: &ast::Variant,
C
corentih 已提交
578 579
                     generics: &Generics,
                     item_id: ast::NodeId) {
580 581 582
        if let Some(ref dis_expr) = variant.node.disr_expr {
            // resolve the discriminator expr as a constant
            self.with_constant_rib(|this| {
583
                this.visit_expr(dis_expr);
584 585 586
            });
        }

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

626
pub type ErrorMessage = Option<(Span, String)>;
627

628
#[derive(Clone, PartialEq, Eq)]
629
pub enum ResolveResult<T> {
C
corentih 已提交
630 631 632
    Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
    Indeterminate, // Couldn't determine due to unresolved globs.
    Success(T), // Successfully resolved the import.
633 634
}

635
impl<T> ResolveResult<T> {
636 637 638 639 640
    fn and_then<U, F: FnOnce(T) -> ResolveResult<U>>(self, f: F) -> ResolveResult<U> {
        match self {
            Failed(msg) => Failed(msg),
            Indeterminate => Indeterminate,
            Success(t) => f(t),
C
corentih 已提交
641
        }
642
    }
643 644 645 646 647 648 649

    fn success(self) -> Option<T> {
        match self {
            Success(t) => Some(t),
            _ => None,
        }
    }
650 651
}

652 653 654
enum FallbackSuggestion {
    NoSuggestion,
    Field,
655
    TraitItem,
656
    TraitMethod(String),
657 658
}

N
Niko Matsakis 已提交
659
#[derive(Copy, Clone)]
660
enum TypeParameters<'a, 'b> {
661
    NoTypeParameters,
C
corentih 已提交
662
    HasTypeParameters(// Type parameters.
663
                      &'b Generics,
664

C
corentih 已提交
665
                      // The kind of the rib used for type parameters.
666
                      RibKind<'a>),
667 668
}

669
// The rib kind controls the translation of local
670
// definitions (`Def::Local`) to upvars (`Def::Upvar`).
N
Niko Matsakis 已提交
671
#[derive(Copy, Clone, Debug)]
672
enum RibKind<'a> {
673 674
    // No translation needs to be applied.
    NormalRibKind,
675

676 677
    // We passed through a closure scope at the given node ID.
    // Translate upvars as appropriate.
678
    ClosureRibKind(NodeId /* func id */),
679

680
    // We passed through an impl or trait and are now in one of its
681
    // methods. Allow references to ty params that impl or trait
682 683
    // binds. Disallow any other upvars (including other ty params that are
    // upvars).
684 685 686
    //
    // The boolean value represents the fact that this method is static or not.
    MethodRibKind(bool),
687

688 689
    // We passed through an item scope. Disallow upvars.
    ItemRibKind,
690 691

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

694 695
    // We passed through a module.
    ModuleRibKind(Module<'a>),
696 697

    // We passed through a `macro_rules!` statement with the given expansion
698
    MacroDefinition(Mark),
699 700
}

N
Niko Matsakis 已提交
701
#[derive(Copy, Clone)]
F
Felix S. Klock II 已提交
702
enum UseLexicalScopeFlag {
703
    DontUseLexicalScope,
C
corentih 已提交
704
    UseLexicalScope,
705 706
}

707
enum ModulePrefixResult<'a> {
708
    NoPrefixFound,
709
    PrefixFound(Module<'a>, usize),
710 711
}

712
/// One local scope.
J
Jorge Aparicio 已提交
713
#[derive(Debug)]
714
struct Rib<'a> {
715
    bindings: FnvHashMap<ast::Ident, Def>,
716
    kind: RibKind<'a>,
B
Brian Anderson 已提交
717
}
718

719 720
impl<'a> Rib<'a> {
    fn new(kind: RibKind<'a>) -> Rib<'a> {
721
        Rib {
722
            bindings: FnvHashMap(),
C
corentih 已提交
723
            kind: kind,
724
        }
725 726 727
    }
}

728 729 730
/// A definition along with the index of the rib it was found on
struct LocalDef {
    ribs: Option<(Namespace, usize)>,
C
corentih 已提交
731
    def: Def,
732 733 734 735 736 737
}

impl LocalDef {
    fn from_def(def: Def) -> Self {
        LocalDef {
            ribs: None,
C
corentih 已提交
738
            def: def,
739 740 741 742
        }
    }
}

743 744 745 746 747
enum LexicalScopeBinding<'a> {
    Item(&'a NameBinding<'a>),
    LocalDef(LocalDef),
}

748 749 750 751
impl<'a> LexicalScopeBinding<'a> {
    fn local_def(self) -> LocalDef {
        match self {
            LexicalScopeBinding::LocalDef(local_def) => local_def,
752
            LexicalScopeBinding::Item(binding) => LocalDef::from_def(binding.def()),
753 754 755
        }
    }

756
    fn item(self) -> Option<&'a NameBinding<'a>> {
757
        match self {
758
            LexicalScopeBinding::Item(binding) => Some(binding),
759 760 761 762 763
            _ => None,
        }
    }
}

J
Jeffrey Seyfried 已提交
764 765 766
enum ModuleKind {
    Block(NodeId),
    Def(Def, Name),
767 768
}

769
/// One node in the tree of modules.
770
pub struct ModuleS<'a> {
J
Jeffrey Seyfried 已提交
771 772
    parent: Option<Module<'a>>,
    kind: ModuleKind,
773

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

777 778 779
    // If the module is an extern crate, `def` is root of the external crate and `extern_crate_id`
    // is the NodeId of the local `extern crate` item (otherwise, `extern_crate_id` is None).
    extern_crate_id: Option<NodeId>,
780

781
    resolutions: RefCell<FnvHashMap<(Name, Namespace), &'a RefCell<NameResolution<'a>>>>,
782

783
    no_implicit_prelude: bool,
784

785
    glob_importers: RefCell<Vec<&'a ImportDirective<'a>>>,
786
    globs: RefCell<Vec<&'a ImportDirective<'a>>>,
787

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

791 792 793
    // Whether this module is populated. If not populated, any attempt to
    // access the children must be preceded with a
    // `populate_module_if_necessary` call.
794
    populated: Cell<bool>,
795

796
    macros: RefCell<FnvHashMap<Name, macros::NameBinding>>,
797
    macros_escape: bool,
798 799
}

800 801 802
pub type Module<'a> = &'a ModuleS<'a>;

impl<'a> ModuleS<'a> {
803
    fn new(parent: Option<Module<'a>>, kind: ModuleKind) -> Self {
804
        ModuleS {
J
Jeffrey Seyfried 已提交
805 806
            parent: parent,
            kind: kind,
807
            normal_ancestor_id: None,
808
            extern_crate_id: None,
809
            resolutions: RefCell::new(FnvHashMap()),
810
            no_implicit_prelude: false,
811
            glob_importers: RefCell::new(Vec::new()),
812
            globs: RefCell::new((Vec::new())),
J
Jeffrey Seyfried 已提交
813
            traits: RefCell::new(None),
814
            populated: Cell::new(true),
815 816
            macros: RefCell::new(FnvHashMap()),
            macros_escape: false,
817
        }
B
Brian Anderson 已提交
818 819
    }

820
    fn for_each_child<F: FnMut(Name, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
821
        for (&(name, ns), name_resolution) in self.resolutions.borrow().iter() {
822
            name_resolution.borrow().binding.map(|binding| f(name, ns, binding));
823 824 825
        }
    }

J
Jeffrey Seyfried 已提交
826 827 828 829 830 831 832
    fn def(&self) -> Option<Def> {
        match self.kind {
            ModuleKind::Def(def, _) => Some(def),
            _ => None,
        }
    }

833
    fn def_id(&self) -> Option<DefId> {
J
Jeffrey Seyfried 已提交
834
        self.def().as_ref().map(Def::def_id)
835 836
    }

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

    fn is_trait(&self) -> bool {
J
Jeffrey Seyfried 已提交
846 847
        match self.kind {
            ModuleKind::Def(Def::Trait(_), _) => true,
848
            _ => false,
849
        }
B
Brian Anderson 已提交
850
    }
V
Victor Berger 已提交
851 852
}

853
impl<'a> fmt::Debug for ModuleS<'a> {
854
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
J
Jeffrey Seyfried 已提交
855
        write!(f, "{:?}", self.def())
856 857 858
    }
}

859
// Records a possibly-private value, type, or module definition.
860
#[derive(Clone, Debug)]
861
pub struct NameBinding<'a> {
862
    kind: NameBindingKind<'a>,
863
    span: Span,
864
    vis: ty::Visibility,
865 866
}

867 868 869 870 871 872 873 874 875 876
pub trait ToNameBinding<'a> {
    fn to_name_binding(self) -> NameBinding<'a>;
}

impl<'a> ToNameBinding<'a> for NameBinding<'a> {
    fn to_name_binding(self) -> NameBinding<'a> {
        self
    }
}

877
#[derive(Clone, Debug)]
878
enum NameBindingKind<'a> {
879
    Def(Def),
880
    Module(Module<'a>),
881 882
    Import {
        binding: &'a NameBinding<'a>,
883
        directive: &'a ImportDirective<'a>,
884
        used: Cell<bool>,
885
    },
886 887 888 889
    Ambiguity {
        b1: &'a NameBinding<'a>,
        b2: &'a NameBinding<'a>,
    }
890 891
}

892 893
struct PrivacyError<'a>(Span, Name, &'a NameBinding<'a>);

J
Jeffrey Seyfried 已提交
894 895 896 897 898 899 900
struct AmbiguityError<'a> {
    span: Span,
    name: Name,
    b1: &'a NameBinding<'a>,
    b2: &'a NameBinding<'a>,
}

901
impl<'a> NameBinding<'a> {
902
    fn module(&self) -> Result<Module<'a>, bool /* true if an error has already been reported */> {
903
        match self.kind {
904
            NameBindingKind::Module(module) => Ok(module),
905
            NameBindingKind::Import { binding, .. } => binding.module(),
906 907 908
            NameBindingKind::Def(Def::Err) => Err(true),
            NameBindingKind::Def(_) => Err(false),
            NameBindingKind::Ambiguity { ..  } => Err(false),
909 910 911
        }
    }

912
    fn def(&self) -> Def {
913
        match self.kind {
914
            NameBindingKind::Def(def) => def,
J
Jeffrey Seyfried 已提交
915
            NameBindingKind::Module(module) => module.def().unwrap(),
916
            NameBindingKind::Import { binding, .. } => binding.def(),
917
            NameBindingKind::Ambiguity { .. } => Def::Err,
918
        }
919
    }
920

921 922 923 924 925 926 927
    // 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 {
928 929
            NameBindingKind::Def(Def::Variant(..)) |
            NameBindingKind::Def(Def::VariantCtor(..)) => true,
930 931
            _ => false,
        }
932 933
    }

934
    fn is_extern_crate(&self) -> bool {
935
        self.module().ok().and_then(|module| module.extern_crate_id).is_some()
936
    }
937 938 939 940 941 942 943

    fn is_import(&self) -> bool {
        match self.kind {
            NameBindingKind::Import { .. } => true,
            _ => false,
        }
    }
944 945 946 947

    fn is_glob_import(&self) -> bool {
        match self.kind {
            NameBindingKind::Import { directive, .. } => directive.is_glob(),
948
            NameBindingKind::Ambiguity { .. } => true,
949 950 951 952 953
            _ => false,
        }
    }

    fn is_importable(&self) -> bool {
954
        match self.def() {
955 956 957 958
            Def::AssociatedConst(..) | Def::Method(..) | Def::AssociatedTy(..) => false,
            _ => true,
        }
    }
959 960
}

961
/// Interns the names of the primitive types.
F
Felix S. Klock II 已提交
962
struct PrimitiveTypeTable {
963
    primitive_types: FnvHashMap<Name, PrimTy>,
964
}
965

966
impl PrimitiveTypeTable {
K
Kevin Butler 已提交
967
    fn new() -> PrimitiveTypeTable {
968
        let mut table = PrimitiveTypeTable { primitive_types: FnvHashMap() };
C
corentih 已提交
969 970 971

        table.intern("bool", TyBool);
        table.intern("char", TyChar);
972 973
        table.intern("f32", TyFloat(FloatTy::F32));
        table.intern("f64", TyFloat(FloatTy::F64));
974 975 976 977 978
        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 已提交
979
        table.intern("str", TyStr);
980 981 982 983 984
        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 已提交
985 986 987 988

        table
    }

989
    fn intern(&mut self, string: &str, primitive_type: PrimTy) {
990
        self.primitive_types.insert(token::intern(string), primitive_type);
991 992 993
    }
}

994
/// The main resolver class.
995
pub struct Resolver<'a> {
E
Eduard Burtescu 已提交
996
    session: &'a Session,
997

998
    pub definitions: Definitions,
999

1000 1001
    // Maps the node id of a statement to the expansions of the `macro_rules!`s
    // immediately above the statement (if appropriate).
1002
    macros_at_scope: FnvHashMap<NodeId, Vec<Mark>>,
1003

1004
    graph_root: Module<'a>,
1005

1006 1007
    prelude: Option<Module<'a>>,

1008
    trait_item_map: FnvHashMap<(Name, DefId), bool /* is static method? */>,
1009

V
Vadim Petrochenkov 已提交
1010 1011 1012
    // Names of fields of an item `DefId` accessible with dot syntax.
    // Used for hints during error reporting.
    field_names: FnvHashMap<DefId, Vec<Name>>,
1013

1014 1015 1016 1017
    // All imports known to succeed or fail.
    determined_imports: Vec<&'a ImportDirective<'a>>,

    // All non-determined imports.
1018
    indeterminate_imports: Vec<&'a ImportDirective<'a>>,
1019 1020

    // The module that represents the current item scope.
1021
    current_module: Module<'a>,
1022 1023

    // The current set of local scopes, for values.
1024
    // FIXME #4948: Reuse ribs to avoid allocation.
1025
    value_ribs: Vec<Rib<'a>>,
1026 1027

    // The current set of local scopes, for types.
1028
    type_ribs: Vec<Rib<'a>>,
1029

1030
    // The current set of local scopes, for labels.
1031
    label_ribs: Vec<Rib<'a>>,
1032

1033
    // The trait that the current context can refer to.
1034 1035 1036 1037
    current_trait_ref: Option<(DefId, TraitRef)>,

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

1039
    // The idents for the primitive types.
E
Eduard Burtescu 已提交
1040
    primitive_type_table: PrimitiveTypeTable,
1041

1042 1043
    pub def_map: DefMap,
    pub freevars: FreevarMap,
1044
    freevars_seen: NodeMap<NodeMap<usize>>,
1045 1046
    pub export_map: ExportMap,
    pub trait_map: TraitMap,
1047

1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
    // 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`.
1062
    module_map: NodeMap<Module<'a>>,
1063

1064 1065 1066 1067 1068
    // Whether or not to print error messages. Can be set to true
    // when getting additional info for error message suggestions,
    // so as to avoid printing duplicate errors
    emit_errors: bool,

1069
    pub make_glob_map: bool,
1070 1071
    // Maps imports to the names of items actually imported (this actually maps
    // all imports, but only glob imports are actually interesting).
1072
    pub glob_map: GlobMap,
1073

1074 1075
    used_imports: FnvHashSet<(NodeId, Namespace)>,
    used_crates: FnvHashSet<CrateNum>,
1076
    pub maybe_unused_trait_imports: NodeSet,
G
Garming Sam 已提交
1077

1078
    privacy_errors: Vec<PrivacyError<'a>>,
J
Jeffrey Seyfried 已提交
1079
    ambiguity_errors: Vec<AmbiguityError<'a>>,
1080
    macro_shadowing_errors: FnvHashSet<Span>,
1081 1082

    arenas: &'a ResolverArenas<'a>,
1083
    dummy_binding: &'a NameBinding<'a>,
1084
    new_import_semantics: bool, // true if `#![feature(item_like_imports)]`
1085

1086 1087
    pub exported_macros: Vec<ast::MacroDef>,
    pub derive_modes: FnvHashMap<Name, Rc<MultiItemModifier>>,
1088
    crate_loader: &'a mut CrateLoader,
1089 1090 1091
    macro_names: FnvHashSet<Name>,

    // Maps the `Mark` of an expansion to its containing module or block.
J
Jeffrey Seyfried 已提交
1092
    expansion_data: FnvHashMap<Mark, &'a ExpansionData<'a>>,
1093 1094
}

1095
pub struct ResolverArenas<'a> {
1096
    modules: arena::TypedArena<ModuleS<'a>>,
1097
    local_modules: RefCell<Vec<Module<'a>>>,
1098
    name_bindings: arena::TypedArena<NameBinding<'a>>,
1099
    import_directives: arena::TypedArena<ImportDirective<'a>>,
1100
    name_resolutions: arena::TypedArena<RefCell<NameResolution<'a>>>,
J
Jeffrey Seyfried 已提交
1101
    expansion_data: arena::TypedArena<ExpansionData<'a>>,
1102 1103 1104
}

impl<'a> ResolverArenas<'a> {
1105
    fn alloc_module(&'a self, module: ModuleS<'a>) -> Module<'a> {
1106 1107 1108 1109 1110 1111 1112 1113
        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()
1114 1115 1116 1117
    }
    fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
        self.name_bindings.alloc(name_binding)
    }
1118 1119
    fn alloc_import_directive(&'a self, import_directive: ImportDirective<'a>)
                              -> &'a ImportDirective {
1120 1121
        self.import_directives.alloc(import_directive)
    }
1122 1123 1124
    fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
        self.name_resolutions.alloc(Default::default())
    }
J
Jeffrey Seyfried 已提交
1125 1126 1127
    fn alloc_expansion_data(&'a self, expansion_data: ExpansionData<'a>) -> &'a ExpansionData<'a> {
        self.expansion_data.alloc(expansion_data)
    }
1128 1129
}

1130
impl<'a> ty::NodeIdTree for Resolver<'a> {
1131 1132
    fn is_descendant_of(&self, mut node: NodeId, ancestor: NodeId) -> bool {
        while node != ancestor {
J
Jeffrey Seyfried 已提交
1133
            node = match self.module_map[&node].parent {
J
Jeffrey Seyfried 已提交
1134
                Some(parent) => parent.normal_ancestor_id.unwrap(),
1135
                None => return false,
1136
            }
1137
        }
J
Jeffrey Seyfried 已提交
1138
        true
1139 1140 1141
    }
}

1142 1143 1144 1145
impl<'a> hir::lowering::Resolver for Resolver<'a> {
    fn resolve_generated_global_path(&mut self, path: &hir::Path, is_value: bool) -> Def {
        let namespace = if is_value { ValueNS } else { TypeNS };
        match self.resolve_crate_relative_path(path.span, &path.segments, namespace) {
1146
            Ok(binding) => binding.def(),
1147 1148 1149 1150
            Err(true) => Def::Err,
            Err(false) => {
                let path_name = &format!("{}", path);
                let error =
1151 1152 1153 1154 1155
                    ResolutionError::UnresolvedName {
                        path: path_name,
                        message: "",
                        context: UnresolvedNameContext::Other,
                        is_static_method: false,
G
ggomez 已提交
1156 1157
                        is_field: false,
                        def: Def::Err,
1158
                    };
1159 1160 1161 1162 1163 1164
                resolve_error(self, path.span, error);
                Def::Err
            }
        }
    }

1165 1166 1167 1168
    fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution> {
        self.def_map.get(&id).cloned()
    }

1169
    fn record_resolution(&mut self, id: NodeId, def: Def) {
1170
        self.def_map.insert(id, PathResolution::new(def));
1171
    }
1172

1173 1174
    fn definitions(&mut self) -> &mut Definitions {
        &mut self.definitions
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
    }
}

trait Named {
    fn name(&self) -> Name;
}

impl Named for ast::PathSegment {
    fn name(&self) -> Name {
        self.identifier.name
    }
}

impl Named for hir::PathSegment {
    fn name(&self) -> Name {
V
Vadim Petrochenkov 已提交
1190
        self.name
1191 1192 1193
    }
}

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

1210 1211 1212
        let mut definitions = Definitions::new();
        DefCollector::new(&mut definitions).collect_root();

1213
        let mut expansion_data = FnvHashMap();
J
Jeffrey Seyfried 已提交
1214 1215
        expansion_data.insert(Mark::root(),
                              arenas.alloc_expansion_data(ExpansionData::root(graph_root)));
1216

K
Kevin Butler 已提交
1217 1218 1219
        Resolver {
            session: session,

1220
            definitions: definitions,
1221
            macros_at_scope: FnvHashMap(),
1222

K
Kevin Butler 已提交
1223 1224
            // The outermost module has def ID 0; this is not reflected in the
            // AST.
1225
            graph_root: graph_root,
1226
            prelude: None,
K
Kevin Butler 已提交
1227

1228
            trait_item_map: FnvHashMap(),
V
Vadim Petrochenkov 已提交
1229
            field_names: FnvHashMap(),
K
Kevin Butler 已提交
1230

1231
            determined_imports: Vec::new(),
1232
            indeterminate_imports: Vec::new(),
K
Kevin Butler 已提交
1233

1234
            current_module: graph_root,
1235 1236
            value_ribs: vec![Rib::new(ModuleRibKind(graph_root))],
            type_ribs: vec![Rib::new(ModuleRibKind(graph_root))],
1237
            label_ribs: Vec::new(),
K
Kevin Butler 已提交
1238 1239 1240 1241 1242 1243

            current_trait_ref: None,
            current_self_type: None,

            primitive_type_table: PrimitiveTypeTable::new(),

1244
            def_map: NodeMap(),
1245 1246
            freevars: NodeMap(),
            freevars_seen: NodeMap(),
1247 1248
            export_map: NodeMap(),
            trait_map: NodeMap(),
1249
            module_map: module_map,
K
Kevin Butler 已提交
1250 1251

            emit_errors: true,
1252
            make_glob_map: make_glob_map == MakeGlobMap::Yes,
1253
            glob_map: NodeMap(),
G
Garming Sam 已提交
1254

1255 1256
            used_imports: FnvHashSet(),
            used_crates: FnvHashSet(),
S
Seo Sanghyeon 已提交
1257 1258
            maybe_unused_trait_imports: NodeSet(),

1259
            privacy_errors: Vec::new(),
1260
            ambiguity_errors: Vec::new(),
1261
            macro_shadowing_errors: FnvHashSet(),
1262 1263

            arenas: arenas,
1264 1265 1266 1267 1268
            dummy_binding: arenas.alloc_name_binding(NameBinding {
                kind: NameBindingKind::Def(Def::Err),
                span: DUMMY_SP,
                vis: ty::Visibility::Public,
            }),
1269
            new_import_semantics: session.features.borrow().item_like_imports,
1270

1271 1272
            exported_macros: Vec::new(),
            derive_modes: FnvHashMap(),
1273
            crate_loader: crate_loader,
1274
            macro_names: FnvHashSet(),
1275
            expansion_data: expansion_data,
1276 1277 1278
        }
    }

1279
    pub fn arenas() -> ResolverArenas<'a> {
1280 1281
        ResolverArenas {
            modules: arena::TypedArena::new(),
1282
            local_modules: RefCell::new(Vec::new()),
1283
            name_bindings: arena::TypedArena::new(),
1284
            import_directives: arena::TypedArena::new(),
1285
            name_resolutions: arena::TypedArena::new(),
J
Jeffrey Seyfried 已提交
1286
            expansion_data: arena::TypedArena::new(),
K
Kevin Butler 已提交
1287 1288
        }
    }
1289

1290 1291
    /// Entry point to crate resolution.
    pub fn resolve_crate(&mut self, krate: &Crate) {
1292 1293 1294 1295 1296 1297 1298
        // Collect `DefId`s for exported macro defs.
        for def in &krate.exported_macros {
            DefCollector::new(&mut self.definitions).with_parent(CRATE_DEF_INDEX, |collector| {
                collector.visit_macro_def(def)
            })
        }

1299 1300 1301 1302
        self.current_module = self.graph_root;
        visit::walk_crate(self, krate);

        check_unused::check_crate(self, krate);
1303
        self.report_errors();
1304
        self.crate_loader.postprocess(krate);
1305 1306
    }

1307 1308 1309 1310 1311 1312
    fn new_module(&self, parent: Module<'a>, kind: ModuleKind, local: bool) -> Module<'a> {
        self.arenas.alloc_module(ModuleS {
            normal_ancestor_id: if local { self.current_module.normal_ancestor_id } else { None },
            populated: Cell::new(local),
            ..ModuleS::new(Some(parent), kind)
        })
1313 1314
    }

1315 1316 1317 1318
    fn get_ribs<'b>(&'b mut self, ns: Namespace) -> &'b mut Vec<Rib<'a>> {
        match ns { ValueNS => &mut self.value_ribs, TypeNS => &mut self.type_ribs }
    }

1319 1320
    fn record_use(&mut self, name: Name, ns: Namespace, binding: &'a NameBinding<'a>, span: Span)
                  -> bool /* true if an error was reported */ {
1321
        // track extern crates for unused_extern_crate lint
1322
        if let Some(DefId { krate, .. }) = binding.module().ok().and_then(ModuleS::def_id) {
1323 1324 1325
            self.used_crates.insert(krate);
        }

1326 1327 1328 1329 1330 1331 1332 1333 1334
        match binding.kind {
            NameBindingKind::Import { directive, binding, ref used } if !used.get() => {
                used.set(true);
                self.used_imports.insert((directive.id, ns));
                self.add_to_glob_map(directive.id, name);
                self.record_use(name, ns, binding, span)
            }
            NameBindingKind::Import { .. } => false,
            NameBindingKind::Ambiguity { b1, b2 } => {
J
Jeffrey Seyfried 已提交
1335 1336
                let ambiguity_error = AmbiguityError { span: span, name: name, b1: b1, b2: b2 };
                self.ambiguity_errors.push(ambiguity_error);
1337 1338 1339
                true
            }
            _ => false
1340
        }
1341
    }
1342

1343 1344 1345 1346
    fn add_to_glob_map(&mut self, id: NodeId, name: Name) {
        if self.make_glob_map {
            self.glob_map.entry(id).or_insert_with(FnvHashSet).insert(name);
        }
1347 1348
    }

1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
    fn expect_module(&mut self, name: Name, binding: &'a NameBinding<'a>, span: Option<Span>)
                     -> ResolveResult<Module<'a>> {
        match binding.module() {
            Ok(module) => Success(module),
            Err(true) => Failed(None),
            Err(false) => {
                let msg = format!("Not a module `{}`", name);
                Failed(span.map(|span| (span, msg)))
            }
        }
    }

1361
    /// Resolves the given module path from the given root `search_module`.
F
Felix S. Klock II 已提交
1362
    fn resolve_module_path_from_root(&mut self,
1363
                                     mut search_module: Module<'a>,
1364
                                     module_path: &[Name],
1365
                                     index: usize,
1366
                                     span: Option<Span>)
J
Jeffrey Seyfried 已提交
1367
                                     -> ResolveResult<Module<'a>> {
1368 1369
        fn search_parent_externals<'a>(this: &mut Resolver<'a>, needle: Name, module: Module<'a>)
                                       -> Option<Module<'a>> {
1370
            match this.resolve_name_in_module(module, needle, TypeNS, false, None) {
1371
                Success(binding) if binding.is_extern_crate() => Some(module),
J
Jeffrey Seyfried 已提交
1372 1373 1374 1375
                _ => if let (&ModuleKind::Def(..), Some(parent)) = (&module.kind, module.parent) {
                    search_parent_externals(this, needle, parent)
                } else {
                    None
C
corentih 已提交
1376
                },
1377
            }
1378 1379
        }

1380
        let mut index = index;
A
Alex Crichton 已提交
1381
        let module_path_len = module_path.len();
1382 1383 1384 1385 1386

        // Resolve the module part of the path. This does not involve looking
        // upward though scope chains; we simply resolve names directly in
        // modules as we go.
        while index < module_path_len {
A
Alex Crichton 已提交
1387
            let name = module_path[index];
1388
            match self.resolve_name_in_module(search_module, name, TypeNS, false, span) {
1389
                Failed(_) => {
1390
                    let segment_name = name.as_str();
1391
                    let module_name = module_to_string(search_module);
1392
                    let msg = if "???" == &module_name {
1393 1394
                        let current_module = self.current_module;
                        match search_parent_externals(self, name, current_module) {
1395
                            Some(module) => {
1396
                                let path_str = names_to_string(module_path);
J
Jonas Schievink 已提交
1397
                                let target_mod_str = module_to_string(&module);
1398
                                let current_mod_str = module_to_string(current_module);
1399 1400 1401 1402 1403 1404 1405

                                let prefix = if target_mod_str == current_mod_str {
                                    "self::".to_string()
                                } else {
                                    format!("{}::", target_mod_str)
                                };

1406
                                format!("Did you mean `{}{}`?", prefix, path_str)
C
corentih 已提交
1407 1408
                            }
                            None => format!("Maybe a missing `extern crate {}`?", segment_name),
1409
                        }
1410
                    } else {
C
corentih 已提交
1411
                        format!("Could not find `{}` in `{}`", segment_name, module_name)
1412
                    };
1413

1414
                    return Failed(span.map(|span| (span, msg)));
1415
                }
B
Brian Anderson 已提交
1416
                Indeterminate => {
C
corentih 已提交
1417 1418 1419
                    debug!("(resolving module path for import) module resolution is \
                            indeterminate: {}",
                           name);
B
Brian Anderson 已提交
1420
                    return Indeterminate;
1421
                }
1422
                Success(binding) => {
1423 1424
                    // Check to see whether there are type bindings, and, if
                    // so, whether there is a module within.
1425 1426 1427
                    match self.expect_module(name, binding, span) {
                        Success(module) => search_module = module,
                        result @ _ => return result,
1428 1429 1430 1431
                    }
                }
            }

T
Tim Chevalier 已提交
1432
            index += 1;
1433 1434
        }

J
Jeffrey Seyfried 已提交
1435
        return Success(search_module);
1436 1437
    }

1438 1439
    /// Attempts to resolve the module part of an import directive or path
    /// rooted at the given module.
F
Felix S. Klock II 已提交
1440
    fn resolve_module_path(&mut self,
1441
                           module_path: &[Name],
1442
                           use_lexical_scope: UseLexicalScopeFlag,
1443
                           span: Option<Span>)
J
Jeffrey Seyfried 已提交
1444
                           -> ResolveResult<Module<'a>> {
1445
        if module_path.len() == 0 {
J
Jeffrey Seyfried 已提交
1446
            return Success(self.graph_root) // Use the crate root
1447
        }
1448

1449
        debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1450
               names_to_string(module_path),
1451
               module_to_string(self.current_module));
1452

1453
        // Resolve the module prefix, if any.
1454
        let module_prefix_result = self.resolve_module_prefix(module_path, span);
1455

1456 1457
        let search_module;
        let start_index;
1458
        match module_prefix_result {
1459
            Failed(err) => return Failed(err),
B
Brian Anderson 已提交
1460
            Indeterminate => {
C
corentih 已提交
1461
                debug!("(resolving module path for import) indeterminate; bailing");
B
Brian Anderson 已提交
1462
                return Indeterminate;
1463
            }
1464 1465 1466 1467 1468 1469 1470 1471
            Success(NoPrefixFound) => {
                // There was no prefix, so we're considering the first element
                // of the path. How we handle this depends on whether we were
                // instructed to use lexical scope or not.
                match use_lexical_scope {
                    DontUseLexicalScope => {
                        // This is a crate-relative path. We will start the
                        // resolution process at index zero.
1472
                        search_module = self.graph_root;
1473 1474 1475 1476 1477 1478
                        start_index = 0;
                    }
                    UseLexicalScope => {
                        // This is not a crate-relative path. We resolve the
                        // first component of the path in the current lexical
                        // scope and then proceed to resolve below that.
1479
                        let ident = ast::Ident::with_empty_ctxt(module_path[0]);
1480 1481 1482 1483 1484 1485 1486 1487 1488
                        let lexical_binding =
                            self.resolve_ident_in_lexical_scope(ident, TypeNS, span);
                        if let Some(binding) = lexical_binding.and_then(LexicalScopeBinding::item) {
                            match self.expect_module(ident.name, binding, span) {
                                Success(containing_module) => {
                                    search_module = containing_module;
                                    start_index = 1;
                                }
                                result @ _ => return result,
1489
                            }
1490 1491 1492 1493
                        } else {
                            let msg =
                                format!("Use of undeclared type or module `{}`", ident.name);
                            return Failed(span.map(|span| (span, msg)));
1494 1495 1496 1497
                        }
                    }
                }
            }
E
Eduard Burtescu 已提交
1498
            Success(PrefixFound(ref containing_module, index)) => {
1499
                search_module = containing_module;
1500
                start_index = index;
1501 1502 1503
            }
        }

1504
        self.resolve_module_path_from_root(search_module, module_path, start_index, span)
1505 1506
    }

1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
    /// 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.
    /// }
    /// ```
1521
    ///
1522 1523
    /// Invariant: This must only be called during main resolution, not during
    /// import resolution.
1524
    fn resolve_ident_in_lexical_scope(&mut self,
1525
                                      mut ident: ast::Ident,
1526
                                      ns: Namespace,
1527
                                      record_used: Option<Span>)
1528
                                      -> Option<LexicalScopeBinding<'a>> {
1529 1530 1531
        if ns == TypeNS {
            ident = ast::Ident::with_empty_ctxt(ident.name);
        }
1532

1533
        // Walk backwards up the ribs in scope.
1534
        for i in (0 .. self.get_ribs(ns).len()).rev() {
1535
            if let Some(def) = self.get_ribs(ns)[i].bindings.get(&ident).cloned() {
1536 1537 1538 1539 1540
                // The ident resolves to a type parameter or local variable.
                return Some(LexicalScopeBinding::LocalDef(LocalDef {
                    ribs: Some((ns, i)),
                    def: def,
                }));
1541 1542
            }

1543
            if let ModuleRibKind(module) = self.get_ribs(ns)[i].kind {
1544
                let name = ident.name;
1545 1546 1547 1548
                let item = self.resolve_name_in_module(module, name, ns, true, record_used);
                if let Success(binding) = item {
                    // The ident resolves to an item.
                    return Some(LexicalScopeBinding::Item(binding));
1549
                }
1550

J
Jeffrey Seyfried 已提交
1551
                if let ModuleKind::Block(..) = module.kind { // We can see through blocks
1552
                } else if !module.no_implicit_prelude {
J
Jeffrey Seyfried 已提交
1553 1554 1555 1556 1557
                    return self.prelude.and_then(|prelude| {
                        self.resolve_name_in_module(prelude, name, ns, false, None).success()
                    }).map(LexicalScopeBinding::Item)
                } else {
                    return None;
1558
                }
1559
            }
1560 1561 1562 1563

            if let MacroDefinition(mac) = self.get_ribs(ns)[i].kind {
                // If an invocation of this macro created `ident`, give up on `ident`
                // and switch to `ident`'s source from the macro definition.
1564 1565 1566
                let (source_ctxt, source_macro) = ident.ctxt.source();
                if source_macro == mac {
                    ident.ctxt = source_ctxt;
1567 1568
                }
            }
1569
        }
1570

1571 1572 1573
        None
    }

1574
    /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1575
    /// (b) some chain of `super::`.
1576
    /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1577
    fn resolve_module_prefix(&mut self, module_path: &[Name], span: Option<Span>)
1578
                             -> ResolveResult<ModulePrefixResult<'a>> {
1579 1580
        // Start at the current module if we see `self` or `super`, or at the
        // top of the crate otherwise.
1581 1582 1583 1584 1585
        let mut i = match &*module_path[0].as_str() {
            "self" => 1,
            "super" => 0,
            _ => return Success(NoPrefixFound),
        };
1586

J
Jeffrey Seyfried 已提交
1587 1588
        let mut containing_module =
            self.module_map[&self.current_module.normal_ancestor_id.unwrap()];
1589 1590

        // Now loop through all the `super`s we find.
1591
        while i < module_path.len() && "super" == module_path[i].as_str() {
1592
            debug!("(resolving module prefix) resolving `super` at {}",
J
Jonas Schievink 已提交
1593
                   module_to_string(&containing_module));
J
Jeffrey Seyfried 已提交
1594
            if let Some(parent) = containing_module.parent {
J
Jeffrey Seyfried 已提交
1595
                containing_module = self.module_map[&parent.normal_ancestor_id.unwrap()];
1596 1597 1598 1599
                i += 1;
            } else {
                let msg = "There are too many initial `super`s.".into();
                return Failed(span.map(|span| (span, msg)));
1600 1601 1602
            }
        }

1603
        debug!("(resolving module prefix) finished resolving prefix at {}",
J
Jonas Schievink 已提交
1604
               module_to_string(&containing_module));
1605 1606

        return Success(PrefixFound(containing_module, i));
1607 1608
    }

1609 1610
    // AST resolution
    //
1611
    // We maintain a list of value ribs and type ribs.
1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
    //
    // 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.

1627
    fn with_scope<F>(&mut self, id: NodeId, f: F)
C
corentih 已提交
1628
        where F: FnOnce(&mut Resolver)
J
Jorge Aparicio 已提交
1629
    {
1630 1631
        let module = self.module_map.get(&id).cloned(); // clones a reference
        if let Some(module) = module {
1632
            // Move down in the graph.
1633
            let orig_module = replace(&mut self.current_module, module);
1634 1635
            self.value_ribs.push(Rib::new(ModuleRibKind(module)));
            self.type_ribs.push(Rib::new(ModuleRibKind(module)));
1636

1637
            f(self);
1638

1639 1640 1641 1642 1643 1644
            self.current_module = orig_module;
            self.value_ribs.pop();
            self.type_ribs.pop();
        } else {
            f(self);
        }
1645 1646
    }

S
Seo Sanghyeon 已提交
1647 1648
    /// Searches the current set of local scopes for labels.
    /// Stops after meeting a closure.
1649
    fn search_label(&self, mut ident: ast::Ident) -> Option<Def> {
1650 1651 1652 1653 1654
        for rib in self.label_ribs.iter().rev() {
            match rib.kind {
                NormalRibKind => {
                    // Continue
                }
1655 1656 1657
                MacroDefinition(mac) => {
                    // If an invocation of this macro created `ident`, give up on `ident`
                    // and switch to `ident`'s source from the macro definition.
1658 1659 1660
                    let (source_ctxt, source_macro) = ident.ctxt.source();
                    if source_macro == mac {
                        ident.ctxt = source_ctxt;
1661 1662
                    }
                }
1663 1664
                _ => {
                    // Do not resolve labels across function boundary
C
corentih 已提交
1665
                    return None;
1666 1667
                }
            }
1668
            let result = rib.bindings.get(&ident).cloned();
S
Seo Sanghyeon 已提交
1669
            if result.is_some() {
C
corentih 已提交
1670
                return result;
1671 1672 1673 1674 1675
            }
        }
        None
    }

1676
    fn resolve_item(&mut self, item: &Item) {
1677
        let name = item.ident.name;
1678

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

1681
        match item.node {
1682 1683
            ItemKind::Enum(_, ref generics) |
            ItemKind::Ty(_, ref generics) |
1684
            ItemKind::Struct(_, ref generics) |
1685
            ItemKind::Union(_, ref generics) |
V
Vadim Petrochenkov 已提交
1686
            ItemKind::Fn(.., ref generics, _) => {
1687
                self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind),
1688
                                             |this| visit::walk_item(this, item));
1689 1690
            }

1691
            ItemKind::DefaultImpl(_, ref trait_ref) => {
1692
                self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
1693
            }
V
Vadim Petrochenkov 已提交
1694
            ItemKind::Impl(.., ref generics, ref opt_trait_ref, ref self_type, ref impl_items) =>
1695
                self.resolve_implementation(generics,
1696
                                            opt_trait_ref,
J
Jonas Schievink 已提交
1697
                                            &self_type,
1698
                                            item.id,
1699
                                            impl_items),
1700

1701
            ItemKind::Trait(_, ref generics, ref bounds, ref trait_items) => {
1702
                // Create a new rib for the trait-wide type parameters.
1703
                self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
1704
                    let local_def_id = this.definitions.local_def_id(item.id);
1705
                    this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
1706
                        this.visit_generics(generics);
1707
                        walk_list!(this, visit_ty_param_bound, bounds);
1708 1709

                        for trait_item in trait_items {
1710
                            match trait_item.node {
1711
                                TraitItemKind::Const(_, ref default) => {
1712 1713 1714 1715 1716
                                    // 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| {
1717
                                            visit::walk_trait_item(this, trait_item)
1718 1719
                                        });
                                    } else {
1720
                                        visit::walk_trait_item(this, trait_item)
1721 1722
                                    }
                                }
1723
                                TraitItemKind::Method(ref sig, _) => {
1724 1725
                                    let type_parameters =
                                        HasTypeParameters(&sig.generics,
V
Vadim Petrochenkov 已提交
1726
                                                          MethodRibKind(!sig.decl.has_self()));
1727
                                    this.with_type_parameter_rib(type_parameters, |this| {
1728
                                        visit::walk_trait_item(this, trait_item)
1729
                                    });
1730
                                }
1731
                                TraitItemKind::Type(..) => {
1732
                                    this.with_type_parameter_rib(NoTypeParameters, |this| {
1733
                                        visit::walk_trait_item(this, trait_item)
1734
                                    });
1735
                                }
1736
                                TraitItemKind::Macro(_) => panic!("unexpanded macro in resolve!"),
1737 1738 1739
                            };
                        }
                    });
1740
                });
1741 1742
            }

1743
            ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
1744
                self.with_scope(item.id, |this| {
1745
                    visit::walk_item(this, item);
1746
                });
1747 1748
            }

1749
            ItemKind::Const(..) | ItemKind::Static(..) => {
A
Alex Crichton 已提交
1750
                self.with_constant_rib(|this| {
1751
                    visit::walk_item(this, item);
1752
                });
1753
            }
1754

1755
            ItemKind::Use(ref view_path) => {
1756
                match view_path.node {
1757
                    ast::ViewPathList(ref prefix, ref items) => {
1758 1759 1760 1761 1762
                        // Resolve prefix of an import with empty braces (issue #28388)
                        if items.is_empty() && !prefix.segments.is_empty() {
                            match self.resolve_crate_relative_path(prefix.span,
                                                                   &prefix.segments,
                                                                   TypeNS) {
1763
                                Ok(binding) => {
1764
                                    let def = binding.def();
1765
                                    self.record_def(item.id, PathResolution::new(def));
1766
                                }
1767 1768
                                Err(true) => self.record_def(item.id, err_path_resolution()),
                                Err(false) => {
1769 1770 1771 1772
                                    resolve_error(self,
                                                  prefix.span,
                                                  ResolutionError::FailedToResolve(
                                                      &path_names_to_string(prefix, 0)));
1773
                                    self.record_def(item.id, err_path_resolution());
1774
                                }
1775 1776 1777 1778
                            }
                        }
                    }
                    _ => {}
W
we 已提交
1779 1780 1781
                }
            }

1782
            ItemKind::ExternCrate(_) => {
1783
                // do nothing, these are just around to be encoded
1784
            }
1785 1786

            ItemKind::Mac(_) => panic!("unexpanded macro in resolve!"),
1787 1788 1789
        }
    }

1790
    fn with_type_parameter_rib<'b, F>(&'b mut self, type_parameters: TypeParameters<'a, 'b>, f: F)
C
corentih 已提交
1791
        where F: FnOnce(&mut Resolver)
J
Jorge Aparicio 已提交
1792
    {
1793
        match type_parameters {
1794
            HasTypeParameters(generics, rib_kind) => {
1795
                let mut function_type_rib = Rib::new(rib_kind);
1796
                let mut seen_bindings = FnvHashMap();
1797
                for type_parameter in &generics.ty_params {
1798
                    let name = type_parameter.ident.name;
1799
                    debug!("with_type_parameter_rib: {}", type_parameter.id);
1800

C
Chris Stankus 已提交
1801 1802
                    if seen_bindings.contains_key(&name) {
                        let span = seen_bindings.get(&name).unwrap();
1803 1804
                        resolve_error(self,
                                      type_parameter.span,
C
Chris Stankus 已提交
1805 1806
                                      ResolutionError::NameAlreadyUsedInTypeParameterList(name,
                                                                                          span));
1807
                    }
C
Chris Stankus 已提交
1808
                    seen_bindings.entry(name).or_insert(type_parameter.span);
1809

1810
                    // plain insert (no renaming)
1811
                    let def_id = self.definitions.local_def_id(type_parameter.id);
1812
                    let def = Def::TyParam(def_id);
1813
                    function_type_rib.bindings.insert(ast::Ident::with_empty_ctxt(name), def);
1814
                    self.record_def(type_parameter.id, PathResolution::new(def));
1815
                }
1816
                self.type_ribs.push(function_type_rib);
1817 1818
            }

B
Brian Anderson 已提交
1819
            NoTypeParameters => {
1820 1821 1822 1823
                // Nothing to do.
            }
        }

A
Alex Crichton 已提交
1824
        f(self);
1825

J
Jeffrey Seyfried 已提交
1826 1827
        if let HasTypeParameters(..) = type_parameters {
            self.type_ribs.pop();
1828 1829 1830
        }
    }

C
corentih 已提交
1831 1832
    fn with_label_rib<F>(&mut self, f: F)
        where F: FnOnce(&mut Resolver)
J
Jorge Aparicio 已提交
1833
    {
1834
        self.label_ribs.push(Rib::new(NormalRibKind));
A
Alex Crichton 已提交
1835
        f(self);
J
Jeffrey Seyfried 已提交
1836
        self.label_ribs.pop();
1837
    }
1838

C
corentih 已提交
1839 1840
    fn with_constant_rib<F>(&mut self, f: F)
        where F: FnOnce(&mut Resolver)
J
Jorge Aparicio 已提交
1841
    {
1842 1843
        self.value_ribs.push(Rib::new(ConstantItemRibKind));
        self.type_ribs.push(Rib::new(ConstantItemRibKind));
A
Alex Crichton 已提交
1844
        f(self);
J
Jeffrey Seyfried 已提交
1845 1846
        self.type_ribs.pop();
        self.value_ribs.pop();
1847 1848
    }

1849 1850 1851 1852
    fn resolve_function(&mut self,
                        rib_kind: RibKind<'a>,
                        declaration: &FnDecl,
                        block: &Block) {
1853
        // Create a value rib for the function.
1854
        self.value_ribs.push(Rib::new(rib_kind));
1855

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

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

J
Jonas Schievink 已提交
1864
            self.visit_ty(&argument.ty);
1865

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

1870
        // Resolve the function body.
1871
        self.visit_block(block);
1872

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

J
Jeffrey Seyfried 已提交
1875 1876
        self.label_ribs.pop();
        self.value_ribs.pop();
1877 1878
    }

F
Felix S. Klock II 已提交
1879
    fn resolve_trait_reference(&mut self,
N
Nick Cameron 已提交
1880
                               id: NodeId,
1881
                               trait_path: &Path,
1882
                               path_depth: usize)
1883
                               -> Result<PathResolution, ()> {
1884
        self.resolve_path(id, trait_path, path_depth, TypeNS).and_then(|path_res| {
1885 1886 1887 1888 1889 1890 1891 1892
            match path_res.base_def {
                Def::Trait(_) => {
                    debug!("(resolving trait) found trait def: {:?}", path_res);
                    return Ok(path_res);
                }
                Def::Err => return Err(true),
                _ => {}
            }
1893

1894 1895 1896 1897 1898 1899
            let mut err = resolve_struct_error(self, trait_path.span, {
                ResolutionError::IsNotATrait(&path_names_to_string(trait_path, path_depth))
            });

            // If it's a typedef, give a note
            if let Def::TyAlias(..) = path_res.base_def {
1900
                err.note(&format!("type aliases cannot be used for traits"));
1901
            }
1902 1903
            err.emit();
            Err(true)
1904 1905
        }).map_err(|error_reported| {
            if error_reported { return }
1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927

            // find possible candidates
            let trait_name = trait_path.segments.last().unwrap().identifier.name;
            let candidates =
                self.lookup_candidates(
                    trait_name,
                    TypeNS,
                    |def| match def {
                        Def::Trait(_) => true,
                        _             => false,
                    },
                );

            // create error object
            let name = &path_names_to_string(trait_path, path_depth);
            let error =
                ResolutionError::UndeclaredTraitName(
                    name,
                    candidates,
                );

            resolve_error(self, trait_path.span, error);
1928
        })
1929 1930
    }

1931 1932
    fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
        where F: FnOnce(&mut Resolver) -> T
J
Jorge Aparicio 已提交
1933
    {
1934 1935 1936 1937 1938 1939 1940
        // 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
    }

C
corentih 已提交
1941
    fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
1942
        where F: FnOnce(&mut Resolver, Option<DefId>) -> T
J
Jorge Aparicio 已提交
1943
    {
1944
        let mut new_val = None;
1945
        let mut new_id = None;
E
Eduard Burtescu 已提交
1946
        if let Some(trait_ref) = opt_trait_ref {
1947
            if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
C
corentih 已提交
1948 1949
                                                               &trait_ref.path,
                                                               0) {
1950 1951 1952 1953
                assert!(path_res.depth == 0);
                self.record_def(trait_ref.ref_id, path_res);
                new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
                new_id = Some(path_res.base_def.def_id());
1954 1955
            } else {
                self.record_def(trait_ref.ref_id, err_path_resolution());
1956
            }
1957
            visit::walk_trait_ref(self, trait_ref);
1958
        }
1959
        let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
1960
        let result = f(self, new_id);
1961 1962 1963 1964
        self.current_trait_ref = original_trait_ref;
        result
    }

1965 1966 1967 1968 1969 1970
    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....)
1971
        self_type_rib.bindings.insert(keywords::SelfType.ident(), self_def);
1972 1973
        self.type_ribs.push(self_type_rib);
        f(self);
J
Jeffrey Seyfried 已提交
1974
        self.type_ribs.pop();
1975 1976
    }

F
Felix S. Klock II 已提交
1977
    fn resolve_implementation(&mut self,
1978 1979 1980
                              generics: &Generics,
                              opt_trait_reference: &Option<TraitRef>,
                              self_type: &Ty,
1981
                              item_id: NodeId,
1982
                              impl_items: &[ImplItem]) {
1983
        // If applicable, create a rib for the type parameters.
1984
        self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
1985
            // Resolve the type parameters.
1986
            this.visit_generics(generics);
1987

1988
            // Resolve the trait reference, if necessary.
1989
            this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
1990
                // Resolve the self type.
1991
                this.visit_ty(self_type);
1992

1993 1994
                let item_def_id = this.definitions.local_def_id(item_id);
                this.with_self_rib(Def::SelfTy(trait_id, Some(item_def_id)), |this| {
1995 1996
                    this.with_current_self_type(self_type, |this| {
                        for impl_item in impl_items {
1997
                            this.resolve_visibility(&impl_item.vis);
1998
                            match impl_item.node {
1999
                                ImplItemKind::Const(..) => {
2000
                                    // If this is a trait impl, ensure the const
2001
                                    // exists in trait
2002
                                    this.check_trait_item(impl_item.ident.name,
2003 2004
                                                          impl_item.span,
                                        |n, s| ResolutionError::ConstNotMemberOfTrait(n, s));
2005
                                    visit::walk_impl_item(this, impl_item);
2006
                                }
2007
                                ImplItemKind::Method(ref sig, _) => {
2008 2009
                                    // If this is a trait impl, ensure the method
                                    // exists in trait
2010
                                    this.check_trait_item(impl_item.ident.name,
2011 2012
                                                          impl_item.span,
                                        |n, s| ResolutionError::MethodNotMemberOfTrait(n, s));
2013 2014 2015 2016 2017

                                    // We also need a new scope for the method-
                                    // specific type parameters.
                                    let type_parameters =
                                        HasTypeParameters(&sig.generics,
V
Vadim Petrochenkov 已提交
2018
                                                          MethodRibKind(!sig.decl.has_self()));
2019
                                    this.with_type_parameter_rib(type_parameters, |this| {
2020
                                        visit::walk_impl_item(this, impl_item);
2021 2022
                                    });
                                }
2023
                                ImplItemKind::Type(ref ty) => {
2024
                                    // If this is a trait impl, ensure the type
2025
                                    // exists in trait
2026
                                    this.check_trait_item(impl_item.ident.name,
2027 2028
                                                          impl_item.span,
                                        |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
2029

2030 2031
                                    this.visit_ty(ty);
                                }
2032
                                ImplItemKind::Macro(_) => panic!("unexpanded macro in resolve!"),
2033
                            }
2034
                        }
2035
                    });
2036 2037
                });
            });
2038
        });
2039 2040
    }

2041
    fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
C
corentih 已提交
2042 2043 2044 2045
        where F: FnOnce(Name, &str) -> ResolutionError
    {
        // If there is a TraitRef in scope for an impl, then the method must be in the
        // trait.
2046
        if let Some((did, ref trait_ref)) = self.current_trait_ref {
2047
            if !self.trait_item_map.contains_key(&(name, did)) {
2048
                let path_str = path_names_to_string(&trait_ref.path, 0);
J
Jonas Schievink 已提交
2049
                resolve_error(self, span, err(name, &path_str));
2050 2051 2052 2053
            }
        }
    }

E
Eduard Burtescu 已提交
2054
    fn resolve_local(&mut self, local: &Local) {
2055
        // Resolve the type.
2056
        walk_list!(self, visit_ty, &local.ty);
2057

2058
        // Resolve the initializer.
2059
        walk_list!(self, visit_expr, &local.init);
2060 2061

        // Resolve the pattern.
2062
        self.resolve_pattern(&local.pat, PatternSource::Let, &mut FnvHashMap());
2063 2064
    }

J
John Clements 已提交
2065 2066 2067 2068
    // 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 已提交
2069
    fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2070
        let mut binding_map = FnvHashMap();
2071 2072 2073 2074 2075 2076 2077 2078

        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 };
2079
                    binding_map.insert(ident.node, binding_info);
2080 2081 2082
                }
            }
            true
2083
        });
2084 2085

        binding_map
2086 2087
    }

J
John Clements 已提交
2088 2089
    // 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 已提交
2090
    fn check_consistent_bindings(&mut self, arm: &Arm) {
2091
        if arm.pats.is_empty() {
C
corentih 已提交
2092
            return;
2093
        }
J
Jonas Schievink 已提交
2094
        let map_0 = self.binding_mode_map(&arm.pats[0]);
D
Daniel Micay 已提交
2095
        for (i, p) in arm.pats.iter().enumerate() {
J
Jonas Schievink 已提交
2096
            let map_i = self.binding_mode_map(&p);
2097

2098
            for (&key, &binding_0) in &map_0 {
2099
                match map_i.get(&key) {
C
corentih 已提交
2100
                    None => {
2101 2102
                        let error = ResolutionError::VariableNotBoundInPattern(key.name, 1, i + 1);
                        resolve_error(self, p.span, error);
C
corentih 已提交
2103 2104 2105 2106 2107
                    }
                    Some(binding_i) => {
                        if binding_0.binding_mode != binding_i.binding_mode {
                            resolve_error(self,
                                          binding_i.span,
M
Mikhail Modin 已提交
2108 2109 2110 2111
                                          ResolutionError::VariableBoundWithDifferentMode(
                                              key.name,
                                              i + 1,
                                              binding_0.span));
C
corentih 已提交
2112
                        }
2113
                    }
2114 2115 2116
                }
            }

2117
            for (&key, &binding) in &map_i {
2118
                if !map_0.contains_key(&key) {
2119 2120
                    resolve_error(self,
                                  binding.span,
2121
                                  ResolutionError::VariableNotBoundInPattern(key.name, i + 1, 1));
2122 2123 2124
                }
            }
        }
2125 2126
    }

F
Felix S. Klock II 已提交
2127
    fn resolve_arm(&mut self, arm: &Arm) {
2128
        self.value_ribs.push(Rib::new(NormalRibKind));
2129

2130
        let mut bindings_list = FnvHashMap();
2131
        for pattern in &arm.pats {
2132
            self.resolve_pattern(&pattern, PatternSource::Match, &mut bindings_list);
2133 2134
        }

2135 2136 2137 2138
        // This has to happen *after* we determine which
        // pat_idents are variants
        self.check_consistent_bindings(arm);

2139
        walk_list!(self, visit_expr, &arm.guard);
J
Jonas Schievink 已提交
2140
        self.visit_expr(&arm.body);
2141

J
Jeffrey Seyfried 已提交
2142
        self.value_ribs.pop();
2143 2144
    }

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

2151
        let mut num_macro_definition_ribs = 0;
2152 2153
        if let Some(anonymous_module) = anonymous_module {
            debug!("(resolving block) found anonymous module, moving down");
2154 2155
            self.value_ribs.push(Rib::new(ModuleRibKind(anonymous_module)));
            self.type_ribs.push(Rib::new(ModuleRibKind(anonymous_module)));
2156 2157 2158
            self.current_module = anonymous_module;
        } else {
            self.value_ribs.push(Rib::new(NormalRibKind));
2159 2160 2161
        }

        // Descend into the block.
2162 2163
        for stmt in &block.stmts {
            if let Some(marks) = self.macros_at_scope.remove(&stmt.id) {
2164
                num_macro_definition_ribs += marks.len() as u32;
2165 2166
                for mark in marks {
                    self.value_ribs.push(Rib::new(MacroDefinition(mark)));
2167
                    self.label_ribs.push(Rib::new(MacroDefinition(mark)));
2168 2169 2170 2171 2172
                }
            }

            self.visit_stmt(stmt);
        }
2173 2174

        // Move back up.
J
Jeffrey Seyfried 已提交
2175
        self.current_module = orig_module;
2176
        for _ in 0 .. num_macro_definition_ribs {
2177
            self.value_ribs.pop();
2178
            self.label_ribs.pop();
2179
        }
2180
        self.value_ribs.pop();
J
Jeffrey Seyfried 已提交
2181 2182
        if let Some(_) = anonymous_module {
            self.type_ribs.pop();
G
Garming Sam 已提交
2183
        }
2184
        debug!("(resolving block) leaving block");
2185 2186
    }

F
Felix S. Klock II 已提交
2187
    fn resolve_type(&mut self, ty: &Ty) {
2188
        match ty.node {
2189
            TyKind::Path(ref maybe_qself, ref path) => {
2190
                // This is a path in the type namespace. Walk through scopes
2191
                // looking for it.
2192 2193
                if let Some(def) = self.resolve_possibly_assoc_item(ty.id, maybe_qself.as_ref(),
                                                                    path, TypeNS) {
2194
                    match def.base_def {
2195
                        Def::Mod(..) if def.depth == 0 => {
2196 2197 2198 2199 2200 2201 2202 2203 2204 2205
                            self.session.span_err(path.span, "expected type, found module");
                            self.record_def(ty.id, err_path_resolution());
                        }
                        _ => {
                            // 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);
                        }
                    }
2206 2207
                } else {
                    self.record_def(ty.id, err_path_resolution());
2208

2209 2210 2211 2212
                    // Keep reporting some errors even if they're ignored above.
                    if let Err(true) = self.resolve_path(ty.id, path, 0, TypeNS) {
                        // `resolve_path` already reported the error
                    } else {
2213 2214 2215 2216
                        let kind = if maybe_qself.is_some() {
                            "associated type"
                        } else {
                            "type name"
2217
                        };
2218

C
corentih 已提交
2219 2220 2221
                        let is_invalid_self_type_name = path.segments.len() > 0 &&
                                                        maybe_qself.is_none() &&
                                                        path.segments[0].identifier.name ==
2222
                                                        keywords::SelfType.name();
G
Guillaume Gomez 已提交
2223
                        if is_invalid_self_type_name {
2224 2225
                            resolve_error(self,
                                          ty.span,
2226
                                          ResolutionError::SelfUsedOutsideImplOrTrait);
2227
                        } else {
2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239
                            let segment = path.segments.last();
                            let segment = segment.expect("missing name in path");
                            let type_name = segment.identifier.name;

                            let candidates =
                                self.lookup_candidates(
                                    type_name,
                                    TypeNS,
                                    |def| match def {
                                        Def::Trait(_) |
                                        Def::Enum(_) |
                                        Def::Struct(_) |
2240
                                        Def::Union(_) |
2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255
                                        Def::TyAlias(_) => true,
                                        _               => false,
                                    },
                                );

                            // create error object
                            let name = &path_names_to_string(path, 0);
                            let error =
                                ResolutionError::UseOfUndeclared(
                                    kind,
                                    name,
                                    candidates,
                                );

                            resolve_error(self, ty.span, error);
G
Guillaume Gomez 已提交
2256
                        }
2257 2258
                    }
                }
2259
            }
2260
            _ => {}
2261
        }
2262
        // Resolve embedded types.
2263
        visit::walk_ty(self, ty);
2264 2265
    }

2266 2267 2268 2269 2270
    fn fresh_binding(&mut self,
                     ident: &ast::SpannedIdent,
                     pat_id: NodeId,
                     outer_pat_id: NodeId,
                     pat_src: PatternSource,
2271
                     bindings: &mut FnvHashMap<ast::Ident, NodeId>)
2272 2273
                     -> PathResolution {
        // Add the binding to the local ribs, if it
2274 2275
        // doesn't already exist in the bindings map. (We
        // must not add it if it's in the bindings map
2276 2277
        // because that breaks the assumptions later
        // passes make about or-patterns.)
2278
        let mut def = Def::Local(self.definitions.local_def_id(pat_id));
2279
        match bindings.get(&ident.node).cloned() {
2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298
            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 => {
2299 2300
                // `Variant1(a) | Variant2(a)`, ok
                // Reuse definition from the first `a`.
2301
                def = self.value_ribs.last_mut().unwrap().bindings[&ident.node];
2302 2303 2304 2305 2306 2307
            }
            Some(..) => {
                span_bug!(ident.span, "two bindings with the same name from \
                                       unexpected pattern source {:?}", pat_src);
            }
            None => {
2308
                // A completely fresh binding, add to the lists if it's valid.
2309
                if ident.node.name != keywords::Invalid.name() {
2310 2311
                    bindings.insert(ident.node, outer_pat_id);
                    self.value_ribs.last_mut().unwrap().bindings.insert(ident.node, def);
2312
                }
2313
            }
2314
        }
2315

2316
        PathResolution::new(def)
2317
    }
2318

2319
    fn resolve_pattern_path<ExpectedFn>(&mut self,
2320 2321 2322 2323 2324 2325
                                        pat_id: NodeId,
                                        qself: Option<&QSelf>,
                                        path: &Path,
                                        namespace: Namespace,
                                        expected_fn: ExpectedFn,
                                        expected_what: &str)
2326 2327
        where ExpectedFn: FnOnce(Def) -> bool
    {
2328 2329 2330
        let resolution = if let Some(resolution) = self.resolve_possibly_assoc_item(pat_id,
                                                                        qself, path, namespace) {
            if resolution.depth == 0 {
2331
                if expected_fn(resolution.base_def) || resolution.base_def == Def::Err {
2332
                    resolution
2333
                } else {
2334 2335 2336 2337 2338 2339
                    resolve_error(
                        self,
                        path.span,
                        ResolutionError::PatPathUnexpected(expected_what,
                                                           resolution.kind_name(), path)
                    );
2340 2341
                    err_path_resolution()
                }
2342 2343 2344 2345
            } 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.
2346 2347 2348 2349
                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);
2350
                }
2351
                resolution
2352
            }
2353 2354 2355 2356 2357 2358 2359 2360 2361
        } else {
            if let Err(false) = self.resolve_path(pat_id, path, 0, namespace) {
                resolve_error(
                    self,
                    path.span,
                    ResolutionError::PatPathUnresolved(expected_what, path)
                );
            }
            err_path_resolution()
2362
        };
2363

2364 2365 2366 2367 2368 2369 2370 2371
        self.record_def(pat_id, resolution);
    }

    fn resolve_pattern(&mut self,
                       pat: &Pat,
                       pat_src: PatternSource,
                       // Maps idents to the node ID for the
                       // outermost pattern that binds them.
2372
                       bindings: &mut FnvHashMap<ast::Ident, NodeId>) {
2373
        // Visit all direct subpatterns of this pattern.
2374 2375 2376 2377 2378 2379
        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.
2380
                    let binding = self.resolve_ident_in_lexical_scope(ident.node, ValueNS, None)
2381
                                      .and_then(LexicalScopeBinding::item);
2382
                    let resolution = binding.map(NameBinding::def).and_then(|def| {
2383 2384
                        let always_binding = !pat_src.is_refutable() || opt_pat.is_some() ||
                                             bmode != BindingMode::ByValue(Mutability::Immutable);
2385
                        match def {
2386 2387 2388 2389
                            Def::StructCtor(_, CtorKind::Const) |
                            Def::VariantCtor(_, CtorKind::Const) |
                            Def::Const(..) if !always_binding => {
                                // A unit struct/variant or constant pattern.
2390 2391
                                let name = ident.node.name;
                                self.record_use(name, ValueNS, binding.unwrap(), ident.span);
2392
                                Some(PathResolution::new(def))
2393
                            }
2394
                            Def::StructCtor(..) | Def::VariantCtor(..) |
2395
                            Def::Const(..) | Def::Static(..) => {
2396
                                // A fresh binding that shadows something unacceptable.
2397
                                resolve_error(
2398
                                    self,
2399 2400
                                    ident.span,
                                    ResolutionError::BindingShadowsSomethingUnacceptable(
2401
                                        pat_src.descr(), ident.node.name, binding.unwrap())
2402
                                );
2403
                                None
2404
                            }
2405
                            Def::Local(..) | Def::Upvar(..) | Def::Fn(..) | Def::Err => {
2406 2407
                                // These entities are explicitly allowed
                                // to be shadowed by fresh bindings.
2408
                                None
2409 2410 2411
                            }
                            def => {
                                span_bug!(ident.span, "unexpected definition for an \
2412
                                                       identifier in pattern: {:?}", def);
2413
                            }
2414
                        }
2415
                    }).unwrap_or_else(|| {
2416
                        self.fresh_binding(ident, pat.id, outer_pat_id, pat_src, bindings)
2417
                    });
2418 2419

                    self.record_def(pat.id, resolution);
2420 2421
                }

2422
                PatKind::TupleStruct(ref path, ref pats, ddpos) => {
2423 2424
                    self.resolve_pattern_path(pat.id, None, path, ValueNS, |def| {
                        match def {
2425 2426 2427 2428 2429 2430
                            Def::StructCtor(_, CtorKind::Fn) |
                            Def::VariantCtor(_, CtorKind::Fn) => true,
                            // `UnitVariant(..)` is accepted for backward compatibility.
                            Def::StructCtor(_, CtorKind::Const) |
                            Def::VariantCtor(_, CtorKind::Const)
                                if pats.is_empty() && ddpos.is_some() => true,
2431
                            _ => false,
2432
                        }
2433
                    }, "tuple struct/variant");
2434 2435
                }

2436 2437
                PatKind::Path(ref qself, ref path) => {
                    self.resolve_pattern_path(pat.id, qself.as_ref(), path, ValueNS, |def| {
2438
                        match def {
2439 2440
                            Def::StructCtor(_, CtorKind::Const) |
                            Def::VariantCtor(_, CtorKind::Const) |
2441
                            Def::Const(..) | Def::AssociatedConst(..) => true,
2442
                            _ => false,
2443
                        }
2444
                    }, "unit struct/variant or constant");
2445 2446
                }

V
Vadim Petrochenkov 已提交
2447
                PatKind::Struct(ref path, ..) => {
2448 2449
                    self.resolve_pattern_path(pat.id, None, path, TypeNS, |def| {
                        match def {
2450
                            Def::Struct(..) | Def::Union(..) | Def::Variant(..) |
2451
                            Def::TyAlias(..) | Def::AssociatedTy(..) => true,
2452 2453 2454
                            _ => false,
                        }
                    }, "variant, struct or type alias");
2455
                }
2456 2457

                _ => {}
2458
            }
2459
            true
2460
        });
2461

2462
        visit::walk_pat(self, pat);
2463 2464
    }

2465 2466 2467
    /// Handles paths that may refer to associated items
    fn resolve_possibly_assoc_item(&mut self,
                                   id: NodeId,
2468
                                   maybe_qself: Option<&QSelf>,
2469
                                   path: &Path,
J
Jeffrey Seyfried 已提交
2470
                                   namespace: Namespace)
2471
                                   -> Option<PathResolution> {
2472 2473
        let max_assoc_types;

2474
        match maybe_qself {
2475 2476
            Some(qself) => {
                if qself.position == 0 {
2477 2478 2479
                    // 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)),
2480
                        depth: path.segments.len(),
2481
                    });
2482 2483 2484 2485 2486 2487 2488 2489
                }
                max_assoc_types = path.segments.len() - qself.position;
                // Make sure the trait is valid.
                let _ = self.resolve_trait_reference(id, path, max_assoc_types);
            }
            None => {
                max_assoc_types = path.segments.len();
            }
2490 2491 2492
        }

        let mut resolution = self.with_no_errors(|this| {
2493
            this.resolve_path(id, path, 0, namespace).ok()
2494 2495 2496 2497 2498 2499
        });
        for depth in 1..max_assoc_types {
            if resolution.is_some() {
                break;
            }
            self.with_no_errors(|this| {
2500 2501 2502 2503 2504 2505
                let partial_resolution = this.resolve_path(id, path, depth, TypeNS).ok();
                if let Some(Def::Mod(..)) = partial_resolution.map(|r| r.base_def) {
                    // Modules cannot have associated items
                } else {
                    resolution = partial_resolution;
                }
2506 2507
            });
        }
2508
        resolution
2509 2510
    }

2511
    /// Skips `path_depth` trailing segments, which is also reflected in the
2512
    /// returned value. See `hir::def::PathResolution` for more info.
J
Jeffrey Seyfried 已提交
2513
    fn resolve_path(&mut self, id: NodeId, path: &Path, path_depth: usize, namespace: Namespace)
2514
                    -> Result<PathResolution, bool /* true if an error was reported */ > {
2515 2516
        debug!("resolve_path(id={:?} path={:?}, path_depth={:?})", id, path, path_depth);

2517
        let span = path.span;
C
corentih 已提交
2518
        let segments = &path.segments[..path.segments.len() - path_depth];
2519

2520
        let mk_res = |def| PathResolution { base_def: def, depth: path_depth };
2521

2522
        if path.global {
2523
            let binding = self.resolve_crate_relative_path(span, segments, namespace);
2524
            return binding.map(|binding| mk_res(binding.def()));
2525 2526
        }

2527
        // Try to find a path to an item in a module.
2528
        let last_ident = segments.last().unwrap().identifier;
V
Cleanup  
Vadim Petrochenkov 已提交
2529 2530 2531 2532 2533 2534 2535
        // Resolve a single identifier with fallback to primitive types
        let resolve_identifier_with_fallback = |this: &mut Self, record_used| {
            let def = this.resolve_identifier(last_ident, namespace, record_used);
            match def {
                None | Some(LocalDef{def: Def::Mod(..), ..}) if namespace == TypeNS =>
                    this.primitive_type_table
                        .primitive_types
2536
                        .get(&last_ident.name)
V
Cleanup  
Vadim Petrochenkov 已提交
2537 2538 2539 2540
                        .map_or(def, |prim_ty| Some(LocalDef::from_def(Def::PrimTy(*prim_ty)))),
                _ => def
            }
        };
2541

2542 2543 2544 2545 2546 2547 2548
        if segments.len() == 1 {
            // 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 已提交
2549 2550
            //     u8::max_value() // OK, resolves to associated function <u8>::max_value,
            //                     // not to non-existent std::u8::max_value
2551 2552 2553 2554
            // }
            //
            // Such behavior is required for backward compatibility.
            // The same fallback is used when `a` resolves to nothing.
2555
            let def = resolve_identifier_with_fallback(self, Some(span)).ok_or(false);
2556
            return def.and_then(|def| self.adjust_local_def(def, span).ok_or(true)).map(mk_res);
N
Nick Cameron 已提交
2557
        }
2558

2559
        let unqualified_def = resolve_identifier_with_fallback(self, None);
2560 2561
        let qualified_binding = self.resolve_module_relative_path(span, segments, namespace);
        match (qualified_binding, unqualified_def) {
2562
            (Ok(binding), Some(ref ud)) if binding.def() == ud.def => {
N
Nick Cameron 已提交
2563 2564
                self.session
                    .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
C
corentih 已提交
2565 2566
                              id,
                              span,
N
Nick Cameron 已提交
2567 2568 2569
                              "unnecessary qualification".to_string());
            }
            _ => {}
2570
        }
N
Nick Cameron 已提交
2571

2572
        qualified_binding.map(|binding| mk_res(binding.def()))
2573 2574
    }

2575
    // Resolve a single identifier
F
Felix S. Klock II 已提交
2576
    fn resolve_identifier(&mut self,
2577
                          identifier: ast::Ident,
2578
                          namespace: Namespace,
2579
                          record_used: Option<Span>)
2580
                          -> Option<LocalDef> {
2581
        if identifier.name == keywords::Invalid.name() {
2582
            return None;
2583 2584
        }

2585 2586
        self.resolve_ident_in_lexical_scope(identifier, namespace, record_used)
            .map(LexicalScopeBinding::local_def)
2587 2588 2589
    }

    // Resolve a local definition, potentially adjusting for closures.
2590
    fn adjust_local_def(&mut self, local_def: LocalDef, span: Span) -> Option<Def> {
2591
        let ribs = match local_def.ribs {
C
corentih 已提交
2592 2593 2594
            Some((TypeNS, i)) => &self.type_ribs[i + 1..],
            Some((ValueNS, i)) => &self.value_ribs[i + 1..],
            _ => &[] as &[_],
2595 2596 2597
        };
        let mut def = local_def.def;
        match def {
2598
            Def::Upvar(..) => {
2599
                span_bug!(span, "unexpected {:?} in bindings", def)
2600
            }
2601
            Def::Local(def_id) => {
2602 2603
                for rib in ribs {
                    match rib.kind {
2604
                        NormalRibKind | ModuleRibKind(..) | MacroDefinition(..) => {
2605 2606 2607 2608
                            // Nothing to do. Continue.
                        }
                        ClosureRibKind(function_id) => {
                            let prev_def = def;
2609
                            let node_id = self.definitions.as_local_node_id(def_id).unwrap();
2610

C
corentih 已提交
2611 2612 2613
                            let seen = self.freevars_seen
                                           .entry(function_id)
                                           .or_insert_with(|| NodeMap());
2614
                            if let Some(&index) = seen.get(&node_id) {
2615
                                def = Def::Upvar(def_id, index, function_id);
2616 2617
                                continue;
                            }
C
corentih 已提交
2618 2619 2620
                            let vec = self.freevars
                                          .entry(function_id)
                                          .or_insert_with(|| vec![]);
2621
                            let depth = vec.len();
C
corentih 已提交
2622 2623 2624 2625
                            vec.push(Freevar {
                                def: prev_def,
                                span: span,
                            });
2626

2627
                            def = Def::Upvar(def_id, depth, function_id);
2628 2629
                            seen.insert(node_id, depth);
                        }
2630
                        ItemRibKind | MethodRibKind(_) => {
2631 2632 2633
                            // This was an attempt to access an upvar inside a
                            // named function item. This is not allowed, so we
                            // report an error.
C
corentih 已提交
2634 2635 2636
                            resolve_error(self,
                                          span,
                                          ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
2637 2638 2639 2640
                            return None;
                        }
                        ConstantItemRibKind => {
                            // Still doesn't deal with upvars
C
corentih 已提交
2641 2642 2643
                            resolve_error(self,
                                          span,
                                          ResolutionError::AttemptToUseNonConstantValueInConstant);
2644 2645 2646 2647 2648
                            return None;
                        }
                    }
                }
            }
2649
            Def::TyParam(..) | Def::SelfTy(..) => {
2650 2651
                for rib in ribs {
                    match rib.kind {
2652
                        NormalRibKind | MethodRibKind(_) | ClosureRibKind(..) |
2653
                        ModuleRibKind(..) | MacroDefinition(..) => {
2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675
                            // Nothing to do. Continue.
                        }
                        ItemRibKind => {
                            // This was an attempt to use a type parameter outside
                            // its scope.

                            resolve_error(self,
                                          span,
                                          ResolutionError::TypeParametersFromOuterFunction);
                            return None;
                        }
                        ConstantItemRibKind => {
                            // see #9186
                            resolve_error(self, span, ResolutionError::OuterTypeParameterContext);
                            return None;
                        }
                    }
                }
            }
            _ => {}
        }
        return Some(def);
2676 2677
    }

2678
    // resolve a "module-relative" path, e.g. a::b::c
F
Felix S. Klock II 已提交
2679
    fn resolve_module_relative_path(&mut self,
2680
                                    span: Span,
2681
                                    segments: &[ast::PathSegment],
2682
                                    namespace: Namespace)
2683 2684
                                    -> Result<&'a NameBinding<'a>,
                                              bool /* true if an error was reported */> {
C
corentih 已提交
2685 2686 2687 2688 2689 2690
        let module_path = segments.split_last()
                                  .unwrap()
                                  .1
                                  .iter()
                                  .map(|ps| ps.identifier.name)
                                  .collect::<Vec<_>>();
2691

2692
        let containing_module;
2693
        match self.resolve_module_path(&module_path, UseLexicalScope, Some(span)) {
2694
            Failed(err) => {
2695 2696 2697
                if let Some((span, msg)) = err {
                    resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
                }
2698
                return Err(true);
2699
            }
2700
            Indeterminate => return Err(false),
J
Jeffrey Seyfried 已提交
2701
            Success(resulting_module) => {
2702 2703 2704 2705
                containing_module = resulting_module;
            }
        }

2706
        let name = segments.last().unwrap().identifier.name;
2707 2708
        let result =
            self.resolve_name_in_module(containing_module, name, namespace, false, Some(span));
2709
        result.success().ok_or(false)
2710 2711
    }

2712 2713
    /// Invariant: This must be called only during main resolution, not during
    /// import resolution.
2714 2715 2716 2717 2718 2719
    fn resolve_crate_relative_path<T>(&mut self, span: Span, segments: &[T], namespace: Namespace)
                                      -> Result<&'a NameBinding<'a>,
                                                bool /* true if an error was reported */>
        where T: Named,
    {
        let module_path = segments.split_last().unwrap().1.iter().map(T::name).collect::<Vec<_>>();
2720
        let root_module = self.graph_root;
2721

2722
        let containing_module;
2723
        match self.resolve_module_path_from_root(root_module, &module_path, 0, Some(span)) {
2724
            Failed(err) => {
2725 2726 2727
                if let Some((span, msg)) = err {
                    resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
                }
2728
                return Err(true);
2729 2730
            }

2731
            Indeterminate => return Err(false),
2732

J
Jeffrey Seyfried 已提交
2733
            Success(resulting_module) => {
2734 2735 2736 2737
                containing_module = resulting_module;
            }
        }

2738
        let name = segments.last().unwrap().name();
2739 2740
        let result =
            self.resolve_name_in_module(containing_module, name, namespace, false, Some(span));
2741
        result.success().ok_or(false)
2742 2743
    }

C
corentih 已提交
2744 2745
    fn with_no_errors<T, F>(&mut self, f: F) -> T
        where F: FnOnce(&mut Resolver) -> T
J
Jorge Aparicio 已提交
2746
    {
2747
        self.emit_errors = false;
A
Alex Crichton 已提交
2748
        let rs = f(self);
2749 2750 2751 2752
        self.emit_errors = true;
        rs
    }

2753 2754
    // 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 已提交
2755
    // FIXME #34673: This needs testing.
2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779
    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| {
            this.value_ribs.push(Rib::new(ModuleRibKind(module)));
            this.type_ribs.push(Rib::new(ModuleRibKind(module)));
            f(this)
        })
    }

    fn with_empty_ribs<T, F>(&mut self, f: F) -> T
        where F: FnOnce(&mut Resolver<'a>) -> T,
    {
        let value_ribs = replace(&mut self.value_ribs, Vec::new());
        let type_ribs = replace(&mut self.type_ribs, Vec::new());
        let label_ribs = replace(&mut self.label_ribs, Vec::new());

        let result = f(self);
        self.value_ribs = value_ribs;
        self.type_ribs = type_ribs;
        self.label_ribs = label_ribs;
        result
    }

2780
    fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
2781
        fn extract_node_id(t: &Ty) -> Option<NodeId> {
2782
            match t.node {
2783 2784
                TyKind::Path(None, _) => Some(t.id),
                TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
2785 2786 2787 2788 2789 2790 2791
                // 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,
            }
        }

2792
        if let Some(node_id) = self.current_self_type.as_ref().and_then(extract_node_id) {
2793
            // Look for a field with the same name in the current self_type.
2794 2795
            if let Some(resolution) = self.def_map.get(&node_id) {
                match resolution.base_def {
2796
                    Def::Struct(did) | Def::Union(did) if resolution.depth == 0 => {
V
Vadim Petrochenkov 已提交
2797 2798
                        if let Some(field_names) = self.field_names.get(&did) {
                            if field_names.iter().any(|&field_name| name == field_name) {
2799 2800
                                return Field;
                            }
2801
                        }
2802
                    }
2803 2804
                    _ => {}
                }
2805
            }
2806 2807 2808
        }

        // Look for a method in the current trait.
2809
        if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
2810 2811
            if let Some(&is_static_method) = self.trait_item_map.get(&(name, trait_did)) {
                if is_static_method {
2812
                    return TraitMethod(path_names_to_string(&trait_ref.path, 0));
2813 2814
                } else {
                    return TraitItem;
2815 2816 2817 2818 2819 2820 2821
                }
            }
        }

        NoSuggestion
    }

2822
    fn find_best_match(&mut self, name: &str) -> SuggestionType {
2823
        if let Some(macro_name) = self.macro_names.iter().find(|n| n.as_str() == name) {
2824 2825 2826
            return SuggestionType::Macro(format!("{}!", macro_name));
        }

2827 2828 2829
        let names = self.value_ribs
                    .iter()
                    .rev()
2830
                    .flat_map(|rib| rib.bindings.keys().map(|ident| &ident.name));
2831

2832
        if let Some(found) = find_best_match_for_name(names, name, None) {
J
Jonas Schievink 已提交
2833
            if name != found {
2834
                return SuggestionType::Function(found);
2835
            }
2836
        } SuggestionType::NotFound
2837 2838
    }

2839 2840
    fn resolve_labeled_block(&mut self, label: Option<ast::Ident>, id: NodeId, block: &Block) {
        if let Some(label) = label {
2841
            let def = Def::Label(id);
2842 2843 2844 2845 2846 2847 2848 2849 2850
            self.with_label_rib(|this| {
                this.label_ribs.last_mut().unwrap().bindings.insert(label, def);
                this.visit_block(block);
            });
        } else {
            self.visit_block(block);
        }
    }

2851
    fn resolve_expr(&mut self, expr: &Expr, parent: Option<&Expr>) {
P
Patrick Walton 已提交
2852 2853
        // First, record candidate traits for this expression if it could
        // result in the invocation of a method call.
2854 2855 2856

        self.record_candidate_traits_for_expr_if_necessary(expr);

2857
        // Next, resolve the node.
2858
        match expr.node {
2859
            ExprKind::Path(ref maybe_qself, ref path) => {
2860 2861
                // This is a local path in the value namespace. Walk through
                // scopes looking for it.
2862 2863
                if let Some(path_res) = self.resolve_possibly_assoc_item(expr.id,
                                                            maybe_qself.as_ref(), path, ValueNS) {
2864
                    // Check if struct variant
2865 2866 2867
                    let is_struct_variant = match path_res.base_def {
                        Def::VariantCtor(_, CtorKind::Fictive) => true,
                        _ => false,
2868 2869
                    };
                    if is_struct_variant {
2870
                        let path_name = path_names_to_string(path, 0);
2871

N
Nick Cameron 已提交
2872 2873
                        let mut err = resolve_struct_error(self,
                                        expr.span,
J
Jonas Schievink 已提交
2874
                                        ResolutionError::StructVariantUsedAsFunction(&path_name));
2875

C
corentih 已提交
2876
                        let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
2877 2878
                                          path_name);
                        if self.emit_errors {
2879
                            err.help(&msg);
2880
                        } else {
N
Nick Cameron 已提交
2881
                            err.span_help(expr.span, &msg);
2882
                        }
N
Nick Cameron 已提交
2883
                        err.emit();
2884
                        self.record_def(expr.id, err_path_resolution());
2885
                    } else {
2886
                        // Write the result into the def map.
2887
                        debug!("(resolving expr) resolved `{}`",
2888
                               path_names_to_string(path, 0));
2889

2890 2891
                        // Partial resolutions will need the set of traits in scope,
                        // so they can be completed during typeck.
2892
                        if path_res.depth != 0 {
2893
                            let method_name = path.segments.last().unwrap().identifier.name;
2894
                            let traits = self.get_traits_containing_item(method_name);
2895 2896 2897
                            self.trait_map.insert(expr.id, traits);
                        }

2898
                        self.record_def(expr.id, path_res);
2899
                    }
2900 2901
                } else {
                    // Be helpful if the name refers to a struct
2902
                    let path_name = path_names_to_string(path, 0);
2903
                    let type_res = self.with_no_errors(|this| {
J
Jeffrey Seyfried 已提交
2904
                        this.resolve_path(expr.id, path, 0, TypeNS)
2905
                    });
2906 2907

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

2909
                    if let Ok(Def::Struct(..)) = type_res.map(|r| r.base_def) {
J
Jeffrey Seyfried 已提交
2910 2911
                        let error_variant =
                            ResolutionError::StructVariantUsedAsFunction(&path_name);
2912 2913 2914 2915 2916 2917
                        let mut err = resolve_struct_error(self, expr.span, error_variant);

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

                        if self.emit_errors {
2918
                            err.help(&msg);
2919 2920 2921 2922 2923 2924 2925 2926 2927
                        } else {
                            err.span_help(expr.span, &msg);
                        }
                        err.emit();
                    } else {
                        // Keep reporting some errors even if they're ignored above.
                        if let Err(true) = self.resolve_path(expr.id, path, 0, ValueNS) {
                            // `resolve_path` already reported the error
                        } else {
2928
                            let mut method_scope = false;
2929
                            let mut is_static = false;
2930 2931
                            self.value_ribs.iter().rev().all(|rib| {
                                method_scope = match rib.kind {
2932 2933 2934 2935
                                    MethodRibKind(is_static_) => {
                                        is_static = is_static_;
                                        true
                                    }
2936 2937 2938 2939 2940
                                    ItemRibKind | ConstantItemRibKind => false,
                                    _ => return true, // Keep advancing
                                };
                                false // Stop advancing
                            });
2941

2942
                            if method_scope &&
2943
                                    &path_name[..] == keywords::SelfValue.name().as_str() {
C
corentih 已提交
2944 2945 2946
                                resolve_error(self,
                                              expr.span,
                                              ResolutionError::SelfNotAvailableInStaticMethod);
2947 2948
                            } else {
                                let last_name = path.segments.last().unwrap().identifier.name;
2949 2950
                                let (mut msg, is_field) =
                                    match self.find_fallback_in_self_type(last_name) {
2951 2952 2953
                                    NoSuggestion => {
                                        // limit search to 5 to reduce the number
                                        // of stupid suggestions
2954
                                        (match self.find_best_match(&path_name) {
2955 2956 2957 2958 2959
                                            SuggestionType::Macro(s) => {
                                                format!("the macro `{}`", s)
                                            }
                                            SuggestionType::Function(s) => format!("`{}`", s),
                                            SuggestionType::NotFound => "".to_string(),
2960 2961 2962 2963 2964 2965 2966 2967
                                        }, false)
                                    }
                                    Field => {
                                        (if is_static && method_scope {
                                            "".to_string()
                                        } else {
                                            format!("`self.{}`", path_name)
                                        }, true)
2968
                                    }
2969
                                    TraitItem => (format!("to call `self.{}`", path_name), false),
2970
                                    TraitMethod(path_str) =>
2971
                                        (format!("to call `{}::{}`", path_str, path_name), false),
2972 2973
                                };

2974
                                let mut context =  UnresolvedNameContext::Other;
G
ggomez 已提交
2975
                                let mut def = Def::Err;
2976
                                if !msg.is_empty() {
J
Jonathan Turner 已提交
2977
                                    msg = format!("did you mean {}?", msg);
2978
                                } else {
2979
                                    // we display a help message if this is a module
2980 2981 2982 2983
                                    let name_path = path.segments.iter()
                                                        .map(|seg| seg.identifier.name)
                                                        .collect::<Vec<_>>();

2984
                                    match self.resolve_module_path(&name_path[..],
J
Jeffrey Seyfried 已提交
2985
                                                                   UseLexicalScope,
2986
                                                                   Some(expr.span)) {
G
ggomez 已提交
2987
                                        Success(e) => {
J
Jeffrey Seyfried 已提交
2988
                                            if let Some(def_type) = e.def() {
G
ggomez 已提交
2989 2990
                                                def = def_type;
                                            }
2991
                                            context = UnresolvedNameContext::PathIsMod(parent);
2992 2993 2994
                                        },
                                        _ => {},
                                    };
2995
                                }
2996

2997 2998
                                resolve_error(self,
                                              expr.span,
2999 3000 3001 3002 3003 3004
                                              ResolutionError::UnresolvedName {
                                                  path: &path_name,
                                                  message: &msg,
                                                  context: context,
                                                  is_static_method: method_scope && is_static,
                                                  is_field: is_field,
G
ggomez 已提交
3005
                                                  def: def,
3006
                                              });
3007
                            }
V
Vincent Belliard 已提交
3008
                        }
3009 3010 3011
                    }
                }

3012
                visit::walk_expr(self, expr);
3013 3014
            }

V
Vadim Petrochenkov 已提交
3015
            ExprKind::Struct(ref path, ..) => {
3016 3017 3018
                // Resolve the path to the structure it goes to. We don't
                // check to ensure that the path is actually a structure; that
                // is checked later during typeck.
J
Jeffrey Seyfried 已提交
3019
                match self.resolve_path(expr.id, path, 0, TypeNS) {
3020 3021 3022
                    Ok(definition) => self.record_def(expr.id, definition),
                    Err(true) => self.record_def(expr.id, err_path_resolution()),
                    Err(false) => {
3023
                        debug!("(resolving expression) didn't find struct def",);
3024

3025 3026
                        resolve_error(self,
                                      path.span,
3027
                                      ResolutionError::DoesNotNameAStruct(
J
Jonas Schievink 已提交
3028
                                                                &path_names_to_string(path, 0))
3029
                                     );
3030
                        self.record_def(expr.id, err_path_resolution());
3031 3032 3033
                    }
                }

3034
                visit::walk_expr(self, expr);
3035 3036
            }

V
Vadim Petrochenkov 已提交
3037
            ExprKind::Loop(_, Some(label)) | ExprKind::While(.., Some(label)) => {
3038
                self.with_label_rib(|this| {
3039
                    let def = Def::Label(expr.id);
3040

3041
                    {
3042
                        let rib = this.label_ribs.last_mut().unwrap();
3043
                        rib.bindings.insert(label.node, def);
3044
                    }
3045

3046
                    visit::walk_expr(this, expr);
3047
                })
3048 3049
            }

3050
            ExprKind::Break(Some(label)) | ExprKind::Continue(Some(label)) => {
3051
                match self.search_label(label.node) {
3052
                    None => {
3053
                        self.record_def(expr.id, err_path_resolution());
3054
                        resolve_error(self,
3055 3056
                                      label.span,
                                      ResolutionError::UndeclaredLabel(&label.node.name.as_str()))
3057
                    }
3058
                    Some(def @ Def::Label(_)) => {
3059
                        // Since this def is a label, it is never read.
3060
                        self.record_def(expr.id, PathResolution::new(def))
3061 3062
                    }
                    Some(_) => {
3063
                        span_bug!(expr.span, "label wasn't mapped to a label def!")
3064 3065 3066
                    }
                }
            }
3067 3068 3069 3070 3071

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

                self.value_ribs.push(Rib::new(NormalRibKind));
3072
                self.resolve_pattern(pattern, PatternSource::IfLet, &mut FnvHashMap());
3073 3074 3075 3076 3077 3078 3079 3080 3081
                self.visit_block(if_block);
                self.value_ribs.pop();

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

            ExprKind::WhileLet(ref pattern, ref subexpression, ref block, label) => {
                self.visit_expr(subexpression);
                self.value_ribs.push(Rib::new(NormalRibKind));
3082
                self.resolve_pattern(pattern, PatternSource::WhileLet, &mut FnvHashMap());
3083

3084
                self.resolve_labeled_block(label.map(|l| l.node), expr.id, block);
3085 3086 3087 3088 3089 3090 3091

                self.value_ribs.pop();
            }

            ExprKind::ForLoop(ref pattern, ref subexpression, ref block, label) => {
                self.visit_expr(subexpression);
                self.value_ribs.push(Rib::new(NormalRibKind));
3092
                self.resolve_pattern(pattern, PatternSource::For, &mut FnvHashMap());
3093

3094
                self.resolve_labeled_block(label.map(|l| l.node), expr.id, block);
3095 3096 3097 3098 3099

                self.value_ribs.pop();
            }

            ExprKind::Field(ref subexpression, _) => {
3100 3101
                self.resolve_expr(subexpression, Some(expr));
            }
3102
            ExprKind::MethodCall(_, ref types, ref arguments) => {
3103 3104 3105 3106 3107 3108 3109 3110 3111
                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);
                }
            }
3112

B
Brian Anderson 已提交
3113
            _ => {
3114
                visit::walk_expr(self, expr);
3115 3116 3117 3118
            }
        }
    }

E
Eduard Burtescu 已提交
3119
    fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3120
        match expr.node {
3121
            ExprKind::Field(_, name) => {
3122 3123 3124 3125
                // 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.
3126
                let traits = self.get_traits_containing_item(name.node.name);
3127
                self.trait_map.insert(expr.id, traits);
3128
            }
V
Vadim Petrochenkov 已提交
3129
            ExprKind::MethodCall(name, ..) => {
C
corentih 已提交
3130
                debug!("(recording candidate traits for expr) recording traits for {}",
3131
                       expr.id);
3132
                let traits = self.get_traits_containing_item(name.node.name);
3133
                self.trait_map.insert(expr.id, traits);
3134
            }
3135
            _ => {
3136 3137 3138 3139 3140
                // Nothing to do.
            }
        }
    }

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

S
Seo Sanghyeon 已提交
3144 3145 3146 3147
        fn add_trait_info(found_traits: &mut Vec<TraitCandidate>,
                          trait_def_id: DefId,
                          import_id: Option<NodeId>,
                          name: Name) {
3148
            debug!("(adding trait info) found trait {:?} for method '{}'",
C
corentih 已提交
3149 3150
                   trait_def_id,
                   name);
S
Seo Sanghyeon 已提交
3151 3152 3153 3154
            found_traits.push(TraitCandidate {
                def_id: trait_def_id,
                import_id: import_id,
            });
E
Eduard Burtescu 已提交
3155
        }
3156

3157
        let mut found_traits = Vec::new();
J
Jeffrey Seyfried 已提交
3158 3159 3160
        // 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 已提交
3161
                add_trait_info(&mut found_traits, trait_def_id, None, name);
E
Eduard Burtescu 已提交
3162
            }
J
Jeffrey Seyfried 已提交
3163
        }
3164

J
Jeffrey Seyfried 已提交
3165 3166
        let mut search_module = self.current_module;
        loop {
E
Eduard Burtescu 已提交
3167
            // Look for trait children.
3168
            let mut search_in_module = |this: &mut Self, module: Module<'a>| {
J
Jeffrey Seyfried 已提交
3169 3170 3171
                let mut traits = module.traits.borrow_mut();
                if traits.is_none() {
                    let mut collected_traits = Vec::new();
3172
                    module.for_each_child(|name, ns, binding| {
J
Jeffrey Seyfried 已提交
3173
                        if ns != TypeNS { return }
3174
                        if let Def::Trait(_) = binding.def() {
3175
                            collected_traits.push((name, binding));
J
Jeffrey Seyfried 已提交
3176 3177 3178
                        }
                    });
                    *traits = Some(collected_traits.into_boxed_slice());
3179
                }
J
Jeffrey Seyfried 已提交
3180

3181
                for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
3182
                    let trait_def_id = binding.def().def_id();
3183
                    if this.trait_item_map.contains_key(&(name, trait_def_id)) {
S
Seo Sanghyeon 已提交
3184 3185 3186
                        let mut import_id = None;
                        if let NameBindingKind::Import { directive, .. } = binding.kind {
                            let id = directive.id;
3187
                            this.maybe_unused_trait_imports.insert(id);
3188
                            this.add_to_glob_map(id, trait_name);
S
Seo Sanghyeon 已提交
3189 3190 3191
                            import_id = Some(id);
                        }
                        add_trait_info(&mut found_traits, trait_def_id, import_id, name);
J
Jeffrey Seyfried 已提交
3192 3193 3194
                    }
                }
            };
3195
            search_in_module(self, search_module);
3196

J
Jeffrey Seyfried 已提交
3197 3198 3199
            if let ModuleKind::Block(..) = search_module.kind {
                search_module = search_module.parent.unwrap();
            } else {
3200
                if !search_module.no_implicit_prelude {
J
Jeffrey Seyfried 已提交
3201
                    self.prelude.map(|prelude| search_in_module(self, prelude));
3202
                }
J
Jeffrey Seyfried 已提交
3203
                break;
E
Eduard Burtescu 已提交
3204
            }
3205 3206
        }

E
Eduard Burtescu 已提交
3207
        found_traits
3208 3209
    }

3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229
    /// 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() {
3230
            self.populate_module_if_necessary(in_module);
3231 3232 3233 3234 3235 3236 3237

            in_module.for_each_child(|name, ns, name_binding| {

                // avoid imports entirely
                if name_binding.is_import() { return; }

                // collect results based on the filter function
3238 3239
                if name == lookup_name && ns == namespace {
                    if filter_fn(name_binding.def()) {
3240
                        // create the path
3241
                        let ident = ast::Ident::with_empty_ctxt(name);
3242 3243 3244 3245 3246
                        let params = PathParameters::none();
                        let segment = PathSegment {
                            identifier: ident,
                            parameters: params,
                        };
3247
                        let span = name_binding.span;
3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261
                        let mut segms = path_segments.clone();
                        segms.push(segment);
                        let path = Path {
                            span: span,
                            global: true,
                            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)
3262
                        if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
3263 3264 3265 3266 3267 3268
                            lookup_results.push(path);
                        }
                    }
                }

                // collect submodules to explore
3269
                if let Ok(module) = name_binding.module() {
3270
                    // form the path
J
Jeffrey Seyfried 已提交
3271 3272 3273
                    let path_segments = match module.kind {
                        _ if module.parent.is_none() => path_segments.clone(),
                        ModuleKind::Def(_, name) => {
3274
                            let mut paths = path_segments.clone();
3275
                            let ident = ast::Ident::with_empty_ctxt(name);
3276 3277 3278 3279 3280 3281 3282 3283
                            let params = PathParameters::none();
                            let segm = PathSegment {
                                identifier: ident,
                                parameters: params,
                            };
                            paths.push(segm);
                            paths
                        }
3284
                        _ => bug!(),
3285 3286
                    };

3287
                    if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
3288
                        // add the module to the lookup
3289
                        let is_extern = in_module_is_extern || name_binding.is_extern_crate();
J
Jeffrey Seyfried 已提交
3290
                        if !worklist.iter().any(|&(m, ..)| m.def() == module.def()) {
3291 3292
                            worklist.push((module, path_segments, is_extern));
                        }
3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303
                    }
                }
            })
        }

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

3304 3305
    fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
        debug!("(recording def) recording {:?} for {}", resolution, node_id);
3306
        if let Some(prev_res) = self.def_map.insert(node_id, resolution) {
3307
            panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution);
3308
        }
3309 3310
    }

3311
    fn resolve_visibility(&mut self, vis: &ast::Visibility) -> ty::Visibility {
3312
        let (path, id) = match *vis {
3313 3314 3315
            ast::Visibility::Public => return ty::Visibility::Public,
            ast::Visibility::Crate(_) => return ty::Visibility::Restricted(ast::CRATE_NODE_ID),
            ast::Visibility::Restricted { ref path, id } => (path, id),
3316
            ast::Visibility::Inherited => {
J
Jeffrey Seyfried 已提交
3317
                return ty::Visibility::Restricted(self.current_module.normal_ancestor_id.unwrap());
3318
            }
3319 3320 3321
        };

        let segments: Vec<_> = path.segments.iter().map(|seg| seg.identifier.name).collect();
3322
        let mut path_resolution = err_path_resolution();
3323
        let vis = match self.resolve_module_path(&segments, DontUseLexicalScope, Some(path.span)) {
3324
            Success(module) => {
J
Jeffrey Seyfried 已提交
3325
                path_resolution = PathResolution::new(module.def().unwrap());
J
Jeffrey Seyfried 已提交
3326
                ty::Visibility::Restricted(module.normal_ancestor_id.unwrap())
3327
            }
3328 3329 3330 3331 3332
            Indeterminate => unreachable!(),
            Failed(err) => {
                if let Some((span, msg)) = err {
                    self.session.span_err(span, &format!("failed to resolve module path. {}", msg));
                }
3333 3334 3335
                ty::Visibility::Public
            }
        };
3336
        self.def_map.insert(id, path_resolution);
3337 3338 3339 3340 3341 3342 3343
        if !self.is_accessible(vis) {
            let msg = format!("visibilities can only be restricted to ancestor modules");
            self.session.span_err(path.span, &msg);
        }
        vis
    }

3344
    fn is_accessible(&self, vis: ty::Visibility) -> bool {
J
Jeffrey Seyfried 已提交
3345
        vis.is_accessible_from(self.current_module.normal_ancestor_id.unwrap(), self)
3346 3347
    }

3348
    fn is_accessible_from(&self, vis: ty::Visibility, module: Module<'a>) -> bool {
J
Jeffrey Seyfried 已提交
3349
        vis.is_accessible_from(module.normal_ancestor_id.unwrap(), self)
3350 3351
    }

3352
    fn report_errors(&self) {
3353
        let mut reported_spans = FnvHashSet();
3354

J
Jeffrey Seyfried 已提交
3355
        for &AmbiguityError { span, name, b1, b2 } in &self.ambiguity_errors {
3356 3357 3358 3359 3360 3361 3362 3363 3364 3365
            if !reported_spans.insert(span) { continue }
            let msg1 = format!("`{}` could resolve to the name imported here", name);
            let msg2 = format!("`{}` could also resolve to the name imported here", name);
            self.session.struct_span_err(span, &format!("`{}` is ambiguous", name))
                .span_note(b1.span, &msg1)
                .span_note(b2.span, &msg2)
                .note(&format!("Consider adding an explicit import of `{}` to disambiguate", name))
                .emit();
        }

3366 3367 3368 3369 3370 3371 3372 3373
        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.
                let node_id = binding.module().unwrap().extern_crate_id.unwrap();
                let msg = format!("extern crate `{}` is private", name);
                self.session.add_lint(lint::builtin::INACCESSIBLE_EXTERN_CRATE, node_id, span, msg);
            } else {
3374
                let def = binding.def();
3375 3376 3377 3378
                self.session.span_err(span, &format!("{} `{}` is private", def.kind_name(), name));
            }
        }
    }
3379

3380 3381 3382 3383 3384 3385 3386
    fn report_conflict(&self,
                       parent: Module,
                       name: Name,
                       ns: Namespace,
                       binding: &NameBinding,
                       old_binding: &NameBinding) {
        // Error on the second of two conflicting names
3387
        if old_binding.span.lo > binding.span.lo {
3388 3389 3390
            return self.report_conflict(parent, name, ns, old_binding, binding);
        }

J
Jeffrey Seyfried 已提交
3391 3392 3393 3394
        let container = match parent.kind {
            ModuleKind::Def(Def::Mod(_), _) => "module",
            ModuleKind::Def(Def::Trait(_), _) => "trait",
            ModuleKind::Block(..) => "block",
3395 3396 3397 3398 3399 3400 3401 3402
            _ => "enum",
        };

        let (participle, noun) = match old_binding.is_import() || old_binding.is_extern_crate() {
            true => ("imported", "import"),
            false => ("defined", "definition"),
        };

3403
        let span = binding.span;
3404 3405 3406
        let msg = {
            let kind = match (ns, old_binding.module()) {
                (ValueNS, _) => "a value",
3407 3408 3409
                (TypeNS, Ok(module)) if module.extern_crate_id.is_some() => "an extern crate",
                (TypeNS, Ok(module)) if module.is_normal() => "a module",
                (TypeNS, Ok(module)) if module.is_trait() => "a trait",
3410 3411 3412 3413 3414 3415 3416
                (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()) {
3417 3418 3419 3420 3421
            (true, true) => {
                let mut e = struct_span_err!(self.session, span, E0259, "{}", msg);
                e.span_label(span, &format!("`{}` was already imported", name));
                e
            },
C
crypto-universe 已提交
3422 3423 3424 3425 3426
            (true, _) | (_, true) if binding.is_import() || old_binding.is_import() => {
                let mut e = struct_span_err!(self.session, span, E0254, "{}", msg);
                e.span_label(span, &"already imported");
                e
            },
M
Mohit Agarwal 已提交
3427 3428 3429 3430 3431
            (true, _) | (_, true) => {
                let mut e = struct_span_err!(self.session, span, E0260, "{}", msg);
                e.span_label(span, &format!("`{}` already imported", name));
                e
            },
3432
            _ => match (old_binding.is_import(), binding.is_import()) {
T
trixnz 已提交
3433 3434 3435 3436 3437
                (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 已提交
3438 3439 3440 3441 3442
                (true, true) => {
                    let mut e = struct_span_err!(self.session, span, E0252, "{}", msg);
                    e.span_label(span, &format!("already imported"));
                    e
                },
3443
                _ => {
3444 3445 3446
                    let mut e = struct_span_err!(self.session, span, E0255, "{}", msg);
                    e.span_label(span, &format!("`{}` was already imported", name));
                    e
3447
                }
3448 3449 3450
            },
        };

3451
        if old_binding.span != syntax_pos::DUMMY_SP {
3452
            err.span_label(old_binding.span, &format!("previous {} of `{}` here", noun, name));
3453 3454 3455 3456
        }
        err.emit();
    }
}
3457 3458 3459 3460 3461 3462 3463 3464 3465 3466

fn names_to_string(names: &[Name]) -> String {
    let mut first = true;
    let mut result = String::new();
    for name in names {
        if first {
            first = false
        } else {
            result.push_str("::")
        }
3467
        result.push_str(&name.as_str());
C
corentih 已提交
3468
    }
3469 3470 3471 3472
    result
}

fn path_names_to_string(path: &Path, depth: usize) -> String {
C
corentih 已提交
3473
    let names: Vec<ast::Name> = path.segments[..path.segments.len() - depth]
3474 3475 3476 3477 3478 3479
                                    .iter()
                                    .map(|seg| seg.identifier.name)
                                    .collect();
    names_to_string(&names[..])
}

3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502
/// 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 {
3503
                session.help(
T
tiehuis 已提交
3504
                    &format!("you can import it into scope: `use {};`.",
3505 3506 3507
                        &path_strings[0]),
                );
            } else {
3508
                session.help("you can import several candidates \
3509 3510 3511 3512 3513
                    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 {
3514
                        session.help(
3515 3516 3517 3518
                            &format!("  and {} other candidates", count).to_string(),
                        );
                        break;
                    } else {
3519
                        session.help(
3520 3521 3522 3523 3524 3525 3526 3527
                            &format!("  `{}`", path_string).to_string(),
                        );
                    }
                }
            }
        }
    } else {
        // nothing found:
3528
        session.help(
3529 3530 3531 3532 3533 3534 3535
            &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()),
        );
    };
}

3536
/// A somewhat inefficient routine to obtain the name of a module.
3537
fn module_to_string(module: Module) -> String {
3538 3539
    let mut names = Vec::new();

3540
    fn collect_mod(names: &mut Vec<ast::Name>, module: Module) {
J
Jeffrey Seyfried 已提交
3541 3542
        if let ModuleKind::Def(_, name) = module.kind {
            if let Some(parent) = module.parent {
3543
                names.push(name);
J
Jeffrey Seyfried 已提交
3544
                collect_mod(names, parent);
3545
            }
J
Jeffrey Seyfried 已提交
3546 3547 3548
        } else {
            // danger, shouldn't be ident?
            names.push(token::intern("<opaque>"));
J
Jeffrey Seyfried 已提交
3549
            collect_mod(names, module.parent.unwrap());
3550 3551 3552 3553
        }
    }
    collect_mod(&mut names, module);

3554
    if names.is_empty() {
3555 3556 3557 3558 3559
        return "???".to_string();
    }
    names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
}

3560
fn err_path_resolution() -> PathResolution {
3561
    PathResolution::new(Def::Err)
3562 3563
}

N
Niko Matsakis 已提交
3564
#[derive(PartialEq,Copy, Clone)]
3565 3566
pub enum MakeGlobMap {
    Yes,
C
corentih 已提交
3567
    No,
3568 3569
}

3570
__build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }