Jerric Lyns John
Jerric Lyns John

Reputation: 936

Not able to specifically traverse through the syntax tree?

I'm trying to implement a Diagnostic Analyzer for Collection initializer and its corresponding Code Fix provider.

Wrong Code:

var sampleList= new List<string>();
sampleList.Add("");
sampleList.Add("");

After CodeFix:

var sampleList= new List<string>(){"", ""};

But I'm stuck at this problem that once I get a node for LocalDeclarationStatement, I'm not aware if there exists a way to get the very next adjacent node from the parent.

Syntax Tree

In the above Picture I require both the ExpressionStatement after analyzing the LocalDeclarationStatement

REQUIREMENT for analyzer

  1. Identify the LocalDeclarationStatement, a collection that is already initialized but doesnt contain CollectionInitializerExpression
  2. Find if the very next line has an Expression statement that is using Add method on the same collection

REQUIREMENT for Code fix

  1. Provide Collection initializer syntax for the adjacent Expression statements that are using Add method on the collection
  2. All other intermitten usage of Add method on the collection has to be avoided.

Upvotes: 1

Views: 178

Answers (2)

Jason Malinowski
Jason Malinowski

Reputation: 19031

You can do something like:

var declarationStatement = ...;
var block = (BlockSyntax)declarationStatement.Parent;
var index = block.Statements.IndexOf(declarationStatement);
var nextStatement = block.Statements[index + 1];

Upvotes: 3

Erti-Chris Eelmaa
Erti-Chris Eelmaa

Reputation: 26318

Wouldn't you just need to turn the concrete block into list, and check?

var nodes = yourSyntaxTree.DescentNodes().ToList();

for(var i = 0; i < nodes.Count; i++){
  var localDeclarationStatement = nodes[i] as LocalDeclarationStatement;
  if(localDeclarationStatement==null && i + 1 >= nodes.Length)
      continue;

  var expressionStatement = nodes[i+1] as ExpressionStatement;
  if(expressionStatement==null)
     continue;

  // there you have it.
}

Upvotes: 1

Related Questions