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::where_bound_predicate_to_string;
13use rustc_data_structures::fx::{FxHashSet, 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::attrs::AttributeKind;
21use rustc_hir::def::Namespace::{self, *};
22use rustc_hir::def::{self, CtorKind, CtorOf, DefKind, MacroKinds};
23use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
24use rustc_hir::{MissingLifetimeKind, PrimTy};
25use rustc_middle::ty;
26use rustc_session::{Session, lint};
27use rustc_span::edit_distance::{edit_distance, find_best_match_for_name};
28use rustc_span::edition::Edition;
29use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym};
30use thin_vec::ThinVec;
31use tracing::debug;
32
33use super::NoConstantGenericsReason;
34use crate::diagnostics::{ImportSuggestion, LabelSuggestion, TypoSuggestion};
35use crate::late::{
36 AliasPossibility, LateResolutionVisitor, LifetimeBinderKind, LifetimeRes, LifetimeRibKind,
37 LifetimeUseSet, QSelf, RibKind,
38};
39use crate::ty::fast_reject::SimplifiedType;
40use crate::{
41 Module, ModuleKind, ModuleOrUniformRoot, ParentScope, PathResult, PathSource, Resolver,
42 ScopeSet, Segment, errors, path_names_to_string,
43};
44
45type Res = def::Res<ast::NodeId>;
46
47enum AssocSuggestion {
49 Field(Span),
50 MethodWithSelf { called: bool },
51 AssocFn { called: bool },
52 AssocType,
53 AssocConst,
54}
55
56impl AssocSuggestion {
57 fn action(&self) -> &'static str {
58 match self {
59 AssocSuggestion::Field(_) => "use the available field",
60 AssocSuggestion::MethodWithSelf { called: true } => {
61 "call the method with the fully-qualified path"
62 }
63 AssocSuggestion::MethodWithSelf { called: false } => {
64 "refer to the method with the fully-qualified path"
65 }
66 AssocSuggestion::AssocFn { called: true } => "call the associated function",
67 AssocSuggestion::AssocFn { called: false } => "refer to the associated function",
68 AssocSuggestion::AssocConst => "use the associated `const`",
69 AssocSuggestion::AssocType => "use the associated type",
70 }
71 }
72}
73
74fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
75 namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
76}
77
78fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
79 namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
80}
81
82fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
84 let variant_path = &suggestion.path;
85 let variant_path_string = path_names_to_string(variant_path);
86
87 let path_len = suggestion.path.segments.len();
88 let enum_path = ast::Path {
89 span: suggestion.path.span,
90 segments: suggestion.path.segments[0..path_len - 1].iter().cloned().collect(),
91 tokens: None,
92 };
93 let enum_path_string = path_names_to_string(&enum_path);
94
95 (variant_path_string, enum_path_string)
96}
97
98#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
100pub(super) struct MissingLifetime {
101 pub id: NodeId,
103 pub id_for_lint: NodeId,
110 pub span: Span,
112 pub kind: MissingLifetimeKind,
114 pub count: usize,
116}
117
118#[derive(Clone, Debug)]
121pub(super) struct ElisionFnParameter {
122 pub index: usize,
124 pub ident: Option<Ident>,
126 pub lifetime_count: usize,
128 pub span: Span,
130}
131
132#[derive(Debug)]
135pub(super) enum LifetimeElisionCandidate {
136 Ignore,
138 Named,
140 Missing(MissingLifetime),
141}
142
143#[derive(Debug)]
145struct BaseError {
146 msg: String,
147 fallback_label: String,
148 span: Span,
149 span_label: Option<(Span, &'static str)>,
150 could_be_expr: bool,
151 suggestion: Option<(Span, &'static str, String)>,
152 module: Option<DefId>,
153}
154
155#[derive(Debug)]
156enum TypoCandidate {
157 Typo(TypoSuggestion),
158 Shadowed(Res, Option<Span>),
159 None,
160}
161
162impl TypoCandidate {
163 fn to_opt_suggestion(self) -> Option<TypoSuggestion> {
164 match self {
165 TypoCandidate::Typo(sugg) => Some(sugg),
166 TypoCandidate::Shadowed(_, _) | TypoCandidate::None => None,
167 }
168 }
169}
170
171impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
172 fn make_base_error(
173 &mut self,
174 path: &[Segment],
175 span: Span,
176 source: PathSource<'_, 'ast, 'ra>,
177 res: Option<Res>,
178 ) -> BaseError {
179 let mut expected = source.descr_expected();
181 let path_str = Segment::names_to_string(path);
182 let item_str = path.last().unwrap().ident;
183
184 if let Some(res) = res {
185 BaseError {
186 msg: format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
187 fallback_label: format!("not a {expected}"),
188 span,
189 span_label: match res {
190 Res::Def(DefKind::TyParam, def_id) => {
191 Some((self.r.def_span(def_id), "found this type parameter"))
192 }
193 _ => None,
194 },
195 could_be_expr: match res {
196 Res::Def(DefKind::Fn, _) => {
197 self.r
199 .tcx
200 .sess
201 .source_map()
202 .span_to_snippet(span)
203 .is_ok_and(|snippet| snippet.ends_with(')'))
204 }
205 Res::Def(
206 DefKind::Ctor(..) | DefKind::AssocFn | DefKind::Const | DefKind::AssocConst,
207 _,
208 )
209 | Res::SelfCtor(_)
210 | Res::PrimTy(_)
211 | Res::Local(_) => true,
212 _ => false,
213 },
214 suggestion: None,
215 module: None,
216 }
217 } else {
218 let mut span_label = None;
219 let item_ident = path.last().unwrap().ident;
220 let item_span = item_ident.span;
221 let (mod_prefix, mod_str, module, suggestion) = if path.len() == 1 {
222 debug!(?self.diag_metadata.current_impl_items);
223 debug!(?self.diag_metadata.current_function);
224 let suggestion = if self.current_trait_ref.is_none()
225 && let Some((fn_kind, _)) = self.diag_metadata.current_function
226 && let Some(FnCtxt::Assoc(_)) = fn_kind.ctxt()
227 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = fn_kind
228 && let Some(items) = self.diag_metadata.current_impl_items
229 && let Some(item) = items.iter().find(|i| {
230 i.kind.ident().is_some_and(|ident| {
231 ident.name == item_str.name && !sig.span.contains(item_span)
233 })
234 }) {
235 let sp = item_span.shrink_to_lo();
236
237 let field = match source {
240 PathSource::Expr(Some(Expr { kind: ExprKind::Struct(expr), .. })) => {
241 expr.fields.iter().find(|f| f.ident == item_ident)
242 }
243 _ => None,
244 };
245 let pre = if let Some(field) = field
246 && field.is_shorthand
247 {
248 format!("{item_ident}: ")
249 } else {
250 String::new()
251 };
252 let is_call = match field {
255 Some(ast::ExprField { expr, .. }) => {
256 matches!(expr.kind, ExprKind::Call(..))
257 }
258 _ => matches!(
259 source,
260 PathSource::Expr(Some(Expr { kind: ExprKind::Call(..), .. })),
261 ),
262 };
263
264 match &item.kind {
265 AssocItemKind::Fn(fn_)
266 if (!sig.decl.has_self() || !is_call) && fn_.sig.decl.has_self() =>
267 {
268 span_label = Some((
272 fn_.ident.span,
273 "a method by that name is available on `Self` here",
274 ));
275 None
276 }
277 AssocItemKind::Fn(fn_) if !fn_.sig.decl.has_self() && !is_call => {
278 span_label = Some((
279 fn_.ident.span,
280 "an associated function by that name is available on `Self` here",
281 ));
282 None
283 }
284 AssocItemKind::Fn(fn_) if fn_.sig.decl.has_self() => {
285 Some((sp, "consider using the method on `Self`", format!("{pre}self.")))
286 }
287 AssocItemKind::Fn(_) => Some((
288 sp,
289 "consider using the associated function on `Self`",
290 format!("{pre}Self::"),
291 )),
292 AssocItemKind::Const(..) => Some((
293 sp,
294 "consider using the associated constant on `Self`",
295 format!("{pre}Self::"),
296 )),
297 _ => None,
298 }
299 } else {
300 None
301 };
302 (String::new(), "this scope".to_string(), None, suggestion)
303 } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
304 if self.r.tcx.sess.edition() > Edition::Edition2015 {
305 expected = "crate";
308 (String::new(), "the list of imported crates".to_string(), None, None)
309 } else {
310 (
311 String::new(),
312 "the crate root".to_string(),
313 Some(CRATE_DEF_ID.to_def_id()),
314 None,
315 )
316 }
317 } else if path.len() == 2 && path[0].ident.name == kw::Crate {
318 (String::new(), "the crate root".to_string(), Some(CRATE_DEF_ID.to_def_id()), None)
319 } else {
320 let mod_path = &path[..path.len() - 1];
321 let mod_res = self.resolve_path(mod_path, Some(TypeNS), None, source);
322 let mod_prefix = match mod_res {
323 PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
324 _ => None,
325 };
326
327 let module_did = mod_prefix.as_ref().and_then(Res::mod_def_id);
328
329 let mod_prefix =
330 mod_prefix.map_or_else(String::new, |res| format!("{} ", res.descr()));
331 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)), module_did, None)
332 };
333
334 let (fallback_label, suggestion) = if path_str == "async"
335 && expected.starts_with("struct")
336 {
337 ("`async` blocks are only allowed in Rust 2018 or later".to_string(), suggestion)
338 } else {
339 let override_suggestion =
341 if ["true", "false"].contains(&item_str.to_string().to_lowercase().as_str()) {
342 let item_typo = item_str.to_string().to_lowercase();
343 Some((item_span, "you may want to use a bool value instead", item_typo))
344 } else if item_str.as_str() == "printf" {
347 Some((
348 item_span,
349 "you may have meant to use the `print` macro",
350 "print!".to_owned(),
351 ))
352 } else {
353 suggestion
354 };
355 (format!("not found in {mod_str}"), override_suggestion)
356 };
357
358 BaseError {
359 msg: format!("cannot find {expected} `{item_str}` in {mod_prefix}{mod_str}"),
360 fallback_label,
361 span: item_span,
362 span_label,
363 could_be_expr: false,
364 suggestion,
365 module,
366 }
367 }
368 }
369
370 pub(crate) fn smart_resolve_partial_mod_path_errors(
378 &mut self,
379 prefix_path: &[Segment],
380 following_seg: Option<&Segment>,
381 ) -> Vec<ImportSuggestion> {
382 if let Some(segment) = prefix_path.last()
383 && let Some(following_seg) = following_seg
384 {
385 let candidates = self.r.lookup_import_candidates(
386 segment.ident,
387 Namespace::TypeNS,
388 &self.parent_scope,
389 &|res: Res| matches!(res, Res::Def(DefKind::Mod, _)),
390 );
391 candidates
393 .into_iter()
394 .filter(|candidate| {
395 if let Some(def_id) = candidate.did
396 && let Some(module) = self.r.get_module(def_id)
397 {
398 Some(def_id) != self.parent_scope.module.opt_def_id()
399 && self
400 .r
401 .resolutions(module)
402 .borrow()
403 .iter()
404 .any(|(key, _r)| key.ident.name == following_seg.ident.name)
405 } else {
406 false
407 }
408 })
409 .collect::<Vec<_>>()
410 } else {
411 Vec::new()
412 }
413 }
414
415 pub(crate) fn smart_resolve_report_errors(
418 &mut self,
419 path: &[Segment],
420 following_seg: Option<&Segment>,
421 span: Span,
422 source: PathSource<'_, 'ast, 'ra>,
423 res: Option<Res>,
424 qself: Option<&QSelf>,
425 ) -> (Diag<'tcx>, Vec<ImportSuggestion>) {
426 debug!(?res, ?source);
427 let base_error = self.make_base_error(path, span, source, res);
428
429 let code = source.error_code(res.is_some());
430 let mut err = self.r.dcx().struct_span_err(base_error.span, base_error.msg.clone());
431 err.code(code);
432
433 if let Some(within_macro_span) =
436 base_error.span.within_macro(span, self.r.tcx.sess.source_map())
437 {
438 err.span_label(within_macro_span, "due to this macro variable");
439 }
440
441 self.detect_missing_binding_available_from_pattern(&mut err, path, following_seg);
442 self.suggest_at_operator_in_slice_pat_with_range(&mut err, path);
443 self.suggest_range_struct_destructuring(&mut err, path, source);
444 self.suggest_swapping_misplaced_self_ty_and_trait(&mut err, source, res, base_error.span);
445
446 if let Some((span, label)) = base_error.span_label {
447 err.span_label(span, label);
448 }
449
450 if let Some(ref sugg) = base_error.suggestion {
451 err.span_suggestion_verbose(sugg.0, sugg.1, &sugg.2, Applicability::MaybeIncorrect);
452 }
453
454 self.suggest_changing_type_to_const_param(&mut err, res, source, span);
455 self.explain_functions_in_pattern(&mut err, res, source);
456
457 if self.suggest_pattern_match_with_let(&mut err, source, span) {
458 err.span_label(base_error.span, base_error.fallback_label);
460 return (err, Vec::new());
461 }
462
463 self.suggest_self_or_self_ref(&mut err, path, span);
464 self.detect_assoc_type_constraint_meant_as_path(&mut err, &base_error);
465 self.detect_rtn_with_fully_qualified_path(
466 &mut err,
467 path,
468 following_seg,
469 span,
470 source,
471 res,
472 qself,
473 );
474 if self.suggest_self_ty(&mut err, source, path, span)
475 || self.suggest_self_value(&mut err, source, path, span)
476 {
477 return (err, Vec::new());
478 }
479
480 if let Some((did, item)) = self.lookup_doc_alias_name(path, source.namespace()) {
481 let item_name = item.name;
482 let suggestion_name = self.r.tcx.item_name(did);
483 err.span_suggestion(
484 item.span,
485 format!("`{suggestion_name}` has a name defined in the doc alias attribute as `{item_name}`"),
486 suggestion_name,
487 Applicability::MaybeIncorrect
488 );
489
490 return (err, Vec::new());
491 };
492
493 let (found, suggested_candidates, mut candidates) = self.try_lookup_name_relaxed(
494 &mut err,
495 source,
496 path,
497 following_seg,
498 span,
499 res,
500 &base_error,
501 );
502 if found {
503 return (err, candidates);
504 }
505
506 if self.suggest_shadowed(&mut err, source, path, following_seg, span) {
507 candidates.clear();
509 }
510
511 let mut fallback = self.suggest_trait_and_bounds(&mut err, source, res, span, &base_error);
512 fallback |= self.suggest_typo(
513 &mut err,
514 source,
515 path,
516 following_seg,
517 span,
518 &base_error,
519 suggested_candidates,
520 );
521
522 if fallback {
523 err.span_label(base_error.span, base_error.fallback_label);
525 }
526 self.err_code_special_cases(&mut err, source, path, span);
527
528 let module = base_error.module.unwrap_or_else(|| CRATE_DEF_ID.to_def_id());
529 self.r.find_cfg_stripped(&mut err, &path.last().unwrap().ident.name, module);
530
531 (err, candidates)
532 }
533
534 fn detect_rtn_with_fully_qualified_path(
535 &self,
536 err: &mut Diag<'_>,
537 path: &[Segment],
538 following_seg: Option<&Segment>,
539 span: Span,
540 source: PathSource<'_, '_, '_>,
541 res: Option<Res>,
542 qself: Option<&QSelf>,
543 ) {
544 if let Some(Res::Def(DefKind::AssocFn, _)) = res
545 && let PathSource::TraitItem(TypeNS, _) = source
546 && let None = following_seg
547 && let Some(qself) = qself
548 && let TyKind::Path(None, ty_path) = &qself.ty.kind
549 && ty_path.segments.len() == 1
550 && self.diag_metadata.current_where_predicate.is_some()
551 {
552 err.span_suggestion_verbose(
553 span,
554 "you might have meant to use the return type notation syntax",
555 format!("{}::{}(..)", ty_path.segments[0].ident, path[path.len() - 1].ident),
556 Applicability::MaybeIncorrect,
557 );
558 }
559 }
560
561 fn detect_assoc_type_constraint_meant_as_path(
562 &self,
563 err: &mut Diag<'_>,
564 base_error: &BaseError,
565 ) {
566 let Some(ty) = self.diag_metadata.current_type_path else {
567 return;
568 };
569 let TyKind::Path(_, path) = &ty.kind else {
570 return;
571 };
572 for segment in &path.segments {
573 let Some(params) = &segment.args else {
574 continue;
575 };
576 let ast::GenericArgs::AngleBracketed(params) = params.deref() else {
577 continue;
578 };
579 for param in ¶ms.args {
580 let ast::AngleBracketedArg::Constraint(constraint) = param else {
581 continue;
582 };
583 let ast::AssocItemConstraintKind::Bound { bounds } = &constraint.kind else {
584 continue;
585 };
586 for bound in bounds {
587 let ast::GenericBound::Trait(trait_ref) = bound else {
588 continue;
589 };
590 if trait_ref.modifiers == ast::TraitBoundModifiers::NONE
591 && base_error.span == trait_ref.span
592 {
593 err.span_suggestion_verbose(
594 constraint.ident.span.between(trait_ref.span),
595 "you might have meant to write a path instead of an associated type bound",
596 "::",
597 Applicability::MachineApplicable,
598 );
599 }
600 }
601 }
602 }
603 }
604
605 fn suggest_self_or_self_ref(&mut self, err: &mut Diag<'_>, path: &[Segment], span: Span) {
606 if !self.self_type_is_available() {
607 return;
608 }
609 let Some(path_last_segment) = path.last() else { return };
610 let item_str = path_last_segment.ident;
611 if ["this", "my"].contains(&item_str.as_str()) {
613 err.span_suggestion_short(
614 span,
615 "you might have meant to use `self` here instead",
616 "self",
617 Applicability::MaybeIncorrect,
618 );
619 if !self.self_value_is_available(path[0].ident.span) {
620 if let Some((FnKind::Fn(_, _, ast::Fn { sig, .. }), fn_span)) =
621 &self.diag_metadata.current_function
622 {
623 let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) {
624 (param.span.shrink_to_lo(), "&self, ")
625 } else {
626 (
627 self.r
628 .tcx
629 .sess
630 .source_map()
631 .span_through_char(*fn_span, '(')
632 .shrink_to_hi(),
633 "&self",
634 )
635 };
636 err.span_suggestion_verbose(
637 span,
638 "if you meant to use `self`, you are also missing a `self` receiver \
639 argument",
640 sugg,
641 Applicability::MaybeIncorrect,
642 );
643 }
644 }
645 }
646 }
647
648 fn try_lookup_name_relaxed(
649 &mut self,
650 err: &mut Diag<'_>,
651 source: PathSource<'_, '_, '_>,
652 path: &[Segment],
653 following_seg: Option<&Segment>,
654 span: Span,
655 res: Option<Res>,
656 base_error: &BaseError,
657 ) -> (bool, FxHashSet<String>, Vec<ImportSuggestion>) {
658 let span = match following_seg {
659 Some(_) if path[0].ident.span.eq_ctxt(path[path.len() - 1].ident.span) => {
660 path[0].ident.span.to(path[path.len() - 1].ident.span)
663 }
664 _ => span,
665 };
666 let mut suggested_candidates = FxHashSet::default();
667 let ident = path.last().unwrap().ident;
669 let is_expected = &|res| source.is_expected(res);
670 let ns = source.namespace();
671 let is_enum_variant = &|res| matches!(res, Res::Def(DefKind::Variant, _));
672 let path_str = Segment::names_to_string(path);
673 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
674 let mut candidates = self
675 .r
676 .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
677 .into_iter()
678 .filter(|ImportSuggestion { did, .. }| {
679 match (did, res.and_then(|res| res.opt_def_id())) {
680 (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
681 _ => true,
682 }
683 })
684 .collect::<Vec<_>>();
685 let intrinsic_candidates: Vec<_> = candidates
688 .extract_if(.., |sugg| {
689 let path = path_names_to_string(&sugg.path);
690 path.starts_with("core::intrinsics::") || path.starts_with("std::intrinsics::")
691 })
692 .collect();
693 if candidates.is_empty() {
694 candidates = intrinsic_candidates;
696 }
697 let crate_def_id = CRATE_DEF_ID.to_def_id();
698 if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
699 let mut enum_candidates: Vec<_> = self
700 .r
701 .lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant)
702 .into_iter()
703 .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
704 .filter(|(_, enum_ty_path)| !enum_ty_path.starts_with("std::prelude::"))
705 .collect();
706 if !enum_candidates.is_empty() {
707 enum_candidates.sort();
708
709 let preamble = if res.is_none() {
712 let others = match enum_candidates.len() {
713 1 => String::new(),
714 2 => " and 1 other".to_owned(),
715 n => format!(" and {n} others"),
716 };
717 format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
718 } else {
719 String::new()
720 };
721 let msg = format!("{preamble}try using the variant's enum");
722
723 suggested_candidates.extend(
724 enum_candidates
725 .iter()
726 .map(|(_variant_path, enum_ty_path)| enum_ty_path.clone()),
727 );
728 err.span_suggestions(
729 span,
730 msg,
731 enum_candidates.into_iter().map(|(_variant_path, enum_ty_path)| enum_ty_path),
732 Applicability::MachineApplicable,
733 );
734 }
735 }
736
737 let typo_sugg = self
739 .lookup_typo_candidate(path, following_seg, source.namespace(), is_expected)
740 .to_opt_suggestion()
741 .filter(|sugg| !suggested_candidates.contains(sugg.candidate.as_str()));
742 if let [segment] = path
743 && !matches!(source, PathSource::Delegation)
744 && self.self_type_is_available()
745 {
746 if let Some(candidate) =
747 self.lookup_assoc_candidate(ident, ns, is_expected, source.is_call())
748 {
749 let self_is_available = self.self_value_is_available(segment.ident.span);
750 let pre = match source {
753 PathSource::Expr(Some(Expr { kind: ExprKind::Struct(expr), .. }))
754 if expr
755 .fields
756 .iter()
757 .any(|f| f.ident == segment.ident && f.is_shorthand) =>
758 {
759 format!("{path_str}: ")
760 }
761 _ => String::new(),
762 };
763 match candidate {
764 AssocSuggestion::Field(field_span) => {
765 if self_is_available {
766 let source_map = self.r.tcx.sess.source_map();
767 let field_is_format_named_arg = source_map
769 .span_to_source(span, |s, start, _| {
770 Ok(s.get(start - 1..start) == Some("{"))
771 });
772 if let Ok(true) = field_is_format_named_arg {
773 err.help(
774 format!("you might have meant to use the available field in a format string: `\"{{}}\", self.{}`", segment.ident.name),
775 );
776 } else {
777 err.span_suggestion_verbose(
778 span.shrink_to_lo(),
779 "you might have meant to use the available field",
780 format!("{pre}self."),
781 Applicability::MaybeIncorrect,
782 );
783 }
784 } else {
785 err.span_label(field_span, "a field by that name exists in `Self`");
786 }
787 }
788 AssocSuggestion::MethodWithSelf { called } if self_is_available => {
789 let msg = if called {
790 "you might have meant to call the method"
791 } else {
792 "you might have meant to refer to the method"
793 };
794 err.span_suggestion_verbose(
795 span.shrink_to_lo(),
796 msg,
797 "self.",
798 Applicability::MachineApplicable,
799 );
800 }
801 AssocSuggestion::MethodWithSelf { .. }
802 | AssocSuggestion::AssocFn { .. }
803 | AssocSuggestion::AssocConst
804 | AssocSuggestion::AssocType => {
805 err.span_suggestion_verbose(
806 span.shrink_to_lo(),
807 format!("you might have meant to {}", candidate.action()),
808 "Self::",
809 Applicability::MachineApplicable,
810 );
811 }
812 }
813 self.r.add_typo_suggestion(err, typo_sugg, ident_span);
814 return (true, suggested_candidates, candidates);
815 }
816
817 if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
819 let mut args_snippet = String::new();
820 if let Some(args_span) = args_span
821 && let Ok(snippet) = self.r.tcx.sess.source_map().span_to_snippet(args_span)
822 {
823 args_snippet = snippet;
824 }
825
826 if let Some(Res::Def(DefKind::Struct, def_id)) = res {
827 let private_fields = self.has_private_fields(def_id);
828 let adjust_error_message =
829 private_fields && self.is_struct_with_fn_ctor(def_id);
830 if adjust_error_message {
831 self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
832 }
833
834 if private_fields {
835 err.note("constructor is not visible here due to private fields");
836 }
837 } else {
838 err.span_suggestion(
839 call_span,
840 format!("try calling `{ident}` as a method"),
841 format!("self.{path_str}({args_snippet})"),
842 Applicability::MachineApplicable,
843 );
844 }
845
846 return (true, suggested_candidates, candidates);
847 }
848 }
849
850 if let Some(res) = res {
852 if self.smart_resolve_context_dependent_help(
853 err,
854 span,
855 source,
856 path,
857 res,
858 &path_str,
859 &base_error.fallback_label,
860 ) {
861 self.r.add_typo_suggestion(err, typo_sugg, ident_span);
863 return (true, suggested_candidates, candidates);
864 }
865 }
866
867 if let Some(rib) = &self.last_block_rib {
869 for (ident, &res) in &rib.bindings {
870 if let Res::Local(_) = res
871 && path.len() == 1
872 && ident.span.eq_ctxt(path[0].ident.span)
873 && ident.name == path[0].ident.name
874 {
875 err.span_help(
876 ident.span,
877 format!("the binding `{path_str}` is available in a different scope in the same function"),
878 );
879 return (true, suggested_candidates, candidates);
880 }
881 }
882 }
883
884 if candidates.is_empty() {
885 candidates = self.smart_resolve_partial_mod_path_errors(path, following_seg);
886 }
887
888 (false, suggested_candidates, candidates)
889 }
890
891 fn lookup_doc_alias_name(&mut self, path: &[Segment], ns: Namespace) -> Option<(DefId, Ident)> {
892 let find_doc_alias_name = |r: &mut Resolver<'ra, '_>, m: Module<'ra>, item_name: Symbol| {
893 for resolution in r.resolutions(m).borrow().values() {
894 let Some(did) = resolution
895 .borrow()
896 .best_binding()
897 .and_then(|binding| binding.res().opt_def_id())
898 else {
899 continue;
900 };
901 if did.is_local() {
902 continue;
906 }
907 if let Some(d) =
908 hir::find_attr!(r.tcx.get_all_attrs(did), AttributeKind::Doc(d) => d)
909 && d.aliases.contains_key(&item_name)
910 {
911 return Some(did);
912 }
913 }
914 None
915 };
916
917 if path.len() == 1 {
918 for rib in self.ribs[ns].iter().rev() {
919 let item = path[0].ident;
920 if let RibKind::Module(module) | RibKind::Block(Some(module)) = rib.kind
921 && let Some(did) = find_doc_alias_name(self.r, module, item.name)
922 {
923 return Some((did, item));
924 }
925 }
926 } else {
927 for (idx, seg) in path.iter().enumerate().rev().skip(1) {
936 let Some(id) = seg.id else {
937 continue;
938 };
939 let Some(res) = self.r.partial_res_map.get(&id) else {
940 continue;
941 };
942 if let Res::Def(DefKind::Mod, module) = res.expect_full_res()
943 && let module = self.r.expect_module(module)
944 && let item = path[idx + 1].ident
945 && let Some(did) = find_doc_alias_name(self.r, module, item.name)
946 {
947 return Some((did, item));
948 }
949 break;
950 }
951 }
952 None
953 }
954
955 fn suggest_trait_and_bounds(
956 &self,
957 err: &mut Diag<'_>,
958 source: PathSource<'_, '_, '_>,
959 res: Option<Res>,
960 span: Span,
961 base_error: &BaseError,
962 ) -> bool {
963 let is_macro =
964 base_error.span.from_expansion() && base_error.span.desugaring_kind().is_none();
965 let mut fallback = false;
966
967 if let (
968 PathSource::Trait(AliasPossibility::Maybe),
969 Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)),
970 false,
971 ) = (source, res, is_macro)
972 && let Some(bounds @ [first_bound, .., last_bound]) =
973 self.diag_metadata.current_trait_object
974 {
975 fallback = true;
976 let spans: Vec<Span> = bounds
977 .iter()
978 .map(|bound| bound.span())
979 .filter(|&sp| sp != base_error.span)
980 .collect();
981
982 let start_span = first_bound.span();
983 let end_span = last_bound.span();
985 let last_bound_span = spans.last().cloned().unwrap();
987 let mut multi_span: MultiSpan = spans.clone().into();
988 for sp in spans {
989 let msg = if sp == last_bound_span {
990 format!(
991 "...because of {these} bound{s}",
992 these = pluralize!("this", bounds.len() - 1),
993 s = pluralize!(bounds.len() - 1),
994 )
995 } else {
996 String::new()
997 };
998 multi_span.push_span_label(sp, msg);
999 }
1000 multi_span.push_span_label(base_error.span, "expected this type to be a trait...");
1001 err.span_help(
1002 multi_span,
1003 "`+` is used to constrain a \"trait object\" type with lifetimes or \
1004 auto-traits; structs and enums can't be bound in that way",
1005 );
1006 if bounds.iter().all(|bound| match bound {
1007 ast::GenericBound::Outlives(_) | ast::GenericBound::Use(..) => true,
1008 ast::GenericBound::Trait(tr) => tr.span == base_error.span,
1009 }) {
1010 let mut sugg = vec![];
1011 if base_error.span != start_span {
1012 sugg.push((start_span.until(base_error.span), String::new()));
1013 }
1014 if base_error.span != end_span {
1015 sugg.push((base_error.span.shrink_to_hi().to(end_span), String::new()));
1016 }
1017
1018 err.multipart_suggestion(
1019 "if you meant to use a type and not a trait here, remove the bounds",
1020 sugg,
1021 Applicability::MaybeIncorrect,
1022 );
1023 }
1024 }
1025
1026 fallback |= self.restrict_assoc_type_in_where_clause(span, err);
1027 fallback
1028 }
1029
1030 fn suggest_typo(
1031 &mut self,
1032 err: &mut Diag<'_>,
1033 source: PathSource<'_, 'ast, 'ra>,
1034 path: &[Segment],
1035 following_seg: Option<&Segment>,
1036 span: Span,
1037 base_error: &BaseError,
1038 suggested_candidates: FxHashSet<String>,
1039 ) -> bool {
1040 let is_expected = &|res| source.is_expected(res);
1041 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
1042 let typo_sugg =
1043 self.lookup_typo_candidate(path, following_seg, source.namespace(), is_expected);
1044 let mut fallback = false;
1045 let typo_sugg = typo_sugg
1046 .to_opt_suggestion()
1047 .filter(|sugg| !suggested_candidates.contains(sugg.candidate.as_str()));
1048 if !self.r.add_typo_suggestion(err, typo_sugg, ident_span) {
1049 fallback = true;
1050 match self.diag_metadata.current_let_binding {
1051 Some((pat_sp, Some(ty_sp), None))
1052 if ty_sp.contains(base_error.span) && base_error.could_be_expr =>
1053 {
1054 err.span_suggestion_short(
1055 pat_sp.between(ty_sp),
1056 "use `=` if you meant to assign",
1057 " = ",
1058 Applicability::MaybeIncorrect,
1059 );
1060 }
1061 _ => {}
1062 }
1063
1064 let suggestion = self.get_single_associated_item(path, &source, is_expected);
1066 self.r.add_typo_suggestion(err, suggestion, ident_span);
1067 }
1068
1069 if self.let_binding_suggestion(err, ident_span) {
1070 fallback = false;
1071 }
1072
1073 fallback
1074 }
1075
1076 fn suggest_shadowed(
1077 &mut self,
1078 err: &mut Diag<'_>,
1079 source: PathSource<'_, '_, '_>,
1080 path: &[Segment],
1081 following_seg: Option<&Segment>,
1082 span: Span,
1083 ) -> bool {
1084 let is_expected = &|res| source.is_expected(res);
1085 let typo_sugg =
1086 self.lookup_typo_candidate(path, following_seg, source.namespace(), is_expected);
1087 let is_in_same_file = &|sp1, sp2| {
1088 let source_map = self.r.tcx.sess.source_map();
1089 let file1 = source_map.span_to_filename(sp1);
1090 let file2 = source_map.span_to_filename(sp2);
1091 file1 == file2
1092 };
1093 if let TypoCandidate::Shadowed(res, Some(sugg_span)) = typo_sugg
1098 && res.opt_def_id().is_some_and(|id| id.is_local() || is_in_same_file(span, sugg_span))
1099 {
1100 err.span_label(
1101 sugg_span,
1102 format!("you might have meant to refer to this {}", res.descr()),
1103 );
1104 return true;
1105 }
1106 false
1107 }
1108
1109 fn err_code_special_cases(
1110 &mut self,
1111 err: &mut Diag<'_>,
1112 source: PathSource<'_, '_, '_>,
1113 path: &[Segment],
1114 span: Span,
1115 ) {
1116 if let Some(err_code) = err.code {
1117 if err_code == E0425 {
1118 for label_rib in &self.label_ribs {
1119 for (label_ident, node_id) in &label_rib.bindings {
1120 let ident = path.last().unwrap().ident;
1121 if format!("'{ident}") == label_ident.to_string() {
1122 err.span_label(label_ident.span, "a label with a similar name exists");
1123 if let PathSource::Expr(Some(Expr {
1124 kind: ExprKind::Break(None, Some(_)),
1125 ..
1126 })) = source
1127 {
1128 err.span_suggestion(
1129 span,
1130 "use the similarly named label",
1131 label_ident.name,
1132 Applicability::MaybeIncorrect,
1133 );
1134 self.diag_metadata.unused_labels.swap_remove(node_id);
1136 }
1137 }
1138 }
1139 }
1140
1141 self.suggest_ident_hidden_by_hygiene(err, path, span);
1142 if let Some(correct) = Self::likely_rust_type(path) {
1144 err.span_suggestion(
1145 span,
1146 "perhaps you intended to use this type",
1147 correct,
1148 Applicability::MaybeIncorrect,
1149 );
1150 }
1151 }
1152 }
1153 }
1154
1155 fn suggest_ident_hidden_by_hygiene(&self, err: &mut Diag<'_>, path: &[Segment], span: Span) {
1156 let [segment] = path else { return };
1157
1158 let ident = segment.ident;
1159 let callsite_span = span.source_callsite();
1160 for rib in self.ribs[ValueNS].iter().rev() {
1161 for (binding_ident, _) in &rib.bindings {
1162 if binding_ident.name == ident.name
1164 && !binding_ident.span.eq_ctxt(span)
1165 && !binding_ident.span.from_expansion()
1166 && binding_ident.span.lo() < callsite_span.lo()
1167 {
1168 err.span_help(
1169 binding_ident.span,
1170 "an identifier with the same name exists, but is not accessible due to macro hygiene",
1171 );
1172 return;
1173 }
1174
1175 if binding_ident.name == ident.name
1177 && binding_ident.span.from_expansion()
1178 && binding_ident.span.source_callsite().eq_ctxt(callsite_span)
1179 && binding_ident.span.source_callsite().lo() < callsite_span.lo()
1180 {
1181 err.span_help(
1182 binding_ident.span,
1183 "an identifier with the same name is defined here, but is not accessible due to macro hygiene",
1184 );
1185 return;
1186 }
1187 }
1188 }
1189 }
1190
1191 fn suggest_self_ty(
1193 &self,
1194 err: &mut Diag<'_>,
1195 source: PathSource<'_, '_, '_>,
1196 path: &[Segment],
1197 span: Span,
1198 ) -> bool {
1199 if !is_self_type(path, source.namespace()) {
1200 return false;
1201 }
1202 err.code(E0411);
1203 err.span_label(span, "`Self` is only available in impls, traits, and type definitions");
1204 if let Some(item) = self.diag_metadata.current_item
1205 && let Some(ident) = item.kind.ident()
1206 {
1207 err.span_label(
1208 ident.span,
1209 format!("`Self` not allowed in {} {}", item.kind.article(), item.kind.descr()),
1210 );
1211 }
1212 true
1213 }
1214
1215 fn suggest_self_value(
1216 &mut self,
1217 err: &mut Diag<'_>,
1218 source: PathSource<'_, '_, '_>,
1219 path: &[Segment],
1220 span: Span,
1221 ) -> bool {
1222 if !is_self_value(path, source.namespace()) {
1223 return false;
1224 }
1225
1226 debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
1227 err.code(E0424);
1228 err.span_label(
1229 span,
1230 match source {
1231 PathSource::Pat => {
1232 "`self` value is a keyword and may not be bound to variables or shadowed"
1233 }
1234 _ => "`self` value is a keyword only available in methods with a `self` parameter",
1235 },
1236 );
1237
1238 if matches!(source, PathSource::Pat) {
1241 return true;
1242 }
1243
1244 let is_assoc_fn = self.self_type_is_available();
1245 let self_from_macro = "a `self` parameter, but a macro invocation can only \
1246 access identifiers it receives from parameters";
1247 if let Some((fn_kind, fn_span)) = &self.diag_metadata.current_function {
1248 if fn_kind.decl().inputs.get(0).is_some_and(|p| p.is_self()) {
1253 err.span_label(*fn_span, format!("this function has {self_from_macro}"));
1254 } else {
1255 let doesnt = if is_assoc_fn {
1256 let (span, sugg) = fn_kind
1257 .decl()
1258 .inputs
1259 .get(0)
1260 .map(|p| (p.span.shrink_to_lo(), "&self, "))
1261 .unwrap_or_else(|| {
1262 let span = fn_kind
1265 .ident()
1266 .map_or(*fn_span, |ident| fn_span.with_lo(ident.span.hi()));
1267 (
1268 self.r
1269 .tcx
1270 .sess
1271 .source_map()
1272 .span_through_char(span, '(')
1273 .shrink_to_hi(),
1274 "&self",
1275 )
1276 });
1277 err.span_suggestion_verbose(
1278 span,
1279 "add a `self` receiver parameter to make the associated `fn` a method",
1280 sugg,
1281 Applicability::MaybeIncorrect,
1282 );
1283 "doesn't"
1284 } else {
1285 "can't"
1286 };
1287 if let Some(ident) = fn_kind.ident() {
1288 err.span_label(
1289 ident.span,
1290 format!("this function {doesnt} have a `self` parameter"),
1291 );
1292 }
1293 }
1294 } else if let Some(item) = self.diag_metadata.current_item {
1295 if matches!(item.kind, ItemKind::Delegation(..)) {
1296 err.span_label(item.span, format!("delegation supports {self_from_macro}"));
1297 } else {
1298 let span = if let Some(ident) = item.kind.ident() { ident.span } else { item.span };
1299 err.span_label(
1300 span,
1301 format!("`self` not allowed in {} {}", item.kind.article(), item.kind.descr()),
1302 );
1303 }
1304 }
1305 true
1306 }
1307
1308 fn detect_missing_binding_available_from_pattern(
1309 &self,
1310 err: &mut Diag<'_>,
1311 path: &[Segment],
1312 following_seg: Option<&Segment>,
1313 ) {
1314 let [segment] = path else { return };
1315 let None = following_seg else { return };
1316 for rib in self.ribs[ValueNS].iter().rev() {
1317 let patterns_with_skipped_bindings = self.r.tcx.with_stable_hashing_context(|hcx| {
1318 rib.patterns_with_skipped_bindings.to_sorted(&hcx, true)
1319 });
1320 for (def_id, spans) in patterns_with_skipped_bindings {
1321 if let DefKind::Struct | DefKind::Variant = self.r.tcx.def_kind(*def_id)
1322 && let Some(fields) = self.r.field_idents(*def_id)
1323 {
1324 for field in fields {
1325 if field.name == segment.ident.name {
1326 if spans.iter().all(|(_, had_error)| had_error.is_err()) {
1327 let multispan: MultiSpan =
1330 spans.iter().map(|(s, _)| *s).collect::<Vec<_>>().into();
1331 err.span_note(
1332 multispan,
1333 "this pattern had a recovered parse error which likely lost \
1334 the expected fields",
1335 );
1336 err.downgrade_to_delayed_bug();
1337 }
1338 let ty = self.r.tcx.item_name(*def_id);
1339 for (span, _) in spans {
1340 err.span_label(
1341 *span,
1342 format!(
1343 "this pattern doesn't include `{field}`, which is \
1344 available in `{ty}`",
1345 ),
1346 );
1347 }
1348 }
1349 }
1350 }
1351 }
1352 }
1353 }
1354
1355 fn suggest_at_operator_in_slice_pat_with_range(&self, err: &mut Diag<'_>, path: &[Segment]) {
1356 let Some(pat) = self.diag_metadata.current_pat else { return };
1357 let (bound, side, range) = match &pat.kind {
1358 ast::PatKind::Range(Some(bound), None, range) => (bound, Side::Start, range),
1359 ast::PatKind::Range(None, Some(bound), range) => (bound, Side::End, range),
1360 _ => return,
1361 };
1362 if let ExprKind::Path(None, range_path) = &bound.kind
1363 && let [segment] = &range_path.segments[..]
1364 && let [s] = path
1365 && segment.ident == s.ident
1366 && segment.ident.span.eq_ctxt(range.span)
1367 {
1368 let (span, snippet) = match side {
1371 Side::Start => (segment.ident.span.between(range.span), " @ ".into()),
1372 Side::End => (range.span.to(segment.ident.span), format!("{} @ ..", segment.ident)),
1373 };
1374 err.subdiagnostic(errors::UnexpectedResUseAtOpInSlicePatWithRangeSugg {
1375 span,
1376 ident: segment.ident,
1377 snippet,
1378 });
1379 }
1380
1381 enum Side {
1382 Start,
1383 End,
1384 }
1385 }
1386
1387 fn suggest_range_struct_destructuring(
1388 &mut self,
1389 err: &mut Diag<'_>,
1390 path: &[Segment],
1391 source: PathSource<'_, '_, '_>,
1392 ) {
1393 if !matches!(source, PathSource::Pat | PathSource::TupleStruct(..) | PathSource::Expr(..)) {
1394 return;
1395 }
1396
1397 let Some(pat) = self.diag_metadata.current_pat else { return };
1398 let ast::PatKind::Range(start, end, end_kind) = &pat.kind else { return };
1399
1400 let [segment] = path else { return };
1401 let failing_span = segment.ident.span;
1402
1403 let in_start = start.as_ref().is_some_and(|e| e.span.contains(failing_span));
1404 let in_end = end.as_ref().is_some_and(|e| e.span.contains(failing_span));
1405
1406 if !in_start && !in_end {
1407 return;
1408 }
1409
1410 let start_snippet =
1411 start.as_ref().and_then(|e| self.r.tcx.sess.source_map().span_to_snippet(e.span).ok());
1412 let end_snippet =
1413 end.as_ref().and_then(|e| self.r.tcx.sess.source_map().span_to_snippet(e.span).ok());
1414
1415 let field = |name: &str, val: String| {
1416 if val == name { val } else { format!("{name}: {val}") }
1417 };
1418
1419 let mut resolve_short_name = |short: Symbol, full: &str| -> String {
1420 let ident = Ident::with_dummy_span(short);
1421 let path = Segment::from_path(&Path::from_ident(ident));
1422
1423 match self.resolve_path(&path, Some(TypeNS), None, PathSource::Type) {
1424 PathResult::NonModule(..) => short.to_string(),
1425 _ => full.to_string(),
1426 }
1427 };
1428 let (struct_path, fields) = match (start_snippet, end_snippet, &end_kind.node) {
1430 (Some(start), Some(end), ast::RangeEnd::Excluded) => (
1431 resolve_short_name(sym::Range, "std::ops::Range"),
1432 vec![field("start", start), field("end", end)],
1433 ),
1434 (Some(start), Some(end), ast::RangeEnd::Included(_)) => (
1435 resolve_short_name(sym::RangeInclusive, "std::ops::RangeInclusive"),
1436 vec![field("start", start), field("end", end)],
1437 ),
1438 (Some(start), None, _) => (
1439 resolve_short_name(sym::RangeFrom, "std::ops::RangeFrom"),
1440 vec![field("start", start)],
1441 ),
1442 (None, Some(end), ast::RangeEnd::Excluded) => {
1443 (resolve_short_name(sym::RangeTo, "std::ops::RangeTo"), vec![field("end", end)])
1444 }
1445 (None, Some(end), ast::RangeEnd::Included(_)) => (
1446 resolve_short_name(sym::RangeToInclusive, "std::ops::RangeToInclusive"),
1447 vec![field("end", end)],
1448 ),
1449 _ => return,
1450 };
1451
1452 err.span_suggestion_verbose(
1453 pat.span,
1454 format!("if you meant to destructure a range use a struct pattern"),
1455 format!("{} {{ {} }}", struct_path, fields.join(", ")),
1456 Applicability::MaybeIncorrect,
1457 );
1458
1459 err.note(
1460 "range patterns match against the start and end of a range; \
1461 to bind the components, use a struct pattern",
1462 );
1463 }
1464
1465 fn suggest_swapping_misplaced_self_ty_and_trait(
1466 &mut self,
1467 err: &mut Diag<'_>,
1468 source: PathSource<'_, 'ast, 'ra>,
1469 res: Option<Res>,
1470 span: Span,
1471 ) {
1472 if let Some((trait_ref, self_ty)) =
1473 self.diag_metadata.currently_processing_impl_trait.clone()
1474 && let TyKind::Path(_, self_ty_path) = &self_ty.kind
1475 && let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1476 self.resolve_path(&Segment::from_path(self_ty_path), Some(TypeNS), None, source)
1477 && let ModuleKind::Def(DefKind::Trait, ..) = module.kind
1478 && trait_ref.path.span == span
1479 && let PathSource::Trait(_) = source
1480 && let Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)) = res
1481 && let Ok(self_ty_str) = self.r.tcx.sess.source_map().span_to_snippet(self_ty.span)
1482 && let Ok(trait_ref_str) =
1483 self.r.tcx.sess.source_map().span_to_snippet(trait_ref.path.span)
1484 {
1485 err.multipart_suggestion(
1486 "`impl` items mention the trait being implemented first and the type it is being implemented for second",
1487 vec![(trait_ref.path.span, self_ty_str), (self_ty.span, trait_ref_str)],
1488 Applicability::MaybeIncorrect,
1489 );
1490 }
1491 }
1492
1493 fn explain_functions_in_pattern(
1494 &self,
1495 err: &mut Diag<'_>,
1496 res: Option<Res>,
1497 source: PathSource<'_, '_, '_>,
1498 ) {
1499 let PathSource::TupleStruct(_, _) = source else { return };
1500 let Some(Res::Def(DefKind::Fn, _)) = res else { return };
1501 err.primary_message("expected a pattern, found a function call");
1502 err.note("function calls are not allowed in patterns: <https://doc.rust-lang.org/book/ch19-00-patterns.html>");
1503 }
1504
1505 fn suggest_changing_type_to_const_param(
1506 &self,
1507 err: &mut Diag<'_>,
1508 res: Option<Res>,
1509 source: PathSource<'_, '_, '_>,
1510 span: Span,
1511 ) {
1512 let PathSource::Trait(_) = source else { return };
1513
1514 let applicability = match res {
1516 Some(Res::PrimTy(PrimTy::Int(_) | PrimTy::Uint(_) | PrimTy::Bool | PrimTy::Char)) => {
1517 Applicability::MachineApplicable
1518 }
1519 Some(Res::Def(DefKind::Struct | DefKind::Enum, _))
1523 if self.r.tcx.features().adt_const_params() =>
1524 {
1525 Applicability::MaybeIncorrect
1526 }
1527 _ => return,
1528 };
1529
1530 let Some(item) = self.diag_metadata.current_item else { return };
1531 let Some(generics) = item.kind.generics() else { return };
1532
1533 let param = generics.params.iter().find_map(|param| {
1534 if let [bound] = &*param.bounds
1536 && let ast::GenericBound::Trait(tref) = bound
1537 && tref.modifiers == ast::TraitBoundModifiers::NONE
1538 && tref.span == span
1539 && param.ident.span.eq_ctxt(span)
1540 {
1541 Some(param.ident.span)
1542 } else {
1543 None
1544 }
1545 });
1546
1547 if let Some(param) = param {
1548 err.subdiagnostic(errors::UnexpectedResChangeTyToConstParamSugg {
1549 span: param.shrink_to_lo(),
1550 applicability,
1551 });
1552 }
1553 }
1554
1555 fn suggest_pattern_match_with_let(
1556 &self,
1557 err: &mut Diag<'_>,
1558 source: PathSource<'_, '_, '_>,
1559 span: Span,
1560 ) -> bool {
1561 if let PathSource::Expr(_) = source
1562 && let Some(Expr { span: expr_span, kind: ExprKind::Assign(lhs, _, _), .. }) =
1563 self.diag_metadata.in_if_condition
1564 {
1565 if lhs.is_approximately_pattern() && lhs.span.contains(span) {
1569 err.span_suggestion_verbose(
1570 expr_span.shrink_to_lo(),
1571 "you might have meant to use pattern matching",
1572 "let ",
1573 Applicability::MaybeIncorrect,
1574 );
1575 return true;
1576 }
1577 }
1578 false
1579 }
1580
1581 fn get_single_associated_item(
1582 &mut self,
1583 path: &[Segment],
1584 source: &PathSource<'_, 'ast, 'ra>,
1585 filter_fn: &impl Fn(Res) -> bool,
1586 ) -> Option<TypoSuggestion> {
1587 if let crate::PathSource::TraitItem(_, _) = source {
1588 let mod_path = &path[..path.len() - 1];
1589 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1590 self.resolve_path(mod_path, None, None, *source)
1591 {
1592 let targets: Vec<_> = self
1593 .r
1594 .resolutions(module)
1595 .borrow()
1596 .iter()
1597 .filter_map(|(key, resolution)| {
1598 resolution
1599 .borrow()
1600 .best_binding()
1601 .map(|binding| binding.res())
1602 .and_then(|res| if filter_fn(res) { Some((*key, res)) } else { None })
1603 })
1604 .collect();
1605 if let [target] = targets.as_slice() {
1606 return Some(TypoSuggestion::single_item_from_ident(
1607 target.0.ident.0,
1608 target.1,
1609 ));
1610 }
1611 }
1612 }
1613 None
1614 }
1615
1616 fn restrict_assoc_type_in_where_clause(&self, span: Span, err: &mut Diag<'_>) -> bool {
1618 let Some(ast::WherePredicate {
1620 kind:
1621 ast::WherePredicateKind::BoundPredicate(ast::WhereBoundPredicate {
1622 bounded_ty,
1623 bound_generic_params,
1624 bounds,
1625 }),
1626 span: where_span,
1627 ..
1628 }) = self.diag_metadata.current_where_predicate
1629 else {
1630 return false;
1631 };
1632 if !bound_generic_params.is_empty() {
1633 return false;
1634 }
1635
1636 let ast::TyKind::Path(Some(qself), path) = &bounded_ty.kind else { return false };
1638 let Some(partial_res) = self.r.partial_res_map.get(&bounded_ty.id) else { return false };
1640 if !matches!(
1641 partial_res.full_res(),
1642 Some(hir::def::Res::Def(hir::def::DefKind::AssocTy, _))
1643 ) {
1644 return false;
1645 }
1646
1647 let peeled_ty = qself.ty.peel_refs();
1648 let ast::TyKind::Path(None, type_param_path) = &peeled_ty.kind else { return false };
1649 let Some(partial_res) = self.r.partial_res_map.get(&peeled_ty.id) else {
1651 return false;
1652 };
1653 if !matches!(
1654 partial_res.full_res(),
1655 Some(hir::def::Res::Def(hir::def::DefKind::TyParam, _))
1656 ) {
1657 return false;
1658 }
1659 let ([ast::PathSegment { args: None, .. }], [ast::GenericBound::Trait(poly_trait_ref)]) =
1660 (&type_param_path.segments[..], &bounds[..])
1661 else {
1662 return false;
1663 };
1664 let [ast::PathSegment { ident, args: None, id }] =
1665 &poly_trait_ref.trait_ref.path.segments[..]
1666 else {
1667 return false;
1668 };
1669 if poly_trait_ref.modifiers != ast::TraitBoundModifiers::NONE {
1670 return false;
1671 }
1672 if ident.span == span {
1673 let Some(partial_res) = self.r.partial_res_map.get(&id) else {
1674 return false;
1675 };
1676 if !matches!(partial_res.full_res(), Some(hir::def::Res::Def(..))) {
1677 return false;
1678 }
1679
1680 let Some(new_where_bound_predicate) =
1681 mk_where_bound_predicate(path, poly_trait_ref, &qself.ty)
1682 else {
1683 return false;
1684 };
1685 err.span_suggestion_verbose(
1686 *where_span,
1687 format!("constrain the associated type to `{ident}`"),
1688 where_bound_predicate_to_string(&new_where_bound_predicate),
1689 Applicability::MaybeIncorrect,
1690 );
1691 }
1692 true
1693 }
1694
1695 fn call_has_self_arg(&self, source: PathSource<'_, '_, '_>) -> Option<(Span, Option<Span>)> {
1698 let mut has_self_arg = None;
1699 if let PathSource::Expr(Some(parent)) = source
1700 && let ExprKind::Call(_, args) = &parent.kind
1701 && !args.is_empty()
1702 {
1703 let mut expr_kind = &args[0].kind;
1704 loop {
1705 match expr_kind {
1706 ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
1707 if arg_name.segments[0].ident.name == kw::SelfLower {
1708 let call_span = parent.span;
1709 let tail_args_span = if args.len() > 1 {
1710 Some(Span::new(
1711 args[1].span.lo(),
1712 args.last().unwrap().span.hi(),
1713 call_span.ctxt(),
1714 None,
1715 ))
1716 } else {
1717 None
1718 };
1719 has_self_arg = Some((call_span, tail_args_span));
1720 }
1721 break;
1722 }
1723 ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
1724 _ => break,
1725 }
1726 }
1727 }
1728 has_self_arg
1729 }
1730
1731 fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
1732 let sm = self.r.tcx.sess.source_map();
1737 if let Some(followed_brace_span) = sm.span_look_ahead(span, "{", Some(50)) {
1738 let close_brace_span = sm.span_look_ahead(followed_brace_span, "}", Some(50));
1741 let closing_brace = close_brace_span.map(|sp| span.to(sp));
1742 (true, closing_brace)
1743 } else {
1744 (false, None)
1745 }
1746 }
1747
1748 fn is_struct_with_fn_ctor(&mut self, def_id: DefId) -> bool {
1749 def_id
1750 .as_local()
1751 .and_then(|local_id| self.r.struct_constructors.get(&local_id))
1752 .map(|struct_ctor| {
1753 matches!(
1754 struct_ctor.0,
1755 def::Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), _)
1756 )
1757 })
1758 .unwrap_or(false)
1759 }
1760
1761 fn update_err_for_private_tuple_struct_fields(
1762 &mut self,
1763 err: &mut Diag<'_>,
1764 source: &PathSource<'_, '_, '_>,
1765 def_id: DefId,
1766 ) -> Option<Vec<Span>> {
1767 match source {
1768 PathSource::TupleStruct(_, pattern_spans) => {
1770 err.primary_message(
1771 "cannot match against a tuple struct which contains private fields",
1772 );
1773
1774 Some(Vec::from(*pattern_spans))
1776 }
1777 PathSource::Expr(Some(Expr {
1779 kind: ExprKind::Call(path, args),
1780 span: call_span,
1781 ..
1782 })) => {
1783 err.primary_message(
1784 "cannot initialize a tuple struct which contains private fields",
1785 );
1786 self.suggest_alternative_construction_methods(
1787 def_id,
1788 err,
1789 path.span,
1790 *call_span,
1791 &args[..],
1792 );
1793
1794 self.r
1795 .field_idents(def_id)
1796 .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
1797 }
1798 _ => None,
1799 }
1800 }
1801
1802 fn smart_resolve_context_dependent_help(
1806 &mut self,
1807 err: &mut Diag<'_>,
1808 span: Span,
1809 source: PathSource<'_, '_, '_>,
1810 path: &[Segment],
1811 res: Res,
1812 path_str: &str,
1813 fallback_label: &str,
1814 ) -> bool {
1815 let ns = source.namespace();
1816 let is_expected = &|res| source.is_expected(res);
1817
1818 let path_sep = |this: &Self, err: &mut Diag<'_>, expr: &Expr, kind: DefKind| {
1819 const MESSAGE: &str = "use the path separator to refer to an item";
1820
1821 let (lhs_span, rhs_span) = match &expr.kind {
1822 ExprKind::Field(base, ident) => (base.span, ident.span),
1823 ExprKind::MethodCall(box MethodCall { receiver, span, .. }) => {
1824 (receiver.span, *span)
1825 }
1826 _ => return false,
1827 };
1828
1829 if lhs_span.eq_ctxt(rhs_span) {
1830 err.span_suggestion_verbose(
1831 lhs_span.between(rhs_span),
1832 MESSAGE,
1833 "::",
1834 Applicability::MaybeIncorrect,
1835 );
1836 true
1837 } else if matches!(kind, DefKind::Struct | DefKind::TyAlias)
1838 && let Some(lhs_source_span) = lhs_span.find_ancestor_inside(expr.span)
1839 && let Ok(snippet) = this.r.tcx.sess.source_map().span_to_snippet(lhs_source_span)
1840 {
1841 err.span_suggestion_verbose(
1845 lhs_source_span.until(rhs_span),
1846 MESSAGE,
1847 format!("<{snippet}>::"),
1848 Applicability::MaybeIncorrect,
1849 );
1850 true
1851 } else {
1852 false
1858 }
1859 };
1860
1861 let find_span = |source: &PathSource<'_, '_, '_>, err: &mut Diag<'_>| {
1862 match source {
1863 PathSource::Expr(Some(Expr { span, kind: ExprKind::Call(_, _), .. }))
1864 | PathSource::TupleStruct(span, _) => {
1865 err.span(*span);
1868 *span
1869 }
1870 _ => span,
1871 }
1872 };
1873
1874 let bad_struct_syntax_suggestion = |this: &mut Self, err: &mut Diag<'_>, def_id: DefId| {
1875 let (followed_by_brace, closing_brace) = this.followed_by_brace(span);
1876
1877 match source {
1878 PathSource::Expr(Some(
1879 parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
1880 )) if path_sep(this, err, parent, DefKind::Struct) => {}
1881 PathSource::Expr(
1882 None
1883 | Some(Expr {
1884 kind:
1885 ExprKind::Path(..)
1886 | ExprKind::Binary(..)
1887 | ExprKind::Unary(..)
1888 | ExprKind::If(..)
1889 | ExprKind::While(..)
1890 | ExprKind::ForLoop { .. }
1891 | ExprKind::Match(..),
1892 ..
1893 }),
1894 ) if followed_by_brace => {
1895 if let Some(sp) = closing_brace {
1896 err.span_label(span, fallback_label.to_string());
1897 err.multipart_suggestion(
1898 "surround the struct literal with parentheses",
1899 vec![
1900 (sp.shrink_to_lo(), "(".to_string()),
1901 (sp.shrink_to_hi(), ")".to_string()),
1902 ],
1903 Applicability::MaybeIncorrect,
1904 );
1905 } else {
1906 err.span_label(
1907 span, format!(
1909 "you might want to surround a struct literal with parentheses: \
1910 `({path_str} {{ /* fields */ }})`?"
1911 ),
1912 );
1913 }
1914 }
1915 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
1916 let span = find_span(&source, err);
1917 err.span_label(this.r.def_span(def_id), format!("`{path_str}` defined here"));
1918
1919 let (tail, descr, applicability, old_fields) = match source {
1920 PathSource::Pat => ("", "pattern", Applicability::MachineApplicable, None),
1921 PathSource::TupleStruct(_, args) => (
1922 "",
1923 "pattern",
1924 Applicability::MachineApplicable,
1925 Some(
1926 args.iter()
1927 .map(|a| this.r.tcx.sess.source_map().span_to_snippet(*a).ok())
1928 .collect::<Vec<Option<String>>>(),
1929 ),
1930 ),
1931 _ => (": val", "literal", Applicability::HasPlaceholders, None),
1932 };
1933
1934 if !this.has_private_fields(def_id) {
1935 let fields = this.r.field_idents(def_id);
1938 let has_fields = fields.as_ref().is_some_and(|f| !f.is_empty());
1939
1940 if let PathSource::Expr(Some(Expr {
1941 kind: ExprKind::Call(path, args),
1942 span,
1943 ..
1944 })) = source
1945 && !args.is_empty()
1946 && let Some(fields) = &fields
1947 && args.len() == fields.len()
1948 {
1950 let path_span = path.span;
1951 let mut parts = Vec::new();
1952
1953 parts.push((
1955 path_span.shrink_to_hi().until(args[0].span),
1956 "{".to_owned(),
1957 ));
1958
1959 for (field, arg) in fields.iter().zip(args.iter()) {
1960 parts.push((arg.span.shrink_to_lo(), format!("{}: ", field)));
1962 }
1963
1964 parts.push((
1966 args.last().unwrap().span.shrink_to_hi().until(span.shrink_to_hi()),
1967 "}".to_owned(),
1968 ));
1969
1970 err.multipart_suggestion_verbose(
1971 format!("use struct {descr} syntax instead of calling"),
1972 parts,
1973 applicability,
1974 );
1975 } else {
1976 let (fields, applicability) = match fields {
1977 Some(fields) => {
1978 let fields = if let Some(old_fields) = old_fields {
1979 fields
1980 .iter()
1981 .enumerate()
1982 .map(|(idx, new)| (new, old_fields.get(idx)))
1983 .map(|(new, old)| {
1984 if let Some(Some(old)) = old
1985 && new.as_str() != old
1986 {
1987 format!("{new}: {old}")
1988 } else {
1989 new.to_string()
1990 }
1991 })
1992 .collect::<Vec<String>>()
1993 } else {
1994 fields
1995 .iter()
1996 .map(|f| format!("{f}{tail}"))
1997 .collect::<Vec<String>>()
1998 };
1999
2000 (fields.join(", "), applicability)
2001 }
2002 None => {
2003 ("/* fields */".to_string(), Applicability::HasPlaceholders)
2004 }
2005 };
2006 let pad = if has_fields { " " } else { "" };
2007 err.span_suggestion(
2008 span,
2009 format!("use struct {descr} syntax instead"),
2010 format!("{path_str} {{{pad}{fields}{pad}}}"),
2011 applicability,
2012 );
2013 }
2014 }
2015 if let PathSource::Expr(Some(Expr {
2016 kind: ExprKind::Call(path, args),
2017 span: call_span,
2018 ..
2019 })) = source
2020 {
2021 this.suggest_alternative_construction_methods(
2022 def_id,
2023 err,
2024 path.span,
2025 *call_span,
2026 &args[..],
2027 );
2028 }
2029 }
2030 _ => {
2031 err.span_label(span, fallback_label.to_string());
2032 }
2033 }
2034 };
2035
2036 match (res, source) {
2037 (
2038 Res::Def(DefKind::Macro(kinds), def_id),
2039 PathSource::Expr(Some(Expr {
2040 kind: ExprKind::Index(..) | ExprKind::Call(..), ..
2041 }))
2042 | PathSource::Struct(_),
2043 ) if kinds.contains(MacroKinds::BANG) => {
2044 let suggestable = def_id.is_local()
2046 || self.r.tcx.lookup_stability(def_id).is_none_or(|s| s.is_stable());
2047
2048 err.span_label(span, fallback_label.to_string());
2049
2050 if path
2052 .last()
2053 .is_some_and(|segment| !segment.has_generic_args && !segment.has_lifetime_args)
2054 && suggestable
2055 {
2056 err.span_suggestion_verbose(
2057 span.shrink_to_hi(),
2058 "use `!` to invoke the macro",
2059 "!",
2060 Applicability::MaybeIncorrect,
2061 );
2062 }
2063
2064 if path_str == "try" && span.is_rust_2015() {
2065 err.note("if you want the `try` keyword, you need Rust 2018 or later");
2066 }
2067 }
2068 (Res::Def(DefKind::Macro(kinds), _), _) if kinds.contains(MacroKinds::BANG) => {
2069 err.span_label(span, fallback_label.to_string());
2070 }
2071 (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
2072 err.span_label(span, "type aliases cannot be used as traits");
2073 if self.r.tcx.sess.is_nightly_build() {
2074 let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
2075 `type` alias";
2076 let span = self.r.def_span(def_id);
2077 if let Ok(snip) = self.r.tcx.sess.source_map().span_to_snippet(span) {
2078 let snip = snip.replacen("type", "trait", 1);
2081 err.span_suggestion(span, msg, snip, Applicability::MaybeIncorrect);
2082 } else {
2083 err.span_help(span, msg);
2084 }
2085 }
2086 }
2087 (
2088 Res::Def(kind @ (DefKind::Mod | DefKind::Trait | DefKind::TyAlias), _),
2089 PathSource::Expr(Some(parent)),
2090 ) if path_sep(self, err, parent, kind) => {
2091 return true;
2092 }
2093 (
2094 Res::Def(DefKind::Enum, def_id),
2095 PathSource::TupleStruct(..) | PathSource::Expr(..),
2096 ) => {
2097 self.suggest_using_enum_variant(err, source, def_id, span);
2098 }
2099 (Res::Def(DefKind::Struct, def_id), source) if ns == ValueNS => {
2100 let struct_ctor = match def_id.as_local() {
2101 Some(def_id) => self.r.struct_constructors.get(&def_id).cloned(),
2102 None => {
2103 let ctor = self.r.cstore().ctor_untracked(self.r.tcx(), def_id);
2104 ctor.map(|(ctor_kind, ctor_def_id)| {
2105 let ctor_res =
2106 Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id);
2107 let ctor_vis = self.r.tcx.visibility(ctor_def_id);
2108 let field_visibilities = self
2109 .r
2110 .tcx
2111 .associated_item_def_ids(def_id)
2112 .iter()
2113 .map(|field_id| self.r.tcx.visibility(field_id))
2114 .collect();
2115 (ctor_res, ctor_vis, field_visibilities)
2116 })
2117 }
2118 };
2119
2120 let (ctor_def, ctor_vis, fields) = if let Some(struct_ctor) = struct_ctor {
2121 if let PathSource::Expr(Some(parent)) = source
2122 && let ExprKind::Field(..) | ExprKind::MethodCall(..) = parent.kind
2123 {
2124 bad_struct_syntax_suggestion(self, err, def_id);
2125 return true;
2126 }
2127 struct_ctor
2128 } else {
2129 bad_struct_syntax_suggestion(self, err, def_id);
2130 return true;
2131 };
2132
2133 let is_accessible = self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
2134 if let Some(use_span) = self.r.inaccessible_ctor_reexport.get(&span)
2135 && is_accessible
2136 {
2137 err.span_note(
2138 *use_span,
2139 "the type is accessed through this re-export, but the type's constructor \
2140 is not visible in this import's scope due to private fields",
2141 );
2142 if is_accessible
2143 && fields
2144 .iter()
2145 .all(|vis| self.r.is_accessible_from(*vis, self.parent_scope.module))
2146 {
2147 err.span_suggestion_verbose(
2148 span,
2149 "the type can be constructed directly, because its fields are \
2150 available from the current scope",
2151 format!(
2155 "crate{}", self.r.tcx.def_path(def_id).to_string_no_crate_verbose(),
2157 ),
2158 Applicability::MachineApplicable,
2159 );
2160 }
2161 self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
2162 }
2163 if !is_expected(ctor_def) || is_accessible {
2164 return true;
2165 }
2166
2167 let field_spans =
2168 self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
2169
2170 if let Some(spans) =
2171 field_spans.filter(|spans| spans.len() > 0 && fields.len() == spans.len())
2172 {
2173 let non_visible_spans: Vec<Span> = iter::zip(&fields, &spans)
2174 .filter(|(vis, _)| {
2175 !self.r.is_accessible_from(**vis, self.parent_scope.module)
2176 })
2177 .map(|(_, span)| *span)
2178 .collect();
2179
2180 if non_visible_spans.len() > 0 {
2181 if let Some(fields) = self.r.field_visibility_spans.get(&def_id) {
2182 err.multipart_suggestion_verbose(
2183 format!(
2184 "consider making the field{} publicly accessible",
2185 pluralize!(fields.len())
2186 ),
2187 fields.iter().map(|span| (*span, "pub ".to_string())).collect(),
2188 Applicability::MaybeIncorrect,
2189 );
2190 }
2191
2192 let mut m: MultiSpan = non_visible_spans.clone().into();
2193 non_visible_spans
2194 .into_iter()
2195 .for_each(|s| m.push_span_label(s, "private field"));
2196 err.span_note(m, "constructor is not visible here due to private fields");
2197 }
2198
2199 return true;
2200 }
2201
2202 err.span_label(span, "constructor is not visible here due to private fields");
2203 }
2204 (Res::Def(DefKind::Union | DefKind::Variant, def_id), _) if ns == ValueNS => {
2205 bad_struct_syntax_suggestion(self, err, def_id);
2206 }
2207 (Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id), _) if ns == ValueNS => {
2208 match source {
2209 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
2210 let span = find_span(&source, err);
2211 err.span_label(
2212 self.r.def_span(def_id),
2213 format!("`{path_str}` defined here"),
2214 );
2215 err.span_suggestion(
2216 span,
2217 "use this syntax instead",
2218 path_str,
2219 Applicability::MaybeIncorrect,
2220 );
2221 }
2222 _ => return false,
2223 }
2224 }
2225 (Res::Def(DefKind::Ctor(_, CtorKind::Fn), ctor_def_id), _) if ns == ValueNS => {
2226 let def_id = self.r.tcx.parent(ctor_def_id);
2227 err.span_label(self.r.def_span(def_id), format!("`{path_str}` defined here"));
2228 let fields = self.r.field_idents(def_id).map_or_else(
2229 || "/* fields */".to_string(),
2230 |field_ids| vec!["_"; field_ids.len()].join(", "),
2231 );
2232 err.span_suggestion(
2233 span,
2234 "use the tuple variant pattern syntax instead",
2235 format!("{path_str}({fields})"),
2236 Applicability::HasPlaceholders,
2237 );
2238 }
2239 (Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }, _) if ns == ValueNS => {
2240 err.span_label(span, fallback_label.to_string());
2241 err.note("can't use `Self` as a constructor, you must use the implemented struct");
2242 }
2243 (
2244 Res::Def(DefKind::TyAlias | DefKind::AssocTy, _),
2245 PathSource::TraitItem(ValueNS, PathSource::TupleStruct(whole, args)),
2246 ) => {
2247 err.note("can't use a type alias as tuple pattern");
2248
2249 let mut suggestion = Vec::new();
2250
2251 if let &&[first, ..] = args
2252 && let &&[.., last] = args
2253 {
2254 suggestion.extend([
2255 (span.between(first), " { 0: ".to_owned()),
2261 (last.between(whole.shrink_to_hi()), " }".to_owned()),
2262 ]);
2263
2264 suggestion.extend(
2265 args.iter()
2266 .enumerate()
2267 .skip(1) .map(|(index, &arg)| (arg.shrink_to_lo(), format!("{index}: "))),
2269 )
2270 } else {
2271 suggestion.push((span.between(whole.shrink_to_hi()), " {}".to_owned()));
2272 }
2273
2274 err.multipart_suggestion(
2275 "use struct pattern instead",
2276 suggestion,
2277 Applicability::MachineApplicable,
2278 );
2279 }
2280 (
2281 Res::Def(DefKind::TyAlias | DefKind::AssocTy, _),
2282 PathSource::TraitItem(
2283 ValueNS,
2284 PathSource::Expr(Some(ast::Expr {
2285 span: whole,
2286 kind: ast::ExprKind::Call(_, args),
2287 ..
2288 })),
2289 ),
2290 ) => {
2291 err.note("can't use a type alias as a constructor");
2292
2293 let mut suggestion = Vec::new();
2294
2295 if let [first, ..] = &**args
2296 && let [.., last] = &**args
2297 {
2298 suggestion.extend([
2299 (span.between(first.span), " { 0: ".to_owned()),
2305 (last.span.between(whole.shrink_to_hi()), " }".to_owned()),
2306 ]);
2307
2308 suggestion.extend(
2309 args.iter()
2310 .enumerate()
2311 .skip(1) .map(|(index, arg)| (arg.span.shrink_to_lo(), format!("{index}: "))),
2313 )
2314 } else {
2315 suggestion.push((span.between(whole.shrink_to_hi()), " {}".to_owned()));
2316 }
2317
2318 err.multipart_suggestion(
2319 "use struct expression instead",
2320 suggestion,
2321 Applicability::MachineApplicable,
2322 );
2323 }
2324 _ => return false,
2325 }
2326 true
2327 }
2328
2329 fn suggest_alternative_construction_methods(
2330 &mut self,
2331 def_id: DefId,
2332 err: &mut Diag<'_>,
2333 path_span: Span,
2334 call_span: Span,
2335 args: &[Box<Expr>],
2336 ) {
2337 if def_id.is_local() {
2338 return;
2340 }
2341 let mut items = self
2344 .r
2345 .tcx
2346 .inherent_impls(def_id)
2347 .iter()
2348 .flat_map(|i| self.r.tcx.associated_items(i).in_definition_order())
2349 .filter(|item| item.is_fn() && !item.is_method())
2351 .filter_map(|item| {
2352 let fn_sig = self.r.tcx.fn_sig(item.def_id).skip_binder();
2354 let ret_ty = fn_sig.output().skip_binder();
2356 let ty::Adt(def, _args) = ret_ty.kind() else {
2357 return None;
2358 };
2359 let input_len = fn_sig.inputs().skip_binder().len();
2360 if def.did() != def_id {
2361 return None;
2362 }
2363 let name = item.name();
2364 let order = !name.as_str().starts_with("new");
2365 Some((order, name, input_len))
2366 })
2367 .collect::<Vec<_>>();
2368 items.sort_by_key(|(order, _, _)| *order);
2369 let suggestion = |name, args| {
2370 format!("::{name}({})", std::iter::repeat_n("_", args).collect::<Vec<_>>().join(", "))
2371 };
2372 match &items[..] {
2373 [] => {}
2374 [(_, name, len)] if *len == args.len() => {
2375 err.span_suggestion_verbose(
2376 path_span.shrink_to_hi(),
2377 format!("you might have meant to use the `{name}` associated function",),
2378 format!("::{name}"),
2379 Applicability::MaybeIncorrect,
2380 );
2381 }
2382 [(_, name, len)] => {
2383 err.span_suggestion_verbose(
2384 path_span.shrink_to_hi().with_hi(call_span.hi()),
2385 format!("you might have meant to use the `{name}` associated function",),
2386 suggestion(name, *len),
2387 Applicability::MaybeIncorrect,
2388 );
2389 }
2390 _ => {
2391 err.span_suggestions_with_style(
2392 path_span.shrink_to_hi().with_hi(call_span.hi()),
2393 "you might have meant to use an associated function to build this type",
2394 items.iter().map(|(_, name, len)| suggestion(name, *len)),
2395 Applicability::MaybeIncorrect,
2396 SuggestionStyle::ShowAlways,
2397 );
2398 }
2399 }
2400 let default_trait = self
2408 .r
2409 .lookup_import_candidates(
2410 Ident::with_dummy_span(sym::Default),
2411 Namespace::TypeNS,
2412 &self.parent_scope,
2413 &|res: Res| matches!(res, Res::Def(DefKind::Trait, _)),
2414 )
2415 .iter()
2416 .filter_map(|candidate| candidate.did)
2417 .find(|did| {
2418 self.r
2419 .tcx
2420 .get_attrs(*did, sym::rustc_diagnostic_item)
2421 .any(|attr| attr.value_str() == Some(sym::Default))
2422 });
2423 let Some(default_trait) = default_trait else {
2424 return;
2425 };
2426 if self
2427 .r
2428 .extern_crate_map
2429 .items()
2430 .flat_map(|(_, crate_)| self.r.tcx.implementations_of_trait((*crate_, default_trait)))
2432 .filter_map(|(_, simplified_self_ty)| *simplified_self_ty)
2433 .filter_map(|simplified_self_ty| match simplified_self_ty {
2434 SimplifiedType::Adt(did) => Some(did),
2435 _ => None,
2436 })
2437 .any(|did| did == def_id)
2438 {
2439 err.multipart_suggestion(
2440 "consider using the `Default` trait",
2441 vec![
2442 (path_span.shrink_to_lo(), "<".to_string()),
2443 (
2444 path_span.shrink_to_hi().with_hi(call_span.hi()),
2445 " as std::default::Default>::default()".to_string(),
2446 ),
2447 ],
2448 Applicability::MaybeIncorrect,
2449 );
2450 }
2451 }
2452
2453 fn has_private_fields(&self, def_id: DefId) -> bool {
2454 let fields = match def_id.as_local() {
2455 Some(def_id) => self.r.struct_constructors.get(&def_id).cloned().map(|(_, _, f)| f),
2456 None => Some(
2457 self.r
2458 .tcx
2459 .associated_item_def_ids(def_id)
2460 .iter()
2461 .map(|field_id| self.r.tcx.visibility(field_id))
2462 .collect(),
2463 ),
2464 };
2465
2466 fields.is_some_and(|fields| {
2467 fields.iter().any(|vis| !self.r.is_accessible_from(*vis, self.parent_scope.module))
2468 })
2469 }
2470
2471 pub(crate) fn find_similarly_named_assoc_item(
2474 &mut self,
2475 ident: Symbol,
2476 kind: &AssocItemKind,
2477 ) -> Option<Symbol> {
2478 let (module, _) = self.current_trait_ref.as_ref()?;
2479 if ident == kw::Underscore {
2480 return None;
2482 }
2483
2484 let targets = self
2485 .r
2486 .resolutions(*module)
2487 .borrow()
2488 .iter()
2489 .filter_map(|(key, res)| {
2490 res.borrow().best_binding().map(|binding| (key, binding.res()))
2491 })
2492 .filter(|(_, res)| match (kind, res) {
2493 (AssocItemKind::Const(..), Res::Def(DefKind::AssocConst, _)) => true,
2494 (AssocItemKind::Fn(_), Res::Def(DefKind::AssocFn, _)) => true,
2495 (AssocItemKind::Type(..), Res::Def(DefKind::AssocTy, _)) => true,
2496 (AssocItemKind::Delegation(_), Res::Def(DefKind::AssocFn, _)) => true,
2497 _ => false,
2498 })
2499 .map(|(key, _)| key.ident.name)
2500 .collect::<Vec<_>>();
2501
2502 find_best_match_for_name(&targets, ident, None)
2503 }
2504
2505 fn lookup_assoc_candidate<FilterFn>(
2506 &mut self,
2507 ident: Ident,
2508 ns: Namespace,
2509 filter_fn: FilterFn,
2510 called: bool,
2511 ) -> Option<AssocSuggestion>
2512 where
2513 FilterFn: Fn(Res) -> bool,
2514 {
2515 fn extract_node_id(t: &Ty) -> Option<NodeId> {
2516 match t.kind {
2517 TyKind::Path(None, _) => Some(t.id),
2518 TyKind::Ref(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
2519 _ => None,
2523 }
2524 }
2525 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
2527 if let Some(node_id) =
2528 self.diag_metadata.current_self_type.as_ref().and_then(extract_node_id)
2529 && let Some(resolution) = self.r.partial_res_map.get(&node_id)
2530 && let Some(Res::Def(DefKind::Struct | DefKind::Union, did)) = resolution.full_res()
2531 && let Some(fields) = self.r.field_idents(did)
2532 && let Some(field) = fields.iter().find(|id| ident.name == id.name)
2533 {
2534 return Some(AssocSuggestion::Field(field.span));
2536 }
2537 }
2538
2539 if let Some(items) = self.diag_metadata.current_trait_assoc_items {
2540 for assoc_item in items {
2541 if let Some(assoc_ident) = assoc_item.kind.ident()
2542 && assoc_ident == ident
2543 {
2544 return Some(match &assoc_item.kind {
2545 ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
2546 ast::AssocItemKind::Fn(box ast::Fn { sig, .. }) if sig.decl.has_self() => {
2547 AssocSuggestion::MethodWithSelf { called }
2548 }
2549 ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn { called },
2550 ast::AssocItemKind::Type(..) => AssocSuggestion::AssocType,
2551 ast::AssocItemKind::Delegation(..)
2552 if self
2553 .r
2554 .delegation_fn_sigs
2555 .get(&self.r.local_def_id(assoc_item.id))
2556 .is_some_and(|sig| sig.has_self) =>
2557 {
2558 AssocSuggestion::MethodWithSelf { called }
2559 }
2560 ast::AssocItemKind::Delegation(..) => AssocSuggestion::AssocFn { called },
2561 ast::AssocItemKind::MacCall(_) | ast::AssocItemKind::DelegationMac(..) => {
2562 continue;
2563 }
2564 });
2565 }
2566 }
2567 }
2568
2569 if let Some((module, _)) = self.current_trait_ref
2571 && let Ok(binding) = self.r.cm().maybe_resolve_ident_in_module(
2572 ModuleOrUniformRoot::Module(module),
2573 ident,
2574 ns,
2575 &self.parent_scope,
2576 None,
2577 )
2578 {
2579 let res = binding.res();
2580 if filter_fn(res) {
2581 match res {
2582 Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) => {
2583 let has_self = match def_id.as_local() {
2584 Some(def_id) => self
2585 .r
2586 .delegation_fn_sigs
2587 .get(&def_id)
2588 .is_some_and(|sig| sig.has_self),
2589 None => {
2590 self.r.tcx.fn_arg_idents(def_id).first().is_some_and(|&ident| {
2591 matches!(ident, Some(Ident { name: kw::SelfLower, .. }))
2592 })
2593 }
2594 };
2595 if has_self {
2596 return Some(AssocSuggestion::MethodWithSelf { called });
2597 } else {
2598 return Some(AssocSuggestion::AssocFn { called });
2599 }
2600 }
2601 Res::Def(DefKind::AssocConst, _) => {
2602 return Some(AssocSuggestion::AssocConst);
2603 }
2604 Res::Def(DefKind::AssocTy, _) => {
2605 return Some(AssocSuggestion::AssocType);
2606 }
2607 _ => {}
2608 }
2609 }
2610 }
2611
2612 None
2613 }
2614
2615 fn lookup_typo_candidate(
2616 &mut self,
2617 path: &[Segment],
2618 following_seg: Option<&Segment>,
2619 ns: Namespace,
2620 filter_fn: &impl Fn(Res) -> bool,
2621 ) -> TypoCandidate {
2622 let mut names = Vec::new();
2623 if let [segment] = path {
2624 let mut ctxt = segment.ident.span.ctxt();
2625
2626 for rib in self.ribs[ns].iter().rev() {
2629 let rib_ctxt = if rib.kind.contains_params() {
2630 ctxt.normalize_to_macros_2_0()
2631 } else {
2632 ctxt.normalize_to_macro_rules()
2633 };
2634
2635 for (ident, &res) in &rib.bindings {
2637 if filter_fn(res) && ident.span.ctxt() == rib_ctxt {
2638 names.push(TypoSuggestion::typo_from_ident(*ident, res));
2639 }
2640 }
2641
2642 if let RibKind::Block(Some(module)) = rib.kind {
2643 self.r.add_module_candidates(module, &mut names, &filter_fn, Some(ctxt));
2644 } else if let RibKind::Module(module) = rib.kind {
2645 let parent_scope = &ParentScope { module, ..self.parent_scope };
2647 self.r.add_scope_set_candidates(
2648 &mut names,
2649 ScopeSet::All(ns),
2650 parent_scope,
2651 ctxt,
2652 filter_fn,
2653 );
2654 break;
2655 }
2656
2657 if let RibKind::MacroDefinition(def) = rib.kind
2658 && def == self.r.macro_def(ctxt)
2659 {
2660 ctxt.remove_mark();
2663 }
2664 }
2665 } else {
2666 let mod_path = &path[..path.len() - 1];
2668 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
2669 self.resolve_path(mod_path, Some(TypeNS), None, PathSource::Type)
2670 {
2671 self.r.add_module_candidates(module, &mut names, &filter_fn, None);
2672 }
2673 }
2674
2675 if let Some(following_seg) = following_seg {
2677 names.retain(|suggestion| match suggestion.res {
2678 Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _) => {
2679 suggestion.candidate != following_seg.ident.name
2681 }
2682 Res::Def(DefKind::Mod, def_id) => {
2683 let module = self.r.expect_module(def_id);
2684 self.r
2685 .resolutions(module)
2686 .borrow()
2687 .iter()
2688 .any(|(key, _)| key.ident.name == following_seg.ident.name)
2689 }
2690 _ => true,
2691 });
2692 }
2693 let name = path[path.len() - 1].ident.name;
2694 names.sort_by(|a, b| a.candidate.as_str().cmp(b.candidate.as_str()));
2696
2697 match find_best_match_for_name(
2698 &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
2699 name,
2700 None,
2701 ) {
2702 Some(found) => {
2703 let Some(sugg) = names.into_iter().find(|suggestion| suggestion.candidate == found)
2704 else {
2705 return TypoCandidate::None;
2706 };
2707 if found == name {
2708 TypoCandidate::Shadowed(sugg.res, sugg.span)
2709 } else {
2710 TypoCandidate::Typo(sugg)
2711 }
2712 }
2713 _ => TypoCandidate::None,
2714 }
2715 }
2716
2717 fn likely_rust_type(path: &[Segment]) -> Option<Symbol> {
2720 let name = path[path.len() - 1].ident.as_str();
2721 Some(match name {
2723 "byte" => sym::u8, "short" => sym::i16,
2725 "Bool" => sym::bool,
2726 "Boolean" => sym::bool,
2727 "boolean" => sym::bool,
2728 "int" => sym::i32,
2729 "long" => sym::i64,
2730 "float" => sym::f32,
2731 "double" => sym::f64,
2732 _ => return None,
2733 })
2734 }
2735
2736 fn let_binding_suggestion(&self, err: &mut Diag<'_>, ident_span: Span) -> bool {
2739 if ident_span.from_expansion() {
2740 return false;
2741 }
2742
2743 if let Some(Expr { kind: ExprKind::Assign(lhs, ..), .. }) = self.diag_metadata.in_assignment
2745 && let ast::ExprKind::Path(None, ref path) = lhs.kind
2746 && self.r.tcx.sess.source_map().is_line_before_span_empty(ident_span)
2747 {
2748 let (span, text) = match path.segments.first() {
2749 Some(seg) if let Some(name) = seg.ident.as_str().strip_prefix("let") => {
2750 let name = name.trim_prefix('_');
2752 (ident_span, format!("let {name}"))
2753 }
2754 _ => (ident_span.shrink_to_lo(), "let ".to_string()),
2755 };
2756
2757 err.span_suggestion_verbose(
2758 span,
2759 "you might have meant to introduce a new binding",
2760 text,
2761 Applicability::MaybeIncorrect,
2762 );
2763 return true;
2764 }
2765
2766 if err.code == Some(E0423)
2769 && let Some((let_span, None, Some(val_span))) = self.diag_metadata.current_let_binding
2770 && val_span.contains(ident_span)
2771 && val_span.lo() == ident_span.lo()
2772 {
2773 err.span_suggestion_verbose(
2774 let_span.shrink_to_hi().to(val_span.shrink_to_lo()),
2775 "you might have meant to use `:` for type annotation",
2776 ": ",
2777 Applicability::MaybeIncorrect,
2778 );
2779 return true;
2780 }
2781 false
2782 }
2783
2784 fn find_module(&self, def_id: DefId) -> Option<(Module<'ra>, ImportSuggestion)> {
2785 let mut result = None;
2786 let mut seen_modules = FxHashSet::default();
2787 let root_did = self.r.graph_root.def_id();
2788 let mut worklist = vec![(
2789 self.r.graph_root,
2790 ThinVec::new(),
2791 root_did.is_local() || !self.r.tcx.is_doc_hidden(root_did),
2792 )];
2793
2794 while let Some((in_module, path_segments, doc_visible)) = worklist.pop() {
2795 if result.is_some() {
2797 break;
2798 }
2799
2800 in_module.for_each_child(self.r, |r, ident, _, name_binding| {
2801 if result.is_some() || !name_binding.vis.is_visible_locally() {
2803 return;
2804 }
2805 if let Some(module_def_id) = name_binding.res().module_like_def_id() {
2806 let mut path_segments = path_segments.clone();
2808 path_segments.push(ast::PathSegment::from_ident(ident.0));
2809 let doc_visible = doc_visible
2810 && (module_def_id.is_local() || !r.tcx.is_doc_hidden(module_def_id));
2811 if module_def_id == def_id {
2812 let path =
2813 Path { span: name_binding.span, segments: path_segments, tokens: None };
2814 result = Some((
2815 r.expect_module(module_def_id),
2816 ImportSuggestion {
2817 did: Some(def_id),
2818 descr: "module",
2819 path,
2820 accessible: true,
2821 doc_visible,
2822 note: None,
2823 via_import: false,
2824 is_stable: true,
2825 },
2826 ));
2827 } else {
2828 if seen_modules.insert(module_def_id) {
2830 let module = r.expect_module(module_def_id);
2831 worklist.push((module, path_segments, doc_visible));
2832 }
2833 }
2834 }
2835 });
2836 }
2837
2838 result
2839 }
2840
2841 fn collect_enum_ctors(&self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
2842 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
2843 let mut variants = Vec::new();
2844 enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
2845 if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
2846 let mut segms = enum_import_suggestion.path.segments.clone();
2847 segms.push(ast::PathSegment::from_ident(ident.0));
2848 let path = Path { span: name_binding.span, segments: segms, tokens: None };
2849 variants.push((path, def_id, kind));
2850 }
2851 });
2852 variants
2853 })
2854 }
2855
2856 fn suggest_using_enum_variant(
2858 &self,
2859 err: &mut Diag<'_>,
2860 source: PathSource<'_, '_, '_>,
2861 def_id: DefId,
2862 span: Span,
2863 ) {
2864 let Some(variant_ctors) = self.collect_enum_ctors(def_id) else {
2865 err.note("you might have meant to use one of the enum's variants");
2866 return;
2867 };
2868
2869 let (suggest_path_sep_dot_span, suggest_only_tuple_variants) = match source {
2874 PathSource::TupleStruct(..) => (None, true),
2876 PathSource::Expr(Some(expr)) => match &expr.kind {
2877 ExprKind::Call(..) => (None, true),
2879 ExprKind::MethodCall(box MethodCall {
2882 receiver,
2883 span,
2884 seg: PathSegment { ident, .. },
2885 ..
2886 }) => {
2887 let dot_span = receiver.span.between(*span);
2888 let found_tuple_variant = variant_ctors.iter().any(|(path, _, ctor_kind)| {
2889 *ctor_kind == CtorKind::Fn
2890 && path.segments.last().is_some_and(|seg| seg.ident == *ident)
2891 });
2892 (found_tuple_variant.then_some(dot_span), false)
2893 }
2894 ExprKind::Field(base, ident) => {
2897 let dot_span = base.span.between(ident.span);
2898 let found_tuple_or_unit_variant = variant_ctors.iter().any(|(path, ..)| {
2899 path.segments.last().is_some_and(|seg| seg.ident == *ident)
2900 });
2901 (found_tuple_or_unit_variant.then_some(dot_span), false)
2902 }
2903 _ => (None, false),
2904 },
2905 _ => (None, false),
2906 };
2907
2908 if let Some(dot_span) = suggest_path_sep_dot_span {
2909 err.span_suggestion_verbose(
2910 dot_span,
2911 "use the path separator to refer to a variant",
2912 "::",
2913 Applicability::MaybeIncorrect,
2914 );
2915 } else if suggest_only_tuple_variants {
2916 let mut suggestable_variants = variant_ctors
2919 .iter()
2920 .filter(|(.., kind)| *kind == CtorKind::Fn)
2921 .map(|(variant, ..)| path_names_to_string(variant))
2922 .collect::<Vec<_>>();
2923 suggestable_variants.sort();
2924
2925 let non_suggestable_variant_count = variant_ctors.len() - suggestable_variants.len();
2926
2927 let source_msg = if matches!(source, PathSource::TupleStruct(..)) {
2928 "to match against"
2929 } else {
2930 "to construct"
2931 };
2932
2933 if !suggestable_variants.is_empty() {
2934 let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
2935 format!("try {source_msg} the enum's variant")
2936 } else {
2937 format!("try {source_msg} one of the enum's variants")
2938 };
2939
2940 err.span_suggestions(
2941 span,
2942 msg,
2943 suggestable_variants,
2944 Applicability::MaybeIncorrect,
2945 );
2946 }
2947
2948 if non_suggestable_variant_count == variant_ctors.len() {
2950 err.help(format!("the enum has no tuple variants {source_msg}"));
2951 }
2952
2953 if non_suggestable_variant_count == 1 {
2955 err.help(format!("you might have meant {source_msg} the enum's non-tuple variant"));
2956 } else if non_suggestable_variant_count >= 1 {
2957 err.help(format!(
2958 "you might have meant {source_msg} one of the enum's non-tuple variants"
2959 ));
2960 }
2961 } else {
2962 let needs_placeholder = |ctor_def_id: DefId, kind: CtorKind| {
2963 let def_id = self.r.tcx.parent(ctor_def_id);
2964 match kind {
2965 CtorKind::Const => false,
2966 CtorKind::Fn => {
2967 !self.r.field_idents(def_id).is_some_and(|field_ids| field_ids.is_empty())
2968 }
2969 }
2970 };
2971
2972 let mut suggestable_variants = variant_ctors
2973 .iter()
2974 .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind))
2975 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
2976 .map(|(variant, kind)| match kind {
2977 CtorKind::Const => variant,
2978 CtorKind::Fn => format!("({variant}())"),
2979 })
2980 .collect::<Vec<_>>();
2981 suggestable_variants.sort();
2982 let no_suggestable_variant = suggestable_variants.is_empty();
2983
2984 if !no_suggestable_variant {
2985 let msg = if suggestable_variants.len() == 1 {
2986 "you might have meant to use the following enum variant"
2987 } else {
2988 "you might have meant to use one of the following enum variants"
2989 };
2990
2991 err.span_suggestions(
2992 span,
2993 msg,
2994 suggestable_variants,
2995 Applicability::MaybeIncorrect,
2996 );
2997 }
2998
2999 let mut suggestable_variants_with_placeholders = variant_ctors
3000 .iter()
3001 .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
3002 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
3003 .filter_map(|(variant, kind)| match kind {
3004 CtorKind::Fn => Some(format!("({variant}(/* fields */))")),
3005 _ => None,
3006 })
3007 .collect::<Vec<_>>();
3008 suggestable_variants_with_placeholders.sort();
3009
3010 if !suggestable_variants_with_placeholders.is_empty() {
3011 let msg =
3012 match (no_suggestable_variant, suggestable_variants_with_placeholders.len()) {
3013 (true, 1) => "the following enum variant is available",
3014 (true, _) => "the following enum variants are available",
3015 (false, 1) => "alternatively, the following enum variant is available",
3016 (false, _) => {
3017 "alternatively, the following enum variants are also available"
3018 }
3019 };
3020
3021 err.span_suggestions(
3022 span,
3023 msg,
3024 suggestable_variants_with_placeholders,
3025 Applicability::HasPlaceholders,
3026 );
3027 }
3028 };
3029
3030 if def_id.is_local() {
3031 err.span_note(self.r.def_span(def_id), "the enum is defined here");
3032 }
3033 }
3034
3035 pub(crate) fn suggest_adding_generic_parameter(
3036 &self,
3037 path: &[Segment],
3038 source: PathSource<'_, '_, '_>,
3039 ) -> Option<(Span, &'static str, String, Applicability)> {
3040 let (ident, span) = match path {
3041 [segment]
3042 if !segment.has_generic_args
3043 && segment.ident.name != kw::SelfUpper
3044 && segment.ident.name != kw::Dyn =>
3045 {
3046 (segment.ident.to_string(), segment.ident.span)
3047 }
3048 _ => return None,
3049 };
3050 let mut iter = ident.chars().map(|c| c.is_uppercase());
3051 let single_uppercase_char =
3052 matches!(iter.next(), Some(true)) && matches!(iter.next(), None);
3053 if !self.diag_metadata.currently_processing_generic_args && !single_uppercase_char {
3054 return None;
3055 }
3056 match (self.diag_metadata.current_item, single_uppercase_char, self.diag_metadata.currently_processing_generic_args) {
3057 (Some(Item { kind: ItemKind::Fn(fn_), .. }), _, _) if fn_.ident.name == sym::main => {
3058 }
3060 (
3061 Some(Item {
3062 kind:
3063 kind @ ItemKind::Fn(..)
3064 | kind @ ItemKind::Enum(..)
3065 | kind @ ItemKind::Struct(..)
3066 | kind @ ItemKind::Union(..),
3067 ..
3068 }),
3069 true, _
3070 )
3071 | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true)
3073 | (Some(Item { kind, .. }), false, _) => {
3074 if let Some(generics) = kind.generics() {
3075 if span.overlaps(generics.span) {
3076 return None;
3085 }
3086
3087 let (msg, sugg) = match source {
3088 PathSource::Type | PathSource::PreciseCapturingArg(TypeNS) => {
3089 ("you might be missing a type parameter", ident)
3090 }
3091 PathSource::Expr(_) | PathSource::PreciseCapturingArg(ValueNS) => (
3092 "you might be missing a const parameter",
3093 format!("const {ident}: /* Type */"),
3094 ),
3095 _ => return None,
3096 };
3097 let (span, sugg) = if let [.., param] = &generics.params[..] {
3098 let span = if let [.., bound] = ¶m.bounds[..] {
3099 bound.span()
3100 } else if let GenericParam {
3101 kind: GenericParamKind::Const { ty, span: _, default }, ..
3102 } = param {
3103 default.as_ref().map(|def| def.value.span).unwrap_or(ty.span)
3104 } else {
3105 param.ident.span
3106 };
3107 (span, format!(", {sugg}"))
3108 } else {
3109 (generics.span, format!("<{sugg}>"))
3110 };
3111 if span.can_be_used_for_suggestions() {
3113 return Some((
3114 span.shrink_to_hi(),
3115 msg,
3116 sugg,
3117 Applicability::MaybeIncorrect,
3118 ));
3119 }
3120 }
3121 }
3122 _ => {}
3123 }
3124 None
3125 }
3126
3127 pub(crate) fn suggestion_for_label_in_rib(
3130 &self,
3131 rib_index: usize,
3132 label: Ident,
3133 ) -> Option<LabelSuggestion> {
3134 let within_scope = self.is_label_valid_from_rib(rib_index);
3136
3137 let rib = &self.label_ribs[rib_index];
3138 let names = rib
3139 .bindings
3140 .iter()
3141 .filter(|(id, _)| id.span.eq_ctxt(label.span))
3142 .map(|(id, _)| id.name)
3143 .collect::<Vec<Symbol>>();
3144
3145 find_best_match_for_name(&names, label.name, None).map(|symbol| {
3146 let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
3150 (*ident, within_scope)
3151 })
3152 }
3153
3154 pub(crate) fn maybe_report_lifetime_uses(
3155 &mut self,
3156 generics_span: Span,
3157 params: &[ast::GenericParam],
3158 ) {
3159 for (param_index, param) in params.iter().enumerate() {
3160 let GenericParamKind::Lifetime = param.kind else { continue };
3161
3162 let def_id = self.r.local_def_id(param.id);
3163
3164 let use_set = self.lifetime_uses.remove(&def_id);
3165 debug!(
3166 "Use set for {:?}({:?} at {:?}) is {:?}",
3167 def_id, param.ident, param.ident.span, use_set
3168 );
3169
3170 let deletion_span = || {
3171 if params.len() == 1 {
3172 Some(generics_span)
3174 } else if param_index == 0 {
3175 match (
3178 param.span().find_ancestor_inside(generics_span),
3179 params[param_index + 1].span().find_ancestor_inside(generics_span),
3180 ) {
3181 (Some(param_span), Some(next_param_span)) => {
3182 Some(param_span.to(next_param_span.shrink_to_lo()))
3183 }
3184 _ => None,
3185 }
3186 } else {
3187 match (
3190 param.span().find_ancestor_inside(generics_span),
3191 params[param_index - 1].span().find_ancestor_inside(generics_span),
3192 ) {
3193 (Some(param_span), Some(prev_param_span)) => {
3194 Some(prev_param_span.shrink_to_hi().to(param_span))
3195 }
3196 _ => None,
3197 }
3198 }
3199 };
3200 match use_set {
3201 Some(LifetimeUseSet::Many) => {}
3202 Some(LifetimeUseSet::One { use_span, use_ctxt }) => {
3203 debug!(?param.ident, ?param.ident.span, ?use_span);
3204
3205 let elidable = matches!(use_ctxt, LifetimeCtxt::Ref);
3206 let deletion_span =
3207 if param.bounds.is_empty() { deletion_span() } else { None };
3208
3209 self.r.lint_buffer.buffer_lint(
3210 lint::builtin::SINGLE_USE_LIFETIMES,
3211 param.id,
3212 param.ident.span,
3213 lint::BuiltinLintDiag::SingleUseLifetime {
3214 param_span: param.ident.span,
3215 use_span: Some((use_span, elidable)),
3216 deletion_span,
3217 ident: param.ident,
3218 },
3219 );
3220 }
3221 None => {
3222 debug!(?param.ident, ?param.ident.span);
3223 let deletion_span = deletion_span();
3224
3225 if deletion_span.is_some_and(|sp| !sp.in_derive_expansion()) {
3227 self.r.lint_buffer.buffer_lint(
3228 lint::builtin::UNUSED_LIFETIMES,
3229 param.id,
3230 param.ident.span,
3231 lint::BuiltinLintDiag::SingleUseLifetime {
3232 param_span: param.ident.span,
3233 use_span: None,
3234 deletion_span,
3235 ident: param.ident,
3236 },
3237 );
3238 }
3239 }
3240 }
3241 }
3242 }
3243
3244 pub(crate) fn emit_undeclared_lifetime_error(
3245 &self,
3246 lifetime_ref: &ast::Lifetime,
3247 outer_lifetime_ref: Option<Ident>,
3248 ) {
3249 debug_assert_ne!(lifetime_ref.ident.name, kw::UnderscoreLifetime);
3250 let mut err = if let Some(outer) = outer_lifetime_ref {
3251 struct_span_code_err!(
3252 self.r.dcx(),
3253 lifetime_ref.ident.span,
3254 E0401,
3255 "can't use generic parameters from outer item",
3256 )
3257 .with_span_label(lifetime_ref.ident.span, "use of generic parameter from outer item")
3258 .with_span_label(outer.span, "lifetime parameter from outer item")
3259 } else {
3260 struct_span_code_err!(
3261 self.r.dcx(),
3262 lifetime_ref.ident.span,
3263 E0261,
3264 "use of undeclared lifetime name `{}`",
3265 lifetime_ref.ident
3266 )
3267 .with_span_label(lifetime_ref.ident.span, "undeclared lifetime")
3268 };
3269
3270 if edit_distance(lifetime_ref.ident.name.as_str(), "'static", 2).is_some() {
3272 err.span_suggestion_verbose(
3273 lifetime_ref.ident.span,
3274 "you may have misspelled the `'static` lifetime",
3275 "'static",
3276 Applicability::MachineApplicable,
3277 );
3278 } else {
3279 self.suggest_introducing_lifetime(
3280 &mut err,
3281 Some(lifetime_ref.ident),
3282 |err, _, span, message, suggestion, span_suggs| {
3283 err.multipart_suggestion_verbose(
3284 message,
3285 std::iter::once((span, suggestion)).chain(span_suggs).collect(),
3286 Applicability::MaybeIncorrect,
3287 );
3288 true
3289 },
3290 );
3291 }
3292
3293 err.emit();
3294 }
3295
3296 fn suggest_introducing_lifetime(
3297 &self,
3298 err: &mut Diag<'_>,
3299 name: Option<Ident>,
3300 suggest: impl Fn(
3301 &mut Diag<'_>,
3302 bool,
3303 Span,
3304 Cow<'static, str>,
3305 String,
3306 Vec<(Span, String)>,
3307 ) -> bool,
3308 ) {
3309 let mut suggest_note = true;
3310 for rib in self.lifetime_ribs.iter().rev() {
3311 let mut should_continue = true;
3312 match rib.kind {
3313 LifetimeRibKind::Generics { binder, span, kind } => {
3314 if let LifetimeBinderKind::ConstItem = kind
3317 && !self.r.tcx().features().generic_const_items()
3318 {
3319 continue;
3320 }
3321 if let LifetimeBinderKind::ImplAssocType = kind {
3322 continue;
3323 }
3324
3325 if !span.can_be_used_for_suggestions()
3326 && suggest_note
3327 && let Some(name) = name
3328 {
3329 suggest_note = false; err.span_label(
3331 span,
3332 format!(
3333 "lifetime `{name}` is missing in item created through this procedural macro",
3334 ),
3335 );
3336 continue;
3337 }
3338
3339 let higher_ranked = matches!(
3340 kind,
3341 LifetimeBinderKind::FnPtrType
3342 | LifetimeBinderKind::PolyTrait
3343 | LifetimeBinderKind::WhereBound
3344 );
3345
3346 let mut rm_inner_binders: FxIndexSet<Span> = Default::default();
3347 let (span, sugg) = if span.is_empty() {
3348 let mut binder_idents: FxIndexSet<Ident> = Default::default();
3349 binder_idents.insert(name.unwrap_or(Ident::from_str("'a")));
3350
3351 if let LifetimeBinderKind::WhereBound = kind
3358 && let Some(predicate) = self.diag_metadata.current_where_predicate
3359 && let ast::WherePredicateKind::BoundPredicate(
3360 ast::WhereBoundPredicate { bounded_ty, bounds, .. },
3361 ) = &predicate.kind
3362 && bounded_ty.id == binder
3363 {
3364 for bound in bounds {
3365 if let ast::GenericBound::Trait(poly_trait_ref) = bound
3366 && let span = poly_trait_ref
3367 .span
3368 .with_hi(poly_trait_ref.trait_ref.path.span.lo())
3369 && !span.is_empty()
3370 {
3371 rm_inner_binders.insert(span);
3372 poly_trait_ref.bound_generic_params.iter().for_each(|v| {
3373 binder_idents.insert(v.ident);
3374 });
3375 }
3376 }
3377 }
3378
3379 let binders_sugg: String = binder_idents
3380 .into_iter()
3381 .map(|ident| ident.to_string())
3382 .intersperse(", ".to_owned())
3383 .collect();
3384 let sugg = format!(
3385 "{}<{}>{}",
3386 if higher_ranked { "for" } else { "" },
3387 binders_sugg,
3388 if higher_ranked { " " } else { "" },
3389 );
3390 (span, sugg)
3391 } else {
3392 let span = self
3393 .r
3394 .tcx
3395 .sess
3396 .source_map()
3397 .span_through_char(span, '<')
3398 .shrink_to_hi();
3399 let sugg =
3400 format!("{}, ", name.map(|i| i.to_string()).as_deref().unwrap_or("'a"));
3401 (span, sugg)
3402 };
3403
3404 if higher_ranked {
3405 let message = Cow::from(format!(
3406 "consider making the {} lifetime-generic with a new `{}` lifetime",
3407 kind.descr(),
3408 name.map(|i| i.to_string()).as_deref().unwrap_or("'a"),
3409 ));
3410 should_continue = suggest(
3411 err,
3412 true,
3413 span,
3414 message,
3415 sugg,
3416 if !rm_inner_binders.is_empty() {
3417 rm_inner_binders
3418 .into_iter()
3419 .map(|v| (v, "".to_string()))
3420 .collect::<Vec<_>>()
3421 } else {
3422 vec![]
3423 },
3424 );
3425 err.note_once(
3426 "for more information on higher-ranked polymorphism, visit \
3427 https://doc.rust-lang.org/nomicon/hrtb.html",
3428 );
3429 } else if let Some(name) = name {
3430 let message =
3431 Cow::from(format!("consider introducing lifetime `{name}` here"));
3432 should_continue = suggest(err, false, span, message, sugg, vec![]);
3433 } else {
3434 let message = Cow::from("consider introducing a named lifetime parameter");
3435 should_continue = suggest(err, false, span, message, sugg, vec![]);
3436 }
3437 }
3438 LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy => break,
3439 _ => {}
3440 }
3441 if !should_continue {
3442 break;
3443 }
3444 }
3445 }
3446
3447 pub(crate) fn emit_non_static_lt_in_const_param_ty_error(&self, lifetime_ref: &ast::Lifetime) {
3448 self.r
3449 .dcx()
3450 .create_err(errors::ParamInTyOfConstParam {
3451 span: lifetime_ref.ident.span,
3452 name: lifetime_ref.ident.name,
3453 })
3454 .emit();
3455 }
3456
3457 pub(crate) fn emit_forbidden_non_static_lifetime_error(
3461 &self,
3462 cause: NoConstantGenericsReason,
3463 lifetime_ref: &ast::Lifetime,
3464 ) {
3465 match cause {
3466 NoConstantGenericsReason::IsEnumDiscriminant => {
3467 self.r
3468 .dcx()
3469 .create_err(errors::ParamInEnumDiscriminant {
3470 span: lifetime_ref.ident.span,
3471 name: lifetime_ref.ident.name,
3472 param_kind: errors::ParamKindInEnumDiscriminant::Lifetime,
3473 })
3474 .emit();
3475 }
3476 NoConstantGenericsReason::NonTrivialConstArg => {
3477 assert!(!self.r.tcx.features().generic_const_exprs());
3478 self.r
3479 .dcx()
3480 .create_err(errors::ParamInNonTrivialAnonConst {
3481 span: lifetime_ref.ident.span,
3482 name: lifetime_ref.ident.name,
3483 param_kind: errors::ParamKindInNonTrivialAnonConst::Lifetime,
3484 help: self
3485 .r
3486 .tcx
3487 .sess
3488 .is_nightly_build()
3489 .then_some(errors::ParamInNonTrivialAnonConstHelp),
3490 })
3491 .emit();
3492 }
3493 }
3494 }
3495
3496 pub(crate) fn report_missing_lifetime_specifiers(
3497 &mut self,
3498 lifetime_refs: Vec<MissingLifetime>,
3499 function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
3500 ) -> ErrorGuaranteed {
3501 let num_lifetimes: usize = lifetime_refs.iter().map(|lt| lt.count).sum();
3502 let spans: Vec<_> = lifetime_refs.iter().map(|lt| lt.span).collect();
3503
3504 let mut err = struct_span_code_err!(
3505 self.r.dcx(),
3506 spans,
3507 E0106,
3508 "missing lifetime specifier{}",
3509 pluralize!(num_lifetimes)
3510 );
3511 self.add_missing_lifetime_specifiers_label(
3512 &mut err,
3513 lifetime_refs,
3514 function_param_lifetimes,
3515 );
3516 err.emit()
3517 }
3518
3519 fn add_missing_lifetime_specifiers_label(
3520 &mut self,
3521 err: &mut Diag<'_>,
3522 lifetime_refs: Vec<MissingLifetime>,
3523 function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
3524 ) {
3525 for < in &lifetime_refs {
3526 err.span_label(
3527 lt.span,
3528 format!(
3529 "expected {} lifetime parameter{}",
3530 if lt.count == 1 { "named".to_string() } else { lt.count.to_string() },
3531 pluralize!(lt.count),
3532 ),
3533 );
3534 }
3535
3536 let mut in_scope_lifetimes: Vec<_> = self
3537 .lifetime_ribs
3538 .iter()
3539 .rev()
3540 .take_while(|rib| {
3541 !matches!(rib.kind, LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy)
3542 })
3543 .flat_map(|rib| rib.bindings.iter())
3544 .map(|(&ident, &res)| (ident, res))
3545 .filter(|(ident, _)| ident.name != kw::UnderscoreLifetime)
3546 .collect();
3547 debug!(?in_scope_lifetimes);
3548
3549 let mut maybe_static = false;
3550 debug!(?function_param_lifetimes);
3551 if let Some((param_lifetimes, params)) = &function_param_lifetimes {
3552 let elided_len = param_lifetimes.len();
3553 let num_params = params.len();
3554
3555 let mut m = String::new();
3556
3557 for (i, info) in params.iter().enumerate() {
3558 let ElisionFnParameter { ident, index, lifetime_count, span } = *info;
3559 debug_assert_ne!(lifetime_count, 0);
3560
3561 err.span_label(span, "");
3562
3563 if i != 0 {
3564 if i + 1 < num_params {
3565 m.push_str(", ");
3566 } else if num_params == 2 {
3567 m.push_str(" or ");
3568 } else {
3569 m.push_str(", or ");
3570 }
3571 }
3572
3573 let help_name = if let Some(ident) = ident {
3574 format!("`{ident}`")
3575 } else {
3576 format!("argument {}", index + 1)
3577 };
3578
3579 if lifetime_count == 1 {
3580 m.push_str(&help_name[..])
3581 } else {
3582 m.push_str(&format!("one of {help_name}'s {lifetime_count} lifetimes")[..])
3583 }
3584 }
3585
3586 if num_params == 0 {
3587 err.help(
3588 "this function's return type contains a borrowed value, but there is no value \
3589 for it to be borrowed from",
3590 );
3591 if in_scope_lifetimes.is_empty() {
3592 maybe_static = true;
3593 in_scope_lifetimes = vec![(
3594 Ident::with_dummy_span(kw::StaticLifetime),
3595 (DUMMY_NODE_ID, LifetimeRes::Static),
3596 )];
3597 }
3598 } else if elided_len == 0 {
3599 err.help(
3600 "this function's return type contains a borrowed value with an elided \
3601 lifetime, but the lifetime cannot be derived from the arguments",
3602 );
3603 if in_scope_lifetimes.is_empty() {
3604 maybe_static = true;
3605 in_scope_lifetimes = vec![(
3606 Ident::with_dummy_span(kw::StaticLifetime),
3607 (DUMMY_NODE_ID, LifetimeRes::Static),
3608 )];
3609 }
3610 } else if num_params == 1 {
3611 err.help(format!(
3612 "this function's return type contains a borrowed value, but the signature does \
3613 not say which {m} it is borrowed from",
3614 ));
3615 } else {
3616 err.help(format!(
3617 "this function's return type contains a borrowed value, but the signature does \
3618 not say whether it is borrowed from {m}",
3619 ));
3620 }
3621 }
3622
3623 #[allow(rustc::symbol_intern_string_literal)]
3624 let existing_name = match &in_scope_lifetimes[..] {
3625 [] => Symbol::intern("'a"),
3626 [(existing, _)] => existing.name,
3627 _ => Symbol::intern("'lifetime"),
3628 };
3629
3630 let mut spans_suggs: Vec<_> = Vec::new();
3631 let build_sugg = |lt: MissingLifetime| match lt.kind {
3632 MissingLifetimeKind::Underscore => {
3633 debug_assert_eq!(lt.count, 1);
3634 (lt.span, existing_name.to_string())
3635 }
3636 MissingLifetimeKind::Ampersand => {
3637 debug_assert_eq!(lt.count, 1);
3638 (lt.span.shrink_to_hi(), format!("{existing_name} "))
3639 }
3640 MissingLifetimeKind::Comma => {
3641 let sugg: String = std::iter::repeat_n([existing_name.as_str(), ", "], lt.count)
3642 .flatten()
3643 .collect();
3644 (lt.span.shrink_to_hi(), sugg)
3645 }
3646 MissingLifetimeKind::Brackets => {
3647 let sugg: String = std::iter::once("<")
3648 .chain(std::iter::repeat_n(existing_name.as_str(), lt.count).intersperse(", "))
3649 .chain([">"])
3650 .collect();
3651 (lt.span.shrink_to_hi(), sugg)
3652 }
3653 };
3654 for < in &lifetime_refs {
3655 spans_suggs.push(build_sugg(lt));
3656 }
3657 debug!(?spans_suggs);
3658 match in_scope_lifetimes.len() {
3659 0 => {
3660 if let Some((param_lifetimes, _)) = function_param_lifetimes {
3661 for lt in param_lifetimes {
3662 spans_suggs.push(build_sugg(lt))
3663 }
3664 }
3665 self.suggest_introducing_lifetime(
3666 err,
3667 None,
3668 |err, higher_ranked, span, message, intro_sugg, _| {
3669 err.multipart_suggestion_verbose(
3670 message,
3671 std::iter::once((span, intro_sugg))
3672 .chain(spans_suggs.clone())
3673 .collect(),
3674 Applicability::MaybeIncorrect,
3675 );
3676 higher_ranked
3677 },
3678 );
3679 }
3680 1 => {
3681 let post = if maybe_static {
3682 let owned = if let [lt] = &lifetime_refs[..]
3683 && lt.kind != MissingLifetimeKind::Ampersand
3684 {
3685 ", or if you will only have owned values"
3686 } else {
3687 ""
3688 };
3689 format!(
3690 ", but this is uncommon unless you're returning a borrowed value from a \
3691 `const` or a `static`{owned}",
3692 )
3693 } else {
3694 String::new()
3695 };
3696 err.multipart_suggestion_verbose(
3697 format!("consider using the `{existing_name}` lifetime{post}"),
3698 spans_suggs,
3699 Applicability::MaybeIncorrect,
3700 );
3701 if maybe_static {
3702 if let [lt] = &lifetime_refs[..]
3708 && (lt.kind == MissingLifetimeKind::Ampersand
3709 || lt.kind == MissingLifetimeKind::Underscore)
3710 {
3711 let pre = if let Some((kind, _span)) = self.diag_metadata.current_function
3712 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
3713 && !sig.decl.inputs.is_empty()
3714 && let sugg = sig
3715 .decl
3716 .inputs
3717 .iter()
3718 .filter_map(|param| {
3719 if param.ty.span.contains(lt.span) {
3720 None
3723 } else if let TyKind::CVarArgs = param.ty.kind {
3724 None
3726 } else if let TyKind::ImplTrait(..) = ¶m.ty.kind {
3727 None
3729 } else {
3730 Some((param.ty.span.shrink_to_lo(), "&".to_string()))
3731 }
3732 })
3733 .collect::<Vec<_>>()
3734 && !sugg.is_empty()
3735 {
3736 let (the, s) = if sig.decl.inputs.len() == 1 {
3737 ("the", "")
3738 } else {
3739 ("one of the", "s")
3740 };
3741 let dotdotdot =
3742 if lt.kind == MissingLifetimeKind::Ampersand { "..." } else { "" };
3743 err.multipart_suggestion_verbose(
3744 format!(
3745 "instead, you are more likely to want to change {the} \
3746 argument{s} to be borrowed{dotdotdot}",
3747 ),
3748 sugg,
3749 Applicability::MaybeIncorrect,
3750 );
3751 "...or alternatively, you might want"
3752 } else if (lt.kind == MissingLifetimeKind::Ampersand
3753 || lt.kind == MissingLifetimeKind::Underscore)
3754 && let Some((kind, _span)) = self.diag_metadata.current_function
3755 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
3756 && let ast::FnRetTy::Ty(ret_ty) = &sig.decl.output
3757 && !sig.decl.inputs.is_empty()
3758 && let arg_refs = sig
3759 .decl
3760 .inputs
3761 .iter()
3762 .filter_map(|param| match ¶m.ty.kind {
3763 TyKind::ImplTrait(_, bounds) => Some(bounds),
3764 _ => None,
3765 })
3766 .flat_map(|bounds| bounds.into_iter())
3767 .collect::<Vec<_>>()
3768 && !arg_refs.is_empty()
3769 {
3770 let mut lt_finder =
3776 LifetimeFinder { lifetime: lt.span, found: None, seen: vec![] };
3777 for bound in arg_refs {
3778 if let ast::GenericBound::Trait(trait_ref) = bound {
3779 lt_finder.visit_trait_ref(&trait_ref.trait_ref);
3780 }
3781 }
3782 lt_finder.visit_ty(ret_ty);
3783 let spans_suggs: Vec<_> = lt_finder
3784 .seen
3785 .iter()
3786 .filter_map(|ty| match &ty.kind {
3787 TyKind::Ref(_, mut_ty) => {
3788 let span = ty.span.with_hi(mut_ty.ty.span.lo());
3789 Some((span, "&'a ".to_string()))
3790 }
3791 _ => None,
3792 })
3793 .collect();
3794 self.suggest_introducing_lifetime(
3795 err,
3796 None,
3797 |err, higher_ranked, span, message, intro_sugg, _| {
3798 err.multipart_suggestion_verbose(
3799 message,
3800 std::iter::once((span, intro_sugg))
3801 .chain(spans_suggs.clone())
3802 .collect(),
3803 Applicability::MaybeIncorrect,
3804 );
3805 higher_ranked
3806 },
3807 );
3808 "alternatively, you might want"
3809 } else {
3810 "instead, you are more likely to want"
3811 };
3812 let mut owned_sugg = lt.kind == MissingLifetimeKind::Ampersand;
3813 let mut sugg = vec![(lt.span, String::new())];
3814 if let Some((kind, _span)) = self.diag_metadata.current_function
3815 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
3816 && let ast::FnRetTy::Ty(ty) = &sig.decl.output
3817 {
3818 let mut lt_finder =
3819 LifetimeFinder { lifetime: lt.span, found: None, seen: vec![] };
3820 lt_finder.visit_ty(&ty);
3821
3822 if let [Ty { span, kind: TyKind::Ref(_, mut_ty), .. }] =
3823 <_finder.seen[..]
3824 {
3825 sugg = vec![(span.with_hi(mut_ty.ty.span.lo()), String::new())];
3831 owned_sugg = true;
3832 }
3833 if let Some(ty) = lt_finder.found {
3834 if let TyKind::Path(None, path) = &ty.kind {
3835 let path: Vec<_> = Segment::from_path(path);
3837 match self.resolve_path(
3838 &path,
3839 Some(TypeNS),
3840 None,
3841 PathSource::Type,
3842 ) {
3843 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
3844 match module.res() {
3845 Some(Res::PrimTy(PrimTy::Str)) => {
3846 sugg = vec![(
3848 lt.span.with_hi(ty.span.hi()),
3849 "String".to_string(),
3850 )];
3851 }
3852 Some(Res::PrimTy(..)) => {}
3853 Some(Res::Def(
3854 DefKind::Struct
3855 | DefKind::Union
3856 | DefKind::Enum
3857 | DefKind::ForeignTy
3858 | DefKind::AssocTy
3859 | DefKind::OpaqueTy
3860 | DefKind::TyParam,
3861 _,
3862 )) => {}
3863 _ => {
3864 owned_sugg = false;
3866 }
3867 }
3868 }
3869 PathResult::NonModule(res) => {
3870 match res.base_res() {
3871 Res::PrimTy(PrimTy::Str) => {
3872 sugg = vec![(
3874 lt.span.with_hi(ty.span.hi()),
3875 "String".to_string(),
3876 )];
3877 }
3878 Res::PrimTy(..) => {}
3879 Res::Def(
3880 DefKind::Struct
3881 | DefKind::Union
3882 | DefKind::Enum
3883 | DefKind::ForeignTy
3884 | DefKind::AssocTy
3885 | DefKind::OpaqueTy
3886 | DefKind::TyParam,
3887 _,
3888 ) => {}
3889 _ => {
3890 owned_sugg = false;
3892 }
3893 }
3894 }
3895 _ => {
3896 owned_sugg = false;
3898 }
3899 }
3900 }
3901 if let TyKind::Slice(inner_ty) = &ty.kind {
3902 sugg = vec![
3904 (lt.span.with_hi(inner_ty.span.lo()), "Vec<".to_string()),
3905 (ty.span.with_lo(inner_ty.span.hi()), ">".to_string()),
3906 ];
3907 }
3908 }
3909 }
3910 if owned_sugg {
3911 err.multipart_suggestion_verbose(
3912 format!("{pre} to return an owned value"),
3913 sugg,
3914 Applicability::MaybeIncorrect,
3915 );
3916 }
3917 }
3918 }
3919 }
3920 _ => {
3921 let lifetime_spans: Vec<_> =
3922 in_scope_lifetimes.iter().map(|(ident, _)| ident.span).collect();
3923 err.span_note(lifetime_spans, "these named lifetimes are available to use");
3924
3925 if spans_suggs.len() > 0 {
3926 err.multipart_suggestion_verbose(
3929 "consider using one of the available lifetimes here",
3930 spans_suggs,
3931 Applicability::HasPlaceholders,
3932 );
3933 }
3934 }
3935 }
3936 }
3937}
3938
3939fn mk_where_bound_predicate(
3940 path: &Path,
3941 poly_trait_ref: &ast::PolyTraitRef,
3942 ty: &Ty,
3943) -> Option<ast::WhereBoundPredicate> {
3944 let modified_segments = {
3945 let mut segments = path.segments.clone();
3946 let [preceding @ .., second_last, last] = segments.as_mut_slice() else {
3947 return None;
3948 };
3949 let mut segments = ThinVec::from(preceding);
3950
3951 let added_constraint = ast::AngleBracketedArg::Constraint(ast::AssocItemConstraint {
3952 id: DUMMY_NODE_ID,
3953 ident: last.ident,
3954 gen_args: None,
3955 kind: ast::AssocItemConstraintKind::Equality {
3956 term: ast::Term::Ty(Box::new(ast::Ty {
3957 kind: ast::TyKind::Path(None, poly_trait_ref.trait_ref.path.clone()),
3958 id: DUMMY_NODE_ID,
3959 span: DUMMY_SP,
3960 tokens: None,
3961 })),
3962 },
3963 span: DUMMY_SP,
3964 });
3965
3966 match second_last.args.as_deref_mut() {
3967 Some(ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs { args, .. })) => {
3968 args.push(added_constraint);
3969 }
3970 Some(_) => return None,
3971 None => {
3972 second_last.args =
3973 Some(Box::new(ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs {
3974 args: ThinVec::from([added_constraint]),
3975 span: DUMMY_SP,
3976 })));
3977 }
3978 }
3979
3980 segments.push(second_last.clone());
3981 segments
3982 };
3983
3984 let new_where_bound_predicate = ast::WhereBoundPredicate {
3985 bound_generic_params: ThinVec::new(),
3986 bounded_ty: Box::new(ty.clone()),
3987 bounds: vec![ast::GenericBound::Trait(ast::PolyTraitRef {
3988 bound_generic_params: ThinVec::new(),
3989 modifiers: ast::TraitBoundModifiers::NONE,
3990 trait_ref: ast::TraitRef {
3991 path: ast::Path { segments: modified_segments, span: DUMMY_SP, tokens: None },
3992 ref_id: DUMMY_NODE_ID,
3993 },
3994 span: DUMMY_SP,
3995 parens: ast::Parens::No,
3996 })],
3997 };
3998
3999 Some(new_where_bound_predicate)
4000}
4001
4002pub(super) fn signal_lifetime_shadowing(sess: &Session, orig: Ident, shadower: Ident) {
4004 struct_span_code_err!(
4005 sess.dcx(),
4006 shadower.span,
4007 E0496,
4008 "lifetime name `{}` shadows a lifetime name that is already in scope",
4009 orig.name,
4010 )
4011 .with_span_label(orig.span, "first declared here")
4012 .with_span_label(shadower.span, format!("lifetime `{}` already in scope", orig.name))
4013 .emit();
4014}
4015
4016struct LifetimeFinder<'ast> {
4017 lifetime: Span,
4018 found: Option<&'ast Ty>,
4019 seen: Vec<&'ast Ty>,
4020}
4021
4022impl<'ast> Visitor<'ast> for LifetimeFinder<'ast> {
4023 fn visit_ty(&mut self, t: &'ast Ty) {
4024 if let TyKind::Ref(_, mut_ty) | TyKind::PinnedRef(_, mut_ty) = &t.kind {
4025 self.seen.push(t);
4026 if t.span.lo() == self.lifetime.lo() {
4027 self.found = Some(&mut_ty.ty);
4028 }
4029 }
4030 walk_ty(self, t)
4031 }
4032}
4033
4034pub(super) fn signal_label_shadowing(sess: &Session, orig: Span, shadower: Ident) {
4037 let name = shadower.name;
4038 let shadower = shadower.span;
4039 sess.dcx()
4040 .struct_span_warn(
4041 shadower,
4042 format!("label name `{name}` shadows a label name that is already in scope"),
4043 )
4044 .with_span_label(orig, "first declared here")
4045 .with_span_label(shadower, format!("label `{name}` already in scope"))
4046 .emit();
4047}