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, DesugaringKind, 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(Span),
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/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_resolve/src/late/diagnostics.rs:416",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/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/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_resolve/src/late/diagnostics.rs:417",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/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(..)
608 | DefKind::AssocFn
609 | DefKind::Const { .. }
610 | DefKind::AssocConst { .. },
611 _,
612 )
613 | Res::SelfCtor(_)
614 | Res::PrimTy(_)
615 | Res::Local(_) => true,
616 _ => false,
617 }
618 }
619
620 pub(crate) fn smart_resolve_partial_mod_path_errors(
628 &mut self,
629 prefix_path: &[Segment],
630 following_seg: Option<&Segment>,
631 ) -> Vec<ImportSuggestion> {
632 if let Some(segment) = prefix_path.last()
633 && let Some(following_seg) = following_seg
634 {
635 let candidates = self.r.lookup_import_candidates(
636 segment.ident,
637 Namespace::TypeNS,
638 &self.parent_scope,
639 &|res: Res| #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Mod, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Mod, _)),
640 );
641 candidates
643 .into_iter()
644 .filter(|candidate| {
645 if let Some(def_id) = candidate.did
646 && let Some(module) = self.r.get_module(def_id)
647 {
648 Some(def_id) != self.parent_scope.module.opt_def_id()
649 && self
650 .r
651 .resolutions(module)
652 .iter()
653 .any(|(key, _r)| key.ident.name == following_seg.ident.name)
654 } else {
655 false
656 }
657 })
658 .collect::<Vec<_>>()
659 } else {
660 Vec::new()
661 }
662 }
663
664 {}
#[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/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(666u32),
::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/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_resolve/src/late/diagnostics.rs:676",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(676u32),
::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(ref sugg) = base_error.suggestion {
err.span_suggestion_verbose(sugg.0, sugg.1, &sugg.2,
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")]
667 pub(crate) fn smart_resolve_report_errors(
668 &mut self,
669 path: &[Segment],
670 following_seg: Option<&Segment>,
671 span: Span,
672 source: PathSource<'_, 'ast, 'ra>,
673 res: Option<Res>,
674 qself: Option<&QSelf>,
675 ) -> (Diag<'tcx>, Vec<ImportSuggestion>) {
676 debug!(?res, ?source);
677 let cross_namespace_res = res.filter(|res| !res.matches_ns(source.namespace()));
678 let could_be_expr = res.is_some_and(|res| self.could_be_expr(res, span));
679 let base_error = self.make_base_error(
680 path,
681 span,
682 source,
683 if cross_namespace_res.is_some() { None } else { res },
684 could_be_expr,
685 );
686
687 let code = source.error_code(res.is_some());
688 let mut err = self.r.dcx().struct_span_err(base_error.span, base_error.msg.clone());
689 err.code(code);
690
691 if let Some(res) = cross_namespace_res {
692 err.note(format!(
693 "{} {} named `{}` exists in another namespace",
694 res.article(),
695 res.descr(),
696 Segment::names_to_string(path),
697 ));
698 }
699
700 if let Some(within_macro_span) =
703 base_error.span.within_macro(span, self.r.tcx.sess.source_map())
704 {
705 err.span_label(within_macro_span, "due to this macro variable");
706 }
707
708 self.detect_missing_binding_available_from_pattern(&mut err, path, following_seg);
709 self.suggest_at_operator_in_slice_pat_with_range(&mut err, path);
710 self.suggest_range_struct_destructuring(&mut err, path, source);
711 self.suggest_swapping_misplaced_self_ty_and_trait(&mut err, source, res, base_error.span);
712
713 if let Some((span, label)) = base_error.span_label {
714 err.span_label(span, label);
715 }
716 for note in &base_error.notes {
717 err.note(note.clone());
718 }
719
720 if let Some(ref sugg) = base_error.suggestion {
721 err.span_suggestion_verbose(sugg.0, sugg.1, &sugg.2, Applicability::MaybeIncorrect);
722 }
723
724 self.suggest_changing_type_to_const_param(&mut err, res, source, path, following_seg, span);
725 self.explain_functions_in_pattern(&mut err, res, source);
726
727 if self.suggest_pattern_match_with_let(&mut err, source, span) {
728 err.span_label(base_error.span, base_error.fallback_label);
730 return (err, Vec::new());
731 }
732
733 self.suggest_self_or_self_ref(&mut err, path, span);
734 self.detect_assoc_type_constraint_meant_as_path(&mut err, &base_error);
735 self.detect_rtn_with_fully_qualified_path(
736 &mut err,
737 path,
738 following_seg,
739 span,
740 source,
741 res,
742 qself,
743 );
744 if self.suggest_self_ty(&mut err, source, path, span)
745 || self.suggest_self_value(&mut err, source, path, span)
746 {
747 return (err, Vec::new());
748 }
749
750 if let Some((did, item)) = self.lookup_doc_alias_name(path, source.namespace()) {
751 let item_name = item.name;
752 let suggestion_name = self.r.tcx.item_name(did);
753 err.span_suggestion(
754 item.span,
755 format!("`{suggestion_name}` has a name defined in the doc alias attribute as `{item_name}`"),
756 suggestion_name,
757 Applicability::MaybeIncorrect
758 );
759
760 return (err, Vec::new());
761 };
762
763 let (found, suggested_candidates, mut candidates) = self.try_lookup_name_relaxed(
764 &mut err,
765 source,
766 path,
767 following_seg,
768 span,
769 res,
770 &base_error,
771 );
772 if found {
773 return (err, candidates);
774 }
775
776 if self.suggest_shadowed(&mut err, source, path, following_seg, span) {
777 candidates.clear();
779 }
780
781 let mut fallback = self.suggest_trait_and_bounds(&mut err, source, res, span, &base_error);
782 fallback |= self.suggest_typo(
783 &mut err,
784 source,
785 path,
786 following_seg,
787 span,
788 &base_error,
789 suggested_candidates,
790 );
791
792 if fallback {
793 err.span_label(base_error.span, base_error.fallback_label);
795 }
796 self.err_code_special_cases(&mut err, source, path, span);
797
798 let module = base_error.module.unwrap_or_else(|| CRATE_DEF_ID.to_def_id());
799 self.r.find_cfg_stripped(&mut err, &path.last().unwrap().ident.name, module);
800
801 (err, candidates)
802 }
803
804 fn detect_rtn_with_fully_qualified_path(
805 &self,
806 err: &mut Diag<'_>,
807 path: &[Segment],
808 following_seg: Option<&Segment>,
809 span: Span,
810 source: PathSource<'_, '_, '_>,
811 res: Option<Res>,
812 qself: Option<&QSelf>,
813 ) {
814 if let Some(Res::Def(DefKind::AssocFn, _)) = res
815 && let PathSource::TraitItem(TypeNS, _) = source
816 && let None = following_seg
817 && let Some(qself) = qself
818 && let TyKind::Path(None, ty_path) = &qself.ty.kind
819 && ty_path.segments.len() == 1
820 && self.diag_metadata.current_where_predicate.is_some()
821 {
822 err.span_suggestion_verbose(
823 span,
824 "you might have meant to use the return type notation syntax",
825 ::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),
826 Applicability::MaybeIncorrect,
827 );
828 }
829 }
830
831 fn detect_assoc_type_constraint_meant_as_path(
832 &self,
833 err: &mut Diag<'_>,
834 base_error: &BaseError,
835 ) {
836 let Some(ty) = self.diag_metadata.current_type_path else {
837 return;
838 };
839 let TyKind::Path(_, path) = &ty.kind else {
840 return;
841 };
842 for segment in &path.segments {
843 let Some(params) = &segment.args else {
844 continue;
845 };
846 let ast::GenericArgs::AngleBracketed(params) = params.deref() else {
847 continue;
848 };
849 for param in ¶ms.args {
850 let ast::AngleBracketedArg::Constraint(constraint) = param else {
851 continue;
852 };
853 let ast::AssocItemConstraintKind::Bound { bounds } = &constraint.kind else {
854 continue;
855 };
856 for bound in bounds {
857 let ast::GenericBound::Trait(trait_ref) = bound else {
858 continue;
859 };
860 if trait_ref.modifiers == ast::TraitBoundModifiers::NONE
861 && base_error.span == trait_ref.span
862 {
863 err.span_suggestion_verbose(
864 constraint.ident.span.between(trait_ref.span),
865 "you might have meant to write a path instead of an associated type bound",
866 "::",
867 Applicability::MachineApplicable,
868 );
869 }
870 }
871 }
872 }
873 }
874
875 fn suggest_self_or_self_ref(&mut self, err: &mut Diag<'_>, path: &[Segment], span: Span) {
876 if !self.self_type_is_available() {
877 return;
878 }
879 let Some(path_last_segment) = path.last() else { return };
880 let item_str = path_last_segment.ident;
881 if ["this", "my"].contains(&item_str.as_str()) {
883 err.span_suggestion_short(
884 span,
885 "you might have meant to use `self` here instead",
886 "self",
887 Applicability::MaybeIncorrect,
888 );
889 if !self.self_value_is_available(path[0].ident.span) {
890 if let Some((FnKind::Fn(_, _, ast::Fn { sig, .. }), fn_span)) =
891 &self.diag_metadata.current_function
892 {
893 let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) {
894 (param.span.shrink_to_lo(), "&self, ")
895 } else {
896 (
897 self.r
898 .tcx
899 .sess
900 .source_map()
901 .span_through_char(*fn_span, '(')
902 .shrink_to_hi(),
903 "&self",
904 )
905 };
906 err.span_suggestion_verbose(
907 span,
908 "if you meant to use `self`, you are also missing a `self` receiver \
909 argument",
910 sugg,
911 Applicability::MaybeIncorrect,
912 );
913 }
914 }
915 }
916 }
917
918 fn try_lookup_name_relaxed(
919 &mut self,
920 err: &mut Diag<'_>,
921 source: PathSource<'_, '_, '_>,
922 path: &[Segment],
923 following_seg: Option<&Segment>,
924 span: Span,
925 res: Option<Res>,
926 base_error: &BaseError,
927 ) -> (bool, FxHashSet<String>, Vec<ImportSuggestion>) {
928 let span = match following_seg {
929 Some(_) if path[0].ident.span.eq_ctxt(path[path.len() - 1].ident.span) => {
930 path[0].ident.span.to(path[path.len() - 1].ident.span)
933 }
934 _ => span,
935 };
936 let mut suggested_candidates = FxHashSet::default();
937 let ident = path.last().unwrap().ident;
939 let is_expected = &|res| source.is_expected(res);
940 let ns = source.namespace();
941 let is_enum_variant = &|res| #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Variant, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Variant, _));
942 let path_str = Segment::names_to_string(path);
943 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
944 let mut candidates = self
945 .r
946 .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
947 .into_iter()
948 .filter(|ImportSuggestion { did, .. }| {
949 match (did, res.and_then(|res| res.opt_def_id())) {
950 (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
951 _ => true,
952 }
953 })
954 .collect::<Vec<_>>();
955 let intrinsic_candidates: Vec<_> = candidates
958 .extract_if(.., |sugg| {
959 let path = path_names_to_string(&sugg.path);
960 path.starts_with("core::intrinsics::") || path.starts_with("std::intrinsics::")
961 })
962 .collect();
963 if candidates.is_empty() {
964 candidates = intrinsic_candidates;
966 }
967 let crate_def_id = CRATE_DEF_ID.to_def_id();
968 if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
969 let mut enum_candidates: Vec<_> = self
970 .r
971 .lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant)
972 .into_iter()
973 .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
974 .filter(|(_, enum_ty_path)| !enum_ty_path.starts_with("std::prelude::"))
975 .collect();
976 if !enum_candidates.is_empty() {
977 enum_candidates.sort();
978
979 let preamble = if res.is_none() {
982 let others = match enum_candidates.len() {
983 1 => String::new(),
984 2 => " and 1 other".to_owned(),
985 n => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" and {0} others", n))
})format!(" and {n} others"),
986 };
987 ::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)
988 } else {
989 String::new()
990 };
991 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");
992
993 suggested_candidates.extend(
994 enum_candidates
995 .iter()
996 .map(|(_variant_path, enum_ty_path)| enum_ty_path.clone()),
997 );
998 err.span_suggestions(
999 span,
1000 msg,
1001 enum_candidates.into_iter().map(|(_variant_path, enum_ty_path)| enum_ty_path),
1002 Applicability::MachineApplicable,
1003 );
1004 }
1005 }
1006
1007 let typo_sugg = self
1009 .lookup_typo_candidate(path, following_seg, source.namespace(), is_expected)
1010 .to_opt_suggestion()
1011 .filter(|sugg| !suggested_candidates.contains(sugg.candidate.as_str()));
1012 if let [segment] = path
1013 && !#[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::Delegation => true,
_ => false,
}matches!(source, PathSource::Delegation)
1014 && self.self_type_is_available()
1015 {
1016 if let Some(candidate) =
1017 self.lookup_assoc_candidate(ident, ns, is_expected, source.is_call())
1018 {
1019 let self_is_available = self.self_value_is_available(segment.ident.span);
1020 let pre = match source {
1023 PathSource::Expr(Some(Expr { kind: ExprKind::Struct(expr), .. }))
1024 if expr
1025 .fields
1026 .iter()
1027 .any(|f| f.ident == segment.ident && f.is_shorthand) =>
1028 {
1029 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", path_str))
})format!("{path_str}: ")
1030 }
1031 _ => String::new(),
1032 };
1033 match candidate {
1034 AssocSuggestion::Field(field_span) => {
1035 if self_is_available {
1036 let source_map = self.r.tcx.sess.source_map();
1037 let field_is_format_named_arg = #[allow(non_exhaustive_omitted_patterns)] match span.desugaring_kind() {
Some(DesugaringKind::FormatLiteral { .. }) => true,
_ => false,
}matches!(
1038 span.desugaring_kind(),
1039 Some(DesugaringKind::FormatLiteral { .. })
1040 ) && source_map
1041 .span_to_source(span, |s, start, _| {
1042 Ok(s.get(start.saturating_sub(1)..start) == Some("{"))
1043 })
1044 .unwrap_or(false);
1045 if field_is_format_named_arg {
1046 err.help(
1047 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might have meant to use the available field in a format string: `\"{{}}\", self.{0}`",
segment.ident.name))
})format!("you might have meant to use the available field in a format string: `\"{{}}\", self.{}`", segment.ident.name),
1048 );
1049 } else {
1050 err.span_suggestion_verbose(
1051 span.shrink_to_lo(),
1052 "you might have meant to use the available field",
1053 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}self.", pre))
})format!("{pre}self."),
1054 Applicability::MaybeIncorrect,
1055 );
1056 }
1057 } else {
1058 err.span_label(field_span, "a field by that name exists in `Self`");
1059 }
1060 }
1061 AssocSuggestion::MethodWithSelf { called } if self_is_available => {
1062 let msg = if called {
1063 "you might have meant to call the method"
1064 } else {
1065 "you might have meant to refer to the method"
1066 };
1067 err.span_suggestion_verbose(
1068 span.shrink_to_lo(),
1069 msg,
1070 "self.",
1071 Applicability::MachineApplicable,
1072 );
1073 }
1074 AssocSuggestion::MethodWithSelf { .. }
1075 | AssocSuggestion::AssocFn { .. }
1076 | AssocSuggestion::AssocConst
1077 | AssocSuggestion::AssocType => {
1078 err.span_suggestion_verbose(
1079 span.shrink_to_lo(),
1080 ::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()),
1081 "Self::",
1082 Applicability::MachineApplicable,
1083 );
1084 }
1085 }
1086 self.r.add_typo_suggestion(err, typo_sugg, ident_span);
1087 return (true, suggested_candidates, candidates);
1088 }
1089
1090 if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
1092 let mut args_snippet = String::new();
1093 if let Some(args_span) = args_span
1094 && let Ok(snippet) = self.r.tcx.sess.source_map().span_to_snippet(args_span)
1095 {
1096 args_snippet = snippet;
1097 }
1098
1099 if let Some(Res::Def(DefKind::Struct, def_id)) = res {
1100 if let Some(ctor) = self.r.struct_ctor(def_id)
1101 && ctor.has_private_fields(self.parent_scope.module, self.r)
1102 {
1103 if #[allow(non_exhaustive_omitted_patterns)] match ctor.res {
Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), _) => true,
_ => false,
}matches!(
1104 ctor.res,
1105 Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), _)
1106 ) {
1107 self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
1108 }
1109 err.note("constructor is not visible here due to private fields");
1110 }
1111 } else {
1112 err.span_suggestion(
1113 call_span,
1114 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("try calling `{0}` as a method",
ident))
})format!("try calling `{ident}` as a method"),
1115 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("self.{0}({1})", path_str,
args_snippet))
})format!("self.{path_str}({args_snippet})"),
1116 Applicability::MachineApplicable,
1117 );
1118 }
1119
1120 return (true, suggested_candidates, candidates);
1121 }
1122 }
1123
1124 if let Some(res) = res {
1126 if self.smart_resolve_context_dependent_help(
1127 err,
1128 span,
1129 source,
1130 path,
1131 res,
1132 &path_str,
1133 &base_error.fallback_label,
1134 ) {
1135 self.r.add_typo_suggestion(err, typo_sugg, ident_span);
1137 return (true, suggested_candidates, candidates);
1138 }
1139 }
1140
1141 if let Some(rib) = &self.last_block_rib {
1143 for (ident, &res) in &rib.bindings {
1144 if let Res::Local(_) = res
1145 && path.len() == 1
1146 && ident.span.eq_ctxt(path[0].ident.span)
1147 && ident.name == path[0].ident.name
1148 {
1149 err.span_help(
1150 ident.span,
1151 ::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"),
1152 );
1153 return (true, suggested_candidates, candidates);
1154 }
1155 }
1156 }
1157
1158 if candidates.is_empty() {
1159 candidates = self.smart_resolve_partial_mod_path_errors(path, following_seg);
1160 }
1161
1162 (false, suggested_candidates, candidates)
1163 }
1164
1165 fn lookup_doc_alias_name(&mut self, path: &[Segment], ns: Namespace) -> Option<(DefId, Ident)> {
1166 let find_doc_alias_name = |r: &mut Resolver<'ra, '_>, m: Module<'ra>, item_name: Symbol| {
1167 for resolution in r.resolutions(m).values() {
1168 let Some(did) =
1169 resolution.borrow(r).best_decl().and_then(|binding| binding.res().opt_def_id())
1170 else {
1171 continue;
1172 };
1173 if did.is_local() {
1174 continue;
1178 }
1179 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)
1180 && d.aliases.contains_key(&item_name)
1181 {
1182 return Some(did);
1183 }
1184 }
1185 None
1186 };
1187
1188 if path.len() == 1 {
1189 for rib in self.ribs[ns].iter().rev() {
1190 let item = path[0].ident;
1191 if let RibKind::Module(module) | RibKind::Block(Some(module)) = rib.kind
1192 && let Some(did) = find_doc_alias_name(self.r, module.to_module(), item.name)
1193 {
1194 return Some((did, item));
1195 }
1196 }
1197 } else {
1198 for (idx, seg) in path.iter().enumerate().rev().skip(1) {
1207 let Some(id) = seg.id else {
1208 continue;
1209 };
1210 let Some(res) = self.r.partial_res_map.get(&id) else {
1211 continue;
1212 };
1213 if let Res::Def(DefKind::Mod, module) = res.expect_full_res()
1214 && let module = self.r.expect_module(module)
1215 && let item = path[idx + 1].ident
1216 && let Some(did) = find_doc_alias_name(self.r, module, item.name)
1217 {
1218 return Some((did, item));
1219 }
1220 break;
1221 }
1222 }
1223 None
1224 }
1225
1226 fn suggest_trait_and_bounds(
1227 &self,
1228 err: &mut Diag<'_>,
1229 source: PathSource<'_, '_, '_>,
1230 res: Option<Res>,
1231 span: Span,
1232 base_error: &BaseError,
1233 ) -> bool {
1234 let is_macro =
1235 base_error.span.from_expansion() && base_error.span.desugaring_kind().is_none();
1236 let mut fallback = false;
1237
1238 if let (
1239 PathSource::Trait(AliasPossibility::Maybe),
1240 Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)),
1241 false,
1242 ) = (source, res, is_macro)
1243 && let Some(bounds @ [first_bound, .., last_bound]) =
1244 self.diag_metadata.current_trait_object
1245 {
1246 fallback = true;
1247 let spans: Vec<Span> = bounds
1248 .iter()
1249 .map(|bound| bound.span())
1250 .filter(|&sp| sp != base_error.span)
1251 .collect();
1252
1253 let start_span = first_bound.span();
1254 let end_span = last_bound.span();
1256 let last_bound_span = spans.last().cloned().unwrap();
1258 let mut multi_span: MultiSpan = spans.clone().into();
1259 for sp in spans {
1260 let msg = if sp == last_bound_span {
1261 ::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!(
1262 "...because of {these} bound{s}",
1263 these = pluralize!("this", bounds.len() - 1),
1264 s = pluralize!(bounds.len() - 1),
1265 )
1266 } else {
1267 String::new()
1268 };
1269 multi_span.push_span_label(sp, msg);
1270 }
1271 multi_span.push_span_label(base_error.span, "expected this type to be a trait...");
1272 err.span_help(
1273 multi_span,
1274 "`+` is used to constrain a \"trait object\" type with lifetimes or \
1275 auto-traits; structs and enums can't be bound in that way",
1276 );
1277 if bounds.iter().all(|bound| match bound {
1278 ast::GenericBound::Outlives(_) | ast::GenericBound::Use(..) => true,
1279 ast::GenericBound::Trait(tr) => tr.span == base_error.span,
1280 }) {
1281 let mut sugg = ::alloc::vec::Vec::new()vec![];
1282 if base_error.span != start_span {
1283 sugg.push((start_span.until(base_error.span), String::new()));
1284 }
1285 if base_error.span != end_span {
1286 sugg.push((base_error.span.shrink_to_hi().to(end_span), String::new()));
1287 }
1288
1289 err.multipart_suggestion(
1290 "if you meant to use a type and not a trait here, remove the bounds",
1291 sugg,
1292 Applicability::MaybeIncorrect,
1293 );
1294 }
1295 }
1296
1297 fallback |= self.restrict_assoc_type_in_where_clause(span, err);
1298 fallback
1299 }
1300
1301 fn suggest_typo(
1302 &mut self,
1303 err: &mut Diag<'_>,
1304 source: PathSource<'_, 'ast, 'ra>,
1305 path: &[Segment],
1306 following_seg: Option<&Segment>,
1307 span: Span,
1308 base_error: &BaseError,
1309 suggested_candidates: FxHashSet<String>,
1310 ) -> bool {
1311 let is_expected = &|res| source.is_expected(res);
1312 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
1313
1314 if self.suggest_assoc_type_from_bounds(err, source, path, ident_span) {
1318 return false;
1319 }
1320
1321 let typo_sugg =
1322 self.lookup_typo_candidate(path, following_seg, source.namespace(), is_expected);
1323 let mut fallback = true;
1324 let typo_sugg = typo_sugg
1325 .to_opt_suggestion()
1326 .filter(|sugg| !suggested_candidates.contains(sugg.candidate.as_str()));
1327 self.r.add_typo_suggestion(err, typo_sugg, ident_span);
1328
1329 match self.diag_metadata.current_let_binding {
1330 Some((pat_sp, Some(ty_sp), None))
1331 if ty_sp.contains(base_error.span) && base_error.could_be_expr =>
1332 {
1333 err.span_suggestion_verbose(
1334 pat_sp.between(ty_sp),
1335 "use `=` if you meant to assign",
1336 " = ",
1337 Applicability::MaybeIncorrect,
1338 );
1339 }
1340 _ => {}
1341 }
1342
1343 let suggestion = self.get_single_associated_item(path, &source, is_expected);
1345 self.r.add_typo_suggestion(err, suggestion, ident_span);
1346
1347 if self.let_binding_suggestion(err, ident_span) {
1348 fallback = false;
1349 }
1350
1351 fallback
1352 }
1353
1354 fn suggest_shadowed(
1355 &mut self,
1356 err: &mut Diag<'_>,
1357 source: PathSource<'_, '_, '_>,
1358 path: &[Segment],
1359 following_seg: Option<&Segment>,
1360 span: Span,
1361 ) -> bool {
1362 let is_expected = &|res| source.is_expected(res);
1363 let typo_sugg =
1364 self.lookup_typo_candidate(path, following_seg, source.namespace(), is_expected);
1365 let is_in_same_file = &|sp1, sp2| {
1366 let source_map = self.r.tcx.sess.source_map();
1367 let file1 = source_map.span_to_filename(sp1);
1368 let file2 = source_map.span_to_filename(sp2);
1369 file1 == file2
1370 };
1371 if let TypoCandidate::Shadowed(res, Some(sugg_span)) = typo_sugg
1376 && res.opt_def_id().is_some_and(|id| id.is_local() || is_in_same_file(span, sugg_span))
1377 {
1378 err.span_label(
1379 sugg_span,
1380 ::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()),
1381 );
1382 return true;
1383 }
1384 false
1385 }
1386
1387 fn err_code_special_cases(
1388 &mut self,
1389 err: &mut Diag<'_>,
1390 source: PathSource<'_, '_, '_>,
1391 path: &[Segment],
1392 span: Span,
1393 ) {
1394 if let Some(err_code) = err.code {
1395 if err_code == E0425 {
1396 for label_rib in &self.label_ribs {
1397 for (label_ident, node_id) in &label_rib.bindings {
1398 let ident = path.last().unwrap().ident;
1399 if ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\'{0}", ident))
})format!("'{ident}") == label_ident.to_string() {
1400 err.span_label(label_ident.span, "a label with a similar name exists");
1401 if let PathSource::Expr(Some(Expr {
1402 kind: ExprKind::Break(None, Some(_)),
1403 ..
1404 })) = source
1405 {
1406 err.span_suggestion(
1407 span,
1408 "use the similarly named label",
1409 label_ident.name,
1410 Applicability::MaybeIncorrect,
1411 );
1412 self.diag_metadata.unused_labels.swap_remove(node_id);
1414 }
1415 }
1416 }
1417 }
1418
1419 self.suggest_ident_hidden_by_hygiene(err, path, span);
1420 if let Some(correct) = Self::likely_rust_type(path) {
1422 err.span_suggestion(
1423 span,
1424 "perhaps you intended to use this type",
1425 correct,
1426 Applicability::MaybeIncorrect,
1427 );
1428 }
1429 }
1430 }
1431 }
1432
1433 fn suggest_ident_hidden_by_hygiene(&self, err: &mut Diag<'_>, path: &[Segment], span: Span) {
1434 let [segment] = path else { return };
1435
1436 let ident = segment.ident;
1437 let callsite_span = span.source_callsite();
1438 for rib in self.ribs[ValueNS].iter().rev() {
1439 for (binding_ident, _) in &rib.bindings {
1440 if binding_ident.name == ident.name
1442 && !binding_ident.span.eq_ctxt(span)
1443 && !binding_ident.span.from_expansion()
1444 && binding_ident.span.lo() < callsite_span.lo()
1445 {
1446 err.span_help(
1447 binding_ident.span,
1448 "an identifier with the same name exists, but is not accessible due to macro hygiene",
1449 );
1450 return;
1451 }
1452
1453 if binding_ident.name == ident.name
1455 && binding_ident.span.from_expansion()
1456 && binding_ident.span.source_callsite().eq_ctxt(callsite_span)
1457 && binding_ident.span.source_callsite().lo() < callsite_span.lo()
1458 {
1459 err.span_help(
1460 binding_ident.span,
1461 "an identifier with the same name is defined here, but is not accessible due to macro hygiene",
1462 );
1463 return;
1464 }
1465 }
1466 }
1467 }
1468
1469 fn suggest_self_ty(
1471 &self,
1472 err: &mut Diag<'_>,
1473 source: PathSource<'_, '_, '_>,
1474 path: &[Segment],
1475 span: Span,
1476 ) -> bool {
1477 if !is_self_type(path, source.namespace()) {
1478 return false;
1479 }
1480 err.code(E0411);
1481 err.span_label(span, "`Self` is only available in impls, traits, and type definitions");
1482 if let Some(item) = self.diag_metadata.current_item
1483 && let Some(ident) = item.kind.ident()
1484 {
1485 err.span_label(
1486 ident.span,
1487 ::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()),
1488 );
1489 }
1490 true
1491 }
1492
1493 fn suggest_self_value(
1494 &mut self,
1495 err: &mut Diag<'_>,
1496 source: PathSource<'_, '_, '_>,
1497 path: &[Segment],
1498 span: Span,
1499 ) -> bool {
1500 if !is_self_value(path, source.namespace()) {
1501 return false;
1502 }
1503
1504 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_resolve/src/late/diagnostics.rs:1504",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(1504u32),
::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);
1505 err.code(E0424);
1506 err.span_label(
1507 span,
1508 match source {
1509 PathSource::Pat => {
1510 "`self` value is a keyword and may not be bound to variables or shadowed"
1511 }
1512 _ => "`self` value is a keyword only available in methods with a `self` parameter",
1513 },
1514 );
1515
1516 if #[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::Pat => true,
_ => false,
}matches!(source, PathSource::Pat) {
1519 return true;
1520 }
1521
1522 let is_assoc_fn = self.self_type_is_available();
1523 let self_from_macro = "a `self` parameter, but a macro invocation can only \
1524 access identifiers it receives from parameters";
1525 if let Some((fn_kind, fn_span)) = &self.diag_metadata.current_function {
1526 if fn_kind.decl().inputs.get(0).is_some_and(|p| p.is_self()) {
1531 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}"));
1532 } else {
1533 let doesnt = if is_assoc_fn {
1534 let (span, sugg) = fn_kind
1535 .decl()
1536 .inputs
1537 .get(0)
1538 .map(|p| (p.span.shrink_to_lo(), "&self, "))
1539 .unwrap_or_else(|| {
1540 let span = fn_kind
1543 .ident()
1544 .map_or(*fn_span, |ident| fn_span.with_lo(ident.span.hi()));
1545 (
1546 self.r
1547 .tcx
1548 .sess
1549 .source_map()
1550 .span_through_char(span, '(')
1551 .shrink_to_hi(),
1552 "&self",
1553 )
1554 });
1555 err.span_suggestion_verbose(
1556 span,
1557 "add a `self` receiver parameter to make the associated `fn` a method",
1558 sugg,
1559 Applicability::MaybeIncorrect,
1560 );
1561 "doesn't"
1562 } else {
1563 "can't"
1564 };
1565 if let Some(ident) = fn_kind.ident() {
1566 err.span_label(
1567 ident.span,
1568 ::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"),
1569 );
1570 }
1571 }
1572 } else if let Some(item) = self.diag_metadata.current_item {
1573 if #[allow(non_exhaustive_omitted_patterns)] match item.kind {
ItemKind::Delegation(..) => true,
_ => false,
}matches!(item.kind, ItemKind::Delegation(..)) {
1574 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}"));
1575 } else {
1576 let span = if let Some(ident) = item.kind.ident() { ident.span } else { item.span };
1577 err.span_label(
1578 span,
1579 ::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()),
1580 );
1581 }
1582 }
1583 true
1584 }
1585
1586 fn detect_missing_binding_available_from_pattern(
1587 &self,
1588 err: &mut Diag<'_>,
1589 path: &[Segment],
1590 following_seg: Option<&Segment>,
1591 ) {
1592 let [segment] = path else { return };
1593 let None = following_seg else { return };
1594 for rib in self.ribs[ValueNS].iter().rev() {
1595 let patterns_with_skipped_bindings =
1596 self.r.tcx.with_stable_hashing_context(|mut hcx| {
1597 rib.patterns_with_skipped_bindings.to_sorted(&mut hcx, true)
1598 });
1599 for (def_id, spans) in patterns_with_skipped_bindings {
1600 if let DefKind::Struct | DefKind::Variant = self.r.tcx.def_kind(*def_id)
1601 && let Some(fields) = self.r.field_idents(*def_id)
1602 {
1603 for field in fields {
1604 if field.name == segment.ident.name {
1605 if spans.iter().all(|(.., had_error)| had_error.is_err()) {
1606 let multispan: MultiSpan =
1609 spans.iter().map(|(s, ..)| *s).collect::<Vec<_>>().into();
1610 err.span_note(
1611 multispan,
1612 "this pattern had a recovered parse error which likely lost \
1613 the expected fields",
1614 );
1615 err.downgrade_to_delayed_bug();
1616 }
1617 let ty = self.r.tcx.item_name(*def_id);
1618 for (span, rest_span, _) in spans {
1619 err.span_label(
1620 *span,
1621 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this pattern doesn\'t include `{0}`, which is available in `{1}`",
field, ty))
})format!(
1622 "this pattern doesn't include `{field}`, which is \
1623 available in `{ty}`",
1624 ),
1625 );
1626 if let Some(rest_span) = rest_span {
1627 err.span_suggestion_verbose(
1628 *rest_span,
1629 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("include `{0}` in the pattern",
field))
})format!("include `{field}` in the pattern"),
1630 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, ..", field))
})format!("{field}, .."),
1631 Applicability::MaybeIncorrect,
1632 );
1633 }
1634 }
1635 }
1636 }
1637 }
1638 }
1639 }
1640 }
1641
1642 fn suggest_at_operator_in_slice_pat_with_range(&self, err: &mut Diag<'_>, path: &[Segment]) {
1643 let Some(pat) = self.diag_metadata.current_pat else { return };
1644 let (bound, side, range) = match &pat.kind {
1645 ast::PatKind::Range(Some(bound), None, range) => (bound, Side::Start, range),
1646 ast::PatKind::Range(None, Some(bound), range) => (bound, Side::End, range),
1647 _ => return,
1648 };
1649 if let ExprKind::Path(None, range_path) = &bound.kind
1650 && let [segment] = &range_path.segments[..]
1651 && let [s] = path
1652 && segment.ident == s.ident
1653 && segment.ident.span.eq_ctxt(range.span)
1654 {
1655 let (span, snippet) = match side {
1658 Side::Start => (segment.ident.span.between(range.span), " @ ".into()),
1659 Side::End => (range.span.to(segment.ident.span), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} @ ..", segment.ident))
})format!("{} @ ..", segment.ident)),
1660 };
1661 err.subdiagnostic(diagnostics::UnexpectedResUseAtOpInSlicePatWithRangeSugg {
1662 span,
1663 ident: segment.ident,
1664 snippet,
1665 });
1666 }
1667
1668 enum Side {
1669 Start,
1670 End,
1671 }
1672 }
1673
1674 fn suggest_range_struct_destructuring(
1675 &mut self,
1676 err: &mut Diag<'_>,
1677 path: &[Segment],
1678 source: PathSource<'_, '_, '_>,
1679 ) {
1680 if !#[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::Pat | PathSource::TupleStruct(..) | PathSource::Expr(..) =>
true,
_ => false,
}matches!(source, PathSource::Pat | PathSource::TupleStruct(..) | PathSource::Expr(..)) {
1681 return;
1682 }
1683
1684 let Some(pat) = self.diag_metadata.current_pat else { return };
1685 let ast::PatKind::Range(start, end, end_kind) = &pat.kind else { return };
1686
1687 let [segment] = path else { return };
1688 let failing_span = segment.ident.span;
1689
1690 let in_start = start.as_ref().is_some_and(|e| e.span.contains(failing_span));
1691 let in_end = end.as_ref().is_some_and(|e| e.span.contains(failing_span));
1692
1693 if !in_start && !in_end {
1694 return;
1695 }
1696
1697 let start_snippet =
1698 start.as_ref().and_then(|e| self.r.tcx.sess.source_map().span_to_snippet(e.span).ok());
1699 let end_snippet =
1700 end.as_ref().and_then(|e| self.r.tcx.sess.source_map().span_to_snippet(e.span).ok());
1701
1702 let field = |name: &str, val: String| {
1703 if val == name { val } else { ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: {1}", name, val))
})format!("{name}: {val}") }
1704 };
1705
1706 let mut resolve_short_name = |short: Symbol, full: &str| -> String {
1707 let ident = Ident::with_dummy_span(short);
1708 let path = Segment::from_path(&Path::from_ident(ident));
1709
1710 match self.resolve_path(&path, Some(TypeNS), None, PathSource::Type) {
1711 PathResult::NonModule(..) => short.to_string(),
1712 _ => full.to_string(),
1713 }
1714 };
1715 let (struct_path, fields) = match (start_snippet, end_snippet, &end_kind.node) {
1717 (Some(start), Some(end), ast::RangeEnd::Excluded) => (
1718 resolve_short_name(sym::Range, "std::ops::Range"),
1719 ::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)],
1720 ),
1721 (Some(start), Some(end), ast::RangeEnd::Included(_)) => (
1722 resolve_short_name(sym::RangeInclusive, "std::ops::RangeInclusive"),
1723 ::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)],
1724 ),
1725 (Some(start), None, _) => (
1726 resolve_short_name(sym::RangeFrom, "std::ops::RangeFrom"),
1727 ::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)],
1728 ),
1729 (None, Some(end), ast::RangeEnd::Excluded) => {
1730 (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)])
1731 }
1732 (None, Some(end), ast::RangeEnd::Included(_)) => (
1733 resolve_short_name(sym::RangeToInclusive, "std::ops::RangeToInclusive"),
1734 ::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)],
1735 ),
1736 _ => return,
1737 };
1738
1739 err.span_suggestion_verbose(
1740 pat.span,
1741 ::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"),
1742 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {{ {1} }}", struct_path,
fields.join(", ")))
})format!("{} {{ {} }}", struct_path, fields.join(", ")),
1743 Applicability::MaybeIncorrect,
1744 );
1745
1746 err.note(
1747 "range patterns match against the start and end of a range; \
1748 to bind the components, use a struct pattern",
1749 );
1750 }
1751
1752 fn suggest_swapping_misplaced_self_ty_and_trait(
1753 &mut self,
1754 err: &mut Diag<'_>,
1755 source: PathSource<'_, 'ast, 'ra>,
1756 res: Option<Res>,
1757 span: Span,
1758 ) {
1759 if let Some((trait_ref, self_ty)) =
1760 self.diag_metadata.currently_processing_impl_trait.clone()
1761 && let TyKind::Path(_, self_ty_path) = &self_ty.kind
1762 && let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1763 self.resolve_path(&Segment::from_path(self_ty_path), Some(TypeNS), None, source)
1764 && module.def_kind() == Some(DefKind::Trait)
1765 && trait_ref.path.span == span
1766 && let PathSource::Trait(_) = source
1767 && let Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)) = res
1768 && let Ok(self_ty_str) = self.r.tcx.sess.source_map().span_to_snippet(self_ty.span)
1769 && let Ok(trait_ref_str) =
1770 self.r.tcx.sess.source_map().span_to_snippet(trait_ref.path.span)
1771 {
1772 err.multipart_suggestion(
1773 "`impl` items mention the trait being implemented first and the type it is being implemented for second",
1774 ::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)],
1775 Applicability::MaybeIncorrect,
1776 );
1777 }
1778 }
1779
1780 fn explain_functions_in_pattern(
1781 &self,
1782 err: &mut Diag<'_>,
1783 res: Option<Res>,
1784 source: PathSource<'_, '_, '_>,
1785 ) {
1786 let PathSource::TupleStruct(_, _) = source else { return };
1787 let Some(Res::Def(DefKind::Fn, _)) = res else { return };
1788 err.primary_message("expected a pattern, found a function call");
1789 err.note("function calls are not allowed in patterns: <https://doc.rust-lang.org/book/ch19-00-patterns.html>");
1790 }
1791
1792 fn suggest_changing_type_to_const_param(
1793 &self,
1794 err: &mut Diag<'_>,
1795 res: Option<Res>,
1796 source: PathSource<'_, '_, '_>,
1797 path: &[Segment],
1798 following_seg: Option<&Segment>,
1799 span: Span,
1800 ) {
1801 if let PathSource::Expr(None) = source
1802 && let Some(Res::Def(DefKind::TyParam, _)) = res
1803 && following_seg.is_none()
1804 && let [segment] = path
1805 {
1806 let Some(item) = self.diag_metadata.current_item else { return };
1814 let Some(generics) = item.kind.generics() else { return };
1815 let Some(span) = generics.params.iter().find_map(|param| {
1816 if param.bounds.is_empty() && param.ident.name == segment.ident.name {
1818 Some(param.ident.span)
1819 } else {
1820 None
1821 }
1822 }) else {
1823 return;
1824 };
1825 err.subdiagnostic(diagnostics::UnexpectedResChangeTyParamToConstParamSugg {
1826 before: span.shrink_to_lo(),
1827 after: span.shrink_to_hi(),
1828 });
1829 return;
1830 }
1831 let PathSource::Trait(_) = source else { return };
1832
1833 let applicability = match res {
1835 Some(Res::PrimTy(PrimTy::Int(_) | PrimTy::Uint(_) | PrimTy::Bool | PrimTy::Char)) => {
1836 Applicability::MachineApplicable
1837 }
1838 Some(Res::Def(DefKind::Struct | DefKind::Enum, _))
1842 if self.r.features.adt_const_params() || self.r.features.min_adt_const_params() =>
1843 {
1844 Applicability::MaybeIncorrect
1845 }
1846 _ => return,
1847 };
1848
1849 let Some(item) = self.diag_metadata.current_item else { return };
1850 let Some(generics) = item.kind.generics() else { return };
1851
1852 let param = generics.params.iter().find_map(|param| {
1853 if let [bound] = &*param.bounds
1855 && let ast::GenericBound::Trait(tref) = bound
1856 && tref.modifiers == ast::TraitBoundModifiers::NONE
1857 && tref.span == span
1858 && param.ident.span.eq_ctxt(span)
1859 {
1860 Some(param.ident.span)
1861 } else {
1862 None
1863 }
1864 });
1865
1866 if let Some(param) = param {
1867 err.subdiagnostic(diagnostics::UnexpectedResChangeTyToConstParamSugg {
1868 span: param.shrink_to_lo(),
1869 applicability,
1870 });
1871 }
1872 }
1873
1874 fn suggest_pattern_match_with_let(
1875 &self,
1876 err: &mut Diag<'_>,
1877 source: PathSource<'_, '_, '_>,
1878 span: Span,
1879 ) -> bool {
1880 if let PathSource::Expr(_) = source
1881 && let Some(Expr { span: expr_span, kind: ExprKind::Assign(lhs, _, _), .. }) =
1882 self.diag_metadata.in_if_condition
1883 {
1884 if lhs.is_approximately_pattern() && lhs.span.contains(span) {
1888 err.span_suggestion_verbose(
1889 expr_span.shrink_to_lo(),
1890 "you might have meant to use pattern matching",
1891 "let ",
1892 Applicability::MaybeIncorrect,
1893 );
1894 return true;
1895 }
1896 }
1897 false
1898 }
1899
1900 fn get_single_associated_item(
1901 &mut self,
1902 path: &[Segment],
1903 source: &PathSource<'_, 'ast, 'ra>,
1904 filter_fn: &impl Fn(Res) -> bool,
1905 ) -> Option<TypoSuggestion> {
1906 if let crate::PathSource::TraitItem(_, _) = source {
1907 let mod_path = &path[..path.len() - 1];
1908 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1909 self.resolve_path(mod_path, None, None, *source)
1910 {
1911 let targets: Vec<_> = self
1912 .r
1913 .resolutions(module)
1914 .iter()
1915 .filter_map(|(key, resolution)| {
1916 let resolution = resolution.borrow(self.r);
1917 resolution.best_decl().map(|binding| binding.res()).and_then(|res| {
1918 if filter_fn(res) {
1919 Some((key.ident.name, resolution.orig_ident_span, res))
1920 } else {
1921 None
1922 }
1923 })
1924 })
1925 .collect();
1926 if let &[(name, orig_ident_span, res)] = targets.as_slice() {
1927 return Some(TypoSuggestion::single_item(name, orig_ident_span, res));
1928 }
1929 }
1930 }
1931 None
1932 }
1933
1934 fn restrict_assoc_type_in_where_clause(&self, span: Span, err: &mut Diag<'_>) -> bool {
1936 let Some(ast::WherePredicate {
1938 kind:
1939 ast::WherePredicateKind::BoundPredicate(ast::WhereBoundPredicate {
1940 bounded_ty,
1941 bound_generic_params,
1942 bounds,
1943 }),
1944 span: where_span,
1945 ..
1946 }) = self.diag_metadata.current_where_predicate
1947 else {
1948 return false;
1949 };
1950 if !bound_generic_params.is_empty() {
1951 return false;
1952 }
1953
1954 let ast::TyKind::Path(Some(qself), path) = &bounded_ty.kind else { return false };
1956 let Some(partial_res) = self.r.partial_res_map.get(&bounded_ty.id) else { return false };
1958 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, _))) {
1959 return false;
1960 }
1961
1962 let peeled_ty = qself.ty.peel_refs();
1963 let ast::TyKind::Path(None, type_param_path) = &peeled_ty.kind else { return false };
1964 let Some(partial_res) = self.r.partial_res_map.get(&peeled_ty.id) else {
1966 return false;
1967 };
1968 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, _))) {
1969 return false;
1970 }
1971 let ([ast::PathSegment { args: None, .. }], [ast::GenericBound::Trait(poly_trait_ref)]) =
1972 (&type_param_path.segments[..], &bounds[..])
1973 else {
1974 return false;
1975 };
1976 let [ast::PathSegment { ident, args: None, id }] =
1977 &poly_trait_ref.trait_ref.path.segments[..]
1978 else {
1979 return false;
1980 };
1981 if poly_trait_ref.modifiers != ast::TraitBoundModifiers::NONE {
1982 return false;
1983 }
1984 if ident.span == span {
1985 let Some(partial_res) = self.r.partial_res_map.get(&id) else {
1986 return false;
1987 };
1988 if !#[allow(non_exhaustive_omitted_patterns)] match partial_res.full_res() {
Some(Res::Def(..)) => true,
_ => false,
}matches!(partial_res.full_res(), Some(Res::Def(..))) {
1989 return false;
1990 }
1991
1992 let Some(new_where_bound_predicate) =
1993 mk_where_bound_predicate(path, poly_trait_ref, &qself.ty)
1994 else {
1995 return false;
1996 };
1997 err.span_suggestion_verbose(
1998 *where_span,
1999 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("constrain the associated type to `{0}`",
ident))
})format!("constrain the associated type to `{ident}`"),
2000 where_bound_predicate_to_string(&new_where_bound_predicate),
2001 Applicability::MaybeIncorrect,
2002 );
2003 }
2004 true
2005 }
2006
2007 fn call_has_self_arg(&self, source: PathSource<'_, '_, '_>) -> Option<(Span, Option<Span>)> {
2010 let mut has_self_arg = None;
2011 if let PathSource::Expr(Some(parent)) = source
2012 && let ExprKind::Call(_, args) = &parent.kind
2013 && !args.is_empty()
2014 {
2015 let mut expr_kind = &args[0].kind;
2016 loop {
2017 match expr_kind {
2018 ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
2019 if arg_name.segments[0].ident.name == kw::SelfLower {
2020 let call_span = parent.span;
2021 let tail_args_span = if args.len() > 1 {
2022 Some(Span::new(
2023 args[1].span.lo(),
2024 args.last().unwrap().span.hi(),
2025 call_span.ctxt(),
2026 None,
2027 ))
2028 } else {
2029 None
2030 };
2031 has_self_arg = Some((call_span, tail_args_span));
2032 }
2033 break;
2034 }
2035 ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
2036 _ => break,
2037 }
2038 }
2039 }
2040 has_self_arg
2041 }
2042
2043 fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
2044 let sm = self.r.tcx.sess.source_map();
2049 if let Some(open_brace_span) = sm.span_followed_by(span, "{") {
2050 let close_brace_span =
2053 sm.span_to_next_source(open_brace_span).ok().and_then(|next_source| {
2054 let mut depth: u32 = 1;
2056 let offset = next_source.char_indices().find_map(|(i, c)| {
2057 match c {
2058 '{' => depth += 1,
2059 '}' if depth == 1 => return Some(i),
2060 '}' => depth -= 1,
2061 _ => {}
2062 }
2063 None
2064 })?;
2065 let start = open_brace_span.hi() + rustc_span::BytePos(offset as u32);
2066 Some(open_brace_span.with_lo(start).with_hi(start + rustc_span::BytePos(1)))
2067 });
2068 let closing_brace = close_brace_span.map(|sp| span.to(sp));
2069 (true, closing_brace)
2070 } else {
2071 (false, None)
2072 }
2073 }
2074
2075 fn update_err_for_private_tuple_struct_fields(
2076 &self,
2077 err: &mut Diag<'_>,
2078 source: &PathSource<'_, '_, '_>,
2079 def_id: DefId,
2080 ) -> Option<Vec<Span>> {
2081 match source {
2082 PathSource::TupleStruct(_, pattern_spans) => {
2084 err.primary_message(
2085 "cannot match against a tuple struct which contains private fields",
2086 );
2087
2088 Some(Vec::from(*pattern_spans))
2090 }
2091 PathSource::Expr(Some(Expr {
2093 kind: ExprKind::Call(path, args),
2094 span: call_span,
2095 ..
2096 })) => {
2097 err.primary_message(
2098 "cannot initialize a tuple struct which contains private fields",
2099 );
2100 self.suggest_alternative_construction_methods(
2101 def_id,
2102 err,
2103 path.span,
2104 *call_span,
2105 &args[..],
2106 );
2107
2108 self.r
2109 .field_idents(def_id)
2110 .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
2111 }
2112 _ => None,
2113 }
2114 }
2115
2116 fn smart_resolve_context_dependent_help(
2120 &mut self,
2121 err: &mut Diag<'_>,
2122 span: Span,
2123 source: PathSource<'_, '_, '_>,
2124 path: &[Segment],
2125 res: Res,
2126 path_str: &str,
2127 fallback_label: &str,
2128 ) -> bool {
2129 let ns = source.namespace();
2130 let is_expected = &|res| source.is_expected(res);
2131
2132 let path_sep = |this: &Self, err: &mut Diag<'_>, expr: &Expr, kind: DefKind| {
2133 const MESSAGE: &str = "use the path separator to refer to an item";
2134
2135 let (lhs_span, rhs_span) = match &expr.kind {
2136 ExprKind::Field(base, ident) => (base.span, ident.span),
2137 ExprKind::MethodCall(MethodCall { receiver, span, .. }) => (receiver.span, *span),
2138 _ => return false,
2139 };
2140
2141 if lhs_span.eq_ctxt(rhs_span) {
2142 err.span_suggestion_verbose(
2143 lhs_span.between(rhs_span),
2144 MESSAGE,
2145 "::",
2146 Applicability::MaybeIncorrect,
2147 );
2148 true
2149 } else if #[allow(non_exhaustive_omitted_patterns)] match kind {
DefKind::Struct | DefKind::TyAlias => true,
_ => false,
}matches!(kind, DefKind::Struct | DefKind::TyAlias)
2150 && let Some(lhs_source_span) = lhs_span.find_ancestor_inside(expr.span)
2151 && let Ok(snippet) = this.r.tcx.sess.source_map().span_to_snippet(lhs_source_span)
2152 {
2153 err.span_suggestion_verbose(
2157 lhs_source_span.until(rhs_span),
2158 MESSAGE,
2159 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>::", snippet))
})format!("<{snippet}>::"),
2160 Applicability::MaybeIncorrect,
2161 );
2162 true
2163 } else {
2164 false
2170 }
2171 };
2172
2173 let find_span = |source: &PathSource<'_, '_, '_>, err: &mut Diag<'_>| {
2174 match source {
2175 PathSource::Expr(Some(Expr { span, kind: ExprKind::Call(_, _), .. }))
2176 | PathSource::TupleStruct(span, _) => {
2177 err.span(*span);
2180 *span
2181 }
2182 _ => span,
2183 }
2184 };
2185
2186 let bad_struct_syntax_suggestion = |this: &Self, err: &mut Diag<'_>, def_id: DefId| {
2187 let (followed_by_brace, closing_brace) = this.followed_by_brace(span);
2188
2189 match source {
2190 PathSource::Expr(Some(
2191 parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
2192 )) if path_sep(this, err, parent, DefKind::Struct) => {}
2193 PathSource::Expr(
2194 None
2195 | Some(Expr {
2196 kind:
2197 ExprKind::Path(..)
2198 | ExprKind::Binary(..)
2199 | ExprKind::Unary(..)
2200 | ExprKind::If(..)
2201 | ExprKind::While(..)
2202 | ExprKind::ForLoop { .. }
2203 | ExprKind::Match(..),
2204 ..
2205 }),
2206 ) if followed_by_brace => {
2207 if let Some(sp) = closing_brace {
2208 err.span_label(span, fallback_label.to_string());
2209 err.multipart_suggestion(
2210 "surround the struct literal with parentheses",
2211 ::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![
2212 (sp.shrink_to_lo(), "(".to_string()),
2213 (sp.shrink_to_hi(), ")".to_string()),
2214 ],
2215 Applicability::MaybeIncorrect,
2216 );
2217 } else {
2218 err.span_label(
2219 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!(
2221 "you might want to surround a struct literal with parentheses: \
2222 `({path_str} {{ /* fields */ }})`?"
2223 ),
2224 );
2225 }
2226 }
2227 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
2228 let span = find_span(&source, err);
2229 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"));
2230
2231 let (tail, descr, applicability, old_fields) = match source {
2232 PathSource::Pat => ("", "pattern", Applicability::MachineApplicable, None),
2233 PathSource::TupleStruct(_, args) => (
2234 "",
2235 "pattern",
2236 Applicability::MachineApplicable,
2237 Some(
2238 args.iter()
2239 .map(|a| this.r.tcx.sess.source_map().span_to_snippet(*a).ok())
2240 .collect::<Vec<Option<String>>>(),
2241 ),
2242 ),
2243 _ => (": val", "literal", Applicability::HasPlaceholders, None),
2244 };
2245
2246 let has_private_fields = match def_id.as_local() {
2248 Some(def_id) => this.r.struct_ctors.get(&def_id).is_some_and(|ctor| {
2249 ctor.has_private_fields(this.parent_scope.module, this.r)
2250 }),
2251 None => this.r.tcx.associated_item_def_ids(def_id).iter().any(|field_id| {
2252 let vis = this.r.tcx.visibility(*field_id);
2253 !this.r.is_accessible_from(vis, this.parent_scope.module)
2254 }),
2255 };
2256 if !has_private_fields {
2257 let fields = this.r.field_idents(def_id);
2260 let has_fields = fields.as_ref().is_some_and(|f| !f.is_empty());
2261
2262 if let PathSource::Expr(Some(Expr {
2263 kind: ExprKind::Call(path, args),
2264 span,
2265 ..
2266 })) = source
2267 && !args.is_empty()
2268 && let Some(fields) = &fields
2269 && args.len() == fields.len()
2270 {
2272 let path_span = path.span;
2273 let mut parts = Vec::new();
2274
2275 parts.push((
2277 path_span.shrink_to_hi().until(args[0].span),
2278 "{".to_owned(),
2279 ));
2280
2281 for (field, arg) in fields.iter().zip(args.iter()) {
2282 parts.push((arg.span.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", field))
})format!("{}: ", field)));
2284 }
2285
2286 parts.push((
2288 args.last().unwrap().span.shrink_to_hi().until(span.shrink_to_hi()),
2289 "}".to_owned(),
2290 ));
2291
2292 err.multipart_suggestion(
2293 ::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"),
2294 parts,
2295 applicability,
2296 );
2297 } else {
2298 let (fields, applicability) = match fields {
2299 Some(fields) => {
2300 let fields = if let Some(old_fields) = old_fields {
2301 fields
2302 .iter()
2303 .enumerate()
2304 .map(|(idx, new)| (new, old_fields.get(idx)))
2305 .map(|(new, old)| {
2306 if let Some(Some(old)) = old
2307 && new.as_str() != old
2308 {
2309 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: {1}", new, old))
})format!("{new}: {old}")
2310 } else {
2311 new.to_string()
2312 }
2313 })
2314 .collect::<Vec<String>>()
2315 } else {
2316 fields
2317 .iter()
2318 .map(|f| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", f, tail))
})format!("{f}{tail}"))
2319 .collect::<Vec<String>>()
2320 };
2321
2322 (fields.join(", "), applicability)
2323 }
2324 None => {
2325 ("/* fields */".to_string(), Applicability::HasPlaceholders)
2326 }
2327 };
2328 let pad = if has_fields { " " } else { "" };
2329 err.span_suggestion(
2330 span,
2331 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use struct {0} syntax instead",
descr))
})format!("use struct {descr} syntax instead"),
2332 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {{{1}{2}{1}}}", path_str, pad,
fields))
})format!("{path_str} {{{pad}{fields}{pad}}}"),
2333 applicability,
2334 );
2335 }
2336 }
2337 if let PathSource::Expr(Some(Expr {
2338 kind: ExprKind::Call(path, args),
2339 span: call_span,
2340 ..
2341 })) = source
2342 {
2343 this.suggest_alternative_construction_methods(
2344 def_id,
2345 err,
2346 path.span,
2347 *call_span,
2348 &args[..],
2349 );
2350 }
2351 }
2352 _ => {
2353 err.span_label(span, fallback_label.to_string());
2354 }
2355 }
2356 };
2357
2358 match (res, source) {
2359 (
2360 Res::Def(DefKind::Macro(kinds), def_id),
2361 PathSource::Expr(Some(Expr {
2362 kind: ExprKind::Index(..) | ExprKind::Call(..), ..
2363 }))
2364 | PathSource::Struct(_),
2365 ) if kinds.contains(MacroKinds::BANG) => {
2366 let suggestable = def_id.is_local()
2368 || self.r.tcx.lookup_stability(def_id).is_none_or(|s| s.is_stable());
2369
2370 err.span_label(span, fallback_label.to_string());
2371
2372 if path
2374 .last()
2375 .is_some_and(|segment| !segment.has_generic_args && !segment.has_lifetime_args)
2376 && suggestable
2377 {
2378 err.span_suggestion_verbose(
2379 span.shrink_to_hi(),
2380 "use `!` to invoke the macro",
2381 "!",
2382 Applicability::MaybeIncorrect,
2383 );
2384 }
2385
2386 if path_str == "try" && span.is_rust_2015() {
2387 err.note("if you want the `try` keyword, you need Rust 2018 or later");
2388 }
2389 }
2390 (Res::Def(DefKind::Macro(kinds), _), _) if kinds.contains(MacroKinds::BANG) => {
2391 err.span_label(span, fallback_label.to_string());
2392 }
2393 (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
2394 err.span_label(span, "type aliases cannot be used as traits");
2395 if self.r.tcx.sess.is_nightly_build() {
2396 let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
2397 `type` alias";
2398 let span = self.r.def_span(def_id);
2399 if let Ok(snip) = self.r.tcx.sess.source_map().span_to_snippet(span) {
2400 let snip = snip.replacen("type", "trait", 1);
2403 err.span_suggestion(span, msg, snip, Applicability::MaybeIncorrect);
2404 } else {
2405 err.span_help(span, msg);
2406 }
2407 }
2408 }
2409 (
2410 Res::Def(kind @ (DefKind::Mod | DefKind::Trait | DefKind::TyAlias), _),
2411 PathSource::Expr(Some(parent)),
2412 ) if path_sep(self, err, parent, kind) => {
2413 return true;
2414 }
2415 (
2416 Res::Def(DefKind::Enum, def_id),
2417 PathSource::TupleStruct(..) | PathSource::Expr(..),
2418 ) => {
2419 self.suggest_using_enum_variant(err, source, def_id, span);
2420 }
2421 (Res::Def(DefKind::Struct, def_id), source) if ns == ValueNS => {
2422 if let PathSource::Expr(Some(parent)) = source
2423 && let ExprKind::Field(..) | ExprKind::MethodCall(..) = parent.kind
2424 {
2425 bad_struct_syntax_suggestion(self, err, def_id);
2426 return true;
2427 }
2428 let Some(ctor) = self.r.struct_ctor(def_id) else {
2429 bad_struct_syntax_suggestion(self, err, def_id);
2430 return true;
2431 };
2432
2433 let is_accessible = self.r.is_accessible_from(ctor.vis, self.parent_scope.module);
2436 if is_accessible
2437 && let mod_path = &path[..path.len() - 1]
2438 && let PathResult::Module(ModuleOrUniformRoot::Module(import_mod)) =
2439 self.resolve_path(mod_path, Some(TypeNS), None, PathSource::Module)
2440 && ctor.has_private_fields(import_mod, self.r)
2441 && let Ok(import_decl) = self.r.cm().maybe_resolve_ident_in_module(
2442 ModuleOrUniformRoot::Module(import_mod),
2443 path.last().unwrap().ident,
2444 TypeNS,
2445 &self.parent_scope,
2446 None,
2447 )
2448 {
2449 err.span_note(
2450 import_decl.span,
2451 "the type is accessed through this re-export, but the type's constructor \
2452 is not visible in this import's scope due to private fields",
2453 );
2454 if !ctor.has_private_fields(self.parent_scope.module, self.r) {
2455 err.span_suggestion_verbose(
2456 span,
2457 "the type can be constructed directly, because its fields are \
2458 available from the current scope",
2459 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("crate{0}",
self.r.tcx.def_path(def_id).to_string_no_crate_verbose()))
})format!(
2463 "crate{}", self.r.tcx.def_path(def_id).to_string_no_crate_verbose(),
2465 ),
2466 Applicability::MachineApplicable,
2467 );
2468 }
2469 self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
2470 }
2471 if !is_expected(ctor.res) || is_accessible {
2472 return true;
2473 }
2474
2475 let field_spans =
2476 self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
2477
2478 if let Some(spans) = field_spans
2479 .filter(|spans| spans.len() > 0 && ctor.field_visibilities.len() == spans.len())
2480 {
2481 let non_visible_spans: Vec<Span> = iter::zip(&ctor.field_visibilities, &spans)
2482 .filter(|(vis, _)| {
2483 !self.r.is_accessible_from(**vis, self.parent_scope.module)
2484 })
2485 .map(|(_, span)| *span)
2486 .collect();
2487
2488 if non_visible_spans.len() > 0 {
2489 if let Some(fields) = self.r.field_visibility_spans.get(&def_id) {
2490 err.multipart_suggestion(
2491 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider making the field{0} publicly accessible",
if fields.len() == 1 { "" } else { "s" }))
})format!(
2492 "consider making the field{} publicly accessible",
2493 pluralize!(fields.len())
2494 ),
2495 fields.iter().map(|span| (*span, "pub ".to_string())).collect(),
2496 Applicability::MaybeIncorrect,
2497 );
2498 }
2499
2500 let mut m: MultiSpan = non_visible_spans.clone().into();
2501 non_visible_spans
2502 .into_iter()
2503 .for_each(|s| m.push_span_label(s, "private field"));
2504 err.span_note(m, "constructor is not visible here due to private fields");
2505 }
2506
2507 return true;
2508 }
2509
2510 err.span_label(span, "constructor is not visible here due to private fields");
2511 }
2512 (Res::Def(DefKind::Union | DefKind::Variant, def_id), _) if ns == ValueNS => {
2513 bad_struct_syntax_suggestion(self, err, def_id);
2514 }
2515 (Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id), _) if ns == ValueNS => {
2516 match source {
2517 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
2518 let span = find_span(&source, err);
2519 err.span_label(
2520 self.r.def_span(def_id),
2521 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` defined here", path_str))
})format!("`{path_str}` defined here"),
2522 );
2523 err.span_suggestion(
2524 span,
2525 "use this syntax instead",
2526 path_str,
2527 Applicability::MaybeIncorrect,
2528 );
2529 }
2530 _ => return false,
2531 }
2532 }
2533 (Res::Def(DefKind::Ctor(_, CtorKind::Fn), ctor_def_id), _) if ns == ValueNS => {
2534 let def_id = self.r.tcx.parent(ctor_def_id);
2535 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"));
2536 let fields = self.r.field_idents(def_id).map_or_else(
2537 || "/* fields */".to_string(),
2538 |field_ids| ::alloc::vec::from_elem("_", field_ids.len())vec!["_"; field_ids.len()].join(", "),
2539 );
2540 err.span_suggestion(
2541 span,
2542 "use the tuple variant pattern syntax instead",
2543 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}({1})", path_str, fields))
})format!("{path_str}({fields})"),
2544 Applicability::HasPlaceholders,
2545 );
2546 }
2547 (Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }, _) if ns == ValueNS => {
2548 err.span_label(span, fallback_label.to_string());
2549 err.note("can't use `Self` as a constructor, you must use the implemented struct");
2550 }
2551 (
2552 Res::Def(DefKind::TyAlias | DefKind::AssocTy, _),
2553 PathSource::TraitItem(ValueNS, PathSource::TupleStruct(whole, args)),
2554 ) => {
2555 err.note("can't use a type alias as tuple pattern");
2556
2557 let mut suggestion = Vec::new();
2558
2559 if let &&[first, ..] = args
2560 && let &&[.., last] = args
2561 {
2562 suggestion.extend([
2563 (span.between(first), " { 0: ".to_owned()),
2569 (last.between(whole.shrink_to_hi()), " }".to_owned()),
2570 ]);
2571
2572 suggestion.extend(
2573 args.iter()
2574 .enumerate()
2575 .skip(1) .map(|(index, &arg)| (arg.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", index))
})format!("{index}: "))),
2577 )
2578 } else {
2579 suggestion.push((span.between(whole.shrink_to_hi()), " {}".to_owned()));
2580 }
2581
2582 err.multipart_suggestion(
2583 "use struct pattern instead",
2584 suggestion,
2585 Applicability::MachineApplicable,
2586 );
2587 }
2588 (
2589 Res::Def(DefKind::TyAlias | DefKind::AssocTy, _),
2590 PathSource::TraitItem(
2591 ValueNS,
2592 PathSource::Expr(Some(ast::Expr {
2593 span: whole,
2594 kind: ast::ExprKind::Call(_, args),
2595 ..
2596 })),
2597 ),
2598 ) => {
2599 err.note("can't use a type alias as a constructor");
2600
2601 let mut suggestion = Vec::new();
2602
2603 if let [first, ..] = &**args
2604 && let [.., last] = &**args
2605 {
2606 suggestion.extend([
2607 (span.between(first.span), " { 0: ".to_owned()),
2613 (last.span.between(whole.shrink_to_hi()), " }".to_owned()),
2614 ]);
2615
2616 suggestion.extend(
2617 args.iter()
2618 .enumerate()
2619 .skip(1) .map(|(index, arg)| (arg.span.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", index))
})format!("{index}: "))),
2621 )
2622 } else {
2623 suggestion.push((span.between(whole.shrink_to_hi()), " {}".to_owned()));
2624 }
2625
2626 err.multipart_suggestion(
2627 "use struct expression instead",
2628 suggestion,
2629 Applicability::MachineApplicable,
2630 );
2631 }
2632 _ => return false,
2633 }
2634 true
2635 }
2636
2637 fn suggest_alternative_construction_methods(
2638 &self,
2639 def_id: DefId,
2640 err: &mut Diag<'_>,
2641 path_span: Span,
2642 call_span: Span,
2643 args: &[Box<Expr>],
2644 ) {
2645 if def_id.is_local() {
2646 return;
2648 }
2649 let mut items = self
2652 .r
2653 .tcx
2654 .inherent_impls(def_id)
2655 .iter()
2656 .flat_map(|&i| self.r.tcx.associated_items(i).in_definition_order())
2657 .filter(|item| item.is_fn() && !item.is_method())
2659 .filter_map(|item| {
2660 let fn_sig = self.r.tcx.fn_sig(item.def_id).skip_binder();
2662 let ret_ty = fn_sig.output().skip_binder();
2664 let ty::Adt(def, _args) = ret_ty.kind() else {
2665 return None;
2666 };
2667 let input_len = fn_sig.inputs().skip_binder().len();
2668 if def.did() != def_id {
2669 return None;
2670 }
2671 let name = item.name();
2672 let order = !name.as_str().starts_with("new");
2673 Some((order, name, input_len))
2674 })
2675 .collect::<Vec<_>>();
2676 items.sort_by_key(|(order, _, _)| *order);
2677 let suggestion = |name, args| {
2678 ::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(", "))
2679 };
2680 match &items[..] {
2681 [] => {}
2682 [(_, name, len)] if *len == args.len() => {
2683 err.span_suggestion_verbose(
2684 path_span.shrink_to_hi(),
2685 ::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",),
2686 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("::{0}", name))
})format!("::{name}"),
2687 Applicability::MaybeIncorrect,
2688 );
2689 }
2690 [(_, name, len)] => {
2691 err.span_suggestion_verbose(
2692 path_span.shrink_to_hi().with_hi(call_span.hi()),
2693 ::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",),
2694 suggestion(name, *len),
2695 Applicability::MaybeIncorrect,
2696 );
2697 }
2698 _ => {
2699 err.span_suggestions_with_style(
2700 path_span.shrink_to_hi().with_hi(call_span.hi()),
2701 "you might have meant to use an associated function to build this type",
2702 items.iter().map(|(_, name, len)| suggestion(name, *len)),
2703 Applicability::MaybeIncorrect,
2704 SuggestionStyle::ShowAlways,
2705 );
2706 }
2707 }
2708 let default_trait = self
2716 .r
2717 .lookup_import_candidates(
2718 Ident::with_dummy_span(sym::Default),
2719 Namespace::TypeNS,
2720 &self.parent_scope,
2721 &|res: Res| #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Trait, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Trait, _)),
2722 )
2723 .iter()
2724 .filter_map(|candidate| candidate.did)
2725 .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)));
2726 let Some(default_trait) = default_trait else {
2727 return;
2728 };
2729 if self
2730 .r
2731 .extern_crate_map
2732 .items()
2733 .flat_map(|(_, crate_)| {
2735 UnordItems::new(
2736 self.r.tcx.implementations_of_trait((*crate_, default_trait)).into_iter(),
2737 )
2738 })
2739 .filter_map(|(_, simplified_self_ty)| *simplified_self_ty)
2740 .filter_map(|simplified_self_ty| match simplified_self_ty {
2741 SimplifiedType::Adt(did) => Some(did),
2742 _ => None,
2743 })
2744 .any(|did| did == def_id)
2745 {
2746 err.multipart_suggestion(
2747 "consider using the `Default` trait",
2748 ::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![
2749 (path_span.shrink_to_lo(), "<".to_string()),
2750 (
2751 path_span.shrink_to_hi().with_hi(call_span.hi()),
2752 " as std::default::Default>::default()".to_string(),
2753 ),
2754 ],
2755 Applicability::MaybeIncorrect,
2756 );
2757 }
2758 }
2759
2760 pub(crate) fn find_similarly_named_assoc_item(
2763 &mut self,
2764 ident: Symbol,
2765 kind: &AssocItemKind,
2766 ) -> Option<Symbol> {
2767 let (module, _) = self.current_trait_ref.as_ref()?;
2768 if ident == kw::Underscore {
2769 return None;
2771 }
2772
2773 let targets = self
2774 .r
2775 .resolutions(*module)
2776 .iter()
2777 .filter_map(|(key, res)| {
2778 res.borrow(self.r).best_decl().map(|binding| (key, binding.res()))
2779 })
2780 .filter(|(_, res)| match (kind, res) {
2781 (AssocItemKind::Const(..), Res::Def(DefKind::AssocConst { .. }, _)) => true,
2782 (AssocItemKind::Fn(_), Res::Def(DefKind::AssocFn, _)) => true,
2783 (AssocItemKind::Type(..), Res::Def(DefKind::AssocTy, _)) => true,
2784 (AssocItemKind::Delegation(_), Res::Def(DefKind::AssocFn, _)) => true,
2785 _ => false,
2786 })
2787 .map(|(key, _)| key.ident.name)
2788 .collect::<Vec<_>>();
2789
2790 find_best_match_for_name(&targets, ident, None)
2791 }
2792
2793 fn lookup_assoc_candidate<FilterFn>(
2794 &self,
2795 ident: Ident,
2796 ns: Namespace,
2797 filter_fn: FilterFn,
2798 called: bool,
2799 ) -> Option<AssocSuggestion>
2800 where
2801 FilterFn: Fn(Res) -> bool,
2802 {
2803 fn extract_node_id(t: &Ty) -> Option<NodeId> {
2804 match t.kind {
2805 TyKind::Path(None, _) => Some(t.id),
2806 TyKind::Ref(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
2807 _ => None,
2811 }
2812 }
2813 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
2815 if let Some(node_id) = self.diag_metadata.current_self_type.and_then(extract_node_id)
2816 && let Some(resolution) = self.r.partial_res_map.get(&node_id)
2817 && let Some(Res::Def(DefKind::Struct | DefKind::Union, did)) = resolution.full_res()
2818 && let Some(fields) = self.r.field_idents(did)
2819 && let Some(field) = fields.iter().find(|id| ident.name == id.name)
2820 {
2821 return Some(AssocSuggestion::Field(field.span));
2823 }
2824 }
2825
2826 if let Some(items) = self.diag_metadata.current_trait_assoc_items {
2827 for assoc_item in items {
2828 if let Some(assoc_ident) = assoc_item.kind.ident()
2829 && assoc_ident == ident
2830 {
2831 return Some(match &assoc_item.kind {
2832 ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
2833 ast::AssocItemKind::Fn(ast::Fn { sig, .. }) if sig.decl.has_self() => {
2834 AssocSuggestion::MethodWithSelf { called }
2835 }
2836 ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn { called },
2837 ast::AssocItemKind::Type(..) => AssocSuggestion::AssocType,
2838 ast::AssocItemKind::Delegation(..)
2839 if self
2840 .r
2841 .owners
2842 .get(&assoc_item.id)
2843 .and_then(|o| self.r.delegation_fn_sigs.get(&o.def_id))
2844 .is_some_and(|sig| sig.has_self) =>
2845 {
2846 AssocSuggestion::MethodWithSelf { called }
2847 }
2848 ast::AssocItemKind::Delegation(..) => AssocSuggestion::AssocFn { called },
2849 ast::AssocItemKind::MacCall(_) | ast::AssocItemKind::DelegationMac(..) => {
2850 continue;
2851 }
2852 });
2853 }
2854 }
2855 }
2856
2857 if let Some((module, _)) = self.current_trait_ref
2859 && let Ok(binding) = self.r.cm().maybe_resolve_ident_in_module(
2860 ModuleOrUniformRoot::Module(module),
2861 ident,
2862 ns,
2863 &self.parent_scope,
2864 None,
2865 )
2866 {
2867 let res = binding.res();
2868 if filter_fn(res) {
2869 match res {
2870 Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) => {
2871 let has_self = match def_id.as_local() {
2872 Some(def_id) => self
2873 .r
2874 .delegation_fn_sigs
2875 .get(&def_id)
2876 .is_some_and(|sig| sig.has_self),
2877 None => {
2878 self.r.tcx.fn_arg_idents(def_id).first().is_some_and(|&ident| {
2879 #[allow(non_exhaustive_omitted_patterns)] match ident {
Some(Ident { name: kw::SelfLower, .. }) => true,
_ => false,
}matches!(ident, Some(Ident { name: kw::SelfLower, .. }))
2880 })
2881 }
2882 };
2883 if has_self {
2884 return Some(AssocSuggestion::MethodWithSelf { called });
2885 } else {
2886 return Some(AssocSuggestion::AssocFn { called });
2887 }
2888 }
2889 Res::Def(DefKind::AssocConst { .. }, _) => {
2890 return Some(AssocSuggestion::AssocConst);
2891 }
2892 Res::Def(DefKind::AssocTy, _) => {
2893 return Some(AssocSuggestion::AssocType);
2894 }
2895 _ => {}
2896 }
2897 }
2898 }
2899
2900 None
2901 }
2902
2903 fn lookup_typo_candidate(
2904 &mut self,
2905 path: &[Segment],
2906 following_seg: Option<&Segment>,
2907 ns: Namespace,
2908 filter_fn: &impl Fn(Res) -> bool,
2909 ) -> TypoCandidate {
2910 let mut names = Vec::new();
2911 if let [segment] = path {
2912 let mut ctxt = segment.ident.span.ctxt();
2913
2914 for rib in self.ribs[ns].iter().rev() {
2917 let rib_ctxt = if rib.kind.contains_params() {
2918 ctxt.normalize_to_macros_2_0()
2919 } else {
2920 ctxt.normalize_to_macro_rules()
2921 };
2922
2923 for (ident, &res) in &rib.bindings {
2925 if filter_fn(res) && ident.span.ctxt() == rib_ctxt {
2926 names.push(TypoSuggestion::new(ident.name, ident.span, res));
2927 }
2928 }
2929
2930 if let RibKind::Block(Some(module)) = rib.kind {
2931 self.r.add_module_candidates(
2932 module.to_module(),
2933 &mut names,
2934 &filter_fn,
2935 Some(ctxt),
2936 );
2937 } else if let RibKind::Module(module) = rib.kind {
2938 let parent_scope =
2940 &ParentScope { module: module.to_module(), ..self.parent_scope };
2941 self.r.add_scope_set_candidates(
2942 &mut names,
2943 ScopeSet::All(ns),
2944 parent_scope,
2945 segment.ident.span.with_ctxt(ctxt),
2946 filter_fn,
2947 );
2948 break;
2949 }
2950
2951 if let RibKind::MacroDefinition(def) = rib.kind
2952 && def == self.r.macro_def(ctxt)
2953 {
2954 ctxt.remove_mark();
2957 }
2958 }
2959 } else {
2960 let mod_path = &path[..path.len() - 1];
2962 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
2963 self.resolve_path(mod_path, Some(TypeNS), None, PathSource::Type)
2964 {
2965 self.r.add_module_candidates(module, &mut names, &filter_fn, None);
2966 }
2967 }
2968
2969 if let Some(following_seg) = following_seg {
2971 names.retain(|suggestion| match suggestion.res {
2972 Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _) => {
2973 suggestion.candidate != following_seg.ident.name
2975 }
2976 Res::Def(DefKind::Mod, def_id) => {
2977 let module = self.r.expect_module(def_id);
2978 self.r
2979 .resolutions(module)
2980 .iter()
2981 .any(|(key, _)| key.ident.name == following_seg.ident.name)
2982 }
2983 _ => true,
2984 });
2985 }
2986 let name = path[path.len() - 1].ident.name;
2987 names.sort_by(|a, b| a.candidate.as_str().cmp(b.candidate.as_str()));
2989
2990 match find_best_match_for_name(
2991 &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
2992 name,
2993 None,
2994 ) {
2995 Some(found) => {
2996 let Some(sugg) = names.into_iter().find(|suggestion| suggestion.candidate == found)
2997 else {
2998 return TypoCandidate::None;
2999 };
3000 if found == name {
3001 TypoCandidate::Shadowed(sugg.res, sugg.span)
3002 } else {
3003 TypoCandidate::Typo(sugg)
3004 }
3005 }
3006 _ => TypoCandidate::None,
3007 }
3008 }
3009
3010 fn likely_rust_type(path: &[Segment]) -> Option<Symbol> {
3013 let name = path[path.len() - 1].ident.as_str();
3014 Some(match name {
3016 "byte" => sym::u8, "short" => sym::i16,
3018 "Bool" => sym::bool,
3019 "Boolean" => sym::bool,
3020 "boolean" => sym::bool,
3021 "int" => sym::i32,
3022 "long" => sym::i64,
3023 "float" => sym::f32,
3024 "double" => sym::f64,
3025 _ => return None,
3026 })
3027 }
3028
3029 fn let_binding_suggestion(&self, err: &mut Diag<'_>, ident_span: Span) -> bool {
3032 if ident_span.from_expansion() {
3033 return false;
3034 }
3035
3036 if let Some(Expr { kind: ExprKind::Assign(lhs, ..), .. }) = self.diag_metadata.in_assignment
3038 && let ast::ExprKind::Path(None, ref path) = lhs.kind
3039 && self.r.tcx.sess.source_map().is_line_before_span_empty(ident_span)
3040 {
3041 let (span, text) = match path.segments.first() {
3042 Some(seg) if let Some(name) = seg.ident.as_str().strip_prefix("let") => {
3043 let name = name.trim_prefix('_');
3045 (ident_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("let {0}", name))
})format!("let {name}"))
3046 }
3047 _ => (ident_span.shrink_to_lo(), "let ".to_string()),
3048 };
3049
3050 err.span_suggestion_verbose(
3051 span,
3052 "you might have meant to introduce a new binding",
3053 text,
3054 Applicability::MaybeIncorrect,
3055 );
3056 return true;
3057 }
3058
3059 if err.code == Some(E0423)
3062 && let Some((let_span, None, Some(val_span))) = self.diag_metadata.current_let_binding
3063 && val_span.contains(ident_span)
3064 && val_span.lo() == ident_span.lo()
3065 {
3066 err.span_suggestion_verbose(
3067 let_span.shrink_to_hi().to(val_span.shrink_to_lo()),
3068 "you might have meant to use `:` for type annotation",
3069 ": ",
3070 Applicability::MaybeIncorrect,
3071 );
3072 return true;
3073 }
3074 false
3075 }
3076
3077 fn find_module(&self, def_id: DefId) -> Option<(Module<'ra>, ImportSuggestion)> {
3078 let mut result = None;
3079 let mut seen_modules = FxHashSet::default();
3080 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)];
3081
3082 while let Some((in_module, path_segments, doc_visible)) = worklist.pop() {
3083 if result.is_some() {
3085 break;
3086 }
3087
3088 in_module.for_each_child(self.r, |r, ident, orig_ident_span, _, name_binding| {
3089 if result.is_some() || !name_binding.vis().is_visible_locally() {
3091 return;
3092 }
3093 if let Some(module_def_id) = name_binding.res().module_like_def_id() {
3094 let mut path_segments = path_segments.clone();
3096 path_segments.push(ast::PathSegment::from_ident(ident.orig(orig_ident_span)));
3097 let doc_visible = doc_visible
3098 && (module_def_id.is_local() || !r.tcx.is_doc_hidden(module_def_id));
3099 if module_def_id == def_id {
3100 let path = Path { span: name_binding.span, segments: path_segments };
3101 result = Some((
3102 r.expect_module(module_def_id),
3103 ImportSuggestion {
3104 did: Some(def_id),
3105 descr: "module",
3106 path,
3107 accessible: true,
3108 doc_visible,
3109 note: None,
3110 via_import: false,
3111 is_stable: true,
3112 },
3113 ));
3114 } else {
3115 if seen_modules.insert(module_def_id) {
3117 let module = r.expect_module(module_def_id);
3118 worklist.push((module, path_segments, doc_visible));
3119 }
3120 }
3121 }
3122 });
3123 }
3124
3125 result
3126 }
3127
3128 fn collect_enum_ctors(&self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
3129 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
3130 let mut variants = Vec::new();
3131 enum_module.for_each_child(self.r, |_, ident, orig_ident_span, _, name_binding| {
3132 if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
3133 let mut segms = enum_import_suggestion.path.segments.clone();
3134 segms.push(ast::PathSegment::from_ident(ident.orig(orig_ident_span)));
3135 let path = Path { span: name_binding.span, segments: segms };
3136 variants.push((path, def_id, kind));
3137 }
3138 });
3139 variants
3140 })
3141 }
3142
3143 fn suggest_using_enum_variant(
3145 &self,
3146 err: &mut Diag<'_>,
3147 source: PathSource<'_, '_, '_>,
3148 def_id: DefId,
3149 span: Span,
3150 ) {
3151 let Some(variant_ctors) = self.collect_enum_ctors(def_id) else {
3152 err.note("you might have meant to use one of the enum's variants");
3153 return;
3154 };
3155
3156 let (suggest_path_sep_dot_span, suggest_only_tuple_variants) = match source {
3161 PathSource::TupleStruct(..) => (None, true),
3163 PathSource::Expr(Some(expr)) => match &expr.kind {
3164 ExprKind::Call(..) => (None, true),
3166 ExprKind::MethodCall(MethodCall {
3169 receiver,
3170 span,
3171 seg: PathSegment { ident, .. },
3172 ..
3173 }) => {
3174 let dot_span = receiver.span.between(*span);
3175 let found_tuple_variant = variant_ctors.iter().any(|(path, _, ctor_kind)| {
3176 *ctor_kind == CtorKind::Fn
3177 && path.segments.last().is_some_and(|seg| seg.ident == *ident)
3178 });
3179 (found_tuple_variant.then_some(dot_span), false)
3180 }
3181 ExprKind::Field(base, ident) => {
3184 let dot_span = base.span.between(ident.span);
3185 let found_tuple_or_unit_variant = variant_ctors.iter().any(|(path, ..)| {
3186 path.segments.last().is_some_and(|seg| seg.ident == *ident)
3187 });
3188 (found_tuple_or_unit_variant.then_some(dot_span), false)
3189 }
3190 _ => (None, false),
3191 },
3192 _ => (None, false),
3193 };
3194
3195 if let Some(dot_span) = suggest_path_sep_dot_span {
3196 err.span_suggestion_verbose(
3197 dot_span,
3198 "use the path separator to refer to a variant",
3199 "::",
3200 Applicability::MaybeIncorrect,
3201 );
3202 } else if suggest_only_tuple_variants {
3203 let mut suggestable_variants = variant_ctors
3206 .iter()
3207 .filter(|(.., kind)| *kind == CtorKind::Fn)
3208 .map(|(variant, ..)| path_names_to_string(variant))
3209 .collect::<Vec<_>>();
3210 suggestable_variants.sort();
3211
3212 let non_suggestable_variant_count = variant_ctors.len() - suggestable_variants.len();
3213
3214 let source_msg = if #[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::TupleStruct(..) => true,
_ => false,
}matches!(source, PathSource::TupleStruct(..)) {
3215 "to match against"
3216 } else {
3217 "to construct"
3218 };
3219
3220 if !suggestable_variants.is_empty() {
3221 let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
3222 ::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")
3223 } else {
3224 ::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")
3225 };
3226
3227 err.span_suggestions(
3228 span,
3229 msg,
3230 suggestable_variants,
3231 Applicability::MaybeIncorrect,
3232 );
3233 }
3234
3235 if non_suggestable_variant_count == variant_ctors.len() {
3237 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}"));
3238 }
3239
3240 if non_suggestable_variant_count == 1 {
3242 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"));
3243 } else if non_suggestable_variant_count >= 1 {
3244 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!(
3245 "you might have meant {source_msg} one of the enum's non-tuple variants"
3246 ));
3247 }
3248 } else {
3249 let needs_placeholder = |ctor_def_id: DefId, kind: CtorKind| {
3250 let def_id = self.r.tcx.parent(ctor_def_id);
3251 match kind {
3252 CtorKind::Const => false,
3253 CtorKind::Fn => {
3254 !self.r.field_idents(def_id).is_some_and(|field_ids| field_ids.is_empty())
3255 }
3256 }
3257 };
3258
3259 let mut suggestable_variants = variant_ctors
3260 .iter()
3261 .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind))
3262 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
3263 .map(|(variant, kind)| match kind {
3264 CtorKind::Const => variant,
3265 CtorKind::Fn => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0}())", variant))
})format!("({variant}())"),
3266 })
3267 .collect::<Vec<_>>();
3268 suggestable_variants.sort();
3269 let no_suggestable_variant = suggestable_variants.is_empty();
3270
3271 if !no_suggestable_variant {
3272 let msg = if suggestable_variants.len() == 1 {
3273 "you might have meant to use the following enum variant"
3274 } else {
3275 "you might have meant to use one of the following enum variants"
3276 };
3277
3278 err.span_suggestions(
3279 span,
3280 msg,
3281 suggestable_variants,
3282 Applicability::MaybeIncorrect,
3283 );
3284 }
3285
3286 let mut suggestable_variants_with_placeholders = variant_ctors
3287 .iter()
3288 .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
3289 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
3290 .filter_map(|(variant, kind)| match kind {
3291 CtorKind::Fn => Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0}(/* fields */))", variant))
})format!("({variant}(/* fields */))")),
3292 _ => None,
3293 })
3294 .collect::<Vec<_>>();
3295 suggestable_variants_with_placeholders.sort();
3296
3297 if !suggestable_variants_with_placeholders.is_empty() {
3298 let msg =
3299 match (no_suggestable_variant, suggestable_variants_with_placeholders.len()) {
3300 (true, 1) => "the following enum variant is available",
3301 (true, _) => "the following enum variants are available",
3302 (false, 1) => "alternatively, the following enum variant is available",
3303 (false, _) => {
3304 "alternatively, the following enum variants are also available"
3305 }
3306 };
3307
3308 err.span_suggestions(
3309 span,
3310 msg,
3311 suggestable_variants_with_placeholders,
3312 Applicability::HasPlaceholders,
3313 );
3314 }
3315 };
3316
3317 if def_id.is_local() {
3318 err.span_note(self.r.def_span(def_id), "the enum is defined here");
3319 }
3320 }
3321
3322 pub(crate) fn detect_and_suggest_const_parameter_error(
3353 &mut self,
3354 path: &[Segment],
3355 source: PathSource<'_, 'ast, 'ra>,
3356 ) -> Option<Diag<'tcx>> {
3357 let Some(item) = self.diag_metadata.current_item else { return None };
3358 let ItemKind::Impl(impl_) = &item.kind else { return None };
3359 let self_ty = &impl_.self_ty;
3360
3361 let [current_parameter] = path else {
3363 return None;
3364 };
3365
3366 let target_ident = current_parameter.ident;
3367
3368 let visitor = ParentPathVisitor::new(self_ty, target_ident);
3370
3371 let Some(parent_segment) = visitor.parent else {
3372 return None;
3373 };
3374
3375 let Some(args) = parent_segment.args.as_ref() else {
3376 return None;
3377 };
3378
3379 let GenericArgs::AngleBracketed(angle) = args.as_ref() else {
3380 return None;
3381 };
3382
3383 let usage_to_pos: FxHashMap<NodeId, usize> = angle
3386 .args
3387 .iter()
3388 .enumerate()
3389 .filter_map(|(pos, arg)| {
3390 if let AngleBracketedArg::Arg(GenericArg::Type(ty)) = arg
3391 && let TyKind::Path(_, path) = &ty.kind
3392 && let [segment] = path.segments.as_slice()
3393 {
3394 Some((segment.id, pos))
3395 } else {
3396 None
3397 }
3398 })
3399 .collect();
3400
3401 let Some(idx) = current_parameter.id.and_then(|id| usage_to_pos.get(&id).copied()) else {
3404 return None;
3405 };
3406
3407 let ns = source.namespace();
3409 let segment = Segment::from(parent_segment);
3410 let segments = [segment];
3411 let finalize = Finalize::new(parent_segment.id, parent_segment.ident.span);
3412
3413 if let Ok(Some(resolve)) = self.resolve_qpath_anywhere(
3414 &None,
3415 &segments,
3416 ns,
3417 source.defer_to_typeck(),
3418 finalize,
3419 source,
3420 ) && let Some(resolve) = resolve.full_res()
3421 && let Res::Def(_, def_id) = resolve
3422 && def_id.is_local()
3423 && let Some(local_def_id) = def_id.as_local()
3424 && let Some(struct_generics) = self.r.struct_generics.get(&local_def_id)
3425 && let Some(target_param) = &struct_generics.params.get(idx)
3426 && let GenericParamKind::Const { ty, .. } = &target_param.kind
3427 && let TyKind::Path(_, path) = &ty.kind
3428 {
3429 let full_type = path
3430 .segments
3431 .iter()
3432 .map(|seg| seg.ident.to_string())
3433 .collect::<Vec<_>>()
3434 .join("::");
3435
3436 let next_impl_param = impl_.generics.params.iter().find(|impl_param| {
3441 angle
3442 .args
3443 .iter()
3444 .find_map(|arg| {
3445 if let AngleBracketedArg::Arg(GenericArg::Type(ty)) = arg
3446 && let TyKind::Path(_, path) = &ty.kind
3447 && let [segment] = path.segments.as_slice()
3448 && segment.ident == impl_param.ident
3449 {
3450 usage_to_pos.get(&segment.id).copied()
3451 } else {
3452 None
3453 }
3454 })
3455 .map_or(false, |pos| pos > idx)
3456 });
3457
3458 let (insert_span, snippet) = match next_impl_param {
3459 Some(next_param) => {
3460 (
3463 next_param.span().shrink_to_lo(),
3464 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("const {0}: {1}, ", target_ident,
full_type))
})format!("const {}: {}, ", target_ident, full_type),
3465 )
3466 }
3467 None => match impl_.generics.params.last() {
3468 Some(last) => {
3469 (
3472 last.span().shrink_to_hi(),
3473 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", const {0}: {1}", target_ident,
full_type))
})format!(", const {}: {}", target_ident, full_type),
3474 )
3475 }
3476 None => {
3477 (
3480 impl_.generics.span.shrink_to_hi(),
3481 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<const {0}: {1}>", target_ident,
full_type))
})format!("<const {}: {}>", target_ident, full_type),
3482 )
3483 }
3484 },
3485 };
3486
3487 let mut err = self.r.dcx().struct_span_err(
3488 target_ident.span,
3489 ::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),
3490 );
3491
3492 err.code(E0425);
3493
3494 err.span_label(target_ident.span, "not found in this scope");
3495
3496 err.span_label(
3497 target_param.span(),
3498 ::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",),
3499 );
3500
3501 err.subdiagnostic(diagnostics::UnexpectedMissingConstParameter {
3502 span: insert_span,
3503 snippet,
3504 item_name: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", target_ident))
})format!("{}", target_ident),
3505 item_location: String::from("impl"),
3506 });
3507
3508 return Some(err);
3509 }
3510
3511 None
3512 }
3513
3514 pub(crate) fn suggest_adding_generic_parameter(
3515 &mut self,
3516 path: &[Segment],
3517 source: PathSource<'_, 'ast, 'ra>,
3518 ) -> (Option<(Span, &'static str, String, Applicability)>, Option<Diag<'tcx>>) {
3519 let (ident, span) = match path {
3520 [segment]
3521 if !segment.has_generic_args
3522 && segment.ident.name != kw::SelfUpper
3523 && segment.ident.name != kw::Dyn =>
3524 {
3525 (segment.ident.to_string(), segment.ident.span)
3526 }
3527 _ => return (None, None),
3528 };
3529 let mut iter = ident.chars().map(|c| c.is_uppercase());
3530 let single_uppercase_char =
3531 #[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);
3532 if !self.diag_metadata.currently_processing_generic_args && !single_uppercase_char {
3533 return (None, None);
3534 }
3535 match (
3536 self.diag_metadata.current_item,
3537 single_uppercase_char,
3538 self.diag_metadata.currently_processing_generic_args,
3539 ) {
3540 (Some(Item { kind: ItemKind::Fn(fn_), .. }), _, _) if fn_.ident.name == sym::main => {
3541 }
3543 (
3544 Some(Item {
3545 kind:
3546 kind @ ItemKind::Fn(..)
3547 | kind @ ItemKind::Enum(..)
3548 | kind @ ItemKind::Struct(..)
3549 | kind @ ItemKind::Union(..),
3550 ..
3551 }),
3552 true,
3553 _,
3554 )
3555 | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true)
3557 | (Some(Item { kind, .. }), false, _) => {
3558 if let Some(generics) = kind.generics() {
3559 if span.overlaps(generics.span) {
3560 return (None, None);
3569 }
3570
3571 let (msg, sugg) = match source {
3572 PathSource::Type | PathSource::PreciseCapturingArg(TypeNS) => {
3573 if let Some(err) =
3574 self.detect_and_suggest_const_parameter_error(path, source)
3575 {
3576 return (None, Some(err));
3577 }
3578 ("you might be missing a type parameter", ident)
3579 }
3580 PathSource::Expr(_) | PathSource::PreciseCapturingArg(ValueNS) => (
3581 "you might be missing a const parameter",
3582 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("const {0}: /* Type */", ident))
})format!("const {ident}: /* Type */"),
3583 ),
3584 _ => return (None, None),
3585 };
3586 let (span, sugg) = if let [.., param] = &generics.params[..] {
3587 let span = if let [.., bound] = ¶m.bounds[..] {
3588 bound.span()
3589 } else if let GenericParam {
3590 kind: GenericParamKind::Const { ty, span: _, default },
3591 ..
3592 } = param
3593 {
3594 default.as_ref().map(|def| def.value.span).unwrap_or(ty.span)
3595 } else {
3596 param.ident.span
3597 };
3598 (span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", {0}", sugg))
})format!(", {sugg}"))
3599 } else {
3600 (generics.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", sugg))
})format!("<{sugg}>"))
3601 };
3602 if span.can_be_used_for_suggestions() {
3604 return (
3605 Some((span.shrink_to_hi(), msg, sugg, Applicability::MaybeIncorrect)),
3606 None,
3607 );
3608 }
3609 }
3610 }
3611 _ => {}
3612 }
3613 (None, None)
3614 }
3615
3616 pub(crate) fn suggestion_for_label_in_rib(
3619 &self,
3620 rib_index: usize,
3621 label: Ident,
3622 ) -> Option<LabelSuggestion> {
3623 let within_scope = self.is_label_valid_from_rib(rib_index);
3625
3626 let rib = &self.label_ribs[rib_index];
3627 let names = rib
3628 .bindings
3629 .iter()
3630 .filter(|(id, _)| id.span.eq_ctxt(label.span))
3631 .map(|(id, _)| id.name)
3632 .collect::<Vec<Symbol>>();
3633
3634 find_best_match_for_name(&names, label.name, None).map(|symbol| {
3635 let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
3639 (*ident, within_scope)
3640 })
3641 }
3642
3643 pub(crate) fn maybe_report_lifetime_uses(
3644 &mut self,
3645 generics_span: Span,
3646 params: &[ast::GenericParam],
3647 ) {
3648 for (param_index, param) in params.iter().enumerate() {
3649 let GenericParamKind::Lifetime = param.kind else { continue };
3650
3651 let def_id = self.r.local_def_id(param.id);
3652
3653 let use_set = self.lifetime_uses.remove(&def_id);
3654 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_resolve/src/late/diagnostics.rs:3654",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3654u32),
::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!(
3655 "Use set for {:?}({:?} at {:?}) is {:?}",
3656 def_id, param.ident, param.ident.span, use_set
3657 );
3658
3659 let deletion_span = || {
3660 if params.len() == 1 {
3661 Some(generics_span)
3663 } else if param_index == 0 {
3664 match (
3667 param.span().find_ancestor_inside(generics_span),
3668 params[param_index + 1].span().find_ancestor_inside(generics_span),
3669 ) {
3670 (Some(param_span), Some(next_param_span)) => {
3671 Some(param_span.to(next_param_span.shrink_to_lo()))
3672 }
3673 _ => None,
3674 }
3675 } else {
3676 match (
3679 param.span().find_ancestor_inside(generics_span),
3680 params[param_index - 1].span().find_ancestor_inside(generics_span),
3681 ) {
3682 (Some(param_span), Some(prev_param_span)) => {
3683 Some(prev_param_span.shrink_to_hi().to(param_span))
3684 }
3685 _ => None,
3686 }
3687 }
3688 };
3689 match use_set {
3690 Some(LifetimeUseSet::Many) => {}
3691 Some(LifetimeUseSet::One { .. }) if !param.bounds.is_empty() => {}
3694 Some(LifetimeUseSet::One { use_span, use_ctxt }) => {
3695 let param_ident = param.ident;
3696 let deletion_span =
3697 if param.bounds.is_empty() { deletion_span() } else { None };
3698 self.r.lint_buffer.dyn_buffer_lint_any(
3699 SINGLE_USE_LIFETIMES,
3700 param.id,
3701 param_ident.span,
3702 move |dcx, level, sess| {
3703 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_resolve/src/late/diagnostics.rs:3703",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3703u32),
::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);
3704
3705 let elidable = #[allow(non_exhaustive_omitted_patterns)] match use_ctxt {
LifetimeCtxt::Ref => true,
_ => false,
}matches!(use_ctxt, LifetimeCtxt::Ref);
3706 let suggestion = if let Some(deletion_span) = deletion_span {
3707 let (use_span, replace_lt) = if elidable {
3708 let use_span = sess
3709 .downcast_ref::<Session>()
3710 .expect("expected a `Session`")
3711 .source_map()
3712 .span_extend_while_whitespace(use_span);
3713 (use_span, String::new())
3714 } else {
3715 (use_span, "'_".to_owned())
3716 };
3717 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_resolve/src/late/diagnostics.rs:3717",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3717u32),
::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);
3718
3719 let deletion_span = if deletion_span.is_empty() {
3722 None
3723 } else {
3724 Some(deletion_span)
3725 };
3726 Some(diagnostics::SingleUseLifetimeSugg {
3727 deletion_span,
3728 use_span,
3729 replace_lt,
3730 })
3731 } else {
3732 None
3733 };
3734 diagnostics::SingleUseLifetime {
3735 suggestion,
3736 param_span: param_ident.span,
3737 use_span,
3738 ident: param_ident,
3739 }
3740 .into_diag(dcx, level)
3741 },
3742 );
3743 }
3744 None => {
3745 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_resolve/src/late/diagnostics.rs:3745",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3745u32),
::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);
3746 let deletion_span = deletion_span();
3747
3748 if deletion_span.is_some_and(|sp| !sp.in_derive_expansion()) {
3750 self.r.lint_buffer.buffer_lint(
3751 UNUSED_LIFETIMES,
3752 param.id,
3753 param.ident.span,
3754 diagnostics::UnusedLifetime { deletion_span, ident: param.ident },
3755 );
3756 }
3757 }
3758 }
3759 }
3760 }
3761
3762 pub(crate) fn emit_undeclared_lifetime_error(
3763 &self,
3764 lifetime_ref: &ast::Lifetime,
3765 outer_lifetime_ref: Option<Ident>,
3766 ) -> ErrorGuaranteed {
3767 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);
3768 let mut err = if let Some(outer) = outer_lifetime_ref {
3769 {
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!(
3770 self.r.dcx(),
3771 lifetime_ref.ident.span,
3772 E0401,
3773 "can't use generic parameters from outer item",
3774 )
3775 .with_span_label(lifetime_ref.ident.span, "use of generic parameter from outer item")
3776 .with_span_label(outer.span, "lifetime parameter from outer item")
3777 } else {
3778 {
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!(
3779 self.r.dcx(),
3780 lifetime_ref.ident.span,
3781 E0261,
3782 "use of undeclared lifetime name `{}`",
3783 lifetime_ref.ident
3784 )
3785 .with_span_label(lifetime_ref.ident.span, "undeclared lifetime")
3786 };
3787
3788 if edit_distance(lifetime_ref.ident.name.as_str(), "'static", 2).is_some() {
3790 err.span_suggestion_verbose(
3791 lifetime_ref.ident.span,
3792 "you may have misspelled the `'static` lifetime",
3793 "'static",
3794 Applicability::MachineApplicable,
3795 );
3796 } else {
3797 self.suggest_introducing_lifetime(
3798 &mut err,
3799 Some(lifetime_ref.ident),
3800 |err, _, span, message, suggestion, span_suggs| {
3801 err.multipart_suggestion(
3802 message,
3803 std::iter::once((span, suggestion)).chain(span_suggs).collect(),
3804 Applicability::MaybeIncorrect,
3805 );
3806 true
3807 },
3808 );
3809 }
3810
3811 err.emit()
3812 }
3813
3814 fn suggest_introducing_lifetime(
3815 &self,
3816 err: &mut Diag<'_>,
3817 name: Option<Ident>,
3818 suggest: impl Fn(
3819 &mut Diag<'_>,
3820 bool,
3821 Span,
3822 Cow<'static, str>,
3823 String,
3824 Vec<(Span, String)>,
3825 ) -> bool,
3826 ) {
3827 self.suggest_introducing_lifetime_filtered(err, name, |_| true, suggest);
3828 }
3829
3830 pub(crate) fn suggest_introducing_lifetime_for_assoc_ty_binding(
3831 &self,
3832 err: &mut Diag<'_>,
3833 lifetime: Span,
3834 ) {
3835 self.suggest_introducing_lifetime_filtered(
3836 err,
3837 None,
3838 |kind| {
3839 !#[allow(non_exhaustive_omitted_patterns)] match kind {
LifetimeBinderKind::FnPtrType | LifetimeBinderKind::PolyTrait |
LifetimeBinderKind::WhereBound => true,
_ => false,
}matches!(
3840 kind,
3841 LifetimeBinderKind::FnPtrType
3842 | LifetimeBinderKind::PolyTrait
3843 | LifetimeBinderKind::WhereBound
3844 )
3845 },
3846 |err, _higher_ranked, span, message, intro_sugg, _| {
3847 err.multipart_suggestion(
3848 message,
3849 ::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())],
3850 Applicability::MaybeIncorrect,
3851 );
3852 false
3853 },
3854 );
3855 }
3856
3857 fn suggest_introducing_lifetime_filtered(
3858 &self,
3859 err: &mut Diag<'_>,
3860 name: Option<Ident>,
3861 mut consider: impl FnMut(LifetimeBinderKind) -> bool,
3862 suggest: impl Fn(
3863 &mut Diag<'_>,
3864 bool,
3865 Span,
3866 Cow<'static, str>,
3867 String,
3868 Vec<(Span, String)>,
3869 ) -> bool,
3870 ) {
3871 let mut suggest_note = true;
3872 for rib in self.lifetime_ribs.iter().rev() {
3873 let mut should_continue = true;
3874 match rib.kind {
3875 LifetimeRibKind::Generics { binder, span, kind } => {
3876 if let LifetimeBinderKind::ConstItem = kind
3879 && !self.r.tcx().features().generic_const_items()
3880 {
3881 continue;
3882 }
3883 if #[allow(non_exhaustive_omitted_patterns)] match kind {
LifetimeBinderKind::ImplAssocType => true,
_ => false,
}matches!(kind, LifetimeBinderKind::ImplAssocType) || !consider(kind) {
3884 continue;
3885 }
3886
3887 if !span.can_be_used_for_suggestions()
3888 && suggest_note
3889 && let Some(name) = name
3890 {
3891 suggest_note = false; err.span_label(
3893 span,
3894 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("lifetime `{0}` is missing in item created through this procedural macro",
name))
})format!(
3895 "lifetime `{name}` is missing in item created through this procedural macro",
3896 ),
3897 );
3898 continue;
3899 }
3900
3901 let higher_ranked = #[allow(non_exhaustive_omitted_patterns)] match kind {
LifetimeBinderKind::FnPtrType | LifetimeBinderKind::PolyTrait |
LifetimeBinderKind::WhereBound => true,
_ => false,
}matches!(
3902 kind,
3903 LifetimeBinderKind::FnPtrType
3904 | LifetimeBinderKind::PolyTrait
3905 | LifetimeBinderKind::WhereBound
3906 );
3907
3908 let mut rm_inner_binders: FxIndexSet<Span> = Default::default();
3909 let (span, sugg) = if span.is_empty() {
3910 let mut binder_idents: FxIndexSet<Ident> = Default::default();
3911 binder_idents.insert(name.unwrap_or(Ident::from_str("'a")));
3912
3913 if let LifetimeBinderKind::WhereBound = kind
3920 && let Some(predicate) = self.diag_metadata.current_where_predicate
3921 && let ast::WherePredicateKind::BoundPredicate(
3922 ast::WhereBoundPredicate { bounded_ty, bounds, .. },
3923 ) = &predicate.kind
3924 && bounded_ty.id == binder
3925 {
3926 for bound in bounds {
3927 if let ast::GenericBound::Trait(poly_trait_ref) = bound
3928 && let span = poly_trait_ref
3929 .span
3930 .with_hi(poly_trait_ref.trait_ref.path.span.lo())
3931 && !span.is_empty()
3932 {
3933 rm_inner_binders.insert(span);
3934 poly_trait_ref.bound_generic_params.iter().for_each(|v| {
3935 binder_idents.insert(v.ident);
3936 });
3937 }
3938 }
3939 }
3940
3941 let binders_sugg: String = binder_idents
3942 .into_iter()
3943 .map(|ident| ident.to_string())
3944 .intersperse(", ".to_owned())
3945 .collect();
3946 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!(
3947 "{}<{}>{}",
3948 if higher_ranked { "for" } else { "" },
3949 binders_sugg,
3950 if higher_ranked { " " } else { "" },
3951 );
3952 (span, sugg)
3953 } else {
3954 let span = self
3955 .r
3956 .tcx
3957 .sess
3958 .source_map()
3959 .span_through_char(span, '<')
3960 .shrink_to_hi();
3961 let sugg =
3962 ::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"));
3963 (span, sugg)
3964 };
3965
3966 if higher_ranked {
3967 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!(
3968 "consider making the {} lifetime-generic with a new `{}` lifetime",
3969 kind.descr(),
3970 name.map(|i| i.to_string()).as_deref().unwrap_or("'a"),
3971 ));
3972 should_continue = suggest(
3973 err,
3974 true,
3975 span,
3976 message,
3977 sugg,
3978 if !rm_inner_binders.is_empty() {
3979 rm_inner_binders
3980 .into_iter()
3981 .map(|v| (v, "".to_string()))
3982 .collect::<Vec<_>>()
3983 } else {
3984 ::alloc::vec::Vec::new()vec![]
3985 },
3986 );
3987 err.note_once(
3988 "for more information on higher-ranked polymorphism, visit \
3989 https://doc.rust-lang.org/nomicon/hrtb.html",
3990 );
3991 } else if let Some(name) = name {
3992 let message =
3993 Cow::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider introducing lifetime `{0}` here",
name))
})format!("consider introducing lifetime `{name}` here"));
3994 should_continue = suggest(err, false, span, message, sugg, ::alloc::vec::Vec::new()vec![]);
3995 } else {
3996 let message = Cow::from("consider introducing a named lifetime parameter");
3997 should_continue = suggest(err, false, span, message, sugg, ::alloc::vec::Vec::new()vec![]);
3998 }
3999 }
4000 LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy => break,
4001 _ => {}
4002 }
4003 if !should_continue {
4004 break;
4005 }
4006 }
4007 }
4008
4009 pub(crate) fn emit_non_static_lt_in_const_param_ty_error(
4010 &self,
4011 lifetime_ref: &ast::Lifetime,
4012 ) -> ErrorGuaranteed {
4013 self.r
4014 .dcx()
4015 .create_err(diagnostics::ParamInTyOfConstParam {
4016 span: lifetime_ref.ident.span,
4017 name: lifetime_ref.ident.name,
4018 })
4019 .emit()
4020 }
4021
4022 pub(crate) fn emit_forbidden_non_static_lifetime_error(
4026 &self,
4027 cause: NoConstantGenericsReason,
4028 lifetime_ref: &ast::Lifetime,
4029 ) -> ErrorGuaranteed {
4030 match cause {
4031 NoConstantGenericsReason::IsEnumDiscriminant => self
4032 .r
4033 .dcx()
4034 .create_err(diagnostics::ParamInEnumDiscriminant {
4035 span: lifetime_ref.ident.span,
4036 name: lifetime_ref.ident.name,
4037 param_kind: diagnostics::ParamKindInEnumDiscriminant::Lifetime,
4038 })
4039 .emit(),
4040 NoConstantGenericsReason::NonTrivialConstArg => {
4041 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());
4042 self.r
4043 .dcx()
4044 .create_err(diagnostics::ParamInNonTrivialAnonConst {
4045 span: lifetime_ref.ident.span,
4046 name: lifetime_ref.ident.name,
4047 param_kind: diagnostics::ParamKindInNonTrivialAnonConst::Lifetime,
4048 help: self.r.tcx.sess.is_nightly_build()
4049 && !self.r.features.min_generic_const_args(),
4050 is_gca: self.r.features.generic_const_args(),
4051 help_gca: self.r.features.generic_const_args(),
4052 help_suggest_gca: self.r.tcx.sess.is_nightly_build()
4053 && !self.r.features.generic_const_args(),
4054 })
4055 .emit()
4056 }
4057 }
4058 }
4059
4060 pub(crate) fn report_missing_lifetime_specifiers<'a>(
4061 &mut self,
4062 lifetime_refs: impl Clone + IntoIterator<Item = &'a MissingLifetime>,
4063 function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
4064 ) -> ErrorGuaranteed {
4065 let num_lifetimes: usize = lifetime_refs.clone().into_iter().map(|lt| lt.count).sum();
4066 let spans: Vec<_> = lifetime_refs.clone().into_iter().map(|lt| lt.span).collect();
4067
4068 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!(
4069 self.r.dcx(),
4070 spans,
4071 E0106,
4072 "missing lifetime specifier{}",
4073 pluralize!(num_lifetimes)
4074 );
4075 self.add_missing_lifetime_specifiers_label(
4076 &mut err,
4077 lifetime_refs,
4078 function_param_lifetimes,
4079 );
4080 err.emit()
4081 }
4082
4083 fn add_missing_lifetime_specifiers_label<'a>(
4084 &mut self,
4085 err: &mut Diag<'_>,
4086 lifetime_refs: impl Clone + IntoIterator<Item = &'a MissingLifetime>,
4087 function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
4088 ) {
4089 for < in lifetime_refs.clone() {
4090 err.span_label(
4091 lt.span,
4092 ::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!(
4093 "expected {} lifetime parameter{}",
4094 if lt.count == 1 { "named".to_string() } else { lt.count.to_string() },
4095 pluralize!(lt.count),
4096 ),
4097 );
4098 }
4099
4100 let mut in_scope_lifetimes: Vec<_> = self
4101 .lifetime_ribs
4102 .iter()
4103 .rev()
4104 .take_while(|rib| {
4105 !#[allow(non_exhaustive_omitted_patterns)] match rib.kind {
LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy => true,
_ => false,
}matches!(rib.kind, LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy)
4106 })
4107 .flat_map(|rib| rib.bindings.iter())
4108 .map(|(&ident, &res)| (ident, res))
4109 .filter(|(ident, _)| ident.name != kw::UnderscoreLifetime)
4110 .collect();
4111 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_resolve/src/late/diagnostics.rs:4111",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(4111u32),
::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);
4112
4113 let mut maybe_static = false;
4114 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_resolve/src/late/diagnostics.rs:4114",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(4114u32),
::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);
4115 if let Some((param_lifetimes, params)) = &function_param_lifetimes {
4116 let elided_len = param_lifetimes.len();
4117 let num_params = params.len();
4118
4119 let mut m = String::new();
4120
4121 for (i, info) in params.iter().enumerate() {
4122 let ElisionFnParameter { ident, index, lifetime_count, span } = *info;
4123 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);
4124
4125 err.span_label(span, "");
4126
4127 if i != 0 {
4128 if i + 1 < num_params {
4129 m.push_str(", ");
4130 } else if num_params == 2 {
4131 m.push_str(" or ");
4132 } else {
4133 m.push_str(", or ");
4134 }
4135 }
4136
4137 let help_name = if let Some(ident) = ident {
4138 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", ident))
})format!("`{ident}`")
4139 } else {
4140 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("argument {0}", index + 1))
})format!("argument {}", index + 1)
4141 };
4142
4143 if lifetime_count == 1 {
4144 m.push_str(&help_name[..])
4145 } else {
4146 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")[..])
4147 }
4148 }
4149
4150 if num_params == 0 {
4151 err.help(
4152 "this function's return type contains a borrowed value, but there is no value \
4153 for it to be borrowed from",
4154 );
4155 if in_scope_lifetimes.is_empty() {
4156 maybe_static = true;
4157 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![(
4158 Ident::with_dummy_span(kw::StaticLifetime),
4159 (DUMMY_NODE_ID, LifetimeRes::Static),
4160 )];
4161 }
4162 } else if elided_len == 0 {
4163 err.help(
4164 "this function's return type contains a borrowed value with an elided \
4165 lifetime, but the lifetime cannot be derived from the arguments",
4166 );
4167 if in_scope_lifetimes.is_empty() {
4168 maybe_static = true;
4169 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![(
4170 Ident::with_dummy_span(kw::StaticLifetime),
4171 (DUMMY_NODE_ID, LifetimeRes::Static),
4172 )];
4173 }
4174 } else if num_params == 1 {
4175 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!(
4176 "this function's return type contains a borrowed value, but the signature does \
4177 not say which {m} it is borrowed from",
4178 ));
4179 } else {
4180 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!(
4181 "this function's return type contains a borrowed value, but the signature does \
4182 not say whether it is borrowed from {m}",
4183 ));
4184 }
4185 }
4186
4187 #[allow(rustc::symbol_intern_string_literal)]
4188 let existing_name = match &in_scope_lifetimes[..] {
4189 [] => Symbol::intern("'a"),
4190 [(existing, _)] => existing.name,
4191 _ => Symbol::intern("'lifetime"),
4192 };
4193
4194 let mut spans_suggs: Vec<_> = Vec::new();
4195 let source_map = self.r.tcx.sess.source_map();
4196 let build_sugg = |lt: MissingLifetime| match lt.kind {
4197 MissingLifetimeKind::Underscore => {
4198 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);
4199 (lt.span, existing_name.to_string())
4200 }
4201 MissingLifetimeKind::Ampersand => {
4202 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);
4203 (lt.span.shrink_to_hi(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} ", existing_name))
})format!("{existing_name} "))
4204 }
4205 MissingLifetimeKind::Comma => {
4206 let sugg: String = std::iter::repeat_n(existing_name.as_str(), lt.count)
4207 .intersperse(", ")
4208 .collect();
4209 let is_empty_brackets = source_map.span_followed_by(lt.span, ">").is_some();
4210 let sugg = if is_empty_brackets { sugg } else { ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, ", sugg))
})format!("{sugg}, ") };
4211 (lt.span.shrink_to_hi(), sugg)
4212 }
4213 MissingLifetimeKind::Brackets => {
4214 let sugg: String = std::iter::once("<")
4215 .chain(std::iter::repeat_n(existing_name.as_str(), lt.count).intersperse(", "))
4216 .chain([">"])
4217 .collect();
4218 (lt.span.shrink_to_hi(), sugg)
4219 }
4220 };
4221 for < in lifetime_refs.clone() {
4222 spans_suggs.push(build_sugg(lt));
4223 }
4224 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_resolve/src/late/diagnostics.rs:4224",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(4224u32),
::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);
4225 match in_scope_lifetimes.len() {
4226 0 => {
4227 if let Some((param_lifetimes, _)) = function_param_lifetimes {
4228 for lt in param_lifetimes {
4229 spans_suggs.push(build_sugg(lt))
4230 }
4231 }
4232 self.suggest_introducing_lifetime(
4233 err,
4234 None,
4235 |err, higher_ranked, span, message, intro_sugg, _| {
4236 err.multipart_suggestion(
4237 message,
4238 std::iter::once((span, intro_sugg))
4239 .chain(spans_suggs.clone())
4240 .collect(),
4241 Applicability::MaybeIncorrect,
4242 );
4243 higher_ranked
4244 },
4245 );
4246 }
4247 1 => {
4248 let post = if maybe_static {
4249 let mut lifetime_refs = lifetime_refs.clone().into_iter();
4250 let owned = if let Some(lt) = lifetime_refs.next()
4251 && lifetime_refs.next().is_none()
4252 && lt.kind != MissingLifetimeKind::Ampersand
4253 {
4254 ", or if you will only have owned values"
4255 } else {
4256 ""
4257 };
4258 ::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!(
4259 ", but this is uncommon unless you're returning a borrowed value from a \
4260 `const` or a `static`{owned}",
4261 )
4262 } else {
4263 String::new()
4264 };
4265 err.multipart_suggestion(
4266 ::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}"),
4267 spans_suggs,
4268 Applicability::MaybeIncorrect,
4269 );
4270 if maybe_static {
4271 let mut lifetime_refs = lifetime_refs.into_iter();
4277 if let Some(lt) = lifetime_refs.next()
4278 && lifetime_refs.next().is_none()
4279 && (lt.kind == MissingLifetimeKind::Ampersand
4280 || lt.kind == MissingLifetimeKind::Underscore)
4281 {
4282 let pre = if let Some((kind, _span)) = self.diag_metadata.current_function
4283 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
4284 && !sig.decl.inputs.is_empty()
4285 && let sugg = sig
4286 .decl
4287 .inputs
4288 .iter()
4289 .filter_map(|param| {
4290 if param.ty.span.contains(lt.span) {
4291 None
4294 } else if let TyKind::CVarArgs = param.ty.kind {
4295 None
4297 } else if let TyKind::ImplTrait(..) = ¶m.ty.kind {
4298 None
4300 } else {
4301 Some((param.ty.span.shrink_to_lo(), "&".to_string()))
4302 }
4303 })
4304 .collect::<Vec<_>>()
4305 && !sugg.is_empty()
4306 {
4307 let (the, s) = if sig.decl.inputs.len() == 1 {
4308 ("the", "")
4309 } else {
4310 ("one of the", "s")
4311 };
4312 let dotdotdot =
4313 if lt.kind == MissingLifetimeKind::Ampersand { "..." } else { "" };
4314 err.multipart_suggestion(
4315 ::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!(
4316 "instead, you are more likely to want to change {the} \
4317 argument{s} to be borrowed{dotdotdot}",
4318 ),
4319 sugg,
4320 Applicability::MaybeIncorrect,
4321 );
4322 "...or alternatively, you might want"
4323 } else if (lt.kind == MissingLifetimeKind::Ampersand
4324 || lt.kind == MissingLifetimeKind::Underscore)
4325 && let Some((kind, _span)) = self.diag_metadata.current_function
4326 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
4327 && let ast::FnRetTy::Ty(ret_ty) = &sig.decl.output
4328 && !sig.decl.inputs.is_empty()
4329 && let arg_refs = sig
4330 .decl
4331 .inputs
4332 .iter()
4333 .filter_map(|param| match ¶m.ty.kind {
4334 TyKind::ImplTrait(_, bounds) => Some(bounds),
4335 _ => None,
4336 })
4337 .flat_map(|bounds| bounds.into_iter())
4338 .collect::<Vec<_>>()
4339 && !arg_refs.is_empty()
4340 {
4341 let mut lt_finder =
4347 LifetimeFinder { lifetime: lt.span, found: None, seen: ::alloc::vec::Vec::new()vec![] };
4348 for bound in arg_refs {
4349 if let ast::GenericBound::Trait(trait_ref) = bound {
4350 lt_finder.visit_trait_ref(&trait_ref.trait_ref);
4351 }
4352 }
4353 lt_finder.visit_ty(ret_ty);
4354 let spans_suggs: Vec<_> = lt_finder
4355 .seen
4356 .iter()
4357 .filter_map(|ty| match &ty.kind {
4358 TyKind::Ref(_, mut_ty) => {
4359 let span = ty.span.with_hi(mut_ty.ty.span.lo());
4360 Some((span, "&'a ".to_string()))
4361 }
4362 _ => None,
4363 })
4364 .collect();
4365 self.suggest_introducing_lifetime(
4366 err,
4367 None,
4368 |err, higher_ranked, span, message, intro_sugg, _| {
4369 err.multipart_suggestion(
4370 message,
4371 std::iter::once((span, intro_sugg))
4372 .chain(spans_suggs.clone())
4373 .collect(),
4374 Applicability::MaybeIncorrect,
4375 );
4376 higher_ranked
4377 },
4378 );
4379 "alternatively, you might want"
4380 } else {
4381 "instead, you are more likely to want"
4382 };
4383 let mut owned_sugg = lt.kind == MissingLifetimeKind::Ampersand;
4384 let mut sugg_slice_to_vec_or_string = false;
4385 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())];
4386 if let Some((kind, _span)) = self.diag_metadata.current_function
4387 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
4388 {
4389 let mut lt_finder =
4390 LifetimeFinder { lifetime: lt.span, found: None, seen: ::alloc::vec::Vec::new()vec![] };
4391 for param in &sig.decl.inputs {
4392 lt_finder.visit_ty(¶m.ty);
4393 }
4394 if let ast::FnRetTy::Ty(ret_ty) = &sig.decl.output {
4395 lt_finder.visit_ty(ret_ty);
4396 let mut ret_lt_finder =
4397 LifetimeFinder { lifetime: lt.span, found: None, seen: ::alloc::vec::Vec::new()vec![] };
4398 ret_lt_finder.visit_ty(ret_ty);
4399 if let [Ty { span, kind: TyKind::Ref(_, mut_ty), .. }] =
4400 &ret_lt_finder.seen[..]
4401 {
4402 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())];
4408 owned_sugg = true;
4409 }
4410 }
4411 if let Some(ty) = lt_finder.found {
4412 if let TyKind::Path(None, path) = &ty.kind {
4413 let path: Vec<_> = Segment::from_path(path);
4415 match self.resolve_path(
4416 &path,
4417 Some(TypeNS),
4418 None,
4419 PathSource::Type,
4420 ) {
4421 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
4422 match module.res() {
4423 Some(Res::PrimTy(PrimTy::Str)) => {
4424 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![(
4426 lt.span.with_hi(ty.span.hi()),
4427 "String".to_string(),
4428 )];
4429 sugg_slice_to_vec_or_string = true;
4430 }
4431 Some(Res::PrimTy(..)) => {}
4432 Some(Res::Def(
4433 DefKind::Struct
4434 | DefKind::Union
4435 | DefKind::Enum
4436 | DefKind::ForeignTy
4437 | DefKind::AssocTy
4438 | DefKind::OpaqueTy
4439 | DefKind::TyParam,
4440 _,
4441 )) => {}
4442 _ => {
4443 owned_sugg = false;
4445 }
4446 }
4447 }
4448 PathResult::NonModule(res) => {
4449 match res.base_res() {
4450 Res::PrimTy(PrimTy::Str) => {
4451 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![(
4453 lt.span.with_hi(ty.span.hi()),
4454 "String".to_string(),
4455 )];
4456 sugg_slice_to_vec_or_string = true;
4457 }
4458 Res::PrimTy(..) => {}
4459 Res::Def(
4460 DefKind::Struct
4461 | DefKind::Union
4462 | DefKind::Enum
4463 | DefKind::ForeignTy
4464 | DefKind::AssocTy
4465 | DefKind::OpaqueTy
4466 | DefKind::TyParam,
4467 _,
4468 ) => {}
4469 _ => {
4470 owned_sugg = false;
4472 }
4473 }
4474 }
4475 _ => {
4476 owned_sugg = false;
4478 }
4479 }
4480 }
4481 if let TyKind::Slice(inner_ty) = &ty.kind {
4482 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![
4484 (lt.span.with_hi(inner_ty.span.lo()), "Vec<".to_string()),
4485 (ty.span.with_lo(inner_ty.span.hi()), ">".to_string()),
4486 ];
4487 sugg_slice_to_vec_or_string = true;
4488 }
4489 }
4490 }
4491 if owned_sugg {
4492 if let Some(span) =
4494 self.find_ref_prefix_span_for_owned_suggestion(lt.span)
4495 && !sugg_slice_to_vec_or_string
4496 {
4497 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())];
4498 }
4499 err.multipart_suggestion(
4500 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} to return an owned value",
pre))
})format!("{pre} to return an owned value"),
4501 sugg,
4502 Applicability::MaybeIncorrect,
4503 );
4504 }
4505 }
4506 }
4507 }
4508 _ => {
4509 let lifetime_spans: Vec<_> =
4510 in_scope_lifetimes.iter().map(|(ident, _)| ident.span).collect();
4511 err.span_note(lifetime_spans, "these named lifetimes are available to use");
4512
4513 if spans_suggs.len() > 0 {
4514 err.multipart_suggestion(
4517 "consider using one of the available lifetimes here",
4518 spans_suggs,
4519 Applicability::HasPlaceholders,
4520 );
4521 }
4522 }
4523 }
4524 }
4525
4526 fn find_ref_prefix_span_for_owned_suggestion(&self, lifetime: Span) -> Option<Span> {
4527 let mut finder = RefPrefixSpanFinder { lifetime, span: None };
4528 if let Some(item) = self.diag_metadata.current_item {
4529 finder.visit_item(item);
4530 } else if let Some((kind, _span)) = self.diag_metadata.current_function
4531 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
4532 {
4533 for param in &sig.decl.inputs {
4534 finder.visit_ty(¶m.ty);
4535 }
4536 if let ast::FnRetTy::Ty(ret_ty) = &sig.decl.output {
4537 finder.visit_ty(ret_ty);
4538 }
4539 }
4540 finder.span
4541 }
4542}
4543
4544fn mk_where_bound_predicate(
4545 path: &Path,
4546 poly_trait_ref: &ast::PolyTraitRef,
4547 ty: &Ty,
4548) -> Option<ast::WhereBoundPredicate> {
4549 let modified_segments = {
4550 let mut segments = path.segments.clone();
4551 let [preceding @ .., second_last, last] = segments.as_mut_slice() else {
4552 return None;
4553 };
4554 let mut segments = ThinVec::from(preceding);
4555
4556 let added_constraint = ast::AngleBracketedArg::Constraint(ast::AssocItemConstraint {
4557 id: DUMMY_NODE_ID,
4558 ident: last.ident,
4559 gen_args: None,
4560 kind: ast::AssocItemConstraintKind::Equality {
4561 term: ast::Term::Ty(Box::new(ast::Ty {
4562 kind: ast::TyKind::Path(None, poly_trait_ref.trait_ref.path.clone()),
4563 id: DUMMY_NODE_ID,
4564 span: DUMMY_SP,
4565 })),
4566 },
4567 span: DUMMY_SP,
4568 });
4569
4570 match second_last.args.as_deref_mut() {
4571 Some(ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs { args, .. })) => {
4572 args.push(added_constraint);
4573 }
4574 Some(_) => return None,
4575 None => {
4576 second_last.args =
4577 Some(Box::new(ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs {
4578 args: ThinVec::from([added_constraint]),
4579 span: DUMMY_SP,
4580 })));
4581 }
4582 }
4583
4584 segments.push(second_last.clone());
4585 segments
4586 };
4587
4588 let new_where_bound_predicate = ast::WhereBoundPredicate {
4589 bound_generic_params: ThinVec::new(),
4590 bounded_ty: Box::new(ty.clone()),
4591 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 {
4592 bound_generic_params: ThinVec::new(),
4593 modifiers: ast::TraitBoundModifiers::NONE,
4594 trait_ref: ast::TraitRef {
4595 path: ast::Path { segments: modified_segments, span: DUMMY_SP },
4596 ref_id: DUMMY_NODE_ID,
4597 },
4598 span: DUMMY_SP,
4599 parens: ast::Parens::No,
4600 })],
4601 };
4602
4603 Some(new_where_bound_predicate)
4604}
4605
4606pub(super) fn signal_lifetime_shadowing(
4608 sess: &Session,
4609 orig: Ident,
4610 shadower: Ident,
4611) -> ErrorGuaranteed {
4612 {
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!(
4613 sess.dcx(),
4614 shadower.span,
4615 E0496,
4616 "lifetime name `{}` shadows a lifetime name that is already in scope",
4617 orig.name,
4618 )
4619 .with_span_label(orig.span, "first declared here")
4620 .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))
4621 .emit()
4622}
4623
4624struct LifetimeFinder<'ast> {
4625 lifetime: Span,
4626 found: Option<&'ast Ty>,
4627 seen: Vec<&'ast Ty>,
4628}
4629
4630impl<'ast> Visitor<'ast> for LifetimeFinder<'ast> {
4631 fn visit_ty(&mut self, t: &'ast Ty) {
4632 if let TyKind::Ref(_, mut_ty) | TyKind::PinnedRef(_, mut_ty) = &t.kind {
4633 self.seen.push(t);
4634 if t.span.lo() == self.lifetime.lo() {
4635 self.found = Some(&mut_ty.ty);
4636 }
4637 }
4638 walk_ty(self, t)
4639 }
4640}
4641
4642struct RefPrefixSpanFinder {
4643 lifetime: Span,
4644 span: Option<Span>,
4645}
4646
4647impl<'ast> Visitor<'ast> for RefPrefixSpanFinder {
4648 fn visit_ty(&mut self, t: &'ast Ty) {
4649 if self.span.is_some() {
4650 return;
4651 }
4652 if let TyKind::Ref(_, mut_ty) | TyKind::PinnedRef(_, mut_ty) = &t.kind
4653 && t.span.lo() == self.lifetime.lo()
4654 {
4655 self.span = Some(t.span.with_hi(mut_ty.ty.span.lo()));
4656 return;
4657 }
4658 walk_ty(self, t);
4659 }
4660}
4661
4662pub(super) fn signal_label_shadowing(sess: &Session, orig: Span, shadower: Ident) {
4665 let name = shadower.name;
4666 let shadower = shadower.span;
4667 sess.dcx()
4668 .struct_span_warn(
4669 shadower,
4670 ::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"),
4671 )
4672 .with_span_label(orig, "first declared here")
4673 .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"))
4674 .emit();
4675}
4676
4677struct ParentPathVisitor<'a> {
4678 target: Ident,
4679 parent: Option<&'a PathSegment>,
4680 stack: Vec<&'a Ty>,
4681}
4682
4683impl<'a> ParentPathVisitor<'a> {
4684 fn new(self_ty: &'a Ty, target: Ident) -> Self {
4685 let mut v = ParentPathVisitor { target, parent: None, stack: Vec::new() };
4686
4687 v.visit_ty(self_ty);
4688 v
4689 }
4690}
4691
4692impl<'a> Visitor<'a> for ParentPathVisitor<'a> {
4693 fn visit_ty(&mut self, ty: &'a Ty) {
4694 if self.parent.is_some() {
4695 return;
4696 }
4697
4698 self.stack.push(ty);
4700
4701 if let TyKind::Path(_, path) = &ty.kind
4702 && let [segment] = path.segments.as_slice()
4704 && segment.ident == self.target
4705 && let [.., parent_ty, _ty] = self.stack.as_slice()
4707 && let TyKind::Path(_, parent_path) = &parent_ty.kind
4708 {
4709 self.parent = parent_path.segments.first();
4710 }
4711
4712 walk_ty(self, ty);
4713
4714 self.stack.pop();
4715 }
4716}