```
Title: SA1629: Diagnostic location is misplaced when documentation ends with a self-closing XML element

SA1629 (“Documentation text must end with a period”) does not correctly place its
squiggly underline or code-fix insertion point when the last meaningful content
in a documentation comment is an empty XML element, such as
`<see cref="Something"/>`.

Current behavior (repro):
For a doc comment like
/// <summary>
/// Text description <see cref="Something"/>
/// </summary>
the diagnostic is reported somewhere *inside* the <see.../> element rather than
immediately after it.  As a result the “add a period” code fix inserts the
period in the wrong position, or the underline appears in a misleading spot.

Expected behavior:
The diagnostic should be located immediately after the last content node that
contributes to the documentation text, meaning *after* the self-closing element
when the trailing content is an empty element with no following text.  The code
fix should add a period at that location.

Any trailing whitespace after the empty element should still be handled as
usual (ignored for the purpose of detecting the missing period).  The only
change is that empty XML elements should be recognised as content for the
purpose of advancing the reported span, so the diagnostic points to the
point right after the element rather than inside it.
```

Fix reporting location of SA1629 after empty elements


**Request: Update SA1503 to support the existing `allowConsecutiveUsings` stylecop.json option**

### Current behavior
Rule SA1503 (braces must not be omitted) currently reports a violation whenever a `using` statement has a non-block child statement, including when that child is another `using` statement. This means that consecutive `using` statements (stacked without braces) always produce an SA1503 diagnostic, even when other layout rules accept the same pattern.

### Desired behavior
SA1503 should respect the `layoutRules.allowConsecutiveUsings` setting in `stylecop.json` in the same way that other rules (for example SA1519) already do.

- When `allowedConsecutiveUsings` is set to `true`, SA1503 must **not** report a violation for a `using` statement whose direct child is another `using` statement (consecutive usings).
- When `allowedConsecutiveUsings` is set to `false`, SA1503 must keep its original behavior for this pattern (braces required).
- The default value of `allowConsecutiveUsings` should match the default used by other rules that consume this option (typically `true`).

### Additional constraints and edge cases
- The change must only affect how SA1503 processes `using` statements. Other statement kinds (if, for, foreach, lock, fixed, etc.) must remain unchanged.
- This option should not influence any other rule; especially, SA1519 should continue to apply its own logic independently of SA1503's decision.
- The setting must be read from the standard stylecop.json settings infrastructure; the analyzer must not read any custom or alternative configuration source.
- The implementation must handle the case where `stylecop.json` is absent or does not contain the option gracefully, falling back to the default behavior (which is expected to be equivalent to `allowConsecutiveUsings: true`).

Update SA1503 to consider the allowConsecutiveUsings option


SA1518 (“File may only contain a single newline at the end”) does not enforce its trailing‑newline requirements on files that contain only whitespace. Such whitespace‑only files are incorrectly treated as empty, so the rule never diagnoses them with any setting. A file that is nothing but whitespace should be treated like any other non‑empty file:
- With `Require`, a whitespace‑only file without a trailing newline should be diagnosed and fixed to an empty file ending with a newline.
- With `Omit`, a whitespace‑only file that already ends with a newline should be diagnosed and fixed to an empty file (no trailing newline).

Fix the emptiness check used by SA1518 so that files consisting only of whitespace are no longer considered empty, and ensure the correct behavioral table above holds.

add tests for white space only files not beeing classified as empty


SA1028 (no trailing whitespace) should flag trailing whitespace on preprocessor directive lines.
Extend the rule to cover: `#define`, `#undef`, `#if`, `#elif`, `#else`, `#endif`, `#warning`, `#region`, `#endregion`.
For now, omit `#error`, `#line`, and `extern alias` directives because our test infrastructure doesn’t exercise them easily.

**Code-fix safety constraint**
The SA1028 code fix provider must *not* offer a remove‑whitespace fix for these new violations. The fixer only knows how to remove trailing whitespace from `WhitespaceTrivia`, `SingleLineCommentTrivia`, `MultiLineCommentTrivia`, and `MultiLineDocumentationCommentTrivia`. For any other trivia kind (including the new directive trivias) the fix must be suppressed; accidentally offering the fix would produce incorrect or crashing behavior. The provider should be restricted to the exact set of trivia kinds it already handles.

Add tests for finding whitespace after most directives


**Title:** SA1205 code fix throws an exception or fails to apply for nested partial types with `protected` or `protected internal` access

**Description:**
When a nested partial type (class, struct, or interface) contains one part that specifies `protected` or `protected internal` accessibility and another part that omits the access modifier, the SA1205 diagnostic correctly fires, but attempting to apply the suggested code fix (via lightbulb/suggestion) fails. Either the fix does not apply at all, or an internal error occurs (typically an exception).

**Steps to reproduce:**
1. Create a C# project with the StyleCop.Analyzers NuGet package.
2. Write a nested partial type that has `protected` or `protected internal` on one part and no access modifier on the other part. For example:
   ```csharp
   public class Outer
   {
       protected internal partial struct Sample
       {
       }

       partial struct Sample
       {
       }
   }
   ```
3. Open the file in Visual Studio and observe the SA1205 warning on the second part.
4. Use the lightbulb to apply the code fix.

**Expected behavior:**
The code fix should add the missing access modifier keyword(s) to the partial declaration, so that both parts declare the same accessibility. For the example above, the fixed code should add `protected internal` before `partial struct Sample` on the second part.

**Observed behavior:**
The code fix does not modify the document. In some scenarios an error toast or an internal exception is reported.

**Additional notes:**
- The problem only occurs for `protected` and `protected internal` access modifiers. Public, internal, and private appear to work correctly.
- The issue affects all nested partial type kinds (class, struct, interface).
- The fix must preserve existing whitespace/trivia so the output remains well-formatted.
- The diagnostic (SA1205) itself is correct and fires as expected; only the code fix is broken.

Added new test case for SA1205 to verify propagation of access modifiers between multiple parts of a nested partial type. Updated code fix accordingly.


# TokenSpacingCodeFixProvider: FixAll does not converge in a single pass and removes newlines when removing immediate spacing

The spacing code fix provider (`TokenSpacingCodeFixProvider`) has a `FixAll` implementation that struggles in two ways:

1. **Overlapping token replacements are overwritten instead of composed**
   When multiple spacing diagnostics affect the same token, later updates simply overwrite earlier fixes in the replacement map. This can partially discard corrections and forces `FixAll` to require multiple iterations to converge. In practice this shows up as tests needing to pass `numberOfFixAllIterations: 2` to get the expected fixed document; under real usage a single “Fix All” run may leave the document only partially corrected.

2. **`ActionRemoveImmediate` strips newlines**
   When a spacing rule asks to remove immediate whitespace around a token, the fixer calls `TriviaHelper.WithoutTrailingWhitespace` (directly or via similar hand-rolled trimming). That helper treats end-of-line trivia as whitespace, so removal can “eat” newlines that separate tokens on different lines. StyleCop spacing rules must never remove line breaks when removing whitespace, so this introduces incorrect formatting and can cause additional diagnostics.

**Expected behavior**
- `FixAll` for spacing rules must produce a fully fixed document in a single pass. When the same token already has a pending replacement in the map, new transformations should be applied *on top* of the previous replacement so that no fix is lost.
- The `ActionRemoveImmediate` fix must remove only whitespace trivia (spaces, tabs) and **stop** at end-of-line trivia. The fix should never collapse or remove newlines between tokens.

**Additional context**
- `TriviaHelper.WithoutTrailingWhitespace` and `IndexOfTrailingWhitespace` currently treat end-of-line trivia as whitespace. A `bool` option to treat end-of-line trivia as non-whitespace (and stop before it) would be the natural way to support the newline-preserving removal without breaking existing callers.
- The existing tests that pass `numberOfFixAllIterations: 2` should become unnecessary once replacements are composed; the fix should be validated by those tests now passing with the default single-pass iteration behavior.

Improved FixAll for TokenSpacingCodeFixProvider


**Request: SA1119 does not handle switch expression parenthesized inside a cast, and code fix introduces extra space**

SA1119 should report unnecessary parentheses when a switch expression is wrapped in parentheses and appears as the argument of a cast expression.

Example: `(string)((n switch { 1 => a, 2 => b }))` — the inner `( ... )` around the switch expression is useless and should be flagged and removed. Currently the analyzer does not detect this situation, and the code fix for SA1119 may insert an unwanted space after the cast’s closing parenthesis in similar patterns (producing something like `(string)( n switch ...)`).

Requirements:
- The rule should recognise when a parenthesized switch expression is the direct or indirect descendant of a cast expression, even if there are outer unnecessary parentheses, and flag those inner parentheses.
- The code fix must remove the unnecessary parentheses without adding a leading space when the parenthesized expression is immediately preceded by a closing parenthesis (e.g., the `)` of a cast). In that position the original spacing should be preserved exactly.
- The fix must behave correctly for any number of nestings; e.g., `(string)((((n switch ...))))` should report all redundant parentheses and remove them without introducing extra space.

Added suggested unit test and fixed code


**Title:** SA1519 should flag missing braces in multi-line `lock` and `fixed` statement bodies

**Description:**

SA1519 (“Braces must not be omitted from multi-line child statement”) currently only inspects `if`, `while`, `for`, `foreach`, and `using` statements. The rule should also cover `lock` and `fixed` statements, which have the same syntactic structure: a parent statement with an embedded child statement that may span multiple lines. When the child statement body of a `lock` or `fixed` spans more than one line and braces are omitted, the analyzer should produce the same diagnostic as it does for the already‑supported statement kinds. Likewise, the code fix should add braces around the multi‑line body for these statement types.

- **Expected behavior:**
  - A `lock` statement whose sole child statement is written across multiple lines without curly braces produces a diagnostic.
  - A `fixed` statement whose sole child statement is written across multiple lines without curly braces produces a diagnostic.
  - Single‑line bodies without braces are still allowed (no diagnostic), matching existing behavior for other statements.
  - The code fix provider correctly inserts braces when braces are missing but required.

- **Acceptance criteria:**
  The rule triggers for `lock` and `fixed` exactly as it does for the existing statement kinds, and the automatic fix inserts curly braces in the multi‑line case.

Make SA1519 work with lock and fixed (fix #2885)


```
Title: Implement SA1634 "File header must show copyright" analyzer

Description:
The SA1634 analyzer is currently stubbed out (disabled-note-tests, TODO) and should be fully implemented.

Expected behavior:
- If a source file has a well-formed file header (XML-style comment at the top of the file), the analyzer must verify that the header contains a `<copyright>` element.
- The tag name comparison must be case-sensitive (only exactly `copyright` in lowercase is valid; anything like `<Copyright>` is not).
- The element may appear as a normal open/close tag with attributes and content, or as a self-closing tag (e.g. `<copyright file="test.cs" company="Foo" />`).
- If the file has no header at all (no XML-style header comment), the analyzer should NOT report a diagnostic – that scenario is covered by other file-header rules.
- If the file header is present but malformed (e.g., contains no XML elements at all), the analyzer should NOT report a diagnostic – it is already covered by SA1633.
- The analyzer should be enabled by default (`EnabledByDefault`) in the final build.

Supporting helper improvements needed:
- `FileHeaderHelpers.ParseFileHeader` currently assumes the extracted XML has a single root element, but real headers may contain multiple top-level elements (e.g. `<author>...</author>` followed by `<copyright>...</copyright>`). The parser needs to handle this, likely by wrapping the extracted text in a temporary root element before parsing.
- A header that consists only of text with no XML tags should be treated as malformed (e.g., `FileHeader.IsMalformed` should be true), rather than being parsed as an empty valid header.
- The `FileHeader` class should expose a way to query for a direct-child-descendant element by tag name, using ordinal (case-sensitive) comparison.

Tests:
- Cover: empty file, file with no header, file with a valid copyright header (standard and self-closing forms), file with another top-level element followed by copyright, file missing copyright but containing other element(s), file using wrong-case copyright tag.
- Auto-generated files (`// <auto-generated/>`) should not produce a diagnostic from any file-header rule. Extract the existing auto-generated test from SA1633 into a shared base class used by both SA1633 and SA1634 tests.
- Update SA1633 test class to inherit from this new base class.

Please implement the analyzer and the necessary helper improvements.
```

Implemented SA1634 + tests, several minor improvements as well


**Title:** SA1216 reports multiple diagnostics when multiple static using directives appear before a non-static using

**Description**
When a block of using directives contains several `using static` directives followed by a regular `using` directive, the SA1216 analyzer (“Using static directives must be placed at correct location”) flags each static `using` as a separate violation. I expect the rule to produce at most one diagnostic for the block, reporting only the last static `using` that is followed by a non-static `using`.

**Repro steps**
1. Create code that declares, in order:
   - a static using
   - another static using
   - a normal using
2. Place the block either directly inside a compilation unit or inside a namespace declaration.
3. Run SA1216.

Example (pseudocode):
```
using static System.Array;
using static System.Math;
using System;
```
**Observed behavior**: SA1216 fires on *both* `using static System.Array;` and `using static System.Math;`.
**Expected behavior**: SA1216 fires only on `using static System.Math;` (the last static using before the non-static one).

**Impact**
The extra diagnostics create noise and can lead to confusing code-fix suggestions. The rule’s intent is to enforce correct ordering of static vs. non-static usings; when multiple static usings are already misplaced, only the one that directly violates the boundary with a following non-static using should be reported.

**Constraints / edge cases**
- The behavior should apply identically to using-directive blocks at the compilation-unit level and inside namespace declarations.
- If there is no non-static using after the static ones, no diagnostic should be produced.
- When a block contains multiple groups (static, non-static, static, non-static), each group boundary that violates the ordering should still be handled appropriately (only the last static using before each non-static using is reported). However, the most frequent practical case is a single block of static usings followed by regular usings, where only one diagnostic is desired.


**Request: Workaround for FixAll performance regression in VS 2015 Update 1**

## Problem
When applying a StyleCop code fix using “Fix All” (project or solution scope) in Visual Studio 2015 Update 1, performance degrades significantly. The bottleneck is the call to `FixAllContext.GetAllDiagnosticsAsync` inside `FixAllContextHelper.GetDocumentDiagnosticsToFixAsync`. We need to bypass that slow API without changing the set of diagnostics that get fixed.

## Acceptance criteria

1. **Project and solution fix-all scopes no longer call `GetAllDiagnosticsAsync`**
   For `FixAllScope.Project` and `FixAllScope.Solution`, instead of delegating to `fixAllContext.GetAllDiagnosticsAsync`, the helper must:
   - obtain the project’s compilation via `Project.GetCompilationAsync`,
   - run only the analyzers that produce any of the diagnostic IDs specified in the `FixAllContext.DiagnosticIds`, and
   - filter the resulting diagnostics to exactly those IDs.

   The document-scope path is unaffected.

2. **Only the required analyzers are executed**
   The workaround must not re-run every analyzer in the solution. It should instantiate and run only those `DiagnosticAnalyzer` types whose `SupportedDiagnostics` intersect with the fix-all context’s diagnostic IDs.

3. **Compilation options (including custom XML resolvers) must be respected**
   Some projects use custom `XmlReferenceResolver` (e.g., setup via `CompilationOptions.WithXmlReferenceResolver`). The compilation used for the direct analysis must carry whatever options the project already has, including any XML resolver and other compilation-option customizations.
   Likewise, the diagnostic-severity configuration (enabling the relevant analyzer IDs, suppressing IDs marked as disabled, reporting AD0001 as an error) must still be active on the compilation so that analyzer behavior matches what users and tests expect. Currently that option setup happens inside `GetSortedDiagnosticsFromDocumentsAsync` and in `CreateSolution`. It must be moved to a lifecycle step that runs **before** the direct analysis, so that the compilation passed to `WithAnalyzers` already has those options applied.

4. **Existing overrides that set custom compilation options must remain correct**
   Several parties override `CreateProject` purely to attach an `XmlReferenceResolver` or to modify compilation options (e.g., `SA1604UnitTests`, `SA1606UnitTests`, `SA1615UnitTests`). Their customizations should continue to work after the change without duplicating the base-logic that enables/suppresses diagnostic IDs. This can be achieved by splitting project creation into a “create sources/project” step and a separate “apply compilation options” step; the custom overrides can then hook into the options step instead.

5. **Fix-all verification in test infrastructure must supply the full set of relevant diagnostic IDs**
   When constructing a `FixAllContext` for fix-all provider tests, the context must include **all** diagnostic IDs that the analyzers under test can report, not only the ones listed in the code fix provider’s `FixableDiagnosticIds`. This ensures that the new direct-analysis path receives the same IDs as would have been returned by the old `GetAllDiagnosticsAsync` call, preserving correctness.

## Non-goals
- No change to the behavior of document-scope Fix All.
- No change to the StyleCopTester utility’s result accuracy; minor adjustments to use `ImmutableArray` builders are acceptable as long as semantics are unchanged.

## Constraints
- The fix must target only the performance regression in VS 2015 Update 1; the API bypass is the official recommended workaround.
- Do not alter the public API of `FixAllContextHelper` or break any existing code-fix provider.

Workaround performance regressions in Visual Studio 2015 Update 1


Improve SA1201 “Elements Must Appear In The Correct Order” diagnostics:

- Change the diagnostic message format to `"A {0} should not follow a {1}"` and supply the two argument placeholders with the names of the element types involved (e.g. `"struct"`, `"class"`, `"constructor"`, `"destructor"`, `"method"`, `"indexer"`, etc.).
- Only flag the specific element that breaks the ordering constraint relative to the immediately preceding element. Do not flag elements that appear after an earlier violation if they themselves are in correct order relative to their own predecessor. In other words, perform a pairwise adjacent check against the expected ordering, not a running-maximum check.


**Title:** SA1648 false positive: constructor with `<inheritdoc />` on a class with a base type

**Description**
Rule SA1648 (`InheritDocMustBeUsedWithInheritingClass`) currently requires that `<inheritdoc/>` only appear on members that actually inherit documentation from a base member. For constructors, this check is too strict: when a class has a base class, the constructor _can_ legitimately inherit documentation from the base class constructor, so `<inheritdoc/>` should be allowed.

**Current behavior**
A constructor with a `<inheritdoc />` comment always triggers SA1648, even when the enclosing class explicitly inherits from a base type that provides a constructor.

**Expected behavior**
SA1648 should **not** fire for a constructor when the class has a non‑null base type. For constructors on classes without a base type, the rule should still report as before.

**Scope**
Only the analyzer logic for SA1648 – the condition that decides whether to emit a diagnostic when encountering `<inheritdoc />` on a member. No code‑fix changes are needed.
The existing logic already handles overrides and interface implementations; this is an analogous case for constructors that inherit documentation from a base class.

Allow inheritdoc for constructors with base types


**Title:** SA1118 does not flag attribute parameters that span multiple lines

**Description:**
The SA1118 rule (“Parameter must not span multiple lines”) currently checks argument lists for method invocations, indexers, and array/collection creation expressions, but it completely ignores attribute argument lists. If an attribute constructor’s second (or later) argument spans multiple lines, no diagnostic is reported, even though the rule’s own description string lists attributes as part of its intended scope.

**Observed behavior:**
A code fragment like
```csharp
[MyAttribute(1,
             2)]
public class Foo { }
```
does not produce SA1118, despite the second argument spanning two lines.

**Expected behavior:**
SA1118 should report a diagnostic on the second (and any subsequent) attribute argument that spans multiple lines, consistent with how it already works for method, indexer, and array arguments. The first argument does not trigger the rule (same as for other argument lists). Arguments whose expressions fall into the existing exception list (e.g., anonymous functions, object-creation expressions) should remain excluded from the check.

**Implementation guidance:**
- Register a syntax node action for attribute argument lists alongside the existing `ArgumentList`/`BracketedArgumentList` handlers.
- Reuse the existing multiline-detection and exception-list logic, adapting it as needed for the attribute argument node types so that the `Expression` of the attribute argument is passed to the exception check.
- Update the rule’s description string if it doesn’t already mention attributes (currently it lists “method/indexer/attribute/array” in the source, but the implementation should match that declared coverage).


**Issue:** The using directive ordering code fixes (e.g., `UsingCodeFixProvider`, applied when fixing violations of SA1208, SA1210, SA1216, etc.) insert blank lines and enforce trailing/leading line breaks using a hard‑coded CRLF (`\r\n`) line ending. This corrupts files that use LF (`\n`) line endings, producing a mix of CRLF and LF newlines.

**Expected behavior:** When the code fix adds synthetic newlines (blank separator lines between using groups, blank lines before/after a block of usings, or ensures an end-of-line exists), it must respect the line‑ending convention already present in the document. The fix should detect the appropriate line ending from the source text (e.g., from the first observed line break) and use that same ending throughout. Both LF and CRLF conventions must be supported.

Any existing call sites that directly use `SyntaxFactory.CarriageReturnLineFeed` for generating these separators need to be updated so that the determined document line ending is passed through and used instead.

Fix UsingCodeFixProvider hard-coding of CRLF


## Request

**Issue:** SA1009 code fix produces broken or ill-formed code when a closing parenthesis is followed by a comment and a semicolon on a subsequent line, or when a member access dot follows the closing parenthesis on a subsequent line.

### Steps to Reproduce
1. Write code that triggers SA1009 (“Closing parenthesis should not be preceded by a space”) where the closing parenthesis has a trailing comment and a semicolon on the next line:
```csharp
await Task.Delay(1000 // comment
    );
```
2. Apply the code fix.
3. Observe that the resulting code is not valid or formats the comment incorrectly.

Similarly, with a member access:
```csharp
await Task.Delay(1000
    ).ConfigureAwait(false);
```
Applying the fix results in incorrect formatting or broken member access.

### Desired Behavior
The code fix should handle these patterns correctly:

- **Comment + semicolon after closing parenthesis**: When a closing parenthesis is followed by a line with a semicolon, and there is a comment between them, the fix should move the semicolon to immediately follow the closing parenthesis on the same line, and place the comment after the semicolon. The result should be syntactically valid and maintain the comment in a natural position.

- **Member access on next line**: When a closing parenthesis is followed by a member-access dot on a separate line, the fix should move the closing parenthesis to the end of the previous line while keeping the dot on the next line. The member access expression must remain intact.

The fix must not break compilation or alter semantics.


```markdown
## Request: SA1135 — support file-scoped namespace declarations (C# 10)

### Background
SA1135 (“Using directives must be qualified”) currently only recognises traditional block-scoped namespace declarations. C# 10 introduced file-scoped namespace declarations, and the rule does not handle them correctly. Users report either missing diagnostics or crashes when a using directive appears inside a file-scoped namespace.

### Acceptance criteria
1. **Detect violations inside file-scoped namespaces**
   When a using directive is a direct child of a file-scoped namespace declaration, SA1135 must evaluate whether the using directive should be flagged. The rule should behave identically to how it behaves inside a block-scoped namespace: if the using directive references a type whose containing namespace differs from the enclosing namespace, report the diagnostic.

2. **Provide a correct code fix**
   For a violation inside a file-scoped namespace, the code fix must produce a fully‑qualified using directive. For example, given:
   ```csharp
   namespace A.B;
   using C;  // where C is A.B.C
   ```
   the fix should produce `using A.B.C;`.

3. **No exceptions**
   The analyzer must not throw an exception (e.g., `InvalidCastException` or `NullReferenceException`) when it encounters a file-scoped namespace declaration.

4. **No regression for existing scenarios**
   - Using directives outside any namespace must continue to be considered always qualified (no diagnostic).
   - Block‑scoped namespace declarations must continue to work exactly as they do today.

### Implementation notes
- The repository already has a pattern for dealing with version‑dependent syntax kinds (the `SyntaxKindEx` helper). File‑scoped namespaces are exposed as `SyntaxKindEx.FileScopedNamespaceDeclaration`.
- There is also a wrapper type (`BaseNamespaceDeclarationSyntaxWrapper`) designed to abstract over both namespace declaration kinds when you need to access the namespace name. Using that wrapper is likely the safest way to extract the containing namespace name without forcing a cast to a specific syntax node type.
- Make sure the fix is covered by unit tests that exercise a file‑scoped namespace declaration containing both a compliant using alias and a non‑compliant unqualified using directive that should be fixed.
```
```

This request is self-contained, gives the user-facing problem, expected behavior, and hints at existing repo conventions (`SyntaxKindEx`, the wrapper) without dictating the exact change or file paths. The agent would need to search for the SA1135 analyzer, understand its structure, and adapt it for file‑scoped namespaces.

Update SA1135 to support file-scoped namespaces


**Title:** SA1119 false positive for cast expression containing a switch expression

**Area:** Maintainability rule SA1119 (unnecessary parenthesis)

**Severity:** Bug / false positive

---

When a C# switch expression (C# 8+) is used directly as the operand of a cast expression, the parentheses required by the cast syntax are flagged by SA1119 as unnecessary. Removing them would produce invalid syntax.

**Steps to reproduce:**
```csharp
return (string)(n switch { 1 => a, 2 => b });
```
SA1119 reports the outer parenthesized expression as unnecessary, but the parentheses are syntactically required here — you cannot write `string n switch { … }` without them.

**Expected behavior:**
SA1119 should suppress its diagnostic when a parenthesized expression wraps a switch expression that is itself the immediate operand of a cast expression. In other words, when the opening parenthesis is immediately preceded by the closing parenthesis of a `CastExpression` node in the syntax tree, the parentheses should be considered syntactically required and should not be flagged.

**Constraints to preserve:**
- Switch expressions that are parenthesized but *not* preceded by a cast should still be flagged and a code fix offered, as they normally are for any other expression type (e.g., `var x = (n switch { … });` → `var x = n switch { … };`).
- The suppression should apply only to the specific `(cast)switch_expr` pattern. Other parenthesized expressions that happen to contain a switch expression deeper inside should still be evaluated normally.
- The fix should work for all forms of cast expressions (C-style casts like `(string)`, etc.).
- Must respect the existing early-return structure in the rule’s analysis walk so that the suppression is cleanly integrated without side effects on other diagnostics.

**Language version:** C# 8.0 and later (switch expressions were introduced in C# 8).

SA1119: Added support for typecast followed by switch expression


```
Title: SA1023 allows illegal spaces after '*' when immediately followed by ')' or another '*'

SA1023 (Dereference and Access of Symbols Must Be Spaced Correctly) is supposed to flag incorrect spacing around the dereference operator and pointer-type asterisks. However, it currently fails to report violations when an asterisk is followed by a closing parenthesis ')' or another asterisk '*', while it correctly flags spaces before '[' and '('.

As a result, the following invalid patterns are silently accepted:

  (int * )          // space between * and )
  (int* * )         // space between * and another *
  typeof(char * )   // same
  default(char* * ) // space after * before another *
  a = * x** x;      // space after * before another *

The rule should disallow a space after an asterisk in these contexts, consistent with how it already prevents a space before an opening parenthesis or bracket (e.g. `( int *` is already flagged). The expected behavior is that any space appearing between an asterisk and an immediately following ')' or '*' should produce a diagnostic.

This impacts code readability in pointer-heavy C# code and causes SA1023 to be inconsistent with StyleCop's own spacing guidelines for asterisk tokens.
```

Fix handling of '*' followed by '*' or ')'


### SA1513 false positive on `yield return` with anonymous object initializer

**Repro**
```csharp
private static IEnumerable<object> Method()
{
    yield return new
    {
        prop = "A"
    };
}
```
SA1513 (Closing curly bracket must be followed by a blank line) fires on the closing curly brace of the anonymous type, even though it is immediately followed by `;` ending the `yield return` statement.

**Expected behavior**
The closing brace of an object/collection initializer that is the expression of a `yield return` statement should be treated the same way the rule already treats initializers in `return` statements, variable declarators, and assignment expressions: when the next token is a semicolon, no blank line is required.

**Why**
SA1513 already exempts closing braces followed by `;` in several statement contexts (variable declaration, assignment, `return`). The `yield return` case is missing, causing a false positive.

**Task**
Update the SA1513 analyzer logic so that a closing brace followed by `;` and belonging to a `yield return` statement is exempted from the blank-line requirement, consistent with the existing exemptions. The fix should be minimal and not affect other behavior of the rule.

Fix for SA1513 incorrectly reported when object initializer used within yield return statement.


**Title**: SA1405/SA1406 analyzers crash on Debug.Assert/Fail calls when the message parameter is omitted

**Description**

The SA1405 (`Debug.Assert must provide message text`) and SA1406 (`Debug.Fail must provide message text`) analyzers are throwing an unhandled exception when they encounter an invocation of `Debug.Assert` or `Debug.Fail` that omits the optional `message` parameter. The crash occurs both with the standard `System.Diagnostics.Debug` and with user-defined types in the `System.Diagnostics` namespace that define `Assert`/`Fail` with optional parameters.

**Repro steps** (from user report):

1. A project contains a call like `Debug.Assert(true);` without a message string.
2. The analyzers attempt to check whether the message argument is supplied.
3. Instead of reporting a diagnostic, the analyzer process terminates with a `NullReferenceException` or an `ArgumentOutOfRangeException`.

**Expected behavior**

- When a call to `Debug.Assert` does **not** provide a value for the message parameter, SA1405 must produce a diagnostic (as it would for any missing required argument).
- When a call to `Debug.Fail` does **not** provide a value for the message parameter, SA1406 must produce a diagnostic.
- The analyzer must never throw an exception, regardless of whether the `Debug` class comes from `System.dll`, a user-defined assembly, or is defined in source, and regardless of parameter optionality.

**Technical hints / constraints**

- The crash is in the shared base class `SystemDiagnosticsDebugDiagnosticBase`.
- The problematic logic currently inspects the **declared parameter count** of the resolved method symbol to decide whether the message is present. For methods with optional parameters, the declared parameter count is larger than the number of arguments actually supplied at the call site.
- Instead, the decision must be based on the **number of arguments** provided in the invocation syntax. If the invocation’s argument list lacks an argument at the index corresponding to the message parameter, the diagnostic should fire.
- Ensure the code handles edge cases where the `ArgumentList` of the `InvocationExpressionSyntax` might be unexpectedly `null`, even if that should not happen in normal C# syntax; the code must not throw.

**Acceptance criteria**

- SA1405 no longer crashes when analyzing `Debug.Assert(true)` or any call that omits the message parameter.
- SA1406 no longer crashes when analyzing `Debug.Fail()` or any call that omits the message parameter.
- The fix works identically whether the `Debug` type is the standard BCL type or a user-defined replacement in the `System.Diagnostics` namespace.
- No behavioral side effects on other overloads or valid calls.

Fix that Debug.Assert/Fail analyzers crash


**Implementation request**
SA1513 (ClosingCurlyBracketMustBeFollowedByBlankLine) currently does not flag missing blank lines when a closing curly brace inside a `case` block is immediately followed by a `break;` statement. This is an incorrect exemption; the rule should require exactly the same blank line after those braces as it does elsewhere. Remove the special handling that suppresses the diagnostic when the next token is a `break` keyword inside a `SwitchSectionSyntax`. After the fix, both

```csharp
case 0:
    if (cond) { … }
    break;
```

and

```csharp
case 1:
    { … }
    break;
```

must report a violation for the `}` token (assuming it is not at the end of the file and no other blank-line exception applies).


**Title:** `documentInterfaces` should support an `"exposed"` mode to require documentation only on non‑internal interfaces

**Context**

The `documentInterfaces` setting in `stylecop.json` currently accepts a boolean value.
- When `true`, SA1600 and related rules require documentation for **all** interface members, regardless of accessibility.
- When `false`, they require no documentation for any interface member.

This all‑or‑nothing behavior is too coarse for teams that want to enforce documentation on externally visible interfaces but not on `internal` ones.

**Request**

Extend `documentInterfaces` to accept the following string values (the old boolean type should be removed):

| Value      | Behavior |
|------------|----------|
| `"all"`    | Documentation is required for all interfaces (equivalent to the old `true`). |
| `"none"`   | Documentation is not required for any interface (equivalent to the old `false`). |
| `"exposed"`| Documentation is required **only** for interfaces whose declared accessibility is anything other than `Internal`. This means `public`, `protected`, `protected internal`, and `private protected` interfaces must be documented; `internal` and `private` may be left undocumented. |

For smoother upgrades, it is acceptable to also accept the string literals `"true"` and `"false"` as aliases for `"all"` and `"none"` respectively.

**Affected components**

- The JSON schema (`stylecop.schema.json`) must be updated: `documentInterfaces` should become a string property with a default of `"all"`.
- The settings model (`DocumentationSettings`) must store the value as a string, defaulting to `"all"`, and parse it from the configuration.
- The analyzer `SA1600ElementsMustBeDocumented` (and any other rule that consults `DocumentInterfaces`) must implement the new logic, using `declaredAccessibility` to distinguish `"exposed"` from the other modes.

**Acceptance criteria**

- A `stylecop.json` with `"documentInterfaces": "exposed"` causes documentation warnings only on interface declarations (and their members) whose `declaredAccessibility` is **not** `Internal`.
- The default value remains `"all"`, so existing projects that did not explicitly set the option continue to require documentation for all interfaces.
- The old boolean values are no longer supported in the schema; any existing JSON must be converted to the new string format.

Changed SA1600 and tests to meet new documentInterfaces values


**Title:** SA1312 does not check variable names introduced via C# 7 pattern syntax

**Description**

SA1312 ("Variable names must begin with lower-case letter") currently only inspects traditional variable declaration sites: `VariableDeclarator`, `ForEachStatement`, `JoinClause`, and `JoinIntoClause`. It misses variables introduced by newer C# 7 pattern syntax, including:

- `out var` declarations (`int.TryParse("0", out var Bar)`)
- deconstruction declarations (`var (X, y) = (1, 2)`)
- pattern variables in `is` expressions (`ex is ArgumentException ArgEx`)
- pattern variables in `switch` case labels (`case int X:`)
- single-variable designations nested inside other patterns (e.g., `foreach (var (X, y) in ...)`)

As a result, in C# 7 code, these variable names are never flagged even when they start with an uppercase letter or an underscore, which is inconsistent with the behavior for regular local variables and foreach iteration variables.

**Desired behavior**

SA1312 should analyze **single variable designations** (the syntax node that represents the variable name in these new contexts) and report diagnostics with the same rule ID and severity when a variable name does not begin with a lowercase letter.

The analysis must respect the same set of safety constraints that apply to other variables:

1. **Discards are exempt** – A single underscore (`_`) used as a discard should never produce a diagnostic. However, a name consisting of multiple underscores (`__`) is not a discard and should be flagged.

2. **NativeMethods class exemption** – Variables inside a class whose name ends with `NativeMethods` must still be ignored entirely, just as they are for ordinary local variables today.

3. **Code-fix compatibility** – The existing `RenameToLowerCaseCodeFixProvider` already knows how to fix SA1312 diagnostics by renaming variables. It should automatically work for these new diagnostics as long as the analyzer emits them with the correct location and metadata. When the rename would conflict with an existing variable, keyword, or parameter already in scope, the code fix must produce a unique non-conflicting name (e.g., by appending a number, or using `@`-escaped keyword notation), matching the behavior provided today for other variable declarations.

**Context / references**

- The rule itself lives in `SA1312VariableNamesMustBeginWithLowerCaseLetter.cs`
- The C# 7 pattern syntax is represented by `SingleVariableDesignation` nodes in the Roslyn syntax tree
- The analyzer already uses a centralized `CheckIdentifier` helper that performs the actual name validation; this helper should be reused for the new syntax node kind to avoid duplicating logic or exemptions

No changes are expected to `RenameToLowerCaseCodeFixProvider.cs` or to any other code-fix provider unless the generated diagnostic locations differ enough to break the existing fix.

Update SA1312 to handle variable designators (pattern syntax)


```
Subject: SA1202 should apply to interfaces and records

### Problem

SA1202 ("Elements must be ordered by access") currently only analyzes `class` and `struct` declarations.
It ignores `interface` declarations (where members can have access modifiers starting in C# 8) and all `record` forms (`record`, `record class`, `record struct`).

Additionally, inside an interface, members that omit an access modifier are implicitly `public`.
The rule must treat those unmarked members the same as explicitly-`public` members for ordering purposes,
so that they are ordered correctly alongside other `public` members instead of being silently skipped or
mis-ordered.

### Acceptance criteria

1. **Interfaces are analyzed**
   - SA1202 fires on members of an `interface` declaration that are ordered incorrectly by access level.
     The expected order is: `public`, `internal`, `protected internal`, `protected`, `private`.
     Unmarked interface members (implicitly `public`) must be treated as `public`, so they sort immediately
     after any explicit `public` members and before `internal`.
   - The code fix can reorder members to satisfy the rule.
   - Example: an `interface` with members in the order
     `private`, `protected internal`, `internal`, `public`, unmarked member
     should be flagged and fixed to:
     `public`, unmarked member, `internal`, `protected internal`, `private`.

2. **Records are analyzed the same as classes/structs**
   - SA1202 must run on `record` (C# 9), `record class` (C# 10), and `record struct` (C# 10)
     declarations and enforce the same access ordering as it already does for `class` and `struct`.

3. **Backward compatibility**
   - Existing behavior for `class` and `struct` must not change.
   - The rule must only be enabled when the language version supports the required features
     (interfaces with access modifiers, record types). If the project’s language level does not
     support them, the analyzer should not produce false positives or crashes, though no
     special handling beyond the compiler’s own syntax support is required.

### Non-goals

- This change does not add new ordering rules or alter the precedence of access levels.
- It does not affect nested types or other declaration kinds beyond the type declarations
  listed above.
```

Update SA1202 to support interfaces and records


Title: SA1137 indentation check misbehaves when type declarations are preceded by attribute lists

SA1137 (ElementsShouldHaveTheSameIndentation) currently treats leading attribute lists as separate elements, or uses the wrong token for indentation, when analyzing class/struct/interface/enum declarations. This produces false positives and incorrect fix suggestions.

Expected behavior:

- For base type declarations (class, struct, interface, enum), any attribute lists that immediately precede the declaration should be ignored when determining the element's indentation. The indentation of the declaration must be measured from the declaration keyword (e.g., `class`), not from the opening bracket of an attribute.
- When the element being analyzed **is** an attribute list (e.g., on a method, property, field, etc.), the rule must continue to check that attribute list's own indentation exactly as it does today.

The fix should correctly handle:
- Multiple attribute lists on the same declaration, both on the same line as each other and on separate lines.
- Cases where attribute lists are mis-indented relative to the declaration keyword; the diagnostic should reference the location of the keyword (or the appropriate leading whitespace), not the attribute brackets.

No other rule behavior should change, and all existing tests for indentation of other element kinds must still pass.

Add tests for base type declarations and fix bugs


**Title**: SA1121 should flag `IntPtr` / `UIntPtr` and suggest `nint` / `nuint` on supported runtimes

**Description**
The rule SA1121 (Use built-in type alias) currently does not flag uses of `System.IntPtr` or `System.UIntPtr` as missing their built-in aliases, even when the project targets a runtime where native‑sized integers (`nint` / `nuint`) are fully available. It also does not provide a code fix that replaces those types with the `nint` / `nuint` aliases.

**Expected behavior**

1. When the project compiles with a runtime that supports native‑sized integers (detected via the presence of `System.Runtime.CompilerServices.RuntimeFeature.NumericIntPtr`), SA1121 should treat `IntPtr` and `UIntPtr` like other types that have a preferred built‑in alias. Specifically:
   - A type usage of `IntPtr` (or `System.IntPtr`) should trigger a diagnostic suggesting the alias `nint`.
   - A type usage of `UIntPtr` (or `System.UIntPtr`) should trigger a diagnostic suggesting the alias `nuint`.

2. The corresponding code fix should replace `IntPtr` with `nint` and `UIntPtr` with `nuint`.

3. No diagnostic should be produced when the project targets an older runtime that does not provide native‑sized integer support (e.g., .NET 6 or earlier). In that case `IntPtr` and `UIntPtr` should remain untouched, even if the C# language version supports the `nint`/`nuint` syntax.

4. Direct use of the `nint` or `nuint` keywords must not produce a false‑positive SA1121 diagnostic (they are already the “alias”).

**Impact**
Users on .NET 7+ who wish to consistently use built‑in type aliases throughout their codebase cannot automatically enforce the rule for `IntPtr`/`UIntPtr` and must manually rewrite those types. This inconsistency also makes it harder to adopt the rule project‑wide.


The SA1106 analyzer ("Code must not contain empty statements") currently flags a stray semicolon that follows a type declaration such as `class Foo { };`, treating that semicolon as an empty statement. However, the same stray semicolon following a namespace declaration (`namespace Foo { };`) is silently ignored. This is inconsistent—a redundant semicolon after a namespace block is just as meaningless as one after a type block and should be reported by SA1106.

Acceptance criteria:
- A diagnostic is raised when a `namespace` declaration is immediately followed by a semicolon token (i.e., the semicolon that terminates the namespace's closing brace, with nothing else on that statement), matching the existing behavior for class, struct, interface, and enum declarations.
- The diagnostic location should point at the semicolon token, not the namespace keyword or the entire declaration.
- The existing handling for empty statements inside method bodies and the handling of type-declaration trailing semicolons must not regress.


**Title: SA1304 duplicates SA1307 diagnostics on public and protected readonly fields**

When both SA1304 (Non‑private readonly fields must begin with upper‑case letter) and SA1307 (Accessible fields must begin with upper‑case letter) are enabled, a public or protected readonly field that starts with a lower‑case letter triggers **two** diagnostics—one from each rule. This is noisy and unhelpful; the field is accessible, so SA1307 is the more specific rule and should take precedence.

**Expected behavior:**

- If SA1307 is enabled (i.e., not suppressed in the ruleset or `.editorconfig`), SA1304 must **not** fire for `public` and `protected` readonly fields.
  SA1304 should still fire for `internal` readonly fields, even when SA1307 is active (so there is no gap in coverage for truly non‑accessible fields).
- If SA1307 is suppressed, SA1304 must still report on `public` and `protected` readonly fields exactly as it did before (so projects that opt out of SA1307 do not lose the naming check).

In other words, SA1304 should yield to SA1307 on any field that is not `internal`, but only while SA1307 is active. There is no change to how internal fields are handled.

**Repro scenario:**

```csharp
public class Foo
{
    public readonly string bar = "baz";     // both SA1304 and SA1307 fire
    protected readonly string bar2 = "baz"; // both fire
    internal readonly string bar3 = "baz";  // currently only SA1304 fires; this should stay
}
```

When SA1307 is enabled I see SA1304 on all three, which is wrong for the first two. When SA1307 is completely suppressed I still see SA1304 on the first two, which is correct.

Please fix the overlap so that SA1304 does not report on public/protected readonly fields when SA1307 is present, while keeping the existing behavior when SA1307 is turned off.

Fix that SA1304 is reported for accessible fields


**Title:** SA1209 does not apply to using‑alias directives inside file‑scoped namespaces
**Area:** OrderingRules / SA1209
**Issue:** #3439

### Description
SA1209 (`UsingAliasDirectivesMustBePlacedAfterOtherUsingDirectives`) currently checks using‑alias placement only for compilation‑unit usings and for usings inside traditional block‑scoped namespace declarations (`namespace Foo { … }`). It completely ignores using directives inside C# 10 file‑scoped namespace declarations (`namespace Foo;`).

This leads to false negatives: files that mistakenly place an alias before (or interleaved with) non‑alias usings inside a file‑scoped namespace do not trigger a diagnostic, even though the same ordering would be flagged inside a block‑scoped namespace.

### Expected behavior
SA1209 should enforce the same ordering rule on using‑alias directives regardless of whether the enclosing namespace is block‑scoped or file‑scoped.

### Example
The following code in a file‑scoped namespace should produce a diagnostic on `using L = System.Linq;` because alias directives are not all placed after normal using directives:

```csharp
namespace Test;
using System.Net;
using System.Threading;
using L = System.Linq;   // should be flagged
using P = System.Threading.Tasks;
```

The fixed version should place all non‑alias usings before alias usings (and preserve alphabetical order as per other ordering rules, but that is handled by other rules; SA1209 only cares about alias/non‑alias grouping).

### Additional context
- The adjacent rule SA1208 (`SystemUsingDirectivesMustBePlacedBeforeOtherUsingDirectives`) was already updated to support file‑scoped namespaces. Its implementation can be used as a reference for the necessary changes.
- The codebase already contains an abstraction (`BaseNamespaceDeclarationSyntaxWrapper` in the `Lightup` folder) and a registration helper (`SyntaxKinds.BaseNamespaceDeclaration`) that unify both namespace syntax kinds.
- No changes to the diagnostic descriptor, code fix provider, or rule documentation are required; only the analyzer registration and the namespace‑handling path need to be adjusted.

### Acceptance criteria
1. SA1209 fires when alias directives are placed before non‑alias directives inside a file‑scoped namespace.
2. The code fix provider correctly reorders the using directives without introducing a block‑scoped namespace wrapper.
3. Existing behavior for compilation‑unit usings and block‑scoped namespace usings remains unchanged.

Update SA1209 to support file-scoped namespaces


**Title:** SA1130 code fix loses trivia and mishandles generic parameter types when converting anonymous methods to lambdas

**Component:** ReadabilityRules / SA1130

**Description**
The SA1130 analyzer suggests replacing anonymous method expressions with lambda expressions where possible. The provided code fix incorrectly handles trivia (comments, whitespace) around the parameter list in several scenarios:

1. **Comments between type and parameter name** – When the anonymous method declares a typed parameter (e.g., `delegate(int /*d*/ i) { }`), the comment that originally appeared between the type and the parameter name is lost or placed in the wrong location after the fix.
2. **Trivia inside generic type arguments** – If the parameter type is a generic type with comments inside the type arguments (e.g., `delegate(List</*c1*/ int> i) { }`), the code fix either fails to apply or produces invalid/incorrect trivia output.
3. **Whitespace preservation** – Leading/trailing whitespace around the parameter and its type is not correctly normalized, sometimes introducing extra whitespace or losing significant formatting.

The expected behavior is that all comments and whitespace from the original anonymous method are transferred faithfully to the resulting lambda expression’s parameter list, so that only the syntactic structure changes and no trivia is silently dropped.

Additionally, after applying the fix, some cases may require two successive code‑fix invocations to completely resolve all violations (for example, because the parameter type removal and trivia adjustment happen in separate passes). The fix‑all iteration logic should correctly handle this without silently giving up or looping indefinitely.


The SA1205 code fix doesn't handle C# 7.2's `private protected` access modifier. When a member is declared `private protected`, the code fix for SA1205 should correctly recognize and propagate the `private protected` keywords, just as it already does for `protected internal`. Currently it falls through to the unexpected-keywords path and produces incorrect results.

Make the SA1205 code fix provider map `Accessibility.ProtectedAndInternal` to the pair of keywords `private` + `protected`, and ensure existing SA1205 tests for nested-type access modifier ordering also exercise `private protected` on class, struct, interface, and record declarations where the language version supports it.

Fix SA1205 support for 'private protected'


```
SA1114 (Parameter list must follow declaration) currently enforces spacing rules only for
method declarations and invocations. Constructor declarations with the same kind of
spacing violation are silently ignored. This is a missing case that should be covered.

Acceptance criteria:

- When a constructor’s opening parenthesis is immediately followed by a blank line
  (empty or whitespace only) before the first parameter, SA1114 must emit a warning
  identical to the one it produces for methods in the same situation.
- No warning should be emitted when:
  - the constructor has no parameters at all,
  - all parameters appear on the same line as the opening parenthesis, or
  - the parameter list starts on the very first line after the opening parenthesis
    (no blank line in between).
- The fix should treat constructors consistently with how the rule already treats
  methods and invocations – no new message, severity, or rule ID changes.
```


**Title:** SA1027 should respect the `UseTabs` indentation setting

**Background**
The `SA1027` analyzer (Tabs must not be used) currently reports every tab character as a violation regardless of whether the project’s stylecop.json uses `indentation.useTabs = true`. This makes the rule incompatible with projects that prefer tabs for indentation.

**Desired behavior**
*When `indentation.useTabs` is **false*** (the default):
- All tabs remain violations. Current behavior is preserved.

*When `indentation.useTabs` is **true***:
- Tabs that appear **only for leading indentation** (at the start of a line, before any non-whitespace character) should be allowed and not reported.
- Conversely, **spaces used for indentation** that could have been replaced by a tab (i.e., a run of spaces that reaches or exceeds the configured `tabSize`) should be flagged as violations.
- Any tab used **after** the first non-whitespace character on a line (e.g., after code, inside comments or strings) is still a violation and must be reported.
- Indentation that mixes spaces and tabs (spaces followed by a tab within the leading whitespace) is considered an error; the presence of a tab after spaces in the indent should be flagged.

The corresponding code fix (`SA1027CodeFixProvider`) should adjust its replacement logic accordingly:
- When `useTabs` is `false`, replace tabs with the appropriate number of spaces (existing behavior).
- When `useTabs` is `true`, replace leading spaces with the correct number of tabs (and any remaining spaces) while leaving non-indentation whitespace untouched.

**Edge cases to handle**

1. **Start-of-line detection** – Only leading whitespace of a line is eligible for indentation handling. If the offending trivia does not start at column 0 of its line, treat all tabs as violations even when `useTabs` is true (the tab is not pure indentation).

2. **Multi-line constructs** – For multi-line comments or other multi-line trivia, each line’s leading whitespace should be evaluated independently based on the line’s start column. Tabs in the middle of a comment line remain violations.

3. **XML documentation trivia** – Whitespace tokens within XML doc comments (e.g., in `<summary>` content) are **not** start-of-line indentation and should **always** have their tabs reported regardless of the `useTabs` setting.

4. **`////` comments** – Unindented comment lines that start with `////` should remain exempt from the rule as they are today (no tabs are reported for them).

5. **Disabled code regions** – Tabs inside `#if false` blocks are ignored, same as the current behavior.

6. **Tabs in string/char literals** – These remain ignored, as with the current rule.

**Additional constraints**
- The change should not break existing functionality when `useTabs` is `false`.
- The code fix must handle the conversion of mixed indentation correctly: when switching from spaces to tabs, spaces already accumulated in the replacement buffer must be replaced with a tab character at the appropriate tab stop.
- The fix must not alter whitespace that appears after the indentation region of the line.

If the above behavior is implemented, SA1027 will become usable in projects that standardize on tab-based indentation, while continuing to enforce a “no tabs” policy for projects that prefer spaces.

Update SA1027 to support the UseTabs setting


```
Title: SA1110 should check opening parenthesis of argument list in primary constructor base type specifications

Problem:
SA1110 enforces that opening parentheses in declarations appear on the same line as the preceding token.
For primary constructors, it already checks the type's own parameter list (e.g., `class Foo\n    (int x)` is flagged).
However, when a primary constructor type specifies a base type with an argument list,
the opening parenthesis of that base-type argument list is not checked.
For example, the following is not currently reported:

    class Bar(int x) : Foo
        (x)
    { }

Expected behavior:
SA1110 should flag the opening parenthesis `(` on the line containing `(x)` and offer a code fix that
moves it to the same line as the base type name, producing `: Foo(x)`.
The same rule should apply when the argument list is empty: `: Foo\n    ()` should be fixed to `: Foo()`.

Scope and constraints:
- This syntax corresponds to Roslyn's `PrimaryConstructorBaseType` syntax node
  (or a light-up wrapper if direct support is not available in the current Roslyn version).
  Ensure any needed light-up constant (e.g., in `SyntaxKindEx`) is added.
- The handler should delegate to the same line-position check used by other declaration handlers
  (e.g., `CheckIfLocationOfPreviousTokenAndOpenTokenAreTheSame`).
- Bail out early if the base type identifier name is missing (malformed code).
- The fix should work for all reference types that support primary constructors
  (class, record); structs cannot have argument lists in base types so they are out of scope.

Acceptance:
- SA1110 fires on the violation shown above.
- The code fix moves the opening parenthesis to the base type identifier line.
- Tests covering the main scenarios (with arguments, without arguments, already-correct placement)
  are added in the C# 9 test class for SA1110.
```

Update SA1110 to also check the primary constructor argument list in a base list


**SA1623: Do not offer a code fix for properties with an empty `<summary>` tag**

When a property's documentation contains an empty `<summary>` element (e.g. `<summary></summary>` or `<summary/>`), the analyzer correctly reports SA1623 because the summary text does not start with the mandatory phrase (`"Gets"`, `"Gets or sets"`, etc.). However, the code fix provider still tries to generate a fix, which can lead to an unhandled exception or a meaningless document change.

The diagnostic must continue to be raised—there is no change to the analyzer's reporting. The code fix provider, on the other hand, must detect that the summary content is empty and simply not register a fix.

**Notes**
- This only affects SA1623. SA1624 cannot fire with an empty summary because it depends on existing text that contains `"Gets or sets"`.

Implemented proposed changes from code review


**Title:** File header code fix should preserve other XML header elements when copyright is missing or incorrect

**Background**
The StyleCop file header rules SA1634 (file must have a copyright header) and SA1636 (copyright text must match the configured text) each provide a code fix via `FileHeaderCodeFixProvider`. Currently the fix replaces the **entire** file‑header comment block with a new header containing only the copyright element. This means any existing elements like `<author>`, `<summary>`, `<file>`, etc. are discarded when the user applies the fix.

**Desired behavior**

For **well‑formed XML** file headers the code fix should:

- **SA1634 (missing copyright element):** Insert a complete `<copyright>` element at the correct position in the header without disturbing other elements.
- **SA1636 (copyright text mismatch):** Update *only* the text content inside the existing `<copyright>` element, preserving its attributes and its place among the other header elements.
- Handle multi‑line copyright text correctly, including lines that appear after a blank line inside the element.
- Handle self‑closing copyright elements (`<copyright … />`).

For **malformed** headers (comment blocks that are not valid XML) the fix may fall back to the current behaviour of replacing the entire header.

**Additional comparer issue**

When the analyzer compares multi‑line copyright text from the source against the configured `copyrightText`, leading whitespace on continuation lines (the space inserted after the `// ` comment prefix) is not properly normalised. This causes false‑positive SA1636 reports. The comparison should trim or normalise this whitespace so that only the logical copyright text is compared.

**Acceptance criteria (behavioural)**

1. Given a well‑formed XML header where only the copyright text is wrong, applying the SA1636 fix leaves `<author>`, `<summary>`, and other elements untouched and updates only the text lines inside the `<copyright>` element to match the configured text.
2. Given a well‑formed header that is missing the `<copyright>` element entirely, applying the SA1634 fix inserts a new `<copyright>` element (for example at the top of the header) without deleting other elements.
3. A malformed header (e.g., lines that cannot be parsed as valid XML) still causes the fix to replace the whole header, as it does today.
4. The SA1636 diagnostic no longer fires when the difference between the configured text and the source is only in comment‑continuation whitespace.

Please implement these changes in the code fix provider and the corresponding analyzer logic.

Fix so for well formed copyright headers so only the copyright tag is updated. On malformed headers the whole header is replaced.


SA1214 diagnostic location is wrong

The SA1214 rule "Static readonly elements must appear before static non-readonly elements" reports diagnostics on the wrong syntax node. When a readonly static field is placed after a non-readonly static field, the squiggle currently appears on the variable identifier (e.g., the `j` in `static readonly int j = 0;`). This is misleading because the rule is about ordering of whole field declarations, not individual variables within a declaration. The diagnostic should be attached to the entire field declaration, consistent with other ordering rules in the suite.

Additionally, the rule should not produce any diagnostics when all static fields in a type are readonly (i.e., there is no static non-readonly field present). Please ensure that case remains clean and is covered.


**Title:** SA1516 does not enforce blank lines around `extern alias` inside file-scoped namespaces (C# 10)

**Background**
Rule SA1516 (Elements must be separated by blank line) already handles `extern alias` directives when they appear outside of a namespace declaration, and for regular (block‑scoped) namespace declarations. File‑scoped namespace support was added in a previous release, but `extern alias` directives inside file‑scoped namespaces are currently ignored by both the analyzer and the code fix.

**Observed behavior**
For a file‑scoped namespace that contains `extern alias`, `using`, and member declarations:
- Missing blank lines between the namespace name and the first `extern alias` directive are not reported.
- Missing blank lines between the last `extern alias` and the first `using` directive are not reported.
- Missing blank lines between the last `using` directive and the first member declaration are not reported (even when no `extern alias` is present, this gap was already partially missing from the original file‑scoped namespace implementation).

**Expected behavior**
Inside a file‑scoped namespace, SA1516 should require blank lines in the same way it does for regular namespace declarations:
- A blank line between the namespace name and the first `extern alias` (if any exist).
- A blank line between the last `extern alias` and the first `using` (if both groups are present).
- A blank line between the namespace name and the first `using` (when no `extern alias` are present).
- A blank line between the last `using` and the first member declaration.

The code fix (`SA1516CodeFixProvider`) must also be updated so that when a diagnostic is raised for an `extern alias` node inside a file‑scoped namespace, the fix provider correctly locates that node as the relevant element to insert blank lines around.

**Edge cases**
- File‑scoped namespace with `extern alias` only, no usings or members.
- File‑scoped namespace with `extern alias` and members, but no usings.
- File‑scoped namespace with `extern alias`, usings, and members – all combinations of missing blank lines between the groups.
- Multiple `extern alias` directives – only the boundaries between groups matter, not between individual `extern alias` directives themselves (unless otherwise required by settings).
- The existing `stylecop.json` settings that affect blank line placement (e.g., `usingDirectives.blankLinesBetweenUsingGroups`) should continue to be respected; the new handling should call the same internal helpers already used for usings and members elsewhere.

The analyzer and code fix should remain compatible with all C# language versions; the change should only affect file‑scoped namespace contexts that already exist in the codebase.


When running **SA1314** (type parameter names must begin with 'T'), the code fix suggests a new name by prefixing 'T' to the existing name. However, the rename suggestion does not fully check for naming conflicts. It only avoids colliding with type parameters of the immediately enclosing type, but does not check against other declarations in the same scope — such as sibling classes, methods, or other members in the enclosing namespace or type. As a result, the code fix can propose a name that would cause a compile-time duplicate-name error when applied.

**Expected behavior:** The rename logic must validate the proposed name against all relevant declarations in the scope where the type parameter is introduced, not just against the enclosing type's own type parameters. In particular:

- For a type parameter on a class/struct/interface, the new name must not conflict with any other type or member in the encompassing namespace/type.
- For a type parameter on a method, the new name must not conflict with members of the enclosing type, other local declarations where applicable, or types in the namespace.
- If the obvious 'T'-prefixed name would conflict, the code fix should either not offer a rename, or propose an alternative non-conflicting name (the exact strategy is less important than never offering an invalid conflicting rename).

A concrete scenario: given a namespace containing `class TFoo {}` and a class `Bar<Foo> {}`, SA1314 flags `Foo`. The code fix must **not** suggest the rename `T Foo` → `TFoo`, because `TFoo` already exists in the namespace.

No change is needed to the diagnostic itself; only the rename validation inside the code-fix path is affected.

Add tests and additional cases to SA1314


**Issue:** SA1001 "Commas must be spaced correctly" falsely reports a violation for commas inside multidimensional array declarations such as `int[,]` or `int[,,]`. In these declarations the comma is immediately followed by the closing bracket `]`, which is standard C# syntax; no space is required after the comma.

**Expected behavior:**
- The analyzer should **not** require a space after a comma when the next token is a closing bracket (`]`) — the same way it already makes an exception when the next token is a comma or a `>` (for generic type parameter lists like `typeof(Func<,>)`).
- The code fix should similarly **avoid inserting** a space after the comma in these contexts.
- Spaces **before** such commas should still be detected and fixed. For example, `int[, ,]` (space before the second comma) should still be reported and corrected to `int[,,]`.

**Acceptance criteria:**
- `int[,] myArray;` and similar declarations produce no SA1001 diagnostics.
- `int[,,]` (with no spaces) produces no SA1001 diagnostics.
- `int[, ,]` (with a space before the comma that is followed by `]`) produces a diagnostic that the comma was preceded by a space, and the code fix removes that space.
- The behavior for commas followed by `>` in generic parameter lists remains unchanged.

Fix for issue #958. SA1001 reported for multidimensional array declaration.


```
Fix false positive diagnostic for using alias directives that reference a type nested inside a generic type.

Currently, a using alias directive such as:

  using Example = System.Collections.Generic.Dictionary<int, string>.ValueCollection;

triggers a style diagnostic where none is expected. The diagnostic incorrectly claims the alias is not ordered correctly, uses an invalid name, or otherwise flags the declaration as violating a readability rule even though the declaration is valid.

The expected behavior is that using alias directives with a target type that is a nested type of a generic type do not produce any diagnostic, assuming the alias otherwise conforms to the relevant readability rules. All existing behavior for non-generic nested types, non-nested types, and array types must continue to work correctly.
```

Fix incorrect qualification of types nested within generic types


**Title:** SA1008 and SA1012 produce false positives and incorrect code fixes for C# 8 tuple property patterns

**Environment:** StyleCop.Analyzers `1.2.0-beta*`, C# 8

**Issue:** When using C# 8’s positional pattern matching with property patterns on a tuple, both `SA1008` (Opening parenthesis must be spaced correctly) and `SA1012` (Opening brace must be spaced correctly) report diagnostics that lead to poor or contradictory code fixes.
A typical expression:

```csharp
_ = tuple is ( { Length: 1 }, { Length: 2 });
```

triggers unexpected spacing warnings. The analyzers either miss required spaces or suggest spaces that make the formatting inconsistent with normal pattern‑matching conventions.

**Expected behavior:**

- `SA1008` should enforce a space between `is` and `(`, and a space after that `(` when it begins a positional pattern clause.
- `SA1012` should accept **no** space between `(` and `{` when the brace opens a property pattern that immediately follows the opening parenthesis of a positional pattern (i.e., `({` is valid). It must still require a space **after** `{`, so `{ Length: …` is correct.
- The supplied code fixes should produce the proper formatting:
  ```csharp
  _ = tuple is ({ Length: 1 }, { Length: 2 });
  ```

**Current behavior (example of problems):**

1. `SA1008` does not recognize the positional pattern clause, so it fails to report a missing space before `(` after `is`, and it may not report the missing space after `(`.
2. `SA1012` flags the absence of a space before `{` in `( {`, even though no space is desired in this specific context, and suggests inserting one. This leads to an incorrect suggestion to change `({` → `( {`, which then conflicts with other spacing rules.

**Potential constraints / edge cases:**
- The fix should only affect spacing inside a property pattern that is a direct sub‑expression of a positional pattern clause after the `is` keyword.
- The fix must not alter spacing behavior in other contexts where a `(` precedes a `{` (e.g., collection initializers, array initializers, lambda bodies).
- It should work correctly for nested patterns and for tuples with more than two elements.
- The code fix for `SA1012` should remove an unwanted space before `{` in this scenario, but it must preserve leading/trailing space semantics everywhere else.

**Impact:** Developers using tuple pattern matching get noisy, incorrect warnings and are offered code fixes that produce invalid or style‑violating formatting, undermining trust in the analyzer and complicating code reviews.

Fix SA1008 and SA1012 for pattern matching tuples


The SA1412 code fix (Store files as UTF-8 with byte order mark) does not offer a Fix All option in the lightbulb preview. When a solution contains many non‑UTF‑8 files, the developer has to apply the fix to each file individually, which is slow and error‑prone.

Other StyleCop analyzers in the same repository (for example, SA1407/SA1408) already support Fix All across document, project, and solution scopes.

We need SA1412 to provide a Fix All provider that:
- works for every standard fix‑all scope (Document, Project, Solution)
- applies the same encoding transformation as the existing single‑document SA1412 code fix (convert the file to UTF‑8 with BOM)
- skips documents that already satisfy SA1412 (i.e., documents for which the analyzer produces no diagnostic), so that unaffected files are left untouched
- correctly updates the solution so that all fixed documents are stored with the new encoding and receive new document IDs (as the current single‑document code fix does)

The per‑document transformation logic already exists and is used by the single‑document fix; the fix‑all provider should reuse it rather than duplicating the logic.

This should be implemented in a way that is consistent with the existing fix‑all implementations in the maintainability rules area (e.g., the SA1407/1408 FixAllProvider), so that the project’s patterns are followed.


**Bug: SA1127 code fix indents constraint clause incorrectly when XML comments or `#region` directives precede the method**

**Observed Behavior**
When StyleCop Analyzers rule SA1127 (generic type constraint clause must be placed on its own line) triggers on a method that has XML doc comments or a `#region` directive immediately before it, the automatic code fix inserts the new line containing the `where` clause with wrong indentation. The indentation is either missing (zero spaces) or unexpectedly large, instead of matching the method declaration’s indentation.

**Expected Behavior**
After applying the code fix, the constraint clause should be placed on a new line indented to the same level as the method declaration — exactly as the fix does when no doc comments or directives precede the method.

**Steps to Reproduce**
1. Create a class with a generic method that places the `where` clause on the same line as the method signature, and precedes the method with an XML doc comment (e.g., `<summary>...</summary>`) or a `#region` directive.
2. Enable SA1127 and run the code fix.
3. Observe the resulting indentation of the inserted constraint line.

**Additional Context**
The problem occurs whenever the method declaration has leading trivia that includes whitespace on lines before the declaration itself. The fix should extract the indentation of the declaration line (the last whitespace trivia before the token that starts the declaration) rather than summing or incorrectly handling whitespace from earlier trivia lines. The fix must work correctly for any combination of leading trivia that may appear before a method declaration, including XML documentation comments, preprocessor directives, blank lines, and any mixture thereof.

Fix SA1127 code fix indenting when additional preceding trivia is present (#1652)


**SA1119: Parentheses around implicit stackalloc array creation should not be flagged as unnecessary**

In C# 8, `stackalloc` can appear without an explicit element type when the element type can be inferred (e.g., `stackalloc[] { 0 }`). SA1119 currently only exempts parentheses around the explicit form (`stackalloc byte[1]`) when used in a variable initializer. The same exemption should apply to the implicit form.
A statement like
```csharp
var span = (stackalloc[] { 0 });
```
should not produce SA1119. Do not report a diagnostic for unnecessary parentheses when a parenthesized implicit stackalloc array creation expression appears as the value of an equals-value clause.


Bug Report: Stream terminates when display configuration changes during KMS capture**

**Summary**
When streaming from an X11 session using the KMS capture backend, the stream terminates abruptly if the display configuration changes (e.g., resolution change, monitor hotplug, or switching display modes). The capture thread encounters a failure when accessing the DRM framebuffer and treats it as a fatal error, causing the entire streaming session to disconnect.

**Environment**
- Platform: Linux (KMS/DRM capture)
- Display server: X11
- Capture method: KMS via `kmsgrab.cpp`

**Steps to Reproduce**
1. Start a streaming session from an X11 desktop using KMS capture.
2. While streaming, change the display resolution or perform an action that triggers a display reconfiguration (e.g., `xrandr --output ... --mode ...` or connecting/disconnecting a monitor).
3. Observe that the stream disconnects immediately with an error logged: "Couldn't get drm fb for plane [...]".

**Expected Behavior**
The capture system should recognize that framebuffer acquisition may temporarily fail during display reconfiguration. Instead of terminating the stream, it should treat this as a transient condition—similar to a capture timeout—and allow the capture loop to retry on the next frame. This would allow the stream to recover automatically once the display reconfiguration completes.

**Actual Behavior**
The capture returns `capture_e::error` when `card.fb()` fails to retrieve the framebuffer for a plane. This propagates up to the main capture loop, which terminates the streaming session.

**Impact**
Users cannot adjust display settings (resolution, rotation, multi-monitor layout) without interrupting active streams. This is particularly problematic for headless or virtual display setups where configuration changes are common.

**Technical Context**
The issue occurs in the KMS capture implementation when querying plane properties during a display reconfiguration window. During this period, the DRM framebuffer ID may be invalid or transitional, causing `drmModeGetFB2` (or similar) to fail. The current implementation logs this as a fatal error and returns `capture_e::error`, whereas `capture_e::timeout` would be more appropriate to indicate that the capture should skip this frame and continue operating.

**Suggested Resolution**
Modify the framebuffer acquisition logic in the KMS capture path to distinguish between permanent capture failures and transient conditions caused by display reconfiguration. When the framebuffer is temporarily unavailable due to reconfiguration, the implementation should return `capture_e::timeout` to allow graceful degradation (dropping the affected frame) rather than terminating the stream.

Fix stream disconnecting when reconfiguring display in X11


 Fix builds and shutdown sequences when the system tray is disabled. During shutdown, `system_tray::end_tray()` is invoked unconditionally in the signal handlers within `main()`, causing link errors or runtime failures when the tray is compiled out or disabled via configuration.

Guard the calls to `system_tray::end_tray()` in the shutdown paths with checks against both the compile-time constant `tray_is_enabled` and the runtime configuration `config::sunshine.system_tray` before attempting to terminate the tray service. Ensure this applies to all exit handlers (e.g., SIGINT/SIGTERM signal handlers and the Windows console control handler paths).

fix: building without the system tray enabled (#5092)


 As a user with a multi-GPU setup (e.g., display connected to an AMD or Intel GPU, but with an NVIDIA GPU available for compute), I want to be able to force the use of NVENC encoding even when Sunshine automatically detects that the display is not connected to the NVIDIA GPU.

Currently, when the encoder is set to "nvenc", Sunshine's KMS capture implementation automatically filters out non-NVIDIA GPUs when enumerating display devices, preventing the use of NVENC in hybrid GPU configurations where the display output is handled by a different vendor's GPU.

Acceptance Criteria:
- When the user explicitly configures `encoder = "nvenc"` in the video settings, the system should attempt to initialize NVENC regardless of whether the display is connected to an NVIDIA GPU or a non-NVIDIA GPU (AMD/Intel).
- If the display is connected to a non-NVIDIA GPU but NVENC is explicitly selected, the system must emit a warning indicating that "Using NVENC with your display connected to a different GPU may not work properly!"
- The automatic skipping of non-NVIDIA GPUs should still occur when the encoder is set to automatic detection (i.e., not explicitly "nvenc"), preserving existing behavior for default configurations.

Constraints:
- This change only affects the Linux KMS capture platform (`kmsgrab`).
- The implementation must check the configured encoder value from the video configuration to determine whether the user has explicitly requested NVENC.

Allow NVENC to be forced to try capturing non-Nvidia GPUs


 **Session launch timeout should respect `ping_timeout` configuration**

Currently, when `rtsp_server_t::session_raise()` creates a new streaming session, it applies a hardcoded 10-second timeout while waiting for the client to begin streaming. If the client doesn't connect within this window, the launch event is silently discarded in `clear()`. This timeout should instead respect the existing `config::stream.ping_timeout` configuration value so users can adjust it for their network conditions.

Additionally, when sessions are discarded due to timeout, no diagnostic information is currently emitted, making it difficult to distinguish between a client that failed to connect versus one that simply took too long.

**Expected behavior:**
- The session initialization timeout should use `config::stream.ping_timeout` instead of a fixed 10-second duration
- When a launch event is discarded due to timeout, the debug log should include the session's `unique_id` to aid troubleshooting

**Impact:**
Users on slower networks or with clients that require longer initialization times cannot currently complete streaming setup before the session is automatically cleaned up. This forces unnecessary retry loops and connection failures.


 **Alphabetically sort applications in configuration**

Ensure that when application entries are persisted via the Web UI configuration API (adding, updating, or deleting), the resulting `apps` array is sorted alphabetically by the application name before writing to the configuration file. This provides a consistent, predictable order in the stored configuration and UI presentation.

The sort order should use standard lexicographical string comparison on the `name` field. This applies to all mutation handlers in the configuration HTTP interface that modify the application list.

feat(apps): order apps alphabetically (#3223)


 Fix config parser to correctly handle list values that end at the end of the file.

The config parser in `src/config.cpp` incorrectly reports a "Missing ']'" error when a list value (enclosed in square brackets) is properly closed but positioned at the end of the configuration file. This occurs because the parser treats reaching the end of input while scanning for the closing bracket as an unconditional error, even when the closing bracket is present at the end of the file.

Modify the list parsing logic to distinguish between unclosed lists and properly closed lists at EOF. The parser should only emit the missing bracket error when the opening bracket is immediately followed by the end of file (indicating an empty, unclosed list), not when `skip_list` returns the end iterator due to the closing bracket being the final character in the file.

fix(config): fix parse error when list ends on last line of config file (#3772)


 Modify `controlBroadcastThread` to monitor both the global Sunshine shutdown event (`mail::shutdown`) and the broadcast-specific shutdown event (`mail::broadcast_shutdown`) when determining whether to terminate the control broadcast loop.

Currently, the thread only checks for `broadcast_shutdown`, which prevents it from properly informing connected clients when the entire Sunshine process is exiting gracefully. Update the loop condition to check both events, and ensure the session processing loop breaks early if either shutdown event is triggered. This ensures clients receive termination notifications during both broadcast-specific teardowns and full application shutdowns.

Inform clients of graceful termination when Sunshine exits


 Simplify the display matching logic in the XDG portal capture implementation to use human-readable identifiers and direct string comparison.

Current behavior: Display names use encoded prefixes (`n` prefix for monitor names, `p` prefix for comma-separated coordinates) requiring complex parsing logic to match PipeWire streams.

Desired behavior:
- Format display identifiers as plain, descriptive strings: use the monitor name directly when available; when unavailable, use `position-{X}x{Y}-resolution-{W}x{H}` format
- Replace prefix-parsing matcher with direct string equality between the requested display name and the generated identifier
- Maintain the invariant that empty display names never match
- Update stream iteration in the configuration path to allow selection of stream objects for assignment

Ensure compatibility with the existing PipeWire stream enumeration and portal session management.

feat(linux/xdgportal): Simplify display matching logic (#5053)


 When `always_send_scancodes` is enabled in the configuration, non-normalized key events (those with `SS_KBE_FLAG_NON_NORMALIZED` set) should be converted to scancodes using the **active keyboard layout** rather than the hardcoded US English layout map.

Currently, the code paths for normalized and non-normalized events both fall back to `VK_TO_SCANCODE_MAP` when scancodes are requested. For non-normalized events with `always_send_scancodes` enabled, this produces incorrect scancodes on hosts using non-US layouts. Instead, use `MapVirtualKey` with `MAPVK_VK_TO_VSC` to perform the conversion against the current keyboard layout.

**Edge cases:** `MapVirtualKey` fails to return valid scancodes for `VK_LWIN`, `VK_RWIN`, and `VK_PAUSE`. Skip the `MapVirtualKey` call for these virtual keys and leave their scancodes unset (0) when processing non-normalized events.

fix(win/input): use active keyboard layout for non-normalized key events (#3125)


 **Bug Report: Frame pacing errors accumulate over consecutive frames**

**Description:**
In the Windows display capture implementation, the frame pacing logic maintains timing by incrementing a `next_frame_time` timestamp with a fixed interval duration after each frame. This approach causes timing errors to accumulate over the duration of a frame pacing group. When the actual sleep duration overshoots or undershoots the target, these errors compound frame-over-frame, potentially leading to increased latency and drift from the intended capture rate.

**Expected Behavior:**
Frame timing should be calculated from a stable reference point (the start of the frame pacing group) using the frame index within the group and the rational frame rate representation. This ensures that each frame's target time is independently calculated from the group start rather than incrementally adding intervals to a timestamp that may have accumulated prior timing errors.

**Impact:**
Long-running capture sessions may experience gradual latency increases or inconsistent frame delivery intervals, particularly when the display refresh rate and client frame rate are not exact multiples of each other but are close (e.g., 59.94Hz display with 60fps client). The current workaround of adjusting client frame rates when they are within 99% of the display rate is also sensitive to floating-point precision and could benefit from rational arithmetic.

**Implementation Notes:**
- The `display_refresh_rate` is available as a `DXGI_RATIONAL` structure which should be used to maintain precision when calculating frame intervals.
- The `capture()` method in `display_base_t` should track the group start time (`frame_pacing_group_start`) and a frame counter (`frame_pacing_group_frames`) within the group, rather than maintaining a `next_frame_time` that is iteratively updated.
- When calculating sleep targets, compute the absolute target time from the group start using integer arithmetic: derive whole seconds and remaining nanoseconds from `frame_index * denominator / numerator` and `frame_index * denominator % numerator` respectively, then add to the group start timestamp.

Don't accumulate errors in capture frame pacing


 **Fix unhandled exceptions causing launch failures and malformed XML responses**

The launch process has several failure points where exceptions escape unhandled or produce unhelpful error outputs:

1. **Command parsing crashes**: `find_working_directory` uses `boost::program_options::split_unix` (or `split_winmain` on Windows) to tokenize command strings. If the command contains malformed escape sequences or unmatched quotes, this throws `boost::escaped_list_error`, crashing the launch. This should be caught, logged with the offending command string, and handled gracefully by returning an empty path.

2. **Process wait exceptions**: The `child.wait()` call during command execution throws on failure rather than using the `error_code` overload. This can terminate the session unexpectedly. We should capture the error code, log the specific failure (including the command name), and return -1 to indicate failure.

3. **Silent XML corruption**: In the HTTP launch/resume handlers, if populating the property tree throws an exception, control falls through to the XML serialization with an empty tree, producing malformed XML that causes Moonlight clients to report "Malformed XML (missing root element)". We need a diagnostic check before serialization that logs when the tree is empty, explaining that control flow was likely interrupted by an exception.

4. **Inconsistent error logging**: Process exit code checking currently excludes `std::errc::permission_denied` from error logging, but we should uniformly log all non-zero exits to aid debugging.

**Acceptance criteria:**
- Malformed command strings in `find_working_directory` are handled gracefully with explicit error logging
- `child.wait()` uses error_code and logs failures without throwing
- Empty property trees in HTTP handlers trigger an explanatory error log before the malformed XML response is sent
- All non-zero process exit codes are logged consistently

fix(launch): Fix several launch failure conditions (exceptions thrown in child.wait, and boost::split_unix) (#4390)


 The session monitor window thread in `main()` is currently detached, which risks resource leaks and undefined behavior during application shutdown. Implement proper thread joining with a graceful shutdown mechanism.

Requirements:
- Ensure the session monitor thread can be signaled to exit by posting a message to its window message loop
- Add `WM_CLOSE` and `WM_DESTROY` handlers to `SessionMonitorWindowProc` to break the message loop and call `PostQuitMessage`
- Replace the `detach()` call with a synchronization mechanism that waits for the thread to exit with a timeout (e.g., 1 second)
- Use `util::fail_guard` or equivalent RAII mechanism to guarantee thread cleanup attempts during scope exit regardless of early returns or exceptions
- Handle edge cases where window creation fails (NULL hwnd) by avoiding invalid `PostMessage` calls
- Do not block indefinitely; if the thread fails to exit within the timeout, fall back to `detach()` with a warning log

Properly join session monitor window thread


 **Issue:** The nvhttp HTTPS server does not gracefully close TLS connections, leaving connections vulnerable to truncation attacks and protocol violations. Ensure that all TLS connections are properly shut down before socket closure.

**Acceptance Criteria:**
- When any HTTPS connection to the GameStream server terminates, the TLS layer must perform a graceful shutdown sequence (exchanging close_notify alerts per RFC 5246) before the underlying TCP socket is closed
- The server must continue to operate on port 443 with the existing certificate configuration and client verification rules
- All existing endpoints (`/serverinfo`, `/pair`, `/applist`, `/launch`, etc.) must function identically from the client's perspective, with no changes to request/response behavior or XML/JSON payload formats
- TLS 1.0 and 1.1 must remain disabled; TLS 1.2+ support must be maintained
- Client certificate verification callbacks must continue to execute without modification, including the custom verification logic that triggers specific error responses on validation failures

**Constraints:**
- The fix must be localized to the HTTPS socket lifecycle management within the nvhttp module
- No changes to the public API surface (`nvhttp::start`, `nvhttp::pin`, etc.) or configuration file formats
- Must preserve existing error handling behavior for certificate validation failures

fix(nvhttp): wrap TLS socket to ensure graceful closure (#3077)


 **Feature Request: Detect and warn about NVIDIA GameStream port conflicts**

Sunshine and NVIDIA's GameStream service both bind to port 47989 by default, causing connection failures when both are active simultaneously. We need to detect this conflict at startup and alert users with actionable remediation steps.

**Acceptance Criteria:**

1. **Conflict Detection (Windows):** On Windows platforms, check whether NVIDIA GameStream is enabled in the system configuration during application initialization.

2. **Port Evaluation:** Compare the configured Sunshine HTTP port against the default value (47989). Trigger the warning only when:
   - The configured port matches the default (47989), AND
   - GameStream is detected as enabled

3. **User Notification:** When conflict conditions are met, emit a high-severity log message that:
   - Clearly states that GameStream is enabled and will interfere with Sunshine streaming
   - Provides two remediation options: disable GameStream in GeForce Experience, or change Sunshine's port via the Advanced tab in the Web UI

4. **Non-blocking Operation:** The warning must not prevent Sunshine from starting or functioning; the application should continue initialization normally after logging the warning.

5. **Graceful Handling:** If GameStream status cannot be determined (e.g., registry unavailable, insufficient permissions), startup should proceed silently without error.

**Edge Cases & Constraints:**
- If the user has changed Sunshine's port away from the default, no warning should appear regardless of GameStream status
- On non-Windows platforms, this check must be skipped entirely
- Detection should not rely on network port scanning to avoid false positives from transient connections

Print a warning if GameStream is using conflicting ports