-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path5-code-generator.js
42 lines (34 loc) · 1.01 KB
/
5-code-generator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// 5-code-generator.js
// 再帰的に自分自身を呼び出して各ノードを表示
// ツリーを1つの巨大な文字列にする。
export function codeGenerator(node) {
switch (node.type) {
case 'Program':
return node.body.map(codeGenerator)
.join('\n');
case 'ExpressionStatement':
return (
codeGenerator(node.expression) +
';'
);
case 'CallExpression':
return (
codeGenerator(node.callee) +
'(' +
node.arguments.map(codeGenerator)
.join(', ') +
')'
);
case 'Identifier':
return node.name;
// return node.name;で呼ばれたcodeGenerator(node.callee)にreturn
case 'NumberLiteral':
return node.value;
// return node.value;で呼ばれたnode.arguments.map(codeGenerator)にreturn
case 'StringLiteral':
return '"' + node.value + '"';
default:
alert('正しい構文を入力してください');
throw new TypeError(node.type);
}
}