EnumExtensionMethodsIncrementalGeneratorTests.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. TypeWrapper extensionClassTypeInfo = new(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<EnumData> GetExtendedEnumTypes_FastIsDefinedFalse ()
  130. {
  131. _initializationLock.EnterUpgradeableReadLock ();
  132. try
  133. {
  134. if (!_isInitialized)
  135. {
  136. Initialize ();
  137. }
  138. return _extendedEnumTypeMappings.Values.Where (static t => t.GeneratorAttribute?.FastIsDefined is false);
  139. }
  140. finally
  141. {
  142. _initializationLock.ExitUpgradeableReadLock ();
  143. }
  144. }
  145. private static IEnumerable<EnumData> GetExtendedEnumTypes_FastIsDefinedTrue ()
  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 true);
  155. }
  156. finally
  157. {
  158. _initializationLock.ExitUpgradeableReadLock ();
  159. }
  160. }
  161. private static void Initialize ()
  162. {
  163. if (!_initializationLock.IsUpgradeableReadLockHeld || !_initializationLock.TryEnterWriteLock (5000))
  164. {
  165. return;
  166. }
  167. try
  168. {
  169. if (_isInitialized)
  170. {
  171. return;
  172. }
  173. _allEnumTypes.CollectionChanged += AllEnumTypes_CollectionChanged;
  174. _enumExtensionClasses.CollectionChanged += EnumExtensionClasses_OnCollectionChanged;
  175. Type [] allAssemblyTypes = Assembly
  176. .GetExecutingAssembly ()
  177. .GetTypes ();
  178. foreach (Type type in allAssemblyTypes.Where (IsDefinedEnum))
  179. {
  180. _allEnumTypes.Add (type);
  181. }
  182. foreach (Type type in allAssemblyTypes.Where (HasExtensionForEnumTypeAttribute))
  183. {
  184. _enumExtensionClasses.Add (type);
  185. }
  186. _isInitialized = true;
  187. }
  188. finally
  189. {
  190. _initializationLock.ExitWriteLock ();
  191. }
  192. return;
  193. static bool IsDefinedEnum (Type t) { return t is { IsEnum: true, IsGenericType: false, IsConstructedGenericType: false, IsTypeDefinition: true }; }
  194. static void AllEnumTypes_CollectionChanged (object? sender, NotifyCollectionChangedEventArgs e)
  195. {
  196. if (e.Action is not NotifyCollectionChangedAction.Add and not NotifyCollectionChangedAction.Replace || e.NewItems is null)
  197. {
  198. return;
  199. }
  200. foreach (Type enumType in e.NewItems.OfType<Type> ())
  201. {
  202. if (enumType.GetCustomAttribute<GenerateEnumExtensionMethodsAttribute> () is not { } generatorAttribute)
  203. {
  204. _boringEnumTypes.Add (enumType);
  205. continue;
  206. }
  207. _extendedEnumTypeMappings.AddOrUpdate (
  208. enumType,
  209. CreateNewEnumData,
  210. UpdateGeneratorAttributeProperty,
  211. generatorAttribute);
  212. }
  213. }
  214. static EnumData CreateNewEnumData (Type tEnum, GenerateEnumExtensionMethodsAttribute attr) { return new (tEnum, attr); }
  215. static EnumData UpdateGeneratorAttributeProperty (Type tEnum, EnumData data, GenerateEnumExtensionMethodsAttribute attr)
  216. {
  217. data.GeneratorAttribute ??= attr;
  218. return data;
  219. }
  220. static void EnumExtensionClasses_OnCollectionChanged (object? sender, NotifyCollectionChangedEventArgs e)
  221. {
  222. if (e.Action != NotifyCollectionChangedAction.Add)
  223. {
  224. return;
  225. }
  226. foreach (Type extensionClassType in e.NewItems!.OfType<Type> ())
  227. {
  228. if (extensionClassType.GetCustomAttribute (typeof (ExtensionsForEnumTypeAttribute<>), false) is not IExtensionsForEnumTypeAttributes
  229. {
  230. EnumType.IsEnum: true
  231. } extensionForAttribute)
  232. {
  233. continue;
  234. }
  235. _extendedEnumTypeMappings [extensionForAttribute.EnumType].ExtensionClass ??= extensionClassType;
  236. }
  237. }
  238. }
  239. private static bool HasExtensionForEnumTypeAttribute (Type t) => t.IsClass && t.IsDefined (typeof (ExtensionsForEnumTypeAttribute<>));
  240. public sealed record EnumData (
  241. Type EnumType,
  242. GenerateEnumExtensionMethodsAttribute? GeneratorAttribute = null,
  243. Type? ExtensionClass = null,
  244. IExtensionsForEnumTypeAttributes? ExtensionForEnumTypeAttribute = null)
  245. {
  246. public Type? ExtensionClass { get; set; } = ExtensionClass;
  247. public IExtensionsForEnumTypeAttributes? ExtensionForEnumTypeAttribute { get; set; } = ExtensionForEnumTypeAttribute;
  248. public GenerateEnumExtensionMethodsAttribute? GeneratorAttribute { get; set; } = GeneratorAttribute;
  249. }
  250. }