Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting node from line number in Roslyn

Tags:

c#

roslyn

How can I get a SyntaxNode based on a line number? Else if its possible to get LineSpan of that line number then to node.

like image 474
Kim KangIn Avatar asked Jul 11 '16 02:07

Kim KangIn


2 Answers

You can get the span of a line from the document text. From there, you can find all nodes that intersect with the span of the line. This will return multiple syntax nodes, which you can then use your criteria to pull out the one you are looking for:

    static void Main(string[] args)
    {
        var code = @"
using System;

namespace ConsoleApplication1
{
    class TypeName
    {   
         public int Add(int x, int y) 
         {
             return x+y;
         }
     }
}";
        var st = SourceText.From(code);
        var sf = SyntaxFactory.ParseSyntaxTree(st);

        var span = sf.GetText().Lines[9].Span;
        var nodes = sf.GetRoot().DescendantNodes().Where(x => x.Span.IntersectsWith(span));

        Console.WriteLine(nodes.Last().ToString());
        Console.ReadKey();
    }
like image 154
John Koerner Avatar answered Sep 23 '22 18:09

John Koerner


using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Text;

var s =  @"class M
{
    public void P() { }
}";
var text = SourceText.From(s);
var lineIndex = 2;
var lineSpan = text.Lines[lineIndex].Span;
var tree = SyntaxFactory.ParseSyntaxTree(text);
var node = tree.GetRoot().FindNode(lineSpan);
// or if you want a all nodes related to the span
var node = tree.GetRoot().DescendantNodesAndSelf(lineSpan);
like image 41
Eli Arbel Avatar answered Sep 25 '22 18:09

Eli Arbel