Skip to content

Explore Code Emission Patterns: Templates vs Builders #150

Description

@clank-hayen

Overview

This issue tracks the exploration of two code emission patterns for the Bishop compiler codegen phase. The goal is to prototype both approaches and compare them to make an informed decision about which pattern to adopt.

Background

The current codegen uses inline string concatenation with `fmt::format()`. While functional, this approach has limitations:

  • String patterns are scattered throughout code
  • Indentation is manually managed
  • Hard to see the final code shape

Approaches to Compare

Template-based Emission

  • External `.cpp.tmpl` template files with placeholders
  • `render_template()` function substitutes variables
  • Templates show code shape at a glance
  • Examples in `codegen/templates/`

Pros:

  • Templates look like actual C++ code
  • Easy to modify output format
  • Separation between structure and logic

Cons:

  • Additional file I/O for templates
  • Limited logic in templates
  • Debugging template issues can be harder

Builder Pattern

  • Fluent API with `CppBuilder` class
  • Methods like `for_loop()`, `block()`, `statement()`, `end()`
  • Auto-manages indentation and brace matching

Pros:

  • Type-safe API
  • IDE autocomplete for methods
  • Automatic indentation management
  • Catches mismatched braces at compile time

Cons:

  • More verbose than templates
  • Learning curve for new contributors
  • Code structure less visible

Comparison Criteria

Criteria Templates Builders
Readability ⭐ Shows final code shape ⭐ Clear API calls
Maintainability Separate files Single class
Type Safety String-based Method-based
Error Detection Runtime Compile-time
Performance File I/O overhead Direct string ops

Patterns to Convert (3-5 representative examples)

  1. For Range Loop (`emit_for.cpp::for_range_stmt`)
  2. Function Definition (`emit_function.cpp::function_def`)
  3. Struct Definition (`emit_struct.cpp::struct_def`)
  4. Method Call (`emit_method_call.cpp`)
  5. If Statement (`emit_if.cpp`)

Branches

  • `feature/codegen-templates` - Template-based prototype
  • `feature/codegen-builders` - Builder pattern prototype

PRs

(Links will be added once PRs are created)

Decision Criteria

After reviewing both prototypes, consider:

  1. Which is easier to read and understand?
  2. Which is easier to extend with new patterns?
  3. Which catches errors earlier?
  4. Which is easier for new contributors?

cc @chrishayen

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions