Query Methods in Roslyn Syntax API

In previous post I discussed about Roslyn Syntax API: First Look .

In pervious approach I traversed manually in Syntax Tree to the Method level and started from Compilation Unit level to get the Method Arguments. Rather than manually navigating the Syntax Tree, you can use LINQ to get the parameter in the function. We can directly apply LINQ on Syntax Tree.

image

If you remember from last post out Syntax Tree was as below,

clip_image001

Now if we want to print method name using LINQ in Syntax tree then,

clip_image003

Underneath LINQ is also doing the manual traversing of the Syntax tree. When you execute above code you will get output as below,

clip_image004

If you have more than one parameters in the method then you can print them like below,

clip_image006

And then you can traverse using foreach to print all the method names. For your reference all the code discussed in this post is given below,


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Roslyn.Compilers;
using Roslyn.Compilers.CSharp;

namespace ConsoleApplication30
{
class Program
{
static void Main(string[] args)
{

SyntaxTree tree = SyntaxTree.ParseCompilationUnit(
@"class Animal
{
void Display(string animalName,int abc)
{
Console.WriteLine(""Animal name is "" + animalName);
}
}");
var root = (CompilationUnitSyntax) tree.Root;

var paraMeterList = from r in root.DescendentNodes().OfType<MethodDeclarationSyntax>()
where r.Identifier.ValueText == "Display"
select r.ParameterList.Parameters.First();
Console.WriteLine(paraMeterList.Single().ToString());

var AllParaMeterList = from r in root.DescendentNodes().OfType<MethodDeclarationSyntax>()
where r.Identifier.ValueText == "Display"
select r.ParameterList.Parameters;
foreach (var r in AllParaMeterList)
{

foreach (var a in r)
{
Console.WriteLine(a.ToString());
}

}
Console.ReadKey(true);

}
}
}

&nbsp;

 

When you execute above listed code, you will get output as below,

clip_image001

In this way you can traverse Syntax tree using LINQ. I hope this post is useful. Thanks for reading Smile

If you find my posts useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you.

4 responses to “Query Methods in Roslyn Syntax API”

  1. […] Query Methods in Roslyn Syntax API and Conditional Reading of Windows Azure BLOB (Dhananjay Kumar) […]

  2. […] Query Methods in Roslyn Syntax API (Dhananjay Kumar) […]

  3. […] Query Methods in Roslyn Syntax API – Dhananjay Kumar […]

Leave a comment

Create a website or blog at WordPress.com