Compare commits

...

42 Commits

Author SHA1 Message Date
Sebastian McKenzie
5a96c2e015 v1.13.0 2014-11-22 23:46:00 +11:00
Sebastian McKenzie
43390c0d1f add experimental usage note about proposal changes 2014-11-22 23:45:05 +11:00
Sebastian McKenzie
d166656149 add constructor spread caveat and add additional Array.from cases 2014-11-22 23:44:47 +11:00
Sebastian McKenzie
acc4d289e4 link straight to caveats in no runtime on doc index 2014-11-22 23:44:28 +11:00
Sebastian McKenzie
717e6df407 use Array.from on single block array comprehensions - closes #199 2014-11-22 23:44:12 +11:00
Sebastian McKenzie
286404c6f2 update changelog for 1.13.0 2014-11-22 23:33:06 +11:00
Sebastian McKenzie
f191fd7883 update #203 test 2014-11-22 23:32:03 +11:00
Sebastian McKenzie
74f36cfaa0 Merge pull request #202 from RReverser/webworker-runtime
Fix runtime injection in Web Worker.
2014-11-22 23:29:07 +11:00
Sebastian McKenzie
71aed8b269 Merge branch 'ctor-spread-speedup' of https://github.com/RReverser/6to5 2014-11-22 23:28:06 +11:00
Sebastian McKenzie
9e6b0b45b3 Revert "Merge pull request #203 from RReverser/ctor-spread-speedup"
This reverts commit 714ca9fbc8, reversing
changes made to d50d4972a7.
2014-11-22 23:27:39 +11:00
Sebastian McKenzie
7bbb3725d4 bump next release version 2014-11-22 23:26:39 +11:00
Sebastian McKenzie
1210c92405 remove hound.yml 2014-11-22 23:26:39 +11:00
Sebastian McKenzie
714ca9fbc8 Merge pull request #203 from RReverser/ctor-spread-speedup
Speed up constructor spreads.
2014-11-22 23:22:53 +11:00
Ingvar Stepanyan
60713f0e5f Speed up constructor spreads.
Replace slow .bind with manual .create+.apply.
Gives up to 19x speed up depending on browser.

http://jsperf.com/apply-constructor
2014-11-22 14:22:50 +02:00
Ingvar Stepanyan
f1f5f8bb27 Speed up constructor spreads.
Replace slow .bind with manual .create+.apply.
Gives up to 19x speed up depending on browser.

http://jsperf.com/apply-constructor
2014-11-22 14:20:55 +02:00
Ingvar Stepanyan
a69f095720 Fix runtime injection in Web Worker.
Web Workers don't have `window` object but they have `self`
(which is available in regular windows as well).
2014-11-22 14:14:42 +02:00
Sebastian McKenzie
d50d4972a7 use experimental option in generation tests 2014-11-21 19:40:05 +11:00
Sebastian McKenzie
bd91bbee71 put experimental ES7 features behind a flag --experimental and experimental option 2014-11-21 19:36:35 +11:00
Sebastian McKenzie
8b46cce466 v1.12.26 2014-11-21 17:10:54 +11:00
Sebastian McKenzie
defa9108bd support computed property destructuring 2014-11-21 17:09:31 +11:00
Sebastian McKenzie
6b1d9b49b7 use generateUidIdentifier over the long form 2014-11-21 17:09:15 +11:00
Sebastian McKenzie
4e333cf357 add arrayify and regexify tests, add destructuring assignment expression statement only test 2014-11-21 17:08:56 +11:00
Sebastian McKenzie
ddcd7ab28d v1.12.25 2014-11-20 21:30:08 +11:00
Sebastian McKenzie
4b8a4492ba remove unused Scope variable 2014-11-20 21:29:00 +11:00
Sebastian McKenzie
4256a9960c update acorn-6to5 - fixes #195 2014-11-20 21:28:07 +11:00
Sebastian McKenzie
ecb695c30c add 1.12.25 changelog 2014-11-20 21:18:31 +11:00
Sebastian McKenzie
db97f665ed remove scope from generator visitor 2014-11-20 21:18:21 +11:00
Sebastian McKenzie
931b68dc5d use generateUidIdentifier instead of generateUid 2014-11-20 21:18:11 +11:00
Sebastian McKenzie
b5feaf7c2f remove dead code 2014-11-20 21:17:57 +11:00
Sebastian McKenzie
d82683f598 remova via regenerator from features 2014-11-20 21:10:35 +11:00
Sebastian McKenzie
6772f5a74f update ast-types, es6-shim, chokidar, estraverse and private 2014-11-20 21:10:23 +11:00
Sebastian McKenzie
a90f133918 update Scope arguments 2014-11-20 21:09:38 +11:00
Sebastian McKenzie
71ad511322 add File::generateUidIdentifier method 2014-11-20 21:08:33 +11:00
Sebastian McKenzie
ff6677a4b7 v1.12.24 2014-11-20 16:56:29 +11:00
Sebastian McKenzie
ac5e0ad392 add changelog for 1.12.24 2014-11-20 16:54:46 +11:00
Sebastian McKenzie
0a25618c34 collect references that haven't been declared in scope - fixes #173 and fixes #175 2014-11-20 16:53:22 +11:00
Sebastian McKenzie
984c048591 v1.12.23 2014-11-20 16:03:53 +11:00
Sebastian McKenzie
5867e24886 remove unused variables 2014-11-20 16:02:56 +11:00
Sebastian McKenzie
02d7cdc701 changelog for 1.12.23 2014-11-20 16:02:15 +11:00
Sebastian McKenzie
d3b3febfeb finish missing code examples in features 2014-11-20 16:02:10 +11:00
Sebastian McKenzie
7fccf98c10 small performance improvements 2014-11-20 15:09:20 +11:00
Sebastian McKenzie
4a1c393bdb inherit generator comments and add block hoisting - fixes #196 2014-11-20 15:09:07 +11:00
42 changed files with 411 additions and 272 deletions

View File

@@ -1,3 +0,0 @@
java_script:
enabled: true
config_file: .jshintrc

View File

@@ -1,3 +1,25 @@
# 1.13.0
* Put experimental ES7 features behind a flag `--experimental` and `experimental` option.
* Constructor speed performance increase. Thanks [@RReverser](https://github.com/RReverser).
* Use `self` instead of `window` in the optional 6to5 runtime. Thanks [@RReverser](https://github.com/RReverser).
# 1.12.26
* Support computed property destructuring.
# 1.12.25
* Update `acorn-6to5`, `ast-types`, `es6-shim`, `chokidar`, `estraverse` and `private`.
# 1.12.24
* Collect references that haven't been declared in scope.
# 1.12.23
* Fix generator function export hoisting.
# 1.12.22
* Update `fs-readdir-recursive` and `chokidar`.

View File

@@ -11,6 +11,7 @@ commander.option("-s, --source-maps", "Save source map alongside the compiled co
commander.option("-f, --filename [filename]", "Filename to use when reading from stdin - this will be used in source-maps, errors etc [stdin]", "stdin");
commander.option("-w, --watch", "Recompile files on changes");
commander.option("-r, --runtime", "Replace 6to5 declarations with references to a runtime");
commander.option("-e, --experimental", "Enable experimental support for proposed ES7 features");
commander.option("-m, --modules [modules]", "Module formatter type to use [common]", "common");
commander.option("-w, --whitelist [whitelist]", "Whitelist of transformers to ONLY use", util.list);
@@ -87,11 +88,12 @@ if (errors.length) {
exports.opts = {
sourceMapName: commander.outFile,
amdModuleIds: commander.amdModuleIds,
experimental: commander.experimental,
blacklist: commander.blacklist,
whitelist: commander.whitelist,
sourceMap: commander.sourceMaps || commander.sourceMapsInline,
comments: !commander.removeComments,
amdModuleIds: commander.amdModuleIds,
runtime: commander.runtime,
modules: commander.modules
};

View File

@@ -8,10 +8,11 @@ var util = require("../lib/6to5/util");
var vm = require("vm");
var _ = require("lodash");
commander.option("-e, --eval [script]", "evaluate script");
commander.option("-p, --print", "evaluate script and print result");
commander.option("-i, --ignore [regex]", "ignore all files that match this regex when using the require hook");
commander.option("-x, --extensions [extensions]", "list of extensions to hook into [.es6,.js]", util.list);
commander.option("-e, --eval [script]", "Evaluate script");
commander.option("-p, --print", "Evaluate script and print result");
commander.option("-i, --ignore [regex]", "Ignore all files that match this regex when using the require hook");
commander.option("-x, --extensions [extensions]", "List of extensions to hook into [.es6,.js]");
commander.option("-r, --experimental", "Enable experimental support for proposed ES7 features");
var pkg = require("../package.json");
commander.version(pkg.version);
@@ -20,17 +21,11 @@ commander.parse(process.argv);
//
var registerOpts = {};
if (commander.ignore) {
registerOpts.ignoreRegex = new RegExp(commander.ignore);
}
if (commander.extensions && commander.extensions.length) {
registerOpts.extensions = commander.extensions;
}
to5.register(registerOpts);
to5.register({
experimental: commander.experimental,
extensions: commander.extensions,
ignore: commander.ignore
});
//

View File

@@ -5,6 +5,16 @@
The [regenerator runtime](https://github.com/facebook/regenerator/blob/master/runtime.js)
and an [ES6 polyfill](polyfill.md) are required in order for generators to work.
### Async/Comprehensions
[Experimental support](usage.md#experimental) must be enabled for these proposed
ES7 features to work.
### Array comprehension/Array destructuring/Spread
An [ES6 polyfill](polyfill.md) is required. More specifically a polyfill for
`Array.from`.
## Classes
Built-in classes such as `Date`, `Array` and `DOM` cannot be subclassed due to
@@ -31,13 +41,13 @@ class Bar extends Foo {
}
```
## Constructor spread
Constructor spreads do not currently support built-ins. ie.
`new Array(...items)`.
## For-of
A polyfill is required for for-of functionality that implements `Symbol` and
adds `prototype[Symbol.iterator]` behaviour to built-ins. Using the polyfills
specified in [polyfill](polyfill.md) suffices.
### Array destructuring / Spread
An [ES6 polyfill](polyfill.md) is required for spread and array destructuring.
More specifically a polyfill for `Array.from`.

View File

@@ -1,6 +1,6 @@
# Features
## Array comprehension
## Array comprehension ([experimental](usage.md#experimental))
```javascript
var results = [for (c of customers) if (c.city == "Seattle") { name: c.name, age: c.age }]
@@ -31,7 +31,7 @@ var bob = {
};
```
## Async functions
## Async functions ([experimental](usage.md#experimental))
```javascript
async function chainAnimationsAsync(elem, animations) {
@@ -133,13 +133,31 @@ for (var i of [1, 2, 3]) {
## Generators
```javascript
function* fibonacci() {
var pre = 0, cur = 1;
for (;;) {
var temp = pre;
pre = cur;
cur += temp;
yield cur;
}
}
for (var n of fibonacci()) {
// truncate the sequence at 1000
if (n > 1000) break;
console.log(n);
}
```
## Generator comprehension
## Generator comprehension ([experimental](usage.md#experimental))
```javascript
var nums = [1, 2, 3, 4, 5, 6];
var multiples = (for (i of nums) if (i % 2) i * i);
assert.equal(multiples.next().value, 1);
assert.equal(multiples.next().value, 9);
assert.equal(multiples.next().value, 25);
```
## Let scoping
@@ -153,7 +171,17 @@ for (let i in arr) {
## Modules
```javascript
import "foo";
import foo from "foo";
import * as foo from "foo";
import {bar} from "foo";
import {foo as bar} from "foo";
export { test };
export var test = 5;
export function test() {}
export default test;
```
## Numeric literals

View File

@@ -3,7 +3,7 @@
- **Readable** - formatting is retained if possible so your generated code is as similar as possible.
- **Extensible** - with a large range of [plugins](plugins.md) and **browser support**.
- **Lossless** - **source map support** so you can debug your compiled code with ease.
- **Compact** - maps directly to the equivalent ES5 with **no runtime**[\*](caveats.md#generators).
- **Compact** - maps directly to the equivalent ES5 with **no runtime**[\*](caveats.md).
## Installation
@@ -31,8 +31,8 @@ And it doesn't end here! To see all the ways you can use 6to5, check out the
## [Features](features.md)
- [Array comprehension](features.md#array-comprehension)
- [Async functions](features.md#async-functions) via [regenerator](https://github.com/facebook/regenerator)
- [Array comprehension](features.md#array-comprehension) ([experimental](usage.md#experimental))
- [Async functions](features.md#async-functions) ([experimental](usage.md#experimental))
- [Arrow functions](features.md#arrow-functions)
- [Classes](features.md#classes)
- [Computed property names](features.md#computed-property-names)
@@ -40,8 +40,8 @@ And it doesn't end here! To see all the ways you can use 6to5, check out the
- [Default parameters](features.md#default-parameters)
- [Destructuring](features.md#destructuring)
- [For-of](features.md#for-of)
- [Generators](features.md#generators) via [regenerator](https://github.com/facebook/regenerator)
- [Generator comprehension](features.md#generator-comprehension)
- [Generators](features.md#generators)
- [Generator comprehension](features.md#generator-comprehension) ([experimental](usage.md#experimental))
- [Let scoping](features.md#let-scoping)
- [Modules](features.md#modules)
- [Numeric literals](features.md#numeric-literals)

View File

@@ -135,7 +135,11 @@ to5.transformFile("filename.js", options, function (err, result) {
// Output comments in generated output
// Default: true
comments: false
comments: false,
// Enable support for experimental ES7 features
// Default: false
experimental: true
}
```
@@ -181,3 +185,11 @@ require("6to5/register")({
extensions: [".js", ".es6"]
});
```
## Experimental
6to5 also has experimental support for ES7 proposals. You can enable this with
the `experimental: true` option when using the [Node API](#node) or
`--experimental` when using the [CLI](#cli).
**NOTE:** That these are subject to change as their proposal status progresses.

View File

@@ -25,15 +25,16 @@ File.normaliseOptions = function (opts) {
opts = _.cloneDeep(opts || {});
_.defaults(opts, {
whitespace: true,
blacklist: [],
whitelist: [],
sourceMap: false,
comments: true,
filename: "unknown",
modules: "common",
runtime: false,
code: true
experimental: false,
whitespace: true,
blacklist: [],
whitelist: [],
sourceMap: false,
comments: true,
filename: "unknown",
modules: "common",
runtime: false,
code: true
});
// normalise windows path separators to unix
@@ -147,7 +148,7 @@ File.prototype.parse = function (code) {
File.prototype.transform = function (ast) {
this.ast = ast;
this.scope = new Scope(null, ast.program);
this.scope = new Scope(ast.program);
var self = this;
@@ -196,6 +197,10 @@ File.prototype.generateUid = function (name, scope) {
return uid;
};
File.prototype.generateUidIdentifier = function (name, scope) {
return t.identifier(this.generateUid(name, scope));
};
File.prototype._generateUid = function (name) {
var uids = this.uids;
var i = uids[name] || 1;

View File

@@ -57,24 +57,25 @@ blacklistTest("unicodeRegex", function () { new RegExp("foo", "u"); });
//
var ignoreRegex = /node_modules/;
var transformOpts = {};
var ignoreRegex = /node_modules/;
var onlyRegex;
var whitelist = [];
var exts = {};
var maps = {};
var old = require.extensions[".js"];
var whitelist = [];
var exts = {};
var maps = {};
var old = require.extensions[".js"];
var loader = function (m, filename) {
if ((ignoreRegex && ignoreRegex.test(filename)) || (onlyRegex && !onlyRegex.test(filename))) {
return old.apply(this, arguments);
}
var result = to5.transformFileSync(filename, {
var result = to5.transformFileSync(filename, _.extend({
whitelist: whitelist,
blacklist: blacklist,
sourceMap: true,
modules: "commonInterop"
});
}, transformOpts));
maps[filename] = result.map;
@@ -107,6 +108,5 @@ module.exports = function (opts) {
if (opts.extensions) hookExtensions(util.arrayify(opts.extensions));
if (opts.blacklist) blacklist = util.arrayify(opts.blacklist);
if (opts.whitelist) whitelist = util.arrayify(opts.whitelist);
_.extend(transformOpts, opts);
};

View File

@@ -8,15 +8,13 @@ module.exports = function (namespace) {
namespace = t.identifier(t.toIdentifier(namespace || "to5Runtime"));
var body = [];
var container = t.functionExpression(null, [], t.blockStatement(body));
var tree = t.program([t.expressionStatement(t.callExpression(container, []))]);
body.push(util.template("self-global", true));
var container = t.functionExpression(null, [t.identifier("global")], t.blockStatement(body));
var tree = t.program([t.expressionStatement(t.callExpression(container, [util.template("self-global")]))]);
body.push(t.variableDeclaration("var", [
t.variableDeclarator(
namespace,
t.assignmentExpression("=", t.memberExpression(t.identifier("self"), namespace), t.objectExpression([]))
t.assignmentExpression("=", t.memberExpression(t.identifier("global"), namespace), t.objectExpression([]))
)
]));

View File

@@ -1,5 +1,5 @@
(function (Constructor, args) {
var bindArgs = [null].concat(args);
var Factory = Constructor.bind.apply(Constructor, bindArgs);
return new Factory;
var instance = Object.create(Constructor.prototype);
Constructor.apply(instance, args);
return instance;
});

View File

@@ -1 +1 @@
var self = typeof global === "undefined" ? window : global;
typeof global === "undefined" ? self : global

View File

@@ -78,7 +78,7 @@ AMDFormatter.prototype._push = function (node) {
if (ids[id]) {
return ids[id];
} else {
return this.ids[id] = t.identifier(this.file.generateUid(id));
return this.ids[id] = this.file.generateUidIdentifier(id);
}
};

View File

@@ -22,8 +22,7 @@ CommonJSInteropFormatter.prototype.importSpecifier = function (specifier, node,
})])
)
]));
return;
} else {
CommonJSFormatter.prototype.importSpecifier.apply(this, arguments);
}
CommonJSFormatter.prototype.importSpecifier.apply(this, arguments);
};

View File

@@ -6,11 +6,11 @@ var go = function (getBody, node, file, scope) {
var thisId;
var getArgumentsId = function () {
return argumentsId = argumentsId || t.identifier(file.generateUid("arguments", scope));
return argumentsId = argumentsId || file.generateUidIdentifier("arguments", scope);
};
var getThisId = function () {
return thisId = thisId || t.identifier(file.generateUid("this", scope));
return thisId = thisId || file.generateUidIdentifier("this", scope);
};
// traverse the function and find all alias functions so we can alias

View File

@@ -1,12 +1,12 @@
var t = require("../../types");
var _ = require("lodash");
module.exports = function (ast, file) {
var body = ast.program.body;
_.each(file.declarations, function (declar) {
for (var i in file.declarations) {
var declar = file.declarations[i];
body.unshift(t.variableDeclaration("var", [
t.variableDeclarator(declar.uid, declar.node)
]));
});
}
};

View File

@@ -2,16 +2,21 @@ var util = require("../../util");
var t = require("../../types");
var _ = require("lodash");
var singleArrayExpression = function (node) {
var single = function (node) {
var block = node.blocks[0];
var templateName = "array-expression-comprehension-map";
if (node.filter) templateName = "array-expression-comprehension-filter";
var right = block.right;
if (!t.isArrayExpression(right)) {
right = util.template("array-from", { VALUE: right });
}
var result = util.template(templateName, {
STATEMENT: node.body,
FILTER: node.filter,
ARRAY: block.right,
ARRAY: right,
KEY: block.left
});
@@ -25,7 +30,7 @@ var singleArrayExpression = function (node) {
};
var multiple = function (node, file) {
var uid = file.generateUid("arr");
var uid = file.generateUidIdentifier("arr");
var container = util.template("array-comprehension-container", {
KEY: uid
@@ -73,8 +78,8 @@ exports._build = function (node, buildBody) {
exports.ComprehensionExpression = function (node, parent, file) {
if (node.generator) return;
if (node.blocks.length === 1 && t.isArrayExpression(node.blocks[0].right)) {
return singleArrayExpression(node);
if (node.blocks.length === 1) {
return single(node);
} else {
return multiple(node, file);
}

View File

@@ -36,7 +36,7 @@ function Class(node, file, scope) {
this.instanceMutatorMap = {};
this.staticMutatorMap = {};
this.hasConstructor = false;
this.className = node.id || t.identifier(file.generateUid("class", scope));
this.className = node.id || file.generateUidIdentifier("class", scope);
this.superName = node.superClass;
}
@@ -58,7 +58,7 @@ Class.prototype.run = function () {
superClassArgument = superClassCallee = getMemberExpressionObject(superName);
} else if (!t.isIdentifier(superName)) {
superClassArgument = superName;
superClassCallee = superName = t.identifier(file.generateUid("ref", this.scope));
superClassCallee = superName = file.generateUidIdentifier("ref", this.scope);
}
}

View File

@@ -27,7 +27,7 @@ var push = function (opts, nodes, elem, parentId) {
var pushObjectPattern = function (opts, nodes, pattern, parentId) {
_.each(pattern.properties, function (prop) {
var pattern2 = prop.value;
var patternId2 = t.memberExpression(parentId, prop.key);
var patternId2 = t.memberExpression(parentId, prop.key, prop.computed);
if (t.isPattern(pattern2)) {
push(opts, nodes, pattern2, patternId2);
@@ -38,7 +38,7 @@ var pushObjectPattern = function (opts, nodes, pattern, parentId) {
};
var pushArrayPattern = function (opts, nodes, pattern, parentId) {
var _parentId = t.identifier(opts.file.generateUid("ref", opts.scope));
var _parentId = opts.file.generateUidIdentifier("ref", opts.scope);
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(_parentId, util.template("array-from", {
VALUE: parentId
@@ -77,7 +77,7 @@ var pushPattern = function (opts) {
var scope = opts.scope;
if (!t.isMemberExpression(parentId) && !t.isIdentifier(parentId)) {
var key = t.identifier(file.generateUid("ref", scope));
var key = file.generateUidIdentifier("ref", scope);
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(key, parentId)
@@ -97,7 +97,7 @@ exports.ForOfStatement = function (node, parent, file, scope) {
var pattern = declar.declarations[0].id;
if (!t.isPattern(pattern)) return;
var key = t.identifier(file.generateUid("ref", scope));
var key = file.generateUidIdentifier("ref", scope);
node.left = t.variableDeclaration(declar.kind, [
t.variableDeclarator(key, null)
]);
@@ -125,7 +125,7 @@ exports.Function = function (node, parent, file, scope) {
if (!t.isPattern(pattern)) return pattern;
hasDestructuring = true;
var parentId = t.identifier(file.generateUid("ref", scope));
var parentId = file.generateUidIdentifier("ref", scope);
pushPattern({
kind: "var",
@@ -155,7 +155,7 @@ exports.ExpressionStatement = function (node, parent, file, scope) {
var nodes = [];
var ref = t.identifier(file.generateUid("ref", scope));
var ref = file.generateUidIdentifier("ref", scope);
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(ref, expr.right)
]));

View File

@@ -5,7 +5,7 @@ exports.ForOfStatement = function (node, parent, file, scope) {
var left = node.left;
var declar;
var stepKey = t.identifier(file.generateUid("step", scope));
var stepKey = file.generateUidIdentifier("step", scope);
var stepValue = t.memberExpression(stepKey, t.identifier("value"));
if (t.isIdentifier(left)) {
@@ -19,7 +19,7 @@ exports.ForOfStatement = function (node, parent, file, scope) {
}
var node2 = util.template("for-of", {
ITERATOR_KEY: file.generateUid("iterator", scope),
ITERATOR_KEY: file.generateUidIdentifier("iterator", scope),
STEP_KEY: stepKey,
OBJECT: node.right
});

View File

@@ -18,170 +18,172 @@ var runtimeAsyncMethod = runtimeProperty("async");
var runtimeWrapMethod = runtimeProperty("wrap");
var runtimeMarkMethod = runtimeProperty("mark");
exports.transform = function transform(node) {
return types.visit(node, visitor);
exports.transform = function transform(node, file) {
return types.visit(node, {
visitFunction: function (path) {
return visitor.call(this, path, file);
}
});
};
var visitor = types.PathVisitor.fromMethodsObject({
visitFunction: function (path) {
// Calling this.traverse(path) first makes for a post-order traversal.
this.traverse(path);
var visitor = function (path, file) {
// Calling this.traverse(path) first makes for a post-order traversal.
this.traverse(path);
var node = path.value;
var node = path.value;
var scope; // we need to actually get the current scope
if (!node.generator && !node.async) {
if (!node.generator && !node.async) {
return;
}
node.generator = false;
if (node.expression) {
// Transform expression lambdas into normal functions.
node.expression = false;
node.body = t.blockStatement([
t.returnStatement(node.body)
]);
}
if (node.async) {
awaitVisitor.visit(path.get("body"));
}
var outerFnId = node.id || (
node.id = file.generateUidIdentifier("callee", scope)
);
var innerFnId = t.identifier(node.id.name + "$");
var contextId = file.generateUidIdentifier("context$", scope);
var vars = hoist(path);
var emitter = new Emitter(contextId);
emitter.explode(path.get("body"));
var outerBody = [];
if (vars && vars.declarations.length > 0) {
outerBody.push(vars);
}
var wrapArgs = [
emitter.getContextFunction(innerFnId),
// Async functions don't care about the outer function because they
// don't need it to be marked and don't inherit from its .prototype.
node.async ? t.literal(null) : outerFnId,
t.thisExpression()
];
var tryEntryList = emitter.getTryEntryList();
if (tryEntryList) {
wrapArgs.push(tryEntryList);
}
var wrapCall = t.callExpression(
node.async ? runtimeAsyncMethod : runtimeWrapMethod,
wrapArgs
);
outerBody.push(t.returnStatement(wrapCall));
node.body = t.blockStatement(outerBody);
if (node.async) {
node.async = false;
return;
}
if (t.isFunctionDeclaration(node)) {
var pp = path.parent;
while (pp && !(t.isBlockStatement(pp.value) || t.isProgram(pp.value))) {
pp = pp.parent;
}
if (!pp) {
return;
}
node.generator = false;
// Here we turn the FunctionDeclaration into a named
// FunctionExpression that will be assigned to a variable of the
// same name at the top of the enclosing block. This is important
// for a very subtle reason: named function expressions can refer to
// themselves by name without fear that the binding may change due
// to code executing outside the function, whereas function
// declarations are vulnerable to the following rebinding:
//
// function f() { return f }
// var g = f;
// f = "asdf";
// g(); // "asdf"
//
// One way to prevent the problem illustrated above is to transform
// the function declaration thus:
//
// var f = function f() { return f };
// var g = f;
// f = "asdf";
// g(); // f
// g()()()()(); // f
//
// In the code below, we transform generator function declarations
// in the following way:
//
// gen().next(); // { value: gen, done: true }
// function *gen() {
// return gen;
// }
//
// becomes something like
//
// var gen = runtime.mark(function *gen() {
// return gen;
// });
// gen().next(); // { value: gen, done: true }
//
// which ensures that the generator body can always reliably refer
// to gen by name.
if (node.expression) {
// Transform expression lambdas into normal functions.
node.expression = false;
node.body = t.blockStatement([
t.returnStatement(node.body)
]);
}
// Remove the FunctionDeclaration so that we can add it back as a
// FunctionExpression passed to runtime.mark.
path.replace();
if (node.async) {
awaitVisitor.visit(path.get("body"));
}
// Change the type of the function to be an expression instead of a
// declaration. Note that all the other fields are the same.
node.type = "FunctionExpression";
var outerFnId = node.id || (
node.id = path.scope.parent.declareTemporary("callee$")
);
var varDecl = t.variableDeclaration("var", [
t.variableDeclarator(
node.id,
t.callExpression(runtimeMarkMethod, [node])
)
]);
var innerFnId = t.identifier(node.id.name + "$");
var contextId = path.scope.declareTemporary("context$");
var vars = hoist(path);
// Copy any comments preceding the function declaration to the
// variable declaration, to avoid weird formatting consequences.
t.inheritsComments(varDecl, node);
t.removeComments(node);
var emitter = new Emitter(contextId);
emitter.explode(path.get("body"));
varDecl._blockHoist = true;
var outerBody = [];
var bodyPath = pp.get("body");
var bodyLen = bodyPath.value.length;
if (vars && vars.declarations.length > 0) {
outerBody.push(vars);
}
var wrapArgs = [
emitter.getContextFunction(innerFnId),
// Async functions don't care about the outer function because they
// don't need it to be marked and don't inherit from its .prototype.
node.async ? t.literal(null) : outerFnId,
t.thisExpression()
];
var tryEntryList = emitter.getTryEntryList();
if (tryEntryList) {
wrapArgs.push(tryEntryList);
}
var wrapCall = t.callExpression(
node.async ? runtimeAsyncMethod : runtimeWrapMethod,
wrapArgs
);
outerBody.push(t.returnStatement(wrapCall));
node.body = t.blockStatement(outerBody);
if (node.async) {
node.async = false;
return;
}
if (t.isFunctionDeclaration(node)) {
var pp = path.parent;
while (pp && !(t.isBlockStatement(pp.value) || t.isProgram(pp.value))) {
pp = pp.parent;
}
if (!pp) {
for (var i = 0; i < bodyLen; ++i) {
var firstStmtPath = bodyPath.get(i);
if (!shouldNotHoistAbove(firstStmtPath)) {
firstStmtPath.insertBefore(varDecl);
return;
}
// Here we turn the FunctionDeclaration into a named
// FunctionExpression that will be assigned to a variable of the
// same name at the top of the enclosing block. This is important
// for a very subtle reason: named function expressions can refer to
// themselves by name without fear that the binding may change due
// to code executing outside the function, whereas function
// declarations are vulnerable to the following rebinding:
//
// function f() { return f }
// var g = f;
// f = "asdf";
// g(); // "asdf"
//
// One way to prevent the problem illustrated above is to transform
// the function declaration thus:
//
// var f = function f() { return f };
// var g = f;
// f = "asdf";
// g(); // f
// g()()()()(); // f
//
// In the code below, we transform generator function declarations
// in the following way:
//
// gen().next(); // { value: gen, done: true }
// function *gen() {
// return gen;
// }
//
// becomes something like
//
// var gen = runtime.mark(function *gen() {
// return gen;
// });
// gen().next(); // { value: gen, done: true }
//
// which ensures that the generator body can always reliably refer
// to gen by name.
// Remove the FunctionDeclaration so that we can add it back as a
// FunctionExpression passed to runtime.mark.
path.replace();
// Change the type of the function to be an expression instead of a
// declaration. Note that all the other fields are the same.
node.type = "FunctionExpression";
var varDecl = t.variableDeclaration("var", [
t.variableDeclarator(
node.id,
t.callExpression(runtimeMarkMethod, [node])
)
]);
if (node.comments) {
// Copy any comments preceding the function declaration to the
// variable declaration, to avoid weird formatting consequences.
varDecl.comments = node.comments;
node.comments = null;
}
var bodyPath = pp.get("body");
var bodyLen = bodyPath.value.length;
for (var i = 0; i < bodyLen; ++i) {
var firstStmtPath = bodyPath.get(i);
if (!shouldNotHoistAbove(firstStmtPath)) {
firstStmtPath.insertBefore(varDecl);
return;
}
}
bodyPath.push(varDecl);
} else {
t.assertFunctionExpression(node);
return t.callExpression(runtimeMarkMethod, [node]);
}
bodyPath.push(varDecl);
} else {
t.assertFunctionExpression(node);
return t.callExpression(runtimeMarkMethod, [node]);
}
});
};
function shouldNotHoistAbove(stmtPath) {
var value = stmtPath.value;

View File

@@ -129,7 +129,7 @@ LetScoping.prototype.run = function () {
// build a call and a unique id that we can assign the return value to
var call = t.callExpression(fn, params);
var ret = t.identifier(this.file.generateUid("ret", this.scope));
var ret = this.file.generateUidIdentifier("ret", this.scope);
var hasYield = traverse.hasType(fn.body, "YieldExpression", t.FUNCTION_TYPES);
if (hasYield) {
@@ -445,7 +445,7 @@ LetScoping.prototype.buildHas = function (ret, call) {
if (has.hasBreak || has.hasContinue) {
// ensure that the parent has a label as we're building a switch and we
// need to be able to access it
var label = forParent.label = forParent.label || t.identifier(this.file.generateUid("loop", this.scope));
var label = forParent.label = forParent.label || this.file.generateUidIdentifier("loop", this.scope);
if (has.hasBreak) {
cases.push(t.switchCase(t.literal("break"), [t.breakStatement(label)]));

View File

@@ -22,9 +22,7 @@ exports.TaggedTemplateExpression = function (node, parent, file) {
t.arrayExpression(raw)
]));
_.each(quasi.expressions, function (expr) {
args.push(expr);
});
args = args.concat(quasi.expressions);
return t.callExpression(node.tag, args);
};

View File

@@ -55,7 +55,7 @@ function traverse(parent, callbacks, opts) {
//
var opts2 = { scope: opts.scope, blacklist: opts.blacklist };
if (t.isScope(node)) opts2.scope = new Scope(opts.scope, node);
if (t.isScope(node)) opts2.scope = new Scope(node, opts.scope);
// enter
if (callbacks.enter) {
@@ -89,9 +89,10 @@ function traverse(parent, callbacks, opts) {
traverse.removeProperties = function (tree) {
var clear = function (node) {
delete node._scopeReferences;
delete node.extendedRange;
delete node._scopeIds;
delete node._parent;
delete node._scope;
delete node.tokens;
delete node.range;
delete node.start;

View File

@@ -6,25 +6,30 @@ var _ = require("lodash");
var FOR_KEYS = ["left", "init"];
function Scope(parent, block) {
/**
* This searches the current "scope" and collects all references/declarations
* within.
*
* @param {Node} block
* @param {Scope} [parent]
*/
function Scope(block, parent) {
this.parent = parent;
this.block = block;
this.info = this.getInfo();
this.declarations = this.info.declarations;
this.references = this.getReferences();
}
Scope.prototype.getInfo = function () {
Scope.prototype.getReferences = function () {
var block = this.block;
if (block._scope) return block._scope;
if (block._scopeReferences) return block._scopeReferences;
var self = this;
var info = block._scope = {
declarations: {}
};
var self = this;
var references = block._scopeReferences = {};
var add = function (node) {
self.addDeclaration(node, info.declarations);
self.add(node, references);
};
// ForStatement - left, init
@@ -56,7 +61,7 @@ Scope.prototype.getInfo = function () {
// Program, Function - var variables
if (t.isProgram(block) || t.isFunction(block)) {
traverse(block, function (node) {
traverse(block, function (node, parent, scope) {
if (t.isFor(node)) {
_.each(FOR_KEYS, function (key) {
var declar = node[key];
@@ -68,12 +73,16 @@ Scope.prototype.getInfo = function () {
// declared within are accessible
if (t.isFunction(node)) return false;
if (t.isIdentifier(node) && t.isReferenced(node, parent) && !scope.has(node.name)) {
add(node);
}
// we've ran into a declaration!
// we'll let the BlockStatement scope deal with `let` declarations
if (t.isDeclaration(node) && !t.isLet(node)) {
add(node);
}
});
}, { scope: this });
}
// Function - params, rest
@@ -85,12 +94,12 @@ Scope.prototype.getInfo = function () {
});
}
return info;
return references;
};
Scope.prototype.addDeclaration = function (node, declarations) {
Scope.prototype.add = function (node, references) {
if (!node) return;
_.merge(declarations || this.declarations, t.getIds(node, true));
_.merge(references || this.references, t.getIds(node, true));
};
Scope.prototype.get = function (id) {
@@ -98,7 +107,7 @@ Scope.prototype.get = function (id) {
};
Scope.prototype.getOwn = function (id) {
return _.has(this.declarations, id) && this.declarations[id];
return _.has(this.references, id) && this.references[id];
};
Scope.prototype.parentGet = function (id) {

View File

@@ -250,6 +250,11 @@ t.inheritsComments = function (child, parent) {
return child;
};
t.removeComments = function (node) {
delete node.leadingComments;
delete node.trailingComments;
};
t.inherits = function (child, parent) {
child.loc = parent.loc;
child.end = parent.end;

View File

@@ -65,7 +65,7 @@ exports.getUid = function (parent, file) {
if (t.isIdentifier(node)) id = node.name;
return t.identifier(file.generateUid(id));
return file.generateUidIdentifier(id);
};
exports.isAbsolute = function (loc) {
@@ -218,7 +218,7 @@ exports.parse = function (opts, code, callback) {
var ast = acorn.parse(code, {
allowReturnOutsideFunction: true,
preserveParens: true,
ecmaVersion: Infinity,
ecmaVersion: opts.experimental ? 7 : 6,
strictMode: true,
onComment: comments,
locations: true,

View File

@@ -1,7 +1,7 @@
{
"name": "6to5",
"description": "Turn ES6 code into readable vanilla ES5 with source maps",
"version": "1.12.22",
"version": "1.13.0",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://github.com/6to5/6to5",
"repository": {
@@ -35,21 +35,21 @@
"test": "make test"
},
"dependencies": {
"ast-types": "~0.6.0",
"ast-types": "0.6.5",
"commander": "2.5.0",
"fs-readdir-recursive": "0.1.0",
"lodash": "2.4.1",
"mkdirp": "0.5.0",
"es6-shim": "0.20.2",
"es6-shim": "0.20.3",
"es6-symbol": "0.1.1",
"regexpu": "0.3.0",
"source-map": "0.1.40",
"chokidar": "0.11.0",
"chokidar": "0.11.1",
"source-map-support": "0.2.8",
"esutils": "1.1.4",
"acorn-6to5": "0.9.1-2",
"estraverse": "^1.7.0",
"private": "^0.1.6"
"acorn-6to5": "0.9.1-3",
"estraverse": "1.8.0",
"private": "0.1.6"
},
"devDependencies": {
"istanbul": "0.3.2",

View File

@@ -0,0 +1,3 @@
{
"experimental": true
}

View File

@@ -0,0 +1 @@
var arr = [for (i of nums) if (i > 1) i * i];

View File

@@ -0,0 +1,7 @@
"use strict";
var arr = Array.from(nums).filter(function (i) {
return i > 1;
}).map(function (i) {
return i * i;
});

View File

@@ -0,0 +1 @@
var arr = [for (i of nums) i * i];

View File

@@ -0,0 +1,5 @@
"use strict";
var arr = Array.from(nums).map(function (i) {
return i * i;
});

View File

@@ -1,3 +1,4 @@
{
"asyncExec": true
"asyncExec": true,
"experimental": true
}

View File

@@ -0,0 +1 @@
console.log([x] = [1]);

View File

@@ -0,0 +1,3 @@
{
"throws": "AssignmentExpression destructuring outside of a ExpressionStatement is forbidden due to current 6to5 limitations"
}

View File

@@ -0,0 +1,3 @@
{
"experimental": true
}

View File

@@ -1,5 +1,5 @@
var Component = React.createClass({
render: function () {
return null;
return null;
}
});

View File

@@ -1,11 +1,11 @@
"use strict";
var _applyConstructor = function (Constructor, args) {
var bindArgs = [null].concat(args);
var instance = Object.create(Constructor.prototype);
var Factory = Constructor.bind.apply(Constructor, bindArgs);
Constructor.apply(instance, args);
return new Factory();
return instance;
};
_applyConstructor(Numbers, Array.from(nums));

View File

@@ -26,7 +26,7 @@ _.each(helper.get("generation"), function (testSuite) {
var expect = task.expect;
var actual = task.actual;
var actualAst = util.parse({ filename: actual.loc }, actual.code);
var actualAst = util.parse({ filename: actual.loc, experimental: true }, actual.code);
var actualCode = generate(actualAst, null, actual.code).code;
chai.expect(actualCode).to.equal(expect.code, actual.loc + " !== " + expect.loc);

View File

@@ -3,8 +3,6 @@ var util = require("../lib/6to5/util");
var t = require("../lib/6to5/types");
suite("util", function () {
test("duplicate mutator map");
test("invalid template", function () {
assert.throws(function () {
util.template("invalid template");
@@ -45,6 +43,34 @@ suite("util", function () {
assert.deepEqual(util.list("foo,bar"), ["foo", "bar"]);
});
test("arrayify", function () {
assert.deepEqual(util.arrayify(undefined), []);
assert.deepEqual(util.arrayify(false), []);
assert.deepEqual(util.arrayify(null), []);
assert.deepEqual(util.arrayify(""), []);
assert.deepEqual(util.arrayify("foo"), ["foo"]);
assert.deepEqual(util.arrayify("foo,bar"), ["foo", "bar"]);
assert.deepEqual(util.arrayify(["foo", "bar"]), ["foo", "bar"]);
assert.throws(function () {
util.arrayify({});
}, /illegal type for arrayify/);
});
test("regexify", function () {
assert.deepEqual(util.regexify(undefined), /(?:)/);
assert.deepEqual(util.regexify(false), /(?:)/);
assert.deepEqual(util.regexify(null), /(?:)/);
assert.deepEqual(util.regexify(""), /(?:)/);
assert.deepEqual(util.regexify(["foo", "bar"]), /foo|bar/);
assert.deepEqual(util.regexify("foobar"), /foobar/);
assert.deepEqual(util.regexify(/foobar/), /foobar/);
assert.throws(function () {
util.regexify({});
}, /illegal type for regexify/);
});
test("getIds");
test("toStatement");