forked from codecentric/net_automatic_interface
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathRoslynExtensions.cs
More file actions
84 lines (70 loc) · 2.3 KB
/
Copy pathRoslynExtensions.cs
File metadata and controls
84 lines (70 loc) · 2.3 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace DotnetAutomaticInterface;
/// <summary>
/// Source: https://github.com/dominikjeske/Samples/blob/main/SourceGenerators/HomeCenter.SourceGenerators/Extensions/RoslynExtensions.cs
/// </summary>
/// <remarks>
/// Enhancements or additional Roslyn-related extension methods should be placed in <see cref="RoslynExtensionsAutomaticInterface"/>
/// </remarks>
public static class RoslynExtensions
{
private static IEnumerable<ITypeSymbol> GetBaseTypesAndThis(this ITypeSymbol type)
{
var current = type;
while (current != null)
{
yield return current;
current = current.BaseType;
}
}
public static IEnumerable<ISymbol> GetAllMembers(this ITypeSymbol type)
{
return type.GetBaseTypesAndThis().SelectMany(n => n.GetMembers());
}
public static string GetClassName(this ClassDeclarationSyntax proxy)
{
return proxy.Identifier.Text;
}
/// <summary>
/// Thanks to https://www.codeproject.com/Articles/871704/Roslyn-Code-Analysis-in-Easy-Samples-Part-2
/// </summary>
public static string GetWhereStatement(
this ITypeParameterSymbol typeParameterSymbol,
SymbolDisplayFormat typeDisplayFormat
)
{
var result = $"where {typeParameterSymbol.Name} : ";
var constraints = new List<string>();
if (typeParameterSymbol.HasReferenceTypeConstraint)
{
constraints.Add("class");
}
if (typeParameterSymbol.HasValueTypeConstraint)
{
constraints.Add("struct");
}
if (typeParameterSymbol.HasNotNullConstraint)
{
constraints.Add("notnull");
}
constraints.AddRange(
typeParameterSymbol.ConstraintTypes.Select(t => t.ToDisplayString(typeDisplayFormat))
);
// The new() constraint must be last
if (typeParameterSymbol.HasConstructorConstraint)
{
constraints.Add("new()");
}
if (constraints.Count == 0)
{
return "";
}
result += string.Join(", ", constraints);
return result;
}
}