fsharp icon indicating copy to clipboard operation
fsharp copied to clipboard

Wrong StructLayoutAttribute.Size for struct unions with no data fields

Open ghost opened this issue 1 year ago • 5 comments

Consider this type:

[<Struct>]
type ABC = A | B | C

F# 9 compiles it to a struct with this attribute (among others):

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Size = 1)]

However, because of the compiler-generated _tag field, the size is actually 4:

> sizeof<ABC>;;                                                        
val it: int = 4

This seems not to cause any problems, but the documentation states "This field must be equal or greater than the total size, in bytes, of the members of the class or structure," which suggests this should be corrected.

ghost avatar Dec 09 '24 17:12 ghost

It's probably some flaw in logic around:

https://github.com/dotnet/fsharp/blob/935b796dc841b6346f655421bb791c1764ab1570/src/Compiler/CodeGen/IlxGen.fs#L11567-L11576

Should be relatively easy to investigate and test. Should be a good first issue, gonna mark it like this.

vzarytovskii avatar Dec 09 '24 18:12 vzarytovskii

Hello, I would like to try fix this.

  1. What would be the expected Size for the struct would be? I see a few lines below that GenTypeDef specifies it as None. Is this the expected behavior for value type DUs too?
  2. If so, would something like this work?
if
    tycon.AllFieldsArray |> Array.exists (fun f -> not f.IsStatic)
    ||
    // Reflection emit doesn't let us emit 'pack' and 'size' for generic structs.
    // In that case we generate a dummy field instead
    (cenv.options.workAroundReflectionEmitBugs && not tycon.TyparsNoRange.IsEmpty)
    ||
    **// Discriminated unions have a compiler-generated _tag field even when they don't have any data fields,
    // so we should not explicitly set Size = 1 for them
    (match tycon.TypeReprInfo with
     | TFSharpTyconRepr { fsobjmodel_kind = TFSharpUnion } -> true
     | _ -> false)**
then
    ILTypeDefLayout.Sequential { Size = None; Pack = None }, ILDefaultPInvokeEncoding.Ansi
else
    ILTypeDefLayout.Sequential { Size = Some 1; Pack = Some 0us }, ILDefaultPInvokeEncoding.Ansi
  1. Where are tests for this part of code? Unfortunately, couldn't locate.

timofey256 avatar Mar 06 '25 22:03 timofey256

This would work, if the goal is to not set the size.

You shouldn't match tycon directly, it should have IsUnionTycon tester.

Tests can be added independently to the component tests suite.

vzarytovskii avatar Mar 06 '25 23:03 vzarytovskii

🤖 Copilot implementation hints

Fix

One-line addition in src/Compiler/CodeGen/IlxGen.fs in defaultLayout() for value types (~line 11918).

Struct DUs have a compiler-generated _tag field (int32) not in tycon.AllFieldsArray. The Size=1 explicit layout is wrong for them.

Add || tycon.IsUnionTycon to the condition that skips Size=1, Pack=0:

// Before: if ... then (existing conditions)
// After:  if ... || tycon.IsUnionTycon then

This makes struct DUs fall into the no-explicit-size branch (Size=None, Pack=None).

Instructions

  • Use TDD: write a test asserting [<Struct>] type ABC = A | B | C is not emitted with .size 1 and that sizeof<ABC> equals 4.
  • Read .github/instructions/CodeGen.instructions.md before editing.
  • Run: dotnet test tests/FSharp.Compiler.ComponentTests/FSharp.Compiler.ComponentTests.fsproj --filter "Struct" -c Debug
  • After code change, invoke the expert-review skill to review your work.
  • Minimal surgical fix. No bloated comments.
  • Run dotnet fantomas . on changed files.

T-Gro avatar May 18 '26 11:05 T-Gro

Opened a PR for this — the fix is adding tycon.IsUnionTycon to the no-explicit-size branch in defaultLayout, plus a small sizeof regression test.

KirtiRamchandani avatar Jun 14 '26 07:06 KirtiRamchandani