|
1 | 1 | using Microsoft.CodeAnalysis; |
2 | 2 | using Microsoft.CodeAnalysis.CSharp.Syntax; |
3 | | -using System.Collections.Generic; |
4 | 3 |
|
5 | 4 | namespace StringLiteralGenerator; |
6 | 5 |
|
7 | 6 | [Generator] |
8 | | -public partial class Utf8StringLiteralGenerator : ISourceGenerator |
| 7 | +public partial class Utf8StringLiteralGenerator : IIncrementalGenerator |
9 | 8 | { |
10 | | - public void Execute(GeneratorExecutionContext context) |
| 9 | + public void Initialize(IncrementalGeneratorInitializationContext context) |
11 | 10 | { |
12 | | - if (context.SyntaxReceiver is not SyntaxReceiver receiver) return; |
| 11 | + context.RegisterPostInitializationOutput(AddAttribute); |
13 | 12 |
|
14 | | - var compilation = context.Compilation; |
| 13 | + var provider = context.SyntaxProvider |
| 14 | + .CreateSyntaxProvider( |
| 15 | + static (node, _) => IsSyntaxTargetForGeneration(node), |
| 16 | + static (context, _) => GetSemanticTargetForGeneration(context.SemanticModel, (MethodDeclarationSyntax)context.Node)! |
| 17 | + ) |
| 18 | + .Where(x => x is not null) |
| 19 | + .Collect(); |
15 | 20 |
|
16 | | - Emit(context, enumerate()); |
17 | | - |
18 | | - IEnumerable<Utf8LiteralMethod> enumerate() |
19 | | - { |
20 | | - foreach (var m in receiver.CandidateMethods) |
21 | | - { |
22 | | - var model = compilation.GetSemanticModel(m.SyntaxTree); |
23 | | - |
24 | | - if (GetSemanticTargetForGeneration(model, m) is { } t) |
25 | | - yield return t; |
26 | | - } |
27 | | - } |
28 | | - } |
29 | | - |
30 | | - public void Initialize(GeneratorInitializationContext context) |
31 | | - { |
32 | | - context.RegisterForPostInitialization(AddAttribute); |
33 | | - context.RegisterForSyntaxNotifications(() => new SyntaxReceiver()); |
34 | | - } |
35 | | - |
36 | | - class SyntaxReceiver : ISyntaxReceiver |
37 | | - { |
38 | | - public List<MethodDeclarationSyntax> CandidateMethods { get; } = new List<MethodDeclarationSyntax>(); |
39 | | - |
40 | | - public void OnVisitSyntaxNode(SyntaxNode syntaxNode) |
41 | | - { |
42 | | - // any field with at least one attribute is a candidate for property generation |
43 | | - if (IsSyntaxTargetForGeneration(syntaxNode)) |
44 | | - { |
45 | | - CandidateMethods.Add((MethodDeclarationSyntax)syntaxNode); |
46 | | - } |
47 | | - } |
| 21 | + context.RegisterSourceOutput(provider, Emit); |
48 | 22 | } |
49 | 23 | } |
0 commit comments