Skip to content

Allow every setting in .editorconfig and document unified configuration - #4221

Merged
AArnott merged 12 commits into
masterfrom
aarnott-unified-editorconfig-settings-docs
Oct 11, 2026
Merged

AArnott merged 12 commits into
masterfrom
aarnott-unified-editorconfig-settings-docs

Conversation

@AArnott

@AArnott AArnott commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Makes .editorconfig/.globalconfig a complete location for all StyleCop settings (stylecop.json and rulesets keep working), and rewrites the configuration docs around it. This supersedes the intent of #3911 and #3197 (no template file; docs instead).

Fixes #3534
Fixes #2551
Fixes #3650
Fixes #3226
Part of #3092 (documents the SA0001 limitation and dotnet_diagnostic usage)
Closes #3911
Closes #3197

Product changes

New .editorconfig keys (stylecop.json still takes precedence):

  • stylecop.ordering.elementOrder (was JSON-only)
  • stylecop.maintainability.topLevelTypes (was JSON-only)
  • stylecop.documentation.variables.<name> (was JSON-only)
  • stylecop.ordering.usingDirectivesPlacement (adds preserve, which the generic key can't express)
  • stylecop.ordering.blankLinesBetweenUsingGroups (adds omit)
  • stylecop.layout.newlineAtEndOfFile (adds explicit allow)

⚑ Reviewer decisions: key names; variables needs key enumeration, so AnalyzerConfigOptionsWrapper.GetKeys() light-up reads AnalyzerConfigOptions.Keys and returns empty on older compilers (variables then stay JSON-only there). EditorConfig lowercases keys, so variable lookup falls back to the lowercase name.

Docs

documentation/Configuration.md now leads with the recommendation, a full settings reference (JSON key ⇄ editorconfig key, values, defaults), and migration tables for stylecop.json and rulesets.

Tests

New tests in SettingsCSharp8UnitTests (keys, precedence, invalid values) and SettingsCSharp11UnitTests (variables, needs Roslyn 4.4 Keys). Settings tests pass on net6.0 and net472.

Performance

Settings are cached per syntax tree; added lookups are a few TryGetValue calls plus one key enumeration per tree on first load.

Add stylecop.ordering.elementOrder, stylecop.ordering.usingDirectivesPlacement,
stylecop.ordering.blankLinesBetweenUsingGroups, stylecop.maintainability.topLevelTypes,
stylecop.layout.newlineAtEndOfFile and stylecop.documentation.variables.<name>.
Rewrite Configuration.md with a settings reference and migration guidance.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@codecov

codecov Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.47739% with 18 lines in your changes missing coverage. Please review.
✅ Project coverage is 97.58%. Comparing base (d51e0fd) to head (73cec6a).
⚠️ Report is 5 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #4221      +/-   ##
==========================================
- Coverage   97.58%   97.58%   -0.01%     
==========================================
  Files        1281     1283       +2     
  Lines      136157   136326     +169     
  Branches     4411     4404       -7     
==========================================
+ Hits       132869   133030     +161     
- Misses       2129     2137       +8     
  Partials     1159     1159              
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

AArnott and others added 6 commits October 10, 2026 12:32
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…NTS.md

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Link to the rule-status page included in the DocFX content instead of the excluded repository README.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@AArnott
AArnott marked this pull request as ready for review October 10, 2026 18:54
Copilot AI balanced review requested due to automatic review settings October 10, 2026 18:54
@AArnott

AArnott commented Oct 10, 2026

Copy link
Copy Markdown
Contributor Author

@bjornhellander what do you think of this?

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Documentation inaccuracies, incomplete compatibility coverage, and repeated reflection should be addressed before approval.

6 open findings
What changed in this PR

Adds complete analyzer configuration through .editorconfig/.globalconfig while retaining stylecop.json precedence.

Changes:

  • Centralizes settings resolution in SettingsReader.
  • Adds new analyzer-config keys and Roslyn light-up support.
  • Expands tests and rewrites configuration documentation.
File Description
SettingsReader.cs Centralizes settings precedence and parsing.
ReadabilitySettings.cs Uses the centralized reader.
OrderingSettings.cs Adds StyleCop-specific ordering keys.
NamingSettings.cs Migrates naming settings parsing.
MaintainabilitySettings.cs Adds topLevelTypes support.
LayoutSettings.cs Adds explicit newline behavior.
IndentationSettings.cs Migrates indentation parsing.
DocumentationSettings.cs Adds analyzer-config variables.
AnalyzerConfigHelper.cs Adds enum parsing helpers.
AnalyzerConfigOptionsWrapper.cs Lights up key enumeration.
SettingsCSharp8UnitTests.cs Tests new configuration keys.
SettingsCSharp11UnitTests.cs Tests variable key enumeration.
Configuration.md Documents unified configuration and migration.
AGENTS.md Establishes settings implementation conventions.

🧠 Review effort: Balanced


💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread documentation/Configuration.md Resolved
Comment thread documentation/Configuration.md Resolved
AArnott and others added 3 commits October 10, 2026 14:31
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…ecedence

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings October 10, 2026 20:36

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread documentation/Configuration.md Resolved
Comment thread documentation/ru-ru/Configuration.md Resolved
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings October 10, 2026 21:01

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Enum parsing accepts undocumented composite or signed values, and the Russian examples remain partially untranslated.

0 open findings

2 resolved since last review
Previously missed (2)

In code that hasn't changed since last review

Medium severity Require Enum.TryParse input to match a defined member name

StyleCop.Analyzers/​StyleCop.Analyzers/​Settings/​ObjectModel/​AnalyzerConfigHelper.cs:130

Enum.TryParse also accepts signed numeric strings and comma-separated combinations. Because only a leading digit is rejected and IsDefined checks the resulting value, inputs such as +1 or insideNamespace,outsideNamespace can select a defined member even though they are outside the documented values. Require the input to match the parsed member name.

Low severity Translate remaining English comments in Russian example

documentation/​ru-ru/​Configuration.md:26

This Russian-localized example still contains English user-facing comments (or ... without ..., Rule severities, and Settings), leaving the example mixed-language. Translate the prose comments while preserving the literal configuration names and values.

This issue also appears on line 107 of the same file.

🧠 Review effort: Balanced

@bjornhellander

bjornhellander commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

@bjornhellander what do you think of this?

I think the general direction looks awesome!

Claude had some concerns, which I have not dug into further:

Must fix

  1. GetKeys() can crash every analyzer on some hosts. In Roslyn 4.4+, the base AnalyzerConfigOptions.Keys getter just
    throws. I checked the IL in 4.4.0 and 5.0.0: it creates an exception object and throws it, which appears to be
    NotImplementedException.
  • Any host whose AnalyzerConfigOptions subclass doesn't override Keys will throw. The compiler's own options class
    does override it, but third-party hosts and test harnesses may not.
  • SettingsReader.GetStringMap (SettingsReader.cs:~178) calls GetKeys() whenever stylecop.json has no variables, which
    is nearly every run. It runs from the DocumentationSettings constructor.
  • Nothing in SettingsHelper.GetSettings/CreateSettingsObjectFromFile catches this exception, so the user would see
    AD0001 from every StyleCop analyzer.
  • The branch's own tests show the problem. SettingsCSharp11UnitTests has to swap in a
    KeysAwareAnalyzerConfigOptionsProvider for all inherited tests. Without it, the existing TestAnalyzerConfigOptions
    (which doesn't override Keys) would hit exactly this throw.
  • Suggested fix: catch NotImplementedException in AnalyzerConfigOptionsWrapper.GetKeys() and return empty. Add a C#11+
    test that uses options without a Keys override.
  1. Performance (per the analyzer-performance skill). Settings are built once per syntax tree per analyzer. Every build
    now walks every editorconfig key for the file (all dotnet_diagnostic.* and IDE keys too) and runs a case-insensitive
    prefix check on each. Before, this path only did a few direct lookups. It's probably small, but maintainers don't
    accept perf risk, so it needs a justification or a cheaper approach.

Behaviour changes worth calling out

  1. Variable lookup is now case-insensitive for stylecop.json too. The fallback
    Variables.TryGetValue(key.ToLowerInvariant(), …) (DocumentationSettings.cs:~320) also applies to JSON variables. A
    JSON variable licensename now matches {LicenseName}, which it didn't before. It's harmless but undocumented. It
    could be limited to editorconfig-sourced names.
  2. excludeFromPunctuationCheck in JSON is now stricter. The old code used value.AsString; the new code uses
    ToStringValue(jsonKey), which throws InvalidSettingsException on a non-string entry. Because of how invalid
    settings are handled, the whole settings object then quietly falls back to defaults, so company name, header and so
    on are lost.
  3. Inconsistent case handling for editorconfig values.
    • The new GetEnum/GetEnumList ignore case: Preserve and preserve both work.
    • fileNamingConvention, tupleElementNameCasing and indent_style still match exact strings.
    • Separately, Enum.TryParse accepts comma-joined names, so a value like allow, require can combine flags. That
      combined value can be a different valid member, so it isn't always rejected.
  4. variables is all-or-nothing. If stylecop.json has any variables, all editorconfig variables are ignored rather than
    merged. This fits the "same setting, JSON wins" rule, but the docs should say so.

Documentation

  1. The template's warning about trailing comments is wrong. Roslyn's property regex is
    ^\s*([\w.-_]+)\s*[=:]\s*(.?)\s([#;].*)?$ (taken from the 4.4.0 binary), so # … and ; … at the end of a line are
    stripped. The real limitation goes the other way: a value can't contain # or ;. That matters for copyrightText,
    headerDecoration (such as #####) and variable values. Since the docs now say "every setting can be set there" and
    recommend editorconfig first, this limitation should be documented.
  2. The rest of the reference table looks right against the code: defaults, the generic-key mappings
    (dotnet_separate_import_directive_groups false→allow, true→require; insert_final_newline) and the precedence notes.

Documentation

  1. The template's warning about trailing comments is wrong. Roslyn's property regex is
    ^\s*([\w.-_]+)\s*[=:]\s*(.?)\s([#;].*)?$ (taken from the 4.4.0 binary), so # … and ; … at the end of a line are
    stripped. The real limitation goes the other way: a value can't contain # or ;. That matters for copyrightText,
    headerDecoration (such as #####) and variable values. Since the docs now say "every setting can be set there" and
    recommend editorconfig first, this limitation should be documented.
  2. The rest of the reference table looks right against the code: defaults, the generic-key mappings
    (dotnet_separate_import_directive_groups false→allow, true→require; insert_final_newline) and the precedence notes.

Tests

  1. VerifyStyleCopJsonTakesPrecedenceOverEditorConfigAsync sets file_header_template but never checks CopyrightText, so
    the fallback-key path isn't verified there.
  2. Nothing covers a host whose options don't implement Keys (see Implement diagnostic SA1000 KeywordsMustBeSpacedCorrectly #1).

Scope and consistency

  1. The AGENTS.md changes are out of scope. A repo-wide file-scoped-namespace rule is a policy change unrelated to
    this PR, and maintainers may want it separately.
  2. The new rule contradicts the code. The new SettingsReader rule says "Don't read AnalyzerConfigOptions … directly",
    yet LayoutSettings (insert_final_newline) and OrderingSettings (csharp_using_directive_placement,
    dotnet_separate_import_directive_groups) still call AnalyzerConfigHelper directly for the generic fallbacks.
    Either soften the rule or add a secondary-key overload to SettingsReader.
  3. Minor:
    • KeysAccessor uses CreateSyntaxPropertyAccessor on a type that isn't syntax. It works, but the name is
      misleading.
    • The wrapper writes System.Collections.Generic.IEnumerable in full instead of adding a using.

Verdict: the refactor is clean and the docs are a clear improvement. I'd block on #1, and ask for #2, #7 and #11/#12
to be addressed before merge.

@AArnott

AArnott commented Oct 11, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, @bjornhellander .

… feedback

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings October 11, 2026 14:13
@AArnott

AArnott commented Oct 11, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for passing this along. I checked each claim against the code and, where useful, against a running compiler. Fixes are in 73cec6a.

Confirmed and fixed

  • 1 / 10 (Keys throws): Correct. The base AnalyzerConfigOptions.Keys throws NotImplementedException. GetKeys() now catches it and returns an empty list. A new CSharp11 test (VerifyHostWithoutKeysSupportDoesNotThrowAsync) uses a host with no Keys override.
  • 2 (performance): Reasonable concern. Variables are only needed by the file-header rules, so the .editorconfig key walk is now lazy and happens on first Variables access, not for every settings object. stylecop.json variables are still read eagerly, so invalid JSON is still reported at the same time.
  • 3 (case-insensitive JSON variables): Correct. That was an unintended behavior change. I removed the lowercase fallback lookup. Only .editorconfig-sourced variables (EditorConfig lowercases keys) use a case-insensitive dictionary. JSON lookups are as before.
  • 5 (case handling): Partly true. indent_style, tupleElementNameCasing and fileNamingConvention were exact-match, so they are now case-insensitive like the other enums. The Enum.TryParse comma-join point is also real, so values containing , are now rejected. A test covers both.
  • 6 (variables not merged): True and by design. It is now documented in the migration steps.
  • 7 (trailing comments): Correct. I confirmed with a test that value # comment is stripped, and that the real limitation is that values can't contain # or ;. I replaced the wrong warning in the English and Russian docs with that limitation, and with the advice to use stylecop.json for such values.
  • 9 (test gap): The precedence test now also asserts the file_header_template fallback.
  • 12 (rule vs. code): Fair. Rather than soften the rule, I added a fallback-key overload to SettingsReader.GetEnum. insert_final_newline, csharp_using_directive_placement and dotnet_separate_import_directive_groups now go through the reader, so no settings class reads AnalyzerConfigHelper directly.
  • 13: Added the using System.Collections.Generic;. The CreateSyntaxPropertyAccessor name is the existing light-up helper for any property getter, so I kept it.

Not changed

  • 4 (excludeFromPunctuationCheck): True, it is stricter now. The old AsString silently yielded null entries for non-strings. Every other string-list setting already throws InvalidSettingsException for non-strings, so this brings it in line. If you'd rather keep the old leniency, tell me.
  • 11 (AGENTS.md): The file-scoped namespace rule was added in response to an earlier review request on this PR. It's a separate commit, so it's easy to drop if the maintainers want it elsewhere.
  • 8: Agreed, no action needed.

Settings tests pass in CSharp8 (net6.0 and net472) and CSharp11, with zero warnings. The documentation localization test also passes.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The configuration reference contains a schema-incompatible value spelling and untranslated Russian guidance.

0 open findings

Previously missed (3)

In code that hasn't changed since last review

Low severity Use schema-compliant PascalCase spelling

documentation/​Configuration.md:66

This row advertises pascalCase for stylecop.json, but Settings/stylecop.schema.json:145-152 only permits camelCase and PascalCase, and the detailed reference below also names the default PascalCase. Schema-aware editors will reject the documented lowercase spelling even though the runtime parser is lenient, so use the schema spelling here.

Low severity Translate remaining English guidance into Russian

documentation/​ru-ru/​Configuration.md:26

This explanatory sentence remains in English in the Russian-localized document. Translate it so readers do not encounter mixed-language guidance.

Low severity Использовать написание PascalCase из схемы

documentation/​ru-ru/​Configuration.md:74

В этой строке для stylecop.json указано pascalCase, однако схема Settings/stylecop.schema.json:145-152 разрешает только camelCase и PascalCase. Редакторы с проверкой схемы отклонят документированный вариант в нижнем регистре, поэтому здесь следует использовать написание из схемы.

🧠 Review effort: Balanced

This was referenced Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants