Reputation: 1107
I am using JavaParser for a code analysis project, where I read a Java source-file and generate an AST (abstract-syntax-tree) for analysis. I need to determine the original number of lines spanned by a given block-statement from an AST.
Essentially I have a method like this:
int numberOfLines(Node astNode){
....
}
And I need to return the number of lines spanned. Example:
void something()
{
// hello world
}
Would return 5.
I have tried converting to a string and counting the lines, like this: new BufferedReader(new StringReader(nodeHere.toString())).lines().count()
, but this does not work due to lack of lexical preservation... for example a single line likes this: "class TestClass {int x; int y; int zz(int a){return a;} }" becomes 10 lines:
class TestClass {
int x;
int y;
int zz(int a) {
return a;
}
}
When an AST is generated, then converted back to string, in essense "beautifying" it... However, JavaParser does preserve original "coordinates" in the range property, so maybe that could be used somehow?
Thanks
Upvotes: 0
Views: 961
Reputation: 115
This answer is probably pretty late but this works for me...
public void visit(MethodDeclaration method) {
int methodBodyLength = method.getRange().map(range -> range.begin.line - range.end.line).orElse(0);
}
Upvotes: 1
Reputation: 2167
There are range and tokenRange properties which you may use. i.e. something like range.end.line - range.begin.line
Upvotes: 1