lib.rs 149.4 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)]
A
Alex Crichton 已提交
22
#![feature(rustc_diagnostic_macros)]
23
#![feature(rustc_private)]
A
Alex Crichton 已提交
24
#![feature(staged_api)]
25

C
corentih 已提交
26 27 28 29
#[macro_use]
extern crate log;
#[macro_use]
extern crate syntax;
30
extern crate arena;
C
corentih 已提交
31 32 33
#[macro_use]
#[no_link]
extern crate rustc_bitflags;
34
#[macro_use]
35 36
extern crate rustc;

S
Steven Fackler 已提交
37 38 39 40 41 42 43 44
use self::PatternBindingMode::*;
use self::Namespace::*;
use self::ResolveResult::*;
use self::FallbackSuggestion::*;
use self::TypeParameters::*;
use self::RibKind::*;
use self::UseLexicalScopeFlag::*;
use self::ModulePrefixResult::*;
45
use self::AssocItemResolveResult::*;
S
Steven Fackler 已提交
46 47 48 49
use self::BareIdentifierPatternResolution::*;
use self::ParentLink::*;
use self::FallbackChecks::*;

50
use rustc::dep_graph::DepNode;
51
use rustc::hir::map as hir_map;
52 53
use rustc::session::Session;
use rustc::lint;
54
use rustc::middle::cstore::CrateStore;
55 56 57
use rustc::hir::def::*;
use rustc::hir::def_id::DefId;
use rustc::hir::pat_util::pat_bindings;
58
use rustc::ty::subst::{ParamSpace, FnSpace, TypeSpace};
59 60
use rustc::hir::{Freevar, FreevarMap, TraitMap, GlobMap};
use rustc::util::nodemap::{NodeMap, FnvHashMap, FnvHashSet};
61

62
use syntax::ast::{self, FloatTy};
63
use syntax::ast::{CRATE_NODE_ID, Name, NodeId, CrateNum, IntTy, UintTy};
64
use syntax::attr::AttrMetaMethods;
65
use syntax::codemap::{self, Span, Pos};
N
Nick Cameron 已提交
66 67
use syntax::errors::DiagnosticBuilder;
use syntax::parse::token::{self, special_names, special_idents};
68
use syntax::util::lev_distance::find_best_match_for_name;
69

70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
use rustc::hir::intravisit::{self, FnKind, Visitor};
use rustc::hir;
use rustc::hir::{Arm, BindByRef, BindByValue, BindingMode, Block};
use rustc::hir::Crate;
use rustc::hir::{Expr, ExprAgain, ExprBreak, ExprCall, ExprField};
use rustc::hir::{ExprLoop, ExprWhile, ExprMethodCall};
use rustc::hir::{ExprPath, ExprStruct, FnDecl};
use rustc::hir::{ForeignItemFn, ForeignItemStatic, Generics};
use rustc::hir::{ImplItem, Item, ItemConst, ItemEnum, ItemExternCrate};
use rustc::hir::{ItemFn, ItemForeignMod, ItemImpl, ItemMod, ItemStatic, ItemDefaultImpl};
use rustc::hir::{ItemStruct, ItemTrait, ItemTy, ItemUse};
use rustc::hir::Local;
use rustc::hir::{Pat, PatKind, Path, PrimTy};
use rustc::hir::{PathSegment, PathParameters};
use rustc::hir::HirVec;
use rustc::hir::{TraitRef, Ty, TyBool, TyChar, TyFloat, TyInt};
use rustc::hir::{TyRptr, TyStr, TyUint, TyPath, TyPtr};
87

88
use std::collections::{HashMap, HashSet};
89
use std::cell::{Cell, RefCell};
90
use std::fmt;
91
use std::mem::replace;
92

93
use resolve_imports::{ImportDirective, NameResolution};
94

95 96
// NB: This module needs to be declared first so diagnostics are
// registered before they are used.
J
Jeffrey Seyfried 已提交
97
mod diagnostics;
98

A
Alex Crichton 已提交
99
mod check_unused;
100
mod build_reduced_graph;
101
mod resolve_imports;
102

103 104 105 106 107 108 109 110 111 112 113
// Perform the callback, not walking deeper if the return is true
macro_rules! execute_callback {
    ($node: expr, $walker: expr) => (
        if let Some(ref callback) = $walker.callback {
            if callback($node, &mut $walker.resolved) {
                return;
            }
        }
    )
}

114 115
enum SuggestionType {
    Macro(String),
116
    Function(token::InternedString),
117 118 119
    NotFound,
}

120
/// Candidates for a name resolution failure
J
Jeffrey Seyfried 已提交
121
struct SuggestedCandidates {
122 123 124 125
    name: String,
    candidates: Vec<Path>,
}

J
Jeffrey Seyfried 已提交
126
enum ResolutionError<'a> {
127
    /// error E0401: can't use type parameters from outer function
128
    TypeParametersFromOuterFunction,
129
    /// error E0402: cannot use an outer type parameter in this context
130
    OuterTypeParameterContext,
131
    /// error E0403: the name is already used for a type parameter in this type parameter list
132
    NameAlreadyUsedInTypeParameterList(Name),
133
    /// error E0404: is not a trait
134
    IsNotATrait(&'a str),
135
    /// error E0405: use of undeclared trait name
136
    UndeclaredTraitName(&'a str, SuggestedCandidates),
137
    /// error E0406: undeclared associated type
138
    UndeclaredAssociatedType,
139
    /// error E0407: method is not a member of trait
140
    MethodNotMemberOfTrait(Name, &'a str),
141 142 143 144
    /// 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),
145
    /// error E0408: variable `{}` from pattern #1 is not bound in pattern
146
    VariableNotBoundInPattern(Name, usize),
147
    /// error E0409: variable is bound with different mode in pattern #{} than in pattern #1
148
    VariableBoundWithDifferentMode(Name, usize),
149
    /// error E0410: variable from pattern is not bound in pattern #1
150
    VariableNotBoundInParentPattern(Name, usize),
151
    /// error E0411: use of `Self` outside of an impl or trait
152
    SelfUsedOutsideImplOrTrait,
153
    /// error E0412: use of undeclared
154
    UseOfUndeclared(&'a str, &'a str, SuggestedCandidates),
155
    /// error E0413: declaration shadows an enum variant or unit-like struct in scope
156
    DeclarationShadowsEnumVariantOrUnitLikeStruct(Name),
157
    /// error E0414: only irrefutable patterns allowed here
158
    OnlyIrrefutablePatternsAllowedHere(DefId, Name),
159
    /// error E0415: identifier is bound more than once in this parameter list
160
    IdentifierBoundMoreThanOnceInParameterList(&'a str),
161
    /// error E0416: identifier is bound more than once in the same pattern
162
    IdentifierBoundMoreThanOnceInSamePattern(&'a str),
163
    /// error E0417: static variables cannot be referenced in a pattern
164
    StaticVariableReference,
165
    /// error E0418: is not an enum variant, struct or const
166
    NotAnEnumVariantStructOrConst(&'a str),
167
    /// error E0419: unresolved enum variant, struct or const
168
    UnresolvedEnumVariantStructOrConst(&'a str),
169
    /// error E0420: is not an associated const
170
    NotAnAssociatedConst(&'a str),
171
    /// error E0421: unresolved associated const
172
    UnresolvedAssociatedConst(&'a str),
173
    /// error E0422: does not name a struct
174
    DoesNotNameAStruct(&'a str),
175
    /// error E0423: is a struct variant name, but this expression uses it like a function name
176
    StructVariantUsedAsFunction(&'a str),
177
    /// error E0424: `self` is not available in a static method
178
    SelfNotAvailableInStaticMethod,
179
    /// error E0425: unresolved name
180
    UnresolvedName(&'a str, &'a str, UnresolvedNameContext),
181
    /// error E0426: use of undeclared label
182
    UndeclaredLabel(&'a str),
183
    /// error E0427: cannot use `ref` binding mode with ...
184
    CannotUseRefBindingModeWith(&'a str),
185
    /// error E0429: `self` imports are only allowed within a { } list
186
    SelfImportsOnlyAllowedWithin,
187
    /// error E0430: `self` import can only appear once in the list
188
    SelfImportCanOnlyAppearOnceInTheList,
189
    /// error E0431: `self` import can only appear in an import list with a non-empty prefix
190
    SelfImportOnlyInImportListWithNonEmptyPrefix,
191
    /// error E0432: unresolved import
192
    UnresolvedImport(Option<(&'a str, &'a str)>),
193
    /// error E0433: failed to resolve
194
    FailedToResolve(&'a str),
195
    /// error E0434: can't capture dynamic environment in a fn item
196
    CannotCaptureDynamicEnvironmentInFnItem,
197
    /// error E0435: attempt to use a non-constant value in a constant
198
    AttemptToUseNonConstantValueInConstant,
199 200
}

201
/// Context of where `ResolutionError::UnresolvedName` arose.
202
#[derive(Clone, PartialEq, Eq, Debug)]
J
Jeffrey Seyfried 已提交
203
enum UnresolvedNameContext {
204 205 206 207
    /// `PathIsMod(id)` indicates that a given path, used in
    /// expression context, actually resolved to a module rather than
    /// a value. The `id` attached to the variant is the node id of
    /// the erroneous path expression.
208
    PathIsMod(ast::NodeId),
209 210 211 212

    /// `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.)
213 214 215
    Other,
}

C
corentih 已提交
216 217 218
fn resolve_error<'b, 'a: 'b, 'tcx: 'a>(resolver: &'b Resolver<'a, 'tcx>,
                                       span: syntax::codemap::Span,
                                       resolution_error: ResolutionError<'b>) {
N
Nick Cameron 已提交
219
    resolve_struct_error(resolver, span, resolution_error).emit();
N
Nick Cameron 已提交
220 221 222 223 224
}

fn resolve_struct_error<'b, 'a: 'b, 'tcx: 'a>(resolver: &'b Resolver<'a, 'tcx>,
                                              span: syntax::codemap::Span,
                                              resolution_error: ResolutionError<'b>)
N
Nick Cameron 已提交
225
                                              -> DiagnosticBuilder<'a> {
226
    if !resolver.emit_errors {
N
Nick Cameron 已提交
227
        return resolver.session.diagnostic().struct_dummy();
228
    }
N
Nick Cameron 已提交
229

N
Nick Cameron 已提交
230
    match resolution_error {
231
        ResolutionError::TypeParametersFromOuterFunction => {
N
Nick Cameron 已提交
232 233 234 235 236
            struct_span_err!(resolver.session,
                             span,
                             E0401,
                             "can't use type parameters from outer function; try using a local \
                              type parameter instead")
C
corentih 已提交
237
        }
238
        ResolutionError::OuterTypeParameterContext => {
N
Nick Cameron 已提交
239 240 241 242
            struct_span_err!(resolver.session,
                             span,
                             E0402,
                             "cannot use an outer type parameter in this context")
C
corentih 已提交
243
        }
244
        ResolutionError::NameAlreadyUsedInTypeParameterList(name) => {
N
Nick Cameron 已提交
245 246 247 248 249 250
            struct_span_err!(resolver.session,
                             span,
                             E0403,
                             "the name `{}` is already used for a type parameter in this type \
                              parameter list",
                             name)
C
corentih 已提交
251
        }
252
        ResolutionError::IsNotATrait(name) => {
N
Nick Cameron 已提交
253
            struct_span_err!(resolver.session, span, E0404, "`{}` is not a trait", name)
C
corentih 已提交
254
        }
255 256 257 258 259 260 261 262
        ResolutionError::UndeclaredTraitName(name, candidates) => {
            let mut err = struct_span_err!(resolver.session,
                                           span,
                                           E0405,
                                           "trait `{}` is not in scope",
                                           name);
            show_candidates(&mut err, span, &candidates);
            err
C
corentih 已提交
263
        }
264
        ResolutionError::UndeclaredAssociatedType => {
N
Nick Cameron 已提交
265
            struct_span_err!(resolver.session, span, E0406, "undeclared associated type")
C
corentih 已提交
266
        }
267
        ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
N
Nick Cameron 已提交
268 269 270 271 272 273
            struct_span_err!(resolver.session,
                             span,
                             E0407,
                             "method `{}` is not a member of trait `{}`",
                             method,
                             trait_)
C
corentih 已提交
274
        }
275
        ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
N
Nick Cameron 已提交
276 277 278 279 280 281
            struct_span_err!(resolver.session,
                             span,
                             E0437,
                             "type `{}` is not a member of trait `{}`",
                             type_,
                             trait_)
C
corentih 已提交
282
        }
283
        ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
N
Nick Cameron 已提交
284 285 286 287 288 289
            struct_span_err!(resolver.session,
                             span,
                             E0438,
                             "const `{}` is not a member of trait `{}`",
                             const_,
                             trait_)
C
corentih 已提交
290
        }
291
        ResolutionError::VariableNotBoundInPattern(variable_name, pattern_number) => {
N
Nick Cameron 已提交
292 293 294 295 296 297
            struct_span_err!(resolver.session,
                             span,
                             E0408,
                             "variable `{}` from pattern #1 is not bound in pattern #{}",
                             variable_name,
                             pattern_number)
C
corentih 已提交
298
        }
299
        ResolutionError::VariableBoundWithDifferentMode(variable_name, pattern_number) => {
N
Nick Cameron 已提交
300 301 302 303 304 305 306
            struct_span_err!(resolver.session,
                             span,
                             E0409,
                             "variable `{}` is bound with different mode in pattern #{} than in \
                              pattern #1",
                             variable_name,
                             pattern_number)
C
corentih 已提交
307
        }
308
        ResolutionError::VariableNotBoundInParentPattern(variable_name, pattern_number) => {
N
Nick Cameron 已提交
309 310 311 312 313 314
            struct_span_err!(resolver.session,
                             span,
                             E0410,
                             "variable `{}` from pattern #{} is not bound in pattern #1",
                             variable_name,
                             pattern_number)
C
corentih 已提交
315
        }
316
        ResolutionError::SelfUsedOutsideImplOrTrait => {
N
Nick Cameron 已提交
317 318 319 320
            struct_span_err!(resolver.session,
                             span,
                             E0411,
                             "use of `Self` outside of an impl or trait")
C
corentih 已提交
321
        }
322 323 324 325 326 327 328 329 330
        ResolutionError::UseOfUndeclared(kind, name, candidates) => {
            let mut err = struct_span_err!(resolver.session,
                                           span,
                                           E0412,
                                           "{} `{}` is undefined or not in scope",
                                           kind,
                                           name);
            show_candidates(&mut err, span, &candidates);
            err
C
corentih 已提交
331
        }
332
        ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(name) => {
N
Nick Cameron 已提交
333 334 335 336 337 338
            struct_span_err!(resolver.session,
                             span,
                             E0413,
                             "declaration of `{}` shadows an enum variant \
                              or unit-like struct in scope",
                             name)
C
corentih 已提交
339
        }
340
        ResolutionError::OnlyIrrefutablePatternsAllowedHere(did, name) => {
N
Nick Cameron 已提交
341 342 343 344 345 346 347
            let mut err = struct_span_err!(resolver.session,
                                           span,
                                           E0414,
                                           "only irrefutable patterns allowed here");
            err.span_note(span,
                          "there already is a constant in scope sharing the same \
                           name as this pattern");
348
            if let Some(sp) = resolver.ast_map.span_if_local(did) {
N
Nick Cameron 已提交
349
                err.span_note(sp, "constant defined here");
350
            }
351 352
            if let Some(binding) = resolver.current_module
                                           .resolve_name_in_lexical_scope(name, ValueNS) {
353
                if binding.is_import() {
354 355
                    err.span_note(binding.span.unwrap(), "constant imported here");
                }
356
            }
N
Nick Cameron 已提交
357
            err
C
corentih 已提交
358
        }
359
        ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
N
Nick Cameron 已提交
360 361 362 363 364
            struct_span_err!(resolver.session,
                             span,
                             E0415,
                             "identifier `{}` is bound more than once in this parameter list",
                             identifier)
C
corentih 已提交
365
        }
366
        ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
N
Nick Cameron 已提交
367 368 369 370 371
            struct_span_err!(resolver.session,
                             span,
                             E0416,
                             "identifier `{}` is bound more than once in the same pattern",
                             identifier)
C
corentih 已提交
372
        }
373
        ResolutionError::StaticVariableReference => {
N
Nick Cameron 已提交
374 375 376 377 378
            struct_span_err!(resolver.session,
                             span,
                             E0417,
                             "static variables cannot be referenced in a pattern, use a \
                              `const` instead")
C
corentih 已提交
379
        }
380
        ResolutionError::NotAnEnumVariantStructOrConst(name) => {
N
Nick Cameron 已提交
381 382 383 384 385
            struct_span_err!(resolver.session,
                             span,
                             E0418,
                             "`{}` is not an enum variant, struct or const",
                             name)
C
corentih 已提交
386
        }
387
        ResolutionError::UnresolvedEnumVariantStructOrConst(name) => {
N
Nick Cameron 已提交
388 389 390 391 392
            struct_span_err!(resolver.session,
                             span,
                             E0419,
                             "unresolved enum variant, struct or const `{}`",
                             name)
C
corentih 已提交
393
        }
394
        ResolutionError::NotAnAssociatedConst(name) => {
N
Nick Cameron 已提交
395 396 397 398 399
            struct_span_err!(resolver.session,
                             span,
                             E0420,
                             "`{}` is not an associated const",
                             name)
C
corentih 已提交
400
        }
401
        ResolutionError::UnresolvedAssociatedConst(name) => {
N
Nick Cameron 已提交
402 403 404 405 406
            struct_span_err!(resolver.session,
                             span,
                             E0421,
                             "unresolved associated const `{}`",
                             name)
C
corentih 已提交
407
        }
408
        ResolutionError::DoesNotNameAStruct(name) => {
N
Nick Cameron 已提交
409 410 411 412 413
            struct_span_err!(resolver.session,
                             span,
                             E0422,
                             "`{}` does not name a structure",
                             name)
C
corentih 已提交
414
        }
415
        ResolutionError::StructVariantUsedAsFunction(path_name) => {
N
Nick Cameron 已提交
416 417 418 419 420 421
            struct_span_err!(resolver.session,
                             span,
                             E0423,
                             "`{}` is the name of a struct or struct variant, but this expression \
                             uses it like a function name",
                             path_name)
C
corentih 已提交
422
        }
423
        ResolutionError::SelfNotAvailableInStaticMethod => {
N
Nick Cameron 已提交
424 425 426 427 428
            struct_span_err!(resolver.session,
                             span,
                             E0424,
                             "`self` is not available in a static method. Maybe a `self` \
                             argument is missing?")
C
corentih 已提交
429
        }
430
        ResolutionError::UnresolvedName(path, msg, context) => {
N
Nick Cameron 已提交
431 432 433 434 435 436
            let mut err = struct_span_err!(resolver.session,
                                           span,
                                           E0425,
                                           "unresolved name `{}`{}",
                                           path,
                                           msg);
437 438

            match context {
439
                UnresolvedNameContext::Other => { } // no help available
440 441 442 443 444 445 446 447 448
                UnresolvedNameContext::PathIsMod(id) => {
                    let mut help_msg = String::new();
                    let parent_id = resolver.ast_map.get_parent_node(id);
                    if let Some(hir_map::Node::NodeExpr(e)) = resolver.ast_map.find(parent_id) {
                        match e.node {
                            ExprField(_, ident) => {
                                help_msg = format!("To reference an item from the \
                                                    `{module}` module, use \
                                                    `{module}::{ident}`",
J
Jonas Schievink 已提交
449
                                                   module = path,
450 451 452 453 454 455
                                                   ident = ident.node);
                            }
                            ExprMethodCall(ident, _, _) => {
                                help_msg = format!("To call a function from the \
                                                    `{module}` module, use \
                                                    `{module}::{ident}(..)`",
J
Jonas Schievink 已提交
456
                                                   module = path,
457 458
                                                   ident = ident.node);
                            }
459 460
                            ExprCall(_, _) => {
                                help_msg = format!("No function corresponds to `{module}(..)`",
J
Jonas Schievink 已提交
461
                                                   module = path);
462 463
                            }
                            _ => { } // no help available
464
                        }
465 466
                    } else {
                        help_msg = format!("Module `{module}` cannot be the value of an expression",
J
Jonas Schievink 已提交
467
                                           module = path);
468 469 470
                    }

                    if !help_msg.is_empty() {
N
Nick Cameron 已提交
471
                        err.fileline_help(span, &help_msg);
472 473 474
                    }
                }
            }
N
Nick Cameron 已提交
475
            err
C
corentih 已提交
476
        }
477
        ResolutionError::UndeclaredLabel(name) => {
N
Nick Cameron 已提交
478 479 480 481 482
            struct_span_err!(resolver.session,
                             span,
                             E0426,
                             "use of undeclared label `{}`",
                             name)
C
corentih 已提交
483
        }
484
        ResolutionError::CannotUseRefBindingModeWith(descr) => {
N
Nick Cameron 已提交
485 486 487 488 489
            struct_span_err!(resolver.session,
                             span,
                             E0427,
                             "cannot use `ref` binding mode with {}",
                             descr)
C
corentih 已提交
490
        }
491
        ResolutionError::SelfImportsOnlyAllowedWithin => {
N
Nick Cameron 已提交
492 493 494 495 496
            struct_span_err!(resolver.session,
                             span,
                             E0429,
                             "{}",
                             "`self` imports are only allowed within a { } list")
C
corentih 已提交
497
        }
498
        ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
N
Nick Cameron 已提交
499 500 501 502
            struct_span_err!(resolver.session,
                             span,
                             E0430,
                             "`self` import can only appear once in the list")
C
corentih 已提交
503
        }
504
        ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
N
Nick Cameron 已提交
505 506 507 508 509
            struct_span_err!(resolver.session,
                             span,
                             E0431,
                             "`self` import can only appear in an import list with a \
                              non-empty prefix")
510
        }
511
        ResolutionError::UnresolvedImport(name) => {
512
            let msg = match name {
513
                Some((n, p)) => format!("unresolved import `{}`{}", n, p),
C
corentih 已提交
514
                None => "unresolved import".to_owned(),
515
            };
N
Nick Cameron 已提交
516
            struct_span_err!(resolver.session, span, E0432, "{}", msg)
C
corentih 已提交
517
        }
518
        ResolutionError::FailedToResolve(msg) => {
N
Nick Cameron 已提交
519
            struct_span_err!(resolver.session, span, E0433, "failed to resolve. {}", msg)
C
corentih 已提交
520
        }
521
        ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
N
Nick Cameron 已提交
522 523 524 525 526 527
            struct_span_err!(resolver.session,
                             span,
                             E0434,
                             "{}",
                             "can't capture dynamic environment in a fn item; use the || { ... } \
                              closure form instead")
C
corentih 已提交
528 529
        }
        ResolutionError::AttemptToUseNonConstantValueInConstant => {
N
Nick Cameron 已提交
530 531 532 533
            struct_span_err!(resolver.session,
                             span,
                             E0435,
                             "attempt to use a non-constant value in a constant")
C
corentih 已提交
534
        }
N
Nick Cameron 已提交
535
    }
536 537
}

N
Niko Matsakis 已提交
538
#[derive(Copy, Clone)]
539
struct BindingInfo {
540
    span: Span,
541
    binding_mode: BindingMode,
542 543 544
}

// Map from the name in a pattern to its binding mode.
545
type BindingMap = HashMap<Name, BindingInfo>;
546

N
Niko Matsakis 已提交
547
#[derive(Copy, Clone, PartialEq)]
F
Felix S. Klock II 已提交
548
enum PatternBindingMode {
549
    RefutableMode,
550
    LocalIrrefutableMode,
551
    ArgumentIrrefutableMode,
552 553
}

N
Niko Matsakis 已提交
554
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
G
Garming Sam 已提交
555
pub enum Namespace {
556
    TypeNS,
C
corentih 已提交
557
    ValueNS,
558 559
}

560
impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
561 562 563
    fn visit_nested_item(&mut self, item: hir::ItemId) {
        self.visit_item(self.ast_map.expect_item(item.id))
    }
564
    fn visit_item(&mut self, item: &Item) {
565
        execute_callback!(hir_map::Node::NodeItem(item), self);
A
Alex Crichton 已提交
566
        self.resolve_item(item);
567
    }
568
    fn visit_arm(&mut self, arm: &Arm) {
A
Alex Crichton 已提交
569
        self.resolve_arm(arm);
570
    }
571
    fn visit_block(&mut self, block: &Block) {
572
        execute_callback!(hir_map::Node::NodeBlock(block), self);
A
Alex Crichton 已提交
573
        self.resolve_block(block);
574
    }
575
    fn visit_expr(&mut self, expr: &Expr) {
576
        execute_callback!(hir_map::Node::NodeExpr(expr), self);
A
Alex Crichton 已提交
577
        self.resolve_expr(expr);
578
    }
579
    fn visit_local(&mut self, local: &Local) {
J
Jonas Schievink 已提交
580
        execute_callback!(hir_map::Node::NodeLocal(&local.pat), self);
A
Alex Crichton 已提交
581
        self.resolve_local(local);
582
    }
583
    fn visit_ty(&mut self, ty: &Ty) {
A
Alex Crichton 已提交
584
        self.resolve_type(ty);
585
    }
586 587 588
    fn visit_generics(&mut self, generics: &Generics) {
        self.resolve_generics(generics);
    }
C
corentih 已提交
589
    fn visit_poly_trait_ref(&mut self, tref: &hir::PolyTraitRef, m: &hir::TraitBoundModifier) {
590 591
        match self.resolve_trait_reference(tref.trait_ref.ref_id, &tref.trait_ref.path, 0) {
            Ok(def) => self.record_def(tref.trait_ref.ref_id, def),
C
corentih 已提交
592 593
            Err(_) => {
                // error already reported
594
                self.record_def(tref.trait_ref.ref_id, err_path_resolution())
C
corentih 已提交
595
            }
596
        }
597
        intravisit::walk_poly_trait_ref(self, tref, m);
598
    }
C
corentih 已提交
599 600 601 602
    fn visit_variant(&mut self,
                     variant: &hir::Variant,
                     generics: &Generics,
                     item_id: ast::NodeId) {
603
        execute_callback!(hir_map::Node::NodeVariant(variant), self);
604 605 606
        if let Some(ref dis_expr) = variant.node.disr_expr {
            // resolve the discriminator expr as a constant
            self.with_constant_rib(|this| {
607
                this.visit_expr(dis_expr);
608 609 610
            });
        }

611
        // `intravisit::walk_variant` without the discriminant expression.
C
corentih 已提交
612 613 614 615 616
        self.visit_variant_data(&variant.node.data,
                                variant.node.name,
                                generics,
                                item_id,
                                variant.span);
617
    }
618 619
    fn visit_foreign_item(&mut self, foreign_item: &hir::ForeignItem) {
        execute_callback!(hir_map::Node::NodeForeignItem(foreign_item), self);
620 621 622 623
        let type_parameters = match foreign_item.node {
            ForeignItemFn(_, ref generics) => {
                HasTypeParameters(generics, FnSpace, ItemRibKind)
            }
C
corentih 已提交
624
            ForeignItemStatic(..) => NoTypeParameters,
625 626
        };
        self.with_type_parameter_rib(type_parameters, |this| {
627
            intravisit::walk_foreign_item(this, foreign_item);
628 629 630
        });
    }
    fn visit_fn(&mut self,
631
                function_kind: FnKind<'v>,
632 633 634 635 636
                declaration: &'v FnDecl,
                block: &'v Block,
                _: Span,
                node_id: NodeId) {
        let rib_kind = match function_kind {
637
            FnKind::ItemFn(_, generics, _, _, _, _, _) => {
638 639 640
                self.visit_generics(generics);
                ItemRibKind
            }
641
            FnKind::Method(_, sig, _, _) => {
642 643
                self.visit_generics(&sig.generics);
                self.visit_explicit_self(&sig.explicit_self);
644 645
                MethodRibKind
            }
646
            FnKind::Closure(_) => ClosureRibKind(node_id),
647 648 649
        };
        self.resolve_function(rib_kind, declaration, block);
    }
650
}
651

652
pub type ErrorMessage = Option<(Span, String)>;
653

654
#[derive(Clone, PartialEq, Eq)]
655
pub enum ResolveResult<T> {
C
corentih 已提交
656 657 658
    Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
    Indeterminate, // Couldn't determine due to unresolved globs.
    Success(T), // Successfully resolved the import.
659 660
}

661
impl<T> ResolveResult<T> {
662 663 664 665 666
    fn and_then<U, F: FnOnce(T) -> ResolveResult<U>>(self, f: F) -> ResolveResult<U> {
        match self {
            Failed(msg) => Failed(msg),
            Indeterminate => Indeterminate,
            Success(t) => f(t),
C
corentih 已提交
667
        }
668
    }
669 670 671 672 673 674 675

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

678 679 680 681
enum FallbackSuggestion {
    NoSuggestion,
    Field,
    Method,
682
    TraitItem,
683
    StaticMethod(String),
684
    TraitMethod(String),
685 686
}

N
Niko Matsakis 已提交
687
#[derive(Copy, Clone)]
688
enum TypeParameters<'tcx, 'a> {
689
    NoTypeParameters,
C
corentih 已提交
690 691
    HasTypeParameters(// Type parameters.
                      &'a Generics,
692

C
corentih 已提交
693 694 695
                      // Identifies the things that these parameters
                      // were declared on (type, fn, etc)
                      ParamSpace,
696

C
corentih 已提交
697
                      // The kind of the rib used for type parameters.
698
                      RibKind<'tcx>),
699 700
}

701
// The rib kind controls the translation of local
702
// definitions (`Def::Local`) to upvars (`Def::Upvar`).
N
Niko Matsakis 已提交
703
#[derive(Copy, Clone, Debug)]
704
enum RibKind<'a> {
705 706
    // No translation needs to be applied.
    NormalRibKind,
707

708 709
    // We passed through a closure scope at the given node ID.
    // Translate upvars as appropriate.
710
    ClosureRibKind(NodeId /* func id */),
711

712
    // We passed through an impl or trait and are now in one of its
713
    // methods. Allow references to ty params that impl or trait
714 715
    // binds. Disallow any other upvars (including other ty params that are
    // upvars).
716
    MethodRibKind,
717

718 719
    // We passed through an item scope. Disallow upvars.
    ItemRibKind,
720 721

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

724 725
    // We passed through a module.
    ModuleRibKind(Module<'a>),
726 727
}

N
Niko Matsakis 已提交
728
#[derive(Copy, Clone)]
F
Felix S. Klock II 已提交
729
enum UseLexicalScopeFlag {
730
    DontUseLexicalScope,
C
corentih 已提交
731
    UseLexicalScope,
732 733
}

734
enum ModulePrefixResult<'a> {
735
    NoPrefixFound,
736
    PrefixFound(Module<'a>, usize),
737 738
}

739 740 741 742 743 744 745 746 747
#[derive(Copy, Clone)]
enum AssocItemResolveResult {
    /// Syntax such as `<T>::item`, which can't be resolved until type
    /// checking.
    TypecheckRequired,
    /// We should have been able to resolve the associated item.
    ResolveAttempt(Option<PathResolution>),
}

N
Niko Matsakis 已提交
748
#[derive(Copy, Clone)]
F
Felix S. Klock II 已提交
749
enum BareIdentifierPatternResolution {
J
Jeffrey Seyfried 已提交
750 751
    FoundStructOrEnumVariant(Def),
    FoundConst(Def, Name),
C
corentih 已提交
752
    BareIdentifierPatternUnresolved,
753 754
}

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

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

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

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

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

791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
impl<'a> LexicalScopeBinding<'a> {
    fn local_def(self) -> LocalDef {
        match self {
            LexicalScopeBinding::LocalDef(local_def) => local_def,
            LexicalScopeBinding::Item(binding) => LocalDef::from_def(binding.def().unwrap()),
        }
    }

    fn def(self) -> Def {
        self.local_def().def
    }

    fn module(self) -> Option<Module<'a>> {
        match self {
            LexicalScopeBinding::Item(binding) => binding.module(),
            _ => None,
        }
    }
}

811
/// The link from a module up to its nearest parent node.
J
Jorge Aparicio 已提交
812
#[derive(Clone,Debug)]
813
enum ParentLink<'a> {
814
    NoParentLink,
815 816
    ModuleParentLink(Module<'a>, Name),
    BlockParentLink(Module<'a>, NodeId),
817 818
}

819
/// One node in the tree of modules.
820 821
pub struct ModuleS<'a> {
    parent_link: ParentLink<'a>,
J
Jeffrey Seyfried 已提交
822
    def: Option<Def>,
823
    is_public: bool,
824

825 826 827
    // If the module is an extern crate, `def` is root of the external crate and `extern_crate_id`
    // is the NodeId of the local `extern crate` item (otherwise, `extern_crate_id` is None).
    extern_crate_id: Option<NodeId>,
828

829
    resolutions: RefCell<HashMap<(Name, Namespace), &'a RefCell<NameResolution<'a>>>>,
830
    unresolved_imports: RefCell<Vec<&'a ImportDirective<'a>>>,
831

832 833 834
    // The module children of this node, including normal modules and anonymous modules.
    // Anonymous children are pseudo-modules that are implicitly created around items
    // contained within blocks.
835 836 837 838 839 840 841 842 843 844 845
    //
    // 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`.
846
    module_children: RefCell<NodeMap<Module<'a>>>,
847

848
    prelude: RefCell<Option<Module<'a>>>,
849

850
    glob_importers: RefCell<Vec<(Module<'a>, &'a ImportDirective<'a>)>>,
851
    globs: RefCell<Vec<&'a ImportDirective<'a>>>,
852

853 854 855
    // Whether this module is populated. If not populated, any attempt to
    // access the children must be preceded with a
    // `populate_module_if_necessary` call.
856
    populated: Cell<bool>,
857 858

    arenas: &'a ResolverArenas<'a>,
859 860
}

861 862 863
pub type Module<'a> = &'a ModuleS<'a>;

impl<'a> ModuleS<'a> {
864 865 866 867 868
    fn new(parent_link: ParentLink<'a>,
           def: Option<Def>,
           external: bool,
           is_public: bool,
           arenas: &'a ResolverArenas<'a>) -> Self {
869
        ModuleS {
870
            parent_link: parent_link,
J
Jeffrey Seyfried 已提交
871
            def: def,
872
            is_public: is_public,
873
            extern_crate_id: None,
874
            resolutions: RefCell::new(HashMap::new()),
875
            unresolved_imports: RefCell::new(Vec::new()),
876
            module_children: RefCell::new(NodeMap()),
877
            prelude: RefCell::new(None),
878
            glob_importers: RefCell::new(Vec::new()),
879
            globs: RefCell::new((Vec::new())),
880
            populated: Cell::new(!external),
881
            arenas: arenas
882
        }
B
Brian Anderson 已提交
883 884
    }

885
    fn for_each_child<F: FnMut(Name, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
886
        for (&(name, ns), name_resolution) in self.resolutions.borrow().iter() {
887
            name_resolution.borrow().binding.map(|binding| f(name, ns, binding));
888 889 890
        }
    }

891
    fn def_id(&self) -> Option<DefId> {
J
Jeffrey Seyfried 已提交
892
        self.def.as_ref().map(Def::def_id)
893 894 895
    }

    fn is_normal(&self) -> bool {
J
Jeffrey Seyfried 已提交
896
        match self.def {
897
            Some(Def::Mod(_)) | Some(Def::ForeignMod(_)) => true,
898 899 900 901 902
            _ => false,
        }
    }

    fn is_trait(&self) -> bool {
J
Jeffrey Seyfried 已提交
903
        match self.def {
904
            Some(Def::Trait(_)) => true,
905
            _ => false,
906
        }
B
Brian Anderson 已提交
907 908
    }

909 910 911 912 913 914 915 916
    fn is_ancestor_of(&self, module: Module<'a>) -> bool {
        if self.def_id() == module.def_id() { return true }
        match module.parent_link {
            ParentLink::BlockParentLink(parent, _) |
            ParentLink::ModuleParentLink(parent, _) => self.is_ancestor_of(parent),
            _ => false,
        }
    }
V
Victor Berger 已提交
917 918
}

919
impl<'a> fmt::Debug for ModuleS<'a> {
920
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
C
corentih 已提交
921
        write!(f,
922 923
               "{:?}, {}",
               self.def,
C
corentih 已提交
924 925 926 927 928
               if self.is_public {
                   "public"
               } else {
                   "private"
               })
929 930 931
    }
}

932
bitflags! {
J
Jorge Aparicio 已提交
933
    #[derive(Debug)]
934
    flags DefModifiers: u8 {
V
Vadim Petrochenkov 已提交
935 936
        // Enum variants are always considered `PUBLIC`, this is needed for `use Enum::Variant`
        // or `use Enum::*` to work on private enums.
T
Fallout  
Tamir Duberstein 已提交
937 938
        const PUBLIC     = 1 << 0,
        const IMPORTABLE = 1 << 1,
V
Vadim Petrochenkov 已提交
939
        // Variants are considered `PUBLIC`, but some of them live in private enums.
940 941
        // We need to track them to prohibit reexports like `pub use PrivEnum::Variant`.
        const PRIVATE_VARIANT = 1 << 2,
942
        const GLOB_IMPORTED = 1 << 3,
943 944 945
    }
}

946
// Records a possibly-private value, type, or module definition.
947
#[derive(Clone, Debug)]
948
pub struct NameBinding<'a> {
949 950
    modifiers: DefModifiers,
    kind: NameBindingKind<'a>,
951
    span: Option<Span>,
952 953
}

954
#[derive(Clone, Debug)]
955
enum NameBindingKind<'a> {
956
    Def(Def),
957
    Module(Module<'a>),
958 959 960
    Import {
        binding: &'a NameBinding<'a>,
        id: NodeId,
961 962
        // Some(error) if using this imported name causes the import to be a privacy error
        privacy_error: Option<Box<PrivacyError<'a>>>,
963
    },
964 965
}

966 967 968
#[derive(Clone, Debug)]
struct PrivacyError<'a>(Span, Name, &'a NameBinding<'a>);

969
impl<'a> NameBinding<'a> {
970
    fn create_from_module(module: Module<'a>, span: Option<Span>) -> Self {
971
        let modifiers = if module.is_public {
T
Fallout  
Tamir Duberstein 已提交
972 973 974 975
            DefModifiers::PUBLIC
        } else {
            DefModifiers::empty()
        } | DefModifiers::IMPORTABLE;
976

977
        NameBinding { modifiers: modifiers, kind: NameBindingKind::Module(module), span: span }
978 979
    }

980
    fn module(&self) -> Option<Module<'a>> {
981 982 983 984
        match self.kind {
            NameBindingKind::Module(module) => Some(module),
            NameBindingKind::Def(_) => None,
            NameBindingKind::Import { binding, .. } => binding.module(),
985 986 987
        }
    }

988
    fn def(&self) -> Option<Def> {
989 990 991 992
        match self.kind {
            NameBindingKind::Def(def) => Some(def),
            NameBindingKind::Module(module) => module.def,
            NameBindingKind::Import { binding, .. } => binding.def(),
993
        }
994
    }
995

996
    fn defined_with(&self, modifiers: DefModifiers) -> bool {
997
        self.modifiers.contains(modifiers)
998 999 1000 1001 1002 1003
    }

    fn is_public(&self) -> bool {
        self.defined_with(DefModifiers::PUBLIC)
    }

1004
    fn is_extern_crate(&self) -> bool {
1005
        self.module().and_then(|module| module.extern_crate_id).is_some()
1006
    }
1007 1008 1009 1010 1011 1012 1013

    fn is_import(&self) -> bool {
        match self.kind {
            NameBindingKind::Import { .. } => true,
            _ => false,
        }
    }
1014 1015
}

1016
/// Interns the names of the primitive types.
F
Felix S. Klock II 已提交
1017
struct PrimitiveTypeTable {
1018
    primitive_types: HashMap<Name, PrimTy>,
1019
}
1020

1021
impl PrimitiveTypeTable {
K
Kevin Butler 已提交
1022
    fn new() -> PrimitiveTypeTable {
C
corentih 已提交
1023 1024 1025 1026
        let mut table = PrimitiveTypeTable { primitive_types: HashMap::new() };

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

        table
    }

1044
    fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1045
        self.primitive_types.insert(token::intern(string), primitive_type);
1046 1047 1048
    }
}

1049
/// The main resolver class.
C
corentih 已提交
1050
pub struct Resolver<'a, 'tcx: 'a> {
E
Eduard Burtescu 已提交
1051
    session: &'a Session,
1052

1053
    ast_map: &'a hir_map::Map<'tcx>,
1054

1055
    graph_root: Module<'a>,
1056

1057
    trait_item_map: FnvHashMap<(Name, DefId), DefId>,
1058

1059
    structs: FnvHashMap<DefId, Vec<Name>>,
1060

1061
    // The number of imports that are currently unresolved.
1062
    unresolved_imports: usize,
1063 1064

    // The module that represents the current item scope.
1065
    current_module: Module<'a>,
1066 1067

    // The current set of local scopes, for values.
1068
    // FIXME #4948: Reuse ribs to avoid allocation.
1069
    value_ribs: Vec<Rib<'a>>,
1070 1071

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

1074
    // The current set of local scopes, for labels.
1075
    label_ribs: Vec<Rib<'a>>,
1076

1077
    // The trait that the current context can refer to.
1078 1079 1080 1081
    current_trait_ref: Option<(DefId, TraitRef)>,

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

1083
    // The idents for the primitive types.
E
Eduard Burtescu 已提交
1084
    primitive_type_table: PrimitiveTypeTable,
1085

J
Jonathan S 已提交
1086
    def_map: RefCell<DefMap>,
1087 1088
    freevars: FreevarMap,
    freevars_seen: NodeMap<NodeMap<usize>>,
1089
    export_map: ExportMap,
1090
    trait_map: TraitMap,
1091

1092 1093 1094 1095 1096
    // Whether or not to print error messages. Can be set to true
    // when getting additional info for error message suggestions,
    // so as to avoid printing duplicate errors
    emit_errors: bool,

1097 1098 1099 1100 1101
    make_glob_map: bool,
    // Maps imports to the names of items actually imported (this actually maps
    // all imports, but only glob imports are actually interesting).
    glob_map: GlobMap,

1102
    used_imports: HashSet<(NodeId, Namespace)>,
1103
    used_crates: HashSet<CrateNum>,
G
Garming Sam 已提交
1104 1105

    // Callback function for intercepting walks
1106
    callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>,
G
Garming Sam 已提交
1107 1108 1109
    // The intention is that the callback modifies this flag.
    // Once set, the resolver falls out of the walk, preserving the ribs.
    resolved: bool,
1110
    privacy_errors: Vec<PrivacyError<'a>>,
1111 1112 1113 1114

    arenas: &'a ResolverArenas<'a>,
}

J
Jeffrey Seyfried 已提交
1115
struct ResolverArenas<'a> {
1116
    modules: arena::TypedArena<ModuleS<'a>>,
1117
    name_bindings: arena::TypedArena<NameBinding<'a>>,
1118
    import_directives: arena::TypedArena<ImportDirective<'a>>,
1119
    name_resolutions: arena::TypedArena<RefCell<NameResolution<'a>>>,
1120 1121 1122
}

impl<'a> ResolverArenas<'a> {
1123 1124 1125 1126 1127 1128
    fn alloc_module(&'a self, module: ModuleS<'a>) -> Module<'a> {
        self.modules.alloc(module)
    }
    fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
        self.name_bindings.alloc(name_binding)
    }
1129 1130
    fn alloc_import_directive(&'a self, import_directive: ImportDirective<'a>)
                              -> &'a ImportDirective {
1131 1132
        self.import_directives.alloc(import_directive)
    }
1133 1134 1135
    fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
        self.name_resolutions.alloc(Default::default())
    }
1136 1137
}

1138
#[derive(PartialEq)]
S
Steven Fackler 已提交
1139 1140
enum FallbackChecks {
    Everything,
C
corentih 已提交
1141
    OnlyTraitAndStatics,
S
Steven Fackler 已提交
1142 1143
}

1144 1145
impl<'a, 'tcx> Resolver<'a, 'tcx> {
    fn new(session: &'a Session,
1146
           ast_map: &'a hir_map::Map<'tcx>,
1147 1148
           make_glob_map: MakeGlobMap,
           arenas: &'a ResolverArenas<'a>)
C
corentih 已提交
1149
           -> Resolver<'a, 'tcx> {
1150
        let root_def_id = ast_map.local_def_id(CRATE_NODE_ID);
1151 1152 1153
        let graph_root =
            ModuleS::new(NoParentLink, Some(Def::Mod(root_def_id)), false, true, arenas);
        let graph_root = arenas.alloc_module(graph_root);
K
Kevin Butler 已提交
1154 1155 1156 1157

        Resolver {
            session: session,

1158 1159
            ast_map: ast_map,

K
Kevin Butler 已提交
1160 1161
            // The outermost module has def ID 0; this is not reflected in the
            // AST.
1162
            graph_root: graph_root,
K
Kevin Butler 已提交
1163

1164 1165
            trait_item_map: FnvHashMap(),
            structs: FnvHashMap(),
K
Kevin Butler 已提交
1166 1167 1168

            unresolved_imports: 0,

1169
            current_module: graph_root,
1170 1171
            value_ribs: vec![Rib::new(ModuleRibKind(graph_root))],
            type_ribs: vec![Rib::new(ModuleRibKind(graph_root))],
1172
            label_ribs: Vec::new(),
K
Kevin Butler 已提交
1173 1174 1175 1176 1177 1178

            current_trait_ref: None,
            current_self_type: None,

            primitive_type_table: PrimitiveTypeTable::new(),

1179
            def_map: RefCell::new(NodeMap()),
1180 1181
            freevars: NodeMap(),
            freevars_seen: NodeMap(),
1182 1183
            export_map: NodeMap(),
            trait_map: NodeMap(),
K
Kevin Butler 已提交
1184
            used_imports: HashSet::new(),
1185
            used_crates: HashSet::new(),
K
Kevin Butler 已提交
1186 1187

            emit_errors: true,
1188
            make_glob_map: make_glob_map == MakeGlobMap::Yes,
1189
            glob_map: NodeMap(),
G
Garming Sam 已提交
1190 1191 1192

            callback: None,
            resolved: false,
1193
            privacy_errors: Vec::new(),
1194 1195 1196 1197 1198 1199 1200 1201

            arenas: arenas,
        }
    }

    fn arenas() -> ResolverArenas<'a> {
        ResolverArenas {
            modules: arena::TypedArena::new(),
1202
            name_bindings: arena::TypedArena::new(),
1203
            import_directives: arena::TypedArena::new(),
1204
            name_resolutions: arena::TypedArena::new(),
K
Kevin Butler 已提交
1205 1206
        }
    }
1207

1208 1209 1210 1211 1212
    fn new_module(&self,
                  parent_link: ParentLink<'a>,
                  def: Option<Def>,
                  external: bool,
                  is_public: bool) -> Module<'a> {
1213
        self.arenas.alloc_module(ModuleS::new(parent_link, def, external, is_public, self.arenas))
1214 1215
    }

1216 1217 1218 1219
    fn new_extern_crate_module(&self,
                               parent_link: ParentLink<'a>,
                               def: Def,
                               is_public: bool,
1220
                               local_node_id: NodeId)
1221
                               -> Module<'a> {
1222
        let mut module = ModuleS::new(parent_link, Some(def), false, is_public, self.arenas);
1223
        module.extern_crate_id = Some(local_node_id);
1224 1225 1226
        self.arenas.modules.alloc(module)
    }

1227 1228 1229 1230
    fn get_ribs<'b>(&'b mut self, ns: Namespace) -> &'b mut Vec<Rib<'a>> {
        match ns { ValueNS => &mut self.value_ribs, TypeNS => &mut self.type_ribs }
    }

1231
    #[inline]
1232 1233 1234 1235 1236 1237
    fn record_use(&mut self, name: Name, ns: Namespace, binding: &'a NameBinding<'a>) {
        // track extern crates for unused_extern_crate lint
        if let Some(DefId { krate, .. }) = binding.module().and_then(ModuleS::def_id) {
            self.used_crates.insert(krate);
        }

1238 1239
        let (import_id, privacy_error) = match binding.kind {
            NameBindingKind::Import { id, ref privacy_error, .. } => (id, privacy_error),
1240 1241 1242
            _ => return,
        };

1243
        self.used_imports.insert((import_id, ns));
1244 1245 1246
        if let Some(error) = privacy_error.as_ref() {
            self.privacy_errors.push((**error).clone());
        }
1247

1248 1249 1250 1251
        if !self.make_glob_map {
            return;
        }
        if self.glob_map.contains_key(&import_id) {
1252
            self.glob_map.get_mut(&import_id).unwrap().insert(name);
1253 1254 1255
            return;
        }

1256
        let mut new_set = FnvHashSet();
1257 1258 1259 1260 1261
        new_set.insert(name);
        self.glob_map.insert(import_id, new_set);
    }

    fn get_trait_name(&self, did: DefId) -> Name {
1262 1263
        if let Some(node_id) = self.ast_map.as_local_node_id(did) {
            self.ast_map.expect_item(node_id).name
1264
        } else {
1265
            self.session.cstore.item_name(did)
1266 1267 1268
        }
    }

1269
    /// Resolves the given module path from the given root `module_`.
F
Felix S. Klock II 已提交
1270
    fn resolve_module_path_from_root(&mut self,
1271
                                     module_: Module<'a>,
1272
                                     module_path: &[Name],
1273
                                     index: usize,
J
Jeffrey Seyfried 已提交
1274 1275
                                     span: Span)
                                     -> ResolveResult<Module<'a>> {
1276
        fn search_parent_externals(needle: Name, module: Module) -> Option<Module> {
1277 1278
            match module.resolve_name(needle, TypeNS, false) {
                Success(binding) if binding.is_extern_crate() => Some(module),
1279
                _ => match module.parent_link {
1280
                    ModuleParentLink(ref parent, _) => {
1281
                        search_parent_externals(needle, parent)
1282
                    }
C
corentih 已提交
1283 1284
                    _ => None,
                },
1285
            }
1286 1287
        }

1288
        let mut search_module = module_;
1289
        let mut index = index;
A
Alex Crichton 已提交
1290
        let module_path_len = module_path.len();
1291 1292 1293 1294 1295

        // Resolve the module part of the path. This does not involve looking
        // upward though scope chains; we simply resolve names directly in
        // modules as we go.
        while index < module_path_len {
A
Alex Crichton 已提交
1296
            let name = module_path[index];
1297
            match self.resolve_name_in_module(search_module, name, TypeNS, false, true) {
1298
                Failed(None) => {
1299
                    let segment_name = name.as_str();
1300
                    let module_name = module_to_string(search_module);
1301
                    let mut span = span;
1302
                    let msg = if "???" == &module_name {
1303
                        span.hi = span.lo + Pos::from_usize(segment_name.len());
1304

C
corentih 已提交
1305
                        match search_parent_externals(name, &self.current_module) {
1306
                            Some(module) => {
1307
                                let path_str = names_to_string(module_path);
J
Jonas Schievink 已提交
1308 1309
                                let target_mod_str = module_to_string(&module);
                                let current_mod_str = module_to_string(&self.current_module);
1310 1311 1312 1313 1314 1315 1316

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

1317
                                format!("Did you mean `{}{}`?", prefix, path_str)
C
corentih 已提交
1318 1319
                            }
                            None => format!("Maybe a missing `extern crate {}`?", segment_name),
1320
                        }
1321
                    } else {
C
corentih 已提交
1322
                        format!("Could not find `{}` in `{}`", segment_name, module_name)
1323
                    };
1324

1325
                    return Failed(Some((span, msg)));
1326
                }
1327
                Failed(err) => return Failed(err),
B
Brian Anderson 已提交
1328
                Indeterminate => {
C
corentih 已提交
1329 1330 1331
                    debug!("(resolving module path for import) module resolution is \
                            indeterminate: {}",
                           name);
B
Brian Anderson 已提交
1332
                    return Indeterminate;
1333
                }
1334
                Success(binding) => {
1335 1336
                    // Check to see whether there are type bindings, and, if
                    // so, whether there is a module within.
J
Jeffrey Seyfried 已提交
1337
                    if let Some(module_def) = binding.module() {
1338
                        self.check_privacy(search_module, name, binding, span);
1339 1340 1341 1342
                        search_module = module_def;
                    } else {
                        let msg = format!("Not a module `{}`", name);
                        return Failed(Some((span, msg)));
1343 1344 1345 1346
                    }
                }
            }

T
Tim Chevalier 已提交
1347
            index += 1;
1348 1349
        }

J
Jeffrey Seyfried 已提交
1350
        return Success(search_module);
1351 1352
    }

1353 1354
    /// Attempts to resolve the module part of an import directive or path
    /// rooted at the given module.
F
Felix S. Klock II 已提交
1355
    fn resolve_module_path(&mut self,
1356
                           module_path: &[Name],
1357
                           use_lexical_scope: UseLexicalScopeFlag,
J
Jeffrey Seyfried 已提交
1358
                           span: Span)
J
Jeffrey Seyfried 已提交
1359
                           -> ResolveResult<Module<'a>> {
1360
        if module_path.len() == 0 {
J
Jeffrey Seyfried 已提交
1361
            return Success(self.graph_root) // Use the crate root
1362
        }
1363

1364
        debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1365
               names_to_string(module_path),
1366
               module_to_string(self.current_module));
1367

1368
        // Resolve the module prefix, if any.
1369
        let module_prefix_result = self.resolve_module_prefix(module_path, span);
1370

1371 1372
        let search_module;
        let start_index;
1373
        match module_prefix_result {
1374
            Failed(err) => return Failed(err),
B
Brian Anderson 已提交
1375
            Indeterminate => {
C
corentih 已提交
1376
                debug!("(resolving module path for import) indeterminate; bailing");
B
Brian Anderson 已提交
1377
                return Indeterminate;
1378
            }
1379 1380 1381 1382 1383 1384 1385 1386
            Success(NoPrefixFound) => {
                // There was no prefix, so we're considering the first element
                // of the path. How we handle this depends on whether we were
                // instructed to use lexical scope or not.
                match use_lexical_scope {
                    DontUseLexicalScope => {
                        // This is a crate-relative path. We will start the
                        // resolution process at index zero.
1387
                        search_module = self.graph_root;
1388 1389 1390 1391 1392 1393
                        start_index = 0;
                    }
                    UseLexicalScope => {
                        // This is not a crate-relative path. We resolve the
                        // first component of the path in the current lexical
                        // scope and then proceed to resolve below that.
1394 1395 1396 1397 1398 1399 1400
                        let ident = hir::Ident::from_name(module_path[0]);
                        match self.resolve_ident_in_lexical_scope(ident, TypeNS, true)
                                  .and_then(LexicalScopeBinding::module) {
                            None => return Failed(None),
                            Some(containing_module) => {
                                search_module = containing_module;
                                start_index = 1;
1401 1402 1403 1404 1405
                            }
                        }
                    }
                }
            }
E
Eduard Burtescu 已提交
1406
            Success(PrefixFound(ref containing_module, index)) => {
1407
                search_module = containing_module;
1408
                start_index = index;
1409 1410 1411
            }
        }

1412 1413 1414
        self.resolve_module_path_from_root(search_module,
                                           module_path,
                                           start_index,
J
Jeffrey Seyfried 已提交
1415
                                           span)
1416 1417
    }

1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
    /// 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.
    /// }
    /// ```
1432
    ///
1433 1434
    /// Invariant: This must only be called during main resolution, not during
    /// import resolution.
1435 1436 1437 1438 1439 1440 1441
    fn resolve_ident_in_lexical_scope(&mut self,
                                      ident: hir::Ident,
                                      ns: Namespace,
                                      record_used: bool)
                                      -> Option<LexicalScopeBinding<'a>> {
        let name = match ns { ValueNS => ident.name, TypeNS => ident.unhygienic_name };

1442
        // Walk backwards up the ribs in scope.
1443 1444 1445 1446 1447 1448 1449
        for i in (0 .. self.get_ribs(ns).len()).rev() {
            if let Some(def) = self.get_ribs(ns)[i].bindings.get(&name).cloned() {
                // The ident resolves to a type parameter or local variable.
                return Some(LexicalScopeBinding::LocalDef(LocalDef {
                    ribs: Some((ns, i)),
                    def: def,
                }));
1450 1451
            }

1452 1453 1454 1455 1456 1457
            if let ModuleRibKind(module) = self.get_ribs(ns)[i].kind {
                let name = ident.unhygienic_name;
                let item = self.resolve_name_in_module(module, name, ns, true, record_used);
                if let Success(binding) = item {
                    // The ident resolves to an item.
                    return Some(LexicalScopeBinding::Item(binding));
1458
                }
1459

1460
                // We can only see through anonymous modules
1461
                if module.def.is_some() { return None; }
1462 1463
            }
        }
1464

1465 1466 1467
        None
    }

1468
    /// Returns the nearest normal module parent of the given module.
1469
    fn get_nearest_normal_module_parent(&mut self, module_: Module<'a>) -> Option<Module<'a>> {
1470 1471
        let mut module_ = module_;
        loop {
1472
            match module_.parent_link {
1473 1474 1475
                NoParentLink => return None,
                ModuleParentLink(new_module, _) |
                BlockParentLink(new_module, _) => {
1476
                    let new_module = new_module;
1477 1478
                    if new_module.is_normal() {
                        return Some(new_module);
1479
                    }
1480
                    module_ = new_module;
1481 1482 1483 1484 1485
                }
            }
        }
    }

1486 1487
    /// Returns the nearest normal module parent of the given module, or the
    /// module itself if it is a normal module.
1488
    fn get_nearest_normal_module_parent_or_self(&mut self, module_: Module<'a>) -> Module<'a> {
1489 1490 1491
        if module_.is_normal() {
            return module_;
        }
1492
        match self.get_nearest_normal_module_parent(module_) {
1493 1494
            None => module_,
            Some(new_module) => new_module,
1495 1496 1497
        }
    }

1498
    /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1499
    /// (b) some chain of `super::`.
1500
    /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1501
    fn resolve_module_prefix(&mut self, module_path: &[Name], span: Span)
1502
                             -> ResolveResult<ModulePrefixResult<'a>> {
1503 1504
        // Start at the current module if we see `self` or `super`, or at the
        // top of the crate otherwise.
1505 1506 1507 1508 1509
        let mut i = match &*module_path[0].as_str() {
            "self" => 1,
            "super" => 0,
            _ => return Success(NoPrefixFound),
        };
1510
        let module_ = self.current_module;
1511
        let mut containing_module = self.get_nearest_normal_module_parent_or_self(module_);
1512 1513

        // Now loop through all the `super`s we find.
1514
        while i < module_path.len() && "super" == module_path[i].as_str() {
1515
            debug!("(resolving module prefix) resolving `super` at {}",
J
Jonas Schievink 已提交
1516
                   module_to_string(&containing_module));
1517
            match self.get_nearest_normal_module_parent(containing_module) {
1518 1519 1520 1521
                None => {
                    let msg = "There are too many initial `super`s.".into();
                    return Failed(Some((span, msg)));
                }
1522 1523 1524
                Some(new_module) => {
                    containing_module = new_module;
                    i += 1;
1525 1526 1527 1528
                }
            }
        }

1529
        debug!("(resolving module prefix) finished resolving prefix at {}",
J
Jonas Schievink 已提交
1530
               module_to_string(&containing_module));
1531 1532

        return Success(PrefixFound(containing_module, i));
1533 1534
    }

1535
    /// Attempts to resolve the supplied name in the given module for the
J
Jeffrey Seyfried 已提交
1536
    /// given namespace. If successful, returns the binding corresponding to
1537
    /// the name.
F
Felix S. Klock II 已提交
1538
    fn resolve_name_in_module(&mut self,
1539
                              module: Module<'a>,
1540
                              name: Name,
1541
                              namespace: Namespace,
1542
                              use_lexical_scope: bool,
1543
                              record_used: bool)
1544
                              -> ResolveResult<&'a NameBinding<'a>> {
1545
        debug!("(resolving name in module) resolving `{}` in `{}`", name, module_to_string(module));
1546

1547
        self.populate_module_if_necessary(module);
1548 1549 1550 1551 1552
        match use_lexical_scope {
            true => module.resolve_name_in_lexical_scope(name, namespace)
                          .map(Success).unwrap_or(Failed(None)),
            false => module.resolve_name(name, namespace, false),
        }.and_then(|binding| {
1553 1554
            if record_used {
                self.record_use(name, namespace, binding);
1555
            }
1556 1557
            Success(binding)
        })
1558 1559 1560 1561
    }

    // AST resolution
    //
1562
    // We maintain a list of value ribs and type ribs.
1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
    //
    // 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.

1578
    fn with_scope<F>(&mut self, id: NodeId, f: F)
C
corentih 已提交
1579
        where F: FnOnce(&mut Resolver)
J
Jorge Aparicio 已提交
1580
    {
1581 1582 1583 1584 1585
        if let Some(module) = self.current_module.module_children.borrow().get(&id) {
            // Move down in the graph.
            let orig_module = ::std::mem::replace(&mut self.current_module, module);
            self.value_ribs.push(Rib::new(ModuleRibKind(module)));
            self.type_ribs.push(Rib::new(ModuleRibKind(module)));
1586

1587
            f(self);
1588

1589 1590 1591 1592 1593 1594
            self.current_module = orig_module;
            self.value_ribs.pop();
            self.type_ribs.pop();
        } else {
            f(self);
        }
1595 1596
    }

S
Seo Sanghyeon 已提交
1597 1598
    /// Searches the current set of local scopes for labels.
    /// Stops after meeting a closure.
1599
    fn search_label(&self, name: Name) -> Option<Def> {
1600 1601 1602 1603 1604 1605 1606
        for rib in self.label_ribs.iter().rev() {
            match rib.kind {
                NormalRibKind => {
                    // Continue
                }
                _ => {
                    // Do not resolve labels across function boundary
C
corentih 已提交
1607
                    return None;
1608 1609 1610
                }
            }
            let result = rib.bindings.get(&name).cloned();
S
Seo Sanghyeon 已提交
1611
            if result.is_some() {
C
corentih 已提交
1612
                return result;
1613 1614 1615 1616 1617
            }
        }
        None
    }

1618
    fn resolve_crate(&mut self, krate: &hir::Crate) {
1619
        debug!("(resolving crate) starting");
1620

1621
        intravisit::walk_crate(self, krate);
1622 1623
    }

1624
    fn resolve_item(&mut self, item: &Item) {
V
Vadim Petrochenkov 已提交
1625
        let name = item.name;
1626

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

1629
        match item.node {
1630 1631 1632
            ItemEnum(_, ref generics) |
            ItemTy(_, ref generics) |
            ItemStruct(_, ref generics) => {
C
corentih 已提交
1633
                self.with_type_parameter_rib(HasTypeParameters(generics, TypeSpace, ItemRibKind),
1634
                                             |this| intravisit::walk_item(this, item));
1635
            }
1636
            ItemFn(_, _, _, _, ref generics, _) => {
C
corentih 已提交
1637
                self.with_type_parameter_rib(HasTypeParameters(generics, FnSpace, ItemRibKind),
1638
                                             |this| intravisit::walk_item(this, item));
1639 1640
            }

F
Flavio Percoco 已提交
1641
            ItemDefaultImpl(_, ref trait_ref) => {
1642
                self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
1643
            }
C
corentih 已提交
1644
            ItemImpl(_, _, ref generics, ref opt_trait_ref, ref self_type, ref impl_items) => {
1645
                self.resolve_implementation(generics,
1646
                                            opt_trait_ref,
J
Jonas Schievink 已提交
1647
                                            &self_type,
1648
                                            item.id,
1649
                                            impl_items);
1650 1651
            }

N
Nick Cameron 已提交
1652
            ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
1653 1654 1655 1656 1657
                // Create a new rib for the trait-wide type parameters.
                self.with_type_parameter_rib(HasTypeParameters(generics,
                                                               TypeSpace,
                                                               ItemRibKind),
                                             |this| {
1658
                    let local_def_id = this.ast_map.local_def_id(item.id);
1659
                    this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
1660
                        this.visit_generics(generics);
1661
                        walk_list!(this, visit_ty_param_bound, bounds);
1662 1663

                        for trait_item in trait_items {
1664
                            match trait_item.node {
1665
                                hir::ConstTraitItem(_, ref default) => {
1666 1667 1668 1669 1670
                                    // 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| {
1671
                                            intravisit::walk_trait_item(this, trait_item)
1672 1673
                                        });
                                    } else {
1674
                                        intravisit::walk_trait_item(this, trait_item)
1675 1676
                                    }
                                }
1677
                                hir::MethodTraitItem(ref sig, _) => {
1678 1679 1680 1681 1682
                                    let type_parameters =
                                        HasTypeParameters(&sig.generics,
                                                          FnSpace,
                                                          MethodRibKind);
                                    this.with_type_parameter_rib(type_parameters, |this| {
1683
                                        intravisit::walk_trait_item(this, trait_item)
1684
                                    });
1685
                                }
1686
                                hir::TypeTraitItem(..) => {
1687
                                    this.with_type_parameter_rib(NoTypeParameters, |this| {
1688
                                        intravisit::walk_trait_item(this, trait_item)
1689
                                    });
1690 1691 1692 1693
                                }
                            };
                        }
                    });
1694
                });
1695 1696
            }

1697
            ItemMod(_) | ItemForeignMod(_) => {
1698
                self.with_scope(item.id, |this| {
1699
                    intravisit::walk_item(this, item);
1700
                });
1701 1702
            }

1703
            ItemConst(..) | ItemStatic(..) => {
A
Alex Crichton 已提交
1704
                self.with_constant_rib(|this| {
1705
                    intravisit::walk_item(this, item);
1706
                });
1707
            }
1708

W
we 已提交
1709
            ItemUse(ref view_path) => {
1710
                match view_path.node {
1711 1712 1713 1714 1715 1716
                    hir::ViewPathList(ref prefix, ref items) => {
                        // Resolve prefix of an import with empty braces (issue #28388)
                        if items.is_empty() && !prefix.segments.is_empty() {
                            match self.resolve_crate_relative_path(prefix.span,
                                                                   &prefix.segments,
                                                                   TypeNS) {
1717
                                Ok(def) =>
J
Jeffrey Seyfried 已提交
1718
                                    self.record_def(item.id, PathResolution::new(def, 0)),
1719 1720
                                Err(true) => self.record_def(item.id, err_path_resolution()),
                                Err(false) => {
1721 1722 1723 1724
                                    resolve_error(self,
                                                  prefix.span,
                                                  ResolutionError::FailedToResolve(
                                                      &path_names_to_string(prefix, 0)));
1725
                                    self.record_def(item.id, err_path_resolution());
1726
                                }
1727 1728 1729 1730
                            }
                        }
                    }
                    _ => {}
W
we 已提交
1731 1732 1733
                }
            }

1734
            ItemExternCrate(_) => {
1735
                // do nothing, these are just around to be encoded
1736
            }
1737 1738 1739
        }
    }

1740
    fn with_type_parameter_rib<'b, F>(&'b mut self, type_parameters: TypeParameters<'a, 'b>, f: F)
C
corentih 已提交
1741
        where F: FnOnce(&mut Resolver)
J
Jorge Aparicio 已提交
1742
    {
1743
        match type_parameters {
1744
            HasTypeParameters(generics, space, rib_kind) => {
1745
                let mut function_type_rib = Rib::new(rib_kind);
1746
                let mut seen_bindings = HashSet::new();
D
Daniel Micay 已提交
1747
                for (index, type_parameter) in generics.ty_params.iter().enumerate() {
1748
                    let name = type_parameter.name;
1749
                    debug!("with_type_parameter_rib: {}", type_parameter.id);
1750

1751
                    if seen_bindings.contains(&name) {
1752 1753
                        resolve_error(self,
                                      type_parameter.span,
C
corentih 已提交
1754
                                      ResolutionError::NameAlreadyUsedInTypeParameterList(name));
1755
                    }
1756
                    seen_bindings.insert(name);
1757

1758
                    // plain insert (no renaming)
1759 1760 1761
                    let def_id = self.ast_map.local_def_id(type_parameter.id);
                    let def = Def::TyParam(space, index as u32, def_id, name);
                    function_type_rib.bindings.insert(name, def);
1762
                }
1763
                self.type_ribs.push(function_type_rib);
1764 1765
            }

B
Brian Anderson 已提交
1766
            NoTypeParameters => {
1767 1768 1769 1770
                // Nothing to do.
            }
        }

A
Alex Crichton 已提交
1771
        f(self);
1772

1773
        match type_parameters {
C
corentih 已提交
1774 1775 1776 1777 1778 1779
            HasTypeParameters(..) => {
                if !self.resolved {
                    self.type_ribs.pop();
                }
            }
            NoTypeParameters => {}
1780 1781 1782
        }
    }

C
corentih 已提交
1783 1784
    fn with_label_rib<F>(&mut self, f: F)
        where F: FnOnce(&mut Resolver)
J
Jorge Aparicio 已提交
1785
    {
1786
        self.label_ribs.push(Rib::new(NormalRibKind));
A
Alex Crichton 已提交
1787
        f(self);
G
Garming Sam 已提交
1788 1789 1790
        if !self.resolved {
            self.label_ribs.pop();
        }
1791
    }
1792

C
corentih 已提交
1793 1794
    fn with_constant_rib<F>(&mut self, f: F)
        where F: FnOnce(&mut Resolver)
J
Jorge Aparicio 已提交
1795
    {
1796 1797
        self.value_ribs.push(Rib::new(ConstantItemRibKind));
        self.type_ribs.push(Rib::new(ConstantItemRibKind));
A
Alex Crichton 已提交
1798
        f(self);
G
Garming Sam 已提交
1799 1800 1801 1802
        if !self.resolved {
            self.type_ribs.pop();
            self.value_ribs.pop();
        }
1803 1804
    }

1805
    fn resolve_function(&mut self, rib_kind: RibKind<'a>, declaration: &FnDecl, block: &Block) {
1806
        // Create a value rib for the function.
1807
        self.value_ribs.push(Rib::new(rib_kind));
1808

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

1812 1813 1814
        // Add each argument to the rib.
        let mut bindings_list = HashMap::new();
        for argument in &declaration.inputs {
J
Jonas Schievink 已提交
1815
            self.resolve_pattern(&argument.pat, ArgumentIrrefutableMode, &mut bindings_list);
1816

J
Jonas Schievink 已提交
1817
            self.visit_ty(&argument.ty);
1818

1819 1820
            debug!("(resolving function) recorded argument");
        }
1821
        intravisit::walk_fn_ret_ty(self, &declaration.output);
1822

1823
        // Resolve the function body.
1824
        self.visit_block(block);
1825

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

G
Garming Sam 已提交
1828 1829 1830 1831
        if !self.resolved {
            self.label_ribs.pop();
            self.value_ribs.pop();
        }
1832 1833
    }

F
Felix S. Klock II 已提交
1834
    fn resolve_trait_reference(&mut self,
N
Nick Cameron 已提交
1835
                               id: NodeId,
1836
                               trait_path: &Path,
1837
                               path_depth: usize)
1838
                               -> Result<PathResolution, ()> {
1839
        self.resolve_path(id, trait_path, path_depth, TypeNS).and_then(|path_res| {
1840
            if let Def::Trait(_) = path_res.base_def {
1841 1842 1843
                debug!("(resolving trait) found trait def: {:?}", path_res);
                Ok(path_res)
            } else {
N
Nick Cameron 已提交
1844 1845 1846
                let mut err =
                    resolve_struct_error(self,
                                  trait_path.span,
J
Jonas Schievink 已提交
1847
                                  ResolutionError::IsNotATrait(&path_names_to_string(trait_path,
N
Nick Cameron 已提交
1848
                                                                                      path_depth)));
1849 1850

                // If it's a typedef, give a note
V
vegai 已提交
1851
                if let Def::TyAlias(did) = path_res.base_def {
V
vegai 已提交
1852
                    err.fileline_note(trait_path.span,
N
Nick Cameron 已提交
1853
                                  "`type` aliases cannot be used for traits");
V
vegai 已提交
1854 1855 1856
                    if let Some(sp) = self.ast_map.span_if_local(did) {
                        err.span_note(sp, "type defined here");
                    }
1857
                }
N
Nick Cameron 已提交
1858
                err.emit();
1859
                Err(true)
1860
            }
1861 1862
        }).map_err(|error_reported| {
            if error_reported { return }
1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884

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

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

            resolve_error(self, trait_path.span, error);
1885
        })
1886 1887
    }

1888 1889
    fn resolve_generics(&mut self, generics: &Generics) {
        for predicate in &generics.where_clause.predicates {
1890
            match predicate {
1891 1892 1893
                &hir::WherePredicate::BoundPredicate(_) |
                &hir::WherePredicate::RegionPredicate(_) => {}
                &hir::WherePredicate::EqPredicate(ref eq_pred) => {
1894 1895 1896 1897 1898 1899 1900
                    self.resolve_path(eq_pred.id, &eq_pred.path, 0, TypeNS).and_then(|path_res| {
                        if let PathResolution { base_def: Def::TyParam(..), .. } = path_res {
                            Ok(self.record_def(eq_pred.id, path_res))
                        } else {
                            Err(false)
                        }
                    }).map_err(|error_reported| {
1901
                        self.record_def(eq_pred.id, err_path_resolution());
1902
                        if error_reported { return }
J
Jeffrey Seyfried 已提交
1903 1904
                        let error_variant = ResolutionError::UndeclaredAssociatedType;
                        resolve_error(self, eq_pred.span, error_variant);
1905
                    }).unwrap_or(());
1906
                }
1907 1908
            }
        }
1909
        intravisit::walk_generics(self, generics);
1910 1911
    }

1912 1913
    fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
        where F: FnOnce(&mut Resolver) -> T
J
Jorge Aparicio 已提交
1914
    {
1915 1916 1917 1918 1919 1920 1921
        // Handle nested impls (inside fn bodies)
        let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
        let result = f(self);
        self.current_self_type = previous_value;
        result
    }

C
corentih 已提交
1922
    fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
1923
        where F: FnOnce(&mut Resolver, Option<DefId>) -> T
J
Jorge Aparicio 已提交
1924
    {
1925
        let mut new_val = None;
1926
        let mut new_id = None;
E
Eduard Burtescu 已提交
1927
        if let Some(trait_ref) = opt_trait_ref {
1928
            if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
C
corentih 已提交
1929 1930
                                                               &trait_ref.path,
                                                               0) {
1931 1932 1933 1934
                assert!(path_res.depth == 0);
                self.record_def(trait_ref.ref_id, path_res);
                new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
                new_id = Some(path_res.base_def.def_id());
1935 1936
            } else {
                self.record_def(trait_ref.ref_id, err_path_resolution());
1937
            }
1938
            intravisit::walk_trait_ref(self, trait_ref);
1939
        }
1940
        let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
1941
        let result = f(self, new_id);
1942 1943 1944 1945
        self.current_trait_ref = original_trait_ref;
        result
    }

1946 1947 1948 1949 1950 1951 1952
    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....)
        let name = special_names::type_self;
1953
        self_type_rib.bindings.insert(name, self_def);
1954 1955
        self.type_ribs.push(self_type_rib);
        f(self);
G
Garming Sam 已提交
1956 1957 1958
        if !self.resolved {
            self.type_ribs.pop();
        }
1959 1960
    }

F
Felix S. Klock II 已提交
1961
    fn resolve_implementation(&mut self,
1962 1963 1964
                              generics: &Generics,
                              opt_trait_reference: &Option<TraitRef>,
                              self_type: &Ty,
1965
                              item_id: NodeId,
1966
                              impl_items: &[ImplItem]) {
1967
        // If applicable, create a rib for the type parameters.
1968
        self.with_type_parameter_rib(HasTypeParameters(generics,
1969
                                                       TypeSpace,
1970
                                                       ItemRibKind),
1971
                                     |this| {
1972
            // Resolve the type parameters.
1973
            this.visit_generics(generics);
1974

1975
            // Resolve the trait reference, if necessary.
1976
            this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
1977
                // Resolve the self type.
1978
                this.visit_ty(self_type);
1979

1980
                this.with_self_rib(Def::SelfTy(trait_id, Some((item_id, self_type.id))), |this| {
1981 1982 1983
                    this.with_current_self_type(self_type, |this| {
                        for impl_item in impl_items {
                            match impl_item.node {
1984
                                hir::ImplItemKind::Const(..) => {
1985
                                    // If this is a trait impl, ensure the const
1986
                                    // exists in trait
V
Vadim Petrochenkov 已提交
1987
                                    this.check_trait_item(impl_item.name,
1988 1989
                                                          impl_item.span,
                                        |n, s| ResolutionError::ConstNotMemberOfTrait(n, s));
1990
                                    this.with_constant_rib(|this| {
1991
                                        intravisit::walk_impl_item(this, impl_item);
1992 1993
                                    });
                                }
1994
                                hir::ImplItemKind::Method(ref sig, _) => {
1995 1996
                                    // If this is a trait impl, ensure the method
                                    // exists in trait
V
Vadim Petrochenkov 已提交
1997
                                    this.check_trait_item(impl_item.name,
1998 1999
                                                          impl_item.span,
                                        |n, s| ResolutionError::MethodNotMemberOfTrait(n, s));
2000 2001 2002 2003 2004 2005 2006 2007

                                    // We also need a new scope for the method-
                                    // specific type parameters.
                                    let type_parameters =
                                        HasTypeParameters(&sig.generics,
                                                          FnSpace,
                                                          MethodRibKind);
                                    this.with_type_parameter_rib(type_parameters, |this| {
2008
                                        intravisit::walk_impl_item(this, impl_item);
2009 2010
                                    });
                                }
2011
                                hir::ImplItemKind::Type(ref ty) => {
2012
                                    // If this is a trait impl, ensure the type
2013
                                    // exists in trait
V
Vadim Petrochenkov 已提交
2014
                                    this.check_trait_item(impl_item.name,
2015 2016
                                                          impl_item.span,
                                        |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
2017

2018 2019
                                    this.visit_ty(ty);
                                }
2020
                            }
2021
                        }
2022
                    });
2023 2024
                });
            });
2025
        });
2026 2027
    }

2028
    fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
C
corentih 已提交
2029 2030 2031 2032
        where F: FnOnce(Name, &str) -> ResolutionError
    {
        // If there is a TraitRef in scope for an impl, then the method must be in the
        // trait.
2033
        if let Some((did, ref trait_ref)) = self.current_trait_ref {
2034
            if !self.trait_item_map.contains_key(&(name, did)) {
2035
                let path_str = path_names_to_string(&trait_ref.path, 0);
J
Jonas Schievink 已提交
2036
                resolve_error(self, span, err(name, &path_str));
2037 2038 2039 2040
            }
        }
    }

E
Eduard Burtescu 已提交
2041
    fn resolve_local(&mut self, local: &Local) {
2042
        // Resolve the type.
2043
        walk_list!(self, visit_ty, &local.ty);
2044

2045
        // Resolve the initializer.
2046
        walk_list!(self, visit_expr, &local.init);
2047 2048

        // Resolve the pattern.
J
Jonas Schievink 已提交
2049
        self.resolve_pattern(&local.pat, LocalIrrefutableMode, &mut HashMap::new());
2050 2051
    }

J
John Clements 已提交
2052 2053 2054 2055
    // 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 已提交
2056
    fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2057
        let mut result = HashMap::new();
2058 2059
        pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
            let name = path1.node;
C
corentih 已提交
2060 2061 2062 2063 2064
            result.insert(name,
                          BindingInfo {
                              span: sp,
                              binding_mode: binding_mode,
                          });
2065
        });
2066
        return result;
2067 2068
    }

J
John Clements 已提交
2069 2070
    // 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 已提交
2071
    fn check_consistent_bindings(&mut self, arm: &Arm) {
2072
        if arm.pats.is_empty() {
C
corentih 已提交
2073
            return;
2074
        }
J
Jonas Schievink 已提交
2075
        let map_0 = self.binding_mode_map(&arm.pats[0]);
D
Daniel Micay 已提交
2076
        for (i, p) in arm.pats.iter().enumerate() {
J
Jonas Schievink 已提交
2077
            let map_i = self.binding_mode_map(&p);
2078

2079
            for (&key, &binding_0) in &map_0 {
2080
                match map_i.get(&key) {
C
corentih 已提交
2081
                    None => {
2082
                        resolve_error(self,
C
corentih 已提交
2083 2084 2085 2086 2087 2088 2089 2090 2091 2092
                                      p.span,
                                      ResolutionError::VariableNotBoundInPattern(key, i + 1));
                    }
                    Some(binding_i) => {
                        if binding_0.binding_mode != binding_i.binding_mode {
                            resolve_error(self,
                                          binding_i.span,
                                          ResolutionError::VariableBoundWithDifferentMode(key,
                                                                                          i + 1));
                        }
2093
                    }
2094 2095 2096
                }
            }

2097
            for (&key, &binding) in &map_i {
2098
                if !map_0.contains_key(&key) {
2099 2100
                    resolve_error(self,
                                  binding.span,
C
corentih 已提交
2101
                                  ResolutionError::VariableNotBoundInParentPattern(key, i + 1));
2102 2103 2104
                }
            }
        }
2105 2106
    }

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

2110
        let mut bindings_list = HashMap::new();
2111
        for pattern in &arm.pats {
J
Jonas Schievink 已提交
2112
            self.resolve_pattern(&pattern, RefutableMode, &mut bindings_list);
2113 2114
        }

2115 2116 2117 2118
        // This has to happen *after* we determine which
        // pat_idents are variants
        self.check_consistent_bindings(arm);

2119
        walk_list!(self, visit_expr, &arm.guard);
J
Jonas Schievink 已提交
2120
        self.visit_expr(&arm.body);
2121

G
Garming Sam 已提交
2122 2123 2124
        if !self.resolved {
            self.value_ribs.pop();
        }
2125 2126
    }

E
Eduard Burtescu 已提交
2127
    fn resolve_block(&mut self, block: &Block) {
2128
        debug!("(resolving block) entering block");
2129
        // Move down in the graph, if there's an anonymous module rooted here.
2130
        let orig_module = self.current_module;
2131
        let anonymous_module =
2132
            orig_module.module_children.borrow().get(&block.id).map(|module| *module);
2133 2134 2135

        if let Some(anonymous_module) = anonymous_module {
            debug!("(resolving block) found anonymous module, moving down");
2136 2137
            self.value_ribs.push(Rib::new(ModuleRibKind(anonymous_module)));
            self.type_ribs.push(Rib::new(ModuleRibKind(anonymous_module)));
2138 2139 2140
            self.current_module = anonymous_module;
        } else {
            self.value_ribs.push(Rib::new(NormalRibKind));
2141 2142 2143
        }

        // Descend into the block.
2144
        intravisit::walk_block(self, block);
2145 2146

        // Move back up.
G
Garming Sam 已提交
2147
        if !self.resolved {
2148
            self.current_module = orig_module;
G
Garming Sam 已提交
2149
            self.value_ribs.pop();
2150 2151 2152
            if let Some(_) = anonymous_module {
                self.type_ribs.pop();
            }
G
Garming Sam 已提交
2153
        }
2154
        debug!("(resolving block) leaving block");
2155 2156
    }

F
Felix S. Klock II 已提交
2157
    fn resolve_type(&mut self, ty: &Ty) {
2158
        match ty.node {
2159
            TyPath(ref maybe_qself, ref path) => {
C
corentih 已提交
2160 2161 2162
                let resolution = match self.resolve_possibly_assoc_item(ty.id,
                                                                        maybe_qself.as_ref(),
                                                                        path,
J
Jeffrey Seyfried 已提交
2163
                                                                        TypeNS) {
C
corentih 已提交
2164 2165 2166
                    // `<T>::a::b::c` is resolved by typeck alone.
                    TypecheckRequired => {
                        // Resolve embedded types.
2167
                        intravisit::walk_ty(self, ty);
C
corentih 已提交
2168 2169 2170 2171
                        return;
                    }
                    ResolveAttempt(resolution) => resolution,
                };
2172 2173

                // This is a path in the type namespace. Walk through scopes
2174
                // looking for it.
2175 2176 2177 2178 2179 2180 2181
                if let Some(def) = resolution {
                    // Write the result into the def map.
                    debug!("(resolving type) writing resolution for `{}` (id {}) = {:?}",
                           path_names_to_string(path, 0), ty.id, def);
                    self.record_def(ty.id, def);
                } else {
                    self.record_def(ty.id, err_path_resolution());
2182

2183 2184 2185 2186
                    // Keep reporting some errors even if they're ignored above.
                    if let Err(true) = self.resolve_path(ty.id, path, 0, TypeNS) {
                        // `resolve_path` already reported the error
                    } else {
2187 2188 2189 2190
                        let kind = if maybe_qself.is_some() {
                            "associated type"
                        } else {
                            "type name"
2191
                        };
2192

2193
                        let self_type_name = special_idents::type_self.name;
C
corentih 已提交
2194 2195 2196 2197
                        let is_invalid_self_type_name = path.segments.len() > 0 &&
                                                        maybe_qself.is_none() &&
                                                        path.segments[0].identifier.name ==
                                                        self_type_name;
G
Guillaume Gomez 已提交
2198
                        if is_invalid_self_type_name {
2199 2200
                            resolve_error(self,
                                          ty.span,
2201
                                          ResolutionError::SelfUsedOutsideImplOrTrait);
2202
                        } else {
2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229
                            let segment = path.segments.last();
                            let segment = segment.expect("missing name in path");
                            let type_name = segment.identifier.name;

                            let candidates =
                                self.lookup_candidates(
                                    type_name,
                                    TypeNS,
                                    |def| match def {
                                        Def::Trait(_) |
                                        Def::Enum(_) |
                                        Def::Struct(_) |
                                        Def::TyAlias(_) => true,
                                        _               => false,
                                    },
                                );

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

                            resolve_error(self, ty.span, error);
G
Guillaume Gomez 已提交
2230
                        }
2231 2232
                    }
                }
2233
            }
2234
            _ => {}
2235
        }
2236
        // Resolve embedded types.
2237
        intravisit::walk_ty(self, ty);
2238 2239
    }

F
Felix S. Klock II 已提交
2240
    fn resolve_pattern(&mut self,
E
Eduard Burtescu 已提交
2241
                       pattern: &Pat,
2242 2243 2244
                       mode: PatternBindingMode,
                       // Maps idents to the node ID for the (outermost)
                       // pattern that binds them
2245
                       bindings_list: &mut HashMap<Name, NodeId>) {
2246
        let pat_id = pattern.id;
2247
        pattern.walk(|pattern| {
2248
            match pattern.node {
2249 2250
                PatKind::Ident(binding_mode, ref path1, ref at_rhs) => {
                    // The meaning of PatKind::Ident with no type parameters
2251 2252 2253 2254
                    // depends on whether an enum variant or unit-like struct
                    // with that name is in scope. The probing lookup has to
                    // be careful not to emit spurious errors. Only matching
                    // patterns (match) can match nullary variants or
2255 2256 2257 2258
                    // unit-like structs. For binding patterns (let
                    // and the LHS of @-patterns), matching such a value is
                    // simply disallowed (since it's rarely what you want).
                    let const_ok = mode == RefutableMode && at_rhs.is_none();
2259

2260
                    let ident = path1.node;
2261
                    let renamed = ident.name;
2262

2263
                    match self.resolve_bare_identifier_pattern(ident, pattern.span) {
J
Jeffrey Seyfried 已提交
2264
                        FoundStructOrEnumVariant(def) if const_ok => {
C
corentih 已提交
2265
                            debug!("(resolving pattern) resolving `{}` to struct or enum variant",
2266
                                   renamed);
2267

C
corentih 已提交
2268 2269 2270 2271 2272 2273 2274 2275
                            self.enforce_default_binding_mode(pattern,
                                                              binding_mode,
                                                              "an enum variant");
                            self.record_def(pattern.id,
                                            PathResolution {
                                                base_def: def,
                                                depth: 0,
                                            });
2276
                        }
A
Alex Crichton 已提交
2277
                        FoundStructOrEnumVariant(..) => {
2278
                            resolve_error(
2279
                                self,
2280
                                pattern.span,
2281
                                ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(
2282 2283
                                    renamed)
                            );
2284
                            self.record_def(pattern.id, err_path_resolution());
2285
                        }
J
Jeffrey Seyfried 已提交
2286
                        FoundConst(def, _) if const_ok => {
C
corentih 已提交
2287 2288 2289 2290 2291 2292 2293 2294
                            debug!("(resolving pattern) resolving `{}` to constant", renamed);

                            self.enforce_default_binding_mode(pattern, binding_mode, "a constant");
                            self.record_def(pattern.id,
                                            PathResolution {
                                                base_def: def,
                                                depth: 0,
                                            });
2295
                        }
J
Jeffrey Seyfried 已提交
2296
                        FoundConst(def, name) => {
2297
                            resolve_error(
2298 2299
                                self,
                                pattern.span,
M
Manish Goregaokar 已提交
2300 2301
                                ResolutionError::OnlyIrrefutablePatternsAllowedHere(def.def_id(),
                                                                                    name)
2302
                            );
2303
                            self.record_def(pattern.id, err_path_resolution());
2304
                        }
2305
                        BareIdentifierPatternUnresolved => {
C
corentih 已提交
2306
                            debug!("(resolving pattern) binding `{}`", renamed);
2307

2308
                            let def_id = self.ast_map.local_def_id(pattern.id);
2309
                            let def = Def::Local(def_id, pattern.id);
2310 2311 2312 2313 2314

                            // Record the definition so that later passes
                            // will be able to distinguish variants from
                            // locals in patterns.

C
corentih 已提交
2315 2316 2317 2318 2319
                            self.record_def(pattern.id,
                                            PathResolution {
                                                base_def: def,
                                                depth: 0,
                                            });
2320 2321 2322 2323 2324 2325

                            // Add the binding to the local ribs, if it
                            // doesn't already exist in the bindings list. (We
                            // must not add it if it's in the bindings list
                            // because that breaks the assumptions later
                            // passes make about or-patterns.)
2326 2327
                            if !bindings_list.contains_key(&renamed) {
                                let this = &mut *self;
2328
                                let last_rib = this.value_ribs.last_mut().unwrap();
2329
                                last_rib.bindings.insert(renamed, def);
2330
                                bindings_list.insert(renamed, pat_id);
2331
                            } else if mode == ArgumentIrrefutableMode &&
C
corentih 已提交
2332
                               bindings_list.contains_key(&renamed) {
2333 2334
                                // Forbid duplicate bindings in the same
                                // parameter list.
2335
                                resolve_error(
2336 2337
                                    self,
                                    pattern.span,
2338
                                    ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2339
                                        &ident.name.as_str())
2340
                                );
C
corentih 已提交
2341
                            } else if bindings_list.get(&renamed) == Some(&pat_id) {
2342 2343
                                // Then this is a duplicate variable in the
                                // same disjunction, which is an error.
2344
                                resolve_error(
2345 2346
                                    self,
                                    pattern.span,
2347
                                    ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2348
                                        &ident.name.as_str())
2349
                                );
2350
                            }
2351 2352
                            // Else, not bound in the same pattern: do
                            // nothing.
2353 2354 2355 2356
                        }
                    }
                }

2357
                PatKind::TupleStruct(ref path, _) | PatKind::Path(ref path) => {
2358
                    // This must be an enum variant, struct or const.
C
corentih 已提交
2359 2360 2361
                    let resolution = match self.resolve_possibly_assoc_item(pat_id,
                                                                            None,
                                                                            path,
J
Jeffrey Seyfried 已提交
2362
                                                                            ValueNS) {
C
corentih 已提交
2363
                        // The below shouldn't happen because all
2364
                        // qualified paths should be in PatKind::QPath.
C
corentih 已提交
2365
                        TypecheckRequired =>
2366 2367 2368 2369 2370
                            span_bug!(path.span,
                                      "resolve_possibly_assoc_item claimed that a path \
                                       in PatKind::Path or PatKind::TupleStruct \
                                       requires typecheck to resolve, but qualified \
                                       paths should be PatKind::QPath"),
C
corentih 已提交
2371 2372
                        ResolveAttempt(resolution) => resolution,
                    };
2373
                    if let Some(path_res) = resolution {
2374
                        match path_res.base_def {
2375
                            Def::Struct(..) if path_res.depth == 0 => {
2376 2377
                                self.record_def(pattern.id, path_res);
                            }
2378
                            Def::Variant(..) | Def::Const(..) => {
2379 2380
                                self.record_def(pattern.id, path_res);
                            }
2381
                            Def::Static(..) => {
2382 2383
                                resolve_error(&self,
                                              path.span,
2384
                                              ResolutionError::StaticVariableReference);
2385
                                self.record_def(pattern.id, err_path_resolution());
2386
                            }
2387 2388 2389 2390
                            _ => {
                                // If anything ends up here entirely resolved,
                                // it's an error. If anything ends up here
                                // partially resolved, that's OK, because it may
2391
                                // be a `T::CONST` that typeck will resolve.
2392
                                if path_res.depth == 0 {
2393
                                    resolve_error(
2394
                                        self,
2395
                                        path.span,
2396
                                        ResolutionError::NotAnEnumVariantStructOrConst(
2397 2398 2399 2400 2401 2402
                                            &path.segments
                                                 .last()
                                                 .unwrap()
                                                 .identifier
                                                 .name
                                                 .as_str())
2403
                                    );
2404
                                    self.record_def(pattern.id, err_path_resolution());
2405
                                } else {
C
corentih 已提交
2406 2407 2408 2409 2410
                                    let const_name = path.segments
                                                         .last()
                                                         .unwrap()
                                                         .identifier
                                                         .name;
2411 2412
                                    let traits = self.get_traits_containing_item(const_name);
                                    self.trait_map.insert(pattern.id, traits);
2413 2414 2415 2416 2417
                                    self.record_def(pattern.id, path_res);
                                }
                            }
                        }
                    } else {
2418
                        resolve_error(
2419 2420
                            self,
                            path.span,
2421
                            ResolutionError::UnresolvedEnumVariantStructOrConst(
2422
                                &path.segments.last().unwrap().identifier.name.as_str())
2423
                        );
2424
                        self.record_def(pattern.id, err_path_resolution());
2425
                    }
2426
                    intravisit::walk_path(self, path);
2427 2428
                }

2429
                PatKind::QPath(ref qself, ref path) => {
2430
                    // Associated constants only.
C
corentih 已提交
2431 2432 2433
                    let resolution = match self.resolve_possibly_assoc_item(pat_id,
                                                                            Some(qself),
                                                                            path,
J
Jeffrey Seyfried 已提交
2434
                                                                            ValueNS) {
C
corentih 已提交
2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445
                        TypecheckRequired => {
                            // All `<T>::CONST` should end up here, and will
                            // require use of the trait map to resolve
                            // during typechecking.
                            let const_name = path.segments
                                                 .last()
                                                 .unwrap()
                                                 .identifier
                                                 .name;
                            let traits = self.get_traits_containing_item(const_name);
                            self.trait_map.insert(pattern.id, traits);
2446
                            intravisit::walk_pat(self, pattern);
C
corentih 已提交
2447 2448 2449 2450
                            return true;
                        }
                        ResolveAttempt(resolution) => resolution,
                    };
2451 2452 2453 2454
                    if let Some(path_res) = resolution {
                        match path_res.base_def {
                            // All `<T as Trait>::CONST` should end up here, and
                            // have the trait already selected.
2455
                            Def::AssociatedConst(..) => {
2456 2457
                                self.record_def(pattern.id, path_res);
                            }
2458
                            _ => {
2459
                                resolve_error(
2460 2461
                                    self,
                                    path.span,
2462
                                    ResolutionError::NotAnAssociatedConst(
2463
                                        &path.segments.last().unwrap().identifier.name.as_str()
2464 2465
                                    )
                                );
2466
                                self.record_def(pattern.id, err_path_resolution());
2467
                            }
2468
                        }
2469
                    } else {
C
corentih 已提交
2470 2471 2472 2473 2474 2475 2476 2477
                        resolve_error(self,
                                      path.span,
                                      ResolutionError::UnresolvedAssociatedConst(&path.segments
                                                                                      .last()
                                                                                      .unwrap()
                                                                                      .identifier
                                                                                      .name
                                                                                      .as_str()));
2478
                        self.record_def(pattern.id, err_path_resolution());
2479
                    }
2480
                    intravisit::walk_pat(self, pattern);
2481 2482
                }

2483
                PatKind::Struct(ref path, _, _) => {
J
Jeffrey Seyfried 已提交
2484
                    match self.resolve_path(pat_id, path, 0, TypeNS) {
2485
                        Ok(definition) => {
2486 2487
                            self.record_def(pattern.id, definition);
                        }
2488 2489
                        Err(true) => self.record_def(pattern.id, err_path_resolution()),
                        Err(false) => {
2490 2491 2492
                            resolve_error(
                                self,
                                path.span,
2493
                                ResolutionError::DoesNotNameAStruct(
J
Jonas Schievink 已提交
2494
                                    &path_names_to_string(path, 0))
2495
                            );
2496
                            self.record_def(pattern.id, err_path_resolution());
2497 2498
                        }
                    }
2499
                    intravisit::walk_path(self, path);
2500 2501
                }

2502
                PatKind::Lit(_) | PatKind::Range(..) => {
2503
                    intravisit::walk_pat(self, pattern);
2504 2505
                }

2506
                _ => {
2507 2508 2509
                    // Nothing to do.
                }
            }
2510
            true
2511
        });
2512 2513
    }

2514
    fn resolve_bare_identifier_pattern(&mut self, ident: hir::Ident, span: Span)
E
Eduard Burtescu 已提交
2515
                                       -> BareIdentifierPatternResolution {
2516 2517 2518 2519
        match self.resolve_ident_in_lexical_scope(ident, ValueNS, true)
                  .map(LexicalScopeBinding::def) {
            Some(def @ Def::Variant(..)) | Some(def @ Def::Struct(..)) => {
                FoundStructOrEnumVariant(def)
2520
            }
2521 2522
            Some(def @ Def::Const(..)) | Some(def @ Def::AssociatedConst(..)) => {
                FoundConst(def, ident.unhygienic_name)
2523
            }
2524 2525 2526 2527 2528
            Some(Def::Static(..)) => {
                resolve_error(self, span, ResolutionError::StaticVariableReference);
                BareIdentifierPatternUnresolved
            }
            _ => BareIdentifierPatternUnresolved,
2529 2530 2531
        }
    }

2532 2533 2534
    /// Handles paths that may refer to associated items
    fn resolve_possibly_assoc_item(&mut self,
                                   id: NodeId,
2535
                                   maybe_qself: Option<&hir::QSelf>,
2536
                                   path: &Path,
J
Jeffrey Seyfried 已提交
2537
                                   namespace: Namespace)
C
corentih 已提交
2538
                                   -> AssocItemResolveResult {
2539 2540
        let max_assoc_types;

2541
        match maybe_qself {
2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552
            Some(qself) => {
                if qself.position == 0 {
                    return TypecheckRequired;
                }
                max_assoc_types = path.segments.len() - qself.position;
                // Make sure the trait is valid.
                let _ = self.resolve_trait_reference(id, path, max_assoc_types);
            }
            None => {
                max_assoc_types = path.segments.len();
            }
2553 2554 2555
        }

        let mut resolution = self.with_no_errors(|this| {
2556
            this.resolve_path(id, path, 0, namespace).ok()
2557 2558 2559 2560 2561 2562
        });
        for depth in 1..max_assoc_types {
            if resolution.is_some() {
                break;
            }
            self.with_no_errors(|this| {
2563
                resolution = this.resolve_path(id, path, depth, TypeNS).ok();
2564 2565
            });
        }
2566
        if let Some(Def::Mod(_)) = resolution.map(|r| r.base_def) {
2567 2568 2569 2570 2571 2572
            // A module is not a valid type or value.
            resolution = None;
        }
        ResolveAttempt(resolution)
    }

2573
    /// Skips `path_depth` trailing segments, which is also reflected in the
2574
    /// returned value. See `hir::def::PathResolution` for more info.
J
Jeffrey Seyfried 已提交
2575
    fn resolve_path(&mut self, id: NodeId, path: &Path, path_depth: usize, namespace: Namespace)
2576
                    -> Result<PathResolution, bool /* true if an error was reported */ > {
2577
        let span = path.span;
C
corentih 已提交
2578
        let segments = &path.segments[..path.segments.len() - path_depth];
2579

J
Jeffrey Seyfried 已提交
2580
        let mk_res = |def| PathResolution::new(def, path_depth);
2581

2582
        if path.global {
2583
            let def = self.resolve_crate_relative_path(span, segments, namespace);
2584
            return def.map(mk_res);
2585 2586
        }

2587
        // Try to find a path to an item in a module.
2588
        let last_ident = segments.last().unwrap().identifier;
V
Cleanup  
Vadim Petrochenkov 已提交
2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600
        // Resolve a single identifier with fallback to primitive types
        let resolve_identifier_with_fallback = |this: &mut Self, record_used| {
            let def = this.resolve_identifier(last_ident, namespace, record_used);
            match def {
                None | Some(LocalDef{def: Def::Mod(..), ..}) if namespace == TypeNS =>
                    this.primitive_type_table
                        .primitive_types
                        .get(&last_ident.unhygienic_name)
                        .map_or(def, |prim_ty| Some(LocalDef::from_def(Def::PrimTy(*prim_ty)))),
                _ => def
            }
        };
2601

2602 2603 2604 2605 2606 2607 2608
        if segments.len() == 1 {
            // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
            // don't report an error right away, but try to fallback to a primitive type.
            // So, we are still able to successfully resolve something like
            //
            // use std::u8; // bring module u8 in scope
            // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
V
Cleanup  
Vadim Petrochenkov 已提交
2609 2610
            //     u8::max_value() // OK, resolves to associated function <u8>::max_value,
            //                     // not to non-existent std::u8::max_value
2611 2612 2613 2614
            // }
            //
            // Such behavior is required for backward compatibility.
            // The same fallback is used when `a` resolves to nothing.
2615 2616
            let def = resolve_identifier_with_fallback(self, true).ok_or(false);
            return def.and_then(|def| self.adjust_local_def(def, span).ok_or(true)).map(mk_res);
N
Nick Cameron 已提交
2617
        }
2618

V
Cleanup  
Vadim Petrochenkov 已提交
2619
        let unqualified_def = resolve_identifier_with_fallback(self, false);
N
Nick Cameron 已提交
2620 2621
        let def = self.resolve_module_relative_path(span, segments, namespace);
        match (def, unqualified_def) {
2622
            (Ok(d), Some(ref ud)) if d == ud.def => {
N
Nick Cameron 已提交
2623 2624
                self.session
                    .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
C
corentih 已提交
2625 2626
                              id,
                              span,
N
Nick Cameron 已提交
2627 2628 2629
                              "unnecessary qualification".to_string());
            }
            _ => {}
2630
        }
N
Nick Cameron 已提交
2631 2632

        def.map(mk_res)
2633 2634
    }

2635
    // Resolve a single identifier
F
Felix S. Klock II 已提交
2636
    fn resolve_identifier(&mut self,
2637
                          identifier: hir::Ident,
2638
                          namespace: Namespace,
2639
                          record_used: bool)
2640
                          -> Option<LocalDef> {
2641
        if identifier.name == special_idents::invalid.name {
2642
            return Some(LocalDef::from_def(Def::Err));
2643 2644
        }

2645 2646
        self.resolve_ident_in_lexical_scope(identifier, namespace, record_used)
            .map(LexicalScopeBinding::local_def)
2647 2648 2649
    }

    // Resolve a local definition, potentially adjusting for closures.
2650
    fn adjust_local_def(&mut self, local_def: LocalDef, span: Span) -> Option<Def> {
2651
        let ribs = match local_def.ribs {
C
corentih 已提交
2652 2653 2654
            Some((TypeNS, i)) => &self.type_ribs[i + 1..],
            Some((ValueNS, i)) => &self.value_ribs[i + 1..],
            _ => &[] as &[_],
2655 2656 2657
        };
        let mut def = local_def.def;
        match def {
2658
            Def::Upvar(..) => {
2659
                span_bug!(span, "unexpected {:?} in bindings", def)
2660
            }
2661
            Def::Local(_, node_id) => {
2662 2663
                for rib in ribs {
                    match rib.kind {
2664
                        NormalRibKind | ModuleRibKind(..) => {
2665 2666 2667 2668 2669 2670
                            // Nothing to do. Continue.
                        }
                        ClosureRibKind(function_id) => {
                            let prev_def = def;
                            let node_def_id = self.ast_map.local_def_id(node_id);

C
corentih 已提交
2671 2672 2673
                            let seen = self.freevars_seen
                                           .entry(function_id)
                                           .or_insert_with(|| NodeMap());
2674
                            if let Some(&index) = seen.get(&node_id) {
2675
                                def = Def::Upvar(node_def_id, node_id, index, function_id);
2676 2677
                                continue;
                            }
C
corentih 已提交
2678 2679 2680
                            let vec = self.freevars
                                          .entry(function_id)
                                          .or_insert_with(|| vec![]);
2681
                            let depth = vec.len();
C
corentih 已提交
2682 2683 2684 2685
                            vec.push(Freevar {
                                def: prev_def,
                                span: span,
                            });
2686

2687
                            def = Def::Upvar(node_def_id, node_id, depth, function_id);
2688 2689 2690 2691 2692 2693
                            seen.insert(node_id, depth);
                        }
                        ItemRibKind | MethodRibKind => {
                            // This was an attempt to access an upvar inside a
                            // named function item. This is not allowed, so we
                            // report an error.
C
corentih 已提交
2694 2695 2696
                            resolve_error(self,
                                          span,
                                          ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
2697 2698 2699 2700
                            return None;
                        }
                        ConstantItemRibKind => {
                            // Still doesn't deal with upvars
C
corentih 已提交
2701 2702 2703
                            resolve_error(self,
                                          span,
                                          ResolutionError::AttemptToUseNonConstantValueInConstant);
2704 2705 2706 2707 2708
                            return None;
                        }
                    }
                }
            }
2709
            Def::TyParam(..) | Def::SelfTy(..) => {
2710 2711
                for rib in ribs {
                    match rib.kind {
2712
                        NormalRibKind | MethodRibKind | ClosureRibKind(..) |
2713
                        ModuleRibKind(..) => {
2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735
                            // Nothing to do. Continue.
                        }
                        ItemRibKind => {
                            // This was an attempt to use a type parameter outside
                            // its scope.

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

2738
    // resolve a "module-relative" path, e.g. a::b::c
F
Felix S. Klock II 已提交
2739
    fn resolve_module_relative_path(&mut self,
2740
                                    span: Span,
2741
                                    segments: &[hir::PathSegment],
2742
                                    namespace: Namespace)
2743
                                    -> Result<Def, bool /* true if an error was reported */> {
C
corentih 已提交
2744 2745 2746 2747 2748 2749
        let module_path = segments.split_last()
                                  .unwrap()
                                  .1
                                  .iter()
                                  .map(|ps| ps.identifier.name)
                                  .collect::<Vec<_>>();
2750

2751
        let containing_module;
2752
        match self.resolve_module_path(&module_path, UseLexicalScope, span) {
2753 2754 2755 2756
            Failed(err) => {
                let (span, msg) = match err {
                    Some((span, msg)) => (span, msg),
                    None => {
2757
                        let msg = format!("Use of undeclared type or module `{}`",
2758
                                          names_to_string(&module_path));
2759
                        (span, msg)
2760 2761
                    }
                };
2762

J
Jonas Schievink 已提交
2763
                resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
2764
                return Err(true);
2765
            }
2766
            Indeterminate => return Err(false),
J
Jeffrey Seyfried 已提交
2767
            Success(resulting_module) => {
2768 2769 2770 2771
                containing_module = resulting_module;
            }
        }

2772
        let name = segments.last().unwrap().identifier.name;
2773
        let result = self.resolve_name_in_module(containing_module, name, namespace, false, true);
2774 2775 2776
        result.success().map(|binding| {
            self.check_privacy(containing_module, name, binding, span);
            binding.def().unwrap()
2777
        }).ok_or(false)
2778 2779
    }

2780 2781
    /// Invariant: This must be called only during main resolution, not during
    /// import resolution.
F
Felix S. Klock II 已提交
2782
    fn resolve_crate_relative_path(&mut self,
2783
                                   span: Span,
2784
                                   segments: &[hir::PathSegment],
2785
                                   namespace: Namespace)
2786
                                   -> Result<Def, bool /* true if an error was reported */> {
C
corentih 已提交
2787 2788 2789 2790 2791 2792
        let module_path = segments.split_last()
                                  .unwrap()
                                  .1
                                  .iter()
                                  .map(|ps| ps.identifier.name)
                                  .collect::<Vec<_>>();
2793

2794
        let root_module = self.graph_root;
2795

2796
        let containing_module;
2797
        match self.resolve_module_path_from_root(root_module,
2798
                                                 &module_path,
2799
                                                 0,
J
Jeffrey Seyfried 已提交
2800
                                                 span) {
2801 2802 2803 2804 2805
            Failed(err) => {
                let (span, msg) = match err {
                    Some((span, msg)) => (span, msg),
                    None => {
                        let msg = format!("Use of undeclared module `::{}`",
2806
                                          names_to_string(&module_path));
2807
                        (span, msg)
2808 2809 2810
                    }
                };

J
Jonas Schievink 已提交
2811
                resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
2812
                return Err(true);
2813 2814
            }

2815
            Indeterminate => return Err(false),
2816

J
Jeffrey Seyfried 已提交
2817
            Success(resulting_module) => {
2818 2819 2820 2821
                containing_module = resulting_module;
            }
        }

2822
        let name = segments.last().unwrap().identifier.name;
J
Jeffrey Seyfried 已提交
2823
        let result = self.resolve_name_in_module(containing_module, name, namespace, false, true);
2824 2825 2826
        result.success().map(|binding| {
            self.check_privacy(containing_module, name, binding, span);
            binding.def().unwrap()
2827
        }).ok_or(false)
2828 2829
    }

C
corentih 已提交
2830 2831
    fn with_no_errors<T, F>(&mut self, f: F) -> T
        where F: FnOnce(&mut Resolver) -> T
J
Jorge Aparicio 已提交
2832
    {
2833
        self.emit_errors = false;
A
Alex Crichton 已提交
2834
        let rs = f(self);
2835 2836 2837 2838
        self.emit_errors = true;
        rs
    }

2839
    fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
C
corentih 已提交
2840 2841 2842
        fn extract_path_and_node_id(t: &Ty,
                                    allow: FallbackChecks)
                                    -> Option<(Path, NodeId, FallbackChecks)> {
2843
            match t.node {
2844
                TyPath(None, ref path) => Some((path.clone(), t.id, allow)),
J
Jonas Schievink 已提交
2845 2846
                TyPtr(ref mut_ty) => extract_path_and_node_id(&mut_ty.ty, OnlyTraitAndStatics),
                TyRptr(_, ref mut_ty) => extract_path_and_node_id(&mut_ty.ty, allow),
2847 2848 2849 2850 2851 2852 2853
                // 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,
            }
        }

2854 2855 2856 2857
        fn get_module<'a, 'tcx>(this: &mut Resolver<'a, 'tcx>,
                                span: Span,
                                name_path: &[ast::Name])
                                -> Option<Module<'a>> {
2858
            let last_name = name_path.last().unwrap();
2859

2860
            if name_path.len() == 1 {
2861
                match this.primitive_type_table.primitive_types.get(last_name) {
2862
                    Some(_) => None,
2863
                    None => this.current_module.resolve_name_in_lexical_scope(*last_name, TypeNS)
2864
                                               .and_then(NameBinding::module)
2865 2866
                }
            } else {
2867
                this.resolve_module_path(&name_path, UseLexicalScope, span).success()
2868 2869 2870
            }
        }

2871
        fn is_static_method(this: &Resolver, did: DefId) -> bool {
2872 2873
            if let Some(node_id) = this.ast_map.as_local_node_id(did) {
                let sig = match this.ast_map.get(node_id) {
2874 2875
                    hir_map::NodeTraitItem(trait_item) => match trait_item.node {
                        hir::MethodTraitItem(ref sig, _) => sig,
C
corentih 已提交
2876
                        _ => return false,
2877
                    },
2878
                    hir_map::NodeImplItem(impl_item) => match impl_item.node {
2879
                        hir::ImplItemKind::Method(ref sig, _) => sig,
C
corentih 已提交
2880
                        _ => return false,
2881
                    },
C
corentih 已提交
2882
                    _ => return false,
2883
                };
2884
                sig.explicit_self.node == hir::SelfStatic
2885
            } else {
2886
                this.session.cstore.is_static_method(did)
2887 2888 2889
            }
        }

2890 2891 2892 2893
        let (path, node_id, allowed) = match self.current_self_type {
            Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
                Some(x) => x,
                None => return NoSuggestion,
2894 2895 2896 2897
            },
            None => return NoSuggestion,
        };

2898 2899
        if allowed == Everything {
            // Look for a field with the same name in the current self_type.
2900
            match self.def_map.borrow().get(&node_id).map(|d| d.full_def()) {
2901 2902 2903 2904
                Some(Def::Enum(did)) |
                Some(Def::TyAlias(did)) |
                Some(Def::Struct(did)) |
                Some(Def::Variant(_, did)) => match self.structs.get(&did) {
2905 2906 2907 2908 2909
                    None => {}
                    Some(fields) => {
                        if fields.iter().any(|&field_name| name == field_name) {
                            return Field;
                        }
2910
                    }
2911 2912 2913
                },
                _ => {} // Self type didn't resolve properly
            }
2914 2915
        }

2916
        let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
2917 2918

        // Look for a method in the current self type's impl module.
2919
        if let Some(module) = get_module(self, path.span, &name_path) {
2920
            if let Some(binding) = module.resolve_name_in_lexical_scope(name, ValueNS) {
2921
                if let Some(Def::Method(did)) = binding.def() {
2922
                    if is_static_method(self, did) {
C
corentih 已提交
2923
                        return StaticMethod(path_names_to_string(&path, 0));
2924 2925 2926 2927 2928
                    }
                    if self.current_trait_ref.is_some() {
                        return TraitItem;
                    } else if allowed == Everything {
                        return Method;
2929 2930
                    }
                }
2931
            }
2932 2933 2934
        }

        // Look for a method in the current trait.
2935 2936 2937
        if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
            if let Some(&did) = self.trait_item_map.get(&(name, trait_did)) {
                if is_static_method(self, did) {
2938
                    return TraitMethod(path_names_to_string(&trait_ref.path, 0));
2939 2940
                } else {
                    return TraitItem;
2941 2942 2943 2944 2945 2946 2947
                }
            }
        }

        NoSuggestion
    }

2948
    fn find_best_match(&mut self, name: &str) -> SuggestionType {
2949
        if let Some(macro_name) = self.session.available_macros
2950
                                  .borrow().iter().find(|n| n.as_str() == name) {
2951 2952 2953
            return SuggestionType::Macro(format!("{}!", macro_name));
        }

2954 2955 2956 2957
        let names = self.value_ribs
                    .iter()
                    .rev()
                    .flat_map(|rib| rib.bindings.keys());
2958

2959
        if let Some(found) = find_best_match_for_name(names, name, None) {
J
Jonas Schievink 已提交
2960
            if name != found {
2961
                return SuggestionType::Function(found);
2962
            }
2963
        } SuggestionType::NotFound
2964 2965
    }

E
Eduard Burtescu 已提交
2966
    fn resolve_expr(&mut self, expr: &Expr) {
P
Patrick Walton 已提交
2967 2968
        // First, record candidate traits for this expression if it could
        // result in the invocation of a method call.
2969 2970 2971

        self.record_candidate_traits_for_expr_if_necessary(expr);

2972
        // Next, resolve the node.
2973
        match expr.node {
2974
            ExprPath(ref maybe_qself, ref path) => {
C
corentih 已提交
2975 2976 2977
                let resolution = match self.resolve_possibly_assoc_item(expr.id,
                                                                        maybe_qself.as_ref(),
                                                                        path,
J
Jeffrey Seyfried 已提交
2978
                                                                        ValueNS) {
C
corentih 已提交
2979 2980 2981 2982 2983
                    // `<T>::a::b::c` is resolved by typeck alone.
                    TypecheckRequired => {
                        let method_name = path.segments.last().unwrap().identifier.name;
                        let traits = self.get_traits_containing_item(method_name);
                        self.trait_map.insert(expr.id, traits);
2984
                        intravisit::walk_expr(self, expr);
C
corentih 已提交
2985 2986 2987 2988
                        return;
                    }
                    ResolveAttempt(resolution) => resolution,
                };
2989

2990 2991
                // This is a local path in the value namespace. Walk through
                // scopes looking for it.
2992
                if let Some(path_res) = resolution {
2993
                    // Check if struct variant
2994
                    let is_struct_variant = if let Def::Variant(_, variant_id) = path_res.base_def {
2995 2996 2997 2998 2999 3000
                        self.structs.contains_key(&variant_id)
                    } else {
                        false
                    };
                    if is_struct_variant {
                        let _ = self.structs.contains_key(&path_res.base_def.def_id());
3001
                        let path_name = path_names_to_string(path, 0);
3002

N
Nick Cameron 已提交
3003 3004
                        let mut err = resolve_struct_error(self,
                                        expr.span,
J
Jonas Schievink 已提交
3005
                                        ResolutionError::StructVariantUsedAsFunction(&path_name));
3006

C
corentih 已提交
3007
                        let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3008 3009
                                          path_name);
                        if self.emit_errors {
N
Nick Cameron 已提交
3010
                            err.fileline_help(expr.span, &msg);
3011
                        } else {
N
Nick Cameron 已提交
3012
                            err.span_help(expr.span, &msg);
3013
                        }
N
Nick Cameron 已提交
3014
                        err.emit();
3015
                        self.record_def(expr.id, err_path_resolution());
3016
                    } else {
3017
                        // Write the result into the def map.
3018
                        debug!("(resolving expr) resolved `{}`",
3019
                               path_names_to_string(path, 0));
3020

3021 3022
                        // Partial resolutions will need the set of traits in scope,
                        // so they can be completed during typeck.
3023
                        if path_res.depth != 0 {
3024
                            let method_name = path.segments.last().unwrap().identifier.name;
3025
                            let traits = self.get_traits_containing_item(method_name);
3026 3027 3028
                            self.trait_map.insert(expr.id, traits);
                        }

3029
                        self.record_def(expr.id, path_res);
3030
                    }
3031 3032 3033 3034 3035
                } else {
                    // Be helpful if the name refers to a struct
                    // (The pattern matching def_tys where the id is in self.structs
                    // matches on regular structs while excluding tuple- and enum-like
                    // structs, which wouldn't result in this error.)
3036
                    let path_name = path_names_to_string(path, 0);
3037
                    let type_res = self.with_no_errors(|this| {
J
Jeffrey Seyfried 已提交
3038
                        this.resolve_path(expr.id, path, 0, TypeNS)
3039
                    });
3040 3041

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

3043
                    if let Ok(Def::Struct(..)) = type_res.map(|r| r.base_def) {
J
Jeffrey Seyfried 已提交
3044 3045
                        let error_variant =
                            ResolutionError::StructVariantUsedAsFunction(&path_name);
3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061
                        let mut err = resolve_struct_error(self, expr.span, error_variant);

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

                        if self.emit_errors {
                            err.fileline_help(expr.span, &msg);
                        } else {
                            err.span_help(expr.span, &msg);
                        }
                        err.emit();
                    } else {
                        // Keep reporting some errors even if they're ignored above.
                        if let Err(true) = self.resolve_path(expr.id, path, 0, ValueNS) {
                            // `resolve_path` already reported the error
                        } else {
3062 3063 3064 3065 3066 3067 3068 3069 3070
                            let mut method_scope = false;
                            self.value_ribs.iter().rev().all(|rib| {
                                method_scope = match rib.kind {
                                    MethodRibKind => true,
                                    ItemRibKind | ConstantItemRibKind => false,
                                    _ => return true, // Keep advancing
                                };
                                false // Stop advancing
                            });
3071

3072
                            if method_scope && special_names::self_.as_str() == &path_name[..] {
C
corentih 已提交
3073 3074 3075
                                resolve_error(self,
                                              expr.span,
                                              ResolutionError::SelfNotAvailableInStaticMethod);
3076 3077 3078 3079 3080 3081
                            } else {
                                let last_name = path.segments.last().unwrap().identifier.name;
                                let mut msg = match self.find_fallback_in_self_type(last_name) {
                                    NoSuggestion => {
                                        // limit search to 5 to reduce the number
                                        // of stupid suggestions
3082
                                        match self.find_best_match(&path_name) {
3083 3084 3085 3086 3087 3088
                                            SuggestionType::Macro(s) => {
                                                format!("the macro `{}`", s)
                                            }
                                            SuggestionType::Function(s) => format!("`{}`", s),
                                            SuggestionType::NotFound => "".to_string(),
                                        }
3089 3090 3091
                                    }
                                    Field => format!("`self.{}`", path_name),
                                    Method |
C
corentih 已提交
3092
                                    TraitItem => format!("to call `self.{}`", path_name),
3093 3094
                                    TraitMethod(path_str) |
                                    StaticMethod(path_str) =>
C
corentih 已提交
3095
                                        format!("to call `{}::{}`", path_str, path_name),
3096 3097
                                };

3098
                                let mut context =  UnresolvedNameContext::Other;
3099
                                if !msg.is_empty() {
3100 3101 3102 3103 3104 3105 3106 3107
                                    msg = format!(". Did you mean {}?", msg);
                                } else {
                                    // we check if this a module and if so, we display a help
                                    // message
                                    let name_path = path.segments.iter()
                                                        .map(|seg| seg.identifier.name)
                                                        .collect::<Vec<_>>();

3108
                                    match self.resolve_module_path(&name_path[..],
J
Jeffrey Seyfried 已提交
3109 3110
                                                                   UseLexicalScope,
                                                                   expr.span) {
3111 3112 3113 3114 3115
                                        Success(_) => {
                                            context = UnresolvedNameContext::PathIsMod(expr.id);
                                        },
                                        _ => {},
                                    };
3116
                                }
3117

3118 3119
                                resolve_error(self,
                                              expr.span,
3120
                                              ResolutionError::UnresolvedName(
J
Jonas Schievink 已提交
3121
                                                  &path_name, &msg, context));
3122
                            }
V
Vincent Belliard 已提交
3123
                        }
3124 3125 3126
                    }
                }

3127
                intravisit::walk_expr(self, expr);
3128 3129
            }

3130
            ExprStruct(ref path, _, _) => {
3131 3132 3133
                // Resolve the path to the structure it goes to. We don't
                // check to ensure that the path is actually a structure; that
                // is checked later during typeck.
J
Jeffrey Seyfried 已提交
3134
                match self.resolve_path(expr.id, path, 0, TypeNS) {
3135 3136 3137
                    Ok(definition) => self.record_def(expr.id, definition),
                    Err(true) => self.record_def(expr.id, err_path_resolution()),
                    Err(false) => {
3138
                        debug!("(resolving expression) didn't find struct def",);
3139

3140 3141
                        resolve_error(self,
                                      path.span,
3142
                                      ResolutionError::DoesNotNameAStruct(
J
Jonas Schievink 已提交
3143
                                                                &path_names_to_string(path, 0))
3144
                                     );
3145
                        self.record_def(expr.id, err_path_resolution());
3146 3147 3148
                    }
                }

3149
                intravisit::walk_expr(self, expr);
3150 3151
            }

P
Pythoner6 已提交
3152
            ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
3153
                self.with_label_rib(|this| {
3154
                    let def = Def::Label(expr.id);
3155

3156
                    {
3157
                        let rib = this.label_ribs.last_mut().unwrap();
3158
                        rib.bindings.insert(label.name, def);
3159
                    }
3160

3161
                    intravisit::walk_expr(this, expr);
3162
                })
3163 3164
            }

3165
            ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
3166
                match self.search_label(label.node.name) {
3167
                    None => {
3168
                        self.record_def(expr.id, err_path_resolution());
3169
                        resolve_error(self,
3170 3171
                                      label.span,
                                      ResolutionError::UndeclaredLabel(&label.node.name.as_str()))
3172
                    }
3173
                    Some(def @ Def::Label(_)) => {
3174
                        // Since this def is a label, it is never read.
C
corentih 已提交
3175 3176 3177 3178 3179
                        self.record_def(expr.id,
                                        PathResolution {
                                            base_def: def,
                                            depth: 0,
                                        })
3180 3181
                    }
                    Some(_) => {
3182
                        span_bug!(expr.span, "label wasn't mapped to a label def!")
3183 3184 3185 3186
                    }
                }
            }

B
Brian Anderson 已提交
3187
            _ => {
3188
                intravisit::walk_expr(self, expr);
3189 3190 3191 3192
            }
        }
    }

E
Eduard Burtescu 已提交
3193
    fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3194
        match expr.node {
3195
            ExprField(_, name) => {
3196 3197 3198 3199
                // 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.
3200
                let traits = self.get_traits_containing_item(name.node);
3201
                self.trait_map.insert(expr.id, traits);
3202
            }
3203
            ExprMethodCall(name, _, _) => {
C
corentih 已提交
3204
                debug!("(recording candidate traits for expr) recording traits for {}",
3205
                       expr.id);
3206
                let traits = self.get_traits_containing_item(name.node);
3207
                self.trait_map.insert(expr.id, traits);
3208
            }
3209
            _ => {
3210 3211 3212 3213 3214
                // Nothing to do.
            }
        }
    }

3215
    fn get_traits_containing_item(&mut self, name: Name) -> Vec<DefId> {
C
corentih 已提交
3216
        debug!("(getting traits containing item) looking for '{}'", name);
E
Eduard Burtescu 已提交
3217

C
corentih 已提交
3218
        fn add_trait_info(found_traits: &mut Vec<DefId>, trait_def_id: DefId, name: Name) {
3219
            debug!("(adding trait info) found trait {:?} for method '{}'",
C
corentih 已提交
3220 3221
                   trait_def_id,
                   name);
E
Eduard Burtescu 已提交
3222 3223
            found_traits.push(trait_def_id);
        }
3224

3225
        let mut found_traits = Vec::new();
J
Jeffrey Seyfried 已提交
3226 3227 3228 3229
        // 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)) {
                add_trait_info(&mut found_traits, trait_def_id, name);
E
Eduard Burtescu 已提交
3230
            }
J
Jeffrey Seyfried 已提交
3231
        }
3232

J
Jeffrey Seyfried 已提交
3233 3234
        let mut search_module = self.current_module;
        loop {
E
Eduard Burtescu 已提交
3235
            // Look for trait children.
3236
            let mut search_in_module = |module: Module<'a>| module.for_each_child(|_, ns, binding| {
3237
                if ns != TypeNS { return }
3238
                let trait_def_id = match binding.def() {
3239
                    Some(Def::Trait(trait_def_id)) => trait_def_id,
3240
                    Some(..) | None => return,
3241 3242 3243
                };
                if self.trait_item_map.contains_key(&(name, trait_def_id)) {
                    add_trait_info(&mut found_traits, trait_def_id, name);
3244
                    let trait_name = self.get_trait_name(trait_def_id);
3245 3246
                    self.record_use(trait_name, TypeNS, binding);
                }
3247 3248
            });
            search_in_module(search_module);
3249

3250
            match search_module.parent_link {
3251 3252 3253 3254
                NoParentLink | ModuleParentLink(..) => {
                    search_module.prelude.borrow().map(search_in_module);
                    break;
                }
E
Eduard Burtescu 已提交
3255
                BlockParentLink(parent_module, _) => {
3256
                    search_module = parent_module;
3257
                }
E
Eduard Burtescu 已提交
3258
            }
3259 3260
        }

E
Eduard Burtescu 已提交
3261
        found_traits
3262 3263
    }

3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283
    /// 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() {
3284
            self.populate_module_if_necessary(in_module);
3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338

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

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

                // collect results based on the filter function
                if let Some(def) = name_binding.def() {
                    if name == lookup_name && ns == namespace && filter_fn(def) {
                        // create the path
                        let ident = hir::Ident::from_name(name);
                        let params = PathParameters::none();
                        let segment = PathSegment {
                            identifier: ident,
                            parameters: params,
                        };
                        let span = name_binding.span.unwrap_or(syntax::codemap::DUMMY_SP);
                        let mut segms = path_segments.clone();
                        segms.push(segment);
                        let segms = HirVec::from_vec(segms);
                        let path = Path {
                            span: span,
                            global: true,
                            segments: segms,
                        };
                        // the entity is accessible in the following cases:
                        // 1. if it's defined in the same crate, it's always
                        // accessible (since private entities can be made public)
                        // 2. if it's defined in another crate, it's accessible
                        // only if both the module is public and the entity is
                        // declared as public (due to pruning, we don't explore
                        // outside crate private modules => no need to check this)
                        if !in_module_is_extern || name_binding.is_public() {
                            lookup_results.push(path);
                        }
                    }
                }

                // collect submodules to explore
                if let Some(module) = name_binding.module() {
                    // form the path
                    let path_segments = match module.parent_link {
                        NoParentLink => path_segments.clone(),
                        ModuleParentLink(_, name) => {
                            let mut paths = path_segments.clone();
                            let ident = hir::Ident::from_name(name);
                            let params = PathParameters::none();
                            let segm = PathSegment {
                                identifier: ident,
                                parameters: params,
                            };
                            paths.push(segm);
                            paths
                        }
3339
                        _ => bug!(),
3340 3341 3342 3343
                    };

                    if !in_module_is_extern || name_binding.is_public() {
                        // add the module to the lookup
3344
                        let is_extern = in_module_is_extern || name_binding.is_extern_crate();
3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356
                        worklist.push((module, path_segments, is_extern));
                    }
                }
            })
        }

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

3357 3358 3359 3360
    fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
        debug!("(recording def) recording {:?} for {}", resolution, node_id);
        if let Some(prev_res) = self.def_map.borrow_mut().insert(node_id, resolution) {
            let span = self.ast_map.opt_span(node_id).unwrap_or(codemap::DUMMY_SP);
3361 3362 3363 3364
            span_bug!(span,
                      "path resolved multiple times ({:?} before, {:?} now)",
                      prev_res,
                      resolution);
3365
        }
3366 3367
    }

F
Felix S. Klock II 已提交
3368
    fn enforce_default_binding_mode(&mut self,
C
corentih 已提交
3369 3370 3371
                                    pat: &Pat,
                                    pat_binding_mode: BindingMode,
                                    descr: &str) {
3372
        match pat_binding_mode {
3373
            BindByValue(_) => {}
A
Alex Crichton 已提交
3374
            BindByRef(..) => {
3375 3376
                resolve_error(self,
                              pat.span,
3377
                              ResolutionError::CannotUseRefBindingModeWith(descr));
3378 3379 3380
            }
        }
    }
3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411

    fn is_visible(&self, binding: &'a NameBinding<'a>, parent: Module<'a>) -> bool {
        binding.is_public() || parent.is_ancestor_of(self.current_module)
    }

    fn check_privacy(&mut self,
                     module: Module<'a>,
                     name: Name,
                     binding: &'a NameBinding<'a>,
                     span: Span) {
        if !self.is_visible(binding, module) {
            self.privacy_errors.push(PrivacyError(span, name, binding));
        }
    }

    fn report_privacy_errors(&self) {
        if self.privacy_errors.len() == 0 { return }
        let mut reported_spans = HashSet::new();
        for &PrivacyError(span, name, binding) in &self.privacy_errors {
            if !reported_spans.insert(span) { continue }
            if binding.is_extern_crate() {
                // Warn when using an inaccessible extern crate.
                let node_id = binding.module().unwrap().extern_crate_id.unwrap();
                let msg = format!("extern crate `{}` is private", name);
                self.session.add_lint(lint::builtin::INACCESSIBLE_EXTERN_CRATE, node_id, span, msg);
            } else {
                let def = binding.def().unwrap();
                self.session.span_err(span, &format!("{} `{}` is private", def.kind_name(), name));
            }
        }
    }
3412

3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467
    fn report_conflict(&self,
                       parent: Module,
                       name: Name,
                       ns: Namespace,
                       binding: &NameBinding,
                       old_binding: &NameBinding) {
        // Error on the second of two conflicting names
        if old_binding.span.unwrap().lo > binding.span.unwrap().lo {
            return self.report_conflict(parent, name, ns, old_binding, binding);
        }

        let container = match parent.def {
            Some(Def::Mod(_)) => "module",
            Some(Def::Trait(_)) => "trait",
            None => "block",
            _ => "enum",
        };

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

        let span = binding.span.unwrap();
        let msg = {
            let kind = match (ns, old_binding.module()) {
                (ValueNS, _) => "a value",
                (TypeNS, Some(module)) if module.extern_crate_id.is_some() => "an extern crate",
                (TypeNS, Some(module)) if module.is_normal() => "a module",
                (TypeNS, Some(module)) if module.is_trait() => "a trait",
                (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()) {
            (true, true) => struct_span_err!(self.session, span, E0259, "{}", msg),
            (true, _) | (_, true) if binding.is_import() || old_binding.is_import() =>
                struct_span_err!(self.session, span, E0254, "{}", msg),
            (true, _) | (_, true) => struct_span_err!(self.session, span, E0260, "{}", msg),
            _ => match (old_binding.is_import(), binding.is_import()) {
                (false, false) => struct_span_err!(self.session, span, E0428, "{}", msg),
                (true, true) => struct_span_err!(self.session, span, E0252, "{}", msg),
                _ => struct_span_err!(self.session, span, E0255, "{}", msg),
            },
        };

        let span = old_binding.span.unwrap();
        if span != codemap::DUMMY_SP {
            err.span_note(span, &format!("previous {} of `{}` here", noun, name));
        }
        err.emit();
    }
}
3468 3469 3470 3471 3472 3473 3474 3475 3476 3477

fn names_to_string(names: &[Name]) -> String {
    let mut first = true;
    let mut result = String::new();
    for name in names {
        if first {
            first = false
        } else {
            result.push_str("::")
        }
3478
        result.push_str(&name.as_str());
C
corentih 已提交
3479
    }
3480 3481 3482 3483
    result
}

fn path_names_to_string(path: &Path, depth: usize) -> String {
C
corentih 已提交
3484
    let names: Vec<ast::Name> = path.segments[..path.segments.len() - depth]
3485 3486 3487 3488 3489 3490
                                    .iter()
                                    .map(|seg| seg.identifier.name)
                                    .collect();
    names_to_string(&names[..])
}

3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516
/// 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,
                   span: syntax::codemap::Span,
                   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 {
                session.fileline_help(
                    span,
T
tiehuis 已提交
3517
                    &format!("you can import it into scope: `use {};`.",
3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551
                        &path_strings[0]),
                );
            } else {
                session.fileline_help(span, "you can import several candidates \
                    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 {
                        session.fileline_help(
                            span,
                            &format!("  and {} other candidates", count).to_string(),
                        );
                        break;
                    } else {
                        session.fileline_help(
                            span,
                            &format!("  `{}`", path_string).to_string(),
                        );
                    }
                }
            }
        }
    } else {
        // nothing found:
        session.fileline_help(
            span,
            &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()),
        );
    };
}

3552
/// A somewhat inefficient routine to obtain the name of a module.
3553
fn module_to_string(module: Module) -> String {
3554 3555
    let mut names = Vec::new();

3556
    fn collect_mod(names: &mut Vec<ast::Name>, module: Module) {
3557 3558 3559 3560
        match module.parent_link {
            NoParentLink => {}
            ModuleParentLink(ref module, name) => {
                names.push(name);
3561
                collect_mod(names, module);
3562 3563 3564 3565
            }
            BlockParentLink(ref module, _) => {
                // danger, shouldn't be ident?
                names.push(special_idents::opaque.name);
3566
                collect_mod(names, module);
3567 3568 3569 3570 3571
            }
        }
    }
    collect_mod(&mut names, module);

3572
    if names.is_empty() {
3573 3574 3575 3576 3577
        return "???".to_string();
    }
    names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
}

3578 3579
fn err_path_resolution() -> PathResolution {
    PathResolution {
3580
        base_def: Def::Err,
3581 3582 3583 3584
        depth: 0,
    }
}

3585

3586
pub struct CrateMap {
J
Jonathan S 已提交
3587
    pub def_map: RefCell<DefMap>,
3588
    pub freevars: FreevarMap,
3589
    pub export_map: ExportMap,
3590
    pub trait_map: TraitMap,
C
corentih 已提交
3591
    pub glob_map: Option<GlobMap>,
3592 3593
}

N
Niko Matsakis 已提交
3594
#[derive(PartialEq,Copy, Clone)]
3595 3596
pub enum MakeGlobMap {
    Yes,
C
corentih 已提交
3597
    No,
3598 3599
}

3600
/// Entry point to crate resolution.
3601
pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
3602
                               ast_map: &'a hir_map::Map<'tcx>,
3603 3604
                               make_glob_map: MakeGlobMap)
                               -> CrateMap {
3605 3606 3607 3608 3609 3610 3611 3612 3613
    // Currently, we ignore the name resolution data structures for
    // the purposes of dependency tracking. Instead we will run name
    // resolution and include its output in the hash of each item,
    // much like we do for macro expansion. In other words, the hash
    // reflects not just its contents but the results of name
    // resolution on those contents. Hopefully we'll push this back at
    // some point.
    let _task = ast_map.dep_graph.in_task(DepNode::Resolve);

3614
    let krate = ast_map.krate();
3615 3616
    let arenas = Resolver::arenas();
    let mut resolver = create_resolver(session, ast_map, krate, make_glob_map, &arenas, None);
3617 3618 3619 3620

    resolver.resolve_crate(krate);

    check_unused::check_crate(&mut resolver, krate);
3621
    resolver.report_privacy_errors();
3622

3623
    CrateMap {
3624 3625
        def_map: resolver.def_map,
        freevars: resolver.freevars,
3626
        export_map: resolver.export_map,
3627
        trait_map: resolver.trait_map,
3628
        glob_map: if resolver.make_glob_map {
C
corentih 已提交
3629 3630 3631 3632
            Some(resolver.glob_map)
        } else {
            None
        },
3633
    }
3634
}
3635

3636 3637 3638 3639 3640 3641 3642 3643
/// Builds a name resolution walker to be used within this module,
/// or used externally, with an optional callback function.
///
/// The callback takes a &mut bool which allows callbacks to end a
/// walk when set to true, passing through the rest of the walk, while
/// preserving the ribs + current module. This allows resolve_path
/// calls to be made with the correct scope info. The node in the
/// callback corresponds to the current node in the walk.
J
Jeffrey Seyfried 已提交
3644 3645 3646 3647 3648 3649 3650
fn create_resolver<'a, 'tcx>(session: &'a Session,
                             ast_map: &'a hir_map::Map<'tcx>,
                             krate: &'a Crate,
                             make_glob_map: MakeGlobMap,
                             arenas: &'a ResolverArenas<'a>,
                             callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>)
                             -> Resolver<'a, 'tcx> {
3651
    let mut resolver = Resolver::new(session, ast_map, make_glob_map, arenas);
G
Garming Sam 已提交
3652 3653 3654

    resolver.callback = callback;

J
Jeffrey Seyfried 已提交
3655
    resolver.build_reduced_graph(krate);
G
Garming Sam 已提交
3656 3657 3658 3659 3660 3661

    resolve_imports::resolve_imports(&mut resolver);

    resolver
}

3662
__build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }