|
| 1 | +using System.Buffers; |
| 2 | +using System.Collections.Immutable; |
| 3 | +using System.Reflection; |
| 4 | +using System.Text; |
| 5 | +using Microsoft.CodeAnalysis; |
| 6 | +using Microsoft.CodeAnalysis.CSharp; |
| 7 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 8 | + |
| 9 | +namespace StackExchange.Redis.Build; |
| 10 | + |
| 11 | +[Generator(LanguageNames.CSharp)] |
| 12 | +public class FastHashGenerator : IIncrementalGenerator |
| 13 | +{ |
| 14 | + public void Initialize(IncrementalGeneratorInitializationContext context) |
| 15 | + { |
| 16 | + var literals = context.SyntaxProvider |
| 17 | + .CreateSyntaxProvider(Predicate, Transform) |
| 18 | + .Where(pair => pair.Name is { Length: > 0 }) |
| 19 | + .Collect(); |
| 20 | + |
| 21 | + context.RegisterSourceOutput(literals, Generate); |
| 22 | + } |
| 23 | + |
| 24 | + private bool Predicate(SyntaxNode node, CancellationToken cancellationToken) |
| 25 | + { |
| 26 | + // looking for [FastHash] partial static class Foo { } |
| 27 | + if (node is ClassDeclarationSyntax decl |
| 28 | + && decl.Modifiers.Any(SyntaxKind.StaticKeyword) |
| 29 | + && decl.Modifiers.Any(SyntaxKind.PartialKeyword)) |
| 30 | + { |
| 31 | + foreach (var attribList in decl.AttributeLists) |
| 32 | + { |
| 33 | + foreach (var attrib in attribList.Attributes) |
| 34 | + { |
| 35 | + if (attrib.Name.ToString() is "FastHashAttribute" or "FastHash") return true; |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + return false; |
| 41 | + } |
| 42 | + |
| 43 | + private (string Namespace, string ParentType, string Name, string Value) Transform( |
| 44 | + GeneratorSyntaxContext ctx, |
| 45 | + CancellationToken cancellationToken) |
| 46 | + { |
| 47 | + // extract the name and value (defaults to name, but can be overridden via attribute) and the location |
| 48 | + if (ctx.SemanticModel.GetDeclaredSymbol(ctx.Node) is not INamedTypeSymbol named) return default; |
| 49 | + string ns = "", parentType = ""; |
| 50 | + if (named.ContainingType is { } containingType) |
| 51 | + { |
| 52 | + parentType = containingType.Name; // don't worry about multi-level nesting for now; add later if needed |
| 53 | + ns = containingType.ContainingNamespace.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat); |
| 54 | + } |
| 55 | + else if (named.ContainingNamespace is { } containingNamespace) |
| 56 | + { |
| 57 | + ns = containingNamespace.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat); |
| 58 | + } |
| 59 | + |
| 60 | + string name = named.Name, value = ""; |
| 61 | + foreach (var attrib in named.GetAttributes()) |
| 62 | + { |
| 63 | + if (attrib.AttributeClass?.Name == "FastHashAttribute") |
| 64 | + { |
| 65 | + if (attrib.ConstructorArguments.Length == 1) |
| 66 | + { |
| 67 | + if (attrib.ConstructorArguments[0].Value?.ToString() is { Length: > 0 } val) |
| 68 | + { |
| 69 | + value = val; |
| 70 | + break; |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + if (string.IsNullOrWhiteSpace(value)) |
| 77 | + { |
| 78 | + value = name.Replace("_", "-"); // if nothing explicit: infer from name |
| 79 | + } |
| 80 | + |
| 81 | + return (ns, parentType, name, value); |
| 82 | + } |
| 83 | + |
| 84 | + private string GetVersion() |
| 85 | + { |
| 86 | + var asm = GetType().Assembly; |
| 87 | + if (asm.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false).FirstOrDefault() is |
| 88 | + AssemblyFileVersionAttribute { Version: { Length: > 0 } } version) |
| 89 | + { |
| 90 | + return version.Version; |
| 91 | + } |
| 92 | + |
| 93 | + return asm.GetName().Version?.ToString() ?? "??"; |
| 94 | + } |
| 95 | + |
| 96 | + private void Generate( |
| 97 | + SourceProductionContext ctx, |
| 98 | + ImmutableArray<(string Namespace, string ParentType, string Name, string Value)> literals) |
| 99 | + { |
| 100 | + if (literals.IsDefaultOrEmpty) return; |
| 101 | + |
| 102 | + var sb = new StringBuilder("// <auto-generated />") |
| 103 | + .AppendLine().Append("// ").Append(GetType().Name).Append(" v").Append(GetVersion()).AppendLine(); |
| 104 | + |
| 105 | + // lease a buffer that is big enough for the longest string |
| 106 | + var buffer = ArrayPool<byte>.Shared.Rent( |
| 107 | + Encoding.UTF8.GetMaxByteCount(literals.Max(l => l.Value.Length))); |
| 108 | + int indent = 0; |
| 109 | + |
| 110 | + StringBuilder NewLine() => sb.AppendLine().Append(' ', indent * 4); |
| 111 | + NewLine().Append("using System;"); |
| 112 | + NewLine().Append("using StackExchange.Redis;"); |
| 113 | + NewLine().Append("#pragma warning disable CS8981"); |
| 114 | + foreach (var grp in literals.GroupBy(l => (l.Namespace, l.ParentType))) |
| 115 | + { |
| 116 | + NewLine(); |
| 117 | + if (!string.IsNullOrWhiteSpace(grp.Key.Namespace)) |
| 118 | + { |
| 119 | + NewLine().Append("namespace ").Append(grp.Key.Namespace); |
| 120 | + NewLine().Append("{"); |
| 121 | + indent++; |
| 122 | + } |
| 123 | + if (!string.IsNullOrWhiteSpace(grp.Key.ParentType)) |
| 124 | + { |
| 125 | + NewLine().Append("partial class ").Append(grp.Key.ParentType); |
| 126 | + NewLine().Append("{"); |
| 127 | + indent++; |
| 128 | + } |
| 129 | + |
| 130 | + foreach (var literal in grp) |
| 131 | + { |
| 132 | + int len; |
| 133 | + unsafe |
| 134 | + { |
| 135 | + fixed (byte* bPtr = buffer) // netstandard2.0 forces fallback API |
| 136 | + { |
| 137 | + fixed (char* cPtr = literal.Value) |
| 138 | + { |
| 139 | + len = Encoding.UTF8.GetBytes(cPtr, literal.Value.Length, bPtr, buffer.Length); |
| 140 | + } |
| 141 | + } |
| 142 | + } |
| 143 | + |
| 144 | + var hash = FastHash.Hash64(buffer.AsSpan(0, len)); |
| 145 | + NewLine().Append("static partial class ").Append(literal.Name); |
| 146 | + NewLine().Append("{"); |
| 147 | + indent++; |
| 148 | + NewLine().Append("public const int Length = ").Append(len).Append(';'); |
| 149 | + NewLine().Append("public const long Hash = ").Append(hash).Append(';'); |
| 150 | + NewLine().Append("public static ReadOnlySpan<byte> U8 => @\"") |
| 151 | + .Append(literal.Value.Replace("\"", "\"\"")).Append("\"u8;"); |
| 152 | + NewLine().Append("public static string Text => @\"") |
| 153 | + .Append(literal.Value.Replace("\"", "\"\"")).Append("\";"); |
| 154 | + NewLine().Append("public static bool Is(long hash, in RawResult value) => hash == Hash && value.IsEqual(U8);"); |
| 155 | + indent--; |
| 156 | + NewLine().Append("}"); |
| 157 | + } |
| 158 | + |
| 159 | + if (!string.IsNullOrWhiteSpace(grp.Key.ParentType)) |
| 160 | + { |
| 161 | + indent--; |
| 162 | + NewLine().Append("}"); |
| 163 | + } |
| 164 | + if (!string.IsNullOrWhiteSpace(grp.Key.Namespace)) |
| 165 | + { |
| 166 | + indent--; |
| 167 | + NewLine().Append("}"); |
| 168 | + } |
| 169 | + } |
| 170 | + |
| 171 | + ArrayPool<byte>.Shared.Return(buffer); |
| 172 | + ctx.AddSource("FastHash.generated.cs", sb.ToString()); |
| 173 | + } |
| 174 | +} |
0 commit comments