diff --git a/lode/dotnet/analyzers/rule-details-conversion.md b/lode/dotnet/analyzers/rule-details-conversion.md index 23c116b..e9e2d09 100644 --- a/lode/dotnet/analyzers/rule-details-conversion.md +++ b/lode/dotnet/analyzers/rule-details-conversion.md @@ -1,5 +1,5 @@ # Conversion Rules E128223 to E128226 -*Updated: 2026-11-14T01:26:59Z* +*Updated: 2026-11-16T15:41:36Z* Detection shape for the .NET 11 conversion family. The rules move working code onto a mechanism the band carries. Sources: [net11-conversion-sweep.md](../analyzer-candidates/net11-conversion-sweep.md). @@ -34,7 +34,8 @@ or a statement-form flag set on a start-info local that later reaches a process ## E128224: Read-Only MemoryStream Reports `new MemoryStream(x)` in a local when `x` is an `Encoding.GetBytes` result or a -`byte[]`, and every use of the local is read shaped. Read shaped means one of: +`byte[]`, and every use of the local is read shaped. The target-typed `new(x)` form +counts too. Read shaped means one of: - A member call in the read set (`Read`, `ReadAsync`, `CopyTo`, `Seek`, `Dispose`, and similar). @@ -43,6 +44,9 @@ Reports `new MemoryStream(x)` in a local when `x` is an `Encoding.GetBytes` resu `XPathDocument`, `XmlReader.Create`, `JsonDocument.Parse`, `XDocument.Load`, `HashAlgorithm.ComputeHash`). +A settable member read is a read only when the syntax reads it. An assignment, an +increment, or a `ref` argument to a member such as `Position` is a write. + A compression wrapper (`GZipStream`, `DeflateStream`, `BrotliStream`) counts as a read consumer only when the creation passes `CompressionMode.Decompress` (`IsDecompressMode` resolves the field symbol). A compress-mode or mode-less @@ -65,7 +69,8 @@ compiler rejects only the `closed abstract` modifier pair on the type. ## E128226: Comparer Set Built By A Loop -Reports `new HashSet(comparer)` in a local when: +Reports `new HashSet(comparer)` in a local when the creation is target typed +(`HashSet set = new(comparer)`) or explicit, and: 1. The creation has no collection initializer. 2. The argument implements `IEqualityComparer`. diff --git a/lode/dotnet/analyzers/rule-details-reliability.md b/lode/dotnet/analyzers/rule-details-reliability.md index f815417..eb005d0 100644 --- a/lode/dotnet/analyzers/rule-details-reliability.md +++ b/lode/dotnet/analyzers/rule-details-reliability.md @@ -1,5 +1,5 @@ # Reliability Rule Details -*Updated: 2026-11-14T01:26:59Z* +*Updated: 2026-11-16T15:41:36Z* Behavior notes for the reliability rules. The complete rule table, the severity, and the code-fix status live in `src/E128.Analyzers/README.md`. The @@ -163,6 +163,11 @@ silent. A group that leads with a distinct separator atom, such as `(?:/[^/]+)+`, also stays silent: `FirstAtomCanAlsoBeLast` exempts it when the first and last consuming atoms cannot match the same text. +The code fix rewrites a single-atom body only. It removes the outer quantifier, +or makes the group non-capturing when removal would lose the empty match. A +multi-atom body has no language-preserving rewrite that clears the report, so +the fixer offers no action for that shape. + Both scans treat character class contents as literals. `BuildCharacterClassMask` marks every index inside a `[...]` class in one pass, and each scan skips masked indices. The mask handles a leading `^`, a leading literal `]`, and escapes. A diff --git a/lode/dotnet/analyzers/rule-details-security.md b/lode/dotnet/analyzers/rule-details-security.md index 69f3b24..3c350aa 100644 --- a/lode/dotnet/analyzers/rule-details-security.md +++ b/lode/dotnet/analyzers/rule-details-security.md @@ -1,5 +1,5 @@ # Security Rule Detail Notes -*Updated: 2026-11-16T15:18:25Z* +*Updated: 2026-11-16T15:41:36Z* Detection shape and exclusions for the E128 security rules that the main rule table cannot show. The severity and the code-fix status live in @@ -30,10 +30,11 @@ name text: - A local whose initializer is a `ContentLength` access on the same chain counts as the bound variable. -A `MaxResponseContentBufferSize` reference anywhere in the enclosing type also -bounds every read in that type. This covers a typed client that configures its -own handler. A bound in a different type is invisible, so a client configured in -a composition root needs an analyzer suppression at the read site. +A `MaxResponseContentBufferSize` setting does not bound a direct content read. +The setting caps the client buffer only, so a read through +`HttpContent.ReadAsStringAsync` stays unbounded. A bound in a different method or +type is invisible, so a client configured in a composition root needs a bound in +the read scope or an analyzer suppression at the read site. An in-memory content type needs no bound: `ByteArrayContent`, its derived `StringContent` and `FormUrlEncodedContent`, `ReadOnlyMemoryContent`, and diff --git a/plans/review-2026-11-14-general/general-context.md b/plans/review-2026-11-14-general/general-context.md deleted file mode 100644 index cf013f0..0000000 --- a/plans/review-2026-11-14-general/general-context.md +++ /dev/null @@ -1,73 +0,0 @@ -# Review Context: days 2 Union Review - -*Updated: 2026-11-14T00:42:34Z* - -## Diff Summary - -Base `be24a59`, head `b70fb1c`, 16 commits, 140 files, 8044 insertions, 2701 deletions. -The diff was delivered as 17 slices of 40KB or less at file boundaries. - -## Vectors Run - -| Vector | Result | -| ------ | ------ | -| `scripts/build.sh` | exit 0, 0 warnings, 0 errors | -| `scripts/diagnostics.sh --group` | no diagnostics | -| `scripts/violation-scan.sh` | 4 hits, all analyzer source fixtures | -| `scripts/suppression-scan.sh --json` | test-only pragmas, pre-existing | -| `scripts/analyzer-stats.sh --json` | rule inventory only | -| `scripts/deps-graph.sh --orphans --json` | two pins, both classified | -| `scripts/nuget-heat-map.sh --json` | 13 packages, no finding | -| `scripts/internal/mechanical-diff.sh --json` | no mechanical files | -| Roslyn navigator | MCP server not queried, no result | - -## Reviewers Run - -| Reviewer | Coverage | Outcome | -| -------- | -------- | ------- | -| security-reviewer | slices 2, 3, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 | 1 High, 4 Medium, 10 Low | -| code-reviewer | slices 1 through 17 | 9 High, 21 Medium, 40 Low | -| adversarial-review | three attackers over slices 1-17, one defender | 4 High, 5 Medium, 8 Low | -| code-review | full range, effort high | 10 findings, no severity split | -| ponytail-review | main-context lean pass | 6 lean findings | -| mr-sparkle-dotnet | build, diagnostics, suppressions, packages | no gate breach | -| code-reviewer slice 7 | docs and config | 1 Medium, 4 Low | - -## Dedup Report - -The defender pass validated the 13 merged Critical and High findings. - -| Merged from | Reviewers | Result | -| ----------- | --------- | ------ | -| Nested fix drops outer `*` | 3 | CONFIRMED High | -| Class not expanded in atom comparison | 2 | CONFIRMED High | -| Start-info local never binds | 4 | CONFIRMED High | -| Compression stream in `Compress` mode | 2 | CONFIRMED High | -| Identifier-text bound detection | 4 | CONFIRMED High | -| `ContentLength` guard fails open | 2 | CONFIRMED High | -| Guarded catch-all treated as exhaustive | 4 | CONFIRMED High | -| `this.p1` and `this.p2` share a root | 2 | Downgraded Medium | -| `{1,}` rewrite leaves the diagnostic | 2 | Downgraded Medium | -| `Position` assignment counts as a read | 1 | Downgraded Medium | -| Type-wide `MaxResponseContentBufferSize` | 2 | Downgraded Medium | -| Tests bypass the shared runner | 2 | Downgraded Medium | -| Target-typed `new(...)` missed | 3 | Downgraded Medium | - -Dropped findings: none. - -A late High finding was missing from the defender batch: `lode/dotnet/release-tracking.md:170`. -The main context confirmed it against source. `AnalyzerReleases.Shipped.md` carries release -3.1.0 with E128227, and `E128.Analyzers.csproj` pins version 3.1.0, while the table ends at -3.0.0. Confirmed High. - -## Notes - -- `scripts/internal/cr-target.sh` reports 15 untracked files that do not exist on disk. The - file list is otherwise correct. Treat the untracked array as unreliable. -- Build clean lowers unconfirmed Medium and Low compliance findings to advisory. -- Tests were not run during the review. The adversarial functionality attacker ran the - shipping-script suite (30 of 30 cases) and the union-switch tests (7 of 7). -- The three adversarial attackers ran as subagents. Their defender was folded into the single - merged defender pass. - -Related: [plan](general-plan.md), [tasks](general-tasks.md). diff --git a/plans/review-2026-11-14-general/general-plan.md b/plans/review-2026-11-14-general/general-plan.md deleted file mode 100644 index a45954b..0000000 --- a/plans/review-2026-11-14-general/general-plan.md +++ /dev/null @@ -1,70 +0,0 @@ -# Review Plan: days 2 Union Review - -*Updated: 2026-11-14T00:42:34Z* - -Target: commits newer than 2 days (base `be24a59`, head `b70fb1c`), 140 files, 16 commits. -Verdict: Resolved. All 8 High findings fixed on `fix/review-2026-11-14-general`. -`scripts/check.sh` green: shell, format, build, 2992 tests (2987 passed, 3 fixed at the -gate, 2 skipped). The 3 gate failures came from `HttpContentHeadersTypeName` resolving -`System.Net.Http.HttpContentHeaders` instead of `System.Net.Http.Headers.HttpContentHeaders`, -which left the ContentLength bound undetected. One-line fix in -`HttpBodyReadWithoutSizeBoundAnalyzer.cs`. -The Medium findings are advisory and stay unapplied. - -## Findings - -| # | Severity | File | Problem | -| - | -------- | ---- | ------- | -| 1 | High | `src/E128.Analyzers.CodeFixers/Reliability/GeneratedRegexNestedCodeFixProvider.cs:53` | Single-atom fix drops the outer `*`, so `(a+)*` becomes `(a+)` and stops matching the empty string. | -| 2 | High | `src/E128.Analyzers/Reliability/GeneratedRegexHelpers.cs:289` | Atom comparison does not expand character classes, so `(?:/[^\s:"']+)+` is exempted and stays exponential. | -| 3 | High | `src/E128.Analyzers/Reliability/HandRolledProcessCaptureAnalyzer.cs:156` | `FlagBinds` never reaches `LocalLinksToProcess`, so a start-info local set after creation never binds. | -| 4 | High | `src/E128.Analyzers/Performance/ReadOnlyMemoryStreamAnalyzer.cs:57-66,232-234` | Compression streams count as read-only consumers in `Compress` mode. | -| 5 | High | `src/E128.Analyzers/Security/HttpBodyReadWithoutSizeBoundAnalyzer.cs:142-157` | Bound detection matches identifier text, not a bounding call or an ordering. | -| 6 | High | `src/E128.Analyzers/README.md:3274-3286` | Documented `ContentLength` guard fails open on a chunked response. | -| 7 | High | `src/E128.Analyzers/Design/UnionSwitchDiscardArmAnalyzer.cs:124-147` | A `when`-guarded discard counts as a catch-all, and the fix produces a non-exhaustive switch. | -| 8 | High | `lode/dotnet/release-tracking.md:170` | The release-to-rule table ends at 3.0.0, but the head commit ships 3.1.0 with E128227. | - -## Phases - -### Phase 1: GeneratedRegex correctness - -Fix findings 1 and 2. Restore language preservation in the nested-quantifier fix. Expand -class contents in the atom comparison, or record the limit in the rule contract. Update the -slash test and the README claim in the same change. - -### Phase 2: E128223 process binding - -Fix finding 3. Route a start-info local receiver through `LocalLinksToProcess`. Add tests for -the post-creation assignment and for `process.StartInfo = psi`. - -### Phase 3: Performance rules - -Fix finding 4. Require `CompressionMode.Decompress` for the compression wrapper types. - -### Phase 4: E128227 size bound - -Fix findings 5 and 6. Accept only a resolved `LoadIntoBufferAsync(long)` overload, or a -null-safe pre-read comparison. Replace the documented remediation and update the test that -locks the weak shape in. - -### Phase 5: E128220 catch-all - -Fix finding 7. Treat a guarded discard or var arm as not exhaustive. Add a test for -`_ when cond =>`. - -### Phase 6: Release record - -Fix finding 8. Add the 3.1.0 row with E128227 and bump the file timestamp. - -## Medium Findings - -Six findings were lowered to Medium by the defender pass: - -- `ProcessLaunchScope.cs:19-32`: `this.p1` and `this.p2` share one root symbol. -- `GeneratedRegexNestedCodeFixProvider.cs:58-60`: `{1,}` rewrite leaves E128014 firing. -- `ReadOnlyMemoryStreamAnalyzer.cs:55,208-218`: a `Position` assignment counts as a read. -- `HttpBodyReadWithoutSizeBoundAnalyzer.cs:47,149-150`: `MaxResponseContentBufferSize` is trusted across the type. -- `tests/E128.Analyzers.Tests/*`: eight test classes bypass the shared runner. -- `ComparerSetConstructionAnalyzer.cs:62` and `ReadOnlyMemoryStreamAnalyzer.cs:102`: target-typed `new(...)` is missed. - -Related: [tasks](general-tasks.md), [context](general-context.md). diff --git a/plans/review-2026-11-14-general/general-tasks.md b/plans/review-2026-11-14-general/general-tasks.md deleted file mode 100644 index f0ee3d3..0000000 --- a/plans/review-2026-11-14-general/general-tasks.md +++ /dev/null @@ -1,14 +0,0 @@ -# Review Tasks: days 2 Union Review - -*Updated: 2026-11-14T00:42:34Z* - -- [x] `src/E128.Analyzers.CodeFixers/Reliability/GeneratedRegexNestedCodeFixProvider.cs:53` Removing the outer `*` changes the pattern language for the single-atom body. Fix: strip the quantifier only when the outer is `+` or the inner is `*`; add a `(a+)*` test. Severity: High. Source: security-reviewer, code-reviewer, adversarial-review. -- [x] `src/E128.Analyzers/Reliability/GeneratedRegexHelpers.cs:289` The atom comparison does not expand character classes, so a catastrophic group is exempted. Fix: expand class contents in the comparison, or state the limit in the README and fix the slash test. Severity: High. Source: adversarial-review, code-reviewer. -- [x] `src/E128.Analyzers/Reliability/HandRolledProcessCaptureAnalyzer.cs:156` A start-info local set after creation never binds, because `FlagBinds` never calls `LocalLinksToProcess`. Fix: route a local receiver through `LocalLinksToProcess`; add assignment-shape tests. Severity: High. Source: code-reviewer, security-reviewer, adversarial-review, code-review. -- [x] `src/E128.Analyzers/Performance/ReadOnlyMemoryStreamAnalyzer.cs:57-66,232-234` Compression streams count as read-only consumers in `Compress` mode. Fix: require the `CompressionMode.Decompress` argument for the three wrapper types. Severity: High. Source: code-reviewer, security-reviewer. -- [x] `src/E128.Analyzers/Security/HttpBodyReadWithoutSizeBoundAnalyzer.cs:142-157` Bound detection matches identifier text, so a parameterless `LoadIntoBufferAsync()` or an unrelated `ContentLength` silences the rule. Fix: resolve the invocation symbol and require the capped overload or a null-safe comparison before the read. Severity: High. Source: code-reviewer, security-reviewer, adversarial-review, code-review. -- [x] `src/E128.Analyzers/README.md:3274-3286` The documented `ContentLength` guard fails open on a chunked response. Fix: document a real bound and update `Silent_WhenContentLengthIsCheckedFirst`. Severity: High. Source: adversarial-review, security-reviewer. -- [x] `src/E128.Analyzers/Design/UnionSwitchDiscardArmAnalyzer.cs:124-147` A `when`-guarded discard counts as a catch-all, and the fix creates a non-exhaustive switch. Fix: treat a guarded arm as not exhaustive; add a `_ when cond =>` test. Severity: High. Source: security-reviewer, adversarial-review, code-review, code-reviewer. -- [x] `lode/dotnet/release-tracking.md:170` The release table ends at 3.0.0, but the head commit ships 3.1.0 with E128227. Fix: add the 3.1.0 row and bump the timestamp. Severity: High. Source: code-reviewer. - -Related: [plan](general-plan.md), [context](general-context.md). diff --git a/src/E128.Analyzers.CodeFixers/Reliability/GeneratedRegexNestedCodeFixProvider.cs b/src/E128.Analyzers.CodeFixers/Reliability/GeneratedRegexNestedCodeFixProvider.cs index 6b3401d..b5cd5a4 100644 --- a/src/E128.Analyzers.CodeFixers/Reliability/GeneratedRegexNestedCodeFixProvider.cs +++ b/src/E128.Analyzers.CodeFixers/Reliability/GeneratedRegexNestedCodeFixProvider.cs @@ -36,9 +36,9 @@ protected override Task RegisterFixesAsync(CodeFixContext context, SyntaxNode ro // A single-atom body makes the outer quantifier redundant, so the rewrite removes it // and the diagnostic clears. When removing the outer quantifier would lose the empty // match, like '(a+)*', the rewrite keeps it and makes the group non-capturing, so the - // language stays. The diagnostic stays in that case. Any other body keeps the - // language with an equivalent unbounded brace repeat. An unbounded brace outer - // quantifier has no language-preserving one-token rewrite and stays flagged. + // language stays. The diagnostic stays in that case. A multi-atom body has no + // language-preserving rewrite that clears the diagnostic: '(x){1,}' still carries the + // nested quantifier, so no fix is offered. internal static string RewriteOuterQuantifier(string pattern) { if (GeneratedRegexHelpers.FindNestedQuantifierSpan(pattern) is not { } span) @@ -52,19 +52,17 @@ internal static string RewriteOuterQuantifier(string pattern) return pattern; } - if (span.SingleAtomBody) + if (!span.SingleAtomBody) { - if (RemovalKeepsLanguage(pattern, span)) - { - return pattern.Remove(quantifierIndex, span.QuantifierLength); - } + return pattern; + } - return MakeGroupNonCapturing(pattern, span); + if (RemovalKeepsLanguage(pattern, span)) + { + return pattern.Remove(quantifierIndex, span.QuantifierLength); } - var lazy = span.QuantifierLength > 1 && pattern[quantifierIndex + 1] is '?'; - var replacement = string.Concat(pattern[quantifierIndex] is '*' ? "{0,}" : "{1,}", lazy ? "?" : string.Empty); - return pattern.Substring(0, quantifierIndex) + replacement + pattern.Substring(quantifierIndex + span.QuantifierLength); + return MakeGroupNonCapturing(pattern, span); } // Removing the outer quantifier keeps the language unless the outer quantifier is a diff --git a/src/E128.Analyzers/E128.Analyzers.csproj b/src/E128.Analyzers/E128.Analyzers.csproj index 5f106ef..9efd31f 100644 --- a/src/E128.Analyzers/E128.Analyzers.csproj +++ b/src/E128.Analyzers/E128.Analyzers.csproj @@ -23,7 +23,7 @@ - 3.1.2 + 3.1.3 true false true diff --git a/src/E128.Analyzers/Performance/ComparerSetConstructionAnalyzer.cs b/src/E128.Analyzers/Performance/ComparerSetConstructionAnalyzer.cs index 003d41d..9d6b3fc 100644 --- a/src/E128.Analyzers/Performance/ComparerSetConstructionAnalyzer.cs +++ b/src/E128.Analyzers/Performance/ComparerSetConstructionAnalyzer.cs @@ -59,12 +59,15 @@ public override void Initialize(AnalysisContext context) context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.EnableConcurrentExecution(); - context.RegisterSyntaxNodeAction(AnalyzeCreation, SyntaxKind.ObjectCreationExpression); + context.RegisterSyntaxNodeAction( + AnalyzeCreation, + SyntaxKind.ObjectCreationExpression, + SyntaxKind.ImplicitObjectCreationExpression); } private static void AnalyzeCreation(SyntaxNodeAnalysisContext context) { - var creation = (ObjectCreationExpressionSyntax)context.Node; + var creation = (BaseObjectCreationExpressionSyntax)context.Node; var model = context.SemanticModel; var cancellationToken = context.CancellationToken; @@ -88,7 +91,7 @@ private static void AnalyzeCreation(SyntaxNodeAnalysisContext context) } private static bool IsComparerHashSet( - ObjectCreationExpressionSyntax creation, + BaseObjectCreationExpressionSyntax creation, SemanticModel model, CancellationToken cancellationToken) { @@ -110,7 +113,7 @@ private static bool HasEqualityComparerArgument( } private static ILocalSymbol? GetTargetLocal( - ObjectCreationExpressionSyntax creation, + BaseObjectCreationExpressionSyntax creation, SemanticModel model, CancellationToken cancellationToken) { diff --git a/src/E128.Analyzers/Performance/ReadOnlyMemoryStreamAnalyzer.cs b/src/E128.Analyzers/Performance/ReadOnlyMemoryStreamAnalyzer.cs index 6bbf840..6068c6d 100644 --- a/src/E128.Analyzers/Performance/ReadOnlyMemoryStreamAnalyzer.cs +++ b/src/E128.Analyzers/Performance/ReadOnlyMemoryStreamAnalyzer.cs @@ -109,12 +109,15 @@ public override void Initialize(AnalysisContext context) context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.EnableConcurrentExecution(); - context.RegisterSyntaxNodeAction(AnalyzeCreation, SyntaxKind.ObjectCreationExpression); + context.RegisterSyntaxNodeAction( + AnalyzeCreation, + SyntaxKind.ObjectCreationExpression, + SyntaxKind.ImplicitObjectCreationExpression); } private static void AnalyzeCreation(SyntaxNodeAnalysisContext context) { - var creation = (ObjectCreationExpressionSyntax)context.Node; + var creation = (BaseObjectCreationExpressionSyntax)context.Node; var model = context.SemanticModel; var cancellationToken = context.CancellationToken; @@ -135,7 +138,7 @@ private static void AnalyzeCreation(SyntaxNodeAnalysisContext context) } private static bool IsMemoryStreamCreation( - ObjectCreationExpressionSyntax creation, + BaseObjectCreationExpressionSyntax creation, SemanticModel model, CancellationToken cancellationToken) { @@ -148,7 +151,7 @@ private static bool IsMemoryStreamCreation( /// capacity, a slice, or an explicit writable flag stays silent. /// private static bool WrapsReadOnlySource( - ObjectCreationExpressionSyntax creation, + BaseObjectCreationExpressionSyntax creation, SemanticModel model, CancellationToken cancellationToken) { @@ -175,7 +178,7 @@ private static bool WrapsReadOnlySource( } private static ILocalSymbol? GetTargetLocal( - ObjectCreationExpressionSyntax creation, + BaseObjectCreationExpressionSyntax creation, SemanticModel model, CancellationToken cancellationToken) { @@ -222,6 +225,11 @@ private static bool IsReadOnlyReference( { if (reference.Parent is MemberAccessExpressionSyntax access && access.Expression == reference) { + if (IsWriteTarget(access)) + { + return false; + } + var name = access.Name.Identifier.ValueText; return access.Parent is InvocationExpressionSyntax ? ReadMemberNames.Contains(name) @@ -232,6 +240,20 @@ private static bool IsReadOnlyReference( && IsReadOnlyConsumer(argument, model, cancellationToken); } + // A settable property such as Position is read only when it is read. An assignment or an + // increment is a write, and the replacement types reject a write. + private static bool IsWriteTarget(ExpressionSyntax expression) + { + return expression.Parent switch + { + AssignmentExpressionSyntax assignment => assignment.Left == expression, + PrefixUnaryExpressionSyntax prefix => prefix.Operand == expression, + PostfixUnaryExpressionSyntax postfix => postfix.Operand == expression, + ArgumentSyntax argument => !argument.RefKindKeyword.IsKind(SyntaxKind.None), + _ => false + }; + } + private static bool IsReadOnlyConsumer( ArgumentSyntax argument, SemanticModel model, diff --git a/src/E128.Analyzers/README.md b/src/E128.Analyzers/README.md index 14829ad..190cacd 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. @@ -709,6 +709,8 @@ Flags `[GeneratedRegex]` patterns where `\s*` or `\s+` is adjacent to a quantifi Flags `[GeneratedRegex]` patterns with nested quantifiers (e.g., `(.+)+`, `(\w+)+`, `(a*)*`) whose first and last consuming atom can match the same text. These cause exponential backtracking on non-matching input. A repeated group whose leading separator atom is a character the trailing atom cannot match stays silent, such as `(?:/[^/]+)+`. A trailing character class is checked by membership, so `(?:/[^\s:"']+)+` still fires: the class matches the `/`. A bounded `{n,m}` outer repeat and an atomic `(?>...)` group also stay silent. +The code fix applies to a single-atom body, such as `(a+)+` or `(a*)*`. A multi-atom body has no language-preserving rewrite that clears the diagnostic, so no fix is offered for that shape. + ### E128002 — string.Empty Flags empty string literals (`""`). `string.Empty` is clearer and avoids allocation ambiguity. @@ -3220,7 +3222,7 @@ int exitCode = result.ExitStatus.ExitCode; Flags a `MemoryStream` that wraps a string or a byte array and is read only. `StringStream` wraps the string without a copy, and `ReadOnlyMemoryStream` wraps the bytes without a copy. -The rule reads one method body. A write call, a buffer read through `ToArray`, an unknown consumer, a return, or a store into another member keeps the report silent, because the target types reject a write. A compression wrapper (`GZipStream`, `DeflateStream`, or `BrotliStream`) counts as a consumer only when it is constructed with `CompressionMode.Decompress`, because a compress mode or a missing mode writes to the inner stream. The rule carries no code fix for the same reason. +The rule reads one method body. A write call, an assignment or increment to a settable member such as `Position`, a buffer read through `ToArray`, an unknown consumer, a return, or a store into another member keeps the report silent, because the target types reject a write. A compression wrapper (`GZipStream`, `DeflateStream`, or `BrotliStream`) counts as a consumer only when it is constructed with `CompressionMode.Decompress`, because a compress mode or a missing mode writes to the inner stream. The rule carries no code fix for the same reason. ```csharp // Before (warns) @@ -3276,7 +3278,7 @@ HashSet set = [with(StringComparer.OrdinalIgnoreCase), .. items]; Flags an `HttpContent.ReadAsStringAsync` or `HttpContent.ReadAsByteArrayAsync` call that buffers the whole body with no cap. An untrusted server can answer with a body large enough to exhaust the heap. -The rule resolves the read and the bound by symbol, not by name. A bound must precede the read. A bound is a resolved `HttpContent.LoadIntoBufferAsync` call with the `long` cap overload, with or without a trailing `CancellationToken`, or a null-safe `ContentLength` comparison on the same content chain. A plain greater-than guard does not bound the read, because `ContentLength` is `null` for a chunked response and the guard passes through. A `MaxResponseContentBufferSize` setting anywhere in the enclosing type bounds it too. An in-memory content type (`StringContent`, `ByteArrayContent`, `ReadOnlyMemoryContent`, `JsonContent`) needs no bound, because its size is already known. The rule carries no code fix, because the cap value is a caller decision. +The rule resolves the read and the bound by symbol, not by name. A bound must precede the read. A bound is a resolved `HttpContent.LoadIntoBufferAsync` call with the `long` cap overload, with or without a trailing `CancellationToken`, or a null-safe `ContentLength` comparison on the same content chain. A plain greater-than guard does not bound the read, because `ContentLength` is `null` for a chunked response and the guard passes through. A `MaxResponseContentBufferSize` setting does not bound a direct content read, because it caps the client buffer only. An in-memory content type (`StringContent`, `ByteArrayContent`, `ReadOnlyMemoryContent`, `JsonContent`) needs no bound, because its size is already known. The rule carries no code fix, because the cap value is a caller decision. ```csharp // Before (warns) diff --git a/src/E128.Analyzers/Reliability/ProcessLaunchScope.cs b/src/E128.Analyzers/Reliability/ProcessLaunchScope.cs index 3ca5881..6e507d5 100644 --- a/src/E128.Analyzers/Reliability/ProcessLaunchScope.cs +++ b/src/E128.Analyzers/Reliability/ProcessLaunchScope.cs @@ -22,13 +22,30 @@ internal static class ProcessLaunchScope CancellationToken cancellationToken) { var current = expression; + MemberAccessExpressionSyntax? last = null; while (current is MemberAccessExpressionSyntax memberAccess) { + if (memberAccess.Expression is ThisExpressionSyntax or BaseExpressionSyntax) + { + // 'this.field' must resolve to the field. The 'this' symbol is the containing + // type, so every field of the type would otherwise share one root. + return model.GetSymbolInfo(memberAccess, cancellationToken).Symbol; + } + + last = memberAccess; current = memberAccess.Expression; } - return model.GetSymbolInfo(current, cancellationToken).Symbol; + var symbol = model.GetSymbolInfo(current, cancellationToken).Symbol; + if (symbol is INamedTypeSymbol or INamespaceSymbol && last is not null) + { + // A type-qualified chain resolves every static member to the type. The member is + // the root, so two static fields of one type stay distinct. + return model.GetSymbolInfo(last, cancellationToken).Symbol; + } + + return symbol; } /// diff --git a/src/E128.Analyzers/Security/HttpBodyReadWithoutSizeBoundAnalyzer.cs b/src/E128.Analyzers/Security/HttpBodyReadWithoutSizeBoundAnalyzer.cs index 3af3d64..ceef028 100644 --- a/src/E128.Analyzers/Security/HttpBodyReadWithoutSizeBoundAnalyzer.cs +++ b/src/E128.Analyzers/Security/HttpBodyReadWithoutSizeBoundAnalyzer.cs @@ -22,9 +22,10 @@ namespace E128.Analyzers.Security; /// ContentLength comparison on the same content chain. A plain /// greater-than guard does not bound the read, because ContentLength is /// null for a chunked response and the guard passes through. A -/// MaxResponseContentBufferSize setting anywhere in the type bounds it -/// too. An in-memory content type needs no bound, because its size is already known. The -/// rule carries no code fix, because the cap value is a caller decision. +/// MaxResponseContentBufferSize setting does not bound a direct content +/// read, because it caps client buffering only. An in-memory content type needs no bound, +/// because its size is already known. The rule carries no code fix, because the cap value is +/// a caller decision. /// [DiagnosticAnalyzer(LanguageNames.CSharp)] public sealed class HttpBodyReadWithoutSizeBoundAnalyzer : DiagnosticAnalyzer @@ -55,14 +56,10 @@ public sealed class HttpBodyReadWithoutSizeBoundAnalyzer : DiagnosticAnalyzer "ReadAsStringAsync", "ReadAsByteArrayAsync"); - private static readonly ImmutableHashSet TypeBoundNames = ImmutableHashSet.Create( - StringComparer.Ordinal, - "MaxResponseContentBufferSize"); - private static readonly DiagnosticDescriptor Rule = new( DiagnosticId, "HTTP body read without a size bound", - "'{0}' buffers the whole body with no size bound. Call LoadIntoBufferAsync with a cap, add a null-safe ContentLength check before the read, or set MaxResponseContentBufferSize.", + "'{0}' buffers the whole body with no size bound. Call LoadIntoBufferAsync with a cap or add a null-safe ContentLength check before the read.", "E128-Security", DiagnosticSeverity.Warning, true); @@ -152,9 +149,9 @@ private static bool IsInMemoryContent(ITypeSymbol? type, INamedTypeSymbol?[] inM } /// - /// True when a bound precedes the read and dominates it, or when the enclosing type - /// configures the client cap. A bound is resolved by symbol. A bound in another method - /// cannot be proven to apply to this read, so only the client cap is trusted at type scope. + /// True when a bound precedes the read and dominates it. A bound is resolved by symbol. + /// A bound in another method or in another type cannot be proven to apply to this read, + /// so the rule accepts only a bound in the read's own scope. /// private static bool HasSizeBound( InvocationExpressionSyntax read, @@ -165,23 +162,21 @@ private static bool HasSizeBound( CancellationToken cancellationToken) { var scope = BlockScope.GetScope(read); - if (scope is not null) + if (scope is null) { - var readRoot = RootName(read.Expression); - if (readRoot.Length > 0) - { - var contentLength = GetContentLengthProperty(httpContentHeaders); - var boundVariables = CollectBoundVariables(scope, model, contentLength, readRoot, cancellationToken); - if (HasCappedBufferLoad(scope, read, readRoot, model, httpContent, cancellationTokenType, cancellationToken) - || HasContentLengthBound(scope, read, readRoot, model, contentLength, boundVariables, cancellationToken)) - { - return true; - } - } + return false; + } + + var readRoot = RootName(read.Expression); + if (readRoot.Length is 0) + { + return false; } - return read.FirstAncestorOrSelf() is { } type - && Mentions(type, TypeBoundNames); + var contentLength = GetContentLengthProperty(httpContentHeaders); + var boundVariables = CollectBoundVariables(scope, model, contentLength, readRoot, cancellationToken); + return HasCappedBufferLoad(scope, read, readRoot, model, httpContent, cancellationTokenType, cancellationToken) + || HasContentLengthBound(scope, read, readRoot, model, contentLength, boundVariables, cancellationToken); } /// @@ -653,11 +648,4 @@ private static string RootName(ExpressionSyntax? expression) return expression; } - - private static bool Mentions(SyntaxNode scope, ImmutableHashSet names) - { - return scope.DescendantNodes() - .OfType() - .Any(name => names.Contains(name.Identifier.ValueText)); - } } diff --git a/tests/E128.Analyzers.Tests/AbstractBaseWithMembersAnalyzerTests.cs b/tests/E128.Analyzers.Tests/AbstractBaseWithMembersAnalyzerTests.cs index b677dfa..bbd9ee5 100644 --- a/tests/E128.Analyzers.Tests/AbstractBaseWithMembersAnalyzerTests.cs +++ b/tests/E128.Analyzers.Tests/AbstractBaseWithMembersAnalyzerTests.cs @@ -1,8 +1,6 @@ using System.Threading.Tasks; using E128.Analyzers.Design; -using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Testing; using Microsoft.CodeAnalysis.Testing; using Xunit; @@ -15,38 +13,15 @@ private static Task VerifyAsync( DiagnosticResult[]? expected = null, LanguageVersion languageVersion = LanguageVersion.Latest) { - var test = new CSharpAnalyzerTest - { - TestCode = code, - ReferenceAssemblies = ReferenceAssemblies.Net.Net100, - }; - - test.TestState.Sources.Add(UnionTestRuntime.StubSource); - - test.SolutionTransforms.Add((solution, projectId) => - { - var project = solution.GetProject(projectId); - if (project?.ParseOptions is not CSharpParseOptions parseOptions - || project.CompilationOptions is not CSharpCompilationOptions compilationOptions) + return AnalyzerTestRunner.VerifyAsync( + code, + expected, + new AnalyzerTestOptions { - return solution; - } - - var suppressions = compilationOptions.SpecificDiagnosticOptions - .Add("RSEXPERIMENTAL006", ReportDiagnostic.Suppress); - return solution - .WithProjectParseOptions(projectId, parseOptions.WithLanguageVersion(languageVersion)) - .WithProjectCompilationOptions( - projectId, - compilationOptions.WithSpecificDiagnosticOptions(suppressions)); - }); - - if (expected is not null) - { - test.ExpectedDiagnostics.AddRange(expected); - } - - return test.RunAsync(TestContext.Current.CancellationToken); + LanguageVersion = languageVersion, + Sources = [UnionTestRuntime.StubSource], + SuppressedDiagnosticIds = ["RSEXPERIMENTAL006"], + }); } [Fact] diff --git a/tests/E128.Analyzers.Tests/AbstractBaseWithMembersCodeFixTests.cs b/tests/E128.Analyzers.Tests/AbstractBaseWithMembersCodeFixTests.cs index c589f03..9aa490b 100644 --- a/tests/E128.Analyzers.Tests/AbstractBaseWithMembersCodeFixTests.cs +++ b/tests/E128.Analyzers.Tests/AbstractBaseWithMembersCodeFixTests.cs @@ -1,8 +1,6 @@ using System.Threading.Tasks; using E128.Analyzers.Design; -using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Testing; using Microsoft.CodeAnalysis.Testing; using Xunit; @@ -12,37 +10,17 @@ public sealed class AbstractBaseWithMembersCodeFixTests { private static Task RunAsync(string code, string fixedCode) { - var test = new CSharpCodeFixTest - { - TestCode = code, - FixedCode = fixedCode, - ReferenceAssemblies = ReferenceAssemblies.Net.Net100, - NumberOfFixAllIterations = 1, - CodeFixTestBehaviors = CodeFixTestBehaviors.SkipLocalDiagnosticCheck, - }; - - test.TestState.Sources.Add(UnionTestRuntime.StubSource); - test.FixedState.Sources.Add(UnionTestRuntime.StubSource); - - test.SolutionTransforms.Add(static (solution, projectId) => - { - var project = solution.GetProject(projectId); - if (project?.ParseOptions is not CSharpParseOptions parseOptions - || project.CompilationOptions is not CSharpCompilationOptions compilationOptions) + return CodeFixTestRunner.RunAsync( + code, + fixedCode, + behaviors: CodeFixTestBehaviors.SkipLocalDiagnosticCheck, + options: new CodeFixTestOptions { - return solution; - } - - var suppressions = compilationOptions.SpecificDiagnosticOptions - .Add("RSEXPERIMENTAL006", ReportDiagnostic.Suppress); - return solution - .WithProjectParseOptions(projectId, parseOptions.WithLanguageVersion(LanguageVersion.Preview)) - .WithProjectCompilationOptions( - projectId, - compilationOptions.WithSpecificDiagnosticOptions(suppressions)); - }); - - return test.RunAsync(TestContext.Current.CancellationToken); + FixAllIterations = 1, + Sources = [UnionTestRuntime.StubSource], + LanguageVersion = LanguageVersion.Preview, + SuppressedDiagnosticIds = ["RSEXPERIMENTAL006"], + }); } [Fact] diff --git a/tests/E128.Analyzers.Tests/AnalyzerTestOptions.cs b/tests/E128.Analyzers.Tests/AnalyzerTestOptions.cs index 9aaf44b..e121e7f 100644 --- a/tests/E128.Analyzers.Tests/AnalyzerTestOptions.cs +++ b/tests/E128.Analyzers.Tests/AnalyzerTestOptions.cs @@ -1,4 +1,6 @@ using System.Collections.Generic; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Testing; namespace E128.Analyzers.Tests; @@ -22,5 +24,11 @@ internal sealed record AnalyzerTestOptions internal IEnumerable<(string Name, string Content)>? AdditionalFiles { get; init; } + internal IEnumerable? AdditionalReferences { get; init; } + internal IEnumerable? Sources { get; init; } + + internal LanguageVersion? LanguageVersion { get; init; } + + internal IEnumerable? SuppressedDiagnosticIds { get; init; } } diff --git a/tests/E128.Analyzers.Tests/AnalyzerTestRunner.cs b/tests/E128.Analyzers.Tests/AnalyzerTestRunner.cs index 1ce392f..bcbf04c 100644 --- a/tests/E128.Analyzers.Tests/AnalyzerTestRunner.cs +++ b/tests/E128.Analyzers.Tests/AnalyzerTestRunner.cs @@ -1,4 +1,6 @@ +using System.Collections.Generic; using System.Threading.Tasks; +using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Testing; using Microsoft.CodeAnalysis.Diagnostics; @@ -27,46 +29,7 @@ internal static Task VerifyAsync( MarkupOptions = options.MarkupOptions }; - if (options.CompilerDiagnostics is { } diagnostics) - { - test.CompilerDiagnostics = diagnostics; - } - - if (options.TestBehaviors is not TestBehaviors.None) - { - test.TestBehaviors = options.TestBehaviors; - } - - if (options.AllowUnsafe) - { - test.SolutionTransforms.Add(static (solution, projectId) => - solution.GetProject(projectId)?.CompilationOptions is CSharpCompilationOptions compilationOptions - ? solution.WithProjectCompilationOptions( - projectId, - compilationOptions.WithAllowUnsafe(true)) - : solution); - } - - if (options.AnalyzerConfig is { } config) - { - test.TestState.AnalyzerConfigFiles.Add((config.Name, config.Content)); - } - - if (options.AdditionalFiles is not null) - { - foreach (var (name, content) in options.AdditionalFiles) - { - test.TestState.AdditionalFiles.Add((name, SourceText.From(content))); - } - } - - if (options.Sources is not null) - { - foreach (var source in options.Sources) - { - test.TestState.Sources.Add(source); - } - } + Configure(test, options); if (expected is not null) { @@ -105,4 +68,105 @@ internal static Task VerifyAsync( { return VerifyAsync(code, [first, second], options); } + + private static void Configure( + CSharpAnalyzerTest test, + AnalyzerTestOptions options) + where TAnalyzer : DiagnosticAnalyzer, new() + { + if (options.CompilerDiagnostics is { } diagnostics) + { + test.CompilerDiagnostics = diagnostics; + } + + if (options.TestBehaviors is not TestBehaviors.None) + { + test.TestBehaviors = options.TestBehaviors; + } + + if (options.AllowUnsafe) + { + test.SolutionTransforms.Add(AllowUnsafe); + } + + if (options.AnalyzerConfig is { } config) + { + test.TestState.AnalyzerConfigFiles.Add((config.Name, config.Content)); + } + + AddAdditionalFiles(test.TestState, options.AdditionalFiles); + AddAdditionalReferences(test.TestState, options.AdditionalReferences); + AddCompilationSettings(test, options); + AddSources(test.TestState, options.Sources); + } + + private static Solution AllowUnsafe(Solution solution, ProjectId projectId) + { + return solution.GetProject(projectId)?.CompilationOptions is CSharpCompilationOptions compilationOptions + ? solution.WithProjectCompilationOptions( + projectId, + compilationOptions.WithAllowUnsafe(true)) + : solution; + } + + private static void AddAdditionalFiles( + SolutionState state, + IEnumerable<(string Name, string Content)>? additionalFiles) + { + if (additionalFiles is null) + { + return; + } + + foreach (var (name, content) in additionalFiles) + { + state.AdditionalFiles.Add((name, SourceText.From(content))); + } + } + + private static void AddAdditionalReferences( + SolutionState state, + IEnumerable? additionalReferences) + { + if (additionalReferences is null) + { + return; + } + + foreach (var reference in additionalReferences) + { + state.AdditionalReferences.Add(reference); + } + } + + private static void AddCompilationSettings( + CSharpAnalyzerTest test, + AnalyzerTestOptions options) + where TAnalyzer : DiagnosticAnalyzer, new() + { + if (options.LanguageVersion is null && options.SuppressedDiagnosticIds is null) + { + return; + } + + test.SolutionTransforms.Add((solution, projectId) => + CompilationSettings.Apply( + solution, + projectId, + options.LanguageVersion, + options.SuppressedDiagnosticIds)); + } + + private static void AddSources(SolutionState state, IEnumerable? sources) + { + if (sources is null) + { + return; + } + + foreach (var source in sources) + { + state.Sources.Add(source); + } + } } diff --git a/tests/E128.Analyzers.Tests/CodeFixTestOptions.cs b/tests/E128.Analyzers.Tests/CodeFixTestOptions.cs new file mode 100644 index 0000000..3cc361e --- /dev/null +++ b/tests/E128.Analyzers.Tests/CodeFixTestOptions.cs @@ -0,0 +1,21 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Testing; + +namespace E128.Analyzers.Tests; + +/// +/// The non-default settings for one code fix test run. Every value is optional. +/// +internal sealed record CodeFixTestOptions +{ + internal int? FixAllIterations { get; init; } + + internal IEnumerable? FixedExpected { get; init; } + + internal IEnumerable? Sources { get; init; } + + internal LanguageVersion? LanguageVersion { get; init; } + + internal IEnumerable? SuppressedDiagnosticIds { get; init; } +} diff --git a/tests/E128.Analyzers.Tests/CodeFixTestRunner.cs b/tests/E128.Analyzers.Tests/CodeFixTestRunner.cs index da42421..121ba6c 100644 --- a/tests/E128.Analyzers.Tests/CodeFixTestRunner.cs +++ b/tests/E128.Analyzers.Tests/CodeFixTestRunner.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; @@ -18,13 +19,14 @@ internal static Task RunAsync( string source, string fixedCode, ReferenceAssemblies? references = null, - int? fixAllIterations = null, DiagnosticResult[]? expected = null, MarkupOptions markupOptions = MarkupOptions.None, - CodeFixTestBehaviors behaviors = CodeFixTestBehaviors.None) + CodeFixTestBehaviors behaviors = CodeFixTestBehaviors.None, + CodeFixTestOptions? options = null) where TAnalyzer : DiagnosticAnalyzer, new() where TFixer : CodeFixProvider, new() { + options ??= new CodeFixTestOptions(); var test = new CSharpCodeFixTest { TestCode = source, @@ -38,19 +40,73 @@ internal static Task RunAsync( test.CodeFixTestBehaviors = behaviors; } - if (fixAllIterations is not null) - { - test.NumberOfFixAllIterations = fixAllIterations.Value; - } - if (expected is not null) { test.ExpectedDiagnostics.AddRange(expected); } + ApplyOptions(test, options); + return test.RunAsync(Xunit.TestContext.Current.CancellationToken); } + private static void ApplyOptions( + CSharpCodeFixTest test, + CodeFixTestOptions options) + where TAnalyzer : DiagnosticAnalyzer, new() + where TFixer : CodeFixProvider, new() + { + if (options.FixAllIterations is { } iterations) + { + test.NumberOfFixAllIterations = iterations; + } + + if (options.FixedExpected is not null) + { + test.FixedState.ExpectedDiagnostics.AddRange(options.FixedExpected); + } + + AddSources(test, options.Sources); + AddCompilationSettings(test, options); + } + + private static void AddSources( + CSharpCodeFixTest test, + IEnumerable? sources) + where TAnalyzer : DiagnosticAnalyzer, new() + where TFixer : CodeFixProvider, new() + { + if (sources is null) + { + return; + } + + foreach (var extraSource in sources) + { + test.TestState.Sources.Add(extraSource); + test.FixedState.Sources.Add(extraSource); + } + } + + private static void AddCompilationSettings( + CSharpCodeFixTest test, + CodeFixTestOptions options) + where TAnalyzer : DiagnosticAnalyzer, new() + where TFixer : CodeFixProvider, new() + { + if (options.LanguageVersion is null && options.SuppressedDiagnosticIds is null) + { + return; + } + + test.SolutionTransforms.Add((solution, projectId) => + CompilationSettings.Apply( + solution, + projectId, + options.LanguageVersion, + options.SuppressedDiagnosticIds)); + } + /// /// Runs a rewrite that keeps the diagnostic. Markup in the fixed code supplies the /// diagnostics that survive the rewrite. diff --git a/tests/E128.Analyzers.Tests/ComparerSetConstructionAnalyzerTests.cs b/tests/E128.Analyzers.Tests/ComparerSetConstructionAnalyzerTests.cs index d5d24e6..3f47b86 100644 --- a/tests/E128.Analyzers.Tests/ComparerSetConstructionAnalyzerTests.cs +++ b/tests/E128.Analyzers.Tests/ComparerSetConstructionAnalyzerTests.cs @@ -188,4 +188,26 @@ void M(string[] items) } """); } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheCreationIsTargetTyped() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System; + using System.Collections.Generic; + + class C + { + void M(string[] items) + { + HashSet set = {|E128226:new(StringComparer.OrdinalIgnoreCase)|}; + foreach (var item in items) + { + set.Add(item); + } + } + } + """); + } } diff --git a/tests/E128.Analyzers.Tests/CompilationSettings.cs b/tests/E128.Analyzers.Tests/CompilationSettings.cs new file mode 100644 index 0000000..9ecf171 --- /dev/null +++ b/tests/E128.Analyzers.Tests/CompilationSettings.cs @@ -0,0 +1,46 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; + +namespace E128.Analyzers.Tests; + +/// +/// Solution transform shared by the analyzer and code fix runners. One place applies the +/// language version and the diagnostic suppressions that a rule test needs. +/// +internal static class CompilationSettings +{ + internal static Solution Apply( + Solution solution, + ProjectId projectId, + LanguageVersion? languageVersion, + IEnumerable? suppressedDiagnosticIds) + { + var project = solution.GetProject(projectId); + if (project?.ParseOptions is not CSharpParseOptions parseOptions) + { + return solution; + } + + if (languageVersion is { } version) + { + solution = solution.WithProjectParseOptions(projectId, parseOptions.WithLanguageVersion(version)); + } + + if (suppressedDiagnosticIds is null + || project.CompilationOptions is not CSharpCompilationOptions compilationOptions) + { + return solution; + } + + var suppressions = compilationOptions.SpecificDiagnosticOptions; + foreach (var id in suppressedDiagnosticIds) + { + suppressions = suppressions.Add(id, ReportDiagnostic.Suppress); + } + + return solution.WithProjectCompilationOptions( + projectId, + compilationOptions.WithSpecificDiagnosticOptions(suppressions)); + } +} diff --git a/tests/E128.Analyzers.Tests/ComplexityCeilingE128CodeFixTests.cs b/tests/E128.Analyzers.Tests/ComplexityCeilingE128CodeFixTests.cs index 844c99f..a9b5ebc 100644 --- a/tests/E128.Analyzers.Tests/ComplexityCeilingE128CodeFixTests.cs +++ b/tests/E128.Analyzers.Tests/ComplexityCeilingE128CodeFixTests.cs @@ -131,8 +131,8 @@ private static Task VerifyMembershipAsync(string source, string fixedCode, param return CodeFixTestRunner.RunAsync( source, fixedCode, - fixAllIterations: 1, - expected: expected); + expected: expected, + options: new CodeFixTestOptions { FixAllIterations = 1 }); } private static Task VerifyNoMembershipAsync(string source, params DiagnosticResult[] expected) diff --git a/tests/E128.Analyzers.Tests/GeneratedRegexNestedE128CodeFixTests.cs b/tests/E128.Analyzers.Tests/GeneratedRegexNestedE128CodeFixTests.cs index 8275464..2ba2be0 100644 --- a/tests/E128.Analyzers.Tests/GeneratedRegexNestedE128CodeFixTests.cs +++ b/tests/E128.Analyzers.Tests/GeneratedRegexNestedE128CodeFixTests.cs @@ -118,9 +118,9 @@ partial class C [Fact] [Trait("Category", "CI")] - public Task NestedQuantifier_MultiAtomBody_ReplacesOuterQuantifierWithUnboundedBrace() + public Task NestedQuantifier_MultiAtomBody_NoFixOffered() { - return VerifyFixAsync( + return CodeFixTestRunner.NoFixAsync( $$""" using System.Text.RegularExpressions; partial class C @@ -129,17 +129,7 @@ partial class C private static partial Regex DigitsOnly(); {{PartialImpl}} } - """, - $$""" - using System.Text.RegularExpressions; - partial class C - { - [{|E128014:GeneratedRegex(@"(?:\w\w+){1,}", RegexOptions.None, 1000)|}] - private static partial Regex DigitsOnly(); - {{PartialImpl}} - } - """, - keepDiagnostic: true); + """); } [Fact] diff --git a/tests/E128.Analyzers.Tests/HandRolledProcessCaptureAnalyzerTests.cs b/tests/E128.Analyzers.Tests/HandRolledProcessCaptureAnalyzerTests.cs index c926486..d6602ff 100644 --- a/tests/E128.Analyzers.Tests/HandRolledProcessCaptureAnalyzerTests.cs +++ b/tests/E128.Analyzers.Tests/HandRolledProcessCaptureAnalyzerTests.cs @@ -217,19 +217,21 @@ void M(string file) [Fact] [Trait("Category", "CI")] - public Task Silent_WhenTheStreamOfAnotherProcessIsRead() + public Task Silent_WhenTheConfiguredProcessIsAFieldAndAnotherFieldWaits() { return AnalyzerTestRunner.VerifyAsync(""" using System.Diagnostics; class C { - void M(string file) + private readonly Process _configured = new(); + private readonly Process _waited = new(); + + void M() { - var info = new ProcessStartInfo(file) { RedirectStandardOutput = true }; - using var process = Process.Start(info); - using var other = Process.Start(info); - string output = other.StandardOutput.ReadToEnd(); - process.WaitForExit(); + this._configured.StartInfo.RedirectStandardOutput = true; + this._configured.Start(); + string output = this._waited.StandardOutput.ReadToEnd(); + this._waited.WaitForExit(); } } """); diff --git a/tests/E128.Analyzers.Tests/HardcodedSecretAnalyzerTests.cs b/tests/E128.Analyzers.Tests/HardcodedSecretAnalyzerTests.cs index e9d4ef8..051a4e5 100644 --- a/tests/E128.Analyzers.Tests/HardcodedSecretAnalyzerTests.cs +++ b/tests/E128.Analyzers.Tests/HardcodedSecretAnalyzerTests.cs @@ -5,7 +5,6 @@ using E128.Analyzers.Security; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Testing; using Microsoft.CodeAnalysis.Testing; using Xunit; @@ -357,30 +356,31 @@ class C public async Task TestCompilationWithTwoXunitReferences_Silent() { var references = await ReferenceAssemblies.Net.Net100.ResolveAsync(LanguageNames.CSharp, CancellationToken.None); - var test = new CSharpAnalyzerTest - { - TestCode = """ - class FactAttribute : System.Attribute { } - class C - { - const string AdminPassword = "hunter2hunter2"; - - [Fact] - void T() { } - } - """, - ReferenceAssemblies = ReferenceAssemblies.Net.Net100 - }; - test.TestState.AdditionalReferences.Add(EmitStub( - "XunitStubOne", - "namespace Xunit { public sealed class FactAttribute { } }", - references)); - test.TestState.AdditionalReferences.Add(EmitStub( - "XunitStubTwo", - "namespace Xunit { public sealed class FactAttribute { } }", - references)); - - await test.RunAsync(TestContext.Current.CancellationToken); + await AnalyzerTestRunner.VerifyAsync( + """ + class FactAttribute : System.Attribute { } + class C + { + const string AdminPassword = "hunter2hunter2"; + + [Fact] + void T() { } + } + """, + options: new AnalyzerTestOptions + { + AdditionalReferences = + [ + EmitStub( + "XunitStubOne", + "namespace Xunit { public sealed class FactAttribute { } }", + references), + EmitStub( + "XunitStubTwo", + "namespace Xunit { public sealed class FactAttribute { } }", + references), + ], + }); } /// @@ -391,25 +391,26 @@ void T() { } public async Task TestCompilationWithNUnitReference_Silent() { var references = await ReferenceAssemblies.Net.Net100.ResolveAsync(LanguageNames.CSharp, CancellationToken.None); - var test = new CSharpAnalyzerTest - { - TestCode = """ - class C - { - const string AdminPassword = "hunter2hunter2"; - - [NUnit.Framework.Test] - void T() { } - } - """, - ReferenceAssemblies = ReferenceAssemblies.Net.Net100 - }; - test.TestState.AdditionalReferences.Add(EmitStub( - "NUnitStub", - "namespace NUnit.Framework { public sealed class TestAttribute : System.Attribute { } }", - references)); - - await test.RunAsync(TestContext.Current.CancellationToken); + await AnalyzerTestRunner.VerifyAsync( + """ + class C + { + const string AdminPassword = "hunter2hunter2"; + + [NUnit.Framework.Test] + void T() { } + } + """, + options: new AnalyzerTestOptions + { + AdditionalReferences = + [ + EmitStub( + "NUnitStub", + "namespace NUnit.Framework { public sealed class TestAttribute : System.Attribute { } }", + references), + ], + }); } [Fact] @@ -417,25 +418,26 @@ void T() { } public async Task TestCompilationWithMsTestReference_Silent() { var references = await ReferenceAssemblies.Net.Net100.ResolveAsync(LanguageNames.CSharp, CancellationToken.None); - var test = new CSharpAnalyzerTest - { - TestCode = """ - class C - { - const string AdminPassword = "hunter2hunter2"; - - [Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod] - void T() { } - } - """, - ReferenceAssemblies = ReferenceAssemblies.Net.Net100 - }; - test.TestState.AdditionalReferences.Add(EmitStub( - "MsTestStub", - "namespace Microsoft.VisualStudio.TestTools.UnitTesting { public sealed class TestMethodAttribute : System.Attribute { } }", - references)); - - await test.RunAsync(TestContext.Current.CancellationToken); + await AnalyzerTestRunner.VerifyAsync( + """ + class C + { + const string AdminPassword = "hunter2hunter2"; + + [Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod] + void T() { } + } + """, + options: new AnalyzerTestOptions + { + AdditionalReferences = + [ + EmitStub( + "MsTestStub", + "namespace Microsoft.VisualStudio.TestTools.UnitTesting { public sealed class TestMethodAttribute : System.Attribute { } }", + references), + ], + }); } private static PortableExecutableReference EmitStub( diff --git a/tests/E128.Analyzers.Tests/HttpBodyReadWithoutSizeBoundAnalyzerTests.cs b/tests/E128.Analyzers.Tests/HttpBodyReadWithoutSizeBoundAnalyzerTests.cs index 18d217a..34f5f59 100644 --- a/tests/E128.Analyzers.Tests/HttpBodyReadWithoutSizeBoundAnalyzerTests.cs +++ b/tests/E128.Analyzers.Tests/HttpBodyReadWithoutSizeBoundAnalyzerTests.cs @@ -263,7 +263,7 @@ async Task M(HttpResponseMessage response, CancellationToken token) [Fact] [Trait("Category", "CI")] - public Task Silent_WhenTheTypeSetsMaxResponseContentBufferSize() + public Task Reports_WhenTheClientCapIsSetOnAnUnrelatedClient() { return AnalyzerTestRunner.VerifyAsync(""" using System.Net.Http; @@ -276,7 +276,7 @@ class C async Task M(HttpResponseMessage response) { _ = await _client.SendAsync(new HttpRequestMessage()); - _ = await response.Content.ReadAsStringAsync(); + _ = await {|E128227:response.Content.ReadAsStringAsync()|}; } } """); diff --git a/tests/E128.Analyzers.Tests/ImmutableArrayDefaultCodeFixTests.cs b/tests/E128.Analyzers.Tests/ImmutableArrayDefaultCodeFixTests.cs index 0423c87..088b015 100644 --- a/tests/E128.Analyzers.Tests/ImmutableArrayDefaultCodeFixTests.cs +++ b/tests/E128.Analyzers.Tests/ImmutableArrayDefaultCodeFixTests.cs @@ -12,8 +12,8 @@ private static Task VerifyFixAsync(string source, string fixedCode) return CodeFixTestRunner.RunAsync( source, fixedCode, - fixAllIterations: 1, - behaviors: CodeFixTestBehaviors.SkipLocalDiagnosticCheck); + behaviors: CodeFixTestBehaviors.SkipLocalDiagnosticCheck, + options: new CodeFixTestOptions { FixAllIterations = 1 }); } [Fact] diff --git a/tests/E128.Analyzers.Tests/LowValueTestCodeFixTests.cs b/tests/E128.Analyzers.Tests/LowValueTestCodeFixTests.cs index 4ac8c33..9139cde 100644 --- a/tests/E128.Analyzers.Tests/LowValueTestCodeFixTests.cs +++ b/tests/E128.Analyzers.Tests/LowValueTestCodeFixTests.cs @@ -30,8 +30,8 @@ private static Task VerifyAsync(string source, string fixedCode) source, fixedCode, references: Net100WithXunit, - fixAllIterations: 1, - behaviors: CodeFixTestBehaviors.SkipLocalDiagnosticCheck); + behaviors: CodeFixTestBehaviors.SkipLocalDiagnosticCheck, + options: new CodeFixTestOptions { FixAllIterations = 1 }); } [Fact] diff --git a/tests/E128.Analyzers.Tests/MemberlessAbstractBaseAnalyzerTests.cs b/tests/E128.Analyzers.Tests/MemberlessAbstractBaseAnalyzerTests.cs index 0d8d995..78ab1f7 100644 --- a/tests/E128.Analyzers.Tests/MemberlessAbstractBaseAnalyzerTests.cs +++ b/tests/E128.Analyzers.Tests/MemberlessAbstractBaseAnalyzerTests.cs @@ -1,8 +1,6 @@ using System.Threading.Tasks; using E128.Analyzers.Design; -using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Testing; using Microsoft.CodeAnalysis.Testing; using Xunit; @@ -15,38 +13,15 @@ private static Task VerifyAsync( DiagnosticResult[]? expected = null, LanguageVersion languageVersion = LanguageVersion.Latest) { - var test = new CSharpAnalyzerTest - { - TestCode = code, - ReferenceAssemblies = ReferenceAssemblies.Net.Net100, - }; - - test.TestState.Sources.Add(UnionTestRuntime.StubSource); - - test.SolutionTransforms.Add((solution, projectId) => - { - var project = solution.GetProject(projectId); - if (project?.ParseOptions is not CSharpParseOptions parseOptions - || project.CompilationOptions is not CSharpCompilationOptions compilationOptions) - { - return solution; - } - - var suppressions = compilationOptions.SpecificDiagnosticOptions - .Add("RSEXPERIMENTAL006", ReportDiagnostic.Suppress); - return solution - .WithProjectParseOptions(projectId, parseOptions.WithLanguageVersion(languageVersion)) - .WithProjectCompilationOptions( - projectId, - compilationOptions.WithSpecificDiagnosticOptions(suppressions)); - }); - - if (expected is not null) - { - test.ExpectedDiagnostics.AddRange(expected); - } - - return test.RunAsync(TestContext.Current.CancellationToken); + return AnalyzerTestRunner.VerifyAsync( + code, + expected, + new AnalyzerTestOptions + { + LanguageVersion = languageVersion, + Sources = [UnionTestRuntime.StubSource], + SuppressedDiagnosticIds = ["RSEXPERIMENTAL006"], + }); } [Fact] diff --git a/tests/E128.Analyzers.Tests/MemberlessAbstractBaseCodeFixTests.cs b/tests/E128.Analyzers.Tests/MemberlessAbstractBaseCodeFixTests.cs index bfc127a..2e7e2f5 100644 --- a/tests/E128.Analyzers.Tests/MemberlessAbstractBaseCodeFixTests.cs +++ b/tests/E128.Analyzers.Tests/MemberlessAbstractBaseCodeFixTests.cs @@ -1,8 +1,6 @@ using System.Threading.Tasks; using E128.Analyzers.Design; -using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Testing; using Microsoft.CodeAnalysis.Testing; using Xunit; @@ -12,42 +10,18 @@ public sealed class MemberlessAbstractBaseCodeFixTests { private static Task RunAsync(string code, string fixedCode, DiagnosticResult[]? expected = null) { - var test = new CSharpCodeFixTest - { - TestCode = code, - FixedCode = fixedCode, - ReferenceAssemblies = ReferenceAssemblies.Net.Net100, - NumberOfFixAllIterations = 1, - CodeFixTestBehaviors = CodeFixTestBehaviors.SkipLocalDiagnosticCheck, - }; - - test.TestState.Sources.Add(UnionTestRuntime.StubSource); - test.FixedState.Sources.Add(UnionTestRuntime.StubSource); - - test.SolutionTransforms.Add(static (solution, projectId) => - { - var project = solution.GetProject(projectId); - if (project?.ParseOptions is not CSharpParseOptions parseOptions - || project.CompilationOptions is not CSharpCompilationOptions compilationOptions) + return CodeFixTestRunner.RunAsync( + code, + fixedCode, + expected: expected, + behaviors: CodeFixTestBehaviors.SkipLocalDiagnosticCheck, + options: new CodeFixTestOptions { - return solution; - } - - var suppressions = compilationOptions.SpecificDiagnosticOptions - .Add("RSEXPERIMENTAL006", ReportDiagnostic.Suppress); - return solution - .WithProjectParseOptions(projectId, parseOptions.WithLanguageVersion(LanguageVersion.Preview)) - .WithProjectCompilationOptions( - projectId, - compilationOptions.WithSpecificDiagnosticOptions(suppressions)); - }); - - if (expected is not null) - { - test.ExpectedDiagnostics.AddRange(expected); - } - - return test.RunAsync(TestContext.Current.CancellationToken); + FixAllIterations = 1, + Sources = [UnionTestRuntime.StubSource], + LanguageVersion = LanguageVersion.Preview, + SuppressedDiagnosticIds = ["RSEXPERIMENTAL006"], + }); } [Fact] diff --git a/tests/E128.Analyzers.Tests/ReadOnlyMemoryStreamAnalyzerTests.cs b/tests/E128.Analyzers.Tests/ReadOnlyMemoryStreamAnalyzerTests.cs index 2a35767..0e6ad28 100644 --- a/tests/E128.Analyzers.Tests/ReadOnlyMemoryStreamAnalyzerTests.cs +++ b/tests/E128.Analyzers.Tests/ReadOnlyMemoryStreamAnalyzerTests.cs @@ -231,4 +231,41 @@ void M(byte[] data) } """); } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenPositionIsAssigned() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.IO; + + class C + { + void M(byte[] data) + { + using var stream = new MemoryStream(data); + stream.Position = 0; + using var reader = new StreamReader(stream); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheCreationIsTargetTyped() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.IO; + + class C + { + void M(byte[] data) + { + MemoryStream stream = {|E128224:new(data)|}; + using var reader = new StreamReader(stream); + } + } + """); + } } diff --git a/tests/E128.Analyzers.Tests/SupportedDiagnosticsCoverageTests.cs b/tests/E128.Analyzers.Tests/SupportedDiagnosticsCoverageTests.cs index 3ba2451..a8fcb2f 100644 --- a/tests/E128.Analyzers.Tests/SupportedDiagnosticsCoverageTests.cs +++ b/tests/E128.Analyzers.Tests/SupportedDiagnosticsCoverageTests.cs @@ -13,8 +13,7 @@ public sealed class SupportedDiagnosticsCoverageTests /// /// Reflection is required: this sweep enumerates every analyzer type and its /// DiagnosticDescriptor fields, so a descriptor that never reaches - /// SupportedDiagnostics fails a test instead of shipping silent. See the - /// GeneratedRegexAnalyzer 2.9.7 audit in plans/roadmap.md. The reflection + /// SupportedDiagnostics fails a test instead of shipping silent. The reflection /// lives in helper methods, not in the test body, because E128090 bans /// reflection inside test methods. /// diff --git a/tests/E128.Analyzers.Tests/UnionSwitchDiscardArmAnalyzerTests.cs b/tests/E128.Analyzers.Tests/UnionSwitchDiscardArmAnalyzerTests.cs index 8d7cc5d..445237e 100644 --- a/tests/E128.Analyzers.Tests/UnionSwitchDiscardArmAnalyzerTests.cs +++ b/tests/E128.Analyzers.Tests/UnionSwitchDiscardArmAnalyzerTests.cs @@ -1,8 +1,6 @@ using System.Threading.Tasks; using E128.Analyzers.Design; -using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Testing; using Microsoft.CodeAnalysis.Testing; using Xunit; @@ -12,38 +10,15 @@ public sealed class UnionSwitchDiscardArmAnalyzerTests { private static Task VerifyAsync(string code, DiagnosticResult[]? expected = null) { - var test = new CSharpAnalyzerTest - { - TestCode = code, - ReferenceAssemblies = ReferenceAssemblies.Net.Net100, - }; - - test.SolutionTransforms.Add(static (solution, projectId) => - { - var project = solution.GetProject(projectId); - if (project?.ParseOptions is not CSharpParseOptions parseOptions - || project.CompilationOptions is not CSharpCompilationOptions compilationOptions) + return AnalyzerTestRunner.VerifyAsync( + code, + expected, + new AnalyzerTestOptions { - return solution; - } - - var suppressions = compilationOptions.SpecificDiagnosticOptions - .Add("RSEXPERIMENTAL006", ReportDiagnostic.Suppress); - return solution - .WithProjectParseOptions(projectId, parseOptions.WithLanguageVersion(LanguageVersion.Preview)) - .WithProjectCompilationOptions( - projectId, - compilationOptions.WithSpecificDiagnosticOptions(suppressions)); - }); - - test.TestState.Sources.Add(UnionTestRuntime.StubSource); - - if (expected is not null) - { - test.ExpectedDiagnostics.AddRange(expected); - } - - return test.RunAsync(TestContext.Current.CancellationToken); + LanguageVersion = LanguageVersion.Preview, + Sources = [UnionTestRuntime.StubSource], + SuppressedDiagnosticIds = ["RSEXPERIMENTAL006"], + }); } private const string UnionSource = diff --git a/tests/E128.Analyzers.Tests/UnionSwitchDiscardArmCodeFixTests.cs b/tests/E128.Analyzers.Tests/UnionSwitchDiscardArmCodeFixTests.cs index 7eaa244..501176a 100644 --- a/tests/E128.Analyzers.Tests/UnionSwitchDiscardArmCodeFixTests.cs +++ b/tests/E128.Analyzers.Tests/UnionSwitchDiscardArmCodeFixTests.cs @@ -2,7 +2,6 @@ using E128.Analyzers.Design; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Testing; using Microsoft.CodeAnalysis.Testing; using Xunit; @@ -16,45 +15,17 @@ private static Task RunAsync( DiagnosticResult[]? expected = null, DiagnosticResult[]? fixedExpected = null) { - var test = new CSharpCodeFixTest - { - TestCode = code, - FixedCode = fixedCode, - ReferenceAssemblies = ReferenceAssemblies.Net.Net100, - }; - - test.TestState.Sources.Add(UnionTestRuntime.StubSource); - test.FixedState.Sources.Add(UnionTestRuntime.StubSource); - - test.SolutionTransforms.Add(static (solution, projectId) => - { - var project = solution.GetProject(projectId); - if (project?.ParseOptions is not CSharpParseOptions parseOptions - || project.CompilationOptions is not CSharpCompilationOptions compilationOptions) + return CodeFixTestRunner.RunAsync( + code, + fixedCode, + expected: expected, + options: new CodeFixTestOptions { - return solution; - } - - var suppressions = compilationOptions.SpecificDiagnosticOptions - .Add("RSEXPERIMENTAL006", ReportDiagnostic.Suppress); - return solution - .WithProjectParseOptions(projectId, parseOptions.WithLanguageVersion(LanguageVersion.Preview)) - .WithProjectCompilationOptions( - projectId, - compilationOptions.WithSpecificDiagnosticOptions(suppressions)); - }); - - if (expected is not null) - { - test.ExpectedDiagnostics.AddRange(expected); - } - - if (fixedExpected is not null) - { - test.FixedState.ExpectedDiagnostics.AddRange(fixedExpected); - } - - return test.RunAsync(TestContext.Current.CancellationToken); + FixedExpected = fixedExpected, + Sources = [UnionTestRuntime.StubSource], + LanguageVersion = LanguageVersion.Preview, + SuppressedDiagnosticIds = ["RSEXPERIMENTAL006"], + }); } private const string UnionSource = diff --git a/tests/E128.Analyzers.Tests/UnionValueReadAnalyzerTests.cs b/tests/E128.Analyzers.Tests/UnionValueReadAnalyzerTests.cs index 31d8152..b65ba76 100644 --- a/tests/E128.Analyzers.Tests/UnionValueReadAnalyzerTests.cs +++ b/tests/E128.Analyzers.Tests/UnionValueReadAnalyzerTests.cs @@ -1,8 +1,6 @@ using System.Threading.Tasks; using E128.Analyzers.Design; -using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Testing; using Microsoft.CodeAnalysis.Testing; using Xunit; @@ -12,38 +10,15 @@ public sealed class UnionValueReadAnalyzerTests { private static Task VerifyAsync(string code, DiagnosticResult[]? expected = null) { - var test = new CSharpAnalyzerTest - { - TestCode = code, - ReferenceAssemblies = ReferenceAssemblies.Net.Net100, - }; - - test.SolutionTransforms.Add(static (solution, projectId) => - { - var project = solution.GetProject(projectId); - if (project?.ParseOptions is not CSharpParseOptions parseOptions - || project.CompilationOptions is not CSharpCompilationOptions compilationOptions) + return AnalyzerTestRunner.VerifyAsync( + code, + expected, + new AnalyzerTestOptions { - return solution; - } - - var suppressions = compilationOptions.SpecificDiagnosticOptions - .Add("RSEXPERIMENTAL006", ReportDiagnostic.Suppress); - return solution - .WithProjectParseOptions(projectId, parseOptions.WithLanguageVersion(LanguageVersion.Preview)) - .WithProjectCompilationOptions( - projectId, - compilationOptions.WithSpecificDiagnosticOptions(suppressions)); - }); - - test.TestState.Sources.Add(UnionTestRuntime.StubSource); - - if (expected is not null) - { - test.ExpectedDiagnostics.AddRange(expected); - } - - return test.RunAsync(TestContext.Current.CancellationToken); + LanguageVersion = LanguageVersion.Preview, + Sources = [UnionTestRuntime.StubSource], + SuppressedDiagnosticIds = ["RSEXPERIMENTAL006"], + }); } private const string UnionSource =