Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
ayaankazerouni opened this issue Nov 12, 2018 · 3 comments
Open

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

ayaankazerouni opened this issue Nov 12, 2018 · 3 comments

Comments

@ayaankazerouni
Copy link

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
Copy link

CirQ commented Mar 13, 2020

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

@ayaankazerouni
Copy link
Author

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
Copy link

jose commented Feb 25, 2021

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants