From 31e540fa6c24ede416080dca9bd9bfbab0c647a3 Mon Sep 17 00:00:00 2001 From: Brent Miller Date: Tue, 17 Nov 2026 11:35:27 -0600 Subject: [PATCH] fix(analyzers): match ByteSize by simple name and resolve it in the fix E128080 exempted only Pug.Core.Classes.ByteSize, so a namespace move made the rule fire on the type's own unit properties. E128082 shared the probe. Match ByteSize by simple name, whatever its namespace. The E128080 code fix hardcoded the retired namespace. Resolve the type in the compilation, add the resolved namespace as a using, and qualify FromBytes with the resolved name. Bump the package to 3.1.5. --- lode/dotnet/analyzer-candidates/index.md | 7 +- lode/dotnet/analyzers/code-fix-patterns.md | 14 +- lode/dotnet/analyzers/shared-helpers.md | 4 +- lode/dotnet/analyzers/symbol-lookups.md | 10 +- .../ByteSizeForDataSizeCodeFixProvider.cs | 123 +++++++++++++----- src/E128.Analyzers/Design/ByteSizeType.cs | 6 +- src/E128.Analyzers/E128.Analyzers.csproj | 2 +- src/E128.Analyzers/README.md | 6 +- .../ByteSizeForDataSizeAnalyzerTests.cs | 34 +++++ .../ByteSizeForDataSizeE128CodeFixTests.cs | 47 ++++++- .../ByteSizeUnwrapViaCastAnalyzerTests.cs | 27 ++++ 11 files changed, 231 insertions(+), 49 deletions(-) diff --git a/lode/dotnet/analyzer-candidates/index.md b/lode/dotnet/analyzer-candidates/index.md index 2fad7ef7..f77bf3db 100644 --- a/lode/dotnet/analyzer-candidates/index.md +++ b/lode/dotnet/analyzer-candidates/index.md @@ -1,5 +1,5 @@ # Analyzer Candidates: Open Register -*Updated: 2026-11-17T16:25:35Z* +*Updated: 2026-11-17T16:36:03Z* One register for every open analyzer candidate, whichever repository noticed it. A candidate enters at status `new`, carries a four-dimension score, and leaves @@ -27,9 +27,8 @@ The four dimensions are frequency (0-2), coverage gap (0-1), expressibility ## Open Candidates -| Pattern | Source | Score | Status | Notes | -| ------- | ------ | ----- | ------ | ----- | -| E128080 self-exemption hardcodes the retired `Pug.Classes.ByteSize` name | session friction | 4/5 | new | The rule fires on unit properties of the type after a namespace move. Repro: the type file after it moved from `Pug.Core.Classes`. Match the containing type by simple name. A namespace suffix also works. A temporary pragma sits in the consuming repo. +No open candidate. `ByteSizeType.Is` matches the type by simple name, so a +namespace move does not break the E128080 exemption. The body-read shape shipped as E128227. See [catalog.md](catalog.md). The JSON enumerator shape closed as skipped, because the enumerator releases no diff --git a/lode/dotnet/analyzers/code-fix-patterns.md b/lode/dotnet/analyzers/code-fix-patterns.md index 5a9087c5..9cf90a5d 100644 --- a/lode/dotnet/analyzers/code-fix-patterns.md +++ b/lode/dotnet/analyzers/code-fix-patterns.md @@ -1,5 +1,5 @@ # Code Fix Patterns -*Updated: 2026-11-11T13:22:57Z* +*Updated: 2026-11-17T16:37:46Z* Implementation patterns and gotchas for Roslyn code fix providers in E128.Analyzers. The emitted text rules live in [code-fix-output.md](code-fix-output.md). The @@ -46,6 +46,18 @@ Apply this rule this way. Gate the analyzer on the API, as [new-analyzer-checklist.md](new-analyzer-checklist.md) § Gate on API Availability requires. When no such API exists, report without a fix. +## Resolve a Project Type Before You Emit It + +Never hardcode the namespace of a type that a consumer project owns. Resolve +the type in the compilation and read its containing namespace. + +`ByteSizeForDataSizeCodeFixProvider` tries the canonical +`Pug.Core.Classes.ByteSize` name first. When that misses, it walks +`Compilation.GlobalNamespace` for a type named `ByteSize` with a static +`FromBytes`. The fix adds the resolved namespace as a using and qualifies +`FromBytes` with the resolved name. A fixed namespace string breaks the fix +when the consumer moves the type. + ## Add a Using Directive Use `UsingDirectives.AddIfMissing(root, namespaceName)` from diff --git a/lode/dotnet/analyzers/shared-helpers.md b/lode/dotnet/analyzers/shared-helpers.md index 3c742209..f19b6600 100644 --- a/lode/dotnet/analyzers/shared-helpers.md +++ b/lode/dotnet/analyzers/shared-helpers.md @@ -1,6 +1,6 @@ # Shared Analyzer Helpers -*Updated: 2026-11-12T21:11:18Z* +*Updated: 2026-11-17T16:36:03Z* `src/E128.Analyzers` and `src/E128.Analyzers.CodeFixers` keep one class per shared concern. A new rule or fix calls an existing helper before it writes a @@ -23,7 +23,7 @@ assembly reaches the analyzer internals through `InternalsVisibleTo`. | `InterfaceMembers.Implements` | True when a method implements an interface member, including an explicit implementation. An interface or delegate method returns false. | | `InterfaceMembers.ImplementsMember` | True when the containing type maps some interface member to the method. | | `NameSuffixes.Matches` | True when a name ends with a suffix at an uppercase-letter position. | -| `ByteSizeType.Is` | True for `Pug.Core.Classes.ByteSize`. | +| `ByteSizeType.Is` | True for a type named `ByteSize`, whatever its namespace. A namespace move must not break the exemption or the cast rule. | | `ReturnTypes.Get` | Returns the return type of a method or the type of a property. | | `ReadOnlyCollectionExposure.Find` | Takes an operation and its containing symbol, not a diagnostic context. Returns the location of a mutable `List` or `Dictionary` field or property that a member exposes as a read-only interface. Unwraps `Task` and `ValueTask`. `MutableCollectionKind` selects the collection. | | `MutableCollectionCatalog` | One list of mutable collection types, their kind, the read-only interface name that replaces each, and the display template. The exposure rule and the read-only return rules both read it. | diff --git a/lode/dotnet/analyzers/symbol-lookups.md b/lode/dotnet/analyzers/symbol-lookups.md index 6c266079..49db3e2a 100644 --- a/lode/dotnet/analyzers/symbol-lookups.md +++ b/lode/dotnet/analyzers/symbol-lookups.md @@ -1,12 +1,20 @@ # Symbol and Semantic Lookups -*Updated: 2026-11-03T03:14:50Z* +*Updated: 2026-11-17T16:37:41Z* Recipes for the question the rule asks once the syntax shape passed. The binding rules live in [new-analyzer-checklist.md](new-analyzer-checklist.md) § Match Symbols, Not Names. The cost rules live in [performance.md](performance.md). +## A Project Type With No Fixed Namespace + +Match a project type by simple name when the type can move between namespaces. +A full metadata name pins the type to one namespace and breaks on a move. +`ByteSizeType.Is` is the example. The E128080 exemption and the E128082 cast +rule both accept a type named `ByteSize` in any namespace. The matching code fix +then resolves the type in the compilation, so the emitted call follows the move. + ## Reach a Member by Documentation Comment ID `GetTypeByMetadataName` reaches a type. A specific overload needs a diff --git a/src/E128.Analyzers.CodeFixers/Design/ByteSizeForDataSizeCodeFixProvider.cs b/src/E128.Analyzers.CodeFixers/Design/ByteSizeForDataSizeCodeFixProvider.cs index 02478912..6dc350cf 100644 --- a/src/E128.Analyzers.CodeFixers/Design/ByteSizeForDataSizeCodeFixProvider.cs +++ b/src/E128.Analyzers.CodeFixers/Design/ByteSizeForDataSizeCodeFixProvider.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Immutable; using System.Composition; using System.Linq; @@ -14,7 +15,7 @@ namespace E128.Analyzers.Design; [Shared] public sealed class ByteSizeForDataSizeCodeFixProvider : E128CodeFixProviderBase { - private const string PugClassesNamespace = "Pug.Core.Classes"; + private const string DefaultByteSizeNamespace = "Pug.Core.Classes"; private const string ByteSizeTypeName = "ByteSize"; public override ImmutableArray FixableDiagnosticIds => @@ -37,42 +38,98 @@ protected override Task RegisterFixesAsync(CodeFixContext context, SyntaxNode ro return Task.CompletedTask; } - private static Task ApplyFixAsync( + private static async Task ApplyFixAsync( Document document, SyntaxNode root, SyntaxToken token, CancellationToken cancellationToken) { - _ = cancellationToken; + // The type moved namespaces before. Resolve it in the compilation instead of + // hardcoding one namespace, so the fix still compiles after a move. + var compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); + var (qualifiedTypeName, namespaceName) = ResolveByteSizeTypeName(compilation); var parent = token.Parent ?? root; var newRoot = parent switch { _ when parent.FirstAncestorOrSelf() is { } local => - FixLocalDeclaration(root, local), + FixLocalDeclaration(root, local, qualifiedTypeName), _ when parent.FirstAncestorOrSelf() is { } property => - FixPropertyDeclaration(root, property), + FixPropertyDeclaration(root, property, qualifiedTypeName), _ when parent.FirstAncestorOrSelf() is { } parameter => - FixParameterDeclaration(root, parameter), + FixParameterDeclaration(root, parameter, qualifiedTypeName), _ when parent.FirstAncestorOrSelf() is { } field => - FixFieldDeclaration(root, field), + FixFieldDeclaration(root, field, qualifiedTypeName), _ => root }; - newRoot = UsingDirectives.AddIfMissing(newRoot, PugClassesNamespace); - return Task.FromResult(document.WithSyntaxRoot(newRoot)); + if (namespaceName is not null) + { + newRoot = UsingDirectives.AddIfMissing(newRoot, namespaceName); + } + + return document.WithSyntaxRoot(newRoot); + } + + private static (string QualifiedTypeName, string? NamespaceName) ResolveByteSizeTypeName( + Compilation? compilation) + { + var type = compilation is null ? null : ResolveByteSizeType(compilation); + + if (type is null) + { + return ($"{DefaultByteSizeNamespace}.{ByteSizeTypeName}", DefaultByteSizeNamespace); + } + + if (type.ContainingNamespace is { IsGlobalNamespace: false } containingNamespace) + { + return (type.ToDisplayString(), containingNamespace.ToDisplayString()); + } + + return (ByteSizeTypeName, null); } - private static SyntaxNode FixLocalDeclaration(SyntaxNode root, LocalDeclarationStatementSyntax local) + private static INamedTypeSymbol? ResolveByteSizeType(Compilation compilation) + { + return compilation.GetTypeByMetadataName($"{DefaultByteSizeNamespace}.{ByteSizeTypeName}") + ?? FindByteSizeType(compilation.GlobalNamespace); + } + + private static INamedTypeSymbol? FindByteSizeType(INamespaceSymbol namespaceSymbol) + { + foreach (var member in namespaceSymbol.GetMembers()) + { + if (member is INamespaceSymbol child) + { + if (FindByteSizeType(child) is { } nested) + { + return nested; + } + } + else if (member is INamedTypeSymbol type + && string.Equals(type.Name, ByteSizeTypeName, StringComparison.Ordinal) + && type.GetMembers("FromBytes").OfType().Any(static method => method.IsStatic)) + { + return type; + } + } + + return null; + } + + private static SyntaxNode FixLocalDeclaration( + SyntaxNode root, + LocalDeclarationStatementSyntax local, + string qualifiedTypeName) { var declaration = local.Declaration; var byteSizeType = CreateByteSizeTypeSyntax(); - var newDeclaration = WrapEveryInitializer(declaration) + var newDeclaration = WrapEveryInitializer(declaration, qualifiedTypeName) .WithType(byteSizeType.WithTrailingTrivia(SyntaxFactory.Space)); var newLocal = local @@ -82,21 +139,27 @@ private static SyntaxNode FixLocalDeclaration(SyntaxNode root, LocalDeclarationS return root.ReplaceNode(local, newLocal); } - private static SyntaxNode FixPropertyDeclaration(SyntaxNode root, PropertyDeclarationSyntax property) + private static SyntaxNode FixPropertyDeclaration( + SyntaxNode root, + PropertyDeclarationSyntax property, + string qualifiedTypeName) { var byteSizeType = CreateByteSizeTypeSyntax(); var newProperty = property.WithType(byteSizeType.WithTrailingTrivia(SyntaxFactory.Space)); if (property.Initializer is { } initializer) { - var wrapped = WrapInFromBytes(initializer.Value); + var wrapped = WrapInFromBytes(initializer.Value, qualifiedTypeName); newProperty = newProperty.WithInitializer(initializer.WithValue(wrapped)); } return root.ReplaceNode(property, newProperty); } - private static SyntaxNode FixParameterDeclaration(SyntaxNode root, ParameterSyntax parameter) + private static SyntaxNode FixParameterDeclaration( + SyntaxNode root, + ParameterSyntax parameter, + string qualifiedTypeName) { if (parameter.Type is null) { @@ -108,18 +171,21 @@ private static SyntaxNode FixParameterDeclaration(SyntaxNode root, ParameterSynt if (parameter.Default is { } defaultValue) { - var wrapped = WrapInFromBytes(defaultValue.Value); + var wrapped = WrapInFromBytes(defaultValue.Value, qualifiedTypeName); newParameter = newParameter.WithDefault(defaultValue.WithValue(wrapped)); } return root.ReplaceNode(parameter, newParameter); } - private static SyntaxNode FixFieldDeclaration(SyntaxNode root, FieldDeclarationSyntax field) + private static SyntaxNode FixFieldDeclaration( + SyntaxNode root, + FieldDeclarationSyntax field, + string qualifiedTypeName) { var declaration = field.Declaration; var byteSizeType = CreateByteSizeTypeSyntax(); - var newDeclaration = WrapEveryInitializer(declaration) + var newDeclaration = WrapEveryInitializer(declaration, qualifiedTypeName) .WithType(byteSizeType.WithTrailingTrivia(SyntaxFactory.Space)); var newModifiers = field.Modifiers; @@ -139,30 +205,25 @@ private static SyntaxNode FixFieldDeclaration(SyntaxNode root, FieldDeclarationS // Every declarator shares the new type, so every initializer must carry the conversion. A field // or local with more than one declarator would otherwise assign an int to ByteSize. - private static VariableDeclarationSyntax WrapEveryInitializer(VariableDeclarationSyntax declaration) + private static VariableDeclarationSyntax WrapEveryInitializer( + VariableDeclarationSyntax declaration, + string qualifiedTypeName) { - var variables = declaration.Variables.Select(static variable => + var variables = declaration.Variables.Select(variable => variable.Initializer is { } initializer - ? variable.WithInitializer(initializer.WithValue(WrapInFromBytes(initializer.Value))) + ? variable.WithInitializer(initializer.WithValue(WrapInFromBytes(initializer.Value, qualifiedTypeName))) : variable); return declaration.WithVariables(SyntaxFactory.SeparatedList(variables)); } - private static InvocationExpressionSyntax WrapInFromBytes(ExpressionSyntax expression) + private static InvocationExpressionSyntax WrapInFromBytes( + ExpressionSyntax expression, + string qualifiedTypeName) { var qualifiedName = SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, - SyntaxFactory.MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - SyntaxFactory.MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - SyntaxFactory.MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - SyntaxFactory.IdentifierName("Pug"), - SyntaxFactory.IdentifierName("Core")), - SyntaxFactory.IdentifierName("Classes")), - SyntaxFactory.IdentifierName(ByteSizeTypeName)), + SyntaxFactory.ParseExpression(qualifiedTypeName), SyntaxFactory.IdentifierName("FromBytes")); return SyntaxFactory.InvocationExpression( diff --git a/src/E128.Analyzers/Design/ByteSizeType.cs b/src/E128.Analyzers/Design/ByteSizeType.cs index 0964e195..86a215f7 100644 --- a/src/E128.Analyzers/Design/ByteSizeType.cs +++ b/src/E128.Analyzers/Design/ByteSizeType.cs @@ -9,12 +9,12 @@ namespace E128.Analyzers.Design; internal static class ByteSizeType { /// - /// True when the type is Pug.Core.Classes.ByteSize. + /// True when the type is named ByteSize, whatever its namespace. + /// A namespace move must not break the exemption or the cast rule. /// internal static bool Is(ITypeSymbol? type) { return type is not null - && string.Equals(type.Name, "ByteSize", StringComparison.Ordinal) - && string.Equals(type.ContainingNamespace?.ToString(), "Pug.Core.Classes", StringComparison.Ordinal); + && string.Equals(type.Name, "ByteSize", StringComparison.Ordinal); } } diff --git a/src/E128.Analyzers/E128.Analyzers.csproj b/src/E128.Analyzers/E128.Analyzers.csproj index 9423e0de..bb052b9d 100644 --- a/src/E128.Analyzers/E128.Analyzers.csproj +++ b/src/E128.Analyzers/E128.Analyzers.csproj @@ -23,7 +23,7 @@ - 3.1.4 + 3.1.5 true false true diff --git a/src/E128.Analyzers/README.md b/src/E128.Analyzers/README.md index 93592e6a..64d4fc04 100644 --- a/src/E128.Analyzers/README.md +++ b/src/E128.Analyzers/README.md @@ -5,7 +5,7 @@ Roslyn analyzers and code fixes that enforce opinionated .NET conventions at com ## Installation ```xml - + ``` > `PrivateAssets="all"` keeps the analyzers out of your consumers' dependency graph. @@ -2309,7 +2309,7 @@ No code fix. ### E128080 — Use ByteSize for data-size values -Flags a numeric property, parameter, field, or local variable whose name ends with a data-size suffix. The suffix list covers `Bytes`, `Kb`, `Kilobytes`, `Mb`, `Megabytes`, `Gb`, `Gigabytes`, `Tb`, `Terabytes`, `FileSize`, `MaxSize`, `CacheSize`, `BufferSize`, and `ChunkSize`. A nullable numeric reports too. Members declared inside the `ByteSize` type are exempt. `ByteSize` comes from `Pug.Core.Classes`. The rule reports at error. +Flags a numeric property, parameter, field, or local variable whose name ends with a data-size suffix. The suffix list covers `Bytes`, `Kb`, `Kilobytes`, `Mb`, `Megabytes`, `Gb`, `Gigabytes`, `Tb`, `Terabytes`, `FileSize`, `MaxSize`, `CacheSize`, `BufferSize`, and `ChunkSize`. A nullable numeric reports too. Members declared inside a type named `ByteSize` are exempt. The rule matches that type by simple name, whatever its namespace. The rule reports at error. The code fix resolves the `ByteSize` type in the compilation, so a namespace move does not break the rewritten call. ```csharp // Before (error) @@ -2333,7 +2333,7 @@ var builder = StringBuilderPool.Shared.Rent(); ### E128082 — Do not unwrap ByteSize via cast -Flags a cast to a numeric type of a `Bytes`, `Bits`, `Kilobytes`, `Megabytes`, `Gigabytes`, or `Terabytes` property on a `ByteSize` value. The cast removes the unit from the type system. Compare `ByteSize` values directly, or format the value. +Flags a cast to a numeric type of a `Bytes`, `Bits`, `Kilobytes`, `Megabytes`, `Gigabytes`, or `Terabytes` property on a `ByteSize` value. The rule matches that type by simple name, whatever its namespace. The cast removes the unit from the type system. Compare `ByteSize` values directly, or format the value. ```csharp // Before (warns) diff --git a/tests/E128.Analyzers.Tests/ByteSizeForDataSizeAnalyzerTests.cs b/tests/E128.Analyzers.Tests/ByteSizeForDataSizeAnalyzerTests.cs index e4f9af82..c256db0c 100644 --- a/tests/E128.Analyzers.Tests/ByteSizeForDataSizeAnalyzerTests.cs +++ b/tests/E128.Analyzers.Tests/ByteSizeForDataSizeAnalyzerTests.cs @@ -120,4 +120,38 @@ partial class C } """); } + + [Fact] + [Trait("Category", "CI")] + public Task NoDiagnostic_ForUnitPropertiesInsideMovedByteSizeType() + { + // The exemption matches the type by simple name. A namespace move must + // not make the rule fire on the unit properties of ByteSize itself. + return AnalyzerTestRunner.VerifyAsync(""" + namespace Pug.Classes + { + public readonly struct ByteSize + { + public long Bytes { get; } + public double Kilobytes { get; } + public long BufferSize { get; } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForOtherTypeInAMovedByteSizeNamespace() + { + return AnalyzerTestRunner.VerifyAsync(""" + namespace Pug.Classes + { + class C + { + public int {|E128080:MaxSizeBytes|} { get; set; } + } + } + """); + } } diff --git a/tests/E128.Analyzers.Tests/ByteSizeForDataSizeE128CodeFixTests.cs b/tests/E128.Analyzers.Tests/ByteSizeForDataSizeE128CodeFixTests.cs index 7add5ff3..bf3b117f 100644 --- a/tests/E128.Analyzers.Tests/ByteSizeForDataSizeE128CodeFixTests.cs +++ b/tests/E128.Analyzers.Tests/ByteSizeForDataSizeE128CodeFixTests.cs @@ -20,16 +20,17 @@ public readonly struct ByteSize } """; - private static Task VerifyFixAsync(string source, string fixedCode) + private static Task VerifyFixAsync(string source, string fixedCode, string? byteSizeStub = null) { + var stub = byteSizeStub ?? ByteSizeStub; var test = new CSharpCodeFixTest { TestCode = source, FixedCode = fixedCode, ReferenceAssemblies = ReferenceAssemblies.Net.Net100 }; - test.TestState.Sources.Add(ByteSizeStub); - test.FixedState.Sources.Add(ByteSizeStub); + test.TestState.Sources.Add(stub); + test.FixedState.Sources.Add(stub); return test.RunAsync(TestContext.Current.CancellationToken); } @@ -82,6 +83,46 @@ void M() """); } + [Fact] + [Trait("Category", "CI")] + public Task MovedByteSizeNamespace_ResolvesTheReferencedType() + { + // The type moved from Pug.Core.Classes. The fix must use the type that + // the compilation resolves, not the retired namespace. + const string MovedStub = """ + namespace Pug.Classes + { + public readonly struct ByteSize + { + public static ByteSize FromBytes(long bytes) => default; + } + } + """; + + return VerifyFixAsync( + """ + class C + { + void M() + { + long {|E128080:maxBufferSize|} = 1; + } + } + """, + """ + using Pug.Classes; + + class C + { + void M() + { + ByteSize maxBufferSize = Pug.Classes.ByteSize.FromBytes(1); + } + } + """, + MovedStub); + } + [Fact] [Trait("Category", "CI")] public Task ParameterWithDefaultValue_OffersNoFix() diff --git a/tests/E128.Analyzers.Tests/ByteSizeUnwrapViaCastAnalyzerTests.cs b/tests/E128.Analyzers.Tests/ByteSizeUnwrapViaCastAnalyzerTests.cs index 3298282f..c1c94792 100644 --- a/tests/E128.Analyzers.Tests/ByteSizeUnwrapViaCastAnalyzerTests.cs +++ b/tests/E128.Analyzers.Tests/ByteSizeUnwrapViaCastAnalyzerTests.cs @@ -67,6 +67,33 @@ void M(ByteSize size) """); } + private const string MovedByteSizeStub = """ + namespace Pug.Classes + { + public struct ByteSize + { + public double Bytes { get; set; } + } + } + """; + + [Fact] + [Trait("Category", "CI")] + public Task Fires_OnCastOfMovedByteSizeType() + { + // The type probe matches by simple name, so a namespace move does not + // stop the rule. + return AnalyzerTestRunner.VerifyAsync(MovedByteSizeStub + """ + class C + { + void M(Pug.Classes.ByteSize size) + { + var x = {|E128082:(long)size.Bytes|}; + } + } + """); + } + [Fact] [Trait("Category", "CI")] public Task NoDiagnostic_ForPlainBytesAccess()