ownable_macro/
lib.rs

1#![forbid(unsafe_code)]
2#![warn(missing_docs)]
3#![warn(clippy::pedantic)]
4
5//! This crate is not to be used on it's own, please see <https://docs.rs/ownable>.
6
7mod attribute;
8mod attribute_parser;
9mod common;
10mod r#enum;
11mod generate;
12mod mode;
13mod r#struct;
14
15use crate::attribute::DeriveAttribute;
16use crate::mode::Mode;
17use proc_macro_error::{abort, proc_macro_error};
18use syn::{parse_macro_input, Data, DeriveInput};
19
20/// Derive to_borrowed.
21#[proc_macro_error]
22#[proc_macro_derive(ToBorrowed, attributes(ownable))]
23pub fn to_borrowed(tokens: proc_macro::TokenStream) -> proc_macro::TokenStream {
24    let input = parse_macro_input!(tokens as DeriveInput);
25    derive(&input, Mode::ToBorrowed).into()
26}
27
28/// Derive to_owned.
29#[proc_macro_error]
30#[proc_macro_derive(ToOwned, attributes(ownable))]
31pub fn to_owned(tokens: proc_macro::TokenStream) -> proc_macro::TokenStream {
32    let input = parse_macro_input!(tokens as DeriveInput);
33    derive(&input, Mode::ToOwned).into()
34}
35
36/// Derive into_owned.
37#[proc_macro_error]
38#[proc_macro_derive(IntoOwned, attributes(ownable))]
39pub fn into_owned(tokens: proc_macro::TokenStream) -> proc_macro::TokenStream {
40    let input = parse_macro_input!(tokens as DeriveInput);
41    derive(&input, Mode::IntoOwned).into()
42}
43
44// a struct to just hold all global data together (rather than passing them always around)
45pub(crate) struct Derive<'a> {
46    pub(crate) input: &'a DeriveInput,
47    pub(crate) attribute: &'a DeriveAttribute,
48    pub(crate) mode: Mode,
49}
50
51fn derive(input: &DeriveInput, mode: Mode) -> proc_macro2::TokenStream {
52    let attribute = &DeriveAttribute::new(input);
53    let derive = Derive {
54        input,
55        attribute,
56        mode,
57    };
58    match &input.data {
59        Data::Struct(data) => derive.derive_struct(data),
60        Data::Enum(data) => derive.derive_enum(data),
61        Data::Union(_data) => abort!(input, "union is not supported"),
62    }
63}