dart-lang / dart-lang/language
Local shadow causes 'cannot be referenced before it is declared'
- Dominant language
- TeX
- Stars
- 2.9k
- Forks
- 239
- Avg merge
- 2d 18h
- Merged PRs (30d)
- 14
Description
```dart
class C {
final int f;
C(this.f);
void m() {
print(f);
final f = this.f;
}
}
```
```
main.dart:10:11: Error: Local variable 'f' can't be referenced before it is declared.
print(f);
^
main.dart:11:11: Context: This is the declaration of the variable 'f'.
final f = this.f;
^
```
In this example, `f` is both a local and instance variable. I see this pattern used a lot to perform type checks on the instance variable. While I understand the error message and its value, I feel like it doesn't make much sense when the local just shadows the instance variable of the same name.
The following code produces roughly the same error. I feel like it should also work, but it's a little weaker of an argument
```dart
void f(int p) {
print(p);
final p = 1;
}
```
Contributor guide
Research direction
Start with the two Dart examples in the issue and review the language specification’s rules for local declarations, lexical scope, and shadowing. Compare the proposed behavior for an instance field and a parameter, then identify the compatibility and analysis consequences. Done means the language-design question has a decided resolution and the specification and relevant tests reflect it.
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
- 30/100