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
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
//! Custom derive support for the `simple-tlv` crate
//!
//! With `#[tlv(slice)]` set, `Encodable` should work for fields implementing `AsRef<[u8]>`,
//! and `Decodable` should work for fields implementing `TryFrom<[u8]>`, even if the field
//! is not `Decodable` or `Encodable`.

#![crate_type = "proc-macro"]
#![warn(rust_2018_idioms, trivial_casts, unused_qualifications)]

mod decodable;
use decodable::DeriveDecodableStruct;
mod encodable;
use encodable::DeriveEncodableStruct;


use proc_macro2::TokenStream;
use syn::{
    Attribute, Field, Ident, Lit, Meta, MetaList, MetaNameValue, NestedMeta,
};
use synstructure::{decl_derive, Structure};

decl_derive!(
    [Decodable, attributes(tlv)] =>

    /// Derive the [`Decodable`][1] trait on a struct.
    ///
    /// See [toplevel documentation for the `simple-tlv_derive` crate][2] for more
    /// information about how to use this macro.
    ///
    /// [1]: https://docs.rs/simple-tlv/latest/simple_tlv/trait.Decodable.html
    /// [2]: https://docs.rs/simple-tlv_derive/
    derive_decodable
);

decl_derive!(
    [Encodable, attributes(tlv)] =>

    /// Derive the [`Encodable`][1] trait on a struct.
    ///
    /// See [toplevel documentation for the `simple-tlv_derive` crate][2] for more
    /// information about how to use this macro.
    ///
    /// [1]: https://docs.rs/simple-tlv/latest/simple_tlv/trait.Decodable.html
    /// [2]: https://docs.rs/simple-tlv_derive/
    derive_encodable
);

/// Custom derive for `simple_tlv::Decodable`
fn derive_decodable(s: Structure<'_>) -> TokenStream {
    let ast = s.ast();

    // TODO: enum support
    match &ast.data {
        syn::Data::Struct(data) => DeriveDecodableStruct::derive(s, data, &ast.ident, &ast.attrs),
        other => panic!("can't derive `Decodable` on: {:?}", other),
    }
}

/// Custom derive for `simple_tlv::Encodable`
fn derive_encodable(s: Structure<'_>) -> TokenStream {
    let ast = s.ast();

    // TODO: enum support
    match &ast.data {
        syn::Data::Struct(data) => DeriveEncodableStruct::derive(s, data, &ast.ident, &ast.attrs),
        other => panic!("can't derive `Encodable` on: {:?}", other),
    }
}

/// Attributes of a field
#[derive(Debug)]
struct FieldAttrs {
    /// Name of the field
    pub name: Ident,

    /// Value of the `#[tlv(tag = "...")]` attribute if provided
    pub tag: u8,

    /// Whether the `#[tlv(slice)]` attribute was set
    pub slice: bool
}

impl FieldAttrs {
    /// Parse the attributes of a field
    fn new(field: &Field) -> Self {
        let name = field
            .ident
            .as_ref()
            .cloned()
            .expect("no name on struct field i.e. tuple structs unsupported");

        let (tag, slice) = extract_attrs(&name, &field.attrs);

        Self { name, tag, slice }
    }
}

fn extract_attrs_optional_tag(name: &Ident, attrs: &[Attribute]) -> (Option<u8>, bool) {
    let mut tag = None;
    let mut slice = false;

    for attr in attrs {
        if !attr.path.is_ident("tlv") {
            continue;
        }

        match attr.parse_meta().expect("error parsing `tlv` attribute") {
            Meta::List(MetaList { nested, .. }) if !nested.is_empty() => {
                for entry in nested {
                    match entry {
                        NestedMeta::Meta(Meta::Path(path)) => {
                            if !path.is_ident("slice") {
                                panic!("unknown `tlv` attribute for field `{}`: {:?}", name, path);
                            }
                            slice = true;
                        }
                        NestedMeta::Meta(Meta::NameValue(MetaNameValue {
                            path,
                            lit: Lit::Str(lit_str),
                            ..
                        })) => {
                            // Parse the `type = "..."` attribute
                            if !path.is_ident("tag") {
                                panic!("unknown `tlv` attribute for field `{}`: {:?}", name, path);
                            }

                            if tag.is_some() {
                                panic!("duplicate SIMPLE-TLV `tag` attribute for field: {}", name);
                            }

                            let possibly_with_prefix = lit_str.value();
                            let without_prefix = possibly_with_prefix.trim_start_matches("0x");
                            let tag_value = u8::from_str_radix(without_prefix, 16).expect("tag values must be between one and 254");
                            if tag_value == 0 || tag_value == 255 {
                                panic!("SIMPLE-TLV tags must not be zero or 255");
                            }
                            tag = Some(tag_value);
                        }
                        other => panic!(
                            "a malformed `tlv` attribute for field `{}`: {:?}",
                            name, other
                        ),
                    }
                }
            }
            other => panic!(
                "malformed `tlv` attribute for field `{}`: {:#?}",
                name, other
            ),
        }
    }

    (tag, slice)
}

fn extract_attrs(name: &Ident, attrs: &[Attribute]) -> (u8, bool) {
    let (tag, slice) = extract_attrs_optional_tag(name, attrs);

    if let Some(tag) = tag {
        (tag, slice)
    } else {
        panic!("SIMPLE-TLV tag missing for `{}`", name);
    }
}