Compare commits

...

437 Commits

Author SHA1 Message Date
Sebastian McKenzie
2053610429 v5.5.3 2015-06-05 12:20:22 +01:00
Sebastian McKenzie
cd4f83b299 fix linting errors 2015-06-05 12:19:32 +01:00
Sebastian McKenzie
ec29ba19a9 add 5.5.3 changelog 2015-06-05 12:18:43 +01:00
Sebastian McKenzie
9dc03e0978 traverse over ClassProperty path rather than node 2015-06-05 12:17:55 +01:00
Sebastian McKenzie
bc4258eca9 add type inferrence for template literals 2015-06-05 12:17:45 +01:00
Sebastian McKenzie
b0e58f9770 add completion statement test and enable experimental option on deadCodeElimination tests 2015-06-05 12:17:36 +01:00
Sebastian McKenzie
a1e2641c91 5.5.2 2015-06-05 12:17:18 +01:00
Sebastian McKenzie
9108422f99 v5.5.2 2015-06-05 12:03:38 +01:00
Sebastian McKenzie
9e8f4b25ca add missing semicolon 2015-06-05 12:02:30 +01:00
Sebastian McKenzie
1cecd24823 make experimental warning more scary 2015-06-05 12:01:52 +01:00
Sebastian McKenzie
97f6e1469b add 5.5.2 changelog 2015-06-05 12:01:44 +01:00
Sebastian McKenzie
ec46eaf224 add scary experimental warning for people who use obscure transformers that are still WIP 2015-06-05 11:55:09 +01:00
Sebastian McKenzie
a102692103 when using babel/register always use the cwd - fixes #1689 2015-06-05 11:54:52 +01:00
Sebastian McKenzie
0376ec8ff0 t.isPure -> this.isPure - fixes #1688 2015-06-05 11:33:25 +01:00
Sebastian McKenzie
5932a07610 5.5.1 2015-06-05 09:57:21 +01:00
Sebastian McKenzie
6110b0c0b3 v5.5.1 2015-06-05 09:56:27 +01:00
Sebastian McKenzie
365e221d95 fix deoptValue binding boolean - fixes #1687 2015-06-05 09:55:47 +01:00
Sebastian McKenzie
acbc4859c0 only remove ClassProperty in flow transformer when it has no value 2015-06-05 09:53:59 +01:00
Sebastian McKenzie
55750e05e7 Revert "enable es6.spec.symbols by default"
This reverts commit f3acedbf08.
2015-06-05 09:44:22 +01:00
Sebastian McKenzie
ba9c4db673 finish 5.5.1 changelog - ref #1686 2015-06-05 09:43:34 +01:00
Sebastian McKenzie
ba8a63a69e remove trailing json comma 2015-06-05 09:42:53 +01:00
Sebastian McKenzie
25581981b5 always remove ClassProperty nodes in flow transformer - fixes #1686 2015-06-05 09:42:46 +01:00
Sebastian McKenzie
02a6feed73 update template literal parsing to properly handle newlines 2015-06-05 09:36:37 +01:00
Sebastian McKenzie
f3acedbf08 enable es6.spec.symbols by default 2015-06-05 08:43:41 +01:00
Sebastian McKenzie
35ab4ffaab 5.5.0 2015-06-05 08:12:17 +01:00
Sebastian McKenzie
ddfb7f2c11 v5.5.0 2015-06-05 08:11:10 +01:00
Sebastian McKenzie
e2ca03f92d fix linting errors 2015-06-05 08:10:22 +01:00
Sebastian McKenzie
c75a3c68e5 add 5.5.0 changelog 2015-06-05 08:08:20 +01:00
Sebastian McKenzie
5d617ea99b upgrade regenerator - fixes #1685 2015-06-05 07:56:33 +01:00
Sebastian McKenzie
58059a2c48 add deoptValue method to Binding that ignores all subsequent setValue calls 2015-06-05 07:52:57 +01:00
Sebastian McKenzie
4c2936773a update type inferrence to support unary operators 2015-06-05 07:47:22 +01:00
Sebastian McKenzie
c7c16ad9c1 add control flow support and deopt bindings on assignments that we can't understand 2015-06-05 07:46:32 +01:00
Sebastian McKenzie
7b676d608b allow NodePaths to be returned in node removal/replacement methods and coerce them to nodes 2015-06-05 07:46:10 +01:00
Sebastian McKenzie
48ecec1e2e move more transformers to builtin-pre group 2015-06-05 07:45:32 +01:00
Sebastian McKenzie
9dc72e71d4 add skipKey method to skip traversal of subsequent keys 2015-06-05 07:45:19 +01:00
Sebastian McKenzie
4a7a02b9af rename builtin-setup transformer group to builtin-pre 2015-06-05 07:44:45 +01:00
Sebastian McKenzie
7cb460d2f3 add eval optional transformer 2015-06-05 07:44:29 +01:00
Sebastian McKenzie
0a7dac8744 move flow to builtin-trailing group 2015-06-05 07:44:15 +01:00
Sebastian McKenzie
667d595a73 use type inferrence to work out whether to wrap template literals with the String constructor 2015-06-05 07:43:58 +01:00
Sebastian McKenzie
2d2d957be5 add back ComprehensionBlock binding identifier keys and remove body form ComprehensionBlock visitor keys 2015-06-04 22:50:17 +01:00
Sebastian McKenzie
5aef7afade fix remaining AssignmentExpression LHS ReferencedIdentifier bugs 2015-06-04 22:43:50 +01:00
Sebastian McKenzie
d5e7b5616c Merge branch 'master' of github.com:babel/babel 2015-06-04 22:23:42 +01:00
Sebastian McKenzie
9aa17a6cc2 don't consider JSXIdentifier HTML tags to be references - fixes #1683 2015-06-04 22:23:24 +01:00
Sebastian McKenzie
0f13097f59 add basic naive constant folding of assignment expressions 2015-06-04 22:08:38 +01:00
Sebastian McKenzie
355ffbdaf8 don't consider the LHS of an AssignmentExpression to be a reference 2015-06-04 22:07:44 +01:00
Sebastian McKenzie
45b0d63d72 copy parent class binding to class in the collection visitor 2015-06-04 22:07:19 +01:00
Sebastian McKenzie
c515271fbd Merge pull request #1677 from jmm/node_modules-robust3
Complete "Fix flawed require hook node_modules check" properly
2015-06-03 19:23:41 +01:00
Jesse McCarthy
6f3501876a Add test for require-hook node_modules check. 2015-06-03 09:04:59 -04:00
Jesse McCarthy
f8afc5fa17 Revert "Add test for require-hook node_modules check."
This reverts commit 1488d88c81.

Wrong branch was accidentally merged. There is a better test.
2015-06-03 09:04:59 -04:00
Sebastian McKenzie
4ecda93147 move deprecated minification.inlineExpressions to aliases 2015-06-03 10:05:56 +01:00
Sebastian McKenzie
41847162b1 check if es7.exportExtensions ie enabled in parser 2015-06-03 10:05:39 +01:00
Sebastian McKenzie
0f7e010e3e remove isSpecifierDefault check for ExportDefaultSpecifier - fixes #1673 2015-06-03 10:05:19 +01:00
Sebastian McKenzie
8201ea0aa2 Merge branch 'master' of github.com:babel/babel
# Conflicts:
#	src/babel/api/register/node.js
2015-06-03 07:26:46 +01:00
Sebastian McKenzie
a7848c1822 Merge branch 'jmm-node_modules-robust' 2015-06-03 07:26:19 +01:00
Sebastian McKenzie
d4abaeeecf Merge branch 'node_modules-robust' of https://github.com/jmm/babel into jmm-node_modules-robust 2015-06-03 07:26:12 +01:00
Sebastian McKenzie
871a82df0a Merge pull request #1665 from Jabher/master
Making babel able to run in node_modules directory
2015-06-03 07:25:22 +01:00
Sebastian McKenzie
ffbf5b0b47 convert property key to computed before checking if it's a displayName property in the react transformer builder - closes #1671 2015-06-02 23:08:46 +01:00
Sebastian McKenzie
9dcceaeb40 move minification.deadCodeElimination back to the builtin-setup transformer group 2015-06-02 17:08:49 +01:00
Sebastian McKenzie
556e58a4ab register function declarations anyway as we may not have hit them 2015-06-02 17:08:31 +01:00
Sebastian McKenzie
b6c35743e6 add import types 2015-06-02 16:24:32 +01:00
Sebastian McKenzie
0abd34f7e6 Merge branch 'master' of github.com:babel/babel 2015-06-02 16:18:13 +01:00
Sebastian McKenzie
cafd7f8e39 add Infinity/NaN, string/number member expressions/calls and Math calls static evaluation 2015-06-02 16:18:08 +01:00
Sebastian McKenzie
43c0a0e65f remove all non-function statements after completion statements in blocks 2015-06-02 16:16:36 +01:00
Sebastian McKenzie
7b359f46fd rename minification.inlineExpressions to minification.constantFolding 2015-06-02 16:16:10 +01:00
Sebastian McKenzie
880827f6ce Merge pull request #1669 from wincent/mixed-type
Add "mixed" Flow type
2015-06-02 16:15:23 +01:00
Greg Hurrell
0c300058a3 Add "mixed" Flow type
"mixed" is one of the base types listed here:

http://flowtype.org/docs/base-types.html

So this commit adds support for it.
2015-06-02 07:15:06 -07:00
Sebastian McKenzie
d35be22f7d add support for resolving array expression elements 2015-06-02 00:32:18 +01:00
Sebastian McKenzie
ff8d90061f add "istanbul ignore next" auxiliary comment when using istanbul compat mode for babel/register 2015-06-02 00:32:07 +01:00
Vsevolod Rodionov
e66109f9d0 Making babel able to run in node_modules directory (while still ignoring node_modules packages)
In case if app is installed by npm install <git tarball url> which is very comfortable thing (postinstall hooks, automatic package installation and so on) babel is unable to run over packages, e.g.
```
 ~/node_modules/some_app$ node-babel app.js
  ```
 is crashing as babel do not want in node_modules directory.

 relative path gives ability to check whether lib is in node_modules _relative_ to current app, so that if app is ran in node_modules by itself it will not be captured.
2015-06-01 14:55:51 -07:00
Sebastian McKenzie
1934c16f0f don't use initializer property for decorators on concise methods in object literals 2015-06-01 22:32:04 +01:00
Sebastian McKenzie
012ac7d9ec remove accidental console.log introduced in 80a7f13460 2015-06-01 22:01:27 +01:00
Jesse McCarthy
efb3b04225 Make node_modules path check robust. 2015-06-01 16:54:56 -04:00
Jesse McCarthy
1488d88c81 Add test for require-hook node_modules check.
(Failing.)
2015-06-01 16:54:52 -04:00
Sebastian McKenzie
80a7f13460 register named method id as a reference to avoid collisions - fixes #1664 2015-06-01 21:53:34 +01:00
Sebastian McKenzie
8919fc22b1 only infer single identifier new expression callees 2015-06-01 21:52:54 +01:00
Sebastian McKenzie
b1273cb774 Merge pull request #1663 from pangratz/fix_for_referencesImport
Minor fix for `referencesImport`
2015-06-01 18:13:49 +01:00
pangratz
0843b8355e Minor fix for referencesImport 2015-06-01 19:09:33 +02:00
Sebastian McKenzie
6457677fb4 add support for NewExpression and reference plain node 2015-06-01 17:29:02 +01:00
Sebastian McKenzie
f8a860bf21 remove unused import 2015-06-01 14:32:58 +01:00
Sebastian McKenzie
f2bed33db8 add type inference for ConditionalExpression, SequenceExpression, AssignmentExpression and add support for base type aliases in isTypeAnnotationGeneric method 2015-06-01 14:25:06 +01:00
Sebastian McKenzie
7d2c6525d8 flesh out type inferrence some more, rename some of the NodePath methods to be less ambiguous, remove dead Binding type methods 2015-06-01 14:01:14 +01:00
Sebastian McKenzie
de652dc747 change getBindingIdentifier keys to be just a string instead of an array 2015-06-01 12:06:36 +01:00
Sebastian McKenzie
9f1053212b add EmptyStatement to t.toSequenceExpression 2015-06-01 12:06:16 +01:00
Sebastian McKenzie
76690a3deb renamed Path#isPreviousType to isType 2015-06-01 12:05:42 +01:00
Sebastian McKenzie
50f2f2fc98 remove DoExpression statement parsing and clear labels and set inFunction to false when parsing DoExpression body - fixes #1658 2015-06-01 03:36:14 +01:00
Sebastian McKenzie
5c27234d19 change TCO BlockStatement visitor back to enter 2015-06-01 00:17:44 +01:00
Sebastian McKenzie
6f5d16f397 remove TCOable check 2015-06-01 00:14:12 +01:00
Sebastian McKenzie
e42a43e3d1 remove unnecessary strict helper 2015-05-31 23:40:59 +01:00
Sebastian McKenzie
bfd307cd57 move some visitors out of deoptimising enter method 2015-05-31 23:40:42 +01:00
Sebastian McKenzie
beb5ee1333 remove useless generator test helpers 2015-05-31 21:26:22 +01:00
Sebastian McKenzie
cde871555d don't pass comments in tokens to estraverse 2015-05-31 21:26:12 +01:00
Sebastian McKenzie
51b0ffa7bf prepend Comment to comment node types 2015-05-31 20:25:26 +01:00
Sebastian McKenzie
255c819727 optimise ES6 tail call transformer to only try TOC on functions that include a call to themselves 2015-05-31 15:40:41 +01:00
Sebastian McKenzie
152ccb2ce8 check if ObjectExpression has any gets/sets before filtering 2015-05-31 15:40:07 +01:00
Sebastian McKenzie
bdb3adfeea revert parts of 07a992e 2015-05-31 09:47:27 +01:00
Sebastian McKenzie
236086bee5 ignore trailing commas when inferring newlines - fixes #1304 2015-05-31 09:46:05 +01:00
Sebastian McKenzie
1436753e6d fix linting errors 2015-05-31 09:24:12 +01:00
Sebastian McKenzie
eadf8ef799 fix syntax error in helpers/parse 2015-05-31 09:20:16 +01:00
Sebastian McKenzie
f1e20cf6ff remove useless comment 2015-05-31 09:16:34 +01:00
Sebastian McKenzie
82a0851526 push comments to token stream to avoid having to re-sort - #1486 2015-05-31 09:16:27 +01:00
Sebastian McKenzie
07a992e6d3 add support for tail calls when in completion record position - fixes #1572 2015-05-31 09:07:44 +01:00
Sebastian McKenzie
f642c2baa8 relax key aliases for plain methods - fixes #1649 2015-05-30 23:53:39 -04:00
Sebastian McKenzie
2f7743cafb optimise module metadata retrieval - #1486 2015-05-30 23:42:24 -04:00
Sebastian McKenzie
44112f2d87 remove unused variable 2015-05-30 23:18:50 -04:00
Sebastian McKenzie
99c4810770 add regeneratot transform to builtin-advanced group 2015-05-30 23:18:45 -04:00
Sebastian McKenzie
9f2ac15695 move jscript transformer to the builtin-trailing group and perform transform on exit - closes #1652, fixes #1651 2015-05-30 23:09:25 -04:00
Sebastian McKenzie
19c1ee157f simplify scope parent alias keys 2015-05-30 23:08:42 -04:00
Sebastian McKenzie
973270772b use ForX alias instead of manually listing all types 2015-05-30 23:08:28 -04:00
Sebastian McKenzie
7334326042 remove extra semicolon 2015-05-30 22:37:18 -04:00
Sebastian McKenzie
4043e8e8b9 fix destructuring transformer AssignmentExpression to properly handle completion records 2015-05-30 22:33:09 -04:00
Sebastian McKenzie
7fd403998c remove dead code 2015-05-30 22:32:48 -04:00
Sebastian McKenzie
1f7fcc2985 Merge branch 'master' of github.com:babel/babel 2015-05-30 22:13:59 -04:00
Sebastian McKenzie
ba19bd36a4 optimise scope tracking into a single pass - #1486 2015-05-30 22:07:03 -04:00
Sebastian McKenzie
e119681b1f return paths accordingly in insertBefore and insertAfter methods 2015-05-30 22:03:25 -04:00
Sebastian McKenzie
fbe22e53a9 add check for dynamic node and output error message accordingly 2015-05-30 22:02:56 -04:00
Sebastian McKenzie
79e826fcc8 attempt to optimise node printing by shifting it into a class 2015-05-30 22:02:29 -04:00
Sebastian McKenzie
cf940268b9 add noScope to template visitor 2015-05-30 22:02:15 -04:00
Sebastian McKenzie
96bb572307 use flow type shorthand for eaching over specifiers 2015-05-30 19:09:23 -04:00
Sebastian McKenzie
5dafe0b66a collapse t.getBindingIdentifiers comment 2015-05-30 19:08:14 -04:00
Sebastian McKenzie
29e24a4cbe don't evaluate non-referenced identifiers 2015-05-30 19:07:58 -04:00
Sebastian McKenzie
f979d55b71 remove special ExpressionStatement handling in destructuring transformer 2015-05-30 19:07:31 -04:00
Sebastian McKenzie
164b2116a3 switch expontentation evaluation to just use the operator 2015-05-30 19:05:31 -04:00
Dan Abramov
55e623a099 Merge pull request #1650 from jmm/contrib-build-version
Make note about buildable versions more prominent.
2015-05-30 11:29:59 +03:00
Jesse McCarthy
a60b4b1302 Make note about buildable versions more prominent. 2015-05-29 14:14:15 -04:00
Dan Abramov
bf23e59bbf Add a note about building older versions. Fixes #1643 2015-05-29 16:50:34 +03:00
Sebastian McKenzie
eb4cee89c5 add referencesImport path method - fixes #1423 2015-05-28 11:39:51 -04:00
Sebastian McKenzie
fb94a87a4d add support for cluster forking - fixes #1611 2015-05-28 10:36:29 -04:00
Sebastian McKenzie
9613c7fdb6 fix linting error 2015-05-28 10:30:09 -04:00
Sebastian McKenzie
d8c97fba15 check plugin.default and then just plugin to support ES6 modules - closes #1627 2015-05-28 10:25:50 -04:00
Sebastian McKenzie
0f663560d4 add --nolazy to babel-node - fixes #1639 2015-05-28 10:24:31 -04:00
Sebastian McKenzie
4901075960 deopt rest parameter member expression optimisation on child arrow functions - fixes #1631 2015-05-28 10:22:12 -04:00
Sebastian McKenzie
4aec242979 add some comments to some path methods and remove some dead code 2015-05-28 10:04:46 -04:00
Sebastian McKenzie
d1d95e0e49 check LHS of ForIn/ForOfStatement for constants - closes #1630 2015-05-28 10:04:32 -04:00
Sebastian McKenzie
d3c643b004 clean up path resolution and add in path resolution recursion detection - cc @RReverser 2015-05-25 19:08:08 +01:00
Sebastian McKenzie
98eb30c482 rename Path#remove to Path#dangerouslyRemove 2015-05-25 16:17:28 +01:00
Sebastian McKenzie
2d43ffb5b4 remove removal scope hooks 2015-05-25 15:57:22 +01:00
Sebastian McKenzie
a195701de2 remove dead code 2015-05-25 15:28:23 +01:00
Sebastian McKenzie
f639f4bea7 upgrade babel-eslint 2015-05-25 15:28:16 +01:00
Sebastian McKenzie
334cbb06c6 flesh out removal hooks more 2015-05-25 15:28:11 +01:00
Sebastian McKenzie
f4a3b2f01a add link to readme in contributing guide so people can't whinge and note in the README that issues without reproducible examples will be closed 2015-05-25 14:55:37 +01:00
Sebastian McKenzie
dbe6f1b9a9 merge remove parent context checks 2015-05-25 04:30:17 +01:00
Sebastian McKenzie
73ada57a17 don't inline classes and functions when they're in different scopes in the utility.deadCodeElimination transformer 2015-05-25 03:33:12 +01:00
Sebastian McKenzie
8e2b743f7e add support for resyncing container on changes 2015-05-25 03:32:25 +01:00
Sebastian McKenzie
a533042503 fix bad .gitignore paths resulting in some tests and path/lib files not being included... 2015-05-25 01:42:54 +01:00
Sebastian McKenzie
49953e3464 enable no-unused-vars in eslint 2015-05-25 01:32:06 +01:00
Sebastian McKenzie
0bf95d6aea even more split up of path methods 2015-05-25 01:01:21 +01:00
Sebastian McKenzie
7d88a1ca0b rename TraversalPath to NodePath and further split up methods into separate files 2015-05-25 00:43:46 +01:00
Sebastian McKenzie
ec74eb41cf reneable eslint and fix assorted linting errors 2015-05-25 00:42:59 +01:00
Sebastian McKenzie
3139482358 clean and fix up visitor merging 2015-05-24 18:15:46 +01:00
Sebastian McKenzie
32f19aff99 clean up file processing API 2015-05-24 18:15:34 +01:00
Sebastian McKenzie
23bead9226 Merge branch 'master' of github.com:babel/babel 2015-05-24 01:45:00 +01:00
Sebastian McKenzie
bd3812c255 handle SwitchStatements as a different type of path when pushing a declaration - fixes #1614 2015-05-24 01:43:04 +01:00
Sebastian McKenzie
e498185a76 Merge pull request #1610 from dekelcohen/master
Fixed Remove Debugger transformer to use DebuggerStatement
2015-05-22 23:36:47 +01:00
Dekel Cohen
167eda4750 Fixed Remove Debugger transformer to use DebuggerStatement 2015-05-23 01:13:23 +03:00
Sebastian McKenzie
3b52ddce6d 5.4.7 2015-05-21 19:00:16 +01:00
Sebastian McKenzie
0e771c5d38 v5.4.7 2015-05-21 18:59:30 +01:00
Sebastian McKenzie
2ec1544f2d add 5.4.7 changelog 2015-05-21 18:58:49 +01:00
Sebastian McKenzie
049ef430b2 5.4.6 2015-05-21 18:58:12 +01:00
Sebastian McKenzie
34eb2babdb don't consider JSXAttribute keys to be referenced identifiers - fixes #1596 2015-05-21 18:58:07 +01:00
Sebastian McKenzie
8706754550 v5.4.6 2015-05-21 18:46:22 +01:00
Sebastian McKenzie
c7b507e119 add 5.4.6 changelog 2015-05-21 18:45:31 +01:00
Sebastian McKenzie
221c632c05 deprecate custom module formatters 2015-05-21 18:44:02 +01:00
Sebastian McKenzie
7dbde208ef spec.functionName transformer: hasBinding(name) returns true for built-in globals, so we attempt to rename the binding but it doesn't exist so exits early, add a check that doesn't perform the renaming and instead uses the wrapper - fixes #1598 2015-05-21 18:43:55 +01:00
Sebastian McKenzie
52a2e3e17c return original input if glob returned nothing in babel-cli - fixes #1591 2015-05-21 10:57:37 +01:00
Sebastian McKenzie
fa22d7dca0 5.4.5 2015-05-21 01:52:03 +01:00
Sebastian McKenzie
9fcdebde08 v5.4.5 2015-05-21 01:44:29 +01:00
Sebastian McKenzie
92157161f0 fix prettyCall generation option 2015-05-21 01:43:02 +01:00
Sebastian McKenzie
82b5479436 add 5.4.5 changelog 2015-05-21 01:41:30 +01:00
Sebastian McKenzie
91a037af55 Merge pull request #1590 from Khan/fix_retainLines_with_jsx
tests for retainLines formatting
2015-05-21 01:39:33 +01:00
Kevin Barabash
067fccc2c9 tests for retainLines formatting 2015-05-20 18:36:47 -06:00
Sebastian McKenzie
348c0d2542 handle TCO for calls that exceed the functions parameter count - fixes #1589 2015-05-21 01:21:49 +01:00
Sebastian McKenzie
f2f6bbb02c clean up explosion of module declarations, remove and inherit comments when taking off the declaration - fixes #1583 2015-05-21 01:03:23 +01:00
Sebastian McKenzie
16f7b967b5 ignore CallExpression _prettyCall when retainLines is enabled - fixes #1585 2015-05-21 00:21:18 +01:00
Sebastian McKenzie
270a8be68d add JSXIdentifier as a valid ReferencedIdentifier - fixes #1584 2015-05-21 00:20:53 +01:00
Sebastian McKenzie
82254d9d9b force push space for await/async - fixes #1581 2015-05-20 12:45:04 +01:00
Sebastian McKenzie
759a265fb0 5.4.4 2015-05-20 10:52:28 +01:00
Sebastian McKenzie
ee46f45c90 v5.4.4 2015-05-20 10:50:35 +01:00
Sebastian McKenzie
c45ce61550 print assignment pattern shorthand with matching key nicely 2015-05-20 10:44:36 +01:00
Sebastian McKenzie
b36cf11ac8 add 5.4.4 changelog 2015-05-20 10:44:17 +01:00
Sebastian McKenzie
dca0f72e4d clarify default option descriptions - fixes #1577 2015-05-20 10:36:58 +01:00
Sebastian McKenzie
68a99ed1e9 fix es6.modules-system for head hoisting 2015-05-20 10:35:01 +01:00
Sebastian McKenzie
af4feb4d88 fix renaming of assignment expressions to fix pattern renaming in the es6.blockScoping transformer - fixes #1576 2015-05-20 10:34:50 +01:00
Sebastian McKenzie
de1e965fec fix placement of for loop in es6.modules-system hoisting test 2015-05-20 10:15:42 +01:00
Sebastian McKenzie
430c5df0e7 rename sourceMapName option to sourceMapTarget - closes #1568 2015-05-20 10:14:28 +01:00
Sebastian McKenzie
9b12f799f7 clean up system module formatter hoisting visitor and allow contextual replacement of variable declarations with expressions in for head positions - fixes #1570 2015-05-20 10:07:29 +01:00
Sebastian McKenzie
f3a9c6ee5d Merge pull request #1562 from clintwood/sourcemap-file
correct cli source map file: value, honor sourceRoot when using -o opion
2015-05-20 09:57:34 +01:00
Sebastian McKenzie
e0aceeafef Merge pull request #1570 from guybedford/system-hoist-bug
System format hoisting bug
2015-05-20 09:57:14 +01:00
Sebastian McKenzie
7643d86047 Merge branch 'master' of github.com:babel/babel 2015-05-20 09:57:03 +01:00
Sebastian McKenzie
98af01a73c update old 6to5 package.json description 2015-05-20 09:56:54 +01:00
Sebastian McKenzie
e280a810c3 add support for all completion record types when exploding an expression to statements 2015-05-20 09:56:45 +01:00
Sebastian McKenzie
7a59575d1e force space before class id when generating classes - fixes #1579 2015-05-20 09:56:19 +01:00
Sebastian McKenzie
b01d8448a0 Merge pull request #1558 from jquense/patch-2
Resolve "babel-plugin-" name before trying the plain name.
2015-05-19 01:28:02 +01:00
jquense
9b3c8569f7 Resolve 'babel-plugin-' name before the plain name
Otherwise you get situations like the following: `plugins: [
'object-assign']` resolves the module `object-assign` (an Object.assign
polyfill) instead of the intended babel plugin:
babel-plugin-object-assign.
2015-05-18 20:26:51 -04:00
Sebastian McKenzie
12104f822f add assignment pattern shorthand support to explode transformer - fixes #1566 2015-05-18 22:44:40 +01:00
Sebastian McKenzie
b4cd2df745 ignore this and arguments when performing TCO on shadowed functions - fixes #1564 2015-05-18 22:41:27 +01:00
guybedford
887ffed84c system hoist bug test case 2015-05-18 23:35:09 +02:00
Sebastian McKenzie
9be3d9c8e1 Merge branch 'master' of github.com:babel/babel 2015-05-18 10:33:12 +01:00
clintwood (Office)
9d3dff3b7a correct cli source map file: value, honor sourceRoot when using -o option 2015-05-18 10:11:20 +02:00
Sebastian McKenzie
55114ec631 update AMD module formatter to add import default remapping - #1150 2015-05-18 02:01:34 +01:00
Sebastian McKenzie
9c3d00d3c3 Merge pull request #1559 from sindresorhus/hometmp
use `home-or-tmp` module instead of `user-home`
2015-05-17 23:50:26 +01:00
Sindre Sorhus
90b8826e73 use home-or-tmp module instead of user-home
The main point about using this instead of just falling back in code is that it depends on an `os.tmpdir()` polyfill [0], which means the tmpdir handling is the same no matter node/iojs version. This is useful as the core `os.tmpdir()` function has changed a lot between node versions.

[0]: https://github.com/sindresorhus/os-tmpdir

---

`os.tmpdir()` diff between Node 0.10.38 and iojs 2.0.2

```diff
+const trailingSlashRe = isWindows ? /[^:]\\$/
+                                  : /.\/$/;
+
 exports.tmpdir = function() {
-  return process.env.TMPDIR ||
-         process.env.TMP ||
-         process.env.TEMP ||
-         (process.platform === 'win32' ? 'c:\\windows\\temp' : '/tmp');
+  var path;
+  if (isWindows) {
+    path = process.env.TEMP ||
+           process.env.TMP ||
+           (process.env.SystemRoot || process.env.windir) + '\\temp';
+  } else {
+    path = process.env.TMPDIR ||
+           process.env.TMP ||
+           process.env.TEMP ||
+           '/tmp';
+  }
+  if (trailingSlashRe.test(path))
+    path = path.slice(0, -1);
+  return path;
 };
```
2015-05-18 00:39:49 +02:00
Sebastian McKenzie
65f39bbf6f switch order of jsx/flow plugins to avoid precedence issues - fixes babel/babel-eslint#103 2015-05-17 22:00:38 +01:00
Sebastian McKenzie
e9eced846f 5.4.3 2015-05-16 02:00:20 +01:00
Sebastian McKenzie
a0befe349d v5.4.3 2015-05-16 01:58:52 +01:00
Sebastian McKenzie
04992effb3 improve lost node path tracking message 2015-05-16 01:54:35 +01:00
Sebastian McKenzie
9ae54d2a50 add 5.4.3 changelog 2015-05-16 01:54:25 +01:00
Sebastian McKenzie
fe72a40159 Revert "add back descriptor.initializer existence check"
This reverts commit 02dfd18023.
2015-05-16 01:50:31 +01:00
Sebastian McKenzie
ea510d09d0 fix module shadowing when using CommonJS-like module formatters - fixes #1544 2015-05-16 01:47:48 +01:00
Sebastian McKenzie
375689a1ff handle path contexts MUCH better, they're now only held during the traversal iteration and the previous context is released upon completion, also verify path keys and try and obtain a new one if invalid - fixes #1545 2015-05-16 01:37:55 +01:00
Sebastian McKenzie
9908e331b7 Merge pull request #1549 from Naddiseo/master
Added DCE tests for all the bugs I've reported so far.
2015-05-15 23:08:32 +01:00
Richard Eames
cd8655708d Added DCE tests for all the bugs I've reported so far. 2015-05-15 15:55:58 -06:00
Sebastian McKenzie
62b94f297a don't create a new binding for local class ids, just copy the parents - fixes #1547 2015-05-15 19:11:24 +01:00
Sebastian McKenzie
01d399ee3c check for existence of variable when checking if node is pure 2015-05-15 18:48:17 +01:00
Sebastian McKenzie
30e3908484 don't perform DCE on single references nested inside the binding initializer - fixes #1546 2015-05-15 18:48:05 +01:00
Sebastian McKenzie
ff12046009 move traverse replace test up 2015-05-15 18:35:15 +01:00
Sebastian McKenzie
1a058b4a6e Merge branch 'master' of github.com:babel/babel 2015-05-15 17:42:40 +01:00
Sebastian McKenzie
02dfd18023 add back descriptor.initializer existence check 2015-05-15 17:42:28 +01:00
Sebastian McKenzie
9ab7df5f47 remove wildcards from start of patterns 2015-05-15 17:42:10 +01:00
Sebastian McKenzie
7a5b140f92 minor generation style nits 2015-05-15 17:41:56 +01:00
Sebastian McKenzie
6f83111c55 Merge pull request #1542 from amasad/already-printed
Fix bug with paren printing in compact + line retained mode
2015-05-15 17:38:40 +01:00
Sebastian McKenzie
f3f60368da remove TraversalPath node getter/setter 2015-05-15 17:34:31 +01:00
Sebastian McKenzie
7a09640b20 add environment to register cache key 2015-05-15 17:34:06 +01:00
Amjad Masad
2916d1262b Don't print leftParen if already printed before the catchup 2015-05-14 23:57:35 -07:00
Amjad Masad
741abb73d2 Add failing test for printing with compact & retainLines 2015-05-14 23:57:05 -07:00
Sebastian McKenzie
2e46755260 5.4.2 2015-05-15 02:36:22 +01:00
Sebastian McKenzie
2cff9519e1 v5.4.2 2015-05-15 02:35:07 +01:00
Sebastian McKenzie
f9c2c6e988 Merge branch 'master' of github.com:babel/babel
# Conflicts:
#	CHANGELOG.md
2015-05-15 02:34:11 +01:00
Sebastian McKenzie
5ae3dc01f1 make path patterns used by only and ignore **very** liberal, this will ease a lot of pain in dealing with them 2015-05-15 02:33:40 +01:00
Sebastian McKenzie
af4fd69dd0 make path patterns used by only and ignore **very** liberal, this will ease a lot of pain in dealing with them 2015-05-15 02:33:22 +01:00
Sebastian McKenzie
4d4493f325 elaborate on shouldIgnore changes in 5.4.1 2015-05-15 02:03:02 +01:00
Sebastian McKenzie
e70d474b39 5.4.1 2015-05-15 02:01:42 +01:00
Sebastian McKenzie
1b45f64858 v5.4.1 2015-05-15 02:00:18 +01:00
Sebastian McKenzie
b89cf6768f fix shouldIgnore only matches switch 2015-05-15 01:57:10 +01:00
Sebastian McKenzie
36ad1108b4 fix loose mode loop being weirdly inserted 2015-05-15 01:56:34 +01:00
Sebastian McKenzie
4c04371ea4 remove loop label due to babel bug 2015-05-15 01:48:47 +01:00
Sebastian McKenzie
d3e385c554 one last try fixing the shouldIgnore only filter... 2015-05-15 01:46:36 +01:00
Sebastian McKenzie
6afcef9805 actually fix shouldIgnore algorithm this time, ugh 2015-05-15 01:44:57 +01:00
Sebastian McKenzie
ed861e230b fix shouldIgnore method for only 2015-05-15 01:41:49 +01:00
Sebastian McKenzie
e15ced2922 add 5.4.1 changelog 2015-05-15 01:37:48 +01:00
Sebastian McKenzie
93052e532f Merge branch 'master' of github.com:babel/babel 2015-05-15 01:35:43 +01:00
Sebastian McKenzie
198d51ddaa heavily improve shouldIgnore algorithm - fixes #1539 2015-05-15 01:34:58 +01:00
Sebastian McKenzie
8730b24def Merge pull request #1540 from browncolyn/master
Added slash as needed dependency
2015-05-15 01:30:50 +01:00
Colyn Brown
f09c0d5998 Added slash as needed dependency 2015-05-14 17:28:20 -07:00
Sebastian McKenzie
21e4481ab7 5.4.0 2015-05-15 00:32:36 +01:00
Sebastian McKenzie
2f61754a24 v5.4.0 2015-05-15 00:29:42 +01:00
Sebastian McKenzie
3910d18bc9 add 5.4.0 changelog 2015-05-15 00:28:47 +01:00
Sebastian McKenzie
583111ebfb expose file metadata object to transformers 2015-05-15 00:24:14 +01:00
Sebastian McKenzie
1b15481460 ignore "ignored files" when babel.transform has determined that it should be ignored, this is likely the result of an rc file resolution - fixes #1362 2015-05-15 00:24:03 +01:00
Sebastian McKenzie
fd9c98ff86 move strict transformer to builtin-setup group - fixes #1538 2015-05-15 00:18:42 +01:00
Sebastian McKenzie
41b5607ef3 fix env option tests 2015-05-15 00:11:28 +01:00
Sebastian McKenzie
ae77ea807f normalise source map file paths when using the CLI - fixes #1496 2015-05-15 00:05:11 +01:00
Sebastian McKenzie
ad44190c6b properly register for head variable declaration paths when performing scope tracking - fixes #1524 2015-05-14 23:53:04 +01:00
Sebastian McKenzie
024e4454a1 add env option - closes #1531 2015-05-14 23:47:56 +01:00
Sebastian McKenzie
14dddcda36 make PathHoister much more flexible, now ignores global references and will not deopt on reassignments and will instead hoist as high as it can, this also fixes #1529 since the order of operations has changed 2015-05-14 23:29:02 +01:00
Sebastian McKenzie
d4fb924b6a add tion comment to all function visitors 2015-05-14 22:37:15 +01:00
Sebastian McKenzie
b02c97af60 Merge pull request #1536 from benjamn/master
Invoke Regenerator on async/generator Function nodes, not whole AST.
2015-05-14 22:27:42 +01:00
Ben Newman
cc611cb71c Invoke Regenerator on async/generator Function nodes, not whole AST.
This should help (dramatically?) with
https://github.com/babel/babel/issues/1486#issuecomment-101491605,
although I'm not sure how to run the benchmarks myself.
2015-05-14 15:42:58 -05:00
Sebastian McKenzie
b8a01a9919 move traversal scope logic and binding into it's own folder, rename Scope#generateTemp to generateDeclaredUidIdentifier, rename Scope#generateUidBasedOnNode to Scope#generateUidIdentifierBasedOnNode 2015-05-14 19:12:26 +01:00
Sebastian McKenzie
55c99661be NFO 2015-05-14 18:07:36 +01:00
Sebastian McKenzie
1563b216df Merge branch 'master' of github.com:babel/babel 2015-05-14 17:56:33 +01:00
Sebastian McKenzie
a9d4b485d9 simplify getStaticContext in es7.functionBind transformer - thanks @RReverser! 2015-05-14 17:48:51 +01:00
Sebastian McKenzie
360daa6267 Merge pull request #1532 from dchambers/prefix-private-methods-with-underscore
Prefix private methods names with underscore.
2015-05-14 16:52:16 +01:00
Sebastian McKenzie
724bf52929 handle "static" contexts in es7.functionBind - #1518 2015-05-14 16:37:44 +01:00
Sebastian McKenzie
7407b37bd9 Merge pull request #1518 from babel/es7.functionBind
Add experimental support for ES7 function bind.
2015-05-14 16:22:21 +01:00
Ingvar Stepanyan
da765cc4c1 Flip the negation in if-else. 2015-05-14 18:05:55 +03:00
dchambers
4f862eee6e Prefix private methods names with underscore. 2015-05-14 13:19:41 +01:00
Ingvar Stepanyan
e05d7cf49a Fix some parsing edge cases for :: operator. 2015-05-14 12:47:51 +03:00
Ingvar Stepanyan
fd8e94a90f Preserve original execution order in :: operator. 2015-05-14 12:39:05 +03:00
Sebastian McKenzie
a6cf28c5b5 Merge pull request #1525 from nkt/exponentiation-operator-inline
Added missing exponential operator inlining
2015-05-13 23:09:57 +01:00
Nikita Gusakov
6b07b13a8e Added missing exponential operator inlining 2015-05-14 01:08:02 +03:00
Sebastian McKenzie
561c4dcc25 5.3.3 2015-05-13 22:09:37 +01:00
Sebastian McKenzie
b516ea596a v5.3.3 2015-05-13 22:08:32 +01:00
Sebastian McKenzie
248758eee3 fix version number 2015-05-13 22:07:33 +01:00
Sebastian McKenzie
a808602ae0 v3.5.3 2015-05-13 22:07:00 +01:00
Sebastian McKenzie
40e3436e95 add 3.5.3 changelog 2015-05-13 22:05:07 +01:00
Sebastian McKenzie
f704770b26 uncomment out return traversal path skipping - fixes #1523 2015-05-13 22:03:50 +01:00
Sebastian McKenzie
330665f150 ignore modules alongside param bindings in minification.deadCodeElimination transformer - fixes #1523 2015-05-13 21:49:28 +01:00
Sebastian McKenzie
af41899d74 5.3.2 2015-05-13 19:58:21 +01:00
Sebastian McKenzie
d12f4d0bc8 v5.3.2 2015-05-13 19:57:20 +01:00
Sebastian McKenzie
97680e9dfd properly hoist all var patterns when wrapping bodies in the es6.blockScoping transformer - fixes #1521 2015-05-13 19:55:40 +01:00
Sebastian McKenzie
51341ca6c3 fix and add missing module specifier reference detection - fixes #1520 2015-05-13 19:23:47 +01:00
Sebastian McKenzie
ab54bfa50e Merge pull request #1519 from zpao/package-licenses
Add license fields to packages
2015-05-13 18:36:25 +01:00
Paul O’Shannessy
60aa933fb6 Add license fields to packages 2015-05-13 10:21:42 -07:00
Ingvar Stepanyan
1a299b2bcc Small fixes to es7.functionBind and generation tests added. 2015-05-13 18:20:33 +03:00
Ingvar Stepanyan
37f662d790 Add experimental support for ES7 function bind. (issue #1287) 2015-05-13 17:58:21 +03:00
Sebastian McKenzie
b0317f9bab don't consider "globals" to cause incompatible scope hoist 2015-05-13 12:33:08 +01:00
Sebastian McKenzie
be2dfaf081 register variable declarator in scope when pushing 2015-05-13 09:11:09 +01:00
Sebastian McKenzie
2c8437ae92 ignore initializerless variable declaration when trying to inline single use variables - fixes #1516 2015-05-13 08:46:41 +01:00
Sebastian McKenzie
2a0bcfd086 add support for evaluating unary ~ 2015-05-13 08:45:16 +01:00
Sebastian McKenzie
2cf41afac3 move expression inlining to exit rather than enter in minification.inlineExpressions transformer 2015-05-13 08:45:06 +01:00
Sebastian McKenzie
e318f5f3be use ReferencedIdentifier virtual type in minification.deadCodeElimination transformer 2015-05-13 08:44:33 +01:00
Sebastian McKenzie
939decb86c stop entire unnecessary traversal for regenerator 2015-05-13 08:44:18 +01:00
Sebastian McKenzie
1baa0df948 clean up array inferrence for #1515 2015-05-13 08:44:03 +01:00
Sebastian McKenzie
e8956a8c44 upgrade dev dependency babel to 5.3.1 2015-05-13 08:43:25 +01:00
Sebastian McKenzie
2f0fdbbc26 5.3.1 2015-05-13 03:21:54 +01:00
Sebastian McKenzie
5f931525bc v5.3.1 2015-05-13 03:20:33 +01:00
Sebastian McKenzie
b86545a320 update 5.3.1 changelog 2015-05-13 03:19:39 +01:00
Sebastian McKenzie
06e75c42bf update module call remap tests 2015-05-13 03:18:55 +01:00
Sebastian McKenzie
05dd65244d add 5.3.1 changelog 2015-05-13 03:16:43 +01:00
Sebastian McKenzie
c4ebfeb0fa fix explosion of modules and colliding identifiers 2015-05-13 03:16:03 +01:00
Sebastian McKenzie
1aa0bbfac9 add TraversalPath#equals 2015-05-13 03:13:27 +01:00
Sebastian McKenzie
58f1e6cbc6 remove incorrect es6.tailCall visitor comment 2015-05-13 03:13:20 +01:00
Sebastian McKenzie
83e0be3038 make import calls sequence expressions - fixes #1514 2015-05-13 03:13:10 +01:00
Sebastian McKenzie
5fc242e4ec upgrade bable dev dependency to 5.3.0 2015-05-13 03:12:32 +01:00
Sebastian McKenzie
dc101adad3 more es6.tailCall transformer cleanup 2015-05-13 01:13:08 +01:00
Sebastian McKenzie
faade72787 optimise and clean up es6.tailCall transformer 2015-05-13 01:11:26 +01:00
Sebastian McKenzie
2a78ae9889 5.3.0 2015-05-13 01:07:11 +01:00
Sebastian McKenzie
9840639843 v5.3.0 2015-05-13 00:13:14 +01:00
Sebastian McKenzie
82c21a901e clean up es6.tailCall thirdPass visitor 2015-05-13 00:11:19 +01:00
Sebastian McKenzie
e1c83144c1 add 5.3.0 changelog 2015-05-13 00:11:08 +01:00
Sebastian McKenzie
ef2ac73215 fix export scope tracking reference counter - fixes #1513 2015-05-12 23:21:30 +01:00
Sebastian McKenzie
735d8955bf sync with upstream acorn 2015-05-12 23:21:30 +01:00
Sebastian McKenzie
3abee0a4fa fix switch case breaks not being correctly transformed when non top-level - fixes #1200 2015-05-12 23:21:30 +01:00
Sebastian McKenzie
b6f18b4f2b Merge pull request #1200 from lukasmlady/regenerator-let-fn-if-bug
Add failing tests that document ES 6 generators bug
2015-05-12 23:21:17 +01:00
Sebastian McKenzie
85cd0465fa Merge pull request #1511 from amasad/trailing-methods
Trailing commas in methods
2015-05-12 21:46:18 +01:00
Amjad Masad
0452e0fdd2 Allow trailing commas in methods 2015-05-12 13:20:36 -07:00
Amjad Masad
462ff572b3 Add failing test for trailing commas in methods 2015-05-12 13:19:21 -07:00
Sebastian McKenzie
d11099bb2b Merge branch 'master' of github.com:babel/babel 2015-05-12 19:13:53 +01:00
Sebastian McKenzie
f5c4684d3e force default parameter IIFE on reference to eval 2015-05-12 19:13:32 +01:00
Sebastian McKenzie
876a22578b Merge pull request #1506 from sverrejoh/patch-1
Added missing license field to package.json
2015-05-12 09:06:55 +01:00
Sverre Johansen
9f5e8b296b Added missing license field to package.json
Project says MIT, but license field missing in package.json
2015-05-12 08:54:56 +02:00
Sebastian McKenzie
d9deb02edc register as inside a type when parsing type aliases to avoid ambiguous jsx parsing - fixes #1378 2015-05-11 23:44:22 +01:00
Sebastian McKenzie
a402d0cdeb ensure that uids don't collide with **any** bindings contained in the program - fixes #1328 2015-05-11 23:37:31 +01:00
Sebastian McKenzie
683fb62505 fix acorn hacky lookahead with token contexts - fixes #1349 2015-05-11 23:20:51 +01:00
Sebastian McKenzie
941474983d clean up es6.objectSuper transformer - fixes #1502 2015-05-11 22:34:08 +01:00
Sebastian McKenzie
2b42773e01 explode duplicate identifiers in export/import specifiers and property shorthand - fixes #1458 2015-05-11 22:08:38 +01:00
Sebastian McKenzie
8277a532f4 skip loose mode for class methods when using decorators, addresses #1501 2015-05-11 17:40:36 +01:00
Sebastian McKenzie
539784b640 add Scope#moveBindingTo method and change more for array loops to for...of 2015-05-11 17:25:09 +01:00
Sebastian McKenzie
f373f8f003 refactor _shadowFunctions transformer to not do an entire traverse per function 2015-05-11 11:38:22 +01:00
Sebastian McKenzie
8605e835eb add exit visitor existence to unvisitable node shortcircuiting 2015-05-11 01:52:19 +01:00
Sebastian McKenzie
b4ace2043a fix shortcircuting of unvisitable nodes 2015-05-11 01:43:18 +01:00
Sebastian McKenzie
444a64e934 remove incorrect no eval in strict mode 2015-05-10 20:01:13 +01:00
Sebastian McKenzie
8ea2ae924d add existence check for ast.comments 2015-05-10 20:00:38 +01:00
Sebastian McKenzie
4ceb1d6f5e short circuit unnecessary visits 2015-05-10 20:00:26 +01:00
Sebastian McKenzie
3c81899ca7 add --harmony_generators to list of node flags - closes #1474, closes #1473 2015-05-10 20:00:12 +01:00
Sebastian McKenzie
ab59fd08e5 fix array type inferrence for file#toArray from being so wonky - fixes #1355 2015-05-10 19:35:41 +01:00
Sebastian McKenzie
19b05b5e61 change some manual array for loops to for..of 2015-05-10 19:35:05 +01:00
Sebastian McKenzie
65a44a1e13 remove use of exports 2015-05-10 16:09:43 +01:00
Sebastian McKenzie
d38f18af40 create null object when clearing internalRemap instead of using an object inherited plain object - fixes #1489 2015-05-09 18:39:59 +01:00
Sebastian McKenzie
2744b9f31f only print misisng ast.comments when available 2015-05-09 17:32:47 +01:00
Sebastian McKenzie
4deed35212 fix syntax errors introduced with previous lodash each removal 2015-05-09 17:27:33 +01:00
Sebastian McKenzie
bc9ae5ea8b remove many instances of lodash each in favor of for of loops 2015-05-09 17:22:01 +01:00
Sebastian McKenzie
87d879e236 Merge branch 'master' of github.com:babel/babel 2015-05-09 16:53:05 +01:00
Sebastian McKenzie
f657598c72 remove noop traversal visitors methods 2015-05-09 16:52:57 +01:00
Sebastian McKenzie
2a5cb9d21b move some utility transformers to minification 2015-05-09 16:52:31 +01:00
Sebastian McKenzie
cf7d6b655e Merge pull request #1487 from amasad/trailing-commas
[es7.trailingFunctionCommas] Allow in new expressions
2015-05-09 03:16:18 +01:00
Amjad Masad
6d2723eec5 New expressions is allowed to have trailing commas in es7 proposal 2015-05-08 19:12:53 -07:00
Amjad Masad
6834cc5b46 Add failing tests for trailing commas in new expressions 2015-05-08 19:12:10 -07:00
Sebastian McKenzie
9b949e574f use block scoped variables in es6.blockScoping transformer 2015-05-09 01:25:36 +01:00
Sebastian McKenzie
a75af0a5d2 optimise es6.constants transformer to use the same traversal path instead of spawning another one 2015-05-09 01:25:21 +01:00
Sebastian McKenzie
080b26769c remove compat-table 2015-05-09 00:09:19 +01:00
Sebastian McKenzie
e037ae7bc9 automatically explode visitors 2015-05-09 00:07:08 +01:00
Sebastian McKenzie
c60ad89937 add verbose mode to logging 2015-05-09 00:06:55 +01:00
Sebastian McKenzie
4194857086 fix system modules test to reflect strict hoisting behaviour 2015-05-08 23:58:25 +01:00
Sebastian McKenzie
1179c44c5b share comments with siblings when nodes are removed - fixes #1484 2015-05-08 23:57:12 +01:00
Sebastian McKenzie
f6d9b270c9 update to tracuer master 2015-05-08 23:48:30 +01:00
Sebastian McKenzie
1be0159b01 Merge pull request #1484 from amasad/type-comment-print
[Flow] Add failing tests for printing comments w/ type alias
2015-05-08 23:46:18 +01:00
Sebastian McKenzie
61ba8ad997 Merge pull request #1472 from babel/single-pass
Merge internal transformers into single traversal pass
2015-05-08 23:36:29 +01:00
Sebastian McKenzie
89e31085d2 ensure dynamic imports are hoisted 2015-05-08 23:33:30 +01:00
Sebastian McKenzie
920c84a1f2 move shadow function visitors to entrance instead of exit 2015-05-08 23:33:20 +01:00
Amjad Masad
ed56fecd04 [Flow] Add failing tests for printing comments w/ type alias 2015-05-08 15:33:00 -07:00
Sebastian McKenzie
f0bfdfb699 skip traversing back into ReturnStatement replacement when rewriting loops in the es6.blockScoping transformer 2015-05-08 23:13:27 +01:00
Sebastian McKenzie
b02a1112bc change ClassExpression visitor to enter instead of exist in the es6.classes transformer 2015-05-08 23:10:02 +01:00
Sebastian McKenzie
590a165776 move hoistDirectives transformer to builtin-setup 2015-05-08 23:09:45 +01:00
Sebastian McKenzie
2fd1b2a484 rename category metadata option to group 2015-05-08 22:54:15 +01:00
Sebastian McKenzie
8f9d02d689 further work splitting up transformers into their own "category" in order of what they need and what they actually do 2015-05-08 22:53:31 +01:00
Sebastian McKenzie
b376b6b33b store uncollapsed transformer pass stack so we have access to it when calling pre and post methods 2015-05-08 22:53:03 +01:00
Sebastian McKenzie
8292d6d8ad fix replacement requeue exiting too early 2015-05-08 22:52:38 +01:00
Sebastian McKenzie
d6a5c39079 update classes to reflect new transformer precedence 2015-05-08 22:52:19 +01:00
Sebastian McKenzie
2a9a59f784 remove incomplete ludicrous transformer 2015-05-08 22:52:02 +01:00
Sebastian McKenzie
abf4a5495a don't pretty print variable declarators in concise mode 2015-05-08 22:51:47 +01:00
Sebastian McKenzie
f8b8723bef Merge pull request #1483 from jquense/patch-1
Fix plugin api typo when an object is passed in
2015-05-08 22:26:45 +01:00
Jason Quense
6b9686f2dd Fix plugin api typo when an object is passed in 2015-05-08 17:25:14 -04:00
Sebastian McKenzie
4a439d8c8e update flow strip type annotations test 2015-05-08 15:52:08 +01:00
Sebastian McKenzie
c526a3eb04 move shadow-functions internal transformer to builtin-cleanup category 2015-05-08 15:51:56 +01:00
Sebastian McKenzie
ba516901af restructure transformers into multiple categories 2015-05-08 15:26:00 +01:00
Sebastian McKenzie
8f52229a86 add get function name to source map classes test 2015-05-08 15:25:50 +01:00
Sebastian McKenzie
5b793f8882 fix TraversalPath#_getPattern incorrectly iterating over the parts 2015-05-08 15:25:34 +01:00
Sebastian McKenzie
b31c14c52a Merge branch 'master' into single-pass 2015-05-08 00:24:33 +01:00
Sebastian McKenzie
78b72512cb better verify the type of the new node before requeueing it and also stop current node traversal on skip 2015-05-08 00:24:04 +01:00
Sebastian McKenzie
2fbb3cad9f add isUser and isGenerated path methods 2015-05-08 00:23:28 +01:00
Sebastian McKenzie
2621081a13 merge in astVisitor in runtime transformer - unsure why this was separate in the first place 2015-05-08 00:23:00 +01:00
Sebastian McKenzie
8daf95bf59 name additional methods that are now covered since the naming is done in tandem 2015-05-08 00:22:43 +01:00
Sebastian McKenzie
6e8ab16b25 run es6.spec.blockScoping transformer on exit rather than enter 2015-05-08 00:22:23 +01:00
Sebastian McKenzie
a5cda5caa7 hoist param declaration when performing tco - fixes #1478 2015-05-07 23:14:03 +01:00
Sebastian McKenzie
13a6c69668 add node existence check to each visitor call 2015-05-07 23:02:40 +01:00
Sebastian McKenzie
380293d030 add transformer dependencies - fixes #1477 2015-05-07 21:35:12 +01:00
Sebastian McKenzie
0b15a97013 Merge branch 'master' into single-pass 2015-05-07 20:15:34 +01:00
Sebastian McKenzie
11af066956 5.2.17 2015-05-07 20:15:17 +01:00
Sebastian McKenzie
d7b4d342c3 v5.2.17 2015-05-07 20:12:47 +01:00
Sebastian McKenzie
77aeebe2a8 add Super node type to ast-types patch 2015-05-07 20:11:37 +01:00
Sebastian McKenzie
c3a08d413f attach auxiliary comment to function declaration helpers - fixes #1476 2015-05-07 20:11:31 +01:00
Sebastian McKenzie
23ac2319af add Super node type to ast-types patch 2015-05-07 20:11:14 +01:00
Sebastian McKenzie
a1bc0704ab attach auxiliary comment to function declaration helpers - fixes #1476 2015-05-07 20:11:02 +01:00
Sebastian McKenzie
0bbfd427af do module formatter on program exit rather than entrance 2015-05-07 16:23:47 +01:00
Sebastian McKenzie
f17b268a71 do member expression and property literal conversion to computed on exit rather than on entrance 2015-05-07 16:23:33 +01:00
Sebastian McKenzie
9ffc265bea don't requeue node unless the type has changed 2015-05-07 16:01:00 +01:00
Sebastian McKenzie
6f664ca64e merge internal transformers into single traversal pass 2015-05-07 15:53:22 +01:00
Sebastian McKenzie
8a4a76000d correctly arrayify commander extensions - closes #1470, fixes #1460 2015-05-07 13:55:12 +01:00
Sebastian McKenzie
e83daf87d4 add this.stop() to secondary strict transformer #1465 2015-05-07 08:38:46 +01:00
Sebastian McKenzie
8ed90d3af2 ignore parameter bindings in minification.deadCodeElimination transformer - fixes #1464 2015-05-07 01:58:54 +01:00
Sebastian McKenzie
0bb311f8ce 5.2.16 2015-05-06 16:45:32 +01:00
Sebastian McKenzie
53f0f0302b v5.2.16 2015-05-06 16:44:28 +01:00
Sebastian McKenzie
c25a5d2480 add 5.2.16 changelog 2015-05-06 16:43:21 +01:00
Sebastian McKenzie
fc8540d88a inherit destructuring param replacement ref from original param - fixes #1461 2015-05-06 16:29:54 +01:00
Sebastian McKenzie
31a4195c81 fix incorrect extensions variable reference - fixes #1460 2015-05-06 16:23:15 +01:00
Sebastian McKenzie
bf0e4ede00 pass correct function scope to nameMethod.property when naming class methods - fixes #1456 2015-05-06 16:03:15 +01:00
Sebastian McKenzie
3757bc6b9a reverse method decorators - fixes #1457 2015-05-06 15:57:21 +01:00
Sebastian McKenzie
2e01f220da Merge branch 'master' of github.com:babel/babel 2015-05-06 15:44:05 +01:00
Sebastian McKenzie
8ae4e1fdf2 add --harmony_rest_parameters flag to babel-node - fixes #1446 2015-05-06 15:43:51 +01:00
Sebastian McKenzie
f6219ec15a Merge pull request #1455 from monsanto/fix-async-constructor
Disallow async constructors
2015-05-06 15:12:12 +01:00
Christopher Monsanto
6a82eb5a5c disallow async constructors -- fixes #1454 2015-05-06 02:50:11 -04:00
Sebastian McKenzie
a241300ff1 force plugins to be ran at all times - fixes #1450 2015-05-06 01:14:17 +01:00
Sebastian McKenzie
d5548a6ff9 5.2.15 2015-05-05 15:41:57 +01:00
Sebastian McKenzie
ba6cb112c3 v5.2.15 2015-05-05 15:41:00 +01:00
Sebastian McKenzie
8f1bb84930 add 5.2.15 changelog 2015-05-05 15:39:05 +01:00
Sebastian McKenzie
235726eee6 remove unnecessary descriptor.initializer check 2015-05-05 15:38:17 +01:00
Sebastian McKenzie
08183ef490 don't add descriptor if we can't find it 2015-05-05 15:37:24 +01:00
Sebastian McKenzie
dc6fc3b30a fix browser-polyfill.js post-make publish purging 2015-05-05 15:37:11 +01:00
Sebastian McKenzie
76f2eb5684 5.2.14 2015-05-05 15:14:59 +01:00
Sebastian McKenzie
4f33687957 v5.2.14 2015-05-05 15:12:19 +01:00
Sebastian McKenzie
74f37fe0a3 expose unminified and minified builds of dist scripts - fixes #1444 2015-05-05 15:11:00 +01:00
Sebastian McKenzie
cc5e4bce52 fix object/property decorator interop 2015-05-05 14:42:41 +01:00
Sebastian McKenzie
f441a7cae8 don't do pretty variable declaration formatting if retainLines is enabled 2015-05-05 14:04:51 +01:00
Sebastian McKenzie
fc2be81c43 expose retainLines option to CLI 2015-05-05 14:04:36 +01:00
Sebastian McKenzie
1277a8f67f 5.2.13 2015-05-05 08:58:35 +01:00
Sebastian McKenzie
86c6d4e769 v5.2.13 2015-05-05 08:57:41 +01:00
Sebastian McKenzie
bf2d527cfe upgrade esquery 2015-05-05 08:56:58 +01:00
Sebastian McKenzie
6b59ea8eac add 5.2.13 changelog 2015-05-05 08:56:28 +01:00
Sebastian McKenzie
72e3cb9243 trigger a reference for export declarations 2015-05-05 08:54:51 +01:00
Sebastian McKenzie
5e5ede6058 move down _modules transformer 2015-05-05 08:54:38 +01:00
Sebastian McKenzie
d25944ea1f move utility transformers to top - fixes #1440 2015-05-05 08:39:46 +01:00
Sebastian McKenzie
fce2aa8fa3 add support for esquery 2015-05-05 03:21:31 +01:00
Sebastian McKenzie
0112c63779 consolidate the concept of "virtual types" 2015-05-05 02:33:49 +01:00
Sebastian McKenzie
6a4e93bf0f make visitor validation more anal, add node type wrappers, add mixin support to visitor explosion, allow visitor entrance/exit to provide an array of callbacks to use rather than limiting it to a single callback 2015-05-05 01:44:01 +01:00
Sebastian McKenzie
4328e920d2 5.2.12 2015-05-05 00:15:48 +01:00
Lukáš Mladý
6491018c21 Add failing tests that document ES 6 generators bug 2015-04-08 14:14:45 +02:00
370 changed files with 6109 additions and 3649 deletions

View File

@@ -3,18 +3,21 @@
"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,
"comma-dangle": 0,
"no-use-before-define": 0,
"no-empty": 0,
"new-parens": 0,
"no-cond-assign": 0
"no-cond-assign": 0,
"no-fallthrough": 0,
"new-cap": 0,
"no-loop-func": 0,
"no-unreachable": 0
},
"env": {
"node": true

14
.gitignore vendored
View File

@@ -8,10 +8,10 @@ test/core/tmp
/browser.js
/browser-polyfill.js
/runtime.js
coverage
dist
.package.json
packages/babel-runtime/core-js
packages/babel-runtime/helpers/*.js
packages/babel-runtime/regenerator/*.js
lib
/coverage
/dist
/.package.json
/packages/babel-runtime/core-js
/packages/babel-runtime/helpers/*.js
/packages/babel-runtime/regenerator/*.js
/lib

3
.gitmodules vendored
View File

@@ -1,6 +1,3 @@
[submodule "vendor/traceur"]
path = vendor/traceur
url = https://github.com/google/traceur-compiler
[submodule "vendor/compat-table"]
path = vendor/compat-table
url = https://github.com/kangax/compat-table

View File

@@ -13,6 +13,207 @@ _Note: Gaps between patch versions are faulty/broken releases._
See [CHANGELOG - 6to5](CHANGELOG-6to5.md) for the pre-4.0.0 version changelog.
## 5.5.3
* **Bug Fix**
* Fix weird state bug when traversing overa `node` `ClassProperty` instead of `path` in the `es6.classes` transformer.
## 5.5.2
* **Bug Fix**
* Fix `NodePath#isPure` on `Property` nodes.
* Use cwd instead of entry file directory when working out relative directory for `babel/register`.
* **Internal**
* Add scary warning for those few who choose to use the WIP experimental transformers.
## 5.5.1
* **Bug Fix**
* Remove `ClassProperty` nodes always in the `Flow` transformer. This is fine now since class properties aren't supported in any engine that supports classes but the `es7.classProperties` transformer will need to be updated in the future to desugar to ES6 classes instead of relying on the `es6.classes` transformer from being ran.
## 5.5.0
* **Bug Fix**
* Allow pushing declarations to `SwitchStatement`s.
* Fix `minification.removeDebugger` to remove `DebuggerStatement`s rather than `ExpressionStatement`s with an identifier of `debugger`.
* Check LHS in `ForInStatement` and `ForOfStatement` for constant violations.
* Register function `id` as a reference when naming methods to avoid collisions.
* Support key literals when checking for the existence of `displayName` property when attempting to add it for `React.createClass`.
* Remove `ExportDefaultSpecifier` check from `t.isDefaultSpecifier`.
* Don't consider `JSXIdentifier` HTML tag identifiers to be references.
* **Polish**
* Update `minification.deadCodeElimination` transformer to remove all statements after completion statements.
* Update `minification.deadCodeElimination` transformer to not inline single used bindings that exist in different scopes.
* When performing Istanbul interop in `babel/register`, add the auxiliary comment `"istanbul ignore text"` to get more accurate coverage.
* Add `--nolazy` argument to `babel-node`.
* Add support for `cluster` forking.
* Perform scope tracking in a single pass instead of multiple.
* Smarten up type inferrence and resolution to support the whole array of language constructs.
* Optimise module metadata retrieval into a single pass.
* Ignore trailing commas when inferring newlines.
* Rename `minification.inlineExpressions` transformer to `minification.constantFolding`.
* Check path relative to entry file when checking to see if we're inside `node_modules` when using `babel/register`.
* Upgrade `regenerator`.
## 5.4.7
* **Bug Fix**
* Don't consider `JSXAttribute` `names` to be valid `ReferencedIdentifier`s.
## 5.4.6
* **Bug Fix**
* Fix `spec.functionName` transformer incorrectly attempting to rename a binding that doesn't exist as it's a global.
* **Internal**
* Deprecate custom module formatters.
## 5.4.5
* **Bug Fix**
* Add `JSXIdentifier` as a valid `ReferencedIdentifier` visitor virtual type.
* Ignore `CallExpression` `_prettyCall` when the `retainLines` option is enabled.
* Inherit comments to new declaration node when exploding module declarations.
* Fix `es6.tailCall` transformer failing on calls that exceed the max parameters of the function.
## 5.4.4
* **Bug Fix**
* Fix bug where replacing variable declarations in the head of a `for` loop would turn them into `ExpressionStatement`s.
* Fix renaming of assignment expressions that were non-identifiers ie. patterns.
* Force space before `class` `id` to avoid breaking named classes when using `compact` mode.
* Add assignment pattern explosion to avoid initial duplicate nodes.
* Ignore this and arguments when performing TCO on shadowed functions.
* **Polish**
* Rename `sourceMapName` option to `sourceMapTarget`. Thanks [@getify](https://github.com/getify)!
* Better detection of completion records, ignore those in `Function`s.
* Clarified descriptions of the options that are enabled by default.
* Resolve `\`babel-plugin-${name}\`` plugin names **before** just checking the `name`. Thanks [@jquense](https://github.com/jquense)!
* Update AMD module formatter to add import default remapping.
## 5.4.3
* **Bug Fix**
* Fix `module` being incorrectly rewritten when used as in an export declaration.
* When performing single-reference inlining, ensure that the single reference isn't a child of the binding itself.
* Fix a bug in `minification.deadCodeElimination` where a new binding instance was being created for local class bindings instead of just inheriting the parent one.
* Fix bug with paren printing in `compact` and `retainLines` mode where a left paren was already printed before catching up.
* **Internal**
* Handle contexts for paths much better. This will ensure that the path node location info is in sync.
## 5.4.2
* **Polish**
* `ignore` and `only` patterns are now **very** liberal. The pattern can now exist anywhere in the path.
## 5.4.1
* **Bug Fix**
* Add missing `slash` dependency. Thanks [@browncolyn](https://github.com/browncolyn)!
* **Polish**
* Clean up `shouldIgnore` algorithm to work how you'd expect rather than being a hacky piece of shit. It now crawls the entire path, checking each section of it against the input ignore/only patterns. This means that the pattern `foo` will ignore the paths `foo/bar.js`, `bar/foo` etc.
## 5.4.0
* **New Feature**
* Added [function bind syntax](https://github.com/zenparsing/es-function-bind) behind stage 0. Thanks [@RReverser](https://github.com/rreverser)!
* Added `env` option. Especially handy when using the `.babelrc`.
* **Bug Fix**
* Fix files not properly being ignored when `babel.transform` ignores them when using `$ babel`.
* Fix scope tracking registering loop head bindings to their `VariableDeclaration` instead of `VariableDeclarator`.
* **Polish**
* Normalise path separators for souce map paths when using `$ babel`.
* Rework `PathHoister` to ignore global references and to not deopt on reassignments to referenced bindings, instead it tries to hoist to the highest scope.
* Added missing exponential operator inlining. Thanks [@nkt](https://github.com/nkt)!
* Optimise `regenerator` transformer. Thanks [@benjamn](https://github.com/benjamn)!
## 5.3.3
* **Bug Fix**
* Fix `minification.deadCodeElimination` transformer incorrectly trying to inline import declarations.
* Fix `minification.inlineExpression` transformer getting into an infinite loop.
## 5.3.2
* **Bug Fix**
* Fix patterns not being considered when hoisting variables in the `es6.blockScoping` transformer.
## 5.3.1
* **Bug Fix**
* Fix unique export specifiers not being cloned when exploding class and function exports,
* **Polish**
* Turn import remaps to sequence expressions to remove their context and improve performance.
## 5.3.0
**Speeeeeeed**
![gifs lol](https://31.media.tumblr.com/568205a0e37ae15eca510fa639589a59/tumblr_n8kw8kpcSb1sg6cg8o1_500.gif)
* **Spec Compliancy**
* Allow trailing param commas for methods when using the `es7.trailingCommas` transformer.
* **Bug Fix**
* Fix `es6.blockScoping` transformer not properly ignoring `break` in `SwitchCase`.
* Fix lookahead context saving to avoid weird tokenizer state.
* Explode duplicate identifiers in export/import specifiers and property shorthand to create unique objects.
* Skip loose mode for class methods when they have decorators.
* When removing nodes, share their comments with their siblings.
* Properly hoist temp param declarations when doing TCO.
* **Internal**
* Add `--harmony_generators` flag to `$ babel-node`.
* Internal AST traversals have been minimised **drastically**. Transformers have been grouped together which means entire tree traversals are much fewer. Visiting nodes is now also skipped if the traversal context can detect that the handler is a noop. This sames precious cycles as it avoids constructing traversal paths and creating a new traversal context. See issues [#1472](https://github.com/babel/babel/issues/1472) and [#1486](https://github.com/babel/babel/issues/1486) for related discussion.
* **Polish**
* Move many `utility` transformers to `minification`.
## 5.2.17
* **Bug Fix**
* Fix auxiliary comments not properly being attached to function declaration helpers.
* Add `Super` node type to `ast-types` patch.
* Ignore parameter bindings when attempting to inline them in the `minification.deadCodeElimination` transformer.
* Correct `extensions` arguments when using the Babel CLI.
## 5.2.16
* **Bug Fix**
* Fix plugins being disabled when using the whitelist.
* Fix correct function scope being passed to `nameMethod.property` when inferring the function name for class methods.
* Fix incorrect extensions reference causing weird issues when using the Babel CLI.
* Fix destructuring param reference replacements not inheriting from their original param.
* **Spec Compliancy**
* Fix order that method decorators are ran in.
## 5.2.15
* **Bug Fix**
* Fix initializer descriptor add attempt if it doesn't exist.
## 5.2.14
* **Bug Fix**
* Fix bug with initializer decorators where the descriptors weren't being defined if there was no `initializer` property.
* **Internal**
* Expose `retainLines` option to CLI.
* Fix `retainLines` option not being taken into consideration when doing multiple variable declaration declarators generation.
* Expose minified and unminified copies of dist scripts.
## 5.2.13
* **Bug Fix**
* Fix `ExportDeclaration`s being incorrectly removed when using the `utility.deadCodeElimination` transformer.
* Fix position of `utility` transformers.
* **New Feature**
* Add built-in `esquery` support.
* **Internal**
* Consolidate notion of "virtual types".
## 5.2.12
* **Polish**
* Make UID generation based on module declarations **much** nicer.
* **Internal**
* Remove internal check for traversal path replacement of self. This is a pattern that **could** come up in the wild and it could lead to pretty nasty code and may lead to internal regressions as the test coverage isn't 100% :( Instead, just put it in the fast path.
## 5.2.11
* **Internal**

View File

@@ -1,3 +1,7 @@
# NOTE: BEFORE OPENING AN ISSUE PLEASE SEE THE [README](https://github.com/babel/babel#readme).
----
<p align="center">
<strong><a href="#setup">Setup</a></strong>
|
@@ -21,6 +25,9 @@ contributing, please read the
## Developing
>Note: Babel moves fast. Only the latest release is guaranteed to build correctly.
>Older releases are not officially supported. If you attempt to build them, do that at your own risk.
#### Setup
```sh
@@ -79,7 +86,6 @@ your [`$PATH`](http://unix.stackexchange.com/questions/26047/how-to-correctly-ad
* Ensure the test are passing (`make test`)
* Create new pull request explaining your proposed change or reference an issue in your commit message
#### Dependencies
+ [ast-types](http://ghub.io/ast-types) This is required to monkeypatch regenerators AST definitions. Could be improved in the future.

View File

@@ -22,6 +22,9 @@ watch-core: clean-core
clean-core:
rm -rf lib
lint:
eslint src/babel
build:
mkdir -p dist
make build-core
@@ -61,7 +64,7 @@ test-cov:
test-parser:
node test/acorn/run.js
test-travis: bootstrap build test
test-travis: bootstrap lint build test
test-browser:
mkdir -p dist
@@ -73,7 +76,7 @@ test-browser:
test -n "`which open`" && open test/browser.html
publish:
publish: lint
git pull --rebase
make test
@@ -82,9 +85,15 @@ publish:
npm version $$version --message "v%s"
make build
cp dist/babel.min.js browser.js
cp dist/polyfill.min.js browser-polyfill.js
cp dist/external-helpers.min.js external-helpers.js
cp dist/babel.js browser.js
cp dist/babel.min.js browser.min.js
cp dist/polyfill.js browser-polyfill.js
cp dist/polyfill.min.js browser-polyfill.min.js
cp dist/external-helpers.js external-helpers.js
cp dist/external-helpers.min.js external-helpers.min.js
node tools/cache-templates
test -f templates.json
@@ -96,7 +105,7 @@ publish:
make publish-cli
make publish-runtime
rm -rf templates.json browser.js browser-polyfill.js external-helpers.js
rm -rf templates.json browser.js browser.min.js browser-polyfill.js browser-polyfill.min.js external-helpers.js external-helpers.min.js
publish-runtime:
cd packages; \
@@ -116,5 +125,4 @@ bootstrap:
npm link
cd packages/babel-cli && npm install && npm link && npm link babel-core
git submodule update --init
cd vendor/compat-table && npm install object-assign
make build

View File

@@ -12,6 +12,10 @@
For questions and support please visit the <a href="https://gitter.im/babel/babel">gitter room</a> or <a href="http://stackoverflow.com/questions/tagged/babeljs">StackOverflow</a>. The Babel issue tracker is <strong>exclusively</strong> for bug reports and feature requests.
</p>
<p align="center">
Issues without instructions to reproduce <strong>will be immediately closed<strong>.
</p>
<p align="center">
For documentation and website issues please visit the <a href="https://github.com/babel/babel.github.io">babel.github.io</a> repo.
</p>

View File

@@ -1,9 +1,10 @@
{
"name": "babel-core",
"description": "Turn ES6 code into readable vanilla ES5 with source maps",
"version": "5.2.12",
"description": "A compiler for writing next generation JavaScript",
"version": "5.5.3",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/",
"license": "MIT",
"repository": "babel/babel",
"main": "lib/babel/api/node.js",
"browser": {
@@ -35,10 +36,12 @@
"core-js": "^0.9.0",
"debug": "^2.1.1",
"detect-indent": "^3.0.0",
"estraverse": "^3.0.0",
"esquery": "^0.4.0",
"estraverse": "^4.0.0",
"esutils": "^2.0.0",
"fs-readdir-recursive": "^0.1.0",
"globals": "^6.4.0",
"home-or-tmp": "^1.0.0",
"is-integer": "^1.0.4",
"js-tokens": "1.0.0",
"leven": "^1.0.1",
@@ -48,7 +51,7 @@
"output-file-sync": "^1.1.0",
"path-is-absolute": "^1.0.0",
"private": "^0.1.6",
"regenerator": "^0.8.20",
"regenerator": "^0.8.28",
"regexpu": "^1.1.2",
"repeating": "^1.1.2",
"resolve": "^1.1.6",
@@ -58,15 +61,14 @@
"source-map-support": "^0.2.10",
"strip-json-comments": "^1.0.2",
"to-fast-properties": "^1.0.0",
"trim-right": "^1.0.0",
"user-home": "^1.1.1"
"trim-right": "^1.0.0"
},
"devDependencies": {
"babel": "5.1.13",
"babel": "5.3.1",
"browserify": "^9.0.8",
"chai": "^2.2.0",
"eslint": "^0.18.0",
"babel-eslint": "^2.0.0",
"eslint": "^0.21.2",
"babel-eslint": "^3.1.9",
"esvalid": "^1.1.0",
"istanbul": "^0.3.5",
"matcha": "^0.6.0",

View File

@@ -107,6 +107,7 @@ if (program.eval || program.print) {
// add back on node and concat the sliced args
process.argv = ["node"].concat(args);
process.execArgv.unshift(__filename);
Module.runMain();
} else {

View File

@@ -55,6 +55,8 @@ babelArgs.forEach(function(arg){
case "--harmony_classes":
case "--harmony_object_literals":
case "--harmony_templates":
case "--harmony_rest_parameters":
case "--harmony_generators":
case "--compiled_keyed_generic_loads":
case "--pretenuring_call_new":
case "--allocation_site_pretenuring":
@@ -410,6 +412,7 @@ babelArgs.forEach(function(arg){
case "--prof_auto":
case "--prof_lazy":
case "--sliding_state_window":
case "--nolazy":
args.unshift(arg);
break;

View File

@@ -1,5 +1,6 @@
var outputFileSync = require("output-file-sync");
var chokidar = require("chokidar");
var slash = require("slash");
var path = require("path");
var util = require("./util");
var fs = require("fs");
@@ -13,8 +14,10 @@ module.exports = function (commander, filenames, opts) {
var dest = path.join(commander.outDir, relative);
var data = util.compile(src, {
sourceFileName: path.relative(dest + "/..", src)
sourceFileName: slash(path.relative(dest + "/..", src)),
sourceMapTarget: path.basename(relative)
});
if (data.ignored) return;
if (commander.sourceMaps && commander.sourceMaps !== "inline") {
var mapLoc = dest + ".map";

View File

@@ -1,6 +1,7 @@
var convertSourceMap = require("convert-source-map");
var sourceMap = require("source-map");
var chokidar = require("chokidar");
var slash = require("slash");
var path = require("path");
var util = require("./util");
var fs = require("fs");
@@ -15,7 +16,8 @@ module.exports = function (commander, filenames, opts) {
var buildResult = function () {
var map = new sourceMap.SourceMapGenerator({
file: commander.outFile || "stdout"
file: path.basename(commander.outFile) || "stdout",
sourceRoot: opts.sourceRoot
});
var code = "";
@@ -27,11 +29,12 @@ module.exports = function (commander, filenames, opts) {
if (result.map) {
var consumer = new sourceMap.SourceMapConsumer(result.map);
var sourceFilename = filename;
var sourceFilename = filename;
if (commander.outFile) {
sourceFilename = path.relative(path.dirname(commander.outFile), sourceFilename);
}
sourceFilename = slash(sourceFilename);
map._sources.add(sourceFilename);
map.setSourceContent(sourceFilename, result.actual);
@@ -114,7 +117,9 @@ module.exports = function (commander, filenames, opts) {
_.each(_filenames, function (filename) {
if (util.shouldIgnore(filename)) return;
results.push(util.compile(filename));
var data = util.compile(filename);
if (data.ignored) return;
results.push(data);
});
output();

View File

@@ -70,10 +70,18 @@ commander.parse(process.argv);
//
if (commander.extensions) {
commander.extensions = util.arrayify(commander.extensions);
}
//
var errors = [];
var filenames = commander.args.reduce(function (globbed, input) {
return globbed.concat(glob.sync(input));
var files = glob.sync(input);
if (!files.length) files = [input];
return globbed.concat(files);
}, []);
each(filenames, function (filename) {

View File

@@ -1,13 +1,14 @@
{
"name": "babel",
"description": "Turn ES6 code into readable vanilla ES5 with source maps",
"version": "5.2.11",
"version": "5.5.2",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/",
"license": "MIT",
"repository": "babel/babel",
"preferGlobal": true,
"dependencies": {
"babel-core": "^5.2.11",
"babel-core": "^5.5.2",
"chokidar": "^1.0.0",
"commander": "^2.6.0",
"convert-source-map": "^1.1.0",
@@ -16,7 +17,8 @@
"lodash": "^3.2.0",
"output-file-sync": "^1.1.0",
"path-is-absolute": "^1.0.0",
"source-map": "^0.4.0"
"source-map": "^0.4.0",
"slash": "^1.0.0"
},
"bin": {
"babel": "./bin/babel/index.js",

View File

@@ -1,7 +1,8 @@
{
"name": "babel-runtime",
"description": "babel selfContained runtime",
"version": "5.2.11",
"version": "5.5.2",
"license": "MIT",
"repository": "babel/babel",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"dependencies": {

48
sebmck-bjs.nfo Normal file
View File

@@ -0,0 +1,48 @@
====== ==========M=
============= == ======O= ======= MM ==
M==+=== ==M === ==== == === ==
=D === === ====MM ==M ==M ==M ===
===M ====M ==== =D ===M === === ==
==7 ====M ==M == ======== =========M ==M
=========== ======M ===MMM === ==M ==
=======MM==========MM== ==M ==M=== ==
==M === M== ==M == === === =D =
==M ===+ == == == ==$M =========== ============M
=== ====M == ==M ===M== ====?MMMM M M
== ===== ==M == ==MM M
==M===M=M =M =MM M M
==MM=M ==
MMM =M
M
> ú B ú A ú B ú E ú L ú <
ÕÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÑÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ͸
³ SOFTWARE .. : JavaScript Compiler ³ COMPANY ... : N/A ³
³ SUPPLIER .. : N/A ³ CRACKER ... : Sebastian McKenzie ³
³ RATING .... : depends.. ³ PACKAGER .. : Sebastian McKenzie ³
³ ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ ³
³ GRAFIX .... : - ³ SOUND ..... : - ³
ÔÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÏÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ;
Babel is a JavaScript compiler and transformation platform for writing NeXt
GeNeRaTiOn JavaScript.
ÆÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÏÍÍÍÍÍÍÍÍÍÍÍÍÍÍÏÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÏÍÍÍÍÍÍÍÏÍÍÍÍÍÍÍÍÍÍÍ͵
³ :: Greets :: ³
³ ³
³ sebmck, thejameskyle, RReverser, zloirock, monsanto, gaearon, zertosh, ³
³ stefanpenner, eventualbuddha, AluisioASG, Apoxx, Couto, dominicbarnes, ³
³ es128, gordonkristan, hkjels, jmeas, josh, loganfsmyth, nightire, ³
³ Rich-Harris, shinnn, shuhei, sindresorhus, tricknotes ³
³ ³
ÔÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ;
-*- JavaScripts for all , All for JavaScripts ! -*-
ÕÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ͸
³ If you want to Contact us, call 555-720-4228, Use the Handle "BABEL" w/ ³
³ password : VISITOR and leave a mail to Sebastian or James. ³
ÔÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ;
-=- We LoVe fun Too! -=-

View File

@@ -153,10 +153,15 @@ pp.flow_parseTypeAlias = function (node) {
node.typeParameters = null
}
var oldInType = this.inType;
this.inType = true;
this.expect(tt.eq)
node.right = this.flow_parseType()
this.inType = oldInType;
this.semicolon()
return this.finishNode(node, "TypeAlias")
@@ -410,6 +415,9 @@ pp.flow_identToTypeAnnotation = function (start, node, id) {
case "boolean":
return this.finishNode(node, "BooleanTypeAnnotation")
case "mixed":
return this.finishNode(node, "MixedTypeAnnotation")
case "number":
return this.finishNode(node, "NumberTypeAnnotation")

View File

@@ -214,7 +214,12 @@ pp.parseExprSubscripts = function(refShorthandDefaultPos) {
}
pp.parseSubscripts = function(base, start, noCalls) {
if (this.eat(tt.dot)) {
if (!noCalls && this.eat(tt.doubleColon)) {
let node = this.startNodeAt(start)
node.object = base
node.callee = this.parseNoCallExpr()
return this.parseSubscripts(this.finishNode(node, "BindExpression"), start, noCalls)
} else if (this.eat(tt.dot)) {
let node = this.startNodeAt(start)
node.object = base
node.property = this.parseIdent(true)
@@ -240,6 +245,13 @@ pp.parseSubscripts = function(base, start, noCalls) {
} return base
}
// Parse a no-call expression (like argument of `new` or `::` operators).
pp.parseNoCallExpr = function() {
let start = this.markPosition()
return this.parseSubscripts(this.parseExprAtom(), start, true)
}
// Parse an atomic expression — either a single token that is an
// expression, an expression started by a keyword like `function` or
// `new`, or an expression wrapped in punctuation like `()`, `[]`,
@@ -262,7 +274,13 @@ pp.parseExprAtom = function(refShorthandDefaultPos) {
if (this.options.features["es7.doExpressions"]) {
let node = this.startNode()
this.next()
var oldInFunction = this.inFunction
var oldLabels = this.labels
this.labels = []
this.inFunction = false
node.body = this.parseBlock()
this.inFunction = oldInFunction
this.labels = oldLabels
return this.finishNode(node, "DoExpression")
}
@@ -363,6 +381,15 @@ pp.parseExprAtom = function(refShorthandDefaultPos) {
case tt.backQuote:
return this.parseTemplate()
case tt.doubleColon:
node = this.startNode()
this.next()
node.object = null
let callee = node.callee = this.parseNoCallExpr()
if (callee.type !== "MemberExpression")
this.raise(callee.start, "Binding should be performed on object property.")
return this.finishNode(node, "BindExpression")
default:
this.unexpected()
}
@@ -472,9 +499,11 @@ pp.parseNew = function() {
this.raise(node.property.start, "The only valid meta property for new is new.target")
return this.finishNode(node, "MetaProperty")
}
let start = this.markPosition()
node.callee = this.parseSubscripts(this.parseExprAtom(), start, true)
if (this.eat(tt.parenL)) node.arguments = this.parseExprList(tt.parenR, false)
node.callee = this.parseNoCallExpr()
if (this.eat(tt.parenL)) node.arguments = this.parseExprList(
tt.parenR,
this.options.features["es7.trailingFunctionCommas"]
)
else node.arguments = empty
return this.finishNode(node, "NewExpression")
}
@@ -484,7 +513,7 @@ pp.parseNew = function() {
pp.parseTemplateElement = function() {
let elem = this.startNode()
elem.value = {
raw: this.input.slice(this.start, this.end),
raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, '\n'),
cooked: this.value
}
this.next()
@@ -632,7 +661,7 @@ pp.parseMethod = function(isGenerator, isAsync) {
let node = this.startNode()
this.initFunction(node, isAsync)
this.expect(tt.parenL)
node.params = this.parseBindingList(tt.parenR, false, false)
node.params = this.parseBindingList(tt.parenR, false, this.options.features["es7.trailingFunctionCommas"])
if (this.options.ecmaVersion >= 6) {
node.generator = isGenerator
}

View File

@@ -14,7 +14,11 @@ var STATE_KEYS = [
"pos",
"end",
"type",
"value"
"value",
"exprAllowed",
"potentialArrowAt",
"currLine",
"input"
];
pp.getState = function () {
@@ -23,6 +27,7 @@ pp.getState = function () {
var key = STATE_KEYS[i]
state[key] = this[key]
}
state.context = this.context.slice()
return state
};

View File

@@ -168,12 +168,6 @@ pp.parseDoStatement = function(node) {
this.labels.push(loopLabel)
node.body = this.parseStatement(false)
this.labels.pop()
if (this.options.features["es7.doExpressions"] && this.type !== tt._while) {
let container = this.startNodeAt(start)
container.expression = this.finishNode(node, "DoExpression")
this.semicolon()
return this.finishNode(container, "ExpressionStatement")
}
this.expect(tt._while)
node.test = this.parseParenExpression()
if (this.options.ecmaVersion >= 6)
@@ -504,7 +498,7 @@ pp.parseClass = function(node, isStatement) {
this.parsePropertyName(method)
}
method.kind = "method"
if (!method.computed && !isGenerator) {
if (!method.computed && !isGenerator && !isAsync) {
if (method.key.type === "Identifier") {
if (this.type !== tt.parenL && (method.key.name === "get" || method.key.name === "set")) {
method.kind = method.key.name
@@ -574,7 +568,7 @@ pp.parseExport = function(node) {
this.parseExportFrom(node)
return this.finishNode(node, "ExportAllDeclaration")
}
} else if (this.isExportDefaultSpecifier()) {
} else if (this.options.features["es7.exportExtensions"] && this.isExportDefaultSpecifier()) {
let specifier = this.startNode()
specifier.exported = this.parseIdent(true)
node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")]

View File

@@ -283,7 +283,7 @@ pp.readToken_lt_gt = function(code) { // '<>'
}
if (next == 33 && code == 60 && this.input.charCodeAt(this.pos + 2) == 45 &&
this.input.charCodeAt(this.pos + 3) == 45) {
if (this.inModule) unexpected()
if (this.inModule) this.unexpected()
// `<!--`, an XML-style comment that should be interpreted as a line comment
this.skipLineComment(4)
this.skipSpace()
@@ -320,7 +320,13 @@ pp.getTokenFromCode = function(code) {
case 93: ++this.pos; return this.finishToken(tt.bracketR)
case 123: ++this.pos; return this.finishToken(tt.braceL)
case 125: ++this.pos; return this.finishToken(tt.braceR)
case 58: ++this.pos; return this.finishToken(tt.colon)
case 58:
if (this.options.features["es7.functionBind"] && this.input.charCodeAt(this.pos + 1) === 58)
return this.finishOp(tt.doubleColon, 2)
++this.pos
return this.finishToken(tt.colon)
case 63: ++this.pos; return this.finishToken(tt.question)
case 64: ++this.pos; return this.finishToken(tt.at)
@@ -571,11 +577,15 @@ pp.readTmplToken = function() {
} else if (isNewLine(ch)) {
out += this.input.slice(chunkStart, this.pos)
++this.pos
if (ch === 13 && this.input.charCodeAt(this.pos) === 10) {
++this.pos
out += "\n"
} else {
out += String.fromCharCode(ch)
switch (ch) {
case 13:
if (this.input.charCodeAt(this.pos) === 10) ++this.pos;
case 10:
out += "\n";
break;
default:
out += String.fromCharCode(ch);
break;
}
if (this.options.locations) {
++this.curLine

View File

@@ -54,6 +54,7 @@ export const types = {
comma: new TokenType(",", beforeExpr),
semi: new TokenType(";", beforeExpr),
colon: new TokenType(":", beforeExpr),
doubleColon: new TokenType("::", beforeExpr),
dot: new TokenType("."),
question: new TokenType("?", beforeExpr),
arrow: new TokenType("=>", beforeExpr),

View File

@@ -1,3 +1,5 @@
/* eslint no-new-func: 0 */
require("./node");
var transform = module.exports = require("../transformation");

View File

@@ -61,8 +61,8 @@ export function parse(code, opts = {}) {
opts.sourceType = "module";
opts.ecmaVersion = Infinity;
opts.plugins = {
flow: true,
jsx: true
jsx: true,
flow: true
};
opts.features = {};

View File

@@ -1,5 +1,5 @@
// required to safely use babel/register within a browserify codebase
export default function () {};
export default function () {}
import "../../polyfill";

View File

@@ -1,9 +1,8 @@
import path from "path";
import os from "os";
import fs from "fs";
import userHome from "user-home";
import homeOrTmp from "home-or-tmp";
const FILENAME = process.env.BABEL_CACHE_PATH || path.join(userHome || os.tmpdir(), ".babel.json");
const FILENAME = process.env.BABEL_CACHE_PATH || path.join(homeOrTmp, ".babel.json");
var data = {};
export function save() {

View File

@@ -6,7 +6,7 @@ import * as babel from "../node";
import each from "lodash/collection/each";
import * as util from "../../util";
import fs from "fs";
import slash from "slash";
import path from "path";
sourceMapSupport.install({
handleUncaughtExceptions: false,
@@ -38,14 +38,20 @@ var only;
var oldHandlers = {};
var maps = {};
var cwd = process.cwd();
var getRelativePath = function (filename){
return path.relative(cwd, filename);
};
var mtime = function (filename) {
return +fs.statSync(filename).mtime;
};
var compile = function (filename) {
var compile = function (filename, opts = {}) {
var result;
var opts = extend({}, transformOpts);
opts = extend(opts, transformOpts);
// this will be done when the file is transformed anyway but we need all
// the options so we can generate the cache key
@@ -53,6 +59,9 @@ var compile = function (filename) {
var cacheKey = `${filename}:${JSON.stringify(opts)}:${babel.version}`;
var env = process.env.BABEL_ENV || process.env.NODE_ENV;
if (env) cacheKey += `:${env}`;
if (cache) {
var cached = cache[cacheKey];
if (cached && cached.mtime === mtime(filename)) {
@@ -79,7 +88,7 @@ var compile = function (filename) {
var shouldIgnore = function (filename) {
if (!ignore && !only) {
return /node_modules/.test(filename);
return getRelativePath(filename).split(path.sep).indexOf("node_modules") >= 0;
} else {
return util.shouldIgnore(filename, ignore || [], only || []);
}
@@ -95,7 +104,9 @@ if (process.env.running_under_istanbul) {
fs.readFileSync = function (filename) {
if (istanbulMonkey[filename]) {
delete istanbulMonkey[filename];
var code = compile(filename);
var code = compile(filename, {
attachAuxiliaryComment: "istanbul ignore next"
});
istanbulMonkey[filename] = true;
return code;
} else {
@@ -161,4 +172,4 @@ export default function (opts = {}) {
delete opts.only;
extend(transformOpts, opts);
};
}

View File

@@ -117,8 +117,9 @@ export default class Buffer {
_removeSpacesAfterLastNewline() {
var lastNewlineIndex = this.buf.lastIndexOf("\n");
if (lastNewlineIndex === -1)
if (lastNewlineIndex === -1) {
return;
}
var index = this.buf.length - 1;
while (index > lastNewlineIndex) {

View File

@@ -1,5 +1,5 @@
export function File(node, print) {
print(node.program);
print.plain(node.program);
}
export function Program(node, print) {

View File

@@ -3,16 +3,16 @@ export function ClassDeclaration(node, print) {
this.push("class");
if (node.id) {
this.space();
print(node.id);
this.push(" ");
print.plain(node.id);
}
print(node.typeParameters);
print.plain(node.typeParameters);
if (node.superClass) {
this.push(" extends ");
print(node.superClass);
print(node.superTypeParameters);
print.plain(node.superClass);
print.plain(node.superTypeParameters);
}
if (node.implements) {
@@ -21,7 +21,7 @@ export function ClassDeclaration(node, print) {
}
this.space();
print(node.body);
print.plain(node.body);
}
export { ClassDeclaration as ClassExpression };
@@ -46,13 +46,13 @@ export function ClassProperty(node, print) {
print.list(node.decorators);
if (node.static) this.push("static ");
print(node.key);
print(node.typeAnnotation);
print.plain(node.key);
print.plain(node.typeAnnotation);
if (node.value) {
this.space();
this.push("=");
this.space();
print(node.value);
print.plain(node.value);
}
this.semicolon();
}

View File

@@ -1,9 +1,9 @@
export function ComprehensionBlock(node, print) {
this.keyword("for");
this.push("(");
print(node.left);
print.plain(node.left);
this.push(" of ");
print(node.right);
print.plain(node.right);
this.push(")");
}
@@ -16,12 +16,12 @@ export function ComprehensionExpression(node, print) {
if (node.filter) {
this.keyword("if");
this.push("(");
print(node.filter);
print.plain(node.filter);
this.push(")");
this.space();
}
print(node.body);
print.plain(node.body);
this.push(node.generator ? ")" : "]");
}

View File

@@ -16,40 +16,40 @@ export function UnaryExpression(node, print) {
this.push(node.operator);
if (hasSpace) this.push(" ");
print(node.argument);
print.plain(node.argument);
}
export function DoExpression(node, print) {
this.push("do");
this.space();
print(node.body);
print.plain(node.body);
}
export function UpdateExpression(node, print) {
if (node.prefix) {
this.push(node.operator);
print(node.argument);
print.plain(node.argument);
} else {
print(node.argument);
print.plain(node.argument);
this.push(node.operator);
}
}
export function ConditionalExpression(node, print) {
print(node.test);
print.plain(node.test);
this.space();
this.push("?");
this.space();
print(node.consequent);
print.plain(node.consequent);
this.space();
this.push(":");
this.space();
print(node.alternate);
print.plain(node.alternate);
}
export function NewExpression(node, print) {
this.push("new ");
print(node.callee);
print.plain(node.callee);
this.push("(");
print.list(node.arguments);
this.push(")");
@@ -69,17 +69,19 @@ export function Super() {
export function Decorator(node, print) {
this.push("@");
print(node.expression);
print.plain(node.expression);
}
export function CallExpression(node, print) {
print(node.callee);
print.plain(node.callee);
this.push("(");
var separator = ",";
if (node._prettyCall) {
var isPrettyCall = node._prettyCall && !this.format.retainLines;
if (isPrettyCall) {
separator += "\n";
this.newline();
this.indent();
@@ -89,7 +91,7 @@ export function CallExpression(node, print) {
print.list(node.arguments, { separator: separator });
if (node._prettyCall) {
if (isPrettyCall) {
this.newline();
this.dedent();
}
@@ -106,8 +108,8 @@ var buildYieldAwait = function (keyword) {
}
if (node.argument) {
this.space();
print(node.argument);
this.push(" ");
print.plain(node.argument);
}
};
};
@@ -120,17 +122,23 @@ export function EmptyStatement() {
}
export function ExpressionStatement(node, print) {
print(node.expression);
print.plain(node.expression);
this.semicolon();
}
export function AssignmentExpression(node, print) {
// todo: add cases where the spaces can be dropped when in compact mode
print(node.left);
print.plain(node.left);
this.push(" ");
this.push(node.operator);
this.push(" ");
print(node.right);
print.plain(node.right);
}
export function BindExpression(node, print) {
print.plain(node.object);
this.push("::");
print.plain(node.callee);
}
export {
@@ -143,7 +151,7 @@ var SCIENTIFIC_NOTATION = /e/i;
export function MemberExpression(node, print) {
var obj = node.object;
print(obj);
print.plain(obj);
if (!node.computed && t.isMemberExpression(node.property)) {
throw new TypeError("Got a MemberExpression for MemberExpression property");
@@ -156,7 +164,7 @@ export function MemberExpression(node, print) {
if (computed) {
this.push("[");
print(node.property);
print.plain(node.property);
this.push("]");
} else {
// 5..toFixed(2);
@@ -165,12 +173,12 @@ export function MemberExpression(node, print) {
}
this.push(".");
print(node.property);
print.plain(node.property);
}
}
export function MetaProperty(node, print) {
print(node.meta);
print.plain(node.meta);
this.push(".");
print(node.property);
print.plain(node.property);
}

View File

@@ -5,7 +5,7 @@ export function AnyTypeAnnotation() {
}
export function ArrayTypeAnnotation(node, print) {
print(node.elementType);
print.plain(node.elementType);
this.push("[");
this.push("]");
}
@@ -21,27 +21,27 @@ export function DeclareClass(node, print) {
export function DeclareFunction(node, print) {
this.push("declare function ");
print(node.id);
print(node.id.typeAnnotation.typeAnnotation);
print.plain(node.id);
print.plain(node.id.typeAnnotation.typeAnnotation);
this.semicolon();
}
export function DeclareModule(node, print) {
this.push("declare module ");
print(node.id);
print.plain(node.id);
this.space();
print(node.body);
print.plain(node.body);
}
export function DeclareVariable(node, print) {
this.push("declare var ");
print(node.id);
print(node.id.typeAnnotation);
print.plain(node.id);
print.plain(node.id.typeAnnotation);
this.semicolon();
}
export function FunctionTypeAnnotation(node, print, parent) {
print(node.typeParameters);
print.plain(node.typeParameters);
this.push("(");
print.list(node.params);
@@ -51,7 +51,7 @@ export function FunctionTypeAnnotation(node, print, parent) {
this.space();
}
this.push("...");
print(node.rest);
print.plain(node.rest);
}
this.push(")");
@@ -65,33 +65,33 @@ export function FunctionTypeAnnotation(node, print, parent) {
}
this.space();
print(node.returnType);
print.plain(node.returnType);
}
export function FunctionTypeParam(node, print) {
print(node.name);
print.plain(node.name);
if (node.optional) this.push("?");
this.push(":");
this.space();
print(node.typeAnnotation);
print.plain(node.typeAnnotation);
}
export function InterfaceExtends(node, print) {
print(node.id);
print(node.typeParameters);
print.plain(node.id);
print.plain(node.typeParameters);
}
export { InterfaceExtends as ClassImplements, InterfaceExtends as GenericTypeAnnotation };
export function _interfaceish(node, print) {
print(node.id);
print(node.typeParameters);
print.plain(node.id);
print.plain(node.typeParameters);
if (node.extends.length) {
this.push(" extends ");
print.join(node.extends, { separator: ", " });
}
this.space();
print(node.body);
print.plain(node.body);
}
export function InterfaceDeclaration(node, print) {
@@ -103,9 +103,13 @@ export function IntersectionTypeAnnotation(node, print) {
print.join(node.types, { separator: " & " });
}
export function MixedTypeAnnotation() {
this.push("mixed");
}
export function NullableTypeAnnotation(node, print) {
this.push("?");
print(node.typeAnnotation);
print.plain(node.typeAnnotation);
}
export function NumberTypeAnnotation() {
@@ -128,17 +132,17 @@ export function TupleTypeAnnotation(node, print) {
export function TypeofTypeAnnotation(node, print) {
this.push("typeof ");
print(node.argument);
print.plain(node.argument);
}
export function TypeAlias(node, print) {
this.push("type ");
print(node.id);
print(node.typeParameters);
print.plain(node.id);
print.plain(node.typeParameters);
this.space();
this.push("=");
this.space();
print(node.right);
print.plain(node.right);
this.semicolon();
}
@@ -146,7 +150,7 @@ export function TypeAnnotation(node, print) {
this.push(":");
this.space();
if (node.optional) this.push("?");
print(node.typeAnnotation);
print.plain(node.typeAnnotation);
}
export function TypeParameterInstantiation(node, print) {
@@ -183,37 +187,37 @@ export function ObjectTypeAnnotation(node, print) {
export function ObjectTypeCallProperty(node, print) {
if (node.static) this.push("static ");
print(node.value);
print.plain(node.value);
}
export function ObjectTypeIndexer(node, print) {
if (node.static) this.push("static ");
this.push("[");
print(node.id);
print.plain(node.id);
this.push(":");
this.space();
print(node.key);
print.plain(node.key);
this.push("]");
this.push(":");
this.space();
print(node.value);
print.plain(node.value);
}
export function ObjectTypeProperty(node, print) {
if (node.static) this.push("static ");
print(node.key);
print.plain(node.key);
if (node.optional) this.push("?");
if (!t.isFunctionTypeAnnotation(node.value)) {
this.push(":");
this.space();
}
print(node.value);
print.plain(node.value);
}
export function QualifiedTypeIdentifier(node, print) {
print(node.qualification);
print.plain(node.qualification);
this.push(".");
print(node.id);
print.plain(node.id);
}
export function UnionTypeAnnotation(node, print) {
@@ -222,8 +226,8 @@ export function UnionTypeAnnotation(node, print) {
export function TypeCastExpression(node, print) {
this.push("(");
print(node.expression);
print(node.typeAnnotation);
print.plain(node.expression);
print.plain(node.typeAnnotation);
this.push(")");
}

View File

@@ -1,11 +1,10 @@
import each from "lodash/collection/each";
import * as t from "../../types";
export function JSXAttribute(node, print) {
print(node.name);
print.plain(node.name);
if (node.value) {
this.push("=");
print(node.value);
print.plain(node.value);
}
}
@@ -14,50 +13,50 @@ export function JSXIdentifier(node) {
}
export function JSXNamespacedName(node, print) {
print(node.namespace);
print.plain(node.namespace);
this.push(":");
print(node.name);
print.plain(node.name);
}
export function JSXMemberExpression(node, print) {
print(node.object);
print.plain(node.object);
this.push(".");
print(node.property);
print.plain(node.property);
}
export function JSXSpreadAttribute(node, print) {
this.push("{...");
print(node.argument);
print.plain(node.argument);
this.push("}");
}
export function JSXExpressionContainer(node, print) {
this.push("{");
print(node.expression);
print.plain(node.expression);
this.push("}");
}
export function JSXElement(node, print) {
var open = node.openingElement;
print(open);
print.plain(open);
if (open.selfClosing) return;
this.indent();
each(node.children, (child) => {
for (var child of (node.children: Array)) {
if (t.isLiteral(child)) {
this.push(child.value, true);
} else {
print(child);
print.plain(child);
}
});
}
this.dedent();
print(node.closingElement);
print.plain(node.closingElement);
}
export function JSXOpeningElement(node, print) {
this.push("<");
print(node.name);
print.plain(node.name);
if (node.attributes.length > 0) {
this.push(" ");
print.join(node.attributes, { separator: " " });
@@ -67,7 +66,7 @@ export function JSXOpeningElement(node, print) {
export function JSXClosingElement(node, print) {
this.push("</");
print(node.name);
print.plain(node.name);
this.push(">");
}

View File

@@ -1,18 +1,18 @@
import * as t from "../../types";
export function _params(node, print) {
print(node.typeParameters);
print.plain(node.typeParameters);
this.push("(");
print.list(node.params, {
iterator: (node) =>{
if (node.optional) this.push("?");
print(node.typeAnnotation);
print.plain(node.typeAnnotation);
}
});
this.push(")");
if (node.returnType) {
print(node.returnType);
print.plain(node.returnType);
}
}
@@ -35,15 +35,15 @@ export function _method(node, print) {
if (node.computed) {
this.push("[");
print(key);
print.plain(key);
this.push("]");
} else {
print(key);
print.plain(key);
}
this._params(value, print);
this.push(" ");
print(value.body);
print.plain(value.body);
}
export function FunctionExpression(node, print) {
@@ -53,14 +53,14 @@ export function FunctionExpression(node, print) {
if (node.id) {
this.push(" ");
print(node.id);
print.plain(node.id);
} else {
this.space();
}
this._params(node, print);
this.space();
print(node.body);
print.plain(node.body);
}
export { FunctionExpression as FunctionDeclaration };
@@ -69,7 +69,7 @@ export function ArrowFunctionExpression(node, print) {
if (node.async) this.push("async ");
if (node.params.length === 1 && t.isIdentifier(node.params[0])) {
print(node.params[0]);
print.plain(node.params[0]);
} else {
this._params(node, print);
}
@@ -82,7 +82,7 @@ export function ArrowFunctionExpression(node, print) {
this.push("(");
}
print(node.body);
print.plain(node.body);
if (bodyNeedsParens) {
this.push(")");

View File

@@ -1,43 +1,42 @@
import each from "lodash/collection/each";
import * as t from "../../types";
export function ImportSpecifier(node, print) {
print(node.imported);
if (node.local && node.local !== node.imported) {
print.plain(node.imported);
if (node.local && node.local.name !== node.imported.name) {
this.push(" as ");
print(node.local);
print.plain(node.local);
}
}
export function ImportDefaultSpecifier(node, print) {
print(node.local);
print.plain(node.local);
}
export function ExportDefaultSpecifier(node, print) {
print(node.exported);
print.plain(node.exported);
}
export function ExportSpecifier(node, print) {
print(node.local);
if (node.exported && node.local !== node.exported) {
print.plain(node.local);
if (node.exported && node.local.name !== node.exported.name) {
this.push(" as ");
print(node.exported);
print.plain(node.exported);
}
}
export function ExportNamespaceSpecifier(node, print) {
this.push("* as ");
print(node.exported);
print.plain(node.exported);
}
export function ExportAllDeclaration(node, print) {
this.push("export *");
if (node.exported) {
this.push(" as ");
print(node.exported);
print.plain(node.exported);
}
this.push(" from ");
print(node.source);
print.plain(node.source);
this.semicolon();
}
@@ -56,14 +55,14 @@ function ExportDeclaration(node, print) {
if (node.declaration) {
var declar = node.declaration;
print(declar);
print.plain(declar);
if (t.isStatement(declar) || t.isFunction(declar) || t.isClass(declar)) return;
} else {
var first = specifiers[0];
var hasSpecial = false;
if (t.isExportDefaultSpecifier(first) || t.isExportNamespaceSpecifier(first)) {
hasSpecial = true;
print(specifiers.shift());
print.plain(specifiers.shift());
if (specifiers.length) {
this.push(", ");
}
@@ -81,7 +80,7 @@ function ExportDeclaration(node, print) {
if (node.source) {
this.push(" from ");
print(node.source);
print.plain(node.source);
}
}
@@ -99,7 +98,7 @@ export function ImportDeclaration(node, print) {
if (specfiers && specfiers.length) {
var first = node.specifiers[0];
if (t.isImportDefaultSpecifier(first) || t.isImportNamespaceSpecifier(first)) {
print(node.specifiers.shift());
print.plain(node.specifiers.shift());
if (node.specifiers.length) {
this.push(", ");
}
@@ -107,20 +106,20 @@ export function ImportDeclaration(node, print) {
if (node.specifiers.length) {
this.push("{");
this.space()
this.space();
print.join(node.specifiers, { separator: ", " });
this.space()
this.space();
this.push("}");
}
this.push(" from ");
}
print(node.source);
print.plain(node.source);
this.semicolon();
}
export function ImportNamespaceSpecifier(node, print) {
this.push("* as ");
print(node.local);
print.plain(node.local);
}

View File

@@ -4,7 +4,7 @@ import * as t from "../../types";
export function WithStatement(node, print) {
this.keyword("with");
this.push("(");
print(node.object);
print.plain(node.object);
this.push(")");
print.block(node.body);
}
@@ -12,7 +12,7 @@ export function WithStatement(node, print) {
export function IfStatement(node, print) {
this.keyword("if");
this.push("(");
print(node.test);
print.plain(node.test);
this.push(")");
this.space();
@@ -29,18 +29,18 @@ export function ForStatement(node, print) {
this.keyword("for");
this.push("(");
print(node.init);
print.plain(node.init);
this.push(";");
if (node.test) {
this.push(" ");
print(node.test);
print.plain(node.test);
}
this.push(";");
if (node.update) {
this.push(" ");
print(node.update);
print.plain(node.update);
}
this.push(")");
@@ -50,7 +50,7 @@ export function ForStatement(node, print) {
export function WhileStatement(node, print) {
this.keyword("while");
this.push("(");
print(node.test);
print.plain(node.test);
this.push(")");
print.block(node.body);
}
@@ -59,9 +59,9 @@ var buildForXStatement = function (op) {
return function (node, print) {
this.keyword("for");
this.push("(");
print(node.left);
print.plain(node.left);
this.push(` ${op} `);
print(node.right);
print.plain(node.right);
this.push(")");
print.block(node.body);
};
@@ -72,11 +72,11 @@ export var ForOfStatement = buildForXStatement("of");
export function DoWhileStatement(node, print) {
this.push("do ");
print(node.body);
print.plain(node.body);
this.space();
this.keyword("while");
this.push("(");
print(node.test);
print.plain(node.test);
this.push(");");
}
@@ -87,7 +87,7 @@ var buildLabelStatement = function (prefix, key) {
var label = node[key || "label"];
if (label) {
this.push(" ");
print(label);
print.plain(label);
}
this.semicolon();
@@ -99,50 +99,50 @@ export var ReturnStatement = buildLabelStatement("return", "argument");
export var BreakStatement = buildLabelStatement("break");
export function LabeledStatement(node, print) {
print(node.label);
print.plain(node.label);
this.push(": ");
print(node.body);
print.plain(node.body);
}
export function TryStatement(node, print) {
this.keyword("try");
print(node.block);
print.plain(node.block);
this.space();
// Esprima bug puts the catch clause in a `handlers` array.
// see https://code.google.com/p/esprima/issues/detail?id=433
// We run into this from regenerator generated ast.
if (node.handlers) {
print(node.handlers[0]);
print.plain(node.handlers[0]);
} else {
print(node.handler);
print.plain(node.handler);
}
if (node.finalizer) {
this.space();
this.push("finally ");
print(node.finalizer);
print.plain(node.finalizer);
}
}
export function CatchClause(node, print) {
this.keyword("catch");
this.push("(");
print(node.param);
print.plain(node.param);
this.push(") ");
print(node.body);
print.plain(node.body);
}
export function ThrowStatement(node, print) {
this.push("throw ");
print(node.argument);
print.plain(node.argument);
this.semicolon();
}
export function SwitchStatement(node, print) {
this.keyword("switch");
this.push("(");
print(node.discriminant);
print.plain(node.discriminant);
this.push(")");
this.space();
this.push("{");
@@ -160,7 +160,7 @@ export function SwitchStatement(node, print) {
export function SwitchCase(node, print) {
if (node.test) {
this.push("case ");
print(node.test);
print.plain(node.test);
this.push(":");
} else {
this.push("default:");
@@ -182,8 +182,8 @@ export function VariableDeclaration(node, print, parent) {
var hasInits = false;
// don't add whitespace to loop heads
if (!t.isFor(parent)) {
for (var i = 0; i < node.declarations.length; i++) {
if (node.declarations[i].init) {
for (var declar of (node.declarations: Array)) {
if (declar.init) {
// has an init so let's split it up over multiple lines
hasInits = true;
}
@@ -191,7 +191,7 @@ export function VariableDeclaration(node, print, parent) {
}
var sep = ",";
if (!this.format.compact && hasInits) {
if (!this.format.compact && !this.format.concise && hasInits && !this.format.retainLines) {
sep += `\n${repeating(" ", node.kind.length + 1)}`;
} else {
sep += " ";
@@ -207,12 +207,12 @@ export function VariableDeclaration(node, print, parent) {
}
export function VariableDeclarator(node, print) {
print(node.id);
print(node.id.typeAnnotation);
print.plain(node.id);
print.plain(node.id.typeAnnotation);
if (node.init) {
this.space();
this.push("=");
this.space();
print(node.init);
print.plain(node.init);
}
}

View File

@@ -1,8 +1,6 @@
import each from "lodash/collection/each";
export function TaggedTemplateExpression(node, print) {
print(node.tag);
print(node.quasi);
print.plain(node.tag);
print.plain(node.quasi);
}
export function TemplateElement(node) {
@@ -15,15 +13,15 @@ export function TemplateLiteral(node, print) {
var quasis = node.quasis;
var len = quasis.length;
each(quasis, (quasi, i) => {
print(quasi);
for (var i = 0; i < len; i++) {
print.plain(quasis[i]);
if (i + 1 < len) {
this.push("${ ");
print(node.expressions[i]);
print.plain(node.expressions[i]);
this.push(" }");
}
});
}
this._push("`");
}

View File

@@ -1,4 +1,6 @@
import each from "lodash/collection/each";
/* eslint quotes: 0 */
import * as t from "../../types";
export function Identifier(node) {
this.push(node.name);
@@ -6,7 +8,7 @@ export function Identifier(node) {
export function RestElement(node, print) {
this.push("...");
print(node.argument);
print.plain(node.argument);
}
export { RestElement as SpreadElement, RestElement as SpreadProperty };
@@ -35,16 +37,29 @@ export function Property(node, print) {
} else {
if (node.computed) {
this.push("[");
print(node.key);
print.plain(node.key);
this.push("]");
} else {
print(node.key);
if (node.shorthand) return;
// print `({ foo: foo = 5 } = {})` as `({ foo = 5 } = {});`
if (t.isAssignmentPattern(node.value) && t.isIdentifier(node.key) && node.key.name === node.value.left.name) {
print.plain(node.value);
return;
}
print.plain(node.key);
// shorthand!
if (node.shorthand &&
(t.isIdentifier(node.key) &&
t.isIdentifier(node.value) &&
node.key.name === node.value.name)) {
return;
}
}
this.push(":");
this.space();
print(node.value);
print.plain(node.value);
}
}
@@ -54,7 +69,8 @@ export function ArrayExpression(node, print) {
this.push("[");
each(elems, (elem, i) => {
for (var i = 0; i < elems.length; i++) {
var elem = elems[i];
if (!elem) {
// If the array expression ends with a hole, that hole
// will be ignored by the interpreter, but if it ends with
@@ -64,10 +80,10 @@ export function ArrayExpression(node, print) {
this.push(",");
} else {
if (i > 0) this.push(" ");
print(elem);
print.plain(elem);
if (i < len - 1) this.push(",");
}
});
}
this.push("]");
}

View File

@@ -1,5 +1,6 @@
import detectIndent from "detect-indent";
import Whitespace from "./whitespace";
import NodePrinter from "./node/printer";
import repeating from "repeating";
import SourceMap from "./source-map";
import Position from "./position";
@@ -20,7 +21,7 @@ class CodeGenerator {
this.opts = opts;
this.ast = ast;
this.whitespace = new Whitespace(this.tokens, this.comments, this.format);
this.whitespace = new Whitespace(this.tokens);
this.position = new Position;
this.map = new SourceMap(this.position, opts, code);
this.buffer = new Buffer(this.position, this.format);
@@ -67,7 +68,6 @@ class CodeGenerator {
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (token.type.label !== "string") continue;
if (checked >= 3) continue;
var raw = code.slice(token.start, token.end);
if (raw[0] === "'") {
@@ -77,6 +77,7 @@ class CodeGenerator {
}
checked++;
if (checked >= 3) break;
}
if (occurences.single > occurences.double) {
@@ -105,11 +106,13 @@ class CodeGenerator {
this.print(ast);
var comments = [];
each(ast.comments, function (comment) {
if (!comment._displayed) comments.push(comment);
});
this._printComments(comments);
if (ast.comments) {
var comments = [];
for (var comment of (ast.comments: Array)) {
if (!comment._displayed) comments.push(comment);
}
this._printComments(comments);
}
return {
map: this.map.get(),
@@ -118,40 +121,15 @@ class CodeGenerator {
}
buildPrint(parent) {
var print = (node, opts) => {
return this.print(node, parent, opts);
};
print.sequence = (nodes, opts = {}) => {
opts.statement = true;
return this.printJoin(print, nodes, opts);
};
print.join = (nodes, opts) => {
return this.printJoin(print, nodes, opts);
};
print.list = function (items, opts = {}) {
if (opts.separator == null) opts.separator = ", ";
print.join(items, opts);
};
print.block = (node) => {
return this.printBlock(print, node);
};
print.indentOnComments = (node) => {
return this.printAndIndentOnComments(print, node);
};
return print;
return new NodePrinter(this, parent);
}
catchUp(node, parent) {
catchUp(node, parent, leftParenPrinted) {
// catch up to this nodes newline if we're behind
if (node.loc && this.format.retainLines && this.buffer.buf) {
var needsParens = false;
if (parent && this.position.line < node.loc.start.line && t.isTerminatorless(parent)) {
if (!leftParenPrinted && parent &&
this.position.line < node.loc.start.line && t.isTerminatorless(parent)) {
needsParens = true;
this._push("(");
}
@@ -163,6 +141,36 @@ class CodeGenerator {
return false;
}
_printNewline(leading, node, parent, opts) {
if (!opts.statement && !n.isUserWhitespacable(node, parent)) {
return;
}
var lines = 0;
if (node.start != null && !node._ignoreUserWhitespace) {
// user node
if (leading) {
lines = this.whitespace.getNewlinesBefore(node);
} else {
lines = this.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 (!this.buffer.buf) lines = 0;
}
this.newline(lines);
}
print(node, parent, opts = {}) {
if (!node) return;
@@ -175,36 +183,6 @@ class CodeGenerator {
this.format.concise = true;
}
var newline = (leading) => {
if (!opts.statement && !n.isUserWhitespacable(node, parent)) {
return;
}
var lines = 0;
if (node.start != null && !node._ignoreUserWhitespace) {
// user node
if (leading) {
lines = this.whitespace.getNewlinesBefore(node);
} else {
lines = this.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 (!this.buffer.buf) lines = 0;
}
this.newline(lines);
};
if (this[node.type]) {
var needsNoLineTermParens = n.needsParensNoLineTerminator(node, parent);
var needsParens = needsNoLineTermParens || n.needsParens(node, parent);
@@ -214,9 +192,9 @@ class CodeGenerator {
this.printLeadingComments(node, parent);
var needsParensFromCatchup = this.catchUp(node, parent);
var needsParensFromCatchup = this.catchUp(node, parent, needsParens);
newline(true);
this._printNewline(true, node, parent, opts);
if (opts.before) opts.before();
this.map.mark(node, "start");
@@ -234,7 +212,7 @@ class CodeGenerator {
this.format.concise = oldConcise;
newline(false);
this._printNewline(false, node, parent, opts);
this.printTrailingComments(node, parent);
} else {
@@ -249,21 +227,24 @@ class CodeGenerator {
if (opts.indent) this.indent();
each(nodes, (node, i) => {
print(node, {
statement: opts.statement,
addNewlines: opts.addNewlines,
after: () => {
if (opts.iterator) {
opts.iterator(node, i);
}
if (opts.separator && i < len - 1) {
this.push(opts.separator);
}
var printOpts = {
statement: opts.statement,
addNewlines: opts.addNewlines,
after: () => {
if (opts.iterator) {
opts.iterator(node, i);
}
});
});
if (opts.separator && i < len - 1) {
this.push(opts.separator);
}
}
};
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
print.plain(node, printOpts);
}
if (opts.indent) this.dedent();
}
@@ -271,7 +252,7 @@ class CodeGenerator {
printAndIndentOnComments(print, node) {
var indent = !!node.leadingComments;
if (indent) this.indent();
print(node);
print.plain(node);
if (indent) this.dedent();
}
@@ -280,13 +261,13 @@ class CodeGenerator {
this.semicolon();
} else {
this.push(" ");
print(node);
print.plain(node);
}
}
generateComment(comment) {
var val = comment.value;
if (comment.type === "Line") {
if (comment.type === "CommentLine") {
val = `//${val}`;
} else {
val = `/*${val}*/`;
@@ -314,9 +295,9 @@ class CodeGenerator {
nodes.push(node.argument);
}
each(nodes, (node) => {
for (let node of (nodes: Array)) {
comments = comments.concat(this._getComments(key, node));
});
}
return comments;
}
@@ -327,23 +308,24 @@ class CodeGenerator {
_printComments(comments) {
if (this.format.compact) return;
if (!this.format.comments) return;
if (!comments || !comments.length) return;
each(comments, (comment) => {
for (var comment of (comments: Array)) {
var skip = false;
// find the original comment in the ast and set it as displayed
each(this.ast.comments, function (origComment) {
if (origComment.start === comment.start) {
// comment has already been output
if (origComment._displayed) skip = true;
if (this.ast.comments) {
// find the original comment in the ast and set it as displayed
for (var origComment of (this.ast.comments: Array)) {
if (origComment.start === comment.start) {
// comment has already been output
if (origComment._displayed) skip = true;
origComment._displayed = true;
return false;
origComment._displayed = true;
break;
}
}
});
}
if (skip) return;
@@ -361,7 +343,7 @@ class CodeGenerator {
}
//
if (comment.type === "Block" && this.format.indent.adjustMultilineComment) {
if (comment.type === "CommentBlock" && this.format.indent.adjustMultilineComment) {
var offset = comment.loc.start.column;
if (offset) {
var newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g");
@@ -378,7 +360,7 @@ class CodeGenerator {
// force a newline for line comments when retainLines is set in case the next printed node
// doesn't catch up
if (this.format.retainLines && comment.type === "Line") {
if (this.format.retainLines && comment.type === "CommentLine") {
val += "\n";
}
@@ -387,7 +369,7 @@ class CodeGenerator {
// whitespace after
this.newline(this.whitespace.getNewlinesAfter(comment));
});
}
}
}

View File

@@ -0,0 +1,32 @@
export default class NodePrinter {
constructor(generator, parent) {
this.generator = generator;
this.parent = parent;
}
plain(node, opts) {
return this.generator.print(node, this.parent, opts);
}
sequence(nodes, opts = {}) {
opts.statement = true;
return this.generator.printJoin(this, nodes, opts);
}
join(nodes, opts) {
return this.generator.printJoin(this, nodes, opts);
}
list(items, opts = {}) {
if (opts.separator == null) opts.separator = ", ";
return this.join(items, opts);
}
block(node) {
return this.generator.printBlock(this, node);
}
indentOnComments(node) {
return this.generator.printAndIndentOnComments(this, node);
}
}

View File

@@ -8,7 +8,7 @@ export default class SourceMap {
if (opts.sourceMaps) {
this.map = new sourceMap.SourceMapGenerator({
file: opts.sourceMapName,
file: opts.sourceMapTarget,
sourceRoot: opts.sourceRoot
});

View File

@@ -1,5 +1,3 @@
import sortBy from "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.
@@ -21,8 +19,8 @@ function getLookupIndex(i, base, max) {
}
export default class Whitespace {
constructor(tokens, comments) {
this.tokens = sortBy(tokens.concat(comments), "start");
constructor(tokens) {
this.tokens = tokens;
this.used = {};
// Profiling this code shows that while generator passes over it, indexes
@@ -40,12 +38,11 @@ export default class Whitespace {
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];
var token = tokens[i];
// this is the token this node starts with
if (node.start === token.start) {
@@ -64,17 +61,17 @@ export default class Whitespace {
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];
var token = tokens[i];
// this is the token this node ends with
if (node.end === token.end) {
startToken = token;
endToken = tokens[i + 1];
if (endToken.type.label === ",") endToken = tokens[i + 2];
this._lastFoundIndex = i;
break;
@@ -85,7 +82,7 @@ export default class Whitespace {
return 1;
} else {
var lines = this.getNewlinesBetween(startToken, endToken);
if (node.type === "Line" && !lines) {
if (node.type === "CommentLine" && !lines) {
// line comment
return 1;
} else {

View File

@@ -85,4 +85,4 @@ export default function (lines: number, lineNumber: number, colNumber: number, o
params.before = params.before.replace(/^./, ">");
}
}).join("\n");
};
}

View File

@@ -0,0 +1,17 @@
import merge from "lodash/object/merge";
export default function (dest, src) {
if (!dest || !src) return;
return merge(dest, src, function(a, b) {
if (Array.isArray(a)) {
var c = a.slice(0);
for (var v of b) {
if (a.indexOf(v) < 0) {
c.push(v);
}
}
return c;
}
});
}

View File

@@ -6,4 +6,4 @@ export default function (ast, comments, tokens) {
} else {
throw new Error("Not a valid ast?");
}
};
}

View File

@@ -1,3 +1,3 @@
export default function () {
return Object.create(null);
};
}

View File

@@ -3,8 +3,9 @@ import estraverse from "estraverse";
import * as acorn from "../../acorn";
export default function (code, opts = {}) {
var comments = [];
var tokens = [];
var commentsAndTokens = [];
var comments = [];
var tokens = [];
var parseOpts = {
allowImportExportEverywhere: opts.looseModules,
@@ -14,21 +15,38 @@ export default function (code, opts = {}) {
strictMode: opts.strictMode,
sourceType: opts.sourceType,
locations: true,
onComment: comments,
features: opts.features || {},
plugins: opts.plugins || {},
onToken: tokens,
ranges: true
};
parseOpts.onToken = function (token) {
tokens.push(token);
commentsAndTokens.push(token);
};
parseOpts.onComment = function (block, text, start, end, startLoc, endLoc) {
var comment = {
type: block ? "CommentBlock" : "CommentLine",
value: text,
start: start,
end: end,
loc: new acorn.SourceLocation(this, startLoc, endLoc),
range: [start, end]
};
commentsAndTokens.push(comment);
comments.push(comment);
};
if (opts.nonStandard) {
parseOpts.plugins.jsx = true;
parseOpts.plugins.flow = true;
}
var ast = acorn.parse(code, parseOpts);
estraverse.attachComments(ast, comments, tokens);
ast = normalizeAst(ast, comments, tokens);
ast = normalizeAst(ast, comments, commentsAndTokens);
return ast;
}

View File

@@ -18,15 +18,16 @@ export const MESSAGES = {
modulesIllegalExportName: "Illegal export $1",
unknownForHead: "Unknown node type $1 in ForStatement",
didYouMean: "Did you mean $1?",
evalInStrictMode: "eval is not allowed in strict mode",
codeGeneratorDeopt: "Note: The code generator has deoptimised the styling of $1 as it exceeds the max of $2.",
missingTemplatesDirectory: "no templates directory - this is most likely the result of a broken `npm publish`. Please report to https://github.com/babel/babel/issues",
unsupportedOutputType: "Unsupported output type $1",
illegalMethodName: "Illegal method name $1",
lostTrackNodePath: "We lost track of this nodes position, likely because the AST was directly manipulated",
traverseNeedsParent: "Must pass a scope and parentPath unless traversing a Program/File got a $1 node",
traverseVerifyRootFunction: "You passed `traverse()` a function when it expected a visitor object, are you sure you didn't mean `{ enter: Function }`?",
traverseVerifyVisitorFunction: "Hey! You passed \`traverse()\` a visitor object with the key $1 that's a straight up `Function` instead of `{ enter: Function }`. You need to normalise it with `traverse.explode(visitor)`.",
traverseVerifyVisitorProperty: "You passed `traverse()` a visitor object with the property $1 that has the invalid property $2",
traverseVerifyNodeType: "You gave us a visitor for the node type $1 but it's not a valid type",
pluginIllegalKind: "Illegal kind $1 for plugin $2",
pluginIllegalPosition: "Illegal position $1 for plugin $2",

View File

@@ -33,6 +33,9 @@ def("DoExpression")
.build("body")
.field("body", [def("Statement")]);
def("Super")
.bases("Expression");
def("ExportDefaultDeclaration")
.bases("Declaration")
.build("declaration")
@@ -69,4 +72,10 @@ def("ExportAllDeclaration")
.field("exported", def("Identifier"))
.field("source", def("Literal"));
def("BindExpression")
.bases("Expression")
.build("object", "callee")
.field("object", or(def("Expression"), null))
.field("callee", def("Expression"));
types.finalize();

View File

@@ -83,4 +83,4 @@ export default function (whitelist, outputType = "global") {
}
return generator(tree).code;
};
}

View File

@@ -1,5 +1,5 @@
import stripJsonComments from "strip-json-comments";
import merge from "lodash/object/merge";
import merge from "../helpers/merge";
import path from "path";
import fs from "fs";
@@ -42,17 +42,7 @@ export default function (loc, opts = {}) {
opts.babelrc.push(file);
if (json.breakConfig) return;
merge(opts, json, function(a, b) {
if (Array.isArray(a)) {
var c = a.slice(0);
for (var v of b) {
if (a.indexOf(v) < 0) {
c.push(v);
}
}
return c;
}
});
merge(opts, json);
}
var up = path.dirname(start);
@@ -66,4 +56,4 @@ export default function (loc, opts = {}) {
}
return opts;
};
}

View File

@@ -3,12 +3,12 @@ import * as optionParsers from "./option-parsers";
import moduleFormatters from "../modules";
import PluginManager from "./plugin-manager";
import shebangRegex from "shebang-regex";
import TraversalPath from "../../traversal/path";
import NodePath from "../../traversal/path";
import Transformer from "../transformer";
import isFunction from "lodash/lang/isFunction";
import isAbsolute from "path-is-absolute";
import resolveRc from "../../tools/resolve-rc";
import sourceMap from "source-map";
import transform from "./../index";
import generate from "../../generation";
import codeFrame from "../../helpers/code-frame";
import defaults from "lodash/object/defaults";
@@ -17,30 +17,17 @@ import traverse from "../../traversal";
import assign from "lodash/object/assign";
import Logger from "./logger";
import parse from "../../helpers/parse";
import Scope from "../../traversal/scope";
import merge from "../../helpers/merge";
import slash from "slash";
import clone from "lodash/lang/clone";
import * as util from "../../util";
import * as api from "../../api/node";
import path from "path";
import each from "lodash/collection/each";
import * as t from "../../types";
var checkTransformerVisitor = {
exit(node, parent, scope, state) {
checkPath(state.stack, this);
}
};
function checkPath(stack, path) {
each(stack, function (pass) {
if (pass.shouldRun || pass.ran) return;
pass.checkPath(path);
});
}
export default class File {
constructor(opts = {}, pipeline) {
this.transformerDependencies = {};
this.dynamicImportTypes = {};
this.dynamicImportIds = {};
this.dynamicImports = [];
@@ -48,8 +35,8 @@ export default class File {
this.declarations = {};
this.usedHelpers = {};
this.dynamicData = {};
this.metadata = {};
this.data = {};
this.uids = {};
this.pipeline = pipeline;
this.log = new Logger(this, opts.filename || "unknown");
@@ -96,10 +83,7 @@ export default class File {
"interop-require",
];
static soloHelpers = [
"ludicrous-proxy-create",
"ludicrous-proxy-directory"
];
static soloHelpers = [];
static options = require("./options");
@@ -121,6 +105,9 @@ export default class File {
if (!option) this.log.error(`Unknown option: ${key}`, ReferenceError);
}
var envKey = process.env.BABEL_ENV || process.env.NODE_ENV || "development";
if (opts.env) merge(opts, opts.env[envKey]);
for (let key in File.options) {
let option = File.options[key];
@@ -178,7 +165,7 @@ export default class File {
defaults(opts, {
sourceFileName: opts.filenameRelative,
sourceMapName: opts.filenameRelative
sourceMapTarget: opts.filenameRelative
});
//
@@ -203,8 +190,9 @@ export default class File {
var stack = [];
// build internal transformers
each(this.pipeline.transformers, function (transformer, key) {
var pass = transformers[key] = transformer.buildPass(file);
for (var key in this.pipeline.transformers) {
var transformer = this.pipeline.transformers[key];
let pass = transformers[key] = transformer.buildPass(file);
if (pass.canTransform()) {
stack.push(pass);
@@ -217,7 +205,7 @@ export default class File {
transformer.manipulateOptions(file.opts, file);
}
}
});
}
// init plugins!
var beforePlugins = [];
@@ -233,8 +221,54 @@ export default class File {
}
stack = beforePlugins.concat(stack, afterPlugins);
// register
this.transformerStack = stack.concat(secondaryStack);
// build transformer stack
this.uncollapsedTransformerStack = stack = stack.concat(secondaryStack);
// build dependency graph
for (let pass of (stack: Array)) {
for (var dep of (pass.transformer.dependencies: Array)) {
this.transformerDependencies[dep] = pass.key;
}
}
// collapse stack categories
this.transformerStack = this.collapseStack(stack);
}
collapseStack(_stack) {
var stack = [];
var ignore = [];
for (let pass of (_stack: Array)) {
// been merged
if (ignore.indexOf(pass) >= 0) continue;
var group = pass.transformer.metadata.group;
// can't merge
if (!pass.canTransform() || !group) {
stack.push(pass);
continue;
}
var mergeStack = [];
for (let pass of (_stack: Array)) {
if (pass.transformer.metadata.group === group) {
mergeStack.push(pass);
ignore.push(pass);
}
}
var visitors = [];
for (let pass of (mergeStack: Array)) {
visitors.push(pass.handlers);
}
var visitor = traverse.visitors.merge(visitors);
var mergeTransformer = new Transformer(group, visitor);
stack.push(mergeTransformer.buildPass(this));
}
return stack;
}
set(key: string, val): any {
@@ -296,7 +330,7 @@ export default class File {
if (comment) {
node.leadingComments = node.leadingComments || [];
node.leadingComments.push({
type: "Line",
type: "CommentLine",
value: " " + comment
});
}
@@ -310,8 +344,6 @@ export default class File {
throw new ReferenceError(`Unknown helper ${name}`);
}
var program = this.ast.program;
var declar = this.declarations[name];
if (declar) return declar;
@@ -337,6 +369,7 @@ export default class File {
ref._generated = true;
ref.id = uid;
ref.type = "FunctionDeclaration";
this.attachAuxiliaryComment(ref);
this.path.unshiftContainer("body", ref);
} else {
ref._compact = true;
@@ -351,27 +384,15 @@ export default class File {
}
errorWithNode(node, msg, Error = SyntaxError) {
var loc = node.loc.start;
var err = new Error(`Line ${loc.line}: ${msg}`);
err.loc = loc;
return err;
}
checkPath(path) {
if (Array.isArray(path)) {
for (var i = 0; i < path.length; i++) {
this.checkPath(path[i]);
}
return;
var err;
if (node.loc) {
var loc = node.loc.start;
err = new Error(`Line ${loc.line}: ${msg}`);
err.loc = loc;
} else {
err = new Error("There's been an error on a dynamic node. This is almost certainly an internal error. Please report it.");
}
var stack = this.transformerStack;
checkPath(stack, path);
path.traverse(checkTransformerVisitor, {
stack: stack
});
return err;
}
mergeSourceMap(map: Object) {
@@ -388,7 +409,7 @@ export default class File {
outputMapGenerator.applySourceMap(inputMapConsumer);
var mergedMap = outputMapGenerator.toJSON();
mergedMap.sources = inputMap.sources
mergedMap.sources = inputMap.sources;
mergedMap.file = inputMap.file;
return mergedMap;
}
@@ -398,6 +419,10 @@ export default class File {
getModuleFormatter(type: string) {
if (isFunction(type) || !moduleFormatters[type]) {
this.log.deprecate("Custom module formatters are deprecated and will be removed in the next major. Please use Babel plugins instead.");
}
var ModuleFormatter = isFunction(type) ? type : moduleFormatters[type];
if (!ModuleFormatter) {
@@ -441,19 +466,14 @@ export default class File {
}
_addAst(ast) {
this.path = TraversalPath.get(null, null, ast, ast, "program", this);
this.path = NodePath.get({
parentPath: null,
parent: ast,
container: ast,
key: "program"
}).setContext(null, this);
this.scope = this.path.scope;
this.ast = ast;
this.path.traverse({
enter(node, parent, scope) {
if (this.isScope()) {
for (var key in scope.bindings) {
scope.bindings[key].setTypeAnnotation();
}
}
}
});
}
addAst(ast) {
@@ -461,40 +481,35 @@ export default class File {
this._addAst(ast);
this.log.debug("End set AST");
this.log.debug("Start prepass");
this.checkPath(this.path);
this.log.debug("End prepass");
this.log.debug("Start module formatter init");
var modFormatter = this.moduleFormatter = this.getModuleFormatter(this.opts.modules);
if (modFormatter.init && this.transformers["es6.modules"].canTransform()) {
modFormatter.init();
}
this.populateModuleMetadata();
this.log.debug("End module formatter init");
}
populateModuleMetadata() {
var modules = {};
this.metadata.modules = modules;
}
transform() {
this.call("pre");
each(this.transformerStack, function (pass) {
for (var pass of (this.transformerStack: Array)) {
pass.transform();
});
}
this.call("post");
return this.generate();
}
wrap(code, callback) {
code = code + "";
try {
if (this.shouldIgnore()) {
return {
metadata: {},
code: code,
map: null,
ast: null
};
}
callback();
return this.generate();
return callback();
} catch (err) {
if (err._babel) {
throw err;
@@ -523,15 +538,15 @@ export default class File {
}
}
addCode(code: string, parseCode?) {
addCode(code: string) {
code = (code || "") + "";
code = this.parseInputSourceMap(code);
this.code = code;
}
if (parseCode) {
this.parseShebang();
this.addAst(this.parse(this.code));
}
parseCode() {
this.parseShebang();
this.addAst(this.parse(this.code));
}
shouldIgnore() {
@@ -540,10 +555,8 @@ export default class File {
}
call(key: string) {
var stack = this.transformerStack;
for (var i = 0; i < stack.length; i++) {
var transformer = stack[i].transformer;
var fn = transformer[key];
for (var pass of (this.uncollapsedTransformerStack: Array)) {
var fn = pass.transformer[key];
if (fn) fn(this);
}
}
@@ -570,28 +583,37 @@ export default class File {
}
}
generate(): {
usedHelpers?: Array<string>;
code: string;
map?: Object;
ast?: Object;
} {
var opts = this.opts;
var ast = this.ast;
makeResult({ code, map = null, ast, ignored }) {
var result = {
metadata: {},
code: "",
map: null,
ast: null
metadata: null,
ignored: !!ignored,
code: null,
ast: null,
map: map
};
if (this.opts.metadataUsedHelpers) {
if (this.opts.code) {
result.code = code;
}
if (this.opts.ast) {
result.ast = ast;
}
if (this.opts.metadata) {
result.metadata = this.metadata;
result.metadata.usedHelpers = Object.keys(this.usedHelpers);
}
if (opts.ast) result.ast = ast;
if (!opts.code) return result;
return result;
}
generate() {
var opts = this.opts;
var ast = this.ast;
var result = { ast };
if (!opts.code) return this.makeResult(result);
this.log.debug("Generation start");
@@ -618,6 +640,6 @@ export default class File {
result.map = null;
}
return result;
return this.makeResult(result);
}
}

View File

@@ -1,4 +1,8 @@
import * as util from "../../util";
import type File from "./index";
import buildDebug from "debug/node";
var verboseDebug = buildDebug("babel:verbose");
var generalDebug = buildDebug("babel");
export default class Logger {
constructor(file: File, filename: string) {
@@ -12,6 +16,10 @@ export default class Logger {
return parts;
}
warn(msg) {
console.warn(this._buildMessage(msg));
}
error(msg: string, Constructor = Error) {
throw new Constructor(this._buildMessage(msg));
}
@@ -22,11 +30,15 @@ export default class Logger {
}
}
verbose(msg: string) {
if (verboseDebug.enabled) verboseDebug(this._buildMessage(msg));
}
debug(msg: string) {
util.debug(this._buildMessage(msg));
if (generalDebug.enabled) generalDebug(this._buildMessage(msg));
}
deopt(node: Object, msg: string) {
util.debug(this._buildMessage(msg));
this.debug(msg);
}
}

View File

@@ -20,6 +20,11 @@
"default": {}
},
"env": {
"hidden": true,
"default": {}
},
"moduleId": {
"description": "specify a custom name for module ids",
"type": "string"
@@ -30,7 +35,6 @@
},
"retainLines": {
"hidden": true,
"type": "boolean",
"default": false,
"description": "retain line numbers - will result in really ugly code"
@@ -39,15 +43,16 @@
"nonStandard": {
"type": "boolean",
"default": true,
"description": "enable support for JSX and Flow"
"description": "enable/disable support for JSX and Flow (on by default)"
},
"experimental": {
"deprecated": "use `--stage 0`/`{ stage: 0 }` instead"
"description": "allow use of experimental transformers",
"default": false
},
"highlightCode": {
"description": "ANSI syntax highlight code frames",
"description": "enable/disable ANSI syntax highlighting of code frames (on by default)",
"type": "boolean",
"default": true
},
@@ -135,6 +140,12 @@
"type": "boolean"
},
"metadata": {
"hidden": true,
"default": true,
"type": "boolean"
},
"ast": {
"hidden": true,
"default": true,
@@ -144,7 +155,7 @@
"comments": {
"type": "boolean",
"default": true,
"description": "output comments in generated output"
"description": "strip/output comments in generated output (on by default)"
},
"compact": {
@@ -175,6 +186,7 @@
},
"metadataUsedHelpers": {
"deprecated": "Not required anymore as this is enabled by default",
"type": "boolean",
"default": false,
"hidden": true
@@ -193,6 +205,11 @@
},
"sourceMapName": {
"alias": "sourceMapTarget",
"description": "DEPRECATED - Please use sourceMapTarget"
},
"sourceMapTarget": {
"type": "string",
"description": "set `file` on returned source map"
},

View File

@@ -35,11 +35,12 @@ export default class PluginManager {
var match = name.match(/^(.*?):(after|before)$/);
if (match) [, name, position] = match;
var loc = util.resolveRelative(name) || util.resolveRelative(`babel-plugin-${name}`);
var loc = util.resolveRelative(`babel-plugin-${name}`) || util.resolveRelative(name);
if (loc) {
var plugin = require(loc);
return {
position: position,
plugin: require(loc)
plugin: plugin.default || plugin
};
} else {
throw new ReferenceError(messages.get("pluginUnknown", name));
@@ -57,6 +58,9 @@ export default class PluginManager {
if (!plugin.buildPass || plugin.constructor.name !== "Transformer") {
throw new TypeError(messages.get("pluginNotTransformer", name));
}
// register as a plugin
plugin.metadata.plugin = true;
}
add(name) {
@@ -65,7 +69,7 @@ export default class PluginManager {
if (name) {
if (typeof name === "object" && name.transformer) {
({ plugin: name, position } = name);
({ transformer: plugin, position } = name);
} else if (typeof name !== "string") {
// not a string so we'll just assume that it's a direct Transformer instance, if not then
// the checks later on will complain

View File

@@ -1,7 +1,9 @@
import explode from "./explode-assignable-expression";
import * as t from "../../types";
export default function (exports, opts) {
export default function (opts) {
var exports = {};
var isAssignment = function (node) {
return node.operator === opts.operator + "=";
};
@@ -10,10 +12,6 @@ export default function (exports, opts) {
return t.assignmentExpression("=", left, right);
};
exports.shouldVisit = function (node) {
return node.operator && (node.operator === opts.operator || node.operator === opts.operator + "=");
};
exports.ExpressionStatement = function (node, parent, scope, file) {
// hit the `AssignmentExpression` one below
if (this.isCompletionRecord()) return;
@@ -44,4 +42,6 @@ export default function (exports, opts) {
if (node.operator !== opts.operator) return;
return opts.build(node.left, node.right);
};
};
return exports;
}

View File

@@ -42,4 +42,4 @@ export default function (exports, opts) {
return nodes;
};
};
}

View File

@@ -10,14 +10,8 @@ import * as react from "./react";
import * as t from "../../types";
export default function (exports, opts) {
exports.check = function (node) {
if (t.isJSX(node)) return true;
if (react.isCreateClass(node)) return true;
return false;
};
exports.JSXIdentifier = function (node, parent) {
if (node.name === "this" && t.isReferenced(node, parent)) {
exports.JSXIdentifier = function (node) {
if (node.name === "this" && this.isReferenced()) {
return t.thisExpression();
} else if (esutils.keyword.isIdentifierNameES6(node.name)) {
node.type = "Identifier";
@@ -26,7 +20,7 @@ export default function (exports, opts) {
}
};
exports.JSXNamespacedName = function (node, parent, scope, file) {
exports.JSXNamespacedName = function () {
throw this.errorWithNode(messages.get("JSXNamespacedTags"));
};
@@ -167,7 +161,8 @@ export default function (exports, opts) {
for (var i = 0; i < props.length; i++) {
var prop = props[i];
if (t.isIdentifier(prop.key, { name: "displayName" })) {
var key = t.toComputedKey(prop);
if (t.isLiteral(key, { value: "displayName" })) {
safe = false;
break;
}
@@ -208,4 +203,4 @@ export default function (exports, opts) {
addDisplayName(left.name, right);
}
};
};
}

View File

@@ -1,4 +1,3 @@
import traverse from "../../traversal";
import * as t from "../../types";
var visitor = {
@@ -7,10 +6,10 @@ var visitor = {
state.found = true;
this.stop();
}
},
if (this.isFunction()) {
this.skip();
}
Function() {
this.skip();
}
};

View File

@@ -1,5 +1,3 @@
import cloneDeep from "lodash/lang/cloneDeep";
import traverse from "../../traversal";
import each from "lodash/collection/each";
import has from "lodash/object/has";
import * as t from "../../types";
@@ -26,7 +24,7 @@ export function push(mutatorMap, node, kind, file) {
if (node.decorators) {
var decorators = map.decorators = map.decorators || t.arrayExpression([]);
decorators.elements = decorators.elements.concat(node.decorators.map(dec => dec.expression));
decorators.elements = decorators.elements.concat(node.decorators.map(dec => dec.expression).reverse());
}
if (map.value || map.initializer) {

View File

@@ -26,7 +26,7 @@ var getObjRef = function (node, nodes, file, scope) {
throw new Error(`We can't explode this node type ${node.type}`);
}
var temp = scope.generateUidBasedOnNode(ref);
var temp = scope.generateUidIdentifierBasedOnNode(ref);
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(temp, ref)
]));
@@ -38,7 +38,7 @@ var getPropRef = function (node, nodes, file, scope) {
var key = t.toComputedKey(node, prop);
if (t.isLiteral(key)) return key;
var temp = scope.generateUidBasedOnNode(prop);
var temp = scope.generateUidIdentifierBasedOnNode(prop);
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(temp, prop)
]));
@@ -68,4 +68,4 @@ export default function (node, nodes, file, scope, allowedSingleIdent) {
uid: uid,
ref: ref
};
};
}

View File

@@ -6,4 +6,4 @@ export default function (node) {
if (!t.isAssignmentPattern(node.params[i])) lastNonDefault = i + 1;
}
return lastNonDefault;
};
}

View File

@@ -6,7 +6,7 @@ export default function (decorators, scope) {
var expression = decorator.expression;
if (!t.isMemberExpression(expression)) continue;
var temp = scope.generateMemoisedReference(expression.object);
var temp = scope.maybeGenerateMemoised(expression.object);
var ref;
var nodes = [];

View File

@@ -2,25 +2,35 @@ import getFunctionArity from "./get-function-arity";
import * as util from "../../util";
import * as t from "../../types";
function visitIdentifier(context, node, scope, state) {
// check if this node matches our function id
if (node.name !== state.name) return;
// check that we don't have a local variable declared as that removes the need
// for the wrapper
var localDeclar = scope.getBindingIdentifier(state.name);
if (localDeclar !== state.outerDeclar) return;
state.selfReference = true;
context.stop();
}
var visitor = {
enter(node, parent, scope, state) {
// check if this node is a referenced identifier that matches the same as our
// function id
if (!this.isReferencedIdentifier({ name: state.name })) return;
ReferencedIdentifier(node, parent, scope, state) {
visitIdentifier(this, node, scope, state);
},
// check that we don't have a local variable declared as that removes the need
// for the wrapper
var localDeclar = scope.getBindingIdentifier(state.name);
if (localDeclar !== state.outerDeclar) return;
state.selfReference = true;
this.stop();
AssignmentExpression(node, parent, scope, state) {
var ids = this.getBindingIdentifiers();
for (var name in ids) {
visitIdentifier(this, ids[name], scope, state);
}
}
};
var wrap = function (state, method, id, scope) {
if (state.selfReference) {
if (scope.hasBinding(id.name)) {
if (scope.hasBinding(id.name) && !scope.hasGlobal(id.name)) {
// we can just munge the local binding
scope.rename(id.name);
} else {
@@ -46,6 +56,7 @@ var wrap = function (state, method, id, scope) {
}
method.id = id;
scope.getProgramParent().references[id.name] = true;
};
var visit = function (node, name, scope) {

View File

@@ -1,4 +1,3 @@
import isString from "lodash/lang/isString";
import * as t from "../../types";
var isCreateClassCallExpression = t.buildMatchMemberExpression("React.createClass");
@@ -26,10 +25,6 @@ export function isCompatTag(tagName) {
return tagName && /^[a-z]|\-/.test(tagName);
}
function isStringLiteral(node) {
return t.isLiteral(node) && isString(node.value);
}
function cleanJSXElementLiteralChild(child, args) {
var lines = child.value.split(/\r\n|\n|\r/);

View File

@@ -1,25 +1,25 @@
import * as t from "../../types";
var awaitVisitor = {
enter(node, parent, scope, state) {
if (t.isFunction(node)) this.skip();
Function() {
this.skip();
},
if (t.isAwaitExpression(node)) {
node.type = "YieldExpression";
AwaitExpression(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]);
}
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]);
}
}
};
var referenceVisitor = {
enter(node, parent, scope, state) {
ReferencedIdentifier(node, parent, scope, state) {
var name = state.id.name;
if (t.isReferencedIdentifier(node, parent, { name: name }) && scope.bindingIdentifierEquals(name, state.id)) {
if (node.name === name && scope.bindingIdentifierEquals(name, state.id)) {
return state.ref = state.ref || scope.generateUidIdentifier(name);
}
}
@@ -55,4 +55,4 @@ export default function (node, callId, scope) {
return call;
}
};
}

View File

@@ -1,3 +1,4 @@
import type NodePath from "../../traversal/path";
import * as messages from "../../messages";
import * as t from "../../types";
@@ -130,7 +131,7 @@ export default class ReplaceSupers {
* Description
*/
traverseLevel(path: TraversalPath, topLevel: boolean) {
traverseLevel(path: NodePath, topLevel: boolean) {
var state = { self: this, topLevel: topLevel };
path.traverse(visitor, state);
}
@@ -192,7 +193,7 @@ export default class ReplaceSupers {
* Description
*/
looseHandle(path: TraversalPath, getThisReference: Function) {
looseHandle(path: NodePath, getThisReference: Function) {
var node = path.node;
if (path.isSuper()) {
return this.getLooseSuperProperty(node, path.parent);
@@ -234,7 +235,7 @@ export default class ReplaceSupers {
* Description
*/
specHandle(path: TraversalPath, getThisReference: Function) {
specHandle(path: NodePath, getThisReference: Function) {
var methodNode = this.methodNode;
var property;
var computed;
@@ -274,7 +275,7 @@ export default class ReplaceSupers {
property = node.property;
computed = node.computed;
} else if (t.isUpdateExpression(node) && isMemberExpressionSuper(node.argument)) {
var binary = t.binaryExpression(node.operator[0], node.argument, t.literal(1))
var binary = t.binaryExpression(node.operator[0], node.argument, t.literal(1));
if (node.prefix) {
// ++super.foo; -> super.foo += 1;
return this.specHandleAssignmentExpression(null, path, binary, getThisReference);

View File

@@ -1,19 +0,0 @@
import * as t from "../../types";
export function has(node) {
var first = node.body[0];
return t.isExpressionStatement(first) && t.isLiteral(first.expression, { value: "use strict" });
}
export function wrap(node, callback) {
var useStrictNode;
if (has(node)) {
useStrictNode = node.body.shift();
}
callback();
if (useStrictNode) {
node.body.unshift(useStrictNode);
}
}

View File

@@ -5,6 +5,13 @@ var pipeline = new Pipeline;
//
import transformers from "./transformers";
for (var key in transformers) {
var transformer = transformers[key];
var metadata = transformer.metadata = transformer.metadata || {};
metadata.group = metadata.group || "builtin-basic";
}
pipeline.addTransformers(transformers);
//

View File

@@ -1,110 +1,120 @@
import * as messages from "../../messages";
import traverse from "../../traversal";
import extend from "lodash/object/extend";
import object from "../../helpers/object";
import * as util from "../../util";
import * as t from "../../types";
var remapVisitor = {
enter(node, parent, scope, formatter) {
var remap = formatter.internalRemap[node.name];
if (this.isReferencedIdentifier() && remap && node !== remap) {
if (!scope.hasBinding(node.name) || scope.bindingIdentifierEquals(node.name, formatter.localImports[node.name])) {
return remap;
}
}
if (t.isUpdateExpression(node)) {
var exported = formatter.getExport(node.argument, scope);
if (exported) {
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, exported);
// 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);
}
}
enter(node) {
if (node._skipModulesRemap) {
return this.skip();
}
},
exit(node, parent, scope, formatter) {
if (t.isAssignmentExpression(node) && !node._ignoreModulesRemap) {
var exported = formatter.getExport(node.left, scope);
if (exported) {
return formatter.remapExportAssignment(node, exported);
ReferencedIdentifier(node, parent, scope, formatter) {
var remap = formatter.internalRemap[node.name];
if (remap && node !== remap) {
if (!scope.hasBinding(node.name) || scope.bindingIdentifierEquals(node.name, formatter.localImports[node.name])) {
if (this.key === "callee" && this.parentPath.isCallExpression()) {
return t.sequenceExpression([t.literal(0), remap]);
} else {
return remap;
}
}
}
},
AssignmentExpression: {
exit(node, parent, scope, formatter) {
if (!node._ignoreModulesRemap) {
var exported = formatter.getExport(node.left, scope);
if (exported) {
return formatter.remapExportAssignment(node, exported);
}
}
}
},
UpdateExpression(node, parent, scope, formatter) {
var exported = formatter.getExport(node.argument, scope);
if (!exported) return;
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, exported);
// 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);
}
};
var importsVisitor = {
ImportDeclaration: {
enter(node, parent, scope, formatter) {
formatter.hasLocalImports = true;
extend(formatter.localImports, this.getBindingIdentifiers());
var metadataVisitor = {
ModuleDeclaration(node, parent, scope, formatter) {
if (node.source) {
node.source.value = formatter.file.resolveModuleSource(node.source.value);
}
},
ImportDeclaration(node, parent, scope, formatter) {
formatter.hasLocalImports = true;
extend(formatter.localImports, this.getBindingIdentifiers());
},
ExportDeclaration(node, parent, scope, formatter) {
formatter.hasLocalExports = true;
var declar = this.get("declaration");
if (declar.isStatement()) {
var bindings = declar.getBindingIdentifiers();
for (var name in bindings) {
var binding = bindings[name];
formatter._addExport(name, binding);
}
}
if (this.isExportNamedDeclaration() && node.specifiers) {
for (var i = 0; i < node.specifiers.length; i++) {
var specifier = node.specifiers[i];
var local = specifier.local;
if (!local) continue;
formatter._addExport(local.name, specifier.exported);
}
}
if (!t.isExportDefaultDeclaration(node)) {
var onlyDefault = node.specifiers && node.specifiers.length === 1 && t.isSpecifierDefault(node.specifiers[0]);
if (!onlyDefault) {
formatter.hasNonDefaultExports = true;
}
}
},
Scope() {
this.skip();
}
};
var exportsVisitor = traverse.explode({
ExportDeclaration: {
enter(node, parent, scope, formatter) {
formatter.hasLocalExports = true;
var declar = this.get("declaration");
if (declar.isStatement()) {
var bindings = declar.getBindingIdentifiers()
for (var name in bindings) {
var binding = bindings[name];
formatter._addExport(name, binding);
}
}
if (this.isExportNamedDeclaration() && node.specifiers) {
for (var i = 0; i < node.specifiers.length; i++) {
var specifier = node.specifiers[i];
var local = specifier.local;
if (!local) continue;
formatter._addExport(local.name, specifier.exported);
}
}
if (!t.isExportDefaultDeclaration(node)) {
var onlyDefault = node.specifiers && node.specifiers.length === 1 && t.isSpecifierDefault(node.specifiers[0]);
if (!onlyDefault) {
formatter.hasNonDefaultExports = true;
}
}
}
}
});
export default class DefaultFormatter {
constructor(file) {
this.internalRemap = object();
@@ -121,8 +131,7 @@ export default class DefaultFormatter {
this.localExports = object();
this.localImports = object();
this.getLocalExports();
this.getLocalImports();
this.getMetadata();
}
isModuleType(node, type) {
@@ -138,12 +147,15 @@ export default class DefaultFormatter {
return (t.isExportDefaultDeclaration(node) || t.isSpecifierDefault(node)) && !this.noInteropRequireExport && !this.hasNonDefaultExports;
}
getLocalExports() {
this.file.path.traverse(exportsVisitor, this);
}
getLocalImports() {
this.file.path.traverse(importsVisitor, this);
getMetadata() {
var has = false;
for (var node of (this.file.ast.program.body: Array)) {
if (t.isModuleDeclaration(node)) {
has = true;
break;
}
}
if (has) this.file.path.traverse(metadataVisitor, this);
}
remapAssignments() {

View File

@@ -10,4 +10,4 @@ export default function (Parent) {
util.inherits(Constructor, Parent);
return Constructor;
};
}

View File

@@ -6,8 +6,8 @@ import * as util from "../../util";
import * as t from "../../types";
export default class AMDFormatter extends DefaultFormatter {
init() {
CommonFormatter.prototype._init.call(this, this.hasNonDefaultExports);
setup() {
CommonFormatter.prototype._setup.call(this, this.hasNonDefaultExports);
}
buildDependencyLiterals() {
@@ -92,9 +92,9 @@ export default class AMDFormatter extends DefaultFormatter {
// import foo from "foo";
var uid = this.scope.generateUidIdentifier(specifier.local.name);
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(uid, t.callExpression(this.file.addHelper("interop-require"), [ref]))
t.variableDeclarator(uid, t.callExpression(this.file.addHelper("interop-require-default"), [ref]))
]));
ref = uid;
ref = t.memberExpression(uid, t.identifier("default"));
} else {
// import { foo } from "foo";
var imported = specifier.imported;

View File

@@ -1,14 +1,13 @@
import DefaultFormatter from "./_default";
import includes from "lodash/collection/includes";
import * as util from "../../util";
import * as t from "../../types";
export default class CommonJSFormatter extends DefaultFormatter {
init() {
this._init(this.hasLocalExports);
setup() {
this._setup(this.hasLocalExports);
}
_init(conditional) {
_setup(conditional) {
var file = this.file;
var scope = file.scope;
@@ -52,7 +51,7 @@ export default class CommonJSFormatter extends DefaultFormatter {
} else if (this.noInteropRequireImport) {
this.internalRemap[variableName.name] = t.memberExpression(ref, t.identifier("default"));
} else {
var uid = this.scope.generateUidBasedOnNode(node, "import");
var uid = this.scope.generateUidIdentifierBasedOnNode(node, "import");
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(uid, t.callExpression(this.file.addHelper("interop-require-default"), [ref]))
@@ -84,7 +83,7 @@ export default class CommonJSFormatter extends DefaultFormatter {
}, true));
}
exportSpecifier(specifier, node, nodes) {
exportSpecifier(specifier) {
if (this.doDefaultExportInterop(specifier)) {
this.hasDefaultOnlyExport = true;
}
@@ -92,7 +91,7 @@ export default class CommonJSFormatter extends DefaultFormatter {
DefaultFormatter.prototype.exportSpecifier.apply(this, arguments);
}
exportDeclaration(node, nodes) {
exportDeclaration(node) {
if (this.doDefaultExportInterop(node)) {
this.hasDefaultOnlyExport = true;
}
@@ -101,8 +100,6 @@ export default class CommonJSFormatter extends DefaultFormatter {
}
_getExternalReference(node, nodes) {
var source = node.source.value;
var call = t.callExpression(t.identifier("require"), [node.source]);
var uid;
@@ -111,7 +108,7 @@ export default class CommonJSFormatter extends DefaultFormatter {
} else if (this.isModuleType(node, "absoluteDefault")) {
call = t.memberExpression(call, t.identifier("default"));
} else {
uid = this.scope.generateUidBasedOnNode(node, "import");
uid = this.scope.generateUidIdentifierBasedOnNode(node, "import");
}
uid = uid || node.specifiers[0].local;

View File

@@ -1,57 +1,57 @@
import DefaultFormatter from "./_default";
import AMDFormatter from "./amd";
import object from "../../helpers/object";
import * as util from "../../util";
import last from "lodash/array/last";
import each from "lodash/collection/each";
import map from "lodash/collection/map";
import * as t from "../../types";
var hoistVariablesVisitor = {
enter(node, parent, scope, state) {
if (t.isFunction(node)) {
// nothing inside is accessible
return this.skip();
Function() {
// nothing inside is accessible
this.skip();
},
VariableDeclaration(node, parent, scope, state) {
if (node.kind !== "var" && !t.isProgram(parent)) { // let, const
// can't be accessed
return;
}
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 (state.formatter._canHoist(node)) return;
var nodes = [];
for (var i = 0; i < node.declarations.length; i++) {
var declar = node.declarations[i];
state.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);
}
// ignore block hoisted nodes as these can be left in
if (state.formatter.canHoist(node)) return;
var nodes = [];
for (var i = 0; i < node.declarations.length; i++) {
var declar = node.declarations[i];
state.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) && parent.left === node) {
return node.declarations[0].id;
}
return nodes;
}
// for (var i in test)
// for (var i = 0;;)
if (t.isFor(parent) && (parent.left === node || parent.init === node)) {
return node.declarations[0].id;
}
return nodes;
}
};
var hoistFunctionsVisitor = {
enter(node, parent, scope, state) {
if (t.isFunction(node)) this.skip();
Function() {
this.skip();
},
if (t.isFunctionDeclaration(node) || state.formatter.canHoist(node)) {
enter(node, parent, scope, state) {
if (t.isFunctionDeclaration(node) || state.formatter._canHoist(node)) {
state.handlerBody.push(node);
this.remove();
this.dangerouslyRemove();
}
}
};
@@ -60,17 +60,17 @@ var runnerSettersVisitor = {
enter(node, parent, scope, state) {
if (node._importSource === state.source) {
if (t.isVariableDeclaration(node)) {
each(node.declarations, function (declar) {
for (var declar of (node.declarations: Array)) {
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();
this.dangerouslyRemove();
}
}
};
@@ -100,14 +100,14 @@ export default class SystemFormatter extends AMDFormatter {
var right = objectIdentifier;
var block = t.blockStatement([
t.expressionStatement(this.buildExportCall(leftIdentifier, valIdentifier))
t.expressionStatement(this._buildExportCall(leftIdentifier, valIdentifier))
]);
return this._addImportSource(t.forInStatement(left, right, block), node);
}
buildExportsAssignment(id, init, node) {
var call = this.buildExportCall(t.literal(id.name), init, true);
var call = this._buildExportCall(t.literal(id.name), init, true);
return this._addImportSource(call, node);
}
@@ -119,13 +119,13 @@ export default class SystemFormatter extends AMDFormatter {
var assign = node;
for (var i = 0; i < exported.length; i++) {
assign = this.buildExportCall(t.literal(exported[i].name), assign);
assign = this._buildExportCall(t.literal(exported[i].name), assign);
}
return assign;
}
buildExportCall(id, init, isStatement) {
_buildExportCall(id, init, isStatement) {
var call = t.callExpression(this.exportIdentifier, [id, init]);
if (isStatement) {
return t.expressionStatement(call);
@@ -143,12 +143,12 @@ export default class SystemFormatter extends AMDFormatter {
]));
}
this.internalRemap = {};
this.internalRemap = object();
this._addImportSource(last(nodes), node);
}
buildRunnerSetters(block, hoistDeclarators) {
_buildRunnerSetters(block, hoistDeclarators) {
var scope = this.file.scope;
return t.arrayExpression(map(this.ids, function (uid, source) {
@@ -164,7 +164,7 @@ export default class SystemFormatter extends AMDFormatter {
}));
}
canHoist(node) {
_canHoist(node) {
return node._blockHoist && !this.file.dynamicImports.length;
}
@@ -181,7 +181,7 @@ export default class SystemFormatter extends AMDFormatter {
MODULE_DEPENDENCIES: t.arrayExpression(this.buildDependencyLiterals()),
EXPORT_IDENTIFIER: this.exportIdentifier,
MODULE_NAME: moduleNameLiteral,
SETTERS: this.buildRunnerSetters(block, hoistDeclarators),
SETTERS: this._buildRunnerSetters(block, hoistDeclarators),
EXECUTE: t.functionExpression(null, [], block)
}, true);

View File

@@ -28,8 +28,9 @@
if (descriptor.initializer) {
descriptor.value = descriptor.initializer.call(target);
Object.defineProperty(target, key, descriptor);
}
Object.defineProperty(target, key, descriptor);
}
return target;

View File

@@ -1,12 +1,12 @@
(function (target, key, descriptors) {
var _descriptor = descriptors[key];
if (!_descriptor) return;
// clone it
var descriptor = {};
for (var _key in _descriptor) descriptor[_key] = _descriptor[_key];
// initialize it
if (!descriptor.initializer) return;
descriptor.value = descriptor.initializer.call(target);
Object.defineProperty(target, key, descriptor);

View File

@@ -1 +0,0 @@
Object(RIGHT)[LEFT] !== undefined;

View File

@@ -1,4 +0,0 @@
(function (proxy, directory) {
directory.push(proxy);
return proxy;
})

View File

@@ -1,3 +1,3 @@
for (var LEN = ARGUMENTS.length, ARRAY = Array(ARRAY_LEN), KEY = START; KEY < LEN; KEY++) {
for (var LEN = ARGUMENTS.length, ARRAY: ARRAY_TYPE = Array(ARRAY_LEN), KEY = START; KEY < LEN; KEY++) {
ARRAY[ARRAY_KEY] = ARGUMENTS[KEY];
}

View File

@@ -1,5 +1,6 @@
import includes from "lodash/collection/includes";
import type Transformer from "./transformer";
import traverse from "../traversal";
import type File from "./file";
/**
* This class is responsible for traversing over the provided `File`s
@@ -8,35 +9,27 @@ import traverse from "../traversal";
export default class TransformerPass {
constructor(file: File, transformer: Transformer) {
this.shouldTransform = !transformer.shouldVisit;
this.transformer = transformer;
this.handlers = transformer.handlers;
this.skipKey = transformer.skipKey;
this.file = file;
this.ran = false;
this.transformer = transformer;
this.handlers = transformer.handlers;
this.file = file;
this.key = transformer.key;
if (this.canTransform() && transformer.metadata.experimental && !file.opts.experimental) {
file.log.warn(`THE TRANSFORMER ${this.key} HAS BEEN MARKED AS EXPERIMENTAL AND IS WIP. USE AT YOUR OWN RISK. ` +
"THIS WILL HIGHLY LIKELY BREAK YOUR CODE SO USE WITH **EXTREME** CAUTION. ENABLE THE " +
"`experimental` OPTION TO IGNORE THIS WARNING.");
}
}
canTransform(): boolean {
return this.file.pipeline.canTransform(this.transformer, this.file.opts);
}
checkPath(path: TraversalPath): boolean {
if (this.shouldTransform || this.ran) return;
this.shouldTransform = this.transformer.shouldVisit(path.node);
return this.file.transformerDependencies[this.key] ||
this.file.pipeline.canTransform(this.transformer, this.file.opts);
}
transform() {
if (!this.shouldTransform) return;
var file = this.file;
file.log.debug(`Start transformer ${this.transformer.key}`);
file.log.debug(`Start transformer ${this.key}`);
traverse(file.ast, this.handlers, file.scope, file);
file.log.debug(`Finish transformer ${this.transformer.key}`);
this.ran = true;
file.log.debug(`Finish transformer ${this.key}`);
}
}

View File

@@ -47,6 +47,8 @@ export default class TransformerPipeline {
}
canTransform(transformer, fileOpts) {
if (transformer.metadata.plugin) return true;
for (var filter of (this.filters: Array)) {
var result = filter(transformer, fileOpts);
if (result != null) return result;
@@ -55,10 +57,21 @@ export default class TransformerPipeline {
return true;
}
pretransform(code: string, opts?: Object) {
var file = new File(opts, this);
return file.wrap(code, function () {
file.addCode(code);
file.parseCode(code);
return file;
});
}
transform(code: string, opts?: Object) {
var file = new File(opts, this);
return file.wrap(code, function () {
file.addCode(code, true);
file.addCode(code);
file.parseCode(code);
return file.transform();
});
}
@@ -69,6 +82,7 @@ export default class TransformerPipeline {
return file.wrap(code, function () {
file.addCode(code);
file.addAst(ast);
return file.transform();
});
}

View File

@@ -4,7 +4,6 @@ import isFunction from "lodash/lang/isFunction";
import traverse from "../traversal";
import isObject from "lodash/lang/isObject";
import assign from "lodash/object/assign";
import * as acorn from "../../acorn";
import File from "./file";
import each from "lodash/collection/each";
@@ -25,8 +24,8 @@ export default class Transformer {
};
this.manipulateOptions = take("manipulateOptions");
this.shouldVisit = take("shouldVisit");
this.metadata = take("metadata") || {};
this.dependencies = this.metadata.dependencies || [];
this.parser = take("parser");
this.post = take("post");
this.pre = take("pre");
@@ -41,18 +40,6 @@ export default class Transformer {
this.handlers = this.normalize(transformer);
this.key = transformerKey;
//
if (!this.shouldVisit) {
var types = Object.keys(this.handlers);
this.shouldVisit = function (node) {
for (var i = 0; i < types.length; i++) {
if (node.type === types[i]) return true;
}
return false;
};
}
}
normalize(transformer: Object): Object {

View File

@@ -1,5 +1,6 @@
{
"useStrict": "strict",
"es5.runtime": "runtime",
"es6.runtime": "runtime"
"es6.runtime": "runtime",
"minification.inlineExpressions": "minification.constantFolding"
}

View File

@@ -5,7 +5,8 @@
"es6.symbols": "es6.spec.symbols",
"es6.blockScopingTDZ": "es6.spec.blockScoping",
"utility.inlineExpressions": "minification.constantFolding",
"utility.deadCodeElimination": "minification.deadCodeElimination",
"minification.removeConsoleCalls": "utility.removeConsole",
"minification.removeDebugger": "utility.removeDebugger"
"utility.removeConsoleCalls": "minification.removeConsole",
"utility.removeDebugger": "minification.removeDebugger"
}

View File

@@ -1,10 +1,16 @@
import * as t from "../../../types";
export function MemberExpression(node) {
var prop = node.property;
if (!node.computed && t.isIdentifier(prop) && !t.isValidIdentifier(prop.name)) {
// foo.default -> foo["default"]
node.property = t.literal(prop.name);
node.computed = true;
export var metadata = {
group: "builtin-trailing"
};
export var MemberExpression = {
exit(node) {
var prop = node.property;
if (!node.computed && t.isIdentifier(prop) && !t.isValidIdentifier(prop.name)) {
// foo.default -> foo["default"]
node.property = t.literal(prop.name);
node.computed = true;
}
}
}
};

View File

@@ -1,9 +1,15 @@
import * as t from "../../../types";
export function Property(node) {
var key = node.key;
if (!node.computed && t.isIdentifier(key) && !t.isValidIdentifier(key.name)) {
// default: "bar" -> "default": "bar"
node.key = t.literal(key.name);
export var metadata = {
group: "builtin-trailing"
};
export var Property = {
exit(node) {
var key = node.key;
if (!node.computed && t.isIdentifier(key) && !t.isValidIdentifier(key.name)) {
// default: "bar" -> "default": "bar"
node.key = t.literal(key.name);
}
}
}
};

View File

@@ -1,17 +1,20 @@
import * as defineMap from "../../helpers/define-map";
import * as t from "../../../types";
export function shouldVisit(node) {
return t.isProperty(node) && (node.kind === "get" || node.kind === "set");
}
export function ObjectExpression(node, parent, scope, file) {
var mutatorMap = {};
var hasAny = false;
for (var prop of (node.properties: Array)) {
if (prop.kind === "get" || prop.kind === "set") {
hasAny = true;
break;
}
}
if (!hasAny) return;
var mutatorMap = {};
node.properties = node.properties.filter(function (prop) {
if (prop.kind === "get" || prop.kind === "set") {
hasAny = true;
defineMap.push(mutatorMap, prop, prop.kind, file);
return false;
} else {
@@ -19,8 +22,6 @@ export function ObjectExpression(node, parent, scope, file) {
}
});
if (!hasAny) return;
return t.callExpression(
t.memberExpression(t.identifier("Object"), t.identifier("defineProperties")),
[node, defineMap.toDefineObject(mutatorMap)]

View File

@@ -1,7 +1,5 @@
import * as t from "../../../types";
export var shouldVisit = t.isArrowFunctionExpression;
export function ArrowFunctionExpression(node) {
t.ensureBlock(node);

View File

@@ -1,3 +1,6 @@
import type NodePath from "../../../traversal/path";
import type Scope from "../../../traversal/scope";
import type File from "../../file";
import traverse from "../../../traversal";
import object from "../../../helpers/object";
import * as util from "../../../util";
@@ -32,14 +35,14 @@ function isVar(node, parent) {
}
function standardizeLets(declars) {
for (var i = 0; i < declars.length; i++) {
delete declars[i]._let;
for (var declar of (declars: Array)) {
delete declar._let;
}
}
export function shouldVisit(node) {
return t.isVariableDeclaration(node) && (node.kind === "let" || node.kind === "const");
}
export var metadata = {
group: "builtin-advanced"
};
export function VariableDeclaration(node, parent, scope, file) {
if (!isLet(node, parent)) return;
@@ -84,8 +87,6 @@ export function BlockStatement(block, parent, scope, file) {
export { BlockStatement as Program };
function replace(node, parent, scope, remaps) {
if (!t.isReferencedIdentifier(node, parent)) return;
var remap = remaps[node.name];
if (!remap) return;
@@ -100,28 +101,33 @@ function replace(node, parent, scope, remaps) {
}
var replaceVisitor = {
enter: replace
ReferencedIdentifier: replace,
AssignmentExpression(node, parent, scope, remaps) {
var ids = this.getBindingIdentifiers();
for (var name in ids) {
replace(ids[name], node, scope, remaps);
}
},
};
function traverseReplace(node, parent, scope, remaps) {
replace(node, parent, scope, remaps);
if (t.isIdentifier(node)) {
replace(node, parent, scope, remaps);
}
scope.traverse(node, replaceVisitor, remaps);
}
var letReferenceBlockVisitor = {
enter(node, parent, scope, state) {
if (this.isFunction()) {
this.traverse(letReferenceFunctionVisitor, state);
return this.skip();
}
Function(node, parent, scope, state) {
this.traverse(letReferenceFunctionVisitor, state);
return this.skip();
}
};
var letReferenceFunctionVisitor = {
enter(node, parent, scope, state) {
// not a direct reference
if (!this.isReferencedIdentifier()) return;
ReferencedIdentifier(node, parent, scope, state) {
var ref = state.letReferences[node.name];
// not a part of our scope
@@ -159,10 +165,8 @@ var hoistVarDeclarationsVisitor = {
};
var loopLabelVisitor = {
enter(node, parent, scope, state) {
if (this.isLabeledStatement()) {
state.innerLabels.push(node.label.name);
}
LabeledStatement(node, parent, scope, state) {
state.innerLabels.push(node.label.name);
}
};
@@ -187,19 +191,28 @@ var loopNodeTo = function (node) {
};
var loopVisitor = {
Loop(node, parent, scope, state) {
var oldIgnoreLabeless = state.ignoreLabeless;
state.ignoreLabeless = true;
this.traverse(loopVisitor, state);
state.ignoreLabeless = oldIgnoreLabeless;
this.skip();
},
Function() {
this.skip();
},
SwitchCase(node, parent, scope, state) {
var oldInSwitchCase = state.inSwitchCase;
state.inSwitchCase = true;
this.traverse(loopVisitor, state);
state.inSwitchCase = oldInSwitchCase;
this.skip();
},
enter(node, parent, scope, state) {
var replace;
if (this.isLoop()) {
state.ignoreLabeless = true;
this.traverse(loopVisitor, state);
state.ignoreLabeless = false;
}
if (this.isFunction() || this.isLoop()) {
return this.skip();
}
var loopText = loopNodeTo(node);
if (loopText) {
@@ -215,6 +228,9 @@ var loopVisitor = {
// they don't refer to the actual loop we're scopifying
if (state.ignoreLabeless) return;
//
if (state.inSwitchCase) return;
// break statements mean something different in this context
if (t.isBreakStatement(node) && t.isSwitchCase(parent)) return;
}
@@ -233,6 +249,7 @@ var loopVisitor = {
if (replace) {
replace = t.returnStatement(replace);
this.skip();
return t.inherits(replace, node);
}
}
@@ -244,7 +261,7 @@ class BlockScoping {
* Description
*/
constructor(loopPath?: TraversalPath, blockPath: TraversalPath, parent: Object, scope: Scope, file: File) {
constructor(loopPath?: NodePath, blockPath: NodePath, parent: Object, scope: Scope, file: File) {
this.parent = parent;
this.scope = scope;
this.file = file;
@@ -467,18 +484,17 @@ class BlockScoping {
var block = this.block;
var declarators = block._letDeclarators || [];
var declar;
//
for (let i = 0; i < declarators.length; i++) {
declar = declarators[i];
let declar = declarators[i];
extend(this.outsideLetReferences, t.getBindingIdentifiers(declar));
}
//
if (block.body) {
for (let i = 0; i < block.body.length; i++) {
declar = block.body[i];
let declar = block.body[i];
if (isLet(declar, block)) {
declarators = declarators.concat(declar.declarations);
}
@@ -487,7 +503,7 @@ class BlockScoping {
//
for (let i = 0; i < declarators.length; i++) {
declar = declarators[i];
let declar = declarators[i];
var keys = t.getBindingIdentifiers(declar);
extend(this.letReferences, keys);
this.hasLetReferences = true;
@@ -524,6 +540,7 @@ class BlockScoping {
var state = {
hasBreakContinue: false,
ignoreLabeless: false,
inSwitchCase: false,
innerLabels: [],
hasReturn: false,
isLoop: !!this.loop,
@@ -551,9 +568,13 @@ class BlockScoping {
*/
pushDeclar(node: { type: "VariableDeclaration" }): Array<Object> {
this.body.push(t.variableDeclaration(node.kind, node.declarations.map(function (declar) {
return t.variableDeclarator(declar.id);
})));
var declars = [];
var names = t.getBindingIdentifiers(node);
for (var name in names) {
declars.push(t.variableDeclarator(names[name]));
}
this.body.push(t.variableDeclaration(node.kind, declars));
var replace = [];
@@ -579,7 +600,6 @@ class BlockScoping {
t.variableDeclarator(ret, call)
]));
var loop = this.loop;
var retCheck;
var has = this.has;
var cases = [];

View File

@@ -1,18 +1,15 @@
import type NodePath from "../../../traversal/path";
import type File from "../../file";
import memoiseDecorators from "../../helpers/memoise-decorators";
import ReplaceSupers from "../../helpers/replace-supers";
import * as nameMethod from "../../helpers/name-method";
import * as defineMap from "../../helpers/define-map";
import * as messages from "../../../messages";
import * as util from "../../../util";
import traverse from "../../../traversal";
import each from "lodash/collection/each";
import has from "lodash/object/has";
import * as t from "../../../types";
const PROPERTY_COLLISION_METHOD_NAME = "__initializeProperties";
export var shouldVisit = t.isClass;
export function ClassDeclaration(node, parent, scope, file) {
return t.variableDeclaration("let", [
t.variableDeclarator(node.id, t.toExpression(node))
@@ -37,23 +34,7 @@ var collectPropertyReferencesVisitor = {
}
};
var constructorVisitor = traverse.explode({
ThisExpression: {
enter(node, parent, scope, ref) {
return ref;
}
},
Function: {
enter(node) {
if (!node.shadow) {
this.skip();
}
}
}
});
var verifyConstructorVisitor = traverse.explode({
var verifyConstructorVisitor = {
MethodDefinition: {
enter() {
this.skip();
@@ -98,7 +79,7 @@ var verifyConstructorVisitor = traverse.explode({
}
}
}
});
};
class ClassTransformer {
@@ -106,7 +87,7 @@ class ClassTransformer {
* Description
*/
constructor(path: TraversalPath, file: File) {
constructor(path: NodePath, file: File) {
this.parent = path.parent;
this.scope = path.scope;
this.node = path.node;
@@ -143,8 +124,6 @@ class ClassTransformer {
run() {
var superName = this.superName;
var className = this.className;
var classBody = this.node.body.body;
var classRef = this.classRef;
var file = this.file;
@@ -175,7 +154,7 @@ class ClassTransformer {
if (this.hasSuper) {
closureArgs.push(superName);
superName = this.scope.generateUidBasedOnNode(superName);
superName = this.scope.generateUidIdentifierBasedOnNode(superName);
closureParams.push(superName);
this.superName = superName;
@@ -264,7 +243,7 @@ class ClassTransformer {
var map = defineMap.push(mutatorMap, node, kind, this.file);
if (enumerable) {
map.enumerable = t.literal(true)
map.enumerable = t.literal(true);
}
if (map.decorators) {
@@ -278,9 +257,6 @@ class ClassTransformer {
buildBody() {
var constructorBody = this.constructorBody;
var constructor = this.constructor;
var className = this.className;
var superName = this.superName;
var classBody = this.node.body.body;
var body = this.body;
@@ -314,10 +290,10 @@ class ClassTransformer {
if (isConstructor) {
this.pushConstructor(node, path);
} else {
this.pushMethod(node);
this.pushMethod(node, path);
}
} else if (t.isClassProperty(node)) {
this.pushProperty(node);
this.pushProperty(node, path);
}
}
@@ -377,7 +353,7 @@ class ClassTransformer {
}
var lastNonNullIndex = 0;
for (var i = 0; i < args.length; i++) {
for (let i = 0; i < args.length; i++) {
if (args[i] !== nullNode) lastNonNullIndex = i;
}
args = args.slice(0, lastNonNullIndex + 1);
@@ -412,7 +388,7 @@ class ClassTransformer {
this.pushMethod(t.methodDefinition(
t.identifier(PROPERTY_COLLISION_METHOD_NAME),
t.functionExpression(null, [], t.blockStatement(body))
), true);
), null, true);
if (this.hasSuper) {
this.bareSuper.insertAfter(call);
@@ -452,7 +428,7 @@ class ClassTransformer {
* Description
*/
verifyConstructor(path: TraversalPath) {
verifyConstructor(path: NodePath) {
var state = {
hasBareSuper: false,
bareSuper: null,
@@ -473,15 +449,15 @@ class ClassTransformer {
* Push a method to its respective mutatorMap.
*/
pushMethod(node: { type: "MethodDefinition" }, allowedIllegal?) {
pushMethod(node: { type: "MethodDefinition" }, path?: NodePath, allowedIllegal?) {
if (!allowedIllegal && t.isLiteral(t.toComputedKey(node), { value: PROPERTY_COLLISION_METHOD_NAME })) {
throw this.file.errorWithNode(node, messages.get("illegalMethodName", PROPERTY_COLLISION_METHOD_NAME));
}
if (node.kind === "method") {
nameMethod.property(node, this.file, this.scope);
nameMethod.property(node, this.file, path ? path.get("value").scope : this.scope);
if (this.isLoose) {
if (this.isLoose && !node.decorators) {
// use assignments instead of define properties for loose classes
var classRef = this.classRef;
@@ -502,10 +478,8 @@ class ClassTransformer {
* Description
*/
pushProperty(node: { type: "ClassProperty" }) {
var key;
this.scope.traverse(node, collectPropertyReferencesVisitor, {
pushProperty(node: { type: "ClassProperty" }, path: NodePath) {
path.traverse(collectPropertyReferencesVisitor, {
references: this.instancePropRefs,
scope: this.scope
});
@@ -521,7 +495,6 @@ class ClassTransformer {
this.pushToMap(node, true, "initializer");
var initializers;
var body;
var target;
if (node.static) {
initializers = this.staticInitializersId = this.staticInitializersId || this.scope.generateUidIdentifier("staticInitializers");
@@ -560,7 +533,7 @@ class ClassTransformer {
* Replace the constructor body of our class.
*/
pushConstructor(method: { type: "MethodDefinition" }, path: TraversalPath) {
pushConstructor(method: { type: "MethodDefinition" }, path: NodePath) {
// https://github.com/babel/babel/issues/1077
var fnPath = path.get("value");
if (fnPath.scope.hasOwnBinding(this.classRef.name)) {

View File

@@ -1,48 +1,41 @@
import * as messages from "../../../messages";
import * as t from "../../../types";
export function shouldVisit(node) {
return t.isVariableDeclaration(node, { kind: "const" }) || t.isImportDeclaration(node);
}
function checkPath(path, file) {
var ids = path.getBindingIdentifiers();
var visitor = {
enter(node, parent, scope, state) {
if (this.isAssignmentExpression() || this.isUpdateExpression()) {
var ids = this.getBindingIdentifiers();
for (var name in ids) {
var id = ids[name];
for (var name in ids) {
var id = ids[name];
var binding = path.scope.getBinding(name);
var constant = state.constants[name];
// no binding exists
if (!binding) continue;
// no constant exists
if (!constant) continue;
// not a constant
if (binding.kind !== "const" && binding.kind !== "module") continue;
var constantIdentifier = constant.identifier;
// check if the assignment id matches the constant declaration id
// if it does then it was the id used to initially declare the
// constant so we can just ignore it
if (binding.identifier === id) continue;
// check if the assignment id matches the constant declaration id
// if it does then it was the id used to initially declare the
// constant so we can just ignore it
if (id === constantIdentifier) continue;
// check if there's been a local binding that shadows this constant
if (!scope.bindingIdentifierEquals(name, constantIdentifier)) continue;
throw state.file.errorWithNode(id, messages.get("readOnly", name));
}
} else if (this.isScope()) {
this.skip();
}
throw file.errorWithNode(id, messages.get("readOnly", name));
}
};
export function Scopable(node, parent, scope, file) {
this.traverse(visitor, {
constants: scope.getAllBindingsOfKind("const", "module"),
file: file
});
}
export function AssignmentExpression(node, parent, scope, file) {
checkPath(this, file);
}
export { AssignmentExpression as UpdateExpression };
export function VariableDeclaration(node) {
if (node.kind === "const") node.kind = "let";
}
export function ForXStatement(node, parent, scope, file) {
var left = this.get("left");
if (left.isIdentifier() || left.isPattern()) {
checkPath(left, file);
}
}

View File

@@ -1,7 +1,9 @@
import * as messages from "../../../messages";
import * as t from "../../../types";
export var shouldVisit = t.isPattern;
export var metadata = {
group: "builtin-advanced"
};
export function ForOfStatement(node, parent, scope, file) {
var left = node.left;
@@ -53,7 +55,7 @@ export function ForOfStatement(node, parent, scope, file) {
export { ForOfStatement as ForInStatement };
exports.Function = function (node, parent, scope, file) {
export function Func/*tion*/(node, parent, scope, file) {
var nodes = [];
var hasDestructuring = false;
@@ -63,6 +65,7 @@ exports.Function = function (node, parent, scope, file) {
hasDestructuring = true;
var ref = scope.generateUidIdentifier("ref");
t.inherits(ref, pattern);
var destructuring = new DestructuringTransformer({
blockHoist: node.params.length - i,
@@ -82,8 +85,7 @@ exports.Function = function (node, parent, scope, file) {
var block = node.body;
block.body = nodes.concat(block.body);
this.checkSelf();
};
}
export function CatchClause(node, parent, scope, file) {
var pattern = node.param;
@@ -103,34 +105,12 @@ export function CatchClause(node, parent, scope, file) {
destructuring.init(pattern, ref);
node.body.body = nodes.concat(node.body.body);
this.checkSelf();
}
export function ExpressionStatement(node, parent, scope, file) {
var expr = node.expression;
if (expr.type !== "AssignmentExpression") return;
if (!t.isPattern(expr.left)) return;
if (this.isCompletionRecord()) return;
var destructuring = new DestructuringTransformer({
operator: expr.operator,
scope: scope,
file: file,
});
return destructuring.init(expr.left, expr.right);
}
export function AssignmentExpression(node, parent, scope, file) {
if (!t.isPattern(node.left)) return;
var ref = scope.generateUidIdentifier("temp");
var nodes = [];
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(ref, node.right)
]));
var destructuring = new DestructuringTransformer({
operator: node.operator,
@@ -139,13 +119,24 @@ export function AssignmentExpression(node, parent, scope, file) {
nodes: nodes
});
if (t.isArrayExpression(node.right)) {
destructuring.arrays[ref.name] = true;
var ref;
if (this.isCompletionRecord() || !this.parentPath.isExpressionStatement()) {
ref = scope.generateUidIdentifierBasedOnNode(node.right, "ref");
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(ref, node.right)
]));
if (t.isArrayExpression(node.right)) {
destructuring.arrays[ref.name] = true;
}
}
destructuring.init(node.left, ref);
destructuring.init(node.left, ref || node.right);
nodes.push(t.expressionStatement(ref));
if (ref) {
nodes.push(t.expressionStatement(ref));
}
return nodes;
}
@@ -160,7 +151,7 @@ function variableDeclarationHasPattern(node) {
}
export function VariableDeclaration(node, parent, scope, file) {
if (t.isForInStatement(parent) || t.isForOfStatement(parent)) return;
if (t.isForXStatement(parent)) return;
if (!variableDeclarationHasPattern(node)) return;
var nodes = [];
@@ -179,7 +170,7 @@ export function VariableDeclaration(node, parent, scope, file) {
file: file
});
if (t.isPattern(pattern) && patternId) {
if (t.isPattern(pattern)) {
destructuring.init(pattern, patternId);
if (+i !== node.declarations.length - 1) {
@@ -295,7 +286,7 @@ class DestructuringTransformer {
// we need to assign the current value of the assignment to avoid evaluating
// it more than once
var tempValueRef = this.scope.generateUidBasedOnNode(valueRef);
var tempValueRef = this.scope.generateUidIdentifierBasedOnNode(valueRef);
var declar = t.variableDeclaration("var", [
t.variableDeclarator(tempValueRef, valueRef)
@@ -377,7 +368,7 @@ class DestructuringTransformer {
// only evaluated once
if (pattern.properties.length > 1 && t.isMemberExpression(objRef)) {
var temp = this.scope.generateUidBasedOnNode(objRef, this.file);
var temp = this.scope.generateUidIdentifierBasedOnNode(objRef, this.file);
this.nodes.push(this.buildVariableDeclaration(temp, objRef));
objRef = temp;
}
@@ -461,7 +452,7 @@ class DestructuringTransformer {
// array
arrayRef = toArray;
} else {
arrayRef = this.scope.generateUidBasedOnNode(arrayRef);
arrayRef = this.scope.generateUidIdentifierBasedOnNode(arrayRef);
this.arrays[arrayRef.name] = true;
this.nodes.push(this.buildVariableDeclaration(arrayRef, toArray));
}
@@ -498,9 +489,8 @@ class DestructuringTransformer {
// trying to destructure a value that we can't evaluate more than once so we
// need to save it to a variable
var shouldMemoise = true;
if (!t.isArrayExpression(ref) && !t.isMemberExpression(ref)) {
var memo = this.scope.generateMemoisedReference(ref, true);
var memo = this.scope.maybeGenerateMemoised(ref, true);
if (memo) {
this.nodes.push(this.buildVariableDeclaration(memo, ref));
ref = memo;

View File

@@ -2,8 +2,6 @@ import * as messages from "../../../messages";
import * as util from "../../../util";
import * as t from "../../../types";
export var shouldVisit = t.isForOfStatement;
export function ForOfStatement(node, parent, scope, file) {
if (this.get("right").isArrayExpression()) {
return _ForOfStatementArray.call(this, node, scope, file);
@@ -33,9 +31,9 @@ export function ForOfStatement(node, parent, scope, file) {
if (build.replaceParent) {
this.parentPath.replaceWithMultiple(build.node);
this.remove();
this.dangerouslyRemove();
} else {
this.replaceWithMultiple(build.node);
return build.node;
}
}

View File

@@ -1,7 +1,5 @@
import * as t from "../../../types";
export { check } from "../internal/modules";
function keepBlockHoist(node, nodes) {
if (node._blockHoist) {
for (let i = 0; i < nodes.length; i++) {
@@ -10,6 +8,10 @@ function keepBlockHoist(node, nodes) {
}
}
export var metadata = {
group: "builtin-modules"
};
export function ImportDeclaration(node, parent, scope, file) {
// flow type
if (node.isType) return;
@@ -17,8 +19,8 @@ export function ImportDeclaration(node, parent, scope, file) {
var nodes = [];
if (node.specifiers.length) {
for (var i = 0; i < node.specifiers.length; i++) {
file.moduleFormatter.importSpecifier(node.specifiers[i], node, nodes, parent);
for (var specifier of (node.specifiers: Array)) {
file.moduleFormatter.importSpecifier(specifier, node, nodes, parent);
}
} else {
file.moduleFormatter.importDeclaration(node, nodes, parent);

View File

@@ -1,33 +1,20 @@
import ReplaceSupers from "../../helpers/replace-supers";
import * as t from "../../../types";
export var shouldVisit = t.isSuper;
function Property(path, node, scope, getObjectRef, file) {
if (!node.method) return;
var value = node.value;
var thisExpr = scope.generateUidIdentifier("this");
if (!node.method && node.kind === "init") return;
if (!t.isFunction(node.value)) return;
var replaceSupers = new ReplaceSupers({
topLevelThisReference: thisExpr,
getObjectRef: getObjectRef,
methodNode: node,
methodPath: path,
isStatic: true,
scope: scope,
file: file
getObjectRef: getObjectRef,
methodNode: node,
methodPath: path,
isStatic: true,
scope: scope,
file: file
});
replaceSupers.replace();
if (replaceSupers.hasSuper) {
value.body.body.unshift(
t.variableDeclaration("var", [
t.variableDeclarator(thisExpr, t.thisExpression())
])
);
}
}
export function ObjectExpression(node, parent, scope, file) {

View File

@@ -2,10 +2,6 @@ import callDelegate from "../../helpers/call-delegate";
import * as util from "../../../util";
import * as t from "../../../types";
export function shouldVisit(node) {
return t.isFunction(node) && hasDefaults(node);
}
var hasDefaults = function (node) {
for (var i = 0; i < node.params.length; i++) {
if (!t.isIdentifier(node.params[i])) return true;
@@ -14,17 +10,18 @@ var hasDefaults = function (node) {
};
var iifeVisitor = {
enter(node, parent, scope, state) {
if (!this.isReferencedIdentifier()) return;
if (!state.scope.hasOwnBinding(node.name)) return;
if (state.scope.bindingIdentifierEquals(node.name, node)) return;
ReferencedIdentifier(node, parent, scope, state) {
if (node.name !== "eval") {
if (!state.scope.hasOwnBinding(node.name)) return;
if (state.scope.bindingIdentifierEquals(node.name, node)) return;
}
state.iife = true;
this.stop();
}
};
exports.Function = function (node, parent, scope, file) {
export function Func/*tion*/(node, parent, scope, file) {
if (!hasDefaults(node)) return;
t.ensureBlock(node);
@@ -96,6 +93,4 @@ exports.Function = function (node, parent, scope, file) {
} else {
node.body.body = body.concat(node.body.body);
}
this.checkSelf();
};
}

View File

@@ -2,8 +2,6 @@ import isNumber from "lodash/lang/isNumber";
import * as util from "../../../util";
import * as t from "../../../types";
export var shouldVisit = t.isRestElement;
var memberExpressionOptimisationVisitor = {
enter(node, parent, scope, state) {
// check if this scope has a local binding that will shadow the rest parameter
@@ -11,6 +9,13 @@ var memberExpressionOptimisationVisitor = {
return this.skip();
}
var stop = () => {
state.canOptimise = false;
this.stop();
};
if (this.isArrowFunctionExpression()) return stop();
// skip over functions as whatever `arguments` we reference inside will refer
// to the wrong function
if (this.isFunctionDeclaration() || this.isFunctionExpression()) {
@@ -33,8 +38,7 @@ var memberExpressionOptimisationVisitor = {
}
}
state.canOptimise = false;
this.stop();
stop();
}
};
@@ -55,10 +59,11 @@ var hasRest = function (node) {
return t.isRestElement(node.params[node.params.length - 1]);
};
exports.Function = function (node, parent, scope, file) {
export function Func/*tion*/(node, parent, scope, file) {
if (!hasRest(node)) return;
var rest = node.params.pop().argument;
var restParam = node.params.pop();
var rest = restParam.argument;
var argsId = t.identifier("arguments");
@@ -91,12 +96,10 @@ exports.Function = function (node, parent, scope, file) {
// we only have shorthands and there's no other references
if (state.canOptimise && state.candidates.length) {
for (var i = 0; i < state.candidates.length; i++) {
var candidate = state.candidates[i];
for (var candidate of (state.candidates: Array)) {
candidate.replaceWith(argsId);
optimizeMemberExpression(candidate.parent, node.params.length);
}
this.checkSelf();
return;
}
@@ -128,15 +131,15 @@ exports.Function = function (node, parent, scope, file) {
}
var loop = util.template("rest", {
ARGUMENTS: argsId,
ARRAY_KEY: arrKey,
ARRAY_LEN: arrLen,
START: start,
ARRAY: rest,
KEY: key,
LEN: len
ARRAY_TYPE: restParam.typeAnnotation,
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);
this.checkSelf();
};
}

View File

@@ -63,42 +63,40 @@ function spec(node, body, objId, initProps, file) {
}
}
export function shouldVisit(node) {
return t.isProperty(node) && node.computed;
}
export var ObjectExpression = {
exit(node, parent, scope, file) {
var hasComputed = false;
export function ObjectExpression(node, parent, scope, file) {
var hasComputed = false;
for (var prop of (node.properties: Array)) {
hasComputed = t.isProperty(prop, { computed: true, kind: "init" });
if (hasComputed) break;
}
for (var i = 0; i < node.properties.length; i++) {
hasComputed = t.isProperty(node.properties[i], { computed: true, kind: "init" });
if (hasComputed) break;
if (!hasComputed) return;
var initProps = [];
var objId = scope.generateUidIdentifierBasedOnNode(parent);
//
var body = [];
//
var callback = spec;
if (file.isLoose("es6.properties.computed")) callback = loose;
var result = callback(node, body, objId, initProps, file);
if (result) return result;
//
body.unshift(t.variableDeclaration("var", [
t.variableDeclarator(objId, t.objectExpression(initProps))
]));
body.push(t.expressionStatement(objId));
return body;
}
if (!hasComputed) return;
var initProps = [];
var objId = scope.generateUidBasedOnNode(parent);
//
var body = [];
//
var callback = spec;
if (file.isLoose("es6.properties.computed")) callback = loose;
var result = callback(node, body, objId, initProps, file);
if (result) return result;
//
body.unshift(t.variableDeclaration("var", [
t.variableDeclarator(objId, t.objectExpression(initProps))
]));
body.push(t.expressionStatement(objId));
return body;
}
};

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