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
// 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 functionality for generating and formatting different types of comments
//! in C code. It supports standard C-style comments, heading comments for section organization,
//! and documentation comments typically used before functions, structs, and other declarations.
//!
//! The components in this module are:
//! - `Comment`: Represents regular C-style comments (single-line or multi-line)
//! - `CommentBuilder`: Facilitates constructing comments using the builder pattern
//! - `DocComment`: Represents documentation comments in C (using `///` style)
//! - `DocCommentBuilder`: Facilitates constructing documentation comments
//!
//! Use this module to add properly formatted comments to generated C code for improved
//! readability, documentation, and code organization.

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

use crate::{Format, Formatter};
use tamacro::DisplayFromFormat;

/// Represents a C-style comment in generated code. This struct supports both standard
/// single-line comments and special heading-style comments that are surrounded by
/// separator lines for visual emphasis.
///
/// ## Comment Types
///
/// This struct can represent two types of comments:
/// 1. **Standard Comments**: Normal comments prefixed with `//`
/// 2. **Heading Comments**: Comments surrounded by horizontal lines of slashes to create
///    visual separation between code sections
///
/// ## Usage
///
/// Comments are used for:
/// - Explaining code behavior and intent
/// - Marking sections of code
/// - Providing context for implementation details
/// - Temporarily disabling code (commenting out)
///
/// ## Examples
///
/// ### Standard Comment
/// ```c
/// // This is a standard comment
/// // It can span multiple lines
/// ```
///
/// ### Heading Comment
/// ```c
/// ////////////////////////////////////////////////////////////////////////////////
/// // This is a heading comment used to mark a major section of code
/// ////////////////////////////////////////////////////////////////////////////////
/// ```
#[derive(Debug, Clone, DisplayFromFormat)]
pub struct Comment {
    /// The text content of the comment, which may contain multiple lines.
    /// Each line will be prefixed with `//` during formatting.
    pub comment: String,

    /// Controls whether the comment is formatted as a heading comment.
    /// When true, the comment will be surrounded by lines of slashes.
    pub is_heading: bool,
}

impl Comment {
    /// Creates and returns a new `CommentBuilder` to construct a `Comment` using the builder pattern.
    ///
    /// This method is the recommended entry point for creating comments as it provides
    /// a fluent API for setting comment text and style.
    ///
    /// ## Example
    ///
    /// ```rust
    /// // Create a standard comment
    /// let standard_comment = Comment::new()
    ///     .comment_with_str("This explains the following code")
    ///     .build();
    ///
    /// // Create a heading comment
    /// let heading_comment = Comment::new()
    ///     .comment_with_str("INITIALIZATION SECTION")
    ///     .heading(true)
    ///     .build();
    /// ```
    pub fn new() -> CommentBuilder {
        CommentBuilder::new()
    }

    /// Internal helper method to add horizontal separator lines for heading comments.
    ///
    /// This method generates a line of slashes that spans most of the available width,
    /// taking into account the current indentation level.
    ///
    /// ## Parameters
    ///
    /// - `fmt`: The formatter to write to
    ///
    /// ## Returns
    ///
    /// A `fmt::Result` indicating success or failure of the write operation
    fn push_heading(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
        if self.is_heading {
            writeln!(
                fmt,
                "{}",
                "/".repeat(80usize.saturating_sub(fmt.current_indent()))
            )?;
        }

        Ok(())
    }
}

impl Format for Comment {
    fn format(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
        self.push_heading(fmt)?;
        for line in self.comment.lines() {
            writeln!(fmt, "// {line}")?;
        }
        self.push_heading(fmt)
    }
}

/// A builder for constructing `Comment` instances in a fluent, chainable manner.
///
/// This builder provides methods for setting the comment text and controlling
/// whether it's formatted as a heading comment. It follows the builder pattern
/// to allow method chaining for a more readable and flexible API.
pub struct CommentBuilder {
    comment: String,
    is_heading: bool,
}

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

impl CommentBuilder {
    /// Creates and returns a new `CommentBuilder` instance with default settings.
    ///
    /// The new builder starts with an empty comment and is not set as a heading comment.
    ///
    /// ## Example
    ///
    /// ```rust
    /// let builder = CommentBuilder::new();
    /// let comment = builder
    ///     .comment_with_str("Some explanation here")
    ///     .build();
    /// ```
    pub fn new() -> Self {
        Self {
            comment: String::new(),
            is_heading: false,
        }
    }

    /// Creates a new `CommentBuilder` initialized with the provided comment text.
    ///
    /// This is a convenience method that creates a builder with pre-filled comment text,
    /// but still defaults to a standard (non-heading) comment style.
    ///
    /// ## Parameters
    ///
    /// - `comment`: The initial text content for the comment
    ///
    /// ## Returns
    ///
    /// A new `CommentBuilder` with the provided text
    ///
    /// ## Example
    ///
    /// ```rust
    /// let comment = CommentBuilder::new_with_str("Important note about this code")
    ///     .build();
    /// ```
    pub fn new_with_str(comment: &str) -> Self {
        Self {
            comment: comment.to_string(),
            is_heading: false,
        }
    }

    /// Sets the comment text for the builder using a String.
    ///
    /// This method overwrites any previously set comment text.
    ///
    /// ## Parameters
    ///
    /// - `comment`: The text content for the comment as a String
    ///
    /// ## Returns
    ///
    /// The builder instance for method chaining
    ///
    /// ## Example
    ///
    /// ```rust
    /// let dynamic_text = format!("Count: {}", some_value);
    /// let comment = CommentBuilder::new()
    ///     .comment(dynamic_text)
    ///     .build();
    /// ```
    pub fn comment(mut self, comment: String) -> Self {
        self.comment = comment;
        self
    }

    /// Sets the comment text for the builder using a string slice.
    ///
    /// This is a convenience method that converts the string slice to a String
    /// and then sets it as the comment text.
    ///
    /// ## Parameters
    ///
    /// - `comment`: The text content for the comment as a string slice
    ///
    /// ## Returns
    ///
    /// The builder instance for method chaining
    ///
    /// ## Example
    ///
    /// ```rust
    /// let comment = CommentBuilder::new()
    ///     .comment_with_str("This function calculates the average")
    ///     .build();
    /// ```
    pub fn comment_with_str(self, comment: &str) -> Self {
        self.comment(comment.to_string())
    }

    /// Controls whether the comment should be formatted as a heading comment.
    ///
    /// Heading comments are surrounded by lines of slashes for visual emphasis,
    /// making them useful for marking major sections of code.
    ///
    /// ## Parameters
    ///
    /// - `b`: Set to true for a heading comment, false for a standard comment
    ///
    /// ## Returns
    ///
    /// The builder instance for method chaining
    ///
    /// ## Example
    ///
    /// ```rust
    /// let section_header = CommentBuilder::new()
    ///     .comment_with_str("HELPER FUNCTIONS")
    ///     .heading(true)
    ///     .build();
    /// ```
    pub fn heading(mut self, b: bool) -> Self {
        self.is_heading = b;
        self
    }

    /// Consumes the builder and returns a new `Comment` instance.
    ///
    /// This method finalizes the building process and returns the constructed comment
    /// with the text and style settings configured during the build process.
    ///
    /// ## Returns
    ///
    /// A new `Comment` instance with the configured settings
    ///
    /// ## Example
    ///
    /// ```rust
    /// let comment = CommentBuilder::new()
    ///     .comment_with_str("Important implementation detail")
    ///     .build();
    /// ```
    pub fn build(self) -> Comment {
        Comment {
            comment: self.comment,
            is_heading: self.is_heading,
        }
    }
}

/// Represents a documentation comment in C code, using the `///` style syntax.
///
/// Documentation comments are special comments typically placed before function declarations,
/// struct definitions, typedefs, and other code elements to document their purpose, parameters,
/// return values, and other important information.
///
/// ## Usage
///
/// Doc comments are typically used to document:
/// - Function signatures (parameters, return values, exceptions)
/// - Data structures and their fields
/// - Global variables and constants
/// - Type definitions
/// - File/module purpose
///
/// ## Example
///
/// ```c
/// /// Calculates the square of a number
/// ///
/// /// @param value The input number to square
/// /// @return The square of the input value
/// int square(int value);
/// ```
#[derive(Debug, Clone, DisplayFromFormat)]
pub struct DocComment {
    /// Lines of documentation comment text.
    /// Each line will be prefixed with `///` during formatting.
    pub docs: Vec<String>,
}

impl DocComment {
    /// Creates and returns a new `DocCommentBuilder` to construct a `DocComment` using the builder pattern.
    ///
    /// This method is the recommended entry point for creating documentation comments as it provides
    /// a fluent API for building multi-line documentation.
    ///
    /// ## Example
    ///
    /// ```rust
    /// let doc_comment = DocComment::new()
    ///     .line_str("Calculates the factorial of a number")
    ///     .line_str("")
    ///     .line_str("@param n The input number")
    ///     .line_str("@return The factorial of n")
    ///     .build();
    /// ```
    pub fn new() -> DocCommentBuilder {
        DocCommentBuilder::new()
    }
}

impl Format for DocComment {
    fn format(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
        for line in &self.docs {
            writeln!(fmt, "/// {line}")?;
        }
        Ok(())
    }
}

/// A builder for constructing `DocComment` instances in a fluent, chainable manner.
///
/// This builder provides methods for building documentation comments line by line
/// or from larger text blocks. It follows the builder pattern to allow method chaining
/// for a more readable and flexible API.
pub struct DocCommentBuilder {
    docs: Vec<String>,
}

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

impl DocCommentBuilder {
    /// Creates and returns a new `DocCommentBuilder` instance with an empty set of documentation lines.
    ///
    /// ## Example
    ///
    /// ```rust
    /// let builder = DocCommentBuilder::new();
    /// let doc = builder
    ///     .line_str("Function description here")
    ///     .line_str("@param name Description of parameter")
    ///     .build();
    /// ```
    pub fn new() -> Self {
        Self { docs: vec![] }
    }

    /// Appends a single line of documentation text to the comment using a String.
    ///
    /// ## Parameters
    ///
    /// - `line`: The line of text to add as a String
    ///
    /// ## Returns
    ///
    /// The builder instance for method chaining
    ///
    /// ## Example
    ///
    /// ```rust
    /// let param_desc = format!("@param count Maximum number (default: {})", DEFAULT_COUNT);
    /// let doc = DocCommentBuilder::new()
    ///     .line(param_desc)
    ///     .build();
    /// ```
    pub fn line(self, line: String) -> Self {
        self.line_str(&line)
    }

    /// Appends a single line of documentation text to the comment using a string slice.
    ///
    /// This method handles empty lines by preserving them in the documentation comment.
    /// Empty lines are useful for separating sections within documentation.
    ///
    /// ## Parameters
    ///
    /// - `line`: The line of text to add as a string slice
    ///
    /// ## Returns
    ///
    /// The builder instance for method chaining
    ///
    /// ## Example
    ///
    /// ```rust
    /// let doc = DocCommentBuilder::new()
    ///     .line_str("Parses a configuration file")
    ///     .line_str("")  // Empty line for visual separation
    ///     .line_str("@param path Path to the configuration file")
    ///     .build();
    /// ```
    pub fn line_str(mut self, line: &str) -> Self {
        self.docs.push(if line.is_empty() {
            String::new()
        } else {
            line.to_string()
        });
        self
    }

    /// Adds a multi-line block of text to the documentation comment using a String.
    ///
    /// This method splits the input text by newlines and adds each line separately.
    /// It also handles line wrapping for long lines to maintain readability.
    ///
    /// ## Parameters
    ///
    /// - `text`: The multi-line text block as a String
    ///
    /// ## Returns
    ///
    /// The builder instance for method chaining
    ///
    /// ## Example
    ///
    /// ```rust
    /// let description = format!(
    ///     "Processes data according to the specified algorithm.\n\n\
    ///     The processing has a complexity of O(n) where n is {}.",
    ///     complexity_description
    /// );
    /// let doc = DocCommentBuilder::new()
    ///     .text(description)
    ///     .build();
    /// ```
    pub fn text(self, text: String) -> Self {
        self.text_str(&text)
    }

    /// Adds a multi-line block of text to the documentation comment using a string slice.
    ///
    /// This method processes the text block and adds it to the documentation comment with
    /// intelligent line handling:
    /// 1. Splits the input by newlines
    /// 2. Preserves empty lines
    /// 3. Performs line wrapping for lines longer than 80 characters
    ///
    /// ## Parameters
    ///
    /// - `text`: The multi-line text block as a string slice
    ///
    /// ## Returns
    ///
    /// The builder instance for method chaining
    ///
    /// ## Example
    ///
    /// ```rust
    /// let doc = DocCommentBuilder::new()
    ///     .text_str(
    ///         "This function implements the algorithm described in:\n\
    ///         Smith, J. (2023). Efficient Algorithms for Data Processing.\n\n\
    ///         Note: The implementation uses recursion and may cause stack overflow\
    ///         with extremely large inputs."
    ///     )
    ///     .build();
    /// ```
    pub fn text_str(self, text: &str) -> Self {
        const MAX_WIDTH: usize = 80;
        let mut res = self;
        for line in text.lines() {
            if line.chars().count() <= MAX_WIDTH {
                res = res.line_str(line);
                continue;
            }

            let mut current = String::new();
            let mut current_len = 0usize;
            for word in line.split(' ') {
                let word_len = word.chars().count();
                if current.is_empty() {
                    current.push_str(word);
                    current_len = word_len;
                } else if current_len + 1 + word_len <= MAX_WIDTH {
                    current.push(' ');
                    current.push_str(word);
                    current_len += 1 + word_len;
                } else {
                    res = res.line_str(&current);
                    current = word.to_string();
                    current_len = word_len;
                }
            }

            if !current.is_empty() {
                res = res.line_str(&current);
            }
        }
        res
    }

    /// Consumes the builder and returns a new `DocComment` instance.
    ///
    /// This method finalizes the building process and returns the constructed documentation
    /// comment containing all the lines added during the building process.
    ///
    /// ## Returns
    ///
    /// A new `DocComment` instance with the configured documentation lines
    ///
    /// ## Example
    ///
    /// ```rust
    /// let complete_doc = DocCommentBuilder::new()
    ///     .line_str("Encrypts data using the specified algorithm")
    ///     .line_str("")
    ///     .line_str("@param data The data to encrypt")
    ///     .line_str("@param key The encryption key")
    ///     .line_str("@return The encrypted data or NULL on failure")
    ///     .build();
    /// ```
    pub fn build(self) -> DocComment {
        DocComment { docs: self.docs }
    }
}

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

    #[test]
    fn comment() {
        let mut c = CommentBuilder::new_with_str("Hello, world").build();
        assert_eq!(c.to_string(), "// Hello, world\n");

        c = CommentBuilder::new_with_str("abc").heading(true).build();
        assert_eq!(
            c.to_string(),
            "////////////////////////////////////////////////////////////////////////////////\n// abc\n////////////////////////////////////////////////////////////////////////////////\n"
        );
    }

    #[test]
    fn doc_comment() {
        let mut c = DocComment::new().text_str("Hello\nworld").build();
        assert_eq!(c.to_string(), "/// Hello\n/// world\n");

        c = DocComment::new().line_str("ABC").build();
        assert_eq!(c.to_string(), "/// ABC\n");
    }

    #[test]
    fn text_str_single_char() {
        let c = DocComment::new().text_str("x").build();
        assert_eq!(c.to_string(), "/// x\n");
    }

    #[test]
    fn text_str_non_ascii() {
        let c = DocComment::new().text_str("café 島津").build();
        assert_eq!(c.to_string(), "/// café 島津\n");
    }

    #[test]
    fn text_str_wraps_without_corruption() {
        let long = format!("{} {}", "A".repeat(82), "B".repeat(5));
        let docs = DocCommentBuilder::new().text_str(&long).build().docs;
        assert_eq!(docs, vec!["A".repeat(82), "B".repeat(5)]);
    }
}