Repository navigation
Description
F# compiler sometimes turns let binding with anonymous function into member function. Then when the anonymous function is needed it constructs subclass of FSharpFunc but this newly constructed instance is not stored so it may be garbage collected. This may affect behavior of programs which don't store another strong reference to that anonymous function.
Repro steps
Here is a complete example:
open System
type State = { Items : ResizeArray<int> }
type StateUpdated() =
let subscribers = ResizeArray<WeakReference<unit -> unit>>()
member _.Subscribe(f : unit -> unit) = subscribers.Add(WeakReference<_>(f))
member _.NotifySubscribers() =
let mutable i = 0
for j = 0 to subscribers.Count - 1 do
let alive, f = subscribers[j].TryGetTarget()
if alive then
f ()
subscribers[i] <- subscribers[j]
i <- i + 1
// Remove garbage collected subscribers.
subscribers.RemoveRange(i, subscribers.Count - i)
type SomeWindow(state : State, stateUpdated : StateUpdated) =
// The assumption is that storing `handler` in a variable would keep the anonymous function alive.
// So `WeakReference` created in `Subscribe` will be kept alive while instance of `SomeWindow` is alive.
// But this is wrong. Decompiling `SomeWindow` shows that there's no field `handler`.
let handler = fun () ->
printfn "Updating window with new items %A" state.Items
do
stateUpdated.Subscribe(handler)
handler () // Populate window with initial items.
// We need some member which uses `handler` otherwise `handler` would be local
// variable in constructor.
member _.EnsureHandlerIsField() =
handler.ToString()
[<EntryPoint>]
let main args =
let state = { Items = ResizeArray() }
let stateUpdated = StateUpdated()
let window = SomeWindow(state, stateUpdated)
GC.Collect(0) // In my real app this is not necessary.
// Simulate state update.
state.Items.Add 1
stateUpdated.NotifySubscribers()
0Expected behavior
I would expect that function referenced by WeakReference created in Subscribe isn't garbage collected and could be called.
Actual behavior
F# compiler removes the only one strong reference handler and creates something like this decompiled code:
[CompilationMapping(SourceConstructFlags.ObjectType)]
[Serializable]
public class SomeWindow
{
internal Program.State state;
public SomeWindow(Program.State state, Program.StateUpdated stateUpdated)
{
Program.SomeWindow someWindow = this;
this.state = state;
stateUpdated.Subscribe((FSharpFunc<Unit, Unit>) new Program.-ctor@30(this));
this.handler();
}
public string EnsureHandlerIsField() => new Program.EnsureHandlerIsField@34(this).ToString();
[CompilerGenerated]
[DebuggerNonUserCode]
internal void handler() => ExtraTopLevelOperators.PrintFormatLine<FSharpFunc<List<int>, Unit>>((PrintfFormat<FSharpFunc<List<int>, Unit>, TextWriter, Unit, Unit>) new PrintfFormat<FSharpFunc<List<int>, Unit>, TextWriter, Unit, Unit, List<int>>("Updating window with new items %A")).Invoke(this.state.Items@);
}Notice that Subscribe is called with (FSharpFunc<Unit, Unit>) new Program.-ctor@30(this) which is not stored anywhere.
Known workarounds
You have to wrap the callback in other type:
open System
type WrappedFunc =
| WrappedFunc of (unit -> unit)
member me.Func =
let (WrappedFunc f) = me
f
type State = { Items : ResizeArray<int> }
type StateUpdated() =
let subscribers = ResizeArray<WeakReference<WrappedFunc>>()
member _.Subscribe(f : WrappedFunc) = subscribers.Add(WeakReference<_>(f))
member _.NotifySubscribers() =
let mutable i = 0
for j = 0 to subscribers.Count - 1 do
let alive, f = subscribers[j].TryGetTarget()
if alive then
f.Func ()
subscribers[i] <- subscribers[j]
i <- i + 1
// Remove garbage collected subscribers.
subscribers.RemoveRange(i, subscribers.Count - i)
type SomeWindow(state : State, stateUpdated : StateUpdated) =
let handler = WrappedFunc <| fun () ->
printfn "Updating window with new items %A" state.Items
do
stateUpdated.Subscribe(handler)
handler.Func () // Populate window with initial items.
member _.EnsureHandlerIsField() =
handler.ToString()
[<EntryPoint>]
let main args =
let state = { Items = ResizeArray() }
let stateUpdated = StateUpdated()
let window = SomeWindow(state, stateUpdated)
GC.Collect(0) // In my real app this is not necessary.
// Simulate state update.
state.Items.Add 1
stateUpdated.NotifySubscribers()
0Related information
- I'm on Intel Mac.
- .NET 7
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone
Activity
kerams commentedon Sep 21, 2023
I don't think this is a bug - page 197.
Granted, you're dealing with a private value, so interoperability is not a concern, strictly speaking.
radekm commentedon Sep 21, 2023
To me it seems counterintuitive. Because lambda function is a value and when I store a value in a variable I would expect that the value will be reused when I reuse the variable (but instead it's recreated every time I reuse the variable).
Additionally I would expect that whenever I use
handlerI get the same instance. But followingprints
Equal false.Or that if I use field in the loop
that it doesn't instantiate new function every time (but according to a decompiler it does).
smoothdeveloper commentedon Sep 21, 2023
under "6.9.24 Values with Underspecified Object Identity and Type Identity"
Relying on identity or lifetime of a "function value" seems to be going against the grain of the language, I assume there are many places where they get inlined (when they don't close over anything), and in other places, they allocate, and yet other places, they turn into methods.
For the original case of this issue, I'm wondering if producing a warning for using function type as type argument to
WeakReferencewould be the right thing to do to avoid this gotcha.radekm commentedon Sep 22, 2023
You're right that it seems that behavior is according to spec. I found 8.6.1.3 Instance Function and Value Definitions in Primary Constructors which states
and
So the simpler fix is to somehow just ensure that right-hand side is not an anonymous function. For example following works
(even though Rider IDE says that
id <|part is redundant - but it's not). Or this works too:radekm commentedon Sep 22, 2023
Something like that would be nice. On the other hand I believe that
shall work fine. My reasoning is that
handlershall be normal value which is not considered as function definition and assigninghandlerXtohandlershould create function object becausehandlerXwas compiled to member which can't be assigned tohandlerunless it's wrapped in function object (unforunately I don't know which part of the spec justifies this).I also believe that it shall work with
WeakReference- because now I have only one valuehandler.