I’ve been playing for quite a while now with ASTs and was trying to get the line and column information associated to a given node parsed on this plugin from eclipse. According to the documented api here I found that the method getStartPosition() can give me the position on the characters of the file that was parsed, but this is not what I wanted.
I went on the CompilationUnit class api documentation to find out the methods getLineNumber(int position) and getColumnNumber(int position) which from my understanding can do the trick. the position paramater is nothing less than what the getStartPosition() method returns, by doing node.getStartPosition().
Now, the problem is the two methods that get line and column on source file doesn’t seems to be available for all nodes. For instance, the method declaration nodes don’t have them!
How can I get such information on all the tree? I know this is not impossible since I was able to use parsers for other languages that for every ast node had a line and column associated with it. In fact, I believe javaparser is one of them for java, since the class contains attributes for line and column hardcoded. Seeing Eclipse JDT seemed to me much more robust to me and being there for quite a while, I would be surprised that such information would not be possible to acquire.
Edit: Again, the problem is obtaining the line number from things different of the compilation unit that only appears on the root:
<type 'org.eclipse.jdt.core.dom.CompilationUnit'>
1
<type 'org.eclipse.jdt.core.dom.TypeDeclaration'>
<type 'org.eclipse.jdt.core.dom.Javadoc'>
<type 'org.eclipse.jdt.core.dom.TagElement'>
<type 'org.eclipse.jdt.core.dom.TextElement'>
<type 'org.eclipse.jdt.core.dom.TextElement'>
<type 'org.eclipse.jdt.core.dom.TextElement'>
<type 'org.eclipse.jdt.core.dom.TextElement'>
<type 'org.eclipse.jdt.core.dom.TextElement'>
<type 'org.eclipse.jdt.core.dom.TextElement'>
Thank you.
For posterity, I’m reposting the answer I posted on the jdt-core-dev mailing list. (My answer is not very different from Ryan’s suggestion above)
Hi Carlos,
You’re correct about the CompilationUnit.getLineNumber(int) method. You use it as follows:
int lineNumber = compilationUnit.getLineNumber(node.getStartPosition()) - 1;However, I don’t understand where you’re stuck. Why do you need the getLineNumber(..) defined for MethodDeclaration? All you have to do is to find the method declaration node, then find out the corresponding CompilationUnit for it using the code below, and then use the above line of code to find the line number. Am I missing something here?
Cheers!
Ayush