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

Getting Parent and Child Node #106

Closed
ffalpha opened this issue Aug 6, 2021 · 3 comments
Closed

Getting Parent and Child Node #106

ffalpha opened this issue Aug 6, 2021 · 3 comments
Labels

Comments

@ffalpha
Copy link

ffalpha commented Aug 6, 2021

Is it possible to get Parent and Child node while using walk method ? Like for example lets saye 3+4 ; So first pair would be ("Program","ExpressionStatement"). then ("ExpressionStatement","BinaryExpression") .It it possible to get something like that ? I tried but only got the nodes types

@emilos
Copy link
Contributor

emilos commented Aug 6, 2021

hey @ffalpha, here's an example:

const AbstractSyntaxTree = require('abstract-syntax-tree')
const tree = new AbstractSyntaxTree("3 + 4")
tree.walk((node, parent) => { console.log(node, parent) })

does this help?

@emilos emilos added the question label Aug 6, 2021
@ffalpha
Copy link
Author

ffalpha commented Aug 6, 2021

Hey @emilos .Thank you for the fast reply. Actually I have tried this. It works fine. I cant get the node type of the child. But the problem is it return the whole node for the parent.
tree.walk((node, parent) => { console.log(node.type, parent) })

When I try parent.type it gives me an error. Parent is just another node ? Right ?
tree.walk((node, parent) => { console.log(node.type, parent.type) })

@emilos
Copy link
Contributor

emilos commented Aug 8, 2021

@ffalpha some nodes might not have a parent (e.g. the Program node does not have one), so you might need to add checks like:

if (parent && parent.type === 'NodeType') {}

if (parent?.type) {}

Thanks!

@emilos emilos closed this as completed Aug 17, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants