lib.rs 141.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 31
extern crate syntax_pos;
extern crate rustc_errors as errors;
32
extern crate arena;
C
corentih 已提交
33
#[macro_use]
34 35
extern crate rustc;

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

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

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

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

69 70 71
use syntax_pos::Span;
use errors::DiagnosticBuilder;

72
use std::collections::{HashMap, HashSet};
73
use std::cell::{Cell, RefCell};
74
use std::fmt;
75
use std::mem::replace;
76

77
use resolve_imports::{ImportDirective, NameResolution};
78

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

A
Alex Crichton 已提交
83
mod check_unused;
84
mod build_reduced_graph;
85
mod resolve_imports;
86
mod assign_ids;
87

88 89
enum SuggestionType {
    Macro(String),
90
    Function(token::InternedString),
91 92 93
    NotFound,
}

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

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

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

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

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

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

N
Nick Cameron 已提交
197
    match resolution_error {
198
        ResolutionError::TypeParametersFromOuterFunction => {
199 200 201 202 203
            let mut err = struct_span_err!(resolver.session,
                                           span,
                                           E0401,
                                           "can't use type parameters from outer function; \
                                           try using a local type parameter instead");
204
            err.span_label(span, &format!("use of type variable from outer function"));
205
            err
C
corentih 已提交
206
        }
207
        ResolutionError::OuterTypeParameterContext => {
N
Nick Cameron 已提交
208 209 210 211
            struct_span_err!(resolver.session,
                             span,
                             E0402,
                             "cannot use an outer type parameter in this context")
C
corentih 已提交
212
        }
213
        ResolutionError::NameAlreadyUsedInTypeParameterList(name) => {
N
Nick Cameron 已提交
214 215 216 217 218 219
            struct_span_err!(resolver.session,
                             span,
                             E0403,
                             "the name `{}` is already used for a type parameter in this type \
                              parameter list",
                             name)
C
corentih 已提交
220
        }
221
        ResolutionError::IsNotATrait(name) => {
N
Nick Cameron 已提交
222
            struct_span_err!(resolver.session, span, E0404, "`{}` is not a trait", name)
C
corentih 已提交
223
        }
224 225 226 227 228 229
        ResolutionError::UndeclaredTraitName(name, candidates) => {
            let mut err = struct_span_err!(resolver.session,
                                           span,
                                           E0405,
                                           "trait `{}` is not in scope",
                                           name);
230
            show_candidates(&mut err, &candidates);
231
            err.span_label(span, &format!("`{}` is not in scope", name));
232
            err
C
corentih 已提交
233
        }
234
        ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
N
Nick Cameron 已提交
235 236 237 238 239 240
            struct_span_err!(resolver.session,
                             span,
                             E0407,
                             "method `{}` is not a member of trait `{}`",
                             method,
                             trait_)
C
corentih 已提交
241
        }
242
        ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
N
Nick Cameron 已提交
243 244 245 246 247 248
            struct_span_err!(resolver.session,
                             span,
                             E0437,
                             "type `{}` is not a member of trait `{}`",
                             type_,
                             trait_)
C
corentih 已提交
249
        }
250
        ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
N
Nick Cameron 已提交
251 252 253 254 255 256
            struct_span_err!(resolver.session,
                             span,
                             E0438,
                             "const `{}` is not a member of trait `{}`",
                             const_,
                             trait_)
C
corentih 已提交
257
        }
M
Manish Goregaokar 已提交
258
        ResolutionError::VariableNotBoundInPattern(variable_name, from, to) => {
N
Nick Cameron 已提交
259 260 261
            struct_span_err!(resolver.session,
                             span,
                             E0408,
M
Manish Goregaokar 已提交
262
                             "variable `{}` from pattern #{} is not bound in pattern #{}",
N
Nick Cameron 已提交
263
                             variable_name,
M
Manish Goregaokar 已提交
264 265
                             from,
                             to)
C
corentih 已提交
266
        }
267
        ResolutionError::VariableBoundWithDifferentMode(variable_name, pattern_number) => {
N
Nick Cameron 已提交
268 269 270 271 272 273 274
            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 已提交
275
        }
276
        ResolutionError::SelfUsedOutsideImplOrTrait => {
277 278 279 280
            let mut err = struct_span_err!(resolver.session,
                                           span,
                                           E0411,
                                           "use of `Self` outside of an impl or trait");
J
Jonathan Turner 已提交
281
            err.span_label(span, &format!("used outside of impl or trait"));
282
            err
C
corentih 已提交
283
        }
284 285 286 287 288 289 290
        ResolutionError::UseOfUndeclared(kind, name, candidates) => {
            let mut err = struct_span_err!(resolver.session,
                                           span,
                                           E0412,
                                           "{} `{}` is undefined or not in scope",
                                           kind,
                                           name);
291
            show_candidates(&mut err, &candidates);
292
            err.span_label(span, &format!("undefined or not in scope"));
293
            err
C
corentih 已提交
294
        }
295
        ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
296
            let mut err = struct_span_err!(resolver.session,
N
Nick Cameron 已提交
297 298 299
                             span,
                             E0415,
                             "identifier `{}` is bound more than once in this parameter list",
300
                             identifier);
301
            err.span_label(span, &format!("used as parameter more than once"));
302
            err
C
corentih 已提交
303
        }
304
        ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
305
            let mut err = struct_span_err!(resolver.session,
N
Nick Cameron 已提交
306 307 308
                             span,
                             E0416,
                             "identifier `{}` is bound more than once in the same pattern",
309
                             identifier);
310
            err.span_label(span, &format!("used in a pattern more than once"));
311
            err
C
corentih 已提交
312
        }
313
        ResolutionError::DoesNotNameAStruct(name) => {
N
Nick Cameron 已提交
314 315 316 317 318
            struct_span_err!(resolver.session,
                             span,
                             E0422,
                             "`{}` does not name a structure",
                             name)
C
corentih 已提交
319
        }
320
        ResolutionError::StructVariantUsedAsFunction(path_name) => {
N
Nick Cameron 已提交
321 322 323 324 325 326
            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 已提交
327
        }
328
        ResolutionError::SelfNotAvailableInStaticMethod => {
N
Nick Cameron 已提交
329 330 331 332 333
            struct_span_err!(resolver.session,
                             span,
                             E0424,
                             "`self` is not available in a static method. Maybe a `self` \
                             argument is missing?")
C
corentih 已提交
334
        }
335
        ResolutionError::UnresolvedName { path, message: msg, context, is_static_method,
G
ggomez 已提交
336
                                          is_field, def } => {
N
Nick Cameron 已提交
337 338 339 340 341 342
            let mut err = struct_span_err!(resolver.session,
                                           span,
                                           E0425,
                                           "unresolved name `{}`{}",
                                           path,
                                           msg);
343
            match context {
344 345 346 347 348 349
                UnresolvedNameContext::Other => {
                    if msg.is_empty() && is_static_method && is_field {
                        err.help("this is an associated function, you don't have access to \
                                  this type's fields or methods");
                    }
                }
350
                UnresolvedNameContext::PathIsMod(parent) => {
351
                    err.help(&match parent.map(|parent| &parent.node) {
352
                        Some(&ExprKind::Field(_, ident)) => {
G
ggomez 已提交
353
                            format!("to reference an item from the `{module}` module, \
354 355 356
                                     use `{module}::{ident}`",
                                    module = path,
                                    ident = ident.node)
357
                        }
358
                        Some(&ExprKind::MethodCall(ident, _, _)) => {
G
ggomez 已提交
359
                            format!("to call a function from the `{module}` module, \
360 361 362 363 364
                                     use `{module}::{ident}(..)`",
                                    module = path,
                                    ident = ident.node)
                        }
                        _ => {
G
ggomez 已提交
365 366
                            format!("{def} `{module}` cannot be used as an expression",
                                    def = def.kind_name(),
367 368 369
                                    module = path)
                        }
                    });
370 371
                }
            }
N
Nick Cameron 已提交
372
            err
C
corentih 已提交
373
        }
374
        ResolutionError::UndeclaredLabel(name) => {
N
Nick Cameron 已提交
375 376 377 378 379
            struct_span_err!(resolver.session,
                             span,
                             E0426,
                             "use of undeclared label `{}`",
                             name)
C
corentih 已提交
380
        }
381
        ResolutionError::SelfImportsOnlyAllowedWithin => {
N
Nick Cameron 已提交
382 383 384 385 386
            struct_span_err!(resolver.session,
                             span,
                             E0429,
                             "{}",
                             "`self` imports are only allowed within a { } list")
C
corentih 已提交
387
        }
388
        ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
N
Nick Cameron 已提交
389 390 391 392
            struct_span_err!(resolver.session,
                             span,
                             E0430,
                             "`self` import can only appear once in the list")
C
corentih 已提交
393
        }
394
        ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
N
Nick Cameron 已提交
395 396 397 398 399
            struct_span_err!(resolver.session,
                             span,
                             E0431,
                             "`self` import can only appear in an import list with a \
                              non-empty prefix")
400
        }
401
        ResolutionError::UnresolvedImport(name) => {
402
            let msg = match name {
403
                Some((n, p)) => format!("unresolved import `{}`{}", n, p),
C
corentih 已提交
404
                None => "unresolved import".to_owned(),
405
            };
N
Nick Cameron 已提交
406
            struct_span_err!(resolver.session, span, E0432, "{}", msg)
C
corentih 已提交
407
        }
408
        ResolutionError::FailedToResolve(msg) => {
N
Nick Cameron 已提交
409
            struct_span_err!(resolver.session, span, E0433, "failed to resolve. {}", msg)
C
corentih 已提交
410
        }
411
        ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
N
Nick Cameron 已提交
412 413 414 415 416 417
            struct_span_err!(resolver.session,
                             span,
                             E0434,
                             "{}",
                             "can't capture dynamic environment in a fn item; use the || { ... } \
                              closure form instead")
C
corentih 已提交
418 419
        }
        ResolutionError::AttemptToUseNonConstantValueInConstant => {
N
Nick Cameron 已提交
420 421 422 423
            struct_span_err!(resolver.session,
                             span,
                             E0435,
                             "attempt to use a non-constant value in a constant")
C
corentih 已提交
424
        }
425 426 427
        ResolutionError::BindingShadowsSomethingUnacceptable(what_binding, shadows_what, name) => {
            let mut err = struct_span_err!(resolver.session,
                                           span,
428
                                           E0530,
429 430
                                           "{}s cannot shadow {}s", what_binding, shadows_what);
            err.span_label(span, &format!("cannot be named the same as a {}", shadows_what));
431
            if let Success(binding) = resolver.current_module.resolve_name(name, ValueNS, true) {
432 433 434 435 436 437 438 439 440
                let participle = if binding.is_import() { "imported" } else { "defined" };
                err.span_label(binding.span, &format!("a {} `{}` is {} here",
                                                      shadows_what, name, participle));
            }
            err
        }
        ResolutionError::PatPathUnresolved(expected_what, path) => {
            struct_span_err!(resolver.session,
                             span,
441
                             E0531,
442 443 444 445 446 447 448
                             "unresolved {} `{}`",
                             expected_what,
                             path.segments.last().unwrap().identifier)
        }
        ResolutionError::PatPathUnexpected(expected_what, found_what, path) => {
            struct_span_err!(resolver.session,
                             span,
449
                             E0532,
450 451 452 453 454
                             "expected {}, found {} `{}`",
                             expected_what,
                             found_what,
                             path.segments.last().unwrap().identifier)
        }
N
Nick Cameron 已提交
455
    }
456 457
}

N
Niko Matsakis 已提交
458
#[derive(Copy, Clone)]
459
struct BindingInfo {
460
    span: Span,
461
    binding_mode: BindingMode,
462 463 464
}

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

467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum PatternSource {
    Match,
    IfLet,
    WhileLet,
    Let,
    For,
    FnParam,
}

impl PatternSource {
    fn is_refutable(self) -> bool {
        match self {
            PatternSource::Match | PatternSource::IfLet | PatternSource::WhileLet => true,
            PatternSource::Let | PatternSource::For | PatternSource::FnParam  => false,
        }
    }
    fn descr(self) -> &'static str {
        match self {
            PatternSource::Match => "match binding",
            PatternSource::IfLet => "if let binding",
            PatternSource::WhileLet => "while let binding",
            PatternSource::Let => "let binding",
            PatternSource::For => "for binding",
            PatternSource::FnParam => "function parameter",
        }
    }
494 495
}

N
Niko Matsakis 已提交
496
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
G
Garming Sam 已提交
497
pub enum Namespace {
498
    TypeNS,
C
corentih 已提交
499
    ValueNS,
500 501
}

502
impl<'a> Visitor for Resolver<'a> {
503
    fn visit_item(&mut self, item: &Item) {
A
Alex Crichton 已提交
504
        self.resolve_item(item);
505
    }
506
    fn visit_arm(&mut self, arm: &Arm) {
A
Alex Crichton 已提交
507
        self.resolve_arm(arm);
508
    }
509
    fn visit_block(&mut self, block: &Block) {
A
Alex Crichton 已提交
510
        self.resolve_block(block);
511
    }
512
    fn visit_expr(&mut self, expr: &Expr) {
513
        self.resolve_expr(expr, None);
514
    }
515
    fn visit_local(&mut self, local: &Local) {
A
Alex Crichton 已提交
516
        self.resolve_local(local);
517
    }
518
    fn visit_ty(&mut self, ty: &Ty) {
A
Alex Crichton 已提交
519
        self.resolve_type(ty);
520
    }
521
    fn visit_poly_trait_ref(&mut self, tref: &ast::PolyTraitRef, m: &ast::TraitBoundModifier) {
522 523
        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 已提交
524 525
            Err(_) => {
                // error already reported
526
                self.record_def(tref.trait_ref.ref_id, err_path_resolution())
C
corentih 已提交
527
            }
528
        }
529
        visit::walk_poly_trait_ref(self, tref, m);
530
    }
C
corentih 已提交
531
    fn visit_variant(&mut self,
532
                     variant: &ast::Variant,
C
corentih 已提交
533 534
                     generics: &Generics,
                     item_id: ast::NodeId) {
535 536 537
        if let Some(ref dis_expr) = variant.node.disr_expr {
            // resolve the discriminator expr as a constant
            self.with_constant_rib(|this| {
538
                this.visit_expr(dis_expr);
539 540 541
            });
        }

542
        // `visit::walk_variant` without the discriminant expression.
C
corentih 已提交
543 544 545 546 547
        self.visit_variant_data(&variant.node.data,
                                variant.node.name,
                                generics,
                                item_id,
                                variant.span);
548
    }
549
    fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
550
        let type_parameters = match foreign_item.node {
551
            ForeignItemKind::Fn(_, ref generics) => {
552 553
                HasTypeParameters(generics, FnSpace, ItemRibKind)
            }
554
            ForeignItemKind::Static(..) => NoTypeParameters,
555 556
        };
        self.with_type_parameter_rib(type_parameters, |this| {
557
            visit::walk_foreign_item(this, foreign_item);
558 559 560
        });
    }
    fn visit_fn(&mut self,
561 562 563
                function_kind: FnKind,
                declaration: &FnDecl,
                block: &Block,
564 565 566
                _: Span,
                node_id: NodeId) {
        let rib_kind = match function_kind {
567
            FnKind::ItemFn(_, generics, _, _, _, _) => {
568 569 570
                self.visit_generics(generics);
                ItemRibKind
            }
571
            FnKind::Method(_, sig, _) => {
572
                self.visit_generics(&sig.generics);
V
Vadim Petrochenkov 已提交
573
                MethodRibKind(!sig.decl.has_self())
574
            }
575
            FnKind::Closure => ClosureRibKind(node_id),
576 577 578
        };
        self.resolve_function(rib_kind, declaration, block);
    }
579
}
580

581
pub type ErrorMessage = Option<(Span, String)>;
582

583
#[derive(Clone, PartialEq, Eq)]
584
pub enum ResolveResult<T> {
C
corentih 已提交
585 586 587
    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.
588 589
}

590
impl<T> ResolveResult<T> {
591 592 593 594 595
    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 已提交
596
        }
597
    }
598 599 600 601 602 603 604

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

607 608 609
enum FallbackSuggestion {
    NoSuggestion,
    Field,
610
    TraitItem,
611
    TraitMethod(String),
612 613
}

N
Niko Matsakis 已提交
614
#[derive(Copy, Clone)]
615
enum TypeParameters<'a, 'b> {
616
    NoTypeParameters,
C
corentih 已提交
617
    HasTypeParameters(// Type parameters.
618
                      &'b Generics,
619

C
corentih 已提交
620 621 622
                      // Identifies the things that these parameters
                      // were declared on (type, fn, etc)
                      ParamSpace,
623

C
corentih 已提交
624
                      // The kind of the rib used for type parameters.
625
                      RibKind<'a>),
626 627
}

628
// The rib kind controls the translation of local
629
// definitions (`Def::Local`) to upvars (`Def::Upvar`).
N
Niko Matsakis 已提交
630
#[derive(Copy, Clone, Debug)]
631
enum RibKind<'a> {
632 633
    // No translation needs to be applied.
    NormalRibKind,
634

635 636
    // We passed through a closure scope at the given node ID.
    // Translate upvars as appropriate.
637
    ClosureRibKind(NodeId /* func id */),
638

639
    // We passed through an impl or trait and are now in one of its
640
    // methods. Allow references to ty params that impl or trait
641 642
    // binds. Disallow any other upvars (including other ty params that are
    // upvars).
643 644 645
    //
    // The boolean value represents the fact that this method is static or not.
    MethodRibKind(bool),
646

647 648
    // We passed through an item scope. Disallow upvars.
    ItemRibKind,
649 650

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

653 654
    // We passed through a module.
    ModuleRibKind(Module<'a>),
655 656

    // We passed through a `macro_rules!` statement with the given expansion
657
    MacroDefinition(Mark),
658 659
}

N
Niko Matsakis 已提交
660
#[derive(Copy, Clone)]
F
Felix S. Klock II 已提交
661
enum UseLexicalScopeFlag {
662
    DontUseLexicalScope,
C
corentih 已提交
663
    UseLexicalScope,
664 665
}

666
enum ModulePrefixResult<'a> {
667
    NoPrefixFound,
668
    PrefixFound(Module<'a>, usize),
669 670
}

671
/// One local scope.
J
Jorge Aparicio 已提交
672
#[derive(Debug)]
673
struct Rib<'a> {
674
    bindings: HashMap<ast::Ident, Def>,
675
    kind: RibKind<'a>,
B
Brian Anderson 已提交
676
}
677

678 679
impl<'a> Rib<'a> {
    fn new(kind: RibKind<'a>) -> Rib<'a> {
680
        Rib {
681
            bindings: HashMap::new(),
C
corentih 已提交
682
            kind: kind,
683
        }
684 685 686
    }
}

687 688 689
/// A definition along with the index of the rib it was found on
struct LocalDef {
    ribs: Option<(Namespace, usize)>,
C
corentih 已提交
690
    def: Def,
691 692 693 694 695 696
}

impl LocalDef {
    fn from_def(def: Def) -> Self {
        LocalDef {
            ribs: None,
C
corentih 已提交
697
            def: def,
698 699 700 701
        }
    }
}

702 703 704 705 706
enum LexicalScopeBinding<'a> {
    Item(&'a NameBinding<'a>),
    LocalDef(LocalDef),
}

707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
impl<'a> LexicalScopeBinding<'a> {
    fn local_def(self) -> LocalDef {
        match self {
            LexicalScopeBinding::LocalDef(local_def) => local_def,
            LexicalScopeBinding::Item(binding) => LocalDef::from_def(binding.def().unwrap()),
        }
    }

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

723
/// The link from a module up to its nearest parent node.
J
Jorge Aparicio 已提交
724
#[derive(Clone,Debug)]
725
enum ParentLink<'a> {
726
    NoParentLink,
727 728
    ModuleParentLink(Module<'a>, Name),
    BlockParentLink(Module<'a>, NodeId),
729 730
}

731
/// One node in the tree of modules.
732 733
pub struct ModuleS<'a> {
    parent_link: ParentLink<'a>,
J
Jeffrey Seyfried 已提交
734
    def: Option<Def>,
735

736 737 738
    // 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>,
739

740
    resolutions: RefCell<HashMap<(Name, Namespace), &'a RefCell<NameResolution<'a>>>>,
741
    unresolved_imports: RefCell<Vec<&'a ImportDirective<'a>>>,
742

743
    no_implicit_prelude: Cell<bool>,
744

745
    glob_importers: RefCell<Vec<(Module<'a>, &'a ImportDirective<'a>)>>,
746
    globs: RefCell<Vec<&'a ImportDirective<'a>>>,
747

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

751 752 753
    // Whether this module is populated. If not populated, any attempt to
    // access the children must be preceded with a
    // `populate_module_if_necessary` call.
754
    populated: Cell<bool>,
755 756

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

759 760 761
pub type Module<'a> = &'a ModuleS<'a>;

impl<'a> ModuleS<'a> {
762 763 764 765
    fn new(parent_link: ParentLink<'a>,
           def: Option<Def>,
           external: bool,
           arenas: &'a ResolverArenas<'a>) -> Self {
766
        ModuleS {
767
            parent_link: parent_link,
J
Jeffrey Seyfried 已提交
768
            def: def,
769
            extern_crate_id: None,
770
            resolutions: RefCell::new(HashMap::new()),
771
            unresolved_imports: RefCell::new(Vec::new()),
772
            no_implicit_prelude: Cell::new(false),
773
            glob_importers: RefCell::new(Vec::new()),
774
            globs: RefCell::new((Vec::new())),
J
Jeffrey Seyfried 已提交
775
            traits: RefCell::new(None),
776
            populated: Cell::new(!external),
777
            arenas: arenas
778
        }
B
Brian Anderson 已提交
779 780
    }

781
    fn for_each_child<F: FnMut(Name, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
782
        for (&(name, ns), name_resolution) in self.resolutions.borrow().iter() {
783
            name_resolution.borrow().binding.map(|binding| f(name, ns, binding));
784 785 786
        }
    }

787
    fn def_id(&self) -> Option<DefId> {
J
Jeffrey Seyfried 已提交
788
        self.def.as_ref().map(Def::def_id)
789 790
    }

791
    // `self` resolves to the first module ancestor that `is_normal`.
792
    fn is_normal(&self) -> bool {
J
Jeffrey Seyfried 已提交
793
        match self.def {
794
            Some(Def::Mod(_)) => true,
795 796 797 798 799
            _ => false,
        }
    }

    fn is_trait(&self) -> bool {
J
Jeffrey Seyfried 已提交
800
        match self.def {
801
            Some(Def::Trait(_)) => true,
802
            _ => false,
803
        }
B
Brian Anderson 已提交
804
    }
V
Victor Berger 已提交
805 806
}

807
impl<'a> fmt::Debug for ModuleS<'a> {
808
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
809
        write!(f, "{:?}", self.def)
810 811 812
    }
}

813
// Records a possibly-private value, type, or module definition.
814
#[derive(Clone, Debug)]
815
pub struct NameBinding<'a> {
816
    kind: NameBindingKind<'a>,
817
    span: Span,
818
    vis: ty::Visibility,
819 820
}

821 822 823 824 825 826 827 828 829 830
pub trait ToNameBinding<'a> {
    fn to_name_binding(self) -> NameBinding<'a>;
}

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

831
#[derive(Clone, Debug)]
832
enum NameBindingKind<'a> {
833
    Def(Def),
834
    Module(Module<'a>),
835 836
    Import {
        binding: &'a NameBinding<'a>,
837
        directive: &'a ImportDirective<'a>,
838
    },
839 840
}

841 842 843
#[derive(Clone, Debug)]
struct PrivacyError<'a>(Span, Name, &'a NameBinding<'a>);

844
impl<'a> NameBinding<'a> {
845
    fn module(&self) -> Option<Module<'a>> {
846 847 848 849
        match self.kind {
            NameBindingKind::Module(module) => Some(module),
            NameBindingKind::Def(_) => None,
            NameBindingKind::Import { binding, .. } => binding.module(),
850 851 852
        }
    }

853
    fn def(&self) -> Option<Def> {
854 855 856 857
        match self.kind {
            NameBindingKind::Def(def) => Some(def),
            NameBindingKind::Module(module) => module.def,
            NameBindingKind::Import { binding, .. } => binding.def(),
858
        }
859
    }
860

861 862 863 864 865 866 867 868 869 870 871 872 873 874
    fn is_pseudo_public(&self) -> bool {
        self.pseudo_vis() == ty::Visibility::Public
    }

    // We sometimes need to treat variants as `pub` for backwards compatibility
    fn pseudo_vis(&self) -> ty::Visibility {
        if self.is_variant() { ty::Visibility::Public } else { self.vis }
    }

    fn is_variant(&self) -> bool {
        match self.kind {
            NameBindingKind::Def(Def::Variant(..)) => true,
            _ => false,
        }
875 876
    }

877
    fn is_extern_crate(&self) -> bool {
878
        self.module().and_then(|module| module.extern_crate_id).is_some()
879
    }
880 881 882 883 884 885 886

    fn is_import(&self) -> bool {
        match self.kind {
            NameBindingKind::Import { .. } => true,
            _ => false,
        }
    }
887 888 889 890 891 892 893 894 895 896 897 898 899 900

    fn is_glob_import(&self) -> bool {
        match self.kind {
            NameBindingKind::Import { directive, .. } => directive.is_glob(),
            _ => false,
        }
    }

    fn is_importable(&self) -> bool {
        match self.def().unwrap() {
            Def::AssociatedConst(..) | Def::Method(..) | Def::AssociatedTy(..) => false,
            _ => true,
        }
    }
901 902
}

903
/// Interns the names of the primitive types.
F
Felix S. Klock II 已提交
904
struct PrimitiveTypeTable {
905
    primitive_types: HashMap<Name, PrimTy>,
906
}
907

908
impl PrimitiveTypeTable {
K
Kevin Butler 已提交
909
    fn new() -> PrimitiveTypeTable {
C
corentih 已提交
910 911 912 913
        let mut table = PrimitiveTypeTable { primitive_types: HashMap::new() };

        table.intern("bool", TyBool);
        table.intern("char", TyChar);
914 915
        table.intern("f32", TyFloat(FloatTy::F32));
        table.intern("f64", TyFloat(FloatTy::F64));
916 917 918 919 920
        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 已提交
921
        table.intern("str", TyStr);
922 923 924 925 926
        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 已提交
927 928 929 930

        table
    }

931
    fn intern(&mut self, string: &str, primitive_type: PrimTy) {
932
        self.primitive_types.insert(token::intern(string), primitive_type);
933 934 935
    }
}

936
/// The main resolver class.
937
pub struct Resolver<'a> {
E
Eduard Burtescu 已提交
938
    session: &'a Session,
939

940
    pub definitions: Definitions,
941

942 943
    // Maps the node id of a statement to the expansions of the `macro_rules!`s
    // immediately above the statement (if appropriate).
944
    macros_at_scope: HashMap<NodeId, Vec<Mark>>,
945

946
    graph_root: Module<'a>,
947

948 949
    prelude: Option<Module<'a>>,

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

952
    structs: FnvHashMap<DefId, Vec<Name>>,
953

954
    // The number of imports that are currently unresolved.
955
    unresolved_imports: usize,
956 957

    // The module that represents the current item scope.
958
    current_module: Module<'a>,
959 960

    // The current set of local scopes, for values.
961
    // FIXME #4948: Reuse ribs to avoid allocation.
962
    value_ribs: Vec<Rib<'a>>,
963 964

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

967
    // The current set of local scopes, for labels.
968
    label_ribs: Vec<Rib<'a>>,
969

970
    // The trait that the current context can refer to.
971 972 973 974
    current_trait_ref: Option<(DefId, TraitRef)>,

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

976
    // The idents for the primitive types.
E
Eduard Burtescu 已提交
977
    primitive_type_table: PrimitiveTypeTable,
978

979 980
    pub def_map: DefMap,
    pub freevars: FreevarMap,
981
    freevars_seen: NodeMap<NodeMap<usize>>,
982 983
    pub export_map: ExportMap,
    pub trait_map: TraitMap,
984

985 986 987 988 989 990 991 992 993 994 995 996 997 998
    // A map from nodes to modules, both normal (`mod`) modules and anonymous modules.
    // Anonymous modules are pseudo-modules that are implicitly created around items
    // contained within blocks.
    //
    // For example, if we have this:
    //
    //  fn f() {
    //      fn g() {
    //          ...
    //      }
    //  }
    //
    // There will be an anonymous module created around `g` with the ID of the
    // entry block for `f`.
999
    pub module_map: NodeMap<Module<'a>>,
1000

1001 1002 1003 1004 1005
    // 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,

1006
    pub make_glob_map: bool,
1007 1008
    // Maps imports to the names of items actually imported (this actually maps
    // all imports, but only glob imports are actually interesting).
1009
    pub glob_map: GlobMap,
1010

1011
    used_imports: HashSet<(NodeId, Namespace)>,
1012
    used_crates: HashSet<CrateNum>,
1013
    pub maybe_unused_trait_imports: NodeSet,
G
Garming Sam 已提交
1014

1015
    privacy_errors: Vec<PrivacyError<'a>>,
1016 1017 1018 1019

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

1020
pub struct ResolverArenas<'a> {
1021
    modules: arena::TypedArena<ModuleS<'a>>,
1022
    local_modules: RefCell<Vec<Module<'a>>>,
1023
    name_bindings: arena::TypedArena<NameBinding<'a>>,
1024
    import_directives: arena::TypedArena<ImportDirective<'a>>,
1025
    name_resolutions: arena::TypedArena<RefCell<NameResolution<'a>>>,
1026 1027 1028
}

impl<'a> ResolverArenas<'a> {
1029
    fn alloc_module(&'a self, module: ModuleS<'a>) -> Module<'a> {
1030 1031 1032 1033 1034 1035 1036 1037
        let module = self.modules.alloc(module);
        if module.def_id().map(|def_id| def_id.is_local()).unwrap_or(true) {
            self.local_modules.borrow_mut().push(module);
        }
        module
    }
    fn local_modules(&'a self) -> ::std::cell::Ref<'a, Vec<Module<'a>>> {
        self.local_modules.borrow()
1038 1039 1040 1041
    }
    fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
        self.name_bindings.alloc(name_binding)
    }
1042 1043
    fn alloc_import_directive(&'a self, import_directive: ImportDirective<'a>)
                              -> &'a ImportDirective {
1044 1045
        self.import_directives.alloc(import_directive)
    }
1046 1047 1048
    fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
        self.name_resolutions.alloc(Default::default())
    }
1049 1050
}

1051
impl<'a> ty::NodeIdTree for Resolver<'a> {
1052
    fn is_descendant_of(&self, node: NodeId, ancestor: NodeId) -> bool {
1053
        let ancestor = self.definitions.local_def_id(ancestor);
1054
        let mut module = *self.module_map.get(&node).unwrap();
J
Jeffrey Seyfried 已提交
1055
        while module.def_id() != Some(ancestor) {
1056 1057 1058 1059 1060 1061
            let module_parent = match self.get_nearest_normal_module_parent(module) {
                Some(parent) => parent,
                None => return false,
            };
            module = module_parent;
        }
J
Jeffrey Seyfried 已提交
1062
        true
1063 1064 1065
    }
}

1066 1067 1068 1069 1070 1071 1072 1073 1074
impl<'a> hir::lowering::Resolver for Resolver<'a> {
    fn resolve_generated_global_path(&mut self, path: &hir::Path, is_value: bool) -> Def {
        let namespace = if is_value { ValueNS } else { TypeNS };
        match self.resolve_crate_relative_path(path.span, &path.segments, namespace) {
            Ok(binding) => binding.def().unwrap(),
            Err(true) => Def::Err,
            Err(false) => {
                let path_name = &format!("{}", path);
                let error =
1075 1076 1077 1078 1079
                    ResolutionError::UnresolvedName {
                        path: path_name,
                        message: "",
                        context: UnresolvedNameContext::Other,
                        is_static_method: false,
G
ggomez 已提交
1080 1081
                        is_field: false,
                        def: Def::Err,
1082
                    };
1083 1084 1085 1086 1087 1088
                resolve_error(self, path.span, error);
                Def::Err
            }
        }
    }

1089 1090 1091 1092
    fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution> {
        self.def_map.get(&id).cloned()
    }

1093
    fn record_resolution(&mut self, id: NodeId, def: Def) {
1094
        self.def_map.insert(id, PathResolution::new(def));
1095
    }
1096 1097

    fn definitions(&mut self) -> Option<&mut Definitions> {
1098
        Some(&mut self.definitions)
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
    }
}

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

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

impl Named for hir::PathSegment {
    fn name(&self) -> Name {
V
Vadim Petrochenkov 已提交
1114
        self.name
1115 1116 1117
    }
}

1118
impl<'a> Resolver<'a> {
1119
    pub fn new(session: &'a Session, make_glob_map: MakeGlobMap, arenas: &'a ResolverArenas<'a>)
1120
               -> Resolver<'a> {
1121
        let root_def_id = DefId::local(CRATE_DEF_INDEX);
1122
        let graph_root =
1123
            ModuleS::new(NoParentLink, Some(Def::Mod(root_def_id)), false, arenas);
1124
        let graph_root = arenas.alloc_module(graph_root);
1125 1126
        let mut module_map = NodeMap();
        module_map.insert(CRATE_NODE_ID, graph_root);
K
Kevin Butler 已提交
1127 1128 1129 1130

        Resolver {
            session: session,

1131
            definitions: Definitions::new(),
1132
            macros_at_scope: HashMap::new(),
1133

K
Kevin Butler 已提交
1134 1135
            // The outermost module has def ID 0; this is not reflected in the
            // AST.
1136
            graph_root: graph_root,
1137
            prelude: None,
K
Kevin Butler 已提交
1138

1139 1140
            trait_item_map: FnvHashMap(),
            structs: FnvHashMap(),
K
Kevin Butler 已提交
1141 1142 1143

            unresolved_imports: 0,

1144
            current_module: graph_root,
1145 1146
            value_ribs: vec![Rib::new(ModuleRibKind(graph_root))],
            type_ribs: vec![Rib::new(ModuleRibKind(graph_root))],
1147
            label_ribs: Vec::new(),
K
Kevin Butler 已提交
1148 1149 1150 1151 1152 1153

            current_trait_ref: None,
            current_self_type: None,

            primitive_type_table: PrimitiveTypeTable::new(),

1154
            def_map: NodeMap(),
1155 1156
            freevars: NodeMap(),
            freevars_seen: NodeMap(),
1157 1158
            export_map: NodeMap(),
            trait_map: NodeMap(),
1159
            module_map: module_map,
K
Kevin Butler 已提交
1160 1161

            emit_errors: true,
1162
            make_glob_map: make_glob_map == MakeGlobMap::Yes,
1163
            glob_map: NodeMap(),
G
Garming Sam 已提交
1164

S
Seo Sanghyeon 已提交
1165 1166 1167 1168
            used_imports: HashSet::new(),
            used_crates: HashSet::new(),
            maybe_unused_trait_imports: NodeSet(),

1169
            privacy_errors: Vec::new(),
1170 1171 1172 1173 1174

            arenas: arenas,
        }
    }

1175
    pub fn arenas() -> ResolverArenas<'a> {
1176 1177
        ResolverArenas {
            modules: arena::TypedArena::new(),
1178
            local_modules: RefCell::new(Vec::new()),
1179
            name_bindings: arena::TypedArena::new(),
1180
            import_directives: arena::TypedArena::new(),
1181
            name_resolutions: arena::TypedArena::new(),
K
Kevin Butler 已提交
1182 1183
        }
    }
1184

1185 1186 1187 1188 1189 1190 1191 1192 1193
    /// Entry point to crate resolution.
    pub fn resolve_crate(&mut self, krate: &Crate) {
        self.current_module = self.graph_root;
        visit::walk_crate(self, krate);

        check_unused::check_crate(self, krate);
        self.report_privacy_errors();
    }

1194 1195 1196
    fn new_module(&self, parent_link: ParentLink<'a>, def: Option<Def>, external: bool)
                  -> Module<'a> {
        self.arenas.alloc_module(ModuleS::new(parent_link, def, external, self.arenas))
1197 1198
    }

1199
    fn new_extern_crate_module(&self, parent_link: ParentLink<'a>, def: Def, local_node_id: NodeId)
1200
                               -> Module<'a> {
1201
        let mut module = ModuleS::new(parent_link, Some(def), false, self.arenas);
1202
        module.extern_crate_id = Some(local_node_id);
1203 1204 1205
        self.arenas.modules.alloc(module)
    }

1206 1207 1208 1209
    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 }
    }

1210
    #[inline]
S
Seo Sanghyeon 已提交
1211
    fn record_use(&mut self, name: Name, binding: &'a NameBinding<'a>) {
1212 1213 1214 1215 1216
        // 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);
        }

1217 1218
        let directive = match binding.kind {
            NameBindingKind::Import { directive, .. } => directive,
1219 1220 1221
            _ => return,
        };

1222 1223 1224
        if !self.make_glob_map {
            return;
        }
1225 1226
        if self.glob_map.contains_key(&directive.id) {
            self.glob_map.get_mut(&directive.id).unwrap().insert(name);
1227 1228 1229
            return;
        }

1230
        let mut new_set = FnvHashSet();
1231
        new_set.insert(name);
1232
        self.glob_map.insert(directive.id, new_set);
1233 1234
    }

1235
    /// Resolves the given module path from the given root `module_`.
F
Felix S. Klock II 已提交
1236
    fn resolve_module_path_from_root(&mut self,
1237
                                     module_: Module<'a>,
1238
                                     module_path: &[Name],
1239
                                     index: usize,
J
Jeffrey Seyfried 已提交
1240 1241
                                     span: Span)
                                     -> ResolveResult<Module<'a>> {
1242
        fn search_parent_externals(needle: Name, module: Module) -> Option<Module> {
1243 1244
            match module.resolve_name(needle, TypeNS, false) {
                Success(binding) if binding.is_extern_crate() => Some(module),
1245
                _ => match module.parent_link {
1246
                    ModuleParentLink(ref parent, _) => {
1247
                        search_parent_externals(needle, parent)
1248
                    }
C
corentih 已提交
1249 1250
                    _ => None,
                },
1251
            }
1252 1253
        }

1254
        let mut search_module = module_;
1255
        let mut index = index;
A
Alex Crichton 已提交
1256
        let module_path_len = module_path.len();
1257 1258 1259 1260 1261

        // 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 已提交
1262
            let name = module_path[index];
1263
            match self.resolve_name_in_module(search_module, name, TypeNS, false, true) {
1264
                Failed(None) => {
1265
                    let segment_name = name.as_str();
1266
                    let module_name = module_to_string(search_module);
1267
                    let msg = if "???" == &module_name {
C
corentih 已提交
1268
                        match search_parent_externals(name, &self.current_module) {
1269
                            Some(module) => {
1270
                                let path_str = names_to_string(module_path);
J
Jonas Schievink 已提交
1271 1272
                                let target_mod_str = module_to_string(&module);
                                let current_mod_str = module_to_string(&self.current_module);
1273 1274 1275 1276 1277 1278 1279

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

1280
                                format!("Did you mean `{}{}`?", prefix, path_str)
C
corentih 已提交
1281 1282
                            }
                            None => format!("Maybe a missing `extern crate {}`?", segment_name),
1283
                        }
1284
                    } else {
C
corentih 已提交
1285
                        format!("Could not find `{}` in `{}`", segment_name, module_name)
1286
                    };
1287

1288
                    return Failed(Some((span, msg)));
1289
                }
1290
                Failed(err) => return Failed(err),
B
Brian Anderson 已提交
1291
                Indeterminate => {
C
corentih 已提交
1292 1293 1294
                    debug!("(resolving module path for import) module resolution is \
                            indeterminate: {}",
                           name);
B
Brian Anderson 已提交
1295
                    return Indeterminate;
1296
                }
1297
                Success(binding) => {
1298 1299
                    // Check to see whether there are type bindings, and, if
                    // so, whether there is a module within.
J
Jeffrey Seyfried 已提交
1300
                    if let Some(module_def) = binding.module() {
1301
                        self.check_privacy(name, binding, span);
1302 1303 1304 1305
                        search_module = module_def;
                    } else {
                        let msg = format!("Not a module `{}`", name);
                        return Failed(Some((span, msg)));
1306 1307 1308 1309
                    }
                }
            }

T
Tim Chevalier 已提交
1310
            index += 1;
1311 1312
        }

J
Jeffrey Seyfried 已提交
1313
        return Success(search_module);
1314 1315
    }

1316 1317
    /// Attempts to resolve the module part of an import directive or path
    /// rooted at the given module.
F
Felix S. Klock II 已提交
1318
    fn resolve_module_path(&mut self,
1319
                           module_path: &[Name],
1320
                           use_lexical_scope: UseLexicalScopeFlag,
J
Jeffrey Seyfried 已提交
1321
                           span: Span)
J
Jeffrey Seyfried 已提交
1322
                           -> ResolveResult<Module<'a>> {
1323
        if module_path.len() == 0 {
J
Jeffrey Seyfried 已提交
1324
            return Success(self.graph_root) // Use the crate root
1325
        }
1326

1327
        debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1328
               names_to_string(module_path),
1329
               module_to_string(self.current_module));
1330

1331
        // Resolve the module prefix, if any.
1332
        let module_prefix_result = self.resolve_module_prefix(module_path, span);
1333

1334 1335
        let search_module;
        let start_index;
1336
        match module_prefix_result {
1337
            Failed(err) => return Failed(err),
B
Brian Anderson 已提交
1338
            Indeterminate => {
C
corentih 已提交
1339
                debug!("(resolving module path for import) indeterminate; bailing");
B
Brian Anderson 已提交
1340
                return Indeterminate;
1341
            }
1342 1343 1344 1345 1346 1347 1348 1349
            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.
1350
                        search_module = self.graph_root;
1351 1352 1353 1354 1355 1356
                        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.
1357
                        let ident = ast::Ident::with_empty_ctxt(module_path[0]);
1358 1359 1360 1361 1362 1363
                        match self.resolve_ident_in_lexical_scope(ident, TypeNS, true)
                                  .and_then(LexicalScopeBinding::module) {
                            None => return Failed(None),
                            Some(containing_module) => {
                                search_module = containing_module;
                                start_index = 1;
1364 1365 1366 1367 1368
                            }
                        }
                    }
                }
            }
E
Eduard Burtescu 已提交
1369
            Success(PrefixFound(ref containing_module, index)) => {
1370
                search_module = containing_module;
1371
                start_index = index;
1372 1373 1374
            }
        }

1375 1376 1377
        self.resolve_module_path_from_root(search_module,
                                           module_path,
                                           start_index,
J
Jeffrey Seyfried 已提交
1378
                                           span)
1379 1380
    }

1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
    /// This resolves the identifier `ident` in the namespace `ns` in the current lexical scope.
    /// More specifically, we proceed up the hierarchy of scopes and return the binding for
    /// `ident` in the first scope that defines it (or None if no scopes define it).
    ///
    /// A block's items are above its local variables in the scope hierarchy, regardless of where
    /// the items are defined in the block. For example,
    /// ```rust
    /// fn f() {
    ///    g(); // Since there are no local variables in scope yet, this resolves to the item.
    ///    let g = || {};
    ///    fn g() {}
    ///    g(); // This resolves to the local variable `g` since it shadows the item.
    /// }
    /// ```
1395
    ///
1396 1397
    /// Invariant: This must only be called during main resolution, not during
    /// import resolution.
1398
    fn resolve_ident_in_lexical_scope(&mut self,
1399
                                      mut ident: ast::Ident,
1400 1401 1402
                                      ns: Namespace,
                                      record_used: bool)
                                      -> Option<LexicalScopeBinding<'a>> {
1403 1404 1405
        if ns == TypeNS {
            ident = ast::Ident::with_empty_ctxt(ident.name);
        }
1406

1407
        // Walk backwards up the ribs in scope.
1408
        for i in (0 .. self.get_ribs(ns).len()).rev() {
1409
            if let Some(def) = self.get_ribs(ns)[i].bindings.get(&ident).cloned() {
1410 1411 1412 1413 1414
                // The ident resolves to a type parameter or local variable.
                return Some(LexicalScopeBinding::LocalDef(LocalDef {
                    ribs: Some((ns, i)),
                    def: def,
                }));
1415 1416
            }

1417
            if let ModuleRibKind(module) = self.get_ribs(ns)[i].kind {
1418
                let name = ident.name;
1419 1420 1421 1422
                let item = self.resolve_name_in_module(module, name, ns, true, record_used);
                if let Success(binding) = item {
                    // The ident resolves to an item.
                    return Some(LexicalScopeBinding::Item(binding));
1423
                }
1424

1425
                // We can only see through anonymous modules
1426
                if module.def.is_some() {
1427 1428 1429 1430 1431 1432 1433
                    return match self.prelude {
                        Some(prelude) if !module.no_implicit_prelude.get() => {
                            prelude.resolve_name(name, ns, false).success()
                                   .map(LexicalScopeBinding::Item)
                        }
                        _ => None,
                    };
1434
                }
1435
            }
1436 1437 1438 1439

            if let MacroDefinition(mac) = self.get_ribs(ns)[i].kind {
                // If an invocation of this macro created `ident`, give up on `ident`
                // and switch to `ident`'s source from the macro definition.
1440 1441 1442
                let (source_ctxt, source_macro) = ident.ctxt.source();
                if source_macro == mac {
                    ident.ctxt = source_ctxt;
1443 1444
                }
            }
1445
        }
1446

1447 1448 1449
        None
    }

1450
    /// Returns the nearest normal module parent of the given module.
1451
    fn get_nearest_normal_module_parent(&self, module_: Module<'a>) -> Option<Module<'a>> {
1452 1453
        let mut module_ = module_;
        loop {
1454
            match module_.parent_link {
1455 1456 1457
                NoParentLink => return None,
                ModuleParentLink(new_module, _) |
                BlockParentLink(new_module, _) => {
1458
                    let new_module = new_module;
1459 1460
                    if new_module.is_normal() {
                        return Some(new_module);
1461
                    }
1462
                    module_ = new_module;
1463 1464 1465 1466 1467
                }
            }
        }
    }

1468 1469
    /// Returns the nearest normal module parent of the given module, or the
    /// module itself if it is a normal module.
1470
    fn get_nearest_normal_module_parent_or_self(&self, module_: Module<'a>) -> Module<'a> {
1471 1472 1473
        if module_.is_normal() {
            return module_;
        }
1474
        match self.get_nearest_normal_module_parent(module_) {
1475 1476
            None => module_,
            Some(new_module) => new_module,
1477 1478 1479
        }
    }

1480
    /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1481
    /// (b) some chain of `super::`.
1482
    /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1483
    fn resolve_module_prefix(&mut self, module_path: &[Name], span: Span)
1484
                             -> ResolveResult<ModulePrefixResult<'a>> {
1485 1486
        // Start at the current module if we see `self` or `super`, or at the
        // top of the crate otherwise.
1487 1488 1489 1490 1491
        let mut i = match &*module_path[0].as_str() {
            "self" => 1,
            "super" => 0,
            _ => return Success(NoPrefixFound),
        };
1492
        let module_ = self.current_module;
1493
        let mut containing_module = self.get_nearest_normal_module_parent_or_self(module_);
1494 1495

        // Now loop through all the `super`s we find.
1496
        while i < module_path.len() && "super" == module_path[i].as_str() {
1497
            debug!("(resolving module prefix) resolving `super` at {}",
J
Jonas Schievink 已提交
1498
                   module_to_string(&containing_module));
1499
            match self.get_nearest_normal_module_parent(containing_module) {
1500 1501 1502 1503
                None => {
                    let msg = "There are too many initial `super`s.".into();
                    return Failed(Some((span, msg)));
                }
1504 1505 1506
                Some(new_module) => {
                    containing_module = new_module;
                    i += 1;
1507 1508 1509 1510
                }
            }
        }

1511
        debug!("(resolving module prefix) finished resolving prefix at {}",
J
Jonas Schievink 已提交
1512
               module_to_string(&containing_module));
1513 1514

        return Success(PrefixFound(containing_module, i));
1515 1516
    }

1517
    /// Attempts to resolve the supplied name in the given module for the
J
Jeffrey Seyfried 已提交
1518
    /// given namespace. If successful, returns the binding corresponding to
1519
    /// the name.
F
Felix S. Klock II 已提交
1520
    fn resolve_name_in_module(&mut self,
1521
                              module: Module<'a>,
1522
                              name: Name,
1523
                              namespace: Namespace,
1524
                              use_lexical_scope: bool,
1525
                              record_used: bool)
1526
                              -> ResolveResult<&'a NameBinding<'a>> {
1527
        debug!("(resolving name in module) resolving `{}` in `{}`", name, module_to_string(module));
1528

1529
        self.populate_module_if_necessary(module);
1530
        module.resolve_name(name, namespace, use_lexical_scope).and_then(|binding| {
1531
            if record_used {
S
Seo Sanghyeon 已提交
1532 1533 1534 1535
                if let NameBindingKind::Import { directive, .. } = binding.kind {
                    self.used_imports.insert((directive.id, namespace));
                }
                self.record_use(name, binding);
1536
            }
1537 1538
            Success(binding)
        })
1539 1540 1541 1542
    }

    // AST resolution
    //
1543
    // We maintain a list of value ribs and type ribs.
1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
    //
    // 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.

1559
    fn with_scope<F>(&mut self, id: NodeId, f: F)
C
corentih 已提交
1560
        where F: FnOnce(&mut Resolver)
J
Jorge Aparicio 已提交
1561
    {
1562 1563
        let module = self.module_map.get(&id).cloned(); // clones a reference
        if let Some(module) = module {
1564 1565 1566 1567
            // 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)));
1568

1569
            f(self);
1570

1571 1572 1573 1574 1575 1576
            self.current_module = orig_module;
            self.value_ribs.pop();
            self.type_ribs.pop();
        } else {
            f(self);
        }
1577 1578
    }

S
Seo Sanghyeon 已提交
1579 1580
    /// Searches the current set of local scopes for labels.
    /// Stops after meeting a closure.
1581
    fn search_label(&self, mut ident: ast::Ident) -> Option<Def> {
1582 1583 1584 1585 1586
        for rib in self.label_ribs.iter().rev() {
            match rib.kind {
                NormalRibKind => {
                    // Continue
                }
1587 1588 1589
                MacroDefinition(mac) => {
                    // If an invocation of this macro created `ident`, give up on `ident`
                    // and switch to `ident`'s source from the macro definition.
1590 1591 1592
                    let (source_ctxt, source_macro) = ident.ctxt.source();
                    if source_macro == mac {
                        ident.ctxt = source_ctxt;
1593 1594
                    }
                }
1595 1596
                _ => {
                    // Do not resolve labels across function boundary
C
corentih 已提交
1597
                    return None;
1598 1599
                }
            }
1600
            let result = rib.bindings.get(&ident).cloned();
S
Seo Sanghyeon 已提交
1601
            if result.is_some() {
C
corentih 已提交
1602
                return result;
1603 1604 1605 1606 1607
            }
        }
        None
    }

1608
    fn resolve_item(&mut self, item: &Item) {
1609
        let name = item.ident.name;
1610

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

1613
        match item.node {
1614 1615 1616
            ItemKind::Enum(_, ref generics) |
            ItemKind::Ty(_, ref generics) |
            ItemKind::Struct(_, ref generics) => {
C
corentih 已提交
1617
                self.with_type_parameter_rib(HasTypeParameters(generics, TypeSpace, ItemRibKind),
1618
                                             |this| visit::walk_item(this, item));
1619
            }
1620
            ItemKind::Fn(_, _, _, _, ref generics, _) => {
C
corentih 已提交
1621
                self.with_type_parameter_rib(HasTypeParameters(generics, FnSpace, ItemRibKind),
1622
                                             |this| visit::walk_item(this, item));
1623 1624
            }

1625
            ItemKind::DefaultImpl(_, ref trait_ref) => {
1626
                self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
1627
            }
1628
            ItemKind::Impl(_, _, ref generics, ref opt_trait_ref, ref self_type, ref impl_items) =>
1629
                self.resolve_implementation(generics,
1630
                                            opt_trait_ref,
J
Jonas Schievink 已提交
1631
                                            &self_type,
1632
                                            item.id,
1633
                                            impl_items),
1634

1635
            ItemKind::Trait(_, ref generics, ref bounds, ref trait_items) => {
1636 1637 1638 1639 1640
                // Create a new rib for the trait-wide type parameters.
                self.with_type_parameter_rib(HasTypeParameters(generics,
                                                               TypeSpace,
                                                               ItemRibKind),
                                             |this| {
1641
                    let local_def_id = this.definitions.local_def_id(item.id);
1642
                    this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
1643
                        this.visit_generics(generics);
1644
                        walk_list!(this, visit_ty_param_bound, bounds);
1645 1646

                        for trait_item in trait_items {
1647
                            match trait_item.node {
1648
                                TraitItemKind::Const(_, ref default) => {
1649 1650 1651 1652 1653
                                    // 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| {
1654
                                            visit::walk_trait_item(this, trait_item)
1655 1656
                                        });
                                    } else {
1657
                                        visit::walk_trait_item(this, trait_item)
1658 1659
                                    }
                                }
1660
                                TraitItemKind::Method(ref sig, _) => {
1661 1662 1663
                                    let type_parameters =
                                        HasTypeParameters(&sig.generics,
                                                          FnSpace,
V
Vadim Petrochenkov 已提交
1664
                                                          MethodRibKind(!sig.decl.has_self()));
1665
                                    this.with_type_parameter_rib(type_parameters, |this| {
1666
                                        visit::walk_trait_item(this, trait_item)
1667
                                    });
1668
                                }
1669
                                TraitItemKind::Type(..) => {
1670
                                    this.with_type_parameter_rib(NoTypeParameters, |this| {
1671
                                        visit::walk_trait_item(this, trait_item)
1672
                                    });
1673
                                }
1674
                                TraitItemKind::Macro(_) => panic!("unexpanded macro in resolve!"),
1675 1676 1677
                            };
                        }
                    });
1678
                });
1679 1680
            }

1681
            ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
1682
                self.with_scope(item.id, |this| {
1683
                    visit::walk_item(this, item);
1684
                });
1685 1686
            }

1687
            ItemKind::Const(..) | ItemKind::Static(..) => {
A
Alex Crichton 已提交
1688
                self.with_constant_rib(|this| {
1689
                    visit::walk_item(this, item);
1690
                });
1691
            }
1692

1693
            ItemKind::Use(ref view_path) => {
1694
                match view_path.node {
1695
                    ast::ViewPathList(ref prefix, ref items) => {
1696 1697 1698 1699 1700
                        // 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) {
1701 1702
                                Ok(binding) => {
                                    let def = binding.def().unwrap();
1703
                                    self.record_def(item.id, PathResolution::new(def));
1704
                                }
1705 1706
                                Err(true) => self.record_def(item.id, err_path_resolution()),
                                Err(false) => {
1707 1708 1709 1710
                                    resolve_error(self,
                                                  prefix.span,
                                                  ResolutionError::FailedToResolve(
                                                      &path_names_to_string(prefix, 0)));
1711
                                    self.record_def(item.id, err_path_resolution());
1712
                                }
1713 1714 1715 1716
                            }
                        }
                    }
                    _ => {}
W
we 已提交
1717 1718 1719
                }
            }

1720
            ItemKind::ExternCrate(_) => {
1721
                // do nothing, these are just around to be encoded
1722
            }
1723 1724

            ItemKind::Mac(_) => panic!("unexpanded macro in resolve!"),
1725 1726 1727
        }
    }

1728
    fn with_type_parameter_rib<'b, F>(&'b mut self, type_parameters: TypeParameters<'a, 'b>, f: F)
C
corentih 已提交
1729
        where F: FnOnce(&mut Resolver)
J
Jorge Aparicio 已提交
1730
    {
1731
        match type_parameters {
1732
            HasTypeParameters(generics, space, rib_kind) => {
1733
                let mut function_type_rib = Rib::new(rib_kind);
1734
                let mut seen_bindings = HashSet::new();
D
Daniel Micay 已提交
1735
                for (index, type_parameter) in generics.ty_params.iter().enumerate() {
1736
                    let name = type_parameter.ident.name;
1737
                    debug!("with_type_parameter_rib: {}", type_parameter.id);
1738

1739
                    if seen_bindings.contains(&name) {
1740 1741
                        resolve_error(self,
                                      type_parameter.span,
C
corentih 已提交
1742
                                      ResolutionError::NameAlreadyUsedInTypeParameterList(name));
1743
                    }
1744
                    seen_bindings.insert(name);
1745

1746
                    // plain insert (no renaming)
1747
                    let def_id = self.definitions.local_def_id(type_parameter.id);
1748
                    let def = Def::TyParam(space, index as u32, def_id, name);
1749
                    function_type_rib.bindings.insert(ast::Ident::with_empty_ctxt(name), def);
1750
                }
1751
                self.type_ribs.push(function_type_rib);
1752 1753
            }

B
Brian Anderson 已提交
1754
            NoTypeParameters => {
1755 1756 1757 1758
                // Nothing to do.
            }
        }

A
Alex Crichton 已提交
1759
        f(self);
1760

J
Jeffrey Seyfried 已提交
1761 1762
        if let HasTypeParameters(..) = type_parameters {
            self.type_ribs.pop();
1763 1764 1765
        }
    }

C
corentih 已提交
1766 1767
    fn with_label_rib<F>(&mut self, f: F)
        where F: FnOnce(&mut Resolver)
J
Jorge Aparicio 已提交
1768
    {
1769
        self.label_ribs.push(Rib::new(NormalRibKind));
A
Alex Crichton 已提交
1770
        f(self);
J
Jeffrey Seyfried 已提交
1771
        self.label_ribs.pop();
1772
    }
1773

C
corentih 已提交
1774 1775
    fn with_constant_rib<F>(&mut self, f: F)
        where F: FnOnce(&mut Resolver)
J
Jorge Aparicio 已提交
1776
    {
1777 1778
        self.value_ribs.push(Rib::new(ConstantItemRibKind));
        self.type_ribs.push(Rib::new(ConstantItemRibKind));
A
Alex Crichton 已提交
1779
        f(self);
J
Jeffrey Seyfried 已提交
1780 1781
        self.type_ribs.pop();
        self.value_ribs.pop();
1782 1783
    }

1784 1785 1786 1787
    fn resolve_function(&mut self,
                        rib_kind: RibKind<'a>,
                        declaration: &FnDecl,
                        block: &Block) {
1788
        // Create a value rib for the function.
1789
        self.value_ribs.push(Rib::new(rib_kind));
1790

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

1794 1795 1796
        // Add each argument to the rib.
        let mut bindings_list = HashMap::new();
        for argument in &declaration.inputs {
1797
            self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
1798

J
Jonas Schievink 已提交
1799
            self.visit_ty(&argument.ty);
1800

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

1805
        // Resolve the function body.
1806
        self.visit_block(block);
1807

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

J
Jeffrey Seyfried 已提交
1810 1811
        self.label_ribs.pop();
        self.value_ribs.pop();
1812 1813
    }

F
Felix S. Klock II 已提交
1814
    fn resolve_trait_reference(&mut self,
N
Nick Cameron 已提交
1815
                               id: NodeId,
1816
                               trait_path: &Path,
1817
                               path_depth: usize)
1818
                               -> Result<PathResolution, ()> {
1819
        self.resolve_path(id, trait_path, path_depth, TypeNS).and_then(|path_res| {
1820
            if let Def::Trait(_) = path_res.base_def {
1821 1822 1823
                debug!("(resolving trait) found trait def: {:?}", path_res);
                Ok(path_res)
            } else {
N
Nick Cameron 已提交
1824 1825 1826
                let mut err =
                    resolve_struct_error(self,
                                  trait_path.span,
J
Jonas Schievink 已提交
1827
                                  ResolutionError::IsNotATrait(&path_names_to_string(trait_path,
N
Nick Cameron 已提交
1828
                                                                                      path_depth)));
1829 1830

                // If it's a typedef, give a note
1831
                if let Def::TyAlias(..) = path_res.base_def {
1832
                    let trait_name = trait_path.segments.last().unwrap().identifier.name;
1833 1834
                    err.span_label(trait_path.span,
                                   &format!("`{}` is not a trait", trait_name));
1835 1836 1837 1838 1839 1840 1841

                    let definition_site = {
                        let segments = &trait_path.segments;
                        if trait_path.global {
                            self.resolve_crate_relative_path(trait_path.span, segments, TypeNS)
                        } else {
                            self.resolve_module_relative_path(trait_path.span, segments, TypeNS)
1842
                        }.map(|binding| binding.span).unwrap_or(syntax_pos::DUMMY_SP)
1843 1844
                    };

1845
                    if definition_site != syntax_pos::DUMMY_SP {
1846 1847
                        err.span_label(definition_site,
                                       &format!("type aliases cannot be used for traits"));
V
vegai 已提交
1848
                    }
1849
                }
N
Nick Cameron 已提交
1850
                err.emit();
1851
                Err(true)
1852
            }
1853 1854
        }).map_err(|error_reported| {
            if error_reported { return }
1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876

            // 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);
1877
        })
1878 1879
    }

1880 1881
    fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
        where F: FnOnce(&mut Resolver) -> T
J
Jorge Aparicio 已提交
1882
    {
1883 1884 1885 1886 1887 1888 1889
        // 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 已提交
1890
    fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
1891
        where F: FnOnce(&mut Resolver, Option<DefId>) -> T
J
Jorge Aparicio 已提交
1892
    {
1893
        let mut new_val = None;
1894
        let mut new_id = None;
E
Eduard Burtescu 已提交
1895
        if let Some(trait_ref) = opt_trait_ref {
1896
            if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
C
corentih 已提交
1897 1898
                                                               &trait_ref.path,
                                                               0) {
1899 1900 1901 1902
                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());
1903 1904
            } else {
                self.record_def(trait_ref.ref_id, err_path_resolution());
1905
            }
1906
            visit::walk_trait_ref(self, trait_ref);
1907
        }
1908
        let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
1909
        let result = f(self, new_id);
1910 1911 1912 1913
        self.current_trait_ref = original_trait_ref;
        result
    }

1914 1915 1916 1917 1918 1919
    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....)
1920
        self_type_rib.bindings.insert(keywords::SelfType.ident(), self_def);
1921 1922
        self.type_ribs.push(self_type_rib);
        f(self);
J
Jeffrey Seyfried 已提交
1923
        self.type_ribs.pop();
1924 1925
    }

F
Felix S. Klock II 已提交
1926
    fn resolve_implementation(&mut self,
1927 1928 1929
                              generics: &Generics,
                              opt_trait_reference: &Option<TraitRef>,
                              self_type: &Ty,
1930
                              item_id: NodeId,
1931
                              impl_items: &[ImplItem]) {
1932
        // If applicable, create a rib for the type parameters.
1933
        self.with_type_parameter_rib(HasTypeParameters(generics,
1934
                                                       TypeSpace,
1935
                                                       ItemRibKind),
1936
                                     |this| {
1937
            // Resolve the type parameters.
1938
            this.visit_generics(generics);
1939

1940
            // Resolve the trait reference, if necessary.
1941
            this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
1942
                // Resolve the self type.
1943
                this.visit_ty(self_type);
1944

1945
                this.with_self_rib(Def::SelfTy(trait_id, Some(item_id)), |this| {
1946 1947
                    this.with_current_self_type(self_type, |this| {
                        for impl_item in impl_items {
1948
                            this.resolve_visibility(&impl_item.vis);
1949
                            match impl_item.node {
1950
                                ImplItemKind::Const(..) => {
1951
                                    // If this is a trait impl, ensure the const
1952
                                    // exists in trait
1953
                                    this.check_trait_item(impl_item.ident.name,
1954 1955
                                                          impl_item.span,
                                        |n, s| ResolutionError::ConstNotMemberOfTrait(n, s));
1956
                                    visit::walk_impl_item(this, impl_item);
1957
                                }
1958
                                ImplItemKind::Method(ref sig, _) => {
1959 1960
                                    // If this is a trait impl, ensure the method
                                    // exists in trait
1961
                                    this.check_trait_item(impl_item.ident.name,
1962 1963
                                                          impl_item.span,
                                        |n, s| ResolutionError::MethodNotMemberOfTrait(n, s));
1964 1965 1966 1967 1968 1969

                                    // We also need a new scope for the method-
                                    // specific type parameters.
                                    let type_parameters =
                                        HasTypeParameters(&sig.generics,
                                                          FnSpace,
V
Vadim Petrochenkov 已提交
1970
                                                          MethodRibKind(!sig.decl.has_self()));
1971
                                    this.with_type_parameter_rib(type_parameters, |this| {
1972
                                        visit::walk_impl_item(this, impl_item);
1973 1974
                                    });
                                }
1975
                                ImplItemKind::Type(ref ty) => {
1976
                                    // If this is a trait impl, ensure the type
1977
                                    // exists in trait
1978
                                    this.check_trait_item(impl_item.ident.name,
1979 1980
                                                          impl_item.span,
                                        |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
1981

1982 1983
                                    this.visit_ty(ty);
                                }
1984
                                ImplItemKind::Macro(_) => panic!("unexpanded macro in resolve!"),
1985
                            }
1986
                        }
1987
                    });
1988 1989
                });
            });
1990
        });
1991 1992
    }

1993
    fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
C
corentih 已提交
1994 1995 1996 1997
        where F: FnOnce(Name, &str) -> ResolutionError
    {
        // If there is a TraitRef in scope for an impl, then the method must be in the
        // trait.
1998
        if let Some((did, ref trait_ref)) = self.current_trait_ref {
1999
            if !self.trait_item_map.contains_key(&(name, did)) {
2000
                let path_str = path_names_to_string(&trait_ref.path, 0);
J
Jonas Schievink 已提交
2001
                resolve_error(self, span, err(name, &path_str));
2002 2003 2004 2005
            }
        }
    }

E
Eduard Burtescu 已提交
2006
    fn resolve_local(&mut self, local: &Local) {
2007
        // Resolve the type.
2008
        walk_list!(self, visit_ty, &local.ty);
2009

2010
        // Resolve the initializer.
2011
        walk_list!(self, visit_expr, &local.init);
2012 2013

        // Resolve the pattern.
2014
        self.resolve_pattern(&local.pat, PatternSource::Let, &mut HashMap::new());
2015 2016
    }

J
John Clements 已提交
2017 2018 2019 2020
    // 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 已提交
2021
    fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2022 2023 2024 2025 2026 2027 2028 2029 2030
        let mut binding_map = HashMap::new();

        pat.walk(&mut |pat| {
            if let PatKind::Ident(binding_mode, ident, ref sub_pat) = pat.node {
                if sub_pat.is_some() || match self.def_map.get(&pat.id) {
                    Some(&PathResolution { base_def: Def::Local(..), .. }) => true,
                    _ => false,
                } {
                    let binding_info = BindingInfo { span: ident.span, binding_mode: binding_mode };
2031
                    binding_map.insert(ident.node, binding_info);
2032 2033 2034
                }
            }
            true
2035
        });
2036 2037

        binding_map
2038 2039
    }

J
John Clements 已提交
2040 2041
    // 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 已提交
2042
    fn check_consistent_bindings(&mut self, arm: &Arm) {
2043
        if arm.pats.is_empty() {
C
corentih 已提交
2044
            return;
2045
        }
J
Jonas Schievink 已提交
2046
        let map_0 = self.binding_mode_map(&arm.pats[0]);
D
Daniel Micay 已提交
2047
        for (i, p) in arm.pats.iter().enumerate() {
J
Jonas Schievink 已提交
2048
            let map_i = self.binding_mode_map(&p);
2049

2050
            for (&key, &binding_0) in &map_0 {
2051
                match map_i.get(&key) {
C
corentih 已提交
2052
                    None => {
2053 2054
                        let error = ResolutionError::VariableNotBoundInPattern(key.name, 1, i + 1);
                        resolve_error(self, p.span, error);
C
corentih 已提交
2055 2056 2057 2058 2059
                    }
                    Some(binding_i) => {
                        if binding_0.binding_mode != binding_i.binding_mode {
                            resolve_error(self,
                                          binding_i.span,
2060
                                          ResolutionError::VariableBoundWithDifferentMode(key.name,
C
corentih 已提交
2061 2062
                                                                                          i + 1));
                        }
2063
                    }
2064 2065 2066
                }
            }

2067
            for (&key, &binding) in &map_i {
2068
                if !map_0.contains_key(&key) {
2069 2070
                    resolve_error(self,
                                  binding.span,
2071
                                  ResolutionError::VariableNotBoundInPattern(key.name, i + 1, 1));
2072 2073 2074
                }
            }
        }
2075 2076
    }

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

2080
        let mut bindings_list = HashMap::new();
2081
        for pattern in &arm.pats {
2082
            self.resolve_pattern(&pattern, PatternSource::Match, &mut bindings_list);
2083 2084
        }

2085 2086 2087 2088
        // This has to happen *after* we determine which
        // pat_idents are variants
        self.check_consistent_bindings(arm);

2089
        walk_list!(self, visit_expr, &arm.guard);
J
Jonas Schievink 已提交
2090
        self.visit_expr(&arm.body);
2091

J
Jeffrey Seyfried 已提交
2092
        self.value_ribs.pop();
2093 2094
    }

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

2101
        let mut num_macro_definition_ribs = 0;
2102 2103
        if let Some(anonymous_module) = anonymous_module {
            debug!("(resolving block) found anonymous module, moving down");
2104 2105
            self.value_ribs.push(Rib::new(ModuleRibKind(anonymous_module)));
            self.type_ribs.push(Rib::new(ModuleRibKind(anonymous_module)));
2106 2107 2108
            self.current_module = anonymous_module;
        } else {
            self.value_ribs.push(Rib::new(NormalRibKind));
2109 2110 2111
        }

        // Descend into the block.
2112 2113
        for stmt in &block.stmts {
            if let Some(marks) = self.macros_at_scope.remove(&stmt.id) {
2114
                num_macro_definition_ribs += marks.len() as u32;
2115 2116
                for mark in marks {
                    self.value_ribs.push(Rib::new(MacroDefinition(mark)));
2117
                    self.label_ribs.push(Rib::new(MacroDefinition(mark)));
2118 2119 2120 2121 2122
                }
            }

            self.visit_stmt(stmt);
        }
2123 2124

        // Move back up.
J
Jeffrey Seyfried 已提交
2125
        self.current_module = orig_module;
2126
        for _ in 0 .. num_macro_definition_ribs {
2127
            self.value_ribs.pop();
2128
            self.label_ribs.pop();
2129
        }
2130
        self.value_ribs.pop();
J
Jeffrey Seyfried 已提交
2131 2132
        if let Some(_) = anonymous_module {
            self.type_ribs.pop();
G
Garming Sam 已提交
2133
        }
2134
        debug!("(resolving block) leaving block");
2135 2136
    }

F
Felix S. Klock II 已提交
2137
    fn resolve_type(&mut self, ty: &Ty) {
2138
        match ty.node {
2139
            TyKind::Path(ref maybe_qself, ref path) => {
2140
                // This is a path in the type namespace. Walk through scopes
2141
                // looking for it.
2142 2143
                if let Some(def) = self.resolve_possibly_assoc_item(ty.id, maybe_qself.as_ref(),
                                                                    path, TypeNS) {
2144
                    match def.base_def {
2145
                        Def::Mod(..) if def.depth == 0 => {
2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
                            self.session.span_err(path.span, "expected type, found module");
                            self.record_def(ty.id, err_path_resolution());
                        }
                        _ => {
                            // Write the result into the def map.
                            debug!("(resolving type) writing resolution for `{}` (id {}) = {:?}",
                                   path_names_to_string(path, 0), ty.id, def);
                            self.record_def(ty.id, def);
                        }
                    }
2156 2157
                } else {
                    self.record_def(ty.id, err_path_resolution());
2158

2159 2160 2161 2162
                    // Keep reporting some errors even if they're ignored above.
                    if let Err(true) = self.resolve_path(ty.id, path, 0, TypeNS) {
                        // `resolve_path` already reported the error
                    } else {
2163 2164 2165 2166
                        let kind = if maybe_qself.is_some() {
                            "associated type"
                        } else {
                            "type name"
2167
                        };
2168

C
corentih 已提交
2169 2170 2171
                        let is_invalid_self_type_name = path.segments.len() > 0 &&
                                                        maybe_qself.is_none() &&
                                                        path.segments[0].identifier.name ==
2172
                                                        keywords::SelfType.name();
G
Guillaume Gomez 已提交
2173
                        if is_invalid_self_type_name {
2174 2175
                            resolve_error(self,
                                          ty.span,
2176
                                          ResolutionError::SelfUsedOutsideImplOrTrait);
2177
                        } else {
2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204
                            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 已提交
2205
                        }
2206 2207
                    }
                }
2208
            }
2209
            _ => {}
2210
        }
2211
        // Resolve embedded types.
2212
        visit::walk_ty(self, ty);
2213 2214
    }

2215 2216 2217 2218 2219
    fn fresh_binding(&mut self,
                     ident: &ast::SpannedIdent,
                     pat_id: NodeId,
                     outer_pat_id: NodeId,
                     pat_src: PatternSource,
2220
                     bindings: &mut HashMap<ast::Ident, NodeId>)
2221 2222
                     -> PathResolution {
        // Add the binding to the local ribs, if it
2223 2224
        // doesn't already exist in the bindings map. (We
        // must not add it if it's in the bindings map
2225 2226
        // because that breaks the assumptions later
        // passes make about or-patterns.)
2227
        let mut def = Def::Local(self.definitions.local_def_id(pat_id), pat_id);
2228
        match bindings.get(&ident.node).cloned() {
2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247
            Some(id) if id == outer_pat_id => {
                // `Variant(a, a)`, error
                resolve_error(
                    self,
                    ident.span,
                    ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
                        &ident.node.name.as_str())
                );
            }
            Some(..) if pat_src == PatternSource::FnParam => {
                // `fn f(a: u8, a: u8)`, error
                resolve_error(
                    self,
                    ident.span,
                    ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
                        &ident.node.name.as_str())
                );
            }
            Some(..) if pat_src == PatternSource::Match => {
2248 2249
                // `Variant1(a) | Variant2(a)`, ok
                // Reuse definition from the first `a`.
2250
                def = self.value_ribs.last_mut().unwrap().bindings[&ident.node];
2251 2252 2253 2254 2255 2256
            }
            Some(..) => {
                span_bug!(ident.span, "two bindings with the same name from \
                                       unexpected pattern source {:?}", pat_src);
            }
            None => {
2257
                // A completely fresh binding, add to the lists if it's valid.
2258
                if ident.node.name != keywords::Invalid.name() {
2259 2260
                    bindings.insert(ident.node, outer_pat_id);
                    self.value_ribs.last_mut().unwrap().bindings.insert(ident.node, def);
2261
                }
2262
            }
2263
        }
2264

2265
        PathResolution::new(def)
2266
    }
2267

2268
    fn resolve_pattern_path<ExpectedFn>(&mut self,
2269 2270 2271 2272 2273 2274
                                        pat_id: NodeId,
                                        qself: Option<&QSelf>,
                                        path: &Path,
                                        namespace: Namespace,
                                        expected_fn: ExpectedFn,
                                        expected_what: &str)
2275 2276
        where ExpectedFn: FnOnce(Def) -> bool
    {
2277 2278 2279
        let resolution = if let Some(resolution) = self.resolve_possibly_assoc_item(pat_id,
                                                                        qself, path, namespace) {
            if resolution.depth == 0 {
2280
                if expected_fn(resolution.base_def) || resolution.base_def == Def::Err {
2281
                    resolution
2282
                } else {
2283 2284 2285 2286 2287 2288
                    resolve_error(
                        self,
                        path.span,
                        ResolutionError::PatPathUnexpected(expected_what,
                                                           resolution.kind_name(), path)
                    );
2289 2290
                    err_path_resolution()
                }
2291 2292 2293 2294
            } else {
                // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
                // or `<T>::A::B`. If `B` should be resolved in value namespace then
                // it needs to be added to the trait map.
2295 2296 2297 2298
                if namespace == ValueNS {
                    let item_name = path.segments.last().unwrap().identifier.name;
                    let traits = self.get_traits_containing_item(item_name);
                    self.trait_map.insert(pat_id, traits);
2299
                }
2300
                resolution
2301
            }
2302 2303 2304 2305 2306 2307 2308 2309 2310
        } else {
            if let Err(false) = self.resolve_path(pat_id, path, 0, namespace) {
                resolve_error(
                    self,
                    path.span,
                    ResolutionError::PatPathUnresolved(expected_what, path)
                );
            }
            err_path_resolution()
2311
        };
2312

2313 2314 2315 2316 2317 2318 2319 2320
        self.record_def(pat_id, resolution);
    }

    fn resolve_pattern(&mut self,
                       pat: &Pat,
                       pat_src: PatternSource,
                       // Maps idents to the node ID for the
                       // outermost pattern that binds them.
2321
                       bindings: &mut HashMap<ast::Ident, NodeId>) {
2322
        // Visit all direct subpatterns of this pattern.
2323 2324 2325 2326 2327 2328
        let outer_pat_id = pat.id;
        pat.walk(&mut |pat| {
            match pat.node {
                PatKind::Ident(bmode, ref ident, ref opt_pat) => {
                    // First try to resolve the identifier as some existing
                    // entity, then fall back to a fresh binding.
2329 2330 2331
                    let resolution = self.resolve_identifier(ident.node, ValueNS, true)
                                         .map(|local_def| PathResolution::new(local_def.def))
                                         .and_then(|resolution| {
2332 2333
                        let always_binding = !pat_src.is_refutable() || opt_pat.is_some() ||
                                             bmode != BindingMode::ByValue(Mutability::Immutable);
2334
                        match resolution.base_def {
2335 2336 2337
                            Def::Struct(..) | Def::Variant(..) |
                            Def::Const(..) | Def::AssociatedConst(..) if !always_binding => {
                                // A constant, unit variant, etc pattern.
2338
                                Some(resolution)
2339
                            }
2340 2341 2342
                            Def::Struct(..) | Def::Variant(..) |
                            Def::Const(..) | Def::AssociatedConst(..) | Def::Static(..) => {
                                // A fresh binding that shadows something unacceptable.
2343
                                resolve_error(
2344
                                    self,
2345 2346
                                    ident.span,
                                    ResolutionError::BindingShadowsSomethingUnacceptable(
2347
                                        pat_src.descr(), resolution.kind_name(), ident.node.name)
2348
                                );
2349
                                None
2350
                            }
2351
                            Def::Local(..) | Def::Upvar(..) | Def::Fn(..) | Def::Err => {
2352 2353
                                // These entities are explicitly allowed
                                // to be shadowed by fresh bindings.
2354
                                None
2355 2356 2357 2358
                            }
                            def => {
                                span_bug!(ident.span, "unexpected definition for an \
                                                       identifier in pattern {:?}", def);
2359
                            }
2360
                        }
2361
                    }).unwrap_or_else(|| {
2362
                        self.fresh_binding(ident, pat.id, outer_pat_id, pat_src, bindings)
2363
                    });
2364 2365

                    self.record_def(pat.id, resolution);
2366 2367
                }

2368 2369 2370
                PatKind::TupleStruct(ref path, _, _) => {
                    self.resolve_pattern_path(pat.id, None, path, ValueNS, |def| {
                        match def {
2371
                            Def::Struct(..) | Def::Variant(..) => true,
2372
                            _ => false,
2373
                        }
2374 2375 2376
                    }, "variant or struct");
                }

2377 2378
                PatKind::Path(ref qself, ref path) => {
                    self.resolve_pattern_path(pat.id, qself.as_ref(), path, ValueNS, |def| {
2379 2380
                        match def {
                            Def::Struct(..) | Def::Variant(..) |
2381
                            Def::Const(..) | Def::AssociatedConst(..) => true,
2382
                            _ => false,
2383
                        }
2384
                    }, "variant, struct or constant");
2385 2386
                }

2387 2388 2389 2390
                PatKind::Struct(ref path, _, _) => {
                    self.resolve_pattern_path(pat.id, None, path, TypeNS, |def| {
                        match def {
                            Def::Struct(..) | Def::Variant(..) |
2391
                            Def::TyAlias(..) | Def::AssociatedTy(..) => true,
2392 2393 2394
                            _ => false,
                        }
                    }, "variant, struct or type alias");
2395
                }
2396 2397

                _ => {}
2398
            }
2399
            true
2400
        });
2401

2402
        visit::walk_pat(self, pat);
2403 2404
    }

2405 2406 2407
    /// Handles paths that may refer to associated items
    fn resolve_possibly_assoc_item(&mut self,
                                   id: NodeId,
2408
                                   maybe_qself: Option<&QSelf>,
2409
                                   path: &Path,
J
Jeffrey Seyfried 已提交
2410
                                   namespace: Namespace)
2411
                                   -> Option<PathResolution> {
2412 2413
        let max_assoc_types;

2414
        match maybe_qself {
2415 2416
            Some(qself) => {
                if qself.position == 0 {
2417 2418 2419
                    // FIXME: Create some fake resolution that can't possibly be a type.
                    return Some(PathResolution {
                        base_def: Def::Mod(self.definitions.local_def_id(ast::CRATE_NODE_ID)),
2420
                        depth: path.segments.len(),
2421
                    });
2422 2423 2424 2425 2426 2427 2428 2429
                }
                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();
            }
2430 2431 2432
        }

        let mut resolution = self.with_no_errors(|this| {
2433
            this.resolve_path(id, path, 0, namespace).ok()
2434 2435 2436 2437 2438 2439
        });
        for depth in 1..max_assoc_types {
            if resolution.is_some() {
                break;
            }
            self.with_no_errors(|this| {
2440 2441 2442 2443 2444 2445
                let partial_resolution = this.resolve_path(id, path, depth, TypeNS).ok();
                if let Some(Def::Mod(..)) = partial_resolution.map(|r| r.base_def) {
                    // Modules cannot have associated items
                } else {
                    resolution = partial_resolution;
                }
2446 2447
            });
        }
2448
        resolution
2449 2450
    }

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

2457
        let span = path.span;
C
corentih 已提交
2458
        let segments = &path.segments[..path.segments.len() - path_depth];
2459

2460
        let mk_res = |def| PathResolution { base_def: def, depth: path_depth };
2461

2462
        if path.global {
2463 2464
            let binding = self.resolve_crate_relative_path(span, segments, namespace);
            return binding.map(|binding| mk_res(binding.def().unwrap()));
2465 2466
        }

2467
        // Try to find a path to an item in a module.
2468
        let last_ident = segments.last().unwrap().identifier;
V
Cleanup  
Vadim Petrochenkov 已提交
2469 2470 2471 2472 2473 2474 2475
        // 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
2476
                        .get(&last_ident.name)
V
Cleanup  
Vadim Petrochenkov 已提交
2477 2478 2479 2480
                        .map_or(def, |prim_ty| Some(LocalDef::from_def(Def::PrimTy(*prim_ty)))),
                _ => def
            }
        };
2481

2482 2483 2484 2485 2486 2487 2488
        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 已提交
2489 2490
            //     u8::max_value() // OK, resolves to associated function <u8>::max_value,
            //                     // not to non-existent std::u8::max_value
2491 2492 2493 2494
            // }
            //
            // Such behavior is required for backward compatibility.
            // The same fallback is used when `a` resolves to nothing.
2495 2496
            let def = resolve_identifier_with_fallback(self, true).ok_or(false);
            return def.and_then(|def| self.adjust_local_def(def, span).ok_or(true)).map(mk_res);
N
Nick Cameron 已提交
2497
        }
2498

V
Cleanup  
Vadim Petrochenkov 已提交
2499
        let unqualified_def = resolve_identifier_with_fallback(self, false);
2500 2501 2502
        let qualified_binding = self.resolve_module_relative_path(span, segments, namespace);
        match (qualified_binding, unqualified_def) {
            (Ok(binding), Some(ref ud)) if binding.def().unwrap() == ud.def => {
N
Nick Cameron 已提交
2503 2504
                self.session
                    .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
C
corentih 已提交
2505 2506
                              id,
                              span,
N
Nick Cameron 已提交
2507 2508 2509
                              "unnecessary qualification".to_string());
            }
            _ => {}
2510
        }
N
Nick Cameron 已提交
2511

2512
        qualified_binding.map(|binding| mk_res(binding.def().unwrap()))
2513 2514
    }

2515
    // Resolve a single identifier
F
Felix S. Klock II 已提交
2516
    fn resolve_identifier(&mut self,
2517
                          identifier: ast::Ident,
2518
                          namespace: Namespace,
2519
                          record_used: bool)
2520
                          -> Option<LocalDef> {
2521
        if identifier.name == keywords::Invalid.name() {
2522
            return None;
2523 2524
        }

2525 2526
        self.resolve_ident_in_lexical_scope(identifier, namespace, record_used)
            .map(LexicalScopeBinding::local_def)
2527 2528 2529
    }

    // Resolve a local definition, potentially adjusting for closures.
2530
    fn adjust_local_def(&mut self, local_def: LocalDef, span: Span) -> Option<Def> {
2531
        let ribs = match local_def.ribs {
C
corentih 已提交
2532 2533 2534
            Some((TypeNS, i)) => &self.type_ribs[i + 1..],
            Some((ValueNS, i)) => &self.value_ribs[i + 1..],
            _ => &[] as &[_],
2535 2536 2537
        };
        let mut def = local_def.def;
        match def {
2538
            Def::Upvar(..) => {
2539
                span_bug!(span, "unexpected {:?} in bindings", def)
2540
            }
2541
            Def::Local(_, node_id) => {
2542 2543
                for rib in ribs {
                    match rib.kind {
2544
                        NormalRibKind | ModuleRibKind(..) | MacroDefinition(..) => {
2545 2546 2547 2548
                            // Nothing to do. Continue.
                        }
                        ClosureRibKind(function_id) => {
                            let prev_def = def;
2549
                            let node_def_id = self.definitions.local_def_id(node_id);
2550

C
corentih 已提交
2551 2552 2553
                            let seen = self.freevars_seen
                                           .entry(function_id)
                                           .or_insert_with(|| NodeMap());
2554
                            if let Some(&index) = seen.get(&node_id) {
2555
                                def = Def::Upvar(node_def_id, node_id, index, function_id);
2556 2557
                                continue;
                            }
C
corentih 已提交
2558 2559 2560
                            let vec = self.freevars
                                          .entry(function_id)
                                          .or_insert_with(|| vec![]);
2561
                            let depth = vec.len();
C
corentih 已提交
2562 2563 2564 2565
                            vec.push(Freevar {
                                def: prev_def,
                                span: span,
                            });
2566

2567
                            def = Def::Upvar(node_def_id, node_id, depth, function_id);
2568 2569
                            seen.insert(node_id, depth);
                        }
2570
                        ItemRibKind | MethodRibKind(_) => {
2571 2572 2573
                            // This was an attempt to access an upvar inside a
                            // named function item. This is not allowed, so we
                            // report an error.
C
corentih 已提交
2574 2575 2576
                            resolve_error(self,
                                          span,
                                          ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
2577 2578 2579 2580
                            return None;
                        }
                        ConstantItemRibKind => {
                            // Still doesn't deal with upvars
C
corentih 已提交
2581 2582 2583
                            resolve_error(self,
                                          span,
                                          ResolutionError::AttemptToUseNonConstantValueInConstant);
2584 2585 2586 2587 2588
                            return None;
                        }
                    }
                }
            }
2589
            Def::TyParam(..) | Def::SelfTy(..) => {
2590 2591
                for rib in ribs {
                    match rib.kind {
2592
                        NormalRibKind | MethodRibKind(_) | ClosureRibKind(..) |
2593
                        ModuleRibKind(..) | MacroDefinition(..) => {
2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615
                            // 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);
2616 2617
    }

2618
    // resolve a "module-relative" path, e.g. a::b::c
F
Felix S. Klock II 已提交
2619
    fn resolve_module_relative_path(&mut self,
2620
                                    span: Span,
2621
                                    segments: &[ast::PathSegment],
2622
                                    namespace: Namespace)
2623 2624
                                    -> Result<&'a NameBinding<'a>,
                                              bool /* true if an error was reported */> {
C
corentih 已提交
2625 2626 2627 2628 2629 2630
        let module_path = segments.split_last()
                                  .unwrap()
                                  .1
                                  .iter()
                                  .map(|ps| ps.identifier.name)
                                  .collect::<Vec<_>>();
2631

2632
        let containing_module;
2633
        match self.resolve_module_path(&module_path, UseLexicalScope, span) {
2634 2635 2636 2637
            Failed(err) => {
                let (span, msg) = match err {
                    Some((span, msg)) => (span, msg),
                    None => {
2638
                        let msg = format!("Use of undeclared type or module `{}`",
2639
                                          names_to_string(&module_path));
2640
                        (span, msg)
2641 2642
                    }
                };
2643

J
Jonas Schievink 已提交
2644
                resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
2645
                return Err(true);
2646
            }
2647
            Indeterminate => return Err(false),
J
Jeffrey Seyfried 已提交
2648
            Success(resulting_module) => {
2649 2650 2651 2652
                containing_module = resulting_module;
            }
        }

2653
        let name = segments.last().unwrap().identifier.name;
2654
        let result = self.resolve_name_in_module(containing_module, name, namespace, false, true);
2655
        result.success().map(|binding| {
2656
            self.check_privacy(name, binding, span);
2657
            binding
2658
        }).ok_or(false)
2659 2660
    }

2661 2662
    /// Invariant: This must be called only during main resolution, not during
    /// import resolution.
2663 2664 2665 2666 2667 2668
    fn resolve_crate_relative_path<T>(&mut self, span: Span, segments: &[T], namespace: Namespace)
                                      -> Result<&'a NameBinding<'a>,
                                                bool /* true if an error was reported */>
        where T: Named,
    {
        let module_path = segments.split_last().unwrap().1.iter().map(T::name).collect::<Vec<_>>();
2669
        let root_module = self.graph_root;
2670

2671
        let containing_module;
2672
        match self.resolve_module_path_from_root(root_module,
2673
                                                 &module_path,
2674
                                                 0,
J
Jeffrey Seyfried 已提交
2675
                                                 span) {
2676 2677 2678 2679 2680
            Failed(err) => {
                let (span, msg) = match err {
                    Some((span, msg)) => (span, msg),
                    None => {
                        let msg = format!("Use of undeclared module `::{}`",
2681
                                          names_to_string(&module_path));
2682
                        (span, msg)
2683 2684 2685
                    }
                };

J
Jonas Schievink 已提交
2686
                resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
2687
                return Err(true);
2688 2689
            }

2690
            Indeterminate => return Err(false),
2691

J
Jeffrey Seyfried 已提交
2692
            Success(resulting_module) => {
2693 2694 2695 2696
                containing_module = resulting_module;
            }
        }

2697
        let name = segments.last().unwrap().name();
J
Jeffrey Seyfried 已提交
2698
        let result = self.resolve_name_in_module(containing_module, name, namespace, false, true);
2699
        result.success().map(|binding| {
2700
            self.check_privacy(name, binding, span);
2701
            binding
2702
        }).ok_or(false)
2703 2704
    }

C
corentih 已提交
2705 2706
    fn with_no_errors<T, F>(&mut self, f: F) -> T
        where F: FnOnce(&mut Resolver) -> T
J
Jorge Aparicio 已提交
2707
    {
2708
        self.emit_errors = false;
A
Alex Crichton 已提交
2709
        let rs = f(self);
2710 2711 2712 2713
        self.emit_errors = true;
        rs
    }

2714 2715
    // Calls `f` with a `Resolver` whose current lexical scope is `module`'s lexical scope,
    // i.e. the module's items and the prelude (unless the module is `#[no_implicit_prelude]`).
J
Jeffrey Seyfried 已提交
2716
    // FIXME #34673: This needs testing.
2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741
    pub fn with_module_lexical_scope<T, F>(&mut self, module: Module<'a>, f: F) -> T
        where F: FnOnce(&mut Resolver<'a>) -> T,
    {
        self.with_empty_ribs(|this| {
            this.value_ribs.push(Rib::new(ModuleRibKind(module)));
            this.type_ribs.push(Rib::new(ModuleRibKind(module)));
            f(this)
        })
    }

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

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

2742
    fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
2743
        fn extract_node_id(t: &Ty) -> Option<NodeId> {
2744
            match t.node {
2745 2746
                TyKind::Path(None, _) => Some(t.id),
                TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
2747 2748 2749 2750 2751 2752 2753
                // 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,
            }
        }

2754
        if let Some(node_id) = self.current_self_type.as_ref().and_then(extract_node_id) {
2755
            // Look for a field with the same name in the current self_type.
2756 2757 2758 2759 2760 2761 2762 2763
            if let Some(resolution) = self.def_map.get(&node_id) {
                match resolution.base_def {
                    Def::Enum(did) | Def::TyAlias(did) |
                    Def::Struct(did) | Def::Variant(_, did) if resolution.depth == 0 => {
                        if let Some(fields) = self.structs.get(&did) {
                            if fields.iter().any(|&field_name| name == field_name) {
                                return Field;
                            }
2764
                        }
2765
                    }
2766 2767
                    _ => {}
                }
2768
            }
2769 2770 2771
        }

        // Look for a method in the current trait.
2772
        if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
2773 2774
            if let Some(&is_static_method) = self.trait_item_map.get(&(name, trait_did)) {
                if is_static_method {
2775
                    return TraitMethod(path_names_to_string(&trait_ref.path, 0));
2776 2777
                } else {
                    return TraitItem;
2778 2779 2780 2781 2782 2783 2784
                }
            }
        }

        NoSuggestion
    }

2785
    fn find_best_match(&mut self, name: &str) -> SuggestionType {
2786
        if let Some(macro_name) = self.session.available_macros
2787
                                  .borrow().iter().find(|n| n.as_str() == name) {
2788 2789 2790
            return SuggestionType::Macro(format!("{}!", macro_name));
        }

2791 2792 2793
        let names = self.value_ribs
                    .iter()
                    .rev()
2794
                    .flat_map(|rib| rib.bindings.keys().map(|ident| &ident.name));
2795

2796
        if let Some(found) = find_best_match_for_name(names, name, None) {
J
Jonas Schievink 已提交
2797
            if name != found {
2798
                return SuggestionType::Function(found);
2799
            }
2800
        } SuggestionType::NotFound
2801 2802
    }

2803 2804
    fn resolve_labeled_block(&mut self, label: Option<ast::Ident>, id: NodeId, block: &Block) {
        if let Some(label) = label {
2805
            let def = Def::Label(id);
2806 2807 2808 2809 2810 2811 2812 2813 2814
            self.with_label_rib(|this| {
                this.label_ribs.last_mut().unwrap().bindings.insert(label, def);
                this.visit_block(block);
            });
        } else {
            self.visit_block(block);
        }
    }

2815
    fn resolve_expr(&mut self, expr: &Expr, parent: Option<&Expr>) {
P
Patrick Walton 已提交
2816 2817
        // First, record candidate traits for this expression if it could
        // result in the invocation of a method call.
2818 2819 2820

        self.record_candidate_traits_for_expr_if_necessary(expr);

2821
        // Next, resolve the node.
2822
        match expr.node {
2823
            ExprKind::Path(ref maybe_qself, ref path) => {
2824 2825
                // This is a local path in the value namespace. Walk through
                // scopes looking for it.
2826 2827
                if let Some(path_res) = self.resolve_possibly_assoc_item(expr.id,
                                                            maybe_qself.as_ref(), path, ValueNS) {
2828
                    // Check if struct variant
2829
                    let is_struct_variant = if let Def::Variant(_, variant_id) = path_res.base_def {
2830 2831 2832 2833 2834 2835
                        self.structs.contains_key(&variant_id)
                    } else {
                        false
                    };
                    if is_struct_variant {
                        let _ = self.structs.contains_key(&path_res.base_def.def_id());
2836
                        let path_name = path_names_to_string(path, 0);
2837

N
Nick Cameron 已提交
2838 2839
                        let mut err = resolve_struct_error(self,
                                        expr.span,
J
Jonas Schievink 已提交
2840
                                        ResolutionError::StructVariantUsedAsFunction(&path_name));
2841

C
corentih 已提交
2842
                        let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
2843 2844
                                          path_name);
                        if self.emit_errors {
2845
                            err.help(&msg);
2846
                        } else {
N
Nick Cameron 已提交
2847
                            err.span_help(expr.span, &msg);
2848
                        }
N
Nick Cameron 已提交
2849
                        err.emit();
2850
                        self.record_def(expr.id, err_path_resolution());
2851
                    } else {
2852
                        // Write the result into the def map.
2853
                        debug!("(resolving expr) resolved `{}`",
2854
                               path_names_to_string(path, 0));
2855

2856 2857
                        // Partial resolutions will need the set of traits in scope,
                        // so they can be completed during typeck.
2858
                        if path_res.depth != 0 {
2859
                            let method_name = path.segments.last().unwrap().identifier.name;
2860
                            let traits = self.get_traits_containing_item(method_name);
2861 2862 2863
                            self.trait_map.insert(expr.id, traits);
                        }

2864
                        self.record_def(expr.id, path_res);
2865
                    }
2866 2867 2868 2869 2870
                } 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.)
2871
                    let path_name = path_names_to_string(path, 0);
2872
                    let type_res = self.with_no_errors(|this| {
J
Jeffrey Seyfried 已提交
2873
                        this.resolve_path(expr.id, path, 0, TypeNS)
2874
                    });
2875 2876

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

2878
                    if let Ok(Def::Struct(..)) = type_res.map(|r| r.base_def) {
J
Jeffrey Seyfried 已提交
2879 2880
                        let error_variant =
                            ResolutionError::StructVariantUsedAsFunction(&path_name);
2881 2882 2883 2884 2885 2886
                        let mut err = resolve_struct_error(self, expr.span, error_variant);

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

                        if self.emit_errors {
2887
                            err.help(&msg);
2888 2889 2890 2891 2892 2893 2894 2895 2896
                        } else {
                            err.span_help(expr.span, &msg);
                        }
                        err.emit();
                    } else {
                        // Keep reporting some errors even if they're ignored above.
                        if let Err(true) = self.resolve_path(expr.id, path, 0, ValueNS) {
                            // `resolve_path` already reported the error
                        } else {
2897
                            let mut method_scope = false;
2898
                            let mut is_static = false;
2899 2900
                            self.value_ribs.iter().rev().all(|rib| {
                                method_scope = match rib.kind {
2901 2902 2903 2904
                                    MethodRibKind(is_static_) => {
                                        is_static = is_static_;
                                        true
                                    }
2905 2906 2907 2908 2909
                                    ItemRibKind | ConstantItemRibKind => false,
                                    _ => return true, // Keep advancing
                                };
                                false // Stop advancing
                            });
2910

2911
                            if method_scope &&
2912
                                    &path_name[..] == keywords::SelfValue.name().as_str() {
C
corentih 已提交
2913 2914 2915
                                resolve_error(self,
                                              expr.span,
                                              ResolutionError::SelfNotAvailableInStaticMethod);
2916 2917
                            } else {
                                let last_name = path.segments.last().unwrap().identifier.name;
2918 2919
                                let (mut msg, is_field) =
                                    match self.find_fallback_in_self_type(last_name) {
2920 2921 2922
                                    NoSuggestion => {
                                        // limit search to 5 to reduce the number
                                        // of stupid suggestions
2923
                                        (match self.find_best_match(&path_name) {
2924 2925 2926 2927 2928
                                            SuggestionType::Macro(s) => {
                                                format!("the macro `{}`", s)
                                            }
                                            SuggestionType::Function(s) => format!("`{}`", s),
                                            SuggestionType::NotFound => "".to_string(),
2929 2930 2931 2932 2933 2934 2935 2936
                                        }, false)
                                    }
                                    Field => {
                                        (if is_static && method_scope {
                                            "".to_string()
                                        } else {
                                            format!("`self.{}`", path_name)
                                        }, true)
2937
                                    }
2938
                                    TraitItem => (format!("to call `self.{}`", path_name), false),
2939
                                    TraitMethod(path_str) =>
2940
                                        (format!("to call `{}::{}`", path_str, path_name), false),
2941 2942
                                };

2943
                                let mut context =  UnresolvedNameContext::Other;
G
ggomez 已提交
2944
                                let mut def = Def::Err;
2945
                                if !msg.is_empty() {
2946 2947
                                    msg = format!(". Did you mean {}?", msg);
                                } else {
2948
                                    // we display a help message if this is a module
2949 2950 2951 2952
                                    let name_path = path.segments.iter()
                                                        .map(|seg| seg.identifier.name)
                                                        .collect::<Vec<_>>();

2953
                                    match self.resolve_module_path(&name_path[..],
J
Jeffrey Seyfried 已提交
2954 2955
                                                                   UseLexicalScope,
                                                                   expr.span) {
G
ggomez 已提交
2956 2957 2958 2959
                                        Success(e) => {
                                            if let Some(def_type) = e.def {
                                                def = def_type;
                                            }
2960
                                            context = UnresolvedNameContext::PathIsMod(parent);
2961 2962 2963
                                        },
                                        _ => {},
                                    };
2964
                                }
2965

2966 2967
                                resolve_error(self,
                                              expr.span,
2968 2969 2970 2971 2972 2973
                                              ResolutionError::UnresolvedName {
                                                  path: &path_name,
                                                  message: &msg,
                                                  context: context,
                                                  is_static_method: method_scope && is_static,
                                                  is_field: is_field,
G
ggomez 已提交
2974
                                                  def: def,
2975
                                              });
2976
                            }
V
Vincent Belliard 已提交
2977
                        }
2978 2979 2980
                    }
                }

2981
                visit::walk_expr(self, expr);
2982 2983
            }

2984
            ExprKind::Struct(ref path, _, _) => {
2985 2986 2987
                // 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 已提交
2988
                match self.resolve_path(expr.id, path, 0, TypeNS) {
2989 2990 2991
                    Ok(definition) => self.record_def(expr.id, definition),
                    Err(true) => self.record_def(expr.id, err_path_resolution()),
                    Err(false) => {
2992
                        debug!("(resolving expression) didn't find struct def",);
2993

2994 2995
                        resolve_error(self,
                                      path.span,
2996
                                      ResolutionError::DoesNotNameAStruct(
J
Jonas Schievink 已提交
2997
                                                                &path_names_to_string(path, 0))
2998
                                     );
2999
                        self.record_def(expr.id, err_path_resolution());
3000 3001 3002
                    }
                }

3003
                visit::walk_expr(self, expr);
3004 3005
            }

3006
            ExprKind::Loop(_, Some(label)) | ExprKind::While(_, _, Some(label)) => {
3007
                self.with_label_rib(|this| {
3008
                    let def = Def::Label(expr.id);
3009

3010
                    {
3011
                        let rib = this.label_ribs.last_mut().unwrap();
3012
                        rib.bindings.insert(label.node, def);
3013
                    }
3014

3015
                    visit::walk_expr(this, expr);
3016
                })
3017 3018
            }

3019
            ExprKind::Break(Some(label)) | ExprKind::Continue(Some(label)) => {
3020
                match self.search_label(label.node) {
3021
                    None => {
3022
                        self.record_def(expr.id, err_path_resolution());
3023
                        resolve_error(self,
3024 3025
                                      label.span,
                                      ResolutionError::UndeclaredLabel(&label.node.name.as_str()))
3026
                    }
3027
                    Some(def @ Def::Label(_)) => {
3028
                        // Since this def is a label, it is never read.
3029
                        self.record_def(expr.id, PathResolution::new(def))
3030 3031
                    }
                    Some(_) => {
3032
                        span_bug!(expr.span, "label wasn't mapped to a label def!")
3033 3034 3035
                    }
                }
            }
3036 3037 3038 3039 3040

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

                self.value_ribs.push(Rib::new(NormalRibKind));
3041
                self.resolve_pattern(pattern, PatternSource::IfLet, &mut HashMap::new());
3042 3043 3044 3045 3046 3047 3048 3049 3050
                self.visit_block(if_block);
                self.value_ribs.pop();

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

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

3053
                self.resolve_labeled_block(label.map(|l| l.node), expr.id, block);
3054 3055 3056 3057 3058 3059 3060

                self.value_ribs.pop();
            }

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

3063
                self.resolve_labeled_block(label.map(|l| l.node), expr.id, block);
3064 3065 3066 3067 3068

                self.value_ribs.pop();
            }

            ExprKind::Field(ref subexpression, _) => {
3069 3070
                self.resolve_expr(subexpression, Some(expr));
            }
3071
            ExprKind::MethodCall(_, ref types, ref arguments) => {
3072 3073 3074 3075 3076 3077 3078 3079 3080
                let mut arguments = arguments.iter();
                self.resolve_expr(arguments.next().unwrap(), Some(expr));
                for argument in arguments {
                    self.resolve_expr(argument, None);
                }
                for ty in types.iter() {
                    self.visit_ty(ty);
                }
            }
3081

B
Brian Anderson 已提交
3082
            _ => {
3083
                visit::walk_expr(self, expr);
3084 3085 3086 3087
            }
        }
    }

E
Eduard Burtescu 已提交
3088
    fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3089
        match expr.node {
3090
            ExprKind::Field(_, name) => {
3091 3092 3093 3094
                // 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.
3095
                let traits = self.get_traits_containing_item(name.node.name);
3096
                self.trait_map.insert(expr.id, traits);
3097
            }
3098
            ExprKind::MethodCall(name, _, _) => {
C
corentih 已提交
3099
                debug!("(recording candidate traits for expr) recording traits for {}",
3100
                       expr.id);
3101
                let traits = self.get_traits_containing_item(name.node.name);
3102
                self.trait_map.insert(expr.id, traits);
3103
            }
3104
            _ => {
3105 3106 3107 3108 3109
                // Nothing to do.
            }
        }
    }

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

S
Seo Sanghyeon 已提交
3113 3114 3115 3116
        fn add_trait_info(found_traits: &mut Vec<TraitCandidate>,
                          trait_def_id: DefId,
                          import_id: Option<NodeId>,
                          name: Name) {
3117
            debug!("(adding trait info) found trait {:?} for method '{}'",
C
corentih 已提交
3118 3119
                   trait_def_id,
                   name);
S
Seo Sanghyeon 已提交
3120 3121 3122 3123
            found_traits.push(TraitCandidate {
                def_id: trait_def_id,
                import_id: import_id,
            });
E
Eduard Burtescu 已提交
3124
        }
3125

3126
        let mut found_traits = Vec::new();
J
Jeffrey Seyfried 已提交
3127 3128 3129
        // Look for the current trait.
        if let Some((trait_def_id, _)) = self.current_trait_ref {
            if self.trait_item_map.contains_key(&(name, trait_def_id)) {
S
Seo Sanghyeon 已提交
3130
                add_trait_info(&mut found_traits, trait_def_id, None, name);
E
Eduard Burtescu 已提交
3131
            }
J
Jeffrey Seyfried 已提交
3132
        }
3133

J
Jeffrey Seyfried 已提交
3134 3135
        let mut search_module = self.current_module;
        loop {
E
Eduard Burtescu 已提交
3136
            // Look for trait children.
3137
            let mut search_in_module = |this: &mut Self, module: Module<'a>| {
J
Jeffrey Seyfried 已提交
3138 3139 3140
                let mut traits = module.traits.borrow_mut();
                if traits.is_none() {
                    let mut collected_traits = Vec::new();
3141
                    module.for_each_child(|name, ns, binding| {
J
Jeffrey Seyfried 已提交
3142 3143
                        if ns != TypeNS { return }
                        if let Some(Def::Trait(_)) = binding.def() {
3144
                            collected_traits.push((name, binding));
J
Jeffrey Seyfried 已提交
3145 3146 3147
                        }
                    });
                    *traits = Some(collected_traits.into_boxed_slice());
3148
                }
J
Jeffrey Seyfried 已提交
3149

3150
                for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
J
Jeffrey Seyfried 已提交
3151
                    let trait_def_id = binding.def().unwrap().def_id();
3152
                    if this.trait_item_map.contains_key(&(name, trait_def_id)) {
S
Seo Sanghyeon 已提交
3153 3154 3155
                        let mut import_id = None;
                        if let NameBindingKind::Import { directive, .. } = binding.kind {
                            let id = directive.id;
3156
                            this.maybe_unused_trait_imports.insert(id);
S
Seo Sanghyeon 已提交
3157 3158 3159
                            import_id = Some(id);
                        }
                        add_trait_info(&mut found_traits, trait_def_id, import_id, name);
3160
                        this.record_use(trait_name, binding);
J
Jeffrey Seyfried 已提交
3161 3162 3163
                    }
                }
            };
3164
            search_in_module(self, search_module);
3165

3166
            match search_module.parent_link {
3167
                NoParentLink | ModuleParentLink(..) => {
3168 3169 3170
                    if !search_module.no_implicit_prelude.get() {
                        self.prelude.map(|prelude| search_in_module(self, prelude));
                    }
3171 3172
                    break;
                }
E
Eduard Burtescu 已提交
3173
                BlockParentLink(parent_module, _) => {
3174
                    search_module = parent_module;
3175
                }
E
Eduard Burtescu 已提交
3176
            }
3177 3178
        }

E
Eduard Burtescu 已提交
3179
        found_traits
3180 3181
    }

3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201
    /// 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() {
3202
            self.populate_module_if_necessary(in_module);
3203 3204 3205 3206 3207 3208 3209 3210 3211 3212

            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
3213
                        let ident = ast::Ident::with_empty_ctxt(name);
3214 3215 3216 3217 3218
                        let params = PathParameters::none();
                        let segment = PathSegment {
                            identifier: ident,
                            parameters: params,
                        };
3219
                        let span = name_binding.span;
3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233
                        let mut segms = path_segments.clone();
                        segms.push(segment);
                        let path = Path {
                            span: span,
                            global: true,
                            segments: segms,
                        };
                        // the entity is accessible in the following cases:
                        // 1. if it's defined in the same crate, it's always
                        // accessible (since private entities can be made public)
                        // 2. if it's defined in another crate, it's accessible
                        // only if both the module is public and the entity is
                        // declared as public (due to pruning, we don't explore
                        // outside crate private modules => no need to check this)
3234
                        if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246
                            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();
3247
                            let ident = ast::Ident::with_empty_ctxt(name);
3248 3249 3250 3251 3252 3253 3254 3255
                            let params = PathParameters::none();
                            let segm = PathSegment {
                                identifier: ident,
                                parameters: params,
                            };
                            paths.push(segm);
                            paths
                        }
3256
                        _ => bug!(),
3257 3258
                    };

3259
                    if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
3260
                        // add the module to the lookup
3261
                        let is_extern = in_module_is_extern || name_binding.is_extern_crate();
3262 3263 3264
                        if !worklist.iter().any(|&(m, _, _)| m.def == module.def) {
                            worklist.push((module, path_segments, is_extern));
                        }
3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275
                    }
                }
            })
        }

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

3276 3277
    fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
        debug!("(recording def) recording {:?} for {}", resolution, node_id);
3278
        if let Some(prev_res) = self.def_map.insert(node_id, resolution) {
3279
            panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution);
3280
        }
3281 3282
    }

3283
    fn resolve_visibility(&mut self, vis: &ast::Visibility) -> ty::Visibility {
3284
        let (path, id) = match *vis {
3285 3286 3287 3288
            ast::Visibility::Public => return ty::Visibility::Public,
            ast::Visibility::Crate(_) => return ty::Visibility::Restricted(ast::CRATE_NODE_ID),
            ast::Visibility::Restricted { ref path, id } => (path, id),
            ast::Visibility::Inherited => {
3289 3290
                let current_module =
                    self.get_nearest_normal_module_parent_or_self(self.current_module);
3291 3292
                let id =
                    self.definitions.as_local_node_id(current_module.def_id().unwrap()).unwrap();
3293 3294 3295 3296 3297
                return ty::Visibility::Restricted(id);
            }
        };

        let segments: Vec<_> = path.segments.iter().map(|seg| seg.identifier.name).collect();
3298
        let mut path_resolution = err_path_resolution();
3299 3300 3301
        let vis = match self.resolve_module_path(&segments, DontUseLexicalScope, path.span) {
            Success(module) => {
                let def = module.def.unwrap();
3302
                path_resolution = PathResolution::new(def);
3303
                ty::Visibility::Restricted(self.definitions.as_local_node_id(def.def_id()).unwrap())
3304 3305 3306 3307 3308 3309 3310 3311 3312 3313
            }
            Failed(Some((span, msg))) => {
                self.session.span_err(span, &format!("failed to resolve module path. {}", msg));
                ty::Visibility::Public
            }
            _ => {
                self.session.span_err(path.span, "unresolved module path");
                ty::Visibility::Public
            }
        };
3314
        self.def_map.insert(id, path_resolution);
3315 3316 3317 3318 3319 3320 3321
        if !self.is_accessible(vis) {
            let msg = format!("visibilities can only be restricted to ancestor modules");
            self.session.span_err(path.span, &msg);
        }
        vis
    }

3322 3323
    fn is_accessible(&self, vis: ty::Visibility) -> bool {
        let current_module = self.get_nearest_normal_module_parent_or_self(self.current_module);
3324
        let node_id = self.definitions.as_local_node_id(current_module.def_id().unwrap()).unwrap();
3325
        vis.is_accessible_from(node_id, self)
3326 3327
    }

3328 3329
    fn check_privacy(&mut self, name: Name, binding: &'a NameBinding<'a>, span: Span) {
        if !self.is_accessible(binding.vis) {
3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349
            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));
            }
        }
    }
3350

3351 3352 3353 3354 3355 3356 3357
    fn report_conflict(&self,
                       parent: Module,
                       name: Name,
                       ns: Namespace,
                       binding: &NameBinding,
                       old_binding: &NameBinding) {
        // Error on the second of two conflicting names
3358
        if old_binding.span.lo > binding.span.lo {
3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373
            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"),
        };

3374
        let span = binding.span;
3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394
        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),
3395
                _ => {
3396 3397 3398
                    let mut e = struct_span_err!(self.session, span, E0255, "{}", msg);
                    e.span_label(span, &format!("`{}` was already imported", name));
                    e
3399
                }
3400 3401 3402
            },
        };

3403
        if old_binding.span != syntax_pos::DUMMY_SP {
3404
            err.span_label(old_binding.span, &format!("previous {} of `{}` here", noun, name));
3405 3406 3407 3408
        }
        err.emit();
    }
}
3409 3410 3411 3412 3413 3414 3415 3416 3417 3418

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("::")
        }
3419
        result.push_str(&name.as_str());
C
corentih 已提交
3420
    }
3421 3422 3423 3424
    result
}

fn path_names_to_string(path: &Path, depth: usize) -> String {
C
corentih 已提交
3425
    let names: Vec<ast::Name> = path.segments[..path.segments.len() - depth]
3426 3427 3428 3429 3430 3431
                                    .iter()
                                    .map(|seg| seg.identifier.name)
                                    .collect();
    names_to_string(&names[..])
}

3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454
/// When an entity with a given name is not available in scope, we search for
/// entities with that name in all crates. This method allows outputting the
/// results of this search in a programmer-friendly way
fn show_candidates(session: &mut DiagnosticBuilder,
                   candidates: &SuggestedCandidates) {

    let paths = &candidates.candidates;

    if paths.len() > 0 {
        // don't show more than MAX_CANDIDATES results, so
        // we're consistent with the trait suggestions
        const MAX_CANDIDATES: usize = 5;

        // we want consistent results across executions, but candidates are produced
        // by iterating through a hash map, so make sure they are ordered:
        let mut path_strings: Vec<_> = paths.into_iter()
                                            .map(|p| path_names_to_string(&p, 0))
                                            .collect();
        path_strings.sort();

        // behave differently based on how many candidates we have:
        if !paths.is_empty() {
            if paths.len() == 1 {
3455
                session.help(
T
tiehuis 已提交
3456
                    &format!("you can import it into scope: `use {};`.",
3457 3458 3459
                        &path_strings[0]),
                );
            } else {
3460
                session.help("you can import several candidates \
3461 3462 3463 3464 3465
                    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 {
3466
                        session.help(
3467 3468 3469 3470
                            &format!("  and {} other candidates", count).to_string(),
                        );
                        break;
                    } else {
3471
                        session.help(
3472 3473 3474 3475 3476 3477 3478 3479
                            &format!("  `{}`", path_string).to_string(),
                        );
                    }
                }
            }
        }
    } else {
        // nothing found:
3480
        session.help(
3481 3482 3483 3484 3485 3486 3487
            &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()),
        );
    };
}

3488
/// A somewhat inefficient routine to obtain the name of a module.
3489
fn module_to_string(module: Module) -> String {
3490 3491
    let mut names = Vec::new();

3492
    fn collect_mod(names: &mut Vec<ast::Name>, module: Module) {
3493 3494 3495 3496
        match module.parent_link {
            NoParentLink => {}
            ModuleParentLink(ref module, name) => {
                names.push(name);
3497
                collect_mod(names, module);
3498 3499 3500
            }
            BlockParentLink(ref module, _) => {
                // danger, shouldn't be ident?
3501
                names.push(token::intern("<opaque>"));
3502
                collect_mod(names, module);
3503 3504 3505 3506 3507
            }
        }
    }
    collect_mod(&mut names, module);

3508
    if names.is_empty() {
3509 3510 3511 3512 3513
        return "???".to_string();
    }
    names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
}

3514
fn err_path_resolution() -> PathResolution {
3515
    PathResolution::new(Def::Err)
3516 3517
}

N
Niko Matsakis 已提交
3518
#[derive(PartialEq,Copy, Clone)]
3519 3520
pub enum MakeGlobMap {
    Yes,
C
corentih 已提交
3521
    No,
3522 3523
}

3524
__build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }