Skip to content

Implicit boxing produces extraneous closure #12546

Open

Description

@chkn

Repro steps

Minimized repro (sharplab):

module Foo

let foo (ob: obj) = box(fun () -> ob.ToString()) :?> (unit -> string)

let go() = foo "hi"

Expected behavior

A single closure should be allocated.

Actual behavior

A second, extraneous closure is allocated that simply wraps the first. Here is the decompiled C# for that closure from sharplab:

[Serializable]
internal sealed class go@5 : FSharpFunc<Unit, string>
{
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    [CompilerGenerated]
    [DebuggerNonUserCode]
    public FSharpFunc<Unit, string> clo1;

    [CompilerGenerated]
    [DebuggerNonUserCode]
    internal go@5(FSharpFunc<Unit, string> clo1)
    {
        this.clo1 = clo1;
    }

    public override string Invoke(Unit arg10)
    {
        return clo1.Invoke(arg10);
    }
}

Known workarounds

Explicitly boxing the argument doesn't produce the extra closure (sharplab):

module Foo

let foo (ob: obj) = box(fun () -> ob.ToString()) :?> (unit -> string)

let go() = foo(box "hi")

Related information

Provide any related information (optional):

  • Operating system
  • .NET Runtime kind (.NET Core, .NET Framework, Mono)
  • Editing Tools (e.g. Visual Studio Version, Visual Studio)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Area-Compiler-CodeGenFeature Improvement

    Type

    No type

    Projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions