Compare commits

...

94 Commits

Author SHA1 Message Date
Sebastian McKenzie
2845c1a894 v2.6.0 2015-01-06 17:44:13 +11:00
Sebastian McKenzie
ed51728aba remove unused variable 2015-01-06 17:43:26 +11:00
Sebastian McKenzie
4c8f4121f0 add 2.6.0 changelog 2015-01-06 17:41:57 +11:00
Sebastian McKenzie
b9e4340700 better use strict handling inside of modules 2015-01-06 17:32:00 +11:00
Sebastian McKenzie
4c9e39afa1 replace slice with a loop in rest parameters 2015-01-06 17:05:52 +11:00
Sebastian McKenzie
7439247095 change spread call expression context from null to undefined 2015-01-06 16:45:39 +11:00
Sebastian McKenzie
254424ced5 add npm install to make bootstrap 2015-01-06 12:17:39 +11:00
Sebastian McKenzie
4fc6823ece no ast check on api tests 2015-01-06 12:17:29 +11:00
Sebastian McKenzie
d531c8aa4c add expressionStatement around system module wildcard exports 2015-01-06 12:17:20 +11:00
Sebastian McKenzie
fc59f1ff46 add closure around let scoping return tests 2015-01-06 12:16:34 +11:00
Sebastian McKenzie
7c7cd6f9b8 use thisExpression instead of identifier("this") 2015-01-06 12:08:53 +11:00
Sebastian McKenzie
e3174d5a39 add esvalid validation to transformation tests 2015-01-06 12:08:40 +11:00
Sebastian McKenzie
2558a5e12e better wildcard imports and exports - fixes #224 2015-01-06 11:48:23 +11:00
Sebastian McKenzie
7526ae5486 fix register require in transformation helper 2015-01-06 10:45:10 +11:00
Sebastian McKenzie
811fcf7e1b upgrade acorn-6to5 2015-01-06 10:44:13 +11:00
Sebastian McKenzie
62818d468e Merge branch 'traceur' 2015-01-06 10:40:42 +11:00
Sebastian McKenzie
a88bd69e30 justify disabled traceur tests 2015-01-06 10:39:56 +11:00
Sebastian McKenzie
8164bb17ce don't use interopRequire if noInteropRequire is set for default module formatter 2015-01-06 10:39:47 +11:00
Sebastian McKenzie
3ec97fc86d only check if a function is a declaration in common module hoisting 2015-01-06 10:39:18 +11:00
Sebastian McKenzie
b38a00d70e add destructuring defaults #230 2015-01-06 10:38:55 +11:00
Sebastian McKenzie
1b85607d7d add ability to assert just an error instead of an error message in tests 2015-01-06 10:38:28 +11:00
Sebastian McKenzie
fd6704ac25 update optional bluebird coroutine test to reflect new addImport 2015-01-06 10:38:11 +11:00
Sebastian McKenzie
9c527f9d9c make regenerator test use the ALL environment var 2015-01-06 10:37:40 +11:00
Sebastian McKenzie
6cf318d60f add updated interop modules to tests 2015-01-06 10:37:11 +11:00
Sebastian McKenzie
64f9f4dff5 only check declarations in let scoping reference check 2015-01-06 10:36:49 +11:00
Sebastian McKenzie
145413dbfd Merge pull request #396 from caspervonb/master
Add .es to register extensions
2015-01-05 20:55:36 +11:00
Casper Beyer
8c58e0f14c Add .es extension to util.canCompile 2015-01-05 16:43:00 +08:00
Casper Beyer
d62914e41c Amend require documentation to include '.es' extension 2015-01-05 16:35:01 +08:00
Casper Beyer
85db67edf4 Add .es to register extensions
.es is a known ecmascript file extension and should be handled by the loader
See RFC 4329, 8.2.
2015-01-05 16:10:41 +08:00
Sebastian McKenzie
348ad2e25c better dynamic imports - fixes #393 2015-01-05 12:40:12 +11:00
Sebastian McKenzie
5ce8ee6c2b add inheritance type check to tests 2015-01-05 12:39:46 +11:00
Sebastian McKenzie
98ad5d42e1 add optional typeof symbol test options 2015-01-05 12:39:12 +11:00
Sebastian McKenzie
b12734abd6 only run traceur and esnext on ALL_6TO5_TESTS environment variable 2015-01-05 12:39:01 +11:00
Sebastian McKenzie
f34907d518 add make bootstrap 2015-01-05 12:38:34 +11:00
Sebastian McKenzie
3bd6ec20c1 remove regenerator tests and git submodule regenerator 2015-01-05 12:38:26 +11:00
Sebastian McKenzie
b8d4479333 fix linting error 2015-01-05 10:24:23 +11:00
Sebastian McKenzie
ed833be34a force computed property on number literal property 2015-01-05 10:23:30 +11:00
Sebastian McKenzie
16024242b0 add type check to inherits template 2015-01-05 10:23:06 +11:00
Sebastian McKenzie
77add8704e alias hidden properties onto it's transformer instance 2015-01-05 10:22:27 +11:00
Sebastian McKenzie
9fd1ec0596 more reliable toValidIdentifier checking, including reserved words 2015-01-05 10:22:06 +11:00
Sebastian McKenzie
90ce4e93ed don't break let reference checking on loops in let scoping 2015-01-05 10:21:50 +11:00
Sebastian McKenzie
cf7b9234c1 make typeofSymbol transformer optional 2015-01-05 10:21:32 +11:00
Sebastian McKenzie
f85eeeb93c fix blockHoist and declarations transformers unneccesarily unshifting use strict statements 2015-01-05 10:21:24 +11:00
Sebastian McKenzie
45d0eea842 fix native type constructor spread - closes #373 2015-01-05 10:20:36 +11:00
Sebastian McKenzie
b0c9d3daa4 Merge branch 'master' into traceur 2015-01-05 10:19:41 +11:00
Sebastian McKenzie
3f152bfc3f upgrade core-js from 0.3.3 to 0.40 and regenerator from 0.8.2 to 0.8.3 2015-01-05 10:19:01 +11:00
Sebastian McKenzie
ffbfa5281b move esnext tests into their own fixtures folder 2015-01-05 10:18:42 +11:00
Sebastian McKenzie
7f87ca0d43 move traceur test suite to a git submodule 2015-01-05 10:18:30 +11:00
Sebastian McKenzie
a8fad4b958 add traceur gits ubmodule 2015-01-05 10:17:23 +11:00
Sebastian McKenzie
945ea145e7 remove esnext from differences table 2015-01-05 10:17:09 +11:00
Sebastian McKenzie
4f10bcedda Merge pull request #392 from thejameskyle/changlog-tags
Add tags to top of changelog
2015-01-05 10:15:36 +11:00
James Kyle
601b3d584f Add tags to top of changelog 2015-01-04 14:41:17 -08:00
Sebastian McKenzie
42878f85fe Merge pull request #391 from thejameskyle/extend-null-check
Make parent constructor check explicit when extending from null
2015-01-05 09:14:33 +11:00
James Kyle
3b4c9c415e Make parent constructor check explicit when extending from null - fixes #386 2015-01-04 13:45:13 -08:00
Sebastian McKenzie
7345899343 Merge pull request #389 from caspervonb/master
Make build target the default target
2015-01-05 03:01:32 +11:00
Casper Beyer
316102ab14 Make build target the default target
The top target is implicitly the default target, having this as *clean*
is rather unothodox, usually it would be the executable or library target.
2015-01-04 23:53:28 +08:00
Sebastian McKenzie
4c2b85deec better NewExpression paren insertion 2015-01-05 01:06:41 +11:00
Sebastian McKenzie
108784db20 add typeof and interop-require-wildcard helpers 2015-01-05 01:06:28 +11:00
Sebastian McKenzie
a3b30bae7a better traceur test api 2015-01-05 01:06:16 +11:00
Sebastian McKenzie
6420954c53 remove traceur tests 2015-01-05 01:06:07 +11:00
Sebastian McKenzie
a6fda01fa0 Merge branch 'master' into traceur
Conflicts:
	package.json
2015-01-05 00:53:59 +11:00
Sebastian McKenzie
655cc8fcb9 v2.5.0 2015-01-05 00:17:35 +11:00
Sebastian McKenzie
97a504bbef 2.5.0 changelog 2015-01-05 00:16:39 +11:00
Sebastian McKenzie
bf3443962b disable failing esnext tests 2015-01-05 00:15:46 +11:00
Sebastian McKenzie
a4394494ef remove noDuplicateProperties test 2015-01-05 00:15:37 +11:00
Sebastian McKenzie
2b333de81f add basic support for assignment patterns 2015-01-05 00:07:50 +11:00
Sebastian McKenzie
b81f824b7e normalise wildcard import into a default object 2015-01-05 00:07:22 +11:00
Sebastian McKenzie
9bfb8c440a add optional typeof symbol transformer 2015-01-05 00:06:57 +11:00
Sebastian McKenzie
9a6c13a6a4 Merge branch 'esnext'
Conflicts:
	package.json
2015-01-05 00:03:53 +11:00
Sebastian McKenzie
ac8d77fb45 upgrade acorn-6to5 2015-01-04 21:14:59 +11:00
Sebastian McKenzie
09c88238e1 upgrade acorn-6to5 2015-01-04 20:37:14 +11:00
Sebastian McKenzie
103b619364 remove arity traceur test check 2015-01-04 20:36:35 +11:00
Sebastian McKenzie
c8a404fb72 Merge branch 'master' into traceur 2015-01-04 20:26:41 +11:00
Sebastian McKenzie
05669204dd fix generation expression comment tests 2015-01-04 20:26:07 +11:00
Sebastian McKenzie
38e6abec02 Merge branch 'master' into traceur 2015-01-04 20:23:37 +11:00
Sebastian McKenzie
1abef2c1e2 more intelligent parens wrapping of no line terminator expressions - fixes #376, reference #349 2015-01-04 20:22:24 +11:00
Sebastian McKenzie
cc6678361a comment out arity check 2015-01-04 20:20:03 +11:00
Sebastian McKenzie
2587694d44 Merge branch 'master' into traceur
Conflicts:
	package.json
2015-01-04 19:52:52 +11:00
Sebastian McKenzie
6a35bdb42b add traceur test suite 2015-01-04 19:40:09 +11:00
Sebastian McKenzie
18813f26bb Merge branch 'master' into esnext 2015-01-04 15:32:41 +11:00
Sebastian McKenzie
ccabb91f69 add back deleted object-define-properties-closure template 2015-01-04 15:30:59 +11:00
Sebastian McKenzie
35fda899a8 remove spec-no-duplicate-properties transformer 2015-01-04 15:30:40 +11:00
Sebastian McKenzie
9a2fd22e91 add newline to esnext super change proto test 2015-01-04 08:35:28 +11:00
Sebastian McKenzie
cbcad22d81 update default parameters transformer to use var a = arguments[0] === undefined ? 1 : arguments[0]; instead of if (a === undefined) a = 1; 2015-01-04 08:35:14 +11:00
Sebastian McKenzie
4d5861cfdc remove invalid strict-mode es6 next class test 2015-01-04 08:34:25 +11:00
Sebastian McKenzie
c578db7ae8 upgrade acorn-6to5 2015-01-04 08:34:14 +11:00
Sebastian McKenzie
dea73b7186 change code assertion to 6to5 output 2015-01-04 08:01:29 +11:00
Sebastian McKenzie
4506e39cf5 add toString key to instance keys as methods are enumerable 2015-01-04 08:01:08 +11:00
Sebastian McKenzie
7ab6df093b use Symbol.iterator instead of @@iterator 2015-01-04 08:00:49 +11:00
Sebastian McKenzie
22eeae1a93 use assert instead of expect 2015-01-04 08:00:40 +11:00
Sebastian McKenzie
a645ae0583 contextLiteral fallback in es6-spread transformer 2015-01-04 07:59:56 +11:00
Sebastian McKenzie
7f4efecb7d support for CallExpression in Scope.prototype.generateUidBasedOnNode 2015-01-04 07:59:43 +11:00
Sebastian McKenzie
0c0f40d14a only automatically assume test is exec if it has a js extension 2015-01-04 07:58:49 +11:00
Sebastian McKenzie
cb54c11d84 add esnext tests 2015-01-04 07:39:11 +11:00
316 changed files with 1809 additions and 2533 deletions

6
.gitmodules vendored Normal file
View File

@@ -0,0 +1,6 @@
[submodule "vendor/traceur"]
path = vendor/traceur
url = https://github.com/google/traceur-compiler
[submodule "vendor/regenerator"]
path = vendor/regenerator
url = https://github.com/facebook/regenerator

View File

@@ -1,6 +1,37 @@
# Changelog
Gaps between patch versions are faulty/broken releases.
> **Tags:**
> - [New Feature]
> - [Bug Fix]
> - [Spec Compliancy]
> - [Breaking Change]
> - [Documentation]
> - [Internal]
> - [Misc]
_Note: Gaps between patch versions are faulty/broken releases._
## 2.6.0
* [Internal] Fix incorrect AST node `identifier("this")`.
* [Spec Compliancy] Add `interopRequireWildcard` around wildcard imports and exports to handle non-object exports.
* [Internal] Upgrade `acorn-6to5`.
* [New Feature] Basic destructuring defaults
* [New Feature] Add `.es` to list of supported extensions.
* [New Feature] Add optional `typeofSymbol` transformer.
* [Bug Fix] Better handling of number literal property keys.
* [Bug Fix] [Internal] Better `toIdentifier` method that handles reserved words.
* [Internal] Upgrade to `core-js` 4.0.0.
* [Internal] Upgrade to `regenerator` 0.8.3.
* [Bug Fix] Handle `NewExpression` paren insertion edegcases better.
* [Spec Compliancy] Class inheritance now has a `function` or `null` type check.
* [Misc] Move `"use strict";` to inside module bodies instead of at the top of the file.
## 2.5.0
* Remove `noDuplicateProperties` transformer.
* Better generated UIDs based on nodes.
* Default parameters now use `arguments[i]`, conditionals and variable declarations instead of using long-form if statements.
## 2.4.10

View File

@@ -6,7 +6,23 @@ MOCHA_CMD = node_modules/mocha/bin/_mocha
export NODE_ENV = test
.PHONY: clean test test-cov test-clean lint test-travis test-spec test-browser publish bench build
.PHONY: clean test test-cov test-clean lint test-travis test-spec test-browser publish bench build bootstrap
build:
mkdir -p dist
node bin/cache-templates
node $(BROWSERIFY_CMD) -e lib/6to5/polyfill.js >dist/polyfill.js
node $(UGLIFY_CMD) dist/polyfill.js >dist/polyfill.min.js
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:
rm -rf coverage templates.json test/tmp dist
@@ -45,22 +61,6 @@ test-browser:
test -n "`which open`" && open test/browser.html
build:
mkdir -p dist
node bin/cache-templates
node $(BROWSERIFY_CMD) -e lib/6to5/polyfill.js >dist/polyfill.js
node $(UGLIFY_CMD) dist/polyfill.js >dist/polyfill.min.js
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
publish:
git pull --rebase
@@ -81,3 +81,8 @@ publish:
git push --follow-tags
rm -rf templates.json browser.js runtime.js browser-polyfill.js
bootstrap:
npm install
git submodule update --init
cd vendor/regenerator; npm install

3
NOTES.md Normal file
View File

@@ -0,0 +1,3 @@
# Notes
* Wildcard exports/imports wont normalise if `export default` is a non-object.

View File

@@ -78,43 +78,43 @@ that when you turn it off and use your code in a full ES6 environment
### Features
| | 6to5 | Traceur | es6-transpiler | esnext | es6now | jstransform |
| ---------------------------- | ---- | ------- | -------------- | ------ | ------ | ----------- |
| Source maps | ✓ | ✓ | ✓ | ✓ | | ✓ |
| No compiler global pollution | ✓ | | ✓ | ✓ | | ✓ |
| Optional runtime | ✓ | | ✓ | | | ✓ |
| Browser compiler | ✓ | ✓ | | ✓ | | |
| | 6to5 | Traceur | es6-transpiler | es6now | jstransform |
| ---------------------------- | ---- | ------- | -------------- | ------ | ----------- |
| Source maps | ✓ | ✓ | ✓ | | ✓ |
| No compiler global pollution | ✓ | | ✓ | | ✓ |
| Optional runtime | ✓ | | ✓ | | ✓ |
| Browser compiler | ✓ | ✓ | | | |
### Language Support
| | 6to5 | Traceur | es6-transpiler | esnext | es6now | jstransform |
| ---------------------------- | ---- | ------- | -------------- | ------ | ------ | ----------- |
| Abstract references | ✓ | | | | | |
| Array comprehension | ✓ | ✓ | ✓ | | | |
| Arrow functions | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Async functions | ✓ | ✓ | | ✓ | | |
| Async generator functions | ✓ | ✓ | | | | |
| Classes | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Computed property names | ✓ | ✓ | ✓ | ✓ | ✓ | |
| Constants | ✓ | ✓ | ✓ | | | |
| Default parameters | ✓ | ✓ | ✓ | ✓ | ✓ | |
| Destructuring | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Exponentiation operator | ✓ | ✓ | | | | |
| Flow types | ✓ | | | | | ✓ |
| For-of | ✓ | ✓ | ✓ | ✓ | ✓ | |
| Generators | ✓ | ✓ | | ✓ | | |
| Generator comprehension | ✓ | ✓ | | | | |
| JSX | ✓ | | | | | |
| Let scoping | ✓ | ✓ | ✓ | | | |
| Modules | ✓ | ✓ | | | ✓ | |
| Object rest/spread | ✓ | | | | | ✓ |
| Property method assignment | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Property name shorthand | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Rest parameters | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| React | ✓ | | | | | |
| Spread | ✓ | ✓ | ✓ | ✓ | ✓ | |
| Template literals | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Unicode regex | ✓ | ✓ | ✓ | | | |
| | 6to5 | Traceur | es6-transpiler | es6now | jstransform |
| ---------------------------- | ---- | ------- | -------------- | ------ | ----------- |
| Abstract references | ✓ | | | | |
| Array comprehension | ✓ | ✓ | ✓ | | |
| Arrow functions | ✓ | ✓ | ✓ | ✓ | ✓ |
| Async functions | ✓ | ✓ | | | |
| Async generator functions | ✓ | ✓ | | | |
| Classes | ✓ | ✓ | ✓ | ✓ | ✓ |
| Computed property names | ✓ | ✓ | ✓ | ✓ | |
| Constants | ✓ | ✓ | ✓ | | |
| Default parameters | ✓ | ✓ | ✓ | ✓ | |
| Destructuring | ✓ | ✓ | ✓ | ✓ | ✓ |
| Exponentiation operator | ✓ | ✓ | | | |
| Flow types | ✓ | | | | ✓ |
| For-of | ✓ | ✓ | ✓ | ✓ | |
| Generators | ✓ | ✓ | | | |
| Generator comprehension | ✓ | ✓ | | | |
| JSX | ✓ | | | | |
| Let scoping | ✓ | ✓ | ✓ | | |
| Modules | ✓ | ✓ | | ✓ | |
| Object rest/spread | ✓ | | | | ✓ |
| Property method assignment | ✓ | ✓ | ✓ | ✓ | ✓ |
| Property name shorthand | ✓ | ✓ | ✓ | ✓ | ✓ |
| Rest parameters | ✓ | ✓ | ✓ | ✓ | ✓ |
| React | ✓ | | | | |
| Spread | ✓ | ✓ | ✓ | ✓ | |
| Template literals | ✓ | ✓ | ✓ | ✓ | ✓ |
| Unicode regex | ✓ | ✓ | ✓ | | |
### [Traceur](https://github.com/google/traceur-compiler)

View File

@@ -208,7 +208,7 @@ result.ast;
### Require hook
All subsequent files required by node with the extensions `.es6` and `.js` will
All subsequent files required by node with the extensions `.es6`, `.es` and `.js` will
be transformed by 6to5. The polyfill specified in [Polyfill](polyfill.md) is
also required; but this is automatically loaded when using:

View File

@@ -10,11 +10,12 @@ var t = require("./types");
var _ = require("lodash");
function File(opts) {
this.dynamicImports = [];
this.opts = File.normaliseOptions(opts);
this.transformers = this.getTransformers();
this.uids = {};
this.ast = {};
this.dynamicImports = [];
this.dynamicImportIds = {};
this.opts = File.normaliseOptions(opts);
this.transformers = this.getTransformers();
this.uids = {};
this.ast = {};
}
File.helpers = [
@@ -29,12 +30,17 @@ File.helpers = [
"object-without-properties",
"has-own",
"slice",
"bind",
"define-property",
"async-to-generator"
"async-to-generator",
"interop-require-wildcard",
"typeof",
"exports-wildcard"
];
File.excludeHelpersFromRuntime = [
"async-to-generator"
"async-to-generator",
"typeof"
];
File.normaliseOptions = function (opts) {
@@ -160,11 +166,20 @@ File.prototype.parseShebang = function (code) {
return code;
};
File.prototype.addImport = function (id, source) {
var specifiers = [t.importSpecifier(t.identifier("default"), id)];
var declar = t.importDeclaration(specifiers, t.literal(source));
declar._blockHoist = 3;
this.dynamicImports.push(declar);
File.prototype.addImport = function (source, name) {
name = name || source;
var id = this.dynamicImportIds[name];
if (!id) {
id = this.dynamicImportIds[name] = this.generateUidIdentifier(name);
var specifiers = [t.importSpecifier(t.identifier("default"), id)];
var declar = t.importDeclaration(specifiers, t.literal(source));
declar._blockHoist = 3;
this.dynamicImports.push(declar);
}
return id;
};
File.prototype.addHelper = function (name) {
@@ -273,7 +288,7 @@ File.prototype.generate = function () {
};
File.prototype.generateUid = function (name, scope) {
name = t.toIdentifier(name);
name = t.toIdentifier(name).replace(/^_+/, "");
scope = scope || this.scope;

View File

@@ -148,11 +148,11 @@ CodeGenerator.prototype.print = function (node, parent, opts) {
};
if (this[node.type]) {
var needsCommentParens = t.isExpression(node) && node.leadingComments && node.leadingComments.length;
var needsParens = needsCommentParens || n.needsParens(node, parent);
var needsNoLineTermParens = n.needsParensNoLineTerminator(node, parent);
var needsParens = needsNoLineTermParens || n.needsParens(node, parent);
if (needsParens) this.push("(");
if (needsCommentParens) this.indent();
if (needsNoLineTermParens) this.indent();
this.printLeadingComments(node, parent);
@@ -163,7 +163,7 @@ CodeGenerator.prototype.print = function (node, parent, opts) {
this[node.type](node, this.buildPrint(node), parent);
if (needsCommentParens) {
if (needsNoLineTermParens) {
this.newline();
this.dedent();
}

View File

@@ -1,5 +1,6 @@
var util = require("../../util");
var t = require("../../types");
var _ = require("lodash");
exports.UnaryExpression = function (node, print) {
var hasSpace = /[a-z]$/.test(node.operator);
@@ -86,6 +87,7 @@ exports.ExpressionStatement = function (node, print) {
exports.BinaryExpression =
exports.LogicalExpression =
exports.AssignmentPattern =
exports.AssignmentExpression = function (node, print) {
print(node.left);
this.push(" " + node.operator + " ");
@@ -102,7 +104,12 @@ exports.MemberExpression = function (node, print) {
throw new TypeError("Got a MemberExpression for MemberExpression property");
}
if (node.computed) {
var computed = node.computed;
if (t.isLiteral(node.property) && _.isNumber(node.property.value)) {
computed = true;
}
if (computed) {
this.push("[");
print(node.property);
this.push("]");

View File

@@ -61,14 +61,40 @@ Node.prototype.needsParens = function () {
if (!parent) return false;
if (t.isNewExpression(parent) && parent.callee === node) {
return t.isCallExpression(node) || _.some(node, function (val) {
if (t.isCallExpression(node)) return true;
var hasCall = _.some(node, function (val) {
return t.isCallExpression(val);
});
if (hasCall) return true;
}
return find(parens, node, parent);
};
Node.prototype.needsParensNoLineTerminator = function () {
var parent = this.parent;
var node = this.node;
if (!parent) return false;
// no comments
if (!node.leadingComments || !node.leadingComments.length) {
return false;
}
if (t.isYieldExpression(parent) || t.isAwaitExpression(parent)) {
return true;
}
if (t.isContinueStatement(parent) || t.isBreakStatement(parent) ||
t.isReturnStatement(parent) || t.isThrowStatement(parent)) {
return true;
}
return false;
};
_.each(Node.prototype, function (fn, key) {
Node[key] = function (node, parent) {
var n = new Node(node, parent);

View File

@@ -13,15 +13,30 @@ _.each([
["<", ">", "<=", ">=", "in", "instanceof"],
[">>", "<<", ">>>"],
["+", "-"],
["*", "/", "%"]
["*", "/", "%"],
["**"]
], function (tier, i) {
_.each(tier, function (op) {
PRECEDENCE[op] = i;
});
});
exports.ObjectExpression = function (node, parent) {
if (t.isExpressionStatement(parent)) {
// ({ foo: "bar" });
return true;
}
if (t.isMemberExpression(parent) && parent.object === node) {
// ({ foo: "bar" }).foo
return true;
}
return false;
};
exports.Binary = function (node, parent) {
if (t.isCallExpression(parent) && parent.callee === node) {
if ((t.isCallExpression(parent) || t.isNewExpression(parent)) && parent.callee === node) {
return true;
}

View File

@@ -12,6 +12,12 @@ var types = require("ast-types");
var def = types.Type.def;
var or = types.Type.or;
def("AssignmentPattern")
.bases("Pattern")
.build("left", "right")
.field("left", def("Pattern"))
.field("right", def("Expression"));
// Acorn - Same as ImportNamespaceSpecifier but `id` is `name`
def("ImportBatchSpecifier")
.bases("Specifier")

View File

@@ -123,7 +123,7 @@ var hookExtensions = function (_exts) {
});
};
hookExtensions([".es6", ".js"]);
hookExtensions([".es6", ".es", ".js"]);
module.exports = function (opts) {
// normalise options

View File

@@ -141,10 +141,17 @@ DefaultFormatter.prototype._exportSpecifier = function (getRef, specifier, node,
// export * from "foo";
nodes.push(this._exportsWildcard(getRef(), node));
} else {
var ref;
if (t.isSpecifierDefault(specifier.id) || this.noInteropRequire) {
ref = t.memberExpression(getRef(), specifier.id);
} else {
ref = t.callExpression(this.file.addHelper("interop-require"), [getRef()]);
}
// export { foo } from "test";
nodes.push(this._exportsAssign(
t.getSpecifierName(specifier),
t.memberExpression(getRef(), specifier.id),
ref,
node
));
}
@@ -155,9 +162,9 @@ DefaultFormatter.prototype._exportSpecifier = function (getRef, specifier, node,
};
DefaultFormatter.prototype._exportsWildcard = function (objectIdentifier) {
return util.template("exports-wildcard", {
OBJECT: objectIdentifier
}, true);
return t.expressionStatement(t.callExpression(this.file.addHelper("exports-wildcard"), [
t.callExpression(this.file.addHelper("interop-require-wildcard"), [objectIdentifier])
]));
};
DefaultFormatter.prototype._exportsAssign = function (id, init) {

View File

@@ -32,18 +32,24 @@ CommonJSFormatter.prototype.importSpecifier = function (specifier, node, nodes)
)
]));
} else {
// import foo from "foo";
var templateName = "require-assign";
// import * as bar from "foo";
if (specifier.type !== "ImportBatchSpecifier") templateName += "-key";
nodes.push(util.template(templateName, {
VARIABLE_NAME: variableName,
MODULE_NAME: node.source,
KEY: specifier.id
}));
if (specifier.type === "ImportBatchSpecifier") {
// import * as bar from "foo";
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(
variableName,
t.callExpression(this.file.addHelper("interop-require-wildcard"), [
t.callExpression(t.identifier("require"), [node.source])
])
)
]));
} else {
// import foo from "foo";
nodes.push(util.template("require-assign-key", {
VARIABLE_NAME: variableName,
MODULE_NAME: node.source,
KEY: specifier.id
}));
}
}
};
@@ -65,7 +71,7 @@ CommonJSFormatter.prototype.exportDeclaration = function (node, nodes) {
// exports = module.exports = VALUE;
if (this.hasNonDefaultExports) templateName = "exports-default-module-override";
if (t.isFunction(declar) || !this.hasNonDefaultExports) {
if (t.isFunctionDeclaration(declar) || !this.hasNonDefaultExports) {
assign = util.template(templateName, {
VALUE: this._pushStatement(declar, nodes)
}, true);

View File

@@ -1,6 +1,7 @@
module.exports = SystemFormatter;
var AMDFormatter = require("./amd");
var useStrict = require("../transformers/use-strict");
var traverse = require("../../traverse");
var util = require("../../util");
var t = require("../../types");
@@ -31,7 +32,7 @@ SystemFormatter.prototype._exportsWildcard = function (objectIdentifier, node) {
var right = objectIdentifier;
var block = t.blockStatement([
this.buildExportCall(leftIdentifier, valIdentifier)
t.expressionStatement(this.buildExportCall(leftIdentifier, valIdentifier))
]);
return this._addImportSource(t.forInStatement(left, right, block), node);
@@ -170,5 +171,9 @@ SystemFormatter.prototype.transform = function (ast) {
handlerBody.push(returnStatement);
if (useStrict._has(block)) {
handlerBody.unshift(block.body.shift());
}
program.body = [runner];
};

View File

@@ -0,0 +1 @@
Function.prototype.bind

View File

@@ -1,3 +1,3 @@
if (SUPER_NAME) {
if (SUPER_NAME !== null) {
SUPER_NAME.apply(this, arguments);
}

View File

@@ -0,0 +1 @@
var VARIABLE_NAME = ARGUMENTS[ARGUMENT_KEY] === undefined ? DEFAULT_VALUE : ARGUMENTS[ARGUMENT_KEY];

View File

@@ -1,5 +1,7 @@
(function (obj) {
for (var i in obj) {
exports[i] = obj[i];
if (exports[i] !== undefined) {
exports[i] = obj[i];
}
}
})(OBJECT);
})

View File

@@ -1 +0,0 @@
if (VARIABLE === undefined) VARIABLE = DEFAULT;

View File

@@ -1,4 +1,7 @@
(function (child, parent) {
if (typeof parent !== "function" && parent !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof parent);
}
child.prototype = Object.create(parent && parent.prototype, {
constructor: {
value: child,

View File

@@ -0,0 +1,3 @@
(function (obj) {
return obj && obj.constructor === Object ? obj : { default: obj };
})

View File

@@ -0,0 +1,5 @@
(function (KEY) {
CONTENT;
return KEY;
})(OBJECT);

View File

@@ -1 +0,0 @@
var VARIABLE_NAME = require(MODULE_NAME);

View File

@@ -0,0 +1,3 @@
for (var KEY = START; KEY < ARGUMENTS.length; KEY++) {
ARRAY[$__0] = ARGUMENTS[KEY];
}

View File

@@ -0,0 +1,3 @@
(function (obj) {
return obj && obj.constructor === Symbol ? "symbol" : typeof obj;
});

View File

@@ -42,7 +42,6 @@ _.each({
// spec
specBlockHoistFunctions: require("./transformers/spec-block-hoist-functions"),
specNoForInOfAssignment: require("./transformers/spec-no-for-in-of-assignment"),
specNoDuplicateProperties: require("./transformers/spec-no-duplicate-properties"),
// playground
methodBinding: require("./transformers/playground-method-binding"),
@@ -86,10 +85,11 @@ _.each({
_declarations: require("./transformers/_declarations"),
// wrap up
useStrict: require("./transformers/use-strict"),
_aliasFunctions: require("./transformers/_alias-functions"),
_moduleFormatter: require("./transformers/_module-formatter"),
useStrict: require("./transformers/use-strict"),
typeofSymbol: require("./transformers/optional-typeof-symbol"),
coreAliasing: require("./transformers/optional-core-aliasing"),
undefinedToVoid: require("./transformers/optional-undefined-to-void"),

View File

@@ -8,20 +8,25 @@ function Transformer(key, transformer, opts) {
this.manipulateOptions = transformer.manipulateOptions;
this.experimental = !!transformer.experimental;
this.secondPass = !!transformer.secondPass;
this.transformer = Transformer.normalise(transformer);
this.transformer = this.normalise(transformer);
this.optional = !!transformer.optional;
this.opts = opts || {};
this.key = key;
}
Transformer.normalise = function (transformer) {
Transformer.prototype.normalise = function (transformer) {
var self = this;
if (_.isFunction(transformer)) {
transformer = { ast: transformer };
}
_.each(transformer, function (fns, type) {
// hidden property
if (type[0] === "_") return;
if (type[0] === "_") {
self[type] = fns;
return;
}
if (_.isFunction(fns)) fns = { enter: fns };

View File

@@ -67,7 +67,7 @@ var go = function (getBody, node, file, scope) {
}
if (thisId) {
pushDeclaration(thisId, t.identifier("this"));
pushDeclaration(thisId, t.thisExpression());
}
};

View File

@@ -1,4 +1,5 @@
var _ = require("lodash");
var useStrict = require("./use-strict");
var _ = require("lodash");
// Priority:
//
@@ -17,13 +18,15 @@ exports.Program = {
}
if (!hasChange) return;
var nodePriorities = _.groupBy(node.body, function (bodyNode) {
var priority = bodyNode._blockHoist;
if (priority == null) priority = 1;
if (priority === true) priority = 2;
return priority;
});
useStrict._wrap(node, function () {
var nodePriorities = _.groupBy(node.body, function (bodyNode) {
var priority = bodyNode._blockHoist;
if (priority == null) priority = 1;
if (priority === true) priority = 2;
return priority;
});
node.body = _.flatten(_.values(nodePriorities).reverse());
node.body = _.flatten(_.values(nodePriorities).reverse());
});
}
};

View File

@@ -1,4 +1,5 @@
var t = require("../../types");
var useStrict = require("./use-strict");
var t = require("../../types");
exports.secondPass = true;
@@ -7,23 +8,25 @@ exports.Program = function (node) {
var kinds = {};
var kind;
for (var i in node._declarations) {
var declar = node._declarations[i];
useStrict._wrap(node, function () {
for (var i in node._declarations) {
var declar = node._declarations[i];
kind = declar.kind || "var";
var declarNode = t.variableDeclarator(declar.id, declar.init);
kind = declar.kind || "var";
var declarNode = t.variableDeclarator(declar.id, declar.init);
if (!declar.init) {
kinds[kind] = kinds[kind] || [];
kinds[kind].push(declarNode);
} else {
node.body.unshift(t.variableDeclaration(kind, [declarNode]));
if (!declar.init) {
kinds[kind] = kinds[kind] || [];
kinds[kind].push(declarNode);
} else {
node.body.unshift(t.variableDeclaration(kind, [declarNode]));
}
}
}
for (kind in kinds) {
node.body.unshift(t.variableDeclaration(kind, kinds[kind]));
}
for (kind in kinds) {
node.body.unshift(t.variableDeclaration(kind, kinds[kind]));
}
});
node._declarations = null;
};

View File

@@ -49,16 +49,29 @@ exports.Function = function (node, parent, file, scope) {
var body = [];
var argsIdentifier = t.identifier("arguments");
argsIdentifier._ignoreAliasFunctions = true;
var lastNonDefaultParam = 0;
for (i in node.defaults) {
def = node.defaults[i];
if (!def) continue;
if (!def) {
lastNonDefaultParam = +i + 1;
continue;
}
body.push(util.template("if-undefined-set-to", {
VARIABLE: node.params[i],
DEFAULT: def
body.push(util.template("default-parameter", {
VARIABLE_NAME: node.params[i],
DEFAULT_VALUE: def,
ARGUMENT_KEY: t.literal(+i),
ARGUMENTS: argsIdentifier
}, true));
}
// we need to cut off all trailing default parameters
node.params = node.params.slice(0, lastNonDefaultParam);
if (iife) {
var container = t.functionExpression(null, [], node.body, node.generator);
container._aliasFunction = true;

View File

@@ -20,11 +20,31 @@ var push = function (opts, nodes, elem, parentId) {
pushObjectPattern(opts, nodes, elem, parentId);
} else if (t.isArrayPattern(elem)) {
pushArrayPattern(opts, nodes, elem, parentId);
} else if (t.isAssignmentPattern(elem)) {
pushAssignmentPattern(opts, nodes, elem, parentId);
} else {
nodes.push(buildVariableAssign(opts, elem, parentId));
}
};
var pushAssignmentPattern = function (opts, nodes, pattern, parentId) {
var tempParentId = opts.scope.generateUidBasedOnNode(parentId, opts.file);
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(tempParentId, parentId)
]));
nodes.push(buildVariableAssign(
opts,
pattern.left,
t.conditionalExpression(
t.binaryExpression("===", tempParentId, t.identifier("undefined")),
pattern.right,
tempParentId
)
));
};
var pushObjectPattern = function (opts, nodes, pattern, parentId) {
for (var i in pattern.properties) {
var prop = pattern.properties[i];
@@ -48,6 +68,8 @@ var pushObjectPattern = function (opts, nodes, pattern, parentId) {
var value = t.callExpression(opts.file.addHelper("object-without-properties"), [parentId, keys]);
nodes.push(buildVariableAssign(opts, prop.argument, value));
} else {
if (t.isLiteral(prop.key)) prop.computed = true;
var pattern2 = prop.value;
var patternId2 = t.memberExpression(parentId, prop.key, prop.computed);
@@ -183,6 +205,24 @@ exports.Function = function (node, parent, file, scope) {
block.body = nodes.concat(block.body);
};
exports.CatchClause = function (node, parent, file, scope) {
var pattern = node.param;
if (!t.isPattern(pattern)) return;
var ref = file.generateUidIdentifier("ref", scope);
node.param = ref;
var nodes = [];
push({
kind: "var",
file: file,
scope: scope
}, nodes, pattern, ref);
node.body.body = nodes.concat(node.body.body);
};
exports.ExpressionStatement = function (node, parent, file, scope) {
var expr = node.expression;
if (expr.type !== "AssignmentExpression") return;

View File

@@ -376,7 +376,7 @@ LetScoping.prototype.getLetReferences = function () {
// this scope has a variable with the same name so it couldn't belong
// to our let scope
if (scope.hasOwn(node.name)) return;
if (scope.hasOwn(node.name, true)) return;
closurify = true;
@@ -388,8 +388,6 @@ LetScoping.prototype.getLetReferences = function () {
}
});
return this.skip();
} else if (t.isLoop(node)) {
return this.skip();
}
}

View File

@@ -1,4 +1,5 @@
var t = require("../../types");
var util = require("../../util");
var t = require("../../types");
exports.Function = function (node, parent, file) {
if (!node.rest) return;
@@ -8,15 +9,19 @@ exports.Function = function (node, parent, file) {
t.ensureBlock(node);
var call = file.toArray(t.identifier("arguments"));
var argsId = t.identifier("arguments");
argsId._ignoreAliasFunctions = true;
if (node.params.length) {
call.arguments.push(t.literal(node.params.length));
}
node.body.body.unshift(
t.variableDeclaration("var", [
t.variableDeclarator(rest, t.arrayExpression([]))
]),
call._ignoreAliasFunctions = true;
node.body.body.unshift(t.variableDeclaration("var", [
t.variableDeclarator(rest, call)
]));
util.template("rest", {
ARGUMENTS: argsId,
START: t.literal(node.params.length),
ARRAY: rest,
KEY: file.generateUidIdentifier("key")
})
);
};

View File

@@ -1,4 +1,5 @@
var t = require("../../types");
var _ = require("lodash");
var getSpreadLiteral = function (spread, file) {
return file.toArray(spread.argument);
@@ -58,7 +59,7 @@ exports.CallExpression = function (node, parent, file, scope) {
var args = node.arguments;
if (!hasSpread(args)) return;
var contextLiteral = t.literal(null);
var contextLiteral = t.identifier("undefined");
node.arguments = [];
@@ -83,6 +84,8 @@ exports.CallExpression = function (node, parent, file, scope) {
if (temp) {
callee.object = t.assignmentExpression("=", temp, callee.object);
contextLiteral = temp;
} else {
contextLiteral = callee.object;
}
t.appendToMemberExpression(callee, t.identifier("apply"));
} else {
@@ -96,7 +99,14 @@ exports.NewExpression = function (node, parent, file) {
var args = node.arguments;
if (!hasSpread(args)) return;
var nativeType = t.isIdentifier(node.callee) && _.contains(t.NATIVE_TYPE_NAMES, node.callee.name);
var nodes = build(args, file);
if (nativeType) {
nodes.unshift(t.arrayExpression([t.literal(null)]));
}
var first = nodes.shift();
if (nodes.length) {
@@ -105,5 +115,15 @@ exports.NewExpression = function (node, parent, file) {
args = first;
}
return t.callExpression(file.addHelper("apply-constructor"), [node.callee, args]);
if (nativeType) {
return t.newExpression(
t.callExpression(
t.memberExpression(file.addHelper("bind"), t.identifier("apply")),
[node.callee, args]
),
[]
);
} else {
return t.callExpression(file.addHelper("apply-constructor"), [node.callee, args]);
}
};

View File

@@ -38,8 +38,6 @@ exports._Function = function (node, callId) {
exports.Function = function (node, parent, file) {
if (!node.async || node.generator) return;
var id = t.identifier("Bluebird");
file.addImport(id, "bluebird");
var id = file.addImport("bluebird");
return exports._Function(node, t.memberExpression(id, t.identifier("coroutine")));
};

View File

@@ -12,8 +12,7 @@ exports.optional = true;
exports.ast = {
enter: function (ast, file) {
file._coreId = file.generateUidIdentifier("core");
file.addImport(file._coreId, "core-js/library");
file._coreId = file.addImport("core-js/library", "core");
},
exit: function (ast, file) {

View File

@@ -0,0 +1,9 @@
var t = require("../../types");
exports.optional = true;
exports.UnaryExpression = function (node, parent, file) {
if (node.operator === "typeof") {
return t.callExpression(file.addHelper("typeof"), [node.argument]);
}
};

View File

@@ -1,25 +0,0 @@
var t = require("../../types");
exports.ObjectExpression = function (node, parent, file) {
var keys = [];
for (var i in node.properties) {
var prop = node.properties[i];
if (prop.computed || prop.kind !== "init") continue;
var key = prop.key;
if (t.isIdentifier(key)) {
key = key.name;
} else if (t.isLiteral(key)) {
key = key.value;
} else {
continue;
}
if (keys.indexOf(key) >= 0) {
throw file.errorWithNode(prop.key, "Duplicate property key");
} else {
keys.push(key);
}
}
};

View File

@@ -1,14 +1,27 @@
var t = require("../../types");
exports._has = function (node) {
var first = node.body[0];
return t.isExpressionStatement(first) && t.isLiteral(first.expression, { value: "use strict" });
};
exports._wrap = function (node, callback) {
var useStrictNode;
if (exports._has(node)) {
useStrictNode = node.body.shift();
}
callback();
if (useStrictNode) {
node.body.unshift(useStrictNode);
}
};
exports.ast = {
exit: function (ast) {
var body = ast.program.body;
var first = body[0];
var noStrict = !first || !t.isExpressionStatement(first) || !t.isLiteral(first.expression) || first.expression.value !== "use strict";
if (noStrict) {
body.unshift(t.expressionStatement(t.literal("use strict")));
if (!exports._has(ast.program)) {
ast.program.body.unshift(t.expressionStatement(t.literal("use strict")));
}
}
};

View File

@@ -63,38 +63,29 @@ Scope.prototype.generateUidBasedOnNode = function (parent, file) {
node = parent.left;
} else if (t.isVariableDeclarator(parent)) {
node = parent.id;
}
var id = "ref";
if (t.isProperty(node)) {
} else if (t.isProperty(node)) {
node = node.key;
}
if (t.isIdentifier(node)) {
id = node.name;
} else if (t.isLiteral(node)) {
id = node.value;
} else if (t.isMemberExpression(node)) {
var parts = [];
var parts = [];
var add = function (node) {
if (t.isMemberExpression(node)) {
add(node.object);
add(node.property);
} else if (t.isIdentifier(node)) {
parts.push(node.name);
} else if (t.isLiteral(node)) {
parts.push(node.value);
}
};
var add = function (node) {
if (t.isMemberExpression(node)) {
add(node.object);
add(node.property);
} else if (t.isIdentifier(node)) {
parts.push(node.name);
} else if (t.isLiteral(node)) {
parts.push(node.value);
} else if (t.isCallExpression(node)) {
add(node.callee);
}
};
add(node);
add(node);
id = parts.join("$");
}
id = id.replace(/^_/, "");
var id = parts.join("$");
id = id.replace(/^_/, "") || "ref";
return file.generateUidIdentifier(id, this);
};
@@ -108,10 +99,6 @@ Scope.prototype.generateUidBasedOnNode = function (parent, file) {
*/
Scope.prototype.generateTempBasedOnNode = function (node, file) {
if (!t.isIdentifier(node) && !t.isMemberExpression(node)) {
throw new TypeError("Invalid node type " + JSON.stringify(node.type) + " passed to Scope.prototype.generateTempBasedOnNode");
}
if (t.isIdentifier(node) && this.has(node.name, true)) {
return null;
}

View File

@@ -39,8 +39,9 @@
"ForInStatement": ["Statement", "For", "Scope", "Loop"],
"ForStatement": ["Statement", "For", "Scope", "Loop"],
"ObjectPattern": ["Pattern"],
"ArrayPattern": ["Pattern"],
"ObjectPattern": ["Pattern"],
"ArrayPattern": ["Pattern"],
"AssignmentPattern": ["Pattern"],
"Property": ["UserWhitespacable"],
"XJSElement": ["UserWhitespacable", "Expression"],

View File

@@ -3,6 +3,10 @@ var _ = require("lodash");
var t = exports;
t.NATIVE_TYPE_NAMES = ["Array", "Object", "Number", "Boolean", "Date", "Array", "String"];
//
var addAssert = function (type, is) {
t["assert" + type] = function (node, opts) {
opts = opts || {};
@@ -214,7 +218,7 @@ t.isReferenced = function (node, parent) {
*/
t.isValidIdentifier = function (name) {
return _.isString(name) && esutils.keyword.isIdentifierName(name) && !esutils.keyword.isKeywordES6(name, true);
return _.isString(name) && esutils.keyword.isIdentifierName(name) && !esutils.keyword.isReservedWordES6(name, true);
};
/*
@@ -227,6 +231,8 @@ t.isValidIdentifier = function (name) {
t.toIdentifier = function (name) {
if (t.isIdentifier(name)) return name.name;
name = name + "";
// replace all non-valid identifiers with dashes
name = name.replace(/[^a-zA-Z0-9$_]/g, "-");
@@ -241,6 +247,10 @@ t.toIdentifier = function (name) {
// remove underscores from start of name
name = name.replace(/^\_/, "");
if (!t.isValidIdentifier(name)) {
name = "_" + name;
}
return name || '_';
};

View File

@@ -3,6 +3,7 @@
"ArrayPattern": ["elements"],
"ArrowFunctionExpression": ["params", "defaults", "rest", "body"],
"AssignmentExpression": ["left", "right"],
"AssignmentPattern": ["left", "right"],
"AwaitExpression": ["argument"],
"BinaryExpression": ["left", "right"],
"BindFunctionExpression": ["callee", "arguments"],

View File

@@ -12,7 +12,7 @@ var _ = require("lodash");
exports.inherits = util.inherits;
exports.canCompile = function (filename, altExts) {
var exts = altExts || [".js", ".jsx", ".es6"];
var exts = altExts || [".js", ".jsx", ".es6", ".es"];
var ext = path.extname(filename);
return _.contains(exts, ext);
};

View File

@@ -1,7 +1,7 @@
{
"name": "6to5",
"description": "Turn ES6 code into readable vanilla ES5 with source maps",
"version": "2.4.10",
"version": "2.6.0",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://github.com/6to5/6to5",
"repository": {
@@ -39,19 +39,20 @@
"test": "make test"
},
"dependencies": {
"acorn-6to5": "0.11.1-8",
"acorn-6to5": "0.11.1-11",
"ast-types": "~0.6.1",
"chokidar": "0.11.1",
"commander": "2.5.0",
"core-js": "^0.3.3",
"core-js": "^0.4.0",
"estraverse": "1.8.0",
"esutils": "1.1.6",
"esvalid": "^1.1.0",
"fs-readdir-recursive": "0.1.0",
"jshint": "^2.5.10",
"lodash": "2.4.1",
"mkdirp": "0.5.0",
"private": "0.1.6",
"regenerator": "^0.8.2",
"regenerator": "^0.8.3",
"regexpu": "0.3.0",
"roadrunner": "^1.0.4",
"source-map": "0.1.40",

View File

@@ -1,8 +1,9 @@
var fs = require("fs");
var _ = require("lodash");
var path = require("path");
var fs = require("fs");
var _ = require("lodash");
var humanise = function (val) {
return val.replace(/-/g, " ");
return path.basename(val, path.extname(val)).replace(/-/g, " ");
};
var readFile = exports.readFile = function (filename) {
@@ -15,11 +16,11 @@ var readFile = exports.readFile = function (filename) {
}
};
exports.get = function (entryName) {
exports.get = function (entryName, entryLoc) {
if (exports.cache[entryName]) return exports.cache[entryName];
var suites = [];
var entryLoc = __dirname + "/fixtures/" + entryName;
var entryLoc = entryLoc || __dirname + "/fixtures/" + entryName;
_.each(fs.readdirSync(entryLoc), function (suiteName) {
if (suiteName[0] === ".") return;
@@ -35,9 +36,18 @@ exports.get = function (entryName) {
var suiteOptsLoc = suite.filename + "/options.json";
if (fs.existsSync(suiteOptsLoc)) suite.options = require(suiteOptsLoc);
_.each(fs.readdirSync(suite.filename), function (taskName) {
var taskDir = suite.filename + "/" + taskName;
if (fs.statSync(taskDir).isFile()) return;
if (fs.statSync(suite.filename).isFile()) {
push(suiteName, suite.filename);
} else {
_.each(fs.readdirSync(suite.filename), function (taskName) {
var taskDir = suite.filename + "/" + taskName;
push(taskName, taskDir);
});
}
function push(taskName, taskDir) {
// tracuer error tests
if (taskName.indexOf("Error_") >= 0) return;
var actualLocAlias = suiteName + "/" + taskName + "/actual.js";
var expectLocAlias = suiteName + "/" + taskName + "/expected.js";
@@ -47,6 +57,13 @@ exports.get = function (entryName) {
var expectLoc = taskDir + "/expected.js";
var execLoc = taskDir + "/exec.js";
if (fs.statSync(taskDir).isFile()) {
var ext = path.extname(taskDir);
if (ext !== ".js" && ext !== ".module.js") return;
execLoc = taskDir;
}
var taskOpts = _.merge({
filenameRelative: expectLocAlias,
sourceFileName: actualLocAlias,
@@ -77,6 +94,18 @@ exports.get = function (entryName) {
}
};
// traceur checks
var shouldSkip = function (code) {
return code.indexOf("// Error:") >= 0 || code.indexOf("// Skip.") >= 0;
};
if (shouldSkip(test.actual.code) || shouldSkip(test.exec.code)) {
return;
} else if (test.exec.code.indexOf("// Async.") >= 0) {
//test.options.asyncExec = true;
}
suite.tests.push(test);
var sourceMappingsLoc = taskDir + "/source-mappings.json";
@@ -90,7 +119,7 @@ exports.get = function (entryName) {
test.options.sourceMap = true;
test.sourceMap = require(sourceMap);
}
});
}
});
return exports.cache[entryName] = suites;
@@ -104,4 +133,5 @@ try {
var cache = exports.cache = {};
cache.transformation = exports.get("transformation");
cache.generation = exports.get("generation");
cache.esnext = exports.get("esnext");
}

View File

@@ -0,0 +1,168 @@
var genHelpers = require("./_generator-helpers");
var transform = require("../lib/6to5/transformation/transform");
var sourceMap = require("source-map");
var esvalid = require("esvalid");
var Module = require("module");
var helper = require("./_helper");
var assert = require("assert");
var chai = require("chai");
var path = require("path");
var util = require("../lib/6to5/util");
var _ = require("lodash");
require("../lib/6to5/polyfill");
global.assertNoOwnProperties = function (obj) {
assert.equal(Object.getOwnPropertyNames(obj).length, 0);
};
global.assertArrayEquals = assert.deepEqual;
global.assert = chai.assert;
global.chai = chai;
global.genHelpers = genHelpers;
// Different Traceur generator message
chai.assert._throw = chai.assert.throw;
chai.assert.throw = function (fn, msg) {
if (msg === '"throw" on executing generator' ||
msg === '"next" on executing generator') {
msg = "Generator is already running";
} else if (msg === "Sent value to newborn generator") {
msg = /^attempt to send (.*?) to newborn generator$/;
}
return chai.assert._throw(fn, msg);
};
var run = function (task, done) {
var actual = task.actual;
var expect = task.expect;
var exec = task.exec;
var opts = task.options;
var getOpts = function (self) {
return _.merge({
filename: self.loc
}, opts);
};
var execCode = exec.code;
var result;
var checkAst = function (result) {
if (opts.noCheckAst) return;
var errors = esvalid.errors(result.ast.program);
if (errors.length) {
var msg = [];
_.each(errors, function (err) {
msg.push(err.message + " - " + JSON.stringify(err.node));
});
throw new Error(msg.join(". "));
}
};
if (execCode) {
result = transform(execCode, getOpts(exec));
checkAst(result);
execCode = result.code;
try {
var fakeRequire = function (loc) {
if (loc === "../../../src/runtime/polyfills/Number.js") {
return Number;
} else if (loc === "../../../src/runtime/polyfills/Math.js") {
return Math;
} else {
return require(path.resolve(exec.loc, "..", loc));
}
};
var fn = new Function("require", "done", execCode);
fn.call(global, fakeRequire, chai.assert, done);
} catch (err) {
err.message = exec.loc + ": " + err.message;
err.message += util.codeFrame(execCode);
throw err;
}
}
var actualCode = actual.code;
var expectCode = expect.code;
if (!execCode || actualCode) {
result = transform(actualCode, getOpts(actual));
checkAst(result);
actualCode = result.code;
chai.expect(actualCode).to.be.equal(expectCode, actual.loc + " !== " + expect.loc);
}
if (task.sourceMap) {
chai.expect(result.map).to.deep.equal(task.sourceMap);
}
if (task.sourceMappings) {
var consumer = new sourceMap.SourceMapConsumer(result.map);
_.each(task.sourceMappings, function (mapping, i) {
var expect = mapping.original;
var actual = consumer.originalPositionFor(mapping.generated);
chai.expect({ line: actual.line, column: actual.column }).to.deep.equal(expect);
});
}
};
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 () {
_.each(testSuite.tests, function (task) {
if (_.contains(suiteOpts.ignoreTasks, task.title) || _.contains(suiteOpts.ignoreTasks, testSuite.title + "/" + task.title)) return;
var runTest = function (done) {
var runTask = function () {
try {
run(task, done);
} catch (err) {
if (task.options.after) task.options.after();
throw err;
}
};
_.extend(task.options, taskOpts);
if (dynamicOpts) dynamicOpts(task.options, task);
var throwMsg = task.options.throws;
if (throwMsg) {
// internal api doesn't have this option but it's best not to pollute
// the options object with useless options
delete task.options.throws;
assert.throws(runTask, function (err) {
return throwMsg === true || err.message.indexOf(throwMsg) >= 0;
});
} else {
runTask();
}
};
var callback;
if (task.options.asyncExec) {
callback = runTest;
} else {
callback = function () {
return runTest();
};
}
test(task.title, !task.disabled && callback);
});
});
});
};

5
test/esnext.js Normal file
View File

@@ -0,0 +1,5 @@
if (!process.env.ALL_6TO5_TESTS) return;
require("./_transformation-helper")({
name: "esnext"
});

View File

@@ -0,0 +1,57 @@
function makeMultiplier() {
// `arguments` should refer to `makeMultiplier`'s arguments.
return (n) => [].slice.call(arguments).reduce((a, b) => a * b) * n;
}
function toArray() {
// Intentionally nest arrow functions to ensure `arguments` is put inside
// `toArray`'s scope.
return (() => (arguments, (() => [].slice.call(arguments)).call())).call();
}
function returnDotArguments(object) {
// Ensure `arguments` is not treated as a reference to the magic value.
return (() => object.arguments).call();
}
function returnArgumentsObject() {
// Ensure `arguments` is not treated as a reference to the magic value.
return (() => ({arguments: 1})).call();
}
function makeArgumentsReturner() {
return (() => function() {
return [].slice.call(arguments);
}).call();
}
// i.e. 2 * 3 * 4 == 24, not 16 (4 * 4)
assert.equal(
makeMultiplier(2, 3)(4),
24,
'ensure `arguments` is hoisted out to the first non-arrow scope'
);
assert.deepEqual(
toArray(1, 2, 3),
[1, 2, 3],
'ensure `arguments` is hoisted out to the first non-arrow scope'
);
assert.equal(
returnDotArguments({arguments: 1}),
1,
'member accesses with `arguments` property should not be replaced'
);
assert.deepEqual(
returnArgumentsObject(),
{arguments: 1},
'object property keys named `arguments` should not be replaced'
);
assert.deepEqual(
makeArgumentsReturner()(1, 2, 3),
[1, 2, 3],
'arguments should not be hoisted from inside non-arrow functions'
);

View File

@@ -0,0 +1,5 @@
var dynamicThisGetter = () => function () { return this; };
assert.equal(
'(' + dynamicThisGetter.toString() + ')',
'(function () {\n return function () {\n return this;\n };\n})'
);

View File

@@ -0,0 +1,2 @@
var empty = () => {};
assert.equal(empty(), undefined);

View File

@@ -0,0 +1,12 @@
var obj = {
method: function() {
return () => (this, () => this);
},
method2: function() {
return () => () => this;
}
};
assert.strictEqual(obj.method()()(), obj);
assert.strictEqual(obj.method2()()(), obj);

View File

@@ -0,0 +1,2 @@
var square = x => x * x;
assert.equal(square(4), 16);

View File

@@ -0,0 +1,2 @@
var keyMaker = val => ({ key: val });
assert.deepEqual(keyMaker(9), { key: 9 });

View File

@@ -0,0 +1,7 @@
var obj = {
method: function() {
return () => this;
}
};
assert.strictEqual(obj.method()(), obj);

View File

@@ -0,0 +1,2 @@
var odds = [0, 2, 4].map(v => v + 1);
assert.deepEqual(odds, [1, 3, 5]);

View File

@@ -0,0 +1,2 @@
var identity = x => x;
assert.equal(identity(1), 1);

View File

@@ -0,0 +1,29 @@
var Animal = class {
sayHi() {
return 'Hi, I am a '+this.type()+'.';
}
static getName() {
return 'Animal';
}
};
var Dog = class extends Animal {
type() { return 'dog'; }
sayHi() {
return super() + ' WOOF!';
}
static getName() {
return super() + '/Dog';
}
};
assert.equal(new Dog().sayHi(), 'Hi, I am a dog. WOOF!');
assert.equal(Dog.getName(), 'Animal/Dog');
var count = 0;
var Cat = class extends (function(){ count++; return Animal; })() {};
assert.equal(count, 1);

View File

@@ -0,0 +1,21 @@
class Animal {
sayHi() {
return 'I am an animal.'
}
sayOther() {
return 'WAT?!';
}
}
class Horse extends Animal {
sayHi() {
return super.sayOther();
}
sayOther() {
return 'I see dead objects.';
}
}
assert.equal(new Horse().sayHi(), 'WAT?!');

View File

@@ -0,0 +1,9 @@
var Person = (class Person {});
assert.equal(typeof Person, 'function');
assert.equal(
(function(){ return (class Person {}); })().name,
'Person'
);
assert.equal(typeof (class {}), 'function');

View File

@@ -0,0 +1,15 @@
class Animal {
sayHi() {
return 'Hi, I am a '+this.type()+'.';
}
}
class Dog extends Animal {
type() { return 'dog'; }
sayHi() {
return super() + ' WOOF!';
}
}
assert.equal(new Dog().sayHi(), 'Hi, I am a dog. WOOF!');

View File

@@ -0,0 +1,14 @@
class Multiplier {
constructor(n=1) {
this.n = n;
}
multiply(n=1) {
return n * this.n;
}
}
assert.equal(new Multiplier().n, 1);
assert.equal(new Multiplier(6).n, 6);
assert.equal(new Multiplier().multiply(), 1);
assert.equal(new Multiplier(2).multiply(3), 6);

View File

@@ -0,0 +1,10 @@
class Person {
getName() {
return this.firstName + ' ' + this.lastName;
}
}
var me = new Person();
me.firstName = 'Brian';
me.lastName = 'Donovan';
assert.equal(me.getName(), 'Brian Donovan');

View File

@@ -0,0 +1,5 @@
class Foo {
}
assert.equal(new Foo().constructor, Foo, 'Foo instances should have Foo as constructor');
assert.ok(new Foo() instanceof Foo, 'Foo instances should be `instanceof` Foo');

View File

@@ -0,0 +1,20 @@
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
var point = new Point(1, 2);
var keys = [];
for (var key in point) {
keys.push(key);
}
assert.equal(point.toString(), '(1, 2)');
assert.deepEqual(keys.sort(), ['toString', 'x', 'y']);

View File

@@ -0,0 +1,15 @@
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
class ZeroPoint extends Point {
constructor() {
super(0, 0);
}
}
assert.equal(new ZeroPoint().x, 0);
assert.equal(new ZeroPoint().y, 0);

View File

@@ -0,0 +1,4 @@
class Obj extends null {}
assert.strictEqual(Obj.toString, Function.toString);
assert.strictEqual(new Obj().toString, undefined);

View File

@@ -0,0 +1,15 @@
class Animal {
get sound() {
return 'I am a ' + this.type + '.';
}
}
class Cat extends Animal {
get type() { return 'cat'; }
get sound() {
return super.sound + ' MEOW!';
}
}
assert.equal(new Cat().sound, 'I am a cat. MEOW!');

View File

@@ -0,0 +1,28 @@
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
get name() {
return this.firstName + ' ' + this.lastName;
}
set name(name) {
var parts = name.split(' ');
this.firstName = parts[0];
this.lastName = parts[1];
}
}
var mazer = new Person('Mazer', 'Rackham');
assert.equal(mazer.name, 'Mazer Rackham');
mazer.name = 'Ender Wiggin';
assert.equal(mazer.firstName, 'Ender');
assert.equal(mazer.lastName, 'Wiggin');
var forLoopProperties = [];
for (var key in mazer) {
forLoopProperties.push(key);
}
assert.ok(forLoopProperties.indexOf('name') >= 0, 'getters/setters are enumerable');

View File

@@ -0,0 +1,9 @@
class Obj {
constructor() {
super();
}
}
assert.doesNotThrow(function() {
new Obj();
});

View File

@@ -0,0 +1,7 @@
class Tripler {
triple(n) {
return n * 3;
}
}
assert.equal(new Tripler().triple(2), 6);

View File

@@ -0,0 +1,12 @@
var value;
class Foo {
foo() {
value = 1;
}
}
var foo = new Foo();
foo.foo = function() { value = 2; };
foo.foo();
assert.equal(value, 2);

View File

@@ -0,0 +1,28 @@
class Joiner {
constructor(string) {
this.string = string;
}
join(...items) {
return items.join(this.string);
}
static join(string, ...items) {
var joiner = new this(string);
// TODO: use spread params here
return joiner.join.apply(joiner, items);
}
}
class ArrayLike {
constructor(...items) {
items.forEach(function(item, i) {
this[i] = item;
}.bind(this));
this.length = items.length;
}
}
var joiner = new Joiner(' & ');
assert.equal(joiner.join(4, 5, 6), '4 & 5 & 6');
assert.equal(new ArrayLike('a', 'b')[1], 'b');

View File

@@ -0,0 +1,12 @@
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
static get ORIGIN() {
return new this(0, 0);
}
}
assert.deepEqual(Point.ORIGIN, new Point(0, 0));

View File

@@ -0,0 +1,30 @@
class Tripler {
static triple(n=1) {
return n * 3;
}
static toString() {
return '3' + super() + '3';
}
}
class MegaTripler extends Tripler {
static triple(n=1) {
return super(n) * super(n);
}
}
var tripler = new Tripler();
assert.equal(Tripler.triple(), 3);
assert.equal(Tripler.triple(2), 6);
assert.equal(tripler.triple, undefined);
assert.equal(Tripler.toString(), '3' + Object.toString.call(Tripler) + '3');
var mega = new MegaTripler();
assert.equal(MegaTripler.triple(2), 36);
assert.equal(mega.triple, undefined);
assert.equal(MegaTripler.toString(), '3' + Object.toString.call(MegaTripler) + '3');

View File

@@ -0,0 +1,7 @@
class Person {
static set DB(value) {
assert.equal(value, 'mysql');
}
}
Person.DB = 'mysql';

View File

@@ -0,0 +1,21 @@
var log = '';
class Base {
p() { log += '[Base]'; }
}
class OtherBase {
p() { log += '[OtherBase]'; }
}
class Derived extends Base {
p() {
log += '[Derived]';
super();
Derived.prototype.__proto__ = OtherBase.prototype;
super();
}
}
new Derived().p();
assert.equal(log, '[Derived][Base][OtherBase]');

View File

@@ -0,0 +1,8 @@
var x = 'y';
var foo = {
get [x]() { return this._y; },
set [x](v) { this._y = v; }
};
assert.equal((foo.y = 10, foo.y), 10);

View File

@@ -0,0 +1,3 @@
var x = 'y';
assert.equal({[x]: function() { return 10; }}.y(), 10);
assert.equal({[x + 'y']() { return 10; }}.yy(), 10);

View File

@@ -0,0 +1,4 @@
var x = 'y';
var foo = {[x]: 10, z: {[x]: 10}};
assert.equal(foo.y + foo.z.y, 20);
assert.equal({[x]: {[x]: {[x]: 10}}}.y.y.y, 10);

View File

@@ -0,0 +1,3 @@
var x = 'y';
assert.equal({[x]: 10}.y, 10);
assert.equal({[x + 'y']: 10}.yy, 10);

View File

@@ -0,0 +1,3 @@
assert.equal((function(a){}).length, 1);
assert.equal((function(a=5){}).length, 0);
assert.equal((function(a, b, c=5){}).length, 2);

View File

@@ -0,0 +1,8 @@
function makeMultiplier(x=1) {
return (y=1) => x * y;
}
assert.equal(makeMultiplier()(), 1);
assert.equal(makeMultiplier(2)(3), 6);
assert.deepEqual([1, 2, 3].map(makeMultiplier(2)), [2, 4, 6]);
assert.deepEqual([undefined, null, 0].map(makeMultiplier(2)), [2, 0, 0]);

View File

@@ -0,0 +1,5 @@
function foo(x=5, y=6) {
return [x, y];
}
assert.deepEqual(foo(undefined, null), [5, null]);

View File

@@ -0,0 +1,11 @@
function call(fn, context=this) {
return fn.call(context);
}
var context = {a: 99};
// use the default parameter
assert.strictEqual(call.call(context, function(){ return this.a; }), 99);
// explicitly provide the default parameter value
assert.strictEqual(call(function(){ return this.a; }, context), 99);

View File

@@ -0,0 +1,4 @@
function foo(x=5) {
return x;
}
assert.equal(foo(), 5);

View File

@@ -0,0 +1,7 @@
var a = {
echo(c) {
return c;
}
};
assert.strictEqual(a.echo(1), 1);

View File

@@ -0,0 +1,9 @@
var a = {
b() {
return this;
}
};
var context = {};
assert.strictEqual(a.b(), a);
assert.strictEqual(a.b.call(context), context);

View File

@@ -0,0 +1,7 @@
var a = {
b() {
return 'c';
}
};
assert.equal(a.b.name, 'b');

View File

@@ -0,0 +1,9 @@
var b = 1;
var a = {
b() {
return b;
}
};
assert.equal(a.b(), 1);

View File

@@ -0,0 +1,10 @@
var a = {
b() {
return b;
}
};
assert.ok(
/return b/.test(a.b.toString()),
'toString contains body'
);

View File

@@ -0,0 +1,7 @@
var a = {
b() {
return 'c';
}
};
assert.equal(a.b(), 'c');

View File

@@ -0,0 +1,5 @@
var join = (joinStr, ...items) => {
return items.join(joinStr);
};
assert.deepEqual(join(' ', 'a', 'b', 'c'), 'a b c');

View File

@@ -0,0 +1,5 @@
function join(joinStr, ...items) {
return items.join(joinStr);
}
assert.deepEqual(join(' ', 'a', 'b', 'c'), 'a b c');

View File

@@ -0,0 +1,5 @@
var join = function(joinStr, ...items) {
return items.join(joinStr);
};
assert.deepEqual(join(' ', 'a', 'b', 'c'), 'a b c');

View File

@@ -0,0 +1,6 @@
function arrayOf() {
return [...arguments];
}
assert.equal(Object.prototype.toString.call(arrayOf()), '[object Array]');
assert.deepEqual(arrayOf(1, 2, 3), [1, 2, 3]);

View File

@@ -0,0 +1,3 @@
var names = ['Brian', 'Madeline'];
assert.deepEqual(['Thomas', ...names], ['Thomas', 'Brian', 'Madeline']);
assert.deepEqual([1, 2, ...[3, 4, 5]], [1, 2, 3, 4, 5]);

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