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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
use super::attributes::AttributeLocation;
use super::{utils::*, Attribute, Visibility};
use crate::prelude::{Delimiter, Ident, Literal, Span, TokenTree};
use crate::{Error, Result};
use std::iter::Peekable;

/// The body of a struct
#[derive(Debug)]
pub struct StructBody {
    /// The fields of this struct, `None` if this struct has no fields
    pub fields: Option<Fields>,
}

impl StructBody {
    pub(crate) fn take(input: &mut Peekable<impl Iterator<Item = TokenTree>>) -> Result<Self> {
        match input.peek() {
            Some(TokenTree::Group(_)) => {}
            Some(TokenTree::Punct(p)) if p.as_char() == ';' => {
                return Ok(StructBody { fields: None })
            }
            token => return Error::wrong_token(token, "group or punct"),
        }
        let group = assume_group(input.next());
        let mut stream = group.stream().into_iter().peekable();
        let fields = match group.delimiter() {
            Delimiter::Brace => {
                let fields = UnnamedField::parse_with_name(&mut stream)?;
                if fields.is_empty() {
                    None
                } else {
                    Some(Fields::Struct(fields))
                }
            }
            Delimiter::Parenthesis => {
                let fields = UnnamedField::parse(&mut stream)?;
                if fields.is_empty() {
                    None
                } else {
                    Some(Fields::Tuple(fields))
                }
            }
            found => {
                return Err(Error::InvalidRustSyntax {
                    span: group.span(),
                    expected: format!("brace or parenthesis, found {:?}", found),
                })
            }
        };
        Ok(StructBody { fields })
    }
}

#[test]
fn test_struct_body_take() {
    use crate::token_stream;

    let stream = &mut token_stream(
        "struct Foo { pub bar: u8, pub(crate) baz: u32, bla: Vec<Box<dyn Future<Output = ()>>> }",
    );
    let (data_type, ident) = super::DataType::take(stream).unwrap();
    assert_eq!(data_type, super::DataType::Struct);
    assert_eq!(ident, "Foo");
    let body = StructBody::take(stream).unwrap();
    let fields = body.fields.as_ref().unwrap();

    assert_eq!(fields.len(), 3);
    let (ident, field) = fields.get(0).unwrap();
    assert_eq!(ident.unwrap(), "bar");
    assert_eq!(field.vis, Visibility::Pub);
    assert_eq!(field.type_string(), "u8");

    let (ident, field) = fields.get(1).unwrap();
    assert_eq!(ident.unwrap(), "baz");
    assert_eq!(field.vis, Visibility::Pub);
    assert_eq!(field.type_string(), "u32");

    let (ident, field) = fields.get(2).unwrap();
    assert_eq!(ident.unwrap(), "bla");
    assert_eq!(field.vis, Visibility::Default);
    assert_eq!(field.type_string(), "Vec<Box<dynFuture<Output=()>>>");

    let stream = &mut token_stream(
        "struct Foo ( pub u8, pub(crate) u32, Vec<Box<dyn Future<Output = ()>>> )",
    );
    let (data_type, ident) = super::DataType::take(stream).unwrap();
    assert_eq!(data_type, super::DataType::Struct);
    assert_eq!(ident, "Foo");
    let body = StructBody::take(stream).unwrap();
    let fields = body.fields.as_ref().unwrap();

    assert_eq!(fields.len(), 3);

    let (ident, field) = fields.get(0).unwrap();
    assert!(ident.is_none());
    assert_eq!(field.vis, Visibility::Pub);
    assert_eq!(field.type_string(), "u8");

    let (ident, field) = fields.get(1).unwrap();
    assert!(ident.is_none());
    assert_eq!(field.vis, Visibility::Pub);
    assert_eq!(field.type_string(), "u32");

    let (ident, field) = fields.get(2).unwrap();
    assert!(ident.is_none());
    assert_eq!(field.vis, Visibility::Default);
    assert_eq!(field.type_string(), "Vec<Box<dynFuture<Output=()>>>");

    let stream = &mut token_stream("struct Foo;");
    let (data_type, ident) = super::DataType::take(stream).unwrap();
    assert_eq!(data_type, super::DataType::Struct);
    assert_eq!(ident, "Foo");
    let body = StructBody::take(stream).unwrap();
    assert!(body.fields.is_none());

    let stream = &mut token_stream("struct Foo {}");
    let (data_type, ident) = super::DataType::take(stream).unwrap();
    assert_eq!(data_type, super::DataType::Struct);
    assert_eq!(ident, "Foo");
    let body = StructBody::take(stream).unwrap();
    assert!(body.fields.is_none());

    let stream = &mut token_stream("struct Foo ()");
    let (data_type, ident) = super::DataType::take(stream).unwrap();
    assert_eq!(data_type, super::DataType::Struct);
    assert_eq!(ident, "Foo");
    let body = StructBody::take(stream).unwrap();
    assert!(body.fields.is_none());
}

/// The body of an enum
#[derive(Debug)]
pub struct EnumBody {
    /// The enum's variants
    pub variants: Vec<EnumVariant>,
}

impl EnumBody {
    pub(crate) fn take(input: &mut Peekable<impl Iterator<Item = TokenTree>>) -> Result<Self> {
        match input.peek() {
            Some(TokenTree::Group(_)) => {}
            Some(TokenTree::Punct(p)) if p.as_char() == ';' => {
                return Ok(EnumBody {
                    variants: Vec::new(),
                })
            }
            token => return Error::wrong_token(token, "group or ;"),
        }
        let group = assume_group(input.next());
        let mut variants = Vec::new();
        let stream = &mut group.stream().into_iter().peekable();
        while stream.peek().is_some() {
            let attributes = Attribute::try_take(AttributeLocation::Variant, stream)?;
            let ident = match super::utils::consume_ident(stream) {
                Some(ident) => ident,
                None => Error::wrong_token(stream.peek(), "ident")?,
            };

            let mut fields = None;
            let mut value = None;

            if let Some(TokenTree::Group(_)) = stream.peek() {
                let group = assume_group(stream.next());
                let stream = &mut group.stream().into_iter().peekable();
                match group.delimiter() {
                    Delimiter::Brace => {
                        fields = Some(Fields::Struct(UnnamedField::parse_with_name(stream)?));
                    }
                    Delimiter::Parenthesis => {
                        fields = Some(Fields::Tuple(UnnamedField::parse(stream)?));
                    }
                    delim => {
                        return Err(Error::InvalidRustSyntax {
                            span: group.span(),
                            expected: format!("Brace or parenthesis, found {:?}", delim),
                        })
                    }
                }
            }
            match stream.peek() {
                Some(TokenTree::Punct(p)) if p.as_char() == '=' => {
                    assume_punct(stream.next(), '=');
                    match stream.next() {
                        Some(TokenTree::Literal(lit)) => {
                            value = Some(lit);
                        }
                        Some(TokenTree::Punct(p)) if p.as_char() == '-' => match stream.next() {
                            Some(TokenTree::Literal(lit)) => {
                                match lit.to_string().parse::<i64>() {
                                    Ok(val) => value = Some(Literal::i64_unsuffixed(-val)),
                                    Err(_) => {
                                        return Err(Error::custom_at(
                                            "parse::<i64> failed",
                                            lit.span(),
                                        ))
                                    }
                                };
                            }
                            token => return Error::wrong_token(token.as_ref(), "literal"),
                        },
                        token => return Error::wrong_token(token.as_ref(), "literal"),
                    }
                }
                Some(TokenTree::Punct(p)) if p.as_char() == ',' => {
                    // next field
                }
                None => {
                    // group done
                }
                token => return Error::wrong_token(token, "group, comma or ="),
            }

            consume_punct_if(stream, ',');

            variants.push(EnumVariant {
                name: ident,
                fields,
                value,
                attributes,
            });
        }

        Ok(EnumBody { variants })
    }
}

#[test]
fn test_enum_body_take() {
    use crate::token_stream;

    let stream = &mut token_stream("enum Foo { }");
    let (data_type, ident) = super::DataType::take(stream).unwrap();
    assert_eq!(data_type, super::DataType::Enum);
    assert_eq!(ident, "Foo");
    let body = EnumBody::take(stream).unwrap();
    assert!(body.variants.is_empty());

    let stream = &mut token_stream("enum Foo { Bar, Baz(u8), Blah { a: u32, b: u128 } }");
    let (data_type, ident) = super::DataType::take(stream).unwrap();
    assert_eq!(data_type, super::DataType::Enum);
    assert_eq!(ident, "Foo");
    let body = EnumBody::take(stream).unwrap();
    assert_eq!(3, body.variants.len());

    assert_eq!(body.variants[0].name, "Bar");
    assert!(body.variants[0].fields.is_none());

    assert_eq!(body.variants[1].name, "Baz");
    assert!(body.variants[1].fields.is_some());
    let fields = body.variants[1].fields.as_ref().unwrap();
    assert_eq!(1, fields.len());
    let (ident, field) = fields.get(0).unwrap();
    assert!(ident.is_none());
    assert_eq!(field.type_string(), "u8");

    assert_eq!(body.variants[2].name, "Blah");
    assert!(body.variants[2].fields.is_some());
    let fields = body.variants[2].fields.as_ref().unwrap();
    assert_eq!(2, fields.len());
    let (ident, field) = fields.get(0).unwrap();
    assert_eq!(ident.unwrap(), "a");
    assert_eq!(field.type_string(), "u32");
    let (ident, field) = fields.get(1).unwrap();
    assert_eq!(ident.unwrap(), "b");
    assert_eq!(field.type_string(), "u128");

    let stream = &mut token_stream("enum Foo { Bar = -1, Baz = 2 }");
    let (data_type, ident) = super::DataType::take(stream).unwrap();
    assert_eq!(data_type, super::DataType::Enum);
    assert_eq!(ident, "Foo");
    let body = EnumBody::take(stream).unwrap();
    assert_eq!(2, body.variants.len());

    assert_eq!(body.variants[0].name, "Bar");
    assert!(body.variants[0].fields.is_none());
    assert_eq!(body.variants[0].get_integer(), -1);

    assert_eq!(body.variants[1].name, "Baz");
    assert!(body.variants[1].fields.is_none());
    assert_eq!(body.variants[1].get_integer(), 2);

    let stream = &mut token_stream("enum Foo { Bar(i32) = -1, Baz { a: i32 } = 2 }");
    let (data_type, ident) = super::DataType::take(stream).unwrap();
    assert_eq!(data_type, super::DataType::Enum);
    assert_eq!(ident, "Foo");
    let body = EnumBody::take(stream).unwrap();
    assert_eq!(2, body.variants.len());

    assert_eq!(body.variants[0].name, "Bar");
    assert!(body.variants[0].fields.is_some());
    let fields = body.variants[0].fields.as_ref().unwrap();
    assert_eq!(fields.len(), 1);
    assert_eq!(body.variants[0].get_integer(), -1);

    assert_eq!(body.variants[1].name, "Baz");
    assert!(body.variants[1].fields.is_some());
    let fields = body.variants[1].fields.as_ref().unwrap();
    assert_eq!(fields.len(), 1);
    assert_eq!(body.variants[1].get_integer(), 2);
}

/// A variant of an enum
#[derive(Debug)]
pub struct EnumVariant {
    /// The name of the variant
    pub name: Ident,
    /// The field of the variant. See [`Fields`] for more info
    pub fields: Option<Fields>,
    /// The value of this variant. This can be one of:
    /// - `Baz = 5`
    /// - `Baz(i32) = 5`
    /// - `Baz { a: i32} = 5`
    /// In either case this value will be `Some(Literal::i32(5))`
    pub value: Option<Literal>,
    /// The attributes of this variant
    pub attributes: Vec<Attribute>,
}

#[cfg(test)]
impl EnumVariant {
    fn get_integer(&self) -> i64 {
        let value = self.value.as_ref().expect("Variant has no value");
        value
            .to_string()
            .parse()
            .expect("Value is not a valid integer")
    }
}

/// The different field types an enum variant can have.
#[derive(Debug)]
pub enum Fields {
    /// Tuple-like variant
    /// ```rs
    /// enum Foo {
    ///     Baz(u32)
    /// }
    /// struct Bar(u32);
    /// ```
    Tuple(Vec<UnnamedField>),

    /// Struct-like variant
    /// ```rs
    /// enum Foo {
    ///     Baz {
    ///         baz: u32
    ///     }
    /// }
    /// struct Bar {
    ///     baz: u32
    /// }
    /// ```
    Struct(Vec<(Ident, UnnamedField)>),
}

impl Fields {
    /// Returns a list of names for the variant.
    ///
    /// ```
    /// enum Foo {
    ///     C(u32, u32), // will return `vec[Index { index: 0 }, Index { index: 1 }]`
    ///     D { a: u32, b: u32 }, // will return `vec[Ident { ident: "a" }, Ident { ident: "b" }]`
    /// }
    pub fn names(&self) -> Vec<IdentOrIndex> {
        let result: Vec<IdentOrIndex> = match self {
            Self::Tuple(fields) => fields
                .iter()
                .enumerate()
                .map(|(index, field)| IdentOrIndex::Index {
                    index,
                    span: field.span(),
                    attributes: &field.attributes,
                })
                .collect(),
            Self::Struct(fields) => fields
                .iter()
                .map(|(ident, field)| IdentOrIndex::Ident {
                    ident,
                    attributes: &field.attributes,
                })
                .collect(),
        };
        if cfg!(test) {
            assert!(!result.is_empty());
        }
        result
    }

    /// Return the delimiter of the group for this variant
    ///
    /// ```
    /// enum Foo {
    ///     C(u32, u32), // will return `Delimiter::Paranthesis`
    ///     D { a: u32, b: u32 }, // will return `Delimiter::Brace`
    /// }
    /// ```
    pub fn delimiter(&self) -> Delimiter {
        match self {
            Self::Tuple(_) => Delimiter::Parenthesis,
            Self::Struct(_) => Delimiter::Brace,
        }
    }
}

#[cfg(test)]
impl Fields {
    fn len(&self) -> usize {
        match self {
            Self::Tuple(fields) => fields.len(),
            Self::Struct(fields) => fields.len(),
        }
    }

    fn get(&self, index: usize) -> Option<(Option<&Ident>, &UnnamedField)> {
        match self {
            Self::Tuple(fields) => fields.get(index).map(|f| (None, f)),
            Self::Struct(fields) => fields.get(index).map(|(ident, field)| (Some(ident), field)),
        }
    }
}

/// An unnamed field
#[derive(Debug)]
pub struct UnnamedField {
    /// The visibility of the field
    pub vis: Visibility,
    /// The type of the field
    pub r#type: Vec<TokenTree>,
    /// The attributes of the field
    pub attributes: Vec<Attribute>,
}

impl UnnamedField {
    pub(crate) fn parse_with_name(
        input: &mut Peekable<impl Iterator<Item = TokenTree>>,
    ) -> Result<Vec<(Ident, Self)>> {
        let mut result = Vec::new();
        loop {
            let attributes = Attribute::try_take(AttributeLocation::Field, input)?;
            let vis = Visibility::try_take(input)?;

            let ident = match input.peek() {
                Some(TokenTree::Ident(_)) => assume_ident(input.next()),
                Some(x) => {
                    return Err(Error::InvalidRustSyntax {
                        span: x.span(),
                        expected: format!("ident or end of group, got {:?}", x),
                    })
                }
                None => break,
            };
            match input.peek() {
                Some(TokenTree::Punct(p)) if p.as_char() == ':' => {
                    input.next();
                }
                token => return Error::wrong_token(token, ":"),
            }
            let r#type = read_tokens_until_punct(input, &[','])?;
            consume_punct_if(input, ',');
            result.push((
                ident,
                Self {
                    vis,
                    r#type,
                    attributes,
                },
            ));
        }
        Ok(result)
    }

    pub(crate) fn parse(
        input: &mut Peekable<impl Iterator<Item = TokenTree>>,
    ) -> Result<Vec<Self>> {
        let mut result = Vec::new();
        while input.peek().is_some() {
            let attributes = Attribute::try_take(AttributeLocation::Field, input)?;
            let vis = Visibility::try_take(input)?;

            let r#type = read_tokens_until_punct(input, &[','])?;
            consume_punct_if(input, ',');
            result.push(Self {
                vis,
                r#type,
                attributes,
            });
        }
        Ok(result)
    }

    /// Return [`type`] as a string. Useful for comparing it for known values.
    ///
    /// [`type`]: #structfield.type
    pub fn type_string(&self) -> String {
        self.r#type.iter().map(|t| t.to_string()).collect()
    }

    /// Return the span of [`type`].
    ///
    /// **note**: Until <https://github.com/rust-lang/rust/issues/54725> is stable, this will return the first span of the type instead
    ///
    /// [`type`]: #structfield.type
    pub fn span(&self) -> Span {
        // BlockedTODO: https://github.com/rust-lang/rust/issues/54725
        // Span::join is unstable
        // if let Some(first) = self.r#type.first() {
        //     let mut span = first.span();
        //     for token in self.r#type.iter().skip(1) {
        //         span = span.join(span).unwrap();
        //     }
        //     span
        // } else {
        //     Span::call_site()
        // }

        match self.r#type.first() {
            Some(first) => first.span(),
            None => Span::call_site(),
        }
    }
}

/// Reference to an enum variant's field. Either by index or by ident.
///
/// ```
/// enum Foo {
///     Bar(u32), // will be IdentOrIndex::Index { index: 0, .. }
///     Baz {
///         a: u32, // will be IdentOrIndex::Ident { ident: "a", .. }
///     },
/// }
#[derive(Debug)]
pub enum IdentOrIndex<'a> {
    /// The variant is a named field
    Ident {
        /// The name of the field
        ident: &'a Ident,
        /// The attributes of the field
        attributes: &'a Vec<Attribute>,
    },
    /// The variant is an unnamed field
    Index {
        /// The field index
        index: usize,
        /// The span of the field type
        span: Span,
        /// The attributes of this field
        attributes: &'a Vec<Attribute>,
    },
}

impl<'a> IdentOrIndex<'a> {
    /// Get the ident. Will panic if this is an `IdentOrIndex::Index`
    pub fn unwrap_ident(&self) -> &'a Ident {
        match self {
            Self::Ident { ident, .. } => ident,
            x => panic!("Expected ident, found {:?}", x),
        }
    }

    /// Convert this ident into a TokenTree. If this is an `Index`, will return `prefix + index` instead.
    pub fn to_token_tree_with_prefix(&self, prefix: &str) -> TokenTree {
        TokenTree::Ident(match self {
            IdentOrIndex::Ident { ident, .. } => (*ident).clone(),
            IdentOrIndex::Index { index, span, .. } => {
                let name = format!("{}{}", prefix, index);
                Ident::new(&name, *span)
            }
        })
    }

    /// Return either the index or the ident of this field with a fixed prefix. The prefix will always be added.
    pub fn to_string_with_prefix(&self, prefix: &str) -> String {
        match self {
            IdentOrIndex::Ident { ident, .. } => ident.to_string(),
            IdentOrIndex::Index { index, .. } => {
                format!("{}{}", prefix, index)
            }
        }
    }

    /// Returns the attributes of this field.
    pub fn attributes(&self) -> &Vec<Attribute> {
        match self {
            Self::Ident { attributes, .. } => attributes,
            Self::Index { attributes, .. } => attributes,
        }
    }
}

impl std::fmt::Display for IdentOrIndex<'_> {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            IdentOrIndex::Ident { ident, .. } => write!(fmt, "{}", ident),
            IdentOrIndex::Index { index, .. } => write!(fmt, "{}", index),
        }
    }
}

#[test]
fn enum_explicit_variants() {
    use crate::token_stream;
    let stream = &mut token_stream("{ A = 1, B = 2 }");
    let body = EnumBody::take(stream).unwrap();
    assert_eq!(body.variants.len(), 2);
}