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

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

T
Fallout  
Tamir Duberstein 已提交
20
#![feature(associated_consts)]
21
#![feature(borrow_state)]
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
extern crate rustc_front;
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::front::map as hir_map;
52 53
use rustc::session::Session;
use rustc::lint;
54
use rustc::middle::cstore::CrateStore;
55
use rustc::middle::def::*;
56
use rustc::middle::def_id::DefId;
57
use rustc::middle::pat_util::pat_bindings;
58
use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
59
use rustc::middle::ty::{Freevar, FreevarMap, TraitMap, GlobMap};
60
use rustc::util::nodemap::{NodeMap, FnvHashMap};
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
use rustc_front::intravisit::{self, FnKind, Visitor};
71 72
use rustc_front::hir;
use rustc_front::hir::{Arm, BindByRef, BindByValue, BindingMode, Block};
73
use rustc_front::hir::Crate;
74
use rustc_front::hir::{Expr, ExprAgain, ExprBreak, ExprCall, ExprField};
75 76 77 78 79 80
use rustc_front::hir::{ExprLoop, ExprWhile, ExprMethodCall};
use rustc_front::hir::{ExprPath, ExprStruct, FnDecl};
use rustc_front::hir::{ForeignItemFn, ForeignItemStatic, Generics};
use rustc_front::hir::{ImplItem, Item, ItemConst, ItemEnum, ItemExternCrate};
use rustc_front::hir::{ItemFn, ItemForeignMod, ItemImpl, ItemMod, ItemStatic, ItemDefaultImpl};
use rustc_front::hir::{ItemStruct, ItemTrait, ItemTy, ItemUse};
81
use rustc_front::hir::Local;
82
use rustc_front::hir::{Pat, PatKind, Path, PrimTy};
83 84
use rustc_front::hir::{PathSegment, PathParameters};
use rustc_front::hir::HirVec;
85 86
use rustc_front::hir::{TraitRef, Ty, TyBool, TyChar, TyFloat, TyInt};
use rustc_front::hir::{TyRptr, TyStr, TyUint, TyPath, TyPtr};
87
use rustc_front::util::walk_pat;
88

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

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

96 97 98 99
// NB: This module needs to be declared first so diagnostics are
// registered before they are used.
pub mod diagnostics;

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

104 105 106 107 108 109 110 111 112 113 114
// 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;
            }
        }
    )
}

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

121 122 123 124 125 126
/// Candidates for a name resolution failure
pub struct SuggestedCandidates {
    name: String,
    candidates: Vec<Path>,
}

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

202
/// Context of where `ResolutionError::UnresolvedName` arose.
203 204
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum UnresolvedNameContext {
205 206 207 208
    /// `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.
209
    PathIsMod(ast::NodeId),
210 211 212 213

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

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

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 已提交
226
                                              -> DiagnosticBuilder<'a> {
227
    if !resolver.emit_errors {
N
Nick Cameron 已提交
228
        return resolver.session.diagnostic().struct_dummy();
229
    }
N
Nick Cameron 已提交
230

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

            match context {
440
                UnresolvedNameContext::Other => { } // no help available
441 442 443 444 445 446 447 448 449
                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 已提交
450
                                                   module = path,
451 452 453 454 455 456
                                                   ident = ident.node);
                            }
                            ExprMethodCall(ident, _, _) => {
                                help_msg = format!("To call a function from the \
                                                    `{module}` module, use \
                                                    `{module}::{ident}(..)`",
J
Jonas Schievink 已提交
457
                                                   module = path,
458 459
                                                   ident = ident.node);
                            }
460 461
                            ExprCall(_, _) => {
                                help_msg = format!("No function corresponds to `{module}(..)`",
J
Jonas Schievink 已提交
462
                                                   module = path);
463 464
                            }
                            _ => { } // no help available
465
                        }
466 467
                    } else {
                        help_msg = format!("Module `{module}` cannot be the value of an expression",
J
Jonas Schievink 已提交
468
                                           module = path);
469 470 471
                    }

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

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

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

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

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

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

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

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

655
#[derive(Clone, PartialEq, Eq)]
656
pub enum ResolveResult<T> {
C
corentih 已提交
657 658 659
    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.
660 661
}

662
impl<T> ResolveResult<T> {
663 664 665 666 667
    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 已提交
668
        }
669
    }
670 671 672 673 674 675 676

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

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

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

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

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

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

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

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

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

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

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

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

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

740 741 742 743 744 745 746 747 748
#[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 已提交
749
#[derive(Copy, Clone)]
F
Felix S. Klock II 已提交
750
enum BareIdentifierPatternResolution {
J
Jeffrey Seyfried 已提交
751 752
    FoundStructOrEnumVariant(Def),
    FoundConst(Def, Name),
C
corentih 已提交
753
    BareIdentifierPatternUnresolved,
754 755
}

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

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

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

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

787
/// The link from a module up to its nearest parent node.
J
Jorge Aparicio 已提交
788
#[derive(Clone,Debug)]
789
enum ParentLink<'a> {
790
    NoParentLink,
791 792
    ModuleParentLink(Module<'a>, Name),
    BlockParentLink(Module<'a>, NodeId),
793 794
}

795
/// One node in the tree of modules.
796 797
pub struct ModuleS<'a> {
    parent_link: ParentLink<'a>,
J
Jeffrey Seyfried 已提交
798
    def: Option<Def>,
799
    is_public: bool,
800

801 802 803
    // 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>,
804

805
    resolutions: RefCell<HashMap<(Name, Namespace), NameResolution<'a>>>,
806
    unresolved_imports: RefCell<Vec<&'a ImportDirective>>,
807

808 809 810
    // 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.
811 812 813 814 815 816 817 818 819 820 821
    //
    // 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`.
822
    module_children: RefCell<NodeMap<Module<'a>>>,
823

824
    prelude: RefCell<Option<Module<'a>>>,
825

826 827 828
    glob_importers: RefCell<Vec<(Module<'a>, &'a ImportDirective)>>,
    resolved_globs: RefCell<(Vec<Module<'a>> /* public */, Vec<Module<'a>> /* private */)>,

829 830
    // The number of public glob imports in this module.
    public_glob_count: Cell<usize>,
831

832 833
    // The number of private glob imports in this module.
    private_glob_count: Cell<usize>,
834

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

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

843 844 845
pub type Module<'a> = &'a ModuleS<'a>;

impl<'a> ModuleS<'a> {
846 847 848 849 850
    fn new(parent_link: ParentLink<'a>,
           def: Option<Def>,
           external: bool,
           is_public: bool,
           arenas: &'a ResolverArenas<'a>) -> Self {
851
        ModuleS {
852
            parent_link: parent_link,
J
Jeffrey Seyfried 已提交
853
            def: def,
854
            is_public: is_public,
855
            extern_crate_id: None,
856
            resolutions: RefCell::new(HashMap::new()),
857
            unresolved_imports: RefCell::new(Vec::new()),
858
            module_children: RefCell::new(NodeMap()),
859
            prelude: RefCell::new(None),
860 861
            glob_importers: RefCell::new(Vec::new()),
            resolved_globs: RefCell::new((Vec::new(), Vec::new())),
862 863
            public_glob_count: Cell::new(0),
            private_glob_count: Cell::new(0),
864
            populated: Cell::new(!external),
865
            arenas: arenas
866
        }
B
Brian Anderson 已提交
867 868
    }

869 870 871 872 873
    fn add_import_directive(&self, import_directive: ImportDirective) {
        let import_directive = self.arenas.alloc_import_directive(import_directive);
        self.unresolved_imports.borrow_mut().push(import_directive);
    }

874
    fn for_each_child<F: FnMut(Name, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
875
        for (&(name, ns), name_resolution) in self.resolutions.borrow().iter() {
876 877 878 879
            name_resolution.binding.map(|binding| f(name, ns, binding));
        }
    }

880
    fn def_id(&self) -> Option<DefId> {
J
Jeffrey Seyfried 已提交
881
        self.def.as_ref().map(Def::def_id)
882 883 884
    }

    fn is_normal(&self) -> bool {
J
Jeffrey Seyfried 已提交
885
        match self.def {
886
            Some(Def::Mod(_)) | Some(Def::ForeignMod(_)) => true,
887 888 889 890 891
            _ => false,
        }
    }

    fn is_trait(&self) -> bool {
J
Jeffrey Seyfried 已提交
892
        match self.def {
893
            Some(Def::Trait(_)) => true,
894
            _ => false,
895
        }
B
Brian Anderson 已提交
896 897
    }

898 899 900 901 902 903 904 905 906
    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,
        }
    }

907 908 909
    fn inc_glob_count(&self, is_public: bool) {
        let glob_count = if is_public { &self.public_glob_count } else { &self.private_glob_count };
        glob_count.set(glob_count.get() + 1);
V
Victor Berger 已提交
910 911 912
    }
}

913
impl<'a> fmt::Debug for ModuleS<'a> {
914
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
C
corentih 已提交
915
        write!(f,
916 917
               "{:?}, {}",
               self.def,
C
corentih 已提交
918 919 920 921 922
               if self.is_public {
                   "public"
               } else {
                   "private"
               })
923 924 925
    }
}

926
bitflags! {
J
Jorge Aparicio 已提交
927
    #[derive(Debug)]
928
    flags DefModifiers: u8 {
V
Vadim Petrochenkov 已提交
929 930
        // 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 已提交
931 932
        const PUBLIC     = 1 << 0,
        const IMPORTABLE = 1 << 1,
V
Vadim Petrochenkov 已提交
933
        // Variants are considered `PUBLIC`, but some of them live in private enums.
934 935
        // We need to track them to prohibit reexports like `pub use PrivEnum::Variant`.
        const PRIVATE_VARIANT = 1 << 2,
936
        const GLOB_IMPORTED = 1 << 3,
937 938 939
    }
}

940
// Records a possibly-private value, type, or module definition.
941
#[derive(Clone, Debug)]
942
pub struct NameBinding<'a> {
943 944
    modifiers: DefModifiers,
    kind: NameBindingKind<'a>,
945
    span: Option<Span>,
946 947
}

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

960 961 962
#[derive(Clone, Debug)]
struct PrivacyError<'a>(Span, Name, &'a NameBinding<'a>);

963
impl<'a> NameBinding<'a> {
964
    fn create_from_module(module: Module<'a>, span: Option<Span>) -> Self {
965
        let modifiers = if module.is_public {
T
Fallout  
Tamir Duberstein 已提交
966 967 968 969
            DefModifiers::PUBLIC
        } else {
            DefModifiers::empty()
        } | DefModifiers::IMPORTABLE;
970

971
        NameBinding { modifiers: modifiers, kind: NameBindingKind::Module(module), span: span }
972 973
    }

974
    fn module(&self) -> Option<Module<'a>> {
975 976 977 978
        match self.kind {
            NameBindingKind::Module(module) => Some(module),
            NameBindingKind::Def(_) => None,
            NameBindingKind::Import { binding, .. } => binding.module(),
979 980 981
        }
    }

982
    fn def(&self) -> Option<Def> {
983 984 985 986
        match self.kind {
            NameBindingKind::Def(def) => Some(def),
            NameBindingKind::Module(module) => module.def,
            NameBindingKind::Import { binding, .. } => binding.def(),
987
        }
988
    }
989

990
    fn defined_with(&self, modifiers: DefModifiers) -> bool {
991
        self.modifiers.contains(modifiers)
992 993 994 995 996 997
    }

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

998
    fn is_extern_crate(&self) -> bool {
999
        self.module().and_then(|module| module.extern_crate_id).is_some()
1000
    }
1001 1002 1003 1004 1005 1006 1007

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

1010
/// Interns the names of the primitive types.
F
Felix S. Klock II 已提交
1011
struct PrimitiveTypeTable {
1012
    primitive_types: HashMap<Name, PrimTy>,
1013
}
1014

1015
impl PrimitiveTypeTable {
K
Kevin Butler 已提交
1016
    fn new() -> PrimitiveTypeTable {
C
corentih 已提交
1017 1018 1019 1020
        let mut table = PrimitiveTypeTable { primitive_types: HashMap::new() };

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

        table
    }

1038
    fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1039
        self.primitive_types.insert(token::intern(string), primitive_type);
1040 1041 1042
    }
}

1043
/// The main resolver class.
C
corentih 已提交
1044
pub struct Resolver<'a, 'tcx: 'a> {
E
Eduard Burtescu 已提交
1045
    session: &'a Session,
1046

1047
    ast_map: &'a hir_map::Map<'tcx>,
1048

1049
    graph_root: Module<'a>,
1050

1051
    trait_item_map: FnvHashMap<(Name, DefId), DefId>,
1052

1053
    structs: FnvHashMap<DefId, Vec<Name>>,
1054

1055
    // The number of imports that are currently unresolved.
1056
    unresolved_imports: usize,
1057 1058

    // The module that represents the current item scope.
1059
    current_module: Module<'a>,
1060 1061

    // The current set of local scopes, for values.
1062
    // FIXME #4948: Reuse ribs to avoid allocation.
1063
    value_ribs: Vec<Rib<'a>>,
1064 1065

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

1068
    // The current set of local scopes, for labels.
1069
    label_ribs: Vec<Rib<'a>>,
1070

1071
    // The trait that the current context can refer to.
1072 1073 1074 1075
    current_trait_ref: Option<(DefId, TraitRef)>,

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

1077
    // The idents for the primitive types.
E
Eduard Burtescu 已提交
1078
    primitive_type_table: PrimitiveTypeTable,
1079

J
Jonathan S 已提交
1080
    def_map: RefCell<DefMap>,
1081 1082
    freevars: FreevarMap,
    freevars_seen: NodeMap<NodeMap<usize>>,
1083
    export_map: ExportMap,
1084
    trait_map: TraitMap,
1085

1086 1087 1088 1089 1090
    // 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,

1091 1092 1093 1094 1095
    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,

1096
    used_imports: HashSet<(NodeId, Namespace)>,
1097
    used_crates: HashSet<CrateNum>,
G
Garming Sam 已提交
1098 1099

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

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

pub struct ResolverArenas<'a> {
    modules: arena::TypedArena<ModuleS<'a>>,
1111
    name_bindings: arena::TypedArena<NameBinding<'a>>,
1112 1113 1114 1115
    import_directives: arena::TypedArena<ImportDirective>,
}

impl<'a> ResolverArenas<'a> {
1116 1117 1118 1119 1120 1121
    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)
    }
1122 1123 1124
    fn alloc_import_directive(&'a self, import_directive: ImportDirective) -> &'a ImportDirective {
        self.import_directives.alloc(import_directive)
    }
1125 1126
}

1127
#[derive(PartialEq)]
S
Steven Fackler 已提交
1128 1129
enum FallbackChecks {
    Everything,
C
corentih 已提交
1130
    OnlyTraitAndStatics,
S
Steven Fackler 已提交
1131 1132
}

1133 1134
impl<'a, 'tcx> Resolver<'a, 'tcx> {
    fn new(session: &'a Session,
1135
           ast_map: &'a hir_map::Map<'tcx>,
1136 1137
           make_glob_map: MakeGlobMap,
           arenas: &'a ResolverArenas<'a>)
C
corentih 已提交
1138
           -> Resolver<'a, 'tcx> {
1139
        let root_def_id = ast_map.local_def_id(CRATE_NODE_ID);
1140 1141 1142
        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 已提交
1143 1144 1145 1146

        Resolver {
            session: session,

1147 1148
            ast_map: ast_map,

K
Kevin Butler 已提交
1149 1150
            // The outermost module has def ID 0; this is not reflected in the
            // AST.
1151
            graph_root: graph_root,
K
Kevin Butler 已提交
1152

1153 1154
            trait_item_map: FnvHashMap(),
            structs: FnvHashMap(),
K
Kevin Butler 已提交
1155 1156 1157

            unresolved_imports: 0,

1158
            current_module: graph_root,
1159 1160
            value_ribs: vec![Rib::new(ModuleRibKind(graph_root))],
            type_ribs: vec![Rib::new(ModuleRibKind(graph_root))],
1161
            label_ribs: Vec::new(),
K
Kevin Butler 已提交
1162 1163 1164 1165 1166 1167

            current_trait_ref: None,
            current_self_type: None,

            primitive_type_table: PrimitiveTypeTable::new(),

1168
            def_map: RefCell::new(NodeMap()),
1169 1170
            freevars: NodeMap(),
            freevars_seen: NodeMap(),
1171 1172
            export_map: NodeMap(),
            trait_map: NodeMap(),
K
Kevin Butler 已提交
1173
            used_imports: HashSet::new(),
1174
            used_crates: HashSet::new(),
K
Kevin Butler 已提交
1175 1176

            emit_errors: true,
1177 1178
            make_glob_map: make_glob_map == MakeGlobMap::Yes,
            glob_map: HashMap::new(),
G
Garming Sam 已提交
1179 1180 1181

            callback: None,
            resolved: false,
1182
            privacy_errors: Vec::new(),
1183 1184 1185 1186 1187 1188 1189 1190

            arenas: arenas,
        }
    }

    fn arenas() -> ResolverArenas<'a> {
        ResolverArenas {
            modules: arena::TypedArena::new(),
1191
            name_bindings: arena::TypedArena::new(),
1192
            import_directives: arena::TypedArena::new(),
K
Kevin Butler 已提交
1193 1194
        }
    }
1195

1196 1197 1198 1199 1200
    fn new_module(&self,
                  parent_link: ParentLink<'a>,
                  def: Option<Def>,
                  external: bool,
                  is_public: bool) -> Module<'a> {
1201
        self.arenas.alloc_module(ModuleS::new(parent_link, def, external, is_public, self.arenas))
1202 1203
    }

1204 1205 1206 1207
    fn new_extern_crate_module(&self,
                               parent_link: ParentLink<'a>,
                               def: Def,
                               is_public: bool,
1208
                               local_node_id: NodeId)
1209
                               -> Module<'a> {
1210
        let mut module = ModuleS::new(parent_link, Some(def), false, is_public, self.arenas);
1211
        module.extern_crate_id = Some(local_node_id);
1212 1213 1214
        self.arenas.modules.alloc(module)
    }

1215 1216 1217 1218
    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 }
    }

1219
    #[inline]
1220 1221 1222 1223 1224 1225
    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);
        }

1226 1227
        let (import_id, privacy_error) = match binding.kind {
            NameBindingKind::Import { id, ref privacy_error, .. } => (id, privacy_error),
1228 1229 1230
            _ => return,
        };

1231
        self.used_imports.insert((import_id, ns));
1232 1233 1234
        if let Some(error) = privacy_error.as_ref() {
            self.privacy_errors.push((**error).clone());
        }
1235

1236 1237 1238 1239
        if !self.make_glob_map {
            return;
        }
        if self.glob_map.contains_key(&import_id) {
1240
            self.glob_map.get_mut(&import_id).unwrap().insert(name);
1241 1242 1243 1244 1245 1246 1247 1248 1249
            return;
        }

        let mut new_set = HashSet::new();
        new_set.insert(name);
        self.glob_map.insert(import_id, new_set);
    }

    fn get_trait_name(&self, did: DefId) -> Name {
1250 1251
        if let Some(node_id) = self.ast_map.as_local_node_id(did) {
            self.ast_map.expect_item(node_id).name
1252
        } else {
1253
            self.session.cstore.item_name(did)
1254 1255 1256
        }
    }

1257
    /// Resolves the given module path from the given root `module_`.
F
Felix S. Klock II 已提交
1258
    fn resolve_module_path_from_root(&mut self,
1259
                                     module_: Module<'a>,
1260
                                     module_path: &[Name],
1261
                                     index: usize,
J
Jeffrey Seyfried 已提交
1262 1263
                                     span: Span)
                                     -> ResolveResult<Module<'a>> {
1264
        fn search_parent_externals(needle: Name, module: Module) -> Option<Module> {
1265 1266
            match module.resolve_name(needle, TypeNS, false) {
                Success(binding) if binding.is_extern_crate() => Some(module),
1267
                _ => match module.parent_link {
1268
                    ModuleParentLink(ref parent, _) => {
1269
                        search_parent_externals(needle, parent)
1270
                    }
C
corentih 已提交
1271 1272
                    _ => None,
                },
1273
            }
1274 1275
        }

1276
        let mut search_module = module_;
1277
        let mut index = index;
A
Alex Crichton 已提交
1278
        let module_path_len = module_path.len();
1279 1280 1281 1282 1283

        // 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 已提交
1284
            let name = module_path[index];
1285
            match self.resolve_name_in_module(search_module, name, TypeNS, false, true) {
1286
                Failed(None) => {
1287
                    let segment_name = name.as_str();
1288
                    let module_name = module_to_string(search_module);
1289
                    let mut span = span;
1290
                    let msg = if "???" == &module_name {
1291
                        span.hi = span.lo + Pos::from_usize(segment_name.len());
1292

C
corentih 已提交
1293
                        match search_parent_externals(name, &self.current_module) {
1294
                            Some(module) => {
1295
                                let path_str = names_to_string(module_path);
J
Jonas Schievink 已提交
1296 1297
                                let target_mod_str = module_to_string(&module);
                                let current_mod_str = module_to_string(&self.current_module);
1298 1299 1300 1301 1302 1303 1304

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

1305
                                format!("Did you mean `{}{}`?", prefix, path_str)
C
corentih 已提交
1306 1307
                            }
                            None => format!("Maybe a missing `extern crate {}`?", segment_name),
1308
                        }
1309
                    } else {
C
corentih 已提交
1310
                        format!("Could not find `{}` in `{}`", segment_name, module_name)
1311
                    };
1312

1313
                    return Failed(Some((span, msg)));
1314
                }
1315
                Failed(err) => return Failed(err),
B
Brian Anderson 已提交
1316
                Indeterminate => {
C
corentih 已提交
1317 1318 1319
                    debug!("(resolving module path for import) module resolution is \
                            indeterminate: {}",
                           name);
B
Brian Anderson 已提交
1320
                    return Indeterminate;
1321
                }
1322
                Success(binding) => {
1323 1324
                    // Check to see whether there are type bindings, and, if
                    // so, whether there is a module within.
J
Jeffrey Seyfried 已提交
1325
                    if let Some(module_def) = binding.module() {
1326
                        self.check_privacy(search_module, name, binding, span);
1327 1328 1329 1330
                        search_module = module_def;
                    } else {
                        let msg = format!("Not a module `{}`", name);
                        return Failed(Some((span, msg)));
1331 1332 1333 1334
                    }
                }
            }

T
Tim Chevalier 已提交
1335
            index += 1;
1336 1337
        }

J
Jeffrey Seyfried 已提交
1338
        return Success(search_module);
1339 1340
    }

1341 1342
    /// Attempts to resolve the module part of an import directive or path
    /// rooted at the given module.
1343 1344 1345
    ///
    /// On success, returns the resolved module, and the closest *private*
    /// module found to the destination when resolving this path.
F
Felix S. Klock II 已提交
1346
    fn resolve_module_path(&mut self,
1347
                           module_path: &[Name],
1348
                           use_lexical_scope: UseLexicalScopeFlag,
J
Jeffrey Seyfried 已提交
1349
                           span: Span)
J
Jeffrey Seyfried 已提交
1350
                           -> ResolveResult<Module<'a>> {
1351
        if module_path.len() == 0 {
J
Jeffrey Seyfried 已提交
1352
            return Success(self.graph_root) // Use the crate root
1353
        }
1354

1355
        debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1356
               names_to_string(module_path),
1357
               module_to_string(self.current_module));
1358

1359
        // Resolve the module prefix, if any.
1360
        let module_prefix_result = self.resolve_module_prefix(module_path);
1361

1362 1363
        let search_module;
        let start_index;
1364
        match module_prefix_result {
1365
            Failed(None) => {
1366
                let mpath = names_to_string(module_path);
1367
                let mpath = &mpath[..];
1368
                match mpath.rfind(':') {
C
Fix ICE  
Corey Richardson 已提交
1369
                    Some(idx) => {
1370
                        let msg = format!("Could not find `{}` in `{}`",
C
corentih 已提交
1371 1372 1373 1374
                                          // idx +- 1 to account for the
                                          // colons on either side
                                          &mpath[idx + 1..],
                                          &mpath[..idx - 1]);
1375
                        return Failed(Some((span, msg)));
C
corentih 已提交
1376
                    }
1377
                    None => {
C
corentih 已提交
1378
                        return Failed(None);
1379
                    }
1380
                }
1381
            }
1382
            Failed(err) => return Failed(err),
B
Brian Anderson 已提交
1383
            Indeterminate => {
C
corentih 已提交
1384
                debug!("(resolving module path for import) indeterminate; bailing");
B
Brian Anderson 已提交
1385
                return Indeterminate;
1386
            }
1387 1388 1389 1390 1391 1392 1393 1394
            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.
1395
                        search_module = self.graph_root;
1396 1397 1398 1399 1400 1401
                        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.
1402
                        match self.resolve_item_in_lexical_scope(module_path[0],
1403 1404
                                                                 TypeNS,
                                                                 true) {
1405
                            Failed(err) => return Failed(err),
1406
                            Indeterminate => {
C
corentih 已提交
1407
                                debug!("(resolving module path for import) indeterminate; bailing");
1408 1409
                                return Indeterminate;
                            }
1410
                            Success(binding) => match binding.module() {
1411 1412 1413 1414 1415
                                Some(containing_module) => {
                                    search_module = containing_module;
                                    start_index = 1;
                                }
                                None => return Failed(None),
1416 1417 1418 1419 1420
                            }
                        }
                    }
                }
            }
E
Eduard Burtescu 已提交
1421
            Success(PrefixFound(ref containing_module, index)) => {
1422
                search_module = containing_module;
1423
                start_index = index;
1424 1425 1426
            }
        }

1427 1428 1429
        self.resolve_module_path_from_root(search_module,
                                           module_path,
                                           start_index,
J
Jeffrey Seyfried 已提交
1430
                                           span)
1431 1432
    }

1433 1434 1435 1436 1437
    /// This function resolves `name` in `namespace` in the current lexical scope, returning
    /// Success(binding) if `name` resolves to an item, or Failed(None) if `name` does not resolve
    /// or resolves to a type parameter or local variable.
    /// n.b. `resolve_identifier_in_local_ribs` also resolves names in the current lexical scope.
    ///
1438 1439
    /// Invariant: This must only be called during main resolution, not during
    /// import resolution.
F
Felix S. Klock II 已提交
1440
    fn resolve_item_in_lexical_scope(&mut self,
1441
                                     name: Name,
1442 1443
                                     namespace: Namespace,
                                     record_used: bool)
1444
                                     -> ResolveResult<&'a NameBinding<'a>> {
1445
        // Walk backwards up the ribs in scope.
1446 1447
        for i in (0 .. self.get_ribs(namespace).len()).rev() {
            if let Some(_) = self.get_ribs(namespace)[i].bindings.get(&name).cloned() {
1448
                // The name resolves to a type parameter or local variable, so return Failed(None).
1449
                return Failed(None);
1450 1451
            }

1452 1453 1454 1455 1456 1457
            if let ModuleRibKind(module) = self.get_ribs(namespace)[i].kind {
                if let Success(binding) = self.resolve_name_in_module(module,
                                                                      name,
                                                                      namespace,
                                                                      true,
                                                                      record_used) {
1458
                    // The name resolves to an item.
1459
                    return Success(binding);
1460
                }
1461 1462
                // We can only see through anonymous modules
                if module.def.is_some() { return Failed(None); }
1463 1464
            }
        }
1465 1466

        Failed(None)
1467 1468
    }

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

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

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

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

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

        return Success(PrefixFound(containing_module, i));
1531 1532
    }

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

1545
        self.populate_module_if_necessary(module);
1546 1547 1548 1549 1550
        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| {
1551 1552
            if record_used {
                self.record_use(name, namespace, binding);
1553
            }
1554 1555
            Success(binding)
        })
1556 1557 1558 1559
    }

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

1576
    fn with_scope<F>(&mut self, id: NodeId, f: F)
C
corentih 已提交
1577
        where F: FnOnce(&mut Resolver)
J
Jorge Aparicio 已提交
1578
    {
1579 1580 1581 1582 1583
        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)));
1584

1585
            f(self);
1586

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

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

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

1619
        intravisit::walk_crate(self, krate);
1620 1621
    }

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

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

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

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

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

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

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

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

W
we 已提交
1707
            ItemUse(ref view_path) => {
1708
                match view_path.node {
1709 1710 1711 1712 1713 1714
                    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) {
J
Jeffrey Seyfried 已提交
1715 1716
                                Some(def) =>
                                    self.record_def(item.id, PathResolution::new(def, 0)),
1717 1718 1719 1720 1721
                                None => {
                                    resolve_error(self,
                                                  prefix.span,
                                                  ResolutionError::FailedToResolve(
                                                      &path_names_to_string(prefix, 0)));
1722
                                    self.record_def(item.id, err_path_resolution());
1723
                                }
1724 1725 1726 1727
                            }
                        }
                    }
                    _ => {}
W
we 已提交
1728 1729 1730
                }
            }

1731
            ItemExternCrate(_) => {
1732
                // do nothing, these are just around to be encoded
1733
            }
1734 1735 1736
        }
    }

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

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

1755
                    // plain insert (no renaming)
1756 1757 1758
                    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);
1759
                }
1760
                self.type_ribs.push(function_type_rib);
1761 1762
            }

B
Brian Anderson 已提交
1763
            NoTypeParameters => {
1764 1765 1766 1767
                // Nothing to do.
            }
        }

A
Alex Crichton 已提交
1768
        f(self);
1769

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

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

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

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

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

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

J
Jonas Schievink 已提交
1814
            self.visit_ty(&argument.ty);
1815

1816 1817
            debug!("(resolving function) recorded argument");
        }
1818
        intravisit::walk_fn_ret_ty(self, &declaration.output);
1819

1820
        // Resolve the function body.
1821
        self.visit_block(block);
1822

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

G
Garming Sam 已提交
1825 1826 1827 1828
        if !self.resolved {
            self.label_ribs.pop();
            self.value_ribs.pop();
        }
1829 1830
    }

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

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

            // 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);
1881
            Err(())
1882 1883 1884
        }
    }

1885 1886
    fn resolve_generics(&mut self, generics: &Generics) {
        for predicate in &generics.where_clause.predicates {
1887
            match predicate {
1888 1889 1890
                &hir::WherePredicate::BoundPredicate(_) |
                &hir::WherePredicate::RegionPredicate(_) => {}
                &hir::WherePredicate::EqPredicate(ref eq_pred) => {
J
Jeffrey Seyfried 已提交
1891
                    let path_res = self.resolve_path(eq_pred.id, &eq_pred.path, 0, TypeNS);
1892
                    if let Some(PathResolution { base_def: Def::TyParam(..), .. }) = path_res {
1893 1894
                        self.record_def(eq_pred.id, path_res.unwrap());
                    } else {
1895 1896
                        resolve_error(self,
                                      eq_pred.span,
1897
                                      ResolutionError::UndeclaredAssociatedType);
1898
                        self.record_def(eq_pred.id, err_path_resolution());
1899 1900
                    }
                }
1901 1902
            }
        }
1903
        intravisit::walk_generics(self, generics);
1904 1905
    }

1906 1907
    fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
        where F: FnOnce(&mut Resolver) -> T
J
Jorge Aparicio 已提交
1908
    {
1909 1910 1911 1912 1913 1914 1915
        // 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 已提交
1916
    fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
1917
        where F: FnOnce(&mut Resolver, Option<DefId>) -> T
J
Jorge Aparicio 已提交
1918
    {
1919
        let mut new_val = None;
1920
        let mut new_id = None;
E
Eduard Burtescu 已提交
1921
        if let Some(trait_ref) = opt_trait_ref {
1922
            if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
C
corentih 已提交
1923 1924
                                                               &trait_ref.path,
                                                               0) {
1925 1926 1927 1928
                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());
1929 1930
            } else {
                self.record_def(trait_ref.ref_id, err_path_resolution());
1931
            }
1932
            intravisit::walk_trait_ref(self, trait_ref);
1933
        }
1934
        let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
1935
        let result = f(self, new_id);
1936 1937 1938 1939
        self.current_trait_ref = original_trait_ref;
        result
    }

1940 1941 1942 1943 1944 1945 1946
    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;
1947
        self_type_rib.bindings.insert(name, self_def);
1948 1949
        self.type_ribs.push(self_type_rib);
        f(self);
G
Garming Sam 已提交
1950 1951 1952
        if !self.resolved {
            self.type_ribs.pop();
        }
1953 1954
    }

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

1969
            // Resolve the trait reference, if necessary.
1970
            this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
1971
                // Resolve the self type.
1972
                this.visit_ty(self_type);
1973

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

                                    // 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| {
2002
                                        intravisit::walk_impl_item(this, impl_item);
2003 2004
                                    });
                                }
2005
                                hir::ImplItemKind::Type(ref ty) => {
2006
                                    // If this is a trait impl, ensure the type
2007
                                    // exists in trait
V
Vadim Petrochenkov 已提交
2008
                                    this.check_trait_item(impl_item.name,
2009 2010
                                                          impl_item.span,
                                        |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
2011

2012 2013
                                    this.visit_ty(ty);
                                }
2014
                            }
2015
                        }
2016
                    });
2017 2018
                });
            });
2019
        });
2020 2021
    }

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

E
Eduard Burtescu 已提交
2035
    fn resolve_local(&mut self, local: &Local) {
2036
        // Resolve the type.
2037
        walk_list!(self, visit_ty, &local.ty);
2038

2039
        // Resolve the initializer.
2040
        walk_list!(self, visit_expr, &local.init);
2041 2042

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

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

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

2073
            for (&key, &binding_0) in &map_0 {
2074
                match map_i.get(&key) {
C
corentih 已提交
2075
                    None => {
2076
                        resolve_error(self,
C
corentih 已提交
2077 2078 2079 2080 2081 2082 2083 2084 2085 2086
                                      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));
                        }
2087
                    }
2088 2089 2090
                }
            }

2091
            for (&key, &binding) in &map_i {
2092
                if !map_0.contains_key(&key) {
2093 2094
                    resolve_error(self,
                                  binding.span,
C
corentih 已提交
2095
                                  ResolutionError::VariableNotBoundInParentPattern(key, i + 1));
2096 2097 2098
                }
            }
        }
2099 2100
    }

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

2104
        let mut bindings_list = HashMap::new();
2105
        for pattern in &arm.pats {
J
Jonas Schievink 已提交
2106
            self.resolve_pattern(&pattern, RefutableMode, &mut bindings_list);
2107 2108
        }

2109 2110 2111 2112
        // This has to happen *after* we determine which
        // pat_idents are variants
        self.check_consistent_bindings(arm);

2113
        walk_list!(self, visit_expr, &arm.guard);
J
Jonas Schievink 已提交
2114
        self.visit_expr(&arm.body);
2115

G
Garming Sam 已提交
2116 2117 2118
        if !self.resolved {
            self.value_ribs.pop();
        }
2119 2120
    }

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

        if let Some(anonymous_module) = anonymous_module {
            debug!("(resolving block) found anonymous module, moving down");
2130 2131
            self.value_ribs.push(Rib::new(ModuleRibKind(anonymous_module)));
            self.type_ribs.push(Rib::new(ModuleRibKind(anonymous_module)));
2132 2133 2134
            self.current_module = anonymous_module;
        } else {
            self.value_ribs.push(Rib::new(NormalRibKind));
2135 2136 2137
        }

        // Descend into the block.
2138
        intravisit::walk_block(self, block);
2139 2140

        // Move back up.
G
Garming Sam 已提交
2141
        if !self.resolved {
2142
            self.current_module = orig_module;
G
Garming Sam 已提交
2143
            self.value_ribs.pop();
2144 2145 2146
            if let Some(_) = anonymous_module {
                self.type_ribs.pop();
            }
G
Garming Sam 已提交
2147
        }
2148
        debug!("(resolving block) leaving block");
2149 2150
    }

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

                // This is a path in the type namespace. Walk through scopes
2168
                // looking for it.
2169
                match resolution {
B
Brian Anderson 已提交
2170
                    Some(def) => {
2171
                        // Write the result into the def map.
C
corentih 已提交
2172
                        debug!("(resolving type) writing resolution for `{}` (id {}) = {:?}",
2173
                               path_names_to_string(path, 0),
C
corentih 已提交
2174 2175
                               ty.id,
                               def);
2176
                        self.record_def(ty.id, def);
2177
                    }
B
Brian Anderson 已提交
2178
                    None => {
2179 2180
                        self.record_def(ty.id, err_path_resolution());

2181
                        // Keep reporting some errors even if they're ignored above.
J
Jeffrey Seyfried 已提交
2182
                        self.resolve_path(ty.id, path, 0, TypeNS);
2183

2184 2185 2186 2187
                        let kind = if maybe_qself.is_some() {
                            "associated type"
                        } else {
                            "type name"
2188
                        };
2189

2190
                        let self_type_name = special_idents::type_self.name;
C
corentih 已提交
2191 2192 2193 2194
                        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 已提交
2195
                        if is_invalid_self_type_name {
2196 2197
                            resolve_error(self,
                                          ty.span,
2198
                                          ResolutionError::SelfUsedOutsideImplOrTrait);
2199
                        } else {
2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226
                            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 已提交
2227
                        }
2228 2229
                    }
                }
2230
            }
2231
            _ => {}
2232
        }
2233
        // Resolve embedded types.
2234
        intravisit::walk_ty(self, ty);
2235 2236
    }

F
Felix S. Klock II 已提交
2237
    fn resolve_pattern(&mut self,
E
Eduard Burtescu 已提交
2238
                       pattern: &Pat,
2239 2240 2241
                       mode: PatternBindingMode,
                       // Maps idents to the node ID for the (outermost)
                       // pattern that binds them
2242
                       bindings_list: &mut HashMap<Name, NodeId>) {
2243
        let pat_id = pattern.id;
2244
        walk_pat(pattern, |pattern| {
2245
            match pattern.node {
2246 2247
                PatKind::Ident(binding_mode, ref path1, ref at_rhs) => {
                    // The meaning of PatKind::Ident with no type parameters
2248 2249 2250 2251
                    // 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
2252 2253 2254 2255
                    // 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();
2256

2257
                    let ident = path1.node;
2258
                    let renamed = ident.name;
2259

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

C
corentih 已提交
2266 2267 2268 2269 2270 2271 2272 2273
                            self.enforce_default_binding_mode(pattern,
                                                              binding_mode,
                                                              "an enum variant");
                            self.record_def(pattern.id,
                                            PathResolution {
                                                base_def: def,
                                                depth: 0,
                                            });
2274
                        }
A
Alex Crichton 已提交
2275
                        FoundStructOrEnumVariant(..) => {
2276
                            resolve_error(
2277
                                self,
2278
                                pattern.span,
2279
                                ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(
2280 2281
                                    renamed)
                            );
2282
                            self.record_def(pattern.id, err_path_resolution());
2283
                        }
J
Jeffrey Seyfried 已提交
2284
                        FoundConst(def, _) if const_ok => {
C
corentih 已提交
2285 2286 2287 2288 2289 2290 2291 2292
                            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,
                                            });
2293
                        }
J
Jeffrey Seyfried 已提交
2294
                        FoundConst(def, name) => {
2295
                            resolve_error(
2296 2297
                                self,
                                pattern.span,
M
Manish Goregaokar 已提交
2298 2299
                                ResolutionError::OnlyIrrefutablePatternsAllowedHere(def.def_id(),
                                                                                    name)
2300
                            );
2301
                            self.record_def(pattern.id, err_path_resolution());
2302
                        }
2303
                        BareIdentifierPatternUnresolved => {
C
corentih 已提交
2304
                            debug!("(resolving pattern) binding `{}`", renamed);
2305

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

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

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

                            // 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.)
2324 2325
                            if !bindings_list.contains_key(&renamed) {
                                let this = &mut *self;
2326
                                let last_rib = this.value_ribs.last_mut().unwrap();
2327
                                last_rib.bindings.insert(renamed, def);
2328
                                bindings_list.insert(renamed, pat_id);
2329
                            } else if mode == ArgumentIrrefutableMode &&
C
corentih 已提交
2330
                               bindings_list.contains_key(&renamed) {
2331 2332
                                // Forbid duplicate bindings in the same
                                // parameter list.
2333
                                resolve_error(
2334 2335
                                    self,
                                    pattern.span,
2336
                                    ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2337
                                        &ident.name.as_str())
2338
                                );
C
corentih 已提交
2339
                            } else if bindings_list.get(&renamed) == Some(&pat_id) {
2340 2341
                                // Then this is a duplicate variable in the
                                // same disjunction, which is an error.
2342
                                resolve_error(
2343 2344
                                    self,
                                    pattern.span,
2345
                                    ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2346
                                        &ident.name.as_str())
2347
                                );
2348
                            }
2349 2350
                            // Else, not bound in the same pattern: do
                            // nothing.
2351 2352 2353 2354
                        }
                    }
                }

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

2427
                PatKind::QPath(ref qself, ref path) => {
2428
                    // Associated constants only.
C
corentih 已提交
2429 2430 2431
                    let resolution = match self.resolve_possibly_assoc_item(pat_id,
                                                                            Some(qself),
                                                                            path,
J
Jeffrey Seyfried 已提交
2432
                                                                            ValueNS) {
C
corentih 已提交
2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443
                        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);
2444
                            intravisit::walk_pat(self, pattern);
C
corentih 已提交
2445 2446 2447 2448
                            return true;
                        }
                        ResolveAttempt(resolution) => resolution,
                    };
2449 2450 2451 2452
                    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.
2453
                            Def::AssociatedConst(..) => {
2454 2455
                                self.record_def(pattern.id, path_res);
                            }
2456
                            _ => {
2457
                                resolve_error(
2458 2459
                                    self,
                                    path.span,
2460
                                    ResolutionError::NotAnAssociatedConst(
2461
                                        &path.segments.last().unwrap().identifier.name.as_str()
2462 2463
                                    )
                                );
2464
                                self.record_def(pattern.id, err_path_resolution());
2465
                            }
2466
                        }
2467
                    } else {
C
corentih 已提交
2468 2469 2470 2471 2472 2473 2474 2475
                        resolve_error(self,
                                      path.span,
                                      ResolutionError::UnresolvedAssociatedConst(&path.segments
                                                                                      .last()
                                                                                      .unwrap()
                                                                                      .identifier
                                                                                      .name
                                                                                      .as_str()));
2476
                        self.record_def(pattern.id, err_path_resolution());
2477
                    }
2478
                    intravisit::walk_pat(self, pattern);
2479 2480
                }

2481
                PatKind::Struct(ref path, _, _) => {
J
Jeffrey Seyfried 已提交
2482
                    match self.resolve_path(pat_id, path, 0, TypeNS) {
2483
                        Some(definition) => {
2484 2485
                            self.record_def(pattern.id, definition);
                        }
2486
                        result => {
C
corentih 已提交
2487
                            debug!("(resolving pattern) didn't find struct def: {:?}", result);
2488 2489 2490
                            resolve_error(
                                self,
                                path.span,
2491
                                ResolutionError::DoesNotNameAStruct(
J
Jonas Schievink 已提交
2492
                                    &path_names_to_string(path, 0))
2493
                            );
2494
                            self.record_def(pattern.id, err_path_resolution());
2495 2496
                        }
                    }
2497
                    intravisit::walk_path(self, path);
2498 2499
                }

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

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

C
corentih 已提交
2512 2513 2514
    fn resolve_bare_identifier_pattern(&mut self,
                                       name: Name,
                                       span: Span)
E
Eduard Burtescu 已提交
2515
                                       -> BareIdentifierPatternResolution {
2516
        match self.resolve_item_in_lexical_scope(name, ValueNS, true) {
2517
            Success(binding) => {
C
corentih 已提交
2518 2519
                debug!("(resolve bare identifier pattern) succeeded in finding {} at {:?}",
                       name,
2520
                       binding);
J
Jeffrey Seyfried 已提交
2521
                match binding.def() {
B
Brian Anderson 已提交
2522
                    None => {
C
corentih 已提交
2523 2524
                        panic!("resolved name in the value namespace to a set of name bindings \
                                with no def?!");
2525
                    }
2526 2527 2528
                    // For the two success cases, this lookup can be
                    // considered as not having a private component because
                    // the lookup happened only within the current module.
2529
                    Some(def @ Def::Variant(..)) | Some(def @ Def::Struct(..)) => {
J
Jeffrey Seyfried 已提交
2530
                        return FoundStructOrEnumVariant(def);
2531
                    }
2532
                    Some(def @ Def::Const(..)) | Some(def @ Def::AssociatedConst(..)) => {
J
Jeffrey Seyfried 已提交
2533
                        return FoundConst(def, name);
2534
                    }
2535
                    Some(Def::Static(..)) => {
2536 2537
                        resolve_error(self, span, ResolutionError::StaticVariableReference);
                        return BareIdentifierPatternUnresolved;
2538
                    }
2539
                    _ => return BareIdentifierPatternUnresolved
2540 2541 2542
                }
            }

2543
            Indeterminate => return BareIdentifierPatternUnresolved,
2544 2545 2546
            Failed(err) => {
                match err {
                    Some((span, msg)) => {
J
Jonas Schievink 已提交
2547
                        resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
2548
                    }
C
corentih 已提交
2549
                    None => (),
2550
                }
2551

C
corentih 已提交
2552
                debug!("(resolve bare identifier pattern) failed to find {}", name);
2553
                return BareIdentifierPatternUnresolved;
2554 2555 2556 2557
            }
        }
    }

2558 2559 2560
    /// Handles paths that may refer to associated items
    fn resolve_possibly_assoc_item(&mut self,
                                   id: NodeId,
2561
                                   maybe_qself: Option<&hir::QSelf>,
2562
                                   path: &Path,
J
Jeffrey Seyfried 已提交
2563
                                   namespace: Namespace)
C
corentih 已提交
2564
                                   -> AssocItemResolveResult {
2565 2566
        let max_assoc_types;

2567
        match maybe_qself {
2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578
            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();
            }
2579 2580 2581
        }

        let mut resolution = self.with_no_errors(|this| {
J
Jeffrey Seyfried 已提交
2582
            this.resolve_path(id, path, 0, namespace)
2583 2584 2585 2586 2587 2588
        });
        for depth in 1..max_assoc_types {
            if resolution.is_some() {
                break;
            }
            self.with_no_errors(|this| {
J
Jeffrey Seyfried 已提交
2589
                resolution = this.resolve_path(id, path, depth, TypeNS);
2590 2591
            });
        }
2592
        if let Some(Def::Mod(_)) = resolution.map(|r| r.base_def) {
2593 2594 2595 2596 2597 2598
            // A module is not a valid type or value.
            resolution = None;
        }
        ResolveAttempt(resolution)
    }

2599 2600
    /// Skips `path_depth` trailing segments, which is also reflected in the
    /// returned value. See `middle::def::PathResolution` for more info.
G
Garming Sam 已提交
2601 2602 2603 2604
    pub fn resolve_path(&mut self,
                        id: NodeId,
                        path: &Path,
                        path_depth: usize,
J
Jeffrey Seyfried 已提交
2605
                        namespace: Namespace)
C
corentih 已提交
2606
                        -> Option<PathResolution> {
2607
        let span = path.span;
C
corentih 已提交
2608
        let segments = &path.segments[..path.segments.len() - path_depth];
2609

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

2612
        if path.global {
2613
            let def = self.resolve_crate_relative_path(span, segments, namespace);
2614
            return def.map(mk_res);
2615 2616
        }

2617
        // Try to find a path to an item in a module.
2618
        let last_ident = segments.last().unwrap().identifier;
V
Cleanup  
Vadim Petrochenkov 已提交
2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630
        // 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
            }
        };
2631

2632 2633 2634 2635 2636 2637 2638
        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 已提交
2639 2640
            //     u8::max_value() // OK, resolves to associated function <u8>::max_value,
            //                     // not to non-existent std::u8::max_value
2641 2642 2643 2644
            // }
            //
            // Such behavior is required for backward compatibility.
            // The same fallback is used when `a` resolves to nothing.
V
Cleanup  
Vadim Petrochenkov 已提交
2645 2646
            let unqualified_def = resolve_identifier_with_fallback(self, true);
            return unqualified_def.and_then(|def| self.adjust_local_def(def, span)).map(mk_res);
N
Nick Cameron 已提交
2647
        }
2648

V
Cleanup  
Vadim Petrochenkov 已提交
2649
        let unqualified_def = resolve_identifier_with_fallback(self, false);
N
Nick Cameron 已提交
2650 2651
        let def = self.resolve_module_relative_path(span, segments, namespace);
        match (def, unqualified_def) {
J
Jeffrey Seyfried 已提交
2652
            (Some(d), Some(ref ud)) if d == ud.def => {
N
Nick Cameron 已提交
2653 2654
                self.session
                    .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
C
corentih 已提交
2655 2656
                              id,
                              span,
N
Nick Cameron 已提交
2657 2658 2659
                              "unnecessary qualification".to_string());
            }
            _ => {}
2660
        }
N
Nick Cameron 已提交
2661 2662

        def.map(mk_res)
2663 2664
    }

2665
    // Resolve a single identifier
F
Felix S. Klock II 已提交
2666
    fn resolve_identifier(&mut self,
2667
                          identifier: hir::Ident,
2668
                          namespace: Namespace,
2669
                          record_used: bool)
2670
                          -> Option<LocalDef> {
2671
        if identifier.name == special_idents::invalid.name {
2672
            return Some(LocalDef::from_def(Def::Err));
2673 2674
        }

J
Jeffrey Seyfried 已提交
2675
        self.resolve_identifier_in_local_ribs(identifier, namespace, record_used)
2676 2677 2678
    }

    // Resolve a local definition, potentially adjusting for closures.
2679
    fn adjust_local_def(&mut self, local_def: LocalDef, span: Span) -> Option<Def> {
2680
        let ribs = match local_def.ribs {
C
corentih 已提交
2681 2682 2683
            Some((TypeNS, i)) => &self.type_ribs[i + 1..],
            Some((ValueNS, i)) => &self.value_ribs[i + 1..],
            _ => &[] as &[_],
2684 2685 2686
        };
        let mut def = local_def.def;
        match def {
2687
            Def::Upvar(..) => {
C
corentih 已提交
2688
                self.session.span_bug(span, &format!("unexpected {:?} in bindings", def))
2689
            }
2690
            Def::Local(_, node_id) => {
2691 2692
                for rib in ribs {
                    match rib.kind {
2693
                        NormalRibKind | ModuleRibKind(..) => {
2694 2695 2696 2697 2698 2699
                            // 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 已提交
2700 2701 2702
                            let seen = self.freevars_seen
                                           .entry(function_id)
                                           .or_insert_with(|| NodeMap());
2703
                            if let Some(&index) = seen.get(&node_id) {
2704
                                def = Def::Upvar(node_def_id, node_id, index, function_id);
2705 2706
                                continue;
                            }
C
corentih 已提交
2707 2708 2709
                            let vec = self.freevars
                                          .entry(function_id)
                                          .or_insert_with(|| vec![]);
2710
                            let depth = vec.len();
C
corentih 已提交
2711 2712 2713 2714
                            vec.push(Freevar {
                                def: prev_def,
                                span: span,
                            });
2715

2716
                            def = Def::Upvar(node_def_id, node_id, depth, function_id);
2717 2718 2719 2720 2721 2722
                            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 已提交
2723 2724 2725
                            resolve_error(self,
                                          span,
                                          ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
2726 2727 2728 2729
                            return None;
                        }
                        ConstantItemRibKind => {
                            // Still doesn't deal with upvars
C
corentih 已提交
2730 2731 2732
                            resolve_error(self,
                                          span,
                                          ResolutionError::AttemptToUseNonConstantValueInConstant);
2733 2734 2735 2736 2737
                            return None;
                        }
                    }
                }
            }
2738
            Def::TyParam(..) | Def::SelfTy(..) => {
2739 2740
                for rib in ribs {
                    match rib.kind {
2741
                        NormalRibKind | MethodRibKind | ClosureRibKind(..) |
2742
                        ModuleRibKind(..) => {
2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764
                            // 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);
2765 2766
    }

2767
    // resolve a "module-relative" path, e.g. a::b::c
F
Felix S. Klock II 已提交
2768
    fn resolve_module_relative_path(&mut self,
2769
                                    span: Span,
2770
                                    segments: &[hir::PathSegment],
2771
                                    namespace: Namespace)
J
Jeffrey Seyfried 已提交
2772
                                    -> Option<Def> {
C
corentih 已提交
2773 2774 2775 2776 2777 2778
        let module_path = segments.split_last()
                                  .unwrap()
                                  .1
                                  .iter()
                                  .map(|ps| ps.identifier.name)
                                  .collect::<Vec<_>>();
2779

2780
        let containing_module;
2781
        match self.resolve_module_path(&module_path, UseLexicalScope, span) {
2782 2783 2784 2785
            Failed(err) => {
                let (span, msg) = match err {
                    Some((span, msg)) => (span, msg),
                    None => {
2786
                        let msg = format!("Use of undeclared type or module `{}`",
2787
                                          names_to_string(&module_path));
2788
                        (span, msg)
2789 2790
                    }
                };
2791

J
Jonas Schievink 已提交
2792
                resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
2793
                return None;
2794
            }
2795
            Indeterminate => return None,
J
Jeffrey Seyfried 已提交
2796
            Success(resulting_module) => {
2797 2798 2799 2800
                containing_module = resulting_module;
            }
        }

2801
        let name = segments.last().unwrap().identifier.name;
2802
        let result = self.resolve_name_in_module(containing_module, name, namespace, false, true);
2803 2804 2805 2806
        result.success().map(|binding| {
            self.check_privacy(containing_module, name, binding, span);
            binding.def().unwrap()
        })
2807 2808
    }

2809 2810
    /// Invariant: This must be called only during main resolution, not during
    /// import resolution.
F
Felix S. Klock II 已提交
2811
    fn resolve_crate_relative_path(&mut self,
2812
                                   span: Span,
2813
                                   segments: &[hir::PathSegment],
2814
                                   namespace: Namespace)
J
Jeffrey Seyfried 已提交
2815
                                   -> Option<Def> {
C
corentih 已提交
2816 2817 2818 2819 2820 2821
        let module_path = segments.split_last()
                                  .unwrap()
                                  .1
                                  .iter()
                                  .map(|ps| ps.identifier.name)
                                  .collect::<Vec<_>>();
2822

2823
        let root_module = self.graph_root;
2824

2825
        let containing_module;
2826
        match self.resolve_module_path_from_root(root_module,
2827
                                                 &module_path,
2828
                                                 0,
J
Jeffrey Seyfried 已提交
2829
                                                 span) {
2830 2831 2832 2833 2834
            Failed(err) => {
                let (span, msg) = match err {
                    Some((span, msg)) => (span, msg),
                    None => {
                        let msg = format!("Use of undeclared module `::{}`",
2835
                                          names_to_string(&module_path));
2836
                        (span, msg)
2837 2838 2839
                    }
                };

J
Jonas Schievink 已提交
2840
                resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
B
Brian Anderson 已提交
2841
                return None;
2842 2843
            }

2844
            Indeterminate => return None,
2845

J
Jeffrey Seyfried 已提交
2846
            Success(resulting_module) => {
2847 2848 2849 2850
                containing_module = resulting_module;
            }
        }

2851
        let name = segments.last().unwrap().identifier.name;
J
Jeffrey Seyfried 已提交
2852
        let result = self.resolve_name_in_module(containing_module, name, namespace, false, true);
2853 2854 2855 2856
        result.success().map(|binding| {
            self.check_privacy(containing_module, name, binding, span);
            binding.def().unwrap()
        })
2857 2858
    }

F
Felix S. Klock II 已提交
2859
    fn resolve_identifier_in_local_ribs(&mut self,
2860
                                        ident: hir::Ident,
2861 2862
                                        namespace: Namespace,
                                        record_used: bool)
2863
                                        -> Option<LocalDef> {
2864
        // Check the local set of ribs.
2865
        let name = match namespace { ValueNS => ident.name, TypeNS => ident.unhygienic_name };
2866

2867
        for i in (0 .. self.get_ribs(namespace).len()).rev() {
2868 2869 2870 2871 2872
            if let Some(def) = self.get_ribs(namespace)[i].bindings.get(&name).cloned() {
                return Some(LocalDef {
                    ribs: Some((namespace, i)),
                    def: def,
                });
2873
            }
2874

2875
            if let ModuleRibKind(module) = self.get_ribs(namespace)[i].kind {
2876 2877 2878 2879
                if let Success(binding) = self.resolve_name_in_module(module,
                                                                      ident.unhygienic_name,
                                                                      namespace,
                                                                      true,
2880
                                                                      record_used) {
J
Jeffrey Seyfried 已提交
2881
                    if let Some(def) = binding.def() {
2882 2883 2884
                        return Some(LocalDef::from_def(def));
                    }
                }
2885 2886
                // We can only see through anonymous modules
                if module.def.is_some() { return None; }
2887
            }
2888
        }
2889 2890

        None
2891 2892
    }

C
corentih 已提交
2893 2894
    fn with_no_errors<T, F>(&mut self, f: F) -> T
        where F: FnOnce(&mut Resolver) -> T
J
Jorge Aparicio 已提交
2895
    {
2896
        self.emit_errors = false;
A
Alex Crichton 已提交
2897
        let rs = f(self);
2898 2899 2900 2901
        self.emit_errors = true;
        rs
    }

2902
    fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
C
corentih 已提交
2903 2904 2905
        fn extract_path_and_node_id(t: &Ty,
                                    allow: FallbackChecks)
                                    -> Option<(Path, NodeId, FallbackChecks)> {
2906
            match t.node {
2907
                TyPath(None, ref path) => Some((path.clone(), t.id, allow)),
J
Jonas Schievink 已提交
2908 2909
                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),
2910 2911 2912 2913 2914 2915 2916
                // 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,
            }
        }

2917 2918 2919 2920
        fn get_module<'a, 'tcx>(this: &mut Resolver<'a, 'tcx>,
                                span: Span,
                                name_path: &[ast::Name])
                                -> Option<Module<'a>> {
2921
            let last_name = name_path.last().unwrap();
2922

2923
            if name_path.len() == 1 {
2924
                match this.primitive_type_table.primitive_types.get(last_name) {
2925
                    Some(_) => None,
2926
                    None => this.current_module.resolve_name_in_lexical_scope(*last_name, TypeNS)
2927
                                               .and_then(NameBinding::module)
2928 2929
                }
            } else {
2930
                this.resolve_module_path(&name_path, UseLexicalScope, span).success()
2931 2932 2933
            }
        }

2934
        fn is_static_method(this: &Resolver, did: DefId) -> bool {
2935 2936
            if let Some(node_id) = this.ast_map.as_local_node_id(did) {
                let sig = match this.ast_map.get(node_id) {
2937 2938
                    hir_map::NodeTraitItem(trait_item) => match trait_item.node {
                        hir::MethodTraitItem(ref sig, _) => sig,
C
corentih 已提交
2939
                        _ => return false,
2940
                    },
2941
                    hir_map::NodeImplItem(impl_item) => match impl_item.node {
2942
                        hir::ImplItemKind::Method(ref sig, _) => sig,
C
corentih 已提交
2943
                        _ => return false,
2944
                    },
C
corentih 已提交
2945
                    _ => return false,
2946
                };
2947
                sig.explicit_self.node == hir::SelfStatic
2948
            } else {
2949
                this.session.cstore.is_static_method(did)
2950 2951 2952
            }
        }

2953 2954 2955 2956
        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,
2957 2958 2959 2960
            },
            None => return NoSuggestion,
        };

2961 2962
        if allowed == Everything {
            // Look for a field with the same name in the current self_type.
2963
            match self.def_map.borrow().get(&node_id).map(|d| d.full_def()) {
2964 2965 2966 2967
                Some(Def::Enum(did)) |
                Some(Def::TyAlias(did)) |
                Some(Def::Struct(did)) |
                Some(Def::Variant(_, did)) => match self.structs.get(&did) {
2968 2969 2970 2971 2972
                    None => {}
                    Some(fields) => {
                        if fields.iter().any(|&field_name| name == field_name) {
                            return Field;
                        }
2973
                    }
2974 2975 2976
                },
                _ => {} // Self type didn't resolve properly
            }
2977 2978
        }

2979
        let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
2980 2981

        // Look for a method in the current self type's impl module.
2982
        if let Some(module) = get_module(self, path.span, &name_path) {
2983
            if let Some(binding) = module.resolve_name_in_lexical_scope(name, ValueNS) {
2984
                if let Some(Def::Method(did)) = binding.def() {
2985
                    if is_static_method(self, did) {
C
corentih 已提交
2986
                        return StaticMethod(path_names_to_string(&path, 0));
2987 2988 2989 2990 2991
                    }
                    if self.current_trait_ref.is_some() {
                        return TraitItem;
                    } else if allowed == Everything {
                        return Method;
2992 2993
                    }
                }
2994
            }
2995 2996 2997
        }

        // Look for a method in the current trait.
2998 2999 3000
        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) {
3001
                    return TraitMethod(path_names_to_string(&trait_ref.path, 0));
3002 3003
                } else {
                    return TraitItem;
3004 3005 3006 3007 3008 3009 3010
                }
            }
        }

        NoSuggestion
    }

3011
    fn find_best_match(&mut self, name: &str) -> SuggestionType {
3012
        if let Some(macro_name) = self.session.available_macros
3013
                                  .borrow().iter().find(|n| n.as_str() == name) {
3014 3015 3016
            return SuggestionType::Macro(format!("{}!", macro_name));
        }

3017 3018 3019 3020
        let names = self.value_ribs
                    .iter()
                    .rev()
                    .flat_map(|rib| rib.bindings.keys());
3021

3022
        if let Some(found) = find_best_match_for_name(names, name, None) {
J
Jonas Schievink 已提交
3023
            if name != found {
3024
                return SuggestionType::Function(found);
3025
            }
3026
        } SuggestionType::NotFound
3027 3028
    }

E
Eduard Burtescu 已提交
3029
    fn resolve_expr(&mut self, expr: &Expr) {
P
Patrick Walton 已提交
3030 3031
        // First, record candidate traits for this expression if it could
        // result in the invocation of a method call.
3032 3033 3034

        self.record_candidate_traits_for_expr_if_necessary(expr);

3035
        // Next, resolve the node.
3036
        match expr.node {
3037
            ExprPath(ref maybe_qself, ref path) => {
C
corentih 已提交
3038 3039 3040
                let resolution = match self.resolve_possibly_assoc_item(expr.id,
                                                                        maybe_qself.as_ref(),
                                                                        path,
J
Jeffrey Seyfried 已提交
3041
                                                                        ValueNS) {
C
corentih 已提交
3042 3043 3044 3045 3046
                    // `<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);
3047
                        intravisit::walk_expr(self, expr);
C
corentih 已提交
3048 3049 3050 3051
                        return;
                    }
                    ResolveAttempt(resolution) => resolution,
                };
3052

3053 3054
                // This is a local path in the value namespace. Walk through
                // scopes looking for it.
3055
                if let Some(path_res) = resolution {
3056
                    // Check if struct variant
3057
                    let is_struct_variant = if let Def::Variant(_, variant_id) = path_res.base_def {
3058 3059 3060 3061 3062 3063
                        self.structs.contains_key(&variant_id)
                    } else {
                        false
                    };
                    if is_struct_variant {
                        let _ = self.structs.contains_key(&path_res.base_def.def_id());
3064
                        let path_name = path_names_to_string(path, 0);
3065

N
Nick Cameron 已提交
3066 3067
                        let mut err = resolve_struct_error(self,
                                        expr.span,
J
Jonas Schievink 已提交
3068
                                        ResolutionError::StructVariantUsedAsFunction(&path_name));
3069

C
corentih 已提交
3070
                        let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3071 3072
                                          path_name);
                        if self.emit_errors {
N
Nick Cameron 已提交
3073
                            err.fileline_help(expr.span, &msg);
3074
                        } else {
N
Nick Cameron 已提交
3075
                            err.span_help(expr.span, &msg);
3076
                        }
N
Nick Cameron 已提交
3077
                        err.emit();
3078
                        self.record_def(expr.id, err_path_resolution());
3079
                    } else {
3080
                        // Write the result into the def map.
3081
                        debug!("(resolving expr) resolved `{}`",
3082
                               path_names_to_string(path, 0));
3083

3084 3085
                        // Partial resolutions will need the set of traits in scope,
                        // so they can be completed during typeck.
3086
                        if path_res.depth != 0 {
3087
                            let method_name = path.segments.last().unwrap().identifier.name;
3088
                            let traits = self.get_traits_containing_item(method_name);
3089 3090 3091
                            self.trait_map.insert(expr.id, traits);
                        }

3092
                        self.record_def(expr.id, path_res);
3093
                    }
3094 3095 3096 3097 3098
                } 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.)
3099
                    let path_name = path_names_to_string(path, 0);
3100
                    let type_res = self.with_no_errors(|this| {
J
Jeffrey Seyfried 已提交
3101
                        this.resolve_path(expr.id, path, 0, TypeNS)
3102
                    });
3103 3104

                    self.record_def(expr.id, err_path_resolution());
3105
                    match type_res.map(|r| r.base_def) {
3106
                        Some(Def::Struct(..)) => {
N
Nick Cameron 已提交
3107 3108
                            let mut err = resolve_struct_error(self,
                                expr.span,
J
Jonas Schievink 已提交
3109
                                ResolutionError::StructVariantUsedAsFunction(&path_name));
3110

C
corentih 已提交
3111 3112 3113
                            let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
                                              path_name);
                            if self.emit_errors {
N
Nick Cameron 已提交
3114
                                err.fileline_help(expr.span, &msg);
C
corentih 已提交
3115
                            } else {
N
Nick Cameron 已提交
3116
                                err.span_help(expr.span, &msg);
3117
                            }
N
Nick Cameron 已提交
3118
                            err.emit();
C
corentih 已提交
3119
                        }
3120 3121
                        _ => {
                            // Keep reporting some errors even if they're ignored above.
J
Jeffrey Seyfried 已提交
3122
                            self.resolve_path(expr.id, path, 0, ValueNS);
3123 3124 3125 3126 3127 3128 3129 3130 3131 3132

                            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
                            });
3133

3134
                            if method_scope && special_names::self_.as_str() == &path_name[..] {
C
corentih 已提交
3135 3136 3137
                                resolve_error(self,
                                              expr.span,
                                              ResolutionError::SelfNotAvailableInStaticMethod);
3138 3139 3140 3141 3142 3143
                            } 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
3144
                                        match self.find_best_match(&path_name) {
3145 3146 3147 3148 3149 3150
                                            SuggestionType::Macro(s) => {
                                                format!("the macro `{}`", s)
                                            }
                                            SuggestionType::Function(s) => format!("`{}`", s),
                                            SuggestionType::NotFound => "".to_string(),
                                        }
3151 3152 3153
                                    }
                                    Field => format!("`self.{}`", path_name),
                                    Method |
C
corentih 已提交
3154
                                    TraitItem => format!("to call `self.{}`", path_name),
3155 3156
                                    TraitMethod(path_str) |
                                    StaticMethod(path_str) =>
C
corentih 已提交
3157
                                        format!("to call `{}::{}`", path_str, path_name),
3158 3159
                                };

3160
                                let mut context =  UnresolvedNameContext::Other;
3161
                                if !msg.is_empty() {
3162 3163 3164 3165 3166 3167 3168 3169
                                    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<_>>();

3170
                                    match self.resolve_module_path(&name_path[..],
J
Jeffrey Seyfried 已提交
3171 3172
                                                                   UseLexicalScope,
                                                                   expr.span) {
3173 3174 3175 3176 3177
                                        Success(_) => {
                                            context = UnresolvedNameContext::PathIsMod(expr.id);
                                        },
                                        _ => {},
                                    };
3178
                                }
3179

3180 3181
                                resolve_error(self,
                                              expr.span,
3182
                                              ResolutionError::UnresolvedName(
J
Jonas Schievink 已提交
3183
                                                  &path_name, &msg, context));
3184
                            }
V
Vincent Belliard 已提交
3185
                        }
3186 3187 3188
                    }
                }

3189
                intravisit::walk_expr(self, expr);
3190 3191
            }

3192
            ExprStruct(ref path, _, _) => {
3193 3194 3195
                // 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 已提交
3196
                match self.resolve_path(expr.id, path, 0, TypeNS) {
3197
                    Some(definition) => self.record_def(expr.id, definition),
3198 3199
                    None => {
                        debug!("(resolving expression) didn't find struct def",);
3200

3201 3202
                        resolve_error(self,
                                      path.span,
3203
                                      ResolutionError::DoesNotNameAStruct(
J
Jonas Schievink 已提交
3204
                                                                &path_names_to_string(path, 0))
3205
                                     );
3206
                        self.record_def(expr.id, err_path_resolution());
3207 3208 3209
                    }
                }

3210
                intravisit::walk_expr(self, expr);
3211 3212
            }

P
Pythoner6 已提交
3213
            ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
3214
                self.with_label_rib(|this| {
3215
                    let def = Def::Label(expr.id);
3216

3217
                    {
3218
                        let rib = this.label_ribs.last_mut().unwrap();
3219
                        rib.bindings.insert(label.name, def);
3220
                    }
3221

3222
                    intravisit::walk_expr(this, expr);
3223
                })
3224 3225
            }

3226
            ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
3227
                match self.search_label(label.node.name) {
3228
                    None => {
3229
                        self.record_def(expr.id, err_path_resolution());
3230
                        resolve_error(self,
3231 3232
                                      label.span,
                                      ResolutionError::UndeclaredLabel(&label.node.name.as_str()))
3233
                    }
3234
                    Some(def @ Def::Label(_)) => {
3235
                        // Since this def is a label, it is never read.
C
corentih 已提交
3236 3237 3238 3239 3240
                        self.record_def(expr.id,
                                        PathResolution {
                                            base_def: def,
                                            depth: 0,
                                        })
3241 3242
                    }
                    Some(_) => {
C
corentih 已提交
3243
                        self.session.span_bug(expr.span, "label wasn't mapped to a label def!")
3244 3245 3246 3247
                    }
                }
            }

B
Brian Anderson 已提交
3248
            _ => {
3249
                intravisit::walk_expr(self, expr);
3250 3251 3252 3253
            }
        }
    }

E
Eduard Burtescu 已提交
3254
    fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3255
        match expr.node {
3256
            ExprField(_, name) => {
3257 3258 3259 3260
                // 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.
3261
                let traits = self.get_traits_containing_item(name.node);
3262
                self.trait_map.insert(expr.id, traits);
3263
            }
3264
            ExprMethodCall(name, _, _) => {
C
corentih 已提交
3265
                debug!("(recording candidate traits for expr) recording traits for {}",
3266
                       expr.id);
3267
                let traits = self.get_traits_containing_item(name.node);
3268
                self.trait_map.insert(expr.id, traits);
3269
            }
3270
            _ => {
3271 3272 3273 3274 3275
                // Nothing to do.
            }
        }
    }

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

C
corentih 已提交
3279
        fn add_trait_info(found_traits: &mut Vec<DefId>, trait_def_id: DefId, name: Name) {
3280
            debug!("(adding trait info) found trait {:?} for method '{}'",
C
corentih 已提交
3281 3282
                   trait_def_id,
                   name);
E
Eduard Burtescu 已提交
3283 3284
            found_traits.push(trait_def_id);
        }
3285

3286
        let mut found_traits = Vec::new();
3287
        let mut search_module = self.current_module;
E
Eduard Burtescu 已提交
3288 3289
        loop {
            // Look for the current trait.
3290 3291
            match self.current_trait_ref {
                Some((trait_def_id, _)) => {
3292
                    if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3293
                        add_trait_info(&mut found_traits, trait_def_id, name);
3294 3295
                    }
                }
3296
                None => {} // Nothing to do.
E
Eduard Burtescu 已提交
3297
            }
3298

E
Eduard Burtescu 已提交
3299
            // Look for trait children.
3300
            let mut search_in_module = |module: Module<'a>| module.for_each_child(|_, ns, binding| {
3301
                if ns != TypeNS { return }
3302
                let trait_def_id = match binding.def() {
3303
                    Some(Def::Trait(trait_def_id)) => trait_def_id,
3304
                    Some(..) | None => return,
3305 3306 3307
                };
                if self.trait_item_map.contains_key(&(name, trait_def_id)) {
                    add_trait_info(&mut found_traits, trait_def_id, name);
3308
                    let trait_name = self.get_trait_name(trait_def_id);
3309 3310
                    self.record_use(trait_name, TypeNS, binding);
                }
3311 3312
            });
            search_in_module(search_module);
3313

3314
            match search_module.parent_link {
3315 3316 3317 3318
                NoParentLink | ModuleParentLink(..) => {
                    search_module.prelude.borrow().map(search_in_module);
                    break;
                }
E
Eduard Burtescu 已提交
3319
                BlockParentLink(parent_module, _) => {
3320
                    search_module = parent_module;
3321
                }
E
Eduard Burtescu 已提交
3322
            }
3323 3324
        }

E
Eduard Burtescu 已提交
3325
        found_traits
3326 3327
    }

3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347
    /// 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() {
3348
            self.populate_module_if_necessary(in_module);
3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 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

            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
                        }
                        _ => unreachable!(),
                    };

                    if !in_module_is_extern || name_binding.is_public() {
                        // add the module to the lookup
3408
                        let is_extern = in_module_is_extern || name_binding.is_extern_crate();
3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420
                        worklist.push((module, path_segments, is_extern));
                    }
                }
            })
        }

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

3421 3422 3423 3424
    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);
C
corentih 已提交
3425 3426 3427 3428
            self.session.span_bug(span,
                                  &format!("path resolved multiple times ({:?} before, {:?} now)",
                                           prev_res,
                                           resolution));
3429
        }
3430 3431
    }

F
Felix S. Klock II 已提交
3432
    fn enforce_default_binding_mode(&mut self,
C
corentih 已提交
3433 3434 3435
                                    pat: &Pat,
                                    pat_binding_mode: BindingMode,
                                    descr: &str) {
3436
        match pat_binding_mode {
3437
            BindByValue(_) => {}
A
Alex Crichton 已提交
3438
            BindByRef(..) => {
3439 3440
                resolve_error(self,
                              pat.span,
3441
                              ResolutionError::CannotUseRefBindingModeWith(descr));
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 3468 3469 3470 3471 3472 3473 3474 3475

    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));
            }
        }
    }
3476

3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 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 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531
    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();
    }
}
3532 3533 3534 3535 3536 3537 3538 3539 3540 3541

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("::")
        }
3542
        result.push_str(&name.as_str());
C
corentih 已提交
3543
    }
3544 3545 3546 3547
    result
}

fn path_names_to_string(path: &Path, depth: usize) -> String {
C
corentih 已提交
3548
    let names: Vec<ast::Name> = path.segments[..path.segments.len() - depth]
3549 3550 3551 3552 3553 3554
                                    .iter()
                                    .map(|seg| seg.identifier.name)
                                    .collect();
    names_to_string(&names[..])
}

3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580
/// 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 已提交
3581
                    &format!("you can import it into scope: `use {};`.",
3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615
                        &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()),
        );
    };
}

3616
/// A somewhat inefficient routine to obtain the name of a module.
3617
fn module_to_string(module: Module) -> String {
3618 3619
    let mut names = Vec::new();

3620
    fn collect_mod(names: &mut Vec<ast::Name>, module: Module) {
3621 3622 3623 3624
        match module.parent_link {
            NoParentLink => {}
            ModuleParentLink(ref module, name) => {
                names.push(name);
3625
                collect_mod(names, module);
3626 3627 3628 3629
            }
            BlockParentLink(ref module, _) => {
                // danger, shouldn't be ident?
                names.push(special_idents::opaque.name);
3630
                collect_mod(names, module);
3631 3632 3633 3634 3635
            }
        }
    }
    collect_mod(&mut names, module);

3636
    if names.is_empty() {
3637 3638 3639 3640 3641
        return "???".to_string();
    }
    names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
}

3642 3643
fn err_path_resolution() -> PathResolution {
    PathResolution {
3644
        base_def: Def::Err,
3645 3646 3647 3648
        depth: 0,
    }
}

3649

3650
pub struct CrateMap {
J
Jonathan S 已提交
3651
    pub def_map: RefCell<DefMap>,
3652
    pub freevars: FreevarMap,
3653
    pub export_map: ExportMap,
3654
    pub trait_map: TraitMap,
C
corentih 已提交
3655
    pub glob_map: Option<GlobMap>,
3656 3657
}

N
Niko Matsakis 已提交
3658
#[derive(PartialEq,Copy, Clone)]
3659 3660
pub enum MakeGlobMap {
    Yes,
C
corentih 已提交
3661
    No,
3662 3663
}

3664
/// Entry point to crate resolution.
3665
pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
3666
                               ast_map: &'a hir_map::Map<'tcx>,
3667 3668
                               make_glob_map: MakeGlobMap)
                               -> CrateMap {
3669 3670 3671 3672 3673 3674 3675 3676 3677
    // 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);

3678
    let krate = ast_map.krate();
3679 3680
    let arenas = Resolver::arenas();
    let mut resolver = create_resolver(session, ast_map, krate, make_glob_map, &arenas, None);
3681 3682 3683 3684

    resolver.resolve_crate(krate);

    check_unused::check_crate(&mut resolver, krate);
3685
    resolver.report_privacy_errors();
3686

3687
    CrateMap {
3688 3689
        def_map: resolver.def_map,
        freevars: resolver.freevars,
3690
        export_map: resolver.export_map,
3691
        trait_map: resolver.trait_map,
3692
        glob_map: if resolver.make_glob_map {
C
corentih 已提交
3693 3694 3695 3696
            Some(resolver.glob_map)
        } else {
            None
        },
3697
    }
3698
}
3699

3700 3701 3702 3703 3704 3705 3706 3707
/// 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.
G
Garming Sam 已提交
3708
pub fn create_resolver<'a, 'tcx>(session: &'a Session,
3709
                                 ast_map: &'a hir_map::Map<'tcx>,
G
Garming Sam 已提交
3710 3711
                                 krate: &'a Crate,
                                 make_glob_map: MakeGlobMap,
3712
                                 arenas: &'a ResolverArenas<'a>,
3713
                                 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>)
G
Garming Sam 已提交
3714
                                 -> Resolver<'a, 'tcx> {
3715
    let mut resolver = Resolver::new(session, ast_map, make_glob_map, arenas);
G
Garming Sam 已提交
3716 3717 3718

    resolver.callback = callback;

J
Jeffrey Seyfried 已提交
3719
    resolver.build_reduced_graph(krate);
G
Garming Sam 已提交
3720 3721 3722 3723 3724 3725

    resolve_imports::resolve_imports(&mut resolver);

    resolver
}

3726
__build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }