kudu_macros/
lib.rs

1//! This module contains macros to be used in the [`kudu`](https://docs.rs/kudu) crates.
2//!
3//! ## Feature flags
4//!
5//! - `detailed-error`: activate this to enable the [`macro@with_location`] macro. If
6//!   not enabled, the [`macro@with_location`] macro will be a no-op.
7
8mod attr;
9mod contract;
10mod serde;
11
12use proc_macro::TokenStream;
13use syn::{parse_macro_input, DeriveInput, ItemStruct, MetaNameValue, punctuated::Punctuated};
14
15#[cfg(feature = "detailed-error")]
16use syn::ItemEnum;
17
18#[cfg(feature = "detailed-error")]
19mod error;
20
21#[cfg(feature = "detailed-error")]
22use crate::error::add_location_to_error_enum;
23
24
25// the `kudu` crate re-exports this macro and adds documentation to it
26#[proc_macro_attribute]
27pub fn with_location(attr: TokenStream, annotated_item: TokenStream) -> TokenStream {
28    with_location_impl(attr, annotated_item)
29}
30
31
32#[cfg(feature = "detailed-error")]
33fn with_location_impl(_attr: TokenStream, annotated_item: TokenStream) -> TokenStream {
34    let error_enum = parse_macro_input!(annotated_item as ItemEnum);
35    add_location_to_error_enum(error_enum).into()
36}
37
38#[cfg(not(feature = "detailed-error"))]
39fn with_location_impl(_attr: TokenStream, annotated_item: TokenStream) -> TokenStream {
40    annotated_item
41}
42
43
44// the `kudu` crate re-exports this macro and adds documentation to it
45#[proc_macro_attribute]
46pub fn contract(attr: TokenStream, annotated_item: TokenStream) -> TokenStream {
47    let attrs = parse_macro_input!(attr with Punctuated::<MetaNameValue, syn::Token![,]>::parse_terminated);
48    let contract_struct = parse_macro_input!(annotated_item as ItemStruct);
49    contract::add_contract_trait_impl(attrs, contract_struct).into()
50}
51
52// the `kudu` crate re-exports this macro and adds documentation to it
53#[proc_macro_derive(ABISerializable)]
54pub fn derive_abiserializable(input: TokenStream) -> TokenStream {
55    let input = parse_macro_input!(input as DeriveInput);
56    serde::derive(&input).into()
57}
58
59// the `kudu` crate re-exports this macro and adds documentation to it
60#[proc_macro_derive(SerializeEnum, attributes(serde))]
61pub fn derive_serialize_enum(input: TokenStream) -> TokenStream {
62    let input = parse_macro_input!(input as DeriveInput);
63    serde::derive_serialize_enum(&input, false).into()
64}
65
66// the `kudu` crate re-exports this macro and adds documentation to it
67#[proc_macro_derive(SerializeEnumPrefixed, attributes(serde))]
68pub fn derive_serialize_enum_prefixed(input: TokenStream) -> TokenStream {
69    let input = parse_macro_input!(input as DeriveInput);
70    serde::derive_serialize_enum(&input, true).into()
71}