HaxeFoundation / HaxeFoundation/haxe

Null safety: Cannot use "this" until all instance fields are initialized.

Open
#10,584 3 comments 0 reactions 0 assignees View on GitHub
Dominant language
Haxe
Stars
6.9k
Forks
715
Avg merge
2d 2h
Merged PRs (30d)
11

Description

**Environment**
macos monterey 12.1
haxe 4.2.4

When null-safety is enabled, it is not possible to get rid of this error even if the offending constructor is annotated with the metadata @:nullSafety(Off). While passing the reference of an object under construction is not generally recommended, there are cases when this isn’t avoidable and is absolutely safe as well.

The error can be reproduced by the following code compiled with the option --macro nullSafety("foo")

```haxe
package foo;

class Main {
final a1: A1;
final a2: A2;

@:nullSafety(Off)
public function new() {
a1 = new A1(this);
a2 = new A2(this);
}
public static function main() {}
}
class A1 {
public function new(m: Main) {}
}
class A2 {
public function new(m: Main) {}
}

```
The reported error is `foo/Main.hx:9: characters 17-21 : Null safety: Cannot use "this" until all instance fields are initialized`.

Curiously enough, if the code is modified in the manner below, the compiler stops to complain.

```haxe
class Main {
final a1: A1;
final a2: A2;

@:nullSafety(Off)
public function new() {
a1 = null; a2 = null;
a1 = new A1(this);
a2 = new A2(this);
}

// ...
```

Contributor guide

Open the contributing guide

Research direction

Reproduce the report in foo/Main.hx using --macro nullSafety("foo") and the shown constructor, then compare it with the version that initializes a1 and a2 to null first. Trace the null-safety handling for @:nullSafety(Off) during constructor field initialization. Done means the annotated constructor no longer reports the shown error while the existing reproduction remains covered by a regression test.

Written by the indexing model from the issue text.

Assessment

Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.