Skip to main content

onc_xdr_derive/
lib.rs

1//! Derive macro for XDR (External Data Representation) encoding.
2//!
3//! XDR is the serialisation format every ONC RPC protocol is built on --
4//! NFSv2, NFSv3, NFSv4, MOUNT, and the portmapper all encode their arguments
5//! and results with it.  The format is defined by [RFC 4506]; the essential
6//! rules this macro implements are:
7//!
8//! * Every field is packed in declaration order with no padding between them.
9//! * Enums (XDR "enum" and discriminated "union") are tagged by a 4-byte
10//!   big-endian discriminant, followed by the arm's payload if it has one.
11//! * Structs carry no tag of their own -- they are just their fields, in order.
12//!
13//! Writing `Pack` and `Unpack` by hand for the ~200 types in [RFC 1813] alone
14//! would be error-prone busywork, so `#[derive(XdrCodec)]` generates them.
15//! Types whose wire form does not follow the mechanical rules above (NFSv2's
16//! fixed-width 32-byte file handles, the RPC reply body's nested unions) still
17//! implement the traits by hand in the protocol crate that defines them.
18//!
19//! # Discriminant values
20//!
21//! Simple enums (all unit variants) use the variant's own `as u32` value, so
22//! the discriminant is declared the normal Rust way:
23//!
24//! ```ignore
25//! #[derive(XdrCodec, Clone, Copy)]
26//! #[repr(u32)]
27//! enum ftype3 {
28//!     NF3REG = 1,
29//!     NF3DIR = 2,
30//! }
31//! ```
32//!
33//! Enums carrying data cannot use `as u32`, so each variant is tagged with an
34//! explicit `#[xdr(N)]` attribute giving its discriminant:
35//!
36//! ```ignore
37//! #[derive(XdrCodec)]
38//! enum post_op_attr {
39//!     #[xdr(1)]
40//!     Some(fattr3),
41//!     #[xdr(0)]
42//!     None,
43//! }
44//! ```
45//!
46//! [RFC 4506]: https://www.rfc-editor.org/rfc/rfc4506
47//! [RFC 1813]: https://www.rfc-editor.org/rfc/rfc1813
48
49#![expect(
50    clippy::panic,
51    reason = "a derive macro's \"runtime\" is the compiler's expansion pass, so a \
52panic here surfaces as a build failure on the offending type, never as a fault in \
53a running binary. Reporting via syn::Error would point at a tighter source span \
54and is worth doing, but these panics cannot reach production code"
55)]
56
57use proc_macro::TokenStream;
58use proc_macro2::TokenStream as TokenStream2;
59use quote::quote;
60use syn::{Attribute, Data, DataEnum, DeriveInput, Expr, Fields, FieldsNamed, FieldsUnnamed, Ident, Index, Lit, Meta, Variant, parse_macro_input};
61
62/// Reads the discriminant out of a `#[xdr(N)]` attribute.
63///
64/// Only data-carrying enum variants need this; simple enums get their
65/// discriminant from `as u32` instead.
66fn parse_xdr_value(attrs: &[Attribute]) -> Option<u32> {
67    for attr in attrs {
68        if attr.path().is_ident("xdr")
69            && let Meta::List(meta_list) = &attr.meta
70            && let Ok(Expr::Lit(syn::ExprLit { lit: Lit::Int(lit_int), .. })) = meta_list.parse_args::<Expr>()
71            && let Ok(value) = lit_int.base10_parse::<u32>()
72        {
73            return Some(value);
74        }
75    }
76    None
77}
78
79/// Emits per-field pack/unpack fragments for a braced struct.
80struct NamedFieldsGenerator<'a> {
81    fields: &'a FieldsNamed,
82}
83
84impl<'a> NamedFieldsGenerator<'a> {
85    const fn new(fields: &'a FieldsNamed) -> Self {
86        Self { fields }
87    }
88
89    fn pack_fields(&self) -> impl Iterator<Item = TokenStream2> + '_ {
90        self.fields.named.iter().map(|f| {
91            let name = &f.ident;
92            quote! {
93                total_write += self.#name.pack(out)?;
94            }
95        })
96    }
97
98    fn packed_size_fields(&self) -> impl Iterator<Item = TokenStream2> + '_ {
99        self.fields.named.iter().map(|f| {
100            let name = &f.ident;
101            quote! {
102                total_size += ::onc_xdr::Pack::packed_size(&self.#name);
103            }
104        })
105    }
106
107    fn unpack_fields(&self) -> impl Iterator<Item = TokenStream2> + '_ {
108        self.fields.named.iter().map(|f| {
109            let name = &f.ident;
110            quote! {
111                let (#name, read_bytes) = ::onc_xdr::Unpack::unpack(input)?;
112                total_read += read_bytes;
113            }
114        })
115    }
116
117    fn struct_construction_fields(&self) -> impl Iterator<Item = TokenStream2> + '_ {
118        self.fields.named.iter().map(|f| {
119            let name = &f.ident;
120            quote! { #name, }
121        })
122    }
123}
124
125/// Emits per-field pack/unpack fragments for a tuple struct.
126struct UnnamedFieldsGenerator<'a> {
127    fields: &'a FieldsUnnamed,
128}
129
130impl<'a> UnnamedFieldsGenerator<'a> {
131    const fn new(fields: &'a FieldsUnnamed) -> Self {
132        Self { fields }
133    }
134
135    fn pack_fields(&self) -> impl Iterator<Item = TokenStream2> + '_ {
136        self.fields.unnamed.iter().enumerate().map(|(i, _)| {
137            let index = Index::from(i);
138            quote! {
139                total_write += self.#index.pack(out)?;
140            }
141        })
142    }
143
144    fn packed_size_fields(&self) -> impl Iterator<Item = TokenStream2> + '_ {
145        self.fields.unnamed.iter().enumerate().map(|(i, _)| {
146            let index = Index::from(i);
147            quote! {
148                total_size += ::onc_xdr::Pack::packed_size(&self.#index);
149            }
150        })
151    }
152
153    fn unpack_fields(&self) -> impl Iterator<Item = TokenStream2> + '_ {
154        self.fields.unnamed.iter().enumerate().map(|(i, _)| {
155            let var_name = Ident::new(&format!("field_{i}"), proc_macro2::Span::call_site());
156            quote! {
157                let (#var_name, read_bytes) = ::onc_xdr::Unpack::unpack(input)?;
158                total_read += read_bytes;
159            }
160        })
161    }
162
163    fn struct_construction_fields(&self) -> impl Iterator<Item = TokenStream2> + '_ {
164        (0..self.fields.unnamed.len()).map(|i| {
165            let var_name = Ident::new(&format!("field_{i}"), proc_macro2::Span::call_site());
166            quote! { #var_name }
167        })
168    }
169}
170
171/// Generates `Pack`/`Unpack` for a struct.
172///
173/// XDR structs are untagged: the encoding is exactly the fields back to back,
174/// so there is no discriminant to write (RFC 4506 sec. 4.14).
175fn generate_struct_impl(name: &Ident, generics: &syn::Generics, fields: &Fields) -> TokenStream2 {
176    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
177
178    match fields {
179        Fields::Named(named_fields) => {
180            let generator = NamedFieldsGenerator::new(named_fields);
181            let pack_fields = generator.pack_fields();
182            let packed_size_fields = generator.packed_size_fields();
183            let unpack_fields = generator.unpack_fields();
184            let struct_fields = generator.struct_construction_fields();
185
186            quote! {
187                impl #impl_generics ::onc_xdr::Pack for #name #ty_generics
188                #where_clause {
189                    fn packed_size(&self) -> usize {
190                        let mut total_size = 0;
191                        #(#packed_size_fields)*
192                        total_size
193                    }
194
195                    fn pack(&self, out: &mut impl std::io::Write) -> ::onc_xdr::Result<usize> {
196                        use ::onc_xdr::Pack;
197                        let mut total_write = 0;
198                        #(#pack_fields)*
199                        Ok(total_write)
200                    }
201                }
202                impl #impl_generics ::onc_xdr::Unpack for #name #ty_generics
203                #where_clause {
204                    fn unpack(input: &mut impl std::io::Read) -> ::onc_xdr::Result<(Self, usize)> {
205                        use ::onc_xdr::Unpack;
206                        let mut total_read = 0;
207                        #(#unpack_fields)*
208                        Ok((Self { #(#struct_fields)* }, total_read))
209                    }
210                }
211            }
212        },
213        Fields::Unnamed(unnamed_fields) => {
214            let generator = UnnamedFieldsGenerator::new(unnamed_fields);
215            let pack_fields = generator.pack_fields();
216            let packed_size_fields = generator.packed_size_fields();
217            let unpack_fields = generator.unpack_fields();
218            let struct_fields = generator.struct_construction_fields();
219
220            quote! {
221                impl #impl_generics ::onc_xdr::Pack for #name #ty_generics
222                #where_clause {
223                    fn packed_size(&self) -> usize {
224                        let mut total_size = 0;
225                        #(#packed_size_fields)*
226                        total_size
227                    }
228
229                    fn pack(&self, out: &mut impl std::io::Write) -> ::onc_xdr::Result<usize> {
230                        use ::onc_xdr::Pack;
231                        let mut total_write = 0;
232                        #(#pack_fields)*
233                        Ok(total_write)
234                    }
235                }
236                impl #impl_generics ::onc_xdr::Unpack for #name #ty_generics
237                #where_clause {
238                    fn unpack(input: &mut impl std::io::Read) -> ::onc_xdr::Result<(Self, usize)> {
239                        use ::onc_xdr::Unpack;
240                        let mut total_read = 0;
241                        #(#unpack_fields)*
242                        Ok((Self(#(#struct_fields),*), total_read))
243                    }
244                }
245            }
246        },
247        Fields::Unit => {
248            quote! {
249                impl #impl_generics ::onc_xdr::Pack for #name #ty_generics
250                #where_clause {
251                    fn packed_size(&self) -> usize {
252                        0
253                    }
254
255                    fn pack(&self, _out: &mut impl std::io::Write) -> ::onc_xdr::Result<usize> {
256                        Ok(0)
257                    }
258                }
259                impl #impl_generics ::onc_xdr::Unpack for #name #ty_generics
260                #where_clause {
261                    fn unpack(_input: &mut impl std::io::Read) -> ::onc_xdr::Result<(Self, usize)> {
262                        Ok((Self, 0))
263                    }
264                }
265            }
266        },
267    }
268}
269
270/// Rejects enum shapes XDR has no encoding for.
271///
272/// An XDR discriminated union arm carries at most one value (RFC 4506
273/// sec. 4.15), so multi-field and braced variants cannot be represented.
274fn validate_complex_enum_variant(variant: &Variant) -> Result<(), String> {
275    match &variant.fields {
276        Fields::Unit => Ok(()),
277        Fields::Unnamed(fields) if fields.unnamed.len() == 1 => Ok(()),
278        _ => Err(format!("Complex enum variant '{}' must be either unit or have exactly one unnamed field", variant.ident)),
279    }
280}
281
282/// Emits the pack arm for one variant of a data-carrying enum.
283fn generate_complex_enum_pack_variant(variant: &Variant) -> TokenStream2 {
284    let ident = &variant.ident;
285    let xdr_value = parse_xdr_value(&variant.attrs).unwrap_or_else(|| {
286        panic!("Complex enum variant '{ident}' must have #[xdr(value)] attribute");
287    });
288
289    match &variant.fields {
290        Fields::Unit => {
291            quote! {
292                Self::#ident => #xdr_value.pack(out),
293            }
294        },
295        Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {
296            quote! {
297                Self::#ident(val) => {
298                    let mut len = #xdr_value.pack(out)?;
299                    len += val.pack(out)?;
300                    Ok(len)
301                },
302            }
303        },
304        _ => panic!("Invalid complex enum variant: {ident}"),
305    }
306}
307
308/// Emits the `packed_size` arm for one variant of a data-carrying enum.
309///
310/// The constant 4 is the discriminant, which XDR always encodes as a 4-byte
311/// big-endian integer regardless of how few values the union has.
312fn generate_complex_enum_packed_size_variant(variant: &Variant) -> TokenStream2 {
313    let ident = &variant.ident;
314
315    match &variant.fields {
316        Fields::Unit => {
317            quote! {
318                Self::#ident => 4,
319            }
320        },
321        Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {
322            quote! {
323                Self::#ident(val) => 4 + val.packed_size(),
324            }
325        },
326        _ => panic!("Invalid complex enum variant: {ident}"),
327    }
328}
329
330/// Emits the unpack arm for one variant of a data-carrying enum.
331fn generate_complex_enum_unpack_variant(variant: &Variant) -> TokenStream2 {
332    let ident = &variant.ident;
333    let xdr_value = parse_xdr_value(&variant.attrs).unwrap_or_else(|| {
334        panic!("Complex enum variant '{ident}' must have #[xdr(value)] attribute");
335    });
336
337    match &variant.fields {
338        Fields::Unit => {
339            quote! {
340                #xdr_value => Ok(Self::#ident),
341            }
342        },
343        Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {
344            quote! {
345                #xdr_value => {
346                    let (val, val_bytes) = ::onc_xdr::Unpack::unpack(input)?;
347                    bytes_read += val_bytes;
348                    Ok(Self::#ident(val))
349                },
350            }
351        },
352        _ => panic!("Invalid complex enum variant: {ident}"),
353    }
354}
355
356/// Generates `Pack`/`Unpack` for an enum whose variants are all unit.
357///
358/// These map onto a plain XDR enum: just the 4-byte discriminant, taken from
359/// the variant's `as u32` value.
360fn generate_simple_enum_impl(name: &Ident, generics: &syn::Generics, data: &DataEnum) -> TokenStream2 {
361    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
362
363    let pack_variants = data.variants.iter().map(|v| {
364        let ident = &v.ident;
365        quote! {
366            Self::#ident => (*self as u32).pack(out),
367        }
368    });
369
370    let unpack_variants = data.variants.iter().map(|v| {
371        let ident = &v.ident;
372        quote! {
373            x if x == Self::#ident as u32 => Ok(Self::#ident),
374        }
375    });
376
377    quote! {
378        impl #impl_generics ::onc_xdr::Pack for #name #ty_generics
379        #where_clause {
380            fn packed_size(&self) -> usize {
381                4
382            }
383
384            fn pack(&self, out: &mut impl std::io::Write) -> ::onc_xdr::Result<usize> {
385                use ::onc_xdr::Pack;
386                match self {
387                    #(#pack_variants)*
388                }
389            }
390        }
391        impl #impl_generics ::onc_xdr::Unpack for #name #ty_generics
392        #where_clause {
393            fn unpack(input: &mut impl std::io::Read) -> ::onc_xdr::Result<(Self, usize)> {
394                let (tag, bytes_read) = u32::unpack(input)?;
395                let result = match tag {
396                    #(#unpack_variants)*
397                    _ => Err(::onc_xdr::Error::InvalidEnumValue(tag)),
398                };
399                result.map(|value| (value, bytes_read))
400            }
401        }
402    }
403}
404
405/// Generates `Pack`/`Unpack` for an enum with data-carrying variants.
406///
407/// These map onto an XDR discriminated union: the 4-byte discriminant from
408/// `#[xdr(N)]`, followed by the arm's payload.
409fn generate_complex_enum_impl(name: &Ident, generics: &syn::Generics, data: &DataEnum) -> TokenStream2 {
410    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
411
412    // Fail at expansion time rather than emitting code that cannot compile.
413    for variant in &data.variants {
414        if let Err(err) = validate_complex_enum_variant(variant) {
415            panic!("{}", err);
416        }
417    }
418
419    let pack_variants = data.variants.iter().map(generate_complex_enum_pack_variant);
420    let packed_size_variants = data.variants.iter().map(generate_complex_enum_packed_size_variant);
421    let unpack_variants = data.variants.iter().map(generate_complex_enum_unpack_variant);
422
423    quote! {
424        impl #impl_generics ::onc_xdr::Pack for #name #ty_generics
425        #where_clause {
426            fn packed_size(&self) -> usize {
427                match self {
428                    #(#packed_size_variants)*
429                }
430            }
431
432            fn pack(&self, out: &mut impl std::io::Write) -> ::onc_xdr::Result<usize> {
433                use ::onc_xdr::Pack;
434                match self {
435                    #(#pack_variants)*
436                }
437            }
438        }
439        impl #impl_generics ::onc_xdr::Unpack for #name #ty_generics
440        #where_clause {
441            fn unpack(input: &mut impl std::io::Read) -> ::onc_xdr::Result<(Self, usize)> {
442                use ::onc_xdr::Unpack;
443                let (tag, mut bytes_read) = u32::unpack(input)?;
444                let result = match tag {
445                    #(#unpack_variants)*
446                    _ => Err(::onc_xdr::Error::InvalidEnumValue(tag)),
447                };
448                result.map(|value| (value, bytes_read))
449            }
450        }
451    }
452}
453
454/// Dispatches to the simple or discriminated-union enum generator.
455fn generate_enum_impl(name: &Ident, generics: &syn::Generics, data: &DataEnum) -> TokenStream2 {
456    let has_data_variants = data.variants.iter().any(|v| !matches!(v.fields, Fields::Unit));
457
458    if has_data_variants { generate_complex_enum_impl(name, generics, data) } else { generate_simple_enum_impl(name, generics, data) }
459}
460
461/// Derives XDR `Pack` and `Unpack` for a struct or enum.
462///
463/// See the crate documentation for the encoding rules and for when to reach
464/// for a hand-written implementation instead.
465///
466/// # Panics
467///
468/// Panics at macro-expansion time when the type cannot be expressed in XDR:
469/// on unions, on a data-carrying enum variant with more than one field or with
470/// named fields, or on a data-carrying variant missing its `#[xdr(N)]` tag.
471#[proc_macro_derive(XdrCodec, attributes(xdr))]
472pub fn derive_xdr_codec(input: TokenStream) -> TokenStream {
473    let input = parse_macro_input!(input as DeriveInput);
474    let name = &input.ident;
475    let generics = &input.generics;
476
477    let result = match &input.data {
478        Data::Struct(data_struct) => generate_struct_impl(name, generics, &data_struct.fields),
479        Data::Enum(data_enum) => generate_enum_impl(name, generics, data_enum),
480        Data::Union(_) => panic!("XdrCodec can only be derived for structs and enums"),
481    };
482
483    result.into()
484}
485
486// Dev-dependencies (onc_xdr, trybuild) are visible to the lib test target
487// but only used from the integration test binary in tests/derive.rs.
488#[cfg(test)]
489mod _dev_dep_anchors {
490    use onc_xdr as _;
491    use trybuild as _;
492}