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, AssocItemKind, DUMMY_NODE_ID, Expr, ExprKind, GenericParam, GenericParamKind,
10 Item, ItemKind, MethodCall, NodeId, Path, PathSegment, Ty, TyKind,
11};
12use rustc_ast_pretty::pprust::{path_to_string, where_bound_predicate_to_string};
13use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
14use rustc_errors::codes::*;
15use rustc_errors::{
16 Applicability, Diag, ErrorGuaranteed, MultiSpan, SuggestionStyle, pluralize,
17 struct_span_code_err,
18};
19use rustc_hir as hir;
20use rustc_hir::def::Namespace::{self, *};
21use rustc_hir::def::{self, CtorKind, CtorOf, DefKind, MacroKinds};
22use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
23use rustc_hir::{MissingLifetimeKind, PrimTy, find_attr};
24use rustc_middle::ty;
25use rustc_session::{Session, lint};
26use rustc_span::edit_distance::{edit_distance, find_best_match_for_name};
27use rustc_span::edition::Edition;
28use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym};
29use thin_vec::ThinVec;
30use tracing::debug;
31
32use super::NoConstantGenericsReason;
33use crate::diagnostics::{ImportSuggestion, LabelSuggestion, TypoSuggestion};
34use crate::late::{
35 AliasPossibility, LateResolutionVisitor, LifetimeBinderKind, LifetimeRes, LifetimeRibKind,
36 LifetimeUseSet, QSelf, RibKind,
37};
38use crate::ty::fast_reject::SimplifiedType;
39use crate::{
40 Module, ModuleKind, ModuleOrUniformRoot, ParentScope, PathResult, PathSource, Resolver,
41 ScopeSet, Segment, errors, path_names_to_string,
42};
43
44type Res = def::Res<ast::NodeId>;
45
46enum AssocSuggestion {
48 Field(Span),
49 MethodWithSelf { called: bool },
50 AssocFn { called: bool },
51 AssocType,
52 AssocConst,
53}
54
55impl AssocSuggestion {
56 fn action(&self) -> &'static str {
57 match self {
58 AssocSuggestion::Field(_) => "use the available field",
59 AssocSuggestion::MethodWithSelf { called: true } => {
60 "call the method with the fully-qualified path"
61 }
62 AssocSuggestion::MethodWithSelf { called: false } => {
63 "refer to the method with the fully-qualified path"
64 }
65 AssocSuggestion::AssocFn { called: true } => "call the associated function",
66 AssocSuggestion::AssocFn { called: false } => "refer to the associated function",
67 AssocSuggestion::AssocConst => "use the associated `const`",
68 AssocSuggestion::AssocType => "use the associated type",
69 }
70 }
71}
72
73fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
74 namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
75}
76
77fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
78 namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
79}
80
81fn path_to_string_without_assoc_item_bindings(path: &Path) -> String {
82 let mut path = path.clone();
83 for segment in &mut path.segments {
84 let mut remove_args = false;
85 if let Some(args) = segment.args.as_deref_mut()
86 && let ast::GenericArgs::AngleBracketed(angle_bracketed) = args
87 {
88 angle_bracketed.args.retain(|arg| #[allow(non_exhaustive_omitted_patterns)] match arg {
ast::AngleBracketedArg::Arg(_) => true,
_ => false,
}matches!(arg, ast::AngleBracketedArg::Arg(_)));
89 remove_args = angle_bracketed.args.is_empty();
90 }
91 if remove_args {
92 segment.args = None;
93 }
94 }
95 path_to_string(&path)
96}
97
98fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
100 let variant_path = &suggestion.path;
101 let variant_path_string = path_names_to_string(variant_path);
102
103 let path_len = suggestion.path.segments.len();
104 let enum_path = ast::Path {
105 span: suggestion.path.span,
106 segments: suggestion.path.segments[0..path_len - 1].iter().cloned().collect(),
107 tokens: None,
108 };
109 let enum_path_string = path_names_to_string(&enum_path);
110
111 (variant_path_string, enum_path_string)
112}
113
114#[derive(#[automatically_derived]
impl ::core::marker::Copy for MissingLifetime { }Copy, #[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::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 {
#[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> {
match ::core::cmp::PartialOrd::partial_cmp(&self.id, &other.id) {
::core::option::Option::Some(::core::cmp::Ordering::Equal) =>
match ::core::cmp::PartialOrd::partial_cmp(&self.id_for_lint,
&other.id_for_lint) {
::core::option::Option::Some(::core::cmp::Ordering::Equal)
=>
match ::core::cmp::PartialOrd::partial_cmp(&self.span,
&other.span) {
::core::option::Option::Some(::core::cmp::Ordering::Equal)
=>
match ::core::cmp::PartialOrd::partial_cmp(&self.kind,
&other.kind) {
::core::option::Option::Some(::core::cmp::Ordering::Equal)
=>
::core::cmp::PartialOrd::partial_cmp(&self.count,
&other.count),
cmp => cmp,
},
cmp => cmp,
},
cmp => cmp,
},
cmp => cmp,
}
}
}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)]
116pub(super) struct MissingLifetime {
117 pub id: NodeId,
119 pub id_for_lint: NodeId,
126 pub span: Span,
128 pub kind: MissingLifetimeKind,
130 pub count: usize,
132}
133
134#[derive(#[automatically_derived]
impl ::core::clone::Clone for ElisionFnParameter {
#[inline]
fn clone(&self) -> ElisionFnParameter {
ElisionFnParameter {
index: ::core::clone::Clone::clone(&self.index),
ident: ::core::clone::Clone::clone(&self.ident),
lifetime_count: ::core::clone::Clone::clone(&self.lifetime_count),
span: ::core::clone::Clone::clone(&self.span),
}
}
}Clone, #[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)]
137pub(super) struct ElisionFnParameter {
138 pub index: usize,
140 pub ident: Option<Ident>,
142 pub lifetime_count: usize,
144 pub span: Span,
146}
147
148#[derive(#[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::Named =>
::core::fmt::Formatter::write_str(f, "Named"),
LifetimeElisionCandidate::Missing(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Missing", &__self_0),
}
}
}Debug)]
151pub(super) enum LifetimeElisionCandidate {
152 Ignore,
154 Named,
156 Missing(MissingLifetime),
157}
158
159#[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"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.msg, &self.fallback_label, &self.span, &self.span_label,
&self.could_be_expr, &self.suggestion, &&self.module];
::core::fmt::Formatter::debug_struct_fields_finish(f, "BaseError",
names, values)
}
}Debug)]
161struct BaseError {
162 msg: String,
163 fallback_label: String,
164 span: Span,
165 span_label: Option<(Span, &'static str)>,
166 could_be_expr: bool,
167 suggestion: Option<(Span, &'static str, String)>,
168 module: Option<DefId>,
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).borrow().iter().find_map(|(key, resolution)| {
195 if key.ident.name != assoc_name {
196 return None;
197 }
198 let resolution = resolution.borrow();
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(box ast::ConstItem { generics, .. })
327 | AssocItemKind::Fn(box ast::Fn { generics, .. })
328 | AssocItemKind::Type(box 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 ) -> BaseError {
390 let mut expected = source.descr_expected();
392 let path_str = Segment::names_to_string(path);
393 let item_str = path.last().unwrap().ident;
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: match res {
407 Res::Def(DefKind::Fn, _) => {
408 self.r
410 .tcx
411 .sess
412 .source_map()
413 .span_to_snippet(span)
414 .is_ok_and(|snippet| snippet.ends_with(')'))
415 }
416 Res::Def(
417 DefKind::Ctor(..) | DefKind::AssocFn | DefKind::Const | DefKind::AssocConst,
418 _,
419 )
420 | Res::SelfCtor(_)
421 | Res::PrimTy(_)
422 | Res::Local(_) => true,
423 _ => false,
424 },
425 suggestion: None,
426 module: None,
427 }
428 } else {
429 let mut span_label = None;
430 let item_ident = path.last().unwrap().ident;
431 let item_span = item_ident.span;
432 let (mod_prefix, mod_str, module, suggestion) = if path.len() == 1 {
433 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late/diagnostics.rs:433",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(433u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&["self.diag_metadata.current_impl_items"],
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&self.diag_metadata.current_impl_items)
as &dyn Value))])
});
} else { ; }
};debug!(?self.diag_metadata.current_impl_items);
434 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late/diagnostics.rs:434",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(434u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&["self.diag_metadata.current_function"],
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&self.diag_metadata.current_function)
as &dyn Value))])
});
} else { ; }
};debug!(?self.diag_metadata.current_function);
435 let suggestion = if self.current_trait_ref.is_none()
436 && let Some((fn_kind, _)) = self.diag_metadata.current_function
437 && let Some(FnCtxt::Assoc(_)) = fn_kind.ctxt()
438 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = fn_kind
439 && let Some(items) = self.diag_metadata.current_impl_items
440 && let Some(item) = items.iter().find(|i| {
441 i.kind.ident().is_some_and(|ident| {
442 ident.name == item_str.name && !sig.span.contains(item_span)
444 })
445 }) {
446 let sp = item_span.shrink_to_lo();
447
448 let field = match source {
451 PathSource::Expr(Some(Expr { kind: ExprKind::Struct(expr), .. })) => {
452 expr.fields.iter().find(|f| f.ident == item_ident)
453 }
454 _ => None,
455 };
456 let pre = if let Some(field) = field
457 && field.is_shorthand
458 {
459 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", item_ident))
})format!("{item_ident}: ")
460 } else {
461 String::new()
462 };
463 let is_call = match field {
466 Some(ast::ExprField { expr, .. }) => {
467 #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
ExprKind::Call(..) => true,
_ => false,
}matches!(expr.kind, ExprKind::Call(..))
468 }
469 _ => #[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::Expr(Some(Expr { kind: ExprKind::Call(..), .. })) => true,
_ => false,
}matches!(
470 source,
471 PathSource::Expr(Some(Expr { kind: ExprKind::Call(..), .. })),
472 ),
473 };
474
475 match &item.kind {
476 AssocItemKind::Fn(fn_)
477 if (!sig.decl.has_self() || !is_call) && fn_.sig.decl.has_self() =>
478 {
479 span_label = Some((
483 fn_.ident.span,
484 "a method by that name is available on `Self` here",
485 ));
486 None
487 }
488 AssocItemKind::Fn(fn_) if !fn_.sig.decl.has_self() && !is_call => {
489 span_label = Some((
490 fn_.ident.span,
491 "an associated function by that name is available on `Self` here",
492 ));
493 None
494 }
495 AssocItemKind::Fn(fn_) if fn_.sig.decl.has_self() => {
496 Some((sp, "consider using the method on `Self`", ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}self.", pre))
})format!("{pre}self.")))
497 }
498 AssocItemKind::Fn(_) => Some((
499 sp,
500 "consider using the associated function on `Self`",
501 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}Self::", pre))
})format!("{pre}Self::"),
502 )),
503 AssocItemKind::Const(..) => Some((
504 sp,
505 "consider using the associated constant on `Self`",
506 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}Self::", pre))
})format!("{pre}Self::"),
507 )),
508 _ => None,
509 }
510 } else {
511 None
512 };
513 (String::new(), "this scope".to_string(), None, suggestion)
514 } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
515 if self.r.tcx.sess.edition() > Edition::Edition2015 {
516 expected = "crate";
519 (String::new(), "the list of imported crates".to_string(), None, None)
520 } else {
521 (
522 String::new(),
523 "the crate root".to_string(),
524 Some(CRATE_DEF_ID.to_def_id()),
525 None,
526 )
527 }
528 } else if path.len() == 2 && path[0].ident.name == kw::Crate {
529 (String::new(), "the crate root".to_string(), Some(CRATE_DEF_ID.to_def_id()), None)
530 } else {
531 let mod_path = &path[..path.len() - 1];
532 let mod_res = self.resolve_path(mod_path, Some(TypeNS), None, source);
533 let mod_prefix = match mod_res {
534 PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
535 _ => None,
536 };
537
538 let module_did = mod_prefix.as_ref().and_then(Res::mod_def_id);
539
540 let mod_prefix =
541 mod_prefix.map_or_else(String::new, |res| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} ", res.descr()))
})format!("{} ", res.descr()));
542 (mod_prefix, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`",
Segment::names_to_string(mod_path)))
})format!("`{}`", Segment::names_to_string(mod_path)), module_did, None)
543 };
544
545 let (fallback_label, suggestion) = if path_str == "async"
546 && expected.starts_with("struct")
547 {
548 ("`async` blocks are only allowed in Rust 2018 or later".to_string(), suggestion)
549 } else {
550 let override_suggestion =
552 if ["true", "false"].contains(&item_str.to_string().to_lowercase().as_str()) {
553 let item_typo = item_str.to_string().to_lowercase();
554 Some((item_span, "you may want to use a bool value instead", item_typo))
555 } else if item_str.as_str() == "printf" {
558 Some((
559 item_span,
560 "you may have meant to use the `print` macro",
561 "print!".to_owned(),
562 ))
563 } else {
564 suggestion
565 };
566 (::alloc::__export::must_use({
::alloc::fmt::format(format_args!("not found in {0}", mod_str))
})format!("not found in {mod_str}"), override_suggestion)
567 };
568
569 BaseError {
570 msg: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot find {0} `{1}` in {2}{3}",
expected, item_str, mod_prefix, mod_str))
})format!("cannot find {expected} `{item_str}` in {mod_prefix}{mod_str}"),
571 fallback_label,
572 span: item_span,
573 span_label,
574 could_be_expr: false,
575 suggestion,
576 module,
577 }
578 }
579 }
580
581 pub(crate) fn smart_resolve_partial_mod_path_errors(
589 &mut self,
590 prefix_path: &[Segment],
591 following_seg: Option<&Segment>,
592 ) -> Vec<ImportSuggestion> {
593 if let Some(segment) = prefix_path.last()
594 && let Some(following_seg) = following_seg
595 {
596 let candidates = self.r.lookup_import_candidates(
597 segment.ident,
598 Namespace::TypeNS,
599 &self.parent_scope,
600 &|res: Res| #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Mod, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Mod, _)),
601 );
602 candidates
604 .into_iter()
605 .filter(|candidate| {
606 if let Some(def_id) = candidate.did
607 && let Some(module) = self.r.get_module(def_id)
608 {
609 Some(def_id) != self.parent_scope.module.opt_def_id()
610 && self
611 .r
612 .resolutions(module)
613 .borrow()
614 .iter()
615 .any(|(key, _r)| key.ident.name == following_seg.ident.name)
616 } else {
617 false
618 }
619 })
620 .collect::<Vec<_>>()
621 } else {
622 Vec::new()
623 }
624 }
625
626 #[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("compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(628u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&["path",
"following_seg", "span", "source", "res", "qself"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&following_seg)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&qself)
as &dyn 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 compiler/rustc_resolve/src/late/diagnostics.rs:638",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(638u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&["res", "source"],
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&res) as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&source) as
&dyn Value))])
});
} else { ; }
};
let base_error = self.make_base_error(path, span, source, res);
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(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);
}
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")]
629 pub(crate) fn smart_resolve_report_errors(
630 &mut self,
631 path: &[Segment],
632 following_seg: Option<&Segment>,
633 span: Span,
634 source: PathSource<'_, 'ast, 'ra>,
635 res: Option<Res>,
636 qself: Option<&QSelf>,
637 ) -> (Diag<'tcx>, Vec<ImportSuggestion>) {
638 debug!(?res, ?source);
639 let base_error = self.make_base_error(path, span, source, res);
640
641 let code = source.error_code(res.is_some());
642 let mut err = self.r.dcx().struct_span_err(base_error.span, base_error.msg.clone());
643 err.code(code);
644
645 if let Some(within_macro_span) =
648 base_error.span.within_macro(span, self.r.tcx.sess.source_map())
649 {
650 err.span_label(within_macro_span, "due to this macro variable");
651 }
652
653 self.detect_missing_binding_available_from_pattern(&mut err, path, following_seg);
654 self.suggest_at_operator_in_slice_pat_with_range(&mut err, path);
655 self.suggest_range_struct_destructuring(&mut err, path, source);
656 self.suggest_swapping_misplaced_self_ty_and_trait(&mut err, source, res, base_error.span);
657
658 if let Some((span, label)) = base_error.span_label {
659 err.span_label(span, label);
660 }
661
662 if let Some(ref sugg) = base_error.suggestion {
663 err.span_suggestion_verbose(sugg.0, sugg.1, &sugg.2, Applicability::MaybeIncorrect);
664 }
665
666 self.suggest_changing_type_to_const_param(&mut err, res, source, path, following_seg, span);
667 self.explain_functions_in_pattern(&mut err, res, source);
668
669 if self.suggest_pattern_match_with_let(&mut err, source, span) {
670 err.span_label(base_error.span, base_error.fallback_label);
672 return (err, Vec::new());
673 }
674
675 self.suggest_self_or_self_ref(&mut err, path, span);
676 self.detect_assoc_type_constraint_meant_as_path(&mut err, &base_error);
677 self.detect_rtn_with_fully_qualified_path(
678 &mut err,
679 path,
680 following_seg,
681 span,
682 source,
683 res,
684 qself,
685 );
686 if self.suggest_self_ty(&mut err, source, path, span)
687 || self.suggest_self_value(&mut err, source, path, span)
688 {
689 return (err, Vec::new());
690 }
691
692 if let Some((did, item)) = self.lookup_doc_alias_name(path, source.namespace()) {
693 let item_name = item.name;
694 let suggestion_name = self.r.tcx.item_name(did);
695 err.span_suggestion(
696 item.span,
697 format!("`{suggestion_name}` has a name defined in the doc alias attribute as `{item_name}`"),
698 suggestion_name,
699 Applicability::MaybeIncorrect
700 );
701
702 return (err, Vec::new());
703 };
704
705 let (found, suggested_candidates, mut candidates) = self.try_lookup_name_relaxed(
706 &mut err,
707 source,
708 path,
709 following_seg,
710 span,
711 res,
712 &base_error,
713 );
714 if found {
715 return (err, candidates);
716 }
717
718 if self.suggest_shadowed(&mut err, source, path, following_seg, span) {
719 candidates.clear();
721 }
722
723 let mut fallback = self.suggest_trait_and_bounds(&mut err, source, res, span, &base_error);
724 fallback |= self.suggest_typo(
725 &mut err,
726 source,
727 path,
728 following_seg,
729 span,
730 &base_error,
731 suggested_candidates,
732 );
733
734 if fallback {
735 err.span_label(base_error.span, base_error.fallback_label);
737 }
738 self.err_code_special_cases(&mut err, source, path, span);
739
740 let module = base_error.module.unwrap_or_else(|| CRATE_DEF_ID.to_def_id());
741 self.r.find_cfg_stripped(&mut err, &path.last().unwrap().ident.name, module);
742
743 (err, candidates)
744 }
745
746 fn detect_rtn_with_fully_qualified_path(
747 &self,
748 err: &mut Diag<'_>,
749 path: &[Segment],
750 following_seg: Option<&Segment>,
751 span: Span,
752 source: PathSource<'_, '_, '_>,
753 res: Option<Res>,
754 qself: Option<&QSelf>,
755 ) {
756 if let Some(Res::Def(DefKind::AssocFn, _)) = res
757 && let PathSource::TraitItem(TypeNS, _) = source
758 && let None = following_seg
759 && let Some(qself) = qself
760 && let TyKind::Path(None, ty_path) = &qself.ty.kind
761 && ty_path.segments.len() == 1
762 && self.diag_metadata.current_where_predicate.is_some()
763 {
764 err.span_suggestion_verbose(
765 span,
766 "you might have meant to use the return type notation syntax",
767 ::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),
768 Applicability::MaybeIncorrect,
769 );
770 }
771 }
772
773 fn detect_assoc_type_constraint_meant_as_path(
774 &self,
775 err: &mut Diag<'_>,
776 base_error: &BaseError,
777 ) {
778 let Some(ty) = self.diag_metadata.current_type_path else {
779 return;
780 };
781 let TyKind::Path(_, path) = &ty.kind else {
782 return;
783 };
784 for segment in &path.segments {
785 let Some(params) = &segment.args else {
786 continue;
787 };
788 let ast::GenericArgs::AngleBracketed(params) = params.deref() else {
789 continue;
790 };
791 for param in ¶ms.args {
792 let ast::AngleBracketedArg::Constraint(constraint) = param else {
793 continue;
794 };
795 let ast::AssocItemConstraintKind::Bound { bounds } = &constraint.kind else {
796 continue;
797 };
798 for bound in bounds {
799 let ast::GenericBound::Trait(trait_ref) = bound else {
800 continue;
801 };
802 if trait_ref.modifiers == ast::TraitBoundModifiers::NONE
803 && base_error.span == trait_ref.span
804 {
805 err.span_suggestion_verbose(
806 constraint.ident.span.between(trait_ref.span),
807 "you might have meant to write a path instead of an associated type bound",
808 "::",
809 Applicability::MachineApplicable,
810 );
811 }
812 }
813 }
814 }
815 }
816
817 fn suggest_self_or_self_ref(&mut self, err: &mut Diag<'_>, path: &[Segment], span: Span) {
818 if !self.self_type_is_available() {
819 return;
820 }
821 let Some(path_last_segment) = path.last() else { return };
822 let item_str = path_last_segment.ident;
823 if ["this", "my"].contains(&item_str.as_str()) {
825 err.span_suggestion_short(
826 span,
827 "you might have meant to use `self` here instead",
828 "self",
829 Applicability::MaybeIncorrect,
830 );
831 if !self.self_value_is_available(path[0].ident.span) {
832 if let Some((FnKind::Fn(_, _, ast::Fn { sig, .. }), fn_span)) =
833 &self.diag_metadata.current_function
834 {
835 let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) {
836 (param.span.shrink_to_lo(), "&self, ")
837 } else {
838 (
839 self.r
840 .tcx
841 .sess
842 .source_map()
843 .span_through_char(*fn_span, '(')
844 .shrink_to_hi(),
845 "&self",
846 )
847 };
848 err.span_suggestion_verbose(
849 span,
850 "if you meant to use `self`, you are also missing a `self` receiver \
851 argument",
852 sugg,
853 Applicability::MaybeIncorrect,
854 );
855 }
856 }
857 }
858 }
859
860 fn try_lookup_name_relaxed(
861 &mut self,
862 err: &mut Diag<'_>,
863 source: PathSource<'_, '_, '_>,
864 path: &[Segment],
865 following_seg: Option<&Segment>,
866 span: Span,
867 res: Option<Res>,
868 base_error: &BaseError,
869 ) -> (bool, FxHashSet<String>, Vec<ImportSuggestion>) {
870 let span = match following_seg {
871 Some(_) if path[0].ident.span.eq_ctxt(path[path.len() - 1].ident.span) => {
872 path[0].ident.span.to(path[path.len() - 1].ident.span)
875 }
876 _ => span,
877 };
878 let mut suggested_candidates = FxHashSet::default();
879 let ident = path.last().unwrap().ident;
881 let is_expected = &|res| source.is_expected(res);
882 let ns = source.namespace();
883 let is_enum_variant = &|res| #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Variant, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Variant, _));
884 let path_str = Segment::names_to_string(path);
885 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
886 let mut candidates = self
887 .r
888 .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
889 .into_iter()
890 .filter(|ImportSuggestion { did, .. }| {
891 match (did, res.and_then(|res| res.opt_def_id())) {
892 (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
893 _ => true,
894 }
895 })
896 .collect::<Vec<_>>();
897 let intrinsic_candidates: Vec<_> = candidates
900 .extract_if(.., |sugg| {
901 let path = path_names_to_string(&sugg.path);
902 path.starts_with("core::intrinsics::") || path.starts_with("std::intrinsics::")
903 })
904 .collect();
905 if candidates.is_empty() {
906 candidates = intrinsic_candidates;
908 }
909 let crate_def_id = CRATE_DEF_ID.to_def_id();
910 if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
911 let mut enum_candidates: Vec<_> = self
912 .r
913 .lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant)
914 .into_iter()
915 .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
916 .filter(|(_, enum_ty_path)| !enum_ty_path.starts_with("std::prelude::"))
917 .collect();
918 if !enum_candidates.is_empty() {
919 enum_candidates.sort();
920
921 let preamble = if res.is_none() {
924 let others = match enum_candidates.len() {
925 1 => String::new(),
926 2 => " and 1 other".to_owned(),
927 n => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" and {0} others", n))
})format!(" and {n} others"),
928 };
929 ::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)
930 } else {
931 String::new()
932 };
933 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");
934
935 suggested_candidates.extend(
936 enum_candidates
937 .iter()
938 .map(|(_variant_path, enum_ty_path)| enum_ty_path.clone()),
939 );
940 err.span_suggestions(
941 span,
942 msg,
943 enum_candidates.into_iter().map(|(_variant_path, enum_ty_path)| enum_ty_path),
944 Applicability::MachineApplicable,
945 );
946 }
947 }
948
949 let typo_sugg = self
951 .lookup_typo_candidate(path, following_seg, source.namespace(), is_expected)
952 .to_opt_suggestion()
953 .filter(|sugg| !suggested_candidates.contains(sugg.candidate.as_str()));
954 if let [segment] = path
955 && !#[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::Delegation => true,
_ => false,
}matches!(source, PathSource::Delegation)
956 && self.self_type_is_available()
957 {
958 if let Some(candidate) =
959 self.lookup_assoc_candidate(ident, ns, is_expected, source.is_call())
960 {
961 let self_is_available = self.self_value_is_available(segment.ident.span);
962 let pre = match source {
965 PathSource::Expr(Some(Expr { kind: ExprKind::Struct(expr), .. }))
966 if expr
967 .fields
968 .iter()
969 .any(|f| f.ident == segment.ident && f.is_shorthand) =>
970 {
971 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", path_str))
})format!("{path_str}: ")
972 }
973 _ => String::new(),
974 };
975 match candidate {
976 AssocSuggestion::Field(field_span) => {
977 if self_is_available {
978 let source_map = self.r.tcx.sess.source_map();
979 let field_is_format_named_arg = source_map
981 .span_to_source(span, |s, start, _| {
982 Ok(s.get(start - 1..start) == Some("{"))
983 });
984 if let Ok(true) = field_is_format_named_arg {
985 err.help(
986 ::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),
987 );
988 } else {
989 err.span_suggestion_verbose(
990 span.shrink_to_lo(),
991 "you might have meant to use the available field",
992 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}self.", pre))
})format!("{pre}self."),
993 Applicability::MaybeIncorrect,
994 );
995 }
996 } else {
997 err.span_label(field_span, "a field by that name exists in `Self`");
998 }
999 }
1000 AssocSuggestion::MethodWithSelf { called } if self_is_available => {
1001 let msg = if called {
1002 "you might have meant to call the method"
1003 } else {
1004 "you might have meant to refer to the method"
1005 };
1006 err.span_suggestion_verbose(
1007 span.shrink_to_lo(),
1008 msg,
1009 "self.",
1010 Applicability::MachineApplicable,
1011 );
1012 }
1013 AssocSuggestion::MethodWithSelf { .. }
1014 | AssocSuggestion::AssocFn { .. }
1015 | AssocSuggestion::AssocConst
1016 | AssocSuggestion::AssocType => {
1017 err.span_suggestion_verbose(
1018 span.shrink_to_lo(),
1019 ::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()),
1020 "Self::",
1021 Applicability::MachineApplicable,
1022 );
1023 }
1024 }
1025 self.r.add_typo_suggestion(err, typo_sugg, ident_span);
1026 return (true, suggested_candidates, candidates);
1027 }
1028
1029 if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
1031 let mut args_snippet = String::new();
1032 if let Some(args_span) = args_span
1033 && let Ok(snippet) = self.r.tcx.sess.source_map().span_to_snippet(args_span)
1034 {
1035 args_snippet = snippet;
1036 }
1037
1038 if let Some(Res::Def(DefKind::Struct, def_id)) = res {
1039 let private_fields = self.has_private_fields(def_id);
1040 let adjust_error_message =
1041 private_fields && self.is_struct_with_fn_ctor(def_id);
1042 if adjust_error_message {
1043 self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
1044 }
1045
1046 if private_fields {
1047 err.note("constructor is not visible here due to private fields");
1048 }
1049 } else {
1050 err.span_suggestion(
1051 call_span,
1052 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("try calling `{0}` as a method",
ident))
})format!("try calling `{ident}` as a method"),
1053 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("self.{0}({1})", path_str,
args_snippet))
})format!("self.{path_str}({args_snippet})"),
1054 Applicability::MachineApplicable,
1055 );
1056 }
1057
1058 return (true, suggested_candidates, candidates);
1059 }
1060 }
1061
1062 if let Some(res) = res {
1064 if self.smart_resolve_context_dependent_help(
1065 err,
1066 span,
1067 source,
1068 path,
1069 res,
1070 &path_str,
1071 &base_error.fallback_label,
1072 ) {
1073 self.r.add_typo_suggestion(err, typo_sugg, ident_span);
1075 return (true, suggested_candidates, candidates);
1076 }
1077 }
1078
1079 if let Some(rib) = &self.last_block_rib {
1081 for (ident, &res) in &rib.bindings {
1082 if let Res::Local(_) = res
1083 && path.len() == 1
1084 && ident.span.eq_ctxt(path[0].ident.span)
1085 && ident.name == path[0].ident.name
1086 {
1087 err.span_help(
1088 ident.span,
1089 ::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"),
1090 );
1091 return (true, suggested_candidates, candidates);
1092 }
1093 }
1094 }
1095
1096 if candidates.is_empty() {
1097 candidates = self.smart_resolve_partial_mod_path_errors(path, following_seg);
1098 }
1099
1100 (false, suggested_candidates, candidates)
1101 }
1102
1103 fn lookup_doc_alias_name(&mut self, path: &[Segment], ns: Namespace) -> Option<(DefId, Ident)> {
1104 let find_doc_alias_name = |r: &mut Resolver<'ra, '_>, m: Module<'ra>, item_name: Symbol| {
1105 for resolution in r.resolutions(m).borrow().values() {
1106 let Some(did) =
1107 resolution.borrow().best_decl().and_then(|binding| binding.res().opt_def_id())
1108 else {
1109 continue;
1110 };
1111 if did.is_local() {
1112 continue;
1116 }
1117 if let Some(d) = {
#[allow(deprecated)]
{
{
'done:
{
for i in r.tcx.get_all_attrs(did) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(Doc(d)) => {
break 'done Some(d);
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}
}hir::find_attr!(r.tcx, did, Doc(d) => d)
1118 && d.aliases.contains_key(&item_name)
1119 {
1120 return Some(did);
1121 }
1122 }
1123 None
1124 };
1125
1126 if path.len() == 1 {
1127 for rib in self.ribs[ns].iter().rev() {
1128 let item = path[0].ident;
1129 if let RibKind::Module(module) | RibKind::Block(Some(module)) = rib.kind
1130 && let Some(did) = find_doc_alias_name(self.r, module, item.name)
1131 {
1132 return Some((did, item));
1133 }
1134 }
1135 } else {
1136 for (idx, seg) in path.iter().enumerate().rev().skip(1) {
1145 let Some(id) = seg.id else {
1146 continue;
1147 };
1148 let Some(res) = self.r.partial_res_map.get(&id) else {
1149 continue;
1150 };
1151 if let Res::Def(DefKind::Mod, module) = res.expect_full_res()
1152 && let module = self.r.expect_module(module)
1153 && let item = path[idx + 1].ident
1154 && let Some(did) = find_doc_alias_name(self.r, module, item.name)
1155 {
1156 return Some((did, item));
1157 }
1158 break;
1159 }
1160 }
1161 None
1162 }
1163
1164 fn suggest_trait_and_bounds(
1165 &self,
1166 err: &mut Diag<'_>,
1167 source: PathSource<'_, '_, '_>,
1168 res: Option<Res>,
1169 span: Span,
1170 base_error: &BaseError,
1171 ) -> bool {
1172 let is_macro =
1173 base_error.span.from_expansion() && base_error.span.desugaring_kind().is_none();
1174 let mut fallback = false;
1175
1176 if let (
1177 PathSource::Trait(AliasPossibility::Maybe),
1178 Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)),
1179 false,
1180 ) = (source, res, is_macro)
1181 && let Some(bounds @ [first_bound, .., last_bound]) =
1182 self.diag_metadata.current_trait_object
1183 {
1184 fallback = true;
1185 let spans: Vec<Span> = bounds
1186 .iter()
1187 .map(|bound| bound.span())
1188 .filter(|&sp| sp != base_error.span)
1189 .collect();
1190
1191 let start_span = first_bound.span();
1192 let end_span = last_bound.span();
1194 let last_bound_span = spans.last().cloned().unwrap();
1196 let mut multi_span: MultiSpan = spans.clone().into();
1197 for sp in spans {
1198 let msg = if sp == last_bound_span {
1199 ::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!(
1200 "...because of {these} bound{s}",
1201 these = pluralize!("this", bounds.len() - 1),
1202 s = pluralize!(bounds.len() - 1),
1203 )
1204 } else {
1205 String::new()
1206 };
1207 multi_span.push_span_label(sp, msg);
1208 }
1209 multi_span.push_span_label(base_error.span, "expected this type to be a trait...");
1210 err.span_help(
1211 multi_span,
1212 "`+` is used to constrain a \"trait object\" type with lifetimes or \
1213 auto-traits; structs and enums can't be bound in that way",
1214 );
1215 if bounds.iter().all(|bound| match bound {
1216 ast::GenericBound::Outlives(_) | ast::GenericBound::Use(..) => true,
1217 ast::GenericBound::Trait(tr) => tr.span == base_error.span,
1218 }) {
1219 let mut sugg = ::alloc::vec::Vec::new()vec![];
1220 if base_error.span != start_span {
1221 sugg.push((start_span.until(base_error.span), String::new()));
1222 }
1223 if base_error.span != end_span {
1224 sugg.push((base_error.span.shrink_to_hi().to(end_span), String::new()));
1225 }
1226
1227 err.multipart_suggestion(
1228 "if you meant to use a type and not a trait here, remove the bounds",
1229 sugg,
1230 Applicability::MaybeIncorrect,
1231 );
1232 }
1233 }
1234
1235 fallback |= self.restrict_assoc_type_in_where_clause(span, err);
1236 fallback
1237 }
1238
1239 fn suggest_typo(
1240 &mut self,
1241 err: &mut Diag<'_>,
1242 source: PathSource<'_, 'ast, 'ra>,
1243 path: &[Segment],
1244 following_seg: Option<&Segment>,
1245 span: Span,
1246 base_error: &BaseError,
1247 suggested_candidates: FxHashSet<String>,
1248 ) -> bool {
1249 let is_expected = &|res| source.is_expected(res);
1250 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
1251
1252 if self.suggest_assoc_type_from_bounds(err, source, path, ident_span) {
1256 return false;
1257 }
1258
1259 let typo_sugg =
1260 self.lookup_typo_candidate(path, following_seg, source.namespace(), is_expected);
1261 let mut fallback = false;
1262 let typo_sugg = typo_sugg
1263 .to_opt_suggestion()
1264 .filter(|sugg| !suggested_candidates.contains(sugg.candidate.as_str()));
1265 if !self.r.add_typo_suggestion(err, typo_sugg, ident_span) {
1266 fallback = true;
1267 match self.diag_metadata.current_let_binding {
1268 Some((pat_sp, Some(ty_sp), None))
1269 if ty_sp.contains(base_error.span) && base_error.could_be_expr =>
1270 {
1271 err.span_suggestion_short(
1272 pat_sp.between(ty_sp),
1273 "use `=` if you meant to assign",
1274 " = ",
1275 Applicability::MaybeIncorrect,
1276 );
1277 }
1278 _ => {}
1279 }
1280
1281 let suggestion = self.get_single_associated_item(path, &source, is_expected);
1283 self.r.add_typo_suggestion(err, suggestion, ident_span);
1284 }
1285
1286 if self.let_binding_suggestion(err, ident_span) {
1287 fallback = false;
1288 }
1289
1290 fallback
1291 }
1292
1293 fn suggest_shadowed(
1294 &mut self,
1295 err: &mut Diag<'_>,
1296 source: PathSource<'_, '_, '_>,
1297 path: &[Segment],
1298 following_seg: Option<&Segment>,
1299 span: Span,
1300 ) -> bool {
1301 let is_expected = &|res| source.is_expected(res);
1302 let typo_sugg =
1303 self.lookup_typo_candidate(path, following_seg, source.namespace(), is_expected);
1304 let is_in_same_file = &|sp1, sp2| {
1305 let source_map = self.r.tcx.sess.source_map();
1306 let file1 = source_map.span_to_filename(sp1);
1307 let file2 = source_map.span_to_filename(sp2);
1308 file1 == file2
1309 };
1310 if let TypoCandidate::Shadowed(res, Some(sugg_span)) = typo_sugg
1315 && res.opt_def_id().is_some_and(|id| id.is_local() || is_in_same_file(span, sugg_span))
1316 {
1317 err.span_label(
1318 sugg_span,
1319 ::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()),
1320 );
1321 return true;
1322 }
1323 false
1324 }
1325
1326 fn err_code_special_cases(
1327 &mut self,
1328 err: &mut Diag<'_>,
1329 source: PathSource<'_, '_, '_>,
1330 path: &[Segment],
1331 span: Span,
1332 ) {
1333 if let Some(err_code) = err.code {
1334 if err_code == E0425 {
1335 for label_rib in &self.label_ribs {
1336 for (label_ident, node_id) in &label_rib.bindings {
1337 let ident = path.last().unwrap().ident;
1338 if ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\'{0}", ident))
})format!("'{ident}") == label_ident.to_string() {
1339 err.span_label(label_ident.span, "a label with a similar name exists");
1340 if let PathSource::Expr(Some(Expr {
1341 kind: ExprKind::Break(None, Some(_)),
1342 ..
1343 })) = source
1344 {
1345 err.span_suggestion(
1346 span,
1347 "use the similarly named label",
1348 label_ident.name,
1349 Applicability::MaybeIncorrect,
1350 );
1351 self.diag_metadata.unused_labels.swap_remove(node_id);
1353 }
1354 }
1355 }
1356 }
1357
1358 self.suggest_ident_hidden_by_hygiene(err, path, span);
1359 if let Some(correct) = Self::likely_rust_type(path) {
1361 err.span_suggestion(
1362 span,
1363 "perhaps you intended to use this type",
1364 correct,
1365 Applicability::MaybeIncorrect,
1366 );
1367 }
1368 }
1369 }
1370 }
1371
1372 fn suggest_ident_hidden_by_hygiene(&self, err: &mut Diag<'_>, path: &[Segment], span: Span) {
1373 let [segment] = path else { return };
1374
1375 let ident = segment.ident;
1376 let callsite_span = span.source_callsite();
1377 for rib in self.ribs[ValueNS].iter().rev() {
1378 for (binding_ident, _) in &rib.bindings {
1379 if binding_ident.name == ident.name
1381 && !binding_ident.span.eq_ctxt(span)
1382 && !binding_ident.span.from_expansion()
1383 && binding_ident.span.lo() < callsite_span.lo()
1384 {
1385 err.span_help(
1386 binding_ident.span,
1387 "an identifier with the same name exists, but is not accessible due to macro hygiene",
1388 );
1389 return;
1390 }
1391
1392 if binding_ident.name == ident.name
1394 && binding_ident.span.from_expansion()
1395 && binding_ident.span.source_callsite().eq_ctxt(callsite_span)
1396 && binding_ident.span.source_callsite().lo() < callsite_span.lo()
1397 {
1398 err.span_help(
1399 binding_ident.span,
1400 "an identifier with the same name is defined here, but is not accessible due to macro hygiene",
1401 );
1402 return;
1403 }
1404 }
1405 }
1406 }
1407
1408 fn suggest_self_ty(
1410 &self,
1411 err: &mut Diag<'_>,
1412 source: PathSource<'_, '_, '_>,
1413 path: &[Segment],
1414 span: Span,
1415 ) -> bool {
1416 if !is_self_type(path, source.namespace()) {
1417 return false;
1418 }
1419 err.code(E0411);
1420 err.span_label(span, "`Self` is only available in impls, traits, and type definitions");
1421 if let Some(item) = self.diag_metadata.current_item
1422 && let Some(ident) = item.kind.ident()
1423 {
1424 err.span_label(
1425 ident.span,
1426 ::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()),
1427 );
1428 }
1429 true
1430 }
1431
1432 fn suggest_self_value(
1433 &mut self,
1434 err: &mut Diag<'_>,
1435 source: PathSource<'_, '_, '_>,
1436 path: &[Segment],
1437 span: Span,
1438 ) -> bool {
1439 if !is_self_value(path, source.namespace()) {
1440 return false;
1441 }
1442
1443 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late/diagnostics.rs:1443",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(1443u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("smart_resolve_path_fragment: E0424, source={0:?}",
source) as &dyn Value))])
});
} else { ; }
};debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
1444 err.code(E0424);
1445 err.span_label(
1446 span,
1447 match source {
1448 PathSource::Pat => {
1449 "`self` value is a keyword and may not be bound to variables or shadowed"
1450 }
1451 _ => "`self` value is a keyword only available in methods with a `self` parameter",
1452 },
1453 );
1454
1455 if #[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::Pat => true,
_ => false,
}matches!(source, PathSource::Pat) {
1458 return true;
1459 }
1460
1461 let is_assoc_fn = self.self_type_is_available();
1462 let self_from_macro = "a `self` parameter, but a macro invocation can only \
1463 access identifiers it receives from parameters";
1464 if let Some((fn_kind, fn_span)) = &self.diag_metadata.current_function {
1465 if fn_kind.decl().inputs.get(0).is_some_and(|p| p.is_self()) {
1470 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}"));
1471 } else {
1472 let doesnt = if is_assoc_fn {
1473 let (span, sugg) = fn_kind
1474 .decl()
1475 .inputs
1476 .get(0)
1477 .map(|p| (p.span.shrink_to_lo(), "&self, "))
1478 .unwrap_or_else(|| {
1479 let span = fn_kind
1482 .ident()
1483 .map_or(*fn_span, |ident| fn_span.with_lo(ident.span.hi()));
1484 (
1485 self.r
1486 .tcx
1487 .sess
1488 .source_map()
1489 .span_through_char(span, '(')
1490 .shrink_to_hi(),
1491 "&self",
1492 )
1493 });
1494 err.span_suggestion_verbose(
1495 span,
1496 "add a `self` receiver parameter to make the associated `fn` a method",
1497 sugg,
1498 Applicability::MaybeIncorrect,
1499 );
1500 "doesn't"
1501 } else {
1502 "can't"
1503 };
1504 if let Some(ident) = fn_kind.ident() {
1505 err.span_label(
1506 ident.span,
1507 ::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"),
1508 );
1509 }
1510 }
1511 } else if let Some(item) = self.diag_metadata.current_item {
1512 if #[allow(non_exhaustive_omitted_patterns)] match item.kind {
ItemKind::Delegation(..) => true,
_ => false,
}matches!(item.kind, ItemKind::Delegation(..)) {
1513 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}"));
1514 } else {
1515 let span = if let Some(ident) = item.kind.ident() { ident.span } else { item.span };
1516 err.span_label(
1517 span,
1518 ::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()),
1519 );
1520 }
1521 }
1522 true
1523 }
1524
1525 fn detect_missing_binding_available_from_pattern(
1526 &self,
1527 err: &mut Diag<'_>,
1528 path: &[Segment],
1529 following_seg: Option<&Segment>,
1530 ) {
1531 let [segment] = path else { return };
1532 let None = following_seg else { return };
1533 for rib in self.ribs[ValueNS].iter().rev() {
1534 let patterns_with_skipped_bindings = self.r.tcx.with_stable_hashing_context(|hcx| {
1535 rib.patterns_with_skipped_bindings.to_sorted(&hcx, true)
1536 });
1537 for (def_id, spans) in patterns_with_skipped_bindings {
1538 if let DefKind::Struct | DefKind::Variant = self.r.tcx.def_kind(*def_id)
1539 && let Some(fields) = self.r.field_idents(*def_id)
1540 {
1541 for field in fields {
1542 if field.name == segment.ident.name {
1543 if spans.iter().all(|(_, had_error)| had_error.is_err()) {
1544 let multispan: MultiSpan =
1547 spans.iter().map(|(s, _)| *s).collect::<Vec<_>>().into();
1548 err.span_note(
1549 multispan,
1550 "this pattern had a recovered parse error which likely lost \
1551 the expected fields",
1552 );
1553 err.downgrade_to_delayed_bug();
1554 }
1555 let ty = self.r.tcx.item_name(*def_id);
1556 for (span, _) in spans {
1557 err.span_label(
1558 *span,
1559 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this pattern doesn\'t include `{0}`, which is available in `{1}`",
field, ty))
})format!(
1560 "this pattern doesn't include `{field}`, which is \
1561 available in `{ty}`",
1562 ),
1563 );
1564 }
1565 }
1566 }
1567 }
1568 }
1569 }
1570 }
1571
1572 fn suggest_at_operator_in_slice_pat_with_range(&self, err: &mut Diag<'_>, path: &[Segment]) {
1573 let Some(pat) = self.diag_metadata.current_pat else { return };
1574 let (bound, side, range) = match &pat.kind {
1575 ast::PatKind::Range(Some(bound), None, range) => (bound, Side::Start, range),
1576 ast::PatKind::Range(None, Some(bound), range) => (bound, Side::End, range),
1577 _ => return,
1578 };
1579 if let ExprKind::Path(None, range_path) = &bound.kind
1580 && let [segment] = &range_path.segments[..]
1581 && let [s] = path
1582 && segment.ident == s.ident
1583 && segment.ident.span.eq_ctxt(range.span)
1584 {
1585 let (span, snippet) = match side {
1588 Side::Start => (segment.ident.span.between(range.span), " @ ".into()),
1589 Side::End => (range.span.to(segment.ident.span), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} @ ..", segment.ident))
})format!("{} @ ..", segment.ident)),
1590 };
1591 err.subdiagnostic(errors::UnexpectedResUseAtOpInSlicePatWithRangeSugg {
1592 span,
1593 ident: segment.ident,
1594 snippet,
1595 });
1596 }
1597
1598 enum Side {
1599 Start,
1600 End,
1601 }
1602 }
1603
1604 fn suggest_range_struct_destructuring(
1605 &mut self,
1606 err: &mut Diag<'_>,
1607 path: &[Segment],
1608 source: PathSource<'_, '_, '_>,
1609 ) {
1610 if !#[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::Pat | PathSource::TupleStruct(..) | PathSource::Expr(..) =>
true,
_ => false,
}matches!(source, PathSource::Pat | PathSource::TupleStruct(..) | PathSource::Expr(..)) {
1611 return;
1612 }
1613
1614 let Some(pat) = self.diag_metadata.current_pat else { return };
1615 let ast::PatKind::Range(start, end, end_kind) = &pat.kind else { return };
1616
1617 let [segment] = path else { return };
1618 let failing_span = segment.ident.span;
1619
1620 let in_start = start.as_ref().is_some_and(|e| e.span.contains(failing_span));
1621 let in_end = end.as_ref().is_some_and(|e| e.span.contains(failing_span));
1622
1623 if !in_start && !in_end {
1624 return;
1625 }
1626
1627 let start_snippet =
1628 start.as_ref().and_then(|e| self.r.tcx.sess.source_map().span_to_snippet(e.span).ok());
1629 let end_snippet =
1630 end.as_ref().and_then(|e| self.r.tcx.sess.source_map().span_to_snippet(e.span).ok());
1631
1632 let field = |name: &str, val: String| {
1633 if val == name { val } else { ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: {1}", name, val))
})format!("{name}: {val}") }
1634 };
1635
1636 let mut resolve_short_name = |short: Symbol, full: &str| -> String {
1637 let ident = Ident::with_dummy_span(short);
1638 let path = Segment::from_path(&Path::from_ident(ident));
1639
1640 match self.resolve_path(&path, Some(TypeNS), None, PathSource::Type) {
1641 PathResult::NonModule(..) => short.to_string(),
1642 _ => full.to_string(),
1643 }
1644 };
1645 let (struct_path, fields) = match (start_snippet, end_snippet, &end_kind.node) {
1647 (Some(start), Some(end), ast::RangeEnd::Excluded) => (
1648 resolve_short_name(sym::Range, "std::ops::Range"),
1649 ::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)],
1650 ),
1651 (Some(start), Some(end), ast::RangeEnd::Included(_)) => (
1652 resolve_short_name(sym::RangeInclusive, "std::ops::RangeInclusive"),
1653 ::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)],
1654 ),
1655 (Some(start), None, _) => (
1656 resolve_short_name(sym::RangeFrom, "std::ops::RangeFrom"),
1657 ::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)],
1658 ),
1659 (None, Some(end), ast::RangeEnd::Excluded) => {
1660 (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)])
1661 }
1662 (None, Some(end), ast::RangeEnd::Included(_)) => (
1663 resolve_short_name(sym::RangeToInclusive, "std::ops::RangeToInclusive"),
1664 ::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)],
1665 ),
1666 _ => return,
1667 };
1668
1669 err.span_suggestion_verbose(
1670 pat.span,
1671 ::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"),
1672 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {{ {1} }}", struct_path,
fields.join(", ")))
})format!("{} {{ {} }}", struct_path, fields.join(", ")),
1673 Applicability::MaybeIncorrect,
1674 );
1675
1676 err.note(
1677 "range patterns match against the start and end of a range; \
1678 to bind the components, use a struct pattern",
1679 );
1680 }
1681
1682 fn suggest_swapping_misplaced_self_ty_and_trait(
1683 &mut self,
1684 err: &mut Diag<'_>,
1685 source: PathSource<'_, 'ast, 'ra>,
1686 res: Option<Res>,
1687 span: Span,
1688 ) {
1689 if let Some((trait_ref, self_ty)) =
1690 self.diag_metadata.currently_processing_impl_trait.clone()
1691 && let TyKind::Path(_, self_ty_path) = &self_ty.kind
1692 && let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1693 self.resolve_path(&Segment::from_path(self_ty_path), Some(TypeNS), None, source)
1694 && let ModuleKind::Def(DefKind::Trait, ..) = module.kind
1695 && trait_ref.path.span == span
1696 && let PathSource::Trait(_) = source
1697 && let Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)) = res
1698 && let Ok(self_ty_str) = self.r.tcx.sess.source_map().span_to_snippet(self_ty.span)
1699 && let Ok(trait_ref_str) =
1700 self.r.tcx.sess.source_map().span_to_snippet(trait_ref.path.span)
1701 {
1702 err.multipart_suggestion(
1703 "`impl` items mention the trait being implemented first and the type it is being implemented for second",
1704 ::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)],
1705 Applicability::MaybeIncorrect,
1706 );
1707 }
1708 }
1709
1710 fn explain_functions_in_pattern(
1711 &self,
1712 err: &mut Diag<'_>,
1713 res: Option<Res>,
1714 source: PathSource<'_, '_, '_>,
1715 ) {
1716 let PathSource::TupleStruct(_, _) = source else { return };
1717 let Some(Res::Def(DefKind::Fn, _)) = res else { return };
1718 err.primary_message("expected a pattern, found a function call");
1719 err.note("function calls are not allowed in patterns: <https://doc.rust-lang.org/book/ch19-00-patterns.html>");
1720 }
1721
1722 fn suggest_changing_type_to_const_param(
1723 &self,
1724 err: &mut Diag<'_>,
1725 res: Option<Res>,
1726 source: PathSource<'_, '_, '_>,
1727 path: &[Segment],
1728 following_seg: Option<&Segment>,
1729 span: Span,
1730 ) {
1731 if let PathSource::Expr(None) = source
1732 && let Some(Res::Def(DefKind::TyParam, _)) = res
1733 && following_seg.is_none()
1734 && let [segment] = path
1735 {
1736 let Some(item) = self.diag_metadata.current_item else { return };
1744 let Some(generics) = item.kind.generics() else { return };
1745 let Some(span) = generics.params.iter().find_map(|param| {
1746 if param.bounds.is_empty() && param.ident.name == segment.ident.name {
1748 Some(param.ident.span)
1749 } else {
1750 None
1751 }
1752 }) else {
1753 return;
1754 };
1755 err.subdiagnostic(errors::UnexpectedResChangeTyParamToConstParamSugg {
1756 before: span.shrink_to_lo(),
1757 after: span.shrink_to_hi(),
1758 });
1759 return;
1760 }
1761 let PathSource::Trait(_) = source else { return };
1762
1763 let applicability = match res {
1765 Some(Res::PrimTy(PrimTy::Int(_) | PrimTy::Uint(_) | PrimTy::Bool | PrimTy::Char)) => {
1766 Applicability::MachineApplicable
1767 }
1768 Some(Res::Def(DefKind::Struct | DefKind::Enum, _))
1772 if self.r.tcx.features().adt_const_params() =>
1773 {
1774 Applicability::MaybeIncorrect
1775 }
1776 _ => return,
1777 };
1778
1779 let Some(item) = self.diag_metadata.current_item else { return };
1780 let Some(generics) = item.kind.generics() else { return };
1781
1782 let param = generics.params.iter().find_map(|param| {
1783 if let [bound] = &*param.bounds
1785 && let ast::GenericBound::Trait(tref) = bound
1786 && tref.modifiers == ast::TraitBoundModifiers::NONE
1787 && tref.span == span
1788 && param.ident.span.eq_ctxt(span)
1789 {
1790 Some(param.ident.span)
1791 } else {
1792 None
1793 }
1794 });
1795
1796 if let Some(param) = param {
1797 err.subdiagnostic(errors::UnexpectedResChangeTyToConstParamSugg {
1798 span: param.shrink_to_lo(),
1799 applicability,
1800 });
1801 }
1802 }
1803
1804 fn suggest_pattern_match_with_let(
1805 &self,
1806 err: &mut Diag<'_>,
1807 source: PathSource<'_, '_, '_>,
1808 span: Span,
1809 ) -> bool {
1810 if let PathSource::Expr(_) = source
1811 && let Some(Expr { span: expr_span, kind: ExprKind::Assign(lhs, _, _), .. }) =
1812 self.diag_metadata.in_if_condition
1813 {
1814 if lhs.is_approximately_pattern() && lhs.span.contains(span) {
1818 err.span_suggestion_verbose(
1819 expr_span.shrink_to_lo(),
1820 "you might have meant to use pattern matching",
1821 "let ",
1822 Applicability::MaybeIncorrect,
1823 );
1824 return true;
1825 }
1826 }
1827 false
1828 }
1829
1830 fn get_single_associated_item(
1831 &mut self,
1832 path: &[Segment],
1833 source: &PathSource<'_, 'ast, 'ra>,
1834 filter_fn: &impl Fn(Res) -> bool,
1835 ) -> Option<TypoSuggestion> {
1836 if let crate::PathSource::TraitItem(_, _) = source {
1837 let mod_path = &path[..path.len() - 1];
1838 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1839 self.resolve_path(mod_path, None, None, *source)
1840 {
1841 let targets: Vec<_> = self
1842 .r
1843 .resolutions(module)
1844 .borrow()
1845 .iter()
1846 .filter_map(|(key, resolution)| {
1847 let resolution = resolution.borrow();
1848 resolution.best_decl().map(|binding| binding.res()).and_then(|res| {
1849 if filter_fn(res) {
1850 Some((key.ident.name, resolution.orig_ident_span, res))
1851 } else {
1852 None
1853 }
1854 })
1855 })
1856 .collect();
1857 if let &[(name, orig_ident_span, res)] = targets.as_slice() {
1858 return Some(TypoSuggestion::single_item(name, orig_ident_span, res));
1859 }
1860 }
1861 }
1862 None
1863 }
1864
1865 fn restrict_assoc_type_in_where_clause(&self, span: Span, err: &mut Diag<'_>) -> bool {
1867 let Some(ast::WherePredicate {
1869 kind:
1870 ast::WherePredicateKind::BoundPredicate(ast::WhereBoundPredicate {
1871 bounded_ty,
1872 bound_generic_params,
1873 bounds,
1874 }),
1875 span: where_span,
1876 ..
1877 }) = self.diag_metadata.current_where_predicate
1878 else {
1879 return false;
1880 };
1881 if !bound_generic_params.is_empty() {
1882 return false;
1883 }
1884
1885 let ast::TyKind::Path(Some(qself), path) = &bounded_ty.kind else { return false };
1887 let Some(partial_res) = self.r.partial_res_map.get(&bounded_ty.id) else { return false };
1889 if !#[allow(non_exhaustive_omitted_patterns)] match partial_res.full_res() {
Some(hir::def::Res::Def(hir::def::DefKind::AssocTy, _)) => true,
_ => false,
}matches!(
1890 partial_res.full_res(),
1891 Some(hir::def::Res::Def(hir::def::DefKind::AssocTy, _))
1892 ) {
1893 return false;
1894 }
1895
1896 let peeled_ty = qself.ty.peel_refs();
1897 let ast::TyKind::Path(None, type_param_path) = &peeled_ty.kind else { return false };
1898 let Some(partial_res) = self.r.partial_res_map.get(&peeled_ty.id) else {
1900 return false;
1901 };
1902 if !#[allow(non_exhaustive_omitted_patterns)] match partial_res.full_res() {
Some(hir::def::Res::Def(hir::def::DefKind::TyParam, _)) => true,
_ => false,
}matches!(
1903 partial_res.full_res(),
1904 Some(hir::def::Res::Def(hir::def::DefKind::TyParam, _))
1905 ) {
1906 return false;
1907 }
1908 let ([ast::PathSegment { args: None, .. }], [ast::GenericBound::Trait(poly_trait_ref)]) =
1909 (&type_param_path.segments[..], &bounds[..])
1910 else {
1911 return false;
1912 };
1913 let [ast::PathSegment { ident, args: None, id }] =
1914 &poly_trait_ref.trait_ref.path.segments[..]
1915 else {
1916 return false;
1917 };
1918 if poly_trait_ref.modifiers != ast::TraitBoundModifiers::NONE {
1919 return false;
1920 }
1921 if ident.span == span {
1922 let Some(partial_res) = self.r.partial_res_map.get(&id) else {
1923 return false;
1924 };
1925 if !#[allow(non_exhaustive_omitted_patterns)] match partial_res.full_res() {
Some(hir::def::Res::Def(..)) => true,
_ => false,
}matches!(partial_res.full_res(), Some(hir::def::Res::Def(..))) {
1926 return false;
1927 }
1928
1929 let Some(new_where_bound_predicate) =
1930 mk_where_bound_predicate(path, poly_trait_ref, &qself.ty)
1931 else {
1932 return false;
1933 };
1934 err.span_suggestion_verbose(
1935 *where_span,
1936 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("constrain the associated type to `{0}`",
ident))
})format!("constrain the associated type to `{ident}`"),
1937 where_bound_predicate_to_string(&new_where_bound_predicate),
1938 Applicability::MaybeIncorrect,
1939 );
1940 }
1941 true
1942 }
1943
1944 fn call_has_self_arg(&self, source: PathSource<'_, '_, '_>) -> Option<(Span, Option<Span>)> {
1947 let mut has_self_arg = None;
1948 if let PathSource::Expr(Some(parent)) = source
1949 && let ExprKind::Call(_, args) = &parent.kind
1950 && !args.is_empty()
1951 {
1952 let mut expr_kind = &args[0].kind;
1953 loop {
1954 match expr_kind {
1955 ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
1956 if arg_name.segments[0].ident.name == kw::SelfLower {
1957 let call_span = parent.span;
1958 let tail_args_span = if args.len() > 1 {
1959 Some(Span::new(
1960 args[1].span.lo(),
1961 args.last().unwrap().span.hi(),
1962 call_span.ctxt(),
1963 None,
1964 ))
1965 } else {
1966 None
1967 };
1968 has_self_arg = Some((call_span, tail_args_span));
1969 }
1970 break;
1971 }
1972 ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
1973 _ => break,
1974 }
1975 }
1976 }
1977 has_self_arg
1978 }
1979
1980 fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
1981 let sm = self.r.tcx.sess.source_map();
1986 if let Some(followed_brace_span) = sm.span_look_ahead(span, "{", Some(50)) {
1987 let close_brace_span = sm.span_look_ahead(followed_brace_span, "}", Some(50));
1990 let closing_brace = close_brace_span.map(|sp| span.to(sp));
1991 (true, closing_brace)
1992 } else {
1993 (false, None)
1994 }
1995 }
1996
1997 fn is_struct_with_fn_ctor(&mut self, def_id: DefId) -> bool {
1998 def_id
1999 .as_local()
2000 .and_then(|local_id| self.r.struct_constructors.get(&local_id))
2001 .map(|struct_ctor| {
2002 #[allow(non_exhaustive_omitted_patterns)] match struct_ctor.0 {
def::Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), _) => true,
_ => false,
}matches!(
2003 struct_ctor.0,
2004 def::Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), _)
2005 )
2006 })
2007 .unwrap_or(false)
2008 }
2009
2010 fn update_err_for_private_tuple_struct_fields(
2011 &mut self,
2012 err: &mut Diag<'_>,
2013 source: &PathSource<'_, '_, '_>,
2014 def_id: DefId,
2015 ) -> Option<Vec<Span>> {
2016 match source {
2017 PathSource::TupleStruct(_, pattern_spans) => {
2019 err.primary_message(
2020 "cannot match against a tuple struct which contains private fields",
2021 );
2022
2023 Some(Vec::from(*pattern_spans))
2025 }
2026 PathSource::Expr(Some(Expr {
2028 kind: ExprKind::Call(path, args),
2029 span: call_span,
2030 ..
2031 })) => {
2032 err.primary_message(
2033 "cannot initialize a tuple struct which contains private fields",
2034 );
2035 self.suggest_alternative_construction_methods(
2036 def_id,
2037 err,
2038 path.span,
2039 *call_span,
2040 &args[..],
2041 );
2042
2043 self.r
2044 .field_idents(def_id)
2045 .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
2046 }
2047 _ => None,
2048 }
2049 }
2050
2051 fn smart_resolve_context_dependent_help(
2055 &mut self,
2056 err: &mut Diag<'_>,
2057 span: Span,
2058 source: PathSource<'_, '_, '_>,
2059 path: &[Segment],
2060 res: Res,
2061 path_str: &str,
2062 fallback_label: &str,
2063 ) -> bool {
2064 let ns = source.namespace();
2065 let is_expected = &|res| source.is_expected(res);
2066
2067 let path_sep = |this: &Self, err: &mut Diag<'_>, expr: &Expr, kind: DefKind| {
2068 const MESSAGE: &str = "use the path separator to refer to an item";
2069
2070 let (lhs_span, rhs_span) = match &expr.kind {
2071 ExprKind::Field(base, ident) => (base.span, ident.span),
2072 ExprKind::MethodCall(box MethodCall { receiver, span, .. }) => {
2073 (receiver.span, *span)
2074 }
2075 _ => return false,
2076 };
2077
2078 if lhs_span.eq_ctxt(rhs_span) {
2079 err.span_suggestion_verbose(
2080 lhs_span.between(rhs_span),
2081 MESSAGE,
2082 "::",
2083 Applicability::MaybeIncorrect,
2084 );
2085 true
2086 } else if #[allow(non_exhaustive_omitted_patterns)] match kind {
DefKind::Struct | DefKind::TyAlias => true,
_ => false,
}matches!(kind, DefKind::Struct | DefKind::TyAlias)
2087 && let Some(lhs_source_span) = lhs_span.find_ancestor_inside(expr.span)
2088 && let Ok(snippet) = this.r.tcx.sess.source_map().span_to_snippet(lhs_source_span)
2089 {
2090 err.span_suggestion_verbose(
2094 lhs_source_span.until(rhs_span),
2095 MESSAGE,
2096 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>::", snippet))
})format!("<{snippet}>::"),
2097 Applicability::MaybeIncorrect,
2098 );
2099 true
2100 } else {
2101 false
2107 }
2108 };
2109
2110 let find_span = |source: &PathSource<'_, '_, '_>, err: &mut Diag<'_>| {
2111 match source {
2112 PathSource::Expr(Some(Expr { span, kind: ExprKind::Call(_, _), .. }))
2113 | PathSource::TupleStruct(span, _) => {
2114 err.span(*span);
2117 *span
2118 }
2119 _ => span,
2120 }
2121 };
2122
2123 let bad_struct_syntax_suggestion = |this: &mut Self, err: &mut Diag<'_>, def_id: DefId| {
2124 let (followed_by_brace, closing_brace) = this.followed_by_brace(span);
2125
2126 match source {
2127 PathSource::Expr(Some(
2128 parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
2129 )) if path_sep(this, err, parent, DefKind::Struct) => {}
2130 PathSource::Expr(
2131 None
2132 | Some(Expr {
2133 kind:
2134 ExprKind::Path(..)
2135 | ExprKind::Binary(..)
2136 | ExprKind::Unary(..)
2137 | ExprKind::If(..)
2138 | ExprKind::While(..)
2139 | ExprKind::ForLoop { .. }
2140 | ExprKind::Match(..),
2141 ..
2142 }),
2143 ) if followed_by_brace => {
2144 if let Some(sp) = closing_brace {
2145 err.span_label(span, fallback_label.to_string());
2146 err.multipart_suggestion(
2147 "surround the struct literal with parentheses",
2148 ::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![
2149 (sp.shrink_to_lo(), "(".to_string()),
2150 (sp.shrink_to_hi(), ")".to_string()),
2151 ],
2152 Applicability::MaybeIncorrect,
2153 );
2154 } else {
2155 err.span_label(
2156 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!(
2158 "you might want to surround a struct literal with parentheses: \
2159 `({path_str} {{ /* fields */ }})`?"
2160 ),
2161 );
2162 }
2163 }
2164 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
2165 let span = find_span(&source, err);
2166 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"));
2167
2168 let (tail, descr, applicability, old_fields) = match source {
2169 PathSource::Pat => ("", "pattern", Applicability::MachineApplicable, None),
2170 PathSource::TupleStruct(_, args) => (
2171 "",
2172 "pattern",
2173 Applicability::MachineApplicable,
2174 Some(
2175 args.iter()
2176 .map(|a| this.r.tcx.sess.source_map().span_to_snippet(*a).ok())
2177 .collect::<Vec<Option<String>>>(),
2178 ),
2179 ),
2180 _ => (": val", "literal", Applicability::HasPlaceholders, None),
2181 };
2182
2183 if !this.has_private_fields(def_id) {
2184 let fields = this.r.field_idents(def_id);
2187 let has_fields = fields.as_ref().is_some_and(|f| !f.is_empty());
2188
2189 if let PathSource::Expr(Some(Expr {
2190 kind: ExprKind::Call(path, args),
2191 span,
2192 ..
2193 })) = source
2194 && !args.is_empty()
2195 && let Some(fields) = &fields
2196 && args.len() == fields.len()
2197 {
2199 let path_span = path.span;
2200 let mut parts = Vec::new();
2201
2202 parts.push((
2204 path_span.shrink_to_hi().until(args[0].span),
2205 "{".to_owned(),
2206 ));
2207
2208 for (field, arg) in fields.iter().zip(args.iter()) {
2209 parts.push((arg.span.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", field))
})format!("{}: ", field)));
2211 }
2212
2213 parts.push((
2215 args.last().unwrap().span.shrink_to_hi().until(span.shrink_to_hi()),
2216 "}".to_owned(),
2217 ));
2218
2219 err.multipart_suggestion(
2220 ::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"),
2221 parts,
2222 applicability,
2223 );
2224 } else {
2225 let (fields, applicability) = match fields {
2226 Some(fields) => {
2227 let fields = if let Some(old_fields) = old_fields {
2228 fields
2229 .iter()
2230 .enumerate()
2231 .map(|(idx, new)| (new, old_fields.get(idx)))
2232 .map(|(new, old)| {
2233 if let Some(Some(old)) = old
2234 && new.as_str() != old
2235 {
2236 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: {1}", new, old))
})format!("{new}: {old}")
2237 } else {
2238 new.to_string()
2239 }
2240 })
2241 .collect::<Vec<String>>()
2242 } else {
2243 fields
2244 .iter()
2245 .map(|f| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", f, tail))
})format!("{f}{tail}"))
2246 .collect::<Vec<String>>()
2247 };
2248
2249 (fields.join(", "), applicability)
2250 }
2251 None => {
2252 ("/* fields */".to_string(), Applicability::HasPlaceholders)
2253 }
2254 };
2255 let pad = if has_fields { " " } else { "" };
2256 err.span_suggestion(
2257 span,
2258 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use struct {0} syntax instead",
descr))
})format!("use struct {descr} syntax instead"),
2259 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {{{1}{2}{1}}}", path_str, pad,
fields))
})format!("{path_str} {{{pad}{fields}{pad}}}"),
2260 applicability,
2261 );
2262 }
2263 }
2264 if let PathSource::Expr(Some(Expr {
2265 kind: ExprKind::Call(path, args),
2266 span: call_span,
2267 ..
2268 })) = source
2269 {
2270 this.suggest_alternative_construction_methods(
2271 def_id,
2272 err,
2273 path.span,
2274 *call_span,
2275 &args[..],
2276 );
2277 }
2278 }
2279 _ => {
2280 err.span_label(span, fallback_label.to_string());
2281 }
2282 }
2283 };
2284
2285 match (res, source) {
2286 (
2287 Res::Def(DefKind::Macro(kinds), def_id),
2288 PathSource::Expr(Some(Expr {
2289 kind: ExprKind::Index(..) | ExprKind::Call(..), ..
2290 }))
2291 | PathSource::Struct(_),
2292 ) if kinds.contains(MacroKinds::BANG) => {
2293 let suggestable = def_id.is_local()
2295 || self.r.tcx.lookup_stability(def_id).is_none_or(|s| s.is_stable());
2296
2297 err.span_label(span, fallback_label.to_string());
2298
2299 if path
2301 .last()
2302 .is_some_and(|segment| !segment.has_generic_args && !segment.has_lifetime_args)
2303 && suggestable
2304 {
2305 err.span_suggestion_verbose(
2306 span.shrink_to_hi(),
2307 "use `!` to invoke the macro",
2308 "!",
2309 Applicability::MaybeIncorrect,
2310 );
2311 }
2312
2313 if path_str == "try" && span.is_rust_2015() {
2314 err.note("if you want the `try` keyword, you need Rust 2018 or later");
2315 }
2316 }
2317 (Res::Def(DefKind::Macro(kinds), _), _) if kinds.contains(MacroKinds::BANG) => {
2318 err.span_label(span, fallback_label.to_string());
2319 }
2320 (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
2321 err.span_label(span, "type aliases cannot be used as traits");
2322 if self.r.tcx.sess.is_nightly_build() {
2323 let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
2324 `type` alias";
2325 let span = self.r.def_span(def_id);
2326 if let Ok(snip) = self.r.tcx.sess.source_map().span_to_snippet(span) {
2327 let snip = snip.replacen("type", "trait", 1);
2330 err.span_suggestion(span, msg, snip, Applicability::MaybeIncorrect);
2331 } else {
2332 err.span_help(span, msg);
2333 }
2334 }
2335 }
2336 (
2337 Res::Def(kind @ (DefKind::Mod | DefKind::Trait | DefKind::TyAlias), _),
2338 PathSource::Expr(Some(parent)),
2339 ) if path_sep(self, err, parent, kind) => {
2340 return true;
2341 }
2342 (
2343 Res::Def(DefKind::Enum, def_id),
2344 PathSource::TupleStruct(..) | PathSource::Expr(..),
2345 ) => {
2346 self.suggest_using_enum_variant(err, source, def_id, span);
2347 }
2348 (Res::Def(DefKind::Struct, def_id), source) if ns == ValueNS => {
2349 let struct_ctor = match def_id.as_local() {
2350 Some(def_id) => self.r.struct_constructors.get(&def_id).cloned(),
2351 None => {
2352 let ctor = self.r.cstore().ctor_untracked(self.r.tcx(), def_id);
2353 ctor.map(|(ctor_kind, ctor_def_id)| {
2354 let ctor_res =
2355 Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id);
2356 let ctor_vis = self.r.tcx.visibility(ctor_def_id);
2357 let field_visibilities = self
2358 .r
2359 .tcx
2360 .associated_item_def_ids(def_id)
2361 .iter()
2362 .map(|&field_id| self.r.tcx.visibility(field_id))
2363 .collect();
2364 (ctor_res, ctor_vis, field_visibilities)
2365 })
2366 }
2367 };
2368
2369 let (ctor_def, ctor_vis, fields) = if let Some(struct_ctor) = struct_ctor {
2370 if let PathSource::Expr(Some(parent)) = source
2371 && let ExprKind::Field(..) | ExprKind::MethodCall(..) = parent.kind
2372 {
2373 bad_struct_syntax_suggestion(self, err, def_id);
2374 return true;
2375 }
2376 struct_ctor
2377 } else {
2378 bad_struct_syntax_suggestion(self, err, def_id);
2379 return true;
2380 };
2381
2382 let is_accessible = self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
2383 if let Some(use_span) = self.r.inaccessible_ctor_reexport.get(&span)
2384 && is_accessible
2385 {
2386 err.span_note(
2387 *use_span,
2388 "the type is accessed through this re-export, but the type's constructor \
2389 is not visible in this import's scope due to private fields",
2390 );
2391 if is_accessible
2392 && fields
2393 .iter()
2394 .all(|vis| self.r.is_accessible_from(*vis, self.parent_scope.module))
2395 {
2396 err.span_suggestion_verbose(
2397 span,
2398 "the type can be constructed directly, because its fields are \
2399 available from the current scope",
2400 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("crate{0}",
self.r.tcx.def_path(def_id).to_string_no_crate_verbose()))
})format!(
2404 "crate{}", self.r.tcx.def_path(def_id).to_string_no_crate_verbose(),
2406 ),
2407 Applicability::MachineApplicable,
2408 );
2409 }
2410 self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
2411 }
2412 if !is_expected(ctor_def) || is_accessible {
2413 return true;
2414 }
2415
2416 let field_spans =
2417 self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
2418
2419 if let Some(spans) =
2420 field_spans.filter(|spans| spans.len() > 0 && fields.len() == spans.len())
2421 {
2422 let non_visible_spans: Vec<Span> = iter::zip(&fields, &spans)
2423 .filter(|(vis, _)| {
2424 !self.r.is_accessible_from(**vis, self.parent_scope.module)
2425 })
2426 .map(|(_, span)| *span)
2427 .collect();
2428
2429 if non_visible_spans.len() > 0 {
2430 if let Some(fields) = self.r.field_visibility_spans.get(&def_id) {
2431 err.multipart_suggestion(
2432 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider making the field{0} publicly accessible",
if fields.len() == 1 { "" } else { "s" }))
})format!(
2433 "consider making the field{} publicly accessible",
2434 pluralize!(fields.len())
2435 ),
2436 fields.iter().map(|span| (*span, "pub ".to_string())).collect(),
2437 Applicability::MaybeIncorrect,
2438 );
2439 }
2440
2441 let mut m: MultiSpan = non_visible_spans.clone().into();
2442 non_visible_spans
2443 .into_iter()
2444 .for_each(|s| m.push_span_label(s, "private field"));
2445 err.span_note(m, "constructor is not visible here due to private fields");
2446 }
2447
2448 return true;
2449 }
2450
2451 err.span_label(span, "constructor is not visible here due to private fields");
2452 }
2453 (Res::Def(DefKind::Union | DefKind::Variant, def_id), _) if ns == ValueNS => {
2454 bad_struct_syntax_suggestion(self, err, def_id);
2455 }
2456 (Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id), _) if ns == ValueNS => {
2457 match source {
2458 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
2459 let span = find_span(&source, err);
2460 err.span_label(
2461 self.r.def_span(def_id),
2462 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` defined here", path_str))
})format!("`{path_str}` defined here"),
2463 );
2464 err.span_suggestion(
2465 span,
2466 "use this syntax instead",
2467 path_str,
2468 Applicability::MaybeIncorrect,
2469 );
2470 }
2471 _ => return false,
2472 }
2473 }
2474 (Res::Def(DefKind::Ctor(_, CtorKind::Fn), ctor_def_id), _) if ns == ValueNS => {
2475 let def_id = self.r.tcx.parent(ctor_def_id);
2476 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"));
2477 let fields = self.r.field_idents(def_id).map_or_else(
2478 || "/* fields */".to_string(),
2479 |field_ids| ::alloc::vec::from_elem("_", field_ids.len())vec!["_"; field_ids.len()].join(", "),
2480 );
2481 err.span_suggestion(
2482 span,
2483 "use the tuple variant pattern syntax instead",
2484 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}({1})", path_str, fields))
})format!("{path_str}({fields})"),
2485 Applicability::HasPlaceholders,
2486 );
2487 }
2488 (Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }, _) if ns == ValueNS => {
2489 err.span_label(span, fallback_label.to_string());
2490 err.note("can't use `Self` as a constructor, you must use the implemented struct");
2491 }
2492 (
2493 Res::Def(DefKind::TyAlias | DefKind::AssocTy, _),
2494 PathSource::TraitItem(ValueNS, PathSource::TupleStruct(whole, args)),
2495 ) => {
2496 err.note("can't use a type alias as tuple pattern");
2497
2498 let mut suggestion = Vec::new();
2499
2500 if let &&[first, ..] = args
2501 && let &&[.., last] = args
2502 {
2503 suggestion.extend([
2504 (span.between(first), " { 0: ".to_owned()),
2510 (last.between(whole.shrink_to_hi()), " }".to_owned()),
2511 ]);
2512
2513 suggestion.extend(
2514 args.iter()
2515 .enumerate()
2516 .skip(1) .map(|(index, &arg)| (arg.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", index))
})format!("{index}: "))),
2518 )
2519 } else {
2520 suggestion.push((span.between(whole.shrink_to_hi()), " {}".to_owned()));
2521 }
2522
2523 err.multipart_suggestion(
2524 "use struct pattern instead",
2525 suggestion,
2526 Applicability::MachineApplicable,
2527 );
2528 }
2529 (
2530 Res::Def(DefKind::TyAlias | DefKind::AssocTy, _),
2531 PathSource::TraitItem(
2532 ValueNS,
2533 PathSource::Expr(Some(ast::Expr {
2534 span: whole,
2535 kind: ast::ExprKind::Call(_, args),
2536 ..
2537 })),
2538 ),
2539 ) => {
2540 err.note("can't use a type alias as a constructor");
2541
2542 let mut suggestion = Vec::new();
2543
2544 if let [first, ..] = &**args
2545 && let [.., last] = &**args
2546 {
2547 suggestion.extend([
2548 (span.between(first.span), " { 0: ".to_owned()),
2554 (last.span.between(whole.shrink_to_hi()), " }".to_owned()),
2555 ]);
2556
2557 suggestion.extend(
2558 args.iter()
2559 .enumerate()
2560 .skip(1) .map(|(index, arg)| (arg.span.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", index))
})format!("{index}: "))),
2562 )
2563 } else {
2564 suggestion.push((span.between(whole.shrink_to_hi()), " {}".to_owned()));
2565 }
2566
2567 err.multipart_suggestion(
2568 "use struct expression instead",
2569 suggestion,
2570 Applicability::MachineApplicable,
2571 );
2572 }
2573 _ => return false,
2574 }
2575 true
2576 }
2577
2578 fn suggest_alternative_construction_methods(
2579 &mut self,
2580 def_id: DefId,
2581 err: &mut Diag<'_>,
2582 path_span: Span,
2583 call_span: Span,
2584 args: &[Box<Expr>],
2585 ) {
2586 if def_id.is_local() {
2587 return;
2589 }
2590 let mut items = self
2593 .r
2594 .tcx
2595 .inherent_impls(def_id)
2596 .iter()
2597 .flat_map(|&i| self.r.tcx.associated_items(i).in_definition_order())
2598 .filter(|item| item.is_fn() && !item.is_method())
2600 .filter_map(|item| {
2601 let fn_sig = self.r.tcx.fn_sig(item.def_id).skip_binder();
2603 let ret_ty = fn_sig.output().skip_binder();
2605 let ty::Adt(def, _args) = ret_ty.kind() else {
2606 return None;
2607 };
2608 let input_len = fn_sig.inputs().skip_binder().len();
2609 if def.did() != def_id {
2610 return None;
2611 }
2612 let name = item.name();
2613 let order = !name.as_str().starts_with("new");
2614 Some((order, name, input_len))
2615 })
2616 .collect::<Vec<_>>();
2617 items.sort_by_key(|(order, _, _)| *order);
2618 let suggestion = |name, args| {
2619 ::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(", "))
2620 };
2621 match &items[..] {
2622 [] => {}
2623 [(_, name, len)] if *len == args.len() => {
2624 err.span_suggestion_verbose(
2625 path_span.shrink_to_hi(),
2626 ::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",),
2627 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("::{0}", name))
})format!("::{name}"),
2628 Applicability::MaybeIncorrect,
2629 );
2630 }
2631 [(_, name, len)] => {
2632 err.span_suggestion_verbose(
2633 path_span.shrink_to_hi().with_hi(call_span.hi()),
2634 ::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",),
2635 suggestion(name, *len),
2636 Applicability::MaybeIncorrect,
2637 );
2638 }
2639 _ => {
2640 err.span_suggestions_with_style(
2641 path_span.shrink_to_hi().with_hi(call_span.hi()),
2642 "you might have meant to use an associated function to build this type",
2643 items.iter().map(|(_, name, len)| suggestion(name, *len)),
2644 Applicability::MaybeIncorrect,
2645 SuggestionStyle::ShowAlways,
2646 );
2647 }
2648 }
2649 let default_trait = self
2657 .r
2658 .lookup_import_candidates(
2659 Ident::with_dummy_span(sym::Default),
2660 Namespace::TypeNS,
2661 &self.parent_scope,
2662 &|res: Res| #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Trait, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Trait, _)),
2663 )
2664 .iter()
2665 .filter_map(|candidate| candidate.did)
2666 .find(|did| {
#[allow(deprecated)]
{
{
'done:
{
for i in self.r.tcx.get_all_attrs(*did) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcDiagnosticItem(sym::Default))
=> {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}
}.is_some()find_attr!(self.r.tcx, *did, RustcDiagnosticItem(sym::Default)));
2667 let Some(default_trait) = default_trait else {
2668 return;
2669 };
2670 if self
2671 .r
2672 .extern_crate_map
2673 .items()
2674 .flat_map(|(_, crate_)| self.r.tcx.implementations_of_trait((*crate_, default_trait)))
2676 .filter_map(|(_, simplified_self_ty)| *simplified_self_ty)
2677 .filter_map(|simplified_self_ty| match simplified_self_ty {
2678 SimplifiedType::Adt(did) => Some(did),
2679 _ => None,
2680 })
2681 .any(|did| did == def_id)
2682 {
2683 err.multipart_suggestion(
2684 "consider using the `Default` trait",
2685 ::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![
2686 (path_span.shrink_to_lo(), "<".to_string()),
2687 (
2688 path_span.shrink_to_hi().with_hi(call_span.hi()),
2689 " as std::default::Default>::default()".to_string(),
2690 ),
2691 ],
2692 Applicability::MaybeIncorrect,
2693 );
2694 }
2695 }
2696
2697 fn has_private_fields(&self, def_id: DefId) -> bool {
2698 let fields = match def_id.as_local() {
2699 Some(def_id) => self.r.struct_constructors.get(&def_id).cloned().map(|(_, _, f)| f),
2700 None => Some(
2701 self.r
2702 .tcx
2703 .associated_item_def_ids(def_id)
2704 .iter()
2705 .map(|&field_id| self.r.tcx.visibility(field_id))
2706 .collect(),
2707 ),
2708 };
2709
2710 fields.is_some_and(|fields| {
2711 fields.iter().any(|vis| !self.r.is_accessible_from(*vis, self.parent_scope.module))
2712 })
2713 }
2714
2715 pub(crate) fn find_similarly_named_assoc_item(
2718 &mut self,
2719 ident: Symbol,
2720 kind: &AssocItemKind,
2721 ) -> Option<Symbol> {
2722 let (module, _) = self.current_trait_ref.as_ref()?;
2723 if ident == kw::Underscore {
2724 return None;
2726 }
2727
2728 let targets = self
2729 .r
2730 .resolutions(*module)
2731 .borrow()
2732 .iter()
2733 .filter_map(|(key, res)| res.borrow().best_decl().map(|binding| (key, binding.res())))
2734 .filter(|(_, res)| match (kind, res) {
2735 (AssocItemKind::Const(..), Res::Def(DefKind::AssocConst, _)) => true,
2736 (AssocItemKind::Fn(_), Res::Def(DefKind::AssocFn, _)) => true,
2737 (AssocItemKind::Type(..), Res::Def(DefKind::AssocTy, _)) => true,
2738 (AssocItemKind::Delegation(_), Res::Def(DefKind::AssocFn, _)) => true,
2739 _ => false,
2740 })
2741 .map(|(key, _)| key.ident.name)
2742 .collect::<Vec<_>>();
2743
2744 find_best_match_for_name(&targets, ident, None)
2745 }
2746
2747 fn lookup_assoc_candidate<FilterFn>(
2748 &mut self,
2749 ident: Ident,
2750 ns: Namespace,
2751 filter_fn: FilterFn,
2752 called: bool,
2753 ) -> Option<AssocSuggestion>
2754 where
2755 FilterFn: Fn(Res) -> bool,
2756 {
2757 fn extract_node_id(t: &Ty) -> Option<NodeId> {
2758 match t.kind {
2759 TyKind::Path(None, _) => Some(t.id),
2760 TyKind::Ref(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
2761 _ => None,
2765 }
2766 }
2767 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
2769 if let Some(node_id) =
2770 self.diag_metadata.current_self_type.as_ref().and_then(extract_node_id)
2771 && let Some(resolution) = self.r.partial_res_map.get(&node_id)
2772 && let Some(Res::Def(DefKind::Struct | DefKind::Union, did)) = resolution.full_res()
2773 && let Some(fields) = self.r.field_idents(did)
2774 && let Some(field) = fields.iter().find(|id| ident.name == id.name)
2775 {
2776 return Some(AssocSuggestion::Field(field.span));
2778 }
2779 }
2780
2781 if let Some(items) = self.diag_metadata.current_trait_assoc_items {
2782 for assoc_item in items {
2783 if let Some(assoc_ident) = assoc_item.kind.ident()
2784 && assoc_ident == ident
2785 {
2786 return Some(match &assoc_item.kind {
2787 ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
2788 ast::AssocItemKind::Fn(box ast::Fn { sig, .. }) if sig.decl.has_self() => {
2789 AssocSuggestion::MethodWithSelf { called }
2790 }
2791 ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn { called },
2792 ast::AssocItemKind::Type(..) => AssocSuggestion::AssocType,
2793 ast::AssocItemKind::Delegation(..)
2794 if self
2795 .r
2796 .delegation_fn_sigs
2797 .get(&self.r.local_def_id(assoc_item.id))
2798 .is_some_and(|sig| sig.has_self) =>
2799 {
2800 AssocSuggestion::MethodWithSelf { called }
2801 }
2802 ast::AssocItemKind::Delegation(..) => AssocSuggestion::AssocFn { called },
2803 ast::AssocItemKind::MacCall(_) | ast::AssocItemKind::DelegationMac(..) => {
2804 continue;
2805 }
2806 });
2807 }
2808 }
2809 }
2810
2811 if let Some((module, _)) = self.current_trait_ref
2813 && let Ok(binding) = self.r.cm().maybe_resolve_ident_in_module(
2814 ModuleOrUniformRoot::Module(module),
2815 ident,
2816 ns,
2817 &self.parent_scope,
2818 None,
2819 )
2820 {
2821 let res = binding.res();
2822 if filter_fn(res) {
2823 match res {
2824 Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) => {
2825 let has_self = match def_id.as_local() {
2826 Some(def_id) => self
2827 .r
2828 .delegation_fn_sigs
2829 .get(&def_id)
2830 .is_some_and(|sig| sig.has_self),
2831 None => {
2832 self.r.tcx.fn_arg_idents(def_id).first().is_some_and(|&ident| {
2833 #[allow(non_exhaustive_omitted_patterns)] match ident {
Some(Ident { name: kw::SelfLower, .. }) => true,
_ => false,
}matches!(ident, Some(Ident { name: kw::SelfLower, .. }))
2834 })
2835 }
2836 };
2837 if has_self {
2838 return Some(AssocSuggestion::MethodWithSelf { called });
2839 } else {
2840 return Some(AssocSuggestion::AssocFn { called });
2841 }
2842 }
2843 Res::Def(DefKind::AssocConst, _) => {
2844 return Some(AssocSuggestion::AssocConst);
2845 }
2846 Res::Def(DefKind::AssocTy, _) => {
2847 return Some(AssocSuggestion::AssocType);
2848 }
2849 _ => {}
2850 }
2851 }
2852 }
2853
2854 None
2855 }
2856
2857 fn lookup_typo_candidate(
2858 &mut self,
2859 path: &[Segment],
2860 following_seg: Option<&Segment>,
2861 ns: Namespace,
2862 filter_fn: &impl Fn(Res) -> bool,
2863 ) -> TypoCandidate {
2864 let mut names = Vec::new();
2865 if let [segment] = path {
2866 let mut ctxt = segment.ident.span.ctxt();
2867
2868 for rib in self.ribs[ns].iter().rev() {
2871 let rib_ctxt = if rib.kind.contains_params() {
2872 ctxt.normalize_to_macros_2_0()
2873 } else {
2874 ctxt.normalize_to_macro_rules()
2875 };
2876
2877 for (ident, &res) in &rib.bindings {
2879 if filter_fn(res) && ident.span.ctxt() == rib_ctxt {
2880 names.push(TypoSuggestion::new(ident.name, ident.span, res));
2881 }
2882 }
2883
2884 if let RibKind::Block(Some(module)) = rib.kind {
2885 self.r.add_module_candidates(module, &mut names, &filter_fn, Some(ctxt));
2886 } else if let RibKind::Module(module) = rib.kind {
2887 let parent_scope = &ParentScope { module, ..self.parent_scope };
2889 self.r.add_scope_set_candidates(
2890 &mut names,
2891 ScopeSet::All(ns),
2892 parent_scope,
2893 segment.ident.span.with_ctxt(ctxt),
2894 filter_fn,
2895 );
2896 break;
2897 }
2898
2899 if let RibKind::MacroDefinition(def) = rib.kind
2900 && def == self.r.macro_def(ctxt)
2901 {
2902 ctxt.remove_mark();
2905 }
2906 }
2907 } else {
2908 let mod_path = &path[..path.len() - 1];
2910 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
2911 self.resolve_path(mod_path, Some(TypeNS), None, PathSource::Type)
2912 {
2913 self.r.add_module_candidates(module, &mut names, &filter_fn, None);
2914 }
2915 }
2916
2917 if let Some(following_seg) = following_seg {
2919 names.retain(|suggestion| match suggestion.res {
2920 Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _) => {
2921 suggestion.candidate != following_seg.ident.name
2923 }
2924 Res::Def(DefKind::Mod, def_id) => {
2925 let module = self.r.expect_module(def_id);
2926 self.r
2927 .resolutions(module)
2928 .borrow()
2929 .iter()
2930 .any(|(key, _)| key.ident.name == following_seg.ident.name)
2931 }
2932 _ => true,
2933 });
2934 }
2935 let name = path[path.len() - 1].ident.name;
2936 names.sort_by(|a, b| a.candidate.as_str().cmp(b.candidate.as_str()));
2938
2939 match find_best_match_for_name(
2940 &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
2941 name,
2942 None,
2943 ) {
2944 Some(found) => {
2945 let Some(sugg) = names.into_iter().find(|suggestion| suggestion.candidate == found)
2946 else {
2947 return TypoCandidate::None;
2948 };
2949 if found == name {
2950 TypoCandidate::Shadowed(sugg.res, sugg.span)
2951 } else {
2952 TypoCandidate::Typo(sugg)
2953 }
2954 }
2955 _ => TypoCandidate::None,
2956 }
2957 }
2958
2959 fn likely_rust_type(path: &[Segment]) -> Option<Symbol> {
2962 let name = path[path.len() - 1].ident.as_str();
2963 Some(match name {
2965 "byte" => sym::u8, "short" => sym::i16,
2967 "Bool" => sym::bool,
2968 "Boolean" => sym::bool,
2969 "boolean" => sym::bool,
2970 "int" => sym::i32,
2971 "long" => sym::i64,
2972 "float" => sym::f32,
2973 "double" => sym::f64,
2974 _ => return None,
2975 })
2976 }
2977
2978 fn let_binding_suggestion(&self, err: &mut Diag<'_>, ident_span: Span) -> bool {
2981 if ident_span.from_expansion() {
2982 return false;
2983 }
2984
2985 if let Some(Expr { kind: ExprKind::Assign(lhs, ..), .. }) = self.diag_metadata.in_assignment
2987 && let ast::ExprKind::Path(None, ref path) = lhs.kind
2988 && self.r.tcx.sess.source_map().is_line_before_span_empty(ident_span)
2989 {
2990 let (span, text) = match path.segments.first() {
2991 Some(seg) if let Some(name) = seg.ident.as_str().strip_prefix("let") => {
2992 let name = name.trim_prefix('_');
2994 (ident_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("let {0}", name))
})format!("let {name}"))
2995 }
2996 _ => (ident_span.shrink_to_lo(), "let ".to_string()),
2997 };
2998
2999 err.span_suggestion_verbose(
3000 span,
3001 "you might have meant to introduce a new binding",
3002 text,
3003 Applicability::MaybeIncorrect,
3004 );
3005 return true;
3006 }
3007
3008 if err.code == Some(E0423)
3011 && let Some((let_span, None, Some(val_span))) = self.diag_metadata.current_let_binding
3012 && val_span.contains(ident_span)
3013 && val_span.lo() == ident_span.lo()
3014 {
3015 err.span_suggestion_verbose(
3016 let_span.shrink_to_hi().to(val_span.shrink_to_lo()),
3017 "you might have meant to use `:` for type annotation",
3018 ": ",
3019 Applicability::MaybeIncorrect,
3020 );
3021 return true;
3022 }
3023 false
3024 }
3025
3026 fn find_module(&self, def_id: DefId) -> Option<(Module<'ra>, ImportSuggestion)> {
3027 let mut result = None;
3028 let mut seen_modules = FxHashSet::default();
3029 let root_did = self.r.graph_root.def_id();
3030 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, ThinVec::new(),
root_did.is_local() ||
!self.r.tcx.is_doc_hidden(root_did))]))vec![(
3031 self.r.graph_root,
3032 ThinVec::new(),
3033 root_did.is_local() || !self.r.tcx.is_doc_hidden(root_did),
3034 )];
3035
3036 while let Some((in_module, path_segments, doc_visible)) = worklist.pop() {
3037 if result.is_some() {
3039 break;
3040 }
3041
3042 in_module.for_each_child(self.r, |r, ident, orig_ident_span, _, name_binding| {
3043 if result.is_some() || !name_binding.vis().is_visible_locally() {
3045 return;
3046 }
3047 if let Some(module_def_id) = name_binding.res().module_like_def_id() {
3048 let mut path_segments = path_segments.clone();
3050 path_segments.push(ast::PathSegment::from_ident(ident.orig(orig_ident_span)));
3051 let doc_visible = doc_visible
3052 && (module_def_id.is_local() || !r.tcx.is_doc_hidden(module_def_id));
3053 if module_def_id == def_id {
3054 let path =
3055 Path { span: name_binding.span, segments: path_segments, tokens: None };
3056 result = Some((
3057 r.expect_module(module_def_id),
3058 ImportSuggestion {
3059 did: Some(def_id),
3060 descr: "module",
3061 path,
3062 accessible: true,
3063 doc_visible,
3064 note: None,
3065 via_import: false,
3066 is_stable: true,
3067 },
3068 ));
3069 } else {
3070 if seen_modules.insert(module_def_id) {
3072 let module = r.expect_module(module_def_id);
3073 worklist.push((module, path_segments, doc_visible));
3074 }
3075 }
3076 }
3077 });
3078 }
3079
3080 result
3081 }
3082
3083 fn collect_enum_ctors(&self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
3084 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
3085 let mut variants = Vec::new();
3086 enum_module.for_each_child(self.r, |_, ident, orig_ident_span, _, name_binding| {
3087 if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
3088 let mut segms = enum_import_suggestion.path.segments.clone();
3089 segms.push(ast::PathSegment::from_ident(ident.orig(orig_ident_span)));
3090 let path = Path { span: name_binding.span, segments: segms, tokens: None };
3091 variants.push((path, def_id, kind));
3092 }
3093 });
3094 variants
3095 })
3096 }
3097
3098 fn suggest_using_enum_variant(
3100 &self,
3101 err: &mut Diag<'_>,
3102 source: PathSource<'_, '_, '_>,
3103 def_id: DefId,
3104 span: Span,
3105 ) {
3106 let Some(variant_ctors) = self.collect_enum_ctors(def_id) else {
3107 err.note("you might have meant to use one of the enum's variants");
3108 return;
3109 };
3110
3111 let (suggest_path_sep_dot_span, suggest_only_tuple_variants) = match source {
3116 PathSource::TupleStruct(..) => (None, true),
3118 PathSource::Expr(Some(expr)) => match &expr.kind {
3119 ExprKind::Call(..) => (None, true),
3121 ExprKind::MethodCall(box MethodCall {
3124 receiver,
3125 span,
3126 seg: PathSegment { ident, .. },
3127 ..
3128 }) => {
3129 let dot_span = receiver.span.between(*span);
3130 let found_tuple_variant = variant_ctors.iter().any(|(path, _, ctor_kind)| {
3131 *ctor_kind == CtorKind::Fn
3132 && path.segments.last().is_some_and(|seg| seg.ident == *ident)
3133 });
3134 (found_tuple_variant.then_some(dot_span), false)
3135 }
3136 ExprKind::Field(base, ident) => {
3139 let dot_span = base.span.between(ident.span);
3140 let found_tuple_or_unit_variant = variant_ctors.iter().any(|(path, ..)| {
3141 path.segments.last().is_some_and(|seg| seg.ident == *ident)
3142 });
3143 (found_tuple_or_unit_variant.then_some(dot_span), false)
3144 }
3145 _ => (None, false),
3146 },
3147 _ => (None, false),
3148 };
3149
3150 if let Some(dot_span) = suggest_path_sep_dot_span {
3151 err.span_suggestion_verbose(
3152 dot_span,
3153 "use the path separator to refer to a variant",
3154 "::",
3155 Applicability::MaybeIncorrect,
3156 );
3157 } else if suggest_only_tuple_variants {
3158 let mut suggestable_variants = variant_ctors
3161 .iter()
3162 .filter(|(.., kind)| *kind == CtorKind::Fn)
3163 .map(|(variant, ..)| path_names_to_string(variant))
3164 .collect::<Vec<_>>();
3165 suggestable_variants.sort();
3166
3167 let non_suggestable_variant_count = variant_ctors.len() - suggestable_variants.len();
3168
3169 let source_msg = if #[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::TupleStruct(..) => true,
_ => false,
}matches!(source, PathSource::TupleStruct(..)) {
3170 "to match against"
3171 } else {
3172 "to construct"
3173 };
3174
3175 if !suggestable_variants.is_empty() {
3176 let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
3177 ::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")
3178 } else {
3179 ::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")
3180 };
3181
3182 err.span_suggestions(
3183 span,
3184 msg,
3185 suggestable_variants,
3186 Applicability::MaybeIncorrect,
3187 );
3188 }
3189
3190 if non_suggestable_variant_count == variant_ctors.len() {
3192 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}"));
3193 }
3194
3195 if non_suggestable_variant_count == 1 {
3197 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"));
3198 } else if non_suggestable_variant_count >= 1 {
3199 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!(
3200 "you might have meant {source_msg} one of the enum's non-tuple variants"
3201 ));
3202 }
3203 } else {
3204 let needs_placeholder = |ctor_def_id: DefId, kind: CtorKind| {
3205 let def_id = self.r.tcx.parent(ctor_def_id);
3206 match kind {
3207 CtorKind::Const => false,
3208 CtorKind::Fn => {
3209 !self.r.field_idents(def_id).is_some_and(|field_ids| field_ids.is_empty())
3210 }
3211 }
3212 };
3213
3214 let mut suggestable_variants = variant_ctors
3215 .iter()
3216 .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind))
3217 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
3218 .map(|(variant, kind)| match kind {
3219 CtorKind::Const => variant,
3220 CtorKind::Fn => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0}())", variant))
})format!("({variant}())"),
3221 })
3222 .collect::<Vec<_>>();
3223 suggestable_variants.sort();
3224 let no_suggestable_variant = suggestable_variants.is_empty();
3225
3226 if !no_suggestable_variant {
3227 let msg = if suggestable_variants.len() == 1 {
3228 "you might have meant to use the following enum variant"
3229 } else {
3230 "you might have meant to use one of the following enum variants"
3231 };
3232
3233 err.span_suggestions(
3234 span,
3235 msg,
3236 suggestable_variants,
3237 Applicability::MaybeIncorrect,
3238 );
3239 }
3240
3241 let mut suggestable_variants_with_placeholders = variant_ctors
3242 .iter()
3243 .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
3244 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
3245 .filter_map(|(variant, kind)| match kind {
3246 CtorKind::Fn => Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0}(/* fields */))", variant))
})format!("({variant}(/* fields */))")),
3247 _ => None,
3248 })
3249 .collect::<Vec<_>>();
3250 suggestable_variants_with_placeholders.sort();
3251
3252 if !suggestable_variants_with_placeholders.is_empty() {
3253 let msg =
3254 match (no_suggestable_variant, suggestable_variants_with_placeholders.len()) {
3255 (true, 1) => "the following enum variant is available",
3256 (true, _) => "the following enum variants are available",
3257 (false, 1) => "alternatively, the following enum variant is available",
3258 (false, _) => {
3259 "alternatively, the following enum variants are also available"
3260 }
3261 };
3262
3263 err.span_suggestions(
3264 span,
3265 msg,
3266 suggestable_variants_with_placeholders,
3267 Applicability::HasPlaceholders,
3268 );
3269 }
3270 };
3271
3272 if def_id.is_local() {
3273 err.span_note(self.r.def_span(def_id), "the enum is defined here");
3274 }
3275 }
3276
3277 pub(crate) fn suggest_adding_generic_parameter(
3278 &self,
3279 path: &[Segment],
3280 source: PathSource<'_, '_, '_>,
3281 ) -> Option<(Span, &'static str, String, Applicability)> {
3282 let (ident, span) = match path {
3283 [segment]
3284 if !segment.has_generic_args
3285 && segment.ident.name != kw::SelfUpper
3286 && segment.ident.name != kw::Dyn =>
3287 {
3288 (segment.ident.to_string(), segment.ident.span)
3289 }
3290 _ => return None,
3291 };
3292 let mut iter = ident.chars().map(|c| c.is_uppercase());
3293 let single_uppercase_char =
3294 #[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);
3295 if !self.diag_metadata.currently_processing_generic_args && !single_uppercase_char {
3296 return None;
3297 }
3298 match (self.diag_metadata.current_item, single_uppercase_char, self.diag_metadata.currently_processing_generic_args) {
3299 (Some(Item { kind: ItemKind::Fn(fn_), .. }), _, _) if fn_.ident.name == sym::main => {
3300 }
3302 (
3303 Some(Item {
3304 kind:
3305 kind @ ItemKind::Fn(..)
3306 | kind @ ItemKind::Enum(..)
3307 | kind @ ItemKind::Struct(..)
3308 | kind @ ItemKind::Union(..),
3309 ..
3310 }),
3311 true, _
3312 )
3313 | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true)
3315 | (Some(Item { kind, .. }), false, _) => {
3316 if let Some(generics) = kind.generics() {
3317 if span.overlaps(generics.span) {
3318 return None;
3327 }
3328
3329 let (msg, sugg) = match source {
3330 PathSource::Type | PathSource::PreciseCapturingArg(TypeNS) => {
3331 ("you might be missing a type parameter", ident)
3332 }
3333 PathSource::Expr(_) | PathSource::PreciseCapturingArg(ValueNS) => (
3334 "you might be missing a const parameter",
3335 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("const {0}: /* Type */", ident))
})format!("const {ident}: /* Type */"),
3336 ),
3337 _ => return None,
3338 };
3339 let (span, sugg) = if let [.., param] = &generics.params[..] {
3340 let span = if let [.., bound] = ¶m.bounds[..] {
3341 bound.span()
3342 } else if let GenericParam {
3343 kind: GenericParamKind::Const { ty, span: _, default }, ..
3344 } = param {
3345 default.as_ref().map(|def| def.value.span).unwrap_or(ty.span)
3346 } else {
3347 param.ident.span
3348 };
3349 (span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", {0}", sugg))
})format!(", {sugg}"))
3350 } else {
3351 (generics.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", sugg))
})format!("<{sugg}>"))
3352 };
3353 if span.can_be_used_for_suggestions() {
3355 return Some((
3356 span.shrink_to_hi(),
3357 msg,
3358 sugg,
3359 Applicability::MaybeIncorrect,
3360 ));
3361 }
3362 }
3363 }
3364 _ => {}
3365 }
3366 None
3367 }
3368
3369 pub(crate) fn suggestion_for_label_in_rib(
3372 &self,
3373 rib_index: usize,
3374 label: Ident,
3375 ) -> Option<LabelSuggestion> {
3376 let within_scope = self.is_label_valid_from_rib(rib_index);
3378
3379 let rib = &self.label_ribs[rib_index];
3380 let names = rib
3381 .bindings
3382 .iter()
3383 .filter(|(id, _)| id.span.eq_ctxt(label.span))
3384 .map(|(id, _)| id.name)
3385 .collect::<Vec<Symbol>>();
3386
3387 find_best_match_for_name(&names, label.name, None).map(|symbol| {
3388 let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
3392 (*ident, within_scope)
3393 })
3394 }
3395
3396 pub(crate) fn maybe_report_lifetime_uses(
3397 &mut self,
3398 generics_span: Span,
3399 params: &[ast::GenericParam],
3400 ) {
3401 for (param_index, param) in params.iter().enumerate() {
3402 let GenericParamKind::Lifetime = param.kind else { continue };
3403
3404 let def_id = self.r.local_def_id(param.id);
3405
3406 let use_set = self.lifetime_uses.remove(&def_id);
3407 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late/diagnostics.rs:3407",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3407u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::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 Value))])
});
} else { ; }
};debug!(
3408 "Use set for {:?}({:?} at {:?}) is {:?}",
3409 def_id, param.ident, param.ident.span, use_set
3410 );
3411
3412 let deletion_span = || {
3413 if params.len() == 1 {
3414 Some(generics_span)
3416 } else if param_index == 0 {
3417 match (
3420 param.span().find_ancestor_inside(generics_span),
3421 params[param_index + 1].span().find_ancestor_inside(generics_span),
3422 ) {
3423 (Some(param_span), Some(next_param_span)) => {
3424 Some(param_span.to(next_param_span.shrink_to_lo()))
3425 }
3426 _ => None,
3427 }
3428 } else {
3429 match (
3432 param.span().find_ancestor_inside(generics_span),
3433 params[param_index - 1].span().find_ancestor_inside(generics_span),
3434 ) {
3435 (Some(param_span), Some(prev_param_span)) => {
3436 Some(prev_param_span.shrink_to_hi().to(param_span))
3437 }
3438 _ => None,
3439 }
3440 }
3441 };
3442 match use_set {
3443 Some(LifetimeUseSet::Many) => {}
3444 Some(LifetimeUseSet::One { use_span, use_ctxt }) => {
3445 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late/diagnostics.rs:3445",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3445u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&["param.ident",
"param.ident.span", "use_span"],
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(¶m.ident)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(¶m.ident.span)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&use_span)
as &dyn Value))])
});
} else { ; }
};debug!(?param.ident, ?param.ident.span, ?use_span);
3446
3447 let elidable = #[allow(non_exhaustive_omitted_patterns)] match use_ctxt {
LifetimeCtxt::Ref => true,
_ => false,
}matches!(use_ctxt, LifetimeCtxt::Ref);
3448 let deletion_span =
3449 if param.bounds.is_empty() { deletion_span() } else { None };
3450
3451 self.r.lint_buffer.buffer_lint(
3452 lint::builtin::SINGLE_USE_LIFETIMES,
3453 param.id,
3454 param.ident.span,
3455 lint::BuiltinLintDiag::SingleUseLifetime {
3456 param_span: param.ident.span,
3457 use_span: Some((use_span, elidable)),
3458 deletion_span,
3459 ident: param.ident,
3460 },
3461 );
3462 }
3463 None => {
3464 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late/diagnostics.rs:3464",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3464u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&["param.ident",
"param.ident.span"],
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(¶m.ident)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(¶m.ident.span)
as &dyn Value))])
});
} else { ; }
};debug!(?param.ident, ?param.ident.span);
3465 let deletion_span = deletion_span();
3466
3467 if deletion_span.is_some_and(|sp| !sp.in_derive_expansion()) {
3469 self.r.lint_buffer.buffer_lint(
3470 lint::builtin::UNUSED_LIFETIMES,
3471 param.id,
3472 param.ident.span,
3473 lint::BuiltinLintDiag::SingleUseLifetime {
3474 param_span: param.ident.span,
3475 use_span: None,
3476 deletion_span,
3477 ident: param.ident,
3478 },
3479 );
3480 }
3481 }
3482 }
3483 }
3484 }
3485
3486 pub(crate) fn emit_undeclared_lifetime_error(
3487 &self,
3488 lifetime_ref: &ast::Lifetime,
3489 outer_lifetime_ref: Option<Ident>,
3490 ) -> ErrorGuaranteed {
3491 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);
3492 let mut err = if let Some(outer) = outer_lifetime_ref {
3493 {
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!(
3494 self.r.dcx(),
3495 lifetime_ref.ident.span,
3496 E0401,
3497 "can't use generic parameters from outer item",
3498 )
3499 .with_span_label(lifetime_ref.ident.span, "use of generic parameter from outer item")
3500 .with_span_label(outer.span, "lifetime parameter from outer item")
3501 } else {
3502 {
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!(
3503 self.r.dcx(),
3504 lifetime_ref.ident.span,
3505 E0261,
3506 "use of undeclared lifetime name `{}`",
3507 lifetime_ref.ident
3508 )
3509 .with_span_label(lifetime_ref.ident.span, "undeclared lifetime")
3510 };
3511
3512 if edit_distance(lifetime_ref.ident.name.as_str(), "'static", 2).is_some() {
3514 err.span_suggestion_verbose(
3515 lifetime_ref.ident.span,
3516 "you may have misspelled the `'static` lifetime",
3517 "'static",
3518 Applicability::MachineApplicable,
3519 );
3520 } else {
3521 self.suggest_introducing_lifetime(
3522 &mut err,
3523 Some(lifetime_ref.ident),
3524 |err, _, span, message, suggestion, span_suggs| {
3525 err.multipart_suggestion(
3526 message,
3527 std::iter::once((span, suggestion)).chain(span_suggs).collect(),
3528 Applicability::MaybeIncorrect,
3529 );
3530 true
3531 },
3532 );
3533 }
3534
3535 err.emit()
3536 }
3537
3538 fn suggest_introducing_lifetime(
3539 &self,
3540 err: &mut Diag<'_>,
3541 name: Option<Ident>,
3542 suggest: impl Fn(
3543 &mut Diag<'_>,
3544 bool,
3545 Span,
3546 Cow<'static, str>,
3547 String,
3548 Vec<(Span, String)>,
3549 ) -> bool,
3550 ) {
3551 let mut suggest_note = true;
3552 for rib in self.lifetime_ribs.iter().rev() {
3553 let mut should_continue = true;
3554 match rib.kind {
3555 LifetimeRibKind::Generics { binder, span, kind } => {
3556 if let LifetimeBinderKind::ConstItem = kind
3559 && !self.r.tcx().features().generic_const_items()
3560 {
3561 continue;
3562 }
3563 if let LifetimeBinderKind::ImplAssocType = kind {
3564 continue;
3565 }
3566
3567 if !span.can_be_used_for_suggestions()
3568 && suggest_note
3569 && let Some(name) = name
3570 {
3571 suggest_note = false; err.span_label(
3573 span,
3574 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("lifetime `{0}` is missing in item created through this procedural macro",
name))
})format!(
3575 "lifetime `{name}` is missing in item created through this procedural macro",
3576 ),
3577 );
3578 continue;
3579 }
3580
3581 let higher_ranked = #[allow(non_exhaustive_omitted_patterns)] match kind {
LifetimeBinderKind::FnPtrType | LifetimeBinderKind::PolyTrait |
LifetimeBinderKind::WhereBound => true,
_ => false,
}matches!(
3582 kind,
3583 LifetimeBinderKind::FnPtrType
3584 | LifetimeBinderKind::PolyTrait
3585 | LifetimeBinderKind::WhereBound
3586 );
3587
3588 let mut rm_inner_binders: FxIndexSet<Span> = Default::default();
3589 let (span, sugg) = if span.is_empty() {
3590 let mut binder_idents: FxIndexSet<Ident> = Default::default();
3591 binder_idents.insert(name.unwrap_or(Ident::from_str("'a")));
3592
3593 if let LifetimeBinderKind::WhereBound = kind
3600 && let Some(predicate) = self.diag_metadata.current_where_predicate
3601 && let ast::WherePredicateKind::BoundPredicate(
3602 ast::WhereBoundPredicate { bounded_ty, bounds, .. },
3603 ) = &predicate.kind
3604 && bounded_ty.id == binder
3605 {
3606 for bound in bounds {
3607 if let ast::GenericBound::Trait(poly_trait_ref) = bound
3608 && let span = poly_trait_ref
3609 .span
3610 .with_hi(poly_trait_ref.trait_ref.path.span.lo())
3611 && !span.is_empty()
3612 {
3613 rm_inner_binders.insert(span);
3614 poly_trait_ref.bound_generic_params.iter().for_each(|v| {
3615 binder_idents.insert(v.ident);
3616 });
3617 }
3618 }
3619 }
3620
3621 let binders_sugg: String = binder_idents
3622 .into_iter()
3623 .map(|ident| ident.to_string())
3624 .intersperse(", ".to_owned())
3625 .collect();
3626 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!(
3627 "{}<{}>{}",
3628 if higher_ranked { "for" } else { "" },
3629 binders_sugg,
3630 if higher_ranked { " " } else { "" },
3631 );
3632 (span, sugg)
3633 } else {
3634 let span = self
3635 .r
3636 .tcx
3637 .sess
3638 .source_map()
3639 .span_through_char(span, '<')
3640 .shrink_to_hi();
3641 let sugg =
3642 ::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"));
3643 (span, sugg)
3644 };
3645
3646 if higher_ranked {
3647 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!(
3648 "consider making the {} lifetime-generic with a new `{}` lifetime",
3649 kind.descr(),
3650 name.map(|i| i.to_string()).as_deref().unwrap_or("'a"),
3651 ));
3652 should_continue = suggest(
3653 err,
3654 true,
3655 span,
3656 message,
3657 sugg,
3658 if !rm_inner_binders.is_empty() {
3659 rm_inner_binders
3660 .into_iter()
3661 .map(|v| (v, "".to_string()))
3662 .collect::<Vec<_>>()
3663 } else {
3664 ::alloc::vec::Vec::new()vec![]
3665 },
3666 );
3667 err.note_once(
3668 "for more information on higher-ranked polymorphism, visit \
3669 https://doc.rust-lang.org/nomicon/hrtb.html",
3670 );
3671 } else if let Some(name) = name {
3672 let message =
3673 Cow::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider introducing lifetime `{0}` here",
name))
})format!("consider introducing lifetime `{name}` here"));
3674 should_continue = suggest(err, false, span, message, sugg, ::alloc::vec::Vec::new()vec![]);
3675 } else {
3676 let message = Cow::from("consider introducing a named lifetime parameter");
3677 should_continue = suggest(err, false, span, message, sugg, ::alloc::vec::Vec::new()vec![]);
3678 }
3679 }
3680 LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy => break,
3681 _ => {}
3682 }
3683 if !should_continue {
3684 break;
3685 }
3686 }
3687 }
3688
3689 pub(crate) fn emit_non_static_lt_in_const_param_ty_error(
3690 &self,
3691 lifetime_ref: &ast::Lifetime,
3692 ) -> ErrorGuaranteed {
3693 self.r
3694 .dcx()
3695 .create_err(errors::ParamInTyOfConstParam {
3696 span: lifetime_ref.ident.span,
3697 name: lifetime_ref.ident.name,
3698 })
3699 .emit()
3700 }
3701
3702 pub(crate) fn emit_forbidden_non_static_lifetime_error(
3706 &self,
3707 cause: NoConstantGenericsReason,
3708 lifetime_ref: &ast::Lifetime,
3709 ) -> ErrorGuaranteed {
3710 match cause {
3711 NoConstantGenericsReason::IsEnumDiscriminant => self
3712 .r
3713 .dcx()
3714 .create_err(errors::ParamInEnumDiscriminant {
3715 span: lifetime_ref.ident.span,
3716 name: lifetime_ref.ident.name,
3717 param_kind: errors::ParamKindInEnumDiscriminant::Lifetime,
3718 })
3719 .emit(),
3720 NoConstantGenericsReason::NonTrivialConstArg => {
3721 if !!self.r.tcx.features().generic_const_exprs() {
::core::panicking::panic("assertion failed: !self.r.tcx.features().generic_const_exprs()")
};assert!(!self.r.tcx.features().generic_const_exprs());
3722 self.r
3723 .dcx()
3724 .create_err(errors::ParamInNonTrivialAnonConst {
3725 span: lifetime_ref.ident.span,
3726 name: lifetime_ref.ident.name,
3727 param_kind: errors::ParamKindInNonTrivialAnonConst::Lifetime,
3728 help: self.r.tcx.sess.is_nightly_build(),
3729 is_ogca: self.r.tcx.features().opaque_generic_const_args(),
3730 help_ogca: self.r.tcx.features().opaque_generic_const_args(),
3731 })
3732 .emit()
3733 }
3734 }
3735 }
3736
3737 pub(crate) fn report_missing_lifetime_specifiers<'a>(
3738 &mut self,
3739 lifetime_refs: impl Clone + IntoIterator<Item = &'a MissingLifetime>,
3740 function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
3741 ) -> ErrorGuaranteed {
3742 let num_lifetimes: usize = lifetime_refs.clone().into_iter().map(|lt| lt.count).sum();
3743 let spans: Vec<_> = lifetime_refs.clone().into_iter().map(|lt| lt.span).collect();
3744
3745 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!(
3746 self.r.dcx(),
3747 spans,
3748 E0106,
3749 "missing lifetime specifier{}",
3750 pluralize!(num_lifetimes)
3751 );
3752 self.add_missing_lifetime_specifiers_label(
3753 &mut err,
3754 lifetime_refs,
3755 function_param_lifetimes,
3756 );
3757 err.emit()
3758 }
3759
3760 fn add_missing_lifetime_specifiers_label<'a>(
3761 &mut self,
3762 err: &mut Diag<'_>,
3763 lifetime_refs: impl Clone + IntoIterator<Item = &'a MissingLifetime>,
3764 function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
3765 ) {
3766 for < in lifetime_refs.clone() {
3767 err.span_label(
3768 lt.span,
3769 ::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!(
3770 "expected {} lifetime parameter{}",
3771 if lt.count == 1 { "named".to_string() } else { lt.count.to_string() },
3772 pluralize!(lt.count),
3773 ),
3774 );
3775 }
3776
3777 let mut in_scope_lifetimes: Vec<_> = self
3778 .lifetime_ribs
3779 .iter()
3780 .rev()
3781 .take_while(|rib| {
3782 !#[allow(non_exhaustive_omitted_patterns)] match rib.kind {
LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy => true,
_ => false,
}matches!(rib.kind, LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy)
3783 })
3784 .flat_map(|rib| rib.bindings.iter())
3785 .map(|(&ident, &res)| (ident, res))
3786 .filter(|(ident, _)| ident.name != kw::UnderscoreLifetime)
3787 .collect();
3788 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late/diagnostics.rs:3788",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3788u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&["in_scope_lifetimes"],
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&in_scope_lifetimes)
as &dyn Value))])
});
} else { ; }
};debug!(?in_scope_lifetimes);
3789
3790 let mut maybe_static = false;
3791 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late/diagnostics.rs:3791",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3791u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&["function_param_lifetimes"],
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&function_param_lifetimes)
as &dyn Value))])
});
} else { ; }
};debug!(?function_param_lifetimes);
3792 if let Some((param_lifetimes, params)) = &function_param_lifetimes {
3793 let elided_len = param_lifetimes.len();
3794 let num_params = params.len();
3795
3796 let mut m = String::new();
3797
3798 for (i, info) in params.iter().enumerate() {
3799 let ElisionFnParameter { ident, index, lifetime_count, span } = *info;
3800 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);
3801
3802 err.span_label(span, "");
3803
3804 if i != 0 {
3805 if i + 1 < num_params {
3806 m.push_str(", ");
3807 } else if num_params == 2 {
3808 m.push_str(" or ");
3809 } else {
3810 m.push_str(", or ");
3811 }
3812 }
3813
3814 let help_name = if let Some(ident) = ident {
3815 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", ident))
})format!("`{ident}`")
3816 } else {
3817 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("argument {0}", index + 1))
})format!("argument {}", index + 1)
3818 };
3819
3820 if lifetime_count == 1 {
3821 m.push_str(&help_name[..])
3822 } else {
3823 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")[..])
3824 }
3825 }
3826
3827 if num_params == 0 {
3828 err.help(
3829 "this function's return type contains a borrowed value, but there is no value \
3830 for it to be borrowed from",
3831 );
3832 if in_scope_lifetimes.is_empty() {
3833 maybe_static = true;
3834 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![(
3835 Ident::with_dummy_span(kw::StaticLifetime),
3836 (DUMMY_NODE_ID, LifetimeRes::Static),
3837 )];
3838 }
3839 } else if elided_len == 0 {
3840 err.help(
3841 "this function's return type contains a borrowed value with an elided \
3842 lifetime, but the lifetime cannot be derived from the arguments",
3843 );
3844 if in_scope_lifetimes.is_empty() {
3845 maybe_static = true;
3846 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![(
3847 Ident::with_dummy_span(kw::StaticLifetime),
3848 (DUMMY_NODE_ID, LifetimeRes::Static),
3849 )];
3850 }
3851 } else if num_params == 1 {
3852 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!(
3853 "this function's return type contains a borrowed value, but the signature does \
3854 not say which {m} it is borrowed from",
3855 ));
3856 } else {
3857 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!(
3858 "this function's return type contains a borrowed value, but the signature does \
3859 not say whether it is borrowed from {m}",
3860 ));
3861 }
3862 }
3863
3864 #[allow(rustc::symbol_intern_string_literal)]
3865 let existing_name = match &in_scope_lifetimes[..] {
3866 [] => Symbol::intern("'a"),
3867 [(existing, _)] => existing.name,
3868 _ => Symbol::intern("'lifetime"),
3869 };
3870
3871 let mut spans_suggs: Vec<_> = Vec::new();
3872 let build_sugg = |lt: MissingLifetime| match lt.kind {
3873 MissingLifetimeKind::Underscore => {
3874 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);
3875 (lt.span, existing_name.to_string())
3876 }
3877 MissingLifetimeKind::Ampersand => {
3878 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);
3879 (lt.span.shrink_to_hi(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} ", existing_name))
})format!("{existing_name} "))
3880 }
3881 MissingLifetimeKind::Comma => {
3882 let sugg: String = std::iter::repeat_n([existing_name.as_str(), ", "], lt.count)
3883 .flatten()
3884 .collect();
3885 (lt.span.shrink_to_hi(), sugg)
3886 }
3887 MissingLifetimeKind::Brackets => {
3888 let sugg: String = std::iter::once("<")
3889 .chain(std::iter::repeat_n(existing_name.as_str(), lt.count).intersperse(", "))
3890 .chain([">"])
3891 .collect();
3892 (lt.span.shrink_to_hi(), sugg)
3893 }
3894 };
3895 for < in lifetime_refs.clone() {
3896 spans_suggs.push(build_sugg(lt));
3897 }
3898 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late/diagnostics.rs:3898",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3898u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&["spans_suggs"],
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&spans_suggs)
as &dyn Value))])
});
} else { ; }
};debug!(?spans_suggs);
3899 match in_scope_lifetimes.len() {
3900 0 => {
3901 if let Some((param_lifetimes, _)) = function_param_lifetimes {
3902 for lt in param_lifetimes {
3903 spans_suggs.push(build_sugg(lt))
3904 }
3905 }
3906 self.suggest_introducing_lifetime(
3907 err,
3908 None,
3909 |err, higher_ranked, span, message, intro_sugg, _| {
3910 err.multipart_suggestion(
3911 message,
3912 std::iter::once((span, intro_sugg))
3913 .chain(spans_suggs.clone())
3914 .collect(),
3915 Applicability::MaybeIncorrect,
3916 );
3917 higher_ranked
3918 },
3919 );
3920 }
3921 1 => {
3922 let post = if maybe_static {
3923 let mut lifetime_refs = lifetime_refs.clone().into_iter();
3924 let owned = if let Some(lt) = lifetime_refs.next()
3925 && lifetime_refs.next().is_none()
3926 && lt.kind != MissingLifetimeKind::Ampersand
3927 {
3928 ", or if you will only have owned values"
3929 } else {
3930 ""
3931 };
3932 ::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!(
3933 ", but this is uncommon unless you're returning a borrowed value from a \
3934 `const` or a `static`{owned}",
3935 )
3936 } else {
3937 String::new()
3938 };
3939 err.multipart_suggestion(
3940 ::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}"),
3941 spans_suggs,
3942 Applicability::MaybeIncorrect,
3943 );
3944 if maybe_static {
3945 let mut lifetime_refs = lifetime_refs.clone().into_iter();
3951 if let Some(lt) = lifetime_refs.next()
3952 && lifetime_refs.next().is_none()
3953 && (lt.kind == MissingLifetimeKind::Ampersand
3954 || lt.kind == MissingLifetimeKind::Underscore)
3955 {
3956 let pre = if let Some((kind, _span)) = self.diag_metadata.current_function
3957 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
3958 && !sig.decl.inputs.is_empty()
3959 && let sugg = sig
3960 .decl
3961 .inputs
3962 .iter()
3963 .filter_map(|param| {
3964 if param.ty.span.contains(lt.span) {
3965 None
3968 } else if let TyKind::CVarArgs = param.ty.kind {
3969 None
3971 } else if let TyKind::ImplTrait(..) = ¶m.ty.kind {
3972 None
3974 } else {
3975 Some((param.ty.span.shrink_to_lo(), "&".to_string()))
3976 }
3977 })
3978 .collect::<Vec<_>>()
3979 && !sugg.is_empty()
3980 {
3981 let (the, s) = if sig.decl.inputs.len() == 1 {
3982 ("the", "")
3983 } else {
3984 ("one of the", "s")
3985 };
3986 let dotdotdot =
3987 if lt.kind == MissingLifetimeKind::Ampersand { "..." } else { "" };
3988 err.multipart_suggestion(
3989 ::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!(
3990 "instead, you are more likely to want to change {the} \
3991 argument{s} to be borrowed{dotdotdot}",
3992 ),
3993 sugg,
3994 Applicability::MaybeIncorrect,
3995 );
3996 "...or alternatively, you might want"
3997 } else if (lt.kind == MissingLifetimeKind::Ampersand
3998 || lt.kind == MissingLifetimeKind::Underscore)
3999 && let Some((kind, _span)) = self.diag_metadata.current_function
4000 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
4001 && let ast::FnRetTy::Ty(ret_ty) = &sig.decl.output
4002 && !sig.decl.inputs.is_empty()
4003 && let arg_refs = sig
4004 .decl
4005 .inputs
4006 .iter()
4007 .filter_map(|param| match ¶m.ty.kind {
4008 TyKind::ImplTrait(_, bounds) => Some(bounds),
4009 _ => None,
4010 })
4011 .flat_map(|bounds| bounds.into_iter())
4012 .collect::<Vec<_>>()
4013 && !arg_refs.is_empty()
4014 {
4015 let mut lt_finder =
4021 LifetimeFinder { lifetime: lt.span, found: None, seen: ::alloc::vec::Vec::new()vec![] };
4022 for bound in arg_refs {
4023 if let ast::GenericBound::Trait(trait_ref) = bound {
4024 lt_finder.visit_trait_ref(&trait_ref.trait_ref);
4025 }
4026 }
4027 lt_finder.visit_ty(ret_ty);
4028 let spans_suggs: Vec<_> = lt_finder
4029 .seen
4030 .iter()
4031 .filter_map(|ty| match &ty.kind {
4032 TyKind::Ref(_, mut_ty) => {
4033 let span = ty.span.with_hi(mut_ty.ty.span.lo());
4034 Some((span, "&'a ".to_string()))
4035 }
4036 _ => None,
4037 })
4038 .collect();
4039 self.suggest_introducing_lifetime(
4040 err,
4041 None,
4042 |err, higher_ranked, span, message, intro_sugg, _| {
4043 err.multipart_suggestion(
4044 message,
4045 std::iter::once((span, intro_sugg))
4046 .chain(spans_suggs.clone())
4047 .collect(),
4048 Applicability::MaybeIncorrect,
4049 );
4050 higher_ranked
4051 },
4052 );
4053 "alternatively, you might want"
4054 } else {
4055 "instead, you are more likely to want"
4056 };
4057 let mut owned_sugg = lt.kind == MissingLifetimeKind::Ampersand;
4058 let mut sugg_is_str_to_string = false;
4059 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())];
4060 if let Some((kind, _span)) = self.diag_metadata.current_function
4061 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
4062 {
4063 let mut lt_finder =
4064 LifetimeFinder { lifetime: lt.span, found: None, seen: ::alloc::vec::Vec::new()vec![] };
4065 for param in &sig.decl.inputs {
4066 lt_finder.visit_ty(¶m.ty);
4067 }
4068 if let ast::FnRetTy::Ty(ret_ty) = &sig.decl.output {
4069 lt_finder.visit_ty(ret_ty);
4070 let mut ret_lt_finder =
4071 LifetimeFinder { lifetime: lt.span, found: None, seen: ::alloc::vec::Vec::new()vec![] };
4072 ret_lt_finder.visit_ty(ret_ty);
4073 if let [Ty { span, kind: TyKind::Ref(_, mut_ty), .. }] =
4074 &ret_lt_finder.seen[..]
4075 {
4076 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())];
4082 owned_sugg = true;
4083 }
4084 }
4085 if let Some(ty) = lt_finder.found {
4086 if let TyKind::Path(None, path) = &ty.kind {
4087 let path: Vec<_> = Segment::from_path(path);
4089 match self.resolve_path(
4090 &path,
4091 Some(TypeNS),
4092 None,
4093 PathSource::Type,
4094 ) {
4095 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
4096 match module.res() {
4097 Some(Res::PrimTy(PrimTy::Str)) => {
4098 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![(
4100 lt.span.with_hi(ty.span.hi()),
4101 "String".to_string(),
4102 )];
4103 sugg_is_str_to_string = true;
4104 }
4105 Some(Res::PrimTy(..)) => {}
4106 Some(Res::Def(
4107 DefKind::Struct
4108 | DefKind::Union
4109 | DefKind::Enum
4110 | DefKind::ForeignTy
4111 | DefKind::AssocTy
4112 | DefKind::OpaqueTy
4113 | DefKind::TyParam,
4114 _,
4115 )) => {}
4116 _ => {
4117 owned_sugg = false;
4119 }
4120 }
4121 }
4122 PathResult::NonModule(res) => {
4123 match res.base_res() {
4124 Res::PrimTy(PrimTy::Str) => {
4125 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![(
4127 lt.span.with_hi(ty.span.hi()),
4128 "String".to_string(),
4129 )];
4130 sugg_is_str_to_string = true;
4131 }
4132 Res::PrimTy(..) => {}
4133 Res::Def(
4134 DefKind::Struct
4135 | DefKind::Union
4136 | DefKind::Enum
4137 | DefKind::ForeignTy
4138 | DefKind::AssocTy
4139 | DefKind::OpaqueTy
4140 | DefKind::TyParam,
4141 _,
4142 ) => {}
4143 _ => {
4144 owned_sugg = false;
4146 }
4147 }
4148 }
4149 _ => {
4150 owned_sugg = false;
4152 }
4153 }
4154 }
4155 if let TyKind::Slice(inner_ty) = &ty.kind {
4156 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![
4158 (lt.span.with_hi(inner_ty.span.lo()), "Vec<".to_string()),
4159 (ty.span.with_lo(inner_ty.span.hi()), ">".to_string()),
4160 ];
4161 }
4162 }
4163 }
4164 if owned_sugg {
4165 if let Some(span) =
4166 self.find_ref_prefix_span_for_owned_suggestion(lt.span)
4167 && !sugg_is_str_to_string
4168 {
4169 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())];
4170 }
4171 err.multipart_suggestion(
4172 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} to return an owned value",
pre))
})format!("{pre} to return an owned value"),
4173 sugg,
4174 Applicability::MaybeIncorrect,
4175 );
4176 }
4177 }
4178 }
4179 }
4180 _ => {
4181 let lifetime_spans: Vec<_> =
4182 in_scope_lifetimes.iter().map(|(ident, _)| ident.span).collect();
4183 err.span_note(lifetime_spans, "these named lifetimes are available to use");
4184
4185 if spans_suggs.len() > 0 {
4186 err.multipart_suggestion(
4189 "consider using one of the available lifetimes here",
4190 spans_suggs,
4191 Applicability::HasPlaceholders,
4192 );
4193 }
4194 }
4195 }
4196 }
4197
4198 fn find_ref_prefix_span_for_owned_suggestion(&self, lifetime: Span) -> Option<Span> {
4199 let mut finder = RefPrefixSpanFinder { lifetime, span: None };
4200 if let Some(item) = self.diag_metadata.current_item {
4201 finder.visit_item(item);
4202 } else if let Some((kind, _span)) = self.diag_metadata.current_function
4203 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
4204 {
4205 for param in &sig.decl.inputs {
4206 finder.visit_ty(¶m.ty);
4207 }
4208 if let ast::FnRetTy::Ty(ret_ty) = &sig.decl.output {
4209 finder.visit_ty(ret_ty);
4210 }
4211 }
4212 finder.span
4213 }
4214}
4215
4216fn mk_where_bound_predicate(
4217 path: &Path,
4218 poly_trait_ref: &ast::PolyTraitRef,
4219 ty: &Ty,
4220) -> Option<ast::WhereBoundPredicate> {
4221 let modified_segments = {
4222 let mut segments = path.segments.clone();
4223 let [preceding @ .., second_last, last] = segments.as_mut_slice() else {
4224 return None;
4225 };
4226 let mut segments = ThinVec::from(preceding);
4227
4228 let added_constraint = ast::AngleBracketedArg::Constraint(ast::AssocItemConstraint {
4229 id: DUMMY_NODE_ID,
4230 ident: last.ident,
4231 gen_args: None,
4232 kind: ast::AssocItemConstraintKind::Equality {
4233 term: ast::Term::Ty(Box::new(ast::Ty {
4234 kind: ast::TyKind::Path(None, poly_trait_ref.trait_ref.path.clone()),
4235 id: DUMMY_NODE_ID,
4236 span: DUMMY_SP,
4237 tokens: None,
4238 })),
4239 },
4240 span: DUMMY_SP,
4241 });
4242
4243 match second_last.args.as_deref_mut() {
4244 Some(ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs { args, .. })) => {
4245 args.push(added_constraint);
4246 }
4247 Some(_) => return None,
4248 None => {
4249 second_last.args =
4250 Some(Box::new(ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs {
4251 args: ThinVec::from([added_constraint]),
4252 span: DUMMY_SP,
4253 })));
4254 }
4255 }
4256
4257 segments.push(second_last.clone());
4258 segments
4259 };
4260
4261 let new_where_bound_predicate = ast::WhereBoundPredicate {
4262 bound_generic_params: ThinVec::new(),
4263 bounded_ty: Box::new(ty.clone()),
4264 bounds: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[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,
tokens: None,
},
ref_id: DUMMY_NODE_ID,
},
span: DUMMY_SP,
parens: ast::Parens::No,
})]))vec![ast::GenericBound::Trait(ast::PolyTraitRef {
4265 bound_generic_params: ThinVec::new(),
4266 modifiers: ast::TraitBoundModifiers::NONE,
4267 trait_ref: ast::TraitRef {
4268 path: ast::Path { segments: modified_segments, span: DUMMY_SP, tokens: None },
4269 ref_id: DUMMY_NODE_ID,
4270 },
4271 span: DUMMY_SP,
4272 parens: ast::Parens::No,
4273 })],
4274 };
4275
4276 Some(new_where_bound_predicate)
4277}
4278
4279pub(super) fn signal_lifetime_shadowing(
4281 sess: &Session,
4282 orig: Ident,
4283 shadower: Ident,
4284) -> ErrorGuaranteed {
4285 {
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!(
4286 sess.dcx(),
4287 shadower.span,
4288 E0496,
4289 "lifetime name `{}` shadows a lifetime name that is already in scope",
4290 orig.name,
4291 )
4292 .with_span_label(orig.span, "first declared here")
4293 .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))
4294 .emit()
4295}
4296
4297struct LifetimeFinder<'ast> {
4298 lifetime: Span,
4299 found: Option<&'ast Ty>,
4300 seen: Vec<&'ast Ty>,
4301}
4302
4303impl<'ast> Visitor<'ast> for LifetimeFinder<'ast> {
4304 fn visit_ty(&mut self, t: &'ast Ty) {
4305 if let TyKind::Ref(_, mut_ty) | TyKind::PinnedRef(_, mut_ty) = &t.kind {
4306 self.seen.push(t);
4307 if t.span.lo() == self.lifetime.lo() {
4308 self.found = Some(&mut_ty.ty);
4309 }
4310 }
4311 walk_ty(self, t)
4312 }
4313}
4314
4315struct RefPrefixSpanFinder {
4316 lifetime: Span,
4317 span: Option<Span>,
4318}
4319
4320impl<'ast> Visitor<'ast> for RefPrefixSpanFinder {
4321 fn visit_ty(&mut self, t: &'ast Ty) {
4322 if self.span.is_some() {
4323 return;
4324 }
4325 if let TyKind::Ref(_, mut_ty) | TyKind::PinnedRef(_, mut_ty) = &t.kind
4326 && t.span.lo() == self.lifetime.lo()
4327 {
4328 self.span = Some(t.span.with_hi(mut_ty.ty.span.lo()));
4329 return;
4330 }
4331 walk_ty(self, t);
4332 }
4333}
4334
4335pub(super) fn signal_label_shadowing(sess: &Session, orig: Span, shadower: Ident) {
4338 let name = shadower.name;
4339 let shadower = shadower.span;
4340 sess.dcx()
4341 .struct_span_warn(
4342 shadower,
4343 ::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"),
4344 )
4345 .with_span_label(orig, "first declared here")
4346 .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"))
4347 .emit();
4348}