The X Macro using D

Jacob Carlborg via Digitalmars-d digitalmars-d at puremagic.com
Fri Jul 21 01:12:55 PDT 2017


On 2017-07-21 00:02, Walter Bright wrote:
> On 7/20/2017 2:21 PM, Stefan Koch wrote:
>> Please tell me this is not going to get into dmd :)
>> templates are so much more expensive then macros.
>> (Well, for now :) )
>>
>> Those templates can and should be replaced by CTFE.
> 
> If you like, present the CTFE solution. Should be fun!

Here's my solution. It sill uses templates for the implementation of "map":

auto map(alias func)(const(Row)[] array)
{
     alias R = typeof(func(Row.init));
     R[] result;

     foreach (e ; array)
         result ~= func(e);

     return result;
}

struct Row
{
     string id;
     int reg;
     int mask;
     int ty;
}

immutable Row[2] table = [
     Row("AH", 4, mAX, TYuchar),
     Row("AL", 0, mAX, TYuchar)
];

alias regm_t = int;
alias tym_t = int;

enum mAX = 1;
enum TYuchar = 1;
enum mTYvolatile = 2;

private __gshared const(char)*[table.length] pseudotab = table.map!(row 
=> row.id);
__gshared ubyte[table.length] pseudoreg = table.map!(row => row.reg);
__gshared int[table.length] pseudomask = table.map!(row => row.mask);
private __gshared const(tym_t)[table.length] pseudoty = table.map!(row 
=> mTYvolatile | row.ty);

I added some type aliases and enums to be able to run the code self 
contained without DMD. Some advantages:

* Less use of templates
* More readable since there's a specific type (Row) with named fields, 
no need to write the fields in comments
* Easier to update when the length of the arrays are not hard coded

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list