The X Macro

KlausO oberhofer at users.sf.net
Mon Jun 28 07:33:25 PDT 2010


I did something similar some time ago:


import std.stdio;

struct EnumDescription
{
   char[] name;
   char[] description;
};

//
// generates an enum, an associated string table and a "save" lookup
// function which determines the string which belongs to an given enum
//
char[] generate_enum(char[] enumname, EnumDescription[] list)
{
   // create enum declaration
   char result[] = "enum " ~ enumname ~ "{";
   foreach(entry; list)
   {
     result ~= entry.name ~ ",";
   }
   result ~= "};";

   // create description array
   result ~= `private static char[][` ~ enumname ~ `.max + 1] s_` ~ 
enumname ~ `ToString =
[`;
   foreach(entry; list)
   {
     result ~= enumname ~ "." ~ entry.name ~ ` : "` ~ entry.description 
~ `",`;
   }
   result ~= "];";

   // create save "toString" function
   result ~= `static char[] ` ~ enumname ~ `ToString(` ~ enumname ~ ` type)
{
   if (type <= ` ~ enumname ~ `.max)
   {
     return s_` ~ enumname ~ `ToString[type];
   }
   return "<invalid enum, no description available>";
}`;

   return result;
}

const EnumDescription[] ErrorList =
[
   { "INTERNAL_ERROR"       , "internal error" },
   { "ALLOCATION_ERROR"     , "allocation error" },
   { "INTEGER_EXPECTED"     , "integer expected" },
];

mixin(generate_enum("ErrorType", ErrorList));


void main()
{
   writefln(ErrorType.ALLOCATION_ERROR, " : ", 
ErrorTypeToString(ErrorType.ALLOCATION_ERROR));
}


Greets

KlausO



Walter Bright schrieb:
> http://www.drdobbs.com/blog/archives/2010/06/the_x_macro.html
> 
> Even though D doesn't have a text macro preprocessor, this can be done 
> using string mixins and a bit of CTFE.


More information about the Digitalmars-d mailing list