Compare commits

..

465 Commits

Author SHA1 Message Date
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
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
Sebastian McKenzie
bbbf0a895d v5.2.12 2015-05-05 00:13:57 +01:00
Sebastian McKenzie
3289b33806 remove no self node replacement error 2015-05-05 00:13:07 +01:00
Sebastian McKenzie
f4b9faa6b3 clean up module declaration based UID generation - fixes #1437 2015-05-04 22:36:18 +01:00
Sebastian McKenzie
239b77816f 5.2.11 2015-05-04 22:33:26 +01:00
Sebastian McKenzie
8565e2b4e5 v5.2.11 2015-05-04 22:32:28 +01:00
Sebastian McKenzie
4317a46a3e add 5.2.11 changelog 2015-05-04 22:31:44 +01:00
Sebastian McKenzie
81ca29adc3 5.2.10 2015-05-04 22:31:38 +01:00
Sebastian McKenzie
c1a6ff7f44 rename getModuleName option to getModuleId 2015-05-04 22:31:34 +01:00
Sebastian McKenzie
7e6e5d4746 v5.2.10 2015-05-04 22:23:39 +01:00
Sebastian McKenzie
12d650e195 checkSelf() for destructuring catch clauses 2015-05-04 22:22:39 +01:00
Sebastian McKenzie
8fb58492df fix default specifiers not taking into consideration sourced imports 2015-05-04 22:20:52 +01:00
Sebastian McKenzie
2c0c2f12df avoid trying to replace a node with itself, antipattern! 2015-05-04 22:20:52 +01:00
Sebastian McKenzie
01e5354fd9 disallow replacing a node with itself 2015-05-04 22:20:52 +01:00
Sebastian McKenzie
0b100c4273 Merge pull request #1386 from jayphelps/module-id-overload
Added getModuleName() option as a function
2015-05-04 22:20:31 +01:00
Jay Phelps
340e75eb59 Added getModuleName() option as a function, allowing you to manipulate the name as needed 2015-05-04 13:30:57 -07:00
Sebastian McKenzie
53808a6d45 fix test/core/path imports 2015-05-04 15:25:35 +01:00
Sebastian McKenzie
e6326332b6 properly coerce input code to string - fixes #1432 2015-05-04 15:08:18 +01:00
Sebastian McKenzie
9e0cf84505 adds test for #1431 2015-05-04 15:06:27 +01:00
Sebastian McKenzie
b7eea7b08c Merge pull request #1431 from pangratz/fix_replaceWithSourceString
Fix bugs in `replaceWithSourceString`
2015-05-04 15:00:27 +01:00
pangratz
92dd67856e Fix bugs in replaceWithSourceString
This fixes 2 bugs within `replaceWithSourceString`:

- `code` is undefined as it should be `replacement`
- the expression of the parsed replacement hasn't been accessed correctly
2015-05-04 09:33:32 +02:00
Sebastian McKenzie
a2bb587e24 remove embedded jsx plugin and use acorn-jsx 2015-05-04 04:33:46 +01:00
Sebastian McKenzie
0c570cb599 5.2.9 2015-05-04 04:03:41 +01:00
Sebastian McKenzie
db6fab2c8f v5.2.9 2015-05-04 04:02:30 +01:00
Sebastian McKenzie
d92deb52b6 v5.2.8 2015-05-04 04:00:13 +01:00
Sebastian McKenzie
b8b70f2f4a rejigger around parse mechanics 2015-05-04 03:57:28 +01:00
Sebastian McKenzie
a8a3f6d34d Merge branch 'master' of github.com:babel/babel 2015-05-04 03:55:25 +01:00
Sebastian McKenzie
9847d226e1 add transform import - closes babel/babel-eslint#83 2015-05-04 03:54:58 +01:00
Sebastian McKenzie
3d48a16305 Merge pull request #1417 from loganfsmyth/fix-phantom-issue-1405
Explicitly sort instead of relying on key ordering.
2015-05-04 03:29:30 +01:00
Sebastian McKenzie
3d24cc9ae5 Merge pull request #1224 from jcoglan/fix-source-map-pathnames
Correct relative pathnames in source maps.
2015-05-04 00:03:27 +01:00
Sebastian McKenzie
5acc58dd68 5.2.7 2015-05-03 23:48:48 +01:00
Sebastian McKenzie
34f02f06a6 v5.2.7 2015-05-03 23:47:50 +01:00
Sebastian McKenzie
6d3fe5b85c add 5.2.7 changelog 2015-05-03 23:45:33 +01:00
Sebastian McKenzie
3878bd812c remove native super inheritance from classes - fixes #1424 2015-05-03 23:45:26 +01:00
Sebastian McKenzie
0717eaddce normalise Program replacement nodes 2015-05-03 23:35:39 +01:00
Sebastian McKenzie
102cbbe493 fix up crazy parse argument order 2015-05-03 23:31:37 +01:00
Sebastian McKenzie
d981b30194 clean up file transform pipeline 2015-05-03 23:26:37 +01:00
Sebastian McKenzie
0fc02f2cf0 add support for replacing nodes with expression source strings 2015-05-03 23:02:19 +01:00
Sebastian McKenzie
f24b5164d4 add extensions option to babel cli 2015-05-03 22:43:20 +01:00
Sebastian McKenzie
4be27ee72c update bin tests to reflect new helper format 2015-05-03 17:47:31 +01:00
Sebastian McKenzie
f0070e4828 ignore _generated FunctionDeclarations too in es6.spec.symbols transformer 2015-05-03 17:40:30 +01:00
Sebastian McKenzie
ce8beec22c update tests to reflect new helper format 2015-05-03 17:28:32 +01:00
Sebastian McKenzie
b30bdf2294 turn inserted helper declarations into function declarations if possible 2015-05-03 17:22:51 +01:00
Sebastian McKenzie
63b44a3e6e fix transformer and module formatter list in $ babel --help - fixes #1421 2015-05-02 23:16:37 +01:00
Logan Smyth
74aaf848ed Explicitly sort instead of relying on implementation-defined numeric key ordering - fixes #1405. 2015-05-01 20:00:22 -07:00
Sebastian McKenzie
95de5400e6 remove dead if statement explosion code - fixes #1413 2015-05-01 23:30:26 +01:00
Sebastian McKenzie
fe7079802b move deadCodeElimination transformer up - fixes #1409, fixes #1408 2015-05-01 23:24:16 +01:00
Sebastian McKenzie
61ddb14e25 Merge branch 'master' of github.com:babel/babel 2015-05-01 23:14:58 +01:00
Sebastian McKenzie
ca7a93cd64 move utility.deadCodeElimination transformer to minification 2015-05-01 23:13:48 +01:00
Sebastian McKenzie
90a1c81d30 split up es3.xLiterals transformers - fixes #1415 2015-05-01 23:13:30 +01:00
Sebastian McKenzie
5e9089d104 Merge pull request #1411 from hzoo/jshint-cleanup
remove old references to jshint
2015-05-01 22:45:15 +01:00
Henry Zhu
1a716943bc remove old references to jshint 2015-05-01 14:08:47 -04:00
Sebastian McKenzie
c28415c38a handle shorthand objects properly when renaming bindings, create new ones and refresh the stored binding identifier if necessary - fixes #1406 2015-05-01 15:23:46 +01:00
Sebastian McKenzie
e1491de6b8 5.2.6 2015-05-01 13:09:33 +01:00
Sebastian McKenzie
253ea8cd18 v5.2.6 2015-05-01 13:08:28 +01:00
Sebastian McKenzie
d37bad3149 add 5.2.6 changelog 2015-05-01 13:07:38 +01:00
Sebastian McKenzie
a2b912bc77 add BABEL mention to deprecation message 2015-05-01 13:07:31 +01:00
Sebastian McKenzie
f1bfbe44e2 expose Pipeline as TransformerPipeline 2015-05-01 13:00:34 +01:00
Sebastian McKenzie
dbdd07d0b8 fix addAliases call 2015-05-01 13:00:26 +01:00
Sebastian McKenzie
166909998e 5.2.5 2015-05-01 13:00:15 +01:00
Sebastian McKenzie
a8ec4c965c v5.2.5 2015-05-01 11:41:15 +01:00
Sebastian McKenzie
d2aff67c6c 5.2.4 2015-05-01 11:39:43 +01:00
Sebastian McKenzie
3353de225d fix parse API not adding all the correct pipeline transformers 2015-05-01 11:39:38 +01:00
Sebastian McKenzie
203ebeef20 v5.2.4 2015-05-01 11:29:06 +01:00
Sebastian McKenzie
032cf990c3 add 5.2.4 changelog 2015-05-01 11:28:24 +01:00
Sebastian McKenzie
16cdb43c67 expose transform pipeline and require node api inside of the browser one to avoid race conditions 2015-05-01 11:27:23 +01:00
Sebastian McKenzie
6f622033c5 5.2.3 2015-05-01 11:27:02 +01:00
Sebastian McKenzie
531d4f1937 v5.2.3 2015-05-01 09:42:23 +01:00
Sebastian McKenzie
f155bc249c fix Program global reference catching for real this time 2015-05-01 09:41:35 +01:00
Sebastian McKenzie
452d0ef30e fix Program global reference catching 2015-05-01 09:40:03 +01:00
Sebastian McKenzie
005754ba98 Revert "Revert "make dead code elimination smarter and eliminate non-referenced "pure" nodes""
This reverts commit c3c4cf17e3.
2015-05-01 09:39:33 +01:00
Sebastian McKenzie
c3c4cf17e3 Revert "make dead code elimination smarter and eliminate non-referenced "pure" nodes"
This reverts commit 4e87809ff9.
2015-05-01 09:39:07 +01:00
Sebastian McKenzie
0866e5a403 add 5.2.3 changelog 2015-05-01 09:36:48 +01:00
Sebastian McKenzie
15f5e658fc Merge branch 'master' of github.com:babel/babel 2015-05-01 09:32:28 +01:00
Sebastian McKenzie
574e6da132 add Statement and Declaration aliases to flow types - fixes #1401 2015-05-01 09:32:11 +01:00
Sebastian McKenzie
da6d27ed16 Merge pull request #1404 from timbur/master
hopefully fixes #1402
2015-05-01 09:31:46 +01:00
Sebastian McKenzie
4e87809ff9 make dead code elimination smarter and eliminate non-referenced "pure" nodes 2015-05-01 09:31:28 +01:00
Sebastian McKenzie
f4267aaab0 Merge pull request #1403 from wyand/master
fix spelling
2015-05-01 09:28:46 +01:00
Sebastian McKenzie
4f255d103a Merge pull request #1400 from monsanto/flow-object-commas
Support commas as object property separators in flow
2015-05-01 09:24:08 +01:00
Tim Burgess
502cc13aed hopefully fixes #1402 2015-05-01 04:05:22 -04:00
Dan Wyand
0a1154e6fd fix spelling 2015-05-01 01:01:10 -04:00
Christopher Monsanto
f5b3d72730 support commas as obj property separators in flow 2015-05-01 00:09:26 -04:00
Sebastian McKenzie
e9bcccffbd futz the bundler idea 2015-05-01 03:26:12 +01:00
Sebastian McKenzie
aaf4cbf06f start on babel module bundling and type inferrence 2015-05-01 02:59:59 +01:00
Sebastian McKenzie
5080534974 5.2.2 2015-05-01 00:44:48 +01:00
Sebastian McKenzie
02cb397873 v5.2.2 2015-05-01 00:43:39 +01:00
Sebastian McKenzie
d9169a87ad allow util.arrayify to take arbitrary types and coerce it into an array - #1398 2015-05-01 00:41:47 +01:00
Sebastian McKenzie
f3b6f2fc61 5.2.1 2015-05-01 00:41:24 +01:00
Sebastian McKenzie
04cc24ee82 v5.2.1 2015-05-01 00:30:42 +01:00
Sebastian McKenzie
f32079ef42 fix regression in node/register that caused node_modules to not be ignored - fixes #1398 2015-05-01 00:29:57 +01:00
Sebastian McKenzie
d1b69656ae update 5.2.0 changelog 2015-04-30 23:28:39 +01:00
Sebastian McKenzie
09453a490b 5.2.0 2015-04-30 23:27:37 +01:00
Sebastian McKenzie
e2e7627f0f v5.2.0 2015-04-30 23:15:06 +01:00
Sebastian McKenzie
4fe24a9a3b Merge pull request #1392 from jden/jden-patch-1
process glob matching in babel-cli (windows compat)
2015-04-30 23:10:24 +01:00
Sebastian McKenzie
d26e7ad577 fix no RHS in class properties causing undefined to be used instead of a noop - fixes #1396 2015-04-30 23:09:17 +01:00
Sebastian McKenzie
571cb4928f add register-without-polyfill option 2015-04-30 22:27:52 +01:00
Sebastian McKenzie
c12e8122f8 fix browser tests 2015-04-30 20:11:32 +01:00
Sebastian McKenzie
92e7a01d14 remove regenerator and test262 git submodule and tests - closes #1393 2015-04-30 20:03:34 +01:00
jden
b9ca9d42dc fix formatting per feedback from @sebmck
https://github.com/babel/babel/pull/1392#discussion-diff-29454022
2015-04-30 11:06:51 -07:00
jden
479c3e477a process glob matching in babel-cli (windows compat) 2015-04-30 10:57:48 -07:00
Sebastian McKenzie
2c3d3d8105 DRY up plugin manager position definition 2015-04-30 18:13:33 +01:00
Sebastian McKenzie
ea03f67505 use a strict regex when splitting string plugins - fixes #1361 2015-04-30 18:13:17 +01:00
Sebastian McKenzie
ee0c88a070 clean up plugin manager constructor and add some basic plugin manager tests 2015-04-30 18:06:15 +01:00
Sebastian McKenzie
98206df864 fix retainLines for comments and block statements - fixes #1388 2015-04-30 17:43:31 +01:00
Sebastian McKenzie
1066a42fb2 fix weird path context state by clearing the context before we visit it 2015-04-30 17:19:27 +01:00
Sebastian McKenzie
062175586c add parens around LHS object patterns 2015-04-30 17:18:36 +01:00
Sebastian McKenzie
0dc6b582a6 Merge pull request #1385 from monsanto/fix-var-checker
fix reference check for shorthand properties
2015-04-30 16:43:36 +01:00
Sebastian McKenzie
d8d70ba137 Merge pull request #1388 from amasad/master
Add failing test for printing block line comments with retainLines option
2015-04-30 16:42:55 +01:00
Sebastian McKenzie
f23c916520 make function name inferrence smarter - fixes #1367 2015-04-30 16:41:25 +01:00
Sebastian McKenzie
8ae4601177 rename insertOntoContainerStart to unshiftContainer 2015-04-30 14:33:54 +01:00
Sebastian McKenzie
9a466d3ef9 add optimisation.flow.forOf internal usage 2015-04-30 14:31:52 +01:00
Sebastian McKenzie
713845d14c add Terminatorless alias key for node expression wrappers that don't accept new lines 2015-04-30 13:56:42 +01:00
Sebastian McKenzie
471d60e5cd Merge branch 'master' of github.com:babel/babel 2015-04-30 13:53:58 +01:00
Sebastian McKenzie
43864e0686 Merge pull request #1390 from amasad/retainLines-return
Parenthesize statement argument when on a different line
2015-04-30 13:53:52 +01:00
Amjad Masad
4c2ae5dd19 Parenthesize statement argument when on a different line 2015-04-30 05:43:08 -07:00
Amjad Masad
a540cbe801 Failing test with return not on the same line as it's expression
Note that this is not a parenthesis issue but this was the easiest way
to reproduce it. I ran into it when testing generators with `retainLines`
and the generated `return` statement (replacing yeild) was printed on
the line preceding the expression being yielded.
2015-04-30 05:06:56 -07:00
Amjad Masad
34cc577fa2 Add failing test for printing block line comments with retainLines option 2015-04-30 04:37:45 -07:00
Sebastian McKenzie
c855b55133 add additional comment test to comment statement with retainlines option generation test 2015-04-29 23:58:36 +01:00
Sebastian McKenzie
16c86c25b7 properly catch up to comments position - fixes #1384 2015-04-29 23:57:43 +01:00
Sebastian McKenzie
4345f7945b Merge pull request #1377 from Mark-Simulacrum/issue-1376
Allow passing an array of globs to "only" option.
2015-04-29 23:39:17 +01:00
Christopher Monsanto
f44c93add2 fix reference check for shorthand properties 2015-04-29 17:56:36 -04:00
Sebastian McKenzie
09e45c51a4 Merge pull request #1384 from amasad/master
Add failing test for printing comments with retainLines option
2015-04-29 22:44:03 +01:00
Amjad Masad
1a42b72b15 Add failing test for printing comments with retainLines option 2015-04-29 14:40:23 -07:00
Sebastian McKenzie
d30415d74a update es6.spec.symbols instanceof test to reflect Function.prototype[@@hasInstance] being nonwritable #1364 2015-04-29 21:20:35 +01:00
Sebastian McKenzie
616ef8d840 make jscript transformer more trigger happy - #1382 2015-04-29 12:03:15 +01:00
Sebastian McKenzie
56437f94bc Merge pull request #1382 from kondi/jscript
add optional jscript transformer for basic IE8 compatibility (fixes #1369)
2015-04-29 11:59:32 +01:00
Pusztai Tibor
881fa6430b add optional jscript transformer for basic IE8 compatibility (fixes #1369) 2015-04-29 12:36:12 +02:00
Sebastian McKenzie
b7971690f3 add additional comments to path class, really need to go and fill in all the dummy jsdoc descriptions... 2015-04-29 01:19:56 +01:00
Sebastian McKenzie
c01d0abbd3 add insertOntoContainerStart and insertOntoContainerEnd methods 2015-04-29 01:13:35 +01:00
Sebastian McKenzie
7043119346 fix PluginManager 2015-04-29 01:13:23 +01:00
Mark-Simulacrum
b5325df57f Allow passing an array of globs to "only" option. 2015-04-28 17:59:20 -06:00
Sebastian McKenzie
0fc958e0fc remove useless force parameter in Buffer#_newline 2015-04-29 00:22:10 +01:00
Sebastian McKenzie
9cb16711dd abstract plugin initialisation to a plugin manager 2015-04-29 00:20:49 +01:00
Sebastian McKenzie
04766b13f5 add retainLines code generator option 2015-04-29 00:20:35 +01:00
Sebastian McKenzie
433d704739 add null check to interop-require-wildcard helper 2015-04-28 16:56:57 +01:00
Sebastian McKenzie
30204d2ee6 disable sudo travis config option, it breaks the build since it's using a cached node_modules which has old major versions of dependencies, ugh 2015-04-28 16:31:00 +01:00
Sebastian McKenzie
374b7cca2c update interop-require-wildcard helper 2015-04-28 15:58:37 +01:00
Sebastian McKenzie
152ae388f0 remove excessive newline 2015-04-28 15:32:16 +01:00
Sebastian McKenzie
04344026bb remove typeof object check for interop-require-wildcard helper 2015-04-28 15:32:09 +01:00
Sebastian McKenzie
cfffaf6cdb upgrade to babel 5 2015-04-28 14:55:28 +01:00
Sebastian McKenzie
2952d94e60 wrap instanceof to support @@hasInstance - fixes #1364 2015-04-28 14:27:30 +01:00
Sebastian McKenzie
0276c3ae81 visit decorators key for ClassProperty nodes 2015-04-28 00:05:10 +01:00
Sebastian McKenzie
c00f8dce3f add make build to makefile and elaborate on build steps in CONTRIBUTING - #1357. 2015-04-27 03:16:39 +01:00
Sebastian McKenzie
4e24ae39cf Merge branch 'master' of github.com:babel/babel 2015-04-27 03:06:23 +01:00
Sebastian McKenzie
12bd6494b7 use class ref instead of class name when adding class super native constructor call - fixes #1358 2015-04-27 03:06:13 +01:00
Sebastian McKenzie
e35c7550fe Merge pull request #1356 from monsanto/clean-build
remove lib/ before building
2015-04-27 02:32:53 +01:00
Christopher Monsanto
e7046abe72 remove lib/ before building 2015-04-26 21:12:50 -04:00
Sebastian McKenzie
affa7f0c6f Merge pull request #1352 from monsanto/descriptor-initalizer
call descriptor.initializer with `target` as `this`
2015-04-26 21:17:50 +01:00
Sebastian McKenzie
be650ffc61 call decorator initializers with the proper context - #1350 - thanks @monsanto 2015-04-26 21:17:15 +01:00
Sebastian McKenzie
3078d48178 don't rely on sequence expressions for <= 1 sequence expressions in blockScoping transformer 2015-04-26 21:15:30 +01:00
Sebastian McKenzie
0be93563dd fix spec.blockScopedFunctions shouldVisit method 2015-04-26 21:15:08 +01:00
Christopher Monsanto
3e55980145 call descriptor.initializer with target as this 2015-04-26 16:11:11 -04:00
Sebastian McKenzie
470ebf3a46 various random optimisations 2015-04-26 21:04:06 +01:00
Sebastian McKenzie
b695369126 add babel brand to code gen deopt message 2015-04-26 21:03:54 +01:00
Sebastian McKenzie
f4611469b4 remove declarations transformer and instead do it whenever we push a generated declaration, better for perf and removes shitty bugs - fixes #1268 2015-04-26 15:46:06 +01:00
Sebastian McKenzie
68bfafe745 add missing ast-types definitions 2015-04-26 05:26:29 +01:00
Sebastian McKenzie
f72782b71c remove transformer prepass and various other optimisations 2015-04-26 05:26:21 +01:00
Sebastian McKenzie
0f1f5e3565 implement path-specific transformer skipping via the starting prepass 2015-04-26 02:42:15 +01:00
Sebastian McKenzie
dfe126f3d4 verify traversal visitors 2015-04-25 22:49:54 +01:00
Sebastian McKenzie
4c9cb957a9 5.1.13 2015-04-25 22:46:01 +01:00
Sebastian McKenzie
8f997f8825 v5.1.13 2015-04-25 18:32:53 +01:00
Sebastian McKenzie
d789a6e7aa remove symbol check from defineProperty helper #1348 2015-04-25 18:31:29 +01:00
Sebastian McKenzie
4007148d9f 5.1.12 2015-04-25 18:23:16 +01:00
Sebastian McKenzie
998f1d544e v5.1.12 2015-04-25 18:21:37 +01:00
Sebastian McKenzie
deed48a3db fix decorator interop - fixes #1277 2015-04-25 18:18:30 +01:00
Sebastian McKenzie
00c0a958db fix runtime tests to reflect core-js 0.9.0 2015-04-25 18:08:00 +01:00
Sebastian McKenzie
1511dcbd73 resolveModuleSource on ExportAllDeclarations - fixes #1342 2015-04-25 17:47:44 +01:00
Sebastian McKenzie
12fef25803 update to core-js 0.9.0 - closes #1348 2015-04-25 17:40:59 +01:00
Sebastian McKenzie
fd30eb1839 Merge branch 'master' of github.com:babel/babel 2015-04-24 19:28:58 +01:00
Sebastian McKenzie
63344eb0a4 only skip traversal of immutable JSX elements in the optimisation.react.constantElements transformer when we've actually hoisted them - closes #1344 2015-04-24 19:28:51 +01:00
Sebastian McKenzie
6e4e11a365 fix JSX literal children not being output correctly 2015-04-24 19:28:17 +01:00
Sebastian McKenzie
e330efe058 Merge pull request #1343 from isojs/fix-ignore-only-windows
Fix ignore/only on Windows
2015-04-24 15:21:33 +01:00
Sebastian McKenzie
ce86eca8b0 Merge pull request #1335 from lukescott/fix-resolve-rc
Fix resolve rc loading options twice
2015-04-24 15:21:18 +01:00
Luke Scott
03dbaa3e0e fix resolve-rc loading options twice - fixes #1329 2015-04-24 07:13:26 -07:00
George Stagas
2bd35fac6e normalize filename slashes for shouldIgnore 2015-04-24 16:58:52 +03:00
Sebastian McKenzie
cdca4e50d9 Merge pull request #1333 from isojs/fix-rimraf-tmp
Fix test temporary dir cleanup
2015-04-24 11:31:09 +01:00
Sebastian McKenzie
bb041c1bd6 Merge pull request #1330 from joemcbride/master
Bump convert-source-map version.
2015-04-24 11:30:47 +01:00
Sebastian McKenzie
a36c1b4a92 rewrite this in shadowed functions inside native derived class constructors - fixes #1340 2015-04-24 11:20:29 +01:00
George Stagas
b760daca21 fix test tmp dir cleanup 2015-04-23 21:27:14 +03:00
Joe McBride
ff63d8f60c Bump convert-source-map version.
Relates to #1014
2015-04-23 09:29:19 -07:00
Sebastian McKenzie
74f04ed6a1 clean up interop require 2015-04-22 00:14:55 +01:00
Sebastian McKenzie
74d880bf18 Merge pull request #1317 from jeffmo/copy_static_props_on_foreign_export_objs
Copy statics from foreign exports objects when doing an ES6 import
2015-04-21 22:44:52 +01:00
jeffmo
5ce38cacaa Copy statics off of foreign exports objects when doing an ES6 import 2015-04-21 12:17:43 -04:00
Sebastian McKenzie
829f642ad8 fix spread properties in assignment position - fixes #1315 2015-04-21 16:24:34 +01:00
Sebastian McKenzie
80a4b95da4 fix incorrect externalHelpers option definition - fixes #1307 2015-04-21 16:16:07 +01:00
Sebastian McKenzie
dc2a20dbcd Merge branch 'master' of github.com:babel/babel 2015-04-21 16:14:49 +01:00
Sebastian McKenzie
f6278e43ce properly handle shorthand JSX attributes in optimisation.react.inlineElements transformer - fixes #1309 2015-04-21 16:14:36 +01:00
Sebastian McKenzie
30bc80000b Merge pull request #1311 from jquense/fix-plugin-position
Fixes bug where position was never set
2015-04-20 17:37:45 +01:00
jquense
ef56042c93 Fixes bug where position was never set
The mallet operator was compiling to `if (!position) position =
name.position`. Since position is set earlier the conditional was always
true and position was never updated from the plugin object.
2015-04-20 12:34:39 -04:00
Sebastian McKenzie
b6498103db 5.1.11 2015-04-20 06:26:23 +01:00
Sebastian McKenzie
7af4302d07 v5.1.11 2015-04-20 06:25:37 +01:00
Sebastian McKenzie
543770960c update 5.1.11 changelog 2015-04-20 06:24:30 +01:00
Sebastian McKenzie
a2975a72cc add 5.1.11 changelog 2015-04-20 06:23:53 +01:00
Sebastian McKenzie
beb3fd51d8 clean up CONTRIBUTING TOC 2015-04-20 06:16:33 +01:00
Sebastian McKenzie
9360860601 memoise and bind member expression decorators - fixes #1296 2015-04-20 06:16:20 +01:00
Sebastian McKenzie
7d4ecea8fb move react children coercion to opening element visitor - fixes #1276 2015-04-20 05:49:59 +01:00
Sebastian McKenzie
a44831b3fa Merge pull request #1285 from bucaran/contributing-doc-deps
Improve formatting and add rundown of deps with links
2015-04-20 00:24:30 +01:00
Sebastian McKenzie
8357f3900f Merge pull request #1282 from bcamper/vanilla-generator-runtime
Use vanilla regenerator when building runtime
2015-04-20 00:23:14 +01:00
Sebastian McKenzie
6b1c5bc358 remove interop require on bluebird - fixes #1289 2015-04-20 00:22:41 +01:00
Sebastian McKenzie
3564309a77 allow plugins to be specified as an object with transformer and position - fixes #1300 2015-04-20 00:05:06 +01:00
Sebastian McKenzie
c9518bb60d consider switches to be a valid scope - fixes #1297 2015-04-19 21:45:43 +01:00
Sebastian McKenzie
0f1215e33e add title to logging - fixes #1292 2015-04-19 16:06:58 +01:00
Sebastian McKenzie
d7b0b5bec0 add space to do-while code gen - fixes #1290 2015-04-17 17:35:36 -07:00
Jorge
3e5af404ab improve formatting and add rundown of deps with links 2015-04-17 15:15:03 +09:00
Sebastian McKenzie
1818094577 validate this before super on exit, not enter - fixes #1284 2015-04-16 22:04:18 -07:00
Brett Camper
6d712b3d14 use vanilla regenerator when building runtime
see #1015
2015-04-16 15:17:58 -04:00
Sebastian McKenzie
11389fe165 add 5.1.10 changelog 2015-04-15 16:12:56 -07:00
Sebastian McKenzie
0ee9531db3 5.1.10 2015-04-15 15:24:49 -07:00
Sebastian McKenzie
1622d2498d v5.1.10 2015-04-15 15:24:00 -07:00
Sebastian McKenzie
b76e6f8e5b disable ludicrous tests 2015-04-15 15:23:14 -07:00
Sebastian McKenzie
beac006832 remove regenerator from bootstrap 2015-04-15 15:22:09 -07:00
Sebastian McKenzie
20d7603c0b remove redundant replaceExpressionWithStatements for statement or block nodes - fixes #1265 2015-04-15 15:16:34 -07:00
Sebastian McKenzie
24b13c5e49 remove unnecessary csp makePredicate - fixes #1267 2015-04-15 15:13:12 -07:00
Sebastian McKenzie
9e21074e88 remove regenerator tests 2015-04-15 15:05:30 -07:00
Sebastian McKenzie
9a825bced7 remove runtime compatibility check - closes #1266 2015-04-15 15:03:45 -07:00
Sebastian McKenzie
fcb78436c6 move es6.proxies to ludicrous 2015-04-15 14:59:37 -07:00
Sebastian McKenzie
bb30a64f8d add extra transform option 2015-04-15 14:59:26 -07:00
Sebastian McKenzie
b483c16fe2 Merge branch 'proxies'
# Conflicts:
#	src/babel/transformation/file/index.js
2015-04-15 13:32:28 -07:00
Sebastian McKenzie
569f046045 5.1.9 2015-04-14 08:32:47 -07:00
Sebastian McKenzie
4e969d3d92 v5.1.9 2015-04-14 08:30:54 -07:00
Sebastian McKenzie
0bca1de285 add 5.1.9 changelog 2015-04-14 08:29:31 -07:00
Sebastian McKenzie
3a5bd06a7e fix proeprty method assignment wrapper generator template 2015-04-14 08:28:02 -07:00
Sebastian McKenzie
66a908aaa7 Mark function token as able to start an expression 2015-04-14 08:18:06 -07:00
Sebastian McKenzie
cd0ed08237 Revert "delegate to babel-cli/babel-core if it's available #1244"
This reverts commit dd84b554e6.
2015-04-14 08:02:02 -07:00
Sebastian McKenzie
dd84b554e6 delegate to babel-cli/babel-core if it's available #1244 2015-04-14 07:53:29 -07:00
Sebastian McKenzie
b51411f090 Merge branch 'master' of github.com:babel/babel 2015-04-14 07:39:52 -07:00
Sebastian McKenzie
4cc843ded3 set hoisted to true for react constant elements optimisation 2015-04-14 07:39:44 -07:00
Sebastian McKenzie
47d253c732 set passModuleArg when handling default export specifiers in amd module formatter - fixes #1260 2015-04-14 07:39:34 -07:00
Sebastian McKenzie
09901274ab Merge pull request #1257 from zloirock/master
Update NATIVE_TYPE_NAMES
2015-04-14 07:28:00 -07:00
rock
35196e20c7 Update NATIVE_TYPE_NAMES 2015-04-14 18:24:13 +06:00
Sebastian McKenzie
35af771a29 Merge branch 'master' of github.com:babel/babel 2015-04-13 21:57:04 -07:00
Sebastian McKenzie
dee80caa09 move export reassignment to exit handler - fixes #1255 2015-04-13 21:56:55 -07:00
Sebastian McKenzie
46b7cc0a72 assorted minor cleanup of variables 2015-04-13 21:56:37 -07:00
Sebastian McKenzie
3b189e22b7 Merge pull request #1256 from jayphelps/fix-writable
class properties with an undefined value are now correctly writable
2015-04-13 21:52:46 -07:00
Jay Phelps
6ca565d7fb class properties with an undefined value are now correctly writable 2015-04-13 20:53:05 -07:00
Sebastian McKenzie
64f5480f96 fix pattern LHS error messages 2015-04-13 16:45:30 -07:00
Sebastian McKenzie
828fdc8769 make illegal LHS pattern error messages more user friendly 2015-04-13 16:40:13 -07:00
Sebastian McKenzie
6763c4415e make parenthesized array patterns illegal - cc @michaelficarra 2015-04-13 16:16:57 -07:00
Sebastian McKenzie
fb30e79e03 5.1.8 2015-04-13 15:46:45 -07:00
Sebastian McKenzie
85fb4304b0 v5.1.8 2015-04-13 15:45:46 -07:00
Sebastian McKenzie
c2da77d7ec only make parenthesized object patterns illegal - fixes #1254, ref jshint/jshint#2269 2015-04-13 15:44:54 -07:00
Sebastian McKenzie
c54c3d3c15 5.1.7 2015-04-13 15:44:02 -07:00
Sebastian McKenzie
2a7c954155 v5.1.7 2015-04-13 14:59:56 -07:00
Sebastian McKenzie
3fb7f7c7cc add 5.1.6-5.1.7 changelog 2015-04-13 14:56:33 -07:00
Sebastian McKenzie
c4b2818336 remove useless kind on import declarations 2015-04-13 14:55:46 -07:00
Sebastian McKenzie
061561bfd8 add proper ecmaVersion and sourceType to parse api 2015-04-13 14:55:37 -07:00
Sebastian McKenzie
d4944d606b 5.1.6 2015-04-13 14:29:21 -07:00
Sebastian McKenzie
736b689c3b v5.1.6 2015-04-13 14:27:09 -07:00
Sebastian McKenzie
e12b377014 don't fall back to runtime catch all on locally declared variables 2015-04-13 14:26:06 -07:00
Sebastian McKenzie
5fd5b815ab fix whitespace in resolveRc 2015-04-13 14:25:47 -07:00
Sebastian McKenzie
92db8312f6 add parse api 2015-04-13 14:25:37 -07:00
James Coglan
1f2f4ce4f3 Correct relative pathnames in source maps.
Say you have a file called `src/thing.js` and you run

    $ babel src/thing.js --out-file lib/thing.js --source-maps true

This generates a source map at `lib/thing.js.map` that contains
"src/thing.js" in its `sources` array. This is incorrect; since browsers
resolve all relative URLs relative to the directory containing the file
that refers to the URL, this resolves to `lib/src/thing.js`.

To make the source map refer to the source files correctly, the
`sources` array should contain "../src/thing.js".
2015-04-13 21:17:11 +01:00
Sebastian McKenzie
e080fe547d 5.1.5 2015-04-13 11:59:47 -07:00
Sebastian McKenzie
b967ecf063 v5.1.5 2015-04-13 11:58:58 -07:00
Sebastian McKenzie
365b7285d2 bump core-js version 2015-04-13 11:58:09 -07:00
Sebastian McKenzie
a40d532b0e 5.1.4 2015-04-13 09:38:21 -07:00
Sebastian McKenzie
0487bf911d v5.1.4 2015-04-13 09:36:21 -07:00
Sebastian McKenzie
57c72d1cd0 fix syntax error in runtime definitions 2015-04-13 09:35:35 -07:00
Sebastian McKenzie
335bdffec2 add missing Reflect methods to runtime transformer #1248 2015-04-13 09:34:45 -07:00
Sebastian McKenzie
e1d76a1dfe 5.1.3 2015-04-13 09:25:37 -07:00
Sebastian McKenzie
a4845323a2 v5.1.3 2015-04-13 09:24:00 -07:00
Sebastian McKenzie
792951b489 add 5.1.3 changelog 2015-04-13 09:23:12 -07:00
Sebastian McKenzie
5adda836af don't do TCO on generators and async functions - fixes #1251 2015-04-13 09:21:59 -07:00
Sebastian McKenzie
4c2c3098c3 Merge branch 'master' of github.com:babel/babel 2015-04-13 09:20:36 -07:00
Sebastian McKenzie
087c714098 simplify runtime transformer traversal and add a catch-all - fixes #1248 2015-04-13 09:20:28 -07:00
Sebastian McKenzie
5a33e4fe05 Merge pull request #1245 from deepsweet/travis-cache
let Travis cache node_modules
2015-04-13 08:29:59 -07:00
Sebastian McKenzie
5f8667eaa7 make parsing of decorators stateless - fixes shuhei/babel-angular2-app#4 2015-04-13 08:26:51 -07:00
Sebastian McKenzie
31b4468514 switch to vanilla regenerator - closes #1247, closes #1123 2015-04-13 08:08:00 -07:00
Kir Belevich
2be9678bbe let Travis cache node_modules 2015-04-13 17:54:50 +07:00
Sebastian McKenzie
b5210877cf 5.1.2 2015-04-13 00:54:00 -07:00
Sebastian McKenzie
658dde768e v5.1.2 2015-04-13 00:52:43 -07:00
Sebastian McKenzie
8df1d81ca4 fix iterable runtime name 2015-04-13 00:51:50 -07:00
Sebastian McKenzie
a505e4a121 aAdd getIterator and isIterable to babel-runtime build script - fixes #1243 2015-04-13 00:48:19 -07:00
Sebastian McKenzie
71eafdcac7 5.1.1 2015-04-13 00:14:47 -07:00
Sebastian McKenzie
65060b0c97 v5.1.1 2015-04-13 00:13:52 -07:00
Sebastian McKenzie
09883962f1 add item to 5.1.0 changelog 2015-04-13 00:13:05 -07:00
Sebastian McKenzie
1583262807 add missing runtime symbol definitions - fixes #1242 2015-04-13 00:12:59 -07:00
Sebastian McKenzie
04c7cd5c0c add note to 5.1.0 changelog 2015-04-12 21:29:29 -07:00
Sebastian McKenzie
3f6969f4f8 5.1.0 2015-04-12 21:23:21 -07:00
Sebastian McKenzie
23db842cb8 v5.1.0 2015-04-12 21:22:25 -07:00
Sebastian McKenzie
41c82e00f9 add 5.1.0 changelog 2015-04-12 21:21:35 -07:00
Sebastian McKenzie
766099e783 5.0.13 2015-04-12 21:21:31 -07:00
Sebastian McKenzie
53bc54b3b2 v5.0.13 2015-04-12 21:14:12 -07:00
Sebastian McKenzie
bb70f37123 Merge branch 'master' of github.com:babel/babel 2015-04-12 20:59:26 -07:00
Sebastian McKenzie
8a0317132e deopt array unpack optimisation on member expressions - fixes #1241 2015-04-12 20:59:17 -07:00
Sebastian McKenzie
f598c70841 Merge pull request #1215 from AluisioASG/es7-trailing-function-commas
ES7 trailing function commas
2015-04-12 19:17:02 -07:00
Sebastian McKenzie
61b57ea055 rejigger decorator alias 2015-04-12 19:10:22 -07:00
Sebastian McKenzie
a971ad7fd2 Merge branch 'master' of github.com:babel/babel 2015-04-12 19:07:19 -07:00
Sebastian McKenzie
27b6f804ce clean up class decorators #1185 2015-04-12 19:06:59 -07:00
Sebastian McKenzie
8ab79f3a72 Merge pull request #1240 from JaRail/master
Fix broken dead-code-removal case.
2015-04-12 18:58:45 -07:00
James Railton
0c2bf2f5a2 Fix broken dead-code-removal case.
The "test" local variable was removed with path work. The last dead-code-removal check used this var. By reintroducing the local var, the unknown variable reference is fixed.
2015-04-12 18:52:37 -07:00
Sebastian McKenzie
7e1a4be085 add use strict header to decorators test 2015-04-12 09:09:26 -07:00
Sebastian McKenzie
bbc951dfe1 fix decorators order - thanks to some random japanese tweet i translated... 2015-04-12 09:05:46 -07:00
Sebastian McKenzie
b3e4aefe12 update runtime transformer to not use $for module - cc @zloirock 2015-04-12 09:00:32 -07:00
Sebastian McKenzie
26b5174dfa add descriptor for all class properties - fixes #1235 2015-04-12 08:53:01 -07:00
Sebastian McKenzie
652d3c7320 move eval and arguments identifier handling to nameMethod helper 2015-04-11 20:51:01 -07:00
Sebastian McKenzie
edc2cd320c don't consider eval and arguments valid identifiers - fixes #1232 2015-04-11 20:45:44 -07:00
Sebastian McKenzie
274a6e01dc add support for inheriting from statically inlined native constructors - closes #1172 2015-04-11 19:47:11 -07:00
Sebastian McKenzie
3561efdb86 update runtime transformer to modular core-js - fixes #1206 2015-04-11 19:07:39 -07:00
Sebastian McKenzie
1a30f1aafc fix regression with completion records for assignment expressions - fixes #1204 2015-04-11 18:13:47 -07:00
Sebastian McKenzie
e362512af3 switch to my branch of regenerator - #1123, fixes #1015 2015-04-11 17:59:14 -07:00
Sebastian McKenzie
cf5d2429b4 add support for replacement of for inits with statements - fixes #1217 2015-04-11 17:40:12 -07:00
Sebastian McKenzie
72098036b2 remove useless this from lodash map 2015-04-11 17:39:50 -07:00
Sebastian McKenzie
7905f48280 clean up dynamic imports, disable hoisting in system module formatter when **any** dynamic imports are included - fixes #1219 2015-04-11 17:22:48 -07:00
Sebastian McKenzie
aba2d1c23c fix loop constants test error message 2015-04-11 16:50:08 -07:00
Sebastian McKenzie
5326e0543d fix scope tracking for constants in loop heads - fixes #1229 2015-04-11 16:39:18 -07:00
Sebastian McKenzie
1360c93e4b fix enumerable property position in test 2015-04-11 16:35:19 -07:00
Sebastian McKenzie
235cbc18cf Merge branch 'master' of github.com:babel/babel 2015-04-11 16:31:11 -07:00
Sebastian McKenzie
98c5255b91 add support for object literal decorators - fixes #1154 2015-04-11 16:30:55 -07:00
Sebastian McKenzie
2a9777cc20 add solo helpers
# Conflicts:
#	src/babel/transformation/file/index.js
2015-04-11 14:33:56 -07:00
Sebastian McKenzie
a8702be756 add solo helpers 2015-04-11 14:33:04 -07:00
Sebastian McKenzie
0995cc3f4e add proxies 2015-04-11 14:32:52 -07:00
Sebastian McKenzie
1cfca745a4 Merge pull request #1228 from Hermanya/patch-1
Update README.md
2015-04-11 08:52:30 -07:00
Herman Starikov
a3459deecf Update README.md 2015-04-11 11:52:01 -04:00
Sebastian McKenzie
070152f6c1 parse await expression as a unary instead of an assignment - fixes #1225 2015-04-10 15:23:11 -07:00
Sebastian McKenzie
719fdf5ca1 set canBeArrow to true when parsing async functions 2015-04-10 13:51:30 -07:00
Sebastian McKenzie
f2460c6173 update to latest acorn 2015-04-10 13:44:50 -07:00
Sebastian McKenzie
155c640409 remove null regex check - fixes #1222 2015-04-10 13:44:41 -07:00
Sebastian McKenzie
7de4718b27 Merge branch 'master' of github.com:babel/babel 2015-04-09 14:58:41 -07:00
Sebastian McKenzie
4e6aed0408 don't shadow default parameter scope iife and instead just apply the this and arguments - fixes #1128 2015-04-09 14:58:33 -07:00
Brian Donovan
3be8ccf68d Prevent this command from failing during CI. 2015-04-09 14:49:45 -07:00
Sebastian McKenzie
704b31f44f use path basename as non-default import fallback - fixes #1207 2015-04-09 14:36:00 -07:00
Sebastian McKenzie
1a9f193841 Merge pull request #1216 from leebyron/update-deps
Update package dependencies
2015-04-09 13:50:23 -07:00
Lee Byron
7ff67589a7 Update package dependencies
Babel currently relies on some older versions of some dependencies. When using babel alongside other projects which use similar dependencies, this can cause npm to install multiple versions of these or to result in Babel loading a version of a dependency it doesn't claim to support.

This was mostly clean, though esutils did have a minor API change.
2015-04-09 13:38:20 -07:00
Brian Donovan
80f109efeb Ensure arrow function bodies are wrapped in parens if needed.
Closes #1214.
2015-04-09 11:50:52 -07:00
Brian Donovan
77c72bb5a6 Unlink global babel before bootstrapping to make it idempotent. 2015-04-09 09:55:48 -07:00
Aluísio Augusto Silva Gonçalves
6c5e0e6590 Add Acorn tests for trailing function commas 2015-04-09 13:35:48 -03:00
Sebastian McKenzie
83324b977d Merge branch 'master' of github.com:babel/babel
# Conflicts:
#	packages/babel-cli/package.json
2015-04-09 06:46:26 -07:00
Sebastian McKenzie
5feab11d3f Merge pull request #1212 from paulmillr/patch-2
Update to stable chokidar.
2015-04-09 06:45:58 -07:00
Sebastian McKenzie
7b4172ce7b remove chokidar from root package.json 2015-04-09 06:45:48 -07:00
Paul Miller
84439384c0 Update to stable chokidar. 2015-04-09 16:45:30 +03:00
Sebastian McKenzie
c9e7c306cc don't emit tokens when doing a lookahead 2015-04-09 06:44:16 -07:00
Sebastian McKenzie
1e398e45ff 5.0.12 2015-04-09 06:44:06 -07:00
Sebastian McKenzie
475324c4b5 Update to stable chokidar. 2015-04-09 06:43:58 -07:00
Sebastian McKenzie
407daf4bac Merge pull request #1205 from suryagaddipati/patch-1
Fix typo
2015-04-08 16:00:32 -07:00
Surya Gaddipati
4155590cd8 Fix typo 2015-04-08 18:00:03 -05:00
Sebastian McKenzie
0be6fd7abe Merge pull request #1203 from sindresorhus/modularize-userhome
modularize `user-home`
2015-04-08 09:49:03 -07:00
Sindre Sorhus
cf51bf1395 modularize user-home
No reason Babel should have to care about the intricacies of this.

This module is already used by `bower`, `eslint`, `yo`, etc.
2015-04-08 22:59:16 +07:00
Sebastian McKenzie
06a31c419a v5.0.12 2015-04-08 08:55:02 -07:00
Sebastian McKenzie
da566110c0 add 5.0.12 changelog 2015-04-08 08:53:40 -07:00
Sebastian McKenzie
c12c4a5c39 don't touch function name containers when remapping modules - fixes #1160 2015-04-08 08:52:53 -07:00
Sebastian McKenzie
d114349890 5.0.11 2015-04-08 08:15:15 -07:00
Sebastian McKenzie
8d6ae0e1eb v5.0.11 2015-04-08 08:14:28 -07:00
Sebastian McKenzie
cb8b47ee2f add missing curly brace to regression test 2015-04-08 08:13:33 -07:00
Sebastian McKenzie
daf24c5c59 add 5.0.10 changelog 2015-04-08 08:12:33 -07:00
Sebastian McKenzie
cdb2784e75 add #1199 regression test 2015-04-08 08:11:01 -07:00
Sebastian McKenzie
93feabb82e fix forOf loop inheritance - fixes #1169 2015-04-08 08:10:53 -07:00
Sebastian McKenzie
982c142bf6 Merge branch 'master' of github.com:babel/babel 2015-04-08 07:47:52 -07:00
Sebastian McKenzie
de5520a94f disable scope caching 2015-04-08 07:42:04 -07:00
Sebastian McKenzie
c239d06f10 fix MetaProperty generation 2015-04-08 07:41:56 -07:00
Sebastian McKenzie
a5fed376d8 Merge pull request #1191 from zertosh/babelrc-comments
Strip out comments before parsing babelrc
2015-04-07 18:09:07 -07:00
Sebastian McKenzie
e99fd77d89 downgrade and fix mocha version - fixes #1196 2015-04-07 18:07:23 -07:00
Sebastian McKenzie
1374863b9c 5.0.10 2015-04-07 18:06:52 -07:00
Andres Suarez
e88c28f88b Strip out comments before parsing babelrc 2015-04-07 18:50:01 -04:00
Sebastian McKenzie
7a0fd26f56 v5.0.10 2015-04-07 13:04:25 -07:00
Sebastian McKenzie
17583e4807 fix decrators modules test 2015-04-07 13:03:41 -07:00
Sebastian McKenzie
37dd5137ff don't modules reassign _ignoreModulesRemap assignments 2015-04-07 13:02:28 -07:00
Sebastian McKenzie
24fced406e Merge branch 'master' of github.com:babel/babel 2015-04-07 09:55:11 -07:00
Sebastian McKenzie
0ab1362893 don't reassign decorated classes - fixes #1167 2015-04-07 09:54:14 -07:00
Sebastian McKenzie
96506f4249 5.0.9 2015-04-07 09:20:40 -07:00
Sebastian McKenzie
ed747f88bd Merge pull request #1185 from Dignifiedquire/class-decorators-scope
Take 2: Fix class decorator scoping.
2015-04-07 08:49:56 -07:00
dignifiedquire
3987545b4f Ensure correct scope for decorated classes. 2015-04-07 14:57:15 +02:00
dignifiedquire
148aa3f96d Use a functionExpression with class decorators. Fixes #1161. 2015-04-07 14:16:48 +02:00
Sebastian McKenzie
0cb5a7c91e Revert "Use a functionExpression with class decorators. Fixes #1161."
This reverts commit f8d56d9612.
2015-04-07 04:40:39 -07:00
Sebastian McKenzie
fc34d5a9b0 Merge pull request #1184 from Dignifiedquire/class-decorators
Use a functionExpression with class decorators. Fixes #1161.
2015-04-07 03:39:59 -07:00
dignifiedquire
f8d56d9612 Use a functionExpression with class decorators. Fixes #1161. 2015-04-07 12:11:49 +02:00
Brian Donovan
737be0e95e Merge pull request #1173 from alawatthe/patch-1
Fixed path for mocha tests in CONTRIBUTING.md
2015-04-06 09:56:31 -07:00
Alexander Zeilmann
26e2b392e8 Fixed path for mocha tests 2015-04-06 18:38:33 +02:00
Sebastian McKenzie
708cdfb993 v5.0.9 2015-04-06 06:28:58 -07:00
Sebastian McKenzie
8cb3aabefa add 5.0.9 changelog 2015-04-06 06:26:11 -07:00
Sebastian McKenzie
4a87b35d20 fix function name self referencing test 2015-04-06 06:23:46 -07:00
Sebastian McKenzie
543554b258 flow tests style nit 2015-04-06 06:20:09 -07:00
Sebastian McKenzie
afd95cf663 add #1168 regression test 2015-04-06 06:20:05 -07:00
Sebastian McKenzie
87ce4b9cd8 fix order of parameter type annotation parsing - fixes #1168 2015-04-06 06:19:13 -07:00
Sebastian McKenzie
6b76f26ed8 use module id if available for umd global name - fixes #1166 2015-04-06 06:14:09 -07:00
Sebastian McKenzie
c2776e63ae rename umd module variable name - fixes #1166 2015-04-06 06:13:43 -07:00
Sebastian McKenzie
3f2fe363d1 Merge pull request #1163 from chocolateboy/babel_node_print_fix
babel-node --print: don't mangle percent characters (%)
2015-04-06 06:06:21 -07:00
Sebastian McKenzie
8de28098f4 Merge pull request #1170 from alawatthe/master
Replaced FUNCTION_ID by FUNCTION_KEY - fixes #1164
2015-04-06 06:02:49 -07:00
Aluísio Augusto Silva Gonçalves
584532cc2c [ES7] Trailing comma in function parameter list
Currenly a stage 1 proposal.
See https://github.com/jeffmo/es-trailing-function-commas.
2015-04-06 09:10:44 -03:00
alawatthe
9a28f3fdb1 Replaced FUNCTION_ID by FUNCTION_KEY - fixes #1164 2015-04-06 10:53:41 +02:00
chocolateboy
88941b3270 babel-node --print: don't mangle percent characters (%)
This applies the babel fix in #528 to babel-node.

before:

    $ babel-node --print --eval '"%%"'
    '%'

after:

    $ babel-node --print --eval '"%%"'
    '%%'
2015-04-05 06:26:29 +01:00
Sebastian McKenzie
3a768db2bf fix missing this in acorn parseExprAtom 2015-04-05 03:26:41 +10:00
Sebastian McKenzie
320a39f4c4 fix computed properties in es7 object rest/spread - thanks @AluisioASG! 2015-04-05 02:52:14 +10:00
Sebastian McKenzie
dc98ac7c93 5.0.8 2015-04-04 17:09:35 +11:00
Sebastian McKenzie
6e456f0ec1 v5.0.8 2015-04-04 17:05:47 +11:00
Sebastian McKenzie
793090628d fix #1157 regression test 2015-04-04 17:03:54 +11:00
Sebastian McKenzie
9ed251cb08 add 5.0.8 changelog 2015-04-04 17:02:50 +11:00
Sebastian McKenzie
480fa7f4e0 add regression test for #1157 2015-04-04 16:59:29 +11:00
Sebastian McKenzie
3e642dfa1b Merge pull request #1157 from jayphelps/patch-1
[BUGFIX] Check whether `value` key is in descriptor instead of checking truthy value
2015-04-04 16:57:57 +11:00
Jay Phelps
d9cbce1862 [BUGFIX] checking whether value key is in descriptor instead of checking if value is truthy since !!0 === false
class Foo {
  static bar = 0;
}

Foo.bar++;
// Cannot assign to read only property 'bar' of function
2015-04-03 22:49:34 -07:00
Sebastian McKenzie
4bd19da3c2 fix tests, better block scoped collisions 2015-04-04 14:17:26 +11:00
Sebastian McKenzie
7c710a0378 move var scope collector to before block - fixes #1153 2015-04-04 14:09:34 +11:00
Sebastian McKenzie
56335409d3 stop constructor verification traversal on FunctionDeclaration/FunctionExpression - fixes #1155 2015-04-04 14:01:26 +11:00
Sebastian McKenzie
91d78afc67 update 5.0.7 changelog 2015-04-04 05:32:32 +11:00
Sebastian McKenzie
54c6339f20 5.0.7 2015-04-04 04:51:24 +11:00
Sebastian McKenzie
fdcf64265e v5.0.7 2015-04-04 04:49:31 +11:00
Sebastian McKenzie
ffdfb491eb disable identifier resolution - fixes #1149 2015-04-04 04:46:49 +11:00
Sebastian McKenzie
eedd431f2b remove HOMEPATH from register cache home resolution 2015-04-04 04:40:10 +11:00
Sebastian McKenzie
db9ed0235f finally fix cli tests 2015-04-04 04:39:28 +11:00
Sebastian McKenzie
6c98d39937 grr, debugging travis builds is hard 2015-04-04 04:01:35 +11:00
Sebastian McKenzie
20651df3ce try and fix babel cli bootstrap 2015-04-04 03:47:47 +11:00
Sebastian McKenzie
f3155919fe shift USERPROFILE over in home resolution in babel/register - fixes #1148 2015-04-04 03:46:07 +11:00
Sebastian McKenzie
0ac8330899 remove bable-core in babel-cli bootstrap 2015-04-04 03:40:01 +11:00
Sebastian McKenzie
67201e9698 add ignore/only option to cli 2015-04-04 03:31:19 +11:00
Sebastian McKenzie
c715d96e46 wrap non-arrays/strings/falsys in an array in util.list - fixes babel/babelify#69 2015-04-04 02:40:09 +11:00
Sebastian McKenzie
b7a08100a6 add default live bindings to common module formatter 2015-04-04 01:56:58 +11:00
Sebastian McKenzie
5f91ee8a1a 5.0.6 2015-04-03 23:15:34 +11:00
Sebastian McKenzie
bc1abb5103 v5.0.6 2015-04-03 23:13:43 +11:00
Sebastian McKenzie
4b9207e5df add 5.0.6 changelog 2015-04-03 23:12:10 +11:00
Sebastian McKenzie
e847f3685f should only throw an error for colliding param bindings for let and const 2015-04-03 23:11:04 +11:00
Sebastian McKenzie
d64c2c0c45 turn internalRemap into a null inherited object, fixes a nasty bug where module import live bindings would return a function if they referenced a method on Object.prototype (eg. toString) 2015-04-03 23:10:09 +11:00
Sebastian McKenzie
76d0fb4ba6 5.0.5 2015-04-03 22:44:16 +11:00
Sebastian McKenzie
0f33b7bfbc v5.0.5 2015-04-03 22:42:50 +11:00
Sebastian McKenzie
630224e504 add 5.0.5 changelog 2015-04-03 22:41:06 +11:00
Sebastian McKenzie
62980ab6b4 Merge branch 'master' of github.com:babel/babel
t push
2015-04-03 22:38:28 +11:00
Sebastian McKenzie
d34480b42b add support for arrays to util.list - fixes #["foo", "bar"] 2015-04-03 22:38:08 +11:00
Sebastian McKenzie
306de2edbf Merge pull request #1144 from tricknotes/fix-for-browserify
Update core-js to ^0.8.1
2015-04-03 22:23:48 +11:00
Ryunosuke SATO
c33e84730d Update core-js to ^0.8.1
This version fixes the error for some environments that
has no `setTimeout`/`setInterval`.
2015-04-03 18:38:33 +09:00
Sebastian McKenzie
20f28aba64 5.0.4 2015-04-03 15:34:20 +11:00
Sebastian McKenzie
9c312607d1 Merge branch 'master' of github.com:babel/babel 2015-04-03 15:33:27 +11:00
Sebastian McKenzie
33659711c3 Merge pull request #1142 from cesarandreu/add-babel-readme
Add README.md to babel-cli
2015-04-03 15:33:00 +11:00
Sebastian McKenzie
b154af48a7 Merge branch 'master' of github.com:babel/babel 2015-04-03 15:32:52 +11:00
Cesar Andreu
bad877946f Add README.md to babel-cli 2015-04-02 21:31:47 -07:00
Sebastian McKenzie
23038dcfff Merge pull request #1141 from fkling/patch-1
Update SO link in README.md
2015-04-03 15:30:47 +11:00
Felix Kling
7c7a7ee17f Update README.md
The SO link currently points to https://github.com/babel/babel/blob/master/stackoverflow.com, which is incorrect. After this change it points to the list of babeljs questions.
2015-04-02 21:29:56 -07:00
435 changed files with 5520 additions and 2649 deletions

View File

@@ -1,6 +1,6 @@
{
"experimental": true,
"playground": true,
"loose": true,
"blacklist": ["es6.tailCall"]
"stage": 0,
"loose": ["all"],
"blacklist": ["es6.tailCall"],
"optional": ["optimisation.flow.forOf"]
}

1
.gitignore vendored
View File

@@ -11,6 +11,7 @@ test/core/tmp
coverage
dist
.package.json
packages/babel-runtime/core-js
packages/babel-runtime/helpers/*.js
packages/babel-runtime/regenerator/*.js
lib

6
.gitmodules vendored
View File

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

View File

@@ -1,5 +1,8 @@
sudo: false
#sudo: false
language: node_js
cache:
directories:
- node_modules
node_js:
- "0.12"
- "iojs"

View File

@@ -13,6 +13,306 @@ _Note: Gaps between patch versions are faulty/broken releases._
See [CHANGELOG - 6to5](CHANGELOG-6to5.md) for the pre-4.0.0 version changelog.
## 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**
* Rename `getModuleName` option to `getModuleId`, doh.
## 5.2.10
* **Bug Fix**
* Fix numerous issues in `replaceWithSourceString`. Thanks [@pangratz](https://github.com/pangratz)!
* **New Feature**
* Add `getModuleName` option. Thanks [@jayphelps](https://github.com/jayphelps)!
## 5.2.9
* **Bug Fix**
* Fix `_blockHoist` transformer incorrectly sorting nodes on shitty environments that aren't spec compliant in their key order.
* Fix broken `parse` API method reference to an undeclared import.
## 5.2.7
* **Bug Fix**
* Move `utility.deadCodeElimination` transformer up to avoid race conditions.
* Fix shorthand property scope binding renaming.
* **Polish**
* Turn helper variable declarations into function declarations if possible.
* **Internal**
* Removed native inheritance support from classes.
* Added `replaceWithSourceString` path API.
* Split up `es3.propertyLiterals` and `es3.memberExpressionLiterals` transformers to `minfication.propertyLiterals` and `es3.memberExpressionLiterals`.
## 5.2.6
* **Internal**
* Fix transformer aliases being accidently set as deprecated ones.
* Expose `Pipeline` as `TransformerPipeline` instead.
## 5.2.5
* **Bug Fix**
* Fix `parse` API not adding all the correct pipeline transformers.
## 5.2.4
* **Bug Fix**
* Fix race condition with the Node API being loaded awkwardly and not being able to initialise itself when used in the browser.
* **Internal**
* Expose `transform.pipeline`.
## 5.2.3
* **Bug Fix**
* Fix plugin containers being called with an undefined import. Thanks [@timbur](https://github.com/timbur)!
* Allow Flow object separators to be commas. Thanks [@monsanto](https://github.com/monsanto)!
* Add missing `Statement` and `Declaration` node aliases to flow types.
## 5.2.2
* **Internal**
* Allow `util.arrayify` to take arbitrary types and coerce it into an array.
## 5.2.1
* **Bug Fix**
* Fix regression in `node/register` that caused `node_modules` to not be ignored.
## 5.2.0
* **Bug Fix**
* Fix plugin strings splitting arbitrarily on `:` which caused full paths on Windows to fail as they include `:` after the drive letter.
* Call class property `initializer`s with their target instead of their descriptor.
* Fix `ignore` and `only` not properly working on Windows path separators. Thanks [@stagas](https://github.com/stagas)!
* Fix `resolveRc` running on files twice causing issues. Thanks [@lukescott](https://github.com/lukescott)!
* Fix shorthand properties not correctly being target for `isReferenced` checks. Thanks [@monsanto](https://github.com/monsanto)!
* **Polish**
* Allow passing an array of globs to `babel/register` `only` and `ignore` options. Thanks [@Mark-Simulacrum](https://github.com/Mark-Simulacrum)!
* When inferring function names that collide with upper bindings, instead of doing the wrapper, instead rename them.
* Consider constant-like variable declaration functions to always refer to themselves so TOC can be performed.
* Process globs manually when using `$ babel` as some shells such as Windows don't explode them. Thanks [@jden](https://github.com/jden)!
* Add alternative way to execute plugins via a closure that's called with the current Babel instance.
* **Internal**
* Remove multiple internal transformers in favor of directly doing things when we need to. Previously, declarations such as `_ref` that we needed to create in specific scopes were done at the very end via the `_declarations` transformer. Now, they're done and added to the scope **right** when they're needed. This gets rid of the crappy `_declarations` property on scope nodes and fixes the crappy regenerator bug where it was creating a new `BlockStatement` so the declarations were being lost.
* Rework transformer traversal optimisation. Turns out that calling a `check` function for **every single node** in the AST is ridiculously expensive. 300,000 nodes timesed by ~30 transformers meant that it took tens of seconds to perform while it's quicker to just do the unnecessary traversal. Seems obvious in hindsight.
* **New Feature**
* Add `jscript` transformer that turns named function expressions into function declarations to get around [JScript's horribly broken function expression semantics](https://kangax.github.io/nfe/#jscript-bugs). Thanks [@kondi](https://github.com/kondi)!
* Add `@@hasInstance` support to objects when using the `es6.spec.symbols` transformer.
* Add `retainLines` option that retains the line (but not the columns!) of the input code.
## 5.1.13
* **Polish**
* Remove symbol check from `defineProperty` helper.
## 5.1.12
* **Bug Fix**
* Fix `resolveModuleSource` not being ran on `ExportAllDeclaration`s.
* Fix `.babelrc` being resolved multiple times when using the require hook.
* Fix parse error on spread properties in assignment position.
* Fix `externalHelpers` option being incorrectly listed as type `string`.
* **Internal**
* Upgrade `core-js` to `0.9.0`.
* **Spec Compliancy**
* Fix object decorators not using the `initializer` pattern.
* Remove property initializer descriptor reflection.
## 5.1.11
* **Bug Fix**
* Memoise and bind member expression decorators.
* Move JSX children cleaning to opening element visitor. Fixes elements not being cleaned in certain scenarios.
* Consider `SwitchStatement`s to be `Scopable`.
* Fix `bluebirdCoroutines` calling `interopRequireWildcard` before it's defined.
* Add space to `do...while` code generation.
* Validate `super` use before `this` on `super` exit rather than entrance.
* **Polish**
* Add Babel name to logger.
## 5.1.10
* **Bug Fix**
* Remove `makePredicate` from acorn in favor of an `indexOf`.
* Remove statements to expression explosion when inserting a block statement.
* **Internal**
* Remove runtime compatibility check.
## 5.1.9
* **Bug Fix**
* Fix class property initializers with `undefined` values not being correctly writable.
* Fix self inferring generators incorrectly causing a stack error.
* Fix default export specifiers not triggering AMD `module` argument inclusion.
* Fix assignments not having their module references properly remapped.
* **Internal**
* Upgrade to latest `acorn`.
* **Polish**
* Make invalid LHS pattern error messages nicer.
## 5.1.8
* **Bug Fix**
* Only make parenthesized object pattern LHS illegal.
## 5.1.7
* **Internal**
* Add `parse` node API.
## 5.1.6
* **Bug Fix**
* Fix `runtime` built-in catchall not properly checking for local variables.
## 5.1.5
* **Internal**
* Bump `core-js` version.
## 5.1.4
* **Polish**
* Add missing `Reflect` methods to runtime transformer.
## 5.1.3
* **Internal**
* Switch entirely to vanilla regenerator.
* Clean up and make the parsing of decorators stateless.
* **Bug Fix**
* Don't do TCO on generators and async functions.
* Add missing `core-js` runtime definitions.
## 5.1.2
* **Bug Fix**
* Add `getIterator` and `isIterable` to `babel-runtime` build script.
## 5.1.1
* **Bug Fix**
* Add missing runtime symbol definitions.
## 5.1.0
* **Bug Fix**
* Fix super reference when using decorators.
* Don't do array unpack optimisation when member expressions are present.
* Add missing descriptors for undecorated class properties.
* Don't consider `arguments` and `eval` valid function names when doing function name inferrence.
* Fix scope tracking of constants in loop heads.
* Parse `AwaitExpression` as a unary instead of an assignment.
* Fix regex evaluation when attempting static evaluation.
* Don't emit tokens when doing a lookahead.
* Add missing `test` declaration to `utility.deadCodeElimination` transformer.
* **Internal**
* Upgrade `regenerator` to the latest and use my branch with the hope of eventually switching to vanilla regenerator.
* Add support for the replacement of for loop `init`s with statements.
* Upgrade dependencies.
* **Polish**
* When adding the scope IIFE when using default parameters, don't shadow the function expression, just `apply` `this` and `arguments` if necessary.
* Use path basename as non-default import fallback.
* **New Feature**
* Add [trailing function comma proposal](https://github.com/jeffmo/es-trailing-function-commas). Thanks [@AluisioASG](https://github.com/AluisioASG)!
* Add support for object literal decorators.
* Make core-js modular when using the `runtime` transformer.
## 5.0.12
* **Bug Fix**
* Fix incorrect remapping of module references inside of a function id redirection container.
## 5.0.11
* **Bug Fix**
* Fix new `for...of` loops not properly inheriting their original loop.
* **Internal**
* Disable scope instance cache.
* **Polish**
* Allow comments in `.babelrc` JSON.
## 5.0.9
* **Polish**
* Use `moduleId` for UMD global name if available.
* **Bug Fix**
* Fix UMD global `module` variable shadowing the `amd`/`common` `module` variable.
* Fix Flow param type annotation regression.
* Fix function name collision `toString` wrapper. Thanks [@alawatthe](https://github.com/alawatthe)!
## 5.0.8
* **Bug Fix**
* Fix falsy static class properties not being writable.
* Fix block scoping collisions not properly detecting modules and function clashes.
* Skip `this` before `super` for derived constructors on functions.
## 5.0.7
* **New Feature**
* Add `--ignore` and `--only` support to the CLI.
* **Bug Fix**
* Remove `HOMEPATH` environment variable from home resolution in `babel/register` cache.
* **Internal**
* Disable WIP path resolution introducing infinite recursion in some code examples.
* **Polish**
* Add live binding to CommonJS default imports.
## 5.0.6
* **Bug Fix**
* Fix mangling of import references that collide with properties on `Object.prototype`.
* Fix duplicate declarations incorrectly being reported for `var`.
## 5.0.5
* **Internal**
* Upgrade `core-js`.
* **Bug Fix**
* Fix arrays not being supported in `util.list`.
## 5.0.4
* **Polish**

View File

@@ -1,9 +1,24 @@
<p align="center">
<strong><a href="#setup">Setup</a></strong>
|
<strong><a href="#running-tests">Running tests</a></strong>
|
<strong><a href="#workflow">Workflow</a></strong>
|
<strong><a href="#dependencies">Dependencies</a></strong>
|
<strong><a href="#code-standards">Code Standards</a></strong>
</p>
----
# Contributing
Contributions are always welcome, no matter how large or small. Before
contributing, please read the
[code of conduct](https://github.com/babel/babel/blob/master/CODE_OF_CONDUCT.md).
## Developing
#### Setup
@@ -14,14 +29,19 @@ $ cd babel
$ make bootstrap
```
Then you need to run:
Then you can either run:
```sh
$ make build-core
```
to build Babel **once** or:
```sh
$ make watch-core
```
This will compile Babel and then sit in the background and on file modification
recompile the necessary files.
to have Babel build itself then incrementally build files on change.
#### Running tests
@@ -35,15 +55,20 @@ This is mostly overkill and you can limit the tests to a select few by directly
running them with `mocha`:
```sh
$ mocha test/transformation.js
$ mocha test/core/transformation.js
```
Use mocha's `--grep` option to run a subset of tests by name:
```sh
$ mocha test/transformation.js --grep es7
$ mocha test/core/transformation.js --grep es7
```
If you don't have `mocha` installed globally, you can still use it from Babel's
dependencies in `node_modules`, but make sure `node_modules/.bin` is added to
your [`$PATH`](http://unix.stackexchange.com/questions/26047/how-to-correctly-add-a-path-to-path) environment variable.
#### Workflow
* Fork the repository
@@ -54,24 +79,91 @@ $ mocha test/transformation.js --grep es7
* 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.
+ [chalk](http://ghub.io/chalk) This is used for terminal color highlighting for syntax errors.
+ [convert-source-map](http://ghub.io/convert-source-map) Turns a source map object into a comment etc.
+ [core-js](http://ghub.io/core-js) Used for the polyfill.
+ [debug](http://ghub.io/debug) Used to output debugging information when NODE_DEBUG is set to babel.
+ [detect-indent](http://ghub.io/detect-indent) This is used in the code generator so it can infer indentation.
+ [estraverse](http://ghub.io/estraverse) The only method on this is attachComments. I'd like to implement our own comment attachment algorithm eventually though.
+ [esutils](http://ghub.io/esutils) Various ES related utilities. Check whether something is a keyword etc.
+ [fs-readdir-recursive](http://ghub.io/fs-readdir-recursive) Recursively search a directory for.
+ [globals](http://ghub.io/globals) A list of JavaScript global variables. This is used by the scope tracking to check for colliding variables.
+ [is-integer](http://ghub.io/is-integer) Checks if something is an integer.
+ [js-tokens](http://ghub.io/js-tokens) This is used to get tokens for syntax error highlighting.
+ [leven](http://ghub.io/leven) A levenstein algorithm to determine how close a word is to another. This is used to offer suggestions when using the utility.undeclaredVariableCheck transformer.
+ [line-numbers](http://ghub.io/line-numbers) Used to produce the code frames in syntax errors.
+ [lodash](http://ghub.io/lodash) Used for various utilities.
+ [minimatch](http://ghub.io/minimatch) This is used to match glob-style ignore/only filters.
+ [output-file-sync](http://ghub.io/output-file-sync) Synchronously writes a file and create its ancestor directories if needed.
+ [path-is-absolute](http://ghub.io/path-is-absolute) Checks if a path is absolute. C:\foo and \foo are considered absolute.
+ [regenerator](http://ghub.io/regenerator) This is used to transform generators/async functions.
+ [regexpu](http://ghub.io/regexpu) Used to transform unicode regex patterns.
+ [repeating](http://ghub.io/repeating) Repeats a string.
+ [shebang-regex](http://ghub.io/shebang-regex) Literally just a regex that matches shebangs.
+ [slash](http://ghub.io/slash) Normalises path separators.
+ [source-map](http://ghub.io/source-map) Generates sourcemaps.
+ [source-map-support](http://ghub.io/source-map-support) Adds source map support to babel-node/babel/register.
+ [strip-json-comments](http://ghub.io/strip-json-comments) Remove comments from a JSON string. This is used for .babelrc files.
+ [to-fast-properties](http://ghub.io/to-fast-properties) A V8 trick to put an object into fast properties mode.
+ [trim-right](http://ghub.io/trim-right) Trims the rightside whitespace.
+ [user-home](http://ghub.io/user-home) Gets the users home directory. This is used to resolve the babel-node/babel/register cache.
#### Code Standards
* **General**
* Max of five arguments for functions
* Max depth of four nested blocks
* 2-spaced soft tabs
* **Naming**
* CamelCase all class names
* camelBack all variable names
* **Spacing**
* Spaces after all keywords
* Spaces before all left curly braces
* **Comments**
* Use JSDoc-style comments for methods
* Single-line comments for ambiguous code
* **Quotes**
* Always use double quotes
* Only use single quotes when the string contains a double quote
* **Declaration**
* No unused variables
* No pollution of global variables and prototypes

View File

@@ -3,23 +3,25 @@ BROWSERIFY_CMD = node_modules/browserify/bin/cmd.js
ISTANBUL_CMD = node_modules/istanbul/lib/cli.js cover
UGLIFY_CMD = node_modules/uglify-js/bin/uglifyjs
#UGLIFY_CMD = node_modules/uglify-js/bin/uglifyjs --mangle sort
JSHINT_CMD = node_modules/jshint/bin/jshint
MOCHA_CMD = node_modules/mocha/bin/_mocha
BABEL_CMD = node_modules/babel/bin/babel
export NODE_ENV = test
.PHONY: clean test test-cov test-clean test-travis test-simple test-all test-browser test-parser publish build bootstrap publish-core publish-runtime build-core watch-core build-core-test
.PHONY: clean test test-cov test-clean test-travis test-simple test-all test-browser test-parser publish build bootstrap publish-core publish-runtime build-core watch-core build-core-test clean-core
build-core:
build-core: clean-core
node $(BABEL_CMD) src --out-dir lib --copy-files
build-core-test:
build-core-test: clean-core
node $(BABEL_CMD) src --out-dir lib --copy-files --auxiliary-comment "istanbul ignore next"
watch-core:
watch-core: clean-core
node $(BABEL_CMD) src --out-dir lib --watch --copy-files
clean-core:
rm -rf lib
build:
mkdir -p dist
make build-core
@@ -80,9 +82,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
@@ -94,7 +102,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; \
@@ -109,9 +117,10 @@ publish-cli:
npm publish
bootstrap:
npm list --global --depth 1 babel >/dev/null 2>&1 && npm uninstall -g babel || true
npm install
npm link
cd packages/babel-cli && npm install && npm link
cd packages/babel-cli && npm install && npm link && npm link babel-core
git submodule update --init
cd vendor/regenerator && npm install
cd vendor/compat-table && npm install object-assign
make build

View File

@@ -9,7 +9,7 @@
</p>
<p align="center">
For questions and support please visit the <a href="https://gitter.im/babel/babel">gitter room</a> or <a href="stackoverflow.com">StackOverflow</a>. The Babel issue tracker is <strong>exclusively</strong> for bug reports and future requests.
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">

View File

@@ -1,7 +1,7 @@
{
"name": "babel-core",
"description": "Turn ES6 code into readable vanilla ES5 with source maps",
"version": "5.0.4",
"version": "5.2.17",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/",
"repository": "babel/babel",
@@ -27,46 +27,52 @@
"test": "make test"
},
"dependencies": {
"acorn-jsx": "^1.0.0",
"ast-types": "~0.7.0",
"bluebird": "^2.9.25",
"chalk": "^1.0.0",
"convert-source-map": "^0.5.0",
"core-js": "^0.8.0",
"convert-source-map": "^1.1.0",
"core-js": "^0.9.0",
"debug": "^2.1.1",
"detect-indent": "^3.0.0",
"estraverse": "^1.9.1",
"esutils": "^1.1.6",
"esquery": "^0.4.0",
"estraverse": "^4.0.0",
"esutils": "^2.0.0",
"fs-readdir-recursive": "^0.1.0",
"globals": "^6.2.0",
"globals": "^6.4.0",
"is-integer": "^1.0.4",
"js-tokens": "1.0.0",
"leven": "^1.0.1",
"line-numbers": "0.2.0",
"lodash": "^3.2.0",
"lodash": "^3.6.0",
"minimatch": "^2.0.3",
"output-file-sync": "^1.1.0",
"path-is-absolute": "^1.0.0",
"private": "^0.1.6",
"regenerator-babel": "0.8.13-2",
"regenerator": "^0.8.20",
"regexpu": "^1.1.2",
"repeating": "^1.1.2",
"resolve": "^1.1.6",
"shebang-regex": "^1.0.0",
"slash": "^1.0.0",
"source-map": "^0.4.0",
"source-map-support": "^0.2.9",
"source-map-support": "^0.2.10",
"strip-json-comments": "^1.0.2",
"to-fast-properties": "^1.0.0",
"trim-right": "^1.0.0"
"trim-right": "^1.0.0",
"user-home": "^1.1.1"
},
"devDependencies": {
"babel": "4.7.13",
"browserify": "^9.0.3",
"chai": "^2.0.0",
"eslint": "^0.15.1",
"babel-eslint": "^1.0.1",
"babel": "5.1.13",
"browserify": "^9.0.8",
"chai": "^2.2.0",
"eslint": "^0.18.0",
"babel-eslint": "^2.0.0",
"esvalid": "^1.1.0",
"istanbul": "^0.3.5",
"matcha": "^0.6.0",
"mocha": "^2.1.0",
"rimraf": "^2.2.8",
"mocha": "2.2.0",
"rimraf": "^2.3.2",
"uglify-js": "^2.4.16"
}
}

View File

@@ -0,0 +1,5 @@
# babel-cli
Babel CLI
For more information please look at [babel](https://github.com/babel/babel).

View File

@@ -4,6 +4,7 @@ var pathIsAbsolute = require("path-is-absolute");
var commander = require("commander");
var Module = require("module");
var babel = require("babel-core");
var inspect = require("util").inspect;
var path = require("path");
var repl = require("repl");
var util = require("babel-core").util;
@@ -71,7 +72,10 @@ if (program.eval || program.print) {
global.require = module.require.bind(module);
var result = _eval(code, global.__filename);
if (program.print) console.log(result);
if (program.print) {
var output = _.isString(result) ? result : inspect(result);
process.stdout.write(output + "\n");
}
} else {
if (program.args.length) {
// slice all arguments up to the first filename since they're babel args that we handle

View File

@@ -55,6 +55,7 @@ babelArgs.forEach(function(arg){
case "--harmony_classes":
case "--harmony_object_literals":
case "--harmony_templates":
case "--harmony_rest_parameters":
case "--compiled_keyed_generic_loads":
case "--pretenuring_call_new":
case "--allocation_site_pretenuring":

View File

@@ -28,7 +28,9 @@ module.exports = function (commander, filenames, opts) {
};
var handleFile = function (src, filename) {
if (util.canCompile(filename)) {
if (util.shouldIgnore(src)) return;
if (util.canCompile(filename, commander.extensions)) {
write(src, filename);
} else if (commander.copyFiles) {
outputFileSync(path.join(commander.outDir, filename), fs.readFileSync(src));

View File

@@ -27,9 +27,14 @@ module.exports = function (commander, filenames, opts) {
if (result.map) {
var consumer = new sourceMap.SourceMapConsumer(result.map);
var sourceFilename = filename;
map._sources.add(filename);
map.setSourceContent(filename, result.actual);
if (commander.outFile) {
sourceFilename = path.relative(path.dirname(commander.outFile), sourceFilename);
}
map._sources.add(sourceFilename);
map.setSourceContent(sourceFilename, result.actual);
consumer.eachMapping(function (mapping) {
map._mappings.add({
@@ -37,7 +42,7 @@ module.exports = function (commander, filenames, opts) {
generatedColumn: mapping.generatedColumn,
originalLine: mapping.originalLine,
originalColumn: mapping.originalColumn,
source: filename
source: sourceFilename
});
});
@@ -107,6 +112,8 @@ module.exports = function (commander, filenames, opts) {
});
_.each(_filenames, function (filename) {
if (util.shouldIgnore(filename)) return;
results.push(util.compile(filename));
});

View File

@@ -1,13 +1,15 @@
#!/usr/bin/env node
var commander = require("commander");
var transform = require("babel-core").transform;
var kebabCase = require("lodash/string/kebabCase");
var options = require("babel-core").options;
var util = require("babel-core").util;
var each = require("lodash/collection/each");
var keys = require("lodash/object/keys");
var fs = require("fs");
var moduleFormatters = require("babel-core/lib/babel/transformation/modules");
var commander = require("commander");
var transform = require("babel-core").transform;
var kebabCase = require("lodash/string/kebabCase");
var options = require("babel-core").options;
var util = require("babel-core").util;
var each = require("lodash/collection/each");
var keys = require("lodash/object/keys");
var fs = require("fs");
var glob = require("glob");
each(options, function (option, key) {
if (option.hidden) return;
@@ -35,6 +37,7 @@ each(options, function (option, key) {
commander.option(arg, desc.join(" "));
})
commander.option("-x, --extensions [extensions]", "List of extensions to compile when a directory has been input [.es6,.js,.es,.jsx]");
commander.option("-w, --watch", "Recompile files on changes");
commander.option("-o, --out-file [out]", "Compile all input files into a single file");
commander.option("-d, --out-dir [out]", "Compile an input directory of modules into an output directory");
@@ -56,8 +59,8 @@ commander.on("--help", function () {
console.log();
};
outKeys("Transformers", transform.transformers);
outKeys("Module formatters", transform.moduleFormatters);
outKeys("Transformers", transform.pipeline.transformers);
outKeys("Module formatters", moduleFormatters);
});
var pkg = require("../../package.json");
@@ -67,9 +70,17 @@ commander.parse(process.argv);
//
if (commander.extensions) {
commander.extensions = util.arrayify(commander.extensions);
}
//
var errors = [];
var filenames = commander.args;
var filenames = commander.args.reduce(function (globbed, input) {
return globbed.concat(glob.sync(input));
}, []);
each(filenames, function (filename) {
if (!fs.existsSync(filename)) {
@@ -102,12 +113,15 @@ if (errors.length) {
//
exports.opts = {};
var opts = exports.opts = {};
each(options, function (opt, key) {
exports.opts[key] = commander[key];
opts[key] = commander[key];
});
opts.ignore = util.arrayify(opts.ignore, util.regexify);
opts.only = util.arrayify(opts.only, util.regexify);
var fn;
if (commander.outDir) {

View File

@@ -16,6 +16,10 @@ exports.readdir = readdir;
exports.canCompile = util.canCompile;
exports.shouldIgnore = function (loc) {
return util.shouldIgnore(loc, index.opts.ignore, index.opts.only);
};
exports.addSourceMappingUrl = function (code, loc) {
return code + "\n//# sourceMappingURL=" + path.basename(loc);
};
@@ -23,6 +27,8 @@ exports.addSourceMappingUrl = function (code, loc) {
exports.transform = function (filename, code, opts) {
opts = _.defaults(opts || {}, index.opts);
opts.filename = filename;
opts.ignore = null;
opts.only = null;
var result = babel.transform(code, opts);
result.filename = filename;

View File

@@ -1,21 +1,22 @@
{
"name": "babel",
"description": "Turn ES6 code into readable vanilla ES5 with source maps",
"version": "5.0.3",
"version": "5.2.16",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/",
"repository": "babel/babel",
"preferGlobal": true,
"dependencies": {
"chokidar": "^0.12.6",
"babel-core": "^5.0.3",
"babel-core": "^5.2.16",
"chokidar": "^1.0.0",
"commander": "^2.6.0",
"convert-source-map": "^1.1.0",
"fs-readdir-recursive": "^0.1.0",
"output-file-sync": "^1.1.0",
"glob": "^5.0.5",
"lodash": "^3.2.0",
"convert-source-map": "^0.5.0",
"source-map": "^0.4.0",
"path-is-absolute": "^1.0.0"
"output-file-sync": "^1.1.0",
"path-is-absolute": "^1.0.0",
"source-map": "^0.4.0"
},
"bin": {
"babel": "./bin/babel/index.js",

View File

@@ -0,0 +1 @@
module.exports = require("babel-core/register-without-polyfill");

View File

@@ -1,10 +1,10 @@
{
"name": "babel-runtime",
"description": "babel selfContained runtime",
"version": "5.0.3",
"version": "5.2.16",
"repository": "babel/babel",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"dependencies": {
"core-js": "^0.8.0"
"core-js": "^0.9.0"
}
}

View File

@@ -13,16 +13,20 @@ function relative(filename) {
return __dirname + "/babel-runtime/" + filename;
}
function readFile(filename, defaultify) {
function readFile(filename, shouldDefaultify) {
var file = fs.readFileSync(require.resolve(filename), "utf8");
if (defaultify) {
file += '\nmodule.exports = { "default": module.exports, __esModule: true };\n';
if (shouldDefaultify) {
file += "\n" + defaultify("module.exports") + "\n";
}
return file;
}
function defaultify(name) {
return 'module.exports = { "default": ' + name + ', __esModule: true };';
}
function updatePackage() {
var pkgLoc = relative("package.json");
var pkg = require(pkgLoc);
@@ -66,7 +70,29 @@ each(File.helpers, function (helperName) {
writeFile("helpers/" + helperName + ".js", buildHelper(helperName));
});
writeFile("regenerator/index.js", readFile("regenerator-babel/runtime-module", true));
writeFile("regenerator/runtime.js", selfContainify(readFile("regenerator-babel/runtime")));
writeFile("regenerator/index.js", readFile("regenerator/runtime-module", true));
writeFile("regenerator/runtime.js", selfContainify(readFile("regenerator/runtime")));
//
var coreDefinitions = require("../lib/babel/transformation/transformers/other/runtime/definitions");
var paths = ["is-iterable", "get-iterator"];
each(coreDefinitions.builtins, function (path) {
paths.push(path);
});
each(coreDefinitions.methods, function (props) {
each(props, function (path) {
paths.push(path);
});
});
each(paths, function (path) {
writeFile("core-js/" + path + ".js", defaultify('require("core-js/library/fn/' + path + '")'));
});
//
updatePackage();

View File

@@ -0,0 +1 @@
module.exports = require("./lib/babel/api/register/node");

View File

@@ -1 +1 @@
module.exports = require("./lib/babel/api/register/node");
module.exports = require("./lib/babel/api/register/node-polyfill");

6
src/acorn/index.js Normal file
View File

@@ -0,0 +1,6 @@
export * from "./src/index";
import "./plugins/flow";
import inject from "acorn-jsx/inject";
import * as acorn from "./src/index";
inject(acorn);

View File

@@ -2,7 +2,7 @@
"name": "acorn",
"description": "ECMAScript parser",
"homepage": "https://github.com/marijnh/acorn",
"main": "src/index.js",
"main": "index.js",
"version": "1.0.0",
"engines": {
"node": ">=0.4.0"

View File

@@ -1,4 +1,4 @@
var acorn = require("..")
var acorn = require("../src/index")
var pp = acorn.Parser.prototype
var tt = acorn.tokTypes
@@ -322,7 +322,7 @@ pp.flow_parseObjectType = function (allowStatic) {
}
pp.flow_objectTypeSemicolon = function () {
if (!this.eat(tt.semi) && this.type !== tt.braceR) {
if (!this.eat(tt.semi) && !this.eat(tt.comma) && this.type !== tt.braceR) {
this.unexpected()
}
}

View File

@@ -1,658 +0,0 @@
var acorn = require("..")
var tt = acorn.tokTypes;
var tc = acorn.tokContexts;
tc.j_oTag = new acorn.TokContext("<tag", false);
tc.j_cTag = new acorn.TokContext("</tag", false);
tc.j_expr = new acorn.TokContext("<tag>...</tag>", true, true);
tt.jsxName = new acorn.TokenType("jsxName");
tt.jsxText = new acorn.TokenType("jsxText", {beforeExpr: true});
tt.jsxTagStart = new acorn.TokenType("jsxTagStart");
tt.jsxTagEnd = new acorn.TokenType("jsxTagEnd");
tt.jsxTagStart.updateContext = function() {
this.context.push(tc.j_expr); // treat as beginning of JSX expression
this.context.push(tc.j_oTag); // start opening tag context
this.exprAllowed = false;
};
tt.jsxTagEnd.updateContext = function(prevType) {
var out = this.context.pop();
if (out === tc.j_oTag && prevType === tt.slash || out === tc.j_cTag) {
this.context.pop();
this.exprAllowed = this.curContext() === tc.j_expr;
} else {
this.exprAllowed = true;
}
};
var pp = acorn.Parser.prototype;
// Reads inline JSX contents token.
pp.jsx_readToken = function() {
var out = "", chunkStart = this.pos;
for (;;) {
if (this.pos >= this.input.length)
this.raise(this.start, "Unterminated JSX contents");
var ch = this.input.charCodeAt(this.pos);
switch (ch) {
case 60: // '<'
case 123: // '{'
if (this.pos === this.start) {
if (ch === 60 && this.exprAllowed) {
++this.pos;
return this.finishToken(tt.jsxTagStart);
}
return this.getTokenFromCode(ch);
}
out += this.input.slice(chunkStart, this.pos);
return this.finishToken(tt.jsxText, out);
case 38: // '&'
out += this.input.slice(chunkStart, this.pos);
out += this.jsx_readEntity();
chunkStart = this.pos;
break;
default:
if (acorn.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);
}
if (this.options.locations) {
++this.curLine;
this.lineStart = this.pos;
}
chunkStart = this.pos;
} else {
++this.pos;
}
}
}
};
pp.jsx_readString = function(quote) {
var out = "", chunkStart = ++this.pos;
for (;;) {
if (this.pos >= this.input.length)
this.raise(this.start, "Unterminated string constant");
var ch = this.input.charCodeAt(this.pos);
if (ch === quote) break;
if (ch === 38) { // '&'
out += this.input.slice(chunkStart, this.pos);
out += this.jsx_readEntity();
chunkStart = this.pos;
} else {
++this.pos;
}
}
out += this.input.slice(chunkStart, this.pos++);
return this.finishToken(tt.string, out);
};
var XHTMLEntities = {
quot: '\u0022',
amp: '&',
apos: '\u0027',
lt: '<',
gt: '>',
nbsp: '\u00A0',
iexcl: '\u00A1',
cent: '\u00A2',
pound: '\u00A3',
curren: '\u00A4',
yen: '\u00A5',
brvbar: '\u00A6',
sect: '\u00A7',
uml: '\u00A8',
copy: '\u00A9',
ordf: '\u00AA',
laquo: '\u00AB',
not: '\u00AC',
shy: '\u00AD',
reg: '\u00AE',
macr: '\u00AF',
deg: '\u00B0',
plusmn: '\u00B1',
sup2: '\u00B2',
sup3: '\u00B3',
acute: '\u00B4',
micro: '\u00B5',
para: '\u00B6',
middot: '\u00B7',
cedil: '\u00B8',
sup1: '\u00B9',
ordm: '\u00BA',
raquo: '\u00BB',
frac14: '\u00BC',
frac12: '\u00BD',
frac34: '\u00BE',
iquest: '\u00BF',
Agrave: '\u00C0',
Aacute: '\u00C1',
Acirc: '\u00C2',
Atilde: '\u00C3',
Auml: '\u00C4',
Aring: '\u00C5',
AElig: '\u00C6',
Ccedil: '\u00C7',
Egrave: '\u00C8',
Eacute: '\u00C9',
Ecirc: '\u00CA',
Euml: '\u00CB',
Igrave: '\u00CC',
Iacute: '\u00CD',
Icirc: '\u00CE',
Iuml: '\u00CF',
ETH: '\u00D0',
Ntilde: '\u00D1',
Ograve: '\u00D2',
Oacute: '\u00D3',
Ocirc: '\u00D4',
Otilde: '\u00D5',
Ouml: '\u00D6',
times: '\u00D7',
Oslash: '\u00D8',
Ugrave: '\u00D9',
Uacute: '\u00DA',
Ucirc: '\u00DB',
Uuml: '\u00DC',
Yacute: '\u00DD',
THORN: '\u00DE',
szlig: '\u00DF',
agrave: '\u00E0',
aacute: '\u00E1',
acirc: '\u00E2',
atilde: '\u00E3',
auml: '\u00E4',
aring: '\u00E5',
aelig: '\u00E6',
ccedil: '\u00E7',
egrave: '\u00E8',
eacute: '\u00E9',
ecirc: '\u00EA',
euml: '\u00EB',
igrave: '\u00EC',
iacute: '\u00ED',
icirc: '\u00EE',
iuml: '\u00EF',
eth: '\u00F0',
ntilde: '\u00F1',
ograve: '\u00F2',
oacute: '\u00F3',
ocirc: '\u00F4',
otilde: '\u00F5',
ouml: '\u00F6',
divide: '\u00F7',
oslash: '\u00F8',
ugrave: '\u00F9',
uacute: '\u00FA',
ucirc: '\u00FB',
uuml: '\u00FC',
yacute: '\u00FD',
thorn: '\u00FE',
yuml: '\u00FF',
OElig: '\u0152',
oelig: '\u0153',
Scaron: '\u0160',
scaron: '\u0161',
Yuml: '\u0178',
fnof: '\u0192',
circ: '\u02C6',
tilde: '\u02DC',
Alpha: '\u0391',
Beta: '\u0392',
Gamma: '\u0393',
Delta: '\u0394',
Epsilon: '\u0395',
Zeta: '\u0396',
Eta: '\u0397',
Theta: '\u0398',
Iota: '\u0399',
Kappa: '\u039A',
Lambda: '\u039B',
Mu: '\u039C',
Nu: '\u039D',
Xi: '\u039E',
Omicron: '\u039F',
Pi: '\u03A0',
Rho: '\u03A1',
Sigma: '\u03A3',
Tau: '\u03A4',
Upsilon: '\u03A5',
Phi: '\u03A6',
Chi: '\u03A7',
Psi: '\u03A8',
Omega: '\u03A9',
alpha: '\u03B1',
beta: '\u03B2',
gamma: '\u03B3',
delta: '\u03B4',
epsilon: '\u03B5',
zeta: '\u03B6',
eta: '\u03B7',
theta: '\u03B8',
iota: '\u03B9',
kappa: '\u03BA',
lambda: '\u03BB',
mu: '\u03BC',
nu: '\u03BD',
xi: '\u03BE',
omicron: '\u03BF',
pi: '\u03C0',
rho: '\u03C1',
sigmaf: '\u03C2',
sigma: '\u03C3',
tau: '\u03C4',
upsilon: '\u03C5',
phi: '\u03C6',
chi: '\u03C7',
psi: '\u03C8',
omega: '\u03C9',
thetasym: '\u03D1',
upsih: '\u03D2',
piv: '\u03D6',
ensp: '\u2002',
emsp: '\u2003',
thinsp: '\u2009',
zwnj: '\u200C',
zwj: '\u200D',
lrm: '\u200E',
rlm: '\u200F',
ndash: '\u2013',
mdash: '\u2014',
lsquo: '\u2018',
rsquo: '\u2019',
sbquo: '\u201A',
ldquo: '\u201C',
rdquo: '\u201D',
bdquo: '\u201E',
dagger: '\u2020',
Dagger: '\u2021',
bull: '\u2022',
hellip: '\u2026',
permil: '\u2030',
prime: '\u2032',
Prime: '\u2033',
lsaquo: '\u2039',
rsaquo: '\u203A',
oline: '\u203E',
frasl: '\u2044',
euro: '\u20AC',
image: '\u2111',
weierp: '\u2118',
real: '\u211C',
trade: '\u2122',
alefsym: '\u2135',
larr: '\u2190',
uarr: '\u2191',
rarr: '\u2192',
darr: '\u2193',
harr: '\u2194',
crarr: '\u21B5',
lArr: '\u21D0',
uArr: '\u21D1',
rArr: '\u21D2',
dArr: '\u21D3',
hArr: '\u21D4',
forall: '\u2200',
part: '\u2202',
exist: '\u2203',
empty: '\u2205',
nabla: '\u2207',
isin: '\u2208',
notin: '\u2209',
ni: '\u220B',
prod: '\u220F',
sum: '\u2211',
minus: '\u2212',
lowast: '\u2217',
radic: '\u221A',
prop: '\u221D',
infin: '\u221E',
ang: '\u2220',
and: '\u2227',
or: '\u2228',
cap: '\u2229',
cup: '\u222A',
'int': '\u222B',
there4: '\u2234',
sim: '\u223C',
cong: '\u2245',
asymp: '\u2248',
ne: '\u2260',
equiv: '\u2261',
le: '\u2264',
ge: '\u2265',
sub: '\u2282',
sup: '\u2283',
nsub: '\u2284',
sube: '\u2286',
supe: '\u2287',
oplus: '\u2295',
otimes: '\u2297',
perp: '\u22A5',
sdot: '\u22C5',
lceil: '\u2308',
rceil: '\u2309',
lfloor: '\u230A',
rfloor: '\u230B',
lang: '\u2329',
rang: '\u232A',
loz: '\u25CA',
spades: '\u2660',
clubs: '\u2663',
hearts: '\u2665',
diams: '\u2666'
};
var hexNumber = /^[\da-fA-F]+$/;
var decimalNumber = /^\d+$/;
pp.jsx_readEntity = function() {
var str = "", count = 0, entity;
var ch = this.input[this.pos];
if (ch !== "&")
this.raise(this.pos, "Entity must start with an ampersand");
var startPos = ++this.pos;
while (this.pos < this.input.length && count++ < 10) {
ch = this.input[this.pos++];
if (ch === ";") {
if (str[0] === "#") {
if (str[1] === "x") {
str = str.substr(2);
if (hexNumber.test(str))
entity = String.fromCharCode(parseInt(str, 16));
} else {
str = str.substr(1);
if (decimalNumber.test(str))
entity = String.fromCharCode(parseInt(str, 10));
}
} else {
entity = XHTMLEntities[str];
}
break;
}
str += ch;
}
if (!entity) {
this.pos = startPos;
return "&";
}
return entity;
};
// Read a JSX identifier (valid tag or attribute name).
//
// Optimized version since JSX identifiers can't contain
// escape characters and so can be read as single slice.
// Also assumes that first character was already checked
// by isIdentifierStart in readToken.
pp.jsx_readWord = function() {
var ch, start = this.pos;
do {
ch = this.input.charCodeAt(++this.pos);
} while (acorn.isIdentifierChar(ch) || ch === 45); // '-'
return this.finishToken(tt.jsxName, this.input.slice(start, this.pos));
};
// Transforms JSX element name to string.
function getQualifiedJSXName(object) {
if (object.type === "JSXIdentifier")
return object.name;
if (object.type === "JSXNamespacedName")
return object.namespace.name + ':' + object.name.name;
if (object.type === "JSXMemberExpression")
return getQualifiedJSXName(object.object) + '.' +
getQualifiedJSXName(object.property);
}
// Parse next token as JSX identifier
pp.jsx_parseIdentifier = function() {
var node = this.startNode();
if (this.type === tt.jsxName)
node.name = this.value;
else if (this.type.keyword)
node.name = this.type.keyword;
else
this.unexpected();
this.next();
return this.finishNode(node, "JSXIdentifier");
};
// Parse namespaced identifier.
pp.jsx_parseNamespacedName = function() {
var start = this.markPosition();
var name = this.jsx_parseIdentifier();
if (!this.eat(tt.colon)) return name;
var node = this.startNodeAt(start);
node.namespace = name;
node.name = this.jsx_parseIdentifier();
return this.finishNode(node, "JSXNamespacedName");
};
// Parses element name in any form - namespaced, member
// or single identifier.
pp.jsx_parseElementName = function() {
var start = this.markPosition();
var node = this.jsx_parseNamespacedName();
while (this.eat(tt.dot)) {
var newNode = this.startNodeAt(start);
newNode.object = node;
newNode.property = this.jsx_parseIdentifier();
node = this.finishNode(newNode, "JSXMemberExpression");
}
return node;
};
// Parses any type of JSX attribute value.
pp.jsx_parseAttributeValue = function() {
switch (this.type) {
case tt.braceL:
var node = this.jsx_parseExpressionContainer();
if (node.expression.type === "JSXEmptyExpression")
this.raise(node.start, "JSX attributes must only be assigned a non-empty expression");
return node;
case tt.jsxTagStart:
case tt.string:
return this.parseExprAtom();
default:
this.raise(this.start, "JSX value should be either an expression or a quoted JSX text");
}
};
// JSXEmptyExpression is unique type since it doesn't actually parse anything,
// and so it should start at the end of last read token (left brace) and finish
// at the beginning of the next one (right brace).
pp.jsx_parseEmptyExpression = function() {
var tmp = this.start;
this.start = this.lastTokEnd;
this.lastTokEnd = tmp;
tmp = this.startLoc;
this.startLoc = this.lastTokEndLoc;
this.lastTokEndLoc = tmp;
return this.finishNode(this.startNode(), "JSXEmptyExpression");
};
// Parses JSX expression enclosed into curly brackets.
pp.jsx_parseExpressionContainer = function() {
var node = this.startNode();
this.next();
node.expression = this.type === tt.braceR
? this.jsx_parseEmptyExpression()
: this.parseExpression();
this.expect(tt.braceR);
return this.finishNode(node, "JSXExpressionContainer");
};
// Parses following JSX attribute name-value pair.
pp.jsx_parseAttribute = function() {
var node = this.startNode();
if (this.eat(tt.braceL)) {
this.expect(tt.ellipsis);
node.argument = this.parseMaybeAssign();
this.expect(tt.braceR);
return this.finishNode(node, "JSXSpreadAttribute");
}
node.name = this.jsx_parseNamespacedName();
node.value = this.eat(tt.eq) ? this.jsx_parseAttributeValue() : null;
return this.finishNode(node, "JSXAttribute");
};
// Parses JSX opening tag starting after '<'.
pp.jsx_parseOpeningElementAt = function(start) {
var node = this.startNodeAt(start);
node.attributes = [];
node.name = this.jsx_parseElementName();
while (this.type !== tt.slash && this.type !== tt.jsxTagEnd)
node.attributes.push(this.jsx_parseAttribute());
node.selfClosing = this.eat(tt.slash);
this.expect(tt.jsxTagEnd);
return this.finishNode(node, "JSXOpeningElement");
};
// Parses JSX closing tag starting after '</'.
pp.jsx_parseClosingElementAt = function(start) {
var node = this.startNodeAt(start);
node.name = this.jsx_parseElementName();
this.expect(tt.jsxTagEnd);
return this.finishNode(node, "JSXClosingElement");
};
// Parses entire JSX element, including it's opening tag
// (starting after '<'), attributes, contents and closing tag.
pp.jsx_parseElementAt = function(start) {
var node = this.startNodeAt(start);
var children = [];
var openingElement = this.jsx_parseOpeningElementAt(start);
var closingElement = null;
if (!openingElement.selfClosing) {
contents: for (;;) {
switch (this.type) {
case tt.jsxTagStart:
start = this.markPosition();
this.next();
if (this.eat(tt.slash)) {
closingElement = this.jsx_parseClosingElementAt(start);
break contents;
}
children.push(this.jsx_parseElementAt(start));
break;
case tt.jsxText:
children.push(this.parseExprAtom());
break;
case tt.braceL:
children.push(this.jsx_parseExpressionContainer());
break;
default:
this.unexpected();
}
}
if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name))
this.raise(
closingElement.start,
"Expected corresponding JSX closing tag for <" + getQualifiedJSXName(openingElement.name) + ">");
}
node.openingElement = openingElement;
node.closingElement = closingElement;
node.children = children;
return this.finishNode(node, "JSXElement");
};
// Parses entire JSX element from current position.
pp.jsx_parseElement = function() {
var start = this.markPosition();
this.next();
return this.jsx_parseElementAt(start);
};
acorn.plugins.jsx = function(instance) {
instance.extend("parseExprAtom", function(inner) {
return function(refShortHandDefaultPos) {
if (this.type === tt.jsxText)
return this.parseLiteral(this.value);
else if (this.type === tt.jsxTagStart)
return this.jsx_parseElement();
else
return inner.call(this, refShortHandDefaultPos);
};
});
instance.extend("readToken", function(inner) {
return function(code) {
var context = this.curContext();
if (context === tc.j_expr) return this.jsx_readToken();
if (context === tc.j_oTag || context === tc.j_cTag) {
if (acorn.isIdentifierStart(code)) return this.jsx_readWord();
if (code == 62) {
++this.pos;
return this.finishToken(tt.jsxTagEnd);
}
if ((code === 34 || code === 39) && context == tc.j_oTag)
return this.jsx_readString(code);
}
if (code === 60 && this.exprAllowed) {
++this.pos;
return this.finishToken(tt.jsxTagStart);
}
return inner.call(this, code);
};
});
instance.extend("updateContext", function(inner) {
return function(prevType) {
if (this.type == tt.braceL) {
var curContext = this.curContext();
if (curContext == tc.j_oTag) this.context.push(tc.b_expr);
else if (curContext == tc.j_expr) this.context.push(tc.b_tmpl);
else inner.call(this, prevType);
this.exprAllowed = true;
} else if (this.type === tt.slash && prevType === tt.jsxTagStart) {
this.context.length -= 2; // do not consider JSX expr -> JSX open tag -> ... anymore
this.context.push(tc.j_cTag); // reconsider as closing tag context
this.exprAllowed = false;
} else {
return inner.call(this, prevType);
}
};
});
}

View File

@@ -93,19 +93,25 @@ pp.parseMaybeAssign = function(noIn, refShorthandDefaultPos, afterLeftParse) {
failOnShorthandAssign = false
}
let start = this.markPosition()
if (this.type == tt.parenL || this.type == tt.name)
this.potentialArrowAt = this.start
let left = this.parseMaybeConditional(noIn, refShorthandDefaultPos)
if (afterLeftParse) left = afterLeftParse.call(this, left, start)
if (this.type.isAssign) {
let node = this.startNodeAt(start)
node.operator = this.value
node.left = this.type === tt.eq ? this.toAssignable(left) : left
refShorthandDefaultPos.start = 0; // reset because shorthand default was used correctly
refShorthandDefaultPos.start = 0 // reset because shorthand default was used correctly
this.checkLVal(left)
if (left.parenthesizedExpression) {
let errorMsg
if (left.type === "ObjectPattern") {
this.raise(left.start, "You're trying to assign to a parenthesized expression, instead of `({ foo }) = {}` use `({ foo } = {})`");
} else {
this.raise(left.start, "Parenthesized left hand expressions are illegal");
errorMsg = "`({a}) = 0` use `({a} = 0)`"
} else if (left.type === "ArrayPattern") {
errorMsg = "`([a]) = 0` use `([a] = 0)`"
}
if (errorMsg) {
this.raise(left.start, `You're trying to assign to a parenthesized expression, eg. instead of ${errorMsg}`)
}
}
this.next()
@@ -224,7 +230,7 @@ pp.parseSubscripts = function(base, start, noCalls) {
} else if (!noCalls && this.eat(tt.parenL)) {
let node = this.startNodeAt(start)
node.callee = base
node.arguments = this.parseExprList(tt.parenR, false)
node.arguments = this.parseExprList(tt.parenR, this.options.features["es7.trailingFunctionCommas"])
return this.parseSubscripts(this.finishNode(node, "CallExpression"), start, noCalls)
} else if (this.type === tt.backQuote) {
let node = this.startNodeAt(start)
@@ -240,7 +246,7 @@ pp.parseSubscripts = function(base, start, noCalls) {
// or `{}`.
pp.parseExprAtom = function(refShorthandDefaultPos) {
let node
let node, canBeArrow = this.potentialArrowAt == this.start
switch (this.type) {
case tt._this:
case tt._super:
@@ -250,7 +256,7 @@ pp.parseExprAtom = function(refShorthandDefaultPos) {
return this.finishNode(node, type)
case tt._yield:
if (this.inGenerator) unexpected()
if (this.inGenerator) this.unexpected()
case tt._do:
if (this.options.features["es7.doExpressions"]) {
@@ -271,7 +277,7 @@ pp.parseExprAtom = function(refShorthandDefaultPos) {
if (id.name === "async") {
// arrow functions
if (this.type === tt.parenL) {
let expr = this.parseParenAndDistinguishExpression(start, true)
let expr = this.parseParenAndDistinguishExpression(start, true, true)
if (expr && expr.type === "ArrowFunctionExpression") {
return expr
} else {
@@ -302,9 +308,8 @@ pp.parseExprAtom = function(refShorthandDefaultPos) {
}
//
if (!this.canInsertSemicolon() && this.eat(tt.arrow)) {
if (canBeArrow && !this.canInsertSemicolon() && this.eat(tt.arrow))
return this.parseArrowExpression(this.startNodeAt(start), [id])
}
return id
case tt.regexp:
@@ -324,7 +329,7 @@ pp.parseExprAtom = function(refShorthandDefaultPos) {
return this.finishNode(node, "Literal")
case tt.parenL:
return this.parseParenAndDistinguishExpression()
return this.parseParenAndDistinguishExpression(null, null, canBeArrow)
case tt.bracketL:
node = this.startNode()
@@ -378,7 +383,7 @@ pp.parseParenExpression = function() {
return val
}
pp.parseParenAndDistinguishExpression = function(start, isAsync) {
pp.parseParenAndDistinguishExpression = function(start, isAsync, canBeArrow) {
start = start || this.markPosition()
let val
if (this.options.ecmaVersion >= 6) {
@@ -407,7 +412,7 @@ pp.parseParenAndDistinguishExpression = function(start, isAsync) {
let innerEnd = this.markPosition()
this.expect(tt.parenR)
if (!this.canInsertSemicolon() && this.eat(tt.arrow)) {
if (canBeArrow && !this.canInsertSemicolon() && this.eat(tt.arrow)) {
if (innerParenStart) this.unexpected(innerParenStart)
return this.parseParenArrowList(start, exprList, isAsync)
}
@@ -508,14 +513,21 @@ pp.parseTemplate = function() {
pp.parseObj = function(isPattern, refShorthandDefaultPos) {
let node = this.startNode(), first = true, propHash = {}
node.properties = []
let decorators = []
this.next()
while (!this.eat(tt.braceR)) {
if (!first) {
this.expect(tt.comma)
if (this.afterTrailingComma(tt.braceR)) break
} else first = false
while (this.type === tt.at) {
decorators.push(this.parseDecorator())
}
let prop = this.startNode(), isGenerator = false, isAsync = false, start
if (decorators.length) {
prop.decorators = decorators
decorators = []
}
if (this.options.features["es7.objectRestSpread"] && this.type === tt.ellipsis) {
prop = this.parseSpread()
prop.type = "SpreadProperty"
@@ -546,6 +558,9 @@ pp.parseObj = function(isPattern, refShorthandDefaultPos) {
this.checkPropClash(prop, propHash)
node.properties.push(this.finishNode(prop, "Property"))
}
if (decorators.length) {
this.raise(this.start, "You have trailing decorators with no property");
}
return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
}
@@ -726,7 +741,7 @@ pp.parseAwait = function (node) {
this.unexpected()
}
node.all = this.eat(tt.star)
node.argument = this.parseMaybeAssign(true)
node.argument = this.parseMaybeUnary()
return this.finishNode(node, "AwaitExpression")
};

View File

@@ -9,41 +9,9 @@
function makePredicate(words) {
words = words.split(" ")
let f = "", cats = []
out: for (let i = 0; i < words.length; ++i) {
for (let j = 0; j < cats.length; ++j)
if (cats[j][0].length == words[i].length) {
cats[j].push(words[i])
continue out
}
cats.push([words[i]])
return function(str) {
return words.indexOf(str) >= 0
}
function compareTo(arr) {
if (arr.length == 1) return f += "return str === " + JSON.stringify(arr[0]) + ";"
f += "switch(str){"
for (let i = 0; i < arr.length; ++i) f += "case " + JSON.stringify(arr[i]) + ":"
f += "return true}return false;"
}
// When there are more than three length categories, an outer
// switch first dispatches on the lengths, to save on comparisons.
if (cats.length > 3) {
cats.sort((a, b) => b.length - a.length)
f += "switch(str.length){"
for (let i = 0; i < cats.length; ++i) {
let cat = cats[i]
f += "case " + cat[0].length + ":"
compareTo(cat)
}
f += "}"
// Otherwise, simply generate a flat `switch` statement.
} else {
compareTo(words)
}
return new Function("str", f)
}
// Reserved word lists for various dialects of the language

View File

@@ -38,9 +38,6 @@ export {isIdentifierChar, isIdentifierStart} from "./identifier"
export {Token} from "./tokenize"
export {isNewLine, lineBreak, lineBreakG} from "./whitespace"
import "../plugins/flow";
import "../plugins/jsx";
export const version = "1.0.0"
// The main exported interface (under `self.acorn` when in the

View File

@@ -18,17 +18,19 @@ var STATE_KEYS = [
];
pp.getState = function () {
var state = {};
var state = {}
for (var i = 0; i < STATE_KEYS.length; i++) {
var key = STATE_KEYS[i];
state[key] = this[key];
var key = STATE_KEYS[i]
state[key] = this[key]
}
return state;
return state
};
pp.lookahead = function() {
var old = this.getState();
this.next();
this.isLookahead = true
this.next()
this.isLookahead = false
var curr = this.getState();
for (var key in old) this[key] = old[key];
return curr;

View File

@@ -21,6 +21,7 @@ pp.toAssignable = function(node, isBinding) {
node.type = "ObjectPattern"
for (let i = 0; i < node.properties.length; i++) {
let prop = node.properties[i]
if (prop.type === "SpreadProperty") continue;
if (prop.kind !== "init") this.raise(prop.key.start, "Object pattern can't contain getter or setter")
this.toAssignable(prop.value, isBinding)
}
@@ -125,7 +126,9 @@ pp.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
this.expect(close)
break
} else {
elts.push(this.parseAssignableListItemTypes(this.parseMaybeDefault()))
var left = this.parseMaybeDefault()
this.parseAssignableListItemTypes(left)
elts.push(this.parseMaybeDefault(null, left))
}
}
return elts

View File

@@ -46,6 +46,9 @@ export function Parser(options, input, startPos) {
this.inModule = this.options.sourceType === "module"
this.strict = this.options.strictMode === false ? false : this.inModule
// Used to signify the start of a potential arrow function
this.potentialArrowAt = -1
// Flags to track whether we are in a function, a generator.
this.inFunction = this.inGenerator = false
// Labels in scope.

View File

@@ -458,7 +458,7 @@ pp.parseFunction = function(node, isStatement, allowExpressionBody, isAsync) {
pp.parseFunctionParams = function(node) {
this.expect(tt.parenL)
node.params = this.parseBindingList(tt.parenR, false, false)
node.params = this.parseBindingList(tt.parenR, false, this.options.features["es7.trailingFunctionCommas"])
}
// Parse a class declaration or literal (depending on the
@@ -471,14 +471,18 @@ pp.parseClass = function(node, isStatement) {
var classBody = this.startNode()
classBody.body = []
this.expect(tt.braceL)
let decorators = []
while (!this.eat(tt.braceR)) {
if (this.eat(tt.semi)) continue
if (this.type === tt.at) {
this.decorators.push(this.parseDecorator())
continue;
decorators.push(this.parseDecorator())
continue
}
var method = this.startNode()
this.takeDecorators(method)
if (decorators.length) {
method.decorators = decorators
decorators = []
}
var isGenerator = this.eat(tt.star), isAsync = false
this.parsePropertyName(method)
if (this.type !== tt.parenL && !method.computed && method.key.type === "Identifier" &&
@@ -500,7 +504,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
@@ -517,7 +521,7 @@ pp.parseClass = function(node, isStatement) {
}
this.parseClassMethod(classBody, method, isGenerator, isAsync)
}
if (this.decorators.length) {
if (decorators.length) {
this.raise(this.start, "You have trailing decorators with no method");
}
node.body = this.finishNode(classBody, "ClassBody")
@@ -687,7 +691,6 @@ pp.parseImport = function(node) {
if (this.type === tt.string) {
node.specifiers = empty
node.source = this.parseExprAtom()
node.kind = ""
} else {
node.specifiers = []
this.parseImportSpecifiers(node)

View File

@@ -28,7 +28,7 @@ const pp = Parser.prototype
// Move to the next token
pp.next = function() {
if (this.options.onToken)
if (this.options.onToken && !this.isLookahead)
this.options.onToken(new Token(this))
this.lastTokEnd = this.end

View File

@@ -116,7 +116,7 @@ kw("do", {isLoop: true})
kw("else", beforeExpr)
kw("finally")
kw("for", {isLoop: true})
kw("function")
kw("function", startsExpr)
kw("if")
kw("return", beforeExpr)
kw("switch")

View File

@@ -1,3 +1,4 @@
require("./node");
var transform = module.exports = require("../transformation");
transform.options = require("../transformation/file/options");
@@ -11,7 +12,7 @@ transform.run = function (code, opts = {}) {
};
transform.load = function (url, callback, opts = {}, hold) {
opts.filename ||= url;
opts.filename = opts.filename || url;
var xhr = global.ActiveXObject ? new global.ActiveXObject("Microsoft.XMLHTTP") : new global.XMLHttpRequest();
xhr.open("GET", url, true);

View File

@@ -4,12 +4,13 @@ import * as acorn from "../../acorn";
import * as util from "../util";
import fs from "fs";
export { util, acorn };
export { util, acorn, transform };
export { pipeline } from "../transformation";
export { canCompile } from "../util";
export { default as options } from "../transformation/file/options";
export { default as Transformer } from "../transformation/transformer";
export { default as transform } from "../transformation";
export { default as TransformerPipeline } from "../transformation/transformer-pipeline";
export { default as traverse } from "../traversal";
export { default as buildExternalHelpers } from "../tools/build-external-helpers";
export { version } from "../../../package";
@@ -18,7 +19,7 @@ import * as t from "../types";
export { t as types };
export function register(opts?: Object) {
var callback = require("./register/node");
var callback = require("./register/node-polyfill");
if (opts != null) callback(opts);
return callback;
}
@@ -52,5 +53,22 @@ export function transformFile(filename: string, opts?: Object, callback: Functio
export function transformFileSync(filename: string, opts?: Object = {}) {
opts.filename = filename;
return transform(fs.readFileSync(filename), opts);
return transform(fs.readFileSync(filename, "utf8"), opts);
}
export function parse(code, opts = {}) {
opts.allowHashBang = true;
opts.sourceType = "module";
opts.ecmaVersion = Infinity;
opts.plugins = {
flow: true,
jsx: true
};
opts.features = {};
for (var key in transform.pipeline.transformers) {
opts.features[key] = true;
}
return acorn.parse(code, opts);
}

View File

@@ -1,12 +1,9 @@
import path from "path";
import os from "os";
import fs from "fs";
import userHome from "user-home";
function getUserHome() {
return process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
}
const FILENAME = process.env.BABEL_CACHE_PATH || path.join(getUserHome() || os.tmpdir(), ".babel.json");
const FILENAME = process.env.BABEL_CACHE_PATH || path.join(userHome || os.tmpdir(), ".babel.json");
var data = {};
export function save() {

View File

@@ -0,0 +1,2 @@
import "../../polyfill";
export { default } from "./node";

View File

@@ -1,4 +1,3 @@
import "../../polyfill";
import sourceMapSupport from "source-map-support";
import * as registerCache from "./cache";
import resolveRc from "../../tools/resolve-rc";
@@ -7,6 +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";
sourceMapSupport.install({
handleUncaughtExceptions: false,
@@ -31,8 +31,10 @@ var cache = registerCache.get();
//
var transformOpts = {};
var ignoreRegex = /node_modules/;
var onlyRegex;
var ignore;
var only;
var oldHandlers = {};
var maps = {};
@@ -76,12 +78,16 @@ var compile = function (filename) {
};
var shouldIgnore = function (filename) {
return (ignoreRegex && ignoreRegex.test(filename)) || (onlyRegex && !onlyRegex.test(filename));
if (!ignore && !only) {
return /node_modules/.test(filename);
} else {
return util.shouldIgnore(filename, ignore || [], only || []);
}
};
var istanbulMonkey = {};
if (process.env.running_under_istanbul) { // jshint ignore:line
if (process.env.running_under_istanbul) {
// we need to monkey patch fs.readFileSync so we can hook into
// what istanbul gets, it's extremely dirty but it's the only way
var _readFileSync = fs.readFileSync;
@@ -111,7 +117,7 @@ var registerExtension = function (ext) {
var old = oldHandlers[ext] || oldHandlers[".js"];
var loader = normalLoader;
if (process.env.running_under_istanbul) loader = istanbulLoader; // jshint ignore:line
if (process.env.running_under_istanbul) loader = istanbulLoader;
require.extensions[ext] = function (m, filename) {
if (shouldIgnore(filename)) {
@@ -142,8 +148,8 @@ var hookExtensions = function (_exts) {
hookExtensions(util.canCompile.EXTENSIONS);
export default function (opts = {}) {
if (opts.only != null) onlyRegex = util.regexify(opts.only);
if (opts.ignore != null) ignoreRegex = util.regexify(opts.ignore);
if (opts.only != null) only = util.arrayify(opts.only, util.regexify);
if (opts.ignore != null) ignore = util.arrayify(opts.ignore, util.regexify);
if (opts.extensions) hookExtensions(util.arrayify(opts.extensions));
@@ -156,16 +162,3 @@ export default function (opts = {}) {
extend(transformOpts, opts);
};
//
try {
var runtimePackage = require("babel-runtime/package");
var version = require("../../../../package").version;
if (runtimePackage.version !== version) {
throw new ReferenceError(`The verison of babel-runtime of ${runtimePackage.runtime} that you have installed does not match the babel verison of ${version}`);
}
} catch (err) {
if (err.code !== "MODULE_NOT_FOUND") throw err;
}

View File

@@ -70,14 +70,14 @@ export default class Buffer {
}
newline(i, removeLast) {
if (this.format.compact) return;
if (this.format.compact || this.format.retainLines) return;
if (this.format.concise) {
this.space();
return;
}
removeLast ||= false;
removeLast = removeLast || false;
if (isNumber(i)) {
i = Math.min(2, i);

View File

@@ -13,7 +13,7 @@ export function BlockStatement(node, print) {
this.push("{");
this.newline();
print.sequence(node.body, { indent: true });
this.removeLast("\n");
if (!this.format.retainLines) this.removeLast("\n");
this.rightBrace();
}
}

View File

@@ -169,4 +169,8 @@ export function MemberExpression(node, print) {
}
}
export { MemberExpression as MetaProperty };
export function MetaProperty(node, print) {
print(node.meta);
this.push(".");
print(node.property);
}

View File

@@ -45,7 +45,7 @@ export function JSXElement(node, print) {
this.indent();
each(node.children, (child) => {
if (t.isLiteral(child)) {
this.push(child.value);
this.push(child.value, true);
} else {
print(child);
}

View File

@@ -75,5 +75,16 @@ export function ArrowFunctionExpression(node, print) {
}
this.push(" => ");
const bodyNeedsParens = t.isObjectExpression(node.body);
if (bodyNeedsParens) {
this.push("(");
}
print(node.body);
if (bodyNeedsParens) {
this.push(")");
}
}

View File

@@ -71,7 +71,7 @@ export var ForInStatement = buildForXStatement("in");
export var ForOfStatement = buildForXStatement("of");
export function DoWhileStatement(node, print) {
this.keyword("do");
this.push("do ");
print(node.body);
this.space();
this.keyword("while");
@@ -191,7 +191,7 @@ export function VariableDeclaration(node, print, parent) {
}
var sep = ",";
if (!this.format.compact && hasInits) {
if (!this.format.compact && hasInits && !this.format.retainLines) {
sep += `\n${repeating(" ", node.kind.length + 1)}`;
} else {
sep += " ";

View File

@@ -12,7 +12,7 @@ import * as t from "../types";
class CodeGenerator {
constructor(ast, opts, code) {
opts ||= {};
opts = opts || {};
this.comments = ast.comments || [];
this.tokens = ast.tokens || [];
@@ -34,9 +34,10 @@ class CodeGenerator {
}
var format = {
retainLines: opts.retainLines,
comments: opts.comments == null || opts.comments,
compact: opts.compact,
quotes: CodeGenerator.findCommonStringDelimeter(code, tokens),
quotes: CodeGenerator.findCommonStringDelimiter(code, tokens),
indent: {
adjustMultilineComment: true,
style: style,
@@ -48,14 +49,14 @@ class CodeGenerator {
format.compact = code.length > 100000; // 100KB
if (format.compact) {
console.error(messages.get("codeGeneratorDeopt", opts.filename, "100KB"));
console.error("[BABEL] " + messages.get("codeGeneratorDeopt", opts.filename, "100KB"));
}
}
return format;
}
static findCommonStringDelimeter(code, tokens) {
static findCommonStringDelimiter(code, tokens) {
var occurences = {
single: 0,
double: 0
@@ -146,6 +147,22 @@ class CodeGenerator {
return print;
}
catchUp(node, parent) {
// 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)) {
needsParens = true;
this._push("(");
}
while (this.position.line < node.loc.start.line) {
this._push("\n");
}
return needsParens;
}
return false;
}
print(node, parent, opts = {}) {
if (!node) return;
@@ -197,6 +214,8 @@ class CodeGenerator {
this.printLeadingComments(node, parent);
var needsParensFromCatchup = this.catchUp(node, parent);
newline(true);
if (opts.before) opts.before();
@@ -208,19 +227,19 @@ class CodeGenerator {
this.newline();
this.dedent();
}
if (needsParens) this.push(")");
if (needsParens || needsParensFromCatchup) this.push(")");
this.map.mark(node, "end");
if (opts.after) opts.after();
this.format.concise = oldConcise;
newline(false);
this.printTrailingComments(node, parent);
} else {
throw new ReferenceError(`unknown node of type ${JSON.stringify(node.type)} with constructor ${JSON.stringify(node && node.constructor.name)}`);
}
this.format.concise = oldConcise;
}
printJoin(print, nodes, opts = {}) {
@@ -328,6 +347,8 @@ class CodeGenerator {
if (skip) return;
this.catchUp(comment);
// whitespace before
this.newline(this.whitespace.getNewlinesBefore(comment));
@@ -340,7 +361,6 @@ class CodeGenerator {
}
//
if (comment.type === "Block" && this.format.indent.adjustMultilineComment) {
var offset = comment.loc.start.column;
if (offset) {
@@ -356,8 +376,13 @@ class CodeGenerator {
val = this.getIndent() + val;
}
//
// 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") {
val += "\n";
}
//
this._push(val);
// whitespace after

View File

@@ -85,16 +85,7 @@ export default class Node {
return false;
}
if (t.isYieldExpression(parent) || t.isAwaitExpression(parent)) {
return true;
}
if (t.isContinueStatement(parent) || t.isBreakStatement(parent) ||
t.isReturnStatement(parent) || t.isThrowStatement(parent)) {
return true;
}
return false;
return t.isTerminatorless(parent);
}
}

View File

@@ -171,4 +171,10 @@ export function ConditionalExpression(node, parent) {
return false;
}
export { ConditionalExpression as AssignmentExpression };
export function AssignmentExpression(node) {
if (t.isObjectPattern(node.left)) {
return true;
} else {
return ConditionalExpression(...arguments);
}
}

View File

@@ -16,7 +16,7 @@ function crawl(node, state = {}) {
} else if (t.isFunction(node)) {
state.hasFunction = true;
} else if (t.isIdentifier(node)) {
state.hasHelper ||= isHelper(node.callee);
state.hasHelper = state.hasHelper || isHelper(node.callee);
}
return state;

View File

@@ -1,65 +1,34 @@
import normalizeAst from "./normalize-ast";
import estraverse from "estraverse";
import codeFrame from "./code-frame";
import * as acorn from "../../acorn";
export default function (opts, code, callback) {
try {
var comments = [];
var tokens = [];
export default function (code, opts = {}) {
var comments = [];
var tokens = [];
var parseOpts = {
allowImportExportEverywhere: opts.looseModules,
allowReturnOutsideFunction: opts.looseModules,
ecmaVersion: 6,
strictMode: opts.strictMode,
sourceType: opts.sourceType,
onComment: comments,
locations: true,
features: opts.features || {},
plugins: opts.plugins || {},
onToken: tokens,
ranges: true
};
var parseOpts = {
allowImportExportEverywhere: opts.looseModules,
allowReturnOutsideFunction: opts.looseModules,
allowHashBang: true,
ecmaVersion: 6,
strictMode: opts.strictMode,
sourceType: opts.sourceType,
locations: true,
onComment: comments,
features: opts.features || {},
plugins: opts.plugins || {},
onToken: tokens,
ranges: true
};
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);
if (callback) {
return callback(ast);
} else {
return ast;
}
} catch (err) {
if (!err._babel) {
err._babel = true;
var message = err.message = `${opts.filename}: ${err.message}`;
var loc = err.loc;
if (loc) {
err.codeFrame = codeFrame(code, loc.line, loc.column + 1, opts);
message += "\n" + err.codeFrame;
}
if (err.stack) {
var newStack = err.stack.replace(err.message, message);
try {
err.stack = newStack;
} catch (e) {
// `err.stack` may be a readonly property in some environments
}
}
}
throw err;
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);
return ast;
}

View File

@@ -22,7 +22,21 @@ export const MESSAGES = {
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"
illegalMethodName: "Illegal method name $1",
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: "You passed \`traverse()\` a visitor object with the key $1 that's a `Function` instead of `{ enter: Function }`. You need to normalise your visitor 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",
pluginKeyCollision: "The plugin $1 collides with another of the same name",
pluginNotTransformer: "The plugin $1 didn't export a Transformer instance",
pluginUnknown: "Unknown plugin $1",
transformerNotFile: "Transformer $1 is resolving to a different Babel version to what is doing the actual transformation..."
};
export function get(key: String, ...args) {

View File

@@ -7,15 +7,15 @@ import * as t from "./types";
extend(estraverse.VisitorKeys, t.VISITOR_KEYS);
// regenerator-babel/ast-types
// regenerator/ast-types
var def = types.Type.def;
var or = types.Type.or;
def("File")
.bases("Node")
.build("program")
.field("program", def("Program"));
//def("File")
// .bases("Node")
// .build("program")
// .field("program", def("Program"));
def("AssignmentPattern")
.bases("Pattern")
@@ -33,6 +33,9 @@ def("DoExpression")
.build("body")
.field("body", [def("Statement")]);
def("Super")
.bases("Expression");
def("ExportDefaultDeclaration")
.bases("Declaration")
.build("declaration")
@@ -55,4 +58,18 @@ def("ExportNamedDeclaration")
)])
.field("source", or(def("ModuleSpecifier"), null));
def("ExportNamespaceSpecifier")
.bases("Specifier")
.field("exported", def("Identifier"));
def("ExportDefaultSpecifier")
.bases("Specifier")
.field("exported", def("Identifier"));
def("ExportAllDeclaration")
.bases("Declaration")
.build("exported", "source")
.field("exported", def("Identifier"))
.field("source", def("Literal"));
types.finalize();

View File

@@ -4,4 +4,4 @@ if (global._babelPolyfill) {
global._babelPolyfill = true;
import "core-js/shim";
import "regenerator-babel/runtime";
import "regenerator/runtime";

View File

@@ -1,3 +1,4 @@
import stripJsonComments from "strip-json-comments";
import merge from "lodash/object/merge";
import path from "path";
import fs from "fs";
@@ -16,24 +17,40 @@ function exists(filename) {
export default function (loc, opts = {}) {
var rel = ".babelrc";
if (!opts.babelrc) {
opts.babelrc = [];
}
function find(start, rel) {
var file = path.join(start, rel);
if (opts.babelrc.indexOf(file) >= 0) {
return;
}
if (exists(file)) {
var content = fs.readFileSync(file, "utf8");
var json;
try {
json = jsons[content] ||= JSON.parse(content);
json = jsons[content] = jsons[content] || JSON.parse(stripJsonComments(content));
} catch (err) {
err.message = `${file}: ${err.message}`;
throw err;
}
opts.babelrc.push(file);
if (json.breakConfig) return;
merge(opts, json, function(a, b) {
if (Array.isArray(a)) {
return a.concat(b);
var c = a.slice(0);
for (var v of b) {
if (a.indexOf(v) < 0) {
c.push(v);
}
}
return c;
}
});
}
@@ -43,11 +60,10 @@ export default function (loc, opts = {}) {
find(up, rel);
}
}
if (opts.breakConfig !== true) {
if (opts.babelrc.indexOf(loc) < 0 && opts.breakConfig !== true) {
find(loc, rel);
}
return opts;
};

View File

@@ -1,5 +1,7 @@
import convertSourceMap from "convert-source-map";
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 isFunction from "lodash/lang/isFunction";
@@ -8,6 +10,7 @@ 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";
import includes from "lodash/collection/includes";
import traverse from "../../traversal";
@@ -16,40 +19,42 @@ import Logger from "./logger";
import parse from "../../helpers/parse";
import Scope from "../../traversal/scope";
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 = {
enter(node, parent, scope, state) {
checkNode(state.stack, node, scope);
exit(node, parent, scope, state) {
checkPath(state.stack, this);
}
};
function checkNode(stack, node, scope) {
function checkPath(stack, path) {
each(stack, function (pass) {
if (pass.shouldRun || pass.ran) return;
pass.checkNode(node, scope);
pass.checkPath(path);
});
}
export default class File {
constructor(opts = {}) {
this.dynamicImportedNoDefault = [];
this.dynamicImportIds = {};
this.dynamicImported = [];
this.dynamicImports = [];
constructor(opts = {}, pipeline) {
this.dynamicImportTypes = {};
this.dynamicImportIds = {};
this.dynamicImports = [];
this.usedHelpers = {};
this.dynamicData = {};
this.data = {};
this.uids = {};
this.declarations = {};
this.usedHelpers = {};
this.dynamicData = {};
this.data = {};
this.uids = {};
this.lastStatements = [];
this.log = new Logger(this, opts.filename || "unknown");
this.opts = this.normalizeOptions(opts);
this.ast = {};
this.pipeline = pipeline;
this.log = new Logger(this, opts.filename || "unknown");
this.opts = this.normalizeOptions(opts);
this.ast = {};
this.buildTransformers();
}
@@ -59,9 +64,10 @@ export default class File {
"defaults",
"create-class",
"create-decorated-class",
"create-decorated-object",
"define-decorated-property-descriptor",
"tagged-template-literal",
"tagged-template-literal-loose",
"interop-require",
"to-array",
"to-consumable-array",
"sliced-to-array",
@@ -73,6 +79,7 @@ export default class File {
"define-property",
"async-to-generator",
"interop-require-wildcard",
"interop-require-default",
"typeof",
"extends",
"get",
@@ -82,7 +89,16 @@ export default class File {
"temporal-undefined",
"temporal-assert-defined",
"self-global",
"default-props"
"default-props",
"instanceof",
// legacy
"interop-require",
];
static soloHelpers = [
"ludicrous-proxy-create",
"ludicrous-proxy-directory"
];
static options = require("./options");
@@ -115,13 +131,15 @@ export default class File {
throw new Error("Deprecated option " + key + ": " + option.deprecated);
}
if (val == null) val = option.default || val;
if (val == null) {
val = clone(option.default);
}
var optionParser = optionParsers[option.type];
if (optionParser) val = optionParser(key, val);
if (optionParser) val = optionParser(key, val, this.pipeline);
if (option.alias) {
opts[option.alias] ||= val;
opts[option.alias] = opts[option.alias] || val;
} else {
opts[key] = val;
}
@@ -185,7 +203,7 @@ export default class File {
var stack = [];
// build internal transformers
each(transform.transformers, function (transformer, key) {
each(this.pipeline.transformers, function (transformer, key) {
var pass = transformers[key] = transformer.buildPass(file);
if (pass.canTransform()) {
@@ -204,8 +222,14 @@ export default class File {
// init plugins!
var beforePlugins = [];
var afterPlugins = [];
var pluginManager = new PluginManager({
file: this,
transformers: this.transformers,
before: beforePlugins,
after: afterPlugins
});
for (var i = 0; i < file.opts.plugins.length; i++) {
this.addPlugin(file.opts.plugins[i], beforePlugins, afterPlugins);
pluginManager.add(file.opts.plugins[i]);
}
stack = beforePlugins.concat(stack, afterPlugins);
@@ -213,99 +237,6 @@ export default class File {
this.transformerStack = stack.concat(secondaryStack);
}
getModuleFormatter(type: string) {
var ModuleFormatter = isFunction(type) ? type : transform.moduleFormatters[type];
if (!ModuleFormatter) {
var loc = util.resolveRelative(type);
if (loc) ModuleFormatter = require(loc);
}
if (!ModuleFormatter) {
throw new ReferenceError(`Unknown module formatter type ${JSON.stringify(type)}`);
}
return new ModuleFormatter(this);
}
addPlugin(name, before, after) {
var position = "before";
var plugin;
if (name) {
if (typeof name === "string") {
// this is a plugin in the form of "foobar" or "foobar:after"
// where the optional colon is the delimiter for plugin position in the transformer stack
[name, position = "before"] = name.split(":");
var loc = util.resolveRelative(name) || util.resolveRelative(`babel-plugin-${name}`);
if (loc) {
plugin = require(loc)
} else {
throw new ReferenceError(`Unknown plugin ${JSON.stringify(name)}`);
}
} else {
// not a string so we'll just assume that it's a direct Transformer instance, if not then
// the checks later on will complain
plugin = name;
}
} else {
throw new TypeError(`Ilegal kind ${typeof name} for plugin name ${JSON.stringify(name)}`);
}
// validate position
if (position !== "before" && position !== "after") {
throw new TypeError(`Plugin ${JSON.stringify(name)} has an illegal position of ${JSON.stringify(position)}`);
}
// validate transformer key
var key = plugin.key;
if (this.transformers[key]) {
throw new ReferenceError(`The key for plugin ${JSON.stringify(name)} of ${key} collides with an existing plugin`);
}
// validate Transformer instance
if (!plugin.buildPass || plugin.constructor.name !== "Transformer") {
throw new TypeError(`Plugin ${JSON.stringify(name)} didn't export default a Transformer instance`);
}
// build!
var pass = this.transformers[key] = plugin.buildPass(this);
if (pass.canTransform()) {
var stack = before;
if (position === "after") stack = after;
stack.push(pass);
}
}
parseInputSourceMap(code: string) {
var opts = this.opts;
if (opts.inputSourceMap !== false) {
var inputMap = convertSourceMap.fromSource(code);
if (inputMap) {
opts.inputSourceMap = inputMap.toObject();
code = convertSourceMap.removeComments(code);
}
}
return code;
}
parseShebang(code: string) {
var shebangMatch = shebangRegex.exec(code);
if (shebangMatch) {
this.shebang = shebangMatch[0];
// remove shebang
code = code.replace(shebangRegex, "");
}
return code;
}
set(key: string, val): any {
return this.data[key] = val;
};
@@ -332,8 +263,8 @@ export default class File {
return source;
}
addImport(source: string, name?: string, noDefault?: boolean): Object {
name ||= source;
addImport(source: string, name?: string, type?: string): Object {
name = name || source;
var id = this.dynamicImportIds[name];
if (!id) {
@@ -344,8 +275,10 @@ export default class File {
var declar = t.importDeclaration(specifiers, t.literal(source));
declar._blockHoist = 3;
this.dynamicImported.push(declar);
if (noDefault) this.dynamicImportedNoDefault.push(declar);
if (type) {
var modules = this.dynamicImportTypes[type] = this.dynamicImportTypes[type] || [];
modules.push(declar);
}
if (this.transformers["es6.modules"].canTransform()) {
this.moduleFormatter.importSpecifier(specifiers[0], declar, this.dynamicImports);
@@ -358,14 +291,10 @@ export default class File {
return id;
}
isConsequenceExpressionStatement(node: Object): boolean {
return t.isExpressionStatement(node) && this.lastStatements.indexOf(node) >= 0;
}
attachAuxiliaryComment(node: Object): Object {
var comment = this.opts.auxiliaryComment;
if (comment) {
node.leadingComments ||= [];
node.leadingComments = node.leadingComments || [];
node.leadingComments.push({
type: "Line",
value: " " + comment
@@ -375,35 +304,51 @@ export default class File {
}
addHelper(name: string): Object {
if (!includes(File.helpers, name)) {
var isSolo = includes(File.soloHelpers, name);
if (!isSolo && !includes(File.helpers, name)) {
throw new ReferenceError(`Unknown helper ${name}`);
}
var program = this.ast.program;
var declar = program._declarations && program._declarations[name];
if (declar) return declar.id;
var declar = this.declarations[name];
if (declar) return declar;
this.usedHelpers[name] = true;
var generator = this.get("helperGenerator");
var runtime = this.get("helpersNamespace");
if (generator) {
return generator(name);
} else if (runtime) {
var id = t.identifier(t.toIdentifier(name));
return t.memberExpression(runtime, id);
} else {
var ref = util.template("helper-" + name);
ref._compact = true;
var uid = this.scope.generateUidIdentifier(name);
this.scope.push({
key: name,
id: uid,
init: ref
});
return uid;
if (!isSolo) {
var generator = this.get("helperGenerator");
var runtime = this.get("helpersNamespace");
if (generator) {
return generator(name);
} else if (runtime) {
var id = t.identifier(t.toIdentifier(name));
return t.memberExpression(runtime, id);
}
}
var ref = util.template("helper-" + name);
var uid = this.declarations[name] = this.scope.generateUidIdentifier(name);
if (t.isFunctionExpression(ref) && !ref.id) {
ref.body._compact = true;
ref._generated = true;
ref.id = uid;
ref.type = "FunctionDeclaration";
this.attachAuxiliaryComment(ref);
this.path.unshiftContainer("body", ref);
} else {
ref._compact = true;
this.scope.push({
id: uid,
init: ref,
unique: true
});
}
return uid;
}
errorWithNode(node, msg, Error = SyntaxError) {
@@ -413,137 +358,19 @@ export default class File {
return err;
}
addCode(code: string) {
code = (code || "") + "";
code = this.parseInputSourceMap(code);
this.code = code;
return this.parseShebang(code);
}
shouldIgnore() {
var opts = this.opts;
var filename = opts.filename;
var ignore = opts.ignore;
var only = opts.only;
if (only.length) {
for (var i = 0; i < only.length; i++) {
if (only[i].test(filename)) return false;
}
return true;
} else if (ignore.length) {
for (var i = 0; i < ignore.length; i++) {
if (ignore[i].test(filename)) return true;
}
}
return false;
}
parse(code: string) {
if (this.shouldIgnore()) {
return {
metadata: {},
code: code,
map: null,
ast: null
};
}
code = this.addCode(code);
var opts = this.opts;
//
var parseOpts = {
highlightCode: opts.highlightCode,
nonStandard: opts.nonStandard,
filename: opts.filename,
plugins: {}
};
var features = parseOpts.features = {};
for (var key in this.transformers) {
var transformer = this.transformers[key];
features[key] = transformer.canTransform();
}
parseOpts.looseModules = this.isLoose("es6.modules");
parseOpts.strictMode = features.strict;
parseOpts.sourceType = "module";
//
return parse(parseOpts, code, (tree) => {
this.transform(tree);
return this.generate();
});
}
setAst(ast) {
this.path = TraversalPath.get(null, null, ast, ast, "program", 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();
}
}
}
});
}
transform(ast) {
this.log.debug();
this.setAst(ast);
this.lastStatements = t.getLastStatements(ast.program);
var modFormatter = this.moduleFormatter = this.getModuleFormatter(this.opts.modules);
if (modFormatter.init && this.transformers["es6.modules"].canTransform()) {
modFormatter.init();
}
this.checkNode(ast);
this.call("pre");
each(this.transformerStack, function (pass) {
pass.transform();
});
this.call("post");
}
call(key: string) {
var stack = this.transformerStack;
for (var i = 0; i < stack.length; i++) {
var transformer = stack[i].transformer;
var fn = transformer[key];
if (fn) fn(this);
}
}
checkNode(node, scope) {
if (Array.isArray(node)) {
for (var i = 0; i < node.length; i++) {
this.checkNode(node[i], scope);
checkPath(path) {
if (Array.isArray(path)) {
for (var i = 0; i < path.length; i++) {
this.checkPath(path[i]);
}
return;
}
var stack = this.transformerStack;
scope ||= this.scope;
checkNode(stack, node, scope);
checkPath(stack, path);
scope.traverse(node, checkTransformerVisitor, {
path.traverse(checkTransformerVisitor, {
stack: stack
});
}
@@ -570,6 +397,180 @@ export default class File {
return map;
}
getModuleFormatter(type: string) {
var ModuleFormatter = isFunction(type) ? type : moduleFormatters[type];
if (!ModuleFormatter) {
var loc = util.resolveRelative(type);
if (loc) ModuleFormatter = require(loc);
}
if (!ModuleFormatter) {
throw new ReferenceError(`Unknown module formatter type ${JSON.stringify(type)}`);
}
return new ModuleFormatter(this);
}
parse(code: string) {
var opts = this.opts;
//
var parseOpts = {
highlightCode: opts.highlightCode,
nonStandard: opts.nonStandard,
filename: opts.filename,
plugins: {}
};
var features = parseOpts.features = {};
for (var key in this.transformers) {
var transformer = this.transformers[key];
features[key] = transformer.canTransform();
}
parseOpts.looseModules = this.isLoose("es6.modules");
parseOpts.strictMode = features.strict;
parseOpts.sourceType = "module";
this.log.debug("Parse start");
var tree = parse(code, parseOpts);
this.log.debug("Parse stop");
return tree;
}
_addAst(ast) {
this.path = TraversalPath.get(null, null, ast, ast, "program", 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) {
this.log.debug("Start set AST");
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.log.debug("End module formatter init");
this.call("pre");
each(this.transformerStack, function (pass) {
pass.transform();
});
this.call("post");
}
wrap(code, callback) {
code = code + "";
try {
if (this.shouldIgnore()) {
return {
metadata: {},
code: code,
map: null,
ast: null
};
}
callback();
return this.generate();
} catch (err) {
if (err._babel) {
throw err;
} else {
err._babel = true;
}
var message = err.message = `${this.opts.filename}: ${err.message}`;
var loc = err.loc;
if (loc) {
err.codeFrame = codeFrame(code, loc.line, loc.column + 1, this.opts);
message += "\n" + err.codeFrame;
}
if (err.stack) {
var newStack = err.stack.replace(err.message, message);
try {
err.stack = newStack;
} catch (e) {
// `err.stack` may be a readonly property in some environments
}
}
throw err;
}
}
addCode(code: string, parseCode?) {
code = (code || "") + "";
code = this.parseInputSourceMap(code);
this.code = code;
if (parseCode) {
this.parseShebang();
this.addAst(this.parse(this.code));
}
}
shouldIgnore() {
var opts = this.opts;
return util.shouldIgnore(opts.filename, opts.ignore, opts.only);
}
call(key: string) {
var stack = this.transformerStack;
for (var i = 0; i < stack.length; i++) {
var transformer = stack[i].transformer;
var fn = transformer[key];
if (fn) fn(this);
}
}
parseInputSourceMap(code: string) {
var opts = this.opts;
if (opts.inputSourceMap !== false) {
var inputMap = convertSourceMap.fromSource(code);
if (inputMap) {
opts.inputSourceMap = inputMap.toObject();
code = convertSourceMap.removeComments(code);
}
}
return code;
}
parseShebang() {
var shebangMatch = shebangRegex.exec(this.code);
if (shebangMatch) {
this.shebang = shebangMatch[0];
this.code = this.code.replace(shebangRegex, "");
}
}
generate(): {
usedHelpers?: Array<string>;
code: string;
@@ -593,10 +594,14 @@ export default class File {
if (opts.ast) result.ast = ast;
if (!opts.code) return result;
this.log.debug("Generation start");
var _result = generate(ast, opts, this.code);
result.code = _result.code;
result.map = _result.map;
this.log.debug("Generation end");
if (this.shebang) {
// add back shebang
result.code = `${this.shebang}\n${result.code}`;

View File

@@ -7,7 +7,7 @@ export default class Logger {
}
_buildMessage(msg: string): string {
var parts = this.filename;
var parts = `[BABEL] ${this.filename}`;
if (msg) parts += `: ${msg}`;
return parts;
}
@@ -18,7 +18,7 @@ export default class Logger {
deprecate(msg) {
if (!this.file.opts.suppressDeprecationMessages) {
console.error(msg);
console.error(this._buildMessage(msg));
}
}

View File

@@ -1,14 +1,13 @@
import transform from "./../index";
import * as util from "../../util";
export function transformerList(key, val) {
export function transformerList(key, val, pipeline) {
val = util.arrayify(val);
if (val.indexOf("all") >= 0 || val.indexOf(true) >= 0) {
val = Object.keys(transform.transformers);
val = Object.keys(pipeline.transformers);
}
return transform._ensureTransformerNames(key, val);
return pipeline._ensureTransformerNames(key, val);
}
export function number(key, val) {

View File

@@ -15,11 +15,26 @@
"hidden": true
},
"extra": {
"hidden": true,
"default": {}
},
"moduleId": {
"description": "specify a custom name for module ids",
"type": "string"
},
"getModuleId": {
"hidden": true
},
"retainLines": {
"type": "boolean",
"default": false,
"description": "retain line numbers - will result in really ugly code"
},
"nonStandard": {
"type": "boolean",
"default": true,
@@ -152,7 +167,7 @@
},
"externalHelpers": {
"type": "string",
"type": "boolean",
"default": false,
"shorthand": "r",
"description": "uses a reference to `babelHelpers` instead of placing helpers at the top of your code."
@@ -201,6 +216,10 @@
"default": false,
"hidden": true,
"description": "stop trying to load .babelrc files"
}
},
"babelrc": {
"hidden": true,
"description": "do not load the same .babelrc file twice"
}
}

View File

@@ -0,0 +1,108 @@
import * as node from "../../api/node";
import * as messages from "../../messages";
import * as util from "../../util";
export default class PluginManager {
static memoisedPlugins = [];
static memoisePluginContainer(fn) {
for (var i = 0; i < PluginManager.memoisedPlugins.length; i++) {
var plugin = PluginManager.memoisedPlugins[i];
if (plugin.container === fn) return plugin.transformer;
}
var transformer = fn(node);
PluginManager.memoisedPlugins.push({
container: fn,
transformer: transformer
});
return transformer;
}
static positions = ["before", "after"];
constructor({ file, transformers, before, after } = { transformers: {}, before: [], after: [] }) {
this.transformers = transformers;
this.file = file;
this.before = before;
this.after = after;
}
subnormaliseString(name, position) {
// this is a plugin in the form of "foobar" or "foobar:after"
// where the optional colon is the delimiter for plugin position in the transformer stack
var match = name.match(/^(.*?):(after|before)$/);
if (match) [, name, position] = match;
var loc = util.resolveRelative(name) || util.resolveRelative(`babel-plugin-${name}`);
if (loc) {
return {
position: position,
plugin: require(loc)
};
} else {
throw new ReferenceError(messages.get("pluginUnknown", name));
}
}
validate(name, plugin) {
// validate transformer key
var key = plugin.key;
if (this.transformers[key]) {
throw new ReferenceError(messages.get("pluginKeyCollision", key));
}
// validate Transformer instance
if (!plugin.buildPass || plugin.constructor.name !== "Transformer") {
throw new TypeError(messages.get("pluginNotTransformer", name));
}
// register as a plugin
plugin.metadata.plugin = true;
}
add(name) {
var position;
var plugin;
if (name) {
if (typeof name === "object" && name.transformer) {
({ plugin: name, 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
plugin = name;
}
if (typeof name === "string") {
({ plugin, position } = this.subnormaliseString(name, position));
}
} else {
throw new TypeError(messages.get("pluginIllegalKind", typeof name, name));
}
// default position
position = position || "before";
// validate position
if (PluginManager.positions.indexOf(position) < 0) {
throw new TypeError(messages.get("pluginIllegalPosition", position, name));
}
// allow plugin containers to be specified so they don't have to manually require
if (typeof plugin === "function") {
plugin = PluginManager.memoisePluginContainer(plugin);
}
//
this.validate(name, plugin);
// build!
var pass = this.transformers[plugin.key] = plugin.buildPass(this.file);
if (pass.canTransform()) {
var stack = position === "before" ? this.before : this.after;
stack.push(pass);
}
}
}

View File

@@ -10,9 +10,13 @@ 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 (file.isConsequenceExpressionStatement(node)) return;
if (this.isCompletionRecord()) return;
var expr = node.expression;
if (!isAssignment(expr)) return;

View File

@@ -8,7 +8,7 @@ export default function (exports, opts) {
exports.ExpressionStatement = function (node, parent, scope, file) {
// hit the `AssignmentExpression` one below
if (file.isConsequenceExpressionStatement(node)) return;
if (this.isCompletionRecord()) return;
var expr = node.expression;
if (!opts.is(expr, file)) return;

View File

@@ -10,16 +10,16 @@ import * as react from "./react";
import * as t from "../../types";
export default function (exports, opts) {
exports.check = function (node) {
exports.shouldVisit = 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)) {
if (node.name === "this" && this.isReferenced()) {
return t.thisExpression();
} else if (esutils.keyword.isIdentifierName(node.name)) {
} else if (esutils.keyword.isIdentifierNameES6(node.name)) {
node.type = "Identifier";
} else {
return t.literal(node.name);
@@ -57,6 +57,8 @@ export default function (exports, opts) {
exports.JSXOpeningElement = {
exit(node, parent, scope, file) {
parent.children = react.buildChildren(parent);
var tagExpr = node.name;
var args = [];
@@ -144,10 +146,6 @@ export default function (exports, opts) {
};
exports.JSXElement = {
enter(node) {
node.children = react.buildChildren(node);
},
exit(node) {
var callExpr = node.openingElement;

View File

@@ -1,10 +1,33 @@
import traverse from "../../traversal";
import * as t from "../../types";
export default function (node) {
var container = t.functionExpression(null, [], node.body, node.generator, node.async);
container.shadow = true;
var visitor = {
enter(node, parent, scope, state) {
if (this.isThisExpression() || this.isReferencedIdentifier({ name: "arguments" })) {
state.found = true;
this.stop();
}
var call = t.callExpression(container, []);
if (this.isFunction()) {
this.skip();
}
}
};
export default function (node, scope) {
var container = t.functionExpression(null, [], node.body, node.generator, node.async);
var callee = container;
var args = [];
var state = { found: false };
scope.traverse(node, visitor, state);
if (state.found) {
callee = t.memberExpression(container, t.identifier("apply"));
args = [t.thisExpression(), t.identifier("arguments")];
}
var call = t.callExpression(callee, args);
if (node.generator) call = t.yieldExpression(call, true);
return t.returnStatement(call);

View File

@@ -4,17 +4,45 @@ import each from "lodash/collection/each";
import has from "lodash/object/has";
import * as t from "../../types";
export function push(mutatorMap, key, kind, computed, value) {
var alias = t.toKeyAlias({ computed }, key);
export function push(mutatorMap, node, kind, file) {
var alias = t.toKeyAlias(node);
//
var map = {};
if (has(mutatorMap, alias)) map = mutatorMap[alias];
mutatorMap[alias] = map;
map._key = key;
if (computed) map._computed = true;
//
map[kind] = value;
map._inherits = map._inherits || [];
map._inherits.push(node);
map._key = node.key;
if (node.computed) {
map._computed = true;
}
if (node.decorators) {
var decorators = map.decorators = map.decorators || t.arrayExpression([]);
decorators.elements = decorators.elements.concat(node.decorators.map(dec => dec.expression).reverse());
}
if (map.value || map.initializer) {
throw file.errorWithNode(node, "Key conflict with sibling node");
}
if (node.value) {
if (node.kind === "init") kind = "value";
if (node.kind === "get") kind = "get";
if (node.kind === "set") kind = "set";
t.inheritsComments(node.value, node);
map[kind] = node.value;
}
return map;
}
export function hasComputed(mutatorMap) {

View File

@@ -0,0 +1,37 @@
import * as t from "../../types";
export default function (decorators, scope) {
for (var i = 0; i < decorators.length; i++) {
var decorator = decorators[i];
var expression = decorator.expression;
if (!t.isMemberExpression(expression)) continue;
var temp = scope.generateMemoisedReference(expression.object);
var ref;
var nodes = [];
if (temp) {
ref = temp;
nodes.push(t.assignmentExpression("=", temp, expression.object));
} else {
ref = expression.object;
}
nodes.push(t.callExpression(
t.memberExpression(
t.memberExpression(ref, expression.property, expression.computed),
t.identifier("bind")
),
[ref]
));
if (nodes.length === 1) {
decorator.expression = nodes[0];
} else {
decorator.expression = t.sequenceExpression(nodes);
}
}
return decorators;
}

View File

@@ -20,26 +20,32 @@ var visitor = {
var wrap = function (state, method, id, scope) {
if (state.selfReference) {
var templateName = "property-method-assignment-wrapper";
if (method.generator) templateName += "-generator";
var template = util.template(templateName, {
FUNCTION: method,
FUNCTION_ID: id,
FUNCTION_KEY: scope.generateUidIdentifier(id.name)
});
if (scope.hasBinding(id.name)) {
// we can just munge the local binding
scope.rename(id.name);
} else {
// need to add a wrapper since we can't change the references
var templateName = "property-method-assignment-wrapper";
if (method.generator) templateName += "-generator";
var template = util.template(templateName, {
FUNCTION: method,
FUNCTION_ID: id,
FUNCTION_KEY: scope.generateUidIdentifier(id.name)
});
template.callee._skipModulesRemap = true;
// shim in dummy params to retain function arity, if you try to read the
// source then you'll get the original since it's proxied so it's all good
var params = template.callee.body.body[0].params;
for (var i = 0, len = getFunctionArity(method); i < len; i++) {
params.push(scope.generateUidIdentifier("x"));
// shim in dummy params to retain function arity, if you try to read the
// source then you'll get the original since it's proxied so it's all good
var params = template.callee.body.body[0].params;
for (var i = 0, len = getFunctionArity(method); i < len; i++) {
params.push(scope.generateUidIdentifier("x"));
}
return template;
}
return template;
} else {
method.id = id;
return method;
}
method.id = id;
};
var visit = function (node, name, scope) {
@@ -81,7 +87,7 @@ var visit = function (node, name, scope) {
// so we can safely just set the id and move along as it shadows the
// bound function id
}
} else {
} else if (state.outerDeclar || scope.hasGlobal(name)) {
scope.traverse(node, visitor, state);
}
@@ -95,19 +101,20 @@ export function custom(node, id, scope) {
export function property(node, file, scope) {
var key = t.toComputedKey(node, node.key);
if (!t.isLiteral(key)) return node; // we can't set a function id with this
if (!t.isLiteral(key)) return; // we can't set a function id with this
var name = t.toIdentifier(key.value);
if (name === "eval" || name === "arguments") name = "_" + name;
var id = t.identifier(name);
var method = node.value;
var state = visit(method, name, scope);
node.value = wrap(state, method, id, scope);
node.value = wrap(state, method, id, scope) || method;
}
export function bare(node, parent, scope) {
// has an `id` so we don't need to infer one
if (node.id) return node;
if (node.id) return;
var id;
if (t.isProperty(parent) && parent.kind === "init" && (!parent.computed || t.isLiteral(parent.key))) {
@@ -116,8 +123,17 @@ export function bare(node, parent, scope) {
} else if (t.isVariableDeclarator(parent)) {
// var foo = function () {};
id = parent.id;
if (t.isIdentifier(id)) {
var bindingInfo = scope.parent.getBinding(id.name);
if (bindingInfo && bindingInfo.constant && scope.getBinding(id.name) === bindingInfo) {
// always going to reference this method
node.id = id;
return;
}
}
} else {
return node;
return;
}
var name;

View File

@@ -34,9 +34,8 @@ function cleanJSXElementLiteralChild(child, args) {
var lines = child.value.split(/\r\n|\n|\r/);
var lastNonEmptyLine = 0;
var i;
for (i = 0; i < lines.length; i++) {
for (let i = 0; i < lines.length; i++) {
if (lines[i].match(/[^ \t]/)) {
lastNonEmptyLine = i;
}
@@ -44,7 +43,7 @@ function cleanJSXElementLiteralChild(child, args) {
var str = "";
for (i = 0; i < lines.length; i++) {
for (let i = 0; i < lines.length; i++) {
var line = lines[i];
var isFirstLine = i === 0;

View File

@@ -19,8 +19,8 @@ var awaitVisitor = {
var referenceVisitor = {
enter(node, parent, scope, state) {
var name = state.id.name;
if (t.isReferencedIdentifier(node, parent, { name: name }) && scope.bindingIdentifierEquals(name, state.id)) {
return state.ref ||= scope.generateUidIdentifier(name);
if (this.isReferencedIdentifier({ name: name }) && scope.bindingIdentifierEquals(name, state.id)) {
return state.ref = state.ref || scope.generateUidIdentifier(name);
}
}
};

View File

@@ -218,7 +218,7 @@ export default class ReplaceSupers {
return this.setSuperProperty(node.left.property, node.right, node.left.computed, getThisReference());
} else {
// super.age += 2; -> var _ref = super.age; super.age = _ref + 2;
ref ||= path.scope.generateUidIdentifier("ref");
ref = ref || path.scope.generateUidIdentifier("ref");
return [
t.variableDeclaration("var", [
t.variableDeclarator(ref, node.left)

View File

@@ -1,68 +1,34 @@
import normalizeAst from "../helpers/normalize-ast";
import Transformer from "./transformer";
import object from "../helpers/object";
import File from "./file";
import each from "lodash/collection/each";
import Pipeline from "./transformer-pipeline";
export default function transform(code: string, opts?: Object) {
var file = new File(opts);
return file.parse(code);
}
var pipeline = new Pipeline;
transform.fromAst = function (ast, code, opts) {
ast = normalizeAst(ast);
//
var file = new File(opts);
file.addCode(code);
file.transform(ast);
return file.generate();
};
import transformers from "./transformers";
pipeline.addTransformers(transformers);
transform._ensureTransformerNames = function (type: string, rawKeys: Array<string>) {
var keys = [];
//
for (var i = 0; i < rawKeys.length; i++) {
var key = rawKeys[i];
import deprecated from "./transformers/deprecated";
pipeline.addDeprecated(deprecated);
var deprecatedKey = transform.deprecatedTransformerMap[key];
var aliasKey = transform.aliasTransformerMap[key];
if (aliasKey) {
keys.push(aliasKey);
} else if (deprecatedKey) {
// deprecated key, remap it to the new one
console.error(`The transformer ${key} has been renamed to ${deprecatedKey}`);
rawKeys.push(deprecatedKey);
} else if (transform.transformers[key]) {
// valid key
keys.push(key);
} else if (transform.namespaces[key]) {
// namespace, append all transformers within this namespace
keys = keys.concat(transform.namespaces[key]);
} else {
// invalid key
throw new ReferenceError(`Unknown transformer ${key} specified in ${type}`);
}
}
//
return keys;
};
import aliases from "./transformers/aliases";
pipeline.addAliases(aliases);
transform.transformerNamespaces = object();
transform.transformers = object();
transform.namespaces = object();
//
transform.deprecatedTransformerMap = require("./transformers/deprecated");
transform.aliasTransformerMap = require("./transformers/aliases");
transform.moduleFormatters = require("./modules");
import * as filters from "./transformers/filters";
pipeline.addFilter(filters.internal);
pipeline.addFilter(filters.blacklist);
pipeline.addFilter(filters.whitelist);
pipeline.addFilter(filters.stage);
pipeline.addFilter(filters.optional);
import rawTransformers from "./transformers";
//
each(rawTransformers, function (transformer, key) {
var namespace = key.split(".")[0];
transform.namespaces[namespace] ||= [];
transform.namespaces[namespace].push(key);
transform.transformerNamespaces[key] = namespace;
transform.transformers[key] = new Transformer(key, transformer);
});
var transform = pipeline.transform.bind(pipeline);
transform.fromAst = pipeline.transformFromAst.bind(pipeline);
transform.pipeline = pipeline;
export default transform;

View File

@@ -5,63 +5,71 @@ import object from "../../helpers/object";
import * as util from "../../util";
import * as t from "../../types";
var remapVisitor = {
var remapVisitor = traverse.explode({
enter(node, parent, scope, formatter) {
if (node._skipModulesRemap) {
return this.skip();
}
},
Identifier(node, parent, scope, formatter) {
var remap = formatter.internalRemap[node.name];
if (this.isReferencedIdentifier() && remap) {
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;
AssignmentExpression: {
exit(node, parent, scope, formatter) {
if (!node._ignoreModulesRemap) {
var exported = formatter.getExport(node.left, scope);
if (exported) {
return formatter.remapExportAssignment(node, exported);
}
var nodes = [];
nodes.push(remapped);
var operator;
if (node.operator === "--") {
operator = "+";
} else { // "++"
operator = "-";
}
nodes.push(t.binaryExpression(operator, node.argument, t.literal(1)));
return t.sequenceExpression(nodes);
}
}
},
if (t.isAssignmentExpression(node)) {
var exported = formatter.getExport(node.left, scope);
if (exported) {
this.skip();
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());
formatter.bumpImportOccurences(node);
}
}
};
@@ -69,7 +77,7 @@ var importsVisitor = {
var exportsVisitor = traverse.explode({
ExportDeclaration: {
enter(node, parent, scope, formatter) {
formatter.hasLocalImports = true;
formatter.hasLocalExports = true;
var declar = this.get("declaration");
if (declar.isStatement()) {
@@ -96,29 +104,23 @@ var exportsVisitor = traverse.explode({
formatter.hasNonDefaultExports = true;
}
}
if (node.source) {
formatter.bumpImportOccurences(node);
}
}
}
});
export default class DefaultFormatter {
constructor(file) {
this.internalRemap = {};
this.defaultIds = object();
this.scope = file.scope;
this.file = file;
this.ids = object();
this.internalRemap = object();
this.defaultIds = object();
this.scope = file.scope;
this.file = file;
this.ids = object();
this.hasNonDefaultExports = false;
this.hasLocalExports = false;
this.hasLocalImports = false;
this.localImportOccurences = object();
this.localExports = object();
this.localImports = object();
@@ -126,6 +128,11 @@ export default class DefaultFormatter {
this.getLocalImports();
}
isModuleType(node, type) {
var modules = this.file.dynamicImportTypes[type];
return modules && modules.indexOf(node) >= 0;
}
transform() {
this.remapAssignments();
}
@@ -134,15 +141,6 @@ export default class DefaultFormatter {
return (t.isExportDefaultDeclaration(node) || t.isSpecifierDefault(node)) && !this.noInteropRequireExport && !this.hasNonDefaultExports;
}
bumpImportOccurences(node) {
var source = node.source.value;
var occurs = this.localImportOccurences;
occurs[source] ||= 0;
if (node.specifiers) {
occurs[source] += node.specifiers.length;
}
}
getLocalExports() {
this.file.path.traverse(exportsVisitor, this);
}
@@ -152,7 +150,7 @@ export default class DefaultFormatter {
}
remapAssignments() {
if (this.hasLocalImports) {
if (this.hasLocalExports || this.hasLocalImports) {
this.file.path.traverse(remapVisitor, this);
}
}
@@ -172,7 +170,7 @@ export default class DefaultFormatter {
}
_addExport(name, exported) {
var info = this.localExports[name] ||= {
var info = this.localExports[name] = this.localExports[name] || {
binding: this.scope.getBindingIdentifier(name),
exported: []
};
@@ -190,7 +188,10 @@ export default class DefaultFormatter {
getModuleName() {
var opts = this.file.opts;
if (opts.moduleId) return opts.moduleId;
// moduleId is n/a if a `getModuleId()` is provided
if (opts.moduleId && !opts.getModuleId) {
return opts.moduleId;
}
var filenameRelative = opts.filenameRelative;
var moduleName = "";
@@ -219,7 +220,12 @@ export default class DefaultFormatter {
// normalize path separators
moduleName = moduleName.replace(/\\/g, "/");
return moduleName;
if (opts.getModuleId) {
// If return is falsy, assume they want us to use our generated default name
return opts.getModuleId(moduleName) || moduleName;
} else {
return moduleName;
}
}
_pushStatement(ref, nodes) {

View File

@@ -6,7 +6,9 @@ import * as util from "../../util";
import * as t from "../../types";
export default class AMDFormatter extends DefaultFormatter {
init = CommonFormatter.prototype.init;
init() {
CommonFormatter.prototype._init.call(this, this.hasNonDefaultExports);
}
buildDependencyLiterals() {
var names = [];
@@ -21,7 +23,7 @@ export default class AMDFormatter extends DefaultFormatter {
*/
transform(program) {
DefaultFormatter.prototype.transform.apply(this, arguments);
CommonFormatter.prototype.transform.apply(this, arguments);
var body = program.body;
@@ -78,9 +80,12 @@ export default class AMDFormatter extends DefaultFormatter {
this.defaultIds[key] = specifier.local;
}
if (includes(this.file.dynamicImportedNoDefault, node)) {
// Prevent unnecessary renaming of dynamic imports.
if (this.isModuleType(node, "absolute")) {
// absolute module reference
} else if (this.isModuleType(node, "absoluteDefault")) {
// prevent unnecessary renaming of dynamic imports
this.ids[node.source.value] = ref;
ref = t.memberExpression(ref, t.identifier("default"));
} else if (t.isImportNamespaceSpecifier(specifier)) {
// import * as bar from "foo";
} else if (!includes(this.file.dynamicImported, node) && t.isSpecifierDefault(specifier) && !this.noInteropRequireImport) {
@@ -100,15 +105,39 @@ export default class AMDFormatter extends DefaultFormatter {
this.internalRemap[specifier.local.name] = ref;
}
exportSpecifier() {
exportSpecifier(specifier, node, nodes) {
if (this.doDefaultExportInterop(specifier)) {
this.passModuleArg = true;
if (specifier.exported !== specifier.local && !node.source) {
nodes.push(util.template("exports-default-assign", {
VALUE: specifier.local
}, true));
return;
}
}
CommonFormatter.prototype.exportSpecifier.apply(this, arguments);
}
exportDeclaration(node) {
exportDeclaration(node, nodes) {
if (this.doDefaultExportInterop(node)) {
this.passModuleArg = true;
var declar = node.declaration;
var assign = util.template("exports-default-assign", {
VALUE: this._pushStatement(declar, nodes)
}, true);
if (t.isFunctionDeclaration(declar)) {
// we can hoist this assignment to the top of the file
assign._blockHoist = 3;
}
nodes.push(assign);
return;
}
CommonFormatter.prototype.exportDeclaration.apply(this, arguments);
DefaultFormatter.prototype.exportDeclaration.apply(this, arguments);
}
}

View File

@@ -5,18 +5,36 @@ import * as t from "../../types";
export default class CommonJSFormatter extends DefaultFormatter {
init() {
this._init(this.hasLocalExports);
}
_init(conditional) {
var file = this.file;
var scope = file.scope;
scope.rename("module");
scope.rename("exports");
if (!this.noInteropRequireImport && this.hasNonDefaultExports) {
if (!this.noInteropRequireImport && conditional) {
var templateName = "exports-module-declaration";
if (this.file.isLoose("es6.modules")) templateName += "-loose";
var declar = util.template(templateName, true);
declar._blockHoist = 3;
file.ast.program.body.unshift(declar);
file.path.unshiftContainer("body", [declar]);
}
}
transform(program) {
DefaultFormatter.prototype.transform.apply(this, arguments);
if (this.hasDefaultOnlyExport) {
program.body.push(
t.expressionStatement(t.assignmentExpression(
"=",
t.memberExpression(t.identifier("module"), t.identifier("exports")),
t.memberExpression(t.identifier("exports"), t.identifier("default"))
))
);
}
}
@@ -27,16 +45,20 @@ export default class CommonJSFormatter extends DefaultFormatter {
// import foo from "foo";
if (t.isSpecifierDefault(specifier)) {
if (includes(this.file.dynamicImportedNoDefault, node)) {
if (this.isModuleType(node, "absolute")) {
// absolute module reference
} else if (this.isModuleType(node, "absoluteDefault")) {
this.internalRemap[variableName.name] = ref;
} else if (this.noInteropRequireImport) {
this.internalRemap[variableName.name] = t.memberExpression(ref, t.identifier("default"));
} else {
if (this.noInteropRequireImport) {
this.internalRemap[variableName.name] = t.memberExpression(ref, t.identifier("default"))
} else if (!includes(this.file.dynamicImported, node)) {
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(variableName, t.callExpression(this.file.addHelper("interop-require"), [ref]))
]));
}
var uid = this.scope.generateUidBasedOnNode(node, "import");
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(uid, t.callExpression(this.file.addHelper("interop-require-default"), [ref]))
]));
this.internalRemap[variableName.name] = t.memberExpression(uid, t.identifier("default"));
}
} else {
if (t.isImportNamespaceSpecifier(specifier)) {
@@ -64,29 +86,15 @@ export default class CommonJSFormatter extends DefaultFormatter {
exportSpecifier(specifier, node, nodes) {
if (this.doDefaultExportInterop(specifier)) {
nodes.push(util.template("exports-default-assign", {
VALUE: specifier.local
}, true));
return;
} else {
DefaultFormatter.prototype.exportSpecifier.apply(this, arguments);
this.hasDefaultOnlyExport = true;
}
DefaultFormatter.prototype.exportSpecifier.apply(this, arguments);
}
exportDeclaration(node, nodes) {
if (this.doDefaultExportInterop(node)) {
var declar = node.declaration;
var assign = util.template("exports-default-assign", {
VALUE: this._pushStatement(declar, nodes)
}, true);
if (t.isFunctionDeclaration(declar)) {
// we can hoist this assignment to the top of the file
assign._blockHoist = 3;
}
nodes.push(assign);
return;
this.hasDefaultOnlyExport = true;
}
DefaultFormatter.prototype.exportDeclaration.apply(this, arguments);
@@ -98,13 +106,16 @@ export default class CommonJSFormatter extends DefaultFormatter {
var call = t.callExpression(t.identifier("require"), [node.source]);
var uid;
if (includes(this.file.dynamicImported, node) && !includes(this.file.dynamicImportedNoDefault, node)) {
if (this.isModuleType(node, "absolute")) {
// absolute module reference
} else if (this.isModuleType(node, "absoluteDefault")) {
call = t.memberExpression(call, t.identifier("default"));
uid = node.specifiers[0].local;
} else {
uid = this.scope.generateUidBasedOnNode(node, "import");
}
uid = uid || node.specifiers[0].local;
var declar = t.variableDeclaration("var", [
t.variableDeclarator(uid, call)
]);

View File

@@ -6,12 +6,8 @@ import each from "lodash/collection/each";
import map from "lodash/collection/map";
import * as t from "../../types";
var canHoist = function (node, file) {
return node._blockHoist && !file.transformers.runtime.canTransform();
}
var hoistVariablesVisitor = {
enter(node, parent, scope, hoistDeclarators) {
enter(node, parent, scope, state) {
if (t.isFunction(node)) {
// nothing inside is accessible
return this.skip();
@@ -24,13 +20,13 @@ var hoistVariablesVisitor = {
}
// ignore block hoisted nodes as these can be left in
if (canHoist(node, scope.file)) return;
if (state.formatter.canHoist(node)) return;
var nodes = [];
for (var i = 0; i < node.declarations.length; i++) {
var declar = node.declarations[i];
hoistDeclarators.push(t.variableDeclarator(declar.id));
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));
@@ -40,14 +36,8 @@ var hoistVariablesVisitor = {
// for (var i in test)
// for (var i = 0;;)
if (t.isFor(parent)) {
if (parent.left === node) {
return node.declarations[0].id;
}
if (parent.init === node) {
return nodes;
}
if (t.isFor(parent) && parent.left === node) {
return node.declarations[0].id;
}
return nodes;
@@ -56,11 +46,11 @@ var hoistVariablesVisitor = {
};
var hoistFunctionsVisitor = {
enter(node, parent, scope, handlerBody) {
enter(node, parent, scope, state) {
if (t.isFunction(node)) this.skip();
if (t.isFunctionDeclaration(node) || canHoist(node, scope.file)) {
handlerBody.push(node);
if (t.isFunctionDeclaration(node) || state.formatter.canHoist(node)) {
state.handlerBody.push(node);
this.remove();
}
}
@@ -87,11 +77,11 @@ var runnerSettersVisitor = {
export default class SystemFormatter extends AMDFormatter {
constructor(file) {
super(file);
this.exportIdentifier = file.scope.generateUidIdentifier("export");
this.noInteropRequireExport = true;
this.noInteropRequireImport = true;
DefaultFormatter.apply(this, arguments);
}
_addImportSource(node, exportNode) {
@@ -174,6 +164,10 @@ export default class SystemFormatter extends AMDFormatter {
}));
}
canHoist(node) {
return node._blockHoist && !this.file.dynamicImports.length;
}
transform(program) {
DefaultFormatter.prototype.transform.apply(this, arguments);
@@ -197,7 +191,10 @@ export default class SystemFormatter extends AMDFormatter {
var returnStatement = handlerBody.pop();
// hoist up all variable declarations
this.file.scope.traverse(block, hoistVariablesVisitor, hoistDeclarators);
this.file.scope.traverse(block, hoistVariablesVisitor, {
formatter: this,
hoistDeclarators: hoistDeclarators
});
if (hoistDeclarators.length) {
var hoistDeclar = t.variableDeclaration("var", hoistDeclarators);
@@ -206,7 +203,10 @@ export default class SystemFormatter extends AMDFormatter {
}
// hoist up function declarations for circular references
this.file.scope.traverse(block, hoistFunctionsVisitor, handlerBody);
this.file.scope.traverse(block, hoistFunctionsVisitor, {
formatter: this,
handlerBody: handlerBody
});
handlerBody.push(returnStatement);

View File

@@ -1,6 +1,7 @@
import DefaultFormatter from "./_default";
import AMDFormatter from "./amd";
import values from "lodash/object/values";
import path from "path";
import * as util from "../../util";
import * as t from "../../types";
@@ -47,11 +48,11 @@ export default class UMDFormatter extends AMDFormatter {
// globals
var browserArgs = [t.memberExpression(t.identifier("module"), t.identifier("exports"))];
if (this.passModuleArg) browserArgs.push(t.identifier("module"));
var browserArgs = [];
if (this.passModuleArg) browserArgs.push(t.identifier("mod"));
for (let name in this.ids) {
var id = this.defaultIds[name] || t.identifier(t.toIdentifier(name));
var id = this.defaultIds[name] || t.identifier(t.toIdentifier(path.basename(name, path.extname(name))));
browserArgs.push(t.memberExpression(t.identifier("global"), id));
}
@@ -60,12 +61,17 @@ export default class UMDFormatter extends AMDFormatter {
var moduleName = this.getModuleName();
if (moduleName) defineArgs.unshift(t.literal(moduleName));
//
var globalArg = this.file.opts.basename;
if (moduleName) globalArg = moduleName;
globalArg = t.identifier(t.toIdentifier(globalArg));
var runner = util.template("umd-runner-body", {
AMD_ARGUMENTS: defineArgs,
COMMON_TEST: commonTests,
COMMON_ARGUMENTS: commonArgs,
BROWSER_ARGUMENTS: browserArgs,
GLOBAL_ARG: t.identifier(t.toIdentifier(this.file.opts.basename))
GLOBAL_ARG: globalArg
});
//

View File

@@ -1,4 +1,4 @@
{
"blacklist": ["useStrict", "es6.blockScoping", "regenerator"],
"blacklist": ["useStrict", "es6.blockScoping", "regenerator", "es6.spread"],
"loose": ["es6.modules"]
}

View File

@@ -1 +0,0 @@
this.KEY = INITIALIZERS.KEY.call(this);

View File

@@ -1 +0,0 @@
CONSTRUCTOR.KEY = INITIALIZERS.KEY.call(CONSTRUCTOR);

View File

@@ -0,0 +1,5 @@
if (SUPER_NAME != null) {
var NATIVE_REF = new SUPER_NAME(...arguments);
NATIVE_REF.__proto__ = CLASS_NAME.prototype;
return NATIVE_REF;
}

View File

@@ -1 +0,0 @@
CORE_ID.isIterable(VALUE);

View File

@@ -1 +0,0 @@
CORE_ID.getIterator(VALUE);

View File

@@ -4,7 +4,7 @@
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if (descriptor.value) descriptor.writable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}

View File

@@ -23,7 +23,11 @@
throw new TypeError("The decorator for method " + descriptor.key + " is of the invalid type " + typeof decorator);
}
}
if (initializers) initializers[key] = descriptor.initializer;
if (descriptor.initializer !== undefined) {
initializers[key] = descriptor;
continue;
}
}
Object.defineProperty(target, key, descriptor);

View File

@@ -0,0 +1,37 @@
(function (descriptors) {
var target = {};
for (var i = 0; i < descriptors.length; i ++) {
var descriptor = descriptors[i];
var decorators = descriptor.decorators;
var key = descriptor.key;
// don't want to expose these to userland since i know people will rely on them
// and think it's spec behaviour
delete descriptor.key;
delete descriptor.decorators;
descriptor.enumerable = true;
descriptor.configurable = true;
descriptor.writable = true;
if (decorators) {
for (var f = 0; f < decorators.length; f++) {
var decorator = decorators[f];
if (typeof decorator === "function") {
descriptor = decorator(target, key, descriptor) || descriptor;
} else {
throw new TypeError("The decorator for method " + descriptor.key + " is of the invalid type " + typeof decorator);
}
}
}
if (descriptor.initializer) {
descriptor.value = descriptor.initializer.call(target);
}
Object.defineProperty(target, key, descriptor);
}
return target;
})

View File

@@ -0,0 +1,13 @@
(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
descriptor.value = descriptor.initializer.call(target);
Object.defineProperty(target, key, descriptor);
})

View File

@@ -1,7 +1,7 @@
(function (obj, key, value) {
return Object.defineProperty(obj, key, {
value: value,
enumerable: key == null || typeof Symbol == "undefined" || key.constructor !== Symbol,
enumerable: true,
configurable: true,
writable: true
});

View File

@@ -0,0 +1,7 @@
(function (left, right) {
if (right != null && right[Symbol.hasInstance]) {
return right[Symbol.hasInstance](left);
} else {
return left instanceof right;
}
});

View File

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

View File

@@ -1,3 +1,14 @@
(function (obj) {
return obj && obj.__esModule ? obj : { default: obj };
if (obj && obj.__esModule) {
return obj;
} else {
var newObj = {};
if (obj != null) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
}
}
newObj.default = obj;
return newObj;
}
})

View File

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

View File

@@ -1,10 +1,10 @@
(function (FUNCTION_KEY) {
function* FUNCTION_ID() {
return yield* FUNCTION_ID.apply(this, arguments);
return yield* FUNCTION_KEY.apply(this, arguments);
}
FUNCTION_ID.toString = function () {
return FUNCTION_ID.toString();
return FUNCTION_KEY.toString();
};
return FUNCTION_ID;

View File

@@ -4,7 +4,7 @@
}
FUNCTION_ID.toString = function () {
return FUNCTION_ID.toString();
return FUNCTION_KEY.toString();
}
return FUNCTION_ID;

View File

@@ -4,8 +4,8 @@
} else if (COMMON_TEST) {
factory(COMMON_ARGUMENTS);
} else {
var module = { exports: {} };
factory(BROWSER_ARGUMENTS);
global.GLOBAL_ARG = module.exports;
var mod = { exports: {} };
factory(mod.exports, BROWSER_ARGUMENTS);
global.GLOBAL_ARG = mod.exports;
}
});

View File

@@ -8,58 +8,35 @@ import traverse from "../traversal";
export default class TransformerPass {
constructor(file: File, transformer: Transformer) {
this.transformer = transformer;
this.shouldRun = !transformer.check;
this.handlers = transformer.handlers;
this.file = file;
this.ran = false;
this.shouldTransform = !transformer.shouldVisit;
this.transformer = transformer;
this.handlers = transformer.handlers;
this.skipKey = transformer.skipKey;
this.file = file;
this.ran = false;
}
canTransform(): boolean {
var transformer = this.transformer;
var opts = this.file.opts;
var key = transformer.key;
// internal
if (key[0] === "_") return true;
// blacklist
var blacklist = opts.blacklist;
if (blacklist.length && includes(blacklist, key)) return false;
// whitelist
var whitelist = opts.whitelist;
if (whitelist) return includes(whitelist, key);
// stage
var stage = transformer.metadata.stage;
if (stage != null && stage >= opts.stage) return true;
// optional
if (transformer.metadata.optional && !includes(opts.optional, key)) return false;
return true;
return this.file.pipeline.canTransform(this.transformer, this.file.opts);
}
checkNode(node: Object): boolean {
var check = this.transformer.check;
if (check) {
return this.shouldRun = check(node);
} else {
return true;
}
checkPath(path: TraversalPath): boolean {
if (this.shouldTransform || this.ran) return;
this.shouldTransform = this.transformer.shouldVisit(path.node);
}
transform() {
if (!this.shouldRun) return;
if (!this.shouldTransform) return;
var file = this.file;
file.log.debug(`Running transformer ${this.transformer.key}`);
file.log.debug(`Start transformer ${this.transformer.key}`);
traverse(file.ast, this.handlers, file.scope, file);
file.log.debug(`Finish transformer ${this.transformer.key}`);
this.ran = true;
}
}

View File

@@ -0,0 +1,105 @@
import Transformer from "./transformer";
import normalizeAst from "../helpers/normalize-ast";
import assign from "lodash/object/assign";
import object from "../helpers/object";
import File from "./file";
export default class TransformerPipeline {
constructor() {
this.transformers = object();
this.namespaces = object();
this.deprecated = object();
this.aliases = object();
this.filters = [];
}
addTransformers(transformers) {
for (var key in transformers) {
this.addTransformer(key, transformers[key]);
}
return this;
}
addTransformer(key, transformer) {
if (this.transformers[key]) throw new Error(); // todo: error
var namespace = key.split(".")[0];
this.namespaces[namespace] = this.namespaces[namespace] || [];
this.namespaces[namespace].push(key);
this.namespaces[key] = namespace;
this.transformers[key] = new Transformer(key, transformer);
}
addAliases(names) {
assign(this.aliases, names);
return this;
}
addDeprecated(names) {
assign(this.deprecated, names);
return this;
}
addFilter(filter: Function) {
this.filters.push(filter);
return this;
}
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;
}
return true;
}
transform(code: string, opts?: Object) {
var file = new File(opts, this);
return file.wrap(code, function () {
file.addCode(code, true);
});
}
transformFromAst(ast, code, opts) {
ast = normalizeAst(ast);
var file = new File(opts, this);
return file.wrap(code, function () {
file.addCode(code);
file.addAst(ast);
});
}
_ensureTransformerNames(type: string, rawKeys: Array<string>) {
var keys = [];
for (var i = 0; i < rawKeys.length; i++) {
var key = rawKeys[i];
var deprecatedKey = this.deprecated[key];
var aliasKey = this.aliases[key];
if (aliasKey) {
keys.push(aliasKey);
} else if (deprecatedKey) {
// deprecated key, remap it to the new one
console.error(`[BABEL] The transformer ${key} has been renamed to ${deprecatedKey}`);
rawKeys.push(deprecatedKey);
} else if (this.transformers[key]) {
// valid key
keys.push(key);
} else if (this.namespaces[key]) {
// namespace, append all transformers within this namespace
keys = keys.concat(this.namespaces[key]);
} else {
// invalid key
throw new ReferenceError(`Unknown transformer ${key} specified in ${type}`);
}
}
return keys;
}
}

View File

@@ -1,4 +1,5 @@
import TransformerPass from "./transformer-pass";
import * as messages from "../messages";
import isFunction from "lodash/lang/isFunction";
import traverse from "../traversal";
import isObject from "lodash/lang/isObject";
@@ -14,7 +15,7 @@ import each from "lodash/collection/each";
*/
export default class Transformer {
constructor(transformerKey: key, transformer: Object, opts: Object) {
constructor(transformerKey: string, transformer: Object) {
transformer = assign({}, transformer);
var take = function (key) {
@@ -24,19 +25,34 @@ export default class Transformer {
};
this.manipulateOptions = take("manipulateOptions");
this.shouldVisit = take("shouldVisit");
this.metadata = take("metadata") || {};
this.parser = take("parser");
this.check = take("check");
this.post = take("post");
this.pre = take("pre");
//
if (this.metadata.stage != null) {
this.metadata.optional = true;
}
//
this.handlers = this.normalize(transformer);
this.opts ||= {};
this.key = transformerKey;
//
if (!this.shouldVisit && !this.handlers.enter && !this.handlers.exit) {
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 {
@@ -71,7 +87,7 @@ export default class Transformer {
buildPass(file: File): TransformerPass {
// validate Transformer instance
if (!(file instanceof File)) {
throw new TypeError(`Transformer ${this.key} is resolving to a different Babel version to what is doing the actual transformation...`);
throw new TypeError(messages.get("transformerNotFile", this.key));
}
return new TransformerPass(file, this);

View File

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

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