bounded_static_derive/
lib.rs

1#![doc(html_root_url = "https://docs.rs/bounded-static-derive/0.8.0")]
2//! Provides the `ToStatic` derive macro.
3//!
4//! The [`ToStatic`] derive macro implements the [`ToBoundedStatic`](https://docs.rs/bounded-static/0.8.0/bounded_static/trait.ToBoundedStatic.html)
5//! and [`IntoBoundedStatic`](https://docs.rs/bounded-static/0.8.0/bounded_static/trait.IntoBoundedStatic.html) traits for any `struct`
6//! and `enum` that can be converted to a form that is bounded by `'static`.
7//!
8//! The [`ToStatic`] macro should be used via the [`bounded-static`](https://docs.rs/bounded-static/0.8.0) crate
9//! rather than using this crate directly.
10#![warn(clippy::all, clippy::pedantic, clippy::nursery, rust_2018_idioms)]
11#![allow(clippy::redundant_pub_crate)]
12#![forbid(unsafe_code)]
13
14use proc_macro2::TokenStream;
15use syn::{Data, DataStruct, DeriveInput, Fields};
16
17mod common;
18mod data_enum;
19mod data_struct;
20
21/// The `ToStatic` derive macro.
22///
23/// Generate [`ToBoundedStatic`](https://docs.rs/bounded-static/0.8.0/bounded_static/trait.ToBoundedStatic.html) and
24/// [`IntoBoundedStatic`](https://docs.rs/bounded-static/0.8.0/bounded_static/trait.IntoBoundedStatic.html) impls for the data item deriving
25/// `ToStatic`.
26#[proc_macro_derive(ToStatic)]
27pub fn to_static(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
28    let input = syn::parse_macro_input!(input as syn::DeriveInput);
29    proc_macro::TokenStream::from(generate_traits(&input))
30}
31
32fn generate_traits(input: &DeriveInput) -> TokenStream {
33    match &input.data {
34        Data::Struct(DataStruct {
35            fields: Fields::Named(fields_named),
36            ..
37        }) => data_struct::generate_struct_named(&input.ident, &input.generics, fields_named),
38        Data::Struct(DataStruct {
39            fields: Fields::Unnamed(fields_unnamed),
40            ..
41        }) => data_struct::generate_struct_unnamed(&input.ident, &input.generics, fields_unnamed),
42        Data::Struct(DataStruct {
43            fields: Fields::Unit,
44            ..
45        }) => data_struct::generate_struct_unit(&input.ident),
46        Data::Enum(data_enum) => data_enum::generate_enum(
47            &input.ident,
48            &input.generics,
49            data_enum.variants.iter().collect::<Vec<_>>().as_slice(),
50        ),
51        Data::Union(_) => unimplemented!("union is not yet supported"),
52    }
53}