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