forked from Unity-Technologies/UnityCsReference
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomScriptAssembly.cs
More file actions
585 lines (478 loc) · 23.6 KB
/
Copy pathCustomScriptAssembly.cs
File metadata and controls
585 lines (478 loc) · 23.6 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
// 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.Linq;
using UnityEditor.Build;
using UnityEditor.Compilation;
using UnityEditor.Modules;
using UnityEditor.Scripting.Compilers;
using UnityEditorInternal;
using DiscoveredTargetInfo = UnityEditor.BuildTargetDiscovery.DiscoveredTargetInfo;
namespace UnityEditor.Scripting.ScriptCompilation
{
// https://docs.microsoft.com/en-us/cpp/windows/changing-a-symbol-or-symbol-name-id
class SymbolNameRestrictions
{
private const int k_MaxLength = 247;
public static bool IsValid(string name)
{
if (string.IsNullOrEmpty(name))
{
return false;
}
if (name.Length > k_MaxLength)
{
return false;
}
// Invalid if the first character is a number.
if (char.IsNumber(name[0]))
{
return false;
}
foreach (var chr in name)
{
// Skip if it's a letter.
if (char.IsLetter(chr))
continue;
// Skip if it's a number.
if (char.IsNumber(chr))
continue;
// Skip if it's an underscore.
if (chr == '_')
continue;
// Invalid for unsupported characters.
return false;
}
return true;
}
}
#pragma warning disable 649
[Serializable]
class VersionDefine
{
public string name;
public string expression;
public string define;
}
[System.Serializable]
class CustomScriptAssemblyData
{
public string name;
public string rootNamespace;
public string[] references;
public string[] includePlatforms;
public string[] excludePlatforms;
public bool allowUnsafeCode;
public bool overrideReferences;
public string[] precompiledReferences;
public bool autoReferenced;
public string[] defineConstraints;
public VersionDefine[] versionDefines;
public bool noEngineReferences;
static Dictionary<string, string> renamedReferences = new Dictionary<string, string>(StringComparer.Ordinal);
static CustomScriptAssemblyData()
{
renamedReferences["Unity.RenderPipelines.Lightweight.Editor"] = "Unity.RenderPipelines.Universal.Editor";
renamedReferences["Unity.RenderPipelines.Lightweight.Runtime"] = "Unity.RenderPipelines.Universal.Runtime";
}
public static CustomScriptAssemblyData FromJson(string json)
{
var assemblyData = FromJsonNoFieldValidation(json);
assemblyData.ValidateFields();
return assemblyData;
}
public static CustomScriptAssemblyData FromJsonNoFieldValidation(string json)
{
var assemblyData = new CustomScriptAssemblyWithLegacyData();
assemblyData.autoReferenced = true;
UnityEngine.JsonUtility.FromJsonOverwrite(json, assemblyData);
UpdateRenamedReferences(assemblyData);
assemblyData.UpdateLegacyData();
if (assemblyData == null)
throw new System.Exception("Json file does not contain an assembly definition");
return assemblyData;
}
public void ValidateFields()
{
if (string.IsNullOrEmpty(name))
throw new System.Exception("Required property 'name' not set");
if ((excludePlatforms != null && excludePlatforms.Length > 0) &&
(includePlatforms != null && includePlatforms.Length > 0))
throw new System.Exception("Both 'excludePlatforms' and 'includePlatforms' are set.");
if (autoReferenced && UnityCodeGenHelpers.IsCodeGen(name))
{
throw new Exception($"Assembly '{name}' is a CodeGen assembly and cannot be Auto Referenced");
}
}
public static string ToJson(CustomScriptAssemblyData data)
{
return UnityEngine.JsonUtility.ToJson(data, true);
}
static void UpdateRenamedReferences(CustomScriptAssemblyData data)
{
if (data.references == null || data.references.Length == 0)
return;
HashSet<string> additionalReferences = null;
for (int i = 0; i < data.references.Length; ++i)
{
var reference = data.references[i];
string newReference;
if (!renamedReferences.TryGetValue(reference, out newReference))
continue;
if (additionalReferences == null)
additionalReferences = new HashSet<string>();
additionalReferences.Add(newReference);
}
if (additionalReferences != null && additionalReferences.Count > 0)
{
for (int i = 0; i < data.references.Length; ++i)
{
var reference = data.references[i];
if (additionalReferences.Contains(reference))
additionalReferences.Remove(reference);
}
if (additionalReferences.Count > 0)
data.references = data.references.Concat(additionalReferences).ToArray();
}
}
[Serializable]
private class CustomScriptAssemblyWithLegacyData : CustomScriptAssemblyData
{
public string[] optionalUnityReferences;
public string Tooltip { get; private set; }
public void UpdateLegacyData()
{
if (optionalUnityReferences != null && optionalUnityReferences.Any())
{
autoReferenced = false;
overrideReferences = true;
references = references ?? new string[0];
precompiledReferences = precompiledReferences ?? new string[0];
defineConstraints = defineConstraints ?? new string[0];
AddTo(ref references, "UnityEngine.TestRunner", "UnityEditor.TestRunner");
AddTo(ref precompiledReferences, "nunit.framework.dll");
AddTo(ref defineConstraints, "UNITY_INCLUDE_TESTS");
}
}
private void AddTo(ref string[] array, params string[] additionalValues)
{
var z = new string[array.Length + additionalValues.Length];
array.CopyTo(z, 0);
additionalValues.CopyTo(z, array.Length);
array = z;
}
}
}
struct CustomScriptAssemblyPlatform
{
public string Name { get; private set; }
public string DisplayName { get; private set; }
public BuildTarget BuildTarget { get; private set; }
public bool HasSubTarget { get; private set; }
public int SubTarget { get; private set; }
public CustomScriptAssemblyPlatform(string name, string displayName, BuildTarget buildTarget, bool hasSubTarget = false, int subTarget = 0) : this()
{
Name = name;
DisplayName = displayName;
BuildTarget = buildTarget;
HasSubTarget = hasSubTarget;
SubTarget = subTarget;
}
public CustomScriptAssemblyPlatform(string name, BuildTarget buildTarget, bool hasSubTarget = false, int subTarget = 0) : this(name, name, buildTarget, hasSubTarget, subTarget) {}
}
[DebuggerDisplay("{Name}")]
class CustomScriptAssembly
{
public string FilePath { get; set; }
public string PathPrefix { get; set; }
public string Name { get; set; }
public string RootNamespace { get; set; }
public string GUID { get; set; }
public string[] References { get; set; }
public string[] AdditionalPrefixes { get; set; }
public CustomScriptAssemblyPlatform[] IncludePlatforms { get; set; }
public CustomScriptAssemblyPlatform[] ExcludePlatforms { get; set; }
public AssetPathMetaData AssetPathMetaData { get; set; }
public ScriptCompilerOptions CompilerOptions { get; set; } = new ScriptCompilerOptions();
public bool OverrideReferences { get; set; }
public string[] PrecompiledReferences { get; set; }
public bool AutoReferenced { get; set; }
public string[] DefineConstraints { get; set; }
public VersionDefine[] VersionDefines { get; set; }
public string[] ResponseFileDefines { get; set; }
public bool NoEngineReferences { get; set; }
private AssemblyFlags assemblyFlags = AssemblyFlags.None;
public bool IsPredefined { get; set; }
public AssemblyFlags AssemblyFlags
{
get
{
if (assemblyFlags != AssemblyFlags.None)
return assemblyFlags;
assemblyFlags = AssemblyFlags.UserAssembly;
if (IncludePlatforms != null && IncludePlatforms.Length == 1 && IncludePlatforms[0].BuildTarget == BuildTarget.NoTarget)
assemblyFlags |= AssemblyFlags.EditorOnly;
if (OverrideReferences)
{
assemblyFlags |= AssemblyFlags.ExplicitReferences;
}
if (!AutoReferenced)
{
assemblyFlags |= AssemblyFlags.ExplicitlyReferenced;
}
if (NoEngineReferences)
{
assemblyFlags |= AssemblyFlags.NoEngineReferences;
}
bool rootFolder, immutable;
bool imported = AssetDatabase.GetAssetFolderInfo(PathPrefix, out rootFolder, out immutable);
// Do not emit warnings for immutable (package) folders,
// as the user cannot do anything to fix them.
if (imported && immutable)
{
assemblyFlags |= AssemblyFlags.SuppressCompilerWarnings;
}
return assemblyFlags;
}
}
public static List<CustomScriptAssemblyPlatform> Platforms { get; private set; }
public static CustomScriptAssemblyPlatform[] DeprecatedPlatforms { get; private set; }
static CustomScriptAssembly()
{
// When removing a platform from Platforms, please add it to DeprecatedPlatforms.
DiscoveredTargetInfo[] buildTargetList = BuildTargetDiscovery.GetBuildTargetInfoList();
// Need extra slots in array for Editor target and subtarget variants which are not included in the build target list
const int numEditorTargets = 1;
Platforms = new List<CustomScriptAssemblyPlatform>(buildTargetList.Length + numEditorTargets)
{
new ("Editor", BuildTarget.NoTarget)
};
for (int i = 0; i < buildTargetList.Length; i++)
{
// normal case
Platforms.Add(
new CustomScriptAssemblyPlatform(
BuildTargetDiscovery.GetScriptAssemblyName(buildTargetList[i]),
buildTargetList[i].niceName,
buildTargetList[i].buildTargetPlatformVal)
);
var extensionModule =
ModuleManager.FindPlatformSupportModule(
ModuleManager.GetTargetStringFromBuildTarget(buildTargetList[i].buildTargetPlatformVal));
// if this build target has extra custom assembly targets, append those
if(extensionModule != null)
{
var extraScriptAssemblyPlatforms = extensionModule.GetExtraScriptAssemblyPlatforms(buildTargetList[i].buildTargetPlatformVal);
if (extraScriptAssemblyPlatforms != null && extraScriptAssemblyPlatforms.Any())
{
foreach(var extraPlatform in extraScriptAssemblyPlatforms)
{
Platforms.Add(new CustomScriptAssemblyPlatform(
BuildTargetDiscovery.GetScriptAssemblyName(buildTargetList[i]) + extraPlatform.AssemblyNamePostfix,
extraPlatform.TargetNiceName,
buildTargetList[i].buildTargetPlatformVal,
true,
extraPlatform.Subtarget));
}
}
}
}
#pragma warning disable 0618
DeprecatedPlatforms = new CustomScriptAssemblyPlatform[]
{
new CustomScriptAssemblyPlatform("PSMobile", BuildTarget.PSM),
new CustomScriptAssemblyPlatform("Tizen", BuildTarget.Tizen),
new CustomScriptAssemblyPlatform("WiiU", BuildTarget.WiiU),
new CustomScriptAssemblyPlatform("Nintendo3DS", BuildTarget.N3DS),
new CustomScriptAssemblyPlatform("PSVita", BuildTarget.PSP2),
new CustomScriptAssemblyPlatform("LinuxStandalone32", BuildTarget.StandaloneLinux),
new CustomScriptAssemblyPlatform("LinuxStandaloneUniversal", BuildTarget.StandaloneLinuxUniversal),
new CustomScriptAssemblyPlatform("Lumin", BuildTarget.Lumin),
};
#pragma warning restore 0618
}
public bool IsCompatibleWithEditor()
{
if (ExcludePlatforms != null)
return ExcludePlatforms.All(p => p.BuildTarget != BuildTarget.NoTarget);
if (IncludePlatforms != null)
return IncludePlatforms.Any(p => p.BuildTarget == BuildTarget.NoTarget);
return true;
}
public bool IsCompatibleWith(BuildTarget buildTarget, int subTarget, EditorScriptCompilationOptions options, string[] defines)
{
bool buildingForEditor = (options & EditorScriptCompilationOptions.BuildingForEditor) == EditorScriptCompilationOptions.BuildingForEditor;
var isBuildingWithTestAssemblies = (options & EditorScriptCompilationOptions.BuildingIncludingTestAssemblies) == EditorScriptCompilationOptions.BuildingIncludingTestAssemblies;
var isTestAssembly = DefineConstraints != null && DefineConstraints.Any(x => x == "UNITY_INCLUDE_TESTS");
var isTestFrameworkAssembly = DefineConstraints != null && DefineConstraints.Any(x => x == "UNITY_TESTS_FRAMEWORK");
if (!buildingForEditor && (isTestAssembly || isTestFrameworkAssembly) && !isBuildingWithTestAssemblies)
{
return false;
}
if (defines != null && defines.Length == 0)
{
throw new ArgumentException("Defines cannot be empty", nameof(defines));
}
// Log invalid define constraints
if (DefineConstraints != null)
{
for (var i = 0; i < DefineConstraints.Length; ++i)
{
if (!DefineConstraintsHelper.IsDefineConstraintValid(DefineConstraints[i]))
{
throw new AssemblyDefinitionException($"Invalid Define Constraint: \"{DefineConstraints[i]}\" at line {(i+1).ToString()}", FilePath);
}
}
}
var allDefines = ResponseFileDefines != null ?
(defines != null ? defines.Concat(ResponseFileDefines) : ResponseFileDefines)
: defines;
if (!DefineConstraintsHelper.IsDefineConstraintsCompatible_Enumerable(allDefines, DefineConstraints))
{
return false;
}
if (isTestAssembly && AssetPathMetaData != null && !AssetPathMetaData.IsTestable)
{
return false;
}
// Compatible with editor and all platforms.
if (IncludePlatforms == null && ExcludePlatforms == null)
{
return true;
}
if (buildingForEditor)
{
return IsCompatibleWithEditor();
}
if (ExcludePlatforms != null)
{
// build target is different
// OR build target matches, but subtarget for target assembly is both present and differs
return ExcludePlatforms.All(p =>
p.BuildTarget != buildTarget ||
(p.BuildTarget == buildTarget &&
(p.HasSubTarget && p.SubTarget != subTarget)));
}
// build target matches, and if present, subtarget matches
return IncludePlatforms.Any(p => p.BuildTarget == buildTarget && (!p.HasSubTarget || p.SubTarget == subTarget));
}
public static CustomScriptAssembly Create(string name, string directory)
{
var customScriptAssembly = new CustomScriptAssembly();
var modifiedDirectory = AssetPath.ReplaceSeparators(directory);
if (modifiedDirectory.Last() != AssetPath.Separator)
modifiedDirectory += AssetPath.Separator.ToString();
customScriptAssembly.Name = name;
customScriptAssembly.RootNamespace = name ?? string.Empty;
customScriptAssembly.FilePath = modifiedDirectory;
customScriptAssembly.PathPrefix = modifiedDirectory;
customScriptAssembly.References = new string[0];
customScriptAssembly.PrecompiledReferences = new string[0];
customScriptAssembly.CompilerOptions = new ScriptCompilerOptions();
customScriptAssembly.AutoReferenced = true;
return customScriptAssembly;
}
public static CustomScriptAssembly FromCustomScriptAssemblyData(string path, string guid, CustomScriptAssemblyData customScriptAssemblyData)
{
if (customScriptAssemblyData == null)
return null;
var pathPrefix = path.Substring(0, path.Length - AssetPath.GetFileName(path).Length);
var customScriptAssembly = new CustomScriptAssembly();
customScriptAssembly.Name = customScriptAssemblyData.name;
customScriptAssembly.RootNamespace = customScriptAssemblyData.rootNamespace;
customScriptAssembly.GUID = guid;
customScriptAssembly.References = customScriptAssemblyData.references;
customScriptAssembly.FilePath = path;
customScriptAssembly.PathPrefix = pathPrefix;
customScriptAssembly.AutoReferenced = customScriptAssemblyData.autoReferenced;
customScriptAssembly.OverrideReferences = customScriptAssemblyData.overrideReferences;
customScriptAssembly.NoEngineReferences = customScriptAssemblyData.noEngineReferences;
customScriptAssembly.PrecompiledReferences = customScriptAssemblyData.precompiledReferences ?? new string[0];
customScriptAssembly.DefineConstraints = customScriptAssemblyData.defineConstraints ?? new string[0];
customScriptAssembly.VersionDefines = (customScriptAssemblyData.versionDefines ?? new VersionDefine[0]);
if (customScriptAssemblyData.includePlatforms != null && customScriptAssemblyData.includePlatforms.Length > 0)
customScriptAssembly.IncludePlatforms = GetPlatformsFromNames(customScriptAssemblyData.includePlatforms);
if (customScriptAssemblyData.excludePlatforms != null && customScriptAssemblyData.excludePlatforms.Length > 0)
customScriptAssembly.ExcludePlatforms = GetPlatformsFromNames(customScriptAssemblyData.excludePlatforms);
var compilerOptions = new ScriptCompilerOptions
{
AllowUnsafeCode = customScriptAssemblyData.allowUnsafeCode
};
customScriptAssembly.CompilerOptions = compilerOptions;
return customScriptAssembly;
}
public static CustomScriptAssemblyPlatform[] GetPlatformsFromNames(string[] names)
{
var platforms = new List<CustomScriptAssemblyPlatform>();
foreach (var name in names)
{
// Ignore deprecated platforms.
if (IsDeprecatedPlatformName(name))
continue;
platforms.Add(GetPlatformFromName(name));
}
return platforms.ToArray();
}
public static bool IsDeprecatedPlatformName(string name)
{
foreach (var platform in DeprecatedPlatforms)
if (string.Equals(platform.Name, name, System.StringComparison.OrdinalIgnoreCase))
return true;
return false;
}
public static CustomScriptAssemblyPlatform GetPlatformFromName(string name)
{
foreach (var platform in Platforms)
if (string.Equals(platform.Name, name, System.StringComparison.OrdinalIgnoreCase))
return platform;
var platformNames = Platforms.Select(p => string.Format("\"{0}\"", p.Name)).ToArray();
System.Array.Sort(platformNames);
var platformsString = string.Join(",\n", platformNames);
throw new System.ArgumentException(string.Format("Platform name '{0}' not supported.\nSupported platform names:\n{1}\n", name, platformsString));
}
public static CustomScriptAssemblyPlatform GetPlatformFromBuildTarget(BuildTarget buildTarget)
{
foreach (var platform in Platforms)
if (platform.BuildTarget == buildTarget)
return platform;
throw new System.ArgumentException(string.Format("No CustomScriptAssemblyPlatform setup for BuildTarget '{0}'", buildTarget));
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((CustomScriptAssembly) obj);
}
public bool Equals(CustomScriptAssembly other)
{
return assemblyFlags == other.assemblyFlags
&& string.Equals(FilePath, other.FilePath, StringComparison.Ordinal)
&& string.Equals(PathPrefix, other.PathPrefix, StringComparison.Ordinal)
&& string.Equals(Name, other.Name, StringComparison.Ordinal)
&& string.Equals(RootNamespace, other.RootNamespace, StringComparison.Ordinal)
&& GUID == other.GUID
&& Equals(References, other.References)
&& Equals(AdditionalPrefixes, other.AdditionalPrefixes)
&& Equals(IncludePlatforms, other.IncludePlatforms)
&& Equals(ExcludePlatforms, other.ExcludePlatforms)
&& Equals(AssetPathMetaData, other.AssetPathMetaData)
&& Equals(CompilerOptions, other.CompilerOptions)
&& OverrideReferences == other.OverrideReferences
&& Equals(PrecompiledReferences, other.PrecompiledReferences)
&& AutoReferenced == other.AutoReferenced
&& Equals(DefineConstraints, other.DefineConstraints)
&& Equals(VersionDefines, other.VersionDefines)
&& Equals(ResponseFileDefines, other.ResponseFileDefines)
&& NoEngineReferences == other.NoEngineReferences
&& IsPredefined == other.IsPredefined;
}
public override int GetHashCode()
{
return GUID.GetHashCode();
}
}
}