Skip to main content

azalea_codec_macros/
lib.rs

1#![doc = include_str!("../README.md")]
2
3mod attrs;
4mod derive_enum;
5mod derive_struct;
6mod utils;
7
8use proc_macro::TokenStream;
9use quote::quote;
10use syn::{Attribute, DeriveInput, Field, Ident, parse_macro_input};
11
12use crate::attrs::{parse_field_attrs, parse_struct_attrs};
13
14/// Automatically implement the `Codec` trait for arbitrary structs or enums.
15///
16/// ## Structs
17///
18/// Structs are typically represented as maps.
19/// ```
20/// # use azalea_codec::Codec;
21/// # use serde_json::json;
22/// #[derive(Codec, Debug, PartialEq)]
23/// struct Thing {
24///     meow: String,
25///     woof: i32,
26/// }
27/// assert_eq!(
28///     Thing::codec_read(&json!({"meow": "!!!", "woof": 100})).unwrap(),
29///     Thing { meow: "!!!".into(), woof: 100 }
30/// );
31/// ```
32///
33/// You can also use structs with a single item to pass-through to another type,
34/// like so:
35/// ```
36/// # use azalea_codec::Codec;
37/// #[derive(Codec)]
38/// struct Thing(String);
39/// #[derive(Codec)]
40/// #[codec(transparent)] // this attribute is required since the field is named
41/// struct SameThing {
42///     thing: Thing,
43/// }
44/// ```
45///
46/// TODO: it's 4am i'm tired i can finish writing this later
47///
48/// ## Enums
49///
50/// When `Codec` is derived on an enum, reading will attempt each variant
51/// sequentially until one matches.
52/// ```
53/// # use azalea_codec::Codec;
54/// #[derive(Codec)]
55/// enum Thing {
56///     A(i32),
57///     B(String),
58/// }
59/// ```
60///
61/// You can easily represent enums that are serialized as strings with
62/// #[codec(key = "...")].
63/// ```
64/// # use azalea_codec::Codec;
65/// #[derive(Codec)]
66/// enum Thing {
67///     #[codec(key = "first")]
68///     A,
69///     #[codec(key = "second")]
70///     B,
71/// }
72/// ```
73///
74/// On occasion, you may want keys in variants that are maps.
75/// ```
76/// # use azalea_codec::Codec;
77/// # use serde_json::json;
78/// #[derive(Codec, Debug, PartialEq)]
79/// #[codec(tag = "type")]
80/// enum Thing {
81///     #[codec(key = "first")]
82///     A { value: i32 },
83///     #[codec(key = "second")]
84///     B { value: String },
85/// }
86/// assert_eq!(
87///     Thing::codec_read(&json!({"type": "first", "value": 1})).unwrap(),
88///     Thing::A { value:1 }
89/// );
90/// ```
91///
92/// You may not want to manually write keys for every variant if their key
93/// should be obvious from the variant name. For this, there is
94/// `#[codec(default_snake_case_key)]`
95///
96/// ```
97/// # use azalea_codec::Codec;
98/// #[derive(Codec, Debug, PartialEq)]
99/// #[codec(tag = "type")]
100/// #[codec(default_snake_case_key)]
101/// enum Thing {
102///     A { value: i32 },
103///     B { value: String },
104/// }
105/// ```
106///
107/// If the key should be read as a different static `Codec`, this is supported
108/// too. Your keys are validated against that `const_from_str` at build-time, by
109/// the way.
110/// ```
111/// #![feature(const_trait_impl, const_cmp)]
112/// # use azalea_codec::Codec;
113/// # use serde_json::json;
114/// # use std::fmt::{self, Display};
115/// use azalea_codec::types::ConstFromStr;
116/// #[derive(Codec, Debug, PartialEq)]
117/// #[codec(tag = "type", tag_as = Key)]
118/// #[codec(default_snake_case_key)]
119/// enum Thing {
120///     A { value: i32 },
121///     B { value: String },
122/// }
123/// #[derive(Codec, PartialEq)]
124/// #[codec(default_snake_case_key)]
125/// enum Key {
126///     First,
127///     Second,
128/// }
129/// const impl ConstFromStr for Key {
130///     fn const_from_str(s: &str) -> Option<Self> {
131///         if s == "a" { Some(Self::First) }
132///         else if s == "b" { Some(Self::Second) }
133///         else { None }
134///     }
135/// }
136/// assert_eq!(
137///     Thing::codec_read(&json!({"type": "first", "value": 1})).unwrap(),
138///     Thing::A { value: 1 }
139/// );
140/// assert_eq!(
141///     Thing::codec_read(&json!({"type": "second", "value": ""})).unwrap(),
142///     Thing::B { value: "".to_string() }
143/// );
144/// ```
145///
146/// Sadly, implementing `ConstFromStr` requires enabling a Nightly-only feature:
147/// [`const_trait_impl`](https://doc.rust-lang.org/beta/unstable-book/language-features/const-trait-impl.html).
148///
149/// Named variants are treated exactly the same as structs, and support all of
150/// their `#[codec(...)]` attributes.
151/// ```
152/// # use azalea_codec::Codec;
153/// #[derive(Codec)]
154/// #[codec(tag = "id", default_snake_case_key)]
155/// enum Thing {
156///     #[codec(allow_unknown_keys)]
157///     A { value: i32 },
158///     B {
159///         #[codec(lenient)]
160///         value: Option<String>,
161///     },
162/// }
163/// ```
164#[proc_macro_derive(Codec, attributes(codec))]
165pub fn derive_codec(input: TokenStream) -> TokenStream {
166    let DeriveInput {
167        ident,
168        data,
169        vis,
170        attrs,
171        generics,
172    } = parse_macro_input!(input);
173
174    match data {
175        syn::Data::Struct(syn::DataStruct { fields, .. }) => match fields {
176            syn::Fields::Named(fields) => derive_struct::derive_codec_for_named_fields_struct(
177                &vis, &attrs, &ident, &generics, fields,
178            ),
179            syn::Fields::Unnamed(fields) => {
180                assert_eq!(
181                    fields.unnamed.len(),
182                    1,
183                    "#[derive(Codec)] cannot be used on structs with more than one unnamed field."
184                );
185                derive_transparent_impl(&attrs, &ident, &fields.unnamed[0])
186            }
187            syn::Fields::Unit => derive_unit_struct_impl(&ident),
188        },
189        syn::Data::Enum(syn::DataEnum { variants, .. }) => {
190            derive_enum::derive_codec_for_enum(&vis, &attrs, &ident, &generics, variants)
191        }
192        _ => {
193            panic!("#[derive(Codec)] can only be used on structs and enums")
194        }
195    }
196}
197
198fn derive_transparent_impl(attrs: &[Attribute], ident: &Ident, field: &Field) -> TokenStream {
199    let _struct_attrs = match parse_struct_attrs(attrs) {
200        Ok(a) => a,
201        Err(e) => return e.into_compile_error().into(),
202    };
203    let field_attrs = match parse_field_attrs(&field.attrs) {
204        Ok(a) => a,
205        Err(e) => return e.into_compile_error().into(),
206    };
207
208    let base_read_expr = if let Some(with) = &field_attrs.with {
209        quote! { #with::codec_read(ops).map(|c| c.0) }
210    } else {
211        quote! { <_>::codec_read(ops) }
212    };
213
214    let read_expr;
215    let write_expr;
216    if let Some(field_ident) = &field.ident {
217        read_expr = quote! {
218            #base_read_expr.map(|#field_ident| Self { #field_ident })
219        };
220        write_expr = quote! { self.#field_ident };
221    } else {
222        read_expr = quote! { #base_read_expr.map(Self) };
223        write_expr = quote! { self.0 };
224    };
225
226    let write_expr = if let Some(with) = &field_attrs.with {
227        quote! { #with(#write_expr.clone()) }
228    } else {
229        write_expr
230    };
231
232    quote! {
233    impl<O: ::azalea_codec::Ops> ::azalea_codec::Codec<O> for #ident {
234        fn codec_read(ops: &O) -> azalea_codec::error::ReadResult<Self> {
235            #read_expr
236        }
237        fn codec_write(&self) -> azalea_codec::error::WriteResult<O> {
238            ::azalea_codec::Codec::codec_write(&#write_expr)
239        }
240    }
241    }
242    .into()
243}
244
245fn derive_unit_struct_impl(ident: &Ident) -> TokenStream {
246    quote! {
247        impl<O: ::azalea_codec::Ops> ::azalea_codec::Codec<O> for #ident {
248        fn codec_read(ops: &O) -> azalea_codec::error::ReadResult<Self> {
249            <()>::codec_read(ops)?;
250            Ok(Self)
251        }
252        fn codec_write(&self) -> azalea_codec::error::WriteResult<O> {
253            ::azalea_codec::Codec::codec_write(&())
254        }
255    }
256    }
257    .into()
258}