On Friday, 26 January 2018 at 11:32:42 UTC, Mike Parker wrote:
On Friday, 26 January 2018 at 11:18:21 UTC, Oleksii Skidan wrote:


I could imagine a mixin-based solution in D:
```d
// Usage:
ASSERT!"a == b";
```
But it seems a bit alien to me. First of all, it kind of stringly-typed one. Secondly, neither IDEs nor advanced text editors are able to figure out that the string contains actual D code, and so neither syntax highlighting nor code assistance work with this approach.

Token strings are intended for this and editors *should* highlight them (don't know if any currently do):

https://dlang.org/spec/lex.html#token_strings

Seems like I have to add some context into this conversation: I'm writing a poor man's testing framework, since it's the best and easiest way to learn D ;-)

I'm trying to achieve something similar to `Catch2``REQUIRE`macro. To be honest, I did not know about toking strings until today, and I don't know D much. Here's what I came up with so far:

```d
string require(string expr)(string file = __FILE__, int line = __LINE__)
{
    import std.array, std.conv;
    return q{
        if (!($expr)) {
            import std.stdio;
            writeln("Test failed @", `$file`, ":", $line, "\n",
" Expected: `", `$expr`, "` to be `true`.\n");
        }
    }.replace("$expr", expr)
     .replace("$file", file)
     .replace("$line", to!string(line));
}

```

That code snippet uses token strings to compose an if statement that basically checks whether the given condition holds. That looks okay-ish to me, the usage of that function is not pretty though:

```d
unittest
{
    mixin(require!q{false}); // This test will fail.
}
```

It would be awesome if I could write something like the this instead:

```d
unittest
{
    require!q{false};
}
```

At first glance it seems like I could have moved the `mixin` statement into the `require` function itself, but that would not really work. Consider the following snippet:

```d
unittest
{
    float value = 3f;
    require!q{value == 3f}; // This line won't compile.
}
```

That code won't even compile, since `value` exists in `unittest` scope, which is not visible to the `require` function.

--
Oleksii

Reply via email to