Skip to main content

Static variable initialization opened up to any expression

Posted by Gilad Bracha


(Follow along with the original thread titled Lazy initialization of statics from the mailing list.)


In Dart static variables may only be initialized with compile-time constants (hereafter referred to as just constants in the interest of brevity).  Static variables include all top-level variables as well as static variables of classes. The motivation is our desire to avoid costly initialization (and attendant slowness) at program startup. However, the requirement to use constants is quite restrictive.

We plan on relaxing the restrictions on initialization of statics while still avoiding high latency at startup by making the initialization lazy. We can evaluate the initializer at first use rather than at library or class load time.

We are aware that the interaction of laziness and imperative programming is problematic, because results are timing dependent. Currently this is a non-issue because the initializers evaluate constants, which are timing-independent.

Nevertheless, lifting the restriction that statics be initialized is a clear win, and has have no semantic effect on currently legal programs. Code that relies on side-effects in initialization could behave in surprising ways, but order dependent initialization is a bad idea and should be avoided in any case.

Below are the relevant spec changes. For speakers of English, the executive summary is:


You will be able to use any expression (not just constant expressions) to initialize a static variable (including top level variables). The initialization will be carried out upon the first invocation of the getter of that variable (aka first read). If the initialization throws an exception, the variable will be set to null, and the exception will be propagated.



Specification Changes


As usual, changes highlighted in yellow.

Variables

Variables are storage locations in memory.  

variableDeclaration:
     declaredIdentifier (',' identifier)*
   ;
initializedVariableDeclaration:
     declaredIdentifier ('=' expression)? (',' initializedIdentifier)*
   ;
initializedIdentifierList:
     initializedIdentifier (',' initializedIdentifier)*
   ;
initializedIdentifier:
     identifier ('=' expression)?
   ;


declaredIdentifier:
     finalVarOrType identifier
   ;



finalVarOrType:
     final type?
   |
var    | type
   ;




A variable that has not been initialized has the initial value null.
A final variable is a variable whose declaration includes the modifier final. A final variable can only be assigned once, when it is initialized, or a compile-time error occurs.

A static variable is a variable that is not associated with a particular instance, but rather with an entire library or class.  

Static variable declarations are initialized lazily. The first time a static variable v is read, it is set to the result of evaluating its initializer. The precise rules are given in sections 7.7 and 10.28.

The lazy semantics are given because we do not want a language where one tends to define expensive initialization computations, causing long application startup times. This is especially crucial for Dart, which is designed for coding client applications.


If a variable declaration does not explicitly specify a type, the type of the declared variable(s) is Dynamic, the unknown type.

A top-level variable is implicitly static. It is a compile-time error to preface a top level variable declaration with the built-in identifier static.  It is a compile-time error if a top level variable is initialized with an expression that is not a compile-time constant.


Static Variables


Static variables are variables whose declarations are immediately contained within a class declaration and that are declared static. The static variables of a class C are those static variables declared by C.

A static variable declaration of one of the forms static T v;, static T v = e; or static final T v = e; always induces an implicit static getter function with signature

static T get v()

whose invocation evaluates as described below.

A static variable declaration of one of the forms static var  v;, static var  v = e; or static final v = e; always induces an implicit static getter function with signature

static get v()

whose invocation evaluates as described below.

A non-final static variable declaration of the form static T v; or the form static T v = e; always induces an implicit static setter function with signature

static void set v(T x)

whose execution sets the value of v to the incoming argument x.

A non-final static variable declaration of the form static var v; or the form static var v = e; always induces an implicit static setter function with signature

static set v(x)

whose execution sets the value of v to the incoming argument x.

Evaluation of static variable getters



Let d be the declaration of a static variable v. The implicit getter method of v executes as follows:
  • If d is of one of the forms static var v = e; , static T v = e; , static final v = e; or static final T v = e; and no value has yet been stored into v then the initializer expression e 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 result of executing the getter is r. Otherwise
  • The result of executing the getter method is the value stored in v.  



Identifier Reference


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

identifier:
      IDENTIFIER
  | BUILT_IN_IDENTIFIER
  ;


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

BUILT_IN_IDENTIFIER:      abstract
   | assert
   | call
   | Dynamic
   | factory
   | get
   | implements
   | import
   | interface
   | library
   | negate
   | operator
   | set
   | source
   | 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 declaration, be it a variable, function, type or label, with the exception of user defined operators named negate or call.

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. However, 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. It is a compile-time error if d is a class, interface, type alias or type variable. 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 library variable then:
    • If d is of one of the forms var v = ei; , T var v = ei; , final v = ei; or final 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. 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

AngularDart 4

AngularDart v4 is now available. We've been busy since the release angular2 v3.1.0 in May. Not only did we "drop the 2", but we also improved the compiler and tightened up the framework to give you smaller code, we updated the package structure to improve usability, and we added several new features. Check out the updated documentation to get started.
Just angular Upgrading to v4 will require more than updating your version constraint. The package has changed names (back) to angular – dropping the 2. You'll need to update your pubspec.yaml and the corresponding imports in your code. In most instances, find-and-replace should do the trick. Going forward, the package will be called package:angular. We'll just update the version number.
Smaller code The updated compiler in 4.0 allows type-based optimizations that not only improve runtime performance but generate better code because we are able to strongly type templates. A big result of the update is that many ap…

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…

Const, Static, Final, Oh my!

Posted by Seth Ladd

(This is an "oldie but a goodie" misc@dartlang.org post originally written by Bob Nystrom. It is being posted here as the explanations still ring true.)

Bob writes:


"static", "final", and "const" mean entirely distinct things in Dart:

"static" means a member is available on the class itself instead of on instances of the class. That's all it means, and it isn't used for anything else. static modifies *members*.

"final" means single-assignment: a final variable or field *must* have an initializer. Once assigned a value, a final variable's value cannot be changed. final modifies *variables*.

"const" has a meaning that's a bit more complex and subtle in Dart. const modifies *values*. You can use it when creating collections, like const [1, 2, 3], and when constructing objects (instead of new) like const Point(2, 3). Here, const means that the object's entire deep state can be determ…