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
//!
//!
//! Function pieces, specifically `Function` which is composed of `FunctionSignature`
//! and `FunctionBody`. Naturally, a `Function` can be used as a "method" for another
//! object, by specifying `self` (or some variant of it) as the first `Parameter` to
//! a `Function` object.
//!

use serde::Serialize;
use tera::{Context, Tera};

use crate::traits::SrcCode;
use crate::{Generic, Generics};

/// Represents a function or method. Determined if any `Parameter` contains `self`
#[derive(Default, Serialize)]
pub struct Function {
    signature: FunctionSignature,
    body: FunctionBody,
}

/// Represents a function/method signature in source code
#[derive(Default, Serialize)]
pub struct FunctionSignature {
    name: String,
    is_pub: bool,
    parameters: Vec<Parameter>,
    generics: Generics,
    return_ty: Option<String>,
}

impl FunctionSignature {
    /// Create a new function signature.
    pub fn new<S: ToString>(name: S) -> Self {
        let mut f = Self::default();
        f.name = name.to_string();
        f
    }

    /// Add a parameter to this signature
    pub fn add_parameter(mut self, param: Parameter) -> Self {
        self.parameters.push(param);
        self
    }

    /// Add a generic to this signature
    pub fn add_generic(mut self, generic: Generic) -> Self {
        self.generics = self.generics.add_generic(generic);
        self
    }

    /// Set a return type, if `None` will result in `()` type.
    pub fn set_return_ty<S: ToString>(mut self, ty: Option<S>) -> Self {
        self.return_ty = ty.map(|s| s.to_string());
        self
    }

    /// Set if this signature should be prefixed with `pub`
    pub fn set_is_pub(mut self, is_pub: bool) -> Self {
        self.is_pub = is_pub;
        self
    }

    /// Set the name of this function.
    pub fn set_name<S: ToString>(mut self, name: S) -> Self {
        self.name = name.to_string();
        self
    }
}

impl SrcCode for FunctionSignature {
    fn generate(&self) -> String {
        let template = r#"
        {% if self.is_pub %}pub {% endif %}fn {{ self.name }}{% if has_generics %}<{{ generic_keys | join(sep=", ") }}>{% endif %}({{ parameters | join(sep=", ") }}) -> {{ return_ty }}{% if has_generics %}
            where
                {% for generic in generics %}{{ generic.generic }}: {{ generic.traits | join(sep=" + ") }},
                {% endfor %}{% endif %}"#;
        let mut context = Context::new();
        context.insert("self", &self);
        context.insert(
            "return_ty",
            &self.return_ty.as_ref().unwrap_or(&"()".to_string()),
        );
        context.insert("has_generics", &!self.generics.is_empty());
        context.insert("generics", &self.generics.generics);
        context.insert(
            "generic_keys",
            &self
                .generics
                .generics
                .iter()
                .map(|g| g.generic.clone())
                .collect::<Vec<String>>(),
        );
        context.insert(
            "parameters",
            &self
                .parameters
                .iter()
                .map(|param| format!("{}: {}", param.name, param.ty))
                .collect::<Vec<String>>(),
        );
        Tera::one_off(template, &context, false).unwrap()
    }
}

/// Represents the function/method's body
#[derive(Default, Serialize)]
pub struct FunctionBody {
    body: String,
}

impl SrcCode for FunctionBody {
    fn generate(&self) -> String {
        let template = r#"
            {{ body }}
        "#;
        let mut ctx = Context::new();
        ctx.insert("body", &self.body);
        Tera::one_off(template, &ctx, false).unwrap()
    }
}

impl<S> From<S> for FunctionBody
where
    S: ToString,
{
    fn from(body: S) -> FunctionBody {
        FunctionBody {
            body: body.to_string(),
        }
    }
}

impl Function {
    /// Create a new function
    pub fn new<S: ToString>(name: S) -> Self {
        let mut f = Self::default();
        f.signature.name = name.to_string();
        f
    }

    /// Add a new parameter to this function
    pub fn add_parameter(mut self, param: Parameter) -> Self {
        self.signature.parameters.push(param);
        self
    }
    /// Add a new trait bound generic to this function
    pub fn add_generic(mut self, generic: Generic) -> Self {
        self.signature.generics = self.signature.generics.add_generic(generic);
        self
    }
    /// Set the return type of this function
    pub fn set_return_ty<S: ToString>(mut self, ty: S) -> Self {
        self.signature.return_ty = Some(ty.to_string());
        self
    }
    /// Set if this function is public
    pub fn set_is_pub(mut self, is_pub: bool) -> Self {
        self.signature = self.signature.set_is_pub(is_pub);
        self
    }
    /// Set the body of the function, this should be valid Rust source code syntax.
    pub fn set_body<S: Into<FunctionBody>>(mut self, body: S) -> Self {
        self.body = body.into();
        self
    }
}

/// Represents a single parameter to a `Function`
#[derive(Serialize, Default)]
pub struct Parameter {
    name: String,
    ty: String,
}
impl Parameter {
    /// Create a new parameter
    ///
    /// Example
    /// -------
    /// ```
    /// use proffer::*;
    ///
    /// let param = Parameter::new("foo", "usize").generate();
    /// let expected = "foo: usize";
    /// assert_eq!(expected, &param);
    /// ```
    ///
    pub fn new<S: ToString>(name: S, ty: S) -> Self {
        Self {
            name: name.to_string(),
            ty: ty.to_string(),
        }
    }
}

impl SrcCode for Parameter {
    fn generate(&self) -> String {
        let template = "{{ self.name }}: {{ self.ty }}";
        let mut ctx = Context::new();
        ctx.insert("self", &self);
        Tera::one_off(template, &ctx, false).unwrap()
    }
}

impl SrcCode for Function {
    fn generate(&self) -> String {
        let template = r#"
        {{ function_signature }}
        {
            {{ body }}
        }
        "#;
        let mut context = Context::new();
        context.insert("body", &self.body.generate());
        context.insert("function_signature", &self.signature.generate());
        Tera::one_off(template, &context, false).unwrap()
    }
}