Skip to content

CompileFast generates incorrect code with arrays and printing #305

@steve7411

Description

@steve7411

Using the latest NuGet release in a project targeting .NET 5.0 on OSX, I've run into a problem where printing values from an array to the console produces unexpected results. If I create a new array with a single element, assign a value to the first element, then Console.WriteLine that value several times, it prints unexpected results.

Here's a method I've used to reproduce the problem:

private static void ReproduceIssue(bool printBeforeRun) {
    if (printBeforeRun)
        Console.WriteLine("Printing something in advance");
    var arr = Variable(typeof(double[]), "arr");
    var printDouble = typeof(Console).GetMethod(nameof(Console.WriteLine), new[] { typeof(double) });
    Console.WriteLine("Returned value: " +
        Lambda<Func<double>>(Block(new[] { arr },
            Assign(arr, NewArrayBounds(typeof(double), Constant(1))),
            Assign(ArrayAccess(arr, Constant(0)), Constant(123.456)),
            Call(printDouble, ArrayAccess(arr, Constant(0))),
            Call(printDouble, ArrayAccess(arr, Constant(0))),
            Call(printDouble, ArrayAccess(arr, Constant(0))),
            Call(printDouble, ArrayAccess(arr, Constant(0))),
            Call(printDouble, ArrayAccess(arr, Constant(0))),
            Call(printDouble, ArrayAccess(arr, Constant(0))),
            Call(printDouble, ArrayAccess(arr, Constant(0))),
            ArrayAccess(arr, Constant(0))
        )).CompileFast()()
    );
}

If I call that like this:

ReproduceIssue(false);
ReproduceIssue(true);

it outputs:

123.456
0
0
0
0
0
0
Returned value: 123.456
Printing something in advance
123.456
3.829538003E-315
4.40912489E-315
3.752484666E-315
4.40912489E-315
3.752484666E-315
4.40912489E-315
Returned value: 123.456

So the value that gets output repeats every other time after the first two prints and the Console.WriteLine("Printing something in advance") before the test affects the results, but the returned value from the block is correct.

Metadata

Metadata

Assignees

Labels

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions