Remove stale docs
Change-Id: I8d8c6a777eea03d92f3a5790eb38128fefe9886c Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/229150 Reviewed-by: Sigmund Cherem <sigmund@google.com> Commit-Queue: Michael Thomsen <mit@google.com>
This commit is contained in:
committed by
Commit Bot
parent
16289b490d
commit
e2acafdf80
@@ -1,191 +0,0 @@
|
||||
# Using Generic Methods
|
||||
|
||||
**Note: This document is out of date. Please see [Sound Dart](https://dart.dev/guides/language/sound-dart) for up-to-date
|
||||
documentation on Dart's type system. The work below was a precursor towards Dart's current type system.
|
||||
|
||||
For historical reasons, this feature is called "generic methods", but it
|
||||
applies equally well to instance methods, static methods, top-level functions,
|
||||
local functions, and even lambda expressions.**
|
||||
|
||||
Initially a [proposal][], generic methods are on their way to being fully
|
||||
supported in Dart. Here is how to use them.
|
||||
|
||||
[proposal]: https://github.com/leafpetersen/dep-generic-methods/blob/master/proposal.md
|
||||
|
||||
When they were still being prototyped, an [older comment-based syntax was
|
||||
designed][old] so that the static analysis could be implemented and tested
|
||||
before the VM and compilers needed to worry about the syntax. Now that real
|
||||
syntax is allowed everywhere, this doc has been updated.
|
||||
|
||||
[old]: GENERIC_METHOD_COMMENTS.md
|
||||
|
||||
## Declaring generic methods
|
||||
|
||||
Type parameters for generic methods are listed after the method or function
|
||||
name, inside angle brackets:
|
||||
|
||||
```dart
|
||||
/// Takes two type parameters, [K] and [V].
|
||||
Map<K, V> singletonMap<K, V>(K key, V value) {
|
||||
return <K, V>{ key, value };
|
||||
}
|
||||
```
|
||||
|
||||
As with classes, you can put bounds on type parameters:
|
||||
|
||||
```dart
|
||||
/// Takes a list of two numbers of some num-derived type [T].
|
||||
T sumPair<T extends num>(List<T> items) {
|
||||
return items[0] + items[1];
|
||||
}
|
||||
```
|
||||
|
||||
Class methods (instance and static) can be declared to take generic parameters
|
||||
in the same way:
|
||||
|
||||
```dart
|
||||
class C {
|
||||
static int f<S, T>(int x) => 3;
|
||||
int m<S, T>(int x) => 3;
|
||||
}
|
||||
```
|
||||
|
||||
This even works for function-typed parameters, local functions, and function
|
||||
expressions:
|
||||
|
||||
```dart
|
||||
/// Takes a generic method as a parameter [callback].
|
||||
void functionTypedParameter(T callback<T>(T thing)) {}
|
||||
|
||||
// Declares a local generic function `itself`.
|
||||
void localFunction() {
|
||||
T itself<T>(T thing) => thing;
|
||||
}
|
||||
|
||||
// Binds a generic function expression to a local variable.
|
||||
void functionExpression() {
|
||||
var lambda = <T>(T thing) => thing;
|
||||
}
|
||||
```
|
||||
|
||||
We do not currently support a way to declare a function as *returning* a generic
|
||||
function. This will eventually be supported using a `typedef`.
|
||||
|
||||
## Using generic method type parameters
|
||||
|
||||
You've seen some examples already, but you can use a generic type parameter
|
||||
almost anywhere you would expect in a generic method.
|
||||
|
||||
* Inside the method's parameter list:
|
||||
|
||||
```dart
|
||||
takeThing<T>(T thing) { ... }
|
||||
// ^-- Here.
|
||||
```
|
||||
|
||||
* Inside type annotations in the body of the method:
|
||||
|
||||
```dart
|
||||
useThing<T>() {
|
||||
T thing = getThing();
|
||||
//^-- Here.
|
||||
List<T> pair = [thing, thing];
|
||||
// ^-- And here.
|
||||
}
|
||||
```
|
||||
|
||||
* In the return type of the method:
|
||||
|
||||
```dart
|
||||
T itself<T>(T thing) => thing;
|
||||
//^-- Here.
|
||||
```
|
||||
|
||||
* As type arguments in generic classes and method calls:
|
||||
|
||||
```dart
|
||||
useThing<T>(T thing) {
|
||||
var pair = <T>[thing, thing];
|
||||
// ^-- Here.
|
||||
var set = new Set<T>()..add(thing);
|
||||
// ^-- And here.
|
||||
}
|
||||
```
|
||||
|
||||
Note that generic methods are not yet supported *at runtime* on the VM and
|
||||
dart2js. On those platforms, uses of generic method type arguments are
|
||||
treated like `dynamic` today. So in this example, `pair`'s reified type at
|
||||
runtime will be `List<dynamic>` and `set` will be `Set<dynamic>`.
|
||||
|
||||
There are two places you *cannot* use a generic method type parameter. Both are
|
||||
because the VM and dart2js don't support reifying generic method type arguments
|
||||
yet. Since these expressions wouldn't do what you want, we've temporarily
|
||||
defined them to be an error:
|
||||
|
||||
* As the right-hand side of an `is` or `is!` expression.
|
||||
|
||||
```dart
|
||||
testType<T>(object) {
|
||||
print(object is T);
|
||||
// ^-- Error!
|
||||
print(object is! T);
|
||||
// ^-- Error!
|
||||
}
|
||||
```
|
||||
|
||||
* As a type literal:
|
||||
|
||||
```dart
|
||||
printType<T>() {
|
||||
Type t = T;
|
||||
// ^-- Error!
|
||||
print(t);
|
||||
}
|
||||
```
|
||||
|
||||
Once we have full runtime support for generic methods, these will be allowed.
|
||||
|
||||
## Calling generic methods
|
||||
|
||||
Most of the time, when you call a generic method, you can leave off the type
|
||||
arguments and strong mode's type inference will fill them in for you
|
||||
automatically. For example:
|
||||
|
||||
```dart
|
||||
var fruits = ["apple", "banana", "cherry"];
|
||||
var lengths = fruits.map((fruit) => fruit.length);
|
||||
```
|
||||
|
||||
The `map()` method on Iterable is now generic and takes a type parameter for the
|
||||
element type of the returned sequence:
|
||||
|
||||
```dart
|
||||
class Iterable<T> {
|
||||
Iterable<S> map<S>(S transform(T element)) { ... }
|
||||
|
||||
// Other stuff...
|
||||
}
|
||||
```
|
||||
|
||||
In this example, the type checker:
|
||||
|
||||
1. Infers `List<String>` for the type of `fruits` based on the elements in the
|
||||
list literal.
|
||||
2. That lets it infer `String` for the type of the lambda parameter `fruit`
|
||||
passed to `map()`.
|
||||
3. Then, from the result of calling `.length`, it infers the return type of the
|
||||
lambda to be `int`.
|
||||
4. That in turn is used to fill in the type argument to the call to `map()` as
|
||||
`int`, and the resulting sequence is an `Iterable<int>`.
|
||||
|
||||
If inference *isn't* able to fill in a type argument for you, it uses `dynamic`
|
||||
instead. If that isn't what you want, or it infers a type you don't want, you
|
||||
can always pass them explicitly:
|
||||
|
||||
```dart
|
||||
// Explicitly give a type so that we don't infer "int".
|
||||
var lengths = fruits.map<num>((fruit) => fruit.length).toList();
|
||||
|
||||
// So that we can later add doubles to the result.
|
||||
lengths.add(1.2);
|
||||
```
|
||||
@@ -1,237 +0,0 @@
|
||||
# Prototype Syntax for Generic Methods
|
||||
|
||||
**Note:** This documents the deprecated comment-based syntax for generic
|
||||
methods. New code should use the [much better real syntax][real]. This document
|
||||
is preserved in case you run into existing code still using the old syntax.
|
||||
|
||||
[real]: GENERIC_METHODS.md
|
||||
|
||||
---
|
||||
|
||||
Generic methods are a [proposed addition to the Dart language](https://github.com/leafpetersen/dep-generic-methods/blob/master/proposal.md).
|
||||
|
||||
This is a summary of the current (as of January 2016) comment-based generic
|
||||
method syntax supported by the analyzer strong mode and the Dart Dev Compiler.
|
||||
The comment-based syntax essentially uses the proposed actual generic method
|
||||
syntax, but wraps it in comments. This allows developers to experiment with
|
||||
generic methods while still ensuring that their code runs on all platforms while
|
||||
generic methods are still being evaluated for inclusion into the language.
|
||||
|
||||
## Declaring generic method parameters
|
||||
|
||||
Generic method parameters are listed using a block comment after the method or
|
||||
function name, inside of angle brackets.
|
||||
|
||||
```dart
|
||||
// This declares a function which takes two unused generic method parameters
|
||||
int f/*<S, T>*/(int x) => 3;
|
||||
```
|
||||
|
||||
As with classes, you can put bounds on type parameters.
|
||||
|
||||
```dart
|
||||
// This declares a function which takes two unused generic method parameters
|
||||
// The first parameter (S) must extend num
|
||||
// The second parameter (T) must extend List<S>
|
||||
int f/*<S extends num, T extends List<S>>*/(int x) => 3;
|
||||
```
|
||||
|
||||
Class methods (instance and static) can be declared to take generic parameters
|
||||
in the same way.
|
||||
|
||||
```dart
|
||||
class C {
|
||||
static int f/*<S, T>*/(int x) => 3;
|
||||
int m/*<S, T>*/(int x) => 3;
|
||||
}
|
||||
```
|
||||
|
||||
Function typed parameters, local functions, and function expressions can also be
|
||||
declared to take generic parameters.
|
||||
|
||||
```dart
|
||||
// foo takes a generic method as a parameter
|
||||
void foo(int f/*<S>*/(int x)) {}
|
||||
|
||||
// foo declares a local generic function
|
||||
void foo() {
|
||||
int f/*<S>*/(int x) => 3;
|
||||
return;
|
||||
}
|
||||
|
||||
// foo binds a generic function expression to a local variable.
|
||||
void foo() {
|
||||
var x = /*<S>*/(int x) => x;
|
||||
}
|
||||
```
|
||||
|
||||
We do not currently support a way to declare a function as returning a generic
|
||||
function. This will eventually be supported using something analogous to Dart
|
||||
typedefs.
|
||||
|
||||
## Using generic method parameters
|
||||
|
||||
The previous examples declared generic method parameters, but did not use them.
|
||||
You can use a generic method parameter `T` anywhere that a type is expected in
|
||||
Dart by writing a type followed by `/*=T*/`. So for example, `dynamic /*=T*/`
|
||||
will be interpreted as `dynamic` by all non-strong mode tools, but will be
|
||||
interpreted as `T` by strong mode. In places where it is valid to leave off a
|
||||
type, simply writing `/*=T*/` will be interpreted as `dynamic` by non-strong
|
||||
mode tools, but will be interpreted as `T` by strong mode. For example:
|
||||
|
||||
```dart
|
||||
// foo is a generic method which takes a single generic method parameter S.
|
||||
// In strong mode, the parameter x will have type S, and the return type will
|
||||
// be S
|
||||
// In normal mode, the parameter x will have type dynamic, and the return
|
||||
// type will be dynamic.
|
||||
dynamic/*=S*/ foo/*<S>*/(dynamic/*=S*/ x) { return x; }
|
||||
```
|
||||
|
||||
This can be written more concisely by leaving off the `dynamic`.
|
||||
|
||||
```dart
|
||||
/*=S*/ foo/*<S>*/(/*=S*/ x) {return x;}
|
||||
```
|
||||
|
||||
You can also put a type to the left of the `/*=T/`. This type will be used
|
||||
for all non-strong mode tools. For example:
|
||||
|
||||
```dart
|
||||
// This method works with `int`, `double`, or `num`. The return type will
|
||||
// match the type of the parameters.
|
||||
num/*=T*/ pickAtRandom/*<T extends num>*/(num/*=T*/ x, num/*=T*/ y) { ... }
|
||||
```
|
||||
|
||||
|
||||
Note that the generic parameter is in scope in the return type of the function,
|
||||
in the argument list of the function, and in the body of the function. When
|
||||
declaring local variables and parameters, you can also use the `/*=T*/` syntax with `var`.
|
||||
|
||||
```dart
|
||||
// foo is a generic method that takes a single generic parameter S, and a value
|
||||
// x of type S
|
||||
void foo/*<S>*/(var /*=S*/ x) {
|
||||
// In strong mode, y will also have type S
|
||||
var /*=S*/ y = x;
|
||||
|
||||
// In strong mode, z will also have type S
|
||||
dynamic /*=S*/ z = y;
|
||||
}
|
||||
```
|
||||
|
||||
Anywhere that a type literal is expected, you can also use the `/*=T*/` syntax to
|
||||
produce a type literal from the generic method parameter.
|
||||
|
||||
```dart
|
||||
void foo/*<S>*/(/*=S*/ x) {
|
||||
// In strong mode, s will get the type literal for S
|
||||
Type s = dynamic /*=S*/;
|
||||
|
||||
// In strong mode, this attempts to cast 3 as type S
|
||||
var y = (3 as dynamic /*=S*/);
|
||||
}
|
||||
```
|
||||
|
||||
You can use the `/*=T*/` syntax to replace any type with a generic type
|
||||
parameter, but you will usually want to replace `dynamic`. Otherwise, since the
|
||||
original type is used at runtime, it may cause checked mode errors:
|
||||
|
||||
```dart
|
||||
List/*<T>*/ makeList/*<T extends num>*/() {
|
||||
return new List<num /*=T*/>();
|
||||
}
|
||||
|
||||
void main() {
|
||||
List<int> list = makeList/*<int>*/(); // <-- Fails here.
|
||||
}
|
||||
```
|
||||
|
||||
This program checks without error in strong mode but fails at runtime in checked
|
||||
mode since the list that gets created is a `List<num>`. A better choice is:
|
||||
|
||||
```dart
|
||||
List/*<T>*/ makeList/*<T extends num>*/() {
|
||||
return new List/*<T>*/();
|
||||
}
|
||||
|
||||
void main() {
|
||||
List<int> list = makeList/*<int>*/();
|
||||
}
|
||||
```
|
||||
|
||||
## Instantiating generic classes with generic method parameters
|
||||
|
||||
You can use generic method parameters to instantiate generic classes using the
|
||||
same `/*=T*/` syntax.
|
||||
|
||||
```dart
|
||||
// foo is a generic method which returns a List<S> in strong mode,
|
||||
// but which returns List<dynamic> in normal mode.
|
||||
List<dynamic /*=S*/> foo/*<S>*/(/*=S*/ x) {
|
||||
// l0 is a list literal whose reified type will be List<S> in strong mode,
|
||||
// and List<dynamic> in normal mode.
|
||||
var l0 = <dynamic /*=S*/>[x];
|
||||
|
||||
// as above, but with a regular constructor.
|
||||
var l1 = new List<dynamic /*=S*/>();
|
||||
return l1;
|
||||
}
|
||||
```
|
||||
|
||||
In most cases, the entire type argument list to the generic class can be
|
||||
enclosed in parentheses, eliminating the need for explicitly writing `dynamic`.
|
||||
|
||||
```dart
|
||||
// This is another way of writing the same code as above
|
||||
List/*<S>*/ foo/*<S>*/(/*=S*/ x) {
|
||||
// The shorthand syntax is not yet supported for list and map literals
|
||||
var l0 = <dynamic /*=S*/>[x];
|
||||
|
||||
// but with regular constructors you can use it
|
||||
var l1 = new List/*<S>*/();
|
||||
return l1;
|
||||
}
|
||||
```
|
||||
|
||||
## Instantiating generic methods
|
||||
|
||||
Generic methods can be called without passing type arguments. Strong mode will
|
||||
attempt to infer the type arguments automatically. If it is unable to do so,
|
||||
then the type arguments will be filled in with whatever their declared bounds
|
||||
are (by default, `dynamic`).
|
||||
|
||||
```dart
|
||||
class C {
|
||||
/*=S*/ inferableFromArgument/*<S>*/(/*=S*/ x) { return null;}
|
||||
/*=S*/ notInferable/*<S>*/(int x) { return null;}
|
||||
}
|
||||
|
||||
void main() {
|
||||
C c = new C();
|
||||
// This line will produce a type error, because strong mode will infer
|
||||
// `int` as the generic argument to fill in for S
|
||||
String x = c.inferableFromArgument(3);
|
||||
|
||||
// This line will not produce a type error, because strong mode is unable
|
||||
// to infer a type and will fill in the type argument with `dynamic`.
|
||||
String y = c.notInferable(3);
|
||||
}
|
||||
```
|
||||
|
||||
In the case that strong mode cannot infer the generic type arguments, the same
|
||||
syntax that was shown above for instantiating generic classes can be used to
|
||||
instantiate generic methods explicitly.
|
||||
|
||||
```dart
|
||||
void main() {
|
||||
C c = new C();
|
||||
// This line will produce a type error, because strong mode will infer
|
||||
// `int` as the generic argument to fill in for S
|
||||
String x = c.inferableFromArgument(3);
|
||||
|
||||
// This line will produce a type error in strong mode, because `int` is
|
||||
// explicitly passed in as the argument to use for S
|
||||
String y = c.notInferable/*<int>*/(3);
|
||||
}
|
||||
```
|
||||
@@ -1,44 +0,0 @@
|
||||
# Strong Mode and Idiomatic JavaScript
|
||||
|
||||
**Note: This document is out of date. Please see [Sound Dart](https://dart.dev/guides/language/sound-dart) for up-to-date
|
||||
documentation on Dart's type system. The work below was a precursor towards Dart's current type system.**
|
||||
|
||||
The Dart Dev Compiler (DDC) uses [Strong Mode](STRONG_MODE.md) to safely generate
|
||||
idiomatic JavaScript. This enables better interoperability between Dart and JavaScript code.
|
||||
|
||||
The standard Dart type system is unsound by design. This means that static type annotations may not match the actual runtime values even when a program is running in checked mode. This allows considerable flexibility, but it also means that Dart implementations cannot easily use these annotations for optimization or code generation.
|
||||
|
||||
Because of this, existing Dart implementations require dynamic dispatch. Furthermore, because Dart’s dispatch semantics are different from JavaScript’s, it effectively precludes mapping Dart calls to idiomatic JavaScript. For example, the following Dart code:
|
||||
|
||||
```dart
|
||||
var x = a.bar;
|
||||
b.foo("hello", x);
|
||||
```
|
||||
|
||||
cannot easily be mapped to the identical JavaScript code. If `a` does not contain a `bar` field, Dart requires a `NoSuchMethodError` while JavaScript simply returns undefined. If `b` contains a `foo` method, but with the wrong number of arguments, Dart again requires a `NoSuchMethodError` while JavaScript either ignores extra arguments or fills in omitted ones with undefined.
|
||||
|
||||
To capture these differences, the Dart2JS compiler instead generates code that approximately looks like:
|
||||
|
||||
```dart
|
||||
var x = getInterceptor(a).get$bar(a);
|
||||
getInterceptor(b).foo$2(b, "hello", x);
|
||||
```
|
||||
The “interceptor” is Dart’s dispatch table for the objects `a` and `b`, and the mangled names (`get$bar` and `foo$2`) account for Dart’s different dispatch semantics.
|
||||
|
||||
The above highlights why Dart-JavaScript interoperability hasn’t been seamless: Dart objects and methods do not look like normal JavaScript ones.
|
||||
|
||||
DDC relies on strong mode to map Dart calling conventions to normal JavaScript ones. If `a` and `b` have static type annotations (with a type other than `dynamic`), strong mode statically verifies that they have a field `bar` and a 2-argument method `foo` respectively. In this case, DDC safely generates the identical JavaScript:
|
||||
|
||||
```javascript
|
||||
var x = a.bar;
|
||||
b.foo("hello", x);
|
||||
```
|
||||
|
||||
Note that DDC still supports the `dynamic` type, but relies on runtime helper functions in this case. E.g., if `a` and `b` are type `dynamic`, DDC instead generates:
|
||||
|
||||
```javascript
|
||||
var x = dload(a, "bar");
|
||||
dsend(b, "foo", "hello", x);
|
||||
```
|
||||
|
||||
where `dload` and `dsend` are runtime helpers that implement Dart dispatch semantics. Programmers are encouraged to use static annotations to avoid this. Strong mode is able to use static checking to enforce much of what checked mode does at runtime. In the code above, strong mode statically verifies that `b`’s type (if not `dynamic`) has a `foo` method that accepts a `String` as its first argument and `a.bar`’s type as its second. If the code is sufficiently typed, runtime checks are unnecessary.
|
||||
@@ -1,198 +0,0 @@
|
||||
# Strong Mode in the Dart Dev Compiler
|
||||
|
||||
## Overview
|
||||
|
||||
In the Dart Dev Compiler (DDC), [static strong mode](STATIC_SAFETY.md) checks are augmented with stricter runtime behavior. Together, they enforce the soundness of Dart type annotations.
|
||||
|
||||
In general, and in contrast to Dart's checked mode, most safety is enforced statically, at analysis time. DDC exploits this to generate relatively few runtime checks while still providing stronger guarantees than checked mode.
|
||||
|
||||
In particular, DDC adds the following:
|
||||
|
||||
- Stricter (but fewer) runtime type checks
|
||||
- Reified type narrowing
|
||||
- Restricted `is`/`as` checks
|
||||
|
||||
In all these cases, DDC (with static checks) is stricter than standard checked mode (or production mode). It may reject (either statically or at runtime) programs that run correctly in checked mode (similar to how checked mode may reject programs that run in production mode).
|
||||
|
||||
On the other hand, programs that statically check and run correctly in DDC should also run the same in checked mode. A caveat to note is that mirrors (or `runtimeType`) may show a more narrow type in DDC (though, in practice, programmers are discouraged from using these features for performance / code size reasons).
|
||||
|
||||
## Runtime checks
|
||||
|
||||
In practice, strong mode enforces most type annotations at compile time, and, thus, requires less work at runtime to enforce safety. Consider the following Dart code:
|
||||
|
||||
```dart
|
||||
String foo(Map<int, String> map, int x) {
|
||||
return map[x.abs()];
|
||||
}
|
||||
```
|
||||
|
||||
Strong mode enforces that the function `foo` is only invoked in a manner consistent with its signature. DDC - which assumes strong mode static checking - inserts no further runtime checks. In contrast, standard Dart checked mode would check the type of the parameters -- `map` and `x` -- along with the type of the return value at runtime on every invocation of `foo`. Even Dart production mode, depending on the implementation and its ability to optimize, may require similar checking to dynamically dispatch the map lookup and the method call in the body of `foo`.
|
||||
|
||||
Nevertheless, there are cases where DDC still requires runtime checks. (Note: DDC may eventually provide a mode to elide these checks, but this would violate soundness and is beyond the scope of this document.)
|
||||
|
||||
### Implicit casts
|
||||
|
||||
Dart has flexible assignability rules. Programmers are not required to explicitly cast from supertypes to subtypes. For example, the following is valid Dart:
|
||||
|
||||
```dart
|
||||
Object o = ...;
|
||||
String s = o; // Implicit downcast
|
||||
String s2 = s.substring(1);
|
||||
```
|
||||
|
||||
The assignment to `s` is an implicit downcast from `Object` to `String` and triggers a runtime check in DDC to ensure it is correct.
|
||||
|
||||
Note that checked mode would also perform this runtime test. Unlike checked mode, DDC would not require a check on the assignment to `s2` - this type is established statically.
|
||||
|
||||
### Inferred variables
|
||||
|
||||
Dart's inference may narrow the static type of certain variables. If the variable is mutable, DDC enforces the narrower type at runtime when necessary.
|
||||
|
||||
In the following example, strong mode will infer of the type of the local variable `y` as an `int`:
|
||||
|
||||
```dart
|
||||
int bar(Object x) {
|
||||
var y = 0;
|
||||
if (x != null) {
|
||||
y = x;
|
||||
}
|
||||
return y.abs();
|
||||
}
|
||||
```
|
||||
|
||||
This allows it to, for example, static verify the call to `y.abs()` and determine that it returns an `int`. However, the parameter `x` is typed as `Object` and the assignment from `x` to `y` now requires a type check to ensure that `y` is only assigned an `int`.
|
||||
|
||||
Note, strong mode and DDC are conservative by enforcing a tighter type than required by standard Dart checked mode. For example, checked mode would accept a non-`int` `x` with an `abs` method that happened to return an `int`. In strong mode, a programmer would have to explicitly opt into this behavior by annotating `y` as an `Object` or `dynamic`.
|
||||
|
||||
### Covariant generics
|
||||
|
||||
Strong mode preserves the covariance of Dart's generic classes. To support this soundly, DDC injects runtime checks on parameters in method invocations whose type is a class type parameter. Consider the call to `baz` in the parameterized class `A`:
|
||||
|
||||
```dart
|
||||
class A<T> {
|
||||
T baz(T x, int y) => x;
|
||||
}
|
||||
|
||||
void foo(A<Object> a) {
|
||||
a.baz(42, 38);
|
||||
}
|
||||
|
||||
void main() {
|
||||
var aString = new A<String>();
|
||||
foo(aString);
|
||||
}
|
||||
```
|
||||
|
||||
Statically, sound mode will not generate an error or warning on this code. The call to `baz` in `foo` is statically valid as `42` is an `Object` (as required by the static type of `a`). However, the runtime type of `a` in this example is the narrower `A<String>`. At runtime, when baz is executed, DDC will check that the type of `x` matches the reified type parameter and, in this example, fail.
|
||||
|
||||
Note, only `x` requires a runtime check. Unlike checked mode, no runtime check is required for `y` or the return value. Both are statically verified.
|
||||
|
||||
### Dynamic operations
|
||||
|
||||
Strong mode allows programmers to explicitly use `dynamic` as a type. It also allows programmers to omit types, and in some of these cases inference may fall back on `dynamic` if it cannot determine a static type. In these cases, DDC inserts runtime checks (typically in the form of runtime helper calls).
|
||||
|
||||
For example, in the following:
|
||||
|
||||
```dart
|
||||
int foo(int x) => x + 1;
|
||||
|
||||
void main() {
|
||||
dynamic bar = foo;
|
||||
bar("hello"); // DDC runtime error
|
||||
}
|
||||
```
|
||||
|
||||
`foo` (via `bar`) is incorrectly invoked on a `String`. There is no static error as `bar` is typed `dynamic`. Instead DDC, performs extra runtime checking on the invocation of `bar`. In this case, it would generate a runtime type error. Note, if the type of `bar` had been omitted, it would have been inferred, and the error would have been reported statically.
|
||||
|
||||
Nevertheless, there are situations where programmers may prefer a dynamic type for flexibility.
|
||||
|
||||
## Runtime type Narrowing
|
||||
|
||||
Strong mode statically infers tighter types for functions and generics. In DDC, this is reflected in the reified type at runtime. This allows DDC to enforce the stricter type soundly at runtime when necessary.
|
||||
|
||||
In particular, this means that DDC may have a stricter concrete runtime type than other Dart implementations for generic classes and functions. The DDC type will always be a subtype.
|
||||
|
||||
This will impact execution in the following ways:
|
||||
- DDC may trigger runtime errors where checked mode is forgiving.
|
||||
- Code that uses reflection may observe a narrower type in DDC.
|
||||
|
||||
### Allocation inference
|
||||
|
||||
When strong infers a narrower type for a closure literal or other allocation expression, DDC reifies this narrower type at runtime. As a result, it can soundly enforce typing errors at runtime.
|
||||
|
||||
The following is an example of where static checking fails to catch a typing error:
|
||||
|
||||
```dart
|
||||
apply(int g(x), y) {
|
||||
print(g(y));
|
||||
}
|
||||
|
||||
typedef int Int2Int(int x);
|
||||
|
||||
void main() {
|
||||
Int2Int f = (x) => x + x;
|
||||
apply(f, "hello");
|
||||
}
|
||||
```
|
||||
|
||||
A programmer examining `apply` would reasonably expect it to print an `int` value. The analyzer (with or without strong mode) fails to report a problem. Standard Dart checked simply prints `"hellohello"`. In DDC, however, a runtime error is thrown on the application of `g` in `apply`. The closure literal assigned to `f` in `main` is reified as an `int -> int`, and DDC enforces this at runtime.
|
||||
|
||||
In this example, if `apply` and its parameters were fully typed, strong mode would report a static error, and DDC would impose no runtime check.
|
||||
|
||||
### Generic methods
|
||||
|
||||
[Note: This is not yet implemented correctly.](https://github.com/dart-lang/dev_compiler/issues/301)
|
||||
|
||||
Similarly, DDC requires that [generic methods](GENERIC_METHODS.md) return the correct reified type. In strong mode, `Iterable.map` is a generic method. In DDC, `lengths` in `main` will have a reified type of `List<int>`. In `foo`, this will trigger a runtime error when a string is added to the list.
|
||||
|
||||
```dart
|
||||
void foo(List l) {
|
||||
l.add("a string");
|
||||
}
|
||||
|
||||
void main() {
|
||||
Iterable<String> list = <String>["hello", "world"];
|
||||
List<int> lengths = list.map((x) => x.length).toList();
|
||||
foo(lengths);
|
||||
print(lengths[2]);
|
||||
}
|
||||
```
|
||||
|
||||
Standard checked mode would print `"a string"` without error.
|
||||
|
||||
## Is / As restrictions
|
||||
|
||||
In standard Dart, `is` and `as` runtime checks expose the unsoundness of the type system in certain cases. For example, consider:
|
||||
|
||||
```dart
|
||||
var list = <dynamic>["hello", "world"];
|
||||
if (list is List<int>) {
|
||||
...
|
||||
} else if (list is List<String>) {
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
Perhaps surprisingly, the first test - `list is List<int>` - evaluates to true here. Such code is highly likely to be erroneous.
|
||||
|
||||
Strong mode provides a stricter subtyping check and DDC enforces this at runtime. For compatibility with standard Dart semantics, however, DDC throws a runtime error when an `is` or `as` check would return a different answer with strong mode typing semantics.
|
||||
|
||||
In the example above, the first `is` check would generate a runtime error.
|
||||
|
||||
Note, we are exploring making this a static error or warning in strong mode. In general, an expression:
|
||||
|
||||
```dart
|
||||
x is T
|
||||
```
|
||||
|
||||
or
|
||||
|
||||
```dart
|
||||
x as T
|
||||
```
|
||||
|
||||
is only guaranteed safe when `T` is a *ground type*:
|
||||
|
||||
- A non-generic class type (e.g., `Object`, `String`, `int`, ...).
|
||||
- A generic class type where all type parameters are implicitly or explicitly `dynamic` (e.g., `List<dynamic>`, `Map`, …).
|
||||
- A function type where the return type and all parameter types are `dynamic` (e.g., (`dynamic`, `dynamic`) -> `dynamic`, ([`dynamic`]) -> `dynamic`).
|
||||
@@ -1,530 +0,0 @@
|
||||
# Strong Mode Static Checking
|
||||
|
||||
**Note: This document is out of date. Please see [Sound Dart](https://dart.dev/guides/language/sound-dart) for up-to-date
|
||||
documentation on Dart's type system. The work below was a precursor towards Dart's current type system.**
|
||||
|
||||
## Overview
|
||||
|
||||
The Dart programming language has an optional, unsound type system. Although it is similar in appearance to languages such as Java, C#, or C++, its type system and static checking are fundamentally different. It permits erroneous behavior in ways that may be surprising to programmers coming from those and other conventional typed languages.
|
||||
|
||||
In Dart, static type annotations can be often misleading. Dart code such as:
|
||||
|
||||
```dart
|
||||
var list = ["hello", "world"];
|
||||
List<int> listOfInts = list;
|
||||
```
|
||||
|
||||
produces neither static nor runtime errors. Actual errors may show up much later on, e.g., with the following code, only at runtime on the invocation of `abs`:
|
||||
|
||||
```dart
|
||||
Iterable<int> iterableOfInts = listOfInts.map((i) => i.abs());
|
||||
```
|
||||
|
||||
Strong mode aims to catch such errors early by validating that variables - e.g., `listOfInts` - actually match their corresponding static type annotations - e.g., `List<int>`. It constrains the Dart programming language to a subset of programs that type check under a restricted set of rules. It statically rejects examples such as the above.
|
||||
|
||||
To accomplish this, strong mode involves the following:
|
||||
|
||||
- **Type inference**. Dart’s standard type rules treats untyped variables as `dynamic`, which
|
||||
suppresses any static warnings on them. Strong mode infers static types based upon context. In the example above, strong mode infers that `list` has type `List`. Note, in strong mode, programmers may still explicitly use the `dynamic` type.
|
||||
|
||||
- **Strict subtyping**. Dart’s primary sources of unsoundness are due to its subtyping rules on function types and generic classes. Strong mode restricts these: e.g., `List` may not used as `List<int>` in the example above.
|
||||
|
||||
- **Generic methods**. Standard Dart does not yet provide generic methods. This makes certain polymorphic methods difficult to use soundly. For example, the `List.map` invocation above is statically typed to return an `Iterable<dynamic>` in standard Dart. Strong mode allows methods to be annotated as generic. `List.map` is statically typed to return an `Iterable<T>` where `T` is bound to `int` in the previous example. A number of common higher-order methods are annotated and checked as generic in strong mode, and programmers may annotate their own methods as well.
|
||||
|
||||
Strong mode is designed to work in conjunction with the Dart Dev Compiler (DDC), which uses static type verification to generate better code. DDC augments strong mode static checking with a minimal set of [runtime checks](RUNTIME_SAFETY.md) that aim to provide full soundness of types.
|
||||
|
||||
Strong mode static analysis may also be used alone for stricter error checking.
|
||||
|
||||
Formal details of the strong mode type system may be found [here](https://dart-lang.github.io/dev_compiler/strong-dart.pdf).
|
||||
|
||||
## Usage
|
||||
|
||||
Strong mode is now integrated into the Dart Analyzer. The analyzer may be invoked in strong mode as follows:
|
||||
|
||||
$ dartanalyzer --strong myapp.dart
|
||||
|
||||
Strong mode may also be enabled in IDEs by creating (if necessary) an `.analysis_options` file in your project and appending the following entry to it:
|
||||
|
||||
```
|
||||
analyzer:
|
||||
strong-mode: true
|
||||
```
|
||||
|
||||
## Type Inference
|
||||
|
||||
With strong mode, we want to provide stronger typing while preserving the
|
||||
terseness of Dart. [Idiomatic Dart
|
||||
code](https://dart.dev/guides/language/effective-dart) discourages type annotations
|
||||
outside of API boundaries, and user shouldn't have to add more types to get
|
||||
better checking. Instead, strong mode uses type inference.
|
||||
|
||||
In Dart, per the specification, the static type of a variable `x` declared as:
|
||||
|
||||
```dart
|
||||
var x = <String, String>{ "hello": "world"};
|
||||
```
|
||||
|
||||
is `dynamic` as there is no explicit type annotation on the left-hand side. To discourage code bloat, the Dart style guide generally recommends omitting these type annotations in many situations. In these cases, the benefits of strong mode would be lost.
|
||||
|
||||
To avoid this, strong mode uses type inference. In the case above, strong mode infers and enforces the type of `x` as `Map<String, String>`. An important aspect to inference is ordering: when an inferred type may be used to infer another type. To maximize the impact, we perform the following inference:
|
||||
|
||||
- Top-level and static fields
|
||||
- Instance fields and methods
|
||||
- Local variables
|
||||
- Constructor calls and literals
|
||||
- Generic method invocations
|
||||
|
||||
Inference may tighten the static type as compared to the Dart specification. An implicitly dynamic type, either alone or in the context of a function or generic parameter type, is inferred to a more specific type. This inference may result in stricter type errors than standard Dart.
|
||||
|
||||
In [DDC](RUNTIME_SAFETY.md), inference may also affect the reified runtime type.
|
||||
|
||||
### Top-level and Static Fields
|
||||
|
||||
Strong mode infers any untyped top-level field or static field from the type of
|
||||
its initializer. The static type of the declared variable is inferred as the static type of the initializer. For example, consider:
|
||||
|
||||
```dart
|
||||
var PI = 3.14159;
|
||||
var radius = 2;
|
||||
var circumference = 2 * PI * radius;
|
||||
```
|
||||
|
||||
Strong mode infers the static type of `PI` as `double` and `radius` as `int` directly from their initializers. It infers the static type of `circumference` as `double`, transitively using the other inferred types. Standard Dart rules would treat all of these static types as `dynamic`. Note that the following later assignment would be allowed in standard Dart, but disallowed (as a static type error) in strong mode:
|
||||
```dart
|
||||
radius = "five inches";
|
||||
```
|
||||
Strong mode inference avoids circular dependences. If a variable’s initializer expression refers to another variable whose type would be dependent (directly or indirectly) on the first, the static type of that other variable is treated as `dynamic` for the purpose of inference.
|
||||
|
||||
### Instance Fields and Methods
|
||||
|
||||
Strong mode performs two types of inference on instance fields and methods.
|
||||
|
||||
The first uses base types to constrain overrides in subtypes. Consider the following example:
|
||||
|
||||
```dart
|
||||
abstract class A {
|
||||
Map get m;
|
||||
int value(int i);
|
||||
}
|
||||
|
||||
class B extends A {
|
||||
var m;
|
||||
value(i) => m[i];
|
||||
…
|
||||
}
|
||||
```
|
||||
|
||||
In Dart, overridden method, getter, or setter types should be subtypes of the corresponding base class ones (otherwise, static warnings are given). In standard Dart, the above declaration of `B` is not an error: both `m`’s getter type and `value`’s return type are `dynamic`.
|
||||
|
||||
Strong mode -- without inference -- would disallow this: if `m` in `B` could be assigned any kind of object, including one that isn't a Map, it would violate the type contract in the declaration of `A`.
|
||||
|
||||
However, rather than rejecting the above code, strong mode employs inference to tighten the static types to obtain a valid override. The corresponding types in B are inferred as if it was:
|
||||
|
||||
```dart
|
||||
class B extends A {
|
||||
Map m;
|
||||
int value(int i) => m[i];
|
||||
…
|
||||
}
|
||||
```
|
||||
|
||||
Note that tightening the argument type for `i` to `int` is not required for soundness; it is done for convenience as it is the typical intent. The programmer may explicitly type this as `dynamic` or `Object` to avoid inferring the narrower type.
|
||||
|
||||
The second form inference is limited to instance fields (not methods) and is similar to that on static fields. For instance fields where the static type is omitted and an initializer is present, the field’s type is inferred as the initializer’s type. In this continuation of our example:
|
||||
|
||||
```dart
|
||||
class C extends A {
|
||||
var y = 42;
|
||||
var m = <int, int>{ 0: 38};
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
the instance field `y` has inferred type `int` based upon its initializer. Note that override-based inference takes precedence over initializer-based inference. The instance field `m` has inferred type `Map`, not `Map<int, int>` due to the corresponding declaration in `A`.
|
||||
|
||||
### Local Variables
|
||||
|
||||
As with fields, local variable types are inferred if the static type is omitted and an initializer expression is present. In the following example:
|
||||
|
||||
```dart
|
||||
Object foo(int x) {
|
||||
final y = x + 1;
|
||||
var z = y * 2;
|
||||
return z;
|
||||
}
|
||||
```
|
||||
|
||||
the static types of `y` and `z` are both inferred as `int` in strong mode. Note that local inference is done in program order: the inferred type of `z` is computed using the inferred type of `y`. Local inference may result in strong mode type errors in otherwise legal Dart code. In the above, a second assignment to `z` with a string value:
|
||||
```dart
|
||||
z = "$z";
|
||||
```
|
||||
would trigger a static error in strong mode, but is allowed in standard Dart. In strong mode, the programmer must use an explicit type annotation to suppress inference. Explicitly declaring `z` with the type `Object` or `dynamic` would suffice in this case.
|
||||
|
||||
### Constructor Calls and Literals
|
||||
|
||||
Strong mode also performs contextual inference on allocation expressions. This inference is rather different from the above: it tightens the runtime type of the corresponding expression using the static type of its context. Contextual inference is used on expressions that allocate a new object: closure literals, map and list literals, and explicit constructor invocations (i.e., via `new` or `const`).
|
||||
|
||||
In DDC, these inferred types are also [reified at runtime](RUNTIME_SAFETY.md) on the newly allocated objects to provide a stronger soundness guarantee.
|
||||
|
||||
#### Closure literals
|
||||
|
||||
Consider the following example:
|
||||
|
||||
```dart
|
||||
int apply(int f(int arg), int value) {
|
||||
return f(value);
|
||||
}
|
||||
|
||||
void main() {
|
||||
int result =
|
||||
apply((x) { x = x * 9 ~/ 5; return x + 32; }, 41);
|
||||
print(result);
|
||||
}
|
||||
```
|
||||
|
||||
The function `apply` takes another function `f`, typed `(int) -> int`, as its first argument. It is invoked in `main` with a closure literal. In standard Dart, the static type of this closure literal would be `(dynamic) -> dynamic`. In strong mode, this type cannot be safely converted to `(int) -> int` : it may return a `String` for example.
|
||||
|
||||
Dart has a syntactic limitation in this case: it is not possible to statically annotate the return type of a closure literal.
|
||||
|
||||
Strong mode sidesteps this difficulty via contextual inference. It infers the closure type as `(int) -> int`. Note, this may trigger further inference and type checks in the body of the closure.
|
||||
|
||||
#### List and map literals
|
||||
|
||||
Similarly, strong mode infers tighter runtime types for list and map literals. E.g., in
|
||||
|
||||
```dart
|
||||
List<String> words = [ "hello", "world" ];
|
||||
```
|
||||
|
||||
the runtime type is inferred as `List<String>` in order to match the context of the left hand side. In other words, the code above type checks and executes as if it was:
|
||||
|
||||
```dart
|
||||
List<String> words = <String>[ "hello", "world" ];
|
||||
```
|
||||
|
||||
Similarly, the following will now trigger a static error in strong mode:
|
||||
|
||||
```dart
|
||||
List<String> words = [ "hello", 42 ]; // Strong Mode Error: 42 is not a String
|
||||
```
|
||||
|
||||
Contextual inference may be recursive:
|
||||
|
||||
```dart
|
||||
Map<List<String>, Map<int, int>> map =
|
||||
{ ["hello"]: { 0: 42 }};
|
||||
```
|
||||
|
||||
In this case, the inner map literal is inferred as a `Map<int, int>`. Note, strong mode will statically reject code where the contextually required type is not compatible. This will trigger a static error:
|
||||
|
||||
```dart
|
||||
Map<List<String>, Map<int, int>> map =
|
||||
{ ["hello"]: { 0: "world" }}; // STATIC ERROR
|
||||
```
|
||||
|
||||
as "world" is not of type `int`.
|
||||
|
||||
#### Constructor invocations
|
||||
|
||||
Finally, strong mode performs similar contextual inference on explicit constructor invocations via `new` or `const`. For example:
|
||||
|
||||
```dart
|
||||
Set<String> string = new Set.from(["hello", "world"]);
|
||||
```
|
||||
|
||||
is treated as if it was written as:
|
||||
|
||||
```dart
|
||||
Set<String> string =
|
||||
new Set<String>.from(<String>["hello", "world"]);
|
||||
```
|
||||
|
||||
Note, as above, context is propagated downward into the expression.
|
||||
|
||||
## Strict subtyping
|
||||
|
||||
The primary sources of unsoundness in Dart are generics and functions. Both introduce circularity in the Dart subtyping relationship.
|
||||
|
||||
### Generics
|
||||
|
||||
Generics in Dart are covariant, with the added rule that the `dynamic` type may serve as both ⊤ (top) and ⊥ (bottom) of the type hierarchy in certain situations. For example, let *<:<sub>D</sub>* represent the standard Dart subtyping rule. Then, for all types `S` and `T`:
|
||||
|
||||
`List<S>` <:<sub>D</sub> `List<dynamic>` <:<sub>D</sub> `List<T>`
|
||||
|
||||
where `List` is equivalent to `List<dynamic>`. This introduces circularity - e.g.:
|
||||
|
||||
`List<int>` <:<sub>D</sub> `List` <:<sub>D</sub> `List<String>`<:<sub>D</sub> `List` <:<sub>D</sub> `List<int>`
|
||||
|
||||
From a programmer’s perspective, this means that, at compile-time, values that are statically typed `List<int>` may later be typed `List<String>` and vice versa. At runtime, a plain `List` can interchangeably act as a `List<int>` or a `List<String>` regardless of its actual values.
|
||||
|
||||
The example taken from [here](https://github.com/dart-lang/dev_compiler/blob/strong/STRONG_MODE.md#motivation) exploits this:
|
||||
|
||||
```dart
|
||||
class MyList extends ListBase<int> implements List {
|
||||
Object length;
|
||||
|
||||
MyList(this.length);
|
||||
|
||||
operator[](index) => "world";
|
||||
operator[]=(index, value) {}
|
||||
}
|
||||
```
|
||||
|
||||
A `MyList` may masquerade as a `List<int>` as it is transitively a subtype:
|
||||
|
||||
`MyList` <:<sub>D</sub> `List` <:<sub>D</sub>`List<int>`
|
||||
|
||||
In strong mode, we introduce a stricter subtyping rule <:<sub>S</sub> to disallow this. In this case, in the context of a generic type parameter, dynamic may only serve as ⊤. This means that this is still true:
|
||||
|
||||
`List<int>` <:<sub>S</sub> `List`
|
||||
|
||||
but that this is not:
|
||||
|
||||
`List` ~~<:<sub>S</sub> `List<int>`~~
|
||||
|
||||
The example above fails in strong mode:
|
||||
|
||||
`MyList` <:<sub>S</sub> `List` ~~<:<sub>S</sub> `List<int>`~~
|
||||
|
||||
|
||||
### Functions
|
||||
|
||||
The other primary source of unsoundness in Dart is function subtyping. An unusual feature of the Dart type system is that function types are bivariant in both the parameter types and the return type (see Section 19.5 of the [Dart specification][dartspec]). As with generics, this leads to circularity:
|
||||
|
||||
`(int) -> int` <:<sub>D</sub> `(Object) -> Object` <:<sub>D</sub> `(int) -> int`
|
||||
|
||||
And, as before, this can lead to surprising behavior. In Dart, an overridden method’s type should be a subtype of the base class method’s type (otherwise, a static warning is given). In our running example, the (implicit) `MyList.length` getter has type:
|
||||
|
||||
`() -> Object`
|
||||
|
||||
while the `List.length` getter it overrides has type:
|
||||
|
||||
`() -> int`
|
||||
|
||||
This is valid in standard Dart as:
|
||||
|
||||
`() -> Object` <:<sub>D</sub> `() -> int`
|
||||
|
||||
Because of this, a `length` that returns "hello" (a valid `Object`) triggers no static or runtime warnings or errors.
|
||||
|
||||
Strong mode enforces the stricter, [traditional function subtyping](https://en.wikipedia.org/wiki/Subtyping#Function_types) rule: subtyping is contravariant in parameter types and covariant in return types. This permits:
|
||||
|
||||
`() -> int` <:<sub>S</sub> `() -> Object`
|
||||
|
||||
but disallows:
|
||||
|
||||
`() -> Object` <:<sub>S</sub> `() -> int`
|
||||
|
||||
With respect to our example, strong mode requires that any subtype of a List have an int-typed length. It statically rejects the length declaration in MyList.
|
||||
|
||||
## Generic Methods
|
||||
|
||||
Strong mode introduces generic methods to allow more expressive typing on polymorphic methods. Such code in standard Dart today often loses static type information. For example, the `Iterable.map` method is declared as below:
|
||||
|
||||
```dart
|
||||
abstract class Iterable<E> {
|
||||
...
|
||||
Iterable map(f(E e));
|
||||
}
|
||||
```
|
||||
|
||||
Regardless of the static type of the function `f`, the `map` always returns an `Iterable<dynamic>` in standard Dart. As result, standard Dart tools miss the obvious error on the following code:
|
||||
|
||||
```dart
|
||||
Iterable<int> results = <int>[1, 2, 3].map((x) => x.toString()); // Static error only in strong mode
|
||||
```
|
||||
|
||||
The variable `results` is statically typed as if it contains `int` values, although it clearly contains `String` values at runtime.
|
||||
|
||||
The [generic methods proposal](https://github.com/leafpetersen/dep-generic-methods/blob/master/proposal.md) adds proper generic methods to the Dart language as a first class language construct and to make methods such as the `Iterable.map` generic.
|
||||
|
||||
To enable experimentation, strong mode provides a [generic methods prototype](GENERIC_METHODS.md) based on the existing proposal, but usable on all existing Dart implementations today. Strong mode relies on this to report the error on the example above.
|
||||
|
||||
The `Iterable.map` method is now declared as follows:
|
||||
|
||||
```dart
|
||||
abstract class Iterable<E> {
|
||||
...
|
||||
Iterable/*<T>*/ map/*<T>*/(/*=T*/ f(E e));
|
||||
}
|
||||
```
|
||||
|
||||
At a use site, the generic type may be explicitly provided or inferred from context:
|
||||
|
||||
```
|
||||
var l = <int>[1, 2, 3];
|
||||
var i1 = l.map((i) => i + 1);
|
||||
var l2 = l.map/*<String>*/((i) { ... });
|
||||
```
|
||||
|
||||
In the first invocation of `map`, the closure is inferred (from context) as `int -> int`, and the generic type of map is inferred as `int` accordingly. As a result, `i1` is inferred as `Iterable<int>`. In the second, the type parameter is explicitly bound to `String`, and the closure is checked against this type. `i2` is typed as `Iterable<String>`.
|
||||
|
||||
Further details on generic methods in strong mode and in DDC may be found [here](GENERIC_METHODS.md).
|
||||
|
||||
## Additional Restrictions
|
||||
|
||||
In addition to stricter typing rules, strong mode enforces other
|
||||
restrictions on Dart programs.
|
||||
|
||||
### Warnings as Errors
|
||||
|
||||
Strong mode effectively treats all standard Dart static warnings as static errors. Most of these warnings are required for soundness (e.g., if a concrete class is missing methods required by a declared interface). A full list of Dart static warnings may found in the [Dart specification][dartspec], or enumerated here:
|
||||
|
||||
[https://github.com/dart-lang/sdk/blob/main/pkg/analyzer/lib/src/generated/error.dart#L3772](https://www.google.com/url?q=https%3A%2F%2Fgithub.com%2Fdart-lang%2Fsdk%2Fblob%2Fmaster%2Fpkg%2Fanalyzer%2Flib%2Fsrc%2Fgenerated%2Ferror.dart%23L3772&sa=D&sntz=1&usg=AFQjCNFc4E37M1PshVcw4zk7C9jXgqfGbw)
|
||||
|
||||
### Super Invocations
|
||||
|
||||
In the context of constructor initializer lists, strong mode restricts `super` invocations to the end. This restriction simplifies generated code with minimal effect on the program.
|
||||
|
||||
### For-in loops
|
||||
|
||||
In for-in statements of the form:
|
||||
|
||||
```dart
|
||||
for (var i in e) { … }
|
||||
```
|
||||
|
||||
Strong mode requires the expression `e` to be an `Iterable`. When the loop variable `i` is also statically typed:
|
||||
|
||||
```dart
|
||||
for (T i in e) { … }
|
||||
```
|
||||
|
||||
the expression `e` is required to be an `Iterable<T>`.
|
||||
|
||||
*Note: we may weaken these.*
|
||||
|
||||
### Field overrides
|
||||
|
||||
By default, fields are overridable in Dart.
|
||||
|
||||
```dart
|
||||
int init(int n) {
|
||||
print('Initializing with $n');
|
||||
return n;
|
||||
}
|
||||
|
||||
class A {
|
||||
int x = init(42);
|
||||
}
|
||||
|
||||
class B extends A {
|
||||
int x;
|
||||
}
|
||||
```
|
||||
|
||||
Disallow overriding fields: this results in complicated generated
|
||||
code where a field definition in a subclass shadows the field
|
||||
definition in a base class but both are generally required to be
|
||||
allocated. Users should prefer explicit getters and setters in such
|
||||
cases. See [issue 52](https://github.com/dart-lang/dev_compiler/issues/52).
|
||||
|
||||
## Optional Features
|
||||
|
||||
### Disable implicit casts
|
||||
|
||||
This is an optional feature of strong mode. It disables implicit down casts. For example:
|
||||
|
||||
```dart
|
||||
main() {
|
||||
num n = 0.5;
|
||||
int x = n; // error: invalid assignment
|
||||
int y = n as int; // ok at compile time, might fail when run
|
||||
}
|
||||
```
|
||||
|
||||
Casts from `dynamic` must be explicit as well:
|
||||
|
||||
```dart
|
||||
main() {
|
||||
dynamic d = 'hi';
|
||||
int x = d; // error: invalid assignment
|
||||
int y = d as int; // ok at compile time, might fail when run
|
||||
}
|
||||
```
|
||||
|
||||
This option is experimental and may be changed or removed in the future.
|
||||
Try it out in your project by editing .analysis_options:
|
||||
|
||||
```yaml
|
||||
analyzer:
|
||||
strong-mode:
|
||||
implicit-casts: False
|
||||
```
|
||||
|
||||
Or pass `--no-implicit-casts` to Dart Analyzer:
|
||||
|
||||
```
|
||||
dartanalyzer --strong --no-implicit-casts my_app.dart
|
||||
```
|
||||
|
||||
### Disable implicit dynamic
|
||||
|
||||
This is an optional feature of analyzer, intended primarily for use with strong mode's inference.
|
||||
It rejects implicit uses of `dynamic` that strong mode inference fails to fill in with a concrete type,
|
||||
ensuring that all types are either successfully inferred or explicitly written. For example:
|
||||
|
||||
```dart
|
||||
main() {
|
||||
var x; // error: implicit dynamic
|
||||
var i = 123; // okay, inferred to be `int x`
|
||||
dynamic y; // okay, declared as dynamic
|
||||
}
|
||||
```
|
||||
|
||||
This also affects: parameters, return types, fields, creating objects with generic type, generic functions/methods, and
|
||||
supertypes:
|
||||
|
||||
```dart
|
||||
// error: parameters and return types are implicit dynamic
|
||||
f(x) => x + 42;
|
||||
dynamic f(dynamic x) => x + 42; // okay
|
||||
int f(int x) => x + 42; // okay
|
||||
|
||||
class C {
|
||||
var f; // error: implicit dynamic field
|
||||
dynamic f; // okay
|
||||
}
|
||||
|
||||
main() {
|
||||
var x = []; // error: implicit List<dynamic>
|
||||
var y = [42]; // okay: List<int>
|
||||
var z = <dynamic>[]; // okay: List<dynamic>
|
||||
|
||||
T genericFn<T>() => null;
|
||||
genericFn(); // error: implicit genericFn<dynamic>
|
||||
genericFn<dynamic>(); // okay
|
||||
int x = genericFn(); // okay, inferred genericFn<int>
|
||||
}
|
||||
|
||||
// error: implicit supertype Iterable<dynamic>
|
||||
class C extends Iterable { /* ... */ }
|
||||
// okay
|
||||
class C extends Iterable<dynamic> { /* ... */ }
|
||||
```
|
||||
|
||||
This feature is to prevent accidental use of `dynamic` in code that does not intend to use it.
|
||||
|
||||
This option is experimental and may be changed or removed in the future.
|
||||
Try it out in your project by editing .analysis_options:
|
||||
|
||||
```yaml
|
||||
analyzer:
|
||||
strong-mode:
|
||||
implicit-dynamic: False
|
||||
```
|
||||
|
||||
Or pass `--no-implicit-dynamic` to Dart Analyzer:
|
||||
|
||||
```
|
||||
dartanalyzer --strong --no-implicit-dynamic my_app.dart
|
||||
```
|
||||
|
||||
### Open Items
|
||||
|
||||
- Is / As restrictions: Dart's `is` and `as` checks are unsound for certain types
|
||||
(generic classes, certain function types). In [DDC](RUNTIME_SAFETY.md), problematic
|
||||
`is` and `as` checks trigger runtime errors. We are considering introducing static
|
||||
errors for these cases.
|
||||
|
||||
[dartspec]: https://dart.dev/guides/language/spec "Dart Language Spec"
|
||||
@@ -1,67 +0,0 @@
|
||||
%%% Cascaded items for math mode
|
||||
%% start with \begin{cascade}
|
||||
%% new line at previous indentation with \cascline
|
||||
%% new line with greater indentation with \cascitem
|
||||
%% end with \end{cascade}
|
||||
%% default indentation is 2em, adjust with \cascadeindent
|
||||
\newdimen\cascadeindent
|
||||
\cascadeindent=1em\newdimen\cascdimen
|
||||
\newcommand{\cascindent}{\global\advance\cascdimen by\cascadeindent \hspace{\cascdimen}}
|
||||
\newcommand{\cascitem}{\\ \global\advance\cascdimen by\cascadeindent \hspace{\cascdimen}}
|
||||
\newcommand{\cascback}[1]{\\ \global\advance\cascdimen by-#1.0\cascadeindent \hspace{\cascdimen}}
|
||||
\newcommand{\cascline}{\\ \hspace{\cascdimen}}
|
||||
\newenvironment{cascade}{\begin{array}[t]{@{}l@{}} \global\cascdimen=0em}{\end{array}}
|
||||
|
||||
|
||||
%%% Binding colon stuff
|
||||
\mathchardef\col="003A % \col for binding colon (mathcode ordinary: less space)
|
||||
\mathchardef\semi="603B % \semi for (regular) semicolon
|
||||
%% use \semicolonforbindingcolon to redefine ; to stand for binding colon
|
||||
\newcommand{\semicolonforbindingcolon}{\mathcode`;="003A}
|
||||
|
||||
%%% Angle bracket stuff
|
||||
\mathchardef\lt="313C % \lt for <
|
||||
\mathchardef\gt="313E % \gt for >
|
||||
%% use \ltgtforanglebrackets to redefine <,> to stand for \langle, \rangle
|
||||
\newcommand{\ltgtforanglebrackets}{\mathcode`<="4268 \mathcode`>="5269}
|
||||
|
||||
\newcommand{\kwop}[1]{\ensuremath{\mathop{\mathbf{#1}}}}
|
||||
\newcommand{\kwbin}[1]{\ensuremath{\mathbin{\mathbf{#1}}}}
|
||||
\newcommand{\kw}[1]{\ensuremath{\mathord{\mathbf{#1}}}}
|
||||
|
||||
\newcommand{\comment}[1]{\hfill \fbox{\Large{#1}}}
|
||||
|
||||
%\newcommand{\qed}{\rule{5pt}{8pt}}
|
||||
\newcommand{\thmbox}
|
||||
{{\ \hfill\hbox{%
|
||||
\vrule width1.0ex height1.0ex
|
||||
}\parfillskip 0pt}}
|
||||
|
||||
\newenvironment{proof}{{\textbf{Proof:} }}{\thmbox}
|
||||
\newenvironment{proofsketch}{{\textbf{Proof (Sketch):} }}{\thmbox}
|
||||
|
||||
\newcommand{\thmstep}[2]{
|
||||
\noindent\begin{tabular}{@{}l@{}l}
|
||||
\lefteqn{\mbox{#1}} &\\
|
||||
\mbox{ } & $\begin{array}{l}#2\end{array}$
|
||||
\end{tabular}
|
||||
}
|
||||
|
||||
\newcommand{\thmstepp}[2]{
|
||||
\noindent\begin{tabular}{lll}
|
||||
\lefteqn{\mbox{#1}} &\\
|
||||
\mbox{ } & #2
|
||||
\end{tabular}
|
||||
}
|
||||
|
||||
\newcommand{\ifthenthm}[2]{
|
||||
\noindent\begin{tabular}[t]{@{}l@{}l}
|
||||
If & \\
|
||||
& $\begin{array}[t]{l}#1\end{array}$ \\
|
||||
then & \\
|
||||
& $\begin{array}[t]{l}#2\end{array}$
|
||||
\end{tabular}
|
||||
}
|
||||
|
||||
% symbol abbreviations
|
||||
\newcommand{\stepsto}{\longmapsto}
|
||||
@@ -1,259 +0,0 @@
|
||||
% proof.sty (Proof Figure Macros)
|
||||
%
|
||||
% version 3.1 (for both LaTeX 2.09 and LaTeX 2e)
|
||||
% Nov 24, 2005
|
||||
% Copyright (C) 1990 -- 2005, Makoto Tatsuta (tatsuta@nii.ac.jp)
|
||||
%
|
||||
% This program is free software; you can redistribute it or modify
|
||||
% it under the terms of the GNU General Public License as published by
|
||||
% the Free Software Foundation; either versions 1, or (at your option)
|
||||
% any later version.
|
||||
%
|
||||
% This program is distributed in the hope that it will be useful
|
||||
% but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
% GNU General Public License for more details.
|
||||
%
|
||||
% Usage:
|
||||
% In \documentstyle, specify an optional style `proof', say,
|
||||
% \documentstyle[proof]{article}.
|
||||
%
|
||||
% The following macros are available:
|
||||
%
|
||||
% In all the following macros, all the arguments such as
|
||||
% <Lowers> and <Uppers> are processed in math mode.
|
||||
%
|
||||
% \infer<Lower><Uppers>
|
||||
% draws an inference.
|
||||
%
|
||||
% Use & in <Uppers> to delimit upper formulae.
|
||||
% <Uppers> consists more than 0 formulae.
|
||||
%
|
||||
% \infer returns \hbox{ ... } or \vbox{ ... } and
|
||||
% sets \@LeftOffset and \@RightOffset globally.
|
||||
%
|
||||
% \infer[<Label>]<Lower><Uppers>
|
||||
% draws an inference labeled with <Label>.
|
||||
%
|
||||
% \infer*<Lower><Uppers>
|
||||
% draws a many step deduction.
|
||||
%
|
||||
% \infer*[<Label>]<Lower><Uppers>
|
||||
% draws a many step deduction labeled with <Label>.
|
||||
%
|
||||
% \infer=<Lower><Uppers>
|
||||
% draws a double-ruled deduction.
|
||||
%
|
||||
% \infer=[<Label>]<Lower><Uppers>
|
||||
% draws a double-ruled deduction labeled with <Label>.
|
||||
%
|
||||
% \deduce<Lower><Uppers>
|
||||
% draws an inference without a rule.
|
||||
%
|
||||
% \deduce[<Proof>]<Lower><Uppers>
|
||||
% draws a many step deduction with a proof name.
|
||||
%
|
||||
% Example:
|
||||
% If you want to write
|
||||
% B C
|
||||
% -----
|
||||
% A D
|
||||
% ----------
|
||||
% E
|
||||
% use
|
||||
% \infer{E}{
|
||||
% A
|
||||
% &
|
||||
% \infer{D}{B & C}
|
||||
% }
|
||||
%
|
||||
|
||||
% Style Parameters
|
||||
|
||||
\newdimen\inferLineSkip \inferLineSkip=2pt
|
||||
\newdimen\inferLabelSkip \inferLabelSkip=5pt
|
||||
\def\inferTabSkip{\quad}
|
||||
|
||||
% Variables
|
||||
|
||||
\newdimen\@LeftOffset % global
|
||||
\newdimen\@RightOffset % global
|
||||
\newdimen\@SavedLeftOffset % safe from users
|
||||
|
||||
\newdimen\UpperWidth
|
||||
\newdimen\LowerWidth
|
||||
\newdimen\LowerHeight
|
||||
\newdimen\UpperLeftOffset
|
||||
\newdimen\UpperRightOffset
|
||||
\newdimen\UpperCenter
|
||||
\newdimen\LowerCenter
|
||||
\newdimen\UpperAdjust
|
||||
\newdimen\RuleAdjust
|
||||
\newdimen\LowerAdjust
|
||||
\newdimen\RuleWidth
|
||||
\newdimen\HLabelAdjust
|
||||
\newdimen\VLabelAdjust
|
||||
\newdimen\WidthAdjust
|
||||
|
||||
\newbox\@UpperPart
|
||||
\newbox\@LowerPart
|
||||
\newbox\@LabelPart
|
||||
\newbox\ResultBox
|
||||
|
||||
% Flags
|
||||
|
||||
\newif\if@inferRule % whether \@infer draws a rule.
|
||||
\newif\if@DoubleRule % whether \@infer draws doulbe rules.
|
||||
\newif\if@ReturnLeftOffset % whether \@infer returns \@LeftOffset.
|
||||
|
||||
% Special Fonts
|
||||
|
||||
\def\DeduceSym{\vtop{\baselineskip4\p@ \lineskiplimit\z@
|
||||
\vbox{\hbox{.}\hbox{.}\hbox{.}}\hbox{.}}}
|
||||
|
||||
% Macros
|
||||
|
||||
% Renaming @ifnextchar and @ifnch of LaTeX2e to @IFnextchar and @IFnch.
|
||||
|
||||
\def\@IFnextchar#1#2#3{%
|
||||
\let\reserved@e=#1\def\reserved@a{#2}\def\reserved@b{#3}\futurelet
|
||||
\reserved@c\@IFnch}
|
||||
\def\@IFnch{\ifx \reserved@c \@sptoken \let\reserved@d\@xifnch
|
||||
\else \ifx \reserved@c \reserved@e\let\reserved@d\reserved@a\else
|
||||
\let\reserved@d\reserved@b\fi
|
||||
\fi \reserved@d}
|
||||
|
||||
\def\@ifEmpty#1#2#3{\def\@tempa{\@empty}\def\@tempb{#1}\relax
|
||||
\ifx \@tempa \@tempb #2\else #3\fi }
|
||||
|
||||
\def\infer{\@IFnextchar *{\@inferSteps}{\relax
|
||||
\@IFnextchar ={\@inferDoubleRule}{\@inferOneStep}}}
|
||||
|
||||
\def\@inferOneStep{\@inferRuletrue \@DoubleRulefalse
|
||||
\@IFnextchar [{\@infer}{\@infer[\@empty]}}
|
||||
|
||||
\def\@inferDoubleRule={\@inferRuletrue \@DoubleRuletrue
|
||||
\@IFnextchar [{\@infer}{\@infer[\@empty]}}
|
||||
|
||||
\def\@inferSteps*{\@IFnextchar [{\@@inferSteps}{\@@inferSteps[\@empty]}}
|
||||
|
||||
\def\@@inferSteps[#1]{\@deduce{#1}[\DeduceSym]}
|
||||
|
||||
\def\deduce{\@IFnextchar [{\@deduce{\@empty}}
|
||||
{\@inferRulefalse \@infer[\@empty]}}
|
||||
|
||||
% \@deduce<Proof Label>[<Proof>]<Lower><Uppers>
|
||||
|
||||
\def\@deduce#1[#2]#3#4{\@inferRulefalse
|
||||
\@infer[\@empty]{#3}{\@infer[{#1}]{#2}{#4}}}
|
||||
|
||||
% \@infer[<Label>]<Lower><Uppers>
|
||||
% If \@inferRuletrue, it draws a rule and <Label> is right to
|
||||
% a rule. In this case, if \@DoubleRuletrue, it draws
|
||||
% double rules.
|
||||
%
|
||||
% Otherwise, draws no rule and <Label> is right to <Lower>.
|
||||
|
||||
\def\@infer[#1]#2#3{\relax
|
||||
% Get parameters
|
||||
\if@ReturnLeftOffset \else \@SavedLeftOffset=\@LeftOffset \fi
|
||||
\setbox\@LabelPart=\hbox{$#1$}\relax
|
||||
\setbox\@LowerPart=\hbox{$#2$}\relax
|
||||
%
|
||||
\global\@LeftOffset=0pt
|
||||
\setbox\@UpperPart=\vbox{\tabskip=0pt \halign{\relax
|
||||
\global\@RightOffset=0pt \@ReturnLeftOffsettrue $##$&&
|
||||
\inferTabSkip
|
||||
\global\@RightOffset=0pt \@ReturnLeftOffsetfalse $##$\cr
|
||||
#3\cr}}\relax
|
||||
\UpperLeftOffset=\@LeftOffset
|
||||
\UpperRightOffset=\@RightOffset
|
||||
% Calculate Adjustments
|
||||
\LowerWidth=\wd\@LowerPart
|
||||
\LowerHeight=\ht\@LowerPart
|
||||
\LowerCenter=0.5\LowerWidth
|
||||
%
|
||||
\UpperWidth=\wd\@UpperPart \advance\UpperWidth by -\UpperLeftOffset
|
||||
\advance\UpperWidth by -\UpperRightOffset
|
||||
\UpperCenter=\UpperLeftOffset
|
||||
\advance\UpperCenter by 0.5\UpperWidth
|
||||
%
|
||||
\ifdim \UpperWidth > \LowerWidth
|
||||
% \UpperCenter > \LowerCenter
|
||||
\UpperAdjust=0pt
|
||||
\RuleAdjust=\UpperLeftOffset
|
||||
\LowerAdjust=\UpperCenter \advance\LowerAdjust by -\LowerCenter
|
||||
\RuleWidth=\UpperWidth
|
||||
\global\@LeftOffset=\LowerAdjust
|
||||
%
|
||||
\else % \UpperWidth <= \LowerWidth
|
||||
\ifdim \UpperCenter > \LowerCenter
|
||||
%
|
||||
\UpperAdjust=0pt
|
||||
\RuleAdjust=\UpperCenter \advance\RuleAdjust by -\LowerCenter
|
||||
\LowerAdjust=\RuleAdjust
|
||||
\RuleWidth=\LowerWidth
|
||||
\global\@LeftOffset=\LowerAdjust
|
||||
%
|
||||
\else % \UpperWidth <= \LowerWidth
|
||||
% \UpperCenter <= \LowerCenter
|
||||
%
|
||||
\UpperAdjust=\LowerCenter \advance\UpperAdjust by -\UpperCenter
|
||||
\RuleAdjust=0pt
|
||||
\LowerAdjust=0pt
|
||||
\RuleWidth=\LowerWidth
|
||||
\global\@LeftOffset=0pt
|
||||
%
|
||||
\fi\fi
|
||||
% Make a box
|
||||
\if@inferRule
|
||||
%
|
||||
\setbox\ResultBox=\vbox{
|
||||
\moveright \UpperAdjust \box\@UpperPart
|
||||
\nointerlineskip \kern\inferLineSkip
|
||||
\if@DoubleRule
|
||||
\moveright \RuleAdjust \vbox{\hrule width\RuleWidth
|
||||
\kern 1pt\hrule width\RuleWidth}\relax
|
||||
\else
|
||||
\moveright \RuleAdjust \vbox{\hrule width\RuleWidth}\relax
|
||||
\fi
|
||||
\nointerlineskip \kern\inferLineSkip
|
||||
\moveright \LowerAdjust \box\@LowerPart }\relax
|
||||
%
|
||||
\@ifEmpty{#1}{}{\relax
|
||||
%
|
||||
\HLabelAdjust=\wd\ResultBox \advance\HLabelAdjust by -\RuleAdjust
|
||||
\advance\HLabelAdjust by -\RuleWidth
|
||||
\WidthAdjust=\HLabelAdjust
|
||||
\advance\WidthAdjust by -\inferLabelSkip
|
||||
\advance\WidthAdjust by -\wd\@LabelPart
|
||||
\ifdim \WidthAdjust < 0pt \WidthAdjust=0pt \fi
|
||||
%
|
||||
\VLabelAdjust=\dp\@LabelPart
|
||||
\advance\VLabelAdjust by -\ht\@LabelPart
|
||||
\VLabelAdjust=0.5\VLabelAdjust \advance\VLabelAdjust by \LowerHeight
|
||||
\advance\VLabelAdjust by \inferLineSkip
|
||||
%
|
||||
\setbox\ResultBox=\hbox{\box\ResultBox
|
||||
\kern -\HLabelAdjust \kern\inferLabelSkip
|
||||
\raise\VLabelAdjust \box\@LabelPart \kern\WidthAdjust}\relax
|
||||
%
|
||||
}\relax % end @ifEmpty
|
||||
%
|
||||
\else % \@inferRulefalse
|
||||
%
|
||||
\setbox\ResultBox=\vbox{
|
||||
\moveright \UpperAdjust \box\@UpperPart
|
||||
\nointerlineskip \kern\inferLineSkip
|
||||
\moveright \LowerAdjust \hbox{\unhbox\@LowerPart
|
||||
\@ifEmpty{#1}{}{\relax
|
||||
\kern\inferLabelSkip \unhbox\@LabelPart}}}\relax
|
||||
\fi
|
||||
%
|
||||
\global\@RightOffset=\wd\ResultBox
|
||||
\global\advance\@RightOffset by -\@LeftOffset
|
||||
\global\advance\@RightOffset by -\LowerWidth
|
||||
\if@ReturnLeftOffset \else \global\@LeftOffset=\@SavedLeftOffset \fi
|
||||
%
|
||||
\box\ResultBox
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
@@ -1,347 +0,0 @@
|
||||
\documentclass[fleqn, draft]{article}
|
||||
\usepackage{proof, amsmath, amssymb, ifthen}
|
||||
\input{macros.tex}
|
||||
|
||||
% types
|
||||
\newcommand{\Arrow}[3][-]{#2 \overset{#1}{\rightarrow} #3}
|
||||
\newcommand{\Bool}{\mathbf{bool}}
|
||||
\newcommand{\Bottom}{\mathbf{bottom}}
|
||||
\newcommand{\Dynamic}{\mathbf{dynamic}}
|
||||
\newcommand{\Null}{\mathbf{Null}}
|
||||
\newcommand{\Num}{\mathbf{num}}
|
||||
\newcommand{\Object}{\mathbf{Object}}
|
||||
\newcommand{\TApp}[2]{#1\mathrm{<}#2\mathrm{>}}
|
||||
\newcommand{\Type}{\mathbf{Type}}
|
||||
\newcommand{\Weak}[1]{\mathbf{\{#1\}}}
|
||||
\newcommand{\Sig}{\mathit{Sig}}
|
||||
\newcommand{\Boxed}[1]{\langle #1 \rangle}
|
||||
|
||||
% expressions
|
||||
\newcommand{\eassign}[2]{#1 = #2}
|
||||
\newcommand{\eas}[2]{#1\ \mathbf{as}\ #2}
|
||||
\newcommand{\ebox}[2]{\langle#1\rangle_{#2}}
|
||||
\newcommand{\ecall}[2]{#1(#2)}
|
||||
\newcommand{\echeck}[2]{\kwop{check}(#1, #2)}
|
||||
\newcommand{\edcall}[2]{\kwop{dcall}(#1, #2)}
|
||||
\newcommand{\edload}[2]{\kwop{dload}(#1, #2)}
|
||||
\newcommand{\edo}[1]{\kwdo\{\,#1\,\}}
|
||||
\newcommand{\eff}{\mathrm{ff}}
|
||||
\newcommand{\eis}[2]{#1\ \mathbf{is}\ #2}
|
||||
\newcommand{\elabel}[1][l]{\mathit{l}}
|
||||
\newcommand{\elambda}[3]{(#1):#2 \Rightarrow #3}
|
||||
\newcommand{\eload}[2]{#1.#2}
|
||||
\newcommand{\enew}[3]{\mathbf{new}\,\TApp{#1}{#2}(#3)}
|
||||
\newcommand{\enull}{\mathbf{null}}
|
||||
\newcommand{\eobject}[2]{\kwobject_{#1} \{#2\}}
|
||||
\newcommand{\eprimapp}[2]{\ecall{#1}{#2}}
|
||||
\newcommand{\eprim}{\kwop{op}}
|
||||
\newcommand{\esend}[3]{\ecall{\eload{#1}{#2}}{#3}}
|
||||
\newcommand{\eset}[3]{\eassign{#1.#2}{#3}}
|
||||
\newcommand{\esuper}{\mathbf{super}}
|
||||
\newcommand{\ethis}{\mathbf{this}}
|
||||
\newcommand{\ethrow}{\mathbf{throw}}
|
||||
\newcommand{\ett}{\mathrm{tt}}
|
||||
\newcommand{\eunbox}[1]{{*#1}}
|
||||
|
||||
% keywords
|
||||
\newcommand{\kwclass}{\kw{class}}
|
||||
\newcommand{\kwdo}{\kw{do}}
|
||||
\newcommand{\kwelse}{\kw{else}}
|
||||
\newcommand{\kwextends}{\kw{extends}}
|
||||
\newcommand{\kwfun}{\kw{fun}}
|
||||
\newcommand{\kwif}{\kw{if}}
|
||||
\newcommand{\kwin}{\kw{in}}
|
||||
\newcommand{\kwlet}{\kw{let}}
|
||||
\newcommand{\kwobject}{\kw{object}}
|
||||
\newcommand{\kwreturn}{\kw{return}}
|
||||
\newcommand{\kwthen}{\kw{then}}
|
||||
\newcommand{\kwvar}{\kw{var}}
|
||||
|
||||
% declarations
|
||||
\newcommand{\dclass}[3]{\kwclass\ #1\ \kwextends\ #2\ \{#3\}}
|
||||
\newcommand{\dfun}[4]{#2(#3):#1 = #4}
|
||||
\newcommand{\dvar}[2]{\kwvar\ #1\ =\ #2}
|
||||
|
||||
|
||||
\newcommand{\fieldDecl}[2]{\kwvar\ #1 : #2}
|
||||
\newcommand{\methodDecl}[3]{\kwfun\ #1 : \iftrans{#2 \triangleleft} #3}
|
||||
|
||||
% statements
|
||||
\newcommand{\sifthenelse}[3]{\kwif\ (#1)\ \kwthen\ #2\ \kwelse\ #3}
|
||||
\newcommand{\sreturn}[1]{\kwreturn\ #1}
|
||||
|
||||
% programs
|
||||
\newcommand{\program}[2]{\kwlet\ #1\ \kwin\ #2}
|
||||
|
||||
% relational operators
|
||||
\newcommand{\sub}{\mathbin{<:}}
|
||||
|
||||
% utilities
|
||||
\newcommand{\many}[1]{\overrightarrow{#1}}
|
||||
\newcommand{\alt}{\ \mathop{|}\ }
|
||||
\newcommand{\opt}[1]{[#1]}
|
||||
\newcommand{\bind}[3]{#1 \Leftarrow\, #2\ \kw{in}\ #3}
|
||||
|
||||
\newcommand{\note}[1]{\textbf{NOTE:} \textit{#1}}
|
||||
|
||||
%dynamic semantics
|
||||
\newcommand{\TypeError}{\mathbf{Error}}
|
||||
|
||||
% inference rules
|
||||
\newcommand{\infrulem}[3][]{
|
||||
\begin{array}{c@{\ }c}
|
||||
\begin{array}{cccc}
|
||||
#2 \vspace{-2mm}
|
||||
\end{array} \\
|
||||
\hrulefill & #1 \\
|
||||
\begin{array}{l}
|
||||
#3
|
||||
\end{array}
|
||||
\end{array}
|
||||
}
|
||||
|
||||
\newcommand{\axiomm}[2][]{
|
||||
\begin{array}{cc}
|
||||
\hrulefill & #1 \\
|
||||
\begin{array}{c}
|
||||
#2
|
||||
\end{array}
|
||||
\end{array}
|
||||
}
|
||||
|
||||
\newcommand{\infrule}[3][]{
|
||||
\[
|
||||
\infrulem[#1]{#2}{#3}
|
||||
\]
|
||||
}
|
||||
|
||||
\newcommand{\axiom}[2][]{
|
||||
\[
|
||||
\axiomm[#1]{#2}
|
||||
\]
|
||||
}
|
||||
|
||||
% judgements and relations
|
||||
\newboolean{show_translation}
|
||||
\setboolean{show_translation}{false}
|
||||
\newcommand{\iftrans}[1]{\ifthenelse{\boolean{show_translation}}{#1}{}}
|
||||
\newcommand{\ifnottrans}[1]{\ifthenelse{\boolean{show_translation}}{#1}}
|
||||
|
||||
\newcommand{\blockOk}[4]{#1 \vdash #2 \col #3\iftrans{\, \Uparrow\, #4}}
|
||||
\newcommand{\declOk}[5][]{#2 \vdash_{#1} #3 \, \Uparrow\, \iftrans{#4\, :\,} #5}
|
||||
\newcommand{\extends}[4][:]{#2[#3\ #1\ #4]}
|
||||
\newcommand{\fieldLookup}[4]{#1 \vdash #2.#3\, \leadsto_f\, #4}
|
||||
\newcommand{\methodLookup}[5]{#1 \vdash #2.#3\, \leadsto_m\, \iftrans{#4 \triangleleft} #5}
|
||||
\newcommand{\fieldAbsent}[3]{#1 \vdash #3 \notin #2}
|
||||
\newcommand{\methodAbsent}[3]{#1 \vdash #3 \notin #2}
|
||||
\newcommand{\hastype}[3]{#1 \vdash #2 \, : \, #3}
|
||||
\newcommand{\stmtOk}[5]{#1 \vdash #2 \, : \, #3\, \Uparrow \iftrans{#4\, :\,} #5}
|
||||
\newcommand{\subst}[2]{[#1/#2]}
|
||||
\newcommand{\subtypeOfOpt}[5][?]{#2 \vdash\ #3 \sub^{#1} #4\, \Uparrow\, #5}
|
||||
\newcommand{\subtypeOf}[4][]{#2 \vdash\ #3 \sub^{#1} #4}
|
||||
\newcommand{\yieldsOk}[5]{#1 \vdash #2 \, : \, #3\, \Uparrow\, \iftrans{#4\, :\,} #5}
|
||||
\newcommand{\programOk}[3]{#1 \vdash #2\iftrans{\, \Uparrow\, #3}}
|
||||
\newcommand{\ok}[2]{#1 \vdash #2\, \mbox{\textbf{ok}}}
|
||||
\newcommand{\overrideOk}[4]{#1 \vdash #2\,\kwextends\, #3 \Leftarrow\, #4}
|
||||
|
||||
\newcommand{\down}[1]{\ensuremath{\downharpoonleft\!\!#1\!\!\downharpoonright}}
|
||||
\newcommand{\up}[1]{\ensuremath{\upharpoonleft\!\!#1\!\!\upharpoonright}}
|
||||
\newcommand{\sigof}[1]{\mathit{sigof}(#1)}
|
||||
\newcommand{\typeof}[1]{\mathit{typeof}(#1)}
|
||||
\newcommand{\sstext}[2]{\ifthenelse{\boolean{show_translation}}{#2}{#1}}
|
||||
|
||||
\newcommand{\evaluatesTo}[5][]{\{#2\alt #3\} \stepsto_{#1} \{#4 \alt #5\}}
|
||||
|
||||
|
||||
\title{Dart strong mode definition}
|
||||
|
||||
\begin{document}
|
||||
|
||||
\textbf{\large PRELIMINARY DRAFT}
|
||||
|
||||
\section*{Syntax}
|
||||
|
||||
|
||||
Terms and types. Note that we allow types to be optional in certain positions
|
||||
(currently function arguments and return types, and on variable declarations).
|
||||
Implicitly these are either inferred or filled in with dynamic.
|
||||
|
||||
There are explicit terms for dynamic calls and loads, and for dynamic type
|
||||
checks.
|
||||
|
||||
Fields can only be read or set within a method via a reference to this, so no
|
||||
dynamic set operation is required (essentially dynamic set becomes a dynamic
|
||||
call to a setter). This just simplifies the presentation a bit. Methods may be
|
||||
externally loaded from the object (either to call them, or to pass them as
|
||||
closurized functions).
|
||||
|
||||
\[
|
||||
\begin{array}{lcl}
|
||||
\text{Type identifiers} & ::= & C, G, T, S, \ldots \\
|
||||
%
|
||||
\text{Arrow kind ($k$)} & ::= & +, -\\
|
||||
%
|
||||
\text{Types $\tau, \sigma$} & ::= &
|
||||
T \alt \Dynamic \alt \Object \alt \Null \alt \Type \alt \Num \\ &&
|
||||
\alt \Bool
|
||||
\alt \Arrow[k]{\many{\tau}}{\sigma} \alt \TApp{C}{\many{\tau}} \\
|
||||
%
|
||||
\text{Ground types $\tau, \sigma$} & ::= &
|
||||
\Dynamic \alt \Object \alt \Null \alt \Type \alt \Num \\ &&
|
||||
\alt \Bool
|
||||
\alt \Arrow[+]{\many{\Dynamic}}{\Dynamic} \alt \TApp{C}{\many{\Dynamic}} \\
|
||||
%
|
||||
\text{Optional type ($[\tau]$)} & ::= & \_ \alt \tau \\
|
||||
%
|
||||
\text{Term identifiers} & ::= & a, b, x, y, m, n, \ldots \\
|
||||
%
|
||||
\text{Primops ($\phi$)} & ::= & \mathrm{+}, \mathrm{-} \ldots \mathrm{||} \ldots \\
|
||||
%
|
||||
\text{Expressions $e$} & ::= &
|
||||
x \alt i \alt \ett \alt \eff \alt \enull \alt \ethis \\&&
|
||||
\alt \elambda{\many{x:\opt{\tau}}}{\opt{\sigma}}{s}
|
||||
\alt \enew{C}{\many{\tau}}{} \\&&
|
||||
\alt \eprimapp{\eprim}{\many{e}} \alt \ecall{e}{\many{e}} \\&&
|
||||
\alt \eload{e}{m} \alt \eload{\ethis}{x} \\&&
|
||||
\alt \eassign{x}{e} \alt \eset{\ethis}{x}{e} \\&&
|
||||
\alt \ethrow \alt \eas{e}{\tau} \alt \eis{e}{\tau} \\
|
||||
%
|
||||
\text{Declaration ($\mathit{vd}$)} & ::= &
|
||||
\dvar{x:\opt{\tau}}{e} \alt \dfun{\tau}{f}{\many{x:\tau}}{s} \\
|
||||
%
|
||||
\text{Statements ($s$)} & ::= & \mathit{vd} \alt e \alt \sifthenelse{e}{s_1}{s_2}
|
||||
\alt \sreturn{e} \alt s;s \\
|
||||
%
|
||||
\text{Class decl ($\mathit{cd}$)} & ::= & \dclass{\TApp{C}{\many{T}}}{\TApp{G}{\many{\tau}}}{\many{\mathit{vd}}} \\
|
||||
%
|
||||
\text{Toplevel decl ($\mathit{td}$)} & ::= & \mathit{vd} \alt \mathit{cd}\\
|
||||
%
|
||||
\text{Program ($P$)} & ::= & \program{\many{\mathit{td}}}{s}
|
||||
\end{array}
|
||||
\]
|
||||
|
||||
|
||||
Type contexts map type variables to their bounds.
|
||||
|
||||
Class signatures describe the methods and fields in an object, along with the
|
||||
super class of the class. There are no static methods or fields.
|
||||
|
||||
The class hierararchy records the classes with their signatures.
|
||||
|
||||
The term context maps term variables to their types. I also abuse notation and
|
||||
allow for the attachment of an optional type to term contexts as follows:
|
||||
$\Gamma_\sigma$ refers to a term context within the body of a method whose class
|
||||
type is $\sigma$.
|
||||
|
||||
\[
|
||||
\begin{array}{lcl}
|
||||
\text{Type context ($\Delta$)} & ::= & \epsilon \alt \Delta, T \sub \tau \\
|
||||
\text{Class element ($\mathit{ce}$)} & ::= &
|
||||
\fieldDecl{x}{\tau} \alt \methodDecl{f}{\tau}{\sigma} \\
|
||||
\text{Class signature ($\Sig$)} & ::= &
|
||||
\dclass{\TApp{C}{\many{T}}}{\TApp{G}{\many{\tau}}}{\many{\mathit{ce}}} \\
|
||||
\text{Class hierarchy ($\Phi$)} & ::= & \epsilon \alt \Phi, C\ :\ \Sig \\
|
||||
\text{Term context ($\Gamma$)} & ::= & \epsilon \alt \Gamma, x\ :\ \tau
|
||||
\end{array}
|
||||
\]
|
||||
|
||||
|
||||
\section*{Subtyping}
|
||||
|
||||
\subsection*{Variant Subtyping}
|
||||
|
||||
We include a special kind of covariant function space to model certain dart
|
||||
idioms. An arrow type decorated with a positive variance annotation ($+$)
|
||||
treats $\Dynamic$ in its argument list covariantly: or equivalently, it treats
|
||||
$\Dynamic$ as bottom. This variant subtyping relation captures this special
|
||||
treatment of dynamic.
|
||||
|
||||
\axiom{\subtypeOf[+]{\Phi, \Delta}{\Dynamic}{\tau}}
|
||||
|
||||
\infrule{\subtypeOf{\Phi, \Delta}{\sigma}{\tau} \quad \sigma \neq \Dynamic}
|
||||
{\subtypeOf[+]{\Phi, \Delta}{\sigma}{\tau}}
|
||||
|
||||
\infrule{\subtypeOf{\Phi, \Delta}{\sigma}{\tau}}
|
||||
{\subtypeOf[-]{\Phi, \Delta}{\sigma}{\tau}}
|
||||
|
||||
\subsection*{Invariant Subtyping}
|
||||
|
||||
Regular subtyping is defined in a fairly standard way, except that generics are
|
||||
uniformly covariant, and that function argument types fall into the variant
|
||||
subtyping relation defined above.
|
||||
|
||||
\axiom{\subtypeOf{\Phi, \Delta}{\tau}{\Dynamic}}
|
||||
|
||||
\axiom{\subtypeOf{\Phi, \Delta}{\tau}{\Object}}
|
||||
|
||||
\axiom{\subtypeOf{\Phi, \Delta}{\Bottom}{\tau}}
|
||||
|
||||
\axiom{\subtypeOf{\Phi, \Delta}{\tau}{\tau}}
|
||||
|
||||
\infrule{(S\, :\, \sigma) \in \Delta \quad
|
||||
\subtypeOf{\Phi, \Delta}{\sigma}{\tau}}
|
||||
{\subtypeOf{\Phi, \Delta}{S}{\tau}}
|
||||
|
||||
\infrule{\subtypeOf[k_1]{\Phi, \Delta}{\sigma_i}{\tau_i} \quad i \in 0, \ldots, n \quad\quad
|
||||
\subtypeOf{\Phi, \Delta}{\tau_r}{\sigma_r} \\
|
||||
\quad (k_0 = \mbox{-}) \lor (k_1 = \mbox{+})
|
||||
}
|
||||
{\subtypeOf{\Phi, \Delta}
|
||||
{\Arrow[k_0]{\tau_0, \ldots, \tau_n}{\tau_r}}
|
||||
{\Arrow[k_1]{\sigma_0, \ldots, \sigma_n}{\sigma_r}}}
|
||||
|
||||
\infrule{\subtypeOf{\Phi, \Delta}{\tau_i}{\sigma_i} & i \in 0, \ldots, n}
|
||||
{\subtypeOf{\Phi, \Delta}
|
||||
{\TApp{C}{\tau_0, \ldots, \tau_n}}
|
||||
{\TApp{C}{\sigma_0, \ldots, \sigma_n}}}
|
||||
|
||||
\infrule{(C : \dclass{\TApp{C}{T_0,\ldots,T_n}}{\TApp{C'}{\upsilon_0, \ldots, \upsilon_k}}{\ldots}) \in \Phi \\
|
||||
\subtypeOf{\Phi, \Delta}{\subst{\tau_0, \ldots, \tau_n}{T_0, \ldots, T_n}{\TApp{C'}{\upsilon_0, \ldots, \upsilon_k}}}{\TApp{G}{\sigma_0, \ldots, \sigma_m}}}
|
||||
{\subtypeOf{\Phi, \Delta}
|
||||
{\TApp{C}{\tau_0, \ldots, \tau_n}}
|
||||
{\TApp{G}{\sigma_0, \ldots, \sigma_m}}}
|
||||
|
||||
|
||||
|
||||
\section*{Typing}
|
||||
\input{static-semantics}
|
||||
|
||||
\pagebreak
|
||||
\section*{Elaboration}
|
||||
\setboolean{show_translation}{true}
|
||||
|
||||
Elaboration is a type driven translation which maps a source Dart term to a
|
||||
translated term which corresponds to the original term with additional dynamic
|
||||
type checks inserted to reify the static unsoundness as runtime type errors.
|
||||
For the translation, we extend the source language slightly as follows.
|
||||
\[
|
||||
\begin{array}{lcl}
|
||||
\text{Expressions $e$} & ::= & \ldots
|
||||
\alt \edcall{e}{\many{e}} \alt \edload{e}{m} \alt \echeck{e}{\tau}\\
|
||||
\end{array}
|
||||
\]
|
||||
|
||||
The expression language is extended with an explicitly checked dynamic call
|
||||
operation, and explicitly checked dynamic method load operation, and a runtime
|
||||
type test. Note that while a user level cast throws an exception on failure,
|
||||
the runtime type test term introduced here produces a hard type error which
|
||||
cannot be caught programmatically.
|
||||
|
||||
We also extend typing contexts slightly by adding an internal type to method signatures.
|
||||
\[
|
||||
\begin{array}{lcl}
|
||||
\text{Class element ($\mathit{ce}$)} & ::= &
|
||||
\fieldDecl{x}{\tau} \alt \methodDecl{f}{\tau}{\sigma} \\
|
||||
\end{array}
|
||||
\]
|
||||
A method signature of the form $\methodDecl{f}{\tau}{\sigma}$ describes a method
|
||||
whose public interface is described by $\sigma$, but which has an internal type
|
||||
$\tau$ which is a subtype of $\sigma$, but which is properly covariant in any
|
||||
type parameters. The elaboration introduces runtime type checks to mediate
|
||||
between the two types. This is discussed further in the translation of classes
|
||||
below.
|
||||
|
||||
\input{static-semantics}
|
||||
|
||||
|
||||
\end{document}
|
||||
Reference in New Issue
Block a user