c2nes / javalang

Pure Python Java parser and tools
MIT License
737 stars 161 forks source link

Feature request: get number of lines in a block? #60

Open ayaankazerouni opened 5 years ago

ayaankazerouni commented 5 years ago

Apologies if this features exists already. Given some kind of code block (like a MethodDeclaration for example), I'd like to get the number of lines in that block. The AST gives me the start position (line, column) of the block, but not end position.

If this feature exists, I would appreciate pointers to it. If it doesn't I'm happy to discuss or contribute with a PR.

Thanks for your work on this project!

CirQ commented 4 years ago

Also looking for such feature, what's the progress?

ayaankazerouni commented 4 years ago

I didn't end up pursuing this. For this and a few other reasons (unrelated to javalang), I ended up using Java and the Eclipse JDT API to do what I needed.

jose commented 3 years ago

I've been using the following piece of code (previously suggested by @lyriccoder's in here) to find the line number of the last line of code in a ClassDeclaration, MethodDeclaration, etc.

def find_end_line_number(node):
    """Finds end line of a node."""
    max_line = node.position.line

    def traverse(node):
        for child in node.children:
            if isinstance(child, list) and (len(child) > 0):
                for item in child:
                    traverse(item)
            else:
                if hasattr(child, '_position'):
                    nonlocal max_line
                    if child._position.line > max_line:
                        max_line = child._position.line
                        return

    traverse(node)
    return max_line

You can then do something like node.position.line - max_line to compute the number of lines in a node.

Although this function seems to be working just fine, it returns the line number of the last line of code, not necessary the last line number of a node. One may expect the last line to be the line where } appears.

It would be great to have such feature out-of-box.