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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
//! Code Generation module

use std::collections::HashMap;

use heck::{ToShoutySnakeCase, ToSnakeCase};
use proc_macro2::{Ident, Literal, Span, TokenStream};

use quote::quote;

use lazy_static::lazy_static;

use crate::error::Error;
use crate::resolver::Resolver;

use crate::resolver::asn::structs::types::Asn1ResolvedType;

/// Supported Codecs
#[derive(clap::ValueEnum, Clone, Debug, PartialEq, Eq, Hash)]
pub enum Codec {
    /// Generate code for ASN.1 APER Codec
    Aper,
}

/// Supported Derive Macros
#[derive(clap::ValueEnum, Clone, Debug, PartialEq, Eq, Hash)]
pub enum Derive {
    /// Generate `Debug` code for the generated strucutres.
    Debug,

    /// Generate 'Clone' code for the generated structures.
    Clone,

    /// Generate 'serde::Serialize' code for the generated structures.
    Serialize,

    /// Generate 'serde::Deserialize' code for the generated structures.
    Deserialize,
}

/// Visibility to be used for the generated Structs, Enums etc.
#[derive(clap::ValueEnum, Clone, Debug)]
pub enum Visibility {
    /// Visibility is Public
    Public,
    /// Visibility is Crate
    Crate,
    /// Visibility is Private
    Private,
}

lazy_static! {
    static ref CODEC_TOKENS: HashMap<Codec, String> = {
        let mut m = HashMap::new();
        m.insert(Codec::Aper, "asn1_codecs_derive::AperCodec".to_string());
        m
    };
    static ref DERIVE_TOKENS: HashMap<Derive, String> = {
        let mut m = HashMap::new();
        m.insert(Derive::Debug, "Debug".to_string());
        m.insert(Derive::Clone, "Clone".to_string());
        m.insert(Derive::Serialize, "serde::Serialize".to_string());
        m.insert(Derive::Deserialize, "serde::Deserialize".to_string());
        m
    };
}

#[derive(Debug)]
pub(crate) struct Generator {
    // Generated Tokens for the module.
    pub(crate) items: Vec<TokenStream>,

    // A counter to uniquify certain names
    pub(crate) counter: usize,

    // Auxillary Items: These are structs/that are referenced inside constructed type.
    pub(crate) aux_items: Vec<TokenStream>,

    // Visibility: Visibility of Generated Items
    pub(crate) visibility: Visibility,

    // codecs
    pub(crate) codecs: Vec<Codec>,

    // Derives
    pub(crate) derives: Vec<Derive>,
}

impl Generator {
    pub(crate) fn new(visibility: &Visibility, codecs: Vec<Codec>, derives: Vec<Derive>) -> Self {
        Generator {
            items: vec![],
            counter: 1,
            aux_items: vec![],
            visibility: visibility.clone(),
            codecs,
            derives,
        }
    }

    // Generates the code using the information from the `Resolver`. Returns a String
    // containing all the code (which is basically a `format!` of the `TokenStream`.
    pub(crate) fn generate(&mut self, resolver: &Resolver) -> Result<String, Error> {
        // FIXME: Not sure how to make sure the crates defined here are a dependency.
        // May be can just do with documenting it.
        let use_tokens = self.generate_use_tokens();
        self.items.push(use_tokens);

        let mut items = vec![];
        for (k, t) in resolver.get_resolved_types() {
            let item = Asn1ResolvedType::generate_for_type(k, t, self)?;
            if let Some(it) = item {
                items.push(it)
            }
        }

        for aux in &self.aux_items {
            items.push(aux.clone())
        }

        self.items.extend(items);

        Ok(self
            .items
            .iter()
            .map(|t| t.to_string())
            .collect::<Vec<String>>()
            .join("\n\n"))
    }

    pub(crate) fn to_type_ident(&self, name: &str) -> Ident {
        Ident::new(
            &capitalize_first(name).replace('-', "_").replace(' ', "_"),
            Span::call_site(),
        )
    }

    pub(crate) fn to_const_ident(&self, name: &str) -> Ident {
        Ident::new(&name.to_shouty_snake_case(), Span::call_site())
    }

    pub(crate) fn to_value_ident(&self, name: &str) -> Ident {
        let mut val = capitalize_first(name).to_snake_case();
        if val == *"type" {
            val = "typ".to_string()
        }
        Ident::new(&val, Span::call_site())
    }

    pub(crate) fn to_inner_type(&self, bits: u8, signed: bool) -> TokenStream {
        if !signed {
            match bits {
                8 => quote!(u8),
                16 => quote!(u16),
                32 => quote!(u32),
                64 => quote!(u64),
                _ => quote!(u64),
            }
        } else {
            match bits {
                8 => quote!(i8),
                16 => quote!(i16),
                32 => quote!(i32),
                64 => quote!(i64),
                _ => quote!(i64),
            }
        }
    }

    pub(crate) fn to_suffixed_literal(&self, bits: u8, signed: bool, value: i128) -> Literal {
        if !signed {
            match bits {
                8 => Literal::u8_suffixed(value as u8),
                16 => Literal::u16_suffixed(value as u16),
                32 => Literal::u32_suffixed(value as u32),
                64 => Literal::u64_suffixed(value as u64),
                _ => Literal::u64_suffixed(value as u64),
            }
        } else {
            match bits {
                8 => Literal::i8_suffixed(value as i8),
                16 => Literal::i16_suffixed(value as i16),
                32 => Literal::i32_suffixed(value as i32),
                64 => Literal::i64_suffixed(value as i64),
                _ => Literal::i64_suffixed(value as i64),
            }
        }
    }

    pub(crate) fn get_unique_name(&mut self, name: &str) -> String {
        self.counter += 1;

        format!("{} {}", name, self.counter)
    }

    pub(crate) fn get_visibility_tokens(&self) -> TokenStream {
        match self.visibility {
            Visibility::Public => quote! { pub },
            Visibility::Crate => quote! { pub(crate) },
            Visibility::Private => quote! {},
        }
    }

    fn generate_use_tokens(&self) -> TokenStream {
        quote! {
            use bitvec::vec::BitVec;
            use bitvec::order::Msb0;
        }
    }

    pub(crate) fn generate_derive_tokens(&self) -> TokenStream {
        let mut tokens = vec![];
        for codec in &self.codecs {
            let codec_token = CODEC_TOKENS.get(codec).unwrap();
            tokens.push(codec_token.to_string());
        }

        for derive in &self.derives {
            let derive_token = DERIVE_TOKENS.get(derive).unwrap();
            tokens.push(derive_token.to_string());
        }

        let token_string = tokens.join(",");

        let derive_token_string = format!("#[derive({})]\n", token_string);
        let derive_token_stream: TokenStream = derive_token_string.parse().unwrap();
        derive_token_stream
    }
}

fn capitalize_first(input: &str) -> String {
    if !input.is_empty() {
        let mut input = input.to_string();
        let (first, _) = input.split_at_mut(1);
        first.make_ascii_uppercase();

        input
    } else {
        input.to_string()
    }
}

#[cfg(test)]
mod tests {

    use super::*;

    #[test]
    fn test_capitalize_first_empty() {
        let empty = "".to_string();
        let capitalized = capitalize_first(&empty);
        assert_eq!(capitalized, empty);
    }

    #[test]
    fn test_capitalize_first_single_letter() {
        let empty = "a".to_string();
        let capitalized = capitalize_first(&empty);
        assert_eq!(capitalized, "A");
    }

    #[test]
    fn test_capitalize_first_word() {
        let empty = "amfTnlAssociationToAddItem".to_string();
        let capitalized = capitalize_first(&empty);
        assert_eq!(capitalized, "AmfTnlAssociationToAddItem");
    }
}