EnumExtensionMethodsIncrementalGeneratorTests.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. using System.Collections.Concurrent;
  2. using System.Collections.ObjectModel;
  3. using System.Reflection;
  4. using NUnit.Framework.Interfaces;
  5. using NUnit.Framework.Internal;
  6. using Terminal.Gui.Analyzers.Internal.Attributes;
  7. using Terminal.Gui.Analyzers.Internal.Generators.EnumExtensions;
  8. // ReSharper disable InconsistentNaming
  9. namespace Terminal.Gui.Analyzers.Internal.Tests.Generators.EnumExtensions;
  10. [TestFixture]
  11. [Category ("Source Generators")]
  12. [TestOf (typeof (EnumExtensionMethodsIncrementalGenerator))]
  13. [Parallelizable (ParallelScope.Children)]
  14. [SuppressMessage ("ReSharper", "ExceptionNotDocumented")]
  15. public class EnumExtensionMethodsIncrementalGeneratorTests
  16. {
  17. private static bool _isInitialized;
  18. /// <summary>All enum types declared in the test assembly.</summary>
  19. private static readonly ObservableCollection<Type> _allEnumTypes = [];
  20. /// <summary>
  21. /// All enum types without a <see cref="GenerateEnumExtensionMethodsAttribute"/>, <see cref="_allEnumTypes"/>
  22. /// </summary>
  23. private static readonly HashSet<Type> _boringEnumTypes = [];
  24. /// <summary>All extension classes generated for enums with our attribute.</summary>
  25. private static readonly ObservableCollection<Type> _enumExtensionClasses = [];
  26. private static readonly ConcurrentDictionary<Type, EnumData> _extendedEnumTypeMappings = [];
  27. private static IEnumerable<Type> ExtendedEnumTypes => _extendedEnumTypeMappings.Keys;
  28. private static readonly ReaderWriterLockSlim _initializationLock = new ();
  29. private static IEnumerable<AssemblyExtendedEnumTypeAttribute> GetAssemblyExtendedEnumTypeAttributes () =>
  30. Assembly.GetExecutingAssembly ()
  31. .GetCustomAttributes<AssemblyExtendedEnumTypeAttribute> ();
  32. private static IEnumerable<TestCaseData> Get_AssemblyExtendedEnumTypeAttribute_EnumHasGeneratorAttribute_Cases ()
  33. {
  34. return GetAssemblyExtendedEnumTypeAttributes ()
  35. .Select (
  36. static attr => new TestCaseData (attr)
  37. {
  38. TestName = $"{nameof (AssemblyExtendedEnumTypeAttribute_EnumHasGeneratorAttribute)}({attr.EnumType.Name},{attr.ExtensionClass.Name})",
  39. HasExpectedResult = true,
  40. ExpectedResult = true
  41. });
  42. }
  43. [Test]
  44. [Category ("Attributes")]
  45. [TestCaseSource (nameof (Get_AssemblyExtendedEnumTypeAttribute_EnumHasGeneratorAttribute_Cases))]
  46. public bool AssemblyExtendedEnumTypeAttribute_EnumHasGeneratorAttribute (AssemblyExtendedEnumTypeAttribute attr)
  47. {
  48. Assume.That (attr, Is.Not.Null);
  49. Assume.That (attr.EnumType, Is.Not.Null);
  50. Assume.That (attr.EnumType.IsEnum);
  51. return attr.EnumType.IsDefined (typeof (GenerateEnumExtensionMethodsAttribute));
  52. }
  53. [Test]
  54. [Category("Attributes")]
  55. public void AssemblyExtendedEnumTypeAttribute_ExtensionClassHasExpectedReverseMappingAttribute ([ValueSource(nameof(GetAssemblyExtendedEnumTypeAttributes))]AssemblyExtendedEnumTypeAttribute attr)
  56. {
  57. Assume.That (attr, Is.Not.Null);
  58. Assume.That (attr.ExtensionClass, Is.Not.Null);
  59. Assume.That (attr.ExtensionClass.IsClass);
  60. Assume.That (attr.ExtensionClass.IsSealed);
  61. Assert.That (attr.ExtensionClass.IsDefined (typeof (ExtensionsForEnumTypeAttribute<>)));
  62. }
  63. [Test]
  64. [Category("Attributes")]
  65. public void ExtendedEnum_AssemblyHasMatchingAttribute ([ValueSource(nameof(GetExtendedEnum_EnumData))]EnumData enumData)
  66. {
  67. Assume.That (enumData, Is.Not.Null);
  68. Assume.That (enumData.EnumType, Is.Not.Null);
  69. Assume.That (enumData.EnumType.IsEnum);
  70. Assert.That (enumData.EnumType, Has.Attribute<GenerateEnumExtensionMethodsAttribute> ());
  71. }
  72. [Test]
  73. public void BoringEnum_DoesNotHaveExtensions ([ValueSource (nameof (_boringEnumTypes))] Type enumType)
  74. {
  75. Assume.That (enumType.IsEnum);
  76. Assert.That (enumType, Has.No.Attribute<GenerateEnumExtensionMethodsAttribute> ());
  77. }
  78. [Test]
  79. public void ExtendedEnum_FastIsDefinedFalse_DoesNotHaveFastIsDefined ([ValueSource (nameof (GetExtendedEnumTypes_FastIsDefinedFalse))] EnumData enumData)
  80. {
  81. Assume.That (enumData.EnumType.IsEnum);
  82. Assume.That (enumData.EnumType, Has.Attribute<GenerateEnumExtensionMethodsAttribute> ());
  83. Assume.That (enumData.GeneratorAttribute, Is.Not.Null);
  84. Assume.That (enumData.GeneratorAttribute, Is.EqualTo (enumData.EnumType.GetCustomAttribute<GenerateEnumExtensionMethodsAttribute> ()));
  85. Assume.That (enumData.GeneratorAttribute, Has.Property ("FastIsDefined").False);
  86. Assume.That (enumData.ExtensionClass, Is.Not.Null);
  87. Assert.That (enumData.ExtensionClass!.GetMethod ("FastIsDefined"), Is.Null);
  88. }
  89. [Test]
  90. public void ExtendedEnum_StaticExtensionClassExists ([ValueSource (nameof (ExtendedEnumTypes))] Type enumType)
  91. {
  92. Assume.That (enumType.IsEnum);
  93. Assume.That (enumType, Has.Attribute<GenerateEnumExtensionMethodsAttribute> ());
  94. Assume.That (enumType, Has.Attribute<GenerateEnumExtensionMethodsAttribute> ());
  95. }
  96. [Test]
  97. public void ExtendedEnum_FastIsDefinedTrue_HasFastIsDefined ([ValueSource (nameof (GetExtendedEnumTypes_FastIsDefinedTrue))] EnumData enumData)
  98. {
  99. Assume.That (enumData.EnumType, Is.Not.Null);
  100. Assume.That (enumData.EnumType.IsEnum);
  101. Assume.That (enumData.EnumType, Has.Attribute<GenerateEnumExtensionMethodsAttribute> ());
  102. Assume.That (enumData.ExtensionClass, Is.Not.Null);
  103. ITypeInfo extensionClassTypeInfo = new TypeWrapper (enumData.ExtensionClass!);
  104. Assume.That (extensionClassTypeInfo.IsStaticClass);
  105. Assume.That (enumData.GeneratorAttribute, Is.Not.Null);
  106. Assume.That (enumData.GeneratorAttribute, Is.EqualTo (enumData.EnumType.GetCustomAttribute<GenerateEnumExtensionMethodsAttribute> ()));
  107. Assume.That (enumData.GeneratorAttribute, Has.Property ("FastIsDefined").True);
  108. MethodInfo? fastIsDefinedMethod = enumData.ExtensionClass!.GetMethod ("FastIsDefined");
  109. Assert.That (fastIsDefinedMethod, Is.Not.Null);
  110. Assert.That (fastIsDefinedMethod, Has.Attribute<ExtensionAttribute> ());
  111. extensionClassTypeInfo.GetMethodsWithAttribute<ExtensionAttribute> (false);
  112. }
  113. private static IEnumerable<EnumData> GetExtendedEnum_EnumData ()
  114. {
  115. _initializationLock.EnterUpgradeableReadLock ();
  116. try
  117. {
  118. if (!_isInitialized)
  119. {
  120. Initialize ();
  121. }
  122. return _extendedEnumTypeMappings.Values;
  123. }
  124. finally
  125. {
  126. _initializationLock.ExitUpgradeableReadLock ();
  127. }
  128. }
  129. private static IEnumerable<Type> GetBoringEnumTypes ()
  130. {
  131. _initializationLock.EnterUpgradeableReadLock ();
  132. try
  133. {
  134. if (!_isInitialized)
  135. {
  136. Initialize ();
  137. }
  138. return _boringEnumTypes;
  139. }
  140. finally
  141. {
  142. _initializationLock.ExitUpgradeableReadLock ();
  143. }
  144. }
  145. private static IEnumerable<EnumData> GetExtendedEnumTypes_FastIsDefinedFalse ()
  146. {
  147. _initializationLock.EnterUpgradeableReadLock ();
  148. try
  149. {
  150. if (!_isInitialized)
  151. {
  152. Initialize ();
  153. }
  154. return _extendedEnumTypeMappings.Values.Where (static t => t.GeneratorAttribute?.FastIsDefined is false);
  155. }
  156. finally
  157. {
  158. _initializationLock.ExitUpgradeableReadLock ();
  159. }
  160. }
  161. private static IEnumerable<EnumData> GetExtendedEnumTypes_FastIsDefinedTrue ()
  162. {
  163. _initializationLock.EnterUpgradeableReadLock ();
  164. try
  165. {
  166. if (!_isInitialized)
  167. {
  168. Initialize ();
  169. }
  170. return _extendedEnumTypeMappings.Values.Where (static t => t.GeneratorAttribute?.FastIsDefined is true);
  171. }
  172. finally
  173. {
  174. _initializationLock.ExitUpgradeableReadLock ();
  175. }
  176. }
  177. private static void Initialize ()
  178. {
  179. if (!_initializationLock.IsUpgradeableReadLockHeld || !_initializationLock.TryEnterWriteLock (5000))
  180. {
  181. return;
  182. }
  183. try
  184. {
  185. if (_isInitialized)
  186. {
  187. return;
  188. }
  189. _allEnumTypes.CollectionChanged += AllEnumTypes_CollectionChanged;
  190. _enumExtensionClasses.CollectionChanged += EnumExtensionClasses_OnCollectionChanged;
  191. Type [] allAssemblyTypes = Assembly
  192. .GetExecutingAssembly ()
  193. .GetTypes ();
  194. foreach (Type type in allAssemblyTypes.Where (IsDefinedEnum))
  195. {
  196. _allEnumTypes.Add (type);
  197. }
  198. foreach (Type type in allAssemblyTypes.Where (HasExtensionForEnumTypeAttribute))
  199. {
  200. _enumExtensionClasses.Add (type);
  201. }
  202. _isInitialized = true;
  203. }
  204. finally
  205. {
  206. _initializationLock.ExitWriteLock ();
  207. }
  208. return;
  209. static bool IsDefinedEnum (Type t) { return t is { IsEnum: true, IsGenericType: false, IsConstructedGenericType: false, IsTypeDefinition: true }; }
  210. static void AllEnumTypes_CollectionChanged (object? sender, NotifyCollectionChangedEventArgs e)
  211. {
  212. if (e.Action is not NotifyCollectionChangedAction.Add and not NotifyCollectionChangedAction.Replace || e.NewItems is null)
  213. {
  214. return;
  215. }
  216. foreach (Type enumType in e.NewItems.OfType<Type> ())
  217. {
  218. if (enumType.GetCustomAttribute<GenerateEnumExtensionMethodsAttribute> () is not { } generatorAttribute)
  219. {
  220. _boringEnumTypes.Add (enumType);
  221. continue;
  222. }
  223. _extendedEnumTypeMappings.AddOrUpdate (
  224. enumType,
  225. CreateNewEnumData,
  226. UpdateGeneratorAttributeProperty,
  227. generatorAttribute);
  228. }
  229. }
  230. static EnumData CreateNewEnumData (Type tEnum, GenerateEnumExtensionMethodsAttribute attr) { return new (tEnum, attr); }
  231. static EnumData UpdateGeneratorAttributeProperty (Type tEnum, EnumData data, GenerateEnumExtensionMethodsAttribute attr)
  232. {
  233. data.GeneratorAttribute ??= attr;
  234. return data;
  235. }
  236. static void EnumExtensionClasses_OnCollectionChanged (object? sender, NotifyCollectionChangedEventArgs e)
  237. {
  238. if (e.Action != NotifyCollectionChangedAction.Add)
  239. {
  240. return;
  241. }
  242. foreach (Type extensionClassType in e.NewItems!.OfType<Type> ())
  243. {
  244. if (extensionClassType.GetCustomAttribute (typeof (ExtensionsForEnumTypeAttribute<>), false) is not IExtensionsForEnumTypeAttributes
  245. {
  246. EnumType.IsEnum: true
  247. } extensionForAttribute)
  248. {
  249. continue;
  250. }
  251. _extendedEnumTypeMappings [extensionForAttribute.EnumType].ExtensionClass ??= extensionClassType;
  252. }
  253. }
  254. }
  255. private static bool HasExtensionForEnumTypeAttribute (Type t) => t.IsClass && t.IsDefined (typeof (ExtensionsForEnumTypeAttribute<>));
  256. public sealed record EnumData (
  257. Type EnumType,
  258. GenerateEnumExtensionMethodsAttribute? GeneratorAttribute = null,
  259. Type? ExtensionClass = null,
  260. IExtensionsForEnumTypeAttributes? ExtensionForEnumTypeAttribute = null)
  261. {
  262. public Type? ExtensionClass { get; set; } = ExtensionClass;
  263. public IExtensionsForEnumTypeAttributes? ExtensionForEnumTypeAttribute { get; set; } = ExtensionForEnumTypeAttribute;
  264. public GenerateEnumExtensionMethodsAttribute? GeneratorAttribute { get; set; } = GeneratorAttribute;
  265. }
  266. }