Compare commits

...

93 Commits

Author SHA1 Message Date
Sebastian McKenzie
7f425d2c6e v1.12.2 2014-11-12 12:22:03 +11:00
Sebastian McKenzie
311a8e042b add missing semicolon 2014-11-12 12:19:25 +11:00
Sebastian McKenzie
27d30329fd add more react spread tests 2014-11-12 12:18:16 +11:00
Sebastian McKenzie
12c5a3e73b add 1.12.2 changelog 2014-11-12 12:17:59 +11:00
Sebastian McKenzie
2a166a6ed1 support jsx spread attributes that aren't the first - fixes #146 2014-11-12 12:17:45 +11:00
Sebastian McKenzie
896929378e add util.trimRight method - fixes #147 2014-11-12 12:17:26 +11:00
Sebastian McKenzie
ae439d27b9 update mocha and browserify 2014-11-12 12:08:33 +11:00
Sebastian McKenzie
e22798261a change useless self references to this 2014-11-12 02:03:46 +11:00
Sebastian McKenzie
d0af8b8d0a remove numeric literals transformer 2014-11-12 02:03:25 +11:00
Sebastian McKenzie
beaa2fa540 add async functions to features 2014-11-12 02:03:11 +11:00
Sebastian McKenzie
b8cac9787e produce new MemberExpression in a CallExpression super identifier instead of mutating the property 2014-11-12 01:51:57 +11:00
Sebastian McKenzie
64f6e4a0c5 clean up classes transformer and add comments 2014-11-12 01:48:55 +11:00
Sebastian McKenzie
c4a7ac5a8b turn classes transformer into a class like let scoping 2014-11-12 01:39:35 +11:00
Sebastian McKenzie
1ed682fa76 fix up jsdoc in let-scoping transformer 2014-11-12 01:39:02 +11:00
Sebastian McKenzie
9987e7fe0e add 1.12.1 changelog 2014-11-12 01:38:50 +11:00
Sebastian McKenzie
e74c7cb0b7 turn the let scoping transformer into a class because it's quite complicated and the logic needs to be WAY more organised 2014-11-12 01:20:51 +11:00
Sebastian McKenzie
2f01e5c3af v1.12.1 2014-11-12 00:47:53 +11:00
Sebastian McKenzie
6847211971 fix up aliasFunctions transformer 2014-11-12 00:46:36 +11:00
Sebastian McKenzie
965e246259 add back opts defaults 2014-11-12 00:46:20 +11:00
Sebastian McKenzie
af59eb7d6a fix linting errors 2014-11-12 00:33:39 +11:00
Sebastian McKenzie
def4319058 stop _alias-functions transformer when hitting a function that's not an arrow function - fixes #145 2014-11-12 00:32:30 +11:00
Sebastian McKenzie
d90383b1ba generator: add Buffer class that deals with the actual code output 2014-11-12 00:27:59 +11:00
Sebastian McKenzie
1ac40ee834 remove static whitespace properties in favor of pushing to the dynamic ones 2014-11-12 00:15:31 +11:00
Sebastian McKenzie
3d5d170eff move whitespace and parentheses generation logic into separate files 2014-11-12 00:11:34 +11:00
Sebastian McKenzie
b5bdba46f1 change test-appveyor to test-spec and add test-clean method to clean up after tests 2014-11-11 23:27:01 +11:00
Sebastian McKenzie
c4e162b8e5 add rails to plugins 2014-11-11 22:27:52 +11:00
Sebastian McKenzie
98bc750b05 add mocha to plugins 2014-11-11 22:25:27 +11:00
Sebastian McKenzie
84002ed1ce add jest to plugins 2014-11-11 22:12:26 +11:00
Sebastian McKenzie
aaab2db0ec add react/jsx to readme 2014-11-11 20:06:02 +11:00
Sebastian McKenzie
7f3959444c v1.12.0 2014-11-11 19:14:52 +11:00
Sebastian McKenzie
0ba9216d6f remove unused variables in react transformer 2014-11-11 19:14:00 +11:00
Sebastian McKenzie
6dfe66bce3 add v1.12.0 to changelog 2014-11-11 19:12:44 +11:00
Sebastian McKenzie
9e08a6f084 combine jsx and react transformer so we can make the jsx output correct - #143 2014-11-11 19:11:30 +11:00
Sebastian McKenzie
b9f3f1e2a9 add comment inheriting to types.inherits 2014-11-11 19:10:41 +11:00
Sebastian McKenzie
4f18ed406c v1.11.15 2014-11-11 17:17:08 +11:00
Sebastian McKenzie
4d8e5f728a 1.11.15 2014-11-11 17:16:11 +11:00
Sebastian McKenzie
54857ceac7 fix jsx literal generator - closes #143 2014-11-11 17:15:37 +11:00
Sebastian McKenzie
5b961ea3e7 v1.11.14 2014-11-11 15:35:18 +11:00
Sebastian McKenzie
35b28cf722 more reliable jsx literal whitespace 2014-11-11 15:34:29 +11:00
Sebastian McKenzie
c5bfbf37f0 add 1.11.14 changelog 2014-11-11 15:27:23 +11:00
Sebastian McKenzie
cfee68aa67 jsx: replace all newlines and excess whitespace with spaces - fixes #142 2014-11-11 15:26:25 +11:00
Sebastian McKenzie
7d0dae129c nicer let-scoping switch 2014-11-11 15:25:37 +11:00
Sebastian McKenzie
f9d14fa2ed add runtime, property-literals and shebang tests 2014-11-11 15:25:27 +11:00
Sebastian McKenzie
11d55e661e rename let-scoping tests to traceur-let-scoping and add additional let-scoping tests 2014-11-11 15:25:13 +11:00
Sebastian McKenzie
0544e98fb1 add switch case generated node whitespace 2014-11-11 15:24:40 +11:00
Sebastian McKenzie
59d918ea67 remove unused isArray traverse.hasType 2014-11-11 15:23:52 +11:00
Sebastian McKenzie
b4232699d2 add newline after shebang 2014-11-11 15:23:31 +11:00
Sebastian McKenzie
6bd67ca660 v1.11.13 2014-11-11 14:31:06 +11:00
Sebastian McKenzie
4722c0ce56 add support for escodegen-style format options 2014-11-11 14:30:06 +11:00
Sebastian McKenzie
25a5caa0fc update regenerator-6to5 2014-11-11 14:29:32 +11:00
Sebastian McKenzie
6f05466cf5 normalise windows path separators to unix 2014-11-11 13:36:59 +11:00
Sebastian McKenzie
1ad9edb57c tests/bin: normalise stdout path separators 2014-11-11 13:33:50 +11:00
Sebastian McKenzie
c6ae33c5a2 tests: change all windows line endings to unix ones 2014-11-11 13:30:19 +11:00
Sebastian McKenzie
e0d620b1d5 remove browser-polyfill.js instead of polyfill.js 2014-11-11 13:29:50 +11:00
Sebastian McKenzie
5588bf56eb add CHANGELOG 2014-11-11 13:29:37 +11:00
Sebastian McKenzie
a0e500de6c v1.11.12 2014-11-11 13:14:31 +11:00
Sebastian McKenzie
bf8d9801ce rename browserified polyfill to browser-polyfill - fixes #140 2014-11-11 13:13:10 +11:00
Sebastian McKenzie
68b99a7004 v1.11.11 2014-11-11 13:06:06 +11:00
Sebastian McKenzie
5ae4f8eec7 add AwaitExpression generator 2014-11-11 13:05:07 +11:00
Sebastian McKenzie
d9a3eadad7 move generators transformer to bottom 2014-11-11 13:03:06 +11:00
Sebastian McKenzie
b1cc5419a4 add AwaitExpression visitor keys - fixes #141 2014-11-11 13:02:55 +11:00
Sebastian McKenzie
c6a7a9c401 v1.11.10 2014-11-11 09:48:28 +11:00
Sebastian McKenzie
608df54b02 bump acorn-6to5 version to one that supports async/await - closes #134 2014-11-11 09:47:29 +11:00
Sebastian McKenzie
2ac83ec95b v1.11.9 2014-11-11 08:07:29 +11:00
Sebastian McKenzie
e4596f638d only check string literals in property-literals transformer 2014-11-11 08:06:31 +11:00
Sebastian McKenzie
1425af9b2a v1.11.8 2014-11-11 07:51:43 +11:00
Sebastian McKenzie
9351c6470f bump regenerator version 2014-11-11 07:50:07 +11:00
Sebastian McKenzie
7b8a50509a v1.11.7 2014-11-11 01:07:20 +11:00
Sebastian McKenzie
1400dee0c1 delegate code and opts assurance to File 2014-11-11 01:06:29 +11:00
Sebastian McKenzie
9e2fc6db9c clone options - sindresorhus/grunt-6to5#7 2014-11-11 01:04:39 +11:00
Sebastian McKenzie
aef5b89492 fix appveyor badge 2014-11-10 21:12:30 +11:00
Sebastian McKenzie
e0bf6f698e add appveyor badge to readme 2014-11-10 21:09:09 +11:00
Sebastian McKenzie
1ac459a05d better appveyor make test 2014-11-10 21:09:04 +11:00
Sebastian McKenzie
1b49835b27 v1.11.6 2014-11-10 16:46:40 +11:00
Sebastian McKenzie
db7b6a4972 fix canCompile in readdirFilter in bin/6to5 util 2014-11-10 16:45:30 +11:00
Sebastian McKenzie
79045e15c5 remove second canCompile declaration 2014-11-10 16:42:04 +11:00
Sebastian McKenzie
b7e6d8f998 add appveyor.yml 2014-11-10 16:31:32 +11:00
Sebastian McKenzie
88c6ce4e48 v1.11.5 2014-11-10 13:10:39 +11:00
Sebastian McKenzie
8c97f1d92e allow constant properties to be modified - fixes #131 2014-11-10 13:09:45 +11:00
Sebastian McKenzie
833e8b091b v1.11.4 2014-11-10 13:02:04 +11:00
Sebastian McKenzie
23ebb23944 add missing util declaration to let scoping transformer 2014-11-10 13:00:52 +11:00
Sebastian McKenzie
778cab33d5 move canCompile method to util 2014-11-10 12:59:24 +11:00
Sebastian McKenzie
5849c6af17 add canCompile method to node api 2014-11-10 12:58:44 +11:00
Sebastian McKenzie
bb0655d8f6 move transformer assignment to new Transformer 2014-11-10 08:21:35 +11:00
Sebastian McKenzie
9977a5f614 change gitter travis hook to always 2014-11-10 08:20:18 +11:00
Sebastian McKenzie
9318d63b5c add let-scoping-return template to let scoping transformer 2014-11-10 08:16:47 +11:00
Sebastian McKenzie
b2ab0dbedc add self-global template to runtime generation 2014-11-10 08:16:38 +11:00
Sebastian McKenzie
e0d3e18865 add allowReturnOutsideFunction to util.parse and make nodes optional in util.template 2014-11-10 08:16:22 +11:00
Sebastian McKenzie
3a3ad4775b add gitter webhook to travis 2014-11-10 08:16:00 +11:00
Sebastian McKenzie
40fdd2a828 dry up types.getIds 2014-11-10 00:51:46 +11:00
Sebastian McKenzie
12f66e852a v1.11.3 2014-11-10 00:22:09 +11:00
Sebastian McKenzie
c61c9aab56 remove invalid ObjectPattern assignment 2014-11-10 00:19:37 +11:00
Sebastian McKenzie
7adc919bb6 remove invalid ObjectPattern destructuring assignment 2014-11-10 00:18:01 +11:00
170 changed files with 1502 additions and 1010 deletions

2
.gitignore vendored
View File

@@ -6,7 +6,7 @@ test/tmp
/templates.json
/tests.json
/browser.js
/polyfill.js
/browser-polyfill.js
/runtime.js
coverage
dist

View File

@@ -9,3 +9,11 @@ branches:
before_script: "npm install -g codeclimate-test-reporter"
script: "make test-travis"
notifications:
webhooks:
urls:
- https://webhooks.gitter.im/e/acf1870e9d223c65e8d5
on_success: always
on_failure: always
on_start: false

28
CHANGELOG.md Normal file
View File

@@ -0,0 +1,28 @@
# 1.12.2
* Upgrade `matcha` to `0.6.0` and `browserify` to `6.3.2`.
* Add own `trimRight` helper instead of relying on the string instance method.
* Support JSX spreads that aren't the first.
# 1.12.1
* Fix `this` and `arguments` mapping in the `_aliasFunctions` transformer.
# 1.12.0
* Combine `jsx` and `react` transformers to `react`.
* Update `react` syntax output to React v0.12.
# 1.11.15
* Fix JSX literal whitespace generation.
# 1.11.14
* Avoid using a switch for let-scoping continue and break statements and use an if statement instead.
* Remove excess whitespace and newlines from JSX literals.
# 1.11.13
* Update regenerator-6to5
* Add support for most escodegen formatting options

View File

@@ -6,6 +6,16 @@
[for (i of [1, 2, 3]) i * i]; // [1, 4, 9]
```
## Async functions
```javascript
async function chainAnimationsAsync(elem, animations) {
for (var anim of animations) {
await anim(elem);
}
}
```
## Arrow functions
```javascript

View File

@@ -6,7 +6,7 @@ MOCHA_CMD = node_modules/mocha/bin/_mocha
export NODE_ENV = test
.PHONY: clean test test-cov test-travis test-browser publish bench build
.PHONY: clean test test-cov test-clean lint test-travis test-spec test-browser publish bench build
clean:
rm -rf coverage templates.json test/tmp dist
@@ -15,16 +15,26 @@ bench:
npm install es6-transpiler traceur esnext es6now jstransform
node node_modules/matcha/bin/_matcha
test:
lint:
$(JSHINT_CMD) lib bin benchmark/index.js
test-clean:
rm -rf test/tmp
test:
make lint
$(MOCHA_CMD)
make test-clean
test-cov:
rm -rf coverage
node $(ISTANBUL_CMD) $(MOCHA_CMD) --
test-travis:
test-spec:
node $(ISTANBUL_CMD) $(MOCHA_CMD) -- --reporter spec
test-travis:
make test-spec
if test -n "$$CODECLIMATE_REPO_TOKEN"; then codeclimate < coverage/lcov.info; fi
test-browser:
@@ -60,7 +70,7 @@ publish:
make build
cp dist/6to5.min.js browser.js
cp dist/polyfill.min.js polyfill.js
cp dist/polyfill.min.js browser-polyfill.js
cp dist/runtime.min.js runtime.js
node bin/cache-templates
@@ -72,4 +82,4 @@ publish:
git push --follow-tags
rm -rf templates.json browser.js runtime.js polyfill.js
rm -rf templates.json browser.js runtime.js browser-polyfill.js

View File

@@ -7,6 +7,10 @@
<img alt="Travis Status" src="http://img.shields.io/travis/6to5/6to5.svg?branch=master&amp;style=flat&amp;label=travis">
</a>
<a href="https://ci.appveyor.com/project/sebmck/6to5">
<img alt="Appveyor Status" src="http://img.shields.io/appveyor/ci/sebmck/6to5.svg?style=flat&amp;label=appveyor">
</a>
<a href="https://codeclimate.com/github/6to5/6to5">
<img alt="Code Climate Score" src="http://img.shields.io/codeclimate/github/6to5/6to5.svg?style=flat">
</a>
@@ -45,11 +49,13 @@ It's as easy as:
- [Caveats](#caveats)
- [Polyfill](#polyfill)
- [Optional runtime](#optional-runtime)
- [React/JSX](#reactjsx)
- [Differences](#differences)
## [Features](FEATURES.md)
- [Array comprehension](FEATURES.md#array-comprehension)
- [Async functions](FEATURES.md#async-functions) via [regenerator](https://github.com/facebook/regenerator)
- [Arrow functions](FEATURES.md#arrow-functions)
- [Classes](FEATURES.md#classes)
- [Computed property names](FEATURES.md#computed-property-names)
@@ -80,7 +86,10 @@ It's as easy as:
- [Gulp](https://github.com/sindresorhus/gulp-6to5)
- [Grunt](https://github.com/sindresorhus/grunt-6to5)
- [Jade](https://github.com/Apoxx/jade-6to5)
- [Jest](https://github.com/6to5/6to5-jest)
- [Karma](https://github.com/shuhei/karma-6to5-preprocessor)
- [Mocha](https://github.com/6to5/6to5-mocha)
- [Rails](https://github.com/6to5/6to5-rails)
- [webpack](https://github.com/Couto/6to5-loader)
### CLI
@@ -342,8 +351,8 @@ require("6to5/polyfill");
### Browser
Available from the `polyfill.js` file within the 6to5 directory of an npm
release.
Available from the `browser-polyfill.js` file within the 6to5 directory of an
npm release.
## Optional runtime
@@ -397,6 +406,14 @@ require("6to5").runtime("myCustomNamespace");
See [Options - runtime](#options) for documentation on changing the reference in
generated code.
## React/JSX
6to5 has built-in support for React v0.12. Tags are automatically transformed to
their equivalent `React.createElement(...)` and `displayName` is automatically
inferred and added to all `React.createClass` calls.
To disable this behaviour add `react` to your blacklist.
## Differences
### Philosophy

17
appveyor.yml Normal file
View File

@@ -0,0 +1,17 @@
environment:
matrix:
- nodejs_version: "0.10"
- nodejs_version: "0.11"
install:
- "npm install"
- "cinst make"
test_script:
- "node --version"
- "npm --version"
- "make test-spec"
build: "off"
version: "{build}"

View File

@@ -6,7 +6,9 @@ var fs = require("fs");
var _ = require("lodash");
exports.readdirFilter = function (filename) {
return readdir(filename).filter(util.canCompile);
return readdir(filename).filter(function (filename) {
return util.canCompile(filename);
});
};
exports.transform = function (filename, code, opts) {

View File

@@ -11,7 +11,7 @@ var _ = require("lodash");
function File(opts) {
this.opts = File.normaliseOptions(opts);
this.moduleFormatter = this.getModuleFormatter(opts.modules);
this.moduleFormatter = this.getModuleFormatter(this.opts.modules);
this.declarations = {};
this.uids = {};
@@ -21,7 +21,7 @@ function File(opts) {
File.declarations = ["extends", "class-props", "slice"];
File.normaliseOptions = function (opts) {
opts = opts || {};
opts = _.cloneDeep(opts || {});
_.defaults(opts, {
whitespace: true,
@@ -33,6 +33,9 @@ File.normaliseOptions = function (opts) {
runtime: false
});
// normalise windows path separators to unix
opts.filename = opts.filename.replace(/\\/g, "/");
_.defaults(opts, {
sourceFileName: opts.filename,
sourceMapName: opts.filename
@@ -110,6 +113,8 @@ File.prototype.errorWithNode = function (node, msg, Error) {
};
File.prototype.parse = function (code) {
code = (code || "") + "";
var self = this;
this.code = code;
@@ -141,7 +146,7 @@ File.prototype.generate = function () {
if (this.shebang) {
// add back shebang
result.code = this.shebang + result.code;
result.code = this.shebang + "\n" + result.code;
}
if (opts.sourceMap === "inline") {

View File

@@ -0,0 +1,123 @@
module.exports = Buffer;
var util = require("../util");
var _ = require("lodash");
function Buffer(position, format) {
this.position = position;
this._indent = format.indent.base;
this.format = format;
this.buf = "";
}
Buffer.prototype.get = function () {
return util.trimRight(this.buf);
};
Buffer.prototype.getIndent = function () {
if (this.format.compact) {
return "";
} else {
return util.repeat(this._indent, this.format.indent.style);
}
};
Buffer.prototype.indentSize = function () {
return this.getIndent().length;
};
Buffer.prototype.indent = function () {
this._indent++;
};
Buffer.prototype.dedent = function () {
this._indent--;
};
Buffer.prototype.semicolon = function () {
if (this.format.semicolons) this.push(";");
};
Buffer.prototype.ensureSemicolon = function () {
if (!this.isLast(";")) this.semicolon();
};
Buffer.prototype.rightBrace = function () {
this.newline(true);
this.push("}");
};
Buffer.prototype.keyword = function (name) {
this.push(name);
this.push(" ");
};
Buffer.prototype.space = function () {
if (this.buf && !this.isLast([" ", "\n"])) {
this.push(" ");
}
};
Buffer.prototype.removeLast = function (cha) {
if (!this.isLast(cha)) return;
this.buf = this.buf.slice(0, -1);
this.position.unshift(cha);
};
Buffer.prototype.newline = function (i, removeLast) {
if (!this.buf) return;
if (this.format.compact) return;
if (this.endsWith("{\n")) return;
if (_.isBoolean(i)) {
removeLast = i;
i = null;
}
if (_.isNumber(i)) {
var self = this;
_.times(i, function () {
self.newline(null, removeLast);
});
return;
}
if (removeLast && this.isLast("\n")) this.removeLast("\n");
this.removeLast(" ");
this.buf = this.buf.replace(/\n(\s+)$/, "\n");
this._push("\n");
};
Buffer.prototype.push = function (str, noIndent) {
if (this._indent && !noIndent && str !== "\n") {
// we have an indent level and we aren't pushing a newline
var indent = this.getIndent();
// replace all newlines with newlines with the indentation
str = str.replace(/\n/g, "\n" + indent);
// we've got a newline before us so prepend on the indentation
if (this.isLast("\n")) str = indent + str;
}
this._push(str);
};
Buffer.prototype._push = function (str) {
this.position.push(str);
this.buf += str;
};
Buffer.prototype.endsWith = function (str) {
return this.buf.slice(-str.length) === str;
};
Buffer.prototype.isLast = function (cha, trimRight) {
var buf = this.buf;
if (trimRight) buf = util.trimRight(buf);
var chars = [].concat(cha);
return _.contains(chars, _.last(buf));
};

View File

@@ -8,6 +8,7 @@ module.exports.CodeGenerator = CodeGenerator;
var Whitespace = require("./whitespace");
var SourceMap = require("./source-map");
var Position = require("./position");
var Buffer = require("./buffer");
var util = require("../util");
var n = require("./node");
var t = require("../types");
@@ -16,29 +17,41 @@ var _ = require("lodash");
function CodeGenerator(ast, opts, code) {
opts = opts || {};
this.style = {
semicolons: true,
comments: true,
compact: false,
indent: {
char: " ",
width: 2
}
};
this.comments = ast.comments || [];
this.tokens = ast.tokens || [];
this.opts = opts;
this.format = CodeGenerator.normaliseOptions(opts);
this.ast = ast;
this.buf = "";
this._indent = 0;
this.whitespace = new Whitespace(this.tokens, this.comments);
this.position = new Position;
this.map = new SourceMap(this.position, opts, code);
this.buffer = new Buffer(this.position, this.format);
}
_.each(Buffer.prototype, function (fn, key) {
CodeGenerator.prototype[key] = function () {
return fn.apply(this.buffer, arguments);
};
});
CodeGenerator.normaliseOptions = function (opts) {
opts = opts.format || {};
opts = _.merge({
parentheses: true,
semicolons: true,
comments: true,
compact: false,
indent: {
adjustMultilineComment: true,
style: " ",
base: 0
}
}, opts);
return opts;
};
CodeGenerator.generators = {
arrayComprehensions: require("./generators/array-comprehensions"),
templateLiterals: require("./generators/template-literals"),
@@ -56,125 +69,15 @@ _.each(CodeGenerator.generators, function (generator) {
_.extend(CodeGenerator.prototype, generator);
});
CodeGenerator.prototype.newline = function (i, removeLast) {
if (!this.buf) return;
if (this.style.compact) return;
if (this.endsWith("{\n")) return;
if (_.isBoolean(i)) {
removeLast = i;
i = null;
}
if (_.isNumber(i)) {
var self = this;
_.times(i, function () {
self.newline(null, removeLast);
});
return;
}
if (removeLast && this.isLast("\n")) this.removeLast("\n");
this.removeLast(" ");
this.buf = this.buf.replace(/\n(\s+)$/, "\n");
this._push("\n");
};
CodeGenerator.prototype.removeLast = function (cha) {
if (!this.isLast(cha)) return;
this.buf = this.buf.slice(0, -1);
this.position.unshift(cha);
};
CodeGenerator.prototype.semicolon = function () {
if (this.style.semicolons) this.push(";");
};
CodeGenerator.prototype.ensureSemicolon = function () {
if (!this.isLast(";")) this.semicolon();
};
CodeGenerator.prototype.rightBrace = function () {
this.newline(true);
this.push("}");
};
CodeGenerator.prototype.keyword = function (name) {
this.push(name);
this.push(" ");
};
CodeGenerator.prototype.space = function () {
if (this.buf && !this.isLast([" ", "\n"])) {
this.push(" ");
}
};
CodeGenerator.prototype.push = function (str, noIndent) {
if (this._indent && !noIndent && str !== "\n") {
// we have an indent level and we aren't pushing a newline
var indent = this.getIndent();
// replace all newlines with newlines with the indentation
str = str.replace(/\n/g, "\n" + indent);
// we've got a newline before us so prepend on the indentation
if (this.isLast("\n")) str = indent + str;
}
this._push(str);
};
CodeGenerator.prototype._push = function (str) {
this.position.push(str);
this.buf += str;
};
CodeGenerator.prototype.endsWith = function (str) {
return this.buf.slice(-str.length) === str;
};
CodeGenerator.prototype.isLast = function (cha, trimRight) {
var buf = this.buf;
if (trimRight) buf = buf.trimRight();
var chars = [].concat(cha);
return _.contains(chars, _.last(buf));
};
CodeGenerator.prototype.getIndent = function () {
if (this.style.compact) {
return "";
} else {
return util.repeat(this.indentSize(), this.style.indent.char);
}
};
CodeGenerator.prototype.indentSize = function () {
return this._indent * this.style.indent.width;
};
CodeGenerator.prototype.indent = function () {
this._indent++;
};
CodeGenerator.prototype.dedent = function () {
this._indent--;
};
CodeGenerator.prototype.generate = function () {
var ast = this.ast;
this.print(ast);
this.buf = this.buf.trimRight();
return {
map: this.map.get(),
ast: ast,
code: this.buf
code: this.buffer.get()
};
};
@@ -353,8 +256,8 @@ CodeGenerator.prototype._getComments = function (key, node) {
};
CodeGenerator.prototype._printComments = function (comments) {
if (this.style.compact) return;
if (!this.style.comments) return;
if (this.format.compact) return;
if (!this.format.comments) return;
if (!comments || !comments.length) return;
var self = this;
@@ -373,14 +276,16 @@ CodeGenerator.prototype._printComments = function (comments) {
//
var offset = comment.loc.start.column;
if (offset) {
var newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g");
val = val.replace(newlineRegex, "\n");
}
if (comment.type === "Block" && self.format.indent.adjustMultilineComment) {
var offset = comment.loc.start.column;
if (offset) {
var newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g");
val = val.replace(newlineRegex, "\n");
}
var indent = Math.max(self.indentSize(), column);
val = val.replace(/\n/g, "\n" + util.repeat(indent));
var indent = Math.max(self.indentSize(), column);
val = val.replace(/\n/g, "\n" + util.repeat(indent));
}
if (column === 0) {
val = self.getIndent() + val;

View File

@@ -44,9 +44,11 @@ exports.ConditionalExpression = function (node, print) {
exports.NewExpression = function (node, print) {
this.push("new ");
print(node.callee);
this.push("(");
print.join(node.arguments, { separator: ", " });
this.push(")");
if (node.arguments.length || this.format.parentheses) {
this.push("(");
print.join(node.arguments, { separator: ", " });
this.push(")");
}
};
exports.SequenceExpression = function (node, print) {
@@ -64,15 +66,20 @@ exports.CallExpression = function (node, print) {
this.push(")");
};
exports.YieldExpression = function (node, print) {
this.push("yield");
if (node.delegate) this.push("*");
if (node.argument) {
this.space();
print(node.argument);
}
var buildYieldAwait = function (keyword) {
return function (node, print) {
this.push(keyword);
if (node.delegate) this.push("*");
if (node.argument) {
this.space();
print(node.argument);
}
};
};
exports.YieldExpression = buildYieldAwait("yield");
exports.AwaitExpression = buildYieldAwait("await");
exports.EmptyStatement = function () {
this.semicolon();
};

View File

@@ -46,15 +46,11 @@ exports.XJSElement = function (node, print) {
this.indent();
_.each(node.children, function (child) {
if (t.isLiteral(child) && typeof child.value === "string") {
if (/\S/.test(child.value)) {
return self.push(child.value.replace(/^\s+|\s+$/g, ""));
} else if (/\n/.test(child.value)) {
return self.newline();
}
if (t.isLiteral(child)) {
self.push(child.value);
} else {
print(child);
}
print(child);
});
this.dedent();

View File

@@ -1,290 +0,0 @@
module.exports = Node;
var t = require("../types");
var _ = require("lodash");
function Node(node, parent) {
this.parent = parent;
this.node = node;
}
//
Node.whitespace = {
FunctionExpression: 1,
FunctionStatement: 1,
ClassExpression: 1,
ClassStatement: 1,
ForOfStatement: 1,
ForInStatement: 1,
ForStatement: 1,
SwitchStatement: 1,
IfStatement: { before: 1 },
//Property: { before: 1 },
Literal: { after: 1 }
};
_.each(Node.whitespace, function (amounts, type) {
if (_.isNumber(amounts)) amounts = { after: amounts, before: amounts };
Node.whitespace[type] = amounts;
});
//
Node.PRECEDENCE = {};
_.each([
["||"],
["&&"],
["|"],
["^"],
["&"],
["==", "===", "!=", "!=="],
["<", ">", "<=", ">=", "in", "instanceof"],
[">>", "<<", ">>>"],
["+", "-"],
["*", "/", "%"]
], function (tier, i) {
_.each(tier, function (op) {
Node.PRECEDENCE[op] = i;
});
});
//
Node.prototype.isUserWhitespacable = function () {
//var parent = this.parent;
var node = this.node;
if (t.isUserWhitespacable(node)) {
return true;
}
//if (t.isArrayExpression(parent)) {
// return true;
//}
return false;
};
Node.prototype.needsWhitespace = function (type) {
var parent = this.parent;
var node = this.node;
if (!node) return 0;
if (t.isExpressionStatement(node)) {
node = node.expression;
}
if (type === "before") {
if (t.isProperty(node) && parent.properties[0] === node) {
return 1;
}
}
if (type === "after") {
if (t.isCallExpression(node)) {
return 1;
}
var exprs = [];
if (t.isVariableDeclaration(node)) {
exprs = _.map(node.declarations, "init");
}
if (t.isArrayExpression(node)) {
exprs = node.elements;
}
if (t.isObjectExpression(node)) {
exprs = node.properties;
}
var lines = 0;
_.each(exprs, function (expr) {
lines = Node.needsWhitespace(expr, node, type);
if (lines) return false;
});
if (lines) return lines;
}
if (t.isCallExpression(node) && t.isFunction(node.callee)) {
return 1;
}
var opts = Node.whitespace[node.type];
return (opts && opts[type]) || 0;
};
Node.prototype.needsWhitespaceBefore = function () {
return this.needsWhitespace("before");
};
Node.prototype.needsWhitespaceAfter = function () {
return this.needsWhitespace("after");
};
Node.prototype.needsParens = function () {
var parent = this.parent;
var node = this.node;
if (!parent) return false;
//
if (t.isUnaryLike(node)) {
return t.isMemberExpression(parent) && parent.object === node;
}
if (t.isBinary(node)) {
//
if (t.isCallExpression(parent) && parent.callee === node) {
return true;
}
//
if (t.isUnaryLike(parent)) {
return true;
}
//
if (t.isMemberExpression(parent) && parent.object === node) {
return true;
}
if (t.isBinary(parent)) {
var parentOp = parent.operator;
var parentPos = Node.PRECEDENCE[parentOp];
var nodeOp = node.operator;
var nodePos = Node.PRECEDENCE[nodeOp];
if (parentPos > nodePos) {
return true;
}
if (parentPos === nodePos && parent.right === node) {
return true;
}
}
}
if (t.isBinaryExpression(node) && node.operator === "in") {
// var i = (1 in []);
if (t.isVariableDeclarator(parent)) {
return true;
}
// for ((1 in []);;);
if (t.isFor(parent)) {
return true;
}
}
// (class {});
if (t.isClassExpression(node) && t.isExpressionStatement(parent)) {
return true;
}
if (t.isSequenceExpression(node)) {
if (t.isForStatement(parent)) {
// Although parentheses wouldn't hurt around sequence
// expressions in the head of for loops, traditional style
// dictates that e.g. i++, j++ should not be wrapped with
// parentheses.
return false;
}
if (t.isExpressionStatement(parent) && parent.expression === node) {
return false;
}
// Otherwise err on the side of overparenthesization, adding
// explicit exceptions above if this proves overzealous.
return true;
}
//
if (t.isYieldExpression(node)) {
return t.isBinary(parent) ||
t.isUnaryLike(parent) ||
t.isCallExpression(parent) ||
t.isMemberExpression(parent) ||
t.isNewExpression(parent) ||
t.isConditionalExpression(parent) ||
t.isYieldExpression(parent);
}
if (t.isNewExpression(parent) && parent.callee === node) {
return t.isCallExpression(node) || _.some(node, function (val) {
return t.isCallExpression(val);
});
}
// (1).valueOf()
if (t.isLiteral(node) && _.isNumber(node.value) && t.isMemberExpression(parent) && parent.object === node) {
return true;
}
if (t.isAssignmentExpression(node) || t.isConditionalExpression(node)) {
//
if (t.isUnaryLike(parent)) {
return true;
}
//
if (t.isBinary(parent)) {
return true;
}
//
if (t.isCallExpression(parent) && parent.callee === node) {
return true;
}
//
if (t.isConditionalExpression(parent) && parent.test === node) {
return true;
}
//
if (t.isMemberExpression(parent) && parent.object === node) {
return true;
}
}
if (t.isFunctionExpression(node)) {
// function () {};
if (t.isExpressionStatement(parent)) {
return true;
}
// (function test() {}).name;
if (t.isMemberExpression(parent) && parent.object === node) {
return true;
}
// (function () {})();
if (t.isCallExpression(parent) && parent.callee === node) {
return true;
}
}
// ({ x, y }) = { x: 5, y: 6 };
if (t.isObjectPattern(node) && t.isAssignmentExpression(parent) && parent.left == node) {
return true;
}
return false;
};
_.each(Node.prototype, function (fn, key) {
Node[key] = function (node, parent) {
var n = new Node(node, parent);
var args = _.toArray(arguments).slice(2);
return n[key].apply(n, args);
};
});

View File

@@ -0,0 +1,90 @@
module.exports = Node;
var whitespace = require("./whitespace");
var parens = require("./parentheses");
var t = require("../../types");
var _ = require("lodash");
var find = function (obj, node, parent) {
var result;
_.each(obj, function (fn, type) {
if (t["is" + type](node)) {
result = fn(node, parent);
if (result != null) return false;
}
});
return result;
};
function Node(node, parent) {
this.parent = parent;
this.node = node;
}
Node.prototype.isUserWhitespacable = function () {
//var parent = this.parent;
var node = this.node;
if (t.isUserWhitespacable(node)) {
return true;
}
//if (t.isArrayExpression(parent)) {
// return true;
//}
return false;
};
Node.prototype.needsWhitespace = function (type) {
var parent = this.parent;
var node = this.node;
if (!node) return 0;
if (t.isExpressionStatement(node)) {
node = node.expression;
}
var lines = find(whitespace[type].nodes, node, parent);
if (lines) return lines;
_.each(find(whitespace[type].list, node, parent), function (expr) {
lines = Node.needsWhitespace(expr, node, type);
if (lines) return false;
});
return lines || 0;
};
Node.prototype.needsWhitespaceBefore = function () {
return this.needsWhitespace("before");
};
Node.prototype.needsWhitespaceAfter = function () {
return this.needsWhitespace("after");
};
Node.prototype.needsParens = function () {
var parent = this.parent;
var node = this.node;
if (!parent) return false;
if (t.isNewExpression(parent) && parent.callee === node) {
return t.isCallExpression(node) || _.some(node, function (val) {
return t.isCallExpression(val);
});
}
return find(parens, node, parent);
};
_.each(Node.prototype, function (fn, key) {
Node[key] = function (node, parent) {
var n = new Node(node, parent);
var args = _.toArray(arguments).slice(2);
return n[key].apply(n, args);
};
});

View File

@@ -0,0 +1,150 @@
var t = require("../../types");
var _ = require("lodash");
var PRECEDENCE = {};
_.each([
["||"],
["&&"],
["|"],
["^"],
["&"],
["==", "===", "!=", "!=="],
["<", ">", "<=", ">=", "in", "instanceof"],
[">>", "<<", ">>>"],
["+", "-"],
["*", "/", "%"]
], function (tier, i) {
_.each(tier, function (op) {
PRECEDENCE[op] = i;
});
});
exports.Binary = function (node, parent) {
if (t.isCallExpression(parent) && parent.callee === node) {
return true;
}
if (t.isUnaryLike(parent)) {
return true;
}
if (t.isMemberExpression(parent) && parent.object === node) {
return true;
}
if (t.isBinary(parent)) {
var parentOp = parent.operator;
var parentPos = PRECEDENCE[parentOp];
var nodeOp = node.operator;
var nodePos = PRECEDENCE[nodeOp];
if (parentPos > nodePos) {
return true;
}
if (parentPos === nodePos && parent.right === node) {
return true;
}
}
};
exports.BinaryExpression = function (node, parent) {
if (node.operator === "in") {
// var i = (1 in []);
if (t.isVariableDeclarator(parent)) {
return true;
}
// for ((1 in []);;);
if (t.isFor(parent)) {
return true;
}
}
};
exports.SequenceExpression = function (node, parent) {
if (t.isForStatement(parent)) {
// Although parentheses wouldn't hurt around sequence
// expressions in the head of for loops, traditional style
// dictates that e.g. i++, j++ should not be wrapped with
// parentheses.
return false;
}
if (t.isExpressionStatement(parent) && parent.expression === node) {
return false;
}
// Otherwise err on the side of overparenthesization, adding
// explicit exceptions above if this proves overzealous.
return true;
};
exports.YieldExpression = function (node, parent) {
return t.isBinary(parent) ||
t.isUnaryLike(parent) ||
t.isCallExpression(parent) ||
t.isMemberExpression(parent) ||
t.isNewExpression(parent) ||
t.isConditionalExpression(parent) ||
t.isYieldExpression(parent);
};
exports.Literal = function (node, parent) {
// (1).valueOf()
if (_.isNumber(node.value) && t.isMemberExpression(parent) && parent.object === node) {
return true;
}
};
exports.ClassExpression = function (node, parent) {
return t.isExpressionStatement(parent);
};
exports.UnaryLike = function (node, parent) {
return t.isMemberExpression(parent) && parent.object === node;
};
exports.FunctionExpression = function (node, parent) {
// function () {};
if (t.isExpressionStatement(parent)) {
return true;
}
// (function test() {}).name;
if (t.isMemberExpression(parent) && parent.object === node) {
return true;
}
// (function () {})();
if (t.isCallExpression(parent) && parent.callee === node) {
return true;
}
};
exports.AssignmentExpression =
exports.ConditionalExpression = function (node, parent) {
if (t.isUnaryLike(parent)) {
return true;
}
if (t.isBinary(parent)) {
return true;
}
if (t.isCallExpression(parent) && parent.callee === node) {
return true;
}
if (t.isConditionalExpression(parent) && parent.test === node) {
return true;
}
if (t.isMemberExpression(parent) && parent.object === node) {
return true;
}
return false;
};

View File

@@ -0,0 +1,60 @@
var _ = require("lodash");
var t = require("../../types");
exports.before = {
nodes: {
Property: function (node, parent) {
if (parent.properties[0] === node) {
return 1;
}
},
SwitchCase: function (node, parent) {
if (parent.cases[0] === node) {
return 1;
}
},
CallExpression: function (node) {
if (t.isFunction(node.callee)) {
return 1;
}
}
}
};
exports.after = {
nodes: {},
list: {
VariableDeclaration: function (node) {
return _.map(node.declarations, "init");
},
ArrayExpression: function (node) {
return node.elements;
},
ObjectExpression: function (node) {
return node.properties;
}
}
};
_.each({
Function: 1,
Class: 1,
For: 1,
SwitchStatement: 1,
IfStatement: { before: 1 },
CallExpression: { after: 1 },
Literal: { after: 1 }
}, function (amounts, type) {
if (_.isNumber(amounts)) amounts = { after: amounts, before: amounts };
_.each(amounts, function (amount, key) {
exports[key].nodes[type] = function () {
return amount;
};
});
});

View File

@@ -1,4 +1,5 @@
var transform = require("./transformation/transform");
var util = require("./util");
var fs = require("fs");
var _ = require("lodash");
@@ -14,6 +15,8 @@ exports.polyfill = function () {
require("./polyfill");
};
exports.canCompile = util.canCompile;
exports.transform = transform;
exports.transformFile = function (filename, opts, callback) {

View File

@@ -11,16 +11,7 @@ module.exports = function (namespace) {
var container = t.functionExpression(null, [], t.blockStatement(body));
var tree = t.program([t.expressionStatement(t.callExpression(container, []))]);
body.push(t.variableDeclaration("var", [
t.variableDeclarator(t.identifier("self"), t.conditionalExpression(
t.binaryExpression("===",
t.unaryExpression("typeof", t.identifier("global"), true),
t.literal("undefined")
),
t.identifier("window"),
t.identifier("global"))
)
]));
body.push(util.template("self-global", true));
body.push(t.variableDeclaration("var", [
t.variableDeclarator(

View File

@@ -0,0 +1 @@
if (typeof RETURN === "object") return RETURN.v;

View File

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

View File

@@ -5,9 +5,6 @@ var File = require("../file");
var _ = require("lodash");
function transform(code, opts) {
opts = opts || {};
code = (code || "") + "";
var file = new File(opts);
return file.parse(code);
}
@@ -20,7 +17,16 @@ transform._ensureTransformerNames = function (type, keys) {
});
};
transform.transformers = {
transform.transformers = {};
transform.moduleFormatters = {
common: require("./modules/common"),
ignore: require("./modules/ignore"),
amd: require("./modules/amd"),
umd: require("./modules/umd")
};
_.each({
modules: require("./transformers/modules"),
propertyNameShorthand: require("./transformers/property-name-shorthand"),
constants: require("./transformers/constants"),
@@ -40,28 +46,17 @@ transform.transformers = {
letScoping: require("./transformers/let-scoping"),
forOf: require("./transformers/for-of"),
unicodeRegex: require("./transformers/unicode-regex"),
generators: require("./transformers/generators"),
numericLiterals: require("./transformers/numeric-literals"),
react: require("./transformers/react"),
jsx: require("./transformers/jsx"),
_aliasFunctions: require("./transformers/_alias-functions"),
_blockHoist: require("./transformers/_block-hoist"),
_declarations: require("./transformers/_declarations"),
generators: require("./transformers/generators"),
useStrict: require("./transformers/use-strict"),
_moduleFormatter: require("./transformers/_module-formatter")
};
transform.moduleFormatters = {
common: require("./modules/common"),
ignore: require("./modules/ignore"),
amd: require("./modules/amd"),
umd: require("./modules/umd")
};
_.each(transform.transformers, function (transformer, key) {
}, function (transformer, key) {
transform.transformers[key] = new Transformer(key, transformer);
});

View File

@@ -14,10 +14,9 @@ var go = function (getBody, node, file, scope) {
};
// traverse the function and find all alias functions so we can alias
// arguments and this if necessary
// `arguments` and `this` if necessary
traverse(node, function (node) {
var _aliasFunction = node._aliasFunction;
if (!_aliasFunction) {
if (!node._aliasFunction) {
if (t.isFunction(node)) {
// stop traversal of this node as it'll be hit again by this transformer
return false;
@@ -26,12 +25,10 @@ var go = function (getBody, node, file, scope) {
}
}
// traverse all child nodes of this function and find arguments and this
// traverse all child nodes of this function and find `arguments` and `this`
traverse(node, function (node, parent) {
if (_aliasFunction === "arrows") {
if (t.isFunction(node) && node._aliasFunction !== "arrows") {
return false;
}
if (t.isFunction(node) && !node._aliasFunction) {
return false;
}
if (node._ignoreAliasFunctions) return;

View File

@@ -1,10 +1,11 @@
var esutils = require("esutils");
var t = require("../../types");
var _ = require("lodash");
exports.Property = function (node) {
// ignore key literals that are valid identifiers
var key = node.key;
if (t.isLiteral(key) && esutils.keyword.isIdentifierName(key.value)) {
if (t.isLiteral(key) && _.isString(key.value) && esutils.keyword.isIdentifierName(key.value)) {
key.type = "Identifier";
key.name = key.value;
delete key.value;

View File

@@ -1,5 +1,6 @@
var util = require("../../util");
var t = require("../../types");
var _ = require("lodash");
var singleArrayExpression = function (node) {
var block = node.blocks[0];
@@ -13,7 +14,13 @@ var singleArrayExpression = function (node) {
ARRAY: block.right,
KEY: block.left
});
result._aliasFunction = true;
_.each([result.callee.object, result], function (call) {
if (t.isCallExpression(call)) {
call.arguments[0]._aliasFunction = true;
}
});
return result;
};
@@ -23,7 +30,7 @@ var multiple = function (node, file) {
var container = util.template("array-comprehension-container", {
KEY: uid
});
container._aliasFunction = true;
container.callee.expression._aliasFunction = true;
var block = container.callee.expression.body;
var body = block.body;

View File

@@ -3,7 +3,7 @@ var t = require("../../types");
exports.ArrowFunctionExpression = function (node) {
t.ensureBlock(node);
node._aliasFunction = "arrows";
node._aliasFunction = true;
node.expression = false;
node.type = "FunctionExpression";

View File

@@ -5,12 +5,12 @@ var _ = require("lodash");
exports.ClassDeclaration = function (node, parent, file, scope) {
return t.variableDeclaration("var", [
t.variableDeclarator(node.id, buildClass(node, file, scope))
t.variableDeclarator(node.id, new Class(node, file, scope).run())
]);
};
exports.ClassExpression = function (node, parent, file, scope) {
return buildClass(node, file, scope);
return new Class(node, file, scope).run();
};
var getMemberExpressionObject = function (node) {
@@ -20,31 +20,59 @@ var getMemberExpressionObject = function (node) {
return node;
};
var buildClass = function (node, file, scope) {
var superName = node.superClass;
var className = node.id || t.identifier(file.generateUid("class", scope));
/**
* Description
*
* @param {Node} node
* @param {File} file
* @param {Scope} scope
*/
var superClassArgument = node.superClass;
var superClassCallee = node.superClass;
function Class(node, file, scope) {
this.scope = scope;
this.node = node;
this.file = file;
this.instanceMutatorMap = {};
this.staticMutatorMap = {};
this.hasConstructor = false;
this.className = node.id || t.identifier(file.generateUid("class", scope));
this.superName = node.superClass;
}
/**
* Description
*
* @returns {Array}
*/
Class.prototype.run = function () {
var superClassArgument = this.superName;
var superClassCallee = this.superName;
var superName = this.superName;
var className = this.className;
var file = this.file;
if (superName) {
if (t.isMemberExpression(superName)) {
superClassArgument = superClassCallee = getMemberExpressionObject(superName);
} else if (!t.isIdentifier(superName)) {
superClassArgument = superName;
superClassCallee = superName = t.identifier(file.generateUid("ref", scope));
superClassCallee = superName = t.identifier(file.generateUid("ref", this.scope));
}
}
this.superName = superName;
var container = util.template("class", {
CLASS_NAME: className
});
var block = container.callee.expression.body;
var body = block.body;
var constructor = body[0].declarations[0].init;
var body = this.body = block.body;
var constructor = this.constructor = body[0].declarations[0].init;
if (node.id) constructor.id = className;
if (this.node.id) constructor.id = className;
var returnStatement = body.pop();
@@ -55,14 +83,7 @@ var buildClass = function (node, file, scope) {
container.callee.expression.params.push(superClassCallee);
}
buildClassBody({
file: file,
body: body,
node: node,
className: className,
superName: superName,
constructor: constructor,
});
this.buildBody();
if (body.length === 1) {
// only a constructor so no need for a closure container
@@ -73,49 +94,29 @@ var buildClass = function (node, file, scope) {
}
};
var buildClassBody = function (opts) {
var file = opts.file;
var body = opts.body;
var node = opts.node;
var constructor = opts.constructor;
var className = opts.className;
var superName = opts.superName;
/**
* Description
*/
var instanceMutatorMap = {};
var staticMutatorMap = {};
var hasConstructor = false;
var classBody = node.body.body;
Class.prototype.buildBody = function () {
var constructor = this.constructor;
var className = this.className;
var superName = this.superName;
var classBody = this.node.body.body;
var body = this.body;
var self = this;
_.each(classBody, function (node) {
var methodName = node.key;
var method = node.value;
replaceInstanceSuperReferences(superName, node);
self.replaceInstanceSuperReferences(node);
if (node.key.name === "constructor") {
if (node.kind === "") {
hasConstructor = true;
addConstructor(constructor, method);
} else {
throw file.errorWithNode(node, "illegal kind for constructor method");
}
self.pushConstructor(node);
} else {
var mutatorMap = instanceMutatorMap;
if (node.static) mutatorMap = staticMutatorMap;
var kind = node.kind;
if (kind === "") {
kind = "value";
util.pushMutatorMap(mutatorMap, methodName, "writable", t.identifier("true"));
}
util.pushMutatorMap(mutatorMap, methodName, kind, node);
self.pushMethod(node);
}
});
if (!hasConstructor && superName) {
if (!this.hasConstructor && superName) {
constructor.body.body.push(util.template("class-super-constructor-call", {
SUPER_NAME: superName
}, true));
@@ -124,16 +125,16 @@ var buildClassBody = function (opts) {
var instanceProps;
var staticProps;
if (!_.isEmpty(instanceMutatorMap)) {
if (!_.isEmpty(this.instanceMutatorMap)) {
var protoId = util.template("prototype-identifier", {
CLASS_NAME: className
});
instanceProps = util.buildDefineProperties(instanceMutatorMap, protoId);
instanceProps = util.buildDefineProperties(this.instanceMutatorMap, protoId);
}
if (!_.isEmpty(staticMutatorMap)) {
staticProps = util.buildDefineProperties(staticMutatorMap, className);
if (!_.isEmpty(this.staticMutatorMap)) {
staticProps = util.buildDefineProperties(this.staticMutatorMap, className);
}
if (instanceProps || staticProps) {
@@ -143,17 +144,50 @@ var buildClassBody = function (opts) {
if (instanceProps) args.push(instanceProps);
body.push(t.expressionStatement(
t.callExpression(file.addDeclaration("class-props"), args)
t.callExpression(this.file.addDeclaration("class-props"), args)
));
}
};
var superIdentifier = function (superName, methodNode, node, parent) {
var methodName = methodNode.key;
/**
* Push a method to it's respective mutatorMap.
*
* @param {Node} node MethodDefinition
*/
if (parent.property === node) {
Class.prototype.pushMethod = function (node) {
var methodName = node.key;
var mutatorMap = this.instanceMutatorMap;
if (node.static) mutatorMap = this.staticMutatorMap;
var kind = node.kind;
if (kind === "") {
kind = "value";
util.pushMutatorMap(mutatorMap, methodName, "writable", t.identifier("true"));
}
util.pushMutatorMap(mutatorMap, methodName, kind, node);
};
/**
* Given a `methodNode`, produce a `MemberExpression` super class reference.
*
* @param {Node} methodNode MethodDefinition
* @param {Node} node Identifier
* @param {Node} parent
*
* @returns {Node}
*/
Class.prototype.superIdentifier = function (methodNode, id, parent) {
var methodName = methodNode.key;
var superName = this.superName || t.identifier("Function");
if (parent.property === id) {
return;
} else if (t.isCallExpression(parent, { callee: node })) {
} else if (t.isCallExpression(parent, { callee: id })) {
// super(); -> ClassName.prototype.MethodName.call(this);
parent.arguments.unshift(t.thisExpression());
@@ -161,15 +195,15 @@ var superIdentifier = function (superName, methodNode, node, parent) {
// constructor() { super(); }
return t.memberExpression(superName, t.identifier("call"));
} else {
node = superName;
id = superName;
// foo() { super(); }
if (!methodNode.static) {
node = t.memberExpression(node, t.identifier("prototype"));
id = t.memberExpression(id, t.identifier("prototype"));
}
node = t.memberExpression(node, methodName, methodNode.computed);
return t.memberExpression(node, t.identifier("call"));
id = t.memberExpression(id, methodName, methodNode.computed);
return t.memberExpression(id, t.identifier("call"));
}
} else if (t.isMemberExpression(parent) && !methodNode.static) {
// super.test -> ClassName.prototype.test
@@ -179,31 +213,50 @@ var superIdentifier = function (superName, methodNode, node, parent) {
}
};
var replaceInstanceSuperReferences = function (superName, methodNode) {
var method = methodNode.value;
/**
* Replace all `super` references with a reference to our `superClass`.
*
* @param {Node} methodNode MethodDefinition
*/
superName = superName || t.identifier("Function");
Class.prototype.replaceInstanceSuperReferences = function (methodNode) {
var method = methodNode.value;
var self = this;
traverse(method, function (node, parent) {
if (t.isIdentifier(node, { name: "super" })) {
return superIdentifier(superName, methodNode, node, parent);
return self.superIdentifier(methodNode, node, parent);
} else if (t.isCallExpression(node)) {
var callee = node.callee;
if (!t.isMemberExpression(callee)) return;
if (callee.object.name !== "super") return;
// super.test(); -> ClassName.prototype.MethodName.call(this);
callee.property.name = callee.property.name + ".call";
// super.test(); -> ClassName.prototype.MethodName.call(this);
callee.property = t.memberExpression(callee.property, t.identifier("call"));
node.arguments.unshift(t.thisExpression());
}
});
};
var addConstructor = function (construct, method) {
construct.defaults = method.defaults;
construct.params = method.params;
construct.body = method.body;
construct.rest = method.rest;
/**
* Replace the constructor body of our class.
*
* @param {Node} method MethodDefinition
*/
t.inherits(construct, method);
Class.prototype.pushConstructor = function (method) {
if (method.kind !== "") {
throw this.file.errorWithNode(method, "illegal kind for constructor method");
}
var construct = this.constructor;
var fn = method.value;
this.hasConstructor = true;
t.inherits(construct, fn);
construct.defaults = fn.defaults;
construct.params = fn.params;
construct.body = fn.body;
construct.rest = fn.rest;
};

View File

@@ -29,7 +29,7 @@ exports.ObjectExpression = function (node, parent, file) {
var containerCallee = container.callee.expression;
var containerBody = containerCallee.body.body;
containerCallee._aliasFunction = "arrows";
containerCallee._aliasFunction = true;
_.each(computed, function (prop) {
containerBody.unshift(

View File

@@ -17,10 +17,14 @@ exports.ForStatement = function (node, parent, file) {
});
};
var getIds = function (node) {
return t.getIds(node, false, ["MemberExpression"]);
};
_.each(node.body, function (child) {
if (child && t.isVariableDeclaration(child, { kind: "const" })) {
_.each(child.declarations, function (declar) {
_.each(t.getIds(declar), function (name) {
_.each(getIds(declar), function (name) {
check(declar, [name]);
constants.push(name);
});
@@ -39,7 +43,7 @@ exports.ForStatement = function (node, parent, file) {
if (child._ignoreConstant) return;
if (t.isVariableDeclarator(child) || t.isDeclaration(child) || t.isAssignmentExpression(child)) {
check(child, t.getIds(child));
check(child, getIds(child));
}
});
};

View File

@@ -11,21 +11,7 @@ var buildVariableAssign = function (kind, id, init) {
}
};
var normalise = function (node) {
if (t.isParenthesizedExpression(node)) {
return node.expression;
} else {
return node;
}
};
var isPattern = function (node) {
return t.isPattern(normalise(node));
};
var push = function (kind, nodes, elem, parentId) {
elem = normalise(elem);
if (t.isObjectPattern(elem)) {
pushObjectPattern(kind, nodes, elem, parentId);
} else if (t.isArrayPattern(elem)) {
@@ -42,7 +28,7 @@ var pushObjectPattern = function (kind, nodes, pattern, parentId) {
var pattern2 = prop.value;
var patternId2 = t.memberExpression(parentId, prop.key);
if (isPattern(pattern2)) {
if (t.isPattern(pattern2)) {
push(kind, nodes, pattern2, patternId2);
} else {
nodes.push(buildVariableAssign(kind, pattern2, patternId2));
@@ -94,7 +80,7 @@ exports.ForOfStatement = function (node, parent, file, scope) {
if (!t.isVariableDeclaration(declar)) return;
var pattern = declar.declarations[0].id;
if (!isPattern(pattern)) return;
if (!t.isPattern(pattern)) return;
var key = t.identifier(file.generateUid("ref", scope));
node.left = t.variableDeclaration(declar.kind, [
@@ -117,7 +103,7 @@ exports.Function = function (node, parent, file, scope) {
var hasDestructuring = false;
node.params = node.params.map(function (pattern) {
if (!isPattern(pattern)) return pattern;
if (!t.isPattern(pattern)) return pattern;
hasDestructuring = true;
var parentId = t.identifier(file.generateUid("ref", scope));
@@ -146,7 +132,7 @@ exports.ExpressionStatement = function (node, parent, file, scope) {
var expr = node.expression;
if (expr.type !== "AssignmentExpression") return;
if (!isPattern(expr.left)) return;
if (!t.isPattern(expr.left)) return;
var nodes = [];
@@ -167,7 +153,7 @@ exports.VariableDeclaration = function (node, parent, file, scope) {
var hasPattern = false;
_.each(node.declarations, function (declar) {
if (isPattern(declar.id)) {
if (t.isPattern(declar.id)) {
hasPattern = true;
return false;
}

View File

@@ -1,89 +0,0 @@
// Based upon the excellent jsx-transpiler by Ingvar Stepanyan (RReverser)
// https://github.com/RReverser/jsx-transpiler
var esutils = require("esutils");
var t = require("../../types");
var _ = require("lodash");
var JSX_ANNOTATION_REGEX = /^\*\s*@jsx\s+([^\s]+)/;
exports.Program = function (node, parent, file) {
var jsx = "React.DOM";
// looking for namespace annotation
_.each(node.leadingComments, function (comment) {
var matches = JSX_ANNOTATION_REGEX.exec(comment.value);
if (matches) jsx = matches[1];
});
// prebuilding AST node
file.jsx = jsx.split(".").map(t.identifier).reduce(function (object, property) {
return t.memberExpression(object, property);
});
};
exports.XJSIdentifier = function (node) {
if (esutils.keyword.isIdentifierName(node.name)) {
node.type = "Identifier";
} else {
return t.literal(node.name);
}
};
exports.XJSNamespacedName = function () {
throw new Error("Namespace tags are not supported. ReactJSX is not XML.");
};
exports.XJSMemberExpression = {
exit: function (node) {
node.computed = t.isLiteral(node.property);
node.type = "MemberExpression";
}
};
exports.XJSExpressionContainer = function (node) {
return node.expression;
};
exports.XJSAttribute = {
exit: function (node) {
var value = node.value || t.literal(true);
return t.property("init", node.name, value);
}
};
exports.XJSOpeningElement = {
exit: function (node, parent, file) {
var tagExpr = node.name;
if (t.isIdentifier(tagExpr)) {
var tagName = tagExpr.name;
if (/[a-z]/.exec(tagName[0]) || _.contains(tagName, "-")) {
tagExpr = t.memberExpression(file.jsx, tagExpr);
}
}
var props = node.attributes;
if (props.length) {
props = t.objectExpression(props);
} else {
props = t.literal(null);
}
return t.callExpression(tagExpr, [props]);
}
};
exports.XJSElement = {
exit: function (node) {
var callExpr = node.openingElement;
var children = node.children;
_.each(children, function (child) {
callExpr.arguments.push(child);
});
return t.inherits(callExpr, node);
}
};

View File

@@ -1,4 +1,5 @@
var traverse = require("../../traverse");
var util = require("../../util");
var t = require("../../types");
var _ = require("lodash");
@@ -16,6 +17,12 @@ var isVar = function (node) {
return t.isVariableDeclaration(node, { kind: "var" }) && !isLet(node);
};
var standardiseLets = function (declars) {
_.each(declars, function (declar) {
delete declar._let;
});
};
exports.VariableDeclaration = function (node) {
isLet(node);
};
@@ -32,7 +39,8 @@ exports.For = function (node, parent, file, scope) {
node.label = parent.label;
}
run(node, node.body, parent, file, scope);
var letScoping = new LetScoping(node, node.body, parent, file, scope);
letScoping.run();
if (node.label && !t.isLabeledStatement(parent)) {
// we've been given a label so let's wrap ourselves
@@ -42,12 +50,98 @@ exports.For = function (node, parent, file, scope) {
exports.BlockStatement = function (block, parent, file, scope) {
if (!t.isFor(parent)) {
run(false, block, parent, file, scope);
var letScoping = new LetScoping(false, block, parent, file, scope);
letScoping.run();
}
};
var noClosure = function (letDeclars, block, replacements) {
standardiseLets(letDeclars);
/**
* Description
*
* @param {Boolean|Node} forParent
* @param {Node} block
* @param {Node} parent
* @param {File} file
* @param {Scope} scope
*/
function LetScoping(forParent, block, parent, file, scope) {
this.forParent = forParent;
this.parent = parent;
this.scope = scope;
this.block = block;
this.file = file;
this.letReferences = {};
this.body = [];
this.info = this.getInfo();
}
/**
* Start the ball rolling.
*/
LetScoping.prototype.run = function () {
var block = this.block;
if (block._letDone) return;
block._letDone = true;
// this is a block within a `Function` so we can safely leave it be
if (t.isFunction(this.parent)) return;
// this block has no let references so let's clean up
if (!this.info.keys.length) return this.noClosure();
// returns whether or not there are any outside let references within any
// functions
var referencesInClosure = this.getLetReferences();
// no need for a closure so let's clean up
if (!referencesInClosure) return this.noClosure();
// if we're inside of a for loop then we search to see if there are any
// `break`s, `continue`s, `return`s etc
this.has = this.checkFor();
// hoist var references to retain scope
this.hoistVarDeclarations();
// set let references to plain var references
standardiseLets(this.info.declarators);
// turn letReferences into an array
var letReferences = _.values(this.letReferences);
// build the closure that we're going to wrap the block with
var fn = t.functionExpression(null, letReferences, t.blockStatement(block.body));
fn._aliasFunction = true;
// replace the current block body with the one we're going to build
block.body = this.body;
// change upper scope references with their uid if they have one
var params = this.getParams(letReferences);
// build a call and a unique id that we can assign the return value to
var call = t.callExpression(fn, params);
var ret = t.identifier(this.file.generateUid("ret", this.scope));
this.build(ret, call);
};
/**
* There are no let references accessed within a closure so we can just traverse
* through this block and replace all references that exist in a high scope to
* their uids.
*/
LetScoping.prototype.noClosure = function () {
var replacements = this.info.duplicates;
var declarators = this.info.declarators;
var block = this.block;
standardiseLets(declarators);
if (_.isEmpty(replacements)) return;
@@ -58,13 +152,17 @@ var noClosure = function (letDeclars, block, replacements) {
});
};
var standardiseLets = function (declars) {
_.each(declars, function (declar) {
delete declar._let;
});
};
/**
* Description
*
* @returns {Object}
*/
LetScoping.prototype.getInfo = function () {
var block = this.block;
var scope = this.scope;
var file = this.file;
var getInfo = function (block, file, scope) {
var opts = {
// array of `Identifier` names of let variables that appear lexically out of
// this scope but should be accessible - eg. `ForOfStatement`.left
@@ -110,15 +208,23 @@ var getInfo = function (block, file, scope) {
return opts;
};
var checkFor = function (forParent, block) {
/**
* If we're inside of a `For*Statement` then traverse it and check if it has one
* of the following node types `ReturnStatement`, `BreakStatement`,
* `ContinueStatement` and replace it with a return value we can track later on.
*
* @returns {Object}
*/
LetScoping.prototype.checkFor = function () {
var has = {
hasContinue: false,
hasReturn: false,
hasBreak: false,
};
if (forParent) {
traverse(block, function (node) {
if (this.forParent) {
traverse(this.block, function (node) {
var replace;
if (t.isFunction(node) || t.isFor(node)) {
@@ -132,7 +238,7 @@ var checkFor = function (forParent, block) {
} else if (t.isReturnStatement(node)) {
has.hasReturn = true;
replace = t.returnStatement(t.objectExpression([
t.property("init", t.identifier("v"), node.argument)
t.property("init", t.identifier("v"), node.argument || t.identifier("undefined"))
]));
}
@@ -143,38 +249,59 @@ var checkFor = function (forParent, block) {
return has;
};
var hoistVarDeclarations = function (block, pushDeclar) {
traverse(block, function (node) {
/**
* Hoist all var declarations in this block to before it so they retain scope
* once we wrap everything is in a closure.
*/
LetScoping.prototype.hoistVarDeclarations = function () {
var self = this;
traverse(this.block, function (node) {
if (t.isForStatement(node)) {
if (isVar(node.init)) {
node.init = t.sequenceExpression(pushDeclar(node.init));
node.init = t.sequenceExpression(self.pushDeclar(node.init));
}
} else if (t.isFor(node)) {
if (isVar(node.left)) {
node.left = node.left.declarations[0].id;
}
} else if (isVar(node)) {
return pushDeclar(node).map(t.expressionStatement);
return self.pushDeclar(node).map(t.expressionStatement);
} else if (t.isFunction(node)) {
return false;
}
});
};
var getParams = function (info, letReferences) {
var params = _.cloneDeep(letReferences);
/**
* Build up a parameter list that we'll call our closure wrapper with, replacing
* all duplicate ids with their uid.
*
* @param {Array} params
* @returns {Array}
*/
LetScoping.prototype.getParams = function (params) {
var info = this.info;
params = _.cloneDeep(params);
_.each(params, function (param) {
param.name = info.duplicates[param.name] || param.name;
});
return params;
};
var getLetReferences = function (block, info, letReferences) {
/**
* Get all let references within this block. Stopping whenever we reach another
* block.
*/
LetScoping.prototype.getLetReferences = function () {
var closurify = false;
var self = this;
// traverse through this block, stopping on functions and checking if they
// contain any outside let references
traverse(block, function (node, parent, scope) {
traverse(this.block, function (node, parent, scope) {
if (t.isFunction(node)) {
traverse(node, function (node, parent) {
// not an identifier so we have no use
@@ -190,10 +317,10 @@ var getLetReferences = function (block, info, letReferences) {
closurify = true;
// this key doesn't appear just outside our scope
if (!_.contains(info.outsideKeys, node.name)) return;
if (!_.contains(self.info.outsideKeys, node.name)) return;
// push this badboy
letReferences[node.name] = node;
self.letReferences[node.name] = node;
});
return false;
@@ -205,121 +332,100 @@ var getLetReferences = function (block, info, letReferences) {
return closurify;
};
var buildPushDeclar = function (body) {
return function (node) {
body.push(t.variableDeclaration(node.kind, node.declarations.map(function (declar) {
return t.variableDeclarator(declar.id);
})));
/**
* Turn a `VariableDeclaration` into an array of `AssignmentExpressions` with
* their declarations hoisted to before the closure wrapper.
*
* @param {Node} node VariableDeclaration
* @returns {Array}
*/
var replace = [];
LetScoping.prototype.buildPushDeclar = function (node) {
this.body.push(t.variableDeclaration(node.kind, node.declarations.map(function (declar) {
return t.variableDeclarator(declar.id);
})));
_.each(node.declarations, function (declar) {
if (!declar.init) return;
var replace = [];
var expr = t.assignmentExpression("=", declar.id, declar.init);
replace.push(t.inherits(expr, declar));
});
_.each(node.declarations, function (declar) {
if (!declar.init) return;
return replace;
};
var expr = t.assignmentExpression("=", declar.id, declar.init);
replace.push(t.inherits(expr, declar));
});
return replace;
};
var run = function (forParent, block, parent, file, scope) {
if (block._letDone) return;
block._letDone = true;
var info = getInfo(block, file, scope);
var declarators = info.declarators;
var letKeys = info.keys;
// this is a block within a `Function` so we can safely leave it be
if (t.isFunction(parent)) return;
// this block has no let references so let's clean up
if (!letKeys.length) return noClosure(declarators, block, info.duplicates);
// outside let references that we need to wrap
var letReferences = {};
// returns whether or not there are any outside let references within any
// functions
var closurify = getLetReferences(block, info, letReferences);
letReferences = _.values(letReferences);
// no need for a closure so let's clean up
if (!closurify) return noClosure(declarators, block, info.duplicates);
// if we're inside of a for loop then we search to see if there are any
// `break`s, `continue`s, `return`s etc
var has = checkFor(forParent, block);
var body = [];
// hoist a `VariableDeclaration` and add `AssignmentExpression`s in it's place
var pushDeclar = buildPushDeclar(body);
// hoist var references to retain scope
hoistVarDeclarations(block, pushDeclar);
// set let references to plain var references
standardiseLets(declarators);
// build the closure that we're going to wrap the block with
var fn = t.functionExpression(null, letReferences, t.blockStatement(block.body));
fn._aliasFunction = true;
// replace the current block body with the one we've built
block.body = body;
// change duplicate let references to their uid if they have one
var params = getParams(info, letReferences);
var call = t.callExpression(fn, params);
var ret = t.identifier(file.generateUid("ret", scope));
/**
* Push the closure to the body.
*
* @param {Node} ret Identifier
* @param {Node} call CallExpression
*/
LetScoping.prototype.build = function (ret, call) {
var has = this.has;
if (has.hasReturn || has.hasBreak || has.hasContinue) {
body.push(t.variableDeclaration("var", [
t.variableDeclarator(ret, call)
]));
this.buildHas(ret, call);
} else {
this.body.push(t.expressionStatement(call));
}
};
var retCheck;
/**
* Description
*
* @param {Node} ret Identifier
* @param {Node} call CallExpression
*/
if (has.hasReturn) {
// typeof ret === "object"
retCheck = t.ifStatement(
t.binaryExpression("===", t.unaryExpression("typeof", ret, true), t.literal("object")),
t.returnStatement(t.memberExpression(ret, t.identifier("v")))
);
LetScoping.prototype.buildHas = function (ret, call) {
var body = this.body;
// there's no `break` or `continue` so we can just push in the `if`
if (!has.hasBreak && !has.hasContinue) {
body.push(retCheck);
}
body.push(t.variableDeclaration("var", [
t.variableDeclarator(ret, call)
]));
var forParent = this.forParent;
var retCheck;
var has = this.has;
var cases = [];
if (has.hasReturn) {
// typeof ret === "object"
retCheck = util.template("let-scoping-return", {
RETURN: ret
});
}
if (has.hasBreak || has.hasContinue) {
// ensure that the parent has a label as we're building a switch and we
// need to be able to access it
var label = forParent.label = forParent.label || t.identifier(this.file.generateUid("loop", this.scope));
if (has.hasBreak) {
cases.push(t.switchCase(t.literal("break"), [t.breakStatement(label)]));
}
if (has.hasBreak || has.hasContinue) {
// ensure that the parent has a label as we're building a switch and we
// need to be able to access it
var label = forParent.label = forParent.label || t.identifier(file.generateUid("loop", scope));
if (has.hasContinue) {
cases.push(t.switchCase(t.literal("continue"), [t.continueStatement(label)]));
}
var cases = [];
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)]));
}
if (has.hasReturn) {
cases.push(t.switchCase(null, [retCheck]));
}
if (has.hasReturn) {
cases.push(t.switchCase(null, [retCheck]));
}
if (cases.length === 1) {
var single = cases[0];
body.push(t.ifStatement(
t.binaryExpression("===", ret, single.test),
single.consequent[0]
));
} else {
body.push(t.switchStatement(ret, cases));
}
} else {
body.push(t.expressionStatement(call));
if (has.hasReturn) body.push(retCheck);
}
};

View File

@@ -1,6 +0,0 @@
var _ = require("lodash");
exports.Literal = function (node) {
// TODO: remove this when the new code generator is released
if (_.isNumber(node.value)) delete node.raw;
};

View File

@@ -1,5 +1,124 @@
var t = require("../../types");
var _ = require("lodash");
// Based upon the excellent jsx-transpiler by Ingvar Stepanyan (RReverser)
// https://github.com/RReverser/jsx-transpiler
// jsx
var esutils = require("esutils");
var t = require("../../types");
var _ = require("lodash");
exports.XJSIdentifier = function (node) {
if (esutils.keyword.isIdentifierName(node.name)) {
node.type = "Identifier";
} else {
return t.literal(node.name);
}
};
exports.XJSNamespacedName = function (node, parent, file) {
throw file.errorWithNode(node, "Namespace tags are not supported. ReactJSX is not XML.");
};
exports.XJSMemberExpression = {
exit: function (node) {
node.computed = t.isLiteral(node.property);
node.type = "MemberExpression";
}
};
exports.XJSExpressionContainer = function (node) {
return node.expression;
};
exports.XJSAttribute = {
exit: function (node) {
var value = node.value || t.literal(true);
return t.property("init", node.name, value);
}
};
exports.XJSOpeningElement = {
exit: function (node) {
var tagExpr = node.name;
var args = [];
var tagName;
if (t.isIdentifier(tagExpr)) {
tagName = tagExpr.name;
} else if (t.isLiteral(tagExpr)) {
tagName = tagExpr.value;
}
if (tagName && (/[a-z]/.exec(tagName[0]) || _.contains(tagName, "-"))) {
args.push(t.literal(tagName));
} else {
args.push(tagExpr);
}
var props = node.attributes;
if (props.length) {
var _props = [];
var objs = [];
var pushProps = function () {
if (!_props.length) return;
objs.push(t.objectExpression(_props));
_props = [];
};
while (props.length) {
var prop = props.shift();
if (t.isXJSSpreadAttribute(prop)) {
pushProps();
objs.push(prop.argument);
} else {
_props.push(prop);
}
}
pushProps();
if (objs.length === 1) {
props = objs[0];
} else {
if (!t.isObjectExpression(objs[0])) {
objs.unshift(t.objectExpression([]));
}
props = t.callExpression(
t.memberExpression(t.identifier("React"), t.identifier("__spread")),
objs
);
}
} else {
props = t.literal(null);
}
args.push(props);
tagExpr = t.memberExpression(t.identifier("React"), t.identifier("createElement"));
return t.callExpression(tagExpr, args);
}
};
exports.XJSElement = {
exit: function (node) {
var callExpr = node.openingElement;
var childrenToRender = node.children.filter(function(child) {
return !(t.isLiteral(child) && _.isString(child.value) && child.value.match(/^[ \t]*[\r\n][ \t\r\n]*$/));
});
_.each(childrenToRender, function (child) {
callExpr.arguments.push(child);
});
return t.inherits(callExpr, node);
}
};
// display names
var addDisplayName = function (id, call) {
if (!call || !t.isCallExpression(call)) return;

View File

@@ -40,8 +40,6 @@ function traverse(parent, callbacks, opts) {
// type is blacklisted
if (_.contains(blacklistTypes, node.type)) return;
var result;
// replace node
var maybeReplace = function (result) {
if (result === false) return;
@@ -54,12 +52,11 @@ function traverse(parent, callbacks, opts) {
// enter
if (callbacks.enter) {
result = callbacks.enter(node, parent, opts2.scope);
var result = callbacks.enter(node, parent, opts2.scope);
maybeReplace(result);
// stop iteration
if (result === false) return;
maybeReplace(result);
}
// traverse node
@@ -114,25 +111,18 @@ traverse.hasType = function (tree, type, blacklistTypes) {
var has = false;
if (_.isArray(tree)) {
// array of nodes, find the first
return tree.some(function (node) {
return traverse.hasType(node, type, blacklistTypes);
});
} else {
// the node we're searching in is blacklisted
if (_.contains(blacklistTypes, tree.type)) return false;
// the node we're searching in is blacklisted
if (_.contains(blacklistTypes, tree.type)) return false;
// the type we're looking for is the same as the passed node
if (tree.type === type) return true;
// the type we're looking for is the same as the passed node
if (tree.type === type) return true;
traverse(tree, function (node) {
if (node.type === type) {
has = true;
return false;
}
}, { blacklist: blacklistTypes });
}
traverse(tree, function (node) {
if (node.type === type) {
has = true;
return false;
}
}, { blacklist: blacklistTypes });
return has;
};

View File

@@ -156,37 +156,26 @@ t.toBlock = function (node, parent) {
return t.blockStatement(node);
};
t.getIds = function (node, map) {
t.getIds = function (node, map, ignoreTypes) {
ignoreTypes = ignoreTypes || [];
var search = [node];
var ids = {};
while (search.length) {
var id = search.shift();
if (!id) continue;
if (_.contains(ignoreTypes, id.type)) continue;
var nodeKey = t.getIds.nodes[id.type];
var arrKey = t.getIds.arrays[id.type];
if (t.isIdentifier(id)) {
ids[id.name] = id;
} else if (t.isArrayPattern(id)) {
_.each(id.elements, function (elem) {
search.push(elem);
});
} else if (t.isAssignmentExpression(id)) {
search.push(id.left);
} else if (t.isObjectPattern(id)) {
_.each(id.properties, function (prop) {
search.push(prop.value);
});
} else if (t.isVariableDeclaration(id)) {
search = search.concat(id.declarations);
} else if (t.isImportSpecifier(id) || t.isExportSpecifier(id) || t.isVariableDeclarator(id) || t.isFunctionDeclaration(id) || t.isClassDeclaration(id)) {
search.push(id.id);
} else if (t.isSpreadElement(id)) {
search.push(id.argument);
} else if (t.isExportDeclaration(id) || t.isImportDeclaration(id)) {
search = search.concat(id.specifiers);
} else if (t.isMemberExpression(id)) {
search.push(id.object);
} else if (t.isParenthesizedExpression(id)) {
search.push(id.expression);
} else if (nodeKey) {
if (id[nodeKey]) search.push(id[nodeKey]);
} else if (arrKey) {
search = search.concat(id[arrKey] || []);
}
}
@@ -194,11 +183,34 @@ t.getIds = function (node, map) {
return ids;
};
t.getIds.nodes = {
AssignmentExpression: "left",
ImportSpecifier: "id",
ExportSpecifier: "id",
VariableDeclarator: "id",
FunctionDeclaration: "id",
ClassDeclaration: "id",
ParenthesizedExpression: "expression",
MemeberExpression: "object",
SpreadElement: "argument",
Property: "value"
};
t.getIds.arrays = {
ExportDeclaration: "specifiers",
ImportDeclaration: "specifiers",
VariableDeclaration: "declarations",
ArrayPattern: "elements",
ObjectPattern: "properties"
};
t.inherits = function (child, parent) {
child.loc = parent.loc;
child.end = parent.end;
child.range = parent.range;
child.start = parent.start;
child.loc = parent.loc;
child.end = parent.end;
child.range = parent.range;
child.start = parent.start;
child.leadingComments = parent.leadingComments;
child.trailingComments = parent.trailingComments;
return child;
};

View File

@@ -3,6 +3,7 @@
"ArrayPattern": ["elements"],
"ArrowFunctionExpression": ["params", "defaults", "rest", "body"],
"AssignmentExpression": ["left", "right"],
"AwaitExpression": ["argument"],
"BinaryExpression": ["left", "right"],
"BlockStatement": ["body"],
"BreakStatement": ["label"],
@@ -70,6 +71,6 @@
"XJSMemberExpression": ["object", "property"],
"XJSNamespacedName": ["namespace", "name"],
"XJSOpeningElement": ["name", "attributes"],
"XJSSpreadAttribute": [],
"XJSSpreadAttribute": ["argument"],
"YieldExpression": ["argument"]
}

View File

@@ -11,6 +11,12 @@ var _ = require("lodash");
exports.inherits = util.inherits;
exports.canCompile = function (filename, altExts) {
var exts = altExts || [".js", ".jsx", ".es6"];
var ext = path.extname(filename);
return _.contains(exts, ext);
};
exports.resolve = function (loc) {
try {
return require.resolve(loc);
@@ -19,6 +25,10 @@ exports.resolve = function (loc) {
}
};
exports.trimRight = function (str) {
return str.replace(/[\n\s]+$/g, "");
};
exports.list = function (val) {
return val ? val.split(",") : [];
};
@@ -46,11 +56,6 @@ exports.isAbsolute = function (loc) {
return false;
};
exports.canCompile = function (filename) {
var ext = path.extname(filename);
return _.contains([".js", ".es6"], ext);
};
exports.sourceMapToComment = function (map) {
var json = JSON.stringify(map);
var base64 = new Buffer(json).toString("base64");
@@ -111,6 +116,11 @@ exports.template = function (name, nodes, keepExpression) {
var template = exports.templates[name];
if (!template) throw new ReferenceError("unknown template " + name);
if (nodes === true) {
keepExpression = true;
nodes = null;
}
template = _.cloneDeep(template);
var inherits = false;
@@ -192,13 +202,14 @@ exports.parse = function (opts, code, callback) {
var tokens = [];
var ast = acorn.parse(code, {
preserveParens: true,
ecmaVersion: Infinity,
strictMode: true,
onComment: comments,
locations: true,
onToken: tokens,
ranges: true
allowReturnOutsideFunction: true,
preserveParens: true,
ecmaVersion: Infinity,
strictMode: true,
onComment: comments,
locations: true,
onToken: tokens,
ranges: true
});
estraverse.attachComments(ast, comments, tokens);

View File

@@ -1,7 +1,7 @@
{
"name": "6to5",
"description": "Turn ES6 code into readable vanilla ES5 with source maps",
"version": "1.11.2",
"version": "1.12.2",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://github.com/6to5/6to5",
"repository": {
@@ -44,19 +44,19 @@
"es6-symbol": "0.1.1",
"regexpu": "0.3.0",
"source-map": "0.1.40",
"regenerator-6to5": "https://github.com/6to5/regenerator-6to5/archive/b7bc53e1a655879974aad53a8ceb93a70efaa08d.tar.gz",
"regenerator-6to5": "https://github.com/6to5/regenerator-6to5/archive/62d1bfcb331dcf0bbcdbbee8043da0c6408f09cf.tar.gz",
"chokidar": "0.10.5",
"source-map-support": "0.2.8",
"esutils": "1.1.4",
"acorn-6to5": "https://github.com/6to5/acorn-6to5/archive/f5110383517eef0bea78c2da2a1fb01fbed74e4e.tar.gz",
"acorn-6to5": "https://github.com/6to5/acorn-6to5/archive/0384a0d51f630f66ed591769c1765581a17d2124.tar.gz",
"estraverse": "^1.7.0"
},
"devDependencies": {
"istanbul": "0.3.2",
"matcha": "0.5.0",
"matcha": "0.6.0",
"mocha": "2.0.1",
"uglify-js": "2.4.15",
"browserify": "6.2.0",
"browserify": "6.3.2",
"rimraf": "2.2.8",
"jshint": "2.5.10",
"chai": "^1.9.2"

1
polyfill.js Normal file
View File

@@ -0,0 +1 @@
module.exports = require("./lib/6to5/polyfill");

View File

@@ -5,9 +5,11 @@ var humanise = function (val) {
return val.replace(/-/g, " ");
};
var readFile = function (filename) {
var readFile = exports.readFile = function (filename) {
if (fs.existsSync(filename)) {
return fs.readFileSync(filename, "utf8").trim();
var file = fs.readFileSync(filename, "utf8").trim();
file = file.replace(/\r\n/g, "\n");
return file;
} else {
return "";
}

View File

@@ -1,4 +1,5 @@
var readdir = require("fs-readdir-recursive");
var helper = require("./_helper");
var assert = require("assert");
var rimraf = require("rimraf");
var mkdirp = require("mkdirp");
@@ -11,15 +12,11 @@ var _ = require("lodash");
var fixtureLoc = __dirname + "/fixtures/bin";
var tmpLoc = __dirname + "/tmp";
var readFile = function (filename) {
return fs.readFileSync(filename, "utf8").trim();
};
var readDir = function (loc) {
var files = {};
if (fs.existsSync(loc)) {
_.each(readdir(loc), function (filename) {
var contents = readFile(loc + "/" + filename);
var contents = helper.readFile(loc + "/" + filename);
files[filename] = contents;
});
}
@@ -51,6 +48,7 @@ var assertTest = function (stdout, stderr, opts) {
var expectStdout = opts.stdout.trim();
stdout = stdout.trim();
stdout = stdout.replace(/\\/g, "/");
if (opts.stdout) {
if (opts.stdoutContains) {
@@ -63,7 +61,7 @@ var assertTest = function (stdout, stderr, opts) {
}
_.each(opts.outFiles, function (expect, filename) {
var actual = readFile(filename);
var actual = helper.readFile(filename);
chai.expect(actual).to.equal(expect, "out-file " + filename);
});
};
@@ -138,7 +136,7 @@ _.each(fs.readdirSync(fixtureLoc), function (binName) {
_.each(["stdout", "stdin", "stderr"], function (key) {
var loc = testLoc + "/" + key + ".txt";
if (fs.existsSync(loc)) {
opts[key] = readFile(loc);
opts[key] = helper.readFile(loc);
} else {
opts[key] = opts[key] || "";
}
@@ -151,7 +149,3 @@ _.each(fs.readdirSync(fixtureLoc), function (binName) {
});
});
});
after(function () {
rimraf.sync(tmpLoc);
});

View File

@@ -1,5 +0,0 @@
({ t: t }) = obj;
({
t: { C: C }
}) = obj;
({ a, b, c }) = obj;

View File

@@ -1,5 +0,0 @@
({ t: t }) = obj;
({
t: { C: C }
}) = obj;
({ a, b, c }) = obj;

View File

@@ -1,2 +1 @@
[a, b] = f();
({ x }) = e();

View File

@@ -4,6 +4,3 @@ var _ref = f();
a = _ref[0];
b = _ref[1];
var _ref2 = e();
x = _ref2.x;

View File

@@ -1,3 +0,0 @@
/** @jsx CUSTOM_DOM */
<a></a>

View File

@@ -1,5 +0,0 @@
/** @jsx CUSTOM_DOM */
"use strict";
CUSTOM_DOM.a(null);

View File

@@ -1 +0,0 @@
<X>{}</X>

View File

@@ -1,3 +0,0 @@
"use strict";
X(null, null);

View File

@@ -1,2 +0,0 @@
<X data-prop={x ? <Y prop={2} /> : <Z>
</Z>}></X>

View File

@@ -1,7 +0,0 @@
"use strict";
X({
"data-prop": x ? Y({
prop: 2
}) : Z(null, "\n")
});

View File

@@ -1,5 +0,0 @@
(<X>{a}</X>);
(<X>{a} {b}</X>);
(<X prop={a} yes></X>);

View File

@@ -1,10 +0,0 @@
"use strict";
(X(null, a));
(X(null, a, " ", b));
(X({
prop: a,
yes: true
}));

View File

@@ -1 +0,0 @@
<a></a>

View File

@@ -1,3 +0,0 @@
"use strict";
React.DOM.a(null);

View File

@@ -1 +0,0 @@
<Test.X></Test.X>

View File

@@ -1,3 +0,0 @@
"use strict";
Test.X(null);

View File

@@ -1 +0,0 @@
<Test:X></Test:X>

View File

@@ -1,3 +0,0 @@
(<X />);
(<X prop="1" />);

View File

@@ -1,7 +0,0 @@
"use strict";
(X(null));
(X({
prop: "1"
}));

View File

@@ -1 +0,0 @@
<X></X>

View File

@@ -1,3 +0,0 @@
"use strict";
X(null);

View File

@@ -1,3 +0,0 @@
(<X prop="2"><Y /></X>);
(<X prop="2"><Y /><Z /></X>);

View File

@@ -1,9 +0,0 @@
"use strict";
(X({
prop: "2"
}, Y(null)));
(X({
prop: "2"
}, Y(null), Z(null)));

View File

@@ -1,13 +0,0 @@
(<X> </X>);
(<X>
</X>);
(<X>
string
</X>);
(<X>
string
string
</X>);

View File

@@ -1,9 +0,0 @@
"use strict";
(X(null, " "));
(X(null, "\n"));
(X(null, "\n string\n"));
(X(null, "\n string\n string\n "));

View File

@@ -0,0 +1,10 @@
for (let i in nums) {
fns.push(function () { return i; });
if (i === 1) {
continue;
} else if (i === 2) {
break;
} else if (i === 3) {
return i;
}
}

View File

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

View File

@@ -0,0 +1,4 @@
for (let i in nums) {
fns.push(function () { return i; });
break;
}

View File

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

View File

@@ -0,0 +1,4 @@
for (let i in nums) {
fns.push(function () { return i; });
continue;
}

View File

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

View File

@@ -0,0 +1,4 @@
for (let i in nums) {
fns.push(function () { return i; });
return;
}

View File

@@ -0,0 +1,14 @@
"use strict";
for (var i in nums) {
var _ret = (function (i) {
fns.push(function () {
return i;
});
return {
v: undefined
};
})(i);
if (typeof _ret === "object") return _ret.v;
}

View File

@@ -0,0 +1,4 @@
for (let i in nums) {
fns.push(function () { return i; });
return i;
}

View File

@@ -0,0 +1,14 @@
"use strict";
for (var i in nums) {
var _ret = (function (i) {
fns.push(function () {
return i;
});
return {
v: i
};
})(i);
if (typeof _ret === "object") return _ret.v;
}

View File

@@ -0,0 +1,3 @@
function test() {
let foo = "bar";
}

View File

@@ -0,0 +1,5 @@
"use strict";
function test() {
var foo = "bar";
}

View File

@@ -0,0 +1 @@
let test = "foo";

View File

@@ -0,0 +1,3 @@
"use strict";
var test = "foo";

View File

@@ -0,0 +1,3 @@
function foo(...test) {
}

View File

@@ -0,0 +1,5 @@
"use strict";
function foo() {
var test = customNamespace.slice.call(arguments);
}

View File

@@ -0,0 +1,3 @@
{
"runtime": "customNamespace"
}

View File

@@ -0,0 +1,3 @@
var obj = {
"foobar": "lol"
};

View File

@@ -0,0 +1,5 @@
"use strict";
var obj = {
foobar: "lol"
};

View File

@@ -0,0 +1,3 @@
function foo(...test) {
}

View File

@@ -0,0 +1,5 @@
"use strict";
function foo() {
var test = to5Runtime.slice.call(arguments);
}

View File

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

View File

@@ -0,0 +1,3 @@
#!/usr/bin/env node
foobar();

View File

@@ -0,0 +1,4 @@
#!/usr/bin/env node
"use strict";
foobar();

View File

@@ -0,0 +1 @@
<div>&nbsp; </div>;

View File

@@ -0,0 +1 @@
React.createElement("div", null, "\u00A0 ");

View File

@@ -0,0 +1 @@
<div>&nbsp;</div>;

View File

@@ -0,0 +1 @@
React.createElement("div", null, "\u00A0");

View File

@@ -0,0 +1,13 @@
var x = (
<div>
{/* A comment at the beginning */}
{/* A second comment at the beginning */}
<span>
{/* A nested comment */}
</span>
{/* A sandwiched comment */}
<br />
{/* A comment at the end */}
{/* A second comment at the end */}
</div>
);

View File

@@ -0,0 +1,11 @@
var x = (React.createElement("div", null,
/* A comment at the beginning */
/* A second comment at the beginning */
React.createElement("span", null
/* A nested comment */
),
/* A sandwiched comment */
React.createElement("br", null)
/* A comment at the end */
/* A second comment at the end */
));

View File

@@ -0,0 +1,10 @@
var x = (
<div
/* a multi-line
comment */
attr1="foo">
<span // a double-slash comment
attr2="bar"
/>
</div>
);

View File

@@ -0,0 +1,8 @@
var x = (React.createElement("div", {
/* a multi-line
comment */
attr1: "foo"},
React.createElement("span", {// a double-slash comment
attr2: "bar"}
)
));

View File

@@ -0,0 +1,3 @@
<Component
{...this.props}
sound="moo" />

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