roslyn icon indicating copy to clipboard operation
roslyn copied to clipboard

Collection expressions: invalid code generated for inline array spread element

Open cston opened this issue 2 years ago • 4 comments

Version Used:

Steps to Reproduce:

Compile and run:

using System.Runtime.CompilerServices;

[InlineArray(3)]
struct MyArray<T>
{
    T _e0;
}

class Program
{
    static void Main()
    {
        MyArray<int> x = new();
        x[0] = 1;
        x[1] = 2;
        x[2] = 3;
        int[] y = [..x];
    }
}

Actual Behavior: Exception thrown at runtime iterating spread.

cston avatar Nov 07 '23 00:11 cston

Moving out as this is a fairly niche scenario. Will reconsider based on customer feedback.

jaredpar avatar Dec 05 '23 23:12 jaredpar

I ran into this today when trying to build a IReadOnlyCollection from an inline array + some extra data.

Is this scenario understood to be broken in the way it is? If so, this really should be prevented from compiling or be fixed... currently trying to use this seemingly valid pattern is a guaranteed AVE/NRE at runtime. The contents of the inline array are accidentally being reinterpreted as a Span (first 8 bytes being the ref, next 4 being the length) which causes an immediate explosion.

https://sharplab.io/#v2:EYLgxg9gTgpgtADwGwBYA+ABATARgLABQGADAAQY4B0ASgK4B2ALgJYC2MlAwhKwA7MAbGFADKwgG7MwMAM4BuQoQDaASXoDm9GAEEoUAIYBPABRYAlAF1CGAMykZjKLTCNS1GLygQ1GrboOGhADehKRhpJ7M4vqMMKS0AhD0AOakrAD6wPpgANaayQoEAL6KRHbYpJykIQTh5FhY1aF14dFQpPp6RqQAvKRaAO5uHl4+mjpdJmaFLeGdAUrEFr2kODOzHZNKOMt9WOuzzbMJSclKyzKeMPoAJitKlJTzRhYHLdz0MhBClADytIxKAB1KDMWIAGXGxkusFu0yOpBKxSAA=== (see the Span<ulong>.Enumerator enumerator = ((Span<ulong>*)(&buffer))->GetEnumerator();)

The workaround is to cast the inline array to a span directly before using the spread operator e.g [..(ReadOnlySpan<ulong>)m_array]

ZingBallyhoo avatar Mar 12 '24 01:03 ZingBallyhoo

Also ran into this myself today. This seems to sometimes cause the CLR to crash and sometimes it just silently fails without the content being added to the list.

aromaa avatar Jun 21 '24 19:06 aromaa

One more report at https://github.com/dotnet/runtime/issues/107018

huoyaoyuan avatar Aug 27 '24 07:08 huoyaoyuan