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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
// 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 comprehensive tools for creating and managing C functions in Rust.
//!
//! It allows for programmatic generation of C function declarations and definitions
//! with support for various function attributes, parameters, return types, and documentation.
//! This is particularly useful for generating C code or bindings from Rust.

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

use crate::{
    Attribute, Block, DocComment, Format, Formatter, RenderOptions, Statement, StorageClass, Type,
    declare_with, has_annotations, write_annotations,
};
use tamacro::DisplayFromFormat;

/// Represents a C function with all its components and attributes.
///
/// The `Function` struct enables the creation of complete C function declarations
/// and definitions, supporting inline, static, and extern modifiers, documentation,
/// parameter lists, return types, and function bodies.
///
/// # Examples
///
/// Basic function with a return value:
/// ```c
/// int main(void) {
///   return 0;
/// }
/// ```
///
/// Function with parameters and modifiers:
/// ```c
/// static inline double calculate_area(double width, double height) {
///   return width * height;
/// }
/// ```
///
/// External function declaration:
/// ```c
/// extern void process_data(char *buffer, size_t length);
/// ```
#[derive(Debug, Clone, DisplayFromFormat)]
pub struct Function {
    /// The name of the function
    pub name: String,

    /// The parameters of the function as a vector of Parameter objects
    pub params: Vec<Parameter>,

    /// The return type of the function
    pub ret: Type,

    /// Whether the function is declared with the 'inline' keyword
    pub is_inline: bool,

    /// The storage class (`static`, `extern`, or none). `static` and `extern`
    /// are mutually exclusive, so they share one field.
    pub storage: StorageClass,

    /// The body of the function. `None` means this is a prototype (a declaration
    /// only); `Some(block)` is a definition, even when the block is empty.
    pub body: Option<Block>,

    /// The attributes applied to the function (e.g. `noreturn`, `always_inline`)
    pub attrs: Vec<Attribute>,

    /// Raw macro/specifier tokens emitted verbatim at the leading annotation slot
    /// (e.g. an export macro like `MYLANG_API`, or `__declspec(dllexport)`).
    pub raw_attrs: Vec<String>,

    /// The optional documentation comment for the function
    pub doc: Option<DocComment>,
}

impl Function {
    /// Creates and returns a new `FunctionBuilder` to construct a `Function` using the builder pattern.
    ///
    /// This method simplifies the process of creating complex function declarations
    /// by providing an interface for defining all function components.
    ///
    /// # Parameters
    ///
    /// * `name` - The name of the function
    /// * `ret` - The return type of the function
    ///
    /// # Returns
    ///
    /// A `FunctionBuilder` instance that can be used to configure and build a `Function`
    ///
    /// # Examples
    ///
    /// ```rust
    /// let func = Function::new("calculate_sum".to_string(), Type::new(BaseType::Int).build())
    ///     .params(vec![
    ///         Parameter::new("a".to_string(), Type::new(BaseType::Int).build()),
    ///         Parameter::new("b".to_string(), Type::new(BaseType::Int).build())
    ///     ])
    ///     .body(Block::new()
    ///         .statement(Statement::Return(Some(Expr::Binary {
    ///             left: Box::new(Expr::Ident("a".to_string())),
    ///             op: BinOp::Add,
    ///             right: Box::new(Expr::Ident("b".to_string()))
    ///         })))
    ///         .build())
    ///     .build();
    /// ```
    pub fn new(name: String, ret: Type) -> FunctionBuilder {
        FunctionBuilder::new(name, ret)
    }

    /// Returns a prototype (declaration-only) copy of this function: same name,
    /// return type, parameters, and modifiers, but with the body dropped so it
    /// renders as `ret name(params);`
    ///
    /// This is the main way to place a declaration in a header while keeping
    /// the definition in a source file.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let def = FunctionBuilder::new_with_str("add", Type::new(BaseType::Int).build())
    ///     .body(Block::new().build())
    ///     .build();
    /// assert_eq!(def.to_prototype().to_string(), "int add(void);\n");
    /// ```
    pub fn to_prototype(&self) -> Function {
        let mut proto = self.clone();
        proto.body = None;
        proto
    }

    /// Returns `true` if this function is a prototype (has no body).
    pub fn is_prototype(&self) -> bool {
        self.body.is_none()
    }
}

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

        if has_annotations(&self.raw_attrs, &self.attrs) {
            write_annotations(fmt, &self.raw_attrs, &self.attrs)?;
            write!(fmt, " ")?;
        }

        if let Some(kw) = self.storage.keyword() {
            write!(fmt, "{kw} ")?;
        }

        if self.is_inline {
            write!(fmt, "inline ")?;
        }

        let params = if self.params.is_empty() {
            "void".to_string()
        } else {
            self.params
                .iter()
                .map(|p| p.render_with(fmt.options()))
                .collect::<Vec<_>>()
                .join(", ")
        };
        write!(
            fmt,
            "{}",
            declare_with(
                &self.ret,
                &format!("{}({})", self.name, params),
                fmt.options()
            )
        )?;

        match &self.body {
            Some(body) => {
                fmt.block(|fmt| body.format(fmt))?;
                writeln!(fmt)
            }
            None => writeln!(fmt, ";"),
        }
    }
}

/// A builder for constructing a `Function` instance with a fluent interface.
///
/// The `FunctionBuilder` provides a step-by-step approach to creating complex C functions
/// by allowing incremental configuration of all function attributes and components.
/// This helps ensure that function declarations are consistent and well-formed.
pub struct FunctionBuilder {
    name: String,
    params: Vec<Parameter>,
    ret: Type,
    is_inline: bool,
    storage: StorageClass,
    body: Option<Block>,
    attrs: Vec<Attribute>,
    raw_attrs: Vec<String>,
    doc: Option<DocComment>,
}

impl FunctionBuilder {
    /// Creates and returns a new `FunctionBuilder` with the specified name and return type.
    ///
    /// # Parameters
    ///
    /// * `name` - The name of the function as a String
    /// * `ret` - The return type of the function
    ///
    /// # Returns
    ///
    /// A new `FunctionBuilder` instance with default values for other properties
    ///
    /// # Examples
    ///
    /// ```rust
    /// let builder = FunctionBuilder::new("process_data".to_string(), Type::new(BaseType::Void).build());
    /// ```
    pub fn new(name: String, ret: Type) -> Self {
        Self {
            name,
            ret,
            params: vec![],
            is_inline: false,
            storage: StorageClass::None,
            body: None,
            attrs: vec![],
            raw_attrs: vec![],
            doc: None,
        }
    }

    /// Creates and returns a new `FunctionBuilder` using a string slice for the name.
    ///
    /// This is a convenience method that converts the provided string slice to a String
    /// before delegating to the standard `new` method.
    ///
    /// # Parameters
    ///
    /// * `name` - The name of the function as a string slice
    /// * `ret` - The return type of the function
    ///
    /// # Returns
    ///
    /// A new `FunctionBuilder` instance with the specified name and return type
    ///
    /// # Examples
    ///
    /// ```rust
    /// let builder = FunctionBuilder::new_with_str("get_value", Type::new(BaseType::Int).build());
    /// ```
    pub fn new_with_str(name: &str, ret: Type) -> Self {
        Self::new(name.to_string(), ret)
    }

    /// Sets the documentation comment for the function being built.
    ///
    /// # Parameters
    ///
    /// * `doc` - The documentation comment to attach to the function
    ///
    /// # Returns
    ///
    /// The builder instance for method chaining
    ///
    /// # Examples
    ///
    /// ```rust
    /// let builder = FunctionBuilder::new_with_str("calculate_area", Type::new(BaseType::Double).build())
    ///     .doc(DocComment::new("Calculates the area of a rectangle").build());
    /// ```
    pub fn doc(mut self, doc: DocComment) -> Self {
        self.doc = Some(doc);
        self
    }

    /// Makes the function inline by setting the `is_inline` flag to true.
    ///
    /// In C, the `inline` keyword provides a hint to the compiler that calls to this function
    /// should be replaced with the function body when possible.
    ///
    /// # Returns
    ///
    /// The builder instance for method chaining
    ///
    /// # Examples
    ///
    /// ```rust
    /// let builder = FunctionBuilder::new_with_str("add", Type::new(BaseType::Int).build())
    ///     .make_inline();
    /// ```
    pub fn make_inline(mut self) -> Self {
        self.is_inline = true;
        self
    }

    /// Makes the function static (internal linkage). Mutually exclusive with
    /// `extern`; calling this after `make_extern` replaces it.
    ///
    /// In C, the `static` keyword for functions limits the visibility of the function
    /// to the file in which it is defined.
    ///
    /// # Returns
    ///
    /// The builder instance for method chaining
    ///
    /// # Examples
    ///
    /// ```rust
    /// let builder = FunctionBuilder::new_with_str("helper_function", Type::new(BaseType::Void).build())
    ///     .make_static();
    /// ```
    pub fn make_static(mut self) -> Self {
        self.storage = StorageClass::Static;
        self
    }

    /// Makes the function extern.
    ///
    /// In C, the `extern` keyword indicates that the function is defined elsewhere,
    /// typically in another compilation unit.
    ///
    /// # Returns
    ///
    /// The builder instance for method chaining
    ///
    /// # Examples
    ///
    /// ```rust
    /// let builder = FunctionBuilder::new_with_str("external_api", Type::new(BaseType::Int).build())
    ///     .make_extern();
    /// ```
    pub fn make_extern(mut self) -> Self {
        self.storage = StorageClass::Extern;
        self
    }

    /// Sets the storage class explicitly.
    pub fn storage(mut self, storage: StorageClass) -> Self {
        self.storage = storage;
        self
    }

    /// Sets the body block for the function being built.
    ///
    /// # Parameters
    ///
    /// * `body` - The block of statements that form the function body
    ///
    /// # Returns
    ///
    /// The builder instance for method chaining
    ///
    /// # Examples
    ///
    /// ```rust
    /// let body = Block::new()
    ///     .statement(Statement::Return(Some(Expr::Int(0))))
    ///     .build();
    /// let builder = FunctionBuilder::new_with_str("main", Type::new(BaseType::Int).build())
    ///     .body(body);
    /// ```
    pub fn body(mut self, body: Block) -> Self {
        self.body = Some(body);
        self
    }

    /// Appends a statement to the function's body block.
    ///
    /// This is a convenience method that adds a single statement to the body
    /// without requiring a separate Block construction.
    ///
    /// # Parameters
    ///
    /// * `stmt` - The statement to append to the function body
    ///
    /// # Returns
    ///
    /// The builder instance for method chaining
    ///
    /// # Examples
    ///
    /// ```rust
    /// let builder = FunctionBuilder::new_with_str("print_message", Type::new(BaseType::Void).build())
    ///     .statement(Statement::Expression(Expr::FuncCall {
    ///         func: "printf".to_string(),
    ///         args: vec![Expr::String("Hello, World!\\n".to_string())]
    ///     }));
    /// ```
    pub fn statement(mut self, stmt: Statement) -> Self {
        self.body
            .get_or_insert_with(|| Block::new().build())
            .stmts
            .push(stmt);
        self
    }

    /// Appends a new line to the function's body block.
    ///
    /// This method adds a special `NewLine` statement that will be rendered as a blank line
    /// in the generated C code, which can be useful for separating logical sections
    /// of code to improve readability.
    ///
    /// # Returns
    ///
    /// The builder instance for method chaining
    ///
    /// # Examples
    ///
    /// ```rust
    /// let builder = FunctionBuilder::new_with_str("complex_function", Type::new(BaseType::Void).build())
    ///     .statement(Statement::Declaration {
    ///         name: "x".to_string(),
    ///         t: Type::new(BaseType::Int).build(),
    ///         init: Some(Expr::Int(0))
    ///     })
    ///     .new_line()
    ///     .statement(Statement::Expression(Expr::FuncCall {
    ///         func: "process".to_string(),
    ///         args: vec![Expr::Ident("x".to_string())]
    ///     }));
    /// ```
    pub fn new_line(mut self) -> Self {
        self.body
            .get_or_insert_with(|| Block::new().build())
            .stmts
            .push(Statement::NewLine);
        self
    }

    /// Appends a parameter to the function being built.
    ///
    /// # Parameters
    ///
    /// * `param` - The parameter to add to the function signature
    ///
    /// # Returns
    ///
    /// The builder instance for method chaining
    ///
    /// # Examples
    ///
    /// ```rust
    /// let param = Parameter::new("value".to_string(), Type::new(BaseType::Int).build()).build();
    /// let builder = FunctionBuilder::new_with_str("increment", Type::new(BaseType::Int).build())
    ///     .param(param);
    /// ```
    pub fn param(mut self, param: Parameter) -> Self {
        self.params.push(param);
        self
    }

    /// Sets the complete list of parameters for the function being built.
    ///
    /// This method replaces any previously added parameters with the provided list.
    ///
    /// # Parameters
    ///
    /// * `params` - A vector of Parameter objects representing the function parameters
    ///
    /// # Returns
    ///
    /// The builder instance for method chaining
    ///
    /// # Examples
    ///
    /// ```rust
    /// let params = vec![
    ///     Parameter::new("x".to_string(), Type::new(BaseType::Double).build()).build(),
    ///     Parameter::new("y".to_string(), Type::new(BaseType::Double).build()).build()
    /// ];
    /// let builder = FunctionBuilder::new_with_str("calculate_distance", Type::new(BaseType::Double).build())
    ///     .params(params);
    /// ```
    pub fn params(mut self, params: Vec<Parameter>) -> Self {
        self.params = params;
        self
    }

    /// Finalizes the function definition and returns a fully constructed `Function`.
    ///
    /// This method consumes the builder and produces the final `Function` object
    /// with all the configured properties.
    ///
    /// # Returns
    ///
    /// A fully constructed `Function` instance
    ///
    /// # Examples
    ///
    /// ```rust
    /// let func = FunctionBuilder::new_with_str("main", Type::new(BaseType::Int).build())
    ///     .body(Block::new()
    ///         .statement(Statement::Return(Some(Expr::Int(0))))
    ///         .build())
    ///     .build();
    /// ```
    /// Adds a single attribute (e.g. [`Attribute::noreturn`]) to the function.
    ///
    /// Function attributes are emitted at the front of the declaration, e.g.
    /// `__attribute__((noreturn)) void abort_(void);`.
    pub fn attr(mut self, attr: Attribute) -> Self {
        self.attrs.push(attr);
        self
    }

    /// Replaces the function's attribute list.
    pub fn attrs(mut self, attrs: Vec<Attribute>) -> Self {
        self.attrs = attrs;
        self
    }

    /// Adds a raw macro/specifier token emitted verbatim at the leading
    /// annotation slot, e.g. `.raw_attr("MYLANG_API")` or
    /// `.raw_attr("__declspec(dllexport)")`.
    pub fn raw_attr(mut self, token: &str) -> Self {
        self.raw_attrs.push(token.to_string());
        self
    }

    /// Replaces the function's raw annotation tokens.
    pub fn raw_attrs(mut self, tokens: Vec<String>) -> Self {
        self.raw_attrs = tokens;
        self
    }

    pub fn build(self) -> Function {
        Function {
            name: self.name,
            ret: self.ret,
            params: self.params,
            is_inline: self.is_inline,
            storage: self.storage,
            body: self.body,
            attrs: self.attrs,
            raw_attrs: self.raw_attrs,
            doc: self.doc,
        }
    }
}

/// Represents a single parameter in a C function declaration or definition.
///
/// A parameter consists of a name and a type, with special handling for array parameters.
/// This struct is used to generate the parameter list in C function signatures.
#[derive(Debug, Clone, DisplayFromFormat)]
pub struct Parameter {
    /// The name of the parameter
    pub name: String,

    /// The type of the parameter
    pub t: Type,

    /// The attributes applied to the parameter (e.g. `unused`)
    pub attrs: Vec<Attribute>,

    /// Raw macro/specifier tokens emitted verbatim before the parameter.
    pub raw_attrs: Vec<String>,
}

impl Parameter {
    /// Creates and returns a new `ParameterBuilder` to construct a `Parameter` using the builder pattern.
    ///
    /// # Parameters
    ///
    /// * `name` - The name of the parameter
    /// * `t` - The type of the parameter
    ///
    /// # Returns
    ///
    /// A new `ParameterBuilder` instance
    ///
    /// # Examples
    ///
    /// ```rust
    /// let builder = Parameter::new("buffer".to_string(),
    ///     Type::new(BaseType::Char).make_pointer().build());
    /// ```
    pub fn new(name: String, t: Type) -> ParameterBuilder {
        ParameterBuilder::new(name, t)
    }
}

/// A builder for constructing a `Parameter` instance with a fluent interface.
///
/// This builder simplifies the creation of function parameters by providing
/// a consistent interface aligned with the other builders in this module.
pub struct ParameterBuilder {
    name: String,
    t: Type,
    attrs: Vec<Attribute>,
    raw_attrs: Vec<String>,
}

impl ParameterBuilder {
    /// Creates and returns a new `ParameterBuilder` with the specified name and type.
    ///
    /// # Parameters
    ///
    /// * `name` - The name of the parameter as a String
    /// * `t` - The type of the parameter
    ///
    /// # Returns
    ///
    /// A new `ParameterBuilder` instance
    ///
    /// # Examples
    ///
    /// ```rust
    /// let builder = ParameterBuilder::new("count".to_string(), Type::new(BaseType::Int).build());
    /// ```
    pub fn new(name: String, t: Type) -> Self {
        Self {
            name,
            t,
            attrs: vec![],
            raw_attrs: vec![],
        }
    }

    /// Creates and returns a new `ParameterBuilder` using a string slice for the name.
    ///
    /// This is a convenience method that converts the provided string slice to a String
    /// before delegating to the standard `new` method.
    ///
    /// # Parameters
    ///
    /// * `name` - The name of the parameter as a string slice
    /// * `t` - The type of the parameter
    ///
    /// # Returns
    ///
    /// A new `ParameterBuilder` instance
    ///
    /// # Examples
    ///
    /// ```rust
    /// let builder = ParameterBuilder::new_with_str("size", Type::new(BaseType::SizeT).build());
    /// ```
    pub fn new_with_str(name: &str, t: Type) -> Self {
        Self::new(name.to_string(), t)
    }

    /// Finalizes the parameter definition and returns a fully constructed `Parameter`.
    ///
    /// This method consumes the builder and produces the final `Parameter` object
    /// with the configured name and type.
    ///
    /// # Returns
    ///
    /// A fully constructed `Parameter` instance
    ///
    /// # Examples
    ///
    /// ```rust
    /// let param = ParameterBuilder::new_with_str("data", Type::new(BaseType::Void).make_pointer().build())
    ///     .build();
    /// ```
    /// Adds a single attribute (e.g. [`Attribute::unused`]) to the parameter.
    ///
    /// Parameter attributes are emitted at the front of the parameter, e.g.
    /// `void f(__attribute__((unused)) int x)`.
    pub fn attr(mut self, attr: Attribute) -> Self {
        self.attrs.push(attr);
        self
    }

    /// Replaces the parameter's attribute list.
    pub fn attrs(mut self, attrs: Vec<Attribute>) -> Self {
        self.attrs = attrs;
        self
    }

    /// Adds a raw macro/specifier token emitted verbatim before the parameter.
    pub fn raw_attr(mut self, token: &str) -> Self {
        self.raw_attrs.push(token.to_string());
        self
    }

    /// Replaces the parameter's raw annotation tokens.
    pub fn raw_attrs(mut self, tokens: Vec<String>) -> Self {
        self.raw_attrs = tokens;
        self
    }

    pub fn build(self) -> Parameter {
        Parameter {
            name: self.name,
            t: self.t,
            attrs: self.attrs,
            raw_attrs: self.raw_attrs,
        }
    }
}

impl Parameter {
    /// Renders this parameter as a C declarator (its type with the parameter
    /// name threaded through), e.g. `int x`, `char *s`, or `void (*cb)(int)`
    pub fn declarator(&self) -> String {
        self.declarator_with(RenderOptions::default())
    }

    /// Like [`declarator`](Self::declarator), but renders any option-sensitive
    /// pieces of the type (e.g. an `alignof` inside an array size) using the
    /// given [`RenderOptions`].
    pub fn declarator_with(&self, opts: RenderOptions) -> String {
        declare_with(&self.t, &self.name, opts)
    }

    /// Renders this parameter including any leading attributes, in the given
    /// style, e.g. `__attribute__((unused)) int x`.
    pub fn render(&self, style: crate::AttrStyle) -> String {
        self.render_with(RenderOptions {
            attr_style: style,
            ..Default::default()
        })
    }

    /// Like [`render`](Self::render), but takes full [`RenderOptions`] so the
    /// declarator and its attributes render consistently with the ambient
    /// formatter.
    ///
    /// A parameter is rendered as a string because it is spliced into the middle
    /// of a function declarator's parameter list; this simply drives the
    /// [`Format`] impl over a scratch buffer so both paths stay in sync.
    pub fn render_with(&self, opts: RenderOptions) -> String {
        crate::render(self, opts)
    }
}

impl Format for Parameter {
    fn format(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
        if has_annotations(&self.raw_attrs, &self.attrs) {
            write_annotations(fmt, &self.raw_attrs, &self.attrs)?;
            write!(fmt, " ")?;
        }
        write!(fmt, "{}", declare_with(&self.t, &self.name, fmt.options()))
    }
}

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

    #[test]
    fn function() {
        let f = FunctionBuilder::new_with_str("some_function", Type::new(BaseType::Double).build())
            .make_inline()
            .param(
                ParameterBuilder::new_with_str("val", Type::new(BaseType::Double).build()).build(),
            )
            .body(
                Block::new()
                    .statement(Statement::Return(Some(Expr::Binary {
                        left: Box::new(Expr::Double(1.23)),
                        op: BinOp::Add,
                        right: Box::new(Expr::Ident("val".to_string())),
                    })))
                    .build(),
            )
            .build();
        let res = r#"inline double some_function(double val) {
  return 1.23 + val;
}
"#;
        assert_eq!(f.to_string(), res);
    }

    #[test]
    fn prototype() {
        let proto = FunctionBuilder::new_with_str("foo", Type::new(BaseType::Void).build()).build();
        assert_eq!(proto.to_string(), "void foo(void);\n");
    }

    #[test]
    fn empty_definition() {
        let empty = FunctionBuilder::new_with_str("arse", Type::new(BaseType::Void).build())
            .body(Block::new().build())
            .build();
        assert_eq!(empty.to_string(), "void arse(void) {\n}\n");
    }

    #[test]
    fn extern_prototype() {
        let ext = FunctionBuilder::new_with_str("lol", Type::new(BaseType::Int).build())
            .make_extern()
            .build();
        assert_eq!(ext.to_string(), "extern int lol(void);\n");
    }

    #[test]
    fn static_inline_definition() {
        let f = FunctionBuilder::new_with_str("x", Type::new(BaseType::Int).build())
            .make_static()
            .make_inline()
            .body(
                Block::new()
                    .statement(Statement::Return(Some(Expr::Int(0))))
                    .build(),
            )
            .build();
        assert_eq!(
            f.to_string(),
            "static inline int x(void) {\n  return 0;\n}\n"
        );
    }

    #[test]
    fn storage_class_is_mutually_exclusive() {
        // The last storage setter wins. you can never get `extern static`
        let f = FunctionBuilder::new_with_str("f", Type::new(BaseType::Int).build())
            .make_static()
            .make_extern()
            .build();
        assert_eq!(f.storage, StorageClass::Extern);
        assert_eq!(f.to_string(), "extern int f(void);\n");

        let g = FunctionBuilder::new_with_str("g", Type::new(BaseType::Int).build())
            .make_extern()
            .make_static()
            .build();
        assert_eq!(g.storage, StorageClass::Static);
        assert_eq!(g.to_string(), "static int g(void);\n");
    }
}