Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

eclipse ASTNode to source code line number

Given an ASTNode in eclipse, is there any way to get the corresponding source code line number?

like image 942
bray Avatar asked Jun 20 '12 19:06

bray


3 Answers

You can get the line number of an ASTNode using the below code

    int lineNumber = compilationUnit.getLineNumber(node.getStartPosition()) - 1;

the compilation unit can be obtained from the ASTParser using the below code

    ASTParser parser = ASTParser.newParser(AST.JLS3);

    // Parse the class as a compilation unit.
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setSource(source); // give your java source here as char array
    parser.setResolveBindings(true);

    // Return the compiled class as a compilation unit
    CompilationUnit compilationUnit = parser.createAST(null);

Then you can use the ASTVisitor pattern to visit the type of required node (say MethodDeclaration node) using the below code:

    compilationUnit.accept(new ASTVisitor() {

        public boolean visit(MethodDeclaration node) {       
            int lineNumber = compilationUnit.getLineNumber(node.getStartPosition()) - 1;
            return true;
        }
    });
like image 186
Unni Kris Avatar answered Oct 27 '22 11:10

Unni Kris


ASTNode has getStartPosition() and getLength() methods which deal with character offsets. To convert from a character offset to a line number you should use CompilationUnit's getLineNumber() method. CompilationUnit is the root of your AST tree.

like image 41
Konstantin Komissarchik Avatar answered Oct 27 '22 10:10

Konstantin Komissarchik


Apart from the general solution that has already been described, there is another one that applies if you need the line number of an ASTNode including leading whitespaces or potential comments written in front of the ASTNode. Then you can use:

int lineNumber = compilationUnit.getLineNumber(compilationUnit.getExtendedStartPosition(astNode))

See the API:

Returns the extended start position of the given node. Unlike ASTNode.getStartPosition() and ASTNode.getLength(), the extended source range may include comments and whitespace immediately before or after the normal source range for the node.

like image 38
MH. Avatar answered Oct 27 '22 10:10

MH.