1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
use rustc_hir as hir;
use rustc_infer::infer::TyCtxtInferExt;
use rustc_macros::{LintDiagnostic, Subdiagnostic};
use rustc_middle::ty::fold::BottomUpFolder;
use rustc_middle::ty::print::{PrintTraitPredicateExt as _, TraitPredPrintModifiersAndPath};
use rustc_middle::ty::{self, Ty, TypeFoldable};
use rustc_session::{declare_lint, declare_lint_pass};
use rustc_span::symbol::kw;
use rustc_span::Span;
use rustc_trait_selection::traits::{self, ObligationCtxt};

use crate::{LateContext, LateLintPass, LintContext};

declare_lint! {
    /// The `opaque_hidden_inferred_bound` lint detects cases in which nested
    /// `impl Trait` in associated type bounds are not written generally enough
    /// to satisfy the bounds of the associated type.
    ///
    /// ### Explanation
    ///
    /// This functionality was removed in #97346, but then rolled back in #99860
    /// because it caused regressions.
    ///
    /// We plan on reintroducing this as a hard error, but in the meantime,
    /// this lint serves to warn and suggest fixes for any use-cases which rely
    /// on this behavior.
    ///
    /// ### Example
    ///
    /// ```rust
    /// #![feature(type_alias_impl_trait)]
    ///
    /// trait Duh {}
    ///
    /// impl Duh for i32 {}
    ///
    /// trait Trait {
    ///     type Assoc: Duh;
    /// }
    ///
    /// impl<F: Duh> Trait for F {
    ///     type Assoc = F;
    /// }
    ///
    /// type Tait = impl Sized;
    ///
    /// fn test() -> impl Trait<Assoc = Tait> {
    ///     42
    /// }
    ///
    /// fn main() {}
    /// ```
    ///
    /// {{produces}}
    ///
    /// In this example, `test` declares that the associated type `Assoc` for
    /// `impl Trait` is `impl Sized`, which does not satisfy the bound `Duh`
    /// on the associated type.
    ///
    /// Although the hidden type, `i32` does satisfy this bound, we do not
    /// consider the return type to be well-formed with this lint. It can be
    /// fixed by changing `Tait = impl Sized` into `Tait = impl Sized + Duh`.
    pub OPAQUE_HIDDEN_INFERRED_BOUND,
    Warn,
    "detects the use of nested `impl Trait` types in associated type bounds that are not general enough"
}

declare_lint_pass!(OpaqueHiddenInferredBound => [OPAQUE_HIDDEN_INFERRED_BOUND]);

impl<'tcx> LateLintPass<'tcx> for OpaqueHiddenInferredBound {
    fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) {
        let hir::ItemKind::OpaqueTy(opaque) = &item.kind else {
            return;
        };
        let def_id = item.owner_id.def_id.to_def_id();
        let infcx = &cx.tcx.infer_ctxt().build();
        // For every projection predicate in the opaque type's explicit bounds,
        // check that the type that we're assigning actually satisfies the bounds
        // of the associated type.
        for (pred, pred_span) in cx.tcx.explicit_item_bounds(def_id).iter_identity_copied() {
            infcx.enter_forall(pred.kind(), |predicate| {
                let ty::ClauseKind::Projection(proj) = predicate else {
                    return;
                };
                // Only check types, since those are the only things that may
                // have opaques in them anyways.
                let Some(proj_term) = proj.term.as_type() else { return };

                // HACK: `impl Trait<Assoc = impl Trait2>` from an RPIT is "ok"...
                if let ty::Alias(ty::Opaque, opaque_ty) = *proj_term.kind()
                    && cx.tcx.parent(opaque_ty.def_id) == def_id
                    && matches!(
                        opaque.origin,
                        hir::OpaqueTyOrigin::FnReturn(_) | hir::OpaqueTyOrigin::AsyncFn(_)
                    )
                {
                    return;
                }

                // HACK: `async fn() -> Self` in traits is "ok"...
                // This is not really that great, but it's similar to why the `-> Self`
                // return type is well-formed in traits even when `Self` isn't sized.
                if let ty::Param(param_ty) = *proj_term.kind()
                    && param_ty.name == kw::SelfUpper
                    && matches!(opaque.origin, hir::OpaqueTyOrigin::AsyncFn(_))
                    && opaque.in_trait
                {
                    return;
                }

                let proj_ty = Ty::new_projection_from_args(
                    cx.tcx,
                    proj.projection_term.def_id,
                    proj.projection_term.args,
                );
                // For every instance of the projection type in the bounds,
                // replace them with the term we're assigning to the associated
                // type in our opaque type.
                let proj_replacer = &mut BottomUpFolder {
                    tcx: cx.tcx,
                    ty_op: |ty| if ty == proj_ty { proj_term } else { ty },
                    lt_op: |lt| lt,
                    ct_op: |ct| ct,
                };
                // For example, in `impl Trait<Assoc = impl Send>`, for all of the bounds on `Assoc`,
                // e.g. `type Assoc: OtherTrait`, replace `<impl Trait as Trait>::Assoc: OtherTrait`
                // with `impl Send: OtherTrait`.
                for (assoc_pred, assoc_pred_span) in cx
                    .tcx
                    .explicit_item_bounds(proj.projection_term.def_id)
                    .iter_instantiated_copied(cx.tcx, proj.projection_term.args)
                {
                    let assoc_pred = assoc_pred.fold_with(proj_replacer);

                    let ocx = ObligationCtxt::new(infcx);
                    let assoc_pred =
                        ocx.normalize(&traits::ObligationCause::dummy(), cx.param_env, assoc_pred);
                    if !ocx.select_all_or_error().is_empty() {
                        // Can't normalize for some reason...?
                        continue;
                    }

                    ocx.register_obligation(traits::Obligation::new(
                        cx.tcx,
                        traits::ObligationCause::dummy(),
                        cx.param_env,
                        assoc_pred,
                    ));

                    // If that predicate doesn't hold modulo regions (but passed during type-check),
                    // then we must've taken advantage of the hack in `project_and_unify_types` where
                    // we replace opaques with inference vars. Emit a warning!
                    if !ocx.select_all_or_error().is_empty() {
                        // If it's a trait bound and an opaque that doesn't satisfy it,
                        // then we can emit a suggestion to add the bound.
                        let add_bound = match (proj_term.kind(), assoc_pred.kind().skip_binder()) {
                            (
                                ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }),
                                ty::ClauseKind::Trait(trait_pred),
                            ) => Some(AddBound {
                                suggest_span: cx.tcx.def_span(*def_id).shrink_to_hi(),
                                trait_ref: trait_pred.print_modifiers_and_trait_path(),
                            }),
                            _ => None,
                        };

                        cx.emit_span_lint(
                            OPAQUE_HIDDEN_INFERRED_BOUND,
                            pred_span,
                            OpaqueHiddenInferredBoundLint {
                                ty: Ty::new_opaque(
                                    cx.tcx,
                                    def_id,
                                    ty::GenericArgs::identity_for_item(cx.tcx, def_id),
                                ),
                                proj_ty: proj_term,
                                assoc_pred_span,
                                add_bound,
                            },
                        );
                    }
                }
            });
        }
    }
}

#[derive(LintDiagnostic)]
#[diag(lint_opaque_hidden_inferred_bound)]
struct OpaqueHiddenInferredBoundLint<'tcx> {
    ty: Ty<'tcx>,
    proj_ty: Ty<'tcx>,
    #[label(lint_specifically)]
    assoc_pred_span: Span,
    #[subdiagnostic]
    add_bound: Option<AddBound<'tcx>>,
}

#[derive(Subdiagnostic)]
#[suggestion(
    lint_opaque_hidden_inferred_bound_sugg,
    style = "verbose",
    applicability = "machine-applicable",
    code = " + {trait_ref}"
)]
struct AddBound<'tcx> {
    #[primary_span]
    suggest_span: Span,
    #[skip_arg]
    trait_ref: TraitPredPrintModifiersAndPath<'tcx>,
}