Skip to main content

rustc_trait_selection/error_reporting/traits/
on_unimplemented.rs

1use std::path::PathBuf;
2
3use rustc_attr_ir::diagnostic::{CustomDiagnostic, FilterOptions, FormatArgs};
4use rustc_attr_ir::find_attr;
5use rustc_hir as hir;
6use rustc_hir::def_id::LocalDefId;
7use rustc_middle::ty::consts::ConstExt;
8use rustc_middle::ty::print::PrintTraitRefExt;
9use rustc_middle::ty::{self, GenericParamDef, GenericParamDefKind};
10use rustc_span::Symbol;
11
12use super::{ObligationCauseCode, PredicateObligation};
13use crate::error_reporting::TypeErrCtxt;
14
15impl<'tcx> TypeErrCtxt<'_, 'tcx> {
16    /// Used to set on_unimplemented's `ItemContext`
17    /// to be the enclosing (async) block/function/closure
18    fn describe_enclosure(&self, def_id: LocalDefId) -> Option<&'static str> {
19        match self.tcx.hir_node_by_def_id(def_id) {
20            hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { .. }, .. }) => Some("a function"),
21            hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. }) => {
22                Some("a trait method")
23            }
24            hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) => {
25                Some("a method")
26            }
27            hir::Node::Expr(hir::Expr {
28                kind: hir::ExprKind::Closure(hir::Closure { kind, .. }),
29                ..
30            }) => Some(self.describe_closure(*kind)),
31            _ => None,
32        }
33    }
34
35    pub fn on_unimplemented_note(
36        &self,
37        trait_pred: ty::PolyTraitClause<'tcx>,
38        obligation: &PredicateObligation<'tcx>,
39        long_ty_path: &mut Option<PathBuf>,
40    ) -> CustomDiagnostic {
41        if trait_pred.polarity() != ty::ClausePolarity::Positive {
42            return CustomDiagnostic::default();
43        }
44        // This is needed as `on_unimplemented` is currently not allowed on trait aliases,
45        // but the "not allowed" is a warning, and this check ensures the attribute has no effect
46        if self.tcx.is_trait_alias(trait_pred.def_id()) {
47            return CustomDiagnostic::default();
48        }
49        let (filter_options, format_args) =
50            self.on_unimplemented_components(trait_pred, obligation, long_ty_path, true);
51        if let Some(command) = {
    {
        'done:
            {
            for i in
                ::rustc_attr_ir::HasAttrs::get_attrs(trait_pred.def_id(),
                    &self.tcx) {
                #[allow(unused_imports)]
                use ::rustc_attr_ir::AttributeKind::*;
                let i: &::rustc_attr_ir::Attribute = i;
                match i {
                    ::rustc_attr_ir::Attribute::Parsed(OnUnimplemented {
                        directive, .. }) => {
                        break 'done Some(directive.as_deref());
                    }
                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(self.tcx, trait_pred.def_id(), OnUnimplemented {directive, ..} => directive.as_deref()).flatten() {
52            command.eval(
53                Some(&filter_options),
54                &format_args,
55            )
56        } else {
57            CustomDiagnostic::default()
58        }
59    }
60
61    pub(crate) fn on_unimplemented_components(
62        &self,
63        trait_pred: ty::PolyTraitClause<'tcx>,
64        obligation: &PredicateObligation<'tcx>,
65        long_ty_path: &mut Option<PathBuf>,
66        print_infer_ty_var: bool,
67    ) -> (FilterOptions, FormatArgs) {
68        let (def_id, args) = (trait_pred.def_id(), trait_pred.skip_binder().trait_ref.args);
69        let trait_pred = trait_pred.skip_binder();
70
71        let mut self_types = ::alloc::vec::Vec::new()vec![];
72        let mut generic_args: Vec<(Symbol, String)> = ::alloc::vec::Vec::new()vec![];
73        let mut crate_local = false;
74        // FIXME(-Zlower-impl-trait-in-trait-to-assoc-ty): HIR is not present for RPITITs,
75        // but I guess we could synthesize one here. We don't see any errors that rely on
76        // that yet, though.
77        let item_context = self.describe_enclosure(obligation.cause.body_def_id).unwrap_or("");
78
79        let direct = match obligation.cause.code() {
80            ObligationCauseCode::BuiltinDerived(..)
81            | ObligationCauseCode::ImplDerived(..)
82            | ObligationCauseCode::WellFormedDerived(..) => false,
83            _ => {
84                // this is a "direct", user-specified, rather than derived,
85                // obligation.
86                true
87            }
88        };
89
90        let from_desugaring = obligation.cause.span.desugaring_kind();
91
92        let cause = if let ObligationCauseCode::MainFunctionType = obligation.cause.code() {
93            Some("MainFunctionType".to_string())
94        } else {
95            None
96        };
97
98        // Add all types without trimmed paths or visible paths, ensuring they end up with
99        // their "canonical" def path.
100        {
    let _guard = NoTrimmedGuard::new();
    {
        let _guard = NoVisibleGuard::new();
        {
            let generics = self.tcx.generics_of(def_id);
            let self_ty = trait_pred.self_ty();
            self_types.push(self_ty.to_string());
            if let Some(def) = self_ty.ty_adt_def() {
                self_types.push(self.tcx.type_of(def.did()).instantiate_identity().skip_norm_wip().to_string());
            }
            for GenericParamDef { name, kind, index, .. } in
                generics.own_params.iter() {
                let value =
                    match kind {
                        GenericParamDefKind::Type { .. } |
                            GenericParamDefKind::Const { .. } => {
                            args[*index as usize].to_string()
                        }
                        GenericParamDefKind::Lifetime => continue,
                    };
                generic_args.push((*name, value));
                if let GenericParamDefKind::Type { .. } = kind {
                    let param_ty = args[*index as usize].expect_ty();
                    if let Some(def) = param_ty.ty_adt_def() {
                        generic_args.push((*name,
                                self.tcx.type_of(def.did()).instantiate_identity().skip_norm_wip().to_string()));
                    }
                }
            }
            if let Some(adt) = self_ty.ty_adt_def() {
                if adt.did().is_local() { crate_local = true; }
                self_types.push(::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("{{{0}}}", adt.descr()))
                        }))
            }
            if self_ty.is_integral() {
                self_types.push("{integral}".to_owned());
            }
            if self_ty.is_array_slice() { self_types.push("&[]".to_owned()); }
            if self_ty.is_fn() {
                let fn_sig = self_ty.fn_sig(self.tcx);
                let shortname =
                    if let ty::FnDef(def_id, _) = *self_ty.kind() &&
                            self.tcx.codegen_fn_attrs(def_id).safe_target_features {
                        "#[target_feature] fn"
                    } else {
                        match fn_sig.safety() {
                            hir::Safety::Safe => "fn",
                            hir::Safety::Unsafe => "unsafe fn",
                        }
                    };
                self_types.push(shortname.to_owned());
            }
            if let ty::Slice(aty) = self_ty.kind() {
                self_types.push("[]".to_owned());
                if let Some(def) = aty.ty_adt_def() {
                    self_types.push(::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("[{0}]",
                                        self.tcx.type_of(def.did()).instantiate_identity().skip_norm_wip()))
                            }));
                }
                if aty.is_integral() {
                    self_types.push("[{integral}]".to_string());
                }
            }
            if let ty::Array(aty, len) = self_ty.kind() {
                self_types.push("[]".to_string());
                let len = len.try_to_target_usize(self.tcx);
                self_types.push(::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("[{0}; _]", aty))
                        }));
                if let Some(n) = len {
                    self_types.push(::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("[{0}; {1}]", aty, n))
                            }));
                }
                if let Some(def) = aty.ty_adt_def() {
                    let def_ty =
                        self.tcx.type_of(def.did()).instantiate_identity().skip_norm_wip();
                    self_types.push(::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("[{0}; _]", def_ty))
                            }));
                    if let Some(n) = len {
                        self_types.push(::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("[{0}; {1}]", def_ty, n))
                                }));
                    }
                }
                if aty.is_integral() {
                    self_types.push("[{integral}; _]".to_string());
                    if let Some(n) = len {
                        self_types.push(::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("[{{integral}}; {0}]", n))
                                }));
                    }
                }
            }
            if let ty::Dynamic(traits, _) = self_ty.kind() {
                for t in traits.iter() {
                    if let ty::ExistentialPredicate::Trait(trait_ref) =
                            t.skip_binder() {
                        self_types.push(self.tcx.def_path_str(trait_ref.def_id));
                    }
                }
            }
            if let ty::Ref(_, ref_ty, rustc_ast::Mutability::Not) =
                            self_ty.kind() && let ty::Slice(sty) = ref_ty.kind() &&
                    sty.is_integral() {
                self_types.push("&[{integral}]".to_owned());
            }
        }
    }
};ty::print::with_no_trimmed_paths!(ty::print::with_no_visible_paths!({
101            let generics = self.tcx.generics_of(def_id);
102            let self_ty = trait_pred.self_ty();
103            self_types.push(self_ty.to_string());
104            if let Some(def) = self_ty.ty_adt_def() {
105                // We also want to be able to select self's original
106                // signature with no type arguments resolved
107                self_types.push(
108                    self.tcx.type_of(def.did()).instantiate_identity().skip_norm_wip().to_string(),
109                );
110            }
111
112            for GenericParamDef { name, kind, index, .. } in generics.own_params.iter() {
113                let value = match kind {
114                    GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => {
115                        args[*index as usize].to_string()
116                    }
117                    GenericParamDefKind::Lifetime => continue,
118                };
119                generic_args.push((*name, value));
120
121                if let GenericParamDefKind::Type { .. } = kind {
122                    let param_ty = args[*index as usize].expect_ty();
123                    if let Some(def) = param_ty.ty_adt_def() {
124                        // We also want to be able to select the parameter's
125                        // original signature with no type arguments resolved
126                        generic_args.push((
127                            *name,
128                            self.tcx
129                                .type_of(def.did())
130                                .instantiate_identity()
131                                .skip_norm_wip()
132                                .to_string(),
133                        ));
134                    }
135                }
136            }
137
138            if let Some(adt) = self_ty.ty_adt_def() {
139                if adt.did().is_local() {
140                    crate_local = true;
141                }
142                self_types.push(format!("{{{}}}", adt.descr()))
143            }
144
145            // Allow targeting all integers using `{integral}`, even if the exact type was resolved
146            if self_ty.is_integral() {
147                self_types.push("{integral}".to_owned());
148            }
149
150            if self_ty.is_array_slice() {
151                self_types.push("&[]".to_owned());
152            }
153
154            if self_ty.is_fn() {
155                let fn_sig = self_ty.fn_sig(self.tcx);
156                let shortname = if let ty::FnDef(def_id, _) = *self_ty.kind()
157                    && self.tcx.codegen_fn_attrs(def_id).safe_target_features
158                {
159                    "#[target_feature] fn"
160                } else {
161                    match fn_sig.safety() {
162                        hir::Safety::Safe => "fn",
163                        hir::Safety::Unsafe => "unsafe fn",
164                    }
165                };
166                self_types.push(shortname.to_owned());
167            }
168
169            // Slices give us `[]`, `[{ty}]`
170            if let ty::Slice(aty) = self_ty.kind() {
171                self_types.push("[]".to_owned());
172                if let Some(def) = aty.ty_adt_def() {
173                    // We also want to be able to select the slice's type's original
174                    // signature with no type arguments resolved
175                    self_types.push(format!(
176                        "[{}]",
177                        self.tcx.type_of(def.did()).instantiate_identity().skip_norm_wip()
178                    ));
179                }
180                if aty.is_integral() {
181                    self_types.push("[{integral}]".to_string());
182                }
183            }
184
185            // Arrays give us `[]`, `[{ty}; _]` and `[{ty}; N]`
186            if let ty::Array(aty, len) = self_ty.kind() {
187                self_types.push("[]".to_string());
188                let len = len.try_to_target_usize(self.tcx);
189                self_types.push(format!("[{aty}; _]"));
190                if let Some(n) = len {
191                    self_types.push(format!("[{aty}; {n}]"));
192                }
193                if let Some(def) = aty.ty_adt_def() {
194                    // We also want to be able to select the array's type's original
195                    // signature with no type arguments resolved
196                    let def_ty = self.tcx.type_of(def.did()).instantiate_identity().skip_norm_wip();
197                    self_types.push(format!("[{def_ty}; _]"));
198                    if let Some(n) = len {
199                        self_types.push(format!("[{def_ty}; {n}]"));
200                    }
201                }
202                if aty.is_integral() {
203                    self_types.push("[{integral}; _]".to_string());
204                    if let Some(n) = len {
205                        self_types.push(format!("[{{integral}}; {n}]"));
206                    }
207                }
208            }
209            if let ty::Dynamic(traits, _) = self_ty.kind() {
210                for t in traits.iter() {
211                    if let ty::ExistentialPredicate::Trait(trait_ref) = t.skip_binder() {
212                        self_types.push(self.tcx.def_path_str(trait_ref.def_id));
213                    }
214                }
215            }
216
217            // `&[{integral}]` - `FromIterator` needs that.
218            if let ty::Ref(_, ref_ty, rustc_ast::Mutability::Not) = self_ty.kind()
219                && let ty::Slice(sty) = ref_ty.kind()
220                && sty.is_integral()
221            {
222                self_types.push("&[{integral}]".to_owned());
223            }
224        }));
225
226        let this = self.tcx.def_path_str(trait_pred.trait_ref.def_id);
227        let this_resolved = trait_pred.trait_ref.print_trait_sugared().to_string();
228        let this_path =
229            ty::TraitRef::identity(self.tcx, def_id).print_only_trait_path().to_string();
230
231        let filter_options =
232            FilterOptions { self_types, from_desugaring, cause, crate_local, direct, generic_args };
233
234        // Unlike the generic_args earlier,
235        // this one is *not* collected under `with_no_trimmed_paths!`
236        // for printing the type to the user
237        //
238        // This includes `Self`, as it is the first parameter in `own_params`.
239        let generic_args = self
240            .tcx
241            .generics_of(trait_pred.trait_ref.def_id)
242            .own_params
243            .iter()
244            .filter_map(|param| {
245                let value = match param.kind {
246                    GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => {
247                        if let Some(ty) = trait_pred.trait_ref.args[param.index as usize].as_type()
248                        {
249                            if print_infer_ty_var == false
250                                && let ty::Infer(ty::TyVar(_)) = ty.kind()
251                            {
252                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}", param.name))
    })format!("{}", param.name)
253                            } else {
254                                self.tcx.short_string(ty, long_ty_path)
255                            }
256                        } else {
257                            trait_pred.trait_ref.args[param.index as usize].to_string()
258                        }
259                    }
260                    GenericParamDefKind::Lifetime => return None,
261                };
262                let name = param.name;
263                Some((name, value))
264            })
265            .collect();
266
267        let format_args =
268            FormatArgs { this, this_path, this_resolved, generic_args, item_context, .. };
269        (filter_options, format_args)
270    }
271}