This repository was archived by the owner on Nov 25, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathBackgroundParser.cs
More file actions
461 lines (408 loc) · 17.8 KB
/
BackgroundParser.cs
File metadata and controls
461 lines (408 loc) · 17.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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Razor.Parser.SyntaxTree;
using System.Web.Razor.Text;
using System.Web.Razor.Utils;
namespace System.Web.Razor.Editor
{
internal class BackgroundParser : IDisposable
{
private MainThreadState _main;
private BackgroundThread _bg;
public BackgroundParser(RazorEngineHost host, string fileName)
{
_main = new MainThreadState(fileName);
_bg = new BackgroundThread(_main, host, fileName);
_main.ResultsReady += (sender, args) => OnResultsReady(args);
}
/// <summary>
/// Fired on the main thread.
/// </summary>
public event EventHandler<DocumentParseCompleteEventArgs> ResultsReady;
public bool IsIdle
{
get { return _main.IsIdle; }
}
public void Start()
{
_bg.Start();
}
public void Cancel()
{
_main.Cancel();
}
public void QueueChange(TextChange change)
{
_main.QueueChange(change);
}
public void Dispose()
{
_main.Cancel();
}
public IDisposable SynchronizeMainThreadState()
{
return _main.Lock();
}
protected virtual void OnResultsReady(DocumentParseCompleteEventArgs args)
{
var handler = ResultsReady;
if (handler != null)
{
handler(this, args);
}
}
internal static bool TreesAreDifferent(Block leftTree, Block rightTree, IEnumerable<TextChange> changes)
{
return TreesAreDifferent(leftTree, rightTree, changes, CancellationToken.None);
}
internal static bool TreesAreDifferent(Block leftTree, Block rightTree, IEnumerable<TextChange> changes, CancellationToken cancelToken)
{
// Apply all the pending changes to the original tree
// PERF: If this becomes a bottleneck, we can probably do it the other way around,
// i.e. visit the tree and find applicable changes for each node.
foreach (TextChange change in changes)
{
cancelToken.ThrowIfCancellationRequested();
Span changeOwner = leftTree.LocateOwner(change);
// Apply the change to the tree
if (changeOwner == null)
{
return true;
}
EditResult result = changeOwner.EditHandler.ApplyChange(changeOwner, change, force: true);
changeOwner.ReplaceWith(result.EditedSpan);
}
// Now compare the trees
bool treesDifferent = !leftTree.EquivalentTo(rightTree);
return treesDifferent;
}
private abstract class ThreadStateBase
{
#if DEBUG
private int _id = -1;
#endif
protected ThreadStateBase()
{
}
[Conditional("DEBUG")]
protected void SetThreadId(int id)
{
#if DEBUG
_id = id;
#endif
}
[Conditional("DEBUG")]
protected void EnsureOnThread()
{
#if DEBUG
Debug.Assert(_id != -1, "SetThreadId was never called!");
Debug.Assert(Thread.CurrentThread.ManagedThreadId == _id, "Called from an unexpected thread!");
#endif
}
[Conditional("DEBUG")]
protected void EnsureNotOnThread()
{
#if DEBUG
Debug.Assert(_id != -1, "SetThreadId was never called!");
Debug.Assert(Thread.CurrentThread.ManagedThreadId != _id, "Called from an unexpected thread!");
#endif
}
}
private class MainThreadState : ThreadStateBase, IDisposable
{
private CancellationTokenSource _cancelSource = new CancellationTokenSource();
private ManualResetEventSlim _hasParcel = new ManualResetEventSlim(false);
private CancellationTokenSource _currentParcelCancelSource;
private string _fileName;
private object _stateLock = new object();
private IList<TextChange> _changes = new List<TextChange>();
public MainThreadState(string fileName)
{
_fileName = fileName;
SetThreadId(Thread.CurrentThread.ManagedThreadId);
}
public event EventHandler<DocumentParseCompleteEventArgs> ResultsReady;
public CancellationToken CancelToken
{
get { return _cancelSource.Token; }
}
public bool IsIdle
{
get
{
lock (_stateLock)
{
return _currentParcelCancelSource == null;
}
}
}
public void Cancel()
{
EnsureOnThread();
_cancelSource.Cancel();
}
public IDisposable Lock()
{
Monitor.Enter(_stateLock);
return new DisposableAction(() => Monitor.Exit(_stateLock));
}
public void QueueChange(TextChange change)
{
RazorEditorTrace.TraceLine("[M][{0}] Queuing Parse for: {1}", Path.GetFileName(_fileName), change);
EnsureOnThread();
lock (_stateLock)
{
// CurrentParcel token source is not null ==> There's a parse underway
if (_currentParcelCancelSource != null)
{
_currentParcelCancelSource.Cancel();
}
_changes.Add(change);
_hasParcel.Set();
}
}
public WorkParcel GetParcel()
{
EnsureNotOnThread(); // Only the background thread can get a parcel
_hasParcel.Wait(_cancelSource.Token);
_hasParcel.Reset();
lock (_stateLock)
{
// Create a cancellation source for this parcel
_currentParcelCancelSource = new CancellationTokenSource();
var changes = _changes;
_changes = new List<TextChange>();
return new WorkParcel(changes, _currentParcelCancelSource.Token);
}
}
public void ReturnParcel(DocumentParseCompleteEventArgs args)
{
lock (_stateLock)
{
// Clear the current parcel cancellation source
if (_currentParcelCancelSource != null)
{
_currentParcelCancelSource.Dispose();
_currentParcelCancelSource = null;
}
// If there are things waiting to be parsed, just don't fire the event because we're already out of date
if (_changes.Any())
{
return;
}
}
var handler = ResultsReady;
if (handler != null)
{
handler(this, args);
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_cancelSource.Dispose();
_hasParcel.Dispose();
}
}
}
private class BackgroundThread : ThreadStateBase
{
private MainThreadState _main;
private Thread _backgroundThread;
private CancellationToken _shutdownToken;
private RazorEngineHost _host;
private string _fileName;
private Block _currentParseTree;
private IList<TextChange> _previouslyDiscarded = new List<TextChange>();
public BackgroundThread(MainThreadState main, RazorEngineHost host, string fileName)
{
// Run on MAIN thread!
_main = main;
_backgroundThread = new Thread(WorkerLoop);
_shutdownToken = _main.CancelToken;
_host = host;
_fileName = fileName;
SetThreadId(_backgroundThread.ManagedThreadId);
}
// **** ANY THREAD ****
public void Start()
{
_backgroundThread.Start();
}
// **** BACKGROUND THREAD ****
private void WorkerLoop()
{
long? elapsedMs = null;
string fileNameOnly = Path.GetFileName(_fileName);
#if EDITOR_TRACING
Stopwatch sw = new Stopwatch();
#endif
try
{
RazorEditorTrace.TraceLine("[BG][{0}] Startup", fileNameOnly);
EnsureOnThread();
while (!_shutdownToken.IsCancellationRequested)
{
// Grab the parcel of work to do
WorkParcel parcel = _main.GetParcel();
if (parcel.Changes.Any())
{
RazorEditorTrace.TraceLine("[BG][{0}] {1} changes arrived", fileNameOnly, parcel.Changes.Count);
try
{
DocumentParseCompleteEventArgs args = null;
using (var linkedCancel = CancellationTokenSource.CreateLinkedTokenSource(_shutdownToken, parcel.CancelToken))
{
if (parcel != null && !linkedCancel.IsCancellationRequested)
{
// Collect ALL changes
#if EDITOR_TRACING
if (_previouslyDiscarded != null && _previouslyDiscarded.Any())
{
RazorEditorTrace.TraceLine("[BG][{0}] Collecting {1} discarded changes", fileNameOnly, _previouslyDiscarded.Count);
}
#endif
var allChanges = Enumerable.Concat(
_previouslyDiscarded ?? Enumerable.Empty<TextChange>(), parcel.Changes).ToList();
var finalChange = allChanges.LastOrDefault();
if (finalChange != null)
{
#if EDITOR_TRACING
sw.Start();
#endif
GeneratorResults results = ParseChange(finalChange.NewBuffer, linkedCancel.Token);
#if EDITOR_TRACING
sw.Stop();
elapsedMs = sw.ElapsedMilliseconds;
sw.Reset();
#endif
RazorEditorTrace.TraceLine(
"[BG][{0}] Parse Complete in {1}ms",
fileNameOnly,
elapsedMs.HasValue ? elapsedMs.Value.ToString() : "?");
if (results != null && !linkedCancel.IsCancellationRequested)
{
// Clear discarded changes list
_previouslyDiscarded = null;
// Take the current tree and check for differences
#if EDITOR_TRACING
sw.Start();
#endif
bool treeStructureChanged = _currentParseTree == null || TreesAreDifferent(_currentParseTree, results.Document, allChanges, parcel.CancelToken);
#if EDITOR_TRACING
sw.Stop();
elapsedMs = sw.ElapsedMilliseconds;
sw.Reset();
#endif
_currentParseTree = results.Document;
RazorEditorTrace.TraceLine("[BG][{0}] Trees Compared in {1}ms. Different = {2}",
fileNameOnly,
elapsedMs.HasValue ? elapsedMs.Value.ToString() : "?",
treeStructureChanged);
// Build Arguments
args = new DocumentParseCompleteEventArgs()
{
GeneratorResults = results,
SourceChange = finalChange,
TreeStructureChanged = treeStructureChanged
};
}
else
{
// Parse completed but we were cancelled in the mean time. Add these to the discarded changes set
RazorEditorTrace.TraceLine("[BG][{0}] Discarded {1} changes", fileNameOnly, allChanges.Count);
_previouslyDiscarded = allChanges;
}
#if CHECK_TREE
if (args != null)
{
// Rewind the buffer and sanity check the line mappings
finalChange.NewBuffer.Position = 0;
int lineCount = finalChange.NewBuffer.ReadToEnd().Split(new string[] { Environment.NewLine, "\r", "\n" }, StringSplitOptions.None).Count();
Debug.Assert(
!args.GeneratorResults.DesignTimeLineMappings.Any(pair => pair.Value.StartLine > lineCount),
"Found a design-time line mapping referring to a line outside the source file!");
Debug.Assert(
!args.GeneratorResults.Document.Flatten().Any(span => span.Start.LineIndex > lineCount),
"Found a span with a line number outside the source file");
Debug.Assert(
!args.GeneratorResults.Document.Flatten().Any(span => span.Start.AbsoluteIndex > parcel.NewBuffer.Length),
"Found a span with an absolute offset outside the source file");
}
#endif
}
}
}
if (args != null)
{
_main.ReturnParcel(args);
}
}
catch (OperationCanceledException)
{
}
}
else
{
RazorEditorTrace.TraceLine("[BG][{0}] no changes arrived?", fileNameOnly, parcel.Changes.Count);
Thread.Yield();
}
}
}
catch (OperationCanceledException)
{
// Do nothing. Just shut down.
}
finally
{
RazorEditorTrace.TraceLine("[BG][{0}] Shutdown", fileNameOnly);
// Clean up main thread resources
_main.Dispose();
}
}
private GeneratorResults ParseChange(ITextBuffer buffer, CancellationToken token)
{
EnsureOnThread();
// Create a template engine
RazorTemplateEngine engine = new RazorTemplateEngine(_host);
// Seek the buffer to the beginning
buffer.Position = 0;
try
{
return engine.GenerateCode(
input: buffer,
className: null,
rootNamespace: null,
sourceFileName: _fileName,
cancelToken: token);
}
catch (OperationCanceledException)
{
return null;
}
}
}
private class WorkParcel
{
public WorkParcel(IList<TextChange> changes, CancellationToken cancelToken)
{
Changes = changes;
CancelToken = cancelToken;
}
public CancellationToken CancelToken { get; private set; }
public IList<TextChange> Changes { get; private set; }
}
}
}