Skip to main content

compile

Function compile 

Source
pub fn compile(layout: Box<Layout>) -> Box<Doc>
Expand description

Compiles a layout into an optimized document (fast path)

This is the main entry point for high-performance compilation. It executes all 10 compiler passes using efficient bump allocation and panics on errors for maximum speed. Use this function when you’re confident in your layout structure and want minimal overhead.

The compilation process transforms the input Layout through multiple intermediate representations, applying optimizations at each step to produce a Doc ready for efficient rendering.

§Arguments

  • layout - The input layout tree to compile. Must be a valid layout structure created using constructor functions like text, comp, etc.

§Returns

A boxed Doc containing the optimized document structure. The document can be rendered multiple times with different parameters without recompilation.

§Panics

This function panics if compilation encounters any errors:

  • Stack overflow: When layout nesting exceeds system stack limits (typically >10,000 levels)
  • Memory allocation failure: When bump allocators cannot allocate memory
  • Internal compiler errors: Unexpected states during pass execution

For error handling without panics, use compile_safe() or compile_safe_with_depth().

§Performance Notes

  • Time: O(n) where n is the number of layout nodes
  • Memory: Uses 10 temporary bump allocators during compilation
  • Stack: Recursive compilation requires stack space proportional to nesting depth
  • Optimal for: Production code with validated layouts where panics are acceptable

§Examples

§Basic Text Layout

use typeset::{compile, render, text};

let layout = text("Hello, world!".to_string());
let doc = compile(layout);
let output = render(doc, 2, 80);
assert_eq!(output, "Hello, world!");

§Complex Nested Layout

use typeset::{compile, render, text, comp, nest, grp};

// Create a function definition layout
let layout = grp(comp(
    text("function".to_string()),
    nest(comp(
        text("calculateSum(a, b)".to_string()),
        comp(
            text("{".to_string()),
            nest(text("return a + b;".to_string())),
            true, false
        ),
        false, false
    )),
    true, false
));

let doc = compile(layout);
let output = render(doc, 4, 40);
// Will produce properly formatted function with indentation

§Performance-Critical Batch Compilation

use typeset::{compile, render, text};

// Compile multiple layouts efficiently
let layouts = vec![
    text("item1".to_string()),
    text("item2".to_string()),
    text("item3".to_string()),
];

let docs: Vec<_> = layouts.into_iter()
    .map(|layout| compile(layout))
    .collect();

// Render all with consistent formatting
for doc in docs {
    let output = render(doc, 2, 80);
    println!("{}", output);
}

§See Also