From baf215fd33ed3a0a857a5b96a1f18ae5145be6f8 Mon Sep 17 00:00:00 2001 From: Richard Robertson Date: Thu, 24 Mar 2022 10:14:19 -0500 Subject: [PATCH] Initial commit --- .editorconfig | 20 + .gitignore | 454 +++++++++++++++ .vscode/launch.json | 26 + .vscode/tasks.json | 53 ++ CHANGELOG.md | 12 + LICENSE.md | 25 + README.md | 238 ++++++++ .../RoslynMemberSorter.Tests.csproj | 24 + RoslynMemberSorter.Tests/UnitTests.cs | 340 +++++++++++ RoslynMemberSorter.sln | 28 + RoslynMemberSorter/Accessibility.cs | 37 ++ RoslynMemberSorter/DeclarationComparer.cs | 540 ++++++++++++++++++ .../DeclarationComparerOptions.cs | 412 +++++++++++++ RoslynMemberSorter/DiagnosticIds.cs | 14 + RoslynMemberSorter/Extensions.cs | 74 +++ RoslynMemberSorter/FieldMutability.cs | 22 + RoslynMemberSorter/MemberSorterAnalyzer.cs | 76 +++ .../MemberSorterCodeFixProvider.cs | 66 +++ RoslynMemberSorter/NameOrder.cs | 22 + RoslynMemberSorter/Order.cs | 23 + RoslynMemberSorter/ParameterSortStyle.cs | 24 + RoslynMemberSorter/README.md | 3 + RoslynMemberSorter/RoslynMemberSorter.csproj | 41 ++ RoslynMemberSorter/SortOrder.cs | 42 ++ 24 files changed, 2616 insertions(+) create mode 100644 .editorconfig create mode 100644 .gitignore create mode 100644 .vscode/launch.json create mode 100644 .vscode/tasks.json create mode 100644 CHANGELOG.md create mode 100644 LICENSE.md create mode 100644 README.md create mode 100644 RoslynMemberSorter.Tests/RoslynMemberSorter.Tests.csproj create mode 100644 RoslynMemberSorter.Tests/UnitTests.cs create mode 100644 RoslynMemberSorter.sln create mode 100644 RoslynMemberSorter/Accessibility.cs create mode 100644 RoslynMemberSorter/DeclarationComparer.cs create mode 100644 RoslynMemberSorter/DeclarationComparerOptions.cs create mode 100644 RoslynMemberSorter/DiagnosticIds.cs create mode 100644 RoslynMemberSorter/Extensions.cs create mode 100644 RoslynMemberSorter/FieldMutability.cs create mode 100644 RoslynMemberSorter/MemberSorterAnalyzer.cs create mode 100644 RoslynMemberSorter/MemberSorterCodeFixProvider.cs create mode 100644 RoslynMemberSorter/NameOrder.cs create mode 100644 RoslynMemberSorter/Order.cs create mode 100644 RoslynMemberSorter/ParameterSortStyle.cs create mode 100644 RoslynMemberSorter/README.md create mode 100644 RoslynMemberSorter/RoslynMemberSorter.csproj create mode 100644 RoslynMemberSorter/SortOrder.cs diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..5216c7a --- /dev/null +++ b/.editorconfig @@ -0,0 +1,20 @@ +# EditorConfig is awesome: https://EditorConfig.org + +# top-most EditorConfig file +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = crlf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.csproj] +indent_style = space +indent_size = 2 + +[*.md] +indent_style = space +indent_size = 4 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2afa2e2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,454 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET +project.lock.json +project.fragment.lock.json +artifacts/ + +# Tye +.tye/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +## +## Visual studio for Mac +## + + +# globs +Makefile.in +*.userprefs +*.usertasks +config.make +config.status +aclocal.m4 +install-sh +autom4te.cache/ +*.tar.gz +tarballs/ +test-results/ + +# Mac bundle stuff +*.dmg +*.app + +# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# JetBrains Rider +.idea/ +*.sln.iml + +## +## Visual Studio Code +## +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..e37e14a --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,26 @@ +{ + "version": "0.2.0", + "configurations": [ + { + // Use IntelliSense to find out which attributes exist for C# debugging + // Use hover for the description of the existing attributes + // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md + "name": ".NET Core Launch (console)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + // If you have changed target frameworks, make sure to update the program path. + "program": "${workspaceFolder}/RoslynMemberSorter.Tests/bin/Debug/net6.0/RoslynMemberSorter.Tests.dll", + "args": [], + "cwd": "${workspaceFolder}/RoslynMemberSorter.Tests", + // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console + "console": "internalConsole", + "stopAtEntry": false + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach" + } + ] +} diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 0000000..0e432bc --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,53 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "build", + "command": "dotnet", + "type": "process", + "args": [ + "build", + "${workspaceFolder}/RoslynMemberSorter.Tests/RoslynMemberSorter.Tests.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "publish", + "command": "dotnet", + "type": "process", + "args": [ + "publish", + "${workspaceFolder}/RoslynMemberSorter.Tests/RoslynMemberSorter.Tests.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "watch", + "command": "dotnet", + "type": "process", + "args": [ + "watch", + "run", + "--project", + "${workspaceFolder}/RoslynMemberSorter.Tests/RoslynMemberSorter.Tests.csproj" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "test", + "command": "dotnet", + "type": "process", + "args": + [ + "test", + "-l", + "liquid.md" + ], + "problemMatcher": [] + } + ] +} diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..485f892 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,12 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +## [0.1.0-alpha] March 25, 2022 + +Initial release diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..5508d87 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,25 @@ +The MIT License (MIT) +===================== + +Copyright © `2022` `Richard Robertson` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..025f45b --- /dev/null +++ b/README.md @@ -0,0 +1,238 @@ +# RoslynMemberSorter + +RoslynMemberSorter uses Roslyn code analysis to detect out of order namespace and type member declarations in C# projects. + +## Installation + +Use the dotnet CLI to install RoslynMemberSorter to a project: + +``` +dotnet add package RichardRobertson.RoslynMemberSorter --version 0.1.0-alpha +``` + +Or add it to your `.csproj` manually in an ``: + +```xml + + + + + all + analyzers + + + +``` + +## Usage + +RoslynMemberSorter uses configuration lines in `.editorconfig`. Some options use comma delimited lists while others use a single enumeration value. Each option will be listed below with its default setting and other available values. + +When a namespace or type is found with members out of order, diagnostic `RMS0001` is emitted on the identifier of the namespace or type. + +Invalid assignments are silently ignored. +- For list options, the invalid list item will be dropped. + - E.g. for `...accessibility = private, bad_value, public`, the item `bad_value` is dropped and `private, public` will be used. +- For single value options, the assignment will be dropped, and the default will +be used. + - E.g. for `...static = bad_value`, the default value of `first` will be used. + +### Accessibility order + +Members can be sorted based on their accessibility level. Any accessibility level not in the list will be placed first due to how the sort works internally. + +This option is used during the `accessibility` sorting stage. + +```editorconfig +dotnet_diagnostic.rms0001.accessibility_order = public, protected_internal, internal, protected, private_protected, private +``` + +The default value is listed above and contains all possible values. + +### Alphabetical identifiers + +Members can be sorted alphabetically by name. + +This option is used during the `identifier` sorting stage. + +```editorconfig +dotnet_diagnostic.rms0001.alphabetical_identifiers = alphabetical +``` + +The default value is listed above. Choices for this option are: +| Value | Definition | +| - | - | +| `default` | Names are not sorted alphabetically. | +| `alphabetical` | Names are sorted in alphabetical order. | +| `reverse_alphabetical` | Names are sorted in reverse alphabetical order. | + +### Explicit interface specifier + +Types can define members that implement interfaces explicitly. These have no inherent accessibility but can be sorted before or after other members of the same kind. + +This option is used during the `explicit_interface_specifer` sorting stage. + +```editorconfig +dotnet_diagnostic.rms0001.explicit_interface_specifier = default +``` + +The default value is listed above. Choices for this option are: +| Value | Definition | +| - | - | +| `default` | Explicit interface implementation is ignored for sorting purposes. | +| `first` | Members that explicitly implement an interface are sorted before members that do not. | +| `last` | Members that explicitly implement an interface as sorted after members that do not. | + +### Field order + +Fields can be sorted based on their mutability. Any mutability level not in the list will be placed first due to how the sort works internally. + +This option is used during the `field_order` sorting stage. + +```editorconfig +dotnet_diagnostic.rms0001.field_order = constant, read_only, mutable +``` + +The default value is listed above and contains all possible values. Each mutability level is defined as: +| Value | Definition | +| - | - | +| `constant` | Fields declared with the `const` modifier. | +| `mutable` | Fields declared with neither the `const` nor the `readonly` modifier. | +| `read_only` | Fields declared with the `readonly` modifier. | + +### Kind order + +Members can be sorted based on what kind of member they are. Examples are properties, nested classes, and constructors. Any type not in the list will be placed first due to how the sort works internally. + +This option is used during the `kind` sorting stage. + +```editorconfig +dotnet_diagnostic.rms0001.kind_order = field, constructor, destructor, indexer, property, event_field, event, method, operator, conversion_operator, enum, interface, struct, class, record, record_struct, delegate +``` + +The default value is listed above and contains all possible values. The names come from the Roslyn enum [SyntaxKind](https://docs.microsoft.com/en-us/dotnet/api/microsoft.codeanalysis.csharp.syntaxkind). + +### Low arity + +Constructors, delegates, indexers, and methods can be sorted by the number of parameters they define. Arity of a method is the number of parameters it has; therefore, `void none()` has arity of zero and `void three(int a, int b, int c)` has an arity of three. + +This option is used during the `parameters` sorting stage. + +```editorconfig +dotnet_diagnostic.rms0001.low_arity = first +``` + +The default value is listed above. Choices for this option are: +| Value | Definition | +| - | - | +| `default` | Method arity is ignored for sorting purposes. | +| `first` | Methods with low arity come before methods with high arity. | +| `last` | Methods with low arity come after methods with high arity. | + +### Operator order + +Overloaded operators do not have names but instead use tokens and keywords to identify them. Any operator not in the list will be placed first due to how the sort works internally. + +This option is used during the `identifier` sorting stage. + +```editorconfig +dotnet_diagnostic.rms0001.operator_order = plus, minus, exclamation, tilde, plus_plus, minus_minus, asterisk, slash, percent, ampersand, bar, caret, less_than_less_than, greater_than_greater_than, equals_equals, exclamation_equals, less_than, greater_than, less_than_equals, greater_than_equals, true, false +``` + +The default value is listed above and contains all possible values. The names come from the Roslyn enum [SyntaxKind](https://docs.microsoft.com/en-us/dotnet/api/microsoft.codeanalysis.csharp.syntaxkind). + +### Parameter sort style + +Constructors, delegates, indexers, and methods can be sorted by the types or names of parameters they define. + +This option is used during the `parameters` sorting stage. + +```editorconfig +dotnet_diagnostic.rms0001.parameter_sort_style = sort_types +``` + +The default value is listed above. Choices for this option are: +| Value | Definition | Example | +| - | - | - | +| `default` | Parameter types and names are ignored for sorting purposes. | | +| `sort_types` | Sort members using the type name of their parameters. | `void method(int b)` before `void method(string a)` | +| `sort_names` | Sort members using the name of their parameters. | `void method(string a)` before `void method(int b)` | + +### Single line events + +Events can be sorted based on whether they are defined on a single line or with accessors. + +> Single line events look like fields. +> ```C# +> public event System.EventHandler MyEvent; +> ``` +> Events with accessors look like properties. +> ```C# +> public event System.EventHandler MyEvent +> { +> add => throw new System.NotImplementedException(); +> remove => throw new System.NotImplementedException(); +> } +> ``` + +This option is used during the `kind` sorting stage. + +```editorconfig +dotnet_diagnostic.rms0001.single_line_events = default +``` + +The default value is listed above. Choices for this option are: +| Value | Definition | +| - | - | +| `default` | Single line or accessor status is ignored for sorting purposes. | +| `first` | Single line events come before events with accessors. | +| `last` | Single line events come after events with accessors. | + +### Sort orders + +The order that each member detail may be sorted can be configured. This influences which details are sorted at all as well as the order they are grouped by. Any detail not in the list will not be sorted at all. + +> Changing the order sorts are done can drastically change the final order. For example: +>- `sort_orders = static, accessibility` can produce the order +> - `public static int PublicStatic;` +> - `private static int PrivateStatic;` +> - `public int PublicInstance;` +> - `private int PrivateInstance;` +>- `sort_orders = accessibility, static` can produce the order +> - `public static int PublicStatic;` +> - `public int PublicInstance;` +> - `private static int PrivateStatic;` +> - `private int PrivateInstance;` + +```editorconfig +dotnet_diagnostic.rms0001.sort_orders = kind, static, field_order, accessibility, explicit_interface_specifier, identifier, parameters +``` + +The default value is listed above and contains all possible values. + +### Static order + +Members can be sorted based on being static or instance. + +This option is used during the `static` sorting stage. + +```editorconfig +dotnet_diagnostic.rms0001.static = first +``` + +The default value is listed above. Choices for this option are: +| Value | Definition | +| - | - | +| `default` | Static or instance status is ignored for sorting purposes. | +| `first` | Static members come before instance members. | +| `last` | Static members come after instance members. | + +## Contributing + +Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. + +Please make sure to update tests as appropriate. + +## License + +[MIT](https://choosealicense.com/licenses/mit/) diff --git a/RoslynMemberSorter.Tests/RoslynMemberSorter.Tests.csproj b/RoslynMemberSorter.Tests/RoslynMemberSorter.Tests.csproj new file mode 100644 index 0000000..b6c1496 --- /dev/null +++ b/RoslynMemberSorter.Tests/RoslynMemberSorter.Tests.csproj @@ -0,0 +1,24 @@ + + + net6.0 + enable + false + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + diff --git a/RoslynMemberSorter.Tests/UnitTests.cs b/RoslynMemberSorter.Tests/UnitTests.cs new file mode 100644 index 0000000..76294fd --- /dev/null +++ b/RoslynMemberSorter.Tests/UnitTests.cs @@ -0,0 +1,340 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CSharp; +using Roslynator.Testing; +using Roslynator.Testing.CSharp; +using Roslynator.Testing.CSharp.Xunit; +using Xunit; + +namespace RoslynMemberSorter.Tests; + +public class UnitTests : XunitDiagnosticVerifier +{ + private static CSharpTestOptions DefaultCSharpTestOptions + { + get + { + var allowedCompilerDiagnosticIds = ImmutableArray.Create( + "CS0067", // Event is never used + "CS0168", // Variable is declared but never used + "CS0169", // Field is never used + "CS0219", // Variable is assigned but its value is never used + "CS0414", // Field is assigned but its value is never used + "CS0649", // Field is never assigned to, and will always have its default value null + "CS0660", // Type defines operator == or operator != but does not override Object.Equals(object o) + "CS0661", // Type defines operator == or operator != but does not override Object.GetHashCode() + "CS8019", // Unnecessary using directive + "CS8321" // The local function is declared but never used + ); + return CSharpTestOptions.Default + .WithParseOptions(CSharpTestOptions.Default.ParseOptions.WithLanguageVersion(LanguageVersion.CSharp10)) + .WithAllowedCompilerDiagnosticIds(allowedCompilerDiagnosticIds) + .WithConfigOptions(new Dictionary() + { + [MakePropertyKey(dco => dco.AccessibilityOrder)] = string.Empty, + [MakePropertyKey(dco => dco.AlphabeticalIdentifiers)] = MakeEnumValue(NameOrder.Default), + [MakePropertyKey(dco => dco.ExplicitInterfaceSpecifiers)] = MakeEnumValue(Order.Default), + [MakePropertyKey(dco => dco.FieldOrder)] = string.Empty, + [MakePropertyKey(dco => dco.KindOrder)] = string.Empty, + [MakePropertyKey(dco => dco.LowArity)] = MakeEnumValue(Order.Default), + [MakePropertyKey(dco => dco.OperatorOrder)] = string.Empty, + [MakePropertyKey(dco => dco.ParameterSortStyle)] = MakeEnumValue(ParameterSortStyle.Default), + [MakePropertyKey(dco => dco.SingleLineEvents)] = MakeEnumValue(Order.Default), + [MakePropertyKey(dco => dco.SortOrders)] = string.Empty, + [MakePropertyKey(dco => dco.Static)] = MakeEnumValue(Order.Default) + }); + } + } + + protected override TestOptions CommonOptions => DefaultCSharpTestOptions; + + private static string MakeEnumList(params TEnum[] values) where TEnum : struct + { + return string.Join(',', values.Select(v => v.ToString()!.ToSnakeCase())); + } + + private static string MakeEnumValue(TEnum value) where TEnum : struct + { + return value.ToString()!.ToSnakeCase(); + } + + private static string MakePropertyKey(System.Linq.Expressions.Expression> expression) + { + if (expression.Body is System.Linq.Expressions.MemberExpression me) + { + return "dotnet_diagnostic.rms0001." + me.Member.Name.ToSnakeCase(); + } + else + { + throw new System.ArgumentException("Expression is not a member access", nameof(expression)); + } + } + + private async Task VerifyDiagnosticAndFixAsync(TestCode source, string expectedFix, Dictionary config) + { + await VerifyDiagnosticAndFixAsync(new DiagnosticTestData(DiagnosticIds.SortMembers, source.Value, source.Spans), new ExpectedTestState(expectedFix), CommonOptions.WithConfigOptions(CommonOptions.ConfigOptions.SetItems(config))).ConfigureAwait(false); + } + + private async Task VerifyNoDiagnosticAsync(TestCode source, Dictionary config) + { + await VerifyNoDiagnosticAsync(new DiagnosticTestData(DiagnosticIds.SortMembers, source.Value, source.Spans), CommonOptions.WithConfigOptions(CommonOptions.ConfigOptions.SetItems(config))).ConfigureAwait(false); + } + + [Fact] + public async Task TestAccessibilityOrderAsync() + { + var source = TestCode.Parse("class [|test|]\r\n{\r\n private int B;\r\n public int A;\r\n}\r\n"); + var config = new Dictionary() + { + [MakePropertyKey(dco => dco.AccessibilityOrder)] = string.Empty, + [MakePropertyKey(dco => dco.SortOrders)] = MakeEnumValue(SortOrder.Accessibility) + }; + + // default sort means do not reorder, verify no diagnostic + await VerifyNoDiagnosticAsync(source, config).ConfigureAwait(false); + + // verify order applies + config[MakePropertyKey(dco => dco.AccessibilityOrder)] = MakeEnumList(Accessibility.Public, Accessibility.Private); + const string expectedFix = "class test\r\n{\r\n public int A;\r\n private int B;\r\n}\r\n"; + await VerifyDiagnosticAndFixAsync(source, expectedFix, config).ConfigureAwait(false); + + // already in order, verify no diagnostic + config[MakePropertyKey(dco => dco.AccessibilityOrder)] = MakeEnumList(Accessibility.Private, Accessibility.Public); + await VerifyNoDiagnosticAsync(source, config).ConfigureAwait(false); + } + + [Fact] + public async Task TestAlphabeticalIdentifiersAsync() + { + var source = TestCode.Parse("class [|test|]\r\n{\r\n int B;\r\n int A;\r\n}\r\n"); + var config = new Dictionary() + { + [MakePropertyKey(dco => dco.AlphabeticalIdentifiers)] = MakeEnumValue(NameOrder.Default), + [MakePropertyKey(dco => dco.SortOrders)] = MakeEnumValue(SortOrder.Identifier) + }; + + // default sort means do not reorder, verify no diagnostic + await VerifyNoDiagnosticAsync(source, config).ConfigureAwait(false); + + // verify order applies + config[MakePropertyKey(dco => dco.AlphabeticalIdentifiers)] = MakeEnumValue(NameOrder.Alphabetical); + const string expectedFix = "class test\r\n{\r\n int A;\r\n int B;\r\n}\r\n"; + await VerifyDiagnosticAndFixAsync(source, expectedFix, config).ConfigureAwait(false); + + // already in order, verify no diagnostic + config[MakePropertyKey(dco => dco.AlphabeticalIdentifiers)] = MakeEnumValue(NameOrder.ReverseAlphabetical); + await VerifyNoDiagnosticAsync(source, config).ConfigureAwait(false); + } + + [Fact] + public async Task TestExplicitInterfaceSpecifiersAsync() + { + var source = TestCode.Parse("class [|test|] : System.Collections.IEnumerable\r\n{\r\n System.Collections.IEnumerator GetEnumerator() => throw new System.NotImplementedException();\r\n System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => throw new System.NotImplementedException();\r\n}\r\n"); + var config = new Dictionary() + { + [MakePropertyKey(dco => dco.ExplicitInterfaceSpecifiers)] = MakeEnumValue(Order.Default), + [MakePropertyKey(dco => dco.SortOrders)] = MakeEnumValue(SortOrder.ExplicitInterfaceSpecifier) + }; + + // default sort means do not reorder, verify no diagnostic + await VerifyNoDiagnosticAsync(source, config).ConfigureAwait(false); + + // verify order applies + config[MakePropertyKey(dco => dco.ExplicitInterfaceSpecifiers)] = MakeEnumValue(Order.First); + const string expectedFix = "class test : System.Collections.IEnumerable\r\n{\r\n System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => throw new System.NotImplementedException();\r\n System.Collections.IEnumerator GetEnumerator() => throw new System.NotImplementedException();\r\n}\r\n"; + await VerifyDiagnosticAndFixAsync(source, expectedFix, config).ConfigureAwait(false); + + // already in order, verify no diagnostic + config[MakePropertyKey(dco => dco.ExplicitInterfaceSpecifiers)] = MakeEnumValue(Order.Last); + await VerifyNoDiagnosticAsync(source, config).ConfigureAwait(false); + } + + [Fact] + public async Task TestFieldOrderAsync() + { + var source = TestCode.Parse("class [|test|]\r\n{\r\n int MutableField;\r\n const int ConstField = 0;\r\n readonly int ReadOnlyField;\r\n}\r\n"); + var config = new Dictionary() + { + [MakePropertyKey(dco => dco.FieldOrder)] = string.Empty, + [MakePropertyKey(dco => dco.SortOrders)] = MakeEnumValue(SortOrder.FieldOrder) + }; + + // default sort means do not reorder, verify no diagnostic + await VerifyNoDiagnosticAsync(source, config).ConfigureAwait(false); + + // verify order applies + config[MakePropertyKey(dco => dco.FieldOrder)] = MakeEnumList(FieldMutability.Const, FieldMutability.ReadOnly, FieldMutability.Mutable); + const string expectedFix = "class test\r\n{\r\n const int ConstField = 0;\r\n readonly int ReadOnlyField;\r\n int MutableField;\r\n}\r\n"; + await VerifyDiagnosticAndFixAsync(source, expectedFix, config).ConfigureAwait(false); + + // already in order, verify no diagnostic + config[MakePropertyKey(dco => dco.FieldOrder)] = MakeEnumList(FieldMutability.Mutable, FieldMutability.Const, FieldMutability.ReadOnly); + await VerifyNoDiagnosticAsync(source, config).ConfigureAwait(false); + } + + [Fact] + public async Task TestKindOrderAsync() + { + var source = TestCode.Parse("class [|test|]\r\n{\r\n int Field;\r\n int Property\r\n {\r\n get;\r\n }\r\n}\r\n"); + var config = new Dictionary() + { + [MakePropertyKey(dco => dco.KindOrder)] = string.Empty, + [MakePropertyKey(dco => dco.SortOrders)] = MakeEnumValue(SortOrder.Kind) + }; + + // default sort order means do not reorder, verify no diagnostic + await VerifyNoDiagnosticAsync(source, config).ConfigureAwait(false); + + // verify order applies + config[MakePropertyKey(dco => dco.KindOrder)] = MakeEnumList(SyntaxKind.PropertyDeclaration, SyntaxKind.FieldDeclaration); + const string expectedFix = "class test\r\n{\r\n int Property\r\n {\r\n get;\r\n }\r\n int Field;\r\n}\r\n"; + await VerifyDiagnosticAndFixAsync(source, expectedFix, config).ConfigureAwait(false); + + // already in order, verify no diagnostic + config[MakePropertyKey(dco => dco.KindOrder)] = MakeEnumList(SyntaxKind.FieldDeclaration, SyntaxKind.PropertyDeclaration); + await VerifyNoDiagnosticAsync(source, config).ConfigureAwait(false); + } + + [Fact] + public async Task TestLowArityAsync() + { + var source = TestCode.Parse("class [|test|]\r\n{\r\n int Method(int a, int b) => throw new System.NotImplementedException();\r\n int Method(int a) => throw new System.NotImplementedException();\r\n}\r\n"); + var config = new Dictionary() + { + [MakePropertyKey(dco => dco.LowArity)] = MakeEnumValue(Order.Default), + [MakePropertyKey(dco => dco.SortOrders)] = MakeEnumValue(SortOrder.Parameters) + }; + + // default sort order means do not reorder, verify no diagnostic + await VerifyNoDiagnosticAsync(source, config).ConfigureAwait(false); + + // verify order applies + config[MakePropertyKey(dco => dco.LowArity)] = MakeEnumValue(Order.First); + const string expectedFix = "class test\r\n{\r\n int Method(int a) => throw new System.NotImplementedException();\r\n int Method(int a, int b) => throw new System.NotImplementedException();\r\n}\r\n"; + await VerifyDiagnosticAndFixAsync(source, expectedFix, config).ConfigureAwait(false); + + // already in order, verify no diagnostic + config[MakePropertyKey(dco => dco.LowArity)] = MakeEnumValue(Order.Last); + await VerifyNoDiagnosticAsync(source, config).ConfigureAwait(false); + } + + [Fact] + public async Task TestOperatorOrderAsync() + { + var source = TestCode.Parse("class [|test|]\r\n{\r\n public static test operator -(test a, test b) => throw new System.NotImplementedException();\r\n public static test operator +(test a, test b) => throw new System.NotImplementedException();\r\n}\r\n"); + var config = new Dictionary() + { + [MakePropertyKey(dco => dco.OperatorOrder)] = string.Empty, + [MakePropertyKey(dco => dco.SortOrders)] = MakeEnumValue(SortOrder.Identifier) + }; + + // default sort order means do not reorder, verify no diagnostic + await VerifyNoDiagnosticAsync(source, config).ConfigureAwait(false); + + // verify order applies + config[MakePropertyKey(dco => dco.OperatorOrder)] = MakeEnumList(SyntaxKind.PlusToken, SyntaxKind.MinusToken); + const string expectedFix = "class test\r\n{\r\n public static test operator +(test a, test b) => throw new System.NotImplementedException();\r\n public static test operator -(test a, test b) => throw new System.NotImplementedException();\r\n}\r\n"; + await VerifyDiagnosticAndFixAsync(source, expectedFix, config).ConfigureAwait(false); + + // already in order, verify no diagnostic + config[MakePropertyKey(dco => dco.OperatorOrder)] = MakeEnumList(SyntaxKind.MinusToken, SyntaxKind.PlusToken); + await VerifyNoDiagnosticAsync(source, config).ConfigureAwait(false); + } + + [Fact] + public async Task TestParameterSortStyleAsync() + { + var source = TestCode.Parse("class [|test|]\r\n{\r\n void Method(int c) => throw new System.NotImplementedException();\r\n void Method(string a) => throw new System.NotImplementedException();\r\n void Method(double b) => throw new System.NotImplementedException();\r\n}\r\n"); + var config = new Dictionary() + { + [MakePropertyKey(dco => dco.ParameterSortStyle)] = MakeEnumValue(ParameterSortStyle.Default), + [MakePropertyKey(dco => dco.SortOrders)] = MakeEnumValue(SortOrder.Parameters) + }; + + // default sort order means do not reorder, verify no diagnostic + await VerifyNoDiagnosticAsync(source, config).ConfigureAwait(false); + + // verify order applies + config[MakePropertyKey(dco => dco.ParameterSortStyle)] = MakeEnumValue(ParameterSortStyle.SortTypes); + const string expectedTypesFix = "class test\r\n{\r\n void Method(double b) => throw new System.NotImplementedException();\r\n void Method(int c) => throw new System.NotImplementedException();\r\n void Method(string a) => throw new System.NotImplementedException();\r\n}\r\n"; + await VerifyDiagnosticAndFixAsync(source, expectedTypesFix, config).ConfigureAwait(false); + + // verify order applies + config[MakePropertyKey(dco => dco.ParameterSortStyle)] = MakeEnumValue(ParameterSortStyle.SortNames); + const string expectedNamesFix = "class test\r\n{\r\n void Method(string a) => throw new System.NotImplementedException();\r\n void Method(double b) => throw new System.NotImplementedException();\r\n void Method(int c) => throw new System.NotImplementedException();\r\n}\r\n"; + await VerifyDiagnosticAndFixAsync(source, expectedNamesFix, config).ConfigureAwait(false); + } + + [Fact] + public async Task TestSingleLineEventsAsync() + { + var source = TestCode.Parse("class [|test|]\r\n{\r\n event System.EventHandler MultiLine\r\n {\r\n add => throw new System.NotImplementedException();\r\n remove => throw new System.NotImplementedException();\r\n }\r\n event System.EventHandler SingleLine;\r\n}\r\n"); + var config = new Dictionary() + { + [MakePropertyKey(dco => dco.SingleLineEvents)] = MakeEnumValue(Order.Default), + [MakePropertyKey(dco => dco.SortOrders)] = MakeEnumValue(SortOrder.Kind) + }; + + // default sort order means do not reorder, verify no diagnostic + await VerifyNoDiagnosticAsync(source, config).ConfigureAwait(false); + + // verify order applies + config[MakePropertyKey(dco => dco.SingleLineEvents)] = MakeEnumValue(Order.First); + const string expectedFix = "class test\r\n{\r\n event System.EventHandler SingleLine;\r\n event System.EventHandler MultiLine\r\n {\r\n add => throw new System.NotImplementedException();\r\n remove => throw new System.NotImplementedException();\r\n }\r\n}\r\n"; + await VerifyDiagnosticAndFixAsync(source, expectedFix, config).ConfigureAwait(false); + + // already in order, verify no diagnostic + config[MakePropertyKey(dco => dco.SingleLineEvents)] = MakeEnumValue(Order.Last); + await VerifyNoDiagnosticAsync(source, config).ConfigureAwait(false); + } + + [Fact] + public async Task TestSortOrdersAsync() + { + var source = TestCode.Parse("class [|test|]\r\n{\r\n public int PublicInstance;\r\n private static int PrivateStatic;\r\n private int PrivateInstance;\r\n public static int PublicStatic;\r\n}\r\n"); + var config = new Dictionary() + { + [MakePropertyKey(dco => dco.AccessibilityOrder)] = MakeEnumList(Accessibility.Public, Accessibility.Private), + [MakePropertyKey(dco => dco.SortOrders)] = string.Empty, + [MakePropertyKey(dco => dco.Static)] = MakeEnumValue(Order.First) + }; + + // default sort order means do not reorder, verify no diagnostic + await VerifyNoDiagnosticAsync(source, config).ConfigureAwait(false); + + // verify order applies + config[MakePropertyKey(dco => dco.SortOrders)] = MakeEnumList(SortOrder.Accessibility, SortOrder.Static); + const string expectedTypesFix = "class test\r\n{\r\n public static int PublicStatic;\r\n public int PublicInstance;\r\n private static int PrivateStatic;\r\n private int PrivateInstance;\r\n}\r\n"; + await VerifyDiagnosticAndFixAsync(source, expectedTypesFix, config).ConfigureAwait(false); + + // verify order applies + config[MakePropertyKey(dco => dco.SortOrders)] = MakeEnumList(SortOrder.Static, SortOrder.Accessibility); + const string expectedNamesFix = "class test\r\n{\r\n public static int PublicStatic;\r\n private static int PrivateStatic;\r\n public int PublicInstance;\r\n private int PrivateInstance;\r\n}\r\n"; + await VerifyDiagnosticAndFixAsync(source, expectedNamesFix, config).ConfigureAwait(false); + } + + [Fact] + public async Task TestStaticAsync() + { + var source = TestCode.Parse("class [|test|]\r\n{\r\n int Instance;\r\n static int Static;\r\n}\r\n"); + var config = new Dictionary() + { + [MakePropertyKey(dco => dco.SortOrders)] = MakeEnumValue(SortOrder.Static), + [MakePropertyKey(dco => dco.Static)] = MakeEnumValue(Order.Default) + }; + + // default sort means do not reorder, verify no diagnostic + await VerifyNoDiagnosticAsync(source, config).ConfigureAwait(false); + + // verify order applies + config[MakePropertyKey(dco => dco.Static)] = MakeEnumValue(Order.First); + const string expectedFix = "class test\r\n{\r\n static int Static;\r\n int Instance;\r\n}\r\n"; + await VerifyDiagnosticAndFixAsync(source, expectedFix, config).ConfigureAwait(false); + + // already in order, verify no diagnostic + config[MakePropertyKey(dco => dco.Static)] = MakeEnumValue(Order.Last); + await VerifyNoDiagnosticAsync(source, config).ConfigureAwait(false); + } +} diff --git a/RoslynMemberSorter.sln b/RoslynMemberSorter.sln new file mode 100644 index 0000000..69f69f7 --- /dev/null +++ b/RoslynMemberSorter.sln @@ -0,0 +1,28 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.30114.105 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RoslynMemberSorter", "RoslynMemberSorter\RoslynMemberSorter.csproj", "{E5B290C2-5430-4526-8409-FB60076943AA}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RoslynMemberSorter.Tests", "RoslynMemberSorter.Tests\RoslynMemberSorter.Tests.csproj", "{B60A65AE-2376-4A5F-8D2E-88E193229509}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {E5B290C2-5430-4526-8409-FB60076943AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E5B290C2-5430-4526-8409-FB60076943AA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E5B290C2-5430-4526-8409-FB60076943AA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E5B290C2-5430-4526-8409-FB60076943AA}.Release|Any CPU.Build.0 = Release|Any CPU + {B60A65AE-2376-4A5F-8D2E-88E193229509}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B60A65AE-2376-4A5F-8D2E-88E193229509}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B60A65AE-2376-4A5F-8D2E-88E193229509}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B60A65AE-2376-4A5F-8D2E-88E193229509}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/RoslynMemberSorter/Accessibility.cs b/RoslynMemberSorter/Accessibility.cs new file mode 100644 index 0000000..b3ddb02 --- /dev/null +++ b/RoslynMemberSorter/Accessibility.cs @@ -0,0 +1,37 @@ +namespace RoslynMemberSorter; + +/// +/// Indicates the accessibility level of a member. +/// +public enum Accessibility +{ + /// + /// Internal members are accessible to callers in the declaring assembly. + /// + Internal, + + /// + /// Private members are accessible to the declaring type. + /// + Private, + + /// + /// Private protected members are accessible to types derived from the declaring type but only in the declaring assembly. + /// + PrivateProtected, + + /// + /// Protected members are accessible to types derived from the declaring type. + /// + Protected, + + /// + /// Protected internal members are accessible to types derived from the declaring type and to the declaring assembly. + /// + ProtectedInternal, + + /// + /// Public members are accessible to all callers. + /// + Public +} diff --git a/RoslynMemberSorter/DeclarationComparer.cs b/RoslynMemberSorter/DeclarationComparer.cs new file mode 100644 index 0000000..fd5d106 --- /dev/null +++ b/RoslynMemberSorter/DeclarationComparer.cs @@ -0,0 +1,540 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace RoslynMemberSorter; + +/// +/// Compares values based on a number of details indicated by . +/// +public sealed class DeclarationComparer : IComparer +{ + /// + /// Initializes a new instance of with the given options. + /// + /// A object specifying what details to compare. + public DeclarationComparer(DeclarationComparerOptions options) + { + Options = options; + } + + /// + /// The options used by this comparer. + /// + /// A object indicating how to compare objects. + public DeclarationComparerOptions Options + { + get; + } + + /// + /// Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other. + /// + /// The first to compare. + /// The second to compare. + /// + /// A signed integer that indicates the relative values of and , as shown in the following table. + /// + /// + /// Value + /// Meaning + /// + /// + /// Less than zero + /// is less than . + /// + /// + /// Zero + /// equals . + /// + /// + /// Greater than zero + /// is greater than . + /// + /// + /// + public int Compare(MemberDeclarationSyntax? x, MemberDeclarationSyntax? y) + { + if (ReferenceEquals(x, y)) + { + return 0; + } + else if (x is null) + { + return 1; + } + else if (y is null) + { + return -1; + } + foreach (var sort in Options.SortOrders) + { + switch (sort) + { + case SortOrder.Kind: + int kindComparison = CompareKind(x, y); + if (kindComparison != 0) + { + return kindComparison; + } + break; + case SortOrder.Static: + int staticComparison = CompareStatic(x, y); + if (staticComparison != 0) + { + return staticComparison; + } + break; + case SortOrder.FieldOrder: + int readOnlyComparison = CompareMutability(x, y); + if (readOnlyComparison != 0) + { + return readOnlyComparison; + } + break; + case SortOrder.Accessibility: + int accessiblityComparison = CompareAccessibility(x, y); + if (accessiblityComparison != 0) + { + return accessiblityComparison; + } + break; + case SortOrder.ExplicitInterfaceSpecifier: + int explicitInterfaceSpecifierComparison = CompareExplicitInterfaceSpecifier(x, y); + if (explicitInterfaceSpecifierComparison != 0) + { + return explicitInterfaceSpecifierComparison; + } + break; + case SortOrder.Identifier: + int identifierComparison = CompareIdentifier(x, y); + if (identifierComparison != 0) + { + return identifierComparison; + } + break; + case SortOrder.Parameters: + int parameterTypesComparison = CompareParameters(x, y); + if (parameterTypesComparison != 0) + { + return parameterTypesComparison; + } + break; + } + } + return 0; + } + + /// + private int CompareAccessibility(MemberDeclarationSyntax x, MemberDeclarationSyntax y) + { + return Options.AccessibilityOrder.IndexOf(GetAccessibility(x)) - Options.AccessibilityOrder.IndexOf(GetAccessibility(y)); + + static Accessibility GetAccessibility(MemberDeclarationSyntax member) + { + if (member.Modifiers.Any(token => token.IsKind(SyntaxKind.PublicKeyword))) + { + return Accessibility.Public; + } + else if (member.Modifiers.Any(token => token.IsKind(SyntaxKind.InternalKeyword))) + { + if (member.Modifiers.Any(token => token.IsKind(SyntaxKind.ProtectedKeyword))) + { + return Accessibility.ProtectedInternal; + } + else + { + return Accessibility.Internal; + } + } + else if (member.Modifiers.Any(token => token.IsKind(SyntaxKind.ProtectedKeyword))) + { + if (member.Modifiers.Any(token => token.IsKind(SyntaxKind.PrivateKeyword))) + { + return Accessibility.PrivateProtected; + } + else + { + return Accessibility.Protected; + } + } + else if (member.Modifiers.Any(token => token.IsKind(SyntaxKind.PrivateKeyword))) + { + return Accessibility.Private; + } + else + { + var xMajorParent = member.Ancestors().FirstOrDefault(node => node.IsKind(SyntaxKind.InterfaceDeclaration) + || node.IsKind(SyntaxKind.ClassDeclaration) + || node.IsKind(SyntaxKind.RecordDeclaration) + || node.IsKind(SyntaxKind.RecordStructDeclaration) + || node.IsKind(SyntaxKind.StructDeclaration)); + if (xMajorParent.IsKind(SyntaxKind.InterfaceDeclaration)) + { + return Accessibility.Public; + } + else if (xMajorParent is null) + { + return Accessibility.Internal; + } + else + { + return Accessibility.Private; + } + } + } + } + + /// + private int CompareExplicitInterfaceSpecifier(MemberDeclarationSyntax x, MemberDeclarationSyntax y) + { + if (Options.ExplicitInterfaceSpecifiers == Order.Default) + { + return 0; + } + var xExplicit = HasExplicitInterfaceSpecifier(x); + var yExplicit = HasExplicitInterfaceSpecifier(y); + if (xExplicit && !yExplicit) + { + return Options.ExplicitInterfaceSpecifiers == Order.First ? -1 : 1; + } + else if (!xExplicit && yExplicit) + { + return Options.ExplicitInterfaceSpecifiers == Order.First ? 1 : -1; + } + else + { + return 0; + } + + static bool HasExplicitInterfaceSpecifier(MemberDeclarationSyntax member) + { + if (member is MethodDeclarationSyntax mMethod) + { + return mMethod.ExplicitInterfaceSpecifier is not null; + } + else if (member is IndexerDeclarationSyntax mIndexer) + { + return mIndexer.ExplicitInterfaceSpecifier is not null; + } + else if (member is PropertyDeclarationSyntax mProperty) + { + return mProperty.ExplicitInterfaceSpecifier is not null; + } + else if (member is EventDeclarationSyntax mEvent) + { + return mEvent.ExplicitInterfaceSpecifier is not null; + } + else + { + return false; + } + } + } + + /// + /// + /// Identifiers vary based on their types as seen in this table. + /// + /// + /// Type + /// Identifer + /// + /// + /// + /// + /// + /// + /// + /// ... + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// ... + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Anything else + /// + /// + /// + /// + private int CompareIdentifier(MemberDeclarationSyntax x, MemberDeclarationSyntax y) + { + if (x is OperatorDeclarationSyntax xOperator && y is OperatorDeclarationSyntax yOperator) + { + return Options.OperatorOrder.IndexOf(xOperator.OperatorToken.Kind(), SyntaxFacts.EqualityComparer) - Options.OperatorOrder.IndexOf(yOperator.OperatorToken.Kind(), SyntaxFacts.EqualityComparer); + } + else if (Options.AlphabeticalIdentifiers != NameOrder.Default) + { + var xName = GetMemberName(x); + var yName = GetMemberName(y); + return StringComparer.Ordinal.Compare(xName, yName) * (Options.AlphabeticalIdentifiers == NameOrder.Alphabetical ? 1 : -1); + + static string? GetMemberName(MemberDeclarationSyntax member) + { + if (member is FieldDeclarationSyntax mField) + { + return mField.Declaration.Variables.First().Identifier.ToString(); + } + else if (member is DelegateDeclarationSyntax mDelegate) + { + return mDelegate.Identifier.ToString(); + } + else if (member is EventDeclarationSyntax mEvent) + { + return mEvent.Identifier.ToString(); + } + else if (member is EventFieldDeclarationSyntax mEventField) + { + return mEventField.Declaration.Variables.First().Identifier.ToString(); + } + else if (member is PropertyDeclarationSyntax mProperty) + { + return mProperty.Identifier.ToString(); + } + else if (member is MethodDeclarationSyntax mMethod) + { + return mMethod.Identifier.ToString(); + } + else if (member is ConversionOperatorDeclarationSyntax mConversionOperator) + { + return mConversionOperator.Type.ToString(); + } + else if (member is BaseTypeDeclarationSyntax mBaseType) + { + return mBaseType.Identifier.ToString(); + } + else + { + return null; + } + } + } + else + { + return 0; + } + } + + /// + private int CompareKind(MemberDeclarationSyntax x, MemberDeclarationSyntax y) + { + if ((x.IsKind(SyntaxKind.EventDeclaration) || x.IsKind(SyntaxKind.EventFieldDeclaration)) && (y.IsKind(SyntaxKind.EventDeclaration) || y.IsKind(SyntaxKind.EventFieldDeclaration))) + { + if (Options.SingleLineEvents == Order.Default) + { + return 0; + } + else + { + var xSingleLine = x.IsKind(SyntaxKind.EventFieldDeclaration); + var ySingleLine = y.IsKind(SyntaxKind.EventFieldDeclaration); + if (xSingleLine && !ySingleLine) + { + return Options.SingleLineEvents == Order.First ? -1 : 1; + } + else if (!xSingleLine && ySingleLine) + { + return Options.SingleLineEvents == Order.First ? 1 : -1; + } + else + { + return 0; + } + } + } + else + { + return Options.KindOrder.IndexOf(x.Kind(), SyntaxFacts.EqualityComparer) - Options.KindOrder.IndexOf(y.Kind(), SyntaxFacts.EqualityComparer); + } + } + + /// + private int CompareMutability(MemberDeclarationSyntax x, MemberDeclarationSyntax y) + { + if (x is not FieldDeclarationSyntax xField || y is not FieldDeclarationSyntax yField) + { + return 0; + } + return Options.FieldOrder.IndexOf(GetFieldMutability(xField)) - Options.FieldOrder.IndexOf(GetFieldMutability(yField)); + + static FieldMutability GetFieldMutability(FieldDeclarationSyntax field) + { + if (field.Modifiers.Any(token => token.IsKind(SyntaxKind.ConstKeyword))) + { + return FieldMutability.Const; + } + else if (field.Modifiers.Any(token => token.IsKind(SyntaxKind.ReadOnlyKeyword))) + { + return FieldMutability.ReadOnly; + } + else + { + return FieldMutability.Mutable; + } + } + } + + /// + private int CompareParameters(MemberDeclarationSyntax x, MemberDeclarationSyntax y) + { + var xParameters = GetParameters(x); + var yParameters = GetParameters(y); + return CompareSeparatedSyntaxList(xParameters, yParameters); + + static SeparatedSyntaxList GetParameters(MemberDeclarationSyntax member) + { + if (member is MethodDeclarationSyntax mMethod) + { + return mMethod.ParameterList.Parameters; + } + else if (member is IndexerDeclarationSyntax mIndexer) + { + return mIndexer.ParameterList.Parameters; + } + else if (member is ConstructorDeclarationSyntax mConstructor) + { + return mConstructor.ParameterList.Parameters; + } + else if (member is DelegateDeclarationSyntax mDelegate) + { + return mDelegate.ParameterList.Parameters; + } + else + { + return default; + } + } + } + + /// + /// Compares parameter lists based on details such as arity, types, and names. + /// + /// The first list to compare. + /// The second list to compare. + /// + /// A signed integer that indicates the relative values of and , as shown in the following table. + /// + /// + /// Value + /// Meaning + /// + /// + /// Less than zero + /// is less than . + /// + /// + /// Zero + /// equals . + /// + /// + /// Greater than zero + /// is greater than . + /// + /// + /// + private int CompareSeparatedSyntaxList(SeparatedSyntaxList x, SeparatedSyntaxList y) + { + if (Options.LowArity == Order.First) + { + if (x.Count < y.Count) + { + return -1; + } + else if (x.Count > y.Count) + { + return 1; + } + } + else if (Options.LowArity == Order.Last) + { + if (x.Count < y.Count) + { + return 1; + } + else if (x.Count > y.Count) + { + return -1; + } + } + if (Options.ParameterSortStyle == ParameterSortStyle.Default) + { + return 0; + } + else if (Options.ParameterSortStyle == ParameterSortStyle.SortTypes) + { + for (var i = 0; i < x.Count && i < y.Count; i++) + { + var comparison = StringComparer.Ordinal.Compare(x[i].Type?.ToString(), y[i].Type?.ToString()); + if (comparison != 0) + { + return comparison; + } + } + } + else + { + for (var i = 0; i < x.Count && i < y.Count; i++) + { + var comparison = StringComparer.Ordinal.Compare(x[i].Identifier.ToString(), y[i].Identifier.ToString()); + if (comparison != 0) + { + return comparison; + } + } + } + return 0; + } + + /// + /// Constant fields are considered static because they are not attached to an instance. + private int CompareStatic(MemberDeclarationSyntax x, MemberDeclarationSyntax y) + { + if (Options.Static == Order.Default) + { + return 0; + } + var xStatic = x.Modifiers.Any(token => token.IsKind(SyntaxKind.StaticKeyword) || token.IsKind(SyntaxKind.ConstKeyword)); + var yStatic = y.Modifiers.Any(token => token.IsKind(SyntaxKind.StaticKeyword) || token.IsKind(SyntaxKind.ConstKeyword)); + if (xStatic && !yStatic) + { + return Options.Static == Order.First ? -1 : 1; + } + else if (!xStatic && yStatic) + { + return Options.Static == Order.First ? 1 : -1; + } + else + { + return 0; + } + } +} diff --git a/RoslynMemberSorter/DeclarationComparerOptions.cs b/RoslynMemberSorter/DeclarationComparerOptions.cs new file mode 100644 index 0000000..83b870b --- /dev/null +++ b/RoslynMemberSorter/DeclarationComparerOptions.cs @@ -0,0 +1,412 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Diagnostics; + +namespace RoslynMemberSorter; + +/// +/// Specifies options for . +/// +public sealed class DeclarationComparerOptions +{ + /// + /// Tries to get a value by key from a collection. + /// + /// The key to try to retrieve. + /// The value if is found. + /// if is found; otherwise . + private delegate bool TryGetDelegate(string key, out string? value); + + /// + /// Indicates the order in which accessibility (eg: public, private) should be sorted. + /// + public ImmutableArray AccessibilityOrder + { + get; + set; + } = ImmutableArray.Create + ( + Accessibility.Public, + Accessibility.ProtectedInternal, + Accessibility.Internal, + Accessibility.Protected, + Accessibility.PrivateProtected, + Accessibility.Private + ); + + /// + /// Indicates how names should be sorted. + /// + public NameOrder AlphabeticalIdentifiers + { + get; + set; + } = NameOrder.Alphabetical; + + /// Indicates where explicit interface implementation members should be ordered. + /// + /// + /// + /// Value + /// Effect + /// + /// + /// + /// Explicit interface implementation is ignored for sorting purposes. + /// + /// + /// + /// Members that explicitly implement an interface are ordered before members that do not. + /// + /// + /// + /// Members that explicitly implement an interface are ordered after members that do not. + /// + /// + /// + public Order ExplicitInterfaceSpecifiers + { + get; + set; + } = Order.First; + + /// + /// Indicates how field mutability should be handled. + /// + public ImmutableArray FieldOrder + { + get; + set; + } = ImmutableArray.Create(FieldMutability.Const, FieldMutability.ReadOnly, FieldMutability.Mutable); + + /// + /// Indicates the order in which member kinds (eg: field, constructor) should be sorted. + /// + public ImmutableArray KindOrder + { + get; + set; + } = ImmutableArray.Create + ( + SyntaxKind.FieldDeclaration, + SyntaxKind.ConstructorDeclaration, + SyntaxKind.DestructorDeclaration, + SyntaxKind.IndexerDeclaration, + SyntaxKind.PropertyDeclaration, + SyntaxKind.EventFieldDeclaration, + SyntaxKind.EventDeclaration, + SyntaxKind.MethodDeclaration, + SyntaxKind.OperatorDeclaration, + SyntaxKind.ConversionOperatorDeclaration, + SyntaxKind.EnumDeclaration, + SyntaxKind.InterfaceDeclaration, + SyntaxKind.StructDeclaration, + SyntaxKind.ClassDeclaration, + SyntaxKind.RecordDeclaration, + SyntaxKind.RecordStructDeclaration, + SyntaxKind.DelegateDeclaration + ); + + /// Indicates how method arity should be handled. + /// + /// + /// + /// Value + /// Effect + /// + /// + /// + /// Method arity is ignored for sorting purposes. + /// + /// + /// + /// Methods with low arity come before methods with high arity. + /// + /// + /// + /// Methods with low arity come after methods with high arity. + /// + /// + /// + /// This can apply to constructors, delegates, indexers, and methods. + public Order LowArity + { + get; + set; + } = Order.First; + + /// + /// Indicates the order in which operators should be sorted as they do not have conventional alphabetical names. + /// + public ImmutableArray OperatorOrder + { + get; + set; + } = ImmutableArray.Create + ( + SyntaxKind.PlusToken, + SyntaxKind.MinusToken, + SyntaxKind.ExclamationToken, + SyntaxKind.TildeToken, + SyntaxKind.PlusPlusToken, + SyntaxKind.MinusMinusToken, + SyntaxKind.AsteriskToken, + SyntaxKind.SlashToken, + SyntaxKind.PercentToken, + SyntaxKind.AmpersandToken, + SyntaxKind.BarToken, + SyntaxKind.CaretToken, + SyntaxKind.LessThanLessThanToken, + SyntaxKind.GreaterThanGreaterThanToken, + SyntaxKind.EqualsEqualsToken, + SyntaxKind.ExclamationEqualsToken, + SyntaxKind.LessThanToken, + SyntaxKind.GreaterThanToken, + SyntaxKind.LessThanEqualsToken, + SyntaxKind.GreaterThanEqualsToken, + SyntaxKind.TrueKeyword, + SyntaxKind.FalseKeyword + ); + + /// + /// Indicates how parameter lists should be compared. + /// + public ParameterSortStyle ParameterSortStyle + { + get; + set; + } = ParameterSortStyle.SortTypes; + + /// Indicates whether single line events should be separated from events with accessors. + /// + /// + /// + /// Value + /// Effect + /// + /// + /// + /// Single line or accessor status is ignored for sorting purposes. + /// + /// + /// + /// Single line events come before events with accessors. + /// + /// + /// + /// Single line events come after events with accessors. + /// + /// + /// + public Order SingleLineEvents + { + get; + set; + } = Order.Default; + + /// + /// Indicates the order in which sorts (eg: by kind, by accessibility) should take place. values not specified here will not be sorted at all. + /// + public ImmutableArray SortOrders + { + get; + set; + } = ImmutableArray.Create + ( + SortOrder.Kind, + SortOrder.Static, + SortOrder.FieldOrder, + SortOrder.Accessibility, + SortOrder.ExplicitInterfaceSpecifier, + SortOrder.Identifier, + SortOrder.Parameters + ); + + /// Indicates how static and instance members should be handled. + /// + /// + /// + /// Value + /// Effect + /// + /// + /// + /// Static or instance status is ignored for sorting purposes. + /// + /// + /// + /// Static members come before instance members. + /// + /// + /// + /// Static members come after instance members. + /// + /// + /// + public Order Static + { + get; + set; + } = Order.First; + + /// + /// Creates a new instance from the given property name and value pairs. + /// + /// The config to read property names and values from. + /// A new using the given property values. + /// Config options are prefixed with "dotnet_diagnostic.rms0001.". Property names are stored in lower snake case. So would be keyed as "dotnet_diagnostic.rms0001.sort_orders". + public static DeclarationComparerOptions FromAnalyzerConfigOptions(AnalyzerConfigOptions options) + { + const string prefix = "dotnet_diagnostic.rms0001."; + return FromFunc(options.TryGetValue, prefix); + } + + /// + /// Creates a new instance from the given property name and value pairs. + /// + /// The dictionary to read property names and values from. + /// A new using the given property values. + /// Property names are stored in lower snake case. So would be keyed as "sort_orders". + public static DeclarationComparerOptions FromDictionary(IReadOnlyDictionary dictionary) + { + return FromFunc(dictionary.TryGetValue, string.Empty); + } + + /// + /// Creates a dictionary that can be passed to to make a copy of these options. + /// + /// An that contains stringified property values from this instance. + /// Property names are stored in lower snake case. So would be keyed as "sort_orders", + public ImmutableDictionary ToImmutableDictionary() + { + var dictionary = new Dictionary(); + foreach (var property in typeof(DeclarationComparerOptions).GetProperties()) + { + var propertyValue = property.GetValue(this); + if (propertyValue is IEnumerable enumAccessibility) + { + dictionary.Add(property.Name.ToSnakeCase(), string.Join(",", enumAccessibility.Select(e => e.ToString().ToSnakeCase()))); + } + else if (propertyValue is IEnumerable enumSyntaxKind) + { + dictionary.Add(property.Name.ToSnakeCase(), string.Join(",", enumSyntaxKind.Select(e => e.ToString().ToSnakeCase()))); + } + else if (propertyValue is IEnumerable enumSortOrders) + { + dictionary.Add(property.Name.ToSnakeCase(), string.Join(",", enumSortOrders.Select(e => e.ToString().ToSnakeCase()))); + } + else if (propertyValue is IEnumerable enumFieldMutability) + { + dictionary.Add(property.Name.ToSnakeCase(), string.Join(",", enumFieldMutability.Select(e => e.ToString().ToSnakeCase()))); + } + else if (propertyValue is Enum) + { + dictionary.Add(property.Name.ToSnakeCase(), propertyValue.ToString().ToSnakeCase()); + } + else + { +#pragma warning disable RCS1079, RCS1140 + throw new NotImplementedException($"A property of type {property.PropertyType} has been detected and stringifying is not yet implemented."); +#pragma warning restore RCS1079, RCS1140 + } + } + return dictionary.ToImmutableDictionary(); + } + + /// + /// Creates a new instance from the given property name and value pairs. + /// + /// A delegate pointing to a keyed collection to read properties from. + /// A to prepend to all key names passed to . + /// A new using the given property values. + /// Property names are stored in lower snake case. So would be keyed as "sort_orders". + private static DeclarationComparerOptions FromFunc(TryGetDelegate tryGetFunc, string prefix) + { + var options = new DeclarationComparerOptions(); + foreach (var property in typeof(DeclarationComparerOptions).GetProperties()) + { + if (tryGetFunc(prefix + property.Name.ToSnakeCase(), out var value) && value is not null) + { + if (property.PropertyType == typeof(ImmutableArray)) + { + property.SetValue(options, TryParseAll(CleanAndSplitString(value))); + } + else if (property.PropertyType == typeof(ImmutableArray)) + { + property.SetValue(options, TryParseAll(CleanAndSplitString(value))); + } + else if (property.PropertyType == typeof(ImmutableArray)) + { + property.SetValue(options, TryParseAll(CleanAndSplitString(value))); + } + else if (property.PropertyType == typeof(Order)) + { + if (Enum.TryParse(CleanString(value), true, out var sortOrder)) + { + property.SetValue(options, sortOrder); + } + } + else if (property.PropertyType == typeof(ParameterSortStyle)) + { + if (Enum.TryParse(CleanString(value), true, out var parameterSortStyle)) + { + property.SetValue(options, parameterSortStyle); + } + } + else if (property.PropertyType == typeof(NameOrder)) + { + if (Enum.TryParse(CleanString(value), true, out var nameOrder)) + { + property.SetValue(options, nameOrder); + } + } + else if (property.PropertyType == typeof(ImmutableArray)) + { + property.SetValue(options, TryParseAll(CleanAndSplitString(value))); + } + else + { +#pragma warning disable RCS1079, RCS1140 + throw new NotImplementedException($"A property of type {property.PropertyType} has been detected and parsing is not yet implemented."); +#pragma warning restore RCS1079, RCS1140 + } + } + } + return options; + + static string CleanString(string value) + { + return value.Trim().Replace("_", string.Empty); + } + + static IEnumerable CleanAndSplitString(string value) + { + return value.Replace("_", string.Empty).Split(',').Select(v => v.Trim()); + } + } + + /// + /// Attempts to convert an enumerable of string values to an array of values. + /// + /// The type of the enumeration to call with. + /// An of to try to convert. + /// A of created from parsing . The array will only contain successful values and invalid values will be dropped. + /// Each value will be run through ignoring case. If that fails, "Declaration", "Token", and "Keyword" will be appended in series to the end of the value to attempt to match a . + private static ImmutableArray TryParseAll(IEnumerable values) where TEnum : struct + { + return values.Select(value => + ( + Enum.TryParse(value, true, out var parseResult) + || Enum.TryParse(value + "Declaration", true, out parseResult) + || Enum.TryParse(value + "Token", true, out parseResult) + || Enum.TryParse(value + "Keyword", true, out parseResult), + parseResult + )) + .Where(item => item.Item1) + .Select(item => item.parseResult) + .ToImmutableArray(); + } +} diff --git a/RoslynMemberSorter/DiagnosticIds.cs b/RoslynMemberSorter/DiagnosticIds.cs new file mode 100644 index 0000000..dee8d15 --- /dev/null +++ b/RoslynMemberSorter/DiagnosticIds.cs @@ -0,0 +1,14 @@ +using Microsoft.CodeAnalysis; + +namespace RoslynMemberSorter; + +/// +/// Stores values used by . +/// +public static class DiagnosticIds +{ + /// + /// The diagnostic RMS0001 to sort members of a type or namespace. + /// + public static readonly DiagnosticDescriptor SortMembers = new("RMS0001", "Sort members", "Sort members", "Style", DiagnosticSeverity.Info, true, null, null); +} diff --git a/RoslynMemberSorter/Extensions.cs b/RoslynMemberSorter/Extensions.cs new file mode 100644 index 0000000..648d56d --- /dev/null +++ b/RoslynMemberSorter/Extensions.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace RoslynMemberSorter; + +/// +/// Contains extension methods. +/// +public static class Extensions +{ + /// + /// Checks to see if a collection is ordered. + /// + /// The type of the elements in . + /// An to check the order of. + /// An to compare elements. + /// if the collection is already ordered; otherwise . + /// or is . + public static bool IsOrdered(this IEnumerable source, IComparer comparer) + { + if (source is null) + { + throw new ArgumentNullException(nameof(source)); + } + if (comparer is null) + { + throw new ArgumentNullException(nameof(comparer)); + } + var enumerator = source.GetEnumerator(); + if (!enumerator.MoveNext()) + { + return true; + } + var lastElement = enumerator.Current; + while (enumerator.MoveNext()) + { + var currentElement = enumerator.Current; + if (comparer.Compare(lastElement, currentElement) > 0) + { + return false; + } + lastElement = currentElement; + } + return true; + } + + /// + /// Converts a Pascal case identifier to a lower snake case identifer. + /// + /// The identifier to convert + /// A that converts capital letters to lower case and separates words with underscores '_'. + /// would be keyed as "sort_orders". + public static string ToSnakeCase(this string value) + { + var builder = new StringBuilder(value.Length); + for (int i = 0; i < value.Length; i++) + { + if (char.IsUpper(value[i])) + { + if (i != 0) + { + builder.Append('_'); + } + builder.Append(char.ToLower(value[i])); + } + else + { + builder.Append(value[i]); + } + } + return builder.ToString(); + } +} diff --git a/RoslynMemberSorter/FieldMutability.cs b/RoslynMemberSorter/FieldMutability.cs new file mode 100644 index 0000000..7a13ec7 --- /dev/null +++ b/RoslynMemberSorter/FieldMutability.cs @@ -0,0 +1,22 @@ +namespace RoslynMemberSorter; + +/// +/// Indicates field mutability. +/// +public enum FieldMutability +{ + /// + /// The field is declared with the const keyword. + /// + Const, + + /// + /// The field is declared with neither the const keyword nor the readonly keyword. + /// + Mutable, + + /// + /// The field is declared with the readonly keyword. + /// + ReadOnly +} diff --git a/RoslynMemberSorter/MemberSorterAnalyzer.cs b/RoslynMemberSorter/MemberSorterAnalyzer.cs new file mode 100644 index 0000000..60ded2a --- /dev/null +++ b/RoslynMemberSorter/MemberSorterAnalyzer.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Diagnostics; + +namespace RoslynMemberSorter; + +/// +/// Analyzes namespaces and types to check if their declared members are in order. +/// +[DiagnosticAnalyzer(LanguageNames.CSharp)] +public sealed class MemberSorterAnalyzer : DiagnosticAnalyzer +{ + /// + public override ImmutableArray SupportedDiagnostics + { + get; + } = ImmutableArray.Create(DiagnosticIds.SortMembers); + + /// + public override void Initialize(AnalysisContext context) + { + context.EnableConcurrentExecution(); + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); + context.RegisterSyntaxNodeAction(AnalyzeFileScopedNamespace, SyntaxKind.FileScopedNamespaceDeclaration); + context.RegisterSyntaxNodeAction(AnalyzeNamespace, SyntaxKind.NamespaceDeclaration); + context.RegisterSyntaxNodeAction(AnalyzeType, SyntaxKind.ClassDeclaration, SyntaxKind.InterfaceDeclaration, SyntaxKind.RecordDeclaration, SyntaxKind.RecordStructDeclaration, SyntaxKind.StructDeclaration); + } + + /// + /// Analyzes a file scoped namespace to see if its members are in order. + /// + /// The context of the analysis. + private void AnalyzeFileScopedNamespace(SyntaxNodeAnalysisContext context) + { + var options = context.Options.AnalyzerConfigOptionsProvider.GetOptions(context.Node.SyntaxTree); + var comparer = new DeclarationComparer(DeclarationComparerOptions.FromAnalyzerConfigOptions(options)); + var fileScopedNamespaceDeclaration = (FileScopedNamespaceDeclarationSyntax)context.Node; + if (!fileScopedNamespaceDeclaration.Members.IsOrdered(comparer)) + { + context.ReportDiagnostic(Diagnostic.Create(DiagnosticIds.SortMembers, fileScopedNamespaceDeclaration.Name.GetLocation(), comparer.Options.ToImmutableDictionary())); + } + } + + /// + /// Analyzes a namespace to see if its members are in order. + /// + /// The context of the analysis. + private void AnalyzeNamespace(SyntaxNodeAnalysisContext context) + { + var options = context.Options.AnalyzerConfigOptionsProvider.GetOptions(context.Node.SyntaxTree); + var comparer = new DeclarationComparer(DeclarationComparerOptions.FromAnalyzerConfigOptions(options)); + var namespaceDeclaration = (NamespaceDeclarationSyntax)context.Node; + if (!namespaceDeclaration.Members.IsOrdered(comparer)) + { + context.ReportDiagnostic(Diagnostic.Create(DiagnosticIds.SortMembers, namespaceDeclaration.Name.GetLocation(), comparer.Options.ToImmutableDictionary())); + } + } + + /// + /// Analyzes a type to see if its members are in order. + /// + /// The context of the analysis. + private void AnalyzeType(SyntaxNodeAnalysisContext context) + { + var options = context.Options.AnalyzerConfigOptionsProvider.GetOptions(context.Node.SyntaxTree); + var comparer = new DeclarationComparer(DeclarationComparerOptions.FromAnalyzerConfigOptions(options)); + var typeDeclaration = (TypeDeclarationSyntax)context.Node; + if (!typeDeclaration.Members.IsOrdered(comparer)) + { + context.ReportDiagnostic(Diagnostic.Create(DiagnosticIds.SortMembers, typeDeclaration.Identifier.GetLocation(), comparer.Options.ToImmutableDictionary())); + } + } +} diff --git a/RoslynMemberSorter/MemberSorterCodeFixProvider.cs b/RoslynMemberSorter/MemberSorterCodeFixProvider.cs new file mode 100644 index 0000000..2c21e4b --- /dev/null +++ b/RoslynMemberSorter/MemberSorterCodeFixProvider.cs @@ -0,0 +1,66 @@ +using System.Collections.Immutable; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Formatting; + +namespace RoslynMemberSorter; + +/// +/// Provides code fixes for . +/// +[ExportCodeFixProvider(LanguageNames.CSharp)] +public sealed class MemberSorterCodeFixProvider : CodeFixProvider +{ + /// + public override ImmutableArray FixableDiagnosticIds + { + get; + } = ImmutableArray.Create(DiagnosticIds.SortMembers.Id); + + /// + public override FixAllProvider? GetFixAllProvider() + { + return WellKnownFixAllProviders.BatchFixer; + } + + /// + public override Task RegisterCodeFixesAsync(CodeFixContext context) + { + var sortMemberDiagnostic = context.Diagnostics.First(diagnostic => diagnostic.Descriptor == DiagnosticIds.SortMembers); + context.RegisterCodeFix( + CodeAction.Create( + "Fix member order", + async cancellationToken => + { + var root = await context.Document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + if (root is null) + { + return context.Document; + } + var comparer = new DeclarationComparer(DeclarationComparerOptions.FromDictionary(context.Diagnostics[0].Properties)); + var nodeAtDiagnostic = root.FindNode(sortMemberDiagnostic.Location.SourceSpan); + SyntaxNode newNode; + if (nodeAtDiagnostic is NamespaceDeclarationSyntax namespaceDeclarationSyntax) + { + newNode = namespaceDeclarationSyntax.WithMembers(new SyntaxList(namespaceDeclarationSyntax.Members.OrderBy(node => node, comparer))); + } + else if (nodeAtDiagnostic is TypeDeclarationSyntax typeDeclarationSyntax) + { + newNode = typeDeclarationSyntax.WithMembers(new SyntaxList(typeDeclarationSyntax.Members.OrderBy(node => node, comparer))); + } + else + { + return context.Document; + } + root = root.ReplaceNode(nodeAtDiagnostic, newNode.WithAdditionalAnnotations(Formatter.Annotation)); + return context.Document.WithSyntaxRoot(root); + }, + DiagnosticIds.SortMembers.Id), + sortMemberDiagnostic); + return Task.CompletedTask; + } +} diff --git a/RoslynMemberSorter/NameOrder.cs b/RoslynMemberSorter/NameOrder.cs new file mode 100644 index 0000000..6727003 --- /dev/null +++ b/RoslynMemberSorter/NameOrder.cs @@ -0,0 +1,22 @@ +namespace RoslynMemberSorter; + +/// +/// Indicates how to sort names. +/// +public enum NameOrder +{ + /// + /// The name of a member is not taken into account when sorting members. + /// + Default, + + /// + /// Names are sorted in alphabetical order (eg: A comes before B). + /// + Alphabetical, + + /// + /// Names are sorted in reverse alphabetical order (eg: B comes before A). + /// + ReverseAlphabetical +} diff --git a/RoslynMemberSorter/Order.cs b/RoslynMemberSorter/Order.cs new file mode 100644 index 0000000..3d7a5d3 --- /dev/null +++ b/RoslynMemberSorter/Order.cs @@ -0,0 +1,23 @@ +namespace RoslynMemberSorter; + +/// +/// Indicates how to sort a given member detail. +/// +/// See properties on for more details. +public enum Order +{ + /// + /// This detail is not taken into account when sorting members. + /// + Default, + + /// + /// This member detail should come first. + /// + First, + + /// + /// This member detail should come last. + /// + Last +} diff --git a/RoslynMemberSorter/ParameterSortStyle.cs b/RoslynMemberSorter/ParameterSortStyle.cs new file mode 100644 index 0000000..bbc1895 --- /dev/null +++ b/RoslynMemberSorter/ParameterSortStyle.cs @@ -0,0 +1,24 @@ +namespace RoslynMemberSorter; + +/// +/// Indicates how parameter lists should be compared. +/// +public enum ParameterSortStyle +{ + /// + /// Indicates parameter types and names are ignored for sorting purposes. + /// + Default, + + /// + /// Sort methods based on parameter types. + /// + /// SomeMethod(int number) comes before SomeMethod(string address). + SortTypes, + + /// + /// Sort methods based on parameter names. + /// + /// SomeMethod(string address) comes before SomeMethod(int number). + SortNames +} diff --git a/RoslynMemberSorter/README.md b/RoslynMemberSorter/README.md new file mode 100644 index 0000000..ce9ccd3 --- /dev/null +++ b/RoslynMemberSorter/README.md @@ -0,0 +1,3 @@ +RoslynMemberSorter uses Roslyn code analysis to detect out of order namespace and type member declarations in C# projects. + +See repository [README](https://github.com/RichardRobertson/RoslynMemberSorter/blob/master/README.md) for full documentation. diff --git a/RoslynMemberSorter/RoslynMemberSorter.csproj b/RoslynMemberSorter/RoslynMemberSorter.csproj new file mode 100644 index 0000000..ebc3839 --- /dev/null +++ b/RoslynMemberSorter/RoslynMemberSorter.csproj @@ -0,0 +1,41 @@ + + + + netstandard2.0 + 10.0 + enable + True + RoslynMemberSorter + RichardRobertson.RoslynMemberSorter + 0.1.0-alpha + Richard Robertson + Uses Roslyn code analysis to detect out of order namespace and type member declarations in C# projects. + Copyright © Richard Robertson 2022 + MIT + https://github.com/RichardRobertson/RoslynMemberSorter + + README.md + https://github.com/RichardRobertson/RoslynMemberSorter/blob/master/CHANGELOG.md#010-alpha-march-25-2022 + Roslyn;Analyzer;C#;CSharp;Member;Sorting;Sorter;Sort;Order + https://github.com/RichardRobertson/RoslynMemberSorter.git + git + $(SourceRevisionId) + + + + + + + + + + + + + + + + + + + diff --git a/RoslynMemberSorter/SortOrder.cs b/RoslynMemberSorter/SortOrder.cs new file mode 100644 index 0000000..2ad3818 --- /dev/null +++ b/RoslynMemberSorter/SortOrder.cs @@ -0,0 +1,42 @@ +namespace RoslynMemberSorter; + +/// +/// Indicates a member detail that can be sorted. These values are used for to indicate the order in which sorts should take place. +/// +public enum SortOrder +{ + /// + /// Sort members based on their accessibility. This uses the order defined by . + /// + Accessibility, + + /// + /// Sort members based on whether they explicitly implement interfaces. This uses the order defined by . + /// + ExplicitInterfaceSpecifier, + + /// + /// Sort fields based on their mutability. This applies to constant and readonly fields and uses the order defined by . + /// + FieldOrder, + + /// + /// Sort members based on their name or operator token. This uses the order defined by for named members or for operators. + /// + Identifier, + + /// + /// Sort members based on their kind. This uses the order defined by . + /// + Kind, + + /// + /// Sort method-like members based on ther parameters. This applies to constructors, delegates, indexers, and methods an uses the orders defined by and . + /// + Parameters, + + /// + /// Sort members based on their static or instance status. This uses the order defined by . + /// + Static +}