Travesing UAST in a very controlled way

I am interested in traversing UAST in a very controlled way to build some representation of code, for example to build the sequence of API calls of a function.
There are two mehods: node.iterate(orderMode) or node.filter(XpathExpression) to iterate all children from the current node.

The difficulty with node.filter(…) is that some nodes could be visited more than only once. Consider the following statement in a java function: { return f(x);}
We traverse the AST from a uast:Block node. As explained in documentation, uast:Block is a sequence of expression. we can iterate over node selected with the following XPath request made of “or” expression:

it = node.filter("//java:ReturnStatement | //java:ExpressionStatement")

The f(x) statement will be is visited twice.

On the other hand, with node.iterate(…) function we have to test if children nodes are direct children of the current node to be able to control the traversal algorithm.

Is there any way to limit output of the Iterator to immediate children, or to test that a child node has the current node as parent?

Hi @mesnardo!

Both node.filter and node.iterate were made to allow more simple cases, e.g. when you need a specific set of nodes only.

If you want to process the whole UAST and build a different data structure from it, try node.get() instead (or ctx.root.get()). This will return you the whole UAST as a tree for Python arrays and dicts, which you can then use to traverse UAST in any specific way.

Let us know if you have any other questions :slight_smile: