tamago 0.2.0

A code generator library for C, with a builder-pattern API
Documentation
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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
// Copyright (c) 2025 Nobuharu Shimazu
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

//! This module provides structured representations and builders for C-style loop constructs.
//! It includes implementations for:
//!
//! - `While` loops - Conditional loops that check the condition before each iteration
//! - `DoWhile` loops - Conditional loops that check the condition after each iteration
//! - `For` loops - Iteration loops with initialization, condition, and increment expressions
//!
//! Each loop type follows a builder pattern for flexible and readable construction.
//! All loop constructs implement the `Format` trait for generating properly formatted C code.

use std::fmt::{self, Write};

use crate::{Block, Expr, Format, Formatter, Statement, Variable};
use tamacro::DisplayFromFormat;

/// Represents a standard while loop in C.
///
/// A while loop evaluates its condition before each iteration of the loop body.
/// If the condition evaluates to false before the first iteration, the loop body
/// will not execute at all.
///
/// ## C Syntax
/// ```c
/// while (condition) {
///     // loop body statements
/// }
/// ```
///
/// ## Example Usage
/// ```rust
/// // Create a while loop that executes while x < 10
/// let while_loop = While::new(expr!("x < 10"))
///     .body(Block::new()
///         .statement(Statement::expr(expr!("x++")))
///         .build())
///     .build();
/// ```
#[derive(Debug, Clone, DisplayFromFormat)]
pub struct While {
    /// The condition expression that determines whether the loop continues.
    /// The loop executes as long as this condition evaluates to true.
    pub cond: Expr,

    /// The body block containing statements to be executed in each iteration.
    pub body: Block,
}

impl While {
    /// Creates a new `WhileBuilder` with the specified condition.
    ///
    /// This is the starting point for constructing a while loop using the builder pattern.
    /// After calling this method, chain additional builder methods and finally call `build()`
    /// to create the while loop.
    ///
    /// ## Parameters
    /// - `cond`: The condition expression that controls the loop execution
    ///
    /// ## Returns
    /// A new `WhileBuilder` instance with the given condition
    ///
    /// ## Example
    /// ```rust
    /// let while_loop = While::new(expr!("count < 10"))
    ///     .body(loop_body)
    ///     .build();
    /// ```
    pub fn new(cond: Expr) -> WhileBuilder {
        WhileBuilder::new(cond)
    }
}

impl Format for While {
    fn format(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
        write!(fmt, "while (")?;
        self.cond.format(fmt)?;
        write!(fmt, ")")?;

        fmt.block(|fmt| self.body.format(fmt))?;
        writeln!(fmt)
    }
}

/// A builder for constructing a `While` loop instance.
///
/// This builder implements the builder pattern for creating while loops
/// with a fluent interface. It allows for clear and concise loop creation
/// with method chaining.
pub struct WhileBuilder {
    cond: Expr,
    body: Block,
}

impl WhileBuilder {
    /// Creates a new `WhileBuilder` with the specified condition expression.
    ///
    /// ## Parameters
    /// - `cond`: The condition expression that will control the loop execution
    ///
    /// ## Returns
    /// A new `WhileBuilder` instance with the given condition and an empty body
    ///
    /// ## Example
    /// ```rust
    /// let builder = WhileBuilder::new(expr!("i < array_size"));
    /// ```
    pub fn new(cond: Expr) -> Self {
        Self {
            cond,
            body: Block::new().build(),
        }
    }

    /// Sets the body block of the while loop.
    ///
    /// ## Parameters
    /// - `body`: A complete `Block` instance containing the statements to execute in the loop
    ///
    /// ## Returns
    /// The builder instance for method chaining
    ///
    /// ## Example
    /// ```rust
    /// let body_block = Block::new()
    ///     .statement(Statement::expr(expr!("process_item(array[i])")))
    ///     .statement(Statement::expr(expr!("i++")))
    ///     .build();
    ///
    /// let builder = WhileBuilder::new(expr!("i < array_size"))
    ///     .body(body_block);
    /// ```
    pub fn body(mut self, body: Block) -> Self {
        self.body = body;
        self
    }

    /// Appends a single statement to the body block of the while loop.
    ///
    /// This is a convenience method for adding one statement at a time
    /// to the loop body instead of creating a complete `Block` first.
    ///
    /// ## Parameters
    /// - `stmt`: The statement to add to the loop body
    ///
    /// ## Returns
    /// The builder instance for method chaining
    ///
    /// ## Example
    /// ```rust
    /// let builder = WhileBuilder::new(expr!("i < 10"))
    ///     .statement(Statement::expr(expr!("sum += array[i]")))
    ///     .statement(Statement::expr(expr!("i++")));
    /// ```
    pub fn statement(mut self, stmt: Statement) -> Self {
        self.body.stmts.push(stmt);
        self
    }

    /// Consumes the builder and creates a `While` instance.
    ///
    /// This finalizes the building process and returns the complete while loop.
    ///
    /// ## Returns
    /// A fully constructed `While` loop instance
    ///
    /// ## Example
    /// ```rust
    /// let while_loop = WhileBuilder::new(expr!("data_available()"))
    ///     .statement(Statement::expr(expr!("process_data()")))
    ///     .build();
    /// ```
    pub fn build(self) -> While {
        While {
            cond: self.cond,
            body: self.body,
        }
    }
}

/// Represents a do-while loop in C.
///
/// A do-while loop evaluates its condition after each iteration of the loop body.
/// This guarantees that the loop body executes at least once, regardless of the
/// condition's initial value.
///
/// ## C Syntax
/// ```c
/// do {
///     // loop body statements
/// } while(condition);
/// ```
///
/// ## Example Usage
/// ```rust
/// // Create a do-while loop that executes at least once
/// let do_while = DoWhile::new(expr!("response != 'q'"))
///     .body(Block::new()
///         .statement(Statement::expr(expr!("display_menu()")))
///         .statement(Statement::expr(expr!("response = get_input()")))
///         .build())
///     .build();
/// ```
#[derive(Debug, Clone, DisplayFromFormat)]
pub struct DoWhile {
    /// The condition expression that determines whether the loop continues.
    /// The loop executes as long as this condition evaluates to true,
    /// with the condition checked after each iteration.
    pub cond: Expr,

    /// The body block containing statements to be executed in each iteration.
    /// This body is guaranteed to execute at least once.
    pub body: Block,
}

impl DoWhile {
    /// Creates a new `DoWhileBuilder` with the specified condition.
    ///
    /// This is the starting point for constructing a do-while loop using the builder pattern.
    /// After calling this method, chain additional builder methods and finally call `build()`
    /// to create the do-while loop.
    ///
    /// ## Parameters
    /// - `cond`: The condition expression that controls the loop continuation
    ///
    /// ## Returns
    /// A new `DoWhileBuilder` instance with the given condition
    ///
    /// ## Example
    /// ```rust
    /// let do_while = DoWhile::new(expr!("data != EOF"))
    ///     .body(loop_body)
    ///     .build();
    /// ```
    pub fn new(cond: Expr) -> DoWhileBuilder {
        DoWhileBuilder::new(cond)
    }
}

impl Format for DoWhile {
    fn format(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
        write!(fmt, "do")?;
        fmt.block(|fmt| self.body.format(fmt))?;

        write!(fmt, " while (")?;
        self.cond.format(fmt)?;
        writeln!(fmt, ");")
    }
}

/// A builder for constructing a `DoWhile` loop instance.
///
/// This builder implements the builder pattern for creating do-while loops
/// with a fluent interface. It allows for clear and concise loop creation
/// with method chaining.
pub struct DoWhileBuilder {
    cond: Expr,
    body: Block,
}

impl DoWhileBuilder {
    /// Creates a new `DoWhileBuilder` with the specified condition expression.
    ///
    /// ## Parameters
    /// - `cond`: The condition expression that will control the loop continuation
    ///
    /// ## Returns
    /// A new `DoWhileBuilder` instance with the given condition and an empty body
    ///
    /// ## Example
    /// ```rust
    /// let builder = DoWhileBuilder::new(expr!("valid_input == false"));
    /// ```
    pub fn new(cond: Expr) -> Self {
        Self {
            cond,
            body: Block::new().build(),
        }
    }

    /// Sets the body block of the do-while loop.
    ///
    /// ## Parameters
    /// - `body`: A complete `Block` instance containing the statements to execute in the loop
    ///
    /// ## Returns
    /// The builder instance for method chaining
    ///
    /// ## Example
    /// ```rust
    /// let body_block = Block::new()
    ///     .statement(Statement::expr(expr!("display_prompt()")))
    ///     .statement(Statement::expr(expr!("input = read_user_input()")))
    ///     .statement(Statement::expr(expr!("valid_input = validate_input(input)")))
    ///     .build();
    ///
    /// let builder = DoWhileBuilder::new(expr!("valid_input == false"))
    ///     .body(body_block);
    /// ```
    pub fn body(mut self, body: Block) -> Self {
        self.body = body;
        self
    }

    /// Appends a single statement to the body block of the do-while loop.
    ///
    /// This is a convenience method for adding one statement at a time
    /// to the loop body instead of creating a complete `Block` first.
    ///
    /// ## Parameters
    /// - `stmt`: The statement to add to the loop body
    ///
    /// ## Returns
    /// The builder instance for method chaining
    ///
    /// ## Example
    /// ```rust
    /// let builder = DoWhileBuilder::new(expr!("has_more_input()"))
    ///     .statement(Statement::expr(expr!("value = read_next_value()")))
    ///     .statement(Statement::expr(expr!("process_value(value)")));
    /// ```
    pub fn statement(mut self, stmt: Statement) -> Self {
        self.body.stmts.push(stmt);
        self
    }

    /// Consumes the builder and creates a `DoWhile` instance.
    ///
    /// This finalizes the building process and returns the complete do-while loop.
    ///
    /// ## Returns
    /// A fully constructed `DoWhile` loop instance
    ///
    /// ## Example
    /// ```rust
    /// let do_while_loop = DoWhileBuilder::new(expr!("!is_valid(input)"))
    ///     .statement(Statement::expr(expr!("prompt_user()")))
    ///     .statement(Statement::expr(expr!("input = get_input()")))
    ///     .build();
    /// ```
    pub fn build(self) -> DoWhile {
        DoWhile {
            cond: self.cond,
            body: self.body,
        }
    }
}

/// Represents a for loop in C, which consists of initialization, condition, step expressions,
/// and a body block of statements.
///
/// A for loop provides a compact way to iterate with a counter or other form of state
/// that is initialized before the loop, checked before each iteration, and updated after
/// each iteration.
///
/// ## C Syntax
/// ```c
/// for (initialization; condition; step) {
///     // loop body statements
/// }
/// ```
///
/// Each of the three expressions (initialization, condition, step) is optional.
///
/// ## Example Usage
/// ```rust
/// // Create a for loop that counts from 0 to 9
/// let for_loop = For::new()
///     .init(expr!("int i = 0"))
///     .cond(expr!("i < 10"))
///     .step(expr!("i++"))
///     .body(Block::new()
///         .statement(Statement::expr(expr!("process(array[i])")))
///         .build())
///     .build();
/// ```
/// The initialization clause of a `for` loop.
///
/// C allows the first clause of a `for` to be *either* a declaration
/// (`for (int i = 0; ...)`) or an ordinary expression (`for (i = 0; ...)`).
/// These are genuinely different grammatical categories, so they get distinct
/// variants here rather than smuggling a declaration through the expression
/// type.
#[derive(Debug, Clone, DisplayFromFormat)]
pub enum ForInit {
    /// A declaration, e.g. `int i = 0`.
    Decl(Variable),

    /// An expression, e.g. `i = 0`.
    Expr(Expr),
}

impl Format for ForInit {
    fn format(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
        match self {
            ForInit::Decl(v) => v.format(fmt),
            ForInit::Expr(e) => e.format(fmt),
        }
    }
}

#[derive(Debug, Clone, DisplayFromFormat)]
pub struct For {
    /// The initialization clause that runs once before the loop begins,
    /// typically declaring and initializing a loop counter. `None` omits it.
    pub init: Option<ForInit>,

    /// The condition expression that determines whether the loop continues.
    /// Evaluated before each iteration. The loop executes as long as this
    /// condition evaluates to true. Can be `None` for an infinite loop.
    pub cond: Option<Expr>,

    /// The step (or update) expression that runs after each iteration.
    /// This is typically used to increment counters or update loop variables.
    /// Can be `None` if no update is needed.
    pub step: Option<Expr>,

    /// The body block containing statements to be executed in each iteration.
    pub body: Block,
}

impl For {
    /// Creates a new `ForBuilder` for constructing a for loop.
    ///
    /// This is the starting point for constructing a for loop using the builder pattern.
    /// After calling this method, chain additional builder methods to set the initialization,
    /// condition, step expressions, and body, then finally call `build()` to create the for loop.
    ///
    /// ## Returns
    /// A new `ForBuilder` instance with all parts set to `None` and an empty body
    ///
    /// ## Example
    /// ```rust
    /// let for_loop = For::new()
    ///     .init(expr!("int i = 0"))
    ///     .cond(expr!("i < array_size"))
    ///     .step(expr!("i++"))
    ///     .body(loop_body)
    ///     .build();
    /// ```
    pub fn new() -> ForBuilder {
        ForBuilder::new()
    }
}

impl Format for For {
    fn format(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
        write!(fmt, "for (")?;
        if let Some(init) = &self.init {
            init.format(fmt)?;
        }
        write!(fmt, ";")?;

        if let Some(cond) = &self.cond {
            write!(fmt, " ")?;
            cond.format(fmt)?;
        }
        write!(fmt, ";")?;

        if let Some(step) = &self.step {
            write!(fmt, " ")?;
            step.format(fmt)?;
        }
        write!(fmt, ")")?;

        fmt.block(|fmt| self.body.format(fmt))?;
        writeln!(fmt)
    }
}

/// A builder for constructing a `For` loop instance.
///
/// This builder implements the builder pattern for creating for loops
/// with a fluent interface. It allows for clear and concise loop creation
/// with method chaining, and supports optional components (initialization,
/// condition, and step expressions).
pub struct ForBuilder {
    init: Option<ForInit>,
    cond: Option<Expr>,
    step: Option<Expr>,
    body: Block,
}

impl Default for ForBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl ForBuilder {
    /// Creates a new `ForBuilder` with all parts initialized to `None` or empty.
    ///
    /// ## Returns
    /// A new `ForBuilder` instance
    ///
    /// ## Example
    /// ```rust
    /// let builder = ForBuilder::new();
    /// ```
    pub fn new() -> Self {
        Self {
            init: None,
            cond: None,
            step: None,
            body: Block::new().build(),
        }
    }

    /// Sets the initialization clause of the for loop.
    ///
    /// See [`init_decl`](Self::init_decl) and [`init_expr`](Self::init_expr) for
    /// convenience wrappers that take a [`Variable`] or [`Expr`] directly.
    ///
    /// ## Parameters
    /// - `init`: The initialization clause
    ///
    /// ## Returns
    /// The builder instance for method chaining
    pub fn init(mut self, init: ForInit) -> Self {
        self.init = Some(init);
        self
    }

    /// Sets the initialization clause to a declaration, e.g. `int i = 0`.
    pub fn init_decl(self, decl: Variable) -> Self {
        self.init(ForInit::Decl(decl))
    }

    /// Sets the initialization clause to an expression, e.g. `i = 0`.
    pub fn init_expr(self, expr: Expr) -> Self {
        self.init(ForInit::Expr(expr))
    }

    /// Sets the condition expression of the for loop.
    ///
    /// This expression is evaluated before each iteration of the loop.
    /// The loop continues as long as this condition evaluates to true.
    ///
    /// ## Parameters
    /// - `cond`: The condition expression
    ///
    /// ## Returns
    /// The builder instance for method chaining
    ///
    /// ## Example
    /// ```rust
    /// let builder = ForBuilder::new()
    ///     .cond(expr!("i < array_length"));
    /// ```
    pub fn cond(mut self, cond: Expr) -> Self {
        self.cond = Some(cond);
        self
    }

    /// Sets the step (or update) expression of the for loop.
    ///
    /// This expression is executed after each iteration of the loop,
    /// and is typically used to increment counters or update loop variables.
    ///
    /// ## Parameters
    /// - `step`: The step expression
    ///
    /// ## Returns
    /// The builder instance for method chaining
    ///
    /// ## Example
    /// ```rust
    /// let builder = ForBuilder::new()
    ///     .step(expr!("i++"));
    /// ```
    pub fn step(mut self, step: Expr) -> Self {
        self.step = Some(step);
        self
    }

    /// Sets the body block of the for loop.
    ///
    /// ## Parameters
    /// - `body`: A complete `Block` instance containing the statements to execute in the loop
    ///
    /// ## Returns
    /// The builder instance for method chaining
    ///
    /// ## Example
    /// ```rust
    /// let body_block = Block::new()
    ///     .statement(Statement::expr(expr!("sum += array[i]")))
    ///     .build();
    ///
    /// let builder = ForBuilder::new()
    ///     .body(body_block);
    /// ```
    pub fn body(mut self, body: Block) -> Self {
        self.body = body;
        self
    }

    /// Appends a single statement to the body block of the for loop.
    ///
    /// This is a convenience method for adding one statement at a time
    /// to the loop body instead of creating a complete `Block` first.
    ///
    /// ## Parameters
    /// - `stmt`: The statement to add to the loop body
    ///
    /// ## Returns
    /// The builder instance for method chaining
    ///
    /// ## Example
    /// ```rust
    /// let builder = ForBuilder::new()
    ///     .init(expr!("int i = 0"))
    ///     .cond(expr!("i < 10"))
    ///     .step(expr!("i++"))
    ///     .statement(Statement::expr(expr!("print_element(array[i])")));
    /// ```
    pub fn statement(mut self, stmt: Statement) -> Self {
        self.body.stmts.push(stmt);
        self
    }

    /// Consumes the builder and creates a `For` instance.
    ///
    /// This finalizes the building process and returns the complete for loop.
    ///
    /// ## Returns
    /// A fully constructed `For` loop instance
    ///
    /// ## Example
    /// ```rust
    /// let for_loop = ForBuilder::new()
    ///     .init(expr!("int i = 0"))
    ///     .cond(expr!("i < size"))
    ///     .step(expr!("i++"))
    ///     .statement(Statement::expr(expr!("process(data[i])")))
    ///     .build();
    /// ```
    pub fn build(self) -> For {
        For {
            init: self.init,
            cond: self.cond,
            step: self.step,
            body: self.body,
        }
    }
}

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

    #[test]
    fn while_stmt() {
        let w = WhileBuilder::new(Expr::Bool(true))
            .body(
                Block::new()
                    .statement(Statement::Return(Some(Expr::Float(1.23))))
                    .build(),
            )
            .build();
        let res = r#"while (true) {
  return 1.23f;
}
"#;
        assert_eq!(w.to_string(), res);
    }

    #[test]
    fn do_while() {
        let w = DoWhileBuilder::new(Expr::Bool(true)).build();
        let res = "do {\n} while (true);\n";
        assert_eq!(w.to_string(), res);
    }

    #[test]
    fn for_stmt() {
        let f = ForBuilder::new()
            .init_decl(
                VariableBuilder::new_with_str("i", Type::new(BaseType::Int).build())
                    .value(Expr::Int(0))
                    .build(),
            )
            .cond(Expr::Binary {
                left: Box::new(Expr::Ident("i".to_string())),
                op: BinOp::LT,
                right: Box::new(Expr::Int(10)),
            })
            .step(Expr::Unary {
                op: UnaryOp::Inc,
                expr: Box::new(Expr::Ident("i".to_string())),
            })
            .body(Block::new().statement(Statement::Continue).build())
            .build();
        let res = r#"for (int i = 0; i < 10; i++) {
  continue;
}
"#;
        assert_eq!(f.to_string(), res);
    }
}