Overview and Preparation
Creating an Analyzer Based on the Analyzer with Code Fix (.NET Standard) Project Template
Creating an Analyzer Based on the Standalone Code Analysis Tool Project Template
if (number < 0){}
public static Project GetProjectFromSolution(String solutionPath){MSBuildLocator.RegisterDefaults();MSBuildWorkspace workspace = MSBuildWorkspace.Create();Solution currSolution = workspace.OpenSolutionAsync(solutionPath).Result;Project currProject = currSolution.Projects.Single();return currProject;}
if (number > 0){}
- Find all the nodes of the tree with the IfStatementSyntax type.
- Access the Statementobject property of the IfStatementSyntax type and check whether it is a node of the BlockSyntax type that encapsulates the necessary information about the code block represented in curly brackets.
- Access the BlockSyntax.Statements property. This property represents a list of StatementSyntax objects. Check that the Statements list is not empty. This list is empty when the if block does not contain any StatementSyntax objects (i.e. the if statement's curly braces are empty).
Project currProject = GetProjectFromSolution(solutionPath)StringBuilder warnings = new StringBuilder();foreach (var document in currProject.Documents){var tree = document.GetSyntaxTreeAsync().Result;var ifStatementNodes = tree.GetRoot().DescendantNodesAndSelf().Where(x => x.IsKind(SyntaxKind.IfStatement));foreach (var node in ifStatementNodes){var ifStatement = node as IfStatementSyntax;if (ifStatement.Statement is BlockSyntaxblockSyntax && !blockSyntax.Statements.Any()){warnings.Append($"Empty if block is found in file" +$" {document.FilePath} at line" +$" {ifStatement.GetLocation().GetLineSpan().StartLinePosition.Line + 1}" +$" \n");}} }if (warnings.Length != 0)File.AppendAllText(logPath, warnings.ToString());
What Project Type to Choose for Your Static Analyzer?
Summary
Credits
Article Type : | Guest Article |
Author : | Ilya Gainulin |
Tags : | CSharp, Knowledge |
Article Date : | 17-03-2021 |
Article Publish Date : | 19-03-2021 |
Note: All content of this article is copyright of their author. |