@casual-simulation/engine262

中文文档
0.0.1-4de2170374e22761996e46eb1362f4496ee57f8f发布于 2022/12/30MITTypeScriptCommonJS零依赖近 30 天下载 1.1万

Implementation of ECMA-262 in JavaScript

原始使用文档
文档目录6 节
  1. Changes from Mainline
  2. Why this exists
  3. Requirements
  4. Using engine262
  5. Testing engine262
  6. Related Projects

engine262

An implementation of ECMA-262 in JavaScript

Goals

  • 100% Spec Compliance
  • Introspection
  • Ease of modification

Non-Goals

  • Speed at the expense of any of the goals

This project is bound by a Code of Conduct.

Join us in #engine262:matrix.org.

Changes from Mainline

  • Additional generators have been added so that it is possible to step through the evaluation by simply calling .next() on the returned iterator.
    • It should be possible to step into most user code, including callbacks from standard library functions.
    • Scenarios that are mostly not supported are stepping into Proxy getters/setters from within standard library functions. For example, it is currently not possible to step into a Proxy getter when using a proxy as the thisValue for standard library functions.
    • The process for enabling stepping for such features is pretty simple: you look for situations where the unwind() function is used and replace it with yield*. The tricky part is that using yield* forces you to make the containing function to be a generator function, which means that callers of that function now also need to use yield* or unwind().

Why this exists

While helping develop new features for JavaScript, I've found that one of the most useful methods of finding what works and what doesn't is being able to actually run code using the new feature. Babel is fantastic for this, but sometimes features just can't be nicely represented with it. Similarly, implementing a feature in one of the engines is a large undertaking, involving long compile times and annoying bugs with the optimizing compilers.

engine262 is a tool to allow JavaScript developers to have a sandbox where new features can be quickly prototyped and explored. As an example, adding do expressions to this engine is as simple as the following diff:

--- a/src/evaluator.mjs
+++ b/src/evaluator.mjs
@@ -232,6 +232,8 @@ export function* Evaluate(node) {
     case 'GeneratorBody':
     case 'AsyncGeneratorBody':
       return yield* Evaluate_AnyFunctionBody(node);
+    case 'DoExpression':
+      return yield* Evaluate_Block(node.Block);
     default:
       throw new OutOfRange('Evaluate', node);
   }
--- a/src/parser/ExpressionParser.mjs
+++ b/src/parser/ExpressionParser.mjs
@@ -579,6 +579,12 @@ export class ExpressionParser extends FunctionParser {
         return this.parseRegularExpressionLiteral();
       case Token.LPAREN:
         return this.parseParenthesizedExpression();
+      case Token.DO: {
+        const node = this.startNode();
+        this.next();
+        node.Block = this.parseBlock();
+        return this.finishNode(node, 'DoExpression');
+      }
       default:
         return this.unexpected();
     }

This simplicity applies to many other proposals, such as optional chaining, pattern matching, the pipeline operator, and more. This engine has also been used to find bugs in ECMA-262 and test262, the test suite for conforming JavaScript implementations.

Requirements

To run engine262 itself, a engine with support for recent ECMAScript features is needed. Additionally, the CLI (bin/engine262.js) and test262 runner (test/test262/test262.js) require a recent version of Node.js.

Using engine262

Use it online: https://engine262.js.org

You can install the latest engine262 build from GitHub Packages.

If you install it globally, you can use the CLI like so:

$ engine262

Or, you can install it locally and use the API:

'use strict';

const {
  Agent,
  setSurroundingAgent,
  ManagedRealm,
  Value,

  CreateDataProperty,

  inspect,
} = require('engine262');

const agent = new Agent({
  // onDebugger() {},
  // ensureCanCompileStrings() {},
  // hasSourceTextAvailable() {},
  // onNodeEvaluation() {},
  // features: [],
});
setSurroundingAgent(agent);

const realm = new ManagedRealm({
  // promiseRejectionTracker() {},
  // resolveImportedModule() {},
  // getImportMetaProperties() {},
  // finalizeImportMeta() {},
  // randomSeed() {},
});

realm.scope(() => {
  // Add print function from host
  const print = new Value((args) => {
    console.log(...args.map((tmp) => inspect(tmp)));
    return Value.undefined;
  });
  CreateDataProperty(realm.GlobalObject, new Value('print'), print);
});

realm.evaluateScript(`
'use strict';

async function* numbers() {
  let i = 0;
  while (true) {
    const n = await Promise.resolve(i++);
    yield n;
  }
}

(async () => {
  for await (const item of numbers()) {
    print(item);
  }
})();
`);

// a stream of numbers fills your console. it fills you with determination.

Testing engine262

This project can be run against test262, which is particularly useful for developing new features and/or tests:

$ # build engine262
$ npm build

$ # update local test262 in test/test262/test262
$ git submodule update --init --recursive

$ # update local test262 to a pull request
$ pushd test/test262/test262
$ git fetch origin refs/pull/$PR_NUMBER/head && git checkout FETCH_HEAD
$ popd

$ # run specific tests
$ npm run test:test262 built-ins/AsyncGenerator*

$ # run all tests
$ npm run test:test262

The output will indicate counts for total tests, passing tests, failing tests, and skipped tests.

Many people and organizations have attempted to write a JavaScript interpreter in JavaScript much like engine262, with different goals. Some of them are included here for reference, though engine262 is not based on any of them.

版本与发布记录

@casual-simulation/engine262 共发布 43 个版本,首次发布于 2022/09/29;过去 12 个月发布了 0 个版本。

版本发布日期距今
0.0.1-4de2170374e22761996e46eb1362f4496ee57f8flatest2022/12/303 年前
0.0.1-6fadd673dfc837c2717737a2729a1baf022566a22022/10/244 年前
0.0.1-6d83cdbf886f5ed0ed77bb9f2b72d97589b4b8a72022/10/224 年前
0.0.1-04ffba3d522a4c88f20f7b91f85815516837f24f2022/10/204 年前
0.0.1-a09eb79588a3480149bb76a7409b4194724f81782022/10/154 年前
0.0.1-5f234b220e83c800746bf26f1fc1618bc1a9a4c12022/10/154 年前

关于 @casual-simulation/engine262 的常见问题

@casual-simulation/engine262 是什么?

Implementation of ECMA-262 in JavaScript

如何安装 @casual-simulation/engine262?

在项目目录运行 npm install @casual-simulation/engine262,或使用 pnpm add / yarn add / bun add。它还提供命令行工具 engine262,可以用 npx engine262 直接运行。

@casual-simulation/engine262 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@casual-simulation/engine262 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@casual-simulation/engine262 可以商用吗?

@casual-simulation/engine262 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@casual-simulation/engine262 的下载量有多少?

根据 npm 官方下载统计,@casual-simulation/engine262 在 2026/10/09 – 2026/11/07 这 30 天内被下载 11,430 次,日均约 381 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@casual-simulation/engine262 还在维护吗?

最新版本 0.0.1-4de2170374e22761996e46eb1362f4496ee57f8f 发布于 2022/12/30(3 年前);至今共发布 43 个版本,其中过去 12 个月发布了 0 个;首次发布于 2022/09/29。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。