1use std::borrow::Cow;
4use std::iter;
5use std::ops::Deref;
6
7use rustc_ast::visit::{FnCtxt, FnKind, LifetimeCtxt, Visitor, walk_ty};
8use rustc_ast::{
9 self as ast, AngleBracketedArg, AssocItemKind, DUMMY_NODE_ID, Expr, ExprKind, GenericArg,
10 GenericArgs, GenericParam, GenericParamKind, Item, ItemKind, MethodCall, NodeId, Path,
11 PathSegment, Ty, TyKind,
12};
13use rustc_ast_pretty::pprust::{path_to_string, where_bound_predicate_to_string};
14use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
15use rustc_data_structures::unord::UnordItems;
16use rustc_errors::codes::*;
17use rustc_errors::{
18 Applicability, Diag, Diagnostic, ErrorGuaranteed, MultiSpan, SuggestionStyle, pluralize,
19 struct_span_code_err,
20};
21use rustc_hir as hir;
22use rustc_hir::attrs::diagnostic::{CustomDiagnostic, FormatArgs};
23use rustc_hir::def::Namespace::{self, *};
24use rustc_hir::def::{CtorKind, CtorOf, DefKind, MacroKinds};
25use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
26use rustc_hir::{MissingLifetimeKind, PrimTy, find_attr};
27use rustc_lint_defs::builtin::{SINGLE_USE_LIFETIMES, UNUSED_LIFETIMES};
28use rustc_middle::ty;
29use rustc_session::Session;
30use rustc_span::edit_distance::{edit_distance, find_best_match_for_name};
31use rustc_span::edition::Edition;
32use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym};
33use thin_vec::{ThinVec, thin_vec};
34use tracing::debug;
35
36use super::NoConstantGenericsReason;
37use crate::diagnostics::impls::{ImportSuggestion, LabelSuggestion, TypoSuggestion};
38use crate::late::{
39 AliasPossibility, LateResolutionVisitor, LifetimeBinderKind, LifetimeRes, LifetimeRibKind,
40 LifetimeUseSet, QSelf, RibKind,
41};
42use crate::ty::fast_reject::SimplifiedType;
43use crate::{
44 Finalize, Module, ModuleOrUniformRoot, ParentScope, PathResult, PathSource, Res, Resolver,
45 ScopeSet, Segment, diagnostics, path_names_to_string,
46};
47
48enum AssocSuggestion {
50 Field,
51 MethodWithSelf { called: bool },
52 AssocFn { called: bool },
53 AssocType,
54 AssocConst,
55}
56
57impl AssocSuggestion {
58 fn action(&self) -> &'static str {
59 match self {
60 AssocSuggestion::Field => "use the available field",
61 AssocSuggestion::MethodWithSelf { called: true } => {
62 "call the method with the fully-qualified path"
63 }
64 AssocSuggestion::MethodWithSelf { called: false } => {
65 "refer to the method with the fully-qualified path"
66 }
67 AssocSuggestion::AssocFn { called: true } => "call the associated function",
68 AssocSuggestion::AssocFn { called: false } => "refer to the associated function",
69 AssocSuggestion::AssocConst => "use the associated `const`",
70 AssocSuggestion::AssocType => "use the associated type",
71 }
72 }
73}
74
75fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
76 namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
77}
78
79fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
80 namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
81}
82
83fn path_to_string_without_assoc_item_bindings(path: &Path) -> String {
84 let mut path = path.clone();
85 for segment in &mut path.segments {
86 let mut remove_args = false;
87 if let Some(args) = segment.args.as_deref_mut()
88 && let ast::GenericArgs::AngleBracketed(angle_bracketed) = args
89 {
90 angle_bracketed.args.retain(|arg| #[allow(non_exhaustive_omitted_patterns)] match arg {
ast::AngleBracketedArg::Arg(_) => true,
_ => false,
}matches!(arg, ast::AngleBracketedArg::Arg(_)));
91 remove_args = angle_bracketed.args.is_empty();
92 }
93 if remove_args {
94 segment.args = None;
95 }
96 }
97 path_to_string(&path)
98}
99
100fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
102 let variant_path = &suggestion.path;
103 let variant_path_string = path_names_to_string(variant_path);
104
105 let path_len = suggestion.path.segments.len();
106 let enum_path = ast::Path {
107 span: suggestion.path.span,
108 segments: suggestion.path.segments[0..path_len - 1].iter().cloned().collect(),
109 };
110 let enum_path_string = path_names_to_string(&enum_path);
111
112 (variant_path_string, enum_path_string)
113}
114
115#[derive(#[automatically_derived]
impl ::core::marker::Copy for MissingLifetime { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for MissingLifetime { }
#[automatically_derived]
impl ::core::clone::Clone for MissingLifetime {
#[inline]
fn clone(&self) -> MissingLifetime {
let _: ::core::clone::AssertParamIsClone<NodeId>;
let _: ::core::clone::AssertParamIsClone<Span>;
let _: ::core::clone::AssertParamIsClone<MissingLifetimeKind>;
let _: ::core::clone::AssertParamIsClone<usize>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for MissingLifetime { }
#[automatically_derived]
impl ::core::cmp::PartialEq for MissingLifetime {
#[inline]
fn eq(&self, other: &MissingLifetime) -> bool {
self.id == other.id && self.id_for_lint == other.id_for_lint &&
self.span == other.span && self.kind == other.kind &&
self.count == other.count
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for MissingLifetime {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<NodeId>;
let _: ::core::cmp::AssertParamIsEq<Span>;
let _: ::core::cmp::AssertParamIsEq<MissingLifetimeKind>;
let _: ::core::cmp::AssertParamIsEq<usize>;
}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for MissingLifetime {
#[inline]
fn partial_cmp(&self, other: &MissingLifetime)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for MissingLifetime {
#[inline]
fn cmp(&self, other: &MissingLifetime) -> ::core::cmp::Ordering {
match ::core::cmp::Ord::cmp(&self.id, &other.id) {
::core::cmp::Ordering::Equal =>
match ::core::cmp::Ord::cmp(&self.id_for_lint,
&other.id_for_lint) {
::core::cmp::Ordering::Equal =>
match ::core::cmp::Ord::cmp(&self.span, &other.span) {
::core::cmp::Ordering::Equal =>
match ::core::cmp::Ord::cmp(&self.kind, &other.kind) {
::core::cmp::Ordering::Equal =>
::core::cmp::Ord::cmp(&self.count, &other.count),
cmp => cmp,
},
cmp => cmp,
},
cmp => cmp,
},
cmp => cmp,
}
}
}Ord, #[automatically_derived]
impl ::core::fmt::Debug for MissingLifetime {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field5_finish(f,
"MissingLifetime", "id", &self.id, "id_for_lint",
&self.id_for_lint, "span", &self.span, "kind", &self.kind,
"count", &&self.count)
}
}Debug)]
117pub(super) struct MissingLifetime {
118 pub id: NodeId,
120 pub id_for_lint: NodeId,
127 pub span: Span,
129 pub kind: MissingLifetimeKind,
131 pub count: usize,
133}
134
135#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ElisionFnParameter {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f,
"ElisionFnParameter", "index", &self.index, "ident", &self.ident,
"lifetime_count", &self.lifetime_count, "span", &&self.span)
}
}Debug)]
138pub(super) struct ElisionFnParameter {
139 pub index: usize,
141 pub ident: Option<Ident>,
143 pub lifetime_count: usize,
145 pub span: Span,
147}
148
149#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for LifetimeElisionCandidate { }
#[automatically_derived]
impl ::core::clone::Clone for LifetimeElisionCandidate {
#[inline]
fn clone(&self) -> LifetimeElisionCandidate {
let _: ::core::clone::AssertParamIsClone<MissingLifetime>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for LifetimeElisionCandidate { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for LifetimeElisionCandidate {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
LifetimeElisionCandidate::Ignore =>
::core::fmt::Formatter::write_str(f, "Ignore"),
LifetimeElisionCandidate::Missing(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Missing", &__self_0),
}
}
}Debug)]
152pub(super) enum LifetimeElisionCandidate {
153 Ignore,
155 Missing(MissingLifetime),
156}
157
158#[derive(#[automatically_derived]
impl ::core::fmt::Debug for BaseError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
&["msg", "fallback_label", "span", "span_label", "could_be_expr",
"suggestion", "module", "notes"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.msg, &self.fallback_label, &self.span, &self.span_label,
&self.could_be_expr, &self.suggestion, &self.module,
&&self.notes];
::core::fmt::Formatter::debug_struct_fields_finish(f, "BaseError",
names, values)
}
}Debug)]
160struct BaseError {
161 msg: String,
162 fallback_label: String,
163 span: Span,
164 span_label: Option<(Span, &'static str)>,
165 could_be_expr: bool,
166 suggestion: Option<(Span, &'static str, String)>,
167 module: Option<DefId>,
168 notes: Vec<String>,
169}
170
171#[derive(#[automatically_derived]
impl ::core::fmt::Debug for TypoCandidate {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
TypoCandidate::Typo(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Typo",
&__self_0),
TypoCandidate::Shadowed(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"Shadowed", __self_0, &__self_1),
TypoCandidate::None =>
::core::fmt::Formatter::write_str(f, "None"),
}
}
}Debug)]
172enum TypoCandidate {
173 Typo(TypoSuggestion),
174 Shadowed(Res, Option<Span>),
175 None,
176}
177
178impl TypoCandidate {
179 fn to_opt_suggestion(self) -> Option<TypoSuggestion> {
180 match self {
181 TypoCandidate::Typo(sugg) => Some(sugg),
182 TypoCandidate::Shadowed(_, _) | TypoCandidate::None => None,
183 }
184 }
185}
186
187impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
188 fn trait_assoc_type_def_id_by_name(
189 &mut self,
190 trait_def_id: DefId,
191 assoc_name: Symbol,
192 ) -> Option<DefId> {
193 let module = self.r.get_module(trait_def_id)?;
194 self.r.resolutions(module).iter().find_map(|(key, resolution)| {
195 if key.ident.name != assoc_name {
196 return None;
197 }
198 let resolution = resolution.borrow(self.r);
199 let binding = resolution.best_decl()?;
200 match binding.res() {
201 Res::Def(DefKind::AssocTy, def_id) => Some(def_id),
202 _ => None,
203 }
204 })
205 }
206
207 fn suggest_assoc_type_from_bounds(
209 &mut self,
210 err: &mut Diag<'_>,
211 source: PathSource<'_, 'ast, 'ra>,
212 path: &[Segment],
213 ident_span: Span,
214 ) -> bool {
215 if source.namespace() != TypeNS {
217 return false;
218 }
219 let [segment] = path else { return false };
220 if segment.has_generic_args {
221 return false;
222 }
223 if !ident_span.can_be_used_for_suggestions() {
224 return false;
225 }
226 let assoc_name = segment.ident.name;
227 if assoc_name == kw::Underscore {
228 return false;
229 }
230
231 let mut matching_bounds: FxIndexMap<
235 Symbol,
236 FxIndexMap<DefId, (DefId, FxIndexSet<String>)>,
237 > = FxIndexMap::default();
238
239 let mut record_bound = |this: &mut Self,
240 ty_param: Symbol,
241 poly_trait_ref: &ast::PolyTraitRef| {
242 if !poly_trait_ref.bound_generic_params.is_empty() {
244 return;
245 }
246 if poly_trait_ref.modifiers != ast::TraitBoundModifiers::NONE {
247 return;
248 }
249 let Some(trait_seg) = poly_trait_ref.trait_ref.path.segments.last() else {
250 return;
251 };
252 let Some(partial_res) = this.r.partial_res_map.get(&trait_seg.id) else {
253 return;
254 };
255 let Some(trait_def_id) = partial_res.full_res().and_then(|res| res.opt_def_id()) else {
256 return;
257 };
258 let Some(assoc_type_def_id) =
259 this.trait_assoc_type_def_id_by_name(trait_def_id, assoc_name)
260 else {
261 return;
262 };
263
264 let trait_path =
268 path_to_string_without_assoc_item_bindings(&poly_trait_ref.trait_ref.path);
269 let trait_bounds = matching_bounds.entry(ty_param).or_default();
270 let trait_bounds = trait_bounds
271 .entry(trait_def_id)
272 .or_insert_with(|| (assoc_type_def_id, FxIndexSet::default()));
273 if true {
{
match (&trait_bounds.0, &assoc_type_def_id) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(trait_bounds.0, assoc_type_def_id);
274 trait_bounds.1.insert(trait_path);
275 };
276
277 let mut record_from_generics = |this: &mut Self, generics: &ast::Generics| {
278 for param in &generics.params {
279 let ast::GenericParamKind::Type { .. } = param.kind else { continue };
280 for bound in ¶m.bounds {
281 let ast::GenericBound::Trait(poly_trait_ref) = bound else { continue };
282 record_bound(this, param.ident.name, poly_trait_ref);
283 }
284 }
285
286 for predicate in &generics.where_clause.predicates {
287 let ast::WherePredicateKind::BoundPredicate(where_bound) = &predicate.kind else {
288 continue;
289 };
290
291 let ast::TyKind::Path(None, bounded_path) = &where_bound.bounded_ty.kind else {
292 continue;
293 };
294 let [ast::PathSegment { ident, args: None, .. }] = &bounded_path.segments[..]
295 else {
296 continue;
297 };
298
299 let Some(partial_res) = this.r.partial_res_map.get(&where_bound.bounded_ty.id)
301 else {
302 continue;
303 };
304 if !#[allow(non_exhaustive_omitted_patterns)] match partial_res.full_res() {
Some(Res::Def(DefKind::TyParam, _)) => true,
_ => false,
}matches!(partial_res.full_res(), Some(Res::Def(DefKind::TyParam, _))) {
305 continue;
306 }
307
308 for bound in &where_bound.bounds {
309 let ast::GenericBound::Trait(poly_trait_ref) = bound else { continue };
310 record_bound(this, ident.name, poly_trait_ref);
311 }
312 }
313 };
314
315 if let Some(item) = self.diag_metadata.current_item
316 && let Some(generics) = item.kind.generics()
317 {
318 record_from_generics(self, generics);
319 }
320
321 if let Some(item) = self.diag_metadata.current_item
322 && #[allow(non_exhaustive_omitted_patterns)] match item.kind {
ItemKind::Impl(..) => true,
_ => false,
}matches!(item.kind, ItemKind::Impl(..))
323 && let Some(assoc) = self.diag_metadata.current_impl_item
324 {
325 let generics = match &assoc.kind {
326 AssocItemKind::Const(ast::ConstItem { generics, .. })
327 | AssocItemKind::Fn(ast::Fn { generics, .. })
328 | AssocItemKind::Type(ast::TyAlias { generics, .. }) => Some(generics),
329 AssocItemKind::Delegation(..)
330 | AssocItemKind::MacCall(..)
331 | AssocItemKind::DelegationMac(..) => None,
332 };
333 if let Some(generics) = generics {
334 record_from_generics(self, generics);
335 }
336 }
337
338 let mut suggestions: FxIndexSet<String> = FxIndexSet::default();
339 for (ty_param, traits) in matching_bounds {
340 let ty_param = ty_param.to_ident_string();
341 let trait_paths_len: usize = traits.values().map(|(_, paths)| paths.len()).sum();
342 if traits.len() == 1 && trait_paths_len == 1 {
343 let assoc_type_def_id = traits.values().next().unwrap().0;
344 let assoc_segment = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", assoc_name,
self.r.item_required_generic_args_suggestion(assoc_type_def_id)))
})format!(
345 "{}{}",
346 assoc_name,
347 self.r.item_required_generic_args_suggestion(assoc_type_def_id)
348 );
349 suggestions.insert(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::{1}", ty_param,
assoc_segment))
})format!("{ty_param}::{assoc_segment}"));
350 } else {
351 for (assoc_type_def_id, trait_paths) in traits.into_values() {
352 let assoc_segment = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", assoc_name,
self.r.item_required_generic_args_suggestion(assoc_type_def_id)))
})format!(
353 "{}{}",
354 assoc_name,
355 self.r.item_required_generic_args_suggestion(assoc_type_def_id)
356 );
357 for trait_path in trait_paths {
358 suggestions
359 .insert(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0} as {1}>::{2}", ty_param,
trait_path, assoc_segment))
})format!("<{ty_param} as {trait_path}>::{assoc_segment}"));
360 }
361 }
362 }
363 }
364
365 if suggestions.is_empty() {
366 return false;
367 }
368
369 let mut suggestions: Vec<String> = suggestions.into_iter().collect();
370 suggestions.sort();
371
372 err.span_suggestions_with_style(
373 ident_span,
374 "you might have meant to use an associated type of the same name",
375 suggestions,
376 Applicability::MaybeIncorrect,
377 SuggestionStyle::ShowAlways,
378 );
379
380 true
381 }
382
383 fn make_base_error(
384 &mut self,
385 path: &[Segment],
386 span: Span,
387 source: PathSource<'_, 'ast, 'ra>,
388 res: Option<Res>,
389 could_be_expr: bool,
390 ) -> BaseError {
391 let mut expected = source.descr_expected();
393 let path_str = Segment::names_to_string(path);
394
395 if let Some(res) = res {
396 BaseError {
397 msg: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected {0}, found {1} `{2}`",
expected, res.descr(), path_str))
})format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
398 fallback_label: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("not a {0}", expected))
})format!("not a {expected}"),
399 span,
400 span_label: match res {
401 Res::Def(DefKind::TyParam, def_id) => {
402 Some((self.r.def_span(def_id), "found this type parameter"))
403 }
404 _ => None,
405 },
406 could_be_expr,
407 suggestion: None,
408 module: None,
409 notes: Vec::new(),
410 }
411 } else {
412 let mut span_label = None;
413 let item_ident = path.last().unwrap().ident;
414 let item_span = item_ident.span;
415 let (tick, mod_prefix, mod_str, module, suggestion) = if path.len() == 1 {
416 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/late/diagnostics.rs:416",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(416u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("self.diag_metadata.current_impl_items")
}> =
::tracing::__macro_support::FieldName::new("self.diag_metadata.current_impl_items");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self.diag_metadata.current_impl_items)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?self.diag_metadata.current_impl_items);
417 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/late/diagnostics.rs:417",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(417u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("self.diag_metadata.current_function")
}> =
::tracing::__macro_support::FieldName::new("self.diag_metadata.current_function");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self.diag_metadata.current_function)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?self.diag_metadata.current_function);
418 let suggestion = if self.current_trait_ref.is_none()
419 && let Some((fn_kind, _)) = self.diag_metadata.current_function
420 && let Some(FnCtxt::Assoc(_)) = fn_kind.ctxt()
421 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = fn_kind
422 && let Some(items) = self.diag_metadata.current_impl_items
423 && let Some(item) = items.iter().find(|i| {
424 i.kind.ident().is_some_and(|ident| {
425 ident.name == item_ident.name && !sig.span.contains(item_span)
427 })
428 }) {
429 let sp = item_span.shrink_to_lo();
430
431 let field = match source {
434 PathSource::Expr(Some(Expr { kind: ExprKind::Struct(expr), .. })) => {
435 expr.fields.iter().find(|f| f.ident == item_ident)
436 }
437 _ => None,
438 };
439 let pre = if let Some(field) = field
440 && field.is_shorthand
441 {
442 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", item_ident))
})format!("{item_ident}: ")
443 } else {
444 String::new()
445 };
446 let is_call = match field {
449 Some(ast::ExprField { expr, .. }) => {
450 #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
ExprKind::Call(..) => true,
_ => false,
}matches!(expr.kind, ExprKind::Call(..))
451 }
452 _ => #[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::Expr(Some(Expr { kind: ExprKind::Call(..), .. })) => true,
_ => false,
}matches!(
453 source,
454 PathSource::Expr(Some(Expr { kind: ExprKind::Call(..), .. })),
455 ),
456 };
457
458 match &item.kind {
459 AssocItemKind::Fn(fn_)
460 if (!sig.decl.has_self() || !is_call) && fn_.sig.decl.has_self() =>
461 {
462 span_label = Some((
466 fn_.ident.span,
467 "a method by that name is available on `Self` here",
468 ));
469 None
470 }
471 AssocItemKind::Fn(fn_) if !fn_.sig.decl.has_self() && !is_call => {
472 span_label = Some((
473 fn_.ident.span,
474 "an associated function by that name is available on `Self` here",
475 ));
476 None
477 }
478 AssocItemKind::Fn(fn_) if fn_.sig.decl.has_self() => {
479 Some((sp, "consider using the method on `Self`", ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}self.", pre))
})format!("{pre}self.")))
480 }
481 AssocItemKind::Fn(_) => Some((
482 sp,
483 "consider using the associated function on `Self`",
484 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}Self::", pre))
})format!("{pre}Self::"),
485 )),
486 AssocItemKind::Const(..) => Some((
487 sp,
488 "consider using the associated constant on `Self`",
489 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}Self::", pre))
})format!("{pre}Self::"),
490 )),
491 _ => None,
492 }
493 } else {
494 None
495 };
496 ("", String::new(), "this scope".to_string(), None, suggestion)
497 } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
498 if self.r.tcx.sess.edition() > Edition::Edition2015 {
499 expected = "crate";
502 ("", String::new(), "the list of imported crates".to_string(), None, None)
503 } else {
504 (
505 "",
506 String::new(),
507 "the crate root".to_string(),
508 Some(CRATE_DEF_ID.to_def_id()),
509 None,
510 )
511 }
512 } else if path.len() == 2 && path[0].ident.name == kw::Crate {
513 (
514 "",
515 String::new(),
516 "the crate root".to_string(),
517 Some(CRATE_DEF_ID.to_def_id()),
518 None,
519 )
520 } else {
521 let mod_path = &path[..path.len() - 1];
522 let mod_res = self.resolve_path(mod_path, Some(TypeNS), None, source);
523 let mod_prefix = match mod_res {
524 PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
525 _ => None,
526 };
527
528 let module_did = mod_prefix.as_ref().and_then(Res::mod_def_id);
529
530 let mod_prefix =
531 mod_prefix.map_or_else(String::new, |res| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} ", res.descr()))
})format!("{} ", res.descr()));
532 ("`", mod_prefix, Segment::names_to_string(mod_path), module_did, None)
533 };
534
535 let suggestion =
536 if ["true", "false"].contains(&item_ident.to_string().to_lowercase().as_str()) {
537 let item_typo = item_ident.to_string().to_lowercase();
539 Some((item_span, "you may want to use a bool value instead", item_typo))
540 } else if item_ident.as_str() == "printf" {
543 Some((
544 item_span,
545 "you may have meant to use the `print` macro",
546 "print!".to_owned(),
547 ))
548 } else {
549 suggestion
550 };
551 let mut msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot find {0} `{1}` in {2}{3}{4}{3}",
expected, item_ident, mod_prefix, tick, mod_str))
})format!(
552 "cannot find {expected} `{item_ident}` in {mod_prefix}{tick}{mod_str}{tick}"
553 );
554 let mut fallback_label = if path_str == "async" && expected.starts_with("struct") {
555 "`async` blocks are only allowed in Rust 2018 or later".to_string()
556 } else {
557 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("not found in {0}{1}{0}", tick,
mod_str))
})format!("not found in {tick}{mod_str}{tick}")
558 };
559 let mut notes = Vec::new();
560 if let Some(module_def_id) = module
561 && let Some(directive) = self.r.on_unknown_data(module_def_id)
562 {
563 let args = FormatArgs { unresolved: item_ident.to_string(), this: mod_str, .. };
564 let CustomDiagnostic {
565 message,
566 label,
567 notes: custom_notes,
568 parent_label: _unreachable,
569 } = directive.eval(None, &args);
570 if let Some(message) = message {
571 notes.push(msg);
572 msg = message;
573 }
574 if let Some(label) = label {
575 fallback_label = label;
576 if let Some((_, span_label)) = span_label.take() {
577 notes.push(span_label.to_string());
578 }
579 }
580 notes.extend(custom_notes);
581 }
582
583 BaseError {
584 msg,
585 fallback_label,
586 span: item_span,
587 span_label,
588 could_be_expr,
589 suggestion,
590 module,
591 notes,
592 }
593 }
594 }
595
596 fn could_be_expr(&self, res: Res, span: Span) -> bool {
597 match res {
598 Res::Def(DefKind::Fn, _) => self
600 .r
601 .tcx
602 .sess
603 .source_map()
604 .span_to_snippet(span)
605 .is_ok_and(|snippet| snippet.ends_with(')')),
606 Res::Def(
607 DefKind::Ctor(..) | DefKind::AssocFn | DefKind::Const | DefKind::AssocConst,
608 _,
609 )
610 | Res::SelfCtor(_)
611 | Res::PrimTy(_)
612 | Res::Local(_) => true,
613 _ => false,
614 }
615 }
616
617 pub(crate) fn smart_resolve_partial_mod_path_errors(
625 &mut self,
626 prefix_path: &[Segment],
627 following_seg: Option<&Segment>,
628 ) -> Vec<ImportSuggestion> {
629 if let Some(segment) = prefix_path.last()
630 && let Some(following_seg) = following_seg
631 {
632 let candidates = self.r.lookup_import_candidates(
633 segment.ident,
634 Namespace::TypeNS,
635 &self.parent_scope,
636 &|res: Res| #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Mod, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Mod, _)),
637 );
638 candidates
640 .into_iter()
641 .filter(|candidate| {
642 if let Some(def_id) = candidate.did
643 && let Some(module) = self.r.get_module(def_id)
644 {
645 Some(def_id) != self.parent_scope.module.opt_def_id()
646 && self
647 .r
648 .resolutions(module)
649 .iter()
650 .any(|(key, _r)| key.ident.name == following_seg.ident.name)
651 } else {
652 false
653 }
654 })
655 .collect::<Vec<_>>()
656 } else {
657 Vec::new()
658 }
659 }
660
661 {}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("smart_resolve_report_errors",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(663u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("path")
}> =
::tracing::__macro_support::FieldName::new("path");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("following_seg")
}> =
::tracing::__macro_support::FieldName::new("following_seg");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("span")
}> =
::tracing::__macro_support::FieldName::new("span");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("source")
}> =
::tracing::__macro_support::FieldName::new("source");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("res")
}> =
::tracing::__macro_support::FieldName::new("res");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("qself")
}> =
::tracing::__macro_support::FieldName::new("qself");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&following_seg)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&qself)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
(Diag<'tcx>, Vec<ImportSuggestion>) = loop {};
return __tracing_attr_fake_return;
}
{
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/late/diagnostics.rs:673",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(673u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("res")
}> =
::tracing::__macro_support::FieldName::new("res");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("source")
}> =
::tracing::__macro_support::FieldName::new("source");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let cross_namespace_res =
res.filter(|res| !res.matches_ns(source.namespace()));
let could_be_expr =
res.is_some_and(|res| self.could_be_expr(res, span));
let base_error =
self.make_base_error(path, span, source,
if cross_namespace_res.is_some() { None } else { res },
could_be_expr);
let code = source.error_code(res.is_some());
let mut err =
self.r.dcx().struct_span_err(base_error.span,
base_error.msg.clone());
err.code(code);
if let Some(res) = cross_namespace_res {
err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1} named `{2}` exists in another namespace",
res.article(), res.descr(), Segment::names_to_string(path)))
}));
}
if let Some(within_macro_span) =
base_error.span.within_macro(span,
self.r.tcx.sess.source_map()) {
err.span_label(within_macro_span,
"due to this macro variable");
}
self.detect_missing_binding_available_from_pattern(&mut err, path,
following_seg);
self.suggest_at_operator_in_slice_pat_with_range(&mut err, path);
self.suggest_range_struct_destructuring(&mut err, path, source);
self.suggest_swapping_misplaced_self_ty_and_trait(&mut err,
source, res, base_error.span);
if let Some((span, label)) = base_error.span_label {
err.span_label(span, label);
}
for note in &base_error.notes { err.note(note.clone()); }
if let Some((span, message, replacement)) = &base_error.suggestion
{
let ident = path.last().unwrap().ident;
let expression =
if span.is_empty() {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", replacement,
ident))
})
} else { replacement.clone() };
if !self.suggest_named_format_argument(&mut err, source,
ident, &expression, Applicability::MaybeIncorrect) {
err.span_suggestion_verbose(*span, *message, replacement,
Applicability::MaybeIncorrect);
}
}
self.suggest_changing_type_to_const_param(&mut err, res, source,
path, following_seg, span);
self.explain_functions_in_pattern(&mut err, res, source);
if self.suggest_pattern_match_with_let(&mut err, source, span) {
err.span_label(base_error.span, base_error.fallback_label);
return (err, Vec::new());
}
self.suggest_self_or_self_ref(&mut err, path, span);
self.detect_assoc_type_constraint_meant_as_path(&mut err,
&base_error);
self.detect_rtn_with_fully_qualified_path(&mut err, path,
following_seg, span, source, res, qself);
if self.suggest_self_ty(&mut err, source, path, span) ||
self.suggest_self_value(&mut err, source, path, span) {
return (err, Vec::new());
}
if let Some((did, item)) =
self.lookup_doc_alias_name(path, source.namespace()) {
let item_name = item.name;
let suggestion_name = self.r.tcx.item_name(did);
err.span_suggestion(item.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` has a name defined in the doc alias attribute as `{1}`",
suggestion_name, item_name))
}), suggestion_name, Applicability::MaybeIncorrect);
return (err, Vec::new());
};
let (found, suggested_candidates, mut candidates) =
self.try_lookup_name_relaxed(&mut err, source, path,
following_seg, span, res, &base_error);
if found { return (err, candidates); }
if self.suggest_shadowed(&mut err, source, path, following_seg,
span) {
candidates.clear();
}
let mut fallback =
self.suggest_trait_and_bounds(&mut err, source, res, span,
&base_error);
fallback |=
self.suggest_typo(&mut err, source, path, following_seg, span,
&base_error, suggested_candidates);
if fallback {
err.span_label(base_error.span, base_error.fallback_label);
}
self.err_code_special_cases(&mut err, source, path, span);
let module =
base_error.module.unwrap_or_else(|| CRATE_DEF_ID.to_def_id());
self.r.find_cfg_stripped(&mut err,
&path.last().unwrap().ident.name, module);
(err, candidates)
}
}
}#[tracing::instrument(skip(self), level = "debug")]
664 pub(crate) fn smart_resolve_report_errors(
665 &mut self,
666 path: &[Segment],
667 following_seg: Option<&Segment>,
668 span: Span,
669 source: PathSource<'_, 'ast, 'ra>,
670 res: Option<Res>,
671 qself: Option<&QSelf>,
672 ) -> (Diag<'tcx>, Vec<ImportSuggestion>) {
673 debug!(?res, ?source);
674 let cross_namespace_res = res.filter(|res| !res.matches_ns(source.namespace()));
675 let could_be_expr = res.is_some_and(|res| self.could_be_expr(res, span));
676 let base_error = self.make_base_error(
677 path,
678 span,
679 source,
680 if cross_namespace_res.is_some() { None } else { res },
681 could_be_expr,
682 );
683
684 let code = source.error_code(res.is_some());
685 let mut err = self.r.dcx().struct_span_err(base_error.span, base_error.msg.clone());
686 err.code(code);
687
688 if let Some(res) = cross_namespace_res {
689 err.note(format!(
690 "{} {} named `{}` exists in another namespace",
691 res.article(),
692 res.descr(),
693 Segment::names_to_string(path),
694 ));
695 }
696
697 if let Some(within_macro_span) =
700 base_error.span.within_macro(span, self.r.tcx.sess.source_map())
701 {
702 err.span_label(within_macro_span, "due to this macro variable");
703 }
704
705 self.detect_missing_binding_available_from_pattern(&mut err, path, following_seg);
706 self.suggest_at_operator_in_slice_pat_with_range(&mut err, path);
707 self.suggest_range_struct_destructuring(&mut err, path, source);
708 self.suggest_swapping_misplaced_self_ty_and_trait(&mut err, source, res, base_error.span);
709
710 if let Some((span, label)) = base_error.span_label {
711 err.span_label(span, label);
712 }
713 for note in &base_error.notes {
714 err.note(note.clone());
715 }
716
717 if let Some((span, message, replacement)) = &base_error.suggestion {
718 let ident = path.last().unwrap().ident;
719 let expression =
722 if span.is_empty() { format!("{replacement}{ident}") } else { replacement.clone() };
723 if !self.suggest_named_format_argument(
724 &mut err,
725 source,
726 ident,
727 &expression,
728 Applicability::MaybeIncorrect,
729 ) {
730 err.span_suggestion_verbose(
731 *span,
732 *message,
733 replacement,
734 Applicability::MaybeIncorrect,
735 );
736 }
737 }
738
739 self.suggest_changing_type_to_const_param(&mut err, res, source, path, following_seg, span);
740 self.explain_functions_in_pattern(&mut err, res, source);
741
742 if self.suggest_pattern_match_with_let(&mut err, source, span) {
743 err.span_label(base_error.span, base_error.fallback_label);
745 return (err, Vec::new());
746 }
747
748 self.suggest_self_or_self_ref(&mut err, path, span);
749 self.detect_assoc_type_constraint_meant_as_path(&mut err, &base_error);
750 self.detect_rtn_with_fully_qualified_path(
751 &mut err,
752 path,
753 following_seg,
754 span,
755 source,
756 res,
757 qself,
758 );
759 if self.suggest_self_ty(&mut err, source, path, span)
760 || self.suggest_self_value(&mut err, source, path, span)
761 {
762 return (err, Vec::new());
763 }
764
765 if let Some((did, item)) = self.lookup_doc_alias_name(path, source.namespace()) {
766 let item_name = item.name;
767 let suggestion_name = self.r.tcx.item_name(did);
768 err.span_suggestion(
769 item.span,
770 format!("`{suggestion_name}` has a name defined in the doc alias attribute as `{item_name}`"),
771 suggestion_name,
772 Applicability::MaybeIncorrect
773 );
774
775 return (err, Vec::new());
776 };
777
778 let (found, suggested_candidates, mut candidates) = self.try_lookup_name_relaxed(
779 &mut err,
780 source,
781 path,
782 following_seg,
783 span,
784 res,
785 &base_error,
786 );
787 if found {
788 return (err, candidates);
789 }
790
791 if self.suggest_shadowed(&mut err, source, path, following_seg, span) {
792 candidates.clear();
794 }
795
796 let mut fallback = self.suggest_trait_and_bounds(&mut err, source, res, span, &base_error);
797 fallback |= self.suggest_typo(
798 &mut err,
799 source,
800 path,
801 following_seg,
802 span,
803 &base_error,
804 suggested_candidates,
805 );
806
807 if fallback {
808 err.span_label(base_error.span, base_error.fallback_label);
810 }
811 self.err_code_special_cases(&mut err, source, path, span);
812
813 let module = base_error.module.unwrap_or_else(|| CRATE_DEF_ID.to_def_id());
814 self.r.find_cfg_stripped(&mut err, &path.last().unwrap().ident.name, module);
815
816 (err, candidates)
817 }
818
819 fn suggest_named_format_argument(
821 &self,
822 err: &mut Diag<'_>,
823 source: PathSource<'_, '_, '_>,
824 ident: Ident,
825 expression: &str,
826 applicability: Applicability,
827 ) -> bool {
828 let PathSource::Expr(Some(Expr {
829 kind: ExprKind::FormatArgs(args),
830 span: format_span,
831 ..
832 })) = source
833 else {
834 return false;
835 };
836 let argument = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} = {1}", ident, expression))
})format!("{ident} = {expression}");
837 let insertion = args
838 .arguments
839 .explicit_args()
840 .last()
841 .map_or(args.span, |arg| arg.original_span)
842 .shrink_to_hi();
843 let source_macro = format_span
845 .source_callee()
846 .and_then(|expn| expn.macro_def_id)
847 .filter(|def_id| !def_id.is_local())
849 .and_then(|def_id| self.r.tcx.get_diagnostic_name(def_id));
850 if #[allow(non_exhaustive_omitted_patterns)] match source_macro {
Some(sym::format_macro | sym::format_args_macro | sym::print_macro |
sym::println_macro | sym::eprint_macro | sym::eprintln_macro |
sym::write_macro | sym::writeln_macro | sym::assert_macro |
sym::assert_eq_macro | sym::assert_ne_macro | sym::debug_assert_macro
| sym::debug_assert_eq_macro | sym::debug_assert_ne_macro |
sym::core_panic_macro | sym::std_panic_macro | sym::unreachable_macro
| sym::todo_macro | sym::unimplemented_macro) => true,
_ => false,
}matches!(
851 source_macro,
852 Some(
853 sym::format_macro
854 | sym::format_args_macro
855 | sym::print_macro
856 | sym::println_macro
857 | sym::eprint_macro
858 | sym::eprintln_macro
859 | sym::write_macro
860 | sym::writeln_macro
861 | sym::assert_macro
862 | sym::assert_eq_macro
863 | sym::assert_ne_macro
864 | sym::debug_assert_macro
865 | sym::debug_assert_eq_macro
866 | sym::debug_assert_ne_macro
867 | sym::core_panic_macro
868 | sym::std_panic_macro
869 | sym::unreachable_macro
870 | sym::todo_macro
871 | sym::unimplemented_macro
872 )
873 ) && !insertion.from_expansion()
874 && !args.span.from_expansion()
875 {
876 err.span_suggestion_verbose(
877 insertion,
878 "you might have meant to add a named formatting argument",
879 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", {0}", argument))
})format!(", {argument}"),
880 applicability,
881 );
882 } else {
883 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might have meant to add a named formatting argument: `{0}`",
argument))
})format!(
884 "you might have meant to add a named formatting argument: `{argument}`"
885 ));
886 }
887 true
888 }
889
890 fn detect_rtn_with_fully_qualified_path(
891 &self,
892 err: &mut Diag<'_>,
893 path: &[Segment],
894 following_seg: Option<&Segment>,
895 span: Span,
896 source: PathSource<'_, '_, '_>,
897 res: Option<Res>,
898 qself: Option<&QSelf>,
899 ) {
900 if let Some(Res::Def(DefKind::AssocFn, _)) = res
901 && let PathSource::TraitItem(TypeNS, _) = source
902 && let None = following_seg
903 && let Some(qself) = qself
904 && let TyKind::Path(None, ty_path) = &qself.ty.kind
905 && ty_path.segments.len() == 1
906 && self.diag_metadata.current_where_predicate.is_some()
907 {
908 err.span_suggestion_verbose(
909 span,
910 "you might have meant to use the return type notation syntax",
911 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::{1}(..)",
ty_path.segments[0].ident, path[path.len() - 1].ident))
})format!("{}::{}(..)", ty_path.segments[0].ident, path[path.len() - 1].ident),
912 Applicability::MaybeIncorrect,
913 );
914 }
915 }
916
917 fn detect_assoc_type_constraint_meant_as_path(
918 &self,
919 err: &mut Diag<'_>,
920 base_error: &BaseError,
921 ) {
922 let Some(ty) = self.diag_metadata.current_type_path else {
923 return;
924 };
925 let TyKind::Path(_, path) = &ty.kind else {
926 return;
927 };
928 for segment in &path.segments {
929 let Some(params) = &segment.args else {
930 continue;
931 };
932 let ast::GenericArgs::AngleBracketed(params) = params.deref() else {
933 continue;
934 };
935 for param in ¶ms.args {
936 let ast::AngleBracketedArg::Constraint(constraint) = param else {
937 continue;
938 };
939 let ast::AssocItemConstraintKind::Bound { bounds } = &constraint.kind else {
940 continue;
941 };
942 for bound in bounds {
943 let ast::GenericBound::Trait(trait_ref) = bound else {
944 continue;
945 };
946 if trait_ref.modifiers == ast::TraitBoundModifiers::NONE
947 && base_error.span == trait_ref.span
948 {
949 err.span_suggestion_verbose(
950 constraint.ident.span.between(trait_ref.span),
951 "you might have meant to write a path instead of an associated type bound",
952 "::",
953 Applicability::MachineApplicable,
954 );
955 }
956 }
957 }
958 }
959 }
960
961 fn suggest_self_or_self_ref(&mut self, err: &mut Diag<'_>, path: &[Segment], span: Span) {
962 if !self.self_type_is_available() {
963 return;
964 }
965 let Some(path_last_segment) = path.last() else { return };
966 let item_str = path_last_segment.ident;
967 if ["this", "my"].contains(&item_str.as_str()) {
969 err.span_suggestion_short(
970 span,
971 "you might have meant to use `self` here instead",
972 "self",
973 Applicability::MaybeIncorrect,
974 );
975 if !self.self_value_is_available(path[0].ident.span) {
976 if let Some((FnKind::Fn(_, _, ast::Fn { sig, .. }), fn_span)) =
977 &self.diag_metadata.current_function
978 {
979 let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) {
980 (param.span.shrink_to_lo(), "&self, ")
981 } else {
982 (
983 self.r
984 .tcx
985 .sess
986 .source_map()
987 .span_through_char(*fn_span, '(')
988 .shrink_to_hi(),
989 "&self",
990 )
991 };
992 err.span_suggestion_verbose(
993 span,
994 "if you meant to use `self`, you are also missing a `self` receiver \
995 argument",
996 sugg,
997 Applicability::MaybeIncorrect,
998 );
999 }
1000 }
1001 }
1002 }
1003
1004 fn try_lookup_name_relaxed(
1005 &mut self,
1006 err: &mut Diag<'_>,
1007 source: PathSource<'_, '_, '_>,
1008 path: &[Segment],
1009 following_seg: Option<&Segment>,
1010 span: Span,
1011 res: Option<Res>,
1012 base_error: &BaseError,
1013 ) -> (bool, FxHashSet<String>, Vec<ImportSuggestion>) {
1014 let span = match following_seg {
1015 Some(_) if path[0].ident.span.eq_ctxt(path[path.len() - 1].ident.span) => {
1016 path[0].ident.span.to(path[path.len() - 1].ident.span)
1019 }
1020 _ => span,
1021 };
1022 let mut suggested_candidates = FxHashSet::default();
1023 let ident = path.last().unwrap().ident;
1025 let is_expected = &|res| source.is_expected(res);
1026 let ns = source.namespace();
1027 let is_enum_variant = &|res| #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Variant, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Variant, _));
1028 let path_str = Segment::names_to_string(path);
1029 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
1030 let mut candidates = self
1031 .r
1032 .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
1033 .into_iter()
1034 .filter(|ImportSuggestion { did, .. }| {
1035 match (did, res.and_then(|res| res.opt_def_id())) {
1036 (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
1037 _ => true,
1038 }
1039 })
1040 .collect::<Vec<_>>();
1041 let intrinsic_candidates: Vec<_> = candidates
1044 .extract_if(.., |sugg| {
1045 let path = path_names_to_string(&sugg.path);
1046 path.starts_with("core::intrinsics::") || path.starts_with("std::intrinsics::")
1047 })
1048 .collect();
1049 if candidates.is_empty() {
1050 candidates = intrinsic_candidates;
1052 }
1053 let crate_def_id = CRATE_DEF_ID.to_def_id();
1054 if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
1055 let mut enum_candidates: Vec<_> = self
1056 .r
1057 .lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant)
1058 .into_iter()
1059 .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
1060 .filter(|(_, enum_ty_path)| !enum_ty_path.starts_with("std::prelude::"))
1061 .collect();
1062 if !enum_candidates.is_empty() {
1063 enum_candidates.sort();
1064
1065 let preamble = if res.is_none() {
1068 let others = match enum_candidates.len() {
1069 1 => String::new(),
1070 2 => " and 1 other".to_owned(),
1071 n => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" and {0} others", n))
})format!(" and {n} others"),
1072 };
1073 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("there is an enum variant `{0}`{1}; ",
enum_candidates[0].0, others))
})format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
1074 } else {
1075 String::new()
1076 };
1077 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}try using the variant\'s enum",
preamble))
})format!("{preamble}try using the variant's enum");
1078
1079 suggested_candidates.extend(
1080 enum_candidates
1081 .iter()
1082 .map(|(_variant_path, enum_ty_path)| enum_ty_path.clone()),
1083 );
1084 err.span_suggestions(
1085 span,
1086 msg,
1087 enum_candidates.into_iter().map(|(_variant_path, enum_ty_path)| enum_ty_path),
1088 Applicability::MachineApplicable,
1089 );
1090 }
1091 }
1092
1093 let typo_sugg = self
1095 .lookup_typo_candidate(path, following_seg, source.namespace(), is_expected)
1096 .to_opt_suggestion()
1097 .filter(|sugg| !suggested_candidates.contains(sugg.candidate.as_str()));
1098 if let [segment] = path
1099 && !#[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::Delegation => true,
_ => false,
}matches!(source, PathSource::Delegation)
1100 && self.self_type_is_available()
1101 {
1102 if let Some((candidate, def_span)) =
1103 self.lookup_assoc_candidate(ident, ns, is_expected, source.is_call())
1104 {
1105 let self_is_available = self.self_value_is_available(segment.ident.span);
1106 let pre = match source {
1109 PathSource::Expr(Some(Expr { kind: ExprKind::Struct(expr), .. }))
1110 if expr
1111 .fields
1112 .iter()
1113 .any(|f| f.ident == segment.ident && f.is_shorthand) =>
1114 {
1115 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", path_str))
})format!("{path_str}: ")
1116 }
1117 _ => String::new(),
1118 };
1119 match candidate {
1120 AssocSuggestion::Field => {
1121 if self_is_available {
1122 if !self.suggest_named_format_argument(
1123 err,
1124 source,
1125 segment.ident,
1126 &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("self.{0}", segment.ident))
})format!("self.{}", segment.ident),
1127 Applicability::MaybeIncorrect,
1128 ) {
1129 err.span_suggestion_verbose(
1130 span.shrink_to_lo(),
1131 "you might have meant to use the available field",
1132 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}self.", pre))
})format!("{pre}self."),
1133 Applicability::MaybeIncorrect,
1134 );
1135 }
1136 } else {
1137 err.span_label(def_span, "a field by that name exists in `Self`");
1138 }
1139 }
1140 AssocSuggestion::MethodWithSelf { .. }
1141 | AssocSuggestion::AssocFn { .. }
1142 | AssocSuggestion::AssocType
1143 if #[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::Expr(Some(Expr { kind: ExprKind::FormatArgs(_), .. })) =>
true,
_ => false,
}matches!(
1144 source,
1145 PathSource::Expr(Some(Expr { kind: ExprKind::FormatArgs(_), .. }))
1146 ) =>
1147 {
1148 let kind = match candidate {
1149 AssocSuggestion::MethodWithSelf { .. } => "a method",
1150 AssocSuggestion::AssocFn { .. } => "an associated function",
1151 AssocSuggestion::AssocType => "an associated type",
1152 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1153 };
1154 err.span_label(
1155 def_span,
1156 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} by that name is available on `Self` here",
kind))
})format!("{kind} by that name is available on `Self` here"),
1157 );
1158 }
1159 AssocSuggestion::MethodWithSelf { called } if self_is_available => {
1160 let msg = if called {
1161 "you might have meant to call the method"
1162 } else {
1163 "you might have meant to refer to the method"
1164 };
1165 err.span_suggestion_verbose(
1166 span.shrink_to_lo(),
1167 msg,
1168 "self.",
1169 Applicability::MachineApplicable,
1170 );
1171 }
1172 AssocSuggestion::MethodWithSelf { .. }
1173 | AssocSuggestion::AssocFn { .. }
1174 | AssocSuggestion::AssocConst
1175 | AssocSuggestion::AssocType => {
1176 if !#[allow(non_exhaustive_omitted_patterns)] match candidate {
AssocSuggestion::AssocConst => true,
_ => false,
}matches!(candidate, AssocSuggestion::AssocConst)
1177 || !self.suggest_named_format_argument(
1178 err,
1179 source,
1180 segment.ident,
1181 &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Self::{0}", segment.ident))
})format!("Self::{}", segment.ident),
1182 Applicability::MaybeIncorrect,
1183 )
1184 {
1185 err.span_suggestion_verbose(
1186 span.shrink_to_lo(),
1187 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might have meant to {0}",
candidate.action()))
})format!("you might have meant to {}", candidate.action()),
1188 "Self::",
1189 Applicability::MachineApplicable,
1190 );
1191 }
1192 }
1193 }
1194 self.r.add_typo_suggestion(err, typo_sugg, ident_span);
1195 return (true, suggested_candidates, candidates);
1196 }
1197
1198 if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
1200 let mut args_snippet = String::new();
1201 if let Some(args_span) = args_span
1202 && let Ok(snippet) = self.r.tcx.sess.source_map().span_to_snippet(args_span)
1203 {
1204 args_snippet = snippet;
1205 }
1206
1207 if let Some(Res::Def(DefKind::Struct, def_id)) = res {
1208 if let Some(ctor) = self.r.struct_ctor(def_id)
1209 && ctor.has_private_fields(self.parent_scope.module, self.r)
1210 {
1211 if #[allow(non_exhaustive_omitted_patterns)] match ctor.res {
Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), _) => true,
_ => false,
}matches!(
1212 ctor.res,
1213 Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), _)
1214 ) {
1215 self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
1216 }
1217 err.note("constructor is not visible here due to private fields");
1218 }
1219 } else {
1220 err.span_suggestion(
1221 call_span,
1222 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("try calling `{0}` as a method",
ident))
})format!("try calling `{ident}` as a method"),
1223 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("self.{0}({1})", path_str,
args_snippet))
})format!("self.{path_str}({args_snippet})"),
1224 Applicability::MachineApplicable,
1225 );
1226 }
1227
1228 return (true, suggested_candidates, candidates);
1229 }
1230 }
1231
1232 if let Some(res) = res {
1234 if self.smart_resolve_context_dependent_help(
1235 err,
1236 span,
1237 source,
1238 path,
1239 res,
1240 &path_str,
1241 &base_error.fallback_label,
1242 ) {
1243 self.r.add_typo_suggestion(err, typo_sugg, ident_span);
1245 return (true, suggested_candidates, candidates);
1246 }
1247 }
1248
1249 if let Some(rib) = &self.last_block_rib {
1251 for (ident, &res) in &rib.bindings {
1252 if let Res::Local(_) = res
1253 && path.len() == 1
1254 && ident.span.eq_ctxt(path[0].ident.span)
1255 && ident.name == path[0].ident.name
1256 {
1257 err.span_help(
1258 ident.span,
1259 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the binding `{0}` is available in a different scope in the same function",
path_str))
})format!("the binding `{path_str}` is available in a different scope in the same function"),
1260 );
1261 return (true, suggested_candidates, candidates);
1262 }
1263 }
1264 }
1265
1266 if candidates.is_empty() {
1267 candidates = self.smart_resolve_partial_mod_path_errors(path, following_seg);
1268 }
1269
1270 (false, suggested_candidates, candidates)
1271 }
1272
1273 fn lookup_doc_alias_name(&mut self, path: &[Segment], ns: Namespace) -> Option<(DefId, Ident)> {
1274 let find_doc_alias_name = |r: &mut Resolver<'ra, '_>, m: Module<'ra>, item_name: Symbol| {
1275 for resolution in r.resolutions(m).values() {
1276 let Some(did) =
1277 resolution.borrow(r).best_decl().and_then(|binding| binding.res().opt_def_id())
1278 else {
1279 continue;
1280 };
1281 if did.is_local() {
1282 continue;
1286 }
1287 if let Some(d) = {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(did, &r.tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(Doc(d)) => {
break 'done Some(d);
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}hir::find_attr!(r.tcx, did, Doc(d) => d)
1288 && d.aliases.contains_key(&item_name)
1289 {
1290 return Some(did);
1291 }
1292 }
1293 None
1294 };
1295
1296 if path.len() == 1 {
1297 for rib in self.ribs[ns].iter().rev() {
1298 let item = path[0].ident;
1299 if let RibKind::Module(module) | RibKind::Block(Some(module)) = rib.kind
1300 && let Some(did) = find_doc_alias_name(self.r, module.to_module(), item.name)
1301 {
1302 return Some((did, item));
1303 }
1304 }
1305 } else {
1306 for (idx, seg) in path.iter().enumerate().rev().skip(1) {
1315 let Some(id) = seg.id else {
1316 continue;
1317 };
1318 let Some(res) = self.r.partial_res_map.get(&id) else {
1319 continue;
1320 };
1321 if let Res::Def(DefKind::Mod, module) = res.expect_full_res()
1322 && let module = self.r.expect_module(module)
1323 && let item = path[idx + 1].ident
1324 && let Some(did) = find_doc_alias_name(self.r, module, item.name)
1325 {
1326 return Some((did, item));
1327 }
1328 break;
1329 }
1330 }
1331 None
1332 }
1333
1334 fn suggest_trait_and_bounds(
1335 &self,
1336 err: &mut Diag<'_>,
1337 source: PathSource<'_, '_, '_>,
1338 res: Option<Res>,
1339 span: Span,
1340 base_error: &BaseError,
1341 ) -> bool {
1342 let is_macro =
1343 base_error.span.from_expansion() && base_error.span.desugaring_kind().is_none();
1344 let mut fallback = false;
1345
1346 if let (
1347 PathSource::Trait(AliasPossibility::Maybe),
1348 Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)),
1349 false,
1350 ) = (source, res, is_macro)
1351 && let Some(bounds @ [first_bound, .., last_bound]) =
1352 self.diag_metadata.current_trait_object
1353 {
1354 fallback = true;
1355 let spans: Vec<Span> = bounds
1356 .iter()
1357 .map(|bound| bound.span())
1358 .filter(|&sp| sp != base_error.span)
1359 .collect();
1360
1361 let start_span = first_bound.span();
1362 let end_span = last_bound.span();
1364 let last_bound_span = spans.last().cloned().unwrap();
1366 let mut multi_span: MultiSpan = spans.clone().into();
1367 for sp in spans {
1368 let msg = if sp == last_bound_span {
1369 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("...because of {0} bound{1}",
if bounds.len() - 1 == 1 { "this" } else { "these" },
if bounds.len() - 1 == 1 { "" } else { "s" }))
})format!(
1370 "...because of {these} bound{s}",
1371 these = pluralize!("this", bounds.len() - 1),
1372 s = pluralize!(bounds.len() - 1),
1373 )
1374 } else {
1375 String::new()
1376 };
1377 multi_span.push_span_label(sp, msg);
1378 }
1379 multi_span.push_span_label(base_error.span, "expected this type to be a trait...");
1380 err.span_help(
1381 multi_span,
1382 "`+` is used to constrain a \"trait object\" type with lifetimes or \
1383 auto-traits; structs and enums can't be bound in that way",
1384 );
1385 if bounds.iter().all(|bound| match bound {
1386 ast::GenericBound::Outlives(_) | ast::GenericBound::Use(..) => true,
1387 ast::GenericBound::Trait(tr) => tr.span == base_error.span,
1388 }) {
1389 let mut sugg = ::alloc::vec::Vec::new()vec![];
1390 if base_error.span != start_span {
1391 sugg.push((start_span.until(base_error.span), String::new()));
1392 }
1393 if base_error.span != end_span {
1394 sugg.push((base_error.span.shrink_to_hi().to(end_span), String::new()));
1395 }
1396
1397 err.multipart_suggestion(
1398 "if you meant to use a type and not a trait here, remove the bounds",
1399 sugg,
1400 Applicability::MaybeIncorrect,
1401 );
1402 }
1403 }
1404
1405 fallback |= self.restrict_assoc_type_in_where_clause(span, err);
1406 fallback
1407 }
1408
1409 fn suggest_typo(
1410 &mut self,
1411 err: &mut Diag<'_>,
1412 source: PathSource<'_, 'ast, 'ra>,
1413 path: &[Segment],
1414 following_seg: Option<&Segment>,
1415 span: Span,
1416 base_error: &BaseError,
1417 suggested_candidates: FxHashSet<String>,
1418 ) -> bool {
1419 let is_expected = &|res| source.is_expected(res);
1420 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
1421
1422 if self.suggest_assoc_type_from_bounds(err, source, path, ident_span) {
1426 return false;
1427 }
1428
1429 let typo_sugg =
1430 self.lookup_typo_candidate(path, following_seg, source.namespace(), is_expected);
1431 let mut fallback = true;
1432 let typo_sugg = typo_sugg
1433 .to_opt_suggestion()
1434 .filter(|sugg| !suggested_candidates.contains(sugg.candidate.as_str()));
1435 self.r.add_typo_suggestion(err, typo_sugg, ident_span);
1436
1437 match self.diag_metadata.current_let_binding {
1438 Some((pat_sp, Some(ty_sp), None))
1439 if ty_sp.contains(base_error.span) && base_error.could_be_expr =>
1440 {
1441 err.span_suggestion_verbose(
1442 pat_sp.between(ty_sp),
1443 "use `=` if you meant to assign",
1444 " = ",
1445 Applicability::MaybeIncorrect,
1446 );
1447 }
1448 _ => {}
1449 }
1450
1451 let suggestion = self.get_single_associated_item(path, &source, is_expected);
1453 self.r.add_typo_suggestion(err, suggestion, ident_span);
1454
1455 if self.let_binding_suggestion(err, ident_span) {
1456 fallback = false;
1457 }
1458
1459 fallback
1460 }
1461
1462 fn suggest_shadowed(
1463 &mut self,
1464 err: &mut Diag<'_>,
1465 source: PathSource<'_, '_, '_>,
1466 path: &[Segment],
1467 following_seg: Option<&Segment>,
1468 span: Span,
1469 ) -> bool {
1470 let is_expected = &|res| source.is_expected(res);
1471 let typo_sugg =
1472 self.lookup_typo_candidate(path, following_seg, source.namespace(), is_expected);
1473 let is_in_same_file = &|sp1, sp2| {
1474 let source_map = self.r.tcx.sess.source_map();
1475 let file1 = source_map.span_to_filename(sp1);
1476 let file2 = source_map.span_to_filename(sp2);
1477 file1 == file2
1478 };
1479 if let TypoCandidate::Shadowed(res, Some(sugg_span)) = typo_sugg
1484 && res.opt_def_id().is_some_and(|id| id.is_local() || is_in_same_file(span, sugg_span))
1485 {
1486 err.span_label(
1487 sugg_span,
1488 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might have meant to refer to this {0}",
res.descr()))
})format!("you might have meant to refer to this {}", res.descr()),
1489 );
1490 return true;
1491 }
1492 false
1493 }
1494
1495 fn err_code_special_cases(
1496 &mut self,
1497 err: &mut Diag<'_>,
1498 source: PathSource<'_, '_, '_>,
1499 path: &[Segment],
1500 span: Span,
1501 ) {
1502 if let Some(err_code) = err.code {
1503 if err_code == E0425 {
1504 for label_rib in &self.label_ribs {
1505 for (label_ident, node_id) in &label_rib.bindings {
1506 let ident = path.last().unwrap().ident;
1507 if ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\'{0}", ident))
})format!("'{ident}") == label_ident.to_string() {
1508 err.span_label(label_ident.span, "a label with a similar name exists");
1509 if let PathSource::Expr(Some(Expr {
1510 kind: ExprKind::Break(None, Some(_)),
1511 ..
1512 })) = source
1513 {
1514 err.span_suggestion(
1515 span,
1516 "use the similarly named label",
1517 label_ident.name,
1518 Applicability::MaybeIncorrect,
1519 );
1520 self.diag_metadata.unused_labels.swap_remove(node_id);
1522 }
1523 }
1524 }
1525 }
1526
1527 self.suggest_ident_hidden_by_hygiene(err, path, span);
1528 if let Some(correct) = Self::likely_rust_type(path) {
1530 err.span_suggestion(
1531 span,
1532 "perhaps you intended to use this type",
1533 correct,
1534 Applicability::MaybeIncorrect,
1535 );
1536 }
1537 }
1538 }
1539 }
1540
1541 fn suggest_ident_hidden_by_hygiene(&self, err: &mut Diag<'_>, path: &[Segment], span: Span) {
1542 let [segment] = path else { return };
1543
1544 let ident = segment.ident;
1545 let callsite_span = span.source_callsite();
1546 for rib in self.ribs[ValueNS].iter().rev() {
1547 for (binding_ident, _) in &rib.bindings {
1548 if binding_ident.name == ident.name
1550 && !binding_ident.span.eq_ctxt(span)
1551 && !binding_ident.span.from_expansion()
1552 && binding_ident.span.lo() < callsite_span.lo()
1553 {
1554 err.span_help(
1555 binding_ident.span,
1556 "an identifier with the same name exists, but is not accessible due to macro hygiene",
1557 );
1558 return;
1559 }
1560
1561 if binding_ident.name == ident.name
1563 && binding_ident.span.from_expansion()
1564 && binding_ident.span.source_callsite().eq_ctxt(callsite_span)
1565 && binding_ident.span.source_callsite().lo() < callsite_span.lo()
1566 {
1567 err.span_help(
1568 binding_ident.span,
1569 "an identifier with the same name is defined here, but is not accessible due to macro hygiene",
1570 );
1571 return;
1572 }
1573 }
1574 }
1575 }
1576
1577 fn suggest_self_ty(
1579 &self,
1580 err: &mut Diag<'_>,
1581 source: PathSource<'_, '_, '_>,
1582 path: &[Segment],
1583 span: Span,
1584 ) -> bool {
1585 if !is_self_type(path, source.namespace()) {
1586 return false;
1587 }
1588 err.code(E0411);
1589 err.span_label(span, "`Self` is only available in impls, traits, and type definitions");
1590 if let Some(item) = self.diag_metadata.current_item
1591 && let Some(ident) = item.kind.ident()
1592 {
1593 err.span_label(
1594 ident.span,
1595 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`Self` not allowed in {0} {1}",
item.kind.article(), item.kind.descr()))
})format!("`Self` not allowed in {} {}", item.kind.article(), item.kind.descr()),
1596 );
1597 }
1598 true
1599 }
1600
1601 fn suggest_self_value(
1602 &mut self,
1603 err: &mut Diag<'_>,
1604 source: PathSource<'_, '_, '_>,
1605 path: &[Segment],
1606 span: Span,
1607 ) -> bool {
1608 if !is_self_value(path, source.namespace()) {
1609 return false;
1610 }
1611
1612 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/late/diagnostics.rs:1612",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(1612u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("smart_resolve_path_fragment: E0424, source={0:?}",
source) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
1613 err.code(E0424);
1614 err.span_label(
1615 span,
1616 match source {
1617 PathSource::Pat => {
1618 "`self` value is a keyword and may not be bound to variables or shadowed"
1619 }
1620 _ => "`self` value is a keyword only available in methods with a `self` parameter",
1621 },
1622 );
1623
1624 if #[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::Pat => true,
_ => false,
}matches!(source, PathSource::Pat) {
1627 return true;
1628 }
1629
1630 let is_assoc_fn = self.self_type_is_available();
1631 let self_from_macro = "a `self` parameter, but a macro invocation can only \
1632 access identifiers it receives from parameters";
1633 if let Some((fn_kind, fn_span)) = &self.diag_metadata.current_function {
1634 if fn_kind.decl().inputs.get(0).is_some_and(|p| p.is_self()) {
1639 err.span_label(*fn_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this function has {0}",
self_from_macro))
})format!("this function has {self_from_macro}"));
1640 } else {
1641 let doesnt = if is_assoc_fn {
1642 let (span, sugg) = fn_kind
1643 .decl()
1644 .inputs
1645 .get(0)
1646 .map(|p| (p.span.shrink_to_lo(), "&self, "))
1647 .unwrap_or_else(|| {
1648 let span = fn_kind
1651 .ident()
1652 .map_or(*fn_span, |ident| fn_span.with_lo(ident.span.hi()));
1653 (
1654 self.r
1655 .tcx
1656 .sess
1657 .source_map()
1658 .span_through_char(span, '(')
1659 .shrink_to_hi(),
1660 "&self",
1661 )
1662 });
1663 err.span_suggestion_verbose(
1664 span,
1665 "add a `self` receiver parameter to make the associated `fn` a method",
1666 sugg,
1667 Applicability::MaybeIncorrect,
1668 );
1669 "doesn't"
1670 } else {
1671 "can't"
1672 };
1673 if let Some(ident) = fn_kind.ident() {
1674 err.span_label(
1675 ident.span,
1676 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this function {0} have a `self` parameter",
doesnt))
})format!("this function {doesnt} have a `self` parameter"),
1677 );
1678 }
1679 }
1680 } else if let Some(item) = self.diag_metadata.current_item {
1681 if #[allow(non_exhaustive_omitted_patterns)] match item.kind {
ItemKind::Delegation(..) => true,
_ => false,
}matches!(item.kind, ItemKind::Delegation(..)) {
1682 err.span_label(item.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("delegation supports {0}",
self_from_macro))
})format!("delegation supports {self_from_macro}"));
1683 } else {
1684 let span = if let Some(ident) = item.kind.ident() { ident.span } else { item.span };
1685 err.span_label(
1686 span,
1687 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`self` not allowed in {0} {1}",
item.kind.article(), item.kind.descr()))
})format!("`self` not allowed in {} {}", item.kind.article(), item.kind.descr()),
1688 );
1689 }
1690 }
1691 true
1692 }
1693
1694 fn detect_missing_binding_available_from_pattern(
1695 &self,
1696 err: &mut Diag<'_>,
1697 path: &[Segment],
1698 following_seg: Option<&Segment>,
1699 ) {
1700 let [segment] = path else { return };
1701 let None = following_seg else { return };
1702 for rib in self.ribs[ValueNS].iter().rev() {
1703 let patterns_with_skipped_bindings =
1704 self.r.tcx.with_stable_hashing_context(|mut hcx| {
1705 rib.patterns_with_skipped_bindings.to_sorted(&mut hcx, true)
1706 });
1707 for (def_id, spans) in patterns_with_skipped_bindings {
1708 if let DefKind::Struct | DefKind::Variant = self.r.tcx.def_kind(*def_id)
1709 && let Some(fields) = self.r.field_idents(*def_id)
1710 {
1711 for field in fields {
1712 if field.name == segment.ident.name {
1713 if spans.iter().all(|(.., had_error)| had_error.is_err()) {
1714 let multispan: MultiSpan =
1717 spans.iter().map(|(s, ..)| *s).collect::<Vec<_>>().into();
1718 err.span_note(
1719 multispan,
1720 "this pattern had a recovered parse error which likely lost \
1721 the expected fields",
1722 );
1723 err.downgrade_to_delayed_bug();
1724 }
1725 let ty = self.r.tcx.item_name(*def_id);
1726 for (span, rest_span, _) in spans {
1727 err.span_label(
1728 *span,
1729 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this pattern doesn\'t include `{0}`, which is available in `{1}`",
field, ty))
})format!(
1730 "this pattern doesn't include `{field}`, which is \
1731 available in `{ty}`",
1732 ),
1733 );
1734 if let Some(rest_span) = rest_span {
1735 err.span_suggestion_verbose(
1736 *rest_span,
1737 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("include `{0}` in the pattern",
field))
})format!("include `{field}` in the pattern"),
1738 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, ..", field))
})format!("{field}, .."),
1739 Applicability::MaybeIncorrect,
1740 );
1741 }
1742 }
1743 }
1744 }
1745 }
1746 }
1747 }
1748 }
1749
1750 fn suggest_at_operator_in_slice_pat_with_range(&self, err: &mut Diag<'_>, path: &[Segment]) {
1751 let Some(pat) = self.diag_metadata.current_pat else { return };
1752 let (bound, side, range) = match &pat.kind {
1753 ast::PatKind::Range(Some(bound), None, range) => (bound, Side::Start, range),
1754 ast::PatKind::Range(None, Some(bound), range) => (bound, Side::End, range),
1755 _ => return,
1756 };
1757 if let ExprKind::Path(None, range_path) = &bound.kind
1758 && let [segment] = &range_path.segments[..]
1759 && let [s] = path
1760 && segment.ident == s.ident
1761 && segment.ident.span.eq_ctxt(range.span)
1762 {
1763 let (span, snippet) = match side {
1766 Side::Start => (segment.ident.span.between(range.span), " @ ".into()),
1767 Side::End => (range.span.to(segment.ident.span), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} @ ..", segment.ident))
})format!("{} @ ..", segment.ident)),
1768 };
1769 err.subdiagnostic(diagnostics::UnexpectedResUseAtOpInSlicePatWithRangeSugg {
1770 span,
1771 ident: segment.ident,
1772 snippet,
1773 });
1774 }
1775
1776 enum Side {
1777 Start,
1778 End,
1779 }
1780 }
1781
1782 fn suggest_range_struct_destructuring(
1783 &mut self,
1784 err: &mut Diag<'_>,
1785 path: &[Segment],
1786 source: PathSource<'_, '_, '_>,
1787 ) {
1788 if !#[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::Pat | PathSource::TupleStruct(..) | PathSource::Expr(..) =>
true,
_ => false,
}matches!(source, PathSource::Pat | PathSource::TupleStruct(..) | PathSource::Expr(..)) {
1789 return;
1790 }
1791
1792 let Some(pat) = self.diag_metadata.current_pat else { return };
1793 let ast::PatKind::Range(start, end, end_kind) = &pat.kind else { return };
1794
1795 let [segment] = path else { return };
1796 let failing_span = segment.ident.span;
1797
1798 let in_start = start.as_ref().is_some_and(|e| e.span.contains(failing_span));
1799 let in_end = end.as_ref().is_some_and(|e| e.span.contains(failing_span));
1800
1801 if !in_start && !in_end {
1802 return;
1803 }
1804
1805 let start_snippet =
1806 start.as_ref().and_then(|e| self.r.tcx.sess.source_map().span_to_snippet(e.span).ok());
1807 let end_snippet =
1808 end.as_ref().and_then(|e| self.r.tcx.sess.source_map().span_to_snippet(e.span).ok());
1809
1810 let field = |name: &str, val: String| {
1811 if val == name { val } else { ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: {1}", name, val))
})format!("{name}: {val}") }
1812 };
1813
1814 let mut resolve_short_name = |short: Symbol, full: &str| -> String {
1815 let ident = Ident::with_dummy_span(short);
1816 let path = Segment::from_path(&Path::from_ident(ident));
1817
1818 match self.resolve_path(&path, Some(TypeNS), None, PathSource::Type) {
1819 PathResult::NonModule(..) => short.to_string(),
1820 _ => full.to_string(),
1821 }
1822 };
1823 let (struct_path, fields) = match (start_snippet, end_snippet, &end_kind.node) {
1825 (Some(start), Some(end), ast::RangeEnd::Excluded) => (
1826 resolve_short_name(sym::Range, "std::ops::Range"),
1827 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[field("start", start), field("end", end)]))vec![field("start", start), field("end", end)],
1828 ),
1829 (Some(start), Some(end), ast::RangeEnd::Included(_)) => (
1830 resolve_short_name(sym::RangeInclusive, "std::ops::RangeInclusive"),
1831 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[field("start", start), field("end", end)]))vec![field("start", start), field("end", end)],
1832 ),
1833 (Some(start), None, _) => (
1834 resolve_short_name(sym::RangeFrom, "std::ops::RangeFrom"),
1835 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[field("start", start)]))vec![field("start", start)],
1836 ),
1837 (None, Some(end), ast::RangeEnd::Excluded) => {
1838 (resolve_short_name(sym::RangeTo, "std::ops::RangeTo"), ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[field("end", end)]))vec![field("end", end)])
1839 }
1840 (None, Some(end), ast::RangeEnd::Included(_)) => (
1841 resolve_short_name(sym::RangeToInclusive, "std::ops::RangeToInclusive"),
1842 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[field("end", end)]))vec![field("end", end)],
1843 ),
1844 _ => return,
1845 };
1846
1847 err.span_suggestion_verbose(
1848 pat.span,
1849 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if you meant to destructure a range use a struct pattern"))
})format!("if you meant to destructure a range use a struct pattern"),
1850 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {{ {1} }}", struct_path,
fields.join(", ")))
})format!("{} {{ {} }}", struct_path, fields.join(", ")),
1851 Applicability::MaybeIncorrect,
1852 );
1853
1854 err.note(
1855 "range patterns match against the start and end of a range; \
1856 to bind the components, use a struct pattern",
1857 );
1858 }
1859
1860 fn suggest_swapping_misplaced_self_ty_and_trait(
1861 &mut self,
1862 err: &mut Diag<'_>,
1863 source: PathSource<'_, 'ast, 'ra>,
1864 res: Option<Res>,
1865 span: Span,
1866 ) {
1867 if let Some((trait_ref, self_ty)) =
1868 self.diag_metadata.currently_processing_impl_trait.clone()
1869 && let TyKind::Path(_, self_ty_path) = &self_ty.kind
1870 && let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1871 self.resolve_path(&Segment::from_path(self_ty_path), Some(TypeNS), None, source)
1872 && module.def_kind() == Some(DefKind::Trait)
1873 && trait_ref.path.span == span
1874 && let PathSource::Trait(_) = source
1875 && let Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)) = res
1876 && let Ok(self_ty_str) = self.r.tcx.sess.source_map().span_to_snippet(self_ty.span)
1877 && let Ok(trait_ref_str) =
1878 self.r.tcx.sess.source_map().span_to_snippet(trait_ref.path.span)
1879 {
1880 err.multipart_suggestion(
1881 "`impl` items mention the trait being implemented first and the type it is being implemented for second",
1882 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(trait_ref.path.span, self_ty_str), (self_ty.span, trait_ref_str)]))vec![(trait_ref.path.span, self_ty_str), (self_ty.span, trait_ref_str)],
1883 Applicability::MaybeIncorrect,
1884 );
1885 }
1886 }
1887
1888 fn explain_functions_in_pattern(
1889 &self,
1890 err: &mut Diag<'_>,
1891 res: Option<Res>,
1892 source: PathSource<'_, '_, '_>,
1893 ) {
1894 let PathSource::TupleStruct(_, _) = source else { return };
1895 let Some(Res::Def(DefKind::Fn, _)) = res else { return };
1896 err.primary_message("expected a pattern, found a function call");
1897 err.note("function calls are not allowed in patterns: <https://doc.rust-lang.org/book/ch19-00-patterns.html>");
1898 }
1899
1900 fn suggest_changing_type_to_const_param(
1901 &self,
1902 err: &mut Diag<'_>,
1903 res: Option<Res>,
1904 source: PathSource<'_, '_, '_>,
1905 path: &[Segment],
1906 following_seg: Option<&Segment>,
1907 span: Span,
1908 ) {
1909 if let PathSource::Expr(None) = source
1910 && let Some(Res::Def(DefKind::TyParam, _)) = res
1911 && following_seg.is_none()
1912 && let [segment] = path
1913 {
1914 let Some(item) = self.diag_metadata.current_item else { return };
1922 let Some(generics) = item.kind.generics() else { return };
1923 let Some(span) = generics.params.iter().find_map(|param| {
1924 if param.bounds.is_empty() && param.ident.name == segment.ident.name {
1926 Some(param.ident.span)
1927 } else {
1928 None
1929 }
1930 }) else {
1931 return;
1932 };
1933 err.subdiagnostic(diagnostics::UnexpectedResChangeTyParamToConstParamSugg {
1934 before: span.shrink_to_lo(),
1935 after: span.shrink_to_hi(),
1936 });
1937 return;
1938 }
1939 let PathSource::Trait(_) = source else { return };
1940
1941 let applicability = match res {
1943 Some(Res::PrimTy(PrimTy::Int(_) | PrimTy::Uint(_) | PrimTy::Bool | PrimTy::Char)) => {
1944 Applicability::MachineApplicable
1945 }
1946 Some(Res::Def(DefKind::Struct | DefKind::Enum, _))
1950 if self.r.features.adt_const_params() || self.r.features.min_adt_const_params() =>
1951 {
1952 Applicability::MaybeIncorrect
1953 }
1954 _ => return,
1955 };
1956
1957 let Some(item) = self.diag_metadata.current_item else { return };
1958 let Some(generics) = item.kind.generics() else { return };
1959
1960 let param = generics.params.iter().find_map(|param| {
1961 if let [bound] = &*param.bounds
1963 && let ast::GenericBound::Trait(tref) = bound
1964 && tref.modifiers == ast::TraitBoundModifiers::NONE
1965 && tref.span == span
1966 && param.ident.span.eq_ctxt(span)
1967 {
1968 Some(param.ident.span)
1969 } else {
1970 None
1971 }
1972 });
1973
1974 if let Some(param) = param {
1975 err.subdiagnostic(diagnostics::UnexpectedResChangeTyToConstParamSugg {
1976 span: param.shrink_to_lo(),
1977 applicability,
1978 });
1979 }
1980 }
1981
1982 fn suggest_pattern_match_with_let(
1983 &self,
1984 err: &mut Diag<'_>,
1985 source: PathSource<'_, '_, '_>,
1986 span: Span,
1987 ) -> bool {
1988 if let PathSource::Expr(_) = source
1989 && let Some(Expr { span: expr_span, kind: ExprKind::Assign(lhs, _, _), .. }) =
1990 self.diag_metadata.in_if_condition
1991 {
1992 if lhs.is_approximately_pattern() && lhs.span.contains(span) {
1996 err.span_suggestion_verbose(
1997 expr_span.shrink_to_lo(),
1998 "you might have meant to use pattern matching",
1999 "let ",
2000 Applicability::MaybeIncorrect,
2001 );
2002 return true;
2003 }
2004 }
2005 false
2006 }
2007
2008 fn get_single_associated_item(
2009 &mut self,
2010 path: &[Segment],
2011 source: &PathSource<'_, 'ast, 'ra>,
2012 filter_fn: &impl Fn(Res) -> bool,
2013 ) -> Option<TypoSuggestion> {
2014 if let crate::PathSource::TraitItem(_, _) = source {
2015 let mod_path = &path[..path.len() - 1];
2016 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
2017 self.resolve_path(mod_path, None, None, *source)
2018 {
2019 let targets: Vec<_> = self
2020 .r
2021 .resolutions(module)
2022 .iter()
2023 .filter_map(|(key, resolution)| {
2024 let resolution = resolution.borrow(self.r);
2025 resolution.best_decl().map(|binding| binding.res()).and_then(|res| {
2026 if filter_fn(res) {
2027 Some((key.ident.name, resolution.orig_ident_span, res))
2028 } else {
2029 None
2030 }
2031 })
2032 })
2033 .collect();
2034 if let &[(name, orig_ident_span, res)] = targets.as_slice() {
2035 return Some(TypoSuggestion::single_item(name, orig_ident_span, res));
2036 }
2037 }
2038 }
2039 None
2040 }
2041
2042 fn restrict_assoc_type_in_where_clause(&self, span: Span, err: &mut Diag<'_>) -> bool {
2044 let Some(ast::WherePredicate {
2046 kind:
2047 ast::WherePredicateKind::BoundPredicate(ast::WhereBoundPredicate {
2048 bounded_ty,
2049 bound_generic_params,
2050 bounds,
2051 }),
2052 span: where_span,
2053 ..
2054 }) = self.diag_metadata.current_where_predicate
2055 else {
2056 return false;
2057 };
2058 if !bound_generic_params.is_empty() {
2059 return false;
2060 }
2061
2062 let ast::TyKind::Path(Some(qself), path) = &bounded_ty.kind else { return false };
2064 let Some(partial_res) = self.r.partial_res_map.get(&bounded_ty.id) else { return false };
2066 if !#[allow(non_exhaustive_omitted_patterns)] match partial_res.full_res() {
Some(Res::Def(DefKind::AssocTy, _)) => true,
_ => false,
}matches!(partial_res.full_res(), Some(Res::Def(DefKind::AssocTy, _))) {
2067 return false;
2068 }
2069
2070 let peeled_ty = qself.ty.peel_refs();
2071 let ast::TyKind::Path(None, type_param_path) = &peeled_ty.kind else { return false };
2072 let Some(partial_res) = self.r.partial_res_map.get(&peeled_ty.id) else {
2074 return false;
2075 };
2076 if !#[allow(non_exhaustive_omitted_patterns)] match partial_res.full_res() {
Some(Res::Def(DefKind::TyParam, _)) => true,
_ => false,
}matches!(partial_res.full_res(), Some(Res::Def(DefKind::TyParam, _))) {
2077 return false;
2078 }
2079 let ([ast::PathSegment { args: None, .. }], [ast::GenericBound::Trait(poly_trait_ref)]) =
2080 (&type_param_path.segments[..], &bounds[..])
2081 else {
2082 return false;
2083 };
2084 let [ast::PathSegment { ident, args: None, id }] =
2085 &poly_trait_ref.trait_ref.path.segments[..]
2086 else {
2087 return false;
2088 };
2089 if poly_trait_ref.modifiers != ast::TraitBoundModifiers::NONE {
2090 return false;
2091 }
2092 if ident.span == span {
2093 let Some(partial_res) = self.r.partial_res_map.get(&id) else {
2094 return false;
2095 };
2096 if !#[allow(non_exhaustive_omitted_patterns)] match partial_res.full_res() {
Some(Res::Def(..)) => true,
_ => false,
}matches!(partial_res.full_res(), Some(Res::Def(..))) {
2097 return false;
2098 }
2099
2100 let Some(new_where_bound_predicate) =
2101 mk_where_bound_predicate(path, poly_trait_ref, &qself.ty)
2102 else {
2103 return false;
2104 };
2105 err.span_suggestion_verbose(
2106 *where_span,
2107 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("constrain the associated type to `{0}`",
ident))
})format!("constrain the associated type to `{ident}`"),
2108 where_bound_predicate_to_string(&new_where_bound_predicate),
2109 Applicability::MaybeIncorrect,
2110 );
2111 }
2112 true
2113 }
2114
2115 fn call_has_self_arg(&self, source: PathSource<'_, '_, '_>) -> Option<(Span, Option<Span>)> {
2118 let mut has_self_arg = None;
2119 if let PathSource::Expr(Some(parent)) = source
2120 && let ExprKind::Call(_, args) = &parent.kind
2121 && !args.is_empty()
2122 {
2123 let mut expr_kind = &args[0].kind;
2124 loop {
2125 match expr_kind {
2126 ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
2127 if arg_name.segments[0].ident.name == kw::SelfLower {
2128 let call_span = parent.span;
2129 let tail_args_span = if args.len() > 1 {
2130 Some(Span::new(
2131 args[1].span.lo(),
2132 args.last().unwrap().span.hi(),
2133 call_span.ctxt(),
2134 None,
2135 ))
2136 } else {
2137 None
2138 };
2139 has_self_arg = Some((call_span, tail_args_span));
2140 }
2141 break;
2142 }
2143 ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
2144 _ => break,
2145 }
2146 }
2147 }
2148 has_self_arg
2149 }
2150
2151 fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
2152 let sm = self.r.tcx.sess.source_map();
2157 if let Some(open_brace_span) = sm.span_followed_by(span, "{") {
2158 let close_brace_span =
2161 sm.span_to_next_source(open_brace_span).ok().and_then(|next_source| {
2162 let mut depth: u32 = 1;
2164 let offset = next_source.char_indices().find_map(|(i, c)| {
2165 match c {
2166 '{' => depth += 1,
2167 '}' if depth == 1 => return Some(i),
2168 '}' => depth -= 1,
2169 _ => {}
2170 }
2171 None
2172 })?;
2173 let start = open_brace_span.hi() + rustc_span::BytePos(offset as u32);
2174 Some(open_brace_span.with_lo(start).with_hi(start + rustc_span::BytePos(1)))
2175 });
2176 let closing_brace = close_brace_span.map(|sp| span.to(sp));
2177 (true, closing_brace)
2178 } else {
2179 (false, None)
2180 }
2181 }
2182
2183 fn update_err_for_private_tuple_struct_fields(
2184 &self,
2185 err: &mut Diag<'_>,
2186 source: &PathSource<'_, '_, '_>,
2187 def_id: DefId,
2188 ) -> Option<Vec<Span>> {
2189 match source {
2190 PathSource::TupleStruct(_, pattern_spans) => {
2192 err.primary_message(
2193 "cannot match against a tuple struct which contains private fields",
2194 );
2195
2196 Some(Vec::from(*pattern_spans))
2198 }
2199 PathSource::Expr(Some(Expr {
2201 kind: ExprKind::Call(path, args),
2202 span: call_span,
2203 ..
2204 })) => {
2205 err.primary_message(
2206 "cannot initialize a tuple struct which contains private fields",
2207 );
2208 self.suggest_alternative_construction_methods(
2209 def_id,
2210 err,
2211 path.span,
2212 *call_span,
2213 &args[..],
2214 );
2215
2216 self.r
2217 .field_idents(def_id)
2218 .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
2219 }
2220 _ => None,
2221 }
2222 }
2223
2224 fn smart_resolve_context_dependent_help(
2228 &mut self,
2229 err: &mut Diag<'_>,
2230 span: Span,
2231 source: PathSource<'_, '_, '_>,
2232 path: &[Segment],
2233 res: Res,
2234 path_str: &str,
2235 fallback_label: &str,
2236 ) -> bool {
2237 let ns = source.namespace();
2238 let is_expected = &|res| source.is_expected(res);
2239
2240 let path_sep = |this: &Self, err: &mut Diag<'_>, expr: &Expr, kind: DefKind| {
2241 const MESSAGE: &str = "use the path separator to refer to an item";
2242
2243 let (lhs_span, rhs_span) = match &expr.kind {
2244 ExprKind::Field(base, ident) => (base.span, ident.span),
2245 ExprKind::MethodCall(MethodCall { receiver, span, .. }) => (receiver.span, *span),
2246 _ => return false,
2247 };
2248
2249 if lhs_span.eq_ctxt(rhs_span) {
2250 err.span_suggestion_verbose(
2251 lhs_span.between(rhs_span),
2252 MESSAGE,
2253 "::",
2254 Applicability::MaybeIncorrect,
2255 );
2256 true
2257 } else if #[allow(non_exhaustive_omitted_patterns)] match kind {
DefKind::Struct | DefKind::TyAlias => true,
_ => false,
}matches!(kind, DefKind::Struct | DefKind::TyAlias)
2258 && let Some(lhs_source_span) = lhs_span.find_ancestor_inside(expr.span)
2259 && let Ok(snippet) = this.r.tcx.sess.source_map().span_to_snippet(lhs_source_span)
2260 {
2261 err.span_suggestion_verbose(
2265 lhs_source_span.until(rhs_span),
2266 MESSAGE,
2267 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>::", snippet))
})format!("<{snippet}>::"),
2268 Applicability::MaybeIncorrect,
2269 );
2270 true
2271 } else {
2272 false
2278 }
2279 };
2280
2281 let find_span = |source: &PathSource<'_, '_, '_>, err: &mut Diag<'_>| {
2282 match source {
2283 PathSource::Expr(Some(Expr { span, kind: ExprKind::Call(_, _), .. }))
2284 | PathSource::TupleStruct(span, _) => {
2285 err.span(*span);
2288 *span
2289 }
2290 _ => span,
2291 }
2292 };
2293
2294 let bad_struct_syntax_suggestion = |this: &Self, err: &mut Diag<'_>, def_id: DefId| {
2295 let (followed_by_brace, closing_brace) = this.followed_by_brace(span);
2296
2297 match source {
2298 PathSource::Expr(Some(
2299 parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
2300 )) if path_sep(this, err, parent, DefKind::Struct) => {}
2301 PathSource::Expr(
2302 None
2303 | Some(Expr {
2304 kind:
2305 ExprKind::Path(..)
2306 | ExprKind::Binary(..)
2307 | ExprKind::Unary(..)
2308 | ExprKind::If(..)
2309 | ExprKind::While(..)
2310 | ExprKind::ForLoop { .. }
2311 | ExprKind::Match(..),
2312 ..
2313 }),
2314 ) if followed_by_brace => {
2315 if let Some(sp) = closing_brace {
2316 err.span_label(span, fallback_label.to_string());
2317 err.multipart_suggestion(
2318 "surround the struct literal with parentheses",
2319 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(sp.shrink_to_lo(), "(".to_string()),
(sp.shrink_to_hi(), ")".to_string())]))vec![
2320 (sp.shrink_to_lo(), "(".to_string()),
2321 (sp.shrink_to_hi(), ")".to_string()),
2322 ],
2323 Applicability::MaybeIncorrect,
2324 );
2325 } else {
2326 err.span_label(
2327 span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might want to surround a struct literal with parentheses: `({0} {{ /* fields */ }})`?",
path_str))
})format!(
2329 "you might want to surround a struct literal with parentheses: \
2330 `({path_str} {{ /* fields */ }})`?"
2331 ),
2332 );
2333 }
2334 }
2335 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
2336 let span = find_span(&source, err);
2337 err.span_label(this.r.def_span(def_id), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` defined here", path_str))
})format!("`{path_str}` defined here"));
2338
2339 let (tail, descr, applicability, old_fields) = match source {
2340 PathSource::Pat => ("", "pattern", Applicability::MachineApplicable, None),
2341 PathSource::TupleStruct(_, args) => (
2342 "",
2343 "pattern",
2344 Applicability::MachineApplicable,
2345 Some(
2346 args.iter()
2347 .map(|a| this.r.tcx.sess.source_map().span_to_snippet(*a).ok())
2348 .collect::<Vec<Option<String>>>(),
2349 ),
2350 ),
2351 _ => (": val", "literal", Applicability::HasPlaceholders, None),
2352 };
2353
2354 let has_private_fields = match def_id.as_local() {
2356 Some(def_id) => this.r.struct_ctors.get(&def_id).is_some_and(|ctor| {
2357 ctor.has_private_fields(this.parent_scope.module, this.r)
2358 }),
2359 None => this.r.tcx.associated_item_def_ids(def_id).iter().any(|field_id| {
2360 let vis = this.r.tcx.visibility(*field_id);
2361 !this.r.is_accessible_from(vis, this.parent_scope.module)
2362 }),
2363 };
2364 if !has_private_fields {
2365 let fields = this.r.field_idents(def_id);
2368 let has_fields = fields.as_ref().is_some_and(|f| !f.is_empty());
2369
2370 if let PathSource::Expr(Some(Expr {
2371 kind: ExprKind::Call(path, args),
2372 span,
2373 ..
2374 })) = source
2375 && !args.is_empty()
2376 && let Some(fields) = &fields
2377 && args.len() == fields.len()
2378 {
2380 let path_span = path.span;
2381 let mut parts = Vec::new();
2382
2383 parts.push((
2385 path_span.shrink_to_hi().until(args[0].span),
2386 "{".to_owned(),
2387 ));
2388
2389 for (field, arg) in fields.iter().zip(args.iter()) {
2390 parts.push((arg.span.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", field))
})format!("{}: ", field)));
2392 }
2393
2394 parts.push((
2396 args.last().unwrap().span.shrink_to_hi().until(span.shrink_to_hi()),
2397 "}".to_owned(),
2398 ));
2399
2400 err.multipart_suggestion(
2401 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use struct {0} syntax instead of calling",
descr))
})format!("use struct {descr} syntax instead of calling"),
2402 parts,
2403 applicability,
2404 );
2405 } else {
2406 let (fields, applicability) = match fields {
2407 Some(fields) => {
2408 let fields = if let Some(old_fields) = old_fields {
2409 fields
2410 .iter()
2411 .enumerate()
2412 .map(|(idx, new)| (new, old_fields.get(idx)))
2413 .map(|(new, old)| {
2414 if let Some(Some(old)) = old
2415 && new.as_str() != old
2416 {
2417 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: {1}", new, old))
})format!("{new}: {old}")
2418 } else {
2419 new.to_string()
2420 }
2421 })
2422 .collect::<Vec<String>>()
2423 } else {
2424 fields
2425 .iter()
2426 .map(|f| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", f, tail))
})format!("{f}{tail}"))
2427 .collect::<Vec<String>>()
2428 };
2429
2430 (fields.join(", "), applicability)
2431 }
2432 None => {
2433 ("/* fields */".to_string(), Applicability::HasPlaceholders)
2434 }
2435 };
2436 let pad = if has_fields { " " } else { "" };
2437 let expression = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {{{1}{2}{1}}}", path_str, pad,
fields))
})format!("{path_str} {{{pad}{fields}{pad}}}");
2438 if !this.suggest_named_format_argument(
2439 err,
2440 source,
2441 path.last().unwrap().ident,
2442 &expression,
2443 applicability,
2444 ) {
2445 err.span_suggestion(
2446 span,
2447 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use struct {0} syntax instead",
descr))
})format!("use struct {descr} syntax instead"),
2448 expression,
2449 applicability,
2450 );
2451 }
2452 }
2453 }
2454 if let PathSource::Expr(Some(Expr {
2455 kind: ExprKind::Call(path, args),
2456 span: call_span,
2457 ..
2458 })) = source
2459 {
2460 this.suggest_alternative_construction_methods(
2461 def_id,
2462 err,
2463 path.span,
2464 *call_span,
2465 &args[..],
2466 );
2467 }
2468 }
2469 _ => {
2470 err.span_label(span, fallback_label.to_string());
2471 }
2472 }
2473 };
2474
2475 match (res, source) {
2476 (
2477 Res::Def(DefKind::Macro(kinds), def_id),
2478 PathSource::Expr(Some(Expr {
2479 kind: ExprKind::Index(..) | ExprKind::Call(..), ..
2480 }))
2481 | PathSource::Struct(_),
2482 ) if kinds.contains(MacroKinds::BANG) => {
2483 let suggestable = def_id.is_local()
2485 || self.r.tcx.lookup_stability(def_id).is_none_or(|s| s.is_stable());
2486
2487 err.span_label(span, fallback_label.to_string());
2488
2489 if path
2491 .last()
2492 .is_some_and(|segment| !segment.has_generic_args && !segment.has_lifetime_args)
2493 && suggestable
2494 {
2495 err.span_suggestion_verbose(
2496 span.shrink_to_hi(),
2497 "use `!` to invoke the macro",
2498 "!",
2499 Applicability::MaybeIncorrect,
2500 );
2501 }
2502
2503 if path_str == "try" && span.is_rust_2015() {
2504 err.note("if you want the `try` keyword, you need Rust 2018 or later");
2505 }
2506 }
2507 (Res::Def(DefKind::Macro(kinds), _), _) if kinds.contains(MacroKinds::BANG) => {
2508 err.span_label(span, fallback_label.to_string());
2509 }
2510 (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
2511 err.span_label(span, "type aliases cannot be used as traits");
2512 if self.r.tcx.sess.is_nightly_build() {
2513 let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
2514 `type` alias";
2515 let span = self.r.def_span(def_id);
2516 if let Ok(snip) = self.r.tcx.sess.source_map().span_to_snippet(span) {
2517 let snip = snip.replacen("type", "trait", 1);
2520 err.span_suggestion(span, msg, snip, Applicability::MaybeIncorrect);
2521 } else {
2522 err.span_help(span, msg);
2523 }
2524 }
2525 }
2526 (
2527 Res::Def(kind @ (DefKind::Mod | DefKind::Trait | DefKind::TyAlias), _),
2528 PathSource::Expr(Some(parent)),
2529 ) if path_sep(self, err, parent, kind) => {
2530 return true;
2531 }
2532 (
2533 Res::Def(DefKind::Enum, def_id),
2534 PathSource::TupleStruct(..) | PathSource::Expr(..),
2535 ) => {
2536 self.suggest_using_enum_variant(err, source, def_id, span);
2537 }
2538 (Res::Def(DefKind::Struct, def_id), source) if ns == ValueNS => {
2539 if let PathSource::Expr(Some(parent)) = source
2540 && let ExprKind::Field(..) | ExprKind::MethodCall(..) = parent.kind
2541 {
2542 bad_struct_syntax_suggestion(self, err, def_id);
2543 return true;
2544 }
2545 let Some(ctor) = self.r.struct_ctor(def_id) else {
2546 bad_struct_syntax_suggestion(self, err, def_id);
2547 return true;
2548 };
2549
2550 let is_accessible = self.r.is_accessible_from(ctor.vis, self.parent_scope.module);
2553 if is_accessible
2554 && let mod_path = &path[..path.len() - 1]
2555 && let PathResult::Module(ModuleOrUniformRoot::Module(import_mod)) =
2556 self.resolve_path(mod_path, Some(TypeNS), None, PathSource::Module)
2557 && ctor.has_private_fields(import_mod, self.r)
2558 && let Ok(import_decl) = self.r.cm().maybe_resolve_ident_in_module(
2559 ModuleOrUniformRoot::Module(import_mod),
2560 path.last().unwrap().ident,
2561 TypeNS,
2562 &self.parent_scope,
2563 None,
2564 )
2565 {
2566 err.span_note(
2567 import_decl.span,
2568 "the type is accessed through this re-export, but the type's constructor \
2569 is not visible in this import's scope due to private fields",
2570 );
2571 if !ctor.has_private_fields(self.parent_scope.module, self.r) {
2572 err.span_suggestion_verbose(
2573 span,
2574 "the type can be constructed directly, because its fields are \
2575 available from the current scope",
2576 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("crate{0}",
self.r.tcx.def_path(def_id).to_string_no_crate_verbose()))
})format!(
2580 "crate{}", self.r.tcx.def_path(def_id).to_string_no_crate_verbose(),
2582 ),
2583 Applicability::MachineApplicable,
2584 );
2585 }
2586 self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
2587 }
2588 if !is_expected(ctor.res) || is_accessible {
2589 return true;
2590 }
2591
2592 let field_spans =
2593 self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
2594
2595 if let Some(spans) = field_spans
2596 .filter(|spans| spans.len() > 0 && ctor.field_visibilities.len() == spans.len())
2597 {
2598 let non_visible_spans: Vec<Span> = iter::zip(&ctor.field_visibilities, &spans)
2599 .filter(|(vis, _)| {
2600 !self.r.is_accessible_from(**vis, self.parent_scope.module)
2601 })
2602 .map(|(_, span)| *span)
2603 .collect();
2604
2605 if non_visible_spans.len() > 0 {
2606 if let Some(fields) = self.r.field_visibility_spans.get(&def_id) {
2607 err.multipart_suggestion(
2608 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider making the field{0} publicly accessible",
if fields.len() == 1 { "" } else { "s" }))
})format!(
2609 "consider making the field{} publicly accessible",
2610 pluralize!(fields.len())
2611 ),
2612 fields.iter().map(|span| (*span, "pub ".to_string())).collect(),
2613 Applicability::MaybeIncorrect,
2614 );
2615 }
2616
2617 let mut m: MultiSpan = non_visible_spans.clone().into();
2618 non_visible_spans
2619 .into_iter()
2620 .for_each(|s| m.push_span_label(s, "private field"));
2621 err.span_note(m, "constructor is not visible here due to private fields");
2622 }
2623
2624 return true;
2625 }
2626
2627 err.span_label(span, "constructor is not visible here due to private fields");
2628 }
2629 (Res::Def(DefKind::Union | DefKind::Variant, def_id), _) if ns == ValueNS => {
2630 bad_struct_syntax_suggestion(self, err, def_id);
2631 }
2632 (Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id), _) if ns == ValueNS => {
2633 match source {
2634 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
2635 let span = find_span(&source, err);
2636 err.span_label(
2637 self.r.def_span(def_id),
2638 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` defined here", path_str))
})format!("`{path_str}` defined here"),
2639 );
2640 err.span_suggestion(
2641 span,
2642 "use this syntax instead",
2643 path_str,
2644 Applicability::MaybeIncorrect,
2645 );
2646 }
2647 _ => return false,
2648 }
2649 }
2650 (Res::Def(DefKind::Ctor(_, CtorKind::Fn), ctor_def_id), _) if ns == ValueNS => {
2651 let def_id = self.r.tcx.parent(ctor_def_id);
2652 err.span_label(self.r.def_span(def_id), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` defined here", path_str))
})format!("`{path_str}` defined here"));
2653 let fields = self.r.field_idents(def_id).map_or_else(
2654 || "/* fields */".to_string(),
2655 |field_ids| ::alloc::vec::from_elem("_", field_ids.len())vec!["_"; field_ids.len()].join(", "),
2656 );
2657 err.span_suggestion(
2658 span,
2659 "use the tuple variant pattern syntax instead",
2660 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}({1})", path_str, fields))
})format!("{path_str}({fields})"),
2661 Applicability::HasPlaceholders,
2662 );
2663 }
2664 (Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }, _) if ns == ValueNS => {
2665 err.span_label(span, fallback_label.to_string());
2666 err.note("can't use `Self` as a constructor, you must use the implemented struct");
2667 }
2668 (
2669 Res::Def(DefKind::TyAlias | DefKind::AssocTy, _),
2670 PathSource::TraitItem(ValueNS, PathSource::TupleStruct(whole, args)),
2671 ) => {
2672 err.note("can't use a type alias as tuple pattern");
2673
2674 let mut suggestion = Vec::new();
2675
2676 if let &&[first, ..] = args
2677 && let &&[.., last] = args
2678 {
2679 suggestion.extend([
2680 (span.between(first), " { 0: ".to_owned()),
2686 (last.between(whole.shrink_to_hi()), " }".to_owned()),
2687 ]);
2688
2689 suggestion.extend(
2690 args.iter()
2691 .enumerate()
2692 .skip(1) .map(|(index, &arg)| (arg.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", index))
})format!("{index}: "))),
2694 )
2695 } else {
2696 suggestion.push((span.between(whole.shrink_to_hi()), " {}".to_owned()));
2697 }
2698
2699 err.multipart_suggestion(
2700 "use struct pattern instead",
2701 suggestion,
2702 Applicability::MachineApplicable,
2703 );
2704 }
2705 (
2706 Res::Def(DefKind::TyAlias | DefKind::AssocTy, _),
2707 PathSource::TraitItem(
2708 ValueNS,
2709 PathSource::Expr(Some(ast::Expr {
2710 span: whole,
2711 kind: ast::ExprKind::Call(_, args),
2712 ..
2713 })),
2714 ),
2715 ) => {
2716 err.note("can't use a type alias as a constructor");
2717
2718 let mut suggestion = Vec::new();
2719
2720 if let [first, ..] = &**args
2721 && let [.., last] = &**args
2722 {
2723 suggestion.extend([
2724 (span.between(first.span), " { 0: ".to_owned()),
2730 (last.span.between(whole.shrink_to_hi()), " }".to_owned()),
2731 ]);
2732
2733 suggestion.extend(
2734 args.iter()
2735 .enumerate()
2736 .skip(1) .map(|(index, arg)| (arg.span.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", index))
})format!("{index}: "))),
2738 )
2739 } else {
2740 suggestion.push((span.between(whole.shrink_to_hi()), " {}".to_owned()));
2741 }
2742
2743 err.multipart_suggestion(
2744 "use struct expression instead",
2745 suggestion,
2746 Applicability::MachineApplicable,
2747 );
2748 }
2749 _ => return false,
2750 }
2751 true
2752 }
2753
2754 fn suggest_alternative_construction_methods(
2755 &self,
2756 def_id: DefId,
2757 err: &mut Diag<'_>,
2758 path_span: Span,
2759 call_span: Span,
2760 args: &[Box<Expr>],
2761 ) {
2762 if def_id.is_local() {
2763 return;
2765 }
2766 let mut items = self
2769 .r
2770 .tcx
2771 .inherent_impls(def_id)
2772 .iter()
2773 .flat_map(|&i| self.r.tcx.associated_items(i).in_definition_order())
2774 .filter(|item| item.is_fn() && !item.is_method())
2776 .filter_map(|item| {
2777 let fn_sig = self.r.tcx.fn_sig(item.def_id).skip_binder();
2779 let ret_ty = fn_sig.output().skip_binder();
2781 let ty::Adt(def, _args) = ret_ty.kind() else {
2782 return None;
2783 };
2784 let input_len = fn_sig.inputs().skip_binder().len();
2785 if def.did() != def_id {
2786 return None;
2787 }
2788 let name = item.name();
2789 let order = !name.as_str().starts_with("new");
2790 Some((order, name, input_len))
2791 })
2792 .collect::<Vec<_>>();
2793 items.sort_by_key(|(order, _, _)| *order);
2794 let suggestion = |name, args| {
2795 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("::{1}({0})",
std::iter::repeat_n("_", args).collect::<Vec<_>>().join(", "),
name))
})format!("::{name}({})", std::iter::repeat_n("_", args).collect::<Vec<_>>().join(", "))
2796 };
2797 match &items[..] {
2798 [] => {}
2799 [(_, name, len)] if *len == args.len() => {
2800 err.span_suggestion_verbose(
2801 path_span.shrink_to_hi(),
2802 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might have meant to use the `{0}` associated function",
name))
})format!("you might have meant to use the `{name}` associated function",),
2803 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("::{0}", name))
})format!("::{name}"),
2804 Applicability::MaybeIncorrect,
2805 );
2806 }
2807 [(_, name, len)] => {
2808 err.span_suggestion_verbose(
2809 path_span.shrink_to_hi().with_hi(call_span.hi()),
2810 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might have meant to use the `{0}` associated function",
name))
})format!("you might have meant to use the `{name}` associated function",),
2811 suggestion(name, *len),
2812 Applicability::MaybeIncorrect,
2813 );
2814 }
2815 _ => {
2816 err.span_suggestions_with_style(
2817 path_span.shrink_to_hi().with_hi(call_span.hi()),
2818 "you might have meant to use an associated function to build this type",
2819 items.iter().map(|(_, name, len)| suggestion(name, *len)),
2820 Applicability::MaybeIncorrect,
2821 SuggestionStyle::ShowAlways,
2822 );
2823 }
2824 }
2825 let default_trait = self
2833 .r
2834 .lookup_import_candidates(
2835 Ident::with_dummy_span(sym::Default),
2836 Namespace::TypeNS,
2837 &self.parent_scope,
2838 &|res: Res| #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Trait, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Trait, _)),
2839 )
2840 .iter()
2841 .filter_map(|candidate| candidate.did)
2842 .find(|did| {
{
'done:
{
for i in
::rustc_attr_ir::HasAttrs::get_attrs(*did, &self.r.tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcDiagnosticItem(sym::Default))
=> {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(self.r.tcx, *did, RustcDiagnosticItem(sym::Default)));
2843 let Some(default_trait) = default_trait else {
2844 return;
2845 };
2846 if self
2847 .r
2848 .extern_crate_map
2849 .items()
2850 .flat_map(|(_, crate_)| {
2852 UnordItems::new(
2853 self.r.tcx.implementations_of_trait((*crate_, default_trait)).into_iter(),
2854 )
2855 })
2856 .filter_map(|(_, simplified_self_ty)| *simplified_self_ty)
2857 .filter_map(|simplified_self_ty| match simplified_self_ty {
2858 SimplifiedType::Adt(did) => Some(did),
2859 _ => None,
2860 })
2861 .any(|did| did == def_id)
2862 {
2863 err.multipart_suggestion(
2864 "consider using the `Default` trait",
2865 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(path_span.shrink_to_lo(), "<".to_string()),
(path_span.shrink_to_hi().with_hi(call_span.hi()),
" as std::default::Default>::default()".to_string())]))vec![
2866 (path_span.shrink_to_lo(), "<".to_string()),
2867 (
2868 path_span.shrink_to_hi().with_hi(call_span.hi()),
2869 " as std::default::Default>::default()".to_string(),
2870 ),
2871 ],
2872 Applicability::MaybeIncorrect,
2873 );
2874 }
2875 }
2876
2877 pub(crate) fn find_similarly_named_assoc_item(
2880 &mut self,
2881 ident: Symbol,
2882 kind: &AssocItemKind,
2883 ) -> Option<Symbol> {
2884 let (module, _) = self.current_trait_ref.as_ref()?;
2885 if ident == kw::Underscore {
2886 return None;
2888 }
2889
2890 let targets = self
2891 .r
2892 .resolutions(*module)
2893 .iter()
2894 .filter_map(|(key, res)| {
2895 res.borrow(self.r).best_decl().map(|binding| (key, binding.res()))
2896 })
2897 .filter(|(_, res)| match (kind, res) {
2898 (AssocItemKind::Const(..), Res::Def(DefKind::AssocConst, _)) => true,
2899 (AssocItemKind::Fn(_), Res::Def(DefKind::AssocFn, _)) => true,
2900 (AssocItemKind::Type(..), Res::Def(DefKind::AssocTy, _)) => true,
2901 (AssocItemKind::Delegation(_), Res::Def(DefKind::AssocFn, _)) => true,
2902 _ => false,
2903 })
2904 .map(|(key, _)| key.ident.name)
2905 .collect::<Vec<_>>();
2906
2907 find_best_match_for_name(&targets, ident, None)
2908 }
2909
2910 fn lookup_assoc_candidate<FilterFn>(
2912 &self,
2913 ident: Ident,
2914 ns: Namespace,
2915 filter_fn: FilterFn,
2916 called: bool,
2917 ) -> Option<(AssocSuggestion, Span)>
2918 where
2919 FilterFn: Fn(Res) -> bool,
2920 {
2921 fn extract_node_id(t: &Ty) -> Option<NodeId> {
2922 match t.kind {
2923 TyKind::Path(None, _) => Some(t.id),
2924 TyKind::Ref(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
2925 _ => None,
2929 }
2930 }
2931 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
2933 if let Some(node_id) = self.diag_metadata.current_self_type.and_then(extract_node_id)
2934 && let Some(resolution) = self.r.partial_res_map.get(&node_id)
2935 && let Some(Res::Def(DefKind::Struct | DefKind::Union, did)) = resolution.full_res()
2936 && let Some(fields) = self.r.field_idents(did)
2937 && let Some(field) = fields.iter().find(|id| ident.name == id.name)
2938 {
2939 return Some((AssocSuggestion::Field, field.span));
2941 }
2942 }
2943
2944 if let Some(items) = self.diag_metadata.current_trait_assoc_items {
2945 for assoc_item in items {
2946 if let Some(assoc_ident) = assoc_item.kind.ident()
2947 && assoc_ident == ident
2948 {
2949 let candidate = match &assoc_item.kind {
2950 ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
2951 ast::AssocItemKind::Fn(ast::Fn { sig, .. }) if sig.decl.has_self() => {
2952 AssocSuggestion::MethodWithSelf { called }
2953 }
2954 ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn { called },
2955 ast::AssocItemKind::Type(..) => AssocSuggestion::AssocType,
2956 ast::AssocItemKind::Delegation(..)
2957 if self
2958 .r
2959 .owners
2960 .get(&assoc_item.id)
2961 .and_then(|o| self.r.delegation_fn_sigs.get(&o.def_id))
2962 .is_some_and(|sig| sig.has_self) =>
2963 {
2964 AssocSuggestion::MethodWithSelf { called }
2965 }
2966 ast::AssocItemKind::Delegation(..) => AssocSuggestion::AssocFn { called },
2967 ast::AssocItemKind::MacCall(_) | ast::AssocItemKind::DelegationMac(..) => {
2968 continue;
2969 }
2970 };
2971 return Some((candidate, assoc_ident.span));
2972 }
2973 }
2974 }
2975
2976 if let Some((module, _)) = self.current_trait_ref
2978 && let Ok(binding) = self.r.cm().maybe_resolve_ident_in_module(
2979 ModuleOrUniformRoot::Module(module),
2980 ident,
2981 ns,
2982 &self.parent_scope,
2983 None,
2984 )
2985 {
2986 let res = binding.res();
2987 if filter_fn(res) {
2988 match res {
2989 Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) => {
2990 let has_self = match def_id.as_local() {
2991 Some(def_id) => self
2992 .r
2993 .delegation_fn_sigs
2994 .get(&def_id)
2995 .is_some_and(|sig| sig.has_self),
2996 None => {
2997 self.r.tcx.fn_arg_idents(def_id).first().is_some_and(|&ident| {
2998 #[allow(non_exhaustive_omitted_patterns)] match ident {
Some(Ident { name: kw::SelfLower, .. }) => true,
_ => false,
}matches!(ident, Some(Ident { name: kw::SelfLower, .. }))
2999 })
3000 }
3001 };
3002 if has_self {
3003 return Some((
3004 AssocSuggestion::MethodWithSelf { called },
3005 binding.span,
3006 ));
3007 } else {
3008 return Some((AssocSuggestion::AssocFn { called }, binding.span));
3009 }
3010 }
3011 Res::Def(DefKind::AssocConst, _) => {
3012 return Some((AssocSuggestion::AssocConst, binding.span));
3013 }
3014 Res::Def(DefKind::AssocTy, _) => {
3015 return Some((AssocSuggestion::AssocType, binding.span));
3016 }
3017 _ => {}
3018 }
3019 }
3020 }
3021
3022 None
3023 }
3024
3025 fn lookup_typo_candidate(
3026 &mut self,
3027 path: &[Segment],
3028 following_seg: Option<&Segment>,
3029 ns: Namespace,
3030 filter_fn: &impl Fn(Res) -> bool,
3031 ) -> TypoCandidate {
3032 let mut names = Vec::new();
3033 if let [segment] = path {
3034 let mut ctxt = segment.ident.span.ctxt();
3035
3036 for rib in self.ribs[ns].iter().rev() {
3039 let rib_ctxt = if rib.kind.contains_params() {
3040 ctxt.normalize_to_macros_2_0()
3041 } else {
3042 ctxt.normalize_to_macro_rules()
3043 };
3044
3045 for (ident, &res) in &rib.bindings {
3047 if filter_fn(res) && ident.span.ctxt() == rib_ctxt {
3048 names.push(TypoSuggestion::new(ident.name, ident.span, res));
3049 }
3050 }
3051
3052 if let RibKind::Block(Some(module)) = rib.kind {
3053 self.r.add_module_candidates(
3054 module.to_module(),
3055 &mut names,
3056 &filter_fn,
3057 Some(ctxt),
3058 );
3059 } else if let RibKind::Module(module) = rib.kind {
3060 let parent_scope =
3062 &ParentScope { module: module.to_module(), ..self.parent_scope };
3063 self.r.add_scope_set_candidates(
3064 &mut names,
3065 ScopeSet::All(ns),
3066 parent_scope,
3067 segment.ident.span.with_ctxt(ctxt),
3068 filter_fn,
3069 );
3070 break;
3071 }
3072
3073 if let RibKind::MacroDefinition(def) = rib.kind
3074 && def == self.r.macro_def(ctxt)
3075 {
3076 ctxt.remove_mark();
3079 }
3080 }
3081 } else {
3082 let mod_path = &path[..path.len() - 1];
3084 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
3085 self.resolve_path(mod_path, Some(TypeNS), None, PathSource::Type)
3086 {
3087 self.r.add_module_candidates(module, &mut names, &filter_fn, None);
3088 }
3089 }
3090
3091 if let Some(following_seg) = following_seg {
3093 names.retain(|suggestion| match suggestion.res {
3094 Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _) => {
3095 suggestion.candidate != following_seg.ident.name
3097 }
3098 Res::Def(DefKind::Mod, def_id) => {
3099 let module = self.r.expect_module(def_id);
3100 self.r
3101 .resolutions(module)
3102 .iter()
3103 .any(|(key, _)| key.ident.name == following_seg.ident.name)
3104 }
3105 _ => true,
3106 });
3107 }
3108 let name = path[path.len() - 1].ident.name;
3109 names.sort_by(|a, b| a.candidate.as_str().cmp(b.candidate.as_str()));
3111
3112 match find_best_match_for_name(
3113 &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
3114 name,
3115 None,
3116 ) {
3117 Some(found) => {
3118 let Some(sugg) = names.into_iter().find(|suggestion| suggestion.candidate == found)
3119 else {
3120 return TypoCandidate::None;
3121 };
3122 if found == name {
3123 TypoCandidate::Shadowed(sugg.res, sugg.span)
3124 } else {
3125 TypoCandidate::Typo(sugg)
3126 }
3127 }
3128 _ => TypoCandidate::None,
3129 }
3130 }
3131
3132 fn likely_rust_type(path: &[Segment]) -> Option<Symbol> {
3135 let name = path[path.len() - 1].ident.as_str();
3136 Some(match name {
3138 "byte" => sym::u8, "short" => sym::i16,
3140 "Bool" => sym::bool,
3141 "Boolean" => sym::bool,
3142 "boolean" => sym::bool,
3143 "int" => sym::i32,
3144 "long" => sym::i64,
3145 "float" => sym::f32,
3146 "double" => sym::f64,
3147 _ => return None,
3148 })
3149 }
3150
3151 fn let_binding_suggestion(&self, err: &mut Diag<'_>, ident_span: Span) -> bool {
3154 if ident_span.from_expansion() {
3155 return false;
3156 }
3157
3158 if let Some(Expr { kind: ExprKind::Assign(lhs, ..), .. }) = self.diag_metadata.in_assignment
3160 && let ast::ExprKind::Path(None, ref path) = lhs.kind
3161 && self.r.tcx.sess.source_map().is_line_before_span_empty(ident_span)
3162 {
3163 let (span, text) = match path.segments.first() {
3164 Some(seg) if let Some(name) = seg.ident.as_str().strip_prefix("let") => {
3165 let name = name.trim_prefix('_');
3167 (ident_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("let {0}", name))
})format!("let {name}"))
3168 }
3169 _ => (ident_span.shrink_to_lo(), "let ".to_string()),
3170 };
3171
3172 err.span_suggestion_verbose(
3173 span,
3174 "you might have meant to introduce a new binding",
3175 text,
3176 Applicability::MaybeIncorrect,
3177 );
3178 return true;
3179 }
3180
3181 if err.code == Some(E0423)
3184 && let Some((let_span, None, Some(val_span))) = self.diag_metadata.current_let_binding
3185 && val_span.contains(ident_span)
3186 && val_span.lo() == ident_span.lo()
3187 {
3188 err.span_suggestion_verbose(
3189 let_span.shrink_to_hi().to(val_span.shrink_to_lo()),
3190 "you might have meant to use `:` for type annotation",
3191 ": ",
3192 Applicability::MaybeIncorrect,
3193 );
3194 return true;
3195 }
3196 false
3197 }
3198
3199 fn find_module(&self, def_id: DefId) -> Option<(Module<'ra>, ImportSuggestion)> {
3200 let mut result = None;
3201 let mut seen_modules = FxHashSet::default();
3202 let mut worklist = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(self.r.graph_root.to_module(), ThinVec::new(), true)]))vec![(self.r.graph_root.to_module(), ThinVec::new(), true)];
3203
3204 while let Some((in_module, path_segments, doc_visible)) = worklist.pop() {
3205 if result.is_some() {
3207 break;
3208 }
3209
3210 in_module.for_each_child(self.r, |r, ident, orig_ident_span, _, name_binding| {
3211 if result.is_some() || !name_binding.vis().is_visible_locally() {
3213 return;
3214 }
3215 if let Some(module_def_id) = name_binding.res().module_like_def_id() {
3216 let mut path_segments = path_segments.clone();
3218 path_segments.push(ast::PathSegment::from_ident(ident.orig(orig_ident_span)));
3219 let doc_visible = doc_visible
3220 && (module_def_id.is_local() || !r.tcx.is_doc_hidden(module_def_id));
3221 if module_def_id == def_id {
3222 let path = Path { span: name_binding.span, segments: path_segments };
3223 result = Some((
3224 r.expect_module(module_def_id),
3225 ImportSuggestion {
3226 did: Some(def_id),
3227 descr: "module",
3228 path,
3229 accessible: true,
3230 doc_visible,
3231 note: None,
3232 via_import: false,
3233 is_stable: true,
3234 },
3235 ));
3236 } else {
3237 if seen_modules.insert(module_def_id) {
3239 let module = r.expect_module(module_def_id);
3240 worklist.push((module, path_segments, doc_visible));
3241 }
3242 }
3243 }
3244 });
3245 }
3246
3247 result
3248 }
3249
3250 fn collect_enum_ctors(&self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
3251 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
3252 let mut variants = Vec::new();
3253 enum_module.for_each_child(self.r, |_, ident, orig_ident_span, _, name_binding| {
3254 if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
3255 let mut segms = enum_import_suggestion.path.segments.clone();
3256 segms.push(ast::PathSegment::from_ident(ident.orig(orig_ident_span)));
3257 let path = Path { span: name_binding.span, segments: segms };
3258 variants.push((path, def_id, kind));
3259 }
3260 });
3261 variants
3262 })
3263 }
3264
3265 fn suggest_using_enum_variant(
3267 &self,
3268 err: &mut Diag<'_>,
3269 source: PathSource<'_, '_, '_>,
3270 def_id: DefId,
3271 span: Span,
3272 ) {
3273 let Some(variant_ctors) = self.collect_enum_ctors(def_id) else {
3274 err.note("you might have meant to use one of the enum's variants");
3275 return;
3276 };
3277
3278 let (suggest_path_sep_dot_span, suggest_only_tuple_variants) = match source {
3283 PathSource::TupleStruct(..) => (None, true),
3285 PathSource::Expr(Some(expr)) => match &expr.kind {
3286 ExprKind::Call(..) => (None, true),
3288 ExprKind::MethodCall(MethodCall {
3291 receiver,
3292 span,
3293 seg: PathSegment { ident, .. },
3294 ..
3295 }) => {
3296 let dot_span = receiver.span.between(*span);
3297 let found_tuple_variant = variant_ctors.iter().any(|(path, _, ctor_kind)| {
3298 *ctor_kind == CtorKind::Fn
3299 && path.segments.last().is_some_and(|seg| seg.ident == *ident)
3300 });
3301 (found_tuple_variant.then_some(dot_span), false)
3302 }
3303 ExprKind::Field(base, ident) => {
3306 let dot_span = base.span.between(ident.span);
3307 let found_tuple_or_unit_variant = variant_ctors.iter().any(|(path, ..)| {
3308 path.segments.last().is_some_and(|seg| seg.ident == *ident)
3309 });
3310 (found_tuple_or_unit_variant.then_some(dot_span), false)
3311 }
3312 _ => (None, false),
3313 },
3314 _ => (None, false),
3315 };
3316
3317 if let Some(dot_span) = suggest_path_sep_dot_span {
3318 err.span_suggestion_verbose(
3319 dot_span,
3320 "use the path separator to refer to a variant",
3321 "::",
3322 Applicability::MaybeIncorrect,
3323 );
3324 } else if suggest_only_tuple_variants {
3325 let mut suggestable_variants = variant_ctors
3328 .iter()
3329 .filter(|(.., kind)| *kind == CtorKind::Fn)
3330 .map(|(variant, ..)| path_names_to_string(variant))
3331 .collect::<Vec<_>>();
3332 suggestable_variants.sort();
3333
3334 let non_suggestable_variant_count = variant_ctors.len() - suggestable_variants.len();
3335
3336 let source_msg = if #[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::TupleStruct(..) => true,
_ => false,
}matches!(source, PathSource::TupleStruct(..)) {
3337 "to match against"
3338 } else {
3339 "to construct"
3340 };
3341
3342 if !suggestable_variants.is_empty() {
3343 let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
3344 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("try {0} the enum\'s variant",
source_msg))
})format!("try {source_msg} the enum's variant")
3345 } else {
3346 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("try {0} one of the enum\'s variants",
source_msg))
})format!("try {source_msg} one of the enum's variants")
3347 };
3348
3349 err.span_suggestions(
3350 span,
3351 msg,
3352 suggestable_variants,
3353 Applicability::MaybeIncorrect,
3354 );
3355 }
3356
3357 if non_suggestable_variant_count == variant_ctors.len() {
3359 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the enum has no tuple variants {0}",
source_msg))
})format!("the enum has no tuple variants {source_msg}"));
3360 }
3361
3362 if non_suggestable_variant_count == 1 {
3364 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might have meant {0} the enum\'s non-tuple variant",
source_msg))
})format!("you might have meant {source_msg} the enum's non-tuple variant"));
3365 } else if non_suggestable_variant_count >= 1 {
3366 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might have meant {0} one of the enum\'s non-tuple variants",
source_msg))
})format!(
3367 "you might have meant {source_msg} one of the enum's non-tuple variants"
3368 ));
3369 }
3370 } else {
3371 let needs_placeholder = |ctor_def_id: DefId, kind: CtorKind| {
3372 let def_id = self.r.tcx.parent(ctor_def_id);
3373 match kind {
3374 CtorKind::Const => false,
3375 CtorKind::Fn => {
3376 !self.r.field_idents(def_id).is_some_and(|field_ids| field_ids.is_empty())
3377 }
3378 }
3379 };
3380
3381 let mut suggestable_variants = variant_ctors
3382 .iter()
3383 .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind))
3384 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
3385 .map(|(variant, kind)| match kind {
3386 CtorKind::Const => variant,
3387 CtorKind::Fn => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0}())", variant))
})format!("({variant}())"),
3388 })
3389 .collect::<Vec<_>>();
3390 suggestable_variants.sort();
3391 let no_suggestable_variant = suggestable_variants.is_empty();
3392
3393 if !no_suggestable_variant {
3394 let msg = if suggestable_variants.len() == 1 {
3395 "you might have meant to use the following enum variant"
3396 } else {
3397 "you might have meant to use one of the following enum variants"
3398 };
3399
3400 err.span_suggestions(
3401 span,
3402 msg,
3403 suggestable_variants,
3404 Applicability::MaybeIncorrect,
3405 );
3406 }
3407
3408 let mut suggestable_variants_with_placeholders = variant_ctors
3409 .iter()
3410 .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
3411 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
3412 .filter_map(|(variant, kind)| match kind {
3413 CtorKind::Fn => Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0}(/* fields */))", variant))
})format!("({variant}(/* fields */))")),
3414 _ => None,
3415 })
3416 .collect::<Vec<_>>();
3417 suggestable_variants_with_placeholders.sort();
3418
3419 if !suggestable_variants_with_placeholders.is_empty() {
3420 let msg =
3421 match (no_suggestable_variant, suggestable_variants_with_placeholders.len()) {
3422 (true, 1) => "the following enum variant is available",
3423 (true, _) => "the following enum variants are available",
3424 (false, 1) => "alternatively, the following enum variant is available",
3425 (false, _) => {
3426 "alternatively, the following enum variants are also available"
3427 }
3428 };
3429
3430 err.span_suggestions(
3431 span,
3432 msg,
3433 suggestable_variants_with_placeholders,
3434 Applicability::HasPlaceholders,
3435 );
3436 }
3437 };
3438
3439 if def_id.is_local() {
3440 err.span_note(self.r.def_span(def_id), "the enum is defined here");
3441 }
3442 }
3443
3444 pub(crate) fn detect_and_suggest_const_parameter_error(
3475 &mut self,
3476 path: &[Segment],
3477 source: PathSource<'_, 'ast, 'ra>,
3478 ) -> Option<Diag<'tcx>> {
3479 let Some(item) = self.diag_metadata.current_item else { return None };
3480 let ItemKind::Impl(impl_) = &item.kind else { return None };
3481 let self_ty = &impl_.self_ty;
3482
3483 let [current_parameter] = path else {
3485 return None;
3486 };
3487
3488 let target_ident = current_parameter.ident;
3489
3490 let visitor = ParentPathVisitor::new(self_ty, target_ident);
3492
3493 let Some(parent_segment) = visitor.parent else {
3494 return None;
3495 };
3496
3497 let Some(args) = parent_segment.args.as_ref() else {
3498 return None;
3499 };
3500
3501 let GenericArgs::AngleBracketed(angle) = args.as_ref() else {
3502 return None;
3503 };
3504
3505 let usage_to_pos: FxHashMap<NodeId, usize> = angle
3508 .args
3509 .iter()
3510 .enumerate()
3511 .filter_map(|(pos, arg)| {
3512 if let AngleBracketedArg::Arg(GenericArg::Type(ty)) = arg
3513 && let TyKind::Path(_, path) = &ty.kind
3514 && let [segment] = path.segments.as_slice()
3515 {
3516 Some((segment.id, pos))
3517 } else {
3518 None
3519 }
3520 })
3521 .collect();
3522
3523 let Some(idx) = current_parameter.id.and_then(|id| usage_to_pos.get(&id).copied()) else {
3526 return None;
3527 };
3528
3529 let ns = source.namespace();
3531 let segment = Segment::from(parent_segment);
3532 let segments = [segment];
3533 let finalize = Finalize::new(parent_segment.id, parent_segment.ident.span);
3534
3535 if let Ok(Some(resolve)) = self.resolve_qpath_anywhere(
3536 &None,
3537 &segments,
3538 ns,
3539 source.defer_to_typeck(),
3540 finalize,
3541 source,
3542 ) && let Some(resolve) = resolve.full_res()
3543 && let Res::Def(_, def_id) = resolve
3544 && def_id.is_local()
3545 && let Some(local_def_id) = def_id.as_local()
3546 && let Some(struct_generics) = self.r.struct_generics.get(&local_def_id)
3547 && let Some(target_param) = &struct_generics.params.get(idx)
3548 && let GenericParamKind::Const { ty, .. } = &target_param.kind
3549 && let TyKind::Path(_, path) = &ty.kind
3550 {
3551 let full_type = path
3552 .segments
3553 .iter()
3554 .map(|seg| seg.ident.to_string())
3555 .collect::<Vec<_>>()
3556 .join("::");
3557
3558 let next_impl_param = impl_.generics.params.iter().find(|impl_param| {
3563 angle
3564 .args
3565 .iter()
3566 .find_map(|arg| {
3567 if let AngleBracketedArg::Arg(GenericArg::Type(ty)) = arg
3568 && let TyKind::Path(_, path) = &ty.kind
3569 && let [segment] = path.segments.as_slice()
3570 && segment.ident == impl_param.ident
3571 {
3572 usage_to_pos.get(&segment.id).copied()
3573 } else {
3574 None
3575 }
3576 })
3577 .map_or(false, |pos| pos > idx)
3578 });
3579
3580 let (insert_span, snippet) = match next_impl_param {
3581 Some(next_param) => {
3582 (
3585 next_param.span().shrink_to_lo(),
3586 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("const {0}: {1}, ", target_ident,
full_type))
})format!("const {}: {}, ", target_ident, full_type),
3587 )
3588 }
3589 None => match impl_.generics.params.last() {
3590 Some(last) => {
3591 (
3594 last.span().shrink_to_hi(),
3595 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", const {0}: {1}", target_ident,
full_type))
})format!(", const {}: {}", target_ident, full_type),
3596 )
3597 }
3598 None => {
3599 (
3602 impl_.generics.span.shrink_to_hi(),
3603 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<const {0}: {1}>", target_ident,
full_type))
})format!("<const {}: {}>", target_ident, full_type),
3604 )
3605 }
3606 },
3607 };
3608
3609 let mut err = self.r.dcx().struct_span_err(
3610 target_ident.span,
3611 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot find const `{0}` in this scope",
target_ident))
})format!("cannot find const `{}` in this scope", target_ident),
3612 );
3613
3614 err.code(E0425);
3615
3616 err.span_label(target_ident.span, "not found in this scope");
3617
3618 err.span_label(
3619 target_param.span(),
3620 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("corresponding const parameter on the type defined here"))
})format!("corresponding const parameter on the type defined here",),
3621 );
3622
3623 err.subdiagnostic(diagnostics::UnexpectedMissingConstParameter {
3624 span: insert_span,
3625 snippet,
3626 item_name: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", target_ident))
})format!("{}", target_ident),
3627 item_location: String::from("impl"),
3628 });
3629
3630 return Some(err);
3631 }
3632
3633 None
3634 }
3635
3636 pub(crate) fn suggest_adding_generic_parameter(
3637 &mut self,
3638 path: &[Segment],
3639 source: PathSource<'_, 'ast, 'ra>,
3640 ) -> (Option<(Span, &'static str, String, Applicability)>, Option<Diag<'tcx>>) {
3641 let (ident, span) = match path {
3642 [segment]
3643 if !segment.has_generic_args
3644 && segment.ident.name != kw::SelfUpper
3645 && segment.ident.name != kw::Dyn =>
3646 {
3647 (segment.ident.to_string(), segment.ident.span)
3648 }
3649 _ => return (None, None),
3650 };
3651 let mut iter = ident.chars().map(|c| c.is_uppercase());
3652 let single_uppercase_char =
3653 #[allow(non_exhaustive_omitted_patterns)] match iter.next() {
Some(true) => true,
_ => false,
}matches!(iter.next(), Some(true)) && #[allow(non_exhaustive_omitted_patterns)] match iter.next() {
None => true,
_ => false,
}matches!(iter.next(), None);
3654 if !self.diag_metadata.currently_processing_generic_args && !single_uppercase_char {
3655 return (None, None);
3656 }
3657 match (
3658 self.diag_metadata.current_item,
3659 single_uppercase_char,
3660 self.diag_metadata.currently_processing_generic_args,
3661 ) {
3662 (Some(Item { kind: ItemKind::Fn(fn_), .. }), _, _) if fn_.ident.name == sym::main => {
3663 }
3665 (
3666 Some(Item {
3667 kind:
3668 kind @ ItemKind::Fn(..)
3669 | kind @ ItemKind::Enum(..)
3670 | kind @ ItemKind::Struct(..)
3671 | kind @ ItemKind::Union(..),
3672 ..
3673 }),
3674 true,
3675 _,
3676 )
3677 | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true)
3679 | (Some(Item { kind, .. }), false, _) => {
3680 if let Some(generics) = kind.generics() {
3681 if span.overlaps(generics.span) {
3682 return (None, None);
3691 }
3692
3693 let (msg, sugg) = match source {
3694 PathSource::Type | PathSource::PreciseCapturingArg(TypeNS) => {
3695 if let Some(err) =
3696 self.detect_and_suggest_const_parameter_error(path, source)
3697 {
3698 return (None, Some(err));
3699 }
3700 ("you might be missing a type parameter", ident)
3701 }
3702 PathSource::Expr(_) | PathSource::PreciseCapturingArg(ValueNS) => (
3703 "you might be missing a const parameter",
3704 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("const {0}: /* Type */", ident))
})format!("const {ident}: /* Type */"),
3705 ),
3706 _ => return (None, None),
3707 };
3708 let (span, sugg) = if let [.., param] = &generics.params[..] {
3709 let span = if let [.., bound] = ¶m.bounds[..] {
3710 bound.span()
3711 } else if let GenericParam {
3712 kind: GenericParamKind::Const { ty, span: _, default },
3713 ..
3714 } = param
3715 {
3716 default.as_ref().map(|def| def.value.span).unwrap_or(ty.span)
3717 } else {
3718 param.ident.span
3719 };
3720 (span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", {0}", sugg))
})format!(", {sugg}"))
3721 } else {
3722 (generics.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", sugg))
})format!("<{sugg}>"))
3723 };
3724 if span.can_be_used_for_suggestions() {
3726 return (
3727 Some((span.shrink_to_hi(), msg, sugg, Applicability::MaybeIncorrect)),
3728 None,
3729 );
3730 }
3731 }
3732 }
3733 _ => {}
3734 }
3735 (None, None)
3736 }
3737
3738 pub(crate) fn suggestion_for_label_in_rib(
3741 &self,
3742 rib_index: usize,
3743 label: Ident,
3744 ) -> Option<LabelSuggestion> {
3745 let within_scope = self.is_label_valid_from_rib(rib_index);
3747
3748 let rib = &self.label_ribs[rib_index];
3749 let names = rib
3750 .bindings
3751 .iter()
3752 .filter(|(id, _)| id.span.eq_ctxt(label.span))
3753 .map(|(id, _)| id.name)
3754 .collect::<Vec<Symbol>>();
3755
3756 find_best_match_for_name(&names, label.name, None).map(|symbol| {
3757 let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
3761 (*ident, within_scope)
3762 })
3763 }
3764
3765 pub(crate) fn maybe_report_lifetime_uses(
3766 &mut self,
3767 generics_span: Span,
3768 params: &[ast::GenericParam],
3769 ) {
3770 for (param_index, param) in params.iter().enumerate() {
3771 let GenericParamKind::Lifetime = param.kind else { continue };
3772
3773 let def_id = self.r.local_def_id(param.id);
3774
3775 let use_set = self.lifetime_uses.remove(&def_id);
3776 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/late/diagnostics.rs:3776",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3776u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Use set for {0:?}({1:?} at {2:?}) is {3:?}",
def_id, param.ident, param.ident.span, use_set) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
3777 "Use set for {:?}({:?} at {:?}) is {:?}",
3778 def_id, param.ident, param.ident.span, use_set
3779 );
3780
3781 let deletion_span = || {
3782 if params.len() == 1 {
3783 Some(generics_span)
3785 } else if param_index == 0 {
3786 match (
3789 param.span().find_ancestor_inside(generics_span),
3790 params[param_index + 1].span().find_ancestor_inside(generics_span),
3791 ) {
3792 (Some(param_span), Some(next_param_span)) => {
3793 Some(param_span.to(next_param_span.shrink_to_lo()))
3794 }
3795 _ => None,
3796 }
3797 } else {
3798 match (
3801 param.span().find_ancestor_inside(generics_span),
3802 params[param_index - 1].span().find_ancestor_inside(generics_span),
3803 ) {
3804 (Some(param_span), Some(prev_param_span)) => {
3805 Some(prev_param_span.shrink_to_hi().to(param_span))
3806 }
3807 _ => None,
3808 }
3809 }
3810 };
3811 match use_set {
3812 Some(LifetimeUseSet::Many) => {}
3813 Some(LifetimeUseSet::One { .. }) if !param.bounds.is_empty() => {}
3816 Some(LifetimeUseSet::One { use_span, use_ctxt }) => {
3817 let param_ident = param.ident;
3818 let deletion_span =
3819 if param.bounds.is_empty() { deletion_span() } else { None };
3820 self.r.lint_buffer.dyn_buffer_lint_any(
3821 SINGLE_USE_LIFETIMES,
3822 param.id,
3823 param_ident.span,
3824 move |dcx, level, sess| {
3825 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/late/diagnostics.rs:3825",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3825u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("param_ident")
}> =
::tracing::__macro_support::FieldName::new("param_ident");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("param_ident.span")
}> =
::tracing::__macro_support::FieldName::new("param_ident.span");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("use_span")
}> =
::tracing::__macro_support::FieldName::new("use_span");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(¶m_ident)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(¶m_ident.span)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&use_span)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?param_ident, ?param_ident.span, ?use_span);
3826
3827 let elidable = #[allow(non_exhaustive_omitted_patterns)] match use_ctxt {
LifetimeCtxt::Ref => true,
_ => false,
}matches!(use_ctxt, LifetimeCtxt::Ref);
3828 let suggestion = if let Some(deletion_span) = deletion_span {
3829 let (use_span, replace_lt) = if elidable {
3830 let use_span = sess
3831 .downcast_ref::<Session>()
3832 .expect("expected a `Session`")
3833 .source_map()
3834 .span_extend_while_whitespace(use_span);
3835 (use_span, String::new())
3836 } else {
3837 (use_span, "'_".to_owned())
3838 };
3839 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/late/diagnostics.rs:3839",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3839u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("deletion_span")
}> =
::tracing::__macro_support::FieldName::new("deletion_span");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("use_span")
}> =
::tracing::__macro_support::FieldName::new("use_span");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&deletion_span)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&use_span)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?deletion_span, ?use_span);
3840
3841 let deletion_span = if deletion_span.is_empty() {
3844 None
3845 } else {
3846 Some(deletion_span)
3847 };
3848 Some(diagnostics::SingleUseLifetimeSugg {
3849 deletion_span,
3850 use_span,
3851 replace_lt,
3852 })
3853 } else {
3854 None
3855 };
3856 diagnostics::SingleUseLifetime {
3857 suggestion,
3858 param_span: param_ident.span,
3859 use_span,
3860 ident: param_ident,
3861 }
3862 .into_diag(dcx, level)
3863 },
3864 );
3865 }
3866 None => {
3867 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/late/diagnostics.rs:3867",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3867u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("param.ident")
}> =
::tracing::__macro_support::FieldName::new("param.ident");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("param.ident.span")
}> =
::tracing::__macro_support::FieldName::new("param.ident.span");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(¶m.ident)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(¶m.ident.span)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?param.ident, ?param.ident.span);
3868 let deletion_span = deletion_span();
3869
3870 if deletion_span.is_some_and(|sp| !sp.in_derive_expansion()) {
3872 self.r.lint_buffer.buffer_lint(
3873 UNUSED_LIFETIMES,
3874 param.id,
3875 param.ident.span,
3876 diagnostics::UnusedLifetime { deletion_span, ident: param.ident },
3877 );
3878 }
3879 }
3880 }
3881 }
3882 }
3883
3884 pub(crate) fn emit_undeclared_lifetime_error(
3885 &self,
3886 lifetime_ref: &ast::Lifetime,
3887 outer_lifetime_ref: Option<Ident>,
3888 ) -> ErrorGuaranteed {
3889 if true {
{
match (&lifetime_ref.ident.name, &kw::UnderscoreLifetime) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_ne!(lifetime_ref.ident.name, kw::UnderscoreLifetime);
3890 let mut err = if let Some(outer) = outer_lifetime_ref {
3891 {
self.r.dcx().struct_span_err(lifetime_ref.ident.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("can\'t use generic parameters from outer item"))
})).with_code(E0401)
}struct_span_code_err!(
3892 self.r.dcx(),
3893 lifetime_ref.ident.span,
3894 E0401,
3895 "can't use generic parameters from outer item",
3896 )
3897 .with_span_label(lifetime_ref.ident.span, "use of generic parameter from outer item")
3898 .with_span_label(outer.span, "lifetime parameter from outer item")
3899 } else {
3900 {
self.r.dcx().struct_span_err(lifetime_ref.ident.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use of undeclared lifetime name `{0}`",
lifetime_ref.ident))
})).with_code(E0261)
}struct_span_code_err!(
3901 self.r.dcx(),
3902 lifetime_ref.ident.span,
3903 E0261,
3904 "use of undeclared lifetime name `{}`",
3905 lifetime_ref.ident
3906 )
3907 .with_span_label(lifetime_ref.ident.span, "undeclared lifetime")
3908 };
3909
3910 if edit_distance(lifetime_ref.ident.name.as_str(), "'static", 2).is_some() {
3912 err.span_suggestion_verbose(
3913 lifetime_ref.ident.span,
3914 "you may have misspelled the `'static` lifetime",
3915 "'static",
3916 Applicability::MachineApplicable,
3917 );
3918 } else {
3919 self.suggest_introducing_lifetime(
3920 &mut err,
3921 Some(lifetime_ref.ident),
3922 |err, _, span, message, suggestion, span_suggs| {
3923 err.multipart_suggestion(
3924 message,
3925 std::iter::once((span, suggestion)).chain(span_suggs).collect(),
3926 Applicability::MaybeIncorrect,
3927 );
3928 true
3929 },
3930 );
3931 }
3932
3933 err.emit()
3934 }
3935
3936 fn suggest_introducing_lifetime(
3937 &self,
3938 err: &mut Diag<'_>,
3939 name: Option<Ident>,
3940 suggest: impl Fn(
3941 &mut Diag<'_>,
3942 bool,
3943 Span,
3944 Cow<'static, str>,
3945 String,
3946 Vec<(Span, String)>,
3947 ) -> bool,
3948 ) {
3949 self.suggest_introducing_lifetime_filtered(err, name, |_| true, suggest);
3950 }
3951
3952 pub(crate) fn suggest_introducing_lifetime_for_assoc_ty_binding(
3953 &self,
3954 err: &mut Diag<'_>,
3955 lifetime: Span,
3956 ) {
3957 self.suggest_introducing_lifetime_filtered(
3958 err,
3959 None,
3960 |kind| {
3961 !#[allow(non_exhaustive_omitted_patterns)] match kind {
LifetimeBinderKind::FnPtrType | LifetimeBinderKind::PolyTrait |
LifetimeBinderKind::WhereBound => true,
_ => false,
}matches!(
3962 kind,
3963 LifetimeBinderKind::FnPtrType
3964 | LifetimeBinderKind::PolyTrait
3965 | LifetimeBinderKind::WhereBound
3966 )
3967 },
3968 |err, _higher_ranked, span, message, intro_sugg, _| {
3969 err.multipart_suggestion(
3970 message,
3971 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span, intro_sugg), (lifetime.shrink_to_hi(), "'a ".to_string())]))vec![(span, intro_sugg), (lifetime.shrink_to_hi(), "'a ".to_string())],
3972 Applicability::MaybeIncorrect,
3973 );
3974 false
3975 },
3976 );
3977 }
3978
3979 fn suggest_introducing_lifetime_filtered(
3980 &self,
3981 err: &mut Diag<'_>,
3982 name: Option<Ident>,
3983 mut consider: impl FnMut(LifetimeBinderKind) -> bool,
3984 suggest: impl Fn(
3985 &mut Diag<'_>,
3986 bool,
3987 Span,
3988 Cow<'static, str>,
3989 String,
3990 Vec<(Span, String)>,
3991 ) -> bool,
3992 ) {
3993 let mut suggest_note = true;
3994 for rib in self.lifetime_ribs.iter().rev() {
3995 let mut should_continue = true;
3996 match rib.kind {
3997 LifetimeRibKind::Generics { binder, span, kind } => {
3998 if let LifetimeBinderKind::ConstItem = kind
4001 && !self.r.tcx().features().generic_const_items()
4002 {
4003 continue;
4004 }
4005 if #[allow(non_exhaustive_omitted_patterns)] match kind {
LifetimeBinderKind::ImplAssocType => true,
_ => false,
}matches!(kind, LifetimeBinderKind::ImplAssocType) || !consider(kind) {
4006 continue;
4007 }
4008
4009 if !span.can_be_used_for_suggestions()
4010 && suggest_note
4011 && let Some(name) = name
4012 {
4013 suggest_note = false; err.span_label(
4015 span,
4016 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("lifetime `{0}` is missing in item created through this procedural macro",
name))
})format!(
4017 "lifetime `{name}` is missing in item created through this procedural macro",
4018 ),
4019 );
4020 continue;
4021 }
4022
4023 let higher_ranked = #[allow(non_exhaustive_omitted_patterns)] match kind {
LifetimeBinderKind::FnPtrType | LifetimeBinderKind::PolyTrait |
LifetimeBinderKind::WhereBound => true,
_ => false,
}matches!(
4024 kind,
4025 LifetimeBinderKind::FnPtrType
4026 | LifetimeBinderKind::PolyTrait
4027 | LifetimeBinderKind::WhereBound
4028 );
4029
4030 let mut rm_inner_binders: FxIndexSet<Span> = Default::default();
4031 let (span, sugg) = if span.is_empty() {
4032 let mut binder_idents: FxIndexSet<Ident> = Default::default();
4033 binder_idents.insert(name.unwrap_or(Ident::from_str("'a")));
4034
4035 if let LifetimeBinderKind::WhereBound = kind
4042 && let Some(predicate) = self.diag_metadata.current_where_predicate
4043 && let ast::WherePredicateKind::BoundPredicate(
4044 ast::WhereBoundPredicate { bounded_ty, bounds, .. },
4045 ) = &predicate.kind
4046 && bounded_ty.id == binder
4047 {
4048 for bound in bounds {
4049 if let ast::GenericBound::Trait(poly_trait_ref) = bound
4050 && let span = poly_trait_ref
4051 .span
4052 .with_hi(poly_trait_ref.trait_ref.path.span.lo())
4053 && !span.is_empty()
4054 {
4055 rm_inner_binders.insert(span);
4056 poly_trait_ref.bound_generic_params.iter().for_each(|v| {
4057 binder_idents.insert(v.ident);
4058 });
4059 }
4060 }
4061 }
4062
4063 let binders_sugg: String = binder_idents
4064 .into_iter()
4065 .map(|ident| ident.to_string())
4066 .intersperse(", ".to_owned())
4067 .collect();
4068 let sugg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}<{1}>{2}",
if higher_ranked { "for" } else { "" }, binders_sugg,
if higher_ranked { " " } else { "" }))
})format!(
4069 "{}<{}>{}",
4070 if higher_ranked { "for" } else { "" },
4071 binders_sugg,
4072 if higher_ranked { " " } else { "" },
4073 );
4074 (span, sugg)
4075 } else {
4076 let span = self
4077 .r
4078 .tcx
4079 .sess
4080 .source_map()
4081 .span_through_char(span, '<')
4082 .shrink_to_hi();
4083 let sugg =
4084 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, ",
name.map(|i| i.to_string()).as_deref().unwrap_or("'a")))
})format!("{}, ", name.map(|i| i.to_string()).as_deref().unwrap_or("'a"));
4085 (span, sugg)
4086 };
4087
4088 if higher_ranked {
4089 let message = Cow::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider making the {0} lifetime-generic with a new `{1}` lifetime",
kind.descr(),
name.map(|i| i.to_string()).as_deref().unwrap_or("'a")))
})format!(
4090 "consider making the {} lifetime-generic with a new `{}` lifetime",
4091 kind.descr(),
4092 name.map(|i| i.to_string()).as_deref().unwrap_or("'a"),
4093 ));
4094 should_continue = suggest(
4095 err,
4096 true,
4097 span,
4098 message,
4099 sugg,
4100 if !rm_inner_binders.is_empty() {
4101 rm_inner_binders
4102 .into_iter()
4103 .map(|v| (v, "".to_string()))
4104 .collect::<Vec<_>>()
4105 } else {
4106 ::alloc::vec::Vec::new()vec![]
4107 },
4108 );
4109 err.note_once(
4110 "for more information on higher-ranked polymorphism, visit \
4111 https://doc.rust-lang.org/nomicon/hrtb.html",
4112 );
4113 } else if let Some(name) = name {
4114 let message =
4115 Cow::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider introducing lifetime `{0}` here",
name))
})format!("consider introducing lifetime `{name}` here"));
4116 should_continue = suggest(err, false, span, message, sugg, ::alloc::vec::Vec::new()vec![]);
4117 } else {
4118 let message = Cow::from("consider introducing a named lifetime parameter");
4119 should_continue = suggest(err, false, span, message, sugg, ::alloc::vec::Vec::new()vec![]);
4120 }
4121 }
4122 LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy => break,
4123 _ => {}
4124 }
4125 if !should_continue {
4126 break;
4127 }
4128 }
4129 }
4130
4131 pub(crate) fn emit_non_static_lt_in_const_param_ty_error(
4132 &self,
4133 lifetime_ref: &ast::Lifetime,
4134 ) -> ErrorGuaranteed {
4135 self.r
4136 .dcx()
4137 .create_err(diagnostics::ParamInTyOfConstParam {
4138 span: lifetime_ref.ident.span,
4139 name: lifetime_ref.ident.name,
4140 })
4141 .emit()
4142 }
4143
4144 pub(crate) fn emit_forbidden_non_static_lifetime_error(
4148 &self,
4149 cause: NoConstantGenericsReason,
4150 lifetime_ref: &ast::Lifetime,
4151 ) -> ErrorGuaranteed {
4152 match cause {
4153 NoConstantGenericsReason::IsEnumDiscriminant => self
4154 .r
4155 .dcx()
4156 .create_err(diagnostics::ParamInEnumDiscriminant {
4157 span: lifetime_ref.ident.span,
4158 name: lifetime_ref.ident.name,
4159 param_kind: diagnostics::ParamKindInEnumDiscriminant::Lifetime,
4160 })
4161 .emit(),
4162 NoConstantGenericsReason::NonTrivialConstArg => {
4163 if !!self.r.features.generic_const_exprs() {
::core::panicking::panic("assertion failed: !self.r.features.generic_const_exprs()")
};assert!(!self.r.features.generic_const_exprs());
4164 self.r
4165 .dcx()
4166 .create_err(diagnostics::ParamInNonTrivialAnonConst {
4167 span: lifetime_ref.ident.span,
4168 name: lifetime_ref.ident.name,
4169 param_kind: diagnostics::ParamKindInNonTrivialAnonConst::Lifetime,
4170 help: self.r.tcx.sess.is_nightly_build()
4171 && !self.r.features.min_generic_const_args(),
4172 is_gca: self.r.features.generic_const_args(),
4173 help_gca: self.r.features.generic_const_args(),
4174 help_suggest_gca: self.r.tcx.sess.is_nightly_build()
4175 && !self.r.features.generic_const_args(),
4176 })
4177 .emit()
4178 }
4179 }
4180 }
4181
4182 pub(crate) fn report_missing_lifetime_specifiers<'a>(
4183 &mut self,
4184 lifetime_refs: impl Clone + IntoIterator<Item = &'a MissingLifetime>,
4185 function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
4186 ) -> ErrorGuaranteed {
4187 let num_lifetimes: usize = lifetime_refs.clone().into_iter().map(|lt| lt.count).sum();
4188 let spans: Vec<_> = lifetime_refs.clone().into_iter().map(|lt| lt.span).collect();
4189
4190 let mut err = {
self.r.dcx().struct_span_err(spans,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("missing lifetime specifier{0}",
if num_lifetimes == 1 { "" } else { "s" }))
})).with_code(E0106)
}struct_span_code_err!(
4191 self.r.dcx(),
4192 spans,
4193 E0106,
4194 "missing lifetime specifier{}",
4195 pluralize!(num_lifetimes)
4196 );
4197 self.add_missing_lifetime_specifiers_label(
4198 &mut err,
4199 lifetime_refs,
4200 function_param_lifetimes,
4201 );
4202 err.emit()
4203 }
4204
4205 fn add_missing_lifetime_specifiers_label<'a>(
4206 &mut self,
4207 err: &mut Diag<'_>,
4208 lifetime_refs: impl Clone + IntoIterator<Item = &'a MissingLifetime>,
4209 function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
4210 ) {
4211 for < in lifetime_refs.clone() {
4212 err.span_label(
4213 lt.span,
4214 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected {0} lifetime parameter{1}",
if lt.count == 1 {
"named".to_string()
} else { lt.count.to_string() },
if lt.count == 1 { "" } else { "s" }))
})format!(
4215 "expected {} lifetime parameter{}",
4216 if lt.count == 1 { "named".to_string() } else { lt.count.to_string() },
4217 pluralize!(lt.count),
4218 ),
4219 );
4220 }
4221
4222 let mut in_scope_lifetimes: Vec<_> = self
4223 .lifetime_ribs
4224 .iter()
4225 .rev()
4226 .take_while(|rib| {
4227 !#[allow(non_exhaustive_omitted_patterns)] match rib.kind {
LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy => true,
_ => false,
}matches!(rib.kind, LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy)
4228 })
4229 .flat_map(|rib| rib.bindings.iter())
4230 .map(|(&ident, &res)| (ident, res))
4231 .filter(|(ident, _)| ident.name != kw::UnderscoreLifetime)
4232 .collect();
4233 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/late/diagnostics.rs:4233",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(4233u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("in_scope_lifetimes")
}> =
::tracing::__macro_support::FieldName::new("in_scope_lifetimes");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&in_scope_lifetimes)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?in_scope_lifetimes);
4234
4235 let mut maybe_static = false;
4236 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/late/diagnostics.rs:4236",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(4236u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("function_param_lifetimes")
}> =
::tracing::__macro_support::FieldName::new("function_param_lifetimes");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&function_param_lifetimes)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?function_param_lifetimes);
4237 if let Some((param_lifetimes, params)) = &function_param_lifetimes {
4238 let elided_len = param_lifetimes.len();
4239 let num_params = params.len();
4240
4241 let mut m = String::new();
4242
4243 for (i, info) in params.iter().enumerate() {
4244 let ElisionFnParameter { ident, index, lifetime_count, span } = *info;
4245 if true {
{
match (&lifetime_count, &0) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_ne!(lifetime_count, 0);
4246
4247 err.span_label(span, "");
4248
4249 if i != 0 {
4250 if i + 1 < num_params {
4251 m.push_str(", ");
4252 } else if num_params == 2 {
4253 m.push_str(" or ");
4254 } else {
4255 m.push_str(", or ");
4256 }
4257 }
4258
4259 let help_name = if let Some(ident) = ident {
4260 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", ident))
})format!("`{ident}`")
4261 } else {
4262 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("argument {0}", index + 1))
})format!("argument {}", index + 1)
4263 };
4264
4265 if lifetime_count == 1 {
4266 m.push_str(&help_name[..])
4267 } else {
4268 m.push_str(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("one of {0}\'s {1} lifetimes",
help_name, lifetime_count))
})format!("one of {help_name}'s {lifetime_count} lifetimes")[..])
4269 }
4270 }
4271
4272 if num_params == 0 {
4273 err.help(
4274 "this function's return type contains a borrowed value, but there is no value \
4275 for it to be borrowed from",
4276 );
4277 if in_scope_lifetimes.is_empty() {
4278 maybe_static = true;
4279 in_scope_lifetimes = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(Ident::with_dummy_span(kw::StaticLifetime),
(DUMMY_NODE_ID, LifetimeRes::Static))]))vec![(
4280 Ident::with_dummy_span(kw::StaticLifetime),
4281 (DUMMY_NODE_ID, LifetimeRes::Static),
4282 )];
4283 }
4284 } else if elided_len == 0 {
4285 err.help(
4286 "this function's return type contains a borrowed value with an elided \
4287 lifetime, but the lifetime cannot be derived from the arguments",
4288 );
4289 if in_scope_lifetimes.is_empty() {
4290 maybe_static = true;
4291 in_scope_lifetimes = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(Ident::with_dummy_span(kw::StaticLifetime),
(DUMMY_NODE_ID, LifetimeRes::Static))]))vec![(
4292 Ident::with_dummy_span(kw::StaticLifetime),
4293 (DUMMY_NODE_ID, LifetimeRes::Static),
4294 )];
4295 }
4296 } else if num_params == 1 {
4297 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this function\'s return type contains a borrowed value, but the signature does not say which {0} it is borrowed from",
m))
})format!(
4298 "this function's return type contains a borrowed value, but the signature does \
4299 not say which {m} it is borrowed from",
4300 ));
4301 } else {
4302 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this function\'s return type contains a borrowed value, but the signature does not say whether it is borrowed from {0}",
m))
})format!(
4303 "this function's return type contains a borrowed value, but the signature does \
4304 not say whether it is borrowed from {m}",
4305 ));
4306 }
4307 }
4308
4309 #[allow(rustc::symbol_intern_string_literal)]
4310 let existing_name = match &in_scope_lifetimes[..] {
4311 [] => Symbol::intern("'a"),
4312 [(existing, _)] => existing.name,
4313 _ => Symbol::intern("'lifetime"),
4314 };
4315
4316 let mut spans_suggs: Vec<_> = Vec::new();
4317 let source_map = self.r.tcx.sess.source_map();
4318 let build_sugg = |lt: MissingLifetime| match lt.kind {
4319 MissingLifetimeKind::Underscore => {
4320 if true {
{
match (<.count, &1) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(lt.count, 1);
4321 (lt.span, existing_name.to_string())
4322 }
4323 MissingLifetimeKind::Ampersand => {
4324 if true {
{
match (<.count, &1) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(lt.count, 1);
4325 (lt.span.shrink_to_hi(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} ", existing_name))
})format!("{existing_name} "))
4326 }
4327 MissingLifetimeKind::Comma => {
4328 let sugg: String = std::iter::repeat_n(existing_name.as_str(), lt.count)
4329 .intersperse(", ")
4330 .collect();
4331 let is_empty_brackets = source_map.span_followed_by(lt.span, ">").is_some();
4332 let sugg = if is_empty_brackets { sugg } else { ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, ", sugg))
})format!("{sugg}, ") };
4333 (lt.span.shrink_to_hi(), sugg)
4334 }
4335 MissingLifetimeKind::Brackets => {
4336 let sugg: String = std::iter::once("<")
4337 .chain(std::iter::repeat_n(existing_name.as_str(), lt.count).intersperse(", "))
4338 .chain([">"])
4339 .collect();
4340 (lt.span.shrink_to_hi(), sugg)
4341 }
4342 };
4343 for < in lifetime_refs.clone() {
4344 spans_suggs.push(build_sugg(lt));
4345 }
4346 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/late/diagnostics.rs:4346",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(4346u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("spans_suggs")
}> =
::tracing::__macro_support::FieldName::new("spans_suggs");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&spans_suggs)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?spans_suggs);
4347 match in_scope_lifetimes.len() {
4348 0 => {
4349 if let Some((param_lifetimes, _)) = function_param_lifetimes {
4350 for lt in param_lifetimes {
4351 spans_suggs.push(build_sugg(lt))
4352 }
4353 }
4354 self.suggest_introducing_lifetime(
4355 err,
4356 None,
4357 |err, higher_ranked, span, message, intro_sugg, _| {
4358 err.multipart_suggestion(
4359 message,
4360 std::iter::once((span, intro_sugg))
4361 .chain(spans_suggs.clone())
4362 .collect(),
4363 Applicability::MaybeIncorrect,
4364 );
4365 higher_ranked
4366 },
4367 );
4368 }
4369 1 => {
4370 let post = if maybe_static {
4371 let mut lifetime_refs = lifetime_refs.clone().into_iter();
4372 let owned = if let Some(lt) = lifetime_refs.next()
4373 && lifetime_refs.next().is_none()
4374 && lt.kind != MissingLifetimeKind::Ampersand
4375 {
4376 ", or if you will only have owned values"
4377 } else {
4378 ""
4379 };
4380 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", but this is uncommon unless you\'re returning a borrowed value from a `const` or a `static`{0}",
owned))
})format!(
4381 ", but this is uncommon unless you're returning a borrowed value from a \
4382 `const` or a `static`{owned}",
4383 )
4384 } else {
4385 String::new()
4386 };
4387 err.multipart_suggestion(
4388 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider using the `{0}` lifetime{1}",
existing_name, post))
})format!("consider using the `{existing_name}` lifetime{post}"),
4389 spans_suggs,
4390 Applicability::MaybeIncorrect,
4391 );
4392 if maybe_static {
4393 let mut lifetime_refs = lifetime_refs.into_iter();
4399 if let Some(lt) = lifetime_refs.next()
4400 && lifetime_refs.next().is_none()
4401 && (lt.kind == MissingLifetimeKind::Ampersand
4402 || lt.kind == MissingLifetimeKind::Underscore)
4403 {
4404 let pre = if let Some((kind, _span)) = self.diag_metadata.current_function
4405 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
4406 && !sig.decl.inputs.is_empty()
4407 && let sugg = sig
4408 .decl
4409 .inputs
4410 .iter()
4411 .filter_map(|param| {
4412 if param.ty.span.contains(lt.span) {
4413 None
4416 } else if let TyKind::CVarArgs = param.ty.kind {
4417 None
4419 } else if let TyKind::ImplTrait(..) = ¶m.ty.kind {
4420 None
4422 } else {
4423 Some((param.ty.span.shrink_to_lo(), "&".to_string()))
4424 }
4425 })
4426 .collect::<Vec<_>>()
4427 && !sugg.is_empty()
4428 {
4429 let (the, s) = if sig.decl.inputs.len() == 1 {
4430 ("the", "")
4431 } else {
4432 ("one of the", "s")
4433 };
4434 let dotdotdot =
4435 if lt.kind == MissingLifetimeKind::Ampersand { "..." } else { "" };
4436 err.multipart_suggestion(
4437 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("instead, you are more likely to want to change {0} argument{1} to be borrowed{2}",
the, s, dotdotdot))
})format!(
4438 "instead, you are more likely to want to change {the} \
4439 argument{s} to be borrowed{dotdotdot}",
4440 ),
4441 sugg,
4442 Applicability::MaybeIncorrect,
4443 );
4444 "...or alternatively, you might want"
4445 } else if (lt.kind == MissingLifetimeKind::Ampersand
4446 || lt.kind == MissingLifetimeKind::Underscore)
4447 && let Some((kind, _span)) = self.diag_metadata.current_function
4448 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
4449 && let ast::FnRetTy::Ty(ret_ty) = &sig.decl.output
4450 && !sig.decl.inputs.is_empty()
4451 && let arg_refs = sig
4452 .decl
4453 .inputs
4454 .iter()
4455 .filter_map(|param| match ¶m.ty.kind {
4456 TyKind::ImplTrait(_, bounds) => Some(bounds),
4457 _ => None,
4458 })
4459 .flat_map(|bounds| bounds.into_iter())
4460 .collect::<Vec<_>>()
4461 && !arg_refs.is_empty()
4462 {
4463 let mut lt_finder =
4469 LifetimeFinder { lifetime: lt.span, found: None, seen: ::alloc::vec::Vec::new()vec![] };
4470 for bound in arg_refs {
4471 if let ast::GenericBound::Trait(trait_ref) = bound {
4472 lt_finder.visit_trait_ref(&trait_ref.trait_ref);
4473 }
4474 }
4475 lt_finder.visit_ty(ret_ty);
4476 let spans_suggs: Vec<_> = lt_finder
4477 .seen
4478 .iter()
4479 .filter_map(|ty| match &ty.kind {
4480 TyKind::Ref(_, mut_ty) => {
4481 let span = ty.span.with_hi(mut_ty.ty.span.lo());
4482 Some((span, "&'a ".to_string()))
4483 }
4484 _ => None,
4485 })
4486 .collect();
4487 self.suggest_introducing_lifetime(
4488 err,
4489 None,
4490 |err, higher_ranked, span, message, intro_sugg, _| {
4491 err.multipart_suggestion(
4492 message,
4493 std::iter::once((span, intro_sugg))
4494 .chain(spans_suggs.clone())
4495 .collect(),
4496 Applicability::MaybeIncorrect,
4497 );
4498 higher_ranked
4499 },
4500 );
4501 "alternatively, you might want"
4502 } else {
4503 "instead, you are more likely to want"
4504 };
4505 let mut owned_sugg = lt.kind == MissingLifetimeKind::Ampersand;
4506 let mut sugg_slice_to_vec_or_string = false;
4507 let mut sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(lt.span, String::new())]))vec![(lt.span, String::new())];
4508 if let Some((kind, _span)) = self.diag_metadata.current_function
4509 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
4510 {
4511 let mut lt_finder =
4512 LifetimeFinder { lifetime: lt.span, found: None, seen: ::alloc::vec::Vec::new()vec![] };
4513 for param in &sig.decl.inputs {
4514 lt_finder.visit_ty(¶m.ty);
4515 }
4516 if let ast::FnRetTy::Ty(ret_ty) = &sig.decl.output {
4517 lt_finder.visit_ty(ret_ty);
4518 let mut ret_lt_finder =
4519 LifetimeFinder { lifetime: lt.span, found: None, seen: ::alloc::vec::Vec::new()vec![] };
4520 ret_lt_finder.visit_ty(ret_ty);
4521 if let [Ty { span, kind: TyKind::Ref(_, mut_ty), .. }] =
4522 &ret_lt_finder.seen[..]
4523 {
4524 sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.with_hi(mut_ty.ty.span.lo()), String::new())]))vec![(span.with_hi(mut_ty.ty.span.lo()), String::new())];
4530 owned_sugg = true;
4531 }
4532 }
4533 if let Some(ty) = lt_finder.found {
4534 if let TyKind::Path(None, path) = &ty.kind {
4535 let path: Vec<_> = Segment::from_path(path);
4537 match self.resolve_path(
4538 &path,
4539 Some(TypeNS),
4540 None,
4541 PathSource::Type,
4542 ) {
4543 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
4544 match module.res() {
4545 Some(Res::PrimTy(PrimTy::Str)) => {
4546 sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(lt.span.with_hi(ty.span.hi()), "String".to_string())]))vec![(
4548 lt.span.with_hi(ty.span.hi()),
4549 "String".to_string(),
4550 )];
4551 sugg_slice_to_vec_or_string = true;
4552 }
4553 Some(Res::PrimTy(..)) => {}
4554 Some(Res::Def(
4555 DefKind::Struct
4556 | DefKind::Union
4557 | DefKind::Enum
4558 | DefKind::ForeignTy
4559 | DefKind::AssocTy
4560 | DefKind::OpaqueTy
4561 | DefKind::TyParam,
4562 _,
4563 )) => {}
4564 _ => {
4565 owned_sugg = false;
4567 }
4568 }
4569 }
4570 PathResult::NonModule(res) => {
4571 match res.base_res() {
4572 Res::PrimTy(PrimTy::Str) => {
4573 sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(lt.span.with_hi(ty.span.hi()), "String".to_string())]))vec![(
4575 lt.span.with_hi(ty.span.hi()),
4576 "String".to_string(),
4577 )];
4578 sugg_slice_to_vec_or_string = true;
4579 }
4580 Res::PrimTy(..) => {}
4581 Res::Def(
4582 DefKind::Struct
4583 | DefKind::Union
4584 | DefKind::Enum
4585 | DefKind::ForeignTy
4586 | DefKind::AssocTy
4587 | DefKind::OpaqueTy
4588 | DefKind::TyParam,
4589 _,
4590 ) => {}
4591 _ => {
4592 owned_sugg = false;
4594 }
4595 }
4596 }
4597 _ => {
4598 owned_sugg = false;
4600 }
4601 }
4602 }
4603 if let TyKind::Slice(inner_ty) = &ty.kind {
4604 sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(lt.span.with_hi(inner_ty.span.lo()), "Vec<".to_string()),
(ty.span.with_lo(inner_ty.span.hi()), ">".to_string())]))vec![
4606 (lt.span.with_hi(inner_ty.span.lo()), "Vec<".to_string()),
4607 (ty.span.with_lo(inner_ty.span.hi()), ">".to_string()),
4608 ];
4609 sugg_slice_to_vec_or_string = true;
4610 }
4611 }
4612 }
4613 if owned_sugg {
4614 if let Some(span) =
4616 self.find_ref_prefix_span_for_owned_suggestion(lt.span)
4617 && !sugg_slice_to_vec_or_string
4618 {
4619 sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span, String::new())]))vec![(span, String::new())];
4620 }
4621 err.multipart_suggestion(
4622 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} to return an owned value",
pre))
})format!("{pre} to return an owned value"),
4623 sugg,
4624 Applicability::MaybeIncorrect,
4625 );
4626 }
4627 }
4628 }
4629 }
4630 _ => {
4631 let lifetime_spans: Vec<_> =
4632 in_scope_lifetimes.iter().map(|(ident, _)| ident.span).collect();
4633 err.span_note(lifetime_spans, "these named lifetimes are available to use");
4634
4635 if spans_suggs.len() > 0 {
4636 err.multipart_suggestion(
4639 "consider using one of the available lifetimes here",
4640 spans_suggs,
4641 Applicability::HasPlaceholders,
4642 );
4643 }
4644 }
4645 }
4646 }
4647
4648 fn find_ref_prefix_span_for_owned_suggestion(&self, lifetime: Span) -> Option<Span> {
4649 let mut finder = RefPrefixSpanFinder { lifetime, span: None };
4650 if let Some(item) = self.diag_metadata.current_item {
4651 finder.visit_item(item);
4652 } else if let Some((kind, _span)) = self.diag_metadata.current_function
4653 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
4654 {
4655 for param in &sig.decl.inputs {
4656 finder.visit_ty(¶m.ty);
4657 }
4658 if let ast::FnRetTy::Ty(ret_ty) = &sig.decl.output {
4659 finder.visit_ty(ret_ty);
4660 }
4661 }
4662 finder.span
4663 }
4664}
4665
4666fn mk_where_bound_predicate(
4667 path: &Path,
4668 poly_trait_ref: &ast::PolyTraitRef,
4669 ty: &Ty,
4670) -> Option<ast::WhereBoundPredicate> {
4671 let modified_segments = {
4672 let mut segments = path.segments.clone();
4673 let [preceding @ .., second_last, last] = segments.as_mut_slice() else {
4674 return None;
4675 };
4676 let mut segments = ThinVec::from(preceding);
4677
4678 let added_constraint = ast::AngleBracketedArg::Constraint(ast::AssocItemConstraint {
4679 id: DUMMY_NODE_ID,
4680 ident: last.ident,
4681 gen_args: None,
4682 kind: ast::AssocItemConstraintKind::Equality {
4683 term: ast::Term::Ty(Box::new(ast::Ty {
4684 kind: ast::TyKind::Path(None, poly_trait_ref.trait_ref.path.clone()),
4685 id: DUMMY_NODE_ID,
4686 span: DUMMY_SP,
4687 })),
4688 },
4689 span: DUMMY_SP,
4690 });
4691
4692 match second_last.args.as_deref_mut() {
4693 Some(ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs { args, .. })) => {
4694 args.push(added_constraint);
4695 }
4696 Some(_) => return None,
4697 None => {
4698 second_last.args =
4699 Some(Box::new(ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs {
4700 args: ThinVec::from([added_constraint]),
4701 span: DUMMY_SP,
4702 })));
4703 }
4704 }
4705
4706 segments.push(second_last.clone());
4707 segments
4708 };
4709
4710 let new_where_bound_predicate = ast::WhereBoundPredicate {
4711 bound_generic_params: ThinVec::new(),
4712 bounded_ty: Box::new(ty.clone()),
4713 bounds: {
let len = [()].len();
let mut vec = ::thin_vec::ThinVec::with_capacity(len);
vec.push(ast::GenericBound::Trait(ast::PolyTraitRef {
bound_generic_params: ThinVec::new(),
modifiers: ast::TraitBoundModifiers::NONE,
trait_ref: ast::TraitRef {
path: ast::Path {
segments: modified_segments,
span: DUMMY_SP,
},
ref_id: DUMMY_NODE_ID,
},
span: DUMMY_SP,
parens: ast::Parens::No,
}));
vec
}thin_vec![ast::GenericBound::Trait(ast::PolyTraitRef {
4714 bound_generic_params: ThinVec::new(),
4715 modifiers: ast::TraitBoundModifiers::NONE,
4716 trait_ref: ast::TraitRef {
4717 path: ast::Path { segments: modified_segments, span: DUMMY_SP },
4718 ref_id: DUMMY_NODE_ID,
4719 },
4720 span: DUMMY_SP,
4721 parens: ast::Parens::No,
4722 })],
4723 };
4724
4725 Some(new_where_bound_predicate)
4726}
4727
4728pub(super) fn signal_lifetime_shadowing(
4730 sess: &Session,
4731 orig: Ident,
4732 shadower: Ident,
4733) -> ErrorGuaranteed {
4734 {
sess.dcx().struct_span_err(shadower.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("lifetime name `{0}` shadows a lifetime name that is already in scope",
orig.name))
})).with_code(E0496)
}struct_span_code_err!(
4735 sess.dcx(),
4736 shadower.span,
4737 E0496,
4738 "lifetime name `{}` shadows a lifetime name that is already in scope",
4739 orig.name,
4740 )
4741 .with_span_label(orig.span, "first declared here")
4742 .with_span_label(shadower.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("lifetime `{0}` already in scope",
orig.name))
})format!("lifetime `{}` already in scope", orig.name))
4743 .emit()
4744}
4745
4746struct LifetimeFinder<'ast> {
4747 lifetime: Span,
4748 found: Option<&'ast Ty>,
4749 seen: Vec<&'ast Ty>,
4750}
4751
4752impl<'ast> Visitor<'ast> for LifetimeFinder<'ast> {
4753 fn visit_ty(&mut self, t: &'ast Ty) {
4754 if let TyKind::Ref(_, mut_ty) | TyKind::PinnedRef(_, mut_ty) = &t.kind {
4755 self.seen.push(t);
4756 if t.span.lo() == self.lifetime.lo() {
4757 self.found = Some(&mut_ty.ty);
4758 }
4759 }
4760 walk_ty(self, t)
4761 }
4762}
4763
4764struct RefPrefixSpanFinder {
4765 lifetime: Span,
4766 span: Option<Span>,
4767}
4768
4769impl<'ast> Visitor<'ast> for RefPrefixSpanFinder {
4770 fn visit_ty(&mut self, t: &'ast Ty) {
4771 if self.span.is_some() {
4772 return;
4773 }
4774 if let TyKind::Ref(_, mut_ty) | TyKind::PinnedRef(_, mut_ty) = &t.kind
4775 && t.span.lo() == self.lifetime.lo()
4776 {
4777 self.span = Some(t.span.with_hi(mut_ty.ty.span.lo()));
4778 return;
4779 }
4780 walk_ty(self, t);
4781 }
4782}
4783
4784pub(super) fn signal_label_shadowing(sess: &Session, orig: Span, shadower: Ident) {
4787 let name = shadower.name;
4788 let shadower = shadower.span;
4789 sess.dcx()
4790 .struct_span_warn(
4791 shadower,
4792 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("label name `{0}` shadows a label name that is already in scope",
name))
})format!("label name `{name}` shadows a label name that is already in scope"),
4793 )
4794 .with_span_label(orig, "first declared here")
4795 .with_span_label(shadower, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("label `{0}` already in scope",
name))
})format!("label `{name}` already in scope"))
4796 .emit();
4797}
4798
4799struct ParentPathVisitor<'a> {
4800 target: Ident,
4801 parent: Option<&'a PathSegment>,
4802 stack: Vec<&'a Ty>,
4803}
4804
4805impl<'a> ParentPathVisitor<'a> {
4806 fn new(self_ty: &'a Ty, target: Ident) -> Self {
4807 let mut v = ParentPathVisitor { target, parent: None, stack: Vec::new() };
4808
4809 v.visit_ty(self_ty);
4810 v
4811 }
4812}
4813
4814impl<'a> Visitor<'a> for ParentPathVisitor<'a> {
4815 fn visit_ty(&mut self, ty: &'a Ty) {
4816 if self.parent.is_some() {
4817 return;
4818 }
4819
4820 self.stack.push(ty);
4822
4823 if let TyKind::Path(_, path) = &ty.kind
4824 && let [segment] = path.segments.as_slice()
4826 && segment.ident == self.target
4827 && let [.., parent_ty, _ty] = self.stack.as_slice()
4829 && let TyKind::Path(_, parent_path) = &parent_ty.kind
4830 {
4831 self.parent = parent_path.segments.first();
4832 }
4833
4834 walk_ty(self, ty);
4835
4836 self.stack.pop();
4837 }
4838}