Book Image

D Cookbook

By : Adam Ruppe
Book Image

D Cookbook

By: Adam Ruppe

Overview of this book

Table of Contents (21 chapters)
D Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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:

  1. 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.

  2. Ensure the parser works at runtime by creating a main function that outputs its result.

  3. 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.

  4. Write the generated...