Module code_writer

Module code_writer 

Source
Expand description

Code writer with automatic indentation tracking for code generation.

This module provides a CodeWriter that simplifies generating properly indented code in C-like languages (Swift, TypeScript, Go, Java, etc.).

§Features

  • RAII-based indentation: Use indent() to get a guard that automatically manages indentation levels
  • No borrow checker fights: Uses Rc<Cell<usize>> internally so indent guards don’t conflict with mutable writes
  • C-like syntax helpers: Built-in support for blocks, comments, parentheses
  • Format macros: cw_write! and cw_writeln! for formatted output

§Basic Example

use roam_codegen::code_writer::CodeWriter;
use roam_codegen::{cw_write, cw_writeln};

let mut output = String::new();
let mut w = CodeWriter::with_indent_spaces(&mut output, 4);

w.writeln("class Example {").unwrap();
{
    let _indent = w.indent();
    w.writeln("private let value: Int").unwrap();
    w.blank_line().unwrap();

    cw_writeln!(w, "func compute() -> Int {{").unwrap();
    {
        let _indent = w.indent();
        cw_writeln!(w, "return value * 2").unwrap();
    }
    w.writeln("}").unwrap();
}
w.writeln("}").unwrap();

§Using the block Helper

For common brace-delimited blocks, use the block helper:

use roam_codegen::code_writer::CodeWriter;

let mut output = String::new();
let mut w = CodeWriter::with_indent_spaces(&mut output, 2);

w.block("class Foo", |w| {
    w.writeln("let x = 42")?;
    w.block("func bar()", |w| {
        w.writeln("return x")
    })
}).unwrap();

§Comma-Separated Lists

use roam_codegen::code_writer::CodeWriter;

let mut output = String::new();
let mut w = CodeWriter::with_indent_spaces(&mut output, 2);

w.write("func(").unwrap();
w.write_separated(vec!["a: Int", "b: String"], ", ", |w, item| {
    w.write(item)
}).unwrap();
w.write(")").unwrap();
// Output: "func(a: Int, b: String)"

Structs§

CodeWriter
A code writer that tracks indentation and provides helpers for generating C-like syntax (used by Swift, TypeScript, Go, etc.)
IndentGuard
RAII guard that maintains indentation level