Skip to content

Instantly share code, notes, and snippets.

@youxkei
Created February 17, 2016 08:39
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 youxkei/2c2775ebfdbb90d60078 to your computer and use it in GitHub Desktop.
Save youxkei/2c2775ebfdbb90d60078 to your computer and use it in GitHub Desktop.
import std.meta : AliasSeq;
mixin template assertThat(string lhs, alias matcher, string file = __FILE__, ulong line = __LINE__)
{
int UNUSED_VARIABLE = ()
{
import core.exception : AssertError;
import std.string : join;
string[] errors;
mixin matcher.match!(lhs, matcher.args);
throw new AssertError(errors.join("\n"), file, line);
return 0;
}();
}
template eq(alias rhs)
{
alias args = rhs;
mixin template match(string lhs, alias rhs)
{
int UNUSED_VARIABLE = ()
{
if (mixin(lhs) != rhs)
{
import std.conv : text;
import core.exception : AssertError;
errors ~= text(lhs, ": ", mixin(lhs), " != ", rhs);
}
return 0;
}();
}
}
template array(matchers...)
{
alias args = matchers;
mixin template match(string lhs, matchers...)
{
int UNUSED_VARIABLE = ()
{
mixin eq!"unused".match!(lhs ~ ".length", matchers.length);
foreach (i, matcher; matchers)
{
import std.conv : to;
if (i < mixin(lhs ~ ".length"))
mixin matcher.match!(lhs ~ "[" ~ i.to!string ~ "]", matcher.args);
}
return 0;
}();
}
}
template field(string fieldName, alias matcher)
{
import std.meta : AliasSeq;
alias args = AliasSeq!(fieldName, matcher);
mixin template match(string lhs, string fieldName, alias matcher)
{
int UNUSED_VARIABLE = ()
{
mixin matcher.match!(lhs ~ "." ~ fieldName, matcher.args);
return 0;
}();
}
}
template all(matchers...)
{
alias args = matchers;
mixin template match(string lhs, matchers...)
{
int UNUSED_VARIABLE = ()
{
foreach (matcher; matchers)
{
import std.conv : to;
mixin matcher.match!(lhs, matcher.args);
}
return 0;
}();
}
}
void main()
{
struct S { int foo, bar; }
S[] ary = [S(1, 2), S(3, 4)];
mixin assertThat!(q{ary}, array!(
all!(
field!("foo", eq!1),
field!("bar", eq!2),
),
all!(
field!("foo", eq!3),
field!("bar", eq!5),
),
));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment