dart-lang / dart-lang/language
Consider allowing static constant fields and top level constants to be considered stable and promotable
- Dominant language
- TeX
- Stars
- 2.9k
- Forks
- 239
- Avg merge
- 2d 18h
- Merged PRs (30d)
- 14
Description
(Based on https://github.com/dart-lang/sdk/issues/53437#issuecomment-1708434129)
Currently, field promotion (#2020) only considers an expression of the form `target._fieldName` to be stable (and thus promotable) if `_fieldName` represents a promotable field and `target` is one of the following:
- `this` (includes implicit uses of `this`, so bare `_fieldName` is considered promotable inside an instance method of a class)
- `super`
- A local variable that isn't modified or write captured during the time period covered by the potential promotion.
- An expression of the form `target._fieldName` that's considered stable.
If, in addition, we considered a reference to a static constant field or a constant top level variable to be stable, then that would permit additional promotions, for example this code snippet (based on the code snippet in https://github.com/dart-lang/sdk/issues/53437):
```dart
enum E {
e1, e2;
final int? _x = 42;
}
main() {
if (E.e1._x != null) {
E.e1._x.isEven; // Ok, `E.e1._x` is promoted to non-null
}
}
```
If we do this, we should probably also consider static constant fields and constant top level variables to be promotable, to preserve the sensible invariant that anything that's stable is promotable (in other words, stability is a stronger notion than promotability). So this would also be allowed:
```dart
const int? i = ...;
main() {
if (i != null) {
i.isEven; // OK, `i` is promoted to non-null
}
```
Note that in contrast to https://github.com/dart-lang/language/issues/3325, there would be no harm in allowing for this stability and promotability to apply to libraries other than the one declaring the constant, because it's already a breaking change to convert a constant declaration into a non-constant one.
Contributor guide
Research direction
Start with the stability and promotability rules described in this issue, then read the linked Dart SDK issue and language issue #3325 for related constraints. Define the specification change for static constant fields and top-level constants, including cross-library behavior, and confirm that the examples are accepted while the stability/promotability invariant is preserved.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- dart
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100