Skip to content

Instantly share code, notes, and snippets.

@packysauce
Last active January 14, 2016 21:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save packysauce/9540572873469566f33e to your computer and use it in GitHub Desktop.
Save packysauce/9540572873469566f33e to your computer and use it in GitHub Desktop.
mkregisters.d
module core.mkregisters;
template decimalDigit(int n) // [3]
{
const string decimalDigit = "0123456789"[n..n+1];
}
template itoa(long n)
{
static if (n < 0)
{
const string itoa = "-" ~ itoa!(-n);
}
else static if (n < 10)
{
const string itoa = decimalDigit!(n);
}
else
{
const string itoa = itoa!(n/10L) ~ decimalDigit!(n%10L);
}
}
template mkregisters(T...)
{
const string mkregisters = _mkregisters!(0, 0, T);
}
template _mkarray(uint N)
{
static if (N == 1)
{
const _mkarray = "";
}
else
{
const _mkarray = "[" ~ itoa!(N) ~ "]";
}
}
// mkregisters!(0, 0, uint, "revision", 0x00,
// 4, 0, uint[4], "irqstatus", 0x08...);
template _mkregisters(int Off, int N, T...)
{
static if ((T.length % 3) == 0 && T.length != 0)
{
alias T[0] Type;
const Offset = T[2];
const diff = cast(int)(Offset - Off); // 8 - 4 = 4
const off = cast(int)(diff / uint.sizeof); // 4/4 = 1
static if (off > 0 && diff >= 0)
{
static if (T.length >= 3)
{
const _mkregisters = "uint _reserved" ~
itoa!(N) ~ _mkarray!(off) ~ ";\n" ~
_mkregisters!(Offset, N+1, T[0 .. 3]) ~
_mkregisters!(Offset + Type.sizeof, N+1, T[3..$]);
}
else
{
const _mkregisters = "uint _reserved" ~
itoa!(N) ~ _mkarray!(off) ~ ";\n";
}
}
else
{
static if (T.length >= 3)
{
const _mkregisters = Type.stringof ~ " " ~ T[1] ~";\n" ~
_mkregisters!(Offset + Type.sizeof, N, T[3 .. $]);
}
else
{
const _mkregisters = Type.stringof ~ " " ~ T[1] ~";\n";
}
}
}
else
{
const string _mkregisters = "";
}
}
version (unittest)
{
static struct Device
{
mixin(mkregisters!(
uint, "a", 0x10,
uint, "b", 0x14,
uint, "c", 0x24,
));
}
/*
assert(Device.a.offsetof == 0x10);
assert(Device.b.offsetof == 0x14);
assert(Device.c.offsetof == 0x24);
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment