Generating data structures from text diagrams
Data structures are often defined with text diagrams. Like domain-specific languages, D can parse these strings and generate data structure definitions at compile time. We'll briefly demonstrate the technique by writing a parser for a simple diagram.
How to do it…
Let's execute the following steps to generate data structures from text diagrams:
Start by writing a regular program to parse the diagram into structured fields. For our diagram, we'll want to split it into lines and then split the data lines into individual fields. The name will be the text within and the length will be one byte per four characters.
Take the structured data and generate the D code from it with string concatenation. Here, we'll build an anonymous structure with each field from the diagram, using simple integral types to match the size. Write out your code with
pragma(msg)
or at runtime while debugging until the code looks right.Use the
mixin
expression to compile your code...