Steven
Steven

Reputation: 4022

Traversing through the AST node

i want to find out the line number where a call is referenced using AST api in a package. How can i do that?

Upvotes: 3

Views: 1900

Answers (2)

VonC
VonC

Reputation: 1324073

You have an illustration on how to search within the method of a CompilationUnit in this papercut article:

for (ICompilationUnit unit : mypackage.getCompilationUnits()) {
IType[] types = unit.getTypes();
for (int i = 0; i < types.length; i++) {
  IType type = types[i];
  IMethod[] methods = type.getMethods();
  • If the method is an ASTNode, you can use the ASTNode.getStartPosition() function.
  • If the compilation unit of that IMember is a CompilationUnit, you can use that in the CompilationUnit.getLineNumber(position)

Upvotes: 2

nanda
nanda

Reputation: 24788

CompilationUnit.getLineNumber(int position)

position is relative to the CompilationUnit object

Documentation:

Returns the line number corresponding to the given source character position in the original source string. The initial line of the compilation unit is numbered 1, and each line extends through the last character of the end-of-line delimiter. The very last line extends through the end of the source string and has no line delimiter. For example, the source string class A\n{\n} has 3 lines corresponding to inclusive character ranges [0,7], [8,9], and [10,10]. Returns -1 for a character position that does not correspond to any source line, or -2 if no line number information is available for this compilation unit.

Upvotes: 2

Related Questions