Skip to content

Commit 4ac4dd2

Browse files
kzucodealta-agentcursoragent
committed
Reuse generated stunts across builds and projects while their types keep their shape.
Stunts are cached in .vs/stunts-cache at the git root (from source control information), keyed by a fingerprint of the generator, the compilation-wide inputs processors read, and the declarations and member signatures of the stunt's types. Unchanged rebuilds skip processing entirely, and test projects consuming the same interfaces share the entries. Co-authored-by: CodeAlta <noreply@codealta.io> Co-authored-by: Cursor <cursoragent@cursor.com>
1 parent 09ed419 commit 4ac4dd2

10 files changed

Lines changed: 1380 additions & 38 deletions

File tree

‎AGENTS.md‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,50 @@ Roslyn compares source hint names case-insensitively; qualify them and disambigu
243243
case-only collisions without changing generated type names. Sealed targets report
244244
`ST003` while other candidates continue generating.
245245

246+
### Generation cache
247+
248+
`StuntCache` reuses the emitted text of a stunt while the types it implements keep their shape,
249+
across builds and across projects. `Stunts.targets` (`ResolveStuntsCacheDir`, before
250+
`GenerateMSBuildEditorConfigFileShouldRun`) sets the compiler-visible `StuntsCacheDir` to
251+
`.vs/stunts-cache/` at the repository root, then the solution directory, then `obj/stunts-cache/`.
252+
The root is the git `SourceRoot` without `NestedRoot` from `InitializeSourceControlInformation`
253+
(as in ThisAssembly.Git): the repository containing the project, so worktrees and submodules get
254+
their own.
255+
`EnableStuntsCache=false` clears it. Without the property (unit tests, other hosts) nothing is
256+
cached. Entries live in a folder per generator version (`StuntFingerprint.Version`: the MVIDs of
257+
the generator, Roslyn, and processor assemblies), one content-addressed `.stunt` file per key,
258+
written to a temporary file and renamed so concurrent builds never read partial entries. A
259+
bounded in-memory copy, keyed by path, serves later compilations in the same compiler server.
260+
Pruning runs at most daily: entries not read for 30 days, other versions' folders not written
261+
for 7.
262+
263+
`StuntFingerprint` keys hash the compilation-wide inputs processors read (generator
264+
configuration, the `DefaultImports` namespaces, the host culture, language version, nullable,
265+
unsafe and metadata import options, pretty-printing, by-ref-like generics support, the corlib
266+
identity, and the accessibility of the optional attributes the generated code uses, looked up
267+
in the compilation the stunt binds against: the treeless one for metadata-only stunts), plus
268+
each candidate type's declaration: attributes, containers, base types, interfaces, and every
269+
member signature, including inherited ones and overridden members. Types used by those
270+
signatures contribute their identity, kind, flags, accessibility, bases, interfaces, and
271+
delegate signature, but not their members; attribute classes also contribute the
272+
`AttributeUsage` of their base chain and the accessibility of named arguments' members.
273+
Stunt keys also include the stunt's full name and the colliding default implementation names its
274+
interfaces use, since collisions with the other stunts of a generation change them; default
275+
implementation keys include their class name.
276+
Processors from other assemblies disable the cache, since their inputs are unknown. Assemblies contribute only their
277+
relation to the compilation (`self`, `friend` through `InternalsVisibleTo`, or `other`), so a
278+
rebuilt or re-versioned library keeps its entries and test heads share them. Anything a
279+
processor starts reading from the compilation must be added to the fingerprint, or hits
280+
will emit stale code.
281+
282+
An entry stores the text added for the stunt (pretty-printed when `EmitCompilerGeneratedFiles`
283+
is on), the flags that replay ST006/ST015 and the unchanged-scaffold skip, and the names of the
284+
interfaces whose default implementation classes it calls; those classes are cached under their
285+
own keys. Registration still runs every time: delegate and nested stunts are parsed back from
286+
the cached text so their forwarders bind. `StuntCacheTests` covers hits, signature changes,
287+
cross-project sharing, friend assemblies, nested and delegate stunts, default implementations,
288+
diagnostics replay, name collisions, culture changes and custom processors; `STUNTS_PROFILE` reports hits, misses and the cache time.
289+
246290
### Signature compatibility
247291

248292
`MemberScaffold` preserves optional defaults, escaped identifiers, indexer metadata names,

‎readme.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,6 +290,13 @@ Compile-time stunts support optional parameters, inherited generic constraints,
290290
and `ref`/`out` arguments alongside spans and other ref structs. Ref-struct and pointer signatures
291291
require unsafe blocks to be enabled.
292292

293+
Generated stunts are cached in `.vs/stunts-cache` at the repository root, a folder the standard
294+
.NET `.gitignore` already excludes. A later build reuses a stunt as long as the types it implements
295+
keep the same declarations and member signatures, so changing method bodies, tests or unrelated
296+
types doesn't regenerate it. Every project in the repository shares the cache, so an interface
297+
consumed by several test projects is generated once. Set `StuntsCacheDir` to use another folder,
298+
or `<EnableStuntsCache>false</EnableStuntsCache>` to always regenerate.
299+
293300
Unsupported targets produce diagnostics at the factory call: `ST012` identifies inaccessible
294301
abstract interface members (such as an internal setter from another assembly, which C# cannot
295302
implement), while `ST013` identifies signatures using `TypedReference`, `ArgIterator`, or

‎src/Stunts.CodeAnalysis/BuildProperties.cs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@ public static class Name
3434
/// <summary><c>DebugSourceGenerators</c>.</summary>
3535
public const string DebugSourceGenerators = "build_property.DebugSourceGenerators";
3636

37+
/// <summary><c>StuntsCacheDir</c>.</summary>
38+
public const string StuntsCacheDir = "build_property.StuntsCacheDir";
39+
3740
/// <summary><c>Debug</c> plus the generator name, such as <c>DebugStuntGenerator</c>.</summary>
3841
public static string Debug(string generator) => "build_property.Debug" + generator;
3942
}
@@ -69,6 +72,10 @@ public static bool EmitCompilerGeneratedFiles(AnalyzerConfigOptions options)
6972
public static string? MSBuildProjectDirectory(AnalyzerConfigOptions options)
7073
=> Text(options, Name.MSBuildProjectDirectory);
7174

75+
/// <summary>Directory where generated stunts are cached across builds and projects.</summary>
76+
public static string? StuntsCacheDir(AnalyzerConfigOptions options)
77+
=> Text(options, Name.StuntsCacheDir);
78+
7279
/// <summary><c>DebugSourceGenerators</c> is true.</summary>
7380
public static bool DebugSourceGenerators(AnalyzerConfigOptions options)
7481
=> IsTrue(options, Name.DebugSourceGenerators);

‎src/Stunts.CompiledProxy/Processors/DefaultImports.cs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,9 @@ public DefaultImports() : this(DefaultNamespaces) { }
3737
/// </summary>
3838
public DefaultImports(params string[] namespaces) => this.namespaces = namespaces;
3939

40+
/// <summary>The namespaces this processor adds.</summary>
41+
internal IReadOnlyList<string> Namespaces => namespaces;
42+
4043
/// <summary>
4144
/// Applies to <see cref="LanguageNames.CSharp"/>.
4245
/// </summary>
Lines changed: 264 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,264 @@
1+
using System;
2+
using System.Collections.Concurrent;
3+
using System.Collections.Generic;
4+
using System.Globalization;
5+
using System.IO;
6+
using System.Text;
7+
using System.Threading;
8+
using Microsoft.CodeAnalysis.Diagnostics;
9+
10+
namespace Stunts
11+
{
12+
/// <summary>What the generator needs from a stunt besides its text.</summary>
13+
[Flags]
14+
enum StuntCacheFlags
15+
{
16+
None = 0,
17+
/// <summary>The processors left the scaffold unchanged, so nothing is emitted.</summary>
18+
Unchanged = 1,
19+
/// <summary>The stunt has no instance constructor (ST006).</summary>
20+
NoConstructor = 2,
21+
GenericMethods = 4,
22+
AotQueryable = 8,
23+
AotRefStruct = 16,
24+
}
25+
26+
/// <summary>A cached generation result.</summary>
27+
sealed class StuntCacheEntry
28+
{
29+
public StuntCacheEntry(StuntCacheFlags flags, IReadOnlyList<string> defaults, string? code)
30+
=> (Flags, Defaults, Code) = (flags, defaults, code);
31+
32+
public StuntCacheFlags Flags { get; }
33+
34+
/// <summary>Interfaces whose default implementation class the stunt calls, as <see cref="StuntFingerprint.Name"/>.</summary>
35+
public IReadOnlyList<string> Defaults { get; }
36+
37+
/// <summary>The source added for the stunt, before registration nests forwarders in it.</summary>
38+
public string? Code { get; }
39+
40+
internal string Write()
41+
{
42+
var builder = new StringBuilder()
43+
.Append(Header).Append('\n')
44+
.Append("flags ").Append(((int)Flags).ToString(CultureInfo.InvariantCulture)).Append('\n');
45+
foreach (var name in Defaults)
46+
builder.Append("default ").Append(name).Append('\n');
47+
48+
var code = Code ?? "";
49+
return builder.Append("code ").Append(code.Length.ToString(CultureInfo.InvariantCulture)).Append('\n')
50+
.Append(code).ToString();
51+
}
52+
53+
internal static StuntCacheEntry? Read(string text)
54+
{
55+
var position = 0;
56+
if (Line(text, ref position) != Header)
57+
return null;
58+
59+
var flags = StuntCacheFlags.None;
60+
var defaults = new List<string>();
61+
while (Line(text, ref position) is string line)
62+
{
63+
if (line.StartsWith("flags ", StringComparison.Ordinal) &&
64+
int.TryParse(line.Substring(6), NumberStyles.None, CultureInfo.InvariantCulture, out var value))
65+
flags = (StuntCacheFlags)value;
66+
else if (line.StartsWith("default ", StringComparison.Ordinal))
67+
defaults.Add(line.Substring(8));
68+
else if (line.StartsWith("code ", StringComparison.Ordinal) &&
69+
int.TryParse(line.Substring(5), NumberStyles.None, CultureInfo.InvariantCulture, out var length))
70+
// A length mismatch is a damaged or foreign file: regenerate.
71+
return text.Length - position == length
72+
? new StuntCacheEntry(flags, defaults, (flags & (StuntCacheFlags.Unchanged | StuntCacheFlags.NoConstructor)) != 0 ? null : text.Substring(position))
73+
: null;
74+
else
75+
return null;
76+
}
77+
78+
return null;
79+
}
80+
81+
const string Header = "stunts-cache 1";
82+
83+
static string? Line(string text, ref int position)
84+
{
85+
var end = text.IndexOf('\n', position);
86+
if (end < 0)
87+
return null;
88+
89+
var line = text.Substring(position, end - position);
90+
position = end + 1;
91+
return line;
92+
}
93+
}
94+
95+
/// <summary>
96+
/// Generation results shared by builds and projects, keyed by <see cref="StuntFingerprint"/>.
97+
/// Entries live in a folder per generator version under <c>StuntsCacheDir</c>, plus an
98+
/// in-memory copy for the lifetime of the compiler server process.
99+
/// </summary>
100+
sealed class StuntCache
101+
{
102+
const string Extension = ".stunt";
103+
// Characters of cached code kept in memory before it is dropped.
104+
const long MemoryBudget = 32L * 1024 * 1024;
105+
static readonly TimeSpan PruneInterval = TimeSpan.FromDays(1);
106+
static readonly TimeSpan TouchAge = TimeSpan.FromDays(7);
107+
static readonly TimeSpan EntryAge = TimeSpan.FromDays(30);
108+
static readonly TimeSpan VersionAge = TimeSpan.FromDays(7);
109+
110+
static readonly ConcurrentDictionary<string, StuntCacheEntry> memory = new(StringComparer.Ordinal);
111+
static long memorySize;
112+
113+
readonly string root;
114+
readonly string directory;
115+
int hits;
116+
int misses;
117+
118+
StuntCache(string root, string directory) => (this.root, this.directory) = (root, directory);
119+
120+
/// <summary>Opens the cache under <c>StuntsCacheDir</c>, or returns null when it is not set.</summary>
121+
public static StuntCache? Create(AnalyzerConfigOptions options, string version)
122+
{
123+
if (BuildProperties.StuntsCacheDir(options) is not string root)
124+
return null;
125+
126+
try
127+
{
128+
root = Path.GetFullPath(root);
129+
var directory = Path.Combine(root, version);
130+
Directory.CreateDirectory(directory);
131+
var cache = new StuntCache(root, directory);
132+
cache.Prune();
133+
return cache;
134+
}
135+
catch (Exception ex) when (IsIOException(ex))
136+
{
137+
return null;
138+
}
139+
}
140+
141+
public int Hits => hits;
142+
143+
public int Misses => misses;
144+
145+
public StuntCacheEntry? Get(string key)
146+
{
147+
var path = Path.Combine(directory, key + Extension);
148+
// Keyed by path, so each cache folder keeps its own entries.
149+
if (memory.TryGetValue(path, out var entry))
150+
{
151+
Interlocked.Increment(ref hits);
152+
return entry;
153+
}
154+
155+
try
156+
{
157+
var info = new FileInfo(path);
158+
if (!info.Exists)
159+
{
160+
Interlocked.Increment(ref misses);
161+
return null;
162+
}
163+
164+
entry = StuntCacheEntry.Read(File.ReadAllText(path, Encoding.UTF8));
165+
if (entry == null)
166+
{
167+
Interlocked.Increment(ref misses);
168+
return null;
169+
}
170+
171+
// Entries in use survive pruning.
172+
if (DateTime.UtcNow - info.LastWriteTimeUtc > TouchAge)
173+
File.SetLastWriteTimeUtc(path, DateTime.UtcNow);
174+
}
175+
catch (Exception ex) when (IsIOException(ex))
176+
{
177+
Interlocked.Increment(ref misses);
178+
return null;
179+
}
180+
181+
Remember(path, entry);
182+
Interlocked.Increment(ref hits);
183+
return entry;
184+
}
185+
186+
public void Add(string key, StuntCacheEntry entry)
187+
{
188+
var path = Path.Combine(directory, key + Extension);
189+
Remember(path, entry);
190+
var temp = path + "." + Guid.NewGuid().ToString("N") + ".tmp";
191+
try
192+
{
193+
if (File.Exists(path))
194+
return;
195+
196+
File.WriteAllText(temp, entry.Write(), new UTF8Encoding(false));
197+
// Another build may have stored the same entry since. Its content is identical.
198+
try
199+
{
200+
File.Move(temp, path);
201+
}
202+
catch (IOException)
203+
{
204+
File.Delete(temp);
205+
}
206+
}
207+
catch (Exception ex) when (IsIOException(ex))
208+
{
209+
try { File.Delete(temp); } catch (Exception e) when (IsIOException(e)) { }
210+
}
211+
}
212+
213+
/// <summary>Drops the in-memory entries, so the next reads come from disk.</summary>
214+
internal static void ClearMemory()
215+
{
216+
memory.Clear();
217+
Interlocked.Exchange(ref memorySize, 0);
218+
}
219+
220+
static void Remember(string path, StuntCacheEntry entry)
221+
{
222+
if (memory.TryAdd(path, entry) &&
223+
Interlocked.Add(ref memorySize, entry.Code?.Length ?? 0) > MemoryBudget)
224+
ClearMemory();
225+
}
226+
227+
// At most once a day: entries not read for a month, temporary files, and the
228+
// folders of generator versions no build has written to for a week.
229+
void Prune()
230+
{
231+
var marker = Path.Combine(root, ".pruned");
232+
var now = DateTime.UtcNow;
233+
if (File.Exists(marker) && now - File.GetLastWriteTimeUtc(marker) < PruneInterval)
234+
return;
235+
236+
File.WriteAllText(marker, now.ToString("o", CultureInfo.InvariantCulture));
237+
foreach (var version in Directory.EnumerateDirectories(root))
238+
{
239+
try
240+
{
241+
if (!string.Equals(version, directory, StringComparison.OrdinalIgnoreCase) &&
242+
now - Directory.GetLastWriteTimeUtc(version) > VersionAge)
243+
{
244+
Directory.Delete(version, true);
245+
continue;
246+
}
247+
248+
foreach (var file in Directory.EnumerateFiles(version))
249+
{
250+
var age = now - File.GetLastWriteTimeUtc(file);
251+
if (file.EndsWith(".tmp", StringComparison.OrdinalIgnoreCase) ? age > PruneInterval : age > EntryAge)
252+
File.Delete(file);
253+
}
254+
}
255+
catch (Exception ex) when (IsIOException(ex))
256+
{
257+
}
258+
}
259+
}
260+
261+
static bool IsIOException(Exception ex)
262+
=> ex is IOException or UnauthorizedAccessException or System.Security.SecurityException or NotSupportedException or ArgumentException;
263+
}
264+
}

0 commit comments

Comments
 (0)