Files
Ryan f9ccf4c1c4 Move Bound struct out of SpacetimeDB.Internal to SpacetimeDB and Local out of SpacetiemDB.Runtime (#3996)
# Description of Changes
This PR fixes a C# SDK regression where using `Bound` in index filters
could trigger an ambiguous reference compiler error for Local after
upgrading to `v1.11.2`, as reported in
[#3995](https://github.com/clockworklabs/SpacetimeDB/issues/3995).
It also fixes a related warning-spam regression (`CS0436`) where user
projects could see `Local` type conflicts between generated module code
and the `SpacetimeDB.Runtime` assembly.

* Introduced a public `SpacetimeDB.Bound` type so users no longer need
to import `SpacetimeDB.Internal` to use bounds in index filters.
* Kept `SpacetimeDB.Internal.Bound` for compatibility, but added
implicit conversions between `SpacetimeDB.Internal.Bound` and
`SpacetimeDB.Bound`.
* Updated the C# code generator to emit fully-qualified
`global::SpacetimeDB.Bound` in generated index filter signatures,
avoiding `SpacetimeDB.Internal` in public-facing APIs and preventing
name collisions (e.g., `Local`).
* Updated internal runtime bounds helpers (`BTreeIndexBounds<...>`) to
explicitly use `SpacetimeDB.Bound` when constructing range-scan
arguments.
* Updated Codegen snapshot fixtures to match the new generated output
(type name + formatting).
* Fixed codegen output for `ITableView` `static abstract` member
implementations to generate `public static` methods (required for the
generated code to compile).
It also fixes a related warning-spam regression (CS0436) where user
projects could see Local type conflicts between generated module code
and the SpacetimeDB.Runtime assembly.

Additional fix (related to the `Local` reports):
* Removed the runtime assembly’s ownership of `SpacetimeDB.Local`
(introduced more recently than the generated module `Local`) to prevent
`CS0436` duplicate-type warnings. Basically, the runtime’s concrete
`Local`/`ProcedureTxContext` helpers were renamed and made internal so
the code generator remains the sole owner of module-level
`SpacetimeDB.Local`.

Regression coverage:
* Added generator regression assertions to ensure generated code does
not reference `global::SpacetimeDB.Internal.Bound<...>` and does
reference `global::SpacetimeDB.Bound<...>`.
* Added a runtime API regression assertion that `SpacetimeDB.Bound`
exists and is public in the runtime reference.
* Added a regression assertion that `SpacetimeDB.Runtime` does not
define codegen-owned types (e.g. `SpacetimeDB.Local`,
`ProcedureContext`, etc.) to prevent future `CS0436` conflicts.
* Added a “simulated downstream user file” compile check ensuring no
`CS0436` diagnostics occur when user code references
`SpacetimeDB.Local`.
# API and ABI breaking changes
None.
* No schema or wire-format changes.
* The changes are limited to C# type exposure / naming and codegen
output.
* `SpacetimeDB.Internal.Bound` remains usable via implicit conversions
(backwards compatible for existing code).
# Expected complexity level and risk
2 - Low
* Changes are isolated to C# runtime type exposure, codegen type
references, and snapshot updates.
* No runtime behavior changes to index scan encoding/decoding; only
avoids requiring SpacetimeDB.Internal in user code.
# Testing
- [X] Ran:`dotnet test
crates/bindings-csharp/Codegen.Tests/Codegen.Tests.csproj`
- [X] Ran regression tests locally.
2026-01-14 22:42:30 +00:00

244 lines
9.4 KiB
C#

namespace SpacetimeDB.Codegen.Tests;
using System.Collections.Immutable;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.CodeAnalysis.Text;
public static class GeneratorSnapshotTests
{
// Note that we can't use assembly path here because it will be put in some deep nested folder.
// Instead, to get the test project directory, we can use the `CallerFilePath` attribute which will magically give us path to the current file.
static string GetProjectDir([CallerFilePath] string path = "") => Path.GetDirectoryName(path)!;
record struct StepOutput(string Key, IncrementalStepRunReason Reason, object Value);
class Fixture(string projectDir, CSharpCompilation sampleCompilation)
{
public static async Task<Fixture> Compile(string name)
{
var projectDir = Path.Combine(GetProjectDir(), "fixtures", name);
using var workspace = MSBuildWorkspace.Create();
var sampleProject = await workspace.OpenProjectAsync($"{projectDir}/{name}.csproj");
var compilation = await sampleProject.GetCompilationAsync();
return new(projectDir, (CSharpCompilation)compilation!);
}
private static CSharpGeneratorDriver CreateDriver(
IIncrementalGenerator generator,
LanguageVersion languageVersion
)
{
return CSharpGeneratorDriver.Create(
[generator.AsSourceGenerator()],
driverOptions: new(
disabledOutputs: IncrementalGeneratorOutputKind.None,
trackIncrementalGeneratorSteps: true
),
// Make sure that generated files are parsed with the same language version.
parseOptions: new(languageVersion)
);
}
public Task Verify(string fileName, object target) =>
Verifier.Verify(target).UseDirectory($"{projectDir}/snapshots").UseFileName(fileName);
private async Task<IEnumerable<SyntaxTree>> RunAndCheckGenerator(
IIncrementalGenerator generator
)
{
var driver = CreateDriver(generator, sampleCompilation.LanguageVersion);
// Store the new driver instance - it contains the results and the cache.
var driverAfterGen = driver.RunGenerators(sampleCompilation);
var genResult = driverAfterGen.GetRunResult();
// Verify the generated code against the snapshots.
await Verify(generator.GetType().Name, genResult);
CheckCacheWorking(sampleCompilation, driverAfterGen);
return genResult.GeneratedTrees;
}
public async Task<CSharpCompilation> RunAndCheckGenerators(
params IIncrementalGenerator[] generators
) =>
sampleCompilation.AddSyntaxTrees(
(await Task.WhenAll(generators.Select(RunAndCheckGenerator))).SelectMany(output =>
output
)
);
}
private static void CheckCacheWorking(
CSharpCompilation sampleCompilation,
GeneratorDriver driverAfterGen
)
{
// Run again with a driver containing the cache and a trivially modified code to verify that the cache is working.
var modifiedCompilation = sampleCompilation
.RemoveAllSyntaxTrees()
.AddSyntaxTrees(
sampleCompilation.SyntaxTrees.Select(tree =>
tree.WithChangedText(
SourceText.From(
string.Join(
"\n",
tree.GetText().Lines.Select(line => $"{line} // Modified")
)
)
)
)
);
var driverAfterRegen = driverAfterGen.RunGenerators(modifiedCompilation);
var regenSteps = driverAfterRegen
.GetRunResult()
.Results.SelectMany(result => result.TrackedSteps)
.Where(step => step.Key.StartsWith("SpacetimeDB."))
.SelectMany(step =>
step.Value.SelectMany(value => value.Outputs)
.Select(output => new StepOutput(step.Key, output.Reason, output.Value))
)
.ToImmutableArray();
// Ensure that we have tracked steps at all.
Assert.NotEmpty(regenSteps);
// Ensure that all steps were cached.
Assert.Empty(
regenSteps.Where(step =>
step.Reason
is not (IncrementalStepRunReason.Cached or IncrementalStepRunReason.Unchanged)
)
);
}
static IEnumerable<Diagnostic> GetCompilationErrors(Compilation compilation)
{
return compilation
.Emit(Stream.Null)
.Diagnostics.Where(diag => diag.Severity != DiagnosticSeverity.Hidden)
// The order of diagnostics is not predictable, sort them by location to make the test deterministic.
.OrderBy(diag => diag.GetMessage() + diag.Location.ToString());
}
static void AssertGeneratedCodeDoesNotUseInternalBound(CSharpCompilation compilation)
{
var generatedText = string.Join(
"\n\n",
compilation.SyntaxTrees.Select(tree => tree.GetText().ToString())
);
Assert.DoesNotContain("global::SpacetimeDB.Internal.Bound<", generatedText);
Assert.Contains("global::SpacetimeDB.Bound<", generatedText);
}
static void AssertPublicBoundIsAvailableInRuntime(Compilation compilation)
{
var bound = compilation.GetTypeByMetadataName("SpacetimeDB.Bound`1");
Assert.NotNull(bound);
Assert.Equal(Accessibility.Public, bound!.DeclaredAccessibility);
}
static void AssertRuntimeDoesNotDefineLocal(Compilation compilation)
{
var runtimeAssembly = compilation
.References.Select(r => compilation.GetAssemblyOrModuleSymbol(r))
.OfType<IAssemblySymbol>()
.FirstOrDefault(a => a.Name == "SpacetimeDB.Runtime");
Assert.NotNull(runtimeAssembly);
// These types are generated per-module by SpacetimeDB.Codegen.Module.
// If Runtime defines any of them too, user projects can hit CS0436 warnings.
var codegenOwnedTypes = new[]
{
"SpacetimeDB.Local",
"SpacetimeDB.ProcedureContext",
"SpacetimeDB.ProcedureTxContext",
"SpacetimeDB.ReducerContext",
"SpacetimeDB.ViewContext",
"SpacetimeDB.AnonymousViewContext",
};
foreach (var name in codegenOwnedTypes)
{
Assert.Null(runtimeAssembly!.GetTypeByMetadataName(name));
}
}
static void AssertNoCs0436Diagnostics(Compilation compilation)
{
var diagnostics = compilation
.Emit(Stream.Null)
.Diagnostics.Where(diag => diag.Severity != DiagnosticSeverity.Hidden);
Assert.DoesNotContain(diagnostics, d => d.Id == "CS0436");
}
[Fact]
public static async Task TypeGeneratorOnClient()
{
var fixture = await Fixture.Compile("client");
var compilationAfterGen = await fixture.RunAndCheckGenerators(
new SpacetimeDB.Codegen.Type()
);
Assert.Empty(GetCompilationErrors(compilationAfterGen));
}
[Fact]
public static async Task TypeAndModuleGeneratorsOnServer()
{
var fixture = await Fixture.Compile("server");
var compilationAfterGen = await fixture.RunAndCheckGenerators(
new SpacetimeDB.Codegen.Type(),
new SpacetimeDB.Codegen.Module()
);
Assert.Empty(GetCompilationErrors(compilationAfterGen));
AssertPublicBoundIsAvailableInRuntime(compilationAfterGen);
AssertRuntimeDoesNotDefineLocal(compilationAfterGen);
AssertGeneratedCodeDoesNotUseInternalBound(compilationAfterGen);
// Regression guard for user-reported warning spam:
// make sure a downstream "user" file that references SpacetimeDB.Local doesn't trigger CS0436.
var userCode =
"namespace User; public sealed class UseLocal { public SpacetimeDB.Local Db; }";
var userTree = CSharpSyntaxTree.ParseText(
userCode,
new CSharpParseOptions(compilationAfterGen.LanguageVersion)
);
var compilationWithUserCode = compilationAfterGen.AddSyntaxTrees(userTree);
AssertNoCs0436Diagnostics(compilationWithUserCode);
}
[Fact]
public static async Task TestDiagnostics()
{
var fixture = await Fixture.Compile("diag");
var compilationAfterGen = await fixture.RunAndCheckGenerators(
new SpacetimeDB.Codegen.Type(),
new SpacetimeDB.Codegen.Module()
);
// Unlike in regular tests, we don't expect this compilation to succeed - it's supposed to be full of errors.
// We already reported the useful ones from the generator, but let's snapshot those emitted by the compiler as well.
// This way we can notice when they get particularly noisy and improve our codegen for the case of a broken code.
await fixture.Verify("ExtraCompilationErrors", GetCompilationErrors(compilationAfterGen));
AssertPublicBoundIsAvailableInRuntime(compilationAfterGen);
AssertRuntimeDoesNotDefineLocal(compilationAfterGen);
AssertGeneratedCodeDoesNotUseInternalBound(compilationAfterGen);
}
}