Skip to content
This repository has been archived by the owner on Aug 24, 2022. It is now read-only.

Elvis operator translated incorrectly in some cases #1015

Open
iskiselev opened this issue Jul 27, 2016 · 3 comments
Open

Elvis operator translated incorrectly in some cases #1015

iskiselev opened this issue Jul 27, 2016 · 3 comments

Comments

@iskiselev
Copy link
Member

Elvis operator translated incorrectly in some cases. Here is test case:

//@useroslyn
using System;

public static class Program
{
    public static void Main()
    {
        WriteNullableTestStruct(new TestStructHolder(new TestStruct(10)));
        WriteNullableTestStruct(new TestStructHolder(null));
    }

    public static void WriteNullableTestStruct(TestStructHolder holder)
    {
        Console.WriteLine(holder.TestStruct?.Field);
    }
}

public class TestStructHolder
{
    public readonly TestStruct? TestStruct;

    public TestStructHolder(TestStruct? testStruct)
    {
        TestStruct = testStruct;
    }
}

public struct TestStruct
{
    public int Field { get; set; }

    public TestStruct(int fieldValue)
    {
        Field = fieldValue;
    }
}

Resiult:

  Expected: "10"
  But was:  "0"

Translation:

  function Program_WriteNullableTestStruct (holder) {
    $T02().WriteLine((
        (holder.TestStruct !== null)
           ? JSIL.Nullable_ValueOrDefault(null, new ($T01())()).TestStruct$Field$value
           : null)
    );
  }; 
@kg
Copy link
Member

kg commented Jul 27, 2016

What would the correct translation be, do you think?

@iskiselev
Copy link
Member Author

ILSPy decompilation:

    public static void WriteNullableTestStruct(TestStructHolder holder)
    {
        TestStruct? testStruct;
        Console.WriteLine(holder.TestStruct.HasValue ? new int?(testStruct.GetValueOrDefault().Field) : null);
    }

So, it should be something like:

  function Program_WriteNullableTestStruct (holder) {
    $T02().WriteLine((
        (holder.TestStruct !== null)
           ? JSIL.Nullable_ValueOrDefault(holder.TestStruct.MemberwiseClone(), new ($T01())()).TestStruct$Field$value
           : null)
    );
  }; 

@iskiselev
Copy link
Member Author

Hm, interesting - we create structure each time when we call JSIL.Nullable_ValueOrDefault. Probably we should just pass type inside and construct instance only if we need.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants