Method name from line number

Given the line number of the particular class source code (Java / C #) - is there an easy way to get the name of the method it is in? (If it falls into one) (Presumably using an abstract syntax tree)

(It would be useful to limit the output of the control style only to the indirect method).

I assume that you will have to use the abstract syntax tree to create the line # -> Method Name.

+4
source share
3 answers

(Java specific)

If the class file was compiled with debugging information, then the line number table will contain a display of the line number of the code ↔. I don’t think there is a built-in API to get this at runtime, although I’m sure that you can probably do with some of the bytecode based libraries like ASM or BCEL.

+2
source

I don't know about Java, but in .NET assemblies there are no line numbers stored in their metadata tables. To do this, you need a PDB (Program Database) file.

+2
source

Yes, as you said, using the right type of AST. DMS Software Reengineering Toolkit can create AST for Java and C #. Each AST node is decorated with line number data. Each AST node corresponds to a grammar rule.

Thus, the problem of determining the method name for the line number is quite simple: look in the AST with the corresponding line number and raise the tree until an AST node is found, which is a method declaration; find the subtree of the method name from this node and print it.

This trick is largely used in static analysis tools built using DMS to report an incorrect method name for a problem with a specific line number. DMS - designed to allow others to create such static analysis tools.

0
source

Source: https://habr.com/ru/post/1286565/


All Articles