Friday, June 22, 2012

Proposal to add metadata to Dart language

Posted by Peter von der Ahé

Disclaimer: This is an early proposal, it is not in the Dart language spec yet. This might change or be retracted. Comments welcome!

UPDATE: Join the discussion about this proposal on the Dart mailing list.

Dart Metadata Level 1

We propose to add metadata in the form of constant expressions prefixed with ‘@’. For example:

class Object {
 @native int hashCode();

In the example above, the metadata is highlighted in blue.

The grammatical rule for metadata is:

metadata: '@' expression ;

The expression must be a constant expression.

The example above assumes these additional declarations:

class Native {
 const Native();

const native = const Native();

Informally, metadata can appear before a class, interface, typedef, constructor, factory, function, field, parameter, or variable declaration. For example:

interface MyInterface {
 @metadata var field;
 @metadata get getter();
 @metadata String method(@metadata parameter, [@metadata optional]);

class MyClass {
 @metadata MyClass(@metadata parameter) {
   @metadata localFunction() => 42;
   @metadata var variable = null;
   for (@metadata var i in [1, 2, 3]) {

Since metadata can be any constant expression, the following is possible:

@const <int>[1, 2, 3]
class MyOtherClass {

Metadata is fully reified and available through mirror-based reflection, in other words, unless reflection is enabled, metadata can be ignored.

Q: Can I access metadata on local variables?
A: It depends: Does the mirror API expose AST nodes? Most likely not, initially.

Q: Can I access metadata on a local function?
A: An object mirror on a closurized local function should be able to return the metadata of the corresponding function declaration. In addition, if the mirror API exposes AST nodes, such AST nodes will include the metadata.

Open question: what about raw strings?

As always, please join the discussion on the Dart mailing list.