views:

256

answers:

3

Given a line number of a particular class source code (Java/C#) - is there an easy way to get the name of the method it falls within? (If it falls within one) (Presumably using an Abstract Syntax Tree)

(This would be useful in limiting the output of checkstyle to just the method touched).

I'm assuming you'd have to use an Abstract Syntax Tree to do Line#->MethodName.

+1  A: 

I don't know about Java, but .NET assemblies don't have line numbers stored in their metadata tables - you would need a PDB (Program Database) file for that kind of information.

Andrew Hare
+2  A: 

(Java-specific)

If the class file was compiled with debug info then the line number table will contain a mapping of code<->line number. I don't think there's a built-in API for getting at this at runtime though I'm sure you can probably do with with some of the bytecode engineering libs out there such as ASM or BCEL.

StephMW
A: 

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

So the problem of determining the method name for a line number is pretty easy: find a node in the AST with corresponding line number, and climb the tree until an AST node is found that represents a method declaration; find the method-name subtree from that node and print it out.

This trick is heavily used in static analysis tools built using DMS, to report an offending method name for a problem diagnosed at a particular line number. DMS is designed to enable others to build such static analysis tools.

Ira Baxter