diff --git a/release-notes.txt b/release-notes.txt index 6f309b9b..c9e9c920 100644 --- a/release-notes.txt +++ b/release-notes.txt @@ -2,6 +2,11 @@ Release notes: Unreleased + - fixes the dynamic resumable code path of `taskSeq` (used in FSI and whenever the F# compiler does not compile the CE to a static state machine, e.g. Debug builds with .NET SDK 10.0.4xx): a `let!`/`do!` on an awaitable that does not complete synchronously dropped the rest of the computation (truncating the sequence, swallowing exceptions, or hanging in loops); `for .. in` over an `IAsyncEnumerable` discarded the awaited `MoveNextAsync` result and called it again; and `DisposeAsync` did not run pending `finally`/`use` compensations. This is the cause of the Debug-only truncation in #473, #505 + - fixes the dynamic resumable code path of `for .. in` over a `taskSeq` inside `task { .. }`, which crashed with a `NullReferenceException` when `MoveNextAsync` did not complete synchronously, #505 + - fixes `taskSeq { for x in source do .. }`, and functions built on it like `TaskSeq.map`, reporting the last item twice when the source's `DisposeAsync` completes asynchronously, #452 + - perf: `for .. in` over an `IAsyncEnumerable` inside `taskSeq`, and therefore most `TaskSeq` functions, awaits a pending `MoveNextAsync` through its `ValueTask` awaiter instead of `AsTask()`, saving a `Task` allocation per suspension + - test: add TaskSeq.Dynamic.Forced.Tests.CE.fs, which forces the dynamic resumable code path (the existing `taskSeqDynamic` tests are compiled statically and never exercised it) - fix: `TaskSeq-replicateUntilNoneAsync re-runs the computation from its initial state on each fresh enumeration` test hung CI by declaring its loop counter `n` inside the computation function, so it reset to 0 on every call and the terminating `None` branch was never reached; `n` is now shared across calls as intended - test: add SideEffects module to TaskSeq.ReplicateInfinite.Tests.fs and TaskSeq.ThreadState.Tests.fs, verifying computation/generator/folder call counts and re-enumeration semantics - test: add direct unit test coverage for the `ValueTask` helper module (`fromResult`, `ofSource`, `ofTask`, `ignore`, `True`/`False`, plus their deprecated aliases), closing a gap where these functions had no dedicated tests despite the `Task`/`Async` equivalents being covered diff --git a/src/FSharp.Control.TaskSeq.Test/FSharp.Control.TaskSeq.Test.fsproj b/src/FSharp.Control.TaskSeq.Test/FSharp.Control.TaskSeq.Test.fsproj index fcb3274d..b0c22070 100644 --- a/src/FSharp.Control.TaskSeq.Test/FSharp.Control.TaskSeq.Test.fsproj +++ b/src/FSharp.Control.TaskSeq.Test/FSharp.Control.TaskSeq.Test.fsproj @@ -71,6 +71,7 @@ + diff --git a/src/FSharp.Control.TaskSeq.Test/TaskSeq.Dynamic.Forced.Tests.CE.fs b/src/FSharp.Control.TaskSeq.Test/TaskSeq.Dynamic.Forced.Tests.CE.fs new file mode 100644 index 00000000..4fee065f --- /dev/null +++ b/src/FSharp.Control.TaskSeq.Test/TaskSeq.Dynamic.Forced.Tests.CE.fs @@ -0,0 +1,443 @@ +module TaskSeq.Tests.``taskSeq forced dynamic path`` + +// The `taskSeq` builder has two implementations of its resumable code: +// +// - the static one, which the F# compiler lowers into a struct state machine, and +// - the dynamic one (`TaskSeqDynamic` / `TaskSeqDynamicInfo` and the `else` branches +// of `if __useResumableCode`), used whenever the compiler cannot (or decides not to) +// lower the computation expression, e.g. in FSI, or when the compiler falls back with +// warning FS3511. +// +// In normally compiled test code, `taskSeq { .. }` and `taskSeqDynamic { .. }` are always +// lowered statically, so the dynamic path is never exercised. The builder below forces the +// dynamic path by making `Run` non-inline: the resumable code then arrives as an opaque +// delegate that was built outside of any state machine, so every `__useResumableCode` +// check inside the builder members evaluates to false. +// +// NOTE: the sequences under test are created in ordinary functions, *not* inside the `task { .. }` +// of the test itself. When dynamic resumable code is nested inside a statically compiled state +// machine, the compiler resolves `__useResumableCode` of the nested code using the outer state +// machine, which gives FS3401 errors (or invalid IL with older compilers). +// +// The important cases are those where an await does *not* complete synchronously, since +// only then the dynamic code has to suspend and resume. + +#nowarn "57" // Experimental library feature, requires '--langversion:preview'. +#nowarn "3513" // Resumable code invocation: intentionally calling ResumableCode as a regular delegate. +#nowarn "1204" // TaskBuilder.RunDynamic is for use by compiled F# code. + +open System +open System.Collections.Generic +open System.Threading +open System.Threading.Tasks + +open Xunit +open FsUnit.Xunit + +open FSharp.Core.CompilerServices +open FSharp.Control + +/// A taskSeq builder that always uses the dynamic (ResumptionDynamicInfo-based) implementation. +type ForcedDynamicTaskSeqBuilder() = + inherit TaskSeqDynamicBuilder() + + // not inline: this is what prevents the compiler from lowering the CE to a state machine + member _.Run(code: ResumableTSC<'T>) : TaskSeq<'T> = + let ts = TaskSeqDynamic<'T>() + ts._initialResumptionFunc <- TaskSeqResumptionFunc<'T>(fun sm -> code.Invoke(&sm)) + ts :> TaskSeq<'T> + +let dynTaskSeq = ForcedDynamicTaskSeqBuilder() + +/// Runs `task { for x in source do body x }` on FSharp.Core's dynamic task implementation. Used to +/// test the `for .. in taskSeq` extension of the `task` CE (see TaskExtensions.fs) on its dynamic path. +/// The CE is desugared by hand, because TaskBuilder cannot be subclassed to get a non-inline Run. +let dynTaskFor (source: TaskSeq<'T>) (body: 'T -> unit) : Task = + TaskBuilder.RunDynamic( + task.Delay(fun () -> + task.For( + source, + fun x -> + body x + task.Zero() + )) + ) + +/// Returns a task that completes asynchronously, with the given result. +let delayed (x: 'T) = task { + do! Task.Delay 1 + return x +} + +/// A task that completes asynchronously, with an exception. +let delayedFail () : Task = task { + do! Task.Delay 1 + return raise (InvalidOperationException "boom") +} + +/// An external IAsyncEnumerable (not built with taskSeq), with control over +/// whether MoveNextAsync and DisposeAsync complete synchronously or not. +type ExternalSource(items: int list, asyncMoveNext: bool, asyncDispose: bool) = + member val DisposeCount = 0 with get, set + member val MoveNextCount = 0 with get, set + + interface IAsyncEnumerable with + member this.GetAsyncEnumerator _ = + let remaining = ref items + let current = ref 0 + + { new IAsyncEnumerator with + member _.Current = current.Value + + member _.MoveNextAsync() = + this.MoveNextCount <- this.MoveNextCount + 1 + + let hasNext = + match remaining.Value with + | x :: rest -> + current.Value <- x + remaining.Value <- rest + true + | [] -> false + + if asyncMoveNext then + ValueTask(delayed hasNext) + else + ValueTask hasNext + + member _.DisposeAsync() = + if asyncDispose then + ValueTask( + task { + do! Task.Delay 1 + this.DisposeCount <- this.DisposeCount + 1 + } + ) + else + this.DisposeCount <- this.DisposeCount + 1 + ValueTask() + } + +// +// The sequences under test. Created outside of any statically compiled state machine, see the note at the top. +// + +module Seqs = + let simple () = dynTaskSeq { + yield 1 + yield 2 + yield 3 + } + + let empty () : TaskSeq = dynTaskSeq { () } + + let awaitTaskBetweenYields () = dynTaskSeq { + yield 1 + do! Task.Delay 1 + yield 2 + do! Task.Delay 1 + yield 3 + } + + // YieldAwaitable goes through the SRTP ^TaskLike Bind overload + let awaitTaskYieldBetweenYields () = dynTaskSeq { + yield 1 + do! Task.Yield() + yield 2 + do! Task.Yield() + yield 3 + } + + let letBangTask () = dynTaskSeq { + let! x = delayed 10 + yield x + let! y = delayed 20 + yield x + y + } + + let letBangValueTask () = dynTaskSeq { + let! x = ValueTask(delayed 10) + yield x + let! y = ValueTask(delayed 20) + yield x + y + } + + let letBangAsync () = dynTaskSeq { + let! x = async { + do! Async.Sleep 1 + return 10 + } + + yield x + + let! y = async { + do! Async.Sleep 1 + return 20 + } + + yield x + y + } + + let awaitsInLoops () = dynTaskSeq { + for i in 1..3 do + do! Task.Delay 1 + yield i + + let mutable i = 4 + + while i <= 6 do + let! x = delayed i + yield x + i <- i + 1 + } + + let awaitFaultedTask () = dynTaskSeq { + yield 1 + let! x = delayedFail () + yield x + } + + let tryWithAfterAwait () = dynTaskSeq { + try + yield 1 + do! Task.Delay 1 + raise (InvalidOperationException "boom") + yield 2 + with :? InvalidOperationException -> + yield 99 + } + + let tryFinallyAfterAwait (finallyCount: int ref) = dynTaskSeq { + try + yield 1 + do! Task.Delay 1 + yield 2 + finally + finallyCount.Value <- finallyCount.Value + 1 + } + + let forOverAsyncEnumerable (source: IAsyncEnumerable) = dynTaskSeq { + for x in source do + yield x + } + + let awaitingInner () = taskSeq { + for i in 1..5 do + do! Task.Delay 1 + yield i + } + + let yieldBangAwaitingInner () = + let inner = dynTaskSeq { + do! Task.Delay 1 + yield 1 + do! Task.Delay 1 + yield 2 + } + + dynTaskSeq { + yield! inner + yield 3 + yield! inner + } + + let earlyDisposal (finallyCount: int ref) = dynTaskSeq { + try + for i in 1..10 do + do! Task.Delay 1 + yield i + finally + finallyCount.Value <- finallyCount.Value + 1 + } + + let reEnumerate () = dynTaskSeq { + for i in 1..3 do + let! x = delayed i + yield x + } + + let largeSyncLoop () = dynTaskSeq { + for i in 1..10_000 do + if i % 1000 = 0 then + yield i + } + +[] +let ``CE forced-dynamic builder really uses the dynamic path`` () = + Seqs.simple () + |> should be instanceOfType> + +[] +let ``CE forced-dynamic empty and simple yields`` () = task { + let! empty = Seqs.empty () |> TaskSeq.toListAsync + empty |> should be Empty + + let! data = Seqs.simple () |> TaskSeq.toListAsync + data |> should equal [ 1; 2; 3 ] +} + +[] +let ``CE forced-dynamic do! Task between yields`` () = task { + let! data = Seqs.awaitTaskBetweenYields () |> TaskSeq.toListAsync + data |> should equal [ 1; 2; 3 ] +} + +[] +let ``CE forced-dynamic do! Task.Yield between yields`` () = task { + let! data = Seqs.awaitTaskYieldBetweenYields () |> TaskSeq.toListAsync + data |> should equal [ 1; 2; 3 ] +} + +[] +let ``CE forced-dynamic let! Task<'T>`` () = task { + let! data = Seqs.letBangTask () |> TaskSeq.toListAsync + data |> should equal [ 10; 30 ] +} + +[] +let ``CE forced-dynamic let! ValueTask<'T>`` () = task { + let! data = Seqs.letBangValueTask () |> TaskSeq.toListAsync + data |> should equal [ 10; 30 ] +} + +[] +let ``CE forced-dynamic let! Async<'T>`` () = task { + let! data = Seqs.letBangAsync () |> TaskSeq.toListAsync + data |> should equal [ 10; 30 ] +} + +[] +let ``CE forced-dynamic awaits inside for and while loops`` () = task { + let! data = Seqs.awaitsInLoops () |> TaskSeq.toListAsync + data |> should equal [ 1..6 ] +} + +[] +let ``CE forced-dynamic exception from awaited faulted task propagates`` () = task { + let! exn = Assert.ThrowsAsync(fun () -> Seqs.awaitFaultedTask () |> TaskSeq.toListAsync :> Task) + exn.Message |> should equal "boom" +} + +[] +let ``CE forced-dynamic try-with catches exception raised after an await`` () = task { + let! data = Seqs.tryWithAfterAwait () |> TaskSeq.toListAsync + data |> should equal [ 1; 99 ] +} + +[] +let ``CE forced-dynamic try-finally runs finally after awaits`` () = task { + let finallyCount = ref 0 + + let! data = + Seqs.tryFinallyAfterAwait finallyCount + |> TaskSeq.toListAsync + + data |> should equal [ 1; 2 ] + finallyCount.Value |> should equal 1 +} + +[] +let ``CE forced-dynamic for over IAsyncEnumerable with async MoveNextAsync`` () = task { + let source = ExternalSource([ 1..5 ], asyncMoveNext = true, asyncDispose = false) + let! data = Seqs.forOverAsyncEnumerable source |> TaskSeq.toListAsync + data |> should equal [ 1..5 ] + source.MoveNextCount |> should equal 6 + source.DisposeCount |> should equal 1 +} + +[] +let ``CE forced-dynamic for over IAsyncEnumerable with async DisposeAsync does not repeat the last item`` asyncMoveNext = task { + let source = ExternalSource([ 1..3 ], asyncMoveNext, asyncDispose = true) + let! data = Seqs.forOverAsyncEnumerable source |> TaskSeq.toListAsync + data |> should equal [ 1; 2; 3 ] + source.DisposeCount |> should equal 1 +} + +[] +let ``CE forced-dynamic for over awaiting taskSeq`` () = task { + let! data = + Seqs.forOverAsyncEnumerable (Seqs.awaitingInner ()) + |> TaskSeq.toListAsync + + data |> should equal [ 1..5 ] +} + +[] +let ``CE forced-dynamic yield! awaiting taskSeq`` () = task { + let! data = Seqs.yieldBangAwaitingInner () |> TaskSeq.toListAsync + data |> should equal [ 1; 2; 3; 1; 2 ] +} + +[] +let ``CE forced-dynamic early disposal runs pending finally`` () = task { + let finallyCount = ref 0 + + let! data = + Seqs.earlyDisposal finallyCount + |> TaskSeq.take 2 + |> TaskSeq.toListAsync + + data |> should equal [ 1; 2 ] + finallyCount.Value |> should equal 1 +} + +[] +let ``CE forced-dynamic re-enumeration with awaits`` () = task { + let ts = Seqs.reEnumerate () + let! data1 = ts |> TaskSeq.toListAsync + let! data2 = ts |> TaskSeq.toListAsync + data1 |> should equal [ 1; 2; 3 ] + data2 |> should equal [ 1; 2; 3 ] +} + +[] +let ``CE forced-dynamic large synchronous loop`` () = task { + let! data = Seqs.largeSyncLoop () |> TaskSeq.toListAsync + data |> should equal [ 1000..1000..10_000 ] +} + +[] +let ``task CE forced-dynamic for over IAsyncEnumerable with async MoveNextAsync`` () = task { + let source = ExternalSource([ 1..5 ], asyncMoveNext = true, asyncDispose = false) + let items = ResizeArray() + do! dynTaskFor source items.Add + List.ofSeq items |> should equal [ 1..5 ] + source.DisposeCount |> should equal 1 +} + +[] +let ``task CE forced-dynamic for over awaiting taskSeq`` () = task { + let items = ResizeArray() + do! dynTaskFor (Seqs.awaitingInner ()) items.Add + List.ofSeq items |> should equal [ 1..5 ] +} + +// Same scenario on the static path: when the source's DisposeAsync completes asynchronously, the +// TryFinallyAsync compensation suspends while `current` still holds the last yielded item. +// See https://github.com/fsprojects/FSharp.Control.TaskSeq/issues/452 +[] +let ``CE static for over IAsyncEnumerable with async DisposeAsync does not repeat the last item`` asyncMoveNext = task { + let source = ExternalSource([ 1..3 ], asyncMoveNext, asyncDispose = true) + + let ts = taskSeq { + for x in source do + yield x + } + + let! data = ts |> TaskSeq.toListAsync + data |> should equal [ 1; 2; 3 ] + source.DisposeCount |> should equal 1 +} + +[] +let ``TaskSeq.map over IAsyncEnumerable with async DisposeAsync does not repeat the last item`` asyncMoveNext = task { + let source = ExternalSource([ 1..3 ], asyncMoveNext, asyncDispose = true) + + let! data = + source + |> TaskSeq.map (fun x -> x * 10) + |> TaskSeq.toListAsync + + data |> should equal [ 10; 20; 30 ] + source.DisposeCount |> should equal 1 +} diff --git a/src/FSharp.Control.TaskSeq/TaskExtensions.fs b/src/FSharp.Control.TaskSeq/TaskExtensions.fs index a811e8a4..27f189cf 100644 --- a/src/FSharp.Control.TaskSeq/TaskExtensions.fs +++ b/src/FSharp.Control.TaskSeq/TaskExtensions.fs @@ -1,16 +1,19 @@ namespace FSharp.Control +// note: these are *not* experimental features anymore, but they forgot to switch off the flag +#nowarn "57" // Experimental library feature, requires '--langversion:preview'. +#nowarn "1204" // This construct is for use by compiled F# code and should not be used directly. +#nowarn "3513" // Resumable code invocation: intentionally calling ResumableCode as a regular delegate in the dynamic path. + open System.Collections.Generic +open System.Runtime.CompilerServices open System.Threading open System.Threading.Tasks open Microsoft.FSharp.Core.CompilerServices +open Microsoft.FSharp.Core.CompilerServices.StateMachineHelpers // raises warning FS0057 open Microsoft.FSharp.Core.LanguagePrimitives.IntrinsicOperators -// note: these are *not* experimental features anymore, but they forgot to switch off the flag -#nowarn "57" // Experimental library feature, requires '--langversion:preview'. -#nowarn "1204" // This construct is for use by compiled F# code and should not be used directly. - [] module TaskExtensions = @@ -22,40 +25,62 @@ module TaskExtensions = member inline _.WhileAsync([] condition: unit -> ValueTask, body: TaskCode<_, unit>) : TaskCode<_, _> = let mutable condition_res = true - // note that this While itself has both a dynamic and static implementation - // so we don't need to add that here (TODO: how to verify?). + // ResumableCode.While has both a dynamic and static implementation, but the body below + // needs its own dynamic implementation (tested in TaskSeq.Dynamic.Forced.Tests.CE.fs). ResumableCode.While( (fun () -> condition_res), TaskCode<_, _>(fun sm -> - let mutable __stack_condition_fin = true - let __stack_vtask = condition () + if __useResumableCode then + //-- RESUMABLE CODE START + let mutable __stack_condition_fin = true + let __stack_vtask = condition () - let mutable awaiter = __stack_vtask.GetAwaiter() + let mutable awaiter = __stack_vtask.GetAwaiter() - if awaiter.IsCompleted then - Debug.logInfo "at Task.WhileAsync: returning completed task" + if awaiter.IsCompleted then + Debug.logInfo "at Task.WhileAsync: returning completed task" - __stack_condition_fin <- true - condition_res <- awaiter.GetResult() - else - Debug.logInfo "at Task.WhileAsync: awaiting non-completed task" + __stack_condition_fin <- true + condition_res <- awaiter.GetResult() + else + Debug.logInfo "at Task.WhileAsync: awaiting non-completed task" + + // This will yield with __stack_fin = false + // This will resume with __stack_fin = true + + // NOTE (AB): if this extra let-binding isn't here, we get NRE exceptions, infinite loops (end of seq not signaled) and warning FS3513 + let __stack_yield_fin = ResumableCode.Yield().Invoke(&sm) + __stack_condition_fin <- __stack_yield_fin - // This will yield with __stack_fin = false - // This will resume with __stack_fin = true + if __stack_condition_fin then + condition_res <- awaiter.GetResult() - // NOTE (AB): if this extra let-binding isn't here, we get NRE exceptions, infinite loops (end of seq not signaled) and warning FS3513 - let __stack_yield_fin = ResumableCode.Yield().Invoke(&sm) - __stack_condition_fin <- __stack_yield_fin if __stack_condition_fin then + if condition_res then body.Invoke(&sm) else true + else + sm.Data.MethodBuilder.AwaitUnsafeOnCompleted(&awaiter, &sm) + false + //-- RESUMABLE CODE END + else + // Dynamic path: follow the protocol of FSharp.Core's dynamic task implementation, which + // expects the awaiter in ResumptionData and does the AwaitUnsafeOnCompleted call itself. + // ResumableCode.Yield() can't be used here, as in dynamic code it resumes with a continuation + // that just returns 'true', skipping the code that reads the result of the condition. + let awaiter = condition().GetAwaiter() + + if awaiter.IsCompleted then condition_res <- awaiter.GetResult() + if condition_res then body.Invoke(&sm) else true + else + sm.ResumptionDynamicInfo.ResumptionData <- (awaiter :> ICriticalNotifyCompletion) + sm.ResumptionDynamicInfo.ResumptionFunc <- + TaskResumptionFunc<_>(fun sm -> + condition_res <- awaiter.GetResult() + if condition_res then body.Invoke(&sm) else true) - if __stack_condition_fin then - if condition_res then body.Invoke(&sm) else true - else - sm.Data.MethodBuilder.AwaitUnsafeOnCompleted(&awaiter, &sm) - false) + false) ) member inline this.For(source: TaskSeq<'T>, body: 'T -> TaskCode<_, unit>) : TaskCode<_, unit> = diff --git a/src/FSharp.Control.TaskSeq/TaskSeqBuilder.fs b/src/FSharp.Control.TaskSeq/TaskSeqBuilder.fs index 9a8fd826..8c96b37f 100644 --- a/src/FSharp.Control.TaskSeq/TaskSeqBuilder.fs +++ b/src/FSharp.Control.TaskSeq/TaskSeqBuilder.fs @@ -448,13 +448,18 @@ and [] TaskSeqDynamic<'T>() = this.MoveNextAsyncResult() member this.DisposeAsync() = + // NOTE: '_machine' must NOT be accessed inside the 'task' below. The F# compiler substitutes the + // 'ResumableStateMachine<_>' type with the task's own state machine struct when compiling the task's + // resumable code, which makes field accesses on '_machine' read garbage (or causes InvalidProgramException). + let data = this._machine.Data + task { - match this._machine.Data.disposalStack with + match data.disposalStack with | null -> () | _ -> let mutable exn = None - for d in Seq.rev this._machine.Data.disposalStack do + for d in Seq.rev data.disposalStack do try do! d () with e -> @@ -579,37 +584,62 @@ type TaskSeqBuilder() = ResumableCode.While( (fun () -> condition_res), ResumableTSC<'T>(fun sm -> - let mutable __stack_condition_fin = true - let __stack_vtask = condition () + if __useResumableCode then + //-- RESUMABLE CODE START + let mutable __stack_condition_fin = true + let __stack_vtask = condition () - if __stack_vtask.IsCompleted then - Debug.logInfo "at WhileAsync: returning completed task" + if __stack_vtask.IsCompleted then + Debug.logInfo "at WhileAsync: returning completed task" - __stack_condition_fin <- true - condition_res <- __stack_vtask.Result - else - Debug.logInfo "at WhileAsync: awaiting non-completed task" + __stack_condition_fin <- true + condition_res <- __stack_vtask.Result + else + Debug.logInfo "at WhileAsync: awaiting non-completed task" - let task = __stack_vtask.AsTask() - let mutable awaiter = task.GetAwaiter() + // Await the ValueTask through its own awaiter. AsTask() would allocate a Task when the + // ValueTask is backed by an IValueTaskSource, like the MoveNextAsync of a taskSeq. + let mutable awaiter = __stack_vtask.GetAwaiter() - // This will yield with __stack_fin = false - // This will resume with __stack_fin = true + // This will yield with __stack_fin = false + // This will resume with __stack_fin = true - // NOTE (AB): if this extra let-binding isn't here, we get NRE exceptions, infinite loops (end of seq not signaled) and warning FS3513 - let __stack_yield_fin = ResumableCode.Yield().Invoke(&sm) - __stack_condition_fin <- __stack_yield_fin + // NOTE (AB): if this extra let-binding isn't here, we get NRE exceptions, infinite loops (end of seq not signaled) and warning FS3513 + let __stack_yield_fin = ResumableCode.Yield().Invoke(&sm) + __stack_condition_fin <- __stack_yield_fin + + if __stack_condition_fin then + condition_res <- awaiter.GetResult() + else + sm.Data.awaiter <- awaiter + sm.Data.current <- ValueNone if __stack_condition_fin then - condition_res <- task.Result + if condition_res then body.Invoke(&sm) else true + else + false + //-- RESUMABLE CODE END + else + // Dynamic path. ResumableCode.Yield() cannot be used here: in dynamic code it resumes + // with a continuation that just returns 'true', so the code after the yield point (reading + // the result of the condition and running the body) would never run. Instead, we install + // our own continuation. The looping itself is done by the dynamic ResumableCode.While. + let vtask = condition () + + if vtask.IsCompleted then + condition_res <- vtask.Result + if condition_res then body.Invoke(&sm) else true else + let awaiter = vtask.GetAwaiter() + + sm.ResumptionDynamicInfo.ResumptionFunc <- + TaskSeqResumptionFunc<'T>(fun sm -> + condition_res <- awaiter.GetResult() + if condition_res then body.Invoke(&sm) else true) + sm.Data.awaiter <- awaiter sm.Data.current <- ValueNone - - if __stack_condition_fin then - if condition_res then body.Invoke(&sm) else true - else - false) + false) ) member inline _.While([] condition: unit -> bool, body: ResumableTSC<'T>) = @@ -632,6 +662,8 @@ type TaskSeqBuilder() = let __stack_vtask = compensationAction () if not __stack_vtask.IsCompleted then + // Note: in dynamic code, ResumableCode.Yield() resumes with a continuation that returns 'true', + // which is exactly what we need here, so this works for both the static and dynamic paths. let mutable awaiter = __stack_vtask.GetAwaiter() let __stack_yield_fin = ResumableCode.Yield().Invoke(&sm) __stack_condition_fin <- __stack_yield_fin @@ -639,6 +671,10 @@ type TaskSeqBuilder() = if not __stack_condition_fin then sm.Data.awaiter <- awaiter + // We are awaiting, not yielding: 'current' may still hold the last yielded item, which would + // otherwise be reported again by MoveNextAsync, see #452 + sm.Data.current <- ValueNone + __stack_condition_fin) ) @@ -668,14 +704,14 @@ type TaskSeqBuilder() = member inline _.Yield(value: 'T) : ResumableTSC<'T> = ResumableTSC<'T>(fun sm -> - // This will yield with __stack_fin = false - // This will resume with __stack_fin = true Debug.logInfo "at Yield" - let __stack_fin = ResumableCode.Yield().Invoke(&sm) + // All work happens before the yield point and the yield is in tail position, so nothing has to run + // after resuming. This makes it behave the same in static and dynamic resumable code: in dynamic code, + // ResumableCode.Yield() resumes with a continuation that just returns 'true', skipping any code after it. sm.Data.current <- ValueSome value sm.Data.awaiter <- null - __stack_fin) + ResumableCode.Yield().Invoke(&sm)) // // These "modules of priority" allow for an indecisive F# to resolve @@ -720,30 +756,28 @@ module LowPriority = = ResumableTSC<'U>(fun sm -> - let mutable awaiter = (^TaskLike: (member GetAwaiter: unit -> ^Awaiter) (task)) - let mutable __stack_fin = true - Debug.logInfo "at TaskLike bind" - - if not (^Awaiter: (member get_IsCompleted: unit -> bool) awaiter) then - // This will yield with __stack_fin2 = false - // This will resume with __stack_fin2 = true - let __stack_fin2 = ResumableCode.Yield().Invoke(&sm) - __stack_fin <- __stack_fin2 - - Debug.logInfo ("at TaskLike bind: this.completed = ", sm.Data.completed) - - if __stack_fin then - Debug.logInfo "at TaskLike bind!: finished awaiting, calling continuation" - let result = (^Awaiter: (member GetResult: unit -> 'T) awaiter) - (continuation result).Invoke(&sm) - - else - Debug.logInfo "at TaskLike bind: await further" - - sm.Data.awaiter <- awaiter - sm.Data.current <- ValueNone - false) + let awaiter = (^TaskLike: (member GetAwaiter: unit -> ^Awaiter) (task)) + + // One code path for static and dynamic resumable code: the await step ends in a tail-position + // Yield(), and Combine runs the continuation after it. When resuming, static code jumps back into + // the Yield and Combine falls through to the continuation; in dynamic code, CombineDynamic has + // installed the continuation. The continuation is invoked in one place only, so it is inlined once. + ResumableCode + .Combine( + ResumableTSC<'U>(fun sm -> + if (^Awaiter: (member get_IsCompleted: unit -> bool) awaiter) then + true + else + Debug.logInfo "at TaskLike bind: await further" + sm.Data.awaiter <- awaiter + sm.Data.current <- ValueNone + ResumableCode.Yield().Invoke(&sm)), + ResumableTSC<'U>(fun sm -> + let result = (^Awaiter: (member GetResult: unit -> 'T) awaiter) + (continuation result).Invoke(&sm)) + ) + .Invoke(&sm)) [] @@ -798,60 +832,43 @@ module HighPriority = // member inline _.Bind(task: Task<'T>, continuation: ('T -> ResumableTSC<'U>)) = ResumableTSC<'U>(fun sm -> - let mutable awaiter = task.GetAwaiter() - let mutable __stack_fin = true - Debug.logInfo "at Bind" - - if not awaiter.IsCompleted then - // This will yield with __stack_fin2 = false - // This will resume with __stack_fin2 = true - let __stack_fin2 = ResumableCode.Yield().Invoke(&sm) - __stack_fin <- __stack_fin2 - - Debug.logInfo ("at Bind: with __stack_fin = ", __stack_fin) - Debug.logInfo ("at Bind: this.completed = ", sm.Data.completed) - - if __stack_fin then - Debug.logInfo "at Bind: finished awaiting, calling continuation" - let result = awaiter.GetResult() - (continuation result).Invoke(&sm) - - else - Debug.logInfo "at Bind: await further" - - sm.Data.awaiter <- awaiter - sm.Data.current <- ValueNone - false) + let awaiter = task.GetAwaiter() + + // Same single code path as the ^TaskLike Bind, see there. + ResumableCode + .Combine( + ResumableTSC<'U>(fun sm -> + if awaiter.IsCompleted then + true + else + Debug.logInfo "at Bind: await further" + sm.Data.awaiter <- awaiter + sm.Data.current <- ValueNone + ResumableCode.Yield().Invoke(&sm)), + ResumableTSC<'U>(fun sm -> (continuation (awaiter.GetResult())).Invoke(&sm)) + ) + .Invoke(&sm)) member inline _.Bind(computation: Async<'T>, continuation: ('T -> ResumableTSC<'U>)) = ResumableTSC<'U>(fun sm -> - let mutable awaiter = Async.StartImmediateAsTask(computation, cancellationToken = sm.Data.cancellationToken).GetAwaiter() - - let mutable __stack_fin = true - Debug.logInfo "at Bind" - - if not awaiter.IsCompleted then - // This will yield with __stack_fin2 = false - // This will resume with __stack_fin2 = true - let __stack_fin2 = ResumableCode.Yield().Invoke(&sm) - __stack_fin <- __stack_fin2 - - Debug.logInfo ("at Bind: with __stack_fin = ", __stack_fin) - Debug.logInfo ("at Bind: this.completed = ", sm.Data.completed) - - if __stack_fin then - Debug.logInfo "at Bind: finished awaiting, calling continuation" - let result = awaiter.GetResult() - (continuation result).Invoke(&sm) - - else - Debug.logInfo "at Bind: await further" - - sm.Data.awaiter <- awaiter - sm.Data.current <- ValueNone - false) + let awaiter = Async.StartImmediateAsTask(computation, cancellationToken = sm.Data.cancellationToken).GetAwaiter() + + // Same single code path as the ^TaskLike Bind, see there. + ResumableCode + .Combine( + ResumableTSC<'U>(fun sm -> + if awaiter.IsCompleted then + true + else + Debug.logInfo "at Bind: await further" + sm.Data.awaiter <- awaiter + sm.Data.current <- ValueNone + ResumableCode.Yield().Invoke(&sm)), + ResumableTSC<'U>(fun sm -> (continuation (awaiter.GetResult())).Invoke(&sm)) + ) + .Invoke(&sm)) [] module TaskSeqBuilder =