I want to find call expressions that doesn't have any parent in this script:
1 + 1
function parent() {
2 + 2
}
3 + 3
Here I want to get 1 + 1
and 3 + 3
nodes but not 2 + 2
.
What I'd like to achieve would be something like:
j(file.source).find(j.ExpressionStatement, {
parent: null
});
So is there a filter that allow to find if an expression has a parent ?
The loc attribute of an AST node has an indentation attribute. If the indentation is 0
when can assume that is a top level expression:
j(file.source).find(j.ExpressionStatement, {
loc: {indent: 0}
});
This is really not robust since it depends on indentation.
Since I couldn't find a safe way to filter over the attributes. We can also use jscodeshift's .filter()
to get the parent node. If it is the program, then we're sure to be top-level:
j(file.source).find(j.ExpressionStatement)
.filter(path => j.Program.check(path.parent.value));