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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
use super::StreamBuilder;
use crate::parse::Visibility;
use crate::prelude::Delimiter;
use crate::prelude::Result;
/// A builder for constants.
pub struct GenConst<'a> {
consts: &'a mut Vec<StreamBuilder>,
attrs: Vec<String>,
name: String,
ty: String,
vis: Visibility,
}
impl<'a> GenConst<'a> {
pub(crate) fn new(
consts: &'a mut Vec<StreamBuilder>,
name: impl Into<String>,
ty: impl Into<String>,
) -> Self {
Self {
consts,
attrs: Vec::new(),
name: name.into(),
ty: ty.into(),
vis: Visibility::Default,
}
}
/// Make the const `pub`. By default the const will have no visibility modifier and will only be visible in the current scope.
#[must_use]
pub const fn make_pub(mut self) -> Self {
self.vis = Visibility::Pub;
self
}
/// Add an outer attribute
#[must_use]
pub fn with_attr(
mut self,
attr: impl Into<String>,
) -> Self {
self.attrs.push(attr.into());
self
}
/// Complete the constant definition. This function takes a callback that will form the value of the constant.
///
/// ```
/// # use virtue::prelude::Generator;
/// # let mut generator = Generator::with_name("Bar");
/// generator
/// .impl_for("Foo")
/// .generate_const("BAR", "u8")
/// .with_value(|b| {
/// b.push_parsed("5")?;
/// Ok(())
/// })?;
/// # generator.assert_eq("impl Foo for Bar { const BAR : u8 = 5 ; }");
/// # Ok::<_, virtue::Error>(())
/// ```
///
/// Generates:
/// ```ignore
/// impl Foo for <struct or enum> {
/// const BAR: u8 = 5;
/// }
/// ```
///
/// # Errors
///
/// Returns an error if parsing fails.
pub fn with_value<F>(
self,
f: F,
) -> Result
where
F: FnOnce(&mut StreamBuilder) -> Result,
{
let mut builder = StreamBuilder::new();
for attr in self.attrs {
builder
.punct('#')
.punct('!')
.group(Delimiter::Bracket, |builder| {
builder.push_parsed(attr)?;
Ok(())
})?;
}
if self.vis == Visibility::Pub {
builder.ident_str("pub");
}
builder
.ident_str("const")
.push_parsed(self.name)?
.punct(':')
.push_parsed(self.ty)?
.punct('=');
f(&mut builder)?;
builder.punct(';');
self.consts.push(builder);
Ok(())
}
}
/// A builder for functions.
pub struct FnBuilder<'a, P> {
parent: &'a mut P,
name: String,
attrs: Vec<String>,
is_async: bool,
lifetimes: Vec<(String, Vec<String>)>,
generics: Vec<(String, Vec<String>)>,
self_arg: FnSelfArg,
args: Vec<(String, String)>,
return_type: Option<String>,
vis: Visibility,
}
impl<'a, P: FnParent> FnBuilder<'a, P> {
pub(super) fn new(
parent: &'a mut P,
name: impl Into<String>,
) -> Self {
Self {
parent,
name: name.into(),
attrs: vec!["inline".to_string()],
is_async: false,
lifetimes: Vec::new(),
generics: Vec::new(),
self_arg: FnSelfArg::None,
args: Vec::new(),
return_type: None,
vis: Visibility::Default,
}
}
/// Add an outer attribute
///
/// # Panics
///
/// Panics if an internal invariant is violated.
#[must_use]
pub fn with_attr(
mut self,
attr: impl Into<String>,
) -> Self {
self.attrs.push(attr.into());
self
}
/// Add `#[inline(always)]` to the function
///
/// # Panics
///
/// Panics if an internal invariant is violated.
#[must_use]
pub fn with_inline_always(mut self) -> Self {
self.attrs.push("inline(always)".to_string());
self
}
/// Add a lifetime parameter.
///
/// ```
/// # use virtue::prelude::Generator;
/// # let mut generator = Generator::with_name("Foo");
/// generator
/// .r#impl()
/// .generate_fn("foo") // fn foo()
/// .with_lifetime("a") // fn foo<'a>()
/// //
/// # .body(|_| Ok(())).unwrap();
/// # generator.assert_eq("impl Foo { fn foo < 'a > () { } }");
/// ```
///
/// # Panics
///
/// Panics if an internal invariant is violated.
#[must_use]
pub fn with_lifetime(
mut self,
name: impl Into<String>,
) -> Self {
self.lifetimes.push((name.into(), Vec::new()));
self
}
/// Make the function async
///
/// ```
/// # use virtue::prelude::Generator;
/// # let mut generator = Generator::with_name("Foo");
/// generator
/// .r#impl()
/// .generate_fn("foo") // fn foo()
/// .as_async() // async fn foo()
/// //
/// # .body(|_| Ok(())).unwrap();
/// # generator.assert_eq("impl Foo { async fn foo () { } }");
/// ```
///
/// # Panics
///
/// Panics if an internal invariant is violated.
#[must_use]
pub const fn as_async(mut self) -> Self {
self.is_async = true;
self
}
/// Add a lifetime parameter.
///
/// `dependencies` are the lifetime dependencies of the given lifetime.
///
/// ```
/// # use virtue::prelude::Generator;
/// # let mut generator = Generator::with_name("Foo");
/// generator
/// .r#impl()
/// .generate_fn("foo") // fn foo()
/// .with_lifetime("a") // fn foo<'a>()
/// .with_lifetime_deps("b", ["a"]) // fn foo<'b: 'a>()
/// //
/// # .body(|_| Ok(())).unwrap();
/// # generator.assert_eq("impl Foo { fn foo < 'a , 'b : 'a > () { } }");
/// ```
///
/// # Panics
///
/// Panics if an internal invariant is violated.
#[must_use]
pub fn with_lifetime_deps<ITER, I>(
mut self,
name: impl Into<String>,
dependencies: ITER,
) -> Self
where
ITER: IntoIterator<Item = I>,
I: Into<String>,
{
self.lifetimes.push((
name.into(),
dependencies.into_iter().map(Into::into).collect(),
));
self
}
/// Add a generic parameter. Keep in mind that will *not* work for lifetimes.
///
/// ```
/// # use virtue::prelude::Generator;
/// # let mut generator = Generator::with_name("Foo");
/// generator
/// .r#impl()
/// .generate_fn("foo") // fn foo()
/// .with_generic("D") // fn foo<D>()
/// //
/// # .body(|_| Ok(())).unwrap();
/// # generator.assert_eq("impl Foo { fn foo < D > () { } }");
/// ```
///
/// # Panics
///
/// Panics if an internal invariant is violated.
#[must_use]
pub fn with_generic(
mut self,
name: impl Into<String>,
) -> Self {
self.generics.push((name.into(), Vec::new()));
self
}
/// Add a generic parameter. Keep in mind that will *not* work for lifetimes.
///
/// `dependencies` are the dependencies of the parameter.
///
/// ```
/// # use virtue::prelude::Generator;
/// # let mut generator = Generator::with_name("Foo");
/// generator
/// .r#impl()
/// .generate_fn("foo") // fn foo()
/// .with_generic("D") // fn foo<D>()
/// .with_generic_deps("E", ["Encodable"]) // fn foo<D, E: Encodable>();
/// //
/// # .body(|_| Ok(())).unwrap();
/// # generator.assert_eq("impl Foo { fn foo < D , E : Encodable > () { } }");
/// ```
///
/// # Panics
///
/// Panics if an internal invariant is violated.
#[must_use]
pub fn with_generic_deps<DEP, I>(
mut self,
name: impl Into<String>,
dependencies: DEP,
) -> Self
where
DEP: IntoIterator<Item = I>,
I: Into<String>,
{
self.generics.push((
name.into(),
dependencies.into_iter().map(Into::into).collect(),
));
self
}
/// Set the value for `self`. See [`FnSelfArg`] for more information.
///
/// ```
/// # use virtue::prelude::{Generator, FnSelfArg};
/// # let mut generator = Generator::with_name("Foo");
/// generator
/// .r#impl()
/// .generate_fn("foo") // fn foo()
/// .with_self_arg(FnSelfArg::RefSelf) // fn foo(&self)
/// //
/// # .body(|_| Ok(())).unwrap();
/// # generator.assert_eq("impl Foo { fn foo (& self ,) { } }");
/// ```
///
/// # Panics
///
/// Panics if an internal invariant is violated.
#[must_use]
pub const fn with_self_arg(
mut self,
self_arg: FnSelfArg,
) -> Self {
self.self_arg = self_arg;
self
}
/// Add an argument with a `name` and a `ty`.
///
/// ```
/// # use virtue::prelude::Generator;
/// # let mut generator = Generator::with_name("Foo");
/// generator
/// .r#impl()
/// .generate_fn("foo") // fn foo()
/// .with_arg("a", "u32") // fn foo(a: u32)
/// .with_arg("b", "u32") // fn foo(a: u32, b: u32)
/// //
/// # .body(|_| Ok(())).unwrap();
/// # generator.assert_eq("impl Foo { fn foo (a : u32 , b : u32) { } }");
/// ```
///
/// # Panics
///
/// Panics if an internal invariant is violated.
#[must_use]
pub fn with_arg(
mut self,
name: impl Into<String>,
ty: impl Into<String>,
) -> Self {
self.args.push((name.into(), ty.into()));
self
}
/// Set the return type for the function. By default the function will have no return type.
///
/// ```
/// # use virtue::prelude::Generator;
/// # let mut generator = Generator::with_name("Foo");
/// generator
/// .r#impl()
/// .generate_fn("foo") // fn foo()
/// .with_return_type("u32") // fn foo() -> u32
/// //
/// # .body(|_| Ok(())).unwrap();
/// # generator.assert_eq("impl Foo { fn foo () ->u32 { } }");
/// ```
///
/// # Panics
///
/// Panics if an internal invariant is violated.
#[must_use]
pub fn with_return_type(
mut self,
ret_type: impl Into<String>,
) -> Self {
self.return_type = Some(ret_type.into());
self
}
/// Make the function `pub`. If this is not called, the function will have no visibility modifier.
///
/// # Panics
///
/// Panics if an internal invariant is violated.
#[must_use]
pub const fn make_pub(mut self) -> Self {
self.vis = Visibility::Pub;
self
}
/// # Errors
///
/// Returns an error if the operation fails.
/// Complete the function definition. This function takes a callback that will form the body of the function.
///
/// ```
/// # use virtue::prelude::Generator;
/// # let mut generator = Generator::with_name("Foo");
/// generator
/// .r#impl()
/// .generate_fn("foo") // fn foo()
/// .body(|b| {
/// b.push_parsed("println!(\"hello world\");")?;
/// Ok(())
/// })
/// .unwrap();
/// // fn foo() {
/// // println!("Hello world");
/// // }
/// # generator.assert_eq("impl Foo { fn foo () { println ! (\"hello world\") ; } }");
/// ```
pub fn body(
self,
body_builder: impl FnOnce(&mut StreamBuilder) -> crate::Result,
) -> crate::Result {
let FnBuilder {
parent,
name,
attrs,
is_async,
lifetimes,
generics,
self_arg,
args,
return_type,
vis,
} = self;
let mut builder = StreamBuilder::new();
// attrs
for attr in attrs {
builder.punct('#').group(Delimiter::Bracket, |builder| {
builder.push_parsed(attr)?;
Ok(())
})?;
}
// function name; `fn name`
if vis == Visibility::Pub {
builder.ident_str("pub");
}
if is_async {
builder.ident_str("async");
}
builder.ident_str("fn");
builder.ident_str(name);
// lifetimes; `<'a: 'b, D: Display>`
if !lifetimes.is_empty() || !generics.is_empty() {
builder.punct('<');
let mut is_first = true;
for (lifetime, dependencies) in lifetimes {
if is_first {
is_first = false;
} else {
builder.punct(',');
}
builder.lifetime_str(lifetime.as_ref());
if !dependencies.is_empty() {
for (idx, dependency) in dependencies.into_iter().enumerate() {
builder.punct(if idx == 0 { ':' } else { '+' });
builder.lifetime_str(dependency.as_ref());
}
}
}
for (generic, dependencies) in generics {
if is_first {
is_first = false;
} else {
builder.punct(',');
}
builder.ident_str(&generic);
if !dependencies.is_empty() {
for (idx, dependency) in dependencies.into_iter().enumerate() {
builder.punct(if idx == 0 { ':' } else { '+' });
builder.push_parsed(&dependency)?;
}
}
}
builder.punct('>');
}
// Arguments; `(&self, foo: &Bar)`
builder.group(Delimiter::Parenthesis, |arg_stream| {
if let Some(self_arg) = self_arg.into_token_tree() {
arg_stream.append(self_arg);
arg_stream.punct(',');
}
for (idx, (arg_name, arg_ty)) in args.into_iter().enumerate() {
if idx != 0 {
arg_stream.punct(',');
}
arg_stream.push_parsed(&arg_name)?;
arg_stream.punct(':');
arg_stream.push_parsed(&arg_ty)?;
}
Ok(())
})?;
// Return type: `-> ResultType`
if let Some(return_type) = return_type {
builder.puncts("->");
builder.push_parsed(&return_type)?;
}
let mut body_stream = StreamBuilder::new();
body_builder(&mut body_stream)?;
parent.append(builder, body_stream)
}
}
pub trait FnParent {
fn append(
&mut self,
fn_definition: StreamBuilder,
fn_body: StreamBuilder,
) -> Result;
}
/// The `self` argument of a function
#[allow(dead_code)]
#[non_exhaustive]
pub enum FnSelfArg {
/// No `self` argument. The function will be a static function.
None,
/// `self`. The function will consume self.
TakeSelf,
/// `mut self`. The function will consume self.
MutTakeSelf,
/// `&self`. The function will take self by reference.
RefSelf,
/// `&mut self`. The function will take self by mutable reference.
MutSelf,
}
impl FnSelfArg {
fn into_token_tree(self) -> Option<StreamBuilder> {
let mut builder = StreamBuilder::new();
match self {
| Self::None => return None,
| Self::TakeSelf => {
builder.ident_str("self");
},
| Self::MutTakeSelf => {
builder.ident_str("mut");
builder.ident_str("self");
},
| Self::RefSelf => {
builder.punct('&');
builder.ident_str("self");
},
| Self::MutSelf => {
builder.punct('&');
builder.ident_str("mut");
builder.ident_str("self");
},
}
Some(builder)
}
}