forked from codecentric/net_automatic_interface
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAutomaticInterfaceGenerator.cs
More file actions
62 lines (52 loc) · 1.99 KB
/
Copy pathAutomaticInterfaceGenerator.cs
File metadata and controls
62 lines (52 loc) · 1.99 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
using System;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace DotnetAutomaticInterface;
[Generator]
public class AutomaticInterfaceGenerator : IIncrementalGenerator
{
public const string DefaultAttributeName = "GenerateAutomaticInterface";
public const string IgnoreAutomaticInterfaceAttributeName = "IgnoreAutomaticInterface";
public const string NamespaceParameterName = "namespaceName";
public const string InterfaceParameterName = "interfaceName";
public const string AsInternalParameterName = "asInternal";
public void Initialize(IncrementalGeneratorInitializationContext context)
{
context.RegisterDefaultAttribute();
context.RegisterIgnoreAttribute();
var classes = context
.SyntaxProvider.ForAttributeWithMetadataName(
$"DotnetAutomaticInterface.{DefaultAttributeName}Attribute",
(node, _) => node is ClassDeclarationSyntax,
(ctx, _) => (ITypeSymbol)ctx.TargetSymbol
)
.Collect();
context.RegisterSourceOutput(classes, GenerateCode);
}
private static void GenerateCode(
SourceProductionContext context,
ImmutableArray<ITypeSymbol> enumerations
)
{
if (enumerations.IsDefaultOrEmpty)
{
return;
}
var generatedInterfaceNames = enumerations
.Select(Builder.GetInterfaceNameFor)
.Where(name => name != null)
.Cast<string>()
.ToList();
foreach (var type in enumerations)
{
var typeNamespace = type.ContainingNamespace.IsGlobalNamespace
? $"${Guid.NewGuid()}"
: $"{type.ContainingNamespace}";
var code = Builder.BuildInterfaceFor(type, generatedInterfaceNames);
var hintName = $"{typeNamespace}.I{type.Name}";
context.AddSource(hintName, code);
}
}
}