buxlabs / abstract-syntax-tree

A library for working with abstract syntax trees.
MIT License
110 stars 13 forks source link

Getting Parent and Child Node #106

Closed ffalpha closed 3 years ago

ffalpha commented 3 years ago

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 commented 3 years ago

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?

ffalpha commented 3 years ago

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 commented 3 years ago

@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!