www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 19127] New: UDAs seem to be raw AST nodes rather than


          Issue ID: 19127
           Summary: UDAs seem to be raw AST nodes rather than expressions
           Product: D
           Version: D2
          Hardware: x86_64
                OS: Linux
            Status: NEW
          Severity: major
          Priority: P1
         Component: dmd
          Assignee: nobody puremagic.com
          Reporter: dhasenan gmail.com

I've identified two issues related to this problem.

https://dlang.org/spec/attribute.html#uda says:

"User-Defined Attributes (UDA) are compile-time expressions that can be
attached to a declaration."

This should be invalid:

  struct jsonize { string name; }
   jsonize int i;

`jsonize` is a type, but it is used as an expression. We see how this
misbehaves when we inspect it:

  foreach (uda; __traits(getAttributes, i)) writeln(uda);
  // Error: cannot pass type jsonize as a function argument

This is an issue whenever we try to inspect the content of a UDA that does not
have required parameters.

While looking for a workaround, I thought to create a function that returned
the UDA value, thinking this function would be executed at compile-time and the
result returned as a UDA value. This was not the case:

  size_t print(string s = "hello world")
    return s.length;
   print int i;
  void main()
    static foreach (uda; __traits(getAttributes, j))

It compiles and prints:

  hello world

That shouldn't happen. The spec says the expression should be a compile-time

We see more clearly what's happening with pragma(msg):

  struct _UDA2 {}
  _UDA2 UDA2(string s) { writeln("hello world"); return _UDA2(); }
   UDA2("hi") int ir;
  pragma(msg, __traits(getAttributes, ir).stringof);

This prints out: tuple(UDA2("hi")) -- it's a tuple containing a function call.
I suspect that this will produce strange breakages in rare cases when using
attributes at compile time (in addition to the current situation where invalid
code is accepted).

Jul 29 2018