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
use std::fmt::{self, Write};

use crate::block::Block;
use crate::body::Body;
use crate::bound::Bound;
use crate::docs::Docs;
use crate::field::Field;
use crate::formatter::Formatter;
use crate::formatter::{fmt_bounds, fmt_generics};

use crate::r#type::Type;

/// Defines a function.
#[derive(Debug, Clone)]
pub struct Function {
    /// The name of the function.
    name: String,
    /// The function's documentation.
    docs: Option<Docs>,
    /// A lint attribute used to suppress a warning or error.
    allow: Option<String>,
    /// Function visibility.
    vis: Option<String>,
    /// Function generics.
    generics: Vec<String>,
    /// If the function takes `&self` or `&mut self`.
    arg_self: Option<String>,
    /// Function arguments.
    args: Vec<Field>,
    /// Return type.
    ret: Option<Type>,
    /// Where bounds.
    bounds: Vec<Bound>,
    /// Body contents.
    pub body: Option<Vec<Body>>,
    /// Function attributes, e.g., `#[no_mangle]`.
    attributes: Vec<String>,
    /// Function `extern` ABI.
    extern_abi: Option<String>,
    /// Whether or not this function is `async` or not.
    r#async: bool,
}

impl Function {
    /// Return a new function definition.
    /// 
    /// # Arguments
    /// 
    /// * `name` - The name of the function.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use rust_codegen::Function;
    /// 
    /// let foo_fn = Function::new("foo_fn");
    /// ```
    pub fn new(name: &str) -> Self {
        Function {
            name: name.to_string(),
            docs: None,
            allow: None,
            vis: None,
            generics: vec![],
            arg_self: None,
            args: vec![],
            ret: None,
            bounds: vec![],
            body: Some(vec![]),
            attributes: vec![],
            extern_abi: None,
            r#async: false,
        }
    }

    /// Set the function documentation.
    /// 
    /// # Arguments
    /// 
    /// * `docs` - The docs to set for the function.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use rust_codegen::Function;
    /// 
    /// let mut foo_fn = Function::new("foo_fn");
    /// foo_fn.doc("Sample Foo function documentation.");
    /// ```
    pub fn doc(&mut self, docs: &str) -> &mut Self {
        self.docs = Some(Docs::new(docs));
        self
    }

    /// Specify lint attribute to supress a warning or error.
    /// 
    /// # Arguments
    /// 
    /// * `allow` - The lint attribute to add.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use rust_codegen::Function;
    /// 
    /// let mut foo_fn = Function::new("foo_fn");
    /// foo_fn.allow("dead_code");
    /// ```
    pub fn allow(&mut self, allow: &str) -> &mut Self {
        self.allow = Some(allow.to_string());
        self
    }

    /// Set the function visibility.
    /// 
    /// # Arguments
    /// 
    /// * `vis` - The visiblity to set for the function.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use rust_codegen::Function;
    /// 
    /// let mut foo_fn = Function::new("foo_fn");
    /// foo_fn.vis("pub");
    /// ```
    pub fn vis(&mut self, vis: &str) -> &mut Self {
        self.vis = Some(vis.to_string());
        self
    }

    /// Set whether this function is async or not.
    /// 
    /// # Arguments
    /// 
    /// * `async` - Indicates whether this function is async or not.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use rust_codegen::Function;
    /// 
    /// let mut foo_fn = Function::new("foo_fn");
    /// foo_fn.set_async(true);
    /// ```
    pub fn set_async(&mut self, r#async: bool) -> &mut Self {
        self.r#async = r#async;
        self
    }

    /// Add a generic to the function.
    /// 
    /// # Arguments
    /// 
    /// * `name` - The name of the generic to add.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use rust_codegen::Function;
    /// 
    /// let mut foo_fn = Function::new("foo_fn");
    /// foo_fn.generic("T");
    /// ```
    pub fn generic(&mut self, name: &str) -> &mut Self {
        self.generics.push(name.to_string());
        self
    }

    /// Add `self` as a function argument.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use rust_codegen::Function;
    /// 
    /// let mut foo_fn = Function::new("foo_fn");
    /// foo_fn.arg_self();
    /// ```
    pub fn arg_self(&mut self) -> &mut Self {
        self.arg_self = Some("self".to_string());
        self
    }

    /// Add `&self` as a function argument.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use rust_codegen::Function;
    /// 
    /// let mut foo_fn = Function::new("foo_fn");
    /// foo_fn.arg_ref_self();
    /// ```
    pub fn arg_ref_self(&mut self) -> &mut Self {
        self.arg_self = Some("&self".to_string());
        self
    }

    /// Add `&mut self` as a function argument.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use rust_codegen::Function;
    /// 
    /// let mut foo_fn = Function::new("foo_fn");
    /// foo_fn.arg_mut_self();
    /// ```
    pub fn arg_mut_self(&mut self) -> &mut Self {
        self.arg_self = Some("&mut self".to_string());
        self
    }

    /// Add a function argument.
    /// 
    /// # Arguments
    /// 
    /// * `name` - The name of the argument.
    /// * `ty` - The type of the argument.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use rust_codegen::Function;
    /// 
    /// let mut foo_fn = Function::new("foo_fn");
    /// foo_fn.arg("name", "&str");
    /// ```
    pub fn arg<T>(&mut self, name: &str, ty: T) -> &mut Self
    where
        T: Into<Type>,
    {
        self.args.push(Field {
            name: name.to_string(),
            ty: ty.into(),
            // While a `Field` is used here, both `documentation`
            // and `annotation` does not make sense for function arguments.
            // Simply use empty strings.
            documentation: Vec::new(),
            annotation: Vec::new(),
        });

        self
    }

    /// Set the function return type.
    /// 
    /// # Arguments
    /// 
    /// * `ty` - The return type.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use rust_codegen::Function;
    /// 
    /// let mut foo_fn = Function::new("foo_fn");
    /// foo_fn.ret("String");
    /// ```
    pub fn ret<T>(&mut self, ty: T) -> &mut Self
    where
        T: Into<Type>,
    {
        self.ret = Some(ty.into());
        self
    }

    /// Add a `where` bound to the function.
    /// 
    /// # Arguments 
    /// 
    /// * `name ` - The name of the bound.
    /// * `ty` - The type of the bound.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use rust_codegen::Function;
    /// 
    /// let mut foo_fn = Function::new("foo_fn");
    /// foo_fn.bound("A", "TraitA");
    /// ```
    pub fn bound<T>(&mut self, name: &str, ty: T) -> &mut Self
    where
        T: Into<Type>,
    {
        self.bounds.push(Bound {
            name: name.to_string(),
            bound: vec![ty.into()],
        });
        self
    }

    /// Push a line to the function implementation.
    /// 
    /// # Arguments
    /// 
    /// * `line` - The line to add to the function.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use rust_codegen::Function;
    /// 
    /// let mut foo_fn = Function::new("foo_fn");
    /// foo_fn.line("println!(\"Hello, world!\")");
    /// ```
    pub fn line<T>(&mut self, line: T) -> &mut Self
    where
        T: ToString,
    {
        self.body
            .get_or_insert(vec![])
            .push(Body::String(line.to_string()));

        self
    }

    /// Add an attribute to the function.
    /// 
    /// # Arguments
    /// 
    /// * `attribute` - The attribute to add.
    /// 
    /// # Examples
    ///
    /// ```
    /// use rust_codegen::Function;
    ///
    /// let mut foo_fn = Function::new("foo_fn");
    /// foo_fn.attr("test");
    /// ```
    pub fn attr(&mut self, attribute: &str) -> &mut Self {
        self.attributes.push(attribute.to_string());
        self
    }

    /// Specify an `extern` ABI for the function.
    /// 
    /// # Arguments
    /// 
    /// * `abi` - The extern ABI to add.
    /// 
    /// # Examples 
    /// 
    /// ```
    /// use rust_codegen::Function;
    ///
    /// let mut foo_fn = Function::new("foo_fn");
    /// foo_fn.extern_abi("C");
    /// ```
    pub fn extern_abi(&mut self, abi: &str) -> &mut Self {
        self.extern_abi.replace(abi.to_string());
        self
    }

    /// Push a block to the function implementation.
    /// 
    /// # Arguments
    /// 
    /// * `block` - The block to push to the function.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use rust_codegen::*;
    ///
    /// let mut foo_fn = Function::new("foo_fn");
    /// 
    /// let mut block = Block::new("");
    /// block.line("println!(\"Hello, world!\");");
    /// 
    /// foo_fn.push_block(block);
    /// ```
    pub fn push_block(&mut self, block: Block) -> &mut Self {
        self.body.get_or_insert(vec![]).push(Body::Block(block));

        self
    }

    /// Formats the function using the given formatter.
    /// 
    /// # Arguments
    /// 
    /// * `is_trait` - Indicates whether it is a trait or not.
    /// * `fmt` - The formatter to use.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use rust_codegen::*;
    /// 
    /// let mut dest = String::new();
    /// let mut fmt = Formatter::new(&mut dest);
    /// 
    /// let mut foo_fn = Function::new("foo_fn");
    /// foo_fn.fmt(false, &mut fmt);
    /// ```
    pub fn fmt(&self, is_trait: bool, fmt: &mut Formatter<'_>) -> fmt::Result {
        if let Some(ref docs) = self.docs {
            docs.fmt(fmt)?;
        }

        if let Some(ref allow) = self.allow {
            write!(fmt, "#[allow({})]\n", allow)?;
        }

        for attr in self.attributes.iter() {
            write!(fmt, "#[{}]\n", attr)?;
        }

        if is_trait {
            assert!(
                self.vis.is_none(),
                "trait fns do not have visibility modifiers"
            );
        }

        if let Some(ref vis) = self.vis {
            write!(fmt, "{} ", vis)?;
        }

        if let Some(ref extern_abi) = self.extern_abi {
            write!(fmt, "extern \"{extern_abi}\" ", extern_abi = extern_abi)?;
        }

        if self.r#async {
            write!(fmt, "async ")?;
        }

        write!(fmt, "fn {}", self.name)?;
        fmt_generics(&self.generics, fmt)?;

        write!(fmt, "(")?;

        if let Some(ref s) = self.arg_self {
            write!(fmt, "{}", s)?;
        }

        for (i, arg) in self.args.iter().enumerate() {
            if i != 0 || self.arg_self.is_some() {
                write!(fmt, ", ")?;
            }

            write!(fmt, "{}: ", arg.name)?;
            arg.ty.fmt(fmt)?;
        }

        write!(fmt, ")")?;

        if let Some(ref ret) = self.ret {
            write!(fmt, " -> ")?;
            ret.fmt(fmt)?;
        }

        fmt_bounds(&self.bounds, fmt)?;

        match self.body {
            Some(ref body) => fmt.block(|fmt| {
                for b in body {
                    b.fmt(fmt)?;
                }

                Ok(())
            }),
            None => {
                if !is_trait {
                    panic!("impl blocks must define fn bodies");
                }

                write!(fmt, ";\n")
            }
        }
    }
}