How to best implement a DSL?

Mr.Bingo Bingo at Namo.com
Sun Jul 29 22:19:59 UTC 2018


On Saturday, 28 July 2018 at 14:59:31 UTC, 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.?
>
> * 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?
> 	* Could I somehow call an external program during compilation 
> which gets the DSL block as input and returns D code?
>
> * 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?
> 	* Is it possible to populate such a dictonary via CTFE?

Why not simply turn your dsl in to D code? If it is pre-existing 
you'll need a simple mapping.

trade 100 shares(x) when (time < 20:00) and timingisright()

could be written any number of ways:

trade(100.shares(x).when("time < 20.0", "&", "timingisright()")

Simply construct your grammar around D types and use UFSC, 
members, and ranges and then either use it directly or map to it.

If the grammar is relatively small but simply lots of variations 
then it should be rather easy(e.g., if you just have trade, 
shares, and when then it would be very easy and the work would in 
implementation.


More information about the Digitalmars-d-learn mailing list