Skip to main content

Crate tamago

Crate tamago 

Source
Expand description

Library for generating C code

This library provides an API for generating C source code. It allows structured generation of C code using Rust, ensuring proper formatting and structure while maintaining readability.

Notable capabilities include a recursive type model with a real declarator algorithm (so pointers, arrays, and function pointers nest correctly), precedence-aware expression printing that inserts only the parentheses a given grouping requires, and translation-unit splitting into a matching header and source pair via Module.

§Modules

  • function: Defines and formats C functions.
  • preprocessor: Manages preprocessor directives like #include, #define, and #pragma.
  • variable: Handles variable declarations.
  • types: Defines C types and type qualifiers.
  • storage: TODO
  • structs: Supports defining and managing C struct types.
  • union: Provides utilities for defining and formatting C unions.
  • typedef: Facilitates creating typedef aliases for types in C.
  • loops: Constructs and formats C loop structures (for, while, do-while).
  • conditional: Handles conditional statements like if, switch.
  • formatter: Provides utilities for formatting generated C code.
  • scope: Defines scope management for C code generation.
  • module: Splits a translation unit into a matching header (.h) and source (.c) pair.
  • ident: Identifier hygiene — sanitizing names, C keyword checks, and fresh-name generation.
  • attribute: GNU/C23 attributes (packed, noreturn, aligned, …) for items.
  • static_assert: _Static_assert/static_assert compile-time assertions.
  • block: Manages blocks of code within functions and control structures.
  • comment: Supports adding inline and documentation comments.
  • expr: Handles C expressions and operations.
  • enums: Supports enumeration (enum) type definitions.

§Example Usage

use tamago::{BaseType, Block, FunctionBuilder, ParameterBuilder, Type};

let func = FunctionBuilder::new_with_str("my_function", Type::new(BaseType::Int).build())
    .param(
        ParameterBuilder::new_with_str(
            "param1",
            Type::new(BaseType::Float).build(),
        )
        .build(),
    )
    .body(Block::new().build())
    .build();

println!("{}", func);

This will generate the following C function:

int my_function(float param1) {
}

Structs§

AnonAggregate
An inline anonymous aggregate used as the “type” of a Field.
Attribute
A single C attribute, such as packed, aligned(8), or format(printf, 1, 2).
Block
Represents a scoped block of code in C, delimited by curly braces {}. A Block contains a sequence of statements that are executed together within the same lexical scope.
BlockBuilder
A builder for constructing Block instances in a fluent, chainable manner.
Comment
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.
CommentBuilder
A builder for constructing Comment instances in a fluent, chainable manner.
DoWhile
Represents a do-while loop in C.
DoWhileBuilder
A builder for constructing a DoWhile loop instance.
DocComment
Represents a documentation comment in C code, using the /// style syntax.
DocCommentBuilder
A builder for constructing DocComment instances in a fluent, chainable manner.
Enum
Represents a complete enum declaration in C programming language.
EnumBuilder
A builder for constructing an Enum instance incrementally.
ErrorDirective
Represents the #error preprocessor directive in C.
ErrorDirectiveBuilder
A builder for constructing a Parameter instance with a fluent interface.
Field
Represents a struct field in C.
FieldBuilder
A builder for constructing a Field instance.
For
ForBuilder
A builder for constructing a For loop instance.
Formatter
Formatter for a scope.
FuncMacro
Represents a function-like macro in C.
FuncMacroBuilder
A builder for constructing a FuncMacro with a fluent interface.
Function
Represents a C function with all its components and attributes.
FunctionBuilder
A builder for constructing a Function instance with a fluent interface.
Gensym
A generator of fresh, unique identifiers.
If
Represents an if statement in C programming language.
IfBuilder
A builder for constructing an If statement instance incrementally.
IfDefDirective
Represents the C preprocessor #ifdef and #ifndef directives.
IfDefDirectiveBuilder
A builder for constructing a complete IfDefDirective instance.
IfDirective
Represents the C preprocessor #if directive.
IfDirectiveBuilder
A builder for constructing a complete IfDirective instance.
Include
Represents the #include preprocessor directive in C.
IncludeBuilder
A builder for constructing an Include instance with a fluent interface.
LineDirective
Represents the C preprocessor #line directive.
Module
A C translation unit: a header (.h) and a source (.c) generated together.
ModuleBuilder
A builder for Module with helpers that route declarations and definitions to the header or the source automatically.
ObjMacro
Represents an object-like macro in C.
ObjMacroBuilder
A builder for constructing an ObjMacro with a fluent interface.
Parameter
Represents a single parameter in a C function declaration or definition.
ParameterBuilder
A builder for constructing a Parameter instance with a fluent interface.
PragmaDirective
Represents a #pragma preprocessor directive in C.
PragmaDirectiveBuilder
A builder for constructing a PragmaDirective with a fluent interface.
RenderOptions
Options that control how code is rendered. Use with render, render_to, render_to_io, or Formatter::with_options.
Scope
Represents a global scope in C, serving as the root container for all C code elements.
ScopeBuilder
A builder for constructing a Scope instance using the builder pattern.
SourceLoc
A source location used for #line mapping: a file path and a 1-based line number in the original (pre-generation) source
StaticAssert
A _Static_assert(cond, "message") compile-time assertion.
Struct
Represents a struct in C.
StructBuilder
A builder for constructing a Struct instance.
Switch
Represents a switch statement in C programming language.
SwitchBuilder
A builder for constructing a Switch statement instance incrementally.
TypeBuilder
A builder for constructing a Type instance with a fluent interface.
TypeDef
Represents a C-style typedef declaration.
TypeDefBuilder
A builder for constructing a TypeDef instance.
Union
Represents a C union with its fields and attributes.
UnionBuilder
A builder for constructing a Union instance with a fluent interface.
Variable
Represents a C variable with its properties and attributes.
VariableBuilder
A builder for constructing a Variable instance with a fluent interface.
Variant
Represents an individual enum variant (constant) within a C enum declaration.
VariantBuilder
A builder for constructing a Variant instance incrementally.
WarningDirective
Represents the C preprocessor #warning directive.
WarningDirectiveBuilder
A builder for constructing a WarningDirective instance.
While
Represents a standard while loop in C.
WhileBuilder
A builder for constructing a While loop instance.

Enums§

AggregateKind
Whether an inline anonymous aggregate member is a struct or a union.
AssignOp
Encapsulates assignment operators used in C expressions.
AttrStyle
The spelling style used when emitting attributes.
BaseType
Represents all base types used in C.
BinOp
Encapsulates binary operators used in C expressions.
BraceStyle
Where the opening brace of a block is placed.
EncodingPrefix
The encoding prefix for a string or character literal.
Expr
Encapsulates all types of expressions in C.
ForInit
Represents a for loop in C, which consists of initialization, condition, step expressions, and a body block of statements.
GlobalStatement
Represents a global statement in C that can appear at the top level of a C file.
HeaderGuard
Controls how a module’s header protects itself against multiple inclusion
IndentStyle
How each level of indentation is rendered.
IntBase
The radix used to render an Expr::IntLit.
IntSuffix
The suffix applied to an Expr::IntLit, controlling its type.
Macro
Represents a macro definition in C, either object-like or function-like.
ScopeOrBlock
Represents a container that holds either a Scope or a Block.
Statement
Represents the various types of statements and preprocessor directives that can appear within a C code block.
StorageClass
A C storage-class specifier.
Type
A recursive description of a C type, built out of a base type wrapped in any number of pointer, array, and function derivations.
TypeQualifier
Represents type qualifiers in C.
UnaryOp
Encapsulates unary operators used in C expressions.

Constants§

C_KEYWORDS
The reserved keywords of C, covering C11 (including the _-prefixed keywords) and the additions introduced by C23.

Traits§

Format

Functions§

declare
Renders a full C declaration for ty naming the declarator inner.
declare_with
Like declare, but renders any option-sensitive sub-expressions (notably an array size such as alignof(T)) using the given RenderOptions instead of the defaults. When a Type is formatted through a Formatter, this is called with the formatter’s own options so nested spellings stay consistent.
format_annotations
Renders raw macro/specifier tokens followed by the typed attribute group, or the empty string if both are empty
format_attrs
Renders a list of attributes in the given style, or the empty string if the list is empty.
has_annotations
Returns whether an annotation slot would render to anything — i.e. there is at least one raw specifier token or one typed attribute. Handy for deciding separating whitespace around write_annotations.
is_c_keyword
Returns true if s is a reserved C keyword (see C_KEYWORDS)
render
Renders any Format value to a String using the given RenderOptions.
render_to
Streams a Format value into any fmt::Write sink instead of building one big String first. This matters for large translation units, where the intermediate String would be sizable.
render_to_io
Streams a Format value directly into an io::Write sink (a file, a socket, stdout, …) without an intermediate String :)
sanitize_ident
Rewrites an arbitrary string into a valid C identifier.
sanitize_ident_strict
Like sanitize_ident, but additionally guarantees the result is not in C’s reserved identifier space.
write_annotations
Writes the combined annotation slot (raw specifier tokens followed by the grouped typed attributes) into fmt in the ambient AttrStyle, or nothing if both are empty.
write_attrs
Writes a group of attributes into fmt as a single __attribute__((...)) / [[...]] group, in the formatter’s ambient AttrStyle, or nothing if the list is empty.