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

Is there a way to print a node to string? #45

Closed
foresightyj opened this issue Aug 16, 2017 · 5 comments
Closed

Is there a way to print a node to string? #45

foresightyj opened this issue Aug 16, 2017 · 5 comments

Comments

@foresightyj
Copy link

foresightyj commented Aug 16, 2017

Is there a way to convert a node (e.g. MethodDeclaration) into a string, either pretty-print (aka, reformatting) or print the original code?

I didn't find such methods in javalang. I had experiences with Roslyn in .net and javaparse. Both support this functionality.

@ConflictGK
Copy link

If I understand correctly you need to retrieve the name of the method being declared. In that case check the attributes:

  1. node.name
  2. node.children

@foresightyj
Copy link
Author

No. I meant the entire code of a method in string. For example, javaparser even supports two types: one that pretty prints the code and one that preserves the original spaces.

@c2nes
Copy link
Owner

c2nes commented Aug 21, 2017

Unfortunately there is no (easy) way to do this at the moment. There are a couple related issues which would address this if someone was up to attempting them and submitting a PR, #37 and #14

@foresightyj
Copy link
Author

Thanks for the response :-)

@leviv
Copy link

leviv commented May 12, 2020

This is very old but this is the solution I came up with for my problem.

    def get_code_snippet (lines, index):
            openingBrackets = 0;
            closingBrackets = 0;

            # Resulting snippet
            snippet = ""

            # loop until we find the final closing bracket, or go over the limit
            while index < len(lines):
                line = lines[index]
                for letter in line:
                    if letter == '}':
                        closingBrackets += 1
                    elif letter == '{':
                        openingBrackets += 1

                    snippet += letter

                    # Early end if we have reached last bracket
                    if closingBrackets == openingBrackets and openingBrackets != 0:
                        return snippet
                    
                index += 1

            return snippet

I called the method in this way:

lines = code.split("\n")
for child in node.body:
    get_code_snippet (lines, child.position[0] - 1)

I hope it can help anyone who stumbles upon this!

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

4 participants