Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Null-coalesce assign should not perform assign if not null #11931

Open
ncannasse opened this issue Jan 21, 2025 · 2 comments · May be fixed by #11963
Open

Null-coalesce assign should not perform assign if not null #11931

ncannasse opened this issue Jan 21, 2025 · 2 comments · May be fixed by #11963
Assignees
Milestone

Comments

@ncannasse
Copy link
Member

The following code:

class Test {
  static function foo(i) {
    var arr = [];
    for( x in 0...i ) {
	var e = arr[x] ??= [];
        trace(e);
    }      
  }
  static function main() {
    trace("Haxe is great!");
    foo(0);
  }
}

Produces the following result:

static foo(i) {
		let arr = [];
		let _g = 0;
		while(_g < i) {
			let x = _g++;
			console.log("Test.hx:6:",arr[x] = arr[x] != null ? arr[x] : []);
		}
}

I would expect instead it to be:

arr[x] != null ? arr[x] : arr[x] = []

So no assign is performed if not null.

@kLabz kLabz added this to the 4.3 Hotfix milestone Jan 21, 2025
@kLabz
Copy link
Contributor

kLabz commented Jan 21, 2025

??= implementation seems wrong indeed

The null-coalescing assignment operator ??= assigns the value of its right-hand operand to its left-hand operand only if the left-hand operand evaluates to null. The ??= operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-null.

fc68ea4

@Simn
Copy link
Member

Simn commented Jan 24, 2025

Note for the implementation: this should not array-read twice, so we need a temp var and turn it into { var tmp = arr[x]; tmp != null ? tmp : arr[x] = []; }.

This might make it worthwhile to have a distinct block-level case where it simply becomes if (arr[x] == null) arr[x] = [].

@RblSb RblSb linked a pull request Jan 31, 2025 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants