Repository navigation
Diagnose static data-source properties in inaccessible containing types #7503
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
db2fa7a
49c5ce7
d41073e
e39d76c
48937b5
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -18,6 +18,14 @@ | |
| [Generator] | ||
| public class StaticPropertyInitializationGenerator : IIncrementalGenerator | ||
| { | ||
| private static readonly DiagnosticDescriptor InaccessibleContainingType = new( | ||
| "TUNITGEN005", | ||
|
Check warning on line 22 in src/TUnit.Core.SourceGenerator/CodeGenerators/StaticPropertyInitializationGenerator.cs
|
||
| "Static data-source property has an inaccessible containing type", | ||
| "Static data-source property '{0}' cannot be initialized because its containing type is inaccessible. Make the type and all containing types internal or public.", | ||
| "TUnit", | ||
| DiagnosticSeverity.Error, | ||
| true); | ||
|
|
||
| public const string ParseStaticProperties = "ParseStaticProperties"; | ||
|
|
||
| public void Initialize(IncrementalGeneratorInitializationContext context) | ||
|
|
@@ -38,10 +46,42 @@ | |
| predicate: static (node, _) => IsCandidateClass(node), | ||
| transform: static (ctx, ct) => GetStaticPropertyChain(ctx, ct)) | ||
| // Every chain contains the class itself, so drop chains without any static data-source | ||
| // property: they add nothing to the result, and keeping them out of the collected array | ||
| // property or diagnostic: they add nothing to the result, and keeping them out of the collected array | ||
| // stops unrelated classes (any class with a base list) from re-running the parse step. | ||
| .Where(static chain => HasAnyProperty(chain)); | ||
|
|
||
| context.RegisterSourceOutput(classChains.Collect().Combine(enabledProvider).Combine(context.CompilationProvider), static (ctx, pair) => | ||
| { | ||
| if (!pair.Left.Right) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| var reported = new HashSet<InaccessibleProperty>(); | ||
| foreach (var chain in pair.Left.Left) | ||
| { | ||
| foreach (var segment in chain) | ||
| { | ||
| foreach (var property in segment.InaccessibleProperties) | ||
| { | ||
| if (reported.Add(property)) | ||
| { | ||
| // Reattach to the current tree so pragmas and per-file diagnostic options apply. | ||
| // The compilation-relative ordinal distinguishes trees with identical paths, | ||
| // while discovery models retain only equatable location data. The syntax provider's | ||
| // semantic transform reruns when the compilation changes, and SegmentCaches is keyed | ||
| // by that compilation, so insertion/reordering refreshes ordinals before this output. | ||
| var tree = pair.Right.SyntaxTrees.ElementAtOrDefault(property.TreeOrdinal); | ||
| var location = tree is null | ||
| ? Location.Create(property.FilePath, property.Span, property.LineSpan) | ||
| : Location.Create(tree, property.Span); | ||
| ctx.ReportDiagnostic(Diagnostic.Create(InaccessibleContainingType, location, property.Name)); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| }); | ||
|
|
||
| var testClasses = classChains | ||
| .Collect() | ||
| .Combine(enabledProvider) | ||
|
|
@@ -57,7 +97,11 @@ | |
| /// </summary> | ||
| /// <param name="TypeKey">Identity of the type, matching <see cref="SymbolEqualityComparer.Default"/>.</param> | ||
| /// <param name="Properties">The type's public static data-source properties, in member order.</param> | ||
| internal sealed record StaticPropertyTypeSegment(string TypeKey, EquatableArray<StaticPropertyEntry> Properties); | ||
| /// <param name="InaccessibleProperties">Source properties that cannot be referenced by generated initialization.</param> | ||
| internal sealed record StaticPropertyTypeSegment(string TypeKey, EquatableArray<StaticPropertyEntry> Properties, | ||
| EquatableArray<InaccessibleProperty> InaccessibleProperties); | ||
|
|
||
| internal sealed record InaccessibleProperty(string Name, string FilePath, TextSpan Span, LinePositionSpan LineSpan, int TreeOrdinal); | ||
|
|
||
| internal sealed record StaticPropertyEntry(string Name, PropertyWithDataSourceModel Model); | ||
|
|
||
|
|
@@ -94,7 +138,7 @@ | |
| // Indexed loop: EquatableArray<T>.GetEnumerator() returns a boxed IEnumerator<T>. | ||
| for (var i = 0; i < chain.Length; i++) | ||
| { | ||
| if (chain[i].Properties.Length > 0) | ||
| if (chain[i].Properties.Length > 0 || chain[i].InaccessibleProperties.Length > 0) | ||
| { | ||
| return true; | ||
| } | ||
|
|
@@ -128,7 +172,7 @@ | |
|
|
||
| if (!cache.TryGetValue(currentType, out var segment)) | ||
| { | ||
| segment = cache.GetOrAdd(currentType, static type => CreateSegment(type)); | ||
| segment = cache.GetOrAdd(currentType, type => CreateSegment(type, context.SemanticModel.Compilation)); | ||
| } | ||
|
|
||
| segments.Add(segment); | ||
|
|
@@ -137,10 +181,34 @@ | |
| return segments.ToEquatableArray(); | ||
| } | ||
|
|
||
| private static StaticPropertyTypeSegment CreateSegment(INamedTypeSymbol type) | ||
| private static bool IsAccessibleContainingType(INamedTypeSymbol type, Compilation compilation) | ||
| { | ||
| if (!compilation.IsSymbolAccessibleWithin(type, compilation.Assembly)) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| for (var current = type; current is not null; current = current.ContainingType) | ||
| { | ||
| if (current.IsFileLocal) | ||
| { | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| return true; | ||
| } | ||
|
|
||
| private static StaticPropertyTypeSegment CreateSegment(INamedTypeSymbol type, Compilation compilation) | ||
| { | ||
| List<StaticPropertyEntry>? properties = null; | ||
|
|
||
| List<InaccessibleProperty>? inaccessibleProperties = null; | ||
|
|
||
| // Generated initialization lives in an unrelated top-level type. Roslyn checks the | ||
| // entire containing-type chain; also exclude types local to a different source file. | ||
| var accessible = IsAccessibleContainingType(type, compilation); | ||
|
|
||
| foreach (var member in type.GetMembers()) | ||
| { | ||
| if (member is IPropertySymbol { DeclaredAccessibility: Accessibility.Public, SetMethod.DeclaredAccessibility: Accessibility.Public, IsStatic: true } property) // Only static properties for session initialization | ||
|
|
@@ -150,6 +218,20 @@ | |
|
|
||
| if (dataSourceAttr != null) | ||
| { | ||
| if (!accessible) | ||
| { | ||
| var location = property.Locations.FirstOrDefault(static location => location.IsInSource); | ||
| if (location is not null) | ||
| { | ||
| inaccessibleProperties ??= []; | ||
| inaccessibleProperties.Add(new InaccessibleProperty(property.Name, | ||
| location.GetLineSpan().Path, location.SourceSpan, location.GetLineSpan().Span, | ||
| compilation.SyntaxTrees.TakeWhile(tree => !ReferenceEquals(tree, location.SourceTree)).Count())); | ||
| } | ||
|
|
||
| continue; | ||
| } | ||
|
|
||
| properties ??= []; | ||
| properties.Add(new StaticPropertyEntry( | ||
| property.Name, | ||
|
|
@@ -164,7 +246,8 @@ | |
|
|
||
| return new StaticPropertyTypeSegment( | ||
| type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), | ||
| properties is null ? EquatableArray<StaticPropertyEntry>.Empty : properties.ToEquatableArray()); | ||
| properties is null ? EquatableArray<StaticPropertyEntry>.Empty : properties.ToEquatableArray(), | ||
| inaccessibleProperties is null ? EquatableArray<InaccessibleProperty>.Empty : inaccessibleProperties.ToEquatableArray()); | ||
| } | ||
|
|
||
| private static EquatableArray<PropertyWithDataSourceModel> ParseStaticPropertyInitializers(ImmutableArray<EquatableArray<StaticPropertyTypeSegment>> classChains, bool enabledProvider) | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Static data-source property 'Value' cannot be initialized because its containing type is inaccessible. Make the type and all containing types internal or public. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Static data-source property 'Value' cannot be initialized because its containing type is inaccessible. Make the type and all containing types internal or public. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Static data-source property 'Value' cannot be initialized because its containing type is inaccessible. Make the type and all containing types internal or public. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,228 @@ | ||
| using System.Collections.Immutable; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CSharp; | ||
| using TUnit.Core.SourceGenerator.CodeGenerators; | ||
|
|
||
| namespace TUnit.Core.SourceGenerator.Tests; | ||
|
|
||
| internal class StaticPropertyAccessibilityTests | ||
| { | ||
| [Test] | ||
| [Arguments("private", true, true)] | ||
| [Arguments("private", true, false)] | ||
| [Arguments("protected", true, true)] | ||
| [Arguments("private protected", true, true)] | ||
| [Arguments("internal", false, true)] | ||
| [Arguments("protected internal", false, true)] | ||
| [Arguments("public", false, true)] | ||
| public async Task Containing_type_accessibility(string accessibility, bool inaccessible, bool enabled) | ||
| { | ||
| var source = $$""" | ||
| public class Outer | ||
| { | ||
| {{accessibility}} class Helper | ||
| { | ||
| public class Nested | ||
| { | ||
| [TUnit.Core.Arguments("value")] | ||
| public static string Value { get; set; } | ||
| } | ||
| } | ||
| } | ||
| """; | ||
| await Check(source, inaccessible, enabled, accessibility); | ||
| } | ||
|
|
||
| [Test] | ||
| [Arguments(false, true)] | ||
| [Arguments(true, true)] | ||
| [Arguments(false, false)] | ||
| [Arguments(true, false)] | ||
| public async Task File_local_container(bool nested, bool enabled) | ||
| { | ||
| var property = "[TUnit.Core.Arguments(\"value\")] public static string Value { get; set; }"; | ||
| var source = "file class Helper { " + (nested ? "public class Nested { " + property + " }" : property) + " }"; | ||
| await Check(source, true, enabled); | ||
| } | ||
|
|
||
| [Test] | ||
| [Arguments("class Helper<T>")] | ||
| [Arguments("struct Helper")] | ||
| [Arguments("record Helper")] | ||
| [Arguments("record struct Helper")] | ||
| public async Task Skipped_helper_has_no_diagnostic(string declaration) | ||
| { | ||
| var source = $$""" | ||
| public class Outer | ||
| { | ||
| private {{declaration}} | ||
| { | ||
| [TUnit.Core.Arguments("value")] | ||
| public static string Value { get; set; } | ||
| } | ||
| } | ||
| """; | ||
| await Check(source, true, true, expectDiagnostic: false); | ||
| } | ||
|
|
||
| [Test] | ||
| public async Task Internal_leaf_in_private_container_reports_once_when_inherited() | ||
| { | ||
| const string source = """ | ||
| public class Outer | ||
| { | ||
| private class Helper | ||
| { | ||
| internal class Nested | ||
| { | ||
| [TUnit.Core.Arguments("value")] | ||
| public static string Value { get; set; } | ||
| } | ||
| private class Derived : Nested { } | ||
| } | ||
| } | ||
| """; | ||
| await Check(source, true, true); | ||
| } | ||
|
|
||
| [Test] | ||
| public async Task File_level_options_suppress_diagnostic() | ||
| { | ||
| const string source = """ | ||
| public class Outer | ||
| { | ||
| private class Helper | ||
| { | ||
| [TUnit.Core.Arguments("value")] | ||
| public static string Value { get; set; } | ||
| } | ||
| } | ||
| """; | ||
| await Check(source, true, true, expectDiagnostic: false, suppressDiagnostic: true); | ||
| } | ||
|
|
||
| [Test] | ||
| [Arguments("")] | ||
| [Arguments("shared.cs")] | ||
| public async Task Duplicate_paths_preserve_tree_identity_and_file_options(string path) | ||
| { | ||
| const string source = """ | ||
| public class Outer | ||
| { | ||
| private class Helper | ||
| { | ||
| [TUnit.Core.Arguments("value")] | ||
| public static string Value { get; set; } | ||
| } | ||
| } | ||
| """; | ||
| var parseOptions = new CSharpParseOptions(LanguageVersion.Preview); | ||
| var first = CSharpSyntaxTree.ParseText(source, parseOptions, path); | ||
| var second = CSharpSyntaxTree.ParseText(source.Replace("Outer", "Other"), parseOptions, path); | ||
| var compilation = CSharpCompilation.Create("DuplicatePaths", [first, second], ReferencesHelper.References, | ||
| new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) | ||
| .WithSyntaxTreeOptionsProvider(new SuppressDiagnosticOptionsProvider(first))); | ||
| GeneratorDriver driver = CSharpGeneratorDriver.Create( | ||
| [new StaticPropertyInitializationGenerator().AsSourceGenerator()], parseOptions: parseOptions); | ||
| driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var output, out var diagnostics); | ||
|
|
||
| await Assert.That(output.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).ToArray()).IsEmpty(); | ||
| await Assert.That(driver.GetRunResult().Results[0].Exception).IsNull(); | ||
| await Assert.That(diagnostics.Length).IsEqualTo(1); | ||
| await Assert.That(diagnostics[0].Id).IsEqualTo("TUNITGEN005"); | ||
| await Assert.That(diagnostics[0].Location.SourceTree).IsEqualTo(second); | ||
| await Assert.That(second.GetText().ToString(diagnostics[0].Location.SourceSpan)).IsEqualTo("Value"); | ||
| } | ||
|
|
||
| [Test] | ||
| [Arguments(false)] | ||
| [Arguments(true)] | ||
| public async Task Tree_order_changes_refresh_diagnostic_identity(bool reorder) | ||
| { | ||
| const string source = """ | ||
| public class Outer | ||
| { | ||
| private class Helper | ||
| { | ||
| [TUnit.Core.Arguments("value")] | ||
| public static string Value { get; set; } | ||
| } | ||
| } | ||
| """; | ||
| var parseOptions = new CSharpParseOptions(LanguageVersion.Preview); | ||
| var offending = CSharpSyntaxTree.ParseText(source, parseOptions, "shared.cs"); | ||
| var unrelated = CSharpSyntaxTree.ParseText("public class Unrelated { }", parseOptions, "shared.cs"); | ||
| var compilation = CSharpCompilation.Create("TreeOrder", [offending, unrelated], ReferencesHelper.References, | ||
| new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) | ||
| .WithSyntaxTreeOptionsProvider(new SuppressDiagnosticOptionsProvider(unrelated))); | ||
| GeneratorDriver driver = CSharpGeneratorDriver.Create( | ||
| [new StaticPropertyInitializationGenerator().AsSourceGenerator()], parseOptions: parseOptions); | ||
| driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out var initialDiagnostics); | ||
| await Assert.That(initialDiagnostics.Length).IsEqualTo(1); | ||
| await Assert.That(initialDiagnostics[0].Location.SourceTree).IsEqualTo(offending); | ||
|
|
||
| // Keep the offending tree unchanged and reuse the driver so incremental caches participate. | ||
| var inserted = CSharpSyntaxTree.ParseText("public class Inserted { }", parseOptions, "shared.cs"); | ||
| compilation = compilation.RemoveAllSyntaxTrees().AddSyntaxTrees(reorder | ||
| ? [unrelated, offending] | ||
| : [inserted, offending, unrelated]); | ||
| driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var output, out var diagnostics); | ||
|
|
||
| await Assert.That(driver.GetRunResult().Results[0].Exception).IsNull(); | ||
| await Assert.That(output.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).ToArray()).IsEmpty(); | ||
| await Assert.That(diagnostics.Length).IsEqualTo(1); | ||
| await Assert.That(diagnostics[0].Id).IsEqualTo("TUNITGEN005"); | ||
| await Assert.That(diagnostics[0].Location.SourceTree).IsEqualTo(offending); | ||
| await Assert.That(offending.GetText().ToString(diagnostics[0].Location.SourceSpan)).IsEqualTo("Value"); | ||
| } | ||
|
|
||
| private static async Task Check(string source, bool inaccessible, bool enabled, | ||
| string? snapshotParameter = null, bool expectDiagnostic = true, bool suppressDiagnostic = false) | ||
| { | ||
| var parseOptions = new CSharpParseOptions(LanguageVersion.Preview); | ||
| var compilation = CSharpCompilation.Create("StaticPropertyAccessibility", | ||
| [CSharpSyntaxTree.ParseText(source, parseOptions)], ReferencesHelper.References, | ||
| new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) | ||
| .WithSyntaxTreeOptionsProvider(suppressDiagnostic ? new SuppressDiagnosticOptionsProvider() : null)); | ||
| GeneratorDriver driver = CSharpGeneratorDriver.Create( | ||
| [new StaticPropertyInitializationGenerator().AsSourceGenerator()], parseOptions: parseOptions); | ||
| driver = driver.WithUpdatedAnalyzerConfigOptions(new TestAnalyzerConfigOptionsProvider( | ||
| ImmutableDictionary<string, string>.Empty.Add("build_property.EnableTUnitSourceGeneration", enabled.ToString()))); | ||
| driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var output, out var diagnostics); | ||
|
|
||
| await Assert.That(output.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).ToArray()) | ||
| .IsEmpty(); | ||
| await Assert.That(driver.GetRunResult().Results[0].Exception).IsNull(); | ||
| await Assert.That(driver.GetRunResult().Results[0].GeneratedSources.Length).IsEqualTo(!enabled || inaccessible ? 0 : 1); | ||
| await Assert.That(diagnostics.Length).IsEqualTo(enabled && inaccessible && expectDiagnostic ? 1 : 0); | ||
| if (enabled && inaccessible && expectDiagnostic) | ||
| { | ||
| await Assert.That(diagnostics[0].Id).IsEqualTo("TUNITGEN005"); | ||
| await Assert.That(diagnostics[0].Location.SourceTree).IsEqualTo(compilation.SyntaxTrees.Single()); | ||
| await Assert.That(source.Substring(diagnostics[0].Location.SourceSpan.Start, diagnostics[0].Location.SourceSpan.Length)) | ||
| .IsEqualTo("Value"); | ||
| if (snapshotParameter is not null) | ||
| { | ||
| await Verify(diagnostics[0].GetMessage()).UseParameters(snapshotParameter); | ||
| } | ||
| } | ||
| } | ||
| private sealed class SuppressDiagnosticOptionsProvider(SyntaxTree? suppressedTree = null) : SyntaxTreeOptionsProvider | ||
| { | ||
| public override GeneratedKind IsGenerated(SyntaxTree tree, CancellationToken cancellationToken) => GeneratedKind.Unknown; | ||
|
|
||
| public override bool TryGetDiagnosticValue(SyntaxTree tree, string diagnosticId, | ||
| CancellationToken cancellationToken, out ReportDiagnostic severity) | ||
| { | ||
| severity = ReportDiagnostic.Suppress; | ||
| return diagnosticId == "TUNITGEN005" && (suppressedTree is null || ReferenceEquals(tree, suppressedTree)); | ||
| } | ||
|
|
||
| public override bool TryGetGlobalDiagnosticValue(string diagnosticId, | ||
| CancellationToken cancellationToken, out ReportDiagnostic severity) | ||
| { | ||
| severity = ReportDiagnostic.Default; | ||
| return false; | ||
| } | ||
| } | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.