半日くらいでコンパイラを作る実演をjsでやりたいです
半日くらいでコンパイラを作る実演をJavaScriptで行うためには、基本的な構成要素と流れを把握し、シンプルなターゲット言語を選ぶことが重要です。ここでは、非常に簡単な言語を作成し、JavaScriptにコンパイルする流れを示します。以下の手順に従って進めましょう。
1. 言語の定義
まず、非常にシンプルな言語(例えば、四則演算と変数代入のみ)を定義します。
// サンプル言語の例
a = 5;
b = a + 3;
c = a * b - 2;2. 字句解析器(Lexer)
ソースコードをトークンに分解します。
function lexer(input) {
const tokens = [];
const tokenTypes = [
{ regex: /^\d+/, type: 'NUMBER' },
{ regex: /^[a-zA-Z_]\w*/, type: 'IDENTIFIER' },
{ regex: /^[=+*-/]/, type: 'OPERATOR' },
{ regex: /^\s+/, type: 'WHITESPACE' }
];
while (input.length > 0) {
let matched = false;
for (const tokenType of tokenTypes) {
const match = tokenType.regex.exec(input);
if (match) {
if (tokenType.type !== 'WHITESPACE') {
tokens.push({ type: tokenType.type, value: match[0] });
}
input = input.slice(match[0].length);
matched = true;
break;
}
}
if (!matched) {
throw new Error(`Unexpected token: ${input[0]}`);
}
}
return tokens;
}
// テスト
const code = "a = 5;\nb = a + 3;\nc = a * b - 2;";
console.log(lexer(code));3. 構文解析器(Parser)
トークンを構文木(AST: Abstract Syntax Tree)に変換します。
function parser(tokens) {
let position = 0;
function walk() {
let token = tokens[position];
if (token.type === 'NUMBER') {
position++;
return { type: 'Literal', value: Number(token.value) };
}
if (token.type === 'IDENTIFIER') {
position++;
return { type: 'Identifier', name: token.value };
}
if (token.type === 'OPERATOR' && token.value === '=') {
position++;
return {
type: 'AssignmentExpression',
left: walk(),
operator: '=',
right: walk()
};
}
if (token.type === 'OPERATOR') {
const node = {
type: 'BinaryExpression',
left: walk(),
operator: token.value,
right: walk()
};
return node;
}
throw new Error(`Unexpected token: ${token.value}`);
}
const ast = [];
while (position < tokens.length) {
ast.push(walk());
}
return ast;
}
// テスト
const tokens = lexer(code);
const ast = parser(tokens);
console.log(JSON.stringify(ast, null, 2));4. コード生成(Code Generator)
ASTをJavaScriptのコードに変換します。
function codeGenerator(node) {
switch (node.type) {
case 'Literal':
return node.value;
case 'Identifier':
return node.name;
case 'AssignmentExpression':
return `${node.left.name} ${node.operator} ${codeGenerator(node.right)};`;
case 'BinaryExpression':
return `${codeGenerator(node.left)} ${node.operator} ${codeGenerator(node.right)}`;
default:
throw new TypeError(node.type);
}
}
function generateCode(ast) {
return ast.map(codeGenerator).join('\n');
}
// テスト
const generatedCode = generateCode(ast);
console.log(generatedCode);5. 実行
生成されたJavaScriptコードを実行します。
function execute(code) {
eval(code);
}
// テスト
execute(generatedCode);まとめ
これで、簡単なコンパイラが完成しました。上記の手順をまとめると、次のようになります。
字句解析:ソースコードをトークンに分解する
構文解析:トークンを構文木に変換する
コード生成:構文木をターゲット言語(JavaScript)のコードに変換する
実行:生成されたコードを実行する
これを応用して、より複雑な言語や機能を追加することができます。