dotnet / roslyn

The Roslyn .NET compiler provides C# and Visual Basic languages with rich code analysis APIs.
https://docs.microsoft.com/dotnet/csharp/roslyn-sdk/
MIT License
19.09k stars 4.04k forks source link

Some struct layout cycles caused by static fields involving generics are not detected #75701

Open AlekseyTs opened 3 weeks ago

AlekseyTs commented 3 weeks ago

Compile the following code:

 #pragma warning disable CS0169 // The field is never used
struct E
{}

struct X<T>
{
    static T _t;
}

struct Y
{
    static X<Z> xz;
}

struct Z
{
    static X<E> xe;
    static X<Y> xy;
}

Observed: No errors. PEVerify output:

Microsoft (R) .NET Framework PE Verifier.  Version  4.0.30319.0
Copyright (c) Microsoft Corporation.  All rights reserved.

[token  0x02000006] Type load failed.
[token  0x02000007] Type load failed.
2 Error(s)

Expected: An error about a circular struct definition. For example, native compiler reports the following errors:

.cs(11,17): error CS0523: Struct member 'Y.xz' of type 'X<Z>' causes a cycle in the struct layout
.cs(6,14): error CS0523: Struct member 'X<Z>._t' of type 'Z' causes a cycle in the struct layout
.cs(17,17): error CS0523: Struct member 'Z.xy' of type 'X<Y>' causes a cycle in the struct layout
.cs(6,14): error CS0523: Struct member 'X<Y>._t' of type 'Y' causes a cycle in the struct layout

If fields are changed to instance fields, the cycles are detected:

.cs(17,10): error CS0523: Struct member 'Z.xy' of type 'X<Y>' causes a cycle in the struct layout
.cs(11,10): error CS0523: Struct member 'Y.xz' of type 'X<Z>' causes a cycle in the struct layout
cston commented 1 week ago

Moving to Backlog since the compiler does not crash.

gafter commented 1 day ago

What language rules mandate an error?

gafter commented 1 day ago

Related to this is the runtime bug https://github.com/dotnet/runtime/issues/5479, which the runtime decided not to fix and yet closed as fixed. I believer the PEVerify issue is the same bug.