Parsing a domain-specific language
D can embed domain-specific languages as strings. By writing a compiler for your specialized language to D in D, you can convert code in any language to a D code string, which can then be mixed in and compiled to the optimized machine code by the D compiler.
To demonstrate the technique, we'll write a small stack-based arithmetic program here.
How to do it…
Let's execute the following steps to parse a domain-specific language:
Write a regular parser for the language, making it work when compiled normally at runtime. For the stack language, this is very simple: we just need to split the string. For a more complex language, we will need to build abstract syntax trees out of classes.
Ensure the parser works at runtime by creating a
main
function that outputs its result.Write methods that return strings of the D code from your language's data structures. The stack language will output calls to D functions for
push
,pop
, and calling an operation.Write the generated...