Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions lode/dotnet/analyzer-candidates/index.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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
Expand Down
14 changes: 13 additions & 1 deletion lode/dotnet/analyzers/code-fix-patterns.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions lode/dotnet/analyzers/shared-helpers.md
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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<T>` and `ValueTask<T>`. `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. |
Expand Down
10 changes: 9 additions & 1 deletion lode/dotnet/analyzers/symbol-lookups.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
Expand All @@ -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<string> FixableDiagnosticIds =>
Expand All @@ -37,42 +38,98 @@ protected override Task RegisterFixesAsync(CodeFixContext context, SyntaxNode ro
return Task.CompletedTask;
}

private static Task<Document> ApplyFixAsync(
private static async Task<Document> 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<LocalDeclarationStatementSyntax>() is { } local =>
FixLocalDeclaration(root, local),
FixLocalDeclaration(root, local, qualifiedTypeName),

_ when parent.FirstAncestorOrSelf<PropertyDeclarationSyntax>() is { } property =>
FixPropertyDeclaration(root, property),
FixPropertyDeclaration(root, property, qualifiedTypeName),

_ when parent.FirstAncestorOrSelf<ParameterSyntax>() is { } parameter =>
FixParameterDeclaration(root, parameter),
FixParameterDeclaration(root, parameter, qualifiedTypeName),

_ when parent.FirstAncestorOrSelf<FieldDeclarationSyntax>() 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<IMethodSymbol>().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
Expand All @@ -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)
{
Expand All @@ -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;
Expand All @@ -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(
Expand Down
6 changes: 3 additions & 3 deletions src/E128.Analyzers/Design/ByteSizeType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ namespace E128.Analyzers.Design;
internal static class ByteSizeType
{
/// <summary>
/// True when the type is <c lang="csharp">Pug.Core.Classes.ByteSize</c>.
/// True when the type is named <c lang="csharp">ByteSize</c>, whatever its namespace.
/// A namespace move must not break the exemption or the cast rule.
/// </summary>
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);
}
}
2 changes: 1 addition & 1 deletion src/E128.Analyzers/E128.Analyzers.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

<!-- NuGet Packaging -->
<PropertyGroup>
<Version>3.1.4</Version>
<Version>3.1.5</Version>
<IsPackable>true</IsPackable>
<IncludeBuildOutput>false</IncludeBuildOutput>
<DevelopmentDependency>true</DevelopmentDependency>
Expand Down
6 changes: 3 additions & 3 deletions src/E128.Analyzers/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ Roslyn analyzers and code fixes that enforce opinionated .NET conventions at com
## Installation

```xml
<PackageReference Include="E128.Analyzers" Version="3.1.4" PrivateAssets="all" />
<PackageReference Include="E128.Analyzers" Version="3.1.5" PrivateAssets="all" />
```

> `PrivateAssets="all"` keeps the analyzers out of your consumers' dependency graph.
Expand Down Expand Up @@ -2309,7 +2309,7 @@ No code fix.

### E128080 &mdash; 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)
Expand All @@ -2333,7 +2333,7 @@ var builder = StringBuilderPool.Shared.Rent();

### E128082 &mdash; 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)
Expand Down
34 changes: 34 additions & 0 deletions tests/E128.Analyzers.Tests/ByteSizeForDataSizeAnalyzerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ByteSizeForDataSizeAnalyzer>("""
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<ByteSizeForDataSizeAnalyzer>("""
namespace Pug.Classes
{
class C
{
public int {|E128080:MaxSizeBytes|} { get; set; }
}
}
""");
}
}
Loading