Eclipse ASTNode to Source Code Line Number

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

+4
source share
3 answers

You can get the ASTNode line number using the code below

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

the compilation unit can be obtained using the code below

  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); 

You can visit the node (e.g. MethodDeclaration node) using the code below:

  compilationUnit.accept(new ASTVisitor() { public boolean visit(MethodDeclaration node) { int lineNumber = compilationUnit.getLineNumber(node.getStartPosition()) - 1; return true; } }); 
+15
source

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

+1
source

Besides the general solution that has already been described, there is one more that applies if you need an ASTNode line number, including leading spaces or potential comments written before the ASTNode. Then you can use:

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

See the API :

Returns the extended starting position of this node. Unlike ASTNode.getStartPosition () and ASTNode.getLength (), an extended range of sources can include comments and spaces immediately before or after the normal source range for a node.

+1
source

All Articles