Last active
June 10, 2022 13:52
-
-
Save Framartin/7eb0266f05011b184701d9b2de5c03bb to your computer and use it in GitHub Desktop.
Generator to browse all the nodes of an Esprima Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def node_generator(node): | |
""" | |
Generator that takes an Esprima object (or a Esprima node) from the esprima | |
module converted as a dict, and outputs all child nodes at any level of the | |
tree. It's useful to browse the entire tree. | |
Subnodes are generated by browsing all the keys. It's not the most | |
optimized way to browse the tree, because some keys will never contains | |
child nodes. But it's very simple, and you're sure to not miss any subnodes. | |
""" | |
if node: # not empty dict or list | |
# node is a dict | |
if isinstance(node, dict): | |
yield node | |
for key in node: | |
yield from node_generator(node[key]) | |
# node is a list | |
elif isinstance(node, list): | |
for subnode in node: | |
yield from node_generator(subnode) | |
# demo | |
import esprima, pprint | |
pp = pprint.PrettyPrinter() | |
program = 'const answer = 42' | |
esprimaTree = esprima.parseScript(program).toDict() | |
for node in node_generator(esprimaTree): | |
pp.pprint(node) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Update: handle the case of empty dict or list.