Build your own DSL
Domain-Specific Languages (DSLs) are specialized programming languages crafted to tackle specific types of problems—think image processing, physical simulations, or financial modeling—without the complexity of general-purpose languages like Python, Terra or C++. By focusing on what matters most in your field, DSLs streamline workflows, boost productivity, and bridge the gap between technical experts and domain specialists.
Terra implements an API that makes it really easy to build your own language constructs with tailored syntax, abstractions, and tools that make coding faster, more intuitive, and less prone to error.
Brainfuck - a minimal language that emulates a Turing machine
With these two operators, you can use Lua to generate arbitrary Terra code at compile-time. This makes the combination of Lua/Terra well suited for writing compilers for high-performance domain-specific languages. For instance, we can implement a compiler for BF, a minimal language that emulates a Turing machine. The Lua function compile
will take a string of BF code, and a maximum tape size N
. It then generates a Terra function that implements the BF code. Here is a skeleton that sets up the BF program:
The function body
is responsible for generating body of the BF program given the code string:
It loops over the code string, and generates the corresponding Terra code for each character of BF (e.g. ">" shifts the tape over by 1 and is implemented by the Terra code ptr = ptr + 1
). We can now compile a BF function:
The result, add3
, is a Terra function that adds3 to an input character and then prints it out:
We can also use goto
statements (goto labelname
) and labels (::labelname::
) to implement BF's looping construct:
We are using these generative programming constructs to implement domain-specific languages and auto-tuners: check out our PLDI paper that describes our implementation of Orion, a language for image processing kernels, and Ebb, which is a DSL for solving mesh-based PDE's in Terra.