How to get the filename and line number of a particular JetBrains.ReSharper.Psi.IDeclaredElement?

384 Views Asked by At

I want to write a test framework extension for resharper. The docs for this are here: http://confluence.jetbrains.net/display/ReSharper/Test+Framework+Support

One aspect of this is indicating if a particular piece of code is part of a test. The piece of code is represented as a IDeclaredElement.

Is it possible to get the filename and line number of a piece of code represented by a particular IDeclaredElement?

Following up to the response below:

@Evgeny, thanks for the answer, I wonder if you can clarify one point for me.

Suppose the user has this test open in visual studio: https://github.com/fschwiet/DreamNJasmine/blob/master/NJasmine.Tests/SampleTest.cs Suppose the user right clicks on line 48, the "player.Resume()" expression. Will the IDeclaredElement tell me specifically they want to run at line 48? Or is it going to give me a IDeclaredElement corresponding to the entire class, and a filename/line number range for the entire class?

I should play with this myself, but I appreciate tapping into what you already know.

2

There are 2 best solutions below

2
On BEST ANSWER

Yes.

The "IDeclaredElement" entity is the code symbol (class, method, variable, etc.). It could be loaded from assembly metadata, it could be declared in source code, it could come from source code implicitly.

You can use

var declarations = declaredElement.GetDeclarations() 

to get all AST elements which declares it (this could return multiple declarations for partial class, for example)

Then, for any IDeclaration, you can use

var documentRange = declaration.GetDocumentRange()
if (documentRange.IsValid())
  Console.WriteLine ("File: {0} Line:{1}",
 DocumentManager.GetInstance(declaration.GetSolution()).GetProjectFile(documentRange.Document).Name,
documentRange.Document.GetCoordsByOffset(documentRange.TextRange.StartOffset).Line
);

By the way, which test framework extension are you developing?

1
On

Will the IDeclaredElement tell me specifically they want to run at line 48?

Once more: IDeclaredElement has no positions in the file. Instead, it's declaration have them. For every declaration (IDeclaration is a regular AST node) there is range in document which covers it. In my previous example, I used TextRange.StartOffset, though you can use TextRange.EndOffset.

If you need more prcise position in the file, please traverse AST tree, and check the coordinates in the document for specific expression/statement