Compare commits

...

46 Commits

Author SHA1 Message Date
Sebastian McKenzie
8c7ef0a2c9 v5.0.2 2015-04-03 06:53:46 +11:00
Sebastian McKenzie
8f79010b16 add regression test for #1130 2015-04-03 06:52:23 +11:00
Sebastian McKenzie
022e6f26aa fix not being able to call non-writable methods - fixes #1133 2015-04-03 06:52:17 +11:00
Sebastian McKenzie
138fa6c9f8 add 5.0.1 changelog 2015-04-03 06:52:02 +11:00
Sebastian McKenzie
c07704cc80 remove parentPath existence check 2015-04-03 06:48:46 +11:00
Sebastian McKenzie
bf811ea34a 5.0.1 2015-04-03 06:47:47 +11:00
Sebastian McKenzie
8af3ea1c43 fix duplicate declaration regression - fixes #1130 2015-04-03 06:47:41 +11:00
Sebastian McKenzie
5fbe147a5e v5.0.1 2015-04-03 05:49:16 +11:00
Sebastian McKenzie
a9e214b1db fix build cli script 2015-04-03 05:48:02 +11:00
Sebastian McKenzie
6812fca7a9 v5.0.0 2015-04-03 05:36:47 +11:00
Sebastian McKenzie
ebc42f5ce0 add setInterval and setTimeout noop to browserify test pending a new core-js patch release 2015-04-03 04:53:13 +11:00
Sebastian McKenzie
b12a97ddd6 rename returnUsedHelpers to metadataUsedHelpers 2015-04-03 04:50:19 +11:00
Sebastian McKenzie
e8daad38a7 remove beta tag from npm publish 2015-04-03 04:39:45 +11:00
Sebastian McKenzie
c6c0bc07e2 fix empty whitelist in build-external-helpers - fixes #1129 2015-04-03 04:39:39 +11:00
Sebastian McKenzie
c60f3f0e34 fix runtime transformer and update tests 2015-04-03 02:56:32 +11:00
Sebastian McKenzie
07078138f3 update to core-js 0.8.0 2015-04-03 02:37:02 +11:00
Sebastian McKenzie
cb0026edfe fix plugin api 2015-04-03 01:53:25 +11:00
Sebastian McKenzie
ab55ec4ea2 fix afterPlugins variable 2015-04-03 00:33:54 +11:00
Sebastian McKenzie
e164123ce9 remove packages README 2015-04-03 00:33:48 +11:00
Sebastian McKenzie
f42bacf4f6 fix syntax error in File 2015-04-03 00:02:13 +11:00
Sebastian McKenzie
46adb07d41 add plugin api - closes #987 2015-04-02 23:49:24 +11:00
Sebastian McKenzie
e10bdf7c5b add try-catch to util.resolveRelative 2015-04-02 23:44:29 +11:00
Sebastian McKenzie
83eea2acc7 add babel-cli init to bootstrap 2015-04-02 23:34:28 +11:00
Sebastian McKenzie
8bdd4cc559 fix babel-external-helpers path in Makefile 2015-04-02 23:16:01 +11:00
Sebastian McKenzie
15d31b5608 move babel cli into separate folder #1097 2015-04-02 23:12:05 +11:00
Sebastian McKenzie
9ed6a7b650 simplify dynamic imports 2015-04-02 22:03:57 +11:00
Sebastian McKenzie
01a2aa7dd1 support multiple export specifier remapping 2015-04-02 20:25:05 +11:00
Sebastian McKenzie
33fde5f143 update 5.0.0 changelog 2015-04-02 20:09:29 +11:00
Sebastian McKenzie
682c775a97 fix babel-node require test to reflect import hoisting 2015-04-02 19:34:21 +11:00
Sebastian McKenzie
4846b89931 export options in browser api 2015-04-02 19:28:18 +11:00
Sebastian McKenzie
25312396a5 add live binding support to modules - fixes #1117, fixes #1057, closes #1118 2015-04-02 19:28:11 +11:00
Sebastian McKenzie
cfff7aa6fb simplfy function name inference wrapper - closes #1002 2015-04-02 02:37:00 +11:00
Sebastian McKenzie
f88a4147a6 traceur upstream sync 2015-04-02 02:21:12 +11:00
Sebastian McKenzie
3c343adf33 add support for super update and assignment expressions - fixes #426 2015-04-02 02:21:04 +11:00
Sebastian McKenzie
269587cde5 hoist block iife to avoid creating a new one for each loop iteration 2015-04-02 00:58:01 +11:00
Sebastian McKenzie
121ba8c381 fix loop block scoping, check for exact reference when doing closure detection - fixes #973 2015-04-02 00:04:10 +11:00
Sebastian McKenzie
563a427b69 add ludicrous transformer 2015-04-01 23:23:09 +11:00
Sebastian McKenzie
658164a0d2 fix booleanString compact option 2015-04-01 23:21:32 +11:00
Sebastian McKenzie
135ba84abb fix es7 export extensions compound list 2015-04-01 23:21:16 +11:00
Sebastian McKenzie
76573093bd add umd globals export - fixes #375 2015-04-01 23:02:03 +11:00
Sebastian McKenzie
22b88487ee remove use strict directive from react test 2015-04-01 14:12:11 +11:00
Sebastian McKenzie
3686951dc1 5.0.0-beta4 2015-04-01 14:07:41 +11:00
Sebastian McKenzie
f43ca32ff5 move es6 tail call test 2015-04-01 14:07:32 +11:00
Sebastian McKenzie
424a59a856 dont coerce jsx expression containers - fixes #1126 2015-04-01 14:07:26 +11:00
Sebastian McKenzie
5f159853d5 fix paramless async calls 2015-04-01 13:57:59 +11:00
Sebastian McKenzie
f9c56c6dd7 properly export acorn 2015-04-01 13:51:15 +11:00
188 changed files with 1685 additions and 824 deletions

6
.gitignore vendored
View File

@@ -11,8 +11,6 @@ test/core/tmp
coverage
dist
.package.json
packages/babel-runtime/es5/helpers/*.js
packages/babel-runtime/es5/regenerator/*.js
packages/babel-runtime/es3/helpers/*.js
packages/babel-runtime/es3/regenerator/*.js
packages/babel-runtime/helpers/*.js
packages/babel-runtime/regenerator/*.js
lib

View File

@@ -13,15 +13,55 @@ _Note: Gaps between patch versions are faulty/broken releases._
See [CHANGELOG - 6to5](CHANGELOG-6to5.md) for the pre-4.0.0 version changelog.
## 5.0.1
* **Bug Fix**
* Fix duplicate declaration regression.
* Fix not being able to call non-writable methods.
## 5.0.0
* **New Feature**
* Decorators based on [@wycat's](https://github.com/wycats) [stage 1 proposal](https://github.com/wycats/javascript-decorators).
* Class property initializers based on [@jeffmo's](https://github.com/jeffmo) [stage 0 proposal](https://gist.github.com/jeffmo/054df782c05639da2adb).
* Export extensions based on [@leebyron's](https://github.com/leebyron) [stage 1 proposal](https://github.com/leebyron/ecmascript-more-export-from).
* UMD module formatter now supports globals.
* Add `es3.runtime`, `optimisation.react.inlineElements` and `optimisation.react.constantElements` transformers.
* Add stage option that replaces the experimental one.
* Allow ES7 transformer to be enabled via `optional` instead of only via `stage`.
* Infer string quotes to use in the code generator.
* Consider `export { foo as default };` to be the same as `export default foo;`.
* Add `nonStandard` option that can be set to `false` to remove parser support for JSX and Flow.
* Add `jsxPragma` option.
* Automatically generate CLI options based on internal API options.
* Add support for `.babelrc` on absolute paths.
* Plugin API!
* **Internal**
* Export `options` in browser API.
* Rewritten parser.
* Don't block hoist when runtime transformer is enabled in system module formatter.
* Rewritten the internal traversal and node replacement API to use "paths" that abstracts out node relationships.
* **Polish**
* JSX output is now more inline with the official JSX transformer.
* Hoist block scoping IIFE - this improves memory usage and performance.
* Better IIFE detection - references are now checked to see if they're referencing the binding we're searching for.
* Check for import reassignments in constants transformer.
* Make method definitions with expression bodies illegal.
* Save register cache on tick instead of `SIGINT`.
* Enable strict mode on babel-node eval flag.
* **Bug Fixes**
* Add support for live bindings. This change also increases the reliablity of export specifier renaming.
* Add support for super update and non equals assignment expressions.
* Rename shadow constructor binding in classes.
* Seed next iteration bindings with previous fresh bindings when reassinging loop block scoped variables.
* Fix new expression spread referencing the wrong constructor.
* Call `resolveModuleSource` on dynamic imports.
* Added `param` to list of duplicate declaration kinds.
* **Breaking Changes**
* The Babel playground has been removed.
* ES7 Abstract References have been removed.
* Experimental option has been removed in favor of a stage option.
* Rename `returnUsedHelpers` to `metadataUsedHelpers`.
## 4.7.16

View File

@@ -20,7 +20,7 @@ Then you need to run:
$ make watch-core
```
This will compile babel and then sit in the background and on file modification
This will compile Babel and then sit in the background and on file modification
recompile the necessary files.
#### Running tests
@@ -31,8 +31,6 @@ You can run tests via:
$ make test
```
This will usually take around two minutes as it's compiling the entire
[test262](https://github.com/tc39/test262) test suite and validating its AST.
This is mostly overkill and you can limit the tests to a select few by directly
running them with `mocha`:

View File

@@ -32,7 +32,7 @@ build:
node $(BROWSERIFY_CMD) lib/babel/api/browser.js -s babel >dist/babel.js
node $(UGLIFY_CMD) dist/babel.js >dist/babel.min.js
node bin/babel-external-helpers >dist/external-helpers.js
node packages/babel-cli/bin/babel-external-helpers >dist/external-helpers.js
node $(UGLIFY_CMD) dist/external-helpers.js >dist/external-helpers.min.js
rm -rf templates.json
@@ -87,11 +87,11 @@ publish:
node tools/cache-templates
test -f templates.json
npm publish --tag beta
npm publish
git push --follow-tags
make publish-core
make publish-cli
make publish-runtime
rm -rf templates.json browser.js browser-polyfill.js external-helpers.js
@@ -100,20 +100,18 @@ publish-runtime:
cd packages; \
node build-runtime.js; \
cd babel-runtime; \
npm publish --tag beta
npm publish
publish-core:
tools/generate-core-package-json >package2.json
mv package.json .package.json
mv package2.json package.json
npm publish --tag beta
rm -rf package.json
mv .package.json package.json
publish-cli:
cd packages; \
node build-cli.js; \
cd babel-cli; \
npm publish
bootstrap:
npm install
npm link
cd packages/babel-cli && npm install && npm link
git submodule update --init
cd vendor/regenerator && npm install
cd vendor/compat-table && npm install object-assign

View File

@@ -1,20 +1,14 @@
{
"name": "babel",
"name": "babel-core",
"description": "Turn ES6 code into readable vanilla ES5 with source maps",
"version": "5.0.0-beta4",
"version": "5.0.2",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/",
"repository": "babel/babel",
"preferGlobal": true,
"main": "lib/babel/api/node.js",
"browser": {
"./lib/babel/api/register/node.js": "./lib/babel/api/register/browser.js"
},
"bin": {
"babel": "./bin/babel/index.js",
"babel-node": "./bin/babel-node",
"babel-external-helpers": "./bin/babel-external-helpers"
},
"keywords": [
"harmony",
"classes",
@@ -35,10 +29,8 @@
"dependencies": {
"ast-types": "~0.7.0",
"chalk": "^1.0.0",
"chokidar": "^0.12.6",
"commander": "^2.6.0",
"convert-source-map": "^0.5.0",
"core-js": "^0.6.0",
"core-js": "^0.8.0",
"debug": "^2.1.1",
"detect-indent": "^3.0.0",
"estraverse": "^1.9.1",

View File

@@ -1,6 +0,0 @@
# What is this?
This is a folder containing additional packages that are built whenever
a new version of babel is released.
**TODO:** Move `babel-core` into here.

View File

@@ -3,10 +3,10 @@
var pathIsAbsolute = require("path-is-absolute");
var commander = require("commander");
var Module = require("module");
var babel = require("../lib/babel/api/node");
var babel = require("babel-core");
var path = require("path");
var repl = require("repl");
var util = require("../lib/babel/util");
var util = require("babel-core").util;
var vm = require("vm");
var _ = require("lodash");

View File

@@ -1,8 +1,8 @@
#!/usr/bin/env node
var commander = require("commander");
var util = require("../lib/babel/util");
var runtime = require("../lib/babel/tools/build-external-helpers");
var util = require("babel-core").util;
var runtime = require("babel-core").buildExternalHelpers;
commander.option("-l, --whitelist [whitelist]", "Whitelist of helpers to ONLY include", util.list);
commander.option("-t, --output-type [type]", "Type of output (global|umd|var)", "global");

View File

@@ -1,15 +1,15 @@
#!/usr/bin/env node
var commander = require("commander");
var transform = require("../../lib/babel/transformation");
var transform = require("babel-core").transform;
var kebabCase = require("lodash/string/kebabCase");
var File = require("../../lib/babel/transformation/file");
var util = require("../../lib/babel/util");
var options = require("babel-core").options;
var util = require("babel-core").util;
var each = require("lodash/collection/each");
var keys = require("lodash/object/keys");
var fs = require("fs");
each(File.options, function (option, key) {
each(options, function (option, key) {
if (option.hidden) return;
var arg = kebabCase(key);
@@ -104,7 +104,7 @@ if (errors.length) {
exports.opts = {};
each(File.options, function (opt, key) {
each(options, function (opt, key) {
exports.opts[key] = commander[key];
});

View File

@@ -1,7 +1,7 @@
var readdir = require("fs-readdir-recursive");
var index = require("./index");
var babel = require("../../lib/babel/api/node");
var util = require("../../lib/babel/util");
var babel = require("babel-core");
var util = require("babel-core").util;
var path = require("path");
var fs = require("fs");
var _ = require("lodash");

View File

@@ -0,0 +1 @@
module.exports = require("babel-core");

View File

@@ -0,0 +1,25 @@
{
"name": "babel",
"description": "Turn ES6 code into readable vanilla ES5 with source maps",
"version": "5.0.1",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/",
"repository": "babel/babel",
"preferGlobal": true,
"dependencies": {
"chokidar": "^0.12.6",
"babel-core": "^5.0.1",
"commander": "^2.6.0",
"fs-readdir-recursive": "^0.1.0",
"output-file-sync": "^1.1.0",
"lodash": "^3.2.0",
"convert-source-map": "^0.5.0",
"source-map": "^0.4.0",
"path-is-absolute": "^1.0.0"
},
"bin": {
"babel": "./bin/babel/index.js",
"babel-node": "./bin/babel-node",
"babel-external-helpers": "./bin/babel-external-helpers"
}
}

View File

@@ -0,0 +1 @@
module.exports = require("babel-core/polyfill");

View File

@@ -0,0 +1 @@
module.exports = require("babel-core/register");

View File

@@ -1,4 +0,0 @@
module.exports = {
"default": require("core-js/client/library"),
__esModule: true
};

View File

@@ -1,10 +1,10 @@
{
"name": "babel-runtime",
"description": "babel selfContained runtime",
"version": "5.0.0-beta3",
"version": "5.0.1",
"repository": "babel/babel",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"dependencies": {
"core-js": "^0.6.0"
"core-js": "^0.8.0"
}
}
}

11
packages/build-cli.js Normal file
View File

@@ -0,0 +1,11 @@
var outputFile = require("output-file-sync");
var pkgLoc = __dirname + "/babel-cli/package.json";
var pkg = require(pkgLoc);
var mainPkg = require("../package.json");
pkg.version = mainPkg.version;
pkg.dependencies["babel-core"] = "^" + mainPkg.version;
outputFile(pkgLoc, JSON.stringify(pkg, null, 2));

View File

@@ -39,39 +39,34 @@ function writeRootFile(filename, content) {
outputFile(filename, content);
}
function doVersion(version) {
var transformer = version + ".runtime";
function writeFile(filename, content) {
return writeRootFile(version + "/" + filename, content);
}
function selfContainify(code) {
return transform(code, {
optional: [transformer]
}).code;
}
function buildHelper(helperName) {
var tree = t.program(
util.template("self-contained-helpers-head", {
HELPER: util.template("helper-" + helperName)
})
);
return transform.fromAst(tree, null, {
optional: [transformer]
}).code;
}
each(File.helpers, function (helperName) {
writeFile("helpers/" + helperName + ".js", buildHelper(helperName));
});
writeFile("regenerator/index.js", readFile("regenerator-babel/runtime-module", true));
writeFile("regenerator/runtime.js", selfContainify(readFile("regenerator-babel/runtime")));
function writeFile(filename, content) {
return writeRootFile(filename, content);
}
doVersion("es3");
doVersion("es5");
function selfContainify(code) {
return transform(code, {
optional: ["runtime"]
}).code;
}
function buildHelper(helperName) {
var tree = t.program(
util.template("self-contained-helpers-head", {
HELPER: util.template("helper-" + helperName)
})
);
return transform.fromAst(tree, null, {
optional: ["runtime"]
}).code;
}
each(File.helpers, function (helperName) {
writeFile("helpers/" + helperName + ".js", buildHelper(helperName));
});
writeFile("regenerator/index.js", readFile("regenerator-babel/runtime-module", true));
writeFile("regenerator/runtime.js", selfContainify(readFile("regenerator-babel/runtime")));
updatePackage();

View File

@@ -272,11 +272,13 @@ pp.parseExprAtom = function(refShorthandDefaultPos) {
// arrow functions
if (this.type === tt.parenL) {
let expr = this.parseParenAndDistinguishExpression(start, true)
if (expr.type === "ArrowFunctionExpression") {
if (expr && expr.type === "ArrowFunctionExpression") {
return expr
} else {
node.callee = id
if (expr.type === "SequenceExpression") {
if (!expr) {
node.arguments = []
} else if (expr.type === "SequenceExpression") {
node.arguments = expr.expressions
} else {
node.arguments = [expr]
@@ -410,7 +412,13 @@ pp.parseParenAndDistinguishExpression = function(start, isAsync) {
return this.parseParenArrowList(start, exprList, isAsync)
}
if (!exprList.length) this.unexpected(this.lastTokStart)
if (!exprList.length) {
if (isAsync) {
return
} else {
this.unexpected(this.lastTokStart)
}
}
if (spreadStart) this.unexpected(spreadStart)
if (refShorthandDefaultPos.start) this.unexpected(refShorthandDefaultPos.start)

View File

@@ -558,9 +558,10 @@ pp.parseClassSuper = function(node) {
pp.parseExport = function(node) {
this.next()
// export * from '...'
if (this.eat(tt.star)) {
if (this.type === tt.star) {
let specifier = this.startNode()
this.next()
if (this.options.features["es7.exportExtensions"] && this.eatContextual("as")) {
let specifier = this.startNode()
specifier.exported = this.parseIdent()
node.specifiers = [this.finishNode(specifier, "ExportNamespaceSpecifier")]
this.parseExportSpecifiersMaybe(node)
@@ -573,7 +574,16 @@ pp.parseExport = function(node) {
let specifier = this.startNode()
specifier.exported = this.parseIdent(true)
node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")]
this.parseExportSpecifiersMaybe(node)
if (this.type === tt.comma && this.lookahead().type === tt.star) {
this.expect(tt.comma)
let specifier = this.startNode()
this.expect(tt.star)
this.expectContextual("as")
specifier.exported = this.parseIdent()
node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier"))
} else {
this.parseExportSpecifiersMaybe(node)
}
this.parseExportFrom(node)
} else if (this.eat(tt._default)) { // export default ...
let expr = this.parseMaybeAssign()

View File

@@ -1,5 +1,6 @@
var transform = module.exports = require("../transformation");
transform.options = require("../transformation/file/options");
transform.version = require("../../../package").version;
transform.transform = transform;

View File

@@ -4,10 +4,9 @@ import * as acorn from "../../acorn";
import * as util from "../util";
import fs from "fs";
export { util };
export { util, acorn };
export { canCompile } from "../util";
export { acorn } from "../../acorn";
export { default as options } from "../transformation/file/options";
export { default as Transformer } from "../transformation/transformer";
export { default as transform } from "../transformation";

View File

@@ -50,9 +50,9 @@ function buildVar(namespace, builder) {
return t.program(body);
}
function buildHelpers(body, namespace, whitelist = []) {
function buildHelpers(body, namespace, whitelist) {
each(File.helpers, function (name) {
if (whitelist.length && whitelist.indexOf(name) === -1) return;
if (whitelist && whitelist.indexOf(name) === -1) return;
var key = t.identifier(t.toIdentifier(name));
body.push(t.expressionStatement(

View File

@@ -173,20 +173,15 @@ export default class File {
return includes(this.opts.loose, key);
}
buildPlugins(stack) {
}
buildTransformers() {
var file = this;
var transformers = {};
var transformers = this.transformers = {};
var secondaryStack = [];
var stack = [];
this.buildPlugins(stack);
// build internal transformers
each(transform.transformers, function (transformer, key) {
var pass = transformers[key] = transformer.buildPass(file);
@@ -203,15 +198,23 @@ export default class File {
}
});
// init plugins!
var beforePlugins = [];
var afterPlugins = [];
for (var i = 0; i < file.opts.plugins.length; i++) {
this.addPlugin(file.opts.plugins[i], beforePlugins, afterPlugins);
}
stack = beforePlugins.concat(stack, afterPlugins);
// register
this.transformerStack = stack.concat(secondaryStack);
this.transformers = transformers;
}
getModuleFormatter(type: string) {
var ModuleFormatter = isFunction(type) ? type : transform.moduleFormatters[type];
if (!ModuleFormatter) {
var loc = util.resolve(type);
var loc = util.resolveRelative(type);
if (loc) ModuleFormatter = require(loc);
}
@@ -222,6 +225,57 @@ export default class File {
return new ModuleFormatter(this);
}
addPlugin(name, before, after) {
var position = "before";
var plugin;
if (name) {
if (typeof name === "string") {
// this is a plugin in the form of "foobar" or "foobar:after"
// where the optional colon is the delimiter for plugin position in the transformer stack
[name, position = "before"] = name.split(":");
var loc = util.resolveRelative(name) || util.resolveRelative(`babel-plugin-${name}`);
if (loc) {
plugin = require(loc)
} else {
throw new ReferenceError(`Unknown plugin ${JSON.stringify(name)}`);
}
} else {
// not a string so we'll just assume that it's a direct Transformer instance, if not then
// the checks later on will complain
plugin = name;
}
} else {
throw new TypeError(`Ilegal kind ${typeof name} for plugin name ${JSON.stringify(name)}`);
}
// validate position
if (position !== "before" && position !== "after") {
throw new TypeError(`Plugin ${JSON.stringify(name)} has an illegal position of ${JSON.stringify(position)}`);
}
// validate transformer key
var key = plugin.key;
if (this.transformers[key]) {
throw new ReferenceError(`The key for plugin ${JSON.stringify(name)} of ${key} collides with an existing plugin`);
}
// validate Transformer instance
if (!plugin.buildPass || plugin.constructor.name !== "Transformer") {
throw new TypeError(`Plugin ${JSON.stringify(name)} didn't export default a Transformer instance`);
}
// build!
var pass = this.transformers[key] = plugin.buildPass(this);
if (pass.canTransform()) {
var stack = before;
if (position === "after") stack = after;
stack.push(pass);
}
}
parseInputSourceMap(code: string) {
var opts = this.opts;
@@ -292,6 +346,7 @@ export default class File {
if (this.transformers["es6.modules"].canTransform()) {
this.moduleFormatter.importSpecifier(specifiers[0], declar, this.dynamicImports);
this.moduleFormatter.hasLocalImports = true;
} else {
this.dynamicImports.push(declar);
}
@@ -386,9 +441,10 @@ export default class File {
parse(code: string) {
if (this.shouldIgnore()) {
return {
code: code,
map: null,
ast: null
metadata: {},
code: code,
map: null,
ast: null
};
}
@@ -521,13 +577,14 @@ export default class File {
var ast = this.ast;
var result = {
code: "",
map: null,
ast: null
metadata: {},
code: "",
map: null,
ast: null
};
if (this.opts.returnUsedHelpers) {
result.usedHelpers = Object.keys(this.usedHelpers);
if (this.opts.metadataUsedHelpers) {
result.metadata.usedHelpers = Object.keys(this.usedHelpers);
}
if (opts.ast) result.ast = ast;

View File

@@ -98,6 +98,11 @@
"shorthand": "P"
},
"plugins": {
"type": "list",
"description": ""
},
"ignore": {
"type": "list",
"description": "list of glob paths to **not** compile"
@@ -127,7 +132,7 @@
},
"compact": {
"type": "booleanstring",
"type": "booleanString",
"default": "auto",
"description": "do not include superfluous whitespace characters and line terminators [true|false|auto]"
},
@@ -153,7 +158,7 @@
"description": "uses a reference to `babelHelpers` instead of placing helpers at the top of your code."
},
"returnUsedHelpers": {
"metadataUsedHelpers": {
"type": "boolean",
"default": false,
"hidden": true

View File

@@ -144,10 +144,14 @@ export default function (exports, opts) {
};
exports.JSXElement = {
enter(node) {
node.children = react.buildChildren(node);
},
exit(node) {
var callExpr = node.openingElement;
callExpr.arguments = callExpr.arguments.concat(react.buildChildren(node));
callExpr.arguments = callExpr.arguments.concat(node.children);
if (callExpr.arguments.length >= 3) {
callExpr._prettyCall = true;

View File

@@ -1,101 +0,0 @@
import includes from "lodash/collection/includes";
import * as util from "../../util";
import has from "lodash/object/has";
import * as t from "../../types";
var isSymbolIterator = t.buildMatchMemberExpression("Symbol.iterator");
var ALIASABLE_CONSTRUCTORS = [
"Symbol",
"Promise",
"Map",
"WeakMap",
"Set",
"WeakSet"
];
export default function (exports, core, prefix) {
var moduleName = `babel-runtime/${prefix}`;
function coreHas(node) {
return node.name !== "_" && has(core, node.name);
}
var astVisitor = {
enter(node, parent, scope, file) {
var prop;
if (this.isMemberExpression() && this.isReferenced()) {
// Array.from -> _core.Array.from
var obj = node.object;
prop = node.property;
if (!t.isReferenced(obj, node)) return;
if (!node.computed && coreHas(obj) && has(core[obj.name], prop.name) && !scope.getBindingIdentifier(obj.name)) {
this.skip();
return t.prependToMemberExpression(node, file.get("coreIdentifier"));
}
} else if (this.isReferencedIdentifier() && !t.isMemberExpression(parent) && includes(ALIASABLE_CONSTRUCTORS, node.name) && !scope.getBindingIdentifier(node.name)) {
// Symbol() -> _core.Symbol(); new Promise -> new _core.Promise
return t.memberExpression(file.get("coreIdentifier"), node);
} else if (this.isCallExpression()) {
// arr[Symbol.iterator]() -> _core.$for.getIterator(arr)
var callee = node.callee;
if (node.arguments.length) return false;
if (!t.isMemberExpression(callee)) return false;
if (!callee.computed) return false;
prop = callee.property;
if (!isSymbolIterator(prop)) return false;
return util.template("corejs-iterator", {
CORE_ID: file.get("coreIdentifier"),
VALUE: callee.object
});
} else if (this.isBinaryExpression()) {
// Symbol.iterator in arr -> core.$for.isIterable(arr)
if (node.operator !== "in") return;
var left = node.left;
if (!isSymbolIterator(left)) return;
return util.template("corejs-is-iterator", {
CORE_ID: file.get("coreIdentifier"),
VALUE: node.right
});
}
}
};
exports.metadata = {
optional: true
};
exports.Program = function (node, parent, scope, file) {
this.traverse(astVisitor, file);
};
exports.pre = function (file) {
file.set("helperGenerator", function (name) {
return file.addImport(`${moduleName}/helpers/${name}`, name);
});
file.setDynamic("coreIdentifier", function () {
return file.addImport(`${moduleName}/core-js`, "core");
});
file.setDynamic("regeneratorIdentifier", function () {
return file.addImport(`${moduleName}/regenerator`, "regeneratorRuntime");
});
};
exports.Identifier = function (node, parent, scope, file) {
if (this.isReferencedIdentifier({ name: "regeneratorRuntime" })) {
return file.get("regeneratorIdentifier");
}
};
};

View File

@@ -25,13 +25,12 @@ var wrap = function (state, method, id, scope) {
var template = util.template(templateName, {
FUNCTION: method,
FUNCTION_ID: id,
FUNCTION_KEY: scope.generateUidIdentifier(id.name),
WRAPPER_KEY: scope.generateUidIdentifier(id.name + "Wrapper")
FUNCTION_KEY: scope.generateUidIdentifier(id.name)
});
// shim in dummy params to retain function arity, if you try to read the
// source then you'll get the original since it's proxied so it's all good
var params = template.callee.body.body[0].declarations[0].init.params;
var params = template.callee.body.body[0].params;
for (var i = 0, len = getFunctionArity(method); i < len; i++) {
params.push(scope.generateUidIdentifier("x"));
}

View File

@@ -81,15 +81,15 @@ export function buildChildren(node) {
for (var i = 0; i < node.children.length; i++) {
var child = node.children[i];
if (t.isJSXExpressionContainer(child)) child = child.expression;
if (t.isLiteral(child) && typeof child.value === "string") {
cleanJSXElementLiteralChild(child, elems);
continue;
} else if (t.isJSXEmptyExpression(child)) {
continue;
}
if (t.isJSXExpressionContainer(child)) child = child.expression;
if (t.isJSXEmptyExpression(child)) continue;
elems.push(child);
}

View File

@@ -1,9 +1,6 @@
module.exports = ReplaceSupers;
import * as messages from "../../messages";
import * as t from "../../types";
function isIllegalBareSuper(node, parent) {
if (!t.isSuper(node)) return false;
if (t.isMemberExpression(parent, { computed: false })) return false;
@@ -11,6 +8,10 @@ function isIllegalBareSuper(node, parent) {
return true;
}
function isMemberExpressionSuper(node) {
return t.isMemberExpression(node) && t.isSuper(node.object);
}
var visitor = {
enter(node, parent, scope, state) {
var topLevel = state.topLevel;
@@ -18,7 +19,7 @@ var visitor = {
if (t.isFunction(node) && !t.isArrowFunctionExpression(node)) {
// we need to call traverseLevel again so we're context aware
self.traverseLevel(node, false);
self.traverseLevel(this, false);
return this.skip();
}
@@ -35,7 +36,10 @@ var visitor = {
var callback = self.specHandle;
if (self.isLoose) callback = self.looseHandle;
return callback.call(self, this, getThisReference);
var result = callback.call(self, this, getThisReference);
if (result) this.hasSuper = true;
if (result === true) return;
return result;
}
};
@@ -47,6 +51,7 @@ export default class ReplaceSupers {
constructor(opts: Object, inClass?: boolean = false) {
this.topLevelThisReference = opts.topLevelThisReference;
this.methodPath = opts.methodPath;
this.methodNode = opts.methodNode;
this.superRef = opts.superRef;
this.isStatic = opts.isStatic;
@@ -118,16 +123,16 @@ export default class ReplaceSupers {
*/
replace() {
this.traverseLevel(this.methodNode.value, true);
this.traverseLevel(this.methodPath.get("value"), true);
}
/**
* Description
*/
traverseLevel(node: Object, topLevel: boolean) {
traverseLevel(path: TraversalPath, topLevel: boolean) {
var state = { self: this, topLevel: topLevel };
this.scope.traverse(node, visitor, state);
path.traverse(visitor, state);
}
/**
@@ -190,7 +195,6 @@ export default class ReplaceSupers {
looseHandle(path: TraversalPath, getThisReference: Function) {
var node = path.node;
if (path.isSuper()) {
this.hasSuper = true;
return this.getLooseSuperProperty(node, path.parent);
} else if (path.isCallExpression()) {
var callee = node.callee;
@@ -198,9 +202,31 @@ export default class ReplaceSupers {
if (!t.isSuper(callee.object)) return;
// super.test(); -> objectRef.prototype.MethodName.call(this);
this.hasSuper = true;
t.appendToMemberExpression(callee, t.identifier("call"));
node.arguments.unshift(getThisReference());
return true;
}
}
/**
* Description
*/
specHandleAssignmentExpression(ref, path, node, getThisReference) {
if (node.operator === "=") {
// super.name = "val"; -> _set(Object.getPrototypeOf(objectRef.prototype), "name", this);
return this.setSuperProperty(node.left.property, node.right, node.left.computed, getThisReference());
} else {
// super.age += 2; -> var _ref = super.age; super.age = _ref + 2;
ref ||= path.scope.generateUidIdentifier("ref");
return [
t.variableDeclaration("var", [
t.variableDeclarator(ref, node.left)
]),
t.expressionStatement(
t.assignmentExpression("=", node.left, t.binaryExpression(node.operator[0], ref, node.right))
)
];
}
}
@@ -237,7 +263,7 @@ export default class ReplaceSupers {
var methodName = methodNode.key.name || "METHOD_NAME";
throw this.file.errorWithNode(node, messages.get("classesIllegalSuperCall", methodName));
}
} else if (t.isMemberExpression(callee) && t.isSuper(callee.object)) {
} else if (isMemberExpressionSuper(callee)) {
// super.test(); -> _get(Object.getPrototypeOf(objectRef.prototype), "test", this).call(this);
property = callee.property;
computed = callee.computed;
@@ -247,16 +273,22 @@ export default class ReplaceSupers {
// super.name; -> _get(Object.getPrototypeOf(objectRef.prototype), "name", this);
property = node.property;
computed = node.computed;
} else if (t.isAssignmentExpression(node) && t.isSuper(node.left.object) && methodNode.kind === "set") {
// super.name = "val"; -> _set(Object.getPrototypeOf(objectRef.prototype), "name", this);
this.hasSuper = true;
return this.setSuperProperty(node.left.property, node.right, node.left.computed, getThisReference());
} else if (t.isUpdateExpression(node) && isMemberExpressionSuper(node.argument)) {
var binary = t.binaryExpression(node.operator[0], node.argument, t.literal(1))
if (node.prefix) {
// ++super.foo; -> super.foo += 1;
return this.specHandleAssignmentExpression(null, path, binary, getThisReference);
} else {
// super.foo++; -> var _ref = super.foo; super.foo = _ref + 1;
var ref = path.scope.generateUidIdentifier("ref");
return this.specHandleAssignmentExpression(ref, path, binary, getThisReference).concat(t.expressionStatement(ref));
}
} else if (t.isAssignmentExpression(node) && isMemberExpressionSuper(node.left)) {
return this.specHandleAssignmentExpression(null, path, node, getThisReference);
}
if (!property) return;
this.hasSuper = true;
thisReference = getThisReference();
var superProperty = this.getSuperProperty(property, computed, thisReference);
if (args) {

View File

@@ -7,37 +7,51 @@ import * as t from "../../types";
var remapVisitor = {
enter(node, parent, scope, formatter) {
if (t.isUpdateExpression(node) && formatter.isLocalReference(node.argument, scope)) {
this.skip();
// expand to long file assignment expression
var assign = t.assignmentExpression(node.operator[0] + "=", node.argument, t.literal(1));
// remap this assignment expression
var remapped = formatter.remapExportAssignment(assign);
// we don't need to change the result
if (t.isExpressionStatement(parent) || node.prefix) {
return remapped;
var remap = formatter.internalRemap[node.name];
if (this.isReferencedIdentifier() && remap) {
if (!scope.hasBinding(node.name) || scope.bindingIdentifierEquals(node.name, formatter.localImports[node.name])) {
return remap;
}
var nodes = [];
nodes.push(remapped);
var operator;
if (node.operator === "--") {
operator = "+";
} else { // "++"
operator = "-";
}
nodes.push(t.binaryExpression(operator, node.argument, t.literal(1)));
return t.sequenceExpression(nodes);
}
if (t.isAssignmentExpression(node) && formatter.isLocalReference(node.left, scope)) {
this.skip();
return formatter.remapExportAssignment(node);
if (t.isUpdateExpression(node)) {
var exported = formatter.getExport(node.argument, scope);
if (exported) {
this.skip();
// expand to long file assignment expression
var assign = t.assignmentExpression(node.operator[0] + "=", node.argument, t.literal(1));
// remap this assignment expression
var remapped = formatter.remapExportAssignment(assign, exported);
// we don't need to change the result
if (t.isExpressionStatement(parent) || node.prefix) {
return remapped;
}
var nodes = [];
nodes.push(remapped);
var operator;
if (node.operator === "--") {
operator = "+";
} else { // "++"
operator = "-";
}
nodes.push(t.binaryExpression(operator, node.argument, t.literal(1)));
return t.sequenceExpression(nodes);
}
}
if (t.isAssignmentExpression(node)) {
var exported = formatter.getExport(node.left, scope);
if (exported) {
this.skip();
return formatter.remapExportAssignment(node, exported);
}
}
}
};
@@ -59,7 +73,21 @@ var exportsVisitor = traverse.explode({
var declar = this.get("declaration");
if (declar.isStatement()) {
extend(formatter.localExports, declar.getBindingIdentifiers());
var bindings = declar.getBindingIdentifiers()
for (var name in bindings) {
var binding = bindings[name];
formatter._addExport(name, binding);
}
}
if (this.isExportNamedDeclaration() && node.specifiers) {
for (var i = 0; i < node.specifiers.length; i++) {
var specifier = node.specifiers[i];
var local = specifier.local;
if (!local) continue;
formatter._addExport(local.name, specifier.exported);
}
}
if (!t.isExportDefaultDeclaration(node)) {
@@ -78,9 +106,12 @@ var exportsVisitor = traverse.explode({
export default class DefaultFormatter {
constructor(file) {
this.scope = file.scope;
this.file = file;
this.ids = object();
this.internalRemap = {};
this.defaultIds = object();
this.scope = file.scope;
this.file = file;
this.ids = object();
this.hasNonDefaultExports = false;
@@ -95,7 +126,7 @@ export default class DefaultFormatter {
this.getLocalImports();
}
init() {
transform() {
this.remapAssignments();
}
@@ -126,27 +157,35 @@ export default class DefaultFormatter {
}
}
isLocalReference(node) {
var localImports = this.localImports;
return t.isIdentifier(node) && localImports[node.name] && localImports[node.name] !== node;
remapExportAssignment(node, exported) {
var assign = node;
for (var i = 0; i < exported.length; i++) {
assign = t.assignmentExpression(
"=",
t.memberExpression(t.identifier("exports"), exported[i]),
assign
);
}
return assign;
}
remapExportAssignment(node) {
return t.assignmentExpression(
"=",
node.left,
t.assignmentExpression(
node.operator,
t.memberExpression(t.identifier("exports"), node.left),
node.right
)
);
_addExport(name, exported) {
var info = this.localExports[name] ||= {
binding: this.scope.getBindingIdentifier(name),
exported: []
};
info.exported.push(exported);
}
isLocalReference(node, scope) {
var localExports = this.localExports;
var name = node.name;
return t.isIdentifier(node) && localExports[name] && localExports[name] === scope.getBindingIdentifier(name);
getExport(node, scope) {
if (!t.isIdentifier(node)) return;
var local = this.localExports[node.name];
if (local && local.binding === scope.getBindingIdentifier(node.name)) {
return local.exported;
}
}
getModuleName() {
@@ -224,6 +263,10 @@ export default class DefaultFormatter {
nodes.push(this.buildExportsWildcard(ref, node));
}
isLoose() {
return this.file.isLoose("es6.modules");
}
exportSpecifier(specifier, node, nodes) {
if (node.source) {
var ref = this.getExternalReference(node, nodes);
@@ -233,6 +276,11 @@ export default class DefaultFormatter {
ref = t.callExpression(this.file.addHelper("interop-require"), [ref]);
} else {
ref = t.memberExpression(ref, specifier.local);
if (!this.isLoose()) {
nodes.push(this.buildExportsFromAssignment(specifier.exported, ref, node));
return;
}
}
// export { foo } from "test";
@@ -250,6 +298,14 @@ export default class DefaultFormatter {
]));
}
buildExportsFromAssignment(id, init) {
this.checkExportIdentifier(id);
return util.template("exports-from-assign", {
INIT: init,
ID: t.literal(id.name)
}, true);
}
buildExportsAssignment(id, init) {
this.checkExportIdentifier(id);
return util.template("exports-assign", {

View File

@@ -21,6 +21,8 @@ export default class AMDFormatter extends DefaultFormatter {
*/
transform(program) {
DefaultFormatter.prototype.transform.apply(this, arguments);
var body = program.body;
// build an array of module names
@@ -69,8 +71,13 @@ export default class AMDFormatter extends DefaultFormatter {
}
importSpecifier(specifier, node, nodes) {
var key = node.source.value;
var ref = this.getExternalReference(node);
if (t.isImportNamespaceSpecifier(specifier) || t.isImportDefaultSpecifier(specifier)) {
this.defaultIds[key] = specifier.local;
}
if (includes(this.file.dynamicImportedNoDefault, node)) {
// Prevent unnecessary renaming of dynamic imports.
this.ids[node.source.value] = ref;
@@ -78,7 +85,11 @@ export default class AMDFormatter extends DefaultFormatter {
// import * as bar from "foo";
} else if (!includes(this.file.dynamicImported, node) && t.isSpecifierDefault(specifier) && !this.noInteropRequireImport) {
// import foo from "foo";
ref = t.callExpression(this.file.addHelper("interop-require"), [ref]);
var uid = this.scope.generateUidIdentifier(specifier.local.name);
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(uid, t.callExpression(this.file.addHelper("interop-require"), [ref]))
]));
ref = uid;
} else {
// import { foo } from "foo";
var imported = specifier.imported;
@@ -86,9 +97,7 @@ export default class AMDFormatter extends DefaultFormatter {
ref = t.memberExpression(ref, imported);
}
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(specifier.local, ref)
]));
this.internalRemap[specifier.local.name] = ref;
}
exportSpecifier() {

View File

@@ -9,15 +9,16 @@ export default class CommonJSFormatter extends DefaultFormatter {
var scope = file.scope;
scope.rename("module");
scope.rename("exports");
if (!this.noInteropRequireImport && this.hasNonDefaultExports) {
var templateName = "exports-module-declaration";
if (this.file.isLoose("es6.modules")) templateName += "-loose";
file.ast.program.body.unshift(util.template(templateName, true));
var declar = util.template(templateName, true);
declar._blockHoist = 3;
file.ast.program.body.unshift(declar);
}
DefaultFormatter.prototype.init.call(this);
};
}
importSpecifier(specifier, node, nodes) {
var variableName = specifier.local;
@@ -26,14 +27,17 @@ export default class CommonJSFormatter extends DefaultFormatter {
// import foo from "foo";
if (t.isSpecifierDefault(specifier)) {
if (!includes(this.file.dynamicImportedNoDefault, node)) {
if (this.noInteropRequireImport || includes(this.file.dynamicImported, node)) {
ref = t.memberExpression(ref, t.identifier("default"));
} else {
ref = t.callExpression(this.file.addHelper("interop-require"), [ref]);
if (includes(this.file.dynamicImportedNoDefault, node)) {
this.internalRemap[variableName.name] = ref;
} else {
if (this.noInteropRequireImport) {
this.internalRemap[variableName.name] = t.memberExpression(ref, t.identifier("default"))
} else if (!includes(this.file.dynamicImported, node)) {
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(variableName, t.callExpression(this.file.addHelper("interop-require"), [ref]))
]));
}
}
nodes.push(t.variableDeclaration("var", [t.variableDeclarator(variableName, ref)]));
} else {
if (t.isImportNamespaceSpecifier(specifier)) {
if (!this.noInteropRequireImport) {
@@ -46,12 +50,7 @@ export default class CommonJSFormatter extends DefaultFormatter {
]));
} else {
// import { foo } from "foo";
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(
variableName,
t.memberExpression(ref, specifier.imported)
)
]));
this.internalRemap[variableName.name] = t.memberExpression(ref, specifier.imported);
}
}
}
@@ -95,16 +94,21 @@ export default class CommonJSFormatter extends DefaultFormatter {
_getExternalReference(node, nodes) {
var source = node.source.value;
var call = t.callExpression(t.identifier("require"), [node.source]);
if (this.localImportOccurences[source] > 1) {
var uid = this.scope.generateUidIdentifier(source);
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(uid, call)
]));
return uid;
var call = t.callExpression(t.identifier("require"), [node.source]);
var uid;
if (includes(this.file.dynamicImported, node) && !includes(this.file.dynamicImportedNoDefault, node)) {
call = t.memberExpression(call, t.identifier("default"));
uid = node.specifiers[0].local;
} else {
return call;
uid = this.scope.generateUidBasedOnNode(node, "import");
}
var declar = t.variableDeclaration("var", [
t.variableDeclarator(uid, call)
]);
nodes.push(declar);
return uid;
}
}

View File

@@ -94,12 +94,8 @@ export default class SystemFormatter extends AMDFormatter {
DefaultFormatter.apply(this, arguments);
}
init() {
DefaultFormatter.prototype.init.call(this);
}
_addImportSource(node, exportNode) {
node._importSource = exportNode.source && exportNode.source.value;
if (node) node._importSource = exportNode.source && exportNode.source.value;
return node;
}
@@ -125,8 +121,18 @@ export default class SystemFormatter extends AMDFormatter {
return this._addImportSource(call, node);
}
remapExportAssignment(node) {
return this.buildExportCall(t.literal(node.left.name), node);
buildExportsFromAssignment() {
return this.buildExportsAssignment(...arguments);
}
remapExportAssignment(node, exported) {
var assign = node;
for (var i = 0; i < exported.length; i++) {
assign = this.buildExportCall(t.literal(exported[i].name), assign);
}
return assign;
}
buildExportCall(id, init, isStatement) {
@@ -140,6 +146,15 @@ export default class SystemFormatter extends AMDFormatter {
importSpecifier(specifier, node, nodes) {
AMDFormatter.prototype.importSpecifier.apply(this, arguments);
for (var name in this.internalRemap) {
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(t.identifier(name), this.internalRemap[name])
]));
}
this.internalRemap = {};
this._addImportSource(last(nodes), node);
}
@@ -160,6 +175,8 @@ export default class SystemFormatter extends AMDFormatter {
}
transform(program) {
DefaultFormatter.prototype.transform.apply(this, arguments);
var hoistDeclarators = [];
var moduleName = this.getModuleName();
var moduleNameLiteral = t.literal(moduleName);

View File

@@ -1,3 +1,4 @@
import DefaultFormatter from "./_default";
import AMDFormatter from "./amd";
import values from "lodash/object/values";
import * as util from "../../util";
@@ -5,12 +6,14 @@ import * as t from "../../types";
export default class UMDFormatter extends AMDFormatter {
transform(program) {
DefaultFormatter.prototype.transform.apply(this, arguments);
var body = program.body;
// build an array of module names
var names = [];
for (var name in this.ids) {
for (let name in this.ids) {
names.push(t.literal(name));
}
@@ -44,7 +47,13 @@ export default class UMDFormatter extends AMDFormatter {
// globals
//var umdArgs = [];
var browserArgs = [t.memberExpression(t.identifier("module"), t.identifier("exports"))];
if (this.passModuleArg) browserArgs.push(t.identifier("module"));
for (let name in this.ids) {
var id = this.defaultIds[name] || t.identifier(t.toIdentifier(name));
browserArgs.push(t.memberExpression(t.identifier("global"), id));
}
//
@@ -54,12 +63,15 @@ export default class UMDFormatter extends AMDFormatter {
var runner = util.template("umd-runner-body", {
AMD_ARGUMENTS: defineArgs,
COMMON_TEST: commonTests,
COMMON_ARGUMENTS: commonArgs
COMMON_ARGUMENTS: commonArgs,
BROWSER_ARGUMENTS: browserArgs,
GLOBAL_ARG: t.identifier(t.toIdentifier(this.file.opts.basename))
});
//
var call = t.callExpression(runner, [factory]);
program.body = [t.expressionStatement(call)];
program.body = [t.expressionStatement(
t.callExpression(runner, [t.thisExpression(), factory])
)];
}
}

View File

@@ -1 +1 @@
CORE_ID.$for.isIterable(VALUE);
CORE_ID.isIterable(VALUE);

View File

@@ -1 +1 @@
CORE_ID.$for.getIterator(VALUE);
CORE_ID.getIterator(VALUE);

View File

@@ -0,0 +1,6 @@
Object.defineProperty(exports, ID, {
enumerable: true,
get: function () {
return INIT;
}
});

View File

@@ -9,7 +9,7 @@
} else {
return get(parent, property, receiver);
}
} else if ("value" in desc && desc.writable) {
} else if ("value" in desc) {
return desc.value;
} else {
var getter = desc.get;

View File

@@ -5,15 +5,17 @@
var parent = Object.getPrototypeOf(object);
if (parent !== null) {
return set(parent, property, value, receiver);
set(parent, property, value, receiver);
}
} else if ("value" in desc && desc.writable) {
return desc.value = value;
desc.value = value;
} else {
var setter = desc.set;
if (setter !== undefined) {
return setter.call(receiver, value);
setter.call(receiver, value);
}
}
return value;
});

View File

@@ -0,0 +1 @@
Object(RIGHT)[LEFT] !== undefined;

View File

@@ -1,11 +1,11 @@
(function (FUNCTION_KEY) {
var WRAPPER_KEY = function* FUNCTION_ID() {
return yield* FUNCTION_KEY.apply(this, arguments);
function* FUNCTION_ID() {
return yield* FUNCTION_ID.apply(this, arguments);
}
FUNCTION_ID.toString = function () {
return FUNCTION_ID.toString();
};
WRAPPER_KEY.toString = function () {
return FUNCTION_KEY.toString();
};
return WRAPPER_KEY;
return FUNCTION_ID;
})(FUNCTION)

View File

@@ -1,11 +1,11 @@
(function (FUNCTION_KEY) {
var WRAPPER_KEY = function FUNCTION_ID() {
function FUNCTION_ID() {
return FUNCTION_KEY.apply(this, arguments);
};
}
WRAPPER_KEY.toString = function () {
return FUNCTION_KEY.toString();
};
FUNCTION_ID.toString = function () {
return FUNCTION_ID.toString();
}
return WRAPPER_KEY;
return FUNCTION_ID;
})(FUNCTION)

View File

@@ -1,7 +1,7 @@
(function (root, factory) {
if (typeof define === "function" && define.amd) {
define(AMD_ARGUMENTS, factory);
} else if (typeof exports === 'object') {
} else if (typeof exports === "object") {
factory(COMMON_ARGUMENTS);
} else {
factory(BROWSER_ARGUMENTS);

View File

@@ -1,7 +1,11 @@
(function (factory) {
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(AMD_ARGUMENTS, factory);
} else if (COMMON_TEST) {
factory(COMMON_ARGUMENTS);
} else {
var module = { exports: {} };
factory(BROWSER_ARGUMENTS);
global.GLOBAL_ARG = module.exports;
}
});

View File

@@ -9,7 +9,7 @@ import each from "lodash/collection/each";
/**
* This is the class responsible for normalising a transformers handlers
* as well as constructing a `TransformerPass` that is repsonsible for
* as well as constructing a `TransformerPass` that is responsible for
* actually running the transformer over the provided `File`.
*/
@@ -69,6 +69,11 @@ export default class Transformer {
}
buildPass(file: File): TransformerPass {
// validate Transformer instance
if (!(file instanceof File)) {
throw new TypeError(`Transformer ${this.key} is resolving to a different Babel version to what is doing the actual transformation...`);
}
return new TransformerPass(file, this);
}
}

View File

@@ -1,5 +0,0 @@
import * as t from "../../../types";
export var metadata = {
optional: true
};

View File

@@ -1,4 +0,0 @@
import core from "core-js/client/library";
import buildRuntimeTransformer from "../../helpers/build-runtime-transformer";
buildRuntimeTransformer(exports, core, "es3");

View File

@@ -70,13 +70,13 @@ export function Loop(node, parent, scope, file) {
node.body._letDeclarators = [init];
}
var blockScoping = new BlockScoping(this, node.body, parent, scope, file);
var blockScoping = new BlockScoping(this, this.get("body"), parent, scope, file);
return blockScoping.run();
}
export function BlockStatement(block, parent, scope, file) {
if (!t.isLoop(parent)) {
var blockScoping = new BlockScoping(null, block, parent, scope, file);
var blockScoping = new BlockScoping(null, this, parent, scope, file);
blockScoping.run();
}
}
@@ -122,12 +122,14 @@ var letReferenceFunctionVisitor = {
// not a direct reference
if (!this.isReferencedIdentifier()) return;
var ref = state.letReferences[node.name];
// not a part of our scope
if (!state.letReferences[node.name]) return;
if (!ref) return;
// this scope has a variable with the same name so it couldn't belong
// to our let scope
if (scope.hasOwnBinding(node.name)) return;
if (scope.getBindingIdentifier(node.name) !== ref) return;
state.closurify = true;
}
@@ -237,20 +239,23 @@ class BlockScoping {
* Description
*/
constructor(loopPath?: TraversalPath, block: Object, parent: Object, scope: Scope, file: File) {
constructor(loopPath?: TraversalPath, blockPath: TraversalPath, parent: Object, scope: Scope, file: File) {
this.parent = parent;
this.scope = scope;
this.block = block;
this.file = file;
this.blockPath = blockPath;
this.block = blockPath.node;
this.outsideLetReferences = object();
this.hasLetReferences = false;
this.letReferences = block._letReferences = object();
this.letReferences = this.block._letReferences = object();
this.body = [];
if (loopPath) {
this.loopParent = loopPath.parent;
this.loopLabel = t.isLabeledStatement(this.loopParent) && this.loopParent.label;
this.loopPath = loopPath;
this.loop = loopPath.node;
}
}
@@ -326,7 +331,7 @@ class BlockScoping {
traverseReplace(loop.update, loop, scope, remaps);
}
scope.traverse(this.block, replaceVisitor, remaps);
this.blockPath.traverse(replaceVisitor, remaps);
}
/**
@@ -376,8 +381,17 @@ class BlockScoping {
// replace the current block body with the one we're going to build
block.body = this.body;
var ref = fn;
if (this.loop) {
ref = this.scope.generateUidIdentifier("loop");
this.loopPath.insertBefore(t.variableDeclaration("var", [
t.variableDeclarator(ref, fn)
]));
}
// build a call and a unique id that we can assign the return value to
var call = t.callExpression(fn, args);
var call = t.callExpression(ref, args);
var ret = this.scope.generateUidIdentifier("ret");
// handle generators
@@ -394,7 +408,20 @@ class BlockScoping {
call = t.awaitExpression(call);
}
this.build(ret, call);
this.buildClosure(ret, call);
}
/**
* Push the closure to the body.
*/
buildClosure(ret: { type: "Identifier" }, call: { type: "CallExpression" }) {
var has = this.has;
if (has.hasReturn || has.hasBreakContinue) {
this.buildHas(ret, call);
} else {
this.body.push(t.expressionStatement(call));
}
}
/**
@@ -474,7 +501,7 @@ class BlockScoping {
// traverse through this block, stopping on functions and checking if they
// contain any local let references
this.scope.traverse(this.block, letReferenceBlockVisitor, state);
this.blockPath.traverse(letReferenceBlockVisitor, state);
return state.closurify;
}
@@ -498,8 +525,8 @@ class BlockScoping {
map: {}
};
this.scope.traverse(this.block, loopLabelVisitor, state);
this.scope.traverse(this.block, loopVisitor, state);
this.blockPath.traverse(loopLabelVisitor, state);
this.blockPath.traverse(loopVisitor, state);
return state;
}
@@ -510,7 +537,7 @@ class BlockScoping {
*/
hoistVarDeclarations() {
traverse(this.block, hoistVarDeclarationsVisitor, this.scope, this);
this.blockPath.traverse(hoistVarDeclarationsVisitor, this);
}
/**
@@ -536,19 +563,6 @@ class BlockScoping {
return replace;
}
/**
* Push the closure to the body.
*/
build(ret: { type: "Identifier" }, call: { type: "CallExpression" }) {
var has = this.has;
if (has.hasReturn || has.hasBreakContinue) {
this.buildHas(ret, call);
} else {
this.body.push(t.expressionStatement(call));
}
}
/**
* Description
*/

View File

@@ -147,7 +147,7 @@ class ClassTransformer {
if (this.hasSuper) {
closureArgs.push(superName);
superName = this.scope.generateUidBasedOnNode(superName, this.file);
superName = this.scope.generateUidBasedOnNode(superName);
closureParams.push(superName);
this.superName = superName;
@@ -279,6 +279,7 @@ class ClassTransformer {
if (isConstructor) this.verifyConstructor(path);
var replaceSupers = new ReplaceSupers({
methodPath: path,
methodNode: node,
objectRef: this.classRef,
superRef: this.superName,

View File

@@ -33,8 +33,12 @@ export function ForOfStatement(node, parent, scope, file) {
t.inherits(loop, node);
if (build.replaceParent) this.parentPath.replaceWithMultiple(build.node);
return build.node;
if (build.replaceParent) {
this.parentPath.replaceWithMultiple(build.node);
this.remove();
} else {
this.replaceWithMultiple(build.node);
}
}
export function _ForOfStatementArray(node, scope, file) {

View File

@@ -3,7 +3,7 @@ import * as t from "../../../types";
export var check = t.isSuper;
function Property(node, scope, getObjectRef, file) {
function Property(path, node, scope, getObjectRef, file) {
if (!node.method) return;
var value = node.value;
@@ -13,6 +13,7 @@ function Property(node, scope, getObjectRef, file) {
topLevelThisReference: thisExpr,
getObjectRef: getObjectRef,
methodNode: node,
methodPath: path,
isStatic: true,
scope: scope,
file: file
@@ -33,8 +34,9 @@ export function ObjectExpression(node, parent, scope, file) {
var objectRef;
var getObjectRef = () => objectRef ||= scope.generateUidIdentifier("obj");
var propPaths = this.get("properties");
for (var i = 0; i < node.properties.length; i++) {
Property(node.properties[i], scope, getObjectRef, file);
Property(propPaths[i], node.properties[i], scope, getObjectRef, file);
}
if (objectRef) {

View File

@@ -5,6 +5,8 @@ export var metadata = {
};
export function TemplateLiteral(node, parent, scope, file) {
if (t.isTaggedTemplateExpression(parent)) return;
for (var i = 0; i < node.expressions.length; i++) {
node.expressions[i] = t.callExpression(t.identifier("String"), [node.expressions[i]]);
}

View File

@@ -26,7 +26,7 @@ function generator(node) {
}
function array(node, parent, scope, file) {
var uid = scope.generateUidBasedOnNode(parent, file);
var uid = scope.generateUidBasedOnNode(parent);
var container = util.template("array-comprehension-container", {
KEY: uid

View File

@@ -10,28 +10,32 @@ export function check(node) {
return t.isExportDefaultSpecifier(node) || t.isExportNamespaceSpecifier(node);
}
export function ExportNamedDeclaration(node, parent, scope) {
var nodes = [];
function build(node, nodes, scope) {
var first = node.specifiers[0];
if (!t.isExportNamespaceSpecifier(first) && !t.isExportDefaultSpecifier(first)) return;
if (t.isExportNamespaceSpecifier(node.specifiers[0])) {
var specifier = node.specifiers.shift();
var uid = scope.generateUidIdentifier(specifier.exported.name);
nodes.push(
t.importDeclaration([t.importNamespaceSpecifier(uid)], node.source),
t.exportNamedDeclaration(null, [t.exportSpecifier(uid, specifier.exported)])
);
} else if (t.isExportDefaultSpecifier(node.specifiers[0])) {
var specifier = node.specifiers.shift();
var uid = scope.generateUidIdentifier(specifier.exported.name);
nodes.push(
t.importDeclaration([t.importSpecifier(uid, specifier.exported)], node.source),
t.exportNamedDeclaration(null, [t.exportSpecifier(uid, t.identifier("default"))])
);
var specifier = node.specifiers.shift();
var uid = scope.generateUidIdentifier(specifier.exported.name);
var newSpecifier;
if (t.isExportNamespaceSpecifier(specifier)) {
newSpecifier = t.importNamespaceSpecifier(uid);
} else {
newSpecifier = t.importDefaultSpecifier(uid);
}
nodes.push(t.importDeclaration([newSpecifier], node.source));
nodes.push(t.exportNamedDeclaration(null, [t.exportSpecifier(uid, specifier.exported)]));
build(node, nodes, scope);
}
export function ExportNamedDeclaration(node, parent, scope) {
var nodes = [];
build(node, nodes, scope);
if (!nodes.length) return;
if (node.specifiers.length > 1) {
if (node.specifiers.length >= 1) {
nodes.push(node);
}

View File

@@ -83,7 +83,6 @@ export default {
// needs to be after `regenerator` due to needing `regeneratorRuntime` references
// needs to be after `es6.forOf` due to needing `Symbol.iterator` references
// needs to be before `es6.modules` due to dynamic imports
"es3.runtime": require("./es3/runtime"),
runtime: require("./other/runtime"),
// needs to be before `_blockHoist` due to function hoisting etc
@@ -101,8 +100,8 @@ export default {
"es7.doExpressions": require("./es7/do-expressions"),
"es6.spec.symbols": require("./es6/spec.symbols"),
ludicrous: require("./other/ludicrous"),
"spec.undefinedToVoid": require("./spec/undefined-to-void"),
"es1.ludicrous": require("./es1/ludicrous"),
_strict: require("./internal/strict"),
_moduleFormatter: require("./internal/module-formatter"),

View File

@@ -78,3 +78,19 @@ export function ExportNamedDeclaration(node, parent, scope) {
return [declar, t.exportNamedDeclaration(null, specifiers)];
}
}
export function Program(node) {
var imports = [];
var rest = [];
for (var i = 0; i < node.body.length; i++) {
var bodyNode = node.body[i];
if (t.isImportDeclaration(bodyNode)) {
imports.push(bodyNode);
} else {
rest.push(bodyNode);
}
}
node.body = imports.concat(rest);
}

View File

@@ -0,0 +1,29 @@
import * as t from "../../../types";
import * as util from "../../../util";
export var metadata = {
optional: true
};
export function BinaryExpression(node) {
if (node.operator === "in") {
return util.template("ludicrous-in", {
LEFT: node.left,
RIGHT: node.right
});
}
}
export function Property(node) {
var key = node.key;
if (t.isLiteral(key) && typeof key.value === "number") {
key.value = "" + key.value;
}
}
export function Literal(node) {
if (node.regex) {
node.regex.pattern = "foobar";
node.regex.flags = "";
}
}

View File

@@ -1,4 +1,98 @@
import core from "core-js/library";
import buildRuntimeTransformer from "../../helpers/build-runtime-transformer";
import includes from "lodash/collection/includes";
import * as util from "../../../util";
import has from "lodash/object/has";
import * as t from "../../../types";
buildRuntimeTransformer(exports, core, "es5");
var isSymbolIterator = t.buildMatchMemberExpression("Symbol.iterator");
var ALIASABLE_CONSTRUCTORS = [
"Symbol",
"Promise",
"Map",
"WeakMap",
"Set",
"WeakSet"
];
function coreHas(node) {
return node.name !== "_" && has(core, node.name);
}
var astVisitor = {
enter(node, parent, scope, file) {
var prop;
if (this.isMemberExpression() && this.isReferenced()) {
// Array.from -> _core.Array.from
var obj = node.object;
prop = node.property;
if (!t.isReferenced(obj, node)) return;
if (!node.computed && coreHas(obj) && has(core[obj.name], prop.name) && !scope.getBindingIdentifier(obj.name)) {
this.skip();
return t.prependToMemberExpression(node, file.get("coreIdentifier"));
}
} else if (this.isReferencedIdentifier() && !t.isMemberExpression(parent) && includes(ALIASABLE_CONSTRUCTORS, node.name) && !scope.getBindingIdentifier(node.name)) {
// Symbol() -> _core.Symbol(); new Promise -> new _core.Promise
return t.memberExpression(file.get("coreIdentifier"), node);
} else if (this.isCallExpression()) {
// arr[Symbol.iterator]() -> _core.$for.getIterator(arr)
var callee = node.callee;
if (node.arguments.length) return false;
if (!t.isMemberExpression(callee)) return false;
if (!callee.computed) return false;
prop = callee.property;
if (!isSymbolIterator(prop)) return false;
return util.template("corejs-iterator", {
CORE_ID: file.get("coreIdentifier"),
VALUE: callee.object
});
} else if (this.isBinaryExpression()) {
// Symbol.iterator in arr -> core.$for.isIterable(arr)
if (node.operator !== "in") return;
var left = node.left;
if (!isSymbolIterator(left)) return;
return util.template("corejs-is-iterator", {
CORE_ID: file.get("coreIdentifier"),
VALUE: node.right
});
}
}
};
exports.metadata = {
optional: true
};
exports.Program = function (node, parent, scope, file) {
this.traverse(astVisitor, file);
};
exports.pre = function (file) {
file.set("helperGenerator", function (name) {
return file.addImport(`babel-runtime/helpers/${name}`, name);
});
file.setDynamic("coreIdentifier", function () {
return file.addImport("babel-runtime/core-js", "core");
});
file.setDynamic("regeneratorIdentifier", function () {
return file.addImport("babel-runtime/regenerator", "regeneratorRuntime");
});
};
exports.Identifier = function (node, parent, scope, file) {
if (this.isReferencedIdentifier({ name: "regeneratorRuntime" })) {
return file.get("regeneratorIdentifier");
}
};

View File

@@ -1,12 +1,8 @@
import * as t from "../../../types";
export function BlockStatement(node, parent, scope, file) {
if ((t.isFunction(parent) && parent.body === node) || t.isExportDeclaration(parent)) {
return;
}
for (var i = 0; i < node.body.length; i++) {
var func = node.body[i];
function statementList(key, node, file) {
for (var i = 0; i < node[key].length; i++) {
var func = node[key][i];
if (!t.isFunctionDeclaration(func)) continue;
var declar = t.variableDeclaration("let", [
@@ -19,8 +15,20 @@ export function BlockStatement(node, parent, scope, file) {
// todo: name this
func.id = null;
node.body[i] = declar;
node[key][i] = declar;
file.checkNode(declar);
}
}
export function BlockStatement(node, parent, scope, file) {
if ((t.isFunction(parent) && parent.body === node) || t.isExportDeclaration(parent)) {
return;
}
statementList("body", node, file);
}
export function SwitchCase(node, parent, scope, file) {
statementList("consequent", node, file);
}

View File

@@ -7,7 +7,7 @@ export default function traverse(parent, opts, scope, state, parentPath) {
if (!opts.noScope && !scope) {
if (parent.type !== "Program" && parent.type !== "File") {
throw new Error(`Must pass a scope unless traversing a Program/File got a ${parent.type} node`);
throw new Error(`Must pass a scope and parentPath unless traversing a Program/File got a ${parent.type} node`);
}
}

View File

@@ -86,24 +86,26 @@ export default class TraversalPath {
}
insertBefore(nodes) {
nodes = this._verifyNodeList(nodes);
this.checkNodes(nodes);
if (this.parentPath.isExpressionStatement()) {
if (this.parentPath.isExpressionStatement() || this.parentPath.isLabeledStatement()) {
return this.parentPath.insertBefore(nodes);
} else if (this.isPreviousType("Statement")) {
this._maybePopFromStatements(nodes);
if (Array.isArray(this.container)) {
this._containerInsertBefore(nodes);
} else if (this.isStatementOrBlock()) {
if (this.node) nodes.push(this.node);
this.container[this.key] = t.blockStatement(nodes);
} else {
throw new Error("no idea what to do with this");
throw new Error("We don't know what to do with this node type. We were previously a Statement but we can't fit in here?");
}
} else if (this.isPreviousType("Expression")) {
if (this.node) nodes.push(this.node);
this.replaceExpressionWithStatements(nodes);
} else {
throw new Error("no idea what to do with this ");
throw new Error("No clue what to do with this node type.");
}
}
@@ -129,23 +131,36 @@ export default class TraversalPath {
this._containerInsert(this.key + 1, nodes);
}
_maybePopFromStatements(nodes) {
var last = nodes[nodes.length - 1];
if (t.isExpressionStatement(last) && t.isIdentifier(last.expression)) {
nodes.pop();
}
}
isStatementOrBlock() {
return includes(t.STATEMENT_OR_BLOCK_KEYS, this.key) && !t.isBlockStatement(this.container);
if (t.isLabeledStatement(this.parent) || t.isBlockStatement(this.container)) {
return false;
} else {
return includes(t.STATEMENT_OR_BLOCK_KEYS, this.key);
}
}
insertAfter(nodes) {
nodes = this._verifyNodeList(nodes);
this.checkNodes(nodes);
if (this.parentPath.isExpressionStatement()) {
if (this.parentPath.isExpressionStatement() || this.parentPath.isLabeledStatement()) {
return this.parentPath.insertAfter(nodes);
} else if (this.isPreviousType("Statement")) {
this._maybePopFromStatements(nodes);
if (Array.isArray(this.container)) {
this._containerInsertAfter(nodes);
} else if (this.isStatementOrBlock()) {
if (this.node) nodes.unshift(this.node);
this.container[this.key] = t.blockStatement(nodes);
} else {
throw new Error("no idea what to do with this");
throw new Error("We don't know what to do with this node type. We were previously a Statement but we can't fit in here?");
}
} else if (this.isPreviousType("Expression")) {
if (this.node) {
@@ -155,7 +170,7 @@ export default class TraversalPath {
}
this.replaceExpressionWithStatements(nodes);
} else {
throw new Error("no idea what to do with this");
throw new Error("No clue what to do with this node type.");
}
}
@@ -201,9 +216,9 @@ export default class TraversalPath {
this.opts = context.opts;
}
this.setScope(file);
this.type = this.node && this.node.type;
this.setScope(file);
}
_remove() {
@@ -216,6 +231,13 @@ export default class TraversalPath {
}
remove() {
var removeParent = false;
if (this.parentPath) {
removeParent ||= this.parentPath.isExpressionStatement();
removeParent ||= this.parentPath.isSequenceExpression() && this.parent.expressions.length === 1
if (removeParent) return this.parentPath.remove();
}
this._remove();
this.removed = true;
}
@@ -251,7 +273,7 @@ export default class TraversalPath {
replaceInline(nodes) {
if (Array.isArray(nodes)) {
if (Array.isArray(this.container)) {
this._verifyNodeList(nodes);
nodes = this._verifyNodeList(nodes);
this._containerInsertAfter(nodes);
return this.remove();
} else {
@@ -263,20 +285,26 @@ export default class TraversalPath {
}
_verifyNodeList(nodes) {
if (typeof nodes === "object") {
if (nodes.constructor !== Array) {
nodes = [nodes];
}
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
if (!node) throw new Error(`Node list has falsy node with the index of ${i}`);
if (!node) {
throw new Error(`Node list has falsy node with the index of ${i}`);
} else if (typeof node !== "object") {
throw new Error(`Node list contains a non-object node with the index of ${i}`);
} else if (!node.type) {
throw new Error(`Node list contains a node without a type with the index of ${i}`);
}
}
return nodes;
}
replaceWithMultiple(nodes: Array<Object>) {
this._verifyNodeList(nodes);
nodes = this._verifyNodeList(nodes);
t.inheritsComments(nodes[0], this.node);
this.container[this.key] = null;
this.insertAfter(nodes);

View File

@@ -57,7 +57,8 @@ var blockVariableVisitor = {
enter(node, parent, scope, state) {
if (this.isFunctionDeclaration() || this.isBlockScoped()) {
state.registerDeclaration(this);
} else if (this.isScope()) {
}
if (this.isScope()) {
this.skip();
}
}
@@ -100,7 +101,7 @@ export default class Scope {
*/
traverse(node: Object, opts: Object, state?) {
traverse(node, opts, this, state);
traverse(node, opts, this, state, this.path);
}
/**
@@ -161,7 +162,7 @@ export default class Scope {
* Description
*/
generateUidBasedOnNode(parent: Object): Object {
generateUidBasedOnNode(parent: Object, defaultName?: String): Object {
var node = parent;
if (t.isAssignmentExpression(parent)) {
@@ -175,7 +176,17 @@ export default class Scope {
var parts = [];
var add = function (node) {
if (t.isMemberExpression(node)) {
if (t.isModuleDeclaration(node)) {
if (node.specifiers && node.specifiers.length) {
for (var i = 0; i < node.specifiers.length; i++) {
add(node.specifiers[i]);
}
} else {
add(node.source);
}
} else if (t.isModuleSpecifier(node)) {
add(node.local);
} else if (t.isMemberExpression(node)) {
add(node.object);
add(node.property);
} else if (t.isIdentifier(node)) {
@@ -195,7 +206,7 @@ export default class Scope {
add(node);
var id = parts.join("$");
id = id.replace(/^_/, "") || "ref";
id = id.replace(/^_/, "") || defaultName || "ref";
return this.generateUidIdentifier(id);
}
@@ -436,9 +447,6 @@ export default class Scope {
var node = path.get(t.FOR_INIT_KEYS[i]);
if (node.isBlockScoped()) this.registerBinding("let", node);
}
var body = path.get("body");
if (body.isBlockStatement()) path = path.get("body");
}
// FunctionExpression - id

View File

@@ -15,6 +15,9 @@
"LabeledStatement": ["Statement"],
"VariableDeclaration": ["Statement", "Declaration"],
"ImportSpecifier": ["ModuleSpecifier"],
"ExportSpecifier": ["ModuleSpecifier"],
"ImportDefaultSpecifier": ["ModuleSpecifier"],
"ExportDefaultSpecifier": ["ModuleSpecifier"],
"ExportNamespaceSpecifier": ["ModuleSpecifier"],
"ExportDefaultFromSpecifier": ["ModuleSpecifier"],
@@ -27,9 +30,6 @@
"FunctionDeclaration": ["Scopable", "Function", "Statement", "Declaration"],
"FunctionExpression": ["Scopable", "Function", "Expression"],
"ImportSpecifier": ["ModuleSpecifier"],
"ExportSpecifier": ["ModuleSpecifier"],
"BlockStatement": ["Scopable", "Statement"],
"Program": ["Scopable"],
"CatchClause": ["Scopable"],

View File

@@ -106,7 +106,7 @@ export function isReferenced(node: Object, parent: Object): boolean {
*/
export function isReferencedIdentifier(node: Object, parent: Object, opts?: Object): boolean {
return t.isIdentifier(node, opts) && t.isReferenced(node, parent);
return (t.isIdentifier(node, opts) || t.isJSXIdentifier(node, opts)) && t.isReferenced(node, parent);
}
/**
@@ -157,14 +157,8 @@ export function isSpecifierDefault(specifier: Object): boolean {
*/
export function isScope(node: Object, parent: Object): boolean {
if (t.isBlockStatement(node)) {
if (t.isLoop(parent, { body: node })) {
return false;
}
if (t.isFunction(parent, { body: node })) {
return false;
}
if (t.isBlockStatement(node) && t.isFunction(parent, { body: node })) {
return false;
}
return t.isScopable(node);

View File

@@ -10,6 +10,7 @@ import contains from "lodash/collection/contains";
import traverse from "./traversal";
import isString from "lodash/lang/isString";
import isRegExp from "lodash/lang/isRegExp";
import Module from "module";
import isEmpty from "lodash/lang/isEmpty";
import parse from "./helpers/parse";
import path from "path";
@@ -38,6 +39,21 @@ export function resolve(loc: string) {
}
}
var relativeMod;
export function resolveRelative(loc: string) {
if (!relativeMod) {
relativeMod = new Module;
relativeMod.paths = Module._nodeModulePaths(process.cwd());
}
try {
return Module._resolveFilename(loc, relativeMod);
} catch (err) {
return null;
}
}
export function list(val: string): Array<string> {
return val ? val.split(",") : [];
}
@@ -74,6 +90,7 @@ var templateVisitor = {
if (t.isExpressionStatement(node)) {
node = node.expression;
}
if (t.isIdentifier(node) && has(nodes, node.name)) {
this.skip();
this.replaceInline(nodes[node.name]);

View File

@@ -33,5 +33,11 @@ suite("api", function () {
assert.ok(script.indexOf("classCallCheck") === -1);
assert.ok(script.indexOf("inherits") >= 0);
});
test("empty whitelist", function () {
var script = buildExternalHelpers([]);
assert.ok(script.indexOf("classCallCheck") === -1);
assert.ok(script.indexOf("inherits") === -1);
});
});
});

View File

@@ -66,7 +66,7 @@ var assertTest = function (stdout, stderr, opts) {
};
var buildTest = function (binName, testName, opts) {
var binLoc = path.normalize(__dirname + "/../../bin/" + binName);
var binLoc = path.normalize(__dirname + "/../../packages/babel-cli/bin/" + binName);
return function (callback) {
this.timeout(5000);

View File

@@ -12,7 +12,10 @@ suite("browserify", function() {
assert.ok(bundle.length, "bundle output code");
// ensure that the code runs without throwing an exception
vm.runInNewContext("var global = this;\n" + bundle, {});
vm.runInNewContext("var global = this;\n" + bundle, {
setInterval: function () {},
setTimeout: function () {}
});
done();
})
})

View File

@@ -1,4 +1,4 @@
import "./bar2";
var foo = () => console.log("foo");
foo();
import "./bar2";

View File

@@ -1,2 +1,2 @@
foo
bar
foo

View File

@@ -1,5 +1,5 @@
"use strict";
export { foo } from "resolved/foo-export-named";
import foo from "resolved/foo-import-default";
import "resolved/foo-import-bare";
export { foo } from "resolved/foo-export-named";

View File

@@ -1,6 +1,6 @@
"use strict";
var _bluebird = require("bluebird");
var _bluebird2 = require("bluebird");
var Foo = (function () {
function Foo() {
@@ -9,7 +9,7 @@ var Foo = (function () {
babelHelpers.createClass(Foo, [{
key: "foo",
value: _bluebird.coroutine(function* () {
value: _bluebird2.coroutine(function* () {
var wat = yield bar();
})
}]);

View File

@@ -1,7 +1,7 @@
"use strict";
var _bluebird = require("bluebird");
var _bluebird2 = require("bluebird");
var foo = _bluebird.coroutine(function* () {
var foo = _bluebird2.coroutine(function* () {
var wat = yield bar();
});
});

View File

@@ -1,10 +1,10 @@
"use strict";
var _bluebird = require("bluebird");
var _bluebird2 = require("bluebird");
var _bar;
var foo = _bar = _bluebird.coroutine(function* () {
var foo = _bar = _bluebird2.coroutine(function* () {
console.log(_bar);
});

View File

@@ -1,7 +1,7 @@
"use strict";
var _bluebird = require("bluebird");
var _bluebird2 = require("bluebird");
var foo = _bluebird.coroutine(function* () {
var foo = _bluebird2.coroutine(function* () {
var wat = yield bar();
});
});

View File

@@ -1,5 +0,0 @@
"use strict";
var _core = require("babel-runtime/es3/core-js")["default"];
_core.Array.isArray(foo);

View File

@@ -1,4 +0,0 @@
{
"optional": ["es3.runtime"],
"stage": 0
}

View File

@@ -1,4 +1,4 @@
assert.equal(() => {
assert.equal((() => {
let sum = 0;
let a = 0;
{
@@ -9,4 +9,4 @@ assert.equal(() => {
}
}
return sum;
}(), 10);
})(), 10);

View File

@@ -1,21 +1,23 @@
"use strict";
(function () {
var _loop = function (i) {
fns.push(function () {
return i;
});
if (i === 1) {
return "continue";
} else if (i === 2) {
return "break";
} else if (i === 3) {
return {
v: i
};
}
};
_loop: for (var i in nums) {
var _ret = (function (i) {
fns.push(function () {
return i;
});
if (i === 1) {
return "continue";
} else if (i === 2) {
return "break";
} else if (i === 3) {
return {
v: i
};
}
})(i);
var _ret = _loop(i);
switch (_ret) {
case "continue":
@@ -28,4 +30,4 @@
if (typeof _ret === "object") return _ret.v;
}
}
})();
})();

View File

@@ -1,12 +1,14 @@
"use strict";
var _loop = function (i) {
fns.push(function () {
return i;
});
return "break";
};
for (var i in nums) {
var _ret = (function (i) {
fns.push(function () {
return i;
});
return "break";
})(i);
var _ret = _loop(i);
if (_ret === "break") break;
}
}

View File

@@ -1,12 +1,14 @@
"use strict";
var _loop = function (_i) {
(function () {
_i;
});
console.log(_i);
_i += 1;
i = _i;
};
for (var i = 0; i < 2; i++) {
(function (_i) {
(function () {
_i;
});
console.log(_i);
_i += 1;
i = _i;
})(i);
}
_loop(i);
}

View File

@@ -1,12 +1,14 @@
"use strict";
var _loop = function (i) {
fns.push(function () {
return i;
});
return "continue";
};
for (var i in nums) {
var _ret = (function (i) {
fns.push(function () {
return i;
});
return "continue";
})(i);
var _ret = _loop(i);
if (_ret === "continue") continue;
}
}

View File

@@ -1,16 +1,18 @@
"use strict";
(function () {
var _loop = function (i) {
fns.push(function () {
return i;
});
return {
v: undefined
};
};
for (var i in nums) {
var _ret = (function (i) {
fns.push(function () {
return i;
});
return {
v: undefined
};
})(i);
var _ret = _loop(i);
if (typeof _ret === "object") return _ret.v;
}
})();
})();

View File

@@ -1,16 +1,18 @@
"use strict";
(function () {
var _loop = function (i) {
fns.push(function () {
return i;
});
return {
v: i
};
};
for (var i in nums) {
var _ret = (function (i) {
fns.push(function () {
return i;
});
return {
v: i
};
})(i);
var _ret = _loop(i);
if (typeof _ret === "object") return _ret.v;
}
})();
})();

View File

@@ -5,17 +5,19 @@ var _didIteratorError = false;
var _iteratorError = undefined;
try {
var _loop = function () {
var i = _step.value;
x = 5;
fns.push(function () {
return i * x;
});
};
for (var _iterator = nums[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var x;
(function () {
var i = _step.value;
x = 5;
fns.push(function () {
return i * x;
});
})();
_loop();
}
} catch (err) {
_didIteratorError = true;
@@ -30,4 +32,4 @@ try {
throw _iteratorError;
}
}
}
}

View File

@@ -0,0 +1,6 @@
let arr = [];
for(let i = 0; i < 10; i++) {
for (let i = 0; i < 10; i++) {
arr.push(() => i);
}
}

View File

@@ -0,0 +1,14 @@
"use strict";
var arr = [];
for (var i = 0; i < 10; i++) {
var _loop = function (_i) {
arr.push(function () {
return _i;
});
};
for (var _i = 0; _i < 10; _i++) {
_loop(_i);
}
}

View File

@@ -1,11 +1,14 @@
"use strict";
var a = 1;
var _loop = function (_a) {
items.forEach(function (item) {
return _a;
});
};
for (var _a = 1; _a < 100; _a++) {
(function (_a) {
items.forEach(function (item) {
return _a;
});
})(_a);
_loop(_a);
}
console.log(a);
console.log(a);

View File

@@ -11,11 +11,46 @@ define(["exports", "foo"], function (exports, _foo) {
_defaults(exports, _interopRequireWildcard(_foo));
exports.foo = _foo.foo;
exports.foo = _foo.foo;
exports.bar = _foo.bar;
exports.bar = _foo.foo;
exports["default"] = _foo.foo;
exports["default"] = _foo.foo;
exports.bar = _foo.bar;
});
Object.defineProperty(exports, "foo", {
enumerable: true,
get: function get() {
return _foo.foo;
}
});
Object.defineProperty(exports, "foo", {
enumerable: true,
get: function get() {
return _foo.foo;
}
});
Object.defineProperty(exports, "bar", {
enumerable: true,
get: function get() {
return _foo.bar;
}
});
Object.defineProperty(exports, "bar", {
enumerable: true,
get: function get() {
return _foo.foo;
}
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function get() {
return _foo.foo;
}
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function get() {
return _foo.foo;
}
});
Object.defineProperty(exports, "bar", {
enumerable: true,
get: function get() {
return _foo.bar;
}
});
});

View File

@@ -3,10 +3,10 @@ define(["exports"], function (exports) {
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
exports.foo7 = foo7;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.foo7 = foo7;
var foo = 1;
exports.foo = foo;
var foo = 1,

View File

@@ -1,20 +1,19 @@
define(["exports", "./evens"], function (exports, _evens) {
"use strict";
exports.nextOdd = nextOdd;
Object.defineProperty(exports, "__esModule", {
value: true
});
var isEven = _evens.isEven;
exports.nextOdd = nextOdd;
function nextOdd(n) {
return isEven(n) ? n + 1 : n + 2;
return _evens.isEven(n) ? n + 1 : n + 2;
}
var isOdd = (function (isEven) {
return function (n) {
return !isEven(n);
};
})(isEven);
})(_evens.isEven);
exports.isOdd = isOdd;
});
});

View File

@@ -1,2 +1,5 @@
import foo from "foo";
import {default as foo2} from "foo";
foo;
foo2;

View File

@@ -3,7 +3,10 @@ define(["exports", "foo"], function (exports, _foo) {
var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
var foo = _interopRequire(_foo);
var _foo2 = _interopRequire(_foo);
var foo2 = _interopRequire(_foo);
});
var _foo22 = _interopRequire(_foo);
_foo2;
_foo22;
});

View File

@@ -1 +1,3 @@
import * as foo from "foo";
foo;

Some files were not shown because too many files have changed in this diff Show More