Skip to main content

rustc_builtin_macros/deriving/
coerce_pointee.rs

1use ast::HasAttrs;
2use rustc_ast::mut_visit::MutVisitor;
3use rustc_ast::visit::{BoundKind, Visitor};
4use rustc_ast::{
5    self as ast, GenericArg, GenericBound, GenericParamKind, ItemKind, TraitBoundModifiers,
6    VariantData, WherePredicate,
7};
8use rustc_data_structures::flat_map_in_place::FlatMapInPlace;
9use rustc_errors::E0802;
10use rustc_expand::base::ExtCtxt;
11use rustc_macros::Diagnostic;
12use rustc_span::{Ident, Span, Symbol, sym};
13use thin_vec::{ThinVec, thin_vec};
14
15use crate::deriving::generic::*;
16use crate::deriving::path_std;
17use crate::diagnostics;
18use crate::util::generic_param_to_arg;
19
20pub(crate) fn expand_derive_coerce_pointee(
21    cx: &ExtCtxt<'_>,
22    span: Span,
23    item: &ast::Item,
24    push: &mut dyn FnMut(Box<ast::Item>),
25    _is_const: bool,
26) {
27    DetectNonGenericPointeeAttr { cx }.visit_item(item);
28
29    let (name_ident, generics) = if let ItemKind::Struct(ident, g, struct_data) = &item.kind {
30        if !#[allow(non_exhaustive_omitted_patterns)] match struct_data {
    VariantData::Struct { fields, recovered: _ } |
        VariantData::Tuple(fields, _) if !fields.is_empty() => true,
    _ => false,
}matches!(
31            struct_data,
32            VariantData::Struct { fields, recovered: _ } | VariantData::Tuple(fields, _)
33                if !fields.is_empty())
34        {
35            cx.dcx().emit_err(RequireOneField { span });
36            return;
37        }
38        (*ident, g)
39    } else {
40        cx.dcx().emit_err(RequireTransparent { span });
41        return;
42    };
43
44    // Convert generic parameters (from the struct) into generic args.
45    let self_params: Vec<_> =
46        generics.params.iter().map(|p| generic_param_to_arg(cx, p, p.span())).collect();
47    let type_params: Vec<_> = generics
48        .params
49        .iter()
50        .enumerate()
51        .filter_map(|(idx, p)| {
52            if let GenericParamKind::Type { .. } = p.kind {
53                Some((idx, p.span(), p.attrs().iter().any(|attr| attr.has_name(sym::pointee))))
54            } else {
55                None
56            }
57        })
58        .collect();
59
60    let pointee_param_idx = if type_params.is_empty() {
61        // `#[derive(CoercePointee)]` requires at least one generic type on the target `struct`
62        cx.dcx().emit_err(RequireOneGeneric { span });
63        return;
64    } else if type_params.len() == 1 {
65        // Regardless of the only type param being designed as `#[pointee]` or not, we can just use it as such
66        type_params[0].0
67    } else {
68        let mut pointees = type_params
69            .iter()
70            .filter_map(|&(idx, span, is_pointee)| is_pointee.then_some((idx, span)));
71        match (pointees.next(), pointees.next()) {
72            (Some((idx, _span)), None) => idx,
73            (None, _) => {
74                cx.dcx().emit_err(RequireOnePointee { span });
75                return;
76            }
77            (Some((_, one)), Some((_, another))) => {
78                cx.dcx().emit_err(TooManyPointees { one, another });
79                return;
80            }
81        }
82    };
83
84    // Create the type of `self`.
85    let path = cx.path_all(span, &[name_ident], self_params.clone());
86    let self_type = cx.ty_path(path);
87
88    // Declare helper function that adds implementation blocks.
89    // FIXME(dingxiangfei2009): Investigate the set of attributes on target struct to be propagated to impls
90    let attrs = {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(cx.generated_attr(span,
            ast::GeneratedAttr::AutomaticallyDerived));
    vec
}thin_vec![cx.generated_attr(span, ast::GeneratedAttr::AutomaticallyDerived)];
91    // # Validity assertion which will be checked later in `rustc_hir_analysis::coherence::builtins`.
92    {
93        let trait_path = cx.std_path(span, { &[sym::marker, sym::CoercePointeeValidated] })path_std!(cx, span, marker::CoercePointeeValidated);
94        push(cx.item_trait_impl(
95            span,
96            attrs.clone(),
97            generics_without_defaults(generics),
98            ast::Safety::Default,
99            false,
100            cx.trait_ref(trait_path),
101            self_type.clone(),
102            ThinVec::new(),
103        ));
104    }
105    let mut add_impl_block = |generics, trait_symbol, trait_args| {
106        let trait_path = cx.std_path_all(span, &[sym::ops, trait_symbol], trait_args);
107        let trait_ref = cx.trait_ref(trait_path);
108        let item = cx.item_trait_impl(
109            span,
110            attrs.clone(),
111            generics,
112            ast::Safety::Default,
113            false,
114            trait_ref,
115            self_type.clone(),
116            ThinVec::new(),
117        );
118        push(item);
119    };
120
121    // Create unsized `self`, that is, one where the `#[pointee]` type arg is replaced with `__S`. For
122    // example, instead of `MyType<'a, T>`, it will be `MyType<'a, __S>`.
123    let s_ty = cx.ty_name(span, sym::__S);
124    let mut alt_self_params = self_params;
125    alt_self_params[pointee_param_idx] = GenericArg::Type(s_ty.clone());
126    let alt_self_type = cx.ty_path(cx.path_all(span, &[name_ident], alt_self_params));
127
128    // # Add `Unsize<__S>` bound to `#[pointee]` at the generic parameter location
129    //
130    // Find the `#[pointee]` parameter and add an `Unsize<__S>` bound to it.
131    let mut impl_generics = generics.clone();
132    let pointee_ty_ident = generics.params[pointee_param_idx].ident;
133    let mut self_bounds;
134    {
135        let pointee = &mut impl_generics.params[pointee_param_idx];
136        self_bounds = pointee.bounds.clone();
137        if !contains_maybe_sized_bound(&self_bounds)
138            && !contains_maybe_sized_bound_on_pointee(
139                &generics.where_clause.predicates,
140                pointee_ty_ident.name,
141            )
142        {
143            cx.dcx().emit_err(RequiresMaybeSized {
144                span: pointee_ty_ident.span,
145                name: pointee_ty_ident,
146            });
147            return;
148        }
149        let arg = GenericArg::Type(s_ty.clone());
150        let unsize = cx.std_path_all(span, &[sym::marker, sym::Unsize], ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [arg]))vec![arg]);
151        pointee.bounds.push(cx.trait_bound(unsize, false));
152        // Drop `#[pointee]` attribute since it should not be recognized outside `derive(CoercePointee)`
153        pointee.attrs.retain(|attr| !attr.has_name(sym::pointee));
154    }
155
156    // # Rewrite generic parameter bounds
157    // For each bound `U: ..` in `struct<U: ..>`, make a new bound with `__S` in place of `#[pointee]`
158    // Example:
159    // ```
160    // struct<
161    //     U: Trait<T>,
162    //     #[pointee] T: Trait<T> + ?Sized,
163    //     V: Trait<T>> ...
164    // ```
165    // ... generates this `impl` generic parameters
166    // ```
167    // impl<
168    //     U: Trait<T> + Trait<__S>,
169    //     T: Trait<T> + ?Sized + Unsize<__S>, // (**)
170    //     __S: Trait<__S> + ?Sized, // (*)
171    //     V: Trait<T> + Trait<__S>> ...
172    // ```
173    // The new bound marked with (*) has to be done separately.
174    // See next section
175    for (idx, (params, orig_params)) in
176        impl_generics.params.iter_mut().zip(&generics.params).enumerate()
177    {
178        // Default type parameters are rejected for `impl` block.
179        // We should drop them now.
180        match &mut params.kind {
181            ast::GenericParamKind::Const { default, .. } => *default = None,
182            ast::GenericParamKind::Type { default } => *default = None,
183            ast::GenericParamKind::Lifetime => {}
184        }
185        // We CANNOT rewrite `#[pointee]` type parameter bounds.
186        // This has been set in stone. (**)
187        // So we skip over it.
188        // Otherwise, we push extra bounds involving `__S`.
189        if idx != pointee_param_idx {
190            for bound in &orig_params.bounds {
191                let mut bound = bound.clone();
192                let mut substitution = TypeSubstitution {
193                    from_name: pointee_ty_ident.name,
194                    to_ty: &s_ty,
195                    rewritten: false,
196                };
197                substitution.visit_param_bound(&mut bound, BoundKind::Bound);
198                if substitution.rewritten {
199                    // We found use of `#[pointee]` somewhere,
200                    // so we make a new bound using `__S` in place of `#[pointee]`
201                    params.bounds.push(bound);
202                }
203            }
204        }
205    }
206
207    // # Insert `__S` type parameter
208    //
209    // We now insert `__S` with the missing bounds marked with (*) above.
210    // We should also write the bounds from `#[pointee]` to `__S` as required by `Unsize<__S>`.
211    {
212        let mut substitution =
213            TypeSubstitution { from_name: pointee_ty_ident.name, to_ty: &s_ty, rewritten: false };
214        for bound in &mut self_bounds {
215            substitution.visit_param_bound(bound, BoundKind::Bound);
216        }
217    }
218
219    // # Rewrite `where` clauses
220    //
221    // Move on to `where` clauses.
222    // Example:
223    // ```
224    // struct MyPointer<#[pointee] T, ..>
225    // where
226    //   U: Trait<V> + Trait<T>,
227    //   Companion<T>: Trait<T>,
228    //   T: Trait<T> + ?Sized,
229    // { .. }
230    // ```
231    // ... will have a impl prelude like so
232    // ```
233    // impl<..> ..
234    // where
235    //   U: Trait<V> + Trait<T>,
236    //   U: Trait<__S>,
237    //   Companion<T>: Trait<T>,
238    //   Companion<__S>: Trait<__S>,
239    //   T: Trait<T> + ?Sized,
240    //   __S: Trait<__S> + ?Sized,
241    // ```
242    //
243    // We should also write a few new `where` bounds from `#[pointee] T` to `__S`
244    // as well as any bound that indirectly involves the `#[pointee] T` type.
245    for predicate in &generics.where_clause.predicates {
246        if let ast::WherePredicateKind::BoundPredicate(bound) = &predicate.kind {
247            let mut substitution = TypeSubstitution {
248                from_name: pointee_ty_ident.name,
249                to_ty: &s_ty,
250                rewritten: false,
251            };
252            let mut kind = ast::WherePredicateKind::BoundPredicate(bound.clone());
253            substitution.visit_where_predicate_kind(&mut kind);
254            if substitution.rewritten {
255                let predicate = ast::WherePredicate {
256                    attrs: predicate.attrs.clone(),
257                    kind,
258                    span: predicate.span,
259                    id: ast::DUMMY_NODE_ID,
260                    is_placeholder: false,
261                };
262                impl_generics.where_clause.predicates.push(predicate);
263            }
264        }
265    }
266
267    let extra_param = cx.typaram(Ident::new(sym::__S, span), self_bounds, None);
268    impl_generics.params.insert(pointee_param_idx + 1, extra_param);
269
270    // Add the impl blocks for `DispatchFromDyn` and `CoerceUnsized`.
271    let gen_args = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [ast::GenericArg::Type(alt_self_type)]))vec![ast::GenericArg::Type(alt_self_type)];
272    add_impl_block(impl_generics.clone(), sym::DispatchFromDyn, gen_args.clone());
273    add_impl_block(impl_generics, sym::CoerceUnsized, gen_args);
274}
275
276fn contains_maybe_sized_bound_on_pointee(predicates: &[WherePredicate], pointee: Symbol) -> bool {
277    for bound in predicates {
278        if let ast::WherePredicateKind::BoundPredicate(bound) = &bound.kind
279            && bound.bounded_ty.kind.is_simple_path().is_some_and(|name| name == pointee)
280        {
281            if contains_maybe_sized_bound(&bound.bounds) {
282                return true;
283            }
284        }
285    }
286    false
287}
288
289fn is_maybe_sized_bound(bound: &GenericBound) -> bool {
290    if let GenericBound::Trait(trait_ref) = bound
291        && let TraitBoundModifiers { polarity: ast::BoundPolarity::Maybe(_), .. } =
292            trait_ref.modifiers
293        && is_sized_marker(&trait_ref.trait_ref.path)
294    {
295        true
296    } else {
297        false
298    }
299}
300
301fn contains_maybe_sized_bound(bounds: &[GenericBound]) -> bool {
302    bounds.iter().any(is_maybe_sized_bound)
303}
304
305fn is_sized_marker(path: &ast::Path) -> bool {
306    const CORE_UNSIZE: [Symbol; 3] = [sym::core, sym::marker, sym::Sized];
307    const STD_UNSIZE: [Symbol; 3] = [sym::std, sym::marker, sym::Sized];
308    let segments = || path.segments.iter().map(|segment| segment.ident.name);
309    if path.is_global() {
310        segments().skip(1).eq(CORE_UNSIZE) || segments().skip(1).eq(STD_UNSIZE)
311    } else {
312        segments().eq(CORE_UNSIZE) || segments().eq(STD_UNSIZE) || *path == sym::Sized
313    }
314}
315
316struct TypeSubstitution<'a> {
317    from_name: Symbol,
318    to_ty: &'a ast::Ty,
319    rewritten: bool,
320}
321
322impl<'a> ast::mut_visit::MutVisitor for TypeSubstitution<'a> {
323    fn visit_ty(&mut self, ty: &mut ast::Ty) {
324        if let Some(name) = ty.kind.is_simple_path()
325            && name == self.from_name
326        {
327            *ty = self.to_ty.clone();
328            self.rewritten = true;
329        } else {
330            ast::mut_visit::walk_ty(self, ty);
331        }
332    }
333
334    fn visit_where_predicate_kind(&mut self, kind: &mut ast::WherePredicateKind) {
335        match kind {
336            rustc_ast::WherePredicateKind::BoundPredicate(bound) => {
337                bound
338                    .bound_generic_params
339                    .flat_map_in_place(|param| self.flat_map_generic_param(param));
340                self.visit_ty(&mut bound.bounded_ty);
341                for bound in &mut bound.bounds {
342                    self.visit_param_bound(bound, BoundKind::Bound)
343                }
344            }
345            rustc_ast::WherePredicateKind::RegionPredicate(_) => {}
346        }
347    }
348}
349
350struct DetectNonGenericPointeeAttr<'a, 'b> {
351    cx: &'a ExtCtxt<'b>,
352}
353
354impl<'a, 'b> rustc_ast::visit::Visitor<'a> for DetectNonGenericPointeeAttr<'a, 'b> {
355    fn visit_attribute(&mut self, attr: &'a rustc_ast::Attribute) -> Self::Result {
356        if attr.has_name(sym::pointee) {
357            self.cx.dcx().emit_err(diagnostics::NonGenericPointee { span: attr.span });
358        }
359    }
360
361    fn visit_generic_param(&mut self, param: &'a rustc_ast::GenericParam) -> Self::Result {
362        let mut error_on_pointee = AlwaysErrorOnGenericParam { cx: self.cx };
363
364        match &param.kind {
365            GenericParamKind::Type { default } => {
366                // The `default` may end up containing a block expression.
367                // The problem is block expressions  may define structs with generics.
368                // A user may attach a #[pointee] attribute to one of these generics
369                // We want to catch that. The simple solution is to just
370                // always raise a `NonGenericPointee` error when this happens.
371                //
372                // This solution does reject valid rust programs but,
373                // such a code would have to, in order:
374                // - Define a smart pointer struct.
375                // - Somewhere in this struct definition use a type with a const generic argument.
376                // - Calculate this const generic in a expression block.
377                // - Define a new smart pointer type in this block.
378                // - Have this smart pointer type have more than 1 generic type.
379                // In this case, the inner smart pointer derive would be complaining that it
380                // needs a pointer attribute. Meanwhile, the outer macro would be complaining
381                // that we attached a #[pointee] to a generic type argument while helpfully
382                // informing the user that #[pointee] can only be attached to generic pointer arguments
383                if let Some(x) = default {
    match ::rustc_ast_ir::visit::VisitorResult::branch(error_on_pointee.visit_ty(x))
        {
        core::ops::ControlFlow::Continue(()) =>
            (),
            #[allow(unreachable_code)]
            core::ops::ControlFlow::Break(r) => {
            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
        }
    };
};rustc_ast::visit::visit_opt!(error_on_pointee, visit_ty, default);
384            }
385
386            GenericParamKind::Const { .. } | GenericParamKind::Lifetime => {
387                rustc_ast::visit::walk_generic_param(&mut error_on_pointee, param);
388            }
389        }
390    }
391
392    fn visit_ty(&mut self, t: &'a rustc_ast::Ty) -> Self::Result {
393        let mut error_on_pointee = AlwaysErrorOnGenericParam { cx: self.cx };
394        error_on_pointee.visit_ty(t)
395    }
396}
397
398struct AlwaysErrorOnGenericParam<'a, 'b> {
399    cx: &'a ExtCtxt<'b>,
400}
401
402impl<'a, 'b> rustc_ast::visit::Visitor<'a> for AlwaysErrorOnGenericParam<'a, 'b> {
403    fn visit_attribute(&mut self, attr: &'a rustc_ast::Attribute) -> Self::Result {
404        if attr.has_name(sym::pointee) {
405            self.cx.dcx().emit_err(diagnostics::NonGenericPointee { span: attr.span });
406        }
407    }
408}
409
410#[derive(const _: () =
    {
        impl<'_sess> rustc_errors::Diagnostic<'_sess> for RequireTransparent {
            #[track_caller]
            fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
                level: rustc_errors::Level) -> rustc_errors::Diag<'_sess> {
                match self {
                    RequireTransparent { span: __binding_0 } => {
                        let mut diag =
                            rustc_errors::Diag::new(dcx, level,
                                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`CoercePointee` can only be derived on `struct`s with `#[repr(transparent)]`")));
                        diag.code(E0802);
                        ;
                        diag.span(__binding_0);
                        diag
                    }
                }
            }
        }
    };Diagnostic)]
411#[diag("`CoercePointee` can only be derived on `struct`s with `#[repr(transparent)]`", code = E0802)]
412struct RequireTransparent {
413    #[primary_span]
414    span: Span,
415}
416
417#[derive(const _: () =
    {
        impl<'_sess> rustc_errors::Diagnostic<'_sess> for RequireOneField {
            #[track_caller]
            fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
                level: rustc_errors::Level) -> rustc_errors::Diag<'_sess> {
                match self {
                    RequireOneField { span: __binding_0 } => {
                        let mut diag =
                            rustc_errors::Diag::new(dcx, level,
                                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`CoercePointee` can only be derived on `struct`s with at least one field")));
                        diag.code(E0802);
                        ;
                        diag.span(__binding_0);
                        diag
                    }
                }
            }
        }
    };Diagnostic)]
418#[diag("`CoercePointee` can only be derived on `struct`s with at least one field", code = E0802)]
419struct RequireOneField {
420    #[primary_span]
421    span: Span,
422}
423
424#[derive(const _: () =
    {
        impl<'_sess> rustc_errors::Diagnostic<'_sess> for RequireOneGeneric {
            #[track_caller]
            fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
                level: rustc_errors::Level) -> rustc_errors::Diag<'_sess> {
                match self {
                    RequireOneGeneric { span: __binding_0 } => {
                        let mut diag =
                            rustc_errors::Diag::new(dcx, level,
                                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`CoercePointee` can only be derived on `struct`s that are generic over at least one type")));
                        diag.code(E0802);
                        ;
                        diag.span(__binding_0);
                        diag
                    }
                }
            }
        }
    };Diagnostic)]
425#[diag("`CoercePointee` can only be derived on `struct`s that are generic over at least one type", code = E0802)]
426struct RequireOneGeneric {
427    #[primary_span]
428    span: Span,
429}
430
431#[derive(const _: () =
    {
        impl<'_sess> rustc_errors::Diagnostic<'_sess> for RequireOnePointee {
            #[track_caller]
            fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
                level: rustc_errors::Level) -> rustc_errors::Diag<'_sess> {
                match self {
                    RequireOnePointee { span: __binding_0 } => {
                        let mut diag =
                            rustc_errors::Diag::new(dcx, level,
                                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("exactly one generic type parameter must be marked as `#[pointee]` to derive `CoercePointee` traits")));
                        diag.code(E0802);
                        ;
                        diag.span(__binding_0);
                        diag
                    }
                }
            }
        }
    };Diagnostic)]
432#[diag("exactly one generic type parameter must be marked as `#[pointee]` to derive `CoercePointee` traits", code = E0802)]
433struct RequireOnePointee {
434    #[primary_span]
435    span: Span,
436}
437
438#[derive(const _: () =
    {
        impl<'_sess> rustc_errors::Diagnostic<'_sess> for TooManyPointees {
            #[track_caller]
            fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
                level: rustc_errors::Level) -> rustc_errors::Diag<'_sess> {
                match self {
                    TooManyPointees { one: __binding_0, another: __binding_1 }
                        => {
                        let mut diag =
                            rustc_errors::Diag::new(dcx, level,
                                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("only one type parameter can be marked as `#[pointee]` when deriving `CoercePointee` traits")));
                        diag.code(E0802);
                        ;
                        diag.span(__binding_0);
                        diag.span_label(__binding_1,
                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("here another type parameter is marked as `#[pointee]`")));
                        diag
                    }
                }
            }
        }
    };Diagnostic)]
439#[diag("only one type parameter can be marked as `#[pointee]` when deriving `CoercePointee` traits", code = E0802)]
440struct TooManyPointees {
441    #[primary_span]
442    one: Span,
443    #[label("here another type parameter is marked as `#[pointee]`")]
444    another: Span,
445}
446
447#[derive(const _: () =
    {
        impl<'_sess> rustc_errors::Diagnostic<'_sess> for RequiresMaybeSized {
            #[track_caller]
            fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
                level: rustc_errors::Level) -> rustc_errors::Diag<'_sess> {
                match self {
                    RequiresMaybeSized { span: __binding_0, name: __binding_1 }
                        => {
                        let mut diag =
                            rustc_errors::Diag::new(dcx, level,
                                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`derive(CoercePointee)` requires `{$name}` to be marked `?Sized`")));
                        diag.code(E0802);
                        ;
                        diag.arg("name", __binding_1);
                        diag.span(__binding_0);
                        diag
                    }
                }
            }
        }
    };Diagnostic)]
448#[diag("`derive(CoercePointee)` requires `{$name}` to be marked `?Sized`", code = E0802)]
449struct RequiresMaybeSized {
450    #[primary_span]
451    span: Span,
452    name: Ident,
453}