Comparing version 4.5.1 to 4.5.2
@@ -16,2 +16,18 @@ # Changelog | ||
## 4.5.2 | ||
* **New Feature** | ||
* `returnUsedHelpers` option and add whitelist to `buildHelpers`. | ||
* **Bug Fix** | ||
* Fix function arity on self referencing inferred named functions. | ||
* **Internal** | ||
* Bump `acorn-babel`. | ||
* Start converting source to ES6... | ||
## 4.5.1 | ||
**Babel now compiles itself!** | ||
![holy shit](http://gifsec.com/wp-content/uploads/GIF/2014/03/OMG-GIF_2.gif) | ||
## 4.5.0 | ||
@@ -18,0 +34,0 @@ |
@@ -10,3 +10,4 @@ "use strict"; | ||
transform.run = function (code, opts) { | ||
opts = opts || {}; | ||
if (!opts) opts = {}; | ||
opts.sourceMap = "inline"; | ||
@@ -17,4 +18,5 @@ return new Function(transform(code, opts).code)(); | ||
transform.load = function (url, callback, opts, hold) { | ||
opts = opts || {}; | ||
opts.filename = opts.filename || url; | ||
if (!opts) opts = {}; | ||
var _opts = opts; | ||
if (!_opts.filename) _opts.filename = url; | ||
@@ -21,0 +23,0 @@ var xhr = global.ActiveXObject ? new global.ActiveXObject("Microsoft.XMLHTTP") : new global.XMLHttpRequest(); |
@@ -55,5 +55,6 @@ "use strict"; | ||
exports.transformFileSync = function (filename, opts) { | ||
opts = opts || {}; | ||
if (!opts) opts = {}; | ||
opts.filename = filename; | ||
return transform(fs.readFileSync(filename), opts); | ||
}; |
@@ -142,3 +142,3 @@ "use strict"; | ||
// normalize options | ||
opts = opts || {}; | ||
if (!opts) opts = {}; | ||
@@ -145,0 +145,0 @@ if (opts.only != null) onlyRegex = util.regexify(opts.only); |
@@ -17,3 +17,3 @@ "use strict"; | ||
var rel = ".babelrc"; | ||
opts = opts || {}; | ||
if (!opts) opts = {}; | ||
@@ -20,0 +20,0 @@ function find(start, rel) { |
@@ -8,3 +8,3 @@ "use strict"; | ||
module.exports = function () { | ||
module.exports = function (whitelist) { | ||
var namespace = t.identifier("babelHelpers"); | ||
@@ -18,5 +18,5 @@ | ||
buildHelpers(body, namespace); | ||
buildHelpers(body, namespace, whitelist); | ||
return generator(tree).code; | ||
}; |
@@ -9,6 +9,10 @@ "use strict"; | ||
module.exports = function (body, namespace) { | ||
var whitelist = arguments[2] === undefined ? [] : arguments[2]; | ||
each(File.helpers, function (name) { | ||
var key = t.identifier(t.toIdentifier(name)); | ||
if (whitelist.length && whitelist.indexOf(key) >= 0) return; | ||
body.push(t.expressionStatement(t.assignmentExpression("=", t.memberExpression(namespace, key), util.template(name)))); | ||
}); | ||
}; |
@@ -83,3 +83,3 @@ "use strict"; | ||
removeLast = removeLast || false; | ||
if (!removeLast) removeLast = false; | ||
@@ -86,0 +86,0 @@ if (isNumber(i)) { |
@@ -23,3 +23,3 @@ "use strict"; | ||
function CodeGenerator(ast, opts, code) { | ||
opts = opts || {}; | ||
if (!opts) opts = {}; | ||
@@ -116,3 +116,4 @@ this.comments = ast.comments || []; | ||
print.sequence = function (nodes, opts) { | ||
opts = opts || {}; | ||
if (!opts) opts = {}; | ||
opts.statement = true; | ||
@@ -127,4 +128,6 @@ return _this.printJoin(print, nodes, opts); | ||
print.list = function (items, opts) { | ||
opts = opts || {}; | ||
opts.separator = opts.separator || ", "; | ||
if (!opts) opts = {}; | ||
var _opts = opts; | ||
if (!_opts.separator) _opts.separator = ", "; | ||
print.join(items, opts); | ||
@@ -158,3 +161,3 @@ }; | ||
opts = opts || {}; | ||
if (!opts) opts = {}; | ||
@@ -231,3 +234,3 @@ var newline = function (leading) { | ||
opts = opts || {}; | ||
if (!opts) opts = {}; | ||
@@ -234,0 +237,0 @@ var len = nodes.length; |
@@ -19,3 +19,3 @@ "use strict"; | ||
})(function (node, state) { | ||
state = state || {}; | ||
if (!state) state = {}; | ||
@@ -34,3 +34,4 @@ if (t.isMemberExpression(node)) { | ||
} else if (t.isIdentifier(node)) { | ||
state.hasHelper = state.hasHelper || isHelper(node.callee); | ||
var _state = state; | ||
if (!_state.hasHelper) _state.hasHelper = isHelper(node.callee); | ||
} | ||
@@ -37,0 +38,0 @@ |
@@ -27,2 +27,3 @@ "use strict"; | ||
this.usedHelpers = {}; | ||
this.dynamicData = {}; | ||
@@ -40,3 +41,3 @@ this.data = {}; | ||
File.validOptions = ["filename", "filenameRelative", "blacklist", "whitelist", "loose", "optional", "modules", "sourceMap", "sourceMapName", "sourceFileName", "sourceRoot", "moduleRoot", "moduleIds", "comments", "reactCompat", "keepModuleIdExtensions", "code", "ast", "playground", "experimental", "externalHelpers", "auxiliaryComment", "compact", "resolveModuleSource", "moduleId", | ||
File.validOptions = ["filename", "filenameRelative", "blacklist", "whitelist", "loose", "optional", "modules", "sourceMap", "sourceMapName", "sourceFileName", "sourceRoot", "moduleRoot", "moduleIds", "comments", "reactCompat", "keepModuleIdExtensions", "code", "ast", "playground", "experimental", "externalHelpers", "auxiliaryComment", "compact", "returnUsedHelpers", "resolveModuleSource", "moduleId", | ||
@@ -61,2 +62,3 @@ // legacy | ||
resolveModuleSource: null, | ||
returnUsedHelpers: false, | ||
externalHelpers: false, | ||
@@ -237,3 +239,4 @@ auxilaryComment: "", | ||
File.prototype.addImport = function (source, name, noDefault) { | ||
name = name || source; | ||
if (!name) name = source; | ||
var id = this.dynamicImportIds[name]; | ||
@@ -264,3 +267,5 @@ | ||
if (comment) { | ||
node.leadingComments = node.leadingComments || []; | ||
var _node = node; | ||
if (!_node.leadingComments) _node.leadingComments = []; | ||
node.leadingComments.push({ | ||
@@ -284,2 +289,4 @@ type: "Line", | ||
this.usedHelpers[name] = true; | ||
var runtime = this.get("helpersNamespace"); | ||
@@ -305,3 +312,3 @@ if (runtime) { | ||
File.prototype.errorWithNode = function (node, msg, Error) { | ||
Error = Error || SyntaxError; | ||
if (!Error) Error = SyntaxError; | ||
@@ -384,3 +391,3 @@ var loc = node.loc.start; | ||
var stack = this.transformerStack; | ||
scope = scope || this.scope; | ||
if (!scope) scope = this.scope; | ||
@@ -404,2 +411,6 @@ checkNode(stack, node, scope); | ||
if (this.opts.returnUsedHelpers) { | ||
result.usedHelpers = Object.keys(this.usedHelpers); | ||
} | ||
if (opts.ast) result.ast = ast; | ||
@@ -406,0 +417,0 @@ if (!opts.code) return result; |
"use strict"; | ||
var getFunctionArity = require("./get-function-arity"); | ||
var util = require("../../util"); | ||
@@ -26,3 +27,3 @@ var t = require("../../types"); | ||
if (method.generator) templateName += "-generator"; | ||
return util.template(templateName, { | ||
var template = util.template(templateName, { | ||
FUNCTION: method, | ||
@@ -33,2 +34,11 @@ FUNCTION_ID: id, | ||
}); | ||
// shim in dummy params to retain function arity, if you try to read the | ||
// source then you'll get the original since it's proxied so it's all good | ||
var params = template.callee.body.body[0].declarations[0].init.params; | ||
for (var i = 0, len = getFunctionArity(method); i < len; i++) { | ||
params.push(scope.generateUidIdentifier("x")); | ||
} | ||
return template; | ||
} else { | ||
@@ -94,3 +104,3 @@ method.id = id; | ||
if (t.isProperty(parent) && parent.kind === "init" && !parent.computed) { | ||
// { foo: function () {} }; | ||
// { foo() {} }; | ||
id = parent.key; | ||
@@ -97,0 +107,0 @@ } else if (t.isVariableDeclarator(parent)) { |
@@ -63,3 +63,6 @@ "use strict"; | ||
transform.namespaces[namespace] = transform.namespaces[namespace] || []; | ||
var _transform$namespaces = transform.namespaces; | ||
var _namespace = namespace; | ||
if (!_transform$namespaces[_namespace]) _transform$namespaces[_namespace] = []; | ||
transform.namespaces[namespace].push(key); | ||
@@ -66,0 +69,0 @@ transform.transformerNamespaces[key] = namespace; |
@@ -38,3 +38,6 @@ "use strict"; | ||
var occurs = this.localImportOccurences; | ||
occurs[source] = occurs[source] || 0; | ||
var _occurs = occurs; | ||
var _source = source; | ||
if (!_occurs[_source]) _occurs[_source] = 0; | ||
occurs[source] += node.specifiers.length; | ||
@@ -41,0 +44,0 @@ }; |
@@ -38,3 +38,7 @@ "use strict"; | ||
this.handlers = this.normalize(transformer); | ||
this.opts = opts || {}; | ||
var _ref = this; | ||
if (!_ref.opts) _ref.opts = {}; | ||
this.key = key; | ||
@@ -41,0 +45,0 @@ } |
"use strict"; | ||
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; | ||
var traverse = require("../../../traversal"); | ||
@@ -23,3 +25,4 @@ var object = require("../../../helpers/object"); | ||
var declar = node.declarations[i]; | ||
declar.init = declar.init || t.identifier("undefined"); | ||
var _declar = declar; | ||
if (!_declar.init) _declar.init = t.identifier("undefined"); | ||
} | ||
@@ -86,49 +89,2 @@ } | ||
/** | ||
* Description | ||
* | ||
* @param {Boolean|Node} loopParent | ||
* @param {Node} block | ||
* @param {Node} parent | ||
* @param {Scope} scope | ||
* @param {File} file | ||
*/ | ||
function BlockScoping(loopParent, block, parent, scope, file) { | ||
this.loopParent = loopParent; | ||
this.parent = parent; | ||
this.scope = scope; | ||
this.block = block; | ||
this.file = file; | ||
this.outsideLetReferences = object(); | ||
this.hasLetReferences = false; | ||
this.letReferences = block._letReferences = object(); | ||
this.body = []; | ||
} | ||
/** | ||
* Start the ball rolling. | ||
*/ | ||
BlockScoping.prototype.run = function () { | ||
var block = this.block; | ||
if (block._letDone) return; | ||
block._letDone = true; | ||
var needsClosure = this.getLetReferences(); | ||
// this is a block within a `Function/Program` so we can safely leave it be | ||
if (t.isFunction(this.parent) || t.isProgram(this.block)) return; | ||
// we can skip everything | ||
if (!this.hasLetReferences) return; | ||
if (needsClosure) { | ||
this.wrapClosure(); | ||
} else { | ||
this.remap(); | ||
} | ||
}; | ||
function replace(node, parent, scope, remaps) { | ||
@@ -159,112 +115,11 @@ if (!t.isReferencedIdentifier(node, parent)) return; | ||
/** | ||
* Description | ||
*/ | ||
BlockScoping.prototype.remap = function () { | ||
var hasRemaps = false; | ||
var letRefs = this.letReferences; | ||
var scope = this.scope; | ||
// alright, so since we aren't wrapping this block in a closure | ||
// we have to check if any of our let variables collide with | ||
// those in upper scopes and then if they do, generate a uid | ||
// for them and replace all references with it | ||
var remaps = object(); | ||
for (var key in letRefs) { | ||
// just an Identifier node we collected in `getLetReferences` | ||
// this is the defining identifier of a declaration | ||
var ref = letRefs[key]; | ||
if (scope.parentHasBinding(key) || scope.hasGlobal(key)) { | ||
var uid = scope.generateUidIdentifier(ref.name).name; | ||
ref.name = uid; | ||
hasRemaps = true; | ||
remaps[key] = remaps[uid] = { | ||
binding: ref, | ||
uid: uid | ||
}; | ||
var letReferenceBlockVisitor = { | ||
enter: function enter(node, parent, scope, state) { | ||
if (t.isFunction(node)) { | ||
scope.traverse(node, letReferenceFunctionVisitor, state); | ||
return this.skip(); | ||
} | ||
} | ||
if (!hasRemaps) return; | ||
// | ||
var loopParent = this.loopParent; | ||
if (loopParent) { | ||
traverseReplace(loopParent.right, loopParent, scope, remaps); | ||
traverseReplace(loopParent.test, loopParent, scope, remaps); | ||
traverseReplace(loopParent.update, loopParent, scope, remaps); | ||
} | ||
scope.traverse(this.block, replaceVisitor, remaps); | ||
}; | ||
/** | ||
* Description | ||
*/ | ||
BlockScoping.prototype.wrapClosure = function () { | ||
var block = this.block; | ||
var outsideRefs = this.outsideLetReferences; | ||
// remap loop heads with colliding variables | ||
if (this.loopParent) { | ||
for (var name in outsideRefs) { | ||
var id = outsideRefs[name]; | ||
if (this.scope.hasGlobal(id.name)) { | ||
delete outsideRefs[id.name]; | ||
delete this.letReferences[id.name]; | ||
this.scope.rename(id.name); | ||
this.letReferences[id.name] = id; | ||
outsideRefs[id.name] = id; | ||
} | ||
} | ||
} | ||
// if we're inside of a for loop then we search to see if there are any | ||
// `break`s, `continue`s, `return`s etc | ||
this.has = this.checkLoop(); | ||
// hoist var references to retain scope | ||
this.hoistVarDeclarations(); | ||
// turn outsideLetReferences into an array | ||
var params = values(outsideRefs); | ||
// build the closure that we're going to wrap the block with | ||
var fn = t.functionExpression(null, params, t.blockStatement(block.body)); | ||
fn._aliasFunction = true; | ||
// replace the current block body with the one we're going to build | ||
block.body = this.body; | ||
// build a call and a unique id that we can assign the return value to | ||
var call = t.callExpression(fn, params); | ||
var ret = this.scope.generateUidIdentifier("ret"); | ||
// handle generators | ||
var hasYield = traverse.hasType(fn.body, this.scope, "YieldExpression", t.FUNCTION_TYPES); | ||
if (hasYield) { | ||
fn.generator = true; | ||
call = t.yieldExpression(call, true); | ||
} | ||
// handlers async functions | ||
var hasAsync = traverse.hasType(fn.body, this.scope, "AwaitExpression", t.FUNCTION_TYPES); | ||
if (hasAsync) { | ||
fn.async = true; | ||
call = t.awaitExpression(call, true); | ||
} | ||
this.build(ret, call); | ||
}; | ||
var letReferenceFunctionVisitor = { | ||
@@ -286,6 +141,15 @@ enter: function enter(node, parent, scope, state) { | ||
var letReferenceBlockVisitor = { | ||
enter: function enter(node, parent, scope, state) { | ||
if (t.isFunction(node)) { | ||
scope.traverse(node, letReferenceFunctionVisitor, state); | ||
var hoistVarDeclarationsVisitor = { | ||
enter: function enter(node, parent, scope, self) { | ||
if (t.isForStatement(node)) { | ||
if (isVar(node.init, node)) { | ||
node.init = t.sequenceExpression(self.pushDeclar(node.init)); | ||
} | ||
} else if (t.isFor(node)) { | ||
if (isVar(node.left, node)) { | ||
node.left = node.left.declarations[0].id; | ||
} | ||
} else if (isVar(node, parent)) { | ||
return self.pushDeclar(node).map(t.expressionStatement); | ||
} else if (t.isFunction(node)) { | ||
return this.skip(); | ||
@@ -296,52 +160,8 @@ } | ||
/** | ||
* Description | ||
*/ | ||
BlockScoping.prototype.getLetReferences = function () { | ||
var block = this.block; | ||
var declarators = block._letDeclarators || []; | ||
var declar; | ||
// | ||
for (var i = 0; i < declarators.length; i++) { | ||
declar = declarators[i]; | ||
extend(this.outsideLetReferences, t.getBindingIdentifiers(declar)); | ||
} | ||
// | ||
if (block.body) { | ||
for (i = 0; i < block.body.length; i++) { | ||
declar = block.body[i]; | ||
if (isLet(declar, block)) { | ||
declarators = declarators.concat(declar.declarations); | ||
} | ||
var loopLabelVisitor = { | ||
enter: function enter(node, parent, scope, state) { | ||
if (t.isLabeledStatement(node)) { | ||
state.innerLabels.push(node.label.name); | ||
} | ||
} | ||
// | ||
for (i = 0; i < declarators.length; i++) { | ||
declar = declarators[i]; | ||
var keys = t.getBindingIdentifiers(declar); | ||
extend(this.letReferences, keys); | ||
this.hasLetReferences = true; | ||
} | ||
// no let references so we can just quit | ||
if (!this.hasLetReferences) return; | ||
// set let references to plain var references | ||
standardizeLets(declarators); | ||
var state = { | ||
letReferences: this.letReferences, | ||
closurify: false | ||
}; | ||
// traverse through this block, stopping on functions and checking if they | ||
// contain any local let references | ||
this.scope.traverse(this.block, letReferenceBlockVisitor, state); | ||
return state.closurify; | ||
}; | ||
@@ -407,152 +227,342 @@ | ||
var loopLabelVisitor = { | ||
enter: function enter(node, parent, scope, state) { | ||
if (t.isLabeledStatement(node)) { | ||
state.innerLabels.push(node.label.name); | ||
} | ||
var BlockScoping = (function () { | ||
/** | ||
* Description | ||
* | ||
* @param {Boolean|Node} loopParent | ||
* @param {Node} block | ||
* @param {Node} parent | ||
* @param {Scope} scope | ||
* @param {File} file | ||
*/ | ||
function BlockScoping(loopParent, block, parent, scope, file) { | ||
_classCallCheck(this, BlockScoping); | ||
this.loopParent = loopParent; | ||
this.parent = parent; | ||
this.scope = scope; | ||
this.block = block; | ||
this.file = file; | ||
this.outsideLetReferences = object(); | ||
this.hasLetReferences = false; | ||
this.letReferences = block._letReferences = object(); | ||
this.body = []; | ||
} | ||
}; | ||
/** | ||
* If we're inside of a loop then traverse it and check if it has one of | ||
* the following node types `ReturnStatement`, `BreakStatement`, | ||
* `ContinueStatement` and replace it with a return value that we can track | ||
* later on. | ||
* | ||
* @returns {Object} | ||
*/ | ||
/** | ||
* Start the ball rolling. | ||
*/ | ||
BlockScoping.prototype.checkLoop = function () { | ||
var state = { | ||
hasBreakContinue: false, | ||
ignoreLabeless: false, | ||
innerLabels: [], | ||
hasReturn: false, | ||
isLoop: !!this.loopParent, | ||
map: {} | ||
BlockScoping.prototype.run = function run() { | ||
var block = this.block; | ||
if (block._letDone) return; | ||
block._letDone = true; | ||
var needsClosure = this.getLetReferences(); | ||
// this is a block within a `Function/Program` so we can safely leave it be | ||
if (t.isFunction(this.parent) || t.isProgram(this.block)) return; | ||
// we can skip everything | ||
if (!this.hasLetReferences) return; | ||
if (needsClosure) { | ||
this.wrapClosure(); | ||
} else { | ||
this.remap(); | ||
} | ||
}; | ||
this.scope.traverse(this.block, loopLabelVisitor, state); | ||
this.scope.traverse(this.block, loopVisitor, state); | ||
/** | ||
* Description | ||
*/ | ||
return state; | ||
}; | ||
BlockScoping.prototype.remap = function remap() { | ||
var hasRemaps = false; | ||
var letRefs = this.letReferences; | ||
var scope = this.scope; | ||
var hoistVarDeclarationsVisitor = { | ||
enter: function enter(node, parent, scope, self) { | ||
if (t.isForStatement(node)) { | ||
if (isVar(node.init, node)) { | ||
node.init = t.sequenceExpression(self.pushDeclar(node.init)); | ||
// alright, so since we aren't wrapping this block in a closure | ||
// we have to check if any of our let variables collide with | ||
// those in upper scopes and then if they do, generate a uid | ||
// for them and replace all references with it | ||
var remaps = object(); | ||
for (var key in letRefs) { | ||
// just an Identifier node we collected in `getLetReferences` | ||
// this is the defining identifier of a declaration | ||
var ref = letRefs[key]; | ||
if (scope.parentHasBinding(key) || scope.hasGlobal(key)) { | ||
var uid = scope.generateUidIdentifier(ref.name).name; | ||
ref.name = uid; | ||
hasRemaps = true; | ||
remaps[key] = remaps[uid] = { | ||
binding: ref, | ||
uid: uid | ||
}; | ||
} | ||
} else if (t.isFor(node)) { | ||
if (isVar(node.left, node)) { | ||
node.left = node.left.declarations[0].id; | ||
} | ||
if (!hasRemaps) return; | ||
// | ||
var loopParent = this.loopParent; | ||
if (loopParent) { | ||
traverseReplace(loopParent.right, loopParent, scope, remaps); | ||
traverseReplace(loopParent.test, loopParent, scope, remaps); | ||
traverseReplace(loopParent.update, loopParent, scope, remaps); | ||
} | ||
scope.traverse(this.block, replaceVisitor, remaps); | ||
}; | ||
/** | ||
* Description | ||
*/ | ||
BlockScoping.prototype.wrapClosure = function wrapClosure() { | ||
var block = this.block; | ||
var outsideRefs = this.outsideLetReferences; | ||
// remap loop heads with colliding variables | ||
if (this.loopParent) { | ||
for (var name in outsideRefs) { | ||
var id = outsideRefs[name]; | ||
if (this.scope.hasGlobal(id.name)) { | ||
delete outsideRefs[id.name]; | ||
delete this.letReferences[id.name]; | ||
this.scope.rename(id.name); | ||
this.letReferences[id.name] = id; | ||
outsideRefs[id.name] = id; | ||
} | ||
} | ||
} else if (isVar(node, parent)) { | ||
return self.pushDeclar(node).map(t.expressionStatement); | ||
} else if (t.isFunction(node)) { | ||
return this.skip(); | ||
} | ||
} | ||
}; | ||
/** | ||
* Hoist all var declarations in this block to before it so they retain scope | ||
* once we wrap everything in a closure. | ||
*/ | ||
// if we're inside of a for loop then we search to see if there are any | ||
// `break`s, `continue`s, `return`s etc | ||
this.has = this.checkLoop(); | ||
BlockScoping.prototype.hoistVarDeclarations = function () { | ||
traverse(this.block, hoistVarDeclarationsVisitor, this.scope, this); | ||
}; | ||
// hoist var references to retain scope | ||
this.hoistVarDeclarations(); | ||
/** | ||
* Turn a `VariableDeclaration` into an array of `AssignmentExpressions` with | ||
* their declarations hoisted to before the closure wrapper. | ||
* | ||
* @param {Node} node VariableDeclaration | ||
* @returns {Array} | ||
*/ | ||
// turn outsideLetReferences into an array | ||
var params = values(outsideRefs); | ||
BlockScoping.prototype.pushDeclar = function (node) { | ||
this.body.push(t.variableDeclaration(node.kind, node.declarations.map(function (declar) { | ||
return t.variableDeclarator(declar.id); | ||
}))); | ||
// build the closure that we're going to wrap the block with | ||
var fn = t.functionExpression(null, params, t.blockStatement(block.body)); | ||
fn._aliasFunction = true; | ||
var replace = []; | ||
// replace the current block body with the one we're going to build | ||
block.body = this.body; | ||
for (var i = 0; i < node.declarations.length; i++) { | ||
var declar = node.declarations[i]; | ||
if (!declar.init) continue; | ||
// build a call and a unique id that we can assign the return value to | ||
var call = t.callExpression(fn, params); | ||
var ret = this.scope.generateUidIdentifier("ret"); | ||
var expr = t.assignmentExpression("=", declar.id, declar.init); | ||
replace.push(t.inherits(expr, declar)); | ||
} | ||
// handle generators | ||
var hasYield = traverse.hasType(fn.body, this.scope, "YieldExpression", t.FUNCTION_TYPES); | ||
if (hasYield) { | ||
fn.generator = true; | ||
call = t.yieldExpression(call, true); | ||
} | ||
return replace; | ||
}; | ||
// handlers async functions | ||
var hasAsync = traverse.hasType(fn.body, this.scope, "AwaitExpression", t.FUNCTION_TYPES); | ||
if (hasAsync) { | ||
fn.async = true; | ||
call = t.awaitExpression(call, true); | ||
} | ||
/** | ||
* Push the closure to the body. | ||
* | ||
* @param {Node} ret Identifier | ||
* @param {Node} call CallExpression | ||
*/ | ||
this.build(ret, call); | ||
}; | ||
BlockScoping.prototype.build = function (ret, call) { | ||
var has = this.has; | ||
if (has.hasReturn || has.hasBreakContinue) { | ||
this.buildHas(ret, call); | ||
} else { | ||
this.body.push(t.expressionStatement(call)); | ||
} | ||
}; | ||
/** | ||
* Description | ||
*/ | ||
/** | ||
* Description | ||
* | ||
* @param {Node} ret Identifier | ||
* @param {Node} call CallExpression | ||
*/ | ||
BlockScoping.prototype.getLetReferences = function getLetReferences() { | ||
var block = this.block; | ||
BlockScoping.prototype.buildHas = function (ret, call) { | ||
var body = this.body; | ||
var declarators = block._letDeclarators || []; | ||
var declar; | ||
body.push(t.variableDeclaration("var", [t.variableDeclarator(ret, call)])); | ||
// | ||
for (var i = 0; i < declarators.length; i++) { | ||
declar = declarators[i]; | ||
extend(this.outsideLetReferences, t.getBindingIdentifiers(declar)); | ||
} | ||
var loopParent = this.loopParent; | ||
var retCheck; | ||
var has = this.has; | ||
var cases = []; | ||
// | ||
if (block.body) { | ||
for (i = 0; i < block.body.length; i++) { | ||
declar = block.body[i]; | ||
if (isLet(declar, block)) { | ||
declarators = declarators.concat(declar.declarations); | ||
} | ||
} | ||
} | ||
if (has.hasReturn) { | ||
// typeof ret === "object" | ||
retCheck = util.template("let-scoping-return", { | ||
RETURN: ret | ||
}); | ||
} | ||
// | ||
for (i = 0; i < declarators.length; i++) { | ||
declar = declarators[i]; | ||
var keys = t.getBindingIdentifiers(declar); | ||
extend(this.letReferences, keys); | ||
this.hasLetReferences = true; | ||
} | ||
if (has.hasBreakContinue) { | ||
if (!loopParent) { | ||
throw new Error("Has no loop parent but we're trying to reassign breaks " + "and continues, something is going wrong here."); | ||
// no let references so we can just quit | ||
if (!this.hasLetReferences) return; | ||
// set let references to plain var references | ||
standardizeLets(declarators); | ||
var state = { | ||
letReferences: this.letReferences, | ||
closurify: false | ||
}; | ||
// traverse through this block, stopping on functions and checking if they | ||
// contain any local let references | ||
this.scope.traverse(this.block, letReferenceBlockVisitor, state); | ||
return state.closurify; | ||
}; | ||
/** | ||
* If we're inside of a loop then traverse it and check if it has one of | ||
* the following node types `ReturnStatement`, `BreakStatement`, | ||
* `ContinueStatement` and replace it with a return value that we can track | ||
* later on. | ||
* | ||
* @returns {Object} | ||
*/ | ||
BlockScoping.prototype.checkLoop = function checkLoop() { | ||
var state = { | ||
hasBreakContinue: false, | ||
ignoreLabeless: false, | ||
innerLabels: [], | ||
hasReturn: false, | ||
isLoop: !!this.loopParent, | ||
map: {} | ||
}; | ||
this.scope.traverse(this.block, loopLabelVisitor, state); | ||
this.scope.traverse(this.block, loopVisitor, state); | ||
return state; | ||
}; | ||
/** | ||
* Hoist all var declarations in this block to before it so they retain scope | ||
* once we wrap everything in a closure. | ||
*/ | ||
BlockScoping.prototype.hoistVarDeclarations = function hoistVarDeclarations() { | ||
traverse(this.block, hoistVarDeclarationsVisitor, this.scope, this); | ||
}; | ||
/** | ||
* Turn a `VariableDeclaration` into an array of `AssignmentExpressions` with | ||
* their declarations hoisted to before the closure wrapper. | ||
* | ||
* @param {Node} node VariableDeclaration | ||
* @returns {Array} | ||
*/ | ||
BlockScoping.prototype.pushDeclar = function pushDeclar(node) { | ||
this.body.push(t.variableDeclaration(node.kind, node.declarations.map(function (declar) { | ||
return t.variableDeclarator(declar.id); | ||
}))); | ||
var replace = []; | ||
for (var i = 0; i < node.declarations.length; i++) { | ||
var declar = node.declarations[i]; | ||
if (!declar.init) continue; | ||
var expr = t.assignmentExpression("=", declar.id, declar.init); | ||
replace.push(t.inherits(expr, declar)); | ||
} | ||
for (var key in has.map) { | ||
cases.push(t.switchCase(t.literal(key), [has.map[key]])); | ||
return replace; | ||
}; | ||
/** | ||
* Push the closure to the body. | ||
* | ||
* @param {Node} ret Identifier | ||
* @param {Node} call CallExpression | ||
*/ | ||
BlockScoping.prototype.build = function build(ret, call) { | ||
var has = this.has; | ||
if (has.hasReturn || has.hasBreakContinue) { | ||
this.buildHas(ret, call); | ||
} else { | ||
this.body.push(t.expressionStatement(call)); | ||
} | ||
}; | ||
/** | ||
* Description | ||
* | ||
* @param {Node} ret Identifier | ||
* @param {Node} call CallExpression | ||
*/ | ||
BlockScoping.prototype.buildHas = function buildHas(ret, call) { | ||
var body = this.body; | ||
body.push(t.variableDeclaration("var", [t.variableDeclarator(ret, call)])); | ||
var loopParent = this.loopParent; | ||
var retCheck; | ||
var has = this.has; | ||
var cases = []; | ||
if (has.hasReturn) { | ||
cases.push(t.switchCase(null, [retCheck])); | ||
// typeof ret === "object" | ||
retCheck = util.template("let-scoping-return", { | ||
RETURN: ret | ||
}); | ||
} | ||
if (cases.length === 1) { | ||
var single = cases[0]; | ||
body.push(this.file.attachAuxiliaryComment(t.ifStatement(t.binaryExpression("===", ret, single.test), single.consequent[0]))); | ||
if (has.hasBreakContinue) { | ||
if (!loopParent) { | ||
throw new Error("Has no loop parent but we're trying to reassign breaks " + "and continues, something is going wrong here."); | ||
} | ||
for (var key in has.map) { | ||
cases.push(t.switchCase(t.literal(key), [has.map[key]])); | ||
} | ||
if (has.hasReturn) { | ||
cases.push(t.switchCase(null, [retCheck])); | ||
} | ||
if (cases.length === 1) { | ||
var single = cases[0]; | ||
body.push(this.file.attachAuxiliaryComment(t.ifStatement(t.binaryExpression("===", ret, single.test), single.consequent[0]))); | ||
} else { | ||
body.push(this.file.attachAuxiliaryComment(t.switchStatement(ret, cases))); | ||
} | ||
} else { | ||
body.push(this.file.attachAuxiliaryComment(t.switchStatement(ret, cases))); | ||
if (has.hasReturn) { | ||
body.push(this.file.attachAuxiliaryComment(retCheck)); | ||
} | ||
} | ||
} else { | ||
if (has.hasReturn) { | ||
body.push(this.file.attachAuxiliaryComment(retCheck)); | ||
} | ||
} | ||
}; | ||
}; | ||
return BlockScoping; | ||
})(); |
"use strict"; | ||
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; | ||
var ReplaceSupers = require("../../helpers/replace-supers"); | ||
@@ -32,257 +34,264 @@ var nameMethod = require("../../helpers/name-method"); | ||
/** | ||
* Description | ||
* | ||
* @param {Node} node | ||
* @param {File} file | ||
* @param {Scope} scope | ||
* @param {Boolean} isStatement | ||
*/ | ||
var ClassTransformer = (function () { | ||
function ClassTransformer(node, file, scope, isStatement) { | ||
this.isStatement = isStatement; | ||
this.scope = scope; | ||
this.node = node; | ||
this.file = file; | ||
/** | ||
* Description | ||
* | ||
* @param {Node} node | ||
* @param {File} file | ||
* @param {Scope} scope | ||
* @param {Boolean} isStatement | ||
*/ | ||
this.hasInstanceMutators = false; | ||
this.hasStaticMutators = false; | ||
function ClassTransformer(node, file, scope, isStatement) { | ||
_classCallCheck(this, ClassTransformer); | ||
this.instanceMutatorMap = {}; | ||
this.staticMutatorMap = {}; | ||
this.hasConstructor = false; | ||
this.className = node.id || scope.generateUidIdentifier("class"); | ||
this.superName = node.superClass || t.identifier("Function"); | ||
this.hasSuper = !!node.superClass; | ||
this.isLoose = file.isLoose("es6.classes"); | ||
} | ||
this.isStatement = isStatement; | ||
this.scope = scope; | ||
this.node = node; | ||
this.file = file; | ||
/** | ||
* Description | ||
* | ||
* @returns {Array} | ||
*/ | ||
this.hasInstanceMutators = false; | ||
this.hasStaticMutators = false; | ||
ClassTransformer.prototype.run = function () { | ||
var superName = this.superName; | ||
var className = this.className; | ||
var classBody = this.node.body.body; | ||
var file = this.file; | ||
this.instanceMutatorMap = {}; | ||
this.staticMutatorMap = {}; | ||
this.hasConstructor = false; | ||
this.className = node.id || scope.generateUidIdentifier("class"); | ||
this.superName = node.superClass || t.identifier("Function"); | ||
this.hasSuper = !!node.superClass; | ||
this.isLoose = file.isLoose("es6.classes"); | ||
} | ||
// | ||
/** | ||
* Description | ||
* | ||
* @returns {Array} | ||
*/ | ||
var body = this.body = []; | ||
ClassTransformer.prototype.run = function run() { | ||
var superName = this.superName; | ||
var className = this.className; | ||
var classBody = this.node.body.body; | ||
var file = this.file; | ||
var constructorBody = t.blockStatement([t.expressionStatement(t.callExpression(file.addHelper("class-call-check"), [t.thisExpression(), className]))]); | ||
// | ||
var constructor; | ||
if (this.node.id) { | ||
constructor = t.functionDeclaration(className, [], constructorBody); | ||
body.push(constructor); | ||
} else { | ||
var constructorName = null; | ||
// when a class has no parent and there is only a constructor or no body | ||
// then the constructor is not wrapped in a closure and needs to be named | ||
var containsOnlyConstructor = classBody.length === 1 && classBody[0].key.name === "constructor"; | ||
if (!this.hasSuper && (classBody.length === 0 || containsOnlyConstructor)) { | ||
constructorName = className; | ||
var body = this.body = []; | ||
var constructorBody = t.blockStatement([t.expressionStatement(t.callExpression(file.addHelper("class-call-check"), [t.thisExpression(), className]))]); | ||
var constructor; | ||
if (this.node.id) { | ||
constructor = t.functionDeclaration(className, [], constructorBody); | ||
body.push(constructor); | ||
} else { | ||
var constructorName = null; | ||
// when a class has no parent and there is only a constructor or no body | ||
// then the constructor is not wrapped in a closure and needs to be named | ||
var containsOnlyConstructor = classBody.length === 1 && classBody[0].key.name === "constructor"; | ||
if (!this.hasSuper && (classBody.length === 0 || containsOnlyConstructor)) { | ||
constructorName = className; | ||
} | ||
constructor = t.functionExpression(constructorName, [], constructorBody); | ||
body.push(t.variableDeclaration("var", [t.variableDeclarator(className, constructor)])); | ||
} | ||
this.constructor = constructor; | ||
constructor = t.functionExpression(constructorName, [], constructorBody); | ||
body.push(t.variableDeclaration("var", [t.variableDeclarator(className, constructor)])); | ||
} | ||
this.constructor = constructor; | ||
var closureParams = []; | ||
var closureArgs = []; | ||
var closureParams = []; | ||
var closureArgs = []; | ||
// | ||
// | ||
if (this.hasSuper) { | ||
closureArgs.push(superName); | ||
if (this.hasSuper) { | ||
closureArgs.push(superName); | ||
if (!t.isIdentifier(superName)) { | ||
superName = this.scope.generateUidBasedOnNode(superName, this.file); | ||
} | ||
if (!t.isIdentifier(superName)) { | ||
superName = this.scope.generateUidBasedOnNode(superName, this.file); | ||
closureParams.push(superName); | ||
this.superName = superName; | ||
body.push(t.expressionStatement(t.callExpression(file.addHelper("inherits"), [className, superName]))); | ||
} | ||
closureParams.push(superName); | ||
this.buildBody(); | ||
this.superName = superName; | ||
body.push(t.expressionStatement(t.callExpression(file.addHelper("inherits"), [className, superName]))); | ||
} | ||
t.inheritsComments(body[0], this.node); | ||
this.buildBody(); | ||
var init; | ||
t.inheritsComments(body[0], this.node); | ||
if (body.length === 1) { | ||
// only a constructor so no need for a closure container | ||
init = t.toExpression(constructor); | ||
} else { | ||
body.push(t.returnStatement(className)); | ||
init = t.callExpression(t.functionExpression(null, closureParams, t.blockStatement(body)), closureArgs); | ||
} | ||
var init; | ||
if (this.isStatement) { | ||
return t.variableDeclaration("let", [t.variableDeclarator(className, init)]); | ||
} else { | ||
return init; | ||
} | ||
}; | ||
if (body.length === 1) { | ||
// only a constructor so no need for a closure container | ||
init = t.toExpression(constructor); | ||
} else { | ||
body.push(t.returnStatement(className)); | ||
init = t.callExpression(t.functionExpression(null, closureParams, t.blockStatement(body)), closureArgs); | ||
} | ||
/** | ||
* Description | ||
*/ | ||
if (this.isStatement) { | ||
return t.variableDeclaration("let", [t.variableDeclarator(className, init)]); | ||
} else { | ||
return init; | ||
} | ||
}; | ||
ClassTransformer.prototype.buildBody = function buildBody() { | ||
var constructor = this.constructor; | ||
var className = this.className; | ||
var superName = this.superName; | ||
var classBody = this.node.body.body; | ||
var body = this.body; | ||
/** | ||
* Description | ||
*/ | ||
for (var i = 0; i < classBody.length; i++) { | ||
var node = classBody[i]; | ||
if (t.isMethodDefinition(node)) { | ||
var replaceSupers = new ReplaceSupers({ | ||
methodNode: node, | ||
className: this.className, | ||
superName: this.superName, | ||
isStatic: node["static"], | ||
isLoose: this.isLoose, | ||
scope: this.scope, | ||
file: this.file | ||
}, true); | ||
replaceSupers.replace(); | ||
ClassTransformer.prototype.buildBody = function () { | ||
var constructor = this.constructor; | ||
var className = this.className; | ||
var superName = this.superName; | ||
var classBody = this.node.body.body; | ||
var body = this.body; | ||
for (var i = 0; i < classBody.length; i++) { | ||
var node = classBody[i]; | ||
if (t.isMethodDefinition(node)) { | ||
var replaceSupers = new ReplaceSupers({ | ||
methodNode: node, | ||
className: this.className, | ||
superName: this.superName, | ||
isStatic: node["static"], | ||
isLoose: this.isLoose, | ||
scope: this.scope, | ||
file: this.file | ||
}, true); | ||
replaceSupers.replace(); | ||
if (!node.computed && t.isIdentifier(node.key, { name: "constructor" }) || t.isLiteral(node.key, { value: "constructor" })) { | ||
this.pushConstructor(node); | ||
} else { | ||
this.pushMethod(node); | ||
if (!node.computed && t.isIdentifier(node.key, { name: "constructor" }) || t.isLiteral(node.key, { value: "constructor" })) { | ||
this.pushConstructor(node); | ||
} else { | ||
this.pushMethod(node); | ||
} | ||
} else if (t.isPrivateDeclaration(node)) { | ||
this.closure = true; | ||
body.unshift(node); | ||
} else if (t.isClassProperty(node)) { | ||
this.pushProperty(node); | ||
} | ||
} else if (t.isPrivateDeclaration(node)) { | ||
this.closure = true; | ||
body.unshift(node); | ||
} else if (t.isClassProperty(node)) { | ||
this.pushProperty(node); | ||
} | ||
} | ||
// we have no constructor, we have a super, and the super doesn't appear to be falsy | ||
if (!this.hasConstructor && this.hasSuper && !t.isFalsyExpression(superName)) { | ||
var helperName = "class-super-constructor-call"; | ||
if (this.isLoose) helperName += "-loose"; | ||
constructor.body.body.push(util.template(helperName, { | ||
CLASS_NAME: className, | ||
SUPER_NAME: this.superName | ||
}, true)); | ||
} | ||
// we have no constructor, we have a super, and the super doesn't appear to be falsy | ||
if (!this.hasConstructor && this.hasSuper && !t.isFalsyExpression(superName)) { | ||
var helperName = "class-super-constructor-call"; | ||
if (this.isLoose) helperName += "-loose"; | ||
constructor.body.body.push(util.template(helperName, { | ||
CLASS_NAME: className, | ||
SUPER_NAME: this.superName | ||
}, true)); | ||
} | ||
var instanceProps; | ||
var staticProps; | ||
var instanceProps; | ||
var staticProps; | ||
if (this.hasInstanceMutators) { | ||
instanceProps = defineMap.build(this.instanceMutatorMap); | ||
} | ||
if (this.hasInstanceMutators) { | ||
instanceProps = defineMap.build(this.instanceMutatorMap); | ||
} | ||
if (this.hasStaticMutators) { | ||
staticProps = defineMap.build(this.staticMutatorMap); | ||
} | ||
if (this.hasStaticMutators) { | ||
staticProps = defineMap.build(this.staticMutatorMap); | ||
} | ||
if (instanceProps || staticProps) { | ||
staticProps = staticProps || t.literal(null); | ||
if (instanceProps || staticProps) { | ||
if (!staticProps) staticProps = t.literal(null); | ||
var args = [className, staticProps]; | ||
if (instanceProps) args.push(instanceProps); | ||
var args = [className, staticProps]; | ||
if (instanceProps) args.push(instanceProps); | ||
body.push(t.expressionStatement(t.callExpression(this.file.addHelper("prototype-properties"), args))); | ||
} | ||
}; | ||
body.push(t.expressionStatement(t.callExpression(this.file.addHelper("prototype-properties"), args))); | ||
} | ||
}; | ||
/** | ||
* Push a method to its respective mutatorMap. | ||
* | ||
* @param {Node} node MethodDefinition | ||
*/ | ||
/** | ||
* Push a method to its respective mutatorMap. | ||
* | ||
* @param {Node} node MethodDefinition | ||
*/ | ||
ClassTransformer.prototype.pushMethod = function (node) { | ||
var methodName = node.key; | ||
ClassTransformer.prototype.pushMethod = function pushMethod(node) { | ||
var methodName = node.key; | ||
var kind = node.kind; | ||
var kind = node.kind; | ||
if (kind === "") { | ||
nameMethod.property(node, this.file, this.scope); | ||
if (kind === "") { | ||
nameMethod.property(node, this.file, this.scope); | ||
if (this.isLoose) { | ||
// use assignments instead of define properties for loose classes | ||
if (this.isLoose) { | ||
// use assignments instead of define properties for loose classes | ||
var className = this.className; | ||
if (!node["static"]) className = t.memberExpression(className, t.identifier("prototype")); | ||
methodName = t.memberExpression(className, methodName, node.computed); | ||
var className = this.className; | ||
if (!node["static"]) className = t.memberExpression(className, t.identifier("prototype")); | ||
methodName = t.memberExpression(className, methodName, node.computed); | ||
var expr = t.expressionStatement(t.assignmentExpression("=", methodName, node.value)); | ||
t.inheritsComments(expr, node); | ||
this.body.push(expr); | ||
return; | ||
var expr = t.expressionStatement(t.assignmentExpression("=", methodName, node.value)); | ||
t.inheritsComments(expr, node); | ||
this.body.push(expr); | ||
return; | ||
} | ||
kind = "value"; | ||
} | ||
kind = "value"; | ||
} | ||
var mutatorMap = this.instanceMutatorMap; | ||
if (node["static"]) { | ||
this.hasStaticMutators = true; | ||
mutatorMap = this.staticMutatorMap; | ||
} else { | ||
this.hasInstanceMutators = true; | ||
} | ||
var mutatorMap = this.instanceMutatorMap; | ||
if (node["static"]) { | ||
this.hasStaticMutators = true; | ||
mutatorMap = this.staticMutatorMap; | ||
} else { | ||
this.hasInstanceMutators = true; | ||
} | ||
defineMap.push(mutatorMap, methodName, kind, node.computed, node); | ||
defineMap.push(mutatorMap, methodName, "enumerable", node.computed, false); | ||
}; | ||
defineMap.push(mutatorMap, methodName, kind, node.computed, node); | ||
defineMap.push(mutatorMap, methodName, "enumerable", node.computed, false); | ||
}; | ||
/** | ||
* Description | ||
* | ||
* @param {Node} node | ||
*/ | ||
/** | ||
* Description | ||
* | ||
* @param {Node} node | ||
*/ | ||
ClassTransformer.prototype.pushProperty = function pushProperty(node) { | ||
if (!node.value) return; | ||
ClassTransformer.prototype.pushProperty = function (node) { | ||
if (!node.value) return; | ||
var key; | ||
var key; | ||
if (node["static"]) { | ||
key = t.memberExpression(this.className, node.key); | ||
this.body.push(t.expressionStatement(t.assignmentExpression("=", key, node.value))); | ||
} else { | ||
key = t.memberExpression(t.thisExpression(), node.key); | ||
this.constructor.body.body.unshift(t.expressionStatement(t.assignmentExpression("=", key, node.value))); | ||
} | ||
}; | ||
if (node["static"]) { | ||
key = t.memberExpression(this.className, node.key); | ||
this.body.push(t.expressionStatement(t.assignmentExpression("=", key, node.value))); | ||
} else { | ||
key = t.memberExpression(t.thisExpression(), node.key); | ||
this.constructor.body.body.unshift(t.expressionStatement(t.assignmentExpression("=", key, node.value))); | ||
} | ||
}; | ||
/** | ||
* Replace the constructor body of our class. | ||
* | ||
* @param {Node} method MethodDefinition | ||
*/ | ||
/** | ||
* Replace the constructor body of our class. | ||
* | ||
* @param {Node} method MethodDefinition | ||
*/ | ||
ClassTransformer.prototype.pushConstructor = function pushConstructor(method) { | ||
if (method.kind) { | ||
throw this.file.errorWithNode(method, messages.get("classesIllegalConstructorKind")); | ||
} | ||
ClassTransformer.prototype.pushConstructor = function (method) { | ||
if (method.kind) { | ||
throw this.file.errorWithNode(method, messages.get("classesIllegalConstructorKind")); | ||
} | ||
var construct = this.constructor; | ||
var fn = method.value; | ||
var construct = this.constructor; | ||
var fn = method.value; | ||
this.hasConstructor = true; | ||
this.hasConstructor = true; | ||
t.inherits(construct, fn); | ||
t.inheritsComments(construct, method); | ||
t.inherits(construct, fn); | ||
t.inheritsComments(construct, method); | ||
construct._ignoreUserWhitespace = true; | ||
construct.params = fn.params; | ||
construct.body.body = construct.body.body.concat(fn.body.body); | ||
}; | ||
construct._ignoreUserWhitespace = true; | ||
construct.params = fn.params; | ||
construct.body.body = construct.body.body.concat(fn.body.body); | ||
}; | ||
return ClassTransformer; | ||
})(); |
"use strict"; | ||
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; | ||
var messages = require("../../../messages"); | ||
@@ -8,248 +10,2 @@ var t = require("../../../types"); | ||
function DestructuringTransformer(opts) { | ||
this.blockHoist = opts.blockHoist; | ||
this.operator = opts.operator; | ||
this.nodes = opts.nodes; | ||
this.scope = opts.scope; | ||
this.file = opts.file; | ||
this.kind = opts.kind; | ||
} | ||
DestructuringTransformer.prototype.buildVariableAssignment = function (id, init) { | ||
var op = this.operator; | ||
if (t.isMemberExpression(id)) op = "="; | ||
var node; | ||
if (op) { | ||
node = t.expressionStatement(t.assignmentExpression(op, id, init)); | ||
} else { | ||
node = t.variableDeclaration(this.kind, [t.variableDeclarator(id, init)]); | ||
} | ||
node._blockHoist = this.blockHoist; | ||
return node; | ||
}; | ||
DestructuringTransformer.prototype.buildVariableDeclaration = function (id, init) { | ||
var declar = t.variableDeclaration("var", [t.variableDeclarator(id, init)]); | ||
declar._blockHoist = this.blockHoist; | ||
return declar; | ||
}; | ||
DestructuringTransformer.prototype.push = function (id, init) { | ||
if (t.isObjectPattern(id)) { | ||
this.pushObjectPattern(id, init); | ||
} else if (t.isArrayPattern(id)) { | ||
this.pushArrayPattern(id, init); | ||
} else if (t.isAssignmentPattern(id)) { | ||
this.pushAssignmentPattern(id, init); | ||
} else { | ||
this.nodes.push(this.buildVariableAssignment(id, init)); | ||
} | ||
}; | ||
DestructuringTransformer.prototype.get = function () {}; | ||
DestructuringTransformer.prototype.pushAssignmentPattern = function (pattern, valueRef) { | ||
// we need to assign the current value of the assignment to avoid evaluating | ||
// it more than once | ||
var tempValueRef = this.scope.generateUidBasedOnNode(valueRef); | ||
var declar = t.variableDeclaration("var", [t.variableDeclarator(tempValueRef, valueRef)]); | ||
declar._blockHoist = this.blockHoist; | ||
this.nodes.push(declar); | ||
// | ||
this.nodes.push(this.buildVariableAssignment(pattern.left, t.conditionalExpression(t.binaryExpression("===", tempValueRef, t.identifier("undefined")), pattern.right, tempValueRef))); | ||
}; | ||
DestructuringTransformer.prototype.pushObjectSpread = function (pattern, objRef, spreadProp, spreadPropIndex) { | ||
// get all the keys that appear in this object before the current spread | ||
var keys = []; | ||
for (var i = 0; i < pattern.properties.length; i++) { | ||
var prop = pattern.properties[i]; | ||
// we've exceeded the index of the spread property to all properties to the | ||
// right need to be ignored | ||
if (i >= spreadPropIndex) break; | ||
// ignore other spread properties | ||
if (t.isSpreadProperty(prop)) continue; | ||
var key = prop.key; | ||
if (t.isIdentifier(key)) key = t.literal(prop.key.name); | ||
keys.push(key); | ||
} | ||
keys = t.arrayExpression(keys); | ||
// | ||
var value = t.callExpression(this.file.addHelper("object-without-properties"), [objRef, keys]); | ||
this.nodes.push(this.buildVariableAssignment(spreadProp.argument, value)); | ||
}; | ||
DestructuringTransformer.prototype.pushObjectProperty = function (prop, propRef) { | ||
if (t.isLiteral(prop.key)) prop.computed = true; | ||
var pattern = prop.value; | ||
var objRef = t.memberExpression(propRef, prop.key, prop.computed); | ||
if (t.isPattern(pattern)) { | ||
this.push(pattern, objRef); | ||
} else { | ||
this.nodes.push(this.buildVariableAssignment(pattern, objRef)); | ||
} | ||
}; | ||
DestructuringTransformer.prototype.pushObjectPattern = function (pattern, objRef) { | ||
// https://github.com/babel/babel/issues/681 | ||
if (!pattern.properties.length) { | ||
this.nodes.push(t.expressionStatement(t.callExpression(this.file.addHelper("object-destructuring-empty"), [objRef]))); | ||
} | ||
// if we have more than one properties in this pattern and the objectRef is a | ||
// member expression then we need to assign it to a temporary variable so it's | ||
// only evaluated once | ||
if (pattern.properties.length > 1 && t.isMemberExpression(objRef)) { | ||
var temp = this.scope.generateUidBasedOnNode(objRef, this.file); | ||
this.nodes.push(this.buildVariableDeclaration(temp, objRef)); | ||
objRef = temp; | ||
} | ||
// | ||
for (var i = 0; i < pattern.properties.length; i++) { | ||
var prop = pattern.properties[i]; | ||
if (t.isSpreadProperty(prop)) { | ||
this.pushObjectSpread(pattern, objRef, prop, i); | ||
} else { | ||
this.pushObjectProperty(prop, objRef); | ||
} | ||
} | ||
}; | ||
var hasRest = function hasRest(pattern) { | ||
for (var i = 0; i < pattern.elements.length; i++) { | ||
if (t.isRestElement(pattern.elements[i])) { | ||
return true; | ||
} | ||
} | ||
return false; | ||
}; | ||
DestructuringTransformer.prototype.canUnpackArrayPattern = function (pattern, arr) { | ||
// not an array so there's no way we can deal with this | ||
if (!t.isArrayExpression(arr)) return false; | ||
// pattern has less elements than the array and doesn't have a rest so some | ||
// elements wont be evaluated | ||
if (pattern.elements.length > arr.elements.length) return; | ||
if (pattern.elements.length < arr.elements.length && !hasRest(pattern)) return false; | ||
// deopt on holes | ||
for (var i = 0; i < pattern.elements.length; i++) { | ||
if (!pattern.elements[i]) return false; | ||
} | ||
return true; | ||
}; | ||
DestructuringTransformer.prototype.pushUnpackedArrayPattern = function (pattern, arr) { | ||
for (var i = 0; i < pattern.elements.length; i++) { | ||
var elem = pattern.elements[i]; | ||
if (t.isRestElement(elem)) { | ||
this.push(elem.argument, t.arrayExpression(arr.elements.slice(i))); | ||
} else { | ||
this.push(elem, arr.elements[i]); | ||
} | ||
} | ||
}; | ||
DestructuringTransformer.prototype.pushArrayPattern = function (pattern, arrayRef) { | ||
if (!pattern.elements) return; | ||
// optimise basic array destructuring of an array expression | ||
// | ||
// we can't do this to a pattern of unequal size to it's right hand | ||
// array expression as then there will be values that wont be evaluated | ||
// | ||
// eg: var [a, b] = [1, 2]; | ||
if (this.canUnpackArrayPattern(pattern, arrayRef)) { | ||
return this.pushUnpackedArrayPattern(pattern, arrayRef); | ||
} | ||
// if we have a rest then we need all the elements so don't tell | ||
// `scope.toArray` to only get a certain amount | ||
var count = !hasRest(pattern) && pattern.elements.length; | ||
// so we need to ensure that the `arrayRef` is an array, `scope.toArray` will | ||
// return a locally bound identifier if it's been inferred to be an array, | ||
// otherwise it'll be a call to a helper that will ensure it's one | ||
var toArray = this.scope.toArray(arrayRef, count); | ||
if (t.isIdentifier(toArray)) { | ||
// we've been given an identifier so it must have been inferred to be an | ||
// array | ||
arrayRef = toArray; | ||
} else { | ||
arrayRef = this.scope.generateUidBasedOnNode(arrayRef); | ||
this.nodes.push(this.buildVariableDeclaration(arrayRef, toArray)); | ||
this.scope.assignTypeGeneric(arrayRef.name, "Array"); | ||
} | ||
// | ||
for (var i = 0; i < pattern.elements.length; i++) { | ||
var elem = pattern.elements[i]; | ||
// hole | ||
if (!elem) continue; | ||
var elemRef; | ||
if (t.isRestElement(elem)) { | ||
elemRef = this.scope.toArray(arrayRef); | ||
if (i > 0) { | ||
elemRef = t.callExpression(t.memberExpression(elemRef, t.identifier("slice")), [t.literal(i)]); | ||
} | ||
// set the element to the rest element argument since we've dealt with it | ||
// being a rest already | ||
elem = elem.argument; | ||
} else { | ||
elemRef = t.memberExpression(arrayRef, t.literal(i), true); | ||
} | ||
this.push(elem, elemRef); | ||
} | ||
}; | ||
DestructuringTransformer.prototype.init = function (pattern, ref) { | ||
// trying to destructure a value that we can't evaluate more than once so we | ||
// need to save it to a variable | ||
if (!t.isArrayExpression(ref) && !t.isMemberExpression(ref) && !t.isIdentifier(ref)) { | ||
var key = this.scope.generateUidBasedOnNode(ref); | ||
this.nodes.push(this.buildVariableDeclaration(key, ref)); | ||
ref = key; | ||
} | ||
// | ||
this.push(pattern, ref); | ||
}; | ||
exports.ForInStatement = exports.ForOfStatement = function (node, parent, scope, file) { | ||
@@ -446,3 +202,3 @@ var left = node.left; | ||
node = nodes[i]; | ||
declar = declar || t.variableDeclaration(node.kind, []); | ||
if (!declar) declar = t.variableDeclaration(node.kind, []); | ||
@@ -460,2 +216,252 @@ if (!t.isVariableDeclaration(node) && declar.kind !== node.kind) { | ||
return nodes; | ||
}; | ||
}; | ||
var hasRest = function hasRest(pattern) { | ||
for (var i = 0; i < pattern.elements.length; i++) { | ||
if (t.isRestElement(pattern.elements[i])) { | ||
return true; | ||
} | ||
} | ||
return false; | ||
}; | ||
var DestructuringTransformer = (function () { | ||
function DestructuringTransformer(opts) { | ||
_classCallCheck(this, DestructuringTransformer); | ||
this.blockHoist = opts.blockHoist; | ||
this.operator = opts.operator; | ||
this.nodes = opts.nodes; | ||
this.scope = opts.scope; | ||
this.file = opts.file; | ||
this.kind = opts.kind; | ||
} | ||
DestructuringTransformer.prototype.buildVariableAssignment = function buildVariableAssignment(id, init) { | ||
var op = this.operator; | ||
if (t.isMemberExpression(id)) op = "="; | ||
var node; | ||
if (op) { | ||
node = t.expressionStatement(t.assignmentExpression(op, id, init)); | ||
} else { | ||
node = t.variableDeclaration(this.kind, [t.variableDeclarator(id, init)]); | ||
} | ||
node._blockHoist = this.blockHoist; | ||
return node; | ||
}; | ||
DestructuringTransformer.prototype.buildVariableDeclaration = function buildVariableDeclaration(id, init) { | ||
var declar = t.variableDeclaration("var", [t.variableDeclarator(id, init)]); | ||
declar._blockHoist = this.blockHoist; | ||
return declar; | ||
}; | ||
DestructuringTransformer.prototype.push = function push(id, init) { | ||
if (t.isObjectPattern(id)) { | ||
this.pushObjectPattern(id, init); | ||
} else if (t.isArrayPattern(id)) { | ||
this.pushArrayPattern(id, init); | ||
} else if (t.isAssignmentPattern(id)) { | ||
this.pushAssignmentPattern(id, init); | ||
} else { | ||
this.nodes.push(this.buildVariableAssignment(id, init)); | ||
} | ||
}; | ||
DestructuringTransformer.prototype.pushAssignmentPattern = function pushAssignmentPattern(pattern, valueRef) { | ||
// we need to assign the current value of the assignment to avoid evaluating | ||
// it more than once | ||
var tempValueRef = this.scope.generateUidBasedOnNode(valueRef); | ||
var declar = t.variableDeclaration("var", [t.variableDeclarator(tempValueRef, valueRef)]); | ||
declar._blockHoist = this.blockHoist; | ||
this.nodes.push(declar); | ||
// | ||
this.nodes.push(this.buildVariableAssignment(pattern.left, t.conditionalExpression(t.binaryExpression("===", tempValueRef, t.identifier("undefined")), pattern.right, tempValueRef))); | ||
}; | ||
DestructuringTransformer.prototype.pushObjectSpread = function pushObjectSpread(pattern, objRef, spreadProp, spreadPropIndex) { | ||
// get all the keys that appear in this object before the current spread | ||
var keys = []; | ||
for (var i = 0; i < pattern.properties.length; i++) { | ||
var prop = pattern.properties[i]; | ||
// we've exceeded the index of the spread property to all properties to the | ||
// right need to be ignored | ||
if (i >= spreadPropIndex) break; | ||
// ignore other spread properties | ||
if (t.isSpreadProperty(prop)) continue; | ||
var key = prop.key; | ||
if (t.isIdentifier(key)) key = t.literal(prop.key.name); | ||
keys.push(key); | ||
} | ||
keys = t.arrayExpression(keys); | ||
// | ||
var value = t.callExpression(this.file.addHelper("object-without-properties"), [objRef, keys]); | ||
this.nodes.push(this.buildVariableAssignment(spreadProp.argument, value)); | ||
}; | ||
DestructuringTransformer.prototype.pushObjectProperty = function pushObjectProperty(prop, propRef) { | ||
if (t.isLiteral(prop.key)) prop.computed = true; | ||
var pattern = prop.value; | ||
var objRef = t.memberExpression(propRef, prop.key, prop.computed); | ||
if (t.isPattern(pattern)) { | ||
this.push(pattern, objRef); | ||
} else { | ||
this.nodes.push(this.buildVariableAssignment(pattern, objRef)); | ||
} | ||
}; | ||
DestructuringTransformer.prototype.pushObjectPattern = function pushObjectPattern(pattern, objRef) { | ||
// https://github.com/babel/babel/issues/681 | ||
if (!pattern.properties.length) { | ||
this.nodes.push(t.expressionStatement(t.callExpression(this.file.addHelper("object-destructuring-empty"), [objRef]))); | ||
} | ||
// if we have more than one properties in this pattern and the objectRef is a | ||
// member expression then we need to assign it to a temporary variable so it's | ||
// only evaluated once | ||
if (pattern.properties.length > 1 && t.isMemberExpression(objRef)) { | ||
var temp = this.scope.generateUidBasedOnNode(objRef, this.file); | ||
this.nodes.push(this.buildVariableDeclaration(temp, objRef)); | ||
objRef = temp; | ||
} | ||
// | ||
for (var i = 0; i < pattern.properties.length; i++) { | ||
var prop = pattern.properties[i]; | ||
if (t.isSpreadProperty(prop)) { | ||
this.pushObjectSpread(pattern, objRef, prop, i); | ||
} else { | ||
this.pushObjectProperty(prop, objRef); | ||
} | ||
} | ||
}; | ||
DestructuringTransformer.prototype.canUnpackArrayPattern = function canUnpackArrayPattern(pattern, arr) { | ||
// not an array so there's no way we can deal with this | ||
if (!t.isArrayExpression(arr)) return false; | ||
// pattern has less elements than the array and doesn't have a rest so some | ||
// elements wont be evaluated | ||
if (pattern.elements.length > arr.elements.length) return; | ||
if (pattern.elements.length < arr.elements.length && !hasRest(pattern)) return false; | ||
// deopt on holes | ||
for (var i = 0; i < pattern.elements.length; i++) { | ||
if (!pattern.elements[i]) return false; | ||
} | ||
return true; | ||
}; | ||
DestructuringTransformer.prototype.pushUnpackedArrayPattern = function pushUnpackedArrayPattern(pattern, arr) { | ||
for (var i = 0; i < pattern.elements.length; i++) { | ||
var elem = pattern.elements[i]; | ||
if (t.isRestElement(elem)) { | ||
this.push(elem.argument, t.arrayExpression(arr.elements.slice(i))); | ||
} else { | ||
this.push(elem, arr.elements[i]); | ||
} | ||
} | ||
}; | ||
DestructuringTransformer.prototype.pushArrayPattern = function pushArrayPattern(pattern, arrayRef) { | ||
if (!pattern.elements) return; | ||
// optimise basic array destructuring of an array expression | ||
// | ||
// we can't do this to a pattern of unequal size to it's right hand | ||
// array expression as then there will be values that wont be evaluated | ||
// | ||
// eg: var [a, b] = [1, 2]; | ||
if (this.canUnpackArrayPattern(pattern, arrayRef)) { | ||
return this.pushUnpackedArrayPattern(pattern, arrayRef); | ||
} | ||
// if we have a rest then we need all the elements so don't tell | ||
// `scope.toArray` to only get a certain amount | ||
var count = !hasRest(pattern) && pattern.elements.length; | ||
// so we need to ensure that the `arrayRef` is an array, `scope.toArray` will | ||
// return a locally bound identifier if it's been inferred to be an array, | ||
// otherwise it'll be a call to a helper that will ensure it's one | ||
var toArray = this.scope.toArray(arrayRef, count); | ||
if (t.isIdentifier(toArray)) { | ||
// we've been given an identifier so it must have been inferred to be an | ||
// array | ||
arrayRef = toArray; | ||
} else { | ||
arrayRef = this.scope.generateUidBasedOnNode(arrayRef); | ||
this.nodes.push(this.buildVariableDeclaration(arrayRef, toArray)); | ||
this.scope.assignTypeGeneric(arrayRef.name, "Array"); | ||
} | ||
// | ||
for (var i = 0; i < pattern.elements.length; i++) { | ||
var elem = pattern.elements[i]; | ||
// hole | ||
if (!elem) continue; | ||
var elemRef; | ||
if (t.isRestElement(elem)) { | ||
elemRef = this.scope.toArray(arrayRef); | ||
if (i > 0) { | ||
elemRef = t.callExpression(t.memberExpression(elemRef, t.identifier("slice")), [t.literal(i)]); | ||
} | ||
// set the element to the rest element argument since we've dealt with it | ||
// being a rest already | ||
elem = elem.argument; | ||
} else { | ||
elemRef = t.memberExpression(arrayRef, t.literal(i), true); | ||
} | ||
this.push(elem, elemRef); | ||
} | ||
}; | ||
DestructuringTransformer.prototype.init = function init(pattern, ref) { | ||
// trying to destructure a value that we can't evaluate more than once so we | ||
// need to save it to a variable | ||
if (!t.isArrayExpression(ref) && !t.isMemberExpression(ref) && !t.isIdentifier(ref)) { | ||
var key = this.scope.generateUidBasedOnNode(ref); | ||
this.nodes.push(this.buildVariableDeclaration(key, ref)); | ||
ref = key; | ||
} | ||
// | ||
this.push(pattern, ref); | ||
}; | ||
return DestructuringTransformer; | ||
})(); |
"use strict"; | ||
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; | ||
var reduceRight = require("lodash/collection/reduceRight"); | ||
@@ -10,2 +12,7 @@ var messages = require("../../../messages"); | ||
exports.Function = function (node, parent, scope, file) { | ||
var tailCall = new TailCallTransformer(node, scope, file); | ||
tailCall.run(); | ||
}; | ||
function returnBlock(expr) { | ||
@@ -15,344 +22,355 @@ return t.blockStatement([t.returnStatement(expr)]); | ||
function TailCallTransformer(node, scope, file) { | ||
this.hasTailRecursion = false; | ||
this.needsArguments = false; | ||
this.setsArguments = false; | ||
this.needsThis = false; | ||
this.ownerId = node.id; | ||
this.vars = []; | ||
// looks for and replaces tail recursion calls | ||
var firstPass = { | ||
enter: function enter(node, parent, scope, state) { | ||
if (t.isIfStatement(node)) { | ||
if (t.isReturnStatement(node.alternate)) { | ||
t.ensureBlock(node, "alternate"); | ||
} | ||
this.scope = scope; | ||
this.file = file; | ||
this.node = node; | ||
} | ||
TailCallTransformer.prototype.getArgumentsId = function () { | ||
return this.argumentsId = this.argumentsId || this.scope.generateUidIdentifier("arguments"); | ||
if (t.isReturnStatement(node.consequent)) { | ||
t.ensureBlock(node, "consequent"); | ||
} | ||
} else if (t.isReturnStatement(node)) { | ||
this.skip(); | ||
return state.subTransform(node.argument); | ||
} else if (t.isTryStatement(parent)) { | ||
if (node === parent.block) { | ||
this.skip(); | ||
} else if (parent.finalizer && node !== parent.finalizer) { | ||
this.skip(); | ||
} | ||
} else if (t.isFunction(node)) { | ||
this.skip(); | ||
} else if (t.isVariableDeclaration(node)) { | ||
this.skip(); | ||
state.vars.push(node); | ||
} | ||
} | ||
}; | ||
TailCallTransformer.prototype.getThisId = function () { | ||
return this.thisId = this.thisId || this.scope.generateUidIdentifier("this"); | ||
// hoists up function declarations, replaces `this` and `arguments` and marks | ||
// them as needed | ||
var secondPass = { | ||
enter: function enter(node, parent, scope, state) { | ||
if (t.isThisExpression(node)) { | ||
state.needsThis = true; | ||
return state.getThisId(); | ||
} else if (t.isReferencedIdentifier(node, parent, { name: "arguments" })) { | ||
state.needsArguments = true; | ||
return state.getArgumentsId(); | ||
} else if (t.isFunction(node)) { | ||
this.skip(); | ||
if (t.isFunctionDeclaration(node)) { | ||
node = t.variableDeclaration("var", [t.variableDeclarator(node.id, t.toExpression(node))]); | ||
node._blockHoist = 2; | ||
return node; | ||
} | ||
} | ||
} | ||
}; | ||
TailCallTransformer.prototype.getLeftId = function () { | ||
return this.leftId = this.leftId || this.scope.generateUidIdentifier("left"); | ||
}; | ||
// optimizes recursion by removing `this` and `arguments` if they aren't used | ||
var thirdPass = { | ||
enter: function enter(node, parent, scope, state) { | ||
if (!t.isExpressionStatement(node)) return; | ||
TailCallTransformer.prototype.getFunctionId = function () { | ||
return this.functionId = this.functionId || this.scope.generateUidIdentifier("function"); | ||
}; | ||
var expr = node.expression; | ||
if (!t.isAssignmentExpression(expr)) return; | ||
TailCallTransformer.prototype.getAgainId = function () { | ||
return this.againId = this.againId || this.scope.generateUidIdentifier("again"); | ||
if (!state.needsThis && expr.left === state.getThisId()) { | ||
this.remove(); | ||
} else if (!state.needsArguments && expr.left === state.getArgumentsId() && t.isArrayExpression(expr.right)) { | ||
return map(expr.right.elements, function (elem) { | ||
return t.expressionStatement(elem); | ||
}); | ||
} | ||
} | ||
}; | ||
TailCallTransformer.prototype.getParams = function () { | ||
var params = this.params; | ||
var TailCallTransformer = (function () { | ||
function TailCallTransformer(node, scope, file) { | ||
_classCallCheck(this, TailCallTransformer); | ||
if (!params) { | ||
params = this.node.params; | ||
this.paramDecls = []; | ||
this.hasTailRecursion = false; | ||
this.needsArguments = false; | ||
this.setsArguments = false; | ||
this.needsThis = false; | ||
this.ownerId = node.id; | ||
this.vars = []; | ||
for (var i = 0; i < params.length; i++) { | ||
var param = params[i]; | ||
if (!param._isDefaultPlaceholder) { | ||
this.paramDecls.push(t.variableDeclarator(param, params[i] = this.scope.generateUidIdentifier("x"))); | ||
} | ||
} | ||
this.scope = scope; | ||
this.file = file; | ||
this.node = node; | ||
} | ||
return this.params = params; | ||
}; | ||
TailCallTransformer.prototype.getArgumentsId = function getArgumentsId() { | ||
var _ref; | ||
TailCallTransformer.prototype.hasDeopt = function () { | ||
// check if the ownerId has been reassigned, if it has then it's not safe to | ||
// perform optimisations | ||
var ownerIdInfo = this.scope.getBindingInfo(this.ownerId.name); | ||
return ownerIdInfo && ownerIdInfo.reassigned; | ||
}; | ||
return (_ref = this, !_ref.argumentsId && (_ref.argumentsId = this.scope.generateUidIdentifier("arguments")), _ref.argumentsId); | ||
}; | ||
TailCallTransformer.prototype.run = function () { | ||
var scope = this.scope; | ||
var node = this.node; | ||
TailCallTransformer.prototype.getThisId = function getThisId() { | ||
var _ref; | ||
// only tail recursion can be optimized as for now, so we can skip anonymous | ||
// functions entirely | ||
var ownerId = this.ownerId; | ||
if (!ownerId) return; | ||
return (_ref = this, !_ref.thisId && (_ref.thisId = this.scope.generateUidIdentifier("this")), _ref.thisId); | ||
}; | ||
// traverse the function and look for tail recursion | ||
scope.traverse(node, firstPass, this); | ||
TailCallTransformer.prototype.getLeftId = function getLeftId() { | ||
var _ref; | ||
if (!this.hasTailRecursion) return; | ||
return (_ref = this, !_ref.leftId && (_ref.leftId = this.scope.generateUidIdentifier("left")), _ref.leftId); | ||
}; | ||
if (this.hasDeopt()) { | ||
this.file.logDeopt(node, messages.get("tailCallReassignmentDeopt")); | ||
return; | ||
} | ||
TailCallTransformer.prototype.getFunctionId = function getFunctionId() { | ||
var _ref; | ||
// | ||
return (_ref = this, !_ref.functionId && (_ref.functionId = this.scope.generateUidIdentifier("function")), _ref.functionId); | ||
}; | ||
scope.traverse(node, secondPass, this); | ||
TailCallTransformer.prototype.getAgainId = function getAgainId() { | ||
var _ref; | ||
if (!this.needsThis || !this.needsArguments) { | ||
scope.traverse(node, thirdPass, this); | ||
} | ||
return (_ref = this, !_ref.againId && (_ref.againId = this.scope.generateUidIdentifier("again")), _ref.againId); | ||
}; | ||
var body = t.ensureBlock(node).body; | ||
TailCallTransformer.prototype.getParams = function getParams() { | ||
var params = this.params; | ||
if (this.vars.length > 0) { | ||
var declarations = flatten(map(this.vars, function (decl) { | ||
return decl.declarations; | ||
}, this)); | ||
var statement = reduceRight(declarations, function (expr, decl) { | ||
return t.assignmentExpression("=", decl.id, expr); | ||
}, t.identifier("undefined")); | ||
body.unshift(t.expressionStatement(statement)); | ||
} | ||
if (!params) { | ||
params = this.node.params; | ||
this.paramDecls = []; | ||
var paramDecls = this.paramDecls; | ||
if (paramDecls.length > 0) { | ||
body.unshift(t.variableDeclaration("var", paramDecls)); | ||
} | ||
for (var i = 0; i < params.length; i++) { | ||
var param = params[i]; | ||
if (!param._isDefaultPlaceholder) { | ||
this.paramDecls.push(t.variableDeclarator(param, params[i] = this.scope.generateUidIdentifier("x"))); | ||
} | ||
} | ||
} | ||
body.unshift(t.expressionStatement(t.assignmentExpression("=", this.getAgainId(), t.literal(false)))); | ||
return this.params = params; | ||
}; | ||
node.body = util.template("tail-call-body", { | ||
AGAIN_ID: this.getAgainId(), | ||
THIS_ID: this.thisId, | ||
ARGUMENTS_ID: this.argumentsId, | ||
FUNCTION_ID: this.getFunctionId(), | ||
BLOCK: node.body | ||
}); | ||
TailCallTransformer.prototype.hasDeopt = function hasDeopt() { | ||
// check if the ownerId has been reassigned, if it has then it's not safe to | ||
// perform optimisations | ||
var ownerIdInfo = this.scope.getBindingInfo(this.ownerId.name); | ||
return ownerIdInfo && ownerIdInfo.reassigned; | ||
}; | ||
var topVars = []; | ||
TailCallTransformer.prototype.run = function run() { | ||
var scope = this.scope; | ||
var node = this.node; | ||
if (this.needsThis) { | ||
topVars.push(t.variableDeclarator(this.getThisId(), t.thisExpression())); | ||
} | ||
// only tail recursion can be optimized as for now, so we can skip anonymous | ||
// functions entirely | ||
var ownerId = this.ownerId; | ||
if (!ownerId) return; | ||
if (this.needsArguments || this.setsArguments) { | ||
var decl = t.variableDeclarator(this.getArgumentsId()); | ||
if (this.needsArguments) { | ||
decl.init = t.identifier("arguments"); | ||
} | ||
topVars.push(decl); | ||
} | ||
// traverse the function and look for tail recursion | ||
scope.traverse(node, firstPass, this); | ||
var leftId = this.leftId; | ||
if (leftId) { | ||
topVars.push(t.variableDeclarator(leftId)); | ||
} | ||
if (!this.hasTailRecursion) return; | ||
if (topVars.length > 0) { | ||
node.body.body.unshift(t.variableDeclaration("var", topVars)); | ||
} | ||
}; | ||
if (this.hasDeopt()) { | ||
this.file.logDeopt(node, messages.get("tailCallReassignmentDeopt")); | ||
return; | ||
} | ||
TailCallTransformer.prototype.subTransform = function (node) { | ||
if (!node) return; | ||
// | ||
var handler = this["subTransform" + node.type]; | ||
if (handler) return handler.call(this, node); | ||
}; | ||
scope.traverse(node, secondPass, this); | ||
TailCallTransformer.prototype.subTransformConditionalExpression = function (node) { | ||
var callConsequent = this.subTransform(node.consequent); | ||
var callAlternate = this.subTransform(node.alternate); | ||
if (!callConsequent && !callAlternate) { | ||
return; | ||
} | ||
if (!this.needsThis || !this.needsArguments) { | ||
scope.traverse(node, thirdPass, this); | ||
} | ||
// if ternary operator had tail recursion in value, convert to optimized if-statement | ||
node.type = "IfStatement"; | ||
node.consequent = callConsequent ? t.toBlock(callConsequent) : returnBlock(node.consequent); | ||
var body = t.ensureBlock(node).body; | ||
if (callAlternate) { | ||
node.alternate = t.isIfStatement(callAlternate) ? callAlternate : t.toBlock(callAlternate); | ||
} else { | ||
node.alternate = returnBlock(node.alternate); | ||
} | ||
if (this.vars.length > 0) { | ||
var declarations = flatten(map(this.vars, function (decl) { | ||
return decl.declarations; | ||
}, this)); | ||
var statement = reduceRight(declarations, function (expr, decl) { | ||
return t.assignmentExpression("=", decl.id, expr); | ||
}, t.identifier("undefined")); | ||
body.unshift(t.expressionStatement(statement)); | ||
} | ||
return [node]; | ||
}; | ||
var paramDecls = this.paramDecls; | ||
if (paramDecls.length > 0) { | ||
body.unshift(t.variableDeclaration("var", paramDecls)); | ||
} | ||
TailCallTransformer.prototype.subTransformLogicalExpression = function (node) { | ||
// only call in right-value of can be optimized | ||
var callRight = this.subTransform(node.right); | ||
if (!callRight) return; | ||
body.unshift(t.expressionStatement(t.assignmentExpression("=", this.getAgainId(), t.literal(false)))); | ||
// cache left value as it might have side-effects | ||
var leftId = this.getLeftId(); | ||
var testExpr = t.assignmentExpression("=", leftId, node.left); | ||
node.body = util.template("tail-call-body", { | ||
AGAIN_ID: this.getAgainId(), | ||
THIS_ID: this.thisId, | ||
ARGUMENTS_ID: this.argumentsId, | ||
FUNCTION_ID: this.getFunctionId(), | ||
BLOCK: node.body | ||
}); | ||
if (node.operator === "&&") { | ||
testExpr = t.unaryExpression("!", testExpr); | ||
} | ||
var topVars = []; | ||
return [t.ifStatement(testExpr, returnBlock(leftId))].concat(callRight); | ||
}; | ||
if (this.needsThis) { | ||
topVars.push(t.variableDeclarator(this.getThisId(), t.thisExpression())); | ||
} | ||
TailCallTransformer.prototype.subTransformSequenceExpression = function (node) { | ||
var seq = node.expressions; | ||
if (this.needsArguments || this.setsArguments) { | ||
var decl = t.variableDeclarator(this.getArgumentsId()); | ||
if (this.needsArguments) { | ||
decl.init = t.identifier("arguments"); | ||
} | ||
topVars.push(decl); | ||
} | ||
// only last element can be optimized | ||
var lastCall = this.subTransform(seq[seq.length - 1]); | ||
if (!lastCall) { | ||
return; | ||
} | ||
var leftId = this.leftId; | ||
if (leftId) { | ||
topVars.push(t.variableDeclarator(leftId)); | ||
} | ||
// remove converted expression from sequence | ||
// and convert to regular expression if needed | ||
if (--seq.length === 1) { | ||
node = seq[0]; | ||
} | ||
if (topVars.length > 0) { | ||
node.body.body.unshift(t.variableDeclaration("var", topVars)); | ||
} | ||
}; | ||
return [t.expressionStatement(node)].concat(lastCall); | ||
}; | ||
TailCallTransformer.prototype.subTransform = function subTransform(node) { | ||
if (!node) return; | ||
TailCallTransformer.prototype.subTransformCallExpression = function (node) { | ||
var callee = node.callee, | ||
thisBinding, | ||
args; | ||
var handler = this["subTransform" + node.type]; | ||
if (handler) return handler.call(this, node); | ||
}; | ||
if (t.isMemberExpression(callee, { computed: false }) && t.isIdentifier(callee.property)) { | ||
switch (callee.property.name) { | ||
case "call": | ||
args = t.arrayExpression(node.arguments.slice(1)); | ||
break; | ||
TailCallTransformer.prototype.subTransformConditionalExpression = function subTransformConditionalExpression(node) { | ||
var callConsequent = this.subTransform(node.consequent); | ||
var callAlternate = this.subTransform(node.alternate); | ||
if (!callConsequent && !callAlternate) { | ||
return; | ||
} | ||
case "apply": | ||
args = node.arguments[1] || t.identifier("undefined"); | ||
break; | ||
// if ternary operator had tail recursion in value, convert to optimized if-statement | ||
node.type = "IfStatement"; | ||
node.consequent = callConsequent ? t.toBlock(callConsequent) : returnBlock(node.consequent); | ||
default: | ||
return; | ||
if (callAlternate) { | ||
node.alternate = t.isIfStatement(callAlternate) ? callAlternate : t.toBlock(callAlternate); | ||
} else { | ||
node.alternate = returnBlock(node.alternate); | ||
} | ||
thisBinding = node.arguments[0]; | ||
callee = callee.object; | ||
} | ||
return [node]; | ||
}; | ||
// only tail recursion can be optimized as for now | ||
if (!t.isIdentifier(callee) || !this.scope.bindingIdentifierEquals(callee.name, this.ownerId)) { | ||
return; | ||
} | ||
TailCallTransformer.prototype.subTransformLogicalExpression = function subTransformLogicalExpression(node) { | ||
// only call in right-value of can be optimized | ||
var callRight = this.subTransform(node.right); | ||
if (!callRight) return; | ||
this.hasTailRecursion = true; | ||
// cache left value as it might have side-effects | ||
var leftId = this.getLeftId(); | ||
var testExpr = t.assignmentExpression("=", leftId, node.left); | ||
if (this.hasDeopt()) return; | ||
if (node.operator === "&&") { | ||
testExpr = t.unaryExpression("!", testExpr); | ||
} | ||
var body = []; | ||
return [t.ifStatement(testExpr, returnBlock(leftId))].concat(callRight); | ||
}; | ||
if (!t.isThisExpression(thisBinding)) { | ||
body.push(t.expressionStatement(t.assignmentExpression("=", this.getThisId(), thisBinding || t.identifier("undefined")))); | ||
} | ||
TailCallTransformer.prototype.subTransformSequenceExpression = function subTransformSequenceExpression(node) { | ||
var seq = node.expressions; | ||
if (!args) { | ||
args = t.arrayExpression(node.arguments); | ||
} | ||
// only last element can be optimized | ||
var lastCall = this.subTransform(seq[seq.length - 1]); | ||
if (!lastCall) { | ||
return; | ||
} | ||
var argumentsId = this.getArgumentsId(); | ||
var params = this.getParams(); | ||
// remove converted expression from sequence | ||
// and convert to regular expression if needed | ||
if (--seq.length === 1) { | ||
node = seq[0]; | ||
} | ||
body.push(t.expressionStatement(t.assignmentExpression("=", argumentsId, args))); | ||
return [t.expressionStatement(node)].concat(lastCall); | ||
}; | ||
var i, param; | ||
TailCallTransformer.prototype.subTransformCallExpression = function subTransformCallExpression(node) { | ||
var callee = node.callee, | ||
thisBinding, | ||
args; | ||
if (t.isArrayExpression(args)) { | ||
var elems = args.elements; | ||
for (i = 0; i < elems.length && i < params.length; i++) { | ||
param = params[i]; | ||
var elem = elems[i] || (elems[i] = t.identifier("undefined")); | ||
if (!param._isDefaultPlaceholder) { | ||
elems[i] = t.assignmentExpression("=", param, elem); | ||
if (t.isMemberExpression(callee, { computed: false }) && t.isIdentifier(callee.property)) { | ||
switch (callee.property.name) { | ||
case "call": | ||
args = t.arrayExpression(node.arguments.slice(1)); | ||
break; | ||
case "apply": | ||
args = node.arguments[1] || t.identifier("undefined"); | ||
break; | ||
default: | ||
return; | ||
} | ||
thisBinding = node.arguments[0]; | ||
callee = callee.object; | ||
} | ||
} else { | ||
this.setsArguments = true; | ||
for (i = 0; i < params.length; i++) { | ||
param = params[i]; | ||
if (!param._isDefaultPlaceholder) { | ||
body.push(t.expressionStatement(t.assignmentExpression("=", param, t.memberExpression(argumentsId, t.literal(i), true)))); | ||
} | ||
// only tail recursion can be optimized as for now | ||
if (!t.isIdentifier(callee) || !this.scope.bindingIdentifierEquals(callee.name, this.ownerId)) { | ||
return; | ||
} | ||
} | ||
body.push(t.expressionStatement(t.assignmentExpression("=", this.getAgainId(), t.literal(true)))); | ||
body.push(t.continueStatement(this.getFunctionId())); | ||
this.hasTailRecursion = true; | ||
return body; | ||
}; | ||
if (this.hasDeopt()) return; | ||
// looks for and replaces tail recursion calls | ||
var firstPass = { | ||
enter: function enter(node, parent, scope, state) { | ||
if (t.isIfStatement(node)) { | ||
if (t.isReturnStatement(node.alternate)) { | ||
t.ensureBlock(node, "alternate"); | ||
} | ||
var body = []; | ||
if (t.isReturnStatement(node.consequent)) { | ||
t.ensureBlock(node, "consequent"); | ||
} | ||
} else if (t.isReturnStatement(node)) { | ||
this.skip(); | ||
return state.subTransform(node.argument); | ||
} else if (t.isTryStatement(parent)) { | ||
if (node === parent.block) { | ||
this.skip(); | ||
} else if (parent.finalizer && node !== parent.finalizer) { | ||
this.skip(); | ||
} | ||
} else if (t.isFunction(node)) { | ||
this.skip(); | ||
} else if (t.isVariableDeclaration(node)) { | ||
this.skip(); | ||
state.vars.push(node); | ||
if (!t.isThisExpression(thisBinding)) { | ||
body.push(t.expressionStatement(t.assignmentExpression("=", this.getThisId(), thisBinding || t.identifier("undefined")))); | ||
} | ||
} | ||
}; | ||
// hoists up function declarations, replaces `this` and `arguments` and marks | ||
// them as needed | ||
var secondPass = { | ||
enter: function enter(node, parent, scope, state) { | ||
if (t.isThisExpression(node)) { | ||
state.needsThis = true; | ||
return state.getThisId(); | ||
} else if (t.isReferencedIdentifier(node, parent, { name: "arguments" })) { | ||
state.needsArguments = true; | ||
return state.getArgumentsId(); | ||
} else if (t.isFunction(node)) { | ||
this.skip(); | ||
if (t.isFunctionDeclaration(node)) { | ||
node = t.variableDeclaration("var", [t.variableDeclarator(node.id, t.toExpression(node))]); | ||
node._blockHoist = 2; | ||
return node; | ||
} | ||
if (!args) { | ||
args = t.arrayExpression(node.arguments); | ||
} | ||
} | ||
}; | ||
// optimizes recursion by removing `this` and `arguments` if they aren't used | ||
var thirdPass = { | ||
enter: function enter(node, parent, scope, state) { | ||
if (!t.isExpressionStatement(node)) return; | ||
var argumentsId = this.getArgumentsId(); | ||
var params = this.getParams(); | ||
var expr = node.expression; | ||
if (!t.isAssignmentExpression(expr)) return; | ||
body.push(t.expressionStatement(t.assignmentExpression("=", argumentsId, args))); | ||
if (!state.needsThis && expr.left === state.getThisId()) { | ||
this.remove(); | ||
} else if (!state.needsArguments && expr.left === state.getArgumentsId() && t.isArrayExpression(expr.right)) { | ||
return map(expr.right.elements, function (elem) { | ||
return t.expressionStatement(elem); | ||
}); | ||
var i, param; | ||
if (t.isArrayExpression(args)) { | ||
var elems = args.elements; | ||
for (i = 0; i < elems.length && i < params.length; i++) { | ||
param = params[i]; | ||
var elem = elems[i] || (elems[i] = t.identifier("undefined")); | ||
if (!param._isDefaultPlaceholder) { | ||
elems[i] = t.assignmentExpression("=", param, elem); | ||
} | ||
} | ||
} else { | ||
this.setsArguments = true; | ||
for (i = 0; i < params.length; i++) { | ||
param = params[i]; | ||
if (!param._isDefaultPlaceholder) { | ||
body.push(t.expressionStatement(t.assignmentExpression("=", param, t.memberExpression(argumentsId, t.literal(i), true)))); | ||
} | ||
} | ||
} | ||
} | ||
}; | ||
exports.Function = function (node, parent, scope, file) { | ||
var tailCall = new TailCallTransformer(node, scope, file); | ||
tailCall.run(); | ||
}; | ||
body.push(t.expressionStatement(t.assignmentExpression("=", this.getAgainId(), t.literal(true)))); | ||
body.push(t.continueStatement(this.getFunctionId())); | ||
return body; | ||
}; | ||
return TailCallTransformer; | ||
})(); |
@@ -6,5 +6,2 @@ "use strict"; | ||
// this goes at the start so we only transform the original user code | ||
"spec.functionName": require("./spec/function-name"), | ||
"validation.undeclaredVariableCheck": require("./validation/undeclared-variable-check"), | ||
@@ -14,2 +11,6 @@ "validation.noForInOfAssignment": require("./validation/no-for-in-of-assignment"), | ||
"validation.react": require("./validation/react"), | ||
// this goes at the start so we only transform the original user code | ||
"spec.functionName": require("./spec/function-name"), | ||
"spec.blockScopedFunctions": require("./spec/block-scoped-functions"), | ||
@@ -16,0 +17,0 @@ |
@@ -51,6 +51,7 @@ "use strict"; | ||
getArgumentsId: function getArgumentsId() { | ||
return argumentsId = argumentsId || scope.generateUidIdentifier("arguments"); | ||
return (!argumentsId && (argumentsId = scope.generateUidIdentifier("arguments")), argumentsId); | ||
}, | ||
getThisId: function getThisId() { | ||
return thisId = thisId || scope.generateUidIdentifier("this"); | ||
return (!thisId && (thisId = scope.generateUidIdentifier("this")), thisId); | ||
} | ||
@@ -66,3 +67,4 @@ }; | ||
var pushDeclaration = function pushDeclaration(id, init) { | ||
body = body || getBody(); | ||
if (!body) body = getBody(); | ||
body.unshift(t.variableDeclaration("var", [t.variableDeclarator(id, init)])); | ||
@@ -69,0 +71,0 @@ }; |
@@ -24,3 +24,6 @@ "use strict"; | ||
} else { | ||
kinds[kind] = kinds[kind] || []; | ||
var _kinds = kinds; | ||
var _kind = kind; | ||
if (!_kinds[_kind]) _kinds[_kind] = []; | ||
kinds[kind].push(declarNode); | ||
@@ -27,0 +30,0 @@ } |
@@ -185,3 +185,3 @@ "use strict"; | ||
Scope.prototype.rename = function (oldName, newName) { | ||
newName = newName || this.generateUidIdentifier(oldName).name; | ||
if (!newName) newName = this.generateUidIdentifier(oldName).name; | ||
@@ -546,3 +546,5 @@ var info = this.getBindingInfo(oldName); | ||
if (t.isBlockStatement(block) || t.isProgram(block)) { | ||
block._declarations = block._declarations || {}; | ||
var _block = block; | ||
if (!_block._declarations) _block._declarations = {}; | ||
block._declarations[opts.key] = { | ||
@@ -549,0 +551,0 @@ kind: opts.kind, |
@@ -27,3 +27,4 @@ "use strict"; | ||
t["assert" + type] = function (node, opts) { | ||
opts = opts || {}; | ||
if (!opts) opts = {}; | ||
if (!is(node, opts)) { | ||
@@ -411,3 +412,4 @@ throw new Error("Expected type " + JSON.stringify(type) + " with option " + JSON.stringify(opts)); | ||
t.ensureBlock = function (node, key) { | ||
key = key || "body"; | ||
if (!key) key = "body"; | ||
return node[key] = t.toBlock(node[key], node); | ||
@@ -414,0 +416,0 @@ }; |
{ | ||
"name": "babel", | ||
"description": "Turn ES6 code into readable vanilla ES5 with source maps", | ||
"version": "4.5.1", | ||
"version": "4.5.2", | ||
"author": "Sebastian McKenzie <sebmck@gmail.com>", | ||
@@ -39,3 +39,3 @@ "homepage": "https://babeljs.io/", | ||
"dependencies": { | ||
"acorn-babel": "0.11.1-34", | ||
"acorn-babel": "0.11.1-35", | ||
"ast-types": "~0.6.1", | ||
@@ -71,3 +71,3 @@ "chalk": "^1.0.0", | ||
"devDependencies": { | ||
"babel": "4.5.0", | ||
"babel": "4.5.1", | ||
"browserify": "^8.1.3", | ||
@@ -77,4 +77,2 @@ "chai": "^2.0.0", | ||
"istanbul": "^0.3.5", | ||
"jshint": "^2.6.0", | ||
"jshint-stylish": "^1.0.0", | ||
"matcha": "^0.6.0", | ||
@@ -81,0 +79,0 @@ "mocha": "^2.1.0", |
@@ -12,5 +12,3 @@ <p align="center"> | ||
<p align="center"> | ||
For more information view the <a href="https://babeljs.io/">documentation</a>. For questions | ||
and support please visit the <a href="https://gitter.im/babel/babel">gitter room</a> before | ||
creating an issue. | ||
For questions and support please visit the <a href="https://gitter.im/babel/babel">gitter room</a> before creating an issue. | ||
</p> | ||
@@ -17,0 +15,0 @@ |
Sorry, the diff of this file is too big to display
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
1640948
9
13147
18
+ Addedacorn-babel@0.11.1-35(transitive)
- Removedacorn-babel@0.11.1-34(transitive)
Updatedacorn-babel@0.11.1-35