Compare commits

...

1188 Commits

Author SHA1 Message Date
Sebastian McKenzie
1b45f64858 v5.4.1 2015-05-15 02:00:18 +01:00
Sebastian McKenzie
b89cf6768f fix shouldIgnore only matches switch 2015-05-15 01:57:10 +01:00
Sebastian McKenzie
36ad1108b4 fix loose mode loop being weirdly inserted 2015-05-15 01:56:34 +01:00
Sebastian McKenzie
4c04371ea4 remove loop label due to babel bug 2015-05-15 01:48:47 +01:00
Sebastian McKenzie
d3e385c554 one last try fixing the shouldIgnore only filter... 2015-05-15 01:46:36 +01:00
Sebastian McKenzie
6afcef9805 actually fix shouldIgnore algorithm this time, ugh 2015-05-15 01:44:57 +01:00
Sebastian McKenzie
ed861e230b fix shouldIgnore method for only 2015-05-15 01:41:49 +01:00
Sebastian McKenzie
e15ced2922 add 5.4.1 changelog 2015-05-15 01:37:48 +01:00
Sebastian McKenzie
93052e532f Merge branch 'master' of github.com:babel/babel 2015-05-15 01:35:43 +01:00
Sebastian McKenzie
198d51ddaa heavily improve shouldIgnore algorithm - fixes #1539 2015-05-15 01:34:58 +01:00
Sebastian McKenzie
8730b24def Merge pull request #1540 from browncolyn/master
Added slash as needed dependency
2015-05-15 01:30:50 +01:00
Colyn Brown
f09c0d5998 Added slash as needed dependency 2015-05-14 17:28:20 -07:00
Sebastian McKenzie
21e4481ab7 5.4.0 2015-05-15 00:32:36 +01:00
Sebastian McKenzie
2f61754a24 v5.4.0 2015-05-15 00:29:42 +01:00
Sebastian McKenzie
3910d18bc9 add 5.4.0 changelog 2015-05-15 00:28:47 +01:00
Sebastian McKenzie
583111ebfb expose file metadata object to transformers 2015-05-15 00:24:14 +01:00
Sebastian McKenzie
1b15481460 ignore "ignored files" when babel.transform has determined that it should be ignored, this is likely the result of an rc file resolution - fixes #1362 2015-05-15 00:24:03 +01:00
Sebastian McKenzie
fd9c98ff86 move strict transformer to builtin-setup group - fixes #1538 2015-05-15 00:18:42 +01:00
Sebastian McKenzie
41b5607ef3 fix env option tests 2015-05-15 00:11:28 +01:00
Sebastian McKenzie
ae77ea807f normalise source map file paths when using the CLI - fixes #1496 2015-05-15 00:05:11 +01:00
Sebastian McKenzie
ad44190c6b properly register for head variable declaration paths when performing scope tracking - fixes #1524 2015-05-14 23:53:04 +01:00
Sebastian McKenzie
024e4454a1 add env option - closes #1531 2015-05-14 23:47:56 +01:00
Sebastian McKenzie
14dddcda36 make PathHoister much more flexible, now ignores global references and will not deopt on reassignments and will instead hoist as high as it can, this also fixes #1529 since the order of operations has changed 2015-05-14 23:29:02 +01:00
Sebastian McKenzie
d4fb924b6a add tion comment to all function visitors 2015-05-14 22:37:15 +01:00
Sebastian McKenzie
b02c97af60 Merge pull request #1536 from benjamn/master
Invoke Regenerator on async/generator Function nodes, not whole AST.
2015-05-14 22:27:42 +01:00
Ben Newman
cc611cb71c Invoke Regenerator on async/generator Function nodes, not whole AST.
This should help (dramatically?) with
https://github.com/babel/babel/issues/1486#issuecomment-101491605,
although I'm not sure how to run the benchmarks myself.
2015-05-14 15:42:58 -05:00
Sebastian McKenzie
b8a01a9919 move traversal scope logic and binding into it's own folder, rename Scope#generateTemp to generateDeclaredUidIdentifier, rename Scope#generateUidBasedOnNode to Scope#generateUidIdentifierBasedOnNode 2015-05-14 19:12:26 +01:00
Sebastian McKenzie
55c99661be NFO 2015-05-14 18:07:36 +01:00
Sebastian McKenzie
1563b216df Merge branch 'master' of github.com:babel/babel 2015-05-14 17:56:33 +01:00
Sebastian McKenzie
a9d4b485d9 simplify getStaticContext in es7.functionBind transformer - thanks @RReverser! 2015-05-14 17:48:51 +01:00
Sebastian McKenzie
360daa6267 Merge pull request #1532 from dchambers/prefix-private-methods-with-underscore
Prefix private methods names with underscore.
2015-05-14 16:52:16 +01:00
Sebastian McKenzie
724bf52929 handle "static" contexts in es7.functionBind - #1518 2015-05-14 16:37:44 +01:00
Sebastian McKenzie
7407b37bd9 Merge pull request #1518 from babel/es7.functionBind
Add experimental support for ES7 function bind.
2015-05-14 16:22:21 +01:00
Ingvar Stepanyan
da765cc4c1 Flip the negation in if-else. 2015-05-14 18:05:55 +03:00
dchambers
4f862eee6e Prefix private methods names with underscore. 2015-05-14 13:19:41 +01:00
Ingvar Stepanyan
e05d7cf49a Fix some parsing edge cases for :: operator. 2015-05-14 12:47:51 +03:00
Ingvar Stepanyan
fd8e94a90f Preserve original execution order in :: operator. 2015-05-14 12:39:05 +03:00
Sebastian McKenzie
a6cf28c5b5 Merge pull request #1525 from nkt/exponentiation-operator-inline
Added missing exponential operator inlining
2015-05-13 23:09:57 +01:00
Nikita Gusakov
6b07b13a8e Added missing exponential operator inlining 2015-05-14 01:08:02 +03:00
Sebastian McKenzie
561c4dcc25 5.3.3 2015-05-13 22:09:37 +01:00
Sebastian McKenzie
b516ea596a v5.3.3 2015-05-13 22:08:32 +01:00
Sebastian McKenzie
248758eee3 fix version number 2015-05-13 22:07:33 +01:00
Sebastian McKenzie
a808602ae0 v3.5.3 2015-05-13 22:07:00 +01:00
Sebastian McKenzie
40e3436e95 add 3.5.3 changelog 2015-05-13 22:05:07 +01:00
Sebastian McKenzie
f704770b26 uncomment out return traversal path skipping - fixes #1523 2015-05-13 22:03:50 +01:00
Sebastian McKenzie
330665f150 ignore modules alongside param bindings in minification.deadCodeElimination transformer - fixes #1523 2015-05-13 21:49:28 +01:00
Sebastian McKenzie
af41899d74 5.3.2 2015-05-13 19:58:21 +01:00
Sebastian McKenzie
d12f4d0bc8 v5.3.2 2015-05-13 19:57:20 +01:00
Sebastian McKenzie
97680e9dfd properly hoist all var patterns when wrapping bodies in the es6.blockScoping transformer - fixes #1521 2015-05-13 19:55:40 +01:00
Sebastian McKenzie
51341ca6c3 fix and add missing module specifier reference detection - fixes #1520 2015-05-13 19:23:47 +01:00
Sebastian McKenzie
ab54bfa50e Merge pull request #1519 from zpao/package-licenses
Add license fields to packages
2015-05-13 18:36:25 +01:00
Paul O’Shannessy
60aa933fb6 Add license fields to packages 2015-05-13 10:21:42 -07:00
Ingvar Stepanyan
1a299b2bcc Small fixes to es7.functionBind and generation tests added. 2015-05-13 18:20:33 +03:00
Ingvar Stepanyan
37f662d790 Add experimental support for ES7 function bind. (issue #1287) 2015-05-13 17:58:21 +03:00
Sebastian McKenzie
b0317f9bab don't consider "globals" to cause incompatible scope hoist 2015-05-13 12:33:08 +01:00
Sebastian McKenzie
be2dfaf081 register variable declarator in scope when pushing 2015-05-13 09:11:09 +01:00
Sebastian McKenzie
2c8437ae92 ignore initializerless variable declaration when trying to inline single use variables - fixes #1516 2015-05-13 08:46:41 +01:00
Sebastian McKenzie
2a0bcfd086 add support for evaluating unary ~ 2015-05-13 08:45:16 +01:00
Sebastian McKenzie
2cf41afac3 move expression inlining to exit rather than enter in minification.inlineExpressions transformer 2015-05-13 08:45:06 +01:00
Sebastian McKenzie
e318f5f3be use ReferencedIdentifier virtual type in minification.deadCodeElimination transformer 2015-05-13 08:44:33 +01:00
Sebastian McKenzie
939decb86c stop entire unnecessary traversal for regenerator 2015-05-13 08:44:18 +01:00
Sebastian McKenzie
1baa0df948 clean up array inferrence for #1515 2015-05-13 08:44:03 +01:00
Sebastian McKenzie
e8956a8c44 upgrade dev dependency babel to 5.3.1 2015-05-13 08:43:25 +01:00
Sebastian McKenzie
2f0fdbbc26 5.3.1 2015-05-13 03:21:54 +01:00
Sebastian McKenzie
5f931525bc v5.3.1 2015-05-13 03:20:33 +01:00
Sebastian McKenzie
b86545a320 update 5.3.1 changelog 2015-05-13 03:19:39 +01:00
Sebastian McKenzie
06e75c42bf update module call remap tests 2015-05-13 03:18:55 +01:00
Sebastian McKenzie
05dd65244d add 5.3.1 changelog 2015-05-13 03:16:43 +01:00
Sebastian McKenzie
c4ebfeb0fa fix explosion of modules and colliding identifiers 2015-05-13 03:16:03 +01:00
Sebastian McKenzie
1aa0bbfac9 add TraversalPath#equals 2015-05-13 03:13:27 +01:00
Sebastian McKenzie
58f1e6cbc6 remove incorrect es6.tailCall visitor comment 2015-05-13 03:13:20 +01:00
Sebastian McKenzie
83e0be3038 make import calls sequence expressions - fixes #1514 2015-05-13 03:13:10 +01:00
Sebastian McKenzie
5fc242e4ec upgrade bable dev dependency to 5.3.0 2015-05-13 03:12:32 +01:00
Sebastian McKenzie
dc101adad3 more es6.tailCall transformer cleanup 2015-05-13 01:13:08 +01:00
Sebastian McKenzie
faade72787 optimise and clean up es6.tailCall transformer 2015-05-13 01:11:26 +01:00
Sebastian McKenzie
2a78ae9889 5.3.0 2015-05-13 01:07:11 +01:00
Sebastian McKenzie
9840639843 v5.3.0 2015-05-13 00:13:14 +01:00
Sebastian McKenzie
82c21a901e clean up es6.tailCall thirdPass visitor 2015-05-13 00:11:19 +01:00
Sebastian McKenzie
e1c83144c1 add 5.3.0 changelog 2015-05-13 00:11:08 +01:00
Sebastian McKenzie
ef2ac73215 fix export scope tracking reference counter - fixes #1513 2015-05-12 23:21:30 +01:00
Sebastian McKenzie
735d8955bf sync with upstream acorn 2015-05-12 23:21:30 +01:00
Sebastian McKenzie
3abee0a4fa fix switch case breaks not being correctly transformed when non top-level - fixes #1200 2015-05-12 23:21:30 +01:00
Sebastian McKenzie
b6f18b4f2b Merge pull request #1200 from lukasmlady/regenerator-let-fn-if-bug
Add failing tests that document ES 6 generators bug
2015-05-12 23:21:17 +01:00
Sebastian McKenzie
85cd0465fa Merge pull request #1511 from amasad/trailing-methods
Trailing commas in methods
2015-05-12 21:46:18 +01:00
Amjad Masad
0452e0fdd2 Allow trailing commas in methods 2015-05-12 13:20:36 -07:00
Amjad Masad
462ff572b3 Add failing test for trailing commas in methods 2015-05-12 13:19:21 -07:00
Sebastian McKenzie
d11099bb2b Merge branch 'master' of github.com:babel/babel 2015-05-12 19:13:53 +01:00
Sebastian McKenzie
f5c4684d3e force default parameter IIFE on reference to eval 2015-05-12 19:13:32 +01:00
Sebastian McKenzie
876a22578b Merge pull request #1506 from sverrejoh/patch-1
Added missing license field to package.json
2015-05-12 09:06:55 +01:00
Sverre Johansen
9f5e8b296b Added missing license field to package.json
Project says MIT, but license field missing in package.json
2015-05-12 08:54:56 +02:00
Sebastian McKenzie
d9deb02edc register as inside a type when parsing type aliases to avoid ambiguous jsx parsing - fixes #1378 2015-05-11 23:44:22 +01:00
Sebastian McKenzie
a402d0cdeb ensure that uids don't collide with **any** bindings contained in the program - fixes #1328 2015-05-11 23:37:31 +01:00
Sebastian McKenzie
683fb62505 fix acorn hacky lookahead with token contexts - fixes #1349 2015-05-11 23:20:51 +01:00
Sebastian McKenzie
941474983d clean up es6.objectSuper transformer - fixes #1502 2015-05-11 22:34:08 +01:00
Sebastian McKenzie
2b42773e01 explode duplicate identifiers in export/import specifiers and property shorthand - fixes #1458 2015-05-11 22:08:38 +01:00
Sebastian McKenzie
8277a532f4 skip loose mode for class methods when using decorators, addresses #1501 2015-05-11 17:40:36 +01:00
Sebastian McKenzie
539784b640 add Scope#moveBindingTo method and change more for array loops to for...of 2015-05-11 17:25:09 +01:00
Sebastian McKenzie
f373f8f003 refactor _shadowFunctions transformer to not do an entire traverse per function 2015-05-11 11:38:22 +01:00
Sebastian McKenzie
8605e835eb add exit visitor existence to unvisitable node shortcircuiting 2015-05-11 01:52:19 +01:00
Sebastian McKenzie
b4ace2043a fix shortcircuting of unvisitable nodes 2015-05-11 01:43:18 +01:00
Sebastian McKenzie
444a64e934 remove incorrect no eval in strict mode 2015-05-10 20:01:13 +01:00
Sebastian McKenzie
8ea2ae924d add existence check for ast.comments 2015-05-10 20:00:38 +01:00
Sebastian McKenzie
4ceb1d6f5e short circuit unnecessary visits 2015-05-10 20:00:26 +01:00
Sebastian McKenzie
3c81899ca7 add --harmony_generators to list of node flags - closes #1474, closes #1473 2015-05-10 20:00:12 +01:00
Sebastian McKenzie
ab59fd08e5 fix array type inferrence for file#toArray from being so wonky - fixes #1355 2015-05-10 19:35:41 +01:00
Sebastian McKenzie
19b05b5e61 change some manual array for loops to for..of 2015-05-10 19:35:05 +01:00
Sebastian McKenzie
65a44a1e13 remove use of exports 2015-05-10 16:09:43 +01:00
Sebastian McKenzie
d38f18af40 create null object when clearing internalRemap instead of using an object inherited plain object - fixes #1489 2015-05-09 18:39:59 +01:00
Sebastian McKenzie
2744b9f31f only print misisng ast.comments when available 2015-05-09 17:32:47 +01:00
Sebastian McKenzie
4deed35212 fix syntax errors introduced with previous lodash each removal 2015-05-09 17:27:33 +01:00
Sebastian McKenzie
bc9ae5ea8b remove many instances of lodash each in favor of for of loops 2015-05-09 17:22:01 +01:00
Sebastian McKenzie
87d879e236 Merge branch 'master' of github.com:babel/babel 2015-05-09 16:53:05 +01:00
Sebastian McKenzie
f657598c72 remove noop traversal visitors methods 2015-05-09 16:52:57 +01:00
Sebastian McKenzie
2a5cb9d21b move some utility transformers to minification 2015-05-09 16:52:31 +01:00
Sebastian McKenzie
cf7d6b655e Merge pull request #1487 from amasad/trailing-commas
[es7.trailingFunctionCommas] Allow in new expressions
2015-05-09 03:16:18 +01:00
Amjad Masad
6d2723eec5 New expressions is allowed to have trailing commas in es7 proposal 2015-05-08 19:12:53 -07:00
Amjad Masad
6834cc5b46 Add failing tests for trailing commas in new expressions 2015-05-08 19:12:10 -07:00
Sebastian McKenzie
9b949e574f use block scoped variables in es6.blockScoping transformer 2015-05-09 01:25:36 +01:00
Sebastian McKenzie
a75af0a5d2 optimise es6.constants transformer to use the same traversal path instead of spawning another one 2015-05-09 01:25:21 +01:00
Sebastian McKenzie
080b26769c remove compat-table 2015-05-09 00:09:19 +01:00
Sebastian McKenzie
e037ae7bc9 automatically explode visitors 2015-05-09 00:07:08 +01:00
Sebastian McKenzie
c60ad89937 add verbose mode to logging 2015-05-09 00:06:55 +01:00
Sebastian McKenzie
4194857086 fix system modules test to reflect strict hoisting behaviour 2015-05-08 23:58:25 +01:00
Sebastian McKenzie
1179c44c5b share comments with siblings when nodes are removed - fixes #1484 2015-05-08 23:57:12 +01:00
Sebastian McKenzie
f6d9b270c9 update to tracuer master 2015-05-08 23:48:30 +01:00
Sebastian McKenzie
1be0159b01 Merge pull request #1484 from amasad/type-comment-print
[Flow] Add failing tests for printing comments w/ type alias
2015-05-08 23:46:18 +01:00
Sebastian McKenzie
61ba8ad997 Merge pull request #1472 from babel/single-pass
Merge internal transformers into single traversal pass
2015-05-08 23:36:29 +01:00
Sebastian McKenzie
89e31085d2 ensure dynamic imports are hoisted 2015-05-08 23:33:30 +01:00
Sebastian McKenzie
920c84a1f2 move shadow function visitors to entrance instead of exit 2015-05-08 23:33:20 +01:00
Amjad Masad
ed56fecd04 [Flow] Add failing tests for printing comments w/ type alias 2015-05-08 15:33:00 -07:00
Sebastian McKenzie
f0bfdfb699 skip traversing back into ReturnStatement replacement when rewriting loops in the es6.blockScoping transformer 2015-05-08 23:13:27 +01:00
Sebastian McKenzie
b02a1112bc change ClassExpression visitor to enter instead of exist in the es6.classes transformer 2015-05-08 23:10:02 +01:00
Sebastian McKenzie
590a165776 move hoistDirectives transformer to builtin-setup 2015-05-08 23:09:45 +01:00
Sebastian McKenzie
2fd1b2a484 rename category metadata option to group 2015-05-08 22:54:15 +01:00
Sebastian McKenzie
8f9d02d689 further work splitting up transformers into their own "category" in order of what they need and what they actually do 2015-05-08 22:53:31 +01:00
Sebastian McKenzie
b376b6b33b store uncollapsed transformer pass stack so we have access to it when calling pre and post methods 2015-05-08 22:53:03 +01:00
Sebastian McKenzie
8292d6d8ad fix replacement requeue exiting too early 2015-05-08 22:52:38 +01:00
Sebastian McKenzie
d6a5c39079 update classes to reflect new transformer precedence 2015-05-08 22:52:19 +01:00
Sebastian McKenzie
2a9a59f784 remove incomplete ludicrous transformer 2015-05-08 22:52:02 +01:00
Sebastian McKenzie
abf4a5495a don't pretty print variable declarators in concise mode 2015-05-08 22:51:47 +01:00
Sebastian McKenzie
f8b8723bef Merge pull request #1483 from jquense/patch-1
Fix plugin api typo when an object is passed in
2015-05-08 22:26:45 +01:00
Jason Quense
6b9686f2dd Fix plugin api typo when an object is passed in 2015-05-08 17:25:14 -04:00
Sebastian McKenzie
4a439d8c8e update flow strip type annotations test 2015-05-08 15:52:08 +01:00
Sebastian McKenzie
c526a3eb04 move shadow-functions internal transformer to builtin-cleanup category 2015-05-08 15:51:56 +01:00
Sebastian McKenzie
ba516901af restructure transformers into multiple categories 2015-05-08 15:26:00 +01:00
Sebastian McKenzie
8f52229a86 add get function name to source map classes test 2015-05-08 15:25:50 +01:00
Sebastian McKenzie
5b793f8882 fix TraversalPath#_getPattern incorrectly iterating over the parts 2015-05-08 15:25:34 +01:00
Sebastian McKenzie
b31c14c52a Merge branch 'master' into single-pass 2015-05-08 00:24:33 +01:00
Sebastian McKenzie
78b72512cb better verify the type of the new node before requeueing it and also stop current node traversal on skip 2015-05-08 00:24:04 +01:00
Sebastian McKenzie
2fbb3cad9f add isUser and isGenerated path methods 2015-05-08 00:23:28 +01:00
Sebastian McKenzie
2621081a13 merge in astVisitor in runtime transformer - unsure why this was separate in the first place 2015-05-08 00:23:00 +01:00
Sebastian McKenzie
8daf95bf59 name additional methods that are now covered since the naming is done in tandem 2015-05-08 00:22:43 +01:00
Sebastian McKenzie
6e8ab16b25 run es6.spec.blockScoping transformer on exit rather than enter 2015-05-08 00:22:23 +01:00
Sebastian McKenzie
a5cda5caa7 hoist param declaration when performing tco - fixes #1478 2015-05-07 23:14:03 +01:00
Sebastian McKenzie
13a6c69668 add node existence check to each visitor call 2015-05-07 23:02:40 +01:00
Sebastian McKenzie
380293d030 add transformer dependencies - fixes #1477 2015-05-07 21:35:12 +01:00
Sebastian McKenzie
0b15a97013 Merge branch 'master' into single-pass 2015-05-07 20:15:34 +01:00
Sebastian McKenzie
11af066956 5.2.17 2015-05-07 20:15:17 +01:00
Sebastian McKenzie
d7b4d342c3 v5.2.17 2015-05-07 20:12:47 +01:00
Sebastian McKenzie
77aeebe2a8 add Super node type to ast-types patch 2015-05-07 20:11:37 +01:00
Sebastian McKenzie
c3a08d413f attach auxiliary comment to function declaration helpers - fixes #1476 2015-05-07 20:11:31 +01:00
Sebastian McKenzie
23ac2319af add Super node type to ast-types patch 2015-05-07 20:11:14 +01:00
Sebastian McKenzie
a1bc0704ab attach auxiliary comment to function declaration helpers - fixes #1476 2015-05-07 20:11:02 +01:00
Sebastian McKenzie
0bbfd427af do module formatter on program exit rather than entrance 2015-05-07 16:23:47 +01:00
Sebastian McKenzie
f17b268a71 do member expression and property literal conversion to computed on exit rather than on entrance 2015-05-07 16:23:33 +01:00
Sebastian McKenzie
9ffc265bea don't requeue node unless the type has changed 2015-05-07 16:01:00 +01:00
Sebastian McKenzie
6f664ca64e merge internal transformers into single traversal pass 2015-05-07 15:53:22 +01:00
Sebastian McKenzie
8a4a76000d correctly arrayify commander extensions - closes #1470, fixes #1460 2015-05-07 13:55:12 +01:00
Sebastian McKenzie
e83daf87d4 add this.stop() to secondary strict transformer #1465 2015-05-07 08:38:46 +01:00
Sebastian McKenzie
8ed90d3af2 ignore parameter bindings in minification.deadCodeElimination transformer - fixes #1464 2015-05-07 01:58:54 +01:00
Sebastian McKenzie
0bb311f8ce 5.2.16 2015-05-06 16:45:32 +01:00
Sebastian McKenzie
53f0f0302b v5.2.16 2015-05-06 16:44:28 +01:00
Sebastian McKenzie
c25a5d2480 add 5.2.16 changelog 2015-05-06 16:43:21 +01:00
Sebastian McKenzie
fc8540d88a inherit destructuring param replacement ref from original param - fixes #1461 2015-05-06 16:29:54 +01:00
Sebastian McKenzie
31a4195c81 fix incorrect extensions variable reference - fixes #1460 2015-05-06 16:23:15 +01:00
Sebastian McKenzie
bf0e4ede00 pass correct function scope to nameMethod.property when naming class methods - fixes #1456 2015-05-06 16:03:15 +01:00
Sebastian McKenzie
3757bc6b9a reverse method decorators - fixes #1457 2015-05-06 15:57:21 +01:00
Sebastian McKenzie
2e01f220da Merge branch 'master' of github.com:babel/babel 2015-05-06 15:44:05 +01:00
Sebastian McKenzie
8ae4e1fdf2 add --harmony_rest_parameters flag to babel-node - fixes #1446 2015-05-06 15:43:51 +01:00
Sebastian McKenzie
f6219ec15a Merge pull request #1455 from monsanto/fix-async-constructor
Disallow async constructors
2015-05-06 15:12:12 +01:00
Christopher Monsanto
6a82eb5a5c disallow async constructors -- fixes #1454 2015-05-06 02:50:11 -04:00
Sebastian McKenzie
a241300ff1 force plugins to be ran at all times - fixes #1450 2015-05-06 01:14:17 +01:00
Sebastian McKenzie
d5548a6ff9 5.2.15 2015-05-05 15:41:57 +01:00
Sebastian McKenzie
ba6cb112c3 v5.2.15 2015-05-05 15:41:00 +01:00
Sebastian McKenzie
8f1bb84930 add 5.2.15 changelog 2015-05-05 15:39:05 +01:00
Sebastian McKenzie
235726eee6 remove unnecessary descriptor.initializer check 2015-05-05 15:38:17 +01:00
Sebastian McKenzie
08183ef490 don't add descriptor if we can't find it 2015-05-05 15:37:24 +01:00
Sebastian McKenzie
dc6fc3b30a fix browser-polyfill.js post-make publish purging 2015-05-05 15:37:11 +01:00
Sebastian McKenzie
76f2eb5684 5.2.14 2015-05-05 15:14:59 +01:00
Sebastian McKenzie
4f33687957 v5.2.14 2015-05-05 15:12:19 +01:00
Sebastian McKenzie
74f37fe0a3 expose unminified and minified builds of dist scripts - fixes #1444 2015-05-05 15:11:00 +01:00
Sebastian McKenzie
cc5e4bce52 fix object/property decorator interop 2015-05-05 14:42:41 +01:00
Sebastian McKenzie
f441a7cae8 don't do pretty variable declaration formatting if retainLines is enabled 2015-05-05 14:04:51 +01:00
Sebastian McKenzie
fc2be81c43 expose retainLines option to CLI 2015-05-05 14:04:36 +01:00
Sebastian McKenzie
1277a8f67f 5.2.13 2015-05-05 08:58:35 +01:00
Sebastian McKenzie
86c6d4e769 v5.2.13 2015-05-05 08:57:41 +01:00
Sebastian McKenzie
bf2d527cfe upgrade esquery 2015-05-05 08:56:58 +01:00
Sebastian McKenzie
6b59ea8eac add 5.2.13 changelog 2015-05-05 08:56:28 +01:00
Sebastian McKenzie
72e3cb9243 trigger a reference for export declarations 2015-05-05 08:54:51 +01:00
Sebastian McKenzie
5e5ede6058 move down _modules transformer 2015-05-05 08:54:38 +01:00
Sebastian McKenzie
d25944ea1f move utility transformers to top - fixes #1440 2015-05-05 08:39:46 +01:00
Sebastian McKenzie
fce2aa8fa3 add support for esquery 2015-05-05 03:21:31 +01:00
Sebastian McKenzie
0112c63779 consolidate the concept of "virtual types" 2015-05-05 02:33:49 +01:00
Sebastian McKenzie
6a4e93bf0f make visitor validation more anal, add node type wrappers, add mixin support to visitor explosion, allow visitor entrance/exit to provide an array of callbacks to use rather than limiting it to a single callback 2015-05-05 01:44:01 +01:00
Sebastian McKenzie
4328e920d2 5.2.12 2015-05-05 00:15:48 +01:00
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
Lukáš Mladý
6491018c21 Add failing tests that document ES 6 generators bug 2015-04-08 14:14:45 +02: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
dff3751e7f v5.0.4 2015-04-03 15:31:08 +11: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
Sebastian McKenzie
9f467ef7c0 5.0.3 2015-04-03 15:29:16 +11:00
Sebastian McKenzie
a52f9ab346 add 5.0.4 changelog 2015-04-03 15:29:11 +11:00
Sebastian McKenzie
5ccbed585b Merge pull request #1140 from cesarandreu/patch-2
Avoid searching .babelrc if breakConfig is set
2015-04-03 15:27:24 +11:00
Sebastian McKenzie
f7c7da7526 v5.0.3 2015-04-03 15:24:47 +11:00
Cesar Andreu
ed58c80c64 Avoid searching .babelrc if breakConfig is set 2015-04-02 21:24:06 -07:00
Sebastian McKenzie
d7fb9f67df t push
make publish
Merge branch 'master' of github.com:babel/babel
2015-04-03 15:23:03 +11:00
Sebastian McKenzie
eef6002324 add 5.0.3 changelog 2015-04-03 15:22:36 +11:00
Sebastian McKenzie
32bcf4c3a5 Merge pull request #1139 from cesarandreu/patch-3
Add breakConfig to options.json
2015-04-03 15:19:41 +11:00
Sebastian McKenzie
86060cb0ce switch back to global uid registry - fixes #1136 2015-04-03 15:18:04 +11:00
Cesar Andreu
66a836d435 breakConfig should be hiddebn 2015-04-02 21:14:26 -07:00
Cesar Andreu
ecc14c2a31 Add breakConfig to options.json 2015-04-02 21:09:56 -07:00
Sebastian McKenzie
7e9b60fba5 turn into absolute location if not for rc resolution - fixes #1137 2015-04-03 15:03:00 +11:00
Sebastian McKenzie
313f1e755a 5.0.2 2015-04-03 06:55:53 +11:00
Sebastian McKenzie
8c7ef0a2c9 v5.0.2 2015-04-03 06:53:46 +11:00
Sebastian McKenzie
8f79010b16 add regression test for #1130 2015-04-03 06:52:23 +11:00
Sebastian McKenzie
022e6f26aa fix not being able to call non-writable methods - fixes #1133 2015-04-03 06:52:17 +11:00
Sebastian McKenzie
138fa6c9f8 add 5.0.1 changelog 2015-04-03 06:52:02 +11:00
Sebastian McKenzie
c07704cc80 remove parentPath existence check 2015-04-03 06:48:46 +11:00
Sebastian McKenzie
bf811ea34a 5.0.1 2015-04-03 06:47:47 +11:00
Sebastian McKenzie
8af3ea1c43 fix duplicate declaration regression - fixes #1130 2015-04-03 06:47:41 +11:00
Sebastian McKenzie
5fbe147a5e v5.0.1 2015-04-03 05:49:16 +11:00
Sebastian McKenzie
a9e214b1db fix build cli script 2015-04-03 05:48:02 +11:00
Sebastian McKenzie
6812fca7a9 v5.0.0 2015-04-03 05:36:47 +11:00
Sebastian McKenzie
ebc42f5ce0 add setInterval and setTimeout noop to browserify test pending a new core-js patch release 2015-04-03 04:53:13 +11:00
Sebastian McKenzie
b12a97ddd6 rename returnUsedHelpers to metadataUsedHelpers 2015-04-03 04:50:19 +11:00
Sebastian McKenzie
e8daad38a7 remove beta tag from npm publish 2015-04-03 04:39:45 +11:00
Sebastian McKenzie
c6c0bc07e2 fix empty whitelist in build-external-helpers - fixes #1129 2015-04-03 04:39:39 +11:00
Sebastian McKenzie
c60f3f0e34 fix runtime transformer and update tests 2015-04-03 02:56:32 +11:00
Sebastian McKenzie
07078138f3 update to core-js 0.8.0 2015-04-03 02:37:02 +11:00
Sebastian McKenzie
cb0026edfe fix plugin api 2015-04-03 01:53:25 +11:00
Sebastian McKenzie
ab55ec4ea2 fix afterPlugins variable 2015-04-03 00:33:54 +11:00
Sebastian McKenzie
e164123ce9 remove packages README 2015-04-03 00:33:48 +11:00
Sebastian McKenzie
f42bacf4f6 fix syntax error in File 2015-04-03 00:02:13 +11:00
Sebastian McKenzie
46adb07d41 add plugin api - closes #987 2015-04-02 23:49:24 +11:00
Sebastian McKenzie
e10bdf7c5b add try-catch to util.resolveRelative 2015-04-02 23:44:29 +11:00
Sebastian McKenzie
83eea2acc7 add babel-cli init to bootstrap 2015-04-02 23:34:28 +11:00
Sebastian McKenzie
8bdd4cc559 fix babel-external-helpers path in Makefile 2015-04-02 23:16:01 +11:00
Sebastian McKenzie
15d31b5608 move babel cli into separate folder #1097 2015-04-02 23:12:05 +11:00
Sebastian McKenzie
9ed6a7b650 simplify dynamic imports 2015-04-02 22:03:57 +11:00
Sebastian McKenzie
01a2aa7dd1 support multiple export specifier remapping 2015-04-02 20:25:05 +11:00
Sebastian McKenzie
33fde5f143 update 5.0.0 changelog 2015-04-02 20:09:29 +11:00
Sebastian McKenzie
682c775a97 fix babel-node require test to reflect import hoisting 2015-04-02 19:34:21 +11:00
Sebastian McKenzie
4846b89931 export options in browser api 2015-04-02 19:28:18 +11:00
Sebastian McKenzie
25312396a5 add live binding support to modules - fixes #1117, fixes #1057, closes #1118 2015-04-02 19:28:11 +11:00
Sebastian McKenzie
cfff7aa6fb simplfy function name inference wrapper - closes #1002 2015-04-02 02:37:00 +11:00
Sebastian McKenzie
f88a4147a6 traceur upstream sync 2015-04-02 02:21:12 +11:00
Sebastian McKenzie
3c343adf33 add support for super update and assignment expressions - fixes #426 2015-04-02 02:21:04 +11:00
Sebastian McKenzie
269587cde5 hoist block iife to avoid creating a new one for each loop iteration 2015-04-02 00:58:01 +11:00
Sebastian McKenzie
121ba8c381 fix loop block scoping, check for exact reference when doing closure detection - fixes #973 2015-04-02 00:04:10 +11:00
Sebastian McKenzie
563a427b69 add ludicrous transformer 2015-04-01 23:23:09 +11:00
Sebastian McKenzie
658164a0d2 fix booleanString compact option 2015-04-01 23:21:32 +11:00
Sebastian McKenzie
135ba84abb fix es7 export extensions compound list 2015-04-01 23:21:16 +11:00
Sebastian McKenzie
76573093bd add umd globals export - fixes #375 2015-04-01 23:02:03 +11:00
Sebastian McKenzie
22b88487ee remove use strict directive from react test 2015-04-01 14:12:11 +11:00
Sebastian McKenzie
3686951dc1 5.0.0-beta4 2015-04-01 14:07:41 +11:00
Sebastian McKenzie
f43ca32ff5 move es6 tail call test 2015-04-01 14:07:32 +11:00
Sebastian McKenzie
424a59a856 dont coerce jsx expression containers - fixes #1126 2015-04-01 14:07:26 +11:00
Sebastian McKenzie
5f159853d5 fix paramless async calls 2015-04-01 13:57:59 +11:00
Sebastian McKenzie
f9c56c6dd7 properly export acorn 2015-04-01 13:51:15 +11:00
Sebastian McKenzie
613e77cd50 v5.0.0-beta4 2015-04-01 00:46:35 +11:00
Sebastian McKenzie
27c97aab34 reneable seting of type annotations 2015-04-01 00:44:54 +11:00
Sebastian McKenzie
ad857dddd1 add verification check to deprecation 2015-04-01 00:39:20 +11:00
Sebastian McKenzie
d9762e9049 expose options 2015-04-01 00:39:12 +11:00
Sebastian McKenzie
088846a347 Merge branch 'master' of github.com:babel/babel 2015-03-31 23:47:55 +11:00
Sebastian McKenzie
7fc28cb63f move deprecation check down 2015-03-31 23:47:40 +11:00
Sebastian McKenzie
3323e0f3a5 add descriptions to remaining options 2015-03-31 23:39:02 +11:00
Sebastian McKenzie
8c09a2198a fix es7.exportExtensions stage 2015-03-31 23:38:51 +11:00
Sebastian McKenzie
eeb5b8d0c3 add es1.ludicrous transformer skeleton 2015-03-31 23:38:40 +11:00
Sebastian McKenzie
19e8274e79 make it abundantly clear in the readme that the issue tracker is not for support and questions. i'm spread thin enough and don't need to be doing support for everyone, i wish i could but sadly i can't :( 2015-03-31 23:38:16 +11:00
Sebastian McKenzie
6353abfd1b move remapAssignments to init method in the module formatter - fixes #1124 2015-03-31 19:28:42 +11:00
Sebastian McKenzie
ee14770a5c fix variable declaration semicolons in for loops 2015-03-31 10:44:31 +11:00
Sebastian McKenzie
d3b9b7251e remove 6to5 binaries 2015-03-31 10:44:10 +11:00
Sebastian McKenzie
3f7f89a6b9 make babel.json filename hidden - #1093 2015-03-31 05:27:22 +11:00
Sebastian McKenzie
7476b8c6a3 don't coerce compiled sibling children to a single literal - @spicyj 2015-03-31 03:49:41 +11:00
Sebastian McKenzie
1ef41b6f32 optimisation.react.inlineElements: move children into props and leave children out if the element has none - @spicyj 2015-03-31 03:31:27 +11:00
Sebastian McKenzie
6bc2bfce7d rename runtimeES3 transformer to es3.runtime 2015-03-31 02:34:32 +11:00
Sebastian McKenzie
153e81261c inherit string quotes - fixes #991 2015-03-31 02:09:56 +11:00
Sebastian McKenzie
b8f2a27e90 take export default specifiers into consideration in t.isSpecifierDefault 2015-03-31 01:41:04 +11:00
Sebastian McKenzie
2f25c3bd17 use users home directory to store babel/register cache - fixes #1093 2015-03-31 01:40:53 +11:00
Sebastian McKenzie
59e07b65dd downgrade core-js 2015-03-31 01:34:38 +11:00
Sebastian McKenzie
769f7fb81d update runtime tests 2015-03-31 01:30:51 +11:00
Sebastian McKenzie
7895857624 remove dead tests 2015-03-31 01:27:48 +11:00
Sebastian McKenzie
80fed5f395 take into consideration default export specifiers in common module formatter - fixes #1071 2015-03-31 01:27:43 +11:00
Sebastian McKenzie
1c7fabdd6d add runtimeES3 transformer 2015-03-31 01:20:14 +11:00
Sebastian McKenzie
12f8fa229d remove redundant spec.functionName tests 2015-03-30 21:49:58 +11:00
Sebastian McKenzie
c6546264d2 split up spec.functionName tests 2015-03-30 21:46:08 +11:00
Sebastian McKenzie
86cc5875cf re-enable shit safari test #1121 2015-03-30 21:46:01 +11:00
Sebastian McKenzie
9ea999b261 clean up class property initializers, handle scope collisions in constructors 2015-03-30 20:32:14 +11:00
Sebastian McKenzie
f81e841283 don't block hoist in system module formatter when runtime transformer is enabled - #1105 2015-03-30 18:24:44 +11:00
Sebastian McKenzie
c14ffb8319 Merge branch 'guybedford-system-unhoist-generators' into experimental 2015-03-30 18:16:44 +11:00
Sebastian McKenzie
b9f4fe86f1 merge 2015-03-30 18:16:28 +11:00
Sebastian McKenzie
56ada634b4 Merge pull request #1112 from ben-ng/patch-1
Incorrect package path
2015-03-30 18:13:37 +11:00
Sebastian McKenzie
c4d68897b3 rename own binding inside constructor if it collides with our class reference - fixes #1077 2015-03-30 18:06:59 +11:00
Sebastian McKenzie
1641caedc4 retain binding values on iteration if reassigned - fixes #1078 2015-03-30 18:02:21 +11:00
Sebastian McKenzie
3d6e722fc7 fix es6.spec.blockScoping transformer reference 2015-03-30 16:58:51 +11:00
Sebastian McKenzie
253493a43f fix es6.blockScopingTDZ transformer filename 2015-03-30 16:55:20 +11:00
Sebastian McKenzie
66471f044a add deprecation alais for es6.blockScopingTDZ 2015-03-30 16:53:46 +11:00
Sebastian McKenzie
5fa227eb73 fix module names for amd/umd tests 2015-03-30 16:53:06 +11:00
Sebastian McKenzie
f3b50f0bb9 rename es6.blockScopingTDZ to es6.spec.blockScoping 2015-03-30 16:52:58 +11:00
Sebastian McKenzie
92bba76bd5 fix test fixture transformer folder names 2015-03-30 16:44:55 +11:00
Sebastian McKenzie
46462e3e69 add optional scope parameter to TraversalPath#hoist 2015-03-30 16:41:29 +11:00
Sebastian McKenzie
bc155f956c add es6.spec.templateLiterals transformer and rename es6.symbols to es6.spec.symbols 2015-03-30 16:41:13 +11:00
Sebastian McKenzie
dc1ba58705 fix experimental arg in babel-node 2015-03-30 07:34:51 +11:00
Sebastian McKenzie
99e274921f remove experimental option in favor of a stage option 2015-03-30 07:30:37 +11:00
Sebastian McKenzie
862bd6d92a use kebab case instead of camelcase for no cli options 2015-03-30 06:43:23 +11:00
Sebastian McKenzie
46d991e3e9 add nonStandard option - @stefanpenner 2015-03-30 06:41:55 +11:00
Sebastian McKenzie
8e1b6df970 properly handle export default shorthand, also consider export default foo; and export { foo as default } to be equivalent 2015-03-30 06:31:41 +11:00
Sebastian McKenzie
f9c8d7d1fd fix incorrect interpreation of export default shorthand, update to new ast definitions - #1091 2015-03-30 06:08:37 +11:00
Sebastian McKenzie
eb2f61e43f add class property initializer and decorator parser tests 2015-03-30 03:52:39 +11:00
Sebastian McKenzie
afe8792ba4 fix names for export declaration generation tests 2015-03-30 03:38:24 +11:00
Sebastian McKenzie
42a2430d2c add support for export extensions https://github.com/leebyron/ecmascript-more-export-from - closes #1091 2015-03-30 03:38:14 +11:00
Sebastian McKenzie
c4d260231b fix optimisation.react.constantElements test fixture names 2015-03-30 01:22:59 +11:00
Sebastian McKenzie
ca5daca5dd add optimisation.react.constantElements transformer - facebook/react#3228 2015-03-30 01:22:45 +11:00
Sebastian McKenzie
3952eefd01 remove some dead code 2015-03-30 00:18:37 +11:00
Sebastian McKenzie
52c6fe2bc1 add a path hoisting mechanism that will hoist a node to it's highest compatible scope, a compatible scope is considered to be one where all references inside can be resolved to, also adds an optimisation.react.constantElements transformer that uses this to much success facebook/react#3226 2015-03-30 00:16:19 +11:00
Sebastian McKenzie
6a698f7ae4 move class property code gen to classes file 2015-03-29 19:31:02 +11:00
Sebastian McKenzie
2b0c07c2e7 only push the initializer function if required 2015-03-29 19:30:53 +11:00
Sebastian McKenzie
e27e7facac add decorator tests 2015-03-29 19:30:41 +11:00
Sebastian McKenzie
0dd32e7d9c fix class decorator methods 2015-03-29 19:30:34 +11:00
Sebastian McKenzie
286ae68da2 make constants and module imports synonymous - closes #954 2015-03-29 17:36:23 +11:00
Sebastian McKenzie
e26f994075 add existence check when merging source map - fixes #1111 2015-03-29 17:17:43 +11:00
Sebastian McKenzie
94f005e324 clean up flow object type property semicolons 2015-03-29 17:14:46 +11:00
Sebastian McKenzie
93e37aaaf1 inherit comments from class method 2015-03-29 17:09:03 +11:00
Sebastian McKenzie
e4db93f6a5 fix flow test range end of object property nodes 2015-03-29 17:05:14 +11:00
Sebastian McKenzie
c9243e8e97 fixes #1114
- The visitor keys for `ObjectTypeAnnotation`s were incorrect so those nodes weren't being traversed so comments weren't attached for them.
 - The type parser wasn't eating the semicolons for the nodes so the `end` location of each of the type properties wasn't accurate which threw off the code generation newline algorithm.
 - Type properties hadn't been given the `UserWhitespacable` alias.
2015-03-29 16:44:36 +11:00
Sebastian McKenzie
bbba374783 5.0.0-beta3 2015-03-29 16:10:17 +11:00
Sebastian McKenzie
7d95fddbed add do expression definition to ast-types - fixes #1113 2015-03-29 16:10:07 +11:00
Ben
617ed09227 Incorrect package path
I'm pretty sure that this is a mistake, since the path doesn't exist relative to this file. Is it supposed to point to the babel-core package.json like this?
2015-03-28 15:32:07 -04:00
Sebastian McKenzie
6d7887cfe2 v5.0.0-beta3 2015-03-29 01:52:30 +11:00
Sebastian McKenzie
b8e9171aaa start on changelog 2015-03-29 01:50:54 +11:00
Sebastian McKenzie
22118c0be0 add Immutable alias keys 2015-03-29 01:50:45 +11:00
Sebastian McKenzie
3754f7615f make insertBefore functionality the same as insertBefore in traversal path and add getStatementParent method 2015-03-29 01:50:36 +11:00
Sebastian McKenzie
b54901018b Merge pull request #1108 from ArrestedDevelopment/jsxpragma-option
JSX Transformer: Add 'jsxPragma' option
2015-03-28 22:17:18 +11:00
ArrestedDevelopment
121b9ca063 Add tests for JSX Pragma option 2015-03-28 02:20:01 -06:00
ArrestedDevelopment
4988a27b6c JSX Transformer: Add 'jsxPragma' option 2015-03-28 01:41:16 -06:00
Sebastian McKenzie
e0297e08b8 Merge pull request #1103 from joliss/makefile
Disable parallelism in Makefile
2015-03-28 08:39:08 +11:00
Sebastian McKenzie
79005d2f03 Merge pull request #1102 from joliss/npmignore
Prefix all npmignored files with "/"
2015-03-28 08:38:56 +11:00
Sebastian McKenzie
5cce8c32a4 Merge pull request #1101 from joliss/make-clean
Delete lib directory on `make clean`
2015-03-28 08:38:37 +11:00
Sebastian McKenzie
95b1accddc Merge pull request #1104 from joliss/travis
Re-enable experimental branch on Travis
2015-03-28 08:38:26 +11:00
Jo Liss
6149e6325f Re-enable experimental branch on Travis 2015-03-27 21:34:38 +00:00
Jo Liss
4c9d4d0378 Disable parallelism in Makefile
When MAKEFLAGS=-j2 is set in the environment, `make test-travis` can fail
surprisingly, because targets are executed in parallel.
2015-03-27 21:28:07 +00:00
Jo Liss
2e599bef4f Prefix all npmignored files with "/"
This in particular stops lib/acorn/src from being incorrectly matched by "src".
2015-03-27 21:02:28 +00:00
Jo Liss
885da177f9 Delete lib directory on make clean 2015-03-27 20:52:00 +00:00
Sebastian McKenzie
463112517f 5.0.0-beta2 2015-03-28 05:48:27 +11:00
Sebastian McKenzie
8f10dc5c39 v5.0.0-beta2 2015-03-28 05:46:57 +11:00
Sebastian McKenzie
0f99bbe293 fix test tmp directory gitignore 2015-03-28 05:45:46 +11:00
Sebastian McKenzie
0a5d2c098f add tag beta to publish scripts 2015-03-28 05:45:37 +11:00
Sebastian McKenzie
dcf4381e26 5.0.0-beta1 2015-03-28 05:45:22 +11:00
Sebastian McKenzie
543582ef47 fix helper filename in build-runtime script 2015-03-28 05:42:55 +11:00
Sebastian McKenzie
a4db58ccaa v5.0.0-beta1 2015-03-28 05:40:16 +11:00
Sebastian McKenzie
d3971e0874 move es6.arrowFunctions transformer up 2015-03-28 05:38:31 +11:00
Sebastian McKenzie
ad98186afc remove redundant semicolons from export declarations 2015-03-28 05:38:22 +11:00
Sebastian McKenzie
df251fbfff fix test paths to reflect new test directory structure 2015-03-28 05:38:12 +11:00
Sebastian McKenzie
dfbcf95b0e disable sourcemap stdin tests 2015-03-28 05:37:55 +11:00
Sebastian McKenzie
07646475d9 fix spread binding with the wrong context 2015-03-28 05:37:38 +11:00
Sebastian McKenzie
9bc67c28e3 fix path api usage in es6.forOf 2015-03-28 05:37:15 +11:00
Sebastian McKenzie
c2990d3548 add array cache to es6.destructuring to avoid running toArray multiple times 2015-03-28 05:37:06 +11:00
Sebastian McKenzie
803f8a3bbc fix paths in api test 2015-03-28 04:38:26 +11:00
Sebastian McKenzie
ee6efee4f8 disable es6 do expressions and decorators tests 2015-03-28 04:37:30 +11:00
Sebastian McKenzie
3f144e6e74 ensure that nodes are only traversed once per context 2015-03-28 04:34:05 +11:00
Sebastian McKenzie
afedfe15ae fix external helper build script to reflect filename schema changes 2015-03-28 04:08:02 +11:00
Sebastian McKenzie
b522294d3c fix helper slice filename 2015-03-28 04:07:44 +11:00
Sebastian McKenzie
954af72476 update various tests to reflect the new architecture 2015-03-28 04:00:20 +11:00
Sebastian McKenzie
de42a6f796 add existence check for child and parent when inheriting comments 2015-03-28 04:00:02 +11:00
Sebastian McKenzie
06a58f228c add TraversalPath#replaceInline, fix traversal path not updating sibling keys correctly 2015-03-28 03:59:51 +11:00
Sebastian McKenzie
7a44576c26 cache rc json 2015-03-28 03:59:14 +11:00
Sebastian McKenzie
eaa3865427 remove es7.classProperties check from parser 2015-03-28 03:59:01 +11:00
Sebastian McKenzie
b83907cc67 restructure testing infrastructure to be more modular 2015-03-28 01:21:48 +11:00
Sebastian McKenzie
a3620a58f8 add externalHelpers to source maps tests 2015-03-28 00:26:11 +11:00
Sebastian McKenzie
67a12f03fa use replaceWithNodes rather than replace in es6.forOf transformer 2015-03-28 00:26:04 +11:00
Sebastian McKenzie
c49871d33c stylistic changes to tests 2015-03-28 00:25:45 +11:00
Sebastian McKenzie
c828688d21 add existence check to t.inherits 2015-03-28 00:23:07 +11:00
Sebastian McKenzie
bd052aea50 inherit first replacement node from the current node 2015-03-28 00:22:59 +11:00
Sebastian McKenzie
ed74ccaa7d add support for decorators before class exports 2015-03-28 00:22:38 +11:00
Sebastian McKenzie
f3c9551b75 add MetaProperty visitor keys 2015-03-28 00:22:18 +11:00
Sebastian McKenzie
710a7f882d add loose mode for es6.spread and es6.destructuring that assumes all values are arrays - emberjs/ember.js#10730 2015-03-28 00:21:37 +11:00
Sebastian McKenzie
902ebd3fe7 switch back helpers to Array.isArray 2015-03-28 00:21:15 +11:00
Sebastian McKenzie
23c20cc47c inherit from the user constructor properly 2015-03-26 01:02:47 +11:00
Sebastian McKenzie
9b627ace5d impose a strict API for traversal paths and ensure AST doesn't have holes mid-transform 2015-03-26 01:02:30 +11:00
Sebastian McKenzie
4fa17341f5 add support for object expressions and patterns to scope.generateUidBasedOnNode 2015-03-26 01:00:32 +11:00
Sebastian McKenzie
1e019c0f16 realign alias keys data 2015-03-26 01:00:12 +11:00
Sebastian McKenzie
ce25ebacbf only coerce the right side in template literal implosion 2015-03-26 00:59:58 +11:00
Sebastian McKenzie
daecec2a86 better parsing of decorators - support class expressions 2015-03-26 00:58:38 +11:00
Sebastian McKenzie
238f9c2e7e call resolveModuleSource on dynamic imports - fixes #1085 2015-03-26 00:50:58 +11:00
Sebastian McKenzie
bc5f2b9be6 add param to list of duplicate declaration kinds - fixes #1084 2015-03-26 00:48:17 +11:00
Sebastian McKenzie
5390715705 update tests to latest experimental changes 2015-03-25 20:20:51 +11:00
Sebastian McKenzie
aa1333123c Merge branch 'master' into experimental
# Please enter a commit message to explain why this merge is necessary,
# especially if it merges an updated upstream into a topic branch.
#
# Lines starting with '#' will be ignored, and an empty message aborts
# the commit.
2015-03-25 14:17:46 +11:00
Sebastian McKenzie
048f9acc55 Merge pull request #1081 from babel/fix-tco-binding-clearing
Clear bindings immediately inside the TCO loop.
2015-03-25 14:16:46 +11:00
Brian Donovan
ed6421876a Clear bindings immediately inside the TCO loop.
We have to ensure that this happens before any potentially-hoisted
declarations from default parameters.

Closes #1080.
2015-03-24 20:15:54 -07:00
Sebastian McKenzie
e60c9fba6a better node injection mechanics that handle statement lists 2015-03-24 04:37:56 +11:00
Sebastian McKenzie
902db03e96 add loose mode to template literals 2015-03-24 03:34:42 +11:00
Sebastian McKenzie
de88b28988 add class property initializers, add more TraversalPath flexibility with additional node injection method 2015-03-24 03:34:34 +11:00
Sebastian McKenzie
0ee230d13c coerce template literal expressions to strings - fixes #1065 2015-03-23 22:04:40 +11:00
Sebastian McKenzie
c12cfe3ed0 make method definitions with expression bodies illegal - fixes #1066 2015-03-23 20:24:32 +11:00
Sebastian McKenzie
1376f2f18f move helper templates to a separate namespace 2015-03-23 17:26:54 +11:00
Sebastian McKenzie
972c621f59 remove template literals from bin 2015-03-23 17:26:31 +11:00
Sebastian McKenzie
5c41a33e41 save register cache on tick instead of sigint - fixes #1062 2015-03-23 17:26:08 +11:00
Sebastian McKenzie
bc6d01d6fc enable strict mode on babel-node eval flag - fixes #1060 2015-03-23 16:53:03 +11:00
Sebastian McKenzie
01463faf36 remove apply-constructor helper from es6.spread transformer - fixes #1052 2015-03-23 16:51:14 +11:00
Sebastian McKenzie
b234603e24 add callDelegate transformation helper - fixes #1064 2015-03-23 16:47:17 +11:00
Sebastian McKenzie
ca79fff0c4 remove acorn compiled source 2015-03-22 04:09:18 +11:00
Sebastian McKenzie
3c8f3cb521 update couple tests to reflect new statement explosion 2015-03-22 04:08:55 +11:00
Sebastian McKenzie
c9974a42ea remove legacy react metadata 2015-03-22 04:08:45 +11:00
Sebastian McKenzie
a87f6f6fdd clean up statement to expression explosion 2015-03-22 04:08:35 +11:00
Sebastian McKenzie
3d28ce7903 git ignore entire lib folder 2015-03-22 04:07:53 +11:00
Sebastian McKenzie
e04ecc79c7 add support for class decorators 2015-03-22 04:07:38 +11:00
Sebastian McKenzie
3e26511fb2 remove ShadowFunctionExpression 2015-03-22 04:07:00 +11:00
Sebastian McKenzie
9c3493e02f add do expressions 2015-03-22 04:06:15 +11:00
Sebastian McKenzie
a14e979897 use module syntax for strict module formatters 2015-03-21 15:27:32 +11:00
Sebastian McKenzie
a4ce653bed update tests to reflect fixed destructuring behaviour and statement to expression explosion 2015-03-21 15:27:13 +11:00
Sebastian McKenzie
70d068226a add ability to explode a list of statements when trying to replace an expression - damn this is powerful and allows some SUPER cool scenarios 2015-03-21 15:26:55 +11:00
Sebastian McKenzie
30b1c0154d update to modular acorn 2015-03-21 15:25:32 +11:00
Sebastian McKenzie
a602873281 update to latest acorn, better array shortcuts, don't add code frame to error message 2015-03-20 20:05:29 +11:00
Sebastian McKenzie
c8b88182f6 fix bin tests 2015-03-20 20:03:49 +11:00
Sebastian McKenzie
64f1c114c1 fix modules generation logic and remove dead node types 2015-03-19 03:17:28 +11:00
Sebastian McKenzie
4ac1a856ae fix remaining issues in estree port 2015-03-19 02:59:44 +11:00
Sebastian McKenzie
0e68b6ca11 add highlightErrors option to parser options 2015-03-19 02:59:30 +11:00
Sebastian McKenzie
2dccc8c919 more estree updates - finish flow parsing 2015-03-19 01:48:44 +11:00
Sebastian McKenzie
fdea18a289 properly support iterators in sliced-to-array helper... 2015-03-19 01:47:19 +11:00
Sebastian McKenzie
c3bdecbd25 move arrow functions transformer to before function names 2015-03-19 01:46:53 +11:00
Sebastian McKenzie
ee63fb52b7 check whitelist for existence rather than length - #1044 2015-03-19 01:46:10 +11:00
Sebastian McKenzie
8575392606 4.7.16 2015-03-18 23:37:24 +11:00
Sebastian McKenzie
d28583bea1 v4.7.16 2015-03-18 23:36:04 +11:00
Sebastian McKenzie
b166f35218 add typed arrays to native types list - #1043 2015-03-18 23:34:37 +11:00
Sebastian McKenzie
0914378bba add 4.7.16 changelog 2015-03-18 23:34:26 +11:00
Sebastian McKenzie
660d764390 remove loop check when aliasing breaks, continues etc - fixes #1051 2015-03-18 23:31:11 +11:00
Sebastian McKenzie
27206d6b7c add complete list of native constructors 2015-03-18 23:27:14 +11:00
Sebastian McKenzie
34dc56b435 Merge branch 'master' into experimental
# Conflicts:
#	src/babel/transformation/transformers/es7/abstract-references.js
#	src/babel/transformation/transformers/playground/mallet-operator.js
#	src/babel/transformation/transformers/playground/memoization-operator.js
#	src/babel/types/index.js
2015-03-18 19:18:25 +11:00
Sebastian McKenzie
d919d7837c 4.7.15 2015-03-18 19:17:07 +11:00
Sebastian McKenzie
b49cf4e779 v4.7.15 2015-03-18 19:16:01 +11:00
Sebastian McKenzie
e30dd7042b fix constructor spreading of collections #1043 2015-03-18 19:14:23 +11:00
Sebastian McKenzie
16d8d928e8 4.7.14 2015-03-18 19:14:02 +11:00
Sebastian McKenzie
4966028397 v4.7.14 2015-03-18 19:11:21 +11:00
Sebastian McKenzie
82e04fffac add 4.7.14 changelog 2015-03-18 19:08:53 +11:00
Sebastian McKenzie
a46313903d deprecate abstract references and remaining playground features 2015-03-18 19:08:05 +11:00
Sebastian McKenzie
68340b1288 add Promise to the list of native types - fixes #1043 2015-03-18 19:06:34 +11:00
Sebastian McKenzie
6a1b33b443 more updates to estree and new acorn 2015-03-18 19:02:15 +11:00
Sebastian McKenzie
df7524d909 update babel dev dependency and use for-of in sliced-to-array helper - fixes #1047 2015-03-18 19:01:58 +11:00
Sebastian McKenzie
2c39d406d1 move acorn into vendor 2015-03-18 19:01:30 +11:00
Sebastian McKenzie
2ff1a5d98b Merge branch 'master' into experimental
# Conflicts:
#	src/babel/transformation/transformers/internal/strict.js
2015-03-17 12:14:32 +11:00
Sebastian McKenzie
7f9fe4af15 4.7.13 2015-03-17 12:12:51 +11:00
Sebastian McKenzie
977290c7e4 v4.7.13 2015-03-17 12:11:26 +11:00
Sebastian McKenzie
ebbdb95278 add 4.7.13 changelog 2015-03-17 12:09:16 +11:00
Sebastian McKenzie
9b586c7587 add support for left side patterns in assignment pattern destructuring - fixes #1037 2015-03-17 12:03:13 +11:00
Brian Donovan
4b5ba6c8c6 Add a test for the this-spread fix in 976e8c1.
Addresses #1033.
2015-03-17 11:31:09 +11:00
Sebastian McKenzie
67efb1b427 ignore this expressions in Scope#generateTempBasedOnNode - fixes #1033 2015-03-17 11:31:00 +11:00
Sebastian McKenzie
bc9c1ab61e handle comments and use strict directives better - fixes #1030 2015-03-17 11:30:30 +11:00
Sebastian McKenzie
65ffe07551 remove react test option 2015-03-17 11:26:28 +11:00
Sebastian McKenzie
b606cc79ca remove class playground property initializer tests 2015-03-17 11:26:18 +11:00
Sebastian McKenzie
0e7fd0741d inject transformer parser plugins 2015-03-17 11:26:06 +11:00
Sebastian McKenzie
276cafaae1 Merge branch 'master' of github.com:babel/babel 2015-03-17 02:45:36 +11:00
Sebastian McKenzie
4f00de50d6 remove playground code gen, remove react metadata, start update of modules to estree 2015-03-17 02:45:16 +11:00
Brian Donovan
b07341a1f7 Add a note about using the --grep option to focus test runs. 2015-03-16 08:45:05 -07:00
Sebastian McKenzie
ec526f9224 embed acorn 2015-03-17 02:44:05 +11:00
Brian Donovan
76301a7713 Fix grammar. 2015-03-16 08:43:45 -07:00
Brian Donovan
67ac91815b Add a test for the this-spread fix in 976e8c1.
Addresses #1033.
2015-03-16 08:40:32 -07:00
Sebastian McKenzie
976e8c1cfd ignore this expressions in Scope#generateTempBasedOnNode - fixes #1033 2015-03-17 02:20:54 +11:00
Sebastian McKenzie
4d965b0f46 consolidate transformer metadata, remove abstract references, make react transformer optional 2015-03-16 19:26:50 +11:00
Sebastian McKenzie
b495370740 only compile babel folder in src 2015-03-16 19:25:58 +11:00
Sebastian McKenzie
b1c5915ed3 remove playground 2015-03-16 16:56:24 +11:00
Sebastian McKenzie
d94bb2e048 handle comments and use strict directives better - fixes #1030 2015-03-16 13:07:28 +11:00
Sebastian McKenzie
25fa10e592 fix syntax errors 2015-03-16 02:00:19 +11:00
Sebastian McKenzie
8d3a7acbd1 add symbol check to defineProperty helper - fixes #1010 2015-03-16 02:00:10 +11:00
Sebastian McKenzie
29d33dd31a Merge branch 'master' of github.com:babel/babel 2015-03-16 01:52:14 +11:00
Sebastian McKenzie
4afd0f553e Merge branch 'experimental'
# Conflicts:
#	src/babel/transformation/transformers/playground/method-binding.js
2015-03-16 01:51:52 +11:00
Sebastian McKenzie
1fb877e9f5 add highlightErrors option - fixes #837 2015-03-16 01:50:37 +11:00
Sebastian McKenzie
866d3a8eab move file into a separate folder 2015-03-16 01:45:08 +11:00
Sebastian McKenzie
76e1f0dd9f add babelrc to vendor 2015-03-16 01:44:17 +11:00
Sebastian McKenzie
1bbe52a022 split up module class declarations - fixes #1021 2015-03-16 01:44:10 +11:00
Sebastian McKenzie
cc0f43813c small style fixes 2015-03-16 01:26:26 +11:00
Sebastian McKenzie
b13b4bbfba add buildPass File check in preperation for plugin api 2015-03-16 01:25:59 +11:00
Sebastian McKenzie
1c6ac0a07a designate all playground and es7 transformers as optional 2015-03-16 01:25:25 +11:00
Sebastian McKenzie
5a319fd553 automate option generation 2015-03-16 01:23:57 +11:00
Sebastian McKenzie
a8cedf813b Revert "remove es7.abstractReferences, playground.methodBinding and playground.objectGetterMemoisation"
This reverts commit f4ce216d1c.
2015-03-16 01:02:35 +11:00
Sebastian McKenzie
9f037fa75e Merge pull request #1025 from thejameskyle/tjk/fix-flag
Correct --gdbjit v8 flag
2015-03-15 18:41:36 +11:00
James Kyle
8681a78618 Correct --gdbjit v8 flag 2015-03-15 00:39:48 -07:00
Sebastian McKenzie
2d72d423b3 Merge pull request #1024 from thejameskyle/tjk/1020-v8-flags
Add all v8 flags (node & iojs)
2015-03-15 18:35:19 +11:00
James Kyle
280964eafe Add all v8 flags (node & iojs). Fixes #1020 2015-03-15 00:33:39 -07:00
Sebastian McKenzie
5ee9b3c37e remove irrelevant test 2015-03-14 04:50:46 +11:00
Sebastian McKenzie
9676056f08 add note about member expression resolution 2015-03-14 04:50:23 +11:00
Sebastian McKenzie
080a844457 rename "reassigned" to "constant" to reflect purpose of the property better 2015-03-14 04:44:51 +11:00
Sebastian McKenzie
1f9f57a2a6 use paths in replace supers helper 2015-03-14 03:58:18 +11:00
Sebastian McKenzie
056b7fc634 hoist uids to their parent function 2015-03-14 03:58:02 +11:00
Sebastian McKenzie
547ecc2f73 update tests to reflect new for-of behaviour 2015-03-14 03:57:53 +11:00
Sebastian McKenzie
a1ab8fa0c1 remove playground.memoisationOperator deprecation message 2015-03-14 03:57:39 +11:00
Sebastian McKenzie
9e61a307d4 fix scope traversal 2015-03-14 03:34:02 +11:00
Sebastian McKenzie
d4d18f4230 Merge branch 'experimental' of github.com:babel/babel into experimental
# Conflicts:
#	src/babel/transformation/transformers/playground/object-getter-memoization.js
#	src/babel/traversal/path/index.js
#	src/babel/traversal/scope.js
2015-03-14 03:10:17 +11:00
Sebastian McKenzie
f4ce216d1c remove es7.abstractReferences, playground.methodBinding and playground.objectGetterMemoisation 2015-03-14 03:00:41 +11:00
Sebastian McKenzie
d71c72de3c 4.7.12 2015-03-14 02:39:09 +11:00
Sebastian McKenzie
b1c21b8d4d v4.7.12 2015-03-14 02:37:30 +11:00
Sebastian McKenzie
e9b0005cf5 deprecate playground.methodBinding 2015-03-14 02:35:10 +11:00
Sebastian McKenzie
63bac550cd Merge branch 'master' into experimental
# Conflicts:
#	src/babel/transformation/transformers/es6/for-of.js
#	src/babel/transformation/transformers/playground/object-getter-memoization.js
2015-03-14 02:34:03 +11:00
Sebastian McKenzie
d0b6aa9882 4.7.11 2015-03-14 02:30:59 +11:00
Sebastian McKenzie
0e877acfdf v4.7.11 2015-03-14 02:29:42 +11:00
Sebastian McKenzie
b670ee18df fix unicode regex test 2015-03-14 02:28:32 +11:00
Sebastian McKenzie
24807120bf fix unicode regexes stripping their unicode flag before being passed on two regexpu - fixes #1009 2015-03-14 02:26:20 +11:00
Sebastian McKenzie
33f7c0b67e rejigger regex flag pulling 2015-03-14 02:12:13 +11:00
Sebastian McKenzie
c23b47f796 4.7.10 2015-03-14 02:02:06 +11:00
Sebastian McKenzie
2871d8a710 v4.7.10 2015-03-14 01:57:26 +11:00
Sebastian McKenzie
3172b5de5d Merge branch 'master' of github.com:babel/babel 2015-03-14 01:53:15 +11:00
Sebastian McKenzie
2c05303813 deprecate some playground transformers 2015-03-14 01:52:59 +11:00
Sebastian McKenzie
75dda10057 add 4.7.10 changelog 2015-03-14 01:52:51 +11:00
Sebastian McKenzie
12664c6cd6 start migration of core from nodes to paths 2015-03-14 01:48:46 +11:00
Sebastian McKenzie
581f70c803 Merge pull request #1013 from Rich-Harris/patch-1
fix inputSourceMap option
2015-03-14 01:47:55 +11:00
Rich Harris
a00d2c33d8 fix inputSourceMap option
See #827 - it looks like `opts.inputSourceMap` is the wrong way round, babel should only use an input sourcemap if the `inputSourceMap` option is *not* `false`
2015-03-13 10:46:50 -04:00
Sebastian McKenzie
c906bd3edc start migration of core from nodes to paths 2015-03-14 01:00:02 +11:00
Sebastian McKenzie
27fc574e9f 4.7.9 2015-03-13 13:33:50 +11:00
Sebastian McKenzie
a3b1fcc79c v4.7.9 2015-03-13 13:30:14 +11:00
Sebastian McKenzie
491cb26c1f remove console.log 2015-03-13 13:29:13 +11:00
Sebastian McKenzie
7c3d052714 add 4.7.9 changelog 2015-03-13 13:27:40 +11:00
Sebastian McKenzie
4971d0c7f0 fix labeled nested for ofs - fixes #996 2015-03-13 13:25:37 +11:00
Sebastian McKenzie
eb4922b1ec update acorn-babel 2015-03-13 13:25:19 +11:00
Sebastian McKenzie
bb26183b44 set inputSourceMap to null by default 2015-03-13 13:14:17 +11:00
Sebastian McKenzie
4b066f7f1b add input sourcemap false option #827 2015-03-13 13:12:38 +11:00
Sebastian McKenzie
41a8257005 various cleanup, remove redundant whitespace, realign object keys etc 2015-03-13 01:09:04 +11:00
Sebastian McKenzie
b44ba25d11 separate binding logic from scope to a binding class, move binding type resolution to the path so it can be used on any expression - #653 2015-03-13 01:08:46 +11:00
Sebastian McKenzie
40a111abbf always resolve rc for absolute filenames 2015-03-13 01:07:33 +11:00
Sebastian McKenzie
9cff51915d switch scope tracking to a path based system 2015-03-12 14:35:55 +11:00
Sebastian McKenzie
3cd110a7c9 fix block scoping break switch collision - fixes #998 2015-03-12 14:35:30 +11:00
Sebastian McKenzie
a7f9e035a4 infer computed literal function names - fixes #993 2015-03-12 14:13:24 +11:00
Sebastian McKenzie
146b9e6708 4.7.8 2015-03-11 10:17:09 +11:00
Sebastian McKenzie
0953c48620 v4.7.8 2015-03-11 07:49:54 +11:00
Sebastian McKenzie
056b90831d manually define each property in computed class helper - fixes #984 2015-03-11 07:45:29 +11:00
Sebastian McKenzie
8ba276b209 4.7.7 2015-03-11 01:25:41 +11:00
Sebastian McKenzie
8eaa9d29e3 v4.7.7 2015-03-11 01:20:34 +11:00
Sebastian McKenzie
6212791356 fix types API exposure - babel/babel-eslint#8 2015-03-11 01:14:36 +11:00
Sebastian McKenzie
d436d32d82 4.7.6 2015-03-11 00:13:03 +11:00
Sebastian McKenzie
2a29f70bba v4.7.6 2015-03-11 00:11:35 +11:00
Sebastian McKenzie
6ccb8957bd add 4.7.6 changelog 2015-03-11 00:09:52 +11:00
Sebastian McKenzie
dc45415ee0 hoist esModule to the top 2015-03-11 00:08:06 +11:00
Sebastian McKenzie
98ca541fde restructure types 2015-03-11 00:04:06 +11:00
Sebastian McKenzie
8328f638c2 add support for if and block statements to t.toSequenceExpression 2015-03-10 17:20:26 +11:00
Sebastian McKenzie
5586ce280f move build-external-helpers to tools 2015-03-10 17:20:14 +11:00
Sebastian McKenzie
0ca71f5e15 add transformation logger 2015-03-10 17:19:51 +11:00
Sebastian McKenzie
212776e220 remove detection 2015-03-10 17:19:35 +11:00
Sebastian McKenzie
4a95a9ec8f remove duplicate insert_final_newline 2015-03-10 17:19:23 +11:00
Sebastian McKenzie
45953ffc8a 4.7.5 2015-03-10 13:39:04 +11:00
Sebastian McKenzie
9c79290bb2 v4.7.5 2015-03-10 13:20:20 +11:00
Sebastian McKenzie
cfdf6b7385 add 4.7.5 changelog 2015-03-10 13:12:19 +11:00
Sebastian McKenzie
907e0e0f86 drop support for node 0.10 to save travis some unnecessary cycles <3 2015-03-10 13:11:06 +11:00
Sebastian McKenzie
f3bd9cbcb8 use a different helper if a class contains class methods to avoid non-enumerability and delegation to es6.properties.computed transformer - fixes #984, closes #986 2015-03-10 13:04:02 +11:00
Sebastian McKenzie
3bd14f9e07 add babel version to register hook cache key 2015-03-10 13:03:22 +11:00
Sebastian McKenzie
102b4b3d1e remove redundant break wrapping in for-of - fixes #985 2015-03-10 12:14:21 +11:00
Sebastian McKenzie
6564f1ff76 4.7.4 2015-03-10 06:13:37 +11:00
Sebastian McKenzie
58d7a5e069 more versatile scope pushing 2015-03-10 06:13:32 +11:00
Sebastian McKenzie
f5db53cebe remove core-js library from babel-runtime 2015-03-10 06:13:16 +11:00
Sebastian McKenzie
2da010fcae clean up #982 2015-03-10 06:11:55 +11:00
Sebastian McKenzie
52b99bdf93 Merge pull request #982 from tricknotes/error-stack
Ignore assignment to Error#stack if it is readonly property
2015-03-10 06:09:03 +11:00
Ryunosuke SATO
9d7e953451 Ignore assignment to Error#stack if it is readonly property
`Error#stack` may be an readonly property in some environments
such as PhantomJS 1.9.2 and Safari 7.0.
2015-03-10 04:05:53 +09:00
Sebastian McKenzie
b1252b865b v4.7.4 2015-03-10 03:29:47 +11:00
Sebastian McKenzie
068b1341d9 fix erroneous whitespace 2015-03-10 03:28:36 +11:00
Sebastian McKenzie
20eb143915 remove Number from the list of valid runtime constructors - fixes #981 2015-03-10 03:27:13 +11:00
Sebastian McKenzie
1302a86bf2 scope -> scopable class alias key 2015-03-10 03:22:55 +11:00
Sebastian McKenzie
b7831f1d7b prepend mocha command with node 2015-03-10 03:15:31 +11:00
Sebastian McKenzie
e46cabb21f remove code coverage from travis make task 2015-03-10 03:12:50 +11:00
Sebastian McKenzie
fff06a047e Revert "delegate node path removal to after call"
This reverts commit 5e0236d9a7.
2015-03-10 02:50:43 +11:00
Sebastian McKenzie
6b0320fc83 disable test262 tests by default 2015-03-10 02:34:35 +11:00
Sebastian McKenzie
5dde63fa0a more elaborate tests for #980 2015-03-10 02:13:00 +11:00
Sebastian McKenzie
672118149a hoist all directives - fixes #980 2015-03-10 01:53:51 +11:00
Sebastian McKenzie
5e0236d9a7 delegate node path removal to after call 2015-03-10 01:44:58 +11:00
Sebastian McKenzie
5101664e7d update 4.7.4 changelog 2015-03-10 01:44:44 +11:00
Sebastian McKenzie
2d684a06d3 update changelog version to 4.7.4 2015-03-10 01:23:24 +11:00
Sebastian McKenzie
e31bad8f42 add 4.7.3 changelog 2015-03-10 01:17:14 +11:00
Sebastian McKenzie
644b4373fc rewrite named function expressions in async function transformers - fixes #979 2015-03-10 01:16:38 +11:00
Sebastian McKenzie
62f37c1e62 fix util.booleanify 2015-03-10 01:10:58 +11:00
Sebastian McKenzie
fc0e89463b use flow types for annotations - goodbye JSDoc! 2015-03-10 00:35:52 +11:00
Sebastian McKenzie
56b6a795a4 remove path.refreshScope until i'm more confident on it's functionality so it doesn't break peopls stuff 2015-03-09 23:09:22 +11:00
Sebastian McKenzie
17b34a2959 dynamic scope tracking, toot toot - fixes #957 2015-03-09 22:07:05 +11:00
Sebastian McKenzie
c4da0253c5 move flattenable keys to types 2015-03-09 16:55:00 +11:00
Sebastian McKenzie
5f2df40f6d consistent whitespace in patch 2015-03-09 16:54:50 +11:00
Sebastian McKenzie
7d20a9b882 add traversal path todos 2015-03-09 16:54:41 +11:00
Sebastian McKenzie
ee0ac9f149 use spread in messages 2015-03-09 16:54:30 +11:00
Sebastian McKenzie
c5d3f42d8a alias core-js/library in babel-runtime - closes #965 2015-03-09 16:54:19 +11:00
Sebastian McKenzie
d162919a53 update symols transformer name 2015-03-09 03:39:30 +11:00
Sebastian McKenzie
d1f712344d add istanbul auxiliary comment task to makefile 2015-03-09 03:38:39 +11:00
Sebastian McKenzie
e985912b54 add Binary node cleanup 2015-03-09 03:38:27 +11:00
Sebastian McKenzie
97a21e4a34 update spec.typeofSymbol references to es6.symbols 2015-03-09 03:38:13 +11:00
Sebastian McKenzie
d8fb7812f7 more utility.removeConsole tests 2015-03-09 03:37:42 +11:00
Sebastian McKenzie
bfe63f5885 rename spec.typeofSymbol transformer to es6.symbols 2015-03-09 03:37:26 +11:00
Sebastian McKenzie
44ca6873a3 add super to contextVariables 2015-03-09 03:37:05 +11:00
Sebastian McKenzie
2f66ea7338 4.7.3 2015-03-08 04:33:50 +11:00
Sebastian McKenzie
70967cf53c v4.7.3 2015-03-08 04:32:46 +11:00
Sebastian McKenzie
dc117a74ae both -> inline - thanks @dkieks 2015-03-08 04:29:48 +11:00
Sebastian McKenzie
b0f32a822d pass file.addImport a name instead of an identifier 2015-03-08 04:10:53 +11:00
Sebastian McKenzie
fd99ea1749 Merge branch 'master' of github.com:babel/babel 2015-03-08 04:05:44 +11:00
Sebastian McKenzie
572129542d fallback to current parentPath if none was provided 2015-03-08 04:04:48 +11:00
Sebastian McKenzie
6f53980bfc move runtime helpers to separate modules - babel/ember-cli-babel#24 2015-03-08 04:04:40 +11:00
Sebastian McKenzie
348af1990d Merge pull request #972 from neVERberleRfellerER/node-external-helpers-tests
add tests for babel-external-helpers
2015-03-08 03:50:28 +11:00
Ondrej Kraus
bd5f350728 add tests for babel-external-helpers 2015-03-07 17:46:40 +01:00
Sebastian McKenzie
958fa282f4 4.7.2 2015-03-08 03:12:09 +11:00
Sebastian McKenzie
31e6b18346 v4.7.2 2015-03-08 03:09:43 +11:00
Sebastian McKenzie
d17ac92a3f fix changelog version 2015-03-08 03:06:46 +11:00
Sebastian McKenzie
188bcb70f7 add 4.7.1 changelog 2015-03-08 03:03:17 +11:00
Sebastian McKenzie
b8bd11a0e7 fix incorrect builder reference 2015-03-08 03:02:19 +11:00
Sebastian McKenzie
45bc74efe7 use a lookup table instead of an if - #945 2015-03-08 02:57:37 +11:00
Sebastian McKenzie
7eb169a894 Merge pull request #945 from neVERberleRfellerER/helper-globals-fix
Add choice of output format to babel-external-helpers
2015-03-08 02:56:30 +11:00
Sebastian McKenzie
eed4f312d8 add sourceMap both option - closes #966 2015-03-08 02:54:23 +11:00
Sebastian McKenzie
44e4dc970f more es6 2015-03-08 02:52:23 +11:00
Sebastian McKenzie
5d32432e67 split up export variable declarations - fixes #939, fixes #964 2015-03-08 02:52:10 +11:00
Sebastian McKenzie
9c9af6dbbd add utility.removeClass tests and move parentPath setting to setContext - fixes #967 2015-03-08 02:49:58 +11:00
Sebastian McKenzie
70cd650e10 remove dead t.isFalsyExpression and ignore private properties in t.cloneDeep - fixes #962 2015-03-08 02:45:14 +11:00
Sebastian McKenzie
c7bb00d58d ignore case breaks - fixes #963 2015-03-07 17:41:56 +11:00
Ondrej Kraus
623be068c4 add unsupportedOutputType to messages.js 2015-03-07 01:53:34 +01:00
Ondrej Kraus
71f5c9791d replace switch with if-else chain 2015-03-07 01:50:50 +01:00
Ondrej Kraus
3e6e86d073 order template keys by length 2015-03-07 01:50:49 +01:00
Ondrej Kraus
a0fb398ca2 add possibility to select format of external helpers 2015-03-07 01:50:49 +01:00
Ondrej Kraus
71b9f19e6a change to normal UMD (fixes bug with leaking variable in AMD mode) 2015-03-07 01:50:48 +01:00
Ondrej Kraus
c45ce58f0c stop assigning to global in generated helpers code 2015-03-07 01:50:48 +01:00
Sebastian McKenzie
d32f587e3c expose dynamicImports when es6.modules is blacklisted babel/ember-cli-babel#24 2015-03-07 03:31:24 +11:00
Sebastian McKenzie
9e1874ba89 4.7.1 2015-03-07 03:31:05 +11:00
Sebastian McKenzie
35fdc5c5d8 v4.7.1 2015-03-07 02:52:17 +11:00
Sebastian McKenzie
a4035fc257 use convert-source-map package - closes #960 2015-03-07 02:46:15 +11:00
Sebastian McKenzie
42e3dc7a70 inherit all options from input source map 2015-03-07 02:28:33 +11:00
Sebastian McKenzie
cdccf24515 4.7.0 2015-03-07 02:04:58 +11:00
Sebastian McKenzie
c8cd5c108b v4.7.0 2015-03-07 01:59:02 +11:00
Sebastian McKenzie
2b95b876e1 return only constructor if class was a named class with only a constructor/no constructor 2015-03-07 01:50:34 +11:00
Sebastian McKenzie
f801772fc2 add inputSourceMap option - fixes #827, related babel/babel-loader#35 2015-03-07 01:50:07 +11:00
Sebastian McKenzie
8ad678e5bc make it illegal to have a rest on a setter 2015-03-07 01:32:03 +11:00
Sebastian McKenzie
35c49dbef7 merge validation transformers 2015-03-07 01:25:44 +11:00
Sebastian McKenzie
119314df74 update traceur 2015-03-07 01:25:37 +11:00
Sebastian McKenzie
51e336b037 class declarations also have a lexical self binding 2015-03-07 01:25:18 +11:00
Sebastian McKenzie
7d446807a9 remove rogue console.log 2015-03-06 23:40:30 +11:00
Sebastian McKenzie
8afdeaf557 replicate module environment in babel-node -e - closes #695, fixes #592 2015-03-06 23:39:49 +11:00
Sebastian McKenzie
4df50954a2 use instance indexOf instead of lodash - #951 2015-03-06 23:31:11 +11:00
Sebastian McKenzie
70b6317865 Merge pull request #951 from neVERberleRfellerER/babel-node-args-fix
add possiblity of passing colliding user arguments by separating them with --
2015-03-06 23:30:31 +11:00
Sebastian McKenzie
5ebdc44297 remove babel-runtime version check to node api 2015-03-06 23:20:48 +11:00
Sebastian McKenzie
a4659fd239 add reference checks for module specifiers - fixes #956 2015-03-06 23:19:26 +11:00
Sebastian McKenzie
19bfa4a35b add debug message for travis... 2015-03-06 23:15:20 +11:00
Sebastian McKenzie
f7fff7d35e add alternate to list of STATEMENT_OR_BLOCK_KEYS - fixes #955 2015-03-06 23:13:03 +11:00
Sebastian McKenzie
130e0ebe6b better classes, more spec compliant and nicer output - fixes #952 2015-03-06 23:08:10 +11:00
Sebastian McKenzie
69c836fc8d Merge branch 'master' of github.com:babel/babel 2015-03-06 02:27:15 +11:00
Sebastian McKenzie
f62a3ef394 further develop ast paths that represent a single location in the ast as an abstraction around a node-parent relationship 2015-03-06 02:26:04 +11:00
Sebastian McKenzie
7a6e568940 clean up classes output 2015-03-06 02:25:24 +11:00
Sebastian McKenzie
65998c3437 add error message for incompatible babel-runtime versions 2015-03-06 02:23:30 +11:00
Ondrej Kraus
160de340b0 add possiblity of passing user arguments by separating them with --
Now, when user arguments have names colliding with node arguments,
they can be separated by -- and will be parsed correctly.
2015-03-05 14:35:53 +01:00
Sebastian McKenzie
76ca40f698 Merge pull request #944 from sindresorhus/modularize-tofastproperties
modularize `util.toFastProperties()`
2015-03-05 01:10:26 +11:00
Sindre Sorhus
01ed824b5c modularize util.toFastProperties()
https://github.com/sindresorhus/to-fast-properties
2015-03-04 21:02:36 +08:00
Sebastian McKenzie
6b0dbc4486 bump regenerator-babel 2015-03-04 23:29:37 +11:00
Sebastian McKenzie
2648268f30 add contextVariables to scope 2015-03-04 22:54:00 +11:00
Sebastian McKenzie
8cf5bf7037 add filename arg to resolveModuleSource option 2015-03-04 22:53:50 +11:00
Sebastian McKenzie
60961bc3ff bump ast-types - fixes #930 2015-03-04 22:53:38 +11:00
Sebastian McKenzie
df16bc17e7 clean up formatting of system module formatter 2015-03-04 22:52:44 +11:00
Sebastian McKenzie
5337ab5a08 statically bind super references in object expressions - fixes #943 2015-03-04 22:52:07 +11:00
Sebastian McKenzie
2eaeebcce4 inherit from class constructor block statement - fixes #937 2015-03-03 23:38:11 +11:00
Sebastian McKenzie
ad71010144 4.6.6 2015-03-03 22:44:44 +11:00
Sebastian McKenzie
864169c1eb v4.6.6 2015-03-03 22:43:06 +11:00
Sebastian McKenzie
930d7f9aa6 add 4.6.6 changelog 2015-03-03 22:38:20 +11:00
Sebastian McKenzie
ed40ec03d1 more es6, template literals and modules 2015-03-03 22:31:49 +11:00
Sebastian McKenzie
73062ae240 take into consideration non-identifier nodes in es6.blockScopingTDZ transformer, also turn default and parameters into lets instead of vars - fixes #929 2015-03-03 22:30:52 +11:00
Sebastian McKenzie
bafa3e0d4c add missing is - fixes #931 - thanks @neVERberleRfellerER 2015-03-03 10:38:18 +11:00
Sebastian McKenzie
f3d2b2bb81 Merge branch 'master' of github.com:babel/babel 2015-03-03 09:49:35 +11:00
Sebastian McKenzie
a74b67d4eb Merge pull request #932 from hzoo/more-es6
More es6
2015-03-03 09:49:29 +11:00
Sebastian McKenzie
625416862f remove no es6 syntax line from contributing.md 2015-03-03 09:49:20 +11:00
Sebastian McKenzie
8dda8838ba check for body existence before length in dead code elimination transformer - fixes #931 2015-03-03 09:37:52 +11:00
Henry Zhu
96d3a25213 use more es6 concise methods 2015-03-02 10:34:30 -05:00
Sebastian McKenzie
727208f376 4.6.5 2015-03-02 22:55:36 +11:00
Sebastian McKenzie
1b046a6ecb v4.6.5 2015-03-02 22:54:35 +11:00
Sebastian McKenzie
3b8ed0d401 add 4.6.5 changelog 2015-03-02 22:51:21 +11:00
Sebastian McKenzie
d4c98d7738 add transformer aliases 2015-03-02 22:47:00 +11:00
Sebastian McKenzie
4e44af819f fix rogue strict reference 2015-03-02 22:45:21 +11:00
Sebastian McKenzie
a65acd73ca fix rogue useStrict transformer references 2015-03-02 22:41:55 +11:00
Sebastian McKenzie
b7cb2bcb7b rename useStrict transformer to strict 2015-03-02 22:37:51 +11:00
Sebastian McKenzie
5ac4dc0541 don't evaluate ArrayExpressions 2015-03-02 17:16:10 +11:00
Sebastian McKenzie
99ddd02b0a change Function export to avoid messing with istanbul 2015-03-02 15:38:43 +11:00
Sebastian McKenzie
19cfee14fd 4.6.4 2015-03-02 15:38:31 +11:00
Sebastian McKenzie
fea487bf91 v4.6.4 2015-03-02 15:34:10 +11:00
Sebastian McKenzie
ff2cbd5a2e Merge branch 'master' of github.com:babel/babel 2015-03-02 15:30:30 +11:00
Sebastian McKenzie
12e01f9e71 remove optional property on function params - fixes #927 2015-03-02 15:30:05 +11:00
Sebastian McKenzie
f62436909d Merge pull request #923 from mathiasbynens/patch-4
Explicitly update the regexpu dependency to v1.1.2
2015-03-02 11:32:27 +11:00
Mathias Bynens
e42c1adeb6 Explicitly update the regexpu dependency to v1.1.2 2015-03-01 18:50:17 +01:00
Sebastian McKenzie
e30dbbab94 properly replace labels in spec for of transformer - fixes #913, closes #914 2015-03-02 01:41:13 +11:00
Sebastian McKenzie
e3daa28e60 rename minification tests to utility 2015-03-02 01:28:34 +11:00
Sebastian McKenzie
9e5d94126c add base type tests 2015-03-02 01:28:17 +11:00
Sebastian McKenzie
95798bee0b add t.valueToNode 2015-03-02 01:28:10 +11:00
Sebastian McKenzie
63f25ab038 check parent for variable collisions when remapping closurified block scopes - fixes #915, closes #922 2015-03-02 01:27:58 +11:00
Sebastian McKenzie
27a8f2d2ea rename broke property to confident in t.evaluate 2015-03-01 18:16:27 +11:00
Sebastian McKenzie
78434bb404 add t.evaluate method 2015-03-01 17:01:46 +11:00
Sebastian McKenzie
82833a8901 update 4.6.3 changelog 2015-03-01 13:45:09 +11:00
Sebastian McKenzie
93d5288d71 4.6.3 2015-03-01 11:05:33 +11:00
Sebastian McKenzie
5d3074b460 v4.6.3 2015-03-01 11:03:55 +11:00
Sebastian McKenzie
a57475abc9 better rest param member expression deopt 2015-03-01 11:01:06 +11:00
Sebastian McKenzie
09e68d8d46 v4.6.2 2015-03-01 10:12:43 +11:00
Sebastian McKenzie
ee850c3aeb merge fix for #917 with #918 2015-03-01 10:09:03 +11:00
Sebastian McKenzie
ff5a149cec Merge branch 'master' of github.com:babel/babel
# Conflicts:
#	src/babel/transformation/transformers/es6/parameters.rest.js
2015-03-01 10:04:52 +11:00
Sebastian McKenzie
957118fb41 delay rest optimisation, deopt on unoptimisable references - fixes #918 2015-03-01 10:04:16 +11:00
Sebastian McKenzie
e7ad0a9741 Merge pull request #919 from neVERberleRfellerER/rest-args-optimization-fix
fix rest optimization in arrow functions
2015-03-01 09:38:00 +11:00
Ondrej Kraus
24f4b041c7 fix rest optimization in arrow functions and add advanced test 2015-02-28 23:28:21 +01:00
Sebastian McKenzie
4c77d04b56 more es6 modules 2015-03-01 01:01:51 +11:00
Sebastian McKenzie
e945f0d10f add support for outputting flow types - fixes #665 2015-03-01 00:32:36 +11:00
Sebastian McKenzie
fb04b2561f copy over files in watch mode 2015-02-28 21:39:40 +11:00
Sebastian McKenzie
a4f8b41507 4.6.1 2015-02-28 11:56:46 +11:00
Sebastian McKenzie
1fb6018e9c v4.6.1 2015-02-28 11:55:47 +11:00
Sebastian McKenzie
bca233d22c add 4.6.1 changelog 2015-02-28 11:52:21 +11:00
Sebastian McKenzie
c78703e194 blacklist regenerator from templates directory - fixes #912 2015-02-28 11:47:18 +11:00
Sebastian McKenzie
43fdbe3d6c fix whitespace 2015-02-28 11:31:43 +11:00
Sebastian McKenzie
8650ca7d55 properly expose util - fixes #52 2015-02-28 11:24:51 +11:00
Sebastian McKenzie
3a0c226a34 upgrade babel 2015-02-28 00:31:35 +11:00
Sebastian McKenzie
73e8bdd048 update 4.6.0 changelog 2015-02-28 00:31:28 +11:00
Sebastian McKenzie
e7c52a734e 4.6.0 2015-02-27 21:14:20 +11:00
Sebastian McKenzie
5a81b02569 v4.6.0 2015-02-27 21:09:17 +11:00
Sebastian McKenzie
999baf2888 fix regex tests 2015-02-27 21:01:13 +11:00
Sebastian McKenzie
70b25e8942 add sticky regex desugaring #904 2015-02-27 20:51:48 +11:00
Sebastian McKenzie
2ddbd4eecc fix es for of break test expected 2015-02-27 20:33:42 +11:00
Sebastian McKenzie
7520807df3 move eslint out of the core into a separate plugin 2015-02-27 16:30:53 +11:00
Sebastian McKenzie
974b71bcc3 flesh out eslint support 2015-02-27 16:11:47 +11:00
Sebastian McKenzie
0aee3c06ec add noCheckAst option to enforce newline test 2015-02-27 15:45:09 +11:00
Sebastian McKenzie
a4382580fc ignore user whitespace when splitting up module declaration - fixes #906 2015-02-27 15:25:13 +11:00
Sebastian McKenzie
166b2eda87 remove rogue export in node api 2015-02-27 15:08:01 +11:00
Sebastian McKenzie
83c23d266f add eslint with an acorn-babel compatibility layer, yay! coming soon to a production release near you 2015-02-27 13:17:22 +11:00
Sebastian McKenzie
a9db70b60d close iterators on abrupt completion - google/traceur-compiler#1773 #838 2015-02-27 11:44:13 +11:00
Sebastian McKenzie
5d90c442cb fix es6 rest parameters transformer comment 2015-02-26 23:25:48 +11:00
Sebastian McKenzie
32606ddb93 remove linting mention from contributing guide 2015-02-26 22:34:54 +11:00
Sebastian McKenzie
330f6910c6 remove unnecessary exception catch and process.exit - fixes #901 2015-02-26 22:33:36 +11:00
Sebastian McKenzie
4ca8a0e6e2 bump browserify 2015-02-26 21:41:15 +11:00
Sebastian McKenzie
f097ddeac3 bump source-map dependency 2015-02-26 21:39:54 +11:00
Sebastian McKenzie
1eb53dd13a add try-catch to bin watching compilation - fixes #901 2015-02-26 21:28:54 +11:00
Sebastian McKenzie
75b5f32e7a make js-tokens version fixed - explanation in #900 2015-02-26 21:15:54 +11:00
Sebastian McKenzie
f753cf4845 Merge pull request #900 from lydell/js-tokens-1.0
Upgrade to js-tokens@1.0.0
2015-02-26 21:13:55 +11:00
Simon Lydell
9a569f64da Upgrade to js-tokens@1.0.0
This commit also adds syntax highlighting for `null`, `false` and `true`.
2015-02-26 11:11:23 +01:00
Sebastian McKenzie
8efeae80af remove export function Function 2015-02-26 20:39:30 +11:00
Sebastian McKenzie
4df9cf6c05 add missing transform import and change babel import to a wildcard 2015-02-26 20:26:08 +11:00
Sebastian McKenzie
7729cb4b68 start using es6 modules 2015-02-26 20:13:00 +11:00
Sebastian McKenzie
307ffcd107 correctly get old extension handler in registerExtension 2015-02-26 16:00:06 +11:00
Sebastian McKenzie
751557aef1 make #889 more efficient and flexible 2015-02-26 15:24:12 +11:00
Sebastian McKenzie
3f146b54ff Merge branch 'master' of github.com:6to5/6to5 2015-02-26 15:04:21 +11:00
Sebastian McKenzie
19a173c622 Merge pull request #899 from xjamundx/patch-1
feat(6to5/register) don't override uncaughtException handler
2015-02-26 15:04:02 +11:00
Sebastian McKenzie
89bcb307a2 Merge pull request #889 from neVERberleRfellerER/rest-args-optimization-v2
Add rest parameters optimization
2015-02-26 15:03:51 +11:00
Sebastian McKenzie
ded1e02da7 move buildHelpers require down a slot 2015-02-26 13:06:15 +11:00
Sebastian McKenzie
564ba67190 4.5.5 2015-02-26 13:06:08 +11:00
Sebastian McKenzie
00c964ed19 v4.5.5 2015-02-26 13:03:02 +11:00
Sebastian McKenzie
3ab88e02c7 delete from require.extensions when old extension handler is undefined 2015-02-26 12:58:01 +11:00
Sebastian McKenzie
bb2fc830eb use some spreads 2015-02-26 12:57:43 +11:00
Sebastian McKenzie
c6a542fd1d finish remaining class conversion 2015-02-26 12:34:05 +11:00
Sebastian McKenzie
553eb2d45e more classes! 2015-02-26 12:19:28 +11:00
Ondrej Kraus
b5f3c3f4cc stop traversal when it is clear that optimization is impossible 2015-02-26 02:05:26 +01:00
Ondrej Kraus
5d83638583 set literal MemberExpression as computed in rest array destructuring 2015-02-26 01:22:00 +01:00
Sebastian McKenzie
f7186980e5 add external helpers test #898 2015-02-26 09:24:28 +11:00
Sebastian McKenzie
0eaaaa503e 4.5.4 2015-02-26 09:24:10 +11:00
Sebastian McKenzie
51dff364db v4.5.4 2015-02-26 09:21:55 +11:00
Sebastian McKenzie
dc6129eb6a fix helper whitelist in build script 2015-02-26 09:19:49 +11:00
Sebastian McKenzie
5b84b9c867 4.5.3 2015-02-26 09:11:15 +11:00
Jamund Ferguson
24ace3c8c2 feat(6to5/register) don't override uncaughtException handler
Maybe we could do this by default or even make it configurable?
2015-02-25 13:51:26 -08:00
Ondrej Kraus
687b0f3180 remove unused function argument 2015-02-25 15:38:32 +01:00
Ondrej Kraus
e6855b974b update tests 2015-02-25 15:30:22 +01:00
Ondrej Kraus
a808742c19 remove strict-mode specific optimizations due to unsolvable ambiguities 2015-02-25 15:24:45 +01:00
Ondrej Kraus
c3f4091b6d replace for-of with with for for performance reasons 2015-02-25 14:41:20 +01:00
Ondrej Kraus
edb880f87c add tests 2015-02-25 14:26:28 +01:00
Ondrej Kraus
e8741daee3 use some ES6 to simplify code 2015-02-25 14:13:15 +01:00
Ondrej Kraus
c5913564f8 replace quotes to conform to coding style 2015-02-25 13:34:18 +01:00
Ondrej Kraus
662bddbaca simplify optimization code 2015-02-25 13:34:17 +01:00
Ondrej Kraus
8f540dfff3 call non-strict mode optimizer before strict mode one to simplify literals 2015-02-25 13:34:17 +01:00
Ondrej Kraus
1265bc5a92 add better optimization when strictMode transformer is enabled 2015-02-25 13:34:15 +01:00
Ondrej Kraus
e677c72d58 add patterns support 2015-02-25 13:34:15 +01:00
Ondrej Kraus
8ca854156a simplify and optimize local binding handling 2015-02-25 13:34:14 +01:00
Ondrej Kraus
81ae656358 remove unused function 2015-02-25 13:34:13 +01:00
Ondrej Kraus
f2981b7e95 replace direct node type checking with helper functions 2015-02-25 13:34:12 +01:00
Ondrej Kraus
99b2e00d33 add rest parameters optimization 2015-02-25 13:34:11 +01:00
2088 changed files with 86945 additions and 10922 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"]
}

View File

@@ -4,7 +4,6 @@ root = true
insert_final_newline = true
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
end_of_line = lf
[*.{js,json}]

1
.eslintignore Normal file
View File

@@ -0,0 +1 @@
src/babel/transformation/templates

22
.eslintrc Normal file
View File

@@ -0,0 +1,22 @@
{
"parser": "babel-eslint",
"rules": {
"strict": 0,
"no-underscore-dangle": 0,
"no-unused-vars": 0,
"curly": 0,
"no-multi-spaces": 0,
"key-spacing": 0,
"no-return-assign": 0,
"consistent-return": 0,
"no-shadow": 0,
"no-comma-dangle": 0,
"no-use-before-define": 0,
"no-empty": 0,
"new-parens": 0,
"no-cond-assign": 0
},
"env": {
"node": true
}
}

5
.gitignore vendored
View File

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

9
.gitmodules vendored
View File

@@ -1,12 +1,3 @@
[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,16 +1,15 @@
node_modules
*.log
*.cache
lib/babel/transformation/templates
test
benchmark
Makefile
.*
dist
tests.json
CHANGELOG.md
.package.json
coverage
vendor
packages
src
/lib/babel/transformation/templates
/test
/benchmark
/Makefile
/dist
/tests.json
/CHANGELOG.md
/.package.json
/coverage
/vendor
/packages
/src

View File

@@ -1,14 +1,12 @@
sudo: false
#sudo: false
language: node_js
cache:
directories:
- node_modules
node_js:
- "0.10"
- "0.12"
- "iojs"
branches:
except:
- experimental
before_script: "npm install -g codeclimate-test-reporter"
script: "make test-travis"

View File

@@ -13,6 +13,607 @@ _Note: Gaps between patch versions are faulty/broken releases._
See [CHANGELOG - 6to5](CHANGELOG-6to5.md) for the pre-4.0.0 version changelog.
## 5.4.1
* **Bug Fix**
* Add missing `slash` dependency. Thanks [@browncolyn](https://github.com/browncolyn)!
* **Polish**
* Clean up `shouldIgnore` algorithm to work how you'd expect rather than being a hacky piece of shit.
## 5.4.0
* **New Feature**
* Added [function bind syntax](https://github.com/zenparsing/es-function-bind) behind stage 0. Thanks [@RReverser](https://github.com/rreverser)!
* Added `env` option. Especially handy when using the `.babelrc`.
* **Bug Fix**
* Fix files not properly being ignored when `babel.transform` ignores them when using `$ babel`.
* Fix scope tracking registering loop head bindings to their `VariableDeclaration` instead of `VariableDeclarator`.
* **Polish**
* Normalise path separators for souce map paths when using `$ babel`.
* Rework `PathHoister` to ignore global references and to not deopt on reassignments to referenced bindings, instead it tries to hoist to the highest scope.
* Added missing exponential operator inlining. Thanks [@nkt](https://github.com/nkt)!
* Optimise `regenerator` transformer. Thanks [@benjamn](https://github.com/benjamn)!
## 5.3.3
* **Bug Fix**
* Fix `minification.deadCodeElimination` transformer incorrectly trying to inline import declarations.
* Fix `minification.inlineExpression` transformer getting into an infinite loop.
## 5.3.2
* **Bug Fix**
* Fix patterns not being considered when hoisting variables in the `es6.blockScoping` transformer.
## 5.3.1
* **Bug Fix**
* Fix unique export specifiers not being cloned when exploding class and function exports,
* **Polish**
* Turn import remaps to sequence expressions to remove their context and improve performance.
## 5.3.0
**Speeeeeeed**
![gifs lol](https://31.media.tumblr.com/568205a0e37ae15eca510fa639589a59/tumblr_n8kw8kpcSb1sg6cg8o1_500.gif)
* **Spec Compliancy**
* Allow trailing param commas for methods when using the `es7.trailingCommas` transformer.
* **Bug Fix**
* Fix `es6.blockScoping` transformer not properly ignoring `break` in `SwitchCase`.
* Fix lookahead context saving to avoid weird tokenizer state.
* Explode duplicate identifiers in export/import specifiers and property shorthand to create unique objects.
* Skip loose mode for class methods when they have decorators.
* When removing nodes, share their comments with their siblings.
* Properly hoist temp param declarations when doing TCO.
* **Internal**
* Add `--harmony_generators` flag to `$ babel-node`.
* Internal AST traversals have been minimised **drastically**. Transformers have been grouped together which means entire tree traversals are much fewer. Visiting nodes is now also skipped if the traversal context can detect that the handler is a noop. This sames precious cycles as it avoids constructing traversal paths and creating a new traversal context. See issues [#1472](https://github.com/babel/babel/issues/1472) and [#1486](https://github.com/babel/babel/issues/1486) for related discussion.
* **Polish**
* Move many `utility` transformers to `minification`.
## 5.2.17
* **Bug Fix**
* Fix auxiliary comments not properly being attached to function declaration helpers.
* Add `Super` node type to `ast-types` patch.
* Ignore parameter bindings when attempting to inline them in the `minification.deadCodeElimination` transformer.
* Correct `extensions` arguments when using the Babel CLI.
## 5.2.16
* **Bug Fix**
* Fix plugins being disabled when using the whitelist.
* Fix correct function scope being passed to `nameMethod.property` when inferring the function name for class methods.
* Fix incorrect extensions reference causing weird issues when using the Babel CLI.
* Fix destructuring param reference replacements not inheriting from their original param.
* **Spec Compliancy**
* Fix order that method decorators are ran in.
## 5.2.15
* **Bug Fix**
* Fix initializer descriptor add attempt if it doesn't exist.
## 5.2.14
* **Bug Fix**
* Fix bug with initializer decorators where the descriptors weren't being defined if there was no `initializer` property.
* **Internal**
* Expose `retainLines` option to CLI.
* Fix `retainLines` option not being taken into consideration when doing multiple variable declaration declarators generation.
* Expose minified and unminified copies of dist scripts.
## 5.2.13
* **Bug Fix**
* Fix `ExportDeclaration`s being incorrectly removed when using the `utility.deadCodeElimination` transformer.
* Fix position of `utility` transformers.
* **New Feature**
* Add built-in `esquery` support.
* **Internal**
* Consolidate notion of "virtual types".
## 5.2.12
* **Polish**
* Make UID generation based on module declarations **much** nicer.
* **Internal**
* Remove internal check for traversal path replacement of self. This is a pattern that **could** come up in the wild and it could lead to pretty nasty code and may lead to internal regressions as the test coverage isn't 100% :( Instead, just put it in the fast path.
## 5.2.11
* **Internal**
* 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**
* Check for top level `breakConfig` in `resolveRc`.
## 5.0.3
* **Bug Fix**
* Make relative location absolute before calling `resolveRc`.
* **Internal**
* Switch to global UID registry.
* Add `breakConfig` option to prevent Babel from erroring when hitting that option.
## 5.0.1
* **Bug Fix**
* Fix duplicate declaration regression.
* Fix not being able to call non-writable methods.
## 5.0.0
* **New Feature**
* Decorators based on [@wycat's](https://github.com/wycats) [stage 1 proposal](https://github.com/wycats/javascript-decorators).
* Class property initializers based on [@jeffmo's](https://github.com/jeffmo) [stage 0 proposal](https://gist.github.com/jeffmo/054df782c05639da2adb).
* Export extensions based on [@leebyron's](https://github.com/leebyron) [stage 1 proposal](https://github.com/leebyron/ecmascript-more-export-from).
* UMD module formatter now supports globals.
* Add `es3.runtime`, `optimisation.react.inlineElements` and `optimisation.react.constantElements` transformers.
* Add stage option that replaces the experimental one.
* Allow ES7 transformer to be enabled via `optional` instead of only via `stage`.
* Infer string quotes to use in the code generator.
* Consider `export { foo as default };` to be the same as `export default foo;`.
* Add `nonStandard` option that can be set to `false` to remove parser support for JSX and Flow.
* Add `jsxPragma` option.
* Automatically generate CLI options based on internal API options.
* Add support for `.babelrc` on absolute paths.
* Plugin API!
* **Internal**
* Export `options` in browser API.
* Rewritten parser.
* Don't block hoist when runtime transformer is enabled in system module formatter.
* Rewritten the internal traversal and node replacement API to use "paths" that abstracts out node relationships.
* **Polish**
* JSX output is now more inline with the official JSX transformer.
* Hoist block scoping IIFE - this improves memory usage and performance.
* Better IIFE detection - references are now checked to see if they're referencing the binding we're searching for.
* Check for import reassignments in constants transformer.
* Make method definitions with expression bodies illegal.
* Save register cache on tick instead of `SIGINT`.
* Enable strict mode on babel-node eval flag.
* **Bug Fixes**
* Add support for live bindings. This change also increases the reliablity of export specifier renaming.
* Add support for super update and non equals assignment expressions.
* Rename shadow constructor binding in classes.
* Seed next iteration bindings with previous fresh bindings when reassinging loop block scoped variables.
* Fix new expression spread referencing the wrong constructor.
* Call `resolveModuleSource` on dynamic imports.
* Added `param` to list of duplicate declaration kinds.
* **Breaking Changes**
* The Babel playground has been removed.
* ES7 Abstract References have been removed.
* Experimental option has been removed in favor of a stage option.
* Rename `returnUsedHelpers` to `metadataUsedHelpers`.
## 4.7.16
* **Bug Fix**
* Fix constructor spreading of typed arrays.
* Fix break/continue/return aliasing of non-loops in block scoping transformer.
## 4.7.15
* **Bug Fix**
* Fix constructor spreading of collections.
## 4.7.14
* **Bug Fix**
* Fix constructor spreading of `Promise`.
* **Internal**
* Deprecate remaining playground transformers and abstract references.
## 4.7.13
* **Bug Fix**
* Handle comments on use strict directives.
* Fix assignment patterns with a left side pattern.
* **Polish**
* Special case `this` when doing expression memoisation.
## 4.7.12
* **Bug Fix**
* Deprecate `playground.methodBinding`.
## 4.7.11
* **Bug Fix**
* Fix unicode regexes stripping their unicode flag before being passed on two `regexpu`.
## 4.7.10
* **Internal**
* Deprecate `playground.methodBinding` and `playground.objectGetterMemoization`.
* **Bug Fix**
* Fix `inputSourceMap` option. Thanks [@Rich-Harris](https://github.com/Rich-Harris)!
## 4.7.9
* **Polish**
* Allow `inputSourceMap` to be set to `false` to skip the source map inference.
* Infer computed literal property names.
* **Bug Fix**
* Fix nested labeled for-ofs.
* Fix block scoping `break` colliding with the parent switch case.
* **Internal**
* Upgrade `acorn-babel`.
## 4.7.8
* **Bug Fix**
* Fix computed classes not properly setting symbols.
## 4.7.7
* **Bug Fix**
* Fix `types` API exposure.
## 4.7.6
* **Bug Fix**
* Fix non-Identifier/Literal computed class methods.
* **Polish**
* Add a fallback if `stack` on an error is unconfigurable.
* Hoist `esModule` module declarations to the top of the file to handle circular dependencies better.
## 4.7.5
* **Bug Fix**
* Don't remap` break`s to call the iterator return.
* **Polish**
* Use a different helper for computed classes for much nicer output. Also fixes a bug in symbols being non-enumerable so they wouldn't be set on the class.
## 4.7.4
* **Bug Fix**
* Rewrite named function expressions in optional async function transformers.
* Hoist directives.
* Remove `Number` from the list of valid `runtime` constructors.
* **Internal**
* `spec.typeofSymbol` transformer has been renamed to `es6.symbols`.
## 4.7.2
* **New Feature**
* `"both"` option for `sourceMap`.
* Add output types to external helpers. Thanks [@neVERberleRfellerER](https://github.com/neVERberleRfellerER)!
* **Bug Fix**
* Fix node duplication sometimes resulting in a recursion error.
* Ignore `break`s within cases inside `for...of`.
* **Polish**
* Split up variable declarations and export declarations to allow easier transformation.
## 4.7.0
* **Bug Fix**
* Add `alternate` to list of `STATEMENT_OR_BLOCK` keys.
* Add support for module specifiers to `t.isReferenced`.
* **New Feature**
* Add `inputSourceMap` option.
* **Polish**
* Throw an error on different `babel` and `babel-runtime` versions.
* Replicate module environment for `babel-node` eval.
* Clean up classes output.
* **Spec Compliancy**
* Make it illegal to use a rest parameter on a setter.
## 4.6.6
* **Bug Fix**
* Fix incorrect method call in `utility.deadCodeElimination` transformer.
* Fix `es6.blockScopingTDZ` transformer duplicating binding nodes.
## 4.6.5
* **Internal**
* `useStrict` transformer has been renamed to `strict`.
## 4.6.4
* **Bug Fix**
* Fix `ForOfStatement` not proplery inheriting labels.
* When in closure mode in block scoping transformer, properly check for variable shadowing.
* **New Feature**
* New `utility.inlineEnvironmentVariables` and `utility.inlineExpression` transformers.
## 4.6.3
* **Bug Fix**
* Fix `arguments` being incorrectly aliased in arrow function rest parameter optimisation.
* Make deoptimisation trigger safer.
* **New Feature**
* Flow types are now retained when blacklisting the `flow` transformer.
## 4.6.1
* **Bug Fix**
* Fix generators in template directory being transformed.
* Fix exposure of `util` for plugins.
## 4.6.0
* **New Feature**
* Desugar sticky regexes to a new constructor expression so it can be handled by a polyfill.
* **Spec Compliancy**
* `for...of` now outputs in a lengthy `try...catch` this is to ensure spec compliancy in regards to iterator returns and abrupt completions. See [google/traceur-compiler#1773](https://github.com/google/traceur-compiler/issues/1773) and [babel/babel/#838](https://github.com/babel/babel/issues/838) for more information.
* **Polish**
* Rest parameters that are only refered to via number properties on member expressions are desugared into a direct `arguments` reference. Thanks [@neVERberleRfellerER](https://github.com/neVERberleRfellerER)!
* `$ babel` no longer exits on syntax errors.
* **Internal**
* Upgrade `browserify`.
* Upgrade `source-map`.
* Publicly expose more internals.
## 4.5.5
* **Polish**
* Delete old extensions when overriding them in `babel/register`.
## 4.5.3
* **Bug Fix**
* Fix whitelisting logic for helper build script.
## 4.5.2
* **New Feature**

View File

@@ -1,12 +1,23 @@
<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).
**NOTE:** Please do not send pull requests that fix linting issues. It's highly
likely that they've already been fixed by the time it's submitted and it just
pollutes the git tree.
## Developing
@@ -18,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,24 +51,24 @@ You can run tests via:
$ make test
```
This will usually take around two minutes as it's compiling the entire
[test262](https://github.com/tc39/test262) test suite and validating it's AST.
This is mostly overkill and you can limit the tests to a select few by directly
running them with `mocha`:
```sh
$ mocha test/transformation.js
$ mocha test/core/transformation.js
```
#### Linting
Please follow the correct code style, this ensures that the code is consistent
and increases maintainability.
Use mocha's `--grep` option to run a subset of tests by name:
```sh
$ make lint
$ 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
@@ -63,25 +79,91 @@ $ make lint
* 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**
* No ES6 syntax features or methods, exclusively ES5.
* 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

@@ -1,21 +1,27 @@
MAKEFLAGS = -j1
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 publish build bootstrap publish-core publish-runtime build-core watch-core
.PHONY: clean test test-cov test-clean test-travis test-simple test-all test-browser 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
watch-core:
build-core-test: clean-core
node $(BABEL_CMD) src --out-dir lib --copy-files --auxiliary-comment "istanbul ignore next"
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
@@ -28,45 +34,41 @@ build:
node $(BROWSERIFY_CMD) lib/babel/api/browser.js -s babel >dist/babel.js
node $(UGLIFY_CMD) dist/babel.js >dist/babel.min.js
node bin/babel-external-helpers >dist/external-helpers.js
node packages/babel-cli/bin/babel-external-helpers >dist/external-helpers.js
node $(UGLIFY_CMD) dist/external-helpers.js >dist/external-helpers.min.js
rm -rf templates.json
clean:
rm -rf coverage templates.json test/tmp dist
rm -rf coverage templates.json test/tmp dist lib
test-clean:
rm -rf test/tmp
test:
$(MOCHA_CMD)
test: test-parser
node $(MOCHA_CMD) test/core
make test-clean
test-simple:
# excludes test262
export SIMPLE_BABEL_TESTS=1; \
make test
test-all:
export ALL_BABEL_TESTS=1; \
make test
test-cov:
rm -rf coverage
export SIMPLE_BABEL_TESTS=1; \
node $(ISTANBUL_CMD) $(MOCHA_CMD) --
make build-core-test
node $(ISTANBUL_CMD) $(MOCHA_CMD) -- test/core
test-travis: bootstrap build
node $(ISTANBUL_CMD) $(MOCHA_CMD) --
if test -n "$$CODECLIMATE_REPO_TOKEN"; then codeclimate < coverage/lcov.info; fi
test-parser:
node test/acorn/run.js
test-travis: bootstrap build test
test-browser:
mkdir -p dist
node tools/cache-templates
node tools/cache-tests
node $(BROWSERIFY_CMD) -e test/_browser.js >dist/babel-test.js
node tools/build-tests
node $(BROWSERIFY_CMD) -e test/core/_browser.js >dist/babel-test.js
rm -rf templates.json tests.json
test -n "`which open`" && open test/browser.html
@@ -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
@@ -91,10 +99,10 @@ publish:
git push --follow-tags
make publish-core
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; \
@@ -102,18 +110,16 @@ publish-runtime:
cd babel-runtime; \
npm publish
publish-core:
tools/generate-core-package-json >package2.json
mv package.json .package.json
mv package2.json package.json
publish-cli:
cd packages; \
node build-cli.js; \
cd babel-cli; \
npm publish
rm -rf package.json
mv .package.json package.json
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 && 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

@@ -5,11 +5,11 @@
</p>
<p align="center">
<strong>Babel</strong> is a transpiler for writing next generation JavaScript.
<strong>Babel</strong> is a compiler for writing next generation JavaScript.
</p>
<p align="center">
For questions and support please visit the <a href="https://gitter.im/babel/babel">gitter room</a> before creating an issue.
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,4 +0,0 @@
#!/usr/bin/env node
var runtime = require("../lib/babel/build-external-helpers");
console.log(runtime());

View File

@@ -1,69 +0,0 @@
#!/usr/bin/env node
/**
* This tiny wrapper file checks for known node flags and appends them
* when found, before invoking the "real" _babel-node(1) executable.
*/
var args = [__dirname + "/_babel-node"];
process.argv.slice(2).forEach(function(arg){
var flag = arg.split("=")[0];
switch (flag) {
case "-d":
args.unshift("--debug");
break;
case "debug":
case "--debug":
case "--debug-brk":
args.unshift(arg);
break;
case "-gc":
case "--expose-gc":
args.unshift("--expose-gc");
break;
case "--gc-global":
case "--harmony":
case "--harmony-proxies":
case "--harmony-collections":
case "--harmony-generators":
case "--no-deprecation":
case "--prof":
case "--throw-deprecation":
case "--trace-deprecation":
case "--use-strict":
args.unshift(arg);
break;
default:
if (arg.indexOf("--trace") === 0) {
args.unshift(arg);
} else {
args.push(arg);
}
break;
}
});
try {
var kexec = require("kexec");
kexec(process.argv[0], args);
} catch (err) {
if (err.code !== "MODULE_NOT_FOUND") throw err;
var child_process = require("child_process");
var proc = child_process.spawn(process.argv[0], args, { stdio: "inherit" });
proc.on("exit", function (code, signal) {
process.on("exit", function () {
if (signal) {
process.kill(process.pid, signal);
} else {
process.exit(code);
}
})
});
}

View File

@@ -1,130 +0,0 @@
#!/usr/bin/env node
var commander = require("commander");
var transform = require("../../lib/babel/transformation");
var util = require("../../lib/babel/util");
var fs = require("fs");
var each = require("lodash/collection/each");
var keys = require("lodash/object/keys");
commander.option("-t, --source-maps-inline", "Append sourceMappingURL comment to bottom of code");
commander.option("-s, --source-maps", "Save source map alongside the compiled code");
commander.option("-f, --filename [filename]", "Filename to use when reading from stdin - this will be used in source-maps, errors etc [stdin]", "stdin");
commander.option("-w, --watch", "Recompile files on changes");
commander.option("-r, --external-helpers", "Replace helpers with references to a `babelHelpers` global");
commander.option("-e, --experimental", "Enable experimental support for proposed ES7 features");
commander.option("-p, --playground", "Enable playground support");
commander.option("-c, --compact [mode]", "When set to \"auto\" compact is `true` when the input size exceeds 100KB. (auto|true|false)", "auto");
commander.option("-m, --modules [modules]", "Module formatter type to use [common]", "common");
commander.option("-l, --whitelist [whitelist]", "Whitelist of transformers to ONLY use", util.list);
commander.option("-b, --blacklist [blacklist]", "Blacklist of transformers to NOT use", util.list);
commander.option("-i, --optional [list]", "List of optional transformers to enable", util.list);
commander.option("-L, --loose [list]", "List of transformers to enable loose mode ON", util.list);
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");
commander.option("-c, --remove-comments", "Remove comments from the compiled code", false);
commander.option("-M, --module-ids", "Insert module id in modules", false);
commander.option("-R, --react-compat", "Makes the react transformer produce pre-v0.12 code");
commander.option("--keep-module-id-extensions", "Keep extensions when generating module ids", false);
commander.option("-a, --auxiliary-comment [comment]", "Comment text to prepend to all auxiliary code");
commander.option("-D, --copy-files", "When compiling a directory copy over non-compilable files");
commander.on("--help", function () {
var outKeys = function (title, obj) {
console.log(" " + title + ":");
console.log();
each(keys(obj).sort(), function (key) {
if (key[0] === "_") return;
if (obj[key].optional) {
key = "[" + key + "]";
}
console.log(" - " + key);
});
console.log();
};
outKeys("Transformers", transform.transformers);
outKeys("Module formatters", transform.moduleFormatters);
});
var pkg = require("../../package.json");
commander.version(pkg.version);
commander.usage("[options] <files ...>");
commander.parse(process.argv);
//
var errors = [];
var filenames = commander.args;
each(filenames, function (filename) {
if (!fs.existsSync(filename)) {
errors.push(filename + " doesn't exist");
}
});
if (commander.outDir && !filenames.length) {
errors.push("filenames required for --out-dir");
}
if (commander.outFile && commander.outDir) {
errors.push("cannot have --out-file and --out-dir");
}
if (commander.watch) {
if (!commander.outFile && !commander.outDir) {
errors.push("--watch requires --out-file or --out-dir");
}
if (!filenames.length) {
errors.push("--watch requires filenames");
}
}
if (commander.sourceMaps) {
if (!commander.outFile && !commander.outDir) {
errors.push("--source-maps requires --out-file or --out-dir");
}
}
if (errors.length) {
console.error(errors.join(". "));
process.exit(2);
}
//
exports.opts = {
keepModuleIdExtensions: commander.keepModuleIdExtensions,
auxiliaryComment: commander.auxiliaryComment,
externalHelpers: commander.externalHelpers,
sourceMapName: commander.outFile,
experimental: commander.experimental,
reactCompat: commander.reactCompat,
playground: commander.playground,
moduleIds: commander.moduleIds,
blacklist: commander.blacklist,
whitelist: commander.whitelist,
sourceMap: commander.sourceMaps || commander.sourceMapsInline,
optional: commander.optional,
comments: !commander.removeComments,
modules: commander.modules,
compact: commander.compact,
loose: commander.loose
};
var fn;
if (commander.outDir) {
fn = require("./dir");
} else {
fn = require("./file");
}
fn(commander, filenames, exports.opts);

View File

@@ -1,3 +0,0 @@
#!/usr/bin/env node
console.error("`6to5` has been renamed to `babel`");
require("../babel");

View File

@@ -1,3 +0,0 @@
#!/usr/bin/env node
console.error("`6to5-node` has been renamed to `babel-node`");
require("../_babel-node");

View File

@@ -1,3 +0,0 @@
#!/usr/bin/env node
console.error("`6to5-runtime` has been renamed to `babel-external-helpers`");
require("../babel-external-helpers");

View File

@@ -1,23 +1,15 @@
{
"name": "babel",
"name": "babel-core",
"description": "Turn ES6 code into readable vanilla ES5 with source maps",
"version": "4.5.3",
"version": "5.4.1",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/",
"license": "MIT",
"repository": "babel/babel",
"preferGlobal": true,
"main": "lib/babel/api/node.js",
"browser": {
"./lib/babel/api/register/node.js": "./lib/babel/api/register/browser.js"
},
"bin": {
"6to5": "./bin/deprecated/6to5",
"6to5-node": "./bin/deprecated/6to5-node",
"6to5-runtime": "./bin/deprecated/6to5-runtime",
"babel": "./bin/babel/index.js",
"babel-node": "./bin/babel-node",
"babel-external-helpers": "./bin/babel-external-helpers"
},
"keywords": [
"harmony",
"classes",
@@ -36,45 +28,52 @@
"test": "make test"
},
"dependencies": {
"acorn-babel": "0.11.1-35",
"ast-types": "~0.6.1",
"acorn-jsx": "^1.0.0",
"ast-types": "~0.7.0",
"bluebird": "^2.9.25",
"chalk": "^1.0.0",
"chokidar": "^0.12.6",
"commander": "^2.6.0",
"core-js": "^0.6.1",
"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": "0.4.1",
"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-1",
"regexpu": "^1.1.1",
"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.1.43",
"source-map-support": "^0.2.9",
"source-map-to-comment": "^1.0.0",
"trim-right": "^1.0.0"
"source-map": "^0.4.0",
"source-map-support": "^0.2.10",
"strip-json-comments": "^1.0.2",
"to-fast-properties": "^1.0.0",
"trim-right": "^1.0.0",
"user-home": "^1.1.1"
},
"devDependencies": {
"babel": "4.5.1",
"browserify": "^8.1.3",
"chai": "^2.0.0",
"babel": "5.3.1",
"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

@@ -1,6 +0,0 @@
# What is this?
This is a folder containing additional packages that are built whenever
a new version of babel is released.
**TODO:** Move `babel-core` into here.

View File

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

View File

@@ -3,10 +3,11 @@
var pathIsAbsolute = require("path-is-absolute");
var commander = require("commander");
var Module = require("module");
var babel = require("../lib/babel/api/node");
var babel = require("babel-core");
var inspect = require("util").inspect;
var path = require("path");
var repl = require("repl");
var util = require("../lib/babel/util");
var util = require("babel-core").util;
var vm = require("vm");
var _ = require("lodash");
@@ -16,8 +17,7 @@ program.option("-e, --eval [script]", "Evaluate script");
program.option("-p, --print [code]", "Evaluate script and print result");
program.option("-i, --ignore [regex]", "Ignore all files that match this regex when using the require hook");
program.option("-x, --extensions [extensions]", "List of extensions to hook into [.es6,.js,.es,.jsx]");
program.option("-r, --experimental", "Enable experimental support for proposed ES7 features");
program.option("-g, --playground", "Enable playground support");
program.option("-r, --stage [stage]", "Enable support for specific ECMAScript stages");
program.option("-w, --whitelist [whitelist]", "Whitelist of transformers to ONLY use", util.list);
program.option("-b, --blacklist [blacklist]", "Blacklist of transformers to NOT use", util.list);
program.option("-o, --optional [optional]", "List of optional transformers to enable", util.list);
@@ -30,25 +30,25 @@ program.parse(process.argv);
//
babel.register({
experimental: program.experimental,
extensions: program.extensions,
playground: program.playground,
blacklist: program.blacklist,
whitelist: program.whitelist,
optional: program.optional,
ignore: program.ignore
ignore: program.ignore,
stage: program.stage,
});
//
var _eval = function (code, filename) {
if (!code) return undefined;
code = babel.transform(code, {
filename: filename,
blacklist: ["useStrict"].concat(program.blacklist || []),
blacklist: program.blacklist,
whitelist: program.whitelist,
optional: program.optional,
experimental: program.experimental,
playground: program.playground
stage: program.stage
}).code;
return vm.runInThisContext(code, {
@@ -60,8 +60,22 @@ if (program.eval || program.print) {
var code = program.eval;
if (!code || code === true) code = program.print;
var result = _eval(code, "eval");
if (program.print) console.log(result);
global.__filename = "[eval]";
global.__dirname = process.cwd();
var module = new Module(global.__filename);
module.filename = global.__filename;
module.paths = Module._nodeModulePaths(global.__dirname);
global.exports = module.exports;
global.module = module;
global.require = module.require.bind(module);
var result = _eval(code, global.__filename);
if (program.print) {
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
@@ -88,7 +102,7 @@ if (program.eval || program.print) {
args = args.slice(i);
// make the filename absolute
var filename = args[0]
var filename = args[0];
if (!pathIsAbsolute(filename)) args[0] = path.join(process.cwd(), filename);
// add back on node and concat the sliced args

View File

@@ -0,0 +1,13 @@
#!/usr/bin/env node
var commander = require("commander");
var util = require("babel-core").util;
var runtime = require("babel-core").buildExternalHelpers;
commander.option("-l, --whitelist [whitelist]", "Whitelist of helpers to ONLY include", util.list);
commander.option("-t, --output-type [type]", "Type of output (global|umd|var)", "global");
commander.usage("[options]");
commander.parse(process.argv);
console.log(runtime(commander.whitelist, commander.outputType));

450
packages/babel-cli/bin/babel-node Executable file
View File

@@ -0,0 +1,450 @@
#!/usr/bin/env node
/**
* This tiny wrapper file checks for known node flags and appends them
* when found, before invoking the "real" _babel-node(1) executable.
*/
var args = [__dirname + "/_babel-node"];
var babelArgs = process.argv.slice(2);
var userArgs;
// separate node arguments from script arguments
var argSeparator = babelArgs.indexOf("--");
if (argSeparator > -1) {
userArgs = babelArgs.slice(argSeparator); // including the --
babelArgs = babelArgs.slice(0, argSeparator);
}
babelArgs.forEach(function(arg){
var flag = arg.split("=")[0];
switch (flag) {
case "-d":
args.unshift("--debug");
break;
case "debug":
case "--debug":
case "--debug-brk":
args.unshift(arg);
break;
case "-gc":
case "--expose-gc":
args.unshift("--expose-gc");
break;
case "--use_strict":
case "--es_staging":
case "--harmony":
case "--harmony_shipping":
case "--harmony_modules":
case "--harmony_arrays":
case "--harmony_array_includes":
case "--harmony_regexps":
case "--harmony_arrow_functions":
case "--harmony_proxies":
case "--harmony_sloppy":
case "--harmony_unicode":
case "--harmony_tostring":
case "--harmony_numeric_literals":
case "--harmony_strings":
case "--harmony_scoping":
case "--harmony_classes":
case "--harmony_object_literals":
case "--harmony_templates":
case "--harmony_rest_parameters":
case "--harmony_generators":
case "--compiled_keyed_generic_loads":
case "--pretenuring_call_new":
case "--allocation_site_pretenuring":
case "--trace_pretenuring":
case "--trace_pretenuring_statistics":
case "--track_fields":
case "--track_double_fields":
case "--track_heap_object_fields":
case "--track_computed_fields":
case "--track_field_types":
case "--smi_binop":
case "--vector_ics":
case "--optimize_for_size":
case "--unbox_double_arrays":
case "--string_slices":
case "--crankshaft":
case "--hydrogen_filter":
case "--use_gvn":
case "--gvn_iterations":
case "--use_canonicalizing":
case "--use_inlining":
case "--use_escape_analysis":
case "--use_allocation_folding":
case "--use_local_allocation_folding":
case "--use_write_barrier_elimination":
case "--max_inlining_levels":
case "--max_inlined_source_size":
case "--max_inlined_nodes":
case "--max_inlined_nodes_cumulative":
case "--loop_invariant_code_motion":
case "--fast_math":
case "--collect_megamorphic_maps_from_stub_cache":
case "--hydrogen_stats":
case "--trace_check_elimination":
case "--trace_hydrogen":
case "--trace_hydrogen_filter":
case "--trace_hydrogen_stubs":
case "--trace_hydrogen_file":
case "--trace_phase":
case "--trace_inlining":
case "--trace_load_elimination":
case "--trace_store_elimination":
case "--trace_alloc":
case "--trace_all_uses":
case "--trace_range":
case "--trace_gvn":
case "--trace_representation":
case "--trace_removable_simulates":
case "--trace_escape_analysis":
case "--trace_allocation_folding":
case "--trace_track_allocation_sites":
case "--trace_migration":
case "--trace_generalization":
case "--stress_pointer_maps":
case "--stress_environments":
case "--deopt_every_n_times":
case "--deopt_every_n_garbage_collections":
case "--print_deopt_stress":
case "--trap_on_deopt":
case "--trap_on_stub_deopt":
case "--deoptimize_uncommon_cases":
case "--polymorphic_inlining":
case "--use_osr":
case "--array_bounds_checks_elimination":
case "--trace_bce":
case "--array_bounds_checks_hoisting":
case "--array_index_dehoisting":
case "--analyze_environment_liveness":
case "--load_elimination":
case "--check_elimination":
case "--store_elimination":
case "--dead_code_elimination":
case "--fold_constants":
case "--trace_dead_code_elimination":
case "--unreachable_code_elimination":
case "--trace_osr":
case "--stress_runs":
case "--lookup_sample_by_shared":
case "--cache_optimized_code":
case "--flush_optimized_code_cache":
case "--inline_construct":
case "--inline_arguments":
case "--inline_accessors":
case "--escape_analysis_iterations":
case "--optimize_for_in":
case "--concurrent_recompilation":
case "--job_based_recompilation":
case "--trace_concurrent_recompilation":
case "--concurrent_recompilation_queue_length":
case "--concurrent_recompilation_delay":
case "--block_concurrent_recompilation":
case "--concurrent_osr":
case "--omit_map_checks_for_leaf_maps":
case "--turbo_filter":
case "--trace_turbo":
case "--trace_turbo_graph":
case "--trace_turbo_cfg_file":
case "--trace_turbo_types":
case "--trace_turbo_scheduler":
case "--trace_turbo_reduction":
case "--trace_turbo_jt":
case "--turbo_asm":
case "--turbo_verify":
case "--turbo_stats":
case "--turbo_types":
case "--turbo_source_positions":
case "--context_specialization":
case "--turbo_deoptimization":
case "--turbo_inlining":
case "--turbo_inlining_intrinsics":
case "--trace_turbo_inlining":
case "--loop_assignment_analysis":
case "--turbo_profiling":
case "--turbo_reuse_spill_slots":
case "--turbo_delay_ssa_decon":
case "--turbo_move_optimization":
case "--turbo_jt":
case "--typed_array_max_size_in_heap":
case "--frame_count":
case "--interrupt_budget":
case "--type_info_threshold":
case "--generic_ic_threshold":
case "--self_opt_count":
case "--trace_opt_verbose":
case "--debug_code":
case "--code_comments":
case "--enable_sse3":
case "--enable_sse4_1":
case "--enable_sahf":
case "--enable_avx":
case "--enable_fma3":
case "--enable_vfp3":
case "--enable_armv7":
case "--enable_armv8":
case "--enable_neon":
case "--enable_sudiv":
case "--enable_mls":
case "--enable_movw_movt":
case "--enable_unaligned_accesses":
case "--enable_32dregs":
case "--enable_vldr_imm":
case "--force_long_branches":
case "--expose_natives_as":
case "--expose_debug_as":
case "--expose_free_buffer":
case "--expose_gc":
case "--expose_gc_as":
case "--expose_externalize_string":
case "--expose_trigger_failure":
case "--stack_trace_limit":
case "--builtins_in_stack_traces":
case "--disable_native_files":
case "--inline_new":
case "--trace_codegen":
case "--trace":
case "--mask_constants_with_cookie":
case "--lazy":
case "--trace_opt":
case "--trace_opt_stats":
case "--opt":
case "--always_opt":
case "--always_osr":
case "--prepare_always_opt":
case "--trace_deopt":
case "--trace_stub_failures":
case "--serialize_toplevel":
case "--serialize_inner":
case "--trace_serializer":
case "--min_preparse_length":
case "--max_opt_count":
case "--compilation_cache":
case "--cache_prototype_transitions":
case "--cpu_profiler_sampling_interval":
case "--trace_debug_json":
case "--trace_js_array_abuse":
case "--trace_external_array_abuse":
case "--trace_array_abuse":
case "--enable_liveedit":
case "--hard_abort":
case "--stack_size":
case "--max_stack_trace_source_length":
case "--always_inline_smi_code":
case "--min_semi_space_size":
case "--target_semi_space_size":
case "--max_semi_space_size":
case "--semi_space_growth_factor":
case "--experimental_new_space_growth_heuristic":
case "--max_old_space_size":
case "--initial_old_space_size":
case "--max_executable_size":
case "--gc_global":
case "--gc_interval":
case "--trace_gc":
case "--trace_gc_nvp":
case "--trace_gc_ignore_scavenger":
case "--trace_idle_notification":
case "--trace_idle_notification_verbose":
case "--print_cumulative_gc_stat":
case "--print_max_heap_committed":
case "--trace_gc_verbose":
case "--trace_fragmentation":
case "--collect_maps":
case "--weak_embedded_maps_in_optimized_code":
case "--weak_embedded_objects_in_optimized_code":
case "--flush_code":
case "--flush_code_incrementally":
case "--trace_code_flushing":
case "--age_code":
case "--incremental_marking":
case "--incremental_marking_steps":
case "--concurrent_sweeping":
case "--trace_incremental_marking":
case "--track_gc_object_stats":
case "--heap_profiler_trace_objects":
case "--use_idle_notification":
case "--use_ic":
case "--trace_ic":
case "--native_code_counters":
case "--always_compact":
case "--never_compact":
case "--compact_code_space":
case "--incremental_code_compaction":
case "--cleanup_code_caches_at_gc":
case "--use_marking_progress_bar":
case "--zap_code_space":
case "--random_seed":
case "--trace_weak_arrays":
case "--track_prototype_users":
case "--use_verbose_printer":
case "--allow_natives_syntax":
case "--trace_parse":
case "--trace_sim":
case "--debug_sim":
case "--check_icache":
case "--stop_sim_at":
case "--sim_stack_alignment":
case "--sim_stack_size":
case "--log_regs_modified":
case "--log_colour":
case "--ignore_asm_unimplemented_break":
case "--trace_sim_messages":
case "--stack_trace_on_illegal":
case "--abort_on_uncaught_exception":
case "--randomize_hashes":
case "--hash_seed":
case "--profile_deserialization":
case "--regexp_optimization":
case "--testing_bool_flag":
case "--testing_maybe_bool_flag":
case "--testing_int_flag":
case "--testing_float_flag":
case "--testing_string_flag":
case "--testing_prng_seed":
case "--testing_serialization_file":
case "--startup_blob":
case "--profile_hydrogen_code_stub_compilation":
case "--predictable":
case "--help":
case "--dump_counters":
case "--debugger":
case "--map_counters":
case "--js_arguments":
case "--gdbjit":
case "--gdbjit_full":
case "--gdbjit_dump":
case "--gdbjit_dump_filter":
case "--force_marking_deque_overflows":
case "--stress_compaction":
case "--log":
case "--log_all":
case "--log_api":
case "--log_code":
case "--log_gc":
case "--log_handles":
case "--log_snapshot_positions":
case "--log_suspect":
case "--prof":
case "--prof_browser_mode":
case "--log_regexp":
case "--logfile":
case "--logfile_per_isolate":
case "--ll_prof":
case "--perf_basic_prof":
case "--perf_jit_prof":
case "--gc_fake_mmap":
case "--log_internal_timer_events":
case "--log_timer_events":
case "--log_instruction_stats":
case "--log_instruction_file":
case "--log_instruction_period":
case "--redirect_code_traces":
case "--redirect_code_traces_to":
case "--hydrogen_track_positions":
case "--trace_elements_transitions":
case "--trace_creation_allocation_sites":
case "--print_code_stubs":
case "--test_secondary_stub_cache":
case "--test_primary_stub_cache":
case "--print_code":
case "--print_opt_code":
case "--print_unopt_code":
case "--print_code_verbose":
case "--print_builtin_code":
case "--sodium":
case "--print_all_code":
case "--es5_readonly":
case "--es52_globals":
case "--harmony_typeof":
case "--harmony_collections":
case "--packed_arrays":
case "--smi_only_arrays":
case "--clever_optimizations":
case "--use_range":
case "--eliminate_dead_phis":
case "--optimize_closures":
case "--loop_weight":
case "--opt_safe_uint32_operations":
case "--parallel_recompilation":
case "--trace_parallel_recompilation":
case "--parallel_recompilation_queue_length":
case "--experimental_profiler":
case "--watch_ic_patching":
case "--self_optimization":
case "--direct_self_opt":
case "--retry_self_opt":
case "--count_based_interrupts":
case "--interrupt_at_exit":
case "--weighted_back_edges":
case "--debug_code (generate extra code":
case "--enable_sse2":
case "--enable_cmov":
case "--enable_rdtsc":
case "--enable_vfp2":
case "--enable_fpu":
case "--stack_trace_on_abort":
case "--always_full_compiler":
case "--debugger_auto_break":
case "--break_on_abort":
case "--max_new_space_size":
case "--trace_external_memory":
case "--lazy_sweeping":
case "--trace_exception":
case "--preallocate_message_memory":
case "--preemption":
case "--extra_code":
case "--remote_debugger":
case "--debugger_agent":
case "--debugger_port":
case "--debug_compile_events":
case "--debug_script_collected_events":
case "--gdbjit":
case "--log_runtime":
case "--prof_auto":
case "--prof_lazy":
case "--sliding_state_window":
args.unshift(arg);
break;
default:
if (arg.indexOf("--trace") === 0) {
args.unshift(arg);
} else {
args.push(arg);
}
break;
}
});
// append arguments passed after --
if (argSeparator > -1) {
args = args.concat(userArgs);
}
try {
var kexec = require("kexec");
kexec(process.argv[0], args);
} catch (err) {
if (err.code !== "MODULE_NOT_FOUND") throw err;
var child_process = require("child_process");
var proc = child_process.spawn(process.argv[0], args, { stdio: "inherit" });
proc.on("exit", function (code, signal) {
process.on("exit", function () {
if (signal) {
process.kill(process.pid, signal);
} else {
process.exit(code);
}
})
});
}

View File

@@ -1,15 +1,12 @@
var outputFileSync = require("output-file-sync");
var chokidar = require("chokidar");
var slash = require("slash");
var path = require("path");
var util = require("./util");
var fs = require("fs");
var _ = require("lodash");
module.exports = function (commander, filenames, opts) {
if (commander.sourceMapsInline) {
opts.sourceMap = "inline";
}
var write = function (src, relative) {
// remove extension and then append back on .js
relative = relative.replace(/\.(\w*?)$/, "") + ".js";
@@ -17,10 +14,11 @@ module.exports = function (commander, filenames, opts) {
var dest = path.join(commander.outDir, relative);
var data = util.compile(src, {
sourceFileName: path.relative(dest + "/..", src)
sourceFileName: slash(path.relative(dest + "/..", src))
});
if (data.ignored) return;
if (commander.sourceMaps) {
if (commander.sourceMaps && commander.sourceMaps !== "inline") {
var mapLoc = dest + ".map";
data.code = util.addSourceMappingUrl(data.code, mapLoc);
outputFileSync(mapLoc, JSON.stringify(data.map));
@@ -31,6 +29,16 @@ module.exports = function (commander, filenames, opts) {
console.log(src + " -> " + dest);
};
var handleFile = function (src, 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));
}
};
var handle = function (filename) {
if (!fs.existsSync(filename)) return;
@@ -41,11 +49,7 @@ module.exports = function (commander, filenames, opts) {
_.each(util.readdir(dirname), function (filename) {
var src = path.join(dirname, filename);
if (util.canCompile(filename)) {
write(src, filename);
} else if (commander.copyFiles) {
outputFileSync(path.join(commander.outDir, filename), fs.readFileSync(src));
}
handleFile(src, filename);
});
} else {
write(filename, filename);
@@ -64,7 +68,11 @@ module.exports = function (commander, filenames, opts) {
_.each(["add", "change"], function (type) {
watcher.on(type, function (filename) {
var relative = path.relative(dirname, filename) || filename;
if (util.canCompile(filename)) write(filename, relative);
try {
handleFile(filename, relative);
} catch (err) {
console.error(err.stack);
}
});
});
});

View File

@@ -1,17 +1,22 @@
var sourceMapToComment = require("source-map-to-comment");
var sourceMap = require("source-map");
var chokidar = require("chokidar");
var path = require("path");
var util = require("./util");
var fs = require("fs");
var _ = require("lodash");
var convertSourceMap = require("convert-source-map");
var sourceMap = require("source-map");
var chokidar = require("chokidar");
var slash = require("slash");
var path = require("path");
var util = require("./util");
var fs = require("fs");
var _ = require("lodash");
module.exports = function (commander, filenames, opts) {
if (commander.sourceMaps === "inline") {
opts.sourceMaps = true;
}
module.exports = function (commander, filenames) {
var results = [];
var buildResult = function () {
var map = new sourceMap.SourceMapGenerator({
file: commander.outFile || "stdout"
file: slash(commander.outFile || "stdout")
});
var code = "";
@@ -24,8 +29,14 @@ module.exports = function (commander, filenames) {
if (result.map) {
var consumer = new sourceMap.SourceMapConsumer(result.map);
map._sources.add(filename);
map.setSourceContent(filename, result.actual);
var sourceFilename = filename;
if (commander.outFile) {
sourceFilename = path.relative(path.dirname(commander.outFile), sourceFilename);
}
sourceFilename = slash(sourceFilename);
map._sources.add(sourceFilename);
map.setSourceContent(sourceFilename, result.actual);
consumer.eachMapping(function (mapping) {
map._mappings.add({
@@ -33,7 +44,7 @@ module.exports = function (commander, filenames) {
generatedColumn: mapping.generatedColumn,
originalLine: mapping.originalLine,
originalColumn: mapping.originalColumn,
source: filename
source: sourceFilename
});
});
@@ -41,8 +52,8 @@ module.exports = function (commander, filenames) {
}
});
if (commander.sourceMapsInline || (!commander.outFile && commander.sourceMaps)) {
code += "\n" + sourceMapToComment(map);
if (commander.sourceMaps === "inline" || (!commander.outFile && commander.sourceMaps)) {
code += "\n" + convertSourceMap.fromObject(map).toComment();
}
return {
@@ -55,7 +66,7 @@ module.exports = function (commander, filenames) {
var result = buildResult();
if (commander.outFile) {
if (commander.sourceMaps) {
if (commander.sourceMaps && commander.sourceMaps !== "inline") {
var mapLoc = commander.outFile + ".map";
result.code = util.addSourceMappingUrl(result.code, mapLoc);
fs.writeFileSync(mapLoc, JSON.stringify(result.map));
@@ -103,7 +114,11 @@ module.exports = function (commander, filenames) {
});
_.each(_filenames, function (filename) {
results.push(util.compile(filename));
if (util.shouldIgnore(filename)) return;
var data = util.compile(filename);
if (data.ignored) return;
results.push(data);
});
output();
@@ -119,7 +134,11 @@ module.exports = function (commander, filenames) {
}).on("all", function (type, filename) {
if (type === "add" || type === "change") {
console.log(type, filename);
walk();
try {
walk();
} catch (err) {
console.error(err.stack);
}
}
});
}

View File

@@ -0,0 +1,133 @@
#!/usr/bin/env node
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;
var arg = kebabCase(key);
if (option.type !== "boolean") {
arg += " [" + (option.type || "string") + "]";
}
if (option.type === "boolean" && option.default === true) {
arg = "no-" + arg;
}
arg = "--" + arg;
if (option.shorthand) {
arg = "-" + option.shorthand + ", " + arg;
}
var desc = [];
if (option.deprecated) desc.push("[DEPRECATED] " + option.deprecated);
if (option.description) desc.push(option.description);
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");
commander.option("-D, --copy-files", "When compiling a directory copy over non-compilable files");
commander.on("--help", function () {
var outKeys = function (title, obj) {
console.log(" " + title + ":");
console.log();
each(keys(obj).sort(), function (key) {
if (key[0] === "_") return;
if (obj[key].optional) key = "[" + key + "]";
console.log(" - " + key);
});
console.log();
};
outKeys("Transformers", transform.pipeline.transformers);
outKeys("Module formatters", moduleFormatters);
});
var pkg = require("../../package.json");
commander.version(pkg.version);
commander.usage("[options] <files ...>");
commander.parse(process.argv);
//
if (commander.extensions) {
commander.extensions = util.arrayify(commander.extensions);
}
//
var errors = [];
var filenames = commander.args.reduce(function (globbed, input) {
return globbed.concat(glob.sync(input));
}, []);
each(filenames, function (filename) {
if (!fs.existsSync(filename)) {
errors.push(filename + " doesn't exist");
}
});
if (commander.outDir && !filenames.length) {
errors.push("filenames required for --out-dir");
}
if (commander.outFile && commander.outDir) {
errors.push("cannot have --out-file and --out-dir");
}
if (commander.watch) {
if (!commander.outFile && !commander.outDir) {
errors.push("--watch requires --out-file or --out-dir");
}
if (!filenames.length) {
errors.push("--watch requires filenames");
}
}
if (errors.length) {
console.error(errors.join(". "));
process.exit(2);
}
//
var opts = exports.opts = {};
each(options, function (opt, 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) {
fn = require("./dir");
} else {
fn = require("./file");
}
fn(commander, filenames, exports.opts);

View File

@@ -1,11 +1,10 @@
var resolveRc = require("../../lib/babel/api/register/resolve-rc");
var readdir = require("fs-readdir-recursive");
var index = require("./index");
var babel = require("../../lib/babel/api/node");
var util = require("../../lib/babel/util");
var path = require("path");
var fs = require("fs");
var _ = require("lodash");
var readdir = require("fs-readdir-recursive");
var index = require("./index");
var babel = require("babel-core");
var util = require("babel-core").util;
var path = require("path");
var fs = require("fs");
var _ = require("lodash");
exports.readdirFilter = function (filename) {
return readdir(filename).filter(function (filename) {
@@ -17,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);
};
@@ -24,19 +27,10 @@ exports.addSourceMappingUrl = function (code, loc) {
exports.transform = function (filename, code, opts) {
opts = _.defaults(opts || {}, index.opts);
opts.filename = filename;
resolveRc(filename, opts);
opts.ignore = null;
opts.only = null;
var result;
try {
result = babel.transform(code, opts);
} catch (e) {
if (e instanceof SyntaxError) {
console.error("SyntaxError:", e.message);
process.exit(1);
} else {
throw e;
}
}
var result = babel.transform(code, opts);
result.filename = filename;
result.actual = code;
return result;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,4 @@
module.exports = {
"default": require("core-js/library"),
__esModule: true
};

View File

@@ -1,7 +1,11 @@
{
"name": "babel-runtime",
"description": "babel selfContained runtime",
"version": "4.5.2",
"version": "5.4.0",
"license": "MIT",
"repository": "babel/babel",
"author": "Sebastian McKenzie <sebmck@gmail.com>"
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"dependencies": {
"core-js": "^0.9.0"
}
}

11
packages/build-cli.js Normal file
View File

@@ -0,0 +1,11 @@
var outputFile = require("output-file-sync");
var pkgLoc = __dirname + "/babel-cli/package.json";
var pkg = require(pkgLoc);
var mainPkg = require("../package.json");
pkg.version = mainPkg.version;
pkg.dependencies["babel-core"] = "^" + mainPkg.version;
outputFile(pkgLoc, JSON.stringify(pkg, null, 2));

View File

@@ -1,61 +1,98 @@
"use strict";
var buildHelpers = require("../lib/babel/build-helpers");
var transform = require("../lib/babel/transformation");
var util = require("../lib/babel/util");
var fs = require("fs");
var t = require("../lib/babel/types");
var _ = require("lodash");
var outputFile = require("output-file-sync");
var transform = require("../lib/babel/transformation");
var each = require("lodash/collection/each");
var File = require("../lib/babel/transformation/file");
var util = require("../lib/babel/util");
var fs = require("fs");
var t = require("../lib/babel/types");
var _ = require("lodash");
var relative = function (filename) {
function relative(filename) {
return __dirname + "/babel-runtime/" + filename;
};
}
var writeFile = function (filename, content) {
filename = relative(filename);
console.log(filename);
fs.writeFileSync(filename, content);
};
var readFile = function (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;
};
}
var updatePackage = function () {
function defaultify(name) {
return 'module.exports = { "default": ' + name + ', __esModule: true };';
}
function updatePackage() {
var pkgLoc = relative("package.json");
var pkg = require(pkgLoc);
var mainPkg = require("../package.json");
pkg.version = mainPkg.version;
writeFile("package.json", JSON.stringify(pkg, null, 2));
};
writeRootFile("package.json", JSON.stringify(pkg, null, 2));
}
var selfContainify = function (code) {
function writeRootFile(filename, content) {
filename = relative(filename);
console.log(filename);
outputFile(filename, content);
}
function writeFile(filename, content) {
return writeRootFile(filename, content);
}
function selfContainify(code) {
return transform(code, {
optional: ["selfContained"]
optional: ["runtime"]
}).code;
};
}
var buildHelpers2 = function () {
var body = util.template("self-contained-helpers-head");
var tree = t.program(body);
buildHelpers(body, t.identifier("helpers"));
function buildHelper(helperName) {
var tree = t.program(
util.template("self-contained-helpers-head", {
HELPER: util.template("helper-" + helperName)
})
);
return transform.fromAst(tree, null, {
optional: ["selfContained"]
optional: ["runtime"]
}).code;
};
}
each(File.helpers, function (helperName) {
writeFile("helpers/" + helperName + ".js", buildHelper(helperName));
});
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 + '")'));
});
//
writeFile("helpers.js", buildHelpers2());
writeFile("core-js.js", readFile("core-js/library", true));
writeFile("regenerator/index.js", readFile("regenerator-babel/runtime-module", true));
writeFile("regenerator/runtime.js", selfContainify(readFile("regenerator-babel/runtime")));
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");

48
sebmck-bjs.nfo Normal file
View File

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

32
src/acorn/AUTHORS Executable file
View File

@@ -0,0 +1,32 @@
List of Acorn contributors. Updated before every release.
Alistair Braidwood
Aparajita Fishman
Arian Stolwijk
Artem Govorov
Brandon Mills
Charles Hughes
Conrad Irwin
David Bonnet
impinball
Ingvar Stepanyan
Jiaxing Wang
Johannes Herr
Jürg Lehni
keeyipchan
krator
Marijn Haverbeke
Martin Carlberg
Mathias Bynens
Mathieu 'p01' Henri
Max Schaefer
Mihai Bazon
Mike Rennie
Oskar Schöldström
Paul Harper
Peter Rust
PlNG
r-e-d
Rich Harris
Sebastian McKenzie
zsjforcn

19
src/acorn/LICENSE Executable file
View File

@@ -0,0 +1,19 @@
Copyright (C) 2012-2014 by various contributors (see AUTHORS)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

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);

44
src/acorn/package.json Executable file
View File

@@ -0,0 +1,44 @@
{
"name": "acorn",
"description": "ECMAScript parser",
"homepage": "https://github.com/marijnh/acorn",
"main": "index.js",
"version": "1.0.0",
"engines": {
"node": ">=0.4.0"
},
"maintainers": [
{
"name": "Marijn Haverbeke",
"email": "marijnh@gmail.com",
"web": "http://marijnhaverbeke.nl"
},
{
"name": "Ingvar Stepanyan",
"email": "me@rreverser.com",
"web": "http://rreverser.com/"
}
],
"repository": {
"type": "git",
"url": "https://github.com/marijnh/acorn.git"
},
"licenses": [
{
"type": "MIT",
"url": "https://raw.githubusercontent.com/marijnh/acorn/master/LICENSE"
}
],
"scripts": {
"test": "node test/run.js",
"prepublish": "node bin/prepublish.sh"
},
"bin": {
"acorn": "./bin/acorn"
},
"devDependencies": {
"babelify": "^5.0.4",
"browserify": "^9.0.3",
"unicode-7.0.0": "~0.1.5"
}
}

836
src/acorn/plugins/flow.js Normal file
View File

@@ -0,0 +1,836 @@
var acorn = require("../src/index")
var pp = acorn.Parser.prototype
var tt = acorn.tokTypes
pp.isRelational = function (op) {
return this.type === tt.relational && this.value === op
}
pp.expectRelational = function (op) {
if (this.isRelational(op)) {
this.next()
} else {
this.unexpected()
}
}
pp.flow_parseDeclareClass = function (node) {
this.next()
this.flow_parseInterfaceish(node, true)
return this.finishNode(node, "DeclareClass")
}
pp.flow_parseDeclareFunction = function (node) {
this.next()
var id = node.id = this.parseIdent()
var typeNode = this.startNode()
var typeContainer = this.startNode()
if (this.isRelational("<")) {
typeNode.typeParameters = this.flow_parseTypeParameterDeclaration()
} else {
typeNode.typeParameters = null
}
this.expect(tt.parenL)
var tmp = this.flow_parseFunctionTypeParams()
typeNode.params = tmp.params
typeNode.rest = tmp.rest
this.expect(tt.parenR)
this.expect(tt.colon)
typeNode.returnType = this.flow_parseType()
typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation")
id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation")
this.finishNode(id, id.type)
this.semicolon()
return this.finishNode(node, "DeclareFunction")
}
pp.flow_parseDeclare = function (node) {
if (this.type === tt._class) {
return this.flow_parseDeclareClass(node)
} else if (this.type === tt._function) {
return this.flow_parseDeclareFunction(node)
} else if (this.type === tt._var) {
return this.flow_parseDeclareVariable(node)
} else if (this.isContextual("module")) {
return this.flow_parseDeclareModule(node)
} else {
this.unexpected()
}
}
pp.flow_parseDeclareVariable = function (node) {
this.next()
node.id = this.flow_parseTypeAnnotatableIdentifier()
this.semicolon()
return this.finishNode(node, "DeclareVariable")
}
pp.flow_parseDeclareModule = function (node) {
this.next()
if (this.type === tt.string) {
node.id = this.parseExprAtom()
} else {
node.id = this.parseIdent()
}
var bodyNode = node.body = this.startNode()
var body = bodyNode.body = []
this.expect(tt.braceL)
while (this.type !== tt.braceR) {
var node2 = this.startNode()
// todo: declare check
this.next()
body.push(this.flow_parseDeclare(node2))
}
this.expect(tt.braceR)
this.finishNode(bodyNode, "BlockStatement")
return this.finishNode(node, "DeclareModule")
}
// Interfaces
pp.flow_parseInterfaceish = function (node, allowStatic) {
node.id = this.parseIdent()
if (this.isRelational("<")) {
node.typeParameters = this.flow_parseTypeParameterDeclaration()
} else {
node.typeParameters = null
}
node.extends = []
if (this.eat(tt._extends)) {
do {
node.extends.push(this.flow_parseInterfaceExtends())
} while(this.eat(tt.comma))
}
node.body = this.flow_parseObjectType(allowStatic)
}
pp.flow_parseInterfaceExtends = function () {
var node = this.startNode()
node.id = this.parseIdent()
if (this.isRelational("<")) {
node.typeParameters = this.flow_parseTypeParameterInstantiation()
} else {
node.typeParameters = null
}
return this.finishNode(node, "InterfaceExtends")
}
pp.flow_parseInterface = function (node) {
this.flow_parseInterfaceish(node, false)
return this.finishNode(node, "InterfaceDeclaration")
}
// Type aliases
pp.flow_parseTypeAlias = function (node) {
node.id = this.parseIdent()
if (this.isRelational("<")) {
node.typeParameters = this.flow_parseTypeParameterDeclaration()
} else {
node.typeParameters = null
}
var oldInType = this.inType;
this.inType = true;
this.expect(tt.eq)
node.right = this.flow_parseType()
this.inType = oldInType;
this.semicolon()
return this.finishNode(node, "TypeAlias")
}
// Type annotations
pp.flow_parseTypeParameterDeclaration = function () {
var node = this.startNode()
node.params = []
this.expectRelational("<")
while (!this.isRelational(">")) {
node.params.push(this.flow_parseTypeAnnotatableIdentifier())
if (!this.isRelational(">")) {
this.expect(tt.comma)
}
}
this.expectRelational(">")
return this.finishNode(node, "TypeParameterDeclaration")
}
pp.flow_parseTypeParameterInstantiation = function () {
var node = this.startNode(), oldInType = this.inType
node.params = []
this.inType = true
this.expectRelational("<")
while (!this.isRelational(">")) {
node.params.push(this.flow_parseType())
if (!this.isRelational(">")) {
this.expect(tt.comma)
}
}
this.expectRelational(">")
this.inType = oldInType
return this.finishNode(node, "TypeParameterInstantiation")
}
pp.flow_parseObjectPropertyKey = function () {
return (this.type === tt.num || this.type === tt.string) ? this.parseExprAtom() : this.parseIdent(true)
}
pp.flow_parseObjectTypeIndexer = function (node, isStatic) {
node.static = isStatic
this.expect(tt.bracketL)
node.id = this.flow_parseObjectPropertyKey()
this.expect(tt.colon)
node.key = this.flow_parseType()
this.expect(tt.bracketR)
this.expect(tt.colon)
node.value = this.flow_parseType()
this.flow_objectTypeSemicolon()
return this.finishNode(node, "ObjectTypeIndexer")
}
pp.flow_parseObjectTypeMethodish = function (node) {
node.params = []
node.rest = null
node.typeParameters = null
if (this.isRelational("<")) {
node.typeParameters = this.flow_parseTypeParameterDeclaration()
}
this.expect(tt.parenL)
while (this.type === tt.name) {
node.params.push(this.flow_parseFunctionTypeParam())
if (this.type !== tt.parenR) {
this.expect(tt.comma)
}
}
if (this.eat(tt.ellipsis)) {
node.rest = this.flow_parseFunctionTypeParam()
}
this.expect(tt.parenR)
this.expect(tt.colon)
node.returnType = this.flow_parseType()
return this.finishNode(node, "FunctionTypeAnnotation")
}
pp.flow_parseObjectTypeMethod = function (start, isStatic, key) {
var node = this.startNodeAt(start)
node.value = this.flow_parseObjectTypeMethodish(this.startNodeAt(start))
node.static = isStatic
node.key = key
node.optional = false
this.flow_objectTypeSemicolon()
return this.finishNode(node, "ObjectTypeProperty")
}
pp.flow_parseObjectTypeCallProperty = function (node, isStatic) {
var valueNode = this.startNode()
node.static = isStatic
node.value = this.flow_parseObjectTypeMethodish(valueNode)
this.flow_objectTypeSemicolon()
return this.finishNode(node, "ObjectTypeCallProperty")
}
pp.flow_parseObjectType = function (allowStatic) {
var nodeStart = this.startNode()
var node
var optional = false
var property
var propertyKey
var propertyTypeAnnotation
var token
var isStatic
nodeStart.callProperties = []
nodeStart.properties = []
nodeStart.indexers = []
this.expect(tt.braceL)
while (this.type !== tt.braceR) {
var start = this.markPosition()
node = this.startNode()
if (allowStatic && this.isContextual("static")) {
this.next()
isStatic = true
}
if (this.type === tt.bracketL) {
nodeStart.indexers.push(this.flow_parseObjectTypeIndexer(node, isStatic))
} else if (this.type === tt.parenL || this.isRelational("<")) {
nodeStart.callProperties.push(this.flow_parseObjectTypeCallProperty(node, allowStatic))
} else {
if (isStatic && this.type === tt.colon) {
propertyKey = this.parseIdent()
} else {
propertyKey = this.flow_parseObjectPropertyKey()
}
if (this.isRelational("<") || this.type === tt.parenL) {
// This is a method property
nodeStart.properties.push(this.flow_parseObjectTypeMethod(start, isStatic, propertyKey))
} else {
if (this.eat(tt.question)) {
optional = true
}
this.expect(tt.colon)
node.key = propertyKey
node.value = this.flow_parseType()
node.optional = optional
node.static = isStatic
this.flow_objectTypeSemicolon()
nodeStart.properties.push(this.finishNode(node, "ObjectTypeProperty"))
}
}
}
this.expect(tt.braceR)
return this.finishNode(nodeStart, "ObjectTypeAnnotation")
}
pp.flow_objectTypeSemicolon = function () {
if (!this.eat(tt.semi) && !this.eat(tt.comma) && this.type !== tt.braceR) {
this.unexpected()
}
}
pp.flow_parseGenericType = function (start, id) {
var node = this.startNodeAt(start)
node.typeParameters = null
node.id = id
while (this.eat(tt.dot)) {
var node2 = this.startNodeAt(start)
node2.qualification = node.id
node2.id = this.parseIdent()
node.id = this.finishNode(node2, "QualifiedTypeIdentifier")
}
if (this.isRelational("<")) {
node.typeParameters = this.flow_parseTypeParameterInstantiation()
}
return this.finishNode(node, "GenericTypeAnnotation")
}
pp.flow_parseVoidType = function () {
var node = this.startNode()
this.expect(tt._void)
return this.finishNode(node, "VoidTypeAnnotation")
}
pp.flow_parseTypeofType = function () {
var node = this.startNode()
this.expect(tt._typeof)
node.argument = this.flow_parsePrimaryType()
return this.finishNode(node, "TypeofTypeAnnotation")
}
pp.flow_parseTupleType = function () {
var node = this.startNode()
node.types = []
this.expect(tt.bracketL)
// We allow trailing commas
while (this.pos < this.input.length && this.type !== tt.bracketR) {
node.types.push(this.flow_parseType())
if (this.type === tt.bracketR) break
this.expect(tt.comma)
}
this.expect(tt.bracketR)
return this.finishNode(node, "TupleTypeAnnotation")
}
pp.flow_parseFunctionTypeParam = function () {
var optional = false
var node = this.startNode()
node.name = this.parseIdent()
if (this.eat(tt.question)) {
optional = true
}
this.expect(tt.colon)
node.optional = optional
node.typeAnnotation = this.flow_parseType()
return this.finishNode(node, "FunctionTypeParam")
}
pp.flow_parseFunctionTypeParams = function () {
var ret = { params: [], rest: null }
while (this.type === tt.name) {
ret.params.push(this.flow_parseFunctionTypeParam())
if (this.type !== tt.parenR) {
this.expect(tt.comma)
}
}
if (this.eat(tt.ellipsis)) {
ret.rest = this.flow_parseFunctionTypeParam()
}
return ret
}
pp.flow_identToTypeAnnotation = function (start, node, id) {
switch (id.name) {
case "any":
return this.finishNode(node, "AnyTypeAnnotation")
case "bool":
case "boolean":
return this.finishNode(node, "BooleanTypeAnnotation")
case "number":
return this.finishNode(node, "NumberTypeAnnotation")
case "string":
return this.finishNode(node, "StringTypeAnnotation")
default:
return this.flow_parseGenericType(start, id)
}
}
// The parsing of types roughly parallels the parsing of expressions, and
// primary types are kind of like primary expressions...they're the
// primitives with which other types are constructed.
pp.flow_parsePrimaryType = function () {
var typeIdentifier = null
var params = null
var returnType = null
var start = this.markPosition()
var node = this.startNode()
var rest = null
var tmp
var typeParameters
var token
var type
var isGroupedType = false
switch (this.type) {
case tt.name:
return this.flow_identToTypeAnnotation(start, node, this.parseIdent())
case tt.braceL:
return this.flow_parseObjectType()
case tt.bracketL:
return this.flow_parseTupleType()
case tt.relational:
if (this.value === "<") {
node.typeParameters = this.flow_parseTypeParameterDeclaration()
this.expect(tt.parenL)
tmp = this.flow_parseFunctionTypeParams()
node.params = tmp.params
node.rest = tmp.rest
this.expect(tt.parenR)
this.expect(tt.arrow)
node.returnType = this.flow_parseType()
return this.finishNode(node, "FunctionTypeAnnotation")
}
case tt.parenL:
this.next()
// Check to see if this is actually a grouped type
if (this.type !== tt.parenR && this.type !== tt.ellipsis) {
if (this.type === tt.name) {
var token = this.lookahead().type
isGroupedType = token !== tt.question && token !== tt.colon
} else {
isGroupedType = true
}
}
if (isGroupedType) {
type = this.flow_parseType()
this.expect(tt.parenR)
// If we see a => next then someone was probably confused about
// function types, so we can provide a better error message
if (this.eat(tt.arrow)) {
this.raise(node,
"Unexpected token =>. It looks like " +
"you are trying to write a function type, but you ended up " +
"writing a grouped type followed by an =>, which is a syntax " +
"error. Remember, function type parameters are named so function " +
"types look like (name1: type1, name2: type2) => returnType. You " +
"probably wrote (type1) => returnType"
)
}
return type
}
tmp = this.flow_parseFunctionTypeParams()
node.params = tmp.params
node.rest = tmp.rest
this.expect(tt.parenR)
this.expect(tt.arrow)
node.returnType = this.flow_parseType()
node.typeParameters = null
return this.finishNode(node, "FunctionTypeAnnotation")
case tt.string:
node.value = this.value
node.raw = this.input.slice(this.start, this.end)
this.next()
return this.finishNode(node, "StringLiteralTypeAnnotation")
default:
if (this.type.keyword) {
switch (this.type.keyword) {
case "void":
return this.flow_parseVoidType()
case "typeof":
return this.flow_parseTypeofType()
}
}
}
this.unexpected()
}
pp.flow_parsePostfixType = function () {
var node = this.startNode()
var type = node.elementType = this.flow_parsePrimaryType()
if (this.type === tt.bracketL) {
this.expect(tt.bracketL)
this.expect(tt.bracketR)
return this.finishNode(node, "ArrayTypeAnnotation")
}
return type
}
pp.flow_parsePrefixType = function () {
var node = this.startNode()
if (this.eat(tt.question)) {
node.typeAnnotation = this.flow_parsePrefixType()
return this.finishNode(node, "NullableTypeAnnotation")
}
return this.flow_parsePostfixType()
}
pp.flow_parseIntersectionType = function () {
var node = this.startNode()
var type = this.flow_parsePrefixType()
node.types = [type]
while (this.eat(tt.bitwiseAND)) {
node.types.push(this.flow_parsePrefixType())
}
return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation")
}
pp.flow_parseUnionType = function () {
var node = this.startNode()
var type = this.flow_parseIntersectionType()
node.types = [type]
while (this.eat(tt.bitwiseOR)) {
node.types.push(this.flow_parseIntersectionType())
}
return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation")
}
pp.flow_parseType = function () {
var oldInType = this.inType
this.inType = true
var type = this.flow_parseUnionType()
this.inType = oldInType
return type
}
pp.flow_parseTypeAnnotation = function () {
var node = this.startNode()
var oldInType = this.inType
this.inType = true
this.expect(tt.colon)
node.typeAnnotation = this.flow_parseType()
this.inType = oldInType
return this.finishNode(node, "TypeAnnotation")
}
pp.flow_parseTypeAnnotatableIdentifier = function (requireTypeAnnotation, canBeOptionalParam) {
var node = this.startNode()
var ident = this.parseIdent()
var isOptionalParam = false
if (canBeOptionalParam && this.eat(tt.question)) {
this.expect(tt.question)
isOptionalParam = true
}
if (requireTypeAnnotation || this.type === tt.colon) {
ident.typeAnnotation = this.flow_parseTypeAnnotation()
this.finishNode(ident, ident.type)
}
if (isOptionalParam) {
ident.optional = true
this.finishNode(ident, ident.type)
}
return ident
}
acorn.plugins.flow = function (instance) {
// function name(): string {}
instance.extend("parseFunctionBody", function (inner) {
return function (node, allowExpression) {
if (this.type === tt.colon) {
node.returnType = this.flow_parseTypeAnnotation()
}
return inner.call(this, node, allowExpression)
}
})
instance.extend("parseStatement", function (inner) {
return function(declaration, topLevel) {
// strict mode handling of `interface` since it's a reserved word
if (this.strict && this.type === tt.name && this.value === "interface") {
var node = this.startNode()
this.next()
return this.flow_parseInterface(node)
} else {
return inner.call(this, declaration, topLevel)
}
}
})
instance.extend("parseExpressionStatement", function (inner) {
return function (node, expr) {
if (expr.type === "Identifier") {
if (expr.name === "declare") {
if (this.type === tt._class || this.type === tt.name || this.type === tt._function || this.type === tt._var) {
return this.flow_parseDeclare(node)
}
} else if (this.type === tt.name) {
if (expr.name === "interface") {
return this.flow_parseInterface(node)
} else if (expr.name === "type") {
return this.flow_parseTypeAlias(node)
}
}
}
return inner.call(this, node, expr)
}
})
instance.extend("shouldParseExportDeclaration", function (inner) {
return function () {
return this.isContextual("type") || inner.call(this)
}
})
instance.extend("parseParenItem", function (inner) {
return function (node, start) {
if (this.type === tt.colon) {
var typeCastNode = this.startNodeAt(start)
typeCastNode.expression = node
typeCastNode.typeAnnotation = this.flow_parseTypeAnnotation()
return this.finishNode(typeCastNode, "TypeCastExpression")
} else {
return node
}
}
})
instance.extend("parseClassId", function (inner) {
return function (node, isStatement) {
inner.call(this, node, isStatement)
if (this.isRelational("<")) {
node.typeParameters = this.flow_parseTypeParameterDeclaration()
}
}
})
instance.extend("readToken", function (inner) {
return function(code) {
if (this.inType && (code === 62 || code === 60)) {
return this.finishOp(tt.relational, 1)
} else {
return inner.call(this, code)
}
}
})
instance.extend("jsx_readToken", function (inner) {
return function () {
if (!this.inType) return inner.call(this)
}
})
instance.extend("parseParenArrowList", function (inner) {
return function (start, exprList, isAsync) {
for (var i = 0; i < exprList.length; i++) {
var listItem = exprList[i]
if (listItem.type === "TypeCastExpression") {
var expr = listItem.expression
expr.typeAnnotation = listItem.typeAnnotation
exprList[i] = expr
}
}
return inner.call(this, start, exprList, isAsync)
}
})
instance.extend("parseClassProperty", function (inner) {
return function (node) {
if (this.type === tt.colon) {
node.typeAnnotation = this.flow_parseTypeAnnotation()
}
return inner.call(this, node)
}
})
instance.extend("isClassProperty", function (inner) {
return function () {
return this.type === tt.colon || inner.call(this)
}
})
instance.extend("parseClassMethod", function (inner) {
return function (classBody, method, isGenerator, isAsync) {
var typeParameters
if (this.isRelational("<")) {
typeParameters = this.flow_parseTypeParameterDeclaration()
}
method.value = this.parseMethod(isGenerator, isAsync)
method.value.typeParameters = typeParameters
classBody.body.push(this.finishNode(method, "MethodDefinition"))
}
})
instance.extend("parseClassSuper", function (inner) {
return function (node, isStatement) {
inner.call(this, node, isStatement)
if (node.superClass && this.isRelational("<")) {
node.superTypeParameters = this.flow_parseTypeParameterInstantiation()
}
if (this.isContextual("implements")) {
this.next()
var implemented = node.implements = []
do {
var node = this.startNode()
node.id = this.parseIdent()
if (this.isRelational("<")) {
node.typeParameters = this.flow_parseTypeParameterInstantiation()
} else {
node.typeParameters = null
}
implemented.push(this.finishNode(node, "ClassImplements"))
} while(this.eat(tt.comma))
}
}
})
instance.extend("parseObjPropValue", function (inner) {
return function (prop) {
var typeParameters
if (this.isRelational("<")) {
typeParameters = this.flow_parseTypeParameterDeclaration()
if (this.type !== tt.parenL) this.unexpected()
}
inner.apply(this, arguments)
prop.value.typeParameters = typeParameters
}
})
instance.extend("parseAssignableListItemTypes", function (inner) {
return function (param) {
if (this.eat(tt.question)) {
param.optional = true
}
if (this.type === tt.colon) {
param.typeAnnotation = this.flow_parseTypeAnnotation()
}
this.finishNode(param, param.type)
return param
}
})
instance.extend("parseImportSpecifiers", function (inner) {
return function (node) {
node.isType = false
if (this.isContextual("type")) {
var start = this.markPosition()
var typeId = this.parseIdent()
if ((this.type === tt.name && this.value !== "from") || this.type === tt.braceL || this.type === tt.star) {
node.isType = true
} else {
node.specifiers.push(this.parseImportSpecifierDefault(typeId, start))
if (this.isContextual("from")) return
this.eat(tt.comma)
}
}
inner.call(this, node)
}
})
// function foo<T>() {}
instance.extend("parseFunctionParams", function (inner) {
return function (node) {
if (this.isRelational("<")) {
node.typeParameters = this.flow_parseTypeParameterDeclaration()
}
inner.call(this, node)
}
})
// var foo: string = bar
instance.extend("parseVarHead", function (inner) {
return function (decl) {
inner.call(this, decl)
if (this.type === tt.colon) {
decl.id.typeAnnotation = this.flow_parseTypeAnnotation()
this.finishNode(decl.id, decl.id.type)
}
}
})
}

806
src/acorn/src/expression.js Executable file
View File

@@ -0,0 +1,806 @@
// A recursive descent parser operates by defining functions for all
// syntactic elements, and recursively calling those, each function
// advancing the input stream and returning an AST node. Precedence
// of constructs (for example, the fact that `!x[1]` means `!(x[1])`
// instead of `(!x)[1]` is handled by the fact that the parser
// function that parses unary prefix operators is called first, and
// in turn calls the function that parses `[]` subscripts — that
// way, it'll receive the node for `x[1]` already parsed, and wraps
// *that* in the unary operator node.
//
// Acorn uses an [operator precedence parser][opp] to handle binary
// operator precedence, because it is much more compact than using
// the technique outlined above, which uses different, nesting
// functions to specify precedence, for all of the ten binary
// precedence levels that JavaScript defines.
//
// [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser
import {types as tt} from "./tokentype"
import {Parser} from "./state"
import {reservedWords} from "./identifier"
import {has} from "./util"
const pp = Parser.prototype
// Check if property name clashes with already added.
// Object/class getters and setters are not allowed to clash —
// either with each other or with an init property — and in
// strict mode, init properties are also not allowed to be repeated.
pp.checkPropClash = function(prop, propHash) {
if (this.options.ecmaVersion >= 6) return
let key = prop.key, name
switch (key.type) {
case "Identifier": name = key.name; break
case "Literal": name = String(key.value); break
default: return
}
let kind = prop.kind || "init", other
if (has(propHash, name)) {
other = propHash[name]
let isGetSet = kind !== "init"
if ((this.strict || isGetSet) && other[kind] || !(isGetSet ^ other.init))
this.raise(key.start, "Redefinition of property")
} else {
other = propHash[name] = {
init: false,
get: false,
set: false
}
}
other[kind] = true
}
// ### Expression parsing
// These nest, from the most general expression type at the top to
// 'atomic', nondivisible expression types at the bottom. Most of
// the functions will simply let the function(s) below them parse,
// and, *if* the syntactic construct they handle is present, wrap
// the AST node that the inner parser gave them in another node.
// Parse a full expression. The optional arguments are used to
// forbid the `in` operator (in for loops initalization expressions)
// and provide reference for storing '=' operator inside shorthand
// property assignment in contexts where both object expression
// and object pattern might appear (so it's possible to raise
// delayed syntax error at correct position).
pp.parseExpression = function(noIn, refShorthandDefaultPos) {
let start = this.markPosition()
let expr = this.parseMaybeAssign(noIn, refShorthandDefaultPos)
if (this.type === tt.comma) {
let node = this.startNodeAt(start)
node.expressions = [expr]
while (this.eat(tt.comma)) node.expressions.push(this.parseMaybeAssign(noIn, refShorthandDefaultPos))
return this.finishNode(node, "SequenceExpression")
}
return expr
}
// Parse an assignment expression. This includes applications of
// operators like `+=`.
pp.parseMaybeAssign = function(noIn, refShorthandDefaultPos, afterLeftParse) {
if (this.type == tt._yield && this.inGenerator) return this.parseYield()
let failOnShorthandAssign
if (!refShorthandDefaultPos) {
refShorthandDefaultPos = {start: 0}
failOnShorthandAssign = true
} else {
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
this.checkLVal(left)
if (left.parenthesizedExpression) {
let errorMsg
if (left.type === "ObjectPattern") {
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()
node.right = this.parseMaybeAssign(noIn)
return this.finishNode(node, "AssignmentExpression")
} else if (failOnShorthandAssign && refShorthandDefaultPos.start) {
this.unexpected(refShorthandDefaultPos.start)
}
return left
}
// Parse a ternary conditional (`?:`) operator.
pp.parseMaybeConditional = function(noIn, refShorthandDefaultPos) {
let start = this.markPosition()
let expr = this.parseExprOps(noIn, refShorthandDefaultPos)
if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr
if (this.eat(tt.question)) {
let node = this.startNodeAt(start)
node.test = expr
node.consequent = this.parseMaybeAssign()
this.expect(tt.colon)
node.alternate = this.parseMaybeAssign(noIn)
return this.finishNode(node, "ConditionalExpression")
}
return expr
}
// Start the precedence parser.
pp.parseExprOps = function(noIn, refShorthandDefaultPos) {
let start = this.markPosition()
let expr = this.parseMaybeUnary(refShorthandDefaultPos)
if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr
return this.parseExprOp(expr, start, -1, noIn)
}
// Parse binary operators with the operator precedence parsing
// algorithm. `left` is the left-hand side of the operator.
// `minPrec` provides context that allows the function to stop and
// defer further parser to one of its callers when it encounters an
// operator that has a lower precedence than the set it is parsing.
pp.parseExprOp = function(left, leftStart, minPrec, noIn) {
let prec = this.type.binop
if (prec != null && (!noIn || this.type !== tt._in)) {
if (prec > minPrec) {
let node = this.startNodeAt(leftStart)
node.left = left
node.operator = this.value
let op = this.type
this.next()
let start = this.markPosition()
node.right = this.parseExprOp(this.parseMaybeUnary(), start, op.rightAssociative ? (prec - 1) : prec, noIn)
this.finishNode(node, (op === tt.logicalOR || op === tt.logicalAND) ? "LogicalExpression" : "BinaryExpression")
return this.parseExprOp(node, leftStart, minPrec, noIn)
}
}
return left
}
// Parse unary operators, both prefix and postfix.
pp.parseMaybeUnary = function(refShorthandDefaultPos) {
if (this.type.prefix) {
let node = this.startNode(), update = this.type === tt.incDec
node.operator = this.value
node.prefix = true
this.next()
node.argument = this.parseMaybeUnary()
if (refShorthandDefaultPos && refShorthandDefaultPos.start) this.unexpected(refShorthandDefaultPos.start)
if (update) this.checkLVal(node.argument)
else if (this.strict && node.operator === "delete" &&
node.argument.type === "Identifier")
this.raise(node.start, "Deleting local variable in strict mode")
return this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression")
}
let start = this.markPosition()
let expr = this.parseExprSubscripts(refShorthandDefaultPos)
if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr
while (this.type.postfix && !this.canInsertSemicolon()) {
let node = this.startNodeAt(start)
node.operator = this.value
node.prefix = false
node.argument = expr
this.checkLVal(expr)
this.next()
expr = this.finishNode(node, "UpdateExpression")
}
return expr
}
// Parse call, dot, and `[]`-subscript expressions.
pp.parseExprSubscripts = function(refShorthandDefaultPos) {
let start = this.markPosition()
let expr = this.parseExprAtom(refShorthandDefaultPos)
if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr
return this.parseSubscripts(expr, start)
}
pp.parseSubscripts = function(base, start, noCalls) {
if (!noCalls && this.eat(tt.doubleColon)) {
let node = this.startNodeAt(start)
node.object = base
node.callee = this.parseNoCallExpr()
return this.parseSubscripts(this.finishNode(node, "BindExpression"), start, noCalls)
} else if (this.eat(tt.dot)) {
let node = this.startNodeAt(start)
node.object = base
node.property = this.parseIdent(true)
node.computed = false
return this.parseSubscripts(this.finishNode(node, "MemberExpression"), start, noCalls)
} else if (this.eat(tt.bracketL)) {
let node = this.startNodeAt(start)
node.object = base
node.property = this.parseExpression()
node.computed = true
this.expect(tt.bracketR)
return this.parseSubscripts(this.finishNode(node, "MemberExpression"), start, noCalls)
} else if (!noCalls && this.eat(tt.parenL)) {
let node = this.startNodeAt(start)
node.callee = base
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)
node.tag = base
node.quasi = this.parseTemplate()
return this.parseSubscripts(this.finishNode(node, "TaggedTemplateExpression"), start, noCalls)
} return base
}
// Parse a no-call expression (like argument of `new` or `::` operators).
pp.parseNoCallExpr = function() {
let start = this.markPosition()
return this.parseSubscripts(this.parseExprAtom(), start, true)
}
// Parse an atomic expression — either a single token that is an
// expression, an expression started by a keyword like `function` or
// `new`, or an expression wrapped in punctuation like `()`, `[]`,
// or `{}`.
pp.parseExprAtom = function(refShorthandDefaultPos) {
let node, canBeArrow = this.potentialArrowAt == this.start
switch (this.type) {
case tt._this:
case tt._super:
let type = this.type === tt._this ? "ThisExpression" : "Super"
node = this.startNode()
this.next()
return this.finishNode(node, type)
case tt._yield:
if (this.inGenerator) this.unexpected()
case tt._do:
if (this.options.features["es7.doExpressions"]) {
let node = this.startNode()
this.next()
node.body = this.parseBlock()
return this.finishNode(node, "DoExpression")
}
case tt.name:
let start = this.markPosition()
node = this.startNode()
let id = this.parseIdent(this.type !== tt.name)
//
if (this.options.features["es7.asyncFunctions"]) {
// async functions!
if (id.name === "async") {
// arrow functions
if (this.type === tt.parenL) {
let expr = this.parseParenAndDistinguishExpression(start, true, true)
if (expr && expr.type === "ArrowFunctionExpression") {
return expr
} else {
node.callee = id
if (!expr) {
node.arguments = []
} else if (expr.type === "SequenceExpression") {
node.arguments = expr.expressions
} else {
node.arguments = [expr]
}
return this.parseSubscripts(this.finishNode(node, "CallExpression"), start)
}
} else if (this.type === tt.name) {
id = this.parseIdent()
this.expect(tt.arrow)
return this.parseArrowExpression(node, [id], true)
}
// normal functions
if (this.type === tt._function && !this.canInsertSemicolon()) {
this.next()
return this.parseFunction(node, false, false, true)
}
} else if (id.name === "await") {
if (this.inAsync) return this.parseAwait(node)
}
}
//
if (canBeArrow && !this.canInsertSemicolon() && this.eat(tt.arrow))
return this.parseArrowExpression(this.startNodeAt(start), [id])
return id
case tt.regexp:
let value = this.value
node = this.parseLiteral(value.value)
node.regex = {pattern: value.pattern, flags: value.flags}
return node
case tt.num: case tt.string:
return this.parseLiteral(this.value)
case tt._null: case tt._true: case tt._false:
node = this.startNode()
node.value = this.type === tt._null ? null : this.type === tt._true
node.raw = this.type.keyword
this.next()
return this.finishNode(node, "Literal")
case tt.parenL:
return this.parseParenAndDistinguishExpression(null, null, canBeArrow)
case tt.bracketL:
node = this.startNode()
this.next()
// check whether this is array comprehension or regular array
if ((this.options.ecmaVersion >= 7 || this.options.features["es7.comprehensions"]) && this.type === tt._for) {
return this.parseComprehension(node, false)
}
node.elements = this.parseExprList(tt.bracketR, true, true, refShorthandDefaultPos)
return this.finishNode(node, "ArrayExpression")
case tt.braceL:
return this.parseObj(false, refShorthandDefaultPos)
case tt._function:
node = this.startNode()
this.next()
return this.parseFunction(node, false)
case tt.at:
this.parseDecorators()
case tt._class:
node = this.startNode()
this.takeDecorators(node)
return this.parseClass(node, false)
case tt._new:
return this.parseNew()
case tt.backQuote:
return this.parseTemplate()
case tt.doubleColon:
node = this.startNode()
this.next()
node.object = null
let callee = node.callee = this.parseNoCallExpr()
if (callee.type !== "MemberExpression")
this.raise(callee.start, "Binding should be performed on object property.")
return this.finishNode(node, "BindExpression")
default:
this.unexpected()
}
}
pp.parseLiteral = function(value) {
let node = this.startNode()
node.value = value
node.raw = this.input.slice(this.start, this.end)
this.next()
return this.finishNode(node, "Literal")
}
pp.parseParenExpression = function() {
this.expect(tt.parenL)
let val = this.parseExpression()
this.expect(tt.parenR)
return val
}
pp.parseParenAndDistinguishExpression = function(start, isAsync, canBeArrow) {
start = start || this.markPosition()
let val
if (this.options.ecmaVersion >= 6) {
this.next()
if ((this.options.features["es7.comprehensions"] || this.options.ecmaVersion >= 7) && this.type === tt._for) {
return this.parseComprehension(this.startNodeAt(start), true)
}
let innerStart = this.markPosition(), exprList = [], first = true
let refShorthandDefaultPos = {start: 0}, spreadStart, innerParenStart
while (this.type !== tt.parenR) {
first ? first = false : this.expect(tt.comma)
if (this.type === tt.ellipsis) {
let spreadNodeStart = this.markPosition()
spreadStart = this.start
exprList.push(this.parseParenItem(this.parseRest(), spreadNodeStart))
break
} else {
if (this.type === tt.parenL && !innerParenStart) {
innerParenStart = this.start
}
exprList.push(this.parseMaybeAssign(false, refShorthandDefaultPos, this.parseParenItem))
}
}
let innerEnd = this.markPosition()
this.expect(tt.parenR)
if (canBeArrow && !this.canInsertSemicolon() && this.eat(tt.arrow)) {
if (innerParenStart) this.unexpected(innerParenStart)
return this.parseParenArrowList(start, exprList, isAsync)
}
if (!exprList.length) {
if (isAsync) {
return
} else {
this.unexpected(this.lastTokStart)
}
}
if (spreadStart) this.unexpected(spreadStart)
if (refShorthandDefaultPos.start) this.unexpected(refShorthandDefaultPos.start)
if (exprList.length > 1) {
val = this.startNodeAt(innerStart)
val.expressions = exprList
this.finishNodeAt(val, "SequenceExpression", innerEnd)
} else {
val = exprList[0]
}
} else {
val = this.parseParenExpression()
}
if (this.options.preserveParens) {
let par = this.startNodeAt(start)
par.expression = val
return this.finishNode(par, "ParenthesizedExpression")
} else {
val.parenthesizedExpression = true
return val
}
}
pp.parseParenArrowList = function(start, exprList, isAsync) {
return this.parseArrowExpression(this.startNodeAt(start), exprList, isAsync)
}
pp.parseParenItem = function(node, start) {
return node
}
// New's precedence is slightly tricky. It must allow its argument
// to be a `[]` or dot subscript expression, but not a call — at
// least, not without wrapping it in parentheses. Thus, it uses the
const empty = []
pp.parseNew = function() {
let node = this.startNode()
let meta = this.parseIdent(true)
if (this.options.ecmaVersion >= 6 && this.eat(tt.dot)) {
node.meta = meta
node.property = this.parseIdent(true)
if (node.property.name !== "target")
this.raise(node.property.start, "The only valid meta property for new is new.target")
return this.finishNode(node, "MetaProperty")
}
node.callee = this.parseNoCallExpr()
if (this.eat(tt.parenL)) node.arguments = this.parseExprList(
tt.parenR,
this.options.features["es7.trailingFunctionCommas"]
)
else node.arguments = empty
return this.finishNode(node, "NewExpression")
}
// Parse template expression.
pp.parseTemplateElement = function() {
let elem = this.startNode()
elem.value = {
raw: this.input.slice(this.start, this.end),
cooked: this.value
}
this.next()
elem.tail = this.type === tt.backQuote
return this.finishNode(elem, "TemplateElement")
}
pp.parseTemplate = function() {
let node = this.startNode()
this.next()
node.expressions = []
let curElt = this.parseTemplateElement()
node.quasis = [curElt]
while (!curElt.tail) {
this.expect(tt.dollarBraceL)
node.expressions.push(this.parseExpression())
this.expect(tt.braceR)
node.quasis.push(curElt = this.parseTemplateElement())
}
this.next()
return this.finishNode(node, "TemplateLiteral")
}
// Parse an object literal or binding pattern.
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"
node.properties.push(prop)
continue
}
if (this.options.ecmaVersion >= 6) {
prop.method = false
prop.shorthand = false
if (isPattern || refShorthandDefaultPos)
start = this.markPosition()
if (!isPattern)
isGenerator = this.eat(tt.star)
}
if (this.options.features["es7.asyncFunctions"] && this.isContextual("async")) {
if (isGenerator || isPattern) this.unexpected()
var asyncId = this.parseIdent()
if (this.type === tt.colon || this.type === tt.parenL) {
prop.key = asyncId
} else {
isAsync = true
this.parsePropertyName(prop)
}
} else {
this.parsePropertyName(prop)
}
this.parseObjPropValue(prop, start, isGenerator, isAsync, 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")
}
pp.parseObjPropValue = function (prop, start, isGenerator, isAsync, isPattern, refShorthandDefaultPos) {
if (this.eat(tt.colon)) {
prop.value = isPattern ? this.parseMaybeDefault() : this.parseMaybeAssign(false, refShorthandDefaultPos)
prop.kind = "init"
} else if (this.options.ecmaVersion >= 6 && this.type === tt.parenL) {
if (isPattern) this.unexpected()
prop.kind = "init"
prop.method = true
prop.value = this.parseMethod(isGenerator, isAsync)
} else if (this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
(prop.key.name === "get" || prop.key.name === "set") &&
(this.type != tt.comma && this.type != tt.braceR)) {
if (isGenerator || isAsync || isPattern) this.unexpected()
prop.kind = prop.key.name
this.parsePropertyName(prop)
prop.value = this.parseMethod(false)
} else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
prop.kind = "init"
if (isPattern) {
if (this.isKeyword(prop.key.name) ||
(this.strict && (reservedWords.strictBind(prop.key.name) || reservedWords.strict(prop.key.name))) ||
(!this.options.allowReserved && this.isReservedWord(prop.key.name)))
this.raise(prop.key.start, "Binding " + prop.key.name)
prop.value = this.parseMaybeDefault(start, prop.key)
} else if (this.type === tt.eq && refShorthandDefaultPos) {
if (!refShorthandDefaultPos.start)
refShorthandDefaultPos.start = this.start
prop.value = this.parseMaybeDefault(start, prop.key)
} else {
prop.value = prop.key
}
prop.shorthand = true
} else this.unexpected()
}
pp.parsePropertyName = function(prop) {
if (this.options.ecmaVersion >= 6) {
if (this.eat(tt.bracketL)) {
prop.computed = true
prop.key = this.parseMaybeAssign()
this.expect(tt.bracketR)
return
} else {
prop.computed = false
}
}
prop.key = (this.type === tt.num || this.type === tt.string) ? this.parseExprAtom() : this.parseIdent(true)
}
// Initialize empty function node.
pp.initFunction = function(node, isAsync) {
node.id = null
if (this.options.ecmaVersion >= 6) {
node.generator = false
node.expression = false
}
if (this.options.features["es7.asyncFunctions"]) {
node.async = !!isAsync
}
}
// Parse object or class method.
pp.parseMethod = function(isGenerator, isAsync) {
let node = this.startNode()
this.initFunction(node, isAsync)
this.expect(tt.parenL)
node.params = this.parseBindingList(tt.parenR, false, this.options.features["es7.trailingFunctionCommas"])
if (this.options.ecmaVersion >= 6) {
node.generator = isGenerator
}
this.parseFunctionBody(node)
return this.finishNode(node, "FunctionExpression")
}
// Parse arrow function expression with given parameters.
pp.parseArrowExpression = function(node, params, isAsync) {
this.initFunction(node, isAsync)
node.params = this.toAssignableList(params, true)
this.parseFunctionBody(node, true)
return this.finishNode(node, "ArrowFunctionExpression")
}
// Parse function body and check parameters.
pp.parseFunctionBody = function(node, allowExpression) {
let isExpression = allowExpression && this.type !== tt.braceL
var oldInAsync = this.inAsync
this.inAsync = node.async
if (isExpression) {
node.body = this.parseMaybeAssign()
node.expression = true
} else {
// Start a new scope with regard to labels and the `inFunction`
// flag (restore them to their old value afterwards).
let oldInFunc = this.inFunction, oldInGen = this.inGenerator, oldLabels = this.labels
this.inFunction = true; this.inGenerator = node.generator; this.labels = []
node.body = this.parseBlock(true)
node.expression = false
this.inFunction = oldInFunc; this.inGenerator = oldInGen; this.labels = oldLabels
}
this.inAsync = oldInAsync
// If this is a strict mode function, verify that argument names
// are not repeated, and it does not try to bind the words `eval`
// or `arguments`.
if (this.strict || !isExpression && node.body.body.length && this.isUseStrict(node.body.body[0])) {
let nameHash = {}, oldStrict = this.strict
this.strict = true
if (node.id)
this.checkLVal(node.id, true)
for (let i = 0; i < node.params.length; i++)
this.checkLVal(node.params[i], true, nameHash)
this.strict = oldStrict
}
}
// Parses a comma-separated list of expressions, and returns them as
// an array. `close` is the token type that ends the list, and
// `allowEmpty` can be turned on to allow subsequent commas with
// nothing in between them to be parsed as `null` (which is needed
// for array literals).
pp.parseExprList = function(close, allowTrailingComma, allowEmpty, refShorthandDefaultPos) {
let elts = [], first = true
while (!this.eat(close)) {
if (!first) {
this.expect(tt.comma)
if (allowTrailingComma && this.afterTrailingComma(close)) break
} else first = false
if (allowEmpty && this.type === tt.comma) {
elts.push(null)
} else {
if (this.type === tt.ellipsis)
elts.push(this.parseSpread(refShorthandDefaultPos))
else
elts.push(this.parseMaybeAssign(false, refShorthandDefaultPos))
}
}
return elts
}
// Parse the next token as an identifier. If `liberal` is true (used
// when parsing properties), it will also convert keywords into
// identifiers.
pp.parseIdent = function(liberal) {
let node = this.startNode()
if (liberal && this.options.allowReserved == "never") liberal = false
if (this.type === tt.name) {
if (!liberal &&
((!this.options.allowReserved && this.isReservedWord(this.value)) ||
(this.strict && reservedWords.strict(this.value)) &&
(this.options.ecmaVersion >= 6 ||
this.input.slice(this.start, this.end).indexOf("\\") == -1)))
this.raise(this.start, "The keyword '" + this.value + "' is reserved")
node.name = this.value
} else if (liberal && this.type.keyword) {
node.name = this.type.keyword
} else {
this.unexpected()
}
this.next()
return this.finishNode(node, "Identifier")
}
// Parses await expression inside async function.
pp.parseAwait = function (node) {
if (this.eat(tt.semi) || this.canInsertSemicolon()) {
this.unexpected()
}
node.all = this.eat(tt.star)
node.argument = this.parseMaybeUnary()
return this.finishNode(node, "AwaitExpression")
};
// Parses yield expression inside generator.
pp.parseYield = function() {
let node = this.startNode()
this.next()
if (this.type == tt.semi || this.canInsertSemicolon() || (this.type != tt.star && !this.type.startsExpr)) {
node.delegate = false
node.argument = null
} else {
node.delegate = this.eat(tt.star)
node.argument = this.parseMaybeAssign()
}
return this.finishNode(node, "YieldExpression")
}
// Parses array and generator comprehensions.
pp.parseComprehension = function(node, isGenerator) {
node.blocks = []
while (this.type === tt._for) {
let block = this.startNode()
this.next()
this.expect(tt.parenL)
block.left = this.parseBindingAtom()
this.checkLVal(block.left, true)
this.expectContextual("of")
block.right = this.parseExpression()
this.expect(tt.parenR)
node.blocks.push(this.finishNode(block, "ComprehensionBlock"))
}
node.filter = this.eat(tt._if) ? this.parseParenExpression() : null
node.body = this.parseExpression()
this.expect(isGenerator ? tt.parenR : tt.bracketR)
node.generator = isGenerator
return this.finishNode(node, "ComprehensionExpression")
}

97
src/acorn/src/identifier.js Executable file
View File

@@ -0,0 +1,97 @@
// This is a trick taken from Esprima. It turns out that, on
// non-Chrome browsers, to check whether a string is in a set, a
// predicate containing a big ugly `switch` statement is faster than
// a regular expression, and on Chrome the two are about on par.
// This function uses `eval` (non-lexical) to produce such a
// predicate from a space-separated string of words.
//
// It starts by sorting the words by length.
function makePredicate(words) {
words = words.split(" ")
return function(str) {
return words.indexOf(str) >= 0
}
}
// Reserved word lists for various dialects of the language
export const reservedWords = {
3: makePredicate("abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile"),
5: makePredicate("class enum extends super const export import"),
6: makePredicate("enum await"),
strict: makePredicate("implements interface let package private protected public static yield"),
strictBind: makePredicate("eval arguments")
}
// And the keywords
var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"
export const keywords = {
5: makePredicate(ecma5AndLessKeywords),
6: makePredicate(ecma5AndLessKeywords + " let const class extends export import yield super")
}
// ## Character categories
// Big ugly regular expressions that match characters in the
// whitespace, identifier, and identifier-start categories. These
// are only applied when a character is found to actually have a
// code point above 128.
// Generated by `tools/generate-identifier-regex.js`.
let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0-\u08b2\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua7ad\ua7b0\ua7b1\ua7f7-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab5f\uab64\uab65\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"
let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08e4-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d01-\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19b0-\u19c0\u19c8\u19c9\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1cf8\u1cf9\u1dc0-\u1df5\u1dfc-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2d\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"
const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]")
const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]")
nonASCIIidentifierStartChars = nonASCIIidentifierChars = null
// These are a run-length and offset encoded representation of the
// >0xffff code points that are a valid part of identifiers. The
// offset starts at 0x10000, and each pair of numbers represents an
// offset to the next range, and then a size of the range. They were
// generated by tools/generate-identifier-regex.js
var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,17,26,6,37,11,29,3,35,5,7,2,4,43,157,99,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,98,21,11,25,71,55,7,1,65,0,16,3,2,2,2,26,45,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,955,52,76,44,33,24,27,35,42,34,4,0,13,47,15,3,22,0,38,17,2,24,133,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,32,4,287,47,21,1,2,0,185,46,82,47,21,0,60,42,502,63,32,0,449,56,1288,920,104,110,2962,1070,13266,568,8,30,114,29,19,47,17,3,32,20,6,18,881,68,12,0,67,12,16481,1,3071,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,4149,196,1340,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42710,42,4148,12,221,16355,541]
var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,1306,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,52,0,13,2,49,13,16,9,83,11,168,11,6,9,8,2,57,0,2,6,3,1,3,2,10,0,11,1,3,6,4,4,316,19,13,9,214,6,3,8,112,16,16,9,82,12,9,9,535,9,20855,9,135,4,60,6,26,9,1016,45,17,3,19723,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,4305,6,792618,239]
// This has a complexity linear to the value of the code. The
// assumption is that looking up astral identifier characters is
// rare.
function isInAstralSet(code, set) {
let pos = 0x10000
for (let i = 0; i < set.length; i += 2) {
pos += set[i]
if (pos > code) return false
pos += set[i + 1]
if (pos >= code) return true
}
}
// Test whether a given character code starts an identifier.
export function isIdentifierStart(code, astral) {
if (code < 65) return code === 36
if (code < 91) return true
if (code < 97) return code === 95
if (code < 123) return true
if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code))
if (astral === false) return false
return isInAstralSet(code, astralIdentifierStartCodes)
}
// Test whether a given character is part of an identifier.
export function isIdentifierChar(code, astral) {
if (code < 48) return code === 36
if (code < 58) return true
if (code < 65) return false
if (code < 91) return true
if (code < 97) return code === 95
if (code < 123) return true
if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code))
if (astral === false) return false
return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
}

79
src/acorn/src/index.js Executable file
View File

@@ -0,0 +1,79 @@
// Acorn is a tiny, fast JavaScript parser written in JavaScript.
//
// Acorn was written by Marijn Haverbeke, Ingvar Stepanyan, and
// various contributors and released under an MIT license.
//
// Git repositories for Acorn are available at
//
// http://marijnhaverbeke.nl/git/acorn
// https://github.com/marijnh/acorn.git
//
// Please use the [github bug tracker][ghbt] to report issues.
//
// [ghbt]: https://github.com/marijnh/acorn/issues
//
// This file defines the main parser interface. The library also comes
// with a [error-tolerant parser][dammit] and an
// [abstract syntax tree walker][walk], defined in other files.
//
// [dammit]: acorn_loose.js
// [walk]: util/walk.js
import {Parser} from "./state"
import {getOptions} from "./options"
import "./parseutil"
import "./statement"
import "./lval"
import "./expression"
import "./lookahead"
export {Parser, plugins} from "./state"
export {defaultOptions} from "./options"
export {SourceLocation} from "./location"
export {getLineInfo} from "./location"
export {Node} from "./node"
export {TokenType, types as tokTypes} from "./tokentype"
export {TokContext, types as tokContexts} from "./tokencontext"
export {isIdentifierChar, isIdentifierStart} from "./identifier"
export {Token} from "./tokenize"
export {isNewLine, lineBreak, lineBreakG} from "./whitespace"
export const version = "1.0.0"
// The main exported interface (under `self.acorn` when in the
// browser) is a `parse` function that takes a code string and
// returns an abstract syntax tree as specified by [Mozilla parser
// API][api].
//
// [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
export function parse(input, options) {
let p = parser(options, input)
let startPos = p.options.locations ? [p.pos, p.curPosition()] : p.pos
p.nextToken()
return p.parseTopLevel(p.options.program || p.startNodeAt(startPos))
}
// This function tries to parse a single expression at a given
// offset in a string. Useful for parsing mixed-language formats
// that embed JavaScript expressions.
export function parseExpressionAt(input, pos, options) {
let p = parser(options, input, pos)
p.nextToken()
return p.parseExpression()
}
// Acorn is organized as a tokenizer and a recursive-descent parser.
// The `tokenize` export provides an interface to the tokenizer.
// Because the tokenizer is optimized for being efficiently used by
// the Acorn parser itself, this interface is somewhat crude and not
// very modular.
export function tokenizer(input, options) {
return parser(options, input)
}
function parser(options, input) {
return new Parser(getOptions(options), String(input))
}

67
src/acorn/src/location.js Executable file
View File

@@ -0,0 +1,67 @@
import {Parser} from "./state"
import {lineBreakG} from "./whitespace"
// These are used when `options.locations` is on, for the
// `startLoc` and `endLoc` properties.
export class Position {
constructor(line, col) {
this.line = line
this.column = col
}
offset(n) {
return new Position(this.line, this.column + n)
}
}
export class SourceLocation {
constructor(p, start, end) {
this.start = start
this.end = end
if (p.sourceFile !== null) this.source = p.sourceFile
}
}
// The `getLineInfo` function is mostly useful when the
// `locations` option is off (for performance reasons) and you
// want to find the line/column position for a given character
// offset. `input` should be the code string that the offset refers
// into.
export function getLineInfo(input, offset) {
for (let line = 1, cur = 0;;) {
lineBreakG.lastIndex = cur
let match = lineBreakG.exec(input)
if (match && match.index < offset) {
++line
cur = match.index + match[0].length
} else {
return new Position(line, offset - cur)
}
}
}
const pp = Parser.prototype
// This function is used to raise exceptions on parse errors. It
// takes an offset integer (into the current `input`) to indicate
// the location of the error, attaches the position to the end
// of the error message, and then raises a `SyntaxError` with that
// message.
pp.raise = function(pos, message) {
let loc = getLineInfo(this.input, pos)
message += " (" + loc.line + ":" + loc.column + ")"
let err = new SyntaxError(message)
err.pos = pos; err.loc = loc; err.raisedAt = this.pos
throw err
}
pp.curPosition = function() {
return new Position(this.curLine, this.pos - this.lineStart)
}
pp.markPosition = function() {
return this.options.locations ? [this.start, this.startLoc] : this.start
}

View File

@@ -0,0 +1,42 @@
import {Parser} from "./state"
const pp = Parser.prototype
var STATE_KEYS = [
"lastTokStartLoc",
"lastTokEndLoc",
"lastTokStart",
"lastTokEnd",
"lineStart",
"startLoc",
"endLoc",
"start",
"pos",
"end",
"type",
"value",
"exprAllowed",
"potentialArrowAt",
"currLine",
"input"
];
pp.getState = function () {
var state = {}
for (var i = 0; i < STATE_KEYS.length; i++) {
var key = STATE_KEYS[i]
state[key] = this[key]
}
state.context = this.context.slice()
return state
};
pp.lookahead = function() {
var old = this.getState();
this.isLookahead = true
this.next()
this.isLookahead = false
var curr = this.getState();
for (var key in old) this[key] = old[key];
return curr;
};

200
src/acorn/src/lval.js Executable file
View File

@@ -0,0 +1,200 @@
import {types as tt} from "./tokentype"
import {Parser} from "./state"
import {reservedWords} from "./identifier"
import {has} from "./util"
const pp = Parser.prototype
// Convert existing expression atom to assignable pattern
// if possible.
pp.toAssignable = function(node, isBinding) {
if (this.options.ecmaVersion >= 6 && node) {
switch (node.type) {
case "Identifier":
case "ObjectPattern":
case "ArrayPattern":
case "AssignmentPattern":
break
case "ObjectExpression":
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)
}
break
case "ArrayExpression":
node.type = "ArrayPattern"
this.toAssignableList(node.elements, isBinding)
break
case "AssignmentExpression":
if (node.operator === "=") {
node.type = "AssignmentPattern"
} else {
this.raise(node.left.end, "Only '=' operator can be used for specifying default value.")
}
break
case "MemberExpression":
if (!isBinding) break
default:
this.raise(node.start, "Assigning to rvalue")
}
}
return node
}
// Convert list of expression atoms to binding list.
pp.toAssignableList = function(exprList, isBinding) {
let end = exprList.length
if (end) {
let last = exprList[end - 1]
if (last && last.type == "RestElement") {
--end
} else if (last && last.type == "SpreadElement") {
last.type = "RestElement"
let arg = last.argument
this.toAssignable(arg, isBinding)
if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern")
this.unexpected(arg.start)
--end
}
}
for (let i = 0; i < end; i++) {
let elt = exprList[i]
if (elt) this.toAssignable(elt, isBinding)
}
return exprList
}
// Parses spread element.
pp.parseSpread = function(refShorthandDefaultPos) {
let node = this.startNode()
this.next()
node.argument = this.parseMaybeAssign(refShorthandDefaultPos)
return this.finishNode(node, "SpreadElement")
}
pp.parseRest = function() {
let node = this.startNode()
this.next()
node.argument = this.type === tt.name || this.type === tt.bracketL ? this.parseBindingAtom() : this.unexpected()
return this.finishNode(node, "RestElement")
}
// Parses lvalue (assignable) atom.
pp.parseBindingAtom = function() {
if (this.options.ecmaVersion < 6) return this.parseIdent()
switch (this.type) {
case tt.name:
return this.parseIdent()
case tt.bracketL:
let node = this.startNode()
this.next()
node.elements = this.parseBindingList(tt.bracketR, true, true)
return this.finishNode(node, "ArrayPattern")
case tt.braceL:
return this.parseObj(true)
default:
this.unexpected()
}
}
pp.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
var elts = [], first = true
while (!this.eat(close)) {
if (first) first = false
else this.expect(tt.comma)
if (allowEmpty && this.type === tt.comma) {
elts.push(null)
} else if (allowTrailingComma && this.afterTrailingComma(close)) {
break
} else if (this.type === tt.ellipsis) {
elts.push(this.parseAssignableListItemTypes(this.parseRest()))
this.expect(close)
break
} else {
var left = this.parseMaybeDefault()
this.parseAssignableListItemTypes(left)
elts.push(this.parseMaybeDefault(null, left))
}
}
return elts
}
pp.parseAssignableListItemTypes = function(param) {
return param
}
// Parses assignment pattern around given atom if possible.
pp.parseMaybeDefault = function(startPos, left) {
startPos = startPos || this.markPosition()
left = left || this.parseBindingAtom()
if (!this.eat(tt.eq)) return left
let node = this.startNodeAt(startPos)
node.operator = "="
node.left = left
node.right = this.parseMaybeAssign()
return this.finishNode(node, "AssignmentPattern")
}
// Verify that a node is an lval — something that can be assigned
// to.
pp.checkLVal = function(expr, isBinding, checkClashes) {
switch (expr.type) {
case "Identifier":
if (this.strict && (reservedWords.strictBind(expr.name) || reservedWords.strict(expr.name)))
this.raise(expr.start, (isBinding ? "Binding " : "Assigning to ") + expr.name + " in strict mode")
if (checkClashes) {
if (has(checkClashes, expr.name))
this.raise(expr.start, "Argument name clash in strict mode")
checkClashes[expr.name] = true
}
break
case "MemberExpression":
if (isBinding) this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " member expression")
break
case "ObjectPattern":
for (let i = 0; i < expr.properties.length; i++) {
var prop = expr.properties[i];
if (prop.type === "Property") prop = prop.value;
this.checkLVal(prop, isBinding, checkClashes)
}
break
case "ArrayPattern":
for (let i = 0; i < expr.elements.length; i++) {
let elem = expr.elements[i]
if (elem) this.checkLVal(elem, isBinding, checkClashes)
}
break
case "AssignmentPattern":
this.checkLVal(expr.left, isBinding, checkClashes)
break
case "SpreadProperty":
case "RestElement":
this.checkLVal(expr.argument, isBinding, checkClashes)
break
default:
this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " rvalue")
}
}

57
src/acorn/src/node.js Executable file
View File

@@ -0,0 +1,57 @@
import {Parser} from "./state"
import {SourceLocation} from "./location"
// Start an AST node, attaching a start offset.
const pp = Parser.prototype
export class Node {}
pp.startNode = function() {
let node = new Node
node.start = this.start
if (this.options.locations)
node.loc = new SourceLocation(this, this.startLoc)
if (this.options.directSourceFile)
node.sourceFile = this.options.directSourceFile
if (this.options.ranges)
node.range = [this.start, 0]
return node
}
pp.startNodeAt = function(pos) {
let node = new Node, start = pos
if (this.options.locations) {
node.loc = new SourceLocation(this, start[1])
start = pos[0]
}
node.start = start
if (this.options.directSourceFile)
node.sourceFile = this.options.directSourceFile
if (this.options.ranges)
node.range = [start, 0]
return node
}
// Finish an AST node, adding `type` and `end` properties.
pp.finishNode = function(node, type) {
node.type = type
node.end = this.lastTokEnd
if (this.options.locations)
node.loc.end = this.lastTokEndLoc
if (this.options.ranges)
node.range[1] = this.lastTokEnd
return node
}
// Finish node at given position
pp.finishNodeAt = function(node, type, pos) {
if (this.options.locations) { node.loc.end = pos[1]; pos = pos[0] }
node.type = type
node.end = pos
if (this.options.ranges)
node.range[1] = pos
return node
}

122
src/acorn/src/options.js Executable file
View File

@@ -0,0 +1,122 @@
import {has, isArray} from "./util"
import {SourceLocation} from "./location"
// A second optional argument can be given to further configure
// the parser process. These options are recognized:
export const defaultOptions = {
// `ecmaVersion` indicates the ECMAScript version to parse. Must
// be either 3, or 5, or 6. This influences support for strict
// mode, the set of reserved words, support for getters and
// setters and other features.
ecmaVersion: 5,
// Source type ("script" or "module") for different semantics
sourceType: "script",
// `onInsertedSemicolon` can be a callback that will be called
// when a semicolon is automatically inserted. It will be passed
// th position of the comma as an offset, and if `locations` is
// enabled, it is given the location as a `{line, column}` object
// as second argument.
onInsertedSemicolon: null,
// `onTrailingComma` is similar to `onInsertedSemicolon`, but for
// trailing commas.
onTrailingComma: null,
// By default, reserved words are not enforced. Disable
// `allowReserved` to enforce them. When this option has the
// value "never", reserved words and keywords can also not be
// used as property names.
allowReserved: true,
// When enabled, a return at the top level is not considered an
// error.
allowReturnOutsideFunction: false,
// When enabled, import/export statements are not constrained to
// appearing at the top of the program.
allowImportExportEverywhere: false,
// When enabled, hashbang directive in the beginning of file
// is allowed and treated as a line comment.
allowHashBang: false,
// When `locations` is on, `loc` properties holding objects with
// `start` and `end` properties in `{line, column}` form (with
// line being 1-based and column 0-based) will be attached to the
// nodes.
locations: false,
// A function can be passed as `onToken` option, which will
// cause Acorn to call that function with object in the same
// format as tokenize() returns. Note that you are not
// allowed to call the parser from the callback—that will
// corrupt its internal state.
onToken: null,
// A function can be passed as `onComment` option, which will
// cause Acorn to call that function with `(block, text, start,
// end)` parameters whenever a comment is skipped. `block` is a
// boolean indicating whether this is a block (`/* */`) comment,
// `text` is the content of the comment, and `start` and `end` are
// character offsets that denote the start and end of the comment.
// When the `locations` option is on, two more parameters are
// passed, the full `{line, column}` locations of the start and
// end of the comments. Note that you are not allowed to call the
// parser from the callback—that will corrupt its internal state.
onComment: null,
// Nodes have their start and end characters offsets recorded in
// `start` and `end` properties (directly on the node, rather than
// the `loc` object, which holds line/column data. To also add a
// [semi-standardized][range] `range` property holding a `[start,
// end]` array with the same numbers, set the `ranges` option to
// `true`.
//
// [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
ranges: false,
// It is possible to parse multiple files into a single AST by
// passing the tree produced by parsing the first file as
// `program` option in subsequent parses. This will add the
// toplevel forms of the parsed file to the `Program` (top) node
// of an existing parse tree.
program: null,
// When `locations` is on, you can pass this to record the source
// file in every node's `loc` object.
sourceFile: null,
// This value, if given, is stored in every node, whether
// `locations` is on or off.
directSourceFile: null,
// When enabled, parenthesized expressions are represented by
// (non-standard) ParenthesizedExpression nodes
preserveParens: false,
plugins: {},
// Babel-specific options
features: {},
strictMode: null
}
// Interpret and default an options object
export function getOptions(opts) {
let options = {}
for (let opt in defaultOptions)
options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]
if (isArray(options.onToken)) {
let tokens = options.onToken
options.onToken = (token) => tokens.push(token)
}
if (isArray(options.onComment))
options.onComment = pushComment(options, options.onComment)
return options
}
function pushComment(options, array) {
return function (block, text, start, end, startLoc, endLoc) {
let comment = {
type: block ? 'Block' : 'Line',
value: text,
start: start,
end: end
}
if (options.locations)
comment.loc = new SourceLocation(this, startLoc, endLoc)
if (options.ranges)
comment.range = [start, end]
array.push(comment)
}
}

89
src/acorn/src/parseutil.js Executable file
View File

@@ -0,0 +1,89 @@
import {types as tt} from "./tokentype"
import {Parser} from "./state"
import {lineBreak} from "./whitespace"
const pp = Parser.prototype
// ## Parser utilities
// Test whether a statement node is the string literal `"use strict"`.
pp.isUseStrict = function(stmt) {
return this.options.ecmaVersion >= 5 && stmt.type === "ExpressionStatement" &&
stmt.expression.type === "Literal" && stmt.expression.value === "use strict"
}
// Predicate that tests whether the next token is of the given
// type, and if yes, consumes it as a side effect.
pp.eat = function(type) {
if (this.type === type) {
this.next()
return true
} else {
return false
}
}
// Tests whether parsed token is a contextual keyword.
pp.isContextual = function(name) {
return this.type === tt.name && this.value === name
}
// Consumes contextual keyword if possible.
pp.eatContextual = function(name) {
return this.value === name && this.eat(tt.name)
}
// Asserts that following token is given contextual keyword.
pp.expectContextual = function(name) {
if (!this.eatContextual(name)) this.unexpected()
}
// Test whether a semicolon can be inserted at the current position.
pp.canInsertSemicolon = function() {
return this.type === tt.eof ||
this.type === tt.braceR ||
lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
}
pp.insertSemicolon = function() {
if (this.canInsertSemicolon()) {
if (this.options.onInsertedSemicolon)
this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc)
return true
}
}
// Consume a semicolon, or, failing that, see if we are allowed to
// pretend that there is a semicolon at this position.
pp.semicolon = function() {
if (!this.eat(tt.semi) && !this.insertSemicolon()) this.unexpected()
}
pp.afterTrailingComma = function(tokType) {
if (this.type == tokType) {
if (this.options.onTrailingComma)
this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc)
this.next()
return true
}
}
// Expect a token of a given type. If found, consume it, otherwise,
// raise an unexpected token error.
pp.expect = function(type) {
this.eat(type) || this.unexpected()
}
// Raise an unexpected token error.
pp.unexpected = function(pos) {
this.raise(pos != null ? pos : this.start, "Unexpected token")
}

78
src/acorn/src/state.js Executable file
View File

@@ -0,0 +1,78 @@
import {reservedWords, keywords} from "./identifier"
import {types as tt, lineBreak} from "./tokentype"
export function Parser(options, input, startPos) {
this.options = options
this.loadPlugins(this.options.plugins)
this.sourceFile = this.options.sourceFile || null
this.isKeyword = keywords[this.options.ecmaVersion >= 6 ? 6 : 5]
this.isReservedWord = reservedWords[this.options.ecmaVersion]
this.input = input
// Set up token state
// The current position of the tokenizer in the input.
if (startPos) {
this.pos = startPos
this.lineStart = Math.max(0, this.input.lastIndexOf("\n", startPos))
this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length
} else {
this.pos = this.lineStart = 0
this.curLine = 1
}
// Properties of the current token:
// Its type
this.type = tt.eof
// For tokens that include more information than their type, the value
this.value = null
// Its start and end offset
this.start = this.end = this.pos
// And, if locations are used, the {line, column} object
// corresponding to those offsets
this.startLoc = this.endLoc = null
// Position information for the previous token
this.lastTokEndLoc = this.lastTokStartLoc = null
this.lastTokStart = this.lastTokEnd = this.pos
// The context stack is used to superficially track syntactic
// context to predict whether a regular expression is allowed in a
// given position.
this.context = this.initialContext()
this.exprAllowed = true
// Figure out if it's a module code.
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.
this.labels = []
this.decorators = []
// If enabled, skip leading hashbang line.
if (this.pos === 0 && this.options.allowHashBang && this.input.slice(0, 2) === '#!')
this.skipLineComment(2)
}
Parser.prototype.extend = function(name, f) {
this[name] = f(this[name])
}
// Registered plugins
export const plugins = {}
Parser.prototype.loadPlugins = function(plugins) {
for (let name in plugins) {
let plugin = exports.plugins[name]
if (!plugin) throw new Error("Plugin '" + name + "' not found")
plugin(this, plugins[name])
}
}

743
src/acorn/src/statement.js Executable file
View File

@@ -0,0 +1,743 @@
import {types as tt} from "./tokentype"
import {Parser} from "./state"
import {lineBreak} from "./whitespace"
const pp = Parser.prototype
// ### Statement parsing
// Parse a program. Initializes the parser, reads any number of
// statements, and wraps them in a Program node. Optionally takes a
// `program` argument. If present, the statements will be appended
// to its body instead of creating a new node.
pp.parseTopLevel = function(node) {
let first = true
if (!node.body) node.body = []
while (this.type !== tt.eof) {
let stmt = this.parseStatement(true, true)
node.body.push(stmt)
if (first && this.isUseStrict(stmt)) this.setStrict(true)
first = false
}
this.next()
if (this.options.ecmaVersion >= 6) {
node.sourceType = this.options.sourceType
}
return this.finishNode(node, "Program")
}
const loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"}
// Parse a single statement.
//
// If expecting a statement and finding a slash operator, parse a
// regular expression literal. This is to handle cases like
// `if (foo) /blah/.exec(foo)`, where looking at the previous token
// does not help.
pp.parseStatement = function(declaration, topLevel) {
if (this.type === tt.at) {
this.parseDecorators(true)
}
let starttype = this.type, node = this.startNode()
// Most types of statements are recognized by the keyword they
// start with. Many are trivial to parse, some require a bit of
// complexity.
switch (starttype) {
case tt._break: case tt._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
case tt._debugger: return this.parseDebuggerStatement(node)
case tt._do: return this.parseDoStatement(node)
case tt._for: return this.parseForStatement(node)
case tt._function:
if (!declaration && this.options.ecmaVersion >= 6) this.unexpected()
return this.parseFunctionStatement(node)
case tt._class:
if (!declaration) this.unexpected()
this.takeDecorators(node)
return this.parseClass(node, true)
case tt._if: return this.parseIfStatement(node)
case tt._return: return this.parseReturnStatement(node)
case tt._switch: return this.parseSwitchStatement(node)
case tt._throw: return this.parseThrowStatement(node)
case tt._try: return this.parseTryStatement(node)
case tt._let: case tt._const: if (!declaration) this.unexpected() // NOTE: falls through to _var
case tt._var: return this.parseVarStatement(node, starttype)
case tt._while: return this.parseWhileStatement(node)
case tt._with: return this.parseWithStatement(node)
case tt.braceL: return this.parseBlock()
case tt.semi: return this.parseEmptyStatement(node)
case tt._export:
case tt._import:
if (!this.options.allowImportExportEverywhere) {
if (!topLevel)
this.raise(this.start, "'import' and 'export' may only appear at the top level")
if (!this.inModule)
this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'")
}
return starttype === tt._import ? this.parseImport(node) : this.parseExport(node)
case tt.name:
if (this.options.features["es7.asyncFunctions"] && this.value === "async" && this.lookahead().type === tt._function) {
this.next();
this.expect(tt._function);
return this.parseFunction(node, true, false, true);
}
// If the statement does not start with a statement keyword or a
// brace, it's an ExpressionStatement or LabeledStatement. We
// simply start parsing an expression, and afterwards, if the
// next token is a colon and the expression was a simple
// Identifier node, we switch to interpreting it as a label.
default:
let maybeName = this.value, expr = this.parseExpression()
if (starttype === tt.name && expr.type === "Identifier" && this.eat(tt.colon))
return this.parseLabeledStatement(node, maybeName, expr)
else return this.parseExpressionStatement(node, expr)
}
}
pp.takeDecorators = function(node) {
if (this.decorators.length) {
node.decorators = this.decorators
this.decorators = []
}
}
pp.parseDecorators = function(allowExport) {
while (this.type === tt.at) {
this.decorators.push(this.parseDecorator());
}
if (allowExport && this.type === tt._export) {
return;
}
if (this.type !== tt._class) {
this.raise(this.start, "Leading decorators must be attached to a class declaration");
}
}
pp.parseDecorator = function(allowExport) {
if (!this.options.features["es7.decorators"]) {
this.unexpected()
}
let node = this.startNode()
this.next()
node.expression = this.parseMaybeAssign()
return this.finishNode(node, "Decorator")
}
pp.parseBreakContinueStatement = function(node, keyword) {
let isBreak = keyword == "break"
this.next()
if (this.eat(tt.semi) || this.insertSemicolon()) node.label = null
else if (this.type !== tt.name) this.unexpected()
else {
node.label = this.parseIdent()
this.semicolon()
}
// Verify that there is an actual destination to break or
// continue to.
for (var i = 0; i < this.labels.length; ++i) {
let lab = this.labels[i]
if (node.label == null || lab.name === node.label.name) {
if (lab.kind != null && (isBreak || lab.kind === "loop")) break
if (node.label && isBreak) break
}
}
if (i === this.labels.length) this.raise(node.start, "Unsyntactic " + keyword)
return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
}
pp.parseDebuggerStatement = function(node) {
this.next()
this.semicolon()
return this.finishNode(node, "DebuggerStatement")
}
pp.parseDoStatement = function(node) {
let start = this.markPosition()
this.next()
this.labels.push(loopLabel)
node.body = this.parseStatement(false)
this.labels.pop()
if (this.options.features["es7.doExpressions"] && this.type !== tt._while) {
let container = this.startNodeAt(start)
container.expression = this.finishNode(node, "DoExpression")
this.semicolon()
return this.finishNode(container, "ExpressionStatement")
}
this.expect(tt._while)
node.test = this.parseParenExpression()
if (this.options.ecmaVersion >= 6)
this.eat(tt.semi)
else
this.semicolon()
return this.finishNode(node, "DoWhileStatement")
}
// Disambiguating between a `for` and a `for`/`in` or `for`/`of`
// loop is non-trivial. Basically, we have to parse the init `var`
// statement or expression, disallowing the `in` operator (see
// the second parameter to `parseExpression`), and then check
// whether the next token is `in` or `of`. When there is no init
// part (semicolon immediately after the opening parenthesis), it
// is a regular `for` loop.
pp.parseForStatement = function(node) {
this.next()
this.labels.push(loopLabel)
this.expect(tt.parenL)
if (this.type === tt.semi) return this.parseFor(node, null)
if (this.type === tt._var || this.type === tt._let || this.type === tt._const) {
let init = this.startNode(), varKind = this.type
this.next()
this.parseVar(init, true, varKind)
this.finishNode(init, "VariableDeclaration")
if ((this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init.declarations.length === 1 &&
!(varKind !== tt._var && init.declarations[0].init))
return this.parseForIn(node, init)
return this.parseFor(node, init)
}
let refShorthandDefaultPos = {start: 0}
let init = this.parseExpression(true, refShorthandDefaultPos)
if (this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
this.toAssignable(init)
this.checkLVal(init)
return this.parseForIn(node, init)
} else if (refShorthandDefaultPos.start) {
this.unexpected(refShorthandDefaultPos.start)
}
return this.parseFor(node, init)
}
pp.parseFunctionStatement = function(node) {
this.next()
return this.parseFunction(node, true)
}
pp.parseIfStatement = function(node) {
this.next()
node.test = this.parseParenExpression()
node.consequent = this.parseStatement(false)
node.alternate = this.eat(tt._else) ? this.parseStatement(false) : null
return this.finishNode(node, "IfStatement")
}
pp.parseReturnStatement = function(node) {
if (!this.inFunction && !this.options.allowReturnOutsideFunction)
this.raise(this.start, "'return' outside of function")
this.next()
// In `return` (and `break`/`continue`), the keywords with
// optional arguments, we eagerly look for a semicolon or the
// possibility to insert one.
if (this.eat(tt.semi) || this.insertSemicolon()) node.argument = null
else { node.argument = this.parseExpression(); this.semicolon() }
return this.finishNode(node, "ReturnStatement")
}
pp.parseSwitchStatement = function(node) {
this.next()
node.discriminant = this.parseParenExpression()
node.cases = []
this.expect(tt.braceL)
this.labels.push(switchLabel)
// Statements under must be grouped (by label) in SwitchCase
// nodes. `cur` is used to keep the node that we are currently
// adding statements to.
for (var cur, sawDefault; this.type != tt.braceR;) {
if (this.type === tt._case || this.type === tt._default) {
let isCase = this.type === tt._case
if (cur) this.finishNode(cur, "SwitchCase")
node.cases.push(cur = this.startNode())
cur.consequent = []
this.next()
if (isCase) {
cur.test = this.parseExpression()
} else {
if (sawDefault) this.raise(this.lastTokStart, "Multiple default clauses")
sawDefault = true
cur.test = null
}
this.expect(tt.colon)
} else {
if (!cur) this.unexpected()
cur.consequent.push(this.parseStatement(true))
}
}
if (cur) this.finishNode(cur, "SwitchCase")
this.next() // Closing brace
this.labels.pop()
return this.finishNode(node, "SwitchStatement")
}
pp.parseThrowStatement = function(node) {
this.next()
if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
this.raise(this.lastTokEnd, "Illegal newline after throw")
node.argument = this.parseExpression()
this.semicolon()
return this.finishNode(node, "ThrowStatement")
}
// Reused empty array added for node fields that are always empty.
const empty = []
pp.parseTryStatement = function(node) {
this.next()
node.block = this.parseBlock()
node.handler = null
if (this.type === tt._catch) {
let clause = this.startNode()
this.next()
this.expect(tt.parenL)
clause.param = this.parseBindingAtom()
this.checkLVal(clause.param, true)
this.expect(tt.parenR)
clause.guard = null
clause.body = this.parseBlock()
node.handler = this.finishNode(clause, "CatchClause")
}
node.guardedHandlers = empty
node.finalizer = this.eat(tt._finally) ? this.parseBlock() : null
if (!node.handler && !node.finalizer)
this.raise(node.start, "Missing catch or finally clause")
return this.finishNode(node, "TryStatement")
}
pp.parseVarStatement = function(node, kind) {
this.next()
this.parseVar(node, false, kind)
this.semicolon()
return this.finishNode(node, "VariableDeclaration")
}
pp.parseWhileStatement = function(node) {
this.next()
node.test = this.parseParenExpression()
this.labels.push(loopLabel)
node.body = this.parseStatement(false)
this.labels.pop()
return this.finishNode(node, "WhileStatement")
}
pp.parseWithStatement = function(node) {
if (this.strict) this.raise(this.start, "'with' in strict mode")
this.next()
node.object = this.parseParenExpression()
node.body = this.parseStatement(false)
return this.finishNode(node, "WithStatement")
}
pp.parseEmptyStatement = function(node) {
this.next()
return this.finishNode(node, "EmptyStatement")
}
pp.parseLabeledStatement = function(node, maybeName, expr) {
for (let i = 0; i < this.labels.length; ++i)
if (this.labels[i].name === maybeName) this.raise(expr.start, "Label '" + maybeName + "' is already declared")
let kind = this.type.isLoop ? "loop" : this.type === tt._switch ? "switch" : null
this.labels.push({name: maybeName, kind: kind})
node.body = this.parseStatement(true)
this.labels.pop()
node.label = expr
return this.finishNode(node, "LabeledStatement")
}
pp.parseExpressionStatement = function(node, expr) {
node.expression = expr
this.semicolon()
return this.finishNode(node, "ExpressionStatement")
}
// Parse a semicolon-enclosed block of statements, handling `"use
// strict"` declarations when `allowStrict` is true (used for
// function bodies).
pp.parseBlock = function(allowStrict) {
let node = this.startNode(), first = true, oldStrict
node.body = []
this.expect(tt.braceL)
while (!this.eat(tt.braceR)) {
let stmt = this.parseStatement(true)
node.body.push(stmt)
if (first && allowStrict && this.isUseStrict(stmt)) {
oldStrict = this.strict
this.setStrict(this.strict = true)
}
first = false
}
if (oldStrict === false) this.setStrict(false)
return this.finishNode(node, "BlockStatement")
}
// Parse a regular `for` loop. The disambiguation code in
// `parseStatement` will already have parsed the init statement or
// expression.
pp.parseFor = function(node, init) {
node.init = init
this.expect(tt.semi)
node.test = this.type === tt.semi ? null : this.parseExpression()
this.expect(tt.semi)
node.update = this.type === tt.parenR ? null : this.parseExpression()
this.expect(tt.parenR)
node.body = this.parseStatement(false)
this.labels.pop()
return this.finishNode(node, "ForStatement")
}
// Parse a `for`/`in` and `for`/`of` loop, which are almost
// same from parser's perspective.
pp.parseForIn = function(node, init) {
let type = this.type === tt._in ? "ForInStatement" : "ForOfStatement"
this.next()
node.left = init
node.right = this.parseExpression()
this.expect(tt.parenR)
node.body = this.parseStatement(false)
this.labels.pop()
return this.finishNode(node, type)
}
// Parse a list of variable declarations.
pp.parseVar = function(node, isFor, kind) {
node.declarations = []
node.kind = kind.keyword
for (;;) {
let decl = this.startNode()
this.parseVarHead(decl)
if (this.eat(tt.eq)) {
decl.init = this.parseMaybeAssign(isFor)
} else if (kind === tt._const && !(this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
this.unexpected()
} else if (decl.id.type != "Identifier" && !(isFor && (this.type === tt._in || this.isContextual("of")))) {
this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value")
} else {
decl.init = null
}
node.declarations.push(this.finishNode(decl, "VariableDeclarator"))
if (!this.eat(tt.comma)) break
}
return node
}
pp.parseVarHead = function (decl) {
decl.id = this.parseBindingAtom()
this.checkLVal(decl.id, true)
}
// Parse a function declaration or literal (depending on the
// `isStatement` parameter).
pp.parseFunction = function(node, isStatement, allowExpressionBody, isAsync) {
this.initFunction(node, isAsync)
if (this.options.ecmaVersion >= 6)
node.generator = this.eat(tt.star)
if (isStatement || this.type === tt.name)
node.id = this.parseIdent()
this.parseFunctionParams(node);
this.parseFunctionBody(node, allowExpressionBody)
return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression")
}
pp.parseFunctionParams = function(node) {
this.expect(tt.parenL)
node.params = this.parseBindingList(tt.parenR, false, this.options.features["es7.trailingFunctionCommas"])
}
// Parse a class declaration or literal (depending on the
// `isStatement` parameter).
pp.parseClass = function(node, isStatement) {
this.next()
this.parseClassId(node, isStatement)
this.parseClassSuper(node)
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) {
decorators.push(this.parseDecorator())
continue
}
var method = this.startNode()
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" &&
method.key.name === "static") {
if (isGenerator) this.unexpected()
method['static'] = true
isGenerator = this.eat(tt.star)
this.parsePropertyName(method)
} else {
method['static'] = false
}
if (!isGenerator && method.key.type === "Identifier" && !method.computed && this.isClassProperty()) {
classBody.body.push(this.parseClassProperty(method))
continue
}
if (this.options.features["es7.asyncFunctions"] && this.type !== tt.parenL &&
!method.computed && method.key.type === "Identifier" && method.key.name === "async") {
isAsync = true
this.parsePropertyName(method)
}
method.kind = "method"
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
this.parsePropertyName(method)
} else if (!method['static'] && method.key.name === "constructor") {
method.kind = "constructor"
}
} else if (!method['static'] && method.key.type === "Literal" && method.key.value === "constructor") {
method.kind = "constructor"
}
}
if (method.kind === "constructor" && method.decorators) {
this.raise(method.start, "You can't attach decorators to a class constructor")
}
this.parseClassMethod(classBody, method, isGenerator, isAsync)
}
if (decorators.length) {
this.raise(this.start, "You have trailing decorators with no method");
}
node.body = this.finishNode(classBody, "ClassBody")
return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
}
pp.isClassProperty = function() {
return this.type === tt.eq || (this.type === tt.semi || this.canInsertSemicolon())
}
pp.parseClassProperty = function(node) {
if (this.type === tt.eq) {
if (!this.options.features["es7.classProperties"]) this.unexpected()
this.next()
node.value = this.parseMaybeAssign();
} else {
node.value = null;
}
this.semicolon()
return this.finishNode(node, "ClassProperty")
}
pp.parseClassMethod = function(classBody, method, isGenerator, isAsync) {
method.value = this.parseMethod(isGenerator, isAsync)
classBody.body.push(this.finishNode(method, "MethodDefinition"))
}
pp.parseClassId = function(node, isStatement) {
node.id = this.type === tt.name ? this.parseIdent() : isStatement ? this.unexpected() : null
}
pp.parseClassSuper = function(node) {
node.superClass = this.eat(tt._extends) ? this.parseExprSubscripts() : null
}
// Parses module export declaration.
pp.parseExport = function(node) {
this.next()
// export * from '...'
if (this.type === tt.star) {
let specifier = this.startNode()
this.next()
if (this.options.features["es7.exportExtensions"] && this.eatContextual("as")) {
specifier.exported = this.parseIdent()
node.specifiers = [this.finishNode(specifier, "ExportNamespaceSpecifier")]
this.parseExportSpecifiersMaybe(node)
this.parseExportFrom(node)
} else {
this.parseExportFrom(node)
return this.finishNode(node, "ExportAllDeclaration")
}
} else if (this.isExportDefaultSpecifier()) {
let specifier = this.startNode()
specifier.exported = this.parseIdent(true)
node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")]
if (this.type === tt.comma && this.lookahead().type === tt.star) {
this.expect(tt.comma)
let specifier = this.startNode()
this.expect(tt.star)
this.expectContextual("as")
specifier.exported = this.parseIdent()
node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier"))
} else {
this.parseExportSpecifiersMaybe(node)
}
this.parseExportFrom(node)
} else if (this.eat(tt._default)) { // export default ...
let expr = this.parseMaybeAssign()
let needsSemi = true
if (expr.type == "FunctionExpression" ||
expr.type == "ClassExpression") {
needsSemi = false
if (expr.id) {
expr.type = expr.type == "FunctionExpression"
? "FunctionDeclaration"
: "ClassDeclaration"
}
}
node.declaration = expr
if (needsSemi) this.semicolon()
this.checkExport(node)
return this.finishNode(node, "ExportDefaultDeclaration")
} else if (this.type.keyword || this.shouldParseExportDeclaration()) {
node.declaration = this.parseStatement(true)
node.specifiers = []
node.source = null
} else { // export { x, y as z } [from '...']
node.declaration = null
node.specifiers = this.parseExportSpecifiers()
if (this.eatContextual("from")) {
node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected()
} else {
node.source = null
}
this.semicolon()
}
this.checkExport(node)
return this.finishNode(node, "ExportNamedDeclaration")
}
pp.isExportDefaultSpecifier = function () {
if (this.type === tt.name) {
return this.value !== "type" && this.value !== "async"
}
if (this.type !== tt._default) {
return false
}
var lookahead = this.lookahead()
return lookahead.type === tt.comma || (lookahead.type === tt.name && lookahead.value === "from")
}
pp.parseExportSpecifiersMaybe = function (node) {
if (this.eat(tt.comma)) {
node.specifiers = node.specifiers.concat(this.parseExportSpecifiers())
}
}
pp.parseExportFrom = function(node) {
this.expectContextual("from")
node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected()
this.semicolon()
this.checkExport(node)
}
pp.shouldParseExportDeclaration = function() {
return this.options.features["es7.asyncFunctions"] && this.isContextual("async")
}
pp.checkExport = function(node) {
if (this.decorators.length) {
var isClass = node.declaration && (node.declaration.type === "ClassDeclaration" || node.declaration.type === "ClassExpression")
if (!node.declaration || !isClass) {
this.raise(node.start, "You can only use decorators on an export when exporting a class");
}
this.takeDecorators(node.declaration)
}
}
// Parses a comma-separated list of module exports.
pp.parseExportSpecifiers = function() {
let nodes = [], first = true
// export { x, y as z } [from '...']
this.expect(tt.braceL)
while (!this.eat(tt.braceR)) {
if (!first) {
this.expect(tt.comma)
if (this.afterTrailingComma(tt.braceR)) break
} else first = false
let node = this.startNode()
node.local = this.parseIdent(this.type === tt._default)
node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local
nodes.push(this.finishNode(node, "ExportSpecifier"))
}
return nodes
}
// Parses import declaration.
pp.parseImport = function(node) {
this.next()
// import '...'
if (this.type === tt.string) {
node.specifiers = empty
node.source = this.parseExprAtom()
} else {
node.specifiers = []
this.parseImportSpecifiers(node)
this.expectContextual("from")
node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected()
}
this.semicolon()
return this.finishNode(node, "ImportDeclaration")
}
// Parses a comma-separated list of module imports.
pp.parseImportSpecifiers = function(node) {
var first = true
if (this.type === tt.name) {
// import defaultObj, { x, y as z } from '...'
var start = this.markPosition()
node.specifiers.push(this.parseImportSpecifierDefault(this.parseIdent(), start))
if (!this.eat(tt.comma)) return
}
if (this.type === tt.star) {
var specifier = this.startNode()
this.next()
this.expectContextual("as")
specifier.local = this.parseIdent()
this.checkLVal(specifier.local, true)
node.specifiers.push(this.finishNode(specifier, "ImportNamespaceSpecifier"))
return
}
this.expect(tt.braceL)
while (!this.eat(tt.braceR)) {
if (!first) {
this.expect(tt.comma)
if (this.afterTrailingComma(tt.braceR)) break
} else first = false
var specifier = this.startNode()
specifier.imported = this.parseIdent(true)
specifier.local = this.eatContextual("as") ? this.parseIdent() : specifier.imported
this.checkLVal(specifier.local, true)
node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"))
}
}
pp.parseImportSpecifierDefault = function (id, start) {
var node = this.startNodeAt(start)
node.local = id
this.checkLVal(node.local, true)
return this.finishNode(node, "ImportDefaultSpecifier")
}

107
src/acorn/src/tokencontext.js Executable file
View File

@@ -0,0 +1,107 @@
// The algorithm used to determine whether a regexp can appear at a
// given point in the program is loosely based on sweet.js' approach.
// See https://github.com/mozilla/sweet.js/wiki/design
import {Parser} from "./state"
import {types as tt} from "./tokentype"
import {lineBreak} from "./whitespace"
export class TokContext {
constructor(token, isExpr, preserveSpace, override) {
this.token = token
this.isExpr = isExpr
this.preserveSpace = preserveSpace
this.override = override
}
}
export const types = {
b_stat: new TokContext("{", false),
b_expr: new TokContext("{", true),
b_tmpl: new TokContext("${", true),
p_stat: new TokContext("(", false),
p_expr: new TokContext("(", true),
q_tmpl: new TokContext("`", true, true, p => p.readTmplToken()),
f_expr: new TokContext("function", true)
}
const pp = Parser.prototype
pp.initialContext = function() {
return [types.b_stat]
}
pp.braceIsBlock = function(prevType) {
let parent
if (prevType === tt.colon && (parent = this.curContext()).token == "{")
return !parent.isExpr
if (prevType === tt._return)
return lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
if (prevType === tt._else || prevType === tt.semi || prevType === tt.eof)
return true
if (prevType == tt.braceL)
return this.curContext() === types.b_stat
return !this.exprAllowed
}
pp.updateContext = function(prevType) {
let update, type = this.type
if (type.keyword && prevType == tt.dot)
this.exprAllowed = false
else if (update = type.updateContext)
update.call(this, prevType)
else
this.exprAllowed = type.beforeExpr
}
// Token-specific context update code
tt.parenR.updateContext = tt.braceR.updateContext = function() {
if (this.context.length == 1) {
this.exprAllowed = true
return
}
let out = this.context.pop()
if (out === types.b_stat && this.curContext() === types.f_expr) {
this.context.pop()
this.exprAllowed = false
} else if (out === types.b_tmpl) {
this.exprAllowed = true
} else {
this.exprAllowed = !out.isExpr
}
}
tt.braceL.updateContext = function(prevType) {
this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr)
this.exprAllowed = true
}
tt.dollarBraceL.updateContext = function() {
this.context.push(types.b_tmpl)
this.exprAllowed = true
}
tt.parenL.updateContext = function(prevType) {
let statementParens = prevType === tt._if || prevType === tt._for || prevType === tt._with || prevType === tt._while
this.context.push(statementParens ? types.p_stat : types.p_expr)
this.exprAllowed = true
}
tt.incDec.updateContext = function() {
// tokExprAllowed stays unchanged
}
tt._function.updateContext = function() {
if (this.curContext() !== types.b_stat)
this.context.push(types.f_expr)
this.exprAllowed = false
}
tt.backQuote.updateContext = function() {
if (this.curContext() === types.q_tmpl)
this.context.pop()
else
this.context.push(types.q_tmpl)
this.exprAllowed = false
}

687
src/acorn/src/tokenize.js Executable file
View File

@@ -0,0 +1,687 @@
import {isIdentifierStart, isIdentifierChar} from "./identifier"
import {types as tt, keywords as keywordTypes} from "./tokentype"
import {Parser} from "./state"
import {SourceLocation} from "./location"
import {lineBreak, lineBreakG, isNewLine, nonASCIIwhitespace} from "./whitespace"
// Object type used to represent tokens. Note that normally, tokens
// simply exist as properties on the parser object. This is only
// used for the onToken callback and the external tokenizer.
export class Token {
constructor(p) {
this.type = p.type
this.value = p.value
this.start = p.start
this.end = p.end
if (p.options.locations)
this.loc = new SourceLocation(p, p.startLoc, p.endLoc)
if (p.options.ranges)
this.range = [p.start, p.end]
}
}
// ## Tokenizer
const pp = Parser.prototype
// Move to the next token
pp.next = function() {
if (this.options.onToken && !this.isLookahead)
this.options.onToken(new Token(this))
this.lastTokEnd = this.end
this.lastTokStart = this.start
this.lastTokEndLoc = this.endLoc
this.lastTokStartLoc = this.startLoc
this.nextToken()
}
pp.getToken = function() {
this.next()
return new Token(this)
}
// If we're in an ES6 environment, make parsers iterable
if (typeof Symbol !== "undefined")
pp[Symbol.iterator] = function () {
let self = this
return {next: function () {
let token = self.getToken()
return {
done: token.type === tt.eof,
value: token
}
}}
}
// Toggle strict mode. Re-reads the next number or string to please
// pedantic tests (`"use strict"; 010;` should fail).
pp.setStrict = function(strict) {
this.strict = strict
if (this.type !== tt.num && this.type !== tt.string) return
this.pos = this.start
if (this.options.locations) {
while (this.pos < this.lineStart) {
this.lineStart = this.input.lastIndexOf("\n", this.lineStart - 2) + 1
--this.curLine
}
}
this.nextToken()
}
pp.curContext = function() {
return this.context[this.context.length - 1]
}
// Read a single token, updating the parser object's token-related
// properties.
pp.nextToken = function() {
let curContext = this.curContext()
if (!curContext || !curContext.preserveSpace) this.skipSpace()
this.start = this.pos
if (this.options.locations) this.startLoc = this.curPosition()
if (this.pos >= this.input.length) return this.finishToken(tt.eof)
if (curContext.override) return curContext.override(this)
else this.readToken(this.fullCharCodeAtPos())
}
pp.readToken = function(code) {
// Identifier or keyword. '\uXXXX' sequences are allowed in
// identifiers, so '\' also dispatches to that.
if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
return this.readWord()
return this.getTokenFromCode(code)
}
pp.fullCharCodeAtPos = function() {
let code = this.input.charCodeAt(this.pos)
if (code <= 0xd7ff || code >= 0xe000) return code
let next = this.input.charCodeAt(this.pos + 1)
return (code << 10) + next - 0x35fdc00
}
pp.skipBlockComment = function() {
let startLoc = this.options.onComment && this.options.locations && this.curPosition()
let start = this.pos, end = this.input.indexOf("*/", this.pos += 2)
if (end === -1) this.raise(this.pos - 2, "Unterminated comment")
this.pos = end + 2
if (this.options.locations) {
lineBreakG.lastIndex = start
let match
while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
++this.curLine
this.lineStart = match.index + match[0].length
}
}
if (this.options.onComment)
this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
startLoc, this.options.locations && this.curPosition())
}
pp.skipLineComment = function(startSkip) {
let start = this.pos
let startLoc = this.options.onComment && this.options.locations && this.curPosition()
let ch = this.input.charCodeAt(this.pos+=startSkip)
while (this.pos < this.input.length && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) {
++this.pos
ch = this.input.charCodeAt(this.pos)
}
if (this.options.onComment)
this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
startLoc, this.options.locations && this.curPosition())
}
// Called at the start of the parse and after every token. Skips
// whitespace and comments, and.
pp.skipSpace = function() {
while (this.pos < this.input.length) {
let ch = this.input.charCodeAt(this.pos)
if (ch === 32) { // ' '
++this.pos
} else if (ch === 13) {
++this.pos
let next = this.input.charCodeAt(this.pos)
if (next === 10) {
++this.pos
}
if (this.options.locations) {
++this.curLine
this.lineStart = this.pos
}
} else if (ch === 10 || ch === 8232 || ch === 8233) {
++this.pos
if (this.options.locations) {
++this.curLine
this.lineStart = this.pos
}
} else if (ch > 8 && ch < 14) {
++this.pos
} else if (ch === 47) { // '/'
let next = this.input.charCodeAt(this.pos + 1)
if (next === 42) { // '*'
this.skipBlockComment()
} else if (next === 47) { // '/'
this.skipLineComment(2)
} else break
} else if (ch === 160) { // '\xa0'
++this.pos
} else if (ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
++this.pos
} else {
break
}
}
}
// Called at the end of every token. Sets `end`, `val`, and
// maintains `context` and `exprAllowed`, and skips the space after
// the token, so that the next one's `start` will point at the
// right position.
pp.finishToken = function(type, val) {
this.end = this.pos
if (this.options.locations) this.endLoc = this.curPosition()
let prevType = this.type
this.type = type
this.value = val
this.updateContext(prevType)
}
// ### Token reading
// This is the function that is called to fetch the next token. It
// is somewhat obscure, because it works in character codes rather
// than characters, and because operator parsing has been inlined
// into it.
//
// All in the name of speed.
//
pp.readToken_dot = function() {
let next = this.input.charCodeAt(this.pos + 1)
if (next >= 48 && next <= 57) return this.readNumber(true)
let next2 = this.input.charCodeAt(this.pos + 2)
if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
this.pos += 3
return this.finishToken(tt.ellipsis)
} else {
++this.pos
return this.finishToken(tt.dot)
}
}
pp.readToken_slash = function() { // '/'
let next = this.input.charCodeAt(this.pos + 1)
if (this.exprAllowed) {++this.pos; return this.readRegexp();}
if (next === 61) return this.finishOp(tt.assign, 2)
return this.finishOp(tt.slash, 1)
}
pp.readToken_mult_modulo = function(code) { // '%*'
var type = code === 42 ? tt.star : tt.modulo
var width = 1
var next = this.input.charCodeAt(this.pos + 1)
if (next === 42) { // '*'
width++
next = this.input.charCodeAt(this.pos + 2)
type = tt.exponent
}
if (next === 61) {
width++
type = tt.assign
}
return this.finishOp(type, width)
}
pp.readToken_pipe_amp = function(code) { // '|&'
let next = this.input.charCodeAt(this.pos + 1)
if (next === code) return this.finishOp(code === 124 ? tt.logicalOR : tt.logicalAND, 2)
if (next === 61) return this.finishOp(tt.assign, 2)
return this.finishOp(code === 124 ? tt.bitwiseOR : tt.bitwiseAND, 1)
}
pp.readToken_caret = function() { // '^'
let next = this.input.charCodeAt(this.pos + 1)
if (next === 61) return this.finishOp(tt.assign, 2)
return this.finishOp(tt.bitwiseXOR, 1)
}
pp.readToken_plus_min = function(code) { // '+-'
let next = this.input.charCodeAt(this.pos + 1)
if (next === code) {
if (next == 45 && this.input.charCodeAt(this.pos + 2) == 62 &&
lineBreak.test(this.input.slice(this.lastTokEnd, this.pos))) {
// A `-->` line comment
this.skipLineComment(3)
this.skipSpace()
return this.nextToken()
}
return this.finishOp(tt.incDec, 2)
}
if (next === 61) return this.finishOp(tt.assign, 2)
return this.finishOp(tt.plusMin, 1)
}
pp.readToken_lt_gt = function(code) { // '<>'
let next = this.input.charCodeAt(this.pos + 1)
let size = 1
if (next === code) {
size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2
if (this.input.charCodeAt(this.pos + size) === 61) return this.finishOp(tt.assign, size + 1)
return this.finishOp(tt.bitShift, size)
}
if (next == 33 && code == 60 && this.input.charCodeAt(this.pos + 2) == 45 &&
this.input.charCodeAt(this.pos + 3) == 45) {
if (this.inModule) this.unexpected()
// `<!--`, an XML-style comment that should be interpreted as a line comment
this.skipLineComment(4)
this.skipSpace()
return this.nextToken()
}
if (next === 61)
size = this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2
return this.finishOp(tt.relational, size)
}
pp.readToken_eq_excl = function(code) { // '=!'
let next = this.input.charCodeAt(this.pos + 1)
if (next === 61) return this.finishOp(tt.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2)
if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
this.pos += 2
return this.finishToken(tt.arrow)
}
return this.finishOp(code === 61 ? tt.eq : tt.prefix, 1)
}
pp.getTokenFromCode = function(code) {
switch (code) {
// The interpretation of a dot depends on whether it is followed
// by a digit or another two dots.
case 46: // '.'
return this.readToken_dot()
// Punctuation tokens.
case 40: ++this.pos; return this.finishToken(tt.parenL)
case 41: ++this.pos; return this.finishToken(tt.parenR)
case 59: ++this.pos; return this.finishToken(tt.semi)
case 44: ++this.pos; return this.finishToken(tt.comma)
case 91: ++this.pos; return this.finishToken(tt.bracketL)
case 93: ++this.pos; return this.finishToken(tt.bracketR)
case 123: ++this.pos; return this.finishToken(tt.braceL)
case 125: ++this.pos; return this.finishToken(tt.braceR)
case 58:
if (this.options.features["es7.functionBind"] && this.input.charCodeAt(this.pos + 1) === 58)
return this.finishOp(tt.doubleColon, 2)
++this.pos
return this.finishToken(tt.colon)
case 63: ++this.pos; return this.finishToken(tt.question)
case 64: ++this.pos; return this.finishToken(tt.at)
case 96: // '`'
if (this.options.ecmaVersion < 6) break
++this.pos
return this.finishToken(tt.backQuote)
case 48: // '0'
let next = this.input.charCodeAt(this.pos + 1)
if (next === 120 || next === 88) return this.readRadixNumber(16); // '0x', '0X' - hex number
if (this.options.ecmaVersion >= 6) {
if (next === 111 || next === 79) return this.readRadixNumber(8); // '0o', '0O' - octal number
if (next === 98 || next === 66) return this.readRadixNumber(2); // '0b', '0B' - binary number
}
// Anything else beginning with a digit is an integer, octal
// number, or float.
case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
return this.readNumber(false)
// Quotes produce strings.
case 34: case 39: // '"', "'"
return this.readString(code)
// Operators are parsed inline in tiny state machines. '=' (61) is
// often referred to. `finishOp` simply skips the amount of
// characters it is given as second argument, and returns a token
// of the type given by its first argument.
case 47: // '/'
return this.readToken_slash()
case 37: case 42: // '%*'
return this.readToken_mult_modulo(code)
case 124: case 38: // '|&'
return this.readToken_pipe_amp(code)
case 94: // '^'
return this.readToken_caret()
case 43: case 45: // '+-'
return this.readToken_plus_min(code)
case 60: case 62: // '<>'
return this.readToken_lt_gt(code)
case 61: case 33: // '=!'
return this.readToken_eq_excl(code)
case 126: // '~'
return this.finishOp(tt.prefix, 1)
}
this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'")
}
pp.finishOp = function(type, size) {
let str = this.input.slice(this.pos, this.pos + size)
this.pos += size
return this.finishToken(type, str)
}
var regexpUnicodeSupport = false
try { new RegExp("\uffff", "u"); regexpUnicodeSupport = true }
catch(e) {}
// Parse a regular expression. Some context-awareness is necessary,
// since a '/' inside a '[]' set does not end the expression.
pp.readRegexp = function() {
let escaped, inClass, start = this.pos
for (;;) {
if (this.pos >= this.input.length) this.raise(start, "Unterminated regular expression")
let ch = this.input.charAt(this.pos)
if (lineBreak.test(ch)) this.raise(start, "Unterminated regular expression")
if (!escaped) {
if (ch === "[") inClass = true
else if (ch === "]" && inClass) inClass = false
else if (ch === "/" && !inClass) break
escaped = ch === "\\"
} else escaped = false
++this.pos
}
let content = this.input.slice(start, this.pos)
++this.pos
// Need to use `readWord1` because '\uXXXX' sequences are allowed
// here (don't ask).
let mods = this.readWord1()
let tmp = content
if (mods) {
let validFlags = /^[gmsiy]*$/
if (this.options.ecmaVersion >= 6) validFlags = /^[gmsiyu]*$/
if (!validFlags.test(mods)) this.raise(start, "Invalid regular expression flag")
if (mods.indexOf('u') >= 0 && !regexpUnicodeSupport) {
// Replace each astral symbol and every Unicode escape sequence that
// possibly represents an astral symbol or a paired surrogate with a
// single ASCII symbol to avoid throwing on regular expressions that
// are only valid in combination with the `/u` flag.
// Note: replacing with the ASCII symbol `x` might cause false
// negatives in unlikely scenarios. For example, `[\u{61}-b]` is a
// perfectly valid pattern that is equivalent to `[a-b]`, but it would
// be replaced by `[x-b]` which throws an error.
tmp = tmp.replace(/\\u([a-fA-F0-9]{4})|\\u\{([0-9a-fA-F]+)\}|[\uD800-\uDBFF][\uDC00-\uDFFF]/g, "x")
}
}
// Detect invalid regular expressions.
try {
new RegExp(tmp)
} catch (e) {
if (e instanceof SyntaxError) this.raise(start, "Error parsing regular expression: " + e.message)
this.raise(e)
}
// Get a regular expression object for this pattern-flag pair, or `null` in
// case the current environment doesn't support the flags it uses.
let value
try {
value = new RegExp(content, mods)
} catch (err) {
value = null
}
return this.finishToken(tt.regexp, {pattern: content, flags: mods, value: value})
}
// Read an integer in the given radix. Return null if zero digits
// were read, the integer value otherwise. When `len` is given, this
// will return `null` unless the integer has exactly `len` digits.
pp.readInt = function(radix, len) {
let start = this.pos, total = 0
for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {
let code = this.input.charCodeAt(this.pos), val
if (code >= 97) val = code - 97 + 10; // a
else if (code >= 65) val = code - 65 + 10; // A
else if (code >= 48 && code <= 57) val = code - 48; // 0-9
else val = Infinity
if (val >= radix) break
++this.pos
total = total * radix + val
}
if (this.pos === start || len != null && this.pos - start !== len) return null
return total
}
pp.readRadixNumber = function(radix) {
this.pos += 2; // 0x
let val = this.readInt(radix)
if (val == null) this.raise(this.start + 2, "Expected number in radix " + radix)
if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number")
return this.finishToken(tt.num, val)
}
// Read an integer, octal integer, or floating-point number.
pp.readNumber = function(startsWithDot) {
let start = this.pos, isFloat = false, octal = this.input.charCodeAt(this.pos) === 48
if (!startsWithDot && this.readInt(10) === null) this.raise(start, "Invalid number")
if (this.input.charCodeAt(this.pos) === 46) {
++this.pos
this.readInt(10)
isFloat = true
}
let next = this.input.charCodeAt(this.pos)
if (next === 69 || next === 101) { // 'eE'
next = this.input.charCodeAt(++this.pos)
if (next === 43 || next === 45) ++this.pos; // '+-'
if (this.readInt(10) === null) this.raise(start, "Invalid number")
isFloat = true
}
if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number")
let str = this.input.slice(start, this.pos), val
if (isFloat) val = parseFloat(str)
else if (!octal || str.length === 1) val = parseInt(str, 10)
else if (/[89]/.test(str) || this.strict) this.raise(start, "Invalid number")
else val = parseInt(str, 8)
return this.finishToken(tt.num, val)
}
// Read a string value, interpreting backslash-escapes.
pp.readCodePoint = function() {
let ch = this.input.charCodeAt(this.pos), code
if (ch === 123) {
if (this.options.ecmaVersion < 6) this.unexpected()
++this.pos
code = this.readHexChar(this.input.indexOf('}', this.pos) - this.pos)
++this.pos
if (code > 0x10FFFF) this.unexpected()
} else {
code = this.readHexChar(4)
}
return code
}
function codePointToString(code) {
// UTF-16 Decoding
if (code <= 0xFFFF) return String.fromCharCode(code)
return String.fromCharCode(((code - 0x10000) >> 10) + 0xD800,
((code - 0x10000) & 1023) + 0xDC00)
}
pp.readString = function(quote) {
let out = "", chunkStart = ++this.pos
for (;;) {
if (this.pos >= this.input.length) this.raise(this.start, "Unterminated string constant")
let ch = this.input.charCodeAt(this.pos)
if (ch === quote) break
if (ch === 92) { // '\'
out += this.input.slice(chunkStart, this.pos)
out += this.readEscapedChar()
chunkStart = this.pos
} else {
if (isNewLine(ch)) this.raise(this.start, "Unterminated string constant")
++this.pos
}
}
out += this.input.slice(chunkStart, this.pos++)
return this.finishToken(tt.string, out)
}
// Reads template string tokens.
pp.readTmplToken = function() {
let out = "", chunkStart = this.pos
for (;;) {
if (this.pos >= this.input.length) this.raise(this.start, "Unterminated template")
let ch = this.input.charCodeAt(this.pos)
if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
if (this.pos === this.start && this.type === tt.template) {
if (ch === 36) {
this.pos += 2
return this.finishToken(tt.dollarBraceL)
} else {
++this.pos
return this.finishToken(tt.backQuote)
}
}
out += this.input.slice(chunkStart, this.pos)
return this.finishToken(tt.template, out)
}
if (ch === 92) { // '\'
out += this.input.slice(chunkStart, this.pos)
out += this.readEscapedChar()
chunkStart = this.pos
} else if (isNewLine(ch)) {
out += this.input.slice(chunkStart, this.pos)
++this.pos
if (ch === 13 && this.input.charCodeAt(this.pos) === 10) {
++this.pos
out += "\n"
} else {
out += String.fromCharCode(ch)
}
if (this.options.locations) {
++this.curLine
this.lineStart = this.pos
}
chunkStart = this.pos
} else {
++this.pos
}
}
}
// Used to read escaped characters
pp.readEscapedChar = function() {
let ch = this.input.charCodeAt(++this.pos)
let octal = /^[0-7]+/.exec(this.input.slice(this.pos, this.pos + 3))
if (octal) octal = octal[0]
while (octal && parseInt(octal, 8) > 255) octal = octal.slice(0, -1)
if (octal === "0") octal = null
++this.pos
if (octal) {
if (this.strict) this.raise(this.pos - 2, "Octal literal in strict mode")
this.pos += octal.length - 1
return String.fromCharCode(parseInt(octal, 8))
} else {
switch (ch) {
case 110: return "\n"; // 'n' -> '\n'
case 114: return "\r"; // 'r' -> '\r'
case 120: return String.fromCharCode(this.readHexChar(2)); // 'x'
case 117: return codePointToString(this.readCodePoint()); // 'u'
case 116: return "\t"; // 't' -> '\t'
case 98: return "\b"; // 'b' -> '\b'
case 118: return "\u000b"; // 'v' -> '\u000b'
case 102: return "\f"; // 'f' -> '\f'
case 48: return "\0"; // 0 -> '\0'
case 13: if (this.input.charCodeAt(this.pos) === 10) ++this.pos; // '\r\n'
case 10: // ' \n'
if (this.options.locations) { this.lineStart = this.pos; ++this.curLine }
return ""
default: return String.fromCharCode(ch)
}
}
}
// Used to read character escape sequences ('\x', '\u', '\U').
pp.readHexChar = function(len) {
let n = this.readInt(16, len)
if (n === null) this.raise(this.start, "Bad character escape sequence")
return n
}
// Used to signal to callers of `readWord1` whether the word
// contained any escape sequences. This is needed because words with
// escape sequences must not be interpreted as keywords.
var containsEsc
// Read an identifier, and return it as a string. Sets `containsEsc`
// to whether the word contained a '\u' escape.
//
// Incrementally adds only escaped chars, adding other chunks as-is
// as a micro-optimization.
pp.readWord1 = function() {
containsEsc = false
let word = "", first = true, chunkStart = this.pos
let astral = this.options.ecmaVersion >= 6
while (this.pos < this.input.length) {
let ch = this.fullCharCodeAtPos()
if (isIdentifierChar(ch, astral)) {
this.pos += ch <= 0xffff ? 1 : 2
} else if (ch === 92) { // "\"
containsEsc = true
word += this.input.slice(chunkStart, this.pos)
let escStart = this.pos
if (this.input.charCodeAt(++this.pos) != 117) // "u"
this.raise(this.pos, "Expecting Unicode escape sequence \\uXXXX")
++this.pos
let esc = this.readCodePoint()
if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
this.raise(escStart, "Invalid Unicode escape")
word += codePointToString(esc)
chunkStart = this.pos
} else {
break
}
first = false
}
return word + this.input.slice(chunkStart, this.pos)
}
// Read an identifier or keyword token. Will check for reserved
// words when necessary.
pp.readWord = function() {
let word = this.readWord1()
let type = tt.name
if ((this.options.ecmaVersion >= 6 || !containsEsc) && this.isKeyword(word))
type = keywordTypes[word]
return this.finishToken(type, word)
}

146
src/acorn/src/tokentype.js Executable file
View File

@@ -0,0 +1,146 @@
// ## Token types
// The assignment of fine-grained, information-carrying type objects
// allows the tokenizer to store the information it has about a
// token in a way that is very cheap for the parser to look up.
// All token type variables start with an underscore, to make them
// easy to recognize.
// The `beforeExpr` property is used to disambiguate between regular
// expressions and divisions. It is set on all token types that can
// be followed by an expression (thus, a slash after them would be a
// regular expression).
//
// `isLoop` marks a keyword as starting a loop, which is important
// to know when parsing a label, in order to allow or disallow
// continue jumps to that label.
export class TokenType {
constructor(label, conf = {}) {
this.label = label
this.keyword = conf.keyword
this.beforeExpr = !!conf.beforeExpr
this.startsExpr = !!conf.startsExpr
this.rightAssociative = !!conf.rightAssociative
this.isLoop = !!conf.isLoop
this.isAssign = !!conf.isAssign
this.prefix = !!conf.prefix
this.postfix = !!conf.postfix
this.binop = conf.binop || null
this.updateContext = null
}
}
function binop(name, prec) {
return new TokenType(name, {beforeExpr: true, binop: prec})
}
const beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true}
export const types = {
num: new TokenType("num", startsExpr),
regexp: new TokenType("regexp", startsExpr),
string: new TokenType("string", startsExpr),
name: new TokenType("name", startsExpr),
eof: new TokenType("eof"),
// Punctuation token types.
bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
bracketR: new TokenType("]"),
braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
braceR: new TokenType("}"),
parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
parenR: new TokenType(")"),
comma: new TokenType(",", beforeExpr),
semi: new TokenType(";", beforeExpr),
colon: new TokenType(":", beforeExpr),
doubleColon: new TokenType("::", beforeExpr),
dot: new TokenType("."),
question: new TokenType("?", beforeExpr),
arrow: new TokenType("=>", beforeExpr),
template: new TokenType("template"),
ellipsis: new TokenType("...", beforeExpr),
backQuote: new TokenType("`", startsExpr),
dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
at: new TokenType("@"),
// Operators. These carry several kinds of properties to help the
// parser use them properly (the presence of these properties is
// what categorizes them as operators).
//
// `binop`, when present, specifies that this operator is a binary
// operator, and will refer to its precedence.
//
// `prefix` and `postfix` mark the operator as a prefix or postfix
// unary operator.
//
// `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
// binary operators with a very low precedence, that should result
// in AssignmentExpression nodes.
eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
prefix: new TokenType("prefix", {beforeExpr: true, prefix: true, startsExpr: true}),
logicalOR: binop("||", 1),
logicalAND: binop("&&", 2),
bitwiseOR: binop("|", 3),
bitwiseXOR: binop("^", 4),
bitwiseAND: binop("&", 5),
equality: binop("==/!=", 6),
relational: binop("</>", 7),
bitShift: binop("<</>>", 8),
plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
modulo: binop("%", 10),
star: binop("*", 10),
slash: binop("/", 10),
exponent: new TokenType("**", {beforeExpr: true, binop: 11, rightAssociative: true})
}
// Map keyword names to token types.
export const keywords = {}
// Succinct definitions of keyword token types
function kw(name, options = {}) {
options.keyword = name
keywords[name] = types["_" + name] = new TokenType(name, options)
}
kw("break")
kw("case", beforeExpr)
kw("catch")
kw("continue")
kw("debugger")
kw("default")
kw("do", {isLoop: true})
kw("else", beforeExpr)
kw("finally")
kw("for", {isLoop: true})
kw("function", startsExpr)
kw("if")
kw("return", beforeExpr)
kw("switch")
kw("throw", beforeExpr)
kw("try")
kw("var")
kw("let")
kw("const")
kw("while", {isLoop: true})
kw("with")
kw("new", {beforeExpr: true, startsExpr: true})
kw("this", startsExpr)
kw("super", startsExpr)
kw("class")
kw("extends", beforeExpr)
kw("export")
kw("import")
kw("yield", {beforeExpr: true, startsExpr: true})
kw("null", startsExpr)
kw("true", startsExpr)
kw("false", startsExpr)
kw("in", {beforeExpr: true, binop: 7})
kw("instanceof", {beforeExpr: true, binop: 7})
kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true})
kw("void", {beforeExpr: true, prefix: true, startsExpr: true})
kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})

9
src/acorn/src/util.js Executable file
View File

@@ -0,0 +1,9 @@
export function isArray(obj) {
return Object.prototype.toString.call(obj) === "[object Array]"
}
// Checks if an object has a property.
export function has(obj, propName) {
return Object.prototype.hasOwnProperty.call(obj, propName)
}

12
src/acorn/src/whitespace.js Executable file
View File

@@ -0,0 +1,12 @@
// Matches a whole line break (where CRLF is considered a single
// line break). Used to count lines.
export const lineBreak = /\r\n?|\n|\u2028|\u2029/
export const lineBreakG = new RegExp(lineBreak.source, "g")
export function isNewLine(code) {
return code === 10 || code === 13 || code === 0x2028 || code == 0x2029
}
export const nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/

View File

@@ -1,18 +1,18 @@
require("./node");
var transform = module.exports = require("../transformation");
transform.options = require("../transformation/file/options");
transform.version = require("../../../package").version;
transform.transform = transform;
transform.run = function (code, opts) {
opts ||= {};
opts.sourceMap = "inline";
transform.run = function (code, opts = {}) {
opts.sourceMaps = "inline";
return new Function(transform(code, opts).code)();
};
transform.load = function (url, callback, opts, hold) {
opts ||= {};
opts.filename ||= url;
transform.load = function (url, callback, opts = {}, hold) {
opts.filename = opts.filename || url;
var xhr = global.ActiveXObject ? new global.ActiveXObject("Microsoft.XMLHTTP") : new global.XMLHttpRequest();
xhr.open("GET", url, true);
@@ -27,7 +27,7 @@ transform.load = function (url, callback, opts, hold) {
if (!hold) transform.run.apply(transform, param);
if (callback) callback(param);
} else {
throw new Error("Could not load " + url);
throw new Error(`Could not load ${url}`);
}
};

View File

@@ -1,32 +1,34 @@
var isFunction = require("lodash/lang/isFunction");
var transform = require("../transformation");
var util = require("../util");
var fs = require("fs");
import isFunction from "lodash/lang/isFunction";
import transform from "../transformation";
import * as acorn from "../../acorn";
import * as util from "../util";
import fs from "fs";
exports.version = require("../../../package").version;
export { util, acorn, transform };
export { pipeline } from "../transformation";
export { canCompile } from "../util";
exports.buildExternalHelpers = require("../build-external-helpers");
export { default as options } from "../transformation/file/options";
export { default as Transformer } from "../transformation/transformer";
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";
exports.types = require("../types");
import * as t from "../types";
export { t as types };
exports.register = function (opts) {
var register = require("./register/node");
if (opts != null) register(opts);
return register;
};
export function register(opts?: Object) {
var callback = require("./register/node-polyfill");
if (opts != null) callback(opts);
return callback;
}
exports.polyfill = function () {
export function polyfill() {
require("../polyfill");
};
}
exports.canCompile = util.canCompile;
// do not use this - this is for use by official maintained babel plugins
exports._util = util;
exports.transform = transform;
exports.transformFile = function (filename, opts, callback) {
export function transformFile(filename: string, opts?: Object, callback: Function) {
if (isFunction(opts)) {
callback = opts;
opts = {};
@@ -47,10 +49,26 @@ exports.transformFile = function (filename, opts, callback) {
callback(null, result);
});
};
}
exports.transformFileSync = function (filename, opts) {
opts ||= {};
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,5 +1,5 @@
// required to safely use babel/register within a browserify codebase
module.exports = function () {};
export default function () {};
require("../../polyfill");
import "../../polyfill";

View File

@@ -1,26 +1,20 @@
var path = require("path");
var os = require("os");
var fs = require("fs");
import path from "path";
import os from "os";
import fs from "fs";
import userHome from "user-home";
var FILENAME = process.env.BABEL_CACHE_PATH || path.join(os.tmpdir(), "babel.json");
const FILENAME = process.env.BABEL_CACHE_PATH || path.join(userHome || os.tmpdir(), ".babel.json");
var data = {};
exports.save = function () {
export function save() {
fs.writeFileSync(FILENAME, JSON.stringify(data, null, " "));
};
}
exports.load = function () {
export function load() {
if (process.env.BABEL_DISABLE_CACHE) return;
process.on("exit", exports.save);
var sigint = function () {
process.removeListener("SIGINT", sigint);
exports.save();
process.kill(process.pid, "SIGINT");
};
process.on("SIGINT", sigint);
process.on("exit", save);
process.nextTick(save);
if (!fs.existsSync(FILENAME)) return;
@@ -29,8 +23,8 @@ exports.load = function () {
} catch (err) {
return;
}
};
}
exports.get = function () {
export function get() {
return data;
};
}

View File

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

View File

@@ -1,15 +1,15 @@
require("../../polyfill");
var sourceMapSupport = require("source-map-support");
var registerCache = require("./cache");
var resolveRc = require("./resolve-rc");
var extend = require("lodash/object/extend");
var babel = require("../node");
var each = require("lodash/collection/each");
var util = require("../../util");
var fs = require("fs");
import sourceMapSupport from "source-map-support";
import * as registerCache from "./cache";
import resolveRc from "../../tools/resolve-rc";
import extend from "lodash/object/extend";
import * as babel from "../node";
import each from "lodash/collection/each";
import * as util from "../../util";
import fs from "fs";
import slash from "slash";
sourceMapSupport.install({
handleUncaughtExceptions: false,
retrieveSourceMap(source) {
var map = maps && maps[source];
if (map) {
@@ -31,9 +31,11 @@ var cache = registerCache.get();
//
var transformOpts = {};
var ignoreRegex = /node_modules/;
var onlyRegex;
var exts = {};
var ignore;
var only;
var oldHandlers = {};
var maps = {};
var mtime = function (filename) {
@@ -44,9 +46,12 @@ var compile = function (filename) {
var result;
var opts = extend({}, transformOpts);
// this will be done when the file is transformed anyway but we need all
// the options so we can generate the cache key
resolveRc(filename, opts);
var cacheKey = filename + ":" + JSON.stringify(opts);
var cacheKey = `${filename}:${JSON.stringify(opts)}:${babel.version}`;
if (cache) {
var cached = cache[cacheKey];
@@ -57,7 +62,7 @@ var compile = function (filename) {
if (!result) {
result = babel.transformFileSync(filename, extend(opts, {
sourceMap: true,
sourceMap: "both",
ast: false
}));
}
@@ -73,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;
@@ -105,10 +114,10 @@ var normalLoader = function (m, filename) {
};
var registerExtension = function (ext) {
var old = require.extensions[ext];
var old = oldHandlers[ext] || oldHandlers[".js"];
var loader = normalLoader;
if (process.env.running_under_istanbul) loader = istanbulLoader; // jshint ignore:line
if (process.env.running_under_istanbul) loader = istanbulLoader;
require.extensions[ext] = function (m, filename) {
if (shouldIgnore(filename)) {
@@ -120,26 +129,27 @@ var registerExtension = function (ext) {
};
var hookExtensions = function (_exts) {
each(exts, function (old, ext) {
require.extensions[ext] = old;
each(oldHandlers, function (old, ext) {
if (old === undefined) {
delete require.extensions[ext];
} else {
require.extensions[ext] = old;
}
});
exts = {};
oldHandlers = {};
each(_exts, function (ext) {
exts[ext] = require.extensions[ext];
oldHandlers[ext] = require.extensions[ext];
registerExtension(ext);
});
};
hookExtensions(util.canCompile.EXTENSIONS);
module.exports = function (opts) {
// normalize options
opts ||= {};
if (opts.only != null) onlyRegex = util.regexify(opts.only);
if (opts.ignore != null) ignoreRegex = util.regexify(opts.ignore);
export default function (opts = {}) {
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));

View File

@@ -1,48 +0,0 @@
var merge = require("lodash/object/merge");
var path = require("path");
var fs = require("fs");
var cache = {};
function exists(filename) {
var cached = cache[filename];
if (cached != null) return cached;
return cache[filename] = fs.existsSync(filename);
}
module.exports = function (loc, opts) {
var rel = ".babelrc";
opts ||= {};
function find(start, rel) {
var file = path.join(start, rel);
if (exists(file)) {
var content = fs.readFileSync(file, "utf8");
var json;
try {
json = JSON.parse(content);
} catch (err) {
err.message = file + ": " + err.message;
throw err;
}
if (json.breakConfig) return;
merge(opts, json, function(a, b) {
if (Array.isArray(a)) {
return a.concat(b);
}
});
}
var up = path.dirname(start);
if (up !== start) { // root
find(up, rel);
}
}
find(loc, rel);
return opts;
};

View File

@@ -1,23 +0,0 @@
var buildHelpers = require("./build-helpers");
var generator = require("./generation");
var util = require("./util");
var t = require("./types");
module.exports = function (whitelist) {
var namespace = t.identifier("babelHelpers");
var body = [];
var container = t.functionExpression(null, [t.identifier("global")], t.blockStatement(body));
var tree = t.program([t.expressionStatement(t.callExpression(container, [util.template("self-global")]))]);
body.push(t.variableDeclaration("var", [
t.variableDeclarator(
namespace,
t.assignmentExpression("=", t.memberExpression(t.identifier("global"), namespace), t.objectExpression([]))
)
]));
buildHelpers(body, namespace, whitelist);
return generator(tree).code;
};

View File

@@ -1,15 +0,0 @@
var File = require("./transformation/file");
var util = require("./util");
var each = require("lodash/collection/each");
var t = require("./types");
module.exports = function (body, namespace, whitelist = []) {
each(File.helpers, function (name) {
if (whitelist.length && whitelist.indexOf(key) >= 0) return;
var key = t.identifier(t.toIdentifier(name));
body.push(t.expressionStatement(
t.assignmentExpression("=", t.memberExpression(namespace, key), util.template(name))
));
});
};

View File

@@ -1,29 +0,0 @@
module.exports = detect;
var SYNTAX_KEYS = require("./syntax-keys");
var traverse = require("../traversal");
var visitors = traverse.explode(require("./visitors"));
function detect(ast) {
var stats = {
syntax: {},
builtins: {}
};
var detectedSyntax = function (name) {
stats.syntax[name] = true;
};
traverse(ast, {
enter(node, parent) {
if (SYNTAX_KEYS[node.type]) {
detectedSyntax(SYNTAX_KEYS[node.type]);
}
var visitor = visitors[node.type];
if (visitor) visitor(node, parent, detectedSyntax);
}
});
return stats;
}

View File

@@ -1,84 +0,0 @@
{
"ArrowFunctionExpression": "es6.arrowFunctions",
"AwaitExpression": "es7.asyncFunctions",
"ClassBody": "es6.classes",
"ClassDeclaration": "es6.classes",
"ClassExpression": "es6.classes",
"MethodDefinition": "es6.classes",
"ComprehensionBlock": "es7.comprehensions",
"ComprehensionExpression": "es7.comprehensions",
"ForOfStatement": "es6.forOf",
"ExportBatchSpecifier": "es6.modules",
"ExportDeclaration": "es6.modules",
"ExportSpecifier": "es6.modules",
"ImportBatchSpecifier": "es6.modules",
"ImportDeclaration": "es6.modules",
"ImportSpecifier": "es6.modules",
"ArrayPattern": "es6.destructuring",
"AssignmentPattern": "es6.destructuring",
"ObjectPattern": "es6.destructuring",
"RestElement": "es6.parameters.rest",
"SpreadElement": "es6.spread",
"SpreadProperty": "es7.objectSpread",
"TaggedTemplateExpression": "es6.templateLiterals",
"TemplateElement": "es6.templateLiterals",
"TemplateLiteral": "es6.templateLiterals",
"VirtualPropertyExpression": "es7.abstractReferences",
"PrivateDeclaration": "es7.abstractReferences",
"YieldExpression": "es6.generators",
"AnyTypeAnnotation": "flow",
"ArrayTypeAnnotation": "flow",
"BooleanTypeAnnotation": "flow",
"ClassProperty": "flow",
"DeclareClass": "flow",
"DeclareFunction": "flow",
"DeclareModule": "flow",
"DeclareVariable": "flow",
"FunctionTypeAnnotation": "flow",
"FunctionTypeParam": "flow",
"GenericTypeAnnotation": "flow",
"InterfaceExtends": "flow",
"InterfaceDeclaration": "flow",
"IntersectionTypeAnnotation": "flow",
"NullableTypeAnnotation": "flow",
"NumberTypeAnnotation": "flow",
"StringLiteralTypeAnnotation": "flow",
"StringTypeAnnotation": "flow",
"TupleTypeAnnotation": "flow",
"TypeofTypeAnnotation": "flow",
"TypeAlias": "flow",
"TypeAnnotation": "flow",
"TypeParameterDeclaration": "flow",
"TypeParameterInstantiation": "flow",
"ObjectTypeAnnotation": "flow",
"ObjectTypeCallProperty": "flow",
"ObjectTypeIndexer": "flow",
"ObjectTypeProperty": "flow",
"QualifiedTypeIdentifier": "flow",
"UnionTypeAnnotation": "flow",
"VoidTypeAnnotation": "flow",
"JSXAttribute": "jsx",
"JSXClosingElement": "jsx",
"JSXElement": "jsx",
"JSXEmptyExpression": "jsx",
"JSXExpressionContainer": "jsx",
"JSXIdentifier": "jsx",
"JSXMemberExpression": "jsx",
"JSXNamespacedName": "jsx",
"JSXOpeningElement": "jsx",
"JSXSpreadAttribute": "jsx"
}

View File

@@ -1,54 +0,0 @@
var t = require("../types");
var includes = require("lodash/collection/includes");
exports.AssignmentExpression = function (node, parent, detected) {
if (node.operator === "**=") {
detected("es6.exponentation");
}
};
exports.BinaryExpression = function (node, parent, detected) {
if (node.operator === "**") {
detected("es6.exponentation");
}
};
exports.VariableDeclaration = function (node, parent, detected) {
if (node.kind === "let" || node.kind === "const") {
detected("es6.blockScoping");
}
if (node.kind === "const") {
detected("es6.constants");
}
};
exports.Property = function (node, parent, detected) {
if (node.shorthand || node.method) {
detected("es6.properties.shorthand");
}
if (node.kind === "set" || node.kind === "get") {
detected("es5.properties.mutators");
}
if (node.computed) {
detected("es6.properties.computed");
}
};
exports.AssignmentPattern = function (node, parent, detected) {
if (t.isFunction(parent) && includes(parent.params, node)) {
detected("es6.parameters.default");
}
};
exports.Function = function (node, parent, detected) {
if (node.generator) {
detected("es6.generators");
}
if (node.async) {
detected("es7.asyncFunctions");
}
};

View File

@@ -1,173 +1,173 @@
module.exports = Buffer;
import repeating from "repeating";
import trimRight from "trim-right";
import isBoolean from "lodash/lang/isBoolean";
import includes from "lodash/collection/includes";
import isNumber from "lodash/lang/isNumber";
var repeating = require("repeating");
var trimRight = require("trim-right");
var isBoolean = require("lodash/lang/isBoolean");
var includes = require("lodash/collection/includes");
var isNumber = require("lodash/lang/isNumber");
function Buffer(position, format) {
this.position = position;
this._indent = format.indent.base;
this.format = format;
this.buf = "";
}
Buffer.prototype.get = function () {
return trimRight(this.buf);
};
Buffer.prototype.getIndent = function () {
if (this.format.compact || this.format.concise) {
return "";
} else {
return repeating(this.format.indent.style, this._indent);
export default class Buffer {
constructor(position, format) {
this.position = position;
this._indent = format.indent.base;
this.format = format;
this.buf = "";
}
};
Buffer.prototype.indentSize = function () {
return this.getIndent().length;
};
Buffer.prototype.indent = function () {
this._indent++;
};
Buffer.prototype.dedent = function () {
this._indent--;
};
Buffer.prototype.semicolon = function () {
this.push(";");
};
Buffer.prototype.ensureSemicolon = function () {
if (!this.isLast(";")) this.semicolon();
};
Buffer.prototype.rightBrace = function () {
this.newline(true);
this.push("}");
};
Buffer.prototype.keyword = function (name) {
this.push(name);
this.space();
};
Buffer.prototype.space = function () {
if (this.format.compact) return;
if (this.buf && !this.isLast(" ") && !this.isLast("\n")) {
this.push(" ");
get() {
return trimRight(this.buf);
}
};
Buffer.prototype.removeLast = function (cha) {
if (this.format.compact) return;
if (!this.isLast(cha)) return;
getIndent() {
if (this.format.compact || this.format.concise) {
return "";
} else {
return repeating(this.format.indent.style, this._indent);
}
}
this.buf = this.buf.substr(0, this.buf.length - 1);
this.position.unshift(cha);
};
indentSize() {
return this.getIndent().length;
}
Buffer.prototype.newline = function (i, removeLast) {
if (this.format.compact) return;
indent() {
this._indent++;
}
if (this.format.concise) {
dedent() {
this._indent--;
}
semicolon() {
this.push(";");
}
ensureSemicolon() {
if (!this.isLast(";")) this.semicolon();
}
rightBrace() {
this.newline(true);
this.push("}");
}
keyword(name) {
this.push(name);
this.space();
return;
}
removeLast ||= false;
if (isNumber(i)) {
i = Math.min(2, i);
if (this.endsWith("{\n") || this.endsWith(":\n")) i--;
if (i <= 0) return;
while (i > 0) {
this._newline(removeLast);
i--;
space() {
if (this.format.compact) return;
if (this.buf && !this.isLast(" ") && !this.isLast("\n")) {
this.push(" ");
}
return;
}
if (isBoolean(i)) {
removeLast = i;
removeLast(cha) {
if (this.format.compact) return;
if (!this.isLast(cha)) return;
this.buf = this.buf.substr(0, this.buf.length - 1);
this.position.unshift(cha);
}
this._newline(removeLast);
};
newline(i, removeLast) {
if (this.format.compact || this.format.retainLines) return;
Buffer.prototype._newline = function (removeLast) {
// never allow more than two lines
if (this.endsWith("\n\n")) return;
// remove the last newline
if (removeLast && this.isLast("\n")) this.removeLast("\n");
this.removeLast(" ");
this._removeSpacesAfterLastNewline();
this._push("\n");
};
/**
* If buffer ends with a newline and some spaces after it, trim those spaces.
*/
Buffer.prototype._removeSpacesAfterLastNewline = function () {
var lastNewlineIndex = this.buf.lastIndexOf("\n");
if (lastNewlineIndex === -1)
return;
var index = this.buf.length - 1;
while (index > lastNewlineIndex) {
if (this.buf[index] !== " ") {
break;
if (this.format.concise) {
this.space();
return;
}
index--;
removeLast = removeLast || false;
if (isNumber(i)) {
i = Math.min(2, i);
if (this.endsWith("{\n") || this.endsWith(":\n")) i--;
if (i <= 0) return;
while (i > 0) {
this._newline(removeLast);
i--;
}
return;
}
if (isBoolean(i)) {
removeLast = i;
}
this._newline(removeLast);
}
if (index === lastNewlineIndex) {
this.buf = this.buf.substring(0, index + 1);
}
};
_newline(removeLast) {
// never allow more than two lines
if (this.endsWith("\n\n")) return;
Buffer.prototype.push = function (str, noIndent) {
if (!this.format.compact && this._indent && !noIndent && str !== "\n") {
// we have an indent level and we aren't pushing a newline
var indent = this.getIndent();
// remove the last newline
if (removeLast && this.isLast("\n")) this.removeLast("\n");
// replace all newlines with newlines with the indentation
str = str.replace(/\n/g, "\n" + indent);
// we've got a newline before us so prepend on the indentation
if (this.isLast("\n")) this._push(indent);
this.removeLast(" ");
this._removeSpacesAfterLastNewline();
this._push("\n");
}
this._push(str);
};
/**
* If buffer ends with a newline and some spaces after it, trim those spaces.
*/
Buffer.prototype._push = function (str) {
this.position.push(str);
this.buf += str;
};
_removeSpacesAfterLastNewline() {
var lastNewlineIndex = this.buf.lastIndexOf("\n");
if (lastNewlineIndex === -1)
return;
Buffer.prototype.endsWith = function (str) {
return this.buf.slice(-str.length) === str;
};
var index = this.buf.length - 1;
while (index > lastNewlineIndex) {
if (this.buf[index] !== " ") {
break;
}
Buffer.prototype.isLast = function (cha) {
if (this.format.compact) return false;
index--;
}
var buf = this.buf;
var last = buf[buf.length - 1];
if (Array.isArray(cha)) {
return includes(cha, last);
} else {
return cha === last;
if (index === lastNewlineIndex) {
this.buf = this.buf.substring(0, index + 1);
}
}
};
push(str, noIndent) {
if (!this.format.compact && this._indent && !noIndent && str !== "\n") {
// we have an indent level and we aren't pushing a newline
var indent = this.getIndent();
// replace all newlines with newlines with the indentation
str = str.replace(/\n/g, `\n${indent}`);
// we've got a newline before us so prepend on the indentation
if (this.isLast("\n")) this._push(indent);
}
this._push(str);
}
_push(str) {
this.position.push(str);
this.buf += str;
}
endsWith(str) {
return this.buf.slice(-str.length) === str;
}
isLast(cha) {
if (this.format.compact) return false;
var buf = this.buf;
var last = buf[buf.length - 1];
if (Array.isArray(cha)) {
return includes(cha, last);
} else {
return cha === last;
}
}
}

View File

@@ -1,19 +1,19 @@
exports.File = function (node, print) {
export function File(node, print) {
print(node.program);
};
}
exports.Program = function (node, print) {
export function Program(node, print) {
print.sequence(node.body);
};
}
exports.BlockStatement = function (node, print) {
export function BlockStatement(node, print) {
if (node.body.length === 0) {
this.push("{}");
} else {
this.push("{");
this.newline();
print.sequence(node.body, { indent: true });
this.removeLast("\n");
if (!this.format.retainLines) this.removeLast("\n");
this.rightBrace();
}
};
}

View File

@@ -1,5 +1,5 @@
exports.ClassExpression =
exports.ClassDeclaration = function (node, print) {
export function ClassDeclaration(node, print) {
print.list(node.decorators);
this.push("class");
if (node.id) {
@@ -7,16 +7,26 @@ exports.ClassDeclaration = function (node, print) {
print(node.id);
}
print(node.typeParameters);
if (node.superClass) {
this.push(" extends ");
print(node.superClass);
print(node.superTypeParameters);
}
if (node.implements) {
this.push(" implements ");
print.join(node.implements, { separator: ", " });
}
this.space();
print(node.body);
};
}
exports.ClassBody = function (node, print) {
export { ClassDeclaration as ClassExpression };
export function ClassBody(node, print) {
if (node.body.length === 0) {
this.push("{}");
} else {
@@ -29,12 +39,30 @@ exports.ClassBody = function (node, print) {
this.rightBrace();
}
};
}
export function ClassProperty(node, print) {
print.list(node.decorators);
if (node.static) this.push("static ");
print(node.key);
print(node.typeAnnotation);
if (node.value) {
this.space();
this.push("=");
this.space();
print(node.value);
}
this.semicolon();
}
export function MethodDefinition(node, print) {
print.list(node.decorators);
exports.MethodDefinition = function (node, print) {
if (node.static) {
this.push("static ");
}
this._method(node, print);
};
}

View File

@@ -1,13 +1,13 @@
exports.ComprehensionBlock = function (node, print) {
export function ComprehensionBlock(node, print) {
this.keyword("for");
this.push("(");
print(node.left);
this.push(" of ");
print(node.right);
this.push(")");
};
}
exports.ComprehensionExpression = function (node, print) {
export function ComprehensionExpression(node, print) {
this.push(node.generator ? "(" : "[");
print.join(node.blocks, { separator: " " });
@@ -24,4 +24,4 @@ exports.ComprehensionExpression = function (node, print) {
print(node.body);
this.push(node.generator ? ")" : "]");
};
}

View File

@@ -1,8 +1,8 @@
var isInteger = require("is-integer");
var isNumber = require("lodash/lang/isNumber");
var t = require("../../types");
import isInteger from "is-integer";
import isNumber from "lodash/lang/isNumber";
import * as t from "../../types";
exports.UnaryExpression = function (node, print) {
export function UnaryExpression(node, print) {
var hasSpace = /[a-z]$/.test(node.operator);
var arg = node.argument;
@@ -17,9 +17,15 @@ exports.UnaryExpression = function (node, print) {
this.push(node.operator);
if (hasSpace) this.push(" ");
print(node.argument);
};
}
exports.UpdateExpression = function (node, print) {
export function DoExpression(node, print) {
this.push("do");
this.space();
print(node.body);
}
export function UpdateExpression(node, print) {
if (node.prefix) {
this.push(node.operator);
print(node.argument);
@@ -27,9 +33,9 @@ exports.UpdateExpression = function (node, print) {
print(node.argument);
this.push(node.operator);
}
};
}
exports.ConditionalExpression = function (node, print) {
export function ConditionalExpression(node, print) {
print(node.test);
this.space();
this.push("?");
@@ -39,25 +45,34 @@ exports.ConditionalExpression = function (node, print) {
this.push(":");
this.space();
print(node.alternate);
};
}
exports.NewExpression = function (node, print) {
export function NewExpression(node, print) {
this.push("new ");
print(node.callee);
this.push("(");
print.list(node.arguments);
this.push(")");
};
}
exports.SequenceExpression = function (node, print) {
export function SequenceExpression(node, print) {
print.list(node.expressions);
};
}
exports.ThisExpression = function () {
export function ThisExpression() {
this.push("this");
};
}
exports.CallExpression = function (node, print) {
export function Super() {
this.push("super");
}
export function Decorator(node, print) {
this.push("@");
print(node.expression);
}
export function CallExpression(node, print) {
print(node.callee);
this.push("(");
@@ -80,7 +95,7 @@ exports.CallExpression = function (node, print) {
}
this.push(")");
};
}
var buildYieldAwait = function (keyword) {
return function (node, print) {
@@ -97,33 +112,42 @@ var buildYieldAwait = function (keyword) {
};
};
exports.YieldExpression = buildYieldAwait("yield");
exports.AwaitExpression = buildYieldAwait("await");
export var YieldExpression = buildYieldAwait("yield");
export var AwaitExpression = buildYieldAwait("await");
exports.EmptyStatement = function () {
export function EmptyStatement() {
this.semicolon();
};
}
exports.ExpressionStatement = function (node, print) {
export function ExpressionStatement(node, print) {
print(node.expression);
this.semicolon();
};
}
exports.BinaryExpression =
exports.LogicalExpression =
exports.AssignmentPattern =
exports.AssignmentExpression = function (node, print) {
export function AssignmentExpression(node, print) {
// todo: add cases where the spaces can be dropped when in compact mode
print(node.left);
this.push(" ");
this.push(node.operator);
this.push(" ");
print(node.right);
}
export function BindExpression(node, print) {
print(node.object);
this.push("::");
print(node.callee);
}
export {
AssignmentExpression as BinaryExpression,
AssignmentExpression as LogicalExpression,
AssignmentExpression as AssignmentPattern
};
var SCIENTIFIC_NOTATION = /e/i;
exports.MemberExpression = function (node, print) {
export function MemberExpression(node, print) {
var obj = node.object;
print(obj);
@@ -149,4 +173,10 @@ exports.MemberExpression = function (node, print) {
this.push(".");
print(node.property);
}
};
}
export function MetaProperty(node, print) {
print(node.meta);
this.push(".");
print(node.property);
}

View File

@@ -1,34 +1,232 @@
exports.AnyTypeAnnotation =
exports.ArrayTypeAnnotation =
exports.BooleanTypeAnnotation =
exports.ClassProperty =
exports.DeclareClass =
exports.DeclareFunction =
exports.DeclareModule =
exports.DeclareVariable =
exports.FunctionTypeAnnotation =
exports.FunctionTypeParam =
exports.GenericTypeAnnotation =
exports.InterfaceExtends =
exports.InterfaceDeclaration =
exports.IntersectionTypeAnnotation =
exports.NullableTypeAnnotation =
exports.NumberTypeAnnotation =
exports.StringLiteralTypeAnnotation =
exports.StringTypeAnnotation =
exports.TupleTypeAnnotation =
exports.TypeofTypeAnnotation =
exports.TypeAlias =
exports.TypeAnnotation =
exports.TypeParameterDeclaration =
exports.TypeParameterInstantiation =
exports.ObjectTypeAnnotation =
exports.ObjectTypeCallProperty =
exports.ObjectTypeIndexer =
exports.ObjectTypeProperty =
exports.QualifiedTypeIdentifier =
exports.UnionTypeAnnotation =
exports.TypeCastExpression =
exports.VoidTypeAnnotation = function () {
// todo: implement these once we have a `--keep-types` option
};
import * as t from "../../types";
export function AnyTypeAnnotation() {
this.push("any");
}
export function ArrayTypeAnnotation(node, print) {
print(node.elementType);
this.push("[");
this.push("]");
}
export function BooleanTypeAnnotation(node) {
this.push("bool");
}
export function DeclareClass(node, print) {
this.push("declare class ");
this._interfaceish(node, print);
}
export function DeclareFunction(node, print) {
this.push("declare function ");
print(node.id);
print(node.id.typeAnnotation.typeAnnotation);
this.semicolon();
}
export function DeclareModule(node, print) {
this.push("declare module ");
print(node.id);
this.space();
print(node.body);
}
export function DeclareVariable(node, print) {
this.push("declare var ");
print(node.id);
print(node.id.typeAnnotation);
this.semicolon();
}
export function FunctionTypeAnnotation(node, print, parent) {
print(node.typeParameters);
this.push("(");
print.list(node.params);
if (node.rest) {
if (node.params.length) {
this.push(",");
this.space();
}
this.push("...");
print(node.rest);
}
this.push(")");
// this node type is overloaded, not sure why but it makes it EXTREMELY annoying
if (parent.type === "ObjectTypeProperty" || parent.type === "ObjectTypeCallProperty" || parent.type === "DeclareFunction") {
this.push(":");
} else {
this.space();
this.push("=>");
}
this.space();
print(node.returnType);
}
export function FunctionTypeParam(node, print) {
print(node.name);
if (node.optional) this.push("?");
this.push(":");
this.space();
print(node.typeAnnotation);
}
export function InterfaceExtends(node, print) {
print(node.id);
print(node.typeParameters);
}
export { InterfaceExtends as ClassImplements, InterfaceExtends as GenericTypeAnnotation };
export function _interfaceish(node, print) {
print(node.id);
print(node.typeParameters);
if (node.extends.length) {
this.push(" extends ");
print.join(node.extends, { separator: ", " });
}
this.space();
print(node.body);
}
export function InterfaceDeclaration(node, print) {
this.push("interface ");
this._interfaceish(node, print);
}
export function IntersectionTypeAnnotation(node, print) {
print.join(node.types, { separator: " & " });
}
export function NullableTypeAnnotation(node, print) {
this.push("?");
print(node.typeAnnotation);
}
export function NumberTypeAnnotation() {
this.push("number");
}
export function StringLiteralTypeAnnotation(node) {
this._stringLiteral(node.value);
}
export function StringTypeAnnotation() {
this.push("string");
}
export function TupleTypeAnnotation(node, print) {
this.push("[");
print.join(node.types, { separator: ", " });
this.push("]");
}
export function TypeofTypeAnnotation(node, print) {
this.push("typeof ");
print(node.argument);
}
export function TypeAlias(node, print) {
this.push("type ");
print(node.id);
print(node.typeParameters);
this.space();
this.push("=");
this.space();
print(node.right);
this.semicolon();
}
export function TypeAnnotation(node, print) {
this.push(":");
this.space();
if (node.optional) this.push("?");
print(node.typeAnnotation);
}
export function TypeParameterInstantiation(node, print) {
this.push("<");
print.join(node.params, { separator: ", " });
this.push(">");
}
export { TypeParameterInstantiation as TypeParameterDeclaration };
export function ObjectTypeAnnotation(node, print) {
this.push("{");
var props = node.properties.concat(node.callProperties, node.indexers);
if (props.length) {
this.space();
print.list(props, {
separator: false,
indent: true,
iterator: () => {
if (props.length !== 1) {
this.semicolon();
this.space();
}
}
});
this.space();
}
this.push("}");
}
export function ObjectTypeCallProperty(node, print) {
if (node.static) this.push("static ");
print(node.value);
}
export function ObjectTypeIndexer(node, print) {
if (node.static) this.push("static ");
this.push("[");
print(node.id);
this.push(":");
this.space();
print(node.key);
this.push("]");
this.push(":");
this.space();
print(node.value);
}
export function ObjectTypeProperty(node, print) {
if (node.static) this.push("static ");
print(node.key);
if (node.optional) this.push("?");
if (!t.isFunctionTypeAnnotation(node.value)) {
this.push(":");
this.space();
}
print(node.value);
}
export function QualifiedTypeIdentifier(node, print) {
print(node.qualification);
this.push(".");
print(node.id);
}
export function UnionTypeAnnotation(node, print) {
print.join(node.types, { separator: " | " });
}
export function TypeCastExpression(node, print) {
this.push("(");
print(node.expression);
print(node.typeAnnotation);
this.push(")");
}
export function VoidTypeAnnotation(node) {
this.push("void");
}

View File

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

View File

@@ -1,21 +1,33 @@
var t = require("../../types");
import * as t from "../../types";
exports._params = function (node, print) {
export function _params(node, print) {
print(node.typeParameters);
this.push("(");
print.list(node.params);
print.list(node.params, {
iterator: (node) =>{
if (node.optional) this.push("?");
print(node.typeAnnotation);
}
});
this.push(")");
};
exports._method = function (node, print) {
if (node.returnType) {
print(node.returnType);
}
}
export function _method(node, print) {
var value = node.value;
var kind = node.kind;
var key = node.key;
if (!kind || kind === "init") {
if (kind === "method" || kind === "init") {
if (value.generator) {
this.push("*");
}
} else {
}
if (kind === "get" || kind === "set") {
this.push(kind + " ");
}
@@ -32,10 +44,9 @@ exports._method = function (node, print) {
this._params(value, print);
this.push(" ");
print(value.body);
};
}
exports.FunctionDeclaration =
exports.FunctionExpression = function (node, print) {
export function FunctionExpression(node, print) {
if (node.async) this.push("async ");
this.push("function");
if (node.generator) this.push("*");
@@ -50,9 +61,11 @@ exports.FunctionExpression = function (node, print) {
this._params(node, print);
this.space();
print(node.body);
};
}
exports.ArrowFunctionExpression = function (node, print) {
export { FunctionExpression as FunctionDeclaration };
export function ArrowFunctionExpression(node, print) {
if (node.async) this.push("async ");
if (node.params.length === 1 && t.isIdentifier(node.params[0])) {
@@ -62,5 +75,16 @@ exports.ArrowFunctionExpression = function (node, print) {
}
this.push(" => ");
const bodyNeedsParens = t.isObjectExpression(node.body);
if (bodyNeedsParens) {
this.push("(");
}
print(node.body);
};
if (bodyNeedsParens) {
this.push(")");
}
}

View File

@@ -1,42 +1,75 @@
var t = require("../../types");
var each = require("lodash/collection/each");
import each from "lodash/collection/each";
import * as t from "../../types";
exports.ImportSpecifier = function (node, print) {
if (t.isSpecifierDefault(node)) {
print(t.getSpecifierName(node));
} else {
return exports.ExportSpecifier.apply(this, arguments);
}
};
exports.ExportSpecifier = function (node, print) {
print(node.id);
if (node.name) {
export function ImportSpecifier(node, print) {
print(node.imported);
if (node.local && node.local.name !== node.imported.name) {
this.push(" as ");
print(node.name);
print(node.local);
}
};
}
exports.ExportBatchSpecifier = function () {
this.push("*");
};
export function ImportDefaultSpecifier(node, print) {
print(node.local);
}
exports.ExportDeclaration = function (node, print) {
export function ExportDefaultSpecifier(node, print) {
print(node.exported);
}
export function ExportSpecifier(node, print) {
print(node.local);
if (node.exported && node.local.name !== node.exported.name) {
this.push(" as ");
print(node.exported);
}
}
export function ExportNamespaceSpecifier(node, print) {
this.push("* as ");
print(node.exported);
}
export function ExportAllDeclaration(node, print) {
this.push("export *");
if (node.exported) {
this.push(" as ");
print(node.exported);
}
this.push(" from ");
print(node.source);
this.semicolon();
}
export function ExportNamedDeclaration(node, print) {
this.push("export ");
ExportDeclaration.call(this, node, print);
}
export function ExportDefaultDeclaration(node, print) {
this.push("export default ");
ExportDeclaration.call(this, node, print);
}
function ExportDeclaration(node, print) {
var specifiers = node.specifiers;
if (node.default) {
this.push("default ");
}
if (node.declaration) {
print(node.declaration);
if (t.isStatement(node.declaration)) return;
var declar = node.declaration;
print(declar);
if (t.isStatement(declar) || t.isFunction(declar) || t.isClass(declar)) return;
} else {
if (specifiers.length === 1 && t.isExportBatchSpecifier(specifiers[0])) {
print(specifiers[0]);
} else {
var first = specifiers[0];
var hasSpecial = false;
if (t.isExportDefaultSpecifier(first) || t.isExportNamespaceSpecifier(first)) {
hasSpecial = true;
print(specifiers.shift());
if (specifiers.length) {
this.push(", ");
}
}
if (specifiers.length || (!specifiers.length && !hasSpecial)) {
this.push("{");
if (specifiers.length) {
this.space();
@@ -53,9 +86,9 @@ exports.ExportDeclaration = function (node, print) {
}
this.ensureSemicolon();
};
}
exports.ImportDeclaration = function (node, print) {
export function ImportDeclaration(node, print) {
this.push("import ");
if (node.isType) {
@@ -64,25 +97,20 @@ exports.ImportDeclaration = function (node, print) {
var specfiers = node.specifiers;
if (specfiers && specfiers.length) {
var foundImportSpecifier = false;
each(node.specifiers, (spec, i) => {
if (+i > 0) {
var first = node.specifiers[0];
if (t.isImportDefaultSpecifier(first) || t.isImportNamespaceSpecifier(first)) {
print(node.specifiers.shift());
if (node.specifiers.length) {
this.push(", ");
}
}
var isDefault = t.isSpecifierDefault(spec);
if (!isDefault && spec.type !== "ImportBatchSpecifier" && !foundImportSpecifier) {
foundImportSpecifier = true;
this.push("{ ");
}
print(spec);
});
if (foundImportSpecifier) {
this.push(" }");
if (node.specifiers.length) {
this.push("{");
this.space()
print.join(node.specifiers, { separator: ", " });
this.space()
this.push("}");
}
this.push(" from ");
@@ -90,9 +118,9 @@ exports.ImportDeclaration = function (node, print) {
print(node.source);
this.semicolon();
};
}
exports.ImportBatchSpecifier = function (node, print) {
export function ImportNamespaceSpecifier(node, print) {
this.push("* as ");
print(node.name);
};
print(node.local);
}

View File

@@ -1,7 +0,0 @@
var each = require("lodash/collection/each");
each(["BindMemberExpression", "BindFunctionExpression"], function (type) {
exports[type] = function () {
throw new ReferenceError("Trying to render non-standard playground node " + JSON.stringify(type));
};
});

View File

@@ -1,15 +1,15 @@
var repeating = require("repeating");
var t = require("../../types");
import repeating from "repeating";
import * as t from "../../types";
exports.WithStatement = function (node, print) {
export function WithStatement(node, print) {
this.keyword("with");
this.push("(");
print(node.object);
this.push(")");
print.block(node.body);
};
}
exports.IfStatement = function (node, print) {
export function IfStatement(node, print) {
this.keyword("if");
this.push("(");
print(node.test);
@@ -23,9 +23,9 @@ exports.IfStatement = function (node, print) {
this.push("else ");
print.indentOnComments(node.alternate);
}
};
}
exports.ForStatement = function (node, print) {
export function ForStatement(node, print) {
this.keyword("for");
this.push("(");
@@ -45,40 +45,40 @@ exports.ForStatement = function (node, print) {
this.push(")");
print.block(node.body);
};
}
exports.WhileStatement = function (node, print) {
export function WhileStatement(node, print) {
this.keyword("while");
this.push("(");
print(node.test);
this.push(")");
print.block(node.body);
};
}
var buildForXStatement = function (op) {
return function (node, print) {
this.keyword("for");
this.push("(");
print(node.left);
this.push(" " + op + " ");
this.push(` ${op} `);
print(node.right);
this.push(")");
print.block(node.body);
};
};
exports.ForInStatement = buildForXStatement("in");
exports.ForOfStatement = buildForXStatement("of");
export var ForInStatement = buildForXStatement("in");
export var ForOfStatement = buildForXStatement("of");
exports.DoWhileStatement = function (node, print) {
this.keyword("do");
export function DoWhileStatement(node, print) {
this.push("do ");
print(node.body);
this.space();
this.keyword("while");
this.push("(");
print(node.test);
this.push(");");
};
}
var buildLabelStatement = function (prefix, key) {
return function (node, print) {
@@ -94,17 +94,17 @@ var buildLabelStatement = function (prefix, key) {
};
};
exports.ContinueStatement = buildLabelStatement("continue");
exports.ReturnStatement = buildLabelStatement("return", "argument");
exports.BreakStatement = buildLabelStatement("break");
export var ContinueStatement = buildLabelStatement("continue");
export var ReturnStatement = buildLabelStatement("return", "argument");
export var BreakStatement = buildLabelStatement("break");
exports.LabeledStatement = function (node, print) {
export function LabeledStatement(node, print) {
print(node.label);
this.push(": ");
print(node.body);
};
}
exports.TryStatement = function (node, print) {
export function TryStatement(node, print) {
this.keyword("try");
print(node.block);
this.space();
@@ -123,23 +123,23 @@ exports.TryStatement = function (node, print) {
this.push("finally ");
print(node.finalizer);
}
};
}
exports.CatchClause = function (node, print) {
export function CatchClause(node, print) {
this.keyword("catch");
this.push("(");
print(node.param);
this.push(") ");
print(node.body);
};
}
exports.ThrowStatement = function (node, print) {
export function ThrowStatement(node, print) {
this.push("throw ");
print(node.argument);
this.semicolon();
};
}
exports.SwitchStatement = function (node, print) {
export function SwitchStatement(node, print) {
this.keyword("switch");
this.push("(");
print(node.discriminant);
@@ -155,9 +155,9 @@ exports.SwitchStatement = function (node, print) {
});
this.push("}");
};
}
exports.SwitchCase = function (node, print) {
export function SwitchCase(node, print) {
if (node.test) {
this.push("case ");
print(node.test);
@@ -170,20 +170,20 @@ exports.SwitchCase = function (node, print) {
this.newline();
print.sequence(node.consequent, { indent: true });
}
};
}
exports.DebuggerStatement = function () {
export function DebuggerStatement() {
this.push("debugger;");
};
}
exports.VariableDeclaration = function (node, print, parent) {
export function VariableDeclaration(node, print, parent) {
this.push(node.kind + " ");
var hasInits = false;
// don't add whitespace to loop heads
if (!t.isFor(parent)) {
for (var i = 0; i < node.declarations.length; i++) {
if (node.declarations[i].init) {
for (var declar of (node.declarations: Array)) {
if (declar.init) {
// has an init so let's split it up over multiple lines
hasInits = true;
}
@@ -191,33 +191,28 @@ exports.VariableDeclaration = function (node, print, parent) {
}
var sep = ",";
if (!this.format.compact && hasInits) {
sep += "\n" + repeating(" ", node.kind.length + 1);
if (!this.format.compact && !this.format.concise && hasInits && !this.format.retainLines) {
sep += `\n${repeating(" ", node.kind.length + 1)}`;
} else {
sep += " ";
}
print.list(node.declarations, { separator: sep });
if (!t.isFor(parent)) {
this.semicolon();
if (t.isFor(parent)) {
if (parent.left === node || parent.init === node) return;
}
};
exports.PrivateDeclaration = function (node, print) {
this.push("private ");
print.join(node.declarations, { separator: ", " });
this.semicolon();
};
}
exports.VariableDeclarator = function (node, print) {
export function VariableDeclarator(node, print) {
print(node.id);
print(node.id.typeAnnotation);
if (node.init) {
print(node.id);
this.space();
this.push("=");
this.space();
print(node.init);
} else {
print(node.id);
}
};
}

View File

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

View File

@@ -1,24 +1,18 @@
var each = require("lodash/collection/each");
import each from "lodash/collection/each";
import * as t from "../../types";
exports.Identifier = function (node) {
export function Identifier(node) {
this.push(node.name);
};
}
exports.RestElement =
exports.SpreadElement =
exports.SpreadProperty = function (node, print) {
export function RestElement(node, print) {
this.push("...");
print(node.argument);
};
}
exports.VirtualPropertyExpression = function (node, print) {
print(node.object);
this.push("::");
print(node.property);
};
export { RestElement as SpreadElement, RestElement as SpreadProperty };
exports.ObjectExpression =
exports.ObjectPattern = function (node, print) {
export function ObjectExpression(node, print) {
var props = node.properties;
if (props.length) {
@@ -32,9 +26,11 @@ exports.ObjectPattern = function (node, print) {
} else {
this.push("{}");
}
};
}
exports.Property = function (node, print) {
export { ObjectExpression as ObjectPattern };
export function Property(node, print) {
if (node.method || node.kind === "get" || node.kind === "set") {
this._method(node, print);
} else {
@@ -44,23 +40,30 @@ exports.Property = function (node, print) {
this.push("]");
} else {
print(node.key);
if (node.shorthand) return;
// shorthand!
if (node.shorthand &&
(t.isIdentifier(node.key) &&
t.isIdentifier(node.value) &&
node.key.name === node.value.name)) {
return;
}
}
this.push(":");
this.space();
print(node.value);
}
};
}
exports.ArrayExpression =
exports.ArrayPattern = function (node, print) {
export function ArrayExpression(node, print) {
var elems = node.elements;
var len = elems.length;
this.push("[");
each(elems, (elem, i) => {
for (var i = 0; i < elems.length; i++) {
var elem = elems[i];
if (!elem) {
// If the array expression ends with a hole, that hole
// will be ignored by the interpreter, but if it ends with
@@ -73,31 +76,44 @@ exports.ArrayPattern = function (node, print) {
print(elem);
if (i < len - 1) this.push(",");
}
});
}
this.push("]");
};
}
exports.Literal = function (node) {
export { ArrayExpression as ArrayPattern };
export function Literal(node) {
var val = node.value;
var type = typeof val;
if (type === "string") {
val = JSON.stringify(val);
// escape illegal js but valid json unicode characters
val = val.replace(/[\u000A\u000D\u2028\u2029]/g, function (c) {
return "\\u" + ("0000" + c.charCodeAt(0).toString(16)).slice(-4);
});
this.push(val);
this._stringLiteral(val);
} else if (type === "number") {
this.push(val + "");
} else if (type === "boolean") {
this.push(val ? "true" : "false");
} else if (node.regex) {
this.push("/" + node.regex.pattern + "/" + node.regex.flags);
this.push(`/${node.regex.pattern}/${node.regex.flags}`);
} else if (val === null) {
this.push("null");
}
};
}
export function _stringLiteral(val) {
val = JSON.stringify(val);
// escape illegal js but valid json unicode characters
val = val.replace(/[\u000A\u000D\u2028\u2029]/g, function (c) {
return "\\u" + ("0000" + c.charCodeAt(0).toString(16)).slice(-4);
});
if (this.format.quotes === "single") {
val = val.slice(1, -1);
val = val.replace(/\\"/g, '"');
val = val.replace(/'/g, "\\'");
val = `'${val}'`;
}
this.push(val);
}

View File

@@ -1,35 +1,399 @@
module.exports = function (ast, opts, code) {
var gen = new CodeGenerator(ast, opts, code);
return gen.generate();
};
import detectIndent from "detect-indent";
import Whitespace from "./whitespace";
import repeating from "repeating";
import SourceMap from "./source-map";
import Position from "./position";
import * as messages from "../messages";
import Buffer from "./buffer";
import extend from "lodash/object/extend";
import each from "lodash/collection/each";
import n from "./node";
import * as t from "../types";
module.exports.CodeGenerator = CodeGenerator;
class CodeGenerator {
constructor(ast, opts, code) {
opts = opts || {};
var detectIndent = require("detect-indent");
var Whitespace = require("./whitespace");
var repeating = require("repeating");
var SourceMap = require("./source-map");
var Position = require("./position");
var messages = require("../messages");
var Buffer = require("./buffer");
var extend = require("lodash/object/extend");
var each = require("lodash/collection/each");
var n = require("./node");
var t = require("../types");
this.comments = ast.comments || [];
this.tokens = ast.tokens || [];
this.format = CodeGenerator.normalizeOptions(code, opts, this.tokens);
this.opts = opts;
this.ast = ast;
function CodeGenerator(ast, opts, code) {
opts ||= {};
this.whitespace = new Whitespace(this.tokens, this.comments, this.format);
this.position = new Position;
this.map = new SourceMap(this.position, opts, code);
this.buffer = new Buffer(this.position, this.format);
}
this.comments = ast.comments || [];
this.tokens = ast.tokens || [];
this.format = CodeGenerator.normalizeOptions(code, opts);
this.opts = opts;
this.ast = ast;
static normalizeOptions(code, opts, tokens) {
var style = " ";
if (code) {
var indent = detectIndent(code).indent;
if (indent && indent !== " ") style = indent;
}
this.whitespace = new Whitespace(this.tokens, this.comments, this.format);
this.position = new Position;
this.map = new SourceMap(this.position, opts, code);
this.buffer = new Buffer(this.position, this.format);
var format = {
retainLines: opts.retainLines,
comments: opts.comments == null || opts.comments,
compact: opts.compact,
quotes: CodeGenerator.findCommonStringDelimiter(code, tokens),
indent: {
adjustMultilineComment: true,
style: style,
base: 0
}
};
if (format.compact === "auto") {
format.compact = code.length > 100000; // 100KB
if (format.compact) {
console.error("[BABEL] " + messages.get("codeGeneratorDeopt", opts.filename, "100KB"));
}
}
return format;
}
static findCommonStringDelimiter(code, tokens) {
var occurences = {
single: 0,
double: 0
};
var checked = 0;
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (token.type.label !== "string") continue;
if (checked >= 3) continue;
var raw = code.slice(token.start, token.end);
if (raw[0] === "'") {
occurences.single++;
} else {
occurences.double++;
}
checked++;
}
if (occurences.single > occurences.double) {
return "single";
} else {
return "double";
}
}
static generators = {
templateLiterals: require("./generators/template-literals"),
comprehensions: require("./generators/comprehensions"),
expressions: require("./generators/expressions"),
statements: require("./generators/statements"),
classes: require("./generators/classes"),
methods: require("./generators/methods"),
modules: require("./generators/modules"),
types: require("./generators/types"),
flow: require("./generators/flow"),
base: require("./generators/base"),
jsx: require("./generators/jsx")
};
generate() {
var ast = this.ast;
this.print(ast);
if (ast.comments) {
var comments = [];
for (var comment of (ast.comments: Array)) {
if (!comment._displayed) comments.push(comment);
}
this._printComments(comments);
}
return {
map: this.map.get(),
code: this.buffer.get()
};
}
buildPrint(parent) {
var print = (node, opts) => {
return this.print(node, parent, opts);
};
print.sequence = (nodes, opts = {}) => {
opts.statement = true;
return this.printJoin(print, nodes, opts);
};
print.join = (nodes, opts) => {
return this.printJoin(print, nodes, opts);
};
print.list = function (items, opts = {}) {
if (opts.separator == null) opts.separator = ", ";
print.join(items, opts);
};
print.block = (node) => {
return this.printBlock(print, node);
};
print.indentOnComments = (node) => {
return this.printAndIndentOnComments(print, node);
};
return print;
}
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;
if (parent && parent._compact) {
node._compact = true;
}
var oldConcise = this.format.concise;
if (node._compact) {
this.format.concise = true;
}
var newline = (leading) => {
if (!opts.statement && !n.isUserWhitespacable(node, parent)) {
return;
}
var lines = 0;
if (node.start != null && !node._ignoreUserWhitespace) {
// user node
if (leading) {
lines = this.whitespace.getNewlinesBefore(node);
} else {
lines = this.whitespace.getNewlinesAfter(node);
}
} else {
// generated node
if (!leading) lines++; // always include at least a single line after
if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0;
var needs = n.needsWhitespaceAfter;
if (leading) needs = n.needsWhitespaceBefore;
if (needs(node, parent)) lines++;
// generated nodes can't add starting file whitespace
if (!this.buffer.buf) lines = 0;
}
this.newline(lines);
};
if (this[node.type]) {
var needsNoLineTermParens = n.needsParensNoLineTerminator(node, parent);
var needsParens = needsNoLineTermParens || n.needsParens(node, parent);
if (needsParens) this.push("(");
if (needsNoLineTermParens) this.indent();
this.printLeadingComments(node, parent);
var needsParensFromCatchup = this.catchUp(node, parent);
newline(true);
if (opts.before) opts.before();
this.map.mark(node, "start");
this[node.type](node, this.buildPrint(node), parent);
if (needsNoLineTermParens) {
this.newline();
this.dedent();
}
if (needsParens || 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)}`);
}
}
printJoin(print, nodes, opts = {}) {
if (!nodes || !nodes.length) return;
var len = nodes.length;
if (opts.indent) this.indent();
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
print(node, {
statement: opts.statement,
addNewlines: opts.addNewlines,
after: () => {
if (opts.iterator) {
opts.iterator(node, i);
}
if (opts.separator && i < len - 1) {
this.push(opts.separator);
}
}
});
}
if (opts.indent) this.dedent();
}
printAndIndentOnComments(print, node) {
var indent = !!node.leadingComments;
if (indent) this.indent();
print(node);
if (indent) this.dedent();
}
printBlock(print, node) {
if (t.isEmptyStatement(node)) {
this.semicolon();
} else {
this.push(" ");
print(node);
}
}
generateComment(comment) {
var val = comment.value;
if (comment.type === "Line") {
val = `//${val}`;
} else {
val = `/*${val}*/`;
}
return val;
}
printTrailingComments(node, parent) {
this._printComments(this.getComments("trailingComments", node, parent));
}
printLeadingComments(node, parent) {
this._printComments(this.getComments("leadingComments", node, parent));
}
getComments(key, node, parent) {
if (t.isExpressionStatement(parent)) {
return [];
}
var comments = [];
var nodes = [node];
if (t.isExpressionStatement(node)) {
nodes.push(node.argument);
}
for (var node of (nodes: Array)) {
comments = comments.concat(this._getComments(key, node));
}
return comments;
}
_getComments(key, node) {
return (node && node[key]) || [];
}
_printComments(comments) {
if (this.format.compact) return;
if (!this.format.comments) return;
if (!comments || !comments.length) return;
for (var comment of (comments: Array)) {
var skip = false;
if (this.ast.comments) {
// find the original comment in the ast and set it as displayed
for (var origComment of (this.ast.comments: Array)) {
if (origComment.start === comment.start) {
// comment has already been output
if (origComment._displayed) skip = true;
origComment._displayed = true;
break;
}
}
}
if (skip) return;
this.catchUp(comment);
// whitespace before
this.newline(this.whitespace.getNewlinesBefore(comment));
var column = this.position.column;
var val = this.generateComment(comment);
if (column && !this.isLast(["\n", " ", "[", "{"])) {
this._push(" ");
column++;
}
//
if (comment.type === "Block" && this.format.indent.adjustMultilineComment) {
var offset = comment.loc.start.column;
if (offset) {
var newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g");
val = val.replace(newlineRegex, "\n");
}
var indent = Math.max(this.indentSize(), column);
val = val.replace(/\n/g, `\n${repeating(" ", indent)}`);
}
if (column === 0) {
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
this.newline(this.whitespace.getNewlinesAfter(comment));
}
}
}
each(Buffer.prototype, function (fn, key) {
@@ -38,321 +402,13 @@ each(Buffer.prototype, function (fn, key) {
};
});
CodeGenerator.normalizeOptions = function (code, opts) {
var style = " ";
if (code) {
var indent = detectIndent(code).indent;
if (indent && indent !== " ") style = indent;
}
var format = {
comments: opts.comments == null || opts.comments,
compact: opts.compact,
indent: {
adjustMultilineComment: true,
style: style,
base: 0
}
};
if (format.compact === "auto") {
format.compact = code.length > 100000; // 100KB
if (format.compact) {
console.error(messages.get("codeGeneratorDeopt", opts.filename, "100KB"));
}
}
return format;
};
CodeGenerator.generators = {
templateLiterals: require("./generators/template-literals"),
comprehensions: require("./generators/comprehensions"),
expressions: require("./generators/expressions"),
statements: require("./generators/statements"),
playground: require("./generators/playground"),
classes: require("./generators/classes"),
methods: require("./generators/methods"),
modules: require("./generators/modules"),
types: require("./generators/types"),
flow: require("./generators/flow"),
base: require("./generators/base"),
jsx: require("./generators/jsx")
};
each(CodeGenerator.generators, function (generator) {
extend(CodeGenerator.prototype, generator);
});
CodeGenerator.prototype.generate = function () {
var ast = this.ast;
this.print(ast);
var comments = [];
each(ast.comments, function (comment) {
if (!comment._displayed) comments.push(comment);
});
this._printComments(comments);
return {
map: this.map.get(),
code: this.buffer.get()
};
module.exports = function (ast, opts, code) {
var gen = new CodeGenerator(ast, opts, code);
return gen.generate();
};
CodeGenerator.prototype.buildPrint = function (parent) {
var print = (node, opts) => {
return this.print(node, parent, opts);
};
print.sequence = (nodes, opts) => {
opts ||= {};
opts.statement = true;
return this.printJoin(print, nodes, opts);
};
print.join = (nodes, opts) => {
return this.printJoin(print, nodes, opts);
};
print.list = function (items, opts) {
opts ||= {};
opts.separator ||= ", ";
print.join(items, opts);
};
print.block = (node) => {
return this.printBlock(print, node);
};
print.indentOnComments = (node) => {
return this.printAndIndentOnComments(print, node);
};
return print;
};
CodeGenerator.prototype.print = function (node, parent, opts) {
if (!node) return "";
if (parent && parent._compact) {
node._compact = true;
}
var oldConcise = this.format.concise;
if (node._compact) {
this.format.concise = true;
}
opts ||= {};
var newline = (leading) => {
if (!opts.statement && !n.isUserWhitespacable(node, parent)) {
return;
}
var lines = 0;
if (node.start != null && !node._ignoreUserWhitespace) {
// user node
if (leading) {
lines = this.whitespace.getNewlinesBefore(node);
} else {
lines = this.whitespace.getNewlinesAfter(node);
}
} else {
// generated node
if (!leading) lines++; // always include at least a single line after
if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0;
var needs = n.needsWhitespaceAfter;
if (leading) needs = n.needsWhitespaceBefore;
if (needs(node, parent)) lines++;
// generated nodes can't add starting file whitespace
if (!this.buffer.buf) lines = 0;
}
this.newline(lines);
};
if (this[node.type]) {
var needsNoLineTermParens = n.needsParensNoLineTerminator(node, parent);
var needsParens = needsNoLineTermParens || n.needsParens(node, parent);
if (needsParens) this.push("(");
if (needsNoLineTermParens) this.indent();
this.printLeadingComments(node, parent);
newline(true);
if (opts.before) opts.before();
this.map.mark(node, "start");
this[node.type](node, this.buildPrint(node), parent);
if (needsNoLineTermParens) {
this.newline();
this.dedent();
}
if (needsParens) this.push(")");
this.map.mark(node, "end");
if (opts.after) opts.after();
newline(false);
this.printTrailingComments(node, parent);
} else {
throw new ReferenceError("unknown node of type " + JSON.stringify(node.type) + " with constructor " + JSON.stringify(node && node.constructor.name));
}
this.format.concise = oldConcise;
};
CodeGenerator.prototype.printJoin = function (print, nodes, opts) {
if (!nodes || !nodes.length) return;
opts ||= {};
var len = nodes.length;
if (opts.indent) this.indent();
each(nodes, (node, i) => {
print(node, {
statement: opts.statement,
addNewlines: opts.addNewlines,
after: () => {
if (opts.iterator) {
opts.iterator(node, i);
}
if (opts.separator && i < len - 1) {
this.push(opts.separator);
}
}
});
});
if (opts.indent) this.dedent();
};
CodeGenerator.prototype.printAndIndentOnComments = function (print, node) {
var indent = !!node.leadingComments;
if (indent) this.indent();
print(node);
if (indent) this.dedent();
};
CodeGenerator.prototype.printBlock = function (print, node) {
if (t.isEmptyStatement(node)) {
this.semicolon();
} else {
this.push(" ");
print(node);
}
};
CodeGenerator.prototype.generateComment = function (comment) {
var val = comment.value;
if (comment.type === "Line") {
val = "//" + val;
} else {
val = "/*" + val + "*/";
}
return val;
};
CodeGenerator.prototype.printTrailingComments = function (node, parent) {
this._printComments(this.getComments("trailingComments", node, parent));
};
CodeGenerator.prototype.printLeadingComments = function (node, parent) {
this._printComments(this.getComments("leadingComments", node, parent));
};
CodeGenerator.prototype.getComments = function (key, node, parent) {
if (t.isExpressionStatement(parent)) {
return [];
}
var comments = [];
var nodes = [node];
if (t.isExpressionStatement(node)) {
nodes.push(node.argument);
}
each(nodes, (node) => {
comments = comments.concat(this._getComments(key, node));
});
return comments;
};
CodeGenerator.prototype._getComments = function (key, node) {
return (node && node[key]) || [];
};
CodeGenerator.prototype._printComments = function (comments) {
if (this.format.compact) return;
if (!this.format.comments) return;
if (!comments || !comments.length) return;
each(comments, (comment) => {
var skip = false;
// find the original comment in the ast and set it as displayed
each(this.ast.comments, function (origComment) {
if (origComment.start === comment.start) {
// comment has already been output
if (origComment._displayed) skip = true;
origComment._displayed = true;
return false;
}
});
if (skip) return;
// whitespace before
this.newline(this.whitespace.getNewlinesBefore(comment));
var column = this.position.column;
var val = this.generateComment(comment);
if (column && !this.isLast(["\n", " ", "[", "{"])) {
this._push(" ");
column++;
}
//
if (comment.type === "Block" && this.format.indent.adjustMultilineComment) {
var offset = comment.loc.start.column;
if (offset) {
var newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g");
val = val.replace(newlineRegex, "\n");
}
var indent = Math.max(this.indentSize(), column);
val = val.replace(/\n/g, "\n" + repeating(" ", indent));
}
if (column === 0) {
val = this.getIndent() + val;
}
//
this._push(val);
// whitespace after
this.newline(this.whitespace.getNewlinesAfter(comment));
});
};
module.exports.CodeGenerator = CodeGenerator;

View File

@@ -1,10 +1,8 @@
module.exports = Node;
var whitespace = require("./whitespace");
var parens = require("./parentheses");
var each = require("lodash/collection/each");
var some = require("lodash/collection/some");
var t = require("../../types");
import whitespace from "./whitespace";
import * as parens from "./parentheses";
import each from "lodash/collection/each";
import some from "lodash/collection/some";
import * as t from "../../types";
var find = function (obj, node, parent) {
if (!obj) return;
@@ -24,79 +22,72 @@ var find = function (obj, node, parent) {
return result;
};
function Node(node, parent) {
this.parent = parent;
this.node = node;
}
Node.isUserWhitespacable = function (node) {
return t.isUserWhitespacable(node);
};
Node.needsWhitespace = function (node, parent, type) {
if (!node) return 0;
if (t.isExpressionStatement(node)) {
node = node.expression;
export default class Node {
constructor(node, parent) {
this.parent = parent;
this.node = node;
}
var linesInfo = find(whitespace.nodes, node, parent);
static isUserWhitespacable(node) {
return t.isUserWhitespacable(node);
}
if (!linesInfo) {
var items = find(whitespace.list, node, parent);
if (items) {
for (var i = 0; i < items.length; i++) {
linesInfo = Node.needsWhitespace(items[i], node, type);
if (linesInfo) break;
static needsWhitespace(node, parent, type) {
if (!node) return 0;
if (t.isExpressionStatement(node)) {
node = node.expression;
}
var linesInfo = find(whitespace.nodes, node, parent);
if (!linesInfo) {
var items = find(whitespace.list, node, parent);
if (items) {
for (var i = 0; i < items.length; i++) {
linesInfo = Node.needsWhitespace(items[i], node, type);
if (linesInfo) break;
}
}
}
return (linesInfo && linesInfo[type]) || 0;
}
return (linesInfo && linesInfo[type]) || 0;
};
Node.needsWhitespaceBefore = function (node, parent) {
return Node.needsWhitespace(node, parent, "before");
};
Node.needsWhitespaceAfter = function (node, parent) {
return Node.needsWhitespace(node, parent, "after");
};
Node.needsParens = function (node, parent) {
if (!parent) return false;
if (t.isNewExpression(parent) && parent.callee === node) {
if (t.isCallExpression(node)) return true;
var hasCall = some(node, function (val) {
return t.isCallExpression(val);
});
if (hasCall) return true;
static needsWhitespaceBefore(node, parent) {
return Node.needsWhitespace(node, parent, "before");
}
return find(parens, node, parent);
};
Node.needsParensNoLineTerminator = function (node, parent) {
if (!parent) return false;
// no comments
if (!node.leadingComments || !node.leadingComments.length) {
return false;
static needsWhitespaceAfter(node, parent) {
return Node.needsWhitespace(node, parent, "after");
}
if (t.isYieldExpression(parent) || t.isAwaitExpression(parent)) {
return true;
static needsParens(node, parent) {
if (!parent) return false;
if (t.isNewExpression(parent) && parent.callee === node) {
if (t.isCallExpression(node)) return true;
var hasCall = some(node, function (val) {
return t.isCallExpression(val);
});
if (hasCall) return true;
}
return find(parens, node, parent);
}
if (t.isContinueStatement(parent) || t.isBreakStatement(parent) ||
t.isReturnStatement(parent) || t.isThrowStatement(parent)) {
return true;
}
static needsParensNoLineTerminator(node, parent) {
if (!parent) return false;
return false;
};
// no comments
if (!node.leadingComments || !node.leadingComments.length) {
return false;
}
return t.isTerminatorless(parent);
}
}
each(Node, function (fn, key) {
Node.prototype[key] = function () {

View File

@@ -1,7 +1,7 @@
var t = require("../../types");
var each = require("lodash/collection/each");
import each from "lodash/collection/each";
import * as t from "../../types";
var PRECEDENCE = {};
const PRECEDENCE = {};
each([
["||"],
@@ -21,14 +21,20 @@ each([
});
});
exports.UpdateExpression = function (node, parent) {
export function NullableTypeAnnotation(node, parent) {
return t.isArrayTypeAnnotation(parent);
}
export { NullableTypeAnnotation as FunctionTypeAnnotation };
export function UpdateExpression(node, parent) {
if (t.isMemberExpression(parent) && parent.object === node) {
// (foo++).test()
return true;
}
};
}
exports.ObjectExpression = function (node, parent) {
export function ObjectExpression(node, parent) {
if (t.isExpressionStatement(parent)) {
// ({ foo: "bar" });
return true;
@@ -40,9 +46,9 @@ exports.ObjectExpression = function (node, parent) {
}
return false;
};
}
exports.Binary = function (node, parent) {
export function Binary(node, parent) {
if ((t.isCallExpression(parent) || t.isNewExpression(parent)) && parent.callee === node) {
return true;
}
@@ -70,9 +76,9 @@ exports.Binary = function (node, parent) {
return true;
}
}
};
}
exports.BinaryExpression = function (node, parent) {
export function BinaryExpression(node, parent) {
if (node.operator === "in") {
// var i = (1 in []);
if (t.isVariableDeclarator(parent)) {
@@ -84,9 +90,9 @@ exports.BinaryExpression = function (node, parent) {
return true;
}
}
};
}
exports.SequenceExpression = function (node, parent) {
export function SequenceExpression(node, parent) {
if (t.isForStatement(parent)) {
// Although parentheses wouldn't hurt around sequence
// expressions in the head of for loops, traditional style
@@ -102,9 +108,9 @@ exports.SequenceExpression = function (node, parent) {
// Otherwise err on the side of overparenthesization, adding
// explicit exceptions above if this proves overzealous.
return true;
};
}
exports.YieldExpression = function (node, parent) {
export function YieldExpression(node, parent) {
return t.isBinary(parent) ||
t.isUnaryLike(parent) ||
t.isCallExpression(parent) ||
@@ -112,17 +118,17 @@ exports.YieldExpression = function (node, parent) {
t.isNewExpression(parent) ||
t.isConditionalExpression(parent) ||
t.isYieldExpression(parent);
};
}
exports.ClassExpression = function (node, parent) {
export function ClassExpression(node, parent) {
return t.isExpressionStatement(parent);
};
}
exports.UnaryLike = function (node, parent) {
export function UnaryLike(node, parent) {
return t.isMemberExpression(parent) && parent.object === node;
};
}
exports.FunctionExpression = function (node, parent) {
export function FunctionExpression(node, parent) {
// function () {};
if (t.isExpressionStatement(parent)) {
return true;
@@ -137,10 +143,9 @@ exports.FunctionExpression = function (node, parent) {
if (t.isCallExpression(parent) && parent.callee === node) {
return true;
}
};
}
exports.AssignmentExpression =
exports.ConditionalExpression = function (node, parent) {
export function ConditionalExpression(node, parent) {
if (t.isUnaryLike(parent)) {
return true;
}
@@ -164,4 +169,12 @@ exports.ConditionalExpression = function (node, parent) {
}
return false;
};
}
export function AssignmentExpression(node) {
if (t.isObjectPattern(node.left)) {
return true;
} else {
return ConditionalExpression(...arguments);
}
}

View File

@@ -1,11 +1,9 @@
var isBoolean = require("lodash/lang/isBoolean");
var each = require("lodash/collection/each");
var map = require("lodash/collection/map");
var t = require("../../types");
var crawl = function (node, state) {
state ||= {};
import isBoolean from "lodash/lang/isBoolean";
import each from "lodash/collection/each";
import map from "lodash/collection/map";
import * as t from "../../types";
function crawl(node, state = {}) {
if (t.isMemberExpression(node)) {
crawl(node.object, state);
if (node.computed) crawl(node.property, state);
@@ -18,13 +16,13 @@ var crawl = function (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;
};
}
var isHelper = function (node) {
function isHelper(node) {
if (t.isMemberExpression(node)) {
return isHelper(node.object) || isHelper(node.property);
} else if (t.isIdentifier(node)) {
@@ -36,12 +34,12 @@ var isHelper = function (node) {
} else {
return false;
}
};
}
var isType = function (node) {
function isType(node) {
return t.isLiteral(node) || t.isObjectExpression(node) || t.isArrayExpression(node) ||
t.isIdentifier(node) || t.isMemberExpression(node);
};
}
exports.nodes = {
AssignmentExpression(node) {

View File

@@ -1,27 +1,27 @@
module.exports = Position;
export default class Position {
constructor() {
this.line = 1;
this.column = 0;
}
function Position() {
this.line = 1;
this.column = 0;
push(str) {
for (var i = 0; i < str.length; i++) {
if (str[i] === "\n") {
this.line++;
this.column = 0;
} else {
this.column++;
}
}
}
unshift(str) {
for (var i = 0; i < str.length; i++) {
if (str[i] === "\n") {
this.line--;
} else {
this.column--;
}
}
}
}
Position.prototype.push = function (str) {
for (var i = 0; i < str.length; i++) {
if (str[i] === "\n") {
this.line++;
this.column = 0;
} else {
this.column++;
}
}
};
Position.prototype.unshift = function (str) {
for (var i = 0; i < str.length; i++) {
if (str[i] === "\n") {
this.line--;
} else {
this.column--;
}
}
};

View File

@@ -1,54 +1,54 @@
module.exports = SourceMap;
import sourceMap from "source-map";
import * as t from "../types";
var sourceMap = require("source-map");
var t = require("../types");
export default class SourceMap {
constructor(position, opts, code) {
this.position = position;
this.opts = opts;
function SourceMap(position, opts, code) {
this.position = position;
this.opts = opts;
if (opts.sourceMaps) {
this.map = new sourceMap.SourceMapGenerator({
file: opts.sourceMapName,
sourceRoot: opts.sourceRoot
});
if (opts.sourceMap) {
this.map = new sourceMap.SourceMapGenerator({
file: opts.sourceMapName,
sourceRoot: opts.sourceRoot
this.map.setSourceContent(opts.sourceFileName, code);
} else {
this.map = null;
}
}
get() {
var map = this.map;
if (map) {
return map.toJSON();
} else {
return map;
}
}
mark(node, type) {
var loc = node.loc;
if (!loc) return; // no location info
var map = this.map;
if (!map) return; // no source map
if (t.isProgram(node) || t.isFile(node)) return; // illegal mapping nodes
var position = this.position;
var generated = {
line: position.line,
column: position.column
};
var original = loc[type];
map.addMapping({
source: this.opts.sourceFileName,
generated: generated,
original: original
});
this.map.setSourceContent(opts.sourceFileName, code);
} else {
this.map = null;
}
}
SourceMap.prototype.get = function () {
var map = this.map;
if (map) {
return map.toJSON();
} else {
return map;
}
};
SourceMap.prototype.mark = function (node, type) {
var loc = node.loc;
if (!loc) return; // no location info
var map = this.map;
if (!map) return; // no source map
if (t.isProgram(node) || t.isFile(node)) return; // illegal mapping nodes
var position = this.position;
var generated = {
line: position.line,
column: position.column
};
var original = loc[type];
map.addMapping({
source: this.opts.sourceFileName,
generated: generated,
original: original
});
};

View File

@@ -1,6 +1,4 @@
module.exports = Whitespace;
var sortBy = require("lodash/collection/sortBy");
import sortBy from "lodash/collection/sortBy";
/**
* Returns `i`th number from `base`, continuing from 0 when `max` is reached.
@@ -22,92 +20,94 @@ function getLookupIndex(i, base, max) {
return i;
}
function Whitespace(tokens, comments) {
this.tokens = sortBy(tokens.concat(comments), "start");
this.used = {};
export default class Whitespace {
constructor(tokens, comments) {
this.tokens = sortBy(tokens.concat(comments), "start");
this.used = {};
// Profiling this code shows that while generator passes over it, indexes
// returned by `getNewlinesBefore` and `getNewlinesAfter` are always increasing.
// Profiling this code shows that while generator passes over it, indexes
// returned by `getNewlinesBefore` and `getNewlinesAfter` are always increasing.
// We use this implementation detail for an optimization: instead of always
// starting to look from `this.tokens[0]`, we will start `for` loops from the
// previous successful match. We will enumerate all tokens—but the common
// case will be much faster.
// We use this implementation detail for an optimization: instead of always
// starting to look from `this.tokens[0]`, we will start `for` loops from the
// previous successful match. We will enumerate all tokens—but the common
// case will be much faster.
this._lastFoundIndex = 0;
}
Whitespace.prototype.getNewlinesBefore = function (node) {
var startToken;
var endToken;
var tokens = this.tokens;
var token;
for (var j = 0; j < tokens.length; j++) {
// optimize for forward traversal by shifting for loop index
var i = getLookupIndex(j, this._lastFoundIndex, this.tokens.length);
token = tokens[i];
// this is the token this node starts with
if (node.start === token.start) {
startToken = tokens[i - 1];
endToken = token;
this._lastFoundIndex = i;
break;
}
this._lastFoundIndex = 0;
}
return this.getNewlinesBetween(startToken, endToken);
};
getNewlinesBefore(node) {
var startToken;
var endToken;
var tokens = this.tokens;
var token;
Whitespace.prototype.getNewlinesAfter = function (node) {
var startToken;
var endToken;
var tokens = this.tokens;
var token;
for (var j = 0; j < tokens.length; j++) {
// optimize for forward traversal by shifting for loop index
var i = getLookupIndex(j, this._lastFoundIndex, this.tokens.length);
token = tokens[i];
for (var j = 0; j < tokens.length; j++) {
// optimize for forward traversal by shifting for loop index
var i = getLookupIndex(j, this._lastFoundIndex, this.tokens.length);
token = tokens[i];
// this is the token this node starts with
if (node.start === token.start) {
startToken = tokens[i - 1];
endToken = token;
// this is the token this node ends with
if (node.end === token.end) {
startToken = token;
endToken = tokens[i + 1];
this._lastFoundIndex = i;
break;
this._lastFoundIndex = i;
break;
}
}
return this.getNewlinesBetween(startToken, endToken);
}
if (endToken && endToken.type.type === "eof") {
return 1;
} else {
var lines = this.getNewlinesBetween(startToken, endToken);
if (node.type === "Line" && !lines) {
// line comment
getNewlinesAfter(node) {
var startToken;
var endToken;
var tokens = this.tokens;
var token;
for (var j = 0; j < tokens.length; j++) {
// optimize for forward traversal by shifting for loop index
var i = getLookupIndex(j, this._lastFoundIndex, this.tokens.length);
token = tokens[i];
// this is the token this node ends with
if (node.end === token.end) {
startToken = token;
endToken = tokens[i + 1];
this._lastFoundIndex = i;
break;
}
}
if (endToken && endToken.type.label === "eof") {
return 1;
} else {
return lines;
}
}
};
Whitespace.prototype.getNewlinesBetween = function (startToken, endToken) {
if (!endToken || !endToken.loc) return 0;
var start = startToken ? startToken.loc.end.line : 1;
var end = endToken.loc.start.line;
var lines = 0;
for (var line = start; line < end; line++) {
if (typeof this.used[line] === "undefined") {
this.used[line] = true;
lines++;
var lines = this.getNewlinesBetween(startToken, endToken);
if (node.type === "Line" && !lines) {
// line comment
return 1;
} else {
return lines;
}
}
}
return lines;
};
getNewlinesBetween(startToken, endToken) {
if (!endToken || !endToken.loc) return 0;
var start = startToken ? startToken.loc.end.line : 1;
var end = endToken.loc.start.line;
var lines = 0;
for (var line = start; line < end; line++) {
if (typeof this.used[line] === "undefined") {
this.used[line] = true;
lines++;
}
}
return lines;
}
}

View File

@@ -1,69 +1,67 @@
var lineNumbers = require("line-numbers");
var repeating = require("repeating");
var jsTokens = require("js-tokens");
var esutils = require("esutils");
var chalk = require("chalk");
var ary = require("lodash/function/ary");
import lineNumbers from "line-numbers";
import repeating from "repeating";
import jsTokens from "js-tokens";
import esutils from "esutils";
import chalk from "chalk";
var defs = {
string: chalk.red,
punctuation: chalk.white.bold,
operator: chalk.white.bold,
curly: chalk.green,
parens: chalk.blue.bold,
square: chalk.yellow,
name: chalk.white,
keyword: chalk.cyan,
number: chalk.magenta,
regex: chalk.magenta,
comment: chalk.grey,
invalid: chalk.inverse
string: chalk.red,
punctuator: chalk.bold,
curly: chalk.green,
parens: chalk.blue.bold,
square: chalk.yellow,
keyword: chalk.cyan,
number: chalk.magenta,
regex: chalk.magenta,
comment: chalk.grey,
invalid: chalk.inverse
};
var newline = /\r\n|[\n\r\u2028\u2029]/;
const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
var highlight = function (text) {
var tokenType = function (match) {
var token = jsTokens.matchToToken(match);
if (token.type === "name" && esutils.keyword.isKeywordES6(token.value)) {
return "keyword";
function getTokenType(match) {
var token = jsTokens.matchToToken(match);
if (token.type === "name" && esutils.keyword.isReservedWordES6(token.value)) {
return "keyword";
}
if (token.type === "punctuator") {
switch (token.value) {
case "{":
case "}":
return "curly";
case "(":
case ")":
return "parens";
case "[":
case "]":
return "square";
}
}
if (token.type === "punctuation") {
switch (token.value) {
case "{":
case "}":
return "curly";
case "(":
case ")":
return "parens";
case "[":
case "]":
return "square";
}
return token.type;
}
function highlight(text) {
return text.replace(jsTokens, function (...args) {
var type = getTokenType(args);
var colorize = defs[type];
if (colorize) {
return args[0].split(NEWLINE).map(str => colorize(str)).join("\n");
} else {
return args[0];
}
return token.type;
};
return text.replace(jsTokens, function (match) {
var type = tokenType(arguments);
if (type in defs) {
var colorize = ary(defs[type], 1);
return match.split(newline).map(colorize).join("\n");
}
return match;
});
};
}
module.exports = function (lines, lineNumber, colNumber) {
export default function (lines: number, lineNumber: number, colNumber: number, opts = {}): string {
colNumber = Math.max(colNumber, 0);
if (chalk.supportsColor) {
if (opts.highlightCode && chalk.supportsColor) {
lines = highlight(lines);
}
lines = lines.split(newline);
lines = lines.split(NEWLINE);
var start = Math.max(lineNumber - 3, 0);
var end = Math.min(lines.length, lineNumber + 3);
@@ -73,7 +71,7 @@ module.exports = function (lines, lineNumber, colNumber) {
end = lines.length;
}
return "\n" + lineNumbers(lines.slice(start, end), {
return lineNumbers(lines.slice(start, end), {
start: start + 1,
before: " ",
after: " | ",
@@ -82,8 +80,7 @@ module.exports = function (lines, lineNumber, colNumber) {
return;
}
if (colNumber) {
params.line += "\n" + params.before + repeating(" ", params.width) +
params.after + repeating(" ", colNumber - 1) + "^";
params.line += `\n${params.before}${repeating(" ", params.width)}${params.after}${repeating(" ", colNumber - 1)}^`;
}
params.before = params.before.replace(/^./, ">");
}

View File

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

View File

@@ -1,6 +1,6 @@
var t = require("../types");
import * as t from "../types";
module.exports = function (ast, comments, tokens) {
export default function (ast, comments, tokens) {
if (ast && ast.type === "Program") {
return t.file(ast, comments || [], tokens || []);
} else {

View File

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

View File

@@ -1,49 +1,34 @@
var normalizeAst = require("./normalize-ast");
var estraverse = require("estraverse");
var codeFrame = require("./code-frame");
var acorn = require("acorn-babel");
import normalizeAst from "./normalize-ast";
import estraverse from "estraverse";
import * as acorn from "../../acorn";
module.exports = function (opts, code, callback) {
try {
var comments = [];
var tokens = [];
export default function (code, opts = {}) {
var comments = [];
var tokens = [];
var ast = acorn.parse(code, {
allowImportExportEverywhere: opts.allowImportExportEverywhere,
allowReturnOutsideFunction: !opts._anal,
ecmaVersion: opts.experimental ? 7 : 6,
playground: opts.playground,
strictMode: opts.strictMode,
onComment: comments,
locations: true,
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
};
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 = opts.filename + ": " + err.message;
var loc = err.loc;
if (loc) {
var frame = codeFrame(code, loc.line, loc.column + 1);
message += frame;
}
if (err.stack) err.stack = err.stack.replace(err.message, message);
err.message = message;
}
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

@@ -1,15 +0,0 @@
/**
* A trick from Bluebird to force V8 to use fast properties for an object.
* Read more: http://stackoverflow.com/questions/24987896/
*
* Use %HasFastProperties(obj) and --allow-natives-syntax to check whether
* a particular object already has fast properties.
*/
module.exports = function toFastProperties(obj) {
/*jshint -W027*/
function f() {}
f.prototype = obj;
return f;
eval(obj);
};

View File

@@ -1,6 +1,6 @@
var util = require("util");
import * as util from "util";
exports.messages = {
export const MESSAGES = {
tailCallReassignmentDeopt: "Function reference has been reassigned so it's probably be dereferenced so we can't optimise this with confidence",
JSXNamespacedTags: "Namespace tags are not supported. ReactJSX is not XML.",
classesIllegalBareSuper: "Illegal use of bare super",
@@ -10,6 +10,7 @@ exports.messages = {
undeclaredVariable: "Reference to undeclared variable $1",
undeclaredVariableSuggestion: "Reference to undeclared variable $1 - did you mean $2?",
settersInvalidParamLength: "Setters must have exactly one parameter",
settersNoRest: "Setters aren't allowed to have a rest",
noAssignmentsInForHead: "No assignments allowed in for-in/of head",
expectedMemberExpressionOrIdentifier: "Expected type MemeberExpression or Identifier",
invalidParentForThisNode: "We don't know how to handle this node within the current parent - please open an issue",
@@ -17,26 +18,37 @@ exports.messages = {
modulesIllegalExportName: "Illegal export $1",
unknownForHead: "Unknown node type $1 in ForStatement",
didYouMean: "Did you mean $1?",
evalInStrictMode: "eval is not allowed in strict mode",
codeGeneratorDeopt: "Note: The code generator has deoptimised the styling of $1 as it exceeds the max of $2."
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",
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 }`?",
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..."
};
exports.get = function (key) {
var msg = exports.messages[key];
if (!msg) throw new ReferenceError("Unknown message `" + key + "`");
export function get(key: String, ...args) {
var msg = MESSAGES[key];
if (!msg) throw new ReferenceError(`Unknown message ${JSON.stringify(key)}`);
var args = [];
for (var i = 1; i < arguments.length; i++) {
args.push(arguments[i]);
}
args = exports.parseArgs(args);
args = parseArgs(args);
return msg.replace(/\$(\d+)/g, function (str, i) {
return args[--i];
});
};
}
exports.parseArgs = function (args) {
export function parseArgs(args: Array<any>) {
return args.map(function (val) {
if (val != null && val.inspect) {
return val.inspect();
@@ -48,4 +60,4 @@ exports.parseArgs = function (args) {
}
}
});
};
}

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