-
Notifications
You must be signed in to change notification settings - Fork 795
/
Copy pathBuildGraph.fs
299 lines (237 loc) · 10.7 KB
/
BuildGraph.fs
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
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.
module FSharp.Compiler.BuildGraph
open System
open System.Threading
open System.Threading.Tasks
open System.Diagnostics
open System.Globalization
open FSharp.Compiler.DiagnosticsLogger
open Internal.Utilities.Library
[<NoEquality; NoComparison>]
type NodeCode<'T> = Node of Async<'T>
let wrapThreadStaticInfo computation =
async {
let diagnosticsLogger = DiagnosticsThreadStatics.DiagnosticsLogger
let phase = DiagnosticsThreadStatics.BuildPhase
try
return! computation
finally
DiagnosticsThreadStatics.DiagnosticsLogger <- diagnosticsLogger
DiagnosticsThreadStatics.BuildPhase <- phase
}
type Async<'T> with
static member AwaitNodeCode(node: NodeCode<'T>) =
match node with
| Node(computation) -> wrapThreadStaticInfo computation
[<Sealed>]
type NodeCodeBuilder() =
static let zero = Node(async.Zero())
[<DebuggerHidden; DebuggerStepThrough>]
member _.Zero() : NodeCode<unit> = zero
[<DebuggerHidden; DebuggerStepThrough>]
member _.Delay(f: unit -> NodeCode<'T>) =
Node(
async.Delay(fun () ->
match f () with
| Node(p) -> p)
)
[<DebuggerHidden; DebuggerStepThrough>]
member _.Return value = Node(async.Return(value))
[<DebuggerHidden; DebuggerStepThrough>]
member _.ReturnFrom(computation: NodeCode<_>) = computation
[<DebuggerHidden; DebuggerStepThrough>]
member _.Bind(Node(p): NodeCode<'a>, binder: 'a -> NodeCode<'b>) : NodeCode<'b> =
Node(
async.Bind(
p,
fun x ->
match binder x with
| Node p -> p
)
)
[<DebuggerHidden; DebuggerStepThrough>]
member _.TryWith(Node(p): NodeCode<'T>, binder: exn -> NodeCode<'T>) : NodeCode<'T> =
Node(
async.TryWith(
p,
fun ex ->
match binder ex with
| Node p -> p
)
)
[<DebuggerHidden; DebuggerStepThrough>]
member _.TryFinally(Node(p): NodeCode<'T>, binder: unit -> unit) : NodeCode<'T> = Node(async.TryFinally(p, binder))
[<DebuggerHidden; DebuggerStepThrough>]
member _.For(xs: 'T seq, binder: 'T -> NodeCode<unit>) : NodeCode<unit> =
Node(
async.For(
xs,
fun x ->
match binder x with
| Node p -> p
)
)
[<DebuggerHidden; DebuggerStepThrough>]
member _.Combine(Node(p1): NodeCode<unit>, Node(p2): NodeCode<'T>) : NodeCode<'T> = Node(async.Combine(p1, p2))
[<DebuggerHidden; DebuggerStepThrough>]
member _.Using(value: CompilationGlobalsScope, binder: CompilationGlobalsScope -> NodeCode<'U>) =
Node(
async {
DiagnosticsThreadStatics.DiagnosticsLogger <- value.DiagnosticsLogger
DiagnosticsThreadStatics.BuildPhase <- value.BuildPhase
try
return! binder value |> Async.AwaitNodeCode
finally
(value :> IDisposable).Dispose()
}
)
[<DebuggerHidden; DebuggerStepThrough>]
member _.Using(value: IDisposable, binder: IDisposable -> NodeCode<'U>) =
Node(
async {
use _ = value
return! binder value |> Async.AwaitNodeCode
}
)
let node = NodeCodeBuilder()
[<AbstractClass; Sealed>]
type NodeCode private () =
static let cancellationToken = Node(wrapThreadStaticInfo Async.CancellationToken)
static member RunImmediate(computation: NodeCode<'T>, ct: CancellationToken) =
let diagnosticsLogger = DiagnosticsThreadStatics.DiagnosticsLogger
let phase = DiagnosticsThreadStatics.BuildPhase
try
try
let work =
async {
DiagnosticsThreadStatics.DiagnosticsLogger <- diagnosticsLogger
DiagnosticsThreadStatics.BuildPhase <- phase
return! computation |> Async.AwaitNodeCode
}
Async.StartImmediateAsTask(work, cancellationToken = ct).Result
finally
DiagnosticsThreadStatics.DiagnosticsLogger <- diagnosticsLogger
DiagnosticsThreadStatics.BuildPhase <- phase
with :? AggregateException as ex when ex.InnerExceptions.Count = 1 ->
raise (ex.InnerExceptions[0])
static member RunImmediateWithoutCancellation(computation: NodeCode<'T>) =
NodeCode.RunImmediate(computation, CancellationToken.None)
static member StartAsTask_ForTesting(computation: NodeCode<'T>, ?ct: CancellationToken) =
let diagnosticsLogger = DiagnosticsThreadStatics.DiagnosticsLogger
let phase = DiagnosticsThreadStatics.BuildPhase
try
let work =
async {
DiagnosticsThreadStatics.DiagnosticsLogger <- diagnosticsLogger
DiagnosticsThreadStatics.BuildPhase <- phase
return! computation |> Async.AwaitNodeCode
}
Async.StartAsTask(work, cancellationToken = defaultArg ct CancellationToken.None)
finally
DiagnosticsThreadStatics.DiagnosticsLogger <- diagnosticsLogger
DiagnosticsThreadStatics.BuildPhase <- phase
static member CancellationToken = cancellationToken
static member FromCancellable(computation: Cancellable<'T>) =
Node(wrapThreadStaticInfo (Cancellable.toAsync computation))
static member AwaitAsync(computation: Async<'T>) = Node(wrapThreadStaticInfo computation)
static member AwaitTask(task: Task<'T>) =
Node(wrapThreadStaticInfo (Async.AwaitTask task))
static member AwaitTask(task: Task) =
Node(wrapThreadStaticInfo (Async.AwaitTask task))
static member AwaitWaitHandle_ForTesting(waitHandle: WaitHandle) =
Node(wrapThreadStaticInfo (Async.AwaitWaitHandle(waitHandle)))
static member Sleep(ms: int) =
Node(wrapThreadStaticInfo (Async.Sleep(ms)))
static member Sequential(computations: NodeCode<'T> seq) =
node {
let results = ResizeArray()
for computation in computations do
let! res = computation
results.Add(res)
return results.ToArray()
}
static member Parallel(computations: NodeCode<'T> seq) =
computations |> Seq.map (fun (Node x) -> x) |> Async.Parallel |> Node
[<RequireQualifiedAccess>]
module GraphNode =
// We need to store the culture for the VS thread that is executing now,
// so that when the agent in the async lazy object picks up thread from the thread pool we can set the culture
let mutable culture = CultureInfo(CultureInfo.CurrentUICulture.Name)
let SetPreferredUILang (preferredUiLang: string option) =
match preferredUiLang with
| Some s ->
culture <- CultureInfo s
#if FX_RESHAPED_GLOBALIZATION
CultureInfo.CurrentUICulture <- culture
#else
Thread.CurrentThread.CurrentUICulture <- culture
#endif
| None -> ()
[<Sealed>]
type GraphNode<'T> private (computation: NodeCode<'T>, cachedResult: ValueOption<'T>, cachedResultNode: NodeCode<'T>) =
let mutable computation = computation
let mutable requestCount = 0
let mutable cachedResult = cachedResult
let mutable cachedResultNode: NodeCode<'T> = cachedResultNode
let isCachedResultNodeNotNull () =
not (obj.ReferenceEquals(cachedResultNode, null))
let semaphore = new SemaphoreSlim(1, 1)
member _.GetOrComputeValue() =
// fast path
if isCachedResultNodeNotNull () then
cachedResultNode
else
node {
Interlocked.Increment(&requestCount) |> ignore
try
let! ct = NodeCode.CancellationToken
// We must set 'taken' before any implicit cancellation checks
// occur, making sure we are under the protection of the 'try'.
// For example, NodeCode's 'try/finally' (TryFinally) uses async.TryFinally which does
// implicit cancellation checks even before the try is entered, as do the
// de-sugaring of 'do!' and other NodeCode constructs.
let mutable taken = false
try
do!
semaphore
.WaitAsync(ct)
.ContinueWith(
(fun _ -> taken <- true),
(TaskContinuationOptions.NotOnCanceled
||| TaskContinuationOptions.NotOnFaulted
||| TaskContinuationOptions.ExecuteSynchronously)
)
|> NodeCode.AwaitTask
match cachedResult with
| ValueSome value -> return value
| _ ->
let tcs = TaskCompletionSource<'T>()
let (Node(p)) = computation
Async.StartWithContinuations(
async {
Thread.CurrentThread.CurrentUICulture <- GraphNode.culture
return! p
},
(fun res ->
cachedResult <- ValueSome res
cachedResultNode <- node.Return res
computation <- Unchecked.defaultof<_>
tcs.SetResult(res)),
(fun ex -> tcs.SetException(ex)),
(fun _ -> tcs.SetCanceled()),
ct
)
return! tcs.Task |> NodeCode.AwaitTask
finally
if taken then
semaphore.Release() |> ignore
finally
Interlocked.Decrement(&requestCount) |> ignore
}
member _.TryPeekValue() = cachedResult
member _.HasValue = cachedResult.IsSome
member _.IsComputing = requestCount > 0
static member FromResult(result: 'T) =
let nodeResult = node.Return result
GraphNode(nodeResult, ValueSome result, nodeResult)
new(computation) = GraphNode(computation, ValueNone, Unchecked.defaultof<_>)