lib.rs 145.7 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)]
22
#![cfg_attr(stage0, 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
use rustc::hir::{Freevar, FreevarMap, TraitCandidate, TraitMap, GlobMap};
54
use rustc::util::nodemap::{NodeMap, NodeSet, FxHashMap, FxHashSet};
55

J
Jeffrey Seyfried 已提交
56
use syntax::ext::hygiene::{Mark, SyntaxContext};
57
use syntax::ast::{self, FloatTy};
J
Jeffrey Seyfried 已提交
58
use syntax::ast::{CRATE_NODE_ID, Name, NodeId, Ident, SpannedIdent, IntTy, UintTy};
J
Jeffrey Seyfried 已提交
59
use syntax::ext::base::SyntaxExtension;
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, ImportDirectiveSubclass, NameResolution, ImportResolver};
J
Jeffrey Seyfried 已提交
80
use macros::{InvocationData, LegacyBinding, LegacyScope};
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, &'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 E0423: is a struct variant name, but this expression uses it like a function name
133
    StructVariantUsedAsFunction(&'a str),
134
    /// error E0424: `self` is not available in a static method
135
    SelfNotAvailableInStaticMethod,
136
    /// error E0425: unresolved name
137 138 139 140 141
    UnresolvedName {
        path: &'a str,
        message: &'a str,
        context: UnresolvedNameContext<'a>,
        is_static_method: bool,
G
ggomez 已提交
142 143
        is_field: bool,
        def: Def,
144
    },
145
    /// error E0426: use of undeclared label
146
    UndeclaredLabel(&'a str),
147
    /// error E0429: `self` imports are only allowed within a { } list
148
    SelfImportsOnlyAllowedWithin,
149
    /// error E0430: `self` import can only appear once in the list
150
    SelfImportCanOnlyAppearOnceInTheList,
151
    /// error E0431: `self` import can only appear in an import list with a non-empty prefix
152
    SelfImportOnlyInImportListWithNonEmptyPrefix,
153
    /// error E0432: unresolved import
154
    UnresolvedImport(Option<(&'a str, &'a str)>),
155
    /// error E0433: failed to resolve
156
    FailedToResolve(&'a str),
157
    /// error E0434: can't capture dynamic environment in a fn item
158
    CannotCaptureDynamicEnvironmentInFnItem,
159
    /// error E0435: attempt to use a non-constant value in a constant
160
    AttemptToUseNonConstantValueInConstant,
161
    /// error E0530: X bindings cannot shadow Ys
162
    BindingShadowsSomethingUnacceptable(&'a str, Name, &'a NameBinding<'a>),
163
    /// error E0531: unresolved pattern path kind `name`
164
    PatPathUnresolved(&'a str, &'a Path),
165
    /// error E0532: expected pattern path kind, found another pattern path kind
166
    PatPathUnexpected(&'a str, &'a str, &'a Path),
167 168
}

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

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

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

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

N
Nick Cameron 已提交
198
    match resolution_error {
199
        ResolutionError::TypeParametersFromOuterFunction => {
200 201 202 203 204
            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");
205
            err.span_label(span, &format!("use of type variable from outer function"));
206
            err
C
corentih 已提交
207
        }
208
        ResolutionError::OuterTypeParameterContext => {
N
Nick Cameron 已提交
209 210 211 212
            struct_span_err!(resolver.session,
                             span,
                             E0402,
                             "cannot use an outer type parameter in this context")
C
corentih 已提交
213
        }
C
Chris Stankus 已提交
214 215 216 217 218 219 220 221 222 223 224
        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 已提交
225
        }
226
        ResolutionError::IsNotATrait(name, kind_name) => {
R
Ryan Scott 已提交
227 228 229 230 231
            let mut err = struct_span_err!(resolver.session,
                                           span,
                                           E0404,
                                           "`{}` is not a trait",
                                           name);
232
            err.span_label(span, &format!("expected trait, found {}", kind_name));
R
Ryan Scott 已提交
233
            err
C
corentih 已提交
234
        }
235 236 237 238 239 240
        ResolutionError::UndeclaredTraitName(name, candidates) => {
            let mut err = struct_span_err!(resolver.session,
                                           span,
                                           E0405,
                                           "trait `{}` is not in scope",
                                           name);
241
            show_candidates(&mut err, &candidates);
242
            err.span_label(span, &format!("`{}` is not in scope", name));
243
            err
C
corentih 已提交
244
        }
245
        ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
C
crypto-universe 已提交
246 247 248 249 250 251
            let mut err = struct_span_err!(resolver.session,
                                           span,
                                           E0407,
                                           "method `{}` is not a member of trait `{}`",
                                           method,
                                           trait_);
252
            err.span_label(span, &format!("not a member of trait `{}`", trait_));
C
crypto-universe 已提交
253
            err
C
corentih 已提交
254
        }
255
        ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
S
Shyam Sundar B 已提交
256
            let mut err = struct_span_err!(resolver.session,
N
Nick Cameron 已提交
257 258 259 260
                             span,
                             E0437,
                             "type `{}` is not a member of trait `{}`",
                             type_,
S
Shyam Sundar B 已提交
261
                             trait_);
262
            err.span_label(span, &format!("not a member of trait `{}`", trait_));
S
Shyam Sundar B 已提交
263
            err
C
corentih 已提交
264
        }
265
        ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
S
Shyam Sundar B 已提交
266
            let mut err = struct_span_err!(resolver.session,
N
Nick Cameron 已提交
267 268 269 270
                             span,
                             E0438,
                             "const `{}` is not a member of trait `{}`",
                             const_,
S
Shyam Sundar B 已提交
271
                             trait_);
272
            err.span_label(span, &format!("not a member of trait `{}`", trait_));
S
Shyam Sundar B 已提交
273
            err
C
corentih 已提交
274
        }
M
Manish Goregaokar 已提交
275
        ResolutionError::VariableNotBoundInPattern(variable_name, from, to) => {
276
            let mut err = struct_span_err!(resolver.session,
N
Nick Cameron 已提交
277 278
                             span,
                             E0408,
M
Manish Goregaokar 已提交
279
                             "variable `{}` from pattern #{} is not bound in pattern #{}",
N
Nick Cameron 已提交
280
                             variable_name,
M
Manish Goregaokar 已提交
281
                             from,
282 283 284
                             to);
            err.span_label(span, &format!("pattern doesn't bind `{}`", variable_name));
            err
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::StructVariantUsedAsFunction(path_name) => {
K
Knight 已提交
338
            let mut err = struct_span_err!(resolver.session,
N
Nick Cameron 已提交
339 340 341 342
                             span,
                             E0423,
                             "`{}` is the name of a struct or struct variant, but this expression \
                             uses it like a function name",
K
Knight 已提交
343 344 345
                             path_name);
            err.span_label(span, &format!("struct called like a function"));
            err
C
corentih 已提交
346
        }
347
        ResolutionError::SelfNotAvailableInStaticMethod => {
348
            let mut err = struct_span_err!(resolver.session,
N
Nick Cameron 已提交
349 350
                             span,
                             E0424,
351 352 353 354
                             "`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 已提交
355
        }
356
        ResolutionError::UnresolvedName { path, message: msg, context, is_static_method,
G
ggomez 已提交
357
                                          is_field, def } => {
N
Nick Cameron 已提交
358 359 360
            let mut err = struct_span_err!(resolver.session,
                                           span,
                                           E0425,
J
Jonathan Turner 已提交
361 362 363 364 365 366 367 368
                                           "unresolved name `{}`",
                                           path);
            if msg != "" {
                err.span_label(span, &msg);
            } else {
                err.span_label(span, &format!("unresolved name"));
            }

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

N
Niko Matsakis 已提交
494
#[derive(Copy, Clone)]
495
struct BindingInfo {
496
    span: Span,
497
    binding_mode: BindingMode,
498 499 500
}

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

503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
#[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",
        }
    }
530 531
}

N
Niko Matsakis 已提交
532
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
G
Garming Sam 已提交
533
pub enum Namespace {
534
    TypeNS,
C
corentih 已提交
535
    ValueNS,
536
    MacroNS,
537 538
}

J
Jeffrey Seyfried 已提交
539 540 541 542
#[derive(Clone, Default, Debug)]
pub struct PerNS<T> {
    value_ns: T,
    type_ns: T,
543
    macro_ns: Option<T>,
J
Jeffrey Seyfried 已提交
544 545 546 547 548 549 550 551
}

impl<T> ::std::ops::Index<Namespace> for PerNS<T> {
    type Output = T;
    fn index(&self, ns: Namespace) -> &T {
        match ns {
            ValueNS => &self.value_ns,
            TypeNS => &self.type_ns,
552
            MacroNS => self.macro_ns.as_ref().unwrap(),
J
Jeffrey Seyfried 已提交
553 554 555 556 557 558 559 560 561
        }
    }
}

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

567
impl<'a> Visitor for Resolver<'a> {
568
    fn visit_item(&mut self, item: &Item) {
A
Alex Crichton 已提交
569
        self.resolve_item(item);
570
    }
571
    fn visit_arm(&mut self, arm: &Arm) {
A
Alex Crichton 已提交
572
        self.resolve_arm(arm);
573
    }
574
    fn visit_block(&mut self, block: &Block) {
A
Alex Crichton 已提交
575
        self.resolve_block(block);
576
    }
577
    fn visit_expr(&mut self, expr: &Expr) {
578
        self.resolve_expr(expr, None);
579
    }
580
    fn visit_local(&mut self, local: &Local) {
A
Alex Crichton 已提交
581
        self.resolve_local(local);
582
    }
583
    fn visit_ty(&mut self, ty: &Ty) {
A
Alex Crichton 已提交
584
        self.resolve_type(ty);
585
    }
586
    fn visit_poly_trait_ref(&mut self, tref: &ast::PolyTraitRef, m: &ast::TraitBoundModifier) {
587
        match self.resolve_trait_reference(tref.trait_ref.ref_id, &tref.trait_ref.path, 0, None) {
588
            Ok(def) => self.record_def(tref.trait_ref.ref_id, def),
C
corentih 已提交
589 590
            Err(_) => {
                // error already reported
591
                self.record_def(tref.trait_ref.ref_id, err_path_resolution())
C
corentih 已提交
592
            }
593
        }
594
        visit::walk_poly_trait_ref(self, tref, m);
595
    }
C
corentih 已提交
596
    fn visit_variant(&mut self,
597
                     variant: &ast::Variant,
C
corentih 已提交
598 599
                     generics: &Generics,
                     item_id: ast::NodeId) {
600 601 602
        if let Some(ref dis_expr) = variant.node.disr_expr {
            // resolve the discriminator expr as a constant
            self.with_constant_rib(|this| {
603
                this.visit_expr(dis_expr);
604 605 606
            });
        }

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

        // Create a value rib for the function.
J
Jeffrey Seyfried 已提交
643
        self.ribs[ValueNS].push(Rib::new(rib_kind));
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672

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

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

            self.visit_ty(&argument.ty);

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

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

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

        self.label_ribs.pop();
J
Jeffrey Seyfried 已提交
673
        self.ribs[ValueNS].pop();
674
    }
675
}
676

677
pub type ErrorMessage = Option<(Span, String)>;
678

679
#[derive(Clone, PartialEq, Eq, Debug)]
680
pub enum ResolveResult<T> {
C
corentih 已提交
681 682 683
    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.
684 685
}

686
impl<T> ResolveResult<T> {
687 688 689 690 691 692
    fn success(self) -> Option<T> {
        match self {
            Success(t) => Some(t),
            _ => None,
        }
    }
693 694
}

695 696 697
enum FallbackSuggestion {
    NoSuggestion,
    Field,
698
    TraitItem,
699
    TraitMethod(String),
700 701
}

N
Niko Matsakis 已提交
702
#[derive(Copy, Clone)]
703
enum TypeParameters<'a, 'b> {
704
    NoTypeParameters,
C
corentih 已提交
705
    HasTypeParameters(// Type parameters.
706
                      &'b Generics,
707

C
corentih 已提交
708
                      // The kind of the rib used for type parameters.
709
                      RibKind<'a>),
710 711
}

712
// The rib kind controls the translation of local
713
// definitions (`Def::Local`) to upvars (`Def::Upvar`).
N
Niko Matsakis 已提交
714
#[derive(Copy, Clone, Debug)]
715
enum RibKind<'a> {
716 717
    // No translation needs to be applied.
    NormalRibKind,
718

719 720
    // We passed through a closure scope at the given node ID.
    // Translate upvars as appropriate.
721
    ClosureRibKind(NodeId /* func id */),
722

723
    // We passed through an impl or trait and are now in one of its
724
    // methods. Allow references to ty params that impl or trait
725 726
    // binds. Disallow any other upvars (including other ty params that are
    // upvars).
727 728 729
    //
    // The boolean value represents the fact that this method is static or not.
    MethodRibKind(bool),
730

731 732
    // We passed through an item scope. Disallow upvars.
    ItemRibKind,
733 734

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

737 738
    // We passed through a module.
    ModuleRibKind(Module<'a>),
739 740

    // We passed through a `macro_rules!` statement with the given expansion
741
    MacroDefinition(Mark),
742 743
}

N
Niko Matsakis 已提交
744
#[derive(Copy, Clone)]
F
Felix S. Klock II 已提交
745
enum UseLexicalScopeFlag {
746
    DontUseLexicalScope,
C
corentih 已提交
747
    UseLexicalScope,
748 749
}

750
enum ModulePrefixResult<'a> {
751
    NoPrefixFound,
752
    PrefixFound(Module<'a>, usize),
753 754
}

755
/// One local scope.
J
Jorge Aparicio 已提交
756
#[derive(Debug)]
757
struct Rib<'a> {
758
    bindings: FxHashMap<Ident, Def>,
759
    kind: RibKind<'a>,
B
Brian Anderson 已提交
760
}
761

762 763
impl<'a> Rib<'a> {
    fn new(kind: RibKind<'a>) -> Rib<'a> {
764
        Rib {
765
            bindings: FxHashMap(),
C
corentih 已提交
766
            kind: kind,
767
        }
768 769 770
    }
}

771 772 773
/// A definition along with the index of the rib it was found on
struct LocalDef {
    ribs: Option<(Namespace, usize)>,
C
corentih 已提交
774
    def: Def,
775 776 777 778 779 780
}

impl LocalDef {
    fn from_def(def: Def) -> Self {
        LocalDef {
            ribs: None,
C
corentih 已提交
781
            def: def,
782 783 784 785
        }
    }
}

786 787 788 789 790
enum LexicalScopeBinding<'a> {
    Item(&'a NameBinding<'a>),
    LocalDef(LocalDef),
}

791 792 793 794
impl<'a> LexicalScopeBinding<'a> {
    fn local_def(self) -> LocalDef {
        match self {
            LexicalScopeBinding::LocalDef(local_def) => local_def,
795
            LexicalScopeBinding::Item(binding) => LocalDef::from_def(binding.def()),
796 797 798
        }
    }

799
    fn item(self) -> Option<&'a NameBinding<'a>> {
800
        match self {
801
            LexicalScopeBinding::Item(binding) => Some(binding),
802 803 804 805 806
            _ => None,
        }
    }
}

J
Jeffrey Seyfried 已提交
807 808 809
enum ModuleKind {
    Block(NodeId),
    Def(Def, Name),
810 811
}

812
/// One node in the tree of modules.
813
pub struct ModuleS<'a> {
J
Jeffrey Seyfried 已提交
814 815
    parent: Option<Module<'a>>,
    kind: ModuleKind,
816

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

820
    resolutions: RefCell<FxHashMap<(Name, Namespace), &'a RefCell<NameResolution<'a>>>>,
821
    legacy_macro_resolutions: RefCell<Vec<(Mark, Name, Span)>>,
822

823 824 825
    // Macro invocations that can expand into items in this module.
    unresolved_invocations: RefCell<FxHashSet<Mark>>,

826
    no_implicit_prelude: bool,
827

828
    glob_importers: RefCell<Vec<&'a ImportDirective<'a>>>,
829
    globs: RefCell<Vec<&'a ImportDirective<'a>>>,
830

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

834 835 836
    // Whether this module is populated. If not populated, any attempt to
    // access the children must be preceded with a
    // `populate_module_if_necessary` call.
837
    populated: Cell<bool>,
838 839
}

840 841 842
pub type Module<'a> = &'a ModuleS<'a>;

impl<'a> ModuleS<'a> {
843
    fn new(parent: Option<Module<'a>>, kind: ModuleKind) -> Self {
844
        ModuleS {
J
Jeffrey Seyfried 已提交
845 846
            parent: parent,
            kind: kind,
847
            normal_ancestor_id: None,
848
            resolutions: RefCell::new(FxHashMap()),
849
            legacy_macro_resolutions: RefCell::new(Vec::new()),
850
            unresolved_invocations: RefCell::new(FxHashSet()),
851
            no_implicit_prelude: false,
852
            glob_importers: RefCell::new(Vec::new()),
853
            globs: RefCell::new((Vec::new())),
J
Jeffrey Seyfried 已提交
854
            traits: RefCell::new(None),
855
            populated: Cell::new(true),
856
        }
B
Brian Anderson 已提交
857 858
    }

859
    fn for_each_child<F: FnMut(Name, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
860
        for (&(name, ns), name_resolution) in self.resolutions.borrow().iter() {
861
            name_resolution.borrow().binding.map(|binding| f(name, ns, binding));
862 863 864
        }
    }

J
Jeffrey Seyfried 已提交
865 866 867 868 869 870 871
    fn def(&self) -> Option<Def> {
        match self.kind {
            ModuleKind::Def(def, _) => Some(def),
            _ => None,
        }
    }

872
    fn def_id(&self) -> Option<DefId> {
J
Jeffrey Seyfried 已提交
873
        self.def().as_ref().map(Def::def_id)
874 875
    }

876
    // `self` resolves to the first module ancestor that `is_normal`.
877
    fn is_normal(&self) -> bool {
J
Jeffrey Seyfried 已提交
878 879
        match self.kind {
            ModuleKind::Def(Def::Mod(_), _) => true,
880 881 882 883 884
            _ => false,
        }
    }

    fn is_trait(&self) -> bool {
J
Jeffrey Seyfried 已提交
885 886
        match self.kind {
            ModuleKind::Def(Def::Trait(_), _) => true,
887
            _ => false,
888
        }
B
Brian Anderson 已提交
889
    }
890 891 892 893

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

896
impl<'a> fmt::Debug for ModuleS<'a> {
897
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
J
Jeffrey Seyfried 已提交
898
        write!(f, "{:?}", self.def())
899 900 901
    }
}

902
// Records a possibly-private value, type, or module definition.
903
#[derive(Clone, Debug)]
904
pub struct NameBinding<'a> {
905
    kind: NameBindingKind<'a>,
906
    expansion: Mark,
907
    span: Span,
908
    vis: ty::Visibility,
909 910
}

911 912 913 914 915 916 917 918 919 920
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
    }
}

921
#[derive(Clone, Debug)]
922
enum NameBindingKind<'a> {
923
    Def(Def),
924
    Module(Module<'a>),
925 926
    Import {
        binding: &'a NameBinding<'a>,
927
        directive: &'a ImportDirective<'a>,
928
        used: Cell<bool>,
929
    },
930 931 932 933
    Ambiguity {
        b1: &'a NameBinding<'a>,
        b2: &'a NameBinding<'a>,
    }
934 935
}

936 937
struct PrivacyError<'a>(Span, Name, &'a NameBinding<'a>);

J
Jeffrey Seyfried 已提交
938 939 940
struct AmbiguityError<'a> {
    span: Span,
    name: Name,
941
    lexical: bool,
J
Jeffrey Seyfried 已提交
942 943 944 945
    b1: &'a NameBinding<'a>,
    b2: &'a NameBinding<'a>,
}

946
impl<'a> NameBinding<'a> {
947
    fn module(&self) -> Result<Module<'a>, bool /* true if an error has already been reported */> {
948
        match self.kind {
949
            NameBindingKind::Module(module) => Ok(module),
950
            NameBindingKind::Import { binding, .. } => binding.module(),
951 952 953
            NameBindingKind::Def(Def::Err) => Err(true),
            NameBindingKind::Def(_) => Err(false),
            NameBindingKind::Ambiguity { ..  } => Err(false),
954 955 956
        }
    }

957
    fn def(&self) -> Def {
958
        match self.kind {
959
            NameBindingKind::Def(def) => def,
J
Jeffrey Seyfried 已提交
960
            NameBindingKind::Module(module) => module.def().unwrap(),
961
            NameBindingKind::Import { binding, .. } => binding.def(),
962
            NameBindingKind::Ambiguity { .. } => Def::Err,
963
        }
964
    }
965

966 967 968 969 970 971 972
    // 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 {
973 974
            NameBindingKind::Def(Def::Variant(..)) |
            NameBindingKind::Def(Def::VariantCtor(..)) => true,
975 976
            _ => false,
        }
977 978
    }

979
    fn is_extern_crate(&self) -> bool {
980 981 982 983 984 985 986 987
        match self.kind {
            NameBindingKind::Import {
                directive: &ImportDirective {
                    subclass: ImportDirectiveSubclass::ExternCrate, ..
                }, ..
            } => true,
            _ => false,
        }
988
    }
989 990 991 992 993 994 995

    fn is_import(&self) -> bool {
        match self.kind {
            NameBindingKind::Import { .. } => true,
            _ => false,
        }
    }
996 997 998 999

    fn is_glob_import(&self) -> bool {
        match self.kind {
            NameBindingKind::Import { directive, .. } => directive.is_glob(),
1000
            NameBindingKind::Ambiguity { b1, .. } => b1.is_glob_import(),
1001 1002 1003 1004 1005
            _ => false,
        }
    }

    fn is_importable(&self) -> bool {
1006
        match self.def() {
1007 1008 1009 1010
            Def::AssociatedConst(..) | Def::Method(..) | Def::AssociatedTy(..) => false,
            _ => true,
        }
    }
1011 1012
}

1013
/// Interns the names of the primitive types.
F
Felix S. Klock II 已提交
1014
struct PrimitiveTypeTable {
1015
    primitive_types: FxHashMap<Name, PrimTy>,
1016
}
1017

1018
impl PrimitiveTypeTable {
K
Kevin Butler 已提交
1019
    fn new() -> PrimitiveTypeTable {
1020
        let mut table = PrimitiveTypeTable { primitive_types: FxHashMap() };
C
corentih 已提交
1021 1022 1023

        table.intern("bool", TyBool);
        table.intern("char", TyChar);
1024 1025
        table.intern("f32", TyFloat(FloatTy::F32));
        table.intern("f64", TyFloat(FloatTy::F64));
1026 1027 1028 1029 1030
        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 已提交
1031
        table.intern("str", TyStr);
1032 1033 1034 1035 1036
        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 已提交
1037 1038 1039 1040

        table
    }

1041
    fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1042
        self.primitive_types.insert(token::intern(string), primitive_type);
1043 1044 1045
    }
}

1046
/// The main resolver class.
1047
pub struct Resolver<'a> {
E
Eduard Burtescu 已提交
1048
    session: &'a Session,
1049

1050
    pub definitions: Definitions,
1051

1052 1053
    // Maps the node id of a statement to the expansions of the `macro_rules!`s
    // immediately above the statement (if appropriate).
1054
    macros_at_scope: FxHashMap<NodeId, Vec<Mark>>,
1055

1056
    graph_root: Module<'a>,
1057

1058 1059
    prelude: Option<Module<'a>>,

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

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

1066 1067 1068 1069
    // All imports known to succeed or fail.
    determined_imports: Vec<&'a ImportDirective<'a>>,

    // All non-determined imports.
1070
    indeterminate_imports: Vec<&'a ImportDirective<'a>>,
1071 1072

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

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

1079
    // The current set of local scopes, for labels.
1080
    label_ribs: Vec<Rib<'a>>,
1081

1082
    // The trait that the current context can refer to.
1083 1084 1085 1086
    current_trait_ref: Option<(DefId, TraitRef)>,

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

1088
    // The idents for the primitive types.
E
Eduard Burtescu 已提交
1089
    primitive_type_table: PrimitiveTypeTable,
1090

1091 1092
    pub def_map: DefMap,
    pub freevars: FreevarMap,
1093
    freevars_seen: NodeMap<NodeMap<usize>>,
1094 1095
    pub export_map: ExportMap,
    pub trait_map: TraitMap,
1096

1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
    // 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`.
1111
    module_map: NodeMap<Module<'a>>,
1112
    extern_crate_roots: FxHashMap<(CrateNum, bool /* MacrosOnly? */), Module<'a>>,
1113

1114 1115 1116 1117 1118
    // 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,

1119
    pub make_glob_map: bool,
1120 1121
    // Maps imports to the names of items actually imported (this actually maps
    // all imports, but only glob imports are actually interesting).
1122
    pub glob_map: GlobMap,
1123

1124 1125
    used_imports: FxHashSet<(NodeId, Namespace)>,
    used_crates: FxHashSet<CrateNum>,
1126
    pub maybe_unused_trait_imports: NodeSet,
G
Garming Sam 已提交
1127

1128
    privacy_errors: Vec<PrivacyError<'a>>,
J
Jeffrey Seyfried 已提交
1129
    ambiguity_errors: Vec<AmbiguityError<'a>>,
1130
    disallowed_shadowing: Vec<&'a LegacyBinding<'a>>,
1131 1132

    arenas: &'a ResolverArenas<'a>,
1133
    dummy_binding: &'a NameBinding<'a>,
1134
    new_import_semantics: bool, // true if `#![feature(item_like_imports)]`
1135
    use_extern_macros: bool, // true if `#![feature(use_extern_macros)]`
1136

1137
    pub exported_macros: Vec<ast::MacroDef>,
1138
    crate_loader: &'a mut CrateLoader,
1139
    macro_names: FxHashSet<Name>,
1140
    builtin_macros: FxHashMap<Name, &'a NameBinding<'a>>,
J
Jeffrey Seyfried 已提交
1141
    lexical_macro_resolutions: Vec<(Name, LegacyScope<'a>)>,
J
Jeffrey Seyfried 已提交
1142 1143
    macro_map: FxHashMap<DefId, Rc<SyntaxExtension>>,
    macro_exports: Vec<Export>,
1144 1145

    // Maps the `Mark` of an expansion to its containing module or block.
1146
    invocations: FxHashMap<Mark, &'a InvocationData<'a>>,
1147 1148 1149

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

1152
pub struct ResolverArenas<'a> {
1153
    modules: arena::TypedArena<ModuleS<'a>>,
1154
    local_modules: RefCell<Vec<Module<'a>>>,
1155
    name_bindings: arena::TypedArena<NameBinding<'a>>,
1156
    import_directives: arena::TypedArena<ImportDirective<'a>>,
1157
    name_resolutions: arena::TypedArena<RefCell<NameResolution<'a>>>,
1158
    invocation_data: arena::TypedArena<InvocationData<'a>>,
J
Jeffrey Seyfried 已提交
1159
    legacy_bindings: arena::TypedArena<LegacyBinding<'a>>,
1160 1161 1162
}

impl<'a> ResolverArenas<'a> {
1163
    fn alloc_module(&'a self, module: ModuleS<'a>) -> Module<'a> {
1164 1165 1166 1167 1168 1169 1170 1171
        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()
1172 1173 1174 1175
    }
    fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
        self.name_bindings.alloc(name_binding)
    }
1176 1177
    fn alloc_import_directive(&'a self, import_directive: ImportDirective<'a>)
                              -> &'a ImportDirective {
1178 1179
        self.import_directives.alloc(import_directive)
    }
1180 1181 1182
    fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
        self.name_resolutions.alloc(Default::default())
    }
1183 1184 1185
    fn alloc_invocation_data(&'a self, expansion_data: InvocationData<'a>)
                             -> &'a InvocationData<'a> {
        self.invocation_data.alloc(expansion_data)
J
Jeffrey Seyfried 已提交
1186
    }
J
Jeffrey Seyfried 已提交
1187 1188 1189
    fn alloc_legacy_binding(&'a self, binding: LegacyBinding<'a>) -> &'a LegacyBinding<'a> {
        self.legacy_bindings.alloc(binding)
    }
1190 1191
}

1192
impl<'a> ty::NodeIdTree for Resolver<'a> {
1193 1194
    fn is_descendant_of(&self, mut node: NodeId, ancestor: NodeId) -> bool {
        while node != ancestor {
J
Jeffrey Seyfried 已提交
1195
            node = match self.module_map[&node].parent {
J
Jeffrey Seyfried 已提交
1196
                Some(parent) => parent.normal_ancestor_id.unwrap(),
1197
                None => return false,
1198
            }
1199
        }
J
Jeffrey Seyfried 已提交
1200
        true
1201 1202 1203
    }
}

1204 1205 1206 1207
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) {
1208
            Ok(binding) => binding.def(),
1209 1210 1211 1212
            Err(true) => Def::Err,
            Err(false) => {
                let path_name = &format!("{}", path);
                let error =
1213 1214 1215 1216 1217
                    ResolutionError::UnresolvedName {
                        path: path_name,
                        message: "",
                        context: UnresolvedNameContext::Other,
                        is_static_method: false,
G
ggomez 已提交
1218 1219
                        is_field: false,
                        def: Def::Err,
1220
                    };
1221 1222 1223 1224 1225 1226
                resolve_error(self, path.span, error);
                Def::Err
            }
        }
    }

1227 1228 1229 1230
    fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution> {
        self.def_map.get(&id).cloned()
    }

1231
    fn record_resolution(&mut self, id: NodeId, def: Def) {
1232
        self.def_map.insert(id, PathResolution::new(def));
1233
    }
1234

1235 1236
    fn definitions(&mut self) -> &mut Definitions {
        &mut self.definitions
1237 1238 1239 1240
    }
}

trait Named {
1241
    fn ident(&self) -> Ident;
1242 1243 1244
}

impl Named for ast::PathSegment {
1245 1246
    fn ident(&self) -> Ident {
        self.identifier
1247 1248 1249 1250
    }
}

impl Named for hir::PathSegment {
1251 1252
    fn ident(&self) -> Ident {
        Ident::with_empty_ctxt(self.name)
1253 1254 1255
    }
}

1256
impl<'a> Resolver<'a> {
1257
    pub fn new(session: &'a Session,
1258
               krate: &Crate,
1259
               make_glob_map: MakeGlobMap,
1260
               crate_loader: &'a mut CrateLoader,
1261
               arenas: &'a ResolverArenas<'a>)
1262
               -> Resolver<'a> {
1263 1264 1265 1266 1267 1268
        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()))
        });
1269 1270
        let mut module_map = NodeMap();
        module_map.insert(CRATE_NODE_ID, graph_root);
K
Kevin Butler 已提交
1271

1272 1273 1274
        let mut definitions = Definitions::new();
        DefCollector::new(&mut definitions).collect_root();

1275
        let mut invocations = FxHashMap();
1276 1277
        invocations.insert(Mark::root(),
                           arenas.alloc_invocation_data(InvocationData::root(graph_root)));
1278

K
Kevin Butler 已提交
1279 1280 1281
        Resolver {
            session: session,

1282
            definitions: definitions,
1283
            macros_at_scope: FxHashMap(),
1284

K
Kevin Butler 已提交
1285 1286
            // The outermost module has def ID 0; this is not reflected in the
            // AST.
1287
            graph_root: graph_root,
1288
            prelude: None,
K
Kevin Butler 已提交
1289

1290 1291
            trait_item_map: FxHashMap(),
            field_names: FxHashMap(),
K
Kevin Butler 已提交
1292

1293
            determined_imports: Vec::new(),
1294
            indeterminate_imports: Vec::new(),
K
Kevin Butler 已提交
1295

1296
            current_module: graph_root,
J
Jeffrey Seyfried 已提交
1297 1298 1299
            ribs: PerNS {
                value_ns: vec![Rib::new(ModuleRibKind(graph_root))],
                type_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1300
                macro_ns: None,
J
Jeffrey Seyfried 已提交
1301
            },
1302
            label_ribs: Vec::new(),
K
Kevin Butler 已提交
1303 1304 1305 1306 1307 1308

            current_trait_ref: None,
            current_self_type: None,

            primitive_type_table: PrimitiveTypeTable::new(),

1309
            def_map: NodeMap(),
1310 1311
            freevars: NodeMap(),
            freevars_seen: NodeMap(),
1312 1313
            export_map: NodeMap(),
            trait_map: NodeMap(),
1314
            module_map: module_map,
1315
            extern_crate_roots: FxHashMap(),
K
Kevin Butler 已提交
1316 1317

            emit_errors: true,
1318
            make_glob_map: make_glob_map == MakeGlobMap::Yes,
1319
            glob_map: NodeMap(),
G
Garming Sam 已提交
1320

1321 1322
            used_imports: FxHashSet(),
            used_crates: FxHashSet(),
S
Seo Sanghyeon 已提交
1323 1324
            maybe_unused_trait_imports: NodeSet(),

1325
            privacy_errors: Vec::new(),
1326
            ambiguity_errors: Vec::new(),
1327
            disallowed_shadowing: Vec::new(),
1328 1329

            arenas: arenas,
1330 1331
            dummy_binding: arenas.alloc_name_binding(NameBinding {
                kind: NameBindingKind::Def(Def::Err),
1332
                expansion: Mark::root(),
1333 1334 1335
                span: DUMMY_SP,
                vis: ty::Visibility::Public,
            }),
1336
            new_import_semantics: session.features.borrow().item_like_imports,
1337
            use_extern_macros: session.features.borrow().use_extern_macros,
1338

1339
            exported_macros: Vec::new(),
1340
            crate_loader: crate_loader,
1341 1342
            macro_names: FxHashSet(),
            builtin_macros: FxHashMap(),
J
Jeffrey Seyfried 已提交
1343
            lexical_macro_resolutions: Vec::new(),
J
Jeffrey Seyfried 已提交
1344 1345
            macro_map: FxHashMap(),
            macro_exports: Vec::new(),
1346
            invocations: invocations,
1347
            name_already_seen: FxHashMap(),
1348 1349 1350
        }
    }

1351
    pub fn arenas() -> ResolverArenas<'a> {
1352 1353
        ResolverArenas {
            modules: arena::TypedArena::new(),
1354
            local_modules: RefCell::new(Vec::new()),
1355
            name_bindings: arena::TypedArena::new(),
1356
            import_directives: arena::TypedArena::new(),
1357
            name_resolutions: arena::TypedArena::new(),
1358
            invocation_data: arena::TypedArena::new(),
J
Jeffrey Seyfried 已提交
1359
            legacy_bindings: arena::TypedArena::new(),
K
Kevin Butler 已提交
1360 1361
        }
    }
1362

J
Jeffrey Seyfried 已提交
1363 1364 1365 1366
    fn per_ns<T, F: FnMut(&mut Self, Namespace) -> T>(&mut self, mut f: F) -> PerNS<T> {
        PerNS {
            type_ns: f(self, TypeNS),
            value_ns: f(self, ValueNS),
1367 1368 1369 1370
            macro_ns: match self.use_extern_macros {
                true => Some(f(self, MacroNS)),
                false => None,
            },
J
Jeffrey Seyfried 已提交
1371 1372 1373
        }
    }

1374 1375
    /// Entry point to crate resolution.
    pub fn resolve_crate(&mut self, krate: &Crate) {
1376
        ImportResolver { resolver: self }.finalize_imports();
1377 1378 1379 1380
        self.current_module = self.graph_root;
        visit::walk_crate(self, krate);

        check_unused::check_crate(self, krate);
1381
        self.report_errors();
1382
        self.crate_loader.postprocess(krate);
1383 1384
    }

1385 1386 1387 1388 1389 1390
    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)
        })
1391 1392
    }

1393 1394
    fn record_use(&mut self, name: Name, ns: Namespace, binding: &'a NameBinding<'a>, span: Span)
                  -> bool /* true if an error was reported */ {
1395
        // track extern crates for unused_extern_crate lint
1396
        if let Some(DefId { krate, .. }) = binding.module().ok().and_then(ModuleS::def_id) {
1397 1398 1399
            self.used_crates.insert(krate);
        }

1400 1401 1402 1403 1404 1405 1406 1407 1408
        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 } => {
1409 1410 1411
                self.ambiguity_errors.push(AmbiguityError {
                    span: span, name: name, lexical: false, b1: b1, b2: b2,
                });
1412 1413 1414
                true
            }
            _ => false
1415
        }
1416
    }
1417

1418 1419
    fn add_to_glob_map(&mut self, id: NodeId, name: Name) {
        if self.make_glob_map {
1420
            self.glob_map.entry(id).or_insert_with(FxHashSet).insert(name);
1421
        }
1422 1423
    }

1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
    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)))
            }
        }
    }

1436
    /// Resolves the given module path from the given root `search_module`.
F
Felix S. Klock II 已提交
1437
    fn resolve_module_path_from_root(&mut self,
1438
                                     mut search_module: Module<'a>,
1439
                                     module_path: &[Ident],
1440
                                     index: usize,
1441
                                     span: Option<Span>)
J
Jeffrey Seyfried 已提交
1442
                                     -> ResolveResult<Module<'a>> {
1443 1444
        fn search_parent_externals<'a>(this: &mut Resolver<'a>, needle: Name, module: Module<'a>)
                                       -> Option<Module<'a>> {
1445
            match this.resolve_name_in_module(module, needle, TypeNS, false, false, None) {
1446
                Success(binding) if binding.is_extern_crate() => Some(module),
J
Jeffrey Seyfried 已提交
1447 1448 1449 1450
                _ => if let (&ModuleKind::Def(..), Some(parent)) = (&module.kind, module.parent) {
                    search_parent_externals(this, needle, parent)
                } else {
                    None
C
corentih 已提交
1451
                },
1452
            }
1453 1454
        }

1455
        let mut index = index;
A
Alex Crichton 已提交
1456
        let module_path_len = module_path.len();
1457 1458 1459 1460 1461

        // 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 {
1462
            let name = module_path[index].name;
1463
            match self.resolve_name_in_module(search_module, name, TypeNS, false, false, span) {
1464
                Failed(_) => {
1465
                    let segment_name = name.as_str();
1466
                    let module_name = module_to_string(search_module);
1467
                    let msg = if "???" == &module_name {
1468 1469
                        let current_module = self.current_module;
                        match search_parent_externals(self, name, current_module) {
1470
                            Some(module) => {
1471
                                let path_str = names_to_string(module_path);
J
Jonas Schievink 已提交
1472
                                let target_mod_str = module_to_string(&module);
1473
                                let current_mod_str = module_to_string(current_module);
1474 1475 1476 1477 1478 1479 1480

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

1481
                                format!("Did you mean `{}{}`?", prefix, path_str)
C
corentih 已提交
1482
                            }
1483
                            None => format!("Maybe a missing `extern crate {};`?", segment_name),
1484
                        }
1485
                    } else {
C
corentih 已提交
1486
                        format!("Could not find `{}` in `{}`", segment_name, module_name)
1487
                    };
1488

1489
                    return Failed(span.map(|span| (span, msg)));
1490
                }
B
Brian Anderson 已提交
1491
                Indeterminate => {
C
corentih 已提交
1492 1493 1494
                    debug!("(resolving module path for import) module resolution is \
                            indeterminate: {}",
                           name);
B
Brian Anderson 已提交
1495
                    return Indeterminate;
1496
                }
1497
                Success(binding) => {
1498 1499
                    // Check to see whether there are type bindings, and, if
                    // so, whether there is a module within.
1500 1501 1502
                    match self.expect_module(name, binding, span) {
                        Success(module) => search_module = module,
                        result @ _ => return result,
1503 1504 1505 1506
                    }
                }
            }

T
Tim Chevalier 已提交
1507
            index += 1;
1508 1509
        }

J
Jeffrey Seyfried 已提交
1510
        return Success(search_module);
1511 1512
    }

1513 1514
    /// Attempts to resolve the module part of an import directive or path
    /// rooted at the given module.
F
Felix S. Klock II 已提交
1515
    fn resolve_module_path(&mut self,
1516
                           module_path: &[Ident],
1517
                           use_lexical_scope: UseLexicalScopeFlag,
1518
                           span: Option<Span>)
J
Jeffrey Seyfried 已提交
1519
                           -> ResolveResult<Module<'a>> {
1520
        if module_path.len() == 0 {
J
Jeffrey Seyfried 已提交
1521
            return Success(self.graph_root) // Use the crate root
1522
        }
1523

1524
        debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1525
               names_to_string(module_path),
1526
               module_to_string(self.current_module));
1527

1528
        // Resolve the module prefix, if any.
1529
        let module_prefix_result = self.resolve_module_prefix(module_path, span);
1530

1531 1532
        let search_module;
        let start_index;
1533
        match module_prefix_result {
1534
            Failed(err) => return Failed(err),
B
Brian Anderson 已提交
1535
            Indeterminate => {
C
corentih 已提交
1536
                debug!("(resolving module path for import) indeterminate; bailing");
B
Brian Anderson 已提交
1537
                return Indeterminate;
1538
            }
1539 1540 1541 1542 1543 1544 1545 1546
            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.
1547
                        search_module = self.graph_root;
1548 1549 1550 1551 1552 1553
                        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.
1554
                        let ident = module_path[0];
1555 1556 1557 1558 1559 1560 1561 1562 1563
                        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,
1564
                            }
1565 1566 1567 1568
                        } else {
                            let msg =
                                format!("Use of undeclared type or module `{}`", ident.name);
                            return Failed(span.map(|span| (span, msg)));
1569 1570 1571 1572
                        }
                    }
                }
            }
E
Eduard Burtescu 已提交
1573
            Success(PrefixFound(ref containing_module, index)) => {
1574
                search_module = containing_module;
1575
                start_index = index;
1576 1577 1578
            }
        }

1579
        self.resolve_module_path_from_root(search_module, module_path, start_index, span)
1580 1581
    }

1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595
    /// 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.
    /// }
    /// ```
1596
    ///
1597 1598
    /// Invariant: This must only be called during main resolution, not during
    /// import resolution.
1599
    fn resolve_ident_in_lexical_scope(&mut self,
1600
                                      mut ident: Ident,
1601
                                      ns: Namespace,
1602
                                      record_used: Option<Span>)
1603
                                      -> Option<LexicalScopeBinding<'a>> {
1604
        if ns == TypeNS {
1605
            ident = Ident::with_empty_ctxt(ident.name);
1606
        }
1607

1608
        // Walk backwards up the ribs in scope.
J
Jeffrey Seyfried 已提交
1609 1610
        for i in (0 .. self.ribs[ns].len()).rev() {
            if let Some(def) = self.ribs[ns][i].bindings.get(&ident).cloned() {
1611 1612 1613 1614 1615
                // The ident resolves to a type parameter or local variable.
                return Some(LexicalScopeBinding::LocalDef(LocalDef {
                    ribs: Some((ns, i)),
                    def: def,
                }));
1616 1617
            }

J
Jeffrey Seyfried 已提交
1618
            if let ModuleRibKind(module) = self.ribs[ns][i].kind {
1619
                let name = ident.name;
1620
                let item = self.resolve_name_in_module(module, name, ns, true, false, record_used);
1621 1622 1623
                if let Success(binding) = item {
                    // The ident resolves to an item.
                    return Some(LexicalScopeBinding::Item(binding));
1624
                }
1625

J
Jeffrey Seyfried 已提交
1626
                if let ModuleKind::Block(..) = module.kind { // We can see through blocks
1627
                } else if !module.no_implicit_prelude {
J
Jeffrey Seyfried 已提交
1628
                    return self.prelude.and_then(|prelude| {
1629
                        self.resolve_name_in_module(prelude, name, ns, false, false, None).success()
J
Jeffrey Seyfried 已提交
1630 1631 1632
                    }).map(LexicalScopeBinding::Item)
                } else {
                    return None;
1633
                }
1634
            }
1635

J
Jeffrey Seyfried 已提交
1636
            if let MacroDefinition(mac) = self.ribs[ns][i].kind {
1637 1638
                // If an invocation of this macro created `ident`, give up on `ident`
                // and switch to `ident`'s source from the macro definition.
1639 1640 1641
                let (source_ctxt, source_macro) = ident.ctxt.source();
                if source_macro == mac {
                    ident.ctxt = source_ctxt;
1642 1643
                }
            }
1644
        }
1645

1646 1647 1648
        None
    }

1649
    /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1650
    /// (b) some chain of `super::`.
1651
    /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1652
    fn resolve_module_prefix(&mut self, module_path: &[Ident], span: Option<Span>)
1653
                             -> ResolveResult<ModulePrefixResult<'a>> {
J
Jeffrey Seyfried 已提交
1654
        if &*module_path[0].name.as_str() == "$crate" {
1655
            return Success(PrefixFound(self.resolve_crate_var(module_path[0].ctxt), 1));
J
Jeffrey Seyfried 已提交
1656 1657
        }

1658 1659
        // Start at the current module if we see `self` or `super`, or at the
        // top of the crate otherwise.
1660
        let mut i = match &*module_path[0].name.as_str() {
1661 1662 1663 1664
            "self" => 1,
            "super" => 0,
            _ => return Success(NoPrefixFound),
        };
1665

J
Jeffrey Seyfried 已提交
1666 1667
        let mut containing_module =
            self.module_map[&self.current_module.normal_ancestor_id.unwrap()];
1668 1669

        // Now loop through all the `super`s we find.
1670
        while i < module_path.len() && "super" == module_path[i].name.as_str() {
1671
            debug!("(resolving module prefix) resolving `super` at {}",
J
Jonas Schievink 已提交
1672
                   module_to_string(&containing_module));
J
Jeffrey Seyfried 已提交
1673
            if let Some(parent) = containing_module.parent {
J
Jeffrey Seyfried 已提交
1674
                containing_module = self.module_map[&parent.normal_ancestor_id.unwrap()];
1675 1676 1677 1678
                i += 1;
            } else {
                let msg = "There are too many initial `super`s.".into();
                return Failed(span.map(|span| (span, msg)));
1679 1680 1681
            }
        }

1682
        debug!("(resolving module prefix) finished resolving prefix at {}",
J
Jonas Schievink 已提交
1683
               module_to_string(&containing_module));
1684 1685

        return Success(PrefixFound(containing_module, i));
1686 1687
    }

1688 1689 1690 1691 1692 1693 1694 1695
    fn resolve_crate_var(&mut self, mut crate_var_ctxt: SyntaxContext) -> Module<'a> {
        while crate_var_ctxt.source().0 != SyntaxContext::empty() {
            crate_var_ctxt = crate_var_ctxt.source().0;
        }
        let module = self.invocations[&crate_var_ctxt.source().1].module.get();
        if module.is_local() { self.graph_root } else { module }
    }

1696 1697
    // AST resolution
    //
1698
    // We maintain a list of value ribs and type ribs.
1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713
    //
    // 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.

1714
    fn with_scope<F>(&mut self, id: NodeId, f: F)
C
corentih 已提交
1715
        where F: FnOnce(&mut Resolver)
J
Jorge Aparicio 已提交
1716
    {
1717 1718
        let module = self.module_map.get(&id).cloned(); // clones a reference
        if let Some(module) = module {
1719
            // Move down in the graph.
1720
            let orig_module = replace(&mut self.current_module, module);
J
Jeffrey Seyfried 已提交
1721 1722
            self.ribs[ValueNS].push(Rib::new(ModuleRibKind(module)));
            self.ribs[TypeNS].push(Rib::new(ModuleRibKind(module)));
1723

1724
            self.finalize_current_module_macro_resolutions();
1725
            f(self);
1726

1727
            self.current_module = orig_module;
J
Jeffrey Seyfried 已提交
1728 1729
            self.ribs[ValueNS].pop();
            self.ribs[TypeNS].pop();
1730 1731 1732
        } else {
            f(self);
        }
1733 1734
    }

S
Seo Sanghyeon 已提交
1735 1736
    /// Searches the current set of local scopes for labels.
    /// Stops after meeting a closure.
1737
    fn search_label(&self, mut ident: Ident) -> Option<Def> {
1738 1739 1740 1741 1742
        for rib in self.label_ribs.iter().rev() {
            match rib.kind {
                NormalRibKind => {
                    // Continue
                }
1743 1744 1745
                MacroDefinition(mac) => {
                    // If an invocation of this macro created `ident`, give up on `ident`
                    // and switch to `ident`'s source from the macro definition.
1746 1747 1748
                    let (source_ctxt, source_macro) = ident.ctxt.source();
                    if source_macro == mac {
                        ident.ctxt = source_ctxt;
1749 1750
                    }
                }
1751 1752
                _ => {
                    // Do not resolve labels across function boundary
C
corentih 已提交
1753
                    return None;
1754 1755
                }
            }
1756
            let result = rib.bindings.get(&ident).cloned();
S
Seo Sanghyeon 已提交
1757
            if result.is_some() {
C
corentih 已提交
1758
                return result;
1759 1760 1761 1762 1763
            }
        }
        None
    }

1764
    fn resolve_item(&mut self, item: &Item) {
1765
        let name = item.ident.name;
1766

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

1769
        match item.node {
1770 1771
            ItemKind::Enum(_, ref generics) |
            ItemKind::Ty(_, ref generics) |
1772
            ItemKind::Struct(_, ref generics) |
1773
            ItemKind::Union(_, ref generics) |
V
Vadim Petrochenkov 已提交
1774
            ItemKind::Fn(.., ref generics, _) => {
1775
                self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind),
1776
                                             |this| visit::walk_item(this, item));
1777 1778
            }

1779
            ItemKind::DefaultImpl(_, ref trait_ref) => {
1780
                self.with_optional_trait_ref(Some(trait_ref), |_, _| {}, None);
1781
            }
V
Vadim Petrochenkov 已提交
1782
            ItemKind::Impl(.., ref generics, ref opt_trait_ref, ref self_type, ref impl_items) =>
1783
                self.resolve_implementation(generics,
1784
                                            opt_trait_ref,
J
Jonas Schievink 已提交
1785
                                            &self_type,
1786
                                            item.id,
1787
                                            impl_items),
1788

1789
            ItemKind::Trait(_, ref generics, ref bounds, ref trait_items) => {
1790
                // Create a new rib for the trait-wide type parameters.
1791
                self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
1792
                    let local_def_id = this.definitions.local_def_id(item.id);
1793
                    this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
1794
                        this.visit_generics(generics);
1795
                        walk_list!(this, visit_ty_param_bound, bounds);
1796 1797

                        for trait_item in trait_items {
1798
                            match trait_item.node {
1799
                                TraitItemKind::Const(_, ref default) => {
1800 1801 1802 1803 1804
                                    // 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| {
1805
                                            visit::walk_trait_item(this, trait_item)
1806 1807
                                        });
                                    } else {
1808
                                        visit::walk_trait_item(this, trait_item)
1809 1810
                                    }
                                }
1811
                                TraitItemKind::Method(ref sig, _) => {
1812 1813
                                    let type_parameters =
                                        HasTypeParameters(&sig.generics,
V
Vadim Petrochenkov 已提交
1814
                                                          MethodRibKind(!sig.decl.has_self()));
1815
                                    this.with_type_parameter_rib(type_parameters, |this| {
1816
                                        visit::walk_trait_item(this, trait_item)
1817
                                    });
1818
                                }
1819
                                TraitItemKind::Type(..) => {
1820
                                    this.with_type_parameter_rib(NoTypeParameters, |this| {
1821
                                        visit::walk_trait_item(this, trait_item)
1822
                                    });
1823
                                }
1824
                                TraitItemKind::Macro(_) => panic!("unexpanded macro in resolve!"),
1825 1826 1827
                            };
                        }
                    });
1828
                });
1829 1830
            }

1831
            ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
1832
                self.with_scope(item.id, |this| {
1833
                    visit::walk_item(this, item);
1834
                });
1835 1836
            }

1837
            ItemKind::Const(..) | ItemKind::Static(..) => {
A
Alex Crichton 已提交
1838
                self.with_constant_rib(|this| {
1839
                    visit::walk_item(this, item);
1840
                });
1841
            }
1842

1843
            ItemKind::Use(ref view_path) => {
1844
                match view_path.node {
1845
                    ast::ViewPathList(ref prefix, ref items) => {
1846 1847 1848 1849 1850
                        // 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) {
1851
                                Ok(binding) => {
1852
                                    let def = binding.def();
1853
                                    self.record_def(item.id, PathResolution::new(def));
1854
                                }
1855 1856
                                Err(true) => self.record_def(item.id, err_path_resolution()),
                                Err(false) => {
1857 1858 1859 1860
                                    resolve_error(self,
                                                  prefix.span,
                                                  ResolutionError::FailedToResolve(
                                                      &path_names_to_string(prefix, 0)));
1861
                                    self.record_def(item.id, err_path_resolution());
1862
                                }
1863 1864 1865 1866
                            }
                        }
                    }
                    _ => {}
W
we 已提交
1867 1868 1869
                }
            }

1870
            ItemKind::ExternCrate(_) => {
1871
                // do nothing, these are just around to be encoded
1872
            }
1873 1874

            ItemKind::Mac(_) => panic!("unexpanded macro in resolve!"),
1875 1876 1877
        }
    }

1878
    fn with_type_parameter_rib<'b, F>(&'b mut self, type_parameters: TypeParameters<'a, 'b>, f: F)
C
corentih 已提交
1879
        where F: FnOnce(&mut Resolver)
J
Jorge Aparicio 已提交
1880
    {
1881
        match type_parameters {
1882
            HasTypeParameters(generics, rib_kind) => {
1883
                let mut function_type_rib = Rib::new(rib_kind);
1884
                let mut seen_bindings = FxHashMap();
1885
                for type_parameter in &generics.ty_params {
1886
                    let name = type_parameter.ident.name;
1887
                    debug!("with_type_parameter_rib: {}", type_parameter.id);
1888

C
Chris Stankus 已提交
1889 1890
                    if seen_bindings.contains_key(&name) {
                        let span = seen_bindings.get(&name).unwrap();
1891 1892
                        resolve_error(self,
                                      type_parameter.span,
C
Chris Stankus 已提交
1893 1894
                                      ResolutionError::NameAlreadyUsedInTypeParameterList(name,
                                                                                          span));
1895
                    }
C
Chris Stankus 已提交
1896
                    seen_bindings.entry(name).or_insert(type_parameter.span);
1897

1898
                    // plain insert (no renaming)
1899
                    let def_id = self.definitions.local_def_id(type_parameter.id);
1900
                    let def = Def::TyParam(def_id);
1901
                    function_type_rib.bindings.insert(Ident::with_empty_ctxt(name), def);
1902
                    self.record_def(type_parameter.id, PathResolution::new(def));
1903
                }
J
Jeffrey Seyfried 已提交
1904
                self.ribs[TypeNS].push(function_type_rib);
1905 1906
            }

B
Brian Anderson 已提交
1907
            NoTypeParameters => {
1908 1909 1910 1911
                // Nothing to do.
            }
        }

A
Alex Crichton 已提交
1912
        f(self);
1913

J
Jeffrey Seyfried 已提交
1914
        if let HasTypeParameters(..) = type_parameters {
J
Jeffrey Seyfried 已提交
1915
            self.ribs[TypeNS].pop();
1916 1917 1918
        }
    }

C
corentih 已提交
1919 1920
    fn with_label_rib<F>(&mut self, f: F)
        where F: FnOnce(&mut Resolver)
J
Jorge Aparicio 已提交
1921
    {
1922
        self.label_ribs.push(Rib::new(NormalRibKind));
A
Alex Crichton 已提交
1923
        f(self);
J
Jeffrey Seyfried 已提交
1924
        self.label_ribs.pop();
1925
    }
1926

C
corentih 已提交
1927 1928
    fn with_constant_rib<F>(&mut self, f: F)
        where F: FnOnce(&mut Resolver)
J
Jorge Aparicio 已提交
1929
    {
J
Jeffrey Seyfried 已提交
1930 1931
        self.ribs[ValueNS].push(Rib::new(ConstantItemRibKind));
        self.ribs[TypeNS].push(Rib::new(ConstantItemRibKind));
A
Alex Crichton 已提交
1932
        f(self);
J
Jeffrey Seyfried 已提交
1933 1934
        self.ribs[TypeNS].pop();
        self.ribs[ValueNS].pop();
1935 1936
    }

F
Felix S. Klock II 已提交
1937
    fn resolve_trait_reference(&mut self,
N
Nick Cameron 已提交
1938
                               id: NodeId,
1939
                               trait_path: &Path,
1940 1941
                               path_depth: usize,
                               generics: Option<&Generics>)
1942
                               -> Result<PathResolution, ()> {
1943
        self.resolve_path(id, trait_path, path_depth, TypeNS).and_then(|path_res| {
1944 1945 1946 1947 1948 1949 1950 1951
            match path_res.base_def {
                Def::Trait(_) => {
                    debug!("(resolving trait) found trait def: {:?}", path_res);
                    return Ok(path_res);
                }
                Def::Err => return Err(true),
                _ => {}
            }
1952

1953
            let mut err = resolve_struct_error(self, trait_path.span, {
1954 1955
                ResolutionError::IsNotATrait(&path_names_to_string(trait_path, path_depth),
                                             path_res.base_def.kind_name())
1956
            });
1957 1958 1959 1960 1961 1962 1963
            if let Some(generics) = generics {
                if let Some(span) = generics.span_for_name(
                    &path_names_to_string(trait_path, path_depth)) {

                    err.span_label(span, &"type parameter defined here");
                }
            }
1964 1965 1966

            // If it's a typedef, give a note
            if let Def::TyAlias(..) = path_res.base_def {
1967
                err.note(&format!("type aliases cannot be used for traits"));
1968
            }
1969 1970
            err.emit();
            Err(true)
1971 1972
        }).map_err(|error_reported| {
            if error_reported { return }
1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994

            // 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);
1995
        })
1996 1997
    }

1998 1999
    fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
        where F: FnOnce(&mut Resolver) -> T
J
Jorge Aparicio 已提交
2000
    {
2001 2002 2003 2004 2005 2006 2007
        // 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
    }

2008 2009 2010 2011 2012
    fn with_optional_trait_ref<T, F>(&mut self,
                                     opt_trait_ref: Option<&TraitRef>,
                                     f: F,
                                     generics: Option<&Generics>)
        -> T
2013
        where F: FnOnce(&mut Resolver, Option<DefId>) -> T
J
Jorge Aparicio 已提交
2014
    {
2015
        let mut new_val = None;
2016
        let mut new_id = None;
E
Eduard Burtescu 已提交
2017
        if let Some(trait_ref) = opt_trait_ref {
2018
            if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
C
corentih 已提交
2019
                                                               &trait_ref.path,
2020 2021
                                                               0,
                                                               generics) {
2022 2023 2024 2025
                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());
2026 2027
            } else {
                self.record_def(trait_ref.ref_id, err_path_resolution());
2028
            }
2029
            visit::walk_trait_ref(self, trait_ref);
2030
        }
2031
        let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2032
        let result = f(self, new_id);
2033 2034 2035 2036
        self.current_trait_ref = original_trait_ref;
        result
    }

2037 2038 2039 2040 2041 2042
    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....)
2043
        self_type_rib.bindings.insert(keywords::SelfType.ident(), self_def);
J
Jeffrey Seyfried 已提交
2044
        self.ribs[TypeNS].push(self_type_rib);
2045
        f(self);
J
Jeffrey Seyfried 已提交
2046
        self.ribs[TypeNS].pop();
2047 2048
    }

F
Felix S. Klock II 已提交
2049
    fn resolve_implementation(&mut self,
2050 2051 2052
                              generics: &Generics,
                              opt_trait_reference: &Option<TraitRef>,
                              self_type: &Ty,
2053
                              item_id: NodeId,
2054
                              impl_items: &[ImplItem]) {
2055
        // If applicable, create a rib for the type parameters.
2056
        self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
2057
            // Resolve the type parameters.
2058
            this.visit_generics(generics);
2059

2060
            // Resolve the trait reference, if necessary.
2061
            this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2062
                // Resolve the self type.
2063
                this.visit_ty(self_type);
2064

2065 2066
                let item_def_id = this.definitions.local_def_id(item_id);
                this.with_self_rib(Def::SelfTy(trait_id, Some(item_def_id)), |this| {
2067 2068
                    this.with_current_self_type(self_type, |this| {
                        for impl_item in impl_items {
2069
                            this.resolve_visibility(&impl_item.vis);
2070
                            match impl_item.node {
2071
                                ImplItemKind::Const(..) => {
2072
                                    // If this is a trait impl, ensure the const
2073
                                    // exists in trait
2074
                                    this.check_trait_item(impl_item.ident.name,
2075 2076
                                                          impl_item.span,
                                        |n, s| ResolutionError::ConstNotMemberOfTrait(n, s));
2077
                                    visit::walk_impl_item(this, impl_item);
2078
                                }
2079
                                ImplItemKind::Method(ref sig, _) => {
2080 2081
                                    // If this is a trait impl, ensure the method
                                    // exists in trait
2082
                                    this.check_trait_item(impl_item.ident.name,
2083 2084
                                                          impl_item.span,
                                        |n, s| ResolutionError::MethodNotMemberOfTrait(n, s));
2085 2086 2087 2088 2089

                                    // We also need a new scope for the method-
                                    // specific type parameters.
                                    let type_parameters =
                                        HasTypeParameters(&sig.generics,
V
Vadim Petrochenkov 已提交
2090
                                                          MethodRibKind(!sig.decl.has_self()));
2091
                                    this.with_type_parameter_rib(type_parameters, |this| {
2092
                                        visit::walk_impl_item(this, impl_item);
2093 2094
                                    });
                                }
2095
                                ImplItemKind::Type(ref ty) => {
2096
                                    // If this is a trait impl, ensure the type
2097
                                    // exists in trait
2098
                                    this.check_trait_item(impl_item.ident.name,
2099 2100
                                                          impl_item.span,
                                        |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
2101

2102 2103
                                    this.visit_ty(ty);
                                }
2104
                                ImplItemKind::Macro(_) => panic!("unexpanded macro in resolve!"),
2105
                            }
2106
                        }
2107
                    });
2108
                });
2109
            }, Some(&generics));
2110
        });
2111 2112
    }

2113
    fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
C
corentih 已提交
2114 2115 2116 2117
        where F: FnOnce(Name, &str) -> ResolutionError
    {
        // If there is a TraitRef in scope for an impl, then the method must be in the
        // trait.
2118
        if let Some((did, ref trait_ref)) = self.current_trait_ref {
2119
            if !self.trait_item_map.contains_key(&(name, did)) {
2120
                let path_str = path_names_to_string(&trait_ref.path, 0);
J
Jonas Schievink 已提交
2121
                resolve_error(self, span, err(name, &path_str));
2122 2123 2124 2125
            }
        }
    }

E
Eduard Burtescu 已提交
2126
    fn resolve_local(&mut self, local: &Local) {
2127
        // Resolve the type.
2128
        walk_list!(self, visit_ty, &local.ty);
2129

2130
        // Resolve the initializer.
2131
        walk_list!(self, visit_expr, &local.init);
2132 2133

        // Resolve the pattern.
2134
        self.resolve_pattern(&local.pat, PatternSource::Let, &mut FxHashMap());
2135 2136
    }

J
John Clements 已提交
2137 2138 2139 2140
    // 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 已提交
2141
    fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2142
        let mut binding_map = FxHashMap();
2143 2144 2145 2146 2147 2148 2149 2150

        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 };
2151
                    binding_map.insert(ident.node, binding_info);
2152 2153 2154
                }
            }
            true
2155
        });
2156 2157

        binding_map
2158 2159
    }

J
John Clements 已提交
2160 2161
    // 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 已提交
2162
    fn check_consistent_bindings(&mut self, arm: &Arm) {
2163
        if arm.pats.is_empty() {
C
corentih 已提交
2164
            return;
2165
        }
J
Jonas Schievink 已提交
2166
        let map_0 = self.binding_mode_map(&arm.pats[0]);
D
Daniel Micay 已提交
2167
        for (i, p) in arm.pats.iter().enumerate() {
J
Jonas Schievink 已提交
2168
            let map_i = self.binding_mode_map(&p);
2169

2170
            for (&key, &binding_0) in &map_0 {
2171
                match map_i.get(&key) {
C
corentih 已提交
2172
                    None => {
2173 2174
                        let error = ResolutionError::VariableNotBoundInPattern(key.name, 1, i + 1);
                        resolve_error(self, p.span, error);
C
corentih 已提交
2175 2176 2177 2178 2179
                    }
                    Some(binding_i) => {
                        if binding_0.binding_mode != binding_i.binding_mode {
                            resolve_error(self,
                                          binding_i.span,
M
Mikhail Modin 已提交
2180 2181 2182 2183
                                          ResolutionError::VariableBoundWithDifferentMode(
                                              key.name,
                                              i + 1,
                                              binding_0.span));
C
corentih 已提交
2184
                        }
2185
                    }
2186 2187 2188
                }
            }

2189
            for (&key, &binding) in &map_i {
2190
                if !map_0.contains_key(&key) {
2191 2192
                    resolve_error(self,
                                  binding.span,
2193
                                  ResolutionError::VariableNotBoundInPattern(key.name, i + 1, 1));
2194 2195 2196
                }
            }
        }
2197 2198
    }

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

2202
        let mut bindings_list = FxHashMap();
2203
        for pattern in &arm.pats {
2204
            self.resolve_pattern(&pattern, PatternSource::Match, &mut bindings_list);
2205 2206
        }

2207 2208 2209 2210
        // This has to happen *after* we determine which
        // pat_idents are variants
        self.check_consistent_bindings(arm);

2211
        walk_list!(self, visit_expr, &arm.guard);
J
Jonas Schievink 已提交
2212
        self.visit_expr(&arm.body);
2213

J
Jeffrey Seyfried 已提交
2214
        self.ribs[ValueNS].pop();
2215 2216
    }

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

2223
        let mut num_macro_definition_ribs = 0;
2224 2225
        if let Some(anonymous_module) = anonymous_module {
            debug!("(resolving block) found anonymous module, moving down");
J
Jeffrey Seyfried 已提交
2226 2227
            self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
            self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
2228
            self.current_module = anonymous_module;
2229
            self.finalize_current_module_macro_resolutions();
2230
        } else {
J
Jeffrey Seyfried 已提交
2231
            self.ribs[ValueNS].push(Rib::new(NormalRibKind));
2232 2233 2234
        }

        // Descend into the block.
2235 2236
        for stmt in &block.stmts {
            if let Some(marks) = self.macros_at_scope.remove(&stmt.id) {
2237
                num_macro_definition_ribs += marks.len() as u32;
2238
                for mark in marks {
J
Jeffrey Seyfried 已提交
2239
                    self.ribs[ValueNS].push(Rib::new(MacroDefinition(mark)));
2240
                    self.label_ribs.push(Rib::new(MacroDefinition(mark)));
2241 2242 2243 2244 2245
                }
            }

            self.visit_stmt(stmt);
        }
2246 2247

        // Move back up.
J
Jeffrey Seyfried 已提交
2248
        self.current_module = orig_module;
2249
        for _ in 0 .. num_macro_definition_ribs {
J
Jeffrey Seyfried 已提交
2250
            self.ribs[ValueNS].pop();
2251
            self.label_ribs.pop();
2252
        }
J
Jeffrey Seyfried 已提交
2253
        self.ribs[ValueNS].pop();
J
Jeffrey Seyfried 已提交
2254
        if let Some(_) = anonymous_module {
J
Jeffrey Seyfried 已提交
2255
            self.ribs[TypeNS].pop();
G
Garming Sam 已提交
2256
        }
2257
        debug!("(resolving block) leaving block");
2258 2259
    }

F
Felix S. Klock II 已提交
2260
    fn resolve_type(&mut self, ty: &Ty) {
2261
        match ty.node {
2262
            TyKind::Path(ref maybe_qself, ref path) => {
2263
                // This is a path in the type namespace. Walk through scopes
2264
                // looking for it.
2265 2266
                if let Some(def) = self.resolve_possibly_assoc_item(ty.id, maybe_qself.as_ref(),
                                                                    path, TypeNS) {
2267
                    match def.base_def {
2268
                        Def::Mod(..) if def.depth == 0 => {
2269 2270 2271 2272 2273 2274 2275 2276 2277 2278
                            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);
                        }
                    }
2279 2280
                } else {
                    self.record_def(ty.id, err_path_resolution());
2281

2282 2283 2284 2285
                    // 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 {
2286 2287 2288 2289
                        let kind = if maybe_qself.is_some() {
                            "associated type"
                        } else {
                            "type name"
2290
                        };
2291

C
corentih 已提交
2292 2293 2294
                        let is_invalid_self_type_name = path.segments.len() > 0 &&
                                                        maybe_qself.is_none() &&
                                                        path.segments[0].identifier.name ==
2295
                                                        keywords::SelfType.name();
G
Guillaume Gomez 已提交
2296
                        if is_invalid_self_type_name {
2297 2298
                            resolve_error(self,
                                          ty.span,
2299
                                          ResolutionError::SelfUsedOutsideImplOrTrait);
2300
                        } else {
2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312
                            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(_) |
2313
                                        Def::Union(_) |
2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328
                                        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 已提交
2329
                        }
2330 2331
                    }
                }
2332
            }
2333
            _ => {}
2334
        }
2335
        // Resolve embedded types.
2336
        visit::walk_ty(self, ty);
2337 2338
    }

2339
    fn fresh_binding(&mut self,
J
Jeffrey Seyfried 已提交
2340
                     ident: &SpannedIdent,
2341 2342 2343
                     pat_id: NodeId,
                     outer_pat_id: NodeId,
                     pat_src: PatternSource,
2344
                     bindings: &mut FxHashMap<Ident, NodeId>)
2345 2346
                     -> PathResolution {
        // Add the binding to the local ribs, if it
2347 2348
        // doesn't already exist in the bindings map. (We
        // must not add it if it's in the bindings map
2349 2350
        // because that breaks the assumptions later
        // passes make about or-patterns.)
2351
        let mut def = Def::Local(self.definitions.local_def_id(pat_id));
2352
        match bindings.get(&ident.node).cloned() {
2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371
            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 => {
2372 2373
                // `Variant1(a) | Variant2(a)`, ok
                // Reuse definition from the first `a`.
J
Jeffrey Seyfried 已提交
2374
                def = self.ribs[ValueNS].last_mut().unwrap().bindings[&ident.node];
2375 2376 2377 2378 2379 2380
            }
            Some(..) => {
                span_bug!(ident.span, "two bindings with the same name from \
                                       unexpected pattern source {:?}", pat_src);
            }
            None => {
2381
                // A completely fresh binding, add to the lists if it's valid.
2382
                if ident.node.name != keywords::Invalid.name() {
2383
                    bindings.insert(ident.node, outer_pat_id);
J
Jeffrey Seyfried 已提交
2384
                    self.ribs[ValueNS].last_mut().unwrap().bindings.insert(ident.node, def);
2385
                }
2386
            }
2387
        }
2388

2389
        PathResolution::new(def)
2390
    }
2391

2392
    fn resolve_pattern_path<ExpectedFn>(&mut self,
2393 2394 2395 2396 2397 2398
                                        pat_id: NodeId,
                                        qself: Option<&QSelf>,
                                        path: &Path,
                                        namespace: Namespace,
                                        expected_fn: ExpectedFn,
                                        expected_what: &str)
2399 2400
        where ExpectedFn: FnOnce(Def) -> bool
    {
2401 2402 2403
        let resolution = if let Some(resolution) = self.resolve_possibly_assoc_item(pat_id,
                                                                        qself, path, namespace) {
            if resolution.depth == 0 {
2404
                if expected_fn(resolution.base_def) || resolution.base_def == Def::Err {
2405
                    resolution
2406
                } else {
2407 2408 2409 2410 2411 2412
                    resolve_error(
                        self,
                        path.span,
                        ResolutionError::PatPathUnexpected(expected_what,
                                                           resolution.kind_name(), path)
                    );
2413 2414
                    err_path_resolution()
                }
2415 2416 2417 2418
            } 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.
2419 2420 2421 2422
                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);
2423
                }
2424
                resolution
2425
            }
2426 2427 2428 2429 2430 2431 2432 2433 2434
        } 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()
2435
        };
2436

2437 2438 2439
        self.record_def(pat_id, resolution);
    }

V
Vadim Petrochenkov 已提交
2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451
    fn resolve_struct_path(&mut self, node_id: NodeId, path: &Path) {
        // Resolution logic is equivalent for expressions and patterns,
        // reuse `resolve_pattern_path` for both.
        self.resolve_pattern_path(node_id, None, path, TypeNS, |def| {
            match def {
                Def::Struct(..) | Def::Union(..) | Def::Variant(..) |
                Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => true,
                _ => false,
            }
        }, "struct, variant or union type");
    }

2452 2453 2454 2455 2456
    fn resolve_pattern(&mut self,
                       pat: &Pat,
                       pat_src: PatternSource,
                       // Maps idents to the node ID for the
                       // outermost pattern that binds them.
2457
                       bindings: &mut FxHashMap<Ident, NodeId>) {
2458
        // Visit all direct subpatterns of this pattern.
2459 2460 2461 2462 2463 2464
        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.
2465
                    let binding = self.resolve_ident_in_lexical_scope(ident.node, ValueNS, None)
2466
                                      .and_then(LexicalScopeBinding::item);
2467
                    let resolution = binding.map(NameBinding::def).and_then(|def| {
2468 2469
                        let always_binding = !pat_src.is_refutable() || opt_pat.is_some() ||
                                             bmode != BindingMode::ByValue(Mutability::Immutable);
2470
                        match def {
2471 2472 2473 2474
                            Def::StructCtor(_, CtorKind::Const) |
                            Def::VariantCtor(_, CtorKind::Const) |
                            Def::Const(..) if !always_binding => {
                                // A unit struct/variant or constant pattern.
2475 2476
                                let name = ident.node.name;
                                self.record_use(name, ValueNS, binding.unwrap(), ident.span);
2477
                                Some(PathResolution::new(def))
2478
                            }
2479
                            Def::StructCtor(..) | Def::VariantCtor(..) |
2480
                            Def::Const(..) | Def::Static(..) => {
2481
                                // A fresh binding that shadows something unacceptable.
2482
                                resolve_error(
2483
                                    self,
2484 2485
                                    ident.span,
                                    ResolutionError::BindingShadowsSomethingUnacceptable(
2486
                                        pat_src.descr(), ident.node.name, binding.unwrap())
2487
                                );
2488
                                None
2489
                            }
2490
                            Def::Local(..) | Def::Upvar(..) | Def::Fn(..) | Def::Err => {
2491 2492
                                // These entities are explicitly allowed
                                // to be shadowed by fresh bindings.
2493
                                None
2494 2495 2496
                            }
                            def => {
                                span_bug!(ident.span, "unexpected definition for an \
2497
                                                       identifier in pattern: {:?}", def);
2498
                            }
2499
                        }
2500
                    }).unwrap_or_else(|| {
2501
                        self.fresh_binding(ident, pat.id, outer_pat_id, pat_src, bindings)
2502
                    });
2503 2504

                    self.record_def(pat.id, resolution);
2505 2506
                }

2507
                PatKind::TupleStruct(ref path, ..) => {
2508 2509
                    self.resolve_pattern_path(pat.id, None, path, ValueNS, |def| {
                        match def {
2510 2511
                            Def::StructCtor(_, CtorKind::Fn) |
                            Def::VariantCtor(_, CtorKind::Fn) => true,
2512
                            _ => false,
2513
                        }
2514
                    }, "tuple struct/variant");
2515 2516
                }

2517 2518
                PatKind::Path(ref qself, ref path) => {
                    self.resolve_pattern_path(pat.id, qself.as_ref(), path, ValueNS, |def| {
2519
                        match def {
2520 2521
                            Def::StructCtor(_, CtorKind::Const) |
                            Def::VariantCtor(_, CtorKind::Const) |
2522
                            Def::Const(..) | Def::AssociatedConst(..) => true,
2523
                            _ => false,
2524
                        }
2525
                    }, "unit struct/variant or constant");
2526 2527
                }

V
Vadim Petrochenkov 已提交
2528
                PatKind::Struct(ref path, ..) => {
V
Vadim Petrochenkov 已提交
2529
                    self.resolve_struct_path(pat.id, path);
2530
                }
2531 2532

                _ => {}
2533
            }
2534
            true
2535
        });
2536

2537
        visit::walk_pat(self, pat);
2538 2539
    }

2540 2541 2542
    /// Handles paths that may refer to associated items
    fn resolve_possibly_assoc_item(&mut self,
                                   id: NodeId,
2543
                                   maybe_qself: Option<&QSelf>,
2544
                                   path: &Path,
J
Jeffrey Seyfried 已提交
2545
                                   namespace: Namespace)
2546
                                   -> Option<PathResolution> {
2547 2548
        let max_assoc_types;

2549
        match maybe_qself {
2550 2551
            Some(qself) => {
                if qself.position == 0 {
2552 2553 2554
                    // 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)),
2555
                        depth: path.segments.len(),
2556
                    });
2557 2558 2559
                }
                max_assoc_types = path.segments.len() - qself.position;
                // Make sure the trait is valid.
2560
                let _ = self.resolve_trait_reference(id, path, max_assoc_types, None);
2561 2562 2563 2564
            }
            None => {
                max_assoc_types = path.segments.len();
            }
2565 2566 2567
        }

        let mut resolution = self.with_no_errors(|this| {
2568
            this.resolve_path(id, path, 0, namespace).ok()
2569 2570 2571 2572 2573 2574
        });
        for depth in 1..max_assoc_types {
            if resolution.is_some() {
                break;
            }
            self.with_no_errors(|this| {
2575 2576 2577 2578 2579 2580
                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;
                }
2581 2582
            });
        }
2583
        resolution
2584 2585
    }

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

2592
        let span = path.span;
C
corentih 已提交
2593
        let segments = &path.segments[..path.segments.len() - path_depth];
2594

2595
        let mk_res = |def| PathResolution { base_def: def, depth: path_depth };
2596

2597
        if path.global {
2598
            let binding = self.resolve_crate_relative_path(span, segments, namespace);
2599
            return binding.map(|binding| mk_res(binding.def()));
2600 2601
        }

2602
        // Try to find a path to an item in a module.
2603
        let last_ident = segments.last().unwrap().identifier;
V
Cleanup  
Vadim Petrochenkov 已提交
2604 2605 2606 2607 2608 2609 2610
        // 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
2611
                        .get(&last_ident.name)
V
Cleanup  
Vadim Petrochenkov 已提交
2612 2613 2614 2615
                        .map_or(def, |prim_ty| Some(LocalDef::from_def(Def::PrimTy(*prim_ty)))),
                _ => def
            }
        };
2616

2617 2618 2619 2620 2621 2622 2623
        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 已提交
2624 2625
            //     u8::max_value() // OK, resolves to associated function <u8>::max_value,
            //                     // not to non-existent std::u8::max_value
2626 2627 2628 2629
            // }
            //
            // Such behavior is required for backward compatibility.
            // The same fallback is used when `a` resolves to nothing.
2630
            let def = resolve_identifier_with_fallback(self, Some(span)).ok_or(false);
2631
            return def.and_then(|def| self.adjust_local_def(def, span).ok_or(true)).map(mk_res);
N
Nick Cameron 已提交
2632
        }
2633

2634
        let unqualified_def = resolve_identifier_with_fallback(self, None);
2635 2636
        let qualified_binding = self.resolve_module_relative_path(span, segments, namespace);
        match (qualified_binding, unqualified_def) {
2637 2638
            (Ok(binding), Some(ref ud)) if binding.def() == ud.def &&
                                           segments[0].identifier.name.as_str() != "$crate" => {
N
Nick Cameron 已提交
2639 2640
                self.session
                    .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
C
corentih 已提交
2641 2642
                              id,
                              span,
N
Nick Cameron 已提交
2643 2644 2645
                              "unnecessary qualification".to_string());
            }
            _ => {}
2646
        }
N
Nick Cameron 已提交
2647

2648
        qualified_binding.map(|binding| mk_res(binding.def()))
2649 2650
    }

2651
    // Resolve a single identifier
F
Felix S. Klock II 已提交
2652
    fn resolve_identifier(&mut self,
2653
                          identifier: Ident,
2654
                          namespace: Namespace,
2655
                          record_used: Option<Span>)
2656
                          -> Option<LocalDef> {
2657
        if identifier.name == keywords::Invalid.name() {
2658
            return None;
2659 2660
        }

2661 2662
        self.resolve_ident_in_lexical_scope(identifier, namespace, record_used)
            .map(LexicalScopeBinding::local_def)
2663 2664 2665
    }

    // Resolve a local definition, potentially adjusting for closures.
2666
    fn adjust_local_def(&mut self, local_def: LocalDef, span: Span) -> Option<Def> {
2667
        let ribs = match local_def.ribs {
J
Jeffrey Seyfried 已提交
2668 2669
            Some((ns, i)) => &self.ribs[ns][i + 1..],
            None => &[] as &[_],
2670 2671 2672
        };
        let mut def = local_def.def;
        match def {
2673
            Def::Upvar(..) => {
2674
                span_bug!(span, "unexpected {:?} in bindings", def)
2675
            }
2676
            Def::Local(def_id) => {
2677 2678
                for rib in ribs {
                    match rib.kind {
2679
                        NormalRibKind | ModuleRibKind(..) | MacroDefinition(..) => {
2680 2681 2682 2683
                            // Nothing to do. Continue.
                        }
                        ClosureRibKind(function_id) => {
                            let prev_def = def;
2684
                            let node_id = self.definitions.as_local_node_id(def_id).unwrap();
2685

C
corentih 已提交
2686 2687 2688
                            let seen = self.freevars_seen
                                           .entry(function_id)
                                           .or_insert_with(|| NodeMap());
2689
                            if let Some(&index) = seen.get(&node_id) {
2690
                                def = Def::Upvar(def_id, index, function_id);
2691 2692
                                continue;
                            }
C
corentih 已提交
2693 2694 2695
                            let vec = self.freevars
                                          .entry(function_id)
                                          .or_insert_with(|| vec![]);
2696
                            let depth = vec.len();
C
corentih 已提交
2697 2698 2699 2700
                            vec.push(Freevar {
                                def: prev_def,
                                span: span,
                            });
2701

2702
                            def = Def::Upvar(def_id, depth, function_id);
2703 2704
                            seen.insert(node_id, depth);
                        }
2705
                        ItemRibKind | MethodRibKind(_) => {
2706 2707 2708
                            // This was an attempt to access an upvar inside a
                            // named function item. This is not allowed, so we
                            // report an error.
C
corentih 已提交
2709 2710 2711
                            resolve_error(self,
                                          span,
                                          ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
2712 2713 2714 2715
                            return None;
                        }
                        ConstantItemRibKind => {
                            // Still doesn't deal with upvars
C
corentih 已提交
2716 2717 2718
                            resolve_error(self,
                                          span,
                                          ResolutionError::AttemptToUseNonConstantValueInConstant);
2719 2720 2721 2722 2723
                            return None;
                        }
                    }
                }
            }
2724
            Def::TyParam(..) | Def::SelfTy(..) => {
2725 2726
                for rib in ribs {
                    match rib.kind {
2727
                        NormalRibKind | MethodRibKind(_) | ClosureRibKind(..) |
2728
                        ModuleRibKind(..) | MacroDefinition(..) => {
2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750
                            // 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);
2751 2752
    }

2753
    // resolve a "module-relative" path, e.g. a::b::c
F
Felix S. Klock II 已提交
2754
    fn resolve_module_relative_path(&mut self,
2755
                                    span: Span,
2756
                                    segments: &[ast::PathSegment],
2757
                                    namespace: Namespace)
2758 2759
                                    -> Result<&'a NameBinding<'a>,
                                              bool /* true if an error was reported */> {
2760 2761
        let module_path =
            segments.split_last().unwrap().1.iter().map(|ps| ps.identifier).collect::<Vec<_>>();
2762

2763
        let module = match self.resolve_module_path(&module_path, UseLexicalScope, Some(span)) {
2764
            Failed(err) => {
2765 2766 2767
                if let Some((span, msg)) = err {
                    resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
                }
2768
                return Err(true);
2769
            }
2770
            Indeterminate => return Err(false),
2771 2772
            Success(module) => module,
        };
2773

2774
        let name = segments.last().unwrap().identifier.name;
2775
        let result = self.resolve_name_in_module(module, name, namespace, false, false, Some(span));
2776
        result.success().ok_or(false)
2777 2778
    }

2779 2780
    /// Invariant: This must be called only during main resolution, not during
    /// import resolution.
2781 2782 2783 2784 2785
    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,
    {
2786
        let module_path = segments.split_last().unwrap().1.iter().map(T::ident).collect::<Vec<_>>();
2787
        let root = self.graph_root;
2788

2789
        let module = match self.resolve_module_path_from_root(root, &module_path, 0, Some(span)) {
2790
            Failed(err) => {
2791 2792 2793
                if let Some((span, msg)) = err {
                    resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
                }
2794
                return Err(true);
2795 2796
            }

2797
            Indeterminate => return Err(false),
2798

2799 2800
            Success(module) => module,
        };
2801

2802
        let name = segments.last().unwrap().ident().name;
2803
        let result = self.resolve_name_in_module(module, name, namespace, false, false, Some(span));
2804
        result.success().ok_or(false)
2805 2806
    }

C
corentih 已提交
2807 2808
    fn with_no_errors<T, F>(&mut self, f: F) -> T
        where F: FnOnce(&mut Resolver) -> T
J
Jorge Aparicio 已提交
2809
    {
2810
        self.emit_errors = false;
A
Alex Crichton 已提交
2811
        let rs = f(self);
2812 2813 2814 2815
        self.emit_errors = true;
        rs
    }

2816 2817
    // 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 已提交
2818
    // FIXME #34673: This needs testing.
2819 2820 2821 2822
    pub fn with_module_lexical_scope<T, F>(&mut self, module: Module<'a>, f: F) -> T
        where F: FnOnce(&mut Resolver<'a>) -> T,
    {
        self.with_empty_ribs(|this| {
J
Jeffrey Seyfried 已提交
2823 2824
            this.ribs[ValueNS].push(Rib::new(ModuleRibKind(module)));
            this.ribs[TypeNS].push(Rib::new(ModuleRibKind(module)));
2825 2826 2827 2828 2829 2830 2831
            f(this)
        })
    }

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

        let result = f(self);
J
Jeffrey Seyfried 已提交
2836
        self.ribs = ribs;
2837 2838 2839 2840
        self.label_ribs = label_ribs;
        result
    }

2841
    fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
2842
        fn extract_node_id(t: &Ty) -> Option<NodeId> {
2843
            match t.node {
2844 2845
                TyKind::Path(None, _) => Some(t.id),
                TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
2846 2847 2848 2849 2850 2851 2852
                // 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,
            }
        }

2853
        if let Some(node_id) = self.current_self_type.as_ref().and_then(extract_node_id) {
2854
            // Look for a field with the same name in the current self_type.
2855 2856
            if let Some(resolution) = self.def_map.get(&node_id) {
                match resolution.base_def {
2857
                    Def::Struct(did) | Def::Union(did) if resolution.depth == 0 => {
V
Vadim Petrochenkov 已提交
2858 2859
                        if let Some(field_names) = self.field_names.get(&did) {
                            if field_names.iter().any(|&field_name| name == field_name) {
2860 2861
                                return Field;
                            }
2862
                        }
2863
                    }
2864 2865
                    _ => {}
                }
2866
            }
2867 2868 2869
        }

        // Look for a method in the current trait.
2870
        if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
2871 2872
            if let Some(&is_static_method) = self.trait_item_map.get(&(name, trait_did)) {
                if is_static_method {
2873
                    return TraitMethod(path_names_to_string(&trait_ref.path, 0));
2874 2875
                } else {
                    return TraitItem;
2876 2877 2878 2879 2880 2881 2882
                }
            }
        }

        NoSuggestion
    }

2883
    fn find_best_match(&mut self, name: &str) -> SuggestionType {
2884
        if let Some(macro_name) = self.macro_names.iter().find(|n| n.as_str() == name) {
2885 2886 2887
            return SuggestionType::Macro(format!("{}!", macro_name));
        }

J
Jeffrey Seyfried 已提交
2888
        let names = self.ribs[ValueNS]
2889 2890
                    .iter()
                    .rev()
2891
                    .flat_map(|rib| rib.bindings.keys().map(|ident| &ident.name));
2892

2893
        if let Some(found) = find_best_match_for_name(names, name, None) {
J
Jonas Schievink 已提交
2894
            if name != found {
2895
                return SuggestionType::Function(found);
2896
            }
2897
        } SuggestionType::NotFound
2898 2899
    }

J
Jeffrey Seyfried 已提交
2900
    fn resolve_labeled_block(&mut self, label: Option<SpannedIdent>, id: NodeId, block: &Block) {
2901
        if let Some(label) = label {
2902
            let def = Def::Label(id);
2903
            self.with_label_rib(|this| {
J
Jeffrey Seyfried 已提交
2904
                this.label_ribs.last_mut().unwrap().bindings.insert(label.node, def);
2905 2906 2907 2908 2909 2910 2911
                this.visit_block(block);
            });
        } else {
            self.visit_block(block);
        }
    }

2912
    fn resolve_expr(&mut self, expr: &Expr, parent: Option<&Expr>) {
P
Patrick Walton 已提交
2913 2914
        // First, record candidate traits for this expression if it could
        // result in the invocation of a method call.
2915 2916 2917

        self.record_candidate_traits_for_expr_if_necessary(expr);

2918
        // Next, resolve the node.
2919
        match expr.node {
2920
            ExprKind::Path(ref maybe_qself, ref path) => {
2921 2922
                // This is a local path in the value namespace. Walk through
                // scopes looking for it.
2923 2924
                if let Some(path_res) = self.resolve_possibly_assoc_item(expr.id,
                                                            maybe_qself.as_ref(), path, ValueNS) {
2925
                    // Check if struct variant
2926 2927 2928
                    let is_struct_variant = match path_res.base_def {
                        Def::VariantCtor(_, CtorKind::Fictive) => true,
                        _ => false,
2929 2930
                    };
                    if is_struct_variant {
2931
                        let path_name = path_names_to_string(path, 0);
2932

N
Nick Cameron 已提交
2933 2934
                        let mut err = resolve_struct_error(self,
                                        expr.span,
J
Jonas Schievink 已提交
2935
                                        ResolutionError::StructVariantUsedAsFunction(&path_name));
2936

C
corentih 已提交
2937
                        let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
2938 2939
                                          path_name);
                        if self.emit_errors {
2940
                            err.help(&msg);
2941
                        } else {
N
Nick Cameron 已提交
2942
                            err.span_help(expr.span, &msg);
2943
                        }
N
Nick Cameron 已提交
2944
                        err.emit();
2945
                        self.record_def(expr.id, err_path_resolution());
2946
                    } else {
2947
                        // Write the result into the def map.
2948
                        debug!("(resolving expr) resolved `{}`",
2949
                               path_names_to_string(path, 0));
2950

2951 2952
                        // Partial resolutions will need the set of traits in scope,
                        // so they can be completed during typeck.
2953
                        if path_res.depth != 0 {
2954
                            let method_name = path.segments.last().unwrap().identifier.name;
2955
                            let traits = self.get_traits_containing_item(method_name);
2956 2957 2958
                            self.trait_map.insert(expr.id, traits);
                        }

2959
                        self.record_def(expr.id, path_res);
2960
                    }
2961 2962
                } else {
                    // Be helpful if the name refers to a struct
2963
                    let path_name = path_names_to_string(path, 0);
2964
                    let type_res = self.with_no_errors(|this| {
J
Jeffrey Seyfried 已提交
2965
                        this.resolve_path(expr.id, path, 0, TypeNS)
2966
                    });
2967 2968

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

2970
                    if let Ok(Def::Struct(..)) = type_res.map(|r| r.base_def) {
J
Jeffrey Seyfried 已提交
2971 2972
                        let error_variant =
                            ResolutionError::StructVariantUsedAsFunction(&path_name);
2973 2974 2975 2976 2977 2978
                        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 {
2979
                            err.help(&msg);
2980 2981 2982 2983 2984 2985 2986 2987 2988
                        } 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 {
2989
                            let mut method_scope = false;
2990
                            let mut is_static = false;
J
Jeffrey Seyfried 已提交
2991
                            self.ribs[ValueNS].iter().rev().all(|rib| {
2992
                                method_scope = match rib.kind {
2993 2994 2995 2996
                                    MethodRibKind(is_static_) => {
                                        is_static = is_static_;
                                        true
                                    }
2997 2998 2999 3000 3001
                                    ItemRibKind | ConstantItemRibKind => false,
                                    _ => return true, // Keep advancing
                                };
                                false // Stop advancing
                            });
3002

3003
                            if method_scope &&
3004
                                    &path_name[..] == keywords::SelfValue.name().as_str() {
C
corentih 已提交
3005 3006 3007
                                resolve_error(self,
                                              expr.span,
                                              ResolutionError::SelfNotAvailableInStaticMethod);
3008 3009
                            } else {
                                let last_name = path.segments.last().unwrap().identifier.name;
3010 3011
                                let (mut msg, is_field) =
                                    match self.find_fallback_in_self_type(last_name) {
3012 3013 3014
                                    NoSuggestion => {
                                        // limit search to 5 to reduce the number
                                        // of stupid suggestions
3015
                                        (match self.find_best_match(&path_name) {
3016 3017 3018 3019 3020
                                            SuggestionType::Macro(s) => {
                                                format!("the macro `{}`", s)
                                            }
                                            SuggestionType::Function(s) => format!("`{}`", s),
                                            SuggestionType::NotFound => "".to_string(),
3021 3022 3023 3024 3025 3026 3027 3028
                                        }, false)
                                    }
                                    Field => {
                                        (if is_static && method_scope {
                                            "".to_string()
                                        } else {
                                            format!("`self.{}`", path_name)
                                        }, true)
3029
                                    }
3030
                                    TraitItem => (format!("to call `self.{}`", path_name), false),
3031
                                    TraitMethod(path_str) =>
3032
                                        (format!("to call `{}::{}`", path_str, path_name), false),
3033 3034
                                };

3035
                                let mut context =  UnresolvedNameContext::Other;
G
ggomez 已提交
3036
                                let mut def = Def::Err;
3037
                                if !msg.is_empty() {
J
Jonathan Turner 已提交
3038
                                    msg = format!("did you mean {}?", msg);
3039
                                } else {
3040
                                    // we display a help message if this is a module
3041 3042
                                    let name_path: Vec<_> =
                                        path.segments.iter().map(|seg| seg.identifier).collect();
3043

3044
                                    match self.resolve_module_path(&name_path[..],
J
Jeffrey Seyfried 已提交
3045
                                                                   UseLexicalScope,
3046
                                                                   Some(expr.span)) {
G
ggomez 已提交
3047
                                        Success(e) => {
J
Jeffrey Seyfried 已提交
3048
                                            if let Some(def_type) = e.def() {
G
ggomez 已提交
3049 3050
                                                def = def_type;
                                            }
3051
                                            context = UnresolvedNameContext::PathIsMod(parent);
3052 3053 3054
                                        },
                                        _ => {},
                                    };
3055
                                }
3056

3057 3058
                                resolve_error(self,
                                              expr.span,
3059 3060 3061 3062 3063 3064
                                              ResolutionError::UnresolvedName {
                                                  path: &path_name,
                                                  message: &msg,
                                                  context: context,
                                                  is_static_method: method_scope && is_static,
                                                  is_field: is_field,
G
ggomez 已提交
3065
                                                  def: def,
3066
                                              });
3067
                            }
V
Vincent Belliard 已提交
3068
                        }
3069 3070 3071
                    }
                }

3072
                visit::walk_expr(self, expr);
3073 3074
            }

V
Vadim Petrochenkov 已提交
3075
            ExprKind::Struct(ref path, ..) => {
V
Vadim Petrochenkov 已提交
3076
                self.resolve_struct_path(expr.id, path);
3077

3078
                visit::walk_expr(self, expr);
3079 3080
            }

3081
            ExprKind::Break(Some(label)) | ExprKind::Continue(Some(label)) => {
3082
                match self.search_label(label.node) {
3083
                    None => {
3084
                        self.record_def(expr.id, err_path_resolution());
3085
                        resolve_error(self,
3086 3087
                                      label.span,
                                      ResolutionError::UndeclaredLabel(&label.node.name.as_str()))
3088
                    }
3089
                    Some(def @ Def::Label(_)) => {
3090
                        // Since this def is a label, it is never read.
3091
                        self.record_def(expr.id, PathResolution::new(def))
3092 3093
                    }
                    Some(_) => {
3094
                        span_bug!(expr.span, "label wasn't mapped to a label def!")
3095 3096 3097
                    }
                }
            }
3098 3099 3100 3101

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

J
Jeffrey Seyfried 已提交
3102
                self.ribs[ValueNS].push(Rib::new(NormalRibKind));
3103
                self.resolve_pattern(pattern, PatternSource::IfLet, &mut FxHashMap());
3104
                self.visit_block(if_block);
J
Jeffrey Seyfried 已提交
3105
                self.ribs[ValueNS].pop();
3106 3107 3108 3109

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

J
Jeffrey Seyfried 已提交
3110 3111 3112 3113 3114 3115 3116
            ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),

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

3117 3118
            ExprKind::WhileLet(ref pattern, ref subexpression, ref block, label) => {
                self.visit_expr(subexpression);
J
Jeffrey Seyfried 已提交
3119
                self.ribs[ValueNS].push(Rib::new(NormalRibKind));
3120
                self.resolve_pattern(pattern, PatternSource::WhileLet, &mut FxHashMap());
3121

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

J
Jeffrey Seyfried 已提交
3124
                self.ribs[ValueNS].pop();
3125 3126 3127 3128
            }

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

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

J
Jeffrey Seyfried 已提交
3134
                self.ribs[ValueNS].pop();
3135 3136 3137
            }

            ExprKind::Field(ref subexpression, _) => {
3138 3139
                self.resolve_expr(subexpression, Some(expr));
            }
3140
            ExprKind::MethodCall(_, ref types, ref arguments) => {
3141 3142 3143 3144 3145 3146 3147 3148 3149
                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);
                }
            }
3150

B
Brian Anderson 已提交
3151
            _ => {
3152
                visit::walk_expr(self, expr);
3153 3154 3155 3156
            }
        }
    }

E
Eduard Burtescu 已提交
3157
    fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3158
        match expr.node {
3159
            ExprKind::Field(_, name) => {
3160 3161 3162 3163
                // 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.
3164
                let traits = self.get_traits_containing_item(name.node.name);
3165
                self.trait_map.insert(expr.id, traits);
3166
            }
V
Vadim Petrochenkov 已提交
3167
            ExprKind::MethodCall(name, ..) => {
C
corentih 已提交
3168
                debug!("(recording candidate traits for expr) recording traits for {}",
3169
                       expr.id);
3170
                let traits = self.get_traits_containing_item(name.node.name);
3171
                self.trait_map.insert(expr.id, traits);
3172
            }
3173
            _ => {
3174 3175 3176 3177 3178
                // Nothing to do.
            }
        }
    }

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

S
Seo Sanghyeon 已提交
3182 3183 3184 3185
        fn add_trait_info(found_traits: &mut Vec<TraitCandidate>,
                          trait_def_id: DefId,
                          import_id: Option<NodeId>,
                          name: Name) {
3186
            debug!("(adding trait info) found trait {:?} for method '{}'",
C
corentih 已提交
3187 3188
                   trait_def_id,
                   name);
S
Seo Sanghyeon 已提交
3189 3190 3191 3192
            found_traits.push(TraitCandidate {
                def_id: trait_def_id,
                import_id: import_id,
            });
E
Eduard Burtescu 已提交
3193
        }
3194

3195
        let mut found_traits = Vec::new();
J
Jeffrey Seyfried 已提交
3196 3197 3198
        // 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 已提交
3199
                add_trait_info(&mut found_traits, trait_def_id, None, name);
E
Eduard Burtescu 已提交
3200
            }
J
Jeffrey Seyfried 已提交
3201
        }
3202

J
Jeffrey Seyfried 已提交
3203 3204
        let mut search_module = self.current_module;
        loop {
E
Eduard Burtescu 已提交
3205
            // Look for trait children.
3206
            let mut search_in_module = |this: &mut Self, module: Module<'a>| {
J
Jeffrey Seyfried 已提交
3207 3208 3209
                let mut traits = module.traits.borrow_mut();
                if traits.is_none() {
                    let mut collected_traits = Vec::new();
3210
                    module.for_each_child(|name, ns, binding| {
J
Jeffrey Seyfried 已提交
3211
                        if ns != TypeNS { return }
3212
                        if let Def::Trait(_) = binding.def() {
3213
                            collected_traits.push((name, binding));
J
Jeffrey Seyfried 已提交
3214 3215 3216
                        }
                    });
                    *traits = Some(collected_traits.into_boxed_slice());
3217
                }
J
Jeffrey Seyfried 已提交
3218

3219
                for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
3220
                    let trait_def_id = binding.def().def_id();
3221
                    if this.trait_item_map.contains_key(&(name, trait_def_id)) {
S
Seo Sanghyeon 已提交
3222 3223 3224
                        let mut import_id = None;
                        if let NameBindingKind::Import { directive, .. } = binding.kind {
                            let id = directive.id;
3225
                            this.maybe_unused_trait_imports.insert(id);
3226
                            this.add_to_glob_map(id, trait_name);
S
Seo Sanghyeon 已提交
3227 3228 3229
                            import_id = Some(id);
                        }
                        add_trait_info(&mut found_traits, trait_def_id, import_id, name);
J
Jeffrey Seyfried 已提交
3230 3231 3232
                    }
                }
            };
3233
            search_in_module(self, search_module);
3234

J
Jeffrey Seyfried 已提交
3235 3236 3237
            if let ModuleKind::Block(..) = search_module.kind {
                search_module = search_module.parent.unwrap();
            } else {
3238
                if !search_module.no_implicit_prelude {
J
Jeffrey Seyfried 已提交
3239
                    self.prelude.map(|prelude| search_in_module(self, prelude));
3240
                }
J
Jeffrey Seyfried 已提交
3241
                break;
E
Eduard Burtescu 已提交
3242
            }
3243 3244
        }

E
Eduard Burtescu 已提交
3245
        found_traits
3246 3247
    }

3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267
    /// 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() {
3268
            self.populate_module_if_necessary(in_module);
3269 3270 3271 3272

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

                // avoid imports entirely
3273
                if name_binding.is_import() && !name_binding.is_extern_crate() { return; }
3274 3275

                // collect results based on the filter function
3276 3277
                if name == lookup_name && ns == namespace {
                    if filter_fn(name_binding.def()) {
3278
                        // create the path
3279
                        let ident = Ident::with_empty_ctxt(name);
3280 3281 3282 3283 3284
                        let params = PathParameters::none();
                        let segment = PathSegment {
                            identifier: ident,
                            parameters: params,
                        };
3285
                        let span = name_binding.span;
3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299
                        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)
3300
                        if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
3301 3302 3303 3304 3305 3306
                            lookup_results.push(path);
                        }
                    }
                }

                // collect submodules to explore
3307
                if let Ok(module) = name_binding.module() {
3308
                    // form the path
3309 3310 3311 3312 3313
                    let mut path_segments = path_segments.clone();
                    path_segments.push(PathSegment {
                        identifier: Ident::with_empty_ctxt(name),
                        parameters: PathParameters::none(),
                    });
3314

3315
                    if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
3316
                        // add the module to the lookup
3317
                        let is_extern = in_module_is_extern || name_binding.is_extern_crate();
J
Jeffrey Seyfried 已提交
3318
                        if !worklist.iter().any(|&(m, ..)| m.def() == module.def()) {
3319 3320
                            worklist.push((module, path_segments, is_extern));
                        }
3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331
                    }
                }
            })
        }

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

3332 3333
    fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
        debug!("(recording def) recording {:?} for {}", resolution, node_id);
3334
        if let Some(prev_res) = self.def_map.insert(node_id, resolution) {
3335
            panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution);
3336
        }
3337 3338
    }

3339
    fn resolve_visibility(&mut self, vis: &ast::Visibility) -> ty::Visibility {
3340
        let (path, id) = match *vis {
3341 3342 3343
            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),
3344
            ast::Visibility::Inherited => {
J
Jeffrey Seyfried 已提交
3345
                return ty::Visibility::Restricted(self.current_module.normal_ancestor_id.unwrap());
3346
            }
3347 3348
        };

3349
        let segments: Vec<_> = path.segments.iter().map(|seg| seg.identifier).collect();
3350
        let mut path_resolution = err_path_resolution();
3351
        let vis = match self.resolve_module_path(&segments, DontUseLexicalScope, Some(path.span)) {
3352
            Success(module) => {
J
Jeffrey Seyfried 已提交
3353
                path_resolution = PathResolution::new(module.def().unwrap());
J
Jeffrey Seyfried 已提交
3354
                ty::Visibility::Restricted(module.normal_ancestor_id.unwrap())
3355
            }
3356 3357 3358 3359 3360
            Indeterminate => unreachable!(),
            Failed(err) => {
                if let Some((span, msg)) = err {
                    self.session.span_err(span, &format!("failed to resolve module path. {}", msg));
                }
3361 3362 3363
                ty::Visibility::Public
            }
        };
3364
        self.def_map.insert(id, path_resolution);
3365 3366 3367 3368 3369 3370 3371
        if !self.is_accessible(vis) {
            let msg = format!("visibilities can only be restricted to ancestor modules");
            self.session.span_err(path.span, &msg);
        }
        vis
    }

3372
    fn is_accessible(&self, vis: ty::Visibility) -> bool {
J
Jeffrey Seyfried 已提交
3373
        vis.is_accessible_from(self.current_module.normal_ancestor_id.unwrap(), self)
3374 3375
    }

3376
    fn is_accessible_from(&self, vis: ty::Visibility, module: Module<'a>) -> bool {
J
Jeffrey Seyfried 已提交
3377
        vis.is_accessible_from(module.normal_ancestor_id.unwrap(), self)
3378 3379
    }

3380 3381
    fn report_errors(&mut self) {
        self.report_shadowing_errors();
3382
        let mut reported_spans = FxHashSet();
3383

3384
        for &AmbiguityError { span, name, b1, b2, lexical } in &self.ambiguity_errors {
3385 3386 3387 3388 3389 3390
            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)
3391 3392 3393 3394 3395
                .note(&if lexical || !b1.is_glob_import() {
                    "macro-expanded macro imports do not shadow".to_owned()
                } else {
                    format!("consider adding an explicit import of `{}` to disambiguate", name)
                })
3396 3397 3398
                .emit();
        }

3399 3400 3401 3402
        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.
3403 3404 3405 3406
                let node_id = match binding.kind {
                    NameBindingKind::Import { directive, .. } => directive.id,
                    _ => unreachable!(),
                };
3407 3408 3409
                let msg = format!("extern crate `{}` is private", name);
                self.session.add_lint(lint::builtin::INACCESSIBLE_EXTERN_CRATE, node_id, span, msg);
            } else {
3410
                let def = binding.def();
3411 3412 3413 3414
                self.session.span_err(span, &format!("{} `{}` is private", def.kind_name(), name));
            }
        }
    }
3415

3416
    fn report_shadowing_errors(&mut self) {
J
Jeffrey Seyfried 已提交
3417
        for (name, scope) in replace(&mut self.lexical_macro_resolutions, Vec::new()) {
3418
            self.resolve_legacy_scope(scope, name, true);
J
Jeffrey Seyfried 已提交
3419 3420
        }

3421
        let mut reported_errors = FxHashSet();
3422
        for binding in replace(&mut self.disallowed_shadowing, Vec::new()) {
3423
            if self.resolve_legacy_scope(binding.parent, binding.name, false).is_some() &&
3424 3425 3426
               reported_errors.insert((binding.name, binding.span)) {
                let msg = format!("`{}` is already in scope", binding.name);
                self.session.struct_span_err(binding.span, &msg)
3427 3428
                    .note("macro-expanded `macro_rules!`s may not shadow \
                           existing macros (see RFC 1560)")
3429 3430 3431 3432 3433
                    .emit();
            }
        }
    }

3434
    fn report_conflict(&mut self,
3435 3436 3437 3438 3439 3440
                       parent: Module,
                       name: Name,
                       ns: Namespace,
                       binding: &NameBinding,
                       old_binding: &NameBinding) {
        // Error on the second of two conflicting names
3441
        if old_binding.span.lo > binding.span.lo {
3442 3443 3444
            return self.report_conflict(parent, name, ns, old_binding, binding);
        }

J
Jeffrey Seyfried 已提交
3445 3446 3447 3448
        let container = match parent.kind {
            ModuleKind::Def(Def::Mod(_), _) => "module",
            ModuleKind::Def(Def::Trait(_), _) => "trait",
            ModuleKind::Block(..) => "block",
3449 3450 3451
            _ => "enum",
        };

3452
        let (participle, noun) = match old_binding.is_import() {
3453 3454 3455 3456
            true => ("imported", "import"),
            false => ("defined", "definition"),
        };

3457
        let span = binding.span;
3458 3459 3460 3461 3462 3463 3464

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

3465 3466 3467
        let msg = {
            let kind = match (ns, old_binding.module()) {
                (ValueNS, _) => "a value",
3468
                (MacroNS, _) => "a macro",
3469
                (TypeNS, _) if old_binding.is_extern_crate() => "an extern crate",
3470 3471
                (TypeNS, Ok(module)) if module.is_normal() => "a module",
                (TypeNS, Ok(module)) if module.is_trait() => "a trait",
3472 3473 3474 3475 3476 3477 3478
                (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()) {
3479 3480 3481 3482 3483
            (true, true) => {
                let mut e = struct_span_err!(self.session, span, E0259, "{}", msg);
                e.span_label(span, &format!("`{}` was already imported", name));
                e
            },
3484
            (true, _) | (_, true) if binding.is_import() && old_binding.is_import() => {
C
crypto-universe 已提交
3485 3486 3487 3488
                let mut e = struct_span_err!(self.session, span, E0254, "{}", msg);
                e.span_label(span, &"already imported");
                e
            },
M
Mohit Agarwal 已提交
3489 3490 3491 3492 3493
            (true, _) | (_, true) => {
                let mut e = struct_span_err!(self.session, span, E0260, "{}", msg);
                e.span_label(span, &format!("`{}` already imported", name));
                e
            },
3494
            _ => match (old_binding.is_import(), binding.is_import()) {
T
trixnz 已提交
3495 3496 3497 3498 3499
                (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 已提交
3500 3501 3502 3503 3504
                (true, true) => {
                    let mut e = struct_span_err!(self.session, span, E0252, "{}", msg);
                    e.span_label(span, &format!("already imported"));
                    e
                },
3505
                _ => {
3506 3507 3508
                    let mut e = struct_span_err!(self.session, span, E0255, "{}", msg);
                    e.span_label(span, &format!("`{}` was already imported", name));
                    e
3509
                }
3510 3511 3512
            },
        };

3513
        if old_binding.span != syntax_pos::DUMMY_SP {
3514
            err.span_label(old_binding.span, &format!("previous {} of `{}` here", noun, name));
3515 3516
        }
        err.emit();
3517
        self.name_already_seen.insert(name, span);
3518 3519
    }
}
3520

3521
fn names_to_string(names: &[Ident]) -> String {
3522 3523
    let mut first = true;
    let mut result = String::new();
3524
    for ident in names {
3525 3526 3527 3528 3529
        if first {
            first = false
        } else {
            result.push_str("::")
        }
3530
        result.push_str(&ident.name.as_str());
C
corentih 已提交
3531
    }
3532 3533 3534 3535
    result
}

fn path_names_to_string(path: &Path, depth: usize) -> String {
3536 3537 3538
    let names: Vec<_> =
        path.segments[..path.segments.len() - depth].iter().map(|seg| seg.identifier).collect();
    names_to_string(&names)
3539 3540
}

3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563
/// 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 {
3564
                session.help(
T
tiehuis 已提交
3565
                    &format!("you can import it into scope: `use {};`.",
3566 3567 3568
                        &path_strings[0]),
                );
            } else {
3569
                session.help("you can import several candidates \
3570 3571 3572 3573 3574
                    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 {
3575
                        session.help(
3576 3577 3578 3579
                            &format!("  and {} other candidates", count).to_string(),
                        );
                        break;
                    } else {
3580
                        session.help(
3581 3582 3583 3584 3585 3586 3587 3588
                            &format!("  `{}`", path_string).to_string(),
                        );
                    }
                }
            }
        }
    } else {
        // nothing found:
3589
        session.help(
3590 3591 3592 3593 3594 3595 3596
            &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()),
        );
    };
}

3597
/// A somewhat inefficient routine to obtain the name of a module.
3598
fn module_to_string(module: Module) -> String {
3599 3600
    let mut names = Vec::new();

3601
    fn collect_mod(names: &mut Vec<Ident>, module: Module) {
J
Jeffrey Seyfried 已提交
3602 3603
        if let ModuleKind::Def(_, name) = module.kind {
            if let Some(parent) = module.parent {
3604
                names.push(Ident::with_empty_ctxt(name));
J
Jeffrey Seyfried 已提交
3605
                collect_mod(names, parent);
3606
            }
J
Jeffrey Seyfried 已提交
3607 3608
        } else {
            // danger, shouldn't be ident?
3609
            names.push(token::str_to_ident("<opaque>"));
J
Jeffrey Seyfried 已提交
3610
            collect_mod(names, module.parent.unwrap());
3611 3612 3613 3614
        }
    }
    collect_mod(&mut names, module);

3615
    if names.is_empty() {
3616 3617
        return "???".to_string();
    }
3618
    names_to_string(&names.into_iter().rev().collect::<Vec<_>>())
3619 3620
}

3621
fn err_path_resolution() -> PathResolution {
3622
    PathResolution::new(Def::Err)
3623 3624
}

N
Niko Matsakis 已提交
3625
#[derive(PartialEq,Copy, Clone)]
3626 3627
pub enum MakeGlobMap {
    Yes,
C
corentih 已提交
3628
    No,
3629 3630
}

3631
__build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }