Giter Site home page Giter Site logo

dotnet / roslynator Goto Github PK

View Code? Open in Web Editor NEW
3.0K 41.0 243.0 46.96 MB

Roslynator is a set of code analysis tools for C#, powered by Roslyn.

Home Page: https://josefpihrt.github.io/docs/roslynator

License: Other

C# 99.02% PowerShell 0.27% Batchfile 0.01% TypeScript 0.70%
csharp roslyn visual-studio dotnet

roslynator's Introduction

Roslynator

Roslynator is a set of code analysis tools for C#, powered by Roslyn.

IMPORTANT: Analyzers will be removed from Roslynator IDE extensions in the next major release. It's recommended to use Roslynator NuGet packages (e.g. Roslynator.Analyzers) instead.

Tools

Documentation

Contributions

Contributions are welcome! If you are interested please see:

TIP: Bugfixes or small improvements can be implemented right away. Larger task like adding new analyzer or refactoring should be discussed first.

.NET Foundation

This project is supported by the .NET Foundation.

This project has adopted the code of conduct defined by the Contributor Covenant to clarify expected behavior in our community. For more information see the .NET Foundation Code of Conduct.

Command Line Tool

Run following command to install Roslynator command line tool:

dotnet tool install -g roslynator.dotnet.cli

See documentation for further information.

Testing Framework

  • Roslynator Testing Framework can be used for unit testing of analyzers, refactorings and code fixes.
  • See documentation for further information.

Client Libraries

  • Roslynator client libraries are meant be used for development of your own analyzers/refactorings.
  • It does not contain any analyzers/refactorings itself.
  • See reference.
Package Version Extends
Roslynator.Core NuGet Microsoft.CodeAnalysis.Common
Roslynator.Workspaces.Core NuGet Microsoft.CodeAnalysis.Workspaces.Common
Roslynator.CSharp NuGet Microsoft.CodeAnalysis.CSharp
Roslynator.CSharp.Workspaces NuGet Microsoft.CodeAnalysis.CSharp.Workspaces

roslynator's People

Contributors

0x326 avatar adrianwilczynski avatar artur-intech avatar asears avatar bdovaz avatar danghor avatar dependabot[bot] avatar drewnoakes avatar glen-84 avatar jakubreznak avatar jameshargreaves12 avatar jiimaho avatar jnyrup avatar jonasschubert avatar josefpihrt avatar jroessel avatar jsliwinski avatar karl-sjogren avatar khellang avatar kidchenko avatar msdn-whiteknight avatar nickcraver avatar onexey avatar peterkaszab avatar prophetlamb avatar sergergood avatar snickler avatar treit avatar xt0rted avatar xtqqczze avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

roslynator's Issues

Please add a Use Initializer refactoring

Refactor from:

var instance = new Instance();
instance.Name = "a";
instance.Value = "b";
instance.Date = DateTime.Now;

To:

var instance = new Instance {
    Name = "a",
    Value = "b",
    Date = DateTime.Now
};

Wrong suggestion for RCS1032

This should not be suggested in following case:
$"UAC is {(UacHelper.IsUacEnabled ? "" : "not ")s}enabled"

Applying the suggestion leads to an error because we are using ':' in the string interpolation and compiler treats it as separator for format specifier. We need the parenthesis in this case.

Analyzer show errors

Severity:Warning
Code:AD0001
Description:Analyzer 'Roslynator.CSharp.DiagnosticAnalyzers.IfStatementSyntaxDiagnosticAnalyzer' threw an exception of type 'System.NullReferenceException' with message 'Object reference not set to an instance of an object.'.
Project:
Line:1
Active

Assign Field From Constructor

There's a refactoring to go from a constructor parameter to a private readonly field, but not to go in the other direction.

Example:

        private readonly IHelloService _helloService;

doing ctrl+. on _helloService should prompt to populate from constructor:

        public HomeController(IHelloService helloService)
        {
            _helloService = helloService;
        }

Please add refactoring to join lines

There's a piece of code like this:

byte[] destinationBuffer = CopyImage (
            sourceBuffer,
            sourceData.Width,
            sourceData.Height,
            sourceData.Stride,
            destinationData.Stride);

Please add a refactoring to join a separated statement into a single line.

RCS1146 and double null checks

When applying UseConditionalAccess on
b != null && b.c != null
it is replaced with
a?.b != null == true

Could this be replaced directly with a?.b != null?

Error "ElseClauseDiagnosticAnalyzer"

Hi Josef,

First Thanks for your great Work.

I'm getting an Error in the Error-List (0.98.1):

Warning AD0001 Analyzer 'Pihrtsoft.CodeAnalysis.CSharp.DiagnosticAnalyzers.ElseClauseDiagnosticAnalyzer' threw an exception of type 'System.NullReferenceException' with message 'Object reference not set to an instance of an object.'. AdressBook.Model 1
IntelliSense
Active

Source Code that triggers this Error is attached.

AdressBook.zip

Loading settings from disk

I tried looking through the code to see how settings were loaded but looks like they only come from inside of vs settings...

I'd like to put a json setting in the root of the project / solution or in a .vs folder and have the settings loaded. This means I can share them with my team and have them applied. Is this possible?

"Change return type to 'void'" refactoring shouldn't be suggested for methods that are overrides or interface implementations

The following code triggers this refactoring:

    private class SomethingJsonConverter : Newtonsoft.Json.JsonConverter
    {
        // other methods elided

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            // we don't support this operation
            throw new NotImplementedException();
        }
    }

which if applied, changes the method to the following which no longer compiles:

    private class SomethingJsonConverter : Newtonsoft.Json.JsonConverter
    {
        // other methods elided

        public void object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            // we don't support this operation
            throw new NotImplementedException();
        }
    }

As per the title, this refactoring should only be suggested for methods that aren't part of a contract.

RCS1146 refactoring suggestion results in broken code

Given the following code, where Data is a class type with an IDictionary<> named Dictionary defined on it:

return data != null && data.Dictionary.TryGetValue(value, out result) ? result as T : null;

Roslynator 1.2.13 in VS 2017 RC flags this as RCS1146 and applies the following refactoring:

data?.Dictionary.TryGetValue(value, out result == true ? result as T : null

But this causes a syntax error due to the missing right parenthesis after out result, the correct code is:

data?.Dictionary.TryGetValue(value, out result) == true ? result as T : null

RCS1104 has an invalid refactoring

int a = 1;
bool b = a == 1 ? false : true;

The suggested refactoring is: !a == 1, which of course should either be !(a==1) or (for this example) a != 1.
I guess a != 1 would only be a non-changing refactoring if != is semantically equivalent to !(==).
In general that should be a valid assumption, but I don't think that is necessarily true for custom types with operator overloads, even though it should.

Call ConfigureAwait is not working

Hello,

I was trying your code analyzer (latest version on Nuget) and I think I found a small issue: I tested a small async method with its ConfigureAwait method missing and I did not get the expected diagnostic (RCS1090).

My small method:

        public async Task BlehAsync()
        {
            await Task.Delay(23);
        }

I was expecting the analyzer to propose adding .ConfigureAwait(false) to the code since it is missing. I know the analyzers are active because they found an issue in my code.

Let me know if you need more information.

Reusing WhiteSpaceOrEndOfLineRemover

Hi Josef,
sorry to contact you this way but I wasn't able to find your contact information on github.

I am currently working on an open source extension for Visual Studio and had to remove unnecessary white spaces when generating property accessor methods.

I recognized that your WhiteSpaceOrEndOfLineRemover does exactly what I was looking for so I took parts of your implementatio for my extension (see my implementation here).

I referenced your work and your license information in my code, but please let me know if it's ok for you that I am resuing your code this way or if I should add any further information.

Thank you in advance,

Best regards,

Patric

P.S.: By the way, your RoslynTools are really great work!

RCS1103 C# Consider replacing if statement with assignment. Goes wrong

RCS1103 markes this code.

if (Regex.IsMatch(dir.FullPath, @"\[0-9]{2}_"))
{
if (!dir.FullPath.Contains(@"\00_wwle") &&
!dir.FullPath.Contains(@"\02_sb") &&
!dir.FullPath.Contains(@"\02_lb") &&
!dir.FullPath.Contains(@"\05_ab")
)
{
result = false;
}
else
{
result = true;
}
}
else
{
result = true;
}

after code changed, code looks like this.

if (Regex.IsMatch(dir.FullPath, @"\[0-9]{2}_"))
{
result = !!dir.FullPath.Contains(@"\00_wwle") &&
!dir.FullPath.Contains(@"\02_sb") &&
!dir.FullPath.Contains(@"\02_lb") &&
!dir.FullPath.Contains(@"\05_ab");
}
else
{
result = true;
}

but the code must be like this.

if (Regex.IsMatch(dir.FullPath, @"\[0-9]{2}_"))
{
result = !(!dir.FullPath.Contains(@"\00_wwle") &&
!dir.FullPath.Contains(@"\02_sb") &&
!dir.FullPath.Contains(@"\02_lb") &&
!dir.FullPath.Contains(@"\05_ab"));
}
else
{
result = true;
}

Bad advice for RCS1058

I have the following code:

    static private bool BFSProcessIndividual(string xref, int adjacentID, int desiredID,
        Queue<int> q, Dictionary<int, bool> marked, Dictionary<int, int> distanceTo, Dictionary<int, int> edgeTo)
    {
        RHIndividualRecord indi = App.CurrentDatabase.FindIndividual(xref);
        if (indi != null && !marked.ContainsKey(indi.ID))
        {
            Debug.WriteLine($"{nameof(BFSProcessIndividual)}: processing indi ID {indi.ID}");
            edgeTo[indi.ID] = adjacentID;
            distanceTo[indi.ID] = distanceTo[adjacentID] + 1;
            marked[indi.ID] = true;

            if (indi.ID == desiredID)
                return true;

            q.Enqueue(indi.ID);
        }

        return false;
    }

The analyzer is suggesting that:

distanceTo[indi.ID] = distanceTo[adjacentID] + 1;

can be simplified to:

distanceTo[indi.ID] += 1;

However, adjacentID and indi.ID are not identical and therefore this isn't valid.

RCS1128 (Use coalesce expression) Errors on the last statement in a block.

Here's a minimal repro:

public bool Test(bool? a)
{
    if (a == null)
        a = true;
}

Stack:

System.ArgumentOutOfRangeException : Specified argument was out of the range of valid values.
   at Microsoft.CodeAnalysis.SyntaxList`1.get_Item(Int32 index)
   at async Roslynator.CSharp.Refactorings.UseCoalesceExpressionRefactoring.RefactorAsync(<Unknown Parameters>)
   at async Microsoft.CodeAnalysis.CodeActions.CodeAction.GetChangedSolutionAsync(<Unknown Parameters>)
   at async Microsoft.CodeAnalysis.CodeActions.CodeAction.ComputeOperationsAsync(<Unknown Parameters>)
   at async Microsoft.CodeAnalysis.CodeActions.CodeAction.ComputePreviewOperationsAsync(<Unknown Parameters>)
   at async Microsoft.CodeAnalysis.CodeActions.CodeAction.GetPreviewOperationsAsync(<Unknown Parameters>)
   at async Microsoft.CodeAnalysis.Editor.Implementation.Suggestions.SuggestedAction.GetPreviewResultAsync(<Unknown Parameters>)
   at async Microsoft.CodeAnalysis.Editor.Implementation.Suggestions.SuggestedActionWithNestedFlavors.<>c__DisplayClass11_0.<GetPreviewAsync>b__0(<Unknown Parameters>)
   at async Microsoft.CodeAnalysis.Extensions.IExtensionManagerExtensions.PerformFunctionAsync[T](<Unknown Parameters>)

The break is here (code link):

StatementSyntax nextStatemnt = statements[index + 1];

(also: minor spelling error in "nextStatemnt" there, yay Intellisense! - I do this all the time...)

I'm not familiar enough with Roslyn to submit a PR, so just passing along. Thanks for this project - it's absolutely fantastic.

README.md

It would be nice to have a readme file with basic info (like the list of List of analyzers & List of refactorings included etc).

void methods and "Use expression-bodied member or Expand to expression-bodied member"

Environment

  • Visual Studio version: 2015 Enterprise update 3
  • Roslynator version: 1.1.7

Description
Both refactoring methods doesn't work well with void methods

1. Use expression-bodied member

Steps to recreate

Write a void method expanded like so:

private void AddName(string name)
{ 
        Names.Add(name);
}

Current behavior

The refactoring option doesn't show.


2. Expand to expression-bodied member

Steps to recreate

Write a void method as expression-bodied like so:

private void AddName(string name) => Names.Add(name);

Current behavior

the refactoring appear but it does it wrongly by adding a return keyword.

private void AddName(string name)
{ 
       return Names.Add(name);
}

VS Code support

It would great to have Roslynator as Visual Studio Code extension.

RCS1058 false positive

namespace ConsoleApplication2
{
    class RCS1058_B
    {
        public int Prop { get; set; }
    }

    class RCS1058_A
    {
        public int Prop { get; set; } = 10;

        public RCS1058_B GetB()
        {
            return new RCS1058_B()
            {
                Prop = Prop / 10 //This cannot be simplified, as Prop on rhs refers to RCS1058_A.Prop
            };
        }
    }

    public class RCS1058
    {
        public static void Run()
        {
            var a = new RCS1058_A();
            var b = a.GetB();
            var hest = 1;
        }
    }
}

Option 'Prefix field identifier with underscore' not taken into account

Hello,

I've got a problem with this option :

On visualstudio startup it's set to 'false'. But when generating a variable, the underscore is there.
I then need to set the option to true, then back to false to have it correctly taken into account.
This need to be done after each start up (same issue on vs 2015 & vs 2017).

I suppose there is a little issue when loading this option.

Could you have a look ?

Pierre

RCS1093 Bad behavior on non-empty #if <def> files

I'm not sure what to suggest here, just providing that the suggestion is odd. Analyzer in play:

RCS1093: Remove file with no code.

But when compiling projects where the whole file is #if conditioned, this is an invalid suggestion overall. Example:

#if NET46
namespace MyTests
{
    public class Test { }
}
#endif

...when the project targets both netstandard1.5 and net46. Screenshot of my example case:
screen shot 2017-02-26 at 10 07 15

So while in the context of that particular framework compilation there isn't any used code, there is code in the file (where the suggestion points). Is it possible to change this check for actual empty files, or is there no knowledge of that available?

RCS1085 false positive

class A
{
    private readonly string s = "s";
    // RCS1085 (consider replacing property with auto-implemented property) at the next line:
    public object S => s;
}

Replacing with auto property can break the existing code here because the property type is more generic than the field type, and not every method that was called on the field can be called on the property.

It's very interesting though that the warning can be suppressed in this small sample (but in the real code it is not working) by adding any comment after the ; in the property declaration (for this reason the comment in my example is above and not after the property).

RCS1031

I agree that this is a terrible misuse of local scopes to circumvent bad coding style...
RCS1031 is triggered on both pair of braces, but the code becomes invalid if any local scope is removed.

{
	int a = 1;
}
{
	int a = 1;
}

RCS1143 - Shouldn't gray the second part of a coalesce, suggesting it's useless

Using VS2015 Enterprise Update 3 / Roslynator 1.2.12 / .Net 4.6.2

rcs1143-2

RCS1143 when active seems to consider the second part of a coalesce expression as useless, graying it out in the UI (the warning doesn't pop in the IntelliSense list though).

It shouldn't use the graying effect, that is used for element that can be deleted or replaced safely, when that is not the case.

It would be nice if we could disable this refactoring too.

rcs1143-options

RCS1102 C# Consider marking class as static

I've false errors RCS1102 C# Consider marking class as static. in project for classes like

internal abstract class Base
{
   // here the RCS1102  error  occurs
   internal abstract class Const  
   {
   }
}

and derived from it

internal class Derived : Base
{
   // here the RCS1102  error occurs
   internal new class Const : Base.Const
   {
   }
}

According to C# rules abstract classes cannot be static, and static classes should be inherited from the Object.
So the check fails in both cases

The extension disables itself all the time

I don't know if this problem happen just with me but every time that I open Visual Studio, the extension starts disabled and I need go to Extensions and Updates to re-enable it.

Any clue about this?

New refactoring for backing field null checks

The following code:

private Thing _thang;

public Thing Thang
{
    if (_thang == null)
    {
        _thang = MethodThatReturnsAThing();
    }

    return _thang;
}

can be simplified to the following, which is semantically equivalent:

private Thing _thang;

public Thing Thang
{
    return _thang ?? (_thang = MethodThatReturnsAThing());
}

Add missing semicolon

Hi,

Thanks for this amazing set of analyzers ๐Ÿ’ฏ ๐ŸŽ‰

The Add missing semicolon analyzer is causing me some stress because:

  1. It always appears first, generally ahead of the analyzer I actually want to invoke (add using statement)
  2. It doesn't appear that I can disable this specific analyzer

Any thoughts on getting this rectified?

Please add refactoring to add braces

Please support adding the braces for single line if and for statements.

Before:

if (i < 0)
    i = 0;

for (int i = 0; i < 3; i++)
     x += i;

After:

if (i < 0) {
    i = 0;
}

for (int i = 0; i < 3; i++) {
     x += i;
}

Analyzers missing in Roslynator 1.1.6.1

After installing Roslynator 1.1.6.1 several analyzers are missing (Visual Studio 2015 Professional)

eg. RCS1100, RCS1101, RCS1102, RCS1103, RCS1104, RCS1105

Uninstalling and reinstalling Roslynator did not help.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.