Compare commits

...

69 Commits

Author SHA1 Message Date
Sebastian McKenzie
a35e63fb29 v3.3.1 2015-02-01 18:44:07 +11:00
Sebastian McKenzie
3fe7df9a48 fix regenerator destructuring test 2015-02-01 18:42:15 +11:00
Sebastian McKenzie
5288f3afda add 3.3.1 changelog 2015-02-01 18:33:54 +11:00
Sebastian McKenzie
25566a24f6 block hoist assignment pattern destructuring - fixes #652 2015-02-01 18:33:36 +11:00
Sebastian McKenzie
2ff6dee0ec 3.3.0 2015-02-01 16:52:23 +11:00
Sebastian McKenzie
491d1238c2 fix buildHelpers function name 2015-02-01 16:51:57 +11:00
Sebastian McKenzie
234414c2f2 v3.3.0 2015-02-01 16:49:18 +11:00
Sebastian McKenzie
3ff544bbab fix indentation detection 2015-02-01 16:47:28 +11:00
Sebastian McKenzie
416c4cbb84 fix linting errors 2015-02-01 16:44:47 +11:00
Sebastian McKenzie
db5bf1749b fix linting errors 2015-02-01 16:43:42 +11:00
Sebastian McKenzie
41349afea3 add 3.3.0 changelog 2015-02-01 16:43:05 +11:00
Sebastian McKenzie
27da6de723 add back runtime - fixes #651 2015-02-01 16:38:13 +11:00
Sebastian McKenzie
2cdb4e3343 fix linting errors 2015-02-01 16:21:13 +11:00
Sebastian McKenzie
981d3e40f8 add canRun check for playground transformers 2015-02-01 16:20:32 +11:00
Sebastian McKenzie
c7a616730c add levenshtein suggestions to undeclared variable transformer 2015-02-01 16:20:18 +11:00
Sebastian McKenzie
5aa8ece242 don't run playground transformers at all if playground isn't enabled 2015-02-01 16:19:49 +11:00
Sebastian McKenzie
8c7ba20f86 fix regenerator transformer order - fixes #617 2015-02-01 16:19:35 +11:00
Sebastian McKenzie
1cc9027fcf 3.2.1 2015-02-01 16:19:09 +11:00
Sebastian McKenzie
e63dbaa646 v3.2.1 2015-01-31 21:33:26 +11:00
Sebastian McKenzie
4a720625d9 fix linting errors 2015-01-31 21:29:44 +11:00
Sebastian McKenzie
ad428b107a add 3.2.1 changelog 2015-01-31 21:28:14 +11:00
Sebastian McKenzie
c0299320f0 avoid transforming of inner labels and propagation of maps in block scoping transformer - #644 2015-01-31 21:27:20 +11:00
Sebastian McKenzie
efaee3d5d9 remove pending tests 2015-01-31 18:11:54 +11:00
Sebastian McKenzie
12bee73070 restructure internal indexes a bit 2015-01-31 18:04:57 +11:00
Sebastian McKenzie
82c18a837d add detection skeleton #631 2015-01-31 17:59:30 +11:00
Sebastian McKenzie
fed51e8246 3.2.0 2015-01-31 17:59:08 +11:00
Sebastian McKenzie
71f17e464f update 3.2.0 changelog 2015-01-31 17:59:02 +11:00
Sebastian McKenzie
026fd7eddb v3.2.0 2015-01-31 10:15:22 +11:00
Sebastian McKenzie
456b2d3910 remove unused keys declaration in types 2015-01-31 10:12:32 +11:00
Sebastian McKenzie
4208bf3f4b add accept to valid options 6to5/gobble-6to5#2 2015-01-31 10:11:40 +11:00
Sebastian McKenzie
a81678d327 add 3.2.0 changelog 2015-01-31 10:11:19 +11:00
Sebastian McKenzie
be55f42f80 simplify Scope::has 2015-01-31 10:06:22 +11:00
Sebastian McKenzie
b1b326cf9c better self contained module tests - fixes #634 2015-01-30 22:32:21 +11:00
Sebastian McKenzie
a9ff73b4f6 use double quotes instead of single 2015-01-30 21:50:31 +11:00
Sebastian McKenzie
f5ccb9c0ba clean up types, add missing jsdoc parameters, add some descriptions 2015-01-30 21:48:32 +11:00
Sebastian McKenzie
1cbbe00b7a Merge pull request #582 from kruppel/kurt/setter-super
Support use of super inside instance setter.
2015-01-30 21:47:24 +11:00
Sebastian McKenzie
055dd5d2c3 simplify t.getDeclarations keys 2015-01-30 21:42:24 +11:00
Sebastian McKenzie
0fea437536 rename t.getIds to t.getDeclarations and remove dead code 2015-01-30 21:36:51 +11:00
Sebastian McKenzie
f325d3b065 add pattern rest parameters test 2015-01-30 21:26:45 +11:00
Sebastian McKenzie
e514660fbd we no longer have to handle labels on loops in block scoping 2015-01-30 21:26:35 +11:00
Sebastian McKenzie
a5d8144cce don't lazily check kangax compat-table exec comment 2015-01-30 21:17:35 +11:00
Sebastian McKenzie
8145840264 add istanbul config 2015-01-30 21:17:16 +11:00
Sebastian McKenzie
a02eafedfd add additional let scoping nested label tests 2015-01-30 21:07:40 +11:00
Sebastian McKenzie
3f3cd2bb3a add better support for labels in the block scoping transformer and add more let scoping tests - fixes #644 and closes #608 2015-01-30 20:51:20 +11:00
Sebastian McKenzie
503a3f2e3a ignore compat-table tests that have no code 2015-01-30 19:43:47 +11:00
Sebastian McKenzie
48a8723fdb add compat-table to make bootstrap 2015-01-30 19:39:58 +11:00
Sebastian McKenzie
92c297b1be add assertVendor test helper 2015-01-30 19:39:51 +11:00
Sebastian McKenzie
56e26378ff delay running 6to5/register in tests 2015-01-30 19:39:38 +11:00
Sebastian McKenzie
f3f69ab4fa fix scope tracking for default parameters iife 2015-01-30 19:39:20 +11:00
Sebastian McKenzie
2a488b951d remove unused variable in commonjs module formatter 2015-01-30 19:39:09 +11:00
Sebastian McKenzie
ac01caacd3 rename useStrict test to something more specific 2015-01-30 19:39:00 +11:00
Sebastian McKenzie
cbdf746474 fix block scoped functions 2015-01-30 19:38:50 +11:00
Sebastian McKenzie
ad0a1ae66d add kangax compat-table tests - fixes #606 2015-01-30 19:38:44 +11:00
Sebastian McKenzie
3b783979d8 add resolveModuleSource option - closes #471 2015-01-30 18:04:54 +11:00
Sebastian McKenzie
b2ec15accc allow test options to be plain javascript files 2015-01-30 18:04:28 +11:00
Sebastian McKenzie
3b7cfc908e use globals module instead of maintaining our own list 2015-01-30 17:17:42 +11:00
Sebastian McKenzie
010ca83d0d improved relative resolution handling for bin/6to5 - closes #643 2015-01-30 16:59:04 +11:00
Sebastian McKenzie
161c895a90 move esvalid to devDependencies 2015-01-30 16:58:38 +11:00
Sebastian McKenzie
47a45f3731 add additional react ThisExpression conversion test 2015-01-30 11:05:16 +11:00
Sebastian McKenzie
7bb3cfd932 3.1.1 2015-01-30 11:04:46 +11:00
Sebastian McKenzie
16a94a769a v3.1.1 2015-01-30 11:02:28 +11:00
Sebastian McKenzie
f7c7918efe add 3.1.1 changelog 2015-01-30 11:00:43 +11:00
Sebastian McKenzie
bf393c025f properly transform XJSIdentifier nodes referencing this into a ThisExpression - facebook/react#2927 2015-01-30 11:00:37 +11:00
Sebastian McKenzie
bbbc9c0c5e remove redundant enumerable: true property on class methods 2015-01-30 10:44:33 +11:00
Sebastian McKenzie
579db9107f fix link in 3.1.0 changelog - thanks @AluisioASG - closes #641 2015-01-30 10:42:52 +11:00
Sebastian McKenzie
d1d30e9ec9 3.1.0 2015-01-30 10:15:09 +11:00
Kurt Ruppel
d87b70b57e Use right side verbatim for ES6 class setter. 2015-01-26 15:55:27 -08:00
Kurt Ruppel
bbfb297d73 Support use of super inside instance setter. 2015-01-26 15:55:27 -08:00
Kurt Ruppel
9b68d08604 Add test for failing assignment to super setter. 2015-01-26 15:55:27 -08:00
121 changed files with 1145 additions and 383 deletions

3
.gitmodules vendored
View File

@@ -7,3 +7,6 @@
[submodule "vendor/test262"]
path = vendor/test262
url = https://github.com/tc39/test262
[submodule "vendor/compat-table"]
path = vendor/compat-table
url = https://github.com/kangax/compat-table

2
.istanbul.yml Normal file
View File

@@ -0,0 +1,2 @@
instrumentation:
root: lib

View File

@@ -11,10 +11,45 @@
_Note: Gaps between patch versions are faulty/broken releases._
## 3.3.1
* **Bug Fix**
* Block hoist assignment pattern destructuring.
## 3.3.0
* **Bug Fix**
* Do all transforms before the regenerator transform is ran.
* **New Feature**
* Added back the 2.x optional runtime.
## 3.2.1
* **Bug Fix**
* Fix block scoping transformer rewriting breaks and continues to inner labels.
## 3.2.0
* **Bug Fix**
* Fixed scope tracking for default parameters IIFE.
* Fixed block scoped functions.
* Improved `bin/6to5` path resolution.
* **New Feature**
* You can now trigger super setters in classes. Thanks [@kruppel](https://github.com/kruppel)!
* Add `resolveSourceMap` option.
* Better support and output for block scoping loops with labels.
## 3.1.1
* **Polish**
* Drop `enumerable: false` clause from class method definitions as `enumerable` already defaults to `false`.
* **Bug Fix**
* Properly transform `XJSIdentifier` nodes referencing `this` into a `ThisExpression`.
## 3.1.0
* **Breaking Change**
* [Make class methods unenumerable](/Users/sebastian/Projects/6to5/6to5/test/fixtures/esnext/es6-classes/getter-setter.js).
* [Make class methods unenumerable](https://esdiscuss.org/topic/classes-and-enumerability#content-61).
## 3.0.16

View File

@@ -21,6 +21,9 @@ build:
node $(BROWSERIFY_CMD) lib/6to5/browser.js -s to5 >dist/6to5.js
node $(UGLIFY_CMD) dist/6to5.js >dist/6to5.min.js
node bin/6to5-runtime >dist/runtime.js
node $(UGLIFY_CMD) dist/runtime.js >dist/runtime.min.js
rm -rf templates.json
clean:
@@ -77,6 +80,7 @@ publish:
make build
cp dist/6to5.min.js browser.js
cp dist/polyfill.min.js browser-polyfill.js
cp dist/runtime.min.js runtime.js
node tools/cache-templates
test -f templates.json
@@ -110,3 +114,4 @@ bootstrap:
npm install
git submodule update --init
cd vendor/regenerator; npm install
cd vendor/compat-table; npm install object-assign

4
bin/6to5-runtime Executable file
View File

@@ -0,0 +1,4 @@
#!/usr/bin/env node
var runtime = require("../lib/6to5/build-runtime");
console.log(runtime());

View File

@@ -53,10 +53,7 @@ module.exports = function (commander, filenames, opts) {
_.each(["add", "change"], function (type) {
watcher.on(type, function (filename) {
// chop off the dirname plus the path separator
var relative = filename.slice(dirname.length + 1);
console.log(type, filename);
var relative = path.relative(dirname, filename) || filename;
write(filename, relative);
});
});

View File

@@ -1,7 +1,7 @@
#!/usr/bin/env node
var commander = require("commander");
var transform = require("../../lib/6to5/transformation/transform");
var transform = require("../../lib/6to5/transformation");
var util = require("../../lib/6to5/util");
var fs = require("fs");
var each = require("lodash/collection/each");
@@ -11,6 +11,7 @@ commander.option("-t, --source-maps-inline", "Append sourceMappingURL comment to
commander.option("-s, --source-maps", "Save source map alongside the compiled code");
commander.option("-f, --filename [filename]", "Filename to use when reading from stdin - this will be used in source-maps, errors etc [stdin]", "stdin");
commander.option("-w, --watch", "Recompile files on changes");
commander.option("-r, --runtime", "Replace 6to5 declarations with references to a runtime");
commander.option("-e, --experimental", "Enable experimental support for proposed ES7 features");
commander.option("-p, --playground", "Enable playground support");
@@ -108,6 +109,7 @@ exports.opts = {
sourceMap: commander.sourceMaps || commander.sourceMapsInline,
optional: commander.optional,
comments: !commander.removeComments,
runtime: commander.runtime,
modules: commander.modules,
loose: commander.loose
};

View File

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

13
lib/6to5/build-helpers.js Normal file
View File

@@ -0,0 +1,13 @@
var File = require("./file");
var util = require("./util");
var each = require("lodash/collection/each");
var t = require("./types");
module.exports = function (body, namespace) {
each(File.helpers, function (name) {
var key = t.identifier(t.toIdentifier(name));
body.push(t.expressionStatement(
t.assignmentExpression("=", t.memberExpression(namespace, key), util.template(name))
));
});
};

25
lib/6to5/build-runtime.js Normal file
View File

@@ -0,0 +1,25 @@
"use strict";
var buildHelpers = require("./build-helpers");
var generator = require("./generation");
var util = require("./util");
var t = require("./types");
module.exports = function () {
var namespace = t.identifier("to5Runtime");
var body = [];
var container = t.functionExpression(null, [t.identifier("global")], t.blockStatement(body));
var tree = t.program([t.expressionStatement(t.callExpression(container, [util.template("self-global")]))]);
body.push(t.variableDeclaration("var", [
t.variableDeclarator(
namespace,
t.assignmentExpression("=", t.memberExpression(t.identifier("global"), namespace), t.objectExpression([]))
)
]));
buildHelpers(body, namespace);
return generator(tree).code;
};

View File

@@ -1,7 +1,29 @@
//exports.canRun = function (ast, userAgent) {
module.exports = detect;
//};
var SYNTAX_KEYS = require("./syntax-keys");
var traverse = require("../traverse");
var visitors = traverse.explode(require("./visitors"));
//exports.whoCanRun = function (ast, userAgent) {
function detect(ast) {
var stats = {
syntax: {},
builtins: {}
};
//};
var detectedSyntax = function (name) {
stats.syntax[name] = true;
};
traverse(ast, {
enter: function (node, parent) {
if (SYNTAX_KEYS[node.type]) {
detectedSyntax(SYNTAX_KEYS[node.type]);
}
var visitor = visitors[node.type];
if (visitor) visitor(node, parent, detectedSyntax);
}
});
return stats;
}

View File

@@ -0,0 +1,84 @@
{
"ArrowFunctionExpression": "es6.arrowFunctions",
"AwaitExpression": "es7.asyncFunctions",
"ClassBody": "es6.classes",
"ClassDeclaration": "es6.classes",
"ClassExpression": "es6.classes",
"MethodDefinition": "es6.classes",
"ComprehensionBlock": "es7.comprehensions",
"ComprehensionExpression": "es7.comprehensions",
"ForOfStatement": "es6.forOf",
"ExportBatchSpecifier": "es6.modules",
"ExportDeclaration": "es6.modules",
"ExportSpecifier": "es6.modules",
"ImportBatchSpecifier": "es6.modules",
"ImportDeclaration": "es6.modules",
"ImportSpecifier": "es6.modules",
"ArrayPattern": "es6.destructuring",
"AssignmentPattern": "es6.destructuring",
"ObjectPattern": "es6.destructuring",
"RestElement": "es6.parameters.rest",
"SpreadElement": "es6.spread",
"SpreadProperty": "es7.objectSpread",
"TaggedTemplateExpression": "es6.templateLiterals",
"TemplateElement": "es6.templateLiterals",
"TemplateLiteral": "es6.templateLiterals",
"VirtualPropertyExpression": "es7.abstractReferences",
"PrivateDeclaration": "es7.abstractReferences",
"YieldExpression": "es6.generators",
"AnyTypeAnnotation": "flow",
"ArrayTypeAnnotation": "flow",
"BooleanTypeAnnotation": "flow",
"ClassProperty": "flow",
"DeclareClass": "flow",
"DeclareFunction": "flow",
"DeclareModule": "flow",
"DeclareVariable": "flow",
"FunctionTypeAnnotation": "flow",
"FunctionTypeParam": "flow",
"GenericTypeAnnotation": "flow",
"InterfaceExtends": "flow",
"InterfaceDeclaration": "flow",
"IntersectionTypeAnnotation": "flow",
"NullableTypeAnnotation": "flow",
"NumberTypeAnnotation": "flow",
"StringLiteralTypeAnnotation": "flow",
"StringTypeAnnotation": "flow",
"TupleTypeAnnotation": "flow",
"TypeofTypeAnnotation": "flow",
"TypeAlias": "flow",
"TypeAnnotation": "flow",
"TypeParameterDeclaration": "flow",
"TypeParameterInstantiation": "flow",
"ObjectTypeAnnotation": "flow",
"ObjectTypeCallProperty": "flow",
"ObjectTypeIndexer": "flow",
"ObjectTypeProperty": "flow",
"QualifiedTypeIdentifier": "flow",
"UnionTypeAnnotation": "flow",
"VoidTypeAnnotation": "flow",
"JSXAttribute": "jsx",
"JSXClosingElement": "jsx",
"JSXElement": "jsx",
"JSXEmptyExpression": "jsx",
"JSXExpressionContainer": "jsx",
"JSXIdentifier": "jsx",
"JSXMemberExpression": "jsx",
"JSXNamespacedName": "jsx",
"JSXOpeningElement": "jsx",
"JSXSpreadAttribute": "jsx"
}

View File

@@ -0,0 +1,54 @@
var t = require("../types");
var _ = require("lodash");
exports.AssignmentExpression = function (node, parent, detected) {
if (node.operator === "**=") {
detected("es6.exponentation");
}
};
exports.BinaryExpression = function (node, parent, detected) {
if (node.operator === "**") {
detected("es6.exponentation");
}
};
exports.VariableDeclaration = function (node, parent, detected) {
if (node.kind === "let" || node.kind === "const") {
detected("es6.blockScoping");
}
if (node.kind === "const") {
detected("es6.constants");
}
};
exports.Property = function (node, parent, detected) {
if (node.shorthand || node.method) {
detected("es6.properties.shorthand");
}
if (node.kind === "set" || node.kind === "get") {
detected("es5.properties.mutators");
}
if (node.computed) {
detected("es6.properties.computed");
}
};
exports.AssignmentPattern = function (node, parent, detected) {
if (t.isFunction(parent) && _.contains(parent.params, node)) {
detected("es6.parameters.default");
}
};
exports.Function = function (node, parent, detected) {
if (node.generator) {
detected("es6.generators");
}
if (node.async) {
detected("es7.asyncFunctions");
}
};

View File

@@ -4,8 +4,8 @@ module.exports = File;
var SHEBANG_REGEX = /^\#\!.*/;
var transform = require("./transformation/transform");
var generate = require("./generation/generator");
var transform = require("./transformation");
var generate = require("./generation");
var clone = require("./helpers/clone");
var Scope = require("./traverse/scope");
var util = require("./util");
@@ -24,7 +24,7 @@ function File(opts) {
this.data = {};
this.lastStatements = [];
this.opts = File.normaliseOptions(opts);
this.opts = this.normaliseOptions(opts);
this.ast = {};
this.buildTransformers();
@@ -49,7 +49,8 @@ File.helpers = [
"interop-require-wildcard",
"typeof",
"extends",
"get"
"get",
"set"
];
File.validOptions = [
@@ -74,14 +75,17 @@ File.validOptions = [
"format",
"playground",
"experimental",
"resolveModuleSource",
"runtime",
// these are used by plugins
"ignore",
"only",
"extensions"
"extensions",
"accept"
];
File.normaliseOptions = function (opts) {
File.prototype.normaliseOptions = function (opts) {
opts = clone(opts);
for (var key in opts) {
@@ -92,6 +96,7 @@ File.normaliseOptions = function (opts) {
defaults(opts, {
keepModuleIdExtensions: false,
resolveModuleSource: null,
experimental: false,
reactCompat: false,
playground: false,
@@ -104,6 +109,7 @@ File.normaliseOptions = function (opts) {
comments: true,
filename: "unknown",
modules: "common",
runtime: false,
loose: [],
code: true,
ast: true
@@ -142,6 +148,10 @@ File.normaliseOptions = function (opts) {
opts.experimental = true;
}
if (opts.runtime) {
this.set("runtimeIdentifier", t.identifier("to5Runtime"));
}
opts.blacklist = transform._ensureTransformerNames("blacklist", opts.blacklist);
opts.whitelist = transform._ensureTransformerNames("whitelist", opts.whitelist);
opts.optional = transform._ensureTransformerNames("optional", opts.optional);
@@ -332,7 +342,11 @@ File.prototype.transform = function (ast) {
this.ast = ast;
this.lastStatements = t.getLastStatements(ast.program);
this.scope = new Scope(ast.program, ast, null, this);
this.moduleFormatter = this.getModuleFormatter(this.opts.modules);
var modFormatter = this.moduleFormatter = this.getModuleFormatter(this.opts.modules);
if (modFormatter.init && this.transformers["es6.modules"].canRun()) {
modFormatter.init();
}
var astRun = function (key) {
each(self.transformerStack, function (pass) {

View File

@@ -40,9 +40,11 @@ each(Buffer.prototype, function (fn, key) {
});
CodeGenerator.normaliseOptions = function (code, opts) {
var indent = detectIndent(code);
var style = indent.indent;
if (!style || style === " ") style = " ";
var style = " ";
if (code) {
var indent = detectIndent(code).indent;
if (indent && indent !== " ") style = indent;
}
return merge({
parentheses: true,

View File

@@ -0,0 +1,38 @@
// taken from stackoverflow, it's crap i know.
module.exports = function (a, b) {
if (a.length === 0) return b.length;
if (b.length === 0) return a.length;
var matrix = [];
// increment along the first column of each row
var i;
for (i = 0; i <= b.length; i++) {
matrix[i] = [i];
}
// increment each column in the first row
var j;
for (j = 0; j <= a.length; j++) {
matrix[0][j] = j;
}
// Fill in the rest of the matrix
for (i = 1; i <= b.length; i++) {
for (j = 1; j <= a.length; j++) {
if (b.charAt(i - 1) == a.charAt(j - 1)) {
matrix[i][j] = matrix[i - 1][j - 1];
} else {
matrix[i][j] = Math.min(
matrix[i - 1][j - 1] + 1, // substitution
Math.min(
matrix[i][j - 1] + 1, // insertion
matrix[i - 1][j] + 1) // deletion
);
}
}
}
return matrix[b.length][a.length];
};

View File

@@ -1,12 +1,14 @@
"use strict";
var transform = require("./transformation/transform");
var transform = require("./transformation");
var util = require("./util");
var fs = require("fs");
var isFunction = require("lodash/lang/isFunction");
exports.version = require("../../package").version;
exports.runtime = require("./build-runtime");
exports.types = require("./types");
exports.register = function (opts) {

View File

@@ -21,6 +21,36 @@ function ReplaceSupers(opts) {
this.file = opts.file;
}
/**
* Sets a super class value of the named property.
*
* @example
*
* _set(Object.getPrototypeOf(CLASS.prototype), "METHOD", "VALUE", this)
*
* @param {Node} property
* @param {boolean} isStatic
* @param {boolean} isComputed
*
* @returns {Node}
*/
ReplaceSupers.prototype.setSuperProperty = function (property, value, isStatic, isComputed, thisExpression) {
return t.callExpression(
this.file.addHelper("set"),
[
t.callExpression(
t.memberExpression(t.identifier("Object"), t.identifier("getPrototypeOf")),
[
isStatic ? this.className : t.memberExpression(this.className, t.identifier("prototype"))
]
),
isComputed ? property : t.literal(property.name),
value,
thisExpression
]
);
};
/**
* Gets a node representing the super class value of the named property.
*
@@ -191,6 +221,7 @@ ReplaceSupers.prototype.specHandle = function (getThisReference, node, parent) {
var property;
var computed;
var args;
var thisReference;
if (t.isIdentifier(node, { name: "super" })) {
if (!(t.isMemberExpression(parent) && !parent.computed && parent.property === node)) {
@@ -226,11 +257,18 @@ ReplaceSupers.prototype.specHandle = function (getThisReference, node, parent) {
// super.name; -> _get(Object.getPrototypeOf(ClassName.prototype), "name", this);
property = node.property;
computed = node.computed;
} else if (t.isAssignmentExpression(node)) {
if (!t.isIdentifier(node.left.object, { name: "super" })) return;
if (methodNode.kind !== "set") return;
thisReference = getThisReference();
// super.name = "val"; -> _set(Object.getPrototypeOf(ClassName.prototype), "name", this);
return this.setSuperProperty(node.left.property, node.right, methodNode.static, node.left.computed, thisReference);
}
if (!property) return;
var thisReference = getThisReference();
thisReference = getThisReference();
var superProperty = this.superProperty(property, methodNode.static, computed, thisReference);
if (args) {
if (args.length === 1 && t.isSpreadElement(args[0])) {

View File

@@ -45,7 +45,7 @@ var exportsVisitor = {
formatter.hasLocalImports = true;
if (declar && t.isStatement(declar)) {
extend(formatter.localExports, t.getIds(declar, true));
extend(formatter.localExports, t.getDeclarations(declar));
}
if (!node.default) {
@@ -67,7 +67,7 @@ var importsVisitor = {
enter: function (node, parent, scope, context, formatter) {
if (t.isImportDeclaration(node)) {
formatter.hasLocalImports = true;
extend(formatter.localImports, t.getIds(node, true));
extend(formatter.localImports, t.getDeclarations(node));
formatter.bumpImportOccurences(node);
}
}

View File

@@ -15,6 +15,8 @@ function AMDFormatter() {
util.inherits(AMDFormatter, DefaultFormatter);
AMDFormatter.prototype.init = CommonFormatter.prototype.init;
AMDFormatter.prototype.buildDependencyLiterals = function () {
var names = [];
for (var name in this.ids) {

View File

@@ -3,20 +3,22 @@
module.exports = CommonJSFormatter;
var DefaultFormatter = require("./_default");
var contains = require("lodash/collection/contains");
var util = require("../../util");
var t = require("../../types");
var contains = require("lodash/collection/contains");
function CommonJSFormatter(file) {
function CommonJSFormatter() {
DefaultFormatter.apply(this, arguments);
if (this.hasNonDefaultExports) {
file.ast.program.body.push(util.template("exports-module-declaration", true));
}
}
util.inherits(CommonJSFormatter, DefaultFormatter);
CommonJSFormatter.prototype.init = function () {
if (this.hasNonDefaultExports) {
this.file.ast.program.body.push(util.template("exports-module-declaration", true));
}
};
CommonJSFormatter.prototype.importSpecifier = function (specifier, node, nodes) {
var variableName = t.getSpecifierName(specifier);

View File

@@ -21,6 +21,8 @@ function SystemFormatter(file) {
util.inherits(SystemFormatter, AMDFormatter);
SystemFormatter.prototype.init = function () {};
SystemFormatter.prototype._addImportSource = function (node, exportNode) {
node._importSource = exportNode.source && exportNode.source.value;
return node;

View File

@@ -0,0 +1,24 @@
(function set(object, property, value, receiver) {
var desc = Object.getOwnPropertyDescriptor(object, property);
if (desc === undefined) {
var parent = Object.getPrototypeOf(object);
if (parent === null) {
return;
} else {
return set(parent, property, value, receiver);
}
} else if ("value" in desc && desc.writable) {
desc.value = value;
return;
} else {
var setter = desc.set;
if (setter === undefined) {
return;
}
return setter.call(receiver, value);
}
});

View File

@@ -41,6 +41,8 @@ TransformerPass.prototype.canRun = function () {
if (transformer.experimental && !opts.experimental) return false;
if (transformer.playground && !opts.playground) return false;
return true;
};

View File

@@ -3,8 +3,8 @@
module.exports = Transformer;
var TransformerPass = require("./transformer-pass");
var t = require("../types");
var isFunction = require("lodash/lang/isFunction");
var traverse = require("../traverse");
var isObject = require("lodash/lang/isObject");
var each = require("lodash/collection/each");
@@ -17,6 +17,7 @@ var each = require("lodash/collection/each");
function Transformer(key, transformer, opts) {
this.manipulateOptions = transformer.manipulateOptions;
this.experimental = !!transformer.experimental;
this.playground = !!transformer.playground;
this.secondPass = !!transformer.secondPass;
this.optional = !!transformer.optional;
this.handlers = this.normalise(transformer);
@@ -31,6 +32,8 @@ Transformer.prototype.normalise = function (transformer) {
transformer = { ast: transformer };
}
traverse.explode(transformer);
each(transformer, function (fns, type) {
// hidden property
if (type[0] === "_") {
@@ -46,13 +49,6 @@ Transformer.prototype.normalise = function (transformer) {
if (!fns.exit) fns.exit = function () { };
transformer[type] = fns;
var aliases = t.FLIPPED_ALIAS_KEYS[type];
if (aliases) {
each(aliases, function (alias) {
transformer[alias] = fns;
});
}
});
return transformer;

View File

@@ -45,19 +45,8 @@ exports.Loop = function (node, parent, scope, context, file) {
t.ensureBlock(node);
node.body._letDeclarators = [init];
}
if (t.isLabeledStatement(parent)) {
// set label so `run` has access to it
node.label = parent.label;
}
var letScoping = new LetScoping(node, node.body, parent, scope, file);
letScoping.run();
if (node.label && !t.isLabeledStatement(parent)) {
// we've been given a label so let's wrap ourselves
return t.labeledStatement(node.label, node);
}
};
exports.Program =
@@ -269,7 +258,7 @@ LetScoping.prototype.getLetReferences = function () {
//
for (var i = 0; i < declarators.length; i++) {
declar = declarators[i];
extend(this.outsideLetReferences, t.getIds(declar, true));
extend(this.outsideLetReferences, t.getDeclarations(declar));
}
//
@@ -285,7 +274,7 @@ LetScoping.prototype.getLetReferences = function () {
//
for (i = 0; i < declarators.length; i++) {
declar = declarators[i];
var keys = t.getIds(declar, true);
var keys = t.getDeclarations(declar);
extend(this.letReferences, keys);
this.hasLetReferences = true;
}
@@ -308,34 +297,71 @@ LetScoping.prototype.getLetReferences = function () {
return state.closurify;
};
var loopNodeTo = function (node) {
if (t.isBreakStatement(node)) {
return "break";
} else if (t.isContinueStatement(node)) {
return "continue";
}
};
var loopVisitor = {
enter: function (node, parent, scope, context, state) {
var replace;
if (t.isLoop(node)) {
state.ignoreLabeless = true;
traverse(node, loopVisitor, scope, state);
state.ignoreLabeless = false;
}
if (t.isFunction(node) || t.isLoop(node)) {
return context.skip();
}
if (node && !node.label && state.isLoop) {
if (t.isBreakStatement(node)) {
if (t.isSwitchCase(parent)) return;
var loopText = loopNodeTo(node);
state.hasBreak = true;
replace = t.returnStatement(t.literal("break"));
} else if (t.isContinueStatement(node)) {
state.hasContinue = true;
replace = t.returnStatement(t.literal("continue"));
if (loopText) {
if (node.label) {
// we shouldn't be transforming this because it exists somewhere inside
if (state.innerLabels.indexOf(node.label.name) >= 0) {
return;
}
loopText = loopText + "|" + node.label.name;
} else {
// we shouldn't be transforming these statements because
// they don't refer to the actual loop we're scopifying
if (state.ignoreLabeless) return;
// break statements mean something different in this context
if (t.isBreakStatement(node) && t.isSwitchCase(parent)) return;
}
state.hasBreakContinue = true;
state.map[loopText] = node;
replace = t.literal(loopText);
}
if (t.isReturnStatement(node)) {
state.hasReturn = true;
replace = t.returnStatement(t.objectExpression([
replace = t.objectExpression([
t.property("init", t.identifier("v"), node.argument || t.identifier("undefined"))
]));
]);
}
if (replace) return t.inherits(replace, node);
if (replace) {
replace = t.returnStatement(replace);
return t.inherits(replace, node);
}
}
};
var loopLabelVisitor = {
enter: function (node, parent, scope, context, state) {
if (t.isLabeledStatement(node)) {
state.innerLabels.push(node.label.name);
}
}
};
@@ -350,13 +376,17 @@ var loopVisitor = {
LetScoping.prototype.checkLoop = function () {
var state = {
hasContinue: false,
hasReturn: false,
hasBreak: false,
isLoop: !!this.loopParent
hasBreakContinue: false,
ignoreLabeless: false,
innerLabels: [],
hasReturn: false,
isLoop: !!this.loopParent,
map: {}
};
traverse(this.block, loopLabelVisitor, this.scope, state);
traverse(this.block, loopVisitor, this.scope, state);
return state;
};
@@ -422,7 +452,7 @@ LetScoping.prototype.pushDeclar = function (node) {
LetScoping.prototype.build = function (ret, call) {
var has = this.has;
if (has.hasReturn || has.hasBreak || has.hasContinue) {
if (has.hasReturn || has.hasBreakContinue) {
this.buildHas(ret, call);
} else {
this.body.push(t.expressionStatement(call));
@@ -455,22 +485,14 @@ LetScoping.prototype.buildHas = function (ret, call) {
});
}
if (has.hasBreak || has.hasContinue) {
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.");
}
// ensure that the parent has a label as we're building a switch and we
// need to be able to access it
var label = loopParent.label = loopParent.label || this.scope.generateUidIdentifier("loop");
if (has.hasBreak) {
cases.push(t.switchCase(t.literal("break"), [t.breakStatement(label)]));
}
if (has.hasContinue) {
cases.push(t.switchCase(t.literal("continue"), [t.continueStatement(label)]));
for (var key in has.map) {
cases.push(t.switchCase(t.literal(key), [has.map[key]]));
}
if (has.hasReturn) {

View File

@@ -231,7 +231,7 @@ Class.prototype.pushMethod = function (node) {
}
util.pushMutatorMap(mutatorMap, methodName, kind, node.computed, node);
util.pushMutatorMap(mutatorMap, methodName, "enumerable", node.computed, t.literal(false));
util.pushMutatorMap(mutatorMap, methodName, "enumerable", node.computed, false);
};
/**

View File

@@ -6,7 +6,7 @@ var t = require("../../../types");
var visitor = {
enter: function (node, parent, scope, context, state) {
if (t.isDeclaration(node) || t.isAssignmentExpression(node)) {
var ids = t.getIds(node, true);
var ids = t.getDeclarations(node);
for (var key in ids) {
var id = ids[key];
@@ -31,7 +31,7 @@ var visitor = {
exports.Scope = function (node, parent, scope, context, file) {
traverse(node, visitor, scope, {
constants: scope.getAllOfKind("const"),
constants: scope.getAllDeclarationsOfKind("const"),
file: file
});
};

View File

@@ -46,9 +46,11 @@ var push = function (opts, nodes, elem, parentId) {
var pushAssignmentPattern = function (opts, nodes, pattern, parentId) {
var tempParentId = opts.scope.generateUidBasedOnNode(parentId, opts.file);
nodes.push(t.variableDeclaration("var", [
var declar = t.variableDeclaration("var", [
t.variableDeclarator(tempParentId, parentId)
]));
]);
declar._blockHoist = opts.blockHoist;
nodes.push(declar);
nodes.push(buildVariableAssign(
opts,

View File

@@ -13,7 +13,7 @@ var hasDefaults = function (node) {
var iifeVisitor = {
enter: function (node, parent, scope, context, state) {
if (t.isReferencedIdentifier(node, parent) && scope.hasOwn(node.name)) {
if (t.isReferencedIdentifier(node, parent) && state.scope.hasOwn(node.name)) {
state.iife = true;
context.stop();
}

View File

@@ -58,15 +58,15 @@ exports.Function = function (node, parent, scope) {
node.body.body.unshift(restDeclar);
}
node.body.body.unshift(
util.template("rest", {
ARGUMENTS: argsId,
ARRAY_KEY: arrKey,
ARRAY_LEN: arrLen,
START: start,
ARRAY: rest,
KEY: key,
LEN: len,
})
);
var loop = util.template("rest", {
ARGUMENTS: argsId,
ARRAY_KEY: arrKey,
ARRAY_LEN: arrLen,
START: start,
ARRAY: rest,
KEY: key,
LEN: len,
});
loop._blockHoist = node.params.length + 1;
node.body.body.unshift(loop);
};

View File

@@ -13,7 +13,7 @@ module.exports = {
react: require("./other/react"),
_modulesSplit: require("./internal/modules-split"),
_modules: require("./internal/modules"),
// needs to be before `regenerator` due to generator comprehensions
// needs to be before `_aliasFunction`
@@ -52,14 +52,13 @@ module.exports = {
// needs to be after `es6.blockScoping` due to needing `letReferences` set on blocks
"es6.blockScopingTDZ": require("./es6/block-scoping-tdz"),
// needs to be after block scoping since regenerator doesn't support it
regenerator: require("./other/regenerator"),
"es6.parameters.default": require("./es6/parameters.default"),
"es6.parameters.rest": require("./es6/parameters.rest"),
"es6.destructuring": require("./es6/destructuring"),
regenerator: require("./other/regenerator"),
// needs to be after `regenerator` due to needing `regeneratorRuntime` references
// needs to be after `es6.forOf` due to needing `Symbol.iterator` references
// needs to be before `es6.modules` due to dynamic imports

View File

@@ -8,7 +8,18 @@
var t = require("../../../types");
var resolveModuleSource = function (node, parent, scope, context, file) {
var resolveModuleSource = file.opts.resolveModuleSource;
if (node.source && resolveModuleSource) {
node.source.value = resolveModuleSource(node.source.value);
}
};
exports.ImportDeclaration = resolveModuleSource;
exports.ExportDeclaration = function (node, parent, scope) {
resolveModuleSource.apply(null, arguments);
var declar = node.declaration;
if (node.default) {

View File

@@ -8,8 +8,10 @@
var esutils = require("esutils");
var t = require("../../../types");
exports.JSXIdentifier = function (node) {
if (esutils.keyword.isIdentifierName(node.name)) {
exports.JSXIdentifier = function (node, parent) {
if (node.name === "this" && t.isReferenced(node, parent)) {
return t.thisExpression();
} else if (esutils.keyword.isIdentifierName(node.name)) {
node.type = "Identifier";
} else {
return t.literal(node.name);

View File

@@ -17,5 +17,5 @@ exports.FunctionExpression = function (node, parent, scope, context) {
};
exports.ThisExpression = function (node, parent, scope, context, file) {
throw file.errorWithNode(node, "Top level `this` is not allowed", ReferenceError);
throw file.errorWithNode(node, "Top level `this` is `undefined` in strict mode", ReferenceError);
};

View File

@@ -1,7 +1,9 @@
"use strict";
var build = require("../../helpers/build-conditional-assignment-operator-transformer");
var t = require("../../../types");
var t = require("../../../types");
exports.playground = true;
build(exports, {
is: function (node, file) {

View File

@@ -3,6 +3,8 @@
var build = require("../../helpers/build-conditional-assignment-operator-transformer");
var t = require("../../../types");
exports.playground = true;
build(exports, {
is: function (node) {
var is = t.isAssignmentExpression(node) && node.operator === "?=";

View File

@@ -2,6 +2,8 @@
var t = require("../../../types");
exports.playground = true;
exports.BindMemberExpression = function (node, parent, scope) {
var object = node.object;
var prop = node.property;

View File

@@ -3,6 +3,8 @@
var traverse = require("../../../traverse");
var t = require("../../../types");
exports.playground = true;
var visitor = {
enter: function (node, parent, scope, context, state) {
if (t.isFunction(node)) return;

View File

@@ -3,13 +3,13 @@
var t = require("../../../types");
exports.BlockStatement = function (node, parent) {
if (t.isFunction(parent) || t.isExportDeclaration(parent)) {
if ((t.isFunction(parent) && parent.body === node) || t.isExportDeclaration(parent)) {
return;
}
for (var i = 0; i < node.body.length; i++) {
var func = node.body[i];
if (!t.isFunctionDeclaration(i)) continue;
if (!t.isFunctionDeclaration(func)) continue;
var declar = t.variableDeclaration("let", [
t.variableDeclarator(func.id, t.toExpression(func))
@@ -21,6 +21,6 @@ exports.BlockStatement = function (node, parent) {
// todo: name this
func.id = null;
func.body[i] = declar;
node.body[i] = declar;
}
};

View File

@@ -1,9 +1,38 @@
"use strict";
var levenshtein = require("../../../helpers/levenshtein");
var t = require("../../../types");
exports.optional = true;
exports.Identifier = function (node, parent, scope, context, file) {
if (!scope.has(node.name, true)) {
throw file.errorWithNode(node, "Reference to undeclared variable", ReferenceError);
if (!t.isReferenced(node, parent)) return;
if (scope.has(node.name, true)) return;
var msg = "Reference to undeclared variable";
// get the closest declaration to offer as a suggestion
// the variable name may have just been mistyped
var declarations = scope.getAllDeclarations();
var closest;
var shortest = -1;
for (var name in declarations) {
var distance = levenshtein(node.name, name);
if (distance <= 0 || distance > 3) continue;
if (distance <= shortest) continue;
closest = name;
shortest = distance;
}
if (closest) {
msg += " - Did you mean " + closest + "?";
}
//
throw file.errorWithNode(node, msg, ReferenceError);
};

View File

@@ -1,64 +0,0 @@
[
"Set",
"Map",
"WeakMap",
"WeakSet",
"Proxy",
"Promise",
"Reflect",
"Symbol",
"System",
"__filename",
"__dirname",
"GLOBAL",
"global",
"module",
"require",
"Buffer",
"console",
"exports",
"process",
"setTimeout",
"clearTimeout",
"setInterval",
"clearInterval",
"setImmediate",
"clearImmediate",
"Array",
"Boolean",
"Date",
"decodeURI",
"decodeURIComponent",
"encodeURI",
"encodeURIComponent",
"Error",
"eval",
"EvalError",
"Function",
"hasOwnProperty",
"isFinite",
"isNaN",
"JSON",
"Map",
"Math",
"Number",
"Object",
"Proxy",
"Promise",
"parseInt",
"parseFloat",
"RangeError",
"ReferenceError",
"RegExp",
"Set",
"String",
"SyntaxError",
"TypeError",
"URIError",
"WeakMap",
"WeakSet",
"arguments",
"NaN",
"window",
"self"
]

View File

@@ -237,6 +237,20 @@ traverse.removeProperties = function (tree) {
return tree;
};
traverse.explode = function (obj) {
for (var type in obj) {
var fns = obj[type];
var aliases = t.FLIPPED_ALIAS_KEYS[type];
if (aliases) {
for (var i = 0; i < aliases.length; i++) {
obj[aliases[i]] = fns;
}
}
}
return obj;
};
function hasBlacklistedType(node, parent, scope, context, state) {
if (node.type === state.type) {
state.has = true;

View File

@@ -3,11 +3,13 @@
module.exports = Scope;
var traverse = require("./index");
var globals = require("globals");
var object = require("../helpers/object");
var t = require("../types");
var each = require("lodash/collection/each");
var has = require("lodash/object/has");
var contains = require("lodash/collection/contains");
var flatten = require("lodash/array/flatten");
var defaults = require("lodash/object/defaults");
var FOR_KEYS = ["left", "init"];
@@ -35,12 +37,12 @@ function Scope(block, parentBlock, parent, file) {
this.declarationKinds = info.declarationKinds;
}
Scope.defaultDeclarations = require("./global-keys");
Scope.defaultDeclarations = flatten([globals.builtin, globals.browser, globals.node].map(Object.keys));
Scope.prototype._add = function (node, references, throwOnDuplicate) {
if (!node) return;
var ids = t.getIds(node, true);
var ids = t.getDeclarations(node);
for (var key in ids) {
var id = ids[key];
@@ -324,12 +326,31 @@ Scope.prototype.getFunctionParent = function () {
};
/**
* Walks the scope tree and gathers all declarations of `kind`.
* Walks the scope tree and gathers **all** declarations.
*
* @returns {Object}
*/
Scope.prototype.getAllOfKind = function (kind) {
Scope.prototype.getAllDeclarations = function () {
var ids = object();
var scope = this;
do {
defaults(ids, scope.declarations);
scope = scope.parent;
} while (scope);
return ids;
};
/**
* Walks the scope tree and gathers all declarations of `kind`.
*
* @param {String} kind
* @returns {Object}
*/
Scope.prototype.getAllDeclarationsOfKind = function (kind) {
var ids = object();
var scope = this;
@@ -385,8 +406,11 @@ Scope.prototype.parentGet = function (id, decl) {
*/
Scope.prototype.has = function (id, decl) {
return (id && (this.hasOwn(id, decl) || this.parentHas(id, decl))) ||
contains(Scope.defaultDeclarations, id);
if (!id) return false;
if (this.hasOwn(id, decl)) return true;
if (this.parentHas(id, decl)) return true;
if (contains(Scope.defaultDeclarations, id)) return true;
return false;
};
/**

View File

@@ -8,15 +8,10 @@ var each = require("lodash/collection/each");
var uniq = require("lodash/array/uniq");
var compact = require("lodash/array/compact");
var defaults = require("lodash/object/defaults");
var keys = require("lodash/object/keys");
var isString = require("lodash/lang/isString");
var t = exports;
t.NATIVE_TYPE_NAMES = ["Array", "Object", "Number", "Boolean", "Date", "Array", "String"];
//
/**
* Registers `is[Type]` and `assert[Type]` generated functions for a given `type`.
* Pass `skipAliasCheck` to force it to directly compare `node.type` with `type`.
@@ -39,8 +34,7 @@ function registerType(type, skipAliasCheck) {
}
t.STATEMENT_OR_BLOCK_KEYS = ["consequent", "body"];
//
t.NATIVE_TYPE_NAMES = ["Array", "Object", "Number", "Boolean", "Date", "Array", "String"];
t.VISITOR_KEYS = require("./visitor-keys");
@@ -66,6 +60,7 @@ each(t.FLIPPED_ALIAS_KEYS, function (types, type) {
/**
* Returns whether `node` is of given `type`.
*
* For better performance, use this instead of `is[Type]` when `type` is unknown.
* Optionally, pass `skipAliasCheck` to directly compare `node.type` with `type`.
*
@@ -156,6 +151,9 @@ t.isFalsyExpression = function (node) {
* declarations hoisted to the top of the current scope.
*
* Expression statements are just resolved to their standard expression.
*
* @param {Array} nodes
* @param {Scope} scope
*/
t.toSequenceExpression = function (nodes, scope) {
@@ -185,17 +183,23 @@ t.toSequenceExpression = function (nodes, scope) {
}
};
//
/*
* Description
*
* @param {Object} actual
* @param {Object} expected
* @returns {Boolean}
*/
t.shallowEqual = function (actual, expected) {
var keys = Object.keys(expected);
var key;
for (var i = 0; i < keys.length; i++) {
key = keys[i];
var key = keys[i];
if (actual[key] !== expected[key])
if (actual[key] !== expected[key]) {
return false;
}
}
return true;
@@ -330,7 +334,7 @@ t.isReferenced = function (node, parent) {
};
/**
* Description
* Check if the input `node` is an `Identifier` and `isReferenced`.
*
* @param {Object} node
* @param {Object} parent
@@ -342,7 +346,8 @@ t.isReferencedIdentifier = function (node, parent) {
};
/**
* Description
* Check if the input `name` is a valid identifier name
* and isn't a reserved word.
*
* @param {String} name
* @returns {Boolean}
@@ -502,12 +507,10 @@ t.toBlock = function (node, parent) {
* declaration then it's assumed to be an assignable.
*
* @param {Object} node
* @param {Boolean} [map]
* @param {Array} [ignoreTypes]
* @returns {Array|Object}
*/
t.getIds = function (node, map, ignoreTypes) {
t.getDeclarations = function (node) {
var search = [].concat(node);
var ids = object();
@@ -515,13 +518,7 @@ t.getIds = function (node, map, ignoreTypes) {
var id = search.shift();
if (!id) continue;
// blacklist types
if (ignoreTypes && ignoreTypes.indexOf(id.type) >= 0) continue;
var nodeKeys = t.getIds.nodes[id.type];
var arrKeys = t.getIds.arrays[id.type];
var i, key;
var keys = t.getDeclarations.keys[id.type];
if (t.isIdentifier(id)) {
ids[id.name] = id;
@@ -529,27 +526,18 @@ t.getIds = function (node, map, ignoreTypes) {
if (t.isDeclaration(node.declaration)) {
search.push(node.declaration);
}
} else if (nodeKeys) {
for (i = 0; i < nodeKeys.length; i++) {
key = nodeKeys[i];
if (id[key]) {
search.push(id[key]);
break;
}
}
} else if (arrKeys) {
for (i = 0; i < arrKeys.length; i++) {
key = arrKeys[i];
} else if (keys) {
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
search = search.concat(id[key] || []);
}
}
}
if (!map) ids = keys(ids);
return ids;
};
t.getIds.nodes = {
t.getDeclarations.keys = {
AssignmentExpression: ["left"],
ImportBatchSpecifier: ["name"],
ImportSpecifier: ["name", "id"],
@@ -562,10 +550,7 @@ t.getIds.nodes = {
RestElement: ["argument"],
Property: ["value"],
ComprehensionBlock: ["left"],
AssignmentPattern: ["left"]
};
t.getIds.arrays = {
AssignmentPattern: ["left"],
PrivateDeclaration: ["declarations"],
ComprehensionExpression: ["blocks"],
ImportDeclaration: ["specifiers"],

View File

@@ -121,7 +121,12 @@ exports.buildDefineProperties = function (mutatorMap) {
map.writable = t.literal(true);
}
map.enumerable = map.enumerable || t.literal(true);
if (map.enumerable === false) {
delete map.enumerable;
} else {
map.enumerable = t.literal(true);
}
map.configurable = t.literal(true);
each(map, function (node, key) {

View File

@@ -1,7 +1,7 @@
{
"name": "6to5",
"description": "Turn ES6 code into readable vanilla ES5 with source maps",
"version": "3.1.0",
"version": "3.3.1",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://6to5.org/",
"repository": "6to5/6to5",
@@ -9,7 +9,8 @@
"main": "lib/6to5/index.js",
"bin": {
"6to5": "./bin/6to5/index.js",
"6to5-node": "./bin/6to5-node"
"6to5-node": "./bin/6to5-node",
"6to5-runtime": "./bin/6to5-runtime"
},
"browser": {
"./lib/6to5/index.js": "./lib/6to5/browser.js",
@@ -42,13 +43,13 @@
"detect-indent": "3.0.0",
"estraverse": "1.9.1",
"esutils": "1.1.6",
"esvalid": "1.1.0",
"fs-readdir-recursive": "0.1.0",
"globals": "^5.1.0",
"js-tokenizer": "1.3.3",
"lodash": "3.0.0",
"output-file-sync": "1.1.0",
"private": "0.1.6",
"regenerator-6to5": "0.8.9-7",
"regenerator-6to5": "0.8.9-8",
"regexpu": "1.1.0",
"roadrunner": "1.0.4",
"source-map": "0.1.43",
@@ -59,6 +60,7 @@
"devDependencies": {
"browserify": "8.1.1",
"chai": "1.10.0",
"esvalid": "1.1.0",
"istanbul": "0.3.5",
"jscs": "1.10.0",
"jshint": "2.6.0",

View File

@@ -1,7 +1,7 @@
{
"name": "6to5-runtime",
"description": "6to5 selfContained runtime",
"version": "3.0.16",
"version": "3.3.0",
"repository": "6to5/6to5",
"author": "Sebastian McKenzie <sebmck@gmail.com>"
}

View File

@@ -1,11 +1,10 @@
"use strict";
var transform = require("../lib/6to5/transformation/transform");
var File = require("../lib/6to5/file");
var util = require("../lib/6to5/util");
var fs = require("fs");
var t = require("../lib/6to5/types");
var _ = require("lodash");
var buildHelpers = require("../lib/6to5/build-helpers");
var transform = require("../lib/6to5/transformation");
var fs = require("fs");
var t = require("../lib/6to5/types");
var _ = require("lodash");
var relative = function (filename) {
return __dirname + "/6to5-runtime/" + filename;
@@ -31,23 +30,18 @@ var updatePackage = function () {
writeFile("package.json", JSON.stringify(pkg, null, 2));
};
var buildHelpers = function () {
var buildHelpers2 = function () {
var body = [];
var tree = t.program(body);
_.each(File.helpers, function (name) {
var key = t.identifier(t.toIdentifier(name));
body.push(t.expressionStatement(
t.assignmentExpression("=", t.memberExpression(t.identifier("exports"), key), util.template(name))
));
});
buildHelpers(body, t.identifier("exports"));
return transform.fromAst(tree, null, {
optional: ["selfContained"]
}).code;
};
writeFile("helpers.js", buildHelpers());
writeFile("helpers.js", buildHelpers2());
writeFile("core-js.js", readFile("core-js/library"));
writeFile("regenerator/index.js", readFile("regenerator-6to5/runtime-module"));
writeFile("regenerator/runtime.js", readFile("regenerator-6to5/runtime"));

View File

@@ -1,3 +1,4 @@
var util = require("../lib/6to5/util");
var path = require("path");
var fs = require("fs");
var _ = require("lodash");
@@ -17,6 +18,13 @@ var readFile = exports.readFile = function (filename) {
}
};
exports.assertVendor = function (name) {
if (!fs.existsSync(__dirname + "/../vendor/" + name)) {
console.error("No vendor/" + name + " - run `make bootstrap`");
process.exit(1);
}
};
exports.get = function (entryName, entryLoc) {
if (exports.cache[entryName]) return exports.cache[entryName];
@@ -34,8 +42,8 @@ exports.get = function (entryName, entryLoc) {
};
suites.push(suite);
var suiteOptsLoc = suite.filename + "/options.json";
if (fs.existsSync(suiteOptsLoc)) suite.options = require(suiteOptsLoc);
var suiteOptsLoc = util.resolve(suite.filename + "/options");
if (suiteOptsLoc) suite.options = require(suiteOptsLoc);
if (fs.statSync(suite.filename).isFile()) {
push(suiteName, suite.filename);
@@ -71,8 +79,8 @@ exports.get = function (entryName, entryLoc) {
sourceMapName: expectLocAlias
}, _.cloneDeep(suite.options));
var taskOptsLoc = taskDir + "/options.json";
if (fs.existsSync(taskOptsLoc)) _.merge(taskOpts, require(taskOptsLoc));
var taskOptsLoc = util.resolve(taskDir + "/options");
if (taskOptsLoc) _.merge(taskOpts, require(taskOptsLoc));
var test = {
title: humanise(taskName, true),

View File

@@ -1,5 +1,5 @@
var genHelpers = require("./_generator-helpers");
var transform = require("../lib/6to5/transformation/transform");
var transform = require("../lib/6to5/transformation");
var sourceMap = require("source-map");
var codeFrame = require("../lib/6to5/helpers/code-frame");
var esvalid = require("esvalid");
@@ -125,12 +125,14 @@ var run = function (task, done) {
module.exports = function (suiteOpts, taskOpts, dynamicOpts) {
taskOpts = taskOpts || {};
require("../register")(taskOpts);
_.each(helper.get(suiteOpts.name, suiteOpts.loc), function (testSuite) {
if (_.contains(suiteOpts.ignoreSuites, testSuite.title)) return;
suite(suiteOpts.name + "/" + testSuite.title, function () {
setup(function () {
require("../register")(taskOpts);
});
_.each(testSuite.tests, function (task) {
if (_.contains(suiteOpts.ignoreTasks, task.title) || _.contains(suiteOpts.ignoreTasks, testSuite.title + "/" + task.title)) return;

View File

@@ -1,4 +1,4 @@
var transform = require("../lib/6to5/transformation/transform");
var transform = require("../lib/6to5/transformation");
var assert = require("assert");
var File = require("../lib/6to5/file");

140
test/detection.js Normal file
View File

@@ -0,0 +1,140 @@
var detect = require("../lib/6to5/detection");
var assert = require("assert");
var util = require("../lib/6to5/util");
suite("detection", function () {
var checkSyntax = function (code, name) {
var ast = util.parse({
experimental: true
}, code);
assert.ok(detect(ast).syntax[name]);
};
test("es5.properties.mutators", function () {
checkSyntax("var obj = { get foo() {} };", "es5.properties.mutators");
checkSyntax("var obj = { set foo() {} };", "es5.properties.mutators");
});
test("es6.exponentation", function () {
checkSyntax("x ** 2;", "es6.exponentation");
checkSyntax("x **= 2;", "es6.exponentation");
});
test("es6.blockScoping", function () {
checkSyntax("let foo;", "es6.blockScoping");
checkSyntax("let foo = bar;", "es6.blockScoping");
checkSyntax("const foo = bar;", "es6.blockScoping");
});
test("es6.constants", function () {
checkSyntax("const foo = bar;", "es6.constants");
});
test("es6.properties.shorthand", function () {
checkSyntax("var obj = { foo };", "es6.properties.shorthand");
checkSyntax("var obj = { foo };", "es6.properties.shorthand");
});
test("es6.properties.computed", function () {
checkSyntax("var obj = { [foo]: bar };", "es6.properties.computed");
checkSyntax("var obj = { ['foo']: bar };", "es6.properties.computed");
});
test("es6.parameters.default", function () {
checkSyntax("var obj = (foo = bar) => {};", "es6.parameters.default");
checkSyntax("var obj = function (foo = bar) {};", "es6.parameters.default");
checkSyntax("function foo(foo = bar) {}", "es6.parameters.default");
});
test("es6.arrowFunctions", function () {
checkSyntax("var foo = x => x;", "es6.arrowFunctions");
checkSyntax("var foo = x => { return x * x };", "es6.arrowFunctions");
checkSyntax("var foo = (x) => x;", "es6.arrowFunctions");
checkSyntax("var foo = (a, b) => { return a * b };", "es6.arrowFunctions");
});
test("es6.classes", function () {
checkSyntax("class Foo {}", "es6.classes");
checkSyntax("var Foo = class {};", "es6.classes");
});
test("es6.forOf", function () {
checkSyntax("for (var val of foo);", "es6.forOf");
checkSyntax("for (val of foo);", "es6.forOf");
});
test("es6.modules", function () {
checkSyntax("import 'foo';", "es6.modules");
checkSyntax("import foo from 'foo';", "es6.modules");
checkSyntax("import * as foo from 'foo';", "es6.modules");
checkSyntax("import { foo } from 'foo';", "es6.modules");
checkSyntax("export { foo } from 'foo';", "es6.modules");
checkSyntax("export var foo = 5;", "es6.modules");
checkSyntax("export class Foo {}", "es6.modules");
checkSyntax("export function foo() {}", "es6.modules");
checkSyntax("export default class Foo {}", "es6.modules");
checkSyntax("export default function foo() {}", "es6.modules");
});
test("es6.destructuring", function () {
checkSyntax("[a, b] = [];", "es6.destructuring");
checkSyntax("var [a, b] = [];", "es6.destructuring");
checkSyntax("({ a, b }) = {};", "es6.destructuring");
checkSyntax("var { a, b } = {};", "es6.destructuring");
checkSyntax("function foo(foo = bar) {}", "es6.destructuring");
});
test("es6.parameters.rest", function () {
checkSyntax("function foo(...items) {}", "es6.parameters.rest");
checkSyntax("var foo = (...items) => {}", "es6.parameters.rest");
});
test("es6.spread", function () {
checkSyntax("new Foo(...items);", "es6.spread");
checkSyntax("foo(...items);", "es6.spread");
checkSyntax("[...items];", "es6.spread");
});
test("es6.templateLiterals", function () {
checkSyntax("`foobar`;", "es6.templateLiterals");
checkSyntax("foobar`foobar`;", "es6.templateLiterals");
});
test("es6.generators", function () {
checkSyntax("function* foo() {}", "es6.generators");
checkSyntax("var foo = function* () {};", "es6.generators");
});
test("es7.asyncFunctions", function () {
checkSyntax("async function foo() {}", "es7.asyncFunctions");
checkSyntax("var foo = async function() {};", "es7.asyncFunctions");
checkSyntax("var foo = async () => {};", "es7.asyncFunctions");
});
test("es7.comprehensions", function () {
checkSyntax("[for (i of test) i]", "es7.comprehensions");
checkSyntax("(for (i of test) i)", "es7.comprehensions");
});
test("es7.objectSpread", function () {
checkSyntax("var foo = { ...bar };", "es7.objectSpread");
});
test("es7.abstractReferences", function () {
checkSyntax("class Foo { private A; }", "es7.abstractReferences");
checkSyntax("foo::bar();", "es7.abstractReferences");
checkSyntax("delete foo::bar;", "es7.abstractReferences");
checkSyntax("foo::bar;", "es7.abstractReferences");
checkSyntax("foo::bar = baz;", "es7.abstractReferences");
});
test("flow", function () {
});
test("jsx", function () {
checkSyntax("<div />", "jsx");
checkSyntax("<Element />", "jsx");
});
});

View File

@@ -2,6 +2,14 @@ class Base {
get sound() {
return 'I am a ' + this.type + '.';
}
get name() {
return this._name;
}
set name(val) {
this._name = val;
}
}
class Animal extends Base {}
@@ -12,6 +20,18 @@ class Cat extends Animal {
get sound() {
return super.sound + ' MEOW!';
}
get name() {
return super.name;
}
set name(val) {
super.name = val + ' Cat';
}
}
assert.equal(new Cat().sound, 'I am a cat. MEOW!');
var cat = new Cat();
assert.equal(cat.sound, 'I am a cat. MEOW!');
cat.name = 'Nyan';
assert.equal(cat.name, 'Nyan Cat');

View File

@@ -0,0 +1,3 @@
export { foo } from "foo-export-named";
import foo from "foo-import-default";
import "foo-import-bare";

View File

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

View File

@@ -0,0 +1,5 @@
exports.blacklist = ["es6.modules"];
exports.resolveModuleSource = function (originalSource) {
return "resolved/" + originalSource;
};

View File

@@ -12,7 +12,6 @@ var Foo = (function () {
value: _asyncToGenerator(function* () {
var wat = yield bar();
}),
enumerable: false,
writable: true,
configurable: true
}

View File

@@ -12,7 +12,6 @@ var Foo = (function () {
value: _bluebird.coroutine(function* () {
var wat = yield bar();
}),
enumerable: false,
writable: true,
configurable: true
}

View File

@@ -0,0 +1,15 @@
var heh = [];
var nums = [1, 2, 3];
loop1:
for (let i in nums) {
let num = nums[i];
heh.push(x => x * num);
if (num >= 2) {
break loop1;
}
}
assert.equal(heh.length, 2);
assert.equal(heh[0](2), 2);
assert.equal(heh[1](4), 8);

View File

@@ -0,0 +1,4 @@
for (let i = 0, x = 2; i < 5; i++);
assert.ok(typeof i === "undefined");
assert.ok(typeof x === "undefined");

View File

@@ -0,0 +1,22 @@
(function () {
var stack = [];
loop1:
for (let j = 0; j < 10; j++) {
for (let i = 0; i < 10; i++) {
stack.push(() => [i, j]);
break;
}
}
assert.deepEqual(stack[0](), [0, 0]);
assert.deepEqual(stack[1](), [0, 1]);
assert.deepEqual(stack[2](), [0, 2]);
assert.deepEqual(stack[3](), [0, 3]);
assert.deepEqual(stack[4](), [0, 4]);
assert.deepEqual(stack[5](), [0, 5]);
assert.deepEqual(stack[6](), [0, 6]);
assert.deepEqual(stack[7](), [0, 7]);
assert.deepEqual(stack[8](), [0, 8]);
assert.deepEqual(stack[9](), [0, 9]);
})();

View File

@@ -0,0 +1,25 @@
(function () {
var stack = [];
loop1:
for (let j = 0; j < 10; j++) {
loop2:
for (let i = 0; i < 10; i++) {
for (let x = 0; x < 10; x++) {
stack.push(() => [j, i, x]);
continue loop2;
}
}
}
assert.deepEqual(stack[0](), [0, 0, 0]);
assert.deepEqual(stack[1](), [0, 1, 0]);
assert.deepEqual(stack[2](), [0, 2, 0]);
assert.deepEqual(stack[3](), [0, 3, 0]);
assert.deepEqual(stack[4](), [0, 4, 0]);
assert.deepEqual(stack[5](), [0, 5, 0]);
assert.deepEqual(stack[6](), [0, 6, 0]);
assert.deepEqual(stack[7](), [0, 7, 0]);
assert.deepEqual(stack[8](), [0, 8, 0]);
assert.deepEqual(stack[9](), [0, 9, 0]);
})();

View File

@@ -0,0 +1,14 @@
(function () {
var stack = [];
loop1:
for (let j = 0; j < 10; j++) {
for (let i = 0; i < 10; i++) {
stack.push(() => [i, j]);
break loop1;
}
}
assert.deepEqual(stack.length, 1);
assert.deepEqual(stack[0](), [0, 0]);
})();

View File

@@ -0,0 +1,22 @@
(function () {
var stack = [];
loop1:
for (let j = 0; j < 10; j++) {
for (let i = 0; i < 10; i++) {
stack.push(() => [i, j]);
continue loop1;
}
}
assert.deepEqual(stack[0](), [0, 0]);
assert.deepEqual(stack[1](), [0, 1]);
assert.deepEqual(stack[2](), [0, 2]);
assert.deepEqual(stack[3](), [0, 3]);
assert.deepEqual(stack[4](), [0, 4]);
assert.deepEqual(stack[5](), [0, 5]);
assert.deepEqual(stack[6](), [0, 6]);
assert.deepEqual(stack[7](), [0, 7]);
assert.deepEqual(stack[8](), [0, 8]);
assert.deepEqual(stack[9](), [0, 9]);
})();

View File

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

View File

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

View File

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

View File

@@ -31,7 +31,6 @@ var Test = (function (Foo) {
_get(Object.getPrototypeOf(Test), "foo", this).apply(this, arguments);
(_get2 = _get(Object.getPrototypeOf(Test), "foo", this)).call.apply(_get2, [this, "test"].concat(_slice.call(arguments)));
},
enumerable: false,
writable: true,
configurable: true
}
@@ -43,7 +42,6 @@ var Test = (function (Foo) {
_get(Object.getPrototypeOf(Test.prototype), "test", this).apply(this, arguments);
(_get2 = _get(Object.getPrototypeOf(Test.prototype), "test", this)).call.apply(_get2, [this, "test"].concat(_slice.call(arguments)));
},
enumerable: false,
writable: true,
configurable: true
}

View File

@@ -19,7 +19,6 @@ var Test = (function (Foo) {
value: function test() {
return _get(Object.getPrototypeOf(Test), "wow", this).call(this);
},
enumerable: false,
writable: true,
configurable: true
}

View File

@@ -10,7 +10,6 @@ var Test = (function () {
get: function () {
return 5 + 5;
},
enumerable: false,
set: function (val) {
this._test = val;
},

View File

@@ -10,7 +10,6 @@ var Test = (function () {
get: function () {
return 5 + 5;
},
enumerable: false,
configurable: true
}
});

View File

@@ -10,7 +10,6 @@ var Test = (function () {
value: function test() {
return 5 + 5;
},
enumerable: false,
writable: true,
configurable: true
}

View File

@@ -10,7 +10,6 @@ var Test = (function () {
set: function (val) {
this._test = val;
},
enumerable: false,
configurable: true
}
});

View File

@@ -18,7 +18,6 @@ var BaseView = (function () {
value: function foo() {
this.autoRender = true;
},
enumerable: false,
writable: true,
configurable: true
}

View File

@@ -8,13 +8,11 @@ var A = (function () {
_prototypeProperties(A, {
a: {
value: function a() {},
enumerable: false,
writable: true,
configurable: true
},
b: {
get: function () {},
enumerable: false,
set: function (b) {},
configurable: true
}

View File

@@ -1,11 +0,0 @@
if (true) {
const x = 1;
switch (x) {
case 1: {
function y() {
assert(x, 1);
};
break;
}
}
}

View File

@@ -0,0 +1,3 @@
var foo = function (...[a, b]) {
};

View File

@@ -0,0 +1,14 @@
"use strict";
var _slicedToArray = function (arr, i) { if (Array.isArray(arr)) { return arr; } else { var _arr = []; for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { _arr.push(_step.value); if (i && _arr.length === i) break; } return _arr; } };
var foo = function () {
for (var _len = arguments.length, _ref = Array(_len), _key = 0; _key < _len; _key++) {
_ref[_key] = arguments[_key];
}
var _ref2 = _slicedToArray(_ref, 2);
var a = _ref2[0];
var b = _ref2[1];
};

View File

@@ -12,14 +12,12 @@ var Foo = (function () {
get: function () {
return _defineProperty(this, "bar", complex()).bar;
},
enumerable: false,
configurable: true
}
}, bar, {
get: function () {
return _defineProperty(this, bar, complex())[bar];
},
enumerable: false,
configurable: true
}));

View File

@@ -0,0 +1,7 @@
var foo = function () {
return () => <this />;
};
var bar = function () {
return () => <this.foo />;
};

View File

@@ -0,0 +1,13 @@
var foo = function () {
var _this = this;
return function () {
return React.createElement(_this, null);
};
};
var bar = function () {
var _this = this;
return function () {
return React.createElement(_this.foo, null);
};
};

View File

@@ -0,0 +1,5 @@
function* foo({ bar }) {
return bar;
}
assert(foo({ bar: "bar" }).next().value, "bar");

View File

@@ -1,5 +1,13 @@
function* foo({ bar }) {
function* foo() {
var { bar } = { bar: "bar" };
return bar;
}
assert(foo({ bar: "bar" }).next().value, "bar");
assert.equal(foo().next().value, "bar");
function* foo2({ bar = 0 }) {
return bar;
}
assert.equal(foo2({ bar: undefined }).next().value, 0);
assert.equal(foo2({ bar: 3 }).next().value, 3);

View File

@@ -0,0 +1 @@
import foo from "foo";

View File

@@ -0,0 +1,6 @@
define(["exports", "foo", "6to5-runtime/helpers"], function (exports, _foo, _to5RuntimeHelpers) {
"use strict";
var _to5Helpers = _to5RuntimeHelpers;
var foo = _to5Helpers.interopRequire(_foo);
});

View File

@@ -0,0 +1 @@
import foo from "foo";

View File

@@ -0,0 +1,5 @@
"use strict";
var _to5Helpers = require("6to5-runtime/helpers");
var foo = _to5Helpers.interopRequire(require("foo"));

View File

@@ -0,0 +1 @@
foo(...bar);

View File

@@ -0,0 +1,13 @@
System.register(["6to5-runtime/helpers"], function (_export) {
"use strict";
var _to5Helpers;
return {
setters: [function (_to5RuntimeHelpers) {
_to5Helpers = _to5RuntimeHelpers;
}],
execute: function () {
foo.apply(undefined, _to5Helpers.toArray(bar));
}
};
});

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