diff --git a/lode/dotnet-reference/dep-map.md b/lode/dotnet-reference/dep-map.md index e3dec72c..7e0ab8c0 100644 --- a/lode/dotnet-reference/dep-map.md +++ b/lode/dotnet-reference/dep-map.md @@ -1,5 +1,5 @@ # dotnet-reference Dependency Map -*Updated: 2026-11-10T23:33:05Z* +*Updated: 2026-11-17T13:33:06Z* > Scope: `dotnet-reference` | Scan root: repo root > Single-repo scan: all sub-projects share one `Directory.Build.props` and `Directory.Packages.props`. @@ -11,8 +11,8 @@ | `E128.Reference.Core` | `Microsoft.NET.Sdk` | `net11.0` | Shared library for Web + Cli | None | | `E128.Reference.Web` | `Microsoft.NET.Sdk.Web` | `net11.0` | ASP.NET Core web service | None (project ref only) | | `E128.Reference.Cli` | `Microsoft.NET.Sdk` | `net11.0` | Console executable | `System.CommandLine` | -| `E128.Analyzers` | `Microsoft.NET.Sdk` | `netstandard2.0` | Roslyn analyzer NuGet package | `Microsoft.CodeAnalysis.CSharp`, `Microsoft.CodeAnalysis.PublicApiAnalyzers` | -| `E128.Analyzers.CodeFixers` | `Microsoft.NET.Sdk` | `netstandard2.0` | Code fix DLL packed into `E128.Analyzers` | `Microsoft.CodeAnalysis.CSharp.Workspaces` + project ref to `E128.Analyzers` | +| `E128.Analyzers` | `Microsoft.NET.Sdk` | `netstandard2.0` | Roslyn analyzer NuGet package | `Microsoft.CodeAnalysis.CSharp`, `Microsoft.CodeAnalysis.PublicApiAnalyzers`, `PolySharp` | +| `E128.Analyzers.CodeFixers` | `Microsoft.NET.Sdk` | `netstandard2.0` | Code fix DLL packed into `E128.Analyzers` | `Microsoft.CodeAnalysis.CSharp.Workspaces`, `PolySharp`, and a project ref to `E128.Analyzers` | All production projects also receive the following **analyzer packages** via `Directory.Build.props` (`PrivateAssets="all"`, compile-time only, not shipped to consumers). Versions are pinned @@ -65,8 +65,8 @@ images and gains a CPU floor. On Linux, .NET 11 compiles ReadyToRun against the | SDK/build image | `mcr.microsoft.com/dotnet/sdk:11.0-resolute` | `Dockerfile` (`restore`/`build` stages) | | .NET SDK pin | see `global.json` | `global.json` | | SDK rollForward | `latestPatch` | `global.json` (pins the SDK to the `11.0.1xx` line) | -| Target framework | `net11.0` (all except `E128.Analyzers`) | `Directory.Build.props` | -| Analyzers TF | `netstandard2.0` | `E128.Analyzers.csproj` | +| Target framework | `net11.0` (all except the two analyzer projects) | `Directory.Build.props` | +| Analyzers TF | `netstandard2.0` | `E128.Analyzers.csproj` and `E128.Analyzers.CodeFixers.csproj` | | CI SDK version | `11.0.x` | `.github/workflows/ci.yml` `setup-dotnet` | | CI platform | `ubuntu-26.04` | `.github/workflows/ci.yml` | | Secret scanner | gitleaks, version and SHA-256 pinned in job `env` | `.github/workflows/ci.yml` (`lint` job) | @@ -151,7 +151,7 @@ reference stays `Microsoft.CodeAnalysis.CSharp.Workspaces`. - Packaged via `dotnet pack`, pushed via `dotnet nuget push` - OIDC-based API key exchange (no stored secrets) -- Triggered by pushes to `src/E128.Analyzers/**` on `main` +- Triggered by pushes to `src/E128.Analyzers/**` or `src/E128.Analyzers.CodeFixers/**` on `main` - Version check gates the push (skips if version already on nuget.org) --- diff --git a/lode/dotnet/analyzers.md b/lode/dotnet/analyzers.md index 47acb421..2a2f423d 100644 --- a/lode/dotnet/analyzers.md +++ b/lode/dotnet/analyzers.md @@ -1,9 +1,9 @@ -# .NET 10 Roslyn Analyzers -*Updated: 2026-11-17T00:00:52Z* +# .NET 11 Roslyn Analyzers +*Updated: 2026-11-17T13:33:06Z* ## Strategy: Deny by Default -All analyzer diagnostics default to `error` via `.globalconfig` (`dotnet_analyzer_diagnostic.severity = error`). A rule stays below `error` only when enabling it makes the build impossible to pass. See § Rules Not Enabled. +All analyzer diagnostics default to `error` via `.globalconfig` (`dotnet_analyzer_diagnostic.severity = error`). A rule stays below `error` only for a recorded reason. See § Rules Not Enabled. A bulk key reaches only a rule that is enabled by default. `.globalconfig` therefore names every default-off rule of every installed package with its own `error` line. The CA rules need no line because `AnalysisMode = All` enables them. @@ -24,7 +24,7 @@ Per [Microsoft guidance](https://learn.microsoft.com/en-us/dotnet/fundamentals/c **`.globalconfig` is purely for analyzer configuration.** It handles rule severity (`dotnet_diagnostic.*`) and enabling (`roslynator_analyzers.enabled_by_default`). It does NOT support editor style settings like indentation, whitespace, or formatting preferences. Put those in `.editorconfig`. -**Inline severity vs `dotnet_diagnostic.*`.** Style rules in `.editorconfig` carry the `:error` suffix on the option value (e.g., `csharp_style_var_for_built_in_types = true:error`). An option suffix of `:silent` or `:suggestion` beats the bulk key, so the repo uses neither. The only `:silent` options left are `csharp_style_prefer_primary_constructors` and `csharp_style_prefer_top_level_statements`, because IDE0290 and IDE0210 are off. The `.globalconfig` lists explicit `dotnet_diagnostic.IDE*` entries only for guardrails and for rules that stay off. That avoids silent drift when rule IDs change. The seven `*_experimental` blank-line options (IDE2000 to IDE2006) are set to `false:error`, because `true` allows the construct and silences the rule. The `tests/.globalconfig` and `benchmarks/.globalconfig` use `global_level = 101` to override the root `global_level = 100`. +**Inline severity vs `dotnet_diagnostic.*`.** Style rules in `.editorconfig` carry the `:error` suffix on the option value (e.g., `csharp_style_var_for_built_in_types = true:error`). An option suffix of `:silent` or `:suggestion` beats the bulk key. The `.editorconfig` uses `:silent` on the expression-bodied member options, on `csharp_style_prefer_primary_constructors`, and on `csharp_style_prefer_top_level_statements`. It uses `:suggestion` on `csharp_style_prefer_range_operator`. IDE0290 and IDE0210 are off. The `.globalconfig` lists explicit `dotnet_diagnostic.IDE*` entries only for guardrails and for rules that stay off. That avoids silent drift when rule IDs change. The seven `*_experimental` blank-line options (IDE2000 to IDE2006) are set to `true`, which allows the construct and silences the rule. The `tests/.globalconfig` and `benchmarks/.globalconfig` use `global_level = 101` to override the root `global_level = 100`. ## MSBuild Properties @@ -52,6 +52,7 @@ Declared in `Directory.Build.props` with `PrivateAssets="all"` (zero runtime imp | AsyncFixer | AF* | Async/await anti-patterns | | IDisposableAnalyzers | IDISP* | Resource ownership and disposal | | Meziantou.Analyzer | MA* | Code quality, performance, security | +| Microsoft.CodeAnalysis.CSharp.CodeStyle | IDE* | Code style rules in the build | | Microsoft.VisualStudio.Threading.Analyzers | VSTHRD* | Threading correctness | | Roslynator.Analyzers | RCS* | Code style + quality | | Roslynator.CodeAnalysis.Analyzers | RCS* | Advanced code analysis | @@ -76,7 +77,7 @@ explicit exception. ## Key Meziantou Rules Enabled as Error -The root `.globalconfig` sets every Meziantou rule to `error`, including the 56 rules that are off by default. The `.globalconfig` carries no setup-owned Meziantou block. Put an override for a test or benchmark project in a `global_level = 101` file. +The root `.globalconfig` sets every Meziantou rule to `error`, including each rule that is off by default. The `.globalconfig` carries no setup-owned Meziantou block. Put an override for a test or benchmark project in a `global_level = 101` file. The table below is aligned with Meziantou's [comparison table](https://github.com/meziantou/Meziantou.Analyzer/blob/main/docs/comparison-with-other-analyzers.md): @@ -90,7 +91,7 @@ The table below is aligned with Meziantou's [comparison table](https://github.co ## Netstandard2.0 Nullable Polyfill (E128.Analyzers) -The analyzer project targets `netstandard2.0` (required for Roslyn analyzers) which lacks `System.Diagnostics.CodeAnalysis.NotNullWhenAttribute`. Rather than hand-rolling a polyfill (which trips MA0048 file-name rules and IDE0130 namespace-mismatch), the project references **PolySharp** as a source generator: +The analyzer project targets `netstandard2.0` (required for Roslyn analyzers) which lacks `System.Diagnostics.CodeAnalysis.NotNullWhenAttribute` and `MaybeNullWhenAttribute`. Rather than hand-rolling a polyfill (which trips MA0048 file-name rules and IDE0130 namespace-mismatch), the project references **PolySharp** as a source generator. `E128.Analyzers.CodeFixers` does the same: ```xml @@ -101,15 +102,15 @@ The analyzer project targets `netstandard2.0` (required for Roslyn analyzers) wh ``` -`PrivateAssets="all"` keeps the generator out of the NuGet package. `PolySharpIncludeGeneratedTypes` scopes generation to only the attribute the project actually uses, avoiding duplicate-type conflicts with consumer projects that target modern TFMs. +`PrivateAssets="all"` keeps the generator out of the NuGet package. `PolySharpIncludeGeneratedTypes` scopes generation to only the attributes the project actually uses, avoiding duplicate-type conflicts with consumer projects that target modern TFMs. ## Public API Tracking (E128.Analyzers) -`Microsoft.CodeAnalysis.PublicApiAnalyzers` enforces API compatibility via `PublicAPI.Shipped.txt` / `PublicAPI.Unshipped.txt`. RS0016 and RS0017 are `none` in the root `.globalconfig`, so no `PublicAPI` entries are required. The project carries no `NoWarn` for either. The `NoWarn` list holds only RS2007 and NU5128. The project's `.editorconfig` sets `RCS9004` to `none` (`SeparatedSyntaxList.Count` is O(1), and the rule conflicts with RCS1080). +`Microsoft.CodeAnalysis.PublicApiAnalyzers` enforces API compatibility via `PublicAPI.Shipped.txt` / `PublicAPI.Unshipped.txt`. RS0016 and RS0017 are `none` in the root `.globalconfig`, so no `PublicAPI` entries are required. The project carries no `NoWarn` for either. The `NoWarn` list holds RS2007, NU5128, and RSEXPERIMENTAL006. The project's `.editorconfig` sets `RCS9004` to `none` (`SeparatedSyntaxList.Count` is O(1), and the rule conflicts with RCS1080). ## Custom Analyzers: E128.Analyzers -`src/E128.Analyzers/` is a solution-local Roslyn analyzer project. It is wired via `Directory.Build.targets` as a `ProjectReference` with `OutputItemType="Analyzer"`. It applies to all projects except the analyzer itself (excluded via `IsRoslynComponent` condition). Severity is governed by `.globalconfig` (blanket error by default). +`src/E128.Analyzers/` is a solution-local Roslyn analyzer project. It is wired via `Directory.Build.targets` as a `ProjectReference` with `OutputItemType="Analyzer"`. It applies to all projects except the two analyzer projects (excluded via `IsRoslynComponent` condition). Severity is governed by `.globalconfig` (blanket error by default). Rules span categories: Design, Reliability, Performance, Unsafe, Maintainability, Security, Style, Testing, and FileSystem. Most rules ship with a code fix. Several rules carry a diagnostic only, because the remediation is context-specific. Examples are `E128045` Direct Console usage, `E128046` Excessive inheritance, E128125 to E128129, and E128136 to E128138. Every rule from E128175 to E128217 is diagnostic only except E128205 and E128209, which ship a code fix. The rules E128154, E128156, and E128162 are diagnostic only. So are the FIPS rules E128142 to E128151. E128071 and E128075 ship a code fix. See `src/E128.Analyzers/README.md` for the complete rule table, code-fix status, and usage examples. @@ -147,9 +148,10 @@ Rules relaxed in test projects (via `tests/.globalconfig` at `global_level=101`) | S4018 | Test runner helpers take explicit type arguments | | E128043 | Guard-clause tests pass `null!` on purpose | | MA0191 | Same guard-clause tests | -| E128097 | Test-specific exception kept from the earlier configuration | +| E128097 | The test suite uses explanatory comments by convention | +| E128227 | Tests read a fixed response from an in-process app or a loopback container | -The same file sets `e128_minimum_framework_version = 100`. The test projects also keep `RS1036`, `RS1038`, `RS1041`, `RS2007`, `RS2008` and `S2699` in `NoWarn`, with a reason beside each in the csproj. +The same file sets `e128_minimum_framework_version = 100`. The `E128.Analyzers.Tests` project also keeps `RS1036`, `RS1038`, `RS1041`, `RS2007`, `RS2008` and `S2699` in `NoWarn`, with a reason beside each in the csproj. `tests/E128.Analyzers.Tests/.globalconfig` sets `none` for E128107 and E128108 at `global_level = 102`. ## ConfigureAwait Scoping (CA2007) @@ -168,7 +170,7 @@ Some Roslynator rules need a style option. A rule without its option reports ROS ## Rules Not Enabled -Every rule runs at `error` except the rules below. Each one conflicts with another enforced rule, needs a file or option the repo lacks, or has a destructive fix. `.globalconfig` carries a reason beside each line. +Every rule runs at `error` except the rules below. Each one conflicts with another enforced rule, needs a file or option the repo lacks, has a destructive fix, or is a maintainer decision. `.globalconfig` carries a reason beside each line. | Rule | State | Reason | | --------------------- | ------------ | ------------------------------------------------------------ | @@ -185,7 +187,7 @@ Every rule runs at `error` except the rules below. Each one conflicts with anoth | S1451 | `none` | Needs a `headerFormat` option the repo lacks | | RS0051 to RS0058 | off | Need `InternalAPI` files | | RS1020 | off | Needs `AnalyzerCategories.txt` | -| CS1591, RCS0044, RS0017, MA0007, RS1007, RCS0036, S3990, S3992, RCS0027, RCS1223, RS0016, RCS0055, MA0181, S3242, MA0003, RS1015, RCS0062, RS1028, RCS1141, RCS1181, RCS0012, S1067, S3267, RCS0053, RCS0061, S126, RCS0056, MA0045, RCS1146, S3358, S1227, S1200, S4055, S4017, S103, S1192, RCS0054, SS039, S1301, RCS0063, IDE0066, RCS0028, RCS0013, RCS0008, RCS1056, IDE0046, RCS1250, IDE0045, S3240, RCS1211, RCS1111, RCS1031, S4040, RCS1014, RCS1050, MA0136, RCS1238, MA0071 | `none` | Maintainer decision. No conflict behind them. | +| CS1591, RCS0044, RS0017, MA0007, RS1007, RCS0036, S3990, S3992, RCS0027, RCS1223, RS0016, RCS0055, MA0181, S3242, MA0003, RS1015, RCS0062, RS1028, RCS1141, RCS1181, RCS0012, S1067, S3267, RCS0053, RCS0061, S126, RCS0056, MA0045, RCS1146, S3358, S1227, S1200, S4055, S4017, S103, S1192, RCS0054, SS039, S1301, RCS0063, IDE0066, RCS0028, RCS0013, RCS0008, RCS1056, IDE0046, RCS1250, IDE0045, S3240, RCS1211, RCS1111, RCS1031, S4040, RCS1014, RCS1050, MA0136, RCS1238, MA0071 | `none` | Maintainer decision. Some also duplicate or oppose another rule, and RCS1056 throws AD0001. | | RCS9004 | `none` | Conflicts with RCS1080. Set in the two analyzer-project `.editorconfig` files only. | | E128107, E128108 | `suggestion` | The code fix deletes tests. `tests/E128.Analyzers.Tests/.globalconfig` sets `none`. | diff --git a/lode/dotnet/architecture-testing.md b/lode/dotnet/architecture-testing.md index f87733a6..b16c59b8 100644 --- a/lode/dotnet/architecture-testing.md +++ b/lode/dotnet/architecture-testing.md @@ -1,5 +1,5 @@ # Architecture Testing -*Updated: 2026-11-16T16:20:12Z* +*Updated: 2026-11-17T13:33:06Z* ## Overview @@ -63,7 +63,7 @@ Enforces dependency direction: Models depend on nothing, Services depend on Mode ### Sealed Classes (`SealedClassTests`) -- All non-abstract classes must be sealed (project convention for to favor immutability) +- All non-abstract classes must be sealed (project convention to favor immutability) ### Service Patterns (`ServicePatternTests`) diff --git a/lode/dotnet/benchmarks.md b/lode/dotnet/benchmarks.md index f3ba9fee..cf48b572 100644 --- a/lode/dotnet/benchmarks.md +++ b/lode/dotnet/benchmarks.md @@ -1,5 +1,5 @@ # Benchmarks -*Updated: 2026-11-16T21:48:36Z* +*Updated: 2026-11-17T13:33:06Z* ## Overview diff --git a/lode/dotnet/code-coverage.md b/lode/dotnet/code-coverage.md index 03097439..338d6491 100644 --- a/lode/dotnet/code-coverage.md +++ b/lode/dotnet/code-coverage.md @@ -1,5 +1,5 @@ # Code Coverage -*Updated: 2026-11-11T14:00:54Z* +*Updated: 2026-11-17T13:33:06Z* Coverage collects in process through the Microsoft.Testing.Platform extension. The CI gate requires 80 percent line coverage in total and in every measured @@ -26,6 +26,7 @@ so it needs no profiler attach step. ```bash dotnet test --solution E128.Reference.slnx \ + --configuration Debug \ --no-build \ --filter-trait "Category=CI" \ --coverage \ @@ -112,19 +113,19 @@ Classes that match no key land in the Unmapped bucket. ## Baseline -Measured 2026-11-07 over five module reports. Classes merge across reports, and -each line keeps its highest hit count. Total: 29276 of 34036 lines, 86.01 +Measured 2026-11-17 over five module reports. Classes merge across reports, and +each line keeps its highest hit count. Total: 36204 of 38213 lines, 94.74 percent. | Assembly | Lines | Line | |----------|-------|------| -| E128.Analyzers | 22021/25188 | 87.43% | -| E128.Analyzers.CodeFixers | 7166/8758 | 81.82% | -| E128.Reference.Cli | 22/23 | 95.65% | -| E128.Reference.Core | 43/43 | 100.0% | -| E128.Reference.Web | 24/24 | 100.0% | +| E128.Analyzers | 28748/29925 | 96.07% | +| E128.Analyzers.CodeFixers | 7344/8166 | 89.93% | +| E128.Reference.Cli | 22/24 | 91.67% | +| E128.Reference.Core | 57/57 | 100.0% | +| E128.Reference.Web | 33/41 | 80.49% | -The Code Fixers assembly sits closest to the floor. +The Reference Web assembly sits closest to the floor. ## Local Setup diff --git a/lode/dotnet/project-structure.md b/lode/dotnet/project-structure.md index 2a6bcb6e..34f8caff 100644 --- a/lode/dotnet/project-structure.md +++ b/lode/dotnet/project-structure.md @@ -1,5 +1,5 @@ # .NET 11 Project Structure -*Updated: 2026-11-10T22:47:34Z* +*Updated: 2026-11-17T13:33:06Z* ## Solution Format @@ -11,15 +11,15 @@ Migration: `dotnet sln migrate` converts `.sln` to `.slnx`. ``` ├── Directory.Build.props # Shared MSBuild PROPERTIES (TFM, analyzers, code analysis) -├── Directory.Build.targets # Conditional TARGETS (test project config, needs IsTestProject set first) +├── Directory.Build.targets # Conditional TARGETS (runtime async, test project config, analyzer reference) ├── Directory.Packages.props # Central Package Management version pins ├── global.json # SDK version + MTP test runner ├── nuget.config # Package sources, trusted signers, source mapping ├── .editorconfig # Code style (formatting, naming, IDE rules) ├── .globalconfig # Analyzer diagnostic severities ├── src/ -│ ├── E128.Analyzers/ # Solution-local Roslyn analyzer -│ ├── E128.Analyzers.CodeFixers/ # Code fix providers for the analyzer +│ ├── E128.Analyzers/ # Solution-local Roslyn analyzer (own .editorconfig) +│ ├── E128.Analyzers.CodeFixers/ # Code fix providers for the analyzer (own .editorconfig) │ ├── E128.Reference.Cli/ # CLI application │ ├── E128.Reference.Core/ # Core library │ └── E128.Reference.Web/ # Web application @@ -28,10 +28,11 @@ Migration: `dotnet sln migrate` converts `.sln` to `.slnx`. │ └── E128.Benchmarks/ # BenchmarkDotNet starter benchmarks (see [Benchmarks](benchmarks.md)) ├── tests/ │ ├── Architecture.Tests/ # ArchUnitNET structural tests -│ ├── E128.Analyzers.Tests/ # Roslyn analyzer unit tests +│ ├── E128.Analyzers.Tests/ # Roslyn analyzer unit tests (own .globalconfig, global_level=102) │ ├── E128.Reference.Cli.Tests/ # CLI unit tests │ ├── E128.Reference.Core.Tests/ # Core library unit tests │ ├── E128.Reference.Tests/ # Web integration tests +│ ├── Directory.Build.targets # Imports the root targets, adds the coverage extension to test projects │ └── .globalconfig # Test-specific severity overrides (global_level=101) ``` @@ -44,13 +45,13 @@ Key properties: - `CentralPackageTransitivePinningEnabled=true`, prevents transitive version drift - `CentralPackageVersionOverrideEnabled=false`, prevents per-project overrides -`Directory.Packages.props` owns the two `CentralPackage*` properties inside a setup-owned block. The block opens with a `repository-setup:begin cpm-hardening` comment that carries a SHA-256 hash. Never edit the block by hand. `Directory.Build.props` sets only the restore and audit properties. +`Directory.Packages.props` owns the two `CentralPackage*` properties inside a setup-owned block. The block opens with a `repository-setup:begin cpm-hardening` comment that carries a SHA-256 hash. Never edit the block by hand. `Directory.Build.props` sets no CPM property. ## Directory.Build.props vs .targets **Props** (evaluated before project files): TFM, language version, nullable, analyzers, code analysis settings, artifact paths, build performance flags, configuration-specific settings. -**Targets** (evaluated after project files): Conditional logic that depends on properties set in `.csproj`, primarily `true` detection for setting `OutputType=Exe` and MTP runner properties. Also contains the E128.Analyzers `ProjectReference`, all projects except the analyzer itself (`IsRoslynComponent != true`) automatically reference it as an `OutputItemType="Analyzer"` with `ReferenceOutputAssembly="false"`. The condition also gates on the `.csproj` existing, so the solution builds cleanly if the analyzer project is removed. +**Targets** (evaluated after project files): Conditional logic that depends on properties set in `.csproj`. `true` detection sets `OutputType=Exe` and the MTP runner properties. The `runtime-async=on` compiler feature applies to `net11.0` projects other than Roslyn component, test, and benchmark projects. `tests/Directory.Build.targets` imports this file and adds the coverage extension to test projects. The file also contains the E128.Analyzers `ProjectReference`: all projects except the two Roslyn components (`IsRoslynComponent != true`) automatically reference it as an `OutputItemType="Analyzer"` with `ReferenceOutputAssembly="false"`. The condition also gates on the `.csproj` existing, so the solution builds cleanly if the analyzer project is removed. ## global.json diff --git a/lode/summary.md b/lode/summary.md index 5be6f62a..d489037b 100644 --- a/lode/summary.md +++ b/lode/summary.md @@ -1,4 +1,4 @@ # E128.Reference Summary -*Updated: 2026-11-11T03:20:00Z* +*Updated: 2026-11-17T13:33:06Z* E128.Reference is the source repository for the published NuGet package E128.Analyzers, and a .NET 11 reference repository demonstrating modern conventions: custom Roslyn analyzers with code fixes (E128.Analyzers, published to nuget.org from `src/E128.Analyzers/`), minimal API web app (Kestrel), System.CommandLine CLI, hardened, Podman-built container images (Ubuntu Resolute base), strict deny-by-default code analysis with third-party Roslyn analyzers (see `Directory.Packages.props`), xUnit v3 + Microsoft Testing Platform with in-process Cobertura coverage and an 80 percent line floor per assembly, ArchUnitNET architecture tests enforcing structural invariants via IL analysis, BenchmarkDotNet starter benchmarks in `benchmarks/`, Central Package Management with transitive pinning, Renovate for automated dependency updates, OIDC trusted publishing to nuget.org via GitHub Actions, and a portable `AGENTS.md` instruction set plus a Claude Code harness layer (`CLAUDE.md` imports `AGENTS.md`, rules, hooks, skills, agents) powered by bash scripts. See `lode/infrastructure/claude-code-maintenance.md` for the portable-versus-Claude-only capability map. diff --git a/src/E128.Analyzers.CodeFixers/Performance/MultiStringEqualsOrChainCodeFixProvider.cs b/src/E128.Analyzers.CodeFixers/Performance/MultiStringEqualsOrChainCodeFixProvider.cs index 2dfa4433..82460562 100644 --- a/src/E128.Analyzers.CodeFixers/Performance/MultiStringEqualsOrChainCodeFixProvider.cs +++ b/src/E128.Analyzers.CodeFixers/Performance/MultiStringEqualsOrChainCodeFixProvider.cs @@ -17,6 +17,23 @@ namespace E128.Analyzers.Performance; [Shared] public sealed class MultiStringEqualsOrChainCodeFixProvider : E128CodeFixProviderBase { + // Longest spelling first, so the global-qualified form is not read as a plain member name. + private static readonly ImmutableArray ComparisonPrefixes = + [ + "global::System.StringComparison.", + "System.StringComparison.", + "StringComparison." + ]; + + private static readonly ImmutableHashSet ComparisonMembers = ImmutableHashSet.Create( + StringComparer.Ordinal, + "Ordinal", + "OrdinalIgnoreCase", + "CurrentCulture", + "CurrentCultureIgnoreCase", + "InvariantCulture", + "InvariantCultureIgnoreCase"); + public override ImmutableArray FixableDiagnosticIds => [MultiStringEqualsOrChainAnalyzer.DiagnosticId]; @@ -66,7 +83,13 @@ protected override async Task RegisterFixesAsync(CodeFixContext context, SyntaxN // The only no-op path is a failed field parse. Validate that too, so a registered fix // always changes code. - var fieldDecl = ParseFieldDeclaration(fieldName, GetComparerExpression(pivot.ComparisonKey), literals); + var comparerExpr = GetComparerExpression(pivot.ComparisonKey); + if (comparerExpr is null) + { + return; + } + + var fieldDecl = ParseFieldDeclaration(fieldName, comparerExpr, literals); if (fieldDecl is null) { return; @@ -164,6 +187,11 @@ private static bool TryExtractChainInfo( string fieldName) { var comparerExpr = GetComparerExpression(pivot.ComparisonKey); + if (comparerExpr is null) + { + return null; + } + var fieldDecl = ParseFieldDeclaration(fieldName, comparerExpr, literals); if (fieldDecl is null) { @@ -212,18 +240,30 @@ private static bool TryExtractChainInfo( return SyntaxFactory.ParseMemberDeclaration(sb.ToString()); } - private static string GetComparerExpression(string comparisonKey) + /// + /// Maps the comparison argument to the matching StringComparer member, for example + /// System.StringComparison.OrdinalIgnoreCase to + /// StringComparer.OrdinalIgnoreCase. Returns null for any other text, such as a variable, + /// which a static field cannot capture and which must not silently become an ordinal comparison. + /// + private static string? GetComparerExpression(string comparisonKey) { if (string.Equals(comparisonKey, "==", StringComparison.Ordinal)) { return "StringComparer.Ordinal"; } - // StringComparison.OrdinalIgnoreCase -> StringComparer.OrdinalIgnoreCase - const string comparisonPrefix = "StringComparison."; - const string comparerPrefix = "StringComparer."; - return comparisonKey.StartsWith(comparisonPrefix, StringComparison.Ordinal) - ? comparerPrefix + comparisonKey.Substring(comparisonPrefix.Length) - : "StringComparer.Ordinal"; + foreach (var prefix in ComparisonPrefixes) + { + if (!comparisonKey.StartsWith(prefix, StringComparison.Ordinal)) + { + continue; + } + + var member = comparisonKey.Substring(prefix.Length); + return ComparisonMembers.Contains(member) ? "StringComparer." + member : null; + } + + return null; } } diff --git a/src/E128.Analyzers.CodeFixers/Reliability/GeneratedRegexCompiledCodeFixProvider.cs b/src/E128.Analyzers.CodeFixers/Reliability/GeneratedRegexCompiledCodeFixProvider.cs index 55859ff1..aa649293 100644 --- a/src/E128.Analyzers.CodeFixers/Reliability/GeneratedRegexCompiledCodeFixProvider.cs +++ b/src/E128.Analyzers.CodeFixers/Reliability/GeneratedRegexCompiledCodeFixProvider.cs @@ -107,6 +107,11 @@ private static async Task ApplyFixAsync( return CreateRegexOptionsNone(expression); } + if (expression is ParenthesizedExpressionSyntax parenthesized) + { + return RemoveCompiledFromParenthesized(parenthesized, semanticModel, cancellationToken); + } + if (expression is BinaryExpressionSyntax binary && binary.IsKind(SyntaxKind.BitwiseOrExpression)) { @@ -116,6 +121,23 @@ private static async Task ApplyFixAsync( return expression; } + private static ExpressionSyntax RemoveCompiledFromParenthesized( + ParenthesizedExpressionSyntax parenthesized, + SemanticModel semanticModel, + CancellationToken cancellationToken) + { + var inner = RemoveCompiled(parenthesized.Expression, semanticModel, cancellationToken); + if (inner is null || inner == parenthesized.Expression) + { + return parenthesized; + } + + // A lone option needs no parentheses. A remaining OR-chain keeps them. + return inner is MemberAccessExpressionSyntax + ? inner.WithTriviaFrom(parenthesized) + : parenthesized.WithExpression(inner); + } + private static ExpressionSyntax? RemoveCompiledFromBinary( BinaryExpressionSyntax binary, ExpressionSyntax originalExpression, diff --git a/src/E128.Analyzers.CodeFixers/Security/InsecureRandomInCryptoContextCodeFixProvider.cs b/src/E128.Analyzers.CodeFixers/Security/InsecureRandomInCryptoContextCodeFixProvider.cs index 374f6d2e..65b41c83 100644 --- a/src/E128.Analyzers.CodeFixers/Security/InsecureRandomInCryptoContextCodeFixProvider.cs +++ b/src/E128.Analyzers.CodeFixers/Security/InsecureRandomInCryptoContextCodeFixProvider.cs @@ -162,10 +162,13 @@ private static bool IsShadowedBySourceType( InvocationExpressionSyntax replacement, INamedTypeSymbol expected) { - var boundPlain = model.GetSpeculativeSymbolInfo( - invocation.SpanStart, - replacement, - SpeculativeBindingOption.BindAsExpression).Symbol; + // Bind the type name alone. Binding the whole invocation yields the method symbol, never the type. + var boundPlain = replacement.Expression is MemberAccessExpressionSyntax { Expression: { } typeName } + ? model.GetSpeculativeSymbolInfo( + invocation.SpanStart, + typeName, + SpeculativeBindingOption.BindAsExpression).Symbol + : null; return boundPlain is ITypeSymbol plainType && string.Equals(plainType.Name, RandomNumberGeneratorName, StringComparison.Ordinal) && diff --git a/src/E128.Analyzers/E128.Analyzers.csproj b/src/E128.Analyzers/E128.Analyzers.csproj index 9efd31fd..9423e0de 100644 --- a/src/E128.Analyzers/E128.Analyzers.csproj +++ b/src/E128.Analyzers/E128.Analyzers.csproj @@ -23,7 +23,7 @@ - 3.1.3 + 3.1.4 true false true diff --git a/src/E128.Analyzers/README.md b/src/E128.Analyzers/README.md index 190cacda..93592e6a 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. diff --git a/src/E128.Analyzers/Reliability/GeneratedRegexAnalyzer.cs b/src/E128.Analyzers/Reliability/GeneratedRegexAnalyzer.cs index 9080c509..d730498c 100644 --- a/src/E128.Analyzers/Reliability/GeneratedRegexAnalyzer.cs +++ b/src/E128.Analyzers/Reliability/GeneratedRegexAnalyzer.cs @@ -239,6 +239,11 @@ private static bool ExpressionContainsCompiled( SemanticModel semanticModel, CancellationToken cancellationToken) { + if (expression is ParenthesizedExpressionSyntax parenthesized) + { + return ExpressionContainsCompiled(parenthesized.Expression, semanticModel, cancellationToken); + } + if (expression is BinaryExpressionSyntax binary && binary.IsKind(SyntaxKind.BitwiseOrExpression)) { diff --git a/tests/E128.Analyzers.Tests/GeneratedRegexCompiledParenthesizedTests.cs b/tests/E128.Analyzers.Tests/GeneratedRegexCompiledParenthesizedTests.cs new file mode 100644 index 00000000..d68a23e9 --- /dev/null +++ b/tests/E128.Analyzers.Tests/GeneratedRegexCompiledParenthesizedTests.cs @@ -0,0 +1,65 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class GeneratedRegexCompiledParenthesizedTests +{ + private const string PartialImpl = " private static partial System.Text.RegularExpressions.Regex DigitsOnly() => null!;"; + + /// + /// Parentheses do not change the options value, so a parenthesized Compiled flag is as + /// redundant as a bare one. The fix drops the flag and the parentheses it leaves redundant. + /// + [Theory] + [Trait("Category", "CI")] + [InlineData("RegexOptions.IgnoreCase | (RegexOptions.Multiline | RegexOptions.Compiled)", "RegexOptions.IgnoreCase | RegexOptions.Multiline")] + [InlineData("(RegexOptions.Compiled | RegexOptions.IgnoreCase) | RegexOptions.Multiline", "RegexOptions.IgnoreCase | RegexOptions.Multiline")] + [InlineData("(RegexOptions.Compiled)", "RegexOptions.None")] + [InlineData("RegexOptions.IgnoreCase | (RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.Compiled)", "RegexOptions.IgnoreCase | (RegexOptions.Multiline | RegexOptions.Singleline)")] + public Task ParenthesizedCompiled_IsReportedAndRemoved(string options, string expected) + { + return CodeFixTestRunner.RunAsync( + $$""" + using System.Text.RegularExpressions; + using System.Threading; + partial class C + { + [{|E128012:GeneratedRegex(@"\d+", {{options}}, 1000)|}] + private static partial Regex DigitsOnly(); + {{PartialImpl}} + } + """, + $$""" + using System.Text.RegularExpressions; + using System.Threading; + partial class C + { + [GeneratedRegex(@"\d+", {{expected}}, 1000)] + private static partial Regex DigitsOnly(); + {{PartialImpl}} + } + """); + } + + /// + /// Parenthesized options without the Compiled flag stay silent. + /// + [Fact] + [Trait("Category", "CI")] + public Task ParenthesizedOptionsWithoutCompiled_Silent() + { + return CodeFixTestRunner.NoFixAsync( + $$""" + using System.Text.RegularExpressions; + using System.Threading; + partial class C + { + [GeneratedRegex(@"\d+", RegexOptions.IgnoreCase | (RegexOptions.Multiline | RegexOptions.Singleline), 1000)] + private static partial Regex DigitsOnly(); + {{PartialImpl}} + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/InsecureRandomInCryptoContextOuterShadowTests.cs b/tests/E128.Analyzers.Tests/InsecureRandomInCryptoContextOuterShadowTests.cs new file mode 100644 index 00000000..d795621a --- /dev/null +++ b/tests/E128.Analyzers.Tests/InsecureRandomInCryptoContextOuterShadowTests.cs @@ -0,0 +1,75 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class InsecureRandomInCryptoContextOuterShadowTests +{ + /// + /// A type in the enclosing namespace wins over a using directive. After the fix adds the + /// cryptography using, the plain name still binds to the source type, so no fix is offered. + /// + [Theory] + [Trait("Category", "CI")] + [InlineData("class RandomNumberGenerator { }")] + [InlineData("static class RandomNumberGenerator { public static int GetInt32(int fromInclusive, int toExclusive) => 4; }")] + public Task NoFix_WhenAGlobalNamespaceTypeShadowsRandomNumberGenerator(string shadow) + { + return CodeFixTestRunner.NoFixAsync( + $$""" + using System; + + {{shadow}} + + class C + { + int M() + { + var token = {|E128075:Random.Shared|}.Next(1, 7); + return token; + } + } + """); + } + + /// + /// The shadow check must not block the fix when the existing cryptography using already + /// resolves the plain name to the BCL type. + /// + [Fact] + [Trait("Category", "CI")] + public Task Fix_WhenNothingShadowsRandomNumberGenerator() + { + return CodeFixTestRunner.RunAsync( + """ + using System; + using System.Security.Cryptography; + + class Other { } + + class C + { + int M() + { + var token = {|E128075:Random.Shared|}.Next(1, 7); + return token; + } + } + """, + """ + using System; + using System.Security.Cryptography; + class Other { } + + class C + { + int M() + { + var token = RandomNumberGenerator.GetInt32(1, 7); + return token; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/MultiStringEqualsOrChainComparerSpellingTests.cs b/tests/E128.Analyzers.Tests/MultiStringEqualsOrChainComparerSpellingTests.cs new file mode 100644 index 00000000..d5b65434 --- /dev/null +++ b/tests/E128.Analyzers.Tests/MultiStringEqualsOrChainComparerSpellingTests.cs @@ -0,0 +1,74 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Microsoft.CodeAnalysis.CSharp.Testing; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class MultiStringEqualsOrChainComparerSpellingTests +{ + private static Task VerifyFixAsync(string source, string fixedCode, int fixAllIterations = 1) + { + return new CSharpCodeFixTest + { + TestCode = source, + FixedCode = fixedCode, + ReferenceAssemblies = ReferenceAssemblies.Net.Net100, + NumberOfFixAllIterations = fixAllIterations + }.RunAsync(TestContext.Current.CancellationToken); + } + + /// + /// A fully qualified comparison keeps its case-insensitive meaning. Mapping it to the ordinal + /// comparer would turn case-insensitive matching into case-sensitive matching. + /// + [Theory] + [Trait("Category", "CI")] + [InlineData("System.StringComparison.OrdinalIgnoreCase", "OrdinalIgnoreCase")] + [InlineData("global::System.StringComparison.CurrentCultureIgnoreCase", "CurrentCultureIgnoreCase")] + public Task QualifiedComparison_KeepsTheMatchingComparer(string comparison, string comparer) + { + var source = $$""" + class C + { + bool M(string text) => + {|E128029:string.Equals(text, "a", {{comparison}}) || string.Equals(text, "b", {{comparison}}) || string.Equals(text, "c", {{comparison}})|}; + } + """; + + var fixedCode = $$""" + using System; + using System.Collections.Generic; + + class C + { + private static readonly HashSet _textValues = new(StringComparer.{{comparer}}) { "a", "b", "c" }; + + bool M(string text) => + _textValues.Contains(text); + } + """; + + return VerifyFixAsync(source, fixedCode); + } + + /// + /// A comparison held in a variable cannot move into a static field, so no fix is offered. + /// + [Fact] + [Trait("Category", "CI")] + public Task VariableComparison_NoFixApplied() + { + const string source = """ + using System; + class C + { + bool M(string text, StringComparison comparison) => + {|E128029:string.Equals(text, "a", comparison) || string.Equals(text, "b", comparison) || string.Equals(text, "c", comparison)|}; + } + """; + + return VerifyFixAsync(source, source, 0); + } +}