rustc_trait_selection/error_reporting/traits/
mod.rs

1pub mod ambiguity;
2pub mod call_kind;
3mod fulfillment_errors;
4pub mod on_unimplemented;
5pub mod on_unimplemented_condition;
6pub mod on_unimplemented_format;
7mod overflow;
8pub mod suggestions;
9
10use std::{fmt, iter};
11
12use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
13use rustc_errors::{Applicability, Diag, E0038, E0276, MultiSpan, struct_span_code_err};
14use rustc_hir::def_id::{DefId, LocalDefId};
15use rustc_hir::intravisit::Visitor;
16use rustc_hir::{self as hir, AmbigArg};
17use rustc_infer::traits::solve::Goal;
18use rustc_infer::traits::{
19    DynCompatibilityViolation, Obligation, ObligationCause, ObligationCauseCode,
20    PredicateObligation, SelectionError,
21};
22use rustc_middle::ty::print::{PrintTraitRefExt as _, with_no_trimmed_paths};
23use rustc_middle::ty::{self, Ty, TyCtxt};
24use rustc_span::{DesugaringKind, ErrorGuaranteed, ExpnKind, Span};
25use tracing::{info, instrument};
26
27pub use self::overflow::*;
28use crate::error_reporting::TypeErrCtxt;
29use crate::traits::{FulfillmentError, FulfillmentErrorCode};
30
31// When outputting impl candidates, prefer showing those that are more similar.
32//
33// We also compare candidates after skipping lifetimes, which has a lower
34// priority than exact matches.
35#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
36pub enum CandidateSimilarity {
37    Exact { ignoring_lifetimes: bool },
38    Fuzzy { ignoring_lifetimes: bool },
39}
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub struct ImplCandidate<'tcx> {
43    pub trait_ref: ty::TraitRef<'tcx>,
44    pub similarity: CandidateSimilarity,
45    impl_def_id: DefId,
46}
47
48enum GetSafeTransmuteErrorAndReason {
49    Silent,
50    Default,
51    Error { err_msg: String, safe_transmute_explanation: Option<String> },
52}
53
54/// Crude way of getting back an `Expr` from a `Span`.
55pub struct FindExprBySpan<'hir> {
56    pub span: Span,
57    pub result: Option<&'hir hir::Expr<'hir>>,
58    pub ty_result: Option<&'hir hir::Ty<'hir>>,
59    pub include_closures: bool,
60    pub tcx: TyCtxt<'hir>,
61}
62
63impl<'hir> FindExprBySpan<'hir> {
64    pub fn new(span: Span, tcx: TyCtxt<'hir>) -> Self {
65        Self { span, result: None, ty_result: None, tcx, include_closures: false }
66    }
67}
68
69impl<'v> Visitor<'v> for FindExprBySpan<'v> {
70    type NestedFilter = rustc_middle::hir::nested_filter::OnlyBodies;
71
72    fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
73        self.tcx
74    }
75
76    fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
77        if self.span == ex.span {
78            self.result = Some(ex);
79        } else {
80            if let hir::ExprKind::Closure(..) = ex.kind
81                && self.include_closures
82                && let closure_header_sp = self.span.with_hi(ex.span.hi())
83                && closure_header_sp == ex.span
84            {
85                self.result = Some(ex);
86            }
87            hir::intravisit::walk_expr(self, ex);
88        }
89    }
90
91    fn visit_ty(&mut self, ty: &'v hir::Ty<'v, AmbigArg>) {
92        if self.span == ty.span {
93            self.ty_result = Some(ty.as_unambig_ty());
94        } else {
95            hir::intravisit::walk_ty(self, ty);
96        }
97    }
98}
99
100/// Summarizes information
101#[derive(Clone)]
102pub enum ArgKind {
103    /// An argument of non-tuple type. Parameters are (name, ty)
104    Arg(String, String),
105
106    /// An argument of tuple type. For a "found" argument, the span is
107    /// the location in the source of the pattern. For an "expected"
108    /// argument, it will be None. The vector is a list of (name, ty)
109    /// strings for the components of the tuple.
110    Tuple(Option<Span>, Vec<(String, String)>),
111}
112
113impl ArgKind {
114    fn empty() -> ArgKind {
115        ArgKind::Arg("_".to_owned(), "_".to_owned())
116    }
117
118    /// Creates an `ArgKind` from the expected type of an
119    /// argument. It has no name (`_`) and an optional source span.
120    pub fn from_expected_ty(t: Ty<'_>, span: Option<Span>) -> ArgKind {
121        match t.kind() {
122            ty::Tuple(tys) => ArgKind::Tuple(
123                span,
124                tys.iter().map(|ty| ("_".to_owned(), ty.to_string())).collect::<Vec<_>>(),
125            ),
126            _ => ArgKind::Arg("_".to_owned(), t.to_string()),
127        }
128    }
129}
130
131#[derive(Copy, Clone)]
132pub enum DefIdOrName {
133    DefId(DefId),
134    Name(&'static str),
135}
136
137impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
138    pub fn report_fulfillment_errors(
139        &self,
140        mut errors: Vec<FulfillmentError<'tcx>>,
141    ) -> ErrorGuaranteed {
142        #[derive(Debug)]
143        struct ErrorDescriptor<'tcx> {
144            goal: Goal<'tcx, ty::Predicate<'tcx>>,
145            index: Option<usize>, // None if this is an old error
146        }
147
148        let mut error_map: FxIndexMap<_, Vec<_>> = self
149            .reported_trait_errors
150            .borrow()
151            .iter()
152            .map(|(&span, goals)| {
153                (span, goals.0.iter().map(|&goal| ErrorDescriptor { goal, index: None }).collect())
154            })
155            .collect();
156
157        // Ensure `T: Sized`, `T: MetaSized`, `T: PointeeSized` and `T: WF` obligations come last,
158        // and `Subtype` obligations from `FormatLiteral` desugarings come first.
159        // This lets us display diagnostics with more relevant type information and hide redundant
160        // E0282 errors.
161        #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
162        enum ErrorSortKey {
163            SubtypeFormat(usize, usize),
164            OtherKind,
165            SizedTrait,
166            MetaSizedTrait,
167            PointeeSizedTrait,
168            Coerce,
169            WellFormed,
170        }
171        errors.sort_by_key(|e| {
172            let maybe_sizedness_did = match e.obligation.predicate.kind().skip_binder() {
173                ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => Some(pred.def_id()),
174                ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(pred)) => Some(pred.def_id()),
175                _ => None,
176            };
177
178            match e.obligation.predicate.kind().skip_binder() {
179                ty::PredicateKind::Subtype(_)
180                    if matches!(
181                        e.obligation.cause.span.desugaring_kind(),
182                        Some(DesugaringKind::FormatLiteral { .. })
183                    ) =>
184                {
185                    let (_, row, col, ..) =
186                        self.tcx.sess.source_map().span_to_location_info(e.obligation.cause.span);
187                    ErrorSortKey::SubtypeFormat(row, col)
188                }
189                _ if maybe_sizedness_did == self.tcx.lang_items().sized_trait() => {
190                    ErrorSortKey::SizedTrait
191                }
192                _ if maybe_sizedness_did == self.tcx.lang_items().meta_sized_trait() => {
193                    ErrorSortKey::MetaSizedTrait
194                }
195                _ if maybe_sizedness_did == self.tcx.lang_items().pointee_sized_trait() => {
196                    ErrorSortKey::PointeeSizedTrait
197                }
198                ty::PredicateKind::Coerce(_) => ErrorSortKey::Coerce,
199                ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(_)) => {
200                    ErrorSortKey::WellFormed
201                }
202                _ => ErrorSortKey::OtherKind,
203            }
204        });
205
206        for (index, error) in errors.iter().enumerate() {
207            // We want to ignore desugarings here: spans are equivalent even
208            // if one is the result of a desugaring and the other is not.
209            let mut span = error.obligation.cause.span;
210            let expn_data = span.ctxt().outer_expn_data();
211            if let ExpnKind::Desugaring(_) = expn_data.kind {
212                span = expn_data.call_site;
213            }
214
215            error_map
216                .entry(span)
217                .or_default()
218                .push(ErrorDescriptor { goal: error.obligation.as_goal(), index: Some(index) });
219        }
220
221        // We do this in 2 passes because we want to display errors in order, though
222        // maybe it *is* better to sort errors by span or something.
223        let mut is_suppressed = vec![false; errors.len()];
224        for (_, error_set) in error_map.iter() {
225            // We want to suppress "duplicate" errors with the same span.
226            for error in error_set {
227                if let Some(index) = error.index {
228                    // Suppress errors that are either:
229                    // 1) strictly implied by another error.
230                    // 2) implied by an error with a smaller index.
231                    for error2 in error_set {
232                        if error2.index.is_some_and(|index2| is_suppressed[index2]) {
233                            // Avoid errors being suppressed by already-suppressed
234                            // errors, to prevent all errors from being suppressed
235                            // at once.
236                            continue;
237                        }
238
239                        if self.error_implies(error2.goal, error.goal)
240                            && !(error2.index >= error.index
241                                && self.error_implies(error.goal, error2.goal))
242                        {
243                            info!("skipping {:?} (implied by {:?})", error, error2);
244                            is_suppressed[index] = true;
245                            break;
246                        }
247                    }
248                }
249            }
250        }
251
252        let mut reported = None;
253
254        for from_expansion in [false, true] {
255            for (error, suppressed) in iter::zip(&errors, &is_suppressed) {
256                if !suppressed && error.obligation.cause.span.from_expansion() == from_expansion {
257                    let guar = self.report_fulfillment_error(error);
258                    self.infcx.set_tainted_by_errors(guar);
259                    reported = Some(guar);
260                    // We want to ignore desugarings here: spans are equivalent even
261                    // if one is the result of a desugaring and the other is not.
262                    let mut span = error.obligation.cause.span;
263                    let expn_data = span.ctxt().outer_expn_data();
264                    if let ExpnKind::Desugaring(_) = expn_data.kind {
265                        span = expn_data.call_site;
266                    }
267                    self.reported_trait_errors
268                        .borrow_mut()
269                        .entry(span)
270                        .or_insert_with(|| (vec![], guar))
271                        .0
272                        .push(error.obligation.as_goal());
273                }
274            }
275        }
276
277        // It could be that we don't report an error because we have seen an `ErrorReported` from
278        // another source. We should probably be able to fix most of these, but some are delayed
279        // bugs that get a proper error after this function.
280        reported.unwrap_or_else(|| self.dcx().delayed_bug("failed to report fulfillment errors"))
281    }
282
283    #[instrument(skip(self), level = "debug")]
284    fn report_fulfillment_error(&self, error: &FulfillmentError<'tcx>) -> ErrorGuaranteed {
285        let mut error = FulfillmentError {
286            obligation: error.obligation.clone(),
287            code: error.code.clone(),
288            root_obligation: error.root_obligation.clone(),
289        };
290        if matches!(
291            error.code,
292            FulfillmentErrorCode::Select(crate::traits::SelectionError::Unimplemented)
293                | FulfillmentErrorCode::Project(_)
294        ) && self.apply_do_not_recommend(&mut error.obligation)
295        {
296            error.code = FulfillmentErrorCode::Select(SelectionError::Unimplemented);
297        }
298
299        match error.code {
300            FulfillmentErrorCode::Select(ref selection_error) => self.report_selection_error(
301                error.obligation.clone(),
302                &error.root_obligation,
303                selection_error,
304            ),
305            FulfillmentErrorCode::Project(ref e) => {
306                self.report_projection_error(&error.obligation, e)
307            }
308            FulfillmentErrorCode::Ambiguity { overflow: None } => {
309                self.maybe_report_ambiguity(&error.obligation)
310            }
311            FulfillmentErrorCode::Ambiguity { overflow: Some(suggest_increasing_limit) } => {
312                self.report_overflow_no_abort(error.obligation.clone(), suggest_increasing_limit)
313            }
314            FulfillmentErrorCode::Subtype(ref expected_found, ref err) => self
315                .report_mismatched_types(
316                    &error.obligation.cause,
317                    error.obligation.param_env,
318                    expected_found.expected,
319                    expected_found.found,
320                    *err,
321                )
322                .emit(),
323            FulfillmentErrorCode::ConstEquate(ref expected_found, ref err) => {
324                let mut diag = self.report_mismatched_consts(
325                    &error.obligation.cause,
326                    error.obligation.param_env,
327                    expected_found.expected,
328                    expected_found.found,
329                    *err,
330                );
331                let code = error.obligation.cause.code().peel_derives().peel_match_impls();
332                if let ObligationCauseCode::WhereClause(..)
333                | ObligationCauseCode::WhereClauseInExpr(..) = code
334                {
335                    self.note_obligation_cause_code(
336                        error.obligation.cause.body_id,
337                        &mut diag,
338                        error.obligation.predicate,
339                        error.obligation.param_env,
340                        code,
341                        &mut vec![],
342                        &mut Default::default(),
343                    );
344                }
345                diag.emit()
346            }
347            FulfillmentErrorCode::Cycle(ref cycle) => self.report_overflow_obligation_cycle(cycle),
348        }
349    }
350}
351
352/// Recovers the "impl X for Y" signature from `impl_def_id` and returns it as a
353/// string.
354pub(crate) fn to_pretty_impl_header(tcx: TyCtxt<'_>, impl_def_id: DefId) -> Option<String> {
355    use std::fmt::Write;
356
357    let trait_ref = tcx.impl_trait_ref(impl_def_id)?.instantiate_identity();
358    let mut w = "impl".to_owned();
359
360    #[derive(Debug, Default)]
361    struct SizednessFound {
362        sized: bool,
363        meta_sized: bool,
364    }
365
366    let mut types_with_sizedness_bounds = FxIndexMap::<_, SizednessFound>::default();
367
368    let args = ty::GenericArgs::identity_for_item(tcx, impl_def_id);
369
370    let arg_names = args.iter().map(|k| k.to_string()).filter(|k| k != "'_").collect::<Vec<_>>();
371    if !arg_names.is_empty() {
372        w.push('<');
373        w.push_str(&arg_names.join(", "));
374        w.push('>');
375
376        for ty in args.types() {
377            // `PointeeSized` params might have no predicates.
378            types_with_sizedness_bounds.insert(ty, SizednessFound::default());
379        }
380    }
381
382    write!(
383        w,
384        " {}{} for {}",
385        tcx.impl_polarity(impl_def_id).as_str(),
386        trait_ref.print_only_trait_path(),
387        tcx.type_of(impl_def_id).instantiate_identity()
388    )
389    .unwrap();
390
391    let predicates = tcx.predicates_of(impl_def_id).predicates;
392    let mut pretty_predicates = Vec::with_capacity(predicates.len());
393
394    let sized_trait = tcx.lang_items().sized_trait();
395    let meta_sized_trait = tcx.lang_items().meta_sized_trait();
396
397    for (p, _) in predicates {
398        // Accumulate the sizedness bounds for each self ty.
399        if let Some(trait_clause) = p.as_trait_clause() {
400            let self_ty = trait_clause.self_ty().skip_binder();
401            let sizedness_of = types_with_sizedness_bounds.entry(self_ty).or_default();
402            if Some(trait_clause.def_id()) == sized_trait {
403                sizedness_of.sized = true;
404                continue;
405            } else if Some(trait_clause.def_id()) == meta_sized_trait {
406                sizedness_of.meta_sized = true;
407                continue;
408            }
409        }
410
411        pretty_predicates.push(p.to_string());
412    }
413
414    for (ty, sizedness) in types_with_sizedness_bounds {
415        if !tcx.features().sized_hierarchy() {
416            if sizedness.sized {
417                // Maybe a default bound, don't write anything.
418            } else {
419                pretty_predicates.push(format!("{ty}: ?Sized"));
420            }
421        } else {
422            if sizedness.sized {
423                // Maybe a default bound, don't write anything.
424                pretty_predicates.push(format!("{ty}: Sized"));
425            } else if sizedness.meta_sized {
426                pretty_predicates.push(format!("{ty}: MetaSized"));
427            } else {
428                pretty_predicates.push(format!("{ty}: PointeeSized"));
429            }
430        }
431    }
432
433    if !pretty_predicates.is_empty() {
434        write!(w, "\n  where {}", pretty_predicates.join(", ")).unwrap();
435    }
436
437    w.push(';');
438    Some(w)
439}
440
441impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
442    pub fn report_extra_impl_obligation(
443        &self,
444        error_span: Span,
445        impl_item_def_id: LocalDefId,
446        trait_item_def_id: DefId,
447        requirement: &dyn fmt::Display,
448    ) -> Diag<'a> {
449        let mut err = struct_span_code_err!(
450            self.dcx(),
451            error_span,
452            E0276,
453            "impl has stricter requirements than trait"
454        );
455
456        if !self.tcx.is_impl_trait_in_trait(trait_item_def_id) {
457            if let Some(span) = self.tcx.hir_span_if_local(trait_item_def_id) {
458                let item_name = self.tcx.item_name(impl_item_def_id.to_def_id());
459                err.span_label(span, format!("definition of `{item_name}` from trait"));
460            }
461        }
462
463        err.span_label(error_span, format!("impl has extra requirement {requirement}"));
464
465        err
466    }
467}
468
469pub fn report_dyn_incompatibility<'tcx>(
470    tcx: TyCtxt<'tcx>,
471    span: Span,
472    hir_id: Option<hir::HirId>,
473    trait_def_id: DefId,
474    violations: &[DynCompatibilityViolation],
475) -> Diag<'tcx> {
476    let trait_str = tcx.def_path_str(trait_def_id);
477    let trait_span = tcx.hir_get_if_local(trait_def_id).and_then(|node| match node {
478        hir::Node::Item(item) => match item.kind {
479            hir::ItemKind::Trait(_, _, _, ident, ..) | hir::ItemKind::TraitAlias(ident, _, _) => {
480                Some(ident.span)
481            }
482            _ => unreachable!(),
483        },
484        _ => None,
485    });
486
487    let mut err = struct_span_code_err!(
488        tcx.dcx(),
489        span,
490        E0038,
491        "the {} `{}` is not dyn compatible",
492        tcx.def_descr(trait_def_id),
493        trait_str
494    );
495    err.span_label(span, format!("`{trait_str}` is not dyn compatible"));
496
497    attempt_dyn_to_impl_suggestion(tcx, hir_id, &mut err);
498
499    let mut reported_violations = FxIndexSet::default();
500    let mut multi_span = vec![];
501    let mut messages = vec![];
502    for violation in violations {
503        if let DynCompatibilityViolation::SizedSelf(sp) = &violation
504            && !sp.is_empty()
505        {
506            // Do not report `SizedSelf` without spans pointing at `SizedSelf` obligations
507            // with a `Span`.
508            reported_violations.insert(DynCompatibilityViolation::SizedSelf(vec![].into()));
509        }
510        if reported_violations.insert(violation.clone()) {
511            let spans = violation.spans();
512            let msg = if trait_span.is_none() || spans.is_empty() {
513                format!("the trait is not dyn compatible because {}", violation.error_msg())
514            } else {
515                format!("...because {}", violation.error_msg())
516            };
517            if spans.is_empty() {
518                err.note(msg);
519            } else {
520                for span in spans {
521                    multi_span.push(span);
522                    messages.push(msg.clone());
523                }
524            }
525        }
526    }
527    let has_multi_span = !multi_span.is_empty();
528    let mut note_span = MultiSpan::from_spans(multi_span.clone());
529    if let (Some(trait_span), true) = (trait_span, has_multi_span) {
530        note_span.push_span_label(trait_span, "this trait is not dyn compatible...");
531    }
532    for (span, msg) in iter::zip(multi_span, messages) {
533        note_span.push_span_label(span, msg);
534    }
535    err.span_note(
536        note_span,
537        "for a trait to be dyn compatible it needs to allow building a vtable\n\
538        for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>",
539    );
540
541    // Only provide the help if its a local trait, otherwise it's not actionable.
542    if trait_span.is_some() {
543        let mut potential_solutions: Vec<_> =
544            reported_violations.into_iter().map(|violation| violation.solution()).collect();
545        potential_solutions.sort();
546        // Allows us to skip suggesting that the same item should be moved to another trait multiple times.
547        potential_solutions.dedup();
548        for solution in potential_solutions {
549            solution.add_to(&mut err);
550        }
551    }
552
553    attempt_dyn_to_enum_suggestion(tcx, trait_def_id, &*trait_str, &mut err);
554
555    err
556}
557
558/// Attempt to suggest converting the `dyn Trait` argument to an enumeration
559/// over the types that implement `Trait`.
560fn attempt_dyn_to_enum_suggestion(
561    tcx: TyCtxt<'_>,
562    trait_def_id: DefId,
563    trait_str: &str,
564    err: &mut Diag<'_>,
565) {
566    let impls_of = tcx.trait_impls_of(trait_def_id);
567
568    if !impls_of.blanket_impls().is_empty() {
569        return;
570    }
571
572    let concrete_impls: Option<Vec<Ty<'_>>> = impls_of
573        .non_blanket_impls()
574        .values()
575        .flatten()
576        .map(|impl_id| {
577            // Don't suggest conversion to enum if the impl types have type parameters.
578            // It's unlikely the user wants to define a generic enum.
579            let Some(impl_type) = tcx.type_of(*impl_id).no_bound_vars() else { return None };
580
581            // Obviously unsized impl types won't be usable in an enum.
582            // Note: this doesn't use `Ty::has_trivial_sizedness` because that function
583            // defaults to assuming that things are *not* sized, whereas we want to
584            // fall back to assuming that things may be sized.
585            match impl_type.kind() {
586                ty::Str | ty::Slice(_) | ty::Dynamic(_, _) => {
587                    return None;
588                }
589                _ => {}
590            }
591            Some(impl_type)
592        })
593        .collect();
594    let Some(concrete_impls) = concrete_impls else { return };
595
596    const MAX_IMPLS_TO_SUGGEST_CONVERTING_TO_ENUM: usize = 9;
597    if concrete_impls.is_empty() || concrete_impls.len() > MAX_IMPLS_TO_SUGGEST_CONVERTING_TO_ENUM {
598        return;
599    }
600
601    let externally_visible = if let Some(def_id) = trait_def_id.as_local() {
602        // We may be executing this during typeck, which would result in cycle
603        // if we used effective_visibilities query, which looks into opaque types
604        // (and therefore calls typeck).
605        tcx.resolutions(()).effective_visibilities.is_exported(def_id)
606    } else {
607        false
608    };
609
610    if let [only_impl] = &concrete_impls[..] {
611        let within = if externally_visible { " within this crate" } else { "" };
612        err.help(with_no_trimmed_paths!(format!(
613            "only type `{only_impl}` implements `{trait_str}`{within}; \
614            consider using it directly instead."
615        )));
616    } else {
617        let types = concrete_impls
618            .iter()
619            .map(|t| with_no_trimmed_paths!(format!("  {}", t)))
620            .collect::<Vec<String>>()
621            .join("\n");
622
623        err.help(format!(
624            "the following types implement `{trait_str}`:\n\
625             {types}\n\
626             consider defining an enum where each variant holds one of these types,\n\
627             implementing `{trait_str}` for this new enum and using it instead",
628        ));
629    }
630
631    if externally_visible {
632        err.note(format!(
633            "`{trait_str}` may be implemented in other crates; if you want to support your users \
634             passing their own types here, you can't refer to a specific type",
635        ));
636    }
637}
638
639/// Attempt to suggest that a `dyn Trait` argument or return type be converted
640/// to use `impl Trait`.
641fn attempt_dyn_to_impl_suggestion(tcx: TyCtxt<'_>, hir_id: Option<hir::HirId>, err: &mut Diag<'_>) {
642    let Some(hir_id) = hir_id else { return };
643    let hir::Node::Ty(ty) = tcx.hir_node(hir_id) else { return };
644    let hir::TyKind::TraitObject([trait_ref, ..], ..) = ty.kind else { return };
645
646    // Only suggest converting `dyn` to `impl` if we're in a function signature.
647    // This ensures that we don't suggest converting e.g.
648    //   `type Alias = Box<dyn DynIncompatibleTrait>;` to
649    //   `type Alias = Box<impl DynIncompatibleTrait>;`
650    let Some((_id, first_non_type_parent_node)) =
651        tcx.hir_parent_iter(hir_id).find(|(_id, node)| !matches!(node, hir::Node::Ty(_)))
652    else {
653        return;
654    };
655    if first_non_type_parent_node.fn_sig().is_none() {
656        return;
657    }
658
659    err.span_suggestion_verbose(
660        ty.span.until(trait_ref.span),
661        "consider using an opaque type instead",
662        "impl ",
663        Applicability::MaybeIncorrect,
664    );
665}