* Now let's move onto our last phase: The Code Generator. * * Our code generator is going to recursively call itself to print each node in * the tree into one giant string.
(node)
| 946 | */ |
| 947 | |
| 948 | function codeGenerator(node) { |
| 949 | |
| 950 | // We'll break things down by the `type` of the `node`. |
| 951 | switch (node.type) { |
| 952 | |
| 953 | // If we have a `Program` node. We will map through each node in the `body` |
| 954 | // and run them through the code generator and join them with a newline. |
| 955 | case 'Program': |
| 956 | return node.body.map(codeGenerator) |
| 957 | .join('\n'); |
| 958 | |
| 959 | // For `ExpressionStatement` we'll call the code generator on the nested |
| 960 | // expression and we'll add a semicolon... |
| 961 | case 'ExpressionStatement': |
| 962 | return ( |
| 963 | codeGenerator(node.expression) + |
| 964 | ';' // << (...because we like to code the *correct* way) |
| 965 | ); |
| 966 | |
| 967 | // For `CallExpression` we will print the `callee`, add an open |
| 968 | // parenthesis, we'll map through each node in the `arguments` array and run |
| 969 | // them through the code generator, joining them with a comma, and then |
| 970 | // we'll add a closing parenthesis. |
| 971 | case 'CallExpression': |
| 972 | return ( |
| 973 | codeGenerator(node.callee) + |
| 974 | '(' + |
| 975 | node.arguments.map(codeGenerator) |
| 976 | .join(', ') + |
| 977 | ')' |
| 978 | ); |
| 979 | |
| 980 | // For `Identifier` we'll just return the `node`'s name. |
| 981 | case 'Identifier': |
| 982 | return node.name; |
| 983 | |
| 984 | // For `NumberLiteral` we'll just return the `node`'s value. |
| 985 | case 'NumberLiteral': |
| 986 | return node.value; |
| 987 | |
| 988 | // For `StringLiteral` we'll add quotations around the `node`'s value. |
| 989 | case 'StringLiteral': |
| 990 | return '"' + node.value + '"'; |
| 991 | |
| 992 | // And if we haven't recognized the node, we'll throw an error. |
| 993 | default: |
| 994 | throw new TypeError(node.type); |
| 995 | } |
| 996 | } |
| 997 | |
| 998 | /** |
| 999 | * ============================================================================ |