summaryrefslogtreecommitdiffstats
path: root/third_party/rust/weedle2/src/argument.rs
blob: 8c0e085f20e0f58086bdb1d5b7a2cebcb389f374 (plain)
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
use crate::attribute::ExtendedAttributeList;
use crate::common::{Default, Identifier, Punctuated};
use crate::types::{AttributedType, Type};

/// Parses a list of argument. Ex: `double v1, double v2, double v3, optional double alpha`
pub type ArgumentList<'a> = Punctuated<Argument<'a>, term!(,)>;

ast_types! {
    /// Parses an argument. Ex: `double v1|double... v1s`
    enum Argument<'a> {
        /// Parses `[attributes]? optional? attributedtype identifier ( = default )?`
        ///
        /// Note: `= default` is only allowed if `optional` is present
        Single(struct SingleArgument<'a> {
            attributes: Option<ExtendedAttributeList<'a>>,
            optional: Option<term!(optional)>,
            type_: AttributedType<'a>,
            identifier: Identifier<'a>,
            default: Option<Default<'a>> = nom::combinator::map(
                nom::combinator::cond(optional.is_some(), weedle!(Option<Default<'a>>)),
                |default| default.unwrap_or(None)
            ),
        }),
        /// Parses `[attributes]? type... identifier`
        Variadic(struct VariadicArgument<'a> {
            attributes: Option<ExtendedAttributeList<'a>>,
            type_: Type<'a>,
            ellipsis: term!(...),
            identifier: Identifier<'a>,
        }),
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::literal::{DecLit, DefaultValue, IntegerLit};
    use crate::Parse;

    test!(should_parse_single_argument { "short a" =>
        "";
        SingleArgument;
        attributes.is_none();
        optional.is_none();
        identifier.0 == "a";
        default.is_none();
    });

    test!(should_parse_variadic_argument { "short... a" =>
        "";
        VariadicArgument;
        attributes.is_none();
        identifier.0 == "a";
    });

    test!(should_parse_optional_single_argument { "optional short a" =>
        "";
        SingleArgument;
        attributes.is_none();
        optional.is_some();
        identifier.0 == "a";
        default.is_none();
    });

    test!(should_parse_optional_single_argument_with_default { "optional short a = 5" =>
        "";
        SingleArgument;
        attributes.is_none();
        optional.is_some();
        identifier.0 == "a";
        default == Some(Default {
            assign: term!(=),
            value: DefaultValue::Integer(IntegerLit::Dec(DecLit("5"))),
        });
    });
}