1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// Copyright 2021-2022 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

//! This crate provides the `Packable` derive macro.

mod enum_info;
mod field_info;
mod fragments;
mod parse;
mod record_info;
mod struct_info;
mod tag_type_info;
mod trait_impl;
mod unpack_error_info;
mod variant_info;

use proc_macro2::Span;
use trait_impl::TraitImpl;

use proc_macro::TokenStream;
use proc_macro_crate::{crate_name, FoundCrate};
use proc_macro_error::{abort, proc_macro_error};
use quote::ToTokens;
use syn::{parse_macro_input, Ident};

#[proc_macro_error]
#[proc_macro_derive(Packable, attributes(packable))]
pub fn packable(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input);

    let crate_string =
        match crate_name("packable").expect("packable should be present in `Cargo.toml`") {
            FoundCrate::Itself => "packable_crate".to_owned(),
            FoundCrate::Name(name) => name,
        };

    match TraitImpl::new(input, Ident::new(&crate_string, Span::call_site())) {
        Ok(trait_impl) => trait_impl.into_token_stream().into(),
        Err(err) => abort!(err),
    }
}