Skip to main content

Proposal for First-class Types in Dart

Posted by Gilad Bracha


First-class Types in Dart

Currently Dart does not provide any access to types as objects at the base level.  We propose to provide a getter on class Object:

@native Type get type;

which returns a reified representation of the class of an object.  Note that the method type can be overridden in subclasses (for example, to implement a remote proxy that hides its implementation).

The declaration of class Type is

class Type {
 @native String toString();
 String descriptor(){...} // return the simple name of the type
}

In other words, Type does not add any API to Object, other than the ability to get its name.  One can use toString() to obtain a description of the type (such as its name), one can test types for equality or identity, one can hash them (assuming we move forward on making all objects hashable) and that is all. The main use of these reified types is to serve as keys to the mirror system. Instances of Type are canonicalized.

An identifier that denotes a type in Dart may now be used in an expression, and denotes the corresponding reified type object. Examples:

new Object().type === Object; // evaluates to true
new Mirrors.reflect(Map);
Type c = List; // List<Dynamic>
Type t = new List<int>().type;
Type s = List<String>; // this requires adjustment to the grammar
class G<T> { foo() {
 Type t = T;
 InterfaceMirror m1 = new Mirrors.reflect(t);
 InterfaceMirror m2 = new Mirrors.reflect(T);
}

The opposite is not the case: one cannot use an expression in contexts where types or classes are specifically required, even if said expression evaluates to a Type object. Hence, the following are illegal:

new List() is c;
// error: assume c is bound to List as above; still, c denotes a variable, not a type


class G<T> {
  T t = new T();
  // error: T is  a type variable bound to some instance of Type, but not class or interface
  static foo() => 42;
  Type gc = G; // G<Dynamic>
  int bar = gc.foo(); // error: gc is bound to G, but denotes a variable not a type
}


No doubt there will be requests to expand the capabilities of class Type to allow the scenarios shown above.  At this time, the expectation is that mirrors  should be used in such cases; that is, use the reified class as a convenient way to obtain a mirror and use the mirror to obtain the desired functionality, as indicated below:

class G<T> {
  T t = new Mirrors.reflect(T).newInstance([],{});
  static foo() => 42;
  Type gc = G;
  int bar = new Mirrors.reflect(gc).invoke(‘foo’, [], {});
}


Spec Changes


The above does require some changes to the spec. While the addition of Object.type could be construed as a library issue, the changed status of type names to valid expressions requires some adjustments.


3. Overview


Dart is a class-based, single-inheritance, pure object-oriented programming language. Dart is optionally typed and supports reified generics and interfaces.  The runtime type of every object is represented as an instance of class Type which can be obtained by calling the getter  type declared in class Object, the root of the Dart class hierarchy.

Dart programs can be statically checked. The static checker will report some violations of the type rules, but such violations do not abort compilation or preclude execution.

Dart programs may be executed in one of two modes: production mode or checked mode. In production mode, static type annotations have absolutely no effect on execution.  In checked mode, assignments are dynamically checked, and certain violations of the type system raise exceptions at run time.


The coexistence between optional typing and reification is based on the following:

  • Reified type information reflects the types of objects at runtime and may always be queried by dynamic typechecking constructs (the analogs of instanceOf, casts, typecase etc. in other languages). Reified type information includes class and interface declarations, the the runtime type (aka class) of of an object, and type arguments to constructors.
  • Static type annotations determine the types of variables and function declarations (including methods and constructors).
  • Production mode respects optional typing. Static type annotations do not affect runtime behavior.
  • Checked mode utilizes static type annotations and dynamic type information aggressively yet selectively to provide early error detection during development.


Dart programs are organized in a modular fashion into units called libraries. Libraries are units of encapsulation and may be mutually recursive.

However they are not first class.  To get multiple copies of a library running simultaneously, one needs to spawn an isolate.  

10.29 Identifier Reference


An identifier expression consists of a single identifier; it provides access to an object via an unqualified name.

identifier:       IDENTIFIER
  ;


IDENTIFIER_NO_DOLLAR:      IDENTIFIER_START_NO_DOLLAR IDENTIFIER_PART_NO_DOLLAR*
   ;
IDENTIFIER:      IDENTIFIER_START IDENTIFIER_PART*
   ;
   ;

BUILT_IN_IDENTIFIER:      abstract
  | as    | assert
  | Dynamic    | factory    | get    | implements
  | interface    | operator    | set    | static    | typedef    ;


IDENTIFIER_START:      IDENTIFIER_START_NO_DOLLAR
   | '$'
   ;
IDENTIFIER_START_NO_DOLLAR:      LETTER
   | '_'
   ;

IDENTIFIER_PART_NO_DOLLAR:      IDENTIFIER_START_NO_DOLLAR
   | DIGIT
   ;



IDENTIFIER_PART:      IDENTIFIER_START
   | DIGIT
   ;
qualified:      identifier ('.' identifier)?
   ;



A built-in identifier is one of the identifiers produced by the production BUILT_IN_IDENTIFIER. It is a compile-time error if a built-in identifier is used as the declared name of a class, interface, type variable or type alias. It is a compile-time error to use a built-in identifier other than   Dynamic as a type annotation. It is a static warning if a built-in identifier is used as the name of a user-defined variable, function or label.

Built-in identifiers are identifiers that are used as keywords in Dart, but are not reserved words in Javascript. To minimize incompatibilities when porting Javascript code to Dart, we do not make these into reserved words. Ergo, a built-in identifier may not be used to name a class or type.  In other words, they are treated as reserved words when used as types. This eliminates many confusing situations without causing compatibility problems.

Evaluation of an identifier expression e of the form id proceeds as follows:
Let d be the innermost declaration in the enclosing lexical scope whose name is id. If no such declaration exists in the lexical scope, let d be the declaration of the inherited member named id if it exists.

  • If d is a class, interface, or type alias T, the value of e is the unique instance of class Type reifying T.
  • If d is a type parameter T, then the value of e is the value of the actual type argument corresponding to T that was  passed to the generative constructor that created the current binding of this.
  • If d is a library variable then:
    • If d is of one of the forms var v = ei; , T var v = ei; , final v = ei; , final T v = ei; , const v = ei; or const T v = ei;  and no value has yet been stored into v then the initializer expression ei is evaluated. If the evaluation succeeded yielding an object o, let r = o, otherwise let r = null. In any case, r is stored into v. The value of e is r.
    • If d is of one of the forms const v = e; or const T v = e; the result of the getter is the value of the compile time constant e. Otherwise
    • e evaluates to the current binding of id.  This case also applies if d is a library function declaration, as these are equivalent to function-valued variable declarations.
  • If d is a local variable or formal parameter then e evaluates to the current binding of id.  This case also applies if d is a local function declaration, as these are equivalent to function-valued variable declarations.

  • If d is a static method, then e evaluates to the function defined by d.
  • If d is the declaration of a static variable or static getter declared in class C, then e is equivalent to the getter invocation C.id.
  • If d is the declaration of a top level getter, then e is equivalent to the getter invocation id.
  • Otherwise e is equivalent to the property extraction  this.id.

Popular posts from this blog

Dart in 2016: The fastest growing programming language at Google, 2nd fastest growing in TIOBE Index

Dart was the fastest growing programming language at Google in 2016 with millions of lines of code written. It also made it to TIOBE Index Top 20 this month (see TIOBE's methodology).

It takes time to build something as ambitious as Dart and, in some ways, Dart is still in its infancy. But we're glad the hard work is starting to pay off.

Many thanks to our amazing community!

We're going to celebrate by ... releasing 1.22 next week (as per our usual 6 week release schedule).

AngularDart is going all Dart

Until now, the multiple language flavors of Angular 2 were written as TypeScript source, and then automatically compiled to both JavaScript and Dart. We're happy to announce that we’re splitting the Angular 2 codebase into two flavors – a Dart version and a TypeScript/JavaScript version – and creating a dedicated AngularDart team.

This is amazing news for Dart developers because:

The framework will feel more like idiomatic Dart.It will make use of Dart features that couldn't work with the TypeScript flavor. It will be faster.
This is equally great news for our TypeScript and JavaScript developers, by the way. Cleaner API, performance gains, easier contributions. Read more on the Angular blog.

Angular 2 for Dart is used by many teams at Google. Most famously by the AdWords team, but many other Google teams build large, mobile-friendly web apps. Some of the top requests from these teams were: make the API feel like Dart, provide a faster edit-refresh cycle, and improve applicat…

The new AdWords UI uses Dart — we asked why

Google just announced a re-designed AdWords experience. In case you’re not familiar with AdWords: businesses use it to advertise on google.com and partner websites. Advertising makes up majority of Google’s revenue, so when Google decides to completely redo the customer-facing front end to it, it’s a big deal. The Dart team is proud to say that this new front end is built with Dart and Angular 2. Whenever you asked us whether Google is ‘even using Dart for anything,’ this is what we had in mind but couldn’t say aloud. Until now. We asked Joshy Joseph, the primary technical lead on the project, some questions. Joshy is focusing on things like infrastructure, application latency and development velocity, so he’s the right person to ask about Dart.Q: What exactly did we launch on Monday?It’s a complete redesign of the AdWords customer experience that is rolling out slowly as a test to a small initial set of advertisers. The most noticeable thing is probably the Material Design look and f…