Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Roslyn to determine line code's position in a source file

I do some research on stackoverflow but I can't find the result I need. My problem is "How to determine line code's position of a source file by using Roslyn". For example: I have a source file (named: sample.cs) and content it looks like

using System;

/// <summary>
/// This is summary of namespace
/// </summary>
namespace LearnRoslyn
{
    /// <summary>
    /// This is summary of class
    /// </summary>
    public class CodeSample2
    {

        public SampleClass MyMethod1(int a, int b, SampleClass cls)
        {
            //This is call method
            cls = new SampleClass();
            cls.MyMethod4(a);

            //This is 3-tier condition
            a = (a > b ? 1 : 0);

            //This is IF comment
            if (a > b && a / b > 1 && b - a == 1)
            {
                //This is another IF comment
                if (a > b || (a / b > 1 && b - a == 1))
                {
                    Console.WriteLine("a > b");
                }
            }
            else
            {
                if (cls != null)
                {
                    Console.WriteLine("a < b");
                }

                if (cls.IsNull)
                {
                    Console.WriteLine("a < b");
                }
            }

            return null;
        }

        public void MyMethod2(int n)
        {

            n = 2;
        }
    }

    public class SampleClass
    {
        public bool IsNull { get; set; }
        public void MyMethod3(int a, int b)
        {

            if (a > b)
            {
                Console.WriteLine("a > b");
            }
            else
            {
                Console.WriteLine("a < b");
            }
        }

        public void MyMethod4(int n)
        {

            n = 2;
        }
    }
}

As I know, use "CSharpSyntaxWalker" (override Visitor method) to implement that, but I don't know how? How to know the code "if (a > b && a / b > 1 && b - a == 1)", position at line 24 in source file sample.cs? Any suggestion for this situation? Thanks.

like image 921
soultingo Avatar asked Jul 18 '18 02:07

soultingo


1 Answers

Expanding on @George Alexandria's comment, you can get the line number of a node from its syntax tree:

class MyWalker : CSharpSyntaxWalker
{
    public override void Visit(SyntaxNode node)
    {
        FileLinePositionSpan span = node.SyntaxTree.GetLineSpan(node.Span);
        int lineNumber = span.StartLinePosition.Line;

        // Do stuff with lineNumber.
        // ...
    }

    // ...
}

See SyntaxTree.GetLineSpan.

like image 143
Matthew Avatar answered Sep 24 '22 21:09

Matthew