__traits(compiles, ...) returns true for syntactic garbage and for semantically incorrect code

monarch_dodra monarchdodra at gmail.com
Mon Dec 17 03:01:59 PST 2012


On Monday, 17 December 2012 at 10:42:38 UTC, Pavel wrote:
> Either I do not understand the work of this feature or it is an 
> obvious bug:
>
> import std.stdio;
> import std.conv;
>
> void main()
> {
>    enum string expr = "DMD compiles this garbage ... iiiii - \" 
> #### $$$";
> 	
>    enum bool bTest = __traits(compiles, expr);
>    enum bool bTest2 = __traits(compiles, "int i = q{};");
> 		
>    writeln("bTest: " ~ to!string(bTest));
>    writeln("bTest2: " ~ to!string(bTest2));
> }
>
> Produces (tested with dmd32 2.060 and dmd32 2.059):
>   bTest: true
>   bTest2: true
>
> (http://dpaste.dzfl.pl/5d338ab3)
>
> Could you please somebody explain this?
>
> Thanks,
> Pavel

__traits(compiles, xxx) just verifies that xxx does not resolve 
to error. In your case, it resolves to... string!

Perhaps you wanted to mixin the string?

//----
import std.stdio;
import std.conv;

void main()
{
    enum string expr = "DMD compiles this garbage ... iiiii - \" 
#### $$$";
	
    enum bool bTest = __traits(compiles, mixin(expr));
    enum bool bTest2 = __traits(compiles, mixin("int i = q{};"));
    enum bool bTest3 = __traits(compiles, mixin("(int i) => 2*i"));
		
    writeln("bTest: " ~ to!string(bTest));
    writeln("bTest2: " ~ to!string(bTest2));
    writeln("bTest3: " ~ to!string(bTest3));
}
//----


More information about the Digitalmars-d mailing list