lib.rs 133.6 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
use self::Namespace::*;
use self::FallbackSuggestion::*;
use self::TypeParameters::*;
use self::RibKind::*;

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

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

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

69
use syntax_pos::{Span, DUMMY_SP};
70 71
use errors::DiagnosticBuilder;

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

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

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

84
mod macros;
A
Alex Crichton 已提交
85
mod check_unused;
86
mod build_reduced_graph;
87
mod resolve_imports;
88

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

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

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

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

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

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

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

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

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

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

497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
#[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",
        }
    }
524 525
}

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

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

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,
546
            MacroNS => self.macro_ns.as_ref().unwrap(),
J
Jeffrey Seyfried 已提交
547 548 549 550 551 552 553 554 555
        }
    }
}

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,
556
            MacroNS => self.macro_ns.as_mut().unwrap(),
J
Jeffrey Seyfried 已提交
557 558 559 560
        }
    }
}

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

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

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

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

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

            self.visit_ty(&argument.ty);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

784
    resolutions: RefCell<FxHashMap<(Name, Namespace), &'a RefCell<NameResolution<'a>>>>,
785
    legacy_macro_resolutions: RefCell<Vec<(Mark, Name, Span)>>,
786

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

790
    no_implicit_prelude: bool,
791

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

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

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

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

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

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

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

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

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

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

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

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

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

875 876 877 878 879 880 881 882 883 884
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
    }
}

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

900 901
struct PrivacyError<'a>(Span, Name, &'a NameBinding<'a>);

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

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

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

928 929 930 931 932 933 934
    // 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 {
935 936
            NameBindingKind::Def(Def::Variant(..)) |
            NameBindingKind::Def(Def::VariantCtor(..)) => true,
937 938
            _ => false,
        }
939 940
    }

941
    fn is_extern_crate(&self) -> bool {
942 943 944 945 946 947 948 949
        match self.kind {
            NameBindingKind::Import {
                directive: &ImportDirective {
                    subclass: ImportDirectiveSubclass::ExternCrate, ..
                }, ..
            } => true,
            _ => false,
        }
950
    }
951 952 953 954 955 956 957

    fn is_import(&self) -> bool {
        match self.kind {
            NameBindingKind::Import { .. } => true,
            _ => false,
        }
    }
958 959 960 961

    fn is_glob_import(&self) -> bool {
        match self.kind {
            NameBindingKind::Import { directive, .. } => directive.is_glob(),
962
            NameBindingKind::Ambiguity { b1, .. } => b1.is_glob_import(),
963 964 965 966 967
            _ => false,
        }
    }

    fn is_importable(&self) -> bool {
968
        match self.def() {
969 970 971 972
            Def::AssociatedConst(..) | Def::Method(..) | Def::AssociatedTy(..) => false,
            _ => true,
        }
    }
973 974
}

975
/// Interns the names of the primitive types.
F
Felix S. Klock II 已提交
976
struct PrimitiveTypeTable {
977
    primitive_types: FxHashMap<Name, PrimTy>,
978
}
979

980
impl PrimitiveTypeTable {
K
Kevin Butler 已提交
981
    fn new() -> PrimitiveTypeTable {
982
        let mut table = PrimitiveTypeTable { primitive_types: FxHashMap() };
C
corentih 已提交
983 984 985

        table.intern("bool", TyBool);
        table.intern("char", TyChar);
986 987
        table.intern("f32", TyFloat(FloatTy::F32));
        table.intern("f64", TyFloat(FloatTy::F64));
988 989 990 991 992
        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 已提交
993
        table.intern("str", TyStr);
994 995 996 997 998
        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 已提交
999 1000 1001 1002

        table
    }

1003
    fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1004
        self.primitive_types.insert(Symbol::intern(string), primitive_type);
1005 1006 1007
    }
}

1008
/// The main resolver class.
1009
pub struct Resolver<'a> {
E
Eduard Burtescu 已提交
1010
    session: &'a Session,
1011

1012
    pub definitions: Definitions,
1013

1014 1015
    // Maps the node id of a statement to the expansions of the `macro_rules!`s
    // immediately above the statement (if appropriate).
1016
    macros_at_scope: FxHashMap<NodeId, Vec<Mark>>,
1017

1018
    graph_root: Module<'a>,
1019

1020 1021
    prelude: Option<Module<'a>>,

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

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

1028 1029 1030 1031
    // All imports known to succeed or fail.
    determined_imports: Vec<&'a ImportDirective<'a>>,

    // All non-determined imports.
1032
    indeterminate_imports: Vec<&'a ImportDirective<'a>>,
1033 1034

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

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

1041
    // The current set of local scopes, for labels.
1042
    label_ribs: Vec<Rib<'a>>,
1043

1044
    // The trait that the current context can refer to.
1045 1046 1047 1048
    current_trait_ref: Option<(DefId, TraitRef)>,

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

1050
    // The idents for the primitive types.
E
Eduard Burtescu 已提交
1051
    primitive_type_table: PrimitiveTypeTable,
1052

1053 1054
    pub def_map: DefMap,
    pub freevars: FreevarMap,
1055
    freevars_seen: NodeMap<NodeMap<usize>>,
1056 1057
    pub export_map: ExportMap,
    pub trait_map: TraitMap,
1058

1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
    // 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`.
1073
    module_map: NodeMap<Module<'a>>,
1074
    extern_crate_roots: FxHashMap<(CrateNum, bool /* MacrosOnly? */), Module<'a>>,
1075

1076
    pub make_glob_map: bool,
1077 1078
    // Maps imports to the names of items actually imported (this actually maps
    // all imports, but only glob imports are actually interesting).
1079
    pub glob_map: GlobMap,
1080

1081 1082
    used_imports: FxHashSet<(NodeId, Namespace)>,
    used_crates: FxHashSet<CrateNum>,
1083
    pub maybe_unused_trait_imports: NodeSet,
G
Garming Sam 已提交
1084

1085
    privacy_errors: Vec<PrivacyError<'a>>,
J
Jeffrey Seyfried 已提交
1086
    ambiguity_errors: Vec<AmbiguityError<'a>>,
1087
    disallowed_shadowing: Vec<&'a LegacyBinding<'a>>,
1088 1089

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

1093
    pub exported_macros: Vec<ast::MacroDef>,
1094
    crate_loader: &'a mut CrateLoader,
1095
    macro_names: FxHashSet<Name>,
1096
    builtin_macros: FxHashMap<Name, &'a NameBinding<'a>>,
1097
    lexical_macro_resolutions: Vec<(Name, &'a Cell<LegacyScope<'a>>)>,
J
Jeffrey Seyfried 已提交
1098 1099
    macro_map: FxHashMap<DefId, Rc<SyntaxExtension>>,
    macro_exports: Vec<Export>,
1100 1101

    // Maps the `Mark` of an expansion to its containing module or block.
1102
    invocations: FxHashMap<Mark, &'a InvocationData<'a>>,
1103 1104 1105

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

1108
pub struct ResolverArenas<'a> {
1109
    modules: arena::TypedArena<ModuleS<'a>>,
1110
    local_modules: RefCell<Vec<Module<'a>>>,
1111
    name_bindings: arena::TypedArena<NameBinding<'a>>,
1112
    import_directives: arena::TypedArena<ImportDirective<'a>>,
1113
    name_resolutions: arena::TypedArena<RefCell<NameResolution<'a>>>,
1114
    invocation_data: arena::TypedArena<InvocationData<'a>>,
J
Jeffrey Seyfried 已提交
1115
    legacy_bindings: arena::TypedArena<LegacyBinding<'a>>,
1116 1117 1118
}

impl<'a> ResolverArenas<'a> {
1119
    fn alloc_module(&'a self, module: ModuleS<'a>) -> Module<'a> {
1120 1121 1122 1123 1124 1125 1126 1127
        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()
1128 1129 1130 1131
    }
    fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
        self.name_bindings.alloc(name_binding)
    }
1132 1133
    fn alloc_import_directive(&'a self, import_directive: ImportDirective<'a>)
                              -> &'a ImportDirective {
1134 1135
        self.import_directives.alloc(import_directive)
    }
1136 1137 1138
    fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
        self.name_resolutions.alloc(Default::default())
    }
1139 1140 1141
    fn alloc_invocation_data(&'a self, expansion_data: InvocationData<'a>)
                             -> &'a InvocationData<'a> {
        self.invocation_data.alloc(expansion_data)
J
Jeffrey Seyfried 已提交
1142
    }
J
Jeffrey Seyfried 已提交
1143 1144 1145
    fn alloc_legacy_binding(&'a self, binding: LegacyBinding<'a>) -> &'a LegacyBinding<'a> {
        self.legacy_bindings.alloc(binding)
    }
1146 1147
}

1148
impl<'a> ty::NodeIdTree for Resolver<'a> {
1149 1150
    fn is_descendant_of(&self, mut node: NodeId, ancestor: NodeId) -> bool {
        while node != ancestor {
J
Jeffrey Seyfried 已提交
1151
            node = match self.module_map[&node].parent {
J
Jeffrey Seyfried 已提交
1152
                Some(parent) => parent.normal_ancestor_id.unwrap(),
1153
                None => return false,
1154
            }
1155
        }
J
Jeffrey Seyfried 已提交
1156
        true
1157 1158 1159
    }
}

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

1182 1183 1184 1185
    fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution> {
        self.def_map.get(&id).cloned()
    }

1186
    fn record_resolution(&mut self, id: NodeId, def: Def) {
1187
        self.def_map.insert(id, PathResolution::new(def));
1188
    }
1189

1190 1191
    fn definitions(&mut self) -> &mut Definitions {
        &mut self.definitions
1192 1193 1194
    }
}

1195
impl<'a> Resolver<'a> {
1196
    pub fn new(session: &'a Session,
1197
               krate: &Crate,
1198
               make_glob_map: MakeGlobMap,
1199
               crate_loader: &'a mut CrateLoader,
1200
               arenas: &'a ResolverArenas<'a>)
1201
               -> Resolver<'a> {
1202 1203 1204 1205 1206 1207
        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()))
        });
1208 1209
        let mut module_map = NodeMap();
        module_map.insert(CRATE_NODE_ID, graph_root);
K
Kevin Butler 已提交
1210

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

1214
        let mut invocations = FxHashMap();
1215 1216
        invocations.insert(Mark::root(),
                           arenas.alloc_invocation_data(InvocationData::root(graph_root)));
1217

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

1221
            definitions: definitions,
1222
            macros_at_scope: FxHashMap(),
1223

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

1229 1230
            trait_item_map: FxHashMap(),
            field_names: FxHashMap(),
K
Kevin Butler 已提交
1231

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

1235
            current_module: graph_root,
J
Jeffrey Seyfried 已提交
1236 1237 1238
            ribs: PerNS {
                value_ns: vec![Rib::new(ModuleRibKind(graph_root))],
                type_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1239
                macro_ns: None,
J
Jeffrey Seyfried 已提交
1240
            },
1241
            label_ribs: Vec::new(),
K
Kevin Butler 已提交
1242 1243 1244 1245 1246 1247

            current_trait_ref: None,
            current_self_type: None,

            primitive_type_table: PrimitiveTypeTable::new(),

1248
            def_map: NodeMap(),
1249 1250
            freevars: NodeMap(),
            freevars_seen: NodeMap(),
1251 1252
            export_map: NodeMap(),
            trait_map: NodeMap(),
1253
            module_map: module_map,
1254
            extern_crate_roots: FxHashMap(),
K
Kevin Butler 已提交
1255

1256
            make_glob_map: make_glob_map == MakeGlobMap::Yes,
1257
            glob_map: NodeMap(),
G
Garming Sam 已提交
1258

1259 1260
            used_imports: FxHashSet(),
            used_crates: FxHashSet(),
S
Seo Sanghyeon 已提交
1261 1262
            maybe_unused_trait_imports: NodeSet(),

1263
            privacy_errors: Vec::new(),
1264
            ambiguity_errors: Vec::new(),
1265
            disallowed_shadowing: Vec::new(),
1266 1267

            arenas: arenas,
1268 1269
            dummy_binding: arenas.alloc_name_binding(NameBinding {
                kind: NameBindingKind::Def(Def::Err),
1270
                expansion: Mark::root(),
1271 1272 1273
                span: DUMMY_SP,
                vis: ty::Visibility::Public,
            }),
1274
            use_extern_macros: session.features.borrow().use_extern_macros,
1275

1276
            exported_macros: Vec::new(),
1277
            crate_loader: crate_loader,
1278 1279
            macro_names: FxHashSet(),
            builtin_macros: FxHashMap(),
J
Jeffrey Seyfried 已提交
1280
            lexical_macro_resolutions: Vec::new(),
J
Jeffrey Seyfried 已提交
1281 1282
            macro_map: FxHashMap(),
            macro_exports: Vec::new(),
1283
            invocations: invocations,
1284
            name_already_seen: FxHashMap(),
1285 1286 1287
        }
    }

1288
    pub fn arenas() -> ResolverArenas<'a> {
1289 1290
        ResolverArenas {
            modules: arena::TypedArena::new(),
1291
            local_modules: RefCell::new(Vec::new()),
1292
            name_bindings: arena::TypedArena::new(),
1293
            import_directives: arena::TypedArena::new(),
1294
            name_resolutions: arena::TypedArena::new(),
1295
            invocation_data: arena::TypedArena::new(),
J
Jeffrey Seyfried 已提交
1296
            legacy_bindings: arena::TypedArena::new(),
K
Kevin Butler 已提交
1297 1298
        }
    }
1299

J
Jeffrey Seyfried 已提交
1300 1301 1302 1303
    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),
1304 1305 1306 1307
            macro_ns: match self.use_extern_macros {
                true => Some(f(self, MacroNS)),
                false => None,
            },
J
Jeffrey Seyfried 已提交
1308 1309 1310
        }
    }

1311 1312
    /// Entry point to crate resolution.
    pub fn resolve_crate(&mut self, krate: &Crate) {
1313
        ImportResolver { resolver: self }.finalize_imports();
1314 1315 1316 1317
        self.current_module = self.graph_root;
        visit::walk_crate(self, krate);

        check_unused::check_crate(self, krate);
1318
        self.report_errors();
1319
        self.crate_loader.postprocess(krate);
1320 1321
    }

1322 1323 1324 1325 1326 1327
    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)
        })
1328 1329
    }

1330 1331
    fn record_use(&mut self, name: Name, ns: Namespace, binding: &'a NameBinding<'a>, span: Span)
                  -> bool /* true if an error was reported */ {
1332
        // track extern crates for unused_extern_crate lint
J
Jeffrey Seyfried 已提交
1333
        if let Some(DefId { krate, .. }) = binding.module().and_then(ModuleS::def_id) {
1334 1335 1336
            self.used_crates.insert(krate);
        }

1337 1338 1339 1340 1341 1342 1343 1344 1345
        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 } => {
1346 1347 1348
                self.ambiguity_errors.push(AmbiguityError {
                    span: span, name: name, lexical: false, b1: b1, b2: b2,
                });
1349 1350 1351
                true
            }
            _ => false
1352
        }
1353
    }
1354

1355 1356
    fn add_to_glob_map(&mut self, id: NodeId, name: Name) {
        if self.make_glob_map {
1357
            self.glob_map.entry(id).or_insert_with(FxHashSet).insert(name);
1358
        }
1359 1360
    }

1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
    /// 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.
    /// }
    /// ```
1375
    ///
1376 1377
    /// Invariant: This must only be called during main resolution, not during
    /// import resolution.
1378
    fn resolve_ident_in_lexical_scope(&mut self,
1379
                                      mut ident: Ident,
1380
                                      ns: Namespace,
1381
                                      record_used: Option<Span>)
1382
                                      -> Option<LexicalScopeBinding<'a>> {
1383
        if ns == TypeNS {
1384
            ident = Ident::with_empty_ctxt(ident.name);
1385
        }
1386

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

J
Jeffrey Seyfried 已提交
1398
            if let ModuleRibKind(module) = self.ribs[ns][i].kind {
1399
                let name = ident.name;
J
Jeffrey Seyfried 已提交
1400
                let item = self.resolve_name_in_module(module, name, ns, false, record_used);
J
Jeffrey Seyfried 已提交
1401
                if let Ok(binding) = item {
1402 1403
                    // The ident resolves to an item.
                    return Some(LexicalScopeBinding::Item(binding));
1404
                }
1405

J
Jeffrey Seyfried 已提交
1406
                if let ModuleKind::Block(..) = module.kind { // We can see through blocks
1407
                } else if !module.no_implicit_prelude {
J
Jeffrey Seyfried 已提交
1408
                    return self.prelude.and_then(|prelude| {
J
Jeffrey Seyfried 已提交
1409
                        self.resolve_name_in_module(prelude, name, ns, false, None).ok()
J
Jeffrey Seyfried 已提交
1410 1411 1412
                    }).map(LexicalScopeBinding::Item)
                } else {
                    return None;
1413
                }
1414
            }
1415

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

1426 1427 1428
        None
    }

1429 1430 1431 1432 1433 1434 1435 1436
    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 }
    }

1437 1438
    // AST resolution
    //
1439
    // We maintain a list of value ribs and type ribs.
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
    //
    // 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.

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

1465
            self.finalize_current_module_macro_resolutions();
1466
            f(self);
1467

1468
            self.current_module = orig_module;
J
Jeffrey Seyfried 已提交
1469 1470
            self.ribs[ValueNS].pop();
            self.ribs[TypeNS].pop();
1471 1472 1473
        } else {
            f(self);
        }
1474 1475
    }

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

1505
    fn resolve_item(&mut self, item: &Item) {
1506
        let name = item.ident.name;
1507

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

1510
        match item.node {
1511 1512
            ItemKind::Enum(_, ref generics) |
            ItemKind::Ty(_, ref generics) |
1513
            ItemKind::Struct(_, ref generics) |
1514
            ItemKind::Union(_, ref generics) |
V
Vadim Petrochenkov 已提交
1515
            ItemKind::Fn(.., ref generics, _) => {
1516
                self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind),
1517
                                             |this| visit::walk_item(this, item));
1518 1519
            }

1520
            ItemKind::DefaultImpl(_, ref trait_ref) => {
1521
                self.with_optional_trait_ref(Some(trait_ref), |_, _| {}, None);
1522
            }
V
Vadim Petrochenkov 已提交
1523
            ItemKind::Impl(.., ref generics, ref opt_trait_ref, ref self_type, ref impl_items) =>
1524
                self.resolve_implementation(generics,
1525
                                            opt_trait_ref,
J
Jonas Schievink 已提交
1526
                                            &self_type,
1527
                                            item.id,
1528
                                            impl_items),
1529

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

                        for trait_item in trait_items {
1539
                            match trait_item.node {
1540
                                TraitItemKind::Const(_, ref default) => {
1541 1542 1543 1544 1545
                                    // 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| {
1546
                                            visit::walk_trait_item(this, trait_item)
1547 1548
                                        });
                                    } else {
1549
                                        visit::walk_trait_item(this, trait_item)
1550 1551
                                    }
                                }
1552
                                TraitItemKind::Method(ref sig, _) => {
1553 1554
                                    let type_parameters =
                                        HasTypeParameters(&sig.generics,
V
Vadim Petrochenkov 已提交
1555
                                                          MethodRibKind(!sig.decl.has_self()));
1556
                                    this.with_type_parameter_rib(type_parameters, |this| {
1557
                                        visit::walk_trait_item(this, trait_item)
1558
                                    });
1559
                                }
1560
                                TraitItemKind::Type(..) => {
1561
                                    this.with_type_parameter_rib(NoTypeParameters, |this| {
1562
                                        visit::walk_trait_item(this, trait_item)
1563
                                    });
1564
                                }
1565
                                TraitItemKind::Macro(_) => panic!("unexpanded macro in resolve!"),
1566 1567 1568
                            };
                        }
                    });
1569
                });
1570 1571
            }

1572
            ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
1573
                self.with_scope(item.id, |this| {
1574
                    visit::walk_item(this, item);
1575
                });
1576 1577
            }

1578
            ItemKind::Const(..) | ItemKind::Static(..) => {
A
Alex Crichton 已提交
1579
                self.with_constant_rib(|this| {
1580
                    visit::walk_item(this, item);
1581
                });
1582
            }
1583

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

1619
            ItemKind::ExternCrate(_) => {
1620
                // do nothing, these are just around to be encoded
1621
            }
1622 1623

            ItemKind::Mac(_) => panic!("unexpanded macro in resolve!"),
1624 1625 1626
        }
    }

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

C
Chris Stankus 已提交
1638 1639
                    if seen_bindings.contains_key(&name) {
                        let span = seen_bindings.get(&name).unwrap();
1640 1641
                        resolve_error(self,
                                      type_parameter.span,
C
Chris Stankus 已提交
1642 1643
                                      ResolutionError::NameAlreadyUsedInTypeParameterList(name,
                                                                                          span));
1644
                    }
C
Chris Stankus 已提交
1645
                    seen_bindings.entry(name).or_insert(type_parameter.span);
1646

1647
                    // plain insert (no renaming)
1648
                    let def_id = self.definitions.local_def_id(type_parameter.id);
1649
                    let def = Def::TyParam(def_id);
1650
                    function_type_rib.bindings.insert(Ident::with_empty_ctxt(name), def);
1651
                    self.record_def(type_parameter.id, PathResolution::new(def));
1652
                }
J
Jeffrey Seyfried 已提交
1653
                self.ribs[TypeNS].push(function_type_rib);
1654 1655
            }

B
Brian Anderson 已提交
1656
            NoTypeParameters => {
1657 1658 1659 1660
                // Nothing to do.
            }
        }

A
Alex Crichton 已提交
1661
        f(self);
1662

J
Jeffrey Seyfried 已提交
1663
        if let HasTypeParameters(..) = type_parameters {
J
Jeffrey Seyfried 已提交
1664
            self.ribs[TypeNS].pop();
1665 1666 1667
        }
    }

C
corentih 已提交
1668 1669
    fn with_label_rib<F>(&mut self, f: F)
        where F: FnOnce(&mut Resolver)
J
Jorge Aparicio 已提交
1670
    {
1671
        self.label_ribs.push(Rib::new(NormalRibKind));
A
Alex Crichton 已提交
1672
        f(self);
J
Jeffrey Seyfried 已提交
1673
        self.label_ribs.pop();
1674
    }
1675

C
corentih 已提交
1676 1677
    fn with_constant_rib<F>(&mut self, f: F)
        where F: FnOnce(&mut Resolver)
J
Jorge Aparicio 已提交
1678
    {
J
Jeffrey Seyfried 已提交
1679 1680
        self.ribs[ValueNS].push(Rib::new(ConstantItemRibKind));
        self.ribs[TypeNS].push(Rib::new(ConstantItemRibKind));
A
Alex Crichton 已提交
1681
        f(self);
J
Jeffrey Seyfried 已提交
1682 1683
        self.ribs[TypeNS].pop();
        self.ribs[ValueNS].pop();
1684 1685
    }

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

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

J
Jeffrey Seyfried 已提交
1711 1712
            let mut err = resolve_struct_error(self, span, {
                ResolutionError::IsNotATrait(&names_to_string(path), def.kind_name())
1713
            });
1714
            if let Some(generics) = generics {
J
Jeffrey Seyfried 已提交
1715
                if let Some(span) = generics.span_for_name(&names_to_string(path)) {
1716 1717 1718
                    err.span_label(span, &"type parameter defined here");
                }
            }
1719 1720

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

J
Jeffrey Seyfried 已提交
1730 1731
            let path = names_to_string(path);
            resolve_error(self, span, ResolutionError::UndeclaredTraitName(&path, candidates));
1732 1733
        }
        err_path_resolution()
1734 1735
    }

1736 1737
    fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
        where F: FnOnce(&mut Resolver) -> T
J
Jorge Aparicio 已提交
1738
    {
1739 1740 1741 1742 1743 1744 1745
        // 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
    }

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

1773 1774 1775 1776 1777 1778
    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....)
1779
        self_type_rib.bindings.insert(keywords::SelfType.ident(), self_def);
J
Jeffrey Seyfried 已提交
1780
        self.ribs[TypeNS].push(self_type_rib);
1781
        f(self);
J
Jeffrey Seyfried 已提交
1782
        self.ribs[TypeNS].pop();
1783 1784
    }

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

1796
            // Resolve the trait reference, if necessary.
1797
            this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
1798
                // Resolve the self type.
1799
                this.visit_ty(self_type);
1800

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

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

1838 1839
                                    this.visit_ty(ty);
                                }
1840
                                ImplItemKind::Macro(_) => panic!("unexpanded macro in resolve!"),
1841
                            }
1842
                        }
1843
                    });
1844
                });
1845
            }, Some(&generics));
1846
        });
1847 1848
    }

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

E
Eduard Burtescu 已提交
1862
    fn resolve_local(&mut self, local: &Local) {
1863
        // Resolve the type.
1864
        walk_list!(self, visit_ty, &local.ty);
1865

1866
        // Resolve the initializer.
1867
        walk_list!(self, visit_expr, &local.init);
1868 1869

        // Resolve the pattern.
1870
        self.resolve_pattern(&local.pat, PatternSource::Let, &mut FxHashMap());
1871 1872
    }

J
John Clements 已提交
1873 1874 1875 1876
    // 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 已提交
1877
    fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
1878
        let mut binding_map = FxHashMap();
1879 1880 1881 1882 1883 1884 1885 1886

        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 };
1887
                    binding_map.insert(ident.node, binding_info);
1888 1889 1890
                }
            }
            true
1891
        });
1892 1893

        binding_map
1894 1895
    }

J
John Clements 已提交
1896 1897
    // 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 已提交
1898
    fn check_consistent_bindings(&mut self, arm: &Arm) {
1899
        if arm.pats.is_empty() {
C
corentih 已提交
1900
            return;
1901
        }
J
Jonas Schievink 已提交
1902
        let map_0 = self.binding_mode_map(&arm.pats[0]);
D
Daniel Micay 已提交
1903
        for (i, p) in arm.pats.iter().enumerate() {
J
Jonas Schievink 已提交
1904
            let map_i = self.binding_mode_map(&p);
1905

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

1925
            for (&key, &binding) in &map_i {
1926
                if !map_0.contains_key(&key) {
1927 1928
                    resolve_error(self,
                                  binding.span,
1929
                                  ResolutionError::VariableNotBoundInPattern(key.name, i + 1, 1));
1930 1931 1932
                }
            }
        }
1933 1934
    }

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

1938
        let mut bindings_list = FxHashMap();
1939
        for pattern in &arm.pats {
1940
            self.resolve_pattern(&pattern, PatternSource::Match, &mut bindings_list);
1941 1942
        }

1943 1944 1945 1946
        // This has to happen *after* we determine which
        // pat_idents are variants
        self.check_consistent_bindings(arm);

1947
        walk_list!(self, visit_expr, &arm.guard);
J
Jonas Schievink 已提交
1948
        self.visit_expr(&arm.body);
1949

J
Jeffrey Seyfried 已提交
1950
        self.ribs[ValueNS].pop();
1951 1952
    }

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

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

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

            self.visit_stmt(stmt);
        }
1982 1983

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

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

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

                    let name = &path_names_to_string(path, 0);
                    let error = ResolutionError::UseOfUndeclared(kind, name, candidates);
                    resolve_error(self, ty.span, error);
2041
                }
2042
            }
2043
        }
2044
        // Resolve embedded types.
2045
        visit::walk_ty(self, ty);
2046 2047
    }

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

2098
        PathResolution::new(def)
2099
    }
2100

2101
    fn resolve_pattern_path<ExpectedFn>(&mut self,
2102 2103 2104 2105 2106 2107
                                        pat_id: NodeId,
                                        qself: Option<&QSelf>,
                                        path: &Path,
                                        namespace: Namespace,
                                        expected_fn: ExpectedFn,
                                        expected_what: &str)
2108 2109
        where ExpectedFn: FnOnce(Def) -> bool
    {
2110 2111 2112
        let resolution = if let Some(resolution) = self.resolve_possibly_assoc_item(pat_id,
                                                                        qself, path, namespace) {
            if resolution.depth == 0 {
2113
                if expected_fn(resolution.base_def) || resolution.base_def == Def::Err {
2114
                    resolution
2115
                } else {
2116 2117 2118 2119 2120 2121
                    resolve_error(
                        self,
                        path.span,
                        ResolutionError::PatPathUnexpected(expected_what,
                                                           resolution.kind_name(), path)
                    );
2122 2123
                    err_path_resolution()
                }
2124 2125 2126 2127
            } 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.
2128 2129 2130 2131
                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);
2132
                }
2133
                resolution
2134
            }
2135
        } else {
J
Jeffrey Seyfried 已提交
2136 2137
            let error = ResolutionError::PatPathUnresolved(expected_what, path);
            resolve_error(self, path.span, error);
2138
            err_path_resolution()
2139
        };
2140

2141 2142 2143
        self.record_def(pat_id, resolution);
    }

V
Vadim Petrochenkov 已提交
2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
    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");
    }

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

                    self.record_def(pat.id, resolution);
2209 2210
                }

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

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

V
Vadim Petrochenkov 已提交
2232
                PatKind::Struct(ref path, ..) => {
V
Vadim Petrochenkov 已提交
2233
                    self.resolve_struct_path(pat.id, path);
2234
                }
2235 2236

                _ => {}
2237
            }
2238
            true
2239
        });
2240

2241
        visit::walk_pat(self, pat);
2242 2243
    }

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

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

J
Jeffrey Seyfried 已提交
2267 2268 2269 2270 2271 2272 2273
        let result = match self.resolve_path(&path, scope, Some(ns), Some(span)) {
            PathResult::NonModule(path_res) => match path_res.base_def {
                Def::Trait(..) if maybe_qself.is_some() => return None,
                _ => path_res,
            },
            PathResult::Module(module) if !module.is_normal() => {
                PathResolution::new(module.def().unwrap())
V
Cleanup  
Vadim Petrochenkov 已提交
2274
            }
2275 2276 2277 2278 2279 2280
            // 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 已提交
2281 2282
            //     u8::max_value() // OK, resolves to associated function <u8>::max_value,
            //                     // not to non-existent std::u8::max_value
2283 2284 2285 2286
            // }
            //
            // Such behavior is required for backward compatibility.
            // The same fallback is used when `a` resolves to nothing.
J
Jeffrey Seyfried 已提交
2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302
            _ if self.primitive_type_table.primitive_types.contains_key(&path[0].name) => {
                PathResolution {
                    base_def: Def::PrimTy(self.primitive_type_table.primitive_types[&path[0].name]),
                    depth: segments.len() - 1,
                }
            }
            PathResult::Module(module) => PathResolution::new(module.def().unwrap()),
            PathResult::Failed(msg, false) => {
                resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
                err_path_resolution()
            }
            _ => return None,
        };

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

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

J
Jeffrey Seyfried 已提交
2317
        Some(result)
2318 2319
    }

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

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

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

            let binding = if let Some(module) = module {
J
Jeffrey Seyfried 已提交
2357
                self.resolve_name_in_module(module, ident.name, ns, false, record_used)
J
Jeffrey Seyfried 已提交
2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372
            } else {
                match self.resolve_ident_in_lexical_scope(ident, ns, record_used) {
                    Some(LexicalScopeBinding::Item(binding)) => Ok(binding),
                    Some(LexicalScopeBinding::Def(def)) if opt_ns.is_some() => {
                        return PathResult::NonModule(PathResolution {
                            base_def: def,
                            depth: path.len() - 1,
                        });
                    }
                    _ => Err(if record_used.is_some() { Determined } else { Undetermined }),
                }
            };

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

J
Jeffrey Seyfried 已提交
2416
        PathResult::Module(module.unwrap())
2417 2418 2419
    }

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

C
corentih 已提交
2440 2441 2442
                            let seen = self.freevars_seen
                                           .entry(function_id)
                                           .or_insert_with(|| NodeMap());
2443
                            if let Some(&index) = seen.get(&node_id) {
2444
                                def = Def::Upvar(def_id, index, function_id);
2445 2446
                                continue;
                            }
C
corentih 已提交
2447 2448 2449
                            let vec = self.freevars
                                          .entry(function_id)
                                          .or_insert_with(|| vec![]);
2450
                            let depth = vec.len();
C
corentih 已提交
2451 2452 2453 2454
                            vec.push(Freevar {
                                def: prev_def,
                                span: span,
                            });
2455

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

                            resolve_error(self,
                                          span,
                                          ResolutionError::TypeParametersFromOuterFunction);
2492
                            return Def::Err;
2493 2494 2495 2496
                        }
                        ConstantItemRibKind => {
                            // see #9186
                            resolve_error(self, span, ResolutionError::OuterTypeParameterContext);
2497
                            return Def::Err;
2498 2499 2500 2501 2502 2503
                        }
                    }
                }
            }
            _ => {}
        }
2504
        return def;
2505 2506
    }

2507 2508
    // 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 已提交
2509
    // FIXME #34673: This needs testing.
2510 2511 2512 2513
    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 已提交
2514 2515
            this.ribs[ValueNS].push(Rib::new(ModuleRibKind(module)));
            this.ribs[TypeNS].push(Rib::new(ModuleRibKind(module)));
2516 2517 2518 2519 2520 2521 2522
            f(this)
        })
    }

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

        let result = f(self);
J
Jeffrey Seyfried 已提交
2527
        self.ribs = ribs;
2528 2529 2530 2531
        self.label_ribs = label_ribs;
        result
    }

2532
    fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
2533
        fn extract_node_id(t: &Ty) -> Option<NodeId> {
2534
            match t.node {
2535 2536
                TyKind::Path(None, _) => Some(t.id),
                TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
2537 2538 2539 2540 2541 2542 2543
                // 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,
            }
        }

2544
        if let Some(node_id) = self.current_self_type.as_ref().and_then(extract_node_id) {
2545
            // Look for a field with the same name in the current self_type.
2546 2547
            if let Some(resolution) = self.def_map.get(&node_id) {
                match resolution.base_def {
2548
                    Def::Struct(did) | Def::Union(did) if resolution.depth == 0 => {
V
Vadim Petrochenkov 已提交
2549 2550
                        if let Some(field_names) = self.field_names.get(&did) {
                            if field_names.iter().any(|&field_name| name == field_name) {
2551 2552
                                return Field;
                            }
2553
                        }
2554
                    }
2555 2556
                    _ => {}
                }
2557
            }
2558 2559 2560
        }

        // Look for a method in the current trait.
2561
        if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
2562 2563
            if let Some(&is_static_method) = self.trait_item_map.get(&(name, trait_did)) {
                if is_static_method {
2564
                    return TraitMethod(path_names_to_string(&trait_ref.path, 0));
2565 2566
                } else {
                    return TraitItem;
2567 2568 2569 2570 2571 2572 2573
                }
            }
        }

        NoSuggestion
    }

2574
    fn find_best_match(&mut self, name: &str) -> SuggestionType {
J
Jeffrey Seyfried 已提交
2575
        if let Some(macro_name) = self.macro_names.iter().find(|&n| n == &name) {
2576 2577 2578
            return SuggestionType::Macro(format!("{}!", macro_name));
        }

J
Jeffrey Seyfried 已提交
2579
        let names = self.ribs[ValueNS]
2580 2581
                    .iter()
                    .rev()
2582
                    .flat_map(|rib| rib.bindings.keys().map(|ident| &ident.name));
2583

2584
        if let Some(found) = find_best_match_for_name(names, name, None) {
2585
            if found != name {
2586
                return SuggestionType::Function(found);
2587
            }
2588
        } SuggestionType::NotFound
2589 2590
    }

J
Jeffrey Seyfried 已提交
2591
    fn resolve_labeled_block(&mut self, label: Option<SpannedIdent>, id: NodeId, block: &Block) {
2592
        if let Some(label) = label {
2593
            let def = Def::Label(id);
2594
            self.with_label_rib(|this| {
J
Jeffrey Seyfried 已提交
2595
                this.label_ribs.last_mut().unwrap().bindings.insert(label.node, def);
2596 2597 2598 2599 2600 2601 2602
                this.visit_block(block);
            });
        } else {
            self.visit_block(block);
        }
    }

2603
    fn resolve_expr(&mut self, expr: &Expr, parent: Option<&Expr>) {
P
Patrick Walton 已提交
2604 2605
        // First, record candidate traits for this expression if it could
        // result in the invocation of a method call.
2606 2607 2608

        self.record_candidate_traits_for_expr_if_necessary(expr);

2609
        // Next, resolve the node.
2610
        match expr.node {
2611
            ExprKind::Path(ref maybe_qself, ref path) => {
2612 2613
                // This is a local path in the value namespace. Walk through
                // scopes looking for it.
2614 2615
                if let Some(path_res) = self.resolve_possibly_assoc_item(expr.id,
                                                            maybe_qself.as_ref(), path, ValueNS) {
2616
                    // Check if struct variant
2617 2618 2619
                    let is_struct_variant = match path_res.base_def {
                        Def::VariantCtor(_, CtorKind::Fictive) => true,
                        _ => false,
2620 2621
                    };
                    if is_struct_variant {
2622
                        let path_name = path_names_to_string(path, 0);
2623

N
Nick Cameron 已提交
2624 2625
                        let mut err = resolve_struct_error(self,
                                        expr.span,
J
Jonas Schievink 已提交
2626
                                        ResolutionError::StructVariantUsedAsFunction(&path_name));
2627

C
corentih 已提交
2628
                        let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
2629
                                          path_name);
J
Jeffrey Seyfried 已提交
2630
                        err.help(&msg);
N
Nick Cameron 已提交
2631
                        err.emit();
2632
                        self.record_def(expr.id, err_path_resolution());
2633
                    } else {
2634
                        // Write the result into the def map.
2635
                        debug!("(resolving expr) resolved `{}`",
2636
                               path_names_to_string(path, 0));
2637

2638 2639
                        // Partial resolutions will need the set of traits in scope,
                        // so they can be completed during typeck.
2640
                        if path_res.depth != 0 {
2641
                            let method_name = path.segments.last().unwrap().identifier.name;
2642
                            let traits = self.get_traits_containing_item(method_name);
2643 2644 2645
                            self.trait_map.insert(expr.id, traits);
                        }

2646
                        self.record_def(expr.id, path_res);
2647
                    }
2648 2649
                } else {
                    // Be helpful if the name refers to a struct
2650
                    let path_name = path_names_to_string(path, 0);
J
Jeffrey Seyfried 已提交
2651 2652 2653 2654 2655 2656 2657
                    let ast::Path { ref segments, global, .. } = *path;
                    let path: Vec<_> = segments.iter().map(|seg| seg.identifier).collect();
                    let scope = if global { PathScope::Global } else { PathScope::Lexical };
                    let type_res = match self.resolve_path(&path, scope, Some(TypeNS), None) {
                        PathResult::NonModule(type_res) => Some(type_res),
                        _ => None,
                    };
2658 2659

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

2661
                    if let Some(Def::Struct(..)) = type_res.map(|r| r.base_def) {
J
Jeffrey Seyfried 已提交
2662 2663
                        let error_variant =
                            ResolutionError::StructVariantUsedAsFunction(&path_name);
2664 2665 2666 2667 2668
                        let mut err = resolve_struct_error(self, expr.span, error_variant);

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

J
Jeffrey Seyfried 已提交
2669
                        err.help(&msg);
2670 2671 2672
                        err.emit();
                    } else {
                        // Keep reporting some errors even if they're ignored above.
J
Jeffrey Seyfried 已提交
2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685
                        let mut method_scope = false;
                        let mut is_static = false;
                        self.ribs[ValueNS].iter().rev().all(|rib| {
                            method_scope = match rib.kind {
                                MethodRibKind(is_static_) => {
                                    is_static = is_static_;
                                    true
                                }
                                ItemRibKind | ConstantItemRibKind => false,
                                _ => return true, // Keep advancing
                            };
                            false // Stop advancing
                        });
2686

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

J
Jeffrey Seyfried 已提交
2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727
                            let mut context = UnresolvedNameContext::Other;
                            let mut def = Def::Err;
                            if !msg.is_empty() {
                                msg = format!("did you mean {}?", msg);
                            } else {
                                // we display a help message if this is a module
                                if let PathResult::Module(module) =
                                        self.resolve_path(&path, scope, None, None) {
                                    def = module.def().unwrap();
                                    context = UnresolvedNameContext::PathIsMod(parent);
                                }
2728
                            }
J
Jeffrey Seyfried 已提交
2729 2730 2731 2732 2733 2734 2735 2736 2737 2738

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

2743
                visit::walk_expr(self, expr);
2744 2745
            }

V
Vadim Petrochenkov 已提交
2746
            ExprKind::Struct(ref path, ..) => {
V
Vadim Petrochenkov 已提交
2747
                self.resolve_struct_path(expr.id, path);
2748

2749
                visit::walk_expr(self, expr);
2750 2751
            }

2752
            ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
2753
                match self.search_label(label.node) {
2754
                    None => {
2755
                        self.record_def(expr.id, err_path_resolution());
2756
                        resolve_error(self,
2757
                                      label.span,
2758
                                      ResolutionError::UndeclaredLabel(&label.node.name.as_str()));
2759
                    }
2760
                    Some(def @ Def::Label(_)) => {
2761
                        // Since this def is a label, it is never read.
2762
                        self.record_def(expr.id, PathResolution::new(def));
2763 2764
                    }
                    Some(_) => {
2765
                        span_bug!(expr.span, "label wasn't mapped to a label def!");
2766 2767
                    }
                }
2768 2769 2770

                // visit `break` argument if any
                visit::walk_expr(self, expr);
2771
            }
2772 2773 2774 2775

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

J
Jeffrey Seyfried 已提交
2776
                self.ribs[ValueNS].push(Rib::new(NormalRibKind));
2777
                self.resolve_pattern(pattern, PatternSource::IfLet, &mut FxHashMap());
2778
                self.visit_block(if_block);
J
Jeffrey Seyfried 已提交
2779
                self.ribs[ValueNS].pop();
2780 2781 2782 2783

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

J
Jeffrey Seyfried 已提交
2784 2785 2786 2787 2788 2789 2790
            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);
            }

2791 2792
            ExprKind::WhileLet(ref pattern, ref subexpression, ref block, label) => {
                self.visit_expr(subexpression);
J
Jeffrey Seyfried 已提交
2793
                self.ribs[ValueNS].push(Rib::new(NormalRibKind));
2794
                self.resolve_pattern(pattern, PatternSource::WhileLet, &mut FxHashMap());
2795

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

J
Jeffrey Seyfried 已提交
2798
                self.ribs[ValueNS].pop();
2799 2800 2801 2802
            }

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

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

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

            ExprKind::Field(ref subexpression, _) => {
2812 2813
                self.resolve_expr(subexpression, Some(expr));
            }
2814
            ExprKind::MethodCall(_, ref types, ref arguments) => {
2815 2816 2817 2818 2819 2820 2821 2822 2823
                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);
                }
            }
2824

B
Brian Anderson 已提交
2825
            _ => {
2826
                visit::walk_expr(self, expr);
2827 2828 2829 2830
            }
        }
    }

E
Eduard Burtescu 已提交
2831
    fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
2832
        match expr.node {
2833
            ExprKind::Field(_, name) => {
2834 2835 2836 2837
                // 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.
2838
                let traits = self.get_traits_containing_item(name.node.name);
2839
                self.trait_map.insert(expr.id, traits);
2840
            }
V
Vadim Petrochenkov 已提交
2841
            ExprKind::MethodCall(name, ..) => {
C
corentih 已提交
2842
                debug!("(recording candidate traits for expr) recording traits for {}",
2843
                       expr.id);
2844
                let traits = self.get_traits_containing_item(name.node.name);
2845
                self.trait_map.insert(expr.id, traits);
2846
            }
2847
            _ => {
2848 2849 2850 2851 2852
                // Nothing to do.
            }
        }
    }

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

S
Seo Sanghyeon 已提交
2856 2857 2858 2859
        fn add_trait_info(found_traits: &mut Vec<TraitCandidate>,
                          trait_def_id: DefId,
                          import_id: Option<NodeId>,
                          name: Name) {
2860
            debug!("(adding trait info) found trait {:?} for method '{}'",
C
corentih 已提交
2861 2862
                   trait_def_id,
                   name);
S
Seo Sanghyeon 已提交
2863 2864 2865 2866
            found_traits.push(TraitCandidate {
                def_id: trait_def_id,
                import_id: import_id,
            });
E
Eduard Burtescu 已提交
2867
        }
2868

2869
        let mut found_traits = Vec::new();
J
Jeffrey Seyfried 已提交
2870 2871 2872
        // 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 已提交
2873
                add_trait_info(&mut found_traits, trait_def_id, None, name);
E
Eduard Burtescu 已提交
2874
            }
J
Jeffrey Seyfried 已提交
2875
        }
2876

J
Jeffrey Seyfried 已提交
2877 2878
        let mut search_module = self.current_module;
        loop {
E
Eduard Burtescu 已提交
2879
            // Look for trait children.
2880
            let mut search_in_module = |this: &mut Self, module: Module<'a>| {
J
Jeffrey Seyfried 已提交
2881 2882 2883
                let mut traits = module.traits.borrow_mut();
                if traits.is_none() {
                    let mut collected_traits = Vec::new();
2884
                    module.for_each_child(|name, ns, binding| {
J
Jeffrey Seyfried 已提交
2885
                        if ns != TypeNS { return }
2886
                        if let Def::Trait(_) = binding.def() {
2887
                            collected_traits.push((name, binding));
J
Jeffrey Seyfried 已提交
2888 2889 2890
                        }
                    });
                    *traits = Some(collected_traits.into_boxed_slice());
2891
                }
J
Jeffrey Seyfried 已提交
2892

2893
                for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
2894
                    let trait_def_id = binding.def().def_id();
2895
                    if this.trait_item_map.contains_key(&(name, trait_def_id)) {
S
Seo Sanghyeon 已提交
2896 2897 2898
                        let mut import_id = None;
                        if let NameBindingKind::Import { directive, .. } = binding.kind {
                            let id = directive.id;
2899
                            this.maybe_unused_trait_imports.insert(id);
2900
                            this.add_to_glob_map(id, trait_name);
S
Seo Sanghyeon 已提交
2901 2902 2903
                            import_id = Some(id);
                        }
                        add_trait_info(&mut found_traits, trait_def_id, import_id, name);
J
Jeffrey Seyfried 已提交
2904 2905 2906
                    }
                }
            };
2907
            search_in_module(self, search_module);
2908

J
Jeffrey Seyfried 已提交
2909 2910 2911
            if let ModuleKind::Block(..) = search_module.kind {
                search_module = search_module.parent.unwrap();
            } else {
2912
                if !search_module.no_implicit_prelude {
J
Jeffrey Seyfried 已提交
2913
                    self.prelude.map(|prelude| search_in_module(self, prelude));
2914
                }
J
Jeffrey Seyfried 已提交
2915
                break;
E
Eduard Burtescu 已提交
2916
            }
2917 2918
        }

E
Eduard Burtescu 已提交
2919
        found_traits
2920 2921
    }

2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941
    /// 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() {
2942
            self.populate_module_if_necessary(in_module);
2943 2944 2945 2946

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

                // avoid imports entirely
2947
                if name_binding.is_import() && !name_binding.is_extern_crate() { return; }
2948 2949

                // collect results based on the filter function
2950 2951
                if name == lookup_name && ns == namespace {
                    if filter_fn(name_binding.def()) {
2952
                        // create the path
2953
                        let ident = Ident::with_empty_ctxt(name);
2954 2955 2956 2957 2958
                        let params = PathParameters::none();
                        let segment = PathSegment {
                            identifier: ident,
                            parameters: params,
                        };
2959
                        let span = name_binding.span;
2960 2961 2962 2963
                        let mut segms = path_segments.clone();
                        segms.push(segment);
                        let path = Path {
                            span: span,
J
Jeffrey Seyfried 已提交
2964
                            global: false,
2965 2966 2967 2968 2969 2970 2971 2972 2973
                            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)
2974
                        if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
2975 2976 2977 2978 2979 2980
                            lookup_results.push(path);
                        }
                    }
                }

                // collect submodules to explore
J
Jeffrey Seyfried 已提交
2981
                if let Some(module) = name_binding.module() {
2982
                    // form the path
2983 2984 2985 2986 2987
                    let mut path_segments = path_segments.clone();
                    path_segments.push(PathSegment {
                        identifier: Ident::with_empty_ctxt(name),
                        parameters: PathParameters::none(),
                    });
2988

2989
                    if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
2990
                        // add the module to the lookup
2991
                        let is_extern = in_module_is_extern || name_binding.is_extern_crate();
J
Jeffrey Seyfried 已提交
2992
                        if !worklist.iter().any(|&(m, ..)| m.def() == module.def()) {
2993 2994
                            worklist.push((module, path_segments, is_extern));
                        }
2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005
                    }
                }
            })
        }

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

3006 3007
    fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
        debug!("(recording def) recording {:?} for {}", resolution, node_id);
3008
        if let Some(prev_res) = self.def_map.insert(node_id, resolution) {
3009
            panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution);
3010
        }
3011 3012
    }

3013
    fn resolve_visibility(&mut self, vis: &ast::Visibility) -> ty::Visibility {
J
Jeffrey Seyfried 已提交
3014
        let (segments, span, id) = match *vis {
3015 3016
            ast::Visibility::Public => return ty::Visibility::Public,
            ast::Visibility::Crate(_) => return ty::Visibility::Restricted(ast::CRATE_NODE_ID),
J
Jeffrey Seyfried 已提交
3017
            ast::Visibility::Restricted { ref path, id } => (&path.segments, path.span, id),
3018
            ast::Visibility::Inherited => {
J
Jeffrey Seyfried 已提交
3019
                return ty::Visibility::Restricted(self.current_module.normal_ancestor_id.unwrap());
3020
            }
3021 3022
        };

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

3044
    fn is_accessible(&self, vis: ty::Visibility) -> bool {
J
Jeffrey Seyfried 已提交
3045
        vis.is_accessible_from(self.current_module.normal_ancestor_id.unwrap(), self)
3046 3047
    }

3048
    fn is_accessible_from(&self, vis: ty::Visibility, module: Module<'a>) -> bool {
J
Jeffrey Seyfried 已提交
3049
        vis.is_accessible_from(module.normal_ancestor_id.unwrap(), self)
3050 3051
    }

3052 3053
    fn report_errors(&mut self) {
        self.report_shadowing_errors();
3054
        let mut reported_spans = FxHashSet();
3055

3056
        for &AmbiguityError { span, name, b1, b2, lexical } in &self.ambiguity_errors {
3057 3058 3059 3060 3061 3062
            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)
3063 3064 3065 3066 3067
                .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)
                })
3068 3069 3070
                .emit();
        }

3071 3072 3073 3074
        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.
3075 3076 3077 3078
                let node_id = match binding.kind {
                    NameBindingKind::Import { directive, .. } => directive.id,
                    _ => unreachable!(),
                };
3079 3080 3081
                let msg = format!("extern crate `{}` is private", name);
                self.session.add_lint(lint::builtin::INACCESSIBLE_EXTERN_CRATE, node_id, span, msg);
            } else {
3082
                let def = binding.def();
3083 3084 3085 3086
                self.session.span_err(span, &format!("{} `{}` is private", def.kind_name(), name));
            }
        }
    }
3087

3088
    fn report_shadowing_errors(&mut self) {
J
Jeffrey Seyfried 已提交
3089
        for (name, scope) in replace(&mut self.lexical_macro_resolutions, Vec::new()) {
3090
            self.resolve_legacy_scope(scope, name, true);
J
Jeffrey Seyfried 已提交
3091 3092
        }

3093
        let mut reported_errors = FxHashSet();
3094
        for binding in replace(&mut self.disallowed_shadowing, Vec::new()) {
3095
            if self.resolve_legacy_scope(&binding.parent, binding.name, false).is_some() &&
3096 3097 3098
               reported_errors.insert((binding.name, binding.span)) {
                let msg = format!("`{}` is already in scope", binding.name);
                self.session.struct_span_err(binding.span, &msg)
3099 3100
                    .note("macro-expanded `macro_rules!`s may not shadow \
                           existing macros (see RFC 1560)")
3101 3102 3103 3104 3105
                    .emit();
            }
        }
    }

3106
    fn report_conflict(&mut self,
3107 3108 3109 3110 3111 3112
                       parent: Module,
                       name: Name,
                       ns: Namespace,
                       binding: &NameBinding,
                       old_binding: &NameBinding) {
        // Error on the second of two conflicting names
3113
        if old_binding.span.lo > binding.span.lo {
3114 3115 3116
            return self.report_conflict(parent, name, ns, old_binding, binding);
        }

J
Jeffrey Seyfried 已提交
3117 3118 3119 3120
        let container = match parent.kind {
            ModuleKind::Def(Def::Mod(_), _) => "module",
            ModuleKind::Def(Def::Trait(_), _) => "trait",
            ModuleKind::Block(..) => "block",
3121 3122 3123
            _ => "enum",
        };

3124
        let (participle, noun) = match old_binding.is_import() {
3125 3126 3127 3128
            true => ("imported", "import"),
            false => ("defined", "definition"),
        };

3129
        let span = binding.span;
3130 3131 3132 3133 3134 3135 3136

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

3137 3138 3139
        let msg = {
            let kind = match (ns, old_binding.module()) {
                (ValueNS, _) => "a value",
3140
                (MacroNS, _) => "a macro",
3141
                (TypeNS, _) if old_binding.is_extern_crate() => "an extern crate",
J
Jeffrey Seyfried 已提交
3142 3143
                (TypeNS, Some(module)) if module.is_normal() => "a module",
                (TypeNS, Some(module)) if module.is_trait() => "a trait",
3144 3145 3146 3147 3148 3149 3150
                (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()) {
3151 3152 3153 3154 3155
            (true, true) => {
                let mut e = struct_span_err!(self.session, span, E0259, "{}", msg);
                e.span_label(span, &format!("`{}` was already imported", name));
                e
            },
3156
            (true, _) | (_, true) if binding.is_import() && old_binding.is_import() => {
C
crypto-universe 已提交
3157 3158 3159 3160
                let mut e = struct_span_err!(self.session, span, E0254, "{}", msg);
                e.span_label(span, &"already imported");
                e
            },
M
Mohit Agarwal 已提交
3161 3162 3163 3164 3165
            (true, _) | (_, true) => {
                let mut e = struct_span_err!(self.session, span, E0260, "{}", msg);
                e.span_label(span, &format!("`{}` already imported", name));
                e
            },
3166
            _ => match (old_binding.is_import(), binding.is_import()) {
T
trixnz 已提交
3167 3168 3169 3170 3171
                (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 已提交
3172 3173 3174 3175 3176
                (true, true) => {
                    let mut e = struct_span_err!(self.session, span, E0252, "{}", msg);
                    e.span_label(span, &format!("already imported"));
                    e
                },
3177
                _ => {
3178 3179 3180
                    let mut e = struct_span_err!(self.session, span, E0255, "{}", msg);
                    e.span_label(span, &format!("`{}` was already imported", name));
                    e
3181
                }
3182 3183 3184
            },
        };

3185
        if old_binding.span != syntax_pos::DUMMY_SP {
3186
            err.span_label(old_binding.span, &format!("previous {} of `{}` here", noun, name));
3187 3188
        }
        err.emit();
3189
        self.name_already_seen.insert(name, span);
3190 3191
    }
}
3192

3193
fn names_to_string(names: &[Ident]) -> String {
3194 3195
    let mut first = true;
    let mut result = String::new();
3196
    for ident in names {
3197 3198 3199 3200 3201
        if first {
            first = false
        } else {
            result.push_str("::")
        }
3202
        result.push_str(&ident.name.as_str());
C
corentih 已提交
3203
    }
3204 3205 3206 3207
    result
}

fn path_names_to_string(path: &Path, depth: usize) -> String {
3208 3209 3210
    let names: Vec<_> =
        path.segments[..path.segments.len() - depth].iter().map(|seg| seg.identifier).collect();
    names_to_string(&names)
3211 3212
}

3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235
/// 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 {
3236
                session.help(
T
tiehuis 已提交
3237
                    &format!("you can import it into scope: `use {};`.",
3238 3239 3240
                        &path_strings[0]),
                );
            } else {
3241
                session.help("you can import several candidates \
3242 3243 3244 3245 3246
                    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 {
3247
                        session.help(
3248 3249 3250 3251
                            &format!("  and {} other candidates", count).to_string(),
                        );
                        break;
                    } else {
3252
                        session.help(
3253 3254 3255 3256 3257 3258 3259 3260
                            &format!("  `{}`", path_string).to_string(),
                        );
                    }
                }
            }
        }
    } else {
        // nothing found:
3261
        session.help(
3262 3263 3264 3265 3266 3267 3268
            &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()),
        );
    };
}

3269
/// A somewhat inefficient routine to obtain the name of a module.
3270
fn module_to_string(module: Module) -> String {
3271 3272
    let mut names = Vec::new();

3273
    fn collect_mod(names: &mut Vec<Ident>, module: Module) {
J
Jeffrey Seyfried 已提交
3274 3275
        if let ModuleKind::Def(_, name) = module.kind {
            if let Some(parent) = module.parent {
3276
                names.push(Ident::with_empty_ctxt(name));
J
Jeffrey Seyfried 已提交
3277
                collect_mod(names, parent);
3278
            }
J
Jeffrey Seyfried 已提交
3279 3280
        } else {
            // danger, shouldn't be ident?
3281
            names.push(Ident::from_str("<opaque>"));
J
Jeffrey Seyfried 已提交
3282
            collect_mod(names, module.parent.unwrap());
3283 3284 3285 3286
        }
    }
    collect_mod(&mut names, module);

3287
    if names.is_empty() {
3288 3289
        return "???".to_string();
    }
3290
    names_to_string(&names.into_iter().rev().collect::<Vec<_>>())
3291 3292
}

3293
fn err_path_resolution() -> PathResolution {
3294
    PathResolution::new(Def::Err)
3295 3296
}

N
Niko Matsakis 已提交
3297
#[derive(PartialEq,Copy, Clone)]
3298 3299
pub enum MakeGlobMap {
    Yes,
C
corentih 已提交
3300
    No,
3301 3302
}

3303
__build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }