Skip to content

Commit

Permalink
Fix #1017: C# null-coalesce ?? operator + add tests for ?.
Browse files Browse the repository at this point in the history
  • Loading branch information
Tarmil committed Aug 29, 2018
1 parent e514045 commit d26a70c
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 3 deletions.
7 changes: 4 additions & 3 deletions src/compiler/WebSharper.Compiler/Translator.fs
Original file line number Diff line number Diff line change
Expand Up @@ -1439,9 +1439,10 @@ type DotNetToJavaScript private (comp: Compilation, ?inProgress) =
base.TransformBinary(a, b, c)

override this.TransformCoalesce(a, b, c) =
let trA = this.TransformExpression a
let trC = innerScope <| fun () -> this.TransformExpression c
Coalesce(trA, b, trC)
let aId = Id.New()
this.TransformLet(aId, a,
Conditional(Binary(Var aId, BinaryOperator.``===``, !~Null), c, Var aId)
)

override this.TransformWhile(a, b) =
let trA = this.TransformExpression a
Expand Down
49 changes: 49 additions & 0 deletions tests/WebSharper.CSharp.Tests/Syntax.cs
Original file line number Diff line number Diff line change
Expand Up @@ -487,6 +487,55 @@ public void Default()
Equal(default(string), null);
}

private class NullTest
{
int x;

public NullTest(int x)
{
this.x = x;
}

public int? X() => this.x;

public int? Increment() {
this.x++;
return this.x;
}
}

[Test]
public void NullConditionalAccess()
{
NullTest x = null;
Equal(x?.X(), null, "object null case");
x = new NullTest(42);
Equal(x?.X(), 42, "object non null case");
Equal(x?.Increment(), 43, "check side effect 1");
Equal(x?.Increment(), 44, "check side effect 2");

int? y = null;
Equal(y?.ToString(), null, "Nullable null case");
y = 23;
Equal(y?.ToString(), "23", "Nullable non-null case");
}

[Test]
public void NullCoalesce()
{
NullTest x = null;
Equal((x ?? new NullTest(42)).X(), 42, "object null case");
x = new NullTest(53);
Equal((x ?? new NullTest(42)).X(), 53, "object non-null case");
Equal(x.Increment() ?? 12, 54, "check side effect 1");
Equal(x.Increment() ?? 35, 55, "check side effect 2");

int? y = null;
Equal(y ?? 67, 67, "Nullable null case");
y = 23;
Equal(y ?? 67, 23, "Nullable non-null case");
}

public int this[int i] => i * i;

public string this[string x] { get { return x + "!"; } }
Expand Down

0 comments on commit d26a70c

Please sign in to comment.