Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable dumpper template function doesn't respect scope

Tags:

d

I have a handy dump function (copied from internet, most likely from https://forum.dlang.org/) that I'm using to investigate variables.

I just noticed it doesn't respect scopes in all cases (see below). Why and how I can fix it to get the expected results ? Or is the function fundamentally flawed ? dump has been very valuable when I have been learning D.

I'm using DMD64 D Compiler v2.083.0 on Linux.

Expected results when compiled with -debug:

(immutable(int) x = 1)
(immutable(immutable(char)[]) x = A)
(immutable(double) x = 1.1)

but instead got:

(immutable(int) x = 1)
(immutable(int) x = 1)
(immutable(double) x = 1.1)

The code:

void dump(alias variable)()
{
  import std.stdio : writefln;
  writefln("(%s %s = %s)",
           typeid(typeof(variable)),
           variable.stringof,
           variable);
}

void main()
{
  {
    immutable x = 1; debug dump!x;
  }

  {
    immutable x = "A"; debug dump!x;
  }

  {
    void f() { immutable x = 1.1; debug dump!x; }
    f();
  }
}
like image 272
user272735 Avatar asked Apr 02 '26 01:04

user272735


1 Answers

Looks like you ran into this compiler bug:

https://issues.dlang.org/show_bug.cgi?id=13617

function-local symbols do not have unique names and conflict with symbols in sibling scopes

A minimal example derived from the bug report to illustrate the issue:

bool isInt(alias x)() { return is(typeof(x) == int); }

void main() {
  { int   a; static assert(isInt!a); }
  { float a; static assert(isInt!a); } // passes unexpectly (compiler bug)
}

The code above incorrectly compiles even the second static assert should fail compile time.

like image 187
Vladimir Panteleev Avatar answered Apr 09 '26 14:04

Vladimir Panteleev