javalang icon indicating copy to clipboard operation
javalang copied to clipboard

how to traverse all AST node?

Open jackie1116 opened this issue 5 years ago • 2 comments

dear all ! how to traverse all AST node? thank you very much!

jackie1116 avatar Aug 23 '19 05:08 jackie1116

Each node has attribute children (it's a list). An element of that list is a list or Node. In general you can traverse smth like this:

tree = javalang.parse.parse(open('file.java').read())
for path, node in tree:
    for child in node.children:
        if isinstance(child, list):
            #recusively do it
                for c in child.children:
                      if isinstance(child, list):
                         ....

lyriccoder avatar Jul 07 '20 09:07 lyriccoder

Each node has attribute children (it's a list). An element of that list is a list or Node. In general you can traverse smth like this:

tree = javalang.parse.parse(open('file.java').read())
for path, node in tree:
    for child in node.children:
        if isinstance(child, list):
            #recusively do it
                for c in child.children:
                      if isinstance(child, list):
                         ....

hello,I find that there are some Node'children are not list, like this:

ReturnStatement(expression=MethodInvocation(arguments=[MemberReference(member=date, postfix_operators=[], prefix_operators=[], qualifier=, selectors=[])], member=parse, postfix_operators=[], prefix_operators=[], qualifier=format, selectors=[], type_arguments=None), label=None)

Node ReturnStatement's child is MethodInvocation, it's in 'expression=MethodInvocation', can you tell me how to solve it?

lhj0402 avatar Feb 24 '21 11:02 lhj0402