Babel用“es2016”预设实现了尾调用优化

does Babel with the `es2016` preset implement tail call optimization?

本文关键字:实现 调用 优化 es2016 Babel      更新时间:2024-02-14

我使用以下示例测试了使用Babel和es2016预设的尾调用递归:

'use strict';
try {
    function r(n) {
        if (n%5000===0)
            console.log(`reached a depth of ${n}`);
        r(n+1);
    }
    r(0);
} catch (e) {
    if (!(e instanceof RangeError))
        throw e;
    else
        console.log('stack blown');
}

我的package.json文件是:

{
    "name": "tail-call-optimization",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "build": "babel es6 --out-dir es5 --source-maps",
        "watch": "babel es6 --out-dir es5 --source-maps --watch",
        "start": "node es5/app.js"
    },
    "author": "",
    "license": "ISC",
    "devDependencies": {
        "babel-cli": "^6.6.5",
        "babel-core": "^6.7.4",
        "babel-loader": "^6.2.4",
        "babel-polyfill": "^6.7.4",
        "babel-preset-es2016": "^6.0.10",
        "babel-runtime": "^6.6.1"
    },
    "dependencies": {
        "babel-polyfill": "^6.7.4",
        "source-map-support": "^0.4.0"
    }
}

并且CCD_ 3简单地为:

{
    "presets": ["es2016"]
}

使用运行以上操作

npm run build && npm run start

导致以下控制台输出:

reached a depth of 0
reached a depth of 5000
reached a depth of 10000
reached a depth of 15000
stack blown

事实上,查看es5目录中的已传输文件,没有任何迹象表明TCO已经实现。

我是不是错过了什么?

我的节点版本是4.3.2

查看:https://babeljs.io/docs/learn-es2015/其中一条写道:

暂时在Babel 6中删除

由于全局支持尾部调用的复杂性和性能影响,只支持显式自引用尾部递归。由于其他错误而删除,并将重新实现。

所以我想目前还没有实现。

目前没有一个"官方"Babel 6插件/预设实现TCO。babel-preset-es2016不是"官方"预设。除非TCO依赖于Babylon中的解析器支持(我想我不会这么认为,但我不确定),否则我认为userland插件/预置可以实现它,而且可能实现(但据我所知)。以下是跟踪最终"正式"重新实施的问题:T2614。如果有人想将该链接PR到Learn ES2015 docs@Marcus提到在这里ping我,我会合并它。