]> git.proxmox.com Git - rustc.git/blob - src/librustc_resolve/lib.rs
New upstream version 1.33.0+dfsg1
[rustc.git] / src / librustc_resolve / lib.rs
1 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
2 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
3 html_root_url = "https://doc.rust-lang.org/nightly/")]
4
5 #![feature(crate_visibility_modifier)]
6 #![feature(label_break_value)]
7 #![feature(nll)]
8 #![feature(rustc_diagnostic_macros)]
9 #![feature(slice_sort_by_cached_key)]
10
11 #![recursion_limit="256"]
12
13 #[macro_use]
14 extern crate bitflags;
15 #[macro_use]
16 extern crate log;
17 #[macro_use]
18 extern crate syntax;
19 extern crate syntax_pos;
20 extern crate rustc_errors as errors;
21 extern crate arena;
22 #[macro_use]
23 extern crate rustc;
24 extern crate rustc_data_structures;
25 extern crate rustc_metadata;
26
27 pub use rustc::hir::def::{Namespace, PerNS};
28
29 use self::TypeParameters::*;
30 use self::RibKind::*;
31
32 use rustc::hir::map::{Definitions, DefCollector};
33 use rustc::hir::{self, PrimTy, Bool, Char, Float, Int, Uint, Str};
34 use rustc::middle::cstore::CrateStore;
35 use rustc::session::Session;
36 use rustc::lint;
37 use rustc::hir::def::*;
38 use rustc::hir::def::Namespace::*;
39 use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, DefId};
40 use rustc::hir::{Freevar, FreevarMap, TraitCandidate, TraitMap, GlobMap};
41 use rustc::session::config::nightly_options;
42 use rustc::ty;
43 use rustc::util::nodemap::{NodeMap, NodeSet, FxHashMap, FxHashSet, DefIdMap};
44
45 use rustc_metadata::creader::CrateLoader;
46 use rustc_metadata::cstore::CStore;
47
48 use syntax::source_map::SourceMap;
49 use syntax::ext::hygiene::{Mark, Transparency, SyntaxContext};
50 use syntax::ast::{self, Name, NodeId, Ident, FloatTy, IntTy, UintTy};
51 use syntax::ext::base::SyntaxExtension;
52 use syntax::ext::base::Determinacy::{self, Determined, Undetermined};
53 use syntax::ext::base::MacroKind;
54 use syntax::symbol::{Symbol, keywords};
55 use syntax::util::lev_distance::find_best_match_for_name;
56
57 use syntax::visit::{self, FnKind, Visitor};
58 use syntax::attr;
59 use syntax::ast::{CRATE_NODE_ID, Arm, IsAsync, BindingMode, Block, Crate, Expr, ExprKind};
60 use syntax::ast::{FnDecl, ForeignItem, ForeignItemKind, GenericParamKind, Generics};
61 use syntax::ast::{Item, ItemKind, ImplItem, ImplItemKind};
62 use syntax::ast::{Label, Local, Mutability, Pat, PatKind, Path};
63 use syntax::ast::{QSelf, TraitItemKind, TraitRef, Ty, TyKind};
64 use syntax::ptr::P;
65
66 use syntax_pos::{Span, DUMMY_SP, MultiSpan};
67 use errors::{Applicability, DiagnosticBuilder, DiagnosticId};
68
69 use std::cell::{Cell, RefCell};
70 use std::{cmp, fmt, iter, mem, ptr};
71 use std::collections::BTreeSet;
72 use std::mem::replace;
73 use rustc_data_structures::ptr_key::PtrKey;
74 use rustc_data_structures::sync::Lrc;
75
76 use resolve_imports::{ImportDirective, ImportDirectiveSubclass, NameResolution, ImportResolver};
77 use macros::{InvocationData, LegacyBinding, ParentScope};
78
79 // N.B., this module needs to be declared first so diagnostics are
80 // registered before they are used.
81 mod diagnostics;
82 mod error_reporting;
83 mod macros;
84 mod check_unused;
85 mod build_reduced_graph;
86 mod resolve_imports;
87
88 fn is_known_tool(name: Name) -> bool {
89 ["clippy", "rustfmt"].contains(&&*name.as_str())
90 }
91
92 enum Weak {
93 Yes,
94 No,
95 }
96
97 enum ScopeSet {
98 Import(Namespace),
99 AbsolutePath(Namespace),
100 Macro(MacroKind),
101 Module,
102 }
103
104 /// A free importable items suggested in case of resolution failure.
105 struct ImportSuggestion {
106 path: Path,
107 }
108
109 /// A field or associated item from self type suggested in case of resolution failure.
110 enum AssocSuggestion {
111 Field,
112 MethodWithSelf,
113 AssocItem,
114 }
115
116 #[derive(Eq)]
117 struct BindingError {
118 name: Name,
119 origin: BTreeSet<Span>,
120 target: BTreeSet<Span>,
121 }
122
123 struct TypoSuggestion {
124 candidate: Symbol,
125
126 /// The kind of the binding ("crate", "module", etc.)
127 kind: &'static str,
128
129 /// An appropriate article to refer to the binding ("a", "an", etc.)
130 article: &'static str,
131 }
132
133 impl PartialOrd for BindingError {
134 fn partial_cmp(&self, other: &BindingError) -> Option<cmp::Ordering> {
135 Some(self.cmp(other))
136 }
137 }
138
139 impl PartialEq for BindingError {
140 fn eq(&self, other: &BindingError) -> bool {
141 self.name == other.name
142 }
143 }
144
145 impl Ord for BindingError {
146 fn cmp(&self, other: &BindingError) -> cmp::Ordering {
147 self.name.cmp(&other.name)
148 }
149 }
150
151 enum ResolutionError<'a> {
152 /// error E0401: can't use type parameters from outer function
153 TypeParametersFromOuterFunction(Def),
154 /// error E0403: the name is already used for a type parameter in this type parameter list
155 NameAlreadyUsedInTypeParameterList(Name, &'a Span),
156 /// error E0407: method is not a member of trait
157 MethodNotMemberOfTrait(Name, &'a str),
158 /// error E0437: type is not a member of trait
159 TypeNotMemberOfTrait(Name, &'a str),
160 /// error E0438: const is not a member of trait
161 ConstNotMemberOfTrait(Name, &'a str),
162 /// error E0408: variable `{}` is not bound in all patterns
163 VariableNotBoundInPattern(&'a BindingError),
164 /// error E0409: variable `{}` is bound in inconsistent ways within the same match arm
165 VariableBoundWithDifferentMode(Name, Span),
166 /// error E0415: identifier is bound more than once in this parameter list
167 IdentifierBoundMoreThanOnceInParameterList(&'a str),
168 /// error E0416: identifier is bound more than once in the same pattern
169 IdentifierBoundMoreThanOnceInSamePattern(&'a str),
170 /// error E0426: use of undeclared label
171 UndeclaredLabel(&'a str, Option<Name>),
172 /// error E0429: `self` imports are only allowed within a { } list
173 SelfImportsOnlyAllowedWithin,
174 /// error E0430: `self` import can only appear once in the list
175 SelfImportCanOnlyAppearOnceInTheList,
176 /// error E0431: `self` import can only appear in an import list with a non-empty prefix
177 SelfImportOnlyInImportListWithNonEmptyPrefix,
178 /// error E0433: failed to resolve
179 FailedToResolve(&'a str),
180 /// error E0434: can't capture dynamic environment in a fn item
181 CannotCaptureDynamicEnvironmentInFnItem,
182 /// error E0435: attempt to use a non-constant value in a constant
183 AttemptToUseNonConstantValueInConstant,
184 /// error E0530: X bindings cannot shadow Ys
185 BindingShadowsSomethingUnacceptable(&'a str, Name, &'a NameBinding<'a>),
186 /// error E0128: type parameters with a default cannot use forward declared identifiers
187 ForwardDeclaredTyParam,
188 }
189
190 /// Combines an error with provided span and emits it
191 ///
192 /// This takes the error provided, combines it with the span and any additional spans inside the
193 /// error and emits it.
194 fn resolve_error<'sess, 'a>(resolver: &'sess Resolver,
195 span: Span,
196 resolution_error: ResolutionError<'a>) {
197 resolve_struct_error(resolver, span, resolution_error).emit();
198 }
199
200 fn resolve_struct_error<'sess, 'a>(resolver: &'sess Resolver,
201 span: Span,
202 resolution_error: ResolutionError<'a>)
203 -> DiagnosticBuilder<'sess> {
204 match resolution_error {
205 ResolutionError::TypeParametersFromOuterFunction(outer_def) => {
206 let mut err = struct_span_err!(resolver.session,
207 span,
208 E0401,
209 "can't use type parameters from outer function");
210 err.span_label(span, "use of type variable from outer function");
211
212 let cm = resolver.session.source_map();
213 match outer_def {
214 Def::SelfTy(maybe_trait_defid, maybe_impl_defid) => {
215 if let Some(impl_span) = maybe_impl_defid.and_then(|def_id| {
216 resolver.definitions.opt_span(def_id)
217 }) {
218 err.span_label(
219 reduce_impl_span_to_impl_keyword(cm, impl_span),
220 "`Self` type implicitly declared here, by this `impl`",
221 );
222 }
223 match (maybe_trait_defid, maybe_impl_defid) {
224 (Some(_), None) => {
225 err.span_label(span, "can't use `Self` here");
226 }
227 (_, Some(_)) => {
228 err.span_label(span, "use a type here instead");
229 }
230 (None, None) => bug!("`impl` without trait nor type?"),
231 }
232 return err;
233 },
234 Def::TyParam(typaram_defid) => {
235 if let Some(typaram_span) = resolver.definitions.opt_span(typaram_defid) {
236 err.span_label(typaram_span, "type variable from outer function");
237 }
238 },
239 _ => {
240 bug!("TypeParametersFromOuterFunction should only be used with Def::SelfTy or \
241 Def::TyParam")
242 }
243 }
244
245 // Try to retrieve the span of the function signature and generate a new message with
246 // a local type parameter
247 let sugg_msg = "try using a local type parameter instead";
248 if let Some((sugg_span, new_snippet)) = cm.generate_local_type_param_snippet(span) {
249 // Suggest the modification to the user
250 err.span_suggestion_with_applicability(
251 sugg_span,
252 sugg_msg,
253 new_snippet,
254 Applicability::MachineApplicable,
255 );
256 } else if let Some(sp) = cm.generate_fn_name_span(span) {
257 err.span_label(sp, "try adding a local type parameter in this method instead");
258 } else {
259 err.help("try using a local type parameter instead");
260 }
261
262 err
263 }
264 ResolutionError::NameAlreadyUsedInTypeParameterList(name, first_use_span) => {
265 let mut err = struct_span_err!(resolver.session,
266 span,
267 E0403,
268 "the name `{}` is already used for a type parameter \
269 in this type parameter list",
270 name);
271 err.span_label(span, "already used");
272 err.span_label(first_use_span.clone(), format!("first use of `{}`", name));
273 err
274 }
275 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
276 let mut err = struct_span_err!(resolver.session,
277 span,
278 E0407,
279 "method `{}` is not a member of trait `{}`",
280 method,
281 trait_);
282 err.span_label(span, format!("not a member of trait `{}`", trait_));
283 err
284 }
285 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
286 let mut err = struct_span_err!(resolver.session,
287 span,
288 E0437,
289 "type `{}` is not a member of trait `{}`",
290 type_,
291 trait_);
292 err.span_label(span, format!("not a member of trait `{}`", trait_));
293 err
294 }
295 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
296 let mut err = struct_span_err!(resolver.session,
297 span,
298 E0438,
299 "const `{}` is not a member of trait `{}`",
300 const_,
301 trait_);
302 err.span_label(span, format!("not a member of trait `{}`", trait_));
303 err
304 }
305 ResolutionError::VariableNotBoundInPattern(binding_error) => {
306 let target_sp = binding_error.target.iter().cloned().collect::<Vec<_>>();
307 let msp = MultiSpan::from_spans(target_sp.clone());
308 let msg = format!("variable `{}` is not bound in all patterns", binding_error.name);
309 let mut err = resolver.session.struct_span_err_with_code(
310 msp,
311 &msg,
312 DiagnosticId::Error("E0408".into()),
313 );
314 for sp in target_sp {
315 err.span_label(sp, format!("pattern doesn't bind `{}`", binding_error.name));
316 }
317 let origin_sp = binding_error.origin.iter().cloned();
318 for sp in origin_sp {
319 err.span_label(sp, "variable not in all patterns");
320 }
321 err
322 }
323 ResolutionError::VariableBoundWithDifferentMode(variable_name,
324 first_binding_span) => {
325 let mut err = struct_span_err!(resolver.session,
326 span,
327 E0409,
328 "variable `{}` is bound in inconsistent \
329 ways within the same match arm",
330 variable_name);
331 err.span_label(span, "bound in different ways");
332 err.span_label(first_binding_span, "first binding");
333 err
334 }
335 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
336 let mut err = struct_span_err!(resolver.session,
337 span,
338 E0415,
339 "identifier `{}` is bound more than once in this parameter list",
340 identifier);
341 err.span_label(span, "used as parameter more than once");
342 err
343 }
344 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
345 let mut err = struct_span_err!(resolver.session,
346 span,
347 E0416,
348 "identifier `{}` is bound more than once in the same pattern",
349 identifier);
350 err.span_label(span, "used in a pattern more than once");
351 err
352 }
353 ResolutionError::UndeclaredLabel(name, lev_candidate) => {
354 let mut err = struct_span_err!(resolver.session,
355 span,
356 E0426,
357 "use of undeclared label `{}`",
358 name);
359 if let Some(lev_candidate) = lev_candidate {
360 err.span_label(span, format!("did you mean `{}`?", lev_candidate));
361 } else {
362 err.span_label(span, format!("undeclared label `{}`", name));
363 }
364 err
365 }
366 ResolutionError::SelfImportsOnlyAllowedWithin => {
367 struct_span_err!(resolver.session,
368 span,
369 E0429,
370 "{}",
371 "`self` imports are only allowed within a { } list")
372 }
373 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
374 let mut err = struct_span_err!(resolver.session, span, E0430,
375 "`self` import can only appear once in an import list");
376 err.span_label(span, "can only appear once in an import list");
377 err
378 }
379 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
380 let mut err = struct_span_err!(resolver.session, span, E0431,
381 "`self` import can only appear in an import list with \
382 a non-empty prefix");
383 err.span_label(span, "can only appear in an import list with a non-empty prefix");
384 err
385 }
386 ResolutionError::FailedToResolve(msg) => {
387 let mut err = struct_span_err!(resolver.session, span, E0433,
388 "failed to resolve: {}", msg);
389 err.span_label(span, msg);
390 err
391 }
392 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
393 let mut err = struct_span_err!(resolver.session,
394 span,
395 E0434,
396 "{}",
397 "can't capture dynamic environment in a fn item");
398 err.help("use the `|| { ... }` closure form instead");
399 err
400 }
401 ResolutionError::AttemptToUseNonConstantValueInConstant => {
402 let mut err = struct_span_err!(resolver.session, span, E0435,
403 "attempt to use a non-constant value in a constant");
404 err.span_label(span, "non-constant value");
405 err
406 }
407 ResolutionError::BindingShadowsSomethingUnacceptable(what_binding, name, binding) => {
408 let shadows_what = binding.descr();
409 let mut err = struct_span_err!(resolver.session, span, E0530, "{}s cannot shadow {}s",
410 what_binding, shadows_what);
411 err.span_label(span, format!("cannot be named the same as {} {}",
412 binding.article(), shadows_what));
413 let participle = if binding.is_import() { "imported" } else { "defined" };
414 let msg = format!("the {} `{}` is {} here", shadows_what, name, participle);
415 err.span_label(binding.span, msg);
416 err
417 }
418 ResolutionError::ForwardDeclaredTyParam => {
419 let mut err = struct_span_err!(resolver.session, span, E0128,
420 "type parameters with a default cannot use \
421 forward declared identifiers");
422 err.span_label(
423 span, "defaulted type parameters cannot be forward declared".to_string());
424 err
425 }
426 }
427 }
428
429 /// Adjust the impl span so that just the `impl` keyword is taken by removing
430 /// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
431 /// everything after the first whitespace (`"impl Iterator for A" -> "impl"`)
432 ///
433 /// Attention: The method used is very fragile since it essentially duplicates the work of the
434 /// parser. If you need to use this function or something similar, please consider updating the
435 /// source_map functions and this function to something more robust.
436 fn reduce_impl_span_to_impl_keyword(cm: &SourceMap, impl_span: Span) -> Span {
437 let impl_span = cm.span_until_char(impl_span, '<');
438 let impl_span = cm.span_until_whitespace(impl_span);
439 impl_span
440 }
441
442 #[derive(Copy, Clone, Debug)]
443 struct BindingInfo {
444 span: Span,
445 binding_mode: BindingMode,
446 }
447
448 /// Map from the name in a pattern to its binding mode.
449 type BindingMap = FxHashMap<Ident, BindingInfo>;
450
451 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
452 enum PatternSource {
453 Match,
454 IfLet,
455 WhileLet,
456 Let,
457 For,
458 FnParam,
459 }
460
461 impl PatternSource {
462 fn descr(self) -> &'static str {
463 match self {
464 PatternSource::Match => "match binding",
465 PatternSource::IfLet => "if let binding",
466 PatternSource::WhileLet => "while let binding",
467 PatternSource::Let => "let binding",
468 PatternSource::For => "for binding",
469 PatternSource::FnParam => "function parameter",
470 }
471 }
472 }
473
474 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
475 enum AliasPossibility {
476 No,
477 Maybe,
478 }
479
480 #[derive(Copy, Clone, Debug)]
481 enum PathSource<'a> {
482 // Type paths `Path`.
483 Type,
484 // Trait paths in bounds or impls.
485 Trait(AliasPossibility),
486 // Expression paths `path`, with optional parent context.
487 Expr(Option<&'a Expr>),
488 // Paths in path patterns `Path`.
489 Pat,
490 // Paths in struct expressions and patterns `Path { .. }`.
491 Struct,
492 // Paths in tuple struct patterns `Path(..)`.
493 TupleStruct,
494 // `m::A::B` in `<T as m::A>::B::C`.
495 TraitItem(Namespace),
496 // Path in `pub(path)`
497 Visibility,
498 }
499
500 impl<'a> PathSource<'a> {
501 fn namespace(self) -> Namespace {
502 match self {
503 PathSource::Type | PathSource::Trait(_) | PathSource::Struct |
504 PathSource::Visibility => TypeNS,
505 PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct => ValueNS,
506 PathSource::TraitItem(ns) => ns,
507 }
508 }
509
510 fn global_by_default(self) -> bool {
511 match self {
512 PathSource::Visibility => true,
513 PathSource::Type | PathSource::Expr(..) | PathSource::Pat |
514 PathSource::Struct | PathSource::TupleStruct |
515 PathSource::Trait(_) | PathSource::TraitItem(..) => false,
516 }
517 }
518
519 fn defer_to_typeck(self) -> bool {
520 match self {
521 PathSource::Type | PathSource::Expr(..) | PathSource::Pat |
522 PathSource::Struct | PathSource::TupleStruct => true,
523 PathSource::Trait(_) | PathSource::TraitItem(..) |
524 PathSource::Visibility => false,
525 }
526 }
527
528 fn descr_expected(self) -> &'static str {
529 match self {
530 PathSource::Type => "type",
531 PathSource::Trait(_) => "trait",
532 PathSource::Pat => "unit struct/variant or constant",
533 PathSource::Struct => "struct, variant or union type",
534 PathSource::TupleStruct => "tuple struct/variant",
535 PathSource::Visibility => "module",
536 PathSource::TraitItem(ns) => match ns {
537 TypeNS => "associated type",
538 ValueNS => "method or associated constant",
539 MacroNS => bug!("associated macro"),
540 },
541 PathSource::Expr(parent) => match parent.map(|p| &p.node) {
542 // "function" here means "anything callable" rather than `Def::Fn`,
543 // this is not precise but usually more helpful than just "value".
544 Some(&ExprKind::Call(..)) => "function",
545 _ => "value",
546 },
547 }
548 }
549
550 fn is_expected(self, def: Def) -> bool {
551 match self {
552 PathSource::Type => match def {
553 Def::Struct(..) | Def::Union(..) | Def::Enum(..) |
554 Def::Trait(..) | Def::TraitAlias(..) | Def::TyAlias(..) |
555 Def::AssociatedTy(..) | Def::PrimTy(..) | Def::TyParam(..) |
556 Def::SelfTy(..) | Def::Existential(..) |
557 Def::ForeignTy(..) => true,
558 _ => false,
559 },
560 PathSource::Trait(AliasPossibility::No) => match def {
561 Def::Trait(..) => true,
562 _ => false,
563 },
564 PathSource::Trait(AliasPossibility::Maybe) => match def {
565 Def::Trait(..) => true,
566 Def::TraitAlias(..) => true,
567 _ => false,
568 },
569 PathSource::Expr(..) => match def {
570 Def::StructCtor(_, CtorKind::Const) | Def::StructCtor(_, CtorKind::Fn) |
571 Def::VariantCtor(_, CtorKind::Const) | Def::VariantCtor(_, CtorKind::Fn) |
572 Def::Const(..) | Def::Static(..) | Def::Local(..) | Def::Upvar(..) |
573 Def::Fn(..) | Def::Method(..) | Def::AssociatedConst(..) |
574 Def::SelfCtor(..) => true,
575 _ => false,
576 },
577 PathSource::Pat => match def {
578 Def::StructCtor(_, CtorKind::Const) |
579 Def::VariantCtor(_, CtorKind::Const) |
580 Def::Const(..) | Def::AssociatedConst(..) |
581 Def::SelfCtor(..) => true,
582 _ => false,
583 },
584 PathSource::TupleStruct => match def {
585 Def::StructCtor(_, CtorKind::Fn) |
586 Def::VariantCtor(_, CtorKind::Fn) |
587 Def::SelfCtor(..) => true,
588 _ => false,
589 },
590 PathSource::Struct => match def {
591 Def::Struct(..) | Def::Union(..) | Def::Variant(..) |
592 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => true,
593 _ => false,
594 },
595 PathSource::TraitItem(ns) => match def {
596 Def::AssociatedConst(..) | Def::Method(..) if ns == ValueNS => true,
597 Def::AssociatedTy(..) if ns == TypeNS => true,
598 _ => false,
599 },
600 PathSource::Visibility => match def {
601 Def::Mod(..) => true,
602 _ => false,
603 },
604 }
605 }
606
607 fn error_code(self, has_unexpected_resolution: bool) -> &'static str {
608 __diagnostic_used!(E0404);
609 __diagnostic_used!(E0405);
610 __diagnostic_used!(E0412);
611 __diagnostic_used!(E0422);
612 __diagnostic_used!(E0423);
613 __diagnostic_used!(E0425);
614 __diagnostic_used!(E0531);
615 __diagnostic_used!(E0532);
616 __diagnostic_used!(E0573);
617 __diagnostic_used!(E0574);
618 __diagnostic_used!(E0575);
619 __diagnostic_used!(E0576);
620 __diagnostic_used!(E0577);
621 __diagnostic_used!(E0578);
622 match (self, has_unexpected_resolution) {
623 (PathSource::Trait(_), true) => "E0404",
624 (PathSource::Trait(_), false) => "E0405",
625 (PathSource::Type, true) => "E0573",
626 (PathSource::Type, false) => "E0412",
627 (PathSource::Struct, true) => "E0574",
628 (PathSource::Struct, false) => "E0422",
629 (PathSource::Expr(..), true) => "E0423",
630 (PathSource::Expr(..), false) => "E0425",
631 (PathSource::Pat, true) | (PathSource::TupleStruct, true) => "E0532",
632 (PathSource::Pat, false) | (PathSource::TupleStruct, false) => "E0531",
633 (PathSource::TraitItem(..), true) => "E0575",
634 (PathSource::TraitItem(..), false) => "E0576",
635 (PathSource::Visibility, true) => "E0577",
636 (PathSource::Visibility, false) => "E0578",
637 }
638 }
639 }
640
641 // A minimal representation of a path segment. We use this in resolve because
642 // we synthesize 'path segments' which don't have the rest of an AST or HIR
643 // `PathSegment`.
644 #[derive(Clone, Copy, Debug)]
645 pub struct Segment {
646 ident: Ident,
647 id: Option<NodeId>,
648 }
649
650 impl Segment {
651 fn from_path(path: &Path) -> Vec<Segment> {
652 path.segments.iter().map(|s| s.into()).collect()
653 }
654
655 fn from_ident(ident: Ident) -> Segment {
656 Segment {
657 ident,
658 id: None,
659 }
660 }
661
662 fn names_to_string(segments: &[Segment]) -> String {
663 names_to_string(&segments.iter()
664 .map(|seg| seg.ident)
665 .collect::<Vec<_>>())
666 }
667 }
668
669 impl<'a> From<&'a ast::PathSegment> for Segment {
670 fn from(seg: &'a ast::PathSegment) -> Segment {
671 Segment {
672 ident: seg.ident,
673 id: Some(seg.id),
674 }
675 }
676 }
677
678 struct UsePlacementFinder {
679 target_module: NodeId,
680 span: Option<Span>,
681 found_use: bool,
682 }
683
684 impl UsePlacementFinder {
685 fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, bool) {
686 let mut finder = UsePlacementFinder {
687 target_module,
688 span: None,
689 found_use: false,
690 };
691 visit::walk_crate(&mut finder, krate);
692 (finder.span, finder.found_use)
693 }
694 }
695
696 impl<'tcx> Visitor<'tcx> for UsePlacementFinder {
697 fn visit_mod(
698 &mut self,
699 module: &'tcx ast::Mod,
700 _: Span,
701 _: &[ast::Attribute],
702 node_id: NodeId,
703 ) {
704 if self.span.is_some() {
705 return;
706 }
707 if node_id != self.target_module {
708 visit::walk_mod(self, module);
709 return;
710 }
711 // find a use statement
712 for item in &module.items {
713 match item.node {
714 ItemKind::Use(..) => {
715 // don't suggest placing a use before the prelude
716 // import or other generated ones
717 if item.span.ctxt().outer().expn_info().is_none() {
718 self.span = Some(item.span.shrink_to_lo());
719 self.found_use = true;
720 return;
721 }
722 },
723 // don't place use before extern crate
724 ItemKind::ExternCrate(_) => {}
725 // but place them before the first other item
726 _ => if self.span.map_or(true, |span| item.span < span ) {
727 if item.span.ctxt().outer().expn_info().is_none() {
728 // don't insert between attributes and an item
729 if item.attrs.is_empty() {
730 self.span = Some(item.span.shrink_to_lo());
731 } else {
732 // find the first attribute on the item
733 for attr in &item.attrs {
734 if self.span.map_or(true, |span| attr.span < span) {
735 self.span = Some(attr.span.shrink_to_lo());
736 }
737 }
738 }
739 }
740 },
741 }
742 }
743 }
744 }
745
746 /// This thing walks the whole crate in DFS manner, visiting each item, resolving names as it goes.
747 impl<'a, 'tcx> Visitor<'tcx> for Resolver<'a> {
748 fn visit_item(&mut self, item: &'tcx Item) {
749 self.resolve_item(item);
750 }
751 fn visit_arm(&mut self, arm: &'tcx Arm) {
752 self.resolve_arm(arm);
753 }
754 fn visit_block(&mut self, block: &'tcx Block) {
755 self.resolve_block(block);
756 }
757 fn visit_anon_const(&mut self, constant: &'tcx ast::AnonConst) {
758 self.with_constant_rib(|this| {
759 visit::walk_anon_const(this, constant);
760 });
761 }
762 fn visit_expr(&mut self, expr: &'tcx Expr) {
763 self.resolve_expr(expr, None);
764 }
765 fn visit_local(&mut self, local: &'tcx Local) {
766 self.resolve_local(local);
767 }
768 fn visit_ty(&mut self, ty: &'tcx Ty) {
769 match ty.node {
770 TyKind::Path(ref qself, ref path) => {
771 self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
772 }
773 TyKind::ImplicitSelf => {
774 let self_ty = keywords::SelfUpper.ident();
775 let def = self.resolve_ident_in_lexical_scope(self_ty, TypeNS, Some(ty.id), ty.span)
776 .map_or(Def::Err, |d| d.def());
777 self.record_def(ty.id, PathResolution::new(def));
778 }
779 _ => (),
780 }
781 visit::walk_ty(self, ty);
782 }
783 fn visit_poly_trait_ref(&mut self,
784 tref: &'tcx ast::PolyTraitRef,
785 m: &'tcx ast::TraitBoundModifier) {
786 self.smart_resolve_path(tref.trait_ref.ref_id, None,
787 &tref.trait_ref.path, PathSource::Trait(AliasPossibility::Maybe));
788 visit::walk_poly_trait_ref(self, tref, m);
789 }
790 fn visit_foreign_item(&mut self, foreign_item: &'tcx ForeignItem) {
791 let type_parameters = match foreign_item.node {
792 ForeignItemKind::Fn(_, ref generics) => {
793 HasTypeParameters(generics, ItemRibKind)
794 }
795 ForeignItemKind::Static(..) => NoTypeParameters,
796 ForeignItemKind::Ty => NoTypeParameters,
797 ForeignItemKind::Macro(..) => NoTypeParameters,
798 };
799 self.with_type_parameter_rib(type_parameters, |this| {
800 visit::walk_foreign_item(this, foreign_item);
801 });
802 }
803 fn visit_fn(&mut self,
804 function_kind: FnKind<'tcx>,
805 declaration: &'tcx FnDecl,
806 _: Span,
807 node_id: NodeId)
808 {
809 let (rib_kind, asyncness) = match function_kind {
810 FnKind::ItemFn(_, ref header, ..) =>
811 (ItemRibKind, header.asyncness),
812 FnKind::Method(_, ref sig, _, _) =>
813 (TraitOrImplItemRibKind, sig.header.asyncness),
814 FnKind::Closure(_) =>
815 // Async closures aren't resolved through `visit_fn`-- they're
816 // processed separately
817 (ClosureRibKind(node_id), IsAsync::NotAsync),
818 };
819
820 // Create a value rib for the function.
821 self.ribs[ValueNS].push(Rib::new(rib_kind));
822
823 // Create a label rib for the function.
824 self.label_ribs.push(Rib::new(rib_kind));
825
826 // Add each argument to the rib.
827 let mut bindings_list = FxHashMap::default();
828 for argument in &declaration.inputs {
829 self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
830
831 self.visit_ty(&argument.ty);
832
833 debug!("(resolving function) recorded argument");
834 }
835 visit::walk_fn_ret_ty(self, &declaration.output);
836
837 // Resolve the function body, potentially inside the body of an async closure
838 if let IsAsync::Async { closure_id, .. } = asyncness {
839 let rib_kind = ClosureRibKind(closure_id);
840 self.ribs[ValueNS].push(Rib::new(rib_kind));
841 self.label_ribs.push(Rib::new(rib_kind));
842 }
843
844 match function_kind {
845 FnKind::ItemFn(.., body) |
846 FnKind::Method(.., body) => {
847 self.visit_block(body);
848 }
849 FnKind::Closure(body) => {
850 self.visit_expr(body);
851 }
852 };
853
854 // Leave the body of the async closure
855 if asyncness.is_async() {
856 self.label_ribs.pop();
857 self.ribs[ValueNS].pop();
858 }
859
860 debug!("(resolving function) leaving function");
861
862 self.label_ribs.pop();
863 self.ribs[ValueNS].pop();
864 }
865 fn visit_generics(&mut self, generics: &'tcx Generics) {
866 // For type parameter defaults, we have to ban access
867 // to following type parameters, as the Substs can only
868 // provide previous type parameters as they're built. We
869 // put all the parameters on the ban list and then remove
870 // them one by one as they are processed and become available.
871 let mut default_ban_rib = Rib::new(ForwardTyParamBanRibKind);
872 let mut found_default = false;
873 default_ban_rib.bindings.extend(generics.params.iter()
874 .filter_map(|param| match param.kind {
875 GenericParamKind::Lifetime { .. } => None,
876 GenericParamKind::Type { ref default, .. } => {
877 found_default |= default.is_some();
878 if found_default {
879 Some((Ident::with_empty_ctxt(param.ident.name), Def::Err))
880 } else {
881 None
882 }
883 }
884 }));
885
886 for param in &generics.params {
887 match param.kind {
888 GenericParamKind::Lifetime { .. } => self.visit_generic_param(param),
889 GenericParamKind::Type { ref default, .. } => {
890 for bound in &param.bounds {
891 self.visit_param_bound(bound);
892 }
893
894 if let Some(ref ty) = default {
895 self.ribs[TypeNS].push(default_ban_rib);
896 self.visit_ty(ty);
897 default_ban_rib = self.ribs[TypeNS].pop().unwrap();
898 }
899
900 // Allow all following defaults to refer to this type parameter.
901 default_ban_rib.bindings.remove(&Ident::with_empty_ctxt(param.ident.name));
902 }
903 }
904 }
905 for p in &generics.where_clause.predicates {
906 self.visit_where_predicate(p);
907 }
908 }
909 }
910
911 #[derive(Copy, Clone)]
912 enum TypeParameters<'a, 'b> {
913 NoTypeParameters,
914 HasTypeParameters(// Type parameters.
915 &'b Generics,
916
917 // The kind of the rib used for type parameters.
918 RibKind<'a>),
919 }
920
921 /// The rib kind controls the translation of local
922 /// definitions (`Def::Local`) to upvars (`Def::Upvar`).
923 #[derive(Copy, Clone, Debug)]
924 enum RibKind<'a> {
925 /// No translation needs to be applied.
926 NormalRibKind,
927
928 /// We passed through a closure scope at the given node ID.
929 /// Translate upvars as appropriate.
930 ClosureRibKind(NodeId /* func id */),
931
932 /// We passed through an impl or trait and are now in one of its
933 /// methods or associated types. Allow references to ty params that impl or trait
934 /// binds. Disallow any other upvars (including other ty params that are
935 /// upvars).
936 TraitOrImplItemRibKind,
937
938 /// We passed through an item scope. Disallow upvars.
939 ItemRibKind,
940
941 /// We're in a constant item. Can't refer to dynamic stuff.
942 ConstantItemRibKind,
943
944 /// We passed through a module.
945 ModuleRibKind(Module<'a>),
946
947 /// We passed through a `macro_rules!` statement
948 MacroDefinition(DefId),
949
950 /// All bindings in this rib are type parameters that can't be used
951 /// from the default of a type parameter because they're not declared
952 /// before said type parameter. Also see the `visit_generics` override.
953 ForwardTyParamBanRibKind,
954 }
955
956 /// One local scope.
957 ///
958 /// A rib represents a scope names can live in. Note that these appear in many places, not just
959 /// around braces. At any place where the list of accessible names (of the given namespace)
960 /// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
961 /// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
962 /// etc.
963 ///
964 /// Different [rib kinds](enum.RibKind) are transparent for different names.
965 ///
966 /// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
967 /// resolving, the name is looked up from inside out.
968 #[derive(Debug)]
969 struct Rib<'a> {
970 bindings: FxHashMap<Ident, Def>,
971 kind: RibKind<'a>,
972 }
973
974 impl<'a> Rib<'a> {
975 fn new(kind: RibKind<'a>) -> Rib<'a> {
976 Rib {
977 bindings: Default::default(),
978 kind,
979 }
980 }
981 }
982
983 /// An intermediate resolution result.
984 ///
985 /// This refers to the thing referred by a name. The difference between `Def` and `Item` is that
986 /// items are visible in their whole block, while defs only from the place they are defined
987 /// forward.
988 enum LexicalScopeBinding<'a> {
989 Item(&'a NameBinding<'a>),
990 Def(Def),
991 }
992
993 impl<'a> LexicalScopeBinding<'a> {
994 fn item(self) -> Option<&'a NameBinding<'a>> {
995 match self {
996 LexicalScopeBinding::Item(binding) => Some(binding),
997 _ => None,
998 }
999 }
1000
1001 fn def(self) -> Def {
1002 match self {
1003 LexicalScopeBinding::Item(binding) => binding.def(),
1004 LexicalScopeBinding::Def(def) => def,
1005 }
1006 }
1007 }
1008
1009 #[derive(Copy, Clone, Debug)]
1010 enum ModuleOrUniformRoot<'a> {
1011 /// Regular module.
1012 Module(Module<'a>),
1013
1014 /// Virtual module that denotes resolution in crate root with fallback to extern prelude.
1015 CrateRootAndExternPrelude,
1016
1017 /// Virtual module that denotes resolution in extern prelude.
1018 /// Used for paths starting with `::` on 2018 edition.
1019 ExternPrelude,
1020
1021 /// Virtual module that denotes resolution in current scope.
1022 /// Used only for resolving single-segment imports. The reason it exists is that import paths
1023 /// are always split into two parts, the first of which should be some kind of module.
1024 CurrentScope,
1025 }
1026
1027 impl ModuleOrUniformRoot<'_> {
1028 fn same_def(lhs: Self, rhs: Self) -> bool {
1029 match (lhs, rhs) {
1030 (ModuleOrUniformRoot::Module(lhs),
1031 ModuleOrUniformRoot::Module(rhs)) => lhs.def() == rhs.def(),
1032 (ModuleOrUniformRoot::CrateRootAndExternPrelude,
1033 ModuleOrUniformRoot::CrateRootAndExternPrelude) |
1034 (ModuleOrUniformRoot::ExternPrelude, ModuleOrUniformRoot::ExternPrelude) |
1035 (ModuleOrUniformRoot::CurrentScope, ModuleOrUniformRoot::CurrentScope) => true,
1036 _ => false,
1037 }
1038 }
1039 }
1040
1041 #[derive(Clone, Debug)]
1042 enum PathResult<'a> {
1043 Module(ModuleOrUniformRoot<'a>),
1044 NonModule(PathResolution),
1045 Indeterminate,
1046 Failed(Span, String, bool /* is the error from the last segment? */),
1047 }
1048
1049 enum ModuleKind {
1050 /// An anonymous module, eg. just a block.
1051 ///
1052 /// ```
1053 /// fn main() {
1054 /// fn f() {} // (1)
1055 /// { // This is an anonymous module
1056 /// f(); // This resolves to (2) as we are inside the block.
1057 /// fn f() {} // (2)
1058 /// }
1059 /// f(); // Resolves to (1)
1060 /// }
1061 /// ```
1062 Block(NodeId),
1063 /// Any module with a name.
1064 ///
1065 /// This could be:
1066 ///
1067 /// * A normal module ‒ either `mod from_file;` or `mod from_block { }`.
1068 /// * A trait or an enum (it implicitly contains associated types, methods and variant
1069 /// constructors).
1070 Def(Def, Name),
1071 }
1072
1073 /// One node in the tree of modules.
1074 pub struct ModuleData<'a> {
1075 parent: Option<Module<'a>>,
1076 kind: ModuleKind,
1077
1078 // The def id of the closest normal module (`mod`) ancestor (including this module).
1079 normal_ancestor_id: DefId,
1080
1081 resolutions: RefCell<FxHashMap<(Ident, Namespace), &'a RefCell<NameResolution<'a>>>>,
1082 single_segment_macro_resolutions: RefCell<Vec<(Ident, MacroKind, ParentScope<'a>,
1083 Option<&'a NameBinding<'a>>)>>,
1084 multi_segment_macro_resolutions: RefCell<Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'a>,
1085 Option<Def>)>>,
1086 builtin_attrs: RefCell<Vec<(Ident, ParentScope<'a>)>>,
1087
1088 // Macro invocations that can expand into items in this module.
1089 unresolved_invocations: RefCell<FxHashSet<Mark>>,
1090
1091 no_implicit_prelude: bool,
1092
1093 glob_importers: RefCell<Vec<&'a ImportDirective<'a>>>,
1094 globs: RefCell<Vec<&'a ImportDirective<'a>>>,
1095
1096 // Used to memoize the traits in this module for faster searches through all traits in scope.
1097 traits: RefCell<Option<Box<[(Ident, &'a NameBinding<'a>)]>>>,
1098
1099 // Whether this module is populated. If not populated, any attempt to
1100 // access the children must be preceded with a
1101 // `populate_module_if_necessary` call.
1102 populated: Cell<bool>,
1103
1104 /// Span of the module itself. Used for error reporting.
1105 span: Span,
1106
1107 expansion: Mark,
1108 }
1109
1110 type Module<'a> = &'a ModuleData<'a>;
1111
1112 impl<'a> ModuleData<'a> {
1113 fn new(parent: Option<Module<'a>>,
1114 kind: ModuleKind,
1115 normal_ancestor_id: DefId,
1116 expansion: Mark,
1117 span: Span) -> Self {
1118 ModuleData {
1119 parent,
1120 kind,
1121 normal_ancestor_id,
1122 resolutions: Default::default(),
1123 single_segment_macro_resolutions: RefCell::new(Vec::new()),
1124 multi_segment_macro_resolutions: RefCell::new(Vec::new()),
1125 builtin_attrs: RefCell::new(Vec::new()),
1126 unresolved_invocations: Default::default(),
1127 no_implicit_prelude: false,
1128 glob_importers: RefCell::new(Vec::new()),
1129 globs: RefCell::new(Vec::new()),
1130 traits: RefCell::new(None),
1131 populated: Cell::new(normal_ancestor_id.is_local()),
1132 span,
1133 expansion,
1134 }
1135 }
1136
1137 fn for_each_child<F: FnMut(Ident, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
1138 for (&(ident, ns), name_resolution) in self.resolutions.borrow().iter() {
1139 name_resolution.borrow().binding.map(|binding| f(ident, ns, binding));
1140 }
1141 }
1142
1143 fn for_each_child_stable<F: FnMut(Ident, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
1144 let resolutions = self.resolutions.borrow();
1145 let mut resolutions = resolutions.iter().collect::<Vec<_>>();
1146 resolutions.sort_by_cached_key(|&(&(ident, ns), _)| (ident.as_str(), ns));
1147 for &(&(ident, ns), &resolution) in resolutions.iter() {
1148 resolution.borrow().binding.map(|binding| f(ident, ns, binding));
1149 }
1150 }
1151
1152 fn def(&self) -> Option<Def> {
1153 match self.kind {
1154 ModuleKind::Def(def, _) => Some(def),
1155 _ => None,
1156 }
1157 }
1158
1159 fn def_id(&self) -> Option<DefId> {
1160 self.def().as_ref().map(Def::def_id)
1161 }
1162
1163 // `self` resolves to the first module ancestor that `is_normal`.
1164 fn is_normal(&self) -> bool {
1165 match self.kind {
1166 ModuleKind::Def(Def::Mod(_), _) => true,
1167 _ => false,
1168 }
1169 }
1170
1171 fn is_trait(&self) -> bool {
1172 match self.kind {
1173 ModuleKind::Def(Def::Trait(_), _) => true,
1174 _ => false,
1175 }
1176 }
1177
1178 fn nearest_item_scope(&'a self) -> Module<'a> {
1179 if self.is_trait() { self.parent.unwrap() } else { self }
1180 }
1181
1182 fn is_ancestor_of(&self, mut other: &Self) -> bool {
1183 while !ptr::eq(self, other) {
1184 if let Some(parent) = other.parent {
1185 other = parent;
1186 } else {
1187 return false;
1188 }
1189 }
1190 true
1191 }
1192 }
1193
1194 impl<'a> fmt::Debug for ModuleData<'a> {
1195 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1196 write!(f, "{:?}", self.def())
1197 }
1198 }
1199
1200 /// Records a possibly-private value, type, or module definition.
1201 #[derive(Clone, Debug)]
1202 pub struct NameBinding<'a> {
1203 kind: NameBindingKind<'a>,
1204 ambiguity: Option<(&'a NameBinding<'a>, AmbiguityKind)>,
1205 expansion: Mark,
1206 span: Span,
1207 vis: ty::Visibility,
1208 }
1209
1210 pub trait ToNameBinding<'a> {
1211 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a>;
1212 }
1213
1214 impl<'a> ToNameBinding<'a> for &'a NameBinding<'a> {
1215 fn to_name_binding(self, _: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
1216 self
1217 }
1218 }
1219
1220 #[derive(Clone, Debug)]
1221 enum NameBindingKind<'a> {
1222 Def(Def, /* is_macro_export */ bool),
1223 Module(Module<'a>),
1224 Import {
1225 binding: &'a NameBinding<'a>,
1226 directive: &'a ImportDirective<'a>,
1227 used: Cell<bool>,
1228 },
1229 }
1230
1231 struct PrivacyError<'a>(Span, Ident, &'a NameBinding<'a>);
1232
1233 struct UseError<'a> {
1234 err: DiagnosticBuilder<'a>,
1235 /// Attach `use` statements for these candidates
1236 candidates: Vec<ImportSuggestion>,
1237 /// The node id of the module to place the use statements in
1238 node_id: NodeId,
1239 /// Whether the diagnostic should state that it's "better"
1240 better: bool,
1241 }
1242
1243 #[derive(Clone, Copy, PartialEq, Debug)]
1244 enum AmbiguityKind {
1245 Import,
1246 AbsolutePath,
1247 BuiltinAttr,
1248 DeriveHelper,
1249 LegacyHelperVsPrelude,
1250 LegacyVsModern,
1251 GlobVsOuter,
1252 GlobVsGlob,
1253 GlobVsExpanded,
1254 MoreExpandedVsOuter,
1255 }
1256
1257 impl AmbiguityKind {
1258 fn descr(self) -> &'static str {
1259 match self {
1260 AmbiguityKind::Import =>
1261 "name vs any other name during import resolution",
1262 AmbiguityKind::AbsolutePath =>
1263 "name in the crate root vs extern crate during absolute path resolution",
1264 AmbiguityKind::BuiltinAttr =>
1265 "built-in attribute vs any other name",
1266 AmbiguityKind::DeriveHelper =>
1267 "derive helper attribute vs any other name",
1268 AmbiguityKind::LegacyHelperVsPrelude =>
1269 "legacy plugin helper attribute vs name from prelude",
1270 AmbiguityKind::LegacyVsModern =>
1271 "`macro_rules` vs non-`macro_rules` from other module",
1272 AmbiguityKind::GlobVsOuter =>
1273 "glob import vs any other name from outer scope during import/macro resolution",
1274 AmbiguityKind::GlobVsGlob =>
1275 "glob import vs glob import in the same module",
1276 AmbiguityKind::GlobVsExpanded =>
1277 "glob import vs macro-expanded name in the same \
1278 module during import/macro resolution",
1279 AmbiguityKind::MoreExpandedVsOuter =>
1280 "macro-expanded name vs less macro-expanded name \
1281 from outer scope during import/macro resolution",
1282 }
1283 }
1284 }
1285
1286 /// Miscellaneous bits of metadata for better ambiguity error reporting.
1287 #[derive(Clone, Copy, PartialEq)]
1288 enum AmbiguityErrorMisc {
1289 SuggestCrate,
1290 SuggestSelf,
1291 FromPrelude,
1292 None,
1293 }
1294
1295 struct AmbiguityError<'a> {
1296 kind: AmbiguityKind,
1297 ident: Ident,
1298 b1: &'a NameBinding<'a>,
1299 b2: &'a NameBinding<'a>,
1300 misc1: AmbiguityErrorMisc,
1301 misc2: AmbiguityErrorMisc,
1302 }
1303
1304 impl<'a> NameBinding<'a> {
1305 fn module(&self) -> Option<Module<'a>> {
1306 match self.kind {
1307 NameBindingKind::Module(module) => Some(module),
1308 NameBindingKind::Import { binding, .. } => binding.module(),
1309 _ => None,
1310 }
1311 }
1312
1313 fn def(&self) -> Def {
1314 match self.kind {
1315 NameBindingKind::Def(def, _) => def,
1316 NameBindingKind::Module(module) => module.def().unwrap(),
1317 NameBindingKind::Import { binding, .. } => binding.def(),
1318 }
1319 }
1320
1321 fn is_ambiguity(&self) -> bool {
1322 self.ambiguity.is_some() || match self.kind {
1323 NameBindingKind::Import { binding, .. } => binding.is_ambiguity(),
1324 _ => false,
1325 }
1326 }
1327
1328 // We sometimes need to treat variants as `pub` for backwards compatibility
1329 fn pseudo_vis(&self) -> ty::Visibility {
1330 if self.is_variant() && self.def().def_id().is_local() {
1331 ty::Visibility::Public
1332 } else {
1333 self.vis
1334 }
1335 }
1336
1337 fn is_variant(&self) -> bool {
1338 match self.kind {
1339 NameBindingKind::Def(Def::Variant(..), _) |
1340 NameBindingKind::Def(Def::VariantCtor(..), _) => true,
1341 _ => false,
1342 }
1343 }
1344
1345 fn is_extern_crate(&self) -> bool {
1346 match self.kind {
1347 NameBindingKind::Import {
1348 directive: &ImportDirective {
1349 subclass: ImportDirectiveSubclass::ExternCrate { .. }, ..
1350 }, ..
1351 } => true,
1352 NameBindingKind::Module(
1353 &ModuleData { kind: ModuleKind::Def(Def::Mod(def_id), _), .. }
1354 ) => def_id.index == CRATE_DEF_INDEX,
1355 _ => false,
1356 }
1357 }
1358
1359 fn is_import(&self) -> bool {
1360 match self.kind {
1361 NameBindingKind::Import { .. } => true,
1362 _ => false,
1363 }
1364 }
1365
1366 fn is_glob_import(&self) -> bool {
1367 match self.kind {
1368 NameBindingKind::Import { directive, .. } => directive.is_glob(),
1369 _ => false,
1370 }
1371 }
1372
1373 fn is_importable(&self) -> bool {
1374 match self.def() {
1375 Def::AssociatedConst(..) | Def::Method(..) | Def::AssociatedTy(..) => false,
1376 _ => true,
1377 }
1378 }
1379
1380 fn is_macro_def(&self) -> bool {
1381 match self.kind {
1382 NameBindingKind::Def(Def::Macro(..), _) => true,
1383 _ => false,
1384 }
1385 }
1386
1387 fn macro_kind(&self) -> Option<MacroKind> {
1388 match self.def() {
1389 Def::Macro(_, kind) => Some(kind),
1390 Def::NonMacroAttr(..) => Some(MacroKind::Attr),
1391 _ => None,
1392 }
1393 }
1394
1395 fn descr(&self) -> &'static str {
1396 if self.is_extern_crate() { "extern crate" } else { self.def().kind_name() }
1397 }
1398
1399 fn article(&self) -> &'static str {
1400 if self.is_extern_crate() { "an" } else { self.def().article() }
1401 }
1402
1403 // Suppose that we resolved macro invocation with `invoc_parent_expansion` to binding `binding`
1404 // at some expansion round `max(invoc, binding)` when they both emerged from macros.
1405 // Then this function returns `true` if `self` may emerge from a macro *after* that
1406 // in some later round and screw up our previously found resolution.
1407 // See more detailed explanation in
1408 // https://github.com/rust-lang/rust/pull/53778#issuecomment-419224049
1409 fn may_appear_after(&self, invoc_parent_expansion: Mark, binding: &NameBinding) -> bool {
1410 // self > max(invoc, binding) => !(self <= invoc || self <= binding)
1411 // Expansions are partially ordered, so "may appear after" is an inversion of
1412 // "certainly appears before or simultaneously" and includes unordered cases.
1413 let self_parent_expansion = self.expansion;
1414 let other_parent_expansion = binding.expansion;
1415 let certainly_before_other_or_simultaneously =
1416 other_parent_expansion.is_descendant_of(self_parent_expansion);
1417 let certainly_before_invoc_or_simultaneously =
1418 invoc_parent_expansion.is_descendant_of(self_parent_expansion);
1419 !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
1420 }
1421 }
1422
1423 /// Interns the names of the primitive types.
1424 ///
1425 /// All other types are defined somewhere and possibly imported, but the primitive ones need
1426 /// special handling, since they have no place of origin.
1427 #[derive(Default)]
1428 struct PrimitiveTypeTable {
1429 primitive_types: FxHashMap<Name, PrimTy>,
1430 }
1431
1432 impl PrimitiveTypeTable {
1433 fn new() -> PrimitiveTypeTable {
1434 let mut table = PrimitiveTypeTable::default();
1435
1436 table.intern("bool", Bool);
1437 table.intern("char", Char);
1438 table.intern("f32", Float(FloatTy::F32));
1439 table.intern("f64", Float(FloatTy::F64));
1440 table.intern("isize", Int(IntTy::Isize));
1441 table.intern("i8", Int(IntTy::I8));
1442 table.intern("i16", Int(IntTy::I16));
1443 table.intern("i32", Int(IntTy::I32));
1444 table.intern("i64", Int(IntTy::I64));
1445 table.intern("i128", Int(IntTy::I128));
1446 table.intern("str", Str);
1447 table.intern("usize", Uint(UintTy::Usize));
1448 table.intern("u8", Uint(UintTy::U8));
1449 table.intern("u16", Uint(UintTy::U16));
1450 table.intern("u32", Uint(UintTy::U32));
1451 table.intern("u64", Uint(UintTy::U64));
1452 table.intern("u128", Uint(UintTy::U128));
1453 table
1454 }
1455
1456 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1457 self.primitive_types.insert(Symbol::intern(string), primitive_type);
1458 }
1459 }
1460
1461 #[derive(Debug, Default, Clone)]
1462 pub struct ExternPreludeEntry<'a> {
1463 extern_crate_item: Option<&'a NameBinding<'a>>,
1464 pub introduced_by_item: bool,
1465 }
1466
1467 /// The main resolver class.
1468 ///
1469 /// This is the visitor that walks the whole crate.
1470 pub struct Resolver<'a> {
1471 session: &'a Session,
1472 cstore: &'a CStore,
1473
1474 pub definitions: Definitions,
1475
1476 graph_root: Module<'a>,
1477
1478 prelude: Option<Module<'a>>,
1479 pub extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'a>>,
1480
1481 /// n.b. This is used only for better diagnostics, not name resolution itself.
1482 has_self: FxHashSet<DefId>,
1483
1484 /// Names of fields of an item `DefId` accessible with dot syntax.
1485 /// Used for hints during error reporting.
1486 field_names: FxHashMap<DefId, Vec<Name>>,
1487
1488 /// All imports known to succeed or fail.
1489 determined_imports: Vec<&'a ImportDirective<'a>>,
1490
1491 /// All non-determined imports.
1492 indeterminate_imports: Vec<&'a ImportDirective<'a>>,
1493
1494 /// The module that represents the current item scope.
1495 current_module: Module<'a>,
1496
1497 /// The current set of local scopes for types and values.
1498 /// FIXME #4948: Reuse ribs to avoid allocation.
1499 ribs: PerNS<Vec<Rib<'a>>>,
1500
1501 /// The current set of local scopes, for labels.
1502 label_ribs: Vec<Rib<'a>>,
1503
1504 /// The trait that the current context can refer to.
1505 current_trait_ref: Option<(Module<'a>, TraitRef)>,
1506
1507 /// The current self type if inside an impl (used for better errors).
1508 current_self_type: Option<Ty>,
1509
1510 /// The current self item if inside an ADT (used for better errors).
1511 current_self_item: Option<NodeId>,
1512
1513 /// FIXME: Refactor things so that these fields are passed through arguments and not resolver.
1514 /// We are resolving a last import segment during import validation.
1515 last_import_segment: bool,
1516 /// This binding should be ignored during in-module resolution, so that we don't get
1517 /// "self-confirming" import resolutions during import validation.
1518 blacklisted_binding: Option<&'a NameBinding<'a>>,
1519
1520 /// The idents for the primitive types.
1521 primitive_type_table: PrimitiveTypeTable,
1522
1523 def_map: DefMap,
1524 import_map: ImportMap,
1525 pub freevars: FreevarMap,
1526 freevars_seen: NodeMap<NodeMap<usize>>,
1527 pub export_map: ExportMap,
1528 pub trait_map: TraitMap,
1529
1530 /// A map from nodes to anonymous modules.
1531 /// Anonymous modules are pseudo-modules that are implicitly created around items
1532 /// contained within blocks.
1533 ///
1534 /// For example, if we have this:
1535 ///
1536 /// fn f() {
1537 /// fn g() {
1538 /// ...
1539 /// }
1540 /// }
1541 ///
1542 /// There will be an anonymous module created around `g` with the ID of the
1543 /// entry block for `f`.
1544 block_map: NodeMap<Module<'a>>,
1545 module_map: FxHashMap<DefId, Module<'a>>,
1546 extern_module_map: FxHashMap<(DefId, bool /* MacrosOnly? */), Module<'a>>,
1547 binding_parent_modules: FxHashMap<PtrKey<'a, NameBinding<'a>>, Module<'a>>,
1548
1549 pub make_glob_map: bool,
1550 /// Maps imports to the names of items actually imported (this actually maps
1551 /// all imports, but only glob imports are actually interesting).
1552 pub glob_map: GlobMap,
1553
1554 used_imports: FxHashSet<(NodeId, Namespace)>,
1555 pub maybe_unused_trait_imports: NodeSet,
1556 pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
1557
1558 /// A list of labels as of yet unused. Labels will be removed from this map when
1559 /// they are used (in a `break` or `continue` statement)
1560 pub unused_labels: FxHashMap<NodeId, Span>,
1561
1562 /// privacy errors are delayed until the end in order to deduplicate them
1563 privacy_errors: Vec<PrivacyError<'a>>,
1564 /// ambiguity errors are delayed for deduplication
1565 ambiguity_errors: Vec<AmbiguityError<'a>>,
1566 /// `use` injections are delayed for better placement and deduplication
1567 use_injections: Vec<UseError<'a>>,
1568 /// crate-local macro expanded `macro_export` referred to by a module-relative path
1569 macro_expanded_macro_export_errors: BTreeSet<(Span, Span)>,
1570
1571 arenas: &'a ResolverArenas<'a>,
1572 dummy_binding: &'a NameBinding<'a>,
1573
1574 crate_loader: &'a mut CrateLoader<'a>,
1575 macro_names: FxHashSet<Ident>,
1576 builtin_macros: FxHashMap<Name, &'a NameBinding<'a>>,
1577 macro_use_prelude: FxHashMap<Name, &'a NameBinding<'a>>,
1578 pub all_macros: FxHashMap<Name, Def>,
1579 macro_map: FxHashMap<DefId, Lrc<SyntaxExtension>>,
1580 macro_defs: FxHashMap<Mark, DefId>,
1581 local_macro_def_scopes: FxHashMap<NodeId, Module<'a>>,
1582
1583 /// List of crate local macros that we need to warn about as being unused.
1584 /// Right now this only includes macro_rules! macros, and macros 2.0.
1585 unused_macros: FxHashSet<DefId>,
1586
1587 /// Maps the `Mark` of an expansion to its containing module or block.
1588 invocations: FxHashMap<Mark, &'a InvocationData<'a>>,
1589
1590 /// Avoid duplicated errors for "name already defined".
1591 name_already_seen: FxHashMap<Name, Span>,
1592
1593 potentially_unused_imports: Vec<&'a ImportDirective<'a>>,
1594
1595 /// This table maps struct IDs into struct constructor IDs,
1596 /// it's not used during normal resolution, only for better error reporting.
1597 struct_constructors: DefIdMap<(Def, ty::Visibility)>,
1598
1599 /// Only used for better errors on `fn(): fn()`
1600 current_type_ascription: Vec<Span>,
1601
1602 injected_crate: Option<Module<'a>>,
1603 }
1604
1605 /// Nothing really interesting here, it just provides memory for the rest of the crate.
1606 #[derive(Default)]
1607 pub struct ResolverArenas<'a> {
1608 modules: arena::TypedArena<ModuleData<'a>>,
1609 local_modules: RefCell<Vec<Module<'a>>>,
1610 name_bindings: arena::TypedArena<NameBinding<'a>>,
1611 import_directives: arena::TypedArena<ImportDirective<'a>>,
1612 name_resolutions: arena::TypedArena<RefCell<NameResolution<'a>>>,
1613 invocation_data: arena::TypedArena<InvocationData<'a>>,
1614 legacy_bindings: arena::TypedArena<LegacyBinding<'a>>,
1615 }
1616
1617 impl<'a> ResolverArenas<'a> {
1618 fn alloc_module(&'a self, module: ModuleData<'a>) -> Module<'a> {
1619 let module = self.modules.alloc(module);
1620 if module.def_id().map(|def_id| def_id.is_local()).unwrap_or(true) {
1621 self.local_modules.borrow_mut().push(module);
1622 }
1623 module
1624 }
1625 fn local_modules(&'a self) -> ::std::cell::Ref<'a, Vec<Module<'a>>> {
1626 self.local_modules.borrow()
1627 }
1628 fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
1629 self.name_bindings.alloc(name_binding)
1630 }
1631 fn alloc_import_directive(&'a self, import_directive: ImportDirective<'a>)
1632 -> &'a ImportDirective {
1633 self.import_directives.alloc(import_directive)
1634 }
1635 fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
1636 self.name_resolutions.alloc(Default::default())
1637 }
1638 fn alloc_invocation_data(&'a self, expansion_data: InvocationData<'a>)
1639 -> &'a InvocationData<'a> {
1640 self.invocation_data.alloc(expansion_data)
1641 }
1642 fn alloc_legacy_binding(&'a self, binding: LegacyBinding<'a>) -> &'a LegacyBinding<'a> {
1643 self.legacy_bindings.alloc(binding)
1644 }
1645 }
1646
1647 impl<'a, 'b: 'a> ty::DefIdTree for &'a Resolver<'b> {
1648 fn parent(self, id: DefId) -> Option<DefId> {
1649 match id.krate {
1650 LOCAL_CRATE => self.definitions.def_key(id.index).parent,
1651 _ => self.cstore.def_key(id).parent,
1652 }.map(|index| DefId { index, ..id })
1653 }
1654 }
1655
1656 /// This interface is used through the AST→HIR step, to embed full paths into the HIR. After that
1657 /// the resolver is no longer needed as all the relevant information is inline.
1658 impl<'a> hir::lowering::Resolver for Resolver<'a> {
1659 fn resolve_hir_path(
1660 &mut self,
1661 path: &ast::Path,
1662 is_value: bool,
1663 ) -> hir::Path {
1664 self.resolve_hir_path_cb(path, is_value,
1665 |resolver, span, error| resolve_error(resolver, span, error))
1666 }
1667
1668 fn resolve_str_path(
1669 &mut self,
1670 span: Span,
1671 crate_root: Option<&str>,
1672 components: &[&str],
1673 is_value: bool
1674 ) -> hir::Path {
1675 let segments = iter::once(keywords::PathRoot.ident())
1676 .chain(
1677 crate_root.into_iter()
1678 .chain(components.iter().cloned())
1679 .map(Ident::from_str)
1680 ).map(|i| self.new_ast_path_segment(i)).collect::<Vec<_>>();
1681
1682
1683 let path = ast::Path {
1684 span,
1685 segments,
1686 };
1687
1688 self.resolve_hir_path(&path, is_value)
1689 }
1690
1691 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution> {
1692 self.def_map.get(&id).cloned()
1693 }
1694
1695 fn get_import(&mut self, id: NodeId) -> PerNS<Option<PathResolution>> {
1696 self.import_map.get(&id).cloned().unwrap_or_default()
1697 }
1698
1699 fn definitions(&mut self) -> &mut Definitions {
1700 &mut self.definitions
1701 }
1702 }
1703
1704 impl<'a> Resolver<'a> {
1705 /// Rustdoc uses this to resolve things in a recoverable way. ResolutionError<'a>
1706 /// isn't something that can be returned because it can't be made to live that long,
1707 /// and also it's a private type. Fortunately rustdoc doesn't need to know the error,
1708 /// just that an error occurred.
1709 pub fn resolve_str_path_error(&mut self, span: Span, path_str: &str, is_value: bool)
1710 -> Result<hir::Path, ()> {
1711 use std::iter;
1712 let mut errored = false;
1713
1714 let path = if path_str.starts_with("::") {
1715 ast::Path {
1716 span,
1717 segments: iter::once(keywords::PathRoot.ident())
1718 .chain({
1719 path_str.split("::").skip(1).map(Ident::from_str)
1720 })
1721 .map(|i| self.new_ast_path_segment(i))
1722 .collect(),
1723 }
1724 } else {
1725 ast::Path {
1726 span,
1727 segments: path_str
1728 .split("::")
1729 .map(Ident::from_str)
1730 .map(|i| self.new_ast_path_segment(i))
1731 .collect(),
1732 }
1733 };
1734 let path = self.resolve_hir_path_cb(&path, is_value, |_, _, _| errored = true);
1735 if errored || path.def == Def::Err {
1736 Err(())
1737 } else {
1738 Ok(path)
1739 }
1740 }
1741
1742 /// resolve_hir_path, but takes a callback in case there was an error
1743 fn resolve_hir_path_cb<F>(
1744 &mut self,
1745 path: &ast::Path,
1746 is_value: bool,
1747 error_callback: F,
1748 ) -> hir::Path
1749 where F: for<'c, 'b> FnOnce(&'c mut Resolver, Span, ResolutionError<'b>)
1750 {
1751 let namespace = if is_value { ValueNS } else { TypeNS };
1752 let span = path.span;
1753 let segments = &path.segments;
1754 let path = Segment::from_path(&path);
1755 // FIXME (Manishearth): Intra doc links won't get warned of epoch changes
1756 let def = match self.resolve_path_without_parent_scope(&path, Some(namespace), true,
1757 span, CrateLint::No) {
1758 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
1759 module.def().unwrap(),
1760 PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 =>
1761 path_res.base_def(),
1762 PathResult::NonModule(..) => {
1763 let msg = "type-relative paths are not supported in this context";
1764 error_callback(self, span, ResolutionError::FailedToResolve(msg));
1765 Def::Err
1766 }
1767 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
1768 PathResult::Failed(span, msg, _) => {
1769 error_callback(self, span, ResolutionError::FailedToResolve(&msg));
1770 Def::Err
1771 }
1772 };
1773
1774 let segments: Vec<_> = segments.iter().map(|seg| {
1775 let mut hir_seg = hir::PathSegment::from_ident(seg.ident);
1776 hir_seg.def = Some(self.def_map.get(&seg.id).map_or(Def::Err, |p| p.base_def()));
1777 hir_seg
1778 }).collect();
1779 hir::Path {
1780 span,
1781 def,
1782 segments: segments.into(),
1783 }
1784 }
1785
1786 fn new_ast_path_segment(&self, ident: Ident) -> ast::PathSegment {
1787 let mut seg = ast::PathSegment::from_ident(ident);
1788 seg.id = self.session.next_node_id();
1789 seg
1790 }
1791 }
1792
1793 impl<'a> Resolver<'a> {
1794 pub fn new(session: &'a Session,
1795 cstore: &'a CStore,
1796 krate: &Crate,
1797 crate_name: &str,
1798 make_glob_map: MakeGlobMap,
1799 crate_loader: &'a mut CrateLoader<'a>,
1800 arenas: &'a ResolverArenas<'a>)
1801 -> Resolver<'a> {
1802 let root_def_id = DefId::local(CRATE_DEF_INDEX);
1803 let root_module_kind = ModuleKind::Def(Def::Mod(root_def_id), keywords::Invalid.name());
1804 let graph_root = arenas.alloc_module(ModuleData {
1805 no_implicit_prelude: attr::contains_name(&krate.attrs, "no_implicit_prelude"),
1806 ..ModuleData::new(None, root_module_kind, root_def_id, Mark::root(), krate.span)
1807 });
1808 let mut module_map = FxHashMap::default();
1809 module_map.insert(DefId::local(CRATE_DEF_INDEX), graph_root);
1810
1811 let mut definitions = Definitions::new();
1812 DefCollector::new(&mut definitions, Mark::root())
1813 .collect_root(crate_name, session.local_crate_disambiguator());
1814
1815 let mut extern_prelude: FxHashMap<Ident, ExternPreludeEntry> =
1816 session.opts.externs.iter().map(|kv| (Ident::from_str(kv.0), Default::default()))
1817 .collect();
1818
1819 if !attr::contains_name(&krate.attrs, "no_core") {
1820 extern_prelude.insert(Ident::from_str("core"), Default::default());
1821 if !attr::contains_name(&krate.attrs, "no_std") {
1822 extern_prelude.insert(Ident::from_str("std"), Default::default());
1823 if session.rust_2018() {
1824 extern_prelude.insert(Ident::from_str("meta"), Default::default());
1825 }
1826 }
1827 }
1828
1829 let mut invocations = FxHashMap::default();
1830 invocations.insert(Mark::root(),
1831 arenas.alloc_invocation_data(InvocationData::root(graph_root)));
1832
1833 let mut macro_defs = FxHashMap::default();
1834 macro_defs.insert(Mark::root(), root_def_id);
1835
1836 Resolver {
1837 session,
1838
1839 cstore,
1840
1841 definitions,
1842
1843 // The outermost module has def ID 0; this is not reflected in the
1844 // AST.
1845 graph_root,
1846 prelude: None,
1847 extern_prelude,
1848
1849 has_self: FxHashSet::default(),
1850 field_names: FxHashMap::default(),
1851
1852 determined_imports: Vec::new(),
1853 indeterminate_imports: Vec::new(),
1854
1855 current_module: graph_root,
1856 ribs: PerNS {
1857 value_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1858 type_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1859 macro_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1860 },
1861 label_ribs: Vec::new(),
1862
1863 current_trait_ref: None,
1864 current_self_type: None,
1865 current_self_item: None,
1866 last_import_segment: false,
1867 blacklisted_binding: None,
1868
1869 primitive_type_table: PrimitiveTypeTable::new(),
1870
1871 def_map: Default::default(),
1872 import_map: Default::default(),
1873 freevars: Default::default(),
1874 freevars_seen: Default::default(),
1875 export_map: FxHashMap::default(),
1876 trait_map: Default::default(),
1877 module_map,
1878 block_map: Default::default(),
1879 extern_module_map: FxHashMap::default(),
1880 binding_parent_modules: FxHashMap::default(),
1881
1882 make_glob_map: make_glob_map == MakeGlobMap::Yes,
1883 glob_map: Default::default(),
1884
1885 used_imports: FxHashSet::default(),
1886 maybe_unused_trait_imports: Default::default(),
1887 maybe_unused_extern_crates: Vec::new(),
1888
1889 unused_labels: FxHashMap::default(),
1890
1891 privacy_errors: Vec::new(),
1892 ambiguity_errors: Vec::new(),
1893 use_injections: Vec::new(),
1894 macro_expanded_macro_export_errors: BTreeSet::new(),
1895
1896 arenas,
1897 dummy_binding: arenas.alloc_name_binding(NameBinding {
1898 kind: NameBindingKind::Def(Def::Err, false),
1899 ambiguity: None,
1900 expansion: Mark::root(),
1901 span: DUMMY_SP,
1902 vis: ty::Visibility::Public,
1903 }),
1904
1905 crate_loader,
1906 macro_names: FxHashSet::default(),
1907 builtin_macros: FxHashMap::default(),
1908 macro_use_prelude: FxHashMap::default(),
1909 all_macros: FxHashMap::default(),
1910 macro_map: FxHashMap::default(),
1911 invocations,
1912 macro_defs,
1913 local_macro_def_scopes: FxHashMap::default(),
1914 name_already_seen: FxHashMap::default(),
1915 potentially_unused_imports: Vec::new(),
1916 struct_constructors: Default::default(),
1917 unused_macros: FxHashSet::default(),
1918 current_type_ascription: Vec::new(),
1919 injected_crate: None,
1920 }
1921 }
1922
1923 pub fn arenas() -> ResolverArenas<'a> {
1924 Default::default()
1925 }
1926
1927 /// Runs the function on each namespace.
1928 fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1929 f(self, TypeNS);
1930 f(self, ValueNS);
1931 f(self, MacroNS);
1932 }
1933
1934 fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1935 loop {
1936 match self.macro_defs.get(&ctxt.outer()) {
1937 Some(&def_id) => return def_id,
1938 None => ctxt.remove_mark(),
1939 };
1940 }
1941 }
1942
1943 /// Entry point to crate resolution.
1944 pub fn resolve_crate(&mut self, krate: &Crate) {
1945 ImportResolver { resolver: self }.finalize_imports();
1946 self.current_module = self.graph_root;
1947 self.finalize_current_module_macro_resolutions();
1948
1949 visit::walk_crate(self, krate);
1950
1951 check_unused::check_crate(self, krate);
1952 self.report_errors(krate);
1953 self.crate_loader.postprocess(krate);
1954 }
1955
1956 fn new_module(
1957 &self,
1958 parent: Module<'a>,
1959 kind: ModuleKind,
1960 normal_ancestor_id: DefId,
1961 expansion: Mark,
1962 span: Span,
1963 ) -> Module<'a> {
1964 let module = ModuleData::new(Some(parent), kind, normal_ancestor_id, expansion, span);
1965 self.arenas.alloc_module(module)
1966 }
1967
1968 fn record_use(&mut self, ident: Ident, ns: Namespace,
1969 used_binding: &'a NameBinding<'a>, is_lexical_scope: bool) {
1970 if let Some((b2, kind)) = used_binding.ambiguity {
1971 self.ambiguity_errors.push(AmbiguityError {
1972 kind, ident, b1: used_binding, b2,
1973 misc1: AmbiguityErrorMisc::None,
1974 misc2: AmbiguityErrorMisc::None,
1975 });
1976 }
1977 if let NameBindingKind::Import { directive, binding, ref used } = used_binding.kind {
1978 // Avoid marking `extern crate` items that refer to a name from extern prelude,
1979 // but not introduce it, as used if they are accessed from lexical scope.
1980 if is_lexical_scope {
1981 if let Some(entry) = self.extern_prelude.get(&ident.modern()) {
1982 if let Some(crate_item) = entry.extern_crate_item {
1983 if ptr::eq(used_binding, crate_item) && !entry.introduced_by_item {
1984 return;
1985 }
1986 }
1987 }
1988 }
1989 used.set(true);
1990 directive.used.set(true);
1991 self.used_imports.insert((directive.id, ns));
1992 self.add_to_glob_map(directive.id, ident);
1993 self.record_use(ident, ns, binding, false);
1994 }
1995 }
1996
1997 fn add_to_glob_map(&mut self, id: NodeId, ident: Ident) {
1998 if self.make_glob_map {
1999 self.glob_map.entry(id).or_default().insert(ident.name);
2000 }
2001 }
2002
2003 /// This resolves the identifier `ident` in the namespace `ns` in the current lexical scope.
2004 /// More specifically, we proceed up the hierarchy of scopes and return the binding for
2005 /// `ident` in the first scope that defines it (or None if no scopes define it).
2006 ///
2007 /// A block's items are above its local variables in the scope hierarchy, regardless of where
2008 /// the items are defined in the block. For example,
2009 /// ```rust
2010 /// fn f() {
2011 /// g(); // Since there are no local variables in scope yet, this resolves to the item.
2012 /// let g = || {};
2013 /// fn g() {}
2014 /// g(); // This resolves to the local variable `g` since it shadows the item.
2015 /// }
2016 /// ```
2017 ///
2018 /// Invariant: This must only be called during main resolution, not during
2019 /// import resolution.
2020 fn resolve_ident_in_lexical_scope(&mut self,
2021 mut ident: Ident,
2022 ns: Namespace,
2023 record_used_id: Option<NodeId>,
2024 path_span: Span)
2025 -> Option<LexicalScopeBinding<'a>> {
2026 assert!(ns == TypeNS || ns == ValueNS);
2027 if ident.name == keywords::Invalid.name() {
2028 return Some(LexicalScopeBinding::Def(Def::Err));
2029 }
2030 ident.span = if ident.name == keywords::SelfUpper.name() {
2031 // FIXME(jseyfried) improve `Self` hygiene
2032 ident.span.with_ctxt(SyntaxContext::empty())
2033 } else if ns == TypeNS {
2034 ident.span.modern()
2035 } else {
2036 ident.span.modern_and_legacy()
2037 };
2038
2039 // Walk backwards up the ribs in scope.
2040 let record_used = record_used_id.is_some();
2041 let mut module = self.graph_root;
2042 for i in (0 .. self.ribs[ns].len()).rev() {
2043 if let Some(def) = self.ribs[ns][i].bindings.get(&ident).cloned() {
2044 // The ident resolves to a type parameter or local variable.
2045 return Some(LexicalScopeBinding::Def(
2046 self.adjust_local_def(ns, i, def, record_used, path_span)
2047 ));
2048 }
2049
2050 module = match self.ribs[ns][i].kind {
2051 ModuleRibKind(module) => module,
2052 MacroDefinition(def) if def == self.macro_def(ident.span.ctxt()) => {
2053 // If an invocation of this macro created `ident`, give up on `ident`
2054 // and switch to `ident`'s source from the macro definition.
2055 ident.span.remove_mark();
2056 continue
2057 }
2058 _ => continue,
2059 };
2060
2061 let item = self.resolve_ident_in_module_unadjusted(
2062 ModuleOrUniformRoot::Module(module),
2063 ident,
2064 ns,
2065 record_used,
2066 path_span,
2067 );
2068 if let Ok(binding) = item {
2069 // The ident resolves to an item.
2070 return Some(LexicalScopeBinding::Item(binding));
2071 }
2072
2073 match module.kind {
2074 ModuleKind::Block(..) => {}, // We can see through blocks
2075 _ => break,
2076 }
2077 }
2078
2079 ident.span = ident.span.modern();
2080 let mut poisoned = None;
2081 loop {
2082 let opt_module = if let Some(node_id) = record_used_id {
2083 self.hygienic_lexical_parent_with_compatibility_fallback(module, &mut ident.span,
2084 node_id, &mut poisoned)
2085 } else {
2086 self.hygienic_lexical_parent(module, &mut ident.span)
2087 };
2088 module = unwrap_or!(opt_module, break);
2089 let orig_current_module = self.current_module;
2090 self.current_module = module; // Lexical resolutions can never be a privacy error.
2091 let result = self.resolve_ident_in_module_unadjusted(
2092 ModuleOrUniformRoot::Module(module),
2093 ident,
2094 ns,
2095 record_used,
2096 path_span,
2097 );
2098 self.current_module = orig_current_module;
2099
2100 match result {
2101 Ok(binding) => {
2102 if let Some(node_id) = poisoned {
2103 self.session.buffer_lint_with_diagnostic(
2104 lint::builtin::PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
2105 node_id, ident.span,
2106 &format!("cannot find {} `{}` in this scope", ns.descr(), ident),
2107 lint::builtin::BuiltinLintDiagnostics::
2108 ProcMacroDeriveResolutionFallback(ident.span),
2109 );
2110 }
2111 return Some(LexicalScopeBinding::Item(binding))
2112 }
2113 Err(Determined) => continue,
2114 Err(Undetermined) =>
2115 span_bug!(ident.span, "undetermined resolution during main resolution pass"),
2116 }
2117 }
2118
2119 if !module.no_implicit_prelude {
2120 if ns == TypeNS {
2121 if let Some(binding) = self.extern_prelude_get(ident, !record_used) {
2122 return Some(LexicalScopeBinding::Item(binding));
2123 }
2124 }
2125 if ns == TypeNS && is_known_tool(ident.name) {
2126 let binding = (Def::ToolMod, ty::Visibility::Public,
2127 DUMMY_SP, Mark::root()).to_name_binding(self.arenas);
2128 return Some(LexicalScopeBinding::Item(binding));
2129 }
2130 if let Some(prelude) = self.prelude {
2131 if let Ok(binding) = self.resolve_ident_in_module_unadjusted(
2132 ModuleOrUniformRoot::Module(prelude),
2133 ident,
2134 ns,
2135 false,
2136 path_span,
2137 ) {
2138 return Some(LexicalScopeBinding::Item(binding));
2139 }
2140 }
2141 }
2142
2143 None
2144 }
2145
2146 fn hygienic_lexical_parent(&mut self, module: Module<'a>, span: &mut Span)
2147 -> Option<Module<'a>> {
2148 if !module.expansion.is_descendant_of(span.ctxt().outer()) {
2149 return Some(self.macro_def_scope(span.remove_mark()));
2150 }
2151
2152 if let ModuleKind::Block(..) = module.kind {
2153 return Some(module.parent.unwrap());
2154 }
2155
2156 None
2157 }
2158
2159 fn hygienic_lexical_parent_with_compatibility_fallback(&mut self, module: Module<'a>,
2160 span: &mut Span, node_id: NodeId,
2161 poisoned: &mut Option<NodeId>)
2162 -> Option<Module<'a>> {
2163 if let module @ Some(..) = self.hygienic_lexical_parent(module, span) {
2164 return module;
2165 }
2166
2167 // We need to support the next case under a deprecation warning
2168 // ```
2169 // struct MyStruct;
2170 // ---- begin: this comes from a proc macro derive
2171 // mod implementation_details {
2172 // // Note that `MyStruct` is not in scope here.
2173 // impl SomeTrait for MyStruct { ... }
2174 // }
2175 // ---- end
2176 // ```
2177 // So we have to fall back to the module's parent during lexical resolution in this case.
2178 if let Some(parent) = module.parent {
2179 // Inner module is inside the macro, parent module is outside of the macro.
2180 if module.expansion != parent.expansion &&
2181 module.expansion.is_descendant_of(parent.expansion) {
2182 // The macro is a proc macro derive
2183 if module.expansion.looks_like_proc_macro_derive() {
2184 if parent.expansion.is_descendant_of(span.ctxt().outer()) {
2185 *poisoned = Some(node_id);
2186 return module.parent;
2187 }
2188 }
2189 }
2190 }
2191
2192 None
2193 }
2194
2195 fn resolve_ident_in_module(
2196 &mut self,
2197 module: ModuleOrUniformRoot<'a>,
2198 ident: Ident,
2199 ns: Namespace,
2200 parent_scope: Option<&ParentScope<'a>>,
2201 record_used: bool,
2202 path_span: Span
2203 ) -> Result<&'a NameBinding<'a>, Determinacy> {
2204 self.resolve_ident_in_module_ext(
2205 module, ident, ns, parent_scope, record_used, path_span
2206 ).map_err(|(determinacy, _)| determinacy)
2207 }
2208
2209 fn resolve_ident_in_module_ext(
2210 &mut self,
2211 module: ModuleOrUniformRoot<'a>,
2212 mut ident: Ident,
2213 ns: Namespace,
2214 parent_scope: Option<&ParentScope<'a>>,
2215 record_used: bool,
2216 path_span: Span
2217 ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> {
2218 let orig_current_module = self.current_module;
2219 match module {
2220 ModuleOrUniformRoot::Module(module) => {
2221 ident.span = ident.span.modern();
2222 if let Some(def) = ident.span.adjust(module.expansion) {
2223 self.current_module = self.macro_def_scope(def);
2224 }
2225 }
2226 ModuleOrUniformRoot::ExternPrelude => {
2227 ident.span = ident.span.modern();
2228 ident.span.adjust(Mark::root());
2229 }
2230 ModuleOrUniformRoot::CrateRootAndExternPrelude |
2231 ModuleOrUniformRoot::CurrentScope => {
2232 // No adjustments
2233 }
2234 }
2235 let result = self.resolve_ident_in_module_unadjusted_ext(
2236 module, ident, ns, parent_scope, false, record_used, path_span,
2237 );
2238 self.current_module = orig_current_module;
2239 result
2240 }
2241
2242 fn resolve_crate_root(&mut self, ident: Ident) -> Module<'a> {
2243 let mut ctxt = ident.span.ctxt();
2244 let mark = if ident.name == keywords::DollarCrate.name() {
2245 // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
2246 // we don't want to pretend that the `macro_rules!` definition is in the `macro`
2247 // as described in `SyntaxContext::apply_mark`, so we ignore prepended modern marks.
2248 // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!`
2249 // definitions actually produced by `macro` and `macro` definitions produced by
2250 // `macro_rules!`, but at least such configurations are not stable yet.
2251 ctxt = ctxt.modern_and_legacy();
2252 let mut iter = ctxt.marks().into_iter().rev().peekable();
2253 let mut result = None;
2254 // Find the last modern mark from the end if it exists.
2255 while let Some(&(mark, transparency)) = iter.peek() {
2256 if transparency == Transparency::Opaque {
2257 result = Some(mark);
2258 iter.next();
2259 } else {
2260 break;
2261 }
2262 }
2263 // Then find the last legacy mark from the end if it exists.
2264 for (mark, transparency) in iter {
2265 if transparency == Transparency::SemiTransparent {
2266 result = Some(mark);
2267 } else {
2268 break;
2269 }
2270 }
2271 result
2272 } else {
2273 ctxt = ctxt.modern();
2274 ctxt.adjust(Mark::root())
2275 };
2276 let module = match mark {
2277 Some(def) => self.macro_def_scope(def),
2278 None => return self.graph_root,
2279 };
2280 self.get_module(DefId { index: CRATE_DEF_INDEX, ..module.normal_ancestor_id })
2281 }
2282
2283 fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'a>) -> Module<'a> {
2284 let mut module = self.get_module(module.normal_ancestor_id);
2285 while module.span.ctxt().modern() != *ctxt {
2286 let parent = module.parent.unwrap_or_else(|| self.macro_def_scope(ctxt.remove_mark()));
2287 module = self.get_module(parent.normal_ancestor_id);
2288 }
2289 module
2290 }
2291
2292 // AST resolution
2293 //
2294 // We maintain a list of value ribs and type ribs.
2295 //
2296 // Simultaneously, we keep track of the current position in the module
2297 // graph in the `current_module` pointer. When we go to resolve a name in
2298 // the value or type namespaces, we first look through all the ribs and
2299 // then query the module graph. When we resolve a name in the module
2300 // namespace, we can skip all the ribs (since nested modules are not
2301 // allowed within blocks in Rust) and jump straight to the current module
2302 // graph node.
2303 //
2304 // Named implementations are handled separately. When we find a method
2305 // call, we consult the module node to find all of the implementations in
2306 // scope. This information is lazily cached in the module node. We then
2307 // generate a fake "implementation scope" containing all the
2308 // implementations thus found, for compatibility with old resolve pass.
2309
2310 pub fn with_scope<F, T>(&mut self, id: NodeId, f: F) -> T
2311 where F: FnOnce(&mut Resolver) -> T
2312 {
2313 let id = self.definitions.local_def_id(id);
2314 let module = self.module_map.get(&id).cloned(); // clones a reference
2315 if let Some(module) = module {
2316 // Move down in the graph.
2317 let orig_module = replace(&mut self.current_module, module);
2318 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(module)));
2319 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(module)));
2320
2321 self.finalize_current_module_macro_resolutions();
2322 let ret = f(self);
2323
2324 self.current_module = orig_module;
2325 self.ribs[ValueNS].pop();
2326 self.ribs[TypeNS].pop();
2327 ret
2328 } else {
2329 f(self)
2330 }
2331 }
2332
2333 /// Searches the current set of local scopes for labels. Returns the first non-None label that
2334 /// is returned by the given predicate function
2335 ///
2336 /// Stops after meeting a closure.
2337 fn search_label<P, R>(&self, mut ident: Ident, pred: P) -> Option<R>
2338 where P: Fn(&Rib, Ident) -> Option<R>
2339 {
2340 for rib in self.label_ribs.iter().rev() {
2341 match rib.kind {
2342 NormalRibKind => {}
2343 // If an invocation of this macro created `ident`, give up on `ident`
2344 // and switch to `ident`'s source from the macro definition.
2345 MacroDefinition(def) => {
2346 if def == self.macro_def(ident.span.ctxt()) {
2347 ident.span.remove_mark();
2348 }
2349 }
2350 _ => {
2351 // Do not resolve labels across function boundary
2352 return None;
2353 }
2354 }
2355 let r = pred(rib, ident);
2356 if r.is_some() {
2357 return r;
2358 }
2359 }
2360 None
2361 }
2362
2363 fn resolve_adt(&mut self, item: &Item, generics: &Generics) {
2364 self.with_current_self_item(item, |this| {
2365 this.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
2366 let item_def_id = this.definitions.local_def_id(item.id);
2367 this.with_self_rib(Def::SelfTy(None, Some(item_def_id)), |this| {
2368 visit::walk_item(this, item);
2369 });
2370 });
2371 });
2372 }
2373
2374 fn future_proof_import(&mut self, use_tree: &ast::UseTree) {
2375 let segments = &use_tree.prefix.segments;
2376 if !segments.is_empty() {
2377 let ident = segments[0].ident;
2378 if ident.is_path_segment_keyword() || ident.span.rust_2015() {
2379 return;
2380 }
2381
2382 let nss = match use_tree.kind {
2383 ast::UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
2384 _ => &[TypeNS],
2385 };
2386 let report_error = |this: &Self, ns| {
2387 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2388 this.session.span_err(ident.span, &format!("imports cannot refer to {}", what));
2389 };
2390
2391 for &ns in nss {
2392 match self.resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span) {
2393 Some(LexicalScopeBinding::Def(..)) => {
2394 report_error(self, ns);
2395 }
2396 Some(LexicalScopeBinding::Item(binding)) => {
2397 let orig_blacklisted_binding =
2398 mem::replace(&mut self.blacklisted_binding, Some(binding));
2399 if let Some(LexicalScopeBinding::Def(..)) =
2400 self.resolve_ident_in_lexical_scope(ident, ns, None,
2401 use_tree.prefix.span) {
2402 report_error(self, ns);
2403 }
2404 self.blacklisted_binding = orig_blacklisted_binding;
2405 }
2406 None => {}
2407 }
2408 }
2409 } else if let ast::UseTreeKind::Nested(use_trees) = &use_tree.kind {
2410 for (use_tree, _) in use_trees {
2411 self.future_proof_import(use_tree);
2412 }
2413 }
2414 }
2415
2416 fn resolve_item(&mut self, item: &Item) {
2417 let name = item.ident.name;
2418 debug!("(resolving item) resolving {}", name);
2419
2420 match item.node {
2421 ItemKind::Ty(_, ref generics) |
2422 ItemKind::Fn(_, _, ref generics, _) |
2423 ItemKind::Existential(_, ref generics) => {
2424 self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind),
2425 |this| visit::walk_item(this, item));
2426 }
2427
2428 ItemKind::Enum(_, ref generics) |
2429 ItemKind::Struct(_, ref generics) |
2430 ItemKind::Union(_, ref generics) => {
2431 self.resolve_adt(item, generics);
2432 }
2433
2434 ItemKind::Impl(.., ref generics, ref opt_trait_ref, ref self_type, ref impl_items) =>
2435 self.resolve_implementation(generics,
2436 opt_trait_ref,
2437 &self_type,
2438 item.id,
2439 impl_items),
2440
2441 ItemKind::Trait(.., ref generics, ref bounds, ref trait_items) => {
2442 // Create a new rib for the trait-wide type parameters.
2443 self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
2444 let local_def_id = this.definitions.local_def_id(item.id);
2445 this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
2446 this.visit_generics(generics);
2447 walk_list!(this, visit_param_bound, bounds);
2448
2449 for trait_item in trait_items {
2450 let type_parameters = HasTypeParameters(&trait_item.generics,
2451 TraitOrImplItemRibKind);
2452 this.with_type_parameter_rib(type_parameters, |this| {
2453 match trait_item.node {
2454 TraitItemKind::Const(ref ty, ref default) => {
2455 this.visit_ty(ty);
2456
2457 // Only impose the restrictions of
2458 // ConstRibKind for an actual constant
2459 // expression in a provided default.
2460 if let Some(ref expr) = *default{
2461 this.with_constant_rib(|this| {
2462 this.visit_expr(expr);
2463 });
2464 }
2465 }
2466 TraitItemKind::Method(_, _) => {
2467 visit::walk_trait_item(this, trait_item)
2468 }
2469 TraitItemKind::Type(..) => {
2470 visit::walk_trait_item(this, trait_item)
2471 }
2472 TraitItemKind::Macro(_) => {
2473 panic!("unexpanded macro in resolve!")
2474 }
2475 };
2476 });
2477 }
2478 });
2479 });
2480 }
2481
2482 ItemKind::TraitAlias(ref generics, ref bounds) => {
2483 // Create a new rib for the trait-wide type parameters.
2484 self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
2485 let local_def_id = this.definitions.local_def_id(item.id);
2486 this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
2487 this.visit_generics(generics);
2488 walk_list!(this, visit_param_bound, bounds);
2489 });
2490 });
2491 }
2492
2493 ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
2494 self.with_scope(item.id, |this| {
2495 visit::walk_item(this, item);
2496 });
2497 }
2498
2499 ItemKind::Static(ref ty, _, ref expr) |
2500 ItemKind::Const(ref ty, ref expr) => {
2501 self.with_item_rib(|this| {
2502 this.visit_ty(ty);
2503 this.with_constant_rib(|this| {
2504 this.visit_expr(expr);
2505 });
2506 });
2507 }
2508
2509 ItemKind::Use(ref use_tree) => {
2510 self.future_proof_import(use_tree);
2511 }
2512
2513 ItemKind::ExternCrate(..) |
2514 ItemKind::MacroDef(..) | ItemKind::GlobalAsm(..) => {
2515 // do nothing, these are just around to be encoded
2516 }
2517
2518 ItemKind::Mac(_) => panic!("unexpanded macro in resolve!"),
2519 }
2520 }
2521
2522 fn with_type_parameter_rib<'b, F>(&'b mut self, type_parameters: TypeParameters<'a, 'b>, f: F)
2523 where F: FnOnce(&mut Resolver)
2524 {
2525 match type_parameters {
2526 HasTypeParameters(generics, rib_kind) => {
2527 let mut function_type_rib = Rib::new(rib_kind);
2528 let mut seen_bindings = FxHashMap::default();
2529 for param in &generics.params {
2530 match param.kind {
2531 GenericParamKind::Lifetime { .. } => {}
2532 GenericParamKind::Type { .. } => {
2533 let ident = param.ident.modern();
2534 debug!("with_type_parameter_rib: {}", param.id);
2535
2536 if seen_bindings.contains_key(&ident) {
2537 let span = seen_bindings.get(&ident).unwrap();
2538 let err = ResolutionError::NameAlreadyUsedInTypeParameterList(
2539 ident.name,
2540 span,
2541 );
2542 resolve_error(self, param.ident.span, err);
2543 }
2544 seen_bindings.entry(ident).or_insert(param.ident.span);
2545
2546 // Plain insert (no renaming).
2547 let def = Def::TyParam(self.definitions.local_def_id(param.id));
2548 function_type_rib.bindings.insert(ident, def);
2549 self.record_def(param.id, PathResolution::new(def));
2550 }
2551 }
2552 }
2553 self.ribs[TypeNS].push(function_type_rib);
2554 }
2555
2556 NoTypeParameters => {
2557 // Nothing to do.
2558 }
2559 }
2560
2561 f(self);
2562
2563 if let HasTypeParameters(..) = type_parameters {
2564 self.ribs[TypeNS].pop();
2565 }
2566 }
2567
2568 fn with_label_rib<F>(&mut self, f: F)
2569 where F: FnOnce(&mut Resolver)
2570 {
2571 self.label_ribs.push(Rib::new(NormalRibKind));
2572 f(self);
2573 self.label_ribs.pop();
2574 }
2575
2576 fn with_item_rib<F>(&mut self, f: F)
2577 where F: FnOnce(&mut Resolver)
2578 {
2579 self.ribs[ValueNS].push(Rib::new(ItemRibKind));
2580 self.ribs[TypeNS].push(Rib::new(ItemRibKind));
2581 f(self);
2582 self.ribs[TypeNS].pop();
2583 self.ribs[ValueNS].pop();
2584 }
2585
2586 fn with_constant_rib<F>(&mut self, f: F)
2587 where F: FnOnce(&mut Resolver)
2588 {
2589 self.ribs[ValueNS].push(Rib::new(ConstantItemRibKind));
2590 self.label_ribs.push(Rib::new(ConstantItemRibKind));
2591 f(self);
2592 self.label_ribs.pop();
2593 self.ribs[ValueNS].pop();
2594 }
2595
2596 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2597 where F: FnOnce(&mut Resolver) -> T
2598 {
2599 // Handle nested impls (inside fn bodies)
2600 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2601 let result = f(self);
2602 self.current_self_type = previous_value;
2603 result
2604 }
2605
2606 fn with_current_self_item<T, F>(&mut self, self_item: &Item, f: F) -> T
2607 where F: FnOnce(&mut Resolver) -> T
2608 {
2609 let previous_value = replace(&mut self.current_self_item, Some(self_item.id));
2610 let result = f(self);
2611 self.current_self_item = previous_value;
2612 result
2613 }
2614
2615 /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`)
2616 fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
2617 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2618 {
2619 let mut new_val = None;
2620 let mut new_id = None;
2621 if let Some(trait_ref) = opt_trait_ref {
2622 let path: Vec<_> = Segment::from_path(&trait_ref.path);
2623 let def = self.smart_resolve_path_fragment(
2624 trait_ref.ref_id,
2625 None,
2626 &path,
2627 trait_ref.path.span,
2628 PathSource::Trait(AliasPossibility::No),
2629 CrateLint::SimplePath(trait_ref.ref_id),
2630 ).base_def();
2631 if def != Def::Err {
2632 new_id = Some(def.def_id());
2633 let span = trait_ref.path.span;
2634 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
2635 self.resolve_path_without_parent_scope(
2636 &path,
2637 Some(TypeNS),
2638 false,
2639 span,
2640 CrateLint::SimplePath(trait_ref.ref_id),
2641 )
2642 {
2643 new_val = Some((module, trait_ref.clone()));
2644 }
2645 }
2646 }
2647 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2648 let result = f(self, new_id);
2649 self.current_trait_ref = original_trait_ref;
2650 result
2651 }
2652
2653 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2654 where F: FnOnce(&mut Resolver)
2655 {
2656 let mut self_type_rib = Rib::new(NormalRibKind);
2657
2658 // plain insert (no renaming, types are not currently hygienic....)
2659 self_type_rib.bindings.insert(keywords::SelfUpper.ident(), self_def);
2660 self.ribs[TypeNS].push(self_type_rib);
2661 f(self);
2662 self.ribs[TypeNS].pop();
2663 }
2664
2665 fn with_self_struct_ctor_rib<F>(&mut self, impl_id: DefId, f: F)
2666 where F: FnOnce(&mut Resolver)
2667 {
2668 let self_def = Def::SelfCtor(impl_id);
2669 let mut self_type_rib = Rib::new(NormalRibKind);
2670 self_type_rib.bindings.insert(keywords::SelfUpper.ident(), self_def);
2671 self.ribs[ValueNS].push(self_type_rib);
2672 f(self);
2673 self.ribs[ValueNS].pop();
2674 }
2675
2676 fn resolve_implementation(&mut self,
2677 generics: &Generics,
2678 opt_trait_reference: &Option<TraitRef>,
2679 self_type: &Ty,
2680 item_id: NodeId,
2681 impl_items: &[ImplItem]) {
2682 // If applicable, create a rib for the type parameters.
2683 self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
2684 // Dummy self type for better errors if `Self` is used in the trait path.
2685 this.with_self_rib(Def::SelfTy(None, None), |this| {
2686 // Resolve the trait reference, if necessary.
2687 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2688 let item_def_id = this.definitions.local_def_id(item_id);
2689 this.with_self_rib(Def::SelfTy(trait_id, Some(item_def_id)), |this| {
2690 if let Some(trait_ref) = opt_trait_reference.as_ref() {
2691 // Resolve type arguments in the trait path.
2692 visit::walk_trait_ref(this, trait_ref);
2693 }
2694 // Resolve the self type.
2695 this.visit_ty(self_type);
2696 // Resolve the type parameters.
2697 this.visit_generics(generics);
2698 // Resolve the items within the impl.
2699 this.with_current_self_type(self_type, |this| {
2700 this.with_self_struct_ctor_rib(item_def_id, |this| {
2701 for impl_item in impl_items {
2702 this.resolve_visibility(&impl_item.vis);
2703
2704 // We also need a new scope for the impl item type parameters.
2705 let type_parameters = HasTypeParameters(&impl_item.generics,
2706 TraitOrImplItemRibKind);
2707 this.with_type_parameter_rib(type_parameters, |this| {
2708 use self::ResolutionError::*;
2709 match impl_item.node {
2710 ImplItemKind::Const(..) => {
2711 // If this is a trait impl, ensure the const
2712 // exists in trait
2713 this.check_trait_item(impl_item.ident,
2714 ValueNS,
2715 impl_item.span,
2716 |n, s| ConstNotMemberOfTrait(n, s));
2717 this.with_constant_rib(|this|
2718 visit::walk_impl_item(this, impl_item)
2719 );
2720 }
2721 ImplItemKind::Method(..) => {
2722 // If this is a trait impl, ensure the method
2723 // exists in trait
2724 this.check_trait_item(impl_item.ident,
2725 ValueNS,
2726 impl_item.span,
2727 |n, s| MethodNotMemberOfTrait(n, s));
2728
2729 visit::walk_impl_item(this, impl_item);
2730 }
2731 ImplItemKind::Type(ref ty) => {
2732 // If this is a trait impl, ensure the type
2733 // exists in trait
2734 this.check_trait_item(impl_item.ident,
2735 TypeNS,
2736 impl_item.span,
2737 |n, s| TypeNotMemberOfTrait(n, s));
2738
2739 this.visit_ty(ty);
2740 }
2741 ImplItemKind::Existential(ref bounds) => {
2742 // If this is a trait impl, ensure the type
2743 // exists in trait
2744 this.check_trait_item(impl_item.ident,
2745 TypeNS,
2746 impl_item.span,
2747 |n, s| TypeNotMemberOfTrait(n, s));
2748
2749 for bound in bounds {
2750 this.visit_param_bound(bound);
2751 }
2752 }
2753 ImplItemKind::Macro(_) =>
2754 panic!("unexpanded macro in resolve!"),
2755 }
2756 });
2757 }
2758 });
2759 });
2760 });
2761 });
2762 });
2763 });
2764 }
2765
2766 fn check_trait_item<F>(&mut self, ident: Ident, ns: Namespace, span: Span, err: F)
2767 where F: FnOnce(Name, &str) -> ResolutionError
2768 {
2769 // If there is a TraitRef in scope for an impl, then the method must be in the
2770 // trait.
2771 if let Some((module, _)) = self.current_trait_ref {
2772 if self.resolve_ident_in_module(
2773 ModuleOrUniformRoot::Module(module),
2774 ident,
2775 ns,
2776 None,
2777 false,
2778 span,
2779 ).is_err() {
2780 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
2781 resolve_error(self, span, err(ident.name, &path_names_to_string(path)));
2782 }
2783 }
2784 }
2785
2786 fn resolve_local(&mut self, local: &Local) {
2787 // Resolve the type.
2788 walk_list!(self, visit_ty, &local.ty);
2789
2790 // Resolve the initializer.
2791 walk_list!(self, visit_expr, &local.init);
2792
2793 // Resolve the pattern.
2794 self.resolve_pattern(&local.pat, PatternSource::Let, &mut FxHashMap::default());
2795 }
2796
2797 // build a map from pattern identifiers to binding-info's.
2798 // this is done hygienically. This could arise for a macro
2799 // that expands into an or-pattern where one 'x' was from the
2800 // user and one 'x' came from the macro.
2801 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2802 let mut binding_map = FxHashMap::default();
2803
2804 pat.walk(&mut |pat| {
2805 if let PatKind::Ident(binding_mode, ident, ref sub_pat) = pat.node {
2806 if sub_pat.is_some() || match self.def_map.get(&pat.id).map(|res| res.base_def()) {
2807 Some(Def::Local(..)) => true,
2808 _ => false,
2809 } {
2810 let binding_info = BindingInfo { span: ident.span, binding_mode: binding_mode };
2811 binding_map.insert(ident, binding_info);
2812 }
2813 }
2814 true
2815 });
2816
2817 binding_map
2818 }
2819
2820 // check that all of the arms in an or-pattern have exactly the
2821 // same set of bindings, with the same binding modes for each.
2822 fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) {
2823 if pats.is_empty() {
2824 return;
2825 }
2826
2827 let mut missing_vars = FxHashMap::default();
2828 let mut inconsistent_vars = FxHashMap::default();
2829 for (i, p) in pats.iter().enumerate() {
2830 let map_i = self.binding_mode_map(&p);
2831
2832 for (j, q) in pats.iter().enumerate() {
2833 if i == j {
2834 continue;
2835 }
2836
2837 let map_j = self.binding_mode_map(&q);
2838 for (&key, &binding_i) in &map_i {
2839 if map_j.is_empty() { // Account for missing bindings when
2840 let binding_error = missing_vars // map_j has none.
2841 .entry(key.name)
2842 .or_insert(BindingError {
2843 name: key.name,
2844 origin: BTreeSet::new(),
2845 target: BTreeSet::new(),
2846 });
2847 binding_error.origin.insert(binding_i.span);
2848 binding_error.target.insert(q.span);
2849 }
2850 for (&key_j, &binding_j) in &map_j {
2851 match map_i.get(&key_j) {
2852 None => { // missing binding
2853 let binding_error = missing_vars
2854 .entry(key_j.name)
2855 .or_insert(BindingError {
2856 name: key_j.name,
2857 origin: BTreeSet::new(),
2858 target: BTreeSet::new(),
2859 });
2860 binding_error.origin.insert(binding_j.span);
2861 binding_error.target.insert(p.span);
2862 }
2863 Some(binding_i) => { // check consistent binding
2864 if binding_i.binding_mode != binding_j.binding_mode {
2865 inconsistent_vars
2866 .entry(key.name)
2867 .or_insert((binding_j.span, binding_i.span));
2868 }
2869 }
2870 }
2871 }
2872 }
2873 }
2874 }
2875 let mut missing_vars = missing_vars.iter().collect::<Vec<_>>();
2876 missing_vars.sort();
2877 for (_, v) in missing_vars {
2878 resolve_error(self,
2879 *v.origin.iter().next().unwrap(),
2880 ResolutionError::VariableNotBoundInPattern(v));
2881 }
2882 let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
2883 inconsistent_vars.sort();
2884 for (name, v) in inconsistent_vars {
2885 resolve_error(self, v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
2886 }
2887 }
2888
2889 fn resolve_arm(&mut self, arm: &Arm) {
2890 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
2891
2892 let mut bindings_list = FxHashMap::default();
2893 for pattern in &arm.pats {
2894 self.resolve_pattern(&pattern, PatternSource::Match, &mut bindings_list);
2895 }
2896
2897 // This has to happen *after* we determine which pat_idents are variants.
2898 self.check_consistent_bindings(&arm.pats);
2899
2900 if let Some(ast::Guard::If(ref expr)) = arm.guard {
2901 self.visit_expr(expr)
2902 }
2903 self.visit_expr(&arm.body);
2904
2905 self.ribs[ValueNS].pop();
2906 }
2907
2908 fn resolve_block(&mut self, block: &Block) {
2909 debug!("(resolving block) entering block");
2910 // Move down in the graph, if there's an anonymous module rooted here.
2911 let orig_module = self.current_module;
2912 let anonymous_module = self.block_map.get(&block.id).cloned(); // clones a reference
2913
2914 let mut num_macro_definition_ribs = 0;
2915 if let Some(anonymous_module) = anonymous_module {
2916 debug!("(resolving block) found anonymous module, moving down");
2917 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
2918 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
2919 self.current_module = anonymous_module;
2920 self.finalize_current_module_macro_resolutions();
2921 } else {
2922 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
2923 }
2924
2925 // Descend into the block.
2926 for stmt in &block.stmts {
2927 if let ast::StmtKind::Item(ref item) = stmt.node {
2928 if let ast::ItemKind::MacroDef(..) = item.node {
2929 num_macro_definition_ribs += 1;
2930 let def = self.definitions.local_def_id(item.id);
2931 self.ribs[ValueNS].push(Rib::new(MacroDefinition(def)));
2932 self.label_ribs.push(Rib::new(MacroDefinition(def)));
2933 }
2934 }
2935
2936 self.visit_stmt(stmt);
2937 }
2938
2939 // Move back up.
2940 self.current_module = orig_module;
2941 for _ in 0 .. num_macro_definition_ribs {
2942 self.ribs[ValueNS].pop();
2943 self.label_ribs.pop();
2944 }
2945 self.ribs[ValueNS].pop();
2946 if anonymous_module.is_some() {
2947 self.ribs[TypeNS].pop();
2948 }
2949 debug!("(resolving block) leaving block");
2950 }
2951
2952 fn fresh_binding(&mut self,
2953 ident: Ident,
2954 pat_id: NodeId,
2955 outer_pat_id: NodeId,
2956 pat_src: PatternSource,
2957 bindings: &mut FxHashMap<Ident, NodeId>)
2958 -> PathResolution {
2959 // Add the binding to the local ribs, if it
2960 // doesn't already exist in the bindings map. (We
2961 // must not add it if it's in the bindings map
2962 // because that breaks the assumptions later
2963 // passes make about or-patterns.)
2964 let ident = ident.modern_and_legacy();
2965 let mut def = Def::Local(pat_id);
2966 match bindings.get(&ident).cloned() {
2967 Some(id) if id == outer_pat_id => {
2968 // `Variant(a, a)`, error
2969 resolve_error(
2970 self,
2971 ident.span,
2972 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2973 &ident.as_str())
2974 );
2975 }
2976 Some(..) if pat_src == PatternSource::FnParam => {
2977 // `fn f(a: u8, a: u8)`, error
2978 resolve_error(
2979 self,
2980 ident.span,
2981 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2982 &ident.as_str())
2983 );
2984 }
2985 Some(..) if pat_src == PatternSource::Match ||
2986 pat_src == PatternSource::IfLet ||
2987 pat_src == PatternSource::WhileLet => {
2988 // `Variant1(a) | Variant2(a)`, ok
2989 // Reuse definition from the first `a`.
2990 def = self.ribs[ValueNS].last_mut().unwrap().bindings[&ident];
2991 }
2992 Some(..) => {
2993 span_bug!(ident.span, "two bindings with the same name from \
2994 unexpected pattern source {:?}", pat_src);
2995 }
2996 None => {
2997 // A completely fresh binding, add to the lists if it's valid.
2998 if ident.name != keywords::Invalid.name() {
2999 bindings.insert(ident, outer_pat_id);
3000 self.ribs[ValueNS].last_mut().unwrap().bindings.insert(ident, def);
3001 }
3002 }
3003 }
3004
3005 PathResolution::new(def)
3006 }
3007
3008 fn resolve_pattern(&mut self,
3009 pat: &Pat,
3010 pat_src: PatternSource,
3011 // Maps idents to the node ID for the
3012 // outermost pattern that binds them.
3013 bindings: &mut FxHashMap<Ident, NodeId>) {
3014 // Visit all direct subpatterns of this pattern.
3015 let outer_pat_id = pat.id;
3016 pat.walk(&mut |pat| {
3017 debug!("resolve_pattern pat={:?} node={:?}", pat, pat.node);
3018 match pat.node {
3019 PatKind::Ident(bmode, ident, ref opt_pat) => {
3020 // First try to resolve the identifier as some existing
3021 // entity, then fall back to a fresh binding.
3022 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS,
3023 None, pat.span)
3024 .and_then(LexicalScopeBinding::item);
3025 let resolution = binding.map(NameBinding::def).and_then(|def| {
3026 let is_syntactic_ambiguity = opt_pat.is_none() &&
3027 bmode == BindingMode::ByValue(Mutability::Immutable);
3028 match def {
3029 Def::StructCtor(_, CtorKind::Const) |
3030 Def::VariantCtor(_, CtorKind::Const) |
3031 Def::Const(..) if is_syntactic_ambiguity => {
3032 // Disambiguate in favor of a unit struct/variant
3033 // or constant pattern.
3034 self.record_use(ident, ValueNS, binding.unwrap(), false);
3035 Some(PathResolution::new(def))
3036 }
3037 Def::StructCtor(..) | Def::VariantCtor(..) |
3038 Def::Const(..) | Def::Static(..) => {
3039 // This is unambiguously a fresh binding, either syntactically
3040 // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
3041 // to something unusable as a pattern (e.g., constructor function),
3042 // but we still conservatively report an error, see
3043 // issues/33118#issuecomment-233962221 for one reason why.
3044 resolve_error(
3045 self,
3046 ident.span,
3047 ResolutionError::BindingShadowsSomethingUnacceptable(
3048 pat_src.descr(), ident.name, binding.unwrap())
3049 );
3050 None
3051 }
3052 Def::Fn(..) | Def::Err => {
3053 // These entities are explicitly allowed
3054 // to be shadowed by fresh bindings.
3055 None
3056 }
3057 def => {
3058 span_bug!(ident.span, "unexpected definition for an \
3059 identifier in pattern: {:?}", def);
3060 }
3061 }
3062 }).unwrap_or_else(|| {
3063 self.fresh_binding(ident, pat.id, outer_pat_id, pat_src, bindings)
3064 });
3065
3066 self.record_def(pat.id, resolution);
3067 }
3068
3069 PatKind::TupleStruct(ref path, ..) => {
3070 self.smart_resolve_path(pat.id, None, path, PathSource::TupleStruct);
3071 }
3072
3073 PatKind::Path(ref qself, ref path) => {
3074 self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
3075 }
3076
3077 PatKind::Struct(ref path, ..) => {
3078 self.smart_resolve_path(pat.id, None, path, PathSource::Struct);
3079 }
3080
3081 _ => {}
3082 }
3083 true
3084 });
3085
3086 visit::walk_pat(self, pat);
3087 }
3088
3089 // High-level and context dependent path resolution routine.
3090 // Resolves the path and records the resolution into definition map.
3091 // If resolution fails tries several techniques to find likely
3092 // resolution candidates, suggest imports or other help, and report
3093 // errors in user friendly way.
3094 fn smart_resolve_path(&mut self,
3095 id: NodeId,
3096 qself: Option<&QSelf>,
3097 path: &Path,
3098 source: PathSource)
3099 -> PathResolution {
3100 self.smart_resolve_path_with_crate_lint(id, qself, path, source, CrateLint::SimplePath(id))
3101 }
3102
3103 /// A variant of `smart_resolve_path` where you also specify extra
3104 /// information about where the path came from; this extra info is
3105 /// sometimes needed for the lint that recommends rewriting
3106 /// absolute paths to `crate`, so that it knows how to frame the
3107 /// suggestion. If you are just resolving a path like `foo::bar`
3108 /// that appears...somewhere, though, then you just want
3109 /// `CrateLint::SimplePath`, which is what `smart_resolve_path`
3110 /// already provides.
3111 fn smart_resolve_path_with_crate_lint(
3112 &mut self,
3113 id: NodeId,
3114 qself: Option<&QSelf>,
3115 path: &Path,
3116 source: PathSource,
3117 crate_lint: CrateLint
3118 ) -> PathResolution {
3119 self.smart_resolve_path_fragment(
3120 id,
3121 qself,
3122 &Segment::from_path(path),
3123 path.span,
3124 source,
3125 crate_lint,
3126 )
3127 }
3128
3129 fn smart_resolve_path_fragment(&mut self,
3130 id: NodeId,
3131 qself: Option<&QSelf>,
3132 path: &[Segment],
3133 span: Span,
3134 source: PathSource,
3135 crate_lint: CrateLint)
3136 -> PathResolution {
3137 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
3138 let ns = source.namespace();
3139 let is_expected = &|def| source.is_expected(def);
3140 let is_enum_variant = &|def| if let Def::Variant(..) = def { true } else { false };
3141
3142 // Base error is amended with one short label and possibly some longer helps/notes.
3143 let report_errors = |this: &mut Self, def: Option<Def>| {
3144 // Make the base error.
3145 let expected = source.descr_expected();
3146 let path_str = Segment::names_to_string(path);
3147 let item_str = path.last().unwrap().ident;
3148 let code = source.error_code(def.is_some());
3149 let (base_msg, fallback_label, base_span) = if let Some(def) = def {
3150 (format!("expected {}, found {} `{}`", expected, def.kind_name(), path_str),
3151 format!("not a {}", expected),
3152 span)
3153 } else {
3154 let item_span = path.last().unwrap().ident.span;
3155 let (mod_prefix, mod_str) = if path.len() == 1 {
3156 (String::new(), "this scope".to_string())
3157 } else if path.len() == 2 && path[0].ident.name == keywords::PathRoot.name() {
3158 (String::new(), "the crate root".to_string())
3159 } else {
3160 let mod_path = &path[..path.len() - 1];
3161 let mod_prefix = match this.resolve_path_without_parent_scope(
3162 mod_path, Some(TypeNS), false, span, CrateLint::No
3163 ) {
3164 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
3165 module.def(),
3166 _ => None,
3167 }.map_or(String::new(), |def| format!("{} ", def.kind_name()));
3168 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)))
3169 };
3170 (format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str),
3171 format!("not found in {}", mod_str),
3172 item_span)
3173 };
3174
3175 let code = DiagnosticId::Error(code.into());
3176 let mut err = this.session.struct_span_err_with_code(base_span, &base_msg, code);
3177
3178 // Emit help message for fake-self from other languages like `this`(javascript)
3179 if ["this", "my"].contains(&&*item_str.as_str())
3180 && this.self_value_is_available(path[0].ident.span, span) {
3181 err.span_suggestion_with_applicability(
3182 span,
3183 "did you mean",
3184 "self".to_string(),
3185 Applicability::MaybeIncorrect,
3186 );
3187 }
3188
3189 // Emit special messages for unresolved `Self` and `self`.
3190 if is_self_type(path, ns) {
3191 __diagnostic_used!(E0411);
3192 err.code(DiagnosticId::Error("E0411".into()));
3193 err.span_label(span, format!("`Self` is only available in impls, traits, \
3194 and type definitions"));
3195 return (err, Vec::new());
3196 }
3197 if is_self_value(path, ns) {
3198 debug!("smart_resolve_path_fragment E0424 source:{:?}", source);
3199
3200 __diagnostic_used!(E0424);
3201 err.code(DiagnosticId::Error("E0424".into()));
3202 err.span_label(span, match source {
3203 PathSource::Pat => {
3204 format!("`self` value is a keyword \
3205 and may not be bound to \
3206 variables or shadowed")
3207 }
3208 _ => {
3209 format!("`self` value is a keyword \
3210 only available in methods \
3211 with `self` parameter")
3212 }
3213 });
3214 return (err, Vec::new());
3215 }
3216
3217 // Try to lookup the name in more relaxed fashion for better error reporting.
3218 let ident = path.last().unwrap().ident;
3219 let candidates = this.lookup_import_candidates(ident, ns, is_expected);
3220 if candidates.is_empty() && is_expected(Def::Enum(DefId::local(CRATE_DEF_INDEX))) {
3221 let enum_candidates =
3222 this.lookup_import_candidates(ident, ns, is_enum_variant);
3223 let mut enum_candidates = enum_candidates.iter()
3224 .map(|suggestion| {
3225 import_candidate_to_enum_paths(&suggestion)
3226 }).collect::<Vec<_>>();
3227 enum_candidates.sort();
3228
3229 if !enum_candidates.is_empty() {
3230 // contextualize for E0412 "cannot find type", but don't belabor the point
3231 // (that it's a variant) for E0573 "expected type, found variant"
3232 let preamble = if def.is_none() {
3233 let others = match enum_candidates.len() {
3234 1 => String::new(),
3235 2 => " and 1 other".to_owned(),
3236 n => format!(" and {} others", n)
3237 };
3238 format!("there is an enum variant `{}`{}; ",
3239 enum_candidates[0].0, others)
3240 } else {
3241 String::new()
3242 };
3243 let msg = format!("{}try using the variant's enum", preamble);
3244
3245 err.span_suggestions_with_applicability(
3246 span,
3247 &msg,
3248 enum_candidates.into_iter()
3249 .map(|(_variant_path, enum_ty_path)| enum_ty_path)
3250 // variants reëxported in prelude doesn't mean `prelude::v1` is the
3251 // type name! FIXME: is there a more principled way to do this that
3252 // would work for other reëxports?
3253 .filter(|enum_ty_path| enum_ty_path != "std::prelude::v1")
3254 // also say `Option` rather than `std::prelude::v1::Option`
3255 .map(|enum_ty_path| {
3256 // FIXME #56861: DRYer prelude filtering
3257 enum_ty_path.trim_start_matches("std::prelude::v1::").to_owned()
3258 }),
3259 Applicability::MachineApplicable,
3260 );
3261 }
3262 }
3263 if path.len() == 1 && this.self_type_is_available(span) {
3264 if let Some(candidate) = this.lookup_assoc_candidate(ident, ns, is_expected) {
3265 let self_is_available = this.self_value_is_available(path[0].ident.span, span);
3266 match candidate {
3267 AssocSuggestion::Field => {
3268 err.span_suggestion_with_applicability(
3269 span,
3270 "try",
3271 format!("self.{}", path_str),
3272 Applicability::MachineApplicable,
3273 );
3274 if !self_is_available {
3275 err.span_label(span, format!("`self` value is a keyword \
3276 only available in \
3277 methods with `self` parameter"));
3278 }
3279 }
3280 AssocSuggestion::MethodWithSelf if self_is_available => {
3281 err.span_suggestion_with_applicability(
3282 span,
3283 "try",
3284 format!("self.{}", path_str),
3285 Applicability::MachineApplicable,
3286 );
3287 }
3288 AssocSuggestion::MethodWithSelf | AssocSuggestion::AssocItem => {
3289 err.span_suggestion_with_applicability(
3290 span,
3291 "try",
3292 format!("Self::{}", path_str),
3293 Applicability::MachineApplicable,
3294 );
3295 }
3296 }
3297 return (err, candidates);
3298 }
3299 }
3300
3301 let mut levenshtein_worked = false;
3302
3303 // Try Levenshtein algorithm.
3304 let suggestion = this.lookup_typo_candidate(path, ns, is_expected, span);
3305 if let Some(suggestion) = suggestion {
3306 let msg = format!(
3307 "{} {} with a similar name exists",
3308 suggestion.article, suggestion.kind
3309 );
3310 err.span_suggestion_with_applicability(
3311 ident_span,
3312 &msg,
3313 suggestion.candidate.to_string(),
3314 Applicability::MaybeIncorrect,
3315 );
3316
3317 levenshtein_worked = true;
3318 }
3319
3320 // Try context dependent help if relaxed lookup didn't work.
3321 if let Some(def) = def {
3322 match (def, source) {
3323 (Def::Macro(..), _) => {
3324 err.span_label(span, format!("did you mean `{}!(...)`?", path_str));
3325 return (err, candidates);
3326 }
3327 (Def::TyAlias(..), PathSource::Trait(_)) => {
3328 err.span_label(span, "type aliases cannot be used as traits");
3329 if nightly_options::is_nightly_build() {
3330 err.note("did you mean to use a trait alias?");
3331 }
3332 return (err, candidates);
3333 }
3334 (Def::Mod(..), PathSource::Expr(Some(parent))) => match parent.node {
3335 ExprKind::Field(_, ident) => {
3336 err.span_label(parent.span, format!("did you mean `{}::{}`?",
3337 path_str, ident));
3338 return (err, candidates);
3339 }
3340 ExprKind::MethodCall(ref segment, ..) => {
3341 err.span_label(parent.span, format!("did you mean `{}::{}(...)`?",
3342 path_str, segment.ident));
3343 return (err, candidates);
3344 }
3345 _ => {}
3346 },
3347 (Def::Enum(..), PathSource::TupleStruct)
3348 | (Def::Enum(..), PathSource::Expr(..)) => {
3349 if let Some(variants) = this.collect_enum_variants(def) {
3350 err.note(&format!("did you mean to use one \
3351 of the following variants?\n{}",
3352 variants.iter()
3353 .map(|suggestion| path_names_to_string(suggestion))
3354 .map(|suggestion| format!("- `{}`", suggestion))
3355 .collect::<Vec<_>>()
3356 .join("\n")));
3357
3358 } else {
3359 err.note("did you mean to use one of the enum's variants?");
3360 }
3361 return (err, candidates);
3362 },
3363 (Def::Struct(def_id), _) if ns == ValueNS => {
3364 if let Some((ctor_def, ctor_vis))
3365 = this.struct_constructors.get(&def_id).cloned() {
3366 let accessible_ctor = this.is_accessible(ctor_vis);
3367 if is_expected(ctor_def) && !accessible_ctor {
3368 err.span_label(span, format!("constructor is not visible \
3369 here due to private fields"));
3370 }
3371 } else {
3372 // HACK(estebank): find a better way to figure out that this was a
3373 // parser issue where a struct literal is being used on an expression
3374 // where a brace being opened means a block is being started. Look
3375 // ahead for the next text to see if `span` is followed by a `{`.
3376 let sm = this.session.source_map();
3377 let mut sp = span;
3378 loop {
3379 sp = sm.next_point(sp);
3380 match sm.span_to_snippet(sp) {
3381 Ok(ref snippet) => {
3382 if snippet.chars().any(|c| { !c.is_whitespace() }) {
3383 break;
3384 }
3385 }
3386 _ => break,
3387 }
3388 }
3389 let followed_by_brace = match sm.span_to_snippet(sp) {
3390 Ok(ref snippet) if snippet == "{" => true,
3391 _ => false,
3392 };
3393 match source {
3394 PathSource::Expr(Some(parent)) => {
3395 match parent.node {
3396 ExprKind::MethodCall(ref path_assignment, _) => {
3397 err.span_suggestion_with_applicability(
3398 sm.start_point(parent.span)
3399 .to(path_assignment.ident.span),
3400 "use `::` to access an associated function",
3401 format!("{}::{}",
3402 path_str,
3403 path_assignment.ident),
3404 Applicability::MaybeIncorrect
3405 );
3406 return (err, candidates);
3407 },
3408 _ => {
3409 err.span_label(
3410 span,
3411 format!("did you mean `{} {{ /* fields */ }}`?",
3412 path_str),
3413 );
3414 return (err, candidates);
3415 },
3416 }
3417 },
3418 PathSource::Expr(None) if followed_by_brace == true => {
3419 err.span_label(
3420 span,
3421 format!("did you mean `({} {{ /* fields */ }})`?",
3422 path_str),
3423 );
3424 return (err, candidates);
3425 },
3426 _ => {
3427 err.span_label(
3428 span,
3429 format!("did you mean `{} {{ /* fields */ }}`?",
3430 path_str),
3431 );
3432 return (err, candidates);
3433 },
3434 }
3435 }
3436 return (err, candidates);
3437 }
3438 (Def::Union(..), _) |
3439 (Def::Variant(..), _) |
3440 (Def::VariantCtor(_, CtorKind::Fictive), _) if ns == ValueNS => {
3441 err.span_label(span, format!("did you mean `{} {{ /* fields */ }}`?",
3442 path_str));
3443 return (err, candidates);
3444 }
3445 (Def::SelfTy(..), _) if ns == ValueNS => {
3446 err.span_label(span, fallback_label);
3447 err.note("can't use `Self` as a constructor, you must use the \
3448 implemented struct");
3449 return (err, candidates);
3450 }
3451 (Def::TyAlias(_), _) | (Def::AssociatedTy(..), _) if ns == ValueNS => {
3452 err.note("can't use a type alias as a constructor");
3453 return (err, candidates);
3454 }
3455 _ => {}
3456 }
3457 }
3458
3459 // Fallback label.
3460 if !levenshtein_worked {
3461 err.span_label(base_span, fallback_label);
3462 this.type_ascription_suggestion(&mut err, base_span);
3463 }
3464 (err, candidates)
3465 };
3466 let report_errors = |this: &mut Self, def: Option<Def>| {
3467 let (err, candidates) = report_errors(this, def);
3468 let def_id = this.current_module.normal_ancestor_id;
3469 let node_id = this.definitions.as_local_node_id(def_id).unwrap();
3470 let better = def.is_some();
3471 this.use_injections.push(UseError { err, candidates, node_id, better });
3472 err_path_resolution()
3473 };
3474
3475 let resolution = match self.resolve_qpath_anywhere(
3476 id,
3477 qself,
3478 path,
3479 ns,
3480 span,
3481 source.defer_to_typeck(),
3482 source.global_by_default(),
3483 crate_lint,
3484 ) {
3485 Some(resolution) if resolution.unresolved_segments() == 0 => {
3486 if is_expected(resolution.base_def()) || resolution.base_def() == Def::Err {
3487 resolution
3488 } else {
3489 // Add a temporary hack to smooth the transition to new struct ctor
3490 // visibility rules. See #38932 for more details.
3491 let mut res = None;
3492 if let Def::Struct(def_id) = resolution.base_def() {
3493 if let Some((ctor_def, ctor_vis))
3494 = self.struct_constructors.get(&def_id).cloned() {
3495 if is_expected(ctor_def) && self.is_accessible(ctor_vis) {
3496 let lint = lint::builtin::LEGACY_CONSTRUCTOR_VISIBILITY;
3497 self.session.buffer_lint(lint, id, span,
3498 "private struct constructors are not usable through \
3499 re-exports in outer modules",
3500 );
3501 res = Some(PathResolution::new(ctor_def));
3502 }
3503 }
3504 }
3505
3506 res.unwrap_or_else(|| report_errors(self, Some(resolution.base_def())))
3507 }
3508 }
3509 Some(resolution) if source.defer_to_typeck() => {
3510 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
3511 // or `<T>::A::B`. If `B` should be resolved in value namespace then
3512 // it needs to be added to the trait map.
3513 if ns == ValueNS {
3514 let item_name = path.last().unwrap().ident;
3515 let traits = self.get_traits_containing_item(item_name, ns);
3516 self.trait_map.insert(id, traits);
3517 }
3518 resolution
3519 }
3520 _ => report_errors(self, None)
3521 };
3522
3523 if let PathSource::TraitItem(..) = source {} else {
3524 // Avoid recording definition of `A::B` in `<T as A>::B::C`.
3525 self.record_def(id, resolution);
3526 }
3527 resolution
3528 }
3529
3530 fn type_ascription_suggestion(&self,
3531 err: &mut DiagnosticBuilder,
3532 base_span: Span) {
3533 debug!("type_ascription_suggetion {:?}", base_span);
3534 let cm = self.session.source_map();
3535 debug!("self.current_type_ascription {:?}", self.current_type_ascription);
3536 if let Some(sp) = self.current_type_ascription.last() {
3537 let mut sp = *sp;
3538 loop { // try to find the `:`, bail on first non-':'/non-whitespace
3539 sp = cm.next_point(sp);
3540 if let Ok(snippet) = cm.span_to_snippet(sp.to(cm.next_point(sp))) {
3541 debug!("snippet {:?}", snippet);
3542 let line_sp = cm.lookup_char_pos(sp.hi()).line;
3543 let line_base_sp = cm.lookup_char_pos(base_span.lo()).line;
3544 debug!("{:?} {:?}", line_sp, line_base_sp);
3545 if snippet == ":" {
3546 err.span_label(base_span,
3547 "expecting a type here because of type ascription");
3548 if line_sp != line_base_sp {
3549 err.span_suggestion_short_with_applicability(
3550 sp,
3551 "did you mean to use `;` here instead?",
3552 ";".to_string(),
3553 Applicability::MaybeIncorrect,
3554 );
3555 }
3556 break;
3557 } else if !snippet.trim().is_empty() {
3558 debug!("tried to find type ascription `:` token, couldn't find it");
3559 break;
3560 }
3561 } else {
3562 break;
3563 }
3564 }
3565 }
3566 }
3567
3568 fn self_type_is_available(&mut self, span: Span) -> bool {
3569 let binding = self.resolve_ident_in_lexical_scope(keywords::SelfUpper.ident(),
3570 TypeNS, None, span);
3571 if let Some(LexicalScopeBinding::Def(def)) = binding { def != Def::Err } else { false }
3572 }
3573
3574 fn self_value_is_available(&mut self, self_span: Span, path_span: Span) -> bool {
3575 let ident = Ident::new(keywords::SelfLower.name(), self_span);
3576 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, path_span);
3577 if let Some(LexicalScopeBinding::Def(def)) = binding { def != Def::Err } else { false }
3578 }
3579
3580 // Resolve in alternative namespaces if resolution in the primary namespace fails.
3581 fn resolve_qpath_anywhere(&mut self,
3582 id: NodeId,
3583 qself: Option<&QSelf>,
3584 path: &[Segment],
3585 primary_ns: Namespace,
3586 span: Span,
3587 defer_to_typeck: bool,
3588 global_by_default: bool,
3589 crate_lint: CrateLint)
3590 -> Option<PathResolution> {
3591 let mut fin_res = None;
3592 // FIXME: can't resolve paths in macro namespace yet, macros are
3593 // processed by the little special hack below.
3594 for (i, ns) in [primary_ns, TypeNS, ValueNS, /*MacroNS*/].iter().cloned().enumerate() {
3595 if i == 0 || ns != primary_ns {
3596 match self.resolve_qpath(id, qself, path, ns, span, global_by_default, crate_lint) {
3597 // If defer_to_typeck, then resolution > no resolution,
3598 // otherwise full resolution > partial resolution > no resolution.
3599 Some(res) if res.unresolved_segments() == 0 || defer_to_typeck =>
3600 return Some(res),
3601 res => if fin_res.is_none() { fin_res = res },
3602 };
3603 }
3604 }
3605 if primary_ns != MacroNS &&
3606 (self.macro_names.contains(&path[0].ident.modern()) ||
3607 self.builtin_macros.get(&path[0].ident.name).cloned()
3608 .and_then(NameBinding::macro_kind) == Some(MacroKind::Bang) ||
3609 self.macro_use_prelude.get(&path[0].ident.name).cloned()
3610 .and_then(NameBinding::macro_kind) == Some(MacroKind::Bang)) {
3611 // Return some dummy definition, it's enough for error reporting.
3612 return Some(
3613 PathResolution::new(Def::Macro(DefId::local(CRATE_DEF_INDEX), MacroKind::Bang))
3614 );
3615 }
3616 fin_res
3617 }
3618
3619 /// Handles paths that may refer to associated items.
3620 fn resolve_qpath(&mut self,
3621 id: NodeId,
3622 qself: Option<&QSelf>,
3623 path: &[Segment],
3624 ns: Namespace,
3625 span: Span,
3626 global_by_default: bool,
3627 crate_lint: CrateLint)
3628 -> Option<PathResolution> {
3629 debug!(
3630 "resolve_qpath(id={:?}, qself={:?}, path={:?}, \
3631 ns={:?}, span={:?}, global_by_default={:?})",
3632 id,
3633 qself,
3634 path,
3635 ns,
3636 span,
3637 global_by_default,
3638 );
3639
3640 if let Some(qself) = qself {
3641 if qself.position == 0 {
3642 // This is a case like `<T>::B`, where there is no
3643 // trait to resolve. In that case, we leave the `B`
3644 // segment to be resolved by type-check.
3645 return Some(PathResolution::with_unresolved_segments(
3646 Def::Mod(DefId::local(CRATE_DEF_INDEX)), path.len()
3647 ));
3648 }
3649
3650 // Make sure `A::B` in `<T as A::B>::C` is a trait item.
3651 //
3652 // Currently, `path` names the full item (`A::B::C`, in
3653 // our example). so we extract the prefix of that that is
3654 // the trait (the slice upto and including
3655 // `qself.position`). And then we recursively resolve that,
3656 // but with `qself` set to `None`.
3657 //
3658 // However, setting `qself` to none (but not changing the
3659 // span) loses the information about where this path
3660 // *actually* appears, so for the purposes of the crate
3661 // lint we pass along information that this is the trait
3662 // name from a fully qualified path, and this also
3663 // contains the full span (the `CrateLint::QPathTrait`).
3664 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
3665 let res = self.smart_resolve_path_fragment(
3666 id,
3667 None,
3668 &path[..=qself.position],
3669 span,
3670 PathSource::TraitItem(ns),
3671 CrateLint::QPathTrait {
3672 qpath_id: id,
3673 qpath_span: qself.path_span,
3674 },
3675 );
3676
3677 // The remaining segments (the `C` in our example) will
3678 // have to be resolved by type-check, since that requires doing
3679 // trait resolution.
3680 return Some(PathResolution::with_unresolved_segments(
3681 res.base_def(), res.unresolved_segments() + path.len() - qself.position - 1
3682 ));
3683 }
3684
3685 let result = match self.resolve_path_without_parent_scope(
3686 &path,
3687 Some(ns),
3688 true,
3689 span,
3690 crate_lint,
3691 ) {
3692 PathResult::NonModule(path_res) => path_res,
3693 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
3694 PathResolution::new(module.def().unwrap())
3695 }
3696 // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
3697 // don't report an error right away, but try to fallback to a primitive type.
3698 // So, we are still able to successfully resolve something like
3699 //
3700 // use std::u8; // bring module u8 in scope
3701 // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
3702 // u8::max_value() // OK, resolves to associated function <u8>::max_value,
3703 // // not to non-existent std::u8::max_value
3704 // }
3705 //
3706 // Such behavior is required for backward compatibility.
3707 // The same fallback is used when `a` resolves to nothing.
3708 PathResult::Module(ModuleOrUniformRoot::Module(_)) |
3709 PathResult::Failed(..)
3710 if (ns == TypeNS || path.len() > 1) &&
3711 self.primitive_type_table.primitive_types
3712 .contains_key(&path[0].ident.name) => {
3713 let prim = self.primitive_type_table.primitive_types[&path[0].ident.name];
3714 PathResolution::with_unresolved_segments(Def::PrimTy(prim), path.len() - 1)
3715 }
3716 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
3717 PathResolution::new(module.def().unwrap()),
3718 PathResult::Failed(span, msg, false) => {
3719 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
3720 err_path_resolution()
3721 }
3722 PathResult::Module(..) | PathResult::Failed(..) => return None,
3723 PathResult::Indeterminate => bug!("indetermined path result in resolve_qpath"),
3724 };
3725
3726 if path.len() > 1 && !global_by_default && result.base_def() != Def::Err &&
3727 path[0].ident.name != keywords::PathRoot.name() &&
3728 path[0].ident.name != keywords::DollarCrate.name() {
3729 let unqualified_result = {
3730 match self.resolve_path_without_parent_scope(
3731 &[*path.last().unwrap()],
3732 Some(ns),
3733 false,
3734 span,
3735 CrateLint::No,
3736 ) {
3737 PathResult::NonModule(path_res) => path_res.base_def(),
3738 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
3739 module.def().unwrap(),
3740 _ => return Some(result),
3741 }
3742 };
3743 if result.base_def() == unqualified_result {
3744 let lint = lint::builtin::UNUSED_QUALIFICATIONS;
3745 self.session.buffer_lint(lint, id, span, "unnecessary qualification")
3746 }
3747 }
3748
3749 Some(result)
3750 }
3751
3752 fn resolve_path_without_parent_scope(
3753 &mut self,
3754 path: &[Segment],
3755 opt_ns: Option<Namespace>, // `None` indicates a module path in import
3756 record_used: bool,
3757 path_span: Span,
3758 crate_lint: CrateLint,
3759 ) -> PathResult<'a> {
3760 // Macro and import paths must have full parent scope available during resolution,
3761 // other paths will do okay with parent module alone.
3762 assert!(opt_ns != None && opt_ns != Some(MacroNS));
3763 let parent_scope = ParentScope { module: self.current_module, ..self.dummy_parent_scope() };
3764 self.resolve_path(path, opt_ns, &parent_scope, record_used, path_span, crate_lint)
3765 }
3766
3767 fn resolve_path(
3768 &mut self,
3769 path: &[Segment],
3770 opt_ns: Option<Namespace>, // `None` indicates a module path in import
3771 parent_scope: &ParentScope<'a>,
3772 record_used: bool,
3773 path_span: Span,
3774 crate_lint: CrateLint,
3775 ) -> PathResult<'a> {
3776 let mut module = None;
3777 let mut allow_super = true;
3778 let mut second_binding = None;
3779 self.current_module = parent_scope.module;
3780
3781 debug!(
3782 "resolve_path(path={:?}, opt_ns={:?}, record_used={:?}, \
3783 path_span={:?}, crate_lint={:?})",
3784 path,
3785 opt_ns,
3786 record_used,
3787 path_span,
3788 crate_lint,
3789 );
3790
3791 for (i, &Segment { ident, id }) in path.iter().enumerate() {
3792 debug!("resolve_path ident {} {:?} {:?}", i, ident, id);
3793 let record_segment_def = |this: &mut Self, def| {
3794 if record_used {
3795 if let Some(id) = id {
3796 if !this.def_map.contains_key(&id) {
3797 assert!(id != ast::DUMMY_NODE_ID, "Trying to resolve dummy id");
3798 this.record_def(id, PathResolution::new(def));
3799 }
3800 }
3801 }
3802 };
3803
3804 let is_last = i == path.len() - 1;
3805 let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
3806 let name = ident.name;
3807
3808 allow_super &= ns == TypeNS &&
3809 (name == keywords::SelfLower.name() ||
3810 name == keywords::Super.name());
3811
3812 if ns == TypeNS {
3813 if allow_super && name == keywords::Super.name() {
3814 let mut ctxt = ident.span.ctxt().modern();
3815 let self_module = match i {
3816 0 => Some(self.resolve_self(&mut ctxt, self.current_module)),
3817 _ => match module {
3818 Some(ModuleOrUniformRoot::Module(module)) => Some(module),
3819 _ => None,
3820 },
3821 };
3822 if let Some(self_module) = self_module {
3823 if let Some(parent) = self_module.parent {
3824 module = Some(ModuleOrUniformRoot::Module(
3825 self.resolve_self(&mut ctxt, parent)));
3826 continue;
3827 }
3828 }
3829 let msg = "there are too many initial `super`s.".to_string();
3830 return PathResult::Failed(ident.span, msg, false);
3831 }
3832 if i == 0 {
3833 if name == keywords::SelfLower.name() {
3834 let mut ctxt = ident.span.ctxt().modern();
3835 module = Some(ModuleOrUniformRoot::Module(
3836 self.resolve_self(&mut ctxt, self.current_module)));
3837 continue;
3838 }
3839 if name == keywords::PathRoot.name() && ident.span.rust_2018() {
3840 module = Some(ModuleOrUniformRoot::ExternPrelude);
3841 continue;
3842 }
3843 if name == keywords::PathRoot.name() &&
3844 ident.span.rust_2015() && self.session.rust_2018() {
3845 // `::a::b` from 2015 macro on 2018 global edition
3846 module = Some(ModuleOrUniformRoot::CrateRootAndExternPrelude);
3847 continue;
3848 }
3849 if name == keywords::PathRoot.name() ||
3850 name == keywords::Crate.name() ||
3851 name == keywords::DollarCrate.name() {
3852 // `::a::b`, `crate::a::b` or `$crate::a::b`
3853 module = Some(ModuleOrUniformRoot::Module(
3854 self.resolve_crate_root(ident)));
3855 continue;
3856 }
3857 }
3858 }
3859
3860 // Report special messages for path segment keywords in wrong positions.
3861 if ident.is_path_segment_keyword() && i != 0 {
3862 let name_str = if name == keywords::PathRoot.name() {
3863 "crate root".to_string()
3864 } else {
3865 format!("`{}`", name)
3866 };
3867 let msg = if i == 1 && path[0].ident.name == keywords::PathRoot.name() {
3868 format!("global paths cannot start with {}", name_str)
3869 } else {
3870 format!("{} in paths can only be used in start position", name_str)
3871 };
3872 return PathResult::Failed(ident.span, msg, false);
3873 }
3874
3875 let binding = if let Some(module) = module {
3876 self.resolve_ident_in_module(module, ident, ns, None, record_used, path_span)
3877 } else if opt_ns.is_none() || opt_ns == Some(MacroNS) {
3878 assert!(ns == TypeNS);
3879 let scopes = if opt_ns.is_none() { ScopeSet::Import(ns) } else { ScopeSet::Module };
3880 self.early_resolve_ident_in_lexical_scope(ident, scopes, parent_scope, record_used,
3881 record_used, path_span)
3882 } else {
3883 let record_used_id =
3884 if record_used { crate_lint.node_id().or(Some(CRATE_NODE_ID)) } else { None };
3885 match self.resolve_ident_in_lexical_scope(ident, ns, record_used_id, path_span) {
3886 // we found a locally-imported or available item/module
3887 Some(LexicalScopeBinding::Item(binding)) => Ok(binding),
3888 // we found a local variable or type param
3889 Some(LexicalScopeBinding::Def(def))
3890 if opt_ns == Some(TypeNS) || opt_ns == Some(ValueNS) => {
3891 record_segment_def(self, def);
3892 return PathResult::NonModule(PathResolution::with_unresolved_segments(
3893 def, path.len() - 1
3894 ));
3895 }
3896 _ => Err(Determinacy::determined(record_used)),
3897 }
3898 };
3899
3900 match binding {
3901 Ok(binding) => {
3902 if i == 1 {
3903 second_binding = Some(binding);
3904 }
3905 let def = binding.def();
3906 let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(def);
3907 if let Some(next_module) = binding.module() {
3908 module = Some(ModuleOrUniformRoot::Module(next_module));
3909 record_segment_def(self, def);
3910 } else if def == Def::ToolMod && i + 1 != path.len() {
3911 if binding.is_import() {
3912 self.session.struct_span_err(
3913 ident.span, "cannot use a tool module through an import"
3914 ).span_note(
3915 binding.span, "the tool module imported here"
3916 ).emit();
3917 }
3918 let def = Def::NonMacroAttr(NonMacroAttrKind::Tool);
3919 return PathResult::NonModule(PathResolution::new(def));
3920 } else if def == Def::Err {
3921 return PathResult::NonModule(err_path_resolution());
3922 } else if opt_ns.is_some() && (is_last || maybe_assoc) {
3923 self.lint_if_path_starts_with_module(
3924 crate_lint,
3925 path,
3926 path_span,
3927 second_binding,
3928 );
3929 return PathResult::NonModule(PathResolution::with_unresolved_segments(
3930 def, path.len() - i - 1
3931 ));
3932 } else {
3933 return PathResult::Failed(ident.span,
3934 format!("not a module `{}`", ident),
3935 is_last);
3936 }
3937 }
3938 Err(Undetermined) => return PathResult::Indeterminate,
3939 Err(Determined) => {
3940 if let Some(ModuleOrUniformRoot::Module(module)) = module {
3941 if opt_ns.is_some() && !module.is_normal() {
3942 return PathResult::NonModule(PathResolution::with_unresolved_segments(
3943 module.def().unwrap(), path.len() - i
3944 ));
3945 }
3946 }
3947 let module_def = match module {
3948 Some(ModuleOrUniformRoot::Module(module)) => module.def(),
3949 _ => None,
3950 };
3951 let msg = if module_def == self.graph_root.def() {
3952 let is_mod = |def| match def { Def::Mod(..) => true, _ => false };
3953 let mut candidates =
3954 self.lookup_import_candidates(ident, TypeNS, is_mod);
3955 candidates.sort_by_cached_key(|c| {
3956 (c.path.segments.len(), c.path.to_string())
3957 });
3958 if let Some(candidate) = candidates.get(0) {
3959 format!("did you mean `{}`?", candidate.path)
3960 } else if !ident.is_reserved() {
3961 format!("maybe a missing `extern crate {};`?", ident)
3962 } else {
3963 // the parser will already have complained about the keyword being used
3964 return PathResult::NonModule(err_path_resolution());
3965 }
3966 } else if i == 0 {
3967 format!("use of undeclared type or module `{}`", ident)
3968 } else {
3969 format!("could not find `{}` in `{}`", ident, path[i - 1].ident)
3970 };
3971 return PathResult::Failed(ident.span, msg, is_last);
3972 }
3973 }
3974 }
3975
3976 self.lint_if_path_starts_with_module(crate_lint, path, path_span, second_binding);
3977
3978 PathResult::Module(match module {
3979 Some(module) => module,
3980 None if path.is_empty() => ModuleOrUniformRoot::CurrentScope,
3981 _ => span_bug!(path_span, "resolve_path: non-empty path `{:?}` has no module", path),
3982 })
3983 }
3984
3985 fn lint_if_path_starts_with_module(
3986 &self,
3987 crate_lint: CrateLint,
3988 path: &[Segment],
3989 path_span: Span,
3990 second_binding: Option<&NameBinding>,
3991 ) {
3992 let (diag_id, diag_span) = match crate_lint {
3993 CrateLint::No => return,
3994 CrateLint::SimplePath(id) => (id, path_span),
3995 CrateLint::UsePath { root_id, root_span } => (root_id, root_span),
3996 CrateLint::QPathTrait { qpath_id, qpath_span } => (qpath_id, qpath_span),
3997 };
3998
3999 let first_name = match path.get(0) {
4000 // In the 2018 edition this lint is a hard error, so nothing to do
4001 Some(seg) if seg.ident.span.rust_2015() && self.session.rust_2015() => seg.ident.name,
4002 _ => return,
4003 };
4004
4005 // We're only interested in `use` paths which should start with
4006 // `{{root}}` currently.
4007 if first_name != keywords::PathRoot.name() {
4008 return
4009 }
4010
4011 match path.get(1) {
4012 // If this import looks like `crate::...` it's already good
4013 Some(Segment { ident, .. }) if ident.name == keywords::Crate.name() => return,
4014 // Otherwise go below to see if it's an extern crate
4015 Some(_) => {}
4016 // If the path has length one (and it's `PathRoot` most likely)
4017 // then we don't know whether we're gonna be importing a crate or an
4018 // item in our crate. Defer this lint to elsewhere
4019 None => return,
4020 }
4021
4022 // If the first element of our path was actually resolved to an
4023 // `ExternCrate` (also used for `crate::...`) then no need to issue a
4024 // warning, this looks all good!
4025 if let Some(binding) = second_binding {
4026 if let NameBindingKind::Import { directive: d, .. } = binding.kind {
4027 // Careful: we still want to rewrite paths from
4028 // renamed extern crates.
4029 if let ImportDirectiveSubclass::ExternCrate { source: None, .. } = d.subclass {
4030 return
4031 }
4032 }
4033 }
4034
4035 let diag = lint::builtin::BuiltinLintDiagnostics
4036 ::AbsPathWithModule(diag_span);
4037 self.session.buffer_lint_with_diagnostic(
4038 lint::builtin::ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
4039 diag_id, diag_span,
4040 "absolute paths must start with `self`, `super`, \
4041 `crate`, or an external crate name in the 2018 edition",
4042 diag);
4043 }
4044
4045 // Resolve a local definition, potentially adjusting for closures.
4046 fn adjust_local_def(&mut self,
4047 ns: Namespace,
4048 rib_index: usize,
4049 mut def: Def,
4050 record_used: bool,
4051 span: Span) -> Def {
4052 let ribs = &self.ribs[ns][rib_index + 1..];
4053
4054 // An invalid forward use of a type parameter from a previous default.
4055 if let ForwardTyParamBanRibKind = self.ribs[ns][rib_index].kind {
4056 if record_used {
4057 resolve_error(self, span, ResolutionError::ForwardDeclaredTyParam);
4058 }
4059 assert_eq!(def, Def::Err);
4060 return Def::Err;
4061 }
4062
4063 match def {
4064 Def::Upvar(..) => {
4065 span_bug!(span, "unexpected {:?} in bindings", def)
4066 }
4067 Def::Local(node_id) => {
4068 for rib in ribs {
4069 match rib.kind {
4070 NormalRibKind | ModuleRibKind(..) | MacroDefinition(..) |
4071 ForwardTyParamBanRibKind => {
4072 // Nothing to do. Continue.
4073 }
4074 ClosureRibKind(function_id) => {
4075 let prev_def = def;
4076
4077 let seen = self.freevars_seen
4078 .entry(function_id)
4079 .or_default();
4080 if let Some(&index) = seen.get(&node_id) {
4081 def = Def::Upvar(node_id, index, function_id);
4082 continue;
4083 }
4084 let vec = self.freevars
4085 .entry(function_id)
4086 .or_default();
4087 let depth = vec.len();
4088 def = Def::Upvar(node_id, depth, function_id);
4089
4090 if record_used {
4091 vec.push(Freevar {
4092 def: prev_def,
4093 span,
4094 });
4095 seen.insert(node_id, depth);
4096 }
4097 }
4098 ItemRibKind | TraitOrImplItemRibKind => {
4099 // This was an attempt to access an upvar inside a
4100 // named function item. This is not allowed, so we
4101 // report an error.
4102 if record_used {
4103 resolve_error(self, span,
4104 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
4105 }
4106 return Def::Err;
4107 }
4108 ConstantItemRibKind => {
4109 // Still doesn't deal with upvars
4110 if record_used {
4111 resolve_error(self, span,
4112 ResolutionError::AttemptToUseNonConstantValueInConstant);
4113 }
4114 return Def::Err;
4115 }
4116 }
4117 }
4118 }
4119 Def::TyParam(..) | Def::SelfTy(..) => {
4120 for rib in ribs {
4121 match rib.kind {
4122 NormalRibKind | TraitOrImplItemRibKind | ClosureRibKind(..) |
4123 ModuleRibKind(..) | MacroDefinition(..) | ForwardTyParamBanRibKind |
4124 ConstantItemRibKind => {
4125 // Nothing to do. Continue.
4126 }
4127 ItemRibKind => {
4128 // This was an attempt to use a type parameter outside
4129 // its scope.
4130 if record_used {
4131 resolve_error(self, span,
4132 ResolutionError::TypeParametersFromOuterFunction(def));
4133 }
4134 return Def::Err;
4135 }
4136 }
4137 }
4138 }
4139 _ => {}
4140 }
4141 def
4142 }
4143
4144 fn lookup_assoc_candidate<FilterFn>(&mut self,
4145 ident: Ident,
4146 ns: Namespace,
4147 filter_fn: FilterFn)
4148 -> Option<AssocSuggestion>
4149 where FilterFn: Fn(Def) -> bool
4150 {
4151 fn extract_node_id(t: &Ty) -> Option<NodeId> {
4152 match t.node {
4153 TyKind::Path(None, _) => Some(t.id),
4154 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
4155 // This doesn't handle the remaining `Ty` variants as they are not
4156 // that commonly the self_type, it might be interesting to provide
4157 // support for those in future.
4158 _ => None,
4159 }
4160 }
4161
4162 // Fields are generally expected in the same contexts as locals.
4163 if filter_fn(Def::Local(ast::DUMMY_NODE_ID)) {
4164 if let Some(node_id) = self.current_self_type.as_ref().and_then(extract_node_id) {
4165 // Look for a field with the same name in the current self_type.
4166 if let Some(resolution) = self.def_map.get(&node_id) {
4167 match resolution.base_def() {
4168 Def::Struct(did) | Def::Union(did)
4169 if resolution.unresolved_segments() == 0 => {
4170 if let Some(field_names) = self.field_names.get(&did) {
4171 if field_names.iter().any(|&field_name| ident.name == field_name) {
4172 return Some(AssocSuggestion::Field);
4173 }
4174 }
4175 }
4176 _ => {}
4177 }
4178 }
4179 }
4180 }
4181
4182 // Look for associated items in the current trait.
4183 if let Some((module, _)) = self.current_trait_ref {
4184 if let Ok(binding) = self.resolve_ident_in_module(
4185 ModuleOrUniformRoot::Module(module),
4186 ident,
4187 ns,
4188 None,
4189 false,
4190 module.span,
4191 ) {
4192 let def = binding.def();
4193 if filter_fn(def) {
4194 return Some(if self.has_self.contains(&def.def_id()) {
4195 AssocSuggestion::MethodWithSelf
4196 } else {
4197 AssocSuggestion::AssocItem
4198 });
4199 }
4200 }
4201 }
4202
4203 None
4204 }
4205
4206 fn lookup_typo_candidate<FilterFn>(
4207 &mut self,
4208 path: &[Segment],
4209 ns: Namespace,
4210 filter_fn: FilterFn,
4211 span: Span,
4212 ) -> Option<TypoSuggestion>
4213 where
4214 FilterFn: Fn(Def) -> bool,
4215 {
4216 let add_module_candidates = |module: Module, names: &mut Vec<TypoSuggestion>| {
4217 for (&(ident, _), resolution) in module.resolutions.borrow().iter() {
4218 if let Some(binding) = resolution.borrow().binding {
4219 if filter_fn(binding.def()) {
4220 names.push(TypoSuggestion {
4221 candidate: ident.name,
4222 article: binding.def().article(),
4223 kind: binding.def().kind_name(),
4224 });
4225 }
4226 }
4227 }
4228 };
4229
4230 let mut names = Vec::new();
4231 if path.len() == 1 {
4232 // Search in lexical scope.
4233 // Walk backwards up the ribs in scope and collect candidates.
4234 for rib in self.ribs[ns].iter().rev() {
4235 // Locals and type parameters
4236 for (ident, def) in &rib.bindings {
4237 if filter_fn(*def) {
4238 names.push(TypoSuggestion {
4239 candidate: ident.name,
4240 article: def.article(),
4241 kind: def.kind_name(),
4242 });
4243 }
4244 }
4245 // Items in scope
4246 if let ModuleRibKind(module) = rib.kind {
4247 // Items from this module
4248 add_module_candidates(module, &mut names);
4249
4250 if let ModuleKind::Block(..) = module.kind {
4251 // We can see through blocks
4252 } else {
4253 // Items from the prelude
4254 if !module.no_implicit_prelude {
4255 names.extend(self.extern_prelude.iter().map(|(ident, _)| {
4256 TypoSuggestion {
4257 candidate: ident.name,
4258 article: "a",
4259 kind: "crate",
4260 }
4261 }));
4262 if let Some(prelude) = self.prelude {
4263 add_module_candidates(prelude, &mut names);
4264 }
4265 }
4266 break;
4267 }
4268 }
4269 }
4270 // Add primitive types to the mix
4271 if filter_fn(Def::PrimTy(Bool)) {
4272 names.extend(
4273 self.primitive_type_table.primitive_types.iter().map(|(name, _)| {
4274 TypoSuggestion {
4275 candidate: *name,
4276 article: "a",
4277 kind: "primitive type",
4278 }
4279 })
4280 )
4281 }
4282 } else {
4283 // Search in module.
4284 let mod_path = &path[..path.len() - 1];
4285 if let PathResult::Module(module) = self.resolve_path_without_parent_scope(
4286 mod_path, Some(TypeNS), false, span, CrateLint::No
4287 ) {
4288 if let ModuleOrUniformRoot::Module(module) = module {
4289 add_module_candidates(module, &mut names);
4290 }
4291 }
4292 }
4293
4294 let name = path[path.len() - 1].ident.name;
4295 // Make sure error reporting is deterministic.
4296 names.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
4297
4298 match find_best_match_for_name(
4299 names.iter().map(|suggestion| &suggestion.candidate),
4300 &name.as_str(),
4301 None,
4302 ) {
4303 Some(found) if found != name => names
4304 .into_iter()
4305 .find(|suggestion| suggestion.candidate == found),
4306 _ => None,
4307 }
4308 }
4309
4310 fn with_resolved_label<F>(&mut self, label: Option<Label>, id: NodeId, f: F)
4311 where F: FnOnce(&mut Resolver)
4312 {
4313 if let Some(label) = label {
4314 self.unused_labels.insert(id, label.ident.span);
4315 let def = Def::Label(id);
4316 self.with_label_rib(|this| {
4317 let ident = label.ident.modern_and_legacy();
4318 this.label_ribs.last_mut().unwrap().bindings.insert(ident, def);
4319 f(this);
4320 });
4321 } else {
4322 f(self);
4323 }
4324 }
4325
4326 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &Block) {
4327 self.with_resolved_label(label, id, |this| this.visit_block(block));
4328 }
4329
4330 fn resolve_expr(&mut self, expr: &Expr, parent: Option<&Expr>) {
4331 // First, record candidate traits for this expression if it could
4332 // result in the invocation of a method call.
4333
4334 self.record_candidate_traits_for_expr_if_necessary(expr);
4335
4336 // Next, resolve the node.
4337 match expr.node {
4338 ExprKind::Path(ref qself, ref path) => {
4339 self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
4340 visit::walk_expr(self, expr);
4341 }
4342
4343 ExprKind::Struct(ref path, ..) => {
4344 self.smart_resolve_path(expr.id, None, path, PathSource::Struct);
4345 visit::walk_expr(self, expr);
4346 }
4347
4348 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
4349 let def = self.search_label(label.ident, |rib, ident| {
4350 rib.bindings.get(&ident.modern_and_legacy()).cloned()
4351 });
4352 match def {
4353 None => {
4354 // Search again for close matches...
4355 // Picks the first label that is "close enough", which is not necessarily
4356 // the closest match
4357 let close_match = self.search_label(label.ident, |rib, ident| {
4358 let names = rib.bindings.iter().map(|(id, _)| &id.name);
4359 find_best_match_for_name(names, &*ident.as_str(), None)
4360 });
4361 self.record_def(expr.id, err_path_resolution());
4362 resolve_error(self,
4363 label.ident.span,
4364 ResolutionError::UndeclaredLabel(&label.ident.as_str(),
4365 close_match));
4366 }
4367 Some(Def::Label(id)) => {
4368 // Since this def is a label, it is never read.
4369 self.record_def(expr.id, PathResolution::new(Def::Label(id)));
4370 self.unused_labels.remove(&id);
4371 }
4372 Some(_) => {
4373 span_bug!(expr.span, "label wasn't mapped to a label def!");
4374 }
4375 }
4376
4377 // visit `break` argument if any
4378 visit::walk_expr(self, expr);
4379 }
4380
4381 ExprKind::IfLet(ref pats, ref subexpression, ref if_block, ref optional_else) => {
4382 self.visit_expr(subexpression);
4383
4384 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
4385 let mut bindings_list = FxHashMap::default();
4386 for pat in pats {
4387 self.resolve_pattern(pat, PatternSource::IfLet, &mut bindings_list);
4388 }
4389 // This has to happen *after* we determine which pat_idents are variants
4390 self.check_consistent_bindings(pats);
4391 self.visit_block(if_block);
4392 self.ribs[ValueNS].pop();
4393
4394 optional_else.as_ref().map(|expr| self.visit_expr(expr));
4395 }
4396
4397 ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
4398
4399 ExprKind::While(ref subexpression, ref block, label) => {
4400 self.with_resolved_label(label, expr.id, |this| {
4401 this.visit_expr(subexpression);
4402 this.visit_block(block);
4403 });
4404 }
4405
4406 ExprKind::WhileLet(ref pats, ref subexpression, ref block, label) => {
4407 self.with_resolved_label(label, expr.id, |this| {
4408 this.visit_expr(subexpression);
4409 this.ribs[ValueNS].push(Rib::new(NormalRibKind));
4410 let mut bindings_list = FxHashMap::default();
4411 for pat in pats {
4412 this.resolve_pattern(pat, PatternSource::WhileLet, &mut bindings_list);
4413 }
4414 // This has to happen *after* we determine which pat_idents are variants.
4415 this.check_consistent_bindings(pats);
4416 this.visit_block(block);
4417 this.ribs[ValueNS].pop();
4418 });
4419 }
4420
4421 ExprKind::ForLoop(ref pattern, ref subexpression, ref block, label) => {
4422 self.visit_expr(subexpression);
4423 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
4424 self.resolve_pattern(pattern, PatternSource::For, &mut FxHashMap::default());
4425
4426 self.resolve_labeled_block(label, expr.id, block);
4427
4428 self.ribs[ValueNS].pop();
4429 }
4430
4431 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
4432
4433 // Equivalent to `visit::walk_expr` + passing some context to children.
4434 ExprKind::Field(ref subexpression, _) => {
4435 self.resolve_expr(subexpression, Some(expr));
4436 }
4437 ExprKind::MethodCall(ref segment, ref arguments) => {
4438 let mut arguments = arguments.iter();
4439 self.resolve_expr(arguments.next().unwrap(), Some(expr));
4440 for argument in arguments {
4441 self.resolve_expr(argument, None);
4442 }
4443 self.visit_path_segment(expr.span, segment);
4444 }
4445
4446 ExprKind::Call(ref callee, ref arguments) => {
4447 self.resolve_expr(callee, Some(expr));
4448 for argument in arguments {
4449 self.resolve_expr(argument, None);
4450 }
4451 }
4452 ExprKind::Type(ref type_expr, _) => {
4453 self.current_type_ascription.push(type_expr.span);
4454 visit::walk_expr(self, expr);
4455 self.current_type_ascription.pop();
4456 }
4457 // Resolve the body of async exprs inside the async closure to which they desugar
4458 ExprKind::Async(_, async_closure_id, ref block) => {
4459 let rib_kind = ClosureRibKind(async_closure_id);
4460 self.ribs[ValueNS].push(Rib::new(rib_kind));
4461 self.label_ribs.push(Rib::new(rib_kind));
4462 self.visit_block(&block);
4463 self.label_ribs.pop();
4464 self.ribs[ValueNS].pop();
4465 }
4466 // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to
4467 // resolve the arguments within the proper scopes so that usages of them inside the
4468 // closure are detected as upvars rather than normal closure arg usages.
4469 ExprKind::Closure(
4470 _, IsAsync::Async { closure_id: inner_closure_id, .. }, _,
4471 ref fn_decl, ref body, _span,
4472 ) => {
4473 let rib_kind = ClosureRibKind(expr.id);
4474 self.ribs[ValueNS].push(Rib::new(rib_kind));
4475 self.label_ribs.push(Rib::new(rib_kind));
4476 // Resolve arguments:
4477 let mut bindings_list = FxHashMap::default();
4478 for argument in &fn_decl.inputs {
4479 self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
4480 self.visit_ty(&argument.ty);
4481 }
4482 // No need to resolve return type-- the outer closure return type is
4483 // FunctionRetTy::Default
4484
4485 // Now resolve the inner closure
4486 {
4487 let rib_kind = ClosureRibKind(inner_closure_id);
4488 self.ribs[ValueNS].push(Rib::new(rib_kind));
4489 self.label_ribs.push(Rib::new(rib_kind));
4490 // No need to resolve arguments: the inner closure has none.
4491 // Resolve the return type:
4492 visit::walk_fn_ret_ty(self, &fn_decl.output);
4493 // Resolve the body
4494 self.visit_expr(body);
4495 self.label_ribs.pop();
4496 self.ribs[ValueNS].pop();
4497 }
4498 self.label_ribs.pop();
4499 self.ribs[ValueNS].pop();
4500 }
4501 _ => {
4502 visit::walk_expr(self, expr);
4503 }
4504 }
4505 }
4506
4507 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
4508 match expr.node {
4509 ExprKind::Field(_, ident) => {
4510 // FIXME(#6890): Even though you can't treat a method like a
4511 // field, we need to add any trait methods we find that match
4512 // the field name so that we can do some nice error reporting
4513 // later on in typeck.
4514 let traits = self.get_traits_containing_item(ident, ValueNS);
4515 self.trait_map.insert(expr.id, traits);
4516 }
4517 ExprKind::MethodCall(ref segment, ..) => {
4518 debug!("(recording candidate traits for expr) recording traits for {}",
4519 expr.id);
4520 let traits = self.get_traits_containing_item(segment.ident, ValueNS);
4521 self.trait_map.insert(expr.id, traits);
4522 }
4523 _ => {
4524 // Nothing to do.
4525 }
4526 }
4527 }
4528
4529 fn get_traits_containing_item(&mut self, mut ident: Ident, ns: Namespace)
4530 -> Vec<TraitCandidate> {
4531 debug!("(getting traits containing item) looking for '{}'", ident.name);
4532
4533 let mut found_traits = Vec::new();
4534 // Look for the current trait.
4535 if let Some((module, _)) = self.current_trait_ref {
4536 if self.resolve_ident_in_module(
4537 ModuleOrUniformRoot::Module(module),
4538 ident,
4539 ns,
4540 None,
4541 false,
4542 module.span,
4543 ).is_ok() {
4544 let def_id = module.def_id().unwrap();
4545 found_traits.push(TraitCandidate { def_id: def_id, import_id: None });
4546 }
4547 }
4548
4549 ident.span = ident.span.modern();
4550 let mut search_module = self.current_module;
4551 loop {
4552 self.get_traits_in_module_containing_item(ident, ns, search_module, &mut found_traits);
4553 search_module = unwrap_or!(
4554 self.hygienic_lexical_parent(search_module, &mut ident.span), break
4555 );
4556 }
4557
4558 if let Some(prelude) = self.prelude {
4559 if !search_module.no_implicit_prelude {
4560 self.get_traits_in_module_containing_item(ident, ns, prelude, &mut found_traits);
4561 }
4562 }
4563
4564 found_traits
4565 }
4566
4567 fn get_traits_in_module_containing_item(&mut self,
4568 ident: Ident,
4569 ns: Namespace,
4570 module: Module<'a>,
4571 found_traits: &mut Vec<TraitCandidate>) {
4572 assert!(ns == TypeNS || ns == ValueNS);
4573 let mut traits = module.traits.borrow_mut();
4574 if traits.is_none() {
4575 let mut collected_traits = Vec::new();
4576 module.for_each_child(|name, ns, binding| {
4577 if ns != TypeNS { return }
4578 if let Def::Trait(_) = binding.def() {
4579 collected_traits.push((name, binding));
4580 }
4581 });
4582 *traits = Some(collected_traits.into_boxed_slice());
4583 }
4584
4585 for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
4586 let module = binding.module().unwrap();
4587 let mut ident = ident;
4588 if ident.span.glob_adjust(module.expansion, binding.span.ctxt().modern()).is_none() {
4589 continue
4590 }
4591 if self.resolve_ident_in_module_unadjusted(
4592 ModuleOrUniformRoot::Module(module),
4593 ident,
4594 ns,
4595 false,
4596 module.span,
4597 ).is_ok() {
4598 let import_id = match binding.kind {
4599 NameBindingKind::Import { directive, .. } => {
4600 self.maybe_unused_trait_imports.insert(directive.id);
4601 self.add_to_glob_map(directive.id, trait_name);
4602 Some(directive.id)
4603 }
4604 _ => None,
4605 };
4606 let trait_def_id = module.def_id().unwrap();
4607 found_traits.push(TraitCandidate { def_id: trait_def_id, import_id: import_id });
4608 }
4609 }
4610 }
4611
4612 fn lookup_import_candidates_from_module<FilterFn>(&mut self,
4613 lookup_ident: Ident,
4614 namespace: Namespace,
4615 start_module: &'a ModuleData<'a>,
4616 crate_name: Ident,
4617 filter_fn: FilterFn)
4618 -> Vec<ImportSuggestion>
4619 where FilterFn: Fn(Def) -> bool
4620 {
4621 let mut candidates = Vec::new();
4622 let mut seen_modules = FxHashSet::default();
4623 let not_local_module = crate_name != keywords::Crate.ident();
4624 let mut worklist = vec![(start_module, Vec::<ast::PathSegment>::new(), not_local_module)];
4625
4626 while let Some((in_module,
4627 path_segments,
4628 in_module_is_extern)) = worklist.pop() {
4629 self.populate_module_if_necessary(in_module);
4630
4631 // We have to visit module children in deterministic order to avoid
4632 // instabilities in reported imports (#43552).
4633 in_module.for_each_child_stable(|ident, ns, name_binding| {
4634 // avoid imports entirely
4635 if name_binding.is_import() && !name_binding.is_extern_crate() { return; }
4636 // avoid non-importable candidates as well
4637 if !name_binding.is_importable() { return; }
4638
4639 // collect results based on the filter function
4640 if ident.name == lookup_ident.name && ns == namespace {
4641 if filter_fn(name_binding.def()) {
4642 // create the path
4643 let mut segms = path_segments.clone();
4644 if lookup_ident.span.rust_2018() {
4645 // crate-local absolute paths start with `crate::` in edition 2018
4646 // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
4647 segms.insert(
4648 0, ast::PathSegment::from_ident(crate_name)
4649 );
4650 }
4651
4652 segms.push(ast::PathSegment::from_ident(ident));
4653 let path = Path {
4654 span: name_binding.span,
4655 segments: segms,
4656 };
4657 // the entity is accessible in the following cases:
4658 // 1. if it's defined in the same crate, it's always
4659 // accessible (since private entities can be made public)
4660 // 2. if it's defined in another crate, it's accessible
4661 // only if both the module is public and the entity is
4662 // declared as public (due to pruning, we don't explore
4663 // outside crate private modules => no need to check this)
4664 if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
4665 candidates.push(ImportSuggestion { path });
4666 }
4667 }
4668 }
4669
4670 // collect submodules to explore
4671 if let Some(module) = name_binding.module() {
4672 // form the path
4673 let mut path_segments = path_segments.clone();
4674 path_segments.push(ast::PathSegment::from_ident(ident));
4675
4676 let is_extern_crate_that_also_appears_in_prelude =
4677 name_binding.is_extern_crate() &&
4678 lookup_ident.span.rust_2018();
4679
4680 let is_visible_to_user =
4681 !in_module_is_extern || name_binding.vis == ty::Visibility::Public;
4682
4683 if !is_extern_crate_that_also_appears_in_prelude && is_visible_to_user {
4684 // add the module to the lookup
4685 let is_extern = in_module_is_extern || name_binding.is_extern_crate();
4686 if seen_modules.insert(module.def_id().unwrap()) {
4687 worklist.push((module, path_segments, is_extern));
4688 }
4689 }
4690 }
4691 })
4692 }
4693
4694 candidates
4695 }
4696
4697 /// When name resolution fails, this method can be used to look up candidate
4698 /// entities with the expected name. It allows filtering them using the
4699 /// supplied predicate (which should be used to only accept the types of
4700 /// definitions expected e.g., traits). The lookup spans across all crates.
4701 ///
4702 /// NOTE: The method does not look into imports, but this is not a problem,
4703 /// since we report the definitions (thus, the de-aliased imports).
4704 fn lookup_import_candidates<FilterFn>(&mut self,
4705 lookup_ident: Ident,
4706 namespace: Namespace,
4707 filter_fn: FilterFn)
4708 -> Vec<ImportSuggestion>
4709 where FilterFn: Fn(Def) -> bool
4710 {
4711 let mut suggestions = self.lookup_import_candidates_from_module(
4712 lookup_ident, namespace, self.graph_root, keywords::Crate.ident(), &filter_fn);
4713
4714 if lookup_ident.span.rust_2018() {
4715 let extern_prelude_names = self.extern_prelude.clone();
4716 for (ident, _) in extern_prelude_names.into_iter() {
4717 if let Some(crate_id) = self.crate_loader.maybe_process_path_extern(ident.name,
4718 ident.span) {
4719 let crate_root = self.get_module(DefId {
4720 krate: crate_id,
4721 index: CRATE_DEF_INDEX,
4722 });
4723 self.populate_module_if_necessary(&crate_root);
4724
4725 suggestions.extend(self.lookup_import_candidates_from_module(
4726 lookup_ident, namespace, crate_root, ident, &filter_fn));
4727 }
4728 }
4729 }
4730
4731 suggestions
4732 }
4733
4734 fn find_module(&mut self,
4735 module_def: Def)
4736 -> Option<(Module<'a>, ImportSuggestion)>
4737 {
4738 let mut result = None;
4739 let mut seen_modules = FxHashSet::default();
4740 let mut worklist = vec![(self.graph_root, Vec::new())];
4741
4742 while let Some((in_module, path_segments)) = worklist.pop() {
4743 // abort if the module is already found
4744 if result.is_some() { break; }
4745
4746 self.populate_module_if_necessary(in_module);
4747
4748 in_module.for_each_child_stable(|ident, _, name_binding| {
4749 // abort if the module is already found or if name_binding is private external
4750 if result.is_some() || !name_binding.vis.is_visible_locally() {
4751 return
4752 }
4753 if let Some(module) = name_binding.module() {
4754 // form the path
4755 let mut path_segments = path_segments.clone();
4756 path_segments.push(ast::PathSegment::from_ident(ident));
4757 if module.def() == Some(module_def) {
4758 let path = Path {
4759 span: name_binding.span,
4760 segments: path_segments,
4761 };
4762 result = Some((module, ImportSuggestion { path }));
4763 } else {
4764 // add the module to the lookup
4765 if seen_modules.insert(module.def_id().unwrap()) {
4766 worklist.push((module, path_segments));
4767 }
4768 }
4769 }
4770 });
4771 }
4772
4773 result
4774 }
4775
4776 fn collect_enum_variants(&mut self, enum_def: Def) -> Option<Vec<Path>> {
4777 if let Def::Enum(..) = enum_def {} else {
4778 panic!("Non-enum def passed to collect_enum_variants: {:?}", enum_def)
4779 }
4780
4781 self.find_module(enum_def).map(|(enum_module, enum_import_suggestion)| {
4782 self.populate_module_if_necessary(enum_module);
4783
4784 let mut variants = Vec::new();
4785 enum_module.for_each_child_stable(|ident, _, name_binding| {
4786 if let Def::Variant(..) = name_binding.def() {
4787 let mut segms = enum_import_suggestion.path.segments.clone();
4788 segms.push(ast::PathSegment::from_ident(ident));
4789 variants.push(Path {
4790 span: name_binding.span,
4791 segments: segms,
4792 });
4793 }
4794 });
4795 variants
4796 })
4797 }
4798
4799 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
4800 debug!("(recording def) recording {:?} for {}", resolution, node_id);
4801 if let Some(prev_res) = self.def_map.insert(node_id, resolution) {
4802 panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution);
4803 }
4804 }
4805
4806 fn resolve_visibility(&mut self, vis: &ast::Visibility) -> ty::Visibility {
4807 match vis.node {
4808 ast::VisibilityKind::Public => ty::Visibility::Public,
4809 ast::VisibilityKind::Crate(..) => {
4810 ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))
4811 }
4812 ast::VisibilityKind::Inherited => {
4813 ty::Visibility::Restricted(self.current_module.normal_ancestor_id)
4814 }
4815 ast::VisibilityKind::Restricted { ref path, id, .. } => {
4816 // For visibilities we are not ready to provide correct implementation of "uniform
4817 // paths" right now, so on 2018 edition we only allow module-relative paths for now.
4818 // On 2015 edition visibilities are resolved as crate-relative by default,
4819 // so we are prepending a root segment if necessary.
4820 let ident = path.segments.get(0).expect("empty path in visibility").ident;
4821 let crate_root = if ident.is_path_segment_keyword() {
4822 None
4823 } else if ident.span.rust_2018() {
4824 let msg = "relative paths are not supported in visibilities on 2018 edition";
4825 self.session.struct_span_err(ident.span, msg)
4826 .span_suggestion(path.span, "try", format!("crate::{}", path))
4827 .emit();
4828 return ty::Visibility::Public;
4829 } else {
4830 let ctxt = ident.span.ctxt();
4831 Some(Segment::from_ident(Ident::new(
4832 keywords::PathRoot.name(), path.span.shrink_to_lo().with_ctxt(ctxt)
4833 )))
4834 };
4835
4836 let segments = crate_root.into_iter()
4837 .chain(path.segments.iter().map(|seg| seg.into())).collect::<Vec<_>>();
4838 let def = self.smart_resolve_path_fragment(
4839 id,
4840 None,
4841 &segments,
4842 path.span,
4843 PathSource::Visibility,
4844 CrateLint::SimplePath(id),
4845 ).base_def();
4846 if def == Def::Err {
4847 ty::Visibility::Public
4848 } else {
4849 let vis = ty::Visibility::Restricted(def.def_id());
4850 if self.is_accessible(vis) {
4851 vis
4852 } else {
4853 self.session.span_err(path.span, "visibilities can only be restricted \
4854 to ancestor modules");
4855 ty::Visibility::Public
4856 }
4857 }
4858 }
4859 }
4860 }
4861
4862 fn is_accessible(&self, vis: ty::Visibility) -> bool {
4863 vis.is_accessible_from(self.current_module.normal_ancestor_id, self)
4864 }
4865
4866 fn is_accessible_from(&self, vis: ty::Visibility, module: Module<'a>) -> bool {
4867 vis.is_accessible_from(module.normal_ancestor_id, self)
4868 }
4869
4870 fn set_binding_parent_module(&mut self, binding: &'a NameBinding<'a>, module: Module<'a>) {
4871 if let Some(old_module) = self.binding_parent_modules.insert(PtrKey(binding), module) {
4872 if !ptr::eq(module, old_module) {
4873 span_bug!(binding.span, "parent module is reset for binding");
4874 }
4875 }
4876 }
4877
4878 fn disambiguate_legacy_vs_modern(
4879 &self,
4880 legacy: &'a NameBinding<'a>,
4881 modern: &'a NameBinding<'a>,
4882 ) -> bool {
4883 // Some non-controversial subset of ambiguities "modern macro name" vs "macro_rules"
4884 // is disambiguated to mitigate regressions from macro modularization.
4885 // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general.
4886 match (self.binding_parent_modules.get(&PtrKey(legacy)),
4887 self.binding_parent_modules.get(&PtrKey(modern))) {
4888 (Some(legacy), Some(modern)) =>
4889 legacy.normal_ancestor_id == modern.normal_ancestor_id &&
4890 modern.is_ancestor_of(legacy),
4891 _ => false,
4892 }
4893 }
4894
4895 fn binding_description(&self, b: &NameBinding, ident: Ident, from_prelude: bool) -> String {
4896 if b.span.is_dummy() {
4897 let add_built_in = match b.def() {
4898 // These already contain the "built-in" prefix or look bad with it.
4899 Def::NonMacroAttr(..) | Def::PrimTy(..) | Def::ToolMod => false,
4900 _ => true,
4901 };
4902 let (built_in, from) = if from_prelude {
4903 ("", " from prelude")
4904 } else if b.is_extern_crate() && !b.is_import() &&
4905 self.session.opts.externs.get(&ident.as_str()).is_some() {
4906 ("", " passed with `--extern`")
4907 } else if add_built_in {
4908 (" built-in", "")
4909 } else {
4910 ("", "")
4911 };
4912
4913 let article = if built_in.is_empty() { b.article() } else { "a" };
4914 format!("{a}{built_in} {thing}{from}",
4915 a = article, thing = b.descr(), built_in = built_in, from = from)
4916 } else {
4917 let introduced = if b.is_import() { "imported" } else { "defined" };
4918 format!("the {thing} {introduced} here",
4919 thing = b.descr(), introduced = introduced)
4920 }
4921 }
4922
4923 fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError) {
4924 let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
4925 let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
4926 // We have to print the span-less alternative first, otherwise formatting looks bad.
4927 (b2, b1, misc2, misc1, true)
4928 } else {
4929 (b1, b2, misc1, misc2, false)
4930 };
4931
4932 let mut err = struct_span_err!(self.session, ident.span, E0659,
4933 "`{ident}` is ambiguous ({why})",
4934 ident = ident, why = kind.descr());
4935 err.span_label(ident.span, "ambiguous name");
4936
4937 let mut could_refer_to = |b: &NameBinding, misc: AmbiguityErrorMisc, also: &str| {
4938 let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
4939 let note_msg = format!("`{ident}` could{also} refer to {what}",
4940 ident = ident, also = also, what = what);
4941
4942 let mut help_msgs = Vec::new();
4943 if b.is_glob_import() && (kind == AmbiguityKind::GlobVsGlob ||
4944 kind == AmbiguityKind::GlobVsExpanded ||
4945 kind == AmbiguityKind::GlobVsOuter &&
4946 swapped != also.is_empty()) {
4947 help_msgs.push(format!("consider adding an explicit import of \
4948 `{ident}` to disambiguate", ident = ident))
4949 }
4950 if b.is_extern_crate() && ident.span.rust_2018() {
4951 help_msgs.push(format!(
4952 "use `::{ident}` to refer to this {thing} unambiguously",
4953 ident = ident, thing = b.descr(),
4954 ))
4955 }
4956 if misc == AmbiguityErrorMisc::SuggestCrate {
4957 help_msgs.push(format!(
4958 "use `crate::{ident}` to refer to this {thing} unambiguously",
4959 ident = ident, thing = b.descr(),
4960 ))
4961 } else if misc == AmbiguityErrorMisc::SuggestSelf {
4962 help_msgs.push(format!(
4963 "use `self::{ident}` to refer to this {thing} unambiguously",
4964 ident = ident, thing = b.descr(),
4965 ))
4966 }
4967
4968 if b.span.is_dummy() {
4969 err.note(&note_msg);
4970 } else {
4971 err.span_note(b.span, &note_msg);
4972 }
4973 for (i, help_msg) in help_msgs.iter().enumerate() {
4974 let or = if i == 0 { "" } else { "or " };
4975 err.help(&format!("{}{}", or, help_msg));
4976 }
4977 };
4978
4979 could_refer_to(b1, misc1, "");
4980 could_refer_to(b2, misc2, " also");
4981 err.emit();
4982 }
4983
4984 fn report_errors(&mut self, krate: &Crate) {
4985 self.report_with_use_injections(krate);
4986
4987 for &(span_use, span_def) in &self.macro_expanded_macro_export_errors {
4988 let msg = "macro-expanded `macro_export` macros from the current crate \
4989 cannot be referred to by absolute paths";
4990 self.session.buffer_lint_with_diagnostic(
4991 lint::builtin::MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
4992 CRATE_NODE_ID, span_use, msg,
4993 lint::builtin::BuiltinLintDiagnostics::
4994 MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def),
4995 );
4996 }
4997
4998 for ambiguity_error in &self.ambiguity_errors {
4999 self.report_ambiguity_error(ambiguity_error);
5000 }
5001
5002 let mut reported_spans = FxHashSet::default();
5003 for &PrivacyError(dedup_span, ident, binding) in &self.privacy_errors {
5004 if reported_spans.insert(dedup_span) {
5005 span_err!(self.session, ident.span, E0603, "{} `{}` is private",
5006 binding.descr(), ident.name);
5007 }
5008 }
5009 }
5010
5011 fn report_with_use_injections(&mut self, krate: &Crate) {
5012 for UseError { mut err, candidates, node_id, better } in self.use_injections.drain(..) {
5013 let (span, found_use) = UsePlacementFinder::check(krate, node_id);
5014 if !candidates.is_empty() {
5015 show_candidates(&mut err, span, &candidates, better, found_use);
5016 }
5017 err.emit();
5018 }
5019 }
5020
5021 fn report_conflict<'b>(&mut self,
5022 parent: Module,
5023 ident: Ident,
5024 ns: Namespace,
5025 new_binding: &NameBinding<'b>,
5026 old_binding: &NameBinding<'b>) {
5027 // Error on the second of two conflicting names
5028 if old_binding.span.lo() > new_binding.span.lo() {
5029 return self.report_conflict(parent, ident, ns, old_binding, new_binding);
5030 }
5031
5032 let container = match parent.kind {
5033 ModuleKind::Def(Def::Mod(_), _) => "module",
5034 ModuleKind::Def(Def::Trait(_), _) => "trait",
5035 ModuleKind::Block(..) => "block",
5036 _ => "enum",
5037 };
5038
5039 let old_noun = match old_binding.is_import() {
5040 true => "import",
5041 false => "definition",
5042 };
5043
5044 let new_participle = match new_binding.is_import() {
5045 true => "imported",
5046 false => "defined",
5047 };
5048
5049 let (name, span) = (ident.name, self.session.source_map().def_span(new_binding.span));
5050
5051 if let Some(s) = self.name_already_seen.get(&name) {
5052 if s == &span {
5053 return;
5054 }
5055 }
5056
5057 let old_kind = match (ns, old_binding.module()) {
5058 (ValueNS, _) => "value",
5059 (MacroNS, _) => "macro",
5060 (TypeNS, _) if old_binding.is_extern_crate() => "extern crate",
5061 (TypeNS, Some(module)) if module.is_normal() => "module",
5062 (TypeNS, Some(module)) if module.is_trait() => "trait",
5063 (TypeNS, _) => "type",
5064 };
5065
5066 let msg = format!("the name `{}` is defined multiple times", name);
5067
5068 let mut err = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) {
5069 (true, true) => struct_span_err!(self.session, span, E0259, "{}", msg),
5070 (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() {
5071 true => struct_span_err!(self.session, span, E0254, "{}", msg),
5072 false => struct_span_err!(self.session, span, E0260, "{}", msg),
5073 },
5074 _ => match (old_binding.is_import(), new_binding.is_import()) {
5075 (false, false) => struct_span_err!(self.session, span, E0428, "{}", msg),
5076 (true, true) => struct_span_err!(self.session, span, E0252, "{}", msg),
5077 _ => struct_span_err!(self.session, span, E0255, "{}", msg),
5078 },
5079 };
5080
5081 err.note(&format!("`{}` must be defined only once in the {} namespace of this {}",
5082 name,
5083 ns.descr(),
5084 container));
5085
5086 err.span_label(span, format!("`{}` re{} here", name, new_participle));
5087 if !old_binding.span.is_dummy() {
5088 err.span_label(self.session.source_map().def_span(old_binding.span),
5089 format!("previous {} of the {} `{}` here", old_noun, old_kind, name));
5090 }
5091
5092 // See https://github.com/rust-lang/rust/issues/32354
5093 let directive = match (&new_binding.kind, &old_binding.kind) {
5094 (NameBindingKind::Import { directive, .. }, _) if !new_binding.span.is_dummy() =>
5095 Some((directive, new_binding.span)),
5096 (_, NameBindingKind::Import { directive, .. }) if !old_binding.span.is_dummy() =>
5097 Some((directive, old_binding.span)),
5098 _ => None,
5099 };
5100 if let Some((directive, binding_span)) = directive {
5101 let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() {
5102 format!("Other{}", name)
5103 } else {
5104 format!("other_{}", name)
5105 };
5106
5107 let mut suggestion = None;
5108 match directive.subclass {
5109 ImportDirectiveSubclass::SingleImport { type_ns_only: true, .. } =>
5110 suggestion = Some(format!("self as {}", suggested_name)),
5111 ImportDirectiveSubclass::SingleImport { source, .. } => {
5112 if let Some(pos) = source.span.hi().0.checked_sub(binding_span.lo().0)
5113 .map(|pos| pos as usize) {
5114 if let Ok(snippet) = self.session.source_map()
5115 .span_to_snippet(binding_span) {
5116 if pos <= snippet.len() {
5117 suggestion = Some(format!(
5118 "{} as {}{}",
5119 &snippet[..pos],
5120 suggested_name,
5121 if snippet.ends_with(";") { ";" } else { "" }
5122 ))
5123 }
5124 }
5125 }
5126 }
5127 ImportDirectiveSubclass::ExternCrate { source, target, .. } =>
5128 suggestion = Some(format!(
5129 "extern crate {} as {};",
5130 source.unwrap_or(target.name),
5131 suggested_name,
5132 )),
5133 _ => unreachable!(),
5134 }
5135
5136 let rename_msg = "you can use `as` to change the binding name of the import";
5137 if let Some(suggestion) = suggestion {
5138 err.span_suggestion_with_applicability(
5139 binding_span,
5140 rename_msg,
5141 suggestion,
5142 Applicability::MaybeIncorrect,
5143 );
5144 } else {
5145 err.span_label(binding_span, rename_msg);
5146 }
5147 }
5148
5149 err.emit();
5150 self.name_already_seen.insert(name, span);
5151 }
5152
5153 fn extern_prelude_get(&mut self, ident: Ident, speculative: bool)
5154 -> Option<&'a NameBinding<'a>> {
5155 if ident.is_path_segment_keyword() {
5156 // Make sure `self`, `super` etc produce an error when passed to here.
5157 return None;
5158 }
5159 self.extern_prelude.get(&ident.modern()).cloned().and_then(|entry| {
5160 if let Some(binding) = entry.extern_crate_item {
5161 if !speculative && entry.introduced_by_item {
5162 self.record_use(ident, TypeNS, binding, false);
5163 }
5164 Some(binding)
5165 } else {
5166 let crate_id = if !speculative {
5167 self.crate_loader.process_path_extern(ident.name, ident.span)
5168 } else if let Some(crate_id) =
5169 self.crate_loader.maybe_process_path_extern(ident.name, ident.span) {
5170 crate_id
5171 } else {
5172 return None;
5173 };
5174 let crate_root = self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
5175 self.populate_module_if_necessary(&crate_root);
5176 Some((crate_root, ty::Visibility::Public, DUMMY_SP, Mark::root())
5177 .to_name_binding(self.arenas))
5178 }
5179 })
5180 }
5181 }
5182
5183 fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
5184 namespace == TypeNS && path.len() == 1 && path[0].ident.name == keywords::SelfUpper.name()
5185 }
5186
5187 fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
5188 namespace == ValueNS && path.len() == 1 && path[0].ident.name == keywords::SelfLower.name()
5189 }
5190
5191 fn names_to_string(idents: &[Ident]) -> String {
5192 let mut result = String::new();
5193 for (i, ident) in idents.iter()
5194 .filter(|ident| ident.name != keywords::PathRoot.name())
5195 .enumerate() {
5196 if i > 0 {
5197 result.push_str("::");
5198 }
5199 result.push_str(&ident.as_str());
5200 }
5201 result
5202 }
5203
5204 fn path_names_to_string(path: &Path) -> String {
5205 names_to_string(&path.segments.iter()
5206 .map(|seg| seg.ident)
5207 .collect::<Vec<_>>())
5208 }
5209
5210 /// Get the stringified path for an enum from an `ImportSuggestion` for an enum variant.
5211 fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
5212 let variant_path = &suggestion.path;
5213 let variant_path_string = path_names_to_string(variant_path);
5214
5215 let path_len = suggestion.path.segments.len();
5216 let enum_path = ast::Path {
5217 span: suggestion.path.span,
5218 segments: suggestion.path.segments[0..path_len - 1].to_vec(),
5219 };
5220 let enum_path_string = path_names_to_string(&enum_path);
5221
5222 (variant_path_string, enum_path_string)
5223 }
5224
5225
5226 /// When an entity with a given name is not available in scope, we search for
5227 /// entities with that name in all crates. This method allows outputting the
5228 /// results of this search in a programmer-friendly way
5229 fn show_candidates(err: &mut DiagnosticBuilder,
5230 // This is `None` if all placement locations are inside expansions
5231 span: Option<Span>,
5232 candidates: &[ImportSuggestion],
5233 better: bool,
5234 found_use: bool) {
5235
5236 // we want consistent results across executions, but candidates are produced
5237 // by iterating through a hash map, so make sure they are ordered:
5238 let mut path_strings: Vec<_> =
5239 candidates.into_iter().map(|c| path_names_to_string(&c.path)).collect();
5240 path_strings.sort();
5241
5242 let better = if better { "better " } else { "" };
5243 let msg_diff = match path_strings.len() {
5244 1 => " is found in another module, you can import it",
5245 _ => "s are found in other modules, you can import them",
5246 };
5247 let msg = format!("possible {}candidate{} into scope", better, msg_diff);
5248
5249 if let Some(span) = span {
5250 for candidate in &mut path_strings {
5251 // produce an additional newline to separate the new use statement
5252 // from the directly following item.
5253 let additional_newline = if found_use {
5254 ""
5255 } else {
5256 "\n"
5257 };
5258 *candidate = format!("use {};\n{}", candidate, additional_newline);
5259 }
5260
5261 err.span_suggestions_with_applicability(
5262 span,
5263 &msg,
5264 path_strings.into_iter(),
5265 Applicability::Unspecified,
5266 );
5267 } else {
5268 let mut msg = msg;
5269 msg.push(':');
5270 for candidate in path_strings {
5271 msg.push('\n');
5272 msg.push_str(&candidate);
5273 }
5274 }
5275 }
5276
5277 /// A somewhat inefficient routine to obtain the name of a module.
5278 fn module_to_string(module: Module) -> Option<String> {
5279 let mut names = Vec::new();
5280
5281 fn collect_mod(names: &mut Vec<Ident>, module: Module) {
5282 if let ModuleKind::Def(_, name) = module.kind {
5283 if let Some(parent) = module.parent {
5284 names.push(Ident::with_empty_ctxt(name));
5285 collect_mod(names, parent);
5286 }
5287 } else {
5288 // danger, shouldn't be ident?
5289 names.push(Ident::from_str("<opaque>"));
5290 collect_mod(names, module.parent.unwrap());
5291 }
5292 }
5293 collect_mod(&mut names, module);
5294
5295 if names.is_empty() {
5296 return None;
5297 }
5298 Some(names_to_string(&names.into_iter()
5299 .rev()
5300 .collect::<Vec<_>>()))
5301 }
5302
5303 fn err_path_resolution() -> PathResolution {
5304 PathResolution::new(Def::Err)
5305 }
5306
5307 #[derive(PartialEq,Copy, Clone)]
5308 pub enum MakeGlobMap {
5309 Yes,
5310 No,
5311 }
5312
5313 #[derive(Copy, Clone, Debug)]
5314 enum CrateLint {
5315 /// Do not issue the lint
5316 No,
5317
5318 /// This lint applies to some random path like `impl ::foo::Bar`
5319 /// or whatever. In this case, we can take the span of that path.
5320 SimplePath(NodeId),
5321
5322 /// This lint comes from a `use` statement. In this case, what we
5323 /// care about really is the *root* `use` statement; e.g., if we
5324 /// have nested things like `use a::{b, c}`, we care about the
5325 /// `use a` part.
5326 UsePath { root_id: NodeId, root_span: Span },
5327
5328 /// This is the "trait item" from a fully qualified path. For example,
5329 /// we might be resolving `X::Y::Z` from a path like `<T as X::Y>::Z`.
5330 /// The `path_span` is the span of the to the trait itself (`X::Y`).
5331 QPathTrait { qpath_id: NodeId, qpath_span: Span },
5332 }
5333
5334 impl CrateLint {
5335 fn node_id(&self) -> Option<NodeId> {
5336 match *self {
5337 CrateLint::No => None,
5338 CrateLint::SimplePath(id) |
5339 CrateLint::UsePath { root_id: id, .. } |
5340 CrateLint::QPathTrait { qpath_id: id, .. } => Some(id),
5341 }
5342 }
5343 }
5344
5345 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }