GPCE Demonstration 23

Implementation of DSLs using staged interpreters in MetaOCaml

Kedar Swadi, Rice University

Summary

Domain-specific languages (DSLs) allow programmers to write
applications faster than in general-purpose languages.
Two approaches are commonly taken to implement DSLs. The first
is to compile the DSLs into machine-level code, or low-level
languages such as C. While this results in fast implementations,
writing compilers requires expertise in compiler technology,
and long implementation times. An alternative approach
uses interpreters to implement DSLs. Though easier to write,
extend and maintain than compilers, the overhead of
interpretation is unacceptably large for many applications.
Relevance to GPCE and uniqueness of approach:
The shortcomings in either approaches significantly
impede the widespread use of DSL-based generative
programming in software development. The demonstration addresses
this problem using multistage programming. It shows how
staged interpreters for implementing DSLs avoid problems in both
abovementioned approaches, and allow efficient machine-level
realizations of DSL programs. Unlike other existing approaches,
this approach guarantees that the generated code is typesafe.
Underlying implementation techniques and technologies used:
This demonstration uses multistage programming in the MetaOCaml
language to write two-stage interpreters which translate DSL
programs into OCaml programs, which are finally compiled into
efficient machine code and executed.

First a quick introduction to multistage programming is
given using a simple example of the power function that
computes x^n. The demonstration shows how three staging
constructs in MetaOCaml are used to automatically generate
typesafe specialised versions of this function from the
generic function.

Second, the demonstration shows how to implement
a staged interpreter for a small language and how
to correctly measure performance of implementations.
Finally, the demonstration visually shows performance gains
from a staged interpreter for the LOGO graphics language. This
is done by concurrently running the graphical outputs for the
simple and staged interpreters on two windows placed side-by-side.

Research papers and information about downloading, installing, and using
MetaOCaml are found at http://www.metaocaml.org.