diff --git a/README.md b/README.md index 0901341..ac1da98 100644 --- a/README.md +++ b/README.md @@ -93,7 +93,7 @@ scripts/podman.sh test | **E128.Reference.Web** | Minimal API web app with Kestrel and a health endpoint | | **E128.Reference.Cli** | System.CommandLine CLI with a `--name` option | | **E128.Reference.Core** | Shared library (Greeter service, models, repositories, services) | -| **E128.Analyzers** | Roslyn analyzers (E128001 to E128226), published to nuget.org | +| **E128.Analyzers** | Roslyn analyzers (E128001 to E128231), published to nuget.org | | **E128.Analyzers.CodeFixers** | Code fix providers for the analyzer rules, shipped in the same package | | **E128.Reference.Tests** | xUnit v3 and MTP with the CI, Podman, and Manual test categories | | **Architecture.Tests** | ArchUnitNET structural invariant tests (layers, naming, sealed) | diff --git a/lode/dotnet/analyzer-candidates/catalog.md b/lode/dotnet/analyzer-candidates/catalog.md index 5c017e3..04ab122 100644 --- a/lode/dotnet/analyzer-candidates/catalog.md +++ b/lode/dotnet/analyzer-candidates/catalog.md @@ -1,5 +1,5 @@ # Analyzer Candidates: Settled Catalog -*Updated: 2026-11-17T23:06:12Z* +*Updated: 2026-11-18T00:04:03Z* This file holds the settled side of the register: which rule shipped, which idea was checked and rejected, and which sweep closed. Every rule ships from @@ -13,8 +13,8 @@ description. The 2026-11-05 external sweep is complete. See [external-sweep.md](external-sweep.md). -The twenty-practice performance sweep shipped fifteen rules and leaves one -extension. See [performance-sweep.md](performance-sweep.md). +The twenty-practice performance sweep shipped fifteen rules, and its E128037 +extension also ships. See [performance-sweep.md](performance-sweep.md). The async sweep closed with no rule. See [async-sweep.md](async-sweep.md). The implicit state machine rule ships as E128218. See @@ -49,6 +49,9 @@ conversion plan. Open .NET 11 conversion shapes: [net11-conversion-sweep.md](net | E128226 | comparer-set-by-loop | implemented | 3.5/5 | 2026-11-13 | | E128227 | http-body-read-without-size-bound | implemented | 3.5/5 | 2026-11-13 | | E128228 | token-validation-flag-false | implemented | n/a | 2026-11-17 | +| E128229 | middleware-func-task-next-delegate | implemented | 4/5 | 2026-11-17 | +| E128230 | static-files-runtime-pipeline | implemented | 4/5 | 2026-11-17 | +| E128231 | split-result-enumerated | implemented | 3.5/5 | 2026-11-17 | ## Rules From Guidance Documents diff --git a/lode/dotnet/analyzer-candidates/guidance-reads.md b/lode/dotnet/analyzer-candidates/guidance-reads.md index ed90e63..5779952 100644 --- a/lode/dotnet/analyzer-candidates/guidance-reads.md +++ b/lode/dotnet/analyzer-candidates/guidance-reads.md @@ -1,5 +1,5 @@ # Guidance Document Reads -*Updated: 2026-11-17T23:06:12Z* +*Updated: 2026-11-18T00:04:03Z* Two published guidance documents seeded a large part of the rule set. Source A is the performance skill guide in `EgorBo/BlazingFastDotnet`. Source B is the @@ -80,19 +80,20 @@ A read on 2026-11-17 checked the whole guide against the shipped rule set and the installed analyzers. The guide covers profiling, runtime knobs, NativeAOT, ASP.NET Core, strings, and vectorization. -Three shapes clear the bar and sit in [index.md](index.md): the `Func` +Three shapes from that read shipped as E128229 to E128231: the `Func` middleware delegate, `UseStaticFiles`, and `string.Split` used only to -enumerate. Three more join the Tier 2 table: a per-item `Parallel.For` body, a -`FileStream` captured by a parallel body, and a `readonly` field re-read inside -a loop. +enumerate. Three more joined the Tier 2 table: a per-item `Parallel.For` body, +a `FileStream` captured by a parallel body, and a `readonly` field re-read +inside a loop. Four shapes have an installed owner. See [skipped-decisions.md](skipped-decisions.md). -Two extensions belong to shipped rules, not to new IDs. E128135 covers -`TensorPrimitives.Sum` only, and a `Min`, `Max`, `Add`, or `Multiply` loop is -the same shape. E128084 covers `List.GetRange` only, and an indexer loop over a -list is the shape that the open `CollectionsMarshal.AsSpan` Tier 2 row guards. +Two extensions belong to shipped rules, not to new IDs. E128135 covers a sum +loop and a min or max loop with a neutral initial value. E128084 covers +`List.GetRange` and an indexer loop over a list. +The `Add` and `Multiply` loop shapes remain open. Neither maps to a one-span +reduction, so each needs its own detection shape. ## Related diff --git a/lode/dotnet/analyzer-candidates/index.md b/lode/dotnet/analyzer-candidates/index.md index 9360308..b0f8710 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-17T23:06:12Z* +*Updated: 2026-11-18T00:19:04Z* 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,16 +27,12 @@ definitions live in the `analyzer-review-miner` agent definition. ## Open Candidates -The guide below is the same source that seeded the shipped performance rules. -Every shape it lists that already has an owner stays out of this table. -The declined shapes sit in [skipped-decisions.md](skipped-decisions.md). - -| Pattern | Source | Score | Status | Notes | -| ------- | ------ | ----- | ------ | ----- | -| Inline middleware takes a `Func` next delegate | BlazingFastDotnet skill guide | 4/5 | new | The `Use` overload allocates one closure per request. Detail below. | -| `UseStaticFiles()` in a minimal API app | BlazingFastDotnet skill guide | 4/5 | new | `MapStaticAssets` serves a build-time manifest. Detail below. | -| `string.Split` result only enumerated | BlazingFastDotnet skill guide | 3.5/5 | new | One array and one string per part allocate. Detail below. | +The BlazingFastDotnet guide is the same source that seeded the shipped +performance rules. Every shape it lists that already has an owner stays out of +this table. The declined shapes sit in +[skipped-decisions.md](skipped-decisions.md). +No open candidate remains from the 2026-11-17 guidance read. `ByteSizeType.Is` matches the type by simple name, so a namespace move does not break the E128080 exemption. @@ -45,69 +41,6 @@ The token-validation flag shape shipped as E128228. See [catalog.md](catalog.md) The JSON enumerator shape closed as skipped, because the enumerator releases no resource. See [skipped-decisions.md](skipped-decisions.md). -### Inline Middleware Next Delegate - -`app.Use(async (ctx, next) => ...)` binds the `Func, Task>` -overload. That overload allocates a `Func` closure on every request. -The `Func` overload passes `next` as a -`RequestDelegate`, so the call allocates nothing. - -```csharp -// Allocates a closure per request. -app.Use(async (context, next) => -{ - await next(); -}); - -// Allocates nothing. -app.Use(async (context, next) => -{ - await next(context); -}); -``` - -Detection: a `Use` call whose lambda declares a second parameter of type -`Func`. The rule reports that lambda. The `ctx` parameter must stay live -up to the `next` call, and the lambda must not reassign it. - -Fix: yes. The rewrite changes the lambda call and leaves the body intact. - -### Static Files Served Through the Runtime Pipeline - -`app.UseStaticFiles()` sends a file through middleware at request time. -`app.MapStaticAssets()` serves a build-time manifest that carries precompressed -variants and ETags. - -Detection: a `UseStaticFiles` call in a project that targets `net9.0` or later. - -Fix: no automatic fix. The call moves into the endpoint mapping section, and a -Razor app also changes how it references the assets. - -### `string.Split` Used Only to Enumerate - -`value.Split(sep)` allocates an array and one string per part. -`MemoryExtensions.Split` yields `Range` values over the existing string. - -```csharp -// Allocates the array and one string per part. -foreach (var part in line.Split(',')) -{ - Handle(part); -} - -// Allocates nothing. -foreach (var range in line.AsSpan().Split(',')) -{ - Handle(line.AsSpan()[range]); -} -``` - -Detection: a `Split` call whose result no code stores. The separator is a -`char` or a constant string. - -Fix: no automatic fix when the body stores a part as a string. The fix applies -when every read is a slice, a comparison, or a numeric parse. - ## Tier 2 Candidates These clear the same bar and wait for a real defect in review. diff --git a/lode/dotnet/analyzers.md b/lode/dotnet/analyzers.md index b493c95..3965462 100644 --- a/lode/dotnet/analyzers.md +++ b/lode/dotnet/analyzers.md @@ -1,5 +1,5 @@ # .NET 11 Roslyn Analyzers -*Updated: 2026-11-17T22:44:32Z* +*Updated: 2026-11-17T23:57:12Z* ## Strategy: Deny by Default @@ -122,7 +122,7 @@ Key rules by category (not exhaustive): | ----------- | -------------------------------------------------------------------------------------------------- | | Design | Sealed-by-default, async void, sync-over-async, ConfigureAwait, TimeProvider, DI, ImmutableArray, abstract base with members is closed (E128225) | | Reliability | GeneratedRegex safety, DateTime roundtrip, Task.WhenAll, JsonDocument lifetime, pool Rent() guard, stackalloc bounds, pool zeroing, service lifetime (E128154, `TryAdd`, keyed, `typeof` and `AddHostedService` forms, and a singleton `DbContext`), `foreach` mutation (E128155, including array writes and `break` or `return` exits), `TaskCompletionSource` options and shared-source completers (E128159), hand-rolled process capture (E128223, redirect, read, then wait), `Path.Combine` segments (E128161), use after `Dispose` (E128162, direct block statement only), `ImmutableArray` default (E128163, no fix for struct instance fields), `await` in `finally` (E128186), exception filter text read (E128188), unreleased `GCHandle` (E128189), hidden `GetBuffer` (E128192), disposable field overwritten in a loop (E128193), `Lazy` without thread safety (E128194), configuration key absent from the settings files (E128195), `JsonSerializerOptions` written after first use (E128196), fixed day count used as a month (E128197), `Substring` count underflow (E128198) | -| Performance | MinBy/MaxBy, HttpCompletionOption, FrozenSet, O(n²) loops, `SearchValues` (E128102), UTF-8 parsing, alternate lookups (E128131 to E128135), span bulk methods (E128140), u8 literals (E128141), complexity ceiling (E128152), `RemoveAt(0)` in loop (E128153), `SaveChanges` in loop (E128185), uncapped `Parallel.ForEachAsync` (E128187), `FileStream` without async I/O (E128190), HTTP and database round trips in a loop (E128203, E128204), collection presize (E128205), empty spin loop (E128206), reflection lookup in a loop (E128207), concurrent dictionary double lookup (E128208), `GetBytes` length in a loop (E128209), `new Regex` in a loop (E128210), `Task.Delay` in a loop without a token (E128211), `ToCharArray` copy (E128212), `Activator` in a loop (E128213), handler without decompression (E128214), `StringBuilder` capacity (E128215), unbounded channel (E128216), large struct by value (E128217), read-only `MemoryStream` (E128224), comparer set filled by a loop (E128226) | +| Performance | MinBy/MaxBy, HttpCompletionOption, FrozenSet, O(n²) loops, `SearchValues` (E128102), UTF-8 parsing, alternate lookups (E128131 to E128135), span bulk methods (E128140), u8 literals (E128141), complexity ceiling (E128152), `RemoveAt(0)` in loop (E128153), `SaveChanges` in loop (E128185), uncapped `Parallel.ForEachAsync` (E128187), `FileStream` without async I/O (E128190), HTTP and database round trips in a loop (E128203, E128204), collection presize (E128205), empty spin loop (E128206), reflection lookup in a loop (E128207), concurrent dictionary double lookup (E128208), `GetBytes` length in a loop (E128209), `new Regex` in a loop (E128210), `Task.Delay` in a loop without a token (E128211), `ToCharArray` copy (E128212), `Activator` in a loop (E128213), handler without decompression (E128214), `StringBuilder` capacity (E128215), unbounded channel (E128216), large struct by value (E128217), read-only `MemoryStream` (E128224), comparer set filled by a loop (E128226), middleware `Func` next delegate (E128229), static files through the runtime pipeline (E128230), split result enumerated without a stored array (E128231) | | Security | FIPS cryptography rules: unapproved hash names, `System.Random` in security code, managed and CNG type creation, RSA key size, cipher mode, PBKDF2 work factor, TLS versions, deprecated RNG, excluded cipher names, AES-GCM tag size, SHA-3 policy, HMAC key length (E128071, E128075, E128142 to E128151), certificate bypass (E128156, `SslOptions` and `SslStream` too), fixed-time compare (E128157), hardcoded URL (E128164, dot boundary), hardcoded secret (E128165, token, credential and bearer names, `??`, indexers, getter returns, `u8`, connection strings), sensitive log argument (E128166, `LoggerMessage`, wrapped args, whole-word `ssn` and `pwd`, skips `EventId` and `Exception`), PFX import without `EphemeralKeySet` (E128191), unvalidated JWT claims used as an identity (E128202), token validation flag pinned false (E128228) | | Unsafe | `Unsafe.As` to `Unsafe.BitCast`, unaligned reads, unaligned non-blittable reads (E128139), bounds bypass, bool and int reinterpret, non-blittable `MemoryMarshal`, fixed buffers, `SkipInit`, unpinned pointers, string writes, null byref, delegate lifetime, bulk copy, pointer and length pairs, nonpublic reflection, raw IL, function pointer types (E128112 to E128129, E128136 to E128139, E128200) | | Style | string.Empty, Encoding.UTF8, XML doc comments, null-forgiving operator | diff --git a/lode/dotnet/analyzers/rule-details-performance-aspnet.md b/lode/dotnet/analyzers/rule-details-performance-aspnet.md new file mode 100644 index 0000000..b6d8728 --- /dev/null +++ b/lode/dotnet/analyzers/rule-details-performance-aspnet.md @@ -0,0 +1,59 @@ +# Performance Rule Details: ASP.NET Core +*Updated: 2026-11-17T23:58:14Z* + +Detection shape for the ASP.NET Core allocation rules E128229 to E128231. The +rest of the performance rules live in +[rule-details-performance.md](rule-details-performance.md). Each rule gates on +the API that supplies its remedy, so a compilation without ASP.NET Core gets no +report. + +### E128229: Middleware next delegate closure + +Flags an inline `Use` middleware whose second parameter is `Func`. The +`Func, Task>` overload allocates a `Func` closure +per request. The `RequestDelegate` overload passes the same delegate with no +allocation. + +The rule resolves `IApplicationBuilder` and `UseMiddlewareExtensions`, then +checks the delegate type by symbol. It reports the second parameter only when +every use of `next` is a call with no argument, at least one call exists, and +the context parameter carries no assignment. + +The code fix writes `RequestDelegate` in the parameter type position, passes the +context to every call, and adds `Microsoft.AspNetCore.Http` when the file lacks +it. + +### E128230: Static files through the runtime pipeline + +Flags a zero-argument `UseStaticFiles` call. `MapStaticAssets` serves a +build-time manifest with precompressed variants and ETags. + +The rule registers only when the compilation declares `MapStaticAssets`, which +gates the rule to a target framework with the endpoint mapping API. The symbol +must belong to `StaticFileExtensions`. A call that passes `StaticFileOptions` +stays silent. No code fix, because the call moves into the endpoint mapping +section and a Razor app also changes how it references the assets. + +### E128231: Split result used only to enumerate + +Flags a `foreach` over `string.Split` with a `char` or constant-string separator +and the default split options. `MemoryExtensions.Split` yields `Range` values +over the source with no array and no part strings. + +The rule registers only when `MemoryExtensions` declares the span `Split` +extension. It reports the loop. The fix applies when the receiver is a name +chain and every read of the part is a length, an element access, or a +constant-string comparison. The fix enumerates `source.AsSpan().Split(separator)` +and reads each part as `source.AsSpan()[range]`. + +A numeric parse stays reported with no fix. The narrowest `Parse` overload for +`ReadOnlySpan` also takes an `IFormatProvider`, so the rewrite would add a +culture decision that the loop does not state. + +## Related + +- [rule-details-performance.md](rule-details-performance.md): the earlier + performance rules and the E128135 and E128084 extensions +- [rule-details-performance-tier2.md](rule-details-performance-tier2.md): the + waiting Tier 2 performance rules +- [rule-details.md](rule-details.md): the remaining rule details diff --git a/lode/dotnet/analyzers/rule-details-performance.md b/lode/dotnet/analyzers/rule-details-performance.md index 085de02..1eaf920 100644 --- a/lode/dotnet/analyzers/rule-details-performance.md +++ b/lode/dotnet/analyzers/rule-details-performance.md @@ -1,5 +1,5 @@ # Performance Rule Details -*Updated: 2026-11-09T23:44:15Z* +*Updated: 2026-11-17T23:58:14Z* Behavior notes for the performance rules. The complete rule table, the severity, and the code-fix status live in `src/E128.Analyzers/README.md`. The @@ -207,6 +207,20 @@ per-iteration values. No code fix. The hoisted field name and the `GeneratedRegex` shape are caller choices. +### E128135 and E128084 extensions + +E128135 also reports a minimum or maximum loop over a `float` or `double` +source. The reduction must start at the neutral value: `MinValue` for a maximum +and `MaxValue` for a minimum. The fix writes the reduction into the accumulator +declaration and removes the loop. + +E128084 also reports `for (int i = 0; i < list.Count; i++)` when the body only +reads `list[i]`. The rule suppresses a loop that mutates the list, writes +through the indexer, or uses the loop variable for another purpose. The fix +enumerates `CollectionsMarshal.AsSpan(list)`. + +ASP.NET Core rules E128229 to E128231 live in +[rule-details-performance-aspnet.md](rule-details-performance-aspnet.md). Tier 2 rules E128211 to E128217 live in [rule-details-performance-tier2.md](rule-details-performance-tier2.md). diff --git a/lode/dotnet/release-tracking.md b/lode/dotnet/release-tracking.md index 18d5ee7..0d351e1 100644 --- a/lode/dotnet/release-tracking.md +++ b/lode/dotnet/release-tracking.md @@ -1,5 +1,5 @@ # Roslyn Analyzer Release Tracking -*Updated: 2026-11-17T22:56:03Z* +*Updated: 2026-11-18T00:22:59Z* ## Overview @@ -171,6 +171,7 @@ that is missing from either file blocks the ship, even on a docs-only change set | 3.0.0 | (none) | E128160 removed. E128223 reports the read-then-wait shape that replaced the hand-rolled process capture. | | 3.1.0 | E128227 | HTTP body read without a size bound. Security, Warning. | | 3.2.0 | E128228 | Token validation flag set to constant false. Security, Warning. | +| 3.3.0 | E128229-231 | Middleware next delegate, static assets, and split enumeration. E128135 and E128084 gain a second detection shape. | ## Sources diff --git a/lode/lode-map.md b/lode/lode-map.md index 3881d95..4b713d4 100644 --- a/lode/lode-map.md +++ b/lode/lode-map.md @@ -1,5 +1,5 @@ # Lode Map -*Updated: 2026-11-17T23:06:12Z* +*Updated: 2026-11-17T23:58:14Z* ## Generated Docs @@ -69,6 +69,7 @@ - [rule-details.md](dotnet/analyzers/rule-details.md): Per-rule detection shape, exclusions, and code-fix behavior for the E128 rules - [rule-details-performance.md](dotnet/analyzers/rule-details-performance.md): Detection shape for performance rules E128203 to E128210 - [rule-details-performance-tier2.md](dotnet/analyzers/rule-details-performance-tier2.md): Detection shape for performance rules E128211 to E128217 +- [rule-details-performance-aspnet.md](dotnet/analyzers/rule-details-performance-aspnet.md): Detection shape for ASP.NET Core performance rules E128229 to E128231 - [rule-details-reliability.md](dotnet/analyzers/rule-details-reliability.md): Detection shape for the reliability rules - [rule-details-reliability-concurrency.md](dotnet/analyzers/rule-details-reliability-concurrency.md): Detection shape for the async and concurrent reliability rules - [rule-details-reliability-resources.md](dotnet/analyzers/rule-details-reliability-resources.md): Detection shape for the resource lifetime and shared state rules diff --git a/plans/roadmap.md b/plans/roadmap.md index 1414f3f..b2761cf 100644 --- a/plans/roadmap.md +++ b/plans/roadmap.md @@ -1,5 +1,5 @@ # Roadmap -*Updated: 2026-11-17T23:07:20Z* +*Updated: 2026-11-18T00:19:04Z* Unplanned work awaiting a plan. @@ -10,112 +10,7 @@ the read that found these shapes lives in ## Active -### Middleware Next Delegate Closure -- **Added:** 2026-11-17T23:07:20Z -- **Register:** 4/5, `new`. Candidate for E128229. -- **Shape:** a `Use` lambda that takes a `Func` next delegate. That overload allocates one closure per request. - -```csharp -// Report -app.Use(async (HttpContext context, Func next) => -{ - await next(); -}); - -// Fix -app.Use(async (HttpContext context, RequestDelegate next) => -{ - await next(context); -}); -``` - -- **Fix scope:** rewrite the parameter type and the call. Report only where `context` stays live and is never reassigned. The `RequestDelegate` overload exists on .NET 7 and later. -- **Trigger:** Plan this entry first. The shape is clear and the fix is a local rewrite. - -### Static Files Mapped at Build Time -- **Added:** 2026-11-17T23:07:20Z -- **Register:** 4/5, `new`. Candidate for E128230. -- **Shape:** `UseStaticFiles` sends a file through middleware at request time. `MapStaticAssets` serves a build-time manifest with precompressed variants and ETags. - -```csharp -// Report -app.UseStaticFiles(); - -// Fix -app.MapStaticAssets(); -``` - -- **Fix scope:** report a `UseStaticFiles` call in a project that targets `net9.0` or later. No automatic fix, because the call moves into the endpoint mapping section. A Razor app also changes how it references the assets. -- **Trigger:** Plan after the middleware rule, because the same project shape and TFM check apply. - -### Split Result Used Only to Enumerate -- **Added:** 2026-11-17T23:07:20Z -- **Register:** 3.5/5, `new`. Candidate for E128231. -- **Shape:** `string.Split` allocates one array and one string per part. `MemoryExtensions.Split` yields `Range` values over the source string. - -```csharp -// Report -foreach (string part in line.Split(',')) -{ - total += int.Parse(part); -} - -// Fix -foreach (Range range in line.AsSpan().Split(',')) -{ - total += int.Parse(line.AsSpan()[range]); -} -``` - -- **Fix scope:** report only where no code stores the array. The separator is a `char` or a constant string. Rewrite only where every read is a slice, a comparison, or a numeric parse. Report without a fix when the body stores a part as a string. -- **Trigger:** Plan after the two ASP.NET Core rules. - -### TensorPrimitives Min and Max Loops -- **Added:** 2026-11-17T23:07:20Z -- **Register:** extension of E128135, no new ID. See [catalog.md](../lode/dotnet/analyzer-candidates/catalog.md). -- **Shape:** E128135 covers `TensorPrimitives.Sum` only. A loop that computes `Min`, `Max`, `Add`, or `Multiply` over one span is the same shape. - -```csharp -// Report -double max = double.MinValue; -foreach (double value in values) -{ - if (value > max) - { - max = value; - } -} - -// Fix -double max = TensorPrimitives.Max(values); -``` - -- **Fix scope:** reuse the E128135 detection and code fix. Add the four members to the same member table. Report only a single-span loop with no other side effect. -- **Trigger:** Plan with E128135. The extension touches one analyzer and one code fix. - -### List Indexer Loop to a Span -- **Added:** 2026-11-17T23:07:20Z -- **Register:** extension of E128084, no new ID. Guards the open `CollectionsMarshal.AsSpan` Tier 2 row. -- **Shape:** E128084 covers `List.GetRange` only. A `for` loop that indexes a `List` repeats a bounds check per element. - -```csharp -// Report -int total = 0; -for (int i = 0; i < items.Count; i++) -{ - total += items[i].Length; -} - -// Fix -int total = 0; -foreach (string item in CollectionsMarshal.AsSpan(items)) -{ - total += item.Length; -} -``` - -- **Fix scope:** suppress the report when the loop mutates the list. The span reads stale memory after a mutation, so the fix is wrong for that shape. -- **Trigger:** Plan with E128084. The fix reuses the existing `List.GetRange` rewrite. +No unplanned work waits for a plan. ## Waiting diff --git a/src/E128.Analyzers.CodeFixers/Performance/ListGetRangeCodeFixProvider.cs b/src/E128.Analyzers.CodeFixers/Performance/ListGetRangeCodeFixProvider.cs index 231d2f1..b24ad3a 100644 --- a/src/E128.Analyzers.CodeFixers/Performance/ListGetRangeCodeFixProvider.cs +++ b/src/E128.Analyzers.CodeFixers/Performance/ListGetRangeCodeFixProvider.cs @@ -7,6 +7,7 @@ using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; namespace E128.Analyzers.Performance; @@ -18,21 +19,103 @@ public sealed class ListGetRangeCodeFixProvider : E128CodeFixProviderBase public override ImmutableArray FixableDiagnosticIds => [ListGetRangeAnalyzer.DiagnosticId]; - protected override Task RegisterFixesAsync(CodeFixContext context, SyntaxNode root) + protected override async Task RegisterFixesAsync(CodeFixContext context, SyntaxNode root) { - var invocation = root.FindNode(context.Diagnostics[0].Location.SourceSpan) + var node = root.FindNode(context.Diagnostics[0].Location.SourceSpan, getInnermostNodeForTie: true); + + if (node is ForStatementSyntax loop) + { + await RegisterLoopFixAsync(context, loop).ConfigureAwait(false); + return; + } + + var invocation = node .AncestorsAndSelf() .OfType() .FirstOrDefault(); if (invocation is null) { - return Task.CompletedTask; + return; } CodeFixRegistration.Register(context, context.Diagnostics[0], "Use CollectionsMarshal.AsSpan with Slice", ListGetRangeAnalyzer.DiagnosticId, ct => ApplyFixAsync(context.Document, invocation, ct)); + } + + private static async Task RegisterLoopFixAsync(CodeFixContext context, ForStatementSyntax loop) + { + var model = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false); + var listType = model?.Compilation.GetTypeByMetadataName("System.Collections.Generic.List`1"); + + if (model is null + || listType is null + || !ListGetRangeAnalyzer.TryMatchIndexerLoop( + loop, + model, + listType, + context.CancellationToken, + out var list, + out _) + || list is null) + { + return; + } + + CodeFixRegistration.Register( + context, + context.Diagnostics[0], + "Enumerate CollectionsMarshal.AsSpan", + ListGetRangeAnalyzer.DiagnosticId, + ct => ApplyLoopFixAsync(context.Document, context.Diagnostics[0].Location.SourceSpan, ct)); + } + + private static async Task ApplyLoopFixAsync( + Document document, + TextSpan span, + CancellationToken cancellationToken) + { + var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); + var listType = model?.Compilation.GetTypeByMetadataName("System.Collections.Generic.List`1"); + + if (root is null + || model is null + || listType is null + || root.FindNode(span, getInnermostNodeForTie: true) is not ForStatementSyntax loop + || !ListGetRangeAnalyzer.TryMatchIndexerLoop( + loop, + model, + listType, + cancellationToken, + out var list, + out var reads) + || list is null + || loop.Declaration is not { Variables.Count: 1 } declaration) + { + return document; + } + + var variableName = declaration.Variables[0].Identifier.ValueText; + var asSpanCall = SyntaxFactory.ParseExpression( + "CollectionsMarshal.AsSpan(" + list.WithoutTrivia().ToFullString() + ")"); - return Task.CompletedTask; + var body = loop.Statement.ReplaceNodes( + reads, + (original, _) => SyntaxFactory.IdentifierName(variableName).WithTriviaFrom(original)); + + var newLoop = SyntaxFactory.ForEachStatement( + SyntaxFactory.IdentifierName("var"), + declaration.Variables[0].Identifier, + asSpanCall, + body); + + var replaced = root.ReplaceNode(loop, newLoop.WithTriviaFrom(loop)); + + var alreadyImported = model.LookupNamespacesAndTypes(loop.SpanStart, name: "CollectionsMarshal").Length > 0; + + var newRoot = alreadyImported ? replaced : UsingDirectives.AddIfMissing(replaced, InteropNamespace); + + return document.WithSyntaxRoot(newRoot); } private static async Task ApplyFixAsync( diff --git a/src/E128.Analyzers.CodeFixers/Performance/ManualSpanSumCodeFixProvider.cs b/src/E128.Analyzers.CodeFixers/Performance/ManualSpanSumCodeFixProvider.cs index 0bd4ed1..20f36a8 100644 --- a/src/E128.Analyzers.CodeFixers/Performance/ManualSpanSumCodeFixProvider.cs +++ b/src/E128.Analyzers.CodeFixers/Performance/ManualSpanSumCodeFixProvider.cs @@ -1,17 +1,21 @@ +using System; +using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; +using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; namespace E128.Analyzers.Performance; /// -/// Code fix for E128135: replaces the sum loop with one -/// TensorPrimitives.Sum call. +/// Code fix for E128135: replaces the reduction loop with one +/// TensorPrimitives call. /// [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(ManualSpanSumCodeFixProvider))] [Shared] @@ -19,9 +23,11 @@ public sealed class ManualSpanSumCodeFixProvider : E128CodeFixProviderBase { private const string TensorsNamespace = "System.Numerics.Tensors"; + /// public override ImmutableArray FixableDiagnosticIds => [ManualSpanSumAnalyzer.DiagnosticId]; + /// protected override Task RegisterFixesAsync(CodeFixContext context, SyntaxNode root) { var loop = root.FindNode(context.Diagnostics[0].Location.SourceSpan, getInnermostNodeForTie: true) @@ -29,16 +35,133 @@ protected override Task RegisterFixesAsync(CodeFixContext context, SyntaxNode ro .OfType() .FirstOrDefault(); - if (loop is null || !ManualSpanSumAnalyzer.TryMatchLoop(loop, out var sumName, out _)) + if (loop is null + || !ManualSpanSumAnalyzer.TryMatchLoop(loop, out var operation, out var accumulatorName, out _)) { return Task.CompletedTask; } + CodeFixRegistration.Register( + context, + context.Diagnostics[0], + "Use TensorPrimitives", + ManualSpanSumAnalyzer.DiagnosticId, + ct => ApplyFixAsync(context.Document, context.Diagnostics[0].Location.SourceSpan, operation, accumulatorName, ct)); + + return Task.CompletedTask; + } + + private static async Task ApplyFixAsync( + Document document, + TextSpan span, + SpanOperation operation, + string accumulatorName, + CancellationToken cancellationToken) + { + var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + var loop = root?.FindNode(span, getInnermostNodeForTie: true) + .AncestorsAndSelf() + .OfType() + .FirstOrDefault(); + + if (root is null || loop is null) + { + return document; + } + + var call = "TensorPrimitives." + MemberName(operation) + "(" + loop.Expression.WithoutTrivia().ToFullString() + ")"; + + if (operation is not SpanOperation.Sum + && loop.Parent is BlockSyntax block + && FindDeclaration(block, loop, accumulatorName) is { } declarator + && ReplaceInitializer(root, block, loop, declarator, call) is { } replacedRoot) + { + return document.WithSyntaxRoot(replacedRoot); + } + var replacement = SyntaxFactory.ParseStatement( - sumName + " += TensorPrimitives.Sum(" + loop.Expression.WithoutTrivia().ToFullString() + ");"); + accumulatorName + (operation is SpanOperation.Sum ? " += " : " = ") + call + ";"); - CodeFixRegistration.Register(context, context.Diagnostics[0], "Use TensorPrimitives.Sum", ManualSpanSumAnalyzer.DiagnosticId, ct => FixSyntax.ReplaceLoopAsync(context.Document, loop, replacement, TensorsNamespace, ct)); + return await FixSyntax.ReplaceLoopAsync( + document, + loop, + replacement, + TensorsNamespace, + cancellationToken).ConfigureAwait(false); + } - return Task.CompletedTask; + private static SyntaxNode? ReplaceInitializer( + SyntaxNode root, + BlockSyntax block, + ForEachStatementSyntax loop, + VariableDeclaratorSyntax declarator, + string call) + { + if (declarator.Initializer is null + || declarator.Parent?.Parent is not LocalDeclarationStatementSyntax declarationStatement) + { + return null; + } + + var initializer = SyntaxFactory.ParseExpression(call).WithTriviaFrom(declarator.Initializer.Value); + var updatedStatement = declarationStatement.ReplaceNode(declarator.Initializer.Value, initializer); + + var statements = new List(block.Statements.Count); + foreach (var statement in block.Statements) + { + if (statement.Span == loop.Span) + { + continue; + } + + statements.Add(statement.Span == declarationStatement.Span ? updatedStatement : statement); + } + + if (statements.Count == block.Statements.Count) + { + return null; + } + + var newBlock = block.WithStatements(SyntaxFactory.List(statements)); + var newRoot = root.ReplaceNode(block, newBlock); + + return UsingDirectives.AddIfMissing(newRoot, TensorsNamespace); + } + + private static VariableDeclaratorSyntax? FindDeclaration( + BlockSyntax block, + ForEachStatementSyntax loop, + string accumulatorName) + { + foreach (var statement in block.Statements) + { + if (statement.SpanStart >= loop.SpanStart) + { + break; + } + + if (statement is LocalDeclarationStatementSyntax declaration) + { + var declarator = declaration.Declaration.Variables + .FirstOrDefault(variable => string.Equals(variable.Identifier.ValueText, accumulatorName, StringComparison.Ordinal)); + + if (declarator is not null) + { + return declarator; + } + } + } + + return null; + } + + private static string MemberName(SpanOperation operation) + { + if (operation is SpanOperation.Max) + { + return "Max"; + } + + return operation is SpanOperation.Min ? "Min" : "Sum"; } } diff --git a/src/E128.Analyzers.CodeFixers/Performance/MiddlewareNextDelegateCodeFixProvider.cs b/src/E128.Analyzers.CodeFixers/Performance/MiddlewareNextDelegateCodeFixProvider.cs new file mode 100644 index 0000000..09c0dd2 --- /dev/null +++ b/src/E128.Analyzers.CodeFixers/Performance/MiddlewareNextDelegateCodeFixProvider.cs @@ -0,0 +1,136 @@ +using System; +using System.Collections.Immutable; +using System.Composition; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace E128.Analyzers.Performance; + +/// +/// Code fix for E128229: changes the next delegate to +/// RequestDelegate and passes the context to every call. +/// +[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(MiddlewareNextDelegateCodeFixProvider))] +[Shared] +public sealed class MiddlewareNextDelegateCodeFixProvider : E128CodeFixProviderBase +{ + private const string HttpNamespace = "Microsoft.AspNetCore.Http"; + + private const int MiddlewareParameterCount = 2; + + /// + public override ImmutableArray FixableDiagnosticIds => + [MiddlewareNextDelegateAnalyzer.DiagnosticId]; + + /// + protected override Task RegisterFixesAsync(CodeFixContext context, SyntaxNode root) + { + var lambda = root.FindNode(context.Diagnostics[0].Location.SourceSpan, getInnermostNodeForTie: true) + .AncestorsAndSelf() + .OfType() + .FirstOrDefault(); + + if (lambda is not { ParameterList.Parameters.Count: MiddlewareParameterCount } + || lambda.ParameterList.Parameters[1].Type is null) + { + return Task.CompletedTask; + } + + var contextName = lambda.ParameterList.Parameters[0].Identifier.ValueText; + var nextName = lambda.ParameterList.Parameters[1].Identifier.ValueText; + + if (string.IsNullOrEmpty(contextName) + || string.IsNullOrEmpty(nextName) + || string.Equals(contextName, "_", StringComparison.Ordinal) + || !MiddlewareNextDelegateAnalyzer.CallsNextWithNoArgument(lambda.Body, contextName, nextName)) + { + return Task.CompletedTask; + } + + CodeFixRegistration.Register( + context, + context.Diagnostics[0], + "Use the RequestDelegate overload", + MiddlewareNextDelegateAnalyzer.DiagnosticId, + ct => ApplyFixAsync(context.Document, lambda, contextName, nextName, ct)); + + return Task.CompletedTask; + } + + private static async Task ApplyFixAsync( + Document document, + ParenthesizedLambdaExpressionSyntax lambda, + string contextName, + string nextName, + CancellationToken cancellationToken) + { + var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + if (root is null) + { + return document; + } + + var replacement = new NextDelegateRewriter(contextName, nextName).Visit(lambda); + + if (replacement is not ParenthesizedLambdaExpressionSyntax rewritten) + { + return document; + } + + var newRoot = UsingDirectives.AddIfMissing( + root.ReplaceNode(lambda, rewritten.WithTriviaFrom(lambda)), + HttpNamespace); + + return document.WithSyntaxRoot(newRoot); + } + + private sealed class NextDelegateRewriter : CSharpSyntaxRewriter + { + private readonly string _contextName; + private readonly string _nextName; + + public NextDelegateRewriter(string contextName, string nextName) + { + _contextName = contextName; + _nextName = nextName; + } + + /// + /// Writes RequestDelegate in the next parameter's type position. + /// + public override SyntaxNode? VisitParameter(ParameterSyntax node) + { + if (string.Equals(node.Identifier.ValueText, _nextName, StringComparison.Ordinal) && node.Type is { } type) + { + return node.WithType( + SyntaxFactory.IdentifierName("RequestDelegate").WithTriviaFrom(type)); + } + + return base.VisitParameter(node); + } + + /// + /// Passes the context to a zero-argument next call. + /// + public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node) + { + var visited = (InvocationExpressionSyntax?)base.VisitInvocationExpression(node); + + if (visited is { Expression: IdentifierNameSyntax { Identifier.ValueText: var name } } + && string.Equals(name, _nextName, StringComparison.Ordinal)) + { + return visited.WithArgumentList( + SyntaxFactory.ArgumentList( + SyntaxFactory.SingletonSeparatedList( + SyntaxFactory.Argument(SyntaxFactory.IdentifierName(_contextName))))); + } + + return visited; + } + } +} diff --git a/src/E128.Analyzers.CodeFixers/Performance/SplitEnumerationCodeFixProvider.cs b/src/E128.Analyzers.CodeFixers/Performance/SplitEnumerationCodeFixProvider.cs new file mode 100644 index 0000000..2654fea --- /dev/null +++ b/src/E128.Analyzers.CodeFixers/Performance/SplitEnumerationCodeFixProvider.cs @@ -0,0 +1,110 @@ +using System.Collections.Immutable; +using System.Composition; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace E128.Analyzers.Performance; + +/// +/// Code fix for E128231: enumerates source.AsSpan().Split(separator) and +/// reads each part as a slice of the span. +/// +[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(SplitEnumerationCodeFixProvider))] +[Shared] +public sealed class SplitEnumerationCodeFixProvider : E128CodeFixProviderBase +{ + private const string SystemNamespace = "System"; + + /// + public override ImmutableArray FixableDiagnosticIds => + [SplitEnumerationAnalyzer.DiagnosticId]; + + /// + protected override async Task RegisterFixesAsync(CodeFixContext context, SyntaxNode root) + { + var loop = root.FindNode(context.Diagnostics[0].Location.SourceSpan, getInnermostNodeForTie: true) + .AncestorsAndSelf() + .OfType() + .FirstOrDefault(); + + if (loop is null) + { + return; + } + + var model = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false); + if (model is null || SplitEnumerationAnalyzer.CreateTerms(model.Compilation) is not { } terms) + { + return; + } + + if (!SplitEnumerationAnalyzer.TryMatch(loop, model, terms, context.CancellationToken, out var receiver, out var separator) + || receiver is null + || separator is null + || !SplitEnumerationAnalyzer.CanRewrite(loop, model, terms, receiver, context.CancellationToken, out var reads)) + { + return; + } + + CodeFixRegistration.Register( + context, + context.Diagnostics[0], + "Enumerate the split ranges over the span", + SplitEnumerationAnalyzer.DiagnosticId, + ct => ApplyFixAsync(context.Document, loop, receiver, separator, reads, ct)); + } + + private static async Task ApplyFixAsync( + Document document, + ForEachStatementSyntax loop, + ExpressionSyntax receiver, + ExpressionSyntax separator, + ImmutableArray reads, + CancellationToken cancellationToken) + { + var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + if (root is null) + { + return document; + } + + var receiverText = receiver.WithoutTrivia().ToFullString(); + var elementText = receiverText + ".AsSpan()[" + loop.Identifier.ValueText + "]"; + + var body = loop.Statement.ReplaceNodes( + reads, + (original, _) => SyntaxFactory.ParseExpression(elementText).WithTriviaFrom(original)); + + var asSpanCall = SyntaxFactory.InvocationExpression( + SyntaxFactory.MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + SyntaxFactory.ParseExpression(receiverText), + SyntaxFactory.IdentifierName("AsSpan"))); + + var splitCall = SyntaxFactory.InvocationExpression( + SyntaxFactory.MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + asSpanCall, + SyntaxFactory.IdentifierName("Split")), + SyntaxFactory.ArgumentList( + SyntaxFactory.SingletonSeparatedList( + SyntaxFactory.Argument(separator.WithoutTrivia())))); + + var newLoop = SyntaxFactory.ForEachStatement( + SyntaxFactory.IdentifierName("var"), + loop.Identifier, + splitCall, + body); + + var newRoot = UsingDirectives.AddIfMissing( + root.ReplaceNode(loop, newLoop.WithTriviaFrom(loop)), + SystemNamespace); + + return document.WithSyntaxRoot(newRoot); + } +} diff --git a/src/E128.Analyzers/AnalyzerReleases.Shipped.md b/src/E128.Analyzers/AnalyzerReleases.Shipped.md index 4bea8ea..60e3e38 100644 --- a/src/E128.Analyzers/AnalyzerReleases.Shipped.md +++ b/src/E128.Analyzers/AnalyzerReleases.Shipped.md @@ -1,3 +1,20 @@ +## Release 3.3.0 + +### New Rules + +Rule ID | Category | Severity | Notes +--------|----------|----------|------ +E128229 | E128-Performance | Warning | Middleware binds the Func next delegate +E128230 | E128-Performance | Warning | Static files served through the runtime pipeline +E128231 | E128-Performance | Warning | Split result enumerated without a stored array + +### Changed Rules + +Rule ID | New Category | New Severity | Old Category | Old Severity | Notes +--------|--------------|--------------|--------------|--------------|------- +E128084 | E128-Performance | Warning | E128-Performance | Warning | Also reports a List indexer loop that reads list[i] +E128135 | E128-Performance | Warning | E128-Performance | Warning | Also reports a min or max loop with a neutral initial value + ## Release 3.2.0 ### New Rules diff --git a/src/E128.Analyzers/E128.Analyzers.csproj b/src/E128.Analyzers/E128.Analyzers.csproj index 63a6ce5..75afefd 100644 --- a/src/E128.Analyzers/E128.Analyzers.csproj +++ b/src/E128.Analyzers/E128.Analyzers.csproj @@ -23,7 +23,7 @@ - 3.2.0 + 3.3.0 true false true diff --git a/src/E128.Analyzers/IndexedForLoop.cs b/src/E128.Analyzers/IndexedForLoop.cs index 4a070c6..82b79a7 100644 --- a/src/E128.Analyzers/IndexedForLoop.cs +++ b/src/E128.Analyzers/IndexedForLoop.cs @@ -16,6 +16,20 @@ internal static bool TryMatch( out string variable, out ExpressionSyntax? boundOwner, out StatementSyntax body) + { + return TryMatch(forStatement, "Length", out variable, out boundOwner, out body); + } + + /// + /// Matches the same shape with a named bound member, such as + /// for (var i = 0; i < list.Count; i++). + /// + internal static bool TryMatch( + ForStatementSyntax forStatement, + string boundMember, + out string variable, + out ExpressionSyntax? boundOwner, + out StatementSyntax body) { variable = string.Empty; boundOwner = null; @@ -29,7 +43,7 @@ internal static bool TryMatch( var declarator = declaration.Variables[0]; if (!IsZeroInitialized(declarator) - || !TryMatchCondition(forStatement, out var conditionName, out var owner) + || !TryMatchCondition(forStatement, boundMember, out var conditionName, out var owner) || !TryGetIncrementedName(forStatement, out var incrementName) || !string.Equals(declarator.Identifier.ValueText, conditionName, StringComparison.Ordinal) || !string.Equals(declarator.Identifier.ValueText, incrementName, StringComparison.Ordinal)) @@ -51,6 +65,7 @@ private static bool IsZeroInitialized(VariableDeclaratorSyntax declarator) private static bool TryMatchCondition( ForStatementSyntax forStatement, + string boundMember, out string conditionName, out ExpressionSyntax? owner) { @@ -59,7 +74,8 @@ private static bool TryMatchCondition( if (forStatement.Condition is not BinaryExpressionSyntax condition || !condition.IsKind(SyntaxKind.LessThanExpression) || condition.Left is not IdentifierNameSyntax conditionVariable - || condition.Right is not MemberAccessExpressionSyntax { Name.Identifier.ValueText: "Length" } length) + || condition.Right is not MemberAccessExpressionSyntax length + || !string.Equals(length.Name.Identifier.ValueText, boundMember, StringComparison.Ordinal)) { return false; } diff --git a/src/E128.Analyzers/Performance/ListGetRangeAnalyzer.cs b/src/E128.Analyzers/Performance/ListGetRangeAnalyzer.cs index 768d5ff..e6fa84d 100644 --- a/src/E128.Analyzers/Performance/ListGetRangeAnalyzer.cs +++ b/src/E128.Analyzers/Performance/ListGetRangeAnalyzer.cs @@ -1,5 +1,7 @@ using System; using System.Collections.Immutable; +using System.Linq; +using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -28,7 +30,17 @@ public sealed class ListGetRangeAnalyzer : DiagnosticAnalyzer "CollectionsMarshal.AsSpan(list).Slice(start, count).ToArray() copies directly from the internal array. " + "The rule skips a call whose result stays a List. The fixed code throws ArgumentOutOfRangeException, not ArgumentException, on a bad range."); - public override ImmutableArray SupportedDiagnostics => [Rule]; + private static readonly DiagnosticDescriptor LoopRule = new( + DiagnosticId, + "Use CollectionsMarshal.AsSpan instead of a List indexer loop", + "The for loop indexes a List and repeats the bounds check per element. Enumerate CollectionsMarshal.AsSpan(list) instead.", + "E128-Performance", + DiagnosticSeverity.Warning, + true, + "CollectionsMarshal.AsSpan returns a span over the internal array with no copy. " + + "The rule stays silent when the loop mutates the list, because the span reads stale memory after a mutation."); + + public override ImmutableArray SupportedDiagnostics => [Rule, LoopRule]; public override void Initialize(AnalysisContext context) { @@ -57,9 +69,200 @@ public override void Initialize(AnalysisContext context) compilationContext.RegisterSyntaxNodeAction( nodeContext => AnalyzeInvocation(nodeContext, listType), SyntaxKind.InvocationExpression); + + compilationContext.RegisterSyntaxNodeAction( + nodeContext => AnalyzeLoop(nodeContext, listType), + SyntaxKind.ForStatement); }); } + private static void AnalyzeLoop(SyntaxNodeAnalysisContext context, INamedTypeSymbol listType) + { + if (!TryMatchIndexerLoop( + (ForStatementSyntax)context.Node, + context.SemanticModel, + listType, + context.CancellationToken, + out _, + out _)) + { + return; + } + + context.ReportDiagnostic(Diagnostic.Create(LoopRule, context.Node.GetLocation())); + } + + /// + /// Matches a for (int i = 0; i < list.Count; i++) loop whose body + /// only reads list[i]. The analyzer and the fix provider call this one + /// helper. + /// + internal static bool TryMatchIndexerLoop( + ForStatementSyntax loop, + SemanticModel model, + INamedTypeSymbol listType, + CancellationToken cancellationToken, + out ExpressionSyntax? list, + out ImmutableArray reads) + { + list = null; + reads = []; + + if (!TryMatchHeader(loop, model, listType, cancellationToken, out var owner, out var declaration) + || owner is null + || declaration is null) + { + return false; + } + + var listSymbol = model.GetSymbolInfo(owner, cancellationToken).Symbol; + var loopVariable = model.GetDeclaredSymbol(declaration.Variables[0], cancellationToken); + + if (listSymbol is not (ILocalSymbol or IParameterSymbol or IFieldSymbol) || loopVariable is null) + { + return false; + } + + if (!TryCollectReads(loop, model, loopVariable, listSymbol, out var builder, cancellationToken)) + { + return false; + } + + if (builder.Count is 0) + { + return false; + } + + list = owner; + reads = builder.ToImmutable(); + return true; + } + + private static bool TryMatchHeader( + ForStatementSyntax loop, + SemanticModel model, + INamedTypeSymbol listType, + CancellationToken cancellationToken, + out ExpressionSyntax? owner, + out VariableDeclarationSyntax? declaration) + { + owner = null; + declaration = null; + + if (loop.Declaration is not { Variables.Count: 1 } variables) + { + return false; + } + + if (!IndexedForLoop.TryMatch(loop, "Count", out _, out var boundOwner, out _) || boundOwner is null) + { + return false; + } + + if (!IsNameChain(boundOwner)) + { + return false; + } + + if (!TypeSymbols.MatchesOriginalDefinition( + model.GetTypeInfo(boundOwner, cancellationToken).Type, + listType)) + { + return false; + } + + owner = boundOwner; + declaration = variables; + return true; + } + + private static bool TryCollectReads( + ForStatementSyntax loop, + SemanticModel model, + ISymbol loopVariable, + ISymbol listSymbol, + out ImmutableArray.Builder builder, + CancellationToken cancellationToken) + { + builder = ImmutableArray.CreateBuilder(); + + foreach (var identifier in loop.Statement.DescendantNodesAndSelf().OfType()) + { + var symbol = model.GetSymbolInfo(identifier, cancellationToken).Symbol; + + if (SymbolEqualityComparer.Default.Equals(symbol, loopVariable)) + { + if (!TryAddElementRead(identifier, model, listSymbol, builder, cancellationToken)) + { + return false; + } + + continue; + } + + if (SymbolEqualityComparer.Default.Equals(symbol, listSymbol) && !IsElementReceiver(identifier)) + { + return false; + } + } + + return true; + } + + private static bool TryAddElementRead( + IdentifierNameSyntax identifier, + SemanticModel model, + ISymbol listSymbol, + ImmutableArray.Builder builder, + CancellationToken cancellationToken) + { + if (identifier.Parent is not ArgumentSyntax argument + || argument.Parent?.Parent is not ElementAccessExpressionSyntax element + || element.ArgumentList.Arguments.Count is not 1 + || element.ArgumentList.Arguments[0].Span != argument.Span + || IsWrite(element)) + { + return false; + } + + if (!SymbolEqualityComparer.Default.Equals( + model.GetSymbolInfo(element.Expression, cancellationToken).Symbol, + listSymbol)) + { + return false; + } + + builder.Add(element); + return true; + } + + private static bool IsElementReceiver(IdentifierNameSyntax identifier) + { + return identifier.Parent is ElementAccessExpressionSyntax element + && element.Expression.Span == identifier.Span; + } + + private static bool IsNameChain(ExpressionSyntax expression) + { + return expression is IdentifierNameSyntax or MemberAccessExpressionSyntax + { + Expression: IdentifierNameSyntax or ThisExpressionSyntax or BaseExpressionSyntax + }; + } + + private static bool IsWrite(ElementAccessExpressionSyntax element) + { + return element.Parent switch + { + AssignmentExpressionSyntax assignment => assignment.Left.Span == element.Span, + PrefixUnaryExpressionSyntax prefix => prefix.Operand.Span == element.Span, + PostfixUnaryExpressionSyntax postfix => postfix.Operand.Span == element.Span, + ArgumentSyntax argument => argument.RefKindKeyword.IsKind(SyntaxKind.RefKeyword) + || argument.RefKindKeyword.IsKind(SyntaxKind.OutKeyword), + _ => false + }; + } + // Returns the member access when the call has the shape x.GetRange(a, b). private static MemberAccessExpressionSyntax? GetRangeAccess(InvocationExpressionSyntax invocation) { diff --git a/src/E128.Analyzers/Performance/ManualSpanSumAnalyzer.cs b/src/E128.Analyzers/Performance/ManualSpanSumAnalyzer.cs index 05f5a8c..de7a2b4 100644 --- a/src/E128.Analyzers/Performance/ManualSpanSumAnalyzer.cs +++ b/src/E128.Analyzers/Performance/ManualSpanSumAnalyzer.cs @@ -9,9 +9,14 @@ namespace E128.Analyzers.Performance; /// -/// E128135: A loop adds the elements of a float or double sequence one at a time. -/// TensorPrimitives.Sum uses the vector path. +/// E128135: A loop reduces the elements of a float or double sequence one at a time. +/// TensorPrimitives uses the vector path. /// +/// +/// The rule covers a sum loop and a min or max loop that keeps a neutral initial value. +/// A minimum or maximum loop whose accumulator starts at any other value keeps a value that +/// TensorPrimitives would replace, so the rule stays silent there. +/// [DiagnosticAnalyzer(LanguageNames.CSharp)] public sealed class ManualSpanSumAnalyzer : DiagnosticAnalyzer { @@ -19,13 +24,13 @@ public sealed class ManualSpanSumAnalyzer : DiagnosticAnalyzer private static readonly DiagnosticDescriptor Rule = new( DiagnosticId, - "Use TensorPrimitives.Sum instead of a sum loop", - "The loop adds the elements one at a time. Use TensorPrimitives.Sum.", + "Use TensorPrimitives instead of a reduction loop", + "The loop reduces the elements one at a time. Use TensorPrimitives.{0}.", "E128-Performance", DiagnosticSeverity.Warning, true, - "TensorPrimitives.Sum reads the span in vector-width blocks. The loop adds one element " + - "per iteration and carries a loop overhead on every step."); + "A TensorPrimitives reduction reads the span in vector-width blocks. The loop reduces one " + + "element per iteration and carries a loop overhead on every step."); public override ImmutableArray SupportedDiagnostics => [Rule]; @@ -59,7 +64,7 @@ public override void Initialize(AnalysisContext context) } var supported = new ITypeSymbol[] { floatType, doubleType } - .Where(type => HasSum(tensors, readOnlySpan.Construct(type))) + .Where(type => HasReduction(tensors, readOnlySpan.Construct(type), "Sum")) .ToImmutableArray(); if (supported.IsEmpty) @@ -67,7 +72,7 @@ public override void Initialize(AnalysisContext context) return; } - var context2 = new SumContext(supported, readOnlySpan, span); + var context2 = new SumContext(supported, tensors, readOnlySpan, span); start.RegisterSyntaxNodeAction( node => Analyze(node, context2), @@ -78,54 +83,310 @@ public override void Initialize(AnalysisContext context) private static void Analyze(SyntaxNodeAnalysisContext context, SumContext sumContext) { if (context.Node is not ForEachStatementSyntax loop - || !TryMatchLoop(loop, out var sumName, out _)) + || !TryMatchLoop(loop, out var operation, out var accumulatorName, out _)) { return; } var model = context.SemanticModel; - if (ManualBitCountAnalyzer.FindType(model, loop, sumName, context.CancellationToken) is not { } sumType - || sumType.SpecialType is not (SpecialType.System_Single or SpecialType.System_Double) - || !sumContext.SupportedTypes.Contains(sumType, SymbolEqualityComparer.Default)) + if (FindAccumulatorType(model, loop, accumulatorName, sumContext, context.CancellationToken) is not { } accumulatorType) { return; } - if (GetElementType(model, loop.Expression, sumContext, context.CancellationToken) is not { } elementType - || !SymbolEqualityComparer.Default.Equals(elementType, sumType)) + if (operation is not SpanOperation.Sum + && (!HasReduction(sumContext.Tensors, sumContext.ReadOnlySpan.Construct(accumulatorType), OperationName(operation)) + || !HasNeutralInitializer(loop, accumulatorName, accumulatorType, operation, model, context.CancellationToken))) { return; } - context.ReportDiagnostic(Diagnostic.Create(Rule, loop.GetLocation())); + context.ReportDiagnostic(Diagnostic.Create(Rule, loop.GetLocation(), OperationName(operation))); + } + + private static ITypeSymbol? FindAccumulatorType( + SemanticModel model, + ForEachStatementSyntax loop, + string accumulatorName, + SumContext sumContext, + System.Threading.CancellationToken cancellationToken) + { + if (ManualBitCountAnalyzer.FindType(model, loop, accumulatorName, cancellationToken) is not { } accumulatorType) + { + return null; + } + + if (accumulatorType.SpecialType is not (SpecialType.System_Single or SpecialType.System_Double)) + { + return null; + } + + if (!sumContext.SupportedTypes.Contains(accumulatorType, SymbolEqualityComparer.Default)) + { + return null; + } + + return GetElementType(model, loop.Expression, sumContext, cancellationToken) is { } elementType + && SymbolEqualityComparer.Default.Equals(elementType, accumulatorType) + ? accumulatorType + : null; } /// - /// Matches a foreach loop whose whole body adds the element to a local. The analyzer and + /// Matches a foreach loop whose whole body reduces the element into a local. The analyzer and /// the fix provider call this one helper. /// - internal static bool TryMatchLoop(ForEachStatementSyntax loop, out string sumName, out string valueName) + internal static bool TryMatchLoop( + ForEachStatementSyntax loop, + out SpanOperation operation, + out string accumulatorName, + out string valueName) { - sumName = string.Empty; + operation = SpanOperation.Sum; + accumulatorName = string.Empty; valueName = loop.Identifier.ValueText; - if (loop.Statement is not BlockSyntax body - || body.Statements.Count is not 1 - || body.Statements[0] is not ExpressionStatementSyntax statement - || statement.Expression is not AssignmentExpressionSyntax add - || !add.IsKind(SyntaxKind.AddAssignmentExpression) - || add.Left is not IdentifierNameSyntax sum - || add.Right is not IdentifierNameSyntax value - || !string.Equals(value.Identifier.ValueText, valueName, StringComparison.Ordinal)) + if (TryMatchSum(loop.Statement, valueName, out accumulatorName)) + { + return true; + } + + if (TryMatchMinOrMax(loop.Statement, valueName, out operation, out accumulatorName)) + { + return true; + } + + operation = SpanOperation.Sum; + return false; + } + + private static bool TryMatchSum(StatementSyntax statement, string valueName, out string accumulatorName) + { + accumulatorName = string.Empty; + statement = UnwrapSingleStatement(statement); + + if (statement is not ExpressionStatementSyntax expression) + { + return false; + } + + if (expression.Expression is not AssignmentExpressionSyntax add + || !add.IsKind(SyntaxKind.AddAssignmentExpression)) + { + return false; + } + + if (add.Left is not IdentifierNameSyntax accumulator || add.Right is not IdentifierNameSyntax value) + { + return false; + } + + if (!string.Equals(value.Identifier.ValueText, valueName, StringComparison.Ordinal)) + { + return false; + } + + accumulatorName = accumulator.Identifier.ValueText; + return true; + } + + private static bool TryMatchMinOrMax( + StatementSyntax statement, + string valueName, + out SpanOperation operation, + out string accumulatorName) + { + operation = SpanOperation.Sum; + accumulatorName = string.Empty; + statement = UnwrapSingleStatement(statement); + + if (statement is not IfStatementSyntax { Else: null } conditional) + { + return false; + } + + if (conditional.Condition is not BinaryExpressionSyntax comparison + || comparison.Right is not IdentifierNameSyntax comparedAccumulator) + { + return false; + } + + if (!IsValueOperand(comparison.Left, valueName) || !TryGetOperation(comparison, out operation)) + { + return false; + } + + if (!TryGetAssignment(conditional.Statement, out var writtenAccumulator, out var writtenValue)) + { + return false; + } + + if (!string.Equals(writtenAccumulator, comparedAccumulator.Identifier.ValueText, StringComparison.Ordinal) + || !string.Equals(writtenValue, valueName, StringComparison.Ordinal)) + { + return false; + } + + accumulatorName = comparedAccumulator.Identifier.ValueText; + return true; + } + + private static StatementSyntax UnwrapSingleStatement(StatementSyntax statement) + { + return statement is BlockSyntax { Statements.Count: 1 } block ? block.Statements[0] : statement; + } + + private static bool IsValueOperand(ExpressionSyntax expression, string valueName) + { + return expression is IdentifierNameSyntax identifier + && string.Equals(identifier.Identifier.ValueText, valueName, StringComparison.Ordinal); + } + + private static bool TryGetOperation(BinaryExpressionSyntax comparison, out SpanOperation operation) + { + if (comparison.IsKind(SyntaxKind.GreaterThanExpression)) + { + operation = SpanOperation.Max; + return true; + } + + if (comparison.IsKind(SyntaxKind.LessThanExpression)) + { + operation = SpanOperation.Min; + return true; + } + + operation = SpanOperation.Sum; + return false; + } + + private static bool TryGetAssignment(StatementSyntax statement, out string accumulatorName, out string valueName) + { + accumulatorName = string.Empty; + valueName = string.Empty; + statement = UnwrapSingleStatement(statement); + + if (statement is not ExpressionStatementSyntax expression + || expression.Expression is not AssignmentExpressionSyntax write) { return false; } - sumName = sum.Identifier.ValueText; + if (write.Left is not IdentifierNameSyntax accumulator || write.Right is not IdentifierNameSyntax value) + { + return false; + } + + accumulatorName = accumulator.Identifier.ValueText; + valueName = value.Identifier.ValueText; return true; } + private static string OperationName(SpanOperation operation) + { + if (operation is SpanOperation.Max) + { + return "Max"; + } + + return operation is SpanOperation.Min ? "Min" : "Sum"; + } + + /// + /// True when the accumulator starts at the value that the reduction leaves unchanged, so + /// the vector call computes the same result as the loop. + /// + private static bool HasNeutralInitializer( + ForEachStatementSyntax loop, + string accumulatorName, + ITypeSymbol accumulatorType, + SpanOperation operation, + SemanticModel model, + System.Threading.CancellationToken cancellationToken) + { + if (loop.Parent is not BlockSyntax block) + { + return false; + } + + for (var i = block.Statements.IndexOf(loop) - 1; i >= 0; i--) + { + var statement = block.Statements[i]; + + if (statement is LocalDeclarationStatementSyntax declaration + && FindDeclarator(declaration, accumulatorName) is { } declarator) + { + return IsNeutralValue(declarator, accumulatorType, operation, model, cancellationToken); + } + + if (WritesTo(statement, accumulatorName)) + { + return false; + } + } + + return false; + } + + private static bool IsNeutralValue( + VariableDeclaratorSyntax declarator, + ITypeSymbol accumulatorType, + SpanOperation operation, + SemanticModel model, + System.Threading.CancellationToken cancellationToken) + { + if (declarator.Initializer?.Value is not { } initializer) + { + return false; + } + + var expectedField = operation is SpanOperation.Max ? "MinValue" : "MaxValue"; + + return model.GetSymbolInfo(initializer, cancellationToken).Symbol is IFieldSymbol field + && string.Equals(field.Name, expectedField, StringComparison.Ordinal) + && SymbolEqualityComparer.Default.Equals(field.ContainingType, accumulatorType); + } + + private static VariableDeclaratorSyntax? FindDeclarator( + LocalDeclarationStatementSyntax declaration, + string name) + { + return declaration.Declaration.Variables + .FirstOrDefault(variable => string.Equals(variable.Identifier.ValueText, name, StringComparison.Ordinal)); + } + + private static bool WritesTo(StatementSyntax statement, string name) + { + foreach (var identifier in statement.DescendantNodesAndSelf().OfType()) + { + if (!string.Equals(identifier.Identifier.ValueText, name, StringComparison.Ordinal)) + { + continue; + } + + if (IsWriteTarget(identifier)) + { + return true; + } + } + + return false; + } + + private static bool IsWriteTarget(IdentifierNameSyntax identifier) + { + return identifier.Parent switch + { + AssignmentExpressionSyntax assignment => assignment.Left == identifier, + PrefixUnaryExpressionSyntax prefix => prefix.Operand == identifier, + PostfixUnaryExpressionSyntax postfix => postfix.Operand == identifier, + ArgumentSyntax argument => argument.RefKindKeyword.IsKind(SyntaxKind.RefKeyword) + || argument.RefKindKeyword.IsKind(SyntaxKind.OutKeyword), + _ => false + }; + } + internal static ITypeSymbol? GetElementType( SemanticModel model, ExpressionSyntax expression, @@ -143,9 +404,9 @@ when TypeSymbols.MatchesOriginalDefinition(named, sumContext.ReadOnlySpan) }; } - private static bool HasSum(INamedTypeSymbol tensors, INamedTypeSymbol spanType) + private static bool HasReduction(INamedTypeSymbol tensors, INamedTypeSymbol spanType, string name) { - return tensors.GetMembers("Sum") + return tensors.GetMembers(name) .OfType() .Any(method => method.Parameters.Length is 1 && SymbolEqualityComparer.Default.Equals(method.Parameters[0].Type, spanType)); @@ -155,16 +416,20 @@ internal sealed class SumContext { public SumContext( ImmutableArray supportedTypes, + INamedTypeSymbol tensors, INamedTypeSymbol readOnlySpan, INamedTypeSymbol span) { SupportedTypes = supportedTypes; + Tensors = tensors; ReadOnlySpan = readOnlySpan; Span = span; } public ImmutableArray SupportedTypes { get; } + public INamedTypeSymbol Tensors { get; } + public INamedTypeSymbol ReadOnlySpan { get; } public INamedTypeSymbol Span { get; } diff --git a/src/E128.Analyzers/Performance/MiddlewareNextDelegateAnalyzer.cs b/src/E128.Analyzers/Performance/MiddlewareNextDelegateAnalyzer.cs new file mode 100644 index 0000000..b75ea9a --- /dev/null +++ b/src/E128.Analyzers/Performance/MiddlewareNextDelegateAnalyzer.cs @@ -0,0 +1,271 @@ +using System; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Diagnostics; + +namespace E128.Analyzers.Performance; + +/// +/// E128229: An inline Use middleware takes a +/// Func<Task> next delegate, so every request allocates one closure. +/// +/// +/// The Func<HttpContext, Func<Task>, Task> overload wraps the +/// next delegate in a new Func<Task> closure on every request. The +/// Func<HttpContext, RequestDelegate, Task> overload passes the same +/// RequestDelegate with no allocation. The rule reports the second +/// parameter only when the lambda calls next() with no argument and never +/// reassigns the context parameter, so the fix can rewrite both sites. +/// +[DiagnosticAnalyzer(LanguageNames.CSharp)] +public sealed class MiddlewareNextDelegateAnalyzer : DiagnosticAnalyzer +{ + internal const string DiagnosticId = "E128229"; + + private const string ApplicationBuilderTypeName = "Microsoft.AspNetCore.Builder.IApplicationBuilder"; + + private const string UseMiddlewareExtensionsTypeName = "Microsoft.AspNetCore.Builder.UseMiddlewareExtensions"; + + private const string HttpContextTypeName = "Microsoft.AspNetCore.Http.HttpContext"; + + private const string RequestDelegateTypeName = "Microsoft.AspNetCore.Http.RequestDelegate"; + + private const string TaskTypeName = "System.Threading.Tasks.Task"; + + private const int MiddlewareParameterCount = 2; + + private const int MiddlewareDelegateArity = 3; + + private const int FuncOfTaskArity = 1; + + private const int ReturnTypeArgumentIndex = 2; + + private static readonly DiagnosticDescriptor Rule = new( + DiagnosticId, + "Middleware binds the Func next delegate", + "This overload allocates one Func closure per request. Use the RequestDelegate overload and call next(context).", + "E128-Performance", + DiagnosticSeverity.Warning, + true, + "The Func overload allocates no per-request closure. " + + "Change the parameter type to RequestDelegate and pass the context to next."); + + /// + public override ImmutableArray SupportedDiagnostics => [Rule]; + + /// + public override void Initialize(AnalysisContext context) + { + if (context is null) + { + throw new ArgumentNullException(nameof(context)); + } + + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); + context.EnableConcurrentExecution(); + + context.RegisterCompilationStartAction(static start => + { + var compilation = start.Compilation; + var applicationBuilder = compilation.GetTypeByMetadataName(ApplicationBuilderTypeName); + var useExtensions = compilation.GetTypeByMetadataName(UseMiddlewareExtensionsTypeName); + var httpContext = compilation.GetTypeByMetadataName(HttpContextTypeName); + var requestDelegate = compilation.GetTypeByMetadataName(RequestDelegateTypeName); + var task = compilation.GetTypeByMetadataName(TaskTypeName); + var func1 = compilation.GetTypeByMetadataName("System.Func`1"); + var func3 = compilation.GetTypeByMetadataName("System.Func`3"); + + if (applicationBuilder is null + || httpContext is null + || requestDelegate is null + || task is null + || func1 is null + || func3 is null) + { + return; + } + + var middleware = new MiddlewareContext(applicationBuilder, useExtensions, httpContext, func1, func3, task); + + start.RegisterSyntaxNodeAction(nodeContext => Analyze(nodeContext, middleware), SyntaxKind.InvocationExpression); + }); + } + + private static void Analyze(SyntaxNodeAnalysisContext context, MiddlewareContext middleware) + { + var invocation = (InvocationExpressionSyntax)context.Node; + + if (FindMiddlewareLambda(invocation, context, middleware) is not { } lambda + || !TryGetParameterNames(lambda, out var contextName, out var nextName, out var nextType) + || nextType is null + || !CallsNextWithNoArgument(lambda.Body, contextName, nextName)) + { + return; + } + + context.ReportDiagnostic(Diagnostic.Create(Rule, nextType.GetLocation())); + } + + private static ParenthesizedLambdaExpressionSyntax? FindMiddlewareLambda( + InvocationExpressionSyntax invocation, + SyntaxNodeAnalysisContext context, + MiddlewareContext middleware) + { + if (invocation.ArgumentList.Arguments.Count is not 1 + || invocation.ArgumentList.Arguments[0].Expression is not ParenthesizedLambdaExpressionSyntax lambda + || lambda.ParameterList.Parameters.Count is not MiddlewareParameterCount) + { + return null; + } + + if (context.SemanticModel.GetSymbolInfo(invocation, context.CancellationToken).Symbol is not IMethodSymbol method + || !IsApplicationBuilderUse(method, middleware) + || method.Parameters.Length is not 1 + || method.Parameters[0].Type is not INamedTypeSymbol delegateType + || !IsFuncTaskDelegate(delegateType, middleware)) + { + return null; + } + + return lambda; + } + + private static bool TryGetParameterNames( + ParenthesizedLambdaExpressionSyntax lambda, + out string contextName, + out string nextName, + out TypeSyntax? nextType) + { + var nextParameter = lambda.ParameterList.Parameters[1]; + nextType = nextParameter.Type; + contextName = lambda.ParameterList.Parameters[0].Identifier.ValueText; + nextName = nextParameter.Identifier.ValueText; + + return nextType is not null + && !string.IsNullOrEmpty(contextName) + && !string.IsNullOrEmpty(nextName) + && !string.Equals(contextName, "_", StringComparison.Ordinal); + } + + private static bool IsApplicationBuilderUse(IMethodSymbol method, MiddlewareContext middleware) + { + return string.Equals(method.Name, "Use", StringComparison.Ordinal) + && (TypeSymbols.Matches(method.ContainingType, middleware.ApplicationBuilder) + || TypeSymbols.Matches(method.ContainingType, middleware.UseExtensions)); + } + + private static bool IsFuncTaskDelegate(INamedTypeSymbol delegateType, MiddlewareContext middleware) + { + return TypeSymbols.MatchesOriginalDefinition(delegateType, middleware.Func3) + && delegateType.TypeArguments.Length is MiddlewareDelegateArity + && SymbolEqualityComparer.Default.Equals(delegateType.TypeArguments[0], middleware.HttpContext) + && IsFuncTask(delegateType.TypeArguments[1], middleware) + && SymbolEqualityComparer.Default.Equals( + delegateType.TypeArguments[ReturnTypeArgumentIndex], + middleware.Task); + } + + private static bool IsFuncTask(ITypeSymbol? type, MiddlewareContext middleware) + { + return type is INamedTypeSymbol { TypeArguments.Length: FuncOfTaskArity } named + && TypeSymbols.MatchesOriginalDefinition(named, middleware.Func1) + && SymbolEqualityComparer.Default.Equals(named.TypeArguments[0], middleware.Task); + } + + /// + /// True when every use of the next delegate is a call with no argument, at least one such + /// call exists, and the context parameter carries no assignment. + /// + internal static bool CallsNextWithNoArgument(SyntaxNode body, string contextName, string nextName) + { + var calls = 0; + + foreach (var node in body.DescendantNodes()) + { + if (node is not IdentifierNameSyntax identifier) + { + continue; + } + + if (IsNamed(identifier, contextName)) + { + if (IsWriteTarget(identifier)) + { + return false; + } + + continue; + } + + if (!IsNamed(identifier, nextName)) + { + continue; + } + + if (identifier.Parent is InvocationExpressionSyntax call + && call.Expression == identifier + && call.ArgumentList.Arguments.Count is 0) + { + calls++; + continue; + } + + return false; + } + + return calls > 0; + } + + internal static bool IsWriteTarget(IdentifierNameSyntax identifier) + { + return identifier.Parent switch + { + AssignmentExpressionSyntax assignment => assignment.Left == identifier, + PrefixUnaryExpressionSyntax prefix => prefix.Operand == identifier + && (prefix.IsKind(SyntaxKind.PreIncrementExpression) + || prefix.IsKind(SyntaxKind.PreDecrementExpression)), + PostfixUnaryExpressionSyntax postfix => postfix.Operand == identifier, + ArgumentSyntax argument => argument.RefKindKeyword.IsKind(SyntaxKind.RefKeyword) + || argument.RefKindKeyword.IsKind(SyntaxKind.OutKeyword), + _ => false + }; + } + + private static bool IsNamed(IdentifierNameSyntax identifier, string name) + { + return string.Equals(identifier.Identifier.ValueText, name, StringComparison.Ordinal); + } + + internal sealed class MiddlewareContext + { + public MiddlewareContext( + INamedTypeSymbol applicationBuilder, + INamedTypeSymbol? useExtensions, + INamedTypeSymbol httpContext, + INamedTypeSymbol func1, + INamedTypeSymbol func3, + INamedTypeSymbol task) + { + ApplicationBuilder = applicationBuilder; + UseExtensions = useExtensions; + HttpContext = httpContext; + Func1 = func1; + Func3 = func3; + Task = task; + } + + public INamedTypeSymbol ApplicationBuilder { get; } + + public INamedTypeSymbol? UseExtensions { get; } + + public INamedTypeSymbol HttpContext { get; } + + public INamedTypeSymbol Func1 { get; } + + public INamedTypeSymbol Func3 { get; } + + public INamedTypeSymbol Task { get; } + } +} diff --git a/src/E128.Analyzers/Performance/RuntimeStaticFilesAnalyzer.cs b/src/E128.Analyzers/Performance/RuntimeStaticFilesAnalyzer.cs new file mode 100644 index 0000000..a8f0e69 --- /dev/null +++ b/src/E128.Analyzers/Performance/RuntimeStaticFilesAnalyzer.cs @@ -0,0 +1,101 @@ +using System; +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Diagnostics; + +namespace E128.Analyzers.Performance; + +/// +/// E128230: A minimal API app serves static files through the request-time middleware with +/// UseStaticFiles. MapStaticAssets serves a +/// build-time manifest instead. +/// +/// +/// The rule registers only when the compilation can bind MapStaticAssets, +/// so a target framework without the endpoint mapping API gets no report. The rewrite moves the +/// call into the endpoint mapping section, and a Razor app also changes how it references the +/// assets, so the rule carries no code fix. +/// +[DiagnosticAnalyzer(LanguageNames.CSharp)] +public sealed class RuntimeStaticFilesAnalyzer : DiagnosticAnalyzer +{ + internal const string DiagnosticId = "E128230"; + + private const string StaticFileExtensionsTypeName = "Microsoft.AspNetCore.Builder.StaticFileExtensions"; + + private const string StaticAssetsExtensionsTypeName = "Microsoft.AspNetCore.Builder.StaticAssetsEndpointRouteBuilderExtensions"; + + private const string UseStaticFilesName = "UseStaticFiles"; + + private const string MapStaticAssetsName = "MapStaticAssets"; + + private static readonly DiagnosticDescriptor Rule = new( + DiagnosticId, + "Static files served through the runtime pipeline", + "UseStaticFiles runs a request-time middleware. MapStaticAssets serves the build-time asset manifest with precompressed variants and ETags.", + "E128-Performance", + DiagnosticSeverity.Warning, + true, + "MapStaticAssets serves the assets from a build-time manifest. " + + "Move the call into the endpoint mapping section and let the manifest publish the assets."); + + /// + public override ImmutableArray SupportedDiagnostics => [Rule]; + + /// + public override void Initialize(AnalysisContext context) + { + if (context is null) + { + throw new ArgumentNullException(nameof(context)); + } + + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); + context.EnableConcurrentExecution(); + + context.RegisterCompilationStartAction(static start => + { + var compilation = start.Compilation; + var staticFiles = compilation.GetTypeByMetadataName(StaticFileExtensionsTypeName); + var staticAssets = compilation.GetTypeByMetadataName(StaticAssetsExtensionsTypeName); + + if (staticFiles is null + || staticAssets is null + || !HasMapStaticAssets(staticAssets)) + { + return; + } + + start.RegisterSyntaxNodeAction(nodeContext => Analyze(nodeContext, staticFiles), SyntaxKind.InvocationExpression); + }); + } + + private static bool HasMapStaticAssets(INamedTypeSymbol staticAssets) + { + return staticAssets.GetMembers(MapStaticAssetsName) + .OfType() + .Any(static method => method.IsExtensionMethod); + } + + private static void Analyze(SyntaxNodeAnalysisContext context, INamedTypeSymbol staticFiles) + { + var invocation = (InvocationExpressionSyntax)context.Node; + + if (invocation.ArgumentList.Arguments.Count is not 0) + { + return; + } + + if (context.SemanticModel.GetSymbolInfo(invocation, context.CancellationToken).Symbol is not IMethodSymbol method + || !string.Equals(method.Name, UseStaticFilesName, StringComparison.Ordinal) + || !TypeSymbols.Matches(method.ContainingType, staticFiles)) + { + return; + } + + context.ReportDiagnostic(Diagnostic.Create(Rule, invocation.GetLocation())); + } +} diff --git a/src/E128.Analyzers/Performance/SpanOperation.cs b/src/E128.Analyzers/Performance/SpanOperation.cs new file mode 100644 index 0000000..c62ce41 --- /dev/null +++ b/src/E128.Analyzers/Performance/SpanOperation.cs @@ -0,0 +1,14 @@ +namespace E128.Analyzers.Performance; + +/// +/// The reduction that an E128135 loop performs. The fix provider selects the TensorPrimitives +/// member from this value. +/// +internal enum SpanOperation +{ + Sum = 0, + + Max = 1, + + Min = 2 +} diff --git a/src/E128.Analyzers/Performance/SplitEnumerationAnalyzer.cs b/src/E128.Analyzers/Performance/SplitEnumerationAnalyzer.cs new file mode 100644 index 0000000..f514ae4 --- /dev/null +++ b/src/E128.Analyzers/Performance/SplitEnumerationAnalyzer.cs @@ -0,0 +1,340 @@ +using System; +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Diagnostics; + +namespace E128.Analyzers.Performance; + +/// +/// E128231: A string.Split result that only a +/// foreach enumerates allocates one array and one string per part. +/// +/// +/// MemoryExtensions.Split yields Range values over +/// the source string with no array and no part strings. The rule reports the loop and the code +/// fix applies only when every use of the part accepts a span, so a loop that stores a part as +/// a string reports with no fix. +/// +[DiagnosticAnalyzer(LanguageNames.CSharp)] +public sealed class SplitEnumerationAnalyzer : DiagnosticAnalyzer +{ + internal const string DiagnosticId = "E128231"; + + private const string StringTypeName = "System.String"; + + private const string MemoryExtensionsTypeName = "System.MemoryExtensions"; + + private const string ReadOnlySpanTypeName = "System.ReadOnlySpan`1"; + + private const string StringSplitOptionsTypeName = "System.StringSplitOptions"; + + private const string SplitName = "Split"; + + private const int SplitParameterCount = 2; + + private const int SeparatorArgumentCount = 1; + + private static readonly DiagnosticDescriptor Rule = new( + DiagnosticId, + "Split result enumerated without a stored array", + "The foreach enumerates a string.Split result. MemoryExtensions.Split yields range values over the same string with no array or part strings.", + "E128-Performance", + DiagnosticSeverity.Warning, + true, + "Enumerate source.AsSpan().Split(separator) and read each part as a slice of the span. " + + "The fix applies only when every use of the part accepts a span."); + + /// + public override ImmutableArray SupportedDiagnostics => [Rule]; + + /// + public override void Initialize(AnalysisContext context) + { + if (context is null) + { + throw new ArgumentNullException(nameof(context)); + } + + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); + context.EnableConcurrentExecution(); + + context.RegisterCompilationStartAction(static start => + { + if (CreateTerms(start.Compilation) is not { } terms) + { + return; + } + + start.RegisterSyntaxNodeAction( + nodeContext => Analyze(nodeContext, terms), + SyntaxKind.ForEachStatement); + }); + } + + /// + /// Resolves the types that a match needs. Returns null when the compilation has no + /// MemoryExtensions.Split remedy. + /// + internal static SplitTerms? CreateTerms(Compilation compilation) + { + var stringType = compilation.GetTypeByMetadataName(StringTypeName); + var memoryExtensions = compilation.GetTypeByMetadataName(MemoryExtensionsTypeName); + var readOnlySpan = compilation.GetTypeByMetadataName(ReadOnlySpanTypeName); + var optionsType = compilation.GetTypeByMetadataName(StringSplitOptionsTypeName); + var rangeType = compilation.GetTypeByMetadataName("System.Range"); + + if (stringType is null + || memoryExtensions is null + || readOnlySpan is null + || optionsType is null + || rangeType is null) + { + return null; + } + + return HasSpanSplit(memoryExtensions, readOnlySpan) + ? new SplitTerms(stringType, optionsType, rangeType) + : null; + } + + private static bool HasSpanSplit(INamedTypeSymbol memoryExtensions, INamedTypeSymbol readOnlySpan) + { + return memoryExtensions.GetMembers(SplitName) + .OfType() + .Any(method => method.IsExtensionMethod + && method.Parameters.Length is SplitParameterCount + && TypeSymbols.MatchesOriginalDefinition(method.Parameters[0].Type, readOnlySpan)); + } + + private static void Analyze(SyntaxNodeAnalysisContext context, SplitTerms terms) + { + var loop = (ForEachStatementSyntax)context.Node; + + if (!TryMatch(loop, context.SemanticModel, terms, context.CancellationToken, out _, out _)) + { + return; + } + + context.ReportDiagnostic(Diagnostic.Create(Rule, loop.GetLocation())); + } + + /// + /// Matches a foreach over a string.Split result with a + /// char or constant-string separator and no split options. + /// + internal static bool TryMatch( + ForEachStatementSyntax loop, + SemanticModel model, + SplitTerms terms, + CancellationToken cancellationToken, + out ExpressionSyntax? receiver, + out ExpressionSyntax? separator) + { + receiver = null; + separator = null; + + if (!IsStringElement(loop.Type, model, terms, cancellationToken)) + { + return false; + } + + if (loop.Expression is not InvocationExpressionSyntax invocation + || invocation.Expression is not MemberAccessExpressionSyntax access + || !string.Equals(access.Name.Identifier.ValueText, SplitName, StringComparison.Ordinal)) + { + return false; + } + + if (invocation.ArgumentList.Arguments.Count is not SeparatorArgumentCount) + { + return false; + } + + if (model.GetSymbolInfo(invocation, cancellationToken).Symbol is not IMethodSymbol method + || !IsSingleArgumentSplit(method, terms)) + { + return false; + } + + var separatorArgument = invocation.ArgumentList.Arguments[0].Expression; + + if (!IsSupportedSeparator(method.Parameters[0].Type, separatorArgument, model, cancellationToken)) + { + return false; + } + + receiver = access.Expression; + separator = separatorArgument; + return true; + } + + private static bool IsSingleArgumentSplit(IMethodSymbol method, SplitTerms terms) + { + return TypeSymbols.Matches(method.ContainingType, terms.StringType) + && method.Parameters.Length is SplitParameterCount + && TypeSymbols.Matches(method.Parameters[1].Type, terms.OptionsType) + && method.Parameters[1].ExplicitDefaultValue is 0; + } + + private static bool IsSupportedSeparator( + ITypeSymbol parameterType, + ExpressionSyntax separatorArgument, + SemanticModel model, + CancellationToken cancellationToken) + { + if (parameterType.SpecialType is SpecialType.System_Char) + { + return true; + } + + if (parameterType.SpecialType is not SpecialType.System_String) + { + return false; + } + + var constant = model.GetConstantValue(separatorArgument, cancellationToken); + + return constant.HasValue && constant.Value is string; + } + + private static bool IsStringElement( + ExpressionSyntax type, + SemanticModel model, + SplitTerms terms, + CancellationToken cancellationToken) + { + if (type is IdentifierNameSyntax identifier + && string.Equals(identifier.Identifier.ValueText, "var", StringComparison.Ordinal)) + { + return true; + } + + return TypeSymbols.Matches(model.GetTypeInfo(type, cancellationToken).Type, terms.StringType); + } + + /// + /// True when the receiver is a name chain, so the fix can repeat it without a second call. + /// + internal static bool IsStableReceiver(ExpressionSyntax receiver) + { + return receiver switch + { + IdentifierNameSyntax => true, + MemberAccessExpressionSyntax access => access.Expression + is IdentifierNameSyntax or ThisExpressionSyntax or BaseExpressionSyntax, + _ => false + }; + } + + /// + /// Collects every read of the loop variable and checks that the rewrite keeps its meaning. + /// + internal static bool CanRewrite( + ForEachStatementSyntax loop, + SemanticModel model, + SplitTerms terms, + ExpressionSyntax receiver, + CancellationToken cancellationToken, + out ImmutableArray reads) + { + reads = []; + + if (!IsStableReceiver(receiver) + || model.GetDeclaredSymbol(loop, cancellationToken) is not ILocalSymbol variable + || model.GetSymbolInfo(receiver, cancellationToken).Symbol is not (ILocalSymbol or IParameterSymbol or IFieldSymbol)) + { + return false; + } + + var builder = ImmutableArray.CreateBuilder(); + + foreach (var identifier in loop.Statement.DescendantNodesAndSelf().OfType()) + { + if (!string.Equals(identifier.Identifier.ValueText, loop.Identifier.ValueText, StringComparison.Ordinal)) + { + continue; + } + + if (!SymbolEqualityComparer.Default.Equals( + model.GetSymbolInfo(identifier, cancellationToken).Symbol, + variable)) + { + continue; + } + + if (!IsEligibleUse(identifier, model, terms, cancellationToken)) + { + return false; + } + + builder.Add(identifier); + } + + reads = builder.ToImmutable(); + return true; + } + + private static bool IsEligibleUse( + IdentifierNameSyntax identifier, + SemanticModel model, + SplitTerms terms, + CancellationToken cancellationToken) + { + switch (identifier.Parent) + { + case MemberAccessExpressionSyntax access when access.Expression.Span == identifier.Span: + return string.Equals(access.Name.Identifier.ValueText, "Length", StringComparison.Ordinal); + + case ElementAccessExpressionSyntax element when element.Expression.Span == identifier.Span: + return element.ArgumentList.Arguments.Count is 1 + && !TypeSymbols.Matches( + model.GetTypeInfo(element.ArgumentList.Arguments[0].Expression, cancellationToken).Type, + terms.RangeType); + + case BinaryExpressionSyntax comparison + when comparison.IsKind(SyntaxKind.EqualsExpression) || comparison.IsKind(SyntaxKind.NotEqualsExpression): + return ComparesWithString(comparison, identifier, model, cancellationToken); + + default: + return false; + } + } + + private static bool ComparesWithString( + BinaryExpressionSyntax comparison, + IdentifierNameSyntax identifier, + SemanticModel model, + CancellationToken cancellationToken) + { + var other = comparison.Left.Span == identifier.Span ? comparison.Right : comparison.Left; + var constant = model.GetConstantValue(other, cancellationToken); + + return constant.HasValue && constant.Value is string; + } + + /// + /// The resolved types that one match needs. + /// + internal sealed class SplitTerms + { + public SplitTerms( + INamedTypeSymbol stringType, + INamedTypeSymbol optionsType, + INamedTypeSymbol rangeType) + { + StringType = stringType; + OptionsType = optionsType; + RangeType = rangeType; + } + + public INamedTypeSymbol StringType { get; } + + public INamedTypeSymbol OptionsType { get; } + + public INamedTypeSymbol RangeType { get; } + } +} diff --git a/src/E128.Analyzers/README.md b/src/E128.Analyzers/README.md index 94811e1..7bab52c 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. @@ -157,7 +157,7 @@ All rules default to **Warning** severity unless noted. Every rule includes a co | E128072 | Prefer `SHA256.HashData()` over `SHA256.Create()` (default: Info) | Yes | | E128081 | Use `StringBuilderPool` instead of `new StringBuilder()` (default: Info) | Yes | | E128083 | Use `ImmutableCollectionsMarshal.AsImmutableArray` instead of `ImmutableArray.Create/CreateRange` with `ToArray` | Yes | -| E128084 | Use `CollectionsMarshal.AsSpan` with `Slice` instead of `List.GetRange` | Yes | +| E128084 | Use `CollectionsMarshal.AsSpan` instead of `List.GetRange` or a list indexer loop | Yes | | E128085 | Use `foreach` + `AddRange` instead of `SelectMany.ToList` | Yes | | E128098 | Collapse chained or looped `string.Replace` calls into a single pass | Yes | | E128102 | Use `SearchValues` for `IndexOfAny` scans | Yes | @@ -172,7 +172,7 @@ All rules default to **Warning** severity unless noted. Every rule includes a co | E128132 | Do not use a culture-aware comparer for a collection key | Yes | | E128133 | Use an alternate lookup instead of a temporary string key | Yes | | E128134 | Use `BitOperations.PopCount` instead of a shift loop | Yes | -| E128135 | Use `TensorPrimitives.Sum` instead of a sum loop | Yes | +| E128135 | Use `TensorPrimitives` instead of a sum, min, or max loop | Yes | | E128140 | Use `Span.Fill`/`Clear`/`CopyTo` instead of an element loop | Yes | | E128141 | Use a `u8` literal instead of `Encoding.UTF8.GetBytes` | Yes | | E128152 | Complexity past the `e128_max_complexity` ceiling (nested loops, recursion) | Yes | @@ -198,6 +198,9 @@ All rules default to **Warning** severity unless noted. Every rule includes a co | E128223 | Hand-rolled child-process capture (use `Process.RunAndCaptureText`) | No | | E128224 | Read-only `MemoryStream` over a string or byte array | No | | E128226 | Comparer set built by constructor and `Add` loop | No | +| E128229 | Middleware binds the `Func` next delegate | Yes | +| E128230 | Static files served through the runtime pipeline | No | +| E128231 | `string.Split` result enumerated without a stored array | Yes | ### Security @@ -1092,16 +1095,30 @@ var result = ImmutableArray.Create(items.ToArray()); var result = ImmutableCollectionsMarshal.AsImmutableArray(items.ToArray()); ``` -### E128084 — List.GetRange allocates intermediate list +### E128084 — List copies and indexer loops + +Flags two `List` shapes. Flags `list.GetRange(start, count)`. `GetRange` allocates an intermediate `List`. Use `CollectionsMarshal.AsSpan(list).Slice(start, count).ToArray()` to copy directly from the internal array without the intermediate allocation. The rule fires only when flow analysis proves the receiver non-null, because `AsSpan(null)` returns an empty span where `GetRange` throws. A bad range throws `ArgumentOutOfRangeException` from `Slice`. +Flags `for (int i = 0; i < list.Count; i++)` when the body only reads `list[i]`. The indexer repeats the bounds check on every element. The rule stays silent when the loop calls any other member on the list, writes through the indexer, or uses the loop variable for another purpose. The loop-variable rewrite enumerates `CollectionsMarshal.AsSpan(list)`, so the rule suppresses a loop that mutates the list. + ```csharp // Before (warns) var slice = list.GetRange(2, 5); +for (int i = 0; i < list.Count; i++) +{ + total += list[i].Length; +} + // After var slice = CollectionsMarshal.AsSpan(list).Slice(2, 5).ToArray(); + +foreach (var item in CollectionsMarshal.AsSpan(list)) +{ + total += item.Length; +} ``` ### E128085 — SelectMany.ToList creates LINQ iterator allocations @@ -1479,9 +1496,11 @@ The analyzer skips a loop whose counter is unsigned (`uint` or `ulong`) by desig ### E128135: Use `TensorPrimitives.Sum` instead of a sum loop -Flags a `foreach` loop whose body is exactly `sum += value;` where both the sum and the element are `float` or `double`, and the source is an array, `Span`, or `ReadOnlySpan`. The loop adds one element per iteration. +Flags a `foreach` loop whose body reduces the elements of a `float` or `double` source one at a time, where the source is an array, `Span`, or `ReadOnlySpan`. + +A sum loop adds the element. A maximum loop reads `if (value > max) { max = value; }`, and a minimum loop reads `if (value < min) { min = value; }`. The min and max shapes report only when the accumulator starts at the neutral value: `MinValue` for a maximum and `MaxValue` for a minimum. Any other start value would survive the reduction. -The fix replaces the loop with `sum += TensorPrimitives.Sum(source);`. The analyzer reports only when the referenced `System.Numerics.Tensors` assembly declares the matching `Sum` overload. +The fix replaces the loop with `sum += TensorPrimitives.Sum(source);` or with `TensorPrimitives.Max/Min(source)` in the accumulator declaration. The analyzer reports only when the referenced `System.Numerics.Tensors` assembly declares every matching member. ### E128136: Do not pair a pointer parameter with a separate length parameter @@ -3322,6 +3341,60 @@ var parameters = new TokenValidationParameters }; ``` +### E128229: Middleware binds the Func next delegate + +Flags an inline `Use` middleware whose second parameter is a `Func`. The `app.Use((context, next) => ...)` overload allocates a `Func` closure on every request. The `RequestDelegate` overload passes the same delegate with no allocation. + +The rule reports only when every use of `next` is a call with no argument, at least one such call exists, and the lambda never reassigns the context parameter. The fix changes the parameter type to `RequestDelegate` and passes the context to every call. The rule also accepts the manual `IApplicationBuilder.Use` overload, not only the extension method. + +```csharp +// Before (warns) +app.Use(async (HttpContext context, Func next) => +{ + await next(); +}); + +// After +app.Use(async (HttpContext context, RequestDelegate next) => +{ + await next(context); +}); +``` + +### E128230: Static files served through the runtime pipeline + +Flags `app.UseStaticFiles()` with no argument. The call runs a request-time middleware. `MapStaticAssets` serves a build-time manifest with precompressed variants and ETags. + +The rule registers only when the compilation declares `MapStaticAssets`, so a target framework without the endpoint mapping API gets no report. A call that passes `StaticFileOptions` stays silent, because the rewrite moves the call into the endpoint mapping section. The rule carries no code fix, because a Razor app also changes how it references the assets. + +```csharp +// Before (warns) +app.UseStaticFiles(); + +// After +app.MapStaticAssets(); +``` + +### E128231: Split result enumerated without a stored array + +Flags a `foreach` that enumerates a `string.Split` result with a `char` or constant-string separator. The call allocates one array and one string per part. `MemoryExtensions.Split` yields `Range` values over the same string with no allocation. + +The rule reports the loop. The fix changes the source to `source.AsSpan().Split(separator)` and reads each part as a slice of the span. The fix applies only when every read of the part is a length, an element access, or a constant-string comparison, and the receiver is a name chain. A loop that passes the part to a method or parses it stays reported with no fix, because `Parse` takes a `ReadOnlySpan` only with an explicit format provider. + +```csharp +// Before (warns) +foreach (string part in line.Split(',')) +{ + total += part.Length; +} + +// After +foreach (var part in line.AsSpan().Split(',')) +{ + total += line.AsSpan()[part].Length; +} +``` + ## Requirements - .NET SDK 11.0+ (targets `netstandard2.0`, runs in any modern Roslyn host) diff --git a/tests/E128.Analyzers.Tests/ListGetRangeAnalyzerTests.cs b/tests/E128.Analyzers.Tests/ListGetRangeAnalyzerTests.cs index ea45ba4..10e5245 100644 --- a/tests/E128.Analyzers.Tests/ListGetRangeAnalyzerTests.cs +++ b/tests/E128.Analyzers.Tests/ListGetRangeAnalyzerTests.cs @@ -1,5 +1,7 @@ using System.Threading.Tasks; using E128.Analyzers.Performance; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Testing; using Xunit; namespace E128.Analyzers.Tests; @@ -10,18 +12,20 @@ public sealed class ListGetRangeAnalyzerTests [Trait("Category", "CI")] public Task Reports_WhenCalledOnList() { - return AnalyzerTestRunner.VerifyAsync(""" - #nullable enable - using System.Collections.Generic; - class C - { - void M() - { - var list = new List { 1, 2, 3, 4, 5 }; - IReadOnlyList range = {|E128084:list.GetRange(1, 3)|}; - } - } - """); + return AnalyzerTestRunner.VerifyAsync( + """ + #nullable enable + using System.Collections.Generic; + class C + { + void M() + { + var list = new List { 1, 2, 3, 4, 5 }; + IReadOnlyList range = {|#0:list.GetRange(1, 3)|}; + } + } + """, + new DiagnosticResult("E128084", DiagnosticSeverity.Warning).WithLocation(0)); } [Fact] @@ -95,4 +99,107 @@ void M() } """); } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAnIndexerLoopReadsAList() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System.Collections.Generic; + class C + { + int Total(List items) + { + int total = 0; + {|#0:for (int i = 0; i < items.Count; i++) + { + total += items[i].Length; + }|} + return total; + } + } + """, + new DiagnosticResult("E128084", DiagnosticSeverity.Warning).WithLocation(0)); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLoopMutatesTheList() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Collections.Generic; + class C + { + int Total(List items) + { + int total = 0; + for (int i = 0; i < items.Count; i++) + { + total += items[i].Length; + items.Add("more"); + } + return total; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLoopWritesThroughTheIndexer() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Collections.Generic; + class C + { + void M(List items) + { + for (int i = 0; i < items.Count; i++) + { + items[i] = "value"; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLoopVariableIndexesAnotherCollection() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Collections.Generic; + class C + { + void M(List items, string[] other) + { + for (int i = 0; i < items.Count; i++) + { + other[i] = items[i]; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLoopVariableHasAnotherUse() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Collections.Generic; + class C + { + void M(List items) + { + int total = 0; + for (int i = 0; i < items.Count; i++) + { + total += items[i].Length + i; + } + } + } + """); + } } diff --git a/tests/E128.Analyzers.Tests/ListGetRangeCodeFixTests.cs b/tests/E128.Analyzers.Tests/ListGetRangeCodeFixTests.cs index 06054ec..f73df55 100644 --- a/tests/E128.Analyzers.Tests/ListGetRangeCodeFixTests.cs +++ b/tests/E128.Analyzers.Tests/ListGetRangeCodeFixTests.cs @@ -1,21 +1,18 @@ using System.Threading.Tasks; using E128.Analyzers.Performance; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Testing; using Xunit; namespace E128.Analyzers.Tests; public sealed class ListGetRangeCodeFixTests { - private static Task VerifyFixAsync(string source, string fixedCode) - { - return CodeFixTestRunner.RunAsync(source, fixedCode); - } - [Fact] [Trait("Category", "CI")] public Task CodeFix_ReplacesGetRangeWithAsSpanSlice() { - return VerifyFixAsync( + return CodeFixTestRunner.RunAsync( """ #nullable enable using System.Collections.Generic; @@ -24,7 +21,7 @@ class C void M() { var list = new List { 1, 2, 3, 4, 5 }; - IReadOnlyList range = {|E128084:list.GetRange(1, 3)|}; + IReadOnlyList range = {|#0:list.GetRange(1, 3)|}; } } """, @@ -41,6 +38,48 @@ void M() IReadOnlyList range = CollectionsMarshal.AsSpan(list).Slice(1, 3).ToArray(); } } - """); + """, + expected: [new DiagnosticResult("E128084", DiagnosticSeverity.Warning).WithLocation(0)]); + } + + [Fact] + [Trait("Category", "CI")] + public Task CodeFix_ReplacesTheIndexerLoopWithAsSpan() + { + return CodeFixTestRunner.RunAsync( + """ + using System.Collections.Generic; + + class C + { + int Total(List items) + { + int total = 0; + {|#0:for (int i = 0; i < items.Count; i++) + { + total += items[i].Length; + }|} + return total; + } + } + """, + """ + using System.Collections.Generic; + using System.Runtime.InteropServices; + + class C + { + int Total(List items) + { + int total = 0; + foreach (var i in CollectionsMarshal.AsSpan(items)) + { + total += i.Length; + } + return total; + } + } + """, + expected: [new DiagnosticResult("E128084", DiagnosticSeverity.Warning).WithLocation(0)]); } } diff --git a/tests/E128.Analyzers.Tests/ListIndexerLoopMatcherTests.cs b/tests/E128.Analyzers.Tests/ListIndexerLoopMatcherTests.cs new file mode 100644 index 0000000..47e7cdc --- /dev/null +++ b/tests/E128.Analyzers.Tests/ListIndexerLoopMatcherTests.cs @@ -0,0 +1,116 @@ +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +/// +/// Direct checks on the E128084 indexer-loop matcher, against a real compilation. +/// The analyzer tests cover the diagnostic; this test shows which shape a change breaks. +/// +public sealed class ListIndexerLoopMatcherTests +{ + private const string Source = """ + using System.Collections.Generic; + class C + { + int Total(List items) + { + int total = 0; + for (int i = 0; i < items.Count; i++) + { + total += items[i].Length; + } + return total; + } + } + """; + + [Fact] + [Trait("Category", "CI")] + public async Task Matches_WhenTheLoopOnlyReadsTheIndexer() + { + var cancellationToken = TestContext.Current.CancellationToken; + var tree = CSharpSyntaxTree.ParseText(Source, cancellationToken: cancellationToken); + var references = await ReferenceAssemblies.Net.Net100.ResolveAsync(LanguageNames.CSharp, cancellationToken); + var compilation = CSharpCompilation.Create( + "Probe", + [tree], + references, + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + var model = compilation.GetSemanticModel(tree); + var root = await tree.GetRootAsync(cancellationToken); + var loop = root.DescendantNodes().OfType().Single(); + var listType = compilation.GetTypeByMetadataName("System.Collections.Generic.List`1"); + + Assert.NotNull(listType); + Assert.True(IndexedForLoop.TryMatch(loop, "Count", out var variable, out var owner, out _)); + Assert.Equal("i", variable); + Assert.NotNull(owner); + + var listSymbol = model.GetSymbolInfo(owner, cancellationToken).Symbol; + var loopVariable = GetLoopVariable(loop, model, cancellationToken); + Assert.True(loopVariable is ILocalSymbol); + + CheckIdentifiers(loop, model, loopVariable, listSymbol, cancellationToken); + + var matched = ListGetRangeAnalyzer.TryMatchIndexerLoop( + loop, + model, + listType, + cancellationToken, + out _, + out var reads); + + Assert.True(matched, "matcher failed"); + var single = Assert.Single(reads); + Assert.NotNull(single); + } + + private static ISymbol? GetLoopVariable( + ForStatementSyntax loop, + SemanticModel model, + CancellationToken cancellationToken) + { + return loop.Declaration is { Variables.Count: 1 } declaration + ? model.GetDeclaredSymbol(declaration.Variables[0], cancellationToken) + : null; + } + + private static void CheckIdentifiers( + ForStatementSyntax loop, + SemanticModel model, + ISymbol? loopVariable, + ISymbol? listSymbol, + CancellationToken cancellationToken) + { + foreach (var identifier in loop.Statement.DescendantNodesAndSelf().OfType()) + { + var symbol = model.GetSymbolInfo(identifier, cancellationToken).Symbol; + + if (SymbolEqualityComparer.Default.Equals(symbol, loopVariable)) + { + Assert.True(identifier.Parent is ArgumentSyntax); + Assert.True(identifier.Parent.Parent?.Parent is ElementAccessExpressionSyntax); + var element = (ElementAccessExpressionSyntax)identifier.Parent.Parent.Parent; + var argument = Assert.Single(element.ArgumentList.Arguments); + Assert.True(argument.Expression.Span == identifier.Span); + Assert.True(element.Parent is MemberAccessExpressionSyntax); + Assert.True(SymbolEqualityComparer.Default.Equals( + model.GetSymbolInfo(element.Expression, cancellationToken).Symbol, + listSymbol)); + } + + if (SymbolEqualityComparer.Default.Equals(symbol, listSymbol)) + { + Assert.True(identifier.Parent is ElementAccessExpressionSyntax); + } + } + } +} diff --git a/tests/E128.Analyzers.Tests/ManualSpanSumAnalyzerBranchCoverageGapTests.cs b/tests/E128.Analyzers.Tests/ManualSpanSumAnalyzerBranchCoverageGapTests.cs index 4f12265..de8efdf 100644 --- a/tests/E128.Analyzers.Tests/ManualSpanSumAnalyzerBranchCoverageGapTests.cs +++ b/tests/E128.Analyzers.Tests/ManualSpanSumAnalyzerBranchCoverageGapTests.cs @@ -144,6 +144,31 @@ float SumFloat(float[] values) """); } + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTensorPrimitivesHasNoMax() + { + return VerifyWithStubAsync( + DoubleOnlyStub, + """ + class C + { + double Max(double[] values) + { + double max = double.MinValue; + foreach (var value in values) + { + if (value > max) + { + max = value; + } + } + return max; + } + } + """); + } + [Fact] [Trait("Category", "CI")] public Task Silent_WhenTensorPrimitivesSumsNeitherFloatNorDouble() diff --git a/tests/E128.Analyzers.Tests/ManualSpanSumAnalyzerTests.cs b/tests/E128.Analyzers.Tests/ManualSpanSumAnalyzerTests.cs index 923d64c..ac75187 100644 --- a/tests/E128.Analyzers.Tests/ManualSpanSumAnalyzerTests.cs +++ b/tests/E128.Analyzers.Tests/ManualSpanSumAnalyzerTests.cs @@ -142,4 +142,120 @@ double Sum(float[] values) } """); } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenALoopComputesTheMaximum() + { + return VerifyAsync(""" + class C + { + double Max(double[] values) + { + double max = double.MinValue; + {|E128135:foreach (var value in values) + { + if (value > max) + { + max = value; + } + }|} + return max; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenALoopComputesTheMinimum() + { + return VerifyAsync(""" + class C + { + float Min(float[] values) + { + float min = float.MaxValue; + {|E128135:foreach (var value in values) + { + if (value < min) + { + min = value; + } + }|} + return min; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheMaximumStartsAtAnArbitraryValue() + { + return VerifyAsync(""" + class C + { + double Max(double[] values) + { + double max = 0; + foreach (var value in values) + { + if (value > max) + { + max = value; + } + } + return max; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheMinimumStartsAtZero() + { + return VerifyAsync(""" + class C + { + double Min(double[] values) + { + double min = 0; + foreach (var value in values) + { + if (value < min) + { + min = value; + } + } + return min; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheAccumulatorIsWrittenBeforeTheLoop() + { + return VerifyAsync(""" + class C + { + double Max(double[] values) + { + double max = double.MinValue; + max = 0; + foreach (var value in values) + { + if (value > max) + { + max = value; + } + } + return max; + } + } + """); + } } diff --git a/tests/E128.Analyzers.Tests/ManualSpanSumCodeFixTests.cs b/tests/E128.Analyzers.Tests/ManualSpanSumCodeFixTests.cs index 0c67a10..cf43a77 100644 --- a/tests/E128.Analyzers.Tests/ManualSpanSumCodeFixTests.cs +++ b/tests/E128.Analyzers.Tests/ManualSpanSumCodeFixTests.cs @@ -13,6 +13,13 @@ private static Task VerifyFixAsync(string source, string fixedCode) "using System;\nusing System.Numerics.Tensors;\n\n" + TestStubs.TensorPrimitives + "\n\n" + fixedCode); } + private static Task VerifyFixWithStubLastAsync(string source, string fixedCode) + { + return CodeFixTestRunner.RunAsync( + "using System;\n\n" + source + "\n\n" + TestStubs.TensorPrimitives, + "using System;\nusing System.Numerics.Tensors;\n\n" + fixedCode + "\n\n" + TestStubs.TensorPrimitives); + } + [Fact] [Trait("Category", "CI")] public Task Fix_ReplacesTheLoopWithSum() @@ -76,4 +83,72 @@ double Sum(ReadOnlySpan values) } """); } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_ReplacesTheMaximumLoopWithMax() + { + return VerifyFixWithStubLastAsync( + """ + class C + { + double Max(double[] values) + { + double max = double.MinValue; + {|E128135:foreach (var value in values) + { + if (value > max) + { + max = value; + } + }|} + return max; + } + } + """, + """ + class C + { + double Max(double[] values) + { + double max = TensorPrimitives.Max(values); + return max; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_ReplacesTheMinimumLoopWithMin() + { + return VerifyFixWithStubLastAsync( + """ + class C + { + float Min(float[] values) + { + float min = float.MaxValue; + {|E128135:foreach (var value in values) + { + if (value < min) + { + min = value; + } + }|} + return min; + } + } + """, + """ + class C + { + float Min(float[] values) + { + float min = TensorPrimitives.Min(values); + return min; + } + } + """); + } } diff --git a/tests/E128.Analyzers.Tests/MiddlewareNextDelegateAnalyzerTests.cs b/tests/E128.Analyzers.Tests/MiddlewareNextDelegateAnalyzerTests.cs new file mode 100644 index 0000000..4e01104 --- /dev/null +++ b/tests/E128.Analyzers.Tests/MiddlewareNextDelegateAnalyzerTests.cs @@ -0,0 +1,191 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class MiddlewareNextDelegateAnalyzerTests +{ + private static readonly AnalyzerTestOptions Options = new() { Sources = [TestStubs.AspNetCoreMinimal] }; + + private static DiagnosticResult Expected() + { + return new DiagnosticResult("E128229", DiagnosticSeverity.Warning).WithLocation(0); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheLambdaTakesAFuncTaskNextDelegate() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Http; + + class C + { + void M(IApplicationBuilder app) + { + app.Use(async (HttpContext context, {|#0:Func|} next) => + { + await next(); + }); + } + } + """, + Expected(), + Options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheLambdaReturnsTheNextCall() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Http; + + class C + { + void M(IApplicationBuilder app) + { + app.Use((HttpContext context, {|#0:Func|} next) => next()); + } + } + """, + Expected(), + Options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLambdaTakesARequestDelegate() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Http; + + class C + { + void M(IApplicationBuilder app) + { + app.Use(async (HttpContext context, RequestDelegate next) => + { + await next(context); + }); + } + } + """, + options: Options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheNextDelegateEscapesTheLambda() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Http; + + class C + { + void M(IApplicationBuilder app) + { + app.Use((HttpContext context, Func next) => Helper(context, next)); + } + + static Task Helper(HttpContext context, Func next) => next(); + } + """, + options: Options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheContextParameterIsReassigned() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Http; + + class C + { + void M(IApplicationBuilder app) + { + app.Use(async (HttpContext context, Func next) => + { + context = new HttpContext(); + await next(); + }); + } + } + """, + options: Options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheUseMethodIsNotOnApplicationBuilder() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Http; + + class App + { + public void Use(Func, Task> middleware) + { + } + } + + class C + { + void M(App app) + { + app.Use(async (HttpContext context, Func next) => + { + await next(); + }); + } + } + """, + options: Options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAspNetCoreIsNotReferenced() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System; + using System.Threading.Tasks; + + class C + { + void M() + { + Func, Task> middleware = (context, next) => next(); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/MiddlewareNextDelegateCodeFixTests.cs b/tests/E128.Analyzers.Tests/MiddlewareNextDelegateCodeFixTests.cs new file mode 100644 index 0000000..9980f09 --- /dev/null +++ b/tests/E128.Analyzers.Tests/MiddlewareNextDelegateCodeFixTests.cs @@ -0,0 +1,140 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class MiddlewareNextDelegateCodeFixTests +{ + private static Task VerifyFixAsync(string source, string fixedCode) + { + return CodeFixTestRunner.RunAsync( + source, + fixedCode, + options: new CodeFixTestOptions { Sources = [TestStubs.AspNetCoreMinimal] }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_ChangesTheParameterTypeAndPassesTheContext() + { + return VerifyFixAsync( + """ + using System; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Http; + + class C + { + void M(IApplicationBuilder app) + { + app.Use(async (HttpContext context, {|E128229:Func|} next) => + { + await next(); + }); + } + } + """, + """ + using System; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Http; + + class C + { + void M(IApplicationBuilder app) + { + app.Use(async (HttpContext context, RequestDelegate next) => + { + await next(context); + }); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_AddsTheHttpNamespace_WhenTheFileOmitsIt() + { + return VerifyFixAsync( + """ + using System; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Builder; + + class C + { + void M(IApplicationBuilder app) + { + app.Use(async (Microsoft.AspNetCore.Http.HttpContext context, {|E128229:Func|} next) => + { + await next(); + }); + } + } + """, + """ + using System; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Http; + + class C + { + void M(IApplicationBuilder app) + { + app.Use(async (Microsoft.AspNetCore.Http.HttpContext context, RequestDelegate next) => + { + await next(context); + }); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_KeepsEveryNextCallInTheBody() + { + return VerifyFixAsync( + """ + using System; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Http; + + class C + { + void M(IApplicationBuilder app) + { + app.Use(async (HttpContext context, {|E128229:Func|} next) => + { + await next(); + await next(); + }); + } + } + """, + """ + using System; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Http; + + class C + { + void M(IApplicationBuilder app) + { + app.Use(async (HttpContext context, RequestDelegate next) => + { + await next(context); + await next(context); + }); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/RuntimeStaticFilesAnalyzerTests.cs b/tests/E128.Analyzers.Tests/RuntimeStaticFilesAnalyzerTests.cs new file mode 100644 index 0000000..0cf4b8e --- /dev/null +++ b/tests/E128.Analyzers.Tests/RuntimeStaticFilesAnalyzerTests.cs @@ -0,0 +1,116 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class RuntimeStaticFilesAnalyzerTests +{ + private const string StubWithoutMapStaticAssets = """ + namespace Microsoft.AspNetCore.Builder + { + public interface IApplicationBuilder + { + } + + public static class StaticFileExtensions + { + public static IApplicationBuilder UseStaticFiles(this IApplicationBuilder app) + { + return app; + } + } + } + """; + + private static readonly AnalyzerTestOptions Options = new() { Sources = [TestStubs.AspNetCoreMinimal] }; + + private static DiagnosticResult Expected() + { + return new DiagnosticResult("E128230", DiagnosticSeverity.Warning).WithLocation(0); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheAppCallsUseStaticFiles() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using Microsoft.AspNetCore.Builder; + + class C + { + void M(IApplicationBuilder app) + { + {|#0:app.UseStaticFiles()|}; + } + } + """, + Expected(), + Options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheFrameworkHasNoMapStaticAssets() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using Microsoft.AspNetCore.Builder; + + class C + { + void M(IApplicationBuilder app) + { + app.UseStaticFiles(); + } + } + """, + options: new AnalyzerTestOptions { Sources = [StubWithoutMapStaticAssets] }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCallPassesStaticFileOptions() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using Microsoft.AspNetCore.Builder; + + class C + { + void M(IApplicationBuilder app) + { + app.UseStaticFiles(new StaticFileOptions()); + } + } + """, + options: Options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAnotherTypeDeclaresUseStaticFiles() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class App + { + public void UseStaticFiles() + { + } + } + + class C + { + void M(App app) + { + app.UseStaticFiles(); + } + } + """, + options: Options); + } +} diff --git a/tests/E128.Analyzers.Tests/SplitEnumerationAnalyzerTests.cs b/tests/E128.Analyzers.Tests/SplitEnumerationAnalyzerTests.cs new file mode 100644 index 0000000..f5bf082 --- /dev/null +++ b/tests/E128.Analyzers.Tests/SplitEnumerationAnalyzerTests.cs @@ -0,0 +1,154 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class SplitEnumerationAnalyzerTests +{ + private static DiagnosticResult Expected() + { + return new DiagnosticResult("E128231", DiagnosticSeverity.Warning).WithLocation(0); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAForeachEnumeratesACharSplit() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + int Sum(string line) + { + int total = 0; + {|#0:foreach (string part in line.Split(',')) + { + total += int.Parse(part); + }|} + return total; + } + } + """, + Expected()); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheLoopVariableIsImplicit() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + void M(string line) + { + {|#0:foreach (var part in line.Split(',')) + { + System.Console.WriteLine(part); + }|} + } + } + """, + Expected()); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheSeparatorIsAConstantString() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + int Count(string line) + { + int total = 0; + {|#0:foreach (string part in line.Split(", ")) + { + total += part.Length; + }|} + return total; + } + } + """, + Expected()); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCallPassesStringSplitOptions() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System; + + class C + { + int Sum(string line) + { + int total = 0; + foreach (string part in line.Split(',', StringSplitOptions.RemoveEmptyEntries)) + { + total += int.Parse(part); + } + return total; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheSeparatorIsNotConstant() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + int Sum(string line, string separator) + { + int total = 0; + foreach (string part in line.Split(separator)) + { + total += int.Parse(part); + } + return total; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLoopEnumeratesSomethingElse() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + int Sum(string[] parts) + { + int total = 0; + foreach (string part in parts) + { + total += int.Parse(part); + } + return total; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public void Silent_WhenTheCoreTypesAreMissing() + { + var compilation = CSharpCompilation.Create("Gate"); + + Assert.Null(SplitEnumerationAnalyzer.CreateTerms(compilation)); + } +} diff --git a/tests/E128.Analyzers.Tests/SplitEnumerationCodeFixTests.cs b/tests/E128.Analyzers.Tests/SplitEnumerationCodeFixTests.cs new file mode 100644 index 0000000..a8a0575 --- /dev/null +++ b/tests/E128.Analyzers.Tests/SplitEnumerationCodeFixTests.cs @@ -0,0 +1,164 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class SplitEnumerationCodeFixTests +{ + private static Task VerifyFixAsync(string source, string fixedCode) + { + return CodeFixTestRunner.RunAsync(source, fixedCode); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheBodyParsesThePart() + { + return CodeFixTestRunner.NoFixAsync( + """ + using System; + + class C + { + int Sum(string line) + { + int total = 0; + {|E128231:foreach (string part in line.Split(',')) + { + total += int.Parse(part); + }|} + return total; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_ReadsTheLengthOfEachSlice() + { + return VerifyFixAsync( + """ + using System; + + class C + { + int Count(string line) + { + int total = 0; + {|E128231:foreach (string part in line.Split(", ")) + { + total += part.Length; + }|} + return total; + } + } + """, + """ + using System; + + class C + { + int Count(string line) + { + int total = 0; + foreach (var part in line.AsSpan().Split(", ")) + { + total += line.AsSpan()[part].Length; + } + return total; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_ComparesEachSliceWithAString() + { + return VerifyFixAsync( + """ + using System; + + class C + { + int Count(string line) + { + int total = 0; + {|E128231:foreach (string part in line.Split(',')) + { + if (part == "skip") + { + total++; + } + }|} + return total; + } + } + """, + """ + using System; + + class C + { + int Count(string line) + { + int total = 0; + foreach (var part in line.AsSpan().Split(',')) + { + if (line.AsSpan()[part] == "skip") + { + total++; + } + } + return total; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheBodyStoresThePartAsAString() + { + return CodeFixTestRunner.NoFixAsync( + """ + class C + { + void M(string line) + { + {|E128231:foreach (string part in line.Split(',')) + { + Handle(part); + }|} + } + + static void Handle(string part) + { + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheReceiverIsAMethodCall() + { + return CodeFixTestRunner.NoFixAsync( + """ + class C + { + void M() + { + {|E128231:foreach (string part in GetLine().Split(',')) + { + System.Console.WriteLine(int.Parse(part)); + }|} + } + + static string GetLine() => string.Empty; + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/TestStubs.cs b/tests/E128.Analyzers.Tests/TestStubs.cs index 769e817..90376dd 100644 --- a/tests/E128.Analyzers.Tests/TestStubs.cs +++ b/tests/E128.Analyzers.Tests/TestStubs.cs @@ -36,6 +36,94 @@ public static double Sum(ReadOnlySpan values) { return 0d; } + + public static float Max(ReadOnlySpan values) + { + return 0f; + } + + public static double Max(ReadOnlySpan values) + { + return 0d; + } + + public static float Min(ReadOnlySpan values) + { + return 0f; + } + + public static double Min(ReadOnlySpan values) + { + return 0d; + } + } + } + """; + + /// + /// Synthetic minimal API surface used by the middleware and static-file tests. + /// + public const string AspNetCoreMinimal = + """ + namespace Microsoft.AspNetCore.Http + { + public class HttpContext + { + } + + public delegate System.Threading.Tasks.Task RequestDelegate(HttpContext context); + } + + namespace Microsoft.AspNetCore.Builder + { + public interface IApplicationBuilder + { + } + + public interface IEndpointRouteBuilder + { + } + + public static class UseMiddlewareExtensions + { + public static IApplicationBuilder Use( + this IApplicationBuilder app, + System.Func, System.Threading.Tasks.Task> middleware) + { + return app; + } + + public static IApplicationBuilder Use( + this IApplicationBuilder app, + System.Func middleware) + { + return app; + } + } + + public sealed class StaticFileOptions + { + } + + public static class StaticFileExtensions + { + public static IApplicationBuilder UseStaticFiles(this IApplicationBuilder app) + { + return app; + } + + public static IApplicationBuilder UseStaticFiles(this IApplicationBuilder app, StaticFileOptions options) + { + return app; + } + } + + public static class StaticAssetsEndpointRouteBuilderExtensions + { + public static IEndpointRouteBuilder MapStaticAssets(this IEndpointRouteBuilder endpoints) + { + return endpoints; + } } } """;