1 use crate::diagnostics
::{ImportSuggestion, LabelSuggestion, TypoSuggestion}
;
2 use crate::late
::lifetimes
::{ElisionFailureInfo, LifetimeContext}
;
3 use crate::late
::{AliasPossibility, LateResolutionVisitor, RibKind}
;
4 use crate::path_names_to_string
;
5 use crate::{CrateLint, Module, ModuleKind, ModuleOrUniformRoot}
;
6 use crate::{PathResult, PathSource, Segment}
;
8 use rustc_ast
::visit
::FnKind
;
10 self as ast
, AssocItemKind
, Expr
, ExprKind
, GenericParam
, GenericParamKind
, Item
, ItemKind
,
11 NodeId
, Path
, Ty
, TyKind
,
13 use rustc_ast_pretty
::pprust
::path_segment_to_string
;
14 use rustc_data_structures
::fx
::FxHashSet
;
15 use rustc_errors
::{pluralize, struct_span_err, Applicability, DiagnosticBuilder}
;
17 use rustc_hir
::def
::Namespace
::{self, *}
;
18 use rustc_hir
::def
::{self, CtorKind, CtorOf, DefKind}
;
19 use rustc_hir
::def_id
::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE}
;
20 use rustc_hir
::PrimTy
;
21 use rustc_session
::parse
::feature_err
;
22 use rustc_span
::edition
::Edition
;
23 use rustc_span
::hygiene
::MacroKind
;
24 use rustc_span
::lev_distance
::find_best_match_for_name
;
25 use rustc_span
::symbol
::{kw, sym, Ident, Symbol}
;
26 use rustc_span
::{BytePos, MultiSpan, Span, DUMMY_SP}
;
32 type Res
= def
::Res
<ast
::NodeId
>;
34 /// A field or associated item from self type suggested in case of resolution failure.
35 enum AssocSuggestion
{
43 impl AssocSuggestion
{
44 fn action(&self) -> &'
static str {
46 AssocSuggestion
::Field
=> "use the available field",
47 AssocSuggestion
::MethodWithSelf
=> "call the method with the fully-qualified path",
48 AssocSuggestion
::AssocFn
=> "call the associated function",
49 AssocSuggestion
::AssocConst
=> "use the associated `const`",
50 AssocSuggestion
::AssocType
=> "use the associated type",
55 crate enum MissingLifetimeSpot
<'tcx
> {
56 Generics(&'tcx hir
::Generics
<'tcx
>),
57 HigherRanked { span: Span, span_type: ForLifetimeSpanType }
,
61 crate enum ForLifetimeSpanType
{
68 impl ForLifetimeSpanType
{
69 crate fn descr(&self) -> &'
static str {
71 Self::BoundEmpty
| Self::BoundTail
=> "bound",
72 Self::TypeEmpty
| Self::TypeTail
=> "type",
76 crate fn suggestion(&self, sugg
: &str) -> String
{
78 Self::BoundEmpty
| Self::TypeEmpty
=> format
!("for<{}> ", sugg
),
79 Self::BoundTail
| Self::TypeTail
=> format
!(", {}", sugg
),
84 impl<'tcx
> Into
<MissingLifetimeSpot
<'tcx
>> for &'tcx hir
::Generics
<'tcx
> {
85 fn into(self) -> MissingLifetimeSpot
<'tcx
> {
86 MissingLifetimeSpot
::Generics(self)
90 fn is_self_type(path
: &[Segment
], namespace
: Namespace
) -> bool
{
91 namespace
== TypeNS
&& path
.len() == 1 && path
[0].ident
.name
== kw
::SelfUpper
94 fn is_self_value(path
: &[Segment
], namespace
: Namespace
) -> bool
{
95 namespace
== ValueNS
&& path
.len() == 1 && path
[0].ident
.name
== kw
::SelfLower
98 /// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
99 fn import_candidate_to_enum_paths(suggestion
: &ImportSuggestion
) -> (String
, String
) {
100 let variant_path
= &suggestion
.path
;
101 let variant_path_string
= path_names_to_string(variant_path
);
103 let path_len
= suggestion
.path
.segments
.len();
104 let enum_path
= ast
::Path
{
105 span
: suggestion
.path
.span
,
106 segments
: suggestion
.path
.segments
[0..path_len
- 1].to_vec(),
109 let enum_path_string
= path_names_to_string(&enum_path
);
111 (variant_path_string
, enum_path_string
)
114 impl<'a
: 'ast
, 'ast
> LateResolutionVisitor
<'a
, '_
, 'ast
> {
115 fn def_span(&self, def_id
: DefId
) -> Option
<Span
> {
117 LOCAL_CRATE
=> self.r
.opt_span(def_id
),
122 .guess_head_span(self.r
.cstore().get_span_untracked(def_id
, self.r
.session
)),
127 /// Handles error reporting for `smart_resolve_path_fragment` function.
128 /// Creates base error and amends it with one short label and possibly some longer helps/notes.
129 pub(crate) fn smart_resolve_report_errors(
133 source
: PathSource
<'_
>,
135 ) -> (DiagnosticBuilder
<'a
>, Vec
<ImportSuggestion
>) {
136 let ident_span
= path
.last().map_or(span
, |ident
| ident
.ident
.span
);
137 let ns
= source
.namespace();
138 let is_expected
= &|res
| source
.is_expected(res
);
139 let is_enum_variant
= &|res
| matches
!(res
, Res
::Def(DefKind
::Variant
, _
));
141 // Make the base error.
142 let mut expected
= source
.descr_expected();
143 let path_str
= Segment
::names_to_string(path
);
144 let item_str
= path
.last().unwrap().ident
;
145 let (base_msg
, fallback_label
, base_span
, could_be_expr
) = if let Some(res
) = res
{
147 format
!("expected {}, found {} `{}`", expected
, res
.descr(), path_str
),
148 format
!("not a {}", expected
),
151 Res
::Def(DefKind
::Fn
, _
) => {
152 // Verify whether this is a fn call or an Fn used as a type.
156 .span_to_snippet(span
)
157 .map(|snippet
| snippet
.ends_with('
)'
))
161 DefKind
::Ctor(..) | DefKind
::AssocFn
| DefKind
::Const
| DefKind
::AssocConst
,
166 | Res
::Local(_
) => true,
171 let item_span
= path
.last().unwrap().ident
.span
;
172 let (mod_prefix
, mod_str
) = if path
.len() == 1 {
173 (String
::new(), "this scope".to_string())
174 } else if path
.len() == 2 && path
[0].ident
.name
== kw
::PathRoot
{
175 if self.r
.session
.edition() > Edition
::Edition2015
{
176 // In edition 2018 onwards, the `::foo` syntax may only pull from the extern prelude
177 // which overrides all other expectations of item type
179 (String
::new(), "the list of imported crates".to_string())
181 (String
::new(), "the crate root".to_string())
183 } else if path
.len() == 2 && path
[0].ident
.name
== kw
::Crate
{
184 (String
::new(), "the crate root".to_string())
186 let mod_path
= &path
[..path
.len() - 1];
188 match self.resolve_path(mod_path
, Some(TypeNS
), false, span
, CrateLint
::No
) {
189 PathResult
::Module(ModuleOrUniformRoot
::Module(module
)) => module
.res(),
192 .map_or_else(String
::new
, |res
| format
!("{} ", res
.descr()));
193 (mod_prefix
, format
!("`{}`", Segment
::names_to_string(mod_path
)))
196 format
!("cannot find {} `{}` in {}{}", expected
, item_str
, mod_prefix
, mod_str
),
197 if path_str
== "async" && expected
.starts_with("struct") {
198 "`async` blocks are only allowed in Rust 2018 or later".to_string()
200 format
!("not found in {}", mod_str
)
207 let code
= source
.error_code(res
.is_some());
208 let mut err
= self.r
.session
.struct_span_err_with_code(base_span
, &base_msg
, code
);
210 if let Some(span
) = self.diagnostic_metadata
.current_block_could_be_bare_struct_literal
{
211 err
.multipart_suggestion(
212 "you might have meant to write a `struct` literal",
214 (span
.shrink_to_lo(), "{ SomeStruct ".to_string()),
215 (span
.shrink_to_hi(), "}".to_string()),
217 Applicability
::HasPlaceholders
,
220 match (source
, self.diagnostic_metadata
.in_if_condition
) {
221 (PathSource
::Expr(_
), Some(Expr { span, kind: ExprKind::Assign(..), .. }
)) => {
222 err
.span_suggestion_verbose(
224 "you might have meant to use pattern matching",
226 Applicability
::MaybeIncorrect
,
232 let is_assoc_fn
= self.self_type_is_available(span
);
233 // Emit help message for fake-self from other languages (e.g., `this` in Javascript).
234 if ["this", "my"].contains(&&*item_str
.as_str()) && is_assoc_fn
{
235 err
.span_suggestion_short(
237 "you might have meant to use `self` here instead",
239 Applicability
::MaybeIncorrect
,
241 if !self.self_value_is_available(path
[0].ident
.span
, span
) {
242 if let Some((FnKind
::Fn(_
, _
, sig
, ..), fn_span
)) =
243 &self.diagnostic_metadata
.current_function
245 let (span
, sugg
) = if let Some(param
) = sig
.decl
.inputs
.get(0) {
246 (param
.span
.shrink_to_lo(), "&self, ")
252 .span_through_char(*fn_span
, '
('
)
257 err
.span_suggestion_verbose(
259 "if you meant to use `self`, you are also missing a `self` receiver \
262 Applicability
::MaybeIncorrect
,
268 // Emit special messages for unresolved `Self` and `self`.
269 if is_self_type(path
, ns
) {
270 err
.code(rustc_errors
::error_code
!(E0411
));
273 "`Self` is only available in impls, traits, and type definitions".to_string(),
275 return (err
, Vec
::new());
277 if is_self_value(path
, ns
) {
278 debug
!("smart_resolve_path_fragment: E0424, source={:?}", source
);
280 err
.code(rustc_errors
::error_code
!(E0424
));
281 err
.span_label(span
, match source
{
282 PathSource
::Pat
=> "`self` value is a keyword and may not be bound to variables or shadowed"
284 _
=> "`self` value is a keyword only available in methods with a `self` parameter"
287 if let Some((fn_kind
, span
)) = &self.diagnostic_metadata
.current_function
{
288 // The current function has a `self' parameter, but we were unable to resolve
289 // a reference to `self`. This can only happen if the `self` identifier we
290 // are resolving came from a different hygiene context.
291 if fn_kind
.decl().inputs
.get(0).map_or(false, |p
| p
.is_self()) {
292 err
.span_label(*span
, "this function has a `self` parameter, but a macro invocation can only access identifiers it receives from parameters");
294 let doesnt
= if is_assoc_fn
{
295 let (span
, sugg
) = fn_kind
299 .map(|p
| (p
.span
.shrink_to_lo(), "&self, "))
305 .span_through_char(*span
, '
('
)
310 err
.span_suggestion_verbose(
312 "add a `self` receiver parameter to make the associated `fn` a method",
314 Applicability
::MaybeIncorrect
,
320 if let Some(ident
) = fn_kind
.ident() {
323 &format
!("this function {} have a `self` parameter", doesnt
),
328 return (err
, Vec
::new());
331 // Try to lookup name in more relaxed fashion for better error reporting.
332 let ident
= path
.last().unwrap().ident
;
333 let candidates
= self
335 .lookup_import_candidates(ident
, ns
, &self.parent_scope
, is_expected
)
337 .filter(|ImportSuggestion { did, .. }
| {
338 match (did
, res
.and_then(|res
| res
.opt_def_id())) {
339 (Some(suggestion_did
), Some(actual_did
)) => *suggestion_did
!= actual_did
,
343 .collect
::<Vec
<_
>>();
344 let crate_def_id
= DefId
::local(CRATE_DEF_INDEX
);
345 if candidates
.is_empty() && is_expected(Res
::Def(DefKind
::Enum
, crate_def_id
)) {
346 let mut enum_candidates
: Vec
<_
> = self
348 .lookup_import_candidates(ident
, ns
, &self.parent_scope
, is_enum_variant
)
350 .map(|suggestion
| import_candidate_to_enum_paths(&suggestion
))
351 .filter(|(_
, enum_ty_path
)| !enum_ty_path
.starts_with("std::prelude::"))
353 if !enum_candidates
.is_empty() {
354 if let (PathSource
::Type
, Some(span
)) =
355 (source
, self.diagnostic_metadata
.current_type_ascription
.last())
361 .type_ascription_path_suggestions
365 // Already reported this issue on the lhs of the type ascription.
367 return (err
, candidates
);
371 enum_candidates
.sort();
373 // Contextualize for E0412 "cannot find type", but don't belabor the point
374 // (that it's a variant) for E0573 "expected type, found variant".
375 let preamble
= if res
.is_none() {
376 let others
= match enum_candidates
.len() {
378 2 => " and 1 other".to_owned(),
379 n
=> format
!(" and {} others", n
),
381 format
!("there is an enum variant `{}`{}; ", enum_candidates
[0].0, others
)
385 let msg
= format
!("{}try using the variant's enum", preamble
);
387 err
.span_suggestions(
390 enum_candidates
.into_iter().map(|(_variant_path
, enum_ty_path
)| enum_ty_path
),
391 Applicability
::MachineApplicable
,
395 if path
.len() == 1 && self.self_type_is_available(span
) {
396 if let Some(candidate
) = self.lookup_assoc_candidate(ident
, ns
, is_expected
) {
397 let self_is_available
= self.self_value_is_available(path
[0].ident
.span
, span
);
399 AssocSuggestion
::Field
=> {
400 if self_is_available
{
403 "you might have meant to use the available field",
404 format
!("self.{}", path_str
),
405 Applicability
::MachineApplicable
,
408 err
.span_label(span
, "a field by this name exists in `Self`");
411 AssocSuggestion
::MethodWithSelf
if self_is_available
=> {
414 "you might have meant to call the method",
415 format
!("self.{}", path_str
),
416 Applicability
::MachineApplicable
,
419 AssocSuggestion
::MethodWithSelf
420 | AssocSuggestion
::AssocFn
421 | AssocSuggestion
::AssocConst
422 | AssocSuggestion
::AssocType
=> {
425 &format
!("you might have meant to {}", candidate
.action()),
426 format
!("Self::{}", path_str
),
427 Applicability
::MachineApplicable
,
431 return (err
, candidates
);
434 // If the first argument in call is `self` suggest calling a method.
435 if let Some((call_span
, args_span
)) = self.call_has_self_arg(source
) {
436 let mut args_snippet
= String
::new();
437 if let Some(args_span
) = args_span
{
438 if let Ok(snippet
) = self.r
.session
.source_map().span_to_snippet(args_span
) {
439 args_snippet
= snippet
;
445 &format
!("try calling `{}` as a method", ident
),
446 format
!("self.{}({})", path_str
, args_snippet
),
447 Applicability
::MachineApplicable
,
449 return (err
, candidates
);
453 // Try Levenshtein algorithm.
454 let typo_sugg
= self.lookup_typo_candidate(path
, ns
, is_expected
, span
);
455 // Try context-dependent help if relaxed lookup didn't work.
456 if let Some(res
) = res
{
457 if self.smart_resolve_context_dependent_help(
465 // We do this to avoid losing a secondary span when we override the main error span.
466 self.r
.add_typo_suggestion(&mut err
, typo_sugg
, ident_span
);
467 return (err
, candidates
);
471 let is_macro
= base_span
.from_expansion() && base_span
.desugaring_kind().is_none();
472 if !self.type_ascription_suggestion(&mut err
, base_span
) {
473 let mut fallback
= false;
475 PathSource
::Trait(AliasPossibility
::Maybe
),
476 Some(Res
::Def(DefKind
::Struct
| DefKind
::Enum
| DefKind
::Union
, _
)),
478 ) = (source
, res
, is_macro
)
480 if let Some(bounds @
[_
, .., _
]) = self.diagnostic_metadata
.current_trait_object
{
482 let spans
: Vec
<Span
> = bounds
484 .map(|bound
| bound
.span())
485 .filter(|&sp
| sp
!= base_span
)
488 let start_span
= bounds
.iter().map(|bound
| bound
.span()).next().unwrap();
489 // `end_span` is the end of the poly trait ref (Foo + 'baz + Bar><)
490 let end_span
= bounds
.iter().map(|bound
| bound
.span()).last().unwrap();
491 // `last_bound_span` is the last bound of the poly trait ref (Foo + >'baz< + Bar)
492 let last_bound_span
= spans
.last().cloned().unwrap();
493 let mut multi_span
: MultiSpan
= spans
.clone().into();
495 let msg
= if sp
== last_bound_span
{
497 "...because of {} bound{}",
498 if bounds
.len() <= 2 { "this" }
else { "these" }
,
499 if bounds
.len() <= 2 { "" }
else { "s" }
,
504 multi_span
.push_span_label(sp
, msg
);
506 multi_span
.push_span_label(
508 "expected this type to be a trait...".to_string(),
512 "`+` is used to constrain a \"trait object\" type with lifetimes or \
513 auto-traits; structs and enums can't be bound in that way",
515 if bounds
.iter().all(|bound
| match bound
{
516 ast
::GenericBound
::Outlives(_
) => true,
517 ast
::GenericBound
::Trait(tr
, _
) => tr
.span
== base_span
,
519 let mut sugg
= vec
![];
520 if base_span
!= start_span
{
521 sugg
.push((start_span
.until(base_span
), String
::new()));
523 if base_span
!= end_span
{
524 sugg
.push((base_span
.shrink_to_hi().to(end_span
), String
::new()));
527 err
.multipart_suggestion(
528 "if you meant to use a type and not a trait here, remove the bounds",
530 Applicability
::MaybeIncorrect
,
536 fallback
|= self.restrict_assoc_type_in_where_clause(span
, &mut err
);
538 if !self.r
.add_typo_suggestion(&mut err
, typo_sugg
, ident_span
) {
540 match self.diagnostic_metadata
.current_let_binding
{
541 Some((pat_sp
, Some(ty_sp
), None
))
542 if ty_sp
.contains(base_span
) && could_be_expr
=>
544 err
.span_suggestion_short(
545 pat_sp
.between(ty_sp
),
546 "use `=` if you meant to assign",
548 Applicability
::MaybeIncorrect
,
554 // If the trait has a single item (which wasn't matched by Levenshtein), suggest it
555 let suggestion
= self.get_single_associated_item(&path
, span
, &source
, is_expected
);
556 self.r
.add_typo_suggestion(&mut err
, suggestion
, ident_span
);
560 err
.span_label(base_span
, fallback_label
);
563 if let Some(err_code
) = &err
.code
{
564 if err_code
== &rustc_errors
::error_code
!(E0425
) {
565 for label_rib
in &self.label_ribs
{
566 for (label_ident
, node_id
) in &label_rib
.bindings
{
567 if format
!("'{}", ident
) == label_ident
.to_string() {
568 err
.span_label(label_ident
.span
, "a label with a similar name exists");
569 if let PathSource
::Expr(Some(Expr
{
570 kind
: ExprKind
::Break(None
, Some(_
)),
576 "use the similarly named label",
577 label_ident
.name
.to_string(),
578 Applicability
::MaybeIncorrect
,
580 // Do not lint against unused label when we suggest them.
581 self.diagnostic_metadata
.unused_labels
.remove(node_id
);
586 } else if err_code
== &rustc_errors
::error_code
!(E0412
) {
587 if let Some(correct
) = Self::likely_rust_type(path
) {
590 "perhaps you intended to use this type",
592 Applicability
::MaybeIncorrect
,
601 fn get_single_associated_item(
605 source
: &PathSource
<'_
>,
606 filter_fn
: &impl Fn(Res
) -> bool
,
607 ) -> Option
<TypoSuggestion
> {
608 if let crate::PathSource
::TraitItem(_
) = source
{
609 let mod_path
= &path
[..path
.len() - 1];
610 if let PathResult
::Module(ModuleOrUniformRoot
::Module(module
)) =
611 self.resolve_path(mod_path
, None
, false, span
, CrateLint
::No
)
613 let resolutions
= self.r
.resolutions(module
).borrow();
614 let targets
: Vec
<_
> =
617 .filter_map(|(key
, resolution
)| {
618 resolution
.borrow().binding
.map(|binding
| binding
.res()).and_then(
619 |res
| if filter_fn(res
) { Some((key, res)) }
else { None }
,
623 if targets
.len() == 1 {
624 let target
= targets
[0];
625 return Some(TypoSuggestion
::single_item_from_res(
635 /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
636 fn restrict_assoc_type_in_where_clause(
639 err
: &mut DiagnosticBuilder
<'_
>,
641 // Detect that we are actually in a `where` predicate.
642 let (bounded_ty
, bounds
, where_span
) =
643 if let Some(ast
::WherePredicate
::BoundPredicate(ast
::WhereBoundPredicate
{
645 bound_generic_params
,
648 })) = self.diagnostic_metadata
.current_where_predicate
650 if !bound_generic_params
.is_empty() {
653 (bounded_ty
, bounds
, span
)
658 // Confirm that the target is an associated type.
659 let (ty
, position
, path
) = if let ast
::TyKind
::Path(
660 Some(ast
::QSelf { ty, position, .. }
),
664 // use this to verify that ident is a type param.
665 let partial_res
= if let Ok(Some(partial_res
)) = self.resolve_qpath_anywhere(
668 &Segment
::from_path(path
),
679 partial_res
.base_res(),
680 hir
::def
::Res
::Def(hir
::def
::DefKind
::AssocTy
, _
)
681 ) && partial_res
.unresolved_segments() == 0)
690 if let ast
::TyKind
::Path(None
, type_param_path
) = &ty
.peel_refs().kind
{
691 // Confirm that the `SelfTy` is a type parameter.
692 let partial_res
= if let Ok(Some(partial_res
)) = self.resolve_qpath_anywhere(
695 &Segment
::from_path(type_param_path
),
706 partial_res
.base_res(),
707 hir
::def
::Res
::Def(hir
::def
::DefKind
::TyParam
, _
)
708 ) && partial_res
.unresolved_segments() == 0)
713 [ast
::PathSegment { ident: constrain_ident, args: None, .. }
],
714 [ast
::GenericBound
::Trait(poly_trait_ref
, ast
::TraitBoundModifier
::None
)],
715 ) = (&type_param_path
.segments
[..], &bounds
[..])
717 if let [ast
::PathSegment { ident, args: None, .. }
] =
718 &poly_trait_ref
.trait_ref
.path
.segments
[..]
720 if ident
.span
== span
{
721 err
.span_suggestion_verbose(
723 &format
!("constrain the associated type to `{}`", ident
),
729 .span_to_snippet(ty
.span
) // Account for `<&'a T as Foo>::Bar`.
730 .unwrap_or_else(|_
| constrain_ident
.to_string()),
731 path
.segments
[..*position
]
733 .map(|segment
| path_segment_to_string(segment
))
736 path
.segments
[*position
..]
738 .map(|segment
| path_segment_to_string(segment
))
743 Applicability
::MaybeIncorrect
,
753 /// Check if the source is call expression and the first argument is `self`. If true,
754 /// return the span of whole call and the span for all arguments expect the first one (`self`).
755 fn call_has_self_arg(&self, source
: PathSource
<'_
>) -> Option
<(Span
, Option
<Span
>)> {
756 let mut has_self_arg
= None
;
757 if let PathSource
::Expr(Some(parent
)) = source
{
759 ExprKind
::Call(_
, args
) if !args
.is_empty() => {
760 let mut expr_kind
= &args
[0].kind
;
763 ExprKind
::Path(_
, arg_name
) if arg_name
.segments
.len() == 1 => {
764 if arg_name
.segments
[0].ident
.name
== kw
::SelfLower
{
765 let call_span
= parent
.span
;
766 let tail_args_span
= if args
.len() > 1 {
769 args
.last().unwrap().span
.hi(),
776 has_self_arg
= Some((call_span
, tail_args_span
));
780 ExprKind
::AddrOf(_
, _
, expr
) => expr_kind
= &expr
.kind
,
791 fn followed_by_brace(&self, span
: Span
) -> (bool
, Option
<Span
>) {
792 // HACK(estebank): find a better way to figure out that this was a
793 // parser issue where a struct literal is being used on an expression
794 // where a brace being opened means a block is being started. Look
795 // ahead for the next text to see if `span` is followed by a `{`.
796 let sm
= self.r
.session
.source_map();
799 sp
= sm
.next_point(sp
);
800 match sm
.span_to_snippet(sp
) {
802 if snippet
.chars().any(|c
| !c
.is_whitespace()) {
809 let followed_by_brace
= matches
!(sm
.span_to_snippet(sp
), Ok(ref snippet
) if snippet
== "{");
810 // In case this could be a struct literal that needs to be surrounded
811 // by parentheses, find the appropriate span.
813 let mut closing_brace
= None
;
815 sp
= sm
.next_point(sp
);
816 match sm
.span_to_snippet(sp
) {
819 closing_brace
= Some(span
.to(sp
));
826 // The bigger the span, the more likely we're incorrect --
827 // bound it to 100 chars long.
832 (followed_by_brace
, closing_brace
)
835 /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
837 /// Returns `true` if able to provide context-dependent help.
838 fn smart_resolve_context_dependent_help(
840 err
: &mut DiagnosticBuilder
<'a
>,
842 source
: PathSource
<'_
>,
845 fallback_label
: &str,
847 let ns
= source
.namespace();
848 let is_expected
= &|res
| source
.is_expected(res
);
850 let path_sep
= |err
: &mut DiagnosticBuilder
<'_
>, expr
: &Expr
| match expr
.kind
{
851 ExprKind
::Field(_
, ident
) => {
854 "use the path separator to refer to an item",
855 format
!("{}::{}", path_str
, ident
),
856 Applicability
::MaybeIncorrect
,
860 ExprKind
::MethodCall(ref segment
, ..) => {
861 let span
= expr
.span
.with_hi(segment
.ident
.span
.hi());
864 "use the path separator to refer to an item",
865 format
!("{}::{}", path_str
, segment
.ident
),
866 Applicability
::MaybeIncorrect
,
873 let find_span
= |source
: &PathSource
<'_
>, err
: &mut DiagnosticBuilder
<'_
>| {
875 PathSource
::Expr(Some(Expr { span, kind: ExprKind::Call(_, _), .. }
))
876 | PathSource
::TupleStruct(span
, _
) => {
877 // We want the main underline to cover the suggested code as well for
886 let mut bad_struct_syntax_suggestion
= |def_id
: DefId
| {
887 let (followed_by_brace
, closing_brace
) = self.followed_by_brace(span
);
890 PathSource
::Expr(Some(
891 parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. }
,
892 )) if path_sep(err
, &parent
) => {}
898 | ExprKind
::Binary(..)
899 | ExprKind
::Unary(..)
901 | ExprKind
::While(..)
902 | ExprKind
::ForLoop(..)
903 | ExprKind
::Match(..),
906 ) if followed_by_brace
=> {
907 if let Some(sp
) = closing_brace
{
908 err
.span_label(span
, fallback_label
);
909 err
.multipart_suggestion(
910 "surround the struct literal with parentheses",
912 (sp
.shrink_to_lo(), "(".to_string()),
913 (sp
.shrink_to_hi(), ")".to_string()),
915 Applicability
::MaybeIncorrect
,
919 span
, // Note the parentheses surrounding the suggestion below
921 "you might want to surround a struct literal with parentheses: \
922 `({} {{ /* fields */ }})`?",
928 PathSource
::Expr(_
) | PathSource
::TupleStruct(..) | PathSource
::Pat
=> {
929 let span
= find_span(&source
, err
);
930 if let Some(span
) = self.def_span(def_id
) {
931 err
.span_label(span
, &format
!("`{}` defined here", path_str
));
933 let (tail
, descr
, applicability
) = match source
{
934 PathSource
::Pat
| PathSource
::TupleStruct(..) => {
935 ("", "pattern", Applicability
::MachineApplicable
)
937 _
=> (": val", "literal", Applicability
::HasPlaceholders
),
939 let (fields
, applicability
) = match self.r
.field_names
.get(&def_id
) {
943 .map(|f
| format
!("{}{}", f
.node
, tail
))
944 .collect
::<Vec
<String
>>()
948 None
=> ("/* fields */".to_string(), Applicability
::HasPlaceholders
),
950 let pad
= match self.r
.field_names
.get(&def_id
) {
951 Some(fields
) if fields
.is_empty() => "",
956 &format
!("use struct {} syntax instead", descr
),
957 format
!("{path_str} {{{pad}{fields}{pad}}}"),
962 err
.span_label(span
, fallback_label
);
967 match (res
, source
) {
968 (Res
::Def(DefKind
::Macro(MacroKind
::Bang
), _
), _
) => {
969 err
.span_label(span
, fallback_label
);
970 err
.span_suggestion_verbose(
972 "use `!` to invoke the macro",
974 Applicability
::MaybeIncorrect
,
976 if path_str
== "try" && span
.rust_2015() {
977 err
.note("if you want the `try` keyword, you need Rust 2018 or later");
980 (Res
::Def(DefKind
::TyAlias
, def_id
), PathSource
::Trait(_
)) => {
981 err
.span_label(span
, "type aliases cannot be used as traits");
982 if self.r
.session
.is_nightly_build() {
983 let msg
= "you might have meant to use `#![feature(trait_alias)]` instead of a \
985 if let Some(span
) = self.def_span(def_id
) {
986 if let Ok(snip
) = self.r
.session
.source_map().span_to_snippet(span
) {
987 // The span contains a type alias so we should be able to
988 // replace `type` with `trait`.
989 let snip
= snip
.replacen("type", "trait", 1);
990 err
.span_suggestion(span
, msg
, snip
, Applicability
::MaybeIncorrect
);
992 err
.span_help(span
, msg
);
999 (Res
::Def(DefKind
::Mod
, _
), PathSource
::Expr(Some(parent
))) => {
1000 if !path_sep(err
, &parent
) {
1005 Res
::Def(DefKind
::Enum
, def_id
),
1006 PathSource
::TupleStruct(..) | PathSource
::Expr(..),
1009 .diagnostic_metadata
1010 .current_type_ascription
1016 .type_ascription_path_suggestions
1023 // We already suggested changing `:` into `::` during parsing.
1027 self.suggest_using_enum_variant(err
, source
, def_id
, span
);
1029 (Res
::Def(DefKind
::Struct
, def_id
), source
) if ns
== ValueNS
=> {
1030 let (ctor_def
, ctor_vis
, fields
) =
1031 if let Some(struct_ctor
) = self.r
.struct_constructors
.get(&def_id
).cloned() {
1032 if let PathSource
::Expr(Some(parent
)) = source
{
1033 if let ExprKind
::Field(..) | ExprKind
::MethodCall(..) = parent
.kind
{
1034 bad_struct_syntax_suggestion(def_id
);
1040 bad_struct_syntax_suggestion(def_id
);
1044 let is_accessible
= self.r
.is_accessible_from(ctor_vis
, self.parent_scope
.module
);
1045 if !is_expected(ctor_def
) || is_accessible
{
1049 let field_spans
= match source
{
1050 // e.g. `if let Enum::TupleVariant(field1, field2) = _`
1051 PathSource
::TupleStruct(_
, pattern_spans
) => {
1052 err
.set_primary_message(
1053 "cannot match against a tuple struct which contains private fields",
1056 // Use spans of the tuple struct pattern.
1057 Some(Vec
::from(pattern_spans
))
1059 // e.g. `let _ = Enum::TupleVariant(field1, field2);`
1060 _
if source
.is_call() => {
1061 err
.set_primary_message(
1062 "cannot initialize a tuple struct which contains private fields",
1065 // Use spans of the tuple struct definition.
1069 .map(|fields
| fields
.iter().map(|f
| f
.span
).collect
::<Vec
<_
>>())
1074 if let Some(spans
) =
1075 field_spans
.filter(|spans
| spans
.len() > 0 && fields
.len() == spans
.len())
1077 let non_visible_spans
: Vec
<Span
> = iter
::zip(&fields
, &spans
)
1078 .filter(|(vis
, _
)| {
1079 !self.r
.is_accessible_from(**vis
, self.parent_scope
.module
)
1081 .map(|(_
, span
)| *span
)
1084 if non_visible_spans
.len() > 0 {
1085 let mut m
: rustc_span
::MultiSpan
= non_visible_spans
.clone().into();
1088 .for_each(|s
| m
.push_span_label(s
, "private field".to_string()));
1089 err
.span_note(m
, "constructor is not visible here due to private fields");
1097 "constructor is not visible here due to private fields".to_string(),
1102 DefKind
::Union
| DefKind
::Variant
| DefKind
::Ctor(_
, CtorKind
::Fictive
),
1106 ) if ns
== ValueNS
=> {
1107 bad_struct_syntax_suggestion(def_id
);
1109 (Res
::Def(DefKind
::Ctor(_
, CtorKind
::Const
), def_id
), _
) if ns
== ValueNS
=> {
1111 PathSource
::Expr(_
) | PathSource
::TupleStruct(..) | PathSource
::Pat
=> {
1112 let span
= find_span(&source
, err
);
1113 if let Some(span
) = self.def_span(def_id
) {
1114 err
.span_label(span
, &format
!("`{}` defined here", path_str
));
1116 err
.span_suggestion(
1118 &"use this syntax instead",
1119 format
!("{path_str}"),
1120 Applicability
::MaybeIncorrect
,
1126 (Res
::Def(DefKind
::Ctor(_
, CtorKind
::Fn
), def_id
), _
) if ns
== ValueNS
=> {
1127 if let Some(span
) = self.def_span(def_id
) {
1128 err
.span_label(span
, &format
!("`{}` defined here", path_str
));
1130 let fields
= self.r
.field_names
.get(&def_id
).map_or_else(
1131 || "/* fields */".to_string(),
1132 |fields
| vec
!["_"; fields
.len()].join(", "),
1134 err
.span_suggestion(
1136 "use the tuple variant pattern syntax instead",
1137 format
!("{}({})", path_str
, fields
),
1138 Applicability
::HasPlaceholders
,
1141 (Res
::SelfTy(..), _
) if ns
== ValueNS
=> {
1142 err
.span_label(span
, fallback_label
);
1143 err
.note("can't use `Self` as a constructor, you must use the implemented struct");
1145 (Res
::Def(DefKind
::TyAlias
| DefKind
::AssocTy
, _
), _
) if ns
== ValueNS
=> {
1146 err
.note("can't use a type alias as a constructor");
1153 /// Given the target `ident` and `kind`, search for the similarly named associated item
1154 /// in `self.current_trait_ref`.
1155 crate fn find_similarly_named_assoc_item(
1158 kind
: &AssocItemKind
,
1159 ) -> Option
<Symbol
> {
1160 let module
= if let Some((module
, _
)) = self.current_trait_ref
{
1165 if ident
== kw
::Underscore
{
1166 // We do nothing for `_`.
1170 let resolutions
= self.r
.resolutions(module
);
1171 let targets
= resolutions
1174 .filter_map(|(key
, res
)| res
.borrow().binding
.map(|binding
| (key
, binding
.res())))
1175 .filter(|(_
, res
)| match (kind
, res
) {
1176 (AssocItemKind
::Const(..), Res
::Def(DefKind
::AssocConst
, _
)) => true,
1177 (AssocItemKind
::Fn(_
), Res
::Def(DefKind
::AssocFn
, _
)) => true,
1178 (AssocItemKind
::TyAlias(..), Res
::Def(DefKind
::AssocTy
, _
)) => true,
1181 .map(|(key
, _
)| key
.ident
.name
)
1182 .collect
::<Vec
<_
>>();
1184 find_best_match_for_name(&targets
, ident
, None
)
1187 fn lookup_assoc_candidate
<FilterFn
>(
1191 filter_fn
: FilterFn
,
1192 ) -> Option
<AssocSuggestion
>
1194 FilterFn
: Fn(Res
) -> bool
,
1196 fn extract_node_id(t
: &Ty
) -> Option
<NodeId
> {
1198 TyKind
::Path(None
, _
) => Some(t
.id
),
1199 TyKind
::Rptr(_
, ref mut_ty
) => extract_node_id(&mut_ty
.ty
),
1200 // This doesn't handle the remaining `Ty` variants as they are not
1201 // that commonly the self_type, it might be interesting to provide
1202 // support for those in future.
1207 // Fields are generally expected in the same contexts as locals.
1208 if filter_fn(Res
::Local(ast
::DUMMY_NODE_ID
)) {
1209 if let Some(node_id
) =
1210 self.diagnostic_metadata
.current_self_type
.as_ref().and_then(extract_node_id
)
1212 // Look for a field with the same name in the current self_type.
1213 if let Some(resolution
) = self.r
.partial_res_map
.get(&node_id
) {
1214 match resolution
.base_res() {
1215 Res
::Def(DefKind
::Struct
| DefKind
::Union
, did
)
1216 if resolution
.unresolved_segments() == 0 =>
1218 if let Some(field_names
) = self.r
.field_names
.get(&did
) {
1221 .any(|&field_name
| ident
.name
== field_name
.node
)
1223 return Some(AssocSuggestion
::Field
);
1233 if let Some(items
) = self.diagnostic_metadata
.current_trait_assoc_items
{
1234 for assoc_item
in items
{
1235 if assoc_item
.ident
== ident
{
1236 return Some(match &assoc_item
.kind
{
1237 ast
::AssocItemKind
::Const(..) => AssocSuggestion
::AssocConst
,
1238 ast
::AssocItemKind
::Fn(box ast
::Fn { sig, .. }
) if sig
.decl
.has_self() => {
1239 AssocSuggestion
::MethodWithSelf
1241 ast
::AssocItemKind
::Fn(..) => AssocSuggestion
::AssocFn
,
1242 ast
::AssocItemKind
::TyAlias(..) => AssocSuggestion
::AssocType
,
1243 ast
::AssocItemKind
::MacCall(_
) => continue,
1249 // Look for associated items in the current trait.
1250 if let Some((module
, _
)) = self.current_trait_ref
{
1251 if let Ok(binding
) = self.r
.resolve_ident_in_module(
1252 ModuleOrUniformRoot
::Module(module
),
1259 let res
= binding
.res();
1261 if self.r
.has_self
.contains(&res
.def_id()) {
1262 return Some(AssocSuggestion
::MethodWithSelf
);
1265 Res
::Def(DefKind
::AssocFn
, _
) => return Some(AssocSuggestion
::AssocFn
),
1266 Res
::Def(DefKind
::AssocConst
, _
) => {
1267 return Some(AssocSuggestion
::AssocConst
);
1269 Res
::Def(DefKind
::AssocTy
, _
) => {
1270 return Some(AssocSuggestion
::AssocType
);
1282 fn lookup_typo_candidate(
1286 filter_fn
: &impl Fn(Res
) -> bool
,
1288 ) -> Option
<TypoSuggestion
> {
1289 let mut names
= Vec
::new();
1290 if path
.len() == 1 {
1291 // Search in lexical scope.
1292 // Walk backwards up the ribs in scope and collect candidates.
1293 for rib
in self.ribs
[ns
].iter().rev() {
1294 // Locals and type parameters
1295 for (ident
, &res
) in &rib
.bindings
{
1297 names
.push(TypoSuggestion
::typo_from_res(ident
.name
, res
));
1301 if let RibKind
::ModuleRibKind(module
) = rib
.kind
{
1302 // Items from this module
1303 self.r
.add_module_candidates(module
, &mut names
, &filter_fn
);
1305 if let ModuleKind
::Block(..) = module
.kind
{
1306 // We can see through blocks
1308 // Items from the prelude
1309 if !module
.no_implicit_prelude
{
1310 let extern_prelude
= self.r
.extern_prelude
.clone();
1311 names
.extend(extern_prelude
.iter().flat_map(|(ident
, _
)| {
1312 self.r
.crate_loader
.maybe_process_path_extern(ident
.name
).and_then(
1314 let crate_mod
= Res
::Def(
1316 DefId { krate: crate_id, index: CRATE_DEF_INDEX }
,
1319 if filter_fn(crate_mod
) {
1320 Some(TypoSuggestion
::typo_from_res(
1321 ident
.name
, crate_mod
,
1330 if let Some(prelude
) = self.r
.prelude
{
1331 self.r
.add_module_candidates(prelude
, &mut names
, &filter_fn
);
1338 // Add primitive types to the mix
1339 if filter_fn(Res
::PrimTy(PrimTy
::Bool
)) {
1340 names
.extend(PrimTy
::ALL
.iter().map(|prim_ty
| {
1341 TypoSuggestion
::typo_from_res(prim_ty
.name(), Res
::PrimTy(*prim_ty
))
1345 // Search in module.
1346 let mod_path
= &path
[..path
.len() - 1];
1347 if let PathResult
::Module(ModuleOrUniformRoot
::Module(module
)) =
1348 self.resolve_path(mod_path
, Some(TypeNS
), false, span
, CrateLint
::No
)
1350 self.r
.add_module_candidates(module
, &mut names
, &filter_fn
);
1354 let name
= path
[path
.len() - 1].ident
.name
;
1355 // Make sure error reporting is deterministic.
1356 names
.sort_by_cached_key(|suggestion
| suggestion
.candidate
.as_str());
1358 match find_best_match_for_name(
1359 &names
.iter().map(|suggestion
| suggestion
.candidate
).collect
::<Vec
<Symbol
>>(),
1363 Some(found
) if found
!= name
=> {
1364 names
.into_iter().find(|suggestion
| suggestion
.candidate
== found
)
1370 // Returns the name of the Rust type approximately corresponding to
1371 // a type name in another programming language.
1372 fn likely_rust_type(path
: &[Segment
]) -> Option
<Symbol
> {
1373 let name
= path
[path
.len() - 1].ident
.as_str();
1374 // Common Java types
1376 "byte" => sym
::u8, // In Java, bytes are signed, but in practice one almost always wants unsigned bytes.
1377 "short" => sym
::i16,
1378 "boolean" => sym
::bool
,
1381 "float" => sym
::f32,
1382 "double" => sym
::f64,
1387 /// Only used in a specific case of type ascription suggestions
1388 fn get_colon_suggestion_span(&self, start
: Span
) -> Span
{
1389 let sm
= self.r
.session
.source_map();
1390 start
.to(sm
.next_point(start
))
1393 fn type_ascription_suggestion(&self, err
: &mut DiagnosticBuilder
<'_
>, base_span
: Span
) -> bool
{
1394 let sm
= self.r
.session
.source_map();
1395 let base_snippet
= sm
.span_to_snippet(base_span
);
1396 if let Some(&sp
) = self.diagnostic_metadata
.current_type_ascription
.last() {
1397 if let Ok(snippet
) = sm
.span_to_snippet(sp
) {
1398 let len
= snippet
.trim_end().len() as u32;
1399 if snippet
.trim() == ":" {
1401 sp
.with_lo(sp
.lo() + BytePos(len
- 1)).with_hi(sp
.lo() + BytePos(len
));
1402 let mut show_label
= true;
1403 if sm
.is_multiline(sp
) {
1404 err
.span_suggestion_short(
1406 "maybe you meant to write `;` here",
1408 Applicability
::MaybeIncorrect
,
1411 let after_colon_sp
=
1412 self.get_colon_suggestion_span(colon_sp
.shrink_to_hi());
1413 if snippet
.len() == 1 {
1415 err
.span_suggestion(
1417 "maybe you meant to write a path separator here",
1419 Applicability
::MaybeIncorrect
,
1426 .type_ascription_path_suggestions
1433 if let Ok(base_snippet
) = base_snippet
{
1434 let mut sp
= after_colon_sp
;
1436 // Try to find an assignment
1437 sp
= sm
.next_point(sp
);
1438 let snippet
= sm
.span_to_snippet(sp
.to(sm
.next_point(sp
)));
1440 Ok(ref x
) if x
.as_str() == "=" => {
1441 err
.span_suggestion(
1443 "maybe you meant to write an assignment here",
1444 format
!("let {}", base_snippet
),
1445 Applicability
::MaybeIncorrect
,
1450 Ok(ref x
) if x
.as_str() == "\n" => break,
1460 "expecting a type here because of type ascription",
1470 fn find_module(&mut self, def_id
: DefId
) -> Option
<(Module
<'a
>, ImportSuggestion
)> {
1471 let mut result
= None
;
1472 let mut seen_modules
= FxHashSet
::default();
1473 let mut worklist
= vec
![(self.r
.graph_root
, Vec
::new())];
1475 while let Some((in_module
, path_segments
)) = worklist
.pop() {
1476 // abort if the module is already found
1477 if result
.is_some() {
1481 in_module
.for_each_child(self.r
, |_
, ident
, _
, name_binding
| {
1482 // abort if the module is already found or if name_binding is private external
1483 if result
.is_some() || !name_binding
.vis
.is_visible_locally() {
1486 if let Some(module
) = name_binding
.module() {
1488 let mut path_segments
= path_segments
.clone();
1489 path_segments
.push(ast
::PathSegment
::from_ident(ident
));
1490 let module_def_id
= module
.def_id();
1491 if module_def_id
== def_id
{
1493 Path { span: name_binding.span, segments: path_segments, tokens: None }
;
1505 // add the module to the lookup
1506 if seen_modules
.insert(module_def_id
) {
1507 worklist
.push((module
, path_segments
));
1517 fn collect_enum_ctors(&mut self, def_id
: DefId
) -> Option
<Vec
<(Path
, DefId
, CtorKind
)>> {
1518 self.find_module(def_id
).map(|(enum_module
, enum_import_suggestion
)| {
1519 let mut variants
= Vec
::new();
1520 enum_module
.for_each_child(self.r
, |_
, ident
, _
, name_binding
| {
1521 if let Res
::Def(DefKind
::Ctor(CtorOf
::Variant
, kind
), def_id
) = name_binding
.res() {
1522 let mut segms
= enum_import_suggestion
.path
.segments
.clone();
1523 segms
.push(ast
::PathSegment
::from_ident(ident
));
1524 let path
= Path { span: name_binding.span, segments: segms, tokens: None }
;
1525 variants
.push((path
, def_id
, kind
));
1532 /// Adds a suggestion for using an enum's variant when an enum is used instead.
1533 fn suggest_using_enum_variant(
1535 err
: &mut DiagnosticBuilder
<'a
>,
1536 source
: PathSource
<'_
>,
1540 let variants
= match self.collect_enum_ctors(def_id
) {
1541 Some(variants
) => variants
,
1543 err
.note("you might have meant to use one of the enum's variants");
1548 let suggest_only_tuple_variants
=
1549 matches
!(source
, PathSource
::TupleStruct(..)) || source
.is_call();
1550 if suggest_only_tuple_variants
{
1551 // Suggest only tuple variants regardless of whether they have fields and do not
1552 // suggest path with added parentheses.
1553 let suggestable_variants
= variants
1555 .filter(|(.., kind
)| *kind
== CtorKind
::Fn
)
1556 .map(|(variant
, ..)| path_names_to_string(variant
))
1557 .collect
::<Vec
<_
>>();
1559 let non_suggestable_variant_count
= variants
.len() - suggestable_variants
.len();
1561 let source_msg
= if source
.is_call() {
1563 } else if matches
!(source
, PathSource
::TupleStruct(..)) {
1569 if !suggestable_variants
.is_empty() {
1570 let msg
= if non_suggestable_variant_count
== 0 && suggestable_variants
.len() == 1 {
1571 format
!("try {} the enum's variant", source_msg
)
1573 format
!("try {} one of the enum's variants", source_msg
)
1576 err
.span_suggestions(
1579 suggestable_variants
.into_iter(),
1580 Applicability
::MaybeIncorrect
,
1584 // If the enum has no tuple variants..
1585 if non_suggestable_variant_count
== variants
.len() {
1586 err
.help(&format
!("the enum has no tuple variants {}", source_msg
));
1589 // If there are also non-tuple variants..
1590 if non_suggestable_variant_count
== 1 {
1592 "you might have meant {} the enum's non-tuple variant",
1595 } else if non_suggestable_variant_count
>= 1 {
1597 "you might have meant {} one of the enum's non-tuple variants",
1602 let needs_placeholder
= |def_id
: DefId
, kind
: CtorKind
| {
1603 let has_no_fields
= self.r
.field_names
.get(&def_id
).map_or(false, |f
| f
.is_empty());
1605 CtorKind
::Const
=> false,
1606 CtorKind
::Fn
| CtorKind
::Fictive
if has_no_fields
=> false,
1611 let mut suggestable_variants
= variants
1613 .filter(|(_
, def_id
, kind
)| !needs_placeholder(*def_id
, *kind
))
1614 .map(|(variant
, _
, kind
)| (path_names_to_string(variant
), kind
))
1615 .map(|(variant
, kind
)| match kind
{
1616 CtorKind
::Const
=> variant
,
1617 CtorKind
::Fn
=> format
!("({}())", variant
),
1618 CtorKind
::Fictive
=> format
!("({} {{}})", variant
),
1620 .collect
::<Vec
<_
>>();
1622 if !suggestable_variants
.is_empty() {
1623 let msg
= if suggestable_variants
.len() == 1 {
1624 "you might have meant to use the following enum variant"
1626 "you might have meant to use one of the following enum variants"
1629 err
.span_suggestions(
1632 suggestable_variants
.drain(..),
1633 Applicability
::MaybeIncorrect
,
1637 let suggestable_variants_with_placeholders
= variants
1639 .filter(|(_
, def_id
, kind
)| needs_placeholder(*def_id
, *kind
))
1640 .map(|(variant
, _
, kind
)| (path_names_to_string(variant
), kind
))
1641 .filter_map(|(variant
, kind
)| match kind
{
1642 CtorKind
::Fn
=> Some(format
!("({}(/* fields */))", variant
)),
1643 CtorKind
::Fictive
=> Some(format
!("({} {{ /* fields */ }})", variant
)),
1646 .collect
::<Vec
<_
>>();
1648 if !suggestable_variants_with_placeholders
.is_empty() {
1650 suggestable_variants
.is_empty(),
1651 suggestable_variants_with_placeholders
.len(),
1653 (true, 1) => "the following enum variant is available",
1654 (true, _
) => "the following enum variants are available",
1655 (false, 1) => "alternatively, the following enum variant is available",
1656 (false, _
) => "alternatively, the following enum variants are also available",
1659 err
.span_suggestions(
1662 suggestable_variants_with_placeholders
.into_iter(),
1663 Applicability
::HasPlaceholders
,
1668 if def_id
.is_local() {
1669 if let Some(span
) = self.def_span(def_id
) {
1670 err
.span_note(span
, "the enum is defined here");
1675 crate fn report_missing_type_error(
1678 ) -> Option
<(Span
, &'
static str, String
, Applicability
)> {
1679 let (ident
, span
) = match path
{
1680 [segment
] if !segment
.has_generic_args
=> {
1681 (segment
.ident
.to_string(), segment
.ident
.span
)
1685 let mut iter
= ident
.chars().map(|c
| c
.is_uppercase());
1686 let single_uppercase_char
=
1687 matches
!(iter
.next(), Some(true)) && matches
!(iter
.next(), None
);
1688 if !self.diagnostic_metadata
.currently_processing_generics
&& !single_uppercase_char
{
1691 match (self.diagnostic_metadata
.current_item
, single_uppercase_char
, self.diagnostic_metadata
.currently_processing_generics
) {
1692 (Some(Item { kind: ItemKind::Fn(..), ident, .. }
), _
, _
) if ident
.name
== sym
::main
=> {
1693 // Ignore `fn main()` as we don't want to suggest `fn main<T>()`
1698 kind @ ItemKind
::Fn(..)
1699 | kind @ ItemKind
::Enum(..)
1700 | kind @ ItemKind
::Struct(..)
1701 | kind @ ItemKind
::Union(..),
1706 // Without the 2nd `true`, we'd suggest `impl <T>` for `impl T` when a type `T` isn't found
1707 | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }
), true, true)
1708 | (Some(Item { kind, .. }
), false, _
) => {
1709 // Likely missing type parameter.
1710 if let Some(generics
) = kind
.generics() {
1711 if span
.overlaps(generics
.span
) {
1712 // Avoid the following:
1713 // error[E0405]: cannot find trait `A` in this scope
1714 // --> $DIR/typo-suggestion-named-underscore.rs:CC:LL
1716 // L | fn foo<T: A>(x: T) {} // Shouldn't suggest underscore
1717 // | ^- help: you might be missing a type parameter: `, A`
1719 // | not found in this scope
1722 let msg
= "you might be missing a type parameter";
1723 let (span
, sugg
) = if let [.., param
] = &generics
.params
[..] {
1724 let span
= if let [.., bound
] = ¶m
.bounds
[..] {
1726 } else if let GenericParam
{
1727 kind
: GenericParamKind
::Const { ty, kw_span: _, default }
, ..
1729 default.as_ref().map(|def
| def
.value
.span
).unwrap_or(ty
.span
)
1733 (span
, format
!(", {}", ident
))
1735 (generics
.span
, format
!("<{}>", ident
))
1737 // Do not suggest if this is coming from macro expansion.
1738 if !span
.from_expansion() {
1740 span
.shrink_to_hi(),
1743 Applicability
::MaybeIncorrect
,
1753 /// Given the target `label`, search the `rib_index`th label rib for similarly named labels,
1754 /// optionally returning the closest match and whether it is reachable.
1755 crate fn suggestion_for_label_in_rib(
1759 ) -> Option
<LabelSuggestion
> {
1760 // Are ribs from this `rib_index` within scope?
1761 let within_scope
= self.is_label_valid_from_rib(rib_index
);
1763 let rib
= &self.label_ribs
[rib_index
];
1767 .filter(|(id
, _
)| id
.span
.ctxt() == label
.span
.ctxt())
1768 .map(|(id
, _
)| id
.name
)
1769 .collect
::<Vec
<Symbol
>>();
1771 find_best_match_for_name(&names
, label
.name
, None
).map(|symbol
| {
1772 // Upon finding a similar name, get the ident that it was from - the span
1773 // contained within helps make a useful diagnostic. In addition, determine
1774 // whether this candidate is within scope.
1775 let (ident
, _
) = rib
.bindings
.iter().find(|(ident
, _
)| ident
.name
== symbol
).unwrap();
1776 (*ident
, within_scope
)
1781 impl<'tcx
> LifetimeContext
<'_
, 'tcx
> {
1782 crate fn report_missing_lifetime_specifiers(
1786 ) -> DiagnosticBuilder
<'tcx
> {
1791 "missing lifetime specifier{}",
1796 crate fn emit_undeclared_lifetime_error(&self, lifetime_ref
: &hir
::Lifetime
) {
1797 let mut err
= struct_span_err
!(
1801 "use of undeclared lifetime name `{}`",
1804 err
.span_label(lifetime_ref
.span
, "undeclared lifetime");
1805 let mut suggests_in_band
= false;
1806 let mut suggest_note
= true;
1807 for missing
in &self.missing_named_lifetime_spots
{
1809 MissingLifetimeSpot
::Generics(generics
) => {
1810 let (span
, sugg
) = if let Some(param
) = generics
.params
.iter().find(|p
| {
1813 hir
::GenericParamKind
::Type { synthetic: true, .. }
1814 | hir
::GenericParamKind
::Lifetime
{
1815 kind
: hir
::LifetimeParamKind
::Elided
,
1819 (param
.span
.shrink_to_lo(), format
!("{}, ", lifetime_ref
))
1821 suggests_in_band
= true;
1822 (generics
.span
, format
!("<{}>", lifetime_ref
))
1824 if !span
.from_expansion() {
1825 err
.span_suggestion(
1827 &format
!("consider introducing lifetime `{}` here", lifetime_ref
),
1829 Applicability
::MaybeIncorrect
,
1831 } else if suggest_note
{
1832 suggest_note
= false; // Avoid displaying the same help multiple times.
1836 "lifetime `{}` is missing in item created through this procedural \
1843 MissingLifetimeSpot
::HigherRanked { span, span_type }
=> {
1844 err
.span_suggestion(
1847 "consider making the {} lifetime-generic with a new `{}` lifetime",
1851 span_type
.suggestion(&lifetime_ref
.to_string()),
1852 Applicability
::MaybeIncorrect
,
1855 "for more information on higher-ranked polymorphism, visit \
1856 https://doc.rust-lang.org/nomicon/hrtb.html",
1862 if self.tcx
.sess
.is_nightly_build()
1863 && !self.tcx
.features().in_band_lifetimes
1867 "if you want to experiment with in-band lifetime bindings, \
1868 add `#![feature(in_band_lifetimes)]` to the crate attributes",
1874 // FIXME(const_generics): This patches over an ICE caused by non-'static lifetimes in const
1875 // generics. We are disallowing this until we can decide on how we want to handle non-'static
1876 // lifetimes in const generics. See issue #74052 for discussion.
1877 crate fn emit_non_static_lt_in_const_generic_error(&self, lifetime_ref
: &hir
::Lifetime
) {
1878 let mut err
= struct_span_err
!(
1882 "use of non-static lifetime `{}` in const generic",
1886 "for more information, see issue #74052 \
1887 <https://github.com/rust-lang/rust/issues/74052>",
1892 crate fn is_trait_ref_fn_scope(&mut self, trait_ref
: &'tcx hir
::PolyTraitRef
<'tcx
>) -> bool
{
1893 if let def
::Res
::Def(_
, did
) = trait_ref
.trait_ref
.path
.res
{
1895 self.tcx
.lang_items().fn_once_trait(),
1896 self.tcx
.lang_items().fn_trait(),
1897 self.tcx
.lang_items().fn_mut_trait(),
1899 .contains(&Some(did
))
1901 let (span
, span_type
) = match &trait_ref
.bound_generic_params
{
1902 [] => (trait_ref
.span
.shrink_to_lo(), ForLifetimeSpanType
::BoundEmpty
),
1903 [.., bound
] => (bound
.span
.shrink_to_hi(), ForLifetimeSpanType
::BoundTail
),
1905 self.missing_named_lifetime_spots
1906 .push(MissingLifetimeSpot
::HigherRanked { span, span_type }
);
1913 crate fn add_missing_lifetime_specifiers_label(
1915 err
: &mut DiagnosticBuilder
<'_
>,
1916 mut spans_with_counts
: Vec
<(Span
, usize)>,
1917 lifetime_names
: &FxHashSet
<Symbol
>,
1918 lifetime_spans
: Vec
<Span
>,
1919 params
: &[ElisionFailureInfo
],
1921 let snippets
: Vec
<Option
<String
>> = spans_with_counts
1923 .map(|(span
, _
)| self.tcx
.sess
.source_map().span_to_snippet(*span
).ok())
1926 // Empty generics are marked with a span of "<", but since from now on
1927 // that information is in the snippets it can be removed from the spans.
1928 for ((span
, _
), snippet
) in spans_with_counts
.iter_mut().zip(&snippets
) {
1929 if snippet
.as_deref() == Some("<") {
1930 *span
= span
.shrink_to_hi();
1934 for &(span
, count
) in &spans_with_counts
{
1938 "expected {} lifetime parameter{}",
1939 if count
== 1 { "named".to_string() }
else { count.to_string() }
,
1945 let suggest_existing
=
1946 |err
: &mut DiagnosticBuilder
<'_
>,
1948 formatters
: Vec
<Option
<Box
<dyn Fn(&str) -> String
>>>| {
1949 if let Some(MissingLifetimeSpot
::HigherRanked { span: for_span, span_type }
) =
1950 self.missing_named_lifetime_spots
.iter().rev().next()
1952 // When we have `struct S<'a>(&'a dyn Fn(&X) -> &X);` we want to not only suggest
1953 // using `'a`, but also introduce the concept of HRLTs by suggesting
1954 // `struct S<'a>(&'a dyn for<'b> Fn(&X) -> &'b X);`. (#72404)
1955 let mut introduce_suggestion
= vec
![];
1957 let a_to_z_repeat_n
= |n
| {
1958 (b'a'
..=b'z'
).map(move |c
| {
1959 let mut s
= '
\''
.to_string();
1960 s
.extend(std
::iter
::repeat(char::from(c
)).take(n
));
1965 // If all single char lifetime names are present, we wrap around and double the chars.
1967 .flat_map(a_to_z_repeat_n
)
1968 .find(|lt
| !lifetime_names
.contains(&Symbol
::intern(<
)))
1971 "consider making the {} lifetime-generic with a new `{}` lifetime",
1976 "for more information on higher-ranked polymorphism, visit \
1977 https://doc.rust-lang.org/nomicon/hrtb.html",
1979 let for_sugg
= span_type
.suggestion(<_name
);
1980 for param
in params
{
1981 if let Ok(snippet
) = self.tcx
.sess
.source_map().span_to_snippet(param
.span
)
1983 if snippet
.starts_with('
&'
) && !snippet
.starts_with("&'") {
1984 introduce_suggestion
1985 .push((param
.span
, format
!("&{} {}", lt_name
, &snippet
[1..])));
1986 } else if let Some(stripped
) = snippet
.strip_prefix("&'_ ") {
1987 introduce_suggestion
1988 .push((param
.span
, format
!("&{} {}", lt_name
, stripped
)));
1992 introduce_suggestion
.push((*for_span
, for_sugg
));
1993 for ((span
, _
), formatter
) in spans_with_counts
.iter().zip(formatters
.iter()) {
1994 if let Some(formatter
) = formatter
{
1995 introduce_suggestion
.push((*span
, formatter(<_name
)));
1998 err
.multipart_suggestion_verbose(
2000 introduce_suggestion
,
2001 Applicability
::MaybeIncorrect
,
2005 let spans_suggs
: Vec
<_
> = formatters
2007 .zip(spans_with_counts
.iter())
2008 .filter_map(|(fmt
, (span
, _
))| {
2009 if let Some(formatter
) = fmt { Some((formatter, span)) }
else { None }
2011 .map(|(formatter
, span
)| (*span
, formatter(name
)))
2013 err
.multipart_suggestion_verbose(
2015 "consider using the `{}` lifetime",
2016 lifetime_names
.iter().next().unwrap()
2019 Applicability
::MaybeIncorrect
,
2022 let suggest_new
= |err
: &mut DiagnosticBuilder
<'_
>, suggs
: Vec
<Option
<String
>>| {
2023 for missing
in self.missing_named_lifetime_spots
.iter().rev() {
2024 let mut introduce_suggestion
= vec
![];
2027 introduce_suggestion
.push(match missing
{
2028 MissingLifetimeSpot
::Generics(generics
) => {
2029 if generics
.span
== DUMMY_SP
{
2030 // Account for malformed generics in the HIR. This shouldn't happen,
2031 // but if we make a mistake elsewhere, mainly by keeping something in
2032 // `missing_named_lifetime_spots` that we shouldn't, like associated
2033 // `const`s or making a mistake in the AST lowering we would provide
2034 // non-sensical suggestions. Guard against that by skipping these.
2038 msg
= "consider introducing a named lifetime parameter".to_string();
2039 should_break
= true;
2040 if let Some(param
) = generics
.params
.iter().find(|p
| {
2043 hir
::GenericParamKind
::Type { synthetic: true, .. }
2044 | hir
::GenericParamKind
::Lifetime
{
2045 kind
: hir
::LifetimeParamKind
::Elided
2049 (param
.span
.shrink_to_lo(), "'a, ".to_string())
2051 (generics
.span
, "<'a>".to_string())
2054 MissingLifetimeSpot
::HigherRanked { span, span_type }
=> {
2056 "consider making the {} lifetime-generic with a new `'a` lifetime",
2059 should_break
= false;
2061 "for more information on higher-ranked polymorphism, visit \
2062 https://doc.rust-lang.org/nomicon/hrtb.html",
2064 (*span
, span_type
.suggestion("'a"))
2066 MissingLifetimeSpot
::Static
=> {
2067 let mut spans_suggs
= Vec
::new();
2068 for ((span
, count
), snippet
) in
2069 spans_with_counts
.iter().copied().zip(snippets
.iter())
2071 let (span
, sugg
) = match snippet
.as_deref() {
2072 Some("&") => (span
.shrink_to_hi(), "'static ".to_owned()),
2073 Some("'_") => (span
, "'static".to_owned()),
2074 Some(snippet
) if !snippet
.ends_with('
>'
) => {
2078 std
::iter
::repeat("'static")
2080 .collect
::<Vec
<_
>>()
2083 } else if snippet
== "<" || snippet
== "(" {
2085 span
.shrink_to_hi(),
2086 std
::iter
::repeat("'static")
2088 .collect
::<Vec
<_
>>()
2093 span
.shrink_to_hi(),
2096 std
::iter
::repeat("'static")
2098 .collect
::<Vec
<_
>>()
2106 spans_suggs
.push((span
, sugg
.to_string()));
2108 err
.multipart_suggestion_verbose(
2109 "consider using the `'static` lifetime",
2111 Applicability
::MaybeIncorrect
,
2117 struct Lifetime(Span
, String
);
2119 fn is_unnamed(&self) -> bool
{
2120 self.1.starts_with('
&'
) && !self.1.starts_with("&'")
2122 fn is_underscore(&self) -> bool
{
2123 self.1.starts_with("&'_ ")
2125 fn is_named(&self) -> bool
{
2126 self.1.starts_with("&'")
2128 fn suggestion(&self, sugg
: String
) -> Option
<(Span
, String
)> {
2132 self.is_underscore(),
2134 sugg
.starts_with('
&'
),
2136 (true, _
, _
, false) => (self.span_unnamed_borrow(), sugg
),
2137 (true, _
, _
, true) => {
2138 (self.span_unnamed_borrow(), sugg
[1..].to_string())
2140 (_
, true, _
, false) => {
2141 (self.span_underscore_borrow(), sugg
.trim().to_string())
2143 (_
, true, _
, true) => {
2144 (self.span_underscore_borrow(), sugg
[1..].trim().to_string())
2146 (_
, _
, true, false) => {
2147 (self.span_named_borrow(), sugg
.trim().to_string())
2149 (_
, _
, true, true) => {
2150 (self.span_named_borrow(), sugg
[1..].trim().to_string())
2156 fn span_unnamed_borrow(&self) -> Span
{
2157 let lo
= self.0.lo() + BytePos(1);
2158 self.0.with_lo(lo
).with_hi(lo
)
2160 fn span_named_borrow(&self) -> Span
{
2161 let lo
= self.0.lo() + BytePos(1);
2164 fn span_underscore_borrow(&self) -> Span
{
2165 let lo
= self.0.lo() + BytePos(1);
2166 let hi
= lo
+ BytePos(2);
2167 self.0.with_lo(lo
).with_hi(hi
)
2171 for param
in params
{
2172 if let Ok(snippet
) = self.tcx
.sess
.source_map().span_to_snippet(param
.span
) {
2173 if let Some((span
, sugg
)) =
2174 Lifetime(param
.span
, snippet
).suggestion("'a ".to_string())
2176 introduce_suggestion
.push((span
, sugg
));
2180 for (span
, sugg
) in spans_with_counts
.iter().copied().zip(suggs
.iter()).filter_map(
2181 |((span
, _
), sugg
)| match &sugg
{
2182 Some(sugg
) => Some((span
, sugg
.to_string())),
2186 let (span
, sugg
) = self
2190 .span_to_snippet(span
)
2192 .and_then(|snippet
| Lifetime(span
, snippet
).suggestion(sugg
.clone()))
2193 .unwrap_or((span
, sugg
));
2194 introduce_suggestion
.push((span
, sugg
.to_string()));
2196 err
.multipart_suggestion_verbose(
2198 introduce_suggestion
,
2199 Applicability
::MaybeIncorrect
,
2207 let lifetime_names
: Vec
<_
> = lifetime_names
.iter().collect();
2208 match &lifetime_names
[..] {
2210 let mut suggs
: Vec
<Option
<Box
<dyn Fn(&str) -> String
>>> = Vec
::new();
2211 for (snippet
, (_
, count
)) in snippets
.iter().zip(spans_with_counts
.iter().copied())
2213 suggs
.push(match snippet
.as_deref() {
2214 Some("&") => Some(Box
::new(|name
| format
!("&{} ", name
))),
2215 Some("'_") => Some(Box
::new(|n
| n
.to_string())),
2216 Some("") => Some(Box
::new(move |n
| format
!("{}, ", n
).repeat(count
))),
2217 Some("<") => Some(Box
::new(move |n
| {
2218 std
::iter
::repeat(n
).take(count
).collect
::<Vec
<_
>>().join(", ")
2220 Some(snippet
) if !snippet
.ends_with('
>'
) => Some(Box
::new(move |name
| {
2224 std
::iter
::repeat(name
.to_string())
2226 .collect
::<Vec
<_
>>()
2233 suggest_existing(err
, &name
.as_str()[..], suggs
);
2236 let mut suggs
= Vec
::new();
2237 for (snippet
, (_
, count
)) in
2238 snippets
.iter().cloned().zip(spans_with_counts
.iter().copied())
2240 suggs
.push(match snippet
.as_deref() {
2241 Some("&") => Some("&'a ".to_string()),
2242 Some("'_") => Some("'a".to_string()),
2244 Some(std
::iter
::repeat("'a, ").take(count
).collect
::<Vec
<_
>>().join(""))
2247 Some(std
::iter
::repeat("'a").take(count
).collect
::<Vec
<_
>>().join(", "))
2249 Some(snippet
) => Some(format
!(
2252 std
::iter
::repeat("'a").take(count
).collect
::<Vec
<_
>>().join(", "),
2257 suggest_new(err
, suggs
);
2259 lts
if lts
.len() > 1 => {
2260 err
.span_note(lifetime_spans
, "these named lifetimes are available to use");
2262 let mut spans_suggs
: Vec
<_
> = Vec
::new();
2263 for ((span
, _
), snippet
) in spans_with_counts
.iter().copied().zip(snippets
.iter()) {
2264 match snippet
.as_deref() {
2265 Some("") => spans_suggs
.push((span
, "'lifetime, ".to_string())),
2266 Some("&") => spans_suggs
2267 .push((span
.with_lo(span
.lo() + BytePos(1)), "'lifetime ".to_string())),
2272 if spans_suggs
.len() > 0 {
2273 // This happens when we have `Foo<T>` where we point at the space before `T`,
2274 // but this can be confusing so we give a suggestion with placeholders.
2275 err
.multipart_suggestion_verbose(
2276 "consider using one of the available lifetimes here",
2278 Applicability
::HasPlaceholders
,
2282 _
=> unreachable
!(),
2286 /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`.
2287 /// This function will emit an error if `generic_const_exprs` is not enabled, the body identified by
2288 /// `body_id` is an anonymous constant and `lifetime_ref` is non-static.
2289 crate fn maybe_emit_forbidden_non_static_lifetime_error(
2291 body_id
: hir
::BodyId
,
2292 lifetime_ref
: &'tcx hir
::Lifetime
,
2294 let is_anon_const
= matches
!(
2295 self.tcx
.def_kind(self.tcx
.hir().body_owner_def_id(body_id
)),
2296 hir
::def
::DefKind
::AnonConst
2298 let is_allowed_lifetime
= matches
!(
2300 hir
::LifetimeName
::Implicit
| hir
::LifetimeName
::Static
| hir
::LifetimeName
::Underscore
2303 if !self.tcx
.lazy_normalization() && is_anon_const
&& !is_allowed_lifetime
{
2305 &self.tcx
.sess
.parse_sess
,
2306 sym
::generic_const_exprs
,
2308 "a non-static lifetime is not allowed in a `const`",