-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathValueTaskValueOptionCE.fs
More file actions
582 lines (483 loc) · 22.8 KB
/
Copy pathValueTaskValueOptionCE.fs
File metadata and controls
582 lines (483 loc) · 22.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
namespace FsToolkit.ErrorHandling
open System
open System.Runtime.CompilerServices
open System.Threading
open System.Threading.Tasks
open Microsoft.FSharp.Core
open Microsoft.FSharp.Core.CompilerServices
open Microsoft.FSharp.Core.CompilerServices.StateMachineHelpers
open Microsoft.FSharp.Core.LanguagePrimitives.IntrinsicOperators
open Microsoft.FSharp.Control
open Microsoft.FSharp.Collections
open IcedTasks
/// ValueTask<'T voption>
type ValueTaskValueOption<'T> = ValueTask<'T voption>
[<Struct; NoComparison; NoEquality>]
type ValueTaskValueOptionStateMachineData<'T> =
[<DefaultValue(false)>]
val mutable Result: 'T voption voption
[<DefaultValue(false)>]
val mutable MethodBuilder: AsyncValueTaskValueOptionMethodBuilder<'T>
member this.IsResultNone =
match this.Result with
| ValueNone -> false
| ValueSome(ValueNone) -> true
| ValueSome _ -> false
member this.SetResult() =
match this.Result with
| ValueNone -> this.MethodBuilder.SetResult ValueNone
| ValueSome x -> this.MethodBuilder.SetResult x
member this.IsTaskCompleted = this.MethodBuilder.Task.IsCompleted
and AsyncValueTaskValueOptionMethodBuilder<'TOverall> =
AsyncValueTaskMethodBuilder<'TOverall voption>
and ValueTaskValueOptionStateMachine<'TOverall> =
ResumableStateMachine<ValueTaskValueOptionStateMachineData<'TOverall>>
and ValueTaskValueOptionResumptionFunc<'TOverall> =
ResumptionFunc<ValueTaskValueOptionStateMachineData<'TOverall>>
and ValueTaskValueOptionResumptionDynamicInfo<'TOverall> =
ResumptionDynamicInfo<ValueTaskValueOptionStateMachineData<'TOverall>>
and ValueTaskValueOptionCode<'TOverall, 'T> =
ResumableCode<ValueTaskValueOptionStateMachineData<'TOverall>, 'T>
type ValueTaskValueOptionBuilderBase() =
member inline _.Delay
(generator: unit -> ValueTaskValueOptionCode<'TOverall, 'T>)
: ValueTaskValueOptionCode<'TOverall, 'T> =
ValueTaskValueOptionCode<'TOverall, 'T>(fun sm -> (generator ()).Invoke(&sm))
/// Used to represent no-ops like the implicit empty "else" branch of an "if" expression.
[<DefaultValue>]
member inline _.Zero<'TOverall>() : ValueTaskValueOptionCode<'TOverall, unit> =
ValueTaskValueOptionCode<_, _>(fun sm ->
sm.Data.Result <- ValueSome(ValueSome Unchecked.defaultof<'TOverall>)
true
)
member inline _.Return(value: 'T) : ValueTaskValueOptionCode<'T, 'T> =
ValueTaskValueOptionCode<'T, _>(fun sm ->
sm.Data.Result <- ValueSome(ValueSome value)
true
)
/// Chains together a step with its following step.
/// Note that this requires that the first step has no result.
/// This prevents constructs like `task { return 1; return 2; }`.
member inline _.Combine
(
task1: ValueTaskValueOptionCode<'TOverall, unit>,
task2: ValueTaskValueOptionCode<'TOverall, 'T>
) : ValueTaskValueOptionCode<'TOverall, 'T> =
ResumableCode.Combine(
task1,
ValueTaskValueOptionCode<'TOverall, 'T>(fun sm ->
if sm.Data.IsResultNone then true else task2.Invoke(&sm)
)
)
/// Builds a step that executes the body while the condition predicate is true.
member inline _.While
([<InlineIfLambda>] condition: unit -> bool, body: ValueTaskValueOptionCode<'TOverall, unit>) : ValueTaskValueOptionCode<
'TOverall,
unit
>
=
let mutable keepGoing = true
ResumableCode.While(
(fun () ->
keepGoing
&& condition ()
),
ValueTaskValueOptionCode<_, _>(fun sm ->
if sm.Data.IsResultNone then
keepGoing <- false
sm.Data.SetResult()
true
else
body.Invoke(&sm)
)
)
/// Wraps a step in a try/with. This catches exceptions both in the evaluation of the function
/// to retrieve the step, and in the continuation of the step (if any).
member inline _.TryWith
(
body: ValueTaskValueOptionCode<'TOverall, 'T>,
catch: exn -> ValueTaskValueOptionCode<'TOverall, 'T>
) : ValueTaskValueOptionCode<'TOverall, 'T> =
ResumableCode.TryWith(body, catch)
/// Wraps a step in a try/finally. This catches exceptions both in the evaluation of the function
/// to retrieve the step, and in the continuation of the step (if any).
member inline _.TryFinally
(
body: ValueTaskValueOptionCode<'TOverall, 'T>,
[<InlineIfLambda>] compensation: unit -> unit
) : ValueTaskValueOptionCode<'TOverall, 'T> =
ResumableCode.TryFinally(
body,
ResumableCode<_, _>(fun _sm ->
compensation ()
true
)
)
member inline this.For
(sequence: seq<'T>, body: 'T -> ValueTaskValueOptionCode<'TOverall, unit>)
: ValueTaskValueOptionCode<'TOverall, unit> =
ResumableCode.Using(
sequence.GetEnumerator(),
// ... and its body is a while loop that advances the enumerator and runs the body on each element.
(fun e ->
this.While(
(fun () -> e.MoveNext()),
ValueTaskValueOptionCode<'TOverall, unit>(fun sm ->
(body e.Current).Invoke(&sm)
)
)
)
)
member inline internal this.TryFinallyAsync
(body: ValueTaskValueOptionCode<'TOverall, 'T>, compensation: unit -> ValueTask)
: ValueTaskValueOptionCode<'TOverall, 'T> =
ResumableCode.TryFinallyAsync(
body,
ResumableCode<_, _>(fun sm ->
if __useResumableCode then
let mutable __stack_condition_fin = true
let __stack_vtask = compensation ()
if not __stack_vtask.IsCompleted then
let mutable awaiter = __stack_vtask.GetAwaiter()
let __stack_yield_fin = ResumableCode.Yield().Invoke(&sm)
__stack_condition_fin <- __stack_yield_fin
if not __stack_condition_fin then
sm.Data.MethodBuilder.AwaitUnsafeOnCompleted(&awaiter, &sm)
__stack_condition_fin
else
let vtask = compensation ()
let mutable awaiter = vtask.GetAwaiter()
let cont =
ValueTaskValueOptionResumptionFunc<'TOverall>(fun sm ->
awaiter.GetResult()
|> ignore
true
)
// shortcut to continue immediately
if awaiter.IsCompleted then
true
else
sm.ResumptionDynamicInfo.ResumptionData <-
(awaiter :> ICriticalNotifyCompletion)
sm.ResumptionDynamicInfo.ResumptionFunc <- cont
false
)
)
member inline this.Using<'Resource, 'TOverall, 'T when 'Resource :> IAsyncDisposableNull>
(resource: 'Resource, body: 'Resource -> ValueTaskValueOptionCode<'TOverall, 'T>)
: ValueTaskValueOptionCode<'TOverall, 'T> =
this.TryFinallyAsync(
(fun sm -> (body resource).Invoke(&sm)),
(fun () ->
if not (isNull (box resource)) then
resource.DisposeAsync()
else
ValueTask()
)
)
member inline this.Source
(valueTaskValueOption: ValueTaskValueOption<'T>)
: ValueTaskValueOption<'T> =
valueTaskValueOption
type ValueTaskValueOptionBuilder() =
inherit ValueTaskValueOptionBuilderBase()
// This is the dynamic implementation - this is not used
// for statically compiled tasks. An executor (resumptionFuncExecutor) is
// registered with the state machine, plus the initial resumption.
// The executor stays constant throughout the execution, it wraps each step
// of the execution in a try/with. The resumption is changed at each step
// to represent the continuation of the computation.
static member RunDynamic(code: ValueTaskValueOptionCode<'T, 'T>) : ValueTaskValueOption<'T> =
let mutable sm = ValueTaskValueOptionStateMachine<'T>()
let initialResumptionFunc =
ValueTaskValueOptionResumptionFunc<'T>(fun sm -> code.Invoke(&sm))
let resumptionInfo =
{ new ValueTaskValueOptionResumptionDynamicInfo<_>(initialResumptionFunc) with
member info.MoveNext(sm) =
let mutable savedExn = null
try
sm.ResumptionDynamicInfo.ResumptionData <- null
let step = info.ResumptionFunc.Invoke(&sm)
// If the `sm.Data.MethodBuilder` has already been set somewhere else (like While/WhileDynamic), we shouldn't continue
if sm.Data.IsTaskCompleted then
()
elif step then
sm.Data.SetResult()
else
match sm.ResumptionDynamicInfo.ResumptionData with
| :? ICriticalNotifyCompletion as awaiter ->
let mutable awaiter = awaiter
sm.Data.MethodBuilder.AwaitUnsafeOnCompleted(&awaiter, &sm)
| awaiter -> assert not (isNull awaiter)
with exn ->
savedExn <- exn
// Run SetException outside the stack unwind, see https://github.com/dotnet/roslyn/issues/26567
match savedExn with
| null -> ()
| exn -> sm.Data.MethodBuilder.SetException exn
member _.SetStateMachine(sm, state) =
sm.Data.MethodBuilder.SetStateMachine(state)
}
sm.ResumptionDynamicInfo <- resumptionInfo
sm.Data.MethodBuilder <- AsyncValueTaskValueOptionMethodBuilder<'T>.Create()
sm.Data.MethodBuilder.Start(&sm)
sm.Data.MethodBuilder.Task
member inline _.Run(code: ValueTaskValueOptionCode<'T, 'T>) : ValueTaskValueOption<'T> =
if __useResumableCode then
__stateMachine<ValueTaskValueOptionStateMachineData<'T>, ValueTaskValueOption<'T>>
(MoveNextMethodImpl<_>(fun sm ->
//-- RESUMABLE CODE START
__resumeAt sm.ResumptionPoint
let mutable __stack_exn: ExceptionNull = null
try
let __stack_code_fin = code.Invoke(&sm)
if
__stack_code_fin
&& not sm.Data.IsTaskCompleted
then
sm.Data.SetResult()
with exn ->
__stack_exn <- exn
// Run SetException outside the stack unwind, see https://github.com/dotnet/roslyn/issues/26567
match __stack_exn with
| null -> ()
| exn -> sm.Data.MethodBuilder.SetException exn
//-- RESUMABLE CODE END
))
(SetStateMachineMethodImpl<_>(fun sm state ->
sm.Data.MethodBuilder.SetStateMachine(state)
))
(AfterCode<_, _>(fun sm ->
sm.Data.MethodBuilder <- AsyncValueTaskValueOptionMethodBuilder<'T>.Create()
sm.Data.MethodBuilder.Start(&sm)
sm.Data.MethodBuilder.Task
))
else
ValueTaskValueOptionBuilder.RunDynamic(code)
[<AutoOpen>]
module ValueTaskValueOptionBuilder =
/// <summary>
/// Builds a <c>ValueTask<'T voption></c> using the computation expression syntax.
/// </summary>
let valueTaskValueOption = ValueTaskValueOptionBuilder()
open Microsoft.FSharp.Control
open System
open System.Runtime.CompilerServices
open System.Threading.Tasks
open Microsoft.FSharp.Core
open Microsoft.FSharp.Core.CompilerServices
open Microsoft.FSharp.Core.CompilerServices.StateMachineHelpers
open Microsoft.FSharp.Core.LanguagePrimitives.IntrinsicOperators
[<AutoOpen>]
module ValueTaskValueOptionCEExtensionsLowPriority =
// Low priority extensions
type ValueTaskValueOptionBuilderBase with
[<NoEagerConstraintApplication>]
static member inline BindDynamic< ^TaskLike, 'TResult1, 'TResult2, ^Awaiter, 'TOverall
when ^TaskLike: (member GetAwaiter: unit -> ^Awaiter)
and ^Awaiter :> ICriticalNotifyCompletion
and ^Awaiter: (member get_IsCompleted: unit -> bool)
and ^Awaiter: (member GetResult: unit -> 'TResult1 voption)>
(
sm: byref<_>,
task: ^TaskLike,
continuation: ('TResult1 -> ValueTaskValueOptionCode<'TOverall, 'TResult2>)
) : bool =
let mutable awaiter = (^TaskLike: (member GetAwaiter: unit -> ^Awaiter) (task))
let cont =
(ValueTaskValueOptionResumptionFunc<'TOverall>(fun sm ->
let result =
(^Awaiter: (member GetResult: unit -> 'TResult1 voption) (awaiter))
match result with
| ValueSome result -> (continuation result).Invoke(&sm)
| ValueNone ->
sm.Data.Result <- ValueSome ValueNone
true
))
// shortcut to continue immediately
if (^Awaiter: (member get_IsCompleted: unit -> bool) (awaiter)) then
cont.Invoke(&sm)
else
sm.ResumptionDynamicInfo.ResumptionData <- (awaiter :> ICriticalNotifyCompletion)
sm.ResumptionDynamicInfo.ResumptionFunc <- cont
false
[<NoEagerConstraintApplication>]
member inline _.Bind< ^TaskLike, 'TResult1, 'TResult2, ^Awaiter, 'TOverall
when ^TaskLike: (member GetAwaiter: unit -> ^Awaiter)
and ^Awaiter :> ICriticalNotifyCompletion
and ^Awaiter: (member get_IsCompleted: unit -> bool)
and ^Awaiter: (member GetResult: unit -> 'TResult1 voption)>
(
task: ^TaskLike,
continuation: ('TResult1 -> ValueTaskValueOptionCode<'TOverall, 'TResult2>)
) : ValueTaskValueOptionCode<'TOverall, 'TResult2> =
ValueTaskValueOptionCode<'TOverall, _>(fun sm ->
if __useResumableCode then
//-- RESUMABLE CODE START
// Get an awaiter from the awaitable
let mutable awaiter = (^TaskLike: (member GetAwaiter: unit -> ^Awaiter) (task))
let mutable __stack_fin = true
if not (^Awaiter: (member get_IsCompleted: unit -> bool) (awaiter)) then
// This will yield with __stack_yield_fin = false
// This will resume with __stack_yield_fin = true
let __stack_yield_fin = ResumableCode.Yield().Invoke(&sm)
__stack_fin <- __stack_yield_fin
if __stack_fin then
let result =
(^Awaiter: (member GetResult: unit -> 'TResult1 voption) (awaiter))
match result with
| ValueSome result -> (continuation result).Invoke(&sm)
| ValueNone ->
sm.Data.Result <- ValueSome ValueNone
true
else
sm.Data.MethodBuilder.AwaitUnsafeOnCompleted(&awaiter, &sm)
false
else
ValueTaskValueOptionBuilderBase.BindDynamic<
^TaskLike,
'TResult1,
'TResult2,
^Awaiter,
'TOverall
>(
&sm,
task,
continuation
)
//-- RESUMABLE CODE END
)
[<NoEagerConstraintApplication>]
member inline this.ReturnFrom< ^TaskLike, ^Awaiter, 'T
when ^TaskLike: (member GetAwaiter: unit -> ^Awaiter)
and ^Awaiter :> ICriticalNotifyCompletion
and ^Awaiter: (member get_IsCompleted: unit -> bool)
and ^Awaiter: (member GetResult: unit -> 'T voption)>
(task: ^TaskLike)
: ValueTaskValueOptionCode<'T, 'T> =
this.Bind(task, (fun v -> this.Return v))
[<NoEagerConstraintApplication>]
member inline this.Source< ^TaskLike, ^Awaiter, 'T
when ^TaskLike: (member GetAwaiter: unit -> ^Awaiter)
and ^Awaiter :> ICriticalNotifyCompletion
and ^Awaiter: (member get_IsCompleted: unit -> bool)
and ^Awaiter: (member GetResult: unit -> 'T)>
(t: ^TaskLike)
: ValueTaskValueOption<'T> =
valueTask {
let! r = t
return ValueSome r
}
member inline _.Using<'Resource, 'TOverall, 'T when 'Resource :> IDisposableNull>
(resource: 'Resource, body: 'Resource -> ValueTaskValueOptionCode<'TOverall, 'T>)
=
ResumableCode.Using(resource, body)
[<AutoOpen>]
module ValueTaskValueOptionCEExtensionsHighPriority =
// High priority extensions
type ValueTaskValueOptionBuilderBase with
static member BindDynamic
(
sm: byref<_>,
task: ValueTaskValueOption<'TResult1>,
continuation: ('TResult1 -> ValueTaskValueOptionCode<'TOverall, 'TResult2>)
) : bool =
let mutable awaiter = task.GetAwaiter()
let cont =
(ValueTaskValueOptionResumptionFunc<'TOverall>(fun sm ->
let result = awaiter.GetResult()
match result with
| ValueSome result -> (continuation result).Invoke(&sm)
| ValueNone ->
sm.Data.Result <- ValueSome ValueNone
true
))
// shortcut to continue immediately
if awaiter.IsCompleted then
cont.Invoke(&sm)
else
sm.ResumptionDynamicInfo.ResumptionData <- (awaiter :> ICriticalNotifyCompletion)
sm.ResumptionDynamicInfo.ResumptionFunc <- cont
false
member inline _.Bind
(
task: ValueTaskValueOption<'TResult1>,
continuation: ('TResult1 -> ValueTaskValueOptionCode<'TOverall, 'TResult2>)
) : ValueTaskValueOptionCode<'TOverall, 'TResult2> =
ValueTaskValueOptionCode<'TOverall, _>(fun sm ->
if __useResumableCode then
//-- RESUMABLE CODE START
// Get an awaiter from the task
let mutable awaiter = task.GetAwaiter()
let mutable __stack_fin = true
if not awaiter.IsCompleted then
// This will yield with __stack_yield_fin = false
// This will resume with __stack_yield_fin = true
let __stack_yield_fin = ResumableCode.Yield().Invoke(&sm)
__stack_fin <- __stack_yield_fin
if __stack_fin then
let result = awaiter.GetResult()
match result with
| ValueSome result -> (continuation result).Invoke(&sm)
| ValueNone ->
sm.Data.Result <- ValueSome ValueNone
true
else
sm.Data.MethodBuilder.AwaitUnsafeOnCompleted(&awaiter, &sm)
false
else
ValueTaskValueOptionBuilderBase.BindDynamic(&sm, task, continuation)
//-- RESUMABLE CODE END
)
member inline this.BindReturn(x: ValueTaskValueOption<'T>, [<InlineIfLambda>] f) =
this.Bind(x, (fun x -> this.Return(f x)))
member inline _.MergeSources(t1: ValueTaskValueOption<'T>, t2: ValueTaskValueOption<'T1>) =
ValueTaskValueOption.zip t1 t2
member inline this.ReturnFrom
(task: ValueTaskValueOption<'T>)
: ValueTaskValueOptionCode<'T, 'T> =
this.Bind(task, (fun v -> this.Return v))
member inline _.Source(s: #seq<_>) = s
[<AutoOpen>]
module ValueTaskValueOptionCEExtensionsMediumPriority =
// Medium priority extensions
type ValueTaskValueOptionBuilderBase with
member inline this.Source(t: Task<'T>) : ValueTaskValueOption<'T> =
valueTask {
let! r = t
return ValueSome r
}
member inline this.Source(t: Task) : ValueTaskValueOption<unit> =
valueTask {
do! t
return ValueSome()
}
member inline this.Source(t: ValueTask<'T>) : ValueTaskValueOption<'T> =
valueTask {
let! r = t
return ValueSome r
}
member inline this.Source(t: ValueTask) : ValueTaskValueOption<unit> =
valueTask {
do! t
return ValueSome()
}
member inline this.Source(opt: 'T voption) : ValueTaskValueOption<'T> =
ValueTask<'T voption>(opt)
member inline this.Source(computation: Async<'T>) : ValueTaskValueOption<'T> =
ValueTask<'T voption>(
computation
|> Async.map ValueSome
|> Async.StartImmediateAsTask
)
[<AutoOpen>]
module ValueTaskValueOptionCEExtensionsHighPriority2 =
// High priority extensions 2
type ValueTaskValueOptionBuilderBase with
member inline this.Source(computation: Async<'T voption>) : ValueTaskValueOption<'T> =
ValueTask<'T voption>(
computation
|> Async.StartImmediateAsTask
)
member inline this.Source(taskValueOption: Task<'T voption>) : ValueTaskValueOption<'T> =
ValueTask<'T voption>(taskValueOption)