-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathFastHashGenerator.cs
More file actions
215 lines (194 loc) · 8.06 KB
/
FastHashGenerator.cs
File metadata and controls
215 lines (194 loc) · 8.06 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
using System.Buffers;
using System.Collections.Immutable;
using System.Reflection;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace StackExchange.Redis.Build;
[Generator(LanguageNames.CSharp)]
public class FastHashGenerator : IIncrementalGenerator
{
public void Initialize(IncrementalGeneratorInitializationContext context)
{
var literals = context.SyntaxProvider
.CreateSyntaxProvider(Predicate, Transform)
.Where(pair => pair.Name is { Length: > 0 })
.Collect();
context.RegisterSourceOutput(literals, Generate);
}
private bool Predicate(SyntaxNode node, CancellationToken cancellationToken)
{
// looking for [FastHash] partial static class Foo { }
if (node is ClassDeclarationSyntax decl
&& decl.Modifiers.Any(SyntaxKind.StaticKeyword)
&& decl.Modifiers.Any(SyntaxKind.PartialKeyword))
{
foreach (var attribList in decl.AttributeLists)
{
foreach (var attrib in attribList.Attributes)
{
if (attrib.Name.ToString() is "FastHashAttribute" or "FastHash") return true;
}
}
}
return false;
}
private static string GetName(INamedTypeSymbol type)
{
if (type.ContainingType is null) return type.Name;
var stack = new Stack<string>();
while (true)
{
stack.Push(type.Name);
if (type.ContainingType is null) break;
type = type.ContainingType;
}
var sb = new StringBuilder(stack.Pop());
while (stack.Count != 0)
{
sb.Append('.').Append(stack.Pop());
}
return sb.ToString();
}
private (string Namespace, string ParentType, string Name, string Value) Transform(
GeneratorSyntaxContext ctx,
CancellationToken cancellationToken)
{
// extract the name and value (defaults to name, but can be overridden via attribute) and the location
if (ctx.SemanticModel.GetDeclaredSymbol(ctx.Node) is not INamedTypeSymbol named) return default;
string ns = "", parentType = "";
if (named.ContainingType is { } containingType)
{
parentType = GetName(containingType);
ns = containingType.ContainingNamespace.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat);
}
else if (named.ContainingNamespace is { } containingNamespace)
{
ns = containingNamespace.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat);
}
string name = named.Name, value = "";
foreach (var attrib in named.GetAttributes())
{
if (attrib.AttributeClass?.Name == "FastHashAttribute")
{
if (attrib.ConstructorArguments.Length == 1)
{
if (attrib.ConstructorArguments[0].Value?.ToString() is { Length: > 0 } val)
{
value = val;
break;
}
}
}
}
if (string.IsNullOrWhiteSpace(value))
{
value = name.Replace("_", "-"); // if nothing explicit: infer from name
}
return (ns, parentType, name, value);
}
private string GetVersion()
{
var asm = GetType().Assembly;
if (asm.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false).FirstOrDefault() is
AssemblyFileVersionAttribute { Version: { Length: > 0 } } version)
{
return version.Version;
}
return asm.GetName().Version?.ToString() ?? "??";
}
private void Generate(
SourceProductionContext ctx,
ImmutableArray<(string Namespace, string ParentType, string Name, string Value)> literals)
{
if (literals.IsDefaultOrEmpty) return;
var sb = new StringBuilder("// <auto-generated />")
.AppendLine().Append("// ").Append(GetType().Name).Append(" v").Append(GetVersion()).AppendLine();
// lease a buffer that is big enough for the longest string
var buffer = ArrayPool<byte>.Shared.Rent(
Encoding.UTF8.GetMaxByteCount(literals.Max(l => l.Value.Length)));
int indent = 0;
StringBuilder NewLine() => sb.AppendLine().Append(' ', indent * 4);
NewLine().Append("using System;");
NewLine().Append("using StackExchange.Redis;");
NewLine().Append("#pragma warning disable CS8981");
foreach (var grp in literals.GroupBy(l => (l.Namespace, l.ParentType)))
{
NewLine();
int braces = 0;
if (!string.IsNullOrWhiteSpace(grp.Key.Namespace))
{
NewLine().Append("namespace ").Append(grp.Key.Namespace);
NewLine().Append("{");
indent++;
braces++;
}
if (!string.IsNullOrWhiteSpace(grp.Key.ParentType))
{
if (grp.Key.ParentType.Contains('.')) // nested types
{
foreach (var part in grp.Key.ParentType.Split('.'))
{
NewLine().Append("partial class ").Append(part);
NewLine().Append("{");
indent++;
braces++;
}
}
else
{
NewLine().Append("partial class ").Append(grp.Key.ParentType);
NewLine().Append("{");
indent++;
braces++;
}
}
foreach (var literal in grp)
{
int len;
unsafe
{
fixed (byte* bPtr = buffer) // netstandard2.0 forces fallback API
{
fixed (char* cPtr = literal.Value)
{
len = Encoding.UTF8.GetBytes(cPtr, literal.Value.Length, bPtr, buffer.Length);
}
}
}
// perform string escaping on the generated value (this includes the quotes, note)
var csValue = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(literal.Value)).ToFullString();
var hash = FastHash.Hash64(buffer.AsSpan(0, len));
NewLine().Append("static partial class ").Append(literal.Name);
NewLine().Append("{");
indent++;
NewLine().Append("public const int Length = ").Append(len).Append(';');
NewLine().Append("public const long Hash = ").Append(hash).Append(';');
NewLine().Append("public static ReadOnlySpan<byte> U8 => ").Append(csValue).Append("u8;");
NewLine().Append("public const string Text = ").Append(csValue).Append(';');
if (len <= 8)
{
// the hash enforces all the values
NewLine().Append("public static bool Is(long hash, in RawResult value) => hash == Hash && value.Payload.Length == Length;");
NewLine().Append("public static bool Is(long hash, ReadOnlySpan<byte> value) => hash == Hash & value.Length == Length;");
}
else
{
NewLine().Append("public static bool Is(long hash, in RawResult value) => hash == Hash && value.IsEqual(U8);");
NewLine().Append("public static bool Is(long hash, ReadOnlySpan<byte> value) => hash == Hash && value.SequenceEqual(U8);");
}
indent--;
NewLine().Append("}");
}
// handle any closing braces
while (braces-- > 0)
{
indent--;
NewLine().Append("}");
}
}
ArrayPool<byte>.Shared.Return(buffer);
ctx.AddSource("FastHash.generated.cs", sb.ToString());
}
}