Skip to main content

annotated_derive/
lib.rs

1//! The derive macros of [`annotated`](https://docs.rs/annotated), which re-exports and documents them.
2
3mod deserialize_expansion;
4mod deserialized_struct;
5mod expansion;
6mod pattern;
7mod serde_names;
8mod validated_struct;
9mod written_rule;
10
11use proc_macro::TokenStream;
12use syn::{DeriveInput, Error, parse_macro_input};
13
14use deserialized_struct::DeserializedStruct;
15use validated_struct::ValidatedStruct;
16
17/// Derives `annotated::Validate` from the `#[validate(...)]` rules on a struct's fields.
18#[proc_macro_derive(Validate, attributes(validate, serde))]
19pub fn derive_validate(input: TokenStream) -> TokenStream {
20    let input = parse_macro_input!(input as DeriveInput);
21    ValidatedStruct::from_input(&input, "Validate")
22        .map_or_else(Error::into_compile_error, |validated_struct| {
23            expansion::validate_impl(&validated_struct)
24        })
25        .into()
26}
27
28/// Derives `annotated::Deserialize`, and serde's `Deserialize` through it. Reading the struct then collects every
29/// missing field and broken rule in it.
30#[proc_macro_derive(Deserialize, attributes(validate, serde, annotated))]
31pub fn derive_deserialize(input: TokenStream) -> TokenStream {
32    let input = parse_macro_input!(input as DeriveInput);
33    DeserializedStruct::from_input(&input)
34        .map_or_else(Error::into_compile_error, |deserialized_struct| {
35            deserialize_expansion::deserialize_impl(&deserialized_struct)
36        })
37        .into()
38}