☼
⌃
☰

Metaprogramming

Table of Contents

Metaprogramming

Metaprogramming is a Programming technique where computer programs treat other programs (or themselves) as their data. This allows a program to read, generate, analyze, or transform source code, effectively enabling "code that writes code."

The core principle behind this is the ability to access and manipulate a program's structure, often represented as a data structure like an Abstract Syntax Tree (AST). By operating on this representation, a metaprogram can build new code, modify existing logic, or perform complex analysis before the program is compiled or executed.

This is commonly achieved in two ways:

  • Compile-time Metaprogramming: Using macros to generate or transform code during compilation. This is powerful for reducing boilerplate and creating expressive Domain-Specific Languages (DSLs).
  • Runtime Metaprogramming: Using techniques like reflection to inspect and modify a program's structure while it is running, allowing for highly dynamic behavior.