Debian Codegraph @

debian/rust-vendor/zerocopy-derive/src/util.rs

raw
1 // SPDX-License-Identifier: BSD-2-Clause OR Apache-2.0 OR MIT
2 //
3 // Copyright 2019 The Fuchsia Authors
4 //
5 // Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
6 // <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
7 // license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
8 // This file may not be copied, modified, or distributed except according to
9 // those terms.
10
11 use std::num::NonZeroU32;
12
13 use proc_macro2::{Span, TokenStream};
14 use quote::{quote, quote_spanned, ToTokens};
15 use syn::{
16 parse::ParseBuffer, parse_quote, spanned::Spanned as _, token::PathSep, Data, DataEnum,
17 DataStruct, DataUnion, DeriveInput, Error, Expr, ExprLit, Field, GenericParam, Ident, Index,
18 Lit, LitStr, Meta, Path, Type, Variant, Visibility, WherePredicate,
19 };
20
21 use crate::repr::{CompoundRepr, EnumRepr, PrimitiveRepr, Repr, Spanned};
22
23 pub(crate) struct Ctx {
24 pub(crate) ast: DeriveInput,
25 pub(crate) zerocopy_crate: Path,
26
27 // The value of the last `#[zerocopy(on_error = ...)]` attribute, or `false`
28 // if none is provided.
29 pub(crate) skip_on_error: bool,
30
31 // The span of the last `#[zerocopy(on_error = ...)]` attribute, if any.
32 pub(crate) on_error_span: Option<proc_macro2::Span>,
33 }
34
35 #[derive(Eq, PartialEq)]
36 enum CratePath {
37 External,
38 CrateRelative,
39 ModuleRelative,
40 }
41
42 fn validate_crate_path(path: &Path) -> Result<CratePath, ()> {
43 if path.segments.is_empty() {
44 return Err(());
45 }
46
47 enum ModuleRelative {
48 Yes,
49 No,
50 }
51 let first = path.segments[0].ident.to_string();
52 let (mut prev_segment, path_type) = match first.as_str() {
53 "Self" => return Err(()),
54 "crate" => {
55 if path.leading_colon.is_some() {
56 return Err(());
57 }
58 (ModuleRelative::No, CratePath::CrateRelative)
59 }
60 "self" | "super" => {
61 if path.leading_colon.is_some() {
62 return Err(());
63 }
64 (ModuleRelative::Yes, CratePath::ModuleRelative)
65 }
66 _ => (ModuleRelative::No, CratePath::External),
67 };
68
69 for seg in path.segments.iter().skip(1) {
70 let ident = seg.ident.to_string();
71 match ident.as_str() {
72 "Self" | "crate" | "self" => return Err(()),
73 "super" => match prev_segment {
74 ModuleRelative::Yes => {}
75 ModuleRelative::No => return Err(()),
76 },
77 _ => {
78 prev_segment = ModuleRelative::No;
79 }
80 }
81 }
82 Ok(path_type)
83 }
84
85 impl Ctx {
86 /// Attempt to extract a crate path from the provided attributes. Defaults to
87 /// `::zerocopy` if not found.
88 pub(crate) fn try_from_derive_input(ast: DeriveInput) -> Result<Self, Error> {
89 let mut path = parse_quote!(::zerocopy);
90 let mut skip_on_error = false;
91 let mut on_error_span = None;
92
93 for attr in &ast.attrs {
94 if let Meta::List(ref meta_list) = attr.meta {
95 if meta_list.path.is_ident("zerocopy") {
96 attr.parse_nested_meta(|meta| {
97 if meta.path.is_ident("crate") {
98 let expr = meta.value().and_then(ParseBuffer::parse);
99 if let Ok(Expr::Lit(ExprLit { lit: Lit::Str(lit), .. })) = expr {
100 if let Ok(mut path_lit) = lit.parse_with(Path::parse_mod_style) {
101 if let Ok(crate_path) = validate_crate_path(&path_lit) {
102 // If not expressly relative, absolutize.
103 if path_lit.leading_colon.is_none() && crate_path == CratePath::External {
104 path_lit.leading_colon = Some(PathSep::default());
105 }
106 path = path_lit;
107 return Ok(());
108 }
109
110 return Err(Error::new(
111 lit.span(),
112 "`crate` attribute requires a valid module path",
113 ));
114 }
115
116 return Err(Error::new(
117 lit.span(),
118 "`crate` attribute requires a path as the value",
119 ));
120 }
121
122 return Err(Error::new(
123 meta.path.span(),
124 "`crate` attribute requires a path as the value",
125 ));
126 }
127
128 if meta.path.is_ident("on_error") {
129 on_error_span = Some(meta.path.span());
130 let value = meta.value()?;
131 let s: LitStr = value.parse()?;
132 match s.value().as_str() {
133 "skip" => skip_on_error = true,
134 "fail" => skip_on_error = false,
135 _ => return Err(Error::new(
136 s.span(),
137 "unrecognized value for `on_error` attribute from `zerocopy`; expected `skip` or `fail`",
138 )),
139 }
140 return Ok(());
141 }
142
143 Err(Error::new(
144 Span::call_site(),
145 format!(
146 "unknown attribute encountered: {}",
147 meta.path.into_token_stream()
148 ),
149 ))
150 })?;
151 }
152 }
153 }
154
155 Ok(Self { ast, zerocopy_crate: path, skip_on_error, on_error_span })
156 }
157
158 pub(crate) fn with_input(&self, input: &DeriveInput) -> Self {
159 Self {
160 ast: input.clone(),
161 zerocopy_crate: self.zerocopy_crate.clone(),
162 skip_on_error: self.skip_on_error,
163 on_error_span: self.on_error_span,
164 }
165 }
166
167 pub(crate) fn skip_on_error(mut self) -> Self {
168 self.skip_on_error = true;
169 self
170 }
171
172 pub(crate) fn core_path(&self) -> TokenStream {
173 let zerocopy_crate = &self.zerocopy_crate;
174 quote!(#zerocopy_crate::util::macro_util::core_reexport)
175 }
176
177 pub(crate) fn cfg_compile_error(&self) -> TokenStream {
178 // By checking both during the compilation of the proc macro *and* in
179 // the generated code, we ensure that `--cfg
180 // zerocopy_unstable_linux` need only be passed *either* when
181 // compiling this crate *or* when compiling the user's crate. The former
182 // is preferable, but in some situations (such as when cross-compiling
183 // using `cargo build --target`), it doesn't get propagated to this
184 // crate's build by default.
185 if cfg!(zerocopy_unstable_linux) {
186 quote!()
187 } else if let Some(span) = self.on_error_span {
188 let core = self.core_path();
189 let error_message =
190 "`on_error` is experimental; pass '--cfg zerocopy_unstable_linux' to enable";
191 quote::quote_spanned! {span=>
192 #[allow(unused_attributes, unexpected_cfgs)]
193 const _: () = {
194 #[cfg(not(zerocopy_unstable_linux))]
195 #core::compile_error!(#error_message);
196 };
197 }
198 } else {
199 quote!()
200 }
201 }
202
203 pub(crate) fn error_or_skip<E>(&self, error: E) -> Result<TokenStream, E> {
204 if self.skip_on_error {
205 Ok(self.cfg_compile_error())
206 } else {
207 Err(error)
208 }
209 }
210 }
211
212 pub(crate) trait DataExt {
213 /// Extracts the names and types of all fields. For enums, extracts the
214 /// names and types of fields from each variant. For tuple structs, the
215 /// names are the indices used to index into the struct (ie, `0`, `1`, etc).
216 ///
217 /// FIXME: Extracting field names for enums doesn't really make sense. Types
218 /// makes sense because we don't care about where they live - we just care
219 /// about transitive ownership. But for field names, we'd only use them when
220 /// generating is_bit_valid, which cares about where they live.
221 fn fields(&self) -> Vec<(&Visibility, TokenStream, &Type)>;
222
223 fn variants(&self) -> Vec<(Option<&Variant>, Vec<(&Visibility, TokenStream, &Type)>)>;
224
225 fn tag(&self) -> Option<Ident>;
226 }
227
228 impl DataExt for Data {
229 fn fields(&self) -> Vec<(&Visibility, TokenStream, &Type)> {
230 match self {
231 Data::Struct(strc) => strc.fields(),
232 Data::Enum(enm) => enm.fields(),
233 Data::Union(un) => un.fields(),
234 }
235 }
236
237 fn variants(&self) -> Vec<(Option<&Variant>, Vec<(&Visibility, TokenStream, &Type)>)> {
238 match self {
239 Data::Struct(strc) => strc.variants(),
240 Data::Enum(enm) => enm.variants(),
241 Data::Union(un) => un.variants(),
242 }
243 }
244
245 fn tag(&self) -> Option<Ident> {
246 match self {
247 Data::Struct(strc) => strc.tag(),
248 Data::Enum(enm) => enm.tag(),
249 Data::Union(un) => un.tag(),
250 }
251 }
252 }
253
254 impl DataExt for DataStruct {
255 fn fields(&self) -> Vec<(&Visibility, TokenStream, &Type)> {
256 map_fields(&self.fields)
257 }
258
259 fn variants(&self) -> Vec<(Option<&Variant>, Vec<(&Visibility, TokenStream, &Type)>)> {
260 vec![(None, self.fields())]
261 }
262
263 fn tag(&self) -> Option<Ident> {
264 None
265 }
266 }
267
268 impl DataExt for DataEnum {
269 fn fields(&self) -> Vec<(&Visibility, TokenStream, &Type)> {
270 map_fields(self.variants.iter().flat_map(|var| &var.fields))
271 }
272
273 fn variants(&self) -> Vec<(Option<&Variant>, Vec<(&Visibility, TokenStream, &Type)>)> {
274 self.variants.iter().map(|var| (Some(var), map_fields(&var.fields))).collect()
275 }
276
277 fn tag(&self) -> Option<Ident> {
278 Some(Ident::new("___ZerocopyTag", Span::call_site()))
279 }
280 }
281
282 impl DataExt for DataUnion {
283 fn fields(&self) -> Vec<(&Visibility, TokenStream, &Type)> {
284 map_fields(&self.fields.named)
285 }
286
287 fn variants(&self) -> Vec<(Option<&Variant>, Vec<(&Visibility, TokenStream, &Type)>)> {
288 vec![(None, self.fields())]
289 }
290
291 fn tag(&self) -> Option<Ident> {
292 None
293 }
294 }
295
296 fn map_fields<'a>(
297 fields: impl 'a + IntoIterator<Item = &'a Field>,
298 ) -> Vec<(&'a Visibility, TokenStream, &'a Type)> {
299 fields
300 .into_iter()
301 .enumerate()
302 .map(|(idx, f)| {
303 (
304 &f.vis,
305 f.ident
306 .as_ref()
307 .map(ToTokens::to_token_stream)
308 .unwrap_or_else(|| Index::from(idx).to_token_stream()),
309 &f.ty,
310 )
311 })
312 .collect()
313 }
314
315 pub(crate) fn to_ident_str(t: &impl ToString) -> String {
316 let s = t.to_string();
317 if let Some(stripped) = s.strip_prefix("r#") {
318 stripped.to_string()
319 } else {
320 s
321 }
322 }
323
324 /// This enum describes what kind of padding check needs to be generated for the
325 /// associated impl.
326 pub(crate) enum PaddingCheck {
327 /// Check that the sum of the fields' sizes exactly equals the struct's
328 /// size.
329 Struct,
330 /// Check that a `repr(C)` struct has no padding.
331 ReprCStruct,
332 /// Check that the size of each field exactly equals the union's size.
333 Union,
334 /// Check that every variant of the enum contains no padding.
335 ///
336 /// Because doing so requires a tag enum, this padding check requires an
337 /// additional `TokenStream` which defines the tag enum as `___ZerocopyTag`.
338 Enum { tag_type_definition: TokenStream },
339 }
340
341 impl PaddingCheck {
342 /// Returns the idents of the trait to use and the macro to call in order to
343 /// validate that a type passes the relevant padding check.
344 pub(crate) fn validator_trait_and_macro_idents(&self) -> (Ident, Ident) {
345 let (trt, mcro) = match self {
346 PaddingCheck::Struct => ("PaddingFree", "struct_padding"),
347 PaddingCheck::ReprCStruct => ("DynamicPaddingFree", "repr_c_struct_has_padding"),
348 PaddingCheck::Union => ("PaddingFree", "union_padding"),
349 PaddingCheck::Enum { .. } => ("PaddingFree", "enum_padding"),
350 };
351
352 let trt = Ident::new(trt, Span::call_site());
353 let mcro = Ident::new(mcro, Span::call_site());
354 (trt, mcro)
355 }
356
357 /// Sometimes performing the padding check requires some additional
358 /// "context" code. For enums, this is the definition of the tag enum.
359 pub(crate) fn validator_macro_context(&self) -> Option<&TokenStream> {
360 match self {
361 PaddingCheck::Struct | PaddingCheck::ReprCStruct | PaddingCheck::Union => None,
362 PaddingCheck::Enum { tag_type_definition } => Some(tag_type_definition),
363 }
364 }
365 }
366
367 #[derive(Clone)]
368 pub(crate) enum Trait {
369 KnownLayout,
370 HasTag,
371 HasField {
372 variant_id: Box<Expr>,
373 field: Box<Type>,
374 field_id: Box<Expr>,
375 },
376 ProjectField {
377 variant_id: Box<Expr>,
378 field: Box<Type>,
379 field_id: Box<Expr>,
380 invariants: Box<Type>,
381 },
382 Immutable,
383 TryFromBytes,
384 FromZeros,
385 FromBytes,
386 IntoBytes,
387 Unaligned,
388 Sized,
389 ByteHash,
390 ByteEq,
391 SplitAt,
392 }
393
394 impl ToTokens for Trait {
395 fn to_tokens(&self, tokens: &mut TokenStream) {
396 // According to [1], the format of the derived `Debug`` output is not
397 // stable and therefore not guaranteed to represent the variant names.
398 // Indeed with the (unstable) `fmt-debug` compiler flag [2], it can
399 // return only a minimalized output or empty string. To make sure this
400 // code will work in the future and independent of the compiler flag, we
401 // translate the variants to their names manually here.
402 //
403 // [1] https://doc.rust-lang.org/1.81.0/std/fmt/trait.Debug.html#stability
404 // [2] https://doc.rust-lang.org/beta/unstable-book/compiler-flags/fmt-debug.html
405 let s = match self {
406 Trait::HasField { .. } => "HasField",
407 Trait::ProjectField { .. } => "ProjectField",
408 Trait::KnownLayout => "KnownLayout",
409 Trait::HasTag => "HasTag",
410 Trait::Immutable => "Immutable",
411 Trait::TryFromBytes => "TryFromBytes",
412 Trait::FromZeros => "FromZeros",
413 Trait::FromBytes => "FromBytes",
414 Trait::IntoBytes => "IntoBytes",
415 Trait::Unaligned => "Unaligned",
416 Trait::Sized => "Sized",
417 Trait::ByteHash => "ByteHash",
418 Trait::ByteEq => "ByteEq",
419 Trait::SplitAt => "SplitAt",
420 };
421 let ident = Ident::new(s, Span::call_site());
422 let arguments: Option<syn::AngleBracketedGenericArguments> = match self {
423 Trait::HasField { variant_id, field, field_id } => {
424 Some(parse_quote!(<#field, #variant_id, #field_id>))
425 }
426 Trait::ProjectField { variant_id, field, field_id, invariants } => {
427 Some(parse_quote!(<#field, #invariants, #variant_id, #field_id>))
428 }
429 Trait::KnownLayout
430 | Trait::HasTag
431 | Trait::Immutable
432 | Trait::TryFromBytes
433 | Trait::FromZeros
434 | Trait::FromBytes
435 | Trait::IntoBytes
436 | Trait::Unaligned
437 | Trait::Sized
438 | Trait::ByteHash
439 | Trait::ByteEq
440 | Trait::SplitAt => None,
441 };
442 tokens.extend(quote!(#ident #arguments));
443 }
444 }
445
446 impl Trait {
447 pub(crate) fn crate_path(&self, ctx: &Ctx) -> Path {
448 let zerocopy_crate = &ctx.zerocopy_crate;
449 let core = ctx.core_path();
450 match self {
451 Self::Sized => parse_quote!(#core::marker::#self),
452 _ => parse_quote!(#zerocopy_crate::#self),
453 }
454 }
455 }
456
457 pub(crate) enum TraitBound {
458 Slf,
459 Other(Trait),
460 }
461
462 pub(crate) enum FieldBounds<'a> {
463 None,
464 All(&'a [TraitBound]),
465 Trailing(&'a [TraitBound]),
466 Explicit(Vec<WherePredicate>),
467 }
468
469 impl<'a> FieldBounds<'a> {
470 pub(crate) const ALL_SELF: FieldBounds<'a> = FieldBounds::All(&[TraitBound::Slf]);
471 pub(crate) const TRAILING_SELF: FieldBounds<'a> = FieldBounds::Trailing(&[TraitBound::Slf]);
472 }
473
474 pub(crate) enum SelfBounds<'a> {
475 None,
476 All(&'a [Trait]),
477 }
478
479 // FIXME(https://github.com/rust-lang/rust-clippy/issues/12908): This is a false
480 // positive. Explicit lifetimes are actually necessary here.
481 #[allow(clippy::needless_lifetimes)]
482 impl<'a> SelfBounds<'a> {
483 pub(crate) const SIZED: Self = Self::All(&[Trait::Sized]);
484 }
485
486 /// Normalizes a slice of bounds by replacing [`TraitBound::Slf`] with `slf`.
487 pub(crate) fn normalize_bounds<'a>(
488 slf: &'a Trait,
489 bounds: &'a [TraitBound],
490 ) -> impl 'a + Iterator<Item = Trait> {
491 bounds.iter().map(move |bound| match bound {
492 TraitBound::Slf => slf.clone(),
493 TraitBound::Other(trt) => trt.clone(),
494 })
495 }
496
497 pub(crate) struct ImplBlockBuilder<'a> {
498 ctx: &'a Ctx,
499 data: &'a dyn DataExt,
500 trt: Trait,
501 field_type_trait_bounds: FieldBounds<'a>,
502 self_type_trait_bounds: SelfBounds<'a>,
503 padding_check: Option<PaddingCheck>,
504 param_extras: Vec<GenericParam>,
505 inner_extras: Option<TokenStream>,
506 outer_extras: Option<TokenStream>,
507 }
508
509 impl<'a> ImplBlockBuilder<'a> {
510 pub(crate) fn new(
511 ctx: &'a Ctx,
512 data: &'a dyn DataExt,
513 trt: Trait,
514 field_type_trait_bounds: FieldBounds<'a>,
515 ) -> Self {
516 Self {
517 ctx,
518 data,
519 trt,
520 field_type_trait_bounds,
521 self_type_trait_bounds: SelfBounds::None,
522 padding_check: None,
523 param_extras: Vec::new(),
524 inner_extras: None,
525 outer_extras: None,
526 }
527 }
528
529 pub(crate) fn self_type_trait_bounds(mut self, self_type_trait_bounds: SelfBounds<'a>) -> Self {
530 self.self_type_trait_bounds = self_type_trait_bounds;
531 self
532 }
533
534 pub(crate) fn padding_check<P: Into<Option<PaddingCheck>>>(mut self, padding_check: P) -> Self {
535 self.padding_check = padding_check.into();
536 self
537 }
538
539 pub(crate) fn param_extras(mut self, param_extras: Vec<GenericParam>) -> Self {
540 self.param_extras.extend(param_extras);
541 self
542 }
543
544 pub(crate) fn inner_extras(mut self, inner_extras: TokenStream) -> Self {
545 self.inner_extras = Some(inner_extras);
546 self
547 }
548
549 pub(crate) fn outer_extras<T: Into<Option<TokenStream>>>(mut self, outer_extras: T) -> Self {
550 self.outer_extras = outer_extras.into();
551 self
552 }
553
554 pub(crate) fn build(self) -> TokenStream {
555 // In this documentation, we will refer to this hypothetical struct:
556 //
557 // #[derive(FromBytes)]
558 // struct Foo<T, I: Iterator>
559 // where
560 // T: Copy,
561 // I: Clone,
562 // I::Item: Clone,
563 // {
564 // a: u8,
565 // b: T,
566 // c: I::Item,
567 // }
568 //
569 // We extract the field types, which in this case are `u8`, `T`, and
570 // `I::Item`. We re-use the existing parameters and where clauses. If
571 // `require_trait_bound == true` (as it is for `FromBytes), we add where
572 // bounds for each field's type:
573 //
574 // impl<T, I: Iterator> FromBytes for Foo<T, I>
575 // where
576 // T: Copy,
577 // I: Clone,
578 // I::Item: Clone,
579 // T: FromBytes,
580 // I::Item: FromBytes,
581 // {
582 // }
583 //
584 // NOTE: It is standard practice to only emit bounds for the type
585 // parameters themselves, not for field types based on those parameters
586 // (e.g., `T` vs `T::Foo`). For a discussion of why this is standard
587 // practice, see https://github.com/rust-lang/rust/issues/26925.
588 //
589 // The reason we diverge from this standard is that doing it that way
590 // for us would be unsound. E.g., consider a type, `T` where `T:
591 // FromBytes` but `T::Foo: !FromBytes`. It would not be sound for us to
592 // accept a type with a `T::Foo` field as `FromBytes` simply because `T:
593 // FromBytes`.
594 //
595 // While there's no getting around this requirement for us, it does have
596 // the pretty serious downside that, when lifetimes are involved, the
597 // trait solver ties itself in knots:
598 //
599 // #[derive(Unaligned)]
600 // #[repr(C)]
601 // struct Dup<'a, 'b> {
602 // a: PhantomData<&'a u8>,
603 // b: PhantomData<&'b u8>,
604 // }
605 //
606 // error[E0283]: type annotations required: cannot resolve `core::marker::PhantomData<&'a u8>: zerocopy::Unaligned`
607 // --> src/main.rs:6:10
608 // |
609 // 6 | #[derive(Unaligned)]
610 // | ^^^^^^^^^
611 // |
612 // = note: required by `zerocopy::Unaligned`
613
614 let type_ident = &self.ctx.ast.ident;
615 let trait_path = self.trt.crate_path(self.ctx);
616 let fields = self.data.fields();
617 let variants = self.data.variants();
618 let tag = self.data.tag();
619 let zerocopy_crate = &self.ctx.zerocopy_crate;
620
621 fn bound_tt(ty: &Type, traits: impl Iterator<Item = Trait>, ctx: &Ctx) -> WherePredicate {
622 let traits = traits.map(|t| t.crate_path(ctx));
623 parse_quote!(#ty: #(#traits)+*)
624 }
625 let field_type_bounds: Vec<_> = match (self.field_type_trait_bounds, &fields[..]) {
626 (FieldBounds::All(traits), _) => fields
627 .iter()
628 .map(|(_vis, _name, ty)| {
629 bound_tt(ty, normalize_bounds(&self.trt, traits), self.ctx)
630 })
631 .collect(),
632 (FieldBounds::None, _) | (FieldBounds::Trailing(..), []) => vec![],
633 (FieldBounds::Trailing(traits), [.., last]) => {
634 vec![bound_tt(last.2, normalize_bounds(&self.trt, traits), self.ctx)]
635 }
636 (FieldBounds::Explicit(bounds), _) => bounds,
637 };
638
639 let padding_check_bound = self
640 .padding_check
641 .map(|check| {
642 // Parse the repr for `align` and `packed` modifiers. Note that
643 // `Repr::<PrimitiveRepr, NonZeroU32>` is more permissive than
644 // what Rust supports for structs, enums, or unions, and thus
645 // reliably extracts these modifiers for any kind of type.
646 let repr =
647 Repr::<PrimitiveRepr, NonZeroU32>::from_attrs(&self.ctx.ast.attrs).unwrap();
648 let core = self.ctx.core_path();
649 let option = quote! { #core::option::Option };
650 let nonzero = quote! { #core::num::NonZeroUsize };
651 let none = quote! { #option::None::<#nonzero> };
652 let repr_align =
653 repr.get_align().map(|spanned| {
654 let n = spanned.t.get();
655 quote_spanned! { spanned.span => (#nonzero::new(#n as usize)) }
656 }).unwrap_or(quote! { (#none) });
657 let repr_packed =
658 repr.get_packed().map(|packed| {
659 let n = packed.get();
660 quote! { (#nonzero::new(#n as usize)) }
661 }).unwrap_or(quote! { (#none) });
662 let variant_types = variants.iter().map(|(_, fields)| {
663 let types = fields.iter().map(|(_vis, _name, ty)| ty);
664 quote!([#((#types)),*])
665 });
666 let validator_context = check.validator_macro_context();
667 let (trt, validator_macro) = check.validator_trait_and_macro_idents();
668 let t = tag.iter();
669 parse_quote! {
670 (): #zerocopy_crate::util::macro_util::#trt<
671 Self,
672 {
673 #validator_context
674 #zerocopy_crate::#validator_macro!(Self, #repr_align, #repr_packed, #(#t,)* #(#variant_types),*)
675 }
676 >
677 }
678 });
679
680 let self_bounds: Option<WherePredicate> = match self.self_type_trait_bounds {
681 SelfBounds::None => None,
682 SelfBounds::All(traits) => {
683 Some(bound_tt(&parse_quote!(Self), traits.iter().cloned(), self.ctx))
684 }
685 };
686
687 let zerocopy_bounds =
688 field_type_bounds
689 .into_iter()
690 .chain(padding_check_bound)
691 .chain(self_bounds)
692 .map(|bound| {
693 if self.ctx.skip_on_error {
694 parse_quote!(for<'zc> #bound)
695 } else {
696 bound.clone()
697 }
698 })
699 .collect::<Vec<_>>();
700
701 let bounds = self
702 .ctx
703 .ast
704 .generics
705 .where_clause
706 .as_ref()
707 .map(|where_clause| where_clause.predicates.iter())
708 .into_iter()
709 .flatten()
710 .chain(zerocopy_bounds.iter());
711
712 // The parameters with trait bounds, but without type defaults.
713 let mut params: Vec<_> = self
714 .ctx
715 .ast
716 .generics
717 .params
718 .clone()
719 .into_iter()
720 .map(|mut param| {
721 match &mut param {
722 GenericParam::Type(ty) => ty.default = None,
723 GenericParam::Const(cnst) => cnst.default = None,
724 GenericParam::Lifetime(_) => {}
725 }
726 parse_quote!(#param)
727 })
728 .chain(self.param_extras)
729 .collect();
730
731 // For MSRV purposes, ensure that lifetimes precede types precede const
732 // generics.
733 params.sort_by_cached_key(|param| match param {
734 GenericParam::Lifetime(_) => 0,
735 GenericParam::Type(_) => 1,
736 GenericParam::Const(_) => 2,
737 });
738
739 // The identifiers of the parameters without trait bounds or type
740 // defaults.
741 let param_idents = self.ctx.ast.generics.params.iter().map(|param| match param {
742 GenericParam::Type(ty) => {
743 let ident = &ty.ident;
744 quote!(#ident)
745 }
746 GenericParam::Lifetime(l) => {
747 let ident = &l.lifetime;
748 quote!(#ident)
749 }
750 GenericParam::Const(cnst) => {
751 let ident = &cnst.ident;
752 quote!({#ident})
753 }
754 });
755
756 let inner_extras = self.inner_extras;
757 let allow_trivial_bounds =
758 if self.ctx.skip_on_error { quote!(#[allow(trivial_bounds)]) } else { quote!() };
759 let impl_tokens = quote! {
760 #allow_trivial_bounds
761 unsafe impl < #(#params),* > #trait_path for #type_ident < #(#param_idents),* >
762 where
763 #(#bounds,)*
764 {
765 fn only_derive_is_allowed_to_implement_this_trait() {}
766
767 #inner_extras
768 }
769 };
770
771 let outer_extras = self.outer_extras.filter(|e| !e.is_empty());
772 let cfg_compile_error = self.ctx.cfg_compile_error();
773 const_block([Some(cfg_compile_error), Some(impl_tokens), outer_extras])
774 }
775 }
776
777 // A polyfill for `Option::then_some`, which was added after our MSRV.
778 //
779 // The `#[allow(unused)]` is necessary because, on sufficiently recent toolchain
780 // versions, `b.then_some(...)` resolves to the inherent method rather than to
781 // this trait, and so this trait is considered unused.
782 //
783 // FIXME(#67): Remove this once our MSRV is >= 1.62.
784 #[allow(unused)]
785 trait BoolExt {
786 fn then_some<T>(self, t: T) -> Option<T>;
787 }
788
789 impl BoolExt for bool {
790 fn then_some<T>(self, t: T) -> Option<T> {
791 if self {
792 Some(t)
793 } else {
794 None
795 }
796 }
797 }
798
799 pub(crate) fn const_block(items: impl IntoIterator<Item = Option<TokenStream>>) -> TokenStream {
800 let items = items.into_iter().flatten();
801 quote! {
802 #[allow(
803 // FIXME(#553): Add a test that generates a warning when
804 // `#[allow(deprecated)]` isn't present.
805 deprecated,
806 // Required on some rustc versions due to a lint that is only
807 // triggered when `derive(KnownLayout)` is applied to `repr(C)`
808 // structs that are generated by macros. See #2177 for details.
809 private_bounds,
810 non_local_definitions,
811 non_camel_case_types,
812 non_upper_case_globals,
813 non_snake_case,
814 non_ascii_idents,
815 clippy::missing_inline_in_public_items,
816 )]
817 #[deny(ambiguous_associated_items)]
818 // While there are not currently any warnings that this suppresses
819 // (that we're aware of), it's good future-proofing hygiene.
820 #[automatically_derived]
821 const _: () = {
822 #(#items)*
823 };
824 }
825 }
826 pub(crate) fn generate_tag_enum(ctx: &Ctx, repr: &EnumRepr, data: &DataEnum) -> TokenStream {
827 let zerocopy_crate = &ctx.zerocopy_crate;
828 let variants = data.variants.iter().map(|v| {
829 let ident = &v.ident;
830 if let Some((eq, discriminant)) = &v.discriminant {
831 quote! { #ident #eq #discriminant }
832 } else {
833 quote! { #ident }
834 }
835 });
836
837 // Don't include any `repr(align)` when generating the tag enum, as that
838 // could add padding after the tag but before any variants, which is not the
839 // correct behavior.
840 let repr = match repr {
841 EnumRepr::Transparent(span) => quote::quote_spanned! { *span => #[repr(transparent)] },
842 EnumRepr::Compound(c, _) => quote! { #c },
843 };
844
845 quote! {
846 #repr
847 #[allow(dead_code)]
848 pub enum ___ZerocopyTag {
849 #(#variants,)*
850 }
851
852 // SAFETY: `___ZerocopyTag` has no fields, and so it does not permit
853 // interior mutation.
854 unsafe impl #zerocopy_crate::Immutable for ___ZerocopyTag {
855 fn only_derive_is_allowed_to_implement_this_trait() {}
856 }
857 }
858 }
859 pub(crate) fn enum_size_from_repr(repr: &EnumRepr) -> Result<usize, Error> {
860 use CompoundRepr::*;
861 use PrimitiveRepr::*;
862 use Repr::*;
863 match repr {
864 Transparent(span)
865 | Compound(
866 Spanned {
867 t: C | Rust | Primitive(U32 | I32 | U64 | I64 | U128 | I128 | Usize | Isize),
868 span,
869 },
870 _,
871 ) => Err(Error::new(
872 *span,
873 "`FromBytes` only supported on enums with `#[repr(...)]` attributes `u8`, `i8`, `u16`, or `i16`",
874 )),
875 Compound(Spanned { t: Primitive(U8 | I8), span: _ }, _align) => Ok(8),
876 Compound(Spanned { t: Primitive(U16 | I16), span: _ }, _align) => Ok(16),
877 }
878 }
879
880 #[cfg(test)]
881 pub(crate) mod testutil {
882 use proc_macro2::TokenStream;
883 use syn::visit::{self, Visit};
884
885 /// Checks for hygiene violations in the generated code.
886 ///
887 /// # Panics
888 ///
889 /// Panics if a hygiene violation is found.
890 pub(crate) fn check_hygiene(ts: TokenStream) {
891 struct AmbiguousItemVisitor;
892
893 impl<'ast> Visit<'ast> for AmbiguousItemVisitor {
894 fn visit_path(&mut self, i: &'ast syn::Path) {
895 if i.segments.len() > 1 && i.segments.first().unwrap().ident == "Self" {
896 panic!(
897 "Found ambiguous path `{}` in generated output. \
898 All associated item access must be fully qualified (e.g., `<Self as Trait>::Item`) \
899 to prevent hygiene issues.",
900 quote::quote!(#i)
901 );
902 }
903 visit::visit_path(self, i);
904 }
905 }
906
907 let file = syn::parse2::<syn::File>(ts).expect("failed to parse generated output as File");
908 AmbiguousItemVisitor.visit_file(&file);
909 }
910
911 #[test]
912 fn test_check_hygiene_success() {
913 check_hygiene(quote::quote! {
914 fn foo() {
915 let _ = <Self as Trait>::Item;
916 }
917 });
918 }
919
920 #[test]
921 #[should_panic(expected = "Found ambiguous path `Self :: Ambiguous`")]
922 fn test_check_hygiene_failure() {
923 check_hygiene(quote::quote! {
924 fn foo() {
925 let _ = Self::Ambiguous;
926 }
927 });
928 }
929
930 #[test]
931 fn test_validate_crate_path() {
932 use syn::parse_str;
933
934 let valid = [
935 "zerocopy",
936 "crate",
937 "crate::foo::bar",
938 "self",
939 "self::foo",
940 "self::super::foo",
941 "super",
942 "super::foo",
943 "super::super::foo",
944 "super::super::super",
945 "foo::bar::baz",
946 "::foo::bar",
947 ];
948
949 for path_str in valid {
950 let path = parse_str::<syn::Path>(path_str).unwrap();
951 assert!(
952 super::validate_crate_path(&path).is_ok(),
953 "expected valid path for `{}`",
954 path_str
955 );
956 }
957
958 let invalid = [
959 "::crate::foo",
960 "::self::foo",
961 "::super::foo",
962 "Self",
963 "Self::foo",
964 "foo::Self::bar",
965 "foo::crate::bar",
966 "foo::super::bar",
967 "foo::self",
968 "super::foo::super",
969 "super::crate::foo",
970 "crate::super::foo",
971 "self::self::foo",
972 ];
973
974 for path_str in invalid {
975 let path = parse_str::<syn::Path>(path_str).unwrap();
976 assert!(
977 super::validate_crate_path(&path).is_err(),
978 "expected invalid path for `{}`",
979 path_str
980 );
981 }
982 }
983 }