Compare commits

...

46 Commits

Author SHA1 Message Date
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
Sebastian McKenzie
afaf3fb0c0 v1.12.22 2014-11-20 00:51:26 +11:00
Sebastian McKenzie
2152ae9b17 remove unused kind variable 2014-11-20 00:50:18 +11:00
Sebastian McKenzie
b8f5693b5e add 1.12.22 changelog 2014-11-20 00:49:27 +11:00
Sebastian McKenzie
638143700b add whitespace around defineArgs 2014-11-20 00:49:12 +11:00
Sebastian McKenzie
aa7eb9c1c9 remove unused opts arg 2014-11-20 00:49:01 +11:00
Sebastian McKenzie
27ca532896 add 1.12.22 changelog 2014-11-20 00:44:12 +11:00
Sebastian McKenzie
913fbdbd87 Merge pull request #190 from webpro/amd-module-id
Make AMD module id's optional
2014-11-20 00:42:53 +11:00
Sebastian McKenzie
fb39df71eb support array destructuring on iterables - fixes #194 2014-11-19 21:10:40 +11:00
Sebastian McKenzie
102a566b1d ensure newlines at end of transformation tests 2014-11-19 21:09:50 +11:00
Lars Kappert
b924e3deb5 Rename to "--amd-module-ids" 2014-11-19 08:55:16 +01:00
Lars Kappert
ef21724a9c Update docs 2014-11-19 08:52:33 +01:00
Lars Kappert
fdad51b53b Revert "update umd and amd tests with new moduleName option"
This reverts commit 5409691a3a.
2014-11-19 08:45:58 +01:00
Lars Kappert
df0e4f6431 Reuse Formatter::getModuleName(), fix opts 2014-11-19 08:43:28 +01:00
Lars Kappert
a37f2093bc Merge branch 'master' of github.com:6to5/6to5 into amd-module-id
Conflicts:
	lib/6to5/file.js
	lib/6to5/transformation/modules/umd.js
2014-11-19 08:39:02 +01:00
Sebastian McKenzie
32b32329b2 make umd module formatter inherit amd constructor 2014-11-19 17:50:42 +11:00
Sebastian McKenzie
d4379d52a7 split up generator transformer emit and explode 2014-11-19 17:48:59 +11:00
Sebastian McKenzie
5c5d811647 bump chokidar and fs-readdir-recursive versions 2014-11-19 17:18:16 +11:00
Sebastian McKenzie
8feb17dd23 normalise whitespace after function keyword 2014-11-19 17:18:05 +11:00
Sebastian McKenzie
55b3f84a2f add sourceRoot and moduleRoot defaults to docs 2014-11-19 13:51:01 +11:00
Lars Kappert
9895711bf4 Improve performance 2014-11-18 22:15:02 +01:00
Lars Kappert
d2724554cc Make module id's for AMD body in UMD optional as well 2014-11-18 22:12:03 +01:00
Lars Kappert
8db466c698 Make AMD module id's optional 2014-11-18 22:04:41 +01:00
119 changed files with 1180 additions and 949 deletions

View File

@@ -1,3 +1,25 @@
# 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`.
* Support array destructuring on iterables.
* Make amd module id optional. Thanks [@webpro](https://github.com/webpro).
# 1.12.21
* Fix unneccesary let scoping replacement.

View File

@@ -18,6 +18,7 @@ commander.option("-b, --blacklist [blacklist]", "Blacklist of transformers to NO
commander.option("-o, --out-file [out]", "Compile all input files into a single file");
commander.option("-d, --out-dir [out]", "Compile an input directory of modules into an output directory");
commander.option("-c, --remove-comments", "Remove comments from the compiled code", false);
commander.option("-a, --amd-module-ids", "Insert module id in AMD modules", false);
commander.on("--help", function(){
var outKeys = function (title, obj) {
@@ -90,6 +91,7 @@ exports.opts = {
whitelist: commander.whitelist,
sourceMap: commander.sourceMaps || commander.sourceMapsInline,
comments: !commander.removeComments,
amdModuleIds: commander.amdModuleIds,
runtime: commander.runtime,
modules: commander.modules
};

View File

@@ -37,7 +37,7 @@ 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.
## Spread
### Array destructuring / Spread
An [ES6 polyfill](polyfill.md) is required in order for spread to work. More
specifically a polyfill for `Array.from`.
An [ES6 polyfill](polyfill.md) is required for spread and array destructuring.
More specifically a polyfill for `Array.from`.

View File

@@ -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
```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

@@ -32,7 +32,7 @@ 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)
- [Async functions](features.md#async-functions)
- [Arrow functions](features.md#arrow-functions)
- [Classes](features.md#classes)
- [Computed property names](features.md#computed-property-names)
@@ -40,7 +40,7 @@ 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)
- [Generators](features.md#generators)
- [Generator comprehension](features.md#generator-comprehension)
- [Let scoping](features.md#let-scoping)
- [Modules](features.md#modules)

View File

@@ -66,7 +66,7 @@ export function bar() {
**Out**
```javascript
define("filename", ["exports", "foo"], function (exports, _foo) {
define(["exports", "foo"], function (exports, _foo) {
exports.bar = bar;
var foo = _foo.default;
@@ -77,6 +77,12 @@ define("filename", ["exports", "foo"], function (exports, _foo) {
});
```
You can optionally specify to include the module id (using the `--amd-module-id` argument):
```javascript
define("filename", ["exports", "foo"], function (exports, _foo) {})
```
### UMD
**In**
@@ -94,7 +100,7 @@ export function bar() {
```javascript
(function (factory) {
if (typeof define === "function" && define.amd) {
define("filename", ["exports", "foo"], factory);
define(["exports", "foo"], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require("foo"));
}

View File

@@ -115,12 +115,19 @@ to5.transformFile("filename.js", options, function (err, result) {
sourceFileName: "filename",
// The root from which all sources are relative
// Default: `moduleRoot` option.
sourceRoot: "assets/scripts",
// Optional prefix for the AMD module formatter that will be prepend to the
// filename on module definitions
// Default: `sourceRoot` option.
moduleRoot: "my-app",
// If truthy, insert an explicit id for each defined AMD module.
// By default, AMD modules are anonymous.
// Default: false
amdModuleIds: true,
// Optionally replace all 6to5 helper declarations with a referenece to this
// variable. If set to `true` then the default namespace is used "to5Runtime".
// Default: false

View File

@@ -147,7 +147,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 +196,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

@@ -78,7 +78,7 @@ exports.Literal = function (node) {
val = JSON.stringify(val);
// escape unicode characters
val = val.replace(/[\u007f-\uffff]/g, function(c) {
val = val.replace(/[\u007f-\uffff]/g, function (c) {
return "\\u" + ("0000" + c.charCodeAt(0).toString(16)).slice(-4);
});

View File

@@ -0,0 +1 @@
Array.from(VALUE);

View File

@@ -29,10 +29,13 @@ AMDFormatter.prototype.transform = function (ast) {
var params = _.values(this.ids);
params.unshift(t.identifier("exports"));
var moduleName = this.getModuleName();
var container = t.functionExpression(null, params, t.blockStatement(body));
var call = t.callExpression(t.identifier("define"), [t.literal(moduleName), names, container]);
var defineArgs = [names, container];
var moduleName = this.getModuleName();
if (moduleName) defineArgs.unshift(t.literal(moduleName));
var call = t.callExpression(t.identifier("define"), defineArgs);
program.body = [t.expressionStatement(call)];
};
@@ -42,6 +45,10 @@ AMDFormatter.prototype.getModuleName = function () {
var filenameRelative = opts.filenameRelative;
var moduleName = "";
if (!opts.amdModuleIds) {
return null;
}
if (opts.moduleRoot) {
moduleName = opts.moduleRoot + "/";
}
@@ -71,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

@@ -5,9 +5,8 @@ var util = require("../../util");
var t = require("../../types");
var _ = require("lodash");
function UMDFormatter(file) {
this.file = file;
this.ids = {};
function UMDFormatter() {
AMDFormatter.apply(this, arguments);
}
util.inherits(UMDFormatter, AMDFormatter);
@@ -32,10 +31,12 @@ UMDFormatter.prototype.transform = function (ast) {
// runner
var defineArgs = [t.arrayExpression([t.literal("exports")].concat(names))];
var moduleName = this.getModuleName();
if (moduleName) defineArgs.unshift(t.literal(moduleName));
var runner = util.template("umd-runner-body", {
AMD_ARGUMENTS: [t.literal(moduleName), t.arrayExpression([t.literal("exports")].concat(names))],
AMD_ARGUMENTS: defineArgs,
COMMON_ARGUMENTS: names.map(function (name) {
return t.callExpression(t.identifier("require"), [name]);

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

@@ -25,7 +25,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

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

@@ -1,5 +1,6 @@
var t = require("../../types");
var _ = require("lodash");
var util = require("../../util");
var t = require("../../types");
var _ = require("lodash");
var buildVariableAssign = function (kind, id, init) {
if (kind === false) {
@@ -11,50 +12,64 @@ var buildVariableAssign = function (kind, id, init) {
}
};
var push = function (kind, nodes, elem, parentId) {
var push = function (opts, nodes, elem, parentId) {
if (t.isObjectPattern(elem)) {
pushObjectPattern(kind, nodes, elem, parentId);
pushObjectPattern(opts, nodes, elem, parentId);
} else if (t.isArrayPattern(elem)) {
pushArrayPattern(kind, nodes, elem, parentId);
pushArrayPattern(opts, nodes, elem, parentId);
} else if (t.isMemberExpression(elem)) {
nodes.push(buildVariableAssign(false, elem, parentId));
} else {
nodes.push(buildVariableAssign(kind, elem, parentId));
nodes.push(buildVariableAssign(opts.kind, elem, parentId));
}
};
var pushObjectPattern = function (kind, nodes, pattern, 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(kind, nodes, pattern2, patternId2);
push(opts, nodes, pattern2, patternId2);
} else {
nodes.push(buildVariableAssign(kind, pattern2, patternId2));
nodes.push(buildVariableAssign(opts.kind, pattern2, patternId2));
}
});
};
var pushArrayPattern = function (kind, nodes, pattern, parentId) {
var pushArrayPattern = function (opts, nodes, pattern, parentId) {
var _parentId = opts.file.generateUidIdentifier("ref", opts.scope);
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(_parentId, util.template("array-from", {
VALUE: parentId
}))
]));
parentId = _parentId;
_.each(pattern.elements, function (elem, i) {
if (!elem) return;
var newPatternId;
if (t.isSpreadElement(elem)) {
newPatternId = t.callExpression(t.memberExpression(parentId, t.identifier("slice")), [t.literal(i)]);
newPatternId = util.template("array-from", {
VALUE: parentId
});
if (+i > 0) {
newPatternId = t.callExpression(t.memberExpression(newPatternId, t.identifier("slice")), [t.literal(i)]);
}
elem = elem.argument;
} else {
newPatternId = t.memberExpression(parentId, t.literal(i), true);
}
push(kind, nodes, elem, newPatternId);
push(opts, nodes, elem, newPatternId);
});
};
var pushPattern = function (opts) {
var kind = opts.kind;
var nodes = opts.nodes;
var pattern = opts.pattern;
var parentId = opts.id;
@@ -62,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)
@@ -71,7 +86,7 @@ var pushPattern = function (opts) {
parentId = key;
}
push(kind, nodes, pattern, parentId);
push(opts, nodes, pattern, parentId);
};
exports.ForInStatement =
@@ -82,14 +97,18 @@ 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)
]);
var nodes = [];
push(declar.kind, nodes, pattern, key);
push({
kind: declar.kind,
file: file,
scope: scope
}, nodes, pattern, key);
t.ensureBlock(node);
@@ -106,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",
@@ -136,12 +155,16 @@ 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)
]));
push(false, nodes, expr.left, ref);
push({
kind: false,
file: file,
scope: scope
}, nodes, expr.left, ref);
return nodes;
};

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

@@ -0,0 +1,204 @@
/**
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* https://raw.github.com/facebook/regenerator/master/LICENSE file. An
* additional grant of patent rights can be found in the PATENTS file in
* the same directory.
*/
var assert = require("assert");
var loc = require("../util").loc;
var t = require("../../../../types");
exports.ParenthesizedExpression = function (expr, path, explodeViaTempVar, finish) {
return finish(this.explodeExpression(path.get("expression")));
};
exports.MemberExpression = function (expr, path, explodeViaTempVar, finish) {
return finish(t.memberExpression(
this.explodeExpression(path.get("object")),
expr.computed ? explodeViaTempVar(null, path.get("property")) : expr.property,
expr.computed
));
};
exports.CallExpression = function (expr, path, explodeViaTempVar, finish) {
var oldCalleePath = path.get("callee");
var newCallee = this.explodeExpression(oldCalleePath);
// If the callee was not previously a MemberExpression, then the
// CallExpression was "unqualified," meaning its `this` object should
// be the global object. If the exploded expression has become a
// MemberExpression, then we need to force it to be unqualified by
// using the (0, object.property)(...) trick; otherwise, it will
// receive the object of the MemberExpression as its `this` object.
if (!t.isMemberExpression(oldCalleePath.node) && t.isMemberExpression(newCallee)) {
newCallee = t.sequenceExpression([
t.literal(0),
newCallee
]);
}
return finish(t.callExpression(
newCallee,
path.get("arguments").map(function (argPath) {
return explodeViaTempVar(null, argPath);
})
));
};
exports.NewExpression = function (expr, path, explodeViaTempVar, finish) {
return finish(t.newExpression(
explodeViaTempVar(null, path.get("callee")),
path.get("arguments").map(function (argPath) {
return explodeViaTempVar(null, argPath);
})
));
};
exports.ObjectExpression = function (expr, path, explodeViaTempVar, finish) {
return finish(t.objectExpression(
path.get("properties").map(function (propPath) {
return t.property(
propPath.value.kind,
propPath.value.key,
explodeViaTempVar(null, propPath.get("value"))
);
})
));
};
exports.ArrayExpression = function (expr, path, explodeViaTempVar, finish) {
return finish(t.arrayExpression(
path.get("elements").map(function (elemPath) {
return explodeViaTempVar(null, elemPath);
})
));
};
exports.SequenceExpression = function (expr, path, explodeViaTempVar, finish, ignoreResult) {
var lastIndex = expr.expressions.length - 1;
var self = this;
var result;
path.get("expressions").each(function (exprPath) {
if (exprPath.name === lastIndex) {
result = self.explodeExpression(exprPath, ignoreResult);
} else {
self.explodeExpression(exprPath, true);
}
});
return result;
};
exports.LogicalExpression = function (expr, path, explodeViaTempVar, finish, ignoreResult) {
var after = loc();
var result;
if (!ignoreResult) {
result = this.makeTempVar();
}
var left = explodeViaTempVar(result, path.get("left"));
if (expr.operator === "&&") {
this.jumpIfNot(left, after);
} else {
assert.strictEqual(expr.operator, "||");
this.jumpIf(left, after);
}
explodeViaTempVar(result, path.get("right"), ignoreResult);
this.mark(after);
return result;
};
exports.ConditionalExpression = function (expr, path, explodeViaTempVar, finish, ignoreResult) {
var elseLoc = loc();
var after = loc();
var test = this.explodeExpression(path.get("test"));
var result;
this.jumpIfNot(test, elseLoc);
if (!ignoreResult) {
result = this.makeTempVar();
}
explodeViaTempVar(result, path.get("consequent"), ignoreResult);
this.jump(after);
this.mark(elseLoc);
explodeViaTempVar(result, path.get("alternate"), ignoreResult);
this.mark(after);
return result;
};
exports.UnaryExpression = function (expr, path, explodeViaTempVar, finish) {
return finish(t.unaryExpression(
expr.operator,
// Can't (and don't need to) break up the syntax of the argument.
// Think about delete a[b].
this.explodeExpression(path.get("argument")),
!!expr.prefix
));
};
exports.BinaryExpression = function (expr, path, explodeViaTempVar, finish) {
return finish(t.binaryExpression(
expr.operator,
explodeViaTempVar(null, path.get("left")),
explodeViaTempVar(null, path.get("right"))
));
};
exports.AssignmentExpression = function (expr, path, explodeViaTempVar, finish) {
return finish(t.assignmentExpression(
expr.operator,
this.explodeExpression(path.get("left")),
this.explodeExpression(path.get("right"))
));
};
exports.UpdateExpression = function (expr, path, explodeViaTempVar, finish) {
return finish(t.updateExpression(
expr.operator,
this.explodeExpression(path.get("argument")),
expr.prefix
));
};
exports.YieldExpression = function (expr, path) {
var after = loc();
var arg = expr.argument && this.explodeExpression(path.get("argument"));
var result;
if (arg && expr.delegate) {
result = this.makeTempVar();
this.emit(t.returnStatement(t.callExpression(
this.contextProperty("delegateYield"), [
arg,
t.literal(result.property.name),
after
]
)));
this.mark(after);
return result;
}
this.emitAssign(this.contextProperty("next"), after);
this.emit(t.returnStatement(arg || null));
this.mark(after);
return this.contextProperty("sent");
};

View File

@@ -0,0 +1,334 @@
/**
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* https://raw.github.com/facebook/regenerator/master/LICENSE file. An
* additional grant of patent rights can be found in the PATENTS file in
* the same directory.
*/
var assert = require("assert");
var types = require("ast-types");
var leap = require("../leap");
var util = require("../util");
var t = require("../../../../types");
var runtimeKeysMethod = util.runtimeProperty("keys");
var loc = util.loc;
exports.ExpressionStatement = function (path) {
this.explodeExpression(path.get("expression"), true);
};
exports.LabeledStatement = function (path, stmt) {
this.explodeStatement(path.get("body"), stmt.label);
};
exports.WhileStatement = function (path, stmt, labelId) {
var before = loc();
var after = loc();
this.mark(before);
this.jumpIfNot(this.explodeExpression(path.get("test")), after);
this.leapManager.withEntry(
new leap.LoopEntry(after, before, labelId),
function () { this.explodeStatement(path.get("body")); }
);
this.jump(before);
this.mark(after);
};
exports.DoWhileStatement = function (path, stmt, labelId) {
var first = loc();
var test = loc();
var after = loc();
this.mark(first);
this.leapManager.withEntry(
new leap.LoopEntry(after, test, labelId),
function () { this.explode(path.get("body")); }
);
this.mark(test);
this.jumpIf(this.explodeExpression(path.get("test")), first);
this.mark(after);
};
exports.ForStatement = function (path, stmt, labelId) {
var head = loc();
var update = loc();
var after = loc();
if (stmt.init) {
// We pass true here to indicate that if stmt.init is an expression
// then we do not care about its result.
this.explode(path.get("init"), true);
}
this.mark(head);
if (stmt.test) {
this.jumpIfNot(this.explodeExpression(path.get("test")), after);
} else {
// No test means continue unconditionally.
}
this.leapManager.withEntry(
new leap.LoopEntry(after, update, labelId),
function () { this.explodeStatement(path.get("body")); }
);
this.mark(update);
if (stmt.update) {
// We pass true here to indicate that if stmt.update is an
// expression then we do not care about its result.
this.explode(path.get("update"), true);
}
this.jump(head);
this.mark(after);
};
exports.ForInStatement = function (path, stmt, labelId) {
t.assertIdentifier(stmt.left);
var head = loc();
var after = loc();
var keyIterNextFn = this.makeTempVar();
this.emitAssign(
keyIterNextFn,
t.callExpression(
runtimeKeysMethod,
[this.explodeExpression(path.get("right"))]
)
);
this.mark(head);
var keyInfoTmpVar = this.makeTempVar();
this.jumpIf(
t.memberExpression(
t.assignmentExpression(
"=",
keyInfoTmpVar,
t.callExpression(keyIterNextFn, [])
),
t.identifier("done"),
false
),
after
);
this.emitAssign(
stmt.left,
t.memberExpression(
keyInfoTmpVar,
t.identifier("value"),
false
)
);
this.leapManager.withEntry(
new leap.LoopEntry(after, head, labelId),
function () { this.explodeStatement(path.get("body")); }
);
this.jump(head);
this.mark(after);
};
exports.BreakStatement = function (path, stmt) {
this.emitAbruptCompletion({
type: "break",
target: this.leapManager.getBreakLoc(stmt.label)
});
};
exports.ContinueStatement = function (path, stmt) {
this.emitAbruptCompletion({
type: "continue",
target: this.leapManager.getContinueLoc(stmt.label)
});
};
exports.SwitchStatement = function (path, stmt) {
// Always save the discriminant into a temporary variable in case the
// test expressions overwrite values like context.sent.
var disc = this.emitAssign(
this.makeTempVar(),
this.explodeExpression(path.get("discriminant"))
);
var after = loc();
var defaultLoc = loc();
var condition = defaultLoc;
var caseLocs = [];
var self = this;
// If there are no cases, .cases might be undefined.
var cases = stmt.cases || [];
for (var i = cases.length - 1; i >= 0; --i) {
var c = cases[i];
t.assertSwitchCase(c);
if (c.test) {
condition = t.conditionalExpression(
t.binaryExpression("===", disc, c.test),
caseLocs[i] = loc(),
condition
);
} else {
caseLocs[i] = defaultLoc;
}
}
this.jump(this.explodeExpression(
new types.NodePath(condition, path, "discriminant")
));
this.leapManager.withEntry(
new leap.SwitchEntry(after),
function () {
path.get("cases").each(function (casePath) {
var i = casePath.name;
self.mark(caseLocs[i]);
casePath.get("consequent").each(
self.explodeStatement,
self
);
});
}
);
this.mark(after);
if (defaultLoc.value === -1) {
this.mark(defaultLoc);
assert.strictEqual(after.value, defaultLoc.value);
}
};
exports.IfStatement = function (path, stmt) {
var elseLoc = stmt.alternate && loc();
var after = loc();
this.jumpIfNot(
this.explodeExpression(path.get("test")),
elseLoc || after
);
this.explodeStatement(path.get("consequent"));
if (elseLoc) {
this.jump(after);
this.mark(elseLoc);
this.explodeStatement(path.get("alternate"));
}
this.mark(after);
};
exports.ReturnStatement = function (path) {
this.emitAbruptCompletion({
type: "return",
value: this.explodeExpression(path.get("argument"))
});
};
exports.TryStatement = function (path, stmt) {
var after = loc();
var self = this;
var handler = stmt.handler;
if (!handler && stmt.handlers) {
handler = stmt.handlers[0] || null;
}
var catchLoc = handler && loc();
var catchEntry = catchLoc && new leap.CatchEntry(
catchLoc,
handler.param
);
var finallyLoc = stmt.finalizer && loc();
var finallyEntry = finallyLoc && new leap.FinallyEntry(finallyLoc);
var tryEntry = new leap.TryEntry(
this.getUnmarkedCurrentLoc(),
catchEntry,
finallyEntry
);
this.tryEntries.push(tryEntry);
this.updateContextPrevLoc(tryEntry.firstLoc);
this.leapManager.withEntry(tryEntry, function () {
this.explodeStatement(path.get("block"));
if (catchLoc) {
if (finallyLoc) {
// If we have both a catch block and a finally block, then
// because we emit the catch block first, we need to jump over
// it to the finally block.
this.jump(finallyLoc);
} else {
// If there is no finally block, then we need to jump over the
// catch block to the fall-through location.
this.jump(after);
}
this.updateContextPrevLoc(self.mark(catchLoc));
var bodyPath = path.get("handler", "body");
var safeParam = this.makeTempVar();
this.clearPendingException(tryEntry.firstLoc, safeParam);
var catchScope = bodyPath.scope;
var catchParamName = handler.param.name;
t.assertCatchClause(catchScope.node);
assert.strictEqual(catchScope.lookup(catchParamName), catchScope);
types.visit(bodyPath, {
visitIdentifier: function (path) {
if (path.value.name === catchParamName &&
path.scope.lookup(catchParamName) === catchScope) {
return safeParam;
}
this.traverse(path);
}
});
this.leapManager.withEntry(catchEntry, function () {
this.explodeStatement(bodyPath);
});
}
if (finallyLoc) {
this.updateContextPrevLoc(this.mark(finallyLoc));
this.leapManager.withEntry(finallyEntry, function () {
this.explodeStatement(path.get("finalizer"));
});
this.emit(t.callExpression(
this.contextProperty("finish"),
[finallyEntry.firstLoc]
));
}
});
this.mark(after);
};
exports.ThrowStatement = function (path) {
this.emit(t.throwStatement(
this.explodeExpression(path.get("argument"))
));
};

View File

@@ -10,16 +10,18 @@
exports.Emitter = Emitter;
var runtimeProperty = require("./util").runtimeProperty;
var assert = require("assert");
var types = require("ast-types");
var leap = require("./leap");
var meta = require("./meta");
var t = require("../../../types");
var _ = require("lodash");
var explodeExpressions = require("./explode-expressions");
var explodeStatements = require("./explode-statements");
var assert = require("assert");
var types = require("ast-types");
var leap = require("../leap");
var meta = require("../meta");
var util = require("../util");
var t = require("../../../../types");
var _ = require("lodash");
var runtimeKeysMethod = runtimeProperty("keys");
var n = types.namedTypes;
var loc = util.loc;
var n = types.namedTypes;
function Emitter(contextId) {
assert.ok(this instanceof Emitter);
@@ -52,18 +54,9 @@ function Emitter(contextId) {
this.leapManager = new leap.LeapManager(this);
}
// Offsets into this.listing that could be used as targets for branches or
// jumps are represented as numeric Literal nodes. This representation has
// the amazingly convenient benefit of allowing the exact value of the
// location to be determined at any time, even after generating code that
// refers to the location.
function loc() {
return t.literal(-1);
}
// Sets the exact value of the given location to the offset of the next
// Statement emitted.
Emitter.prototype.mark = function(loc) {
Emitter.prototype.mark = function (loc) {
t.assertLiteral(loc);
var index = this.listing.length;
if (loc.value === -1) {
@@ -77,7 +70,7 @@ Emitter.prototype.mark = function(loc) {
return loc;
};
Emitter.prototype.emit = function(node) {
Emitter.prototype.emit = function (node) {
if (t.isExpression(node)) node = t.expressionStatement(node);
t.assertStatement(node);
this.listing.push(node);
@@ -85,20 +78,20 @@ Emitter.prototype.emit = function(node) {
// Shorthand for emitting assignment statements. This will come in handy
// for assignments to temporary variables.
Emitter.prototype.emitAssign = function(lhs, rhs) {
Emitter.prototype.emitAssign = function (lhs, rhs) {
this.emit(this.assign(lhs, rhs));
return lhs;
};
// Shorthand for an assignment statement.
Emitter.prototype.assign = function(lhs, rhs) {
Emitter.prototype.assign = function (lhs, rhs) {
return t.expressionStatement(
t.assignmentExpression("=", lhs, rhs));
};
// Convenience function for generating expressions like context.next,
// context.sent, and context.rval.
Emitter.prototype.contextProperty = function(name, computed) {
Emitter.prototype.contextProperty = function (name, computed) {
return t.memberExpression(
this.contextId,
computed ? t.literal(name) : t.identifier(name),
@@ -116,7 +109,7 @@ var volatileContextPropertyNames = {
// A "volatile" context property is a MemberExpression like context.sent
// that should probably be stored in a temporary variable when there's a
// possibility the property will get overwritten.
Emitter.prototype.isVolatileContextProperty = function(expr) {
Emitter.prototype.isVolatileContextProperty = function (expr) {
if (t.isMemberExpression(expr)) {
if (expr.computed) {
// If it's a computed property such as context[couldBeAnything],
@@ -136,7 +129,7 @@ Emitter.prototype.isVolatileContextProperty = function(expr) {
};
// Shorthand for setting context.rval and jumping to `context.stop()`.
Emitter.prototype.stop = function(rval) {
Emitter.prototype.stop = function (rval) {
if (rval) {
this.setReturnValue(rval);
}
@@ -144,7 +137,7 @@ Emitter.prototype.stop = function(rval) {
this.jump(this.finalLoc);
};
Emitter.prototype.setReturnValue = function(valuePath) {
Emitter.prototype.setReturnValue = function (valuePath) {
t.assertExpression(valuePath.value);
this.emitAssign(
@@ -153,7 +146,7 @@ Emitter.prototype.setReturnValue = function(valuePath) {
);
};
Emitter.prototype.clearPendingException = function(tryLoc, assignee) {
Emitter.prototype.clearPendingException = function (tryLoc, assignee) {
t.assertLiteral(tryLoc);
var catchCall = t.callExpression(
@@ -170,13 +163,13 @@ Emitter.prototype.clearPendingException = function(tryLoc, assignee) {
// Emits code for an unconditional jump to the given location, even if the
// exact value of the location is not yet known.
Emitter.prototype.jump = function(toLoc) {
Emitter.prototype.jump = function (toLoc) {
this.emitAssign(this.contextProperty("next"), toLoc);
this.emit(t.breakStatement());
};
// Conditional jump.
Emitter.prototype.jumpIf = function(test, toLoc) {
Emitter.prototype.jumpIf = function (test, toLoc) {
t.assertExpression(test);
t.assertLiteral(toLoc);
@@ -190,7 +183,7 @@ Emitter.prototype.jumpIf = function(test, toLoc) {
};
// Conditional jump, with the condition negated.
Emitter.prototype.jumpIfNot = function(test, toLoc) {
Emitter.prototype.jumpIfNot = function (test, toLoc) {
t.assertExpression(test);
t.assertLiteral(toLoc);
@@ -217,11 +210,11 @@ Emitter.prototype.jumpIfNot = function(test, toLoc) {
// other local variables, and since we just increment `nextTempId`
// monotonically, uniqueness is assured.
var nextTempId = 0;
Emitter.prototype.makeTempVar = function() {
Emitter.prototype.makeTempVar = function () {
return this.contextProperty("t" + nextTempId++);
};
Emitter.prototype.getContextFunction = function(id) {
Emitter.prototype.getContextFunction = function (id) {
var node = t.functionExpression(
id || null,
[this.contextId],
@@ -244,7 +237,7 @@ Emitter.prototype.getContextFunction = function(id) {
//
// Each marked location in this.listing will correspond to one generated
// case statement.
Emitter.prototype.getDispatchLoop = function() {
Emitter.prototype.getDispatchLoop = function () {
var self = this;
var cases = [];
var current;
@@ -253,7 +246,7 @@ Emitter.prototype.getDispatchLoop = function() {
// case, we can skip the rest of the statements until the next case.
var alreadyEnded = false;
self.listing.forEach(function(stmt, i) {
self.listing.forEach(function (stmt, i) {
if (self.marked.hasOwnProperty(i)) {
cases.push(t.switchCase(t.literal(i), current = []));
alreadyEnded = false;
@@ -306,7 +299,7 @@ function isSwitchCaseEnder(stmt) {
t.isThrowStatement(stmt);
}
Emitter.prototype.getTryEntryList = function() {
Emitter.prototype.getTryEntryList = function () {
if (this.tryEntries.length === 0) {
// To avoid adding a needless [] to the majority of runtime.wrap
// argument lists, force the caller to handle this case specially.
@@ -316,7 +309,7 @@ Emitter.prototype.getTryEntryList = function() {
var lastLocValue = 0;
return t.arrayExpression(
this.tryEntries.map(function(tryEntry) {
this.tryEntries.map(function (tryEntry) {
var thisLocValue = tryEntry.firstLoc.value;
assert.ok(thisLocValue >= lastLocValue, "try entries out of order");
lastLocValue = thisLocValue;
@@ -346,7 +339,7 @@ Emitter.prototype.getTryEntryList = function() {
// No destructive modification of AST nodes.
Emitter.prototype.explode = function(path, ignoreResult) {
Emitter.prototype.explode = function (path, ignoreResult) {
assert.ok(path instanceof types.NodePath);
var node = path.value;
@@ -389,12 +382,11 @@ function getDeclError(node) {
JSON.stringify(node));
}
Emitter.prototype.explodeStatement = function(path, labelId) {
Emitter.prototype.explodeStatement = function (path, labelId) {
assert.ok(path instanceof types.NodePath);
var stmt = path.value;
var self = this;
var after, head;
t.assertStatement(stmt);
@@ -423,338 +415,15 @@ Emitter.prototype.explodeStatement = function(path, labelId) {
return;
}
switch (stmt.type) {
case "ExpressionStatement":
self.explodeExpression(path.get("expression"), true);
break;
case "LabeledStatement":
self.explodeStatement(path.get("body"), stmt.label);
break;
case "WhileStatement":
var before = loc();
after = loc();
self.mark(before);
self.jumpIfNot(self.explodeExpression(path.get("test")), after);
self.leapManager.withEntry(
new leap.LoopEntry(after, before, labelId),
function() { self.explodeStatement(path.get("body")); }
);
self.jump(before);
self.mark(after);
break;
case "DoWhileStatement":
var first = loc();
var test = loc();
after = loc();
self.mark(first);
self.leapManager.withEntry(
new leap.LoopEntry(after, test, labelId),
function() { self.explode(path.get("body")); }
);
self.mark(test);
self.jumpIf(self.explodeExpression(path.get("test")), first);
self.mark(after);
break;
case "ForStatement":
head = loc();
var update = loc();
after = loc();
if (stmt.init) {
// We pass true here to indicate that if stmt.init is an expression
// then we do not care about its result.
self.explode(path.get("init"), true);
}
self.mark(head);
if (stmt.test) {
self.jumpIfNot(self.explodeExpression(path.get("test")), after);
} else {
// No test means continue unconditionally.
}
self.leapManager.withEntry(
new leap.LoopEntry(after, update, labelId),
function() { self.explodeStatement(path.get("body")); }
);
self.mark(update);
if (stmt.update) {
// We pass true here to indicate that if stmt.update is an
// expression then we do not care about its result.
self.explode(path.get("update"), true);
}
self.jump(head);
self.mark(after);
break;
case "ForInStatement":
t.assertIdentifier(stmt.left);
head = loc();
after = loc();
var keyIterNextFn = self.makeTempVar();
self.emitAssign(
keyIterNextFn,
t.callExpression(
runtimeKeysMethod,
[self.explodeExpression(path.get("right"))]
)
);
self.mark(head);
var keyInfoTmpVar = self.makeTempVar();
self.jumpIf(
t.memberExpression(
t.assignmentExpression(
"=",
keyInfoTmpVar,
t.callExpression(keyIterNextFn, [])
),
t.identifier("done"),
false
),
after
);
self.emitAssign(
stmt.left,
t.memberExpression(
keyInfoTmpVar,
t.identifier("value"),
false
)
);
self.leapManager.withEntry(
new leap.LoopEntry(after, head, labelId),
function() { self.explodeStatement(path.get("body")); }
);
self.jump(head);
self.mark(after);
break;
case "BreakStatement":
self.emitAbruptCompletion({
type: "break",
target: self.leapManager.getBreakLoc(stmt.label)
});
break;
case "ContinueStatement":
self.emitAbruptCompletion({
type: "continue",
target: self.leapManager.getContinueLoc(stmt.label)
});
break;
case "SwitchStatement":
// Always save the discriminant into a temporary variable in case the
// test expressions overwrite values like context.sent.
var disc = self.emitAssign(
self.makeTempVar(),
self.explodeExpression(path.get("discriminant"))
);
after = loc();
var defaultLoc = loc();
var condition = defaultLoc;
var caseLocs = [];
// If there are no cases, .cases might be undefined.
var cases = stmt.cases || [];
for (var i = cases.length - 1; i >= 0; --i) {
var c = cases[i];
t.assertSwitchCase(c);
if (c.test) {
condition = t.conditionalExpression(
t.binaryExpression("===", disc, c.test),
caseLocs[i] = loc(),
condition
);
} else {
caseLocs[i] = defaultLoc;
}
}
self.jump(self.explodeExpression(
new types.NodePath(condition, path, "discriminant")
));
self.leapManager.withEntry(
new leap.SwitchEntry(after),
function() {
path.get("cases").each(function(casePath) {
var i = casePath.name;
self.mark(caseLocs[i]);
casePath.get("consequent").each(
self.explodeStatement,
self
);
});
}
);
self.mark(after);
if (defaultLoc.value === -1) {
self.mark(defaultLoc);
assert.strictEqual(after.value, defaultLoc.value);
}
break;
case "IfStatement":
var elseLoc = stmt.alternate && loc();
after = loc();
self.jumpIfNot(
self.explodeExpression(path.get("test")),
elseLoc || after
);
self.explodeStatement(path.get("consequent"));
if (elseLoc) {
self.jump(after);
self.mark(elseLoc);
self.explodeStatement(path.get("alternate"));
}
self.mark(after);
break;
case "ReturnStatement":
self.emitAbruptCompletion({
type: "return",
value: self.explodeExpression(path.get("argument"))
});
break;
case "TryStatement":
after = loc();
var handler = stmt.handler;
if (!handler && stmt.handlers) {
handler = stmt.handlers[0] || null;
}
var catchLoc = handler && loc();
var catchEntry = catchLoc && new leap.CatchEntry(
catchLoc,
handler.param
);
var finallyLoc = stmt.finalizer && loc();
var finallyEntry = finallyLoc && new leap.FinallyEntry(finallyLoc);
var tryEntry = new leap.TryEntry(
self.getUnmarkedCurrentLoc(),
catchEntry,
finallyEntry
);
self.tryEntries.push(tryEntry);
self.updateContextPrevLoc(tryEntry.firstLoc);
self.leapManager.withEntry(tryEntry, function() {
self.explodeStatement(path.get("block"));
if (catchLoc) {
if (finallyLoc) {
// If we have both a catch block and a finally block, then
// because we emit the catch block first, we need to jump over
// it to the finally block.
self.jump(finallyLoc);
} else {
// If there is no finally block, then we need to jump over the
// catch block to the fall-through location.
self.jump(after);
}
self.updateContextPrevLoc(self.mark(catchLoc));
var bodyPath = path.get("handler", "body");
var safeParam = self.makeTempVar();
self.clearPendingException(tryEntry.firstLoc, safeParam);
var catchScope = bodyPath.scope;
var catchParamName = handler.param.name;
t.assertCatchClause(catchScope.node);
assert.strictEqual(catchScope.lookup(catchParamName), catchScope);
types.visit(bodyPath, {
visitIdentifier: function(path) {
if (path.value.name === catchParamName &&
path.scope.lookup(catchParamName) === catchScope) {
return safeParam;
}
this.traverse(path);
}
});
self.leapManager.withEntry(catchEntry, function() {
self.explodeStatement(bodyPath);
});
}
if (finallyLoc) {
self.updateContextPrevLoc(self.mark(finallyLoc));
self.leapManager.withEntry(finallyEntry, function() {
self.explodeStatement(path.get("finalizer"));
});
self.emit(t.callExpression(
self.contextProperty("finish"),
[finallyEntry.firstLoc]
));
}
});
self.mark(after);
break;
case "ThrowStatement":
self.emit(t.throwStatement(
self.explodeExpression(path.get("argument"))
));
break;
default:
var fn = explodeStatements[stmt.type];
if (fn) {
fn.call(this, path, stmt, labelId);
} else {
throw new Error("unknown Statement of type " + JSON.stringify(stmt.type));
}
};
Emitter.prototype.emitAbruptCompletion = function(record) {
Emitter.prototype.emitAbruptCompletion = function (record) {
if (!isValidCompletion(record)) {
assert.ok(
false,
@@ -816,7 +485,7 @@ function isValidCompletion(record) {
// statements). There's no logical harm in marking such locations as jump
// targets, but minimizing the number of switch cases keeps the generated
// code shorter.
Emitter.prototype.getUnmarkedCurrentLoc = function() {
Emitter.prototype.getUnmarkedCurrentLoc = function () {
return t.literal(this.listing.length);
};
@@ -830,7 +499,7 @@ Emitter.prototype.getUnmarkedCurrentLoc = function() {
// would know the location of the current instruction with complete
// precision at all times, but we don't have that luxury here, as it would
// be costly and verbose to set context.prev before every statement.
Emitter.prototype.updateContextPrevLoc = function(loc) {
Emitter.prototype.updateContextPrevLoc = function (loc) {
if (loc) {
t.assertLiteral(loc);
@@ -853,7 +522,7 @@ Emitter.prototype.updateContextPrevLoc = function(loc) {
this.emitAssign(this.contextProperty("prev"), loc);
};
Emitter.prototype.explodeExpression = function(path, ignoreResult) {
Emitter.prototype.explodeExpression = function (path, ignoreResult) {
assert.ok(path instanceof types.NodePath);
var expr = path.value;
@@ -864,7 +533,6 @@ Emitter.prototype.explodeExpression = function(path, ignoreResult) {
}
var self = this;
var result, after; // Used optionally by several cases below.
function finish(expr) {
t.assertExpression(expr);
@@ -934,180 +602,10 @@ Emitter.prototype.explodeExpression = function(path, ignoreResult) {
// emitting the expression with all its side effects, and we should not
// return a result.
switch (expr.type) {
case "ParenthesizedExpression":
return finish(self.explodeExpression(path.get("expression")));
case "MemberExpression":
return finish(t.memberExpression(
self.explodeExpression(path.get("object")),
expr.computed ? explodeViaTempVar(null, path.get("property")) : expr.property,
expr.computed
));
case "CallExpression":
var oldCalleePath = path.get("callee");
var newCallee = self.explodeExpression(oldCalleePath);
// If the callee was not previously a MemberExpression, then the
// CallExpression was "unqualified," meaning its `this` object should
// be the global object. If the exploded expression has become a
// MemberExpression, then we need to force it to be unqualified by
// using the (0, object.property)(...) trick; otherwise, it will
// receive the object of the MemberExpression as its `this` object.
if (!t.isMemberExpression(oldCalleePath.node) && t.isMemberExpression(newCallee)) {
newCallee = t.sequenceExpression([
t.literal(0),
newCallee
]);
}
return finish(t.callExpression(
newCallee,
path.get("arguments").map(function(argPath) {
return explodeViaTempVar(null, argPath);
})
));
case "NewExpression":
return finish(t.newExpression(
explodeViaTempVar(null, path.get("callee")),
path.get("arguments").map(function(argPath) {
return explodeViaTempVar(null, argPath);
})
));
case "ObjectExpression":
return finish(t.objectExpression(
path.get("properties").map(function(propPath) {
return t.property(
propPath.value.kind,
propPath.value.key,
explodeViaTempVar(null, propPath.get("value"))
);
})
));
case "ArrayExpression":
return finish(t.arrayExpression(
path.get("elements").map(function(elemPath) {
return explodeViaTempVar(null, elemPath);
})
));
case "SequenceExpression":
var lastIndex = expr.expressions.length - 1;
path.get("expressions").each(function(exprPath) {
if (exprPath.name === lastIndex) {
result = self.explodeExpression(exprPath, ignoreResult);
} else {
self.explodeExpression(exprPath, true);
}
});
return result;
case "LogicalExpression":
after = loc();
if (!ignoreResult) {
result = self.makeTempVar();
}
var left = explodeViaTempVar(result, path.get("left"));
if (expr.operator === "&&") {
self.jumpIfNot(left, after);
} else {
assert.strictEqual(expr.operator, "||");
self.jumpIf(left, after);
}
explodeViaTempVar(result, path.get("right"), ignoreResult);
self.mark(after);
return result;
case "ConditionalExpression":
var elseLoc = loc();
after = loc();
var test = self.explodeExpression(path.get("test"));
self.jumpIfNot(test, elseLoc);
if (!ignoreResult) {
result = self.makeTempVar();
}
explodeViaTempVar(result, path.get("consequent"), ignoreResult);
self.jump(after);
self.mark(elseLoc);
explodeViaTempVar(result, path.get("alternate"), ignoreResult);
self.mark(after);
return result;
case "UnaryExpression":
return finish(t.unaryExpression(
expr.operator,
// Can't (and don't need to) break up the syntax of the argument.
// Think about delete a[b].
self.explodeExpression(path.get("argument")),
!!expr.prefix
));
case "BinaryExpression":
return finish(t.binaryExpression(
expr.operator,
explodeViaTempVar(null, path.get("left")),
explodeViaTempVar(null, path.get("right"))
));
case "AssignmentExpression":
return finish(t.assignmentExpression(
expr.operator,
self.explodeExpression(path.get("left")),
self.explodeExpression(path.get("right"))
));
case "UpdateExpression":
return finish(t.updateExpression(
expr.operator,
self.explodeExpression(path.get("argument")),
expr.prefix
));
case "YieldExpression":
after = loc();
var arg = expr.argument && self.explodeExpression(path.get("argument"));
if (arg && expr.delegate) {
result = self.makeTempVar();
self.emit(t.returnStatement(t.callExpression(
self.contextProperty("delegateYield"), [
arg,
t.literal(result.property.name),
after
]
)));
self.mark(after);
return result;
}
self.emitAssign(self.contextProperty("next"), after);
self.emit(t.returnStatement(arg || null));
self.mark(after);
return self.contextProperty("sent");
default:
var fn = explodeExpressions[expr.type];
if (fn) {
return fn.call(this, expr, path, explodeViaTempVar, finish, ignoreResult);
} else {
throw new Error("unknown Expression of type " + JSON.stringify(expr.type));
}
};

View File

@@ -17,7 +17,7 @@ var _ = require("lodash");
// and replaces any Declaration nodes in its body with assignments, then
// returns a VariableDeclaration containing just the names of the removed
// declarations.
exports.hoist = function(funPath) {
exports.hoist = function (funPath) {
assert.ok(funPath instanceof types.NodePath);
t.assertFunction(funPath.value);
@@ -27,7 +27,7 @@ exports.hoist = function(funPath) {
t.assertVariableDeclaration(vdec);
var exprs = [];
vdec.declarations.forEach(function(dec) {
vdec.declarations.forEach(function (dec) {
vars[dec.id.name] = dec.id;
if (dec.init) {
@@ -49,7 +49,7 @@ exports.hoist = function(funPath) {
}
types.visit(funPath.get("body"), {
visitVariableDeclaration: function(path) {
visitVariableDeclaration: function (path) {
var expr = varDeclToExpr(path.value, false);
if (expr === null) {
path.replace();
@@ -64,7 +64,7 @@ exports.hoist = function(funPath) {
return false;
},
visitForStatement: function(path) {
visitForStatement: function (path) {
var init = path.value.init;
if (t.isVariableDeclaration(init)) {
path.get("init").replace(varDeclToExpr(init, false));
@@ -72,7 +72,7 @@ exports.hoist = function(funPath) {
this.traverse(path);
},
visitForInStatement: function(path) {
visitForInStatement: function (path) {
var left = path.value.left;
if (t.isVariableDeclaration(left)) {
path.get("left").replace(varDeclToExpr(left, true));
@@ -80,7 +80,7 @@ exports.hoist = function(funPath) {
this.traverse(path);
},
visitFunctionDeclaration: function(path) {
visitFunctionDeclaration: function (path) {
var node = path.value;
vars[node.id.name] = node.id;
@@ -118,14 +118,14 @@ exports.hoist = function(funPath) {
return false;
},
visitFunctionExpression: function() {
visitFunctionExpression: function () {
// Don't descend into nested function expressions.
return false;
}
});
var paramNames = {};
funPath.get("params").each(function(paramPath) {
funPath.get("params").each(function (paramPath) {
var param = paramPath.value;
if (t.isIdentifier(param)) {
paramNames[param.name] = param;
@@ -137,7 +137,7 @@ exports.hoist = function(funPath) {
var declarations = [];
Object.keys(vars).forEach(function(name) {
Object.keys(vars).forEach(function (name) {
if (!_.has(paramNames, name)) {
declarations.push(t.variableDeclarator(vars[name], null));
}

View File

@@ -124,7 +124,7 @@ function LeapManager(emitter) {
this.entryStack = [new FunctionEntry(emitter.finalLoc)];
}
LeapManager.prototype.withEntry = function(entry, callback) {
LeapManager.prototype.withEntry = function (entry, callback) {
assert.ok(entry instanceof Entry);
this.entryStack.push(entry);
try {
@@ -135,7 +135,7 @@ LeapManager.prototype.withEntry = function(entry, callback) {
}
};
LeapManager.prototype._findLeapLocation = function(property, label) {
LeapManager.prototype._findLeapLocation = function (property, label) {
for (var i = this.entryStack.length - 1; i >= 0; --i) {
var entry = this.entryStack[i];
var loc = entry[property];
@@ -154,10 +154,10 @@ LeapManager.prototype._findLeapLocation = function(property, label) {
return null;
};
LeapManager.prototype.getBreakLoc = function(label) {
LeapManager.prototype.getBreakLoc = function (label) {
return this._findLeapLocation("breakLoc", label);
};
LeapManager.prototype.getContinueLoc = function(label) {
LeapManager.prototype.getContinueLoc = function (label) {
return this._findLeapLocation("continueLoc", label);
};

View File

@@ -35,7 +35,7 @@ function makePredicate(propertyName, knownTypes) {
return result;
}
types.eachField(node, function(name, child) {
types.eachField(node, function (name, child) {
check(child);
});

View File

@@ -38,19 +38,19 @@ var GFName = "GeneratorFunction";
if (GF.name !== GFName) GF.name = GFName;
if (GF.name !== GFName) throw new Error(GFName + " renamed?");
runtime.isGeneratorFunction = function(genFun) {
runtime.isGeneratorFunction = function (genFun) {
var ctor = genFun && genFun.constructor;
return ctor ? GF.name === ctor.name : false;
};
runtime.mark = function(genFun) {
runtime.mark = function (genFun) {
genFun.__proto__ = GFp;
genFun.prototype = Object.create(Gp);
return genFun;
};
runtime.async = function(innerFn, outerFn, self, tryList) {
return new Promise(function(resolve, reject) {
runtime.async = function (innerFn, outerFn, self, tryList) {
return new Promise(function (resolve, reject) {
var generator = wrap(innerFn, outerFn, self, tryList);
var callNext = step.bind(generator.next);
var callThrow = step.bind(generator["throw"]);
@@ -202,11 +202,11 @@ function Generator(innerFn, outerFn, self, tryList) {
return generator;
}
Gp[iteratorSymbol] = function() {
Gp[iteratorSymbol] = function () {
return this;
};
Gp.toString = function() {
Gp.toString = function () {
return "[object Generator]";
};
@@ -240,7 +240,7 @@ function Context(tryList) {
this.reset();
}
runtime.keys = function(object) {
runtime.keys = function (object) {
var keys = [];
for (var key in object) {
keys.push(key);
@@ -293,7 +293,7 @@ runtime.values = values;
Context.prototype = {
constructor: Context,
reset: function() {
reset: function () {
this.prev = 0;
this.next = 0;
this.sent = undefined;
@@ -311,7 +311,7 @@ Context.prototype = {
}
},
stop: function() {
stop: function () {
this.done = true;
var rootEntry = this.tryEntries[0];
@@ -323,7 +323,7 @@ Context.prototype = {
return this.rval;
},
dispatchException: function(exception) {
dispatchException: function (exception) {
if (this.done) {
throw exception;
}
@@ -375,7 +375,7 @@ Context.prototype = {
}
},
_findFinallyEntry: function(finallyLoc) {
_findFinallyEntry: function (finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev &&
@@ -387,7 +387,7 @@ Context.prototype = {
}
},
abrupt: function(type, arg) {
abrupt: function (type, arg) {
var entry = this._findFinallyEntry();
var record = entry ? entry.completion : {};
@@ -403,7 +403,7 @@ Context.prototype = {
return ContinueSentinel;
},
complete: function(record) {
complete: function (record) {
if (record.type === "throw") {
throw record.arg;
}
@@ -418,12 +418,12 @@ Context.prototype = {
return ContinueSentinel;
},
finish: function(finallyLoc) {
finish: function (finallyLoc) {
var entry = this._findFinallyEntry(finallyLoc);
return this.complete(entry.completion);
},
"catch": function(tryLoc) {
"catch": function (tryLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
@@ -442,7 +442,7 @@ Context.prototype = {
throw new Error("illegal catch attempt");
},
delegateYield: function(iterable, resultName, nextLoc) {
delegateYield: function (iterable, resultName, nextLoc) {
this.delegate = {
iterator: values(iterable),
resultName: resultName,

View File

@@ -16,3 +16,13 @@ exports.runtimeProperty = function (name) {
t.identifier(name)
);
};
// Offsets into this.listing that could be used as targets for branches or
// jumps are represented as numeric Literal nodes. This representation has
// the amazingly convenient benefit of allowing the exact value of the
// location to be determined at any time, even after generating code that
// refers to the location.
exports.loc = function () {
return t.literal(-1);
};

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;
@@ -208,11 +210,11 @@ function shouldNotHoistAbove(stmtPath) {
}
var awaitVisitor = types.PathVisitor.fromMethodsObject({
visitFunction: function() {
visitFunction: function () {
return false; // Don't descend into nested function scopes.
},
visitAwaitExpression: function(path) {
visitAwaitExpression: function (path) {
// Convert await expressions to yield expressions.
return t.yieldExpression(path.value.argument, false);
}

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

@@ -1,13 +1,13 @@
var t = require("../../types");
var _ = require("lodash");
var util = require("../../util");
var t = require("../../types");
var _ = require("lodash");
var getSpreadLiteral = function (spread) {
var literal = spread.argument;
if (!t.isArrayExpression(literal)) {
literal = t.callExpression(
t.memberExpression(t.identifier("Array"), t.identifier("from")),
[literal]
);
literal = util.template("array-from", {
VALUE: literal
});
}
return literal;
};

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) {

View File

@@ -1,7 +1,7 @@
{
"name": "6to5",
"description": "Turn ES6 code into readable vanilla ES5 with source maps",
"version": "1.12.21",
"version": "1.12.26",
"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.0.2",
"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.10.5",
"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

@@ -2,4 +2,4 @@
var Test = function Test() {
arr.map(x => x * x);
};
};

View File

@@ -2,4 +2,4 @@
var arr = [1, 2, 3].map(function (i) {
return i * i;
});
});

View File

@@ -4,4 +4,4 @@ var a = function (_ref) {
var target = _ref.target;
return console.log(target);
};
a({ target: "I am a target" });
a({ target: "I am a target" });

View File

@@ -2,4 +2,4 @@
var t = function () {
return 5 + 5;
};
};

View File

@@ -1,3 +1,3 @@
"use strict";
var t = function () {};
var t = function () {};

View File

@@ -2,4 +2,4 @@
arr.map(function (x) {
return x * x;
});
});

View File

@@ -2,4 +2,4 @@
arr.map(function (i) {
return i + 1;
});
});

View File

@@ -2,4 +2,4 @@
var t = function (i, x) {
return i * x;
};
};

View File

@@ -2,4 +2,4 @@
var t = function (i) {
return i * 5;
};
};

View File

@@ -2,4 +2,4 @@
var t = function (i) {
return i * 5;
};
};

View File

@@ -4,4 +4,4 @@ nums.forEach(function (v) {
if (v % 5 === 0) {
fives.push(v);
}
});
});

View File

@@ -3,4 +3,4 @@
var _this = this;
var t = function (x) {
return _this.x + x;
};
};

View File

@@ -1,3 +1,3 @@
"use strict";
var Test = function Test() {};
var Test = function Test() {};

View File

@@ -2,4 +2,4 @@
var Test = function Test() {
Function.prototype.hasOwnProperty.call(this, "test");
};
};

View File

@@ -3,4 +3,4 @@
foo((function (_ref) {
_ref[bar] = "foobar";
return _ref;
})({}));
})({}));

View File

@@ -3,4 +3,4 @@
foo = (function (_foo) {
_foo[bar] = "foobar";
return _foo;
})({});
})({});

View File

@@ -5,4 +5,4 @@ var obj = (function (_obj) {
return "foobar";
};
return _obj;
})({});
})({});

View File

@@ -7,4 +7,4 @@ var obj = (function (_obj) {
})({
foo: "foo",
bar: "bar"
});
});

View File

@@ -4,4 +4,4 @@ var obj = (function (_obj) {
_obj["x" + foo] = "heh";
_obj["y" + bar] = "noo";
return _obj;
})({});
})({});

View File

@@ -3,4 +3,4 @@
var obj = (function (_obj) {
_obj["x" + foo] = "heh";
return _obj;
})({});
})({});

View File

@@ -4,4 +4,4 @@ var _this = this;
var obj = (function (_obj) {
_obj["x" + _this.foo] = "heh";
return _obj;
})({});
})({});

View File

@@ -3,4 +3,4 @@
var foo = (function (_foo) {
_foo[bar] = "foobar";
return _foo;
})({});
})({});

View File

@@ -2,15 +2,19 @@
var _ref = [1, 2];
var a = _ref[0];
var b = _ref[1];
var _ref2 = [3, 4];
var _ref2 = Array.from(_ref);
var c = _ref2[0];
var d = _ref2[1];
var _ref3 = { e: 5, f: 6 };
var e = _ref3.e;
var f = _ref3.f;
var _ref4 = { a: 7, b: 8 };
var g = _ref4.a;
var h = _ref4.b;
var a = _ref2[0];
var b = _ref2[1];
var _ref3 = [3, 4];
var _ref4 = Array.from(_ref3);
var c = _ref4[0];
var d = _ref4[1];
var _ref5 = { e: 5, f: 6 };
var e = _ref5.e;
var f = _ref5.f;
var _ref6 = { a: 7, b: 8 };
var g = _ref6.a;
var h = _ref6.b;

View File

@@ -2,7 +2,13 @@
var _ref = ["hello", [", ", "junk"], ["world"]];
var a = _ref[0];
var b = _ref[1][0];
var c = _ref[2][0];
var d = _ref[3];
var _ref2 = Array.from(_ref);
var a = _ref2[0];
var _ref3 = Array.from(_ref2[1]);
var b = _ref3[0];
var _ref4 = Array.from(_ref2[2]);
var c = _ref4[0];
var d = _ref2[3];

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

@@ -2,5 +2,7 @@
var _ref = f();
a = _ref[0];
b = _ref[1];
var _ref2 = Array.from(_ref);
a = _ref2[0];
b = _ref2[1];

View File

@@ -2,7 +2,13 @@
var _ref = ["foo", "hello", [", ", "junk"], ["world"]];
var a = _ref[1];
var b = _ref[2][0];
var c = _ref[3][0];
var d = _ref[4];
var _ref2 = Array.from(_ref);
var a = _ref2[1];
var _ref3 = Array.from(_ref2[2]);
var b = _ref3[0];
var _ref4 = Array.from(_ref2[3]);
var c = _ref4[0];
var d = _ref2[4];

View File

@@ -1,7 +1,9 @@
"use strict";
for (var _ref in obj) {
var name = _ref[0];
var value = _ref[1];
var _ref2 = Array.from(_ref);
var name = _ref2[0];
var value = _ref2[1];
print("Name: " + name + ", Value: " + value);
}

View File

@@ -2,7 +2,9 @@
for (var _iterator = this.test.expectation.registers[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) {
var _ref = _step.value;
var name = _ref[0];
var before = _ref[1];
var after = _ref[2];
}
var _ref2 = Array.from(_ref);
var name = _ref2[0];
var before = _ref2[1];
var after = _ref2[2];
}

View File

@@ -2,5 +2,7 @@
var _ref = [1, 2];
this.foo = _ref[0];
this.bar = _ref[1];
var _ref2 = Array.from(_ref);
this.foo = _ref2[0];
this.bar = _ref2[1];

View File

@@ -1,6 +1,10 @@
"use strict";
var x1 = rect.topLeft[0];
var y1 = rect.topLeft[1];
var x2 = rect.bottomRight[0];
var y2 = rect.bottomRight[1];
var _ref = Array.from(rect.topLeft);
var x1 = _ref[0];
var y1 = _ref[1];
var _ref2 = Array.from(rect.bottomRight);
var x2 = _ref2[0];
var y2 = _ref2[1];

View File

@@ -2,4 +2,4 @@
var x = coords.x;
var y = coords.y;
var foo = "bar";
var foo = "bar";

View File

@@ -3,4 +3,4 @@
var x1 = rect.topLeft.x;
var y1 = rect.topLeft.y;
var x2 = rect.bottomRight.x;
var y2 = rect.bottomRight.y;
var y2 = rect.bottomRight.y;

View File

@@ -1,4 +1,4 @@
"use strict";
var x = coords.x;
var y = coords.y;
var y = coords.y;

View File

@@ -15,13 +15,17 @@ function unpackObject(_ref2) {
console.log(unpackObject({ title: "title", author: "author" }));
var unpackArray = function (_ref3, _ref4) {
var a = _ref3[0];
var b = _ref3[1];
var c = _ref3[2];
var x = _ref4[0];
var y = _ref4[1];
var z = _ref4[2];
var unpackArray = function (_ref3, _ref5) {
var _ref4 = Array.from(_ref3);
var a = _ref4[0];
var b = _ref4[1];
var c = _ref4[2];
var _ref6 = Array.from(_ref5);
var x = _ref6[0];
var y = _ref6[1];
var z = _ref6[2];
return a + b + c;
};

View File

@@ -0,0 +1,7 @@
function* f() {
for (var i = 0; i < 3; i++) {
yield i;
}
}
var [...xs] = f();
assert.deepEqual(xs, [0, 1, 2]);

View File

@@ -1,9 +1,11 @@
"use strict";
var isSorted = function (_ref) {
var x = _ref[0];
var y = _ref[1];
var wow = _ref.slice(2);
var _ref2 = Array.from(_ref);
var x = _ref2[0];
var y = _ref2[1];
var wow = Array.from(_ref2).slice(2);
if (!zs.length) return true;
if (y > x) return isSorted(zs);

View File

@@ -2,4 +2,4 @@
for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) {
i = _step.value;
}
}

View File

@@ -2,4 +2,4 @@
for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) {
var i = _step.value;
}
}

View File

@@ -1,4 +1,4 @@
define("modules-amd/exports-default/expected", ["exports"], function (exports) {
define(["exports"], function (exports) {
"use strict";
exports["default"] = 42;
@@ -12,4 +12,4 @@ define("modules-amd/exports-default/expected", ["exports"], function (exports) {
var Foo = function Foo() {};
exports["default"] = Foo;
});
});

View File

@@ -1,4 +1,4 @@
define("modules-amd/exports-from/expected", ["exports", "foo"], function (exports, _foo) {
define(["exports", "foo"], function (exports, _foo) {
"use strict";
(function (obj) {
@@ -14,4 +14,4 @@ define("modules-amd/exports-from/expected", ["exports", "foo"], function (export
exports["default"] = _foo.foo;
exports["default"] = _foo.foo;
exports.bar = _foo.bar;
});
});

View File

@@ -1,4 +1,4 @@
define("modules-amd/exports-named/expected", ["exports"], function (exports) {
define(["exports"], function (exports) {
"use strict";
exports.foo = foo;
@@ -8,4 +8,4 @@ define("modules-amd/exports-named/expected", ["exports"], function (exports) {
exports["default"] = foo;
exports["default"] = foo;
exports.bar = bar;
});
});

View File

@@ -1,4 +1,4 @@
define("modules-amd/exports-variable/expected", ["exports"], function (exports) {
define(["exports"], function (exports) {
"use strict";
exports.foo7 = foo7;
@@ -12,4 +12,4 @@ define("modules-amd/exports-variable/expected", ["exports"], function (exports)
var foo8 = function foo8() {};
exports.foo8 = foo8;
});
});

View File

@@ -1,4 +1,4 @@
define("modules-amd/hoist-function-exports/expected", ["exports", "./evens"], function (exports, _evens) {
define(["exports", "./evens"], function (exports, _evens) {
"use strict";
exports.nextOdd = nextOdd;
@@ -12,4 +12,4 @@ define("modules-amd/hoist-function-exports/expected", ["exports", "./evens"], fu
return !isEven(n);
};
})(isEven);
});
});

View File

@@ -1,6 +1,6 @@
define("modules-amd/imports-default/expected", ["exports", "foo"], function (exports, _foo) {
define(["exports", "foo"], function (exports, _foo) {
"use strict";
var foo = _foo["default"];
var foo = _foo["default"];
});
});

View File

@@ -1,5 +1,5 @@
define("modules-amd/imports-glob/expected", ["exports", "foo"], function (exports, _foo) {
define(["exports", "foo"], function (exports, _foo) {
"use strict";
var foo = _foo;
});
});

View File

@@ -1,6 +1,6 @@
define("modules-amd/imports-mixing/expected", ["exports", "foo"], function (exports, _foo) {
define(["exports", "foo"], function (exports, _foo) {
"use strict";
var foo = _foo["default"];
var xyz = _foo.baz;
});
});

View File

@@ -1,4 +1,4 @@
define("modules-amd/imports-named/expected", ["exports", "foo"], function (exports, _foo) {
define(["exports", "foo"], function (exports, _foo) {
"use strict";
var bar = _foo.bar;
@@ -7,4 +7,4 @@ define("modules-amd/imports-named/expected", ["exports", "foo"], function (expor
var baz = _foo.bar;
var baz = _foo.bar;
var xyz = _foo.xyz;
});
});

View File

@@ -1,3 +1,3 @@
define("modules-amd/imports/expected", ["exports", "foo", "foo-bar", "./directory/foo-bar"], function (exports, _foo, _fooBar, _directoryFooBar) {
define(["exports", "foo", "foo-bar", "./directory/foo-bar"], function (exports, _foo, _fooBar, _directoryFooBar) {
"use strict";
});
});

View File

@@ -1,4 +1,4 @@
define("modules-amd/overview/expected", ["exports", "foo", "foo-bar", "./directory/foo-bar"], function (exports, _foo, _fooBar, _directoryFooBar) {
define(["exports", "foo", "foo-bar", "./directory/foo-bar"], function (exports, _foo, _fooBar, _directoryFooBar) {
"use strict";
var foo = _foo["default"];
@@ -9,4 +9,4 @@ define("modules-amd/overview/expected", ["exports", "foo", "foo-bar", "./directo
var test = exports.test = 5;
exports["default"] = test;
});
});

View File

@@ -1,3 +1,3 @@
"use strict";
var foo = require("foo");
var foo = require("foo");

View File

@@ -5,4 +5,4 @@ var bar = require("foo").bar;
var baz = require("foo").baz;
var baz = require("foo").bar;
var baz = require("foo").bar;
var xyz = require("foo").xyz;
var xyz = require("foo").xyz;

View File

@@ -1,3 +1,3 @@
"use strict";
var foo = require("foo");
var foo = require("foo");

View File

@@ -5,4 +5,4 @@ var bar = require("foo").bar;
var baz = require("foo").baz;
var baz = require("foo").bar;
var baz = require("foo").bar;
var xyz = require("foo").xyz;
var xyz = require("foo").xyz;

View File

@@ -1,6 +1,6 @@
(function (factory) {
if (typeof define === "function" && define.amd) {
define("modules-umd/exports-default/expected", ["exports"], factory);
define(["exports"], factory);
} else if (typeof exports !== "undefined") {
factory(exports);
}
@@ -18,4 +18,4 @@
var Foo = function Foo() {};
exports["default"] = Foo;
});
});

View File

@@ -1,6 +1,6 @@
(function (factory) {
if (typeof define === "function" && define.amd) {
define("modules-umd/exports-from/expected", ["exports", "foo"], factory);
define(["exports", "foo"], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require("foo"));
}
@@ -20,4 +20,4 @@
exports["default"] = _foo.foo;
exports["default"] = _foo.foo;
exports.bar = _foo.bar;
});
});

View File

@@ -1,6 +1,6 @@
(function (factory) {
if (typeof define === "function" && define.amd) {
define("modules-umd/exports-named/expected", ["exports"], factory);
define(["exports"], factory);
} else if (typeof exports !== "undefined") {
factory(exports);
}
@@ -14,4 +14,4 @@
exports["default"] = foo;
exports["default"] = foo;
exports.bar = bar;
});
});

View File

@@ -1,6 +1,6 @@
(function (factory) {
if (typeof define === "function" && define.amd) {
define("modules-umd/exports-variable/expected", ["exports"], factory);
define(["exports"], factory);
} else if (typeof exports !== "undefined") {
factory(exports);
}
@@ -18,4 +18,4 @@
var foo8 = function foo8() {};
exports.foo8 = foo8;
});
});

View File

@@ -1,6 +1,6 @@
(function (factory) {
if (typeof define === "function" && define.amd) {
define("modules-umd/hoist-function-exports/expected", ["exports", "./evens"], factory);
define(["exports", "./evens"], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require("./evens"));
}
@@ -18,4 +18,4 @@
return !isEven(n);
};
})(isEven);
});
});

View File

@@ -1,6 +1,6 @@
(function (factory) {
if (typeof define === "function" && define.amd) {
define("modules-umd/imports-default/expected", ["exports", "foo"], factory);
define(["exports", "foo"], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require("foo"));
}
@@ -9,4 +9,4 @@
var foo = _foo["default"];
var foo = _foo["default"];
});
});

View File

@@ -1,6 +1,6 @@
(function (factory) {
if (typeof define === "function" && define.amd) {
define("modules-umd/imports-glob/expected", ["exports", "foo"], factory);
define(["exports", "foo"], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require("foo"));
}
@@ -8,4 +8,4 @@
"use strict";
var foo = _foo;
});
});

View File

@@ -1,6 +1,6 @@
(function (factory) {
if (typeof define === "function" && define.amd) {
define("modules-umd/imports-mixing/expected", ["exports", "foo"], factory);
define(["exports", "foo"], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require("foo"));
}
@@ -9,4 +9,4 @@
var foo = _foo["default"];
var xyz = _foo.baz;
});
});

View File

@@ -1,6 +1,6 @@
(function (factory) {
if (typeof define === "function" && define.amd) {
define("modules-umd/imports-named/expected", ["exports", "foo"], factory);
define(["exports", "foo"], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require("foo"));
}
@@ -13,4 +13,4 @@
var baz = _foo.bar;
var baz = _foo.bar;
var xyz = _foo.xyz;
});
});

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