forked from Unity-Technologies/UnityCsReference
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEditorCompilation.cs
More file actions
1270 lines (1020 loc) · 54 KB
/
Copy pathEditorCompilation.cs
File metadata and controls
1270 lines (1020 loc) · 54 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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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.Linq;
using System.Runtime.InteropServices;
using UnityEditor.Modules;
using UnityEditor.Compilation;
using UnityEditor.Scripting.Compilers;
using UnityEditorInternal;
using CompilerMessage = UnityEditor.Scripting.Compilers.CompilerMessage;
using CompilerMessageType = UnityEditor.Scripting.Compilers.CompilerMessageType;
using Directory = System.IO.Directory;
using File = System.IO.File;
using IOException = System.IO.IOException;
namespace UnityEditor.Scripting.ScriptCompilation
{
class EditorCompilation
{
public enum CompileStatus
{
Idle,
Compiling,
CompilationStarted,
CompilationFailed,
CompilationComplete
}
public enum DeleteFileOptions
{
NoLogError = 0,
LogError = 1,
}
[StructLayout(LayoutKind.Sequential)]
public struct TargetAssemblyInfo
{
public string Name;
public AssemblyFlags Flags;
}
[StructLayout(LayoutKind.Sequential)]
public struct AssemblyCompilerMessages
{
public string assemblyFilename;
public CompilerMessage[] messages;
}
[StructLayout(LayoutKind.Sequential)]
public struct PackageAssembly
{
public string DirectoryPath;
public string Name;
public bool IncludeTestAssemblies;
}
[Flags]
public enum CompilationSetupErrorFlags
{
none = 0,
cyclicReferences = (1 << 0),
loadError = (1 << 0)
}
bool areAllScriptsDirty;
string projectDirectory = string.Empty;
string assemblySuffix = string.Empty;
private HashSet<string> allScripts = new HashSet<string>();
HashSet<string> dirtyScripts = new HashSet<string>();
HashSet<string> runScriptUpdaterAssemblies = new HashSet<string>();
PrecompiledAssembly[] precompiledAssemblies;
CustomScriptAssembly[] customScriptAssemblies;
CustomScriptAssembly[] packageCustomScriptAssemblies;
EditorBuildRules.TargetAssembly[] customTargetAssemblies; // TargetAssemblies for customScriptAssemblies and packageCustomScriptAssemblies.
PrecompiledAssembly[] unityAssemblies;
CompilationTask compilationTask;
string outputDirectory;
CompilationSetupErrorFlags setupErrorFlags = CompilationSetupErrorFlags.none;
List<Compilation.AssemblyBuilder> assemblyBuilders = new List<Compilation.AssemblyBuilder>();
static readonly string EditorTempPath = "Temp";
public Action<CompilationSetupErrorFlags> setupErrorFlagsChanged;
private PackageAssembly[] m_PackageAssemblies;
public event Action<string> assemblyCompilationStarted;
public event Action<string, UnityEditor.Compilation.CompilerMessage[]> assemblyCompilationFinished;
static EditorCompilation()
{
}
internal string GetAssemblyTimestampPath(string editorAssemblyPath)
{
return AssetPath.Combine(editorAssemblyPath, "BuiltinAssemblies.stamp");
}
internal void SetProjectDirectory(string projectDirectory)
{
this.projectDirectory = projectDirectory;
}
internal void SetAssemblySuffix(string assemblySuffix)
{
this.assemblySuffix = assemblySuffix;
}
public void SetAllScripts(string[] allScripts)
{
this.allScripts = new HashSet<string>(allScripts);
foreach (var dirtyScript in dirtyScripts)
this.allScripts.Add(dirtyScript);
}
public bool IsExtensionSupportedByCompiler(string extension)
{
var languages = ScriptCompilers.SupportedLanguages;
return languages.Count(l => l.GetExtensionICanCompile() == extension) > 0;
}
public string[] GetExtensionsSupportedByCompiler()
{
var languages = ScriptCompilers.SupportedLanguages;
return languages.Select(language => language.GetExtensionICanCompile()).ToArray();
}
public void DirtyPredefinedAssemblyScripts(EditorScriptCompilationOptions options, BuildTargetGroup platformGroup, BuildTarget platform)
{
var scriptAssemblySettings = CreateScriptAssemblySettings(platformGroup, platform, options);
var scriptAssemblies = GetAllScriptAssembliesOfType(scriptAssemblySettings, EditorBuildRules.TargetAssemblyType.Predefined);
foreach (var assembly in scriptAssemblies)
{
foreach (var script in assembly.Files)
{
dirtyScripts.Add(script);
}
}
}
public void DirtyAllScripts()
{
areAllScriptsDirty = true;
}
public void DirtyScript(string path)
{
allScripts.Add(path);
dirtyScripts.Add(path);
}
public void ClearDirtyScripts()
{
dirtyScripts.Clear();
areAllScriptsDirty = false;
}
public void RunScriptUpdaterOnAssembly(string assemblyFilename)
{
runScriptUpdaterAssemblies.Add(assemblyFilename);
}
public void SetAllUnityAssemblies(PrecompiledAssembly[] unityAssemblies)
{
this.unityAssemblies = unityAssemblies;
}
public void SetCompileScriptsOutputDirectory(string directory)
{
this.outputDirectory = directory;
}
public string GetCompileScriptsOutputDirectory()
{
if (string.IsNullOrEmpty(outputDirectory))
throw new Exception("Must set an output directory through SetCompileScriptsOutputDirectory before compiling");
return outputDirectory;
}
public void SetCompilationSetupErrorFlags(CompilationSetupErrorFlags flags)
{
var newFlags = setupErrorFlags | flags;
if (newFlags != setupErrorFlags)
{
setupErrorFlags = newFlags;
if (setupErrorFlagsChanged != null)
setupErrorFlagsChanged(setupErrorFlags);
}
}
public void ClearCompilationSetupErrorFlags(CompilationSetupErrorFlags flags)
{
var newFlags = setupErrorFlags & ~flags;
if (newFlags != setupErrorFlags)
{
setupErrorFlags = newFlags;
if (setupErrorFlagsChanged != null)
setupErrorFlagsChanged(setupErrorFlags);
}
}
public bool HaveSetupErrors()
{
return setupErrorFlags != CompilationSetupErrorFlags.none;
}
public void SetAllPrecompiledAssemblies(PrecompiledAssembly[] precompiledAssemblies)
{
this.precompiledAssemblies = precompiledAssemblies;
}
public PrecompiledAssembly[] GetAllPrecompiledAssemblies()
{
return this.precompiledAssemblies;
}
public TargetAssemblyInfo[] GetAllCompiledAndResolvedCustomTargetAssemblies()
{
if (customTargetAssemblies == null)
return new TargetAssemblyInfo[0];
var customTargetAssemblyCompiledPaths = new Dictionary<EditorBuildRules.TargetAssembly, string>();
foreach (var assembly in customTargetAssemblies)
{
var path = assembly.FullPath(outputDirectory, assemblySuffix);
// Collect all assemblies that have been compiled (exist on file system)
if (File.Exists(path))
customTargetAssemblyCompiledPaths.Add(assembly, path);
}
bool removed;
do
{
removed = false;
if (customTargetAssemblyCompiledPaths.Count > 0)
{
foreach (var assembly in customTargetAssemblies)
{
if (!customTargetAssemblyCompiledPaths.ContainsKey(assembly))
continue;
// Check for each compiled assembly that all it's references
// have also been compiled. If not, remove it from the list
// of compiled assemblies.
foreach (var reference in assembly.References)
{
if (!customTargetAssemblyCompiledPaths.ContainsKey(reference))
{
customTargetAssemblyCompiledPaths.Remove(assembly);
removed = true;
break;
}
}
}
}
}
while (removed);
var count = customTargetAssemblyCompiledPaths.Count;
var targetAssemblies = new TargetAssemblyInfo[customTargetAssemblyCompiledPaths.Count];
int index = 0;
foreach (var entry in customTargetAssemblyCompiledPaths)
{
var assembly = entry.Key;
targetAssemblies[index++] = ToTargetAssemblyInfo(assembly);
}
return targetAssemblies;
}
static CustomScriptAssembly LoadCustomScriptAssemblyFromJson(string path)
{
var json = File.ReadAllText(path);
try
{
var customScriptAssemblyData = CustomScriptAssemblyData.FromJson(json);
return CustomScriptAssembly.FromCustomScriptAssemblyData(path, customScriptAssemblyData);
}
catch (Exception e)
{
throw new Compilation.AssemblyDefinitionException(e.Message, path);
}
}
string[] CustomTargetAssembliesToFilePaths(IEnumerable<EditorBuildRules.TargetAssembly> targetAssemblies)
{
var customAssemblies = targetAssemblies.Select(a => FindCustomTargetAssemblyFromTargetAssembly(a));
var filePaths = customAssemblies.Select(a => a.FilePath).ToArray();
return filePaths;
}
string CustomTargetAssembliesToFilePaths(EditorBuildRules.TargetAssembly targetAssembly)
{
return FindCustomTargetAssemblyFromTargetAssembly(targetAssembly).FilePath;
}
void CheckCyclicAssemblyReferencesDFS(EditorBuildRules.TargetAssembly visitAssembly, HashSet<EditorBuildRules.TargetAssembly> visited)
{
if (visited.Contains(visitAssembly))
throw new Compilation.AssemblyDefinitionException("Assembly with cyclic references detected", CustomTargetAssembliesToFilePaths(visited));
visited.Add(visitAssembly);
foreach (var reference in visitAssembly.References)
{
if (reference.Filename == visitAssembly.Filename)
throw new Compilation.AssemblyDefinitionException("Assembly contains a references to itself", CustomTargetAssembliesToFilePaths(visitAssembly));
CheckCyclicAssemblyReferencesDFS(reference, visited);
}
visited.Remove(visitAssembly);
}
void CheckCyclicAssemblyReferences()
{
if (customTargetAssemblies == null || customTargetAssemblies.Length < 1)
return;
var visited = new HashSet<EditorBuildRules.TargetAssembly>();
try
{
foreach (var assembly in customTargetAssemblies)
CheckCyclicAssemblyReferencesDFS(assembly, visited);
}
catch (Exception e)
{
SetCompilationSetupErrorFlags(CompilationSetupErrorFlags.cyclicReferences);
throw e;
}
}
void UpdateCustomTargetAssemblies()
{
var allCustomScriptAssemblies = new List<CustomScriptAssembly>();
if (customScriptAssemblies != null)
allCustomScriptAssemblies.AddRange(customScriptAssemblies);
if (packageCustomScriptAssemblies != null)
{
if (customScriptAssemblies == null)
{
// There are no other custom script assemblies, add default customs script assemblies for all packages.
allCustomScriptAssemblies.AddRange(packageCustomScriptAssemblies.Select(a => CustomScriptAssembly.Create(a.Name, a.FilePath)));
}
else
{
foreach (var packageCustomScriptAssembly in packageCustomScriptAssemblies)
{
var packageAssembly = this.m_PackageAssemblies.Single(x => x.Name == packageCustomScriptAssembly.Name);
var pathPrefix = packageCustomScriptAssembly.PathPrefix.ToLowerInvariant();
// We have found an assembly definition file in the package directory, do not
// add a default custom script assembly for the package.
var customAssemblyInPackageRoot = customScriptAssemblies.SingleOrDefault(a => a.PathPrefix.ToLowerInvariant() == pathPrefix);
if (customAssemblyInPackageRoot != null)
{
continue;
}
allCustomScriptAssemblies.Add(CreatePackageCustomScriptAssembly(packageAssembly));
}
}
}
foreach (var assembly in allCustomScriptAssemblies)
{
try
{
if (m_PackageAssemblies != null && !assembly.PackageAssembly.HasValue)
{
var pathPrefix = assembly.PathPrefix.ToLowerInvariant();
foreach (var packageAssembly in m_PackageAssemblies)
{
var lower = AssetPath.ReplaceSeparators(packageAssembly.DirectoryPath).ToLowerInvariant();
if (pathPrefix.StartsWith(lower))
{
assembly.PackageAssembly = packageAssembly;
break;
}
}
}
foreach (var reference in assembly.References)
{
if (!allCustomScriptAssemblies.Any(a => a.Name == reference))
throw new Compilation.AssemblyDefinitionException(string.Format("Assembly has reference to non-existent assembly '{0}'", reference), assembly.FilePath);
}
}
catch (Exception e)
{
SetCompilationSetupErrorFlags(CompilationSetupErrorFlags.loadError);
throw e;
}
}
customTargetAssemblies = EditorBuildRules.CreateTargetAssemblies(allCustomScriptAssemblies);
ClearCompilationSetupErrorFlags(CompilationSetupErrorFlags.cyclicReferences);
}
public void SetAllCustomScriptAssemblyJsons(string[] paths)
{
var assemblies = new List<CustomScriptAssembly>();
ClearCompilationSetupErrorFlags(CompilationSetupErrorFlags.loadError);
foreach (var path in paths)
{
var fullPath = AssetPath.IsPathRooted(path) ? AssetPath.GetFullPath(path) : AssetPath.Combine(projectDirectory, path);
CustomScriptAssembly loadedCustomScriptAssembly = null;
try
{
loadedCustomScriptAssembly = LoadCustomScriptAssemblyFromJson(fullPath);
var duplicates = assemblies.Where(a => string.Equals(a.Name, loadedCustomScriptAssembly.Name, System.StringComparison.OrdinalIgnoreCase));
if (duplicates.Any())
{
var filePaths = new List<string>();
filePaths.Add(loadedCustomScriptAssembly.FilePath);
filePaths.AddRange(duplicates.Select(a => a.FilePath));
throw new Compilation.AssemblyDefinitionException(string.Format("Assembly with name '{0}' already exists", loadedCustomScriptAssembly.Name), filePaths.ToArray());
}
var samePrefixes = assemblies.Where(a => a.PathPrefix == loadedCustomScriptAssembly.PathPrefix);
if (samePrefixes.Any())
{
var filePaths = new List<string>();
filePaths.Add(loadedCustomScriptAssembly.FilePath);
filePaths.AddRange(samePrefixes.Select(a => a.FilePath));
throw new Compilation.AssemblyDefinitionException(string.Format("Folder '{0}' contains multiple assembly definition files", loadedCustomScriptAssembly.PathPrefix), filePaths.ToArray());
}
if (loadedCustomScriptAssembly.References == null)
loadedCustomScriptAssembly.References = new string[0];
if (loadedCustomScriptAssembly.References.Length != loadedCustomScriptAssembly.References.Distinct().Count())
throw new Compilation.AssemblyDefinitionException("Assembly has duplicate references", loadedCustomScriptAssembly.FilePath);
}
catch (Exception e)
{
SetCompilationSetupErrorFlags(CompilationSetupErrorFlags.loadError);
throw e;
}
assemblies.Add(loadedCustomScriptAssembly);
}
customScriptAssemblies = assemblies.ToArray();
UpdateCustomTargetAssemblies();
}
public void SetAllPackageAssemblies(PackageAssembly[] packageAssemblies)
{
m_PackageAssemblies = packageAssemblies;
this.packageCustomScriptAssemblies = m_PackageAssemblies.Select(CreatePackageCustomScriptAssembly).ToArray();
UpdateCustomTargetAssemblies();
}
private static CustomScriptAssembly CreatePackageCustomScriptAssembly(PackageAssembly packageAssembly)
{
var customScriptAssembly = CustomScriptAssembly.Create(packageAssembly.Name, AssetPath.ReplaceSeparators(packageAssembly.DirectoryPath));
customScriptAssembly.PackageAssembly = packageAssembly;
return customScriptAssembly;
}
// Delete all .dll's that aren't used anymore
public void DeleteUnusedAssemblies()
{
string fullEditorAssemblyPath = AssetPath.Combine(projectDirectory, GetCompileScriptsOutputDirectory());
if (!Directory.Exists(fullEditorAssemblyPath))
return;
var deleteFiles = Directory.GetFiles(fullEditorAssemblyPath).Select(f => AssetPath.ReplaceSeparators(f)).ToList();
string timestampPath = GetAssemblyTimestampPath(GetCompileScriptsOutputDirectory());
deleteFiles.Remove(AssetPath.Combine(projectDirectory, timestampPath));
var scriptAssemblies = GetAllScriptAssemblies(EditorScriptCompilationOptions.BuildingForEditor);
foreach (var assembly in scriptAssemblies)
{
if (assembly.Files.Length > 0)
{
string path = AssetPath.Combine(fullEditorAssemblyPath, assembly.Filename);
deleteFiles.Remove(path);
deleteFiles.Remove(MDBPath(path));
deleteFiles.Remove(PDBPath(path));
}
}
foreach (var path in deleteFiles)
DeleteFile(path);
}
public void CleanScriptAssemblies()
{
string fullEditorAssemblyPath = AssetPath.Combine(projectDirectory, GetCompileScriptsOutputDirectory());
if (!Directory.Exists(fullEditorAssemblyPath))
return;
foreach (var path in Directory.GetFiles(fullEditorAssemblyPath))
DeleteFile(path);
}
static void DeleteFile(string path, DeleteFileOptions fileOptions = DeleteFileOptions.LogError)
{
try
{
File.Delete(path);
}
catch (Exception)
{
if (fileOptions == DeleteFileOptions.LogError)
UnityEngine.Debug.LogErrorFormat("Could not delete file '{0}'\n", path);
}
}
static bool MoveOrReplaceFile(string sourcePath, string destinationPath)
{
bool fileMoved = true;
try
{
File.Move(sourcePath, destinationPath);
}
catch (IOException)
{
fileMoved = false;
}
if (!fileMoved)
{
fileMoved = true;
var backupFile = destinationPath + ".bak";
DeleteFile(backupFile, DeleteFileOptions.NoLogError); // Delete any previous backup files.
try
{
File.Replace(sourcePath, destinationPath, backupFile, true);
}
catch (IOException)
{
fileMoved = false;
}
// Try to delete backup file. Does not need to exist
// We will eventually delete the file in DeleteUnusedAssemblies.
DeleteFile(backupFile, DeleteFileOptions.NoLogError);
}
return fileMoved;
}
static string PDBPath(string dllPath)
{
return dllPath.Replace(".dll", ".pdb");
}
static string MDBPath(string dllPath)
{
return dllPath + ".mdb";
}
static bool CopyAssembly(string sourcePath, string destinationPath)
{
if (!MoveOrReplaceFile(sourcePath, destinationPath))
return false;
string sourceMdb = MDBPath(sourcePath);
string destinationMdb = MDBPath(destinationPath);
if (File.Exists(sourceMdb))
MoveOrReplaceFile(sourceMdb, destinationMdb);
else if (File.Exists(destinationMdb))
DeleteFile(destinationMdb);
string sourcePdb = PDBPath(sourcePath);
string destinationPdb = PDBPath(destinationPath);
if (File.Exists(sourcePdb))
MoveOrReplaceFile(sourcePdb, destinationPdb);
else if (File.Exists(destinationPdb))
DeleteFile(destinationPdb);
return true;
}
public CustomScriptAssembly FindCustomScriptAssemblyFromAssemblyName(string assemblyName)
{
List<CustomScriptAssembly> allCustomScriptAssemblies = new List<CustomScriptAssembly>();
if (customScriptAssemblies != null)
allCustomScriptAssemblies.AddRange(customScriptAssemblies);
if (packageCustomScriptAssemblies != null)
allCustomScriptAssemblies.AddRange(packageCustomScriptAssemblies);
var customScriptAssembly = allCustomScriptAssemblies.Single(a => AssemblyNameWithSuffix(a.Name) == AssetPath.GetAssemblyNameWithoutExtension(assemblyName));
return customScriptAssembly;
}
internal CustomScriptAssembly FindCustomScriptAssemblyFromScriptPath(string scriptPath)
{
var customTargetAssembly = EditorBuildRules.GetCustomTargetAssembly(scriptPath, projectDirectory, customTargetAssemblies);
var customScriptAssembly = customTargetAssembly != null ? FindCustomScriptAssemblyFromAssemblyName(customTargetAssembly.Filename) : null;
return customScriptAssembly;
}
internal CustomScriptAssembly FindCustomTargetAssemblyFromTargetAssembly(EditorBuildRules.TargetAssembly assembly)
{
var assemblyName = AssetPath.GetAssemblyNameWithoutExtension(assembly.Filename);
return FindCustomScriptAssemblyFromAssemblyName(assemblyName);
}
public bool CompileScripts(EditorScriptCompilationOptions options, BuildTargetGroup platformGroup, BuildTarget platform)
{
var scriptAssemblySettings = CreateScriptAssemblySettings(platformGroup, platform, options);
EditorBuildRules.TargetAssembly[] notCompiledTargetAssemblies = null;
bool result = CompileScripts(scriptAssemblySettings, EditorTempPath, options, ref notCompiledTargetAssemblies);
if (notCompiledTargetAssemblies != null)
foreach (var targetAssembly in notCompiledTargetAssemblies)
{
var customScriptAssembly = customScriptAssemblies.Single(a => a.Name == AssetPath.GetAssemblyNameWithoutExtension(targetAssembly.Filename));
var filePath = customScriptAssembly.FilePath;
if (filePath.StartsWith(projectDirectory))
filePath = filePath.Substring(projectDirectory.Length);
UnityEngine.Debug.LogWarning(string.Format("Script assembly '{0}' has not been compiled. Folder containing assembly definition file '{1}' contains script files for different script languages. Folder must only contain script files for one script language.", targetAssembly.Filename, filePath));
}
return result;
}
private static EditorBuildRules.TargetAssembly[] GetCustomAssembliesNotContainingTests(EditorBuildRules.TargetAssembly[] targetAssemblies)
{
return (targetAssemblies ?? Enumerable.Empty<EditorBuildRules.TargetAssembly>()).Where(x => (x.OptionalUnityReferences & OptionalUnityReferences.TestAssemblies) != OptionalUnityReferences.TestAssemblies).ToArray();
}
internal bool CompileScripts(ScriptAssemblySettings scriptAssemblySettings, string tempBuildDirectory, EditorScriptCompilationOptions options, ref EditorBuildRules.TargetAssembly[] notCompiledTargetAssemblies)
{
DeleteUnusedAssemblies();
IEnumerable<string> allDirtyScripts = areAllScriptsDirty ? allScripts.ToArray() : dirtyScripts.ToArray();
areAllScriptsDirty = false;
dirtyScripts.Clear();
if (!allDirtyScripts.Any() && runScriptUpdaterAssemblies.Count == 0)
return false;
var assemblies = new EditorBuildRules.CompilationAssemblies
{
UnityAssemblies = unityAssemblies,
PrecompiledAssemblies = precompiledAssemblies,
CustomTargetAssemblies = customTargetAssemblies,
PredefinedAssembliesCustomTargetReferences = GetCustomAssembliesNotContainingTests(customTargetAssemblies),
EditorAssemblyReferences = ModuleUtils.GetAdditionalReferencesForUserScripts()
};
var args = new EditorBuildRules.GenerateChangedScriptAssembliesArgs
{
AllSourceFiles = allScripts,
DirtySourceFiles = allDirtyScripts,
ProjectDirectory = projectDirectory,
Settings = scriptAssemblySettings,
Assemblies = assemblies,
RunUpdaterAssemblies = runScriptUpdaterAssemblies
};
var scriptAssemblies = EditorBuildRules.GenerateChangedScriptAssemblies(args);
notCompiledTargetAssemblies = args.NotCompiledTargetAssemblies.ToArray();
if (!scriptAssemblies.Any())
return false;
return CompileScriptAssemblies(scriptAssemblies, scriptAssemblySettings, tempBuildDirectory, options, CompilationTaskOptions.StopOnFirstError);
}
internal bool CompileCustomScriptAssemblies(EditorScriptCompilationOptions options, BuildTargetGroup platformGroup, BuildTarget platform)
{
var scriptAssemblySettings = CreateScriptAssemblySettings(platformGroup, platform, options);
return CompileCustomScriptAssemblies(scriptAssemblySettings, EditorTempPath, options, platformGroup, platform);
}
internal bool CompileCustomScriptAssemblies(ScriptAssemblySettings scriptAssemblySettings, string tempBuildDirectory, EditorScriptCompilationOptions options, BuildTargetGroup platformGroup, BuildTarget platform)
{
var scriptAssemblies = GetAllScriptAssembliesOfType(scriptAssemblySettings, EditorBuildRules.TargetAssemblyType.Custom);
return CompileScriptAssemblies(scriptAssemblies, scriptAssemblySettings, tempBuildDirectory, options, CompilationTaskOptions.None);
}
internal bool CompileScriptAssemblies(ScriptAssembly[] scriptAssemblies, ScriptAssemblySettings scriptAssemblySettings, string tempBuildDirectory, EditorScriptCompilationOptions options, CompilationTaskOptions compilationTaskOptions)
{
StopAllCompilation();
// Do no start compilation if there is an setup error.
if (setupErrorFlags != CompilationSetupErrorFlags.none)
return false;
CheckCyclicAssemblyReferences();
DeleteUnusedAssemblies();
if (!Directory.Exists(scriptAssemblySettings.OutputDirectory))
Directory.CreateDirectory(scriptAssemblySettings.OutputDirectory);
if (!Directory.Exists(tempBuildDirectory))
Directory.CreateDirectory(tempBuildDirectory);
// Compile to tempBuildDirectory
compilationTask = new CompilationTask(scriptAssemblies, tempBuildDirectory, options, compilationTaskOptions, UnityEngine.SystemInfo.processorCount);
compilationTask.OnCompilationStarted += (assembly, phase) =>
{
var assemblyOutputPath = AssetPath.Combine(scriptAssemblySettings.OutputDirectory, assembly.Filename);
Console.WriteLine("- Starting compile {0}", assemblyOutputPath);
InvokeAssemblyCompilationStarted(assemblyOutputPath);
};
compilationTask.OnCompilationFinished += (assembly, messages) =>
{
var assemblyOutputPath = AssetPath.Combine(scriptAssemblySettings.OutputDirectory, assembly.Filename);
Console.WriteLine("- Finished compile {0}", assemblyOutputPath);
if (runScriptUpdaterAssemblies.Contains(assembly.Filename))
runScriptUpdaterAssemblies.Remove(assembly.Filename);
if (messages.Any(m => m.type == CompilerMessageType.Error))
{
AddUnitySpecificErrorMessages(assembly, messages);
InvokeAssemblyCompilationFinished(assemblyOutputPath, messages);
return;
}
var buildingForEditor = scriptAssemblySettings.BuildingForEditor;
string enginePath = InternalEditorUtility.GetEngineCoreModuleAssemblyPath();
string unetPath = UnityEditor.EditorApplication.applicationContentsPath + "/UnityExtensions/Unity/Networking/UnityEngine.Networking.dll";
if (!Serialization.Weaver.WeaveUnetFromEditor(assembly, tempBuildDirectory, tempBuildDirectory, enginePath, unetPath, buildingForEditor))
{
messages.Add(new CompilerMessage { message = "UNet Weaver failed", type = CompilerMessageType.Error, file = assembly.FullPath, line = -1, column = -1 });
StopAllCompilation();
InvokeAssemblyCompilationFinished(assemblyOutputPath, messages);
return;
}
// Copy from tempBuildDirectory to assembly output directory
if (!CopyAssembly(AssetPath.Combine(tempBuildDirectory, assembly.Filename), assembly.FullPath))
{
messages.Add(new CompilerMessage { message = string.Format("Copying assembly from directory {0} to {1} failed", tempBuildDirectory, assembly.OutputDirectory), type = CompilerMessageType.Error, file = assembly.FullPath, line = -1, column = -1 });
StopCompilationTask();
InvokeAssemblyCompilationFinished(assemblyOutputPath, messages);
return;
}
InvokeAssemblyCompilationFinished(assemblyOutputPath, messages);
};
compilationTask.Poll();
return true;
}
void AddUnitySpecificErrorMessages(ScriptAssembly assembly, List<CompilerMessage> messages)
{
// error CS0227: Unsafe code requires the `unsafe' command line option to be specified
if (!messages.Any(m => m.type == CompilerMessageType.Error && m.message.Contains("CS0227")))
return;
var assemblyName = AssetPath.GetAssemblyNameWithoutExtension(assembly.Filename);
string unityUnsafeMessage;
try
{
var customScriptAssembly = FindCustomScriptAssemblyFromAssemblyName(assemblyName);
unityUnsafeMessage = string.Format("Enable \"Allow 'unsafe' code\" in the inspector for '{0}' to fix this error.", customScriptAssembly.FilePath);
}
catch
{
unityUnsafeMessage = "Enable \"Allow 'unsafe' code\" in Player Settings to fix this error.";
}
List<CompilerMessage> newMessages = new List<CompilerMessage>();
foreach (var message in messages)
{
if (message.type == CompilerMessageType.Error && message.message.Contains("CS0227"))
{
var newMessage = new CompilerMessage(message);
newMessage.message += ". " + unityUnsafeMessage;
newMessages.Add(newMessage);
}
else
{
newMessages.Add(message);
}
}
messages.Clear();
messages.AddRange(newMessages);
}
public void InvokeAssemblyCompilationStarted(string assemblyOutputPath)
{
if (assemblyCompilationStarted != null)
assemblyCompilationStarted(assemblyOutputPath);
}
public void InvokeAssemblyCompilationFinished(string assemblyOutputPath, List<CompilerMessage> messages)
{
if (assemblyCompilationFinished != null)
{
var convertedMessages = ConvertCompilerMessages(messages);
assemblyCompilationFinished(assemblyOutputPath, convertedMessages);
}
}
public bool AreAllScriptsDirty()
{
return areAllScriptsDirty;
}
public bool DoesProjectFolderHaveAnyDirtyScripts()
{
return (areAllScriptsDirty && allScripts.Count > 0) || dirtyScripts.Count > 0;
}
public bool DoesProjectFolderHaveAnyScripts()
{
return allScripts != null && allScripts.Count > 0;
}
ScriptAssemblySettings CreateScriptAssemblySettings(BuildTargetGroup buildTargetGroup, BuildTarget buildTarget, EditorScriptCompilationOptions options)
{
var defines = InternalEditorUtility.GetCompilationDefines(options, buildTargetGroup, buildTarget);
var predefinedAssembliesCompilerOptions = new ScriptCompilerOptions();
if ((options & EditorScriptCompilationOptions.BuildingPredefinedAssembliesAllowUnsafeCode) == EditorScriptCompilationOptions.BuildingPredefinedAssembliesAllowUnsafeCode)
predefinedAssembliesCompilerOptions.AllowUnsafeCode = true;
var settings = new ScriptAssemblySettings
{
BuildTarget = buildTarget,
BuildTargetGroup = buildTargetGroup,
OutputDirectory = GetCompileScriptsOutputDirectory(),
Defines = defines,
ApiCompatibilityLevel = PlayerSettings.GetApiCompatibilityLevel(buildTargetGroup),
CompilationOptions = options,
PredefinedAssembliesCompilerOptions = predefinedAssembliesCompilerOptions,
FilenameSuffix = assemblySuffix,
OptionalUnityReferences = ToOptionalUnityReferences(options),
};
return settings;
}
ScriptAssemblySettings CreateEditorScriptAssemblySettings(EditorScriptCompilationOptions options)
{
return CreateScriptAssemblySettings(EditorUserBuildSettings.activeBuildTargetGroup, EditorUserBuildSettings.activeBuildTarget, options);
}
public AssemblyCompilerMessages[] GetCompileMessages()
{
if (compilationTask == null)
return null;
var result = new AssemblyCompilerMessages[compilationTask.CompilerMessages.Count];
int index = 0;
foreach (var entry in compilationTask.CompilerMessages)
{
var assembly = entry.Key;
var messages = entry.Value;
result[index++] = new AssemblyCompilerMessages { assemblyFilename = assembly.Filename, messages = messages };
}
// Sort compiler messages by assemby filename to make the order deterministic.
Array.Sort(result, (m1, m2) => String.Compare(m1.assemblyFilename, m2.assemblyFilename));
return result;
}
public bool IsCompilationPending()
{
// If there were any errors in setting up the compilation, then return false.
if (setupErrorFlags != CompilationSetupErrorFlags.none)
return false;
// If we have dirty scripts or script updater has marked assemblies for updated,
// then compilation will trigger on next TickCompilationPipeline.
return DoesProjectFolderHaveAnyDirtyScripts() || runScriptUpdaterAssemblies.Count() > 0;
}
public bool IsAnyAssemblyBuilderCompiling()
{
if (assemblyBuilders.Count > 0)
{
bool isCompiling = false;
var removeAssemblyBuilders = new List<Compilation.AssemblyBuilder>();
// Check status of compile tasks
foreach (var assemblyBuilder in assemblyBuilders)
{
var status = assemblyBuilder.status;
if (status == Compilation.AssemblyBuilderStatus.IsCompiling)
isCompiling = true;
else if (status == Compilation.AssemblyBuilderStatus.Finished)
removeAssemblyBuilders.Add(assemblyBuilder);
}
// Remove all compile tasks that finished compiling.
if (removeAssemblyBuilders.Count > 0)
assemblyBuilders.RemoveAll(t => removeAssemblyBuilders.Contains(t));
return isCompiling;
}
return false;
}
public bool IsCompiling()
{
// Native code expects IsCompiling to be true after marking scripts as dirty,
// therefore return true if the compilation is pending
return IsCompilationTaskCompiling() || IsCompilationPending() || IsAnyAssemblyBuilderCompiling();
}
public bool IsCompilationTaskCompiling()
{
return compilationTask != null && compilationTask.IsCompiling;
}
public void StopAllCompilation()
{
StopCompilationTask();
compilationTask = null;
}
public void StopCompilationTask()
{
if (compilationTask == null)
return;
compilationTask.Stop();
}
internal static OptionalUnityReferences ToOptionalUnityReferences(EditorScriptCompilationOptions editorScriptCompilationOptions)
{
var optinalUnityReferences = OptionalUnityReferences.None;
var buildingIncludingTestAssemblies = (editorScriptCompilationOptions & EditorScriptCompilationOptions.BuildingIncludingTestAssemblies) == EditorScriptCompilationOptions.BuildingIncludingTestAssemblies;
if (buildingIncludingTestAssemblies)
{
optinalUnityReferences |= OptionalUnityReferences.TestAssemblies;
}
return optinalUnityReferences;
}
public CompileStatus TickCompilationPipeline(EditorScriptCompilationOptions options, BuildTargetGroup platformGroup, BuildTarget platform)
{
// Return CompileStatus.Compiling if any compile task is still compiling.
// This ensures that the compile tasks finish compiling before any
// scripts in the Assets folder are compiled and a domain reload
// is triggered.
if (IsAnyAssemblyBuilderCompiling())
return CompileStatus.Compiling;
// If we are not currently compiling and there are dirty scripts, start compilation.
if (!IsCompilationTaskCompiling() && IsCompilationPending())
{
if (CompileScripts(options, platformGroup, platform))
return CompileStatus.CompilationStarted;