kotlin_poet_rs/spec/
argument.rs

1use crate::io::RenderKotlin;
2use crate::spec::{CodeBlock, Name};
3use crate::tokens;
4
5/// Function argument, consists of pair name and value.
6/// If name is [None] is considered as positional argument.
7///
8/// Set of function arguments could is usually represented as [Vec<Argument>].
9///
10/// # Examples
11///
12/// ## Named argument
13/// ```rust
14/// use kotlin_poet_rs::spec::{CodeBlock, Name, Argument};
15/// use kotlin_poet_rs::io::RenderKotlin;
16///
17/// let argument = Argument::new_named(
18///      Name::from("name"), CodeBlock::atom("value")
19/// );
20///
21/// assert_eq!(argument.render_string(), "name = value");
22/// ```
23///
24/// ## Positional argument
25/// ```rust
26/// use kotlin_poet_rs::spec::{CodeBlock, Name, Argument};
27/// use kotlin_poet_rs::io::RenderKotlin;
28///
29/// let argument = Argument::new_positional(
30///     CodeBlock::statement("value")
31/// );
32///
33/// assert_eq!(argument.render_string(), "value");
34/// ```
35#[derive(Debug, Clone)]
36pub struct Argument {
37    name: Option<Name>,
38    value: CodeBlock,
39}
40
41impl Argument {
42    /// Creates new positional argument
43    pub fn new_positional<CodeBlockLike: Into<CodeBlock>>(value: CodeBlockLike) -> Self {
44        Argument {
45            name: None,
46            value: value.into(),
47        }
48    }
49
50    /// Creates new named argument
51    pub fn new_named<NameLike: Into<Name>, CodeBlockLike: Into<CodeBlock>>(name: NameLike, value: CodeBlockLike) -> Self {
52        Argument {
53            name: Some(name.into()),
54            value: value.into(),
55        }
56    }
57}
58
59impl RenderKotlin for Argument {
60    fn render_into(&self, block: &mut CodeBlock) {
61        if let Some(name) = &self.name {
62            block.push_renderable(name);
63            block.push_space();
64            block.push_static_atom(tokens::ASSIGN);
65            block.push_space();
66        }
67        block.push_atom(self.value.to_string().as_str());
68    }
69}
70
71#[cfg(test)]
72mod tests {
73    use crate::spec::{CodeBlock, Name, Argument};
74    use crate::io::RenderKotlin;
75
76    #[test]
77    fn test_rendering() {
78        let argument = Argument::new_positional(CodeBlock::statement("value"));
79        assert_eq!(argument.render_string(), "value");
80
81        let argument = Argument::new_named(Name::from("name"), CodeBlock::atom("value"), );
82        println!("{}", argument.render_string());
83        assert_eq!(argument.render_string(), "name = value");
84    }
85}