Compare commits
326 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2a29f70bba | ||
|
|
6ccb8957bd | ||
|
|
dc45415ee0 | ||
|
|
98ca541fde | ||
|
|
8328f638c2 | ||
|
|
5586ce280f | ||
|
|
0ca71f5e15 | ||
|
|
212776e220 | ||
|
|
4a95a9ec8f | ||
|
|
45953ffc8a | ||
|
|
9c79290bb2 | ||
|
|
cfdf6b7385 | ||
|
|
907e0e0f86 | ||
|
|
f3bd9cbcb8 | ||
|
|
3bd14f9e07 | ||
|
|
102b4b3d1e | ||
|
|
6564f1ff76 | ||
|
|
58d7a5e069 | ||
|
|
f5db53cebe | ||
|
|
2da010fcae | ||
|
|
52b99bdf93 | ||
|
|
9d7e953451 | ||
|
|
b1252b865b | ||
|
|
068b1341d9 | ||
|
|
20eb143915 | ||
|
|
1302a86bf2 | ||
|
|
b7831f1d7b | ||
|
|
e46cabb21f | ||
|
|
fff06a047e | ||
|
|
6b0320fc83 | ||
|
|
5dde63fa0a | ||
|
|
672118149a | ||
|
|
5e0236d9a7 | ||
|
|
5101664e7d | ||
|
|
2d684a06d3 | ||
|
|
e31bad8f42 | ||
|
|
644b4373fc | ||
|
|
62f37c1e62 | ||
|
|
fc0e89463b | ||
|
|
56b6a795a4 | ||
|
|
17b34a2959 | ||
|
|
c4da0253c5 | ||
|
|
5f2df40f6d | ||
|
|
7d20a9b882 | ||
|
|
ee0ac9f149 | ||
|
|
c5d3f42d8a | ||
|
|
d162919a53 | ||
|
|
d1f712344d | ||
|
|
e985912b54 | ||
|
|
97a21e4a34 | ||
|
|
d8fb7812f7 | ||
|
|
bfe63f5885 | ||
|
|
44ca6873a3 | ||
|
|
2f66ea7338 | ||
|
|
70967cf53c | ||
|
|
dc117a74ae | ||
|
|
b0f32a822d | ||
|
|
fd99ea1749 | ||
|
|
572129542d | ||
|
|
6f53980bfc | ||
|
|
348af1990d | ||
|
|
bd5f350728 | ||
|
|
958fa282f4 | ||
|
|
31e6b18346 | ||
|
|
d17ac92a3f | ||
|
|
188bcb70f7 | ||
|
|
b8bd11a0e7 | ||
|
|
45bc74efe7 | ||
|
|
7eb169a894 | ||
|
|
eed4f312d8 | ||
|
|
44e4dc970f | ||
|
|
5d32432e67 | ||
|
|
9c9af6dbbd | ||
|
|
70cd650e10 | ||
|
|
c7bb00d58d | ||
|
|
623be068c4 | ||
|
|
71f5c9791d | ||
|
|
3e6e86d073 | ||
|
|
a0fb398ca2 | ||
|
|
71b9f19e6a | ||
|
|
c45ce58f0c | ||
|
|
d32f587e3c | ||
|
|
9e1874ba89 | ||
|
|
35fdc5c5d8 | ||
|
|
a4035fc257 | ||
|
|
42e3dc7a70 | ||
|
|
cdccf24515 | ||
|
|
c8cd5c108b | ||
|
|
2b95b876e1 | ||
|
|
f801772fc2 | ||
|
|
8ad678e5bc | ||
|
|
35c49dbef7 | ||
|
|
119314df74 | ||
|
|
51e336b037 | ||
|
|
7d446807a9 | ||
|
|
8afdeaf557 | ||
|
|
4df50954a2 | ||
|
|
70b6317865 | ||
|
|
5ebdc44297 | ||
|
|
a4659fd239 | ||
|
|
19bfa4a35b | ||
|
|
f7fff7d35e | ||
|
|
130e0ebe6b | ||
|
|
69c836fc8d | ||
|
|
f62a3ef394 | ||
|
|
7a6e568940 | ||
|
|
65998c3437 | ||
|
|
160de340b0 | ||
|
|
76ca40f698 | ||
|
|
01ed824b5c | ||
|
|
6b0dbc4486 | ||
|
|
2648268f30 | ||
|
|
8cf5bf7037 | ||
|
|
60961bc3ff | ||
|
|
df16bc17e7 | ||
|
|
5337ab5a08 | ||
|
|
2eaeebcce4 | ||
|
|
ad71010144 | ||
|
|
864169c1eb | ||
|
|
930d7f9aa6 | ||
|
|
ed40ec03d1 | ||
|
|
73062ae240 | ||
|
|
bafa3e0d4c | ||
|
|
f3d2b2bb81 | ||
|
|
a74b67d4eb | ||
|
|
625416862f | ||
|
|
8dda8838ba | ||
|
|
96d3a25213 | ||
|
|
727208f376 | ||
|
|
1b046a6ecb | ||
|
|
3b8ed0d401 | ||
|
|
d4c98d7738 | ||
|
|
4e44af819f | ||
|
|
a65acd73ca | ||
|
|
b7cb2bcb7b | ||
|
|
5ac4dc0541 | ||
|
|
99ddd02b0a | ||
|
|
19cfee14fd | ||
|
|
fea487bf91 | ||
|
|
ff2cbd5a2e | ||
|
|
12e01f9e71 | ||
|
|
f62436909d | ||
|
|
e42c1adeb6 | ||
|
|
e30dbbab94 | ||
|
|
e3daa28e60 | ||
|
|
9e5d94126c | ||
|
|
95798bee0b | ||
|
|
63f25ab038 | ||
|
|
27a8f2d2ea | ||
|
|
78434bb404 | ||
|
|
82833a8901 | ||
|
|
93d5288d71 | ||
|
|
5d3074b460 | ||
|
|
a57475abc9 | ||
|
|
09e68d8d46 | ||
|
|
ee850c3aeb | ||
|
|
ff5a149cec | ||
|
|
957118fb41 | ||
|
|
e7ad0a9741 | ||
|
|
24f4b041c7 | ||
|
|
4c77d04b56 | ||
|
|
e945f0d10f | ||
|
|
fb04b2561f | ||
|
|
a4f8b41507 | ||
|
|
1fb6018e9c | ||
|
|
bca233d22c | ||
|
|
c78703e194 | ||
|
|
43fdbe3d6c | ||
|
|
8650ca7d55 | ||
|
|
3a0c226a34 | ||
|
|
73e8bdd048 | ||
|
|
e7c52a734e | ||
|
|
5a81b02569 | ||
|
|
999baf2888 | ||
|
|
70b25e8942 | ||
|
|
2ddbd4eecc | ||
|
|
7520807df3 | ||
|
|
974b71bcc3 | ||
|
|
0aee3c06ec | ||
|
|
a4382580fc | ||
|
|
166b2eda87 | ||
|
|
83c23d266f | ||
|
|
a9db70b60d | ||
|
|
5d90c442cb | ||
|
|
32606ddb93 | ||
|
|
330f6910c6 | ||
|
|
4ca8a0e6e2 | ||
|
|
f097ddeac3 | ||
|
|
1eb53dd13a | ||
|
|
75b5f32e7a | ||
|
|
f753cf4845 | ||
|
|
9a569f64da | ||
|
|
8efeae80af | ||
|
|
4df9cf6c05 | ||
|
|
7729cb4b68 | ||
|
|
307ffcd107 | ||
|
|
751557aef1 | ||
|
|
3f146b54ff | ||
|
|
19a173c622 | ||
|
|
89bcb307a2 | ||
|
|
ded1e02da7 | ||
|
|
564ba67190 | ||
|
|
00c964ed19 | ||
|
|
3ab88e02c7 | ||
|
|
bb2fc830eb | ||
|
|
c6a542fd1d | ||
|
|
553eb2d45e | ||
|
|
b5f3c3f4cc | ||
|
|
5d83638583 | ||
|
|
f7186980e5 | ||
|
|
0eaaaa503e | ||
|
|
51dff364db | ||
|
|
dc6129eb6a | ||
|
|
5b84b9c867 | ||
|
|
04c3027f4d | ||
|
|
95e2345b19 | ||
|
|
eafb02be31 | ||
|
|
b91997354c | ||
|
|
4b8039a00c | ||
|
|
0a0931dc2e | ||
|
|
24ace3c8c2 | ||
|
|
372c06eb80 | ||
|
|
b8121ed4d0 | ||
|
|
1f79445ee5 | ||
|
|
cb46ca60af | ||
|
|
24c0c7679f | ||
|
|
687b0f3180 | ||
|
|
e6855b974b | ||
|
|
a808742c19 | ||
|
|
d7ec337567 | ||
|
|
845f1ce65e | ||
|
|
c3f4091b6d | ||
|
|
edb880f87c | ||
|
|
e8741daee3 | ||
|
|
88563a0c26 | ||
|
|
ccd7a6560c | ||
|
|
c340597fdb | ||
|
|
e498358125 | ||
|
|
c5913564f8 | ||
|
|
662bddbaca | ||
|
|
8f540dfff3 | ||
|
|
1265bc5a92 | ||
|
|
e677c72d58 | ||
|
|
8ca854156a | ||
|
|
81ae656358 | ||
|
|
f2981b7e95 | ||
|
|
99b2e00d33 | ||
|
|
25232d3141 | ||
|
|
5b9878451a | ||
|
|
23d6fb6bb1 | ||
|
|
8d1b5c8ccb | ||
|
|
10bd7d1b91 | ||
|
|
f5d9636353 | ||
|
|
a7f713ef5a | ||
|
|
ba11069b1c | ||
|
|
c13f8a3f50 | ||
|
|
339bd2b6d9 | ||
|
|
a2843a5cb8 | ||
|
|
c31832439a | ||
|
|
b7f19221a9 | ||
|
|
46a37f4672 | ||
|
|
cfe2c19a02 | ||
|
|
649d91ef25 | ||
|
|
4d72bffa30 | ||
|
|
5889233adc | ||
|
|
7bb98352df | ||
|
|
12ebeed7c6 | ||
|
|
7d87e52377 | ||
|
|
2bab285970 | ||
|
|
00651e671e | ||
|
|
37588a6ceb | ||
|
|
a45d6960da | ||
|
|
b13aa41a75 | ||
|
|
20a4ed6140 | ||
|
|
c256e060b3 | ||
|
|
bef315efd6 | ||
|
|
2ec5390b63 | ||
|
|
f4c9dd8768 | ||
|
|
510c7a3e60 | ||
|
|
3ce9508a1c | ||
|
|
717ef280f7 | ||
|
|
8c5e7cf272 | ||
|
|
811a843be9 | ||
|
|
b7c297bb89 | ||
|
|
b7342ef4ea | ||
|
|
1a899f5e77 | ||
|
|
f2eb1643c0 | ||
|
|
9621d1bbeb | ||
|
|
3cf7b2b761 | ||
|
|
ae8b1e242b | ||
|
|
eea48f866d | ||
|
|
84d2d7b7d4 | ||
|
|
ea30a619dd | ||
|
|
87a201db22 | ||
|
|
bcc86c47bc | ||
|
|
b6df9b583b | ||
|
|
52ea7b5f59 | ||
|
|
7bff8239a1 | ||
|
|
04d79c1740 | ||
|
|
e387da7c2b | ||
|
|
53cf453480 | ||
|
|
341528ee4a | ||
|
|
5f6808ba92 | ||
|
|
0b2f1fedcb | ||
|
|
c3c94f0a4a | ||
|
|
f2d60aab9e | ||
|
|
ab6bb35a4f | ||
|
|
e11b943514 | ||
|
|
b44a6eb297 | ||
|
|
f3288ddb1f | ||
|
|
476aa44a90 | ||
|
|
c5589e9336 | ||
|
|
404eb2f972 | ||
|
|
366257915e | ||
|
|
e0cd9bdbe3 | ||
|
|
39854dc088 | ||
|
|
81132aa942 | ||
|
|
5ba2e6254b | ||
|
|
61ea720637 | ||
|
|
55357a331d | ||
|
|
5deaeba3a0 | ||
|
|
a38ae381e2 | ||
|
|
9a2e56f003 | ||
|
|
5bc78b0237 | ||
|
|
c5af8b8694 | ||
|
|
c637575cab |
3
.babelrc
3
.babelrc
@@ -1,5 +1,6 @@
|
||||
{
|
||||
"experimental": true,
|
||||
"playground": true,
|
||||
"loose": true
|
||||
"loose": true,
|
||||
"blacklist": ["es6.tailCall"]
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ root = true
|
||||
insert_final_newline = true
|
||||
charset = utf-8
|
||||
trim_trailing_whitespace = true
|
||||
insert_final_newline = true
|
||||
end_of_line = lf
|
||||
|
||||
[*.{js,json}]
|
||||
|
||||
1
.eslintignore
Normal file
1
.eslintignore
Normal file
@@ -0,0 +1 @@
|
||||
src/babel/transformation/templates
|
||||
22
.eslintrc
Normal file
22
.eslintrc
Normal file
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"parser": "babel-eslint",
|
||||
"rules": {
|
||||
"strict": 0,
|
||||
"no-underscore-dangle": 0,
|
||||
"no-unused-vars": 0,
|
||||
"curly": 0,
|
||||
"no-multi-spaces": 0,
|
||||
"key-spacing": 0,
|
||||
"no-return-assign": 0,
|
||||
"consistent-return": 0,
|
||||
"no-shadow": 0,
|
||||
"no-comma-dangle": 0,
|
||||
"no-use-before-define": 0,
|
||||
"no-empty": 0,
|
||||
"new-parens": 0,
|
||||
"no-cond-assign": 0
|
||||
},
|
||||
"env": {
|
||||
"node": true
|
||||
}
|
||||
}
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -12,4 +12,6 @@ coverage
|
||||
dist
|
||||
.package.json
|
||||
packages/babel-runtime/*.js
|
||||
packages/babel-runtime/helpers/*.js
|
||||
packages/babel-runtime/regenerator/*.js
|
||||
lib
|
||||
|
||||
58
.jscsrc
58
.jscsrc
@@ -1,58 +0,0 @@
|
||||
{
|
||||
"excludeFiles": ["lib/babel/transformation/templates"],
|
||||
"disallowSpacesInNamedFunctionExpression": {
|
||||
"beforeOpeningRoundBrace": true
|
||||
},
|
||||
"requireSpacesInAnonymousFunctionExpression": {
|
||||
"beforeOpeningRoundBrace": true
|
||||
},
|
||||
"requireSpacesInAnonymousFunctionExpression": {
|
||||
"beforeOpeningRoundBrace": true
|
||||
},
|
||||
"disallowSpacesInFunctionDeclaration": {
|
||||
"beforeOpeningRoundBrace": true
|
||||
},
|
||||
"disallowSpacesInsideArrayBrackets": true,
|
||||
"disallowSpacesInsideParentheses": true,
|
||||
"disallowSpaceAfterObjectKeys": true,
|
||||
"disallowSpaceAfterPrefixUnaryOperators": true,
|
||||
"disallowSpaceBeforePostfixUnaryOperators": true,
|
||||
"disallowSpaceBeforeBinaryOperators": [
|
||||
","
|
||||
],
|
||||
"disallowMixedSpacesAndTabs": true,
|
||||
"disallowTrailingWhitespace": true,
|
||||
"disallowYodaConditions": true,
|
||||
"disallowKeywords": [ "with" ],
|
||||
"disallowMultipleLineBreaks": true,
|
||||
"requireSpaceBeforeBlockStatements": true,
|
||||
"requireParenthesesAroundIIFE": true,
|
||||
"requireSpacesInConditionalExpression": true,
|
||||
"requireBlocksOnNewline": 1,
|
||||
"requireCommaBeforeLineBreak": true,
|
||||
"requireSpaceBeforeBinaryOperators": true,
|
||||
"requireSpaceAfterBinaryOperators": true,
|
||||
"requireLineFeedAtFileEnd": true,
|
||||
"requireCapitalizedConstructors": true,
|
||||
"requireSpacesInForStatement": true,
|
||||
"requireCurlyBraces": [
|
||||
"do"
|
||||
],
|
||||
"requireSpaceAfterKeywords": [
|
||||
"if",
|
||||
"else",
|
||||
"for",
|
||||
"while",
|
||||
"do",
|
||||
"switch",
|
||||
"case",
|
||||
"return",
|
||||
"try",
|
||||
"catch",
|
||||
"typeof",
|
||||
"function"
|
||||
],
|
||||
"validateLineBreaks": "LF",
|
||||
"validateQuoteMarks": "\"",
|
||||
"validateIndentation": 2
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
lib/babel/transformation/templates
|
||||
27
.jshintrc
27
.jshintrc
@@ -1,27 +0,0 @@
|
||||
{
|
||||
"esnext": true,
|
||||
"indent": 2,
|
||||
"freeze": true,
|
||||
"validthis": true,
|
||||
"camelcase": true,
|
||||
"unused": true,
|
||||
"eqnull": true,
|
||||
"newcap": true,
|
||||
"supernew": true,
|
||||
"noyield": true,
|
||||
"evil": true,
|
||||
"node": true,
|
||||
"boss": true,
|
||||
"expr": true,
|
||||
"undef": true,
|
||||
"maxparams": 5,
|
||||
"maxdepth": 4,
|
||||
|
||||
"globals": {
|
||||
"window": true,
|
||||
"suite": true,
|
||||
"set": true,
|
||||
"before": true,
|
||||
"bench": true
|
||||
}
|
||||
}
|
||||
@@ -13,3 +13,4 @@ CHANGELOG.md
|
||||
coverage
|
||||
vendor
|
||||
packages
|
||||
src
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
sudo: false
|
||||
language: node_js
|
||||
node_js:
|
||||
- "0.10"
|
||||
- "0.12"
|
||||
- "iojs"
|
||||
|
||||
|
||||
171
CHANGELOG.md
171
CHANGELOG.md
@@ -13,6 +13,177 @@ _Note: Gaps between patch versions are faulty/broken releases._
|
||||
|
||||
See [CHANGELOG - 6to5](CHANGELOG-6to5.md) for the pre-4.0.0 version changelog.
|
||||
|
||||
## 4.7.6
|
||||
|
||||
* **Bug Fix**
|
||||
* Fix non-Identifier/Literal computed class methods.
|
||||
* **Polish**
|
||||
* Add a fallback if `stack` on an error is unconfigurable.
|
||||
* Hoist `esModule` module declarations to the top of the file to handle circular dependencies better.
|
||||
|
||||
## 4.7.5
|
||||
|
||||
* **Bug Fix**
|
||||
* Don't remap` break`s to call the iterator return.
|
||||
* **Polish**
|
||||
* Use a different helper for computed classes for much nicer output. Also fixes a bug in symbols being non-enumerable so they wouldn't be set on the class.
|
||||
|
||||
## 4.7.4
|
||||
|
||||
* **Bug Fix**
|
||||
* Rewrite named function expressions in optional async function transformers.
|
||||
* Hoist directives.
|
||||
* Remove `Number` from the list of valid `runtime` constructors.
|
||||
* **Internal**
|
||||
* `spec.typeofSymbol` transformer has been renamed to `es6.symbols`.
|
||||
|
||||
## 4.7.2
|
||||
|
||||
* **New Feature**
|
||||
* `"both"` option for `sourceMap`.
|
||||
* Add output types to external helpers. Thanks [@neVERberleRfellerER](https://github.com/neVERberleRfellerER)!
|
||||
* **Bug Fix**
|
||||
* Fix node duplication sometimes resulting in a recursion error.
|
||||
* Ignore `break`s within cases inside `for...of`.
|
||||
* **Polish**
|
||||
* Split up variable declarations and export declarations to allow easier transformation.
|
||||
|
||||
## 4.7.0
|
||||
|
||||
* **Bug Fix**
|
||||
* Add `alternate` to list of `STATEMENT_OR_BLOCK` keys.
|
||||
* Add support for module specifiers to `t.isReferenced`.
|
||||
* **New Feature**
|
||||
* Add `inputSourceMap` option.
|
||||
* **Polish**
|
||||
* Throw an error on different `babel` and `babel-runtime` versions.
|
||||
* Replicate module environment for `babel-node` eval.
|
||||
* Clean up classes output.
|
||||
* **Spec Compliancy**
|
||||
* Make it illegal to use a rest parameter on a setter.
|
||||
|
||||
## 4.6.6
|
||||
|
||||
* **Bug Fix**
|
||||
* Fix incorrect method call in `utility.deadCodeElimination` transformer.
|
||||
* Fix `es6.blockScopingTDZ` transformer duplicating binding nodes.
|
||||
|
||||
## 4.6.5
|
||||
|
||||
* **Internal**
|
||||
* `useStrict` transformer has been renamed to `strict`.
|
||||
|
||||
## 4.6.4
|
||||
|
||||
* **Bug Fix**
|
||||
* Fix `ForOfStatement` not proplery inheriting labels.
|
||||
* When in closure mode in block scoping transformer, properly check for variable shadowing.
|
||||
* **New Feature**
|
||||
* New `utility.inlineEnvironmentVariables` and `utility.inlineExpression` transformers.
|
||||
|
||||
## 4.6.3
|
||||
|
||||
* **Bug Fix**
|
||||
* Fix `arguments` being incorrectly aliased in arrow function rest parameter optimisation.
|
||||
* Make deoptimisation trigger safer.
|
||||
* **New Feature**
|
||||
* Flow types are now retained when blacklisting the `flow` transformer.
|
||||
|
||||
## 4.6.1
|
||||
|
||||
* **Bug Fix**
|
||||
* Fix generators in template directory being transformed.
|
||||
* Fix exposure of `util` for plugins.
|
||||
|
||||
## 4.6.0
|
||||
|
||||
* **New Feature**
|
||||
* Desugar sticky regexes to a new constructor expression so it can be handled by a polyfill.
|
||||
* **Spec Compliancy**
|
||||
* `for...of` now outputs in a lengthy `try...catch` this is to ensure spec compliancy in regards to iterator returns and abrupt completions. See [google/traceur-compiler#1773](https://github.com/google/traceur-compiler/issues/1773) and [babel/babel/#838](https://github.com/babel/babel/issues/838) for more information.
|
||||
* **Polish**
|
||||
* Rest parameters that are only refered to via number properties on member expressions are desugared into a direct `arguments` reference. Thanks [@neVERberleRfellerER](https://github.com/neVERberleRfellerER)!
|
||||
* `$ babel` no longer exits on syntax errors.
|
||||
* **Internal**
|
||||
* Upgrade `browserify`.
|
||||
* Upgrade `source-map`.
|
||||
* Publicly expose more internals.
|
||||
|
||||
## 4.5.5
|
||||
|
||||
* **Polish**
|
||||
* Delete old extensions when overriding them in `babel/register`.
|
||||
|
||||
## 4.5.3
|
||||
|
||||
* **Bug Fix**
|
||||
* Fix whitelisting logic for helper build script.
|
||||
|
||||
## 4.5.2
|
||||
|
||||
* **New Feature**
|
||||
* `returnUsedHelpers` option and add whitelist to `buildHelpers`.
|
||||
* **Bug Fix**
|
||||
* Fix function arity on self referencing inferred named functions.
|
||||
* **Internal**
|
||||
* Bump `acorn-babel`.
|
||||
* Start converting source to ES6...
|
||||
|
||||
## 4.5.1
|
||||
|
||||
**Babel now compiles itself!**
|
||||
|
||||

|
||||
|
||||
## 4.5.0
|
||||
|
||||
* **New Feature**
|
||||
* Add `.babelrc` support.
|
||||
* **Bug Fix**
|
||||
* Move use strict directives to the module formatter bodies.
|
||||
* **Internal**
|
||||
* Make default `bin/babel` behaviour to ignore non-compilable files and add a `--copy-files` flag to revert to the old behaviour.
|
||||
|
||||
## 4.4.6
|
||||
|
||||
* **Bug Fix**
|
||||
* Fix extending a class expression with no methods/only constructor. Thanks [@neVERberleRfellerER](https://github.com/neVERberleRfellerER)!
|
||||
* Allow `MemberExpression` as a valid `left` of `ForOfStatement`.
|
||||
* **Polish**
|
||||
* Throw an error when people try and transpile code with the `@jsx React.DOM` pragma as it conflicts with the custom jsx constructo method detection.
|
||||
* Crawl all comments for `@jsx` pragma.
|
||||
* **Internal**
|
||||
* Upgrade `chalk`.
|
||||
* Upgrade `core-js`.
|
||||
|
||||
## 4.4.5
|
||||
|
||||
* **Internal**
|
||||
* Remove function self reference optimisation.
|
||||
|
||||
## 4.4.4
|
||||
|
||||
* **Bug Fix**
|
||||
* Handle inferred function ids to be reassigned and deopt to a slower but working equivalent.
|
||||
* Don't unpack array patterns that have more elements than their right hand array expression.
|
||||
* **Polish**
|
||||
* Improve syntax highlighting in the code frame. Thanks [@lydell](https://github.com/lydell)!
|
||||
* **Internal**
|
||||
* Upgrade `acorn-babel`.
|
||||
|
||||
## 4.4.3
|
||||
|
||||
* **Bug Fix**
|
||||
* Fix `for...of` iterator break returns being duplicated.
|
||||
* Only call `return` on the iterator if it exists.
|
||||
* **Internal**
|
||||
* Rename `selfContained` transformer to `runtime`.
|
||||
|
||||
## 4.4.2
|
||||
|
||||
* **New Feature**
|
||||
* Add `moduleId` option for specifying a custom module id.
|
||||
|
||||
## 4.4.0
|
||||
|
||||
* **New Feature**
|
||||
|
||||
@@ -4,12 +4,42 @@ Contributions are always welcome, no matter how large or small. Before
|
||||
contributing, please read the
|
||||
[code of conduct](https://github.com/babel/babel/blob/master/CODE_OF_CONDUCT.md).
|
||||
|
||||
**NOTE:** Please do not send pull requests that fix linting issues. It's highly
|
||||
likely that they've already been fixed by the time it's submitted and it just
|
||||
pollutes the git tree.
|
||||
|
||||
## Developing
|
||||
|
||||
#### Setup
|
||||
|
||||
```sh
|
||||
$ git clone https://github.com/babel/babel
|
||||
$ cd babel
|
||||
$ make bootstrap
|
||||
```
|
||||
|
||||
Then you need to run:
|
||||
|
||||
```sh
|
||||
$ make watch-core
|
||||
```
|
||||
|
||||
This will compile babel and then sit in the background and on file modification
|
||||
recompile the necessary files.
|
||||
|
||||
#### Running tests
|
||||
|
||||
You can run tests via:
|
||||
|
||||
```sh
|
||||
$ make test
|
||||
```
|
||||
|
||||
This will usually take around two minutes as it's compiling the entire
|
||||
[test262](https://github.com/tc39/test262) test suite and validating it's AST.
|
||||
This is mostly overkill and you can limit the tests to a select few by directly
|
||||
running them with `mocha`:
|
||||
|
||||
```sh
|
||||
$ mocha test/transformation.js
|
||||
```
|
||||
|
||||
#### Workflow
|
||||
|
||||
* Fork the repository
|
||||
@@ -18,13 +48,11 @@ pollutes the git tree.
|
||||
* Link your forked clone (`npm link`)
|
||||
* Develop your changes ensuring you're fetching updates from upstream often
|
||||
* Ensure the test are passing (`make test`)
|
||||
* Create new pull request explaining your proposed change or reference an issue
|
||||
in your commit message
|
||||
* Create new pull request explaining your proposed change or reference an issue in your commit message
|
||||
|
||||
#### Code Standards
|
||||
|
||||
* **General**
|
||||
* No ES6 syntax features or methods, exclusively ES5.
|
||||
* Max of five arguments for functions
|
||||
* Max depth of four nested blocks
|
||||
* 2-spaced soft tabs
|
||||
@@ -43,11 +71,3 @@ pollutes the git tree.
|
||||
* **Declaration**
|
||||
* No unused variables
|
||||
* No pollution of global variables and prototypes
|
||||
|
||||
## Testing
|
||||
|
||||
$ make test
|
||||
|
||||
## Linting
|
||||
|
||||
$ make lint
|
||||
|
||||
34
Makefile
34
Makefile
@@ -4,21 +4,24 @@ UGLIFY_CMD = node_modules/uglify-js/bin/uglifyjs
|
||||
#UGLIFY_CMD = node_modules/uglify-js/bin/uglifyjs --mangle sort
|
||||
JSHINT_CMD = node_modules/jshint/bin/jshint
|
||||
MOCHA_CMD = node_modules/mocha/bin/_mocha
|
||||
JSCS_CMD = node_modules/jscs/bin/jscs
|
||||
BABEL_CMD = node_modules/babel/bin/babel
|
||||
|
||||
export NODE_ENV = test
|
||||
|
||||
.PHONY: clean test test-cov test-clean lint test-travis test-simple test-all test-browser publish build bootstrap publish-core publish-runtime build-core watch-core
|
||||
.PHONY: clean test test-cov test-clean test-travis test-simple test-all test-browser publish build bootstrap publish-core publish-runtime build-core watch-core build-core-test
|
||||
|
||||
build-core:
|
||||
#node $(BABEL_CMD) src --out-dir lib
|
||||
node $(BABEL_CMD) src --out-dir lib --copy-files
|
||||
|
||||
build-core-test:
|
||||
node $(BABEL_CMD) src --out-dir lib --copy-files --auxiliary-comment "istanbul ignore next"
|
||||
|
||||
watch-core:
|
||||
#node $(BABEL_CMD) src --out-dir lib --watch
|
||||
node $(BABEL_CMD) src --out-dir lib --watch --copy-files
|
||||
|
||||
build:
|
||||
mkdir -p dist
|
||||
make build-core
|
||||
|
||||
node tools/cache-templates
|
||||
|
||||
@@ -36,34 +39,23 @@ build:
|
||||
clean:
|
||||
rm -rf coverage templates.json test/tmp dist
|
||||
|
||||
lint:
|
||||
$(JSHINT_CMD) --reporter node_modules/jshint-stylish/stylish.js lib bin
|
||||
$(JSCS_CMD) lib bin
|
||||
|
||||
test-clean:
|
||||
rm -rf test/tmp
|
||||
|
||||
test: lint
|
||||
$(MOCHA_CMD)
|
||||
test:
|
||||
node $(MOCHA_CMD)
|
||||
make test-clean
|
||||
|
||||
test-simple:
|
||||
# excludes test262
|
||||
export SIMPLE_BABEL_TESTS=1; \
|
||||
make test
|
||||
|
||||
test-all:
|
||||
export ALL_BABEL_TESTS=1; \
|
||||
make test
|
||||
|
||||
test-cov:
|
||||
rm -rf coverage
|
||||
export SIMPLE_BABEL_TESTS=1; \
|
||||
make build-core-test
|
||||
node $(ISTANBUL_CMD) $(MOCHA_CMD) --
|
||||
|
||||
test-travis: build-core bootstrap
|
||||
node $(ISTANBUL_CMD) $(MOCHA_CMD) --
|
||||
if test -n "$$CODECLIMATE_REPO_TOKEN"; then codeclimate < coverage/lcov.info; fi
|
||||
test-travis: bootstrap build test
|
||||
|
||||
test-browser:
|
||||
mkdir -p dist
|
||||
@@ -119,5 +111,5 @@ publish-core:
|
||||
bootstrap:
|
||||
npm install
|
||||
git submodule update --init
|
||||
cd vendor/regenerator; npm install
|
||||
cd vendor/compat-table; npm install object-assign
|
||||
cd vendor/regenerator && npm install
|
||||
cd vendor/compat-table && npm install object-assign
|
||||
|
||||
@@ -9,8 +9,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
For more information view the <a href="https://babeljs.io/">documentation</a>. For
|
||||
support visit the <a href="https://gitter.im/babel/babel">gitter room</a>.
|
||||
For questions and support please visit the <a href="https://gitter.im/babel/babel">gitter room</a> before creating an issue.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
|
||||
@@ -50,14 +50,28 @@ var _eval = function (code, filename) {
|
||||
experimental: program.experimental,
|
||||
playground: program.playground
|
||||
}).code;
|
||||
return vm.runInThisContext(code, filename);
|
||||
|
||||
return vm.runInThisContext(code, {
|
||||
filename: filename
|
||||
});
|
||||
};
|
||||
|
||||
if (program.eval || program.print) {
|
||||
var code = program.eval;
|
||||
if (!code || code === true) code = program.print;
|
||||
|
||||
var result = _eval(code, "eval");
|
||||
global.__filename = "[eval]";
|
||||
global.__dirname = process.cwd();
|
||||
|
||||
var module = new Module(global.__filename);
|
||||
module.filename = global.__filename;
|
||||
module.paths = Module._nodeModulePaths(global.__dirname);
|
||||
|
||||
global.exports = module.exports;
|
||||
global.module = module;
|
||||
global.require = module.require.bind(module);
|
||||
|
||||
var result = _eval(code, global.__filename);
|
||||
if (program.print) console.log(result);
|
||||
} else {
|
||||
if (program.args.length) {
|
||||
@@ -85,7 +99,7 @@ if (program.eval || program.print) {
|
||||
args = args.slice(i);
|
||||
|
||||
// make the filename absolute
|
||||
var filename = args[0]
|
||||
var filename = args[0];
|
||||
if (!pathIsAbsolute(filename)) args[0] = path.join(process.cwd(), filename);
|
||||
|
||||
// add back on node and concat the sliced args
|
||||
|
||||
@@ -1,4 +1,13 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
var runtime = require("../lib/babel/build-external-helpers");
|
||||
console.log(runtime());
|
||||
var commander = require("commander");
|
||||
var util = require("../lib/babel/util");
|
||||
var runtime = require("../lib/babel/tools/build-external-helpers");
|
||||
|
||||
commander.option("-l, --whitelist [whitelist]", "Whitelist of helpers to ONLY include", util.list);
|
||||
commander.option("-t, --output-type [type]", "Type of output (global|umd|var)", "global");
|
||||
|
||||
commander.usage("[options]");
|
||||
commander.parse(process.argv);
|
||||
|
||||
console.log(runtime(commander.whitelist, commander.outputType));
|
||||
|
||||
@@ -7,7 +7,17 @@
|
||||
|
||||
var args = [__dirname + "/_babel-node"];
|
||||
|
||||
process.argv.slice(2).forEach(function(arg){
|
||||
var babelArgs = process.argv.slice(2);
|
||||
var userArgs;
|
||||
|
||||
// separate node arguments from script arguments
|
||||
var argSeparator = babelArgs.indexOf("--");
|
||||
if (argSeparator > -1) {
|
||||
userArgs = babelArgs.slice(argSeparator); // including the --
|
||||
babelArgs = babelArgs.slice(0, argSeparator);
|
||||
}
|
||||
|
||||
babelArgs.forEach(function(arg){
|
||||
var flag = arg.split("=")[0];
|
||||
|
||||
switch (flag) {
|
||||
@@ -49,6 +59,11 @@ process.argv.slice(2).forEach(function(arg){
|
||||
}
|
||||
});
|
||||
|
||||
// append arguments passed after --
|
||||
if (argSeparator > -1) {
|
||||
args = args.concat(userArgs);
|
||||
}
|
||||
|
||||
try {
|
||||
var kexec = require("kexec");
|
||||
kexec(process.argv[0], args);
|
||||
|
||||
@@ -31,6 +31,14 @@ module.exports = function (commander, filenames, opts) {
|
||||
console.log(src + " -> " + dest);
|
||||
};
|
||||
|
||||
var handleFile = function (src, filename) {
|
||||
if (util.canCompile(filename)) {
|
||||
write(src, filename);
|
||||
} else if (commander.copyFiles) {
|
||||
outputFileSync(path.join(commander.outDir, filename), fs.readFileSync(src));
|
||||
}
|
||||
};
|
||||
|
||||
var handle = function (filename) {
|
||||
if (!fs.existsSync(filename)) return;
|
||||
|
||||
@@ -41,11 +49,7 @@ module.exports = function (commander, filenames, opts) {
|
||||
|
||||
_.each(util.readdir(dirname), function (filename) {
|
||||
var src = path.join(dirname, filename);
|
||||
if (util.canCompile(filename)) {
|
||||
write(src, filename);
|
||||
} else {
|
||||
outputFileSync(path.join(commander.outDir, filename), fs.readFileSync(src));
|
||||
}
|
||||
handleFile(src, filename);
|
||||
});
|
||||
} else {
|
||||
write(filename, filename);
|
||||
@@ -64,7 +68,11 @@ module.exports = function (commander, filenames, opts) {
|
||||
_.each(["add", "change"], function (type) {
|
||||
watcher.on(type, function (filename) {
|
||||
var relative = path.relative(dirname, filename) || filename;
|
||||
write(filename, relative);
|
||||
try {
|
||||
handleFile(filename, relative);
|
||||
} catch (err) {
|
||||
console.error(err.stack);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
var sourceMapToComment = require("source-map-to-comment");
|
||||
var sourceMap = require("source-map");
|
||||
var chokidar = require("chokidar");
|
||||
var path = require("path");
|
||||
var util = require("./util");
|
||||
var fs = require("fs");
|
||||
var _ = require("lodash");
|
||||
var convertSourceMap = require("convert-source-map");
|
||||
var sourceMap = require("source-map");
|
||||
var chokidar = require("chokidar");
|
||||
var path = require("path");
|
||||
var util = require("./util");
|
||||
var fs = require("fs");
|
||||
var _ = require("lodash");
|
||||
|
||||
module.exports = function (commander, filenames) {
|
||||
var results = [];
|
||||
@@ -42,7 +42,7 @@ module.exports = function (commander, filenames) {
|
||||
});
|
||||
|
||||
if (commander.sourceMapsInline || (!commander.outFile && commander.sourceMaps)) {
|
||||
code += "\n" + sourceMapToComment(map);
|
||||
code += "\n" + convertSourceMap.fromObject(map).toComment();
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -119,7 +119,11 @@ module.exports = function (commander, filenames) {
|
||||
}).on("all", function (type, filename) {
|
||||
if (type === "add" || type === "change") {
|
||||
console.log(type, filename);
|
||||
walk();
|
||||
try {
|
||||
walk();
|
||||
} catch (err) {
|
||||
console.error(err.stack);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ commander.option("-M, --module-ids", "Insert module id in modules", false);
|
||||
commander.option("-R, --react-compat", "Makes the react transformer produce pre-v0.12 code");
|
||||
commander.option("--keep-module-id-extensions", "Keep extensions when generating module ids", false);
|
||||
commander.option("-a, --auxiliary-comment [comment]", "Comment text to prepend to all auxiliary code");
|
||||
commander.option("-D, --copy-files", "When compiling a directory copy over non-compilable files");
|
||||
|
||||
commander.on("--help", function () {
|
||||
var outKeys = function (title, obj) {
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
var readdir = require("fs-readdir-recursive");
|
||||
var index = require("./index");
|
||||
var babel = require("../../lib/babel/api/node");
|
||||
var util = require("../../lib/babel/util");
|
||||
var path = require("path");
|
||||
var fs = require("fs");
|
||||
var _ = require("lodash");
|
||||
var resolveRc = require("../../lib/babel/api/register/resolve-rc");
|
||||
var readdir = require("fs-readdir-recursive");
|
||||
var index = require("./index");
|
||||
var babel = require("../../lib/babel/api/node");
|
||||
var util = require("../../lib/babel/util");
|
||||
var path = require("path");
|
||||
var fs = require("fs");
|
||||
var _ = require("lodash");
|
||||
|
||||
exports.readdirFilter = function (filename) {
|
||||
return readdir(filename).filter(function (filename) {
|
||||
@@ -23,18 +24,9 @@ exports.addSourceMappingUrl = function (code, loc) {
|
||||
exports.transform = function (filename, code, opts) {
|
||||
opts = _.defaults(opts || {}, index.opts);
|
||||
opts.filename = filename;
|
||||
resolveRc(filename, opts);
|
||||
|
||||
var result;
|
||||
try {
|
||||
result = babel.transform(code, opts);
|
||||
} catch (e) {
|
||||
if (e instanceof SyntaxError) {
|
||||
console.error("SyntaxError:", e.message);
|
||||
process.exit(1);
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
var result = babel.transform(code, opts);
|
||||
result.filename = filename;
|
||||
result.actual = code;
|
||||
return result;
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
See [babel.github.io/docs](https://github.com/babel/babel.github.io/tree/master/docs).
|
||||
@@ -1,58 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
var isFunction = require("lodash/lang/isFunction");
|
||||
var transform = require("../transformation");
|
||||
var util = require("../util");
|
||||
var fs = require("fs");
|
||||
|
||||
exports.version = require("../../../package").version;
|
||||
|
||||
exports.buildExternalHelpers = require("../build-external-helpers");
|
||||
|
||||
exports.types = require("../types");
|
||||
|
||||
exports.register = function (opts) {
|
||||
var register = require("./register/node");
|
||||
if (opts != null) register(opts);
|
||||
return register;
|
||||
};
|
||||
|
||||
exports.polyfill = function () {
|
||||
require("../polyfill");
|
||||
};
|
||||
|
||||
exports.canCompile = util.canCompile;
|
||||
|
||||
// do not use this - this is for use by official maintained babel plugins
|
||||
exports._util = util;
|
||||
|
||||
exports.transform = transform;
|
||||
|
||||
exports.transformFile = function (filename, opts, callback) {
|
||||
if (isFunction(opts)) {
|
||||
callback = opts;
|
||||
opts = {};
|
||||
}
|
||||
|
||||
opts.filename = filename;
|
||||
|
||||
fs.readFile(filename, function (err, code) {
|
||||
if (err) return callback(err);
|
||||
|
||||
var result;
|
||||
|
||||
try {
|
||||
result = transform(code, opts);
|
||||
} catch (err) {
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
callback(null, result);
|
||||
});
|
||||
};
|
||||
|
||||
exports.transformFileSync = function (filename, opts) {
|
||||
opts = opts || {};
|
||||
opts.filename = filename;
|
||||
return transform(fs.readFileSync(filename), opts);
|
||||
};
|
||||
@@ -1,7 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
// required to safely use babel/register within a browserify codebase
|
||||
|
||||
module.exports = function () {};
|
||||
|
||||
require("../../polyfill");
|
||||
@@ -1,25 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
var buildHelpers = require("./build-helpers");
|
||||
var generator = require("./generation");
|
||||
var util = require("./util");
|
||||
var t = require("./types");
|
||||
|
||||
module.exports = function () {
|
||||
var namespace = t.identifier("babelHelpers");
|
||||
|
||||
var body = [];
|
||||
var container = t.functionExpression(null, [t.identifier("global")], t.blockStatement(body));
|
||||
var tree = t.program([t.expressionStatement(t.callExpression(container, [util.template("self-global")]))]);
|
||||
|
||||
body.push(t.variableDeclaration("var", [
|
||||
t.variableDeclarator(
|
||||
namespace,
|
||||
t.assignmentExpression("=", t.memberExpression(t.identifier("global"), namespace), t.objectExpression([]))
|
||||
)
|
||||
]));
|
||||
|
||||
buildHelpers(body, namespace);
|
||||
|
||||
return generator(tree).code;
|
||||
};
|
||||
@@ -1,13 +0,0 @@
|
||||
var File = require("./transformation/file");
|
||||
var util = require("./util");
|
||||
var each = require("lodash/collection/each");
|
||||
var t = require("./types");
|
||||
|
||||
module.exports = function (body, namespace) {
|
||||
each(File.helpers, function (name) {
|
||||
var key = t.identifier(t.toIdentifier(name));
|
||||
body.push(t.expressionStatement(
|
||||
t.assignmentExpression("=", t.memberExpression(namespace, key), util.template(name))
|
||||
));
|
||||
});
|
||||
};
|
||||
@@ -1,29 +0,0 @@
|
||||
module.exports = detect;
|
||||
|
||||
var SYNTAX_KEYS = require("./syntax-keys");
|
||||
var traverse = require("../traversal");
|
||||
var visitors = traverse.explode(require("./visitors"));
|
||||
|
||||
function detect(ast) {
|
||||
var stats = {
|
||||
syntax: {},
|
||||
builtins: {}
|
||||
};
|
||||
|
||||
var detectedSyntax = function (name) {
|
||||
stats.syntax[name] = true;
|
||||
};
|
||||
|
||||
traverse(ast, {
|
||||
enter: function (node, parent) {
|
||||
if (SYNTAX_KEYS[node.type]) {
|
||||
detectedSyntax(SYNTAX_KEYS[node.type]);
|
||||
}
|
||||
|
||||
var visitor = visitors[node.type];
|
||||
if (visitor) visitor(node, parent, detectedSyntax);
|
||||
}
|
||||
});
|
||||
|
||||
return stats;
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
{
|
||||
"ArrowFunctionExpression": "es6.arrowFunctions",
|
||||
|
||||
"AwaitExpression": "es7.asyncFunctions",
|
||||
|
||||
"ClassBody": "es6.classes",
|
||||
"ClassDeclaration": "es6.classes",
|
||||
"ClassExpression": "es6.classes",
|
||||
"MethodDefinition": "es6.classes",
|
||||
|
||||
"ComprehensionBlock": "es7.comprehensions",
|
||||
"ComprehensionExpression": "es7.comprehensions",
|
||||
|
||||
"ForOfStatement": "es6.forOf",
|
||||
|
||||
"ExportBatchSpecifier": "es6.modules",
|
||||
"ExportDeclaration": "es6.modules",
|
||||
"ExportSpecifier": "es6.modules",
|
||||
"ImportBatchSpecifier": "es6.modules",
|
||||
"ImportDeclaration": "es6.modules",
|
||||
"ImportSpecifier": "es6.modules",
|
||||
|
||||
"ArrayPattern": "es6.destructuring",
|
||||
"AssignmentPattern": "es6.destructuring",
|
||||
"ObjectPattern": "es6.destructuring",
|
||||
|
||||
"RestElement": "es6.parameters.rest",
|
||||
|
||||
"SpreadElement": "es6.spread",
|
||||
|
||||
"SpreadProperty": "es7.objectSpread",
|
||||
|
||||
"TaggedTemplateExpression": "es6.templateLiterals",
|
||||
"TemplateElement": "es6.templateLiterals",
|
||||
"TemplateLiteral": "es6.templateLiterals",
|
||||
|
||||
"VirtualPropertyExpression": "es7.abstractReferences",
|
||||
"PrivateDeclaration": "es7.abstractReferences",
|
||||
|
||||
"YieldExpression": "es6.generators",
|
||||
|
||||
"AnyTypeAnnotation": "flow",
|
||||
"ArrayTypeAnnotation": "flow",
|
||||
"BooleanTypeAnnotation": "flow",
|
||||
"ClassProperty": "flow",
|
||||
"DeclareClass": "flow",
|
||||
"DeclareFunction": "flow",
|
||||
"DeclareModule": "flow",
|
||||
"DeclareVariable": "flow",
|
||||
"FunctionTypeAnnotation": "flow",
|
||||
"FunctionTypeParam": "flow",
|
||||
"GenericTypeAnnotation": "flow",
|
||||
"InterfaceExtends": "flow",
|
||||
"InterfaceDeclaration": "flow",
|
||||
"IntersectionTypeAnnotation": "flow",
|
||||
"NullableTypeAnnotation": "flow",
|
||||
"NumberTypeAnnotation": "flow",
|
||||
"StringLiteralTypeAnnotation": "flow",
|
||||
"StringTypeAnnotation": "flow",
|
||||
"TupleTypeAnnotation": "flow",
|
||||
"TypeofTypeAnnotation": "flow",
|
||||
"TypeAlias": "flow",
|
||||
"TypeAnnotation": "flow",
|
||||
"TypeParameterDeclaration": "flow",
|
||||
"TypeParameterInstantiation": "flow",
|
||||
"ObjectTypeAnnotation": "flow",
|
||||
"ObjectTypeCallProperty": "flow",
|
||||
"ObjectTypeIndexer": "flow",
|
||||
"ObjectTypeProperty": "flow",
|
||||
"QualifiedTypeIdentifier": "flow",
|
||||
"UnionTypeAnnotation": "flow",
|
||||
"VoidTypeAnnotation": "flow",
|
||||
|
||||
"JSXAttribute": "jsx",
|
||||
"JSXClosingElement": "jsx",
|
||||
"JSXElement": "jsx",
|
||||
"JSXEmptyExpression": "jsx",
|
||||
"JSXExpressionContainer": "jsx",
|
||||
"JSXIdentifier": "jsx",
|
||||
"JSXMemberExpression": "jsx",
|
||||
"JSXNamespacedName": "jsx",
|
||||
"JSXOpeningElement": "jsx",
|
||||
"JSXSpreadAttribute": "jsx"
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
var t = require("../types");
|
||||
var includes = require("lodash/collection/includes");
|
||||
|
||||
exports.AssignmentExpression = function (node, parent, detected) {
|
||||
if (node.operator === "**=") {
|
||||
detected("es6.exponentation");
|
||||
}
|
||||
};
|
||||
|
||||
exports.BinaryExpression = function (node, parent, detected) {
|
||||
if (node.operator === "**") {
|
||||
detected("es6.exponentation");
|
||||
}
|
||||
};
|
||||
|
||||
exports.VariableDeclaration = function (node, parent, detected) {
|
||||
if (node.kind === "let" || node.kind === "const") {
|
||||
detected("es6.blockScoping");
|
||||
}
|
||||
|
||||
if (node.kind === "const") {
|
||||
detected("es6.constants");
|
||||
}
|
||||
};
|
||||
|
||||
exports.Property = function (node, parent, detected) {
|
||||
if (node.shorthand || node.method) {
|
||||
detected("es6.properties.shorthand");
|
||||
}
|
||||
|
||||
if (node.kind === "set" || node.kind === "get") {
|
||||
detected("es5.properties.mutators");
|
||||
}
|
||||
|
||||
if (node.computed) {
|
||||
detected("es6.properties.computed");
|
||||
}
|
||||
};
|
||||
|
||||
exports.AssignmentPattern = function (node, parent, detected) {
|
||||
if (t.isFunction(parent) && includes(parent.params, node)) {
|
||||
detected("es6.parameters.default");
|
||||
}
|
||||
};
|
||||
|
||||
exports.Function = function (node, parent, detected) {
|
||||
if (node.generator) {
|
||||
detected("es6.generators");
|
||||
}
|
||||
|
||||
if (node.async) {
|
||||
detected("es7.asyncFunctions");
|
||||
}
|
||||
};
|
||||
@@ -1,175 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
module.exports = Buffer;
|
||||
|
||||
var repeating = require("repeating");
|
||||
var trimRight = require("trim-right");
|
||||
var isBoolean = require("lodash/lang/isBoolean");
|
||||
var includes = require("lodash/collection/includes");
|
||||
var isNumber = require("lodash/lang/isNumber");
|
||||
|
||||
function Buffer(position, format) {
|
||||
this.position = position;
|
||||
this._indent = format.indent.base;
|
||||
this.format = format;
|
||||
this.buf = "";
|
||||
}
|
||||
|
||||
Buffer.prototype.get = function () {
|
||||
return trimRight(this.buf);
|
||||
};
|
||||
|
||||
Buffer.prototype.getIndent = function () {
|
||||
if (this.format.compact || this.format.concise) {
|
||||
return "";
|
||||
} else {
|
||||
return repeating(this.format.indent.style, this._indent);
|
||||
}
|
||||
};
|
||||
|
||||
Buffer.prototype.indentSize = function () {
|
||||
return this.getIndent().length;
|
||||
};
|
||||
|
||||
Buffer.prototype.indent = function () {
|
||||
this._indent++;
|
||||
};
|
||||
|
||||
Buffer.prototype.dedent = function () {
|
||||
this._indent--;
|
||||
};
|
||||
|
||||
Buffer.prototype.semicolon = function () {
|
||||
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.space();
|
||||
};
|
||||
|
||||
Buffer.prototype.space = function () {
|
||||
if (this.format.compact) return;
|
||||
if (this.buf && !this.isLast(" ") && !this.isLast("\n")) {
|
||||
this.push(" ");
|
||||
}
|
||||
};
|
||||
|
||||
Buffer.prototype.removeLast = function (cha) {
|
||||
if (this.format.compact) return;
|
||||
if (!this.isLast(cha)) return;
|
||||
|
||||
this.buf = this.buf.substr(0, this.buf.length - 1);
|
||||
this.position.unshift(cha);
|
||||
};
|
||||
|
||||
Buffer.prototype.newline = function (i, removeLast) {
|
||||
if (this.format.compact) return;
|
||||
|
||||
if (this.format.concise) {
|
||||
this.space();
|
||||
return;
|
||||
}
|
||||
|
||||
removeLast = removeLast || false;
|
||||
|
||||
if (isNumber(i)) {
|
||||
i = Math.min(2, i);
|
||||
|
||||
if (this.endsWith("{\n") || this.endsWith(":\n")) i--;
|
||||
if (i <= 0) return;
|
||||
|
||||
while (i > 0) {
|
||||
this._newline(removeLast);
|
||||
i--;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (isBoolean(i)) {
|
||||
removeLast = i;
|
||||
}
|
||||
|
||||
this._newline(removeLast);
|
||||
};
|
||||
|
||||
Buffer.prototype._newline = function (removeLast) {
|
||||
// never allow more than two lines
|
||||
if (this.endsWith("\n\n")) return;
|
||||
|
||||
// remove the last newline
|
||||
if (removeLast && this.isLast("\n")) this.removeLast("\n");
|
||||
|
||||
this.removeLast(" ");
|
||||
this._removeSpacesAfterLastNewline();
|
||||
this._push("\n");
|
||||
};
|
||||
|
||||
/**
|
||||
* If buffer ends with a newline and some spaces after it, trim those spaces.
|
||||
*/
|
||||
|
||||
Buffer.prototype._removeSpacesAfterLastNewline = function () {
|
||||
var lastNewlineIndex = this.buf.lastIndexOf("\n");
|
||||
if (lastNewlineIndex === -1)
|
||||
return;
|
||||
|
||||
var index = this.buf.length - 1;
|
||||
while (index > lastNewlineIndex) {
|
||||
if (this.buf[index] !== " ") {
|
||||
break;
|
||||
}
|
||||
|
||||
index--;
|
||||
}
|
||||
|
||||
if (index === lastNewlineIndex) {
|
||||
this.buf = this.buf.substring(0, index + 1);
|
||||
}
|
||||
};
|
||||
|
||||
Buffer.prototype.push = function (str, noIndent) {
|
||||
if (!this.format.compact && 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")) this._push(indent);
|
||||
}
|
||||
|
||||
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) {
|
||||
if (this.format.compact) return false;
|
||||
|
||||
var buf = this.buf;
|
||||
var last = buf[buf.length - 1];
|
||||
|
||||
if (Array.isArray(cha)) {
|
||||
return includes(cha, last);
|
||||
} else {
|
||||
return cha === last;
|
||||
}
|
||||
};
|
||||
@@ -1,36 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
exports.AnyTypeAnnotation =
|
||||
exports.ArrayTypeAnnotation =
|
||||
exports.BooleanTypeAnnotation =
|
||||
exports.ClassProperty =
|
||||
exports.DeclareClass =
|
||||
exports.DeclareFunction =
|
||||
exports.DeclareModule =
|
||||
exports.DeclareVariable =
|
||||
exports.FunctionTypeAnnotation =
|
||||
exports.FunctionTypeParam =
|
||||
exports.GenericTypeAnnotation =
|
||||
exports.InterfaceExtends =
|
||||
exports.InterfaceDeclaration =
|
||||
exports.IntersectionTypeAnnotation =
|
||||
exports.NullableTypeAnnotation =
|
||||
exports.NumberTypeAnnotation =
|
||||
exports.StringLiteralTypeAnnotation =
|
||||
exports.StringTypeAnnotation =
|
||||
exports.TupleTypeAnnotation =
|
||||
exports.TypeofTypeAnnotation =
|
||||
exports.TypeAlias =
|
||||
exports.TypeAnnotation =
|
||||
exports.TypeParameterDeclaration =
|
||||
exports.TypeParameterInstantiation =
|
||||
exports.ObjectTypeAnnotation =
|
||||
exports.ObjectTypeCallProperty =
|
||||
exports.ObjectTypeIndexer =
|
||||
exports.ObjectTypeProperty =
|
||||
exports.QualifiedTypeIdentifier =
|
||||
exports.UnionTypeAnnotation =
|
||||
exports.TypeCastExpression =
|
||||
exports.VoidTypeAnnotation = function () {
|
||||
// todo: implement these once we have a `--keep-types` option
|
||||
};
|
||||
@@ -1,9 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
var each = require("lodash/collection/each");
|
||||
|
||||
each(["BindMemberExpression", "BindFunctionExpression"], function (type) {
|
||||
exports[type] = function () {
|
||||
throw new ReferenceError("Trying to render non-standard playground node " + JSON.stringify(type));
|
||||
};
|
||||
});
|
||||
@@ -1,32 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
var each = require("lodash/collection/each");
|
||||
|
||||
exports.TaggedTemplateExpression = function (node, print) {
|
||||
print(node.tag);
|
||||
print(node.quasi);
|
||||
};
|
||||
|
||||
exports.TemplateElement = function (node) {
|
||||
this._push(node.value.raw);
|
||||
};
|
||||
|
||||
exports.TemplateLiteral = function (node, print) {
|
||||
this.push("`");
|
||||
|
||||
var quasis = node.quasis;
|
||||
var self = this;
|
||||
var len = quasis.length;
|
||||
|
||||
each(quasis, function (quasi, i) {
|
||||
print(quasi);
|
||||
|
||||
if (i + 1 < len) {
|
||||
self.push("${ ");
|
||||
print(node.expressions[i]);
|
||||
self.push(" }");
|
||||
}
|
||||
});
|
||||
|
||||
this._push("`");
|
||||
};
|
||||
@@ -1,368 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
module.exports = function (ast, opts, code) {
|
||||
var gen = new CodeGenerator(ast, opts, code);
|
||||
return gen.generate();
|
||||
};
|
||||
|
||||
module.exports.CodeGenerator = CodeGenerator;
|
||||
|
||||
var detectIndent = require("detect-indent");
|
||||
var Whitespace = require("./whitespace");
|
||||
var repeating = require("repeating");
|
||||
var SourceMap = require("./source-map");
|
||||
var Position = require("./position");
|
||||
var messages = require("../messages");
|
||||
var Buffer = require("./buffer");
|
||||
var extend = require("lodash/object/extend");
|
||||
var each = require("lodash/collection/each");
|
||||
var n = require("./node");
|
||||
var t = require("../types");
|
||||
|
||||
function CodeGenerator(ast, opts, code) {
|
||||
opts = opts || {};
|
||||
|
||||
this.comments = ast.comments || [];
|
||||
this.tokens = ast.tokens || [];
|
||||
this.format = CodeGenerator.normalizeOptions(code, opts);
|
||||
this.opts = opts;
|
||||
this.ast = ast;
|
||||
|
||||
this.whitespace = new Whitespace(this.tokens, this.comments, this.format);
|
||||
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.normalizeOptions = function (code, opts) {
|
||||
var style = " ";
|
||||
if (code) {
|
||||
var indent = detectIndent(code).indent;
|
||||
if (indent && indent !== " ") style = indent;
|
||||
}
|
||||
|
||||
var format = {
|
||||
comments: opts.comments == null || opts.comments,
|
||||
compact: opts.compact,
|
||||
indent: {
|
||||
adjustMultilineComment: true,
|
||||
style: style,
|
||||
base: 0
|
||||
}
|
||||
};
|
||||
|
||||
if (format.compact === "auto") {
|
||||
format.compact = code.length > 100000; // 100KB
|
||||
|
||||
if (format.compact) {
|
||||
console.error(messages.get("codeGeneratorDeopt", opts.filename, "100KB"));
|
||||
}
|
||||
}
|
||||
|
||||
return format;
|
||||
};
|
||||
|
||||
CodeGenerator.generators = {
|
||||
templateLiterals: require("./generators/template-literals"),
|
||||
comprehensions: require("./generators/comprehensions"),
|
||||
expressions: require("./generators/expressions"),
|
||||
statements: require("./generators/statements"),
|
||||
playground: require("./generators/playground"),
|
||||
classes: require("./generators/classes"),
|
||||
methods: require("./generators/methods"),
|
||||
modules: require("./generators/modules"),
|
||||
types: require("./generators/types"),
|
||||
flow: require("./generators/flow"),
|
||||
base: require("./generators/base"),
|
||||
jsx: require("./generators/jsx")
|
||||
};
|
||||
|
||||
each(CodeGenerator.generators, function (generator) {
|
||||
extend(CodeGenerator.prototype, generator);
|
||||
});
|
||||
|
||||
CodeGenerator.prototype.generate = function () {
|
||||
var ast = this.ast;
|
||||
|
||||
this.print(ast);
|
||||
|
||||
var comments = [];
|
||||
each(ast.comments, function (comment) {
|
||||
if (!comment._displayed) comments.push(comment);
|
||||
});
|
||||
this._printComments(comments);
|
||||
|
||||
return {
|
||||
map: this.map.get(),
|
||||
code: this.buffer.get()
|
||||
};
|
||||
};
|
||||
|
||||
CodeGenerator.prototype.buildPrint = function (parent) {
|
||||
var self = this;
|
||||
|
||||
var print = function (node, opts) {
|
||||
return self.print(node, parent, opts);
|
||||
};
|
||||
|
||||
print.sequence = function (nodes, opts) {
|
||||
opts = opts || {};
|
||||
opts.statement = true;
|
||||
return self.printJoin(print, nodes, opts);
|
||||
};
|
||||
|
||||
print.join = function (nodes, opts) {
|
||||
return self.printJoin(print, nodes, opts);
|
||||
};
|
||||
|
||||
print.list = function (items, opts) {
|
||||
opts = opts || {};
|
||||
opts.separator = opts.separator || ", ";
|
||||
print.join(items, opts);
|
||||
};
|
||||
|
||||
print.block = function (node) {
|
||||
return self.printBlock(print, node);
|
||||
};
|
||||
|
||||
print.indentOnComments = function (node) {
|
||||
return self.printAndIndentOnComments(print, node);
|
||||
};
|
||||
|
||||
return print;
|
||||
};
|
||||
|
||||
CodeGenerator.prototype.print = function (node, parent, opts) {
|
||||
if (!node) return "";
|
||||
|
||||
if (parent && parent._compact) {
|
||||
node._compact = true;
|
||||
}
|
||||
|
||||
var oldConcise = this.format.concise;
|
||||
if (node._compact) {
|
||||
this.format.concise = true;
|
||||
}
|
||||
|
||||
var self = this;
|
||||
|
||||
opts = opts || {};
|
||||
|
||||
var newline = function (leading) {
|
||||
if (!opts.statement && !n.isUserWhitespacable(node, parent)) {
|
||||
return;
|
||||
}
|
||||
|
||||
var lines = 0;
|
||||
|
||||
if (node.start != null && !node._ignoreUserWhitespace) {
|
||||
// user node
|
||||
if (leading) {
|
||||
lines = self.whitespace.getNewlinesBefore(node);
|
||||
} else {
|
||||
lines = self.whitespace.getNewlinesAfter(node);
|
||||
}
|
||||
} else {
|
||||
// generated node
|
||||
if (!leading) lines++; // always include at least a single line after
|
||||
if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0;
|
||||
|
||||
var needs = n.needsWhitespaceAfter;
|
||||
if (leading) needs = n.needsWhitespaceBefore;
|
||||
if (needs(node, parent)) lines++;
|
||||
|
||||
// generated nodes can't add starting file whitespace
|
||||
if (!self.buffer.buf) lines = 0;
|
||||
}
|
||||
|
||||
self.newline(lines);
|
||||
};
|
||||
|
||||
if (this[node.type]) {
|
||||
var needsNoLineTermParens = n.needsParensNoLineTerminator(node, parent);
|
||||
var needsParens = needsNoLineTermParens || n.needsParens(node, parent);
|
||||
|
||||
if (needsParens) this.push("(");
|
||||
if (needsNoLineTermParens) this.indent();
|
||||
|
||||
this.printLeadingComments(node, parent);
|
||||
|
||||
newline(true);
|
||||
|
||||
if (opts.before) opts.before();
|
||||
this.map.mark(node, "start");
|
||||
|
||||
this[node.type](node, this.buildPrint(node), parent);
|
||||
|
||||
if (needsNoLineTermParens) {
|
||||
this.newline();
|
||||
this.dedent();
|
||||
}
|
||||
if (needsParens) this.push(")");
|
||||
|
||||
this.map.mark(node, "end");
|
||||
if (opts.after) opts.after();
|
||||
|
||||
newline(false);
|
||||
|
||||
this.printTrailingComments(node, parent);
|
||||
} else {
|
||||
throw new ReferenceError("unknown node of type " + JSON.stringify(node.type) + " with constructor " + JSON.stringify(node && node.constructor.name));
|
||||
}
|
||||
|
||||
this.format.concise = oldConcise;
|
||||
};
|
||||
|
||||
CodeGenerator.prototype.printJoin = function (print, nodes, opts) {
|
||||
if (!nodes || !nodes.length) return;
|
||||
|
||||
opts = opts || {};
|
||||
|
||||
var self = this;
|
||||
var len = nodes.length;
|
||||
|
||||
if (opts.indent) self.indent();
|
||||
|
||||
each(nodes, function (node, i) {
|
||||
print(node, {
|
||||
statement: opts.statement,
|
||||
addNewlines: opts.addNewlines,
|
||||
after: function () {
|
||||
if (opts.iterator) {
|
||||
opts.iterator(node, i);
|
||||
}
|
||||
|
||||
if (opts.separator && i < len - 1) {
|
||||
self.push(opts.separator);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
if (opts.indent) self.dedent();
|
||||
};
|
||||
|
||||
CodeGenerator.prototype.printAndIndentOnComments = function (print, node) {
|
||||
var indent = !!node.leadingComments;
|
||||
if (indent) this.indent();
|
||||
print(node);
|
||||
if (indent) this.dedent();
|
||||
};
|
||||
|
||||
CodeGenerator.prototype.printBlock = function (print, node) {
|
||||
if (t.isEmptyStatement(node)) {
|
||||
this.semicolon();
|
||||
} else {
|
||||
this.push(" ");
|
||||
print(node);
|
||||
}
|
||||
};
|
||||
|
||||
CodeGenerator.prototype.generateComment = function (comment) {
|
||||
var val = comment.value;
|
||||
if (comment.type === "Line") {
|
||||
val = "//" + val;
|
||||
} else {
|
||||
val = "/*" + val + "*/";
|
||||
}
|
||||
return val;
|
||||
};
|
||||
|
||||
CodeGenerator.prototype.printTrailingComments = function (node, parent) {
|
||||
this._printComments(this.getComments("trailingComments", node, parent));
|
||||
};
|
||||
|
||||
CodeGenerator.prototype.printLeadingComments = function (node, parent) {
|
||||
this._printComments(this.getComments("leadingComments", node, parent));
|
||||
};
|
||||
|
||||
CodeGenerator.prototype.getComments = function (key, node, parent) {
|
||||
if (t.isExpressionStatement(parent)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
var comments = [];
|
||||
var nodes = [node];
|
||||
var self = this;
|
||||
|
||||
if (t.isExpressionStatement(node)) {
|
||||
nodes.push(node.argument);
|
||||
}
|
||||
|
||||
each(nodes, function (node) {
|
||||
comments = comments.concat(self._getComments(key, node));
|
||||
});
|
||||
|
||||
return comments;
|
||||
};
|
||||
|
||||
CodeGenerator.prototype._getComments = function (key, node) {
|
||||
return (node && node[key]) || [];
|
||||
};
|
||||
|
||||
CodeGenerator.prototype._printComments = function (comments) {
|
||||
if (this.format.compact) return;
|
||||
|
||||
if (!this.format.comments) return;
|
||||
if (!comments || !comments.length) return;
|
||||
|
||||
var self = this;
|
||||
|
||||
each(comments, function (comment) {
|
||||
var skip = false;
|
||||
|
||||
// find the original comment in the ast and set it as displayed
|
||||
each(self.ast.comments, function (origComment) {
|
||||
if (origComment.start === comment.start) {
|
||||
// comment has already been output
|
||||
if (origComment._displayed) skip = true;
|
||||
|
||||
origComment._displayed = true;
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
if (skip) return;
|
||||
|
||||
// whitespace before
|
||||
self.newline(self.whitespace.getNewlinesBefore(comment));
|
||||
|
||||
var column = self.position.column;
|
||||
var val = self.generateComment(comment);
|
||||
|
||||
if (column && !self.isLast(["\n", " ", "[", "{"])) {
|
||||
self._push(" ");
|
||||
column++;
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
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" + repeating(" ", indent));
|
||||
}
|
||||
|
||||
if (column === 0) {
|
||||
val = self.getIndent() + val;
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
self._push(val);
|
||||
|
||||
// whitespace after
|
||||
self.newline(self.whitespace.getNewlinesAfter(comment));
|
||||
});
|
||||
};
|
||||
@@ -1,117 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
module.exports = Node;
|
||||
|
||||
var whitespace = require("./whitespace");
|
||||
var parens = require("./parentheses");
|
||||
var each = require("lodash/collection/each");
|
||||
var some = require("lodash/collection/some");
|
||||
var t = require("../../types");
|
||||
|
||||
var find = function (obj, node, parent) {
|
||||
if (!obj) return;
|
||||
var result;
|
||||
|
||||
var types = Object.keys(obj);
|
||||
for (var i = 0; i < types.length; i++) {
|
||||
var type = types[i];
|
||||
|
||||
if (t.is(type, node)) {
|
||||
var fn = obj[type];
|
||||
result = fn(node, parent);
|
||||
if (result != null) break;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
function Node(node, parent) {
|
||||
this.parent = parent;
|
||||
this.node = node;
|
||||
}
|
||||
|
||||
Node.isUserWhitespacable = function (node) {
|
||||
return t.isUserWhitespacable(node);
|
||||
};
|
||||
|
||||
Node.needsWhitespace = function (node, parent, type) {
|
||||
if (!node) return 0;
|
||||
|
||||
if (t.isExpressionStatement(node)) {
|
||||
node = node.expression;
|
||||
}
|
||||
|
||||
var linesInfo = find(whitespace.nodes, node, parent);
|
||||
|
||||
if (!linesInfo) {
|
||||
var items = find(whitespace.list, node, parent);
|
||||
if (items) {
|
||||
for (var i = 0; i < items.length; i++) {
|
||||
linesInfo = Node.needsWhitespace(items[i], node, type);
|
||||
if (linesInfo) break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (linesInfo && linesInfo[type]) || 0;
|
||||
};
|
||||
|
||||
Node.needsWhitespaceBefore = function (node, parent) {
|
||||
return Node.needsWhitespace(node, parent, "before");
|
||||
};
|
||||
|
||||
Node.needsWhitespaceAfter = function (node, parent) {
|
||||
return Node.needsWhitespace(node, parent, "after");
|
||||
};
|
||||
|
||||
Node.needsParens = function (node, parent) {
|
||||
if (!parent) return false;
|
||||
|
||||
if (t.isNewExpression(parent) && parent.callee === node) {
|
||||
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.needsParensNoLineTerminator = function (node, parent) {
|
||||
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, function (fn, key) {
|
||||
Node.prototype[key] = function () {
|
||||
// Avoid leaking arguments to prevent deoptimization
|
||||
var args = new Array(arguments.length + 2);
|
||||
|
||||
args[0] = this.node;
|
||||
args[1] = this.parent;
|
||||
|
||||
for (var i = 0; i < args.length; i++) {
|
||||
args[i + 2] = arguments[i];
|
||||
}
|
||||
|
||||
return Node[key].apply(null, args);
|
||||
};
|
||||
});
|
||||
@@ -1,29 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
module.exports = Position;
|
||||
|
||||
function Position() {
|
||||
this.line = 1;
|
||||
this.column = 0;
|
||||
}
|
||||
|
||||
Position.prototype.push = function (str) {
|
||||
for (var i = 0; i < str.length; i++) {
|
||||
if (str[i] === "\n") {
|
||||
this.line++;
|
||||
this.column = 0;
|
||||
} else {
|
||||
this.column++;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Position.prototype.unshift = function (str) {
|
||||
for (var i = 0; i < str.length; i++) {
|
||||
if (str[i] === "\n") {
|
||||
this.line--;
|
||||
} else {
|
||||
this.column--;
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -1,56 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
module.exports = SourceMap;
|
||||
|
||||
var sourceMap = require("source-map");
|
||||
var t = require("../types");
|
||||
|
||||
function SourceMap(position, opts, code) {
|
||||
this.position = position;
|
||||
this.opts = opts;
|
||||
|
||||
if (opts.sourceMap) {
|
||||
this.map = new sourceMap.SourceMapGenerator({
|
||||
file: opts.sourceMapName,
|
||||
sourceRoot: opts.sourceRoot
|
||||
});
|
||||
|
||||
this.map.setSourceContent(opts.sourceFileName, code);
|
||||
} else {
|
||||
this.map = null;
|
||||
}
|
||||
}
|
||||
|
||||
SourceMap.prototype.get = function () {
|
||||
var map = this.map;
|
||||
if (map) {
|
||||
return map.toJSON();
|
||||
} else {
|
||||
return map;
|
||||
}
|
||||
};
|
||||
|
||||
SourceMap.prototype.mark = function (node, type) {
|
||||
var loc = node.loc;
|
||||
if (!loc) return; // no location info
|
||||
|
||||
var map = this.map;
|
||||
if (!map) return; // no source map
|
||||
|
||||
if (t.isProgram(node) || t.isFile(node)) return; // illegal mapping nodes
|
||||
|
||||
var position = this.position;
|
||||
|
||||
var generated = {
|
||||
line: position.line,
|
||||
column: position.column
|
||||
};
|
||||
|
||||
var original = loc[type];
|
||||
|
||||
map.addMapping({
|
||||
source: this.opts.sourceFileName,
|
||||
generated: generated,
|
||||
original: original
|
||||
});
|
||||
};
|
||||
@@ -1,115 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
module.exports = Whitespace;
|
||||
|
||||
var sortBy = require("lodash/collection/sortBy");
|
||||
|
||||
/**
|
||||
* Returns `i`th number from `base`, continuing from 0 when `max` is reached.
|
||||
* Useful for shifting `for` loop by a fixed number but going over all items.
|
||||
*
|
||||
* @param {Number} i Current index in the loop
|
||||
* @param {Number} base Start index for which to return 0
|
||||
* @param {Number} max Array length
|
||||
* @returns {Number} shiftedIndex
|
||||
*/
|
||||
|
||||
function getLookupIndex(i, base, max) {
|
||||
i += base;
|
||||
|
||||
if (i >= max) {
|
||||
i -= max;
|
||||
}
|
||||
|
||||
return i;
|
||||
}
|
||||
|
||||
function Whitespace(tokens, comments) {
|
||||
this.tokens = sortBy(tokens.concat(comments), "start");
|
||||
this.used = {};
|
||||
|
||||
// Profiling this code shows that while generator passes over it, indexes
|
||||
// returned by `getNewlinesBefore` and `getNewlinesAfter` are always increasing.
|
||||
|
||||
// We use this implementation detail for an optimization: instead of always
|
||||
// starting to look from `this.tokens[0]`, we will start `for` loops from the
|
||||
// previous successful match. We will enumerate all tokens—but the common
|
||||
// case will be much faster.
|
||||
|
||||
this._lastFoundIndex = 0;
|
||||
}
|
||||
|
||||
Whitespace.prototype.getNewlinesBefore = function (node) {
|
||||
var startToken;
|
||||
var endToken;
|
||||
var tokens = this.tokens;
|
||||
var token;
|
||||
|
||||
for (var j = 0; j < tokens.length; j++) {
|
||||
// optimize for forward traversal by shifting for loop index
|
||||
var i = getLookupIndex(j, this._lastFoundIndex, this.tokens.length);
|
||||
token = tokens[i];
|
||||
|
||||
// this is the token this node starts with
|
||||
if (node.start === token.start) {
|
||||
startToken = tokens[i - 1];
|
||||
endToken = token;
|
||||
|
||||
this._lastFoundIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return this.getNewlinesBetween(startToken, endToken);
|
||||
};
|
||||
|
||||
Whitespace.prototype.getNewlinesAfter = function (node) {
|
||||
var startToken;
|
||||
var endToken;
|
||||
var tokens = this.tokens;
|
||||
var token;
|
||||
|
||||
for (var j = 0; j < tokens.length; j++) {
|
||||
// optimize for forward traversal by shifting for loop index
|
||||
var i = getLookupIndex(j, this._lastFoundIndex, this.tokens.length);
|
||||
token = tokens[i];
|
||||
|
||||
// this is the token this node ends with
|
||||
if (node.end === token.end) {
|
||||
startToken = token;
|
||||
endToken = tokens[i + 1];
|
||||
|
||||
this._lastFoundIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (endToken && endToken.type.type === "eof") {
|
||||
return 1;
|
||||
} else {
|
||||
var lines = this.getNewlinesBetween(startToken, endToken);
|
||||
if (node.type === "Line" && !lines) {
|
||||
// line comment
|
||||
return 1;
|
||||
} else {
|
||||
return lines;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Whitespace.prototype.getNewlinesBetween = function (startToken, endToken) {
|
||||
if (!endToken || !endToken.loc) return 0;
|
||||
|
||||
var start = startToken ? startToken.loc.end.line : 1;
|
||||
var end = endToken.loc.start.line;
|
||||
var lines = 0;
|
||||
|
||||
for (var line = start; line < end; line++) {
|
||||
if (typeof this.used[line] === "undefined") {
|
||||
this.used[line] = true;
|
||||
lines++;
|
||||
}
|
||||
}
|
||||
|
||||
return lines;
|
||||
};
|
||||
@@ -1,78 +0,0 @@
|
||||
// syntax highlighting based on https://github.com/dominictarr/ansi-highlight by the fantastic Dominic Tarr
|
||||
|
||||
var repeating = require("repeating");
|
||||
var tokenize = require("js-tokenizer");
|
||||
var chalk = require("chalk");
|
||||
|
||||
var defs = {
|
||||
string1: "red",
|
||||
string2: "red",
|
||||
punct: ["white", "bold"],
|
||||
curly: "green",
|
||||
parens: ["blue", "bold"],
|
||||
square: ["yellow"],
|
||||
name: "white",
|
||||
keyword: ["cyan"],
|
||||
number: "magenta",
|
||||
regexp: "magenta",
|
||||
comment1: "grey",
|
||||
comment2: "grey"
|
||||
};
|
||||
|
||||
var highlight = function (text) {
|
||||
var colorize = function (str, col) {
|
||||
if (!col) return str;
|
||||
|
||||
if (Array.isArray(col)) {
|
||||
col.forEach(function (col) {
|
||||
str = chalk[col](str);
|
||||
});
|
||||
} else {
|
||||
str = chalk[col](str);
|
||||
}
|
||||
return str;
|
||||
};
|
||||
|
||||
return tokenize(text, true).map(function (str) {
|
||||
var type = tokenize.type(str);
|
||||
return colorize(str, defs[type]);
|
||||
}).join("");
|
||||
};
|
||||
|
||||
module.exports = function (lines, lineNumber, colNumber) {
|
||||
colNumber = Math.max(colNumber, 0);
|
||||
|
||||
if (chalk.supportsColor) {
|
||||
lines = highlight(lines);
|
||||
}
|
||||
|
||||
lines = lines.split(/\r\n|[\n\r\u2028\u2029]/);
|
||||
|
||||
var start = Math.max(lineNumber - 3, 0);
|
||||
var end = Math.min(lines.length, lineNumber + 3);
|
||||
var width = (end + "").length;
|
||||
|
||||
if (!lineNumber && !colNumber) {
|
||||
start = 0;
|
||||
end = lines.length;
|
||||
}
|
||||
|
||||
return "\n" + lines.slice(start, end).map(function (line, i) {
|
||||
var curr = i + start + 1;
|
||||
|
||||
var gutter = curr === lineNumber ? "> " : " ";
|
||||
|
||||
var sep = curr + repeating(" ", width + 1);
|
||||
gutter += sep + "| ";
|
||||
|
||||
var str = gutter + line;
|
||||
|
||||
if (colNumber && curr === lineNumber) {
|
||||
str += "\n";
|
||||
str += repeating(" ", gutter.length - 2);
|
||||
str += "|" + repeating(" ", colNumber) + "^";
|
||||
}
|
||||
|
||||
return str;
|
||||
}).join("\n");
|
||||
};
|
||||
@@ -1,5 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
module.exports = function () {
|
||||
return Object.create(null);
|
||||
};
|
||||
@@ -1,17 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
/**
|
||||
* A trick from Bluebird to force V8 to use fast properties for an object.
|
||||
* Read more: http://stackoverflow.com/questions/24987896/
|
||||
*
|
||||
* Use %HasFastProperties(obj) and --allow-natives-syntax to check whether
|
||||
* a particular object already has fast properties.
|
||||
*/
|
||||
|
||||
module.exports = function toFastProperties(obj) {
|
||||
/*jshint -W027*/
|
||||
function f() {}
|
||||
f.prototype = obj;
|
||||
return f;
|
||||
eval(obj);
|
||||
};
|
||||
@@ -1,470 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
module.exports = File;
|
||||
|
||||
var sourceMapToComment = require("source-map-to-comment");
|
||||
var shebangRegex = require("shebang-regex");
|
||||
var isFunction = require("lodash/lang/isFunction");
|
||||
var transform = require("./index");
|
||||
var generate = require("../generation");
|
||||
var defaults = require("lodash/object/defaults");
|
||||
var includes = require("lodash/collection/includes");
|
||||
var assign = require("lodash/object/assign");
|
||||
var parse = require("../helpers/parse");
|
||||
var Scope = require("../traversal/scope");
|
||||
var slash = require("slash");
|
||||
var util = require("../util");
|
||||
var path = require("path");
|
||||
var each = require("lodash/collection/each");
|
||||
var t = require("../types");
|
||||
|
||||
function File(opts) {
|
||||
this.dynamicImportedNoDefault = [];
|
||||
this.dynamicImportIds = {};
|
||||
this.dynamicImported = [];
|
||||
this.dynamicImports = [];
|
||||
|
||||
this.dynamicData = {};
|
||||
this.data = {};
|
||||
|
||||
this.lastStatements = [];
|
||||
this.opts = this.normalizeOptions(opts);
|
||||
this.ast = {};
|
||||
|
||||
this.buildTransformers();
|
||||
}
|
||||
|
||||
File.helpers = [
|
||||
"inherits",
|
||||
"defaults",
|
||||
"prototype-properties",
|
||||
"apply-constructor",
|
||||
"tagged-template-literal",
|
||||
"tagged-template-literal-loose",
|
||||
"interop-require",
|
||||
"to-array",
|
||||
"to-consumable-array",
|
||||
"sliced-to-array",
|
||||
"object-without-properties",
|
||||
"has-own",
|
||||
"slice",
|
||||
"bind",
|
||||
"define-property",
|
||||
"async-to-generator",
|
||||
"interop-require-wildcard",
|
||||
"typeof",
|
||||
"extends",
|
||||
"get",
|
||||
"set",
|
||||
"class-call-check",
|
||||
"object-destructuring-empty",
|
||||
"temporal-undefined",
|
||||
"temporal-assert-defined",
|
||||
"tail-call",
|
||||
"self-global"
|
||||
];
|
||||
|
||||
File.validOptions = [
|
||||
"filename",
|
||||
"filenameRelative",
|
||||
"blacklist",
|
||||
"whitelist",
|
||||
"loose",
|
||||
"optional",
|
||||
"modules",
|
||||
"sourceMap",
|
||||
"sourceMapName",
|
||||
"sourceFileName",
|
||||
"sourceRoot",
|
||||
"moduleRoot",
|
||||
"moduleIds",
|
||||
"comments",
|
||||
"reactCompat",
|
||||
"keepModuleIdExtensions",
|
||||
"code",
|
||||
"ast",
|
||||
"playground",
|
||||
"experimental",
|
||||
"externalHelpers",
|
||||
"auxiliaryComment",
|
||||
"compact",
|
||||
|
||||
"resolveModuleSource",
|
||||
"getModuleName",
|
||||
|
||||
// legacy
|
||||
"format",
|
||||
|
||||
// these are used by plugins
|
||||
"ignore",
|
||||
"only",
|
||||
"extensions",
|
||||
"accept"
|
||||
];
|
||||
|
||||
File.prototype.normalizeOptions = function (opts) {
|
||||
opts = assign({}, opts);
|
||||
|
||||
for (var key in opts) {
|
||||
if (key[0] !== "_" && File.validOptions.indexOf(key) < 0) {
|
||||
throw new ReferenceError("Unknown option: " + key);
|
||||
}
|
||||
}
|
||||
|
||||
defaults(opts, {
|
||||
keepModuleIdExtensions: false,
|
||||
resolveModuleSource: null,
|
||||
externalHelpers: false,
|
||||
auxilaryComment: "",
|
||||
experimental: false,
|
||||
reactCompat: false,
|
||||
playground: false,
|
||||
moduleIds: false,
|
||||
blacklist: [],
|
||||
whitelist: [],
|
||||
sourceMap: false,
|
||||
optional: [],
|
||||
comments: true,
|
||||
filename: "unknown",
|
||||
modules: "common",
|
||||
compact: "auto",
|
||||
loose: [],
|
||||
code: true,
|
||||
ast: true
|
||||
});
|
||||
|
||||
// normalize windows path separators to unix
|
||||
opts.filename = slash(opts.filename);
|
||||
if (opts.sourceRoot) {
|
||||
opts.sourceRoot = slash(opts.sourceRoot);
|
||||
}
|
||||
|
||||
opts.basename = path.basename(opts.filename, path.extname(opts.filename));
|
||||
|
||||
opts.blacklist = util.arrayify(opts.blacklist);
|
||||
opts.whitelist = util.arrayify(opts.whitelist);
|
||||
opts.optional = util.arrayify(opts.optional);
|
||||
opts.compact = util.booleanify(opts.compact);
|
||||
opts.loose = util.arrayify(opts.loose);
|
||||
|
||||
if (includes(opts.loose, "all") || includes(opts.loose, true)) {
|
||||
opts.loose = Object.keys(transform.transformers);
|
||||
}
|
||||
|
||||
defaults(opts, {
|
||||
moduleRoot: opts.sourceRoot
|
||||
});
|
||||
|
||||
defaults(opts, {
|
||||
sourceRoot: opts.moduleRoot
|
||||
});
|
||||
|
||||
defaults(opts, {
|
||||
filenameRelative: opts.filename
|
||||
});
|
||||
|
||||
defaults(opts, {
|
||||
sourceFileName: opts.filenameRelative,
|
||||
sourceMapName: opts.filenameRelative
|
||||
});
|
||||
|
||||
if (opts.playground) {
|
||||
opts.experimental = true;
|
||||
}
|
||||
|
||||
if (opts.externalHelpers) {
|
||||
this.set("runtimeIdentifier", t.identifier("babelHelpers"));
|
||||
}
|
||||
|
||||
opts.blacklist = transform._ensureTransformerNames("blacklist", opts.blacklist);
|
||||
opts.whitelist = transform._ensureTransformerNames("whitelist", opts.whitelist);
|
||||
opts.optional = transform._ensureTransformerNames("optional", opts.optional);
|
||||
opts.loose = transform._ensureTransformerNames("loose", opts.loose);
|
||||
|
||||
if (opts.reactCompat) {
|
||||
opts.optional.push("reactCompat");
|
||||
console.error("The reactCompat option has been moved into the optional transformer `reactCompat`");
|
||||
}
|
||||
|
||||
var ensureEnabled = function (key) {
|
||||
var namespace = transform.transformerNamespaces[key];
|
||||
if (namespace === "es7") opts.experimental = true;
|
||||
if (namespace === "playground") opts.playground = true;
|
||||
};
|
||||
|
||||
each(opts.whitelist, ensureEnabled);
|
||||
each(opts.optional, ensureEnabled);
|
||||
|
||||
return opts;
|
||||
};
|
||||
|
||||
File.prototype.isLoose = function (key) {
|
||||
return includes(this.opts.loose, key);
|
||||
};
|
||||
|
||||
File.prototype.buildTransformers = function () {
|
||||
var file = this;
|
||||
|
||||
var transformers = {};
|
||||
|
||||
var secondaryStack = [];
|
||||
var stack = [];
|
||||
|
||||
each(transform.transformers, function (transformer, key) {
|
||||
var pass = transformers[key] = transformer.buildPass(file);
|
||||
|
||||
if (pass.canRun(file)) {
|
||||
stack.push(pass);
|
||||
|
||||
if (transformer.secondPass) {
|
||||
secondaryStack.push(pass);
|
||||
}
|
||||
|
||||
if (transformer.manipulateOptions) {
|
||||
transformer.manipulateOptions(file.opts, file);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
this.transformerStack = stack.concat(secondaryStack);
|
||||
this.transformers = transformers;
|
||||
};
|
||||
|
||||
File.prototype.debug = function (msg) {
|
||||
var parts = this.opts.filename;
|
||||
if (msg) parts += ": " + msg;
|
||||
util.debug(parts);
|
||||
};
|
||||
|
||||
File.prototype.getModuleFormatter = function (type) {
|
||||
var ModuleFormatter = isFunction(type) ? type : transform.moduleFormatters[type];
|
||||
|
||||
if (!ModuleFormatter) {
|
||||
var loc = util.resolve(type);
|
||||
if (loc) ModuleFormatter = require(loc);
|
||||
}
|
||||
|
||||
if (!ModuleFormatter) {
|
||||
throw new ReferenceError("Unknown module formatter type " + JSON.stringify(type));
|
||||
}
|
||||
|
||||
return new ModuleFormatter(this);
|
||||
};
|
||||
|
||||
File.prototype.parseShebang = function (code) {
|
||||
var shebangMatch = shebangRegex.exec(code);
|
||||
|
||||
if (shebangMatch) {
|
||||
this.shebang = shebangMatch[0];
|
||||
|
||||
// remove shebang
|
||||
code = code.replace(shebangRegex, "");
|
||||
}
|
||||
|
||||
return code;
|
||||
};
|
||||
|
||||
File.prototype.set = function (key, val) {
|
||||
return this.data[key] = val;
|
||||
};
|
||||
|
||||
File.prototype.setDynamic = function (key, fn) {
|
||||
this.dynamicData[key] = fn;
|
||||
};
|
||||
|
||||
File.prototype.get = function (key) {
|
||||
var data = this.data[key];
|
||||
if (data) {
|
||||
return data;
|
||||
} else {
|
||||
var dynamic = this.dynamicData[key];
|
||||
if (dynamic) {
|
||||
return this.set(key, dynamic());
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
File.prototype.addImport = function (source, name, noDefault) {
|
||||
name = name || source;
|
||||
var id = this.dynamicImportIds[name];
|
||||
|
||||
if (!id) {
|
||||
id = this.dynamicImportIds[name] = this.scope.generateUidIdentifier(name);
|
||||
|
||||
var specifiers = [t.importSpecifier(t.identifier("default"), id)];
|
||||
var declar = t.importDeclaration(specifiers, t.literal(source));
|
||||
declar._blockHoist = 3;
|
||||
|
||||
this.dynamicImported.push(declar);
|
||||
if (noDefault) this.dynamicImportedNoDefault.push(declar);
|
||||
|
||||
this.moduleFormatter.importSpecifier(specifiers[0], declar, this.dynamicImports);
|
||||
}
|
||||
|
||||
return id;
|
||||
};
|
||||
|
||||
File.prototype.isConsequenceExpressionStatement = function (node) {
|
||||
return t.isExpressionStatement(node) && this.lastStatements.indexOf(node) >= 0;
|
||||
};
|
||||
|
||||
File.prototype.attachAuxiliaryComment = function (node) {
|
||||
var comment = this.opts.auxiliaryComment;
|
||||
if (comment) {
|
||||
node.leadingComments = node.leadingComments || [];
|
||||
node.leadingComments.push({
|
||||
type: "Line",
|
||||
value: " " + comment
|
||||
});
|
||||
}
|
||||
return node;
|
||||
};
|
||||
|
||||
File.prototype.addHelper = function (name) {
|
||||
if (!includes(File.helpers, name)) {
|
||||
throw new ReferenceError("Unknown helper " + name);
|
||||
}
|
||||
|
||||
var program = this.ast.program;
|
||||
|
||||
var declar = program._declarations && program._declarations[name];
|
||||
if (declar) return declar.id;
|
||||
|
||||
var runtime = this.get("runtimeIdentifier");
|
||||
if (runtime) {
|
||||
name = t.identifier(t.toIdentifier(name));
|
||||
return t.memberExpression(runtime, name);
|
||||
} else {
|
||||
var ref = util.template(name);
|
||||
ref._compact = true;
|
||||
var uid = this.scope.generateUidIdentifier(name);
|
||||
this.scope.push({
|
||||
key: name,
|
||||
id: uid,
|
||||
init: ref
|
||||
});
|
||||
return uid;
|
||||
}
|
||||
};
|
||||
|
||||
File.prototype.logDeopt = function () {
|
||||
// todo, (node, msg)
|
||||
};
|
||||
|
||||
File.prototype.errorWithNode = function (node, msg, Error) {
|
||||
Error = Error || SyntaxError;
|
||||
|
||||
var loc = node.loc.start;
|
||||
var err = new Error("Line " + loc.line + ": " + msg);
|
||||
err.loc = loc;
|
||||
return err;
|
||||
};
|
||||
|
||||
File.prototype.addCode = function (code) {
|
||||
code = (code || "") + "";
|
||||
this.code = code;
|
||||
return this.parseShebang(code);
|
||||
};
|
||||
|
||||
File.prototype.parse = function (code) {
|
||||
var self = this;
|
||||
|
||||
code = this.addCode(code);
|
||||
|
||||
var opts = this.opts;
|
||||
|
||||
opts.allowImportExportEverywhere = this.isLoose("es6.modules");
|
||||
opts.strictMode = this.transformers.useStrict.canRun();
|
||||
|
||||
return parse(opts, code, function (tree) {
|
||||
self.transform(tree);
|
||||
return self.generate();
|
||||
});
|
||||
};
|
||||
|
||||
File.prototype.transform = function (ast) {
|
||||
this.debug();
|
||||
|
||||
this.ast = ast;
|
||||
this.lastStatements = t.getLastStatements(ast.program);
|
||||
this.scope = new Scope(ast.program, ast, null, this);
|
||||
|
||||
var modFormatter = this.moduleFormatter = this.getModuleFormatter(this.opts.modules);
|
||||
if (modFormatter.init && this.transformers["es6.modules"].canRun()) {
|
||||
modFormatter.init();
|
||||
}
|
||||
|
||||
this.checkNode(ast);
|
||||
|
||||
this.call("pre");
|
||||
|
||||
each(this.transformerStack, function (pass) {
|
||||
pass.transform();
|
||||
});
|
||||
|
||||
this.call("post");
|
||||
};
|
||||
|
||||
File.prototype.call = function (key) {
|
||||
var stack = this.transformerStack;
|
||||
for (var i = 0; i < stack.length; i++) {
|
||||
var transformer = stack[i].transformer;
|
||||
if (transformer[key]) {
|
||||
transformer[key](this);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
var checkTransformerVisitor = {
|
||||
enter: function (node, parent, scope, state) {
|
||||
checkNode(state.stack, node, scope);
|
||||
}
|
||||
};
|
||||
|
||||
var checkNode = function (stack, node, scope) {
|
||||
each(stack, function (pass) {
|
||||
if (pass.shouldRun) return;
|
||||
pass.checkNode(node, scope);
|
||||
});
|
||||
};
|
||||
|
||||
File.prototype.checkNode = function (node, scope) {
|
||||
var stack = this.transformerStack;
|
||||
scope = scope || this.scope;
|
||||
|
||||
checkNode(stack, node, scope);
|
||||
|
||||
scope.traverse(node, checkTransformerVisitor, {
|
||||
stack: stack
|
||||
});
|
||||
};
|
||||
|
||||
File.prototype.generate = function () {
|
||||
var opts = this.opts;
|
||||
var ast = this.ast;
|
||||
|
||||
var result = {
|
||||
code: "",
|
||||
map: null,
|
||||
ast: null
|
||||
};
|
||||
|
||||
if (opts.ast) result.ast = ast;
|
||||
if (!opts.code) return result;
|
||||
|
||||
var _result = generate(ast, opts, this.code);
|
||||
result.code = _result.code;
|
||||
result.map = _result.map;
|
||||
|
||||
if (this.shebang) {
|
||||
// add back shebang
|
||||
result.code = this.shebang + "\n" + result.code;
|
||||
}
|
||||
|
||||
if (opts.sourceMap === "inline") {
|
||||
result.code += "\n" + sourceMapToComment(result.map);
|
||||
result.map = null;
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
@@ -1,73 +0,0 @@
|
||||
var cloneDeep = require("lodash/lang/cloneDeep");
|
||||
var traverse = require("../../traversal");
|
||||
var clone = require("lodash/lang/clone");
|
||||
var each = require("lodash/collection/each");
|
||||
var has = require("lodash/object/has");
|
||||
var t = require("../../types");
|
||||
|
||||
exports.push = function (mutatorMap, key, kind, computed, value) {
|
||||
var alias;
|
||||
|
||||
if (t.isIdentifier(key)) {
|
||||
alias = key.name;
|
||||
if (computed) alias = "computed:" + alias;
|
||||
} else if (t.isLiteral(key)) {
|
||||
alias = String(key.value);
|
||||
} else {
|
||||
alias = JSON.stringify(traverse.removeProperties(cloneDeep(key)));
|
||||
}
|
||||
|
||||
var map;
|
||||
if (has(mutatorMap, alias)) {
|
||||
map = mutatorMap[alias];
|
||||
} else {
|
||||
map = {};
|
||||
}
|
||||
mutatorMap[alias] = map;
|
||||
|
||||
map._key = key;
|
||||
if (computed) {
|
||||
map._computed = true;
|
||||
}
|
||||
|
||||
map[kind] = value;
|
||||
};
|
||||
|
||||
exports.build = function (mutatorMap) {
|
||||
var objExpr = t.objectExpression([]);
|
||||
|
||||
each(mutatorMap, function (map) {
|
||||
var mapNode = t.objectExpression([]);
|
||||
|
||||
var propNode = t.property("init", map._key, mapNode, map._computed);
|
||||
|
||||
if (!map.get && !map.set) {
|
||||
map.writable = t.literal(true);
|
||||
}
|
||||
|
||||
if (map.enumerable === false) {
|
||||
delete map.enumerable;
|
||||
} else {
|
||||
map.enumerable = t.literal(true);
|
||||
}
|
||||
|
||||
map.configurable = t.literal(true);
|
||||
|
||||
each(map, function (node, key) {
|
||||
if (key[0] === "_") return;
|
||||
|
||||
node = clone(node);
|
||||
var inheritNode = node;
|
||||
if (t.isMethodDefinition(node)) node = node.value;
|
||||
|
||||
var prop = t.property("init", t.identifier(key), node);
|
||||
t.inheritsComments(prop, inheritNode);
|
||||
t.removeComments(inheritNode);
|
||||
mapNode.properties.push(prop);
|
||||
});
|
||||
|
||||
objExpr.properties.push(propNode);
|
||||
});
|
||||
|
||||
return objExpr;
|
||||
};
|
||||
@@ -1,53 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
var util = require("../../util");
|
||||
var t = require("../../types");
|
||||
|
||||
var visitor = {
|
||||
enter: function (node, parent, scope, state) {
|
||||
// check if this node is an identifier that matches the same as our function id
|
||||
if (!t.isIdentifier(node, { name: state.id })) return;
|
||||
|
||||
// check if this node is the one referenced
|
||||
if (!t.isReferenced(node, parent)) return;
|
||||
|
||||
// check that we don't have a local variable declared as that removes the need
|
||||
// for the wrapper
|
||||
var localDeclar = scope.getBindingIdentifier(state.id);
|
||||
if (localDeclar !== state.outerDeclar) return;
|
||||
|
||||
state.selfReference = true;
|
||||
this.stop();
|
||||
}
|
||||
};
|
||||
|
||||
exports.property = function (node, file, scope) {
|
||||
var key = t.toComputedKey(node, node.key);
|
||||
if (!t.isLiteral(key)) return node; // we can't set a function id with this
|
||||
|
||||
var id = t.toIdentifier(key.value);
|
||||
key = t.identifier(id);
|
||||
|
||||
var state = {
|
||||
id: id,
|
||||
selfReference: false,
|
||||
outerDeclar: scope.getBindingIdentifier(id),
|
||||
};
|
||||
|
||||
scope.traverse(node, visitor, state);
|
||||
|
||||
var method = node.value;
|
||||
|
||||
if (state.selfReference) {
|
||||
var templateName = "property-method-assignment-wrapper";
|
||||
if (method.generator) templateName += "-generator";
|
||||
node.value = util.template(templateName, {
|
||||
FUNCTION: method,
|
||||
FUNCTION_ID: key,
|
||||
FUNCTION_KEY: scope.generateUidIdentifier(id),
|
||||
WRAPPER_KEY: scope.generateUidIdentifier(id + "Wrapper")
|
||||
});
|
||||
} else {
|
||||
method.id = key;
|
||||
}
|
||||
};
|
||||
@@ -1,40 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
var t = require("../../types");
|
||||
|
||||
var visitor = {
|
||||
enter: function (node) {
|
||||
if (t.isFunction(node)) this.skip();
|
||||
|
||||
if (t.isAwaitExpression(node)) {
|
||||
node.type = "YieldExpression";
|
||||
|
||||
if (node.all) {
|
||||
// await* foo; -> yield Promise.all(foo);
|
||||
node.all = false;
|
||||
node.argument = t.callExpression(t.memberExpression(t.identifier("Promise"), t.identifier("all")), [node.argument]);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = function (node, callId, scope) {
|
||||
node.async = false;
|
||||
node.generator = true;
|
||||
|
||||
scope.traverse(node, visitor);
|
||||
|
||||
var call = t.callExpression(callId, [node]);
|
||||
var id = node.id;
|
||||
delete node.id;
|
||||
|
||||
if (t.isFunctionDeclaration(node)) {
|
||||
var declar = t.variableDeclaration("let", [
|
||||
t.variableDeclarator(id, call)
|
||||
]);
|
||||
declar._blockHoist = true;
|
||||
return declar;
|
||||
} else {
|
||||
return call;
|
||||
}
|
||||
};
|
||||
@@ -1,303 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
module.exports = ReplaceSupers;
|
||||
|
||||
var messages = require("../../messages");
|
||||
var t = require("../../types");
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {Object} opts
|
||||
* @param {Boolean} [inClass]
|
||||
*/
|
||||
|
||||
function ReplaceSupers(opts, inClass) {
|
||||
this.topLevelThisReference = opts.topLevelThisReference;
|
||||
this.methodNode = opts.methodNode;
|
||||
this.className = opts.className;
|
||||
this.superName = opts.superName;
|
||||
this.isStatic = opts.isStatic;
|
||||
this.hasSuper = false;
|
||||
this.inClass = inClass;
|
||||
this.isLoose = opts.isLoose;
|
||||
this.scope = opts.scope;
|
||||
this.file = opts.file;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a super class value of the named property.
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* _set(Object.getPrototypeOf(CLASS.prototype), "METHOD", "VALUE", this)
|
||||
*
|
||||
* @param {Node} property
|
||||
* @param {Node} value
|
||||
* @param {Boolean} isComputed
|
||||
* @param {Node} thisExpression
|
||||
*
|
||||
* @returns {Node}
|
||||
*/
|
||||
|
||||
ReplaceSupers.prototype.setSuperProperty = function (property, value, isComputed, thisExpression) {
|
||||
return t.callExpression(
|
||||
this.file.addHelper("set"),
|
||||
[
|
||||
t.callExpression(
|
||||
t.memberExpression(t.identifier("Object"), t.identifier("getPrototypeOf")),
|
||||
[
|
||||
this.isStatic ? this.className : t.memberExpression(this.className, t.identifier("prototype"))
|
||||
]
|
||||
),
|
||||
isComputed ? property : t.literal(property.name),
|
||||
value,
|
||||
thisExpression
|
||||
]
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets a node representing the super class value of the named property.
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* _get(Object.getPrototypeOf(CLASS.prototype), "METHOD", this)
|
||||
*
|
||||
* @param {Node} property
|
||||
* @param {Boolean} isComputed
|
||||
* @param {Node} thisExpression
|
||||
*
|
||||
* @returns {Node}
|
||||
*/
|
||||
|
||||
ReplaceSupers.prototype.getSuperProperty = function (property, isComputed, thisExpression) {
|
||||
return t.callExpression(
|
||||
this.file.addHelper("get"),
|
||||
[
|
||||
t.callExpression(
|
||||
t.memberExpression(t.identifier("Object"), t.identifier("getPrototypeOf")),
|
||||
[
|
||||
this.isStatic ? this.className : t.memberExpression(this.className, t.identifier("prototype"))
|
||||
]
|
||||
),
|
||||
isComputed ? property : t.literal(property.name),
|
||||
thisExpression
|
||||
]
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*/
|
||||
|
||||
ReplaceSupers.prototype.replace = function () {
|
||||
this.traverseLevel(this.methodNode.value, true);
|
||||
};
|
||||
|
||||
var visitor = {
|
||||
enter: function (node, parent, scope, state) {
|
||||
var topLevel = state.topLevel;
|
||||
var self = state.self;
|
||||
|
||||
if (t.isFunction(node) && !t.isArrowFunctionExpression(node)) {
|
||||
// we need to call traverseLevel again so we're context aware
|
||||
self.traverseLevel(node, false);
|
||||
return this.skip();
|
||||
}
|
||||
|
||||
if (t.isProperty(node, { method: true }) || t.isMethodDefinition(node)) {
|
||||
// break on object methods
|
||||
return this.skip();
|
||||
}
|
||||
|
||||
var getThisReference = topLevel ?
|
||||
// top level so `this` is the instance
|
||||
t.thisExpression :
|
||||
// not in the top level so we need to create a reference
|
||||
self.getThisReference.bind(self);
|
||||
|
||||
var callback = self.specHandle;
|
||||
if (self.isLoose) callback = self.looseHandle;
|
||||
return callback.call(self, getThisReference, node, parent);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {Object} node
|
||||
* @param {Boolean} topLevel
|
||||
*/
|
||||
|
||||
ReplaceSupers.prototype.traverseLevel = function (node, topLevel) {
|
||||
var state = { self: this, topLevel: topLevel };
|
||||
this.scope.traverse(node, visitor, state);
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*/
|
||||
|
||||
ReplaceSupers.prototype.getThisReference = function () {
|
||||
if (this.topLevelThisReference) {
|
||||
return this.topLevelThisReference;
|
||||
} else {
|
||||
var ref = this.topLevelThisReference = this.scope.generateUidIdentifier("this");
|
||||
this.methodNode.value.body.body.unshift(t.variableDeclaration("var", [
|
||||
t.variableDeclarator(this.topLevelThisReference, t.thisExpression())
|
||||
]));
|
||||
return ref;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {Object} node
|
||||
* @param {Object} id
|
||||
* @param {Object} parent
|
||||
* @returns {Object}
|
||||
*/
|
||||
|
||||
ReplaceSupers.prototype.getLooseSuperProperty = function (id, parent) {
|
||||
var methodNode = this.methodNode;
|
||||
var methodName = methodNode.key;
|
||||
var superName = this.superName || t.identifier("Function");
|
||||
|
||||
if (parent.property === id) {
|
||||
return;
|
||||
} else if (t.isCallExpression(parent, { callee: id })) {
|
||||
// super(); -> ClassName.prototype.MethodName.call(this);
|
||||
parent.arguments.unshift(t.thisExpression());
|
||||
|
||||
if (methodName.name === "constructor") {
|
||||
// constructor() { super(); }
|
||||
return t.memberExpression(superName, t.identifier("call"));
|
||||
} else {
|
||||
id = superName;
|
||||
|
||||
// foo() { super(); }
|
||||
if (!methodNode.static) {
|
||||
id = t.memberExpression(id, t.identifier("prototype"));
|
||||
}
|
||||
|
||||
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
|
||||
return t.memberExpression(superName, t.identifier("prototype"));
|
||||
} else {
|
||||
return superName;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {Function} getThisReference
|
||||
* @param {Object} node
|
||||
* @param {Object} parent
|
||||
*/
|
||||
|
||||
ReplaceSupers.prototype.looseHandle = function (getThisReference, node, parent) {
|
||||
if (t.isIdentifier(node, { name: "super" })) {
|
||||
this.hasSuper = true;
|
||||
return this.getLooseSuperProperty(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);
|
||||
this.hasSuper = true;
|
||||
t.appendToMemberExpression(callee, t.identifier("call"));
|
||||
node.arguments.unshift(getThisReference());
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {Function} getThisReference
|
||||
* @param {Object} node
|
||||
* @param {Object} parent
|
||||
*/
|
||||
|
||||
ReplaceSupers.prototype.specHandle = function (getThisReference, node, parent) {
|
||||
var methodNode = this.methodNode;
|
||||
var property;
|
||||
var computed;
|
||||
var args;
|
||||
var thisReference;
|
||||
|
||||
if (isIllegalBareSuper(node, parent)) {
|
||||
throw this.file.errorWithNode(node, messages.get("classesIllegalBareSuper"));
|
||||
}
|
||||
|
||||
if (t.isCallExpression(node)) {
|
||||
var callee = node.callee;
|
||||
if (isSuper(callee, node)) {
|
||||
// super(); -> _get(Object.getPrototypeOf(ClassName), "MethodName", this).call(this);
|
||||
property = methodNode.key;
|
||||
computed = methodNode.computed;
|
||||
args = node.arguments;
|
||||
|
||||
// bare `super` call is illegal inside non-constructors
|
||||
// - https://esdiscuss.org/topic/super-call-in-methods
|
||||
// - https://twitter.com/wycats/status/544553184396836864
|
||||
if (methodNode.key.name !== "constructor" || !this.inClass) {
|
||||
var methodName = methodNode.key.name || "METHOD_NAME";
|
||||
throw this.file.errorWithNode(node, messages.get("classesIllegalSuperCall", methodName));
|
||||
}
|
||||
} else if (t.isMemberExpression(callee) && isSuper(callee.object, callee)) {
|
||||
// super.test(); -> _get(Object.getPrototypeOf(ClassName.prototype), "test", this).call(this);
|
||||
property = callee.property;
|
||||
computed = callee.computed;
|
||||
args = node.arguments;
|
||||
}
|
||||
} else if (t.isMemberExpression(node) && isSuper(node.object, node)) {
|
||||
// super.name; -> _get(Object.getPrototypeOf(ClassName.prototype), "name", this);
|
||||
property = node.property;
|
||||
computed = node.computed;
|
||||
} else if (t.isAssignmentExpression(node) && isSuper(node.left.object, node.left) && methodNode.kind === "set") {
|
||||
// super.name = "val"; -> _set(Object.getPrototypeOf(ClassName.prototype), "name", this);
|
||||
this.hasSuper = true;
|
||||
return this.setSuperProperty(node.left.property, node.right, node.left.computed, getThisReference());
|
||||
}
|
||||
|
||||
if (!property) return;
|
||||
|
||||
this.hasSuper = true;
|
||||
|
||||
thisReference = getThisReference();
|
||||
var superProperty = this.getSuperProperty(property, computed, thisReference);
|
||||
if (args) {
|
||||
if (args.length === 1 && t.isSpreadElement(args[0])) {
|
||||
// super(...arguments);
|
||||
return t.callExpression(
|
||||
t.memberExpression(superProperty, t.identifier("apply")),
|
||||
[thisReference, args[0].argument]
|
||||
);
|
||||
} else {
|
||||
return t.callExpression(
|
||||
t.memberExpression(superProperty, t.identifier("call")),
|
||||
[thisReference].concat(args)
|
||||
);
|
||||
}
|
||||
} else {
|
||||
return superProperty;
|
||||
}
|
||||
};
|
||||
|
||||
var isIllegalBareSuper = function (node, parent) {
|
||||
if (!isSuper(node, parent)) return false;
|
||||
if (t.isMemberExpression(parent, { computed: false })) return false;
|
||||
if (t.isCallExpression(parent, { callee: node })) return false;
|
||||
return true;
|
||||
};
|
||||
|
||||
var isSuper = function (node, parent) {
|
||||
return t.isIdentifier(node, { name: "super" }) && t.isReferenced(node, parent);
|
||||
};
|
||||
@@ -1,295 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
module.exports = DefaultFormatter;
|
||||
|
||||
var messages = require("../../messages");
|
||||
var extend = require("lodash/object/extend");
|
||||
var object = require("../../helpers/object");
|
||||
var util = require("../../util");
|
||||
var t = require("../../types");
|
||||
|
||||
function DefaultFormatter(file) {
|
||||
this.scope = file.scope;
|
||||
this.file = file;
|
||||
this.ids = object();
|
||||
|
||||
this.hasNonDefaultExports = false;
|
||||
|
||||
this.hasLocalExports = false;
|
||||
this.hasLocalImports = false;
|
||||
|
||||
this.localImportOccurences = object();
|
||||
this.localExports = object();
|
||||
this.localImports = object();
|
||||
|
||||
this.getLocalExports();
|
||||
this.getLocalImports();
|
||||
|
||||
this.remapAssignments();
|
||||
}
|
||||
|
||||
DefaultFormatter.prototype.doDefaultExportInterop = function (node) {
|
||||
return node.default && !this.noInteropRequireExport && !this.hasNonDefaultExports;
|
||||
};
|
||||
|
||||
DefaultFormatter.prototype.bumpImportOccurences = function (node) {
|
||||
var source = node.source.value;
|
||||
var occurs = this.localImportOccurences;
|
||||
occurs[source] = occurs[source] || 0;
|
||||
occurs[source] += node.specifiers.length;
|
||||
};
|
||||
|
||||
var exportsVisitor = {
|
||||
enter: function (node, parent, scope, formatter) {
|
||||
var declar = node && node.declaration;
|
||||
if (t.isExportDeclaration(node)) {
|
||||
formatter.hasLocalImports = true;
|
||||
|
||||
if (declar && t.isStatement(declar)) {
|
||||
extend(formatter.localExports, t.getBindingIdentifiers(declar));
|
||||
}
|
||||
|
||||
if (!node.default) {
|
||||
formatter.hasNonDefaultExports = true;
|
||||
}
|
||||
|
||||
if (node.source) {
|
||||
formatter.bumpImportOccurences(node);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
DefaultFormatter.prototype.getLocalExports = function () {
|
||||
this.file.scope.traverse(this.file.ast, exportsVisitor, this);
|
||||
};
|
||||
|
||||
var importsVisitor = {
|
||||
enter: function (node, parent, scope, formatter) {
|
||||
if (t.isImportDeclaration(node)) {
|
||||
formatter.hasLocalImports = true;
|
||||
extend(formatter.localImports, t.getBindingIdentifiers(node));
|
||||
formatter.bumpImportOccurences(node);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
DefaultFormatter.prototype.getLocalImports = function () {
|
||||
this.file.scope.traverse(this.file.ast, importsVisitor, this);
|
||||
};
|
||||
|
||||
var remapVisitor = {
|
||||
enter: function (node, parent, scope, formatter) {
|
||||
if (t.isUpdateExpression(node) && formatter.isLocalReference(node.argument, scope)) {
|
||||
this.skip();
|
||||
|
||||
// expand to long file assignment expression
|
||||
var assign = t.assignmentExpression(node.operator[0] + "=", node.argument, t.literal(1));
|
||||
|
||||
// remap this assignment expression
|
||||
var remapped = formatter.remapExportAssignment(assign);
|
||||
|
||||
// we don't need to change the result
|
||||
if (t.isExpressionStatement(parent) || node.prefix) {
|
||||
return remapped;
|
||||
}
|
||||
|
||||
var nodes = [];
|
||||
nodes.push(remapped);
|
||||
|
||||
var operator;
|
||||
if (node.operator === "--") {
|
||||
operator = "+";
|
||||
} else { // "++"
|
||||
operator = "-";
|
||||
}
|
||||
nodes.push(t.binaryExpression(operator, node.argument, t.literal(1)));
|
||||
|
||||
return t.sequenceExpression(nodes);
|
||||
}
|
||||
|
||||
if (t.isAssignmentExpression(node) && formatter.isLocalReference(node.left, scope)) {
|
||||
this.skip();
|
||||
return formatter.remapExportAssignment(node);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
DefaultFormatter.prototype.remapAssignments = function () {
|
||||
if (this.hasLocalImports) {
|
||||
this.file.scope.traverse(this.file.ast, remapVisitor, this);
|
||||
}
|
||||
};
|
||||
|
||||
DefaultFormatter.prototype.isLocalReference = function (node) {
|
||||
var localImports = this.localImports;
|
||||
return t.isIdentifier(node) && localImports[node.name] && localImports[node.name] !== node;
|
||||
};
|
||||
|
||||
DefaultFormatter.prototype.remapExportAssignment = function (node) {
|
||||
return t.assignmentExpression(
|
||||
"=",
|
||||
node.left,
|
||||
t.assignmentExpression(
|
||||
node.operator,
|
||||
t.memberExpression(t.identifier("exports"), node.left),
|
||||
node.right
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
DefaultFormatter.prototype.isLocalReference = function (node, scope) {
|
||||
var localExports = this.localExports;
|
||||
var name = node.name;
|
||||
return t.isIdentifier(node) && localExports[name] && localExports[name] === scope.getBindingIdentifier(name);
|
||||
};
|
||||
|
||||
DefaultFormatter.prototype.getModuleName = function () {
|
||||
var opts = this.file.opts;
|
||||
if (opts.getModuleName) return opts.getModuleName(opts.filename);
|
||||
|
||||
var filenameRelative = opts.filenameRelative;
|
||||
var moduleName = "";
|
||||
|
||||
if (opts.moduleRoot) {
|
||||
moduleName = opts.moduleRoot + "/";
|
||||
}
|
||||
|
||||
if (!opts.filenameRelative) {
|
||||
return moduleName + opts.filename.replace(/^\//, "");
|
||||
}
|
||||
|
||||
if (opts.sourceRoot) {
|
||||
// remove sourceRoot from filename
|
||||
var sourceRootRegEx = new RegExp("^" + opts.sourceRoot + "\/?");
|
||||
filenameRelative = filenameRelative.replace(sourceRootRegEx, "");
|
||||
}
|
||||
|
||||
if (!opts.keepModuleIdExtensions) {
|
||||
// remove extension
|
||||
filenameRelative = filenameRelative.replace(/\.(\w*?)$/, "");
|
||||
}
|
||||
|
||||
moduleName += filenameRelative;
|
||||
|
||||
// normalize path separators
|
||||
moduleName = moduleName.replace(/\\/g, "/");
|
||||
|
||||
return moduleName;
|
||||
};
|
||||
|
||||
DefaultFormatter.prototype._pushStatement = function (ref, nodes) {
|
||||
if (t.isClass(ref) || t.isFunction(ref)) {
|
||||
if (ref.id) {
|
||||
nodes.push(t.toStatement(ref));
|
||||
ref = ref.id;
|
||||
}
|
||||
}
|
||||
|
||||
return ref;
|
||||
};
|
||||
|
||||
DefaultFormatter.prototype._hoistExport = function (declar, assign, priority) {
|
||||
if (t.isFunctionDeclaration(declar)) {
|
||||
assign._blockHoist = priority || 2;
|
||||
}
|
||||
|
||||
return assign;
|
||||
};
|
||||
|
||||
DefaultFormatter.prototype.getExternalReference = function (node, nodes) {
|
||||
var ids = this.ids;
|
||||
var id = node.source.value;
|
||||
|
||||
if (ids[id]) {
|
||||
return ids[id];
|
||||
} else {
|
||||
return this.ids[id] = this._getExternalReference(node, nodes);
|
||||
}
|
||||
};
|
||||
|
||||
DefaultFormatter.prototype.checkExportIdentifier = function (node) {
|
||||
if (t.isIdentifier(node, { name: "__esModule" })) {
|
||||
throw this.file.errorWithNode(node, messages.get("modulesIllegalExportName", node.name));
|
||||
}
|
||||
};
|
||||
|
||||
DefaultFormatter.prototype.exportSpecifier = function (specifier, node, nodes) {
|
||||
if (node.source) {
|
||||
var ref = this.getExternalReference(node, nodes);
|
||||
|
||||
if (t.isExportBatchSpecifier(specifier)) {
|
||||
// export * from "foo";
|
||||
nodes.push(this.buildExportsWildcard(ref, node));
|
||||
} else {
|
||||
if (t.isSpecifierDefault(specifier) && !this.noInteropRequireExport) {
|
||||
// importing a default so we need to normalize it
|
||||
ref = t.callExpression(this.file.addHelper("interop-require"), [ref]);
|
||||
} else {
|
||||
ref = t.memberExpression(ref, t.getSpecifierId(specifier));
|
||||
}
|
||||
|
||||
// export { foo } from "test";
|
||||
nodes.push(this.buildExportsAssignment(
|
||||
t.getSpecifierName(specifier),
|
||||
ref,
|
||||
node
|
||||
));
|
||||
}
|
||||
} else {
|
||||
// export { foo };
|
||||
nodes.push(this.buildExportsAssignment(t.getSpecifierName(specifier), specifier.id, node));
|
||||
}
|
||||
};
|
||||
|
||||
DefaultFormatter.prototype.buildExportsWildcard = function (objectIdentifier) {
|
||||
return t.expressionStatement(t.callExpression(this.file.addHelper("defaults"), [
|
||||
t.identifier("exports"),
|
||||
t.callExpression(this.file.addHelper("interop-require-wildcard"), [objectIdentifier])
|
||||
]));
|
||||
};
|
||||
|
||||
DefaultFormatter.prototype.buildExportsAssignment = function (id, init) {
|
||||
this.checkExportIdentifier(id);
|
||||
return util.template("exports-assign", {
|
||||
VALUE: init,
|
||||
KEY: id
|
||||
}, true);
|
||||
};
|
||||
|
||||
DefaultFormatter.prototype.exportDeclaration = function (node, nodes) {
|
||||
var declar = node.declaration;
|
||||
|
||||
var id = declar.id;
|
||||
|
||||
if (node.default) {
|
||||
id = t.identifier("default");
|
||||
}
|
||||
|
||||
var assign;
|
||||
|
||||
if (t.isVariableDeclaration(declar)) {
|
||||
for (var i = 0; i < declar.declarations.length; i++) {
|
||||
var decl = declar.declarations[i];
|
||||
|
||||
decl.init = this.buildExportsAssignment(decl.id, decl.init, node).expression;
|
||||
|
||||
var newDeclar = t.variableDeclaration(declar.kind, [decl]);
|
||||
if (i === 0) t.inherits(newDeclar, declar);
|
||||
nodes.push(newDeclar);
|
||||
}
|
||||
} else {
|
||||
var ref = declar;
|
||||
|
||||
if (t.isFunctionDeclaration(declar) || t.isClassDeclaration(declar)) {
|
||||
ref = declar.id;
|
||||
nodes.push(declar);
|
||||
}
|
||||
|
||||
assign = this.buildExportsAssignment(id, ref, node);
|
||||
|
||||
nodes.push(assign);
|
||||
|
||||
this._hoistExport(declar, assign);
|
||||
}
|
||||
};
|
||||
@@ -1,108 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
module.exports = AMDFormatter;
|
||||
|
||||
var DefaultFormatter = require("./_default");
|
||||
var CommonFormatter = require("./common");
|
||||
var includes = require("lodash/collection/includes");
|
||||
var values = require("lodash/object/values");
|
||||
var util = require("../../util");
|
||||
var t = require("../../types");
|
||||
|
||||
function AMDFormatter() {
|
||||
CommonFormatter.apply(this, arguments);
|
||||
}
|
||||
|
||||
util.inherits(AMDFormatter, DefaultFormatter);
|
||||
|
||||
AMDFormatter.prototype.init = CommonFormatter.prototype.init;
|
||||
|
||||
AMDFormatter.prototype.buildDependencyLiterals = function () {
|
||||
var names = [];
|
||||
for (var name in this.ids) {
|
||||
names.push(t.literal(name));
|
||||
}
|
||||
return names;
|
||||
};
|
||||
|
||||
/**
|
||||
* Wrap the entire body in a `define` wrapper.
|
||||
*/
|
||||
|
||||
AMDFormatter.prototype.transform = function (program) {
|
||||
var body = program.body;
|
||||
|
||||
// build an array of module names
|
||||
|
||||
var names = [t.literal("exports")];
|
||||
if (this.passModuleArg) names.push(t.literal("module"));
|
||||
names = names.concat(this.buildDependencyLiterals());
|
||||
names = t.arrayExpression(names);
|
||||
|
||||
// build up define container
|
||||
|
||||
var params = values(this.ids);
|
||||
if (this.passModuleArg) params.unshift(t.identifier("module"));
|
||||
params.unshift(t.identifier("exports"));
|
||||
|
||||
var container = t.functionExpression(null, params, t.blockStatement(body));
|
||||
|
||||
var defineArgs = [names, container];
|
||||
var moduleName = this.getModuleName();
|
||||
if (moduleName) defineArgs.unshift(t.literal(moduleName));
|
||||
|
||||
var call = t.callExpression(t.identifier("define"), defineArgs);
|
||||
|
||||
program.body = [t.expressionStatement(call)];
|
||||
};
|
||||
|
||||
/**
|
||||
* Get the AMD module name that we'll prepend to the wrapper
|
||||
* to define this module
|
||||
*/
|
||||
|
||||
AMDFormatter.prototype.getModuleName = function () {
|
||||
if (this.file.opts.moduleIds) {
|
||||
return DefaultFormatter.prototype.getModuleName.apply(this, arguments);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
AMDFormatter.prototype._getExternalReference = function (node) {
|
||||
return this.scope.generateUidIdentifier(node.source.value);
|
||||
};
|
||||
|
||||
AMDFormatter.prototype.importDeclaration = function (node) {
|
||||
this.getExternalReference(node);
|
||||
};
|
||||
|
||||
AMDFormatter.prototype.importSpecifier = function (specifier, node, nodes) {
|
||||
var key = t.getSpecifierName(specifier);
|
||||
var ref = this.getExternalReference(node);
|
||||
|
||||
if (includes(this.file.dynamicImportedNoDefault, node)) {
|
||||
// Prevent unnecessary renaming of dynamic imports.
|
||||
this.ids[node.source.value] = ref;
|
||||
} else if (t.isImportBatchSpecifier(specifier)) {
|
||||
// import * as bar from "foo";
|
||||
} else if (!includes(this.file.dynamicImported, node) && t.isSpecifierDefault(specifier) && !this.noInteropRequireImport) {
|
||||
// import foo from "foo";
|
||||
ref = t.callExpression(this.file.addHelper("interop-require"), [ref]);
|
||||
} else {
|
||||
// import {foo} from "foo";
|
||||
ref = t.memberExpression(ref, t.getSpecifierId(specifier), false);
|
||||
}
|
||||
|
||||
nodes.push(t.variableDeclaration("var", [
|
||||
t.variableDeclarator(key, ref)
|
||||
]));
|
||||
};
|
||||
|
||||
AMDFormatter.prototype.exportDeclaration = function (node) {
|
||||
if (this.doDefaultExportInterop(node)) {
|
||||
this.passModuleArg = true;
|
||||
}
|
||||
|
||||
CommonFormatter.prototype.exportDeclaration.apply(this, arguments);
|
||||
};
|
||||
@@ -1,106 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
module.exports = CommonJSFormatter;
|
||||
|
||||
var DefaultFormatter = require("./_default");
|
||||
var includes = require("lodash/collection/includes");
|
||||
var util = require("../../util");
|
||||
var t = require("../../types");
|
||||
|
||||
function CommonJSFormatter() {
|
||||
DefaultFormatter.apply(this, arguments);
|
||||
}
|
||||
|
||||
util.inherits(CommonJSFormatter, DefaultFormatter);
|
||||
|
||||
CommonJSFormatter.prototype.init = function () {
|
||||
var file = this.file;
|
||||
var scope = file.scope;
|
||||
|
||||
scope.rename("module");
|
||||
|
||||
if (!this.noInteropRequireImport && this.hasNonDefaultExports) {
|
||||
var templateName = "exports-module-declaration";
|
||||
if (this.file.isLoose("es6.modules")) templateName += "-loose";
|
||||
file.ast.program.body.push(util.template(templateName, true));
|
||||
}
|
||||
};
|
||||
|
||||
CommonJSFormatter.prototype.importSpecifier = function (specifier, node, nodes) {
|
||||
var variableName = t.getSpecifierName(specifier);
|
||||
|
||||
var ref = this.getExternalReference(node, nodes);
|
||||
|
||||
// import foo from "foo";
|
||||
if (t.isSpecifierDefault(specifier)) {
|
||||
if (!includes(this.file.dynamicImportedNoDefault, node)) {
|
||||
if (this.noInteropRequireImport || includes(this.file.dynamicImported, node)) {
|
||||
ref = t.memberExpression(ref, t.identifier("default"));
|
||||
} else {
|
||||
ref = t.callExpression(this.file.addHelper("interop-require"), [ref]);
|
||||
}
|
||||
}
|
||||
nodes.push(t.variableDeclaration("var", [t.variableDeclarator(variableName, ref)]));
|
||||
} else {
|
||||
if (specifier.type === "ImportBatchSpecifier") {
|
||||
|
||||
if (!this.noInteropRequireImport) {
|
||||
ref = t.callExpression(this.file.addHelper("interop-require-wildcard"), [ref]);
|
||||
}
|
||||
|
||||
// import * as bar from "foo";
|
||||
nodes.push(t.variableDeclaration("var", [
|
||||
t.variableDeclarator(variableName, ref)
|
||||
]));
|
||||
} else {
|
||||
// import { foo } from "foo";
|
||||
nodes.push(t.variableDeclaration("var", [
|
||||
t.variableDeclarator(
|
||||
variableName,
|
||||
t.memberExpression(ref, t.getSpecifierId(specifier))
|
||||
)
|
||||
]));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
CommonJSFormatter.prototype.importDeclaration = function (node, nodes) {
|
||||
// import "foo";
|
||||
nodes.push(util.template("require", {
|
||||
MODULE_NAME: node.source
|
||||
}, true));
|
||||
};
|
||||
|
||||
CommonJSFormatter.prototype.exportDeclaration = function (node, nodes) {
|
||||
if (this.doDefaultExportInterop(node)) {
|
||||
var declar = node.declaration;
|
||||
var assign = util.template("exports-default-assign", {
|
||||
VALUE: this._pushStatement(declar, nodes)
|
||||
}, true);
|
||||
|
||||
if (t.isFunctionDeclaration(declar)) {
|
||||
// we can hoist this assignment to the top of the file
|
||||
assign._blockHoist = 3;
|
||||
}
|
||||
|
||||
nodes.push(assign);
|
||||
return;
|
||||
}
|
||||
|
||||
DefaultFormatter.prototype.exportDeclaration.apply(this, arguments);
|
||||
};
|
||||
|
||||
CommonJSFormatter.prototype._getExternalReference = function (node, nodes) {
|
||||
var source = node.source.value;
|
||||
var call = t.callExpression(t.identifier("require"), [node.source]);
|
||||
|
||||
if (this.localImportOccurences[source] > 1) {
|
||||
var uid = this.scope.generateUidIdentifier(source);
|
||||
nodes.push(t.variableDeclaration("var", [
|
||||
t.variableDeclarator(uid, call)
|
||||
]));
|
||||
return uid;
|
||||
} else {
|
||||
return call;
|
||||
}
|
||||
};
|
||||
@@ -1,20 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
module.exports = IgnoreFormatter;
|
||||
|
||||
var t = require("../../types");
|
||||
|
||||
function IgnoreFormatter() {
|
||||
|
||||
}
|
||||
|
||||
IgnoreFormatter.prototype.exportDeclaration = function (node, nodes) {
|
||||
var declar = t.toStatement(node.declaration, true);
|
||||
if (declar) nodes.push(t.inherits(declar, node));
|
||||
};
|
||||
|
||||
IgnoreFormatter.prototype.importDeclaration =
|
||||
IgnoreFormatter.prototype.importSpecifier =
|
||||
IgnoreFormatter.prototype.exportSpecifier = function () {
|
||||
|
||||
};
|
||||
@@ -1,196 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
module.exports = SystemFormatter;
|
||||
|
||||
var DefaultFormatter = require("./_default");
|
||||
var AMDFormatter = require("./amd");
|
||||
var util = require("../../util");
|
||||
var last = require("lodash/array/last");
|
||||
var each = require("lodash/collection/each");
|
||||
var map = require("lodash/collection/map");
|
||||
var t = require("../../types");
|
||||
|
||||
function SystemFormatter(file) {
|
||||
this.exportIdentifier = file.scope.generateUidIdentifier("export");
|
||||
this.noInteropRequireExport = true;
|
||||
this.noInteropRequireImport = true;
|
||||
|
||||
DefaultFormatter.apply(this, arguments);
|
||||
}
|
||||
|
||||
util.inherits(SystemFormatter, AMDFormatter);
|
||||
|
||||
SystemFormatter.prototype.init = function () {};
|
||||
|
||||
SystemFormatter.prototype._addImportSource = function (node, exportNode) {
|
||||
node._importSource = exportNode.source && exportNode.source.value;
|
||||
return node;
|
||||
};
|
||||
|
||||
SystemFormatter.prototype.buildExportsWildcard = function (objectIdentifier, node) {
|
||||
var leftIdentifier = this.scope.generateUidIdentifier("key");
|
||||
var valIdentifier = t.memberExpression(objectIdentifier, leftIdentifier, true);
|
||||
|
||||
var left = t.variableDeclaration("var", [
|
||||
t.variableDeclarator(leftIdentifier)
|
||||
]);
|
||||
|
||||
var right = objectIdentifier;
|
||||
|
||||
var block = t.blockStatement([
|
||||
t.expressionStatement(this.buildExportCall(leftIdentifier, valIdentifier))
|
||||
]);
|
||||
|
||||
return this._addImportSource(t.forInStatement(left, right, block), node);
|
||||
};
|
||||
|
||||
SystemFormatter.prototype.buildExportsAssignment = function (id, init, node) {
|
||||
var call = this.buildExportCall(t.literal(id.name), init, true);
|
||||
return this._addImportSource(call, node);
|
||||
};
|
||||
|
||||
SystemFormatter.prototype.remapExportAssignment = function (node) {
|
||||
return this.buildExportCall(t.literal(node.left.name), node);
|
||||
};
|
||||
|
||||
SystemFormatter.prototype.buildExportCall = function (id, init, isStatement) {
|
||||
var call = t.callExpression(this.exportIdentifier, [id, init]);
|
||||
if (isStatement) {
|
||||
return t.expressionStatement(call);
|
||||
} else {
|
||||
return call;
|
||||
}
|
||||
};
|
||||
|
||||
SystemFormatter.prototype.importSpecifier = function (specifier, node, nodes) {
|
||||
AMDFormatter.prototype.importSpecifier.apply(this, arguments);
|
||||
this._addImportSource(last(nodes), node);
|
||||
};
|
||||
|
||||
var runnerSettersVisitor = {
|
||||
enter: function (node, parent, scope, state) {
|
||||
if (node._importSource === state.source) {
|
||||
if (t.isVariableDeclaration(node)) {
|
||||
each(node.declarations, function (declar) {
|
||||
state.hoistDeclarators.push(t.variableDeclarator(declar.id));
|
||||
state.nodes.push(t.expressionStatement(
|
||||
t.assignmentExpression("=", declar.id, declar.init)
|
||||
));
|
||||
});
|
||||
} else {
|
||||
state.nodes.push(node);
|
||||
}
|
||||
|
||||
this.remove();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
SystemFormatter.prototype.buildRunnerSetters = function (block, hoistDeclarators) {
|
||||
var scope = this.file.scope;
|
||||
|
||||
return t.arrayExpression(map(this.ids, function (uid, source) {
|
||||
var state = {
|
||||
source: source,
|
||||
nodes: [],
|
||||
hoistDeclarators: hoistDeclarators
|
||||
};
|
||||
|
||||
scope.traverse(block, runnerSettersVisitor, state);
|
||||
|
||||
return t.functionExpression(null, [uid], t.blockStatement(state.nodes));
|
||||
}));
|
||||
};
|
||||
|
||||
var hoistVariablesVisitor = {
|
||||
enter: function (node, parent, scope, hoistDeclarators) {
|
||||
if (t.isFunction(node)) {
|
||||
// nothing inside is accessible
|
||||
return this.skip();
|
||||
}
|
||||
|
||||
if (t.isVariableDeclaration(node)) {
|
||||
if (node.kind !== "var" && !t.isProgram(parent)) { // let, const
|
||||
// can't be accessed
|
||||
return;
|
||||
}
|
||||
|
||||
// ignore block hoisted nodes as these can be left in
|
||||
if (node._blockHoist) return;
|
||||
|
||||
var nodes = [];
|
||||
|
||||
for (var i = 0; i < node.declarations.length; i++) {
|
||||
var declar = node.declarations[i];
|
||||
hoistDeclarators.push(t.variableDeclarator(declar.id));
|
||||
if (declar.init) {
|
||||
// no initializer so we can just hoist it as-is
|
||||
var assign = t.expressionStatement(t.assignmentExpression("=", declar.id, declar.init));
|
||||
nodes.push(assign);
|
||||
}
|
||||
}
|
||||
|
||||
// for (var i in test)
|
||||
// for (var i = 0;;)
|
||||
if (t.isFor(parent)) {
|
||||
if (parent.left === node) {
|
||||
return node.declarations[0].id;
|
||||
}
|
||||
|
||||
if (parent.init === node) {
|
||||
return t.toSequenceExpression(nodes, scope);
|
||||
}
|
||||
}
|
||||
|
||||
return nodes;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
var hoistFunctionsVisitor = {
|
||||
enter: function (node, parent, scope, handlerBody) {
|
||||
if (t.isFunction(node)) this.skip();
|
||||
|
||||
if (t.isFunctionDeclaration(node) || node._blockHoist) {
|
||||
handlerBody.push(node);
|
||||
this.remove();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
SystemFormatter.prototype.transform = function (program) {
|
||||
var hoistDeclarators = [];
|
||||
var moduleName = this.getModuleName();
|
||||
var moduleNameLiteral = t.literal(moduleName);
|
||||
|
||||
var block = t.blockStatement(program.body);
|
||||
|
||||
var runner = util.template("system", {
|
||||
MODULE_NAME: moduleNameLiteral,
|
||||
MODULE_DEPENDENCIES: t.arrayExpression(this.buildDependencyLiterals()),
|
||||
EXPORT_IDENTIFIER: this.exportIdentifier,
|
||||
SETTERS: this.buildRunnerSetters(block, hoistDeclarators),
|
||||
EXECUTE: t.functionExpression(null, [], block)
|
||||
}, true);
|
||||
|
||||
var handlerBody = runner.expression.arguments[2].body.body;
|
||||
if (!moduleName) runner.expression.arguments.shift();
|
||||
|
||||
var returnStatement = handlerBody.pop();
|
||||
|
||||
// hoist up all variable declarations
|
||||
this.file.scope.traverse(block, hoistVariablesVisitor, hoistDeclarators);
|
||||
|
||||
if (hoistDeclarators.length) {
|
||||
var hoistDeclar = t.variableDeclaration("var", hoistDeclarators);
|
||||
hoistDeclar._blockHoist = true;
|
||||
handlerBody.unshift(hoistDeclar);
|
||||
}
|
||||
|
||||
// hoist up function declarations for circular references
|
||||
this.file.scope.traverse(block, hoistFunctionsVisitor, handlerBody);
|
||||
|
||||
handlerBody.push(returnStatement);
|
||||
|
||||
program.body = [runner];
|
||||
};
|
||||
@@ -1,73 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
module.exports = UMDFormatter;
|
||||
|
||||
var AMDFormatter = require("./amd");
|
||||
var util = require("../../util");
|
||||
var t = require("../../types");
|
||||
var values = require("lodash/object/values");
|
||||
|
||||
function UMDFormatter() {
|
||||
AMDFormatter.apply(this, arguments);
|
||||
}
|
||||
|
||||
util.inherits(UMDFormatter, AMDFormatter);
|
||||
|
||||
UMDFormatter.prototype.transform = function (program) {
|
||||
var body = program.body;
|
||||
|
||||
// build an array of module names
|
||||
|
||||
var names = [];
|
||||
for (var name in this.ids) {
|
||||
names.push(t.literal(name));
|
||||
}
|
||||
|
||||
// factory
|
||||
|
||||
var ids = values(this.ids);
|
||||
var args = [t.identifier("exports")];
|
||||
if (this.passModuleArg) args.push(t.identifier("module"));
|
||||
args = args.concat(ids);
|
||||
|
||||
var factory = t.functionExpression(null, args, t.blockStatement(body));
|
||||
|
||||
// amd
|
||||
|
||||
var defineArgs = [t.literal("exports")];
|
||||
if (this.passModuleArg) defineArgs.push(t.literal("module"));
|
||||
defineArgs = defineArgs.concat(names);
|
||||
defineArgs = [t.arrayExpression(defineArgs)];
|
||||
|
||||
// common
|
||||
|
||||
var testExports = util.template("test-exports");
|
||||
var testModule = util.template("test-module");
|
||||
var commonTests = this.passModuleArg ? t.logicalExpression("&&", testExports, testModule) : testExports;
|
||||
|
||||
var commonArgs = [t.identifier("exports")];
|
||||
if (this.passModuleArg) commonArgs.push(t.identifier("module"));
|
||||
commonArgs = commonArgs.concat(names.map(function (name) {
|
||||
return t.callExpression(t.identifier("require"), [name]);
|
||||
}));
|
||||
|
||||
// globals
|
||||
|
||||
//var umdArgs = [];
|
||||
|
||||
//
|
||||
|
||||
var moduleName = this.getModuleName();
|
||||
if (moduleName) defineArgs.unshift(t.literal(moduleName));
|
||||
|
||||
var runner = util.template("umd-runner-body", {
|
||||
AMD_ARGUMENTS: defineArgs,
|
||||
COMMON_TEST: commonTests,
|
||||
COMMON_ARGUMENTS: commonArgs
|
||||
});
|
||||
|
||||
//
|
||||
|
||||
var call = t.callExpression(runner, [factory]);
|
||||
program.body = [t.expressionStatement(call)];
|
||||
};
|
||||
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"blacklist": ["useStrict"]
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
for (var ITERATOR_KEY = OBJECT[Symbol.iterator](), STEP_KEY; !(STEP_KEY = ITERATOR_KEY.next()).done; ) {
|
||||
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
(function () {
|
||||
function GET_OUTER_ID() {
|
||||
return ID;
|
||||
}
|
||||
|
||||
return FUNCTION;
|
||||
})()
|
||||
@@ -1,4 +0,0 @@
|
||||
(function (child, staticProps, instanceProps) {
|
||||
if (staticProps) Object.defineProperties(child, staticProps);
|
||||
if (instanceProps) Object.defineProperties(child.prototype, instanceProps);
|
||||
})
|
||||
@@ -1,2 +0,0 @@
|
||||
var helpers = exports.default = {};
|
||||
exports.__esModule = true;
|
||||
@@ -1,63 +0,0 @@
|
||||
module.exports = TransformerPass;
|
||||
|
||||
var includes = require("lodash/collection/includes");
|
||||
|
||||
/**
|
||||
* This class is responsible for traversing over the provided `File`s
|
||||
* AST and running it's parent transformers handlers over it.
|
||||
*/
|
||||
|
||||
function TransformerPass(file, transformer) {
|
||||
this.transformer = transformer;
|
||||
this.shouldRun = !transformer.check;
|
||||
this.handlers = transformer.handlers;
|
||||
this.file = file;
|
||||
}
|
||||
|
||||
TransformerPass.prototype.canRun = function () {
|
||||
var transformer = this.transformer;
|
||||
|
||||
var opts = this.file.opts;
|
||||
var key = transformer.key;
|
||||
|
||||
// internal
|
||||
if (key[0] === "_") return true;
|
||||
|
||||
// blacklist
|
||||
var blacklist = opts.blacklist;
|
||||
if (blacklist.length && includes(blacklist, key)) return false;
|
||||
|
||||
// whitelist
|
||||
var whitelist = opts.whitelist;
|
||||
if (whitelist.length) return includes(whitelist, key);
|
||||
|
||||
// optional
|
||||
if (transformer.optional && !includes(opts.optional, key)) return false;
|
||||
|
||||
// experimental
|
||||
if (transformer.experimental && !opts.experimental) return false;
|
||||
|
||||
// playground
|
||||
if (transformer.playground && !opts.playground) return false;
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
TransformerPass.prototype.checkNode = function (node) {
|
||||
var check = this.transformer.check;
|
||||
if (check) {
|
||||
return this.shouldRun = check(node);
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
TransformerPass.prototype.transform = function () {
|
||||
if (!this.shouldRun) return;
|
||||
|
||||
var file = this.file;
|
||||
|
||||
file.debug("Running transformer " + this.transformer.key);
|
||||
|
||||
file.scope.traverse(file.ast, this.handlers, file);
|
||||
};
|
||||
@@ -1,75 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
module.exports = Transformer;
|
||||
|
||||
var TransformerPass = require("./transformer-pass");
|
||||
var isFunction = require("lodash/lang/isFunction");
|
||||
var traverse = require("../traversal");
|
||||
var isObject = require("lodash/lang/isObject");
|
||||
var assign = require("lodash/object/assign");
|
||||
var each = require("lodash/collection/each");
|
||||
|
||||
/**
|
||||
* This is the class responsible for normalising a transformers handlers
|
||||
* as well as constructing a `TransformerPass` that is repsonsible for
|
||||
* actually running the transformer over the provided `File`.
|
||||
*/
|
||||
|
||||
function Transformer(key, transformer, opts) {
|
||||
transformer = assign({}, transformer);
|
||||
|
||||
var take = function (key) {
|
||||
var val = transformer[key];
|
||||
delete transformer[key];
|
||||
return val;
|
||||
};
|
||||
|
||||
this.manipulateOptions = take("manipulateOptions");
|
||||
this.check = take("check");
|
||||
this.post = take("post");
|
||||
this.pre = take("pre");
|
||||
|
||||
this.experimental = !!take("experimental");
|
||||
this.playground = !!take("playground");
|
||||
this.secondPass = !!take("secondPass");
|
||||
this.optional = !!take("optional");
|
||||
|
||||
this.handlers = this.normalize(transformer);
|
||||
this.opts = opts || {};
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
Transformer.prototype.normalize = function (transformer) {
|
||||
var self = this;
|
||||
|
||||
if (isFunction(transformer)) {
|
||||
transformer = { ast: transformer };
|
||||
}
|
||||
|
||||
traverse.explode(transformer);
|
||||
|
||||
each(transformer, function (fns, type) {
|
||||
// hidden property
|
||||
if (type[0] === "_") {
|
||||
self[type] = fns;
|
||||
return;
|
||||
}
|
||||
|
||||
if (type === "enter" || type === "exit") return;
|
||||
|
||||
if (isFunction(fns)) fns = { enter: fns };
|
||||
|
||||
if (!isObject(fns)) return;
|
||||
|
||||
if (!fns.enter) fns.enter = function () { };
|
||||
if (!fns.exit) fns.exit = function () { };
|
||||
|
||||
transformer[type] = fns;
|
||||
});
|
||||
|
||||
return transformer;
|
||||
};
|
||||
|
||||
Transformer.prototype.buildPass = function (file) {
|
||||
return new TransformerPass(file, this);
|
||||
};
|
||||
@@ -1 +0,0 @@
|
||||
{}
|
||||
@@ -1,15 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
var t = require("../../../types");
|
||||
|
||||
exports.check = t.isArrowFunctionExpression;
|
||||
|
||||
exports.ArrowFunctionExpression = function (node) {
|
||||
t.ensureBlock(node);
|
||||
|
||||
node._aliasFunction = "arrow";
|
||||
node.expression = false;
|
||||
node.type = "FunctionExpression";
|
||||
|
||||
return node;
|
||||
};
|
||||
@@ -1,561 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
var traverse = require("../../../traversal");
|
||||
var object = require("../../../helpers/object");
|
||||
var util = require("../../../util");
|
||||
var t = require("../../../types");
|
||||
var values = require("lodash/object/values");
|
||||
var extend = require("lodash/object/extend");
|
||||
|
||||
exports.check = function (node) {
|
||||
return t.isVariableDeclaration(node) && (node.kind === "let" || node.kind === "const");
|
||||
};
|
||||
|
||||
var isLet = function (node, parent) {
|
||||
if (!t.isVariableDeclaration(node)) return false;
|
||||
if (node._let) return true;
|
||||
if (node.kind !== "let") return false;
|
||||
|
||||
// https://github.com/babel/babel/issues/255
|
||||
if (isLetInitable(node, parent)) {
|
||||
for (var i = 0; i < node.declarations.length; i++) {
|
||||
var declar = node.declarations[i];
|
||||
declar.init = declar.init || t.identifier("undefined");
|
||||
}
|
||||
}
|
||||
|
||||
node._let = true;
|
||||
node.kind = "var";
|
||||
return true;
|
||||
};
|
||||
|
||||
var isLetInitable = function (node, parent) {
|
||||
return !t.isFor(parent) || t.isFor(parent) && parent.left !== node;
|
||||
};
|
||||
|
||||
var isVar = function (node, parent) {
|
||||
return t.isVariableDeclaration(node, { kind: "var" }) && !isLet(node, parent);
|
||||
};
|
||||
|
||||
var standardizeLets = function (declars) {
|
||||
for (var i = 0; i < declars.length; i++) {
|
||||
delete declars[i]._let;
|
||||
}
|
||||
};
|
||||
|
||||
exports.VariableDeclaration = function (node, parent, scope, file) {
|
||||
if (!isLet(node, parent)) return;
|
||||
|
||||
if (isLetInitable(node) && file.transformers["es6.blockScopingTDZ"].canRun()) {
|
||||
var nodes = [node];
|
||||
|
||||
for (var i = 0; i < node.declarations.length; i++) {
|
||||
var decl = node.declarations[i];
|
||||
if (decl.init) {
|
||||
var assign = t.assignmentExpression("=", decl.id, decl.init);
|
||||
assign._ignoreBlockScopingTDZ = true;
|
||||
nodes.push(t.expressionStatement(assign));
|
||||
}
|
||||
decl.init = file.addHelper("temporal-undefined");
|
||||
}
|
||||
|
||||
node._blockHoist = 2;
|
||||
|
||||
return nodes;
|
||||
}
|
||||
};
|
||||
|
||||
exports.Loop = function (node, parent, scope, file) {
|
||||
var init = node.left || node.init;
|
||||
if (isLet(init, node)) {
|
||||
t.ensureBlock(node);
|
||||
node.body._letDeclarators = [init];
|
||||
}
|
||||
var blockScoping = new BlockScoping(node, node.body, parent, scope, file);
|
||||
blockScoping.run();
|
||||
};
|
||||
|
||||
exports.Program =
|
||||
exports.BlockStatement = function (block, parent, scope, file) {
|
||||
if (!t.isLoop(parent)) {
|
||||
var blockScoping = new BlockScoping(false, block, parent, scope, file);
|
||||
blockScoping.run();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {Boolean|Node} loopParent
|
||||
* @param {Node} block
|
||||
* @param {Node} parent
|
||||
* @param {Scope} scope
|
||||
* @param {File} file
|
||||
*/
|
||||
|
||||
function BlockScoping(loopParent, block, parent, scope, file) {
|
||||
this.loopParent = loopParent;
|
||||
this.parent = parent;
|
||||
this.scope = scope;
|
||||
this.block = block;
|
||||
this.file = file;
|
||||
|
||||
this.outsideLetReferences = object();
|
||||
this.hasLetReferences = false;
|
||||
this.letReferences = block._letReferences = object();
|
||||
this.body = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the ball rolling.
|
||||
*/
|
||||
|
||||
BlockScoping.prototype.run = function () {
|
||||
var block = this.block;
|
||||
if (block._letDone) return;
|
||||
block._letDone = true;
|
||||
|
||||
var needsClosure = this.getLetReferences();
|
||||
|
||||
// this is a block within a `Function/Program` so we can safely leave it be
|
||||
if (t.isFunction(this.parent) || t.isProgram(this.block)) return;
|
||||
|
||||
// we can skip everything
|
||||
if (!this.hasLetReferences) return;
|
||||
|
||||
if (needsClosure) {
|
||||
this.wrapClosure();
|
||||
} else {
|
||||
this.remap();
|
||||
}
|
||||
};
|
||||
|
||||
function replace(node, parent, scope, remaps) {
|
||||
if (!t.isReferencedIdentifier(node, parent)) return;
|
||||
|
||||
var remap = remaps[node.name];
|
||||
if (!remap) return;
|
||||
|
||||
var ownBinding = scope.getBindingIdentifier(node.name);
|
||||
if (ownBinding === remap.binding) {
|
||||
node.name = remap.uid;
|
||||
} else {
|
||||
// scope already has it's own binding that doesn't
|
||||
// match the one we have a stored replacement for
|
||||
if (this) this.skip();
|
||||
}
|
||||
}
|
||||
|
||||
var replaceVisitor = {
|
||||
enter: replace
|
||||
};
|
||||
|
||||
function traverseReplace(node, parent, scope, remaps) {
|
||||
replace(node, parent, scope, remaps);
|
||||
scope.traverse(node, replaceVisitor, remaps);
|
||||
}
|
||||
|
||||
/**
|
||||
* Description
|
||||
*/
|
||||
|
||||
BlockScoping.prototype.remap = function () {
|
||||
var hasRemaps = false;
|
||||
var letRefs = this.letReferences;
|
||||
var scope = this.scope;
|
||||
|
||||
// alright, so since we aren't wrapping this block in a closure
|
||||
// we have to check if any of our let variables collide with
|
||||
// those in upper scopes and then if they do, generate a uid
|
||||
// for them and replace all references with it
|
||||
var remaps = object();
|
||||
|
||||
for (var key in letRefs) {
|
||||
// just an Identifier node we collected in `getLetReferences`
|
||||
// this is the defining identifier of a declaration
|
||||
var ref = letRefs[key];
|
||||
|
||||
if (scope.parentHasBinding(key) || scope.hasGlobal(key)) {
|
||||
var uid = scope.generateUidIdentifier(ref.name).name;
|
||||
ref.name = uid;
|
||||
|
||||
hasRemaps = true;
|
||||
remaps[key] = remaps[uid] = {
|
||||
binding: ref,
|
||||
uid: uid
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasRemaps) return;
|
||||
|
||||
//
|
||||
|
||||
var loopParent = this.loopParent;
|
||||
if (loopParent) {
|
||||
traverseReplace(loopParent.right, loopParent, scope, remaps);
|
||||
traverseReplace(loopParent.test, loopParent, scope, remaps);
|
||||
traverseReplace(loopParent.update, loopParent, scope, remaps);
|
||||
}
|
||||
|
||||
scope.traverse(this.block, replaceVisitor, remaps);
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*/
|
||||
|
||||
BlockScoping.prototype.wrapClosure = function () {
|
||||
var block = this.block;
|
||||
|
||||
var outsideRefs = this.outsideLetReferences;
|
||||
|
||||
// remap loop heads with colliding variables
|
||||
if (this.loopParent) {
|
||||
for (var name in outsideRefs) {
|
||||
var id = outsideRefs[name];
|
||||
|
||||
if (this.scope.hasGlobal(id.name)) {
|
||||
delete outsideRefs[id.name];
|
||||
delete this.letReferences[id.name];
|
||||
|
||||
this.scope.rename(id.name);
|
||||
|
||||
this.letReferences[id.name] = id;
|
||||
outsideRefs[id.name] = id;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// if we're inside of a for loop then we search to see if there are any
|
||||
// `break`s, `continue`s, `return`s etc
|
||||
this.has = this.checkLoop();
|
||||
|
||||
// hoist var references to retain scope
|
||||
this.hoistVarDeclarations();
|
||||
|
||||
// turn outsideLetReferences into an array
|
||||
var params = values(outsideRefs);
|
||||
|
||||
// build the closure that we're going to wrap the block with
|
||||
var fn = t.functionExpression(null, params, t.blockStatement(block.body));
|
||||
fn._aliasFunction = true;
|
||||
|
||||
// replace the current block body with the one we're going to build
|
||||
block.body = this.body;
|
||||
|
||||
// build a call and a unique id that we can assign the return value to
|
||||
var call = t.callExpression(fn, params);
|
||||
var ret = this.scope.generateUidIdentifier("ret");
|
||||
|
||||
// handle generators
|
||||
var hasYield = traverse.hasType(fn.body, this.scope, "YieldExpression", t.FUNCTION_TYPES);
|
||||
if (hasYield) {
|
||||
fn.generator = true;
|
||||
call = t.yieldExpression(call, true);
|
||||
}
|
||||
|
||||
// handlers async functions
|
||||
var hasAsync = traverse.hasType(fn.body, this.scope, "AwaitExpression", t.FUNCTION_TYPES);
|
||||
if (hasAsync) {
|
||||
fn.async = true;
|
||||
call = t.awaitExpression(call, true);
|
||||
}
|
||||
|
||||
this.build(ret, call);
|
||||
};
|
||||
|
||||
var letReferenceFunctionVisitor = {
|
||||
enter: function (node, parent, scope, state) {
|
||||
// not a direct reference
|
||||
if (!t.isReferencedIdentifier(node, parent)) return;
|
||||
|
||||
// this scope has a variable with the same name so it couldn't belong
|
||||
// to our let scope
|
||||
if (scope.hasOwnBinding(node.name)) return;
|
||||
|
||||
// not a part of our scope
|
||||
if (!state.letReferences[node.name]) return;
|
||||
|
||||
state.closurify = true;
|
||||
}
|
||||
};
|
||||
|
||||
var letReferenceBlockVisitor = {
|
||||
enter: function (node, parent, scope, state) {
|
||||
if (t.isFunction(node)) {
|
||||
scope.traverse(node, letReferenceFunctionVisitor, state);
|
||||
return this.skip();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*/
|
||||
|
||||
BlockScoping.prototype.getLetReferences = function () {
|
||||
var block = this.block;
|
||||
|
||||
var declarators = block._letDeclarators || [];
|
||||
var declar;
|
||||
|
||||
//
|
||||
for (var i = 0; i < declarators.length; i++) {
|
||||
declar = declarators[i];
|
||||
extend(this.outsideLetReferences, t.getBindingIdentifiers(declar));
|
||||
}
|
||||
|
||||
//
|
||||
if (block.body) {
|
||||
for (i = 0; i < block.body.length; i++) {
|
||||
declar = block.body[i];
|
||||
if (isLet(declar, block)) {
|
||||
declarators = declarators.concat(declar.declarations);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
for (i = 0; i < declarators.length; i++) {
|
||||
declar = declarators[i];
|
||||
var keys = t.getBindingIdentifiers(declar);
|
||||
extend(this.letReferences, keys);
|
||||
this.hasLetReferences = true;
|
||||
}
|
||||
|
||||
// no let references so we can just quit
|
||||
if (!this.hasLetReferences) return;
|
||||
|
||||
// set let references to plain var references
|
||||
standardizeLets(declarators);
|
||||
|
||||
var state = {
|
||||
letReferences: this.letReferences,
|
||||
closurify: false
|
||||
};
|
||||
|
||||
// traverse through this block, stopping on functions and checking if they
|
||||
// contain any local let references
|
||||
this.scope.traverse(this.block, letReferenceBlockVisitor, state);
|
||||
|
||||
return state.closurify;
|
||||
};
|
||||
|
||||
var loopNodeTo = function (node) {
|
||||
if (t.isBreakStatement(node)) {
|
||||
return "break";
|
||||
} else if (t.isContinueStatement(node)) {
|
||||
return "continue";
|
||||
}
|
||||
};
|
||||
|
||||
var loopVisitor = {
|
||||
enter: function (node, parent, scope, state) {
|
||||
var replace;
|
||||
|
||||
if (t.isLoop(node)) {
|
||||
state.ignoreLabeless = true;
|
||||
scope.traverse(node, loopVisitor, state);
|
||||
state.ignoreLabeless = false;
|
||||
}
|
||||
|
||||
if (t.isFunction(node) || t.isLoop(node)) {
|
||||
return this.skip();
|
||||
}
|
||||
|
||||
var loopText = loopNodeTo(node);
|
||||
|
||||
if (loopText) {
|
||||
if (node.label) {
|
||||
// we shouldn't be transforming this because it exists somewhere inside
|
||||
if (state.innerLabels.indexOf(node.label.name) >= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
loopText = loopText + "|" + node.label.name;
|
||||
} else {
|
||||
// we shouldn't be transforming these statements because
|
||||
// they don't refer to the actual loop we're scopifying
|
||||
if (state.ignoreLabeless) return;
|
||||
|
||||
// break statements mean something different in this context
|
||||
if (t.isBreakStatement(node) && t.isSwitchCase(parent)) return;
|
||||
}
|
||||
|
||||
state.hasBreakContinue = true;
|
||||
state.map[loopText] = node;
|
||||
replace = t.literal(loopText);
|
||||
}
|
||||
|
||||
if (t.isReturnStatement(node)) {
|
||||
state.hasReturn = true;
|
||||
replace = t.objectExpression([
|
||||
t.property("init", t.identifier("v"), node.argument || t.identifier("undefined"))
|
||||
]);
|
||||
}
|
||||
|
||||
if (replace) {
|
||||
replace = t.returnStatement(replace);
|
||||
return t.inherits(replace, node);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
var loopLabelVisitor = {
|
||||
enter: function (node, parent, scope, state) {
|
||||
if (t.isLabeledStatement(node)) {
|
||||
state.innerLabels.push(node.label.name);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* If we're inside of a loop then traverse it and check if it has one of
|
||||
* the following node types `ReturnStatement`, `BreakStatement`,
|
||||
* `ContinueStatement` and replace it with a return value that we can track
|
||||
* later on.
|
||||
*
|
||||
* @returns {Object}
|
||||
*/
|
||||
|
||||
BlockScoping.prototype.checkLoop = function () {
|
||||
var state = {
|
||||
hasBreakContinue: false,
|
||||
ignoreLabeless: false,
|
||||
innerLabels: [],
|
||||
hasReturn: false,
|
||||
isLoop: !!this.loopParent,
|
||||
map: {}
|
||||
};
|
||||
|
||||
this.scope.traverse(this.block, loopLabelVisitor, state);
|
||||
this.scope.traverse(this.block, loopVisitor, state);
|
||||
|
||||
return state;
|
||||
};
|
||||
|
||||
var hoistVarDeclarationsVisitor = {
|
||||
enter: function (node, parent, scope, self) {
|
||||
if (t.isForStatement(node)) {
|
||||
if (isVar(node.init, node)) {
|
||||
node.init = t.sequenceExpression(self.pushDeclar(node.init));
|
||||
}
|
||||
} else if (t.isFor(node)) {
|
||||
if (isVar(node.left, node)) {
|
||||
node.left = node.left.declarations[0].id;
|
||||
}
|
||||
} else if (isVar(node, parent)) {
|
||||
return self.pushDeclar(node).map(t.expressionStatement);
|
||||
} else if (t.isFunction(node)) {
|
||||
return this.skip();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Hoist all var declarations in this block to before it so they retain scope
|
||||
* once we wrap everything in a closure.
|
||||
*/
|
||||
|
||||
BlockScoping.prototype.hoistVarDeclarations = function () {
|
||||
traverse(this.block, hoistVarDeclarationsVisitor, this.scope, this);
|
||||
};
|
||||
|
||||
/**
|
||||
* Turn a `VariableDeclaration` into an array of `AssignmentExpressions` with
|
||||
* their declarations hoisted to before the closure wrapper.
|
||||
*
|
||||
* @param {Node} node VariableDeclaration
|
||||
* @returns {Array}
|
||||
*/
|
||||
|
||||
BlockScoping.prototype.pushDeclar = function (node) {
|
||||
this.body.push(t.variableDeclaration(node.kind, node.declarations.map(function (declar) {
|
||||
return t.variableDeclarator(declar.id);
|
||||
})));
|
||||
|
||||
var replace = [];
|
||||
|
||||
for (var i = 0; i < node.declarations.length; i++) {
|
||||
var declar = node.declarations[i];
|
||||
if (!declar.init) continue;
|
||||
|
||||
var expr = t.assignmentExpression("=", declar.id, declar.init);
|
||||
replace.push(t.inherits(expr, declar));
|
||||
}
|
||||
|
||||
return replace;
|
||||
};
|
||||
|
||||
/**
|
||||
* Push the closure to the body.
|
||||
*
|
||||
* @param {Node} ret Identifier
|
||||
* @param {Node} call CallExpression
|
||||
*/
|
||||
|
||||
BlockScoping.prototype.build = function (ret, call) {
|
||||
var has = this.has;
|
||||
if (has.hasReturn || has.hasBreakContinue) {
|
||||
this.buildHas(ret, call);
|
||||
} else {
|
||||
this.body.push(t.expressionStatement(call));
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {Node} ret Identifier
|
||||
* @param {Node} call CallExpression
|
||||
*/
|
||||
|
||||
BlockScoping.prototype.buildHas = function (ret, call) {
|
||||
var body = this.body;
|
||||
|
||||
body.push(t.variableDeclaration("var", [
|
||||
t.variableDeclarator(ret, call)
|
||||
]));
|
||||
|
||||
var loopParent = this.loopParent;
|
||||
var retCheck;
|
||||
var has = this.has;
|
||||
var cases = [];
|
||||
|
||||
if (has.hasReturn) {
|
||||
// typeof ret === "object"
|
||||
retCheck = util.template("let-scoping-return", {
|
||||
RETURN: ret
|
||||
});
|
||||
}
|
||||
|
||||
if (has.hasBreakContinue) {
|
||||
if (!loopParent) {
|
||||
throw new Error("Has no loop parent but we're trying to reassign breaks " +
|
||||
"and continues, something is going wrong here.");
|
||||
}
|
||||
|
||||
for (var key in has.map) {
|
||||
cases.push(t.switchCase(t.literal(key), [has.map[key]]));
|
||||
}
|
||||
|
||||
if (has.hasReturn) {
|
||||
cases.push(t.switchCase(null, [retCheck]));
|
||||
}
|
||||
|
||||
if (cases.length === 1) {
|
||||
var single = cases[0];
|
||||
body.push(this.file.attachAuxiliaryComment(t.ifStatement(
|
||||
t.binaryExpression("===", ret, single.test),
|
||||
single.consequent[0]
|
||||
)));
|
||||
} else {
|
||||
body.push(this.file.attachAuxiliaryComment(t.switchStatement(ret, cases)));
|
||||
}
|
||||
} else {
|
||||
if (has.hasReturn) {
|
||||
body.push(this.file.attachAuxiliaryComment(retCheck));
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -1,296 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
var ReplaceSupers = require("../../helpers/replace-supers");
|
||||
var nameMethod = require("../../helpers/name-method");
|
||||
var defineMap = require("../../helpers/define-map");
|
||||
var messages = require("../../../messages");
|
||||
var util = require("../../../util");
|
||||
var t = require("../../../types");
|
||||
|
||||
exports.check = t.isClass;
|
||||
|
||||
exports.ClassDeclaration = function (node, parent, scope, file) {
|
||||
return new ClassTransformer(node, file, scope, true).run();
|
||||
};
|
||||
|
||||
exports.ClassExpression = function (node, parent, scope, file) {
|
||||
if (!node.id) {
|
||||
if (t.isProperty(parent) && parent.value === node && !parent.computed && t.isIdentifier(parent.key)) {
|
||||
// var o = { foo: class {} };
|
||||
node.id = parent.key;
|
||||
}
|
||||
|
||||
if (t.isVariableDeclarator(parent) && t.isIdentifier(parent.id)) {
|
||||
// var foo = class {};
|
||||
node.id = parent.id;
|
||||
}
|
||||
}
|
||||
|
||||
return new ClassTransformer(node, file, scope, false).run();
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {Node} node
|
||||
* @param {File} file
|
||||
* @param {Scope} scope
|
||||
* @param {Boolean} isStatement
|
||||
*/
|
||||
|
||||
function ClassTransformer(node, file, scope, isStatement) {
|
||||
this.isStatement = isStatement;
|
||||
this.scope = scope;
|
||||
this.node = node;
|
||||
this.file = file;
|
||||
|
||||
this.hasInstanceMutators = false;
|
||||
this.hasStaticMutators = false;
|
||||
|
||||
this.instanceMutatorMap = {};
|
||||
this.staticMutatorMap = {};
|
||||
this.hasConstructor = false;
|
||||
this.className = node.id || scope.generateUidIdentifier("class");
|
||||
this.superName = node.superClass || t.identifier("Function");
|
||||
this.hasSuper = !!node.superClass;
|
||||
this.isLoose = file.isLoose("es6.classes");
|
||||
}
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @returns {Array}
|
||||
*/
|
||||
|
||||
ClassTransformer.prototype.run = function () {
|
||||
var superName = this.superName;
|
||||
var className = this.className;
|
||||
var file = this.file;
|
||||
|
||||
//
|
||||
|
||||
var body = this.body = [];
|
||||
|
||||
var constructorBody = t.blockStatement([
|
||||
t.expressionStatement(t.callExpression(file.addHelper("class-call-check"), [
|
||||
t.thisExpression(),
|
||||
className
|
||||
]))
|
||||
]);
|
||||
var constructor;
|
||||
|
||||
if (this.node.id) {
|
||||
constructor = t.functionDeclaration(className, [], constructorBody);
|
||||
body.push(constructor);
|
||||
} else {
|
||||
constructor = t.functionExpression(null, [], constructorBody);
|
||||
body.push(t.variableDeclaration("var", [
|
||||
t.variableDeclarator(className, constructor)
|
||||
]));
|
||||
}
|
||||
this.constructor = constructor;
|
||||
|
||||
var closureParams = [];
|
||||
var closureArgs = [];
|
||||
|
||||
//
|
||||
|
||||
if (this.hasSuper) {
|
||||
closureArgs.push(superName);
|
||||
|
||||
if (!t.isIdentifier(superName)) {
|
||||
superName = this.scope.generateUidBasedOnNode(superName, this.file);
|
||||
}
|
||||
|
||||
closureParams.push(superName);
|
||||
|
||||
this.superName = superName;
|
||||
body.push(t.expressionStatement(t.callExpression(file.addHelper("inherits"), [className, superName])));
|
||||
}
|
||||
|
||||
this.buildBody();
|
||||
|
||||
t.inheritsComments(body[0], this.node);
|
||||
|
||||
var init;
|
||||
|
||||
if (body.length === 1) {
|
||||
// only a constructor so no need for a closure container
|
||||
init = t.toExpression(constructor);
|
||||
} else {
|
||||
body.push(t.returnStatement(className));
|
||||
init = t.callExpression(
|
||||
t.functionExpression(null, closureParams, t.blockStatement(body)),
|
||||
closureArgs
|
||||
);
|
||||
}
|
||||
|
||||
if (this.isStatement) {
|
||||
return t.variableDeclaration("let", [
|
||||
t.variableDeclarator(className, init)
|
||||
]);
|
||||
} else {
|
||||
return init;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*/
|
||||
|
||||
ClassTransformer.prototype.buildBody = function () {
|
||||
var constructor = this.constructor;
|
||||
var className = this.className;
|
||||
var superName = this.superName;
|
||||
var classBody = this.node.body.body;
|
||||
var body = this.body;
|
||||
|
||||
for (var i = 0; i < classBody.length; i++) {
|
||||
var node = classBody[i];
|
||||
if (t.isMethodDefinition(node)) {
|
||||
var replaceSupers = new ReplaceSupers({
|
||||
methodNode: node,
|
||||
className: this.className,
|
||||
superName: this.superName,
|
||||
isStatic: node.static,
|
||||
isLoose: this.isLoose,
|
||||
scope: this.scope,
|
||||
file: this.file
|
||||
}, true);
|
||||
replaceSupers.replace();
|
||||
|
||||
if ((!node.computed && t.isIdentifier(node.key, { name: "constructor" })) || t.isLiteral(node.key, { value: "constructor" })) {
|
||||
this.pushConstructor(node);
|
||||
} else {
|
||||
this.pushMethod(node);
|
||||
}
|
||||
} else if (t.isPrivateDeclaration(node)) {
|
||||
this.closure = true;
|
||||
body.unshift(node);
|
||||
} else if (t.isClassProperty(node)) {
|
||||
this.pushProperty(node);
|
||||
}
|
||||
}
|
||||
|
||||
// we have no constructor, we have a super, and the super doesn't appear to be falsy
|
||||
if (!this.hasConstructor && this.hasSuper && !t.isFalsyExpression(superName)) {
|
||||
var helperName = "class-super-constructor-call";
|
||||
if (this.isLoose) helperName += "-loose";
|
||||
constructor.body.body.push(util.template(helperName, {
|
||||
CLASS_NAME: className,
|
||||
SUPER_NAME: this.superName
|
||||
}, true));
|
||||
}
|
||||
|
||||
var instanceProps;
|
||||
var staticProps;
|
||||
|
||||
if (this.hasInstanceMutators) {
|
||||
instanceProps = defineMap.build(this.instanceMutatorMap);
|
||||
}
|
||||
|
||||
if (this.hasStaticMutators) {
|
||||
staticProps = defineMap.build(this.staticMutatorMap);
|
||||
}
|
||||
|
||||
if (instanceProps || staticProps) {
|
||||
staticProps = staticProps || t.literal(null);
|
||||
|
||||
var args = [className, staticProps];
|
||||
if (instanceProps) args.push(instanceProps);
|
||||
|
||||
body.push(t.expressionStatement(
|
||||
t.callExpression(this.file.addHelper("prototype-properties"), args)
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Push a method to its respective mutatorMap.
|
||||
*
|
||||
* @param {Node} node MethodDefinition
|
||||
*/
|
||||
|
||||
ClassTransformer.prototype.pushMethod = function (node) {
|
||||
var methodName = node.key;
|
||||
|
||||
var kind = node.kind;
|
||||
|
||||
if (kind === "") {
|
||||
nameMethod.property(node, this.file, this.scope);
|
||||
|
||||
if (this.isLoose) {
|
||||
// use assignments instead of define properties for loose classes
|
||||
|
||||
var className = this.className;
|
||||
if (!node.static) className = t.memberExpression(className, t.identifier("prototype"));
|
||||
methodName = t.memberExpression(className, methodName, node.computed);
|
||||
|
||||
var expr = t.expressionStatement(t.assignmentExpression("=", methodName, node.value));
|
||||
t.inheritsComments(expr, node);
|
||||
this.body.push(expr);
|
||||
return;
|
||||
}
|
||||
|
||||
kind = "value";
|
||||
}
|
||||
|
||||
var mutatorMap = this.instanceMutatorMap;
|
||||
if (node.static) {
|
||||
this.hasStaticMutators = true;
|
||||
mutatorMap = this.staticMutatorMap;
|
||||
} else {
|
||||
this.hasInstanceMutators = true;
|
||||
}
|
||||
|
||||
defineMap.push(mutatorMap, methodName, kind, node.computed, node);
|
||||
defineMap.push(mutatorMap, methodName, "enumerable", node.computed, false);
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {Node} node
|
||||
*/
|
||||
|
||||
ClassTransformer.prototype.pushProperty = function (node) {
|
||||
if (!node.value) return;
|
||||
|
||||
var key;
|
||||
|
||||
if (node.static) {
|
||||
key = t.memberExpression(this.className, node.key);
|
||||
this.body.push(
|
||||
t.expressionStatement(t.assignmentExpression("=", key, node.value))
|
||||
);
|
||||
} else {
|
||||
key = t.memberExpression(t.thisExpression(), node.key);
|
||||
this.constructor.body.body.unshift(
|
||||
t.expressionStatement(t.assignmentExpression("=", key, node.value))
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Replace the constructor body of our class.
|
||||
*
|
||||
* @param {Node} method MethodDefinition
|
||||
*/
|
||||
|
||||
ClassTransformer.prototype.pushConstructor = function (method) {
|
||||
if (method.kind) {
|
||||
throw this.file.errorWithNode(method, messages.get("classesIllegalConstructorKind"));
|
||||
}
|
||||
|
||||
var construct = this.constructor;
|
||||
var fn = method.value;
|
||||
|
||||
this.hasConstructor = true;
|
||||
|
||||
t.inherits(construct, fn);
|
||||
t.inheritsComments(construct, method);
|
||||
|
||||
construct._ignoreUserWhitespace = true;
|
||||
construct.params = fn.params;
|
||||
construct.body.body = construct.body.body.concat(fn.body.body);
|
||||
};
|
||||
@@ -1,484 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
var messages = require("../../../messages");
|
||||
var t = require("../../../types");
|
||||
|
||||
exports.check = t.isPattern;
|
||||
|
||||
function DestructuringTransformer(opts) {
|
||||
this.blockHoist = opts.blockHoist;
|
||||
this.operator = opts.operator;
|
||||
this.nodes = opts.nodes;
|
||||
this.scope = opts.scope;
|
||||
this.file = opts.file;
|
||||
this.kind = opts.kind;
|
||||
}
|
||||
|
||||
DestructuringTransformer.prototype.buildVariableAssignment = function (id, init) {
|
||||
var op = this.operator;
|
||||
if (t.isMemberExpression(id)) op = "=";
|
||||
|
||||
var node;
|
||||
|
||||
if (op) {
|
||||
node = t.expressionStatement(t.assignmentExpression(op, id, init));
|
||||
} else {
|
||||
node = t.variableDeclaration(this.kind, [
|
||||
t.variableDeclarator(id, init)
|
||||
]);
|
||||
}
|
||||
|
||||
node._blockHoist = this.blockHoist;
|
||||
|
||||
return node;
|
||||
};
|
||||
|
||||
DestructuringTransformer.prototype.buildVariableDeclaration = function (id, init) {
|
||||
var declar = t.variableDeclaration("var", [
|
||||
t.variableDeclarator(id, init)
|
||||
]);
|
||||
declar._blockHoist = this.blockHoist;
|
||||
return declar;
|
||||
};
|
||||
|
||||
DestructuringTransformer.prototype.push = function (id, init) {
|
||||
if (t.isObjectPattern(id)) {
|
||||
this.pushObjectPattern(id, init);
|
||||
} else if (t.isArrayPattern(id)) {
|
||||
this.pushArrayPattern(id, init);
|
||||
} else if (t.isAssignmentPattern(id)) {
|
||||
this.pushAssignmentPattern(id, init);
|
||||
} else {
|
||||
this.nodes.push(this.buildVariableAssignment(id, init));
|
||||
}
|
||||
};
|
||||
|
||||
DestructuringTransformer.prototype.get = function () {
|
||||
|
||||
};
|
||||
|
||||
DestructuringTransformer.prototype.pushAssignmentPattern = function (pattern, valueRef) {
|
||||
// we need to assign the current value of the assignment to avoid evaluating
|
||||
// it more than once
|
||||
|
||||
var tempValueRef = this.scope.generateUidBasedOnNode(valueRef);
|
||||
|
||||
var declar = t.variableDeclaration("var", [
|
||||
t.variableDeclarator(tempValueRef, valueRef)
|
||||
]);
|
||||
declar._blockHoist = this.blockHoist;
|
||||
this.nodes.push(declar);
|
||||
|
||||
//
|
||||
|
||||
this.nodes.push(this.buildVariableAssignment(
|
||||
pattern.left,
|
||||
t.conditionalExpression(
|
||||
t.binaryExpression("===", tempValueRef, t.identifier("undefined")),
|
||||
pattern.right,
|
||||
tempValueRef
|
||||
)
|
||||
));
|
||||
};
|
||||
|
||||
DestructuringTransformer.prototype.pushObjectSpread = function (pattern, objRef, spreadProp, spreadPropIndex) {
|
||||
// get all the keys that appear in this object before the current spread
|
||||
|
||||
var keys = [];
|
||||
|
||||
for (var i = 0; i < pattern.properties.length; i++) {
|
||||
var prop = pattern.properties[i];
|
||||
|
||||
// we've exceeded the index of the spread property to all properties to the
|
||||
// right need to be ignored
|
||||
if (i >= spreadPropIndex) break;
|
||||
|
||||
// ignore other spread properties
|
||||
if (t.isSpreadProperty(prop)) continue;
|
||||
|
||||
var key = prop.key;
|
||||
if (t.isIdentifier(key)) key = t.literal(prop.key.name);
|
||||
keys.push(key);
|
||||
}
|
||||
|
||||
keys = t.arrayExpression(keys);
|
||||
|
||||
//
|
||||
|
||||
var value = t.callExpression(this.file.addHelper("object-without-properties"), [objRef, keys]);
|
||||
this.nodes.push(this.buildVariableAssignment(spreadProp.argument, value));
|
||||
};
|
||||
|
||||
DestructuringTransformer.prototype.pushObjectProperty = function (prop, propRef) {
|
||||
if (t.isLiteral(prop.key)) prop.computed = true;
|
||||
|
||||
var pattern = prop.value;
|
||||
var objRef = t.memberExpression(propRef, prop.key, prop.computed);
|
||||
|
||||
if (t.isPattern(pattern)) {
|
||||
this.push(pattern, objRef);
|
||||
} else {
|
||||
this.nodes.push(this.buildVariableAssignment(pattern, objRef));
|
||||
}
|
||||
};
|
||||
|
||||
DestructuringTransformer.prototype.pushObjectPattern = function (pattern, objRef) {
|
||||
// https://github.com/babel/babel/issues/681
|
||||
|
||||
if (!pattern.properties.length) {
|
||||
this.nodes.push(t.expressionStatement(
|
||||
t.callExpression(this.file.addHelper("object-destructuring-empty"), [objRef])
|
||||
));
|
||||
}
|
||||
|
||||
// if we have more than one properties in this pattern and the objectRef is a
|
||||
// member expression then we need to assign it to a temporary variable so it's
|
||||
// only evaluated once
|
||||
|
||||
if (pattern.properties.length > 1 && t.isMemberExpression(objRef)) {
|
||||
var temp = this.scope.generateUidBasedOnNode(objRef, this.file);
|
||||
this.nodes.push(this.buildVariableDeclaration(temp, objRef));
|
||||
objRef = temp;
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
for (var i = 0; i < pattern.properties.length; i++) {
|
||||
var prop = pattern.properties[i];
|
||||
if (t.isSpreadProperty(prop)) {
|
||||
this.pushObjectSpread(pattern, objRef, prop, i);
|
||||
} else {
|
||||
this.pushObjectProperty(prop, objRef);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
var hasRest = function (pattern) {
|
||||
for (var i = 0; i < pattern.elements.length; i++) {
|
||||
if (t.isRestElement(pattern.elements[i])) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
DestructuringTransformer.prototype.canUnpackArrayPattern = function (pattern, arr) {
|
||||
// not an array so there's no way we can deal with this
|
||||
if (!t.isArrayExpression(arr)) return false;
|
||||
|
||||
// pattern has less elements than the array and doesn't have a rest so some
|
||||
// elements wont be evaluated
|
||||
if (pattern.elements.length < arr.elements.length && !hasRest(pattern)) return false;
|
||||
|
||||
// deopt on holes
|
||||
for (var i = 0; i < pattern.elements.length; i++) {
|
||||
if (!pattern.elements[i]) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
DestructuringTransformer.prototype.pushUnpackedArrayPattern = function (pattern, arr) {
|
||||
for (var i = 0; i < pattern.elements.length; i++) {
|
||||
var elem = pattern.elements[i];
|
||||
if (t.isRestElement(elem)) {
|
||||
this.push(elem.argument, t.arrayExpression(arr.elements.slice(i)));
|
||||
} else {
|
||||
this.push(elem, arr.elements[i]);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
DestructuringTransformer.prototype.pushArrayPattern = function (pattern, arrayRef) {
|
||||
if (!pattern.elements) return;
|
||||
|
||||
// optimise basic array destructuring of an array expression
|
||||
//
|
||||
// we can't do this to a pattern of unequal size to it's right hand
|
||||
// array expression as then there will be values that wont be evaluated
|
||||
//
|
||||
// eg: var [a, b] = [1, 2];
|
||||
|
||||
if (this.canUnpackArrayPattern(pattern, arrayRef)) {
|
||||
return this.pushUnpackedArrayPattern(pattern, arrayRef);
|
||||
}
|
||||
|
||||
// if we have a rest then we need all the elements so don't tell
|
||||
// `scope.toArray` to only get a certain amount
|
||||
|
||||
var count = !hasRest(pattern) && pattern.elements.length;
|
||||
|
||||
// so we need to ensure that the `arrayRef` is an array, `scope.toArray` will
|
||||
// return a locally bound identifier if it's been inferred to be an array,
|
||||
// otherwise it'll be a call to a helper that will ensure it's one
|
||||
|
||||
var toArray = this.scope.toArray(arrayRef, count);
|
||||
|
||||
if (t.isIdentifier(toArray)) {
|
||||
// we've been given an identifier so it must have been inferred to be an
|
||||
// array
|
||||
arrayRef = toArray;
|
||||
} else {
|
||||
arrayRef = this.scope.generateUidBasedOnNode(arrayRef);
|
||||
this.nodes.push(this.buildVariableDeclaration(arrayRef, toArray));
|
||||
this.scope.assignTypeGeneric(arrayRef.name, "Array");
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
for (var i = 0; i < pattern.elements.length; i++) {
|
||||
var elem = pattern.elements[i];
|
||||
|
||||
// hole
|
||||
if (!elem) continue;
|
||||
|
||||
var elemRef;
|
||||
|
||||
if (t.isRestElement(elem)) {
|
||||
elemRef = this.scope.toArray(arrayRef);
|
||||
|
||||
if (i > 0) {
|
||||
elemRef = t.callExpression(t.memberExpression(elemRef, t.identifier("slice")), [t.literal(i)]);
|
||||
}
|
||||
|
||||
// set the element to the rest element argument since we've dealt with it
|
||||
// being a rest already
|
||||
elem = elem.argument;
|
||||
} else {
|
||||
elemRef = t.memberExpression(arrayRef, t.literal(i), true);
|
||||
}
|
||||
|
||||
this.push(elem, elemRef);
|
||||
}
|
||||
};
|
||||
|
||||
DestructuringTransformer.prototype.init = function (pattern, ref) {
|
||||
// trying to destructure a value that we can't evaluate more than once so we
|
||||
// need to save it to a variable
|
||||
|
||||
if (!t.isArrayExpression(ref) && !t.isMemberExpression(ref) && !t.isIdentifier(ref)) {
|
||||
var key = this.scope.generateUidBasedOnNode(ref);
|
||||
this.nodes.push(this.buildVariableDeclaration(key, ref));
|
||||
ref = key;
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
this.push(pattern, ref);
|
||||
};
|
||||
|
||||
exports.ForInStatement =
|
||||
exports.ForOfStatement = function (node, parent, scope, file) {
|
||||
var left = node.left;
|
||||
|
||||
if (t.isPattern(left)) {
|
||||
// for ({ length: k } in { abc: 3 });
|
||||
|
||||
var temp = scope.generateUidIdentifier("ref");
|
||||
|
||||
node.left = t.variableDeclaration("var", [
|
||||
t.variableDeclarator(temp)
|
||||
]);
|
||||
|
||||
t.ensureBlock(node);
|
||||
|
||||
node.body.body.unshift(t.variableDeclaration("var", [
|
||||
t.variableDeclarator(left, temp)
|
||||
]));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (!t.isVariableDeclaration(left)) return;
|
||||
|
||||
var pattern = left.declarations[0].id;
|
||||
if (!t.isPattern(pattern)) return;
|
||||
|
||||
var key = scope.generateUidIdentifier("ref");
|
||||
node.left = t.variableDeclaration(left.kind, [
|
||||
t.variableDeclarator(key, null)
|
||||
]);
|
||||
|
||||
var nodes = [];
|
||||
|
||||
var destructuring = new DestructuringTransformer({
|
||||
kind: left.kind,
|
||||
file: file,
|
||||
scope: scope,
|
||||
nodes: nodes
|
||||
});
|
||||
|
||||
destructuring.init(pattern, key);
|
||||
|
||||
t.ensureBlock(node);
|
||||
|
||||
var block = node.body;
|
||||
block.body = nodes.concat(block.body);
|
||||
};
|
||||
|
||||
exports.Function = function (node, parent, scope, file) {
|
||||
var nodes = [];
|
||||
|
||||
var hasDestructuringTransformer = false;
|
||||
|
||||
node.params = node.params.map(function (pattern, i) {
|
||||
if (!t.isPattern(pattern)) return pattern;
|
||||
|
||||
hasDestructuringTransformer = true;
|
||||
var ref = scope.generateUidIdentifier("ref");
|
||||
|
||||
var destructuring = new DestructuringTransformer({
|
||||
blockHoist: node.params.length - i,
|
||||
nodes: nodes,
|
||||
scope: scope,
|
||||
file: file,
|
||||
kind: "var",
|
||||
});
|
||||
destructuring.init(pattern, ref);
|
||||
|
||||
return ref;
|
||||
});
|
||||
|
||||
if (!hasDestructuringTransformer) return;
|
||||
|
||||
t.ensureBlock(node);
|
||||
|
||||
var block = node.body;
|
||||
block.body = nodes.concat(block.body);
|
||||
};
|
||||
|
||||
exports.CatchClause = function (node, parent, scope, file) {
|
||||
var pattern = node.param;
|
||||
if (!t.isPattern(pattern)) return;
|
||||
|
||||
var ref = scope.generateUidIdentifier("ref");
|
||||
node.param = ref;
|
||||
|
||||
var nodes = [];
|
||||
|
||||
var destructuring = new DestructuringTransformer({
|
||||
kind: "let",
|
||||
file: file,
|
||||
scope: scope,
|
||||
nodes: nodes
|
||||
});
|
||||
destructuring.init(pattern, ref);
|
||||
|
||||
node.body.body = nodes.concat(node.body.body);
|
||||
|
||||
return node;
|
||||
};
|
||||
|
||||
exports.ExpressionStatement = function (node, parent, scope, file) {
|
||||
var expr = node.expression;
|
||||
if (expr.type !== "AssignmentExpression") return;
|
||||
if (!t.isPattern(expr.left)) return;
|
||||
if (file.isConsequenceExpressionStatement(node)) return;
|
||||
|
||||
var nodes = [];
|
||||
|
||||
var ref = scope.generateUidIdentifier("ref");
|
||||
nodes.push(t.variableDeclaration("var", [
|
||||
t.variableDeclarator(ref, expr.right)
|
||||
]));
|
||||
|
||||
var destructuring = new DestructuringTransformer({
|
||||
operator: expr.operator,
|
||||
file: file,
|
||||
scope: scope,
|
||||
nodes: nodes
|
||||
});
|
||||
destructuring.init(expr.left, ref);
|
||||
|
||||
return nodes;
|
||||
};
|
||||
|
||||
exports.AssignmentExpression = function (node, parent, scope, file) {
|
||||
if (!t.isPattern(node.left)) return;
|
||||
|
||||
var ref = scope.generateUidIdentifier("temp");
|
||||
scope.push({
|
||||
key: ref.name,
|
||||
id: ref
|
||||
});
|
||||
|
||||
var nodes = [];
|
||||
nodes.push(t.assignmentExpression("=", ref, node.right));
|
||||
|
||||
var destructuring = new DestructuringTransformer({
|
||||
operator: node.operator,
|
||||
file: file,
|
||||
scope: scope,
|
||||
nodes: nodes
|
||||
});
|
||||
destructuring.init(node.left, ref);
|
||||
|
||||
nodes.push(ref);
|
||||
|
||||
return t.toSequenceExpression(nodes, scope);
|
||||
};
|
||||
|
||||
var variableDeclarationhasPattern = function (node) {
|
||||
for (var i = 0; i < node.declarations.length; i++) {
|
||||
if (t.isPattern(node.declarations[i].id)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
exports.VariableDeclaration = function (node, parent, scope, file) {
|
||||
if (t.isForInStatement(parent) || t.isForOfStatement(parent)) return;
|
||||
if (!variableDeclarationhasPattern(node)) return;
|
||||
|
||||
var nodes = [];
|
||||
var declar;
|
||||
|
||||
for (var i = 0; i < node.declarations.length; i++) {
|
||||
declar = node.declarations[i];
|
||||
|
||||
var patternId = declar.init;
|
||||
var pattern = declar.id;
|
||||
|
||||
var destructuring = new DestructuringTransformer({
|
||||
nodes: nodes,
|
||||
scope: scope,
|
||||
kind: node.kind,
|
||||
file: file
|
||||
});
|
||||
|
||||
if (t.isPattern(pattern) && patternId) {
|
||||
destructuring.init(pattern, patternId);
|
||||
|
||||
if (+i !== node.declarations.length - 1) {
|
||||
// we aren't the last declarator so let's just make the
|
||||
// last transformed node inherit from us
|
||||
t.inherits(nodes[nodes.length - 1], declar);
|
||||
}
|
||||
} else {
|
||||
nodes.push(t.inherits(destructuring.buildVariableAssignment(declar.id, declar.init), declar));
|
||||
}
|
||||
}
|
||||
|
||||
if (!t.isProgram(parent) && !t.isBlockStatement(parent)) {
|
||||
// https://github.com/babel/babel/issues/113
|
||||
// for (let [x] = [0]; false;) {}
|
||||
|
||||
declar = null;
|
||||
|
||||
for (i = 0; i < nodes.length; i++) {
|
||||
node = nodes[i];
|
||||
declar = declar || t.variableDeclaration(node.kind, []);
|
||||
|
||||
if (!t.isVariableDeclaration(node) && declar.kind !== node.kind) {
|
||||
throw file.errorWithNode(node, messages.get("invalidParentForThisNode"));
|
||||
}
|
||||
|
||||
declar.declarations = declar.declarations.concat(node.declarations);
|
||||
}
|
||||
|
||||
return declar;
|
||||
}
|
||||
|
||||
return nodes;
|
||||
};
|
||||
@@ -1,34 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
var ReplaceSupers = require("../../helpers/replace-supers");
|
||||
var t = require("../../../types");
|
||||
|
||||
exports.check = function (node) {
|
||||
return t.isIdentifier(node, { name: "super" });
|
||||
};
|
||||
|
||||
exports.Property = function (node, parent, scope, file) {
|
||||
if (!node.method) return;
|
||||
|
||||
var value = node.value;
|
||||
var thisExpr = scope.generateUidIdentifier("this");
|
||||
|
||||
var replaceSupers = new ReplaceSupers({
|
||||
topLevelThisReference: thisExpr,
|
||||
methodNode: node,
|
||||
className: thisExpr,
|
||||
isStatic: true,
|
||||
scope: scope,
|
||||
file: file
|
||||
});
|
||||
|
||||
replaceSupers.replace();
|
||||
|
||||
if (replaceSupers.hasSuper) {
|
||||
value.body.body.unshift(
|
||||
t.variableDeclaration("var", [
|
||||
t.variableDeclarator(thisExpr, t.thisExpression())
|
||||
])
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -1,76 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
var util = require("../../../util");
|
||||
var t = require("../../../types");
|
||||
|
||||
exports.check = t.isRestElement;
|
||||
|
||||
var hasRest = function (node) {
|
||||
return t.isRestElement(node.params[node.params.length - 1]);
|
||||
};
|
||||
|
||||
exports.Function = function (node, parent, scope) {
|
||||
if (!hasRest(node)) return;
|
||||
|
||||
var rest = node.params.pop().argument;
|
||||
|
||||
var argsId = t.identifier("arguments");
|
||||
|
||||
// otherwise `arguments` will be remapped in arrow functions
|
||||
argsId._ignoreAliasFunctions = true;
|
||||
|
||||
var start = t.literal(node.params.length);
|
||||
var key = scope.generateUidIdentifier("key");
|
||||
var len = scope.generateUidIdentifier("len");
|
||||
|
||||
var arrKey = key;
|
||||
var arrLen = len;
|
||||
if (node.params.length) {
|
||||
// this method has additional params, so we need to subtract
|
||||
// the index of the current argument position from the
|
||||
// position in the array that we want to populate
|
||||
arrKey = t.binaryExpression("-", key, start);
|
||||
|
||||
// we need to work out the size of the array that we're
|
||||
// going to store all the rest parameters
|
||||
//
|
||||
// we need to add a check to avoid constructing the array
|
||||
// with <0 if there are less arguments than params as it'll
|
||||
// cause an error
|
||||
arrLen = t.conditionalExpression(
|
||||
t.binaryExpression(">", len, start),
|
||||
t.binaryExpression("-", len, start),
|
||||
t.literal(0)
|
||||
);
|
||||
}
|
||||
|
||||
// support patterns
|
||||
if (t.isPattern(rest)) {
|
||||
var pattern = rest;
|
||||
rest = scope.generateUidIdentifier("ref");
|
||||
|
||||
// let the destructuring transformer handle this
|
||||
var restDeclar = t.variableDeclaration("var", [
|
||||
t.variableDeclarator(pattern, rest)
|
||||
]);
|
||||
|
||||
// retain evaluation position
|
||||
restDeclar._blockHoist = node.params.length + 1;
|
||||
|
||||
node.body.body.unshift(restDeclar);
|
||||
}
|
||||
|
||||
scope.assignTypeGeneric(rest.name, "Array");
|
||||
|
||||
var loop = util.template("rest", {
|
||||
ARGUMENTS: argsId,
|
||||
ARRAY_KEY: arrKey,
|
||||
ARRAY_LEN: arrLen,
|
||||
START: start,
|
||||
ARRAY: rest,
|
||||
KEY: key,
|
||||
LEN: len,
|
||||
});
|
||||
loop._blockHoist = node.params.length + 1;
|
||||
node.body.body.unshift(loop);
|
||||
};
|
||||
@@ -1,19 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
var clone = require("lodash/lang/clone");
|
||||
var t = require("../../../types");
|
||||
|
||||
exports.check = function (node) {
|
||||
return t.isProperty(node) && (node.method || node.shorthand);
|
||||
};
|
||||
|
||||
exports.Property = function (node) {
|
||||
if (node.method) {
|
||||
node.method = false;
|
||||
}
|
||||
|
||||
if (node.shorthand) {
|
||||
node.shorthand = false;
|
||||
node.key = t.removeComments(clone(node.key));
|
||||
}
|
||||
};
|
||||
@@ -1,379 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
var reduceRight = require("lodash/collection/reduceRight");
|
||||
var messages = require("../../../messages");
|
||||
var flatten = require("lodash/array/flatten");
|
||||
var util = require("../../../util");
|
||||
var map = require("lodash/collection/map");
|
||||
var t = require("../../../types");
|
||||
|
||||
function returnBlock(expr) {
|
||||
return t.blockStatement([t.returnStatement(expr)]);
|
||||
}
|
||||
|
||||
function TailCallTransformer(node, scope, file) {
|
||||
this.hasTailRecursion = false;
|
||||
this.needsArguments = false;
|
||||
this.setsArguments = false;
|
||||
this.needsThis = false;
|
||||
this.ownerId = node.id;
|
||||
this.vars = [];
|
||||
|
||||
this.scope = scope;
|
||||
this.file = file;
|
||||
this.node = node;
|
||||
}
|
||||
|
||||
TailCallTransformer.prototype.getArgumentsId = function () {
|
||||
return this.argumentsId = this.argumentsId || this.scope.generateUidIdentifier("arguments");
|
||||
};
|
||||
|
||||
TailCallTransformer.prototype.getThisId = function () {
|
||||
return this.thisId = this.thisId || this.scope.generateUidIdentifier("this");
|
||||
};
|
||||
|
||||
TailCallTransformer.prototype.getLeftId = function () {
|
||||
return this.leftId = this.leftId || this.scope.generateUidIdentifier("left");
|
||||
};
|
||||
|
||||
TailCallTransformer.prototype.getFunctionId = function () {
|
||||
return this.functionId = this.functionId || this.scope.generateUidIdentifier("function");
|
||||
};
|
||||
|
||||
TailCallTransformer.prototype.getAgainId = function () {
|
||||
return this.againId = this.againId || this.scope.generateUidIdentifier("again");
|
||||
};
|
||||
|
||||
TailCallTransformer.prototype.getParams = function () {
|
||||
var params = this.params;
|
||||
|
||||
if (!params) {
|
||||
params = this.node.params;
|
||||
this.paramDecls = [];
|
||||
|
||||
for (var i = 0; i < params.length; i++) {
|
||||
var param = params[i];
|
||||
if (!param._isDefaultPlaceholder) {
|
||||
this.paramDecls.push(t.variableDeclarator(
|
||||
param,
|
||||
params[i] = this.scope.generateUidIdentifier("x")
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return this.params = params;
|
||||
};
|
||||
|
||||
TailCallTransformer.prototype.hasDeopt = function () {
|
||||
// check if the ownerId has been reassigned, if it has then it's not safe to
|
||||
// perform optimisations
|
||||
var ownerIdInfo = this.scope.getBindingInfo(this.ownerId.name);
|
||||
return ownerIdInfo && ownerIdInfo.reassigned;
|
||||
};
|
||||
|
||||
TailCallTransformer.prototype.run = function () {
|
||||
var scope = this.scope;
|
||||
var node = this.node;
|
||||
|
||||
// only tail recursion can be optimized as for now, so we can skip anonymous
|
||||
// functions entirely
|
||||
var ownerId = this.ownerId;
|
||||
if (!ownerId) return;
|
||||
|
||||
// traverse the function and look for tail recursion
|
||||
scope.traverse(node, firstPass, this);
|
||||
|
||||
if (!this.hasTailRecursion) return;
|
||||
|
||||
if (this.hasDeopt()) {
|
||||
this.file.logDeopt(node, messages.get("tailCallReassignmentDeopt"));
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
scope.traverse(node, secondPass, this);
|
||||
|
||||
if (!this.needsThis || !this.needsArguments) {
|
||||
scope.traverse(node, thirdPass, this);
|
||||
}
|
||||
|
||||
var body = t.ensureBlock(node).body;
|
||||
|
||||
if (this.vars.length > 0) {
|
||||
var declarations = flatten(map(this.vars, function (decl) {
|
||||
return decl.declarations;
|
||||
}, this));
|
||||
var statement = reduceRight(declarations, function (expr, decl) {
|
||||
return t.assignmentExpression("=", decl.id, expr);
|
||||
}, t.identifier("undefined"));
|
||||
body.unshift(t.expressionStatement(statement));
|
||||
}
|
||||
|
||||
var paramDecls = this.paramDecls;
|
||||
if (paramDecls.length > 0) {
|
||||
body.unshift(t.variableDeclaration("var", paramDecls));
|
||||
}
|
||||
|
||||
body.unshift(t.expressionStatement(
|
||||
t.assignmentExpression("=", this.getAgainId(), t.literal(false)))
|
||||
);
|
||||
|
||||
node.body = util.template("tail-call-body", {
|
||||
AGAIN_ID: this.getAgainId(),
|
||||
THIS_ID: this.thisId,
|
||||
ARGUMENTS_ID: this.argumentsId,
|
||||
FUNCTION_ID: this.getFunctionId(),
|
||||
BLOCK: node.body
|
||||
});
|
||||
|
||||
var topVars = [];
|
||||
|
||||
if (this.needsThis) {
|
||||
topVars.push(t.variableDeclarator(this.getThisId(), t.thisExpression()));
|
||||
}
|
||||
|
||||
if (this.needsArguments || this.setsArguments) {
|
||||
var decl = t.variableDeclarator(this.getArgumentsId());
|
||||
if (this.needsArguments) {
|
||||
decl.init = t.identifier("arguments");
|
||||
}
|
||||
topVars.push(decl);
|
||||
}
|
||||
|
||||
var leftId = this.leftId;
|
||||
if (leftId) {
|
||||
topVars.push(t.variableDeclarator(leftId));
|
||||
}
|
||||
|
||||
if (topVars.length > 0) {
|
||||
node.body.body.unshift(t.variableDeclaration("var", topVars));
|
||||
}
|
||||
};
|
||||
|
||||
TailCallTransformer.prototype.subTransform = function (node) {
|
||||
if (!node) return;
|
||||
|
||||
var handler = this["subTransform" + node.type];
|
||||
if (handler) return handler.call(this, node);
|
||||
};
|
||||
|
||||
TailCallTransformer.prototype.subTransformConditionalExpression = function (node) {
|
||||
var callConsequent = this.subTransform(node.consequent);
|
||||
var callAlternate = this.subTransform(node.alternate);
|
||||
if (!callConsequent && !callAlternate) {
|
||||
return;
|
||||
}
|
||||
|
||||
// if ternary operator had tail recursion in value, convert to optimized if-statement
|
||||
node.type = "IfStatement";
|
||||
node.consequent = callConsequent ? t.toBlock(callConsequent) : returnBlock(node.consequent);
|
||||
|
||||
if (callAlternate) {
|
||||
node.alternate = t.isIfStatement(callAlternate) ? callAlternate : t.toBlock(callAlternate);
|
||||
} else {
|
||||
node.alternate = returnBlock(node.alternate);
|
||||
}
|
||||
|
||||
return [node];
|
||||
};
|
||||
|
||||
TailCallTransformer.prototype.subTransformLogicalExpression = function (node) {
|
||||
// only call in right-value of can be optimized
|
||||
var callRight = this.subTransform(node.right);
|
||||
if (!callRight) return;
|
||||
|
||||
// cache left value as it might have side-effects
|
||||
var leftId = this.getLeftId();
|
||||
var testExpr = t.assignmentExpression(
|
||||
"=",
|
||||
leftId,
|
||||
node.left
|
||||
);
|
||||
|
||||
if (node.operator === "&&") {
|
||||
testExpr = t.unaryExpression("!", testExpr);
|
||||
}
|
||||
|
||||
return [t.ifStatement(testExpr, returnBlock(leftId))].concat(callRight);
|
||||
};
|
||||
|
||||
TailCallTransformer.prototype.subTransformSequenceExpression = function (node) {
|
||||
var seq = node.expressions;
|
||||
|
||||
// only last element can be optimized
|
||||
var lastCall = this.subTransform(seq[seq.length - 1]);
|
||||
if (!lastCall) {
|
||||
return;
|
||||
}
|
||||
|
||||
// remove converted expression from sequence
|
||||
// and convert to regular expression if needed
|
||||
if (--seq.length === 1) {
|
||||
node = seq[0];
|
||||
}
|
||||
|
||||
return [t.expressionStatement(node)].concat(lastCall);
|
||||
};
|
||||
|
||||
TailCallTransformer.prototype.subTransformCallExpression = function (node) {
|
||||
var callee = node.callee, thisBinding, args;
|
||||
|
||||
if (t.isMemberExpression(callee, { computed: false }) && t.isIdentifier(callee.property)) {
|
||||
switch (callee.property.name) {
|
||||
case "call":
|
||||
args = t.arrayExpression(node.arguments.slice(1));
|
||||
break;
|
||||
|
||||
case "apply":
|
||||
args = node.arguments[1] || t.identifier("undefined");
|
||||
break;
|
||||
|
||||
default:
|
||||
return;
|
||||
}
|
||||
|
||||
thisBinding = node.arguments[0];
|
||||
callee = callee.object;
|
||||
}
|
||||
|
||||
// only tail recursion can be optimized as for now
|
||||
if (!t.isIdentifier(callee) || !this.scope.bindingIdentifierEquals(callee.name, this.ownerId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.hasTailRecursion = true;
|
||||
|
||||
if (this.hasDeopt()) return;
|
||||
|
||||
var body = [];
|
||||
|
||||
if (!t.isThisExpression(thisBinding)) {
|
||||
body.push(t.expressionStatement(t.assignmentExpression(
|
||||
"=",
|
||||
this.getThisId(),
|
||||
thisBinding || t.identifier("undefined")
|
||||
)));
|
||||
}
|
||||
|
||||
if (!args) {
|
||||
args = t.arrayExpression(node.arguments);
|
||||
}
|
||||
|
||||
var argumentsId = this.getArgumentsId();
|
||||
var params = this.getParams();
|
||||
|
||||
body.push(t.expressionStatement(t.assignmentExpression(
|
||||
"=",
|
||||
argumentsId,
|
||||
args
|
||||
)));
|
||||
|
||||
var i, param;
|
||||
|
||||
if (t.isArrayExpression(args)) {
|
||||
var elems = args.elements;
|
||||
for (i = 0; i < elems.length && i < params.length; i++) {
|
||||
param = params[i];
|
||||
var elem = elems[i] || (elems[i] = t.identifier("undefined"));
|
||||
if (!param._isDefaultPlaceholder) {
|
||||
elems[i] = t.assignmentExpression("=", param, elem);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
this.setsArguments = true;
|
||||
for (i = 0; i < params.length; i++) {
|
||||
param = params[i];
|
||||
if (!param._isDefaultPlaceholder) {
|
||||
body.push(t.expressionStatement(t.assignmentExpression(
|
||||
"=",
|
||||
param,
|
||||
t.memberExpression(argumentsId, t.literal(i), true)
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
body.push(t.expressionStatement(
|
||||
t.assignmentExpression("=", this.getAgainId(), t.literal(true))
|
||||
));
|
||||
body.push(t.continueStatement(this.getFunctionId()));
|
||||
|
||||
return body;
|
||||
};
|
||||
|
||||
// looks for and replaces tail recursion calls
|
||||
var firstPass = {
|
||||
enter: function (node, parent, scope, state) {
|
||||
if (t.isIfStatement(node)) {
|
||||
if (t.isReturnStatement(node.alternate)) {
|
||||
t.ensureBlock(node, "alternate");
|
||||
}
|
||||
|
||||
if (t.isReturnStatement(node.consequent)) {
|
||||
t.ensureBlock(node, "consequent");
|
||||
}
|
||||
} else if (t.isReturnStatement(node)) {
|
||||
this.skip();
|
||||
return state.subTransform(node.argument);
|
||||
} else if (t.isTryStatement(parent)) {
|
||||
if (node === parent.block) {
|
||||
this.skip();
|
||||
} else if (parent.finalizer && node !== parent.finalizer) {
|
||||
this.skip();
|
||||
}
|
||||
} else if (t.isFunction(node)) {
|
||||
this.skip();
|
||||
} else if (t.isVariableDeclaration(node)) {
|
||||
this.skip();
|
||||
state.vars.push(node);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// hoists up function declarations, replaces `this` and `arguments` and marks
|
||||
// them as needed
|
||||
var secondPass = {
|
||||
enter: function (node, parent, scope, state) {
|
||||
if (t.isThisExpression(node)) {
|
||||
state.needsThis = true;
|
||||
return state.getThisId();
|
||||
} else if (t.isReferencedIdentifier(node, parent, { name: "arguments" })) {
|
||||
state.needsArguments = true;
|
||||
return state.getArgumentsId();
|
||||
} else if (t.isFunction(node)) {
|
||||
this.skip();
|
||||
if (t.isFunctionDeclaration(node)) {
|
||||
node = t.variableDeclaration("var", [
|
||||
t.variableDeclarator(node.id, t.toExpression(node))
|
||||
]);
|
||||
node._blockHoist = 2;
|
||||
return node;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// optimizes recursion by removing `this` and `arguments` if they aren't used
|
||||
var thirdPass = {
|
||||
enter: function (node, parent, scope, state) {
|
||||
if (!t.isExpressionStatement(node)) return;
|
||||
|
||||
var expr = node.expression;
|
||||
if (!t.isAssignmentExpression(expr)) return;
|
||||
|
||||
if (!state.needsThis && expr.left === state.getThisId()) {
|
||||
this.remove();
|
||||
} else if (!state.needsArguments && expr.left === state.getArgumentsId() && t.isArrayExpression(expr.right)) {
|
||||
return map(expr.right.elements, function (elem) {
|
||||
return t.expressionStatement(elem);
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
exports.Function = function (node, parent, scope, file) {
|
||||
var tailCall = new TailCallTransformer(node, scope, file);
|
||||
tailCall.run();
|
||||
};
|
||||
@@ -1,21 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
var rewritePattern = require("regexpu/rewrite-pattern");
|
||||
var pull = require("lodash/array/pull");
|
||||
var t = require("../../../types");
|
||||
|
||||
exports.check = function (node) {
|
||||
return t.isLiteral(node) && node.regex && node.regex.flags.indexOf("u") >= 0;
|
||||
};
|
||||
|
||||
exports.Literal = function (node) {
|
||||
var regex = node.regex;
|
||||
if (!regex) return;
|
||||
|
||||
var flags = regex.flags.split("");
|
||||
if (regex.flags.indexOf("u") < 0) return;
|
||||
pull(flags, "u");
|
||||
|
||||
regex.pattern = rewritePattern(regex.pattern, regex.flags);
|
||||
regex.flags = flags.join("");
|
||||
};
|
||||
@@ -1,5 +0,0 @@
|
||||
exports.SequenceExpression = function (node) {
|
||||
if (node.expressions.length === 1) {
|
||||
return node.expressions[0];
|
||||
}
|
||||
};
|
||||
@@ -1,33 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
var t = require("../../../types");
|
||||
|
||||
exports.secondPass = true;
|
||||
|
||||
exports.BlockStatement =
|
||||
exports.Program = function (node, parent, scope, file) {
|
||||
if (!node._declarations) return;
|
||||
|
||||
var kinds = {};
|
||||
var kind;
|
||||
|
||||
for (var i in node._declarations) {
|
||||
var declar = node._declarations[i];
|
||||
|
||||
kind = declar.kind || "var";
|
||||
var declarNode = t.variableDeclarator(declar.id, declar.init);
|
||||
|
||||
if (declar.init) {
|
||||
node.body.unshift(file.attachAuxiliaryComment(t.variableDeclaration(kind, [declarNode])));
|
||||
} else {
|
||||
kinds[kind] = kinds[kind] || [];
|
||||
kinds[kind].push(declarNode);
|
||||
}
|
||||
}
|
||||
|
||||
for (kind in kinds) {
|
||||
node.body.unshift(file.attachAuxiliaryComment(t.variableDeclaration(kind, kinds[kind])));
|
||||
}
|
||||
|
||||
node._declarations = null;
|
||||
};
|
||||
@@ -1,11 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
exports.Program = function (program, parent, scope, file) {
|
||||
if (!file.transformers["es6.modules"].canRun()) return;
|
||||
|
||||
program.body = file.dynamicImports.concat(program.body);
|
||||
|
||||
if (file.moduleFormatter.transform) {
|
||||
file.moduleFormatter.transform(program);
|
||||
}
|
||||
};
|
||||
@@ -1,9 +0,0 @@
|
||||
var t = require("../../../types");
|
||||
|
||||
exports.optional = true;
|
||||
|
||||
exports.ExpressionStatement = function (node) {
|
||||
if (t.isIdentifier(node.expression, { name: "debugger" })) {
|
||||
this.remove();
|
||||
}
|
||||
};
|
||||
@@ -1,9 +0,0 @@
|
||||
//var t = require("../../../types");
|
||||
|
||||
exports.optional = true;
|
||||
|
||||
exports.Scopable = function () {
|
||||
//for (var name in scope.bindings) {
|
||||
// scope.rename(name, scope.generateUidIdentifier("a").name);
|
||||
//}
|
||||
};
|
||||
@@ -1,14 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
var remapAsyncToGenerator = require("../../helpers/remap-async-to-generator");
|
||||
var bluebirdCoroutines = require("./bluebird-coroutines");
|
||||
|
||||
exports.optional = true;
|
||||
|
||||
exports.manipulateOptions = bluebirdCoroutines.manipulateOptions;
|
||||
|
||||
exports.Function = function (node, parent, scope, file) {
|
||||
if (!node.async || node.generator) return;
|
||||
|
||||
return remapAsyncToGenerator(node, file.addHelper("async-to-generator"), scope);
|
||||
};
|
||||
@@ -1,13 +0,0 @@
|
||||
var t = require("../../../types");
|
||||
|
||||
exports.TypeCastExpression = function (node) {
|
||||
return node.expression;
|
||||
};
|
||||
|
||||
exports.ImportDeclaration = function (node) {
|
||||
if (node.isType) this.remove();
|
||||
};
|
||||
|
||||
exports.ExportDeclaration = function (node) {
|
||||
if (t.isTypeAlias(node.declaration)) this.remove();
|
||||
};
|
||||
@@ -1,15 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
var regenerator = require("regenerator-babel");
|
||||
var t = require("../../../types");
|
||||
|
||||
exports.check = function (node) {
|
||||
return t.isFunction(node) && (node.async || node.generator);
|
||||
};
|
||||
|
||||
exports.Program = {
|
||||
enter: function (ast) {
|
||||
regenerator.transform(ast);
|
||||
this.stop();
|
||||
}
|
||||
};
|
||||
@@ -1,30 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
var messages = require("../../../messages");
|
||||
var t = require("../../../types");
|
||||
|
||||
exports.Program = function (program) {
|
||||
var first = program.body[0];
|
||||
if (t.isExpressionStatement(first) && t.isLiteral(first.expression, { value: "use strict" })) {
|
||||
program.body.shift();
|
||||
}
|
||||
};
|
||||
|
||||
exports.post = function (file) {
|
||||
file.ast.program.body.unshift(t.expressionStatement(t.literal("use strict")));
|
||||
};
|
||||
|
||||
exports.FunctionDeclaration =
|
||||
exports.FunctionExpression = function () {
|
||||
this.skip();
|
||||
};
|
||||
|
||||
exports.ThisExpression = function () {
|
||||
return t.identifier("undefined");
|
||||
};
|
||||
|
||||
exports.CallExpression = function (node, parent, scope, file) {
|
||||
if (t.isIdentifier(node.callee, { name: "eval" })) {
|
||||
throw file.errorWithNode(node, messages.get("evalInStrictMode"));
|
||||
}
|
||||
};
|
||||
@@ -1,24 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
var messages = require("../../../messages");
|
||||
var build = require("../../helpers/build-conditional-assignment-operator-transformer");
|
||||
var t = require("../../../types");
|
||||
|
||||
exports.playground = true;
|
||||
|
||||
build(exports, {
|
||||
is: function (node, file) {
|
||||
var is = t.isAssignmentExpression(node) && node.operator === "||=";
|
||||
if (is) {
|
||||
var left = node.left;
|
||||
if (!t.isMemberExpression(left) && !t.isIdentifier(left)) {
|
||||
throw file.errorWithNode(left, messages.get("expectedMemberExpressionOrIdentifier"));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
},
|
||||
|
||||
build: function (node) {
|
||||
return t.unaryExpression("!", node, true);
|
||||
}
|
||||
});
|
||||
@@ -1,95 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
var t = require("../../../types");
|
||||
var util = require("../../../util");
|
||||
|
||||
var propertyFunctionVisitor = {
|
||||
enter: function (node, parent, scope, state) {
|
||||
if (t.isReferencedIdentifier(node, parent, { name: state.name }) && scope.getBindingIdentifier(node.name) === state.binding) {
|
||||
return state.getOuter();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
//exports.ArrowFunctionExpression =
|
||||
exports.FunctionExpression = function (node, parent, scope) {
|
||||
// has an `id` so we don't need to infer one
|
||||
if (node.id) return;
|
||||
|
||||
var id;
|
||||
if (t.isProperty(parent) && parent.kind === "init" && !parent.computed) {
|
||||
// { foo: function () {} };
|
||||
id = parent.key;
|
||||
} else if (t.isVariableDeclarator(parent)) {
|
||||
// var foo = function () {};
|
||||
id = parent.id;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!t.isIdentifier(id)) return;
|
||||
|
||||
var name = t.toIdentifier(id.name);
|
||||
id = t.identifier(name);
|
||||
|
||||
// check to see if we have a local binding of the id we're setting inside of
|
||||
// the function, this is important as there are caveats associated
|
||||
|
||||
var bindingInfo = scope.getOwnBindingInfo(name);
|
||||
|
||||
if (bindingInfo) {
|
||||
if (bindingInfo.type === "param") {
|
||||
// safari will blow up in strict mode with code like:
|
||||
//
|
||||
// var t = function t(t) {};
|
||||
//
|
||||
// with the error:
|
||||
//
|
||||
// Cannot declare a parameter named 't' as it shadows the name of a
|
||||
// strict mode function.
|
||||
//
|
||||
// this isn't to the spec and they've invented this behaviour which is
|
||||
// **extremely** annoying so we avoid setting the name if it has a param
|
||||
// with the same id
|
||||
} else {
|
||||
// otherwise it's defined somewhere in scope like:
|
||||
//
|
||||
// var t = function () {
|
||||
// var t = 2;
|
||||
// };
|
||||
//
|
||||
// so we can safely just set the id and move along as it shadows the
|
||||
// bound function id
|
||||
node.id = id;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
var binding = scope.getBindingIdentifier(name);
|
||||
var outerId;
|
||||
|
||||
scope.traverse(node, propertyFunctionVisitor, {
|
||||
name: name,
|
||||
binding: binding,
|
||||
|
||||
getOuter: function () {
|
||||
return t.callExpression(
|
||||
outerId || (outerId = scope.generateUidIdentifier("getOuter")),
|
||||
[]
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
node.id = id;
|
||||
|
||||
if (outerId) {
|
||||
return util.template("named-func", {
|
||||
GET_OUTER_ID: outerId,
|
||||
FUNCTION: node,
|
||||
ID: id
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -1,11 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
var t = require("../../../types");
|
||||
|
||||
exports.optional = true;
|
||||
|
||||
exports.Identifier = function (node, parent) {
|
||||
if (node.name === "undefined" && t.isReferenced(node, parent)) {
|
||||
return t.unaryExpression("void", t.literal(0), true);
|
||||
}
|
||||
};
|
||||
@@ -1,15 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
var messages = require("../../../messages");
|
||||
var t = require("../../../types");
|
||||
|
||||
exports.check = t.isFor;
|
||||
|
||||
exports.ForInStatement =
|
||||
exports.ForOfStatement = function (node, parent, scope, file) {
|
||||
var left = node.left;
|
||||
if (t.isVariableDeclaration(left)) {
|
||||
var declar = left.declarations[0];
|
||||
if (declar.init) throw file.errorWithNode(declar, messages.get("noAssignmentsInForHead"));
|
||||
}
|
||||
};
|
||||
@@ -1,14 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
var messages = require("../../../messages");
|
||||
|
||||
exports.check = function (node) {
|
||||
return node.kind === "set";
|
||||
};
|
||||
|
||||
exports.MethodDefinition =
|
||||
exports.Property = function (node, parent, scope, file) {
|
||||
if (node.kind === "set" && node.value.params.length !== 1) {
|
||||
throw file.errorWithNode(node.value, messages.get("settersInvalidParamLength"));
|
||||
}
|
||||
};
|
||||
@@ -1,54 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
module.exports = TraversalContext;
|
||||
|
||||
var TraversalPath = require("./path");
|
||||
var flatten = require("lodash/array/flatten");
|
||||
var compact = require("lodash/array/compact");
|
||||
|
||||
function TraversalContext(scope, opts, state, parentPath) {
|
||||
this.shouldFlatten = false;
|
||||
this.parentPath = parentPath;
|
||||
|
||||
this.scope = scope;
|
||||
this.state = state;
|
||||
this.opts = opts;
|
||||
}
|
||||
|
||||
TraversalContext.prototype.flatten = function () {
|
||||
this.shouldFlatten = true;
|
||||
};
|
||||
|
||||
TraversalContext.prototype.visitNode = function (node, obj, key) {
|
||||
var iteration = new TraversalPath(this, node, obj, key);
|
||||
return iteration.visit();
|
||||
};
|
||||
|
||||
TraversalContext.prototype.visit = function (node, key) {
|
||||
var nodes = node[key];
|
||||
if (!nodes) return;
|
||||
|
||||
if (!Array.isArray(nodes)) {
|
||||
return this.visitNode(node, node, key);
|
||||
}
|
||||
|
||||
// nothing to traverse!
|
||||
if (nodes.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (var i = 0; i < nodes.length; i++) {
|
||||
if (nodes[i] && this.visitNode(node, nodes, i)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.shouldFlatten) {
|
||||
node[key] = flatten(node[key]);
|
||||
|
||||
if (key === "body") {
|
||||
// we can safely compact this
|
||||
node[key] = compact(node[key]);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -1,156 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
module.exports = TraversalPath;
|
||||
|
||||
/* jshint maxparams:7 */
|
||||
|
||||
var traverse = require("./index");
|
||||
var includes = require("lodash/collection/includes");
|
||||
var Scope = require("./scope");
|
||||
var t = require("../types");
|
||||
|
||||
function TraversalPath(context, parent, obj, key) {
|
||||
this.shouldRemove = false;
|
||||
this.shouldSkip = false;
|
||||
this.shouldStop = false;
|
||||
|
||||
this.parentPath = context.parentPath;
|
||||
this.context = context;
|
||||
this.state = this.context.state;
|
||||
this.opts = this.context.opts;
|
||||
|
||||
this.key = key;
|
||||
this.obj = obj;
|
||||
|
||||
this.parent = parent;
|
||||
this.scope = TraversalPath.getScope(this.getNode(), parent, context.scope);
|
||||
this.state = context.state;
|
||||
}
|
||||
|
||||
TraversalPath.prototype.remove = function () {
|
||||
this.shouldRemove = true;
|
||||
this.shouldSkip = true;
|
||||
};
|
||||
|
||||
TraversalPath.prototype.skip = function () {
|
||||
this.shouldSkip = true;
|
||||
};
|
||||
|
||||
TraversalPath.prototype.stop = function () {
|
||||
this.shouldStop = true;
|
||||
this.shouldSkip = true;
|
||||
};
|
||||
|
||||
TraversalPath.prototype.flatten = function () {
|
||||
this.context.flatten();
|
||||
};
|
||||
|
||||
TraversalPath.getScope = function (node, parent, scope) {
|
||||
var ourScope = scope;
|
||||
|
||||
// we're entering a new scope so let's construct it!
|
||||
if (t.isScope(node, parent)) {
|
||||
ourScope = new Scope(node, parent, scope);
|
||||
}
|
||||
|
||||
return ourScope;
|
||||
};
|
||||
|
||||
TraversalPath.prototype.maybeRemove = function () {
|
||||
if (this.shouldRemove) {
|
||||
this.setNode(null);
|
||||
this.flatten();
|
||||
}
|
||||
};
|
||||
|
||||
TraversalPath.prototype.setNode = function (val) {
|
||||
return this.obj[this.key] = val;
|
||||
};
|
||||
|
||||
TraversalPath.prototype.getNode = function () {
|
||||
return this.obj[this.key];
|
||||
};
|
||||
|
||||
TraversalPath.prototype.replaceNode = function (replacement) {
|
||||
var isArray = Array.isArray(replacement);
|
||||
|
||||
// inherit comments from original node to the first replacement node
|
||||
var inheritTo = replacement;
|
||||
if (isArray) inheritTo = replacement[0];
|
||||
if (inheritTo) t.inheritsComments(inheritTo, this.getNode());
|
||||
|
||||
// replace the node
|
||||
this.setNode(replacement);
|
||||
|
||||
var file = this.scope && this.scope.file;
|
||||
if (file) {
|
||||
if (isArray) {
|
||||
for (var i = 0; i < replacement.length; i++) {
|
||||
file.checkNode(replacement[i], this.scope);
|
||||
}
|
||||
} else {
|
||||
file.checkNode(replacement, this.scope);
|
||||
}
|
||||
}
|
||||
|
||||
// we're replacing a statement or block node with an array of statements so we better
|
||||
// ensure that it's a block
|
||||
if (isArray) {
|
||||
if (includes(t.STATEMENT_OR_BLOCK_KEYS, this.key) && !t.isBlockStatement(this.obj)) {
|
||||
t.ensureBlock(this.obj, this.key);
|
||||
}
|
||||
|
||||
this.flatten();
|
||||
}
|
||||
};
|
||||
|
||||
TraversalPath.prototype.call = function (key) {
|
||||
var node = this.getNode();
|
||||
if (!node) return;
|
||||
|
||||
var opts = this.opts;
|
||||
var fn = opts[key] || opts;
|
||||
if (opts[node.type]) fn = opts[node.type][key] || fn;
|
||||
|
||||
var replacement = fn.call(this, node, this.parent, this.scope, this.state);
|
||||
|
||||
if (replacement) {
|
||||
this.replaceNode(replacement);
|
||||
node = replacement;
|
||||
}
|
||||
|
||||
this.maybeRemove();
|
||||
|
||||
return node;
|
||||
};
|
||||
|
||||
TraversalPath.prototype.visit = function () {
|
||||
var opts = this.opts;
|
||||
var node = this.getNode();
|
||||
|
||||
// type is blacklisted
|
||||
if (opts.blacklist && opts.blacklist.indexOf(node.type) > -1) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.call("enter");
|
||||
|
||||
if (this.shouldSkip) {
|
||||
return this.shouldStop;
|
||||
}
|
||||
|
||||
node = this.getNode();
|
||||
|
||||
if (Array.isArray(node)) {
|
||||
// traverse over these replacement nodes we purposely don't call exitNode
|
||||
// as the original node has been destroyed
|
||||
for (var i = 0; i < node.length; i++) {
|
||||
traverse.node(node[i], opts, this.scope, this.state, this);
|
||||
}
|
||||
} else {
|
||||
traverse.node(node, opts, this.scope, this.state, this);
|
||||
this.call("exit");
|
||||
}
|
||||
|
||||
return this.shouldStop;
|
||||
};
|
||||
@@ -1,646 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
module.exports = Scope;
|
||||
|
||||
var includes = require("lodash/collection/includes");
|
||||
var traverse = require("./index");
|
||||
var defaults = require("lodash/object/defaults");
|
||||
var messages = require("../messages");
|
||||
var globals = require("globals");
|
||||
var flatten = require("lodash/array/flatten");
|
||||
var extend = require("lodash/object/extend");
|
||||
var object = require("../helpers/object");
|
||||
var each = require("lodash/collection/each");
|
||||
var t = require("../types");
|
||||
|
||||
/**
|
||||
* This searches the current "scope" and collects all references/bindings
|
||||
* within.
|
||||
*
|
||||
* @param {Node} block
|
||||
* @param {Node} parentBlock
|
||||
* @param {Scope} [parent]
|
||||
* @param {File} [file]
|
||||
*/
|
||||
|
||||
function Scope(block, parentBlock, parent, file) {
|
||||
this.parent = parent;
|
||||
this.file = parent ? parent.file : file;
|
||||
|
||||
this.parentBlock = parentBlock;
|
||||
this.block = block;
|
||||
|
||||
this.crawl();
|
||||
}
|
||||
|
||||
Scope.globals = flatten([globals.builtin, globals.browser, globals.node].map(Object.keys));
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {Object} node
|
||||
* @param {Object} opts
|
||||
* @param [state]
|
||||
*/
|
||||
|
||||
Scope.prototype.traverse = function (node, opts, state) {
|
||||
traverse(node, opts, this, state);
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {String} [name="temp"]
|
||||
*/
|
||||
|
||||
Scope.prototype.generateTemp = function (name) {
|
||||
var id = this.generateUidIdentifier(name || "temp");
|
||||
this.push({
|
||||
key: id.name,
|
||||
id: id
|
||||
});
|
||||
return id;
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {String} name
|
||||
*/
|
||||
|
||||
Scope.prototype.generateUidIdentifier = function (name) {
|
||||
var id = t.identifier(this.generateUid(name));
|
||||
this.getFunctionParent().registerBinding("uid", id);
|
||||
return id;
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {String} name
|
||||
*/
|
||||
|
||||
Scope.prototype.generateUid = function (name) {
|
||||
name = t.toIdentifier(name).replace(/^_+/, "");
|
||||
|
||||
var uid;
|
||||
var i = 0;
|
||||
do {
|
||||
uid = this._generateUid(name, i);
|
||||
i++;
|
||||
} while (this.hasBinding(uid) || this.hasGlobal(uid));
|
||||
return uid;
|
||||
};
|
||||
|
||||
Scope.prototype._generateUid = function (name, i) {
|
||||
var id = name;
|
||||
if (i > 1) id += i;
|
||||
return "_" + id;
|
||||
};
|
||||
|
||||
/*
|
||||
* Description
|
||||
*
|
||||
* @param {Object} parent
|
||||
* @returns {Object}
|
||||
*/
|
||||
|
||||
Scope.prototype.generateUidBasedOnNode = function (parent) {
|
||||
var node = parent;
|
||||
|
||||
if (t.isAssignmentExpression(parent)) {
|
||||
node = parent.left;
|
||||
} else if (t.isVariableDeclarator(parent)) {
|
||||
node = parent.id;
|
||||
} else if (t.isProperty(node)) {
|
||||
node = node.key;
|
||||
}
|
||||
|
||||
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);
|
||||
} else if (t.isCallExpression(node)) {
|
||||
add(node.callee);
|
||||
}
|
||||
};
|
||||
|
||||
add(node);
|
||||
|
||||
var id = parts.join("$");
|
||||
id = id.replace(/^_/, "") || "ref";
|
||||
|
||||
return this.generateUidIdentifier(id);
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {Object} node
|
||||
* @returns {Object}
|
||||
*/
|
||||
|
||||
Scope.prototype.generateTempBasedOnNode = function (node) {
|
||||
if (t.isIdentifier(node) && this.hasBinding(node.name)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var id = this.generateUidBasedOnNode(node);
|
||||
this.push({
|
||||
key: id.name,
|
||||
id: id
|
||||
});
|
||||
return id;
|
||||
};
|
||||
|
||||
Scope.prototype.checkBlockScopedCollisions = function (kind, name, id) {
|
||||
var local = this.getOwnBindingInfo(name);
|
||||
if (!local) return;
|
||||
|
||||
if (kind === "param") return;
|
||||
if (kind === "hoisted" && local.kind === "let") return;
|
||||
|
||||
if (local.kind === "let" || local.kind === "const" || local.kind === "module") {
|
||||
throw this.file.errorWithNode(id, messages.get("scopeDuplicateDeclaration", name), TypeError);
|
||||
}
|
||||
};
|
||||
|
||||
Scope.prototype.rename = function (oldName, newName) {
|
||||
newName = newName || this.generateUidIdentifier(oldName).name;
|
||||
|
||||
var info = this.getBindingInfo(oldName);
|
||||
if (!info) return;
|
||||
|
||||
var binding = info.identifier;
|
||||
var scope = info.scope;
|
||||
|
||||
scope.traverse(scope.block, {
|
||||
enter: function (node, parent, scope) {
|
||||
if (t.isReferencedIdentifier(node, parent) && node.name === oldName) {
|
||||
node.name = newName;
|
||||
} else if (t.isDeclaration(node)) {
|
||||
var ids = t.getBindingIdentifiers(node);
|
||||
for (var name in ids) {
|
||||
if (name === oldName) ids[name].name = newName;
|
||||
}
|
||||
} else if (t.isScope(node, parent)) {
|
||||
if (!scope.bindingIdentifierEquals(oldName, binding)) {
|
||||
this.skip();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
this.clearOwnBinding(oldName);
|
||||
scope.bindings[newName] = info;
|
||||
|
||||
binding.name = newName;
|
||||
};
|
||||
|
||||
Scope.prototype.inferType = function (node) {
|
||||
var target;
|
||||
|
||||
if (t.isVariableDeclarator(node)) {
|
||||
target = node.init;
|
||||
}
|
||||
|
||||
if (t.isArrayExpression(target)) {
|
||||
return t.genericTypeAnnotation(t.identifier("Array"));
|
||||
}
|
||||
|
||||
if (t.isObjectExpression(target)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (t.isLiteral(target)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (t.isCallExpression(target) && t.isIdentifier(target.callee)) {
|
||||
var funcInfo = this.getBindingInfo(target.callee.name);
|
||||
if (funcInfo) {
|
||||
var funcNode = funcInfo.node;
|
||||
return !funcInfo.reassigned && t.isFunction(funcNode) && node.returnType;
|
||||
}
|
||||
}
|
||||
|
||||
if (t.isIdentifier(target)) {
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
Scope.prototype.isTypeGeneric = function (name, genericName) {
|
||||
var info = this.getBindingInfo(name);
|
||||
if (!info) return false;
|
||||
|
||||
var type = info.typeAnnotation;
|
||||
return t.isGenericTypeAnnotation(type) && t.isIdentifier(type.id, { name: genericName });
|
||||
};
|
||||
|
||||
Scope.prototype.assignTypeGeneric = function (name, type) {
|
||||
this.assignType(name, t.genericTypeAnnotation(t.identifier(type)));
|
||||
};
|
||||
|
||||
Scope.prototype.assignType = function (name, type) {
|
||||
var info = this.getBindingInfo(name);
|
||||
if (!info) return;
|
||||
|
||||
info.identifier.typeAnnotation = info.typeAnnotation = type;
|
||||
};
|
||||
|
||||
Scope.prototype.getTypeAnnotation = function (name, id, node) {
|
||||
var info = {
|
||||
annotation: null,
|
||||
inferred: false
|
||||
};
|
||||
|
||||
var type;
|
||||
|
||||
if (id.typeAnnotation) {
|
||||
type = id.typeAnnotation;
|
||||
}
|
||||
|
||||
if (!type) {
|
||||
info.inferred = true;
|
||||
type = this.inferType(node);
|
||||
}
|
||||
|
||||
if (type) {
|
||||
if (t.isTypeAnnotation(type)) type = type.typeAnnotation;
|
||||
info.annotation = type;
|
||||
}
|
||||
|
||||
return info;
|
||||
};
|
||||
|
||||
Scope.prototype.toArray = function (node, i) {
|
||||
var file = this.file;
|
||||
|
||||
if (t.isIdentifier(node) && this.isTypeGeneric(node.name, "Array")) {
|
||||
return node;
|
||||
}
|
||||
|
||||
if (t.isArrayExpression(node)) {
|
||||
return node;
|
||||
}
|
||||
|
||||
if (t.isIdentifier(node, { name: "arguments" })) {
|
||||
return t.callExpression(t.memberExpression(file.addHelper("slice"), t.identifier("call")), [node]);
|
||||
}
|
||||
|
||||
var helperName = "to-array";
|
||||
var args = [node];
|
||||
if (i === true) {
|
||||
helperName = "to-consumable-array";
|
||||
} else if (i) {
|
||||
args.push(t.literal(i));
|
||||
helperName = "sliced-to-array";
|
||||
}
|
||||
return t.callExpression(file.addHelper(helperName), args);
|
||||
};
|
||||
|
||||
Scope.prototype.clearOwnBinding = function (name) {
|
||||
delete this.bindings[name];
|
||||
};
|
||||
|
||||
Scope.prototype.registerDeclaration = function (node) {
|
||||
if (t.isFunctionDeclaration(node)) {
|
||||
this.registerBinding("hoisted", node);
|
||||
} else if (t.isVariableDeclaration(node)) {
|
||||
for (var i = 0; i < node.declarations.length; i++) {
|
||||
this.registerBinding(node.kind, node.declarations[i]);
|
||||
}
|
||||
} else if (t.isClassDeclaration(node)) {
|
||||
this.registerBinding("let", node);
|
||||
} else if (t.isImportDeclaration(node) || t.isExportDeclaration(node)) {
|
||||
this.registerBinding("module", node);
|
||||
} else {
|
||||
this.registerBinding("unknown", node);
|
||||
}
|
||||
};
|
||||
|
||||
Scope.prototype.registerBindingReassignment = function (node) {
|
||||
var ids = t.getBindingIdentifiers(node);
|
||||
for (var name in ids) {
|
||||
var info = this.getBindingInfo(name);
|
||||
if (info) {
|
||||
info.reassigned = true;
|
||||
|
||||
if (info.typeAnnotationInferred) {
|
||||
// destroy the inferred typeAnnotation
|
||||
info.typeAnnotation = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Scope.prototype.registerBinding = function (kind, node) {
|
||||
if (!kind) throw new ReferenceError("no `kind`");
|
||||
|
||||
var ids = t.getBindingIdentifiers(node);
|
||||
|
||||
for (var name in ids) {
|
||||
var id = ids[name];
|
||||
|
||||
this.checkBlockScopedCollisions(kind, name, id);
|
||||
|
||||
var typeInfo = this.getTypeAnnotation(name, id, node);
|
||||
|
||||
this.bindings[name] = {
|
||||
typeAnnotationInferred: typeInfo.inferred,
|
||||
typeAnnotation: typeInfo.annotation,
|
||||
reassigned: false,
|
||||
identifier: id,
|
||||
scope: this,
|
||||
node: node,
|
||||
kind: kind
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
Scope.prototype.registerVariableDeclaration = function (declar) {
|
||||
var declars = declar.declarations;
|
||||
for (var i = 0; i < declars.length; i++) {
|
||||
this.registerBinding(declars[i], declar.kind);
|
||||
}
|
||||
};
|
||||
|
||||
var functionVariableVisitor = {
|
||||
enter: function (node, parent, scope, state) {
|
||||
if (t.isFor(node)) {
|
||||
each(t.FOR_INIT_KEYS, function (key) {
|
||||
var declar = node[key];
|
||||
if (t.isVar(declar)) state.scope.registerBinding("var", declar);
|
||||
});
|
||||
}
|
||||
|
||||
// this block is a function so we'll stop since none of the variables
|
||||
// declared within are accessible
|
||||
if (t.isFunction(node)) return this.skip();
|
||||
|
||||
// function identifier doesn't belong to this scope
|
||||
if (state.blockId && node === state.blockId) return;
|
||||
|
||||
// delegate block scope handling to the `blockVariableVisitor`
|
||||
if (t.isBlockScoped(node)) return;
|
||||
|
||||
// this will be hit again once we traverse into it after this iteration
|
||||
if (t.isExportDeclaration(node) && t.isDeclaration(node.declaration)) return;
|
||||
|
||||
// we've ran into a declaration!
|
||||
if (t.isDeclaration(node)) state.scope.registerDeclaration(node);
|
||||
}
|
||||
};
|
||||
|
||||
Scope.prototype.addGlobal = function (node) {
|
||||
this.globals[node.name] = node;
|
||||
};
|
||||
|
||||
Scope.prototype.hasGlobal = function (name) {
|
||||
var scope = this;
|
||||
|
||||
do {
|
||||
if (scope.globals[name]) return true;
|
||||
} while (scope = scope.parent);
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
var programReferenceVisitor = {
|
||||
enter: function (node, parent, scope, state) {
|
||||
if (t.isReferencedIdentifier(node, parent) && !scope.hasBinding(node.name)) {
|
||||
state.addGlobal(node);
|
||||
} else if (t.isLabeledStatement(node)) {
|
||||
state.addGlobal(node);
|
||||
} else if (t.isAssignmentExpression(node) || t.isUpdateExpression(node) || (t.isUnaryExpression(node) && node.operator === "delete")) {
|
||||
scope.registerBindingReassignment(node);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
var blockVariableVisitor = {
|
||||
enter: function (node, parent, scope, state) {
|
||||
if (t.isFunctionDeclaration(node) || t.isBlockScoped(node)) {
|
||||
state.registerDeclaration(node);
|
||||
} else if (t.isScope(node, parent)) {
|
||||
this.skip();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Scope.prototype.crawl = function () {
|
||||
var block = this.block;
|
||||
var i;
|
||||
|
||||
//
|
||||
|
||||
var info = block._scopeInfo;
|
||||
if (info) {
|
||||
extend(this, info);
|
||||
return;
|
||||
}
|
||||
|
||||
info = block._scopeInfo = {
|
||||
bindings: object(),
|
||||
globals: object()
|
||||
};
|
||||
|
||||
extend(this, info);
|
||||
|
||||
// ForStatement - left, init
|
||||
|
||||
if (t.isLoop(block)) {
|
||||
for (i = 0; i < t.FOR_INIT_KEYS.length; i++) {
|
||||
var node = block[t.FOR_INIT_KEYS[i]];
|
||||
if (t.isBlockScoped(node)) this.registerBinding("let", node);
|
||||
}
|
||||
|
||||
if (t.isBlockStatement(block.body)) {
|
||||
block = block.body;
|
||||
}
|
||||
}
|
||||
|
||||
// FunctionExpression - id
|
||||
|
||||
if (t.isFunctionExpression(block) && block.id) {
|
||||
if (!t.isProperty(this.parentBlock, { method: true })) {
|
||||
this.registerBinding("var", block.id);
|
||||
}
|
||||
}
|
||||
|
||||
// Function - params, rest
|
||||
|
||||
if (t.isFunction(block)) {
|
||||
for (i = 0; i < block.params.length; i++) {
|
||||
this.registerBinding("param", block.params[i]);
|
||||
}
|
||||
this.traverse(block.body, blockVariableVisitor, this);
|
||||
}
|
||||
|
||||
// Program, BlockStatement, Function - let variables
|
||||
|
||||
if (t.isBlockStatement(block) || t.isProgram(block)) {
|
||||
this.traverse(block, blockVariableVisitor, this);
|
||||
}
|
||||
|
||||
// CatchClause - param
|
||||
|
||||
if (t.isCatchClause(block)) {
|
||||
this.registerBinding("let", block.param);
|
||||
}
|
||||
|
||||
// ComprehensionExpression - blocks
|
||||
|
||||
if (t.isComprehensionExpression(block)) {
|
||||
this.registerBinding("let", block);
|
||||
}
|
||||
|
||||
// Program, Function - var variables
|
||||
|
||||
if (t.isProgram(block) || t.isFunction(block)) {
|
||||
this.traverse(block, functionVariableVisitor, {
|
||||
blockId: block.id,
|
||||
scope: this
|
||||
});
|
||||
}
|
||||
|
||||
// Program
|
||||
|
||||
if (t.isProgram(block)) {
|
||||
this.traverse(block, programReferenceVisitor, this);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {Object} opts
|
||||
*/
|
||||
|
||||
Scope.prototype.push = function (opts) {
|
||||
var block = this.block;
|
||||
|
||||
if (t.isLoop(block) || t.isCatchClause(block) || t.isFunction(block)) {
|
||||
t.ensureBlock(block);
|
||||
block = block.body;
|
||||
}
|
||||
|
||||
if (t.isBlockStatement(block) || t.isProgram(block)) {
|
||||
block._declarations = block._declarations || {};
|
||||
block._declarations[opts.key] = {
|
||||
kind: opts.kind,
|
||||
id: opts.id,
|
||||
init: opts.init
|
||||
};
|
||||
} else {
|
||||
throw new TypeError("cannot add a declaration here in node type " + block.type);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Walk up the scope tree until we hit either a Function or reach the
|
||||
* very top and hit Program.
|
||||
*/
|
||||
|
||||
Scope.prototype.getFunctionParent = function () {
|
||||
var scope = this;
|
||||
while (scope.parent && !t.isFunction(scope.block)) {
|
||||
scope = scope.parent;
|
||||
}
|
||||
return scope;
|
||||
};
|
||||
|
||||
/**
|
||||
* Walks the scope tree and gathers **all** bindings.
|
||||
*
|
||||
* @returns {Object}
|
||||
*/
|
||||
|
||||
Scope.prototype.getAllBindings = function () {
|
||||
var ids = object();
|
||||
|
||||
var scope = this;
|
||||
do {
|
||||
defaults(ids, scope.bindings);
|
||||
scope = scope.parent;
|
||||
} while (scope);
|
||||
|
||||
return ids;
|
||||
};
|
||||
|
||||
/**
|
||||
* Walks the scope tree and gathers all declarations of `kind`.
|
||||
*
|
||||
* @param {String} kind
|
||||
* @returns {Object}
|
||||
*/
|
||||
|
||||
Scope.prototype.getAllBindingsOfKind = function (kind) {
|
||||
var ids = object();
|
||||
|
||||
var scope = this;
|
||||
do {
|
||||
for (var name in scope.bindings) {
|
||||
var binding = scope.bindings[name];
|
||||
if (binding.kind === kind) ids[name] = binding;
|
||||
}
|
||||
scope = scope.parent;
|
||||
} while (scope);
|
||||
|
||||
return ids;
|
||||
};
|
||||
|
||||
// misc
|
||||
|
||||
Scope.prototype.bindingIdentifierEquals = function (name, node) {
|
||||
return this.getBindingIdentifier(name) === node;
|
||||
};
|
||||
|
||||
// get
|
||||
|
||||
Scope.prototype.getBindingInfo = function (name) {
|
||||
var scope = this;
|
||||
|
||||
do {
|
||||
var binding = scope.getOwnBindingInfo(name);
|
||||
if (binding) return binding;
|
||||
} while (scope = scope.parent);
|
||||
};
|
||||
|
||||
Scope.prototype.getOwnBindingInfo = function (name) {
|
||||
return this.bindings[name];
|
||||
};
|
||||
|
||||
Scope.prototype.getBindingIdentifier = function (name) {
|
||||
var info = this.getBindingInfo(name);
|
||||
return info && info.identifier;
|
||||
};
|
||||
|
||||
Scope.prototype.getOwnBindingIdentifier = function (name) {
|
||||
var binding = this.bindings[name];
|
||||
return binding && binding.identifier;
|
||||
};
|
||||
|
||||
// has
|
||||
|
||||
Scope.prototype.hasOwnBinding = function (name) {
|
||||
return !!this.getOwnBindingInfo(name);
|
||||
};
|
||||
|
||||
Scope.prototype.hasBinding = function (name) {
|
||||
if (!name) return false;
|
||||
if (this.hasOwnBinding(name)) return true;
|
||||
if (this.parentHasBinding(name)) return true;
|
||||
if (includes(Scope.globals, name)) return true;
|
||||
return false;
|
||||
};
|
||||
|
||||
Scope.prototype.parentHasBinding = function (name) {
|
||||
return this.parent && this.parent.hasBinding(name);
|
||||
};
|
||||
@@ -1,805 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
var toFastProperties = require("../helpers/to-fast-properties");
|
||||
var isString = require("lodash/lang/isString");
|
||||
var compact = require("lodash/array/compact");
|
||||
var esutils = require("esutils");
|
||||
var object = require("../helpers/object");
|
||||
var each = require("lodash/collection/each");
|
||||
var uniq = require("lodash/array/uniq");
|
||||
|
||||
var t = exports;
|
||||
|
||||
/**
|
||||
* Registers `is[Type]` and `assert[Type]` generated functions for a given `type`.
|
||||
* Pass `skipAliasCheck` to force it to directly compare `node.type` with `type`.
|
||||
*
|
||||
* @param {String} type
|
||||
* @param {Boolean?} skipAliasCheck
|
||||
*/
|
||||
|
||||
function registerType(type, skipAliasCheck) {
|
||||
var is = t["is" + type] = function (node, opts) {
|
||||
return t.is(type, node, opts, skipAliasCheck);
|
||||
};
|
||||
|
||||
t["assert" + type] = function (node, opts) {
|
||||
opts = opts || {};
|
||||
if (!is(node, opts)) {
|
||||
throw new Error("Expected type " + JSON.stringify(type) + " with option " + JSON.stringify(opts));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
t.STATEMENT_OR_BLOCK_KEYS = ["consequent", "body"];
|
||||
t.NATIVE_TYPE_NAMES = ["Array", "Object", "Number", "Boolean", "Date", "Array", "String"];
|
||||
t.FOR_INIT_KEYS = ["left", "init"];
|
||||
|
||||
t.VISITOR_KEYS = require("./visitor-keys");
|
||||
t.ALIAS_KEYS = require("./alias-keys");
|
||||
|
||||
t.FLIPPED_ALIAS_KEYS = {};
|
||||
|
||||
each(t.VISITOR_KEYS, function (keys, type) {
|
||||
registerType(type, true);
|
||||
});
|
||||
|
||||
each(t.ALIAS_KEYS, function (aliases, type) {
|
||||
each(aliases, function (alias) {
|
||||
var types = t.FLIPPED_ALIAS_KEYS[alias] = t.FLIPPED_ALIAS_KEYS[alias] || [];
|
||||
types.push(type);
|
||||
});
|
||||
});
|
||||
|
||||
each(t.FLIPPED_ALIAS_KEYS, function (types, type) {
|
||||
t[type.toUpperCase() + "_TYPES"] = types;
|
||||
registerType(type, false);
|
||||
});
|
||||
|
||||
/**
|
||||
* Returns whether `node` is of given `type`.
|
||||
*
|
||||
* For better performance, use this instead of `is[Type]` when `type` is unknown.
|
||||
* Optionally, pass `skipAliasCheck` to directly compare `node.type` with `type`.
|
||||
*
|
||||
* @param {String} type
|
||||
* @param {Node} node
|
||||
* @param {Object?} opts
|
||||
* @param {Boolean?} skipAliasCheck
|
||||
* @returns {Boolean} isOfType
|
||||
*/
|
||||
|
||||
t.is = function (type, node, opts, skipAliasCheck) {
|
||||
if (!node) return false;
|
||||
|
||||
var typeMatches = type === node.type;
|
||||
|
||||
if (!typeMatches && !skipAliasCheck) {
|
||||
var aliases = t.FLIPPED_ALIAS_KEYS[type];
|
||||
|
||||
if (typeof aliases !== "undefined") {
|
||||
typeMatches = aliases.indexOf(node.type) > -1;
|
||||
}
|
||||
}
|
||||
|
||||
if (!typeMatches) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (typeof opts !== "undefined") {
|
||||
return t.shallowEqual(node, opts);
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
//
|
||||
|
||||
t.BUILDER_KEYS = require("./builder-keys");
|
||||
|
||||
each(t.VISITOR_KEYS, function (keys, type) {
|
||||
if (t.BUILDER_KEYS[type]) return;
|
||||
|
||||
var defs = {};
|
||||
each(keys, function (key) {
|
||||
defs[key] = null;
|
||||
});
|
||||
t.BUILDER_KEYS[type] = defs;
|
||||
});
|
||||
|
||||
each(t.BUILDER_KEYS, function (keys, type) {
|
||||
t[type[0].toLowerCase() + type.slice(1)] = function () {
|
||||
var node = {};
|
||||
node.start = null;
|
||||
node.type = type;
|
||||
|
||||
var i = 0;
|
||||
|
||||
for (var key in keys) {
|
||||
var arg = arguments[i++];
|
||||
if (arg === undefined) arg = keys[key];
|
||||
node[key] = arg;
|
||||
}
|
||||
|
||||
return node;
|
||||
};
|
||||
});
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {Object} node
|
||||
* @returns {Object}
|
||||
*/
|
||||
|
||||
t.toComputedKey = function (node, key) {
|
||||
if (!node.computed) {
|
||||
if (t.isIdentifier(key)) key = t.literal(key.name);
|
||||
}
|
||||
return key;
|
||||
};
|
||||
|
||||
/*
|
||||
* Shallowly checks to see if the passed `node` is falsy.
|
||||
*
|
||||
* @param {Object} node
|
||||
* @returns {Boolean}
|
||||
*/
|
||||
|
||||
t.isFalsyExpression = function (node) {
|
||||
if (t.isLiteral(node)) {
|
||||
return !node.value;
|
||||
} else if (t.isIdentifier(node)) {
|
||||
return node.name === "undefined";
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Turn an array of statement `nodes` into a `SequenceExpression`.
|
||||
*
|
||||
* Variable declarations are turned into simple assignments and their
|
||||
* declarations hoisted to the top of the current scope.
|
||||
*
|
||||
* Expression statements are just resolved to their standard expression.
|
||||
*
|
||||
* @param {Array} nodes
|
||||
* @param {Scope} scope
|
||||
*/
|
||||
|
||||
t.toSequenceExpression = function (nodes, scope) {
|
||||
var exprs = [];
|
||||
|
||||
each(nodes, function (node) {
|
||||
if (t.isExpression(node)) {
|
||||
exprs.push(node);
|
||||
} if (t.isExpressionStatement(node)) {
|
||||
exprs.push(node.expression);
|
||||
} else if (t.isVariableDeclaration(node)) {
|
||||
each(node.declarations, function (declar) {
|
||||
scope.push({
|
||||
kind: node.kind,
|
||||
key: declar.id.name,
|
||||
id: declar.id
|
||||
});
|
||||
exprs.push(t.assignmentExpression("=", declar.id, declar.init));
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
if (exprs.length === 1) {
|
||||
return exprs[0];
|
||||
} else {
|
||||
return t.sequenceExpression(exprs);
|
||||
}
|
||||
};
|
||||
|
||||
/*
|
||||
* Description
|
||||
*
|
||||
* @param {Object} actual
|
||||
* @param {Object} expected
|
||||
* @returns {Boolean}
|
||||
*/
|
||||
|
||||
t.shallowEqual = function (actual, expected) {
|
||||
var keys = Object.keys(expected);
|
||||
|
||||
for (var i = 0; i < keys.length; i++) {
|
||||
var key = keys[i];
|
||||
|
||||
if (actual[key] !== expected[key]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {Object} member
|
||||
* @param {Object} append
|
||||
* @param {Boolean} [computed]
|
||||
* @returns {Object} member
|
||||
*/
|
||||
|
||||
t.appendToMemberExpression = function (member, append, computed) {
|
||||
member.object = t.memberExpression(member.object, member.property, member.computed);
|
||||
member.property = append;
|
||||
member.computed = !!computed;
|
||||
return member;
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {Object} member
|
||||
* @param {Object} append
|
||||
* @returns {Object} member
|
||||
*/
|
||||
|
||||
t.prependToMemberExpression = function (member, append) {
|
||||
member.object = t.memberExpression(append, member.object);
|
||||
return member;
|
||||
};
|
||||
|
||||
/**
|
||||
* Check if the input `node` is a reference to a bound variable.
|
||||
*
|
||||
* @param {Object} node
|
||||
* @param {Object} parent
|
||||
* @returns {Boolean}
|
||||
*/
|
||||
|
||||
t.isReferenced = function (node, parent) {
|
||||
// yes: PARENT[NODE]
|
||||
// yes: NODE.child
|
||||
// no: parent.CHILD
|
||||
if (t.isMemberExpression(parent)) {
|
||||
if (parent.property === node && parent.computed) {
|
||||
return true;
|
||||
} else if (parent.object === node) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// yes: { [NODE]: "" }
|
||||
// no: { NODE: "" }
|
||||
if (t.isProperty(parent) && parent.key === node) {
|
||||
return parent.computed;
|
||||
}
|
||||
|
||||
// no: var NODE = init;
|
||||
// yes: var id = NODE;
|
||||
if (t.isVariableDeclarator(parent)) {
|
||||
return parent.id !== node;
|
||||
}
|
||||
|
||||
// no: function NODE() {}
|
||||
// no: function foo(NODE) {}
|
||||
if (t.isFunction(parent)) {
|
||||
for (var i = 0; i < parent.params.length; i++) {
|
||||
var param = parent.params[i];
|
||||
if (param === node) return false;
|
||||
}
|
||||
|
||||
return parent.id !== node;
|
||||
}
|
||||
|
||||
// no: class NODE {}
|
||||
if (t.isClass(parent)) {
|
||||
return parent.id !== node;
|
||||
}
|
||||
|
||||
// yes: class { [NODE](){} }
|
||||
if (t.isMethodDefinition(parent)) {
|
||||
return parent.key === node && parent.computed;
|
||||
}
|
||||
|
||||
// no: NODE: for (;;) {}
|
||||
if (t.isLabeledStatement(parent)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// no: try {} catch (NODE) {}
|
||||
if (t.isCatchClause(parent)) {
|
||||
return parent.param !== node;
|
||||
}
|
||||
|
||||
// no: function foo(...NODE) {}
|
||||
if (t.isRestElement(parent)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// no: [NODE = foo] = [];
|
||||
// yes: [foo = NODE] = [];
|
||||
if (t.isAssignmentPattern(parent)) {
|
||||
return parent.right === node;
|
||||
}
|
||||
|
||||
// no: [NODE] = [];
|
||||
// no: ({ NODE }) = [];
|
||||
if (t.isPattern(parent)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// no: import NODE from "bar";
|
||||
if (t.isImportSpecifier(parent)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// no: import * as NODE from "foo";
|
||||
if (t.isImportBatchSpecifier(parent)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// no: class Foo { private NODE; }
|
||||
if (t.isPrivateDeclaration(parent)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* Check if the input `node` is an `Identifier` and `isReferenced`.
|
||||
*
|
||||
* @param {Node} node
|
||||
* @parma {Node} parent
|
||||
* @returns {Boolean}
|
||||
*/
|
||||
|
||||
t.isReferencedIdentifier = function (node, parent, opts) {
|
||||
return t.isIdentifier(node, opts) && t.isReferenced(node, parent);
|
||||
};
|
||||
|
||||
/**
|
||||
* Check if the input `name` is a valid identifier name
|
||||
* and isn't a reserved word.
|
||||
*
|
||||
* @param {String} name
|
||||
* @returns {Boolean}
|
||||
*/
|
||||
|
||||
t.isValidIdentifier = function (name) {
|
||||
return isString(name) && esutils.keyword.isIdentifierName(name) && !esutils.keyword.isReservedWordES6(name, true);
|
||||
};
|
||||
|
||||
/*
|
||||
* Description
|
||||
*
|
||||
* @param {String} name
|
||||
* @returns {String}
|
||||
*/
|
||||
|
||||
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, "-");
|
||||
|
||||
// remove all dashes and numbers from start of name
|
||||
name = name.replace(/^[-0-9]+/, "");
|
||||
|
||||
// camel case
|
||||
name = name.replace(/[-\s]+(.)?/g, function (match, c) {
|
||||
return c ? c.toUpperCase() : "";
|
||||
});
|
||||
|
||||
if (!t.isValidIdentifier(name)) {
|
||||
name = "_" + name;
|
||||
}
|
||||
|
||||
return name || "_";
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {Object} node
|
||||
* @param {String=} key
|
||||
*/
|
||||
|
||||
t.ensureBlock = function (node, key) {
|
||||
key = key || "body";
|
||||
return node[key] = t.toBlock(node[key], node);
|
||||
};
|
||||
|
||||
/**
|
||||
* Build a function that when called will return whether or not the
|
||||
* input `node` `MemberExpression` matches the input `match`.
|
||||
*
|
||||
* For example, given the match `React.createClass` it would match the
|
||||
* parsed nodes of `React.createClass` and `React["createClass"]`.
|
||||
*
|
||||
* @param {String} match Dot-delimited string
|
||||
* @param {Boolean} [allowPartial] Allow a partial match
|
||||
* @returns {Function}
|
||||
*/
|
||||
|
||||
t.buildMatchMemberExpression = function (match, allowPartial) {
|
||||
var parts = match.split(".");
|
||||
|
||||
return function (member) {
|
||||
// not a member expression
|
||||
if (!t.isMemberExpression(member)) return false;
|
||||
|
||||
var search = [member];
|
||||
var i = 0;
|
||||
|
||||
while (search.length) {
|
||||
var node = search.shift();
|
||||
|
||||
if (allowPartial && i === parts.length) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (t.isIdentifier(node)) {
|
||||
// this part doesn't match
|
||||
if (parts[i] !== node.name) return false;
|
||||
} else if (t.isLiteral(node)) {
|
||||
// this part doesn't match
|
||||
if (parts[i] !== node.value) return false;
|
||||
} else if (t.isMemberExpression(node)) {
|
||||
if (node.computed && !t.isLiteral(node.property)) {
|
||||
// we can't deal with this
|
||||
return false;
|
||||
} else {
|
||||
search.push(node.object);
|
||||
search.push(node.property);
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
// we can't deal with this
|
||||
return false;
|
||||
}
|
||||
|
||||
// too many parts
|
||||
if (++i > parts.length) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {Object} node
|
||||
* @param {Boolean} [ignore]
|
||||
* @returns {Object|Boolean}
|
||||
*/
|
||||
|
||||
t.toStatement = function (node, ignore) {
|
||||
if (t.isStatement(node)) {
|
||||
return node;
|
||||
}
|
||||
|
||||
var mustHaveId = false;
|
||||
var newType;
|
||||
|
||||
if (t.isClass(node)) {
|
||||
mustHaveId = true;
|
||||
newType = "ClassDeclaration";
|
||||
} else if (t.isFunction(node)) {
|
||||
mustHaveId = true;
|
||||
newType = "FunctionDeclaration";
|
||||
} else if (t.isAssignmentExpression(node)) {
|
||||
return t.expressionStatement(node);
|
||||
}
|
||||
|
||||
if (mustHaveId && !node.id) {
|
||||
newType = false;
|
||||
}
|
||||
|
||||
if (!newType) {
|
||||
if (ignore) {
|
||||
return false;
|
||||
} else {
|
||||
throw new Error("cannot turn " + node.type + " to a statement");
|
||||
}
|
||||
}
|
||||
|
||||
node.type = newType;
|
||||
|
||||
return node;
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {Object} node
|
||||
* @returns {Object}
|
||||
*/
|
||||
|
||||
exports.toExpression = function (node) {
|
||||
if (t.isExpressionStatement(node)) {
|
||||
node = node.expression;
|
||||
}
|
||||
|
||||
if (t.isClass(node)) {
|
||||
node.type = "ClassExpression";
|
||||
} else if (t.isFunction(node)) {
|
||||
node.type = "FunctionExpression";
|
||||
}
|
||||
|
||||
if (t.isExpression(node)) {
|
||||
return node;
|
||||
} else {
|
||||
throw new Error("cannot turn " + node.type + " to an expression");
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {Object} node
|
||||
* @param {Object} parent
|
||||
* @returns {Object}
|
||||
*/
|
||||
|
||||
t.toBlock = function (node, parent) {
|
||||
if (t.isBlockStatement(node)) {
|
||||
return node;
|
||||
}
|
||||
|
||||
if (t.isEmptyStatement(node)) {
|
||||
node = [];
|
||||
}
|
||||
|
||||
if (!Array.isArray(node)) {
|
||||
if (!t.isStatement(node)) {
|
||||
if (t.isFunction(parent)) {
|
||||
node = t.returnStatement(node);
|
||||
} else {
|
||||
node = t.expressionStatement(node);
|
||||
}
|
||||
}
|
||||
|
||||
node = [node];
|
||||
}
|
||||
|
||||
return t.blockStatement(node);
|
||||
};
|
||||
|
||||
/**
|
||||
* Return a list of binding identifiers associated with
|
||||
* the input `node`.
|
||||
*
|
||||
* @param {Object} node
|
||||
* @returns {Array|Object}
|
||||
*/
|
||||
|
||||
t.getBindingIdentifiers = function (node) {
|
||||
var search = [].concat(node);
|
||||
var ids = object();
|
||||
|
||||
while (search.length) {
|
||||
var id = search.shift();
|
||||
if (!id) continue;
|
||||
|
||||
var keys = t.getBindingIdentifiers.keys[id.type];
|
||||
|
||||
if (t.isIdentifier(id)) {
|
||||
ids[id.name] = id;
|
||||
} else if (t.isImportSpecifier(id)) {
|
||||
search.push(id.name || id.id);
|
||||
} else if (t.isExportDeclaration(id)) {
|
||||
if (t.isDeclaration(node.declaration)) {
|
||||
search.push(node.declaration);
|
||||
}
|
||||
} else if (keys) {
|
||||
for (var i = 0; i < keys.length; i++) {
|
||||
var key = keys[i];
|
||||
search = search.concat(id[key] || []);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ids;
|
||||
};
|
||||
|
||||
t.getBindingIdentifiers.keys = {
|
||||
UnaryExpression: ["argument"],
|
||||
AssignmentExpression: ["left"],
|
||||
ImportBatchSpecifier: ["name"],
|
||||
VariableDeclarator: ["id"],
|
||||
FunctionDeclaration: ["id"],
|
||||
ClassDeclaration: ["id"],
|
||||
SpreadElement: ["argument"],
|
||||
RestElement: ["argument"],
|
||||
UpdateExpression: ["argument"],
|
||||
SpreadProperty: ["argument"],
|
||||
Property: ["value"],
|
||||
ComprehensionBlock: ["left"],
|
||||
AssignmentPattern: ["left"],
|
||||
PrivateDeclaration: ["declarations"],
|
||||
ComprehensionExpression: ["blocks"],
|
||||
ImportDeclaration: ["specifiers"],
|
||||
VariableDeclaration: ["declarations"],
|
||||
ArrayPattern: ["elements"],
|
||||
ObjectPattern: ["properties"]
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {Object} node
|
||||
* @returns {Boolean}
|
||||
*/
|
||||
|
||||
t.isLet = function (node) {
|
||||
return t.isVariableDeclaration(node) && (node.kind !== "var" || node._let);
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {Object} node
|
||||
* @returns {Boolean}
|
||||
*/
|
||||
|
||||
t.isBlockScoped = function (node) {
|
||||
return t.isFunctionDeclaration(node) || t.isClassDeclaration(node) || t.isLet(node);
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {Object} node
|
||||
* @returns {Boolean}
|
||||
*/
|
||||
|
||||
t.isVar = function (node) {
|
||||
return t.isVariableDeclaration(node, { kind: "var" }) && !node._let;
|
||||
};
|
||||
|
||||
//
|
||||
|
||||
t.COMMENT_KEYS = ["leadingComments", "trailingComments"];
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {Object} child
|
||||
* @returns {Object} child
|
||||
*/
|
||||
|
||||
t.removeComments = function (child) {
|
||||
each(t.COMMENT_KEYS, function (key) {
|
||||
delete child[key];
|
||||
});
|
||||
return child;
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {Object} child
|
||||
* @param {Object} parent
|
||||
* @returns {Object} child
|
||||
*/
|
||||
|
||||
t.inheritsComments = function (child, parent) {
|
||||
each(t.COMMENT_KEYS, function (key) {
|
||||
child[key] = uniq(compact([].concat(child[key], parent[key])));
|
||||
});
|
||||
return child;
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {Object} child
|
||||
* @param {Object} parent
|
||||
* @returns {Object} child
|
||||
*/
|
||||
|
||||
t.inherits = function (child, parent) {
|
||||
child._declarations = parent._declarations;
|
||||
child._scopeInfo = parent._scopeInfo;
|
||||
child.range = parent.range;
|
||||
child.start = parent.start;
|
||||
child.loc = parent.loc;
|
||||
child.end = parent.end;
|
||||
t.inheritsComments(child, parent);
|
||||
return child;
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {Object} node
|
||||
* @returns {Array}
|
||||
*/
|
||||
|
||||
t.getLastStatements = function (node) {
|
||||
var nodes = [];
|
||||
|
||||
var add = function (node) {
|
||||
nodes = nodes.concat(t.getLastStatements(node));
|
||||
};
|
||||
|
||||
if (t.isIfStatement(node)) {
|
||||
add(node.consequent);
|
||||
add(node.alternate);
|
||||
} else if (t.isFor(node) || t.isWhile(node)) {
|
||||
add(node.body);
|
||||
} else if (t.isProgram(node) || t.isBlockStatement(node)) {
|
||||
add(node.body[node.body.length - 1]);
|
||||
} else if (node) {
|
||||
nodes.push(node);
|
||||
}
|
||||
|
||||
return nodes;
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {Object} specifier
|
||||
* @returns {String}
|
||||
*/
|
||||
|
||||
t.getSpecifierName = function (specifier) {
|
||||
return specifier.name || specifier.id;
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {Object} specifier
|
||||
* @returns {String}
|
||||
*/
|
||||
|
||||
t.getSpecifierId = function (specifier) {
|
||||
if (specifier.default) {
|
||||
return t.identifier("default");
|
||||
} else {
|
||||
return specifier.id;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {Object} specifier
|
||||
* @returns {Boolean}
|
||||
*/
|
||||
|
||||
t.isSpecifierDefault = function (specifier) {
|
||||
return specifier.default || t.isIdentifier(specifier.id) && specifier.id.name === "default";
|
||||
};
|
||||
|
||||
/**
|
||||
* Description
|
||||
*
|
||||
* @param {Node} node
|
||||
* @param {Node} parent
|
||||
* @returns {Boolean}
|
||||
*/
|
||||
|
||||
t.isScope = function (node, parent) {
|
||||
if (t.isBlockStatement(node)) {
|
||||
if (t.isLoop(parent.block, { body: node })) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (t.isFunction(parent.block, { body: node })) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return t.isScopable(node);
|
||||
};
|
||||
|
||||
toFastProperties(t);
|
||||
toFastProperties(t.VISITOR_KEYS);
|
||||
@@ -1,137 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
require("./patch");
|
||||
|
||||
var cloneDeep = require("lodash/lang/cloneDeep");
|
||||
var contains = require("lodash/collection/contains");
|
||||
var traverse = require("./traversal");
|
||||
var isString = require("lodash/lang/isString");
|
||||
var isRegExp = require("lodash/lang/isRegExp");
|
||||
var isEmpty = require("lodash/lang/isEmpty");
|
||||
var parse = require("./helpers/parse");
|
||||
var debug = require("debug/node");
|
||||
var path = require("path");
|
||||
var util = require("util");
|
||||
var each = require("lodash/collection/each");
|
||||
var has = require("lodash/object/has");
|
||||
var fs = require("fs");
|
||||
var t = require("./types");
|
||||
|
||||
exports.inherits = util.inherits;
|
||||
|
||||
exports.debug = debug("babel");
|
||||
|
||||
exports.canCompile = function (filename, altExts) {
|
||||
var exts = altExts || exports.canCompile.EXTENSIONS;
|
||||
var ext = path.extname(filename);
|
||||
return contains(exts, ext);
|
||||
};
|
||||
|
||||
exports.canCompile.EXTENSIONS = [".js", ".jsx", ".es6", ".es"];
|
||||
|
||||
exports.resolve = function (loc) {
|
||||
try {
|
||||
return require.resolve(loc);
|
||||
} catch (err) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
exports.list = function (val) {
|
||||
return val ? val.split(",") : [];
|
||||
};
|
||||
|
||||
exports.regexify = function (val) {
|
||||
if (!val) return new RegExp(/.^/);
|
||||
if (Array.isArray(val)) val = val.join("|");
|
||||
if (isString(val)) return new RegExp(val);
|
||||
if (isRegExp(val)) return val;
|
||||
throw new TypeError("illegal type for regexify");
|
||||
};
|
||||
|
||||
exports.arrayify = function (val) {
|
||||
if (!val) return [];
|
||||
if (isString(val)) return exports.list(val);
|
||||
if (Array.isArray(val)) return val;
|
||||
throw new TypeError("illegal type for arrayify");
|
||||
};
|
||||
|
||||
exports.booleanify = function (val) {
|
||||
if (val === "true") return true;
|
||||
if (val === "false") return false;
|
||||
return val;
|
||||
};
|
||||
|
||||
var templateVisitor = {
|
||||
enter: function (node, parent, scope, nodes) {
|
||||
if (t.isExpressionStatement(node)) {
|
||||
node = node.expression;
|
||||
}
|
||||
if (t.isIdentifier(node) && has(nodes, node.name)) {
|
||||
this.skip();
|
||||
return nodes[node.name];
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
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);
|
||||
|
||||
if (!isEmpty(nodes)) {
|
||||
traverse(template, templateVisitor, null, nodes);
|
||||
}
|
||||
|
||||
if (template.body.length > 1) return template.body;
|
||||
|
||||
var node = template.body[0];
|
||||
|
||||
if (!keepExpression && t.isExpressionStatement(node)) {
|
||||
return node.expression;
|
||||
} else {
|
||||
return node;
|
||||
}
|
||||
};
|
||||
|
||||
exports.parseTemplate = function (loc, code) {
|
||||
var ast = parse({ filename: loc }, code).program;
|
||||
return traverse.removeProperties(ast);
|
||||
};
|
||||
|
||||
var loadTemplates = function () {
|
||||
var templates = {};
|
||||
|
||||
var templatesLoc = __dirname + "/transformation/templates";
|
||||
if (!fs.existsSync(templatesLoc)) {
|
||||
throw new Error("no templates directory - this is most likely the " +
|
||||
"result of a broken `npm publish`. Please report to " +
|
||||
"https://github.com/babel/babel/issues");
|
||||
}
|
||||
|
||||
each(fs.readdirSync(templatesLoc), function (name) {
|
||||
if (name[0] === ".") return;
|
||||
|
||||
var key = path.basename(name, path.extname(name));
|
||||
var loc = templatesLoc + "/" + name;
|
||||
var code = fs.readFileSync(loc, "utf8");
|
||||
|
||||
templates[key] = exports.parseTemplate(loc, code);
|
||||
});
|
||||
|
||||
return templates;
|
||||
};
|
||||
|
||||
try {
|
||||
exports.templates = require("../../templates.json");
|
||||
} catch (err) {
|
||||
if (err.code !== "MODULE_NOT_FOUND") throw err;
|
||||
|
||||
exports.templates = loadTemplates();
|
||||
}
|
||||
30
package.json
30
package.json
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "babel",
|
||||
"description": "Turn ES6 code into readable vanilla ES5 with source maps",
|
||||
"version": "4.4.0",
|
||||
"version": "4.7.6",
|
||||
"author": "Sebastian McKenzie <sebmck@gmail.com>",
|
||||
"homepage": "https://babeljs.io/",
|
||||
"repository": "babel/babel",
|
||||
@@ -36,12 +36,13 @@
|
||||
"test": "make test"
|
||||
},
|
||||
"dependencies": {
|
||||
"acorn-babel": "0.11.1-33",
|
||||
"ast-types": "~0.6.1",
|
||||
"chalk": "^0.5.1",
|
||||
"acorn-babel": "0.11.1-37",
|
||||
"ast-types": "~0.7.0",
|
||||
"chalk": "^1.0.0",
|
||||
"chokidar": "^0.12.6",
|
||||
"commander": "^2.6.0",
|
||||
"core-js": "^0.5.4",
|
||||
"convert-source-map": "^0.5.0",
|
||||
"core-js": "^0.6.1",
|
||||
"debug": "^2.1.1",
|
||||
"detect-indent": "^3.0.0",
|
||||
"estraverse": "^1.9.1",
|
||||
@@ -49,30 +50,31 @@
|
||||
"fs-readdir-recursive": "^0.1.0",
|
||||
"globals": "^6.2.0",
|
||||
"is-integer": "^1.0.4",
|
||||
"js-tokenizer": "^1.3.3",
|
||||
"js-tokens": "1.0.0",
|
||||
"leven": "^1.0.1",
|
||||
"line-numbers": "0.2.0",
|
||||
"lodash": "^3.2.0",
|
||||
"output-file-sync": "^1.1.0",
|
||||
"path-is-absolute": "^1.0.0",
|
||||
"private": "^0.1.6",
|
||||
"regenerator-babel": "0.8.10-2",
|
||||
"regexpu": "^1.1.1",
|
||||
"regenerator-babel": "0.8.13-2",
|
||||
"regexpu": "^1.1.2",
|
||||
"repeating": "^1.1.2",
|
||||
"shebang-regex": "^1.0.0",
|
||||
"slash": "^1.0.0",
|
||||
"source-map": "^0.1.43",
|
||||
"source-map": "^0.4.0",
|
||||
"source-map-support": "^0.2.9",
|
||||
"source-map-to-comment": "^1.0.0",
|
||||
"to-fast-properties": "^1.0.0",
|
||||
"trim-right": "^1.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"browserify": "^8.1.3",
|
||||
"babel": "4.6.0",
|
||||
"browserify": "^9.0.3",
|
||||
"chai": "^2.0.0",
|
||||
"eslint": "^0.15.1",
|
||||
"babel-eslint": "^1.0.1",
|
||||
"esvalid": "^1.1.0",
|
||||
"istanbul": "^0.3.5",
|
||||
"jscs": "^1.11.3",
|
||||
"jshint": "^2.6.0",
|
||||
"jshint-stylish": "^1.0.0",
|
||||
"matcha": "^0.6.0",
|
||||
"mocha": "^2.1.0",
|
||||
"rimraf": "^2.2.8",
|
||||
|
||||
0
packages/babel-runtime/helpers/.gitkeep
Normal file
0
packages/babel-runtime/helpers/.gitkeep
Normal file
@@ -1,7 +1,10 @@
|
||||
{
|
||||
"name": "babel-runtime",
|
||||
"description": "babel selfContained runtime",
|
||||
"version": "4.3.0",
|
||||
"version": "4.7.5",
|
||||
"repository": "babel/babel",
|
||||
"author": "Sebastian McKenzie <sebmck@gmail.com>"
|
||||
"author": "Sebastian McKenzie <sebmck@gmail.com>",
|
||||
"dependencies": {
|
||||
"core-js": "^0.6.1"
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
"use strict";
|
||||
|
||||
var buildHelpers = require("../lib/babel/build-helpers");
|
||||
var transform = require("../lib/babel/transformation");
|
||||
var util = require("../lib/babel/util");
|
||||
var fs = require("fs");
|
||||
var t = require("../lib/babel/types");
|
||||
var _ = require("lodash");
|
||||
var transform = require("../lib/babel/transformation");
|
||||
var each = require("lodash/collection/each");
|
||||
var File = require("../lib/babel/transformation/file");
|
||||
var util = require("../lib/babel/util");
|
||||
var fs = require("fs");
|
||||
var t = require("../lib/babel/types");
|
||||
var _ = require("lodash");
|
||||
|
||||
var relative = function (filename) {
|
||||
return __dirname + "/babel-runtime/" + filename;
|
||||
@@ -39,22 +40,26 @@ var updatePackage = function () {
|
||||
|
||||
var selfContainify = function (code) {
|
||||
return transform(code, {
|
||||
optional: ["selfContained"]
|
||||
optional: ["runtime"]
|
||||
}).code;
|
||||
};
|
||||
|
||||
var buildHelpers2 = function () {
|
||||
var body = util.template("self-contained-helpers-head");
|
||||
var tree = t.program(body);
|
||||
|
||||
buildHelpers(body, t.identifier("helpers"));
|
||||
var buildHelper = function (helperName) {
|
||||
var tree = t.program(
|
||||
util.template("self-contained-helpers-head", {
|
||||
HELPER: util.template(helperName)
|
||||
})
|
||||
);
|
||||
|
||||
return transform.fromAst(tree, null, {
|
||||
optional: ["selfContained"]
|
||||
optional: ["runtime"]
|
||||
}).code;
|
||||
};
|
||||
|
||||
writeFile("helpers.js", buildHelpers2());
|
||||
each(File.helpers, function (helperName) {
|
||||
writeFile("helpers/" + helperName + ".js", buildHelper(helperName));
|
||||
});
|
||||
|
||||
writeFile("core-js.js", readFile("core-js/library", true));
|
||||
writeFile("regenerator/index.js", readFile("regenerator-babel/runtime-module", true));
|
||||
writeFile("regenerator/runtime.js", selfContainify(readFile("regenerator-babel/runtime")));
|
||||
|
||||
@@ -1,20 +1,16 @@
|
||||
"use strict";
|
||||
|
||||
var transform = module.exports = require("../transformation");
|
||||
|
||||
transform.version = require("../../../package").version;
|
||||
|
||||
transform.transform = transform;
|
||||
|
||||
transform.run = function (code, opts) {
|
||||
opts = opts || {};
|
||||
transform.run = function (code, opts = {}) {
|
||||
opts.sourceMap = "inline";
|
||||
return new Function(transform(code, opts).code)();
|
||||
};
|
||||
|
||||
transform.load = function (url, callback, opts, hold) {
|
||||
opts = opts || {};
|
||||
opts.filename = opts.filename || url;
|
||||
transform.load = function (url, callback, opts = {}, hold) {
|
||||
opts.filename ||= url;
|
||||
|
||||
var xhr = global.ActiveXObject ? new global.ActiveXObject("Microsoft.XMLHTTP") : new global.XMLHttpRequest();
|
||||
xhr.open("GET", url, true);
|
||||
@@ -29,7 +25,7 @@ transform.load = function (url, callback, opts, hold) {
|
||||
if (!hold) transform.run.apply(transform, param);
|
||||
if (callback) callback(param);
|
||||
} else {
|
||||
throw new Error("Could not load " + url);
|
||||
throw new Error(`Could not load ${url}`);
|
||||
}
|
||||
};
|
||||
|
||||
52
src/babel/api/node.js
Normal file
52
src/babel/api/node.js
Normal file
@@ -0,0 +1,52 @@
|
||||
import isFunction from "lodash/lang/isFunction";
|
||||
import transform from "../transformation";
|
||||
import fs from "fs";
|
||||
|
||||
import * as util from "../util";
|
||||
export { util as _util };
|
||||
export { canCompile } from "../util";
|
||||
|
||||
export { default as acorn } from "acorn-babel";
|
||||
export { default as transform } from "../transformation";
|
||||
export { default as traverse } from "../traversal";
|
||||
export { default as buildExternalHelpers } from "../tools/build-external-helpers";
|
||||
export { default as types } from "../types";
|
||||
export { version } from "../../../package";
|
||||
|
||||
export function register(opts) {
|
||||
var callback = require("./register/node");
|
||||
if (opts != null) callback(opts);
|
||||
return callback;
|
||||
}
|
||||
|
||||
export function polyfill() {
|
||||
require("../polyfill");
|
||||
}
|
||||
|
||||
export function transformFile(filename, opts, callback) {
|
||||
if (isFunction(opts)) {
|
||||
callback = opts;
|
||||
opts = {};
|
||||
}
|
||||
|
||||
opts.filename = filename;
|
||||
|
||||
fs.readFile(filename, function (err, code) {
|
||||
if (err) return callback(err);
|
||||
|
||||
var result;
|
||||
|
||||
try {
|
||||
result = transform(code, opts);
|
||||
} catch (err) {
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
callback(null, result);
|
||||
});
|
||||
}
|
||||
|
||||
export function transformFileSync(filename, opts = {}) {
|
||||
opts.filename = filename;
|
||||
return transform(fs.readFileSync(filename), opts);
|
||||
}
|
||||
5
src/babel/api/register/browser.js
Normal file
5
src/babel/api/register/browser.js
Normal file
@@ -0,0 +1,5 @@
|
||||
// required to safely use babel/register within a browserify codebase
|
||||
|
||||
export default function () {};
|
||||
|
||||
import "../../polyfill";
|
||||
@@ -1,24 +1,22 @@
|
||||
"use strict";
|
||||
|
||||
var path = require("path");
|
||||
var os = require("os");
|
||||
var fs = require("fs");
|
||||
import path from "path";
|
||||
import os from "os";
|
||||
import fs from "fs";
|
||||
|
||||
var FILENAME = process.env.BABEL_CACHE_PATH || path.join(os.tmpdir(), "babel.json");
|
||||
var data = {};
|
||||
|
||||
exports.save = function () {
|
||||
export function save() {
|
||||
fs.writeFileSync(FILENAME, JSON.stringify(data, null, " "));
|
||||
};
|
||||
}
|
||||
|
||||
exports.load = function () {
|
||||
export function load() {
|
||||
if (process.env.BABEL_DISABLE_CACHE) return;
|
||||
|
||||
process.on("exit", exports.save);
|
||||
process.on("exit", save);
|
||||
|
||||
var sigint = function () {
|
||||
process.removeListener("SIGINT", sigint);
|
||||
exports.save();
|
||||
save();
|
||||
process.kill(process.pid, "SIGINT");
|
||||
};
|
||||
|
||||
@@ -31,8 +29,8 @@ exports.load = function () {
|
||||
} catch (err) {
|
||||
return;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
exports.get = function () {
|
||||
export function get() {
|
||||
return data;
|
||||
};
|
||||
}
|
||||
@@ -1,17 +1,16 @@
|
||||
"use strict";
|
||||
|
||||
require("../../polyfill");
|
||||
|
||||
var sourceMapSupport = require("source-map-support");
|
||||
var registerCache = require("./cache");
|
||||
var extend = require("lodash/object/extend");
|
||||
var babel = require("../node");
|
||||
var each = require("lodash/collection/each");
|
||||
var util = require("../../util");
|
||||
var fs = require("fs");
|
||||
import "../../polyfill";
|
||||
import sourceMapSupport from "source-map-support";
|
||||
import * as registerCache from "./cache";
|
||||
import resolveRc from "./resolve-rc";
|
||||
import extend from "lodash/object/extend";
|
||||
import * as babel from "../node";
|
||||
import each from "lodash/collection/each";
|
||||
import * as util from "../../util";
|
||||
import fs from "fs";
|
||||
|
||||
sourceMapSupport.install({
|
||||
retrieveSourceMap: function (source) {
|
||||
handleUncaughtExceptions: false,
|
||||
retrieveSourceMap(source) {
|
||||
var map = maps && maps[source];
|
||||
if (map) {
|
||||
return {
|
||||
@@ -34,7 +33,7 @@ var cache = registerCache.get();
|
||||
var transformOpts = {};
|
||||
var ignoreRegex = /node_modules/;
|
||||
var onlyRegex;
|
||||
var exts = {};
|
||||
var oldHandlers = {};
|
||||
var maps = {};
|
||||
|
||||
var mtime = function (filename) {
|
||||
@@ -44,7 +43,10 @@ var mtime = function (filename) {
|
||||
var compile = function (filename) {
|
||||
var result;
|
||||
|
||||
var cacheKey = filename + ":" + JSON.stringify(transformOpts);
|
||||
var opts = extend({}, transformOpts);
|
||||
resolveRc(filename, opts);
|
||||
|
||||
var cacheKey = `${filename}:${JSON.stringify(opts)}:${babel.version}`;
|
||||
|
||||
if (cache) {
|
||||
var cached = cache[cacheKey];
|
||||
@@ -54,10 +56,10 @@ var compile = function (filename) {
|
||||
}
|
||||
|
||||
if (!result) {
|
||||
result = babel.transformFileSync(filename, extend({
|
||||
sourceMap: true,
|
||||
result = babel.transformFileSync(filename, extend(opts, {
|
||||
sourceMap: "both",
|
||||
ast: false
|
||||
}, transformOpts));
|
||||
}));
|
||||
}
|
||||
|
||||
if (cache) {
|
||||
@@ -103,7 +105,7 @@ var normalLoader = function (m, filename) {
|
||||
};
|
||||
|
||||
var registerExtension = function (ext) {
|
||||
var old = require.extensions[ext];
|
||||
var old = oldHandlers[ext] || oldHandlers[".js"];
|
||||
|
||||
var loader = normalLoader;
|
||||
if (process.env.running_under_istanbul) loader = istanbulLoader; // jshint ignore:line
|
||||
@@ -118,24 +120,25 @@ var registerExtension = function (ext) {
|
||||
};
|
||||
|
||||
var hookExtensions = function (_exts) {
|
||||
each(exts, function (old, ext) {
|
||||
require.extensions[ext] = old;
|
||||
each(oldHandlers, function (old, ext) {
|
||||
if (old === undefined) {
|
||||
delete require.extensions[ext];
|
||||
} else {
|
||||
require.extensions[ext] = old;
|
||||
}
|
||||
});
|
||||
|
||||
exts = {};
|
||||
oldHandlers = {};
|
||||
|
||||
each(_exts, function (ext) {
|
||||
exts[ext] = require.extensions[ext];
|
||||
oldHandlers[ext] = require.extensions[ext];
|
||||
registerExtension(ext);
|
||||
});
|
||||
};
|
||||
|
||||
hookExtensions(util.canCompile.EXTENSIONS);
|
||||
|
||||
module.exports = function (opts) {
|
||||
// normalize options
|
||||
opts = opts || {};
|
||||
|
||||
export default function (opts = {}) {
|
||||
if (opts.only != null) onlyRegex = util.regexify(opts.only);
|
||||
if (opts.ignore != null) ignoreRegex = util.regexify(opts.ignore);
|
||||
|
||||
@@ -150,3 +153,16 @@ module.exports = function (opts) {
|
||||
|
||||
extend(transformOpts, opts);
|
||||
};
|
||||
|
||||
//
|
||||
|
||||
try {
|
||||
var runtimePackage = require("babel-runtime/package");
|
||||
var version = require("../../package").version;
|
||||
if (runtimePackage.version !== version) {
|
||||
throw new ReferenceError(`The verison of babel-runtime of ${runtimePackage.runtime} that you have installed does not match the babel verison of ${version}`);
|
||||
}
|
||||
} catch (err) {
|
||||
if (err.code !== "MODULE_NOT_FOUND") throw err;
|
||||
}
|
||||
|
||||
47
src/babel/api/register/resolve-rc.js
Normal file
47
src/babel/api/register/resolve-rc.js
Normal file
@@ -0,0 +1,47 @@
|
||||
import merge from "lodash/object/merge";
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
|
||||
var cache = {};
|
||||
|
||||
function exists(filename) {
|
||||
var cached = cache[filename];
|
||||
if (cached != null) return cached;
|
||||
return cache[filename] = fs.existsSync(filename);
|
||||
}
|
||||
|
||||
export default function (loc, opts = {}) {
|
||||
var rel = ".babelrc";
|
||||
|
||||
function find(start, rel) {
|
||||
var file = path.join(start, rel);
|
||||
|
||||
if (exists(file)) {
|
||||
var content = fs.readFileSync(file, "utf8");
|
||||
var json;
|
||||
|
||||
try {
|
||||
json = JSON.parse(content);
|
||||
} catch (err) {
|
||||
err.message = `${file}: ${err.message}`;
|
||||
throw err;
|
||||
}
|
||||
|
||||
if (json.breakConfig) return;
|
||||
merge(opts, json, function(a, b) {
|
||||
if (Array.isArray(a)) {
|
||||
return a.concat(b);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
var up = path.dirname(start);
|
||||
if (up !== start) { // root
|
||||
find(up, rel);
|
||||
}
|
||||
}
|
||||
|
||||
find(loc, rel);
|
||||
|
||||
return opts;
|
||||
};
|
||||
173
src/babel/generation/buffer.js
Normal file
173
src/babel/generation/buffer.js
Normal file
@@ -0,0 +1,173 @@
|
||||
import repeating from "repeating";
|
||||
import trimRight from "trim-right";
|
||||
import isBoolean from "lodash/lang/isBoolean";
|
||||
import includes from "lodash/collection/includes";
|
||||
import isNumber from "lodash/lang/isNumber";
|
||||
|
||||
export default class Buffer {
|
||||
constructor(position, format) {
|
||||
this.position = position;
|
||||
this._indent = format.indent.base;
|
||||
this.format = format;
|
||||
this.buf = "";
|
||||
}
|
||||
|
||||
get() {
|
||||
return trimRight(this.buf);
|
||||
}
|
||||
|
||||
getIndent() {
|
||||
if (this.format.compact || this.format.concise) {
|
||||
return "";
|
||||
} else {
|
||||
return repeating(this.format.indent.style, this._indent);
|
||||
}
|
||||
}
|
||||
|
||||
indentSize() {
|
||||
return this.getIndent().length;
|
||||
}
|
||||
|
||||
indent() {
|
||||
this._indent++;
|
||||
}
|
||||
|
||||
dedent() {
|
||||
this._indent--;
|
||||
}
|
||||
|
||||
semicolon() {
|
||||
this.push(";");
|
||||
}
|
||||
|
||||
ensureSemicolon() {
|
||||
if (!this.isLast(";")) this.semicolon();
|
||||
}
|
||||
|
||||
rightBrace() {
|
||||
this.newline(true);
|
||||
this.push("}");
|
||||
}
|
||||
|
||||
keyword(name) {
|
||||
this.push(name);
|
||||
this.space();
|
||||
}
|
||||
|
||||
space() {
|
||||
if (this.format.compact) return;
|
||||
if (this.buf && !this.isLast(" ") && !this.isLast("\n")) {
|
||||
this.push(" ");
|
||||
}
|
||||
}
|
||||
|
||||
removeLast(cha) {
|
||||
if (this.format.compact) return;
|
||||
if (!this.isLast(cha)) return;
|
||||
|
||||
this.buf = this.buf.substr(0, this.buf.length - 1);
|
||||
this.position.unshift(cha);
|
||||
}
|
||||
|
||||
newline(i, removeLast) {
|
||||
if (this.format.compact) return;
|
||||
|
||||
if (this.format.concise) {
|
||||
this.space();
|
||||
return;
|
||||
}
|
||||
|
||||
removeLast ||= false;
|
||||
|
||||
if (isNumber(i)) {
|
||||
i = Math.min(2, i);
|
||||
|
||||
if (this.endsWith("{\n") || this.endsWith(":\n")) i--;
|
||||
if (i <= 0) return;
|
||||
|
||||
while (i > 0) {
|
||||
this._newline(removeLast);
|
||||
i--;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (isBoolean(i)) {
|
||||
removeLast = i;
|
||||
}
|
||||
|
||||
this._newline(removeLast);
|
||||
}
|
||||
|
||||
_newline(removeLast) {
|
||||
// never allow more than two lines
|
||||
if (this.endsWith("\n\n")) return;
|
||||
|
||||
// remove the last newline
|
||||
if (removeLast && this.isLast("\n")) this.removeLast("\n");
|
||||
|
||||
this.removeLast(" ");
|
||||
this._removeSpacesAfterLastNewline();
|
||||
this._push("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* If buffer ends with a newline and some spaces after it, trim those spaces.
|
||||
*/
|
||||
|
||||
_removeSpacesAfterLastNewline() {
|
||||
var lastNewlineIndex = this.buf.lastIndexOf("\n");
|
||||
if (lastNewlineIndex === -1)
|
||||
return;
|
||||
|
||||
var index = this.buf.length - 1;
|
||||
while (index > lastNewlineIndex) {
|
||||
if (this.buf[index] !== " ") {
|
||||
break;
|
||||
}
|
||||
|
||||
index--;
|
||||
}
|
||||
|
||||
if (index === lastNewlineIndex) {
|
||||
this.buf = this.buf.substring(0, index + 1);
|
||||
}
|
||||
}
|
||||
|
||||
push(str, noIndent) {
|
||||
if (!this.format.compact && 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")) this._push(indent);
|
||||
}
|
||||
|
||||
this._push(str);
|
||||
}
|
||||
|
||||
_push(str) {
|
||||
this.position.push(str);
|
||||
this.buf += str;
|
||||
}
|
||||
|
||||
endsWith(str) {
|
||||
return this.buf.slice(-str.length) === str;
|
||||
}
|
||||
|
||||
isLast(cha) {
|
||||
if (this.format.compact) return false;
|
||||
|
||||
var buf = this.buf;
|
||||
var last = buf[buf.length - 1];
|
||||
|
||||
if (Array.isArray(cha)) {
|
||||
return includes(cha, last);
|
||||
} else {
|
||||
return cha === last;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,12 @@
|
||||
"use strict";
|
||||
|
||||
exports.File = function (node, print) {
|
||||
export function File(node, print) {
|
||||
print(node.program);
|
||||
};
|
||||
}
|
||||
|
||||
exports.Program = function (node, print) {
|
||||
export function Program(node, print) {
|
||||
print.sequence(node.body);
|
||||
};
|
||||
}
|
||||
|
||||
exports.BlockStatement = function (node, print) {
|
||||
export function BlockStatement(node, print) {
|
||||
if (node.body.length === 0) {
|
||||
this.push("{}");
|
||||
} else {
|
||||
@@ -18,4 +16,4 @@ exports.BlockStatement = function (node, print) {
|
||||
this.removeLast("\n");
|
||||
this.rightBrace();
|
||||
}
|
||||
};
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user