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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
#![recursion_limit = "256"]

extern crate proc_macro;
extern crate proc_macro2;
extern crate quote;
extern crate syn;

use proc_macro2::{Span, TokenStream};
use quote::{quote, ToTokens};
use syn::{
    parse::{Parse, ParseStream},
    token, Attribute, Data, DeriveInput, Error, Ident, Lit, Meta, Result, Token, Type, TypeArray,
    TypePath,
};

#[proc_macro_derive(NlaType, attributes(tbname, nla_type, nla_nest))]
pub fn derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let input = syn::parse_macro_input!(input as DeriveInput);
    _derive(input)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

fn _derive(input: DeriveInput) -> Result<TokenStream> {
    let data = match &input.data {
        Data::Enum(d) => d,
        _ => return Err(Error::new(Span::call_site(), "expected enum")),
    };

    let ident = &input.ident;
    // implements TryFrom<u16>, Into<usize> and Into<u16> for Enum
    let mut ret = quote! {
        impl std::convert::TryFrom<u16> for #ident {
            type Error = Errno;

            fn try_from(v: u16) -> std::result::Result<Self, Self::Error> {
                if v >= Self::_MAX as u16 {
                    Err(Errno(libc::ERANGE))
                } else {
                    unsafe { Ok(::std::mem::transmute::<u16, Self>(v)) }
                }
            }
        }
        #[allow(clippy::from_over_into)]
        impl std::convert::Into<usize> for #ident {
            fn into(self) -> usize {
                self as usize
            }
        }
        #[allow(clippy::from_over_into)]
        impl std::convert::Into<u16> for #ident {
            fn into(self) -> u16 {
                self as u16
            }
        }
    };

    // get getter and putter for each attr
    let mut getfns: Vec<TokenStream> = Vec::new();
    let mut putfns: Vec<TokenStream> = Vec::new();
    for var in data.variants.iter() {
        for attr in var.attrs.iter() {
            if let Some((getfn, putfn)) = parse_var_attr(&ident, &var.ident, attr)? {
                getfns.push(getfn);
                putfns.push(putfn);
            }
        }
    }

    if putfns.len() > 0 {
        ret = quote! {
            #ret
            impl #ident {
                #(#putfns)*
            }
        };
    }

    // tbname="..."
    let tb_idents: Vec<_> = input
        .attrs
        .iter()
        .map(|attr| parse_attr(attr).ok()?)
        .filter(|x| x.is_some())
        .map(|x| x.unwrap())
        .collect();
    if tb_idents.len() == 0 {
        return Ok(ret);
    }

    // implements AttrTbl
    // XXX: should check multiple tbname specified
    let tbid = &tb_idents[0];
    ret = quote! {
        #ret
        pub struct #tbid<'a> ([Option<&'a Attr<'a>>; #ident::_MAX as usize]);
        impl <'a> std::ops::Index<#ident> for #tbid<'a> {
            type Output = Option<&'a Attr<'a>>;

            fn index(&self, a: #ident) -> &Self::Output {
                &self.0[a as usize]
            }
        }
        impl <'a> std::ops::IndexMut<#ident> for #tbid<'a> {
            fn index_mut(&mut self, a: #ident) -> &mut Self::Output {
                &mut self.0[a as usize]
            }
        }
        impl <'a> AttrTbl<'a> for #tbid<'a> {
            type Index = #ident;
            fn new() -> Self {
                // Self(Default::default())
                Self([None; #ident::_MAX as usize])
            }
            fn _set(&mut self, i: #ident, attr: &'a Attr) {
                self[i] = Some(attr);
            }
        }
    };

    if getfns.len() == 0 {
        return Ok(ret);
    }

    return Ok(quote! {
        #ret
        impl <'a> #tbid<'a> {
            #(#getfns)*
        }
    });
}

// tbname="..."
fn parse_attr(attr: &Attribute) -> Result<Option<Ident>> {
    match &attr.path {
        path if path.is_ident("nla_type") => {
            return Err(Error::new_spanned(
                attr,
                "#[nla_ ...] is specified on variant",
            ));
        }
        path if path.is_ident("nla_nest") => {
            return Err(Error::new_spanned(
                attr,
                "#[nla_ ...] is specified on variant",
            ));
        }
        path if path.is_ident("tbname") => match attr.parse_meta()? {
            Meta::NameValue(nv) => match nv.lit {
                Lit::Str(lit_str) => {
                    return Ok(Some(Ident::new(&lit_str.value(), Span::call_site())));
                }
                _ => {
                    return Err(Error::new_spanned(attr, "#[tbname] must be a string"));
                }
            },
            _ => {
                return Err(Error::new_spanned(attr, "#[tbname] must be a name-value"));
            }
        },
        _ => return Ok(None),
    }
}

// nla_type="..." or nla_nest="..."
fn parse_var_attr(
    ei: &Ident,
    vi: &Ident,
    attr: &Attribute,
) -> Result<Option<(TokenStream, TokenStream)>> {
    if attr.path.is_ident("nla_type") {
        parse_type_attr(ei, vi, attr)
    } else if attr.path.is_ident("nla_nest") {
        parse_nest_attr(ei, vi, attr)
    } else {
        // XXX: ignore tbname
        Ok(None)
    }
}

// nla_type="(_1_, _2_)"
// 2: getter fn name
// 1: Id  	- struct name or type
//    Str	- "str"
//    CStr	- "cstr"
//    Bytes	- "bytes"
//    Array	- "["
//    Path      - mod::struct
fn parse_type_attr(
    ei: &Ident,
    vi: &Ident,
    attr: &Attribute,
) -> Result<Option<(TokenStream, TokenStream)>> {
    #[derive(Debug)]
    enum SigType {
        Id(Ident),
        Str,
        CStr,
        Bytes,
        Array(TypeArray),
        Path(TypePath),
        Flag,
    }
    impl ToTokens for SigType {
        fn to_tokens(&self, tokens: &mut TokenStream) {
            match self {
                Self::Id(i) => i.to_tokens(tokens),
                Self::Str => "str".to_tokens(tokens),
                Self::CStr => "cstr".to_tokens(tokens),
                Self::Bytes => "bytes".to_tokens(tokens),
                Self::Flag => "flag".to_tokens(tokens),
                Self::Array(a) => a.to_tokens(tokens),
                Self::Path(p) => p.to_tokens(tokens),
            }
        }
    }
    impl Parse for SigType {
        fn parse(input: ParseStream) -> Result<Self> {
            if input.peek(token::Bracket) || input.peek2(Token![:]) {
                match input.parse::<Type>()? {
                    Type::Array(t) => return Ok(Self::Array(t)),
                    Type::Path(t) => return Ok(Self::Path(t)),
                    _ => return Err(input.error("expected identifier, array type or TypePath")),
                };
            }
            match input.parse::<Ident>()? {
                s if s == "bytes" => Ok(Self::Bytes),
                s if s == "str" => Ok(Self::Str),
                s if s == "cstr" => Ok(Self::CStr),
                s if s == "flag" => Ok(Self::Flag),
                s @ _ => Ok(Self::Id(s)),
            }
        }
    }

    #[derive(Debug)]
    struct Signature {
        rtype: SigType,
        name: Ident,
    }
    impl Parse for Signature {
        fn parse(input: ParseStream) -> Result<Self> {
            let rtype = input.parse()?;
            input.parse::<Token![,]>()?;
            let name = input.parse()?;
            Ok(Signature {
                rtype: rtype,
                name: name,
            })
        }
    }

    let args = attr.parse_args::<Signature>()?;
    let name = args.name;
    let putfn = Ident::new(&format!("put_{}", name), Span::call_site());
    let tid = args.rtype;
    match tid {
        SigType::Str => Ok(Some((
            quote! {
                pub fn #name(&self) -> Result<Option<&str>> {
                    if let Some(attr) = self[#ei::#vi] {
                        Ok(Some(attr.str()?))
                    } else {
                        Ok(None)
                    }
                }
            },
            quote! {
                pub fn #putfn<'a>(nlv: &'a mut MsgVec, data: &str) -> Result<&'a mut MsgVec> {
                    nlv.put_str(#ei::#vi, data)
                }
            },
        ))),
        SigType::CStr => Ok(Some((
            quote! {
                pub fn #name(&self) -> Result<Option<&str>> {
                    if let Some(attr) = self[#ei::#vi] {
                        Ok(Some(attr.cstr()?))
                    } else {
                        Ok(None)
                    }
                }
            },
            quote! {
                pub fn #putfn<'a>(nlv: &'a mut MsgVec, data: &str) -> Result<&'a mut MsgVec> {
                    nlv.put_cstr(#ei::#vi, data)
                }
            },
        ))),
        SigType::Bytes => Ok(Some((
            quote! {
                pub fn #name(&self) -> Result<Option<&[u8]>> {
                    if let Some(attr) = self[#ei::#vi] {
                        Ok(Some(attr.bytes_ref()))
                    } else {
                        Ok(None)
                    }
                }
            },
            quote! {
                pub fn #putfn<'a>(nlv: &'a mut MsgVec, data: &[u8]) -> Result<&'a mut MsgVec> {
                    nlv.put_bytes(#ei::#vi, data)
                }
            },
        ))),
        SigType::Flag => Ok(Some((
            quote! {
                pub fn #name(&self) -> Result<bool> {
                    if let Some(attr) = self[#ei::#vi] {
                        if attr.payload_len() > 0 {
                            return Err(Errno(libc::ERANGE));
                        }
                        return Ok(true);
                    }
                    Ok(false)
                }
            },
            quote! {
                pub fn #putfn<'a>(nlv: &'a mut MsgVec) -> Result<&'a mut MsgVec> {
                    nlv.put_flag(#ei::#vi)
                }
            },
        ))),
        SigType::Id(_) | SigType::Array(_) | SigType::Path(_) => Ok(Some((
            quote! {
                pub fn #name(&self) -> Result<Option<&#tid>> {
                    if let Some(attr) = self[#ei::#vi] {
                        Ok(Some(attr.value_ref::<#tid>()?))
                    } else {
                        Ok(None)
                    }
                }
            },
            quote! {
                pub fn #putfn<'a>(nlv: &'a mut MsgVec, data: &#tid) -> Result<&'a mut MsgVec> {
                    nlv.put(#ei::#vi, data)
                }
            },
        ))),
    }
}

// nla_nest="(_1_, _2_)"
// 2: getter fn name
// 1: Id  	- struct name or type
//    Path      - mod::struct
//    ArrayId	- "[" Id
//    ArrayPath	- "[" Path
fn parse_nest_attr(
    ei: &Ident,
    vi: &Ident,
    attr: &Attribute,
) -> Result<Option<(TokenStream, TokenStream)>> {
    #[derive(Debug)]
    enum SigType {
        Id(Ident),
        Path(TypePath),
        ArrayId(Ident),
        ArrayPath(TypePath),
    }
    impl Parse for SigType {
        fn parse(input: ParseStream) -> Result<Self> {
            if input.peek(token::Bracket) {
                let content;
                let _bracket_token = syn::bracketed!(content in input);
                if content.peek2(Token![:]) {
                    return Ok(Self::ArrayPath(content.parse::<TypePath>()?));
                }
                match content.parse::<Ident>() {
                    Ok(t) => return Ok(Self::ArrayId(t)),
                    Err(_) => return Err(input.error("expected identifier or TypePath")),
                }
            } else {
                if input.peek2(Token![:]) {
                    return Ok(Self::Path(input.parse::<TypePath>()?));
                }
                match input.parse::<Ident>() {
                    Ok(t) => return Ok(Self::Id(t)),
                    Err(_) => return Err(input.error("expected identifier or TypePath")),
                }
            }
        }
    }
    impl ToTokens for SigType {
        fn to_tokens(&self, tokens: &mut TokenStream) {
            match self {
                Self::Id(i) | Self::ArrayId(i) => i.to_tokens(tokens),
                Self::Path(p) | Self::ArrayPath(p) => p.to_tokens(tokens),
            }
        }
    }

    struct Signature {
        rtype: SigType,
        name: Ident,
    }
    impl Parse for Signature {
        fn parse(input: ParseStream) -> Result<Self> {
            let rtype = input.parse()?;
            input.parse::<Token![,]>()?;
            let name = input.parse()?;
            Ok(Signature {
                rtype: rtype,
                name: name,
            })
        }
    }

    let args = attr.parse_args::<Signature>()?;
    let name = args.name;
    let tid = args.rtype;
    let startfn = Ident::new(&format!("{}_start", name), Span::call_site());
    match tid {
        SigType::ArrayId(_) | SigType::ArrayPath(_) => Ok(Some((
            quote! {
                pub fn #name(&self) -> Result<Option<Vec<#tid>>> {
                    if let Some(attr) = self[#ei::#vi] {
                        Ok(Some(attr.nest_array::<#tid>()?))
                    } else {
                        Ok(None)
                    }
                }
            },
            quote! {
                pub fn #startfn(nlv: &mut MsgVec) -> Result<&mut MsgVec> {
                    nlv.nest_start(#ei::#vi)
                }
            },
        ))),
        SigType::Id(_) | SigType::Path(_) => Ok(Some((
            quote! {
                pub fn #name(&self) -> Result<Option<#tid>> {
                    if let Some(attr) = self[#ei::#vi] {
                        Ok(Some(#tid::from_nest(attr)?))
                    } else {
                        Ok(None)
                    }
                }
            },
            quote! {
                pub fn #startfn(nlv: &mut MsgVec) -> Result<&mut MsgVec> {
                    nlv.nest_start(#ei::#vi)
                }
            },
        ))),
    }
}