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).

A stronger Dart for everyone

We are constantly asking ourselves:
How do we make developers even more productive when writing Dart apps? We believe that a critical part of the answer to this question is to make strongmode – a sound static type system for Dart – the standard for all Dart developers.

Teams that use Dart to build apps like Soundtrap, AdWords, AdSense, and Greentea say they really enjoy using strong mode features, such as early error detection. In fact, teams that have switched completely to strong mode cite not only early error detection but also better code readability and maintainability as major benefits. We hear this both from small teams and – even more so – from large teams with hundreds of developers writing and maintaining millions of lines of Dart code. As Björn Sperber from Soundtrap says,
Strong mode and the smooth integration with IntelliJ is a joy to use and a huge improvement. If you’ve tried out Flutter, you’ve already used strong mode checks from the Dart analyzer.

Given the benefits …

AngularDart 3.0: Easy upgrade, better performance

AngularDart 3.0 is now available. It brings better performance and smaller generated code, while also making you more productive.


Version 3.0 is an evolution: although it has some breaking changes (detailed below), it is a smooth upgrade due to minimal public API adjustments. Most of the progress is under the hood—in code quality, stability, generated code size, performance, and developer experience.

Code quality:
2731 instances of making the framework code more type safe (using sound Dart).The AngularDart framework code size is down by 12%.Many additional style updates to the codebase:Changed to use idiomatic <T> for generic methods.Removed NgZoneImpl, all the code exists in NgZone now.Stability:
Many CSS encapsulation fixes due to update with csslib package.Fixed bugs with IE11.

Performance:
For the Mail sample app, we see 30% faster time-to-interactive (currently 3812 ms on a simulated 3G connection, measured via Lighthouse).Our large app benchmark shows 2x faster render times of…