forked from Unity-Technologies/UnityCsReference
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompilationTask.cs
More file actions
710 lines (578 loc) · 26.8 KB
/
Copy pathCompilationTask.cs
File metadata and controls
710 lines (578 loc) · 26.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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using UnityEditor.Scripting.Compilers;
using UnityEngine.Profiling;
using Unity.Scripting.Compilation;
namespace UnityEditor.Scripting.ScriptCompilation
{
[Flags]
enum CompilationTaskOptions
{
None = 0,
StopOnFirstError = (1 << 0)
}
// CompilationTask represents one complete rebuild of all the ScriptAssembly's that are passed in the constructor.
// The ScriptAssembly's are built in correct order according to their ScriptAssembly dependencies.
class CompilationTask : IDisposable
{
enum CompilionTaskState
{
Started = 0,
Running = 1,
Finished = 2
}
List<ScriptAssembly> pendingAssemblies;
HashSet<ScriptAssembly> codeGenAssemblies;
HashSet<ScriptAssembly> compiledCodeGenAssemblies = new HashSet<ScriptAssembly>();
HashSet<ScriptAssembly> notCompiledCodeGenAssemblies = new HashSet<ScriptAssembly>();
Dictionary<ScriptAssembly, CompilerMessage[]> compiledAssemblies = new Dictionary<ScriptAssembly, CompilerMessage[]>();
Dictionary<ScriptAssembly, CompilerMessage[]> processedAssemblies = new Dictionary<ScriptAssembly, CompilerMessage[]>();
Dictionary<ScriptAssembly, ScriptCompilerBase> compilerTasks = new Dictionary<ScriptAssembly, ScriptCompilerBase>();
HashSet<ScriptAssembly> unchangedCompiledAssemblies = new HashSet<ScriptAssembly>();
List<PostProcessorTask> postProcessorTasks = new List<PostProcessorTask>();
List<PostProcessorTask> pendingPostProcessorTasks = new List<PostProcessorTask>();
ScriptAssembly[] scriptAssemblies;
string buildOutputDirectory;
object context;
int compilePhase = 0;
EditorScriptCompilationOptions options;
CompilationTaskOptions compilationTaskOptions;
int maxConcurrentCompilers;
CompilionTaskState state = CompilionTaskState.Started;
IILPostProcessing ilPostProcessing;
private readonly CompilerFactory compilerFactory;
StreamWriter logWriter;
public event Action<object> OnCompilationTaskStarted;
public event Action<object> OnCompilationTaskFinished;
public event Action<ScriptAssembly, int> OnBeforeCompilationStarted;
public event Action<ScriptAssembly, int> OnCompilationStarted;
public event Action<ScriptAssembly> OnPostProcessingStarted;
public event Action<ScriptAssembly, List<CompilerMessage>> OnCompilationFinished;
public bool Stopped { get; private set; }
public bool CompileErrors { get; private set; }
bool BuildingForEditor
{
get
{
return (options & EditorScriptCompilationOptions.BuildingForEditor) == EditorScriptCompilationOptions.BuildingForEditor;
}
}
bool UseReferenceAssemblies
{
get
{
return (options & EditorScriptCompilationOptions.BuildingUseReferenceAssemblies) == EditorScriptCompilationOptions.BuildingUseReferenceAssemblies;
}
}
public CompilationTask(ScriptAssembly[] scriptAssemblies,
ScriptAssembly[] codeGenAssemblies,
string buildOutputDirectory,
object context,
EditorScriptCompilationOptions options,
CompilationTaskOptions compilationTaskOptions,
int maxConcurrentCompilers,
IILPostProcessing ilPostProcessing,
CompilerFactory compilerFactory)
{
this.scriptAssemblies = scriptAssemblies;
pendingAssemblies = new List<ScriptAssembly>();
if (codeGenAssemblies != null)
this.codeGenAssemblies = new HashSet<ScriptAssembly>(codeGenAssemblies);
else
this.codeGenAssemblies = new HashSet<ScriptAssembly>();
// Try to queue codegen assemblies for compilation first,
// so they get compiled as soon as possible.
if (codeGenAssemblies != null && codeGenAssemblies.Count() > 0)
pendingAssemblies.AddRange(codeGenAssemblies);
pendingAssemblies.AddRange(scriptAssemblies);
CompileErrors = false;
this.buildOutputDirectory = buildOutputDirectory;
this.context = context;
this.options = options;
this.compilationTaskOptions = compilationTaskOptions;
this.maxConcurrentCompilers = maxConcurrentCompilers;
this.ilPostProcessing = ilPostProcessing;
this.compilerFactory = compilerFactory;
try
{
logWriter = File.CreateText(LogFilePath);
}
catch (Exception e)
{
Console.WriteLine($"Could not create text file {LogFilePath}\n{e}");
}
}
public ScriptAssembly[] ScriptAssemblies
{
get
{
return scriptAssemblies;
}
}
public HashSet<ScriptAssembly> CodeGenAssemblies
{
get
{
return codeGenAssemblies;
}
}
public bool AreAllCodegenAssembliesCompiled
{
get
{
return codeGenAssemblies.Count == compiledCodeGenAssemblies.Count;
}
}
string LogFilePath
{
get
{
return AssetPath.Combine(buildOutputDirectory, "CompilationLog.txt");
}
}
public void Dispose()
{
if (logWriter != null)
logWriter.Dispose();
}
public bool IsCompiling
{
get { return pendingAssemblies.Count > 0 || compilerTasks.Count > 0 || pendingPostProcessorTasks.Count > 0 || postProcessorTasks.Count > 0; }
}
public Dictionary<ScriptAssembly, CompilerMessage[]> CompilerMessages
{
get { return processedAssemblies; }
}
public void Stop()
{
if (Stopped)
return;
foreach (var task in compilerTasks)
{
var compiler = task.Value;
compiler.Dispose();
}
compilerTasks.Clear();
Stopped = true;
}
void HandleOnCompilationTaskStarted()
{
if (state == CompilionTaskState.Started)
{
if (OnCompilationTaskStarted != null)
OnCompilationTaskStarted(context);
state = CompilionTaskState.Running;
}
}
void HandleOnCompilationTaskFinished()
{
if (state == CompilionTaskState.Running)
{
if (OnCompilationTaskFinished != null)
OnCompilationTaskFinished(context);
state = CompilionTaskState.Finished;
}
}
// Returns true when compilation is finished due to one of these reasons
// * Was stopped (CompilationTask.Stopped will be true)
// * Compilation had errors (CompilationTask.CompileErrors will be true)
// * Compilation succesfully completed without errors.
public bool Poll()
{
HandleOnCompilationTaskStarted();
if (Stopped)
{
HandleOnCompilationTaskFinished();
return true;
}
Dictionary<ScriptAssembly, ScriptCompilerBase> finishedCompilerTasks = null;
// Check if any compiler processes are finished.
foreach (var task in compilerTasks)
{
var compiler = task.Value;
// Did compiler task finish?
if (compiler.Poll())
{
if (finishedCompilerTasks == null)
finishedCompilerTasks = new Dictionary<ScriptAssembly, ScriptCompilerBase>();
var assembly = task.Key;
finishedCompilerTasks.Add(assembly, compiler);
}
}
// Save compiler messages from finished compiler processes and check for compile errors.
if (finishedCompilerTasks != null)
foreach (var task in finishedCompilerTasks)
{
var assembly = task.Key;
var compiler = task.Value;
var messages = compiler.GetCompilerMessages();
var messagesList = messages.ToList();
assembly.HasCompileErrors = messagesList.Any(m => m.type == CompilerMessageType.Error);
compiledAssemblies.Add(assembly, messagesList.ToArray());
bool havePostProcessors = ilPostProcessing != null && ilPostProcessing.HasPostProcessors;
bool isCodeGenAssembly = codeGenAssemblies.Contains(assembly);
bool hasCompileErrors = messagesList.Any(m => m.type == CompilerMessageType.Error);
if (isCodeGenAssembly)
{
if (hasCompileErrors)
notCompiledCodeGenAssemblies.Add(assembly);
else
compiledCodeGenAssemblies.Add(assembly);
}
if (havePostProcessors &&
notCompiledCodeGenAssemblies.Count == 0 &&
!hasCompileErrors &&
!isCodeGenAssembly)
{
var assemblySourcePath = AssetPath.Combine(buildOutputDirectory, assembly.Filename);
var pdbSourcePath = AssetPath.Combine(buildOutputDirectory, assembly.PdbFilename);
try
{
if (assemblySourcePath != assembly.FullPath)
File.Copy(assemblySourcePath, assembly.FullPath, true);
if (pdbSourcePath != assembly.PdbFullPath)
File.Copy(pdbSourcePath, assembly.PdbFullPath, true);
var postProcessorTask = new PostProcessorTask(assembly, messagesList, buildOutputDirectory, ilPostProcessing);
pendingPostProcessorTasks.Add(postProcessorTask);
}
catch (IOException e)
{
UnityEngine.Debug.LogError($"Fail to copy {assemblySourcePath} or {pdbSourcePath} to {AssetPath.GetDirectoryName(assembly.FullPath)} before post processing the assembly. Skipping post processing.\n{e}");
// OnCompilationFinished callbacks might add more compiler messages
OnCompilationFinished?.Invoke(assembly, messagesList);
processedAssemblies.Add(assembly, messagesList.ToArray());
}
}
else
{
// OnCompilationFinished callbacks might add more compiler messages
OnCompilationFinished?.Invoke(assembly, messagesList);
processedAssemblies.Add(assembly, messagesList.ToArray());
}
if (!CompileErrors)
CompileErrors = assembly.HasCompileErrors;
try
{
var referenceAssemblyPath = AssetPath.Combine(buildOutputDirectory, assembly.ReferenceAssemblyFilename);
// If a reference assembly is built, check if it is unchanged
// since the previous compilation.
if (UseReferenceAssemblies &&
BuildingForEditor &&
File.Exists(referenceAssemblyPath))
{
Profiler.BeginSample("ReferenceAssemblyHelpers.IsReferenceAssemblyUnchanged");
bool isUnchanged = ReferenceAssemblyHelpers.IsReferenceAssemblyUnchanged(assembly, buildOutputDirectory);
Profiler.EndSample();
if (isUnchanged)
{
unchangedCompiledAssemblies.Add(assembly);
}
}
File.Delete(referenceAssemblyPath);
}
catch (Exception e)
{
UnityEngine.Debug.LogException(e);
}
// If a codgen / IL Post processor has compile errors, clear
// pending assemblies waiting for compilation and assemblies
// waiting to get post processed.
if (isCodeGenAssembly && hasCompileErrors)
{
pendingPostProcessorTasks.Clear();
pendingAssemblies.Clear();
}
compilerTasks.Remove(assembly);
compiler.Dispose();
}
if (ilPostProcessing != null && ilPostProcessing.HasPostProcessors)
{
PollPostProcessors();
}
// If StopOnFirstError is set, do not queue assemblies for compilation in case of compile errors.
bool stopOnFirstError = (compilationTaskOptions & CompilationTaskOptions.StopOnFirstError) == CompilationTaskOptions.StopOnFirstError;
if (stopOnFirstError && CompileErrors)
{
foreach (var pendingAssembly in pendingAssemblies)
{
if (UnityCodeGenHelpers.IsCodeGen(pendingAssembly.Filename))
notCompiledCodeGenAssemblies.Add(pendingAssembly);
}
pendingAssemblies.Clear();
if (FinishedCompilation)
{
HandleOnCompilationTaskFinished();
}
return FinishedCompilation;
}
// Queue pending assemblies for compilation if we have no running compilers or if compilers have finished.
if (compilerTasks.Count == 0 || (finishedCompilerTasks != null && finishedCompilerTasks.Count > 0))
QueuePendingAssemblies();
if (FinishedCompilation)
{
HandleOnCompilationTaskFinished();
}
return FinishedCompilation;
}
void PollPostProcessors()
{
if (pendingPostProcessorTasks.Count == 0 && postProcessorTasks.Count == 0)
return;
// Not all codegen assemblies have been compiled yet.
if (!AreAllCodegenAssembliesCompiled)
{
// If any codegen assemblies are not getting compiled, clear
// pending il post processing tasks.
if (notCompiledCodeGenAssemblies.Any())
pendingPostProcessorTasks.Clear();
return;
}
List<PostProcessorTask> startedPostProcessorTasks = null;
// Check if any pending post processors can be run
foreach (var postProcessorTask in pendingPostProcessorTasks)
{
if (RunningMaxConcurrentProcesses)
break;
var assembly = postProcessorTask.Assembly;
// We break out of this loop instead to continuing to ensure that
// OnCompilationFinished events are emitted in the same order as
// they finished compiling.
if (IsAnyProcessUsingAssembly(assembly))
break;
if (startedPostProcessorTasks == null)
{
startedPostProcessorTasks = new List<PostProcessorTask>();
}
startedPostProcessorTasks.Add(postProcessorTask);
postProcessorTask.Start();
LogStartInfo($"# Starting IL post processing on {assembly.Filename}", postProcessorTask.GetProcessStartInfo());
OnPostProcessingStarted?.Invoke(assembly);
postProcessorTasks.Add(postProcessorTask);
}
if (startedPostProcessorTasks != null)
foreach (var postProcessorTask in startedPostProcessorTasks)
{
pendingPostProcessorTasks.Remove(postProcessorTask);
}
HashSet<PostProcessorTask> finishedPostProcessorTasks = null;
foreach (var postProcessorTask in postProcessorTasks)
{
// We break out of this loop instead to continuing to ensure that
// OnCompilationFinished events are emitted in the same order as
// they finished compiling.
if (!postProcessorTask.Poll())
break;
// Do not copy the post processed assembly in OnCompilationFinished
// if any of the running compilers have a reference to the assembly.
// As we might copy it while the compiler has the assembly open.
if (IsAnyProcessUsingAssembly(postProcessorTask.Assembly))
break;
var messagesList = postProcessorTask.GetCompilerMessages();
// OnCompilationFinished callbacks might add more compiler messages
OnCompilationFinished?.Invoke(postProcessorTask.Assembly, messagesList);
processedAssemblies.Add(postProcessorTask.Assembly, messagesList.ToArray());
if (!CompileErrors)
CompileErrors = messagesList.Any(m => m.type == CompilerMessageType.Error);
if (finishedPostProcessorTasks == null)
finishedPostProcessorTasks = new HashSet<PostProcessorTask>();
finishedPostProcessorTasks.Add(postProcessorTask);
}
if (finishedPostProcessorTasks != null)
foreach (var finishedPostProcessorTask in finishedPostProcessorTasks)
{
finishedPostProcessorTask.Dispose();
postProcessorTasks.Remove(finishedPostProcessorTask);
}
}
bool FinishedCompilation
{
get
{
return pendingAssemblies.Count == 0 &&
compilerTasks.Count == 0 &&
postProcessorTasks.Count == 0 &&
pendingPostProcessorTasks.Count == 0;
}
}
bool RunningMaxConcurrentProcesses
{
get
{
return (compilerTasks.Count + postProcessorTasks.Count) >= maxConcurrentCompilers;
}
}
bool IsAnyProcessUsingAssembly(ScriptAssembly assembly)
{
if (IsAnyRunningCompilerUsingAssembly(assembly))
return true;
if (IsAnyRunningPostProcessorUsingAssembly(assembly))
return true;
return false;
}
bool IsAnyRunningCompilerUsingAssembly(ScriptAssembly assembly)
{
foreach (var compilerTask in compilerTasks)
{
var compilerAssembly = compilerTask.Key;
if (compilerAssembly.ScriptAssemblyReferences.Contains(assembly))
return true;
}
return false;
}
bool IsAnyRunningPostProcessorUsingAssembly(ScriptAssembly assembly)
{
foreach (var postProcessorTask in postProcessorTasks)
{
if (postProcessorTask.IsFinished)
continue;
var postProcessorAssembly = postProcessorTask.Assembly;
if (postProcessorAssembly.ScriptAssemblyReferences.Contains(assembly))
return true;
}
return false;
}
void QueuePendingAssemblies()
{
if (pendingAssemblies.Count == 0)
return;
List<ScriptAssembly> assemblyCompileQueue = null;
List<ScriptAssembly> removePendingAssemblies = null;
// Find assemblies that have all their references already compiled.
foreach (var pendingAssembly in pendingAssemblies)
{
bool compileAssembly = true;
int unchangedAssemblyReferencesCount = 0;
foreach (var reference in pendingAssembly.ScriptAssemblyReferences)
{
CompilerMessage[] messages;
if (unchangedCompiledAssemblies.Contains(reference))
{
unchangedAssemblyReferencesCount++;
continue;
}
if (!compiledAssemblies.TryGetValue(reference, out messages))
{
// If a reference is not compiling and not pending
// also remove this assembly from pending.
if (!compilerTasks.ContainsKey(reference) && !pendingAssemblies.Contains(reference))
{
if (removePendingAssemblies == null)
removePendingAssemblies = new List<ScriptAssembly>();
removePendingAssemblies.Add(pendingAssembly);
}
compileAssembly = false;
break;
}
// If reference has compile errors, do not compile the pending assembly.
bool compileErrors = messages.Any(m => m.type == CompilerMessageType.Error);
if (compileErrors)
{
if (removePendingAssemblies == null)
removePendingAssemblies = new List<ScriptAssembly>();
removePendingAssemblies.Add(pendingAssembly);
compileAssembly = false;
break;
}
}
// If the assembly exists and is up to date (no compile errors)
// and it was dirtied because it is a reference to one or more
// dirty assemblies and none of them changed, then we do not
// need to recompile the assembly.
// Most expensive checks at the bottom.
if (UseReferenceAssemblies &&
BuildingForEditor &&
!pendingAssembly.HasCompileErrors &&
pendingAssembly.DirtySource == DirtySource.DirtyReference &&
unchangedAssemblyReferencesCount > 0 &&
unchangedAssemblyReferencesCount == pendingAssembly.ScriptAssemblyReferences.Length &&
File.Exists(pendingAssembly.FullPath))
{
var assemblyOutputPath = AssetPath.Combine(pendingAssembly.OutputDirectory, pendingAssembly.Filename);
Console.WriteLine($"- Skipping compile {assemblyOutputPath} because all references are unchanged");
unchangedCompiledAssemblies.Add(pendingAssembly);
if (removePendingAssemblies == null)
removePendingAssemblies = new List<ScriptAssembly>();
removePendingAssemblies.Add(pendingAssembly);
compileAssembly = false;
}
if (compileAssembly)
{
if (assemblyCompileQueue == null)
assemblyCompileQueue = new List<ScriptAssembly>();
assemblyCompileQueue.Add(pendingAssembly);
}
}
if (removePendingAssemblies != null)
{
foreach (var assembly in removePendingAssemblies)
{
pendingAssemblies.Remove(assembly);
// If a codegen assembly was removed fro pending assemblies,
// clear all pending compilation and post processing.
if (codeGenAssemblies.Contains(assembly))
{
notCompiledCodeGenAssemblies.Add(assembly);
pendingPostProcessorTasks.Clear();
pendingAssemblies.Clear();
assemblyCompileQueue = null;
break;
}
}
// All pending assemblies were removed and no assemblies
// were queued for compilation.
if (assemblyCompileQueue == null)
return;
}
// No assemblies to compile, need to wait for more references to finish compiling.
if (assemblyCompileQueue == null)
{
if (compilerTasks.Count == 0)
throw new Exception("No pending assemblies queued for compilation and no compilers running. Compilation will never finish.");
return;
}
// Begin compiling any queued assemblies
foreach (var assembly in assemblyCompileQueue)
{
pendingAssemblies.Remove(assembly);
if (assembly.CallOnBeforeCompilationStarted && OnBeforeCompilationStarted != null)
OnBeforeCompilationStarted(assembly, compilePhase);
var compiler = compilerFactory.Create(assembly, buildOutputDirectory);
compilerTasks.Add(assembly, compiler);
// Start compiler process
compiler.BeginCompiling();
LogStartInfo($"# Starting compiling {assembly.Filename}", compiler.GetProcessStartInfo());
if (OnCompilationStarted != null)
OnCompilationStarted(assembly, compilePhase);
if (RunningMaxConcurrentProcesses)
break;
}
compilePhase++;
}
void LogStartInfo(string message, ProcessStartInfo startInfo)
{
try
{
if (startInfo == null)
{
logWriter.WriteLine(message);
logWriter.WriteLine($"Error: ProcessStartInfo is null");
logWriter.Flush();
return;
}
logWriter.WriteLine(message);
logWriter.WriteLine($"{startInfo.FileName} {startInfo.Arguments}");
logWriter.Flush();
}
catch (Exception e)
{
Console.WriteLine($"Writing to {LogFilePath} falied\n{e}");
}
}
}
}