How to best implement a DSL?

rikki cattermole rikki at cattermole.co.nz
Sat Jul 28 15:43:12 UTC 2018


On 29/07/2018 2:59 AM, Robert M. Münch wrote:
> Hi, I'm seeking for ideas/comments/experiences how to best implement a 
> DSL in D.
> 
> What I would like to do is something like this:
> 
>      ... my D code ...
> 
>      my-dsl {
>          ... my multi-line DSL code ...
>          trade 100 shares(x) when (time < 20:00) and timingisright()
>      }
> 
> 
>      ... my D code ...
> 
> 
> Some things that circle in my head:
> * Can the D parser somehow be missued for a DSL? So I can skip all the 
> generic features for types etc.?

Let's go with no.

> * I could use a PEG grammer for parsing the DSL, but this leads to quite 
> some overhead for a tiny DSL.
> 
> * For static DSL code I would like to use CTFE to convert it into D code
>      * Does this requires a CTFE compatible PEG parser tookit?

Yes.

>      * Could I somehow call an external program during compilation which 
> gets the DSL block as input and returns D code?

No. But you can pre-process.

> * For dynamic DSL code I think I need to create something like an 
> interpreter
>      * How can I reference D variables from DSL code? Is there a lookup 
> meachnisam or do I have to create a dictonary?

Registration, but like you said, a giant dictionary.

>      * Is it possible to populate such a dictonary via CTFE?

Sort of, it can be registered, but the actual execution of the 
registration occurs at runtime.



But you're slightly over thinking this. Write an interpreter and a 
parser. The fact that the parser can work at CTFE is irrelevant and 
almost a footnote on the page of details ;).

If you want to be clever you could generate D code and mix it in based 
upon what was parsed. But you'd still want that dictionary.


More information about the Digitalmars-d-learn mailing list