MCPcopy
hub / github.com/jamiebuilds/the-super-tiny-compiler / traverser

Function traverser

the-super-tiny-compiler.js:730–794  ·  view source on GitHub ↗
(ast, visitor)

Source from the content-addressed store, hash-verified

728// So we define a traverser function which accepts an AST and a
729// visitor. Inside we're going to define two functions...
730function traverser(ast, visitor) {
731
732 // A `traverseArray` function that will allow us to iterate over an array and
733 // call the next function that we will define: `traverseNode`.
734 function traverseArray(array, parent) {
735 array.forEach(child => {
736 traverseNode(child, parent);
737 });
738 }
739
740 // `traverseNode` will accept a `node` and its `parent` node. So that it can
741 // pass both to our visitor methods.
742 function traverseNode(node, parent) {
743
744 // We start by testing for the existence of a method on the visitor with a
745 // matching `type`.
746 let methods = visitor[node.type];
747
748 // If there is an `enter` method for this node type we'll call it with the
749 // `node` and its `parent`.
750 if (methods && methods.enter) {
751 methods.enter(node, parent);
752 }
753
754 // Next we are going to split things up by the current node type.
755 switch (node.type) {
756
757 // We'll start with our top level `Program`. Since Program nodes have a
758 // property named body that has an array of nodes, we will call
759 // `traverseArray` to traverse down into them.
760 //
761 // (Remember that `traverseArray` will in turn call `traverseNode` so we
762 // are causing the tree to be traversed recursively)
763 case 'Program':
764 traverseArray(node.body, node);
765 break;
766
767 // Next we do the same with `CallExpression` and traverse their `params`.
768 case 'CallExpression':
769 traverseArray(node.params, node);
770 break;
771
772 // In the cases of `NumberLiteral` and `StringLiteral` we don't have any
773 // child nodes to visit, so we'll just break.
774 case 'NumberLiteral':
775 case 'StringLiteral':
776 break;
777
778 // And again, if we haven't recognized the node type then we'll throw an
779 // error.
780 default:
781 throw new TypeError(node.type);
782 }
783
784 // If there is an `exit` method for this node type we'll call it with the
785 // `node` and its `parent`.
786 if (methods && methods.exit) {
787 methods.exit(node, parent);

Callers 1

transformerFunction · 0.85

Calls 1

traverseNodeFunction · 0.85

Tested by

no test coverage detected