Getting column number in source generators (IIncrementalGenerator)

69 views Asked by At

I am currently working on some source generators in combination with interceptors. As basis, I used this documentation: https://github.com/dotnet/roslyn/blob/main/docs/features/interceptors.md

My problem is the following: Given the following code:

public class Test
{
    public void TestFunc()
    {
        var foo = new Foo();
        foo.Bar();
    }
}

Basically, I want to intercept the Bar call here. Retrieving the filename for the cs file is pretty straightforward - also, retrieving the line number.

var path = GetInterceptorFilePath(context.Node.SyntaxTree,
context.SemanticModel.Compilation);
var line = context.SemanticModel.SyntaxTree.GetLineSpan(context.Node.Span).StartLinePosition.Line
+ 1;

The problem starts when trying to get the character.

My approaches so far: context.SemanticModel.SyntaxTree.GetLineSpan(context.Node.Span).Span.Start.Character. But that returns just 1; it seems this will not take whitespace into account. The next: context.Node.ToString().IndexOf("Bar", StringComparison.Ordinal) This will also ignore whitespace.

That said, what is the correct approach?

Also, consider that people sometimes use tabs or spaces - tabs can have different lengths. And I am not sure how this is considered for the interceptors. The documentation here doesn't reveal more, either.

1

There are 1 answers

4
RatzMouze On

Once you have the syntax node for the `InvocationExpressionSyntax`, then you can use a `.GetLocation()` on that node. It will give you a `Location` object, from where you will find the filepath and the `SourceSpan` object with the start, end and length of the invocation.