Giter Club home page Giter Club logo

roslyn-analyzers's Introduction

Roslyn Analyzers

Windows Debug Windows Release Ubuntu Debug Ubuntu Release
main Build Status codecov Build Status Build Status Build Status

What is Roslyn?

Roslyn is the compiler platform for .NET. It consists of the compiler itself and a powerful set of APIs to interact with the compiler. The Roslyn platform is hosted at github.com/dotnet/roslyn.

What are Roslyn Analyzers?

Roslyn analyzers analyze your code for style, quality and maintainability, design and other issues. The documentation for Roslyn Analyzers can be found at learn.microsoft.com/dotnet/fundamentals/code-analysis/overview.

Microsoft created a set of analyzers called Microsoft.CodeAnalysis.NetAnalyzers that contains the most important "FxCop" rules from static code analysis, converted to Roslyn analyzers, in addition to more analyzers. These analyzers check your code for security, performance, and design issues, among others. The documentation for .NET analyzers can be found here.

Main analyzers

Recently the set of analyzer packages produced by this repository have been consolidated. The following table summarizes this information:

NuGet Package Name Version Summary
Microsoft.CodeAnalysis.NetAnalyzers NuGet ✔️ Primary analyzer package for this repo. Included default for .NET 5+. For earlier targets read more.
Microsoft.CodeAnalysis.BannedApiAnalyzers NuGet ✔️ Allows banning use of arbitrary code. Read more.
Microsoft.CodeAnalysis.PublicApiAnalyzers NuGet ✔️ Helps library authors monitor changes to their public APIs. Read more.
Microsoft.CodeAnalysis.Analyzers NuGet ⚠️ Intended projects providing analyzers and code fixes. Read more.
Roslyn.Diagnostics.Analyzers NuGet ⚠️ Rules specific to the Roslyn project, not intended for general consumption. Read more.
Microsoft.CodeAnalysis.FxCopAnalyzers NuGet ⛔ Use Microsoft.CodeAnalysis.NetAnalyzers instead. Read more.
Microsoft.CodeQuality.Analyzers NuGet ⛔ Use Microsoft.CodeAnalysis.NetAnalyzers instead. Read more.
Microsoft.NetCore.Analyzers NuGet ⛔ Use Microsoft.CodeAnalysis.NetAnalyzers instead. Read more.
Microsoft.NetFramework.Analyzers NuGet ⛔ Use Microsoft.CodeAnalysis.NetAnalyzers instead. Read more.

Microsoft.CodeAnalysis.NetAnalyzers

Latest stable version: NuGet

Latest pre-release version (.NET8 analyzers): here

This is the primary analyzer package for this repo that contains all the .NET code analysis rules (CAxxxx) that are built into the .NET SDK starting .NET5 release. The documentation for CA rules can be found at learn.microsoft.com/visualstudio/code-quality/code-analysis-for-managed-code-warnings.

You do not need to manually install this NuGet package to your project if you are using .NET5 SDK or later. These analyzers are enabled by default for projects targeting .NET5 or later. For projects targeting earlier .NET frameworks, you can enable them in your MSBuild project file by setting one of the following properties:

  1. EnableNETAnalyzers

    <PropertyGroup>
      <EnableNETAnalyzers>true</EnableNETAnalyzers>
    </PropertyGroup>
  2. AnalysisLevel

    <PropertyGroup>
      <AnalysisLevel>latest</AnalysisLevel>
    </PropertyGroup>

Microsoft.CodeAnalysis.FxCopAnalyzers

NOTE: Starting version 3.3.2, Microsoft.CodeAnalysis.FxCopAnalyzers has been deprecated in favor of Microsoft.CodeAnalysis.NetAnalyzers. Documentation to migrate from FxCopAnalyzers to NetAnalyzers is available here.

Latest stable version: NuGet

This is a migration analyzer package for existing binary FxCop users. It contains all the ported FxCop code analysis rules (CAxxxx). It's recommended to use Microsoft.CodeAnalysis.NetAnalyzers instead. The documentation for that can be found at learn.microsoft.com/visualstudio/code-quality/install-net-analyzers.

The documentation for all the ported and unported FxCop rules can be found at learn.microsoft.com/visualstudio/code-quality/fxcop-rule-port-status.

This analyzer package contains all the ported FxCop rules that are applicable for both .NetCore/.NetStandard and Desktop .NetFramework projects. You do not need to install any separate analyzer package from this repo to get target-framework specific FxCop rules.

The following are subpackages or NuGet dependencies that are automatically installed when you install the Microsoft.CodeAnalysis.FxCopAnalyzers package:

NOTE: Starting version 3.3.2, Microsoft.CodeQuality.Analyzers, Microsoft.NetCore.Analyzers and Microsoft.NetFramework.Analyzers have also been deprecated in favor of Microsoft.CodeAnalysis.NetAnalyzers. Documentation to migrate to NetAnalyzers is available here.

Microsoft.CodeQuality.Analyzers

Latest stable version: NuGet

This package contains common code quality improvement rules that are not specific to usage of any particular API. For example, CA1801 (ReviewUnusedParameters) flags parameters that are unused and is part of this package.

Microsoft.NetCore.Analyzers

Latest stable version: NuGet

This package contains rules for correct usage of APIs that are present in .NetCore/.NetStandard framework libraries. For example, CA1309 (UseOrdinalStringComparison) flags usages of string compare APIs that don't specify a StringComparison argument. Getting started with NetCore Analyzers

NOTE: This analyzer package is applicable for both .NetCore/.NetStandard and Desktop .NetFramework projects. If the API whose usage is being checked exists only in .NetCore/.NetStandard libraries, then the analyzer will bail out silently for Desktop .NetFramework projects. Otherwise, if the API exists in both .NetCore/.NetStandard and Desktop .NetFramework libraries, the analyzer will run correctly for both .NetCore/.NetStandard and Desktop .NetFramework projects.

Microsoft.NetFramework.Analyzers

Latest stable version: NuGet

This package contains rules for correct usage of APIs that are present only in Desktop .NetFramework libraries.

NOTE: The analyzers in this package will silently bail out if installed on a .NetCore/.NetStandard project that do not have the underlying API whose usage is being checked. If future versions of .NetCore/.NetStandard libraries include these APIs, the analyzers will automatically light up on .NetCore/.NetStandard projects that target these libraries.

Other Analyzer Packages

Microsoft.CodeAnalysis.Analyzers

Latest stable version: NuGet

Latest pre-release version: here

This package contains rules for correct usage of APIs from the Microsoft.CodeAnalysis NuGet package, i.e. .NET Compiler Platform ("Roslyn") APIs. These are primarily aimed towards helping authors of diagnostic analyzers and code fix providers to invoke the Microsoft.CodeAnalysis APIs in a recommended manner. More info about rules in this package

Roslyn.Diagnostics.Analyzers

Latest stable version: NuGet

Latest pre-release version: here

This package contains rules that are very specific to the .NET Compiler Platform ("Roslyn") project, i.e. dotnet/roslyn repo. This analyzer package is not intended for general consumption outside the Roslyn repo. More info about rules in this package

Microsoft.CodeAnalysis.BannedApiAnalyzers

Latest stable version: NuGet

Latest pre-release version: here

This package contains customizable rules for identifying references to banned APIs. More info about rules in this package

For instructions on using this analyzer, see Instructions.

Microsoft.CodeAnalysis.PublicApiAnalyzers

Latest stable version: NuGet

Latest pre-release version: here

This package contains rules to help library authors monitoring change to their public APIs. More info about rules in this package

For instructions on using this analyzer, see Instructions.

MetaCompilation (prototype)

Created by summer 2015 interns Zoë Petard, Jessica Petty, and Daniel King

The MetaCompilation Analyzer is an analyzer that functions as a tutorial to teach users how to write an analyzer. It uses diagnostics and code fixes to guide the user through the various steps required to create a simple analyzer. It is designed for novice analyzer developers who have some previous programming experience.

For instructions on using this tutorial, see Instructions.

Getting Started

  1. Install Visual Studio 2022 or later, with at least the following workloads:
    1. .NET desktop development
    2. .NET Core cross-platform development
    3. Visual Studio extension development
  2. Clone this repository
  3. Install .NET SDK version specified in .\global.json with "dotnet":
  4. Open a command prompt and go to the directory of the Roslyn Analyzer Repo
  5. Run the restore and build command: build.cmd(in the command prompt) or .\build.cmd(in PowerShell).
  6. Execute tests: test.cmd (in the command prompt) or .\test.cmd (in PowerShell).

Submitting Pull Requests

Prior to submitting a pull request, ensure the build and all tests pass using using steps 4 and 5 above.

Guidelines for contributing a new Code Analysis (CA) rule to the repo

See GuidelinesForNewRules.md for contributing a new Code Analysis rule to the repo.

Versioning Scheme for Analyzer Packages

See VERSIONING.md for the versioning scheme for all analyzer packages built out of this repo.

Recommended version of Analyzer Packages

Recommended Analyzer Package Version: NuGet

Required Visual Studio Version: Visual Studio 2019 16.9 RTW or later

Required .NET SDK Version: .NET 5.0 SDK or later

The documentation for .NET SDK Analyzers can be found here

roslyn-analyzers's People

Contributors

333fred avatar basoundr avatar buyaa-n avatar collinalpert avatar cosifne avatar cyrusnajmabadi avatar daking2014 avatar danielkim-msft avatar dotnet-bot avatar dotnet-maestro[bot] avatar dotpaul avatar drewnoakes avatar evangelink avatar genlu avatar github-actions[bot] avatar jarlob avatar jkoritzinsky avatar jmarolf avatar lingxiachen avatar lllxxxccc avatar mavasani avatar newellclark avatar paulomorgado avatar qinxgit avatar ryzngard avatar sharwell avatar srivatsn avatar tmat avatar tmeschter avatar youssef1313 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  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

roslyn-analyzers's Issues

Setup NuGet package creation

This probably involves creating a separate project that just runs packaging for everything after Analyzers.sln is built, or maybe giving each sub-project (Microsoft.CodeAnalysis.Analyzers, AnalyzerPowerPack, etc.) it's own packaging project. We should consider using NuProj as well.

Change which trailing trivia to analyze

The trivia checks should be as follows:

if (ifKeyword.HasTrailingTrivia) 
{
    if (ifKeyword.TrailingTrivia.Count == 1)
    {
        var trailingTrivia = ifKeyword.TrailingTrivia.First();

add .Count ==1 and change .Last() to .First()

TrailingTrivia checking

Check the count of TrailingTrivia in the final user product, and change .Last() to .First()

Remove uses of ToString()

I see a fair number of places where ToString() is being called to get a string representation of an object which is then compared to some known/expected value.

The contract of the object.ToString method is very loose: it must simply return some string representation of the object. That string representation may not be what you want or expect, and in many cases it isn't documented at all. For example, calling ToString() on a SyntaxNode may return a string that preserves the original formatting in the document, or it may not.

For that reason you should generally only use ToString for debugging or logging purposes, and all other uses should be replaced with something else.

Add code fix to template

Move the code fix from SyntaxNodeAnalyzer into the blank template, with an explanatory comment

Rewrite all messages

Rewrite the messages so that there are no ...s and they are consistent and allow people to not use the code fixes. Make the squiggled thing the subject.

  • "identifying" -> "distinguishing", id message

Analyze if statement to include comments

  • inserting context.Register needs AnalyzeIfStatement comment inserted
  • inserting AnalyzeIfStatement needs AnalyzeIfStatement comment inserted
  • incorrect parameter needs AnalyzeIfStatement comment inserted

Add README.md

In particular, note how to get started with the project (downloading NuGet packages, building, etc.).

Diagnostic messages should be specific

I see a number of diagnostics where the title and message are the same.

Diagnostic titles should be very short and general, as they describe the diagnostic in general. Messages, on the other hand, can and should be customized to include information specific to a particular instance of a diagnostic.

For example, if your diagnostic's title is

Diagnostic ID has not been declared

then the accompanying message should be

Diagnotic ID '{0}' has not been declared

where {0} is a placeholder for the actual ID. Later, when calling Diagnostic.Create you can pass in the actual ID and the placeholder will be filled in.

Don't pass arguments you don't need

I've noticed a lot of methods in DiagnosticAnalyzer.cs that take a CompilationAnalysisContext as as argument, but then make no use of it (or pass it along to some other method that makes no use of it). These should be removed.

Avoid use of 'object'

For example (from DiagnosticAnalyzer.cs):

internal List<object> CheckInitialize(CompilationAnalysisContext context)

This method always returns the same three things: an IMethodSymbol representing the Register method, a List<ISymbol> representing the arguments, and (sometimes) an InvocationExpressionSyntax for the method call. By putting them into a List<object> to return them, you're losing that type information. There are at least two problems with this:

  1. You aren't documenting what CheckInitialize really returns; instead, the caller needs to somehow know that the first item in the list is an IMethodSymbol, the second is a List<object>, etc.
  2. If you accidentally change the set of items returned, or return them in the wrong order, the compiler can't help you check that the caller is still using them in the correct way. For example, if the IMethodSymbol accidentally became the second item in the list, you wouldn't know until you run the code that something was broken.

The fix here is to create a helper type to hold these three pieces of information. E.g.,

class InitializeInfo
{
    public IMethodSymbol RegisterMethod { get; }
    public List<ISymbol> RegisterArgs { get; }
    public InvocationExpressionSyntax InvocationExpression { get; }

    public InitializeInfo(IMethodSymbol registerMethod, List<ISymbol> registerArgs, InvocationExpressionSyntax InvocationExpression = null;
    {
        RegisterMethod = registerMethod;
        RegisterArgs = registerArgs;
        InvocationExpression = invocationExpression;
    }
}

Principle: you should avoid using object whenever possible. In practice, you always have more information about type of an object, and by being as specific as possible the compiler can help catch errors.

Add comments to code fixes

Have most code fixes come with a comment
Sync with template
Comments above rather than below

  • Register comment, "IfStatementSyntax" -> "IfStatement"
  • "intergers" -> "integers"
  • red squiggle is quoted

Place a blank line after blocks

For example (from DiagnosticAnalyzer.cs), don't do this:

if (registerInfo == null)
{
    return;
}
var registerSymbol = (IMethodSymbol)registerInfo[0];

Instead, do this:

if (registerInfo == null)
{
    return;
}

var registerSymbol = (IMethodSymbol)registerInfo[0];

Principle: A block contains a set of related code. It should be visually distinct from the code that come after it, which is not related (at least, not in the same way).

Enable CI builds

This includes the following:

  • Porting BuildAndTest.proj from dotnet/roslyn
  • Creating the appropriate cibuild.cmd/cibuild.sh scripts
  • Setting up Jenkins to work with this repo
  • Displaying Jenkins status badges on the home page

Replacing an explicit declaration with an equivalent compiler-generated should not trigger RS0017

See, for example, a declaration of an empty protected instance constructor in the class Microsoft.CodeAnalysis.Location:

    public abstract class Location
    {
        protected Location()
        {
        }

        // ...

This declaration is redundant. If you remove it from source, the compiler generates exactly the same by default. So, it does not affect a shape of public API in any way.

But when I tried to remove it, the build failed with an error:

error RS0017: Symbol 'Microsoft.CodeAnalysis.Location.Location()' is part of the declared API, but is either not public or could not be found

EXPECTED: This error does not occur.

Fix Github README.md

  • use ``` to insert code snippets
  • links should be new lines, text should be links
  • link to how to recreate the syntax tree image
  • "underline" -> "squiggle"
  • "produce live warnings" -> "produce live diagnostics"
  • when explaining what the tutorial creates, it should allow for no trivia to be present
  • analyzer information section is wordy
  • link to Alex Turner's blog
  • verify accuracy of current links
  • don't discourage use of code fixes
  • open a new file for debugging should tell them to open a console app
  • walk through the steps of making an analyzer, per Kasey's suggestion
  • crop image

Wording issues

  • change "must" to "should" everywhere
  • change "single whitespace" to "single space" everywhere

Update Labels

By and large we should copy the set of labels used by dotnet/roslyn:

  • 0 - Backlog (#CCCCCC)
  • 1 - Planning (#CCCCCC)
  • 2 - Ready (#CCCCCC)
  • 3 - Working (#CCCCCC)
  • 4 - In Review (#CCCCCC)
  • Area-Infrastructure (#5319e7)
  • Area-MetaCompilation (#5319e7)
  • Blocked (#6400)
  • Bug (#fc2929)
  • Discussion (#fbca04)
  • Enhancement (#fc2929)
  • Feature Request (#fc2929)
  • Localization (#fc2929)
  • Need More Info (#fbca04)
  • Question (#fc2929)
  • Resolution-Answered (#CCCCCC)
  • Resolution-By Design (#CCCCCC)
  • Resolution-Duplicate (#CCCCCC)
  • Resolution-External (#CCCCCC)
  • Resolution-Fixed (#CCCCCC)
  • Resolution-Not Applicable (#CCCCCC)
  • Resolution-Not Reproducible (#CCCCCC)
  • Resolution-Won't Fix (#CCCCCC)
  • Test (#fc2929)
  • Up for Grabs (#90EE90)
  • Verification Not Required (#6400)
  • Verified (#6400)
  • cla-already-signed (#009800)
  • cla-not-required (#90EE90)
  • cla-required (#e11d21)
  • cla-signed (#207de5)
  • Update existing issues with tags

Use minimum possible accessibility

Consider (from DiagnosticAnalyzer.cs):

public const string RuleCategory = "Tutorial";

RuleCategory is only used within MetaCompilationAnalyzer, and as such it should be private. This goes for any member of a type. Also, in this particular case you'll need to change the name to match the coding conventions for private const/static members. So you'll end up with this:

private const string s_ruleCategory = "Tutorial";

Principle: Types and members should only be as accessible as they need to be.

Move from MSTest to xUnit

MSTest has issues with running unit tests involving Roslyn. Also, dotnet/roslyn uses xUnit instead of MSTest and it would be good to be consistent.

Don't pass message args in if there aren't any

ReportDiagnostic(context, IncorrectAccessorReturnRule, returnDeclaration.GetLocation());

vs.

ReportDiagnostic(context, IncorrectAccessorReturnRule, returnDeclaration.GetLocation(), IncorrectAccessorReturnRule.MessageFormat);

includes in the user end product

Sync up code fixes

Sync up all the code fixes written by different people so they follow the same format. Use SyntaxGenerator instead of SyntaxFactory, separate into two methods the creation of the new node and the insertion of that node, and move the creation of the node to the CodeFixNodeCreator class

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.