EnumExtensionMethodsIncrementalGenerator.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. using System;
  2. using System.Diagnostics.CodeAnalysis;
  3. using System.Text;
  4. using System.Threading;
  5. using Microsoft.CodeAnalysis;
  6. using Microsoft.CodeAnalysis.Text;
  7. using Terminal.Gui.Analyzers.Internal.Attributes;
  8. using Terminal.Gui.Analyzers.Internal.Constants;
  9. namespace Terminal.Gui.Analyzers.Internal.Generators.EnumExtensions;
  10. /// <summary>
  11. /// Incremental code generator for enums decorated with <see cref="GenerateEnumExtensionMethodsAttribute"/>.
  12. /// </summary>
  13. [SuppressMessage ("CodeQuality", "IDE0079", Justification = "Suppressions here are intentional and the warnings they disable are just noise.")]
  14. [Generator (LanguageNames.CSharp)]
  15. public sealed class EnumExtensionMethodsIncrementalGenerator : IIncrementalGenerator
  16. {
  17. private const string ExtensionsForEnumTypeAttributeFullyQualifiedName = $"{Strings.AnalyzersAttributesNamespace}.{ExtensionsForEnumTypeAttributeName}";
  18. private const string ExtensionsForEnumTypeAttributeName = "ExtensionsForEnumTypeAttribute";
  19. private const string GeneratorAttributeFullyQualifiedName = $"{Strings.AnalyzersAttributesNamespace}.{GeneratorAttributeName}";
  20. private const string GeneratorAttributeName = nameof (GenerateEnumExtensionMethodsAttribute);
  21. /// <summary>Fully-qualified symbol name format without the "global::" prefix.</summary>
  22. private static readonly SymbolDisplayFormat _fullyQualifiedSymbolDisplayFormatWithoutGlobal =
  23. SymbolDisplayFormat.FullyQualifiedFormat.WithGlobalNamespaceStyle (SymbolDisplayGlobalNamespaceStyle.Omitted);
  24. /// <inheritdoc/>
  25. /// <remarks>
  26. /// <para>
  27. /// Basically, this method is called once by the compiler, and is responsible for wiring up
  28. /// everything important about how source generation works.
  29. /// </para>
  30. /// <para>
  31. /// See in-line comments for specifics of what's going on.
  32. /// </para>
  33. /// <para>
  34. /// Note that <paramref name="context"/> is everything in the compilation,
  35. /// except for code generated by this generator or generators which have not yet executed.<br/>
  36. /// The methods registered to perform generation get called on-demand by the host (the IDE,
  37. /// compiler, etc), sometimes as often as every single keystroke.
  38. /// </para>
  39. /// </remarks>
  40. public void Initialize (IncrementalGeneratorInitializationContext context)
  41. {
  42. // Write out namespaces that may be used later. Harmless to declare them now and will avoid
  43. // additional processing and potential omissions later on.
  44. context.RegisterPostInitializationOutput (GenerateDummyNamespaces);
  45. // This executes the delegate given to it immediately after Roslyn gets all set up.
  46. //
  47. // As written, this will result in the GenerateEnumExtensionMethodsAttribute code
  48. // being added to the environment, so that it can be used without having to actually
  49. // be declared explicitly in the target project.
  50. // This is important, as it guarantees the type will exist and also guarantees it is
  51. // defined exactly as the generator expects it to be defined.
  52. context.RegisterPostInitializationOutput (GenerateAttributeSources);
  53. // Next up, we define our pipeline.
  54. // To do so, we create one or more IncrementalValuesProvider<T> objects, each of which
  55. // defines on stage of analysis or generation as needed.
  56. //
  57. // Critically, these must be as fast and efficient as reasonably possible because,
  58. // once the pipeline is registered, this stuff can get called A LOT.
  59. //
  60. // Note that declaring these doesn't really do much of anything unless they are given to the
  61. // RegisterSourceOutput method at the end of this method.
  62. //
  63. // The delegates are not actually evaluated right here. That is triggered by changes being
  64. // made to the source code.
  65. // This provider grabs attributes that pass our filter and then creates lightweight
  66. // metadata objects to be used in the final code generation step.
  67. // It also preemptively removes any nulls from the collection before handing things off
  68. // to the code generation logic.
  69. IncrementalValuesProvider<EnumExtensionMethodsGenerationInfo?> enumGenerationInfos =
  70. context
  71. .SyntaxProvider
  72. // This method is a highly-optimized (and highly-recommended) filter on the incoming
  73. // code elements that only bothers to present code that is annotated with the specified
  74. // attribute, by its fully-qualified name, as a string, which is the first parameter.
  75. //
  76. // Two delegates are passed to it, in the second and third parameters.
  77. //
  78. // The second parameter is a filter predicate taking each SyntaxNode that passes the
  79. // name filter above, and then refines that result.
  80. //
  81. // It is critical that the filter predicate be as simple and fast as possible, as it
  82. // will be called a ton, triggered by keystrokes or anything else that modifies code
  83. // in or even related to (in either direction) the pre-filtered code.
  84. // It should collect metadata only and not actually generate any code.
  85. // It must return a boolean indicating whether the supplied SyntaxNode should be
  86. // given to the transform delegate at all.
  87. //
  88. // The third parameter is the "transform" delegate.
  89. // That one only runs when code is changed that passed both the attribute name filter
  90. // and the filter predicate in the second parameter.
  91. // It will be called for everything that passes both of those, so it can still happen
  92. // a lot, but should at least be pretty close.
  93. // In our case, it should be 100% accurate, since we're using OUR attribute, which can
  94. // only be applied to enum types in the first place.
  95. //
  96. // That delegate is responsible for creating some sort of lightweight data structure
  97. // which can later be used to generate the actual source code for output.
  98. //
  99. // THIS DELEGATE DOES NOT GENERATE CODE!
  100. // However, it does need to return instances of the metadata class in use that are either
  101. // null or complete enough to generate meaningful code from, later on.
  102. //
  103. // We then filter out any that were null with the .Where call at the end, so that we don't
  104. // know or care about them when it's time to generate code.
  105. //
  106. // While the syntax of that .Where call is the same as LINQ, that is actually a
  107. // highly-optimized implementation specifically for this use.
  108. .ForAttributeWithMetadataName (
  109. GeneratorAttributeFullyQualifiedName,
  110. IsPotentiallyInterestingDeclaration,
  111. GatherMetadataForCodeGeneration
  112. )
  113. .WithTrackingName ("CollectEnumMetadata")
  114. .Where (static eInfo => eInfo is { });
  115. // Finally, we wire up any IncrementalValuesProvider<T> instances above to the appropriate
  116. // delegate that takes the SourceProductionContext that is current at run-time and an instance of
  117. // our metadata type and takes appropriate action.
  118. // Typically that means generating code from that metadata and adding it to the compilation via
  119. // the received context object.
  120. //
  121. // As with everything else , the delegate will be invoked once for each item that passed
  122. // all of the filters above, so we get to write that method from the perspective of a single
  123. // enum type declaration.
  124. context.RegisterSourceOutput (enumGenerationInfos, GenerateSourceFromGenerationInfo);
  125. }
  126. private static EnumExtensionMethodsGenerationInfo? GatherMetadataForCodeGeneration (
  127. GeneratorAttributeSyntaxContext context,
  128. CancellationToken cancellationToken
  129. )
  130. {
  131. var cts = CancellationTokenSource.CreateLinkedTokenSource (cancellationToken);
  132. cancellationToken.ThrowIfCancellationRequested ();
  133. // If it's not an enum symbol, we don't care.
  134. // EnumUnderlyingType is null for non-enums, so this validates it's an enum declaration.
  135. if (context.TargetSymbol is not INamedTypeSymbol { EnumUnderlyingType: { } } namedSymbol)
  136. {
  137. return null;
  138. }
  139. INamespaceSymbol? enumNamespaceSymbol = namedSymbol.ContainingNamespace;
  140. if (enumNamespaceSymbol is null or { IsGlobalNamespace: true })
  141. {
  142. // Explicitly choosing not to support enums in the global namespace.
  143. // The corresponding analyzer will report this.
  144. return null;
  145. }
  146. string enumName = namedSymbol.Name;
  147. string enumNamespace = enumNamespaceSymbol.ToDisplayString (_fullyQualifiedSymbolDisplayFormatWithoutGlobal);
  148. TypeCode enumTypeCode = namedSymbol.EnumUnderlyingType.Name switch
  149. {
  150. "UInt32" => TypeCode.UInt32,
  151. "Int32" => TypeCode.Int32,
  152. _ => TypeCode.Empty
  153. };
  154. EnumExtensionMethodsGenerationInfo info = new (
  155. enumNamespace,
  156. enumName,
  157. enumTypeCode
  158. );
  159. if (!info.TryConfigure (namedSymbol, cts.Token))
  160. {
  161. cts.Cancel ();
  162. cts.Token.ThrowIfCancellationRequested ();
  163. }
  164. return info;
  165. }
  166. private static void GenerateAttributeSources (IncrementalGeneratorPostInitializationContext postInitializationContext)
  167. {
  168. postInitializationContext
  169. .AddSource (
  170. $"{nameof (IExtensionsForEnumTypeAttributes)}.g.cs",
  171. SourceText.From (
  172. $$"""
  173. // ReSharper disable All
  174. {{Strings.Templates.AutoGeneratedCommentBlock}}
  175. using System;
  176. namespace {{Strings.AnalyzersAttributesNamespace}};
  177. /// <summary>
  178. /// Interface to simplify general enumeration of constructed generic types for
  179. /// <see cref="ExtensionsForEnumTypeAttribute{TEnum}"/>
  180. /// </summary>
  181. {{Strings.Templates.AttributesForGeneratedInterfaces}}
  182. public interface IExtensionsForEnumTypeAttributes
  183. {
  184. System.Type EnumType { get; }
  185. }
  186. """,
  187. Encoding.UTF8));
  188. postInitializationContext
  189. .AddSource (
  190. $"{nameof (AssemblyExtendedEnumTypeAttribute)}.g.cs",
  191. SourceText.From (
  192. $$"""
  193. // ReSharper disable All
  194. #nullable enable
  195. {{Strings.Templates.AutoGeneratedCommentBlock}}
  196. namespace {{Strings.AnalyzersAttributesNamespace}};
  197. /// <summary>Assembly attribute declaring a known pairing of an <see langword="enum" /> type to an extension class.</summary>
  198. /// <remarks>This attribute should only be written by internal source generators for Terminal.Gui. No other usage of any kind is supported.</remarks>
  199. {{Strings.Templates.AttributesForGeneratedTypes}}
  200. [System.AttributeUsageAttribute(System.AttributeTargets.Assembly, AllowMultiple = true)]
  201. public sealed class {{nameof(AssemblyExtendedEnumTypeAttribute)}} : System.Attribute
  202. {
  203. /// <summary>Creates a new instance of <see cref="AssemblyExtendedEnumTypeAttribute" /> from the provided parameters.</summary>
  204. /// <param name="enumType">The <see cref="System.Type" /> of an <see langword="enum" /> decorated with a <see cref="GenerateEnumExtensionMethodsAttribute" />.</param>
  205. /// <param name="extensionClass">The <see cref="System.Type" /> of the <see langword="class" /> decorated with an <see cref="ExtensionsForEnumTypeAttribute{TEnum}" /> referring to the same type as <paramref name="enumType" />.</param>
  206. public AssemblyExtendedEnumTypeAttribute (System.Type enumType, System.Type extensionClass)
  207. {
  208. EnumType = enumType;
  209. ExtensionClass = extensionClass;
  210. }
  211. /// <summary>An <see langword="enum" /> type that has been extended by Terminal.Gui source generators.</summary>
  212. public System.Type EnumType { get; init; }
  213. /// <summary>A class containing extension methods for <see cref="EnumType"/>.</summary>
  214. public System.Type ExtensionClass { get; init; }
  215. /// <inheritdoc />
  216. public override string ToString () => $"{EnumType.Name},{ExtensionClass.Name}";
  217. }
  218. """,
  219. Encoding.UTF8));
  220. postInitializationContext
  221. .AddSource (
  222. $"{GeneratorAttributeFullyQualifiedName}.g.cs",
  223. SourceText.From (
  224. $$"""
  225. {{Strings.Templates.StandardHeader}}
  226. namespace {{Strings.AnalyzersAttributesNamespace}};
  227. /// <summary>
  228. /// Used to enable source generation of a common set of extension methods for enum types.
  229. /// </summary>
  230. {{Strings.Templates.AttributesForGeneratedTypes}}
  231. [{{Strings.DotnetNames.Types.AttributeUsageAttribute}} ({{Strings.DotnetNames.Types.AttributeTargets}}.Enum)]
  232. public sealed class {{GeneratorAttributeName}} : {{Strings.DotnetNames.Types.Attribute}}
  233. {
  234. /// <summary>
  235. /// The name of the generated static class.
  236. /// </summary>
  237. /// <remarks>
  238. /// If unspecified, null, empty, or only whitespace, defaults to the name of the enum plus "Extensions".<br/>
  239. /// No other validation is performed, so illegal values will simply result in compiler errors.
  240. /// <para>
  241. /// Explicitly specifying a default value is unnecessary and will result in unnecessary processing.
  242. /// </para>
  243. /// </remarks>
  244. public string? ClassName { get; set; }
  245. /// <summary>
  246. /// The namespace in which to place the generated static class containing the extension methods.
  247. /// </summary>
  248. /// <remarks>
  249. /// If unspecified, null, empty, or only whitespace, defaults to the namespace of the enum.<br/>
  250. /// No other validation is performed, so illegal values will simply result in compiler errors.
  251. /// <para>
  252. /// Explicitly specifying a default value is unnecessary and will result in unnecessary processing.
  253. /// </para>
  254. /// </remarks>
  255. public string? ClassNamespace { get; set; }
  256. /// <summary>
  257. /// Whether to generate a fast, zero-allocation, non-boxing, and reflection-free alternative to the built-in
  258. /// <see cref="Enum.HasFlag"/> method.
  259. /// </summary>
  260. /// <remarks>
  261. /// <para>
  262. /// Default: false
  263. /// </para>
  264. /// <para>
  265. /// If the enum is not decorated with <see cref="Flags"/>, this option has no effect.
  266. /// </para>
  267. /// <para>
  268. /// If multiple members have the same value, the first member with that value will be used and subsequent members
  269. /// with the same value will be skipped.
  270. /// </para>
  271. /// <para>
  272. /// Overloads taking the enum type itself as well as the underlying type of the enum will be generated, enabling
  273. /// avoidance of implicit or explicit cast overhead.
  274. /// </para>
  275. /// <para>
  276. /// Explicitly specifying a default value is unnecessary and will result in unnecessary processing.
  277. /// </para>
  278. /// </remarks>
  279. public bool FastHasFlags { get; set; }
  280. /// <summary>
  281. /// Whether to generate a fast, zero-allocation, and reflection-free alternative to the built-in
  282. /// <see cref="Enum.IsDefined"/> method,
  283. /// using a switch expression as a hard-coded reverse mapping of numeric values to explicitly-named members.
  284. /// </summary>
  285. /// <remarks>
  286. /// <para>
  287. /// Default: true
  288. /// </para>
  289. /// <para>
  290. /// If multiple members have the same value, the first member with that value will be used and subsequent members
  291. /// with the same value will be skipped.
  292. /// </para>
  293. /// <para>
  294. /// As with <see cref="Enum.IsDefined"/> the source generator only considers explicitly-named members.<br/>
  295. /// Generation of values which represent valid bitwise combinations of members of enums decorated with
  296. /// <see cref="Flags"/> is not affected by this property.
  297. /// </para>
  298. /// </remarks>
  299. public bool FastIsDefined { get; init; } = true;
  300. /// <summary>
  301. /// Gets a <see langword="bool"/> value indicating if this <see cref="GenerateEnumExtensionMethodsAttribute"/> instance
  302. /// contains default values only. See <see href="#remarks">remarks</see> of this method or documentation on properties of this type for details.
  303. /// </summary>
  304. /// <returns>
  305. /// A <see langword="bool"/> value indicating if all property values are default for this
  306. /// <see cref="GenerateEnumExtensionMethodsAttribute"/> instance.
  307. /// </returns>
  308. /// <remarks>
  309. /// Default values that will result in a <see langword="true"/> return value are:<br/>
  310. /// <see cref="FastIsDefined"/> &amp;&amp; !<see cref="FastHasFlags"/> &amp;&amp; <see cref="ClassName"/>
  311. /// <see langword="is"/> <see langword="null"/> &amp;&amp; <see cref="ClassNamespace"/> <see langword="is"/>
  312. /// <see langword="null"/>
  313. /// </remarks>
  314. public override bool IsDefaultAttribute ()
  315. {
  316. return FastIsDefined
  317. && !FastHasFlags
  318. && ClassName is null
  319. && ClassNamespace is null;
  320. }
  321. }
  322. """,
  323. Encoding.UTF8));
  324. postInitializationContext
  325. .AddSource (
  326. $"{ExtensionsForEnumTypeAttributeFullyQualifiedName}.g.cs",
  327. SourceText.From (
  328. $$"""
  329. // ReSharper disable RedundantNameQualifier
  330. // ReSharper disable RedundantNullableDirective
  331. // ReSharper disable UnusedType.Global
  332. {{Strings.Templates.AutoGeneratedCommentBlock}}
  333. #nullable enable
  334. namespace {{Strings.AnalyzersAttributesNamespace}};
  335. /// <summary>
  336. /// Attribute written by the source generator for enum extension classes, for easier analysis and reflection.
  337. /// </summary>
  338. /// <remarks>
  339. /// Properties are just convenient shortcuts to properties of <typeparamref name="TEnum"/>.
  340. /// </remarks>
  341. {{Strings.Templates.AttributesForGeneratedTypes}}
  342. [System.AttributeUsageAttribute (System.AttributeTargets.Class | System.AttributeTargets.Interface)]
  343. public sealed class {{ExtensionsForEnumTypeAttributeName}}<TEnum>: System.Attribute, IExtensionsForEnumTypeAttributes where TEnum : struct, Enum
  344. {
  345. /// <summary>
  346. /// The namespace-qualified name of <typeparamref name="TEnum"/>.
  347. /// </summary>
  348. public string EnumFullName => EnumType.FullName!;
  349. /// <summary>
  350. /// The unqualified name of <typeparamref name="TEnum"/>.
  351. /// </summary>
  352. public string EnumName => EnumType.Name;
  353. /// <summary>
  354. /// The namespace containing <typeparamref name="TEnum"/>.
  355. /// </summary>
  356. public string EnumNamespace => EnumType.Namespace!;
  357. /// <summary>
  358. /// The <see cref="Type"/> given by <see langword="typeof"/>(<typeparamref name="TEnum"/>).
  359. /// </summary>
  360. public Type EnumType => typeof (TEnum);
  361. }
  362. """,
  363. Encoding.UTF8));
  364. }
  365. [SuppressMessage ("Roslynator", "RCS1267", Justification = "Intentionally used so that Spans are used.")]
  366. private static void GenerateDummyNamespaces (IncrementalGeneratorPostInitializationContext postInitializeContext)
  367. {
  368. postInitializeContext.AddSource (
  369. string.Concat (Strings.InternalAnalyzersNamespace, "Namespaces.g.cs"),
  370. SourceText.From (Strings.Templates.DummyNamespaceDeclarations, Encoding.UTF8));
  371. }
  372. private static void GenerateSourceFromGenerationInfo (SourceProductionContext context, EnumExtensionMethodsGenerationInfo? enumInfo)
  373. {
  374. // Just in case we still made it this far with a null...
  375. if (enumInfo is not { })
  376. {
  377. return;
  378. }
  379. CodeWriter writer = new (enumInfo);
  380. context.AddSource ($"{enumInfo.FullyQualifiedClassName}.g.cs", writer.GenerateSourceText ());
  381. }
  382. /// <summary>
  383. /// Returns true if <paramref name="syntaxNode"/> is an EnumDeclarationSyntax
  384. /// whose parent is a NamespaceDeclarationSyntax, FileScopedNamespaceDeclarationSyntax, or a
  385. /// (Class|Struct)DeclarationSyntax.<br/>
  386. /// Additional filtering is performed in later stages.
  387. /// </summary>
  388. private static bool IsPotentiallyInterestingDeclaration (SyntaxNode syntaxNode, CancellationToken cancellationToken)
  389. {
  390. cancellationToken.ThrowIfCancellationRequested ();
  391. return syntaxNode is
  392. {
  393. RawKind: 8858, //(int)SyntaxKind.EnumDeclaration,
  394. Parent.RawKind: 8845 //(int)SyntaxKind.FileScopedNamespaceDeclaration
  395. or 8842 //(int)SyntaxKind.NamespaceDeclaration
  396. or 8855 //(int)SyntaxKind.ClassDeclaration
  397. or 8856 //(int)SyntaxKind.StructDeclaration
  398. or 9068 //(int)SyntaxKind.RecordStructDeclaration
  399. or 9063 //(int)SyntaxKind.RecordDeclaration
  400. };
  401. }
  402. }