views:

127

answers:

2

hi,

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

+2  A: 

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.

nanda
how am i supposed to know the method's position?
Steven
position is relative to the CompilationUnit.
nanda
i need actual line number in source file
Steven
position (the parameter) is relative to the CompilationUnit, but the result (return value) is absolute to the file.
nanda
oh ok....i get it thanks
Steven
if so... then maybe can you change the accepted answer?
nanda
Didn't see your answer at the time. +1
VonC
+2  A: 

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)
VonC
are you sure its getoccurencecount to get position?
Steven