用js实现js解释器
实现一个 JavaScript 解释器是一个复杂的任务,通常需要解析、编译和执行代码。以下是实现一个简化版解释器的核心思路和关键代码片段。
词法分析(Lexer)
将源代码拆分为令牌(tokens),识别关键字、标识符、运算符等。

function tokenize(code) {
const tokens = [];
const regex = /\s*(\b\w+\b|[\(\)\{\}\[\];,=+\-*/]|"[^"]*"|'[^']*'|\d+\.?\d*)\s*/g;
let match;
while ((match = regex.exec(code)) !== null) {
tokens.push(match[1]);
}
return tokens;
}
语法分析(Parser)
将令牌转换为抽象语法树(AST),定义语言结构。

function parse(tokens) {
let index = 0;
function walk() {
let token = tokens[index];
if (token === '{') {
const node = { type: 'BlockStatement', body: [] };
token = tokens[++index];
while (token !== '}') {
node.body.push(walk());
token = tokens[index];
}
index++;
return node;
}
if (/^[0-9]+$/.test(token)) {
index++;
return { type: 'NumericLiteral', value: Number(token) };
}
if (token === '(') {
index++;
const expression = walk();
if (tokens[index] !== ')') throw new Error('Missing closing parenthesis');
index++;
return expression;
}
throw new TypeError(`Unknown token: ${token}`);
}
return { type: 'Program', body: walk() };
}
执行器(Interpreter)
遍历 AST 并执行代码逻辑。
function interpret(ast) {
const environment = {};
function evaluate(node, env) {
switch (node.type) {
case 'Program':
return evaluate(node.body, env);
case 'BlockStatement':
let result;
node.body.forEach(statement => {
result = evaluate(statement, env);
});
return result;
case 'NumericLiteral':
return node.value;
default:
throw new TypeError(`Unknown node type: ${node.type}`);
}
}
return evaluate(ast, environment);
}
示例用法
将词法分析、语法分析和执行器串联起来:
const code = '{ 42 }';
const tokens = tokenize(code);
const ast = parse(tokens);
const result = interpret(ast);
console.log(result); // 输出: 42
扩展方向
- 支持变量声明:在环境中存储变量名和值。
- 支持函数调用:解析函数定义和调用逻辑。
- 错误处理:添加更详细的语法和运行时错误提示。
- 优化性能:引入字节码编译或 JIT 技术。






