lib.rs 179.8 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
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
A
Alex Crichton 已提交
12
      html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
13
      html_root_url = "https://doc.rust-lang.org/nightly/")]
14

A
Alex Crichton 已提交
15
#![feature(rustc_diagnostic_macros)]
16
#![feature(slice_sort_by_cached_key)]
17

C
corentih 已提交
18 19 20 21
#[macro_use]
extern crate log;
#[macro_use]
extern crate syntax;
22 23
extern crate syntax_pos;
extern crate rustc_errors as errors;
24
extern crate arena;
C
corentih 已提交
25
#[macro_use]
26
extern crate rustc;
27
extern crate rustc_data_structures;
28

S
Steven Fackler 已提交
29 30 31 32
use self::Namespace::*;
use self::TypeParameters::*;
use self::RibKind::*;

33
use rustc::hir::map::{Definitions, DefCollector};
34
use rustc::hir::{self, PrimTy, TyBool, TyChar, TyFloat, TyInt, TyUint, TyStr};
35
use rustc::middle::cstore::{CrateStore, CrateLoader};
36 37
use rustc::session::Session;
use rustc::lint;
38
use rustc::hir::def::*;
39
use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, DefId};
40
use rustc::ty;
S
Seo Sanghyeon 已提交
41
use rustc::hir::{Freevar, FreevarMap, TraitCandidate, TraitMap, GlobMap};
42
use rustc::util::nodemap::{NodeMap, NodeSet, FxHashMap, FxHashSet, DefIdMap};
43

V
Vadim Petrochenkov 已提交
44
use syntax::codemap::{BytePos, CodeMap};
45
use syntax::ext::hygiene::{Mark, MarkKind, SyntaxContext};
V
Vadim Petrochenkov 已提交
46
use syntax::ast::{self, Name, NodeId, Ident, FloatTy, IntTy, UintTy};
J
Jeffrey Seyfried 已提交
47
use syntax::ext::base::SyntaxExtension;
J
Jeffrey Seyfried 已提交
48
use syntax::ext::base::Determinacy::{self, Determined, Undetermined};
49
use syntax::ext::base::MacroKind;
50
use syntax::symbol::{Symbol, keywords};
51
use syntax::util::lev_distance::find_best_match_for_name;
52

53
use syntax::visit::{self, FnKind, Visitor};
54
use syntax::attr;
55
use syntax::ast::{Arm, BindingMode, Block, Crate, Expr, ExprKind};
56
use syntax::ast::{FnDecl, ForeignItem, ForeignItemKind, GenericParam, Generics};
57
use syntax::ast::{Item, ItemKind, ImplItem, ImplItemKind};
58
use syntax::ast::{Label, Local, Mutability, Pat, PatKind, Path};
J
Jeffrey Seyfried 已提交
59
use syntax::ast::{QSelf, TraitItemKind, TraitRef, Ty, TyKind};
M
Mark Mansi 已提交
60
use syntax::feature_gate::{feature_err, GateIssue};
61
use syntax::parse::token;
62
use syntax::ptr::P;
63

64
use syntax_pos::{Span, DUMMY_SP, MultiSpan};
65
use errors::{DiagnosticBuilder, DiagnosticId};
66

67
use std::cell::{Cell, RefCell};
68
use std::cmp;
69
use std::collections::BTreeSet;
70
use std::fmt;
M
Manish Goregaokar 已提交
71
use std::iter;
72
use std::mem::replace;
73
use rustc_data_structures::sync::Lrc;
74

75
use resolve_imports::{ImportDirective, ImportDirectiveSubclass, NameResolution, ImportResolver};
76
use macros::{InvocationData, LegacyBinding, LegacyScope, MacroBinding};
77

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

82
mod macros;
A
Alex Crichton 已提交
83
mod check_unused;
84
mod build_reduced_graph;
85
mod resolve_imports;
86

87 88 89
/// A free importable items suggested in case of resolution failure.
struct ImportSuggestion {
    path: Path,
90 91
}

92 93 94 95 96
/// A field or associated item from self type suggested in case of resolution failure.
enum AssocSuggestion {
    Field,
    MethodWithSelf,
    AssocItem,
97 98
}

99 100 101
#[derive(Eq)]
struct BindingError {
    name: Name,
102 103
    origin: BTreeSet<Span>,
    target: BTreeSet<Span>,
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
}

impl PartialOrd for BindingError {
    fn partial_cmp(&self, other: &BindingError) -> Option<cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl PartialEq for BindingError {
    fn eq(&self, other: &BindingError) -> bool {
        self.name == other.name
    }
}

impl Ord for BindingError {
    fn cmp(&self, other: &BindingError) -> cmp::Ordering {
        self.name.cmp(&other.name)
    }
}

J
Jeffrey Seyfried 已提交
124
enum ResolutionError<'a> {
125
    /// error E0401: can't use type parameters from outer function
126
    TypeParametersFromOuterFunction(Def),
127
    /// error E0403: the name is already used for a type parameter in this type parameter list
C
Chris Stankus 已提交
128
    NameAlreadyUsedInTypeParameterList(Name, &'a Span),
129
    /// error E0407: method is not a member of trait
130
    MethodNotMemberOfTrait(Name, &'a str),
131 132 133 134
    /// 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),
135 136 137 138
    /// error E0408: variable `{}` is not bound in all patterns
    VariableNotBoundInPattern(&'a BindingError),
    /// error E0409: variable `{}` is bound in inconsistent ways within the same match arm
    VariableBoundWithDifferentMode(Name, Span),
139
    /// error E0415: identifier is bound more than once in this parameter list
140
    IdentifierBoundMoreThanOnceInParameterList(&'a str),
141
    /// error E0416: identifier is bound more than once in the same pattern
142
    IdentifierBoundMoreThanOnceInSamePattern(&'a str),
143
    /// error E0426: use of undeclared label
144
    UndeclaredLabel(&'a str, Option<Name>),
145
    /// error E0429: `self` imports are only allowed within a { } list
146
    SelfImportsOnlyAllowedWithin,
147
    /// error E0430: `self` import can only appear once in the list
148
    SelfImportCanOnlyAppearOnceInTheList,
149
    /// error E0431: `self` import can only appear in an import list with a non-empty prefix
150
    SelfImportOnlyInImportListWithNonEmptyPrefix,
151
    /// error E0432: unresolved import
152
    UnresolvedImport(Option<(Span, &'a str, &'a str)>),
153
    /// error E0433: failed to resolve
154
    FailedToResolve(&'a str),
155
    /// error E0434: can't capture dynamic environment in a fn item
156
    CannotCaptureDynamicEnvironmentInFnItem,
157
    /// error E0435: attempt to use a non-constant value in a constant
158
    AttemptToUseNonConstantValueInConstant,
159
    /// error E0530: X bindings cannot shadow Ys
160
    BindingShadowsSomethingUnacceptable(&'a str, Name, &'a NameBinding<'a>),
161 162
    /// error E0128: type parameters with a default cannot use forward declared identifiers
    ForwardDeclaredTyParam,
163 164
}

165 166 167 168
/// Combines an error with provided span and emits it
///
/// This takes the error provided, combines it with the span and any additional spans inside the
/// error and emits it.
169 170 171
fn resolve_error<'sess, 'a>(resolver: &'sess Resolver,
                            span: Span,
                            resolution_error: ResolutionError<'a>) {
N
Nick Cameron 已提交
172
    resolve_struct_error(resolver, span, resolution_error).emit();
N
Nick Cameron 已提交
173 174
}

175 176 177 178
fn resolve_struct_error<'sess, 'a>(resolver: &'sess Resolver,
                                   span: Span,
                                   resolution_error: ResolutionError<'a>)
                                   -> DiagnosticBuilder<'sess> {
N
Nick Cameron 已提交
179
    match resolution_error {
180
        ResolutionError::TypeParametersFromOuterFunction(outer_def) => {
181 182 183
            let mut err = struct_span_err!(resolver.session,
                                           span,
                                           E0401,
184
                                           "can't use type parameters from outer function");
185
            err.span_label(span, "use of type variable from outer function");
186 187

            let cm = resolver.session.codemap();
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
            match outer_def {
                Def::SelfTy(_, maybe_impl_defid) => {
                    if let Some(impl_span) = maybe_impl_defid.map_or(None,
                            |def_id| resolver.definitions.opt_span(def_id)) {
                        err.span_label(reduce_impl_span_to_impl_keyword(cm, impl_span),
                                    "`Self` type implicitely declared here, on the `impl`");
                    }
                },
                Def::TyParam(typaram_defid) => {
                    if let Some(typaram_span) = resolver.definitions.opt_span(typaram_defid) {
                        err.span_label(typaram_span, "type variable from outer function");
                    }
                },
                Def::Mod(..) | Def::Struct(..) | Def::Union(..) | Def::Enum(..) | Def::Variant(..) |
                Def::Trait(..) | Def::TyAlias(..) | Def::TyForeign(..) | Def::TraitAlias(..) |
                Def::AssociatedTy(..) | Def::PrimTy(..) | Def::Fn(..) | Def::Const(..) |
                Def::Static(..) | Def::StructCtor(..) | Def::VariantCtor(..) | Def::Method(..) |
                Def::AssociatedConst(..) | Def::Local(..) | Def::Upvar(..) | Def::Label(..) |
                Def::Macro(..) | Def::GlobalAsm(..) | Def::Err =>
                    bug!("TypeParametersFromOuterFunction should only be used with Def::SelfTy or \
                         Def::TyParam")
            }

            // Try to retrieve the span of the function signature and generate a new message with
            // a local type parameter
            let sugg_msg = "try using a local type parameter instead";
214
            if let Some((sugg_span, new_snippet)) = generate_local_type_param_snippet(cm, span) {
215 216 217 218
                // Suggest the modification to the user
                err.span_suggestion(sugg_span,
                                    sugg_msg,
                                    new_snippet);
219 220
            } else if let Some(sp) = generate_fn_name_span(cm, span) {
                err.span_label(sp, "try adding a local type parameter in this method instead");
221 222 223 224
            } else {
                err.help("try using a local type parameter instead");
            }

225
            err
C
corentih 已提交
226
        }
C
Chris Stankus 已提交
227 228 229 230 231 232 233
        ResolutionError::NameAlreadyUsedInTypeParameterList(name, first_use_span) => {
             let mut err = struct_span_err!(resolver.session,
                                            span,
                                            E0403,
                                            "the name `{}` is already used for a type parameter \
                                            in this type parameter list",
                                            name);
234 235
             err.span_label(span, "already used");
             err.span_label(first_use_span.clone(), format!("first use of `{}`", name));
C
Chris Stankus 已提交
236
             err
C
corentih 已提交
237
        }
238
        ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
C
crypto-universe 已提交
239 240 241 242 243 244
            let mut err = struct_span_err!(resolver.session,
                                           span,
                                           E0407,
                                           "method `{}` is not a member of trait `{}`",
                                           method,
                                           trait_);
245
            err.span_label(span, format!("not a member of trait `{}`", trait_));
C
crypto-universe 已提交
246
            err
C
corentih 已提交
247
        }
248
        ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
S
Shyam Sundar B 已提交
249
            let mut err = struct_span_err!(resolver.session,
N
Nick Cameron 已提交
250 251 252 253
                             span,
                             E0437,
                             "type `{}` is not a member of trait `{}`",
                             type_,
S
Shyam Sundar B 已提交
254
                             trait_);
255
            err.span_label(span, format!("not a member of trait `{}`", trait_));
S
Shyam Sundar B 已提交
256
            err
C
corentih 已提交
257
        }
258
        ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
S
Shyam Sundar B 已提交
259
            let mut err = struct_span_err!(resolver.session,
N
Nick Cameron 已提交
260 261 262 263
                             span,
                             E0438,
                             "const `{}` is not a member of trait `{}`",
                             const_,
S
Shyam Sundar B 已提交
264
                             trait_);
265
            err.span_label(span, format!("not a member of trait `{}`", trait_));
S
Shyam Sundar B 已提交
266
            err
C
corentih 已提交
267
        }
268
        ResolutionError::VariableNotBoundInPattern(binding_error) => {
269
            let target_sp = binding_error.target.iter().map(|x| *x).collect::<Vec<_>>();
270 271
            let msp = MultiSpan::from_spans(target_sp.clone());
            let msg = format!("variable `{}` is not bound in all patterns", binding_error.name);
272 273 274 275 276
            let mut err = resolver.session.struct_span_err_with_code(
                msp,
                &msg,
                DiagnosticId::Error("E0408".into()),
            );
277
            for sp in target_sp {
278
                err.span_label(sp, format!("pattern doesn't bind `{}`", binding_error.name));
279
            }
280
            let origin_sp = binding_error.origin.iter().map(|x| *x).collect::<Vec<_>>();
281
            for sp in origin_sp {
282
                err.span_label(sp, "variable not in all patterns");
283
            }
284
            err
C
corentih 已提交
285
        }
M
Mikhail Modin 已提交
286 287 288
        ResolutionError::VariableBoundWithDifferentMode(variable_name,
                                                        first_binding_span) => {
            let mut err = struct_span_err!(resolver.session,
N
Nick Cameron 已提交
289 290
                             span,
                             E0409,
291 292 293
                             "variable `{}` is bound in inconsistent \
                             ways within the same match arm",
                             variable_name);
294 295
            err.span_label(span, "bound in different ways");
            err.span_label(first_binding_span, "first binding");
M
Mikhail Modin 已提交
296
            err
C
corentih 已提交
297
        }
298
        ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
299
            let mut err = struct_span_err!(resolver.session,
N
Nick Cameron 已提交
300 301 302
                             span,
                             E0415,
                             "identifier `{}` is bound more than once in this parameter list",
303
                             identifier);
304
            err.span_label(span, "used as parameter more than once");
305
            err
C
corentih 已提交
306
        }
307
        ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
308
            let mut err = struct_span_err!(resolver.session,
N
Nick Cameron 已提交
309 310 311
                             span,
                             E0416,
                             "identifier `{}` is bound more than once in the same pattern",
312
                             identifier);
313
            err.span_label(span, "used in a pattern more than once");
314
            err
C
corentih 已提交
315
        }
316
        ResolutionError::UndeclaredLabel(name, lev_candidate) => {
C
crypto-universe 已提交
317 318 319 320 321
            let mut err = struct_span_err!(resolver.session,
                                           span,
                                           E0426,
                                           "use of undeclared label `{}`",
                                           name);
322 323 324 325 326
            if let Some(lev_candidate) = lev_candidate {
                err.span_label(span, format!("did you mean `{}`?", lev_candidate));
            } else {
                err.span_label(span, format!("undeclared label `{}`", name));
            }
C
crypto-universe 已提交
327
            err
C
corentih 已提交
328
        }
329
        ResolutionError::SelfImportsOnlyAllowedWithin => {
N
Nick Cameron 已提交
330 331 332 333 334
            struct_span_err!(resolver.session,
                             span,
                             E0429,
                             "{}",
                             "`self` imports are only allowed within a { } list")
C
corentih 已提交
335
        }
336
        ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
E
Esteban Küber 已提交
337 338 339 340
            let mut err = struct_span_err!(resolver.session, span, E0430,
                                           "`self` import can only appear once in an import list");
            err.span_label(span, "can only appear once in an import list");
            err
C
corentih 已提交
341
        }
342
        ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
E
Esteban Küber 已提交
343 344 345 346 347
            let mut err = struct_span_err!(resolver.session, span, E0431,
                                           "`self` import can only appear in an import list with \
                                            a non-empty prefix");
            err.span_label(span, "can only appear in an import list with a non-empty prefix");
            err
348
        }
349
        ResolutionError::UnresolvedImport(name) => {
350 351 352
            let (span, msg) = match name {
                Some((sp, n, _)) => (sp, format!("unresolved import `{}`", n)),
                None => (span, "unresolved import".to_owned()),
353
            };
K
Knight 已提交
354
            let mut err = struct_span_err!(resolver.session, span, E0432, "{}", msg);
355
            if let Some((_, _, p)) = name {
356
                err.span_label(span, p);
K
Knight 已提交
357 358
            }
            err
C
corentih 已提交
359
        }
360
        ResolutionError::FailedToResolve(msg) => {
J
Jonathan Turner 已提交
361 362
            let mut err = struct_span_err!(resolver.session, span, E0433,
                                           "failed to resolve. {}", msg);
363
            err.span_label(span, msg);
364
            err
C
corentih 已提交
365
        }
366
        ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
E
Esteban Küber 已提交
367 368 369 370 371 372 373
            let mut err = struct_span_err!(resolver.session,
                                           span,
                                           E0434,
                                           "{}",
                                           "can't capture dynamic environment in a fn item");
            err.help("use the `|| { ... }` closure form instead");
            err
C
corentih 已提交
374 375
        }
        ResolutionError::AttemptToUseNonConstantValueInConstant => {
E
Esteban Küber 已提交
376 377
            let mut err = struct_span_err!(resolver.session, span, E0435,
                                           "attempt to use a non-constant value in a constant");
378
            err.span_label(span, "non-constant value");
S
Shyam Sundar B 已提交
379
            err
C
corentih 已提交
380
        }
381
        ResolutionError::BindingShadowsSomethingUnacceptable(what_binding, name, binding) => {
382
            let shadows_what = PathResolution::new(binding.def()).kind_name();
383 384
            let mut err = struct_span_err!(resolver.session,
                                           span,
385
                                           E0530,
386
                                           "{}s cannot shadow {}s", what_binding, shadows_what);
387
            err.span_label(span, format!("cannot be named the same as a {}", shadows_what));
388
            let participle = if binding.is_import() { "imported" } else { "defined" };
389
            let msg = format!("a {} `{}` is {} here", shadows_what, name, participle);
390
            err.span_label(binding.span, msg);
391 392
            err
        }
393 394 395 396
        ResolutionError::ForwardDeclaredTyParam => {
            let mut err = struct_span_err!(resolver.session, span, E0128,
                                           "type parameters with a default cannot use \
                                            forward declared identifiers");
E
Esteban Küber 已提交
397
            err.span_label(span, format!("defaulted type parameters cannot be forward declared"));
398 399
            err
        }
N
Nick Cameron 已提交
400
    }
401 402
}

403 404 405 406 407 408 409 410 411 412 413 414 415
/// Adjust the impl span so that just the `impl` keyword is taken by removing
/// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
/// everything after the first whitespace (`"impl Iterator for A" -> "impl"`)
///
/// Attention: The method used is very fragile since it essentially duplicates the work of the
/// parser. If you need to use this function or something similar, please consider updating the
/// codemap functions and this function to something more robust.
fn reduce_impl_span_to_impl_keyword(cm: &CodeMap, impl_span: Span) -> Span {
    let impl_span = cm.span_until_char(impl_span, '<');
    let impl_span = cm.span_until_whitespace(impl_span);
    impl_span
}

416 417 418 419 420 421 422 423 424
fn generate_fn_name_span(cm: &CodeMap, span: Span) -> Option<Span> {
    let prev_span = cm.span_extend_to_prev_str(span, "fn", true);
    cm.span_to_snippet(prev_span).map(|snippet| {
        let len = snippet.find(|c: char| !c.is_alphanumeric() && c != '_')
            .expect("no label after fn");
        prev_span.with_hi(BytePos(prev_span.lo().0 + len as u32))
    }).ok()
}

425 426 427 428 429
/// Take the span of a type parameter in a function signature and try to generate a span for the
/// function name (with generics) and a new snippet for this span with the pointed type parameter as
/// a new local type parameter.
///
/// For instance:
430
/// ```rust,ignore (pseudo-Rust)
431 432
/// // Given span
/// fn my_function(param: T)
433
/// //                    ^ Original span
434 435 436
///
/// // Result
/// fn my_function(param: T)
437
/// // ^^^^^^^^^^^ Generated span with snippet `my_function<T>`
438 439 440 441 442 443 444 445
/// ```
///
/// Attention: The method used is very fragile since it essentially duplicates the work of the
/// parser. If you need to use this function or something similar, please consider updating the
/// codemap functions and this function to something more robust.
fn generate_local_type_param_snippet(cm: &CodeMap, span: Span) -> Option<(Span, String)> {
    // Try to extend the span to the previous "fn" keyword to retrieve the function
    // signature
446
    let sugg_span = cm.span_extend_to_prev_str(span, "fn", false);
447 448 449
    if sugg_span != span {
        if let Ok(snippet) = cm.span_to_snippet(sugg_span) {
            // Consume the function name
450 451
            let mut offset = snippet.find(|c: char| !c.is_alphanumeric() && c != '_')
                .expect("no label after fn");
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486

            // Consume the generics part of the function signature
            let mut bracket_counter = 0;
            let mut last_char = None;
            for c in snippet[offset..].chars() {
                match c {
                    '<' => bracket_counter += 1,
                    '>' => bracket_counter -= 1,
                    '(' => if bracket_counter == 0 { break; }
                    _ => {}
                }
                offset += c.len_utf8();
                last_char = Some(c);
            }

            // Adjust the suggestion span to encompass the function name with its generics
            let sugg_span = sugg_span.with_hi(BytePos(sugg_span.lo().0 + offset as u32));

            // Prepare the new suggested snippet to append the type parameter that triggered
            // the error in the generics of the function signature
            let mut new_snippet = if last_char == Some('>') {
                format!("{}, ", &snippet[..(offset - '>'.len_utf8())])
            } else {
                format!("{}<", &snippet[..offset])
            };
            new_snippet.push_str(&cm.span_to_snippet(span).unwrap_or("T".to_string()));
            new_snippet.push('>');

            return Some((sugg_span, new_snippet));
        }
    }

    None
}

487
#[derive(Copy, Clone, Debug)]
488
struct BindingInfo {
489
    span: Span,
490
    binding_mode: BindingMode,
491 492
}

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

496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum PatternSource {
    Match,
    IfLet,
    WhileLet,
    Let,
    For,
    FnParam,
}

impl PatternSource {
    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",
        }
    }
517 518
}

A
Alex Burka 已提交
519 520 521 522 523 524
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum AliasPossibility {
    No,
    Maybe,
}

525 526 527 528 529
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum PathSource<'a> {
    // Type paths `Path`.
    Type,
    // Trait paths in bounds or impls.
A
Alex Burka 已提交
530
    Trait(AliasPossibility),
531
    // Expression paths `path`, with optional parent context.
532
    Expr(Option<&'a Expr>),
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
    // Paths in path patterns `Path`.
    Pat,
    // Paths in struct expressions and patterns `Path { .. }`.
    Struct,
    // Paths in tuple struct patterns `Path(..)`.
    TupleStruct,
    // `m::A::B` in `<T as m::A>::B::C`.
    TraitItem(Namespace),
    // Path in `pub(path)`
    Visibility,
    // Path in `use a::b::{...};`
    ImportPrefix,
}

impl<'a> PathSource<'a> {
    fn namespace(self) -> Namespace {
        match self {
A
Alex Burka 已提交
550
            PathSource::Type | PathSource::Trait(_) | PathSource::Struct |
551 552 553 554 555 556 557 558 559 560 561
            PathSource::Visibility | PathSource::ImportPrefix => TypeNS,
            PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct => ValueNS,
            PathSource::TraitItem(ns) => ns,
        }
    }

    fn global_by_default(self) -> bool {
        match self {
            PathSource::Visibility | PathSource::ImportPrefix => true,
            PathSource::Type | PathSource::Expr(..) | PathSource::Pat |
            PathSource::Struct | PathSource::TupleStruct |
A
Alex Burka 已提交
562
            PathSource::Trait(_) | PathSource::TraitItem(..) => false,
563 564 565 566 567 568 569
        }
    }

    fn defer_to_typeck(self) -> bool {
        match self {
            PathSource::Type | PathSource::Expr(..) | PathSource::Pat |
            PathSource::Struct | PathSource::TupleStruct => true,
A
Alex Burka 已提交
570
            PathSource::Trait(_) | PathSource::TraitItem(..) |
571 572 573 574 575 576 577
            PathSource::Visibility | PathSource::ImportPrefix => false,
        }
    }

    fn descr_expected(self) -> &'static str {
        match self {
            PathSource::Type => "type",
A
Alex Burka 已提交
578
            PathSource::Trait(_) => "trait",
579 580 581 582 583 584 585 586 587 588
            PathSource::Pat => "unit struct/variant or constant",
            PathSource::Struct => "struct, variant or union type",
            PathSource::TupleStruct => "tuple struct/variant",
            PathSource::Visibility => "module",
            PathSource::ImportPrefix => "module or enum",
            PathSource::TraitItem(ns) => match ns {
                TypeNS => "associated type",
                ValueNS => "method or associated constant",
                MacroNS => bug!("associated macro"),
            },
589
            PathSource::Expr(parent) => match parent.map(|p| &p.node) {
590 591 592 593 594 595 596 597 598 599 600 601 602
                // "function" here means "anything callable" rather than `Def::Fn`,
                // this is not precise but usually more helpful than just "value".
                Some(&ExprKind::Call(..)) => "function",
                _ => "value",
            },
        }
    }

    fn is_expected(self, def: Def) -> bool {
        match self {
            PathSource::Type => match def {
                Def::Struct(..) | Def::Union(..) | Def::Enum(..) |
                Def::Trait(..) | Def::TyAlias(..) | Def::AssociatedTy(..) |
P
Paul Lietar 已提交
603 604
                Def::PrimTy(..) | Def::TyParam(..) | Def::SelfTy(..) |
                Def::TyForeign(..) => true,
605 606
                _ => false,
            },
A
Alex Burka 已提交
607 608 609 610 611
            PathSource::Trait(AliasPossibility::No) => match def {
                Def::Trait(..) => true,
                _ => false,
            },
            PathSource::Trait(AliasPossibility::Maybe) => match def {
612
                Def::Trait(..) => true,
A
Alex Burka 已提交
613
                Def::TraitAlias(..) => true,
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
                _ => false,
            },
            PathSource::Expr(..) => match def {
                Def::StructCtor(_, CtorKind::Const) | Def::StructCtor(_, CtorKind::Fn) |
                Def::VariantCtor(_, CtorKind::Const) | Def::VariantCtor(_, CtorKind::Fn) |
                Def::Const(..) | Def::Static(..) | Def::Local(..) | Def::Upvar(..) |
                Def::Fn(..) | Def::Method(..) | Def::AssociatedConst(..) => true,
                _ => false,
            },
            PathSource::Pat => match def {
                Def::StructCtor(_, CtorKind::Const) |
                Def::VariantCtor(_, CtorKind::Const) |
                Def::Const(..) | Def::AssociatedConst(..) => true,
                _ => false,
            },
            PathSource::TupleStruct => match def {
                Def::StructCtor(_, CtorKind::Fn) | Def::VariantCtor(_, CtorKind::Fn) => true,
                _ => false,
            },
            PathSource::Struct => match def {
                Def::Struct(..) | Def::Union(..) | Def::Variant(..) |
                Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => true,
                _ => false,
            },
            PathSource::TraitItem(ns) => match def {
                Def::AssociatedConst(..) | Def::Method(..) if ns == ValueNS => true,
                Def::AssociatedTy(..) if ns == TypeNS => true,
                _ => false,
            },
            PathSource::ImportPrefix => match def {
                Def::Mod(..) | Def::Enum(..) => true,
                _ => false,
            },
            PathSource::Visibility => match def {
                Def::Mod(..) => true,
                _ => false,
            },
        }
    }

    fn error_code(self, has_unexpected_resolution: bool) -> &'static str {
        __diagnostic_used!(E0404);
        __diagnostic_used!(E0405);
        __diagnostic_used!(E0412);
        __diagnostic_used!(E0422);
        __diagnostic_used!(E0423);
        __diagnostic_used!(E0425);
        __diagnostic_used!(E0531);
        __diagnostic_used!(E0532);
        __diagnostic_used!(E0573);
        __diagnostic_used!(E0574);
        __diagnostic_used!(E0575);
        __diagnostic_used!(E0576);
        __diagnostic_used!(E0577);
        __diagnostic_used!(E0578);
        match (self, has_unexpected_resolution) {
A
Alex Burka 已提交
670 671
            (PathSource::Trait(_), true) => "E0404",
            (PathSource::Trait(_), false) => "E0405",
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
            (PathSource::Type, true) => "E0573",
            (PathSource::Type, false) => "E0412",
            (PathSource::Struct, true) => "E0574",
            (PathSource::Struct, false) => "E0422",
            (PathSource::Expr(..), true) => "E0423",
            (PathSource::Expr(..), false) => "E0425",
            (PathSource::Pat, true) | (PathSource::TupleStruct, true) => "E0532",
            (PathSource::Pat, false) | (PathSource::TupleStruct, false) => "E0531",
            (PathSource::TraitItem(..), true) => "E0575",
            (PathSource::TraitItem(..), false) => "E0576",
            (PathSource::Visibility, true) | (PathSource::ImportPrefix, true) => "E0577",
            (PathSource::Visibility, false) | (PathSource::ImportPrefix, false) => "E0578",
        }
    }
}

688 689 690
/// Different kinds of symbols don't influence each other.
///
/// Therefore, they have a separate universe (namespace).
691
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
G
Garming Sam 已提交
692
pub enum Namespace {
693
    TypeNS,
C
corentih 已提交
694
    ValueNS,
695
    MacroNS,
696 697
}

698
/// Just a helper ‒ separate structure for each namespace.
J
Jeffrey Seyfried 已提交
699 700 701 702
#[derive(Clone, Default, Debug)]
pub struct PerNS<T> {
    value_ns: T,
    type_ns: T,
703
    macro_ns: Option<T>,
J
Jeffrey Seyfried 已提交
704 705 706 707 708 709 710 711
}

impl<T> ::std::ops::Index<Namespace> for PerNS<T> {
    type Output = T;
    fn index(&self, ns: Namespace) -> &T {
        match ns {
            ValueNS => &self.value_ns,
            TypeNS => &self.type_ns,
712
            MacroNS => self.macro_ns.as_ref().unwrap(),
J
Jeffrey Seyfried 已提交
713 714 715 716 717 718 719 720 721
        }
    }
}

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

727 728 729
struct UsePlacementFinder {
    target_module: NodeId,
    span: Option<Span>,
730
    found_use: bool,
731 732
}

733 734 735 736 737 738 739 740 741 742 743 744
impl UsePlacementFinder {
    fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, bool) {
        let mut finder = UsePlacementFinder {
            target_module,
            span: None,
            found_use: false,
        };
        visit::walk_crate(&mut finder, krate);
        (finder.span, finder.found_use)
    }
}

745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
impl<'tcx> Visitor<'tcx> for UsePlacementFinder {
    fn visit_mod(
        &mut self,
        module: &'tcx ast::Mod,
        _: Span,
        _: &[ast::Attribute],
        node_id: NodeId,
    ) {
        if self.span.is_some() {
            return;
        }
        if node_id != self.target_module {
            visit::walk_mod(self, module);
            return;
        }
        // find a use statement
        for item in &module.items {
            match item.node {
                ItemKind::Use(..) => {
                    // don't suggest placing a use before the prelude
                    // import or other generated ones
766
                    if item.span.ctxt().outer().expn_info().is_none() {
767
                        self.span = Some(item.span.shrink_to_lo());
768
                        self.found_use = true;
769 770 771 772 773 774 775
                        return;
                    }
                },
                // don't place use before extern crate
                ItemKind::ExternCrate(_) => {}
                // but place them before the first other item
                _ => if self.span.map_or(true, |span| item.span < span ) {
776 777 778
                    if item.span.ctxt().outer().expn_info().is_none() {
                        // don't insert between attributes and an item
                        if item.attrs.is_empty() {
779
                            self.span = Some(item.span.shrink_to_lo());
780 781 782 783
                        } else {
                            // find the first attribute on the item
                            for attr in &item.attrs {
                                if self.span.map_or(true, |span| attr.span < span) {
784
                                    self.span = Some(attr.span.shrink_to_lo());
785 786 787 788
                                }
                            }
                        }
                    }
789 790 791 792 793 794
                },
            }
        }
    }
}

795
/// This thing walks the whole crate in DFS manner, visiting each item, resolving names as it goes.
796 797
impl<'a, 'tcx> Visitor<'tcx> for Resolver<'a> {
    fn visit_item(&mut self, item: &'tcx Item) {
A
Alex Crichton 已提交
798
        self.resolve_item(item);
799
    }
800
    fn visit_arm(&mut self, arm: &'tcx Arm) {
A
Alex Crichton 已提交
801
        self.resolve_arm(arm);
802
    }
803
    fn visit_block(&mut self, block: &'tcx Block) {
A
Alex Crichton 已提交
804
        self.resolve_block(block);
805
    }
806
    fn visit_expr(&mut self, expr: &'tcx Expr) {
807
        self.resolve_expr(expr, None);
808
    }
809
    fn visit_local(&mut self, local: &'tcx Local) {
A
Alex Crichton 已提交
810
        self.resolve_local(local);
811
    }
812
    fn visit_ty(&mut self, ty: &'tcx Ty) {
813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
        match ty.node {
            TyKind::Path(ref qself, ref path) => {
                self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
            }
            TyKind::ImplicitSelf => {
                let self_ty = keywords::SelfType.ident();
                let def = self.resolve_ident_in_lexical_scope(self_ty, TypeNS, true, ty.span)
                              .map_or(Def::Err, |d| d.def());
                self.record_def(ty.id, PathResolution::new(def));
            }
            TyKind::Array(ref element, ref length) => {
                self.visit_ty(element);
                self.with_constant_rib(|this| {
                    this.visit_expr(length);
                });
                return;
            }
            _ => (),
831 832
        }
        visit::walk_ty(self, ty);
833
    }
834 835 836
    fn visit_poly_trait_ref(&mut self,
                            tref: &'tcx ast::PolyTraitRef,
                            m: &'tcx ast::TraitBoundModifier) {
837
        self.smart_resolve_path(tref.trait_ref.ref_id, None,
A
Alex Burka 已提交
838
                                &tref.trait_ref.path, PathSource::Trait(AliasPossibility::Maybe));
839
        visit::walk_poly_trait_ref(self, tref, m);
840
    }
C
corentih 已提交
841
    fn visit_variant(&mut self,
842 843
                     variant: &'tcx ast::Variant,
                     generics: &'tcx Generics,
C
corentih 已提交
844
                     item_id: ast::NodeId) {
845 846 847
        if let Some(ref dis_expr) = variant.node.disr_expr {
            // resolve the discriminator expr as a constant
            self.with_constant_rib(|this| {
848
                this.visit_expr(dis_expr);
849 850 851
            });
        }

852
        // `visit::walk_variant` without the discriminant expression.
C
corentih 已提交
853
        self.visit_variant_data(&variant.node.data,
854
                                variant.node.ident,
C
corentih 已提交
855 856 857
                                generics,
                                item_id,
                                variant.span);
858
    }
859
    fn visit_foreign_item(&mut self, foreign_item: &'tcx ForeignItem) {
860
        let type_parameters = match foreign_item.node {
861
            ForeignItemKind::Fn(_, ref generics) => {
862
                HasTypeParameters(generics, ItemRibKind)
863
            }
864
            ForeignItemKind::Static(..) => NoTypeParameters,
P
Paul Lietar 已提交
865
            ForeignItemKind::Ty => NoTypeParameters,
866
            ForeignItemKind::Macro(..) => NoTypeParameters,
867 868
        };
        self.with_type_parameter_rib(type_parameters, |this| {
869
            visit::walk_foreign_item(this, foreign_item);
870 871 872
        });
    }
    fn visit_fn(&mut self,
873 874
                function_kind: FnKind<'tcx>,
                declaration: &'tcx FnDecl,
875 876 877
                _: Span,
                node_id: NodeId) {
        let rib_kind = match function_kind {
878
            FnKind::ItemFn(..) => {
879 880
                ItemRibKind
            }
881 882
            FnKind::Method(_, _, _, _) => {
                TraitOrImplItemRibKind
883
            }
884
            FnKind::Closure(_) => ClosureRibKind(node_id),
885
        };
886 887

        // Create a value rib for the function.
J
Jeffrey Seyfried 已提交
888
        self.ribs[ValueNS].push(Rib::new(rib_kind));
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917

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

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

            self.visit_ty(&argument.ty);

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

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

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

        self.label_ribs.pop();
J
Jeffrey Seyfried 已提交
918
        self.ribs[ValueNS].pop();
919
    }
920 921 922
    fn visit_generics(&mut self, generics: &'tcx Generics) {
        // For type parameter defaults, we have to ban access
        // to following type parameters, as the Substs can only
923 924 925
        // provide previous type parameters as they're built. We
        // put all the parameters on the ban list and then remove
        // them one by one as they are processed and become available.
926
        let mut default_ban_rib = Rib::new(ForwardTyParamBanRibKind);
927 928
        default_ban_rib.bindings.extend(generics.params.iter()
            .filter_map(|p| if let GenericParam::Type(ref tp) = *p { Some(tp) } else { None })
929 930 931
            .skip_while(|p| p.default.is_none())
            .map(|p| (Ident::with_empty_ctxt(p.ident.name), Def::Err)));

932 933 934 935 936 937 938
        for param in &generics.params {
            match *param {
                GenericParam::Lifetime(_) => self.visit_generic_param(param),
                GenericParam::Type(ref ty_param) => {
                    for bound in &ty_param.bounds {
                        self.visit_ty_param_bound(bound);
                    }
939

940 941 942 943 944
                    if let Some(ref ty) = ty_param.default {
                        self.ribs[TypeNS].push(default_ban_rib);
                        self.visit_ty(ty);
                        default_ban_rib = self.ribs[TypeNS].pop().unwrap();
                    }
945

946 947 948 949
                    // Allow all following defaults to refer to this type parameter.
                    default_ban_rib.bindings.remove(&Ident::with_empty_ctxt(ty_param.ident.name));
                }
            }
950 951 952
        }
        for p in &generics.where_clause.predicates { self.visit_where_predicate(p); }
    }
953
}
954

N
Niko Matsakis 已提交
955
#[derive(Copy, Clone)]
956
enum TypeParameters<'a, 'b> {
957
    NoTypeParameters,
C
corentih 已提交
958
    HasTypeParameters(// Type parameters.
959
                      &'b Generics,
960

C
corentih 已提交
961
                      // The kind of the rib used for type parameters.
962
                      RibKind<'a>),
963 964
}

965
// The rib kind controls the translation of local
966
// definitions (`Def::Local`) to upvars (`Def::Upvar`).
N
Niko Matsakis 已提交
967
#[derive(Copy, Clone, Debug)]
968
enum RibKind<'a> {
969 970
    // No translation needs to be applied.
    NormalRibKind,
971

972 973
    // We passed through a closure scope at the given node ID.
    // Translate upvars as appropriate.
974
    ClosureRibKind(NodeId /* func id */),
975

976
    // We passed through an impl or trait and are now in one of its
977
    // methods or associated types. Allow references to ty params that impl or trait
978 979
    // binds. Disallow any other upvars (including other ty params that are
    // upvars).
980
    TraitOrImplItemRibKind,
981

982 983
    // We passed through an item scope. Disallow upvars.
    ItemRibKind,
984 985

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

988 989
    // We passed through a module.
    ModuleRibKind(Module<'a>),
990

991 992
    // We passed through a `macro_rules!` statement
    MacroDefinition(DefId),
993 994 995 996 997

    // All bindings in this rib are type parameters that can't be used
    // from the default of a type parameter because they're not declared
    // before said type parameter. Also see the `visit_generics` override.
    ForwardTyParamBanRibKind,
998 999
}

1000
/// One local scope.
1001 1002 1003
///
/// A rib represents a scope names can live in. Note that these appear in many places, not just
/// around braces. At any place where the list of accessible names (of the given namespace)
1004 1005 1006
/// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
/// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
/// etc.
1007 1008 1009 1010 1011
///
/// Different [rib kinds](enum.RibKind) are transparent for different names.
///
/// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
/// resolving, the name is looked up from inside out.
J
Jorge Aparicio 已提交
1012
#[derive(Debug)]
1013
struct Rib<'a> {
1014
    bindings: FxHashMap<Ident, Def>,
1015
    kind: RibKind<'a>,
B
Brian Anderson 已提交
1016
}
1017

1018 1019
impl<'a> Rib<'a> {
    fn new(kind: RibKind<'a>) -> Rib<'a> {
1020
        Rib {
1021
            bindings: FxHashMap(),
1022
            kind,
1023
        }
1024 1025 1026
    }
}

1027 1028 1029 1030 1031
/// An intermediate resolution result.
///
/// This refers to the thing referred by a name. The difference between `Def` and `Item` is that
/// items are visible in their whole block, while defs only from the place they are defined
/// forward.
1032 1033
enum LexicalScopeBinding<'a> {
    Item(&'a NameBinding<'a>),
J
Jeffrey Seyfried 已提交
1034
    Def(Def),
1035 1036
}

1037
impl<'a> LexicalScopeBinding<'a> {
1038
    fn item(self) -> Option<&'a NameBinding<'a>> {
1039
        match self {
1040
            LexicalScopeBinding::Item(binding) => Some(binding),
1041 1042 1043
            _ => None,
        }
    }
1044 1045 1046 1047 1048 1049 1050

    fn def(self) -> Def {
        match self {
            LexicalScopeBinding::Item(binding) => binding.def(),
            LexicalScopeBinding::Def(def) => def,
        }
    }
1051 1052
}

1053
#[derive(Clone, Debug)]
J
Jeffrey Seyfried 已提交
1054 1055 1056 1057
enum PathResult<'a> {
    Module(Module<'a>),
    NonModule(PathResolution),
    Indeterminate,
1058
    Failed(Span, String, bool /* is the error from the last segment? */),
J
Jeffrey Seyfried 已提交
1059 1060
}

J
Jeffrey Seyfried 已提交
1061
enum ModuleKind {
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
    /// An anonymous module, eg. just a block.
    ///
    /// ```
    /// fn main() {
    ///     fn f() {} // (1)
    ///     { // This is an anonymous module
    ///         f(); // This resolves to (2) as we are inside the block.
    ///         fn f() {} // (2)
    ///     }
    ///     f(); // Resolves to (1)
    /// }
    /// ```
J
Jeffrey Seyfried 已提交
1074
    Block(NodeId),
1075 1076 1077
    /// Any module with a name.
    ///
    /// This could be:
1078
    ///
1079 1080 1081
    /// * A normal module ‒ either `mod from_file;` or `mod from_block { }`.
    /// * A trait or an enum (it implicitly contains associated types, methods and variant
    ///   constructors).
J
Jeffrey Seyfried 已提交
1082
    Def(Def, Name),
1083 1084
}

1085
/// One node in the tree of modules.
1086
pub struct ModuleData<'a> {
J
Jeffrey Seyfried 已提交
1087 1088
    parent: Option<Module<'a>>,
    kind: ModuleKind,
1089

1090 1091
    // The def id of the closest normal module (`mod`) ancestor (including this module).
    normal_ancestor_id: DefId,
1092

1093
    resolutions: RefCell<FxHashMap<(Ident, Namespace), &'a RefCell<NameResolution<'a>>>>,
1094
    legacy_macro_resolutions: RefCell<Vec<(Mark, Ident, Span, MacroKind)>>,
1095
    macro_resolutions: RefCell<Vec<(Box<[Ident]>, Span)>>,
1096

1097 1098 1099
    // Macro invocations that can expand into items in this module.
    unresolved_invocations: RefCell<FxHashSet<Mark>>,

1100
    no_implicit_prelude: bool,
1101

1102
    glob_importers: RefCell<Vec<&'a ImportDirective<'a>>>,
1103
    globs: RefCell<Vec<&'a ImportDirective<'a>>>,
1104

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

1108 1109 1110
    // Whether this module is populated. If not populated, any attempt to
    // access the children must be preceded with a
    // `populate_module_if_necessary` call.
1111
    populated: Cell<bool>,
1112 1113 1114

    /// Span of the module itself. Used for error reporting.
    span: Span,
J
Jeffrey Seyfried 已提交
1115 1116

    expansion: Mark,
1117 1118
}

1119
type Module<'a> = &'a ModuleData<'a>;
1120

1121
impl<'a> ModuleData<'a> {
O
Oliver Schneider 已提交
1122 1123 1124
    fn new(parent: Option<Module<'a>>,
           kind: ModuleKind,
           normal_ancestor_id: DefId,
J
Jeffrey Seyfried 已提交
1125
           expansion: Mark,
O
Oliver Schneider 已提交
1126
           span: Span) -> Self {
1127
        ModuleData {
1128 1129 1130
            parent,
            kind,
            normal_ancestor_id,
1131
            resolutions: RefCell::new(FxHashMap()),
1132
            legacy_macro_resolutions: RefCell::new(Vec::new()),
1133
            macro_resolutions: RefCell::new(Vec::new()),
1134
            unresolved_invocations: RefCell::new(FxHashSet()),
1135
            no_implicit_prelude: false,
1136
            glob_importers: RefCell::new(Vec::new()),
1137
            globs: RefCell::new(Vec::new()),
J
Jeffrey Seyfried 已提交
1138
            traits: RefCell::new(None),
1139
            populated: Cell::new(normal_ancestor_id.is_local()),
1140 1141
            span,
            expansion,
1142
        }
B
Brian Anderson 已提交
1143 1144
    }

1145 1146 1147
    fn for_each_child<F: FnMut(Ident, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
        for (&(ident, ns), name_resolution) in self.resolutions.borrow().iter() {
            name_resolution.borrow().binding.map(|binding| f(ident, ns, binding));
1148 1149 1150
        }
    }

1151 1152
    fn for_each_child_stable<F: FnMut(Ident, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
        let resolutions = self.resolutions.borrow();
1153 1154 1155
        let mut resolutions = resolutions.iter().collect::<Vec<_>>();
        resolutions.sort_by_cached_key(|&(&(ident, ns), _)| (ident.name.as_str(), ns));
        for &(&(ident, ns), &resolution) in resolutions.iter() {
1156 1157 1158 1159
            resolution.borrow().binding.map(|binding| f(ident, ns, binding));
        }
    }

J
Jeffrey Seyfried 已提交
1160 1161 1162 1163 1164 1165 1166
    fn def(&self) -> Option<Def> {
        match self.kind {
            ModuleKind::Def(def, _) => Some(def),
            _ => None,
        }
    }

1167
    fn def_id(&self) -> Option<DefId> {
J
Jeffrey Seyfried 已提交
1168
        self.def().as_ref().map(Def::def_id)
1169 1170
    }

1171
    // `self` resolves to the first module ancestor that `is_normal`.
1172
    fn is_normal(&self) -> bool {
J
Jeffrey Seyfried 已提交
1173 1174
        match self.kind {
            ModuleKind::Def(Def::Mod(_), _) => true,
1175 1176 1177 1178 1179
            _ => false,
        }
    }

    fn is_trait(&self) -> bool {
J
Jeffrey Seyfried 已提交
1180 1181
        match self.kind {
            ModuleKind::Def(Def::Trait(_), _) => true,
1182
            _ => false,
1183
        }
B
Brian Anderson 已提交
1184
    }
1185 1186

    fn is_local(&self) -> bool {
1187
        self.normal_ancestor_id.is_local()
1188
    }
1189 1190 1191 1192

    fn nearest_item_scope(&'a self) -> Module<'a> {
        if self.is_trait() { self.parent.unwrap() } else { self }
    }
V
Victor Berger 已提交
1193 1194
}

1195
impl<'a> fmt::Debug for ModuleData<'a> {
1196
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
J
Jeffrey Seyfried 已提交
1197
        write!(f, "{:?}", self.def())
1198 1199 1200
    }
}

1201
// Records a possibly-private value, type, or module definition.
1202
#[derive(Clone, Debug)]
1203
pub struct NameBinding<'a> {
1204
    kind: NameBindingKind<'a>,
1205
    expansion: Mark,
1206
    span: Span,
1207
    vis: ty::Visibility,
1208 1209
}

1210
pub trait ToNameBinding<'a> {
J
Jeffrey Seyfried 已提交
1211
    fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a>;
1212 1213
}

J
Jeffrey Seyfried 已提交
1214 1215
impl<'a> ToNameBinding<'a> for &'a NameBinding<'a> {
    fn to_name_binding(self, _: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
1216 1217 1218 1219
        self
    }
}

1220
#[derive(Clone, Debug)]
1221
enum NameBindingKind<'a> {
1222
    Def(Def),
1223
    Module(Module<'a>),
1224 1225
    Import {
        binding: &'a NameBinding<'a>,
1226
        directive: &'a ImportDirective<'a>,
1227
        used: Cell<bool>,
J
Jeffrey Seyfried 已提交
1228
        legacy_self_import: bool,
1229
    },
1230 1231 1232
    Ambiguity {
        b1: &'a NameBinding<'a>,
        b2: &'a NameBinding<'a>,
1233
        legacy: bool,
1234
    }
1235 1236
}

1237 1238
struct PrivacyError<'a>(Span, Name, &'a NameBinding<'a>);

1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
struct UseError<'a> {
    err: DiagnosticBuilder<'a>,
    /// Attach `use` statements for these candidates
    candidates: Vec<ImportSuggestion>,
    /// The node id of the module to place the use statements in
    node_id: NodeId,
    /// Whether the diagnostic should state that it's "better"
    better: bool,
}

J
Jeffrey Seyfried 已提交
1249 1250 1251
struct AmbiguityError<'a> {
    span: Span,
    name: Name,
1252
    lexical: bool,
J
Jeffrey Seyfried 已提交
1253 1254
    b1: &'a NameBinding<'a>,
    b2: &'a NameBinding<'a>,
1255
    legacy: bool,
J
Jeffrey Seyfried 已提交
1256 1257
}

1258
impl<'a> NameBinding<'a> {
J
Jeffrey Seyfried 已提交
1259
    fn module(&self) -> Option<Module<'a>> {
1260
        match self.kind {
J
Jeffrey Seyfried 已提交
1261
            NameBindingKind::Module(module) => Some(module),
1262
            NameBindingKind::Import { binding, .. } => binding.module(),
1263
            NameBindingKind::Ambiguity { legacy: true, b1, .. } => b1.module(),
J
Jeffrey Seyfried 已提交
1264
            _ => None,
1265 1266 1267
        }
    }

1268
    fn def(&self) -> Def {
1269
        match self.kind {
1270
            NameBindingKind::Def(def) => def,
J
Jeffrey Seyfried 已提交
1271
            NameBindingKind::Module(module) => module.def().unwrap(),
1272
            NameBindingKind::Import { binding, .. } => binding.def(),
1273
            NameBindingKind::Ambiguity { legacy: true, b1, .. } => b1.def(),
1274
            NameBindingKind::Ambiguity { .. } => Def::Err,
1275
        }
1276
    }
1277

1278
    fn def_ignoring_ambiguity(&self) -> Def {
J
Jeffrey Seyfried 已提交
1279
        match self.kind {
1280 1281 1282
            NameBindingKind::Import { binding, .. } => binding.def_ignoring_ambiguity(),
            NameBindingKind::Ambiguity { b1, .. } => b1.def_ignoring_ambiguity(),
            _ => self.def(),
J
Jeffrey Seyfried 已提交
1283 1284 1285
        }
    }

1286
    fn get_macro(&self, resolver: &mut Resolver<'a>) -> Lrc<SyntaxExtension> {
1287 1288 1289
        resolver.get_macro(self.def_ignoring_ambiguity())
    }

1290 1291
    // We sometimes need to treat variants as `pub` for backwards compatibility
    fn pseudo_vis(&self) -> ty::Visibility {
1292 1293 1294 1295 1296
        if self.is_variant() && self.def().def_id().is_local() {
            ty::Visibility::Public
        } else {
            self.vis
        }
1297 1298 1299 1300
    }

    fn is_variant(&self) -> bool {
        match self.kind {
1301 1302
            NameBindingKind::Def(Def::Variant(..)) |
            NameBindingKind::Def(Def::VariantCtor(..)) => true,
1303 1304
            _ => false,
        }
1305 1306
    }

1307
    fn is_extern_crate(&self) -> bool {
1308 1309 1310
        match self.kind {
            NameBindingKind::Import {
                directive: &ImportDirective {
1311
                    subclass: ImportDirectiveSubclass::ExternCrate(_), ..
1312 1313 1314 1315
                }, ..
            } => true,
            _ => false,
        }
1316
    }
1317 1318 1319 1320 1321 1322 1323

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

1325 1326 1327 1328 1329 1330 1331 1332 1333
    fn is_renamed_extern_crate(&self) -> bool {
        if let NameBindingKind::Import { directive, ..} = self.kind {
            if let ImportDirectiveSubclass::ExternCrate(Some(_)) = directive.subclass {
                return true;
            }
        }
        false
    }

1334 1335 1336
    fn is_glob_import(&self) -> bool {
        match self.kind {
            NameBindingKind::Import { directive, .. } => directive.is_glob(),
1337
            NameBindingKind::Ambiguity { b1, .. } => b1.is_glob_import(),
1338 1339 1340 1341 1342
            _ => false,
        }
    }

    fn is_importable(&self) -> bool {
1343
        match self.def() {
1344 1345 1346 1347
            Def::AssociatedConst(..) | Def::Method(..) | Def::AssociatedTy(..) => false,
            _ => true,
        }
    }
1348 1349 1350 1351 1352 1353 1354

    fn is_macro_def(&self) -> bool {
        match self.kind {
            NameBindingKind::Def(Def::Macro(..)) => true,
            _ => false,
        }
    }
1355 1356 1357 1358

    fn descr(&self) -> &'static str {
        if self.is_extern_crate() { "extern crate" } else { self.def().kind_name() }
    }
1359 1360
}

1361
/// Interns the names of the primitive types.
1362 1363 1364
///
/// All other types are defined somewhere and possibly imported, but the primitive ones need
/// special handling, since they have no place of origin.
F
Felix S. Klock II 已提交
1365
struct PrimitiveTypeTable {
1366
    primitive_types: FxHashMap<Name, PrimTy>,
1367
}
1368

1369
impl PrimitiveTypeTable {
K
Kevin Butler 已提交
1370
    fn new() -> PrimitiveTypeTable {
1371
        let mut table = PrimitiveTypeTable { primitive_types: FxHashMap() };
C
corentih 已提交
1372 1373 1374

        table.intern("bool", TyBool);
        table.intern("char", TyChar);
1375 1376
        table.intern("f32", TyFloat(FloatTy::F32));
        table.intern("f64", TyFloat(FloatTy::F64));
1377
        table.intern("isize", TyInt(IntTy::Isize));
1378 1379 1380 1381
        table.intern("i8", TyInt(IntTy::I8));
        table.intern("i16", TyInt(IntTy::I16));
        table.intern("i32", TyInt(IntTy::I32));
        table.intern("i64", TyInt(IntTy::I64));
1382
        table.intern("i128", TyInt(IntTy::I128));
C
corentih 已提交
1383
        table.intern("str", TyStr);
1384
        table.intern("usize", TyUint(UintTy::Usize));
1385 1386 1387 1388
        table.intern("u8", TyUint(UintTy::U8));
        table.intern("u16", TyUint(UintTy::U16));
        table.intern("u32", TyUint(UintTy::U32));
        table.intern("u64", TyUint(UintTy::U64));
1389
        table.intern("u128", TyUint(UintTy::U128));
K
Kevin Butler 已提交
1390 1391 1392
        table
    }

1393
    fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1394
        self.primitive_types.insert(Symbol::intern(string), primitive_type);
1395 1396 1397
    }
}

1398
/// The main resolver class.
1399 1400
///
/// This is the visitor that walks the whole crate.
1401
pub struct Resolver<'a> {
E
Eduard Burtescu 已提交
1402
    session: &'a Session,
1403
    cstore: &'a CrateStore,
1404

1405
    pub definitions: Definitions,
1406

1407
    graph_root: Module<'a>,
1408

1409 1410
    prelude: Option<Module<'a>>,

1411 1412
    // n.b. This is used only for better diagnostics, not name resolution itself.
    has_self: FxHashSet<DefId>,
1413

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

1418 1419 1420 1421
    // All imports known to succeed or fail.
    determined_imports: Vec<&'a ImportDirective<'a>>,

    // All non-determined imports.
1422
    indeterminate_imports: Vec<&'a ImportDirective<'a>>,
1423 1424

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

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

1431
    // The current set of local scopes, for labels.
1432
    label_ribs: Vec<Rib<'a>>,
1433

1434
    // The trait that the current context can refer to.
1435
    current_trait_ref: Option<(Module<'a>, TraitRef)>,
1436 1437 1438

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

1440
    // The idents for the primitive types.
E
Eduard Burtescu 已提交
1441
    primitive_type_table: PrimitiveTypeTable,
1442

1443
    def_map: DefMap,
1444
    pub freevars: FreevarMap,
1445
    freevars_seen: NodeMap<NodeMap<usize>>,
1446 1447
    pub export_map: ExportMap,
    pub trait_map: TraitMap,
1448

1449
    // A map from nodes to anonymous modules.
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
    // 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`.
1463 1464
    block_map: NodeMap<Module<'a>>,
    module_map: FxHashMap<DefId, Module<'a>>,
J
Jeffrey Seyfried 已提交
1465
    extern_module_map: FxHashMap<(DefId, bool /* MacrosOnly? */), Module<'a>>,
1466

1467
    pub make_glob_map: bool,
1468 1469
    /// Maps imports to the names of items actually imported (this actually maps
    /// all imports, but only glob imports are actually interesting).
1470
    pub glob_map: GlobMap,
1471

1472
    used_imports: FxHashSet<(NodeId, Namespace)>,
1473
    pub maybe_unused_trait_imports: NodeSet,
1474
    pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
G
Garming Sam 已提交
1475

1476
    /// privacy errors are delayed until the end in order to deduplicate them
1477
    privacy_errors: Vec<PrivacyError<'a>>,
1478
    /// ambiguity errors are delayed for deduplication
J
Jeffrey Seyfried 已提交
1479
    ambiguity_errors: Vec<AmbiguityError<'a>>,
1480 1481
    /// `use` injections are delayed for better placement and deduplication
    use_injections: Vec<UseError<'a>>,
1482 1483
    /// `use` injections for proc macros wrongly imported with #[macro_use]
    proc_mac_errors: Vec<macros::ProcMacError>,
1484

J
Jeffrey Seyfried 已提交
1485
    gated_errors: FxHashSet<Span>,
1486
    disallowed_shadowing: Vec<&'a LegacyBinding<'a>>,
1487 1488

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

1492
    crate_loader: &'a mut CrateLoader,
J
Jeffrey Seyfried 已提交
1493
    macro_names: FxHashSet<Ident>,
J
Jeffrey Seyfried 已提交
1494
    global_macros: FxHashMap<Name, &'a NameBinding<'a>>,
1495
    pub all_macros: FxHashMap<Name, Def>,
J
Jeffrey Seyfried 已提交
1496
    lexical_macro_resolutions: Vec<(Ident, &'a Cell<LegacyScope<'a>>)>,
1497
    macro_map: FxHashMap<DefId, Lrc<SyntaxExtension>>,
1498 1499
    macro_defs: FxHashMap<Mark, DefId>,
    local_macro_def_scopes: FxHashMap<NodeId, Module<'a>>,
J
Jeffrey Seyfried 已提交
1500
    macro_exports: Vec<Export>,
1501
    pub whitelisted_legacy_custom_derives: Vec<Name>,
1502
    pub found_unresolved_macro: bool,
1503

E
est31 已提交
1504
    // List of crate local macros that we need to warn about as being unused.
E
est31 已提交
1505
    // Right now this only includes macro_rules! macros, and macros 2.0.
E
est31 已提交
1506
    unused_macros: FxHashSet<DefId>,
E
est31 已提交
1507

1508
    // Maps the `Mark` of an expansion to its containing module or block.
1509
    invocations: FxHashMap<Mark, &'a InvocationData<'a>>,
1510 1511 1512

    // Avoid duplicated errors for "name already defined".
    name_already_seen: FxHashMap<Name, Span>,
1513 1514 1515 1516 1517 1518

    // If `#![feature(proc_macro)]` is set
    proc_macro_enabled: bool,

    // A set of procedural macros imported by `#[macro_use]` that have already been warned about
    warned_proc_macros: FxHashSet<Name>,
1519 1520

    potentially_unused_imports: Vec<&'a ImportDirective<'a>>,
1521

1522 1523 1524
    // This table maps struct IDs into struct constructor IDs,
    // it's not used during normal resolution, only for better error reporting.
    struct_constructors: DefIdMap<(Def, ty::Visibility)>,
1525 1526 1527

    // Only used for better errors on `fn(): fn()`
    current_type_ascription: Vec<Span>,
1528 1529

    injected_crate: Option<Module<'a>>,
1530 1531
}

1532
/// Nothing really interesting here, it just provides memory for the rest of the crate.
1533
pub struct ResolverArenas<'a> {
1534
    modules: arena::TypedArena<ModuleData<'a>>,
1535
    local_modules: RefCell<Vec<Module<'a>>>,
1536
    name_bindings: arena::TypedArena<NameBinding<'a>>,
1537
    import_directives: arena::TypedArena<ImportDirective<'a>>,
1538
    name_resolutions: arena::TypedArena<RefCell<NameResolution<'a>>>,
1539
    invocation_data: arena::TypedArena<InvocationData<'a>>,
J
Jeffrey Seyfried 已提交
1540
    legacy_bindings: arena::TypedArena<LegacyBinding<'a>>,
1541 1542 1543
}

impl<'a> ResolverArenas<'a> {
1544
    fn alloc_module(&'a self, module: ModuleData<'a>) -> Module<'a> {
1545 1546 1547 1548 1549 1550 1551 1552
        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()
1553 1554 1555 1556
    }
    fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
        self.name_bindings.alloc(name_binding)
    }
1557 1558
    fn alloc_import_directive(&'a self, import_directive: ImportDirective<'a>)
                              -> &'a ImportDirective {
1559 1560
        self.import_directives.alloc(import_directive)
    }
1561 1562 1563
    fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
        self.name_resolutions.alloc(Default::default())
    }
1564 1565 1566
    fn alloc_invocation_data(&'a self, expansion_data: InvocationData<'a>)
                             -> &'a InvocationData<'a> {
        self.invocation_data.alloc(expansion_data)
J
Jeffrey Seyfried 已提交
1567
    }
J
Jeffrey Seyfried 已提交
1568 1569 1570
    fn alloc_legacy_binding(&'a self, binding: LegacyBinding<'a>) -> &'a LegacyBinding<'a> {
        self.legacy_bindings.alloc(binding)
    }
1571 1572
}

1573 1574 1575 1576
impl<'a, 'b: 'a> ty::DefIdTree for &'a Resolver<'b> {
    fn parent(self, id: DefId) -> Option<DefId> {
        match id.krate {
            LOCAL_CRATE => self.definitions.def_key(id.index).parent,
1577
            _ => self.cstore.def_key(id).parent,
1578
        }.map(|index| DefId { index, ..id })
1579 1580 1581
    }
}

1582 1583
/// This interface is used through the AST→HIR step, to embed full paths into the HIR. After that
/// the resolver is no longer needed as all the relevant information is inline.
1584
impl<'a> hir::lowering::Resolver for Resolver<'a> {
J
Jeffrey Seyfried 已提交
1585
    fn resolve_hir_path(&mut self, path: &mut hir::Path, is_value: bool) {
1586 1587 1588 1589 1590
        self.resolve_hir_path_cb(path, is_value,
                                 |resolver, span, error| resolve_error(resolver, span, error))
    }

    fn resolve_str_path(&mut self, span: Span, crate_root: Option<&str>,
M
Manish Goregaokar 已提交
1591
                        components: &[&str], is_value: bool) -> hir::Path {
1592 1593 1594 1595 1596 1597 1598 1599
        let mut path = hir::Path {
            span,
            def: Def::Err,
            segments: iter::once(keywords::CrateRoot.name()).chain({
                crate_root.into_iter().chain(components.iter().cloned()).map(Symbol::intern)
            }).map(hir::PathSegment::from_name).collect(),
        };

M
Manish Goregaokar 已提交
1600
        self.resolve_hir_path(&mut path, is_value);
1601 1602 1603
        path
    }

M
Manish Goregaokar 已提交
1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
    fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution> {
        self.def_map.get(&id).cloned()
    }

    fn definitions(&mut self) -> &mut Definitions {
        &mut self.definitions
    }
}

impl<'a> Resolver<'a> {
1614 1615 1616
    /// Rustdoc uses this to resolve things in a recoverable way. ResolutionError<'a>
    /// isn't something that can be returned because it can't be made to live that long,
    /// and also it's a private type. Fortunately rustdoc doesn't need to know the error,
1617
    /// just that an error occurred.
M
Manish Goregaokar 已提交
1618 1619
    pub fn resolve_str_path_error(&mut self, span: Span, path_str: &str, is_value: bool)
        -> Result<hir::Path, ()> {
M
Manish Goregaokar 已提交
1620
        use std::iter;
1621
        let mut errored = false;
M
Manish Goregaokar 已提交
1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639

        let mut path = if path_str.starts_with("::") {
            hir::Path {
                span,
                def: Def::Err,
                segments: iter::once(keywords::CrateRoot.name()).chain({
                    path_str.split("::").skip(1).map(Symbol::intern)
                }).map(hir::PathSegment::from_name).collect(),
            }
        } else {
            hir::Path {
                span,
                def: Def::Err,
                segments: path_str.split("::").map(Symbol::intern)
                                  .map(hir::PathSegment::from_name).collect(),
            }
        };
        self.resolve_hir_path_cb(&mut path, is_value, |_, _, _| errored = true);
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650
        if errored || path.def == Def::Err {
            Err(())
        } else {
            Ok(path)
        }
    }

    /// resolve_hir_path, but takes a callback in case there was an error
    fn resolve_hir_path_cb<F>(&mut self, path: &mut hir::Path, is_value: bool, error_callback: F)
            where F: for<'c, 'b> FnOnce(&'c mut Resolver, Span, ResolutionError<'b>)
        {
1651
        let namespace = if is_value { ValueNS } else { TypeNS };
1652
        let hir::Path { ref segments, span, ref mut def } = *path;
V
Vadim Petrochenkov 已提交
1653 1654
        let path: Vec<Ident> = segments.iter()
            .map(|seg| Ident::new(seg.name, span))
1655
            .collect();
1656
        match self.resolve_path(&path, Some(namespace), true, span) {
J
Jeffrey Seyfried 已提交
1657
            PathResult::Module(module) => *def = module.def().unwrap(),
1658 1659
            PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 =>
                *def = path_res.base_def(),
1660
            PathResult::NonModule(..) => match self.resolve_path(&path, None, true, span) {
1661
                PathResult::Failed(span, msg, _) => {
1662
                    error_callback(self, span, ResolutionError::FailedToResolve(&msg));
J
Jeffrey Seyfried 已提交
1663 1664 1665 1666
                }
                _ => {}
            },
            PathResult::Indeterminate => unreachable!(),
1667
            PathResult::Failed(span, msg, _) => {
1668
                error_callback(self, span, ResolutionError::FailedToResolve(&msg));
1669 1670 1671 1672 1673
            }
        }
    }
}

1674
impl<'a> Resolver<'a> {
1675
    pub fn new(session: &'a Session,
1676
               cstore: &'a CrateStore,
1677
               krate: &Crate,
1678
               crate_name: &str,
1679
               make_glob_map: MakeGlobMap,
1680
               crate_loader: &'a mut CrateLoader,
1681
               arenas: &'a ResolverArenas<'a>)
1682
               -> Resolver<'a> {
1683 1684
        let root_def_id = DefId::local(CRATE_DEF_INDEX);
        let root_module_kind = ModuleKind::Def(Def::Mod(root_def_id), keywords::Invalid.name());
1685
        let graph_root = arenas.alloc_module(ModuleData {
1686
            no_implicit_prelude: attr::contains_name(&krate.attrs, "no_implicit_prelude"),
J
Jeffrey Seyfried 已提交
1687
            ..ModuleData::new(None, root_module_kind, root_def_id, Mark::root(), krate.span)
1688
        });
1689 1690
        let mut module_map = FxHashMap();
        module_map.insert(DefId::local(CRATE_DEF_INDEX), graph_root);
K
Kevin Butler 已提交
1691

1692
        let mut definitions = Definitions::new();
J
Jeffrey Seyfried 已提交
1693
        DefCollector::new(&mut definitions, Mark::root())
1694
            .collect_root(crate_name, session.local_crate_disambiguator());
1695

1696
        let mut invocations = FxHashMap();
1697 1698
        invocations.insert(Mark::root(),
                           arenas.alloc_invocation_data(InvocationData::root(graph_root)));
1699

1700
        let features = session.features_untracked();
1701

1702 1703 1704
        let mut macro_defs = FxHashMap();
        macro_defs.insert(Mark::root(), root_def_id);

K
Kevin Butler 已提交
1705
        Resolver {
1706
            session,
K
Kevin Butler 已提交
1707

1708 1709
            cstore,

1710
            definitions,
1711

K
Kevin Butler 已提交
1712 1713
            // The outermost module has def ID 0; this is not reflected in the
            // AST.
1714
            graph_root,
1715
            prelude: None,
K
Kevin Butler 已提交
1716

1717
            has_self: FxHashSet(),
1718
            field_names: FxHashMap(),
K
Kevin Butler 已提交
1719

1720
            determined_imports: Vec::new(),
1721
            indeterminate_imports: Vec::new(),
K
Kevin Butler 已提交
1722

1723
            current_module: graph_root,
J
Jeffrey Seyfried 已提交
1724 1725 1726
            ribs: PerNS {
                value_ns: vec![Rib::new(ModuleRibKind(graph_root))],
                type_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1727
                macro_ns: Some(vec![Rib::new(ModuleRibKind(graph_root))]),
J
Jeffrey Seyfried 已提交
1728
            },
1729
            label_ribs: Vec::new(),
K
Kevin Butler 已提交
1730 1731 1732 1733 1734 1735

            current_trait_ref: None,
            current_self_type: None,

            primitive_type_table: PrimitiveTypeTable::new(),

1736
            def_map: NodeMap(),
1737 1738
            freevars: NodeMap(),
            freevars_seen: NodeMap(),
A
Alex Crichton 已提交
1739
            export_map: FxHashMap(),
1740
            trait_map: NodeMap(),
1741
            module_map,
1742
            block_map: NodeMap(),
J
Jeffrey Seyfried 已提交
1743
            extern_module_map: FxHashMap(),
K
Kevin Butler 已提交
1744

1745
            make_glob_map: make_glob_map == MakeGlobMap::Yes,
1746
            glob_map: NodeMap(),
G
Garming Sam 已提交
1747

1748
            used_imports: FxHashSet(),
S
Seo Sanghyeon 已提交
1749
            maybe_unused_trait_imports: NodeSet(),
1750
            maybe_unused_extern_crates: Vec::new(),
S
Seo Sanghyeon 已提交
1751

1752
            privacy_errors: Vec::new(),
1753
            ambiguity_errors: Vec::new(),
1754
            use_injections: Vec::new(),
1755
            proc_mac_errors: Vec::new(),
J
Jeffrey Seyfried 已提交
1756
            gated_errors: FxHashSet(),
1757
            disallowed_shadowing: Vec::new(),
1758

1759
            arenas,
1760 1761
            dummy_binding: arenas.alloc_name_binding(NameBinding {
                kind: NameBindingKind::Def(Def::Err),
1762
                expansion: Mark::root(),
1763 1764 1765
                span: DUMMY_SP,
                vis: ty::Visibility::Public,
            }),
1766

1767 1768 1769
            // The `proc_macro` and `decl_macro` features imply `use_extern_macros`
            use_extern_macros:
                features.use_extern_macros || features.proc_macro || features.decl_macro,
1770

1771
            crate_loader,
1772
            macro_names: FxHashSet(),
J
Jeffrey Seyfried 已提交
1773
            global_macros: FxHashMap(),
1774
            all_macros: FxHashMap(),
J
Jeffrey Seyfried 已提交
1775
            lexical_macro_resolutions: Vec::new(),
J
Jeffrey Seyfried 已提交
1776 1777
            macro_map: FxHashMap(),
            macro_exports: Vec::new(),
1778 1779
            invocations,
            macro_defs,
1780
            local_macro_def_scopes: FxHashMap(),
1781
            name_already_seen: FxHashMap(),
1782
            whitelisted_legacy_custom_derives: Vec::new(),
1783 1784
            proc_macro_enabled: features.proc_macro,
            warned_proc_macros: FxHashSet(),
1785
            potentially_unused_imports: Vec::new(),
1786
            struct_constructors: DefIdMap(),
1787
            found_unresolved_macro: false,
E
est31 已提交
1788
            unused_macros: FxHashSet(),
1789
            current_type_ascription: Vec::new(),
1790
            injected_crate: None,
1791 1792 1793
        }
    }

1794
    pub fn arenas() -> ResolverArenas<'a> {
1795 1796
        ResolverArenas {
            modules: arena::TypedArena::new(),
1797
            local_modules: RefCell::new(Vec::new()),
1798
            name_bindings: arena::TypedArena::new(),
1799
            import_directives: arena::TypedArena::new(),
1800
            name_resolutions: arena::TypedArena::new(),
1801
            invocation_data: arena::TypedArena::new(),
J
Jeffrey Seyfried 已提交
1802
            legacy_bindings: arena::TypedArena::new(),
K
Kevin Butler 已提交
1803 1804
        }
    }
1805

1806
    /// Runs the function on each namespace.
J
Jeffrey Seyfried 已提交
1807 1808 1809 1810
    fn per_ns<T, F: FnMut(&mut Self, Namespace) -> T>(&mut self, mut f: F) -> PerNS<T> {
        PerNS {
            type_ns: f(self, TypeNS),
            value_ns: f(self, ValueNS),
1811 1812 1813 1814
            macro_ns: match self.use_extern_macros {
                true => Some(f(self, MacroNS)),
                false => None,
            },
J
Jeffrey Seyfried 已提交
1815 1816 1817
        }
    }

J
Jeffrey Seyfried 已提交
1818 1819 1820 1821 1822 1823 1824 1825 1826
    fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
        loop {
            match self.macro_defs.get(&ctxt.outer()) {
                Some(&def_id) => return def_id,
                None => ctxt.remove_mark(),
            };
        }
    }

1827 1828
    /// Entry point to crate resolution.
    pub fn resolve_crate(&mut self, krate: &Crate) {
1829
        ImportResolver { resolver: self }.finalize_imports();
1830
        self.current_module = self.graph_root;
1831
        self.finalize_current_module_macro_resolutions();
1832

1833 1834 1835
        visit::walk_crate(self, krate);

        check_unused::check_crate(self, krate);
1836
        self.report_errors(krate);
1837
        self.crate_loader.postprocess(krate);
1838 1839
    }

O
Oliver Schneider 已提交
1840 1841 1842 1843 1844
    fn new_module(
        &self,
        parent: Module<'a>,
        kind: ModuleKind,
        normal_ancestor_id: DefId,
J
Jeffrey Seyfried 已提交
1845
        expansion: Mark,
O
Oliver Schneider 已提交
1846 1847
        span: Span,
    ) -> Module<'a> {
J
Jeffrey Seyfried 已提交
1848 1849
        let module = ModuleData::new(Some(parent), kind, normal_ancestor_id, expansion, span);
        self.arenas.alloc_module(module)
1850 1851
    }

1852
    fn record_use(&mut self, ident: Ident, ns: Namespace, binding: &'a NameBinding<'a>, span: Span)
1853
                  -> bool /* true if an error was reported */ {
1854
        match binding.kind {
J
Jeffrey Seyfried 已提交
1855 1856
            NameBindingKind::Import { directive, binding, ref used, legacy_self_import }
                    if !used.get() => {
1857
                used.set(true);
1858
                directive.used.set(true);
J
Jeffrey Seyfried 已提交
1859 1860 1861 1862
                if legacy_self_import {
                    self.warn_legacy_self_import(directive);
                    return false;
                }
1863
                self.used_imports.insert((directive.id, ns));
1864 1865
                self.add_to_glob_map(directive.id, ident);
                self.record_use(ident, ns, binding, span)
1866 1867
            }
            NameBindingKind::Import { .. } => false,
1868
            NameBindingKind::Ambiguity { b1, b2, legacy } => {
1869
                self.ambiguity_errors.push(AmbiguityError {
1870
                    span: span, name: ident.name, lexical: false, b1: b1, b2: b2, legacy,
1871
                });
1872
                if legacy {
A
Alex Crichton 已提交
1873
                    self.record_use(ident, ns, b1, span);
1874 1875
                }
                !legacy
1876 1877
            }
            _ => false
1878
        }
1879
    }
1880

1881
    fn add_to_glob_map(&mut self, id: NodeId, ident: Ident) {
1882
        if self.make_glob_map {
1883
            self.glob_map.entry(id).or_insert_with(FxHashSet).insert(ident.name);
1884
        }
1885 1886
    }

1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900
    /// 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.
    /// }
    /// ```
1901
    ///
1902 1903
    /// Invariant: This must only be called during main resolution, not during
    /// import resolution.
1904
    fn resolve_ident_in_lexical_scope(&mut self,
1905
                                      mut ident: Ident,
1906
                                      ns: Namespace,
1907 1908
                                      record_used: bool,
                                      path_span: Span)
1909
                                      -> Option<LexicalScopeBinding<'a>> {
1910
        if ns == TypeNS {
1911 1912 1913
            ident.span = if ident.name == keywords::SelfType.name() {
                // FIXME(jseyfried) improve `Self` hygiene
                ident.span.with_ctxt(SyntaxContext::empty())
J
Jeffrey Seyfried 已提交
1914
            } else {
1915
                ident.span.modern()
J
Jeffrey Seyfried 已提交
1916
            }
1917
        }
1918

1919
        // Walk backwards up the ribs in scope.
J
Jeffrey Seyfried 已提交
1920
        let mut module = self.graph_root;
J
Jeffrey Seyfried 已提交
1921 1922
        for i in (0 .. self.ribs[ns].len()).rev() {
            if let Some(def) = self.ribs[ns][i].bindings.get(&ident).cloned() {
1923
                // The ident resolves to a type parameter or local variable.
1924
                return Some(LexicalScopeBinding::Def(
1925
                    self.adjust_local_def(ns, i, def, record_used, path_span)
1926
                ));
1927 1928
            }

J
Jeffrey Seyfried 已提交
1929 1930
            module = match self.ribs[ns][i].kind {
                ModuleRibKind(module) => module,
1931
                MacroDefinition(def) if def == self.macro_def(ident.span.ctxt()) => {
J
Jeffrey Seyfried 已提交
1932 1933
                    // If an invocation of this macro created `ident`, give up on `ident`
                    // and switch to `ident`'s source from the macro definition.
1934
                    ident.span.remove_mark();
J
Jeffrey Seyfried 已提交
1935
                    continue
1936
                }
J
Jeffrey Seyfried 已提交
1937 1938
                _ => continue,
            };
1939

J
Jeffrey Seyfried 已提交
1940 1941 1942 1943 1944 1945
            let item = self.resolve_ident_in_module_unadjusted(
                module, ident, ns, false, record_used, path_span,
            );
            if let Ok(binding) = item {
                // The ident resolves to an item.
                return Some(LexicalScopeBinding::Item(binding));
1946
            }
1947

J
Jeffrey Seyfried 已提交
1948 1949 1950 1951 1952 1953
            match module.kind {
                ModuleKind::Block(..) => {}, // We can see through blocks
                _ => break,
            }
        }

1954
        ident.span = ident.span.modern();
J
Jeffrey Seyfried 已提交
1955
        loop {
1956
            module = unwrap_or!(self.hygienic_lexical_parent(module, &mut ident.span), break);
J
Jeffrey Seyfried 已提交
1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979
            let orig_current_module = self.current_module;
            self.current_module = module; // Lexical resolutions can never be a privacy error.
            let result = self.resolve_ident_in_module_unadjusted(
                module, ident, ns, false, record_used, path_span,
            );
            self.current_module = orig_current_module;

            match result {
                Ok(binding) => return Some(LexicalScopeBinding::Item(binding)),
                Err(Undetermined) => return None,
                Err(Determined) => {}
            }
        }

        match self.prelude {
            Some(prelude) if !module.no_implicit_prelude => {
                self.resolve_ident_in_module_unadjusted(prelude, ident, ns, false, false, path_span)
                    .ok().map(LexicalScopeBinding::Item)
            }
            _ => None,
        }
    }

1980
    fn hygienic_lexical_parent(&mut self, mut module: Module<'a>, span: &mut Span)
J
Jeffrey Seyfried 已提交
1981
                               -> Option<Module<'a>> {
1982 1983
        if !module.expansion.is_descendant_of(span.ctxt().outer()) {
            return Some(self.macro_def_scope(span.remove_mark()));
J
Jeffrey Seyfried 已提交
1984 1985 1986 1987 1988 1989
        }

        if let ModuleKind::Block(..) = module.kind {
            return Some(module.parent.unwrap());
        }

B
Bastien Orivel 已提交
1990
        let mut module_expansion = module.expansion.modern(); // for backward compatibility
J
Jeffrey Seyfried 已提交
1991 1992 1993 1994
        while let Some(parent) = module.parent {
            let parent_expansion = parent.expansion.modern();
            if module_expansion.is_descendant_of(parent_expansion) &&
               parent_expansion != module_expansion {
1995
                return if parent_expansion.is_descendant_of(span.ctxt().outer()) {
J
Jeffrey Seyfried 已提交
1996 1997 1998 1999
                    Some(parent)
                } else {
                    None
                };
2000
            }
J
Jeffrey Seyfried 已提交
2001 2002
            module = parent;
            module_expansion = parent_expansion;
2003
        }
2004

2005 2006 2007
        None
    }

J
Jeffrey Seyfried 已提交
2008 2009 2010 2011 2012 2013 2014 2015
    fn resolve_ident_in_module(&mut self,
                               module: Module<'a>,
                               mut ident: Ident,
                               ns: Namespace,
                               ignore_unresolved_invocations: bool,
                               record_used: bool,
                               span: Span)
                               -> Result<&'a NameBinding<'a>, Determinacy> {
2016
        ident.span = ident.span.modern();
J
Jeffrey Seyfried 已提交
2017
        let orig_current_module = self.current_module;
2018
        if let Some(def) = ident.span.adjust(module.expansion) {
J
Jeffrey Seyfried 已提交
2019 2020 2021 2022 2023 2024 2025 2026 2027
            self.current_module = self.macro_def_scope(def);
        }
        let result = self.resolve_ident_in_module_unadjusted(
            module, ident, ns, ignore_unresolved_invocations, record_used, span,
        );
        self.current_module = orig_current_module;
        result
    }

2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038
    fn resolve_crate_root(&mut self, mut ctxt: SyntaxContext, legacy: bool) -> Module<'a> {
        let mark = if legacy {
            // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
            // we don't want to pretend that the `macro_rules!` definition is in the `macro`
            // as described in `SyntaxContext::apply_mark`, so we ignore prepended modern marks.
            ctxt.marks().into_iter().find(|&mark| mark.kind() != MarkKind::Modern)
        } else {
            ctxt = ctxt.modern();
            ctxt.adjust(Mark::root())
        };
        let module = match mark {
J
Jeffrey Seyfried 已提交
2039 2040 2041 2042 2043 2044 2045 2046
            Some(def) => self.macro_def_scope(def),
            None => return self.graph_root,
        };
        self.get_module(DefId { index: CRATE_DEF_INDEX, ..module.normal_ancestor_id })
    }

    fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'a>) -> Module<'a> {
        let mut module = self.get_module(module.normal_ancestor_id);
2047
        while module.span.ctxt().modern() != *ctxt {
J
Jeffrey Seyfried 已提交
2048 2049
            let parent = module.parent.unwrap_or_else(|| self.macro_def_scope(ctxt.remove_mark()));
            module = self.get_module(parent.normal_ancestor_id);
2050
        }
J
Jeffrey Seyfried 已提交
2051
        module
2052 2053
    }

2054 2055
    // AST resolution
    //
2056
    // We maintain a list of value ribs and type ribs.
2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071
    //
    // 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.

M
Manish Goregaokar 已提交
2072 2073
    pub fn with_scope<F, T>(&mut self, id: NodeId, f: F) -> T
        where F: FnOnce(&mut Resolver) -> T
J
Jorge Aparicio 已提交
2074
    {
2075
        let id = self.definitions.local_def_id(id);
2076 2077
        let module = self.module_map.get(&id).cloned(); // clones a reference
        if let Some(module) = module {
2078
            // Move down in the graph.
2079
            let orig_module = replace(&mut self.current_module, module);
J
Jeffrey Seyfried 已提交
2080 2081
            self.ribs[ValueNS].push(Rib::new(ModuleRibKind(module)));
            self.ribs[TypeNS].push(Rib::new(ModuleRibKind(module)));
2082

2083
            self.finalize_current_module_macro_resolutions();
M
Manish Goregaokar 已提交
2084
            let ret = f(self);
2085

2086
            self.current_module = orig_module;
J
Jeffrey Seyfried 已提交
2087 2088
            self.ribs[ValueNS].pop();
            self.ribs[TypeNS].pop();
M
Manish Goregaokar 已提交
2089
            ret
2090
        } else {
M
Manish Goregaokar 已提交
2091
            f(self)
2092
        }
2093 2094
    }

2095 2096 2097
    /// Searches the current set of local scopes for labels. Returns the first non-None label that
    /// is returned by the given predicate function
    ///
S
Seo Sanghyeon 已提交
2098
    /// Stops after meeting a closure.
2099 2100 2101
    fn search_label<P, R>(&self, mut ident: Ident, pred: P) -> Option<R>
        where P: Fn(&Rib, Ident) -> Option<R>
    {
2102 2103
        for rib in self.label_ribs.iter().rev() {
            match rib.kind {
J
Jeffrey Seyfried 已提交
2104 2105 2106
                NormalRibKind => {}
                // If an invocation of this macro created `ident`, give up on `ident`
                // and switch to `ident`'s source from the macro definition.
2107
                MacroDefinition(def) => {
2108 2109
                    if def == self.macro_def(ident.span.ctxt()) {
                        ident.span.remove_mark();
2110 2111
                    }
                }
2112 2113
                _ => {
                    // Do not resolve labels across function boundary
C
corentih 已提交
2114
                    return None;
2115 2116
                }
            }
2117 2118 2119
            let r = pred(rib, ident);
            if r.is_some() {
                return r;
2120 2121 2122 2123 2124
            }
        }
        None
    }

2125
    fn resolve_item(&mut self, item: &Item) {
2126
        let name = item.ident.name;
2127

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

2130 2131
        self.check_proc_macro_attrs(&item.attrs);

2132
        match item.node {
2133 2134
            ItemKind::Enum(_, ref generics) |
            ItemKind::Ty(_, ref generics) |
2135
            ItemKind::Struct(_, ref generics) |
2136
            ItemKind::Union(_, ref generics) |
V
Vadim Petrochenkov 已提交
2137
            ItemKind::Fn(.., ref generics, _) => {
2138
                self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind),
2139
                                             |this| visit::walk_item(this, item));
2140 2141
            }

V
Vadim Petrochenkov 已提交
2142
            ItemKind::Impl(.., ref generics, ref opt_trait_ref, ref self_type, ref impl_items) =>
2143
                self.resolve_implementation(generics,
2144
                                            opt_trait_ref,
J
Jonas Schievink 已提交
2145
                                            &self_type,
2146
                                            item.id,
2147
                                            impl_items),
2148

2149
            ItemKind::Trait(.., ref generics, ref bounds, ref trait_items) => {
2150
                // Create a new rib for the trait-wide type parameters.
2151
                self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
2152
                    let local_def_id = this.definitions.local_def_id(item.id);
2153
                    this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
2154
                        this.visit_generics(generics);
2155
                        walk_list!(this, visit_ty_param_bound, bounds);
2156 2157

                        for trait_item in trait_items {
2158 2159
                            this.check_proc_macro_attrs(&trait_item.attrs);

2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
                            let type_parameters = HasTypeParameters(&trait_item.generics,
                                                                    TraitOrImplItemRibKind);
                            this.with_type_parameter_rib(type_parameters, |this| {
                                match trait_item.node {
                                    TraitItemKind::Const(ref ty, ref default) => {
                                        this.visit_ty(ty);

                                        // Only impose the restrictions of
                                        // ConstRibKind for an actual constant
                                        // expression in a provided default.
                                        if let Some(ref expr) = *default{
                                            this.with_constant_rib(|this| {
                                                this.visit_expr(expr);
                                            });
                                        }
2175
                                    }
2176
                                    TraitItemKind::Method(_, _) => {
2177
                                        visit::walk_trait_item(this, trait_item)
2178 2179
                                    }
                                    TraitItemKind::Type(..) => {
2180
                                        visit::walk_trait_item(this, trait_item)
2181 2182 2183 2184 2185 2186
                                    }
                                    TraitItemKind::Macro(_) => {
                                        panic!("unexpanded macro in resolve!")
                                    }
                                };
                            });
2187 2188
                        }
                    });
2189
                });
2190 2191
            }

A
Alex Burka 已提交
2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202
            ItemKind::TraitAlias(ref generics, ref bounds) => {
                // Create a new rib for the trait-wide type parameters.
                self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
                    let local_def_id = this.definitions.local_def_id(item.id);
                    this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
                        this.visit_generics(generics);
                        walk_list!(this, visit_ty_param_bound, bounds);
                    });
                });
            }

2203
            ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
2204
                self.with_scope(item.id, |this| {
2205
                    visit::walk_item(this, item);
2206
                });
2207 2208
            }

2209 2210 2211 2212 2213 2214 2215
            ItemKind::Static(ref ty, _, ref expr) |
            ItemKind::Const(ref ty, ref expr) => {
                self.with_item_rib(|this| {
                    this.visit_ty(ty);
                    this.with_constant_rib(|this| {
                        this.visit_expr(expr);
                    });
2216
                });
2217
            }
2218

2219
            ItemKind::Use(ref use_tree) => {
2220
                // Imports are resolved as global by default, add starting root segment.
2221
                let path = Path {
2222
                    segments: use_tree.prefix.make_root().into_iter().collect(),
2223 2224
                    span: use_tree.span,
                };
2225
                self.resolve_use_tree(item.id, use_tree, &path);
W
we 已提交
2226 2227
            }

2228
            ItemKind::ExternCrate(_) | ItemKind::MacroDef(..) | ItemKind::GlobalAsm(_) => {
2229
                // do nothing, these are just around to be encoded
2230
            }
2231 2232

            ItemKind::Mac(_) => panic!("unexpanded macro in resolve!"),
2233 2234 2235
        }
    }

2236
    fn resolve_use_tree(&mut self, id: NodeId, use_tree: &ast::UseTree, prefix: &Path) {
2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249
        match use_tree.kind {
            ast::UseTreeKind::Nested(ref items) => {
                let path = Path {
                    segments: prefix.segments
                        .iter()
                        .chain(use_tree.prefix.segments.iter())
                        .cloned()
                        .collect(),
                    span: prefix.span.to(use_tree.prefix.span),
                };

                if items.len() == 0 {
                    // Resolve prefix of an import with empty braces (issue #28388).
2250
                    self.smart_resolve_path(id, None, &path, PathSource::ImportPrefix);
2251
                } else {
2252 2253
                    for &(ref tree, nested_id) in items {
                        self.resolve_use_tree(nested_id, tree, &path);
2254 2255 2256 2257 2258 2259 2260 2261
                    }
                }
            }
            ast::UseTreeKind::Simple(_) => {},
            ast::UseTreeKind::Glob => {},
        }
    }

2262
    fn with_type_parameter_rib<'b, F>(&'b mut self, type_parameters: TypeParameters<'a, 'b>, f: F)
C
corentih 已提交
2263
        where F: FnOnce(&mut Resolver)
J
Jorge Aparicio 已提交
2264
    {
2265
        match type_parameters {
2266
            HasTypeParameters(generics, rib_kind) => {
2267
                let mut function_type_rib = Rib::new(rib_kind);
2268
                let mut seen_bindings = FxHashMap();
2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279
                for param in &generics.params {
                    if let GenericParam::Type(ref type_parameter) = *param {
                        let ident = type_parameter.ident.modern();
                        debug!("with_type_parameter_rib: {}", type_parameter.id);

                        if seen_bindings.contains_key(&ident) {
                            let span = seen_bindings.get(&ident).unwrap();
                            let err = ResolutionError::NameAlreadyUsedInTypeParameterList(
                                ident.name,
                                span,
                            );
2280
                            resolve_error(self, type_parameter.ident.span, err);
2281
                        }
2282
                        seen_bindings.entry(ident).or_insert(type_parameter.ident.span);
2283

2284 2285 2286 2287 2288 2289
                        // plain insert (no renaming)
                        let def_id = self.definitions.local_def_id(type_parameter.id);
                        let def = Def::TyParam(def_id);
                        function_type_rib.bindings.insert(ident, def);
                        self.record_def(type_parameter.id, PathResolution::new(def));
                    }
2290
                }
J
Jeffrey Seyfried 已提交
2291
                self.ribs[TypeNS].push(function_type_rib);
2292 2293
            }

B
Brian Anderson 已提交
2294
            NoTypeParameters => {
2295 2296 2297 2298
                // Nothing to do.
            }
        }

A
Alex Crichton 已提交
2299
        f(self);
2300

J
Jeffrey Seyfried 已提交
2301
        if let HasTypeParameters(..) = type_parameters {
J
Jeffrey Seyfried 已提交
2302
            self.ribs[TypeNS].pop();
2303 2304 2305
        }
    }

C
corentih 已提交
2306 2307
    fn with_label_rib<F>(&mut self, f: F)
        where F: FnOnce(&mut Resolver)
J
Jorge Aparicio 已提交
2308
    {
2309
        self.label_ribs.push(Rib::new(NormalRibKind));
A
Alex Crichton 已提交
2310
        f(self);
J
Jeffrey Seyfried 已提交
2311
        self.label_ribs.pop();
2312
    }
2313

2314 2315 2316 2317 2318 2319 2320 2321 2322 2323
    fn with_item_rib<F>(&mut self, f: F)
        where F: FnOnce(&mut Resolver)
    {
        self.ribs[ValueNS].push(Rib::new(ItemRibKind));
        self.ribs[TypeNS].push(Rib::new(ItemRibKind));
        f(self);
        self.ribs[TypeNS].pop();
        self.ribs[ValueNS].pop();
    }

C
corentih 已提交
2324 2325
    fn with_constant_rib<F>(&mut self, f: F)
        where F: FnOnce(&mut Resolver)
J
Jorge Aparicio 已提交
2326
    {
J
Jeffrey Seyfried 已提交
2327
        self.ribs[ValueNS].push(Rib::new(ConstantItemRibKind));
A
Alex Crichton 已提交
2328
        f(self);
J
Jeffrey Seyfried 已提交
2329
        self.ribs[ValueNS].pop();
2330 2331
    }

2332 2333
    fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
        where F: FnOnce(&mut Resolver) -> T
J
Jorge Aparicio 已提交
2334
    {
2335 2336 2337 2338 2339 2340 2341
        // 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
    }

2342
    /// This is called to resolve a trait reference from an `impl` (i.e. `impl Trait for Foo`)
2343
    fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
2344
        where F: FnOnce(&mut Resolver, Option<DefId>) -> T
J
Jorge Aparicio 已提交
2345
    {
2346
        let mut new_val = None;
2347
        let mut new_id = None;
E
Eduard Burtescu 已提交
2348
        if let Some(trait_ref) = opt_trait_ref {
2349
            let path: Vec<_> = trait_ref.path.segments.iter()
V
Vadim Petrochenkov 已提交
2350
                .map(|seg| seg.ident)
2351
                .collect();
2352 2353 2354 2355 2356 2357 2358
            let def = self.smart_resolve_path_fragment(
                trait_ref.ref_id,
                None,
                &path,
                trait_ref.path.span,
                PathSource::Trait(AliasPossibility::No)
            ).base_def();
2359 2360
            if def != Def::Err {
                new_id = Some(def.def_id());
2361 2362 2363 2364
                let span = trait_ref.path.span;
                if let PathResult::Module(module) = self.resolve_path(&path, None, false, span) {
                    new_val = Some((module, trait_ref.clone()));
                }
2365
            }
2366
        }
2367
        let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2368
        let result = f(self, new_id);
2369 2370 2371 2372
        self.current_trait_ref = original_trait_ref;
        result
    }

2373 2374 2375 2376 2377 2378
    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....)
2379
        self_type_rib.bindings.insert(keywords::SelfType.ident(), self_def);
J
Jeffrey Seyfried 已提交
2380
        self.ribs[TypeNS].push(self_type_rib);
2381
        f(self);
J
Jeffrey Seyfried 已提交
2382
        self.ribs[TypeNS].pop();
2383 2384
    }

F
Felix S. Klock II 已提交
2385
    fn resolve_implementation(&mut self,
2386 2387 2388
                              generics: &Generics,
                              opt_trait_reference: &Option<TraitRef>,
                              self_type: &Ty,
2389
                              item_id: NodeId,
2390
                              impl_items: &[ImplItem]) {
2391
        // If applicable, create a rib for the type parameters.
2392
        self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411
            // Dummy self type for better errors if `Self` is used in the trait path.
            this.with_self_rib(Def::SelfTy(None, None), |this| {
                // Resolve the trait reference, if necessary.
                this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
                    let item_def_id = this.definitions.local_def_id(item_id);
                    this.with_self_rib(Def::SelfTy(trait_id, Some(item_def_id)), |this| {
                        if let Some(trait_ref) = opt_trait_reference.as_ref() {
                            // Resolve type arguments in trait path
                            visit::walk_trait_ref(this, trait_ref);
                        }
                        // Resolve the self type.
                        this.visit_ty(self_type);
                        // Resolve the type parameters.
                        this.visit_generics(generics);
                        this.with_current_self_type(self_type, |this| {
                            for impl_item in impl_items {
                                this.check_proc_macro_attrs(&impl_item.attrs);
                                this.resolve_visibility(&impl_item.vis);

2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436
                                // We also need a new scope for the impl item type parameters.
                                let type_parameters = HasTypeParameters(&impl_item.generics,
                                                                        TraitOrImplItemRibKind);
                                this.with_type_parameter_rib(type_parameters, |this| {
                                    use self::ResolutionError::*;
                                    match impl_item.node {
                                        ImplItemKind::Const(..) => {
                                            // If this is a trait impl, ensure the const
                                            // exists in trait
                                            this.check_trait_item(impl_item.ident,
                                                                ValueNS,
                                                                impl_item.span,
                                                |n, s| ConstNotMemberOfTrait(n, s));
                                            this.with_constant_rib(|this|
                                                visit::walk_impl_item(this, impl_item)
                                            );
                                        }
                                        ImplItemKind::Method(_, _) => {
                                            // If this is a trait impl, ensure the method
                                            // exists in trait
                                            this.check_trait_item(impl_item.ident,
                                                                ValueNS,
                                                                impl_item.span,
                                                |n, s| MethodNotMemberOfTrait(n, s));

2437
                                            visit::walk_impl_item(this, impl_item);
2438 2439 2440 2441 2442 2443 2444 2445 2446
                                        }
                                        ImplItemKind::Type(ref ty) => {
                                            // If this is a trait impl, ensure the type
                                            // exists in trait
                                            this.check_trait_item(impl_item.ident,
                                                                TypeNS,
                                                                impl_item.span,
                                                |n, s| TypeNotMemberOfTrait(n, s));

2447
                                            this.visit_ty(ty);
2448 2449 2450
                                        }
                                        ImplItemKind::Macro(_) =>
                                            panic!("unexpanded macro in resolve!"),
2451
                                    }
2452
                                });
2453
                            }
2454
                        });
2455
                    });
2456
                });
2457
            });
2458
        });
2459 2460
    }

2461
    fn check_trait_item<F>(&mut self, ident: Ident, ns: Namespace, span: Span, err: F)
C
corentih 已提交
2462 2463 2464 2465
        where F: FnOnce(Name, &str) -> ResolutionError
    {
        // If there is a TraitRef in scope for an impl, then the method must be in the
        // trait.
2466 2467 2468 2469
        if let Some((module, _)) = self.current_trait_ref {
            if self.resolve_ident_in_module(module, ident, ns, false, false, span).is_err() {
                let path = &self.current_trait_ref.as_ref().unwrap().1.path;
                resolve_error(self, span, err(ident.name, &path_names_to_string(path)));
2470 2471 2472 2473
            }
        }
    }

E
Eduard Burtescu 已提交
2474
    fn resolve_local(&mut self, local: &Local) {
2475
        // Resolve the type.
2476
        walk_list!(self, visit_ty, &local.ty);
2477

2478
        // Resolve the initializer.
2479
        walk_list!(self, visit_expr, &local.init);
2480 2481

        // Resolve the pattern.
2482
        self.resolve_pattern(&local.pat, PatternSource::Let, &mut FxHashMap());
2483 2484
    }

J
John Clements 已提交
2485 2486 2487 2488
    // 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 已提交
2489
    fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2490
        let mut binding_map = FxHashMap();
2491 2492 2493

        pat.walk(&mut |pat| {
            if let PatKind::Ident(binding_mode, ident, ref sub_pat) = pat.node {
2494 2495
                if sub_pat.is_some() || match self.def_map.get(&pat.id).map(|res| res.base_def()) {
                    Some(Def::Local(..)) => true,
2496 2497 2498
                    _ => false,
                } {
                    let binding_info = BindingInfo { span: ident.span, binding_mode: binding_mode };
V
Vadim Petrochenkov 已提交
2499
                    binding_map.insert(ident, binding_info);
2500 2501 2502
                }
            }
            true
2503
        });
2504 2505

        binding_map
2506 2507
    }

J
John Clements 已提交
2508 2509
    // check that all of the arms in an or-pattern have exactly the
    // same set of bindings, with the same binding modes for each.
2510 2511
    fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) {
        if pats.is_empty() {
C
corentih 已提交
2512
            return;
2513
        }
2514 2515 2516

        let mut missing_vars = FxHashMap();
        let mut inconsistent_vars = FxHashMap();
2517
        for (i, p) in pats.iter().enumerate() {
J
Jonas Schievink 已提交
2518
            let map_i = self.binding_mode_map(&p);
2519

2520
            for (j, q) in pats.iter().enumerate() {
2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531
                if i == j {
                    continue;
                }

                let map_j = self.binding_mode_map(&q);
                for (&key, &binding_i) in &map_i {
                    if map_j.len() == 0 {                   // Account for missing bindings when
                        let binding_error = missing_vars    // map_j has none.
                            .entry(key.name)
                            .or_insert(BindingError {
                                name: key.name,
2532 2533
                                origin: BTreeSet::new(),
                                target: BTreeSet::new(),
2534 2535 2536
                            });
                        binding_error.origin.insert(binding_i.span);
                        binding_error.target.insert(q.span);
C
corentih 已提交
2537
                    }
2538 2539 2540 2541 2542 2543 2544
                    for (&key_j, &binding_j) in &map_j {
                        match map_i.get(&key_j) {
                            None => {  // missing binding
                                let binding_error = missing_vars
                                    .entry(key_j.name)
                                    .or_insert(BindingError {
                                        name: key_j.name,
2545 2546
                                        origin: BTreeSet::new(),
                                        target: BTreeSet::new(),
2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557
                                    });
                                binding_error.origin.insert(binding_j.span);
                                binding_error.target.insert(p.span);
                            }
                            Some(binding_i) => {  // check consistent binding
                                if binding_i.binding_mode != binding_j.binding_mode {
                                    inconsistent_vars
                                        .entry(key.name)
                                        .or_insert((binding_j.span, binding_i.span));
                                }
                            }
C
corentih 已提交
2558
                        }
2559
                    }
2560 2561
                }
            }
2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573
        }
        let mut missing_vars = missing_vars.iter().collect::<Vec<_>>();
        missing_vars.sort();
        for (_, v) in missing_vars {
            resolve_error(self,
                          *v.origin.iter().next().unwrap(),
                          ResolutionError::VariableNotBoundInPattern(v));
        }
        let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
        inconsistent_vars.sort();
        for (name, v) in inconsistent_vars {
            resolve_error(self, v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
2574
        }
2575 2576
    }

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

2580
        let mut bindings_list = FxHashMap();
2581
        for pattern in &arm.pats {
2582
            self.resolve_pattern(&pattern, PatternSource::Match, &mut bindings_list);
2583 2584
        }

2585 2586
        // This has to happen *after* we determine which pat_idents are variants
        self.check_consistent_bindings(&arm.pats);
2587

2588
        walk_list!(self, visit_expr, &arm.guard);
J
Jonas Schievink 已提交
2589
        self.visit_expr(&arm.body);
2590

J
Jeffrey Seyfried 已提交
2591
        self.ribs[ValueNS].pop();
2592 2593
    }

E
Eduard Burtescu 已提交
2594
    fn resolve_block(&mut self, block: &Block) {
2595
        debug!("(resolving block) entering block");
2596
        // Move down in the graph, if there's an anonymous module rooted here.
2597
        let orig_module = self.current_module;
2598
        let anonymous_module = self.block_map.get(&block.id).cloned(); // clones a reference
2599

2600
        let mut num_macro_definition_ribs = 0;
2601 2602
        if let Some(anonymous_module) = anonymous_module {
            debug!("(resolving block) found anonymous module, moving down");
J
Jeffrey Seyfried 已提交
2603 2604
            self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
            self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
2605
            self.current_module = anonymous_module;
2606
            self.finalize_current_module_macro_resolutions();
2607
        } else {
J
Jeffrey Seyfried 已提交
2608
            self.ribs[ValueNS].push(Rib::new(NormalRibKind));
2609 2610 2611
        }

        // Descend into the block.
2612
        for stmt in &block.stmts {
2613
            if let ast::StmtKind::Item(ref item) = stmt.node {
2614
                if let ast::ItemKind::MacroDef(..) = item.node {
2615
                    num_macro_definition_ribs += 1;
2616 2617 2618
                    let def = self.definitions.local_def_id(item.id);
                    self.ribs[ValueNS].push(Rib::new(MacroDefinition(def)));
                    self.label_ribs.push(Rib::new(MacroDefinition(def)));
2619 2620 2621 2622 2623
                }
            }

            self.visit_stmt(stmt);
        }
2624 2625

        // Move back up.
J
Jeffrey Seyfried 已提交
2626
        self.current_module = orig_module;
2627
        for _ in 0 .. num_macro_definition_ribs {
J
Jeffrey Seyfried 已提交
2628
            self.ribs[ValueNS].pop();
2629
            self.label_ribs.pop();
2630
        }
J
Jeffrey Seyfried 已提交
2631
        self.ribs[ValueNS].pop();
J
Jeffrey Seyfried 已提交
2632
        if let Some(_) = anonymous_module {
J
Jeffrey Seyfried 已提交
2633
            self.ribs[TypeNS].pop();
G
Garming Sam 已提交
2634
        }
2635
        debug!("(resolving block) leaving block");
2636 2637
    }

2638
    fn fresh_binding(&mut self,
V
Vadim Petrochenkov 已提交
2639
                     ident: Ident,
2640 2641 2642
                     pat_id: NodeId,
                     outer_pat_id: NodeId,
                     pat_src: PatternSource,
2643
                     bindings: &mut FxHashMap<Ident, NodeId>)
2644 2645
                     -> PathResolution {
        // Add the binding to the local ribs, if it
2646 2647
        // doesn't already exist in the bindings map. (We
        // must not add it if it's in the bindings map
2648 2649
        // because that breaks the assumptions later
        // passes make about or-patterns.)
2650
        let mut def = Def::Local(pat_id);
V
Vadim Petrochenkov 已提交
2651
        match bindings.get(&ident).cloned() {
2652 2653 2654 2655 2656 2657
            Some(id) if id == outer_pat_id => {
                // `Variant(a, a)`, error
                resolve_error(
                    self,
                    ident.span,
                    ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
V
Vadim Petrochenkov 已提交
2658
                        &ident.name.as_str())
2659 2660 2661 2662 2663 2664 2665 2666
                );
            }
            Some(..) if pat_src == PatternSource::FnParam => {
                // `fn f(a: u8, a: u8)`, error
                resolve_error(
                    self,
                    ident.span,
                    ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
V
Vadim Petrochenkov 已提交
2667
                        &ident.name.as_str())
2668 2669
                );
            }
2670 2671 2672
            Some(..) if pat_src == PatternSource::Match ||
                        pat_src == PatternSource::IfLet ||
                        pat_src == PatternSource::WhileLet => {
2673 2674
                // `Variant1(a) | Variant2(a)`, ok
                // Reuse definition from the first `a`.
V
Vadim Petrochenkov 已提交
2675
                def = self.ribs[ValueNS].last_mut().unwrap().bindings[&ident];
2676 2677 2678 2679 2680 2681
            }
            Some(..) => {
                span_bug!(ident.span, "two bindings with the same name from \
                                       unexpected pattern source {:?}", pat_src);
            }
            None => {
2682
                // A completely fresh binding, add to the lists if it's valid.
V
Vadim Petrochenkov 已提交
2683 2684 2685
                if ident.name != keywords::Invalid.name() {
                    bindings.insert(ident, outer_pat_id);
                    self.ribs[ValueNS].last_mut().unwrap().bindings.insert(ident, def);
2686
                }
2687
            }
2688
        }
2689

2690
        PathResolution::new(def)
2691
    }
2692

2693 2694 2695 2696 2697
    fn resolve_pattern(&mut self,
                       pat: &Pat,
                       pat_src: PatternSource,
                       // Maps idents to the node ID for the
                       // outermost pattern that binds them.
2698
                       bindings: &mut FxHashMap<Ident, NodeId>) {
2699
        // Visit all direct subpatterns of this pattern.
2700 2701 2702
        let outer_pat_id = pat.id;
        pat.walk(&mut |pat| {
            match pat.node {
V
Vadim Petrochenkov 已提交
2703
                PatKind::Ident(bmode, ident, ref opt_pat) => {
2704 2705
                    // First try to resolve the identifier as some existing
                    // entity, then fall back to a fresh binding.
V
Vadim Petrochenkov 已提交
2706
                    let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS,
2707
                                                                      false, pat.span)
2708
                                      .and_then(LexicalScopeBinding::item);
2709
                    let resolution = binding.map(NameBinding::def).and_then(|def| {
2710 2711
                        let is_syntactic_ambiguity = opt_pat.is_none() &&
                            bmode == BindingMode::ByValue(Mutability::Immutable);
2712
                        match def {
2713 2714
                            Def::StructCtor(_, CtorKind::Const) |
                            Def::VariantCtor(_, CtorKind::Const) |
2715 2716 2717
                            Def::Const(..) if is_syntactic_ambiguity => {
                                // Disambiguate in favor of a unit struct/variant
                                // or constant pattern.
V
Vadim Petrochenkov 已提交
2718
                                self.record_use(ident, ValueNS, binding.unwrap(), ident.span);
2719
                                Some(PathResolution::new(def))
2720
                            }
2721
                            Def::StructCtor(..) | Def::VariantCtor(..) |
2722
                            Def::Const(..) | Def::Static(..) => {
2723 2724 2725 2726 2727
                                // This is unambiguously a fresh binding, either syntactically
                                // (e.g. `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
                                // to something unusable as a pattern (e.g. constructor function),
                                // but we still conservatively report an error, see
                                // issues/33118#issuecomment-233962221 for one reason why.
2728
                                resolve_error(
2729
                                    self,
2730 2731
                                    ident.span,
                                    ResolutionError::BindingShadowsSomethingUnacceptable(
V
Vadim Petrochenkov 已提交
2732
                                        pat_src.descr(), ident.name, binding.unwrap())
2733
                                );
2734
                                None
2735
                            }
2736
                            Def::Fn(..) | Def::Err => {
2737 2738
                                // These entities are explicitly allowed
                                // to be shadowed by fresh bindings.
2739
                                None
2740 2741 2742
                            }
                            def => {
                                span_bug!(ident.span, "unexpected definition for an \
2743
                                                       identifier in pattern: {:?}", def);
2744
                            }
2745
                        }
2746
                    }).unwrap_or_else(|| {
2747
                        self.fresh_binding(ident, pat.id, outer_pat_id, pat_src, bindings)
2748
                    });
2749 2750

                    self.record_def(pat.id, resolution);
2751 2752
                }

2753
                PatKind::TupleStruct(ref path, ..) => {
2754
                    self.smart_resolve_path(pat.id, None, path, PathSource::TupleStruct);
2755 2756
                }

2757
                PatKind::Path(ref qself, ref path) => {
2758
                    self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
2759 2760
                }

V
Vadim Petrochenkov 已提交
2761
                PatKind::Struct(ref path, ..) => {
2762
                    self.smart_resolve_path(pat.id, None, path, PathSource::Struct);
2763
                }
2764 2765

                _ => {}
2766
            }
2767
            true
2768
        });
2769

2770
        visit::walk_pat(self, pat);
2771 2772
    }

2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783
    // High-level and context dependent path resolution routine.
    // Resolves the path and records the resolution into definition map.
    // If resolution fails tries several techniques to find likely
    // resolution candidates, suggest imports or other help, and report
    // errors in user friendly way.
    fn smart_resolve_path(&mut self,
                          id: NodeId,
                          qself: Option<&QSelf>,
                          path: &Path,
                          source: PathSource)
                          -> PathResolution {
2784
        let segments = &path.segments.iter()
V
Vadim Petrochenkov 已提交
2785
            .map(|seg| seg.ident)
2786
            .collect::<Vec<_>>();
2787
        self.smart_resolve_path_fragment(id, qself, segments, path.span, source)
2788 2789 2790
    }

    fn smart_resolve_path_fragment(&mut self,
2791
                                   id: NodeId,
2792
                                   qself: Option<&QSelf>,
V
Vadim Petrochenkov 已提交
2793
                                   path: &[Ident],
2794 2795 2796
                                   span: Span,
                                   source: PathSource)
                                   -> PathResolution {
2797
        let ident_span = path.last().map_or(span, |ident| ident.span);
2798 2799
        let ns = source.namespace();
        let is_expected = &|def| source.is_expected(def);
2800
        let is_enum_variant = &|def| if let Def::Variant(..) = def { true } else { false };
2801 2802 2803 2804 2805 2806 2807

        // Base error is amended with one short label and possibly some longer helps/notes.
        let report_errors = |this: &mut Self, def: Option<Def>| {
            // Make the base error.
            let expected = source.descr_expected();
            let path_str = names_to_string(path);
            let code = source.error_code(def.is_some());
2808
            let (base_msg, fallback_label, base_span) = if let Some(def) = def {
2809
                (format!("expected {}, found {} `{}`", expected, def.kind_name(), path_str),
2810 2811
                 format!("not a {}", expected),
                 span)
2812
            } else {
V
Vadim Petrochenkov 已提交
2813
                let item_str = path[path.len() - 1];
2814
                let item_span = path[path.len() - 1].span;
2815 2816
                let (mod_prefix, mod_str) = if path.len() == 1 {
                    (format!(""), format!("this scope"))
V
Vadim Petrochenkov 已提交
2817
                } else if path.len() == 2 && path[0].name == keywords::CrateRoot.name() {
2818 2819 2820
                    (format!(""), format!("the crate root"))
                } else {
                    let mod_path = &path[..path.len() - 1];
2821
                    let mod_prefix = match this.resolve_path(mod_path, Some(TypeNS), false, span) {
2822 2823 2824 2825 2826 2827
                        PathResult::Module(module) => module.def(),
                        _ => None,
                    }.map_or(format!(""), |def| format!("{} ", def.kind_name()));
                    (mod_prefix, format!("`{}`", names_to_string(mod_path)))
                };
                (format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str),
2828 2829
                 format!("not found in {}", mod_str),
                 item_span)
2830
            };
2831
            let code = DiagnosticId::Error(code.into());
2832
            let mut err = this.session.struct_span_err_with_code(base_span, &base_msg, code);
2833 2834 2835 2836

            // Emit special messages for unresolved `Self` and `self`.
            if is_self_type(path, ns) {
                __diagnostic_used!(E0411);
2837
                err.code(DiagnosticId::Error("E0411".into()));
2838
                err.span_label(span, "`Self` is only available in traits and impls");
2839
                return (err, Vec::new());
2840 2841 2842
            }
            if is_self_value(path, ns) {
                __diagnostic_used!(E0424);
2843
                err.code(DiagnosticId::Error("E0424".into()));
2844
                err.span_label(span, format!("`self` value is only available in \
2845
                                               methods with `self` parameter"));
2846
                return (err, Vec::new());
2847 2848 2849
            }

            // Try to lookup the name in more relaxed fashion for better error reporting.
2850
            let ident = *path.last().unwrap();
V
Vadim Petrochenkov 已提交
2851
            let candidates = this.lookup_import_candidates(ident.name, ns, is_expected);
2852
            if candidates.is_empty() && is_expected(Def::Enum(DefId::local(CRATE_DEF_INDEX))) {
2853
                let enum_candidates =
V
Vadim Petrochenkov 已提交
2854
                    this.lookup_import_candidates(ident.name, ns, is_enum_variant);
E
Esteban Küber 已提交
2855 2856 2857 2858 2859
                let mut enum_candidates = enum_candidates.iter()
                    .map(|suggestion| import_candidate_to_paths(&suggestion)).collect::<Vec<_>>();
                enum_candidates.sort();
                for (sp, variant_path, enum_path) in enum_candidates {
                    if sp == DUMMY_SP {
2860 2861 2862 2863
                        let msg = format!("there is an enum variant `{}`, \
                                        try using `{}`?",
                                        variant_path,
                                        enum_path);
2864 2865
                        err.help(&msg);
                    } else {
2866 2867
                        err.span_suggestion(span, "you can try using the variant's enum",
                                            enum_path);
2868 2869
                    }
                }
2870
            }
2871
            if path.len() == 1 && this.self_type_is_available(span) {
V
Vadim Petrochenkov 已提交
2872 2873
                if let Some(candidate) = this.lookup_assoc_candidate(ident, ns, is_expected) {
                    let self_is_available = this.self_value_is_available(path[0].span, span);
2874 2875
                    match candidate {
                        AssocSuggestion::Field => {
2876 2877
                            err.span_suggestion(span, "try",
                                                format!("self.{}", path_str));
2878
                            if !self_is_available {
2879
                                err.span_label(span, format!("`self` value is only available in \
2880 2881 2882 2883
                                                               methods with `self` parameter"));
                            }
                        }
                        AssocSuggestion::MethodWithSelf if self_is_available => {
2884 2885
                            err.span_suggestion(span, "try",
                                                format!("self.{}", path_str));
2886 2887
                        }
                        AssocSuggestion::MethodWithSelf | AssocSuggestion::AssocItem => {
2888 2889
                            err.span_suggestion(span, "try",
                                                format!("Self::{}", path_str));
2890 2891
                        }
                    }
2892
                    return (err, candidates);
2893 2894 2895
                }
            }

2896 2897 2898
            let mut levenshtein_worked = false;

            // Try Levenshtein.
2899
            if let Some(candidate) = this.lookup_typo_candidate(path, ns, is_expected, span) {
2900
                err.span_label(ident_span, format!("did you mean `{}`?", candidate));
2901 2902 2903
                levenshtein_worked = true;
            }

2904 2905 2906 2907
            // Try context dependent help if relaxed lookup didn't work.
            if let Some(def) = def {
                match (def, source) {
                    (Def::Macro(..), _) => {
2908
                        err.span_label(span, format!("did you mean `{}!(...)`?", path_str));
2909
                        return (err, candidates);
2910
                    }
A
Alex Burka 已提交
2911
                    (Def::TyAlias(..), PathSource::Trait(_)) => {
2912
                        err.span_label(span, "type aliases cannot be used for traits");
2913
                        return (err, candidates);
2914
                    }
2915
                    (Def::Mod(..), PathSource::Expr(Some(parent))) => match parent.node {
2916
                        ExprKind::Field(_, ident) => {
2917
                            err.span_label(parent.span, format!("did you mean `{}::{}`?",
V
Vadim Petrochenkov 已提交
2918
                                                                 path_str, ident));
2919
                            return (err, candidates);
2920
                        }
2921
                        ExprKind::MethodCall(ref segment, ..) => {
2922
                            err.span_label(parent.span, format!("did you mean `{}::{}(...)`?",
2923
                                                                 path_str, segment.ident));
2924
                            return (err, candidates);
2925 2926 2927
                        }
                        _ => {}
                    },
2928 2929
                    (Def::Enum(..), PathSource::TupleStruct)
                        | (Def::Enum(..), PathSource::Expr(..))  => {
2930 2931 2932 2933
                        if let Some(variants) = this.collect_enum_variants(def) {
                            err.note(&format!("did you mean to use one \
                                               of the following variants?\n{}",
                                variants.iter()
2934 2935
                                    .map(|suggestion| path_names_to_string(suggestion))
                                    .map(|suggestion| format!("- `{}`", suggestion))
2936 2937 2938 2939 2940 2941 2942 2943
                                    .collect::<Vec<_>>()
                                    .join("\n")));

                        } else {
                            err.note("did you mean to use one of the enum's variants?");
                        }
                        return (err, candidates);
                    },
E
Esteban Küber 已提交
2944
                    (Def::Struct(def_id), _) if ns == ValueNS => {
2945 2946 2947 2948 2949 2950
                        if let Some((ctor_def, ctor_vis))
                                = this.struct_constructors.get(&def_id).cloned() {
                            let accessible_ctor = this.is_accessible(ctor_vis);
                            if is_expected(ctor_def) && !accessible_ctor {
                                err.span_label(span, format!("constructor is not visible \
                                                              here due to private fields"));
2951
                            }
2952
                        } else {
2953 2954
                            err.span_label(span, format!("did you mean `{} {{ /* fields */ }}`?",
                                                         path_str));
2955
                        }
2956
                        return (err, candidates);
2957
                    }
2958 2959 2960
                    (Def::Union(..), _) |
                    (Def::Variant(..), _) |
                    (Def::VariantCtor(_, CtorKind::Fictive), _) if ns == ValueNS => {
2961
                        err.span_label(span, format!("did you mean `{} {{ /* fields */ }}`?",
2962
                                                     path_str));
2963
                        return (err, candidates);
2964
                    }
E
Esteban Küber 已提交
2965
                    (Def::SelfTy(..), _) if ns == ValueNS => {
2966
                        err.span_label(span, fallback_label);
E
Esteban Küber 已提交
2967 2968
                        err.note("can't use `Self` as a constructor, you must use the \
                                  implemented struct");
2969
                        return (err, candidates);
2970
                    }
2971
                    (Def::TyAlias(_), _) | (Def::AssociatedTy(..), _) if ns == ValueNS => {
E
Esteban Küber 已提交
2972
                        err.note("can't use a type alias as a constructor");
2973
                        return (err, candidates);
E
Esteban Küber 已提交
2974
                    }
2975 2976 2977 2978
                    _ => {}
                }
            }

2979
            // Fallback label.
2980
            if !levenshtein_worked {
2981
                err.span_label(base_span, fallback_label);
2982
                this.type_ascription_suggestion(&mut err, base_span);
2983
            }
2984
            (err, candidates)
2985 2986
        };
        let report_errors = |this: &mut Self, def: Option<Def>| {
2987 2988 2989 2990 2991
            let (err, candidates) = report_errors(this, def);
            let def_id = this.current_module.normal_ancestor_id;
            let node_id = this.definitions.as_local_node_id(def_id).unwrap();
            let better = def.is_some();
            this.use_injections.push(UseError { err, candidates, node_id, better });
2992 2993 2994 2995 2996 2997
            err_path_resolution()
        };

        let resolution = match self.resolve_qpath_anywhere(id, qself, path, ns, span,
                                                           source.defer_to_typeck(),
                                                           source.global_by_default()) {
2998 2999
            Some(resolution) if resolution.unresolved_segments() == 0 => {
                if is_expected(resolution.base_def()) || resolution.base_def() == Def::Err {
3000 3001
                    resolution
                } else {
3002 3003 3004
                    // Add a temporary hack to smooth the transition to new struct ctor
                    // visibility rules. See #38932 for more details.
                    let mut res = None;
3005
                    if let Def::Struct(def_id) = resolution.base_def() {
3006
                        if let Some((ctor_def, ctor_vis))
3007
                                = self.struct_constructors.get(&def_id).cloned() {
3008 3009
                            if is_expected(ctor_def) && self.is_accessible(ctor_vis) {
                                let lint = lint::builtin::LEGACY_CONSTRUCTOR_VISIBILITY;
3010
                                self.session.buffer_lint(lint, id, span,
3011
                                    "private struct constructors are not usable through \
3012
                                     re-exports in outer modules",
3013
                                );
3014 3015 3016 3017 3018
                                res = Some(PathResolution::new(ctor_def));
                            }
                        }
                    }

3019
                    res.unwrap_or_else(|| report_errors(self, Some(resolution.base_def())))
3020 3021 3022 3023 3024 3025 3026
                }
            }
            Some(resolution) if source.defer_to_typeck() => {
                // 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.
                if ns == ValueNS {
V
Vadim Petrochenkov 已提交
3027
                    let item_name = *path.last().unwrap();
3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042
                    let traits = self.get_traits_containing_item(item_name, ns);
                    self.trait_map.insert(id, traits);
                }
                resolution
            }
            _ => report_errors(self, None)
        };

        if let PathSource::TraitItem(..) = source {} else {
            // Avoid recording definition of `A::B` in `<T as A>::B::C`.
            self.record_def(id, resolution);
        }
        resolution
    }

3043 3044 3045 3046 3047 3048 3049 3050 3051
    fn type_ascription_suggestion(&self,
                                  err: &mut DiagnosticBuilder,
                                  base_span: Span) {
        debug!("type_ascription_suggetion {:?}", base_span);
        let cm = self.session.codemap();
        debug!("self.current_type_ascription {:?}", self.current_type_ascription);
        if let Some(sp) = self.current_type_ascription.last() {
            let mut sp = *sp;
            loop {  // try to find the `:`, bail on first non-':'/non-whitespace
3052 3053
                sp = cm.next_point(sp);
                if let Ok(snippet) = cm.span_to_snippet(sp.to(cm.next_point(sp))) {
3054
                    debug!("snippet {:?}", snippet);
3055 3056
                    let line_sp = cm.lookup_char_pos(sp.hi()).line;
                    let line_base_sp = cm.lookup_char_pos(base_span.lo()).line;
3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077
                    debug!("{:?} {:?}", line_sp, line_base_sp);
                    if snippet == ":" {
                        err.span_label(base_span,
                                       "expecting a type here because of type ascription");
                        if line_sp != line_base_sp {
                            err.span_suggestion_short(sp,
                                                      "did you mean to use `;` here instead?",
                                                      ";".to_string());
                        }
                        break;
                    } else if snippet.trim().len() != 0  {
                        debug!("tried to find type ascription `:` token, couldn't find it");
                        break;
                    }
                } else {
                    break;
                }
            }
        }
    }

3078 3079 3080
    fn self_type_is_available(&mut self, span: Span) -> bool {
        let binding = self.resolve_ident_in_lexical_scope(keywords::SelfType.ident(),
                                                          TypeNS, false, span);
3081 3082 3083
        if let Some(LexicalScopeBinding::Def(def)) = binding { def != Def::Err } else { false }
    }

3084 3085 3086
    fn self_value_is_available(&mut self, self_span: Span, path_span: Span) -> bool {
        let ident = Ident::new(keywords::SelfValue.name(), self_span);
        let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, false, path_span);
3087 3088 3089 3090 3091 3092 3093
        if let Some(LexicalScopeBinding::Def(def)) = binding { def != Def::Err } else { false }
    }

    // Resolve in alternative namespaces if resolution in the primary namespace fails.
    fn resolve_qpath_anywhere(&mut self,
                              id: NodeId,
                              qself: Option<&QSelf>,
V
Vadim Petrochenkov 已提交
3094
                              path: &[Ident],
3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107
                              primary_ns: Namespace,
                              span: Span,
                              defer_to_typeck: bool,
                              global_by_default: bool)
                              -> Option<PathResolution> {
        let mut fin_res = None;
        // FIXME: can't resolve paths in macro namespace yet, macros are
        // processed by the little special hack below.
        for (i, ns) in [primary_ns, TypeNS, ValueNS, /*MacroNS*/].iter().cloned().enumerate() {
            if i == 0 || ns != primary_ns {
                match self.resolve_qpath(id, qself, path, ns, span, global_by_default) {
                    // If defer_to_typeck, then resolution > no resolution,
                    // otherwise full resolution > partial resolution > no resolution.
3108 3109
                    Some(res) if res.unresolved_segments() == 0 || defer_to_typeck =>
                        return Some(res),
3110 3111 3112 3113
                    res => if fin_res.is_none() { fin_res = res },
                };
            }
        }
V
Vadim Petrochenkov 已提交
3114
        let is_global = self.global_macros.get(&path[0].name).cloned()
3115
            .map(|binding| binding.get_macro(self).kind() == MacroKind::Bang).unwrap_or(false);
3116
        if primary_ns != MacroNS && (is_global ||
V
Vadim Petrochenkov 已提交
3117
                                     self.macro_names.contains(&path[0].modern())) {
3118
            // Return some dummy definition, it's enough for error reporting.
J
Josh Driver 已提交
3119 3120 3121
            return Some(
                PathResolution::new(Def::Macro(DefId::local(CRATE_DEF_INDEX), MacroKind::Bang))
            );
3122 3123 3124 3125 3126 3127 3128 3129
        }
        fin_res
    }

    /// Handles paths that may refer to associated items.
    fn resolve_qpath(&mut self,
                     id: NodeId,
                     qself: Option<&QSelf>,
V
Vadim Petrochenkov 已提交
3130
                     path: &[Ident],
3131 3132 3133 3134 3135
                     ns: Namespace,
                     span: Span,
                     global_by_default: bool)
                     -> Option<PathResolution> {
        if let Some(qself) = qself {
J
Jeffrey Seyfried 已提交
3136 3137
            if qself.position == 0 {
                // FIXME: Create some fake resolution that can't possibly be a type.
3138 3139 3140
                return Some(PathResolution::with_unresolved_segments(
                    Def::Mod(DefId::local(CRATE_DEF_INDEX)), path.len()
                ));
3141
            }
3142 3143
            // Make sure `A::B` in `<T as A>::B::C` is a trait item.
            let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
3144
            let res = self.smart_resolve_path_fragment(id, None, &path[..qself.position + 1],
3145
                                                       span, PathSource::TraitItem(ns));
3146 3147 3148
            return Some(PathResolution::with_unresolved_segments(
                res.base_def(), res.unresolved_segments() + path.len() - qself.position - 1
            ));
3149 3150
        }

3151
        let result = match self.resolve_path(&path, Some(ns), true, span) {
3152
            PathResult::NonModule(path_res) => path_res,
J
Jeffrey Seyfried 已提交
3153 3154
            PathResult::Module(module) if !module.is_normal() => {
                PathResolution::new(module.def().unwrap())
V
Cleanup  
Vadim Petrochenkov 已提交
3155
            }
3156 3157 3158 3159 3160 3161
            // 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 已提交
3162 3163
            //     u8::max_value() // OK, resolves to associated function <u8>::max_value,
            //                     // not to non-existent std::u8::max_value
3164 3165 3166 3167
            // }
            //
            // Such behavior is required for backward compatibility.
            // The same fallback is used when `a` resolves to nothing.
3168
            PathResult::Module(..) | PathResult::Failed(..)
3169
                    if (ns == TypeNS || path.len() > 1) &&
3170
                       self.primitive_type_table.primitive_types
V
Vadim Petrochenkov 已提交
3171 3172
                           .contains_key(&path[0].name) => {
                let prim = self.primitive_type_table.primitive_types[&path[0].name];
3173
                PathResolution::with_unresolved_segments(Def::PrimTy(prim), path.len() - 1)
J
Jeffrey Seyfried 已提交
3174 3175
            }
            PathResult::Module(module) => PathResolution::new(module.def().unwrap()),
3176
            PathResult::Failed(span, msg, false) => {
J
Jeffrey Seyfried 已提交
3177 3178 3179
                resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
                err_path_resolution()
            }
3180 3181
            PathResult::Failed(..) => return None,
            PathResult::Indeterminate => bug!("indetermined path result in resolve_qpath"),
J
Jeffrey Seyfried 已提交
3182 3183
        };

3184
        if path.len() > 1 && !global_by_default && result.base_def() != Def::Err &&
V
Vadim Petrochenkov 已提交
3185 3186
           path[0].name != keywords::CrateRoot.name() &&
           path[0].name != keywords::DollarCrate.name() {
3187
            let unqualified_result = {
3188
                match self.resolve_path(&[*path.last().unwrap()], Some(ns), false, span) {
3189
                    PathResult::NonModule(path_res) => path_res.base_def(),
3190 3191 3192 3193
                    PathResult::Module(module) => module.def().unwrap(),
                    _ => return Some(result),
                }
            };
3194
            if result.base_def() == unqualified_result {
3195
                let lint = lint::builtin::UNUSED_QUALIFICATIONS;
3196
                self.session.buffer_lint(lint, id, span, "unnecessary qualification")
N
Nick Cameron 已提交
3197
            }
3198
        }
N
Nick Cameron 已提交
3199

J
Jeffrey Seyfried 已提交
3200
        Some(result)
3201 3202
    }

J
Jeffrey Seyfried 已提交
3203
    fn resolve_path(&mut self,
V
Vadim Petrochenkov 已提交
3204
                    path: &[Ident],
J
Jeffrey Seyfried 已提交
3205
                    opt_ns: Option<Namespace>, // `None` indicates a module path
3206 3207
                    record_used: bool,
                    path_span: Span)
J
Jeffrey Seyfried 已提交
3208
                    -> PathResult<'a> {
3209 3210
        let mut module = None;
        let mut allow_super = true;
J
Jeffrey Seyfried 已提交
3211 3212

        for (i, &ident) in path.iter().enumerate() {
3213
            debug!("resolve_path ident {} {:?}", i, ident);
J
Jeffrey Seyfried 已提交
3214 3215
            let is_last = i == path.len() - 1;
            let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
V
Vadim Petrochenkov 已提交
3216
            let name = ident.name;
J
Jeffrey Seyfried 已提交
3217

3218
            if i == 0 && ns == TypeNS && name == keywords::SelfValue.name() {
V
Vadim Petrochenkov 已提交
3219
                let mut ctxt = ident.span.ctxt().modern();
J
Jeffrey Seyfried 已提交
3220
                module = Some(self.resolve_self(&mut ctxt, self.current_module));
J
Jeffrey Seyfried 已提交
3221
                continue
3222
            } else if allow_super && ns == TypeNS && name == keywords::Super.name() {
V
Vadim Petrochenkov 已提交
3223
                let mut ctxt = ident.span.ctxt().modern();
J
Jeffrey Seyfried 已提交
3224 3225 3226 3227
                let self_module = match i {
                    0 => self.resolve_self(&mut ctxt, self.current_module),
                    _ => module.unwrap(),
                };
J
Jeffrey Seyfried 已提交
3228
                if let Some(parent) = self_module.parent {
J
Jeffrey Seyfried 已提交
3229
                    module = Some(self.resolve_self(&mut ctxt, parent));
J
Jeffrey Seyfried 已提交
3230 3231 3232
                    continue
                } else {
                    let msg = "There are too many initial `super`s.".to_string();
3233
                    return PathResult::Failed(ident.span, msg, false);
J
Jeffrey Seyfried 已提交
3234
                }
V
Vadim Petrochenkov 已提交
3235 3236
            } else if i == 0 && ns == TypeNS && name == keywords::Extern.name() {
                continue;
J
Jeffrey Seyfried 已提交
3237 3238 3239
            }
            allow_super = false;

V
Vadim Petrochenkov 已提交
3240
            if ns == TypeNS {
3241 3242
                if (i == 0 && name == keywords::CrateRoot.name()) ||
                   (i == 1 && name == keywords::Crate.name() &&
V
Vadim Petrochenkov 已提交
3243
                              path[0].name == keywords::CrateRoot.name()) {
V
Vadim Petrochenkov 已提交
3244
                    // `::a::b` or `::crate::a::b`
V
Vadim Petrochenkov 已提交
3245
                    module = Some(self.resolve_crate_root(ident.span.ctxt(), false));
V
Vadim Petrochenkov 已提交
3246
                    continue
3247
                } else if i == 0 && name == keywords::DollarCrate.name() {
V
Vadim Petrochenkov 已提交
3248
                    // `$crate::a::b`
V
Vadim Petrochenkov 已提交
3249
                    module = Some(self.resolve_crate_root(ident.span.ctxt(), true));
V
Vadim Petrochenkov 已提交
3250
                    continue
V
Vadim Petrochenkov 已提交
3251 3252
                } else if i == 1 && !token::is_path_segment_keyword(ident) {
                    let prev_name = path[0].name;
V
Vadim Petrochenkov 已提交
3253 3254
                    if prev_name == keywords::Extern.name() ||
                       prev_name == keywords::CrateRoot.name() &&
3255
                       self.session.features_untracked().extern_absolute_paths {
V
Vadim Petrochenkov 已提交
3256
                        // `::extern_crate::a::b`
3257
                        let crate_id = self.crate_loader.process_path_extern(name, ident.span);
V
Vadim Petrochenkov 已提交
3258 3259 3260 3261 3262 3263
                        let crate_root =
                            self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
                        self.populate_module_if_necessary(crate_root);
                        module = Some(crate_root);
                        continue
                    }
V
Vadim Petrochenkov 已提交
3264
                }
3265 3266
            }

3267 3268 3269 3270 3271 3272
            // Report special messages for path segment keywords in wrong positions.
            if name == keywords::CrateRoot.name() && i != 0 ||
               name == keywords::DollarCrate.name() && i != 0 ||
               name == keywords::SelfValue.name() && i != 0 ||
               name == keywords::SelfType.name() && i != 0 ||
               name == keywords::Super.name() && i != 0 ||
V
Vadim Petrochenkov 已提交
3273
               name == keywords::Extern.name() && i != 0 ||
3274
               name == keywords::Crate.name() && i != 1 &&
V
Vadim Petrochenkov 已提交
3275
                    path[0].name != keywords::CrateRoot.name() {
3276 3277 3278 3279 3280
                let name_str = if name == keywords::CrateRoot.name() {
                    format!("crate root")
                } else {
                    format!("`{}`", name)
                };
V
Vadim Petrochenkov 已提交
3281
                let msg = if i == 1 && path[0].name == keywords::CrateRoot.name() {
3282 3283 3284 3285 3286 3287 3288 3289 3290
                    format!("global paths cannot start with {}", name_str)
                } else if i == 0 && name == keywords::Crate.name() {
                    format!("{} can only be used in absolute paths", name_str)
                } else {
                    format!("{} in paths can only be used in start position", name_str)
                };
                return PathResult::Failed(ident.span, msg, false);
            }

J
Jeffrey Seyfried 已提交
3291
            let binding = if let Some(module) = module {
V
Vadim Petrochenkov 已提交
3292
                self.resolve_ident_in_module(module, ident, ns, false, record_used, path_span)
3293
            } else if opt_ns == Some(MacroNS) {
V
Vadim Petrochenkov 已提交
3294
                self.resolve_lexical_macro_path_segment(ident, ns, record_used, path_span)
3295
                    .map(MacroBinding::binding)
J
Jeffrey Seyfried 已提交
3296
            } else {
V
Vadim Petrochenkov 已提交
3297
                match self.resolve_ident_in_lexical_scope(ident, ns, record_used, path_span) {
J
Jeffrey Seyfried 已提交
3298
                    Some(LexicalScopeBinding::Item(binding)) => Ok(binding),
3299 3300
                    Some(LexicalScopeBinding::Def(def))
                            if opt_ns == Some(TypeNS) || opt_ns == Some(ValueNS) => {
3301 3302 3303
                        return PathResult::NonModule(PathResolution::with_unresolved_segments(
                            def, path.len() - 1
                        ));
J
Jeffrey Seyfried 已提交
3304
                    }
3305
                    _ => Err(if record_used { Determined } else { Undetermined }),
J
Jeffrey Seyfried 已提交
3306 3307 3308 3309 3310
                }
            };

            match binding {
                Ok(binding) => {
3311 3312
                    let def = binding.def();
                    let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(def);
J
Jeffrey Seyfried 已提交
3313
                    if let Some(next_module) = binding.module() {
J
Jeffrey Seyfried 已提交
3314
                        module = Some(next_module);
3315
                    } else if def == Def::Err {
J
Jeffrey Seyfried 已提交
3316
                        return PathResult::NonModule(err_path_resolution());
3317
                    } else if opt_ns.is_some() && (is_last || maybe_assoc) {
3318 3319 3320
                        return PathResult::NonModule(PathResolution::with_unresolved_segments(
                            def, path.len() - i - 1
                        ));
J
Jeffrey Seyfried 已提交
3321
                    } else {
3322
                        return PathResult::Failed(ident.span,
V
Vadim Petrochenkov 已提交
3323
                                                  format!("Not a module `{}`", ident),
3324
                                                  is_last);
J
Jeffrey Seyfried 已提交
3325 3326 3327 3328 3329 3330
                    }
                }
                Err(Undetermined) => return PathResult::Indeterminate,
                Err(Determined) => {
                    if let Some(module) = module {
                        if opt_ns.is_some() && !module.is_normal() {
3331 3332 3333
                            return PathResult::NonModule(PathResolution::with_unresolved_segments(
                                module.def().unwrap(), path.len() - i
                            ));
J
Jeffrey Seyfried 已提交
3334 3335
                        }
                    }
3336
                    let msg = if module.and_then(ModuleData::def) == self.graph_root.def() {
J
Jeffrey Seyfried 已提交
3337 3338
                        let is_mod = |def| match def { Def::Mod(..) => true, _ => false };
                        let mut candidates =
3339
                            self.lookup_import_candidates(name, TypeNS, is_mod);
3340 3341 3342
                        candidates.sort_by_cached_key(|c| {
                            (c.path.segments.len(), c.path.to_string())
                        });
J
Jeffrey Seyfried 已提交
3343
                        if let Some(candidate) = candidates.get(0) {
3344
                            format!("Did you mean `{}`?", candidate.path)
J
Jeffrey Seyfried 已提交
3345
                        } else {
V
Vadim Petrochenkov 已提交
3346
                            format!("Maybe a missing `extern crate {};`?", ident)
J
Jeffrey Seyfried 已提交
3347 3348
                        }
                    } else if i == 0 {
V
Vadim Petrochenkov 已提交
3349
                        format!("Use of undeclared type or module `{}`", ident)
J
Jeffrey Seyfried 已提交
3350
                    } else {
V
Vadim Petrochenkov 已提交
3351
                        format!("Could not find `{}` in `{}`", ident, path[i - 1])
J
Jeffrey Seyfried 已提交
3352
                    };
3353
                    return PathResult::Failed(ident.span, msg, is_last);
J
Jeffrey Seyfried 已提交
3354 3355
                }
            }
3356 3357
        }

3358
        PathResult::Module(module.unwrap_or(self.graph_root))
3359 3360 3361
    }

    // Resolve a local definition, potentially adjusting for closures.
3362 3363 3364 3365
    fn adjust_local_def(&mut self,
                        ns: Namespace,
                        rib_index: usize,
                        mut def: Def,
3366 3367
                        record_used: bool,
                        span: Span) -> Def {
3368 3369 3370 3371
        let ribs = &self.ribs[ns][rib_index + 1..];

        // An invalid forward use of a type parameter from a previous default.
        if let ForwardTyParamBanRibKind = self.ribs[ns][rib_index].kind {
3372
            if record_used {
3373
                resolve_error(self, span, ResolutionError::ForwardDeclaredTyParam);
3374 3375 3376 3377 3378
            }
            assert_eq!(def, Def::Err);
            return Def::Err;
        }

3379
        match def {
3380
            Def::Upvar(..) => {
3381
                span_bug!(span, "unexpected {:?} in bindings", def)
3382
            }
3383
            Def::Local(node_id) => {
3384 3385
                for rib in ribs {
                    match rib.kind {
3386 3387
                        NormalRibKind | ModuleRibKind(..) | MacroDefinition(..) |
                        ForwardTyParamBanRibKind => {
3388 3389 3390 3391 3392
                            // Nothing to do. Continue.
                        }
                        ClosureRibKind(function_id) => {
                            let prev_def = def;

C
corentih 已提交
3393 3394 3395
                            let seen = self.freevars_seen
                                           .entry(function_id)
                                           .or_insert_with(|| NodeMap());
3396
                            if let Some(&index) = seen.get(&node_id) {
3397
                                def = Def::Upvar(node_id, index, function_id);
3398 3399
                                continue;
                            }
C
corentih 已提交
3400 3401 3402
                            let vec = self.freevars
                                          .entry(function_id)
                                          .or_insert_with(|| vec![]);
3403
                            let depth = vec.len();
3404
                            def = Def::Upvar(node_id, depth, function_id);
3405

3406
                            if record_used {
3407 3408
                                vec.push(Freevar {
                                    def: prev_def,
3409
                                    span,
3410 3411 3412
                                });
                                seen.insert(node_id, depth);
                            }
3413
                        }
3414
                        ItemRibKind | TraitOrImplItemRibKind => {
3415 3416 3417
                            // This was an attempt to access an upvar inside a
                            // named function item. This is not allowed, so we
                            // report an error.
3418
                            if record_used {
3419 3420 3421
                                resolve_error(self, span,
                                        ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
                            }
3422
                            return Def::Err;
3423 3424 3425
                        }
                        ConstantItemRibKind => {
                            // Still doesn't deal with upvars
3426
                            if record_used {
3427 3428 3429
                                resolve_error(self, span,
                                        ResolutionError::AttemptToUseNonConstantValueInConstant);
                            }
3430
                            return Def::Err;
3431 3432 3433 3434
                        }
                    }
                }
            }
3435
            Def::TyParam(..) | Def::SelfTy(..) => {
3436 3437
                for rib in ribs {
                    match rib.kind {
3438
                        NormalRibKind | TraitOrImplItemRibKind | ClosureRibKind(..) |
3439 3440
                        ModuleRibKind(..) | MacroDefinition(..) | ForwardTyParamBanRibKind |
                        ConstantItemRibKind => {
3441 3442 3443 3444 3445
                            // Nothing to do. Continue.
                        }
                        ItemRibKind => {
                            // This was an attempt to use a type parameter outside
                            // its scope.
3446
                            if record_used {
3447
                                resolve_error(self, span,
3448
                                    ResolutionError::TypeParametersFromOuterFunction(def));
3449
                            }
3450
                            return Def::Err;
3451 3452 3453 3454 3455 3456
                        }
                    }
                }
            }
            _ => {}
        }
3457
        return def;
3458 3459
    }

3460
    fn lookup_assoc_candidate<FilterFn>(&mut self,
3461
                                        ident: Ident,
3462 3463 3464 3465 3466
                                        ns: Namespace,
                                        filter_fn: FilterFn)
                                        -> Option<AssocSuggestion>
        where FilterFn: Fn(Def) -> bool
    {
3467
        fn extract_node_id(t: &Ty) -> Option<NodeId> {
3468
            match t.node {
3469 3470
                TyKind::Path(None, _) => Some(t.id),
                TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
3471 3472 3473 3474 3475 3476 3477
                // 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,
            }
        }

3478
        // Fields are generally expected in the same contexts as locals.
3479
        if filter_fn(Def::Local(ast::DUMMY_NODE_ID)) {
3480 3481 3482
            if let Some(node_id) = self.current_self_type.as_ref().and_then(extract_node_id) {
                // Look for a field with the same name in the current self_type.
                if let Some(resolution) = self.def_map.get(&node_id) {
3483 3484 3485
                    match resolution.base_def() {
                        Def::Struct(did) | Def::Union(did)
                                if resolution.unresolved_segments() == 0 => {
3486
                            if let Some(field_names) = self.field_names.get(&did) {
3487
                                if field_names.iter().any(|&field_name| ident.name == field_name) {
3488 3489
                                    return Some(AssocSuggestion::Field);
                                }
3490
                            }
3491
                        }
3492
                        _ => {}
3493
                    }
3494
                }
3495
            }
3496 3497
        }

3498
        // Look for associated items in the current trait.
3499 3500 3501 3502
        if let Some((module, _)) = self.current_trait_ref {
            if let Ok(binding) =
                    self.resolve_ident_in_module(module, ident, ns, false, false, module.span) {
                let def = binding.def();
3503
                if filter_fn(def) {
3504
                    return Some(if self.has_self.contains(&def.def_id()) {
3505 3506 3507 3508
                        AssocSuggestion::MethodWithSelf
                    } else {
                        AssocSuggestion::AssocItem
                    });
3509 3510 3511 3512
                }
            }
        }

3513
        None
3514 3515
    }

3516
    fn lookup_typo_candidate<FilterFn>(&mut self,
V
Vadim Petrochenkov 已提交
3517
                                       path: &[Ident],
3518
                                       ns: Namespace,
3519 3520
                                       filter_fn: FilterFn,
                                       span: Span)
3521
                                       -> Option<Symbol>
3522 3523
        where FilterFn: Fn(Def) -> bool
    {
3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534
        let add_module_candidates = |module: Module, names: &mut Vec<Name>| {
            for (&(ident, _), resolution) in module.resolutions.borrow().iter() {
                if let Some(binding) = resolution.borrow().binding {
                    if filter_fn(binding.def()) {
                        names.push(ident.name);
                    }
                }
            }
        };

        let mut names = Vec::new();
3535
        if path.len() == 1 {
3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571
            // Search in lexical scope.
            // Walk backwards up the ribs in scope and collect candidates.
            for rib in self.ribs[ns].iter().rev() {
                // Locals and type parameters
                for (ident, def) in &rib.bindings {
                    if filter_fn(*def) {
                        names.push(ident.name);
                    }
                }
                // Items in scope
                if let ModuleRibKind(module) = rib.kind {
                    // Items from this module
                    add_module_candidates(module, &mut names);

                    if let ModuleKind::Block(..) = module.kind {
                        // We can see through blocks
                    } else {
                        // Items from the prelude
                        if let Some(prelude) = self.prelude {
                            if !module.no_implicit_prelude {
                                add_module_candidates(prelude, &mut names);
                            }
                        }
                        break;
                    }
                }
            }
            // Add primitive types to the mix
            if filter_fn(Def::PrimTy(TyBool)) {
                for (name, _) in &self.primitive_type_table.primitive_types {
                    names.push(*name);
                }
            }
        } else {
            // Search in module.
            let mod_path = &path[..path.len() - 1];
3572 3573
            if let PathResult::Module(module) = self.resolve_path(mod_path, Some(TypeNS),
                                                                  false, span) {
3574 3575
                add_module_candidates(module, &mut names);
            }
3576
        }
3577

V
Vadim Petrochenkov 已提交
3578
        let name = path[path.len() - 1].name;
3579
        // Make sure error reporting is deterministic.
3580
        names.sort_by_cached_key(|name| name.as_str());
3581
        match find_best_match_for_name(names.iter(), &name.as_str(), None) {
3582
            Some(found) if found != name => Some(found),
3583
            _ => None,
3584
        }
3585 3586
    }

3587
    fn with_resolved_label<F>(&mut self, label: Option<Label>, id: NodeId, f: F)
3588 3589
        where F: FnOnce(&mut Resolver)
    {
3590
        if let Some(label) = label {
3591
            let def = Def::Label(id);
3592
            self.with_label_rib(|this| {
3593
                this.label_ribs.last_mut().unwrap().bindings.insert(label.ident, def);
3594
                f(this);
3595 3596
            });
        } else {
3597
            f(self);
3598 3599 3600
        }
    }

3601
    fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &Block) {
3602 3603 3604
        self.with_resolved_label(label, id, |this| this.visit_block(block));
    }

3605
    fn resolve_expr(&mut self, expr: &Expr, parent: Option<&Expr>) {
P
Patrick Walton 已提交
3606 3607
        // First, record candidate traits for this expression if it could
        // result in the invocation of a method call.
3608 3609 3610

        self.record_candidate_traits_for_expr_if_necessary(expr);

3611
        // Next, resolve the node.
3612
        match expr.node {
3613 3614
            ExprKind::Path(ref qself, ref path) => {
                self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
3615
                visit::walk_expr(self, expr);
3616 3617
            }

V
Vadim Petrochenkov 已提交
3618
            ExprKind::Struct(ref path, ..) => {
3619
                self.smart_resolve_path(expr.id, None, path, PathSource::Struct);
3620
                visit::walk_expr(self, expr);
3621 3622
            }

3623
            ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
3624
                match self.search_label(label.ident, |rib, id| rib.bindings.get(&id).cloned()) {
3625
                    None => {
3626 3627 3628
                        // Search again for close matches...
                        // Picks the first label that is "close enough", which is not necessarily
                        // the closest match
3629
                        let close_match = self.search_label(label.ident, |rib, ident| {
3630 3631 3632
                            let names = rib.bindings.iter().map(|(id, _)| &id.name);
                            find_best_match_for_name(names, &*ident.name.as_str(), None)
                        });
3633
                        self.record_def(expr.id, err_path_resolution());
3634
                        resolve_error(self,
3635
                                      label.ident.span,
3636
                                      ResolutionError::UndeclaredLabel(&label.ident.name.as_str(),
3637
                                                                       close_match));
3638
                    }
3639
                    Some(def @ Def::Label(_)) => {
3640
                        // Since this def is a label, it is never read.
3641
                        self.record_def(expr.id, PathResolution::new(def));
3642 3643
                    }
                    Some(_) => {
3644
                        span_bug!(expr.span, "label wasn't mapped to a label def!");
3645 3646
                    }
                }
3647 3648 3649

                // visit `break` argument if any
                visit::walk_expr(self, expr);
3650
            }
3651

3652
            ExprKind::IfLet(ref pats, ref subexpression, ref if_block, ref optional_else) => {
3653 3654
                self.visit_expr(subexpression);

J
Jeffrey Seyfried 已提交
3655
                self.ribs[ValueNS].push(Rib::new(NormalRibKind));
3656 3657 3658 3659 3660 3661
                let mut bindings_list = FxHashMap();
                for pat in pats {
                    self.resolve_pattern(pat, PatternSource::IfLet, &mut bindings_list);
                }
                // This has to happen *after* we determine which pat_idents are variants
                self.check_consistent_bindings(pats);
3662
                self.visit_block(if_block);
J
Jeffrey Seyfried 已提交
3663
                self.ribs[ValueNS].pop();
3664 3665 3666 3667

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

J
Jeffrey Seyfried 已提交
3668 3669 3670
            ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),

            ExprKind::While(ref subexpression, ref block, label) => {
3671 3672 3673 3674
                self.with_resolved_label(label, expr.id, |this| {
                    this.visit_expr(subexpression);
                    this.visit_block(block);
                });
J
Jeffrey Seyfried 已提交
3675 3676
            }

3677
            ExprKind::WhileLet(ref pats, ref subexpression, ref block, label) => {
3678 3679
                self.with_resolved_label(label, expr.id, |this| {
                    this.visit_expr(subexpression);
3680
                    this.ribs[ValueNS].push(Rib::new(NormalRibKind));
3681 3682 3683 3684 3685 3686
                    let mut bindings_list = FxHashMap();
                    for pat in pats {
                        this.resolve_pattern(pat, PatternSource::WhileLet, &mut bindings_list);
                    }
                    // This has to happen *after* we determine which pat_idents are variants
                    this.check_consistent_bindings(pats);
3687
                    this.visit_block(block);
3688
                    this.ribs[ValueNS].pop();
3689
                });
3690 3691 3692 3693
            }

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

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

J
Jeffrey Seyfried 已提交
3699
                self.ribs[ValueNS].pop();
3700 3701
            }

3702
            // Equivalent to `visit::walk_expr` + passing some context to children.
3703
            ExprKind::Field(ref subexpression, _) => {
3704
                self.resolve_expr(subexpression, Some(expr));
3705
            }
3706
            ExprKind::MethodCall(ref segment, ref arguments) => {
3707
                let mut arguments = arguments.iter();
3708
                self.resolve_expr(arguments.next().unwrap(), Some(expr));
3709 3710 3711
                for argument in arguments {
                    self.resolve_expr(argument, None);
                }
3712
                self.visit_path_segment(expr.span, segment);
3713
            }
3714 3715 3716 3717 3718 3719 3720

            ExprKind::Repeat(ref element, ref count) => {
                self.visit_expr(element);
                self.with_constant_rib(|this| {
                    this.visit_expr(count);
                });
            }
3721
            ExprKind::Call(ref callee, ref arguments) => {
3722
                self.resolve_expr(callee, Some(expr));
3723 3724 3725 3726
                for argument in arguments {
                    self.resolve_expr(argument, None);
                }
            }
3727 3728 3729 3730 3731
            ExprKind::Type(ref type_expr, _) => {
                self.current_type_ascription.push(type_expr.span);
                visit::walk_expr(self, expr);
                self.current_type_ascription.pop();
            }
B
Brian Anderson 已提交
3732
            _ => {
3733
                visit::walk_expr(self, expr);
3734 3735 3736 3737
            }
        }
    }

E
Eduard Burtescu 已提交
3738
    fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3739
        match expr.node {
V
Vadim Petrochenkov 已提交
3740
            ExprKind::Field(_, ident) => {
3741 3742 3743 3744
                // 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.
V
Vadim Petrochenkov 已提交
3745
                let traits = self.get_traits_containing_item(ident, ValueNS);
3746
                self.trait_map.insert(expr.id, traits);
3747
            }
3748
            ExprKind::MethodCall(ref segment, ..) => {
C
corentih 已提交
3749
                debug!("(recording candidate traits for expr) recording traits for {}",
3750
                       expr.id);
3751
                let traits = self.get_traits_containing_item(segment.ident, ValueNS);
3752
                self.trait_map.insert(expr.id, traits);
3753
            }
3754
            _ => {
3755 3756 3757 3758 3759
                // Nothing to do.
            }
        }
    }

J
Jeffrey Seyfried 已提交
3760 3761
    fn get_traits_containing_item(&mut self, mut ident: Ident, ns: Namespace)
                                  -> Vec<TraitCandidate> {
3762
        debug!("(getting traits containing item) looking for '{}'", ident.name);
E
Eduard Burtescu 已提交
3763

3764
        let mut found_traits = Vec::new();
J
Jeffrey Seyfried 已提交
3765
        // Look for the current trait.
3766 3767 3768 3769
        if let Some((module, _)) = self.current_trait_ref {
            if self.resolve_ident_in_module(module, ident, ns, false, false, module.span).is_ok() {
                let def_id = module.def_id().unwrap();
                found_traits.push(TraitCandidate { def_id: def_id, import_id: None });
E
Eduard Burtescu 已提交
3770
            }
J
Jeffrey Seyfried 已提交
3771
        }
3772

3773
        ident.span = ident.span.modern();
J
Jeffrey Seyfried 已提交
3774 3775
        let mut search_module = self.current_module;
        loop {
3776
            self.get_traits_in_module_containing_item(ident, ns, search_module, &mut found_traits);
J
Jeffrey Seyfried 已提交
3777
            search_module =
3778
                unwrap_or!(self.hygienic_lexical_parent(search_module, &mut ident.span), break);
3779
        }
3780

3781 3782
        if let Some(prelude) = self.prelude {
            if !search_module.no_implicit_prelude {
3783
                self.get_traits_in_module_containing_item(ident, ns, prelude, &mut found_traits);
E
Eduard Burtescu 已提交
3784
            }
3785 3786
        }

E
Eduard Burtescu 已提交
3787
        found_traits
3788 3789
    }

3790
    fn get_traits_in_module_containing_item(&mut self,
3791
                                            ident: Ident,
3792
                                            ns: Namespace,
3793
                                            module: Module<'a>,
3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807
                                            found_traits: &mut Vec<TraitCandidate>) {
        let mut traits = module.traits.borrow_mut();
        if traits.is_none() {
            let mut collected_traits = Vec::new();
            module.for_each_child(|name, ns, binding| {
                if ns != TypeNS { return }
                if let Def::Trait(_) = binding.def() {
                    collected_traits.push((name, binding));
                }
            });
            *traits = Some(collected_traits.into_boxed_slice());
        }

        for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
3808
            let module = binding.module().unwrap();
J
Jeffrey Seyfried 已提交
3809
            let mut ident = ident;
3810
            if ident.span.glob_adjust(module.expansion, binding.span.ctxt().modern()).is_none() {
J
Jeffrey Seyfried 已提交
3811 3812 3813 3814
                continue
            }
            if self.resolve_ident_in_module_unadjusted(module, ident, ns, false, false, module.span)
                   .is_ok() {
3815 3816 3817 3818 3819 3820 3821 3822
                let import_id = match binding.kind {
                    NameBindingKind::Import { directive, .. } => {
                        self.maybe_unused_trait_imports.insert(directive.id);
                        self.add_to_glob_map(directive.id, trait_name);
                        Some(directive.id)
                    }
                    _ => None,
                };
3823
                let trait_def_id = module.def_id().unwrap();
3824 3825 3826 3827 3828
                found_traits.push(TraitCandidate { def_id: trait_def_id, import_id: import_id });
            }
        }
    }

3829 3830 3831 3832 3833 3834 3835
    /// 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).
3836 3837 3838 3839 3840 3841 3842 3843
    fn lookup_import_candidates<FilterFn>(&mut self,
                                          lookup_name: Name,
                                          namespace: Namespace,
                                          filter_fn: FilterFn)
                                          -> Vec<ImportSuggestion>
        where FilterFn: Fn(Def) -> bool
    {
        let mut candidates = Vec::new();
3844
        let mut worklist = Vec::new();
3845
        let mut seen_modules = FxHashSet();
3846 3847 3848 3849 3850
        worklist.push((self.graph_root, Vec::new(), false));

        while let Some((in_module,
                        path_segments,
                        in_module_is_extern)) = worklist.pop() {
3851
            self.populate_module_if_necessary(in_module);
3852

3853 3854 3855
            // We have to visit module children in deterministic order to avoid
            // instabilities in reported imports (#43552).
            in_module.for_each_child_stable(|ident, ns, name_binding| {
3856
                // avoid imports entirely
3857
                if name_binding.is_import() && !name_binding.is_extern_crate() { return; }
3858 3859
                // avoid non-importable candidates as well
                if !name_binding.is_importable() { return; }
3860 3861

                // collect results based on the filter function
3862
                if ident.name == lookup_name && ns == namespace {
3863
                    if filter_fn(name_binding.def()) {
3864 3865
                        // create the path
                        let mut segms = path_segments.clone();
3866
                        segms.push(ast::PathSegment::from_ident(ident));
3867
                        let path = Path {
3868
                            span: name_binding.span,
3869 3870 3871 3872 3873 3874 3875 3876 3877
                            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)
3878
                        if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
3879
                            candidates.push(ImportSuggestion { path: path });
3880 3881 3882 3883 3884
                        }
                    }
                }

                // collect submodules to explore
J
Jeffrey Seyfried 已提交
3885
                if let Some(module) = name_binding.module() {
3886
                    // form the path
3887
                    let mut path_segments = path_segments.clone();
3888
                    path_segments.push(ast::PathSegment::from_ident(ident));
3889

3890
                    if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
3891
                        // add the module to the lookup
3892
                        let is_extern = in_module_is_extern || name_binding.is_extern_crate();
3893
                        if seen_modules.insert(module.def_id().unwrap()) {
3894 3895
                            worklist.push((module, path_segments, is_extern));
                        }
3896 3897 3898 3899 3900
                    }
                }
            })
        }

3901
        candidates
3902 3903
    }

3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918
    fn find_module(&mut self,
                   module_def: Def)
                   -> Option<(Module<'a>, ImportSuggestion)>
    {
        let mut result = None;
        let mut worklist = Vec::new();
        let mut seen_modules = FxHashSet();
        worklist.push((self.graph_root, Vec::new()));

        while let Some((in_module, path_segments)) = worklist.pop() {
            // abort if the module is already found
            if let Some(_) = result { break; }

            self.populate_module_if_necessary(in_module);

3919
            in_module.for_each_child_stable(|ident, _, name_binding| {
3920 3921 3922
                // abort if the module is already found or if name_binding is private external
                if result.is_some() || !name_binding.vis.is_visible_locally() {
                    return
3923 3924 3925 3926
                }
                if let Some(module) = name_binding.module() {
                    // form the path
                    let mut path_segments = path_segments.clone();
3927
                    path_segments.push(ast::PathSegment::from_ident(ident));
3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952
                    if module.def() == Some(module_def) {
                        let path = Path {
                            span: name_binding.span,
                            segments: path_segments,
                        };
                        result = Some((module, ImportSuggestion { path: path }));
                    } else {
                        // add the module to the lookup
                        if seen_modules.insert(module.def_id().unwrap()) {
                            worklist.push((module, path_segments));
                        }
                    }
                }
            });
        }

        result
    }

    fn collect_enum_variants(&mut self, enum_def: Def) -> Option<Vec<Path>> {
        if let Def::Enum(..) = enum_def {} else {
            panic!("Non-enum def passed to collect_enum_variants: {:?}", enum_def)
        }

        self.find_module(enum_def).map(|(enum_module, enum_import_suggestion)| {
3953 3954
            self.populate_module_if_necessary(enum_module);

3955 3956 3957 3958
            let mut variants = Vec::new();
            enum_module.for_each_child_stable(|ident, _, name_binding| {
                if let Def::Variant(..) = name_binding.def() {
                    let mut segms = enum_import_suggestion.path.segments.clone();
3959
                    segms.push(ast::PathSegment::from_ident(ident));
3960 3961 3962 3963 3964 3965 3966 3967 3968 3969
                    variants.push(Path {
                        span: name_binding.span,
                        segments: segms,
                    });
                }
            });
            variants
        })
    }

3970 3971
    fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
        debug!("(recording def) recording {:?} for {}", resolution, node_id);
3972
        if let Some(prev_res) = self.def_map.insert(node_id, resolution) {
3973
            panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution);
3974
        }
3975 3976
    }

3977
    fn resolve_visibility(&mut self, vis: &ast::Visibility) -> ty::Visibility {
3978 3979 3980 3981 3982 3983
        match vis.node {
            ast::VisibilityKind::Public => ty::Visibility::Public,
            ast::VisibilityKind::Crate(..) => {
                ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))
            }
            ast::VisibilityKind::Inherited => {
3984
                ty::Visibility::Restricted(self.current_module.normal_ancestor_id)
3985
            }
3986
            ast::VisibilityKind::Restricted { ref path, id, .. } => {
3987 3988
                // Visibilities are resolved as global by default, add starting root segment.
                let segments = path.make_root().iter().chain(path.segments.iter())
3989
                    .map(|seg| seg.ident)
3990 3991 3992
                    .collect::<Vec<_>>();
                let def = self.smart_resolve_path_fragment(id, None, &segments, path.span,
                                                           PathSource::Visibility).base_def();
3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004
                if def == Def::Err {
                    ty::Visibility::Public
                } else {
                    let vis = ty::Visibility::Restricted(def.def_id());
                    if self.is_accessible(vis) {
                        vis
                    } else {
                        self.session.span_err(path.span, "visibilities can only be restricted \
                                                          to ancestor modules");
                        ty::Visibility::Public
                    }
                }
4005 4006 4007 4008
            }
        }
    }

4009
    fn is_accessible(&self, vis: ty::Visibility) -> bool {
4010
        vis.is_accessible_from(self.current_module.normal_ancestor_id, self)
4011 4012
    }

4013
    fn is_accessible_from(&self, vis: ty::Visibility, module: Module<'a>) -> bool {
4014
        vis.is_accessible_from(module.normal_ancestor_id, self)
4015 4016
    }

4017
    fn report_errors(&mut self, krate: &Crate) {
4018
        self.report_shadowing_errors();
4019
        self.report_with_use_injections(krate);
4020
        self.report_proc_macro_import(krate);
4021
        let mut reported_spans = FxHashSet();
4022

4023
        for &AmbiguityError { span, name, b1, b2, lexical, legacy } in &self.ambiguity_errors {
4024
            if !reported_spans.insert(span) { continue }
4025 4026 4027
            let participle = |binding: &NameBinding| {
                if binding.is_import() { "imported" } else { "defined" }
            };
4028 4029
            let msg1 = format!("`{}` could refer to the name {} here", name, participle(b1));
            let msg2 = format!("`{}` could also refer to the name {} here", name, participle(b2));
4030
            let note = if b1.expansion == Mark::root() || !lexical && b1.is_glob_import() {
4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047
                format!("consider adding an explicit import of `{}` to disambiguate", name)
            } else if let Def::Macro(..) = b1.def() {
                format!("macro-expanded {} do not shadow",
                        if b1.is_import() { "macro imports" } else { "macros" })
            } else {
                format!("macro-expanded {} do not shadow when used in a macro invocation path",
                        if b1.is_import() { "imports" } else { "items" })
            };
            if legacy {
                let id = match b2.kind {
                    NameBindingKind::Import { directive, .. } => directive.id,
                    _ => unreachable!(),
                };
                let mut span = MultiSpan::from_span(span);
                span.push_span_label(b1.span, msg1);
                span.push_span_label(b2.span, msg2);
                let msg = format!("`{}` is ambiguous", name);
4048
                self.session.buffer_lint(lint::builtin::LEGACY_IMPORTS, id, span, &msg);
4049
            } else {
4050
                let mut err =
G
Guillaume Gomez 已提交
4051
                    struct_span_err!(self.session, span, E0659, "`{}` is ambiguous", name);
4052 4053 4054 4055 4056 4057 4058
                err.span_note(b1.span, &msg1);
                match b2.def() {
                    Def::Macro(..) if b2.span == DUMMY_SP =>
                        err.note(&format!("`{}` is also a builtin macro", name)),
                    _ => err.span_note(b2.span, &msg2),
                };
                err.note(&note).emit();
4059
            }
4060 4061
        }

4062 4063
        for &PrivacyError(span, name, binding) in &self.privacy_errors {
            if !reported_spans.insert(span) { continue }
G
Guillaume Gomez 已提交
4064
            span_err!(self.session, span, E0603, "{} `{}` is private", binding.descr(), name);
4065 4066
        }
    }
4067

4068 4069
    fn report_with_use_injections(&mut self, krate: &Crate) {
        for UseError { mut err, candidates, node_id, better } in self.use_injections.drain(..) {
4070
            let (span, found_use) = UsePlacementFinder::check(krate, node_id);
4071
            if !candidates.is_empty() {
4072
                show_candidates(&mut err, span, &candidates, better, found_use);
4073 4074 4075 4076 4077
            }
            err.emit();
        }
    }

4078
    fn report_shadowing_errors(&mut self) {
J
Jeffrey Seyfried 已提交
4079 4080
        for (ident, scope) in replace(&mut self.lexical_macro_resolutions, Vec::new()) {
            self.resolve_legacy_scope(scope, ident, true);
J
Jeffrey Seyfried 已提交
4081 4082
        }

4083
        let mut reported_errors = FxHashSet();
4084
        for binding in replace(&mut self.disallowed_shadowing, Vec::new()) {
J
Jeffrey Seyfried 已提交
4085 4086 4087
            if self.resolve_legacy_scope(&binding.parent, binding.ident, false).is_some() &&
               reported_errors.insert((binding.ident, binding.span)) {
                let msg = format!("`{}` is already in scope", binding.ident);
4088
                self.session.struct_span_err(binding.span, &msg)
4089 4090
                    .note("macro-expanded `macro_rules!`s may not shadow \
                           existing macros (see RFC 1560)")
4091 4092 4093 4094 4095
                    .emit();
            }
        }
    }

C
Cldfire 已提交
4096
    fn report_conflict<'b>(&mut self,
4097
                       parent: Module,
4098
                       ident: Ident,
4099
                       ns: Namespace,
C
Cldfire 已提交
4100 4101
                       new_binding: &NameBinding<'b>,
                       old_binding: &NameBinding<'b>) {
4102
        // Error on the second of two conflicting names
4103
        if old_binding.span.lo() > new_binding.span.lo() {
4104
            return self.report_conflict(parent, ident, ns, old_binding, new_binding);
4105 4106
        }

J
Jeffrey Seyfried 已提交
4107 4108 4109 4110
        let container = match parent.kind {
            ModuleKind::Def(Def::Mod(_), _) => "module",
            ModuleKind::Def(Def::Trait(_), _) => "trait",
            ModuleKind::Block(..) => "block",
4111 4112 4113
            _ => "enum",
        };

4114 4115 4116
        let old_noun = match old_binding.is_import() {
            true => "import",
            false => "definition",
4117 4118
        };

4119 4120 4121 4122 4123
        let new_participle = match new_binding.is_import() {
            true => "imported",
            false => "defined",
        };

4124
        let (name, span) = (ident.name, self.session.codemap().def_span(new_binding.span));
4125 4126 4127 4128 4129 4130 4131

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

4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144
        let old_kind = match (ns, old_binding.module()) {
            (ValueNS, _) => "value",
            (MacroNS, _) => "macro",
            (TypeNS, _) if old_binding.is_extern_crate() => "extern crate",
            (TypeNS, Some(module)) if module.is_normal() => "module",
            (TypeNS, Some(module)) if module.is_trait() => "trait",
            (TypeNS, _) => "type",
        };

        let namespace = match ns {
            ValueNS => "value",
            MacroNS => "macro",
            TypeNS => "type",
4145 4146
        };

4147 4148 4149
        let msg = format!("the name `{}` is defined multiple times", name);

        let mut err = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) {
4150
            (true, true) => struct_span_err!(self.session, span, E0259, "{}", msg),
4151
            (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() {
4152 4153
                true => struct_span_err!(self.session, span, E0254, "{}", msg),
                false => struct_span_err!(self.session, span, E0260, "{}", msg),
M
Mohit Agarwal 已提交
4154
            },
4155
            _ => match (old_binding.is_import(), new_binding.is_import()) {
4156 4157 4158
                (false, false) => struct_span_err!(self.session, span, E0428, "{}", msg),
                (true, true) => struct_span_err!(self.session, span, E0252, "{}", msg),
                _ => struct_span_err!(self.session, span, E0255, "{}", msg),
4159 4160 4161
            },
        };

4162 4163 4164 4165 4166 4167
        err.note(&format!("`{}` must be defined only once in the {} namespace of this {}",
                          name,
                          namespace,
                          container));

        err.span_label(span, format!("`{}` re{} here", name, new_participle));
4168
        if old_binding.span != DUMMY_SP {
4169 4170
            err.span_label(self.session.codemap().def_span(old_binding.span),
                           format!("previous {} of the {} `{}` here", old_noun, old_kind, name));
4171
        }
4172

C
Cldfire 已提交
4173 4174
        // See https://github.com/rust-lang/rust/issues/32354
        if old_binding.is_import() || new_binding.is_import() {
4175
            let binding = if new_binding.is_import() && new_binding.span != DUMMY_SP {
C
Cldfire 已提交
4176 4177 4178 4179 4180 4181 4182 4183
                new_binding
            } else {
                old_binding
            };

            let cm = self.session.codemap();
            let rename_msg = "You can use `as` to change the binding name of the import";

4184 4185
            if let (Ok(snippet), false) = (cm.span_to_snippet(binding.span),
                                           binding.is_renamed_extern_crate()) {
4186 4187 4188 4189 4190 4191
                let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() {
                    format!("Other{}", name)
                } else {
                    format!("other_{}", name)
                };

C
Cldfire 已提交
4192 4193
                err.span_suggestion(binding.span,
                                    rename_msg,
4194
                                    if snippet.ends_with(';') {
4195
                                        format!("{} as {};",
4196
                                                &snippet[..snippet.len()-1],
4197
                                                suggested_name)
4198
                                    } else {
4199
                                        format!("{} as {}", snippet, suggested_name)
4200
                                    });
C
Cldfire 已提交
4201 4202 4203 4204 4205
            } else {
                err.span_label(binding.span, rename_msg);
            }
        }

4206
        err.emit();
4207
        self.name_already_seen.insert(name, span);
4208
    }
J
Jeffrey Seyfried 已提交
4209 4210 4211

    fn warn_legacy_self_import(&self, directive: &'a ImportDirective<'a>) {
        let (id, span) = (directive.id, directive.span);
4212 4213
        let msg = "`self` no longer imports values";
        self.session.buffer_lint(lint::builtin::LEGACY_IMPORTS, id, span, msg);
J
Jeffrey Seyfried 已提交
4214
    }
4215 4216 4217 4218 4219

    fn check_proc_macro_attrs(&mut self, attrs: &[ast::Attribute]) {
        if self.proc_macro_enabled { return; }

        for attr in attrs {
4220 4221 4222
            if attr.path.segments.len() > 1 {
                continue
            }
4223
            let ident = attr.path.segments[0].ident;
4224 4225 4226 4227
            let result = self.resolve_lexical_macro_path_segment(ident,
                                                                 MacroNS,
                                                                 false,
                                                                 attr.path.span);
4228 4229
            if let Ok(binding) = result {
                if let SyntaxExtension::AttrProcMacro(..) = *binding.binding().get_macro(self) {
4230 4231 4232 4233 4234 4235 4236
                    attr::mark_known(attr);

                    let msg = "attribute procedural macros are experimental";
                    let feature = "proc_macro";

                    feature_err(&self.session.parse_sess, feature,
                                attr.span, GateIssue::Language, msg)
E
Esteban Küber 已提交
4237
                        .span_label(binding.span(), "procedural macro imported here")
4238 4239 4240 4241 4242
                        .emit();
                }
            }
        }
    }
4243
}
4244

V
Vadim Petrochenkov 已提交
4245 4246
fn is_self_type(path: &[Ident], namespace: Namespace) -> bool {
    namespace == TypeNS && path.len() == 1 && path[0].name == keywords::SelfType.name()
4247 4248
}

V
Vadim Petrochenkov 已提交
4249 4250
fn is_self_value(path: &[Ident], namespace: Namespace) -> bool {
    namespace == ValueNS && path.len() == 1 && path[0].name == keywords::SelfValue.name()
4251 4252
}

V
Vadim Petrochenkov 已提交
4253
fn names_to_string(idents: &[Ident]) -> String {
4254
    let mut result = String::new();
4255
    for (i, ident) in idents.iter()
V
Vadim Petrochenkov 已提交
4256
                            .filter(|ident| ident.name != keywords::CrateRoot.name())
4257
                            .enumerate() {
4258 4259 4260
        if i > 0 {
            result.push_str("::");
        }
V
Vadim Petrochenkov 已提交
4261
        result.push_str(&ident.name.as_str());
C
corentih 已提交
4262
    }
4263 4264 4265
    result
}

4266
fn path_names_to_string(path: &Path) -> String {
4267
    names_to_string(&path.segments.iter()
V
Vadim Petrochenkov 已提交
4268
                        .map(|seg| seg.ident)
4269
                        .collect::<Vec<_>>())
4270 4271
}

4272
/// Get the path for an enum and the variant from an `ImportSuggestion` for an enum variant.
E
Esteban Küber 已提交
4273
fn import_candidate_to_paths(suggestion: &ImportSuggestion) -> (Span, String, String) {
4274 4275 4276 4277 4278 4279 4280 4281 4282 4283
    let variant_path = &suggestion.path;
    let variant_path_string = path_names_to_string(variant_path);

    let path_len = suggestion.path.segments.len();
    let enum_path = ast::Path {
        span: suggestion.path.span,
        segments: suggestion.path.segments[0..path_len - 1].to_vec(),
    };
    let enum_path_string = path_names_to_string(&enum_path);

E
Esteban Küber 已提交
4284
    (suggestion.path.span, variant_path_string, enum_path_string)
4285 4286 4287
}


4288 4289 4290
/// 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
4291
fn show_candidates(err: &mut DiagnosticBuilder,
4292 4293
                   // This is `None` if all placement locations are inside expansions
                   span: Option<Span>,
4294
                   candidates: &[ImportSuggestion],
4295 4296
                   better: bool,
                   found_use: bool) {
4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307

    // 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<_> =
        candidates.into_iter().map(|c| path_names_to_string(&c.path)).collect();
    path_strings.sort();

    let better = if better { "better " } else { "" };
    let msg_diff = match path_strings.len() {
        1 => " is found in another module, you can import it",
        _ => "s are found in other modules, you can import them",
4308
    };
4309 4310
    let msg = format!("possible {}candidate{} into scope", better, msg_diff);

4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321
    if let Some(span) = span {
        for candidate in &mut path_strings {
            // produce an additional newline to separate the new use statement
            // from the directly following item.
            let additional_newline = if found_use {
                ""
            } else {
                "\n"
            };
            *candidate = format!("use {};\n{}", candidate, additional_newline);
        }
4322

4323 4324 4325 4326 4327 4328 4329 4330 4331
        err.span_suggestions(span, &msg, path_strings);
    } else {
        let mut msg = msg;
        msg.push(':');
        for candidate in path_strings {
            msg.push('\n');
            msg.push_str(&candidate);
        }
    }
4332 4333
}

4334
/// A somewhat inefficient routine to obtain the name of a module.
4335
fn module_to_string(module: Module) -> Option<String> {
4336 4337
    let mut names = Vec::new();

4338
    fn collect_mod(names: &mut Vec<Ident>, module: Module) {
J
Jeffrey Seyfried 已提交
4339 4340
        if let ModuleKind::Def(_, name) = module.kind {
            if let Some(parent) = module.parent {
4341
                names.push(Ident::with_empty_ctxt(name));
J
Jeffrey Seyfried 已提交
4342
                collect_mod(names, parent);
4343
            }
J
Jeffrey Seyfried 已提交
4344 4345
        } else {
            // danger, shouldn't be ident?
4346
            names.push(Ident::from_str("<opaque>"));
J
Jeffrey Seyfried 已提交
4347
            collect_mod(names, module.parent.unwrap());
4348 4349 4350 4351
        }
    }
    collect_mod(&mut names, module);

4352
    if names.is_empty() {
4353
        return None;
4354
    }
4355
    Some(names_to_string(&names.into_iter()
4356
                        .rev()
4357
                        .collect::<Vec<_>>()))
4358 4359
}

4360
fn err_path_resolution() -> PathResolution {
4361
    PathResolution::new(Def::Err)
4362 4363
}

N
Niko Matsakis 已提交
4364
#[derive(PartialEq,Copy, Clone)]
4365 4366
pub enum MakeGlobMap {
    Yes,
C
corentih 已提交
4367
    No,
4368 4369
}

4370
__build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }