RealyUniqueName / Safety

Null safety for Haxe
MIT License
54 stars 5 forks source link

Safety: Cannot access "..." of a nullable value inside lambdas #8

Closed restorer closed 5 years ago

restorer commented 5 years ago
class Bug3 {
    public function bug() : Void {
        var s : Null<String> = ((Math.random() > 0.5) ? "A" : null);

        if (s != null) {
            // Safety: Cannot access "length" of a nullable value.
            function cb() : Int { return s.length; }
        }
    }
}

See https://github.com/restorer/haxe-safety-bugs/blob/master/safetybugs/Main.hx#L60 for working example.

restorer commented 5 years ago

This is for Haxe 4.0.0-preview.5 and Safety from master.

RealyUniqueName commented 5 years ago

This is an intended behavior. Because while created in a safe area the closure could be invoked outside of the body of that if. Leaving this open to not forget to add a test case.

restorer commented 5 years ago

That makes sense, but kotlin solve that somehow in some cases. Eg.

fun main(args: Array<String>) {
    // s is var (not val)
    var s : String? = if (java.util.Random().nextFloat() > 0.5) "AB" else null
    val items = listOf(1, 2, 3, 4, 5)

    if (s != null) {
    println(items.map { it * s.length })
    }
}

Haxe with Safety:

public function bug() : Void {
    var s : Null<String> = ((Math.random() > 0.5) ? "AB" : null);
    var l = [1, 2, 3, 4, 5];

    if (s != null) {
        // Safety: Cannot access "length" of a nullable value.
        trace(l.map(function (v) { return v * s.length; }));
    }
}
RealyUniqueName commented 5 years ago

fixed in https://github.com/HaxeFoundation/haxe/pull/7717