rustc_builtin_macros/deriving/
coerce_pointee.rs

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