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
use crate::lua_generator::{LuaGenerator, ToLua};
use crate::nodes::{
    Expression,
    StringExpression,
    TableExpression,
};

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Arguments {
    Tuple(Vec<Expression>),
    String(StringExpression),
    Table(TableExpression),
}

impl Arguments {
    pub fn to_expressions(self) -> Vec<Expression> {
        match self {
            Self::Tuple(expressions) => expressions,
            Self::String(string) => vec![string.into()],
            Self::Table(table) => vec![table.into()],
        }
    }

    pub fn append_argument<T: Into<Expression>>(self, argument: T) -> Self {
        let mut expressions = self.to_expressions();
        expressions.push(argument.into());
        Arguments::Tuple(expressions)
    }
}

impl Default for Arguments {
    fn default() -> Self {
        Arguments::Tuple(Vec::new())
    }
}

impl ToLua for Arguments {
    fn to_lua(&self, generator: &mut LuaGenerator) {
        match self {
            Self::String(string) => string.to_lua(generator),
            Self::Table(table) => table.to_lua(generator),
            Self::Tuple(expressions) => {
                generator.push_char_force_without_space('(');

                let last_index = expressions.len().checked_sub(1).unwrap_or(0);
                expressions.iter().enumerate()
                    .for_each(|(index, expression)| {
                        expression.to_lua(generator);

                        if index != last_index {
                            generator.push_char(',');
                        }
                    });

                generator.push_char(')');
            }
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    mod snapshot {
        use super::*;

        use insta::assert_snapshot;

        fn get_expression() -> Expression {
            Expression::Identifier("foo".to_owned()).into()
        }

        #[test]
        fn empty_tuple() {
            assert_snapshot!("empty_tuple", Arguments::Tuple(vec![]).to_lua_string());
        }

        #[test]
        fn single_argument() {
            let arguments = Arguments::Tuple(vec![get_expression()]);

            assert_snapshot!("single_argument", arguments.to_lua_string());
        }

        #[test]
        fn two_arguments() {
            let arguments = Arguments::Tuple(vec![
                get_expression(),
                get_expression(),
            ]);

            assert_snapshot!("two_arguments", arguments.to_lua_string());
        }
    }
}